Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix | SqlClient-826 Missed synchronization #1029

Merged
merged 24 commits into from
May 12, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
17a8b3d
Fixes #826
Apr 13, 2021
e26b2a3
Merge branch 'mainDotNet' into SqlClient-826
Apr 13, 2021
0021191
Few improvements:
Apr 15, 2021
77b660e
Merge branch 'mainDotNet' into SqlClient-826
Jun 28, 2021
fab6ac4
Fix upon PR comment "Generally, we use ADP class to manage exceptions"
Jul 7, 2021
697d7d9
Fix upon PR comment: isInfiniteTimeout case added
Jul 7, 2021
14adb61
isInfiniteTimeout fixed
Jul 7, 2021
4dd170c
Connect timeout greater than int.MaxValue fixed
Jul 12, 2021
308bded
Merge branch 'mainDotNet' into SqlClient-826
Jul 13, 2021
8e37afc
Merge branch 'mainDotNet' into SqlClient-826
Jul 13, 2021
0445abe
Merge remote-tracking branch 'Upstream/main' into SqlClient-826
DavoudEshtehari May 8, 2023
829050e
Removes LINQ usage. Resolving https://github.com/dotnet/SqlClient/pul…
jinek May 10, 2023
3dd7083
New resource message, resolving https://github.com/dotnet/SqlClient/p…
jinek May 10, 2023
325d7bf
Update src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net…
jinek May 10, 2023
478d85b
fix of "src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlCl…
jinek May 10, 2023
7bb78ef
Merge remote-tracking branch 'origin/SqlClient-826' into SqlClient-826
jinek May 10, 2023
85d47c2
Update resource
DavoudEshtehari May 10, 2023
11595a5
Update src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlCli…
jinek May 11, 2023
a9ec7b9
Update src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlCli…
jinek May 11, 2023
c06d419
Update src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlCli…
jinek May 11, 2023
eb85d92
Update src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlCli…
jinek May 11, 2023
41c9d54
Update src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlCli…
jinek May 11, 2023
ff402c4
Fix of https://github.com/dotnet/SqlClient/pull/1029#discussion_r1190…
jinek May 11, 2023
82ad1c0
Update src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlCli…
jinek May 11, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,24 @@
// 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.Runtime.Serialization;

jinek marked this conversation as resolved.
Show resolved Hide resolved
namespace System.Net
{
[Serializable]
internal class InternalException : Exception
{
internal InternalException()
public InternalException() : this("InternalException thrown.")
{
}

public InternalException(string message) : this(message, null)
{
}

public InternalException(string message, Exception innerException) : base(message, innerException)
{
NetEventSource.Fail(this, "InternalException thrown.");
NetEventSource.Fail(this, message);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
jinek marked this conversation as resolved.
Show resolved Hide resolved
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
Expand Down Expand Up @@ -336,141 +338,81 @@ private static Socket Connect(string serverName, int port, TimeSpan timeout, boo
{
SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.INFO, "IP preference : {0}", Enum.GetName(typeof(SqlConnectionIPAddressPreference), ipPreference));

IPAddress[] ipAddresses = Dns.GetHostAddresses(serverName);
Stopwatch timeTaken = Stopwatch.StartNew();

string IPv4String = null;
string IPv6String = null;

// Returning null socket is handled by the caller function.
if (ipAddresses == null || ipAddresses.Length == 0)
{
return null;
}

Socket[] sockets = new Socket[ipAddresses.Length];
AddressFamily[] preferedIPFamilies = new AddressFamily[2];
IEnumerable<IPAddress> ipAddresses = Dns.GetHostAddresses(serverName).Where(address =>
address.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6);

if (ipPreference == SqlConnectionIPAddressPreference.IPv4First)
ipAddresses = ipPreference switch
{
preferedIPFamilies[0] = AddressFamily.InterNetwork;
preferedIPFamilies[1] = AddressFamily.InterNetworkV6;
}
else if (ipPreference == SqlConnectionIPAddressPreference.IPv6First)
{
preferedIPFamilies[0] = AddressFamily.InterNetworkV6;
preferedIPFamilies[1] = AddressFamily.InterNetwork;
}
// else -> UsePlatformDefault

CancellationTokenSource cts = null;
SqlConnectionIPAddressPreference.IPv4First => ipAddresses.OrderByDescending(address =>
address.AddressFamily == AddressFamily.InterNetwork),
SqlConnectionIPAddressPreference.IPv6First => ipAddresses.OrderByDescending(address =>
address.AddressFamily == AddressFamily.InterNetworkV6),
SqlConnectionIPAddressPreference.UsePlatformDefault => ipAddresses,
_ => throw new ArgumentOutOfRangeException(nameof(ipPreference), ipPreference, null)
DavoudEshtehari marked this conversation as resolved.
Show resolved Hide resolved
};

if (!isInfiniteTimeout)
foreach (IPAddress ipAddress in ipAddresses)
{
cts = new CancellationTokenSource(timeout);
cts.Token.Register(Cancel);
}

Socket availableSocket = null;
try
{
// We go through the IP list twice.
// In the first traversal, we only try to connect with the preferedIPFamilies[0].
// In the second traversal, we only try to connect with the preferedIPFamilies[1].
// For UsePlatformDefault preference, we do traversal once.
for (int i = 0; i < preferedIPFamilies.Length; ++i)
{
for (int n = 0; n < ipAddresses.Length; n++)
{
IPAddress ipAddress = ipAddresses[n];
try
{
if (ipAddress != null)
{
if (ipAddress.AddressFamily != preferedIPFamilies[i] && ipPreference != SqlConnectionIPAddressPreference.UsePlatformDefault)
{
continue;
}
var socket =
new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { Blocking = false };

sockets[n] = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
bool isSocketSelected = false;

// enable keep-alive on socket
SetKeepAliveValues(ref sockets[n]);
// enable keep-alive on socket
SetKeepAliveValues(ref socket);

SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.INFO, "Connecting to IP address {0} and port {1} using {2} address family.",
args0: ipAddress,
args1: port,
args2: ipAddress.AddressFamily);
sockets[n].Connect(ipAddress, port);
if (sockets[n] != null) // sockets[n] can be null if cancel callback is executed during connect()
{
if (sockets[n].Connected)
{
availableSocket = sockets[n];
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
IPv4String = ipAddress.ToString();
}
else if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
IPv6String = ipAddress.ToString();
}

break;
}
else
{
sockets[n].Dispose();
sockets[n] = null;
}
}
}
}
catch (Exception e)
{
SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "THIS EXCEPTION IS BEING SWALLOWED: {0}", args0: e?.Message);
SqlClientEventSource.Log.TryAdvancedTraceEvent($"{s_className}.{System.Reflection.MethodBase.GetCurrentMethod().Name}{EventType.ERR}THIS EXCEPTION IS BEING SWALLOWED: {e}");
}
}
SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.INFO,
"Connecting to IP address {0} and port {1} using {2} address family.", ipAddress,
port, ipAddress.AddressFamily);

