Fix the test case
[metaproxy-moved-to-github.git] / src / filter_http_rewrite.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2013 Index Data
3
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
7 version.
8
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
12 for more details.
13
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
17 */
18
19 #include "config.hpp"
20 #include <metaproxy/filter.hpp>
21 #include <metaproxy/package.hpp>
22 #include <metaproxy/util.hpp>
23 #include "filter_http_rewrite.hpp"
24
25 #include <yaz/zgdu.h>
26 #include <yaz/log.h>
27
28 #include <boost/regex.hpp>
29 #include <boost/lexical_cast.hpp>
30
31 #include <list>
32 #include <map>
33
34 #if HAVE_SYS_TYPES_H
35 #include <sys/types.h>
36 #endif
37
38 namespace mp = metaproxy_1;
39 namespace yf = mp::filter;
40
41 yf::HttpRewrite::HttpRewrite()
42 {
43 }
44
45 yf::HttpRewrite::~HttpRewrite()
46 {
47 }
48
49 void yf::HttpRewrite::process(mp::Package & package) const 
50 {
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;
55     //we have an http req
56     if (gdu && gdu->which == Z_GDU_HTTP_Request)
57     {
58         Z_HTTP_Request *hreq = gdu->u.HTTP_Request;
59         mp::odr o;
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;
66     }
67     package.move();
68     gdu = package.response().get();
69     if (gdu && gdu->which == Z_GDU_HTTP_Response)
70     {
71         Z_HTTP_Response *hres = gdu->u.HTTP_Response;
72         yaz_log(YLOG_LOG, "Response code %d", hres->code);
73         mp::odr o;
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;
79     }
80 }
81
82 void yf::HttpRewrite::rewrite_reqline (mp::odr & o, Z_HTTP_Request *hreq,
83         std::map<std::string, std::string> & vars) const 
84 {
85     //rewrite the request line
86     std::string path;
87     if (strstr(hreq->path, "http://") == hreq->path)
88     {
89         yaz_log(YLOG_LOG, "Path in the method line is absolute, " 
90             "possibly a proxy request");
91         path += hreq->path;
92     }
93     else
94     {
95         //TODO what about proto
96         path += "http://";
97         path += z_HTTP_header_lookup(hreq->headers, "Host");
98         path += hreq->path; 
99     }
100     yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
101     std::string npath = 
102         test_patterns(vars, path, req_uri_pats, req_groups_bynum);
103     if (!npath.empty())
104     {
105         yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
106         hreq->path = odr_strdup(o, npath.c_str());
107     }
108 }
109
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 
114 {
115     for (Z_HTTP_Header *header = headers;
116             header != 0; 
117             header = header->next) 
118     {
119         std::string sheader(header->name);
120         sheader += ": ";
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);
124         if (!out.empty()) 
125         {
126             size_t pos = out.find(": ");
127             if (pos == std::string::npos)
128             {
129                 yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
130                 continue;
131             }
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());
135         }
136     }
137 }
138
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 
143 {
144     if (*content_buf)
145     {
146         std::string body(*content_buf);
147         std::string nbody = 
148             test_patterns(vars, body, uri_pats, groups_bynum);
149         if (!nbody.empty())
150         {
151             *content_buf = odr_strdup(o, nbody.c_str());
152             *content_len = nbody.size();
153         }
154     }
155 }
156
157 /**
158  * Tests pattern from the vector in order and executes recipe on
159  the first match.
160  */
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)
166     const
167 {
168     for (unsigned i = 0; i < uri_pats.size(); i++) 
169     {
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;
174     }
175     return "";
176 }
177
178
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
185 {
186     //exec regex against value
187     boost::regex re(uri_re);
188     boost::smatch what;
189     std::string::const_iterator start, end;
190     start = txt.begin();
191     end = txt.end();
192     std::string out;
193     while (regex_search(start, end, what, re)) //find next full match
194     {
195         unsigned i;
196         for (i = 1; i < what.size(); ++i)
197         {
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()) 
202             {   //it is
203                 if (!what[i].str().empty())
204                     vars[it->second] = what[i];
205             }
206
207         }
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);
213         out.append(rvalue);
214         start = what[0].second; //move search forward
215     }
216     //if we had a match cat the last part
217     if (start != txt.begin())
218         out.append(start, end);
219     return out;
220 }
221
222 void yf::HttpRewrite::parse_groups(
223         const spair_vec & uri_pats,
224         std::vector<std::map<int, std::string> > & groups_bynum_vec)
225 {
226     for (unsigned h = 0; h < uri_pats.size(); h++) 
227     {
228         int gnum = 0;
229         bool esc = false;
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)
235         {
236             if (!esc && str[i] == '\\')
237             {
238                 esc = true;
239                 continue;
240             }
241             if (!esc && str[i] == '(') //group starts
242             {
243                 gnum++;
244                 if (i+1 < str.size() && str[i+1] == '?') //group with attrs 
245                 {
246                     i++;
247                     if (i+1 < str.size() && str[i+1] == ':') //non-capturing
248                     {
249                         if (gnum > 0) gnum--;
250                         i++;
251                         continue;
252                     }
253                     if (i+1 < str.size() && str[i+1] == 'P') //optional, python
254                         i++;
255                     if (i+1 < str.size() && str[i+1] == '<') //named
256                     {
257                         i++;
258                         std::string gname;
259                         bool term = false;
260                         while (++i < str.size())
261                         {
262                             if (str[i] == '>') { term = true; break; }
263                             if (!isalnum(str[i])) 
264                                 throw mp::filter::FilterException
265                                     ("Only alphanumeric chars allowed, found "
266                                      " in '" 
267                                      + str 
268                                      + "' at " 
269                                      + boost::lexical_cast<std::string>(i)); 
270                             gname += str[i];
271                         }
272                         if (!term)
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);
279                     }
280                 }
281             }
282             esc = false;
283         }
284         groups_bynum_vec.push_back(groups_bynum);
285     }
286 }
287
288 std::string yf::HttpRewrite::sub_vars (const std::string & in, 
289         const std::map<std::string, std::string> & vars)
290 {
291     std::string out;
292     bool esc = false;
293     for (unsigned i = 0; i < in.size(); ++i)
294     {
295         if (!esc && in[i] == '\\')
296         {
297             esc = true;
298             continue;
299         }
300         if (!esc && in[i] == '$') //var
301         {
302             if (i+1 < in.size() && in[i+1] == '{') //ref prefix
303             {
304                 ++i;
305                 std::string name;
306                 bool term = false;
307                 while (++i < in.size()) 
308                 {
309                     if (in[i] == '}') { term = true; break; }
310                     name += in[i];
311                 }
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
316                     = vars.find(name);
317                 if (it != vars.end())
318                 {
319                     out += it->second;
320                 }
321             }
322             else
323             {
324                 throw mp::filter::FilterException
325                     ("Malformed or trimmed var ref in '"
326                      +in+"' at "+boost::lexical_cast<std::string>(i)); 
327             }
328             continue;
329         }
330         //passthru
331         out += in[i];
332         esc = false;
333     }
334     return out;
335 }
336
337 void yf::HttpRewrite::configure(
338         const spair_vec req_uri_pats,
339         const spair_vec res_uri_pats)
340 {
341     //TODO should we really copy them out?
342     this->req_uri_pats = req_uri_pats;
343     this->res_uri_pats = res_uri_pats;
344     //pick up names
345     parse_groups(req_uri_pats, req_groups_bynum);
346     parse_groups(res_uri_pats, res_groups_bynum);
347 }
348
349
350 static void configure_rules(const xmlNode *ptr, yf::HttpRewrite::spair_vec & dest)
351 {
352     for (ptr = ptr->children; ptr; ptr = ptr->next)
353     {
354         if (ptr->type != XML_ELEMENT_NODE)
355             continue;
356         else if (!strcmp((const char *) ptr->name, "rewrite"))
357         {
358             std::string from, to;
359             const struct _xmlAttr *attr;
360             for (attr = ptr->properties; attr; attr = attr->next)
361             {
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);
366                 else
367                     throw mp::filter::FilterException
368                         ("Bad attribute "
369                          + std::string((const char *) attr->name)
370                          + " in rewrite section of http_rewrite");
371             }
372             yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'", 
373                     from.c_str(), to.c_str());
374             if (!from.empty())
375                 dest.push_back(std::make_pair(from, to));
376         }
377         else
378         {
379             throw mp::filter::FilterException
380                 ("Bad element o"
381                  + std::string((const char *) ptr->name)
382                  + " in http_rewrite1 filter");
383         }
384     }
385 }
386
387 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
388         const char *path)
389 {
390     spair_vec req_uri_pats;
391     spair_vec res_uri_pats;
392     for (ptr = ptr->children; ptr; ptr = ptr->next)
393     {
394         if (ptr->type != XML_ELEMENT_NODE)
395             continue;
396         else if (!strcmp((const char *) ptr->name, "request"))
397         {
398             configure_rules(ptr, req_uri_pats);
399         }
400         else if (!strcmp((const char *) ptr->name, "response"))
401         {
402             configure_rules(ptr, res_uri_pats);
403         }
404         else
405         {
406             throw mp::filter::FilterException
407                 ("Bad element "
408                  + std::string((const char *) ptr->name)
409                  + " in http_rewrite1 filter");
410         }
411     }
412     configure(req_uri_pats, res_uri_pats);
413 }
414
415 static mp::filter::Base* filter_creator()
416 {
417     return new mp::filter::HttpRewrite;
418 }
419
420 extern "C" {
421     struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
422         0,
423         "http_rewrite",
424         filter_creator
425     };
426 }
427
428
429 /*
430  * Local variables:
431  * c-basic-offset: 4
432  * c-file-style: "Stroustrup"
433  * indent-tabs-mode: nil
434  * End:
435  * vim: shiftwidth=4 tabstop=8 expandtab
436  */
437