]> git.ipfire.org Git - thirdparty/dovecot/core.git/commitdiff
lib-var-expand: regex - Support older back references
authorAki Tuomi <aki.tuomi@open-xchange.com>
Tue, 23 Sep 2025 09:58:07 +0000 (12:58 +0300)
committeraki.tuomi <aki.tuomi@open-xchange.com>
Tue, 23 Sep 2025 12:03:51 +0000 (12:03 +0000)
src/lib-var-expand/expansion-filter.c
src/lib-var-expand/test-var-expand.c

index 4bff618d97a2d4e3908010f49f9b53dd16c0fd08..a72bd1e132b31e8cc3d4c953f992c6ca526ba9a4 100644 (file)
@@ -750,6 +750,32 @@ static int fn_ldap_dn(const struct var_expand_statement *stmt,
        return 0;
 }
 
+static const char *fix_replacement_pattern(const char *pattern)
+{
+       const char *p1, *p0 = pattern;
+       string_t *dest = t_str_new(strlen(pattern));
+
+       while ((p1 = strchr(p0, '\\')) != NULL) {
+               str_append_data(dest, p0, p1 - p0);
+               if (i_isdigit(p1[1])) {
+                       str_append_c(dest, '$');
+                       str_append_c(dest, p1[1]);
+                       p1 += 2;
+               } else if (p1[1] == '\\') {
+                       str_append_c(dest, '\\');
+                       p1 += 2;
+               } else {
+                       str_append_c(dest, *p1);
+                       p1++;
+               }
+               p0 = p1;
+       }
+
+       str_append(dest, p0);
+
+       return str_c(dest);
+}
+
 static int fn_regexp(const struct var_expand_statement *stmt,
                     struct var_expand_state *state, const char **error_r)
 {
@@ -798,6 +824,11 @@ static int fn_regexp(const struct var_expand_statement *stmt,
        const char *input ATTR_UNUSED = str_c(state->transfer);
        string_t *dest = t_str_new(strlen(rep));
 
+       if (strchr(rep, '\\') != NULL) {
+               /* fix replacement pattern */
+               rep = fix_replacement_pattern(rep);
+       }
+
        int ret = dregex_replace(pat, input, rep, dest, 0, error_r);
 
        if (ret > 0)
index 6ee360c637fca1b970b7664ee36faca86ae71c1a..2e7ba232a7bbc82ee5ddfb7c37df594e84556d5e 100644 (file)
@@ -199,6 +199,9 @@ static void test_var_expand_builtin_filters(void) {
 #ifdef HAVE_LIBPCRE
                /* regexp */
                { .in = "%{literal('hello world') | regexp('(.*) (.*)', '$2 $1')}", .out = "world hello" },
+               { .in = "%{literal('hello world') | regexp('(.*) (.*)', '\\\\2 \\\\1')}", .out = "world hello" },
+               { .in = "%{literal('hello world') | regexp('(.*) (.*)', '\\\\\\\\2 \\\\\\\\1')}", .out = "\\2 \\1" },
+               { .in = "%{literal('hello world') | regexp('(.*) (.*)', '\\\\\\\\\\\\2 \\\\\\\\\\\\1')}", .out = "\\world \\hello" },
 #endif
                /* index */
                { .in = "%{user | index('@',0)}", .out = "user", .ret = 0 },