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
3 changes: 3 additions & 0 deletions changes-entries/66608.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
*) mod_proxy_fcgi: Fix SCRIPT_NAME when proxy-fcgi-pathinfo is set and the
URL path contains %-escapes; it held the whole path instead of the part
before PATH_INFO. PR 66608. [Arturo Bernal]
25 changes: 25 additions & 0 deletions modules/proxy/mod_proxy_fcgi.c
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ typedef struct {

typedef struct {
char *dirwalk_uri_path;
int path_info_escaped; /* r->path_info is still %-encoded */
} fcgi_req_config_t;

/* We will assume FPM, but still differentiate */
Expand Down Expand Up @@ -142,6 +143,7 @@ static int proxy_fcgi_canon(request_rec *r, char *url)
ap_set_module_config(r->request_config, &proxy_fcgi_module, rconf);
}
rconf->dirwalk_uri_path = NULL;
rconf->path_info_escaped = 0;

pathinfo_type = apr_table_get(r->subprocess_env, "proxy-fcgi-pathinfo");
if (pathinfo_type) {
Expand Down Expand Up @@ -179,6 +181,9 @@ static int proxy_fcgi_canon(request_rec *r, char *url)
if (!strcasecmp(pathinfo_type, "unescape")) {
ap_unescape_url_keep2f(r->path_info, 0);
}
else {
rconf->path_info_escaped = 1;
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01061)
"set r->path_info to %s", r->path_info);
}
Expand Down Expand Up @@ -434,6 +439,26 @@ static apr_status_t send_environment(proxy_conn_rec *conn, request_rec *r,
ap_add_common_vars(r);
ap_add_cgi_vars(r);

/* ap_add_cgi_vars() finds where PATH_INFO starts in r->uri to set
* SCRIPT_NAME, which fails with a %-encoded PATH_INFO as r->uri is
* decoded: do it again with the decoded PATH_INFO. SCRIPT_NAME is the
* whole r->uri for an SSI include, which it leaves alone.
*/
if (rconf && rconf->path_info_escaped && r->path_info && *r->path_info
&& strcmp(r->protocol, "INCLUDED")) {
core_dir_config *d = ap_get_core_module_config(r->per_dir_config);
char *path_info = apr_pstrdup(r->pool, r->path_info);

if (ap_unescape_url_ex(path_info, d->decode_encoded_slashes
? 0 : AP_UNESCAPE_URL_KEEP_SLASHES)
== OK) {
apr_table_setn(r->subprocess_env, "SCRIPT_NAME",
apr_pstrndup(r->pool, r->uri,
ap_find_path_info(r->uri,
path_info)));
}
}

/* SCRIPT_NAME/FILENAME set, restore original */
r->filename = proxy_filename;

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", "include"])


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

Answers every request with a JSON body holding the CGI variables it was
sent, so that a test can check what mod_proxy_fcgi passed to the backend.
"""
import json
import socket
import struct
import threading

FCGI_BEGIN_REQUEST = 1
FCGI_END_REQUEST = 3
FCGI_PARAMS = 4
FCGI_STDIN = 5
FCGI_STDOUT = 6


def _read_exact(conn, n):
data = b""
while len(data) < n:
chunk = conn.recv(n - len(data))
if not chunk:
raise ConnectionError("connection closed")
data += chunk
return data


def _read_record(conn):
version, rtype, req_id, clen, plen, _ = \
struct.unpack("!BBHHBB", _read_exact(conn, 8))
content = _read_exact(conn, clen)
_read_exact(conn, plen)
return rtype, req_id, content


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):
nlen = length()
vlen = length()
name = data[pos:pos + nlen].decode("latin-1")
pos += nlen
params[name] = data[pos:pos + vlen].decode("latin-1")
pos += vlen
return params


def _record(rtype, req_id, content=b""):
return struct.pack("!BBHHBB", 1, rtype, req_id, len(content), 0, 0) + content


class FcgiEcho:

def __init__(self, host, port):
self._host = host
self._port = port
self._socket = None
self._thread = None
self._done = False

def start(self):
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._socket.bind((self._host, self._port))
self._socket.listen(5)
self._socket.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._socket.close()

def _serve(self):
while not self._done:
try:
conn, _ = self._socket.accept()
except socket.timeout:
continue
except OSError:
break
with conn:
conn.settimeout(5)
try:
self._handle(conn)
except (ConnectionError, socket.timeout, struct.error):
pass

def _handle(self, conn):
req_id = 1
params = b""
while True:
rtype, req_id, content = _read_record(conn)
if rtype == FCGI_PARAMS:
params += content
elif rtype == FCGI_STDIN and not content:
break
body = json.dumps(_parse_params(params)).encode()
head = b"Content-Type: application/json\r\n\r\n"
conn.sendall(_record(FCGI_STDOUT, req_id, head + body)
+ _record(FCGI_STDOUT, req_id)
+ _record(FCGI_END_REQUEST, req_id, b"\0" * 8))
80 changes: 80 additions & 0 deletions test/modules/proxy/test_12_fcgi_script_name.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import json
import os

import pytest

from pyhttpd.conf import HttpdConf
from .fcgi_echo import FcgiEcho


class TestProxyFcgiScriptName:
"""SCRIPT_NAME sent to a FastCGI backend with proxy-fcgi-pathinfo set.
It must not include the PATH_INFO part (RFC 3875 4.1.13), also when the
URL path holds %-escapes (PR 66608)."""

@pytest.fixture(autouse=True, scope='class')
def _class_scope(self, 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}")
env.require(env.has_shared_module("include"),
"mod_include not available", dep="mod_include",
detected=f"no mod_include.so in {env.libexec_dir}")
# An SSI page including the FastCGI paths as subrequests, which run
# with SERVER_PROTOCOL "INCLUDED".
with open(os.path.join(env.server_dir, "htdocs", "fcgi_inc.shtml"),
"w") as fd:
fd.write('@@<!--#include virtual="/inc/a/b" -->@@\n'
'@@<!--#include virtual="/inc/a%20b/c" -->@@\n')
backend = FcgiEcho("127.0.0.1", env.http_port2)
backend.start()
conf = HttpdConf(env)
conf.start_vhost(domains=[f"test1.{env.http_tld}"], port=env.http_port)
conf.add([
"SetEnvIf Request_URI ^/app/ proxy-fcgi-pathinfo=1",
"SetEnvIf Request_URI ^/unesc/ proxy-fcgi-pathinfo=unescape",
"ProxyFCGIBackendType GENERIC",
f"ProxyPass /app/ fcgi://127.0.0.1:{env.http_port2}/",
f"ProxyPass /unesc/ fcgi://127.0.0.1:{env.http_port2}/",
# SetEnvIf does not run for subrequests, mod_rewrite does.
"<Location /inc/>",
" RewriteEngine on",
" RewriteRule ^ - [E=proxy-fcgi-pathinfo:1]",
"</Location>",
f"ProxyPass /inc/ fcgi://127.0.0.1:{env.http_port2}/",
"<Location /fcgi_inc.shtml>",
" Options +Includes",
" SetOutputFilter INCLUDES",
"</Location>",
])
conf.end_vhost()
conf.install()
assert env.apache_restart() == 0
yield
backend.stop()

@pytest.mark.parametrize("path, script_name, path_info", [
("/app/a/b", "/app", "/a/b"),
("/app/a/x%20y", "/app", "/a/x%20y"),
("/app/%C3%A9t%C3%A9/z", "/app", "/%C3%A9t%C3%A9/z"),
("/unesc/a/x%20y", "/unesc", "/a/x y"),
])
def test_proxy_012_01(self, env, path, script_name, path_info):
r = env.curl_get(env.mkurl("http", "test1", path))
assert r.response["status"] == 200
params = json.loads(r.response["body"])
assert params["SCRIPT_NAME"] == script_name
assert params["PATH_INFO"] == path_info

def test_proxy_012_02(self, env):
"""An SSI include keeps the SCRIPT_NAME core gives "INCLUDED"
subrequests, the whole URI, escaped or not."""
r = env.curl_get(env.mkurl("http", "test1", "/fcgi_inc.shtml"))
assert r.response["status"] == 200
included = [json.loads(part) for part in
r.response["body"].decode().split("@@")[1::2]]
assert [(p["SERVER_PROTOCOL"], p["SCRIPT_NAME"], p["PATH_INFO"])
for p in included] == [
("INCLUDED", "/inc/a/b", "/a/b"),
("INCLUDED", "/inc/a b/c", "/a%20b/c"),
]
Loading