SftpClient Thread leak when authentication fails
Nobody has claimed this yet.
- Dominant language
- C#
- Stars
- 4.4k
- Forks
- 993
- Avg merge
- 9d 21h
- Merged PRs (30d)
- 1
Description
Using 2016.1.0
As the title says, when attempting to call Connect(), if the connection succeeds but the authentication fails, a leak happens. This can be negated by wrapping the connection in a Try/Catch and calling Disconnect if the call throws.
Here's a simple loop producing the effect (remove the Disconnect to see the increase in thread count) :
class Program
{
static void Main(string[] args)
{
var testCount = 10;
var clientInstance = new SftpClient("127.0.0.1", 22, "username", "invalidpassword");
var process = Process.GetCurrentProcess();
var threadCountBefore = process.Threads.Count;
for (var i = 0; i < testCount; i++)
{
try
{
clientInstance.Connect();
}
catch
{
// Without this, there is a thread leak
clientInstance.Disconnect();
}
}
process.Refresh();
var threadCountAfter = process.Threads.Count;
}
}
After some research, I believe it is linked to the message listener thread in Session.cs. After starting it, if the key exchange fails, the code will gracefully exit by calling Disconnect() first. Otherwise, it goes on to authentication but allows the exceptions to break the flow and exit immediately, without calling Disconnect().
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start in Session.cs and reproduce the issue with the provided Connect() loop using invalid credentials. Trace the authentication-failure path after the message listener thread starts, comparing it with the key-exchange failure path. Done means repeated failed authentication attempts no longer leak threads without requiring an explicit Disconnect().
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- networking
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100