Close listening socket on fatal accept() errors to prevent busy loop

If a TCP listening socket is externally destroyed (e.g., via ss -K,
or a process using NETLINK_SOCK_DIAG/SOCK_DESTROY), accept()
permanently returns -1 with errno == EINVAL because the socket is
no longer in TCP_LISTEN state.  Since poll() keeps reporting the
stale fd as readable, the main loop spins calling
do_tcp_connection() -> accept() indefinitely, consuming 100% CPU.

Distinguish transient errors (EAGAIN, ECONNABORTED, EMFILE, ENFILE,
ENOMEM, ENOBUFS) from fatal ones.  On transient errors just return
and retry on the next poll cycle.  On fatal errors close the tcpfd
and mark it -1 so poll() no longer selects it.

In --bind-dynamic mode the listener will be automatically rebuilt
on the next address change event via newaddress().

Signed-off-by: Yuefu Zhou <yuefu16.zhou@gmail.com>
This commit is contained in:
Yuefu Zhou authored and Simon Kelley committed 2026-09-04 22:00:52 +01:00
1 parent ad9208358e
commit a9880c595f
1 file changed
+14 -1
+14 -1
View File
@@ -2027,7 +2027,20 @@ static void do_tcp_connection(struct listener *listener, time_t now, int slot)
while ((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR); while ((confd = accept(listener->tcpfd, NULL, NULL)) == -1 && errno == EINTR);
if (confd == -1) if (confd == -1)
return; {
/* Transient errors: just return and retry on next poll cycle. */
if (errno == EAGAIN || errno == ECONNABORTED ||
errno == EMFILE || errno == ENFILE ||
errno == ENOMEM || errno == ENOBUFS)
return;
/* Fatal error (EINVAL, EBADF, etc): socket is permanently broken.
Close it so poll() no longer selects it. In --bind-dynamic mode
the listener will be rebuilt on the next address change event. */
close(listener->tcpfd);
listener->tcpfd = -1;
return;
}
if (getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) == -1) if (getsockname(confd, (struct sockaddr *)&tcp_addr, &tcp_len) == -1)
{ {