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 {
72 std::list<Within> within_list;
74 void rewrite_reqline(mp::odr & o, Z_HTTP_Request *hreq,
75 std::map<std::string, std::string> & vars) const;
76 void rewrite_headers(mp::odr & o, Z_HTTP_Header *headers,
77 std::map<std::string, std::string> & vars) const;
78 void rewrite_body(mp::odr & o,
79 char **content_buf, int *content_len,
80 std::map<std::string, std::string> & vars) const;
82 class HttpRewrite::Event : public HTMLParserEvent {
83 void openTagStart(const char *tag, int tag_len);
84 void anyTagEnd(const char *tag, int tag_len, int close_it);
85 void attribute(const char *tag, int tag_len,
86 const char *attr, int attr_len,
87 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::list<Within>::const_iterator enabled_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)
247 enabled_within = m_phase->within_list.end();
250 yf::HttpRewrite::Event::~Event()
255 const char *yf::HttpRewrite::Event::result()
257 return wrbuf_cstr(m_w);
260 void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
262 // check if there is <within tag="x" .. />
263 if (enabled_within == m_phase->within_list.end())
265 std::string t(tag, tag_len);
266 std::list<Within>::const_iterator it =
267 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)
287 wrbuf_putc(m_w, '<');
288 wrbuf_write(m_w, tag, tag_len);
291 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
296 std::list<Within>::const_iterator it = enabled_within;
297 if (it != m_phase->within_list.end())
299 std::string t(tag, tag_len);
300 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
302 enabled_within = m_phase->within_list.end();
307 wrbuf_putc(m_w, '/');
308 wrbuf_putc(m_w, '>');
311 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
312 const char *attr, int attr_len,
313 const char *value, int val_len)
315 std::list<Within>::const_iterator it = m_phase->within_list.begin();
318 for (; it != m_phase->within_list.end(); it++)
320 std::string t(tag, tag_len);
321 if (it->tag.length() == 0 ||
322 yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
324 std::string a(attr, attr_len);
325 std::vector<std::string> attr;
326 boost::split(attr, it->attr, boost::is_any_of(","));
328 for (i = 0; i < attr.size(); i++)
330 if (attr[i].compare("#text") &&
331 yaz_strcasecmp(attr[i].c_str(), a.c_str()) == 0)
339 wrbuf_putc(m_w, ' ');
340 wrbuf_write(m_w, attr, attr_len);
341 wrbuf_puts(m_w, "=\"");
346 std::string input(value, val_len);
347 output = it->rule->test_patterns(m_vars, input);
350 wrbuf_write(m_w, value, val_len);
352 wrbuf_puts(m_w, output.c_str());
353 wrbuf_puts(m_w, "\"");
356 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
358 std::list<Within>::const_iterator it = enabled_within;
359 if (it != m_phase->within_list.end())
361 std::string t(tag, tag_len);
362 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
364 enabled_within = m_phase->within_list.end();
367 wrbuf_puts(m_w, "</");
368 wrbuf_write(m_w, tag, tag_len);
371 void yf::HttpRewrite::Event::text(const char *value, int len)
373 std::list<Within>::const_iterator it = enabled_within;
376 if (it != m_phase->within_list.end())
379 if (it->attr.length() > 0)
382 std::vector<std::string> attr;
383 boost::split(attr, it->attr, boost::is_any_of(","));
385 for (i = 0; i < attr.size(); i++)
387 if (attr[i].compare("#text") == 0)
397 std::string input(value, len);
398 output = it->rule->test_patterns(m_vars, input);
401 wrbuf_write(m_w, value, len);
403 wrbuf_puts(m_w, output.c_str());
408 * Tests pattern from the vector in order and executes recipe on
411 const std::string yf::HttpRewrite::Rule::test_patterns(
412 std::map<std::string, std::string> & vars,
413 const std::string & txt) const
415 std::list<Replace>::const_iterator it = replace_list.begin();
417 for (; it != replace_list.end(); it++)
419 std::string out = it->search_replace(vars, txt);
420 if (!out.empty()) return out;
425 const std::string yf::HttpRewrite::Replace::search_replace(
426 std::map<std::string, std::string> & vars,
427 const std::string & txt) const
429 //exec regex against value
430 boost::regex re(regex);
432 std::string::const_iterator start, end;
436 while (regex_search(start, end, what, re)) //find next full match
439 for (i = 1; i < what.size(); ++i)
441 //check if the group is named
442 std::map<int, std::string>::const_iterator it
443 = group_index.find(i);
444 if (it != group_index.end())
446 if (!what[i].str().empty())
447 vars[it->second] = what[i];
451 //prepare replacement string
452 std::string rvalue = sub_vars(vars);
453 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
454 what.str(0).c_str(), rvalue.c_str());
455 out.append(start, what[0].first);
457 start = what[0].second; //move search forward
459 //if we had a match cat the last part
460 if (start != txt.begin())
461 out.append(start, end);
465 void yf::HttpRewrite::Replace::parse_groups()
469 const std::string & str = regex;
471 yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
472 for (size_t i = 0; i < str.size(); ++i)
475 if (!esc && str[i] == '\\')
480 if (!esc && str[i] == '(') //group starts
483 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
486 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
488 if (gnum > 0) gnum--;
494 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
496 if (i+1 < str.size() && str[i+1] == '<') //named
501 while (++i < str.size())
503 if (str[i] == '>') { term = true; break; }
504 if (!isalnum(str[i]))
505 throw mp::filter::FilterException
506 ("Only alphanumeric chars allowed, found "
510 + boost::lexical_cast<std::string>(i));
514 throw mp::filter::FilterException
515 ("Unterminated group name '" + gname
516 + " in '" + str +"'");
517 group_index[gnum] = gname;
518 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
519 gname.c_str(), gnum);
528 std::string yf::HttpRewrite::Replace::sub_vars (
529 const std::map<std::string, std::string> & vars) const
533 const std::string & in = recipe;
534 for (size_t i = 0; i < in.size(); ++i)
536 if (!esc && in[i] == '\\')
541 if (!esc && in[i] == '$') //var
543 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
548 while (++i < in.size())
550 if (in[i] == '}') { term = true; break; }
553 if (!term) throw mp::filter::FilterException
554 ("Unterminated var ref in '"+in+"' at "
555 + boost::lexical_cast<std::string>(i));
556 std::map<std::string, std::string>::const_iterator it
558 if (it != vars.end())
565 throw mp::filter::FilterException
566 ("Malformed or trimmed var ref in '"
567 +in+"' at "+boost::lexical_cast<std::string>(i));
578 yf::HttpRewrite::Phase::Phase() : m_verbose(0)
582 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
584 static const char *names[2] = { "verbose", 0 };
585 std::string values[1];
587 mp::xml::parse_attr(ptr, names, values);
589 phase.m_verbose = atoi(values[0].c_str());
591 std::map<std::string, RulePtr > rules;
592 for (ptr = ptr->children; ptr; ptr = ptr->next)
594 if (ptr->type != XML_ELEMENT_NODE)
596 else if (!strcmp((const char *) ptr->name, "rule"))
598 static const char *names[2] = { "name", 0 };
599 std::string values[1];
600 values[0] = "default";
601 mp::xml::parse_attr(ptr, names, values);
603 RulePtr rule(new Rule);
604 for (xmlNode *p = ptr->children; p; p = p->next)
606 if (p->type != XML_ELEMENT_NODE)
608 if (!strcmp((const char *) p->name, "rewrite"))
611 const struct _xmlAttr *attr;
612 for (attr = p->properties; attr; attr = attr->next)
614 if (!strcmp((const char *) attr->name, "from"))
615 replace.regex = mp::xml::get_text(attr->children);
616 else if (!strcmp((const char *) attr->name, "to"))
617 replace.recipe = mp::xml::get_text(attr->children);
619 throw mp::filter::FilterException
621 + std::string((const char *) attr->name)
622 + " in rewrite section of http_rewrite");
624 yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
625 replace.regex.c_str(), replace.recipe.c_str());
626 replace.parse_groups();
627 if (!replace.regex.empty())
628 rule->replace_list.push_back(replace);
631 throw mp::filter::FilterException
633 + std::string((const char *) p->name)
634 + " in http_rewrite filter");
636 rules[values[0]] = rule;
638 else if (!strcmp((const char *) ptr->name, "within"))
640 static const char *names[6] =
641 { "header", "attr", "tag", "rule", "reqline", 0 };
642 std::string values[5];
643 mp::xml::parse_attr(ptr, names, values);
645 w.header = values[0];
648 std::map<std::string,RulePtr>::const_iterator it =
649 rules.find(values[3]);
650 if (it == rules.end())
651 throw mp::filter::FilterException
652 ("Reference to non-existing rule '" + values[3] +
653 "' in http_rewrite filter");
655 w.reqline = values[4] == "1";
656 phase.within_list.push_back(w);
660 throw mp::filter::FilterException
662 + std::string((const char *) ptr->name)
663 + " in http_rewrite filter");
668 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
671 for (ptr = ptr->children; ptr; ptr = ptr->next)
673 if (ptr->type != XML_ELEMENT_NODE)
675 else if (!strcmp((const char *) ptr->name, "request"))
677 configure_phase(ptr, *req_phase);
679 else if (!strcmp((const char *) ptr->name, "response"))
681 configure_phase(ptr, *res_phase);
685 throw mp::filter::FilterException
687 + std::string((const char *) ptr->name)
688 + " in http_rewrite1 filter");
693 static mp::filter::Base* filter_creator()
695 return new mp::filter::HttpRewrite;
699 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
710 * c-file-style: "Stroustrup"
711 * indent-tabs-mode: nil
713 * vim: shiftwidth=4 tabstop=8 expandtab