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