Skip to content

Commit 7c35b7d

Browse files
wfurtCopilot
andauthored
Guard against empty remote address on macOS accept (dotnet#131869)
Fixes dotnet#121848 ## Problem On macOS, when a peer connects to an `AF_INET6` listening socket and immediately resets the connection (`SO_LINGER=0`), `accept(2)` returns a valid file descriptor but leaves the remote sockaddr buffer untouched and reports `addrlen=0`. This kernel behavior was measured with a plain C repro in the [issue comment](dotnet#121848 (comment)) and does not depend on dual-mode or `IPV6_V6ONLY`. The 2024 fix (dotnet#108616) guarded the `EndPoint.Create` call inside `FinishOperationAccept` on the Unix path, but the shared `FinishOperationSyncSuccess` in [`SocketAsyncEventArgs.cs`](https://github.com/dotnet/runtime/blob/main/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs#L1016) calls `Create` a second time on the same zero-sized `SocketAddress` and throws `ArgumentException`. For Kestrel this kills the accept loop permanently while the process stays alive and the port stays bound. --------- Co-authored-by: Copilot <[email protected]>
1 parent ef97877 commit 7c35b7d

3 files changed

Lines changed: 61 additions & 4 deletions

File tree

‎src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1089,8 +1089,10 @@ public Socket Accept()
10891089

10901090
Debug.Assert(!acceptedSocketHandle.IsInvalid);
10911091

1092-
Socket socket = CreateAcceptSocket(acceptedSocketHandle, _rightEndPoint.Create(socketAddress));
1093-
if (NetEventSource.Log.IsEnabled()) NetEventSource.Accepted(socket, socket.RemoteEndPoint!, socket.LocalEndPoint);
1092+
// macOS can return accept() success with an empty remote sockaddr when the peer reset before accept.
1093+
EndPoint? remoteEndPoint = socketAddress.Size > 0 ? _rightEndPoint.Create(socketAddress) : null;
1094+
Socket socket = CreateAcceptSocket(acceptedSocketHandle, remoteEndPoint);
1095+
if (NetEventSource.Log.IsEnabled()) NetEventSource.Accepted(socket, remoteEndPoint, socket.LocalEndPoint);
10941096
return socket;
10951097
}
10961098

‎src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1013,13 +1013,17 @@ internal void FinishOperationSyncSuccess(int bytesTransferred, SocketFlags flags
10131013

10141014
if (socketError == SocketError.Success)
10151015
{
1016-
_acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket!, _currentSocket._rightEndPoint!.Create(remoteSocketAddress));
1016+
// macOS can return accept() success with an empty remote sockaddr when the peer reset before accept.
1017+
EndPoint? remoteEndPoint = remoteSocketAddress.Size > 0
1018+
? _currentSocket._rightEndPoint!.Create(remoteSocketAddress)
1019+
: null;
1020+
_acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket!, remoteEndPoint);
10171021

10181022
if (NetEventSource.Log.IsEnabled())
10191023
{
10201024
try
10211025
{
1022-
NetEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
1026+
NetEventSource.Accepted(_acceptSocket, remoteEndPoint, _acceptSocket.LocalEndPoint);
10231027
}
10241028
catch (ObjectDisposedException) { }
10251029
}

‎src/libraries/System.Net.Sockets/tests/FunctionalTests/Accept.cs‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,4 +493,55 @@ public sealed class AcceptEap : Accept<SocketHelperEap>
493493
{
494494
public AcceptEap(ITestOutputHelper output) : base(output) {}
495495
}
496+
497+
public sealed class AcceptDualStackResetTests
498+
{
499+
[ConditionalTheory(typeof(Socket), nameof(Socket.OSSupportsIPv6))]
500+
[SkipOnPlatform(TestPlatforms.Wasi | TestPlatforms.OpenBSD, "These platforms don't support dual-mode sockets")]
501+
[InlineData(false)]
502+
[InlineData(true)]
503+
public async Task Accept_DualStackListener_PeerImmediatelyResets_ListenerStaysHealthy(bool useAsync)
504+
{
505+
for (int i = 0; i < 200; i++)
506+
{
507+
using Socket listener = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
508+
listener.DualMode = true;
509+
listener.Bind(new IPEndPoint(IPAddress.IPv6Any, 0));
510+
int port = ((IPEndPoint)listener.LocalEndPoint!).Port;
511+
listener.Listen(2);
512+
513+
using Socket ipv6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
514+
using Socket ipv4 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
515+
516+
await ipv4.ConnectAsync(IPAddress.Loopback, port).WaitAsync(TimeSpan.FromSeconds(5));
517+
ipv4.LingerState = new LingerOption(true, 0);
518+
ipv4.Close();
519+
520+
await ipv6.ConnectAsync(IPAddress.IPv6Loopback, port).WaitAsync(TimeSpan.FromSeconds(5));
521+
byte[] message = [42];
522+
Assert.Equal(message.Length, ipv6.Send(message));
523+
524+
bool receivedMessage = false;
525+
for (int acceptCount = 0; acceptCount < 2 && !receivedMessage; acceptCount++)
526+
{
527+
using Socket accepted = useAsync
528+
? await listener.AcceptAsync().WaitAsync(TimeSpan.FromSeconds(5))
529+
: listener.Accept();
530+
531+
try
532+
{
533+
byte[] received = new byte[message.Length];
534+
int receivedCount = await accepted.ReceiveAsync(received).WaitAsync(TimeSpan.FromSeconds(5));
535+
receivedMessage = receivedCount == message.Length && received.AsSpan().SequenceEqual(message);
536+
}
537+
catch (SocketException)
538+
{
539+
// Some platforms surface the reset connection from accept(), while others discard it.
540+
}
541+
}
542+
543+
Assert.True(receivedMessage);
544+
}
545+
}
546+
}
496547
}

0 commit comments

Comments
 (0)