More logging when deciding not to rewrite
[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             bool start_anchor;
44             boost::regex re;
45             boost::smatch what;
46             std::string recipe;
47             std::map<int, std::string> group_index;
48             std::string sub_vars(
49                 const std::map<std::string, std::string> & vars) const;
50             void parse_groups(std::string pattern);
51         };
52
53         class HttpRewrite::Rule {
54         public:
55             std::list<Replace> replace_list;
56             bool test_patterns(
57                 std::map<std::string, std::string> &vars,
58                 std::string &txt, bool anchor);
59         };
60         class HttpRewrite::Within {
61         public:
62             boost::regex header;
63             boost::regex attr;
64             boost::regex tag;
65             std::string type;
66             bool reqline;
67             RulePtr rule;
68             bool exec(std::map<std::string, std::string> &vars,
69                       std::string &txt, bool anchor) const;
70         };
71
72         class HttpRewrite::Content {
73         public:
74             std::string type;
75             boost::regex content_re;
76             std::list<Within> within_list;
77             void configure(const xmlNode *ptr,
78                            std::map<std::string, RulePtr > &rules);
79             void quoted_literal(std::string &content,
80                                 std::map<std::string, std::string> &vars) const;
81             void parse(int verbose, std::string &content,
82                        std::map<std::string, std::string> & vars) const;
83         };
84         class HttpRewrite::Phase {
85         public:
86             Phase();
87             int m_verbose;
88             std::list<Content> content_list;
89             void rewrite_reqline(mp::odr & o, Z_HTTP_Request *hreq,
90                 std::map<std::string, std::string> & vars) const;
91             void rewrite_headers(mp::odr & o, Z_HTTP_Header *headers,
92                 std::map<std::string, std::string> & vars) const;
93             void rewrite_body(mp::odr & o,
94                               const char *content_type,
95                               char **content_buf, int *content_len,
96                               std::map<std::string, std::string> & vars) const;
97         };
98         class HttpRewrite::Event : public HTMLParserEvent {
99             void openTagStart(const char *tag, int tag_len);
100             void anyTagEnd(const char *tag, int tag_len, int close_it);
101             void attribute(const char *tag, int tag_len,
102                            const char *attr, int attr_len,
103                            const char *value, int val_len,
104                            const char *sep);
105             void closeTag(const char *tag, int tag_len);
106             void text(const char *value, int len);
107             const Content *m_content;
108             WRBUF m_w;
109             std::stack<std::list<Within>::const_iterator> s_within;
110             std::map<std::string, std::string> &m_vars;
111         public:
112             Event(const Content *p, std::map<std::string, std::string> &vars);
113             ~Event();
114             const char *result();
115         };
116     }
117 }
118
119 yf::HttpRewrite::HttpRewrite() :
120     req_phase(new Phase), res_phase(new Phase)
121 {
122 }
123
124 yf::HttpRewrite::~HttpRewrite()
125 {
126 }
127
128 void yf::HttpRewrite::process(mp::Package & package) const
129 {
130     yaz_log(YLOG_LOG, "HttpRewrite begins....");
131     Z_GDU *gdu = package.request().get();
132     //map of request/response vars
133     std::map<std::string, std::string> vars;
134     //we have an http req
135     if (gdu && gdu->which == Z_GDU_HTTP_Request)
136     {
137         Z_HTTP_Request *hreq = gdu->u.HTTP_Request;
138         mp::odr o;
139         req_phase->rewrite_reqline(o, hreq, vars);
140         yaz_log(YLOG_LOG, ">> Request headers");
141         req_phase->rewrite_headers(o, hreq->headers, vars);
142         req_phase->rewrite_body(o,
143                                 z_HTTP_header_lookup(hreq->headers,
144                                                      "Content-Type"),
145                                 &hreq->content_buf, &hreq->content_len,
146                                 vars);
147         package.request() = gdu;
148     }
149     package.move();
150     gdu = package.response().get();
151     if (gdu && gdu->which == Z_GDU_HTTP_Response)
152     {
153         Z_HTTP_Response *hres = gdu->u.HTTP_Response;
154         yaz_log(YLOG_LOG, "Response code %d", hres->code);
155         mp::odr o;
156         yaz_log(YLOG_LOG, "<< Respose headers");
157         res_phase->rewrite_headers(o, hres->headers, vars);
158         res_phase->rewrite_body(o,
159                                 z_HTTP_header_lookup(hres->headers,
160                                                      "Content-Type"),
161                                 &hres->content_buf, &hres->content_len,
162                                 vars);
163         package.response() = gdu;
164     }
165 }
166
167 void yf::HttpRewrite::Phase::rewrite_reqline (mp::odr & o,
168         Z_HTTP_Request *hreq,
169         std::map<std::string, std::string> & vars) const
170 {
171     //rewrite the request line
172     std::string path;
173     if (strstr(hreq->path, "http://") == hreq->path)
174     {
175         yaz_log(YLOG_LOG, "Path in the method line is absolute, "
176             "possibly a proxy request");
177         path += hreq->path;
178     }
179     else
180     {
181         //TODO what about proto
182         const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
183         if (!host)
184             return;
185
186         path += "http://";
187         path += host;
188         path += hreq->path;
189     }
190
191     std::list<Content>::const_iterator cit = content_list.begin();
192     for (; cit != content_list.end(); cit++)
193         if (cit->type == "headers")
194             break;
195
196     if (cit == content_list.end())
197         return;
198
199     std::list<Within>::const_iterator it = cit->within_list.begin();
200     for (; it != cit->within_list.end(); it++)
201         if (it->reqline)
202         {
203             yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
204             if (it->exec(vars, path, true))
205             {
206                 yaz_log(YLOG_LOG, "Rewritten request URL is %s", path.c_str());
207                 hreq->path = odr_strdup(o, path.c_str());
208             }
209         }
210 }
211
212 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
213         Z_HTTP_Header *headers,
214         std::map<std::string, std::string> & vars) const
215 {
216     std::list<Content>::const_iterator cit = content_list.begin();
217     for (; cit != content_list.end(); cit++)
218         if (cit->type == "headers")
219             break;
220
221     if (cit == content_list.end())
222         return;
223
224     for (Z_HTTP_Header *header = headers; header; header = header->next)
225     {
226         std::list<Within>::const_iterator it = cit->within_list.begin();
227         for (; it != cit->within_list.end(); it++)
228         {
229             if (!it->header.empty() &&
230                 regex_match(header->name, it->header))
231             {
232 #ifdef OLDHEADERMATCH                
233                 // Matches and replaces the whole header line.
234                 // This is good if you want to play with the header name too,
235                 // but useless for patterns that want to anchor to the beginning
236                 // or end of the header value, as we want to do with host-relative
237                 // links. This code should probably be removed.
238                 std::string sheader(header->name);
239                 sheader += ": ";
240                 sheader += header->value;
241
242                 if (it->exec(vars, sheader, true))
243                 {
244                     size_t pos = sheader.find(": ");
245                     if (pos == std::string::npos)
246                     {
247                         yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
248                         continue;
249                     }
250                     header->name = odr_strdup(
251                         o, sheader.substr(0, pos).c_str());
252                     header->value = odr_strdup(
253                         o, sheader.substr(pos + 2, std::string::npos).c_str());
254                 }
255 #else
256                 // Match and replace only the header value
257                 std::string hval(header->value);
258                 if (it->exec(vars, hval, true))
259                 {
260                     header->value = odr_strdup(o, hval.c_str());
261                 }
262                     
263 #endif
264             }
265         }
266     }
267 }
268
269 void yf::HttpRewrite::Phase::rewrite_body(
270     mp::odr &o,
271     const char *content_type,
272     char **content_buf,
273     int *content_len,
274     std::map<std::string, std::string> & vars) const
275 {
276     if (*content_len == 0)
277         return;
278     std::list<Content>::const_iterator cit = content_list.begin();
279     for (; cit != content_list.end(); cit++)
280     {
281         yaz_log(YLOG_LOG, "rewrite_body: content_type=%s type=%s",
282                 content_type, cit->type.c_str());
283         if (cit->type != "headers"
284             && regex_match(content_type, cit->content_re))
285             break;
286     }
287     if (cit == content_list.end()) {
288         yaz_log(YLOG_LOG,"rewrite_body: No content rule matched %s, not rewriting",
289                 content_type );  
290         return;
291     }
292
293     int i;
294     for (i = 0; i < *content_len; i++)
295         if ((*content_buf)[i] == 0) {
296             yaz_log(YLOG_LOG,"rewrite_body: Looks like binary stuff, not rewriting");
297             return;  // binary content. skip
298         }
299
300     std::string content(*content_buf, *content_len);
301     cit->parse(m_verbose, content, vars);
302     *content_buf = odr_strdup(o, content.c_str());
303     *content_len = strlen(*content_buf);
304 }
305
306 yf::HttpRewrite::Event::Event(const Content *p,
307                               std::map<std::string, std::string> & vars
308     ) : m_content(p), m_vars(vars)
309 {
310     m_w = wrbuf_alloc();
311 }
312
313 yf::HttpRewrite::Event::~Event()
314 {
315     wrbuf_destroy(m_w);
316 }
317
318 const char *yf::HttpRewrite::Event::result()
319 {
320     return wrbuf_cstr(m_w);
321 }
322
323 void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
324 {
325     wrbuf_putc(m_w, '<');
326     wrbuf_write(m_w, tag, tag_len);
327
328     std::string t(tag, tag_len);
329     std::list<Within>::const_iterator it = m_content->within_list.begin();
330     for (; it != m_content->within_list.end(); it++)
331     {
332         if (!it->tag.empty() && regex_match(t, it->tag))
333         {
334             if (!it->attr.empty() && regex_match("#text", it->attr))
335             {
336                 s_within.push(it);
337                 return;
338             }
339         }
340     }
341 }
342
343 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
344                                        int close_it)
345 {
346     if (close_it)
347     {
348         if (!s_within.empty())
349         {
350             std::list<Within>::const_iterator it = s_within.top();
351             std::string t(tag, tag_len);
352             if (regex_match(t, it->tag))
353                 s_within.pop();
354         }
355     }
356     if (close_it)
357         wrbuf_putc(m_w, '/');
358     wrbuf_putc(m_w, '>');
359 }
360
361 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
362                                        const char *attr, int attr_len,
363                                        const char *value, int val_len,
364                                        const char *sep)
365 {
366     std::list<Within>::const_iterator it = m_content->within_list.begin();
367     bool subst = false;
368
369     for (; it != m_content->within_list.end(); it++)
370     {
371         std::string t(tag, tag_len);
372         if (it->tag.empty() || regex_match(t, it->tag))
373         {
374             std::string a(attr, attr_len);
375             if (!it->attr.empty() && regex_match(a, it->attr))
376                 subst = true;
377         }
378         if (subst)
379             break;
380     }
381
382     wrbuf_putc(m_w, ' ');
383     wrbuf_write(m_w, attr, attr_len);
384     if (value)
385     {
386         wrbuf_puts(m_w, "=");
387         wrbuf_puts(m_w, sep);
388
389         std::string output;
390         if (subst)
391         {
392             std::string s(value, val_len);
393             it->exec(m_vars, s, true);
394             wrbuf_puts(m_w, s.c_str());
395         }
396         else
397             wrbuf_write(m_w, value, val_len);
398         wrbuf_puts(m_w, sep);
399     }
400 }
401
402 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
403 {
404     if (!s_within.empty())
405     {
406         std::list<Within>::const_iterator it = s_within.top();
407         std::string t(tag, tag_len);
408         if (regex_match(t, it->tag))
409             s_within.pop();
410     }
411     wrbuf_puts(m_w, "</");
412     wrbuf_write(m_w, tag, tag_len);
413 }
414
415 void yf::HttpRewrite::Event::text(const char *value, int len)
416 {
417     std::list<Within>::const_iterator it = m_content->within_list.end();
418     if (!s_within.empty())
419         it = s_within.top();
420     if (it != m_content->within_list.end())
421     {
422         std::string s(value, len);
423         it->exec(m_vars, s, false);
424         wrbuf_puts(m_w, s.c_str());
425     }
426     else
427         wrbuf_write(m_w, value, len);
428 }
429
430 static bool embed_quoted_literal(
431     std::string &content,
432     std::map<std::string, std::string> &vars,
433     mp::filter::HttpRewrite::RulePtr ruleptr,
434     bool html_context)
435 {
436     bool replace = false;
437     std::string res;
438     const char *cp = content.c_str();
439     const char *cp0 = cp;
440     while (*cp)
441     {
442         if (html_context && !strncmp(cp, "&quot;", 6))
443         {
444             cp += 6;
445             res.append(cp0, cp - cp0);
446             cp0 = cp;
447             while (*cp)
448             {
449                 if (!strncmp(cp, "&quot;", 6))
450                     break;
451                 if (*cp == '\n')
452                     break;
453                 cp++;
454             }
455             if (!*cp)
456                 break;
457             std::string s(cp0, cp - cp0);
458             if (ruleptr->test_patterns(vars, s, true))
459                 replace = true;
460             cp0 = cp;
461             res.append(s);
462         }
463         else if (*cp == '"' || *cp == '\'')
464         {
465             int m = *cp;
466             cp++;
467             res.append(cp0, cp - cp0);
468             cp0 = cp;
469             while (*cp)
470             {
471                 if (cp[-1] != '\\' && *cp == m)
472                     break;
473                 if (*cp == '\n')
474                     break;
475                 cp++;
476             }
477             if (!*cp)
478                 break;
479             std::string s(cp0, cp - cp0);
480             if (ruleptr->test_patterns(vars, s, true))
481                 replace = true;
482             cp0 = cp;
483             res.append(s);
484         }
485         else if (*cp == '/' && cp[1] == '/')
486         {
487             while (cp[1] && cp[1] != '\n')
488                 cp++;
489         }
490         cp++;
491     }
492     res.append(cp0, cp - cp0);
493     content = res;
494     return replace;
495 }
496
497 bool yf::HttpRewrite::Within::exec(
498     std::map<std::string, std::string> & vars,
499     std::string & txt, bool anchor) const
500 {
501     if (type == "quoted-literal")
502     {
503         return embed_quoted_literal(txt, vars, rule, true);
504     }
505     else
506     {
507         return rule->test_patterns(vars, txt, anchor);
508     }
509 }
510
511 bool yf::HttpRewrite::Rule::test_patterns(
512     std::map<std::string, std::string> & vars,
513     std::string & txt, bool anchor)
514 {
515     bool replaces = false;
516     bool first = anchor;
517     std::string out;
518     std::string::const_iterator start, end;
519     start = txt.begin();
520     end = txt.end();
521     while (1)
522     {
523         std::list<Replace>::iterator bit = replace_list.end();
524         {
525             std::string::const_iterator best_pos = txt.end();
526             std::list<Replace>::iterator it = replace_list.begin();
527             for (; it != replace_list.end(); it++)
528             {
529                 if (it->start_anchor && !first)
530                     continue;
531                 if (regex_search(start, end, it->what, it->re))
532                 {
533                     if (it->what[0].first < best_pos)
534                     {
535                         best_pos = it->what[0].first;
536                         bit = it;
537                     }
538                 }
539             }
540             if (bit == replace_list.end())
541                 break;
542         }
543         first = false;
544         replaces = true;
545         size_t i;
546         for (i = 1; i < bit->what.size(); ++i)
547         {
548             //check if the group is named
549             std::map<int, std::string>::const_iterator git
550                 = bit->group_index.find(i);
551             if (git != bit->group_index.end())
552             {   //it is
553                 vars[git->second] = bit->what[i];
554             }
555
556         }
557         //prepare replacement string
558         std::string rvalue = bit->sub_vars(vars);
559         yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
560                 bit->what.str(0).c_str(), rvalue.c_str());
561         out.append(start, bit->what[0].first);
562         out.append(rvalue);
563         start = bit->what[0].second; //move search forward
564     }
565     out.append(start, end);
566     txt = out;
567     return replaces;
568 }
569
570 void yf::HttpRewrite::Replace::parse_groups(std::string pattern)
571 {
572     int gnum = 0;
573     bool esc = false;
574     const std::string &str = pattern;
575     std::string res;
576     start_anchor = str[0] == '^';
577     yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
578     for (size_t i = 0; i < str.size(); ++i)
579     {
580         res += str[i];
581         if (!esc && str[i] == '\\')
582         {
583             esc = true;
584             continue;
585         }
586         if (!esc && str[i] == '(') //group starts
587         {
588             gnum++;
589             if (i+1 < str.size() && str[i+1] == '?') //group with attrs
590             {
591                 i++;
592                 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
593                 {
594                     if (gnum > 0) gnum--;
595                     res += str[i];
596                     i++;
597                     res += str[i];
598                     continue;
599                 }
600                 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
601                     i++;
602                 if (i+1 < str.size() && str[i+1] == '<') //named
603                 {
604                     i++;
605                     std::string gname;
606                     bool term = false;
607                     while (++i < str.size())
608                     {
609                         if (str[i] == '>') { term = true; break; }
610                         if (!isalnum(str[i]))
611                             throw mp::filter::FilterException
612                                 ("Only alphanumeric chars allowed, found "
613                                  " in '"
614                                  + str
615                                  + "' at "
616                                  + boost::lexical_cast<std::string>(i));
617                         gname += str[i];
618                     }
619                     if (!term)
620                         throw mp::filter::FilterException
621                             ("Unterminated group name '" + gname
622                              + " in '" + str +"'");
623                     group_index[gnum] = gname;
624                     yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
625                             gname.c_str(), gnum);
626                 }
627             }
628         }
629         esc = false;
630     }
631     re = res;
632 }
633
634 std::string yf::HttpRewrite::Replace::sub_vars(
635     const std::map<std::string, std::string> & vars) const
636 {
637     std::string out;
638     bool esc = false;
639     const std::string & in = recipe;
640     for (size_t i = 0; i < in.size(); ++i)
641     {
642         if (!esc && in[i] == '\\')
643         {
644             esc = true;
645             continue;
646         }
647         if (!esc && in[i] == '$') //var
648         {
649             if (i+1 < in.size() && in[i+1] == '{') //ref prefix
650             {
651                 ++i;
652                 std::string name;
653                 bool term = false;
654                 while (++i < in.size())
655                 {
656                     if (in[i] == '}') { term = true; break; }
657                     name += in[i];
658                 }
659                 if (!term) throw mp::filter::FilterException
660                     ("Unterminated var ref in '"+in+"' at "
661                      + boost::lexical_cast<std::string>(i));
662                 std::map<std::string, std::string>::const_iterator it
663                     = vars.find(name);
664                 if (it != vars.end())
665                 {
666                     out += it->second;
667                 }
668             }
669             else
670             {
671                 throw mp::filter::FilterException
672                     ("Malformed or trimmed var ref in '"
673                      +in+"' at "+boost::lexical_cast<std::string>(i));
674             }
675             continue;
676         }
677         //passthru
678         out += in[i];
679         esc = false;
680     }
681     return out;
682 }
683
684 yf::HttpRewrite::Phase::Phase() : m_verbose(0)
685 {
686 }
687
688 void yf::HttpRewrite::Content::parse(
689     int verbose,
690     std::string &content,
691     std::map<std::string, std::string> &vars) const
692 {
693     if (type == "html")
694     {
695         HTMLParser parser;
696         Event ev(this, vars);
697
698         parser.set_verbose(verbose);
699
700         parser.parse(ev, content.c_str());
701         content = ev.result();
702     }
703     if (type == "quoted-literal")
704     {
705         quoted_literal(content, vars);
706     }
707 }
708
709 void yf::HttpRewrite::Content::quoted_literal(
710     std::string &content,
711     std::map<std::string, std::string> &vars) const
712 {
713     std::list<Within>::const_iterator it = within_list.begin();
714     if (it != within_list.end())
715         embed_quoted_literal(content, vars, it->rule, false);
716 }
717
718 void yf::HttpRewrite::Content::configure(
719     const xmlNode *ptr, std::map<std::string, RulePtr > &rules)
720 {
721     for (; ptr; ptr = ptr->next)
722     {
723         if (ptr->type != XML_ELEMENT_NODE)
724             continue;
725         if (!strcmp((const char *) ptr->name, "within"))
726         {
727             static const char *names[7] =
728                 { "header", "attr", "tag", "rule", "reqline", "type", 0 };
729             std::string values[6];
730             mp::xml::parse_attr(ptr, names, values);
731             Within w;
732             if (values[0].length() > 0)
733                 w.header.assign(values[0], boost::regex_constants::icase);
734             if (values[1].length() > 0)
735                 w.attr.assign(values[1], boost::regex_constants::icase);
736             if (values[2].length() > 0)
737                 w.tag.assign(values[2], boost::regex_constants::icase);
738
739             std::vector<std::string> rulenames;
740             boost::split(rulenames, values[3], boost::is_any_of(","));
741             if (rulenames.size() == 0)
742             {
743                 throw mp::filter::FilterException
744                     ("Empty rule in '" + values[3] +
745                      "' in http_rewrite filter");
746             }
747             else if (rulenames.size() == 1)
748             {
749                 std::map<std::string,RulePtr>::const_iterator it =
750                     rules.find(rulenames[0]);
751                 if (it == rules.end())
752                     throw mp::filter::FilterException
753                         ("Reference to non-existing rule '" + rulenames[0] +
754                          "' in http_rewrite filter");
755                 w.rule = it->second;
756
757             }
758             else
759             {
760                 RulePtr rule(new Rule);
761                 size_t i;
762                 for (i = 0; i < rulenames.size(); i++)
763                 {
764                     std::map<std::string,RulePtr>::const_iterator it =
765                         rules.find(rulenames[i]);
766                     if (it == rules.end())
767                         throw mp::filter::FilterException
768                             ("Reference to non-existing rule '" + rulenames[i] +
769                              "' in http_rewrite filter");
770                     RulePtr subRule = it->second;
771                     std::list<Replace>::iterator rit =
772                         subRule->replace_list.begin();
773                     for (; rit != subRule->replace_list.end(); rit++)
774                         rule->replace_list.push_back(*rit);
775                 }
776                 w.rule = rule;
777             }
778             w.reqline = values[4] == "1";
779             w.type = values[5];
780             if (w.type.empty() || w.type == "quoted-literal")
781                 ;
782             else
783                 throw mp::filter::FilterException
784                     ("within type must be quoted-literal or none in "
785                      " in http_rewrite filter");
786             within_list.push_back(w);
787         }
788     }
789 }
790
791 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
792 {
793     static const char *names[2] = { "verbose", 0 };
794     std::string values[1];
795     values[0] = "0";
796     mp::xml::parse_attr(ptr, names, values);
797
798     phase.m_verbose = atoi(values[0].c_str());
799
800     std::map<std::string, RulePtr > rules;
801     for (ptr = ptr->children; ptr; ptr = ptr->next)
802     {
803         if (ptr->type != XML_ELEMENT_NODE)
804             continue;
805         else if (!strcmp((const char *) ptr->name, "rule"))
806         {
807             static const char *names[2] = { "name", 0 };
808             std::string values[1];
809             values[0] = "default";
810             mp::xml::parse_attr(ptr, names, values);
811
812             RulePtr rule(new Rule);
813             for (xmlNode *p = ptr->children; p; p = p->next)
814             {
815                 if (p->type != XML_ELEMENT_NODE)
816                     continue;
817                 if (!strcmp((const char *) p->name, "rewrite"))
818                 {
819                     Replace replace;
820                     std::string from;
821                     const struct _xmlAttr *attr;
822                     for (attr = p->properties; attr; attr = attr->next)
823                     {
824                         if (!strcmp((const char *) attr->name,  "from"))
825                             from = mp::xml::get_text(attr->children);
826                         else if (!strcmp((const char *) attr->name,  "to"))
827                             replace.recipe = mp::xml::get_text(attr->children);
828                         else
829                             throw mp::filter::FilterException
830                                 ("Bad attribute "
831                                  + std::string((const char *) attr->name)
832                                  + " in rewrite section of http_rewrite");
833                     }
834                     yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
835                             from.c_str(), replace.recipe.c_str());
836                     if (!from.empty())
837                     {
838                         replace.parse_groups(from);
839                         rule->replace_list.push_back(replace);
840                     }
841                 }
842                 else
843                     throw mp::filter::FilterException
844                         ("Bad element "
845                          + std::string((const char *) p->name)
846                          + " in http_rewrite filter");
847             }
848             rules[values[0]] = rule;
849         }
850         else if (!strcmp((const char *) ptr->name, "content"))
851         {
852             static const char *names[3] =
853                 { "type", "mime", 0 };
854             std::string values[2];
855             mp::xml::parse_attr(ptr, names, values);
856             if (values[0].empty())
857             {
858                     throw mp::filter::FilterException
859                         ("Missing attribute, type for for element "
860                          + std::string((const char *) ptr->name)
861                          + " in http_rewrite filter");
862             }
863             Content c;
864
865             c.type = values[0];
866             if (!values[1].empty())
867                 c.content_re.assign(values[1], boost::regex::icase);
868             c.configure(ptr->children, rules);
869             phase.content_list.push_back(c);
870         }
871         else
872         {
873             throw mp::filter::FilterException
874                 ("Bad element "
875                  + std::string((const char *) ptr->name)
876                  + " in http_rewrite filter");
877         }
878     }
879 }
880
881 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
882         const char *path)
883 {
884     for (ptr = ptr->children; ptr; ptr = ptr->next)
885     {
886         if (ptr->type != XML_ELEMENT_NODE)
887             continue;
888         else if (!strcmp((const char *) ptr->name, "request"))
889         {
890             configure_phase(ptr, *req_phase);
891         }
892         else if (!strcmp((const char *) ptr->name, "response"))
893         {
894             configure_phase(ptr, *res_phase);
895         }
896         else
897         {
898             throw mp::filter::FilterException
899                 ("Bad element "
900                  + std::string((const char *) ptr->name)
901                  + " in http_rewrite1 filter");
902         }
903     }
904 }
905
906 static mp::filter::Base* filter_creator()
907 {
908     return new mp::filter::HttpRewrite;
909 }
910
911 extern "C" {
912     struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
913         0,
914         "http_rewrite",
915         filter_creator
916     };
917 }
918
919
920 /*
921  * Local variables:
922  * c-basic-offset: 4
923  * c-file-style: "Stroustrup"
924  * indent-tabs-mode: nil
925  * End:
926  * vim: shiftwidth=4 tabstop=8 expandtab
927  */
928