Skip to content

Commit

Permalink
Fix Socket array length to avoid possible out of bounds errors (#1031)
Browse files Browse the repository at this point in the history
  • Loading branch information
cheenamalhotra committed Apr 14, 2021
1 parent e4d87e6 commit 2e773ae
Showing 1 changed file with 18 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,13 @@ private static Socket Connect(string serverName, int port, TimeSpan timeout, boo
string IPv4String = null;
string IPv6String = null;

Socket[] sockets = new Socket[2];
// 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[] { AddressFamily.InterNetwork, AddressFamily.InterNetworkV6 };

CancellationTokenSource cts = null;
Expand Down Expand Up @@ -360,6 +366,8 @@ void Cancel()
Socket availableSocket = null;
try
{
int n = 0; // Socket index

// 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].
Expand All @@ -371,18 +379,18 @@ void Cancel()
{
if (ipAddress != null && ipAddress.AddressFamily == preferedIPFamilies[i])
{
sockets[i] = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sockets[n] = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

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

SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.INFO, "Connecting to IP address {0} and port {1}", args0: ipAddress, args1: port);
sockets[i].Connect(ipAddress, port);
if (sockets[i] != null) // sockets[i] can be null if cancel callback is executed during connect()
sockets[n].Connect(ipAddress, port);
if (sockets[n] != null) // sockets[i] can be null if cancel callback is executed during connect()
{
if (sockets[i].Connected)
if (sockets[n].Connected)
{
availableSocket = sockets[i];
availableSocket = sockets[n];

if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
Expand All @@ -397,10 +405,11 @@ void Cancel()
}
else
{
sockets[i].Dispose();
sockets[i] = null;
sockets[n].Dispose();
sockets[n] = null;
}
}
n++;
}
}
catch (Exception e)
Expand Down

0 comments on commit 2e773ae

Please sign in to comment.