TCP peer address can be lost if the connection is reset before `uv_tcp_getpeername()`
TCP peer address can be lost if the connection is reset before uv_tcp_getpeername()
On Unix, libuv currently accepts TCP connections with a null peer-address destination, then obtains the peer address
through uv_tcp_getpeername(), which calls the operating system's getpeername() on the accepted socket. The address
that accept() / accept4() could have returned is not retained.
Those operations usually identify the same peer, but they can differ after a socket-state transition. On Linux, a
connection that was established and then reset before userspace accepted it can still be returned by accept(). The
address supplied directly by accept(..., &peer, ...) can be available even when a subsequent getpeername() on that
socket returns ENOTCONN. The kernel has explicitly distinguished those address lookups since Linux 2.3.43.
With libuv's current accept path, the address is never captured. A later query can therefore lose the identity of a
connection that was accepted. In Node.js this can produce an accepted socket whose remoteAddress / remotePort are
undefined, even when read in the application's connection callback.
Question
Given that accept() can return the peer identity of a connection that a later getpeername() can no longer recover,
should libuv retain that identity at accept time?
In particular, I am interested in whether the current lifetime semantics are intentional and whether preserving the accept-time address together with the accepted connection would be considered a reasonable direction.
The attached POC is intended as an existence/correctness demonstration rather than a proposed final implementation.
Reproducer
I have a small Node.js server and Python client that reproduce this.
The client:
- creates a normal TCP socket,
- completes a normal
connect(), - sets
SO_LINGERto{1, 0}, - immediately closes the socket.
On Linux this produces an abortive close / RST.
For the correctness test I built Node.js v26.10.0, which bundles libuv v1.52.1, both upstream and with the proof-of-concept libuv change applied.
Both builds report the same Node.js and libuv versions; the relevant difference is the local libuv patch.
A 100,000-connection run produced:
Node.js v26.10.0 / libuv v1.52.1, upstream:
Total: 100000
Address: 3268
Undefined: 96732
Node.js v26.10.0 / libuv v1.52.1, patched:
Total: 100000
Address: 100000
Undefined: 0With upstream libuv, the peer address was unavailable in 96,732 of 100,000 accepted connections in this run.
With the proof-of-concept change, the peer address was available in all 100,000 connections.
The exact failure percentage is timing-dependent and is not the important result. What the test demonstrates is that the TCP connection completed normally and was accepted, yet peer identity could subsequently become unrecoverable with the upstream behavior. Preserving the accept-time address eliminated that observed failure mode in this test.
Proof of concept
The proof of concept and reproducer are here:
https://github.com/bobnil/libuv-accept-peer-address-poc
The patch changes the Unix accept path so that the sockaddr returned by accept() / accept4() is preserved together
with the pending accepted fd and made available to the accepted TCP handle.
The POC is intended to demonstrate only that:
- the peer address is available at accept time,
- libuv can retain it,
- retaining it eliminates the observed RST failure mode.
It is not intended as a proposal for the production implementation.
In particular, where or how the address should be stored, and the associated internal memory/layout/API/ABI considerations, are deliberately left open.
Why accept-time information differs from a later getpeername()
The sockaddr returned by accept() describes the peer of the connection being accepted. A later getpeername(fd) asks
about the peer of the socket at query time. These are normally equivalent, but the Linux kernel has a concrete
counterexample:
established TCP child → RST before userspace accept → TCP_CLOSE
accept(..., &peer, ...) → stored peer address returned
getpeername(accepted_fd) → ENOTCONNLinux 2.3.15 explicitly retained an established-then-RST child for a subsequent accept(). Linux 2.3.43 then changed
the address retrieval in accept() to getname(..., peer=2), while ordinary getpeername() uses peer=1. In IPv4,
the state check that rejects TCP_CLOSE applies to peer=1 and not peer=2; the same distinction was introduced for
IPv6. This is an explicit semantic distinction in the kernel, rather than merely a timing inference from the reproducer.
The relevant source is in the 2.3.15 and
2.3.43 patches (net/ipv4/tcp_ipv4.c,
net/ipv4/af_inet.c, net/socket.c, and net/ipv6/af_inet6.c).
When libuv discards the accept-time result, it cannot recover that identity if the later live query fails. This information-lifetime difference is the correctness issue here.
Historical context
I looked into the history because there are old performance-related changes in this area. The history seems to show several individually reasonable decisions whose combination produced the current edge case.
A fuller account of the BSD, Linux, Node.js, and libuv history, with source references, is available in Historical context and source references.
Original BSD socket interface
The ability to obtain the peer address from accept() is part of the original sockets API. Berkeley's
1983 4.2bsd Interprocess Communication Primer
demonstrates a server supplying a peer-address buffer directly to accept(). A
historical accept(2) manual describes
the address as a result parameter containing the connecting entity's address. getpeername() was a separate operation
for a connected socket, not a required second step after accept().
BSD-derived FreeBSD kernel code makes
the lifetime distinction visible too: its getpeername() path checks connected state and can return ENOTCONN. This
establishes the historical API baseline. The Linux patches above provide the particularly explicit implementation of the
reset-before-accept case relevant to this reproducer.
Original Node.js behavior
Before the libuv backend, Node.js retained the peer information returned by its accept operation and stored the remote address and port on the newly created socket before emitting the connection event.
So the effective lifetime was:
accept
├─ accepted connection
└─ peer identity
↓
Socket
↓
connection callbackOriginal libuv abstraction
The behavior changed with the original libuv backend.
This is already visible in the libuv code shipped with Node.js v0.5.0 in July 2011.
On Unix, the accept path already received a peer sockaddr, but retained only the accepted file descriptor until
uv_accept() initialized the client handle. Accept-time endpoint information was therefore not part of the state
propagated to that handle.
This behavior predates uv_tcp_getpeername().
Contemporary libuv API material also makes the separation explicit: the connection callback signals that an accepted
connection is available, and uv_accept(server, client) subsequently initializes the client handle from that
already-accepted connection.
The Windows backend had a similar abstraction around AcceptEx(): the accepted socket was propagated to the client
handle, while accept-time endpoint information was not made persistent peer identity on that handle.
This appears consistent with libuv's original goal of providing a common Unix/Windows I/O abstraction. I have not found a historical comment explaining the specific decision not to propagate the accept-time peer address, so I do not want to speculate about the original motivation.
uv_tcp_getpeername()
uv_tcp_getpeername() was added to libuv in September 2011 (libuv/libuv@12b01e9) as a separate query on the resulting
socket.
The following day, Node.js began using that API to correctly populate remoteAddress and remotePort.
At that point the effective model was approximately:
accept
↓
getpeername
↓
save peer identity
↓
connection callbackThere was already a theoretical interval between accept() and getpeername(), but it was small.
Making the lookup lazy
Shortly afterward, Node.js commit nodejs/node-v0.x-archive@1bb820a, net: remove unconditional getpeername() call,
removed that unconditional lookup.
The commit reported an approximately 1% improvement in the http_simple benchmark.
That optimization makes sense in context: the benchmark did not use the peer address, so performing a separate
getpeername() for every accepted TCP connection was unnecessary work.
The change made peer lookup lazy, however, so the interval became:
accept
↓
connection callback
↓
arbitrary application / event-loop activity
↓
socket state may change
↓
first remoteAddress access
↓
getpeername()This makes the underlying lifetime difference much easier to observe.
2012: stop requesting the unused sockaddr
In May 2012, libuv commit libuv/libuv@752ac30, unix: don't pass sockaddr to accept(), changed the Unix accept path
so that accept() no longer received a sockaddr destination.
The commit message says it:
“Shaves a few nanoseconds off the accept() syscall.”
Context is important here.
Technically, this is correct. If the returned address is not going to be used, avoiding the kernel work required to populate/copy the sockaddr to userspace can save some time.
So, viewed in its historical context, this was a reasonable cleanup/optimization: libuv stopped retrieving information that its existing abstraction was already discarding.
The change did not introduce the loss of accept-time peer identity. That behavior already existed. It merely stopped paying the cost of obtaining data that was not being retained.
This distinction is also important for the performance question here.
The 2011 Node.js optimization removed a separate unconditional getpeername() syscall from every accepted
connection.
Retaining the sockaddr already returned as part of accept() would not restore that extra syscall.
Previous reports
This root cause appears to have been identified previously in Node.js.
In nodejs/node-v0.x-archive#7566 in 2014, the report noted that socket information could be returned by accept(),
but that libuv ignored it, and suggested retaining that information together with the accepted connection as the
reliable solution.
The issue therefore appears to describe essentially the same underlying race.
The symptom was reported again in nodejs/node#23858 in 2018. That case is particularly relevant because the remote
properties were read directly from the server's connection handler, showing that this is not limited to applications
trying to inspect a socket long after it has closed.
Node.js later changed its caching behavior so that peer information that had already been retrieved could remain available after the socket closed.
That solves:
getpeername succeeds
↓
peer identity cached
↓
socket closes
↓
remoteAddress still availablebut not:
socket reset/destroyed
↓
first peer lookup has not happened yet
↓
no cached peer identity
↓
information unavailableThat distinction appeared again in nodejs/node#48061 in 2023.
The resulting Node.js change documented that the remote properties can be undefined after destruction rather than
changing the underlying libuv accept behavior.
Performance experiment
I separately benchmarked the end-to-end connection-throughput effect of always retrieving and preserving the sockaddr at accept time.
This is intentionally separate from the Node.js correctness test above.
The performance benchmark uses standalone libuv v1.53.0, comparing:
upstream libuv v1.53.0against:
the same libuv v1.53.0 revision
+ the proof-of-concept patchThe methodology, results, and reproduction commands are collected here:
https://github.com/bobnil/libuv-accept-peer-address-poc/blob/main/BENCHMARK.md
The benchmark server:
- accepts the connection using
uv_accept(), - counts it,
- immediately closes the accepted handle,
- never queries the peer address.
This deliberately gives upstream the best possible case:
upstream:
accept without sockaddr
no later getpeername()
patched:
accept with sockaddr
preserve peer address
address is never usedSo the patched build pays the accept-time retrieval/preservation cost on every connection, while the upstream build never pays for peer lookup at all.
The tests include same-machine loopback and two-machine network runs, ranging from 500,000 to 50 million connections per run.
Across the datasets, the direction of the measured difference changes. Some runs favor upstream and some favor the patched build, while run-to-run variation is larger than the observed difference.
I therefore could not identify a reproducible connection-throughput regression from retrieving and preserving the accept-time sockaddr in this Linux environment.
I do not interpret that as evidence that the operation has exactly zero cost, nor as evidence that every operating system, kernel, CPU, or workload will behave identically.
It only shows that I was unable to measure a stable end-to-end throughput regression with this benchmark.
Why is this important for me?
I encounter this several times a day in a Node.js application that uses the client's address for an abuse filter. In some cases, remoteAddress is already unavailable in the server's connection callback, so I cannot add that client's address to the filter. That practical failure is what prompted this report.
Source: libuv/libuv