Log when the filter is invoked
[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     std::cout << "HttpRewrite begins...." << std::endl;
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         std::cout << ">> Request headers" << std::endl;
62         rewrite_headers(o, hreq->headers, vars);
63         rewrite_body(o, &hreq->content_buf, &hreq->content_len, vars);
64         package.request() = gdu;
65     }
66     package.move();
67     gdu = package.response().get();
68     if (gdu && gdu->which == Z_GDU_HTTP_Response)
69     {
70         Z_HTTP_Response *hres = gdu->u.HTTP_Response;
71         yaz_log(YLOG_DEBUG, "Response %d", hres->code);
72         mp::odr o;
73         std::cout << "<< Respose headers" << std::endl;
74         rewrite_headers(o, hres->headers, vars);
75         rewrite_body(o, &hres->content_buf, &hres->content_len, vars);
76         package.response() = gdu;
77     }
78 }
79
80 void yf::HttpRewrite::rewrite_reqline (mp::odr & o, Z_HTTP_Request *hreq,
81         std::map<std::string, std::string> & vars) const 
82 {
83     //rewrite the request line
84     std::string path;
85     if (strstr(hreq->path, "http://") == hreq->path)
86     {
87         std::cout << "Path in the method line is absolute, " 
88             "possibly a proxy request\n";
89         path += hreq->path;
90     }
91     else
92     {
93         //TODO what about proto
94         path += z_HTTP_header_lookup(hreq->headers, "Host");
95         path += hreq->path; 
96     }
97     std::cout << "Proxy request URL is " << path << std::endl;
98     std::string npath = 
99         test_patterns(vars, path, req_uri_pats, req_groups_bynum);
100     std::cout << "Resp request URL is " << npath << std::endl;
101     if (!npath.empty())
102         hreq->path = odr_strdup(o, npath.c_str());
103 }
104
105 void yf::HttpRewrite::rewrite_headers (mp::odr & o, Z_HTTP_Header *headers,
106         std::map<std::string, std::string> & vars) const 
107 {
108     for (Z_HTTP_Header *header = headers;
109             header != 0; 
110             header = header->next) 
111     {
112         std::string sheader(header->name);
113         sheader += ": ";
114         sheader += header->value;
115         std::cout << header->name << ": " << header->value << std::endl;
116         std::string out = test_patterns(vars, 
117                 sheader, 
118                 req_uri_pats, req_groups_bynum);
119         if (!out.empty()) 
120         {
121             size_t pos = out.find(": ");
122             if (pos == std::string::npos)
123             {
124                 std::cout << "Header malformed during rewrite, ignoring";
125                 continue;
126             }
127             header->name = odr_strdup(o, out.substr(0, pos).c_str());
128             header->value = odr_strdup(o, out.substr(pos+2, 
129                         std::string::npos).c_str());
130         }
131     }
132 }
133
134 void yf::HttpRewrite::rewrite_body (mp::odr & o, char **content_buf, int *content_len,
135         std::map<std::string, std::string> & vars) const 
136 {
137     if (*content_buf)
138     {
139         std::string body(*content_buf);
140         std::string nbody = 
141             test_patterns(vars, body, req_uri_pats, req_groups_bynum);
142         if (!nbody.empty())
143         {
144             *content_buf = odr_strdup(o, nbody.c_str());
145             *content_len = nbody.size();
146         }
147     }
148 }
149
150 /**
151  * Tests pattern from the vector in order and executes recipe on
152  the first match.
153  */
154 const std::string yf::HttpRewrite::test_patterns(
155         std::map<std::string, std::string> & vars,
156         const std::string & txt, 
157         const spair_vec & uri_pats,
158         const std::vector<std::map<int, std::string> > & groups_bynum_vec)
159     const
160 {
161     for (unsigned i = 0; i < uri_pats.size(); i++) 
162     {
163         std::string out = search_replace(vars, txt, 
164                 uri_pats[i].first, uri_pats[i].second,
165                 groups_bynum_vec[i]);
166         if (!out.empty()) return out;
167     }
168     return "";
169 }
170
171
172 const std::string yf::HttpRewrite::search_replace(
173         std::map<std::string, std::string> & vars,
174         const std::string & txt,
175         const std::string & uri_re,
176         const std::string & uri_pat,
177         const std::map<int, std::string> & groups_bynum) const
178 {
179     //exec regex against value
180     boost::regex re(uri_re);
181     boost::smatch what;
182     std::string::const_iterator start, end;
183     start = txt.begin();
184     end = txt.end();
185     std::string out;
186     while (regex_search(start, end, what, re)) //find next full match
187     {
188         unsigned i;
189         for (i = 1; i < what.size(); ++i)
190         {
191             //check if the group is named
192             std::map<int, std::string>::const_iterator it
193                 = groups_bynum.find(i);
194             if (it != groups_bynum.end()) 
195             {   //it is
196                 std::string name = it->second;
197                 if (!what[i].str().empty())
198                     vars[name] = what[i];
199             }
200
201         }
202         //prepare replacement string
203         std::string rvalue = sub_vars(uri_pat, vars);
204         //rewrite value
205         std::string rhvalue = what.prefix().str() 
206             + rvalue + what.suffix().str();
207         std::cout << "! Rewritten '"+what.str(0)+"' to '"+rvalue+"'\n";
208         out += rhvalue;
209         start = what[0].second; //move search forward
210     }
211     return out;
212 }
213
214 void yf::HttpRewrite::parse_groups(
215         const spair_vec & uri_pats,
216         std::vector<std::map<int, std::string> > & groups_bynum_vec)
217 {
218     for (unsigned h = 0; h < uri_pats.size(); h++) 
219     {
220         int gnum = 0;
221         bool esc = false;
222         //regex is first, subpat is second
223         std::string str = uri_pats[h].first;
224         //for each pair we have an indexing map
225         std::map<int, std::string> groups_bynum;
226         for (unsigned i = 0; i < str.size(); ++i)
227         {
228             if (!esc && str[i] == '\\')
229             {
230                 esc = true;
231                 continue;
232             }
233             if (!esc && str[i] == '(') //group starts
234             {
235                 gnum++;
236                 if (i+1 < str.size() && str[i+1] == '?') //group with attrs 
237                 {
238                     i++;
239                     if (i+1 < str.size() && str[i+1] == ':') //non-capturing
240                     {
241                         if (gnum > 0) gnum--;
242                         i++;
243                         continue;
244                     }
245                     if (i+1 < str.size() && str[i+1] == 'P') //optional, python
246                         i++;
247                     if (i+1 < str.size() && str[i+1] == '<') //named
248                     {
249                         i++;
250                         std::string gname;
251                         bool term = false;
252                         while (++i < str.size())
253                         {
254                             if (str[i] == '>') { term = true; break; }
255                             if (!isalnum(str[i])) 
256                                 throw mp::filter::FilterException
257                                     ("Only alphanumeric chars allowed, found "
258                                      " in '" 
259                                      + str 
260                                      + "' at " 
261                                      + boost::lexical_cast<std::string>(i)); 
262                             gname += str[i];
263                         }
264                         if (!term)
265                             throw mp::filter::FilterException
266                                 ("Unterminated group name '" + gname 
267                                  + " in '" + str +"'");
268                         groups_bynum[gnum] = gname;
269                         std::cout << "Found named group '" << gname 
270                             << "' at $" << gnum << std::endl;
271                     }
272                 }
273             }
274             esc = false;
275         }
276         groups_bynum_vec.push_back(groups_bynum);
277     }
278 }
279
280 std::string yf::HttpRewrite::sub_vars (const std::string & in, 
281         const std::map<std::string, std::string> & vars)
282 {
283     std::string out;
284     bool esc = false;
285     for (unsigned i = 0; i < in.size(); ++i)
286     {
287         if (!esc && in[i] == '\\')
288         {
289             esc = true;
290             continue;
291         }
292         if (!esc && in[i] == '$') //var
293         {
294             if (i+1 < in.size() && in[i+1] == '{') //ref prefix
295             {
296                 ++i;
297                 std::string name;
298                 bool term = false;
299                 while (++i < in.size()) 
300                 {
301                     if (in[i] == '}') { term = true; break; }
302                     name += in[i];
303                 }
304                 if (!term) throw mp::filter::FilterException
305                     ("Unterminated var ref in '"+in+"' at "
306                      + boost::lexical_cast<std::string>(i));
307                 std::map<std::string, std::string>::const_iterator it
308                     = vars.find(name);
309                 if (it != vars.end())
310                 {
311                     out += it->second;
312                 }
313             }
314             else
315             {
316                 throw mp::filter::FilterException
317                     ("Malformed or trimmed var ref in '"
318                      +in+"' at "+boost::lexical_cast<std::string>(i)); 
319             }
320             continue;
321         }
322         //passthru
323         out += in[i];
324         esc = false;
325     }
326     return out;
327 }
328
329 void yf::HttpRewrite::configure(
330         const spair_vec req_uri_pats,
331         const spair_vec res_uri_pats)
332 {
333     //TODO should we really copy them out?
334     this->req_uri_pats = req_uri_pats;
335     this->res_uri_pats = res_uri_pats;
336     //pick up names
337     parse_groups(req_uri_pats, req_groups_bynum);
338     parse_groups(res_uri_pats, res_groups_bynum);
339 }
340
341
342 static void configure_rules(const xmlNode *ptr, yf::HttpRewrite::spair_vec & dest)
343 {
344     for (ptr = ptr->children; ptr; ptr = ptr->next)
345     {
346         if (ptr->type != XML_ELEMENT_NODE)
347             continue;
348         else if (!strcmp((const char *) ptr->name, "rewrite"))
349         {
350             std::string from, to;
351             const struct _xmlAttr *attr;
352             for (attr = ptr->properties; attr; attr = attr->next)
353             {
354                 if (!strcmp((const char *) attr->name,  "from"))
355                     from = mp::xml::get_text(attr->children);
356                 else if (!strcmp((const char *) attr->name,  "to"))
357                     to = mp::xml::get_text(attr->children);
358                 else
359                     throw mp::filter::FilterException
360                         ("Bad attribute "
361                          + std::string((const char *) attr->name)
362                          + " in rewrite section of http_rewrite");
363             }
364             std::cout << "Found rewrite rule from=" << from << " to " << to << std::endl;
365             if (!from.empty())
366                 dest.push_back(std::make_pair(from, to));
367         }
368         else
369         {
370             throw mp::filter::FilterException
371                 ("Bad element o"
372                  + std::string((const char *) ptr->name)
373                  + " in http_rewrite1 filter");
374         }
375     }
376 }
377
378 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
379         const char *path)
380 {
381     spair_vec req_uri_pats;
382     spair_vec res_uri_pats;
383     for (ptr = ptr->children; ptr; ptr = ptr->next)
384     {
385         if (ptr->type != XML_ELEMENT_NODE)
386             continue;
387         else if (!strcmp((const char *) ptr->name, "request"))
388         {
389             std::cout << "Found request rule" << std::endl;
390             configure_rules(ptr, req_uri_pats);
391         }
392         else if (!strcmp((const char *) ptr->name, "response"))
393         {
394             configure_rules(ptr, res_uri_pats);
395         }
396         else
397         {
398             throw mp::filter::FilterException
399                 ("Bad element "
400                  + std::string((const char *) ptr->name)
401                  + " in http_rewrite1 filter");
402         }
403     }
404     configure(req_uri_pats, res_uri_pats);
405 }
406
407 static mp::filter::Base* filter_creator()
408 {
409     return new mp::filter::HttpRewrite;
410 }
411
412 extern "C" {
413     struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
414         0,
415         "http_rewrite",
416         filter_creator
417     };
418 }
419
420
421 /*
422  * Local variables:
423  * c-basic-offset: 4
424  * c-file-style: "Stroustrup"
425  * indent-tabs-mode: nil
426  * End:
427  * vim: shiftwidth=4 tabstop=8 expandtab
428  */
429