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;
57 std::map<std::string, std::string> &vars,
58 std::string &txt, bool anchor);
60 class HttpRewrite::Within {
68 bool exec(std::map<std::string, std::string> &vars,
69 std::string &txt, bool anchor) const;
72 class HttpRewrite::Content {
75 boost::regex content_re;
76 std::list<Within> within_list;
77 void configure(const xmlNode *ptr,
78 std::map<std::string, RulePtr > &rules);
79 void quoted_literal(std::string &content,
80 std::map<std::string, std::string> &vars) const;
81 void parse(int verbose, std::string &content,
82 std::map<std::string, std::string> & vars) const;
84 class HttpRewrite::Phase {
88 std::list<Content> content_list;
89 void rewrite_reqline(mp::odr & o, Z_HTTP_Request *hreq,
90 std::map<std::string, std::string> & vars) const;
91 void rewrite_headers(mp::odr & o, Z_HTTP_Header *headers,
92 std::map<std::string, std::string> & vars) const;
93 void rewrite_body(mp::odr & o,
94 const char *content_type,
95 char **content_buf, int *content_len,
96 std::map<std::string, std::string> & vars) const;
98 class HttpRewrite::Event : public HTMLParserEvent {
99 void openTagStart(const char *tag, int tag_len);
100 void anyTagEnd(const char *tag, int tag_len, int close_it);
101 void attribute(const char *tag, int tag_len,
102 const char *attr, int attr_len,
103 const char *value, int val_len,
105 void closeTag(const char *tag, int tag_len);
106 void text(const char *value, int len);
107 const Content *m_content;
109 std::stack<std::list<Within>::const_iterator> s_within;
110 std::map<std::string, std::string> &m_vars;
112 Event(const Content *p, std::map<std::string, std::string> &vars);
114 const char *result();
119 yf::HttpRewrite::HttpRewrite() :
120 req_phase(new Phase), res_phase(new Phase)
124 yf::HttpRewrite::~HttpRewrite()
128 void yf::HttpRewrite::process(mp::Package & package) const
130 yaz_log(YLOG_LOG, "HttpRewrite begins....");
131 Z_GDU *gdu = package.request().get();
132 //map of request/response vars
133 std::map<std::string, std::string> vars;
134 //we have an http req
135 if (gdu && gdu->which == Z_GDU_HTTP_Request)
137 Z_HTTP_Request *hreq = gdu->u.HTTP_Request;
139 req_phase->rewrite_reqline(o, hreq, vars);
140 yaz_log(YLOG_LOG, ">> Request headers");
141 req_phase->rewrite_headers(o, hreq->headers, vars);
142 req_phase->rewrite_body(o,
143 z_HTTP_header_lookup(hreq->headers,
145 &hreq->content_buf, &hreq->content_len,
147 package.request() = gdu;
150 gdu = package.response().get();
151 if (gdu && gdu->which == Z_GDU_HTTP_Response)
153 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
154 yaz_log(YLOG_LOG, "Response code %d", hres->code);
156 yaz_log(YLOG_LOG, "<< Respose headers");
157 res_phase->rewrite_headers(o, hres->headers, vars);
158 res_phase->rewrite_body(o,
159 z_HTTP_header_lookup(hres->headers,
161 &hres->content_buf, &hres->content_len,
163 package.response() = gdu;
167 void yf::HttpRewrite::Phase::rewrite_reqline (mp::odr & o,
168 Z_HTTP_Request *hreq,
169 std::map<std::string, std::string> & vars) const
171 //rewrite the request line
173 if (strstr(hreq->path, "http://") == hreq->path)
175 yaz_log(YLOG_LOG, "Path in the method line is absolute, "
176 "possibly a proxy request");
181 //TODO what about proto
182 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
191 std::list<Content>::const_iterator cit = content_list.begin();
192 for (; cit != content_list.end(); cit++)
193 if (cit->type == "headers")
196 if (cit == content_list.end())
199 std::list<Within>::const_iterator it = cit->within_list.begin();
200 for (; it != cit->within_list.end(); it++)
203 yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
204 if (it->exec(vars, path, true))
206 yaz_log(YLOG_LOG, "Rewritten request URL is %s", path.c_str());
207 hreq->path = odr_strdup(o, path.c_str());
212 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
213 Z_HTTP_Header *headers,
214 std::map<std::string, std::string> & vars) const
216 std::list<Content>::const_iterator cit = content_list.begin();
217 for (; cit != content_list.end(); cit++)
218 if (cit->type == "headers")
221 if (cit == content_list.end())
224 for (Z_HTTP_Header *header = headers; header; header = header->next)
226 std::list<Within>::const_iterator it = cit->within_list.begin();
227 for (; it != cit->within_list.end(); it++)
229 if (it->header.length() > 0 &&
230 yaz_strcasecmp(it->header.c_str(), header->name) == 0)
232 std::string sheader(header->name);
234 sheader += header->value;
236 if (it->exec(vars, sheader, true))
238 size_t pos = sheader.find(": ");
239 if (pos == std::string::npos)
241 yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
244 header->name = odr_strdup(
245 o, sheader.substr(0, pos).c_str());
246 header->value = odr_strdup(
247 o, sheader.substr(pos + 2, std::string::npos).c_str());
254 void yf::HttpRewrite::Phase::rewrite_body(
256 const char *content_type,
259 std::map<std::string, std::string> & vars) const
261 if (*content_len == 0)
263 std::list<Content>::const_iterator cit = content_list.begin();
264 for (; cit != content_list.end(); cit++)
266 yaz_log(YLOG_LOG, "rewrite_body: content_type=%s type=%s",
267 content_type, cit->type.c_str());
268 if (cit->type != "headers"
269 && regex_match(content_type, cit->content_re))
272 if (cit == content_list.end())
276 for (i = 0; i < *content_len; i++)
277 if ((*content_buf)[i] == 0)
278 return; // binary content. skip
280 std::string content(*content_buf, *content_len);
281 cit->parse(m_verbose, content, vars);
282 *content_buf = odr_strdup(o, content.c_str());
283 *content_len = strlen(*content_buf);
286 yf::HttpRewrite::Event::Event(const Content *p,
287 std::map<std::string, std::string> & vars
288 ) : m_content(p), m_vars(vars)
293 yf::HttpRewrite::Event::~Event()
298 const char *yf::HttpRewrite::Event::result()
300 return wrbuf_cstr(m_w);
303 void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
305 wrbuf_putc(m_w, '<');
306 wrbuf_write(m_w, tag, tag_len);
308 std::string t(tag, tag_len);
309 std::list<Within>::const_iterator it = m_content->within_list.begin();
310 for (; it != m_content->within_list.end(); it++)
312 if (it->tag.length() > 0 && yaz_strcasecmp(it->tag.c_str(),
315 std::vector<std::string> attr;
316 boost::split(attr, it->attr, boost::is_any_of(","));
318 for (i = 0; i < attr.size(); i++)
320 if (attr[i].compare("#text") == 0)
330 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
335 if (!s_within.empty())
337 std::list<Within>::const_iterator it = s_within.top();
338 std::string t(tag, tag_len);
339 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
344 wrbuf_putc(m_w, '/');
345 wrbuf_putc(m_w, '>');
348 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
349 const char *attr, int attr_len,
350 const char *value, int val_len,
353 std::list<Within>::const_iterator it = m_content->within_list.begin();
356 for (; it != m_content->within_list.end(); it++)
358 std::string t(tag, tag_len);
359 if (it->tag.length() == 0 ||
360 yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
362 std::string a(attr, attr_len);
363 std::vector<std::string> attr;
364 boost::split(attr, it->attr, boost::is_any_of(","));
366 for (i = 0; i < attr.size(); i++)
368 if (attr[i].compare("#text") &&
369 yaz_strcasecmp(attr[i].c_str(), a.c_str()) == 0)
377 wrbuf_putc(m_w, ' ');
378 wrbuf_write(m_w, attr, attr_len);
381 wrbuf_puts(m_w, "=");
382 wrbuf_puts(m_w, sep);
387 std::string s(value, val_len);
388 it->exec(m_vars, s, true);
389 wrbuf_puts(m_w, s.c_str());
392 wrbuf_write(m_w, value, val_len);
393 wrbuf_puts(m_w, sep);
397 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
399 if (!s_within.empty())
401 std::list<Within>::const_iterator it = s_within.top();
402 std::string t(tag, tag_len);
403 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
406 wrbuf_puts(m_w, "</");
407 wrbuf_write(m_w, tag, tag_len);
410 void yf::HttpRewrite::Event::text(const char *value, int len)
412 std::list<Within>::const_iterator it = m_content->within_list.end();
413 if (!s_within.empty())
415 if (it != m_content->within_list.end())
417 std::string s(value, len);
418 it->exec(m_vars, s, false);
419 wrbuf_puts(m_w, s.c_str());
422 wrbuf_write(m_w, value, len);
425 static bool embed_quoted_literal(
426 std::string &content,
427 std::map<std::string, std::string> &vars,
428 mp::filter::HttpRewrite::RulePtr ruleptr,
431 bool replace = false;
433 const char *cp = content.c_str();
434 const char *cp0 = cp;
437 if (html_context && !strncmp(cp, """, 6))
440 res.append(cp0, cp - cp0);
444 if (!strncmp(cp, """, 6))
452 std::string s(cp0, cp - cp0);
453 if (ruleptr->test_patterns(vars, s, true))
458 else if (*cp == '"' || *cp == '\'')
462 res.append(cp0, cp - cp0);
466 if (cp[-1] != '\\' && *cp == m)
474 std::string s(cp0, cp - cp0);
475 if (ruleptr->test_patterns(vars, s, true))
480 else if (*cp == '/' && cp[1] == '/')
482 while (cp[1] && cp[1] != '\n')
487 res.append(cp0, cp - cp0);
492 bool yf::HttpRewrite::Within::exec(
493 std::map<std::string, std::string> & vars,
494 std::string & txt, bool anchor) const
496 if (type == "quoted-literal")
498 return embed_quoted_literal(txt, vars, rule, true);
502 return rule->test_patterns(vars, txt, anchor);
506 bool yf::HttpRewrite::Rule::test_patterns(
507 std::map<std::string, std::string> & vars,
508 std::string & txt, bool anchor)
510 bool replaces = false;
513 std::string::const_iterator start, end;
518 std::list<Replace>::iterator bit = replace_list.end();
520 std::string::const_iterator best_pos = txt.end();
521 std::list<Replace>::iterator it = replace_list.begin();
522 for (; it != replace_list.end(); it++)
524 if (it->start_anchor && !first)
526 if (regex_search(start, end, it->what, it->re))
528 if (it->what[0].first < best_pos)
530 best_pos = it->what[0].first;
535 if (bit == replace_list.end())
541 for (i = 1; i < bit->what.size(); ++i)
543 //check if the group is named
544 std::map<int, std::string>::const_iterator git
545 = bit->group_index.find(i);
546 if (git != bit->group_index.end())
548 vars[git->second] = bit->what[i];
552 //prepare replacement string
553 std::string rvalue = bit->sub_vars(vars);
554 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
555 bit->what.str(0).c_str(), rvalue.c_str());
556 out.append(start, bit->what[0].first);
558 start = bit->what[0].second; //move search forward
560 out.append(start, end);
565 void yf::HttpRewrite::Replace::parse_groups(std::string pattern)
569 const std::string &str = pattern;
571 start_anchor = str[0] == '^';
572 yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
573 for (size_t i = 0; i < str.size(); ++i)
576 if (!esc && str[i] == '\\')
581 if (!esc && str[i] == '(') //group starts
584 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
587 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
589 if (gnum > 0) gnum--;
595 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
597 if (i+1 < str.size() && str[i+1] == '<') //named
602 while (++i < str.size())
604 if (str[i] == '>') { term = true; break; }
605 if (!isalnum(str[i]))
606 throw mp::filter::FilterException
607 ("Only alphanumeric chars allowed, found "
611 + boost::lexical_cast<std::string>(i));
615 throw mp::filter::FilterException
616 ("Unterminated group name '" + gname
617 + " in '" + str +"'");
618 group_index[gnum] = gname;
619 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
620 gname.c_str(), gnum);
629 std::string yf::HttpRewrite::Replace::sub_vars(
630 const std::map<std::string, std::string> & vars) const
634 const std::string & in = recipe;
635 for (size_t i = 0; i < in.size(); ++i)
637 if (!esc && in[i] == '\\')
642 if (!esc && in[i] == '$') //var
644 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
649 while (++i < in.size())
651 if (in[i] == '}') { term = true; break; }
654 if (!term) throw mp::filter::FilterException
655 ("Unterminated var ref in '"+in+"' at "
656 + boost::lexical_cast<std::string>(i));
657 std::map<std::string, std::string>::const_iterator it
659 if (it != vars.end())
666 throw mp::filter::FilterException
667 ("Malformed or trimmed var ref in '"
668 +in+"' at "+boost::lexical_cast<std::string>(i));
679 yf::HttpRewrite::Phase::Phase() : m_verbose(0)
683 void yf::HttpRewrite::Content::parse(
685 std::string &content,
686 std::map<std::string, std::string> &vars) const
691 Event ev(this, vars);
693 parser.set_verbose(verbose);
695 parser.parse(ev, content.c_str());
696 content = ev.result();
698 if (type == "quoted-literal")
700 quoted_literal(content, vars);
704 void yf::HttpRewrite::Content::quoted_literal(
705 std::string &content,
706 std::map<std::string, std::string> &vars) const
708 std::list<Within>::const_iterator it = within_list.begin();
709 if (it != within_list.end())
710 embed_quoted_literal(content, vars, it->rule, false);
713 void yf::HttpRewrite::Content::configure(
714 const xmlNode *ptr, std::map<std::string, RulePtr > &rules)
716 for (; ptr; ptr = ptr->next)
718 if (ptr->type != XML_ELEMENT_NODE)
720 if (!strcmp((const char *) ptr->name, "within"))
722 static const char *names[7] =
723 { "header", "attr", "tag", "rule", "reqline", "type", 0 };
724 std::string values[6];
725 mp::xml::parse_attr(ptr, names, values);
727 w.header = values[0];
730 std::map<std::string,RulePtr>::const_iterator it =
731 rules.find(values[3]);
732 if (it == rules.end())
733 throw mp::filter::FilterException
734 ("Reference to non-existing rule '" + values[3] +
735 "' in http_rewrite filter");
737 w.reqline = values[4] == "1";
739 if (w.type.empty() || w.type == "quoted-literal")
742 throw mp::filter::FilterException
743 ("within type must be quoted-literal or none in "
744 " in http_rewrite filter");
745 within_list.push_back(w);
750 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
752 static const char *names[2] = { "verbose", 0 };
753 std::string values[1];
755 mp::xml::parse_attr(ptr, names, values);
757 phase.m_verbose = atoi(values[0].c_str());
759 std::map<std::string, RulePtr > rules;
760 for (ptr = ptr->children; ptr; ptr = ptr->next)
762 if (ptr->type != XML_ELEMENT_NODE)
764 else if (!strcmp((const char *) ptr->name, "rule"))
766 static const char *names[2] = { "name", 0 };
767 std::string values[1];
768 values[0] = "default";
769 mp::xml::parse_attr(ptr, names, values);
771 RulePtr rule(new Rule);
772 for (xmlNode *p = ptr->children; p; p = p->next)
774 if (p->type != XML_ELEMENT_NODE)
776 if (!strcmp((const char *) p->name, "rewrite"))
780 const struct _xmlAttr *attr;
781 for (attr = p->properties; attr; attr = attr->next)
783 if (!strcmp((const char *) attr->name, "from"))
784 from = mp::xml::get_text(attr->children);
785 else if (!strcmp((const char *) attr->name, "to"))
786 replace.recipe = mp::xml::get_text(attr->children);
788 throw mp::filter::FilterException
790 + std::string((const char *) attr->name)
791 + " in rewrite section of http_rewrite");
793 yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
794 from.c_str(), replace.recipe.c_str());
797 replace.parse_groups(from);
798 rule->replace_list.push_back(replace);
802 throw mp::filter::FilterException
804 + std::string((const char *) p->name)
805 + " in http_rewrite filter");
807 rules[values[0]] = rule;
809 else if (!strcmp((const char *) ptr->name, "content"))
811 static const char *names[3] =
812 { "type", "mime", 0 };
813 std::string values[2];
814 mp::xml::parse_attr(ptr, names, values);
815 if (values[0].empty())
817 throw mp::filter::FilterException
818 ("Missing attribute, type for for element "
819 + std::string((const char *) ptr->name)
820 + " in http_rewrite filter");
825 // if (!values[1].empty())
826 c.content_re = values[1];
827 c.configure(ptr->children, rules);
828 phase.content_list.push_back(c);
832 throw mp::filter::FilterException
834 + std::string((const char *) ptr->name)
835 + " in http_rewrite filter");
840 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
843 for (ptr = ptr->children; ptr; ptr = ptr->next)
845 if (ptr->type != XML_ELEMENT_NODE)
847 else if (!strcmp((const char *) ptr->name, "request"))
849 configure_phase(ptr, *req_phase);
851 else if (!strcmp((const char *) ptr->name, "response"))
853 configure_phase(ptr, *res_phase);
857 throw mp::filter::FilterException
859 + std::string((const char *) ptr->name)
860 + " in http_rewrite1 filter");
865 static mp::filter::Base* filter_creator()
867 return new mp::filter::HttpRewrite;
871 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
882 * c-file-style: "Stroustrup"
883 * indent-tabs-mode: nil
885 * vim: shiftwidth=4 tabstop=8 expandtab