// If we have already got a valid Socket, or the platform default was prefered
// we won't do the second traversal.
if (availableSocket != null || ipPreference == SqlConnectionIPAddressPreference.UsePlatformDefault)
{
break;
}
try
{
socket.Connect(ipAddress, port);
throw new InternalException(
$"Call to {nameof(Socket.Connect)} must throw {nameof(SocketException)} " +
$"with {SocketError.WouldBlock.ToString()} error code");
}
}
finally
{
cts?.Dispose();
}

// we only record the ip we can connect with successfully.
if (IPv4String != null || IPv6String != null)
{
pendingDNSInfo = new SQLDNSInfo(cachedFQDN, IPv4String, IPv6String, port.ToString());
}
catch (SocketException socketException) when (socketException.SocketErrorCode ==
SocketError.WouldBlock)
{
// https://github.com/dotnet/SqlClient/issues/826#issuecomment-736224118

return availableSocket;
var timeLeft = timeout - timeTaken.Elapsed;

void Cancel()
{
for (int i = 0; i < sockets.Length; ++i)
{
if (timeLeft <= TimeSpan.Zero && !isInfiniteTimeout)
return null;
try
{
if (sockets[i] != null && !sockets[i].Connected)
{
sockets[i].Dispose();
sockets[i] = null;
}
int connectionTimeout = isInfiniteTimeout? -1 : checked((int)(timeLeft.TotalMilliseconds * 1000));
Socket.Select(null, new List<Socket> {socket}, null,
connectionTimeout);
}
catch (Exception e)
catch (SocketException) { }

if (socket.Connected)
{
SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "THIS EXCEPTION IS BEING SWALLOWED: {0}", args0: e?.Message);
isSocketSelected = true;
socket.Blocking = true;
string iPv4String = null;
string iPv6String = null;
string ipAddressString = ipAddress.ToString();
if (socket.AddressFamily == AddressFamily.InterNetwork)
iPv4String = ipAddressString;
else iPv6String = ipAddressString;
jinek marked this conversation as resolved.
Show resolved Hide resolved
pendingDNSInfo = new SQLDNSInfo(cachedFQDN, iPv4String, iPv6String, port.ToString());
return socket;
}
}
finally
{
if (!isSocketSelected)
socket.Dispose();
jinek marked this conversation as resolved.
Show resolved Hide resolved
}
}

return null;
}

private static Task<Socket> ParallelConnectAsync(IPAddress[] serverAddresses, int port)
Expand Down