From 8c57d477dbc7515adabbdbe5bc77dbb0b9a18ca5 Mon Sep 17 00:00:00 2001 From: Martin Regen Date: Mon, 9 Oct 2017 15:27:22 +0200 Subject: [PATCH] fix a race condition during connect, when both addresses return quickly with an error condition TaskCompletionSource could be signaled twice, causing an exception. Fix: Advance connection counters before connecting --- Stack/Opc.Ua.Core/Stack/Tcp/TcpMessageSocket.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Stack/Opc.Ua.Core/Stack/Tcp/TcpMessageSocket.cs b/Stack/Opc.Ua.Core/Stack/Tcp/TcpMessageSocket.cs index b52273af5c..fe7ac68258 100644 --- a/Stack/Opc.Ua.Core/Stack/Tcp/TcpMessageSocket.cs +++ b/Stack/Opc.Ua.Core/Stack/Tcp/TcpMessageSocket.cs @@ -361,6 +361,17 @@ namespace Opc.Ua.Bindings do { error = SocketError.NotInitialized; + + lock (m_socketLock) + { + if (addressesV6.Length > arrayV6Index) + m_socketResponses++; + if (addressesV4.Length > arrayV4Index) + m_socketResponses++; + if (m_tcs.Task.IsCompleted) + m_tcs = new TaskCompletionSource(); + } + if (addressesV6.Length > arrayV6Index && m_socket == null) { if (BeginConnect(addressesV6[arrayV6Index], AddressFamily.InterNetworkV6, port, doCallback) == SocketError.Success) @@ -394,7 +405,6 @@ namespace Opc.Ua.Bindings case SocketError.Success: return true; case SocketError.ConnectionRefused: - m_tcs = new TaskCompletionSource(); break; default: goto ErrorExit; @@ -699,10 +709,6 @@ namespace Opc.Ua.Bindings RemoteEndPoint = new IPEndPoint(address, port), }; args.Completed += new EventHandler(OnSocketConnected); - lock (m_socketLock) - { - m_socketResponses++; - } if (!socket.ConnectAsync(args)) { // I/O completed synchronously