Skip to content

Commit 175fa83

Browse files
committed
Fix for issue dotnet#1733 - hang on infinite timeout
Also fix SSRP when DataSource is an IP address
1 parent bd21d76 commit 175fa83

File tree

5 files changed

+48
-40
lines changed

5 files changed

+48
-40
lines changed

src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs

+10
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// See the LICENSE file in the project root for more information.
44

55
using System;
6+
using System.Net;
67
using System.Net.Security;
78
using System.Security.Cryptography.X509Certificates;
89

@@ -194,6 +195,15 @@ internal static bool ValidateSslServerCertificate(string targetServerName, X509C
194195
}
195196
}
196197

198+
internal static IPAddress[] GetDnsIpAddresses(string serverName)
199+
{
200+
using (TrySNIEventScope.Create(nameof(GetDnsIpAddresses)))
201+
{
202+
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.INFO, "Getting DNS host entries for serverName {0}.", args0: serverName);
203+
return Dns.GetHostAddresses(serverName);
204+
}
205+
}
206+
197207
/// <summary>
198208
/// Sets last error encountered for SNI
199209
/// </summary>

src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNITcpHandle.cs

+2-16
Original file line numberDiff line numberDiff line change
@@ -299,14 +299,7 @@ private Socket TryConnectParallel(string hostName, int port, TimeSpan ts, bool i
299299
Socket availableSocket = null;
300300
Task<Socket> connectTask;
301301

302-
Task<IPAddress[]> serverAddrTask = Dns.GetHostAddressesAsync(hostName);
303-
bool complete = serverAddrTask.Wait(ts);
304-
305-
// DNS timed out - don't block
306-
if (!complete)
307-
return null;
308-
309-
IPAddress[] serverAddresses = serverAddrTask.Result;
302+
IPAddress[] serverAddresses = SNICommon.GetDnsIpAddresses(hostName);
310303

311304
if (serverAddresses.Length > MaxParallelIpAddresses)
312305
{
@@ -358,14 +351,7 @@ private static Socket Connect(string serverName, int port, TimeSpan timeout, boo
358351
{
359352
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "IP preference : {0}", Enum.GetName(typeof(SqlConnectionIPAddressPreference), ipPreference));
360353

361-
Task<IPAddress[]> serverAddrTask = Dns.GetHostAddressesAsync(serverName);
362-
bool complete = serverAddrTask.Wait(timeout);
363-
364-
// DNS timed out - don't block
365-
if (!complete)
366-
return null;
367-
368-
IPAddress[] ipAddresses = serverAddrTask.Result;
354+
IPAddress[] ipAddresses = SNICommon.GetDnsIpAddresses(serverName);
369355

370356
string IPv4String = null;
371357
string IPv6String = null;

src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SSRP.cs

+12-23
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,16 @@ private static byte[] SendUDPRequest(string browserHostname, int port, byte[] re
170170
Debug.Assert(port >= 0 && port <= 65535, "Invalid port");
171171
Debug.Assert(requestPacket != null && requestPacket.Length > 0, "requestPacket should not be null or 0-length array");
172172

173-
bool isIpAddress = IPAddress.TryParse(browserHostname, out IPAddress address);
173+
if (IPAddress.TryParse(browserHostname, out IPAddress address))
174+
{
175+
SsrpResult response = SendUDPRequest(new IPAddress[] { address }, port, requestPacket, allIPsInParallel);
176+
if (response != null && response.ResponsePacket != null)
177+
return response.ResponsePacket;
178+
else if (response != null && response.Error != null)
179+
throw response.Error;
180+
else
181+
return null;
182+
}
174183

175184
TimeSpan ts = default;
176185
// In case the Timeout is Infinite, we will receive the max value of Int64 as the tick count
@@ -181,27 +190,7 @@ private static byte[] SendUDPRequest(string browserHostname, int port, byte[] re
181190
ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;
182191
}
183192

184-
IPAddress[] ipAddresses = null;
185-
if (!isIpAddress)
186-
{
187-
Task<IPAddress[]> serverAddrTask = Dns.GetHostAddressesAsync(browserHostname);
188-
bool taskComplete;
189-
try
190-
{
191-
taskComplete = serverAddrTask.Wait(ts);
192-
}
193-
catch (AggregateException ae)
194-
{
195-
throw ae.InnerException;
196-
}
197-
198-
// If DNS took too long, need to return instead of blocking
199-
if (!taskComplete)
200-
return null;
201-
202-
ipAddresses = serverAddrTask.Result;
203-
}
204-
193+
IPAddress[] ipAddresses = SNICommon.GetDnsIpAddresses(browserHostname);
205194
Debug.Assert(ipAddresses.Length > 0, "DNS should throw if zero addresses resolve");
206195

207196
switch (ipPreference)
@@ -278,7 +267,7 @@ private static SsrpResult SendUDPRequest(IPAddress[] ipAddresses, int port, byte
278267
for (int i = 0; i < ipAddresses.Length; i++)
279268
{
280269
IPEndPoint endPoint = new IPEndPoint(ipAddresses[i], port);
281-
tasks.Add(Task.Factory.StartNew<SsrpResult>(() => SendUDPRequest(endPoint, requestPacket)));
270+
tasks.Add(Task.Factory.StartNew<SsrpResult>(() => SendUDPRequest(endPoint, requestPacket), cts.Token));
282271
}
283272

284273
List<Task<SsrpResult>> completedTasks = new();

src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/ConnectivityTest.cs

+15
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,21 @@ public static void EnvironmentHostNameSPIDTest()
8888
Assert.True(false, "No non-empty hostname found for the application");
8989
}
9090

91+
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
92+
public static async void ConnectionTimeoutInfiniteTest()
93+
{
94+
// Exercise the special-case infinite connect timeout code path
95+
SqlConnectionStringBuilder builder = new(DataTestUtility.TCPConnectionString)
96+
{
97+
ConnectTimeout = 0 // Infinite
98+
};
99+
100+
using SqlConnection conn = new(builder.ConnectionString);
101+
CancellationTokenSource cts = new(30000);
102+
// Will throw TaskCanceledException and fail the test in the event of a hang
103+
await conn.OpenAsync(cts.Token);
104+
}
105+
91106
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
92107
public static void ConnectionTimeoutTestWithThread()
93108
{

src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/InstanceNameTest/InstanceNameTest.cs

+9-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// See the LICENSE file in the project root for more information.
44

55
using System;
6+
using System.Net;
67
using System.Net.Sockets;
78
using System.Text;
89
using System.Threading.Tasks;
@@ -20,9 +21,9 @@ public static void ConnectToSQLWithInstanceNameTest()
2021
bool proceed = true;
2122
string dataSourceStr = builder.DataSource.Replace("tcp:", "");
2223
string[] serverNamePartsByBackSlash = dataSourceStr.Split('\\');
24+
string hostname = serverNamePartsByBackSlash[0];
2325
if (!dataSourceStr.Contains(",") && serverNamePartsByBackSlash.Length == 2)
2426
{
25-
string hostname = serverNamePartsByBackSlash[0];
2627
proceed = !string.IsNullOrWhiteSpace(hostname) && IsBrowserAlive(hostname);
2728
}
2829

@@ -31,6 +32,13 @@ public static void ConnectToSQLWithInstanceNameTest()
3132
using SqlConnection connection = new(builder.ConnectionString);
3233
connection.Open();
3334
connection.Close();
35+
36+
// Exercise the IP address-specific code in SSRP
37+
IPAddress[] addresses = Dns.GetHostAddresses(hostname);
38+
builder.DataSource = builder.DataSource.Replace(hostname, addresses[0].ToString());
39+
using SqlConnection connection2 = new(builder.ConnectionString);
40+
connection2.Open();
41+
connection2.Close();
3442
}
3543
}
3644

0 commit comments

Comments
 (0)