Cancellation and timeouts
Every network operation in SshSharp is asynchronous and takes a CancellationToken. Apart from connecting, which has
SshClientOptions.ConnectTimeout, and SFTP, whose SftpClient.OperationTimeout catches a server that stops answering, there are
no separate timeout properties to learn: a timeout is a token that cancels itself.
When to use
Always, for anything that talks to the network. A server that accepts the TCP connection and then says nothing would otherwise be waited for until the operating system gives up, which can take minutes.
Bound connecting
Set ConnectTimeout, as ssh -o ConnectTimeout=15 does:
try
{
await using var client = await SshClient.ConnectAsync("example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = await LoadKeysAsync(cancellationToken),
HostKeyVerifier = verifier,
ConnectTimeout = TimeSpan.FromSeconds(15), // TCP, key exchange and authentication together
}, cancellationToken);
}
catch (SshException ex) when (ex.Reason == SshFailureReason.Timeout)
{
Console.WriteLine($"Gave up: {ex.Message}"); // the caller cancelling is an OperationCanceledException instead
}
It covers the whole attempt: resolving the name, the TCP connection (or the connection through Proxy), the key exchange, host key
verification and authentication, including the time your callbacks take (a host key prompt, KeyboardInteractive). Over a stream
you opened (SshClient.ConnectAsync(stream, ...)) it covers the key exchange and authentication. It ends with the connection:
commands and transfers are bounded by their own tokens.
When it passes, the attempt fails with SshException (Reason = Timeout, with a TimeoutException as its inner exception). Your
token still works alongside it, and cancelling it is an OperationCanceledException, never a timeout, so the two are easy to tell
apart. null (the default) sets no limit.
With ssh_config, ConnectTimeout applies when connecting by alias, per hop, and fails the same way. There it starts before the
identity files are loaded and covers the ProxyJump hops before the host, as ssh's does. SshConfigConnectOptions.ConnectTimeout,
when set, replaces the configured value for every host (Timeout.InfiniteTimeSpan for no limit).
ConnectionAttempts (in ssh_config, SshConfigConnectOptions.ConnectionAttempts, or SshClientOptions.ConnectionAttempts) tries
a server that could not be reached again, one second later, for a host that may be restarting. Only failures to reach it count
(refused, unreachable, timed out), never a name that does not resolve, a proxy's refusal, or a failed handshake or login, and the
attempts share the one ConnectTimeout: with ConnectTimeout 10 and ConnectionAttempts 30, connecting still gives up after ten
seconds.
// A server that is restarting refuses for a moment: try up to 5 times, a second apart, all within 30 seconds.
await using var client = await SshClient.ConnectAsync("example.com", 22, new SshClientOptions
{
UserName = "deploy",
Password = Environment.GetEnvironmentVariable("DEPLOY_PASSWORD"),
HostKeyVerifier = verifier,
ConnectionAttempts = 5,
ConnectTimeout = TimeSpan.FromSeconds(30),
}, cancellationToken);
With JumpHosts or a Proxy, the attempts are of the connection this machine makes: to the first jump host, or to the proxy.
With SshClientOptions.JumpHosts, the destination's ConnectTimeout bounds the whole chain (every hop, every tunnel, and the
destination's handshake and login), and a hop's own ConnectTimeout bounds that hop within it. Either fails the same way.
A token gives the same bound without the option, with an exception of your choosing:
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(15)); // TCP, key exchange and authentication together
try
{
await using var client = await SshClient.ConnectAsync("example.com", 22, options, timeout.Token);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
throw new TimeoutException("example.com did not answer within 15 seconds.");
}
Notes
- One limit for all of the server's addresses. A host name with several addresses (IPv6 and IPv4) is tried address by address
within the same
ConnectTimeout, so an address that does not answer can use it up before the next is tried. Where the IPv6 route is known to be broken, setAddressFamily = SshAddressFamily.Inet(see Connecting), or race the addresses withStaggeredConnectDelay(see Race the server's addresses). - The DI package maps its endpoint's
ConnectTimeoutonto this option and reports it as aTimeoutException; see ASP.NET Core and dependency injection.
Bound a command
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromMinutes(2));
// `timeout` on the server stops the program too; cancelling only closes this side's channel.
var result = await client.RunCommandAsync("timeout 110 ./run-migrations.sh", timeout.Token);
Bound SFTP requests
A token bounds one call, however long it should take. For SFTP, where a large transfer may rightly take hours, set
OperationTimeout instead: it fails a request only once the server has sent nothing at all for that long, so slow transfers go on
while a hung server is caught, including one that stops reading what you send. See
Fail when the server stops answering.
A cancelled SFTP request returns at once, even while it is being sent: a request is never cut off halfway (the server would read a
broken stream), so the send goes on in the background, and the session stays usable once it completes. A cancelled upload still
waits for the answers to the writes it already sent, for at most OperationTimeout (5 s when it is not set), to know what the
server holds and leave a file a resume can continue.
Stop the program when you give up
Cancelling closes the command's channel on this side; the connection stays usable. Without a terminal, OpenSSH does not signal the
program, which runs on until it next writes output (and gets SIGPIPE) or finishes. To stop it, send a signal before the channel
closes:
await using var session = await client.StartCommandAsync("./long-job.sh", cancellationToken: cancellationToken);
try
{
await session.StandardOutput.CopyToAsync(Stream.Null, cancellationToken);
await session.WaitForExitAsync(cancellationToken);
}
catch (OperationCanceledException)
{
// Ask the program to stop before the channel closes (OpenSSH delivers signals; some servers ignore them).
await session.SendSignalAsync("TERM", CancellationToken.None);
throw;
}
Stop when the connection ends
Link your token with client.ConnectionClosed, so waits end when either side gives up:
// Stop work when either the caller gives up or the connection ends.
using var both = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken, client.ConnectionClosed);
await using var session = await client.StartCommandAsync("tail -F /var/log/app.log", cancellationToken: both.Token);
using var reader = new StreamReader(session.StandardOutput);
while (await reader.ReadLineAsync(both.Token) is { } line)
{
Console.WriteLine(line);
}
What is thrown
| What happened | Exception |
|---|---|
| Your token was cancelled | OperationCanceledException (or TaskCanceledException, a subclass) |
SshClientOptions.ConnectTimeout, or ConnectTimeout from ssh_config, passed |
SshException, Reason = Timeout (inner TimeoutException) |
The server missed KeepAliveCountMax keep-alives |
SshException, Reason = Timeout |
An SFTP server sent nothing for SftpClient.OperationTimeout |
SshException, Reason = Timeout (inner TimeoutException) |
| The connection ended during the operation | SshException, Reason = ConnectionClosed |
The DI factory's ConnectTimeout passed |
TimeoutException |
Notes and pitfalls
- Distinguish your timeout from the caller's cancellation: with
ConnectTimeoutthey are different exceptions already; with a token of your own, catchOperationCanceledExceptionwhenthe caller's token is not cancelled, as in the token example. - Dispose
CancellationTokenSources withusing; a linked source keeps a registration on its parents until disposed. - Ping has no timeout of its own.
PingAsyncwaits for an answer until the connection ends; give it a token with a limit. - Disposal is not cancellation.
DisposeAsyncon a client ends every operation on it, which then fail withSshExceptionorObjectDisposedException. Cancel first when you want a cleanOperationCanceledException.