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/69804.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*) core: Fix ListenCoresBucketsRatio with IPv6: a wildcard "Listen"
lost IPv6 on the additional listener buckets, and a link-local
"Listen [fe80::...%iface]" made httpd fail to start.
PR 69804 [Arturo Bernal]
18 changes: 12 additions & 6 deletions server/listen.c
Original file line number Diff line number Diff line change
Expand Up @@ -866,8 +866,6 @@ AP_DECLARE(apr_status_t) ap_duplicate_listeners(apr_pool_t *p, server_rec *s,
lr = ap_listeners;
while (lr) {
ap_listen_rec *duplr;
char *hostname;
apr_port_t port;
apr_sockaddr_t *sa;
int sock_proto = 0;
#ifdef HAVE_SYSTEMD
Expand All @@ -885,13 +883,21 @@ AP_DECLARE(apr_status_t) ap_duplicate_listeners(apr_pool_t *p, server_rec *s,
duplr = apr_palloc(p, sizeof(ap_listen_rec));
duplr->slave = NULL;
duplr->protocol = apr_pstrdup(p, lr->protocol);
hostname = apr_pstrdup(p, lr->bind_addr->hostname);
port = lr->bind_addr->port;
stat = apr_sockaddr_info_get(&sa, hostname, APR_UNSPEC, port, 0, p);
#if APR_VERSION_AT_LEAST(1,6,0)
/* Copy the address the listener bound, rather than resolving
* it again, so that each duplicate binds exactly the same
* address (family, scope).
*/
stat = apr_sockaddr_info_copy(&sa, lr->bind_addr, p);
#else
stat = apr_sockaddr_info_get(&sa, lr->bind_addr->hostname,
lr->bind_addr->family,
lr->bind_addr->port, 0, p);
#endif
if (stat != APR_SUCCESS) {
ap_log_perror(APLOG_MARK, APLOG_CRIT, stat, p, APLOGNO(10397)
"failure looking up %s to duplicate "
"listening socket", hostname);
"listening socket", lr->bind_addr->hostname);
return stat;
}
duplr->bind_addr = sa;
Expand Down
172 changes: 172 additions & 0 deletions test/modules/core/test_016_listen_buckets_ipv6.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import os
import re
import socket
import subprocess
from collections import Counter

import pytest

from pyhttpd.conf import HttpdConf


def link_local_address():
"""An IPv6 link-local address of this host and its interface name, as
(address, interface, scope_id), or None. Read from the kernel and
checked by binding a socket to it."""
path = "/proc/net/if_inet6"
if not os.path.isfile(path):
return None
with open(path) as fd:
for line in fd:
hexaddr, ifindex, _plen, scope, _flags, ifname = line.split()
if scope != '20' or ifname == 'lo': # 0x20: link-local
continue
addr = socket.inet_ntop(socket.AF_INET6, bytes.fromhex(hexaddr))
try:
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
s.bind((addr, 0, 0, int(ifindex, 16)))
except OSError:
continue
return addr, ifname, int(ifindex, 16)
return None


def apr_compiled_version(env):
"""APR version httpd was compiled with, as a tuple, from httpd -V."""
out = subprocess.run([os.path.join(env.bin_dir, 'httpd'), '-V'],
capture_output=True, text=True).stdout
m = re.search(r'Compiled using:\s+APR (\d+)\.(\d+)', out)
return (int(m.group(1)), int(m.group(2))) if m else (0, 0)


def free_port(addr: str, scope_id: int) -> int:
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
s.bind((addr, 0, 0, scope_id))
return s.getsockname()[1]


def listening_count(port: int) -> int:
"""Number of IPv6 sockets in LISTEN state on *port*."""
count = 0
with open("/proc/net/tcp6") as fd:
next(fd) # header line
for line in fd:
fields = line.split()
local_port = int(fields[1].split(':')[1], 16)
if local_port == port and fields[3] == '0A': # TCP_LISTEN
count += 1
return count


def listening_families(port: int):
"""Address families of all sockets in LISTEN state on *port*, read
straight from the kernel instead of trusting what httpd logged."""
families = []
for family, path in [(socket.AF_INET, "/proc/net/tcp"),
(socket.AF_INET6, "/proc/net/tcp6")]:
if not os.path.isfile(path):
continue
with open(path) as fd:
next(fd) # header line
for line in fd:
fields = line.split()
local_addr, state = fields[1], fields[3]
local_port = int(local_addr.split(':')[1], 16)
if local_port == port and state == '0A': # TCP_LISTEN
families.append(family)
return families


class TestListenBucketsIPv6:
# ListenCoresBucketsRatio only kicks in with SO_REUSEPORT and more than
# one bucket worth of online cores; on anything else it logs a warning
# and keeps a single bucket, in which case there is nothing to check.
RE_BUCKETS = re.compile(r'.*AH02819: Using (?P<n>\d+) listeners bucket.*')

def test_core_016_01(self, env):
# Target 2-3 buckets regardless of how many cores this host has;
# a ratio of 1 would spawn one bucket (and child process) per core,
# needlessly heavy on a many-core CI runner.
cpu_count = os.cpu_count() or 1
ratio = max(1, cpu_count // 3)
conf = HttpdConf(env, extras={
'base': f"""
ListenCoresBucketsRatio {ratio}
""",
})
conf.install()

start_pos = env.httpd_error_log.current_pos()
assert env.apache_restart() == 0
m = None
if env.httpd_error_log.wait_for(self.RE_BUCKETS, start_pos, timeout=5):
with open(env.httpd_error_log.path) as fd:
fd.seek(start_pos)
for line in fd:
m = self.RE_BUCKETS.match(line)
if m:
break
if m is None or int(m.group('n')) <= 1:
pytest.skip("ListenCoresBucketsRatio did not create multiple "
"listener buckets on this host (no SO_REUSEPORT "
"or too few online cores)")
num_buckets = int(m.group('n'))

families = listening_families(env.http_port)
if socket.AF_INET6 not in families:
pytest.skip("no IPv6 support on this host")
# The "Listen <port>" directive has no address, so it resolves to
# one or more wildcard sockets (one per address family that
# open_listeners() keeps: on Linux with the default
# --enable-v4-mapped that is a single dual-stack IPv6 socket; a
# build configured --disable-v4-mapped would keep a separate IPv4
# socket too). Whichever families the *original* bucket ends up
# with, every other bucket must duplicate the same set: none of
# them may silently gain or lose a family relative to the others.
counts = Counter(families)
for family, count in counts.items():
assert count == num_buckets, (
f"{family!s} appears in {count} of the {num_buckets} "
f"listener buckets for port {env.http_port}, expected all "
f"of them to have it: {families}"
)

def _num_buckets(self, env, start_pos):
if env.httpd_error_log.wait_for(self.RE_BUCKETS, start_pos, timeout=5):
with open(env.httpd_error_log.path) as fd:
fd.seek(start_pos)
for line in fd:
m = self.RE_BUCKETS.match(line)
if m:
return int(m.group('n'))
return 0

# A link-local listener carries its interface as a scope; each
# duplicated bucket must bind the same scoped address, or the bind
# fails and httpd does not start.
def test_core_016_02(self, env):
# "Listen" only takes a scope ID when built against APR >= 1.7
if apr_compiled_version(env) < (1, 7):
pytest.skip("Listen scope IDs need APR 1.7 or later")
ll = link_local_address()
if ll is None:
pytest.skip("no usable IPv6 link-local address on this host")
addr, ifname, scope_id = ll
port = free_port(addr, scope_id)
cpu_count = os.cpu_count() or 1
ratio = max(1, cpu_count // 3)
conf = HttpdConf(env, extras={
'base': f"""
ListenCoresBucketsRatio {ratio}
Listen [{addr}%{ifname}]:{port}
""",
})
conf.install()

start_pos = env.httpd_error_log.current_pos()
assert env.apache_restart() == 0
num_buckets = self._num_buckets(env, start_pos)
if num_buckets <= 1:
pytest.skip("ListenCoresBucketsRatio did not create multiple "
"listener buckets on this host")
assert listening_count(port) == num_buckets
Loading