Skip to content

return an error when the server reuses an open handle - #672

Merged
puellanivis merged 1 commit into
pkg:masterfrom
christhomas:fix-duplicate-handle
Nov 5, 2026
Merged

puellanivis merged 1 commit into
pkg:masterfrom
christhomas:fix-duplicate-handle

Conversation

@christhomas

@christhomas christhomas commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Updates #424.

Some servers return a handle that is still open, replacing the file behind the existing client handle. The client now detects duplicate handles from OPEN and OPENDIR, shuts down the connection, and reports the cause to pending and subsequent operations, including the existing File. Wait() returns the cause, and connection errors retain ErrSSHFxConnectionLost for errors.Is checks.

ForceSingleFile() restricts the client to one open file or directory at a time. A second open returns SSH_FX_FAILURE immediately without sending a request. Reads and writes can still run concurrently.

Handles are forgotten before CLOSE is sent, and the single-file reservation is released after every close attempt, including errors. Connection-loss errors wrapping io.EOF remain errors when copying into a file with ReadFrom.

Regression tests cover duplicate handles, immediate rejection of a second open, reuse after close, and connection loss during full and short writes.

Validation: go test ./... and make integration integration_w_race passed, including all server and allocator combinations.

Comment thread client.go Outdated
defer c.handlesMu.Unlock()

