Imported Upstream version 5.8.0.22

Former-commit-id: df344e34b07851d296efb3e6604c8db42b6f7aa3
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2017-10-19 20:04:20 +00:00
parent 5f4a27cc8a
commit 7d05485754
5020 changed files with 114082 additions and 186061 deletions

View File

@ -5,7 +5,6 @@
<AssemblyName>System.Net.Sockets</AssemblyName>
<ProjectGuid>{43311AFB-D7C4-4E5A-B1DE-855407F90D1B}</ProjectGuid>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DefineConstants Condition="'$(TargetGroup)' == 'uap'">$(DefineConstants);uap</DefineConstants>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
<OmitResources Condition="'$(TargetGroup)' == 'netfx'">true</OmitResources>
</PropertyGroup>
@ -150,6 +149,9 @@
<Compile Include="$(CommonPath)\System\Net\SafeCloseSocket.Windows.cs">
<Link>Common\System\Net\SafeCloseSocket.Windows.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\ContextAwareResult.Windows.cs">
<Link>Common\System\Net\ContextAwareResult.Windows.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\SocketAddressPal.Windows.cs">
<Link>Common\System\Net\SocketAddressPal.Windows.cs</Link>
</Compile>
@ -247,28 +249,13 @@
<Compile Include="$(CommonPath)\Interop\Windows\Winsock\WSABuffer.cs">
<Link>Interop\Windows\Winsock\WSABuffer.cs</Link>
</Compile>
</ItemGroup>
<!-- Windows : Win32 only -->
<ItemGroup Condition="'$(TargetsWindows)' == 'true' AND '$(TargetGroup)' != 'uap' AND '$(TargetGroup)' != 'netfx'">
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.SetFileCompletionNotificationModes.cs">
<Link>Interop\Windows\kernel32\Interop.SetFileCompletionNotificationModes.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\ContextAwareResult.Windows.cs">
<Link>Common\System\Net\ContextAwareResult.Windows.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\CompletionPortHelper.Windows.cs">
<Link>Common\System\Net\CompletionPortHelper.Windows.cs</Link>
</Compile>
</ItemGroup>
<!-- Windows : Win32 + WinRT -->
<ItemGroup Condition="'$(TargetsWindows)' == 'true' AND '$(TargetGroup)' == 'uap'">
<Compile Include="$(CommonPath)\System\Net\ContextAwareResult.Uap.cs">
<Link>Common\System\Net\ContextAwareResult.Uap.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\CompletionPortHelper.Uap.cs">
<Link>Common\System\Net\CompletionPortHelper.Uap.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup Condition=" '$(TargetsUnix)' == 'true' ">
<Compile Include="System\Net\Sockets\AcceptOverlappedAsyncResult.Unix.cs" />
<Compile Include="System\Net\Sockets\BaseOverlappedAsyncResult.Unix.cs" />

View File

