Factor out impl from test
[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         std::cout << "Response " << 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 void yf::HttpRewrite::configure(const xmlNode* ptr, bool test_only, const char *path) {};
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 (int 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         std::cout << "! Rewritten '"+what.str(0)+"' to '"+rvalue+"'\n";
210         out += rhvalue;
211         start = what[0].second; //move search forward
212     }
213     return out;
214 }
215
216 void yf::HttpRewrite::parse_groups(
217         const spair_vec & uri_pats,
218         std::vector<std::map<int, std::string> > & groups_bynum_vec)
219 {
220     for (int h = 0; h < uri_pats.size(); h++) 
221     {
222         int gnum = 0;
223         bool esc = false;
224         //regex is first, subpat is second
225         std::string str = uri_pats[h].first;
226         //for each pair we have an indexing map
227         std::map<int, std::string> groups_bynum;
228         for (int i = 0; i < str.size(); ++i)
229         {
230             if (!esc && str[i] == '\\')
231             {
232                 esc = true;
233                 continue;
234             }
235             if (!esc && str[i] == '(') //group starts
236             {
237                 gnum++;
238                 if (i+1 < str.size() && str[i+1] == '?') //group with attrs 
239                 {
240                     i++;
241                     if (i+1 < str.size() && str[i+1] == ':') //non-capturing
242                     {
243                         if (gnum > 0) gnum--;
244                         i++;
245                         continue;
246                     }
247                     if (i+1 < str.size() && str[i+1] == 'P') //optional, python
248                         i++;
249                     if (i+1 < str.size() && str[i+1] == '<') //named
250                     {
251                         i++;
252                         std::string gname;
253                         bool term = false;
254                         while (++i < str.size())
255                         {
256                             if (str[i] == '>') { term = true; break; }
257                             if (!isalnum(str[i])) 
258                                 throw mp::filter::FilterException
259                                     ("Only alphanumeric chars allowed, found "
260                                      " in '" 
261                                      + str 
262                                      + "' at " 
263                                      + boost::lexical_cast<std::string>(i)); 
264                             gname += str[i];
265                         }
266                         if (!term)
267                             throw mp::filter::FilterException
268                                 ("Unterminated group name '" + gname 
269                                  + " in '" + str +"'");
270                         groups_bynum[gnum] = gname;
271                         std::cout << "Found named group '" << gname 
272                             << "' at $" << gnum << std::endl;
273                     }
274                 }
275             }
276             esc = false;
277         }
278         groups_bynum_vec.push_back(groups_bynum);
279     }
280 }
281
282 std::string yf::HttpRewrite::sub_vars (const std::string & in, 
283         const std::map<std::string, std::string> & vars)
284 {
285     std::string out;
286     bool esc = false;
287     for (int i = 0; i < in.size(); ++i)
288     {
289         if (!esc && in[i] == '\\')
290         {
291             esc = true;
292             continue;
293         }
294         if (!esc && in[i] == '$') //var
295         {
296             if (i+1 < in.size() && in[i+1] == '{') //ref prefix
297             {
298                 ++i;
299                 std::string name;
300                 bool term = false;
301                 while (++i < in.size()) 
302                 {
303                     if (in[i] == '}') { term = true; break; }
304                     name += in[i];
305                 }
306                 if (!term) throw mp::filter::FilterException
307                     ("Unterminated var ref in '"+in+"' at "
308                      + boost::lexical_cast<std::string>(i));
309                 std::map<std::string, std::string>::const_iterator it
310                     = vars.find(name);
311                 if (it != vars.end())
312                 {
313                     out += it->second;
314                 }
315             }
316             else
317             {
318                 throw mp::filter::FilterException
319                     ("Malformed or trimmed var ref in '"
320                      +in+"' at "+boost::lexical_cast<std::string>(i)); 
321             }
322             continue;
323         }
324         //passthru
325         out += in[i];
326         esc = false;
327     }
328     return out;
329 }
330
331 void yf::HttpRewrite::configure(
332         const spair_vec req_uri_pats,
333         const spair_vec res_uri_pats)
334 {
335     //TODO should we really copy them out?
336     this->req_uri_pats = req_uri_pats;
337     this->res_uri_pats = res_uri_pats;
338     //pick up names
339     parse_groups(req_uri_pats, req_groups_bynum);
340     parse_groups(res_uri_pats, res_groups_bynum);
341 }
342
343 static mp::filter::Base* filter_creator()
344 {
345     return new mp::filter::HttpRewrite;
346 }
347
348 extern "C" {
349     struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
350         0,
351         "http_rewrite",
352         filter_creator
353     };
354 }
355
356
357 /*
358  * Local variables:
359  * c-basic-offset: 4
360  * c-file-style: "Stroustrup"
361  * indent-tabs-mode: nil
362  * End:
363  * vim: shiftwidth=4 tabstop=8 expandtab
364  */
365