1 /* This file is part of Metaproxy.
2 Copyright (C) 2005-2013 Index Data
4 Metaproxy is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
9 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 #include <metaproxy/filter.hpp>
21 #include <metaproxy/package.hpp>
22 #include <metaproxy/util.hpp>
23 #include "filter_http_rewrite.hpp"
24 #include "html_parser.hpp"
30 #include <boost/regex.hpp>
31 #include <boost/lexical_cast.hpp>
32 #include <boost/algorithm/string.hpp>
36 namespace mp = metaproxy_1;
37 namespace yf = mp::filter;
39 namespace metaproxy_1 {
41 class HttpRewrite::Replace {
46 std::map<int, std::string> group_index;
48 const std::map<std::string, std::string> & vars) const;
49 void parse_groups(std::string pattern);
52 class HttpRewrite::Rule {
54 std::list<Replace> replace_list;
55 const std::string test_patterns(
56 std::map<std::string, std::string> & vars,
57 const std::string & txt);
59 class HttpRewrite::Within {
68 class HttpRewrite::Phase {
71 std::list<Within> within_list;
73 void rewrite_reqline(mp::odr & o, Z_HTTP_Request *hreq,
74 std::map<std::string, std::string> & vars) const;
75 void rewrite_headers(mp::odr & o, Z_HTTP_Header *headers,
76 std::map<std::string, std::string> & vars) const;
77 void rewrite_body(mp::odr & o,
78 char **content_buf, int *content_len,
79 std::map<std::string, std::string> & vars) const;
81 class HttpRewrite::Event : public HTMLParserEvent {
82 void openTagStart(const char *tag, int tag_len);
83 void anyTagEnd(const char *tag, int tag_len, int close_it);
84 void attribute(const char *tag, int tag_len,
85 const char *attr, int attr_len,
86 const char *value, int val_len,
88 void closeTag(const char *tag, int tag_len);
89 void text(const char *value, int len);
92 std::stack<std::list<Within>::const_iterator> s_within;
93 std::map<std::string, std::string> &m_vars;
95 Event(const Phase *p, std::map<std::string, std::string> &vars);
102 yf::HttpRewrite::HttpRewrite() :
103 req_phase(new Phase), res_phase(new Phase)
107 yf::HttpRewrite::~HttpRewrite()
111 void yf::HttpRewrite::process(mp::Package & package) const
113 yaz_log(YLOG_LOG, "HttpRewrite begins....");
114 Z_GDU *gdu = package.request().get();
115 //map of request/response vars
116 std::map<std::string, std::string> vars;
117 //we have an http req
118 if (gdu && gdu->which == Z_GDU_HTTP_Request)
120 Z_HTTP_Request *hreq = gdu->u.HTTP_Request;
122 req_phase->rewrite_reqline(o, hreq, vars);
123 yaz_log(YLOG_LOG, ">> Request headers");
124 req_phase->rewrite_headers(o, hreq->headers, vars);
125 req_phase->rewrite_body(o,
126 &hreq->content_buf, &hreq->content_len, vars);
127 package.request() = gdu;
130 gdu = package.response().get();
131 if (gdu && gdu->which == Z_GDU_HTTP_Response)
133 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
134 yaz_log(YLOG_LOG, "Response code %d", hres->code);
136 yaz_log(YLOG_LOG, "<< Respose headers");
137 res_phase->rewrite_headers(o, hres->headers, vars);
138 res_phase->rewrite_body(o, &hres->content_buf,
139 &hres->content_len, vars);
140 package.response() = gdu;
144 void yf::HttpRewrite::Phase::rewrite_reqline (mp::odr & o,
145 Z_HTTP_Request *hreq,
146 std::map<std::string, std::string> & vars) const
148 //rewrite the request line
150 if (strstr(hreq->path, "http://") == hreq->path)
152 yaz_log(YLOG_LOG, "Path in the method line is absolute, "
153 "possibly a proxy request");
158 //TODO what about proto
160 path += z_HTTP_header_lookup(hreq->headers, "Host");
165 std::list<Within>::const_iterator it = within_list.begin();
166 for (; it != within_list.end(); it++)
169 RulePtr rule = it->rule;
170 yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
171 std::string npath = rule->test_patterns(vars, path);
174 yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
175 hreq->path = odr_strdup(o, npath.c_str());
180 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
181 Z_HTTP_Header *headers,
182 std::map<std::string, std::string> & vars) const
184 for (Z_HTTP_Header *header = headers; header; header = header->next)
186 std::list<Within>::const_iterator it = within_list.begin();
187 for (; it != within_list.end(); it++)
189 if (it->header.length() > 0 &&
190 yaz_strcasecmp(it->header.c_str(), header->name) == 0)
192 std::string sheader(header->name);
194 sheader += header->value;
196 RulePtr rule = it->rule;
197 std::string out = rule->test_patterns(vars, sheader);
200 size_t pos = out.find(": ");
201 if (pos == std::string::npos)
203 yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
206 header->name = odr_strdup(o, out.substr(0, pos).c_str());
207 header->value = odr_strdup(o,
209 std::string::npos).c_str());
216 void yf::HttpRewrite::Phase::rewrite_body(mp::odr & o,
219 std::map<std::string, std::string> & vars) const
224 for (i = 0; i < *content_len; i++)
225 if ((*content_buf)[i] == 0)
226 return; // binary content. skip
229 Event ev(this, vars);
231 parser.set_verbose(m_verbose);
233 std::string buf(*content_buf, *content_len);
235 parser.parse(ev, buf.c_str());
236 const char *res = ev.result();
237 *content_buf = odr_strdup(o, res);
238 *content_len = strlen(res);
242 yf::HttpRewrite::Event::Event(const Phase *p,
243 std::map<std::string, std::string> & vars
244 ) : m_phase(p), m_vars(vars)
249 yf::HttpRewrite::Event::~Event()
254 const char *yf::HttpRewrite::Event::result()
256 return wrbuf_cstr(m_w);
259 void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
261 wrbuf_putc(m_w, '<');
262 wrbuf_write(m_w, tag, tag_len);
264 std::string t(tag, tag_len);
265 std::list<Within>::const_iterator it = m_phase->within_list.begin();
266 for (; it != m_phase->within_list.end(); it++)
268 if (it->tag.length() > 0 && yaz_strcasecmp(it->tag.c_str(),
271 std::vector<std::string> attr;
272 boost::split(attr, it->attr, boost::is_any_of(","));
274 for (i = 0; i < attr.size(); i++)
276 if (attr[i].compare("#text") == 0)
286 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
291 if (!s_within.empty())
293 std::list<Within>::const_iterator it = s_within.top();
294 std::string t(tag, tag_len);
295 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
300 wrbuf_putc(m_w, '/');
301 wrbuf_putc(m_w, '>');
304 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
305 const char *attr, int attr_len,
306 const char *value, int val_len,
309 std::list<Within>::const_iterator it = m_phase->within_list.begin();
312 for (; it != m_phase->within_list.end(); it++)
314 std::string t(tag, tag_len);
315 if (it->tag.length() == 0 ||
316 yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
318 std::string a(attr, attr_len);
319 std::vector<std::string> attr;
320 boost::split(attr, it->attr, boost::is_any_of(","));
322 for (i = 0; i < attr.size(); i++)
324 if (attr[i].compare("#text") &&
325 yaz_strcasecmp(attr[i].c_str(), a.c_str()) == 0)
333 wrbuf_putc(m_w, ' ');
334 wrbuf_write(m_w, attr, attr_len);
337 wrbuf_puts(m_w, "=");
338 wrbuf_puts(m_w, sep);
343 std::string input(value, val_len);
344 output = it->rule->test_patterns(m_vars, input);
347 wrbuf_write(m_w, value, val_len);
349 wrbuf_puts(m_w, output.c_str());
350 wrbuf_puts(m_w, sep);
354 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
356 if (!s_within.empty())
358 std::list<Within>::const_iterator it = s_within.top();
359 std::string t(tag, tag_len);
360 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
363 wrbuf_puts(m_w, "</");
364 wrbuf_write(m_w, tag, tag_len);
367 void yf::HttpRewrite::Event::text(const char *value, int len)
369 std::list<Within>::const_iterator it = m_phase->within_list.end();
370 if (!s_within.empty())
373 if (it != m_phase->within_list.end())
375 std::string input(value, len);
376 output = it->rule->test_patterns(m_vars, input);
379 wrbuf_write(m_w, value, len);
381 wrbuf_puts(m_w, output.c_str());
384 const std::string yf::HttpRewrite::Rule::test_patterns(
385 std::map<std::string, std::string> & vars,
386 const std::string & txt)
389 std::string::const_iterator start, end;
394 std::list<Replace>::iterator bit = replace_list.end();
396 std::string::const_iterator best_pos = txt.end();
397 std::list<Replace>::iterator it = replace_list.begin();
398 for (; it != replace_list.end(); it++)
400 if (regex_search(start, end, it->what, it->re))
402 if (it->what[0].first < best_pos)
404 best_pos = it->what[0].first;
409 if (bit == replace_list.end())
414 for (i = 1; i < bit->what.size(); ++i)
416 //check if the group is named
417 std::map<int, std::string>::const_iterator git
418 = bit->group_index.find(i);
419 if (git != bit->group_index.end())
421 vars[git->second] = bit->what[i];
425 //prepare replacement string
426 std::string rvalue = bit->sub_vars(vars);
427 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
428 bit->what.str(0).c_str(), rvalue.c_str());
429 out.append(start, bit->what[0].first);
431 start = bit->what[0].second; //move search forward
433 if (start != txt.begin())
434 out.append(start, end);
438 void yf::HttpRewrite::Replace::parse_groups(std::string pattern)
442 const std::string &str = pattern;
444 yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
445 for (size_t i = 0; i < str.size(); ++i)
448 if (!esc && str[i] == '\\')
453 if (!esc && str[i] == '(') //group starts
456 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
459 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
461 if (gnum > 0) gnum--;
467 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
469 if (i+1 < str.size() && str[i+1] == '<') //named
474 while (++i < str.size())
476 if (str[i] == '>') { term = true; break; }
477 if (!isalnum(str[i]))
478 throw mp::filter::FilterException
479 ("Only alphanumeric chars allowed, found "
483 + boost::lexical_cast<std::string>(i));
487 throw mp::filter::FilterException
488 ("Unterminated group name '" + gname
489 + " in '" + str +"'");
490 group_index[gnum] = gname;
491 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
492 gname.c_str(), gnum);
501 std::string yf::HttpRewrite::Replace::sub_vars(
502 const std::map<std::string, std::string> & vars) const
506 const std::string & in = recipe;
507 for (size_t i = 0; i < in.size(); ++i)
509 if (!esc && in[i] == '\\')
514 if (!esc && in[i] == '$') //var
516 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
521 while (++i < in.size())
523 if (in[i] == '}') { term = true; break; }
526 if (!term) throw mp::filter::FilterException
527 ("Unterminated var ref in '"+in+"' at "
528 + boost::lexical_cast<std::string>(i));
529 std::map<std::string, std::string>::const_iterator it
531 if (it != vars.end())
538 throw mp::filter::FilterException
539 ("Malformed or trimmed var ref in '"
540 +in+"' at "+boost::lexical_cast<std::string>(i));
551 yf::HttpRewrite::Phase::Phase() : m_verbose(0)
555 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
557 static const char *names[2] = { "verbose", 0 };
558 std::string values[1];
560 mp::xml::parse_attr(ptr, names, values);
562 phase.m_verbose = atoi(values[0].c_str());
564 std::map<std::string, RulePtr > rules;
565 for (ptr = ptr->children; ptr; ptr = ptr->next)
567 if (ptr->type != XML_ELEMENT_NODE)
569 else if (!strcmp((const char *) ptr->name, "rule"))
571 static const char *names[2] = { "name", 0 };
572 std::string values[1];
573 values[0] = "default";
574 mp::xml::parse_attr(ptr, names, values);
576 RulePtr rule(new Rule);
577 for (xmlNode *p = ptr->children; p; p = p->next)
579 if (p->type != XML_ELEMENT_NODE)
581 if (!strcmp((const char *) p->name, "rewrite"))
585 const struct _xmlAttr *attr;
586 for (attr = p->properties; attr; attr = attr->next)
588 if (!strcmp((const char *) attr->name, "from"))
589 from = mp::xml::get_text(attr->children);
590 else if (!strcmp((const char *) attr->name, "to"))
591 replace.recipe = mp::xml::get_text(attr->children);
593 throw mp::filter::FilterException
595 + std::string((const char *) attr->name)
596 + " in rewrite section of http_rewrite");
598 yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
599 from.c_str(), replace.recipe.c_str());
602 replace.parse_groups(from);
603 rule->replace_list.push_back(replace);
607 throw mp::filter::FilterException
609 + std::string((const char *) p->name)
610 + " in http_rewrite filter");
612 rules[values[0]] = rule;
614 else if (!strcmp((const char *) ptr->name, "within"))
616 static const char *names[6] =
617 { "header", "attr", "tag", "rule", "reqline", 0 };
618 std::string values[5];
619 mp::xml::parse_attr(ptr, names, values);
621 w.header = values[0];
624 std::map<std::string,RulePtr>::const_iterator it =
625 rules.find(values[3]);
626 if (it == rules.end())
627 throw mp::filter::FilterException
628 ("Reference to non-existing rule '" + values[3] +
629 "' in http_rewrite filter");
631 w.reqline = values[4] == "1";
632 phase.within_list.push_back(w);
636 throw mp::filter::FilterException
638 + std::string((const char *) ptr->name)
639 + " in http_rewrite filter");
644 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
647 for (ptr = ptr->children; ptr; ptr = ptr->next)
649 if (ptr->type != XML_ELEMENT_NODE)
651 else if (!strcmp((const char *) ptr->name, "request"))
653 configure_phase(ptr, *req_phase);
655 else if (!strcmp((const char *) ptr->name, "response"))
657 configure_phase(ptr, *res_phase);
661 throw mp::filter::FilterException
663 + std::string((const char *) ptr->name)
664 + " in http_rewrite1 filter");
669 static mp::filter::Base* filter_creator()
671 return new mp::filter::HttpRewrite;
675 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
686 * c-file-style: "Stroustrup"
687 * indent-tabs-mode: nil
689 * vim: shiftwidth=4 tabstop=8 expandtab