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 {
45 std::map<int, std::string> group_index;
46 const std::string search_replace(
47 std::map<std::string, std::string> & vars,
48 const std::string & txt) const;
50 const std::map<std::string, std::string> & vars) const;
54 class HttpRewrite::Rule {
56 std::list<Replace> replace_list;
57 const std::string test_patterns(
58 std::map<std::string, std::string> & vars,
59 const std::string & txt) const;
61 class HttpRewrite::Within {
70 class HttpRewrite::Phase {
73 std::list<Within> within_list;
75 void rewrite_reqline(mp::odr & o, Z_HTTP_Request *hreq,
76 std::map<std::string, std::string> & vars) const;
77 void rewrite_headers(mp::odr & o, Z_HTTP_Header *headers,
78 std::map<std::string, std::string> & vars) const;
79 void rewrite_body(mp::odr & o,
80 char **content_buf, int *content_len,
81 std::map<std::string, std::string> & vars) const;
83 class HttpRewrite::Event : public HTMLParserEvent {
84 void openTagStart(const char *tag, int tag_len);
85 void anyTagEnd(const char *tag, int tag_len, int close_it);
86 void attribute(const char *tag, int tag_len,
87 const char *attr, int attr_len,
88 const char *value, int val_len,
90 void closeTag(const char *tag, int tag_len);
91 void text(const char *value, int len);
94 std::stack<std::list<Within>::const_iterator> s_within;
95 std::map<std::string, std::string> &m_vars;
97 Event(const Phase *p, std::map<std::string, std::string> &vars);
104 yf::HttpRewrite::HttpRewrite() :
105 req_phase(new Phase), res_phase(new Phase)
109 yf::HttpRewrite::~HttpRewrite()
113 void yf::HttpRewrite::process(mp::Package & package) const
115 yaz_log(YLOG_LOG, "HttpRewrite begins....");
116 Z_GDU *gdu = package.request().get();
117 //map of request/response vars
118 std::map<std::string, std::string> vars;
119 //we have an http req
120 if (gdu && gdu->which == Z_GDU_HTTP_Request)
122 Z_HTTP_Request *hreq = gdu->u.HTTP_Request;
124 req_phase->rewrite_reqline(o, hreq, vars);
125 yaz_log(YLOG_LOG, ">> Request headers");
126 req_phase->rewrite_headers(o, hreq->headers, vars);
127 req_phase->rewrite_body(o,
128 &hreq->content_buf, &hreq->content_len, vars);
129 package.request() = gdu;
132 gdu = package.response().get();
133 if (gdu && gdu->which == Z_GDU_HTTP_Response)
135 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
136 yaz_log(YLOG_LOG, "Response code %d", hres->code);
138 yaz_log(YLOG_LOG, "<< Respose headers");
139 res_phase->rewrite_headers(o, hres->headers, vars);
140 res_phase->rewrite_body(o, &hres->content_buf,
141 &hres->content_len, vars);
142 package.response() = gdu;
146 void yf::HttpRewrite::Phase::rewrite_reqline (mp::odr & o,
147 Z_HTTP_Request *hreq,
148 std::map<std::string, std::string> & vars) const
150 //rewrite the request line
152 if (strstr(hreq->path, "http://") == hreq->path)
154 yaz_log(YLOG_LOG, "Path in the method line is absolute, "
155 "possibly a proxy request");
160 //TODO what about proto
162 path += z_HTTP_header_lookup(hreq->headers, "Host");
167 std::list<Within>::const_iterator it = within_list.begin();
168 for (; it != within_list.end(); it++)
171 RulePtr rule = it->rule;
172 yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
173 std::string npath = rule->test_patterns(vars, path);
176 yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
177 hreq->path = odr_strdup(o, npath.c_str());
182 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
183 Z_HTTP_Header *headers,
184 std::map<std::string, std::string> & vars) const
186 for (Z_HTTP_Header *header = headers; header; header = header->next)
188 std::list<Within>::const_iterator it = within_list.begin();
189 for (; it != within_list.end(); it++)
191 if (it->header.length() > 0 &&
192 yaz_strcasecmp(it->header.c_str(), header->name) == 0)
194 std::string sheader(header->name);
196 sheader += header->value;
198 RulePtr rule = it->rule;
199 std::string out = rule->test_patterns(vars, sheader);
202 size_t pos = out.find(": ");
203 if (pos == std::string::npos)
205 yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
208 header->name = odr_strdup(o, out.substr(0, pos).c_str());
209 header->value = odr_strdup(o,
211 std::string::npos).c_str());
218 void yf::HttpRewrite::Phase::rewrite_body(mp::odr & o,
221 std::map<std::string, std::string> & vars) const
226 for (i = 0; i < *content_len; i++)
227 if ((*content_buf)[i] == 0)
228 return; // binary content. skip
231 Event ev(this, vars);
233 parser.set_verbose(m_verbose);
235 std::string buf(*content_buf, *content_len);
237 parser.parse(ev, buf.c_str());
238 const char *res = ev.result();
239 *content_buf = odr_strdup(o, res);
240 *content_len = strlen(res);
244 yf::HttpRewrite::Event::Event(const Phase *p,
245 std::map<std::string, std::string> & vars
246 ) : m_phase(p), m_vars(vars)
251 yf::HttpRewrite::Event::~Event()
256 const char *yf::HttpRewrite::Event::result()
258 return wrbuf_cstr(m_w);
261 void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
263 wrbuf_putc(m_w, '<');
264 wrbuf_write(m_w, tag, tag_len);
266 std::string t(tag, tag_len);
267 std::list<Within>::const_iterator it = m_phase->within_list.begin();
268 for (; it != m_phase->within_list.end(); it++)
270 if (it->tag.length() > 0 && yaz_strcasecmp(it->tag.c_str(),
273 std::vector<std::string> attr;
274 boost::split(attr, it->attr, boost::is_any_of(","));
276 for (i = 0; i < attr.size(); i++)
278 if (attr[i].compare("#text") == 0)
288 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
293 if (!s_within.empty())
295 std::list<Within>::const_iterator it = s_within.top();
296 std::string t(tag, tag_len);
297 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
302 wrbuf_putc(m_w, '/');
303 wrbuf_putc(m_w, '>');
306 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
307 const char *attr, int attr_len,
308 const char *value, int val_len,
311 std::list<Within>::const_iterator it = m_phase->within_list.begin();
314 for (; it != m_phase->within_list.end(); it++)
316 std::string t(tag, tag_len);
317 if (it->tag.length() == 0 ||
318 yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
320 std::string a(attr, attr_len);
321 std::vector<std::string> attr;
322 boost::split(attr, it->attr, boost::is_any_of(","));
324 for (i = 0; i < attr.size(); i++)
326 if (attr[i].compare("#text") &&
327 yaz_strcasecmp(attr[i].c_str(), a.c_str()) == 0)
335 wrbuf_putc(m_w, ' ');
336 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);
353 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
355 if (!s_within.empty())
357 std::list<Within>::const_iterator it = s_within.top();
358 std::string t(tag, tag_len);
359 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
362 wrbuf_puts(m_w, "</");
363 wrbuf_write(m_w, tag, tag_len);
366 void yf::HttpRewrite::Event::text(const char *value, int len)
368 std::list<Within>::const_iterator it = m_phase->within_list.end();
369 if (!s_within.empty())
372 if (it != m_phase->within_list.end())
374 std::string input(value, len);
375 output = it->rule->test_patterns(m_vars, input);
378 wrbuf_write(m_w, value, len);
380 wrbuf_puts(m_w, output.c_str());
385 * Tests pattern from the vector in order and executes recipe on
388 const std::string yf::HttpRewrite::Rule::test_patterns(
389 std::map<std::string, std::string> & vars,
390 const std::string & txt) const
392 std::list<Replace>::const_iterator it = replace_list.begin();
394 for (; it != replace_list.end(); it++)
396 std::string out = it->search_replace(vars, txt);
397 if (!out.empty()) return out;
402 const std::string yf::HttpRewrite::Replace::search_replace(
403 std::map<std::string, std::string> & vars,
404 const std::string & txt) const
406 //exec regex against value
407 boost::regex re(regex);
409 std::string::const_iterator start, end;
413 while (regex_search(start, end, what, re)) //find next full match
416 for (i = 1; i < what.size(); ++i)
418 //check if the group is named
419 std::map<int, std::string>::const_iterator it
420 = group_index.find(i);
421 if (it != group_index.end())
423 vars[it->second] = what[i];
427 //prepare replacement string
428 std::string rvalue = sub_vars(vars);
429 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
430 what.str(0).c_str(), rvalue.c_str());
431 out.append(start, what[0].first);
433 start = what[0].second; //move search forward
435 //if we had a match cat the last part
436 if (start != txt.begin())
437 out.append(start, end);
441 void yf::HttpRewrite::Replace::parse_groups()
445 const std::string & str = regex;
447 yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
448 for (size_t i = 0; i < str.size(); ++i)
451 if (!esc && str[i] == '\\')
456 if (!esc && str[i] == '(') //group starts
459 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
462 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
464 if (gnum > 0) gnum--;
470 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
472 if (i+1 < str.size() && str[i+1] == '<') //named
477 while (++i < str.size())
479 if (str[i] == '>') { term = true; break; }
480 if (!isalnum(str[i]))
481 throw mp::filter::FilterException
482 ("Only alphanumeric chars allowed, found "
486 + boost::lexical_cast<std::string>(i));
490 throw mp::filter::FilterException
491 ("Unterminated group name '" + gname
492 + " in '" + str +"'");
493 group_index[gnum] = gname;
494 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
495 gname.c_str(), gnum);
504 std::string yf::HttpRewrite::Replace::sub_vars(
505 const std::map<std::string, std::string> & vars) const
509 const std::string & in = recipe;
510 for (size_t i = 0; i < in.size(); ++i)
512 if (!esc && in[i] == '\\')
517 if (!esc && in[i] == '$') //var
519 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
524 while (++i < in.size())
526 if (in[i] == '}') { term = true; break; }
529 if (!term) throw mp::filter::FilterException
530 ("Unterminated var ref in '"+in+"' at "
531 + boost::lexical_cast<std::string>(i));
532 std::map<std::string, std::string>::const_iterator it
534 if (it != vars.end())
541 throw mp::filter::FilterException
542 ("Malformed or trimmed var ref in '"
543 +in+"' at "+boost::lexical_cast<std::string>(i));
554 yf::HttpRewrite::Phase::Phase() : m_verbose(0)
558 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
560 static const char *names[2] = { "verbose", 0 };
561 std::string values[1];
563 mp::xml::parse_attr(ptr, names, values);
565 phase.m_verbose = atoi(values[0].c_str());
567 std::map<std::string, RulePtr > rules;
568 for (ptr = ptr->children; ptr; ptr = ptr->next)
570 if (ptr->type != XML_ELEMENT_NODE)
572 else if (!strcmp((const char *) ptr->name, "rule"))
574 static const char *names[2] = { "name", 0 };
575 std::string values[1];
576 values[0] = "default";
577 mp::xml::parse_attr(ptr, names, values);
579 RulePtr rule(new Rule);
580 for (xmlNode *p = ptr->children; p; p = p->next)
582 if (p->type != XML_ELEMENT_NODE)
584 if (!strcmp((const char *) p->name, "rewrite"))
587 const struct _xmlAttr *attr;
588 for (attr = p->properties; attr; attr = attr->next)
590 if (!strcmp((const char *) attr->name, "from"))
591 replace.regex = mp::xml::get_text(attr->children);
592 else if (!strcmp((const char *) attr->name, "to"))
593 replace.recipe = mp::xml::get_text(attr->children);
595 throw mp::filter::FilterException
597 + std::string((const char *) attr->name)
598 + " in rewrite section of http_rewrite");
600 yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
601 replace.regex.c_str(), replace.recipe.c_str());
602 replace.parse_groups();
603 if (!replace.regex.empty())
604 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