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