MEDIUM: checks: capture groups in expect regexes

Parse back-references in comments of tcp-check expect rules.  If references are
made, capture groups in the match and replace references to it within the
comment when logging the error. Both text and binary regex can caputre groups
and reference them in the expect rule comment.

[Cf: I slightly updated the patch. exp_replace() function is used instead of a
custom one. And if the trash buffer is too small to contain the comment during
the substitution, the comment is ignored.]
diff --git a/reg-tests/checks/tcp-check_comment-with-capture.vtc b/reg-tests/checks/tcp-check_comment-with-capture.vtc
new file mode 100644
index 0000000..31f8820
--- /dev/null
+++ b/reg-tests/checks/tcp-check_comment-with-capture.vtc
@@ -0,0 +1,60 @@
+varnishtest "tcp-check expect rule with capture groups"
+#EXCLUDE_TARGETS=freebsd,osx,generic
+#REQUIRE_VERSION=2.2
+#REGTEST_TYPE=slow
+# This script tests expect rules matching a regex with capture groups and
+# defining a comment with backreferences. Text and binary regex are tested.
+feature ignore_unknown_macro
+
+syslog S1 -level notice {
+    recv
+    expect ~ "[^:\\[ ]\\[${h1_pid}\\]: Proxy be1 started."
+    recv
+    expect ~ "[^:\\[ ]\\[${h1_pid}\\]: Health check for server be1/srv1 failed.*code=400 reason=Bad Request"
+} -start
+
+syslog S2 -level notice {
+    recv
+    expect ~ "[^:\\[ ]\\[${h1_pid}\\]: Proxy be2 started."
+    recv
+    expect ~ "[^:\\[ ]\\[${h1_pid}\\]: Health check for server be2/srv1 failed.*code=400 reason=Bad Request"
+} -start
+
+server s1 {
+    rxreq
+    txresp -status 400 -reason "Bad Request"
+} -start
+
+server s2 {
+    rxreq
+    txresp -status 400 -reason "Bad Request"
+} -start
+
+haproxy h1 -conf {
+  defaults
+    timeout client 5s
+    timeout connect 5s
+    timeout server 5s
+    timeout check 5s
+
+  backend be1
+    log ${S1_addr}:${S1_port} len 2048 local0
+    option tcp-check
+    option log-health-checks
+    tcp-check connect
+    tcp-check send "GET / HTTP/1.1\r\n\r\n"
+    tcp-check expect !rstring "HTTP/1\\.1\s+([45][0-9]{2})\s+([^\r\n]*)" comment " Bad response: code=\\1 reason=\\2"
+    server srv1 ${s1_addr}:${s1_port} check inter 1000ms rise 1 fall 1
+
+  backend be2
+    log ${S2_addr}:${S2_port} len 2048 local0
+    option tcp-check
+    option log-health-checks
+    tcp-check connect
+    tcp-check send-binary "474554202f20485454502f312e31200d0a0d0a" # GET / HTTP/1.1\r\n\r\n
+    tcp-check expect !rbinary "485454502F312E3120(34[0-9]{4}|35[0-9]{4})20(([^0].)*)" comment " Bad response: code=\\1 reason=\\2"
+    server srv1 ${s2_addr}:${s2_port} check inter 1000ms rise 1 fall 1
+} -start
+
+syslog S1 -wait
+syslog S2 -wait