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
146 std::string body(*content_buf);
148 test_patterns(vars, body, uri_pats, groups_bynum);
151 *content_buf = odr_strdup(o, nbody.c_str());
152 *content_len = nbody.size();
158 * Tests pattern from the vector in order and executes recipe on
161 const std::string yf::HttpRewrite::test_patterns(
162 std::map<std::string, std::string> & vars,
163 const std::string & txt,
164 const spair_vec & uri_pats,
165 const std::vector<std::map<int, std::string> > & groups_bynum_vec)
168 for (unsigned i = 0; i < uri_pats.size(); i++)
170 std::string out = search_replace(vars, txt,
171 uri_pats[i].first, uri_pats[i].second,
172 groups_bynum_vec[i]);
173 if (!out.empty()) return out;
179 const std::string yf::HttpRewrite::search_replace(
180 std::map<std::string, std::string> & vars,
181 const std::string & txt,
182 const std::string & uri_re,
183 const std::string & uri_pat,
184 const std::map<int, std::string> & groups_bynum) const
186 //exec regex against value
187 boost::regex re(uri_re);
189 std::string::const_iterator start, end;
193 while (regex_search(start, end, what, re)) //find next full match
196 for (i = 1; i < what.size(); ++i)
198 //check if the group is named
199 std::map<int, std::string>::const_iterator it
200 = groups_bynum.find(i);
201 if (it != groups_bynum.end())
203 if (!what[i].str().empty())
204 vars[it->second] = what[i];
208 //prepare replacement string
209 std::string rvalue = sub_vars(uri_pat, vars);
210 yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
211 what.str(0).c_str(), rvalue.c_str());
212 out.append(start, what[0].first);
214 start = what[0].second; //move search forward
216 //if we had a match cat the last part
217 if (start != txt.begin())
218 out.append(start, end);
222 void yf::HttpRewrite::parse_groups(
223 const spair_vec & uri_pats,
224 std::vector<std::map<int, std::string> > & groups_bynum_vec)
226 for (unsigned h = 0; h < uri_pats.size(); h++)
230 //regex is first, subpat is second
231 std::string str = uri_pats[h].first;
232 //for each pair we have an indexing map
233 std::map<int, std::string> groups_bynum;
234 for (unsigned i = 0; i < str.size(); ++i)
236 if (!esc && str[i] == '\\')
241 if (!esc && str[i] == '(') //group starts
244 if (i+1 < str.size() && str[i+1] == '?') //group with attrs
247 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
249 if (gnum > 0) gnum--;
253 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
255 if (i+1 < str.size() && str[i+1] == '<') //named
260 while (++i < str.size())
262 if (str[i] == '>') { term = true; break; }
263 if (!isalnum(str[i]))
264 throw mp::filter::FilterException
265 ("Only alphanumeric chars allowed, found "
269 + boost::lexical_cast<std::string>(i));
273 throw mp::filter::FilterException
274 ("Unterminated group name '" + gname
275 + " in '" + str +"'");
276 groups_bynum[gnum] = gname;
277 yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
278 gname.c_str(), gnum);
284 groups_bynum_vec.push_back(groups_bynum);
288 std::string yf::HttpRewrite::sub_vars (const std::string & in,
289 const std::map<std::string, std::string> & vars)
293 for (unsigned i = 0; i < in.size(); ++i)
295 if (!esc && in[i] == '\\')
300 if (!esc && in[i] == '$') //var
302 if (i+1 < in.size() && in[i+1] == '{') //ref prefix
307 while (++i < in.size())
309 if (in[i] == '}') { term = true; break; }
312 if (!term) throw mp::filter::FilterException
313 ("Unterminated var ref in '"+in+"' at "
314 + boost::lexical_cast<std::string>(i));
315 std::map<std::string, std::string>::const_iterator it
317 if (it != vars.end())
324 throw mp::filter::FilterException
325 ("Malformed or trimmed var ref in '"
326 +in+"' at "+boost::lexical_cast<std::string>(i));
337 void yf::HttpRewrite::configure(
338 const spair_vec req_uri_pats,
339 const spair_vec res_uri_pats)
341 //TODO should we really copy them out?
342 this->req_uri_pats = req_uri_pats;
343 this->res_uri_pats = res_uri_pats;
345 parse_groups(req_uri_pats, req_groups_bynum);
346 parse_groups(res_uri_pats, res_groups_bynum);
350 static void configure_rules(const xmlNode *ptr, yf::HttpRewrite::spair_vec & dest)
352 for (ptr = ptr->children; ptr; ptr = ptr->next)
354 if (ptr->type != XML_ELEMENT_NODE)
356 else if (!strcmp((const char *) ptr->name, "rewrite"))
358 std::string from, to;
359 const struct _xmlAttr *attr;
360 for (attr = ptr->properties; attr; attr = attr->next)
362 if (!strcmp((const char *) attr->name, "from"))
363 from = mp::xml::get_text(attr->children);
364 else if (!strcmp((const char *) attr->name, "to"))
365 to = mp::xml::get_text(attr->children);
367 throw mp::filter::FilterException
369 + std::string((const char *) attr->name)
370 + " in rewrite section of http_rewrite");
372 yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
373 from.c_str(), to.c_str());
375 dest.push_back(std::make_pair(from, to));
379 throw mp::filter::FilterException
381 + std::string((const char *) ptr->name)
382 + " in http_rewrite1 filter");
387 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
390 spair_vec req_uri_pats;
391 spair_vec res_uri_pats;
392 for (ptr = ptr->children; ptr; ptr = ptr->next)
394 if (ptr->type != XML_ELEMENT_NODE)
396 else if (!strcmp((const char *) ptr->name, "request"))
398 configure_rules(ptr, req_uri_pats);
400 else if (!strcmp((const char *) ptr->name, "response"))
402 configure_rules(ptr, res_uri_pats);
406 throw mp::filter::FilterException
408 + std::string((const char *) ptr->name)
409 + " in http_rewrite1 filter");
412 configure(req_uri_pats, res_uri_pats);
415 static mp::filter::Base* filter_creator()
417 return new mp::filter::HttpRewrite;
421 struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
432 * c-file-style: "Stroustrup"
433 * indent-tabs-mode: nil
435 * vim: shiftwidth=4 tabstop=8 expandtab