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 {
69 class HttpRewrite::Content {
72 boost::regex content_re;
73 std::list<Within> within_list;
74 void configure(const xmlNode *ptr,
75 std::map<std::string, RulePtr > &rules);
76 void quoted_literal(std::string &content,
77 std::map<std::string, std::string> &vars) const;
79 class HttpRewrite::Phase {
83 std::list<Content> content_list;
84 void rewrite_reqline(mp::odr & o, Z_HTTP_Request *hreq,
85 std::map<std::string, std::string> & vars) const;
86 void rewrite_headers(mp::odr & o, Z_HTTP_Header *headers,
87 std::map<std::string, std::string> & vars) const;
88 void rewrite_body(mp::odr & o,
89 const char *content_type,
90 char **content_buf, int *content_len,
91 std::map<std::string, std::string> & vars) const;
93 class HttpRewrite::Event : public HTMLParserEvent {
94 void openTagStart(const char *tag, int tag_len);
95 void anyTagEnd(const char *tag, int tag_len, int close_it);
96 void attribute(const char *tag, int tag_len,
97 const char *attr, int attr_len,
98 const char *value, int val_len,
100 void closeTag(const char *tag, int tag_len);
101 void text(const char *value, int len);
102 const Content *m_content;
104 std::stack<std::list<Within>::const_iterator> s_within;
105 std::map<std::string, std::string> &m_vars;
107 Event(const Content *p, std::map<std::string, std::string> &vars);
109 const char *result();
114 yf::HttpRewrite::HttpRewrite() :
115 req_phase(new Phase), res_phase(new Phase)
119 yf::HttpRewrite::~HttpRewrite()
123 void yf::HttpRewrite::process(mp::Package & package) const
125 yaz_log(YLOG_LOG, "HttpRewrite begins....");
126 Z_GDU *gdu = package.request().get();
127 //map of request/response vars
128 std::map<std::string, std::string> vars;
129 //we have an http req
130 if (gdu && gdu->which == Z_GDU_HTTP_Request)
132 Z_HTTP_Request *hreq = gdu->u.HTTP_Request;
134 req_phase->rewrite_reqline(o, hreq, vars);
135 yaz_log(YLOG_LOG, ">> Request headers");
136 req_phase->rewrite_headers(o, hreq->headers, vars);
137 req_phase->rewrite_body(o,
138 z_HTTP_header_lookup(hreq->headers,
140 &hreq->content_buf, &hreq->content_len,
142 package.request() = gdu;
145 gdu = package.response().get();
146 if (gdu && gdu->which == Z_GDU_HTTP_Response)
148 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
149 yaz_log(YLOG_LOG, "Response code %d", hres->code);
151 yaz_log(YLOG_LOG, "<< Respose headers");
152 res_phase->rewrite_headers(o, hres->headers, vars);
153 res_phase->rewrite_body(o,
154 z_HTTP_header_lookup(hres->headers,
156 &hres->content_buf, &hres->content_len,
158 package.response() = gdu;
162 void yf::HttpRewrite::Phase::rewrite_reqline (mp::odr & o,
163 Z_HTTP_Request *hreq,
164 std::map<std::string, std::string> & vars) const
166 //rewrite the request line
168 if (strstr(hreq->path, "http://") == hreq->path)
170 yaz_log(YLOG_LOG, "Path in the method line is absolute, "
171 "possibly a proxy request");
176 //TODO what about proto
177 const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
186 std::list<Content>::const_iterator cit = content_list.begin();
187 for (; cit != content_list.end(); cit++)
188 if (cit->type == "headers")
191 if (cit == content_list.end())
194 std::list<Within>::const_iterator it = cit->within_list.begin();
195 for (; it != cit->within_list.end(); it++)
198 yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
199 if (it->rule->test_patterns(vars, path, true))
201 yaz_log(YLOG_LOG, "Rewritten request URL is %s", path.c_str());
202 hreq->path = odr_strdup(o, path.c_str());
207 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
208 Z_HTTP_Header *headers,
209 std::map<std::string, std::string> & vars) const
211 std::list<Content>::const_iterator cit = content_list.begin();
212 for (; cit != content_list.end(); cit++)
213 if (cit->type == "headers")
216 if (cit == content_list.end())
219 for (Z_HTTP_Header *header = headers; header; header = header->next)
221 std::list<Within>::const_iterator it = cit->within_list.begin();
222 for (; it != cit->within_list.end(); it++)
224 if (it->header.length() > 0 &&
225 yaz_strcasecmp(it->header.c_str(), header->name) == 0)
227 std::string sheader(header->name);
229 sheader += header->value;
231 if (it->rule->test_patterns(vars, sheader, true))
233 size_t pos = sheader.find(": ");
234 if (pos == std::string::npos)
236 yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
239 header->name = odr_strdup(
240 o, sheader.substr(0, pos).c_str());
241 header->value = odr_strdup(
242 o, sheader.substr(pos + 2, std::string::npos).c_str());
249 void yf::HttpRewrite::Phase::rewrite_body(
251 const char *content_type,
254 std::map<std::string, std::string> & vars) const
256 std::list<Content>::const_iterator cit = content_list.begin();
257 for (; cit != content_list.end(); cit++)
259 yaz_log(YLOG_LOG, "rewrite_body: content_type=%s type=%s",
260 content_type, cit->type.c_str());
261 if (cit->type != "headers"
262 && regex_match(content_type, cit->content_re))
265 if (cit == content_list.end())
271 for (i = 0; i < *content_len; i++)
272 if ((*content_buf)[i] == 0)
273 return; // binary content. skip
275 if (cit->type == "html")
278 Event ev(&*cit, vars);
280 parser.set_verbose(m_verbose);
282 std::string buf(*content_buf, *content_len);
284 parser.parse(ev, buf.c_str());
285 const char *res = ev.result();
286 *content_buf = odr_strdup(o, res);
287 *content_len = strlen(res);
289 if (cit->type == "quoted-literal")
291 std::string content(*content_buf, *content_len);
292 cit->quoted_literal(content, vars);
293 *content_buf = odr_strdup(o, content.c_str());
294 *content_len = strlen(*content_buf);
299 yf::HttpRewrite::Event::Event(const Content *p,
300 std::map<std::string, std::string> & vars
301 ) : m_content(p), m_vars(vars)
306 yf::HttpRewrite::Event::~Event()
311 const char *yf::HttpRewrite::Event::result()
313 return wrbuf_cstr(m_w);
316 void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
318 wrbuf_putc(m_w, '<');
319 wrbuf_write(m_w, tag, tag_len);
321 std::string t(tag, tag_len);
322 std::list<Within>::const_iterator it = m_content->within_list.begin();
323 for (; it != m_content->within_list.end(); it++)
325 if (it->tag.length() > 0 && yaz_strcasecmp(it->tag.c_str(),
328 std::vector<std::string> attr;
329 boost::split(attr, it->attr, boost::is_any_of(","));
331 for (i = 0; i < attr.size(); i++)
333 if (attr[i].compare("#text") == 0)
343 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
348 if (!s_within.empty())
350 std::list<Within>::const_iterator it = s_within.top();
351 std::string t(tag, tag_len);
352 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
357 wrbuf_putc(m_w, '/');
358 wrbuf_putc(m_w, '>');
361 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
362 const char *attr, int attr_len,
363 const char *value, int val_len,
366 std::list<Within>::const_iterator it = m_content->within_list.begin();
369 for (; it != m_content->within_list.end(); it++)
371 std::string t(tag, tag_len);
372 if (it->tag.length() == 0 ||
373 yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
375 std::string a(attr, attr_len);
376 std::vector<std::string> attr;
377 boost::split(attr, it->attr, boost::is_any_of(","));
379 for (i = 0; i < attr.size(); i++)
381 if (attr[i].compare("#text") &&
382 yaz_strcasecmp(attr[i].c_str(), a.c_str()) == 0)
390 wrbuf_putc(m_w, ' ');
391 wrbuf_write(m_w, attr, attr_len);
394 wrbuf_puts(m_w, "=");
395 wrbuf_puts(m_w, sep);
400 std::string s(value, val_len);
401 it->rule->test_patterns(m_vars, s, true);
402 wrbuf_puts(m_w, s.c_str());
405 wrbuf_write(m_w, value, val_len);
406 wrbuf_puts(m_w, sep);
410 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
412 if (!s_within.empty())
414 std::list<Within>::const_iterator it = s_within.top();
415 std::string t(tag, tag_len);
416 if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
419 wrbuf_puts(m_w, "</");
420 wrbuf_write(m_w, tag, tag_len);
423 void yf::HttpRewrite::Event::text(const char *value, int len)
425 std::list<Within>::const_iterator it = m_content->within_list.end();
426 if (!s_within.empty())
428 if (it != m_content->within_list.end())
430 std::string s(value, len);
431 it->rule->test_patterns(m_vars, s, false);
432 wrbuf_puts(m_w, s.c_str());
435 wrbuf_write(m_w, value, len);
438 bool yf::HttpRewrite::Rule::test_patterns(
439 std::map<std::string, std::string> & vars,
440 std::string & txt, bool anchor)
442 bool replaces = false;
445 std::string::const_iterator start, end;
450 std::list<Replace>::iterator bit = replace_list.end();
452 std::string::const_iterator best_pos = txt.end();
453 std::list<Replace>::iterator it = replace_list.begin();
454 for (; it != replace_list.end(); it++)
456 if (it->start_anchor && !first)
458 if (regex_search(start, end, it->what, it->re))
460 if (it->what[0].first < best_pos)
462 best_pos = it->what[0].first;
467 if (bit == replace_list.end())
473 for (i = 1; i < bit->what.size(); ++i)
475 //check if the group is named
476 std::map<int, std::string>::const_iterator git
477 = bit->group_index.find(i);
478 if (git != bit->group_index.end())
480 vars[git->second] = bit->what[i];
484 //prepare replacement string
485 std::string rvalue = bit->sub_vars(vars);
486 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
487 bit->what.str(0).c_str(), rvalue.c_str());
488 out.append(start, bit->what[0].first);
490 start = bit->what[0].second; //move search forward
492 out.append(start, end);
497 void yf::HttpRewrite::Replace::parse_groups(std::string pattern)
501 const std::string &str = pattern;
503 start_anchor = str[0] == '^';
504 yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
505 for (size_t i = 0; i < str.size(); ++i)
508 if (!esc && str[i] == '\\')
513 if (!esc && str[i] == '(') //group starts
516 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
519 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
521 if (gnum > 0) gnum--;
527 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
529 if (i+1 < str.size() && str[i+1] == '<') //named
534 while (++i < str.size())
536 if (str[i] == '>') { term = true; break; }
537 if (!isalnum(str[i]))
538 throw mp::filter::FilterException
539 ("Only alphanumeric chars allowed, found "
543 + boost::lexical_cast<std::string>(i));
547 throw mp::filter::FilterException
548 ("Unterminated group name '" + gname
549 + " in '" + str +"'");
550 group_index[gnum] = gname;
551 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
552 gname.c_str(), gnum);
561 std::string yf::HttpRewrite::Replace::sub_vars(
562 const std::map<std::string, std::string> & vars) const
566 const std::string & in = recipe;
567 for (size_t i = 0; i < in.size(); ++i)
569 if (!esc && in[i] == '\\')
574 if (!esc && in[i] == '$') //var
576 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
581 while (++i < in.size())
583 if (in[i] == '}') { term = true; break; }
586 if (!term) throw mp::filter::FilterException
587 ("Unterminated var ref in '"+in+"' at "
588 + boost::lexical_cast<std::string>(i));
589 std::map<std::string, std::string>::const_iterator it
591 if (it != vars.end())
598 throw mp::filter::FilterException
599 ("Malformed or trimmed var ref in '"
600 +in+"' at "+boost::lexical_cast<std::string>(i));
611 yf::HttpRewrite::Phase::Phase() : m_verbose(0)
615 void yf::HttpRewrite::Content::quoted_literal(
616 std::string &content,
617 std::map<std::string, std::string> &vars) const
620 const char *cp = content.c_str();
621 const char *cp0 = cp;
624 if (*cp == '"' || *cp == '\'')
628 res.append(cp0, cp - cp0);
632 if (cp[-1] != '\\' && *cp == m)
640 std::list<Within>::const_iterator it = within_list.begin();
641 std::string s(cp0, cp - cp0);
642 if (it != within_list.end())
643 it->rule->test_patterns(vars, s, true);
647 else if (*cp == '/' && cp[1] == '/')
649 while (cp[1] && cp[1] != '\n')
654 res.append(cp0, cp - cp0);
658 void yf::HttpRewrite::Content::configure(
659 const xmlNode *ptr, std::map<std::string, RulePtr > &rules)
661 for (; ptr; ptr = ptr->next)
663 if (ptr->type != XML_ELEMENT_NODE)
665 if (!strcmp((const char *) ptr->name, "within"))
667 static const char *names[6] =
668 { "header", "attr", "tag", "rule", "reqline", 0 };
669 std::string values[5];
670 mp::xml::parse_attr(ptr, names, values);
672 w.header = values[0];
675 std::map<std::string,RulePtr>::const_iterator it =
676 rules.find(values[3]);
677 if (it == rules.end())
678 throw mp::filter::FilterException
679 ("Reference to non-existing rule '" + values[3] +
680 "' in http_rewrite filter");
682 w.reqline = values[4] == "1";
683 within_list.push_back(w);
688 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
690 static const char *names[2] = { "verbose", 0 };
691 std::string values[1];
693 mp::xml::parse_attr(ptr, names, values);
695 phase.m_verbose = atoi(values[0].c_str());
697 std::map<std::string, RulePtr > rules;
698 for (ptr = ptr->children; ptr; ptr = ptr->next)
700 if (ptr->type != XML_ELEMENT_NODE)
702 else if (!strcmp((const char *) ptr->name, "rule"))
704 static const char *names[2] = { "name", 0 };
705 std::string values[1];
706 values[0] = "default";
707 mp::xml::parse_attr(ptr, names, values);
709 RulePtr rule(new Rule);
710 for (xmlNode *p = ptr->children; p; p = p->next)
712 if (p->type != XML_ELEMENT_NODE)
714 if (!strcmp((const char *) p->name, "rewrite"))
718 const struct _xmlAttr *attr;
719 for (attr = p->properties; attr; attr = attr->next)
721 if (!strcmp((const char *) attr->name, "from"))
722 from = mp::xml::get_text(attr->children);
723 else if (!strcmp((const char *) attr->name, "to"))
724 replace.recipe = mp::xml::get_text(attr->children);
726 throw mp::filter::FilterException
728 + std::string((const char *) attr->name)
729 + " in rewrite section of http_rewrite");
731 yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
732 from.c_str(), replace.recipe.c_str());
735 replace.parse_groups(from);
736 rule->replace_list.push_back(replace);
740 throw mp::filter::FilterException
742 + std::string((const char *) p->name)
743 + " in http_rewrite filter");
745 rules[values[0]] = rule;
747 else if (!strcmp((const char *) ptr->name, "content"))
749 static const char *names[3] =
750 { "type", "mime", 0 };
751 std::string values[2];
752 mp::xml::parse_attr(ptr, names, values);
753 if (values[0].empty())
755 throw mp::filter::FilterException
756 ("Missing attribute, type for for element "
757 + std::string((const char *) ptr->name)
758 + " in http_rewrite filter");
763 // if (!values[1].empty())
764 c.content_re = values[1];
765 c.configure(ptr->children, rules);
766 phase.content_list.push_back(c);
770 throw mp::filter::FilterException
772 + std::string((const char *) ptr->name)
773 + " in http_rewrite filter");
778 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
781 for (ptr = ptr->children; ptr; ptr = ptr->next)
783 if (ptr->type != XML_ELEMENT_NODE)
785 else if (!strcmp((const char *) ptr->name, "request"))
787 configure_phase(ptr, *req_phase);
789 else if (!strcmp((const char *) ptr->name, "response"))
791 configure_phase(ptr, *res_phase);
795 throw mp::filter::FilterException
797 + std::string((const char *) ptr->name)
798 + " in http_rewrite1 filter");
803 static mp::filter::Base* filter_creator()
805 return new mp::filter::HttpRewrite;
809 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
820 * c-file-style: "Stroustrup"
821 * indent-tabs-mode: nil
823 * vim: shiftwidth=4 tabstop=8 expandtab