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;
49 std::string sub_vars (
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);
89 void closeTag(const char *tag, int tag_len);
90 void text(const char *value, int len);
93 std::stack<std::list<Within>::const_iterator> s_within;
94 std::map<std::string, std::string> &m_vars;
96 Event(const Phase *p, std::map<std::string, std::string> &vars);
103 yf::HttpRewrite::HttpRewrite() :
104 req_phase(new Phase), res_phase(new Phase)
108 yf::HttpRewrite::~HttpRewrite()
112 void yf::HttpRewrite::process(mp::Package & package) const
114 yaz_log(YLOG_LOG, "HttpRewrite begins....");
115 Z_GDU *gdu = package.request().get();
116 //map of request/response vars
117 std::map<std::string, std::string> vars;
118 //we have an http req
119 if (gdu && gdu->which == Z_GDU_HTTP_Request)
121 Z_HTTP_Request *hreq = gdu->u.HTTP_Request;
123 req_phase->rewrite_reqline(o, hreq, vars);
124 yaz_log(YLOG_LOG, ">> Request headers");
125 req_phase->rewrite_headers(o, hreq->headers, vars);
126 req_phase->rewrite_body(o,
127 &hreq->content_buf, &hreq->content_len, vars);
128 package.request() = gdu;
131 gdu = package.response().get();
132 if (gdu && gdu->which == Z_GDU_HTTP_Response)
134 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
135 yaz_log(YLOG_LOG, "Response code %d", hres->code);
137 yaz_log(YLOG_LOG, "<< Respose headers");
138 res_phase->rewrite_headers(o, hres->headers, vars);
139 res_phase->rewrite_body(o, &hres->content_buf,
140 &hres->content_len, vars);
141 package.response() = gdu;
145 void yf::HttpRewrite::Phase::rewrite_reqline (mp::odr & o,
146 Z_HTTP_Request *hreq,
147 std::map<std::string, std::string> & vars) const
149 //rewrite the request line
151 if (strstr(hreq->path, "http://") == hreq->path)
153 yaz_log(YLOG_LOG, "Path in the method line is absolute, "
154 "possibly a proxy request");
159 //TODO what about proto
161 path += z_HTTP_header_lookup(hreq->headers, "Host");
166 std::list<Within>::const_iterator it = within_list.begin();
167 for (; it != within_list.end(); it++)
170 RulePtr rule = it->rule;
171 yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
172 std::string npath = rule->test_patterns(vars, path);
175 yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
176 hreq->path = odr_strdup(o, npath.c_str());
181 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
182 Z_HTTP_Header *headers,
183 std::map<std::string, std::string> & vars) const
185 for (Z_HTTP_Header *header = headers; header; header = header->next)
187 std::list<Within>::const_iterator it = within_list.begin();
188 for (; it != within_list.end(); it++)
190 if (it->header.length() > 0 &&
191 yaz_strcasecmp(it->header.c_str(), header->name) == 0)
193 std::string sheader(header->name);
195 sheader += header->value;
197 RulePtr rule = it->rule;
198 std::string out = rule->test_patterns(vars, sheader);
201 size_t pos = out.find(": ");
202 if (pos == std::string::npos)
204 yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
207 header->name = odr_strdup(o, out.substr(0, pos).c_str());
208 header->value = odr_strdup(o,
210 std::string::npos).c_str());
217 void yf::HttpRewrite::Phase::rewrite_body(mp::odr & o,
220 std::map<std::string, std::string> & vars) const
225 for (i = 0; i < *content_len; i++)
226 if ((*content_buf)[i] == 0)
227 return; // binary content. skip
230 Event ev(this, vars);
232 parser.set_verbose(m_verbose);
234 std::string buf(*content_buf, *content_len);
236 parser.parse(ev, buf.c_str());
237 const char *res = ev.result();
238 *content_buf = odr_strdup(o, res);
239 *content_len = strlen(res);
243 yf::HttpRewrite::Event::Event(const Phase *p,
244 std::map<std::string, std::string> & vars
245 ) : m_phase(p), m_vars(vars)
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 wrbuf_putc(m_w, '<');
263 wrbuf_write(m_w, tag, tag_len);
265 std::string t(tag, tag_len);
266 std::list<Within>::const_iterator it = m_phase->within_list.begin();
267 for (; it != m_phase->within_list.end(); it++)
269 if (it->tag.length() > 0 && yaz_strcasecmp(it->tag.c_str(),
272 std::vector<std::string> attr;
273 boost::split(attr, it->attr, boost::is_any_of(","));
275 for (i = 0; i < attr.size(); i++)
277 if (attr[i].compare("#text") == 0)
287 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
292 if (!s_within.empty())
294 std::list<Within>::const_iterator it = s_within.top();
295 std::string t(tag, tag_len);
296 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
301 wrbuf_putc(m_w, '/');
302 wrbuf_putc(m_w, '>');
305 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
306 const char *attr, int attr_len,
307 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);
335 wrbuf_puts(m_w, "=\"");
340 std::string input(value, val_len);
341 output = it->rule->test_patterns(m_vars, input);
344 wrbuf_write(m_w, value, val_len);
346 wrbuf_puts(m_w, output.c_str());
347 wrbuf_puts(m_w, "\"");
350 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
352 if (!s_within.empty())
354 std::list<Within>::const_iterator it = s_within.top();
355 std::string t(tag, tag_len);
356 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
359 wrbuf_puts(m_w, "</");
360 wrbuf_write(m_w, tag, tag_len);
363 void yf::HttpRewrite::Event::text(const char *value, int len)
365 std::list<Within>::const_iterator it = m_phase->within_list.end();
366 if (!s_within.empty())
369 if (it != m_phase->within_list.end())
371 std::string input(value, len);
372 output = it->rule->test_patterns(m_vars, input);
375 wrbuf_write(m_w, value, len);
377 wrbuf_puts(m_w, output.c_str());
382 * Tests pattern from the vector in order and executes recipe on
385 const std::string yf::HttpRewrite::Rule::test_patterns(
386 std::map<std::string, std::string> & vars,
387 const std::string & txt) const
389 std::list<Replace>::const_iterator it = replace_list.begin();
391 for (; it != replace_list.end(); it++)
393 std::string out = it->search_replace(vars, txt);
394 if (!out.empty()) return out;
399 const std::string yf::HttpRewrite::Replace::search_replace(
400 std::map<std::string, std::string> & vars,
401 const std::string & txt) const
403 //exec regex against value
404 boost::regex re(regex);
406 std::string::const_iterator start, end;
410 while (regex_search(start, end, what, re)) //find next full match
413 for (i = 1; i < what.size(); ++i)
415 //check if the group is named
416 std::map<int, std::string>::const_iterator it
417 = group_index.find(i);
418 if (it != group_index.end())
420 if (!what[i].str().empty())
421 vars[it->second] = what[i];
425 //prepare replacement string
426 std::string rvalue = sub_vars(vars);
427 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
428 what.str(0).c_str(), rvalue.c_str());
429 out.append(start, what[0].first);
431 start = what[0].second; //move search forward
433 //if we had a match cat the last part
434 if (start != txt.begin())
435 out.append(start, end);
439 void yf::HttpRewrite::Replace::parse_groups()
443 const std::string & str = regex;
445 yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
446 for (size_t i = 0; i < str.size(); ++i)
449 if (!esc && str[i] == '\\')
454 if (!esc && str[i] == '(') //group starts
457 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
460 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
462 if (gnum > 0) gnum--;
468 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
470 if (i+1 < str.size() && str[i+1] == '<') //named
475 while (++i < str.size())
477 if (str[i] == '>') { term = true; break; }
478 if (!isalnum(str[i]))
479 throw mp::filter::FilterException
480 ("Only alphanumeric chars allowed, found "
484 + boost::lexical_cast<std::string>(i));
488 throw mp::filter::FilterException
489 ("Unterminated group name '" + gname
490 + " in '" + str +"'");
491 group_index[gnum] = gname;
492 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
493 gname.c_str(), gnum);
502 std::string yf::HttpRewrite::Replace::sub_vars (
503 const std::map<std::string, std::string> & vars) const
507 const std::string & in = recipe;
508 for (size_t i = 0; i < in.size(); ++i)
510 if (!esc && in[i] == '\\')
515 if (!esc && in[i] == '$') //var
517 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
522 while (++i < in.size())
524 if (in[i] == '}') { term = true; break; }
527 if (!term) throw mp::filter::FilterException
528 ("Unterminated var ref in '"+in+"' at "
529 + boost::lexical_cast<std::string>(i));
530 std::map<std::string, std::string>::const_iterator it
532 if (it != vars.end())
539 throw mp::filter::FilterException
540 ("Malformed or trimmed var ref in '"
541 +in+"' at "+boost::lexical_cast<std::string>(i));
552 yf::HttpRewrite::Phase::Phase() : m_verbose(0)
556 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
558 static const char *names[2] = { "verbose", 0 };
559 std::string values[1];
561 mp::xml::parse_attr(ptr, names, values);
563 phase.m_verbose = atoi(values[0].c_str());
565 std::map<std::string, RulePtr > rules;
566 for (ptr = ptr->children; ptr; ptr = ptr->next)
568 if (ptr->type != XML_ELEMENT_NODE)
570 else if (!strcmp((const char *) ptr->name, "rule"))
572 static const char *names[2] = { "name", 0 };
573 std::string values[1];
574 values[0] = "default";
575 mp::xml::parse_attr(ptr, names, values);
577 RulePtr rule(new Rule);
578 for (xmlNode *p = ptr->children; p; p = p->next)
580 if (p->type != XML_ELEMENT_NODE)
582 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 replace.regex = 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 replace.regex.c_str(), replace.recipe.c_str());
600 replace.parse_groups();
601 if (!replace.regex.empty())
602 rule->replace_list.push_back(replace);
605 throw mp::filter::FilterException
607 + std::string((const char *) p->name)
608 + " in http_rewrite filter");
610 rules[values[0]] = rule;
612 else if (!strcmp((const char *) ptr->name, "within"))
614 static const char *names[6] =
615 { "header", "attr", "tag", "rule", "reqline", 0 };
616 std::string values[5];
617 mp::xml::parse_attr(ptr, names, values);
619 w.header = values[0];
622 std::map<std::string,RulePtr>::const_iterator it =
623 rules.find(values[3]);
624 if (it == rules.end())
625 throw mp::filter::FilterException
626 ("Reference to non-existing rule '" + values[3] +
627 "' in http_rewrite filter");
629 w.reqline = values[4] == "1";
630 phase.within_list.push_back(w);
634 throw mp::filter::FilterException
636 + std::string((const char *) ptr->name)
637 + " in http_rewrite filter");
642 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
645 for (ptr = ptr->children; ptr; ptr = ptr->next)
647 if (ptr->type != XML_ELEMENT_NODE)
649 else if (!strcmp((const char *) ptr->name, "request"))
651 configure_phase(ptr, *req_phase);
653 else if (!strcmp((const char *) ptr->name, "response"))
655 configure_phase(ptr, *res_phase);
659 throw mp::filter::FilterException
661 + std::string((const char *) ptr->name)
662 + " in http_rewrite1 filter");
667 static mp::filter::Base* filter_creator()
669 return new mp::filter::HttpRewrite;
673 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
684 * c-file-style: "Stroustrup"
685 * indent-tabs-mode: nil
687 * vim: shiftwidth=4 tabstop=8 expandtab