Try to comapte buffers
[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     std::cout << "About to rewrite body: " << *content_buf;
145     if (*content_buf)
146     {
147         std::string body(*content_buf);
148         std::string nbody = 
149             test_patterns(vars, body, uri_pats, groups_bynum);
150         if (!nbody.empty())
151         {
152             *content_buf = odr_strdup(o, nbody.c_str());
153             *content_len = nbody.size();
154         }
155     }
156 }
157
158 /**
159  * Tests pattern from the vector in order and executes recipe on
160  the first match.
161  */
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)
167     const
168 {
169     for (unsigned i = 0; i < uri_pats.size(); i++) 
170     {
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;
175     }
176     return "";
177 }
178
179
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
186 {
187     //exec regex against value
188     boost::regex re(uri_re);
189     boost::smatch what;
190     std::string::const_iterator start, end;
191     start = txt.begin();
192     end = txt.end();
193     std::string out;
194     while (regex_search(start, end, what, re)) //find next full match
195     {
196         unsigned i;
197         for (i = 1; i < what.size(); ++i)
198         {
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()) 
203             {   //it is
204                 if (!what[i].str().empty())
205                     vars[it->second] = what[i];
206             }
207
208         }
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);
214         out.append(rvalue);
215         start = what[0].second; //move search forward
216     }
217     //if we had a match cat the last part
218     if (start != txt.begin())
219         out.append(start, end);
220     return out;
221 }
222
223 void yf::HttpRewrite::parse_groups(
224         const spair_vec & uri_pats,
225         std::vector<std::map<int, std::string> > & groups_bynum_vec)
226 {
227     for (unsigned h = 0; h < uri_pats.size(); h++) 
228     {
229         int gnum = 0;
230         bool esc = false;
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)
236         {
237             if (!esc && str[i] == '\\')
238             {
239                 esc = true;
240                 continue;
241             }
242             if (!esc && str[i] == '(') //group starts
243             {
244                 gnum++;
245                 if (i+1 < str.size() && str[i+1] == '?') //group with attrs 
246                 {
247                     i++;
248                     if (i+1 < str.size() && str[i+1] == ':') //non-capturing
249                     {
250                         if (gnum > 0) gnum--;
251                         i++;
252                         continue;
253                     }
254                     if (i+1 < str.size() && str[i+1] == 'P') //optional, python
255                         i++;
256                     if (i+1 < str.size() && str[i+1] == '<') //named
257                     {
258                         i++;
259                         std::string gname;
260                         bool term = false;
261                         while (++i < str.size())
262                         {
263                             if (str[i] == '>') { term = true; break; }
264                             if (!isalnum(str[i])) 
265                                 throw mp::filter::FilterException
266                                     ("Only alphanumeric chars allowed, found "
267                                      " in '" 
268                                      + str 
269                                      + "' at " 
270                                      + boost::lexical_cast<std::string>(i)); 
271                             gname += str[i];
272                         }
273                         if (!term)
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);
280                     }
281                 }
282             }
283             esc = false;
284         }
285         groups_bynum_vec.push_back(groups_bynum);
286     }
287 }
288
289 std::string yf::HttpRewrite::sub_vars (const std::string & in, 
290         const std::map<std::string, std::string> & vars)
291 {
292     std::string out;
293     bool esc = false;
294     for (unsigned i = 0; i < in.size(); ++i)
295     {
296         if (!esc && in[i] == '\\')
297         {
298             esc = true;
299             continue;
300         }
301         if (!esc && in[i] == '$') //var
302         {
303             if (i+1 < in.size() && in[i+1] == '{') //ref prefix
304             {
305                 ++i;
306                 std::string name;
307                 bool term = false;
308                 while (++i < in.size()) 
309                 {
310                     if (in[i] == '}') { term = true; break; }
311                     name += in[i];
312                 }
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
317                     = vars.find(name);
318                 if (it != vars.end())
319                 {
320                     out += it->second;
321                 }
322             }
323             else
324             {
325                 throw mp::filter::FilterException
326                     ("Malformed or trimmed var ref in '"
327                      +in+"' at "+boost::lexical_cast<std::string>(i)); 
328             }
329             continue;
330         }
331         //passthru
332         out += in[i];
333         esc = false;
334     }
335     return out;
336 }
337
338 void yf::HttpRewrite::configure(
339         const spair_vec req_uri_pats,
340         const spair_vec res_uri_pats)
341 {
342     //TODO should we really copy them out?
343     this->req_uri_pats = req_uri_pats;
344     this->res_uri_pats = res_uri_pats;
345     //pick up names
346     parse_groups(req_uri_pats, req_groups_bynum);
347     parse_groups(res_uri_pats, res_groups_bynum);
348 }
349
350
351 static void configure_rules(const xmlNode *ptr, yf::HttpRewrite::spair_vec & dest)
352 {
353     for (ptr = ptr->children; ptr; ptr = ptr->next)
354     {
355         if (ptr->type != XML_ELEMENT_NODE)
356             continue;
357         else if (!strcmp((const char *) ptr->name, "rewrite"))
358         {
359             std::string from, to;
360             const struct _xmlAttr *attr;
361             for (attr = ptr->properties; attr; attr = attr->next)
362             {
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);
367                 else
368                     throw mp::filter::FilterException
369                         ("Bad attribute "
370                          + std::string((const char *) attr->name)
371                          + " in rewrite section of http_rewrite");
372             }
373             yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'", 
374                     from.c_str(), to.c_str());
375             if (!from.empty())
376                 dest.push_back(std::make_pair(from, to));
377         }
378         else
379         {
380             throw mp::filter::FilterException
381                 ("Bad element o"
382                  + std::string((const char *) ptr->name)
383                  + " in http_rewrite1 filter");
384         }
385     }
386 }
387
388 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
389         const char *path)
390 {
391     spair_vec req_uri_pats;
392     spair_vec res_uri_pats;
393     for (ptr = ptr->children; ptr; ptr = ptr->next)
394     {
395         if (ptr->type != XML_ELEMENT_NODE)
396             continue;
397         else if (!strcmp((const char *) ptr->name, "request"))
398         {
399             configure_rules(ptr, req_uri_pats);
400         }
401         else if (!strcmp((const char *) ptr->name, "response"))
402         {
403             configure_rules(ptr, res_uri_pats);
404         }
405         else
406         {
407             throw mp::filter::FilterException
408                 ("Bad element "
409                  + std::string((const char *) ptr->name)
410                  + " in http_rewrite1 filter");
411         }
412     }
413     configure(req_uri_pats, res_uri_pats);
414 }
415
416 static mp::filter::Base* filter_creator()
417 {
418     return new mp::filter::HttpRewrite;
419 }
420
421 extern "C" {
422     struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
423         0,
424         "http_rewrite",
425         filter_creator
426     };
427 }
428
429
430 /*
431  * Local variables:
432  * c-basic-offset: 4
433  * c-file-style: "Stroustrup"
434  * indent-tabs-mode: nil
435  * End:
436  * vim: shiftwidth=4 tabstop=8 expandtab
437  */
438