@ -25,13 +25,10 @@ namespace System.Net.Sockets
// Internal buffers for WSARecvMsg
private byte[] _wsaMessageBuffer;
private GCHandle _wsaMessageBufferGCHandle;
private IntPtr _ptrWSAMessageBuffer;
private byte[] _controlBuffer;
private GCHandle _controlBufferGCHandle;
private IntPtr _ptrControlBuffer;
private WSABuffer[] _wsaRecvMsgWSABufferArray;
private GCHandle _wsaRecvMsgWSABufferArrayGCHandle;
private IntPtr _ptrWSARecvMsgWSABufferArray;
// Internal buffer for AcceptEx when Buffer not supplied.
private IntPtr _ptrAcceptBuffer;
@ -39,8 +36,6 @@ namespace System.Net.Sockets
// Internal SocketAddress buffer
private GCHandle _socketAddressGCHandle;
private Internals.SocketAddress _pinnedSocketAddress;
private IntPtr _ptrSocketAddressBuffer;
private IntPtr _ptrSocketAddressBufferSize;
// SendPacketsElements property variables.
private SendPacketsElement[] _sendPacketsElementsInternal;
@ -51,7 +46,6 @@ namespace System.Net.Sockets
// Internal variables for SendPackets
private FileStream[] _sendPacketsFileStreams;
private SafeHandle[] _sendPacketsFileHandles;
private IntPtr _ptrSendPacketsDescriptor;
// Overlapped object related variables.
private PreAllocatedOverlapped _preAllocatedOverlapped;
@ -228,7 +222,7 @@ namespace System.Net.Sockets
bool success = socket.ConnectEx(
handle,
_ptrSocketAddressBuffer,
PtrSocketAddressBuffer,
_socketAddress.Size,
_ptrSingleBuffer,
Count,
@ -370,8 +364,8 @@ namespace System.Net.Sockets
1,
out bytesTransferred,
ref flags,
_ptrSocketAddressBuffer,
_ptrSocketAddressBufferSize,
PtrSocketAddressBuffer,
PtrSocketAddressBufferSize,
overlapped,
IntPtr.Zero);
}
@ -383,8 +377,8 @@ namespace System.Net.Sockets
_bufferListInternal.Count,
out bytesTransferred,
ref flags,
_ptrSocketAddressBuffer,
_ptrSocketAddressBufferSize,
PtrSocketAddressBuffer,
PtrSocketAddressBufferSize,
overlapped,
IntPtr.Zero);
}
@ -409,12 +403,18 @@ namespace System.Net.Sockets
// WSAMsg also contains a single WSABuffer describing a control buffer.
PinSocketAddressBuffer();
// Create and pin a WSAMessageBuffer if none already.
// Create a WSAMessageBuffer if none exists yet.
if (_wsaMessageBuffer == null)
{
Debug.Assert(!_wsaMessageBufferGCHandle.IsAllocated);
_wsaMessageBuffer = new byte[sizeof(Interop.Winsock.WSAMsg)];
}
// And ensure the WSAMessageBuffer is appropriately pinned.
Debug.Assert(!_wsaMessageBufferGCHandle.IsAllocated || _wsaMessageBufferGCHandle.Target == _wsaMessageBuffer);
if (!_wsaMessageBufferGCHandle.IsAllocated)
{
_wsaMessageBufferGCHandle = GCHandle.Alloc(_wsaMessageBuffer, GCHandleType.Pinned);
_ptrWSAMessageBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);
}
// Create and pin an appropriately sized control buffer if none already
@ -438,13 +438,10 @@ namespace System.Net.Sockets
}
_controlBuffer = new byte[sizeof(Interop.Winsock.ControlDataIPv6)];
}
if (!_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle = GCHandle.Alloc(_controlBuffer, GCHandleType.Pinned);
_ptrControlBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_controlBuffer, 0);
}
// If single buffer we need a pinned 1 element WSABuffer.
// If single buffer we need a single element WSABuffer.
WSABuffer[] wsaRecvMsgWSABufferArray;
uint wsaRecvMsgWSABufferCount;
if (_buffer != null)
{
if (_wsaRecvMsgWSABufferArray == null)
@ -453,41 +450,69 @@ namespace System.Net.Sockets
}
_wsaRecvMsgWSABufferArray[0].Pointer = _ptrSingleBuffer;
_wsaRecvMsgWSABufferArray[0].Length = _count;
_wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaRecvMsgWSABufferArray, GCHandleType.Pinned);
_ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaRecvMsgWSABufferArray, 0);
wsaRecvMsgWSABufferArray = _wsaRecvMsgWSABufferArray;
wsaRecvMsgWSABufferCount = 1;
}
else
{
// Just pin the multi-buffer WSABuffer.
_wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaBufferArray, GCHandleType.Pinned);
_ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaBufferArray, 0);
// Use the multi-buffer WSABuffer.
wsaRecvMsgWSABufferArray = _wsaBufferArray;
wsaRecvMsgWSABufferCount = (uint)_bufferListInternal.Count;
}
// Ensure the array is pinned.
Debug.Assert(!_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated || _wsaRecvMsgWSABufferArrayGCHandle.Target == wsaRecvMsgWSABufferArray);
if (!_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated)
{
_wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(wsaRecvMsgWSABufferArray, GCHandleType.Pinned);
}
// Fill in WSAMessageBuffer.
unsafe
{
Interop.Winsock.WSAMsg* pMessage = (Interop.Winsock.WSAMsg*)_ptrWSAMessageBuffer; ;
pMessage->socketAddress = _ptrSocketAddressBuffer;
Interop.Winsock.WSAMsg* pMessage = (Interop.Winsock.WSAMsg*)PtrWSAMessageBuffer;
pMessage->socketAddress = PtrSocketAddressBuffer;
pMessage->addressLength = (uint)_socketAddress.Size;
pMessage->buffers = _ptrWSARecvMsgWSABufferArray;
if (_buffer != null)
fixed (void* ptrWSARecvMsgWSABufferArray = &wsaRecvMsgWSABufferArray[0])
{
pMessage->count = (uint)1;
}
else
{
pMessage->count = (uint)_bufferListInternal.Count;
pMessage->buffers = (IntPtr)ptrWSARecvMsgWSABufferArray;
}
pMessage->count = wsaRecvMsgWSABufferCount;
if (_controlBuffer != null)
{
pMessage->controlBuffer.Pointer = _ptrControlBuffer;
Debug.Assert(_controlBuffer.Length > 0);
Debug.Assert(!_controlBufferGCHandle.IsAllocated || _controlBufferGCHandle.Target == _controlBuffer);
if (!_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle = GCHandle.Alloc(_controlBuffer, GCHandleType.Pinned);
}
fixed (void* ptrControlBuffer = &_controlBuffer[0])
{
pMessage->controlBuffer.Pointer = (IntPtr)ptrControlBuffer;
}
pMessage->controlBuffer.Length = _controlBuffer.Length;
}
pMessage->flags = _socketFlags;
}
}
private unsafe IntPtr PtrWSAMessageBuffer
{
get
{
Debug.Assert(_wsaMessageBuffer != null);
Debug.Assert(_wsaMessageBuffer.Length == sizeof(Interop.Winsock.WSAMsg));
Debug.Assert(_wsaMessageBufferGCHandle.IsAllocated);
Debug.Assert(_wsaMessageBufferGCHandle.Target == _wsaMessageBuffer);
fixed (void* ptrWSAMessageBuffer = &_wsaMessageBuffer[0])
{
return (IntPtr)ptrWSAMessageBuffer;
}
}
}
internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeCloseSocket handle)
{
SocketError socketError = SocketError.Success;
@ -498,7 +523,7 @@ namespace System.Net.Sockets
socketError = socket.WSARecvMsg(
handle,
_ptrWSAMessageBuffer,
PtrWSAMessageBuffer,
out bytesTransferred,
overlapped,
IntPtr.Zero);
@ -663,13 +688,24 @@ namespace System.Net.Sockets
internal unsafe SocketError DoOperationSendPackets(Socket socket, SafeCloseSocket handle)
{
Debug.Assert(_sendPacketsDescriptor != null);
Debug.Assert(_sendPacketsDescriptor.Length > 0);
Debug.Assert(_multipleBufferGCHandles != null);
Debug.Assert(_multipleBufferGCHandles[0].IsAllocated);
Debug.Assert(_multipleBufferGCHandles[0].Target == _sendPacketsDescriptor);
IntPtr ptrSendPacketsDescriptor;
fixed (void* p = &_sendPacketsDescriptor[0])
{
ptrSendPacketsDescriptor = (IntPtr)p;
}
SocketError socketError = SocketError.Success;
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
bool result = socket.TransmitPackets(
handle,
_ptrSendPacketsDescriptor,
ptrSendPacketsDescriptor,
_sendPacketsDescriptor.Length,
_sendPacketsSendSize,
overlapped,
@ -721,7 +757,7 @@ namespace System.Net.Sockets
1,
out bytesTransferred,
_socketFlags,
_ptrSocketAddressBuffer,
PtrSocketAddressBuffer,
_socketAddress.Size,
overlapped,
IntPtr.Zero);
@ -734,7 +770,7 @@ namespace System.Net.Sockets
_bufferListInternal.Count,
out bytesTransferred,
_socketFlags,
_ptrSocketAddressBuffer,
PtrSocketAddressBuffer,
_socketAddress.Size,
overlapped,
IntPtr.Zero);
@ -865,11 +901,27 @@ namespace System.Net.Sockets
// Pin down the new one.
_socketAddressGCHandle = GCHandle.Alloc(_socketAddress.Buffer, GCHandleType.Pinned);
_socketAddress.CopyAddressSizeIntoBuffer();
_ptrSocketAddressBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, 0);
_ptrSocketAddressBufferSize = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, _socketAddress.GetAddressSizeOffset());
_pinnedSocketAddress = _socketAddress;
}
private unsafe IntPtr PtrSocketAddressBuffer
{
get
{
Debug.Assert(_pinnedSocketAddress != null);
Debug.Assert(_pinnedSocketAddress.Buffer != null);
Debug.Assert(_pinnedSocketAddress.Buffer.Length > 0);
Debug.Assert(_socketAddressGCHandle.IsAllocated);
Debug.Assert(_socketAddressGCHandle.Target == _pinnedSocketAddress.Buffer);
fixed (void* ptrSocketAddressBuffer = &_pinnedSocketAddress.Buffer[0])
{
return (IntPtr)ptrSocketAddressBuffer;
}
}
}
private IntPtr PtrSocketAddressBufferSize => PtrSocketAddressBuffer + _socketAddress.GetAddressSizeOffset();
// Cleans up any existing Overlapped object and related state variables.
private void FreeOverlapped()
{
@ -917,19 +969,16 @@ namespace System.Net.Sockets
if (_wsaMessageBufferGCHandle.IsAllocated)
{
_wsaMessageBufferGCHandle.Free();
_ptrWSAMessageBuffer = IntPtr.Zero;
}
if (_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated)
{
_wsaRecvMsgWSABufferArrayGCHandle.Free();
_ptrWSARecvMsgWSABufferArray = IntPtr.Zero;
}
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
_ptrControlBuffer = IntPtr.Zero;
}
}
@ -1061,9 +1110,6 @@ namespace System.Net.Sockets
}
}
// Get pointer to native descriptor.
_ptrSendPacketsDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(_sendPacketsDescriptor, 0);
// Fill in native descriptor.
int descriptorIndex = 0;
int fileIndex = 0;
@ -1223,7 +1269,7 @@ namespace System.Net.Sockets
private unsafe int GetSocketAddressSize()
{
return *(int*)_ptrSocketAddressBufferSize;
return *(int*)PtrSocketAddressBufferSize;
}
private unsafe void FinishOperationReceiveMessageFrom()