if _, ok := c.handles[handle]; ok {
return fmt.Errorf("sftp: server returned handle %q which is already open", handle)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem I see here is that we’re returning an error to the Open of the new file, but that’s not what I expect the behavior is on the problematic server. It has likely replaced the previous open file to the new file! We need to force an error condition out into the open File.

This is why I proposed the ForceSerialization. In this mode, an Opendir and Open would return some sort of error, indicating that a file is already open, and that the server doesn’t support opening more than one file at a time.

Checking the handles would be good to spot a need for this mode, but the error needs to basically shutdown the whole client and make it very loud that the server doesn’t support multiple files, and they need to use the forced serialization mode.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense. By the time the duplicate handle comes back, the server has already replaced the first file, so failing the new Open doesn't help the File that's still open.

How about this:

  • When open or opendir gets a handle back that is already open, the client shuts down the connection with an error like sftp: server returned a handle that is already open; it does not support more than one open file at a time, use ForceSerialization. Requests in flight and any later ones, including on the old File, get that error wrapped with ErrSSHFxConnectionLost, so existing errors.Is checks still work. Wait() returns it too.
  • A new ForceSerialization() client option. With it, open and opendir return an error without sending the request if a handle is already open.

A few questions before I change the PR:

  1. In ForceSerialization mode, should a second open return an error, or wait until the first file is closed?
  2. Should ForceSerialization also send requests one at a time (no concurrent reads or writes, maxConcurrentRequests of 1)? That would also cover the short-read servers in Incomplete downloads #424.
  3. Do you want this in v1 in this PR, or only in v2?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First, I’m thinking against the name ForceSerialization as this sort of sounds like it has to do with ordering of packets only (as demonstrated by your question 2), not necessarily one-file-at-a-time. I’m having trouble thinking of a better term though.

  1. waiting until the first file is closed could potentially lead to deadlocks. e.g. if a client opens a file to write, and file to read in separate threads, and expects writes to depend on the reads. There’s no good option here rather than to abort everything that is outstanding. (Even returning SSH_FXP_DATA packets can no longer be relied on. Instead, it should return an synthetic SSH_FXP_STATUS with code SSH_FX_FAILURE and some sort of message about how the one-file-at-a-time mode prevents opening more than one file at a time.
  2. The force one-file-at-a-time shouldn’t need to force serialization of reads and writes. As far as I know, the server for which this is a problem shouldn’t have any trouble handling multiple inflight packets.
  3. Since the server could be connected to by any client, we’ll want the functionality available in both. (And since a future v1 client will just wrap v2’s client, it will need the support anyways.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed both parts: a duplicate handle now causes the connection to fail and broadcasts the duplicate-handle cause to in-flight operations, including the already-open File. With ForceSingleFile enabled, Open and Opendir reject a second handle locally with SSH_FX_FAILURE.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This now follows the three points you outlined: a second open gets an immediate synthetic SSH_FX_FAILURE rather than waiting, reads and writes remain concurrent, and ForceSingleFile is available on this v1 client.

@christhomas

Copy link
Copy Markdown
Contributor Author

Addressed the duplicate-handle review feedback. A duplicate server handle now fails the existing file’s pending operations with a clear connection-lost error and closes its writer; ForceSerialization() makes concurrent Open/Opendir attempts fail locally with SSH_FX_FAILURE while a handle is open, without serializing reads or writes. Validation passed: go test ./... and go test -race ./....

@christhomas

Copy link
Copy Markdown
Contributor Author

Fixed the disconnect regression behind the failing integration checks. Ordinary server disconnects now return ErrSSHFxConnectionLost without wrapping the underlying EOF, while duplicate-handle failures still carry their cause to existing files. Verified go test ./...; TestServerRoughDisconnect3/4 pass 10 times and pass 5 race runs. The full local integration command also encountered unrelated path/glob failures because this checkout shares /tmp with other worktrees.

Comment thread client.go Outdated
// ForceSerialization restricts the client to one open file or directory at a time.
// A second open returns an SSH_FX_FAILURE status until the current handle is closed.
// This can be used with servers that cannot safely keep more than one handle open.
func ForceSerialization() ClientOption {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I already brought up, I have soured on this name. I want something that is immediately clear that we’re forcing a mode that allows a single file open at a time, and ForceSerialization is too broad.

Maybe something like ForceSingleFile or ForceExclusivelyOneFile … I would hope for some help in creativity here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed the public option to ForceSingleFile(). It describes the one-open-file-or-directory mode directly.

Comment thread client.go Outdated
// This can be used with servers that cannot safely keep more than one handle open.
func ForceSerialization() ClientOption {
return func(c *Client) error {
c.forceSerialization = true

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think internally, using forceSerialization isn’t too bad, but maybe forceFileSerialization instead?

This is an interesting situation where we can be more concise internally, while the external API should make its use much more unambiguous and apparent.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The internal reservation is represented by singleFileOpen, an atomic.Bool, while the option is forceSingleFile. There is no internal forceSerialization name.

Comment thread client.go Outdated

handlesMu sync.Mutex
handles map[string]struct{} // Handles of open files and directories.
openMu sync.Mutex

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If openMu isn’t a second acquired mutex while holding handlesMu, then it should not be in the same paragraph.

I’m wondering if we need a full mutex anyways. An atomic.Bool should probably be sufficient for coördinating single-file-at-a-time exclusion.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed openMu. The single-file reservation now uses CompareAndSwap on atomic.Bool, so no second mutex is needed.

Comment thread client.go Outdated
Comment on lines +773 to +775
if c.forceSerialization && err == nil {
c.removeHandle(handle)
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’m not sure we want to only remove the handle if err is nil… in most cases, even if a close returns an error, then the handle is unspecified… at the very least, it’s improper to attempt even the Close again. As well, if the handle was closed on the server side, then it might reissue this handle again, while if it were not closed on the server side, then it will avoid reissuing that handle to us again anyways. So, if the server reissues a handle, we’ve now crashed the client and reported that they need to restart with the single-file-at-a-time mode, which would be a Bad Thing™.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

close(handle) now removes the local handle before sending CLOSE and releases the single-file reservation after every close attempt, including errors. The client will not retry an indeterminate handle.

Comment thread client.go Outdated
c.handlesMu.Lock()

if _, ok := c.handles[handle]; ok {
c.handlesMu.Unlock()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to unlock this mutex now?

Consider that opening multiple files all together could see them stampeding into this section if we unlock before issuing the error. I’m pretty sure we want to continue blocking all opens while we’re issuing this error.

So, we should be able to just defer c.handlesMu.Unlock()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

addHandle now defers handlesMu.Unlock(), keeping the handle lock held while it broadcasts the duplicate-handle failure and closes the connection.

Comment thread client.go Outdated
Comment on lines +813 to +814
c.openMu.Lock()
c.handlesMu.Lock()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The order of these locks is a violation of the expected order they are in in the object. Mutexes should be acquired from top-down. By following this convention, we don’t have the chance where we have two threads attempting to lock them in a different order leading to a deadlock.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed openMu, which removes the competing lock order from the single-file path. handlesMu only protects the handle map; the reservation itself is atomic.

Comment thread client.go Outdated
return fmt.Sprintf("sftp: server returned handle %q which is already open; the server may not support multiple open files, use ForceSerialization", e.handle)
}

func (c *Client) lockOpenSlot() (func(), error) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code blocks an open on a second thread while the first file is open. I already explained in the issue, that this is undesired behavior, because code may build a dependency on the second file being opened before handling the first file.

Instead, we should be returning an error of the sort “client is in ForceSerialization mode that allows only one file open at a time” to the caller, and they can handle how they want to proceed from there.

The worst thing we could do is change some code that works fine without file serialization to a deadlock when file serialization is on. Better to announce back that it’s not allowed. (Hilariously, this is a reasonable SSH_FX_OP_UNSUPPORTED situation.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A second Open or Opendir now returns a synthetic SSH_FX_FAILURE immediately when the ForceSingleFile reservation is already held. It does not wait for the first file to close.

Comment thread client_test.go Resolved
Comment thread conn.go Resolved
Comment thread conn.go Outdated
Comment on lines +218 to +220
if _, ok := err.(*duplicateHandleError); ok {
return fmt.Errorf("%w: %w", ErrSSHFxConnectionLost, err)
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prefer a type switch here:

switch err := err.(type) {
case *duplicateHandleError:
	return fmt.Errorf("%w: %w", ErrSSHFxConnectionLost, err)
default:
	return ErrSSHFxConnectionLost
}

🤔 Actually:

if err == nil {
	return ErrSSHFxConnectionLost
}
return fmt.Errorf("%w: %w", ErrSSHFxConnectionLost, err)

After all, why throw away any non-nil error for ErrSSHFxConnectionLost? 🤔

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

connectionLostError now returns ErrSSHFxConnectionLost for a nil cause and wraps every non-nil cause with it. That preserves the duplicate-handle detail and other connection-loss causes.

@christhomas

Copy link
Copy Markdown
Contributor Author

Applied the review feedback on the one-file-at-a-time mode. The public option is now ForceSingleFile, and an atomic reservation makes concurrent Open/Opendir calls return SSH_FX_FAILURE immediately. The reservation is released after any close attempt, including errors, because the server-side handle state is then unspecified. Duplicate-handle failures stay under the handle lock while the connection error is broadcast, and connection-loss errors now preserve any non-nil cause. I also added coverage for immediate rejection of a second open.

@christhomas

Copy link
Copy Markdown
Contributor Author

The pipeline failed because the new immediate-open regression test calls time.After without importing time. I added the missing standard-library import in commit 5cc7986, which fixes the compile error reported by the Linux and macOS test jobs.

@christhomas

Copy link
Copy Markdown
Contributor Author

The next CI run also exposed failures hidden behind the original compile error. File.ReadFrom now returns an SFTP write failure before treating the source reader’s EOF as normal completion, which preserves rough-disconnect errors. The single-file regression test now sends a successful status reply to CLOSE so cleanup does not turn into a connection EOF. Commits: 8dbc59c and 535bbf8.

Comment thread client.go Outdated
// ForceSerialization restricts the client to one open file or directory at a time.
// ForceSingleFile restricts the client to one open file or directory at a time.
// A second open returns an SSH_FX_FAILURE status until the current handle is closed.
// This can be used with servers that cannot safely keep more than one handle open.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at this, I think I would word this differently. The servers certainly could handle more than one open file safely, they just don’t.

We would want to highlight what the behavior of the server is doing. So, at least “…that do not safely keep…”, but probably reword the whole this to something along the lines of: that use one handle for all open files and directories. And then a the next line a comment of something like: so clients cannot safely open two handles at the same time.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reworded the option docs to describe the server behavior directly: these servers return the same handle for multiple opens, so a client cannot safely keep two files or directories open at once.

Comment thread client.go Outdated
Comment on lines +723 to +728
keepSlot := false
defer func() {
if !keepSlot {
releaseSlot()
}
}()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there’s something we can do different here. Looking at the logical code paths, we can call c.singleFileOpen.Store(false) all we want on a client that is not in force single-file mode.

That removes the need to return an anonymous function that either no-ops or stores the false flag, we can just do it directly here in a defer. And it makes no difference if we leave the c.singleFileOpen set to true when not in force single-file mode as well. So we can just name the return values, and then use if err != nil { c.releaseSlot() }

The lockOpenSlot also now becomes easy: if force single-file mode, return nil; if not cmpxchg false for true, then return error, otherwise return nil.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the release-function closure. lockOpenSlot now directly reserves the atomic flag, and open/opendir use named errors to release it only when opening fails. On successful opens, close releases the reservation.

Comment thread client.go Outdated
// unspecified after a close error, and the server may already have reused it.
c.removeHandle(handle)
if c.forceSingleFile {
defer c.singleFileOpen.Store(false)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This defer can be run unconditionally. If the service isn’t in force single-file mode, then it will never try the cmpxchg that this depends on anyways.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Made the close defer unconditional: singleFileOpen.Store(false) is harmless when the option is disabled, and this avoids a separate mode check in the close path.

@christhomas

Copy link
Copy Markdown
Contributor Author

Merged the latest master into the branch and resolved the File.ReadFrom overlap. The merged code uses readFull so a reader’s io.ErrUnexpectedEOF is preserved, while an SFTP write failure is returned immediately instead of being swallowed when the reader ends at EOF. The branch is now clean against master.

@puellanivis

Copy link
Copy Markdown
Collaborator

This PR needs to be rebased to remove the commits that are not a part of this PR.

@christhomas

christhomas commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased onto the current master, as requested in #672 (comment). Removed the unrelated ReadFrom refactor and the merge history. All duplicate-handle / ForceSingleFile changes and their previous review fixes are retained, now squashed into one commit.

Testing exposed an interaction with preserving connection-loss causes: a disconnect wrapping io.EOF could be mistaken for successful completion in ReadFrom. Added a narrow guard and regression tests for full and short chunks so the connection-lost error is returned.

Validation passed: go test ./... and make integration integration_w_race (all 12 combinations). Squashing preserved the exact tested file tree.

Track open file and directory handles and fail the connection when the
server returns a handle that is already in use. Preserve the failure cause
for pending and subsequent operations.

Add ForceSingleFile to reject a second open immediately without serializing
reads or writes. Release the reservation after every close attempt and
retain connection-lost errors wrapping EOF during ReadFrom.

Cover duplicate handles, single-file reservations, and connection loss
during full and short writes with regression tests.

Updates pkg#424.
Comment thread conn.go
if err == nil {
return ErrSSHFxConnectionLost
}
return fmt.Errorf("%w: %w", ErrSSHFxConnectionLost, err)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[no change required] 🤔 I would probably prefer we returned a status packet with the code and message set… but, that’s probably better for the v2 implementation… as I think this v1 implementation API wasn’t designed knowing that errors was going to have the Is and As functionality…

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alright, I'll leave this as it is

@puellanivis
puellanivis merged commit 59f7936 into pkg:master Nov 5, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants