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/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/include/ap_mmn.h b/include/ap_mmn.h index d00c6d1ec9c..8c315918632 100644 --- a/include/ap_mmn.h +++ b/include/ap_mmn.h @@ -612,6 +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() and the AP_REG_NOTEMPTY, + * AP_REG_NOTEMPTY_ATSTART and AP_REG_ANCHORED + * options */ #define MODULE_MAGIC_COOKIE 0x41503234UL /* "AP24" */ @@ -619,7 +622,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..72095f777f8 100644 --- a/include/ap_regex.h +++ b/include/ap_regex.h @@ -82,10 +82,15 @@ 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 */ +#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) @@ -169,7 +174,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 +189,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/modules/filters/mod_proxy_html.c b/modules/filters/mod_proxy_html.c index efaa2bb7db2..108fab08541 100644 --- a/modules/filters/mod_proxy_html.c +++ b/modules/filters/mod_proxy_html.c @@ -194,13 +194,29 @@ 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; 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 +240,33 @@ 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) + || !match_in_range(&pmatch[0], offs, len)) { + 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 +282,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 +403,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); @@ -459,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; @@ -522,8 +574,29 @@ 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) + || !match_in_range(&pmatch[0], offs, + len)) { + 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 +615,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..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) @@ -283,9 +299,48 @@ 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) + || !match_in_range(®m[0], pos - buff, bytes)) { + 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 +391,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/metadata/mod_headers.c b/modules/metadata/mod_headers.c index f514b4bc6a0..227a8957d07 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,137 @@ 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). + * 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 + */ + 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 +912,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) 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_pcre.c b/server/util_pcre.c index 46e82112a58..bc61e2b8ff6 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) { @@ -423,16 +438,22 @@ AP_DECLARE(int) ap_regexec_len(const ap_regex_t *preg, const char *buff, 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, (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) { 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/README.pytest b/test/README.pytest index 30cc8f0274d..ed5eb6910fe 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: @@ -268,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 @@ -292,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/modules/filters/test_010_substitute_empty_match.py b/test/modules/filters/test_010_substitute_empty_match.py new file mode 100644 index 00000000000..b9f35cb01ca --- /dev/null +++ b/test/modules/filters/test_010_substitute_empty_match.py @@ -0,0 +1,82 @@ +import os + +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 +# 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", PARAMS) + 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..2fc7538baa3 --- /dev/null +++ b/test/modules/metadata/test_006_expr_backref.py @@ -0,0 +1,138 @@ +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 +# (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 + + +# 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') + @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..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", "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/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_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() 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..cd52084b053 --- /dev/null +++ b/test/modules/proxy/test_13_fcgi_setenvif.py @@ -0,0 +1,80 @@ +import pytest + +from pyhttpd.backport import not_backported +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"] + + @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"] == "" + 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/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. 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