Use *SocketOption for keep-alive on Win < 10 v1709

Rely on defaults and a ConditionalWeakTable to allow:
 - setting time and/or interval via IOControl
 - getting time or interval


Commit migrated from https://github.com/dotnet/corefx/commit/88a2b199ffddc2171c65b583025d7f2acd3224b9
This commit is contained in:
Luigi Berrettini authored and Stephen Toub committed 2018-11-15 12:16:38 -05:00
1 parent 5d052cf21c
commit 124baeec18
4 files changed
+280 -23

No files matched your search

@@ -127,6 +127,7 @@
<Compile Include="System\Net\Sockets\SendPacketsElementFlags.Windows.cs" />
<Compile Include="System\Net\Sockets\Socket.Windows.cs" />
<Compile Include="System\Net\Sockets\SocketAsyncEventArgs.Windows.cs" />
<Compile Include="System\Net\Sockets\IOControlKeepAlive.Windows.cs" />
<Compile Include="System\Net\Sockets\SocketPal.Windows.cs" />
<Compile Include="System\Net\Sockets\TransmitFileAsyncResult.Windows.cs" />
<Compile Include="System\Net\Sockets\UnixDomainSocketEndPoint.Windows.cs" />
@@ -0,0 +1,115 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Net.Sockets
{
// Allow hiding keep-alive time and interval handling behind *SocketOption
// on Windows < 10 v1709 that only supports set via IOControl
internal class IOControlKeepAlive
{
private const uint WindowsDefaultTimeMs = 7200000u;
private const uint WindowsDefaultIntervalMs = 1000u;
private static readonly bool s_supportsKeepAliveViaSocketOption = SupportsKeepAliveViaSocketOption();
private static readonly ConditionalWeakTable<SafeSocketHandle, IOControlKeepAlive> s_socketKeepAliveTable = new ConditionalWeakTable<SafeSocketHandle, IOControlKeepAlive>();
[ThreadStatic]
private static byte[] s_keepAliveValuesBuffer;
private uint _timeMs = WindowsDefaultTimeMs;
private uint _intervalMs = WindowsDefaultIntervalMs;
public static bool IsNeeded
{
get
{
return !s_supportsKeepAliveViaSocketOption;
}
}
public static SocketError Get(SafeSocketHandle handle, SocketOptionName optionName, byte[] optionValueSeconds, ref int optionLength)
{
if (optionValueSeconds == null || !BitConverter.TryWriteBytes(optionValueSeconds.AsSpan(), Get(handle, optionName)))
return SocketError.Fault;
optionLength = optionValueSeconds.Length;
return SocketError.Success;
}
public static int Get(SafeSocketHandle handle, SocketOptionName optionName)
{
IOControlKeepAlive ioControlKeepAlive;
s_socketKeepAliveTable.TryGetValue(handle, out ioControlKeepAlive);
return optionName == SocketOptionName.TcpKeepAliveTime ?
MillisecondsToSeconds(ioControlKeepAlive?._timeMs ?? WindowsDefaultTimeMs) :
MillisecondsToSeconds(ioControlKeepAlive?._intervalMs ?? WindowsDefaultIntervalMs);
}
public static SocketError Set(SafeSocketHandle handle, SocketOptionName optionName, byte[] optionValueSeconds)
{
if (optionValueSeconds == null || optionValueSeconds.Length < sizeof(int))
return SocketError.Fault;
return Set(handle, optionName, BitConverter.ToInt32(optionValueSeconds, 0));
}
public static SocketError Set(SafeSocketHandle handle, SocketOptionName optionName, int optionValueSeconds)
{
IOControlKeepAlive ioControlKeepAlive = s_socketKeepAliveTable.GetOrCreateValue(handle);
if (optionName == SocketOptionName.TcpKeepAliveTime)
ioControlKeepAlive._timeMs = SecondsToMilliseconds(optionValueSeconds);
else
ioControlKeepAlive._intervalMs = SecondsToMilliseconds(optionValueSeconds);
byte[] buffer = s_keepAliveValuesBuffer ?? (s_keepAliveValuesBuffer = new byte[3 * sizeof(uint)]);
ioControlKeepAlive.Fill(buffer);
int realOptionLength = 0;
return SocketPal.WindowsIoctl(handle, unchecked((int)IOControlCode.KeepAliveValues), buffer, null, out realOptionLength);
}
private static bool SupportsKeepAliveViaSocketOption()
{
AddressFamily addressFamily = Socket.OSSupportsIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6;
using (Socket socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp))
{
int time = MillisecondsToSeconds(WindowsDefaultTimeMs);
SocketError timeErrCode = Interop.Winsock.setsockopt(
socket.SafeHandle,
SocketOptionLevel.Tcp,
SocketOptionName.TcpKeepAliveTime,
ref time,
sizeof(int));
int interval = MillisecondsToSeconds(WindowsDefaultIntervalMs);
SocketError intervalErrCode = Interop.Winsock.setsockopt(
socket.SafeHandle,
SocketOptionLevel.Tcp,
SocketOptionName.TcpKeepAliveInterval,
ref interval,
sizeof(int));
return timeErrCode == SocketError.Success && intervalErrCode == SocketError.Success;
}
}
private static int MillisecondsToSeconds(uint milliseconds)
{
return (int)(milliseconds / 1000u);
}
private static uint SecondsToMilliseconds(int seconds)
{
return (uint)seconds * 1000u;
}
private void Fill(byte[] buffer)
{
Debug.Assert(buffer != null);
Debug.Assert(buffer.Length == 3 * sizeof(uint));
const uint onOff = 1u;
BitConverter.TryWriteBytes(buffer.AsSpan(), onOff);
BitConverter.TryWriteBytes(buffer.AsSpan(sizeof(uint)), _timeMs);
BitConverter.TryWriteBytes(buffer.AsSpan(sizeof(uint) * 2), _intervalMs);
}
}
}
@@ -117,6 +117,7 @@ namespace System.Net.Sockets
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Send(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out int bytesTransferred)
{
const int StackThreshold = 16; // arbitrary limit to avoid too much space on stack (note: may be over-sized, that's OK - length passed separately)
@@ -489,23 +490,43 @@ namespace System.Net.Sockets
public static unsafe SocketError SetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
ref optionValue,
sizeof(int));
SocketError errorCode;
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval)
&& IOControlKeepAlive.IsNeeded)
{
errorCode = IOControlKeepAlive.Set(handle, optionName, optionValue);
}
else
{
errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
ref optionValue,
sizeof(int));
}
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
optionValue,
optionValue != null ? optionValue.Length : 0);
SocketError errorCode;
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval)
&& IOControlKeepAlive.IsNeeded)
{
errorCode = IOControlKeepAlive.Set(handle, optionName, optionValue);
}
else
{
errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
optionValue,
optionValue != null ? optionValue.Length : 0);
}
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
@@ -599,6 +620,14 @@ namespace System.Net.Sockets
public static SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue)
{
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval)
&& IOControlKeepAlive.IsNeeded)
{
optionValue = IOControlKeepAlive.Get(handle, optionName);
return SocketError.Success;
}
int optionLength = 4; // sizeof(int)
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
@@ -611,6 +640,14 @@ namespace System.Net.Sockets
public static SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue, ref int optionLength)
{
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval)
&& IOControlKeepAlive.IsNeeded)
{
IOControlKeepAlive.Get(handle, optionName, optionValue, ref optionLength);
return SocketError.Success;
}
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
@@ -12,6 +12,8 @@ namespace System.Net.Sockets.Tests
private const int RetryCount = 60;
private const int Time = 5;
private const int Interval = 2;
private const int WindowsDefaultTime = 7200;
private const int WindowsDefaultInterval = 1;
private static bool IsUnixOrWindowsAtLeast1703 =>
!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1703OrGreater;
@@ -19,9 +21,6 @@ namespace System.Net.Sockets.Tests
private static bool IsWindowsBelow1703 =>
PlatformDetection.IsWindows && !PlatformDetection.IsWindows10Version1703OrGreater;
private static bool IsUnixOrWindowsAtLeast1709 =>
!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1709OrGreater;
private static bool IsWindowsBelow1709 =>
PlatformDetection.IsWindows && !PlatformDetection.IsWindows10Version1709OrGreater;
@@ -45,7 +44,7 @@ namespace System.Net.Sockets.Tests
}
[ConditionalFact(typeof(KeepAliveTest), nameof(IsUnixOrWindowsAtLeast1703))]
public void Socket_Set_KeepAlive_RetryCount_Success()
public void Socket_KeepAlive_RetryCount_Success()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
@@ -55,7 +54,7 @@ namespace System.Net.Sockets.Tests
}
[ConditionalFact(typeof(KeepAliveTest), nameof(IsWindowsBelow1703))]
public void Socket_Set_KeepAlive_RetryCount_Failure()
public void Socket_KeepAlive_RetryCount_Failure()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
@@ -65,7 +64,7 @@ namespace System.Net.Sockets.Tests
}
[Fact]
public void Socket_Set_KeepAlive_Time_Success()
public void Socket_KeepAlive_Time()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
@@ -74,8 +73,8 @@ namespace System.Net.Sockets.Tests
}
}
[ConditionalFact(typeof(KeepAliveTest), nameof(IsUnixOrWindowsAtLeast1709))]
public void Socket_Set_KeepAlive_Interval_Success()
[Fact]
public void Socket_KeepAlive_Interval()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
@@ -85,12 +84,117 @@ namespace System.Net.Sockets.Tests
}
[ConditionalFact(typeof(KeepAliveTest), nameof(IsWindowsBelow1709))]
public void Socket_Set_KeepAlive_Interval_Failure()
public void Socket_KeepAlive_Time_And_Interval()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<SocketException>(() => socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, Interval));
Assert.Throws<SocketException>(() => socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
Assert.Equal<int>(WindowsDefaultTime, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime));
Assert.Equal<int>(WindowsDefaultInterval, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, Time);
Assert.Equal<int>(Time, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime));
Assert.Equal<int>(WindowsDefaultInterval, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, Interval);
Assert.Equal<int>(Time, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime));
Assert.Equal<int>(Interval, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
}
}
[ConditionalFact(typeof(KeepAliveTest), nameof(IsWindowsBelow1709))]
public void Socket_KeepAlive_Interval_And_Time()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Equal<int>(WindowsDefaultTime, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime));
Assert.Equal<int>(WindowsDefaultInterval, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, Interval);
Assert.Equal<int>(WindowsDefaultTime, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime));
Assert.Equal<int>(Interval, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, Time);
Assert.Equal<int>(Time, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime));
Assert.Equal<int>(Interval, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
}
}
[Fact]
public void Socket_Get_KeepAlive_Time_AsByteArray_OptionLengthZero_Failure()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<SocketException>(() => socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 0));
}
}
[Fact]
public void Socket_Get_KeepAlive_Time_AsByteArray_BufferNull_Failure()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
byte[] bufferNull = null;
Assert.Throws<SocketException>(() => socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, bufferNull));
}
}
[Fact]
public void Socket_Get_KeepAlive_Time_AsByteArray_BufferLengthZero_Failure()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
byte[] bufferLenghtZero = new byte[0];
Assert.Throws<SocketException>(() => socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, bufferLenghtZero));
}
}
[Fact]
public void Socket_Get_KeepAlive_Time_AsByteArray_BufferShort_Failure()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
byte[] bufferShort = new byte[1];
Assert.Throws<SocketException>(() => socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, bufferShort));
}
}
[Fact]
public void Socket_Set_KeepAlive_Time_AsByteArray_BufferNull_Failure()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
byte[] bufferNull = null;
Assert.Throws<SocketException>(() => socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, bufferNull));
}
}
[Fact]
public void Socket_Set_KeepAlive_Time_AsByteArray_BufferLengthZero_Failure()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
byte[] bufferLenghtZero = new byte[0];
Assert.Throws<SocketException>(() => socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, bufferLenghtZero));
}
}
[Fact]
public void Socket_Set_KeepAlive_Time_AsByteArray_BufferShort_Failure()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
byte[] bufferShort = new byte[1];
Assert.Throws<SocketException>(() => socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, bufferShort));
}
}
[Fact]
public void Socket_KeepAlive_Time_AsByteArray_Success()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, BitConverter.GetBytes(Time));
Assert.Equal<int>(Time, BitConverter.ToInt32(socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, sizeof(int)), 0));
}
}
}