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>
35 #include <sys/types.h>
38 namespace mp = metaproxy_1;
39 namespace yf = mp::filter;
41 yf::HttpRewrite::HttpRewrite()
45 yf::HttpRewrite::~HttpRewrite()
49 void yf::HttpRewrite::process(mp::Package & package) const
51 yaz_log(YLOG_DEBUG, "HttpRewrite begins....");
52 Z_GDU *gdu = package.request().get();
53 //map of request/response vars
54 std::map<std::string, std::string> vars;
56 if (gdu && gdu->which == Z_GDU_HTTP_Request)
58 Z_HTTP_Request *hreq = gdu->u.HTTP_Request;
60 rewrite_reqline(o, hreq, vars);
61 yaz_log(YLOG_DEBUG, ">> Request headers");
62 rewrite_headers(o, hreq->headers, vars);
63 rewrite_body(o, &hreq->content_buf, &hreq->content_len, vars);
64 package.request() = gdu;
67 gdu = package.response().get();
68 if (gdu && gdu->which == Z_GDU_HTTP_Response)
70 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
71 yaz_log(YLOG_DEBUG, "Response code %d", hres->code);
73 yaz_log(YLOG_DEBUG, "<< Respose headers");
74 rewrite_headers(o, hres->headers, vars);
75 rewrite_body(o, &hres->content_buf, &hres->content_len, vars);
76 package.response() = gdu;
80 void yf::HttpRewrite::rewrite_reqline (mp::odr & o, Z_HTTP_Request *hreq,
81 std::map<std::string, std::string> & vars) const
83 //rewrite the request line
85 if (strstr(hreq->path, "http://") == hreq->path)
87 yaz_log(YLOG_DEBUG, "Path in the method line is absolute, "
88 "possibly a proxy request");
93 //TODO what about proto
95 path += z_HTTP_header_lookup(hreq->headers, "Host");
98 yaz_log(YLOG_DEBUG, "Proxy request URL is %s", path.c_str());
100 test_patterns(vars, path, req_uri_pats, req_groups_bynum);
103 yaz_log(YLOG_DEBUG, "Rewritten request URL is %s", npath.c_str());
104 hreq->path = odr_strdup(o, npath.c_str());
108 void yf::HttpRewrite::rewrite_headers (mp::odr & o, Z_HTTP_Header *headers,
109 std::map<std::string, std::string> & vars) const
111 for (Z_HTTP_Header *header = headers;
113 header = header->next)
115 std::string sheader(header->name);
117 sheader += header->value;
118 yaz_log(YLOG_DEBUG, "%s: %s", header->name, header->value);
119 std::string out = test_patterns(vars,
121 req_uri_pats, req_groups_bynum);
124 size_t pos = out.find(": ");
125 if (pos == std::string::npos)
127 yaz_log(YLOG_DEBUG, "Header malformed during rewrite, ignoring");
130 header->name = odr_strdup(o, out.substr(0, pos).c_str());
131 header->value = odr_strdup(o, out.substr(pos+2,
132 std::string::npos).c_str());
137 void yf::HttpRewrite::rewrite_body (mp::odr & o, char **content_buf, int *content_len,
138 std::map<std::string, std::string> & vars) const
142 std::string body(*content_buf);
144 test_patterns(vars, body, req_uri_pats, req_groups_bynum);
147 *content_buf = odr_strdup(o, nbody.c_str());
148 *content_len = nbody.size();
154 * Tests pattern from the vector in order and executes recipe on
157 const std::string yf::HttpRewrite::test_patterns(
158 std::map<std::string, std::string> & vars,
159 const std::string & txt,
160 const spair_vec & uri_pats,
161 const std::vector<std::map<int, std::string> > & groups_bynum_vec)
164 for (unsigned i = 0; i < uri_pats.size(); i++)
166 std::string out = search_replace(vars, txt,
167 uri_pats[i].first, uri_pats[i].second,
168 groups_bynum_vec[i]);
169 if (!out.empty()) return out;
175 const std::string yf::HttpRewrite::search_replace(
176 std::map<std::string, std::string> & vars,
177 const std::string & txt,
178 const std::string & uri_re,
179 const std::string & uri_pat,
180 const std::map<int, std::string> & groups_bynum) const
182 //exec regex against value
183 boost::regex re(uri_re);
185 std::string::const_iterator start, end;
189 while (regex_search(start, end, what, re)) //find next full match
192 for (i = 1; i < what.size(); ++i)
194 //check if the group is named
195 std::map<int, std::string>::const_iterator it
196 = groups_bynum.find(i);
197 if (it != groups_bynum.end())
199 std::string name = it->second;
200 if (!what[i].str().empty())
201 vars[name] = what[i];
205 //prepare replacement string
206 std::string rvalue = sub_vars(uri_pat, vars);
208 std::string rhvalue = what.prefix().str()
209 + rvalue + what.suffix().str();
210 yaz_log(YLOG_DEBUG, "! Rewritten '%s' to '%s'",
211 what.str(0).c_str(), rvalue.c_str());
213 start = what[0].second; //move search forward
218 void yf::HttpRewrite::parse_groups(
219 const spair_vec & uri_pats,
220 std::vector<std::map<int, std::string> > & groups_bynum_vec)
222 for (unsigned h = 0; h < uri_pats.size(); h++)
226 //regex is first, subpat is second
227 std::string str = uri_pats[h].first;
228 //for each pair we have an indexing map
229 std::map<int, std::string> groups_bynum;
230 for (unsigned i = 0; i < str.size(); ++i)
232 if (!esc && str[i] == '\\')
237 if (!esc && str[i] == '(') //group starts
240 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
243 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
245 if (gnum > 0) gnum--;
249 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
251 if (i+1 < str.size() && str[i+1] == '<') //named
256 while (++i < str.size())
258 if (str[i] == '>') { term = true; break; }
259 if (!isalnum(str[i]))
260 throw mp::filter::FilterException
261 ("Only alphanumeric chars allowed, found "
265 + boost::lexical_cast<std::string>(i));
269 throw mp::filter::FilterException
270 ("Unterminated group name '" + gname
271 + " in '" + str +"'");
272 groups_bynum[gnum] = gname;
273 yaz_log(YLOG_DEBUG, "Found named group '%s' at $%d",
274 gname.c_str(), gnum);
280 groups_bynum_vec.push_back(groups_bynum);
284 std::string yf::HttpRewrite::sub_vars (const std::string & in,
285 const std::map<std::string, std::string> & vars)
289 for (unsigned i = 0; i < in.size(); ++i)
291 if (!esc && in[i] == '\\')
296 if (!esc && in[i] == '$') //var
298 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
303 while (++i < in.size())
305 if (in[i] == '}') { term = true; break; }
308 if (!term) throw mp::filter::FilterException
309 ("Unterminated var ref in '"+in+"' at "
310 + boost::lexical_cast<std::string>(i));
311 std::map<std::string, std::string>::const_iterator it
313 if (it != vars.end())
320 throw mp::filter::FilterException
321 ("Malformed or trimmed var ref in '"
322 +in+"' at "+boost::lexical_cast<std::string>(i));
333 void yf::HttpRewrite::configure(
334 const spair_vec req_uri_pats,
335 const spair_vec res_uri_pats)
337 //TODO should we really copy them out?
338 this->req_uri_pats = req_uri_pats;
339 this->res_uri_pats = res_uri_pats;
341 parse_groups(req_uri_pats, req_groups_bynum);
342 parse_groups(res_uri_pats, res_groups_bynum);
346 static void configure_rules(const xmlNode *ptr, yf::HttpRewrite::spair_vec & dest)
348 for (ptr = ptr->children; ptr; ptr = ptr->next)
350 if (ptr->type != XML_ELEMENT_NODE)
352 else if (!strcmp((const char *) ptr->name, "rewrite"))
354 std::string from, to;
355 const struct _xmlAttr *attr;
356 for (attr = ptr->properties; attr; attr = attr->next)
358 if (!strcmp((const char *) attr->name, "from"))
359 from = mp::xml::get_text(attr->children);
360 else if (!strcmp((const char *) attr->name, "to"))
361 to = mp::xml::get_text(attr->children);
363 throw mp::filter::FilterException
365 + std::string((const char *) attr->name)
366 + " in rewrite section of http_rewrite");
368 yaz_log(YLOG_DEBUG, "Found rewrite rule from '%s' to '%s'",
369 from.c_str(), to.c_str());
371 dest.push_back(std::make_pair(from, to));
375 throw mp::filter::FilterException
377 + std::string((const char *) ptr->name)
378 + " in http_rewrite1 filter");
383 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
386 spair_vec req_uri_pats;
387 spair_vec res_uri_pats;
388 for (ptr = ptr->children; ptr; ptr = ptr->next)
390 if (ptr->type != XML_ELEMENT_NODE)
392 else if (!strcmp((const char *) ptr->name, "request"))
394 configure_rules(ptr, req_uri_pats);
396 else if (!strcmp((const char *) ptr->name, "response"))
398 configure_rules(ptr, res_uri_pats);
402 throw mp::filter::FilterException
404 + std::string((const char *) ptr->name)
405 + " in http_rewrite1 filter");
408 configure(req_uri_pats, res_uri_pats);
411 static mp::filter::Base* filter_creator()
413 return new mp::filter::HttpRewrite;
417 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
428 * c-file-style: "Stroustrup"
429 * indent-tabs-mode: nil
431 * vim: shiftwidth=4 tabstop=8 expandtab