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 {
47 std::map<int, std::string> group_index;
49 const std::map<std::string, std::string> & vars) const;
50 void parse_groups(std::string pattern);
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);
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,
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
160 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
170 std::list<Within>::const_iterator it = within_list.begin();
171 for (; it != within_list.end(); it++)
174 RulePtr rule = it->rule;
175 yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
176 std::string npath = rule->test_patterns(vars, path);
179 yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
180 hreq->path = odr_strdup(o, npath.c_str());
185 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
186 Z_HTTP_Header *headers,
187 std::map<std::string, std::string> & vars) const
189 for (Z_HTTP_Header *header = headers; header; header = header->next)
191 std::list<Within>::const_iterator it = within_list.begin();
192 for (; it != within_list.end(); it++)
194 if (it->header.length() > 0 &&
195 yaz_strcasecmp(it->header.c_str(), header->name) == 0)
197 std::string sheader(header->name);
199 sheader += header->value;
201 RulePtr rule = it->rule;
202 std::string out = rule->test_patterns(vars, sheader);
205 size_t pos = out.find(": ");
206 if (pos == std::string::npos)
208 yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
211 header->name = odr_strdup(o, out.substr(0, pos).c_str());
212 header->value = odr_strdup(o,
214 std::string::npos).c_str());
221 void yf::HttpRewrite::Phase::rewrite_body(mp::odr & o,
224 std::map<std::string, std::string> & vars) const
229 for (i = 0; i < *content_len; i++)
230 if ((*content_buf)[i] == 0)
231 return; // binary content. skip
234 Event ev(this, vars);
236 parser.set_verbose(m_verbose);
238 std::string buf(*content_buf, *content_len);
240 parser.parse(ev, buf.c_str());
241 const char *res = ev.result();
242 *content_buf = odr_strdup(o, res);
243 *content_len = strlen(res);
247 yf::HttpRewrite::Event::Event(const Phase *p,
248 std::map<std::string, std::string> & vars
249 ) : m_phase(p), m_vars(vars)
254 yf::HttpRewrite::Event::~Event()
259 const char *yf::HttpRewrite::Event::result()
261 return wrbuf_cstr(m_w);
264 void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
266 wrbuf_putc(m_w, '<');
267 wrbuf_write(m_w, tag, tag_len);
269 std::string t(tag, tag_len);
270 std::list<Within>::const_iterator it = m_phase->within_list.begin();
271 for (; it != m_phase->within_list.end(); it++)
273 if (it->tag.length() > 0 && yaz_strcasecmp(it->tag.c_str(),
276 std::vector<std::string> attr;
277 boost::split(attr, it->attr, boost::is_any_of(","));
279 for (i = 0; i < attr.size(); i++)
281 if (attr[i].compare("#text") == 0)
291 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
296 if (!s_within.empty())
298 std::list<Within>::const_iterator it = s_within.top();
299 std::string t(tag, tag_len);
300 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
305 wrbuf_putc(m_w, '/');
306 wrbuf_putc(m_w, '>');
309 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
310 const char *attr, int attr_len,
311 const char *value, int val_len,
314 std::list<Within>::const_iterator it = m_phase->within_list.begin();
317 for (; it != m_phase->within_list.end(); it++)
319 std::string t(tag, tag_len);
320 if (it->tag.length() == 0 ||
321 yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
323 std::string a(attr, attr_len);
324 std::vector<std::string> attr;
325 boost::split(attr, it->attr, boost::is_any_of(","));
327 for (i = 0; i < attr.size(); i++)
329 if (attr[i].compare("#text") &&
330 yaz_strcasecmp(attr[i].c_str(), a.c_str()) == 0)
338 wrbuf_putc(m_w, ' ');
339 wrbuf_write(m_w, attr, attr_len);
342 wrbuf_puts(m_w, "=");
343 wrbuf_puts(m_w, sep);
348 std::string input(value, val_len);
349 output = it->rule->test_patterns(m_vars, input);
352 wrbuf_write(m_w, value, val_len);
354 wrbuf_puts(m_w, output.c_str());
355 wrbuf_puts(m_w, sep);
359 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
361 if (!s_within.empty())
363 std::list<Within>::const_iterator it = s_within.top();
364 std::string t(tag, tag_len);
365 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
368 wrbuf_puts(m_w, "</");
369 wrbuf_write(m_w, tag, tag_len);
372 void yf::HttpRewrite::Event::text(const char *value, int len)
374 std::list<Within>::const_iterator it = m_phase->within_list.end();
375 if (!s_within.empty())
378 if (it != m_phase->within_list.end())
380 std::string input(value, len);
381 output = it->rule->test_patterns(m_vars, input);
384 wrbuf_write(m_w, value, len);
386 wrbuf_puts(m_w, output.c_str());
389 const std::string yf::HttpRewrite::Rule::test_patterns(
390 std::map<std::string, std::string> & vars,
391 const std::string & txt)
395 std::string::const_iterator start, end;
400 std::list<Replace>::iterator bit = replace_list.end();
402 std::string::const_iterator best_pos = txt.end();
403 std::list<Replace>::iterator it = replace_list.begin();
404 for (; it != replace_list.end(); it++)
406 if (it->start_anchor && !first)
408 if (regex_search(start, end, it->what, it->re))
410 if (it->what[0].first < best_pos)
412 best_pos = it->what[0].first;
417 if (bit == replace_list.end())
422 for (i = 1; i < bit->what.size(); ++i)
424 //check if the group is named
425 std::map<int, std::string>::const_iterator git
426 = bit->group_index.find(i);
427 if (git != bit->group_index.end())
429 vars[git->second] = bit->what[i];
433 //prepare replacement string
434 std::string rvalue = bit->sub_vars(vars);
435 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
436 bit->what.str(0).c_str(), rvalue.c_str());
437 out.append(start, bit->what[0].first);
439 start = bit->what[0].second; //move search forward
441 if (start != txt.begin())
442 out.append(start, end);
446 void yf::HttpRewrite::Replace::parse_groups(std::string pattern)
450 const std::string &str = pattern;
452 start_anchor = str[0] == '^';
453 yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
454 for (size_t i = 0; i < str.size(); ++i)
457 if (!esc && str[i] == '\\')
462 if (!esc && str[i] == '(') //group starts
465 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
468 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
470 if (gnum > 0) gnum--;
476 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
478 if (i+1 < str.size() && str[i+1] == '<') //named
483 while (++i < str.size())
485 if (str[i] == '>') { term = true; break; }
486 if (!isalnum(str[i]))
487 throw mp::filter::FilterException
488 ("Only alphanumeric chars allowed, found "
492 + boost::lexical_cast<std::string>(i));
496 throw mp::filter::FilterException
497 ("Unterminated group name '" + gname
498 + " in '" + str +"'");
499 group_index[gnum] = gname;
500 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
501 gname.c_str(), gnum);
510 std::string yf::HttpRewrite::Replace::sub_vars(
511 const std::map<std::string, std::string> & vars) const
515 const std::string & in = recipe;
516 for (size_t i = 0; i < in.size(); ++i)
518 if (!esc && in[i] == '\\')
523 if (!esc && in[i] == '$') //var
525 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
530 while (++i < in.size())
532 if (in[i] == '}') { term = true; break; }
535 if (!term) throw mp::filter::FilterException
536 ("Unterminated var ref in '"+in+"' at "
537 + boost::lexical_cast<std::string>(i));
538 std::map<std::string, std::string>::const_iterator it
540 if (it != vars.end())
547 throw mp::filter::FilterException
548 ("Malformed or trimmed var ref in '"
549 +in+"' at "+boost::lexical_cast<std::string>(i));
560 yf::HttpRewrite::Phase::Phase() : m_verbose(0)
564 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
566 static const char *names[2] = { "verbose", 0 };
567 std::string values[1];
569 mp::xml::parse_attr(ptr, names, values);
571 phase.m_verbose = atoi(values[0].c_str());
573 std::map<std::string, RulePtr > rules;
574 for (ptr = ptr->children; ptr; ptr = ptr->next)
576 if (ptr->type != XML_ELEMENT_NODE)
578 else if (!strcmp((const char *) ptr->name, "rule"))
580 static const char *names[2] = { "name", 0 };
581 std::string values[1];
582 values[0] = "default";
583 mp::xml::parse_attr(ptr, names, values);
585 RulePtr rule(new Rule);
586 for (xmlNode *p = ptr->children; p; p = p->next)
588 if (p->type != XML_ELEMENT_NODE)
590 if (!strcmp((const char *) p->name, "rewrite"))
594 const struct _xmlAttr *attr;
595 for (attr = p->properties; attr; attr = attr->next)
597 if (!strcmp((const char *) attr->name, "from"))
598 from = mp::xml::get_text(attr->children);
599 else if (!strcmp((const char *) attr->name, "to"))
600 replace.recipe = mp::xml::get_text(attr->children);
602 throw mp::filter::FilterException
604 + std::string((const char *) attr->name)
605 + " in rewrite section of http_rewrite");
607 yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
608 from.c_str(), replace.recipe.c_str());
611 replace.parse_groups(from);
612 rule->replace_list.push_back(replace);
616 throw mp::filter::FilterException
618 + std::string((const char *) p->name)
619 + " in http_rewrite filter");
621 rules[values[0]] = rule;
623 else if (!strcmp((const char *) ptr->name, "within"))
625 static const char *names[6] =
626 { "header", "attr", "tag", "rule", "reqline", 0 };
627 std::string values[5];
628 mp::xml::parse_attr(ptr, names, values);
630 w.header = values[0];
633 std::map<std::string,RulePtr>::const_iterator it =
634 rules.find(values[3]);
635 if (it == rules.end())
636 throw mp::filter::FilterException
637 ("Reference to non-existing rule '" + values[3] +
638 "' in http_rewrite filter");
640 w.reqline = values[4] == "1";
641 phase.within_list.push_back(w);
645 throw mp::filter::FilterException
647 + std::string((const char *) ptr->name)
648 + " in http_rewrite filter");
653 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
656 for (ptr = ptr->children; ptr; ptr = ptr->next)
658 if (ptr->type != XML_ELEMENT_NODE)
660 else if (!strcmp((const char *) ptr->name, "request"))
662 configure_phase(ptr, *req_phase);
664 else if (!strcmp((const char *) ptr->name, "response"))
666 configure_phase(ptr, *res_phase);
670 throw mp::filter::FilterException
672 + std::string((const char *) ptr->name)
673 + " in http_rewrite1 filter");
678 static mp::filter::Base* filter_creator()
680 return new mp::filter::HttpRewrite;
684 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
695 * c-file-style: "Stroustrup"
696 * indent-tabs-mode: nil
698 * vim: shiftwidth=4 tabstop=8 expandtab