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 *tag, int tag_len);
82 void anyTagEnd(const char *tag, int tag_len, int close_it);
83 void attribute(const char *tag, int tag_len,
84 const char *attr, int attr_len,
85 const char *value, int val_len);
86 void closeTag(const char *tag, int tag_len);
87 void text(const char *value, int len);
90 std::list<Within>::const_iterator enabled_within;
91 std::map<std::string, std::string> &m_vars;
93 Event(const Phase *p, std::map<std::string, std::string> &vars);
100 yf::HttpRewrite::HttpRewrite() :
101 req_phase(new Phase), res_phase(new Phase)
105 yf::HttpRewrite::~HttpRewrite()
109 void yf::HttpRewrite::process(mp::Package & package) const
111 yaz_log(YLOG_LOG, "HttpRewrite begins....");
112 Z_GDU *gdu = package.request().get();
113 //map of request/response vars
114 std::map<std::string, std::string> vars;
115 //we have an http req
116 if (gdu && gdu->which == Z_GDU_HTTP_Request)
118 Z_HTTP_Request *hreq = gdu->u.HTTP_Request;
120 req_phase->rewrite_reqline(o, hreq, vars);
121 yaz_log(YLOG_LOG, ">> Request headers");
122 req_phase->rewrite_headers(o, hreq->headers, vars);
123 req_phase->rewrite_body(o,
124 &hreq->content_buf, &hreq->content_len, vars);
125 package.request() = gdu;
128 gdu = package.response().get();
129 if (gdu && gdu->which == Z_GDU_HTTP_Response)
131 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
132 yaz_log(YLOG_LOG, "Response code %d", hres->code);
134 yaz_log(YLOG_LOG, "<< Respose headers");
135 res_phase->rewrite_headers(o, hres->headers, vars);
136 res_phase->rewrite_body(o, &hres->content_buf,
137 &hres->content_len, vars);
138 package.response() = gdu;
142 void yf::HttpRewrite::Phase::rewrite_reqline (mp::odr & o,
143 Z_HTTP_Request *hreq,
144 std::map<std::string, std::string> & vars) const
146 //rewrite the request line
148 if (strstr(hreq->path, "http://") == hreq->path)
150 yaz_log(YLOG_LOG, "Path in the method line is absolute, "
151 "possibly a proxy request");
156 //TODO what about proto
158 path += z_HTTP_header_lookup(hreq->headers, "Host");
163 std::list<Within>::const_iterator it = within_list.begin();
164 for (; it != within_list.end(); it++)
167 RulePtr rule = it->rule;
168 yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
169 std::string npath = rule->test_patterns(vars, path);
172 yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
173 hreq->path = odr_strdup(o, npath.c_str());
178 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
179 Z_HTTP_Header *headers,
180 std::map<std::string, std::string> & vars) const
182 for (Z_HTTP_Header *header = headers; header; header = header->next)
184 std::list<Within>::const_iterator it = within_list.begin();
185 for (; it != within_list.end(); it++)
187 if (it->header.length() > 0 &&
188 yaz_strcasecmp(it->header.c_str(), header->name) == 0)
190 std::string sheader(header->name);
192 sheader += header->value;
194 RulePtr rule = it->rule;
195 std::string out = rule->test_patterns(vars, sheader);
198 size_t pos = out.find(": ");
199 if (pos == std::string::npos)
201 yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
204 header->name = odr_strdup(o, out.substr(0, pos).c_str());
205 header->value = odr_strdup(o,
207 std::string::npos).c_str());
214 void yf::HttpRewrite::Phase::rewrite_body(mp::odr & o,
217 std::map<std::string, std::string> & vars) const
222 for (i = 0; i < *content_len; i++)
223 if ((*content_buf)[i] == 0)
224 return; // binary content. skip
227 Event ev(this, vars);
228 std::string buf(*content_buf, *content_len);
230 parser.parse(ev, buf.c_str());
231 const char *res = ev.result();
232 *content_buf = odr_strdup(o, res);
233 *content_len = strlen(res);
237 yf::HttpRewrite::Event::Event(const Phase *p,
238 std::map<std::string, std::string> & vars
239 ) : m_phase(p), m_vars(vars)
242 enabled_within = m_phase->within_list.end();
245 yf::HttpRewrite::Event::~Event()
250 const char *yf::HttpRewrite::Event::result()
252 return wrbuf_cstr(m_w);
255 void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
257 // check if there is <within tag="x" .. />
258 if (enabled_within == m_phase->within_list.end())
260 std::string t(tag, tag_len);
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 && yaz_strcasecmp(it->tag.c_str(),
272 wrbuf_putc(m_w, '<');
273 wrbuf_write(m_w, tag, tag_len);
276 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
281 std::list<Within>::const_iterator it = enabled_within;
282 if (it != m_phase->within_list.end())
284 std::string t(tag, tag_len);
285 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
287 enabled_within = m_phase->within_list.end();
292 wrbuf_putc(m_w, '/');
293 wrbuf_putc(m_w, '>');
296 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
297 const char *attr, int attr_len,
298 const char *value, int val_len)
300 std::list<Within>::const_iterator it = m_phase->within_list.begin();
303 for (; it != m_phase->within_list.end(); it++)
305 std::string t(tag, tag_len);
306 if (it->tag.length() == 0 ||
307 yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
309 std::string a(attr, attr_len);
310 std::vector<std::string> attr;
311 boost::split(attr, it->attr, boost::is_any_of(","));
313 for (i = 0; i < attr.size(); i++)
315 if (attr[i].compare("#text") &&
316 yaz_strcasecmp(attr[i].c_str(), a.c_str()) == 0)
324 wrbuf_putc(m_w, ' ');
325 wrbuf_write(m_w, attr, attr_len);
326 wrbuf_puts(m_w, "=\"");
331 std::string input(value, val_len);
332 output = it->rule->test_patterns(m_vars, input);
335 wrbuf_write(m_w, value, val_len);
337 wrbuf_puts(m_w, output.c_str());
338 wrbuf_puts(m_w, "\"");
341 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
343 std::list<Within>::const_iterator it = enabled_within;
344 if (it != m_phase->within_list.end())
346 std::string t(tag, tag_len);
347 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
349 enabled_within = m_phase->within_list.end();
352 wrbuf_puts(m_w, "</");
353 wrbuf_write(m_w, tag, tag_len);
356 void yf::HttpRewrite::Event::text(const char *value, int len)
358 std::list<Within>::const_iterator it = enabled_within;
361 if (it != m_phase->within_list.end())
364 if (it->attr.length() > 0)
367 std::vector<std::string> attr;
368 boost::split(attr, it->attr, boost::is_any_of(","));
370 for (i = 0; i < attr.size(); i++)
372 if (attr[i].compare("#text") == 0)
382 std::string input(value, len);
383 output = it->rule->test_patterns(m_vars, input);
386 wrbuf_write(m_w, value, len);
388 wrbuf_puts(m_w, output.c_str());
393 * Tests pattern from the vector in order and executes recipe on
396 const std::string yf::HttpRewrite::Rule::test_patterns(
397 std::map<std::string, std::string> & vars,
398 const std::string & txt) const
400 std::list<Replace>::const_iterator it = replace_list.begin();
402 for (; it != replace_list.end(); it++)
404 std::string out = it->search_replace(vars, txt);
405 if (!out.empty()) return out;
410 const std::string yf::HttpRewrite::Replace::search_replace(
411 std::map<std::string, std::string> & vars,
412 const std::string & txt) const
414 //exec regex against value
415 boost::regex re(regex);
417 std::string::const_iterator start, end;
421 while (regex_search(start, end, what, re)) //find next full match
424 for (i = 1; i < what.size(); ++i)
426 //check if the group is named
427 std::map<int, std::string>::const_iterator it
428 = group_index.find(i);
429 if (it != group_index.end())
431 if (!what[i].str().empty())
432 vars[it->second] = what[i];
436 //prepare replacement string
437 std::string rvalue = sub_vars(vars);
438 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
439 what.str(0).c_str(), rvalue.c_str());
440 out.append(start, what[0].first);
442 start = what[0].second; //move search forward
444 //if we had a match cat the last part
445 if (start != txt.begin())
446 out.append(start, end);
450 void yf::HttpRewrite::Replace::parse_groups()
454 const std::string & str = regex;
456 yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
457 for (size_t i = 0; i < str.size(); ++i)
460 if (!esc && str[i] == '\\')
465 if (!esc && str[i] == '(') //group starts
468 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
471 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
473 if (gnum > 0) gnum--;
479 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
481 if (i+1 < str.size() && str[i+1] == '<') //named
486 while (++i < str.size())
488 if (str[i] == '>') { term = true; break; }
489 if (!isalnum(str[i]))
490 throw mp::filter::FilterException
491 ("Only alphanumeric chars allowed, found "
495 + boost::lexical_cast<std::string>(i));
499 throw mp::filter::FilterException
500 ("Unterminated group name '" + gname
501 + " in '" + str +"'");
502 group_index[gnum] = gname;
503 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
504 gname.c_str(), gnum);
513 std::string yf::HttpRewrite::Replace::sub_vars (
514 const std::map<std::string, std::string> & vars) const
518 const std::string & in = recipe;
519 for (size_t i = 0; i < in.size(); ++i)
521 if (!esc && in[i] == '\\')
526 if (!esc && in[i] == '$') //var
528 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
533 while (++i < in.size())
535 if (in[i] == '}') { term = true; break; }
538 if (!term) throw mp::filter::FilterException
539 ("Unterminated var ref in '"+in+"' at "
540 + boost::lexical_cast<std::string>(i));
541 std::map<std::string, std::string>::const_iterator it
543 if (it != vars.end())
550 throw mp::filter::FilterException
551 ("Malformed or trimmed var ref in '"
552 +in+"' at "+boost::lexical_cast<std::string>(i));
564 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
566 std::map<std::string, RulePtr > rules;
567 for (ptr = ptr->children; ptr; ptr = ptr->next)
569 if (ptr->type != XML_ELEMENT_NODE)
571 else if (!strcmp((const char *) ptr->name, "rule"))
573 static const char *names[2] = { "name", 0 };
574 std::string values[1];
575 values[0] = "default";
576 mp::xml::parse_attr(ptr, names, values);
578 RulePtr rule(new Rule);
579 for (xmlNode *p = ptr->children; p; p = p->next)
581 if (p->type != XML_ELEMENT_NODE)
583 if (!strcmp((const char *) p->name, "rewrite"))
586 const struct _xmlAttr *attr;
587 for (attr = p->properties; attr; attr = attr->next)
589 if (!strcmp((const char *) attr->name, "from"))
590 replace.regex = mp::xml::get_text(attr->children);
591 else if (!strcmp((const char *) attr->name, "to"))
592 replace.recipe = mp::xml::get_text(attr->children);
594 throw mp::filter::FilterException
596 + std::string((const char *) attr->name)
597 + " in rewrite section of http_rewrite");
599 yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
600 replace.regex.c_str(), replace.recipe.c_str());
601 replace.parse_groups();
602 if (!replace.regex.empty())
603 rule->replace_list.push_back(replace);
606 throw mp::filter::FilterException
608 + std::string((const char *) p->name)
609 + " in http_rewrite filter");
611 rules[values[0]] = rule;
613 else if (!strcmp((const char *) ptr->name, "within"))
615 static const char *names[6] =
616 { "header", "attr", "tag", "rule", "reqline", 0 };
617 std::string values[5];
618 mp::xml::parse_attr(ptr, names, values);
620 w.header = values[0];
623 std::map<std::string,RulePtr>::const_iterator it =
624 rules.find(values[3]);
625 if (it == rules.end())
626 throw mp::filter::FilterException
627 ("Reference to non-existing rule '" + values[3] +
628 "' in http_rewrite filter");
630 w.reqline = values[4] == "1";
631 phase.within_list.push_back(w);
635 throw mp::filter::FilterException
637 + std::string((const char *) ptr->name)
638 + " in http_rewrite filter");
643 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
646 for (ptr = ptr->children; ptr; ptr = ptr->next)
648 if (ptr->type != XML_ELEMENT_NODE)
650 else if (!strcmp((const char *) ptr->name, "request"))
652 configure_phase(ptr, *req_phase);
654 else if (!strcmp((const char *) ptr->name, "response"))
656 configure_phase(ptr, *res_phase);
660 throw mp::filter::FilterException
662 + std::string((const char *) ptr->name)
663 + " in http_rewrite1 filter");
668 static mp::filter::Base* filter_creator()
670 return new mp::filter::HttpRewrite;
674 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
685 * c-file-style: "Stroustrup"
686 * indent-tabs-mode: nil
688 * vim: shiftwidth=4 tabstop=8 expandtab