From eb93746dbad05570800da7aba57109b185f3b504 Mon Sep 17 00:00:00 2001 From: Yann Ylavic Date: Tue, 16 Jan 2024 16:51:03 +0000 Subject: [PATCH 01/10] Merge r1915267 from trunk (conflicts resolved in include/ap_mmn.h, server/util_pcre.c): regex: Add ap_regexec_ex() which can take a starting offset to match from. * include/ap_mmn.h: Bump MMN minor. * include/ap_regex.h: Declare ap_regexec_ex(). * server/util_pcre.c(ap_regexec, ap_regexec_len, ap_regexec_ex): Reuse existing ap_regexec_len() code to implement ap_regexec_ex() where the offset is given instead of zero, then implement ap_regexec{,len}() in terms of ap_regexec_ex(). git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1915267 13f79535-47bb-0310-9956-ffa450edef68 (cherry picked from commit e52a206008bdfced5551206d695b3c01b7d1948a) --- include/ap_mmn.h | 3 ++- include/ap_regex.h | 27 +++++++++++++++++++++++---- server/util_pcre.c | 31 +++++++++++++++++++++++-------- 3 files changed, 48 insertions(+), 13 deletions(-) diff --git a/include/ap_mmn.h b/include/ap_mmn.h index d00c6d1ec9c..595fb178c82 100644 --- a/include/ap_mmn.h +++ b/include/ap_mmn.h @@ -612,6 +612,7 @@ * 20120211.140 (2.4.64-dev) Add ap_set_time_process_request() to scoreboard.h * 20120211.141 (2.4.64-dev) add ap_stat_check() to httpd.h * 20120211.142 (2.4.64-dev) Add ap_*_timingsafe() to httpd.h + * 20120211.143 (2.4.72-dev) Add ap_regexec_ex() */ #define MODULE_MAGIC_COOKIE 0x41503234UL /* "AP24" */ @@ -619,7 +620,7 @@ #ifndef MODULE_MAGIC_NUMBER_MAJOR #define MODULE_MAGIC_NUMBER_MAJOR 20120211 #endif -#define MODULE_MAGIC_NUMBER_MINOR 142 /* 0...n */ +#define MODULE_MAGIC_NUMBER_MINOR 143 /* 0...n */ /** * Determine if the server's current MODULE_MAGIC_NUMBER is at least a diff --git a/include/ap_regex.h b/include/ap_regex.h index d6afbb17d76..d45bb7a0d4d 100644 --- a/include/ap_regex.h +++ b/include/ap_regex.h @@ -169,7 +169,8 @@ AP_DECLARE(int) ap_regcomp(ap_regex_t *preg, const char *regex, int cflags); * @return 0 for successful match, \p AP_REG_NOMATCH otherwise */ AP_DECLARE(int) ap_regexec(const ap_regex_t *preg, const char *string, - apr_size_t nmatch, ap_regmatch_t *pmatch, int eflags); + apr_size_t nmatch, ap_regmatch_t *pmatch, + int eflags); /** * Match a string with given length against a pre-compiled regex. The string @@ -183,10 +184,28 @@ AP_DECLARE(int) ap_regexec(const ap_regex_t *preg, const char *string, * other flags are ignored) * @return 0 for successful match, AP_REG_NOMATCH otherwise */ -AP_DECLARE(int) ap_regexec_len(const ap_regex_t *preg, const char *buff, - apr_size_t len, apr_size_t nmatch, - ap_regmatch_t *pmatch, int eflags); +AP_DECLARE(int) ap_regexec_len(const ap_regex_t *preg, + const char *buff, apr_size_t len, + apr_size_t nmatch, ap_regmatch_t *pmatch, + int eflags); +/** + * Match a string with given length and at a given offset against a + * pre-compiled regex. The string does not need to be NUL-terminated. + * @param preg The pre-compiled regex + * @param buff The string to match + * @param len Length of the string to match + * @param pos Offset in the string where the match should (re)start + * @param nmatch Provide information regarding the location of any matches + * @param pmatch Provide information regarding the location of any matches + * @param eflags Bitwise OR of AP_REG_* flags (NOTBOL and NOTEOL supported, + * other flags are ignored) + * @return 0 for successful match, AP_REG_NOMATCH otherwise + */ +AP_DECLARE(int) ap_regexec_ex(const ap_regex_t *preg, + const char *buff, apr_size_t len, apr_size_t pos, + apr_size_t nmatch, ap_regmatch_t *pmatch, + int eflags); /** * Return the error code returned by regcomp or regexec into error messages * @param errcode the error code returned by regexec or regcomp diff --git a/server/util_pcre.c b/server/util_pcre.c index 46e82112a58..8f36ce7f4f2 100644 --- a/server/util_pcre.c +++ b/server/util_pcre.c @@ -396,13 +396,22 @@ AP_DECLARE(int) ap_regexec(const ap_regex_t *preg, const char *string, apr_size_t nmatch, ap_regmatch_t *pmatch, int eflags) { - return ap_regexec_len(preg, string, strlen(string), nmatch, pmatch, - eflags); + return ap_regexec_ex(preg, string, strlen(string), 0, + nmatch, pmatch, eflags); } -AP_DECLARE(int) ap_regexec_len(const ap_regex_t *preg, const char *buff, - apr_size_t len, apr_size_t nmatch, - ap_regmatch_t *pmatch, int eflags) +AP_DECLARE(int) ap_regexec_len(const ap_regex_t *preg, + const char *buff, apr_size_t len, + apr_size_t nmatch, ap_regmatch_t *pmatch, + int eflags) +{ + return ap_regexec_ex(preg, buff, len, 0, nmatch, pmatch, eflags); +} + +AP_DECLARE(int) ap_regexec_ex(const ap_regex_t *preg, + const char *buff, apr_size_t len, apr_size_t pos, + apr_size_t nmatch, ap_regmatch_t *pmatch, + int eflags) { int rc; int options = 0, to_free = 0; @@ -412,7 +421,13 @@ AP_DECLARE(int) ap_regexec_len(const ap_regex_t *preg, const char *buff, match_data_pt data = get_match_data(ncaps, NULL, &to_free); #else int small_vector[POSIX_MALLOC_THRESHOLD * 3]; - match_data_pt data = get_match_data(ncaps, small_vector, &to_free); + match_data_pt data; + + /* PCRE1 uses ints, reject overflowing values */ + if (len > APR_INT32_MAX || pos > APR_INT32_MAX) { + return AP_REG_INVARG; + } + data = get_match_data(ncaps, small_vector, &to_free); #endif if (!data) { @@ -427,12 +442,12 @@ AP_DECLARE(int) ap_regexec_len(const ap_regex_t *preg, const char *buff, #ifdef HAVE_PCRE2 rc = pcre2_match((const pcre2_code *)preg->re_pcre, (const unsigned char *)buff, len, - 0, options, data, NULL); + pos, options, data, NULL); ovector = pcre2_get_ovector_pointer(data); #else ovector = data; rc = pcre_exec((const pcre *)preg->re_pcre, NULL, buff, (int)len, - 0, options, ovector, ncaps * 3); + (int)pos, options, ovector, ncaps * 3); #endif if (rc >= 0) { From 2372f46294f4f57c1b5e4c96954f205eff733631 Mon Sep 17 00:00:00 2001 From: Yann Ylavic Date: Tue, 16 Jan 2024 16:56:58 +0000 Subject: [PATCH 02/10] Merge r1915268 from trunk (conflicts resolved in include/ap_mmn.h, server/util_pcre.c): regex: Add AP_REG_NOTEMPTY_ATSTART maching option. * include/ap_mmn.h: Bump MMN minor. * include/ap_regex.h: Define AP_REG_NOTEMPTY_ATSTART bit. * server/util_pcre.c(ap_regexec_ex): Map AP_REG_NOTEMPTY_ATSTART to native PCRE_NOTEMPTY_ATSTART. git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1915268 13f79535-47bb-0310-9956-ffa450edef68 (cherry picked from commit 97a18733327438ac52ac13b2904e4319dca5ce0d) --- include/ap_mmn.h | 3 ++- include/ap_regex.h | 2 ++ server/util_pcre.c | 2 ++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/include/ap_mmn.h b/include/ap_mmn.h index 595fb178c82..0bb498c0702 100644 --- a/include/ap_mmn.h +++ b/include/ap_mmn.h @@ -613,6 +613,7 @@ * 20120211.141 (2.4.64-dev) add ap_stat_check() to httpd.h * 20120211.142 (2.4.64-dev) Add ap_*_timingsafe() to httpd.h * 20120211.143 (2.4.72-dev) Add ap_regexec_ex() + * 20120211.144 (2.4.72-dev) Add AP_REG_NOTEMPTY_ATSTART */ #define MODULE_MAGIC_COOKIE 0x41503234UL /* "AP24" */ @@ -620,7 +621,7 @@ #ifndef MODULE_MAGIC_NUMBER_MAJOR #define MODULE_MAGIC_NUMBER_MAJOR 20120211 #endif -#define MODULE_MAGIC_NUMBER_MINOR 143 /* 0...n */ +#define MODULE_MAGIC_NUMBER_MINOR 144 /* 0...n */ /** * Determine if the server's current MODULE_MAGIC_NUMBER is at least a diff --git a/include/ap_regex.h b/include/ap_regex.h index d45bb7a0d4d..559ef9f34e7 100644 --- a/include/ap_regex.h +++ b/include/ap_regex.h @@ -86,6 +86,8 @@ extern "C" { #define AP_REG_NO_DEFAULT 0x400 /**< Don't implicitely add AP_REG_DEFAULT options */ +#define AP_REG_NOTEMPTY_ATSTART 0x800 /**< Empty match not valid at first position */ + #define AP_REG_MATCH "MATCH_" /**< suggested prefix for ap_regname */ #define AP_REG_DEFAULT (AP_REG_DOTALL|AP_REG_DOLLAR_ENDONLY) diff --git a/server/util_pcre.c b/server/util_pcre.c index 8f36ce7f4f2..2336846130b 100644 --- a/server/util_pcre.c +++ b/server/util_pcre.c @@ -438,6 +438,8 @@ AP_DECLARE(int) ap_regexec_ex(const ap_regex_t *preg, options |= PCREn(NOTBOL); if ((eflags & AP_REG_NOTEOL) != 0) options |= PCREn(NOTEOL); + if ((eflags & AP_REG_NOTEMPTY_ATSTART) != 0) + options |= PCREn(NOTEMPTY_ATSTART); #ifdef HAVE_PCRE2 rc = pcre2_match((const pcre2_code *)preg->re_pcre, From abf114dabe492513be04bd12a2fa4ebb88898f76 Mon Sep 17 00:00:00 2001 From: Eric Covener Date: Thu, 26 Nov 2026 12:47:04 -0500 Subject: [PATCH 03/10] regex: Add AP_REG_NOTEMPTY and AP_REG_ANCHORED matching options. 2.4.x-only change, not a trunk merge. Trunk got these two options as a small part of r1810605 (ap_expr: open string expressions to the ), a large ap_expr change that is not being backported. The mod_headers edit* fix (r1915271) and the empty-match handling in mod_substitute and mod_proxy_html (4d328d9889) retry an empty match with AP_REG_NOTEMPTY_ATSTART|AP_REG_ANCHORED, so 2.4.x needs the option, with the same values as on trunk. * include/ap_mmn.h: Bump MMN minor. * include/ap_regex.h: Define AP_REG_NOTEMPTY and AP_REG_ANCHORED bits, as on trunk. * server/util_pcre.c (ap_regexec_ex): Map them to native PCRE_NOTEMPTY and PCRE_ANCHORED. Co-Authored-By: Claude Opus 5.5 --- include/ap_mmn.h | 3 ++- include/ap_regex.h | 3 +++ server/util_pcre.c | 4 ++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/include/ap_mmn.h b/include/ap_mmn.h index 0bb498c0702..c9a04634c93 100644 --- a/include/ap_mmn.h +++ b/include/ap_mmn.h @@ -614,6 +614,7 @@ * 20120211.142 (2.4.64-dev) Add ap_*_timingsafe() to httpd.h * 20120211.143 (2.4.72-dev) Add ap_regexec_ex() * 20120211.144 (2.4.72-dev) Add AP_REG_NOTEMPTY_ATSTART + * 20120211.145 (2.4.72-dev) Add AP_REG_NOTEMPTY and AP_REG_ANCHORED */ #define MODULE_MAGIC_COOKIE 0x41503234UL /* "AP24" */ @@ -621,7 +622,7 @@ #ifndef MODULE_MAGIC_NUMBER_MAJOR #define MODULE_MAGIC_NUMBER_MAJOR 20120211 #endif -#define MODULE_MAGIC_NUMBER_MINOR 144 /* 0...n */ +#define MODULE_MAGIC_NUMBER_MINOR 145 /* 0...n */ /** * Determine if the server's current MODULE_MAGIC_NUMBER is at least a diff --git a/include/ap_regex.h b/include/ap_regex.h index 559ef9f34e7..72095f777f8 100644 --- a/include/ap_regex.h +++ b/include/ap_regex.h @@ -82,6 +82,9 @@ extern "C" { #define AP_REG_NOMEM 0x20 /* nomem in our code */ #define AP_REG_DOTALL 0x40 /* perl's /s flag */ +#define AP_REG_NOTEMPTY 0x080 /**< Empty match not valid */ +#define AP_REG_ANCHORED 0x100 /**< Match at the first position */ + #define AP_REG_DOLLAR_ENDONLY 0x200 /* '$' matches at end of subject string only */ #define AP_REG_NO_DEFAULT 0x400 /**< Don't implicitely add AP_REG_DEFAULT options */ diff --git a/server/util_pcre.c b/server/util_pcre.c index 2336846130b..bc61e2b8ff6 100644 --- a/server/util_pcre.c +++ b/server/util_pcre.c @@ -438,8 +438,12 @@ AP_DECLARE(int) ap_regexec_ex(const ap_regex_t *preg, options |= PCREn(NOTBOL); if ((eflags & AP_REG_NOTEOL) != 0) options |= PCREn(NOTEOL); + if ((eflags & AP_REG_NOTEMPTY) != 0) + options |= PCREn(NOTEMPTY); if ((eflags & AP_REG_NOTEMPTY_ATSTART) != 0) options |= PCREn(NOTEMPTY_ATSTART); + if ((eflags & AP_REG_ANCHORED) != 0) + options |= PCREn(ANCHORED); #ifdef HAVE_PCRE2 rc = pcre2_match((const pcre2_code *)preg->re_pcre, From 04ef3f815fa0ffd8f60b2bf421d05c2f71548ee7 Mon Sep 17 00:00:00 2001 From: Eric Covener Date: Thu, 26 Nov 2026 12:47:33 -0500 Subject: [PATCH 04/10] Merge r1915271 from trunk (conflicts resolved in modules/metadata/mod_headers.c): mod_headers: Avoid infinite recursion with the edit* action and empty matches. Change the recursion used for edit* to a loop using the new ap_regexec_ex() function taking the current position (offset) in the subject string. After an empty match do the same thing as pcre2_substitute() (or Perl's /g), that is: don't allow for another empty match at the same positition by setting the AP_REG_NOTEMPTY_ATSTART option. If there is a non-empty match use it, otherwise skip/consume the first character and continue from there. * modules/metadata/mod_headers.c: Rename the hdr_edit_r enum for edit* to hdr_edit_all to better express what is does (and since the action is not recursive anymore). * modules/metadata/mod_headers.c(push_string, push_match): New helpers to consume the subject and substitutions in an array of iovec. * modules/metadata/mod_headers.c(process_regexp): Implement the new logic, using push_match() and push_string() to fill the iovec array finally passed to apr_strcatv() for the resulting string. git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1915271 13f79535-47bb-0310-9956-ffa450edef68 (cherry picked from commit 64ecf00d7c1974450bf8780ed1dd3200396745fa) --- changes-entries/mod_headers-edit_all.txt | 2 + modules/metadata/mod_headers.c | 148 ++++++++++++++++++----- 2 files changed, 119 insertions(+), 31 deletions(-) create mode 100644 changes-entries/mod_headers-edit_all.txt diff --git a/changes-entries/mod_headers-edit_all.txt b/changes-entries/mod_headers-edit_all.txt new file mode 100644 index 00000000000..41136ed56f0 --- /dev/null +++ b/changes-entries/mod_headers-edit_all.txt @@ -0,0 +1,2 @@ + *) mod_headers: Fix a possible infinite recursion with the edit* action and + empty matches. [Yann Ylavic] diff --git a/modules/metadata/mod_headers.c b/modules/metadata/mod_headers.c index f514b4bc6a0..88af1e25012 100644 --- a/modules/metadata/mod_headers.c +++ b/modules/metadata/mod_headers.c @@ -94,8 +94,8 @@ typedef enum { hdr_merge = 'g', /* merge (merge, but avoid duplicates) */ hdr_unset = 'u', /* unset header */ hdr_echo = 'e', /* echo headers from request to response */ - hdr_edit = 'r', /* change value by regexp, match once */ - hdr_edit_r = 'R', /* change value by regexp, everymatch */ + hdr_edit = 'r', /* substitute value by regexp, first match */ + hdr_edit_all = 'R', /* substitute value by regexp, all matches */ hdr_setifempty = 'i', /* set value if header not already present*/ hdr_note = 'n' /* set value of header in a note */ } hdr_actions; @@ -389,7 +389,7 @@ static char *parse_format_string(cmd_parms *cmd, header_entry *hdr, const char * return NULL; } /* Tags are in the replacement value for edit */ - else if (hdr->action == hdr_edit || hdr->action == hdr_edit_r ) { + else if (hdr->action == hdr_edit || hdr->action == hdr_edit_all ) { s = hdr->subs; } @@ -454,7 +454,7 @@ static APR_INLINE const char *header_inout_cmd(cmd_parms *cmd, else if (!strcasecmp(action, "edit")) new->action = hdr_edit; else if (!strcasecmp(action, "edit*")) - new->action = hdr_edit_r; + new->action = hdr_edit_all; else if (!strcasecmp(action, "note")) { if (cmd->info == &hdr_in) { return "RequestHeader does not support the 'note' action"; @@ -465,7 +465,7 @@ static APR_INLINE const char *header_inout_cmd(cmd_parms *cmd, return "first argument must be 'add', 'set', 'setifempty', 'append', 'merge', " "'unset', 'echo', 'note', 'edit', or 'edit*'."; - if (new->action == hdr_edit || new->action == hdr_edit_r) { + if (new->action == hdr_edit || new->action == hdr_edit_all) { if (subs == NULL) { return "Header edit requires a match and a substitution"; } @@ -626,39 +626,125 @@ static char* process_tags(header_entry *hdr, request_rec *r) } return str ? str : ""; } + +/* Helper for process_regexp(), push a string in an iovec array */ +static void push_string(apr_array_header_t *iovecs, + const char *str, apr_size_t len) +{ + if (len) { + struct iovec *vec = &APR_ARRAY_PUSH(iovecs, struct iovec); + vec->iov_base = (void *)str; + vec->iov_len = len; + } +} + +/* Helper for process_regexp(), push a match/substitution in an iovec array */ +static int push_match(apr_array_header_t *iovecs, + const char *str, apr_size_t len, apr_size_t *pos, + int flags, ap_regmatch_t pmatch[AP_MAX_REG_MATCH], + header_entry *hdr, request_rec *r) +{ + const char *sub; + int rc; + + rc = ap_regexec_ex(hdr->regex, str, len, *pos, + AP_MAX_REG_MATCH, pmatch, flags); + if (rc != 0) { + return (rc == AP_REG_NOMATCH) ? 0 : -1; + } + + /* Sanity checks (note that the rm_so/rm_eo offsets include *pos) */ + ap_assert(pmatch[0].rm_so >= 0 && pmatch[0].rm_so <= pmatch[0].rm_eo); + + /* Process tags in the input string rather than the resulting + * substitution to avoid surprises + */ + sub = ap_pregsub(r->pool, process_tags(hdr, r), str, + AP_MAX_REG_MATCH, pmatch); + if (sub == NULL) { + return -1; + } + + /* Keep what's before the match and substitute the latter */ + push_string(iovecs, str + *pos, (apr_size_t)pmatch[0].rm_so - *pos); + push_string(iovecs, sub, strlen(sub)); + + /* Consumed up to the end of match */ + *pos = pmatch[0].rm_eo; + return 1; +} + static const char *process_regexp(header_entry *hdr, const char *value, request_rec *r) { + apr_array_header_t *iovecs; ap_regmatch_t pmatch[AP_MAX_REG_MATCH]; - const char *subs; - const char *remainder; - char *ret; - int diffsz; - if (ap_regexec(hdr->regex, value, AP_MAX_REG_MATCH, pmatch, 0)) { - /* no match, nothing to do */ + apr_size_t length = strlen(value), offset = 0; + int rc; + + iovecs = apr_array_make(r->pool, 5, sizeof(struct iovec)); + + /* Find, substitute and consume the first match */ + rc = push_match(iovecs, value, length, &offset, 0, pmatch, hdr, r); + if (rc < 0) { + return NULL; + } + if (rc == 0) { + /* No match, no change */ return value; } - /* Process tags in the input string rather than the resulting - * substitution to avoid surprises - */ - subs = ap_pregsub(r->pool, process_tags(hdr, r), value, AP_MAX_REG_MATCH, pmatch); - if (subs == NULL) - return NULL; - diffsz = strlen(subs) - (pmatch[0].rm_eo - pmatch[0].rm_so); - if (hdr->action == hdr_edit) { - remainder = value + pmatch[0].rm_eo; + + /* Loop to edit multiple matches if applicable */ + if (hdr->action == hdr_edit_all) { + apr_size_t match_offset = pmatch[0].rm_so; + + while (offset < length) { + int flags = 0; + + /* Apply the same magic as pcre2_substitute() to avoid an + * infinite loop (and align with Perl's /g), that is: after + * an empty match ask for a match either non-empty or above + * offset; on success consume the match as usual, otherwise + * consume the next char; rinse and repeat from the new + * offset. + */ + if (match_offset == offset) { + flags = AP_REG_NOTEMPTY_ATSTART | AP_REG_ANCHORED; + } + rc = push_match(iovecs, value, length, &offset, flags, + pmatch, hdr, r); + if (rc < 0) { + return NULL; + } + if (rc == 0) { + if (flags == 0) { + /* No more match */ + break; + } + + /* Assume no CRLF in the value of a header. + * TODO: handle UTF-8 matching, i.e. add an AP_REG_UTF8 + * option to the ap_regex API along with an ap_regoptions() + * or so helper to get the options used at ->regex compile + * time (including from "(*UTF*)" patterns); here if + * AP_REG_UTF8 is set then consume a whole UTF-8 char, + * potentially multibyte. + */ + push_string(iovecs, value + offset, 1); + ++offset; + continue; + } + + match_offset = pmatch[0].rm_so; + } } - else { /* recurse to edit multiple matches if applicable */ - remainder = process_regexp(hdr, value + pmatch[0].rm_eo, r); - if (remainder == NULL) - return NULL; - diffsz += strlen(remainder) - strlen(value + pmatch[0].rm_eo); + + /* Keep the remainder if any */ + if (offset < length) { + push_string(iovecs, value + offset, length - offset); } - ret = apr_palloc(r->pool, strlen(value) + 1 + diffsz); - memcpy(ret, value, pmatch[0].rm_so); - strcpy(ret + pmatch[0].rm_so, subs); - strcat(ret, remainder); - return ret; + + return apr_pstrcatv(r->pool, (void *)iovecs->elts, iovecs->nelts, NULL); } static int echo_header(void *v, const char *key, const char *val) @@ -814,7 +900,7 @@ static int do_headers_fixup(request_rec *r, apr_table_t *headers, apr_table_do(echo_header, &v, r->headers_in, NULL); break; case hdr_edit: - case hdr_edit_r: + case hdr_edit_all: if (!ap_cstr_casecmp(hdr->header, "Content-Type") && r->content_type) { const char *repl = process_regexp(hdr, r->content_type, r); if (repl == NULL) From eec9fb44e93c45af595a33cb6931e63baf851b9a Mon Sep 17 00:00:00 2001 From: Eric Covener Date: Thu, 26 Nov 2026 12:41:08 -0500 Subject: [PATCH 05/10] Merge 4d328d9889 from trunk (conflicts resolved in modules/filters/mod_substitute.c): Backreferences without a capturing match, and empty regex matches (#1096) * Backreferences without a capturing match, and empty regex matches: An expression only fills the caller's match vector and source when a capturing regex is evaluated and matches, so an expression that is true via a '||' short-circuit, a regex without groups, or '!~' left $N / %N to be expanded from whatever the vector held before: a previous condition or entry, or nothing at all. mod_substitute and mod_proxy_html did not advance past an empty match, so a pattern that can match the empty string (x*, ^, \b, a lookahead) never progressed. * server/util_expr_eval.c (ap_expr_eval_re_backref): Expand only groups with rm_so >= 0 and a non-empty span. (ap_expr_eval_comp): Reset the match vector when a capturing regex does not match. * modules/mappers/mod_rewrite.c (apply_rewrite_cond): Start with no source, and update the condition backreferences only when the expression produced captures, so %N keeps referring to the last matching RewriteCond as with the other condition types. (do_expand): Require rm_so >= 0. * modules/proxy/mod_proxy_fcgi.c (fix_cgivars): Reset the source and match vector before each ProxyFCGISetEnvIf entry. * server/util.c (regsub_core): Require rm_so >= 0. * server/util_regex.c (ap_rxplus_exec): Don't recurse on an empty match at the start of the string. (ap_rxplus_match): Refuse groups that did not participate. * modules/filters/mod_substitute.c (do_pattmatch), modules/filters/mod_proxy_html.c (dump_content, pstartElement): Match from an absolute offset in the line with ap_regexec_ex(), so ^, \b and lookbehinds keep their meaning after a previous match, and after an empty match retry with AP_REG_NOTEMPTY_ATSTART|AP_REG_ANCHORED or copy one byte, as pcre2_substitute() and Perl's /g do. * test/modules/filters/test_010_substitute_empty_match.py, test/modules/metadata/test_006_expr_backref.py, test/modules/proxy/test_13_fcgi_setenvif.py, test/modules/proxy/fcgi_faker.py, test/unit/regex.c: New tests. * test/modules/proxy/env.py: Load mod_proxy_fcgi. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PUN2EPhoNvc4rfibgy6H72 * * test/modules/filters/test_010_substitute_empty_match.py: Write the documents with newline="" so the multi-line cases stay LF-only on Windows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PUN2EPhoNvc4rfibgy6H72 * * changes-entries/regex_backrefs.txt: Add. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PUN2EPhoNvc4rfibgy6H72 --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit 4d328d988972bf34ace84eb2c18c70331e70b4c1) --- changes-entries/regex_backrefs.txt | 6 + modules/filters/mod_proxy_html.c | 67 ++++++- modules/filters/mod_substitute.c | 54 ++++- modules/mappers/mod_rewrite.c | 14 +- modules/proxy/mod_proxy_fcgi.c | 11 ++ server/util.c | 9 +- server/util_expr_eval.c | 17 +- server/util_regex.c | 10 +- .../test_010_substitute_empty_match.py | 70 +++++++ .../modules/metadata/test_006_expr_backref.py | 133 +++++++++++++ test/modules/proxy/env.py | 4 +- test/modules/proxy/fcgi_faker.py | 98 +++++++++ test/modules/proxy/test_13_fcgi_setenvif.py | 77 ++++++++ test/unit/regex.c | 187 ++++++++++++++++++ 14 files changed, 736 insertions(+), 21 deletions(-) create mode 100644 changes-entries/regex_backrefs.txt create mode 100644 test/modules/filters/test_010_substitute_empty_match.py create mode 100644 test/modules/metadata/test_006_expr_backref.py create mode 100644 test/modules/proxy/fcgi_faker.py create mode 100644 test/modules/proxy/test_13_fcgi_setenvif.py create mode 100644 test/unit/regex.c diff --git a/changes-entries/regex_backrefs.txt b/changes-entries/regex_backrefs.txt new file mode 100644 index 00000000000..80099ac5b32 --- /dev/null +++ b/changes-entries/regex_backrefs.txt @@ -0,0 +1,6 @@ + *) core, mod_rewrite, mod_proxy_fcgi, mod_substitute, mod_proxy_html: + Fix backreferences ($N, %N) to groups that did not participate in + a match, or left over from a previous condition when an expression + is true without a capturing match, and fix regex patterns that can + match the empty string not making progress in mod_substitute and + mod_proxy_html. [Eric Covener] diff --git a/modules/filters/mod_proxy_html.c b/modules/filters/mod_proxy_html.c index efaa2bb7db2..9b30d1e7fa9 100644 --- a/modules/filters/mod_proxy_html.c +++ b/modules/filters/mod_proxy_html.c @@ -200,7 +200,7 @@ static void dump_content(saxctxt *ctx) char *found; size_t s_from, s_to; size_t match; - int nmatch; + int nmatch, eflags, i; ap_regmatch_t pmatch[10]; size_t len, offs; urlmap *themap = ctx->map; @@ -224,7 +224,32 @@ static void dump_content(saxctxt *ctx) temp.strlen = 0; nmatch = 10; offs = 0; - while (!ap_regexec(m->from.r, ctx->vb.buf+offs, nmatch, pmatch, 0)) { + eflags = 0; + len = strlen(ctx->vb.buf); + do { + /* Match from the current offset in the whole buffer (so that + * ^, \b, lookbehinds... keep their meaning), the offsets are + * then made relative to offs below. + */ + if (ap_regexec_ex(m->from.r, ctx->vb.buf, len, offs, + nmatch, pmatch, eflags)) { + if (!eflags) { + break; + } + /* No non-empty match right after an empty one, consume + * the next char and retry a "normal" match from there. + */ + ap_varbuf_strmemcat(&temp, ctx->vb.buf+offs, 1); + ++offs; + eflags = 0; + continue; + } + for (i = 0; i < nmatch; ++i) { + if (pmatch[i].rm_so >= 0) { + pmatch[i].rm_so -= offs; + pmatch[i].rm_eo -= offs; + } + } match = pmatch[0].rm_so; s_from = pmatch[0].rm_eo - match; VERBOSEB( @@ -240,7 +265,14 @@ static void dump_content(saxctxt *ctx) ap_varbuf_regsub(&temp, m->to, ctx->vb.buf+offs, nmatch, pmatch, 0); /* Continue past the match */ offs += pmatch[0].rm_eo; - } + /* After an empty match, the same (empty) match at the same + * position would loop forever: like pcre2_substitute() or + * Perl's /g, ask for a non-empty match at this position + * first, otherwise skip a char (above). + */ + eflags = (s_from == 0) ? AP_REG_NOTEMPTY_ATSTART | AP_REG_ANCHORED + : 0; + } while (ctx->vb.buf[offs]); /* Copy any remaining text */ ap_varbuf_strcat(&temp, ctx->vb.buf+offs); /* Replace the original buffer with the result */ @@ -354,6 +386,7 @@ static void pstartElement(void *ctxt, const xmlChar *uname, char *found; saxctxt *ctx = (saxctxt*) ctxt; size_t nmatch; + int eflags; ap_regmatch_t pmatch[10]; #ifndef GO_FASTER int verbose = APLOGrtrace1(ctx->f->r); @@ -522,8 +555,27 @@ static void pstartElement(void *ctxt, const xmlChar *uname, temp.strlen = 0; nmatch = 10; offs = 0; - while (!ap_regexec(m->from.r, ctx->vb.buf+offs, - nmatch, pmatch, 0)) { + eflags = 0; + len = strlen(ctx->vb.buf); + do { + /* See dump_content() */ + if (ap_regexec_ex(m->from.r, ctx->vb.buf, len, + offs, nmatch, pmatch, + eflags)) { + if (!eflags) { + break; + } + ap_varbuf_strmemcat(&temp, ctx->vb.buf+offs, 1); + ++offs; + eflags = 0; + continue; + } + for (i = 0; i < (int)nmatch; ++i) { + if (pmatch[i].rm_so >= 0) { + pmatch[i].rm_so -= offs; + pmatch[i].rm_eo -= offs; + } + } match = pmatch[0].rm_so; s_from = pmatch[0].rm_eo - match; VERBOSE({ @@ -542,7 +594,10 @@ static void pstartElement(void *ctxt, const xmlChar *uname, /* Continue past the match */ offs += pmatch[0].rm_eo; ++num_match; - } + eflags = (s_from == 0) + ? AP_REG_NOTEMPTY_ATSTART | AP_REG_ANCHORED + : 0; + } while (ctx->vb.buf[offs]); /* Copy any remaining text */ ap_varbuf_strcat(&temp, ctx->vb.buf+offs); /* Replace buffer */ diff --git a/modules/filters/mod_substitute.c b/modules/filters/mod_substitute.c index 954acd64d99..9d062c4bf94 100644 --- a/modules/filters/mod_substitute.c +++ b/modules/filters/mod_substitute.c @@ -283,9 +283,47 @@ static apr_status_t do_pattmatch(ap_filter_t *f, apr_bucket *inb, const char *pos = buff; char *repl; apr_size_t space_left = cfg->max_line_length; - while (!ap_regexec_len(script->regexp, pos, left, - AP_MAX_REG_MATCH, regm, 0)) { + int eflags = 0; + for (;;) { apr_status_t rv; + int n; + /* Match from the current position in the whole line + * (so that ^, \b, lookbehinds... keep their meaning), + * the offsets are then made relative to pos below. + */ + if (ap_regexec_ex(script->regexp, buff, bytes, + pos - buff, AP_MAX_REG_MATCH, regm, + eflags)) { + if (!eflags || !left) { + break; + } + /* No non-empty match right after an empty one, + * consume the next char and retry a "normal" + * match from there (see below). + */ + if (script->flatten && !force_quick) { + if (vb.strlen >= cfg->max_line_length) + return APR_ENOMEM; + ap_varbuf_strmemcat(&vb, pos, 1); + } + else { + if (space_left <= 1) + return APR_ENOMEM; + space_left--; + apr_bucket_split(b, 1); + b = APR_BUCKET_NEXT(b); + } + pos++; + left--; + eflags = 0; + continue; + } + for (n = 0; n < AP_MAX_REG_MATCH; ++n) { + if (regm[n].rm_so >= 0) { + regm[n].rm_so -= pos - buff; + regm[n].rm_eo -= pos - buff; + } + } ap_log_rerror(APLOG_MARK, APLOG_TRACE8, 0, f->r, "Matching found"); have_match = 1; @@ -336,6 +374,18 @@ static apr_status_t do_pattmatch(ap_filter_t *f, apr_bucket *inb, */ pos += regm[0].rm_eo; left -= regm[0].rm_eo; + if (!left) { + break; + } + /* After an empty match, the same (empty) match at + * the same position would loop forever: like + * pcre2_substitute() or Perl's /g, ask for a + * non-empty match at this position first, otherwise + * skip a char (above). + */ + eflags = (regm[0].rm_eo == regm[0].rm_so) + ? AP_REG_NOTEMPTY_ATSTART | AP_REG_ANCHORED + : 0; } if (have_match && script->flatten && !force_quick) { char *copy; diff --git a/modules/mappers/mod_rewrite.c b/modules/mappers/mod_rewrite.c index 62bcd38bee7..0fde49a214b 100644 --- a/modules/mappers/mod_rewrite.c +++ b/modules/mappers/mod_rewrite.c @@ -2593,6 +2593,7 @@ static char *do_expand(char *input, rewrite_ctx *ctx, rewriterule_entry *entry, /* see ap_pregsub() in server/util.c */ if (bri->source && n < AP_MAX_REG_MATCH + && bri->regmatch[n].rm_so >= 0 && bri->regmatch[n].rm_eo > bri->regmatch[n].rm_so) { span = bri->regmatch[n].rm_eo - bri->regmatch[n].rm_so; if (entry && (entry->flags & RULEFLAG_ESCAPEBACKREF)) { @@ -4275,7 +4276,11 @@ static cond_return_type apply_rewrite_cond(rewritecond_entry *p, rewrite_ctx *ct case CONDPAT_AP_EXPR: { - const char *err, *source; + /* source (and regmatch) are only set by the expression if a + * capturing regex is actually evaluated, e.g. not when the + * expression short-circuits before reaching it. + */ + const char *err, *source = NULL; rc = ap_expr_exec_re(r, p->expr, AP_MAX_REG_MATCH, regmatch, &source, &err); if (rc < 0 || err) { @@ -4288,8 +4293,11 @@ static cond_return_type apply_rewrite_cond(rewritecond_entry *p, rewrite_ctx *ct rc = (rc > 0) ? COND_RC_MATCH : COND_RC_NOMATCH; } - /* update briRC backref info */ - if (rc && !(p->flags & CONDFLAG_NOTMATCH)) { + /* update briRC backref info, if the expression produced some + * (i.e. a capturing regex matched), otherwise keep the ones from + * the last matching RewriteCond + */ + if (rc && !(p->flags & CONDFLAG_NOTMATCH) && source) { ctx->briRC.source = source; memcpy(ctx->briRC.regmatch, regmatch, sizeof(regmatch)); } diff --git a/modules/proxy/mod_proxy_fcgi.c b/modules/proxy/mod_proxy_fcgi.c index 82e0c1e4218..94ce89677ae 100644 --- a/modules/proxy/mod_proxy_fcgi.c +++ b/modules/proxy/mod_proxy_fcgi.c @@ -203,6 +203,17 @@ static apr_status_t fix_cgivars(request_rec *r, fcgi_dirconf_t *dconf) entries = (sei_entry *) dconf->env_fixups->elts; for (i = 0; i < dconf->env_fixups->nelts; i++) { sei_entry *entry = &entries[i]; + int n; + + /* The expression only sets src/regm when a capturing regex is + * actually evaluated and matches; reset them first so that $N in + * the condition or the replacement does not pick up the + * backreferences of a previous entry. + */ + src = NULL; + for (n = 0; n < AP_MAX_REG_MATCH; ++n) { + regm[n].rm_so = regm[n].rm_eo = -1; + } rc = ap_expr_exec_re(r, entry->cond, AP_MAX_REG_MATCH, regm, &src, &err); if (rc < 0) { diff --git a/server/util.c b/server/util.c index 0cdf543499d..5eff6ba4209 100644 --- a/server/util.c +++ b/server/util.c @@ -402,8 +402,10 @@ static apr_status_t regsub_core(apr_pool_t *p, char **result, src++; len++; } - else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) { - if (APR_SIZE_MAX - len <= pmatch[no].rm_eo - pmatch[no].rm_so) + else if (no < nmatch && pmatch[no].rm_so >= 0 + && pmatch[no].rm_so < pmatch[no].rm_eo) { + if (APR_SIZE_MAX - len <= (apr_size_t)(pmatch[no].rm_eo + - pmatch[no].rm_so)) return APR_ENOMEM; len += pmatch[no].rm_eo - pmatch[no].rm_so; } @@ -439,7 +441,8 @@ static apr_status_t regsub_core(apr_pool_t *p, char **result, c = *src++; *dst++ = c; } - else if (no < nmatch && pmatch[no].rm_so < pmatch[no].rm_eo) { + else if (no < nmatch && pmatch[no].rm_so >= 0 + && pmatch[no].rm_so < pmatch[no].rm_eo) { len = pmatch[no].rm_eo - pmatch[no].rm_so; memcpy(dst, source + pmatch[no].rm_so, len); dst += len; diff --git a/server/util_expr_eval.c b/server/util_expr_eval.c index be9684df290..df93c587186 100644 --- a/server/util_expr_eval.c +++ b/server/util_expr_eval.c @@ -198,9 +198,13 @@ static const char *ap_expr_eval_re_backref(ap_expr_eval_ctx_t *ctx, unsigned int || **ctx->re_source == '\0' || ctx->re_nmatch < n + 1) return ""; - len = ctx->re_pmatch[n].rm_eo - ctx->re_pmatch[n].rm_so; - if (len == 0) + /* A group which did not participate in the match has rm_so == rm_eo + * == -1; expand only a group with a non-empty span in the source. + */ + if (ctx->re_pmatch[n].rm_so < 0 + || ctx->re_pmatch[n].rm_eo <= ctx->re_pmatch[n].rm_so) return ""; + len = ctx->re_pmatch[n].rm_eo - ctx->re_pmatch[n].rm_so; return apr_pstrndup(ctx->p, *ctx->re_source + ctx->re_pmatch[n].rm_so, len); } @@ -303,6 +307,15 @@ static int ap_expr_eval_comp(ap_expr_eval_ctx_t *ctx, const ap_expr_t *node) result = (0 == ap_regexec(regex, word, ctx->re_nmatch, ctx->re_pmatch, 0)); *ctx->re_source = result ? word : NULL; + if (!result) { + /* ap_regexec() leaves the vector untouched on no + * match, don't let stale offsets linger + */ + apr_size_t i; + for (i = 0; i < ctx->re_nmatch; ++i) { + ctx->re_pmatch[i].rm_so = ctx->re_pmatch[i].rm_eo = -1; + } + } } else { result = (0 == ap_regexec(regex, word, 0, NULL, 0)); diff --git a/server/util_regex.c b/server/util_regex.c index 5405f8d4d0b..b8de1d86f06 100644 --- a/server/util_regex.c +++ b/server/util_regex.c @@ -162,8 +162,11 @@ AP_DECLARE(int) ap_rxplus_exec(apr_pool_t *pool, ap_rxplus_t *rx, newl = strlen(*newpattern); diffsz = newl - oldl; remainder = pattern + startl + oldl; - if (rx->flags & AP_REG_MULTI) { - /* recurse to do any further matches */ + if ((rx->flags & AP_REG_MULTI) && startl + oldl > 0) { + /* recurse to do any further matches (unless the match was + * empty at the start of the pattern, which would recurse + * on the very same pattern indefinitely) + */ ret += ap_rxplus_exec(pool, rx, remainder, &subs); if (ret > 1) { /* a further substitution happened */ @@ -193,7 +196,8 @@ AP_DECLARE(int) ap_rxplus_nmatch(ap_rxplus_t *rx) AP_DECLARE(void) ap_rxplus_match(ap_rxplus_t *rx, int n, int *len, const char **match) { - if (n >= 0 && n < ap_rxplus_nmatch(rx)) { + if (n >= 0 && n < ap_rxplus_nmatch(rx) && rx->pmatch[n].rm_so >= 0 + && rx->pmatch[n].rm_eo >= rx->pmatch[n].rm_so) { *match = rx->match + rx->pmatch[n].rm_so; *len = rx->pmatch[n].rm_eo - rx->pmatch[n].rm_so; } diff --git a/test/modules/filters/test_010_substitute_empty_match.py b/test/modules/filters/test_010_substitute_empty_match.py new file mode 100644 index 00000000000..5a4a0bd48c3 --- /dev/null +++ b/test/modules/filters/test_010_substitute_empty_match.py @@ -0,0 +1,70 @@ +import os + +import pytest + +from pyhttpd.conf import HttpdConf + +# Patterns that can match the empty string must not loop forever (or until +# SubstituteMaxLineLength is hit) in do_pattmatch(). Expected results follow +# the same convention as mod_headers' edit* and pcre2_substitute(): after an +# empty match, a non-empty match is tried at the same position, otherwise one +# character is copied and matching continues after it. Matching resumes +# within the whole line, so ^, $, \b and lookarounds keep their meaning. +CASES = { + # name: (pattern, replacement, flags, input, expected) + 'star_dash_flatten': ('x*', '-', 'f', 'abc', '-a-b-c-'), + 'star_dash_quick': ('x*', '-', 'q', 'abc', '-a-b-c-'), + 'star_empty_flatten': ('b*', '', 'f', 'abc', 'ac'), + 'star_empty_quick': ('b*', '', 'q', 'abc', 'ac'), + 'optional_group_flatten': ('(b)?', '[$1]', 'f', 'abc', '[]a[b][]c[]'), + 'optional_group_quick': ('(b)?', '[$1]', 'q', 'abc', '[]a[b][]c[]'), + 'anchor_start_flatten': ('^', '>', 'f', 'abc', '>abc'), + 'anchor_start_quick': ('^', '>', 'q', 'abc', '>abc'), + 'anchor_start_lines': ('^', '>', 'f', 'ab\ncd', '>ab\n>cd'), + 'anchor_end_flatten': ('$', '<', 'f', 'abc', 'abc<'), + # (httpd compiles regexes with DOLLAR_ENDONLY: $ only matches at the + # very end of the line, i.e. after the newline) + 'anchor_end_lines': ('$', '<', 'q', 'ab\ncd', 'ab\n + AddOutputFilterByType SUBSTITUTE text/html + Substitute "s/{pattern}/{repl}/{flags}" + + """, + }) + conf.add_vhost_test1() + conf.install() + assert env.apache_restart() == 0 + + @pytest.mark.parametrize("name", list(CASES), ids=list(CASES)) + def test_filters_010_01(self, env, name): + pattern, repl, flags, _, expected = CASES[name] + self.configure(env, pattern, repl, flags) + r = env.curl_get(env.mkurl("http", "test1", f"/{name}.html"), + options=['--max-time', '10']) + assert r.response, f"{name}: no response (hang?): {r.stderr}" + assert r.response["status"] == 200, f"{name}: status {r.response['status']}" + body = r.response["body"].decode() + assert body == expected, f"{name}: body {body!r}, expected {expected!r}" diff --git a/test/modules/metadata/test_006_expr_backref.py b/test/modules/metadata/test_006_expr_backref.py new file mode 100644 index 00000000000..4bfee9b223a --- /dev/null +++ b/test/modules/metadata/test_006_expr_backref.py @@ -0,0 +1,133 @@ +import pytest + +from pyhttpd.conf import HttpdConf + +# An expression that evaluates to true without evaluating a capturing regex +# (short-circuited by '||', regex without captures, '!~' non-match) must not +# expand $N / %N backreferences from the offsets of a previous match: they +# are empty in mod_setenvif (SetEnvIfExpr), and those of the last matching +# RewriteCond in mod_rewrite (RewriteCond expr). +EXPR = "req('X-Match') == 'skip' || req('X-Match') =~ m#^(.+)$#" +NOCAP = "req('X-Match') =~ m#^.+$#" +NEG = "req('X-Match') !~ m#^(zzz)$#" +# a value much longer than X-Short, so that %1 taken with X-Long's offsets +# but X-Short's string would not equal X-Long +LONG = "long-" + "x" * 200 + + +class TestExprBackref: + + @pytest.fixture(autouse=True, scope='class') + @classmethod + def _class_scope(cls, env): + conf = HttpdConf(env, extras={ + f"test1.{env.http_tld}": f""" + RewriteEngine On + RewriteCond expr "{EXPR}" + RewriteRule ^/rewrite$ /redir/-%1- [R=302,L] + + # a previous capturing RewriteCond, then an expr one that is + # true without captures: %1 must still be the previous capture + RewriteCond %{{HTTP:X-Prev}} ^(.+)$ + RewriteCond expr "{EXPR}" + RewriteRule ^/rewrite-prev$ /redir/-%1- [R=302,L] + + RewriteCond expr "{NOCAP}" + RewriteRule ^/rewrite-nocap$ /redir/-%1- [R=302,L] + + RewriteCond expr "{NEG}" + RewriteRule ^/rewrite-neg$ /redir/-%1- [R=302,L] + + # an expr with captures, then a regex RewriteCond on a different + # (longer) string, then an expr true without captures: %1 must be + # the regex condition's capture of its own string + RewriteCond expr "req('X-Short') =~ m#^(.+)$#" + RewriteCond %{{HTTP:X-Long}} ^(.+)$ + RewriteCond expr "%{{REQUEST_METHOD}} == 'GET'" + RewriteRule ^/rewrite-mixed$ /redir/-%1- [R=302,L] + + RewriteCond expr "req('X-Short') =~ m#^(.+)$#" + RewriteCond %{{HTTP:X-Long}} ^(.+)$ + RewriteCond expr "{EXPR}" + RewriteRule ^/rewrite-mixed-short-circuit$ /redir/-%1- [R=302,L] + + # a regex SetEnvIf first, leaving captures in the match vector + SetEnvIf X-Prev "^(.+)$" PREV=[$1] + SetEnvIfExpr "{EXPR}" "CAPTURE=[$1]" + SetEnvIfExpr "{NOCAP}" "NOCAP=[$1]" + SetEnvIfExpr "{NEG}" "NEG=[$1]" + # $1 used inside the condition itself + SetEnvIfExpr "({EXPR}) && $1 == 'foo'" "INCOND=[$1]" + Header always set X-Prev-Env "%{{PREV}}e" + Header always set X-Capture "%{{CAPTURE}}e" + Header always set X-Nocap "%{{NOCAP}}e" + Header always set X-Neg "%{{NEG}}e" + Header always set X-Incond "%{{INCOND}}e" + + # Header edit* with patterns matching the empty string + Header always set X-Edit "abc" + Header always edit* X-Edit "x*" "-" + Header always set X-Edit-Anchor "abc" + Header always edit* X-Edit-Anchor "^" ">" + Header always set X-Edit-Opt "abc" + Header always edit* X-Edit-Opt "(b)?" "[$1]" + """, + }) + conf.add_vhost_test1() + conf.install() + assert env.apache_restart() == 0 + + def get(self, env, path, headers): + options = [] + for k, v in headers.items(): + options += ['-H', f'{k}: {v}'] + r = env.curl_get(env.mkurl("http", "test1", path), options=options) + assert r.response, f"no response: {r.stderr}" + return r + + @pytest.mark.parametrize("path, value, expected", [ + ("/rewrite", "skip", "--"), + ("/rewrite", "foo", "-foo-"), + ("/rewrite-prev", "skip", "-previous-"), + ("/rewrite-prev", "foo", "-foo-"), + ("/rewrite-nocap", "foo", "--"), + ("/rewrite-neg", "foo", "--"), + ], ids=["short-circuit", "match", "prev-short-circuit", "prev-match", + "no-captures", "negated"]) + def test_metadata_006_01_rewrite(self, env, path, value, expected): + r = self.get(env, path, {"X-Match": value, "X-Prev": "previous"}) + assert r.response["status"] == 302 + location = r.response["header"]["location"] + assert location.endswith(f"/redir/{expected}"), location + + @pytest.mark.parametrize("path", [ + "/rewrite-mixed", "/rewrite-mixed-short-circuit", + ]) + def test_metadata_006_04_rewrite_mixed(self, env, path): + r = self.get(env, path, {"X-Short": "ab", "X-Long": LONG, + "X-Match": "skip"}) + assert r.response["status"] == 302 + location = r.response["header"]["location"] + assert location.endswith(f"/redir/-{LONG}-"), location + + @pytest.mark.parametrize("value, expected", [ + # (for '!~', mod_setenvif deliberately sets the literal value when + # the regex did not match, see the comment in match_headers()) + ("skip", {"x-capture": "[]", "x-nocap": "[]", "x-neg": "[$1]", + "x-prev-env": "[previous]", "x-incond": "(null)"}), + ("foo", {"x-capture": "[foo]", "x-nocap": "[]", "x-neg": "[$1]", + "x-prev-env": "[previous]", "x-incond": "[foo]"}), + ], ids=["short-circuit", "match"]) + def test_metadata_006_02_setenvif(self, env, value, expected): + r = self.get(env, "/", {"X-Match": value, "X-Prev": "previous"}) + for name, val in expected.items(): + assert r.response["header"][name] == val, name + + def test_metadata_006_03_header_edit_empty(self, env): + r = self.get(env, "/", {}) + h = r.response["header"] + # (unlike Perl's /g and mod_substitute, mod_headers does not try a + # final empty match once the whole value has been consumed) + assert h["x-edit"] == "-a-b-c" + assert h["x-edit-anchor"] == ">abc" + assert h["x-edit-opt"] == "[]a[b][]c" diff --git a/test/modules/proxy/env.py b/test/modules/proxy/env.py index ef7bd722088..aa26f23ae09 100644 --- a/test/modules/proxy/env.py +++ b/test/modules/proxy/env.py @@ -82,8 +82,8 @@ def __init__(self, env: 'HttpdTestEnv'): super().__init__(env=env) self.add_source_dir(os.path.dirname(inspect.getfile(ProxyTestSetup))) self.add_modules(["proxy", "proxy_http", "proxy_ajp", "proxy_balancer", - "proxy_connect", "proxy_uwsgi", "lbmethod_byrequests", - "remoteip"]) + "proxy_connect", "proxy_uwsgi", "proxy_fcgi", + "lbmethod_byrequests", "remoteip"]) self.add_optional_modules(["proxy_hcheck", "proxy_scgi"]) diff --git a/test/modules/proxy/fcgi_faker.py b/test/modules/proxy/fcgi_faker.py new file mode 100644 index 00000000000..6f1d4637789 --- /dev/null +++ b/test/modules/proxy/fcgi_faker.py @@ -0,0 +1,98 @@ +""" +Minimal fake FastCGI responder for testing mod_proxy_fcgi. + +Speaks just enough of the FastCGI record protocol to accept one request +(FCGI_BEGIN_REQUEST, FCGI_PARAMS..., empty FCGI_PARAMS, FCGI_STDIN..., empty +FCGI_STDIN) and answer with a JSON document of the CGI parameters it was +given, so tests can inspect what ProxyFCGISetEnvIf produced. +""" +import json +import socket +import struct + +from .env import TCPFaker + +FCGI_BEGIN_REQUEST = 1 +FCGI_END_REQUEST = 3 +FCGI_PARAMS = 4 +FCGI_STDIN = 5 +FCGI_STDOUT = 6 + + +def _record(rtype, req_id, content): + pad = (8 - len(content) % 8) % 8 + return struct.pack("!BBHHBx", 1, rtype, req_id, len(content), pad) \ + + content + b"\0" * pad + + +def _parse_params(data): + params = {} + pos = 0 + while pos < len(data): + lens = [] + for _ in range(2): + if data[pos] >> 7: + lens.append(struct.unpack_from("!I", data, pos)[0] & 0x7fffffff) + pos += 4 + else: + lens.append(data[pos]) + pos += 1 + name = data[pos:pos + lens[0]].decode("latin-1") + pos += lens[0] + val = data[pos:pos + lens[1]].decode("latin-1") + pos += lens[1] + params[name] = val + return params + + +class FCGIFaker(TCPFaker): + + def __init__(self, host, port): + super().__init__(host, port) + self.params = None + + def _handle(self, c): + buf = b"" + params_raw = b"" + req_id = 1 + stdin_done = False + while not stdin_done: + data = c.recv(65536) + if not data: + break + buf += data + while len(buf) >= 8: + _, rtype, rid, clen, plen = struct.unpack_from("!BBHHBx", buf, 0) + if len(buf) < 8 + clen + plen: + break + content = buf[8:8 + clen] + buf = buf[8 + clen + plen:] + req_id = rid + if rtype == FCGI_PARAMS: + params_raw += content + elif rtype == FCGI_STDIN and clen == 0: + stdin_done = True + break + self.params = _parse_params(params_raw) + body = json.dumps(self.params).encode() + out = b"Content-Type: application/json\r\n\r\n" + body + c.sendall(_record(FCGI_STDOUT, req_id, out) + + _record(FCGI_STDOUT, req_id, b"") + + _record(FCGI_END_REQUEST, req_id, struct.pack("!IBxxx", 0, 0))) + + def _process(self): + while not self._done: + try: + c, _ = self._socket.accept() + try: + self._handle(c) + try: + c.shutdown(socket.SHUT_WR) + except OSError: + pass + finally: + c.close() + except socket.timeout: + pass + except ConnectionAbortedError: + self._done = True diff --git a/test/modules/proxy/test_13_fcgi_setenvif.py b/test/modules/proxy/test_13_fcgi_setenvif.py new file mode 100644 index 00000000000..53e46fde9d1 --- /dev/null +++ b/test/modules/proxy/test_13_fcgi_setenvif.py @@ -0,0 +1,77 @@ +import pytest + +from pyhttpd.conf import HttpdConf +from .fcgi_faker import FCGIFaker + +# ProxyFCGISetEnvIf conditions that evaluate to true without a capturing +# regex match (short-circuited by '||', a regex without captures, a '!~' +# non-match) must expand $N in the replacement to nothing, not to the +# captures of a previous ProxyFCGISetEnvIf entry. +SHORT_CIRCUIT = "req('X-Match') == 'skip' || req('X-Match') =~ m#^(.+)$#" + + +class TestProxyFCGISetEnvIf: + + @pytest.fixture(autouse=True, scope='class') + @classmethod + def _class_scope(cls, env): + env.require(env.has_shared_module("proxy_fcgi"), "mod_proxy_fcgi not available", + dep="mod_proxy_fcgi", + detected=f"no mod_proxy_fcgi.so in {env.libexec_dir}") + faker = FCGIFaker("127.0.0.1", env.http_port2) + faker.start() + conf = HttpdConf(env) + conf.start_vhost(domains=[f"test1.{env.http_tld}"], port=env.http_port) + conf.add([ + f"ProxyPass / fcgi://127.0.0.1:{env.http_port2}/", + # a preceding entry with captures, which the next ones must not see + "ProxyFCGISetEnvIf \"req('X-Prev') =~ m#^(.+)$#\" PREV_CAPTURE \"<$1>\"", + f"ProxyFCGISetEnvIf \"{SHORT_CIRCUIT}\" X_CAPTURE \"<$1>\"", + "ProxyFCGISetEnvIf \"req('X-Nocap') =~ m#^.+$#\" NOCAP_CAPTURE \"<$1>\"", + "ProxyFCGISetEnvIf \"req('X-Neg') !~ m#^(zzz)$#\" NEG_CAPTURE \"<$1>\"", + "ProxyFCGISetEnvIf \"req('X-Two') =~ m#^(.)(.)#\" TWO_CAPTURE \"<$2$1>\"", + ]) + conf.end_vhost() + conf.install() + assert env.apache_restart() == 0 + yield faker + faker.stop() + + def get_params(self, env, headers): + options = [] + for k, v in headers.items(): + options += ['-H', f'{k}: {v}'] + r = env.curl_get(env.mkurl("http", "test1", "/"), options=options) + assert r.response, f"no response: {r.stderr}" + assert r.response["status"] == 200, r.response + return r.response["json"] + + def test_proxy_13_01_short_circuit(self, env): + params = self.get_params(env, {"X-Match": "skip", "X-Prev": "previous"}) + assert params["PREV_CAPTURE"] == "" + assert params["X_CAPTURE"] == "<>" + + def test_proxy_13_02_match(self, env): + params = self.get_params(env, {"X-Match": "foo", "X-Prev": "previous"}) + assert params["PREV_CAPTURE"] == "" + assert params["X_CAPTURE"] == "" + + def test_proxy_13_03_regex_without_captures(self, env): + params = self.get_params(env, {"X-Nocap": "foo", "X-Prev": "previous"}) + assert params["NOCAP_CAPTURE"] == "<>" + + def test_proxy_13_04_negated_match(self, env): + params = self.get_params(env, {"X-Neg": "foo", "X-Prev": "previous"}) + assert params["NEG_CAPTURE"] == "<>" + + def test_proxy_13_05_multiple_captures(self, env): + params = self.get_params(env, {"X-Two": "ab"}) + assert params["TWO_CAPTURE"] == "" + + def test_proxy_13_06_no_match_unset(self, env): + # none of the conditions is true: no variables at all + params = self.get_params(env, {}) + # (NEG_CAPTURE is set: a missing header is "" which does not match) + for name in ["PREV_CAPTURE", "X_CAPTURE", "NOCAP_CAPTURE", + "TWO_CAPTURE"]: + assert name not in params, params diff --git a/test/unit/regex.c b/test/unit/regex.c new file mode 100644 index 00000000000..b6cc33a0679 --- /dev/null +++ b/test/unit/regex.c @@ -0,0 +1,187 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "../httpdunit.h" + +#include "httpd.h" +#include "ap_regex.h" +#include "apr_strings.h" + +/* + * Test Fixture -- runs once per test + */ + +static apr_pool_t *g_pool; + +static void regex_setup(void) +{ + if (apr_pool_create(&g_pool, NULL) != APR_SUCCESS) { + exit(1); + } +} + +static void regex_teardown(void) +{ + apr_pool_destroy(g_pool); +} + +/* + * ap_regexec() must fill every slot of the vector: groups which did not + * participate in the match (and slots beyond the last group) get -1/-1. + */ + +START_TEST(regexec_fills_unused_slots_with_minus_one) +{ + ap_regex_t re; + ap_regmatch_t pmatch[AP_MAX_REG_MATCH]; + int i; + + for (i = 0; i < AP_MAX_REG_MATCH; ++i) { + pmatch[i].rm_so = pmatch[i].rm_eo = 12345; + } + + ck_assert_int_eq(ap_regcomp(&re, "^(a)(x)?(c)?", 0), 0); + ck_assert_int_eq(ap_regexec(&re, "abc", AP_MAX_REG_MATCH, pmatch, 0), 0); + + ck_assert_int_eq(pmatch[0].rm_so, 0); + ck_assert_int_eq(pmatch[0].rm_eo, 1); + ck_assert_int_eq(pmatch[1].rm_so, 0); + ck_assert_int_eq(pmatch[1].rm_eo, 1); + for (i = 2; i < AP_MAX_REG_MATCH; ++i) { + ck_assert_int_eq(pmatch[i].rm_so, -1); + ck_assert_int_eq(pmatch[i].rm_eo, -1); + } + ap_regfree(&re); +} +END_TEST + +/* + * ap_pregsub() with a match vector that was never (fully) filled in: slots + * with negative or inverted offsets must expand to nothing. + */ + +struct ap_pregsub_case { + const char *input; + const char *source; + ap_regmatch_t pmatch[3]; + const char *expected; +}; + +const struct ap_pregsub_case ap_pregsub_cases[] = { + /* a regular match */ + { "<$0|$1|$2>", "abc", { {0, 3}, {1, 2}, {-1, -1} }, "" }, + /* nothing matched at all (as ap_regexec() leaves a reset vector) */ + { "<$0|$1|$2>", "abc", { {-1, -1}, {-1, -1}, {-1, -1} }, "<||>" }, + /* negative start, positive end */ + { "<$1>", "abc", { {0, 3}, {-1, 2}, {-1, -1} }, "<>" }, + /* negative start, negative end but inverted */ + { "<$1>", "abc", { {0, 3}, {-5, -1}, {-1, -1} }, "<>" }, + /* inverted offsets: negative length */ + { "<$1>", "abc", { {0, 3}, {2, 1}, {-1, -1} }, "<>" }, + /* empty group */ + { "<$1>", "abc", { {0, 3}, {1, 1}, {-1, -1} }, "<>" }, + /* a group above nmatch is ignored */ + { "<$5>", "abc", { {0, 3}, {1, 2}, {-1, -1} }, "<>" }, +}; + +const size_t ap_pregsub_cases_len = sizeof(ap_pregsub_cases) / + sizeof(ap_pregsub_cases[0]); + +HTTPD_START_LOOP_TEST(pregsub_rejects_bogus_offsets, ap_pregsub_cases_len) +{ + const struct ap_pregsub_case *c = &ap_pregsub_cases[_i]; + ap_regmatch_t pmatch[3]; + char *result; + + memcpy(pmatch, c->pmatch, sizeof(pmatch)); + result = ap_pregsub(g_pool, c->input, c->source, 3, pmatch); + ck_assert_ptr_nonnull(result); + ck_assert_str_eq(result, c->expected); +} +END_TEST + +/* + * ap_rxplus_match() must not hand out a pointer/length for a group which + * did not participate in the match. + */ + +START_TEST(rxplus_match_rejects_unset_groups) +{ + ap_rxplus_t *rx = ap_rxplus_compile(g_pool, "/^(a)(x)?(c)?/"); + const char *match = NULL; + int len = 0; + + ck_assert_ptr_nonnull(rx); + ck_assert_int_eq(ap_rxplus_exec(g_pool, rx, "abc", NULL), 1); + + ap_rxplus_match(rx, 1, &len, &match); + ck_assert_int_eq(len, 1); + ck_assert_ptr_nonnull(match); + ck_assert_int_eq(match[0], 'a'); + + match = NULL; + len = 0; + ap_rxplus_match(rx, 2, &len, &match); + ck_assert_int_eq(len, -1); + ck_assert_ptr_null(match); +} +END_TEST + +/* + * ap_rxplus_exec() with the 'g' flag must terminate on patterns that match + * the empty string, and still substitute all non-empty matches. + */ + +struct ap_rxplus_exec_case { + const char *expr; + const char *subject; + const char *expected; +}; + +const struct ap_rxplus_exec_case ap_rxplus_exec_cases[] = { + { "s/b/-/g", "abcb", "a-c-" }, + /* leftmost match is empty at offset 0: substituted once, no recursion */ + { "s/x*/-/g", "abc", "-abc" }, + { "s/b*/-/g", "abc", "-abc" }, + { "s/^/-/g", "abc", "-abc" }, + /* non-empty match consumed, then a single empty match on the empty + * remainder, then no further recursion */ + { "s/c*$/-/g", "abc", "ab--" }, + { "s/b+/-/g", "abbc", "a-c" }, +}; + +const size_t ap_rxplus_exec_cases_len = sizeof(ap_rxplus_exec_cases) / + sizeof(ap_rxplus_exec_cases[0]); + +HTTPD_START_LOOP_TEST(rxplus_exec_terminates_on_empty_matches, ap_rxplus_exec_cases_len) +{ + const struct ap_rxplus_exec_case *c = &ap_rxplus_exec_cases[_i]; + ap_rxplus_t *rx = ap_rxplus_compile(g_pool, c->expr); + char *result = NULL; + + ck_assert_ptr_nonnull(rx); + ck_assert_int_ge(ap_rxplus_exec(g_pool, rx, c->subject, &result), 1); + ck_assert_ptr_nonnull(result); + ck_assert_str_eq(result, c->expected); +} +END_TEST + +/* + * Test Case Boilerplate + */ +HTTPD_BEGIN_TEST_CASE_WITH_FIXTURE(regex, regex_setup, regex_teardown) +#include "test/unit/regex.tests" +HTTPD_END_TEST_CASE From cd6d75afdca2222c55a07e6de5d1c36ff1e82198 Mon Sep 17 00:00:00 2001 From: Eric Covener Date: Thu, 26 Nov 2026 12:53:21 -0500 Subject: [PATCH 06/10] * include/ap_mmn.h: Use a single MMN minor bump for this backport. 2.4.x-only change, not a trunk merge. The merges of r1915267 and r1915268 and the 2.4.x-only AP_REG_NOTEMPTY/AP_REG_ANCHORED commit each bumped the minor (143, 144, 145), following the trunk commits. They land in 2.4.x together, so one bump to 143 covering all of the new API is enough. Co-Authored-By: Claude Opus 5.5 --- include/ap_mmn.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/include/ap_mmn.h b/include/ap_mmn.h index c9a04634c93..8c315918632 100644 --- a/include/ap_mmn.h +++ b/include/ap_mmn.h @@ -612,9 +612,9 @@ * 20120211.140 (2.4.64-dev) Add ap_set_time_process_request() to scoreboard.h * 20120211.141 (2.4.64-dev) add ap_stat_check() to httpd.h * 20120211.142 (2.4.64-dev) Add ap_*_timingsafe() to httpd.h - * 20120211.143 (2.4.72-dev) Add ap_regexec_ex() - * 20120211.144 (2.4.72-dev) Add AP_REG_NOTEMPTY_ATSTART - * 20120211.145 (2.4.72-dev) Add AP_REG_NOTEMPTY and AP_REG_ANCHORED + * 20120211.143 (2.4.72-dev) Add ap_regexec_ex() and the AP_REG_NOTEMPTY, + * AP_REG_NOTEMPTY_ATSTART and AP_REG_ANCHORED + * options */ #define MODULE_MAGIC_COOKIE 0x41503234UL /* "AP24" */ @@ -622,7 +622,7 @@ #ifndef MODULE_MAGIC_NUMBER_MAJOR #define MODULE_MAGIC_NUMBER_MAJOR 20120211 #endif -#define MODULE_MAGIC_NUMBER_MINOR 145 /* 0...n */ +#define MODULE_MAGIC_NUMBER_MINOR 143 /* 0...n */ /** * Determine if the server's current MODULE_MAGIC_NUMBER is at least a From b1b015f7cbd850328bcbd1c15c6c922ca734d9c6 Mon Sep 17 00:00:00 2001 From: Eric Covener Date: Thu, 26 Nov 2026 14:43:54 -0500 Subject: [PATCH 07/10] Regex matches with out of order or out of range offsets (#1098) * Regex matches with out of order or out of range offsets: PCRE versions which accept \K in a lookaround (PCRE1, PCRE2 before 10.38) can report a match whose start is after its end ("a(?=bc\K)"), or before the offset the match was started from ("(?<=\K.)b" from a later position). mod_headers' edit/edit* aborted the child on the first with ap_assert() and used a wrapped-around length for the second, and mod_substitute and mod_proxy_html used the offsets as-is. * modules/metadata/mod_headers.c (push_match): Replace ap_assert() with AP_DEBUG_ASSERT() plus a runtime check, also requiring the match to start at or after *pos and end within the string, and treat a match failing it as no match. * modules/filters/mod_substitute.c (match_in_range): New helper. (do_pattmatch): Treat a match out of range as no match. * modules/filters/mod_proxy_html.c (match_in_range): New helper. (dump_content, pstartElement): Treat a match out of range as no match. * changes-entries/regex_match_offsets.txt: Add. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PUN2EPhoNvc4rfibgy6H72 * Delete changes-entries/regex_match_offsets.txt no changes-entry --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit 8347e21aeea669b599fb7e4cf3db0299de5207b1) --- modules/filters/mod_proxy_html.c | 27 ++++++++++++++++++++++++--- modules/filters/mod_substitute.c | 19 ++++++++++++++++++- modules/metadata/mod_headers.c | 16 ++++++++++++++-- 3 files changed, 56 insertions(+), 6 deletions(-) diff --git a/modules/filters/mod_proxy_html.c b/modules/filters/mod_proxy_html.c index 9b30d1e7fa9..108fab08541 100644 --- a/modules/filters/mod_proxy_html.c +++ b/modules/filters/mod_proxy_html.c @@ -194,6 +194,22 @@ static void pcharacters(void *ctxt, const xmlChar *uchars, int length) FLUSH; } +/* Whether a successful match's offsets are within [start, len] and in + * order. Some PCRE versions accept \K in a lookaround, which can report + * a match starting after its end or before the start offset; such a match + * is treated as no match. + */ +static int match_in_range(const ap_regmatch_t *m, apr_size_t start, + apr_size_t len) +{ + int ok = (m->rm_so >= 0 + && (apr_size_t)m->rm_so >= start + && m->rm_so <= m->rm_eo + && (apr_size_t)m->rm_eo <= len); + AP_DEBUG_ASSERT(ok); + return ok; +} + static void dump_content(saxctxt *ctx) { urlmap *m; @@ -232,7 +248,8 @@ static void dump_content(saxctxt *ctx) * then made relative to offs below. */ if (ap_regexec_ex(m->from.r, ctx->vb.buf, len, offs, - nmatch, pmatch, eflags)) { + nmatch, pmatch, eflags) + || !match_in_range(&pmatch[0], offs, len)) { if (!eflags) { break; } @@ -492,7 +509,9 @@ static void pstartElement(void *ctxt, const xmlChar *uname, if (m->flags & M_REGEX) { nmatch = 10; if (!ap_regexec(m->from.r, ctx->vb.buf, nmatch, - pmatch, 0)) { + pmatch, 0) + && match_in_range(&pmatch[0], 0, + strlen(ctx->vb.buf))) { ++num_match; match = pmatch[0].rm_so; s_from = pmatch[0].rm_eo - match; @@ -561,7 +580,9 @@ static void pstartElement(void *ctxt, const xmlChar *uname, /* See dump_content() */ if (ap_regexec_ex(m->from.r, ctx->vb.buf, len, offs, nmatch, pmatch, - eflags)) { + eflags) + || !match_in_range(&pmatch[0], offs, + len)) { if (!eflags) { break; } diff --git a/modules/filters/mod_substitute.c b/modules/filters/mod_substitute.c index 9d062c4bf94..fdb5b7dc1f0 100644 --- a/modules/filters/mod_substitute.c +++ b/modules/filters/mod_substitute.c @@ -124,6 +124,22 @@ static void *merge_substitute_dcfg(apr_pool_t *p, void *basev, void *overv) #define CAP2LINEMAX(n) ((n) < (apr_size_t)200 ? (int)(n) : 200) +/* Whether a successful match's offsets are within [start, len] and in + * order. Some PCRE versions accept \K in a lookaround, which can report + * a match starting after its end or before the start offset; such a match + * is treated as no match. + */ +static int match_in_range(const ap_regmatch_t *m, apr_size_t start, + apr_size_t len) +{ + int ok = (m->rm_so >= 0 + && (apr_size_t)m->rm_so >= start + && m->rm_so <= m->rm_eo + && (apr_size_t)m->rm_eo <= len); + AP_DEBUG_ASSERT(ok); + return ok; +} + static apr_status_t do_pattmatch(ap_filter_t *f, apr_bucket *inb, apr_bucket_brigade *mybb, apr_pool_t *pool) @@ -293,7 +309,8 @@ static apr_status_t do_pattmatch(ap_filter_t *f, apr_bucket *inb, */ if (ap_regexec_ex(script->regexp, buff, bytes, pos - buff, AP_MAX_REG_MATCH, regm, - eflags)) { + eflags) + || !match_in_range(®m[0], pos - buff, bytes)) { if (!eflags || !left) { break; } diff --git a/modules/metadata/mod_headers.c b/modules/metadata/mod_headers.c index 88af1e25012..227a8957d07 100644 --- a/modules/metadata/mod_headers.c +++ b/modules/metadata/mod_headers.c @@ -653,8 +653,20 @@ static int push_match(apr_array_header_t *iovecs, return (rc == AP_REG_NOMATCH) ? 0 : -1; } - /* Sanity checks (note that the rm_so/rm_eo offsets include *pos) */ - ap_assert(pmatch[0].rm_so >= 0 && pmatch[0].rm_so <= pmatch[0].rm_eo); + /* Sanity checks (note that the rm_so/rm_eo offsets include *pos). + * Some PCRE versions accept \K in a lookaround, which can report a + * match starting after its end or before *pos; treat it as no match. + */ + AP_DEBUG_ASSERT(pmatch[0].rm_so >= 0 + && (apr_size_t)pmatch[0].rm_so >= *pos + && pmatch[0].rm_so <= pmatch[0].rm_eo + && (apr_size_t)pmatch[0].rm_eo <= len); + if (pmatch[0].rm_so < 0 + || (apr_size_t)pmatch[0].rm_so < *pos + || pmatch[0].rm_so > pmatch[0].rm_eo + || (apr_size_t)pmatch[0].rm_eo > len) { + return 0; + } /* Process tags in the input string rather than the resulting * substitution to avoid surprises From 5f72bba3124273f92aa6545ef3d80c2ed0082017 Mon Sep 17 00:00:00 2001 From: Eric Covener Date: Thu, 26 Nov 2026 20:54:02 -0500 Subject: [PATCH 08/10] Merge 9dd5a60043 from trunk (PR #1101; conflicts resolved in test/modules/proxy/test_03_uwsgi.py, AGENTS.md changes omitted): test: Load mod_proxy_ajp, mod_proxy_uwsgi and mod_proxy_fcgi as optional modules. A module in ProxyTestSetup.add_modules() that the build lacks stops setup with "Unable to find modules", failing every test under test/modules/proxy, and the env.require() checks in the tests that use these modules could never be reached. Load them with add_optional_modules() so a build without one skips only those tests (or fails them under --strict-optional). * test/modules/proxy/env.py: Move proxy_ajp, proxy_uwsgi and proxy_fcgi to add_optional_modules(). * test/modules/proxy/test_03_uwsgi.py: Check for mod_proxy_uwsgi with env.require() in the setup fixture, which had no check. * test/README.pytest: Describe when a test module belongs in add_modules() and when in add_optional_modules(). (2.4.x's test_03_uwsgi.py has a single module-level setup fixture, so the check goes there; 2.4.x has no AGENTS.md.) --- test/README.pytest | 17 +++++++++++++++++ test/modules/proxy/env.py | 10 ++++++---- test/modules/proxy/test_03_uwsgi.py | 3 +++ 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/test/README.pytest b/test/README.pytest index 30cc8f0274d..f7a31ff67e5 100644 --- a/test/README.pytest +++ b/test/README.pytest @@ -234,6 +234,23 @@ and cache the answer: @H2TestEnv.needs_h2load("1.41.0") @HttpdTestEnv.needs_multipart() +If your test needs a module, list it in the test package's +'*TestSetup' (its env.py). 'add_modules()' is for modules that +every test in the package needs: a build without one of them +stops setup with "Unable to find modules", so the whole package +fails. A module that only some of the tests use goes in +'add_optional_modules()', which loads it when it is there, and +the tests that use it check for it: + + env.require(env.has_shared_module("proxy_fcgi"), + "mod_proxy_fcgi not available", + dep="mod_proxy_fcgi", + detected=f"no mod_proxy_fcgi.so in {env.libexec_dir}") + +'has_shared_module()' is true for a module built as a DSO and for +one compiled into httpd. test/modules/proxy/test_13_fcgi_setenvif.py +is an example. + For a check that can only be made once the test is running, 'env.require()' does the same job from inside the body: diff --git a/test/modules/proxy/env.py b/test/modules/proxy/env.py index aa26f23ae09..3aa2870d58c 100644 --- a/test/modules/proxy/env.py +++ b/test/modules/proxy/env.py @@ -81,10 +81,12 @@ class ProxyTestSetup(HttpdTestSetup): def __init__(self, env: 'HttpdTestEnv'): super().__init__(env=env) self.add_source_dir(os.path.dirname(inspect.getfile(ProxyTestSetup))) - self.add_modules(["proxy", "proxy_http", "proxy_ajp", "proxy_balancer", - "proxy_connect", "proxy_uwsgi", "proxy_fcgi", - "lbmethod_byrequests", "remoteip"]) - self.add_optional_modules(["proxy_hcheck", "proxy_scgi"]) + self.add_modules(["proxy", "proxy_http", "proxy_balancer", + "proxy_connect", "lbmethod_byrequests", "remoteip"]) + # Modules only some tests use: a build without one skips those + # tests (env.require()) instead of failing setup for the package. + self.add_optional_modules(["proxy_hcheck", "proxy_scgi", "proxy_ajp", + "proxy_uwsgi", "proxy_fcgi"]) class ProxyTestEnv(HttpdTestEnv): diff --git a/test/modules/proxy/test_03_uwsgi.py b/test/modules/proxy/test_03_uwsgi.py index fff082321f5..40303f803ef 100644 --- a/test/modules/proxy/test_03_uwsgi.py +++ b/test/modules/proxy/test_03_uwsgi.py @@ -18,6 +18,9 @@ @pytest.fixture(autouse=True, scope="class") def _proxy_uwsgi_setup(env): + env.require(env.has_shared_module("proxy_uwsgi"), "mod_proxy_uwsgi not available", + dep="mod_proxy_uwsgi", + detected=f"no mod_proxy_uwsgi.so in {env.libexec_dir}") faker = UwsgiFaker(port=UWSGI_PORT) faker.start() From 5f7b1c488170e4a53f3256ed687799684556bb23 Mon Sep 17 00:00:00 2001 From: Eric Covener Date: Thu, 26 Nov 2026 21:45:27 -0500 Subject: [PATCH 09/10] Merge 4468c242a6 from trunk (PR #1101): test: Mark the tests of the regex backreference changes not_backported. test/ is copied to 2.4.x as it is, so mark the tests from #1096 that fail on a 2.4.x without the change, expecting the backport (#1097) in 2.4.72. Marks follow a run against unfixed 2.4.x: a test that hangs the server, crashes it or leaves errors in the error log is skipped, one that fails cleanly is an expected failure, and one that passes is left unmarked. * test/modules/filters/test_010_substitute_empty_match.py: Skip the cases that loop forever or log "Line too long"; anchor_nonempty fails cleanly; lookbehind passes already. * test/modules/metadata/test_006_expr_backref.py: Skip the class: its Header edit* lines crash every request without r1915271. * test/modules/proxy/test_13_fcgi_setenvif.py: Only the short-circuit test fails without the change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PUN2ETFf8d5srUT51exsTS (cherry picked from commit 4468c242a6a48db509c516d53af8103157c5865c) --- .../filters/test_010_substitute_empty_match.py | 14 +++++++++++++- test/modules/metadata/test_006_expr_backref.py | 5 +++++ test/modules/proxy/test_13_fcgi_setenvif.py | 3 +++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/test/modules/filters/test_010_substitute_empty_match.py b/test/modules/filters/test_010_substitute_empty_match.py index 5a4a0bd48c3..b9f35cb01ca 100644 --- a/test/modules/filters/test_010_substitute_empty_match.py +++ b/test/modules/filters/test_010_substitute_empty_match.py @@ -2,6 +2,7 @@ import pytest +from pyhttpd.backport import not_backported, skip_not_backported from pyhttpd.conf import HttpdConf # Patterns that can match the empty string must not loop forever (or until @@ -33,6 +34,17 @@ 'mixed_empty_nonempty': ('b*', '-', 'f', 'abbc', '-a--c-'), } +# Without the change, most of these loop until "Line too long" is logged, +# and star_empty_* loop forever. +WHAT = "mod_substitute empty matches" +SKIP = skip_not_backported("gh-1096", WHAT, backported_in="2.4.72") +MARKS = { + 'anchor_nonempty': not_backported("gh-1096", WHAT, backported_in="2.4.72"), + 'lookbehind': (), +} +PARAMS = [pytest.param(name, id=name, marks=MARKS.get(name, SKIP)) + for name in CASES] + class TestSubstituteEmptyMatch: @@ -58,7 +70,7 @@ def configure(self, env, pattern, repl, flags): conf.install() assert env.apache_restart() == 0 - @pytest.mark.parametrize("name", list(CASES), ids=list(CASES)) + @pytest.mark.parametrize("name", PARAMS) def test_filters_010_01(self, env, name): pattern, repl, flags, _, expected = CASES[name] self.configure(env, pattern, repl, flags) diff --git a/test/modules/metadata/test_006_expr_backref.py b/test/modules/metadata/test_006_expr_backref.py index 4bfee9b223a..2fc7538baa3 100644 --- a/test/modules/metadata/test_006_expr_backref.py +++ b/test/modules/metadata/test_006_expr_backref.py @@ -1,5 +1,6 @@ import pytest +from pyhttpd.backport import skip_not_backported from pyhttpd.conf import HttpdConf # An expression that evaluates to true without evaluating a capturing regex @@ -15,6 +16,10 @@ LONG = "long-" + "x" * 200 +# Without r1915271 the Header edit* lines below crash every request, so +# none of the tests can run. +@skip_not_backported("r1915271", "mod_headers edit* recursion on empty matches", + backported_in="2.4.72") class TestExprBackref: @pytest.fixture(autouse=True, scope='class') diff --git a/test/modules/proxy/test_13_fcgi_setenvif.py b/test/modules/proxy/test_13_fcgi_setenvif.py index 53e46fde9d1..cd52084b053 100644 --- a/test/modules/proxy/test_13_fcgi_setenvif.py +++ b/test/modules/proxy/test_13_fcgi_setenvif.py @@ -1,5 +1,6 @@ import pytest +from pyhttpd.backport import not_backported from pyhttpd.conf import HttpdConf from .fcgi_faker import FCGIFaker @@ -46,6 +47,8 @@ def get_params(self, env, headers): assert r.response["status"] == 200, r.response return r.response["json"] + @not_backported("gh-1096", "ProxyFCGISetEnvIf backreferences without a capturing match", + backported_in="2.4.72") def test_proxy_13_01_short_circuit(self, env): params = self.get_params(env, {"X-Match": "skip", "X-Prev": "previous"}) assert params["PREV_CAPTURE"] == "" From fd0fe4a808b24133d7f25305f1e6ab25314d8cea Mon Sep 17 00:00:00 2001 From: Eric Covener Date: Thu, 26 Nov 2026 21:51:54 -0500 Subject: [PATCH 10/10] Merge c1185a1b89 from trunk (PR #1101): test: Name the pull request in the not_backported examples. Changes are made by pull request now, so the examples showing svn revisions led to marks waiting for a revision that never comes. Show "gh-NNNN" instead, and say that the "rNNNNNNN" names in older marks are svn revisions from before the move to git. * test/pyhttpd/backport.py, test/README.pytest: Use gh-1096 in the examples, and explain the older revision names. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PUN2ETFf8d5srUT51exsTS (cherry picked from commit c1185a1b89dc25f189c13c5ba3b1f9d7c058978b) --- test/README.pytest | 11 +++++++---- test/pyhttpd/backport.py | 9 ++++++--- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/test/README.pytest b/test/README.pytest index f7a31ff67e5..ed5eb6910fe 100644 --- a/test/README.pytest +++ b/test/README.pytest @@ -285,12 +285,15 @@ This directory is the same on trunk and on 2.4.x: a test is written on trunk, then `test/` is copied to 2.4.x as it is, and `check-test-sync.sh` fails if the two branches differ. A test covering a trunk change that 2.4.x does not have yet carries a mark from `pyhttpd/backport.py` (or, in `pytest_suite/`, -`apache_pytest.not_backported`) naming the trunk revision: +`apache_pytest.not_backported`) naming the pull request that made the +change: from pyhttpd.backport import not_backported, skip_not_backported - @not_backported("r1939033", "nonce-count validation") - def test_digest_001(self, env): ... + @not_backported("gh-1096", "mod_substitute empty matches") + def test_filters_010_01(self, env): ... + +Older marks name svn revisions ("r1939033"), from before the move to git. `not_backported` makes the test an expected failure on a server older than 2.5.0, `skip_not_backported` skips it where failing would hang or crash the @@ -309,7 +312,7 @@ skipped, or failed under `--strict-optional`. When the change is backported, add the 2.4.x release it first appears in: - @not_backported("r1939033", "nonce-count validation", backported_in="2.4.71") + @not_backported("gh-1096", "mod_substitute empty matches", backported_in="2.4.72") on trunk, then copy `test/` to 2.4.x again. Older 2.4.x servers keep the expectation. `platform="win32"` limits it to one `sys.platform`. diff --git a/test/pyhttpd/backport.py b/test/pyhttpd/backport.py index c258b48557a..44cfe5ba695 100644 --- a/test/pyhttpd/backport.py +++ b/test/pyhttpd/backport.py @@ -9,12 +9,15 @@ appears in, on trunk and copy the file over; older 2.4.x releases keep the expectation. - pytestmark = not_backported("r1939033", "nonce-count validation") + pytestmark = not_backported("gh-1096", "mod_substitute empty matches") - @skip_not_backported("r1938487", "recursion limit in mod_sed", - backported_in="2.4.71") + @skip_not_backported("gh-1096", "mod_substitute empty matches", + backported_in="2.4.72") def test_... +The first argument names the pull request that made the change ("gh-1096"). +Older marks name svn revisions ("r1939033"), from before the move to git. + platform limits the expectation to one sys.platform, for a failure on 2.4.x which trunk does not have there.