SSH.NET icon indicating copy to clipboard operation
SSH.NET copied to clipboard

Timeout properties are ignored when connecting via a proxy

Open magomedov opened this issue 9 years ago • 1 comments

The problem is that we have a slow sftp server which takes some time to establish connection with. It may take up to 2 minutes to establish a connection, and after that it works fine. When connecting using various ftp-clients we increased timeout property and it worked for us. However this does not work via the code. When trying to connect via a secured proxy - it seems that both ConnectionInfo.Timeout and SftpClient.OperationTimeout have no effect and connection is terminated due to a timeout after ~27 seconds. This seems to be an old issue with at least one other user facing it in 2015 http://stackoverflow.com/questions/34388446/c-sharp-renci-sshnet-sftp-client-connection-behind-proxy-timeout#comment72017745_34388446 For me it the same with Renci.SSH 2014 as well as with the latest version SSH.NET.2016.0.0

Thank you in advance for your consideration of the issue

magomedov avatar Feb 24 '17 11:02 magomedov

This is not related to a proxy. SSH.NET uses System.Net.Sockets together with ManualResetEvent.WaitOne(connectTimeout) method, which provides a way to allow cross-thread communication and to let other threads know when something has completed. In this case it blocks the thread until socket connection is established and continues when it receives a signal about connect completion or failure (timeout).

However, the WaitOne timeout can be used to force a lower timeout than the system default, but if you want to increase the timeout (i.e. to more than 21 seconds which is default on Windows) you have to change the TCP settings (Max SYN Retransmissions) of the underlying operating system.

PS C:\Windows\system32> netsh interface tcp show global
Querying active state...

TCP Global Parameters
----------------------------------------------
Receive-Side Scaling State          : enabled
Chimney Offload State               : disabled
NetDMA State                        : disabled
Direct Cache Access (DCA)           : disabled
Receive Window Auto-Tuning Level    : normal
Add-On Congestion Control Provider  : none
ECN Capability                      : disabled
RFC 1323 Timestamps                 : disabled
Initial RTO                         : 3000
Receive Segment Coalescing State    : disabled
Non Sack Rtt Resiliency             : disabled
Max SYN Retransmissions             : 2
TCP Fast Open                       : enabled

PS C:\Windows\system32>

The default value is 2, which yields an effective TCP connection timeout of about 21 seconds. A value of 3 increases the timeout to about 40 seconds, and 4 to about 90 seconds.

Note: In Windows 7 and Windows Server 2008 R2, the TCP maximum SYN retransmission value is set to 2, and is not configurable. Because of the 3-second limit of the initial time-out value, the TCP three-way handshake is limited to a 21-second timeframe (3 seconds + 2 * 3 seconds + 4 * 3 seconds = 21 seconds).

You have to install hotfix provided by Microsoft, which enables the configuration of the TCP maximum SYN retransmission amount in Windows 7 or Windows Server 2008 R2 (on Windows 8.1 and 10 it is configurable by default).

Example configuration:

PS C:\Windows\system32> netsh interface tcp set global MaxSynRetransmissions=3
Ok.
PS C:\Windows\system32>
PS C:\Windows\system32> netsh interface tcp show global
Querying active state...

TCP Global Parameters
----------------------------------------------
Receive-Side Scaling State          : enabled
Chimney Offload State               : disabled
NetDMA State                        : disabled
Direct Cache Access (DCA)           : disabled
Receive Window Auto-Tuning Level    : normal
Add-On Congestion Control Provider  : none
ECN Capability                      : disabled
RFC 1323 Timestamps                 : disabled
Initial RTO                         : 3000
Receive Segment Coalescing State    : disabled
Non Sack Rtt Resiliency             : disabled
Max SYN Retransmissions             : 3
TCP Fast Open                       : enabled
PS C:\Windows\system32>

As mentioned above, now the timeout will be 40 seconds. And again, by setting timeout via the ConnectionInfo.Timeout() you can force only a lower timeout than currently configured 40 seconds.

For more info check the SSH.NET code in Abstractions/SocketAbstraction.cs and Connect method:

If connection is not established within provided timeout value, then you receive SshOperationTimeoutException

if (socket.ConnectAsync(args))
{
      if (!connectCompleted.WaitOne(connectTimeout))
      {
      // avoid ObjectDisposedException in ConnectCompleted
      args.Completed -= ConnectCompleted;
      // dispose Socket
      socket.Dispose();
      // dispose ManualResetEvent
      connectCompleted.Dispose();
      // dispose SocketAsyncEventArgs
      args.Dispose();

      throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
                                   "Connection failed to establish within {0:F0} milliseconds.",
                                    connectTimeout.TotalMilliseconds));
       }
}

However, as mentioned above, you can force only a lower timeout value than the system default (or currently set value). Otherwise socket timeout is received after 21, 40 or 90 seconds etc... args.SocketError == TimedOut and SocketException is thrown

if (args.SocketError != SocketError.Success)
{
      var socketError = (int) args.SocketError;

      // dispose Socket
      socket.Dispose();
      // dispose SocketAsyncEventArgs
      args.Dispose();

      throw new SocketException(socketError);
}

Additional information: A connection attempt failed because the connected party did 
not properly respond after a period of time, or established connection failed because 
connected host has failed to respond.

An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in 
Renci.SshNet.dll.

SocketErrorCode : TimedOut

kasbst avatar May 04 '17 19:05 kasbst