within header=... matches only the header value
[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         return;
289
290     int i;
291     for (i = 0; i < *content_len; i++)
292         if ((*content_buf)[i] == 0)
293             return;  // binary content. skip
294
295     std::string content(*content_buf, *content_len);
296     cit->parse(m_verbose, content, vars);
297     *content_buf = odr_strdup(o, content.c_str());
298     *content_len = strlen(*content_buf);
299 }
300
301 yf::HttpRewrite::Event::Event(const Content *p,
302                               std::map<std::string, std::string> & vars
303     ) : m_content(p), m_vars(vars)
304 {
305     m_w = wrbuf_alloc();
306 }
307
308 yf::HttpRewrite::Event::~Event()
309 {
310     wrbuf_destroy(m_w);
311 }
312
313 const char *yf::HttpRewrite::Event::result()
314 {
315     return wrbuf_cstr(m_w);
316 }
317
318 void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
319 {
320     wrbuf_putc(m_w, '<');
321     wrbuf_write(m_w, tag, tag_len);
322
323     std::string t(tag, tag_len);
324     std::list<Within>::const_iterator it = m_content->within_list.begin();
325     for (; it != m_content->within_list.end(); it++)
326     {
327         if (!it->tag.empty() && regex_match(t, it->tag))
328         {
329             if (!it->attr.empty() && regex_match("#text", it->attr))
330             {
331                 s_within.push(it);
332                 return;
333             }
334         }
335     }
336 }
337
338 void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
339                                        int close_it)
340 {
341     if (close_it)
342     {
343         if (!s_within.empty())
344         {
345             std::list<Within>::const_iterator it = s_within.top();
346             std::string t(tag, tag_len);
347             if (regex_match(t, it->tag))
348                 s_within.pop();
349         }
350     }
351     if (close_it)
352         wrbuf_putc(m_w, '/');
353     wrbuf_putc(m_w, '>');
354 }
355
356 void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
357                                        const char *attr, int attr_len,
358                                        const char *value, int val_len,
359                                        const char *sep)
360 {
361     std::list<Within>::const_iterator it = m_content->within_list.begin();
362     bool subst = false;
363
364     for (; it != m_content->within_list.end(); it++)
365     {
366         std::string t(tag, tag_len);
367         if (it->tag.empty() || regex_match(t, it->tag))
368         {
369             std::string a(attr, attr_len);
370             if (!it->attr.empty() && regex_match(a, it->attr))
371                 subst = true;
372         }
373         if (subst)
374             break;
375     }
376
377     wrbuf_putc(m_w, ' ');
378     wrbuf_write(m_w, attr, attr_len);
379     if (value)
380     {
381         wrbuf_puts(m_w, "=");
382         wrbuf_puts(m_w, sep);
383
384         std::string output;
385         if (subst)
386         {
387             std::string s(value, val_len);
388             it->exec(m_vars, s, true);
389             wrbuf_puts(m_w, s.c_str());
390         }
391         else
392             wrbuf_write(m_w, value, val_len);
393         wrbuf_puts(m_w, sep);
394     }
395 }
396
397 void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
398 {
399     if (!s_within.empty())
400     {
401         std::list<Within>::const_iterator it = s_within.top();
402         std::string t(tag, tag_len);
403         if (regex_match(t, it->tag))
404             s_within.pop();
405     }
406     wrbuf_puts(m_w, "</");
407     wrbuf_write(m_w, tag, tag_len);
408 }
409
410 void yf::HttpRewrite::Event::text(const char *value, int len)
411 {
412     std::list<Within>::const_iterator it = m_content->within_list.end();
413     if (!s_within.empty())
414         it = s_within.top();
415     if (it != m_content->within_list.end())
416     {
417         std::string s(value, len);
418         it->exec(m_vars, s, false);
419         wrbuf_puts(m_w, s.c_str());
420     }
421     else
422         wrbuf_write(m_w, value, len);
423 }
424
425 static bool embed_quoted_literal(
426     std::string &content,
427     std::map<std::string, std::string> &vars,
428     mp::filter::HttpRewrite::RulePtr ruleptr,
429     bool html_context)
430 {
431     bool replace = false;
432     std::string res;
433     const char *cp = content.c_str();
434     const char *cp0 = cp;
435     while (*cp)
436     {
437         if (html_context && !strncmp(cp, "&quot;", 6))
438         {
439             cp += 6;
440             res.append(cp0, cp - cp0);
441             cp0 = cp;
442             while (*cp)
443             {
444                 if (!strncmp(cp, "&quot;", 6))
445                     break;
446                 if (*cp == '\n')
447                     break;
448                 cp++;
449             }
450             if (!*cp)
451                 break;
452             std::string s(cp0, cp - cp0);
453             if (ruleptr->test_patterns(vars, s, true))
454                 replace = true;
455             cp0 = cp;
456             res.append(s);
457         }
458         else if (*cp == '"' || *cp == '\'')
459         {
460             int m = *cp;
461             cp++;
462             res.append(cp0, cp - cp0);
463             cp0 = cp;
464             while (*cp)
465             {
466                 if (cp[-1] != '\\' && *cp == m)
467                     break;
468                 if (*cp == '\n')
469                     break;
470                 cp++;
471             }
472             if (!*cp)
473                 break;
474             std::string s(cp0, cp - cp0);
475             if (ruleptr->test_patterns(vars, s, true))
476                 replace = true;
477             cp0 = cp;
478             res.append(s);
479         }
480         else if (*cp == '/' && cp[1] == '/')
481         {
482             while (cp[1] && cp[1] != '\n')
483                 cp++;
484         }
485         cp++;
486     }
487     res.append(cp0, cp - cp0);
488     content = res;
489     return replace;
490 }
491
492 bool yf::HttpRewrite::Within::exec(
493     std::map<std::string, std::string> & vars,
494     std::string & txt, bool anchor) const
495 {
496     if (type == "quoted-literal")
497     {
498         return embed_quoted_literal(txt, vars, rule, true);
499     }
500     else
501     {
502         return rule->test_patterns(vars, txt, anchor);
503     }
504 }
505
506 bool yf::HttpRewrite::Rule::test_patterns(
507     std::map<std::string, std::string> & vars,
508     std::string & txt, bool anchor)
509 {
510     bool replaces = false;
511     bool first = anchor;
512     std::string out;
513     std::string::const_iterator start, end;
514     start = txt.begin();
515     end = txt.end();
516     while (1)
517     {
518         std::list<Replace>::iterator bit = replace_list.end();
519         {
520             std::string::const_iterator best_pos = txt.end();
521             std::list<Replace>::iterator it = replace_list.begin();
522             for (; it != replace_list.end(); it++)
523             {
524                 if (it->start_anchor && !first)
525                     continue;
526                 if (regex_search(start, end, it->what, it->re))
527                 {
528                     if (it->what[0].first < best_pos)
529                     {
530                         best_pos = it->what[0].first;
531                         bit = it;
532                     }
533                 }
534             }
535             if (bit == replace_list.end())
536                 break;
537         }
538         first = false;
539         replaces = true;
540         size_t i;
541         for (i = 1; i < bit->what.size(); ++i)
542         {
543             //check if the group is named
544             std::map<int, std::string>::const_iterator git
545                 = bit->group_index.find(i);
546             if (git != bit->group_index.end())
547             {   //it is
548                 vars[git->second] = bit->what[i];
549             }
550
551         }
552         //prepare replacement string
553         std::string rvalue = bit->sub_vars(vars);
554         yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
555                 bit->what.str(0).c_str(), rvalue.c_str());
556         out.append(start, bit->what[0].first);
557         out.append(rvalue);
558         start = bit->what[0].second; //move search forward
559     }
560     out.append(start, end);
561     txt = out;
562     return replaces;
563 }
564
565 void yf::HttpRewrite::Replace::parse_groups(std::string pattern)
566 {
567     int gnum = 0;
568     bool esc = false;
569     const std::string &str = pattern;
570     std::string res;
571     start_anchor = str[0] == '^';
572     yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
573     for (size_t i = 0; i < str.size(); ++i)
574     {
575         res += str[i];
576         if (!esc && str[i] == '\\')
577         {
578             esc = true;
579             continue;
580         }
581         if (!esc && str[i] == '(') //group starts
582         {
583             gnum++;
584             if (i+1 < str.size() && str[i+1] == '?') //group with attrs
585             {
586                 i++;
587                 if (i+1 < str.size() && str[i+1] == ':') //non-capturing
588                 {
589                     if (gnum > 0) gnum--;
590                     res += str[i];
591                     i++;
592                     res += str[i];
593                     continue;
594                 }
595                 if (i+1 < str.size() && str[i+1] == 'P') //optional, python
596                     i++;
597                 if (i+1 < str.size() && str[i+1] == '<') //named
598                 {
599                     i++;
600                     std::string gname;
601                     bool term = false;
602                     while (++i < str.size())
603                     {
604                         if (str[i] == '>') { term = true; break; }
605                         if (!isalnum(str[i]))
606                             throw mp::filter::FilterException
607                                 ("Only alphanumeric chars allowed, found "
608                                  " in '"
609                                  + str
610                                  + "' at "
611                                  + boost::lexical_cast<std::string>(i));
612                         gname += str[i];
613                     }
614                     if (!term)
615                         throw mp::filter::FilterException
616                             ("Unterminated group name '" + gname
617                              + " in '" + str +"'");
618                     group_index[gnum] = gname;
619                     yaz_log(YLOG_LOG, "Found named group '%s' at $%d",
620                             gname.c_str(), gnum);
621                 }
622             }
623         }
624         esc = false;
625     }
626     re = res;
627 }
628
629 std::string yf::HttpRewrite::Replace::sub_vars(
630     const std::map<std::string, std::string> & vars) const
631 {
632     std::string out;
633     bool esc = false;
634     const std::string & in = recipe;
635     for (size_t i = 0; i < in.size(); ++i)
636     {
637         if (!esc && in[i] == '\\')
638         {
639             esc = true;
640             continue;
641         }
642         if (!esc && in[i] == '$') //var
643         {
644             if (i+1 < in.size() && in[i+1] == '{') //ref prefix
645             {
646                 ++i;
647                 std::string name;
648                 bool term = false;
649                 while (++i < in.size())
650                 {
651                     if (in[i] == '}') { term = true; break; }
652                     name += in[i];
653                 }
654                 if (!term) throw mp::filter::FilterException
655                     ("Unterminated var ref in '"+in+"' at "
656                      + boost::lexical_cast<std::string>(i));
657                 std::map<std::string, std::string>::const_iterator it
658                     = vars.find(name);
659                 if (it != vars.end())
660                 {
661                     out += it->second;
662                 }
663             }
664             else
665             {
666                 throw mp::filter::FilterException
667                     ("Malformed or trimmed var ref in '"
668                      +in+"' at "+boost::lexical_cast<std::string>(i));
669             }
670             continue;
671         }
672         //passthru
673         out += in[i];
674         esc = false;
675     }
676     return out;
677 }
678
679 yf::HttpRewrite::Phase::Phase() : m_verbose(0)
680 {
681 }
682
683 void yf::HttpRewrite::Content::parse(
684     int verbose,
685     std::string &content,
686     std::map<std::string, std::string> &vars) const
687 {
688     if (type == "html")
689     {
690         HTMLParser parser;
691         Event ev(this, vars);
692
693         parser.set_verbose(verbose);
694
695         parser.parse(ev, content.c_str());
696         content = ev.result();
697     }
698     if (type == "quoted-literal")
699     {
700         quoted_literal(content, vars);
701     }
702 }
703
704 void yf::HttpRewrite::Content::quoted_literal(
705     std::string &content,
706     std::map<std::string, std::string> &vars) const
707 {
708     std::list<Within>::const_iterator it = within_list.begin();
709     if (it != within_list.end())
710         embed_quoted_literal(content, vars, it->rule, false);
711 }
712
713 void yf::HttpRewrite::Content::configure(
714     const xmlNode *ptr, std::map<std::string, RulePtr > &rules)
715 {
716     for (; ptr; ptr = ptr->next)
717     {
718         if (ptr->type != XML_ELEMENT_NODE)
719             continue;
720         if (!strcmp((const char *) ptr->name, "within"))
721         {
722             static const char *names[7] =
723                 { "header", "attr", "tag", "rule", "reqline", "type", 0 };
724             std::string values[6];
725             mp::xml::parse_attr(ptr, names, values);
726             Within w;
727             if (values[0].length() > 0)
728                 w.header.assign(values[0], boost::regex_constants::icase);
729             if (values[1].length() > 0)
730                 w.attr.assign(values[1], boost::regex_constants::icase);
731             if (values[2].length() > 0)
732                 w.tag.assign(values[2], boost::regex_constants::icase);
733
734             std::vector<std::string> rulenames;
735             boost::split(rulenames, values[3], boost::is_any_of(","));
736             if (rulenames.size() == 0)
737             {
738                 throw mp::filter::FilterException
739                     ("Empty rule in '" + values[3] +
740                      "' in http_rewrite filter");
741             }
742             else if (rulenames.size() == 1)
743             {
744                 std::map<std::string,RulePtr>::const_iterator it =
745                     rules.find(rulenames[0]);
746                 if (it == rules.end())
747                     throw mp::filter::FilterException
748                         ("Reference to non-existing rule '" + rulenames[0] +
749                          "' in http_rewrite filter");
750                 w.rule = it->second;
751
752             }
753             else
754             {
755                 RulePtr rule(new Rule);
756                 size_t i;
757                 for (i = 0; i < rulenames.size(); i++)
758                 {
759                     std::map<std::string,RulePtr>::const_iterator it =
760                         rules.find(rulenames[i]);
761                     if (it == rules.end())
762                         throw mp::filter::FilterException
763                             ("Reference to non-existing rule '" + rulenames[i] +
764                              "' in http_rewrite filter");
765                     RulePtr subRule = it->second;
766                     std::list<Replace>::iterator rit =
767                         subRule->replace_list.begin();
768                     for (; rit != subRule->replace_list.end(); rit++)
769                         rule->replace_list.push_back(*rit);
770                 }
771                 w.rule = rule;
772             }
773             w.reqline = values[4] == "1";
774             w.type = values[5];
775             if (w.type.empty() || w.type == "quoted-literal")
776                 ;
777             else
778                 throw mp::filter::FilterException
779                     ("within type must be quoted-literal or none in "
780                      " in http_rewrite filter");
781             within_list.push_back(w);
782         }
783     }
784 }
785
786 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
787 {
788     static const char *names[2] = { "verbose", 0 };
789     std::string values[1];
790     values[0] = "0";
791     mp::xml::parse_attr(ptr, names, values);
792
793     phase.m_verbose = atoi(values[0].c_str());
794
795     std::map<std::string, RulePtr > rules;
796     for (ptr = ptr->children; ptr; ptr = ptr->next)
797     {
798         if (ptr->type != XML_ELEMENT_NODE)
799             continue;
800         else if (!strcmp((const char *) ptr->name, "rule"))
801         {
802             static const char *names[2] = { "name", 0 };
803             std::string values[1];
804             values[0] = "default";
805             mp::xml::parse_attr(ptr, names, values);
806
807             RulePtr rule(new Rule);
808             for (xmlNode *p = ptr->children; p; p = p->next)
809             {
810                 if (p->type != XML_ELEMENT_NODE)
811                     continue;
812                 if (!strcmp((const char *) p->name, "rewrite"))
813                 {
814                     Replace replace;
815                     std::string from;
816                     const struct _xmlAttr *attr;
817                     for (attr = p->properties; attr; attr = attr->next)
818                     {
819                         if (!strcmp((const char *) attr->name,  "from"))
820                             from = mp::xml::get_text(attr->children);
821                         else if (!strcmp((const char *) attr->name,  "to"))
822                             replace.recipe = mp::xml::get_text(attr->children);
823                         else
824                             throw mp::filter::FilterException
825                                 ("Bad attribute "
826                                  + std::string((const char *) attr->name)
827                                  + " in rewrite section of http_rewrite");
828                     }
829                     yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
830                             from.c_str(), replace.recipe.c_str());
831                     if (!from.empty())
832                     {
833                         replace.parse_groups(from);
834                         rule->replace_list.push_back(replace);
835                     }
836                 }
837                 else
838                     throw mp::filter::FilterException
839                         ("Bad element "
840                          + std::string((const char *) p->name)
841                          + " in http_rewrite filter");
842             }
843             rules[values[0]] = rule;
844         }
845         else if (!strcmp((const char *) ptr->name, "content"))
846         {
847             static const char *names[3] =
848                 { "type", "mime", 0 };
849             std::string values[2];
850             mp::xml::parse_attr(ptr, names, values);
851             if (values[0].empty())
852             {
853                     throw mp::filter::FilterException
854                         ("Missing attribute, type for for element "
855                          + std::string((const char *) ptr->name)
856                          + " in http_rewrite filter");
857             }
858             Content c;
859
860             c.type = values[0];
861             if (!values[1].empty())
862                 c.content_re.assign(values[1], boost::regex::icase);
863             c.configure(ptr->children, rules);
864             phase.content_list.push_back(c);
865         }
866         else
867         {
868             throw mp::filter::FilterException
869                 ("Bad element "
870                  + std::string((const char *) ptr->name)
871                  + " in http_rewrite filter");
872         }
873     }
874 }
875
876 void yf::HttpRewrite::configure(const xmlNode * ptr, bool test_only,
877         const char *path)
878 {
879     for (ptr = ptr->children; ptr; ptr = ptr->next)
880     {
881         if (ptr->type != XML_ELEMENT_NODE)
882             continue;
883         else if (!strcmp((const char *) ptr->name, "request"))
884         {
885             configure_phase(ptr, *req_phase);
886         }
887         else if (!strcmp((const char *) ptr->name, "response"))
888         {
889             configure_phase(ptr, *res_phase);
890         }
891         else
892         {
893             throw mp::filter::FilterException
894                 ("Bad element "
895                  + std::string((const char *) ptr->name)
896                  + " in http_rewrite1 filter");
897         }
898     }
899 }
900
901 static mp::filter::Base* filter_creator()
902 {
903     return new mp::filter::HttpRewrite;
904 }
905
906 extern "C" {
907     struct metaproxy_1_filter_struct metaproxy_1_filter_http_rewrite = {
908         0,
909         "http_rewrite",
910         filter_creator
911     };
912 }
913
914
915 /*
916  * Local variables:
917  * c-basic-offset: 4
918  * c-file-style: "Stroustrup"
919  * indent-tabs-mode: nil
920  * End:
921  * vim: shiftwidth=4 tabstop=8 expandtab
922  */
923