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
94 path += z_HTTP_header_lookup(hreq->headers, "Host");
97 yaz_log(YLOG_DEBUG, "Proxy request URL is %s", path.c_str());
99 test_patterns(vars, path, req_uri_pats, req_groups_bynum);
102 yaz_log(YLOG_DEBUG, "Rewritten request URL is %s", npath.c_str());
103 hreq->path = odr_strdup(o, npath.c_str());
107 void yf::HttpRewrite::rewrite_headers (mp::odr & o, Z_HTTP_Header *headers,
108 std::map<std::string, std::string> & vars) const
110 for (Z_HTTP_Header *header = headers;
112 header = header->next)
114 std::string sheader(header->name);
116 sheader += header->value;
117 yaz_log(YLOG_DEBUG, "%s: %s", header->name, header->value);
118 std::string out = test_patterns(vars,
120 req_uri_pats, req_groups_bynum);
123 size_t pos = out.find(": ");
124 if (pos == std::string::npos)
126 yaz_log(YLOG_DEBUG, "Header malformed during rewrite, ignoring");
129 header->name = odr_strdup(o, out.substr(0, pos).c_str());
130 header->value = odr_strdup(o, out.substr(pos+2,
131 std::string::npos).c_str());
136 void yf::HttpRewrite::rewrite_body (mp::odr & o, char **content_buf, int *content_len,
137 std::map<std::string, std::string> & vars) const
141 std::string body(*content_buf);
143 test_patterns(vars, body, req_uri_pats, req_groups_bynum);
146 *content_buf = odr_strdup(o, nbody.c_str());
147 *content_len = nbody.size();
153 * Tests pattern from the vector in order and executes recipe on
156 const std::string yf::HttpRewrite::test_patterns(
157 std::map<std::string, std::string> & vars,
158 const std::string & txt,
159 const spair_vec & uri_pats,
160 const std::vector<std::map<int, std::string> > & groups_bynum_vec)
163 for (unsigned i = 0; i < uri_pats.size(); i++)
165 std::string out = search_replace(vars, txt,
166 uri_pats[i].first, uri_pats[i].second,
167 groups_bynum_vec[i]);
168 if (!out.empty()) return out;
174 const std::string yf::HttpRewrite::search_replace(
175 std::map<std::string, std::string> & vars,
176 const std::string & txt,
177 const std::string & uri_re,
178 const std::string & uri_pat,
179 const std::map<int, std::string> & groups_bynum) const
181 //exec regex against value
182 boost::regex re(uri_re);
184 std::string::const_iterator start, end;
188 while (regex_search(start, end, what, re)) //find next full match
191 for (i = 1; i < what.size(); ++i)
193 //check if the group is named
194 std::map<int, std::string>::const_iterator it
195 = groups_bynum.find(i);
196 if (it != groups_bynum.end())
198 std::string name = it->second;
199 if (!what[i].str().empty())
200 vars[name] = what[i];
204 //prepare replacement string
205 std::string rvalue = sub_vars(uri_pat, vars);
207 std::string rhvalue = what.prefix().str()
208 + rvalue + what.suffix().str();
209 yaz_log(YLOG_DEBUG, "! Rewritten '%s' to '%s'",
210 what.str(0).c_str(), rvalue.c_str());
212 start = what[0].second; //move search forward
217 void yf::HttpRewrite::parse_groups(
218 const spair_vec & uri_pats,
219 std::vector<std::map<int, std::string> > & groups_bynum_vec)
221 for (unsigned h = 0; h < uri_pats.size(); h++)
225 //regex is first, subpat is second
226 std::string str = uri_pats[h].first;
227 //for each pair we have an indexing map
228 std::map<int, std::string> groups_bynum;
229 for (unsigned i = 0; i < str.size(); ++i)
231 if (!esc && str[i] == '\\')
236 if (!esc && str[i] == '(') //group starts
239 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
242 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
244 if (gnum > 0) gnum--;
248 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
250 if (i+1 < str.size() && str[i+1] == '<') //named
255 while (++i < str.size())
257 if (str[i] == '>') { term = true; break; }
258 if (!isalnum(str[i]))
259 throw mp::filter::FilterException
260 ("Only alphanumeric chars allowed, found "
264 + boost::lexical_cast<std::string>(i));
268 throw mp::filter::FilterException
269 ("Unterminated group name '" + gname
270 + " in '" + str +"'");
271 groups_bynum[gnum] = gname;
272 yaz_log(YLOG_DEBUG, "Found named group '%s' at $%d",
273 gname.c_str(), gnum);
279 groups_bynum_vec.push_back(groups_bynum);
283 std::string yf::HttpRewrite::sub_vars (const std::string & in,
284 const std::map<std::string, std::string> & vars)
288 for (unsigned i = 0; i < in.size(); ++i)
290 if (!esc && in[i] == '\\')
295 if (!esc && in[i] == '$') //var
297 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
302 while (++i < in.size())
304 if (in[i] == '}') { term = true; break; }
307 if (!term) throw mp::filter::FilterException
308 ("Unterminated var ref in '"+in+"' at "
309 + boost::lexical_cast<std::string>(i));
310 std::map<std::string, std::string>::const_iterator it
312 if (it != vars.end())
319 throw mp::filter::FilterException
320 ("Malformed or trimmed var ref in '"
321 +in+"' at "+boost::lexical_cast<std::string>(i));
332 void yf::HttpRewrite::configure(
333 const spair_vec req_uri_pats,
334 const spair_vec res_uri_pats)
336 //TODO should we really copy them out?
337 this->req_uri_pats = req_uri_pats;
338 this->res_uri_pats = res_uri_pats;
340 parse_groups(req_uri_pats, req_groups_bynum);
341 parse_groups(res_uri_pats, res_groups_bynum);
345 static void configure_rules(const xmlNode *ptr, yf::HttpRewrite::spair_vec & dest)
347 for (ptr = ptr->children; ptr; ptr = ptr->next)
349 if (ptr->type != XML_ELEMENT_NODE)
351 else if (!strcmp((const char *) ptr->name, "rewrite"))
353 std::string from, to;
354 const struct _xmlAttr *attr;
355 for (attr = ptr->properties; attr; attr = attr->next)
357 if (!strcmp((const char *) attr->name, "from"))
358 from = mp::xml::get_text(attr->children);
359 else if (!strcmp((const char *) attr->name, "to"))
360 to = mp::xml::get_text(attr->children);
362 throw mp::filter::FilterException
364 + std::string((const char *) attr->name)
365 + " in rewrite section of http_rewrite");
367 yaz_log(YLOG_DEBUG, "Found rewrite rule from '%s' to '%s'",
368 from.c_str(), to.c_str());
370 dest.push_back(std::make_pair(from, to));
374 throw mp::filter::FilterException
376 + std::string((const char *) ptr->name)
377 + " in http_rewrite1 filter");
382 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
385 spair_vec req_uri_pats;
386 spair_vec res_uri_pats;
387 for (ptr = ptr->children; ptr; ptr = ptr->next)
389 if (ptr->type != XML_ELEMENT_NODE)
391 else if (!strcmp((const char *) ptr->name, "request"))
393 configure_rules(ptr, req_uri_pats);
395 else if (!strcmp((const char *) ptr->name, "response"))
397 configure_rules(ptr, res_uri_pats);
401 throw mp::filter::FilterException
403 + std::string((const char *) ptr->name)
404 + " in http_rewrite1 filter");
407 configure(req_uri_pats, res_uri_pats);
410 static mp::filter::Base* filter_creator()
412 return new mp::filter::HttpRewrite;
416 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
427 * c-file-style: "Stroustrup"
428 * indent-tabs-mode: nil
430 * vim: shiftwidth=4 tabstop=8 expandtab