View File

@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Net.Sockets
@ -135,7 +136,7 @@ namespace System.Net.Sockets
if (_buffer != null)
{
// Can't have both set
throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, "Buffer"));
throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, nameof(Buffer)));
}
// Copy the user-provided list into our internal buffer list,
@ -304,7 +305,7 @@ namespace System.Net.Sockets
// Can't have both Buffer and BufferList.
if (_bufferList != null)
{
throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, "BufferList"));
throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, nameof(BufferList)));
}
// Offset and count can't be negative and the
@ -418,14 +419,23 @@ namespace System.Net.Sockets
private void StartConfiguring()
{
int status = Interlocked.CompareExchange(ref _operating, Configuring, Free);
if (status == InProgress || status == Configuring)
if (status != Free)
{
throw new InvalidOperationException(SR.net_socketopinprogress);
ThrowForNonFreeStatus(status);
}
else if (status == Disposed)
}
private void ThrowForNonFreeStatus(int status)
{
Debug.Assert(status == InProgress || status == Configuring || status == Disposed, $"Unexpected status: {status}");
if (status == Disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
else
{
throw new InvalidOperationException(SR.net_socketopinprogress);
}
}
// Prepares for a native async socket call.
@ -433,17 +443,10 @@ namespace System.Net.Sockets
internal void StartOperationCommon(Socket socket)
{
// Change status to "in-use".
if (Interlocked.CompareExchange(ref _operating, InProgress, Free) != Free)
int status = Interlocked.CompareExchange(ref _operating, InProgress, Free);
if (status != Free)
{
// If it was already "in-use" check if Dispose was called.
if (_disposeCalled)
{
// Dispose was called - throw ObjectDisposed.
throw new ObjectDisposedException(GetType().FullName);
}
// Only one at a time.
throw new InvalidOperationException(SR.net_socketopinprogress);
ThrowForNonFreeStatus(status);
}
// Prepare execution context for callback.
@ -452,6 +455,7 @@ namespace System.Net.Sockets
if (_completedChanged || socket != _currentSocket)
{
_completedChanged = false;
_currentSocket = socket;
_context = null;
}
@ -460,9 +464,6 @@ namespace System.Net.Sockets
{
_context = ExecutionContext.Capture();
}
// Remember current socket.
_currentSocket = socket;
}
internal void StartOperationAccept()
@ -484,7 +485,7 @@ namespace System.Net.Sockets
// Caller specified a buffer - see if it is large enough
if (_count < _acceptAddressBufferCount)
{
throw new ArgumentException(SR.Format(SR.net_buffercounttoosmall, "Count"));
throw new ArgumentException(SR.Format(SR.net_buffercounttoosmall, nameof(Count)));
}
// Buffer is already pinned if necessary.
@ -688,23 +689,15 @@ namespace System.Net.Sockets
{
SetResults(SocketError.Success, bytesTransferred, flags);
if (NetEventSource.IsEnabled || Socket.s_perfCountersEnabled)
{
LogBytesTransferred(bytesTransferred, _completedOperation);
}
SocketError socketError = SocketError.Success;
switch (_completedOperation)
{
case SocketAsyncOperation.Accept:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
// Get the endpoint.
Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket._rightEndPoint);
@ -718,72 +711,35 @@ namespace System.Net.Sockets
}
else
{
SetResults(socketError, bytesTransferred, SocketFlags.None);
SetResults(socketError, bytesTransferred, flags);
_acceptSocket = null;
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
break;
case SocketAsyncOperation.Connect:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
socketError = FinishOperationConnect();
// Mark socket connected.
if (socketError == SocketError.Success)
{
if (NetEventSource.IsEnabled) NetEventSource.Connected(_currentSocket, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint);
// Mark socket connected.
_currentSocket.SetToConnected();
_connectSocket = _currentSocket;
}
else
{
SetResults(socketError, bytesTransferred, flags);
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
break;
case SocketAsyncOperation.Disconnect:
_currentSocket.SetToDisconnected();
_currentSocket._remoteEndPoint = null;
break;
case SocketAsyncOperation.Receive:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
break;
case SocketAsyncOperation.ReceiveFrom:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
// Deal with incoming address.
_socketAddress.InternalSize = GetSocketAddressSize();
Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
@ -800,19 +756,6 @@ namespace System.Net.Sockets
break;
case SocketAsyncOperation.ReceiveMessageFrom:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
// Deal with incoming address.
_socketAddress.InternalSize = GetSocketAddressSize();
socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
@ -830,65 +773,40 @@ namespace System.Net.Sockets
FinishOperationReceiveMessageFrom();
break;
case SocketAsyncOperation.Send:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
break;
case SocketAsyncOperation.SendPackets:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (NetEventSource.IsEnabled)
{
LogSendPacketsBuffers(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
FinishOperationSendPackets();
break;
case SocketAsyncOperation.SendTo:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
break;
}
if (socketError != SocketError.Success)
{
// Asynchronous failure or something went wrong after async success.
SetResults(socketError, bytesTransferred, flags);
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
// Complete the operation.
Complete();
}
private void LogBytesTransferred(int bytesTransferred, SocketAsyncOperation operation)
{
if (bytesTransferred > 0)
{
if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
bool sendOp = false;
switch (operation)
{
case SocketAsyncOperation.Connect:
case SocketAsyncOperation.Send:
case SocketAsyncOperation.SendPackets:
case SocketAsyncOperation.SendTo:
sendOp = true;
break;
}
UpdatePerfCounters(bytesTransferred, sendOp);
}
}
}
internal void FinishOperationAsyncSuccess(int bytesTransferred, SocketFlags flags)
{
FinishOperationSyncSuccess(bytesTransferred, flags);

View File

@ -16,6 +16,7 @@ namespace System.Net.Sockets
{
public const bool SupportsMultipleConnectAttempts = false;
private static readonly bool SupportsDualModeIPv4PacketInfo = GetPlatformSupportsDualModeIPv4PacketInfo();
private static readonly byte[] s_peekBuffer = new byte[1];
private static bool GetPlatformSupportsDualModeIPv4PacketInfo()
{
@ -620,23 +621,13 @@ namespace System.Net.Sockets
{
// Special case a receive of 0 bytes into a single buffer. A common pattern is to ReceiveAsync 0 bytes in order
// to be asynchronously notified when data is available, without needing to dedicate a buffer. Some platforms (e.g. macOS),
// however, special-case a receive of 0 to always succeed immediately even if data isn't available. As such, we treat 0
// specially, checking whether any bytes are available rather than doing an actual receive.
receivedFlags = SocketFlags.None;
received = -1;
int available = 0;
errno = Interop.Sys.GetBytesAvailable(socket, &available);
if (errno == Interop.Error.SUCCESS)
// however complete a 0-byte read successfully when data isn't available, as the request can logically be satisfied
// synchronously. As such, we treat 0 specially, and perform a 1-byte peek.
received = Receive(socket, flags | SocketFlags.Peek, s_peekBuffer, 0, s_peekBuffer.Length, socketAddress, ref socketAddressLen, out receivedFlags, out errno);
if (received > 0)
{
if (available > 0)
{
bytesReceived = 0;
errorCode = SocketError.Success;
return true;
}
errno = Interop.Error.EAGAIN; // simulate a receive with no data available
// Peeked for 1-byte, but the actual request was for 0.
received = 0;
}
}
else
@ -1434,7 +1425,7 @@ namespace System.Net.Sockets
Socket socket = socketList[i] as Socket;
if (socket == null)
{
throw new ArgumentException(SR.Format(SR.net_sockets_select, socket?.GetType().FullName ?? "null", typeof(Socket).FullName));
throw new ArgumentException(SR.Format(SR.net_sockets_select, socket?.GetType().FullName ?? "null", typeof(Socket).FullName), nameof(socketList));
}
int fd = (int)socket.SafeHandle.DangerousGetHandle();

View File

@ -288,7 +288,7 @@ namespace System.Net.Sockets.Tests
byte[] buffer = new byte[1];
acceptArgs.SetBuffer(buffer, 0, buffer.Length);
Assert.Throws<ArgumentException>(() => server.AcceptAsync(acceptArgs));
AssertExtensions.Throws<ArgumentException>(null, () => server.AcceptAsync(acceptArgs));
}
}

View File

@ -200,7 +200,7 @@ namespace System.Net.Sockets.Tests
[Fact]
public void Connect_IPAddresses_EmptyArray_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().Connect(new IPAddress[0], 1));
AssertExtensions.Throws<ArgumentException>("addresses", () => GetSocket().Connect(new IPAddress[0], 1));
}
[Fact]
@ -261,7 +261,7 @@ namespace System.Net.Sockets.Tests
public void Send_Buffers_EmptyBuffers_Throws_Argument()
{
SocketError errorCode;
Assert.Throws<ArgumentException>(() => GetSocket().Send(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode));
AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().Send(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode));
}
[Fact]
@ -328,7 +328,7 @@ namespace System.Net.Sockets.Tests
public void Receive_Buffers_EmptyBuffers_Throws_Argument()
{
SocketError errorCode;
Assert.Throws<ArgumentException>(() => GetSocket().Receive(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode));
AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().Receive(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode));
}
[Fact]
@ -349,7 +349,7 @@ namespace System.Net.Sockets.Tests
public void ReceiveFrom_AddressFamily_Throws_Argument()
{
EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1);
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint));
AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
@ -403,7 +403,7 @@ namespace System.Net.Sockets.Tests
EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo));
AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
@ -448,34 +448,34 @@ namespace System.Net.Sockets.Tests
[Fact]
public void SetSocketOption_Linger_NotLingerOption_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new object()));
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new object()));
}
[Fact]
public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1)));
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1)));
AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1)));
AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1)));
}
[Fact]
public void SetSocketOption_IPMulticast_NotIPMulticastOption_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new object()));
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new object()));
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new object()));
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new object()));
}
[Fact]
public void SetSocketOption_IPv6Multicast_NotIPMulticastOption_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new object()));
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new object()));
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new object()));
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new object()));
}
[Fact]
public void SetSocketOption_Object_InvalidOptionName_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, new object()));
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, new object()));
}
[Fact]
@ -517,7 +517,7 @@ namespace System.Net.Sockets.Tests
BufferList = s_buffers
};
Assert.Throws<ArgumentException>(() => GetSocket().AcceptAsync(eventArgs));
AssertExtensions.Throws<ArgumentException>("BufferList", () => GetSocket().AcceptAsync(eventArgs));
}
[Fact]
@ -550,7 +550,7 @@ namespace System.Net.Sockets.Tests
BufferList = s_buffers
};
Assert.Throws<ArgumentException>(() => GetSocket().ConnectAsync(eventArgs));
AssertExtensions.Throws<ArgumentException>("BufferList", () => GetSocket().ConnectAsync(eventArgs));
}
[Fact]
@ -601,7 +601,7 @@ namespace System.Net.Sockets.Tests
BufferList = s_buffers
};
Assert.Throws<ArgumentException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs));
AssertExtensions.Throws<ArgumentException>("BufferList", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs));
}
[Fact]
@ -637,7 +637,7 @@ namespace System.Net.Sockets.Tests
RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1)
};
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs));
AssertExtensions.Throws<ArgumentException>("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveMessageFromAsync that dereferences null SAEA argument")]
@ -660,7 +660,7 @@ namespace System.Net.Sockets.Tests
RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1)
};
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs));
AssertExtensions.Throws<ArgumentException>("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendAsync that dereferences null SAEA argument")]
@ -1056,8 +1056,8 @@ namespace System.Net.Sockets.Tests
[Fact]
public void BeginConnect_IPAddresses_EmptyIPAddresses_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().BeginConnect(new IPAddress[0], 1, TheAsyncCallback, null));
Assert.Throws<ArgumentException>(() => { GetSocket().ConnectAsync(new IPAddress[0], 1); });
AssertExtensions.Throws<ArgumentException>("addresses", () => GetSocket().BeginConnect(new IPAddress[0], 1, TheAsyncCallback, null));
AssertExtensions.Throws<ArgumentException>("addresses", () => { GetSocket().ConnectAsync(new IPAddress[0], 1); });
}
[Theory]
@ -1096,7 +1096,7 @@ namespace System.Net.Sockets.Tests
[Fact]
public void EndConnect_UnrelatedAsyncResult_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().EndConnect(Task.CompletedTask));
AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndConnect(Task.CompletedTask));
}
[Fact]
@ -1138,8 +1138,8 @@ namespace System.Net.Sockets.Tests
[Fact]
public void BeginSend_Buffers_EmptyBuffers_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().BeginSend(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentException>(() => { GetSocket().SendAsync(new List<ArraySegment<byte>>(), SocketFlags.None); });
AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().BeginSend(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null));
AssertExtensions.Throws<ArgumentException>("buffers", () => { GetSocket().SendAsync(new List<ArraySegment<byte>>(), SocketFlags.None); });
}
[Fact]
@ -1151,7 +1151,7 @@ namespace System.Net.Sockets.Tests
[Fact]
public void EndSend_UnrelatedAsyncResult_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().EndSend(Task.CompletedTask));
AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndSend(Task.CompletedTask));
}
[Fact]
@ -1203,7 +1203,7 @@ namespace System.Net.Sockets.Tests
[Fact]
public void EndSendto_UnrelatedAsyncResult_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().EndSendTo(Task.CompletedTask));
AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndSendTo(Task.CompletedTask));
}
[Fact]
@ -1245,8 +1245,8 @@ namespace System.Net.Sockets.Tests
[Fact]
public void BeginReceive_Buffers_EmptyBuffers_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().BeginReceive(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentException>(() => { GetSocket().ReceiveAsync(new List<ArraySegment<byte>>(), SocketFlags.None); });
AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().BeginReceive(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null));
AssertExtensions.Throws<ArgumentException>("buffers", () => { GetSocket().ReceiveAsync(new List<ArraySegment<byte>>(), SocketFlags.None); });
}
[Fact]
@ -1275,8 +1275,8 @@ namespace System.Net.Sockets.Tests
public void BeginReceiveFrom_AddressFamily_Throws_Argument()
{
EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1);
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentException>(() => { GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); });
AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
AssertExtensions.Throws<ArgumentException>("remoteEP", () => { GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); });
}
[Fact]
@ -1343,8 +1343,8 @@ namespace System.Net.Sockets.Tests
{
EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1);
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null));
Assert.Throws<ArgumentException>(() => { GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); });
AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null));
AssertExtensions.Throws<ArgumentException>("remoteEP", () => { GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); });
}
[Fact]
@ -1399,7 +1399,7 @@ namespace System.Net.Sockets.Tests
EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo));
AssertExtensions.Throws<ArgumentException>("endPoint", () => GetSocket(AddressFamily.InterNetwork).EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo));
}
[Fact]

