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"
28 #include <boost/regex.hpp>
29 #include <boost/lexical_cast.hpp>
33 namespace mp = metaproxy_1;
34 namespace yf = mp::filter;
36 namespace metaproxy_1 {
38 class HttpRewrite::Replace {
42 std::map<int, std::string> group_index;
43 const std::string search_replace(
44 std::map<std::string, std::string> & vars,
45 const std::string & txt) const;
46 std::string sub_vars (
47 const std::map<std::string, std::string> & vars) const;
51 class HttpRewrite::Rule {
53 std::list<Replace> replace_list;
54 const std::string test_patterns(
55 std::map<std::string, std::string> & vars,
56 const std::string & txt) const;
58 class HttpRewrite::Within {
66 class HttpRewrite::Phase {
68 std::list<Within> within_list;
69 void rewrite_reqline(mp::odr & o, Z_HTTP_Request *hreq,
70 std::map<std::string, std::string> & vars) const;
71 void rewrite_headers(mp::odr & o, Z_HTTP_Header *headers,
72 std::map<std::string, std::string> & vars) const;
73 void rewrite_body(mp::odr & o,
74 char **content_buf, int *content_len,
75 std::map<std::string, std::string> & vars) const;
80 yf::HttpRewrite::HttpRewrite() :
81 req_phase(new Phase), res_phase(new Phase)
85 yf::HttpRewrite::~HttpRewrite()
89 void yf::HttpRewrite::process(mp::Package & package) const
91 yaz_log(YLOG_LOG, "HttpRewrite begins....");
92 Z_GDU *gdu = package.request().get();
93 //map of request/response vars
94 std::map<std::string, std::string> vars;
96 if (gdu && gdu->which == Z_GDU_HTTP_Request)
98 Z_HTTP_Request *hreq = gdu->u.HTTP_Request;
100 req_phase->rewrite_reqline(o, hreq, vars);
101 yaz_log(YLOG_LOG, ">> Request headers");
102 req_phase->rewrite_headers(o, hreq->headers, vars);
103 req_phase->rewrite_body(o,
104 &hreq->content_buf, &hreq->content_len, vars);
105 package.request() = gdu;
108 gdu = package.response().get();
109 if (gdu && gdu->which == Z_GDU_HTTP_Response)
111 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
112 yaz_log(YLOG_LOG, "Response code %d", hres->code);
114 yaz_log(YLOG_LOG, "<< Respose headers");
115 res_phase->rewrite_headers(o, hres->headers, vars);
116 res_phase->rewrite_body(o, &hres->content_buf,
117 &hres->content_len, vars);
118 package.response() = gdu;
122 void yf::HttpRewrite::Phase::rewrite_reqline (mp::odr & o,
123 Z_HTTP_Request *hreq,
124 std::map<std::string, std::string> & vars) const
126 //rewrite the request line
128 if (strstr(hreq->path, "http://") == hreq->path)
130 yaz_log(YLOG_LOG, "Path in the method line is absolute, "
131 "possibly a proxy request");
136 //TODO what about proto
138 path += z_HTTP_header_lookup(hreq->headers, "Host");
142 std::list<Within>::const_iterator it = within_list.begin();
143 if (it != within_list.end())
145 RulePtr rule = it->rule;
147 yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
148 std::string npath = rule->test_patterns(vars, path);
151 yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
152 hreq->path = odr_strdup(o, npath.c_str());
157 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
158 Z_HTTP_Header *headers,
159 std::map<std::string, std::string> & vars) const
161 for (Z_HTTP_Header *header = headers;
163 header = header->next)
165 std::string sheader(header->name);
167 sheader += header->value;
168 yaz_log(YLOG_LOG, "%s: %s", header->name, header->value);
170 std::list<Within>::const_iterator it = within_list.begin();
171 if (it == within_list.end())
173 RulePtr rule = it->rule;
175 std::string out = rule->test_patterns(vars, sheader);
178 size_t pos = out.find(": ");
179 if (pos == std::string::npos)
181 yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
184 header->name = odr_strdup(o, out.substr(0, pos).c_str());
185 header->value = odr_strdup(o, out.substr(pos+2,
186 std::string::npos).c_str());
191 void yf::HttpRewrite::Phase::rewrite_body(mp::odr & o,
194 std::map<std::string, std::string> & vars) const
199 std::list<Within>::const_iterator it = within_list.begin();
200 if (it != within_list.end())
202 RulePtr rule = it->rule;
204 std::string body(*content_buf);
205 std::string nbody = rule->test_patterns(vars, body);
208 *content_buf = odr_strdup(o, nbody.c_str());
209 *content_len = nbody.size();
216 * Tests pattern from the vector in order and executes recipe on
219 const std::string yf::HttpRewrite::Rule::test_patterns(
220 std::map<std::string, std::string> & vars,
221 const std::string & txt) const
223 std::list<Replace>::const_iterator it = replace_list.begin();
225 for (; it != replace_list.end(); it++)
227 std::string out = it->search_replace(vars, txt);
228 if (!out.empty()) return out;
233 const std::string yf::HttpRewrite::Replace::search_replace(
234 std::map<std::string, std::string> & vars,
235 const std::string & txt) const
237 //exec regex against value
238 boost::regex re(regex);
240 std::string::const_iterator start, end;
244 while (regex_search(start, end, what, re)) //find next full match
247 for (i = 1; i < what.size(); ++i)
249 //check if the group is named
250 std::map<int, std::string>::const_iterator it
251 = group_index.find(i);
252 if (it != group_index.end())
254 if (!what[i].str().empty())
255 vars[it->second] = what[i];
259 //prepare replacement string
260 std::string rvalue = sub_vars(vars);
261 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
262 what.str(0).c_str(), rvalue.c_str());
263 out.append(start, what[0].first);
265 start = what[0].second; //move search forward
267 //if we had a match cat the last part
268 if (start != txt.begin())
269 out.append(start, end);
273 void yf::HttpRewrite::Replace::parse_groups()
277 const std::string & str = regex;
279 yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
280 for (size_t i = 0; i < str.size(); ++i)
283 if (!esc && str[i] == '\\')
288 if (!esc && str[i] == '(') //group starts
291 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
294 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
296 if (gnum > 0) gnum--;
302 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
304 if (i+1 < str.size() && str[i+1] == '<') //named
309 while (++i < str.size())
311 if (str[i] == '>') { term = true; break; }
312 if (!isalnum(str[i]))
313 throw mp::filter::FilterException
314 ("Only alphanumeric chars allowed, found "
318 + boost::lexical_cast<std::string>(i));
322 throw mp::filter::FilterException
323 ("Unterminated group name '" + gname
324 + " in '" + str +"'");
325 group_index[gnum] = gname;
326 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
327 gname.c_str(), gnum);
336 std::string yf::HttpRewrite::Replace::sub_vars (
337 const std::map<std::string, std::string> & vars) const
341 const std::string & in = recipe;
342 for (size_t i = 0; i < in.size(); ++i)
344 if (!esc && in[i] == '\\')
349 if (!esc && in[i] == '$') //var
351 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
356 while (++i < in.size())
358 if (in[i] == '}') { term = true; break; }
361 if (!term) throw mp::filter::FilterException
362 ("Unterminated var ref in '"+in+"' at "
363 + boost::lexical_cast<std::string>(i));
364 std::map<std::string, std::string>::const_iterator it
366 if (it != vars.end())
373 throw mp::filter::FilterException
374 ("Malformed or trimmed var ref in '"
375 +in+"' at "+boost::lexical_cast<std::string>(i));
387 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
389 std::map<std::string, RulePtr > rules;
390 for (ptr = ptr->children; ptr; ptr = ptr->next)
392 if (ptr->type != XML_ELEMENT_NODE)
394 else if (!strcmp((const char *) ptr->name, "rule"))
396 static const char *names[2] = { "name", 0 };
397 std::string values[1];
398 values[0] = "default";
399 mp::xml::parse_attr(ptr, names, values);
401 RulePtr rule(new Rule);
402 for (xmlNode *p = ptr->children; p; p = p->next)
404 if (p->type != XML_ELEMENT_NODE)
406 if (!strcmp((const char *) p->name, "rewrite"))
409 const struct _xmlAttr *attr;
410 for (attr = p->properties; attr; attr = attr->next)
412 if (!strcmp((const char *) attr->name, "from"))
413 replace.regex = mp::xml::get_text(attr->children);
414 else if (!strcmp((const char *) attr->name, "to"))
415 replace.recipe = mp::xml::get_text(attr->children);
417 throw mp::filter::FilterException
419 + std::string((const char *) attr->name)
420 + " in rewrite section of http_rewrite");
422 yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
423 replace.regex.c_str(), replace.recipe.c_str());
424 replace.parse_groups();
425 if (!replace.regex.empty())
426 rule->replace_list.push_back(replace);
429 throw mp::filter::FilterException
431 + std::string((const char *) p->name)
432 + " in http_rewrite filter");
434 if (!rule->replace_list.empty())
435 rules[values[0]] = rule;
437 else if (!strcmp((const char *) ptr->name, "within"))
439 static const char *names[5] =
440 { "header", "attr", "tag", "rule", 0 };
441 std::string values[4];
442 mp::xml::parse_attr(ptr, names, values);
444 w.header = values[0];
447 std::map<std::string,RulePtr>::const_iterator it =
448 rules.find(values[3]);
449 if (it == rules.end())
450 throw mp::filter::FilterException
451 ("Reference to non-existing rule '" + values[3] +
452 "' in http_rewrite filter");
454 phase.within_list.push_back(w);
458 throw mp::filter::FilterException
460 + std::string((const char *) ptr->name)
461 + " in http_rewrite filter");
466 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
469 for (ptr = ptr->children; ptr; ptr = ptr->next)
471 if (ptr->type != XML_ELEMENT_NODE)
473 else if (!strcmp((const char *) ptr->name, "request"))
475 configure_phase(ptr, *req_phase);
477 else if (!strcmp((const char *) ptr->name, "response"))
479 configure_phase(ptr, *res_phase);
483 throw mp::filter::FilterException
485 + std::string((const char *) ptr->name)
486 + " in http_rewrite1 filter");
491 static mp::filter::Base* filter_creator()
493 return new mp::filter::HttpRewrite;
497 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
508 * c-file-style: "Stroustrup"
509 * indent-tabs-mode: nil
511 * vim: shiftwidth=4 tabstop=8 expandtab