Only do CDATA for attr="#text", verbose flag
[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 <boost/regex.hpp>
30 #include <boost/lexical_cast.hpp>
31 #include <boost/algorithm/string.hpp>
32
33 #include <map>
34
35 namespace mp = metaproxy_1;
36 namespace yf = mp::filter;
37
38 namespace metaproxy_1 {
39     namespace filter {
40         class HttpRewrite::Replace {
41         public:
42             std::string regex;
43             std::string recipe;
44             std::map<int, std::string> group_index;
45             const std::string search_replace(
46                 std::map<std::string, std::string> & vars,
47                 const std::string & txt) const;
48             std::string sub_vars (
49                 const std::map<std::string, std::string> & vars) const;
50             void parse_groups();
51         };
52
53         class HttpRewrite::Rule {
54         public:
55             std::list<Replace> replace_list;
56             const std::string test_patterns(
57                 std::map<std::string, std::string> & vars,
58                 const std::string & txt) const;
59         };
60         class HttpRewrite::Within {
61         public:
62             std::string header;
63             std::string attr;
64             std::string tag;
65             bool reqline;
66             RulePtr rule;
67         };
68
69         class HttpRewrite::Phase {
70         public:
71             Phase();
72             std::list<Within> within_list;
73             int m_verbose;
74             void rewrite_reqline(mp::odr & o, Z_HTTP_Request *hreq,
75                 std::map<std::string, std::string> & vars) const;
76             void rewrite_headers(mp::odr & o, Z_HTTP_Header *headers,
77                 std::map<std::string, std::string> & vars) const;
78             void rewrite_body(mp::odr & o,
79                 char **content_buf, int *content_len,
80                 std::map<std::string, std::string> & vars) const;
81         };
82         class HttpRewrite::Event : public HTMLParserEvent {
83             void openTagStart(const char *tag, int tag_len);
84             void anyTagEnd(const char *tag, int tag_len, int close_it);
85             void attribute(const char *tag, int tag_len,
86                            const char *attr, int attr_len,
87                            const char *value, int val_len);
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::list<Within>::const_iterator enabled_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     enabled_within = m_phase->within_list.end();
248 }
249
250 yf::HttpRewrite::Event::~Event()
251 {
252     wrbuf_destroy(m_w);
253 }
254
255 const char *yf::HttpRewrite::Event::result()
256 {
257     return wrbuf_cstr(m_w);
258 }
259
260 void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
261 {
262     // check if there is <within tag="x" .. />
263     if (enabled_within == m_phase->within_list.end())
264     {
265         std::string t(tag, tag_len);
266         std::list<Within>::const_iterator it =
267             m_phase->within_list.begin();
268         for (; it != m_phase->within_list.end(); it++)
269         {
270             if (it->tag.length() > 0 && yaz_strcasecmp(it->tag.c_str(),
271                                                        t.c_str()) == 0)
272             {
273                 std::vector<std::string> attr;
274                 boost::split(attr, it->attr, boost::is_any_of(","));
275                 size_t i;
276                 for (i = 0; i < attr.size(); i++)
277                 {
278                     if (attr[i].compare("#text") == 0)
279                     {
280                         enabled_within = it;
281                         break;
282                     }
283                 }
284             }
285         }
286     }
287     wrbuf_putc(m_w, '<');
288     wrbuf_write(m_w, tag, tag_len);
289 }
290
291 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
292                                        int close_it)
293 {
294     if (close_it)
295     {
296         std::list<Within>::const_iterator it = enabled_within;
297         if (it != m_phase->within_list.end())
298         {
299             std::string t(tag, tag_len);
300             if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
301             {
302                 enabled_within = m_phase->within_list.end();
303             }
304         }
305     }
306     if (close_it)
307         wrbuf_putc(m_w, '/');
308     wrbuf_putc(m_w, '>');
309 }
310
311 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
312                                        const char *attr, int attr_len,
313                                        const char *value, int val_len)
314 {
315     std::list<Within>::const_iterator it = m_phase->within_list.begin();
316     bool subst = false;
317
318     for (; it != m_phase->within_list.end(); it++)
319     {
320         std::string t(tag, tag_len);
321         if (it->tag.length() == 0 ||
322             yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
323         {
324             std::string a(attr, attr_len);
325             std::vector<std::string> attr;
326             boost::split(attr, it->attr, boost::is_any_of(","));
327             size_t i;
328             for (i = 0; i < attr.size(); i++)
329             {
330                 if (attr[i].compare("#text") &&
331                     yaz_strcasecmp(attr[i].c_str(), a.c_str()) == 0)
332                     subst = true;
333             }
334         }
335         if (subst)
336             break;
337     }
338
339     wrbuf_putc(m_w, ' ');
340     wrbuf_write(m_w, attr, attr_len);
341     wrbuf_puts(m_w, "=\"");
342
343     std::string output;
344     if (subst)
345     {
346         std::string input(value, val_len);
347         output = it->rule->test_patterns(m_vars, input);
348     }
349     if (output.empty())
350         wrbuf_write(m_w, value, val_len);
351     else
352         wrbuf_puts(m_w, output.c_str());
353     wrbuf_puts(m_w, "\"");
354 }
355
356 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
357 {
358     std::list<Within>::const_iterator it = enabled_within;
359     if (it != m_phase->within_list.end())
360     {
361         std::string t(tag, tag_len);
362         if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
363         {
364             enabled_within = m_phase->within_list.end();
365         }
366     }
367     wrbuf_puts(m_w, "</");
368     wrbuf_write(m_w, tag, tag_len);
369 }
370
371 void yf::HttpRewrite::Event::text(const char *value, int len)
372 {
373     std::list<Within>::const_iterator it = enabled_within;
374     bool subst = false;
375
376     if (it != m_phase->within_list.end())
377     {
378         subst = true;
379         if (it->attr.length() > 0)
380         {
381             subst = false;
382             std::vector<std::string> attr;
383             boost::split(attr, it->attr, boost::is_any_of(","));
384             size_t i;
385             for (i = 0; i < attr.size(); i++)
386             {
387                 if (attr[i].compare("#text") == 0)
388                 {
389                     subst = true;
390                 }
391             }
392         }
393     }
394     std::string output;
395     if (subst)
396     {
397         std::string input(value, len);
398         output = it->rule->test_patterns(m_vars, input);
399     }
400     if (output.empty())
401         wrbuf_write(m_w, value, len);
402     else
403         wrbuf_puts(m_w, output.c_str());
404 }
405
406
407 /**
408  * Tests pattern from the vector in order and executes recipe on
409  the first match.
410  */
411 const std::string yf::HttpRewrite::Rule::test_patterns(
412         std::map<std::string, std::string> & vars,
413         const std::string & txt) const
414 {
415     std::list<Replace>::const_iterator it = replace_list.begin();
416
417     for (; it != replace_list.end(); it++)
418     {
419         std::string out = it->search_replace(vars, txt);
420         if (!out.empty()) return out;
421     }
422     return "";
423 }
424
425 const std::string yf::HttpRewrite::Replace::search_replace(
426         std::map<std::string, std::string> & vars,
427         const std::string & txt) const
428 {
429     //exec regex against value
430     boost::regex re(regex);
431     boost::smatch what;
432     std::string::const_iterator start, end;
433     start = txt.begin();
434     end = txt.end();
435     std::string out;
436     while (regex_search(start, end, what, re)) //find next full match
437     {
438         size_t i;
439         for (i = 1; i < what.size(); ++i)
440         {
441             //check if the group is named
442             std::map<int, std::string>::const_iterator it
443                 = group_index.find(i);
444             if (it != group_index.end())
445             {   //it is
446                 if (!what[i].str().empty())
447                     vars[it->second] = what[i];
448             }
449
450         }
451         //prepare replacement string
452         std::string rvalue = sub_vars(vars);
453         yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
454                 what.str(0).c_str(), rvalue.c_str());
455         out.append(start, what[0].first);
456         out.append(rvalue);
457         start = what[0].second; //move search forward
458     }
459     //if we had a match cat the last part
460     if (start != txt.begin())
461         out.append(start, end);
462     return out;
463 }
464
465 void yf::HttpRewrite::Replace::parse_groups()
466 {
467     int gnum = 0;
468     bool esc = false;
469     const std::string & str = regex;
470     std::string res;
471     yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
472     for (size_t i = 0; i < str.size(); ++i)
473     {
474         res += str[i];
475         if (!esc && str[i] == '\\')
476         {
477             esc = true;
478             continue;
479         }
480         if (!esc && str[i] == '(') //group starts
481         {
482             gnum++;
483             if (i+1 < str.size() && str[i+1] == '?') //group with attrs
484             {
485                 i++;
486                 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
487                 {
488                     if (gnum > 0) gnum--;
489                     res += str[i];
490                     i++;
491                     res += str[i];
492                     continue;
493                 }
494                 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
495                     i++;
496                 if (i+1 < str.size() && str[i+1] == '<') //named
497                 {
498                     i++;
499                     std::string gname;
500                     bool term = false;
501                     while (++i < str.size())
502                     {
503                         if (str[i] == '>') { term = true; break; }
504                         if (!isalnum(str[i]))
505                             throw mp::filter::FilterException
506                                 ("Only alphanumeric chars allowed, found "
507                                  " in '"
508                                  + str
509                                  + "' at "
510                                  + boost::lexical_cast<std::string>(i));
511                         gname += str[i];
512                     }
513                     if (!term)
514                         throw mp::filter::FilterException
515                             ("Unterminated group name '" + gname
516                              + " in '" + str +"'");
517                     group_index[gnum] = gname;
518                     yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
519                             gname.c_str(), gnum);
520                 }
521             }
522         }
523         esc = false;
524     }
525     regex = res;
526 }
527
528 std::string yf::HttpRewrite::Replace::sub_vars (
529         const std::map<std::string, std::string> & vars) const
530 {
531     std::string out;
532     bool esc = false;
533     const std::string & in = recipe;
534     for (size_t i = 0; i < in.size(); ++i)
535     {
536         if (!esc && in[i] == '\\')
537         {
538             esc = true;
539             continue;
540         }
541         if (!esc && in[i] == '$') //var
542         {
543             if (i+1 < in.size() && in[i+1] == '{') //ref prefix
544             {
545                 ++i;
546                 std::string name;
547                 bool term = false;
548                 while (++i < in.size())
549                 {
550                     if (in[i] == '}') { term = true; break; }
551                     name += in[i];
552                 }
553                 if (!term) throw mp::filter::FilterException
554                     ("Unterminated var ref in '"+in+"' at "
555                      + boost::lexical_cast<std::string>(i));
556                 std::map<std::string, std::string>::const_iterator it
557                     = vars.find(name);
558                 if (it != vars.end())
559                 {
560                     out += it->second;
561                 }
562             }
563             else
564             {
565                 throw mp::filter::FilterException
566                     ("Malformed or trimmed var ref in '"
567                      +in+"' at "+boost::lexical_cast<std::string>(i));
568             }
569             continue;
570         }
571         //passthru
572         out += in[i];
573         esc = false;
574     }
575     return out;
576 }
577
578 yf::HttpRewrite::Phase::Phase() : m_verbose(0)
579 {
580 }
581
582 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
583 {
584     static const char *names[2] = { "verbose", 0 };
585     std::string values[1];
586     values[0] = "0";
587     mp::xml::parse_attr(ptr, names, values);
588
589     phase.m_verbose = atoi(values[0].c_str());
590
591     std::map<std::string, RulePtr > rules;
592     for (ptr = ptr->children; ptr; ptr = ptr->next)
593     {
594         if (ptr->type != XML_ELEMENT_NODE)
595             continue;
596         else if (!strcmp((const char *) ptr->name, "rule"))
597         {
598             static const char *names[2] = { "name", 0 };
599             std::string values[1];
600             values[0] = "default";
601             mp::xml::parse_attr(ptr, names, values);
602
603             RulePtr rule(new Rule);
604             for (xmlNode *p = ptr->children; p; p = p->next)
605             {
606                 if (p->type != XML_ELEMENT_NODE)
607                     continue;
608                 if (!strcmp((const char *) p->name, "rewrite"))
609                 {
610                     Replace replace;
611                     const struct _xmlAttr *attr;
612                     for (attr = p->properties; attr; attr = attr->next)
613                     {
614                         if (!strcmp((const char *) attr->name,  "from"))
615                             replace.regex = mp::xml::get_text(attr->children);
616                         else if (!strcmp((const char *) attr->name,  "to"))
617                             replace.recipe = mp::xml::get_text(attr->children);
618                         else
619                             throw mp::filter::FilterException
620                                 ("Bad attribute "
621                                  + std::string((const char *) attr->name)
622                                  + " in rewrite section of http_rewrite");
623                     }
624                     yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
625                             replace.regex.c_str(), replace.recipe.c_str());
626                     replace.parse_groups();
627                     if (!replace.regex.empty())
628                         rule->replace_list.push_back(replace);
629                 }
630                 else
631                     throw mp::filter::FilterException
632                         ("Bad element "
633                          + std::string((const char *) p->name)
634                          + " in http_rewrite filter");
635             }
636             rules[values[0]] = rule;
637         }
638         else if (!strcmp((const char *) ptr->name, "within"))
639         {
640             static const char *names[6] =
641                 { "header", "attr", "tag", "rule", "reqline", 0 };
642             std::string values[5];
643             mp::xml::parse_attr(ptr, names, values);
644             Within w;
645             w.header = values[0];
646             w.attr = values[1];
647             w.tag = values[2];
648             std::map<std::string,RulePtr>::const_iterator it =
649                 rules.find(values[3]);
650             if (it == rules.end())
651                 throw mp::filter::FilterException
652                     ("Reference to non-existing rule '" + values[3] +
653                      "' in http_rewrite filter");
654             w.rule = it->second;
655             w.reqline = values[4] == "1";
656             phase.within_list.push_back(w);
657         }
658         else
659         {
660             throw mp::filter::FilterException
661                 ("Bad element "
662                  + std::string((const char *) ptr->name)
663                  + " in http_rewrite filter");
664         }
665     }
666 }
667
668 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
669         const char *path)
670 {
671     for (ptr = ptr->children; ptr; ptr = ptr->next)
672     {
673         if (ptr->type != XML_ELEMENT_NODE)
674             continue;
675         else if (!strcmp((const char *) ptr->name, "request"))
676         {
677             configure_phase(ptr, *req_phase);
678         }
679         else if (!strcmp((const char *) ptr->name, "response"))
680         {
681             configure_phase(ptr, *res_phase);
682         }
683         else
684         {
685             throw mp::filter::FilterException
686                 ("Bad element "
687                  + std::string((const char *) ptr->name)
688                  + " in http_rewrite1 filter");
689         }
690     }
691 }
692
693 static mp::filter::Base* filter_creator()
694 {
695     return new mp::filter::HttpRewrite;
696 }
697
698 extern "C" {
699     struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
700         0,
701         "http_rewrite",
702         filter_creator
703     };
704 }
705
706
707 /*
708  * Local variables:
709  * c-basic-offset: 4
710  * c-file-style: "Stroustrup"
711  * indent-tabs-mode: nil
712  * End:
713  * vim: shiftwidth=4 tabstop=8 expandtab
714  */
715