Use all Replaces from/to in each buffer
[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 #include "html_parser.hpp"
25
26 #include <yaz/zgdu.h>
27 #include <yaz/log.h>
28
29 #include <stack>
30 #include <boost/regex.hpp>
31 #include <boost/lexical_cast.hpp>
32 #include <boost/algorithm/string.hpp>
33
34 #include <map>
35
36 namespace mp = metaproxy_1;
37 namespace yf = mp::filter;
38
39 namespace metaproxy_1 {
40     namespace filter {
41         class HttpRewrite::Replace {
42         public:
43             boost::regex re;
44             boost::smatch what;
45             std::string recipe;
46             std::map<int, std::string> group_index;
47             std::string sub_vars(
48                 const std::map<std::string, std::string> & vars) const;
49             void parse_groups(std::string pattern);
50         };
51
52         class HttpRewrite::Rule {
53         public:
54             std::list<Replace> replace_list;
55             const std::string test_patterns(
56                 std::map<std::string, std::string> & vars,
57                 const std::string & txt);
58         };
59         class HttpRewrite::Within {
60         public:
61             std::string header;
62             std::string attr;
63             std::string tag;
64             bool reqline;
65             RulePtr rule;
66         };
67
68         class HttpRewrite::Phase {
69         public:
70             Phase();
71             std::list<Within> within_list;
72             int m_verbose;
73             void rewrite_reqline(mp::odr & o, Z_HTTP_Request *hreq,
74                 std::map<std::string, std::string> & vars) const;
75             void rewrite_headers(mp::odr & o, Z_HTTP_Header *headers,
76                 std::map<std::string, std::string> & vars) const;
77             void rewrite_body(mp::odr & o,
78                 char **content_buf, int *content_len,
79                 std::map<std::string, std::string> & vars) const;
80         };
81         class HttpRewrite::Event : public HTMLParserEvent {
82             void openTagStart(const char *tag, int tag_len);
83             void anyTagEnd(const char *tag, int tag_len, int close_it);
84             void attribute(const char *tag, int tag_len,
85                            const char *attr, int attr_len,
86                            const char *value, int val_len,
87                            const char *sep);
88             void closeTag(const char *tag, int tag_len);
89             void text(const char *value, int len);
90             const Phase *m_phase;
91             WRBUF m_w;
92             std::stack<std::list<Within>::const_iterator> s_within;
93             std::map<std::string, std::string> &m_vars;
94         public:
95             Event(const Phase *p, std::map<std::string, std::string> &vars);
96             ~Event();
97             const char *result();
98         };
99     }
100 }
101
102 yf::HttpRewrite::HttpRewrite() :
103     req_phase(new Phase), res_phase(new Phase)
104 {
105 }
106
107 yf::HttpRewrite::~HttpRewrite()
108 {
109 }
110
111 void yf::HttpRewrite::process(mp::Package & package) const
112 {
113     yaz_log(YLOG_LOG, "HttpRewrite begins....");
114     Z_GDU *gdu = package.request().get();
115     //map of request/response vars
116     std::map<std::string, std::string> vars;
117     //we have an http req
118     if (gdu && gdu->which == Z_GDU_HTTP_Request)
119     {
120         Z_HTTP_Request *hreq = gdu->u.HTTP_Request;
121         mp::odr o;
122         req_phase->rewrite_reqline(o, hreq, vars);
123         yaz_log(YLOG_LOG, ">> Request headers");
124         req_phase->rewrite_headers(o, hreq->headers, vars);
125         req_phase->rewrite_body(o,
126                 &hreq->content_buf, &hreq->content_len, vars);
127         package.request() = gdu;
128     }
129     package.move();
130     gdu = package.response().get();
131     if (gdu && gdu->which == Z_GDU_HTTP_Response)
132     {
133         Z_HTTP_Response *hres = gdu->u.HTTP_Response;
134         yaz_log(YLOG_LOG, "Response code %d", hres->code);
135         mp::odr o;
136         yaz_log(YLOG_LOG, "<< Respose headers");
137         res_phase->rewrite_headers(o, hres->headers, vars);
138         res_phase->rewrite_body(o, &hres->content_buf,
139                 &hres->content_len, vars);
140         package.response() = gdu;
141     }
142 }
143
144 void yf::HttpRewrite::Phase::rewrite_reqline (mp::odr & o,
145         Z_HTTP_Request *hreq,
146         std::map<std::string, std::string> & vars) const
147 {
148     //rewrite the request line
149     std::string path;
150     if (strstr(hreq->path, "http://") == hreq->path)
151     {
152         yaz_log(YLOG_LOG, "Path in the method line is absolute, "
153             "possibly a proxy request");
154         path += hreq->path;
155     }
156     else
157     {
158         //TODO what about proto
159         path += "http://";
160         path += z_HTTP_header_lookup(hreq->headers, "Host");
161         path += hreq->path;
162     }
163
164
165     std::list<Within>::const_iterator it = within_list.begin();
166     for (; it != within_list.end(); it++)
167         if (it->reqline)
168         {
169             RulePtr rule = it->rule;
170             yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
171             std::string npath = rule->test_patterns(vars, path);
172             if (!npath.empty())
173             {
174                 yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
175                 hreq->path = odr_strdup(o, npath.c_str());
176             }
177         }
178 }
179
180 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
181         Z_HTTP_Header *headers,
182         std::map<std::string, std::string> & vars) const
183 {
184     for (Z_HTTP_Header *header = headers; header; header = header->next)
185     {
186         std::list<Within>::const_iterator it = within_list.begin();
187         for (; it != within_list.end(); it++)
188         {
189             if (it->header.length() > 0 &&
190                 yaz_strcasecmp(it->header.c_str(), header->name) == 0)
191             {
192                 std::string sheader(header->name);
193                 sheader += ": ";
194                 sheader += header->value;
195
196                 RulePtr rule = it->rule;
197                 std::string out = rule->test_patterns(vars, sheader);
198                 if (!out.empty())
199                 {
200                     size_t pos = out.find(": ");
201                     if (pos == std::string::npos)
202                     {
203                         yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
204                         continue;
205                     }
206                     header->name = odr_strdup(o, out.substr(0, pos).c_str());
207                     header->value = odr_strdup(o,
208                                                out.substr(pos + 2,
209                                                           std::string::npos).c_str());
210                 }
211             }
212         }
213     }
214 }
215
216 void yf::HttpRewrite::Phase::rewrite_body(mp::odr & o,
217         char **content_buf,
218         int *content_len,
219         std::map<std::string, std::string> & vars) const
220 {
221     if (*content_buf)
222     {
223         int i;
224         for (i = 0; i < *content_len; i++)
225             if ((*content_buf)[i] == 0)
226                 return;  // binary content. skip
227
228         HTMLParser parser;
229         Event ev(this, vars);
230
231         parser.set_verbose(m_verbose);
232
233         std::string buf(*content_buf, *content_len);
234
235         parser.parse(ev, buf.c_str());
236         const char *res = ev.result();
237         *content_buf = odr_strdup(o, res);
238         *content_len = strlen(res);
239     }
240 }
241
242 yf::HttpRewrite::Event::Event(const Phase *p,
243                               std::map<std::string, std::string> & vars
244     ) : m_phase(p), m_vars(vars)
245 {
246     m_w = wrbuf_alloc();
247 }
248
249 yf::HttpRewrite::Event::~Event()
250 {
251     wrbuf_destroy(m_w);
252 }
253
254 const char *yf::HttpRewrite::Event::result()
255 {
256     return wrbuf_cstr(m_w);
257 }
258
259 void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
260 {
261     wrbuf_putc(m_w, '<');
262     wrbuf_write(m_w, tag, tag_len);
263
264     std::string t(tag, tag_len);
265     std::list<Within>::const_iterator it = m_phase->within_list.begin();
266     for (; it != m_phase->within_list.end(); it++)
267     {
268         if (it->tag.length() > 0 && yaz_strcasecmp(it->tag.c_str(),
269                                                    t.c_str()) == 0)
270         {
271             std::vector<std::string> attr;
272             boost::split(attr, it->attr, boost::is_any_of(","));
273             size_t i;
274             for (i = 0; i < attr.size(); i++)
275             {
276                 if (attr[i].compare("#text") == 0)
277                 {
278                     s_within.push(it);
279                     return;
280                 }
281             }
282         }
283     }
284 }
285
286 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
287                                        int close_it)
288 {
289     if (close_it)
290     {
291         if (!s_within.empty())
292         {
293             std::list<Within>::const_iterator it = s_within.top();
294             std::string t(tag, tag_len);
295             if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
296                 s_within.pop();
297         }
298     }
299     if (close_it)
300         wrbuf_putc(m_w, '/');
301     wrbuf_putc(m_w, '>');
302 }
303
304 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
305                                        const char *attr, int attr_len,
306                                        const char *value, int val_len,
307                                        const char *sep)
308 {
309     std::list<Within>::const_iterator it = m_phase->within_list.begin();
310     bool subst = false;
311
312     for (; it != m_phase->within_list.end(); it++)
313     {
314         std::string t(tag, tag_len);
315         if (it->tag.length() == 0 ||
316             yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
317         {
318             std::string a(attr, attr_len);
319             std::vector<std::string> attr;
320             boost::split(attr, it->attr, boost::is_any_of(","));
321             size_t i;
322             for (i = 0; i < attr.size(); i++)
323             {
324                 if (attr[i].compare("#text") &&
325                     yaz_strcasecmp(attr[i].c_str(), a.c_str()) == 0)
326                     subst = true;
327             }
328         }
329         if (subst)
330             break;
331     }
332
333     wrbuf_putc(m_w, ' ');
334     wrbuf_write(m_w, attr, attr_len);
335     if (value)
336     {
337         wrbuf_puts(m_w, "=");
338         wrbuf_puts(m_w, sep);
339
340         std::string output;
341         if (subst)
342         {
343             std::string input(value, val_len);
344             output = it->rule->test_patterns(m_vars, input);
345         }
346         if (output.empty())
347             wrbuf_write(m_w, value, val_len);
348         else
349             wrbuf_puts(m_w, output.c_str());
350         wrbuf_puts(m_w, sep);
351     }
352 }
353
354 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
355 {
356     if (!s_within.empty())
357     {
358         std::list<Within>::const_iterator it = s_within.top();
359         std::string t(tag, tag_len);
360         if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
361             s_within.pop();
362     }
363     wrbuf_puts(m_w, "</");
364     wrbuf_write(m_w, tag, tag_len);
365 }
366
367 void yf::HttpRewrite::Event::text(const char *value, int len)
368 {
369     std::list<Within>::const_iterator it = m_phase->within_list.end();
370     if (!s_within.empty())
371         it = s_within.top();
372     std::string output;
373     if (it != m_phase->within_list.end())
374     {
375         std::string input(value, len);
376         output = it->rule->test_patterns(m_vars, input);
377     }
378     if (output.empty())
379         wrbuf_write(m_w, value, len);
380     else
381         wrbuf_puts(m_w, output.c_str());
382 }
383
384 const std::string yf::HttpRewrite::Rule::test_patterns(
385         std::map<std::string, std::string> & vars,
386         const std::string & txt)
387 {
388     std::string out;
389     std::string::const_iterator start, end;
390     start = txt.begin();
391     end = txt.end();
392     while (1)
393     {
394         std::list<Replace>::iterator bit = replace_list.end();
395         {
396             std::string::const_iterator best_pos = txt.end();
397             std::list<Replace>::iterator it = replace_list.begin();
398             for (; it != replace_list.end(); it++)
399             {
400                 if (regex_search(start, end, it->what, it->re))
401                 {
402                     if (it->what[0].first < best_pos)
403                     {
404                         best_pos = it->what[0].first;
405                         bit = it;
406                     }
407                 }
408             }
409             if (bit == replace_list.end())
410                 break;
411         }
412
413         size_t i;
414         for (i = 1; i < bit->what.size(); ++i)
415         {
416             //check if the group is named
417             std::map<int, std::string>::const_iterator git
418                 = bit->group_index.find(i);
419             if (git != bit->group_index.end())
420             {   //it is
421                 vars[git->second] = bit->what[i];
422             }
423
424         }
425         //prepare replacement string
426         std::string rvalue = bit->sub_vars(vars);
427         yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
428                 bit->what.str(0).c_str(), rvalue.c_str());
429         out.append(start, bit->what[0].first);
430         out.append(rvalue);
431         start = bit->what[0].second; //move search forward
432     }
433     if (start != txt.begin())
434         out.append(start, end);
435     return out;
436 }
437
438 void yf::HttpRewrite::Replace::parse_groups(std::string pattern)
439 {
440     int gnum = 0;
441     bool esc = false;
442     const std::string &str = pattern;
443     std::string res;
444     yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
445     for (size_t i = 0; i < str.size(); ++i)
446     {
447         res += str[i];
448         if (!esc && str[i] == '\\')
449         {
450             esc = true;
451             continue;
452         }
453         if (!esc && str[i] == '(') //group starts
454         {
455             gnum++;
456             if (i+1 < str.size() && str[i+1] == '?') //group with attrs
457             {
458                 i++;
459                 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
460                 {
461                     if (gnum > 0) gnum--;
462                     res += str[i];
463                     i++;
464                     res += str[i];
465                     continue;
466                 }
467                 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
468                     i++;
469                 if (i+1 < str.size() && str[i+1] == '<') //named
470                 {
471                     i++;
472                     std::string gname;
473                     bool term = false;
474                     while (++i < str.size())
475                     {
476                         if (str[i] == '>') { term = true; break; }
477                         if (!isalnum(str[i]))
478                             throw mp::filter::FilterException
479                                 ("Only alphanumeric chars allowed, found "
480                                  " in '"
481                                  + str
482                                  + "' at "
483                                  + boost::lexical_cast<std::string>(i));
484                         gname += str[i];
485                     }
486                     if (!term)
487                         throw mp::filter::FilterException
488                             ("Unterminated group name '" + gname
489                              + " in '" + str +"'");
490                     group_index[gnum] = gname;
491                     yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
492                             gname.c_str(), gnum);
493                 }
494             }
495         }
496         esc = false;
497     }
498     re = res;
499 }
500
501 std::string yf::HttpRewrite::Replace::sub_vars(
502     const std::map<std::string, std::string> & vars) const
503 {
504     std::string out;
505     bool esc = false;
506     const std::string & in = recipe;
507     for (size_t i = 0; i < in.size(); ++i)
508     {
509         if (!esc && in[i] == '\\')
510         {
511             esc = true;
512             continue;
513         }
514         if (!esc && in[i] == '$') //var
515         {
516             if (i+1 < in.size() && in[i+1] == '{') //ref prefix
517             {
518                 ++i;
519                 std::string name;
520                 bool term = false;
521                 while (++i < in.size())
522                 {
523                     if (in[i] == '}') { term = true; break; }
524                     name += in[i];
525                 }
526                 if (!term) throw mp::filter::FilterException
527                     ("Unterminated var ref in '"+in+"' at "
528                      + boost::lexical_cast<std::string>(i));
529                 std::map<std::string, std::string>::const_iterator it
530                     = vars.find(name);
531                 if (it != vars.end())
532                 {
533                     out += it->second;
534                 }
535             }
536             else
537             {
538                 throw mp::filter::FilterException
539                     ("Malformed or trimmed var ref in '"
540                      +in+"' at "+boost::lexical_cast<std::string>(i));
541             }
542             continue;
543         }
544         //passthru
545         out += in[i];
546         esc = false;
547     }
548     return out;
549 }
550
551 yf::HttpRewrite::Phase::Phase() : m_verbose(0)
552 {
553 }
554
555 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
556 {
557     static const char *names[2] = { "verbose", 0 };
558     std::string values[1];
559     values[0] = "0";
560     mp::xml::parse_attr(ptr, names, values);
561
562     phase.m_verbose = atoi(values[0].c_str());
563
564     std::map<std::string, RulePtr > rules;
565     for (ptr = ptr->children; ptr; ptr = ptr->next)
566     {
567         if (ptr->type != XML_ELEMENT_NODE)
568             continue;
569         else if (!strcmp((const char *) ptr->name, "rule"))
570         {
571             static const char *names[2] = { "name", 0 };
572             std::string values[1];
573             values[0] = "default";
574             mp::xml::parse_attr(ptr, names, values);
575
576             RulePtr rule(new Rule);
577             for (xmlNode *p = ptr->children; p; p = p->next)
578             {
579                 if (p->type != XML_ELEMENT_NODE)
580                     continue;
581                 if (!strcmp((const char *) p->name, "rewrite"))
582                 {
583                     Replace replace;
584                     std::string from;
585                     const struct _xmlAttr *attr;
586                     for (attr = p->properties; attr; attr = attr->next)
587                     {
588                         if (!strcmp((const char *) attr->name,  "from"))
589                             from = mp::xml::get_text(attr->children);
590                         else if (!strcmp((const char *) attr->name,  "to"))
591                             replace.recipe = mp::xml::get_text(attr->children);
592                         else
593                             throw mp::filter::FilterException
594                                 ("Bad attribute "
595                                  + std::string((const char *) attr->name)
596                                  + " in rewrite section of http_rewrite");
597                     }
598                     yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
599                             from.c_str(), replace.recipe.c_str());
600                     if (!from.empty())
601                     {
602                         replace.parse_groups(from);
603                         rule->replace_list.push_back(replace);
604                     }
605                 }
606                 else
607                     throw mp::filter::FilterException
608                         ("Bad element "
609                          + std::string((const char *) p->name)
610                          + " in http_rewrite filter");
611             }
612             rules[values[0]] = rule;
613         }
614         else if (!strcmp((const char *) ptr->name, "within"))
615         {
616             static const char *names[6] =
617                 { "header", "attr", "tag", "rule", "reqline", 0 };
618             std::string values[5];
619             mp::xml::parse_attr(ptr, names, values);
620             Within w;
621             w.header = values[0];
622             w.attr = values[1];
623             w.tag = values[2];
624             std::map<std::string,RulePtr>::const_iterator it =
625                 rules.find(values[3]);
626             if (it == rules.end())
627                 throw mp::filter::FilterException
628                     ("Reference to non-existing rule '" + values[3] +
629                      "' in http_rewrite filter");
630             w.rule = it->second;
631             w.reqline = values[4] == "1";
632             phase.within_list.push_back(w);
633         }
634         else
635         {
636             throw mp::filter::FilterException
637                 ("Bad element "
638                  + std::string((const char *) ptr->name)
639                  + " in http_rewrite filter");
640         }
641     }
642 }
643
644 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
645         const char *path)
646 {
647     for (ptr = ptr->children; ptr; ptr = ptr->next)
648     {
649         if (ptr->type != XML_ELEMENT_NODE)
650             continue;
651         else if (!strcmp((const char *) ptr->name, "request"))
652         {
653             configure_phase(ptr, *req_phase);
654         }
655         else if (!strcmp((const char *) ptr->name, "response"))
656         {
657             configure_phase(ptr, *res_phase);
658         }
659         else
660         {
661             throw mp::filter::FilterException
662                 ("Bad element "
663                  + std::string((const char *) ptr->name)
664                  + " in http_rewrite1 filter");
665         }
666     }
667 }
668
669 static mp::filter::Base* filter_creator()
670 {
671     return new mp::filter::HttpRewrite;
672 }
673
674 extern "C" {
675     struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
676         0,
677         "http_rewrite",
678         filter_creator
679     };
680 }
681
682
683 /*
684  * Local variables:
685  * c-basic-offset: 4
686  * c-file-style: "Stroustrup"
687  * indent-tabs-mode: nil
688  * End:
689  * vim: shiftwidth=4 tabstop=8 expandtab
690  */
691