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_LOG, "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_LOG, ">> Request headers");
62 rewrite_headers(o, hreq->headers, vars, req_uri_pats, req_groups_bynum);
63 rewrite_body(o, &hreq->content_buf, &hreq->content_len, vars,
64 req_uri_pats, req_groups_bynum);
65 package.request() = gdu;
68 gdu = package.response().get();
69 if (gdu && gdu->which == Z_GDU_HTTP_Response)
71 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
72 yaz_log(YLOG_LOG, "Response code %d", hres->code);
74 yaz_log(YLOG_LOG, "<< Respose headers");
75 rewrite_headers(o, hres->headers, vars, res_uri_pats, res_groups_bynum);
76 rewrite_body(o, &hres->content_buf, &hres->content_len, vars,
77 res_uri_pats, res_groups_bynum);
78 package.response() = gdu;
82 void yf::HttpRewrite::rewrite_reqline (mp::odr & o, Z_HTTP_Request *hreq,
83 std::map<std::string, std::string> & vars) const
85 //rewrite the request line
87 if (strstr(hreq->path, "http://") == hreq->path)
89 yaz_log(YLOG_LOG, "Path in the method line is absolute, "
90 "possibly a proxy request");
95 //TODO what about proto
97 path += z_HTTP_header_lookup(hreq->headers, "Host");
100 yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
102 test_patterns(vars, path, req_uri_pats, req_groups_bynum);
105 yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
106 hreq->path = odr_strdup(o, npath.c_str());
110 void yf::HttpRewrite::rewrite_headers (mp::odr & o, Z_HTTP_Header *headers,
111 std::map<std::string, std::string> & vars,
112 const spair_vec & uri_pats,
113 const std::vector<std::map<int, std::string> > & groups_bynum) const
115 for (Z_HTTP_Header *header = headers;
117 header = header->next)
119 std::string sheader(header->name);
121 sheader += header->value;
122 yaz_log(YLOG_LOG, "%s: %s", header->name, header->value);
123 std::string out = test_patterns(vars, sheader, uri_pats, groups_bynum);
126 size_t pos = out.find(": ");
127 if (pos == std::string::npos)
129 yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
132 header->name = odr_strdup(o, out.substr(0, pos).c_str());
133 header->value = odr_strdup(o, out.substr(pos+2,
134 std::string::npos).c_str());
139 void yf::HttpRewrite::rewrite_body (mp::odr & o, char **content_buf, int *content_len,
140 std::map<std::string, std::string> & vars,
141 const spair_vec & uri_pats,
142 const std::vector<std::map<int, std::string> > & groups_bynum) const
144 std::cout << "About to rewrite body: " << *content_buf;
147 std::string body(*content_buf);
149 test_patterns(vars, body, uri_pats, groups_bynum);
152 *content_buf = odr_strdup(o, nbody.c_str());
153 *content_len = nbody.size();
159 * Tests pattern from the vector in order and executes recipe on
162 const std::string yf::HttpRewrite::test_patterns(
163 std::map<std::string, std::string> & vars,
164 const std::string & txt,
165 const spair_vec & uri_pats,
166 const std::vector<std::map<int, std::string> > & groups_bynum_vec)
169 for (unsigned i = 0; i < uri_pats.size(); i++)
171 std::string out = search_replace(vars, txt,
172 uri_pats[i].first, uri_pats[i].second,
173 groups_bynum_vec[i]);
174 if (!out.empty()) return out;
180 const std::string yf::HttpRewrite::search_replace(
181 std::map<std::string, std::string> & vars,
182 const std::string & txt,
183 const std::string & uri_re,
184 const std::string & uri_pat,
185 const std::map<int, std::string> & groups_bynum) const
187 //exec regex against value
188 boost::regex re(uri_re);
190 std::string::const_iterator start, end;
194 while (regex_search(start, end, what, re)) //find next full match
197 for (i = 1; i < what.size(); ++i)
199 //check if the group is named
200 std::map<int, std::string>::const_iterator it
201 = groups_bynum.find(i);
202 if (it != groups_bynum.end())
204 if (!what[i].str().empty())
205 vars[it->second] = what[i];
209 //prepare replacement string
210 std::string rvalue = sub_vars(uri_pat, vars);
211 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
212 what.str(0).c_str(), rvalue.c_str());
213 out.append(start, what[0].first);
215 start = what[0].second; //move search forward
217 //if we had a match cat the last part
218 if (start != txt.begin())
219 out.append(start, end);
223 void yf::HttpRewrite::parse_groups(
224 const spair_vec & uri_pats,
225 std::vector<std::map<int, std::string> > & groups_bynum_vec)
227 for (unsigned h = 0; h < uri_pats.size(); h++)
231 //regex is first, subpat is second
232 std::string str = uri_pats[h].first;
233 //for each pair we have an indexing map
234 std::map<int, std::string> groups_bynum;
235 for (unsigned i = 0; i < str.size(); ++i)
237 if (!esc && str[i] == '\\')
242 if (!esc && str[i] == '(') //group starts
245 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
248 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
250 if (gnum > 0) gnum--;
254 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
256 if (i+1 < str.size() && str[i+1] == '<') //named
261 while (++i < str.size())
263 if (str[i] == '>') { term = true; break; }
264 if (!isalnum(str[i]))
265 throw mp::filter::FilterException
266 ("Only alphanumeric chars allowed, found "
270 + boost::lexical_cast<std::string>(i));
274 throw mp::filter::FilterException
275 ("Unterminated group name '" + gname
276 + " in '" + str +"'");
277 groups_bynum[gnum] = gname;
278 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
279 gname.c_str(), gnum);
285 groups_bynum_vec.push_back(groups_bynum);
289 std::string yf::HttpRewrite::sub_vars (const std::string & in,
290 const std::map<std::string, std::string> & vars)
294 for (unsigned i = 0; i < in.size(); ++i)
296 if (!esc && in[i] == '\\')
301 if (!esc && in[i] == '$') //var
303 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
308 while (++i < in.size())
310 if (in[i] == '}') { term = true; break; }
313 if (!term) throw mp::filter::FilterException
314 ("Unterminated var ref in '"+in+"' at "
315 + boost::lexical_cast<std::string>(i));
316 std::map<std::string, std::string>::const_iterator it
318 if (it != vars.end())
325 throw mp::filter::FilterException
326 ("Malformed or trimmed var ref in '"
327 +in+"' at "+boost::lexical_cast<std::string>(i));
338 void yf::HttpRewrite::configure(
339 const spair_vec req_uri_pats,
340 const spair_vec res_uri_pats)
342 //TODO should we really copy them out?
343 this->req_uri_pats = req_uri_pats;
344 this->res_uri_pats = res_uri_pats;
346 parse_groups(req_uri_pats, req_groups_bynum);
347 parse_groups(res_uri_pats, res_groups_bynum);
351 static void configure_rules(const xmlNode *ptr, yf::HttpRewrite::spair_vec & dest)
353 for (ptr = ptr->children; ptr; ptr = ptr->next)
355 if (ptr->type != XML_ELEMENT_NODE)
357 else if (!strcmp((const char *) ptr->name, "rewrite"))
359 std::string from, to;
360 const struct _xmlAttr *attr;
361 for (attr = ptr->properties; attr; attr = attr->next)
363 if (!strcmp((const char *) attr->name, "from"))
364 from = mp::xml::get_text(attr->children);
365 else if (!strcmp((const char *) attr->name, "to"))
366 to = mp::xml::get_text(attr->children);
368 throw mp::filter::FilterException
370 + std::string((const char *) attr->name)
371 + " in rewrite section of http_rewrite");
373 yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
374 from.c_str(), to.c_str());
376 dest.push_back(std::make_pair(from, to));
380 throw mp::filter::FilterException
382 + std::string((const char *) ptr->name)
383 + " in http_rewrite1 filter");
388 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
391 spair_vec req_uri_pats;
392 spair_vec res_uri_pats;
393 for (ptr = ptr->children; ptr; ptr = ptr->next)
395 if (ptr->type != XML_ELEMENT_NODE)
397 else if (!strcmp((const char *) ptr->name, "request"))
399 configure_rules(ptr, req_uri_pats);
401 else if (!strcmp((const char *) ptr->name, "response"))
403 configure_rules(ptr, res_uri_pats);
407 throw mp::filter::FilterException
409 + std::string((const char *) ptr->name)
410 + " in http_rewrite1 filter");
413 configure(req_uri_pats, res_uri_pats);
416 static mp::filter::Base* filter_creator()
418 return new mp::filter::HttpRewrite;
422 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
433 * c-file-style: "Stroustrup"
434 * indent-tabs-mode: nil
436 * vim: shiftwidth=4 tabstop=8 expandtab