View File

@ -82,7 +82,7 @@ namespace System.Net.Sockets.Tests
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
Assert.Throws<ArgumentException>(() =>
AssertExtensions.Throws<ArgumentException>("remoteEP", () =>
{
sock.SendTo(new byte[10], new DnsEndPoint("localhost", UnusedPort));
});
@ -98,7 +98,7 @@ namespace System.Net.Sockets.Tests
int port = sock.BindToAnonymousPort(IPAddress.Loopback);
EndPoint endpoint = new DnsEndPoint("localhost", port);
Assert.Throws<ArgumentException>(() =>
AssertExtensions.Throws<ArgumentException>("remoteEP", () =>
{
sock.ReceiveFrom(new byte[10], ref endpoint);
});
@ -174,7 +174,7 @@ namespace System.Net.Sockets.Tests
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
Assert.Throws<ArgumentException>(() =>
AssertExtensions.Throws<ArgumentException>("remoteEP", () =>
{
sock.BeginSendTo(new byte[10], 0, 0, SocketFlags.None, new DnsEndPoint("localhost", UnusedPort), null, null);
});

View File

@ -1 +1 @@
a5661e52c3bb75899c93187c9542f6ba0e8f84aa
ef120ada456f292695655c3e53e9b882ec68bd5d

View File

@ -19,7 +19,7 @@ namespace System.Net.Sockets.Tests
private void TestLingerState_ArgumentException(Socket sock, bool enabled, int lingerTime)
{
Assert.Throws<ArgumentException>(() =>
AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () =>
{
sock.LingerState = new LingerOption(enabled, lingerTime);
});

View File

@ -13,7 +13,8 @@ namespace System.Net.Sockets.Tests
public class LoggingTest : RemoteExecutorTestBase
{
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetEventSource is only part of .NET Core")]
[ActiveIssue(20470, TargetFrameworkMonikers.UapAot)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetEventSource is only part of .NET Core.")]
public static void EventSource_ExistsWithCorrectId()
{
Type esType = typeof(Socket).Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
@ -27,7 +28,8 @@ namespace System.Net.Sockets.Tests
[OuterLoop]
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetEventSource is only part of .NET Core")]
[ActiveIssue(20470, TargetFrameworkMonikers.UapAot)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetEventSource is only part of .NET Core.")]
public void EventSource_EventsRaisedAsExpected()
{
RemoteInvoke(() =>

View File

@ -10,96 +10,52 @@ namespace System.Net.Sockets.Tests
{
public class ReceiveMessageFromAsync
{
public void OnCompleted(object sender, SocketAsyncEventArgs args)
{
EventWaitHandle handle = (EventWaitHandle)args.UserToken;
handle.Set();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Success_IPv4()
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void ReceiveSentMessages_SocketAsyncEventArgs_Success(bool ipv4, bool changeReceiveBufferEachCall)
{
ManualResetEvent completed = new ManualResetEvent(false);
const int DataLength = 1024;
AddressFamily family = ipv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6;
IPAddress loopback = ipv4 ? IPAddress.Loopback : IPAddress.IPv6Loopback;
if (Socket.OSSupportsIPv4)
var completed = new ManualResetEventSlim(false);
using (var sender = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
using (var receiver = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
{
using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
sender.Bind(new IPEndPoint(loopback, 0));
receiver.SetSocketOption(ipv4 ? SocketOptionLevel.IP : SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true);
int port = receiver.BindToAnonymousPort(loopback);
var args = new SocketAsyncEventArgs() { RemoteEndPoint = new IPEndPoint(ipv4 ? IPAddress.Any : IPAddress.IPv6Any, 0) };
args.Completed += (s,e) => completed.Set();
args.SetBuffer(new byte[DataLength], 0, DataLength);
for (int iters = 0; iters < 5; iters++)
{
int port = receiver.BindToAnonymousPort(IPAddress.Loopback);
receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sender.Bind(new IPEndPoint(IPAddress.Loopback, 0));
for (int i = 0; i < TestSettings.UDPRedundancy; i++)
{
sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port));
sender.SendTo(new byte[DataLength], new IPEndPoint(loopback, port));
}
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
args.SetBuffer(new byte[1024], 0, 1024);
args.Completed += OnCompleted;
args.UserToken = completed;
bool pending = receiver.ReceiveMessageFromAsync(args);
if (!pending)
if (changeReceiveBufferEachCall)
{
OnCompleted(null, args);
args.SetBuffer(new byte[DataLength], 0, DataLength);
}
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timeout while waiting for connection");
if (!receiver.ReceiveMessageFromAsync(args))
{
completed.Set();
}
Assert.True(completed.Wait(TestSettings.PassingTestTimeout), "Timeout while waiting for connection");
completed.Reset();
Assert.Equal(1024, args.BytesTransferred);
Assert.Equal(DataLength, args.BytesTransferred);
Assert.Equal(sender.LocalEndPoint, args.RemoteEndPoint);
Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, args.ReceiveMessageFromPacketInfo.Address);
sender.Dispose();
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Success_IPv6()
{
ManualResetEvent completed = new ManualResetEvent(false);
if (Socket.OSSupportsIPv6)
{
using (Socket receiver = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp))
{
int port = receiver.BindToAnonymousPort(IPAddress.IPv6Loopback);
receiver.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true);
Socket sender = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
sender.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0));
for (int i = 0; i < TestSettings.UDPRedundancy; i++)
{
sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.IPv6Loopback, port));
}
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
args.SetBuffer(new byte[1024], 0, 1024);
args.Completed += OnCompleted;
args.UserToken = completed;
bool pending = receiver.ReceiveMessageFromAsync(args);
if (!pending)
{
OnCompleted(null, args);
}
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timeout while waiting for connection");
Assert.Equal(1024, args.BytesTransferred);
Assert.Equal(sender.LocalEndPoint, args.RemoteEndPoint);
Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, args.ReceiveMessageFromPacketInfo.Address);
sender.Dispose();
}
}
}
@ -108,30 +64,33 @@ namespace System.Net.Sockets.Tests
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Task_Success(bool ipv4)
public async Task ReceiveSentMessages_Tasks_Success(bool ipv4)
{
const int DataLength = 1024;
AddressFamily family = ipv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6;
IPAddress loopback = ipv4 ? IPAddress.Loopback : IPAddress.IPv6Loopback;
using (Socket receiver = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
using (Socket sender = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
using (var receiver = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
using (var sender = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
{
int port = receiver.BindToAnonymousPort(loopback);
receiver.SetSocketOption(ipv4 ? SocketOptionLevel.IP : SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true);
sender.Bind(new IPEndPoint(loopback, 0));
receiver.SetSocketOption(ipv4 ? SocketOptionLevel.IP : SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true);
int port = receiver.BindToAnonymousPort(loopback);
for (int i = 0; i < TestSettings.UDPRedundancy; i++)
for (int iters = 0; iters < 5; iters++)
{
sender.SendTo(new byte[1024], new IPEndPoint(loopback, port));
}
for (int i = 0; i < TestSettings.UDPRedundancy; i++)
{
sender.SendTo(new byte[DataLength], new IPEndPoint(loopback, port));
}
SocketReceiveMessageFromResult result = await receiver.ReceiveMessageFromAsync(
new ArraySegment<byte>(new byte[1024], 0, 1024), SocketFlags.None,
new IPEndPoint(ipv4 ? IPAddress.Any : IPAddress.IPv6Any, 0));
Assert.Equal(1024, result.ReceivedBytes);
Assert.Equal(sender.LocalEndPoint, result.RemoteEndPoint);
Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, result.PacketInformation.Address);
SocketReceiveMessageFromResult result = await receiver.ReceiveMessageFromAsync(
new ArraySegment<byte>(new byte[DataLength], 0, DataLength), SocketFlags.None,
new IPEndPoint(ipv4 ? IPAddress.Any : IPAddress.IPv6Any, 0));
Assert.Equal(DataLength, result.ReceivedBytes);
Assert.Equal(sender.LocalEndPoint, result.RemoteEndPoint);
Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, result.PacketInformation.Address);
}
}
}
}

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8" ?>
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
<Library Name="System.Net.Sockets.Tests">
<Assembly Name="System.Net.Sockets">
<!-- Needed for 2 tests that require inline metadata -->
<Namespace Name="System.Net.Sockets" Dynamic="Required All" />
</Assembly>
</Library>
</Directives>

View File

@ -25,7 +25,7 @@ namespace System.Net.Sockets.Tests
public void Select_Read_NotASocket_Throws()
{
var list = new List<object> { new object() };
Assert.Throws<ArgumentException>(() => Socket.Select(list, null, null, SelectSuccessTimeoutMicroseconds));
AssertExtensions.Throws<ArgumentException>("socketList", () => Socket.Select(list, null, null, SelectSuccessTimeoutMicroseconds));
}
[Fact]
@ -145,7 +145,7 @@ namespace System.Net.Sockets.Tests
public void Select_Write_NotASocket_Throws()
{
var list = new List<object> { new object() };
Assert.Throws<ArgumentException>(() => Socket.Select(null, list, null, SelectSuccessTimeoutMicroseconds));
AssertExtensions.Throws<ArgumentException>("socketList", () => Socket.Select(null, list, null, SelectSuccessTimeoutMicroseconds));
}
[Fact]
@ -235,7 +235,7 @@ namespace System.Net.Sockets.Tests
public void Select_Error_NotASocket_Throws()
{
var list = new List<object> { new object() };
Assert.Throws<ArgumentException>(() => Socket.Select(null, null, list, SelectSuccessTimeoutMicroseconds));
AssertExtensions.Throws<ArgumentException>("socketList", () => Socket.Select(null, null, list, SelectSuccessTimeoutMicroseconds));
}
[Fact]

View File

@ -16,8 +16,9 @@ namespace System.Net.Sockets.Tests
private readonly ITestOutputHelper _log;
private IPAddress _serverAddress = IPAddress.IPv6Loopback;
// In the current directory
private const string TestFileName = "NCLTest.Socket.SendPacketsAsync.testpayload";
// Accessible directories for UWP app:
// C:\Users\<UserName>\AppData\Local\Packages\<ApplicationPackageName>\
private string TestFileName = Environment.GetEnvironmentVariable("LocalAppData") + @"\NCLTest.Socket.SendPacketsAsync.testpayload";
private static int s_testFileSize = 1024;
#region Additional test attributes
@ -88,12 +89,8 @@ namespace System.Net.Sockets.Tests
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() =>
{
sock.SendPacketsAsync(null);
});
Assert.Equal("e", ex.ParamName);
AssertExtensions.Throws<ArgumentNullException>("e", () => sock.SendPacketsAsync(null));
}
}
}
@ -117,12 +114,7 @@ namespace System.Net.Sockets.Tests
[InlineData(SocketImplementationType.Async)]
public void NullList_Throws(SocketImplementationType type)
{
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() =>
{
SendPackets(type, (SendPacketsElement[])null, SocketError.Success, 0);
});
Assert.Equal("e.SendPacketsElements", ex.ParamName);
AssertExtensions.Throws<ArgumentNullException>("e.SendPacketsElements", () => SendPackets(type, (SendPacketsElement[])null, SocketError.Success, 0));
}
[OuterLoop] // TODO: Issue #11345
@ -279,7 +271,7 @@ namespace System.Net.Sockets.Tests
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_EmptyFileName_Throws(SocketImplementationType type)
{
Assert.Throws<ArgumentException>(() =>
AssertExtensions.Throws<ArgumentException>("path", null, () =>
{
SendPackets(type, new SendPacketsElement(String.Empty), 0);
});
@ -291,7 +283,7 @@ namespace System.Net.Sockets.Tests
[PlatformSpecific(TestPlatforms.Windows)] // whitespace-only is a valid name on Unix
public void SendPacketsElement_BlankFileName_Throws(SocketImplementationType type)
{
Assert.Throws<ArgumentException>(() =>
AssertExtensions.Throws<ArgumentException>("path", null, () =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement(" \t "), 0);
@ -304,7 +296,7 @@ namespace System.Net.Sockets.Tests
[PlatformSpecific(TestPlatforms.Windows)] // valid filename chars on Unix
public void SendPacketsElement_BadCharactersFileName_Throws(SocketImplementationType type)
{
Assert.Throws<ArgumentException>(() =>
AssertExtensions.Throws<ArgumentException>("path", null, () =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement("blarkd@dfa?/sqersf"), 0);

View File

@ -699,6 +699,35 @@ namespace System.Net.Sockets.Tests
}
}
[Fact]
public async Task Receive0ByteReturns_WhenPeerDisconnects()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = AcceptAsync(listener);
await Task.WhenAll(
acceptTask,
ConnectAsync(client, new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
// Have the client do a 0-byte receive. No data is available, so this should pend.
Task<int> receive = ReceiveAsync(client, new ArraySegment<byte>(Array.Empty<byte>()));
Assert.False(receive.IsCompleted, $"Task should not have been completed, was {receive.Status}");
// Disconnect the client
server.Close();
// The client should now wake up
Assert.Equal(0, await receive);
}
}
}
[Theory]
[InlineData(false, 1)]
[InlineData(true, 1)]

View File

@ -156,6 +156,25 @@ namespace System.Net.Sockets.Tests
}
}
[Fact]
public void SetBuffer_NoBuffer_ResetsCountOffset()
{
using (var saea = new SocketAsyncEventArgs())
{
saea.SetBuffer(42, 84);
Assert.Equal(0, saea.Offset);
Assert.Equal(0, saea.Count);
saea.SetBuffer(new byte[3], 1, 2);
Assert.Equal(1, saea.Offset);
Assert.Equal(2, saea.Count);
saea.SetBuffer(null, 1, 2);
Assert.Equal(0, saea.Offset);
Assert.Equal(0, saea.Count);
}
}
[Fact]
public void SetBufferListWhenBufferSet_Throws()
{
@ -165,7 +184,7 @@ namespace System.Net.Sockets.Tests
byte[] buffer = new byte[1];
saea.SetBuffer(buffer, 0, 1);
Assert.Throws<ArgumentException>(() => saea.BufferList = bufferList);
AssertExtensions.Throws<ArgumentException>(null, () => saea.BufferList = bufferList);
Assert.Same(buffer, saea.Buffer);
Assert.Null(saea.BufferList);
@ -181,7 +200,7 @@ namespace System.Net.Sockets.Tests
{
var bufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) };
saea.BufferList = bufferList;
Assert.Throws<ArgumentException>(() => saea.SetBuffer(new byte[1], 0, 1));
AssertExtensions.Throws<ArgumentException>(null, () => saea.SetBuffer(new byte[1], 0, 1));
Assert.Same(bufferList, saea.BufferList);
Assert.Null(saea.Buffer);

View File

@ -55,7 +55,7 @@ namespace System.Net.Sockets.Tests
// TODO: Issue #4887
// The socket option 'ReuseUnicastPost' only works on Windows 10 systems. In addition, setting the option
// is a no-op unless specialized network settings using PowerShell configuration are first applied to the
// machine. This is currently difficult to test in the CI environment. So, this ests will be disabled for now
// machine. This is currently difficult to test in the CI environment. So, this test will be disabled for now
[OuterLoop] // TODO: Issue #11345
[ActiveIssue(4887)]
public void ReuseUnicastPort_CreateSocketSetOptionToOneAndGetOption_SocketsReuseUnicastPortSupport_OptionIsOne()
@ -83,6 +83,7 @@ namespace System.Net.Sockets.Tests
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task MulticastInterface_Set_AnyInterface_Succeeds()
{
// On all platforms, index 0 means "any interface"
@ -92,10 +93,11 @@ namespace System.Net.Sockets.Tests
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // see comment below
[ActiveIssue(21327, TargetFrameworkMonikers.Uap)] // UWP Apps are forbidden to send network traffic to the local Computer.
public async Task MulticastInterface_Set_Loopback_Succeeds()
{
// On Windows, we can apparently assume interface 1 is "loopback." On other platforms, this is not a
// valid assumption. We could maybe use NetworkInterface.LoopbackInterfaceIndex to get the index, but
// On Windows, we can apparently assume interface 1 is "loopback." On other platforms, this is not a
// valid assumption. We could maybe use NetworkInterface.LoopbackInterfaceIndex to get the index, but
// this would introduce a dependency on System.Net.NetworkInformation, which depends on System.Net.Sockets,
// which is what we're testing here.... So for now, we'll just assume "loopback == 1" and run this on
// Windows only.

View File

@ -71,9 +71,6 @@
<Link>SocketCommon\SocketImplementationType.cs</Link>
</Compile>
<!-- Common test files -->
<Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
<Link>Common\System\AssertExtensions.cs</Link>
</Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
@ -98,12 +95,6 @@
<Compile Include="$(CommonTestPath)\System\Diagnostics\Tracing\TestEventListener.cs">
<Link>Common\System\Diagnostics\Tracing\TestEventListener.cs</Link>
</Compile>
<Compile Include="$(CommonTestPath)\System\Diagnostics\RemoteExecutorTestBase.cs">
<Link>Common\System\Diagnostics\RemoteExecutorTestBase.cs</Link>
</Compile>
<Compile Include="$(CommonTestPath)\System\IO\FileCleanupTestBase.cs">
<Link>Common\System\IO\FileCleanupTestBase.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Diagnostics\RemoteExecutorConsoleApp\RemoteExecutorConsoleApp.csproj">
@ -111,5 +102,8 @@
<Name>RemoteExecutorConsoleApp</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>

View File

@ -28,7 +28,7 @@ namespace System.Net.Sockets.Tests
[InlineData(AddressFamily.Unknown)]
public void Ctor_InvalidFamily_Throws(AddressFamily family)
{
Assert.Throws<ArgumentException>(() => new TcpClient(family));
AssertExtensions.Throws<ArgumentException>("family", () => new TcpClient(family));
}
[Fact]

View File

@ -91,8 +91,8 @@ namespace System.Net.Sockets.Tests
Assert.Throws<ArgumentNullException>(() => listener.EndAcceptSocket(null));
Assert.Throws<ArgumentNullException>(() => listener.EndAcceptTcpClient(null));
Assert.Throws<ArgumentException>(() => listener.EndAcceptSocket(Task.CompletedTask));
Assert.Throws<ArgumentException>(() => listener.EndAcceptTcpClient(Task.CompletedTask));
AssertExtensions.Throws<ArgumentException>("asyncResult", () => listener.EndAcceptSocket(Task.CompletedTask));
AssertExtensions.Throws<ArgumentException>("asyncResult", () => listener.EndAcceptTcpClient(Task.CompletedTask));
}
[Fact]