Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changes-entries/proxy_fcgi_expr_backref.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*) mod_proxy_fcgi: Fix a crash, or a value taken from a previous
ProxyFCGISetEnvIf, when $N is used after a condition that captured
nothing. $N is then empty.
PR 70369 [Arturo Bernal]
3 changes: 3 additions & 0 deletions modules/proxy/mod_proxy_fcgi.c
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,9 @@ static apr_status_t fix_cgivars(request_rec *r, fcgi_dirconf_t *dconf)
for (i = 0; i < dconf->env_fixups->nelts; i++) {
sei_entry *entry = &entries[i];

/* set only by a capturing regex of this condition */
src = NULL;

rc = ap_expr_exec_re(r, entry->cond, AP_MAX_REG_MATCH, regm, &src, &err);
if (rc < 0) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10241)
Expand Down
2 changes: 1 addition & 1 deletion test/modules/proxy/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def __init__(self, env: 'HttpdTestEnv'):
self.add_modules(["proxy", "proxy_http", "proxy_ajp", "proxy_balancer",
"proxy_connect", "proxy_uwsgi", "lbmethod_byrequests",
"remoteip"])
self.add_optional_modules(["proxy_hcheck"])
self.add_optional_modules(["proxy_hcheck", "proxy_fcgi"])


class ProxyTestEnv(HttpdTestEnv):
Expand Down
113 changes: 113 additions & 0 deletions test/modules/proxy/fcgi_faker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""
Minimal fake FastCGI responder for testing mod_proxy_fcgi.

Answers every request with a JSON object of the FCGI_PARAMS whose
names start with "TEST_", so tests can check what mod_proxy_fcgi sent.
"""
import json
import socket
import struct
import threading

FCGI_HEADER = ">BBHHBB"
FCGI_END_REQUEST = 3
FCGI_PARAMS = 4
FCGI_STDIN = 5
FCGI_STDOUT = 6


def _recv(conn, n):
data = b""
while len(data) < n:
chunk = conn.recv(n - len(data))
if not chunk:
raise EOFError
data += chunk
return data


def _parse_params(data):
params = {}
pos = 0

def length():
nonlocal pos
if data[pos] & 0x80:
n = struct.unpack_from(">I", data, pos)[0] & 0x7fffffff
pos += 4
else:
n = data[pos]
pos += 1
return n

while pos < len(data):
klen = length()
vlen = length()
key = data[pos:pos + klen].decode("latin-1")
pos += klen
params[key] = data[pos:pos + vlen].decode("latin-1")
pos += vlen
return params


def _record(rtype, rid, content=b""):
return struct.pack(FCGI_HEADER, 1, rtype, rid, len(content), 0, 0) + content


def _handle(conn):
try:
params = b""
while True:
_, rtype, rid, clen, plen, _ = struct.unpack(FCGI_HEADER,
_recv(conn, 8))
content = _recv(conn, clen)
_recv(conn, plen)
if rtype == FCGI_PARAMS:
params += content
elif rtype == FCGI_STDIN and clen == 0:
break
body = json.dumps({k: v for k, v in _parse_params(params).items()
if k.startswith("TEST_")}).encode()
out = b"Content-Type: application/json\r\n\r\n" + body
conn.sendall(_record(FCGI_STDOUT, rid, out)
+ _record(FCGI_STDOUT, rid)
+ _record(FCGI_END_REQUEST, rid, b"\0" * 8))
except (EOFError, OSError):
pass
finally:
conn.close()


class FcgiFaker:
"""Fake FastCGI backend running in a daemon thread."""

def __init__(self, port: int):
self._port = port
self._done = False
self._sock = None
self._thread = None

def start(self):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._sock.bind(("127.0.0.1", self._port))
self._sock.listen(16)
self._sock.settimeout(0.5)
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()

def stop(self):
self._done = True
self._thread.join(timeout=5)
self._sock.close()

def _serve(self):
while not self._done:
try:
conn, _ = self._sock.accept()
except socket.timeout:
continue
except OSError:
break
conn.settimeout(None)
threading.Thread(target=_handle, args=(conn,), daemon=True).start()
48 changes: 48 additions & 0 deletions test/modules/proxy/test_12_fcgi_setenvif.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import pytest

from pyhttpd.conf import HttpdConf
from .fcgi_faker import FcgiFaker


class TestProxyFcgiSetEnvIf:

@pytest.fixture(autouse=True, scope='class')
@classmethod
def _class_scope(cls, env):
if not env.has_shared_module("proxy_fcgi"):
pytest.skip("mod_proxy_fcgi not available")
faker = FcgiFaker(env.http_port2)
faker.start()
backend = f"fcgi://127.0.0.1:{env.http_port2}/"
conf = HttpdConf(env)
conf.start_vhost(domains=[f"test1.{env.http_tld}"],
port=env.http_port, with_ssl=False)
conf.add([
"<Location /capture/>",
f" ProxyPass {backend}",
" ProxyFCGISetEnvIf \"reqenv('REQUEST_URI') =~ m#^/capture/(.+)#\" TEST_CAPTURED \"$1\"",
" ProxyFCGISetEnvIf true TEST_NOCAP \"[$1]\"",
"</Location>",
"<Location /nocap/>",
f" ProxyPass {backend}",
" ProxyFCGISetEnvIf true TEST_NOCAP \"[$1]\"",
"</Location>",
])
conf.end_vhost()
conf.install()
assert env.apache_restart() == 0
yield
faker.stop()

# $1 after a condition that captured nothing is empty, not the capture
# of the previous ProxyFCGISetEnvIf nor uninitialized memory (BZ 70369)
@pytest.mark.parametrize("path, expected", [
("/capture/abc", {"TEST_CAPTURED": "abc", "TEST_NOCAP": "[]"}),
("/nocap/abc", {"TEST_NOCAP": "[]"}),
])
def test_proxy_12_01_expr_no_capture(self, env, path, expected):
url = env.mkurl("http", "test1", path)
r = env.curl_get(url, 5)
assert r.exit_code == 0, f"{r}"
assert r.response["status"] == 200
assert r.json == expected
Loading