From 728cdd3532364f63de8319ace7246a1837d6ff5d Mon Sep 17 00:00:00 2001 From: Jiajie Chen Date: Sun, 29 Nov 2026 12:21:29 +0800 Subject: [PATCH 1/2] arg: cache host name addresses across port list A host name that resolves to both IPv6 and IPv4 is searched for every port in a comma-separated list. The fix for that in #416 re-resolved the name for each port because gethostbyname2() returns static storage that the IPv4 fallback overwrites. Copy the IPv6 and IPv4 address lists into private storage and reuse them for every port. This keeps the per-port family search while reducing the resolver calls from about 2N to 2 for N ports. The cache also avoids the stale n.a / NULL hostent path for names that resolve only to IPv6, and MAXNWAD is raised so a dual-stack name with 100 comma-separated ports still fits the address chain. --- lib/common.h | 7 ++- src/arg.c | 149 +++++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 144 insertions(+), 12 deletions(-) diff --git a/lib/common.h b/lib/common.h index 22c76f08..94edd7ae 100644 --- a/lib/common.h +++ b/lib/common.h @@ -356,7 +356,12 @@ extern int optind; # endif /* defined(HASIPv6) */ # define MAXDCPATH 4 /* paths in DCpath[] */ -# define MAXNWAD 100 /* maximum network addresses */ +/* + * A host name with a comma-separated port list needs at least one network + * address entry per port for each address family. Allow for the historical + * 100-port capacity when a name has one address per family. + */ +# define MAXNWAD 200 /* maximum network addresses */ # if !defined(MEMMOVE) # define MEMMOVE memmove diff --git a/src/arg.c b/src/arg.c index 426ddaad..0bbea787 100644 --- a/src/arg.c +++ b/src/arg.c @@ -56,6 +56,9 @@ static int enter_nwad(struct lsof_context *ctx, struct nwad *n, int sp, int ep, static struct hostent *lkup_hostnm(char *hn, struct nwad *n); static char *isIPv4addr(char *hn, unsigned char *a, int al); #if defined(HASIPv6) +static int clone_hostent(struct hostent *src, struct hostent *dst, + char **store); +static void set_nwad_address(struct nwad *n, struct hostent *he); static int nwad_has_explicit_family(struct lsof_context *ctx, int af); #endif /* defined(HASIPv6) */ @@ -1260,6 +1263,13 @@ int enter_network_address(struct lsof_context *ctx, /* context */ #if defined(HASIPv6) char *cp; int host_af = 0; + struct hostent he_v6; + struct hostent he_v4; + char *he_v6_store = (char *)NULL; + char *he_v4_store = (char *)NULL; + int have_v6 = 0; + int have_v4 = 0; + int checked_v4 = 0; #endif /* defined(HASIPv6) */ if (!na) { @@ -1352,6 +1362,12 @@ int enter_network_address(struct lsof_context *ctx, /* context */ "%s: no space for protocol name from: -i ", Pn); safestrprt(na, stderr, 1); nwad_exit: +#if defined(HASIPv6) + if (he_v6_store) + (void)free((FREE_P *)he_v6_store); + if (he_v4_store) + (void)free((FREE_P *)he_v4_store); +#endif /* defined(HASIPv6) */ if (n.proto) (void)free((FREE_P *)n.proto); if (hn) @@ -1492,6 +1508,25 @@ int enter_network_address(struct lsof_context *ctx, /* context */ safestrprt(na, stderr, 1); goto nwad_exit; } +#if defined(HASIPv6) + /* + * A host name can be followed by a comma-separated port list. + * gethostbyname2() returns storage that the next lookup + * overwrites, so keep a private copy of the IPv6 addresses + * for the later ports. + */ + if (!ft && (n.af == AF_INET6)) { + if (clone_hostent(he, &he_v6, &he_v6_store)) { + (void)fprintf(stderr, + "%s: no space for host addresses: -i ", + Pn); + safestrprt(na, stderr, 1); + goto nwad_exit; + } + have_v6 = 1; + he = &he_v6; + } +#endif /* defined(HASIPv6) */ } wa = p; } @@ -1640,11 +1675,15 @@ int enter_network_address(struct lsof_context *ctx, /* context */ nwad_enter: #if defined(HASIPv6) - /* Restore the first hostname family after the previous port's lookup. */ - if (hn && n.af != host_af) { + /* + * Reuse the cached host name addresses for every port. The IPv6 + * addresses were copied when the name was resolved; the IPv4 + * fallback is copied when it is first looked up. + */ + if (have_v6) { n.af = host_af; - if (!(he = lkup_hostnm(hn, &n))) - goto unacc_address; + he = &he_v6; + set_nwad_address(&n, he); } #endif /* defined(HASIPv6) */ @@ -1654,15 +1693,41 @@ int enter_network_address(struct lsof_context *ctx, /* context */ #if defined(HASIPv6) /* - * If IPv6 is enabled, a host name was specified, and the - * associated * address is for the AF_INET6 address family, - * try to get and address for the AF_INET family, too, unless - * IPv4 is prohibited. + * If a host name resolved to IPv6, also search the IPv4 family, + * unless the lookups are restricted to IPv6. The IPv4 hostent + * is copied on first use so that later ports don't have to + * repeat the lookup. */ - if (hn && (n.af == AF_INET6) && (ft != 6)) { - n.af = AF_INET; - if ((he = lkup_hostnm(hn, &n))) + if (have_v6 && (n.af == AF_INET6)) { + if (have_v4) { + n.af = AF_INET; + he = &he_v4; + set_nwad_address(&n, he); continue; + } + if (!checked_v4) { + /* + * Try the IPv4 lookup once. If the name has no IPv4 + * addresses, later ports don't retry it. + */ + n.af = AF_INET; + he = lkup_hostnm(hn, &n); + checked_v4 = 1; + if (he) { + if (clone_hostent(he, &he_v4, + &he_v4_store)) { + (void)fprintf( + stderr, + "%s: no space for host addresses: -i ", Pn); + safestrprt(na, stderr, 1); + goto nwad_exit; + } + have_v4 = 1; + he = &he_v4; + set_nwad_address(&n, he); + continue; + } + } } #endif /* defined(HASIPv6) */ @@ -1677,6 +1742,12 @@ int enter_network_address(struct lsof_context *ctx, /* context */ (void)free((FREE_P *)n.proto); if (hn) (void)free((FREE_P *)hn); +#if defined(HASIPv6) + if (he_v6_store) + (void)free((FREE_P *)he_v6_store); + if (he_v4_store) + (void)free((FREE_P *)he_v4_store); +#endif /* defined(HASIPv6) */ return (0); } @@ -2237,6 +2308,62 @@ static char *isIPv4addr(char *hn, /* host name */ return (hn); } +#if defined(HASIPv6) +/* + * set_nwad_address() - copy a hostent's first address into an nwad + * + * enter_nwad() uses the address already in the nwad for its first entry, so + * the cached hostent's first address must be restored before each use. + */ + +static void +set_nwad_address(struct nwad *n, /* network address destination */ + struct hostent *he) /* cached hostent */ +{ + zeromem((char *)n->a, sizeof(n->a)); + (void)memcpy((void *)n->a, (void *)he->h_addr_list[0], + (size_t)he->h_length); +} + +/* + * clone_hostent() - copy a hostent's address list into private storage + * + * gethostbyname2() returns a pointer to static storage that the next lookup + * overwrites. Save the addresses so a host name's family can be reused for + * every port in a comma-separated list. + */ + +static int +clone_hostent(struct hostent *src, /* hostent to copy */ + struct hostent *dst, /* destination hostent */ + char **store) /* returned malloc'd storage */ +{ + char *data, **list; + size_t alen, i, n; + if (!src || !src->h_addr_list || !src->h_addr_list[0]) + return (1); + for (n = 0; src->h_addr_list[n]; n++) + ; + alen = ((n + 1) * sizeof(char *)) + (n * (size_t)src->h_length); + if ((data = (char *)malloc(alen)) == NULL) + return (1); + list = (char **)data; + data += (n + 1) * sizeof(char *); + for (i = 0; i < n; i++) { + (void)memcpy(data + (i * (size_t)src->h_length), src->h_addr_list[i], + (size_t)src->h_length); + list[i] = data + (i * (size_t)src->h_length); + } + list[n] = (char *)NULL; + *dst = *src; + dst->h_name = (char *)NULL; + dst->h_aliases = (char **)NULL; + dst->h_addr_list = list; + *store = (char *)list; + return (0); +} +#endif /* defined(HASIPv6) */ + /* * lkup_hostnm() - look up host name */ From 91456027bd1e74a35bb275169063bcf1f61b9c29 Mon Sep 17 00:00:00 2001 From: Jiajie Chen Date: Sun, 29 Nov 2026 12:21:31 +0800 Subject: [PATCH 2/2] tests: split hostname port-family regression Move the port-list family regression out of case-23 into its own case-25. case-23 is reported as SKIP on CI when the configured host name has only one address, which hid the new test's PASS. The new case uses the loopback addresses returned by getaddrinfo() instead of hard-coded ones, reports failures with FAIL:/sys.exit(1) instead of an assert, and skips only if a dual-family localhost is unavailable. Make case-23 count addresses across families and fall back to localhost, so it runs on systems whose host name has a single address. --- Makefile.am | 1 + tests/case-23-multi-address-hostname.bash | 75 ++++++++------------ tests/case-25-hostname-port-families.bash | 86 +++++++++++++++++++++++ 3 files changed, 118 insertions(+), 44 deletions(-) create mode 100755 tests/case-25-hostname-port-families.bash diff --git a/Makefile.am b/Makefile.am index f512f204..8761ee76 100644 --- a/Makefile.am +++ b/Makefile.am @@ -141,6 +141,7 @@ DIALECT_NEUTRAL_TESTS = tests/case-00-hello.bash \ tests/case-22-empty-process-name.bash \ tests/case-23-multi-address-hostname.bash \ tests/case-24-dual-stack-socket.bash \ + tests/case-25-hostname-port-families.bash \ tests/case-30-json-output.bash \ tests/case-31-jsonl-output.bash TESTS = $(DIALECT_NEUTRAL_TESTS) diff --git a/tests/case-23-multi-address-hostname.bash b/tests/case-23-multi-address-hostname.bash index 2286e73a..25f35383 100755 --- a/tests/case-23-multi-address-hostname.bash +++ b/tests/case-23-multi-address-hostname.bash @@ -12,66 +12,53 @@ if ! command -v python3 >/dev/null 2>&1; then exit 77 fi -# Every port in a hostname filter must search both address families. -python3 - "$lsof" <<'PY' >> "$report" 2>&1 || exit 1 -import os -import socket -import subprocess -import sys - -try: - sockets = [] - for family, address in ((socket.AF_INET, "127.0.0.1"), - (socket.AF_INET6, "::1")): - if address not in {x[4][0] for x in socket.getaddrinfo( - "localhost", None, family, socket.SOCK_STREAM)}: - raise OSError(f"localhost does not resolve to {address}") - s = socket.socket(family, socket.SOCK_STREAM) - s.bind((address, 0)) - s.listen(1) - sockets.append(s) -except OSError as e: - print(f"SKIP: dual-family localhost unavailable: {e}") -else: - ports = [str(s.getsockname()[1]) for s in sockets] - expected = {str(s.fileno()) for s in sockets} - for order in (["0"] + ports, ports[::-1]): - result = subprocess.run( - [sys.argv[1], "-nP", "-a", "-p", str(os.getpid()), "-Ff", - "-iTCP@localhost:" + ",".join(order)], - capture_output=True, text=True, timeout=10) - found = {line[1:] for line in result.stdout.splitlines() - if line.startswith("f")} - assert result.returncode == 0 and found == expected, ( - order, result.returncode, found, expected, result.stderr) - print("PASS: hostname port lists search both families in either order") -PY - -host=$(hostname) -naddr=$(python3 - "$host" <<'PY' +count_addresses() { + python3 - "$1" <<'PY' import socket import sys host = sys.argv[1] -count = 0 +addresses = set() for family in (socket.AF_INET, socket.AF_INET6): try: infos = socket.getaddrinfo(host, None, family, socket.SOCK_STREAM) except OSError: continue - count = max(count, len({info[4][0] for info in infos})) -print(count) + for info in infos: + address = info[4][0] + if family == socket.AF_INET6: + try: + packed = socket.inet_pton(socket.AF_INET6, address) + except OSError: + continue + # Ignore v4-mapped IPv6 addresses; the IPv4 lookup counts them. + if packed[:12] == b"\0" * 10 + b"\xff\xff": + continue + addresses.add(address) +print(len(addresses)) PY -) +} + +host=$(hostname) +naddr=$(count_addresses "$host") +if [ "${naddr:-0}" -lt 2 ]; then + # Prefer localhost: most systems resolve it to one IPv4 and one IPv6 + # loopback address, which is enough to exercise the multiple-entry path + # without requiring additional privileges. + localhost_naddr=$(count_addresses localhost) + if [ "${localhost_naddr:-0}" -ge 2 ]; then + host=localhost + naddr=$localhost_naddr + fi +fi if [ "${naddr:-0}" -lt 2 ]; then - echo "SKIP: $host resolves to fewer than two addresses in one family" \ - >> "$report" + echo "SKIP: $host resolves to fewer than two addresses" >> "$report" exit 77 fi { - echo "host name: $host ($naddr addresses in one address family)" + echo "host name: $host ($naddr addresses)" $lsof -a -i@"$host" -p $$ >/dev/null 2>&1 status=$? case $status in diff --git a/tests/case-25-hostname-port-families.bash b/tests/case-25-hostname-port-families.bash new file mode 100755 index 00000000..c4e2095b --- /dev/null +++ b/tests/case-25-hostname-port-families.bash @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +# Regression test for host name filters with a port list. +# +# A host name can resolve to both IPv4 and IPv6 addresses. Every port in +# -i@host:port1,port2,... must search both address families. An IPv4 +# fallback for the first port must not leave the parser restricted to IPv4 +# for the later ports. +source tests/common.bash + +if ! command -v python3 >/dev/null 2>&1; then + echo "SKIP: python3 not available" >> "$report" + exit 77 +fi + +python3 - "$lsof" <<'PY' >> "$report" 2>&1 +import os +import socket +import subprocess +import sys + +lsof = sys.argv[1] + + +def fail(message): + print(f"FAIL: {message}") + sys.exit(1) + + +def loopback(family): + """Return a loopback sockaddr for localhost in family, or an error.""" + try: + infos = socket.getaddrinfo("localhost", 0, family, socket.SOCK_STREAM) + except OSError as e: + return None, str(e) + for fam, _, _, _, sockaddr in infos: + if fam != family: + continue + address = sockaddr[0] + if family == socket.AF_INET6: + try: + packed = socket.inet_pton(socket.AF_INET6, address) + except OSError: + continue + if packed[:12] == b"\0" * 10 + b"\xff\xff": + continue + return sockaddr, None + return None, "no usable loopback address" + + +sockets = [] +for family in (socket.AF_INET, socket.AF_INET6): + sockaddr, error = loopback(family) + if sockaddr is None: + print(f"SKIP: dual-family localhost unavailable: {error}") + sys.exit(77) + try: + sock = socket.socket(family, socket.SOCK_STREAM) + sock.bind(sockaddr) + sock.listen(1) + except OSError as e: + print(f"SKIP: can't listen on {sockaddr[0]}: {e}") + sys.exit(77) + sockets.append(sock) + +ports = [str(sock.getsockname()[1]) for sock in sockets] +expected = {str(sock.fileno()) for sock in sockets} + +# Port 0 matches nothing; putting it first forces the parser to switch to the +# IPv4 fallback before it processes the ports that matter. +for order in (["0"] + ports, ports[::-1]): + try: + result = subprocess.run( + [lsof, "-nP", "-a", "-p", str(os.getpid()), "-Ff", + "-iTCP@localhost:" + ",".join(order)], + capture_output=True, text=True, timeout=10) + except (OSError, subprocess.TimeoutExpired) as e: + fail(f"lsof {' '.join(order)}: {e}") + found = {line[1:] for line in result.stdout.splitlines() + if line.startswith("f")} + if result.returncode != 0 or found != expected: + fail(f"order={order} returncode={result.returncode} " + f"found={sorted(found)} expected={sorted(expected)} " + f"stderr={result.stderr.strip()}") + +print("PASS: hostname port lists search both families in either order") +PY