From 694cb81cac5c72147a78ed4fd1ab88a9d3ded1a1 Mon Sep 17 00:00:00 2001 From: Joe Orton Date: Fri, 27 Nov 2026 15:23:32 +0000 Subject: [PATCH 1/3] mod_proxy_html: Fix handling of ProxyHTMLURLMap regex compile failures: * modules/filters/mod_proxy_html.c (comp_urlmap): Set regflags for interpolated rules too, and fail if the regex does not compile. (fixup_rules): Skip a rule whose interpolated regex does not compile; only evaluate conditions and interpolate with ProxyHTMLInterp on. (has_request_regex): New function. (check_filter_init): Use fixup_rules() for an interpolated regex without ProxyHTMLInterp. * test/modules/filters/test_011_proxy_html_urlmap.py: New test. * test/modules/filters/env.py (FiltersTestSetup.__init__): Load mod_xml2enc and mod_proxy_html if available. (FiltersTestEnv.__init__): Log mod_proxy_html at debug level. (FiltersTestEnv.configtest): New method. * changes-entries/proxy-html-urlmap-regex.txt: Add. Co-Authored-By: Claude Fable 5.2 --- changes-entries/proxy-html-urlmap-regex.txt | 3 + modules/filters/mod_proxy_html.c | 53 +++++++--- test/modules/filters/env.py | 20 +++- .../filters/test_011_proxy_html_urlmap.py | 96 +++++++++++++++++++ 4 files changed, 158 insertions(+), 14 deletions(-) create mode 100644 changes-entries/proxy-html-urlmap-regex.txt create mode 100644 test/modules/filters/test_011_proxy_html_urlmap.py diff --git a/changes-entries/proxy-html-urlmap-regex.txt b/changes-entries/proxy-html-urlmap-regex.txt new file mode 100644 index 00000000000..ac8b8e88b7d --- /dev/null +++ b/changes-entries/proxy-html-urlmap-regex.txt @@ -0,0 +1,3 @@ + *) mod_proxy_html: Fix a crash if a ProxyHTMLURLMap regex using + interpolated variables was invalid, and fail at startup for any + other invalid regex. [Joe Orton] diff --git a/modules/filters/mod_proxy_html.c b/modules/filters/mod_proxy_html.c index 3dffa5c8771..3c3cc7ce622 100644 --- a/modules/filters/mod_proxy_html.c +++ b/modules/filters/mod_proxy_html.c @@ -877,15 +877,30 @@ static const char *interpolate_vars(request_rec *r, const char *str) } return str; } +/* Whether any rule has a regex which is compiled per request. */ +static int has_request_regex(const urlmap *map) +{ + for (; map; map = map->next) { + if ((map->flags & M_REGEX) && (map->flags & M_INTERPOLATE_FROM)) + return 1; + } + return 0; +} + +/* Build the map for this request. Conditions and interpolation only + * apply with ProxyHTMLInterp on; without it the pattern of a regex rule + * flagged for interpolation is compiled as written. + */ static void fixup_rules(saxctxt *ctx) { urlmap *newp; urlmap *p; urlmap *prev = NULL; request_rec *r = ctx->f->r; + int interp = ctx->cfg->interp; for (p = ctx->cfg->map; p; p = p->next) { - if (p->cond != NULL) { + if (interp && p->cond != NULL) { const char *err; int ok = ap_expr_exec(r, p->cond, &err); if (err) { @@ -900,15 +915,23 @@ static void fixup_rules(saxctxt *ctx) newp = apr_pmemdup(r->pool, p, sizeof(urlmap)); if (newp->flags & M_INTERPOLATE_FROM) { - newp->from.c = interpolate_vars(r, newp->from.c); + if (interp) + newp->from.c = interpolate_vars(r, newp->from.c); if (!newp->from.c || !*newp->from.c) continue; /* don't use empty from-pattern */ if (newp->flags & M_REGEX) { - newp->from.r = ap_pregcomp(r->pool, newp->from.c, - newp->regflags); + const char *pattern = newp->from.c; + + newp->from.r = ap_pregcomp(r->pool, pattern, newp->regflags); + if (!newp->from.r) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10705) + "ProxyHTMLURLMap: could not compile " + "regex '%s', rule ignored", pattern); + continue; + } } } - if (newp->flags & M_INTERPOLATE_TO) { + if (interp && (newp->flags & M_INTERPOLATE_TO)) { newp->to = interpolate_vars(r, newp->to); } /* evaluate p->cond; continue if unsatisfied */ @@ -973,7 +996,7 @@ static saxctxt *check_filter_init (ap_filter_t *f) ap_varbuf_init(f->r->pool, &fctx->vb, bufsz); apr_table_unset(f->r->headers_out, "Content-Length"); - if (cfg->interp) + if (cfg->interp || has_request_regex(cfg->map)) fixup_rules(fctx); else fctx->map = cfg->map; @@ -1220,18 +1243,22 @@ static const char *comp_urlmap(cmd_parms *cmd, urlmap *newmap, | REGFLAG(M_INTERPOLATE_TO,flags,'V') | REGFLAG(M_INTERPOLATE_FROM,flags,'v'); + newmap->regflags + = REGFLAG(AP_REG_EXTENDED,flags,'x') + | REGFLAG(AP_REG_ICASE,flags,'i') + | REGFLAG(AP_REG_NOSUB,flags,'n') + | REGFLAG(AP_REG_NEWLINE,flags,'s'); + newmap->to = to; + if ((newmap->flags & M_INTERPOLATE_FROM) || !(newmap->flags & M_REGEX)) { newmap->from.c = from; - newmap->to = to; } else { - newmap->regflags - = REGFLAG(AP_REG_EXTENDED,flags,'x') - | REGFLAG(AP_REG_ICASE,flags,'i') - | REGFLAG(AP_REG_NOSUB,flags,'n') - | REGFLAG(AP_REG_NEWLINE,flags,'s'); newmap->from.r = ap_pregcomp(cmd->pool, from, newmap->regflags); - newmap->to = to; + if (!newmap->from.r) { + return apr_pstrcat(cmd->pool, "ProxyHTMLURLMap: could not " + "compile regex '", from, "'", NULL); + } } if (cond != NULL) { /* back-compatibility: support old-style ENV expressions diff --git a/test/modules/filters/env.py b/test/modules/filters/env.py index 149cdcdd4c7..f980371fc69 100644 --- a/test/modules/filters/env.py +++ b/test/modules/filters/env.py @@ -1,8 +1,10 @@ import inspect import logging import os +from typing import List from pyhttpd.env import HttpdTestEnv, HttpdTestSetup +from pyhttpd.result import ExecResult log = logging.getLogger(__name__) @@ -14,13 +16,29 @@ def __init__(self, env: 'HttpdTestEnv'): self.add_source_dir(os.path.dirname(inspect.getfile(FiltersTestSetup))) self.add_modules(["substitute", "sed", "buffer", "brotli", "ext_filter", "include", "deflate"]) self.add_cgi_module() + self.add_optional_modules(["xml2enc", "proxy_html"]) class FiltersTestEnv(HttpdTestEnv): def __init__(self, pytestconfig=None): super().__init__(pytestconfig=pytestconfig) - self.add_httpd_log_modules(["substitute", "sed", "buffer", "brotli", "ext_filter", "core"]) + self.add_httpd_log_modules(["substitute", "sed", "buffer", "brotli", "ext_filter", "core", "proxy_html"]) def setup_httpd(self, setup: HttpdTestSetup = None): super().setup_httpd(setup=FiltersTestSetup(env=self)) + + def configtest(self, lines: List[str]) -> ExecResult: + """Run `httpd -t` on a standalone config of the generated + modules.conf plus `lines`, leaving the running server alone.""" + conf_path = os.path.join(self.gen_dir, "filters-configtest.conf") + modules_conf = os.path.join(self.server_conf_dir, "modules.conf") + with open(conf_path, 'w') as fd: + fd.write('\n'.join([ + f'ServerRoot "{self.server_dir}"', + f'Include "{modules_conf}"', + f'DocumentRoot "{self.server_docs_dir}"', + f'Listen {self.http_port2}', + ] + lines) + '\n') + return self.run([os.path.join(self.bin_dir, 'httpd'), '-t', + '-f', conf_path]) diff --git a/test/modules/filters/test_011_proxy_html_urlmap.py b/test/modules/filters/test_011_proxy_html_urlmap.py new file mode 100644 index 00000000000..5bc1f56bc7b --- /dev/null +++ b/test/modules/filters/test_011_proxy_html_urlmap.py @@ -0,0 +1,96 @@ +import os + +import pytest + +from pyhttpd.backport import not_backported, skip_not_backported +from pyhttpd.conf import HttpdConf + +# ProxyHTMLURLMap rules with a regex ('R') which is interpolated per +# request ('v'): the pattern is only compiled once the request's +# environment is known, and may then turn out not to be a regex at all. +DOC = 'link' + +# Logged when the pattern for a request does not compile. +NO_COMPILE = r'.*ProxyHTMLURLMap: could not compile regex.*' + + +class TestProxyHTMLURLMap: + + @pytest.fixture(autouse=True, scope='class') + @classmethod + def _class_scope(cls, env): + env.require(env.has_shared_module("proxy_html"), + "mod_proxy_html not available", dep="mod_proxy_html", + detected=f"no mod_proxy_html.so in {env.libexec_dir}") + doc_dir = os.path.join(env.server_dir, "htdocs", "test1", "phtml") + os.makedirs(doc_dir, exist_ok=True) + with open(os.path.join(doc_dir, "doc.html"), "w") as f: + f.write(DOC) + conf = HttpdConf(env, extras={ + f"test1.{env.http_tld}": """ + SetEnvIf X-Foo "(.+)" FOO=$1 + + SetEnv PROXY_HTML_FORCE 1 + ProxyHTMLEnable On + ProxyHTMLLinks a href + + + ProxyHTMLInterp On + ProxyHTMLURLMap "${FOO}" "X" Rv + + + ProxyHTMLInterp On + ProxyHTMLURLMap "${FOO}" "X" Rvi + + + ProxyHTMLURLMap "Z.d" "X" Rv + + Alias /phtml/interp %s + Alias /phtml/icase %s + Alias /phtml/nointerp %s + """ % ((doc_dir,) * 3), + }) + conf.add_vhost_test1() + conf.install() + # The core warns that ${FOO} is not a variable it can expand. + env.httpd_error_log.add_ignored_lognos(["AH00111"]) + assert env.apache_restart() == 0 + + def get(self, env, path, foo=None): + options = ["-H", f"X-Foo: {foo}"] if foo else None + r = env.curl_get(env.mkurl("http", "test1", path), options=options) + assert r.response["status"] == 200 + return r.response["body"].decode() + + def test_filters_011_01_interpolated_regex(self, env): + assert 'href="/X/x"' in self.get(env, "/phtml/interp/doc.html", "Z.d") + + # The interpolated pattern is not a regex: the rule is ignored. + @skip_not_backported("gh-1104", "invalid interpolated regex") + def test_filters_011_02_interpolated_regex_invalid(self, env): + assert 'href="/Zed/x"' in self.get(env, "/phtml/interp/doc.html", "[") + env.httpd_error_log.ignore_recent(matches=[NO_COMPILE]) + # ... and the next request is not affected by it. + assert 'href="/X/x"' in self.get(env, "/phtml/interp/doc.html", "Zed") + + # The regex flags apply to an interpolated pattern too. + @not_backported("gh-1104", "regex flags with interpolation") + def test_filters_011_03_interpolated_regex_flags(self, env): + assert 'href="/X/x"' in self.get(env, "/phtml/icase/doc.html", "zED") + assert 'href="/Zed/x"' in self.get(env, "/phtml/interp/doc.html", "zED") + + # Without ProxyHTMLInterp nothing is interpolated, and the pattern is + # used as it was written. + @skip_not_backported("gh-1104", "interpolated regex without ProxyHTMLInterp") + def test_filters_011_04_regex_without_interp(self, env): + assert 'href="/X/x"' in self.get(env, "/phtml/nointerp/doc.html") + + @not_backported("gh-1104", "invalid regex is a configuration error") + def test_filters_011_05_invalid_regex_config(self, env): + r = env.configtest(['ProxyHTMLURLMap "[" "X" R']) + assert r.exit_code != 0 + assert "ProxyHTMLURLMap" in r.stderr + + def test_filters_011_06_valid_regex_config(self, env): + r = env.configtest(['ProxyHTMLURLMap "[a-z]" "X" R']) + assert r.exit_code == 0, r.stderr From 49e6651edbd339adbb1b6b446d32c41a87d6db1b Mon Sep 17 00:00:00 2001 From: Joe Orton Date: Fri, 27 Nov 2026 15:28:32 +0000 Subject: [PATCH 2/3] mod_proxy_html: Add ProxyHTMLMaxBufSize directive: * modules/filters/mod_proxy_html.c (buffer_text): New function. (pcdata, pcomment): Use it. (pendElement, pstartElement): Reset overflow state. (set_maxbufsz): New function. (proxy_html_config, proxy_html_merge, proxy_html_cmds): Add ProxyHTMLMaxBufSize, defaulting to 1M. * docs/manual/mod/mod_proxy_html.xml: Document ProxyHTMLMaxBufSize. * test/modules/filters/test_012_proxy_html_maxbuf.py: New test. * changes-entries/proxy-html-maxbufsize.txt: Add. Co-Authored-By: Claude Fable 5.2 --- changes-entries/proxy-html-maxbufsize.txt | 3 + docs/manual/mod/mod_proxy_html.xml | 25 ++++ modules/filters/mod_proxy_html.c | 68 ++++++++++- .../filters/test_012_proxy_html_maxbuf.py | 108 ++++++++++++++++++ 4 files changed, 200 insertions(+), 4 deletions(-) create mode 100644 changes-entries/proxy-html-maxbufsize.txt create mode 100644 test/modules/filters/test_012_proxy_html_maxbuf.py diff --git a/changes-entries/proxy-html-maxbufsize.txt b/changes-entries/proxy-html-maxbufsize.txt new file mode 100644 index 00000000000..7f58f2a7de1 --- /dev/null +++ b/changes-entries/proxy-html-maxbufsize.txt @@ -0,0 +1,3 @@ + *) mod_proxy_html: Add ProxyHTMLMaxBufSize, 1M by default; a larger + inline script, stylesheet or comment is passed through without + being rewritten by ProxyHTMLExtended. [Joe Orton] diff --git a/docs/manual/mod/mod_proxy_html.xml b/docs/manual/mod/mod_proxy_html.xml index 70d731b0a81..e0c078e054c 100644 --- a/docs/manual/mod/mod_proxy_html.xml +++ b/docs/manual/mod/mod_proxy_html.xml @@ -424,6 +424,31 @@ size and avoid the need to resize the buffer dynamically during a request. + +ProxyHTMLMaxBufSize +Sets the maximum size of an inline script, stylesheet or +comment which is rewritten. +ProxyHTMLMaxBufSize bytes +ProxyHTMLMaxBufSize 1M +server config +virtual hostdirectory + +Available in version 2.5.1 and later. + +

With ProxyHTMLExtended +enabled, mod_proxy_html reads each inline script, +stylesheet or comment into memory in full before rewriting it. This +directive limits the size of that buffer. A script, stylesheet or comment +larger than bytes is passed through as received from the +backend, without any ProxyHTMLURLMap rule applied to it, and a warning is +logged.

+

The value may be followed by K, M or +G for kilobytes, megabytes or gigabytes. A value of +0 removes the limit.

+
+
+ ProxyHTMLEvents Specify attributes to treat as scripting events. diff --git a/modules/filters/mod_proxy_html.c b/modules/filters/mod_proxy_html.c index 3c3cc7ce622..6b1a93d836a 100644 --- a/modules/filters/mod_proxy_html.c +++ b/modules/filters/mod_proxy_html.c @@ -109,6 +109,8 @@ typedef struct { const char *etag; unsigned int flags; int bufsz; + apr_size_t maxbufsz; + int maxbufsz_set; apr_hash_t *links; apr_array_header_t *events; const char *charset_out; @@ -130,9 +132,11 @@ typedef struct { char rbuf[4]; apr_size_t rlen; apr_size_t rmin; + int overflow; /* buffered text went over the limit */ } saxctxt; #define DEFAULT_BUFSZ (8192) +#define DEFAULT_MAXBUFSZ (1024 * 1024) #define NORM_LC 0x1 #define NORM_MSSLASH 0x2 @@ -356,12 +360,40 @@ static void pinternalSubset(void* ctxt, const xmlChar *name, } ap_fputs(ctx->f->next, ctx->bb, ">\n"); } + +/* Buffer text which is rewritten when the element ends. If the buffer + * would grow beyond ProxyHTMLMaxBufSize, write out what it holds and + * pass through the rest of the text up to the end of the element, + * none of it rewritten. + */ +static void buffer_text(saxctxt *ctx, const char *chars, apr_size_t length) +{ + apr_size_t max = ctx->cfg->maxbufsz; + + if (!ctx->overflow && max + && (ctx->vb.strlen > max || length > max - ctx->vb.strlen)) { + ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, ctx->f->r, APLOGNO(10706) + "Inline script, stylesheet or comment larger than " + "ProxyHTMLMaxBufSize (%" APR_SIZE_T_FMT + " bytes), not rewritten", max); + AP_fwrite(ctx, ctx->vb.buf, ctx->vb.strlen, 0); + ctx->vb.strlen = 0; + ctx->overflow = 1; + } + if (ctx->overflow) { + AP_fwrite(ctx, chars, length, 0); + } + else { + ap_varbuf_strmemcat(&ctx->vb, chars, length); + } +} + static void pcdata(void *ctxt, const xmlChar *uchars, int length) { const char *chars = (const char*) uchars; saxctxt *ctx = (saxctxt*) ctxt; if (ctx->cfg->extfix) { - ap_varbuf_strmemcat(&ctx->vb, chars, length); + buffer_text(ctx, chars, length); } else { /* not sure if this should force-flush @@ -378,9 +410,9 @@ static void pcomment(void *ctxt, const xmlChar *uchars) return; if (ctx->cfg->extfix) { - ap_varbuf_strcat(&ctx->vb, ""); + buffer_text(ctx, "", 3); } else { ap_fputs(ctx->f->next, ctx->bb, "

' + f'', +} + +NO_DIRECTIVE = not_backported("gh-1104", "ProxyHTMLMaxBufSize") + +TOO_LARGE = r'.*larger than ProxyHTMLMaxBufSize.*' + + +class TestProxyHTMLMaxBufSize: + + @pytest.fixture(autouse=True, scope='class') + @classmethod + def _class_scope(cls, env): + env.require(env.has_shared_module("proxy_html"), + "mod_proxy_html not available", dep="mod_proxy_html", + detected=f"no mod_proxy_html.so in {env.libexec_dir}") + doc_dir = os.path.join(env.server_dir, "htdocs", "test1", "phtml") + os.makedirs(doc_dir, exist_ok=True) + for name, text in DOCS.items(): + with open(os.path.join(doc_dir, name), "w") as f: + f.write(text) + cls.doc_dir = doc_dir + + def configure(self, env, maxbuf): + conf = HttpdConf(env, extras={ + f"test1.{env.http_tld}": f""" + + SetEnv PROXY_HTML_FORCE 1 + ProxyHTMLEnable On + ProxyHTMLExtended On + ProxyHTMLLinks a href + ProxyHTMLURLMap http://backend.example/ /proxy/ + {maxbuf} + + """, + }) + conf.add_vhost_test1() + conf.install() + assert env.apache_restart() == 0 + + def get(self, env, name): + r = env.curl_get(env.mkurl("http", "test1", f"/phtml/{name}")) + assert r.response["status"] == 200 + return r.response["body"].decode() + + @NO_DIRECTIVE + def test_filters_012_01_limit(self, env): + self.configure(env, f"ProxyHTMLMaxBufSize {MAXBUF}") + body = self.get(env, "small.html") + assert SMALL.replace("http://backend.example/", "/proxy/") in body + assert "backend.example" not in body + + # Over the limit: all of the script comes through untouched, the + # stylesheet after it is rewritten. + body = self.get(env, "large.html") + assert f"" in body + assert ("") in body + env.httpd_error_log.ignore_recent(matches=[TOO_LARGE]) + + body = self.get(env, "comment.html") + assert f"" in body + assert ("") in body + env.httpd_error_log.ignore_recent(matches=[TOO_LARGE]) + + @pytest.mark.parametrize("maxbuf", [ + pytest.param("ProxyHTMLMaxBufSize 0", marks=NO_DIRECTIVE), + pytest.param("ProxyHTMLMaxBufSize 1M", marks=NO_DIRECTIVE), + "", + ]) + def test_filters_012_02_under_limit(self, env, maxbuf): + self.configure(env, maxbuf) + for name in ["large.html", "comment.html"]: + assert "backend.example" not in self.get(env, name) + + @pytest.mark.parametrize("value, ok", [ + pytest.param("64K", True, marks=NO_DIRECTIVE), + pytest.param("0", True, marks=NO_DIRECTIVE), + ("-1", False), ("lots", False), + ]) + def test_filters_012_03_config(self, env, value, ok): + r = env.configtest([f"ProxyHTMLMaxBufSize {value}"]) + assert (r.exit_code == 0) == ok, r.stderr From 53f3cf2bc10c47d3f5b19cdc5eb646fa43d3b18f Mon Sep 17 00:00:00 2001 From: Joe Orton Date: Fri, 27 Nov 2026 15:30:16 +0000 Subject: [PATCH 3/3] mod_proxy_html: Disable HTML 4 clean-up with libxml2 >= 2.14: * modules/filters/mod_proxy_html.c (PROXY_HTML_ENFORCE): Define for libxml2 < 2.14. (fpi_html, fpi_html_legacy, fpi_xhtml, fpi_xhtml_legacy): Define only with PROXY_HTML_ENFORCE. (empty_elts, is_empty_elt): New, used without PROXY_HTML_ENFORCE. (pendElement, pstartElement): Compile element and attribute enforcement, and use htmlTagLookup(), only with PROXY_HTML_ENFORCE; drop the pragmas ignoring deprecated declarations. (set_doctype): Fail for the HTML and XHTML forms otherwise. * docs/manual/mod/mod_proxy_html.xml: Document the restriction on ProxyHTMLDocType. * test/modules/filters/test_013_proxy_html_doctype.py: New test. * test/pytest_suite/t/conf/proxy.conf.in: Use the HTML5 form of ProxyHTMLDocType. * changes-entries/proxy-html-doctype-libxml2.txt: Add. Co-Authored-By: Claude Fable 5.2 --- .../proxy-html-doctype-libxml2.txt | 3 + docs/manual/mod/mod_proxy_html.xml | 5 ++ modules/filters/mod_proxy_html.c | 70 +++++++++++++--- .../filters/test_013_proxy_html_doctype.py | 80 +++++++++++++++++++ test/pytest_suite/t/conf/proxy.conf.in | 2 +- 5 files changed, 148 insertions(+), 12 deletions(-) create mode 100644 changes-entries/proxy-html-doctype-libxml2.txt create mode 100644 test/modules/filters/test_013_proxy_html_doctype.py diff --git a/changes-entries/proxy-html-doctype-libxml2.txt b/changes-entries/proxy-html-doctype-libxml2.txt new file mode 100644 index 00000000000..ca5552f6df9 --- /dev/null +++ b/changes-entries/proxy-html-doctype-libxml2.txt @@ -0,0 +1,3 @@ + *) mod_proxy_html: Reject "ProxyHTMLDocType HTML|XHTML" if built with + libxml2 2.14 or later, with which HTML 4 documents can no longer + be cleaned up. [Joe Orton] diff --git a/docs/manual/mod/mod_proxy_html.xml b/docs/manual/mod/mod_proxy_html.xml index e0c078e054c..d9ac598020f 100644 --- a/docs/manual/mod/mod_proxy_html.xml +++ b/docs/manual/mod/mod_proxy_html.xml @@ -322,6 +322,11 @@ will also clean up the HTML to the specified standard. It cannot fix every error, but it will strip out bogus elements and attributes. It will also optionally log other errors at LogLevel Debug.

+The first form relies on the description of HTML 4 which +libxml2 provided up to version 2.13. If mod_proxy_html +is built with libxml2 2.14 or later, the first form is not available and +is rejected as a configuration error. To declare such a document type +without the clean-up, give it in the second form.
diff --git a/modules/filters/mod_proxy_html.c b/modules/filters/mod_proxy_html.c index 6b1a93d836a..4ab45417487 100644 --- a/modules/filters/mod_proxy_html.c +++ b/modules/filters/mod_proxy_html.c @@ -136,6 +136,33 @@ typedef struct { } saxctxt; #define DEFAULT_BUFSZ (8192) + +/* Cleaning up documents to HTML 4.01 or XHTML 1.0 relies on the element + * and attribute tables which libxml2 2.14 no longer has. + */ +#if LIBXML_VERSION < 21400 +#define PROXY_HTML_ENFORCE 1 +#endif + +#ifndef PROXY_HTML_ENFORCE +/* Elements which have no content and no end tag. */ +static const char *const empty_elts[] = { + "area", "base", "basefont", "bgsound", "br", "col", "embed", "frame", + "hr", "img", "input", "isindex", "keygen", "link", "meta", "param", + "source", "track", "wbr", NULL +}; + +static int is_empty_elt(const char *name) +{ + const char *const *e; + + for (e = empty_elts; *e; e++) { + if (!ap_cstr_casecmp(name, *e)) + return 1; + } + return 0; +} +#endif #define DEFAULT_MAXBUFSZ (1024 * 1024) #define NORM_LC 0x1 @@ -145,6 +172,7 @@ static htmlSAXHandler sax; typedef enum { ATTR_IGNORE, ATTR_URI, ATTR_EVENT } rewrite_t; +#ifdef PROXY_HTML_ENFORCE static const char *const fpi_html = "\n"; static const char *const fpi_html_legacy = @@ -153,6 +181,7 @@ static const char *const fpi_xhtml = "\n"; static const char *const fpi_xhtml_legacy = "\n"; +#endif static const char *const fpi_html5 = "\n"; static const char *const html_etag = ">"; static const char *const xhtml_etag = " />"; @@ -421,16 +450,13 @@ static void pcomment(void *ctxt, const xmlChar *uchars) } } -/* Deprecated in newer libxml2 releases. */ -#if defined(__clang__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif static void pendElement(void *ctxt, const xmlChar *uname) { saxctxt *ctx = (saxctxt*) ctxt; const char *name = (const char*) uname; +#ifdef PROXY_HTML_ENFORCE const htmlElemDesc* desc = htmlTagLookup(uname); + int empty = desc && desc->empty; if ((ctx->cfg->doctype == fpi_html) || (ctx->cfg->doctype == fpi_xhtml)) { /* enforce html */ @@ -444,6 +470,9 @@ static void pendElement(void *ctxt, const xmlChar *uname) if (!desc) return; } +#else + int empty = is_empty_elt(name); +#endif /* TODO - implement HTML "allowed here" using the stack */ /* nah. Keeping the stack is too much overhead */ @@ -452,7 +481,7 @@ static void pendElement(void *ctxt, const xmlChar *uname) ctx->vb.strlen = 0; /* having dumped it, we can re-use the memory */ } ctx->overflow = 0; - if (!desc || !desc->empty) { + if (!empty) { ap_fprintf(ctx->f->next, ctx->bb, "", name); } } @@ -460,7 +489,10 @@ static void pendElement(void *ctxt, const xmlChar *uname) static void pstartElement(void *ctxt, const xmlChar *uname, const xmlChar** uattrs) { +#ifdef PROXY_HTML_ENFORCE int required_attrs; + int enforce = 0; +#endif int num_match; size_t offs, len; rewrite_t is_uri; @@ -479,7 +511,12 @@ static void pstartElement(void *ctxt, const xmlChar *uname, int i; const char *name = (const char*) uname; const char** attrs = (const char**) uattrs; +#ifdef PROXY_HTML_ENFORCE const htmlElemDesc* desc = htmlTagLookup(uname); + int empty = desc && desc->empty; +#else + int empty = is_empty_elt(name); +#endif urlmap *themap = ctx->map; const char *accept_charset = NULL; struct ap_varbuf temp; @@ -488,7 +525,7 @@ static void pstartElement(void *ctxt, const xmlChar *uname, #ifdef HAVE_STACK const void** descp; #endif - int enforce = 0; +#ifdef PROXY_HTML_ENFORCE if ((ctx->cfg->doctype == fpi_html) || (ctx->cfg->doctype == fpi_xhtml)) { /* enforce html */ if (!desc || desc->depr) { @@ -508,6 +545,7 @@ static void pstartElement(void *ctxt, const xmlChar *uname, } enforce = 1; } +#endif #ifdef HAVE_STACK descp = apr_array_push(ctx->stack); *descp = desc; @@ -534,14 +572,17 @@ static void pstartElement(void *ctxt, const xmlChar *uname, ap_fputc(ctx->f->next, ctx->bb, '<'); ap_fputs(ctx->f->next, ctx->bb, name); +#ifdef PROXY_HTML_ENFORCE required_attrs = 0; if ((enforce > 0) && (desc != NULL) && (desc->attrs_req != NULL)) for (a = desc->attrs_req; *a; a++) ++required_attrs; +#endif if (attrs) { linkattrs = apr_hash_get(ctx->cfg->links, name, APR_HASH_KEY_STRING); for (a = attrs; *a; a += 2) { +#ifdef PROXY_HTML_ENFORCE if (desc && enforce > 0) { switch (htmlAttrAllowed(desc, (xmlChar*)*a, 2-enforce)) { case HTML_INVALID: @@ -561,6 +602,7 @@ static void pstartElement(void *ctxt, const xmlChar *uname, break; } } +#endif ctx->vb.strlen = 0; ctx->vb.buf[0] = '\0'; if (a[1]) { @@ -785,22 +827,21 @@ static void pstartElement(void *ctxt, const xmlChar *uname, } ctx->vb.strlen = 0; ctx->overflow = 0; - if (desc && desc->empty) + if (empty) ap_fputs(ctx->f->next, ctx->bb, ctx->etag); else ap_fputc(ctx->f->next, ctx->bb, '>'); +#ifdef PROXY_HTML_ENFORCE if ((enforce > 0) && (required_attrs > 0)) { /* if there are more required attributes than we found then complain */ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, ctx->f->r, APLOGNO(01420) "HTML element %s is missing %d required attributes", name, required_attrs); } +#endif ap_varbuf_free(&temp); } -#if defined(__clang__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) -#pragma GCC diagnostic pop -#endif static meta *metafix(request_rec *r, const char *buf, apr_size_t len) { @@ -1368,6 +1409,7 @@ static const char *set_doctype(cmd_parms *cmd, void *CFG, if (!strcasecmp(t, "auto")) { cfg->doctype = DEFAULT_DOCTYPE; /* activates pinternalSubset */ } +#ifdef PROXY_HTML_ENFORCE else if (!strcasecmp(t, "xhtml")) { cfg->etag = xhtml_etag; if (l && !strcasecmp(l, "legacy")) @@ -1382,6 +1424,12 @@ static const char *set_doctype(cmd_parms *cmd, void *CFG, else cfg->doctype = fpi_html; } +#else + else if (!strcasecmp(t, "xhtml") || !strcasecmp(t, "html")) { + return "ProxyHTMLDocType HTML and XHTML are not available " + "with libxml2 2.14 or later"; + } +#endif else if (!strcasecmp(t, "html5")) { cfg->etag = html_etag; cfg->doctype = fpi_html5; diff --git a/test/modules/filters/test_013_proxy_html_doctype.py b/test/modules/filters/test_013_proxy_html_doctype.py new file mode 100644 index 00000000000..80389c74b4a --- /dev/null +++ b/test/modules/filters/test_013_proxy_html_doctype.py @@ -0,0 +1,80 @@ +import os + +import pytest + +from pyhttpd.backport import not_backported +from pyhttpd.conf import HttpdConf + +# "ProxyHTMLDocType HTML|XHTML [Legacy]" cleans up the document, dropping +# elements and attributes which HTML 4 does not have. It relies on tables +# which libxml2 2.14 removed, so a module built with a newer libxml2 +# refuses those forms rather than accept them and clean up nothing. +DOC = ('t' + '

text
more

' + 'old' + '') + +ENFORCING = ["HTML", "XHTML", "HTML Legacy", "XHTML Legacy"] + + +class TestProxyHTMLDocType: + + @pytest.fixture(autouse=True, scope='class') + @classmethod + def _class_scope(cls, env): + env.require(env.has_shared_module("proxy_html"), + "mod_proxy_html not available", dep="mod_proxy_html", + detected=f"no mod_proxy_html.so in {env.libexec_dir}") + doc_dir = os.path.join(env.server_dir, "htdocs", "test1", "phtml") + os.makedirs(doc_dir, exist_ok=True) + with open(os.path.join(doc_dir, "doctype.html"), "w") as f: + f.write(DOC) + + def get(self, env, doctype): + conf = HttpdConf(env, extras={ + f"test1.{env.http_tld}": f""" + + SetEnv PROXY_HTML_FORCE 1 + ProxyHTMLEnable On + ProxyHTMLLinks a href + ProxyHTMLDocType {doctype} + + """, + }) + conf.add_vhost_test1() + conf.install() + assert env.apache_restart() == 0 + r = env.curl_get(env.mkurl("http", "test1", "/phtml/doctype.html")) + assert r.response["status"] == 200 + return r.response["body"].decode() + + # Either the form is refused, or it does what is documented. (An + # unpatched server fails this only if built with libxml2 >= 2.14.) + @not_backported("gh-1104", "ProxyHTMLDocType with libxml2 2.14") + @pytest.mark.parametrize("doctype", ENFORCING) + def test_filters_013_01_enforcing(self, env, doctype): + r = env.configtest([f"ProxyHTMLDocType {doctype}"]) + if r.exit_code != 0: + assert "libxml2" in r.stderr + return + body = self.get(env, doctype) + assert 'class="ok"' in body + assert "data-bogus" not in body + if "Legacy" not in doctype: + assert "" not in body + assert "old" in body + + # The other forms never cleaned anything up. + @pytest.mark.parametrize("doctype, declared", [ + ("HTML5", ""), + ("auto", None), + ('"-//W3C//DTD HTML 4.01//EN"', "-//W3C//DTD HTML 4.01//EN"), + ]) + def test_filters_013_02_other_forms(self, env, doctype, declared): + body = self.get(env, doctype) + if declared: + assert body.startswith(declared) + assert 'data-bogus="x"' in body + assert 'old' in body + # an empty element gets no end tag + assert "text
more" in body diff --git a/test/pytest_suite/t/conf/proxy.conf.in b/test/pytest_suite/t/conf/proxy.conf.in index 3025038a494..dab47b48620 100644 --- a/test/pytest_suite/t/conf/proxy.conf.in +++ b/test/pytest_suite/t/conf/proxy.conf.in @@ -325,7 +325,7 @@ Alias /modules/proxy/fcgi-uds-sethandler @SERVERROOT@/htdocs/modules/proxy/fcgi ProxyHTMLEnable on ProxyHTMLLinks a href - ProxyHTMLDocType HTML + ProxyHTMLDocType HTML5 ProxyHTMLURLMap http://a.example.com/ http://b.example.com/ ProxyPass http://@SERVERNAME@:@PORT@/modules/proxy_html