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"
29 #include <boost/regex.hpp>
30 #include <boost/lexical_cast.hpp>
31 #include <boost/algorithm/string.hpp>
35 namespace mp = metaproxy_1;
36 namespace yf = mp::filter;
38 namespace metaproxy_1 {
40 class HttpRewrite::Replace {
44 std::map<int, std::string> group_index;
45 const std::string search_replace(
46 std::map<std::string, std::string> & vars,
47 const std::string & txt) const;
48 std::string sub_vars (
49 const std::map<std::string, std::string> & vars) const;
53 class HttpRewrite::Rule {
55 std::list<Replace> replace_list;
56 const std::string test_patterns(
57 std::map<std::string, std::string> & vars,
58 const std::string & txt) const;
60 class HttpRewrite::Within {
69 class HttpRewrite::Phase {
71 std::list<Within> within_list;
72 void rewrite_reqline(mp::odr & o, Z_HTTP_Request *hreq,
73 std::map<std::string, std::string> & vars) const;
74 void rewrite_headers(mp::odr & o, Z_HTTP_Header *headers,
75 std::map<std::string, std::string> & vars) const;
76 void rewrite_body(mp::odr & o,
77 char **content_buf, int *content_len,
78 std::map<std::string, std::string> & vars) const;
80 class HttpRewrite::Event : public HTMLParserEvent {
81 void openTagStart(const char *name);
82 void anyTagEnd(const char *name, int close_it);
83 void attribute(const char *tagName,
87 void closeTag(const char *name);
88 void text(const char *value, int len);
91 std::list<Within>::const_iterator enabled_within;
92 std::map<std::string, std::string> &m_vars;
94 Event(const Phase *p, std::map<std::string, std::string> &vars);
101 yf::HttpRewrite::HttpRewrite() :
102 req_phase(new Phase), res_phase(new Phase)
106 yf::HttpRewrite::~HttpRewrite()
110 void yf::HttpRewrite::process(mp::Package & package) const
112 yaz_log(YLOG_LOG, "HttpRewrite begins....");
113 Z_GDU *gdu = package.request().get();
114 //map of request/response vars
115 std::map<std::string, std::string> vars;
116 //we have an http req
117 if (gdu && gdu->which == Z_GDU_HTTP_Request)
119 Z_HTTP_Request *hreq = gdu->u.HTTP_Request;
121 req_phase->rewrite_reqline(o, hreq, vars);
122 yaz_log(YLOG_LOG, ">> Request headers");
123 req_phase->rewrite_headers(o, hreq->headers, vars);
124 req_phase->rewrite_body(o,
125 &hreq->content_buf, &hreq->content_len, vars);
126 package.request() = gdu;
129 gdu = package.response().get();
130 if (gdu && gdu->which == Z_GDU_HTTP_Response)
132 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
133 yaz_log(YLOG_LOG, "Response code %d", hres->code);
135 yaz_log(YLOG_LOG, "<< Respose headers");
136 res_phase->rewrite_headers(o, hres->headers, vars);
137 res_phase->rewrite_body(o, &hres->content_buf,
138 &hres->content_len, vars);
139 package.response() = gdu;
143 void yf::HttpRewrite::Phase::rewrite_reqline (mp::odr & o,
144 Z_HTTP_Request *hreq,
145 std::map<std::string, std::string> & vars) const
147 //rewrite the request line
149 if (strstr(hreq->path, "http://") == hreq->path)
151 yaz_log(YLOG_LOG, "Path in the method line is absolute, "
152 "possibly a proxy request");
157 //TODO what about proto
159 path += z_HTTP_header_lookup(hreq->headers, "Host");
164 std::list<Within>::const_iterator it = within_list.begin();
165 for (; it != within_list.end(); it++)
168 RulePtr rule = it->rule;
169 yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
170 std::string npath = rule->test_patterns(vars, path);
173 yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
174 hreq->path = odr_strdup(o, npath.c_str());
179 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
180 Z_HTTP_Header *headers,
181 std::map<std::string, std::string> & vars) const
183 for (Z_HTTP_Header *header = headers; header; header = header->next)
185 std::list<Within>::const_iterator it = within_list.begin();
186 for (; it != within_list.end(); it++)
188 if (it->header.length() > 0 &&
189 yaz_strcasecmp(it->header.c_str(), header->name) == 0)
191 std::string sheader(header->name);
193 sheader += header->value;
195 RulePtr rule = it->rule;
196 std::string out = rule->test_patterns(vars, sheader);
199 size_t pos = out.find(": ");
200 if (pos == std::string::npos)
202 yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
205 header->name = odr_strdup(o, out.substr(0, pos).c_str());
206 header->value = odr_strdup(o,
208 std::string::npos).c_str());
215 void yf::HttpRewrite::Phase::rewrite_body(mp::odr & o,
218 std::map<std::string, std::string> & vars) const
223 for (i = 0; i < *content_len; i++)
224 if ((*content_buf)[i] == 0)
225 return; // binary content. skip
228 Event ev(this, vars);
229 std::string buf(*content_buf, *content_len);
231 parser.parse(ev, buf.c_str());
232 const char *res = ev.result();
233 *content_buf = odr_strdup(o, res);
234 *content_len = strlen(res);
238 yf::HttpRewrite::Event::Event(const Phase *p,
239 std::map<std::string, std::string> & vars
240 ) : m_phase(p), m_vars(vars)
243 enabled_within = m_phase->within_list.end();
246 yf::HttpRewrite::Event::~Event()
251 const char *yf::HttpRewrite::Event::result()
253 return wrbuf_cstr(m_w);
256 void yf::HttpRewrite::Event::openTagStart(const char *name)
258 // check if there is <within tag="x" .. />
259 if (enabled_within == m_phase->within_list.end())
261 std::list<Within>::const_iterator it =
262 m_phase->within_list.begin();
263 for (; it != m_phase->within_list.end(); it++)
265 if (it->tag.length() > 0 && it->tag.compare(name) == 0)
271 wrbuf_putc(m_w, '<');
272 wrbuf_puts(m_w, name);
275 void yf::HttpRewrite::Event::anyTagEnd(const char *name, int close_it)
279 std::list<Within>::const_iterator it = enabled_within;
280 if (it != m_phase->within_list.end())
282 if (it->tag.compare(name) == 0)
284 enabled_within = m_phase->within_list.end();
289 wrbuf_putc(m_w, '/');
290 wrbuf_putc(m_w, '>');
293 void yf::HttpRewrite::Event::attribute(const char *tagName,
298 std::list<Within>::const_iterator it = m_phase->within_list.begin();
301 for (; it != m_phase->within_list.end(); it++)
303 if (it->tag.length() == 0 || it->tag.compare(tagName) == 0)
305 std::vector<std::string> attr;
306 boost::split(attr, it->attr, boost::is_any_of(","));
308 for (i = 0; i < attr.size(); i++)
310 if (attr[i].compare("#text") && attr[i].compare(name) == 0)
318 wrbuf_putc(m_w, ' ');
319 wrbuf_puts(m_w, name);
320 wrbuf_puts(m_w, "=\"");
325 std::string input(value, val_len);
326 output = it->rule->test_patterns(m_vars, input);
329 wrbuf_write(m_w, value, val_len);
331 wrbuf_puts(m_w, output.c_str());
332 wrbuf_puts(m_w, "\"");
335 void yf::HttpRewrite::Event::closeTag(const char *name)
337 std::list<Within>::const_iterator it = enabled_within;
338 if (it != m_phase->within_list.end())
340 if (it->tag.compare(name) == 0)
342 enabled_within = m_phase->within_list.end();
345 wrbuf_puts(m_w, "</");
346 wrbuf_puts(m_w, name);
349 void yf::HttpRewrite::Event::text(const char *value, int len)
351 std::list<Within>::const_iterator it = enabled_within;
354 if (it != m_phase->within_list.end())
357 if (it->attr.length() > 0)
360 std::vector<std::string> attr;
361 boost::split(attr, it->attr, boost::is_any_of(","));
363 for (i = 0; i < attr.size(); i++)
365 if (attr[i].compare("#text") == 0)
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());
386 * Tests pattern from the vector in order and executes recipe on
389 const std::string yf::HttpRewrite::Rule::test_patterns(
390 std::map<std::string, std::string> & vars,
391 const std::string & txt) const
393 std::list<Replace>::const_iterator it = replace_list.begin();
395 for (; it != replace_list.end(); it++)
397 std::string out = it->search_replace(vars, txt);
398 if (!out.empty()) return out;
403 const std::string yf::HttpRewrite::Replace::search_replace(
404 std::map<std::string, std::string> & vars,
405 const std::string & txt) const
407 //exec regex against value
408 boost::regex re(regex);
410 std::string::const_iterator start, end;
414 while (regex_search(start, end, what, re)) //find next full match
417 for (i = 1; i < what.size(); ++i)
419 //check if the group is named
420 std::map<int, std::string>::const_iterator it
421 = group_index.find(i);
422 if (it != group_index.end())
424 if (!what[i].str().empty())
425 vars[it->second] = what[i];
429 //prepare replacement string
430 std::string rvalue = sub_vars(vars);
431 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
432 what.str(0).c_str(), rvalue.c_str());
433 out.append(start, what[0].first);
435 start = what[0].second; //move search forward
437 //if we had a match cat the last part
438 if (start != txt.begin())
439 out.append(start, end);
443 void yf::HttpRewrite::Replace::parse_groups()
447 const std::string & str = regex;
449 yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
450 for (size_t i = 0; i < str.size(); ++i)
453 if (!esc && str[i] == '\\')
458 if (!esc && str[i] == '(') //group starts
461 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
464 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
466 if (gnum > 0) gnum--;
472 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
474 if (i+1 < str.size() && str[i+1] == '<') //named
479 while (++i < str.size())
481 if (str[i] == '>') { term = true; break; }
482 if (!isalnum(str[i]))
483 throw mp::filter::FilterException
484 ("Only alphanumeric chars allowed, found "
488 + boost::lexical_cast<std::string>(i));
492 throw mp::filter::FilterException
493 ("Unterminated group name '" + gname
494 + " in '" + str +"'");
495 group_index[gnum] = gname;
496 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
497 gname.c_str(), gnum);
506 std::string yf::HttpRewrite::Replace::sub_vars (
507 const std::map<std::string, std::string> & vars) const
511 const std::string & in = recipe;
512 for (size_t i = 0; i < in.size(); ++i)
514 if (!esc && in[i] == '\\')
519 if (!esc && in[i] == '$') //var
521 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
526 while (++i < in.size())
528 if (in[i] == '}') { term = true; break; }
531 if (!term) throw mp::filter::FilterException
532 ("Unterminated var ref in '"+in+"' at "
533 + boost::lexical_cast<std::string>(i));
534 std::map<std::string, std::string>::const_iterator it
536 if (it != vars.end())
543 throw mp::filter::FilterException
544 ("Malformed or trimmed var ref in '"
545 +in+"' at "+boost::lexical_cast<std::string>(i));
557 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
559 std::map<std::string, RulePtr > rules;
560 for (ptr = ptr->children; ptr; ptr = ptr->next)
562 if (ptr->type != XML_ELEMENT_NODE)
564 else if (!strcmp((const char *) ptr->name, "rule"))
566 static const char *names[2] = { "name", 0 };
567 std::string values[1];
568 values[0] = "default";
569 mp::xml::parse_attr(ptr, names, values);
571 RulePtr rule(new Rule);
572 for (xmlNode *p = ptr->children; p; p = p->next)
574 if (p->type != XML_ELEMENT_NODE)
576 if (!strcmp((const char *) p->name, "rewrite"))
579 const struct _xmlAttr *attr;
580 for (attr = p->properties; attr; attr = attr->next)
582 if (!strcmp((const char *) attr->name, "from"))
583 replace.regex = mp::xml::get_text(attr->children);
584 else if (!strcmp((const char *) attr->name, "to"))
585 replace.recipe = mp::xml::get_text(attr->children);
587 throw mp::filter::FilterException
589 + std::string((const char *) attr->name)
590 + " in rewrite section of http_rewrite");
592 yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
593 replace.regex.c_str(), replace.recipe.c_str());
594 replace.parse_groups();
595 if (!replace.regex.empty())
596 rule->replace_list.push_back(replace);
599 throw mp::filter::FilterException
601 + std::string((const char *) p->name)
602 + " in http_rewrite filter");
604 rules[values[0]] = rule;
606 else if (!strcmp((const char *) ptr->name, "within"))
608 static const char *names[6] =
609 { "header", "attr", "tag", "rule", "reqline", 0 };
610 std::string values[5];
611 mp::xml::parse_attr(ptr, names, values);
613 w.header = values[0];
616 std::map<std::string,RulePtr>::const_iterator it =
617 rules.find(values[3]);
618 if (it == rules.end())
619 throw mp::filter::FilterException
620 ("Reference to non-existing rule '" + values[3] +
621 "' in http_rewrite filter");
623 w.reqline = values[4] == "1";
624 phase.within_list.push_back(w);
628 throw mp::filter::FilterException
630 + std::string((const char *) ptr->name)
631 + " in http_rewrite filter");
636 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
639 for (ptr = ptr->children; ptr; ptr = ptr->next)
641 if (ptr->type != XML_ELEMENT_NODE)
643 else if (!strcmp((const char *) ptr->name, "request"))
645 configure_phase(ptr, *req_phase);
647 else if (!strcmp((const char *) ptr->name, "response"))
649 configure_phase(ptr, *res_phase);
653 throw mp::filter::FilterException
655 + std::string((const char *) ptr->name)
656 + " in http_rewrite1 filter");
661 static mp::filter::Base* filter_creator()
663 return new mp::filter::HttpRewrite;
667 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
678 * c-file-style: "Stroustrup"
679 * indent-tabs-mode: nil
681 * vim: shiftwidth=4 tabstop=8 expandtab