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 {
46 std::map<int, std::string> group_index;
48 const std::map<std::string, std::string> & vars) const;
49 void parse_groups(std::string pattern);
52 class HttpRewrite::Rule {
54 std::list<Replace> replace_list;
55 const std::string test_patterns(
56 std::map<std::string, std::string> & vars,
57 const std::string & txt);
59 class HttpRewrite::Within {
68 class HttpRewrite::Phase {
71 std::list<Within> within_list;
73 void rewrite_reqline(mp::odr & o, Z_HTTP_Request *hreq,
74 std::map<std::string, std::string> & vars) const;
75 void rewrite_headers(mp::odr & o, Z_HTTP_Header *headers,
76 std::map<std::string, std::string> & vars) const;
77 void rewrite_body(mp::odr & o,
78 char **content_buf, int *content_len,
79 std::map<std::string, std::string> & vars) const;
81 class HttpRewrite::Event : public HTMLParserEvent {
82 void openTagStart(const char *tag, int tag_len);
83 void anyTagEnd(const char *tag, int tag_len, int close_it);
84 void attribute(const char *tag, int tag_len,
85 const char *attr, int attr_len,
86 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::stack<std::list<Within>::const_iterator> s_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
159 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
169 std::list<Within>::const_iterator it = within_list.begin();
170 for (; it != within_list.end(); it++)
173 RulePtr rule = it->rule;
174 yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
175 std::string npath = rule->test_patterns(vars, path);
178 yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
179 hreq->path = odr_strdup(o, npath.c_str());
184 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
185 Z_HTTP_Header *headers,
186 std::map<std::string, std::string> & vars) const
188 for (Z_HTTP_Header *header = headers; header; header = header->next)
190 std::list<Within>::const_iterator it = within_list.begin();
191 for (; it != within_list.end(); it++)
193 if (it->header.length() > 0 &&
194 yaz_strcasecmp(it->header.c_str(), header->name) == 0)
196 std::string sheader(header->name);
198 sheader += header->value;
200 RulePtr rule = it->rule;
201 std::string out = rule->test_patterns(vars, sheader);
204 size_t pos = out.find(": ");
205 if (pos == std::string::npos)
207 yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
210 header->name = odr_strdup(o, out.substr(0, pos).c_str());
211 header->value = odr_strdup(o,
213 std::string::npos).c_str());
220 void yf::HttpRewrite::Phase::rewrite_body(mp::odr & o,
223 std::map<std::string, std::string> & vars) const
228 for (i = 0; i < *content_len; i++)
229 if ((*content_buf)[i] == 0)
230 return; // binary content. skip
233 Event ev(this, vars);
235 parser.set_verbose(m_verbose);
237 std::string buf(*content_buf, *content_len);
239 parser.parse(ev, buf.c_str());
240 const char *res = ev.result();
241 *content_buf = odr_strdup(o, res);
242 *content_len = strlen(res);
246 yf::HttpRewrite::Event::Event(const Phase *p,
247 std::map<std::string, std::string> & vars
248 ) : m_phase(p), m_vars(vars)
253 yf::HttpRewrite::Event::~Event()
258 const char *yf::HttpRewrite::Event::result()
260 return wrbuf_cstr(m_w);
263 void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
265 wrbuf_putc(m_w, '<');
266 wrbuf_write(m_w, tag, tag_len);
268 std::string t(tag, tag_len);
269 std::list<Within>::const_iterator it = m_phase->within_list.begin();
270 for (; it != m_phase->within_list.end(); it++)
272 if (it->tag.length() > 0 && yaz_strcasecmp(it->tag.c_str(),
275 std::vector<std::string> attr;
276 boost::split(attr, it->attr, boost::is_any_of(","));
278 for (i = 0; i < attr.size(); i++)
280 if (attr[i].compare("#text") == 0)
290 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
295 if (!s_within.empty())
297 std::list<Within>::const_iterator it = s_within.top();
298 std::string t(tag, tag_len);
299 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
304 wrbuf_putc(m_w, '/');
305 wrbuf_putc(m_w, '>');
308 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
309 const char *attr, int attr_len,
310 const char *value, int val_len,
313 std::list<Within>::const_iterator it = m_phase->within_list.begin();
316 for (; it != m_phase->within_list.end(); it++)
318 std::string t(tag, tag_len);
319 if (it->tag.length() == 0 ||
320 yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
322 std::string a(attr, attr_len);
323 std::vector<std::string> attr;
324 boost::split(attr, it->attr, boost::is_any_of(","));
326 for (i = 0; i < attr.size(); i++)
328 if (attr[i].compare("#text") &&
329 yaz_strcasecmp(attr[i].c_str(), a.c_str()) == 0)
337 wrbuf_putc(m_w, ' ');
338 wrbuf_write(m_w, attr, attr_len);
341 wrbuf_puts(m_w, "=");
342 wrbuf_puts(m_w, sep);
347 std::string input(value, val_len);
348 output = it->rule->test_patterns(m_vars, input);
351 wrbuf_write(m_w, value, val_len);
353 wrbuf_puts(m_w, output.c_str());
354 wrbuf_puts(m_w, sep);
358 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
360 if (!s_within.empty())
362 std::list<Within>::const_iterator it = s_within.top();
363 std::string t(tag, tag_len);
364 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
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 = m_phase->within_list.end();
374 if (!s_within.empty())
377 if (it != m_phase->within_list.end())
379 std::string input(value, len);
380 output = it->rule->test_patterns(m_vars, input);
383 wrbuf_write(m_w, value, len);
385 wrbuf_puts(m_w, output.c_str());
388 const std::string yf::HttpRewrite::Rule::test_patterns(
389 std::map<std::string, std::string> & vars,
390 const std::string & txt)
393 std::string::const_iterator start, end;
398 std::list<Replace>::iterator bit = replace_list.end();
400 std::string::const_iterator best_pos = txt.end();
401 std::list<Replace>::iterator it = replace_list.begin();
402 for (; it != replace_list.end(); it++)
404 if (regex_search(start, end, it->what, it->re))
406 if (it->what[0].first < best_pos)
408 best_pos = it->what[0].first;
413 if (bit == replace_list.end())
418 for (i = 1; i < bit->what.size(); ++i)
420 //check if the group is named
421 std::map<int, std::string>::const_iterator git
422 = bit->group_index.find(i);
423 if (git != bit->group_index.end())
425 vars[git->second] = bit->what[i];
429 //prepare replacement string
430 std::string rvalue = bit->sub_vars(vars);
431 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
432 bit->what.str(0).c_str(), rvalue.c_str());
433 out.append(start, bit->what[0].first);
435 start = bit->what[0].second; //move search forward
437 if (start != txt.begin())
438 out.append(start, end);
442 void yf::HttpRewrite::Replace::parse_groups(std::string pattern)
446 const std::string &str = pattern;
448 yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
449 for (size_t i = 0; i < str.size(); ++i)
452 if (!esc && str[i] == '\\')
457 if (!esc && str[i] == '(') //group starts
460 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
463 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
465 if (gnum > 0) gnum--;
471 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
473 if (i+1 < str.size() && str[i+1] == '<') //named
478 while (++i < str.size())
480 if (str[i] == '>') { term = true; break; }
481 if (!isalnum(str[i]))
482 throw mp::filter::FilterException
483 ("Only alphanumeric chars allowed, found "
487 + boost::lexical_cast<std::string>(i));
491 throw mp::filter::FilterException
492 ("Unterminated group name '" + gname
493 + " in '" + str +"'");
494 group_index[gnum] = gname;
495 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
496 gname.c_str(), gnum);
505 std::string yf::HttpRewrite::Replace::sub_vars(
506 const std::map<std::string, std::string> & vars) const
510 const std::string & in = recipe;
511 for (size_t i = 0; i < in.size(); ++i)
513 if (!esc && in[i] == '\\')
518 if (!esc && in[i] == '$') //var
520 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
525 while (++i < in.size())
527 if (in[i] == '}') { term = true; break; }
530 if (!term) throw mp::filter::FilterException
531 ("Unterminated var ref in '"+in+"' at "
532 + boost::lexical_cast<std::string>(i));
533 std::map<std::string, std::string>::const_iterator it
535 if (it != vars.end())
542 throw mp::filter::FilterException
543 ("Malformed or trimmed var ref in '"
544 +in+"' at "+boost::lexical_cast<std::string>(i));
555 yf::HttpRewrite::Phase::Phase() : m_verbose(0)
559 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
561 static const char *names[2] = { "verbose", 0 };
562 std::string values[1];
564 mp::xml::parse_attr(ptr, names, values);
566 phase.m_verbose = atoi(values[0].c_str());
568 std::map<std::string, RulePtr > rules;
569 for (ptr = ptr->children; ptr; ptr = ptr->next)
571 if (ptr->type != XML_ELEMENT_NODE)
573 else if (!strcmp((const char *) ptr->name, "rule"))
575 static const char *names[2] = { "name", 0 };
576 std::string values[1];
577 values[0] = "default";
578 mp::xml::parse_attr(ptr, names, values);
580 RulePtr rule(new Rule);
581 for (xmlNode *p = ptr->children; p; p = p->next)
583 if (p->type != XML_ELEMENT_NODE)
585 if (!strcmp((const char *) p->name, "rewrite"))
589 const struct _xmlAttr *attr;
590 for (attr = p->properties; attr; attr = attr->next)
592 if (!strcmp((const char *) attr->name, "from"))
593 from = mp::xml::get_text(attr->children);
594 else if (!strcmp((const char *) attr->name, "to"))
595 replace.recipe = mp::xml::get_text(attr->children);
597 throw mp::filter::FilterException
599 + std::string((const char *) attr->name)
600 + " in rewrite section of http_rewrite");
602 yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
603 from.c_str(), replace.recipe.c_str());
606 replace.parse_groups(from);
607 rule->replace_list.push_back(replace);
611 throw mp::filter::FilterException
613 + std::string((const char *) p->name)
614 + " in http_rewrite filter");
616 rules[values[0]] = rule;
618 else if (!strcmp((const char *) ptr->name, "within"))
620 static const char *names[6] =
621 { "header", "attr", "tag", "rule", "reqline", 0 };
622 std::string values[5];
623 mp::xml::parse_attr(ptr, names, values);
625 w.header = values[0];
628 std::map<std::string,RulePtr>::const_iterator it =
629 rules.find(values[3]);
630 if (it == rules.end())
631 throw mp::filter::FilterException
632 ("Reference to non-existing rule '" + values[3] +
633 "' in http_rewrite filter");
635 w.reqline = values[4] == "1";
636 phase.within_list.push_back(w);
640 throw mp::filter::FilterException
642 + std::string((const char *) ptr->name)
643 + " in http_rewrite filter");
648 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
651 for (ptr = ptr->children; ptr; ptr = ptr->next)
653 if (ptr->type != XML_ELEMENT_NODE)
655 else if (!strcmp((const char *) ptr->name, "request"))
657 configure_phase(ptr, *req_phase);
659 else if (!strcmp((const char *) ptr->name, "response"))
661 configure_phase(ptr, *res_phase);
665 throw mp::filter::FilterException
667 + std::string((const char *) ptr->name)
668 + " in http_rewrite1 filter");
673 static mp::filter::Base* filter_creator()
675 return new mp::filter::HttpRewrite;
679 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
690 * c-file-style: "Stroustrup"
691 * indent-tabs-mode: nil
693 * vim: shiftwidth=4 tabstop=8 expandtab