http_rewrite: fix start anchor (^) match
[metaproxy-moved-to-github.git] / src / filter_http_rewrite.cpp
index 4a35bad..145d7fe 100644 (file)
@@ -21,12 +21,15 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 #include <metaproxy/package.hpp>
 #include <metaproxy/util.hpp>
 #include "filter_http_rewrite.hpp"
+#include "html_parser.hpp"
 
 #include <yaz/zgdu.h>
 #include <yaz/log.h>
 
+#include <stack>
 #include <boost/regex.hpp>
 #include <boost/lexical_cast.hpp>
+#include <boost/algorithm/string.hpp>
 
 #include <map>
 
@@ -37,15 +40,14 @@ namespace metaproxy_1 {
     namespace filter {
         class HttpRewrite::Replace {
         public:
-            std::string regex;
+            bool start_anchor;
+            boost::regex re;
+            boost::smatch what;
             std::string recipe;
             std::map<int, std::string> group_index;
-            const std::string search_replace(
-                std::map<std::string, std::string> & vars,
-                const std::string & txt) const;
-            std::string sub_vars (
+            std::string sub_vars(
                 const std::map<std::string, std::string> & vars) const;
-            void parse_groups();
+            void parse_groups(std::string pattern);
         };
 
         class HttpRewrite::Rule {
@@ -53,19 +55,22 @@ namespace metaproxy_1 {
             std::list<Replace> replace_list;
             const std::string test_patterns(
                 std::map<std::string, std::string> & vars,
-                const std::string & txt) const;
+                const std::string & txt);
         };
         class HttpRewrite::Within {
         public:
             std::string header;
             std::string attr;
             std::string tag;
+            bool reqline;
             RulePtr rule;
         };
 
         class HttpRewrite::Phase {
         public:
+            Phase();
             std::list<Within> within_list;
+            int m_verbose;
             void rewrite_reqline(mp::odr & o, Z_HTTP_Request *hreq,
                 std::map<std::string, std::string> & vars) const;
             void rewrite_headers(mp::odr & o, Z_HTTP_Header *headers,
@@ -74,6 +79,24 @@ namespace metaproxy_1 {
                 char **content_buf, int *content_len,
                 std::map<std::string, std::string> & vars) const;
         };
+        class HttpRewrite::Event : public HTMLParserEvent {
+            void openTagStart(const char *tag, int tag_len);
+            void anyTagEnd(const char *tag, int tag_len, int close_it);
+            void attribute(const char *tag, int tag_len,
+                           const char *attr, int attr_len,
+                           const char *value, int val_len,
+                           const char *sep);
+            void closeTag(const char *tag, int tag_len);
+            void text(const char *value, int len);
+            const Phase *m_phase;
+            WRBUF m_w;
+            std::stack<std::list<Within>::const_iterator> s_within;
+            std::map<std::string, std::string> &m_vars;
+        public:
+            Event(const Phase *p, std::map<std::string, std::string> &vars);
+            ~Event();
+            const char *result();
+        };
     }
 }
 
@@ -134,56 +157,63 @@ void yf::HttpRewrite::Phase::rewrite_reqline (mp::odr & o,
     else
     {
         //TODO what about proto
+        const char *host = z_HTTP_header_lookup(hreq->headers, "Host");
+        if (!host)
+            return;
+
         path += "http://";
-        path += z_HTTP_header_lookup(hreq->headers, "Host");
+        path += host;
         path += hreq->path;
     }
 
-    std::list<Within>::const_iterator it = within_list.begin();
-    if (it != within_list.end())
-    {
-        RulePtr rule = it->rule;
 
-        yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
-        std::string npath = rule->test_patterns(vars, path);
-        if (!npath.empty())
+    std::list<Within>::const_iterator it = within_list.begin();
+    for (; it != within_list.end(); it++)
+        if (it->reqline)
         {
-            yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
-            hreq->path = odr_strdup(o, npath.c_str());
+            RulePtr rule = it->rule;
+            yaz_log(YLOG_LOG, "Proxy request URL is %s", path.c_str());
+            std::string npath = rule->test_patterns(vars, path);
+            if (!npath.empty())
+            {
+                yaz_log(YLOG_LOG, "Rewritten request URL is %s", npath.c_str());
+                hreq->path = odr_strdup(o, npath.c_str());
+            }
         }
-    }
 }
 
 void yf::HttpRewrite::Phase::rewrite_headers(mp::odr & o,
         Z_HTTP_Header *headers,
         std::map<std::string, std::string> & vars) const
 {
-    for (Z_HTTP_Header *header = headers;
-            header != 0;
-            header = header->next)
+    for (Z_HTTP_Header *header = headers; header; header = header->next)
     {
-        std::string sheader(header->name);
-        sheader += ": ";
-        sheader += header->value;
-        yaz_log(YLOG_LOG, "%s: %s", header->name, header->value);
-
         std::list<Within>::const_iterator it = within_list.begin();
-        if (it == within_list.end())
-            continue;
-        RulePtr rule = it->rule;
-
-        std::string out = rule->test_patterns(vars, sheader);
-        if (!out.empty())
+        for (; it != within_list.end(); it++)
         {
-            size_t pos = out.find(": ");
-            if (pos == std::string::npos)
+            if (it->header.length() > 0 &&
+                yaz_strcasecmp(it->header.c_str(), header->name) == 0)
             {
-                yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
-                continue;
+                std::string sheader(header->name);
+                sheader += ": ";
+                sheader += header->value;
+
+                RulePtr rule = it->rule;
+                std::string out = rule->test_patterns(vars, sheader);
+                if (!out.empty())
+                {
+                    size_t pos = out.find(": ");
+                    if (pos == std::string::npos)
+                    {
+                        yaz_log(YLOG_LOG, "Header malformed during rewrite, ignoring");
+                        continue;
+                    }
+                    header->name = odr_strdup(o, out.substr(0, pos).c_str());
+                    header->value = odr_strdup(o,
+                                               out.substr(pos + 2,
+                                                          std::string::npos).c_str());
+                }
             }
-            header->name = odr_strdup(o, out.substr(0, pos).c_str());
-            header->value = odr_strdup(o, out.substr(pos+2,
-                                                     std::string::npos).c_str());
         }
     }
 }
@@ -195,87 +225,231 @@ void yf::HttpRewrite::Phase::rewrite_body(mp::odr & o,
 {
     if (*content_buf)
     {
+        int i;
+        for (i = 0; i < *content_len; i++)
+            if ((*content_buf)[i] == 0)
+                return;  // binary content. skip
 
-        std::list<Within>::const_iterator it = within_list.begin();
-        if (it != within_list.end())
+        HTMLParser parser;
+        Event ev(this, vars);
+
+        parser.set_verbose(m_verbose);
+
+        std::string buf(*content_buf, *content_len);
+
+        parser.parse(ev, buf.c_str());
+        const char *res = ev.result();
+        *content_buf = odr_strdup(o, res);
+        *content_len = strlen(res);
+    }
+}
+
+yf::HttpRewrite::Event::Event(const Phase *p,
+                              std::map<std::string, std::string> & vars
+    ) : m_phase(p), m_vars(vars)
+{
+    m_w = wrbuf_alloc();
+}
+
+yf::HttpRewrite::Event::~Event()
+{
+    wrbuf_destroy(m_w);
+}
+
+const char *yf::HttpRewrite::Event::result()
+{
+    return wrbuf_cstr(m_w);
+}
+
+void yf::HttpRewrite::Event::openTagStart(const char *tag, int tag_len)
+{
+    wrbuf_putc(m_w, '<');
+    wrbuf_write(m_w, tag, tag_len);
+
+    std::string t(tag, tag_len);
+    std::list<Within>::const_iterator it = m_phase->within_list.begin();
+    for (; it != m_phase->within_list.end(); it++)
+    {
+        if (it->tag.length() > 0 && yaz_strcasecmp(it->tag.c_str(),
+                                                   t.c_str()) == 0)
         {
-            RulePtr rule = it->rule;
+            std::vector<std::string> attr;
+            boost::split(attr, it->attr, boost::is_any_of(","));
+            size_t i;
+            for (i = 0; i < attr.size(); i++)
+            {
+                if (attr[i].compare("#text") == 0)
+                {
+                    s_within.push(it);
+                    return;
+                }
+            }
+        }
+    }
+}
+
+void yf::HttpRewrite::Event::anyTagEnd(const char *tag, int tag_len,
+                                       int close_it)
+{
+    if (close_it)
+    {
+        if (!s_within.empty())
+        {
+            std::list<Within>::const_iterator it = s_within.top();
+            std::string t(tag, tag_len);
+            if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
+                s_within.pop();
+        }
+    }
+    if (close_it)
+        wrbuf_putc(m_w, '/');
+    wrbuf_putc(m_w, '>');
+}
+
+void yf::HttpRewrite::Event::attribute(const char *tag, int tag_len,
+                                       const char *attr, int attr_len,
+                                       const char *value, int val_len,
+                                       const char *sep)
+{
+    std::list<Within>::const_iterator it = m_phase->within_list.begin();
+    bool subst = false;
 
-            std::string body(*content_buf);
-            std::string nbody = rule->test_patterns(vars, body);
-            if (!nbody.empty())
+    for (; it != m_phase->within_list.end(); it++)
+    {
+        std::string t(tag, tag_len);
+        if (it->tag.length() == 0 ||
+            yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
+        {
+            std::string a(attr, attr_len);
+            std::vector<std::string> attr;
+            boost::split(attr, it->attr, boost::is_any_of(","));
+            size_t i;
+            for (i = 0; i < attr.size(); i++)
             {
-                *content_buf = odr_strdup(o, nbody.c_str());
-                *content_len = nbody.size();
+                if (attr[i].compare("#text") &&
+                    yaz_strcasecmp(attr[i].c_str(), a.c_str()) == 0)
+                    subst = true;
             }
         }
+        if (subst)
+            break;
+    }
+
+    wrbuf_putc(m_w, ' ');
+    wrbuf_write(m_w, attr, attr_len);
+    if (value)
+    {
+        wrbuf_puts(m_w, "=");
+        wrbuf_puts(m_w, sep);
+
+        std::string output;
+        if (subst)
+        {
+            std::string input(value, val_len);
+            output = it->rule->test_patterns(m_vars, input);
+        }
+        if (output.empty())
+            wrbuf_write(m_w, value, val_len);
+        else
+            wrbuf_puts(m_w, output.c_str());
+        wrbuf_puts(m_w, sep);
     }
 }
 
-/**
- * Tests pattern from the vector in order and executes recipe on
- the first match.
- */
-const std::string yf::HttpRewrite::Rule::test_patterns(
-        std::map<std::string, std::string> & vars,
-        const std::string & txt) const
+void yf::HttpRewrite::Event::closeTag(const char *tag, int tag_len)
 {
-    std::list<Replace>::const_iterator it = replace_list.begin();
+    if (!s_within.empty())
+    {
+        std::list<Within>::const_iterator it = s_within.top();
+        std::string t(tag, tag_len);
+        if (yaz_strcasecmp(it->tag.c_str(), t.c_str()) == 0)
+            s_within.pop();
+    }
+    wrbuf_puts(m_w, "</");
+    wrbuf_write(m_w, tag, tag_len);
+}
 
-    for (; it != replace_list.end(); it++)
+void yf::HttpRewrite::Event::text(const char *value, int len)
+{
+    std::list<Within>::const_iterator it = m_phase->within_list.end();
+    if (!s_within.empty())
+        it = s_within.top();
+    std::string output;
+    if (it != m_phase->within_list.end())
     {
-        std::string out = it->search_replace(vars, txt);
-        if (!out.empty()) return out;
+        std::string input(value, len);
+        output = it->rule->test_patterns(m_vars, input);
     }
-    return "";
+    if (output.empty())
+        wrbuf_write(m_w, value, len);
+    else
+        wrbuf_puts(m_w, output.c_str());
 }
 
-const std::string yf::HttpRewrite::Replace::search_replace(
+const std::string yf::HttpRewrite::Rule::test_patterns(
         std::map<std::string, std::string> & vars,
-        const std::string & txt) const
+        const std::string & txt)
 {
-    //exec regex against value
-    boost::regex re(regex);
-    boost::smatch what;
+    bool first = true;
+    std::string out;
     std::string::const_iterator start, end;
     start = txt.begin();
     end = txt.end();
-    std::string out;
-    while (regex_search(start, end, what, re)) //find next full match
+    while (1)
     {
+        std::list<Replace>::iterator bit = replace_list.end();
+        {
+            std::string::const_iterator best_pos = txt.end();
+            std::list<Replace>::iterator it = replace_list.begin();
+            for (; it != replace_list.end(); it++)
+            {
+                if (it->start_anchor && !first)
+                    continue;
+                if (regex_search(start, end, it->what, it->re))
+                {
+                    if (it->what[0].first < best_pos)
+                    {
+                        best_pos = it->what[0].first;
+                        bit = it;
+                    }
+                }
+            }
+            if (bit == replace_list.end())
+                break;
+        }
+        first = false;
         size_t i;
-        for (i = 1; i < what.size(); ++i)
+        for (i = 1; i < bit->what.size(); ++i)
         {
             //check if the group is named
-            std::map<int, std::string>::const_iterator it
-                = group_index.find(i);
-            if (it != group_index.end())
+            std::map<int, std::string>::const_iterator git
+                = bit->group_index.find(i);
+            if (git != bit->group_index.end())
             {   //it is
-                if (!what[i].str().empty())
-                    vars[it->second] = what[i];
+                vars[git->second] = bit->what[i];
             }
 
         }
         //prepare replacement string
-        std::string rvalue = sub_vars(vars);
+        std::string rvalue = bit->sub_vars(vars);
         yaz_log(YLOG_LOG, "! Rewritten '%s' to '%s'",
-                what.str(0).c_str(), rvalue.c_str());
-        out.append(start, what[0].first);
+                bit->what.str(0).c_str(), rvalue.c_str());
+        out.append(start, bit->what[0].first);
         out.append(rvalue);
-        start = what[0].second; //move search forward
+        start = bit->what[0].second; //move search forward
     }
-    //if we had a match cat the last part
     if (start != txt.begin())
         out.append(start, end);
     return out;
 }
 
-void yf::HttpRewrite::Replace::parse_groups()
+void yf::HttpRewrite::Replace::parse_groups(std::string pattern)
 {
     int gnum = 0;
     bool esc = false;
-    const std::string & str = regex;
+    const std::string &str = pattern;
     std::string res;
+    start_anchor = str[0] == '^';
     yaz_log(YLOG_LOG, "Parsing groups from '%s'", str.c_str());
     for (size_t i = 0; i < str.size(); ++i)
     {
@@ -330,11 +504,11 @@ void yf::HttpRewrite::Replace::parse_groups()
         }
         esc = false;
     }
-    regex = res;
+    re = res;
 }
 
-std::string yf::HttpRewrite::Replace::sub_vars (
-        const std::map<std::string, std::string> & vars) const
+std::string yf::HttpRewrite::Replace::sub_vars(
+    const std::map<std::string, std::string> & vars) const
 {
     std::string out;
     bool esc = false;
@@ -383,9 +557,19 @@ std::string yf::HttpRewrite::Replace::sub_vars (
     return out;
 }
 
+yf::HttpRewrite::Phase::Phase() : m_verbose(0)
+{
+}
 
 void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
 {
+    static const char *names[2] = { "verbose", 0 };
+    std::string values[1];
+    values[0] = "0";
+    mp::xml::parse_attr(ptr, names, values);
+
+    phase.m_verbose = atoi(values[0].c_str());
+
     std::map<std::string, RulePtr > rules;
     for (ptr = ptr->children; ptr; ptr = ptr->next)
     {
@@ -406,11 +590,12 @@ void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
                 if (!strcmp((const char *) p->name, "rewrite"))
                 {
                     Replace replace;
+                    std::string from;
                     const struct _xmlAttr *attr;
                     for (attr = p->properties; attr; attr = attr->next)
                     {
                         if (!strcmp((const char *) attr->name,  "from"))
-                            replace.regex = mp::xml::get_text(attr->children);
+                            from = mp::xml::get_text(attr->children);
                         else if (!strcmp((const char *) attr->name,  "to"))
                             replace.recipe = mp::xml::get_text(attr->children);
                         else
@@ -420,10 +605,12 @@ void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
                                  + " in rewrite section of http_rewrite");
                     }
                     yaz_log(YLOG_LOG, "Found rewrite rule from '%s' to '%s'",
-                            replace.regex.c_str(), replace.recipe.c_str());
-                    replace.parse_groups();
-                    if (!replace.regex.empty())
+                            from.c_str(), replace.recipe.c_str());
+                    if (!from.empty())
+                    {
+                        replace.parse_groups(from);
                         rule->replace_list.push_back(replace);
+                    }
                 }
                 else
                     throw mp::filter::FilterException
@@ -431,14 +618,13 @@ void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
                          + std::string((const char *) p->name)
                          + " in http_rewrite filter");
             }
-            if (!rule->replace_list.empty())
-                rules[values[0]] = rule;
+            rules[values[0]] = rule;
         }
         else if (!strcmp((const char *) ptr->name, "within"))
         {
-            static const char *names[5] =
-                { "header", "attr", "tag", "rule", 0 };
-            std::string values[4];
+            static const char *names[6] =
+                { "header", "attr", "tag", "rule", "reqline", 0 };
+            std::string values[5];
             mp::xml::parse_attr(ptr, names, values);
             Within w;
             w.header = values[0];
@@ -451,6 +637,7 @@ void yf::HttpRewrite::configure_phase(const xmlNode *ptr, Phase &phase)
                     ("Reference to non-existing rule '" + values[3] +
                      "' in http_rewrite filter");
             w.rule = it->second;
+            w.reqline = values[4] == "1";
             phase.within_list.push_back(w);
         }
         else