fix(remote): make SSHClient safe to close concurrently; refcount shared clients

- sshConn/sftpCli are immutable after Connect; Close is serialized, only
  sets an atomic closed flag and closes the clients, so concurrent calls
  get errors instead of a data race or nil dereference (N-P0-8)
- Acquire/Release user counting: panes own the client from Connect,
  mirror and remote copy/delete jobs take a reference, and leaving a host
  (goParent at root, re-mirror, exit SSH mode) releases instead of closing
  a client another pane or job still uses (N-P1-12, partial)
- ports TestCloseRace; adds a mirror-then-leave UI regression test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-31 23:14:53 +03:00
parent fbaffb4354
commit dc3d1b77fe
5 changed files with 238 additions and 63 deletions

View file

@ -12,6 +12,7 @@ import (
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pkg/sftp"
@ -23,17 +24,61 @@ import (
)
// SSHClient wraps an SSH connection and SFTP client for remote filesystem access.
//
// It is safe for concurrent use: sshConn and sftpCli are set once by Connect
// and never reassigned, Close is serialized and only flips the closed flag
// and closes the underlying clients (which then fail calls with an error
// instead of panicking). Panels and jobs sharing a client use Acquire and
// Release; the client is closed when the last user releases it (N-P0-8).
type SSHClient struct {
// Host is the SSH host configuration used to establish the connection.
Host SSHHost
sshConn *ssh.Client
sftpCli *sftp.Client
sshConn *ssh.Client // immutable after Connect
sftpCli *sftp.Client // immutable after Connect
closeMu sync.Mutex
closed atomic.Bool
users atomic.Int32
keepaliveStop chan struct{}
keepaliveWg sync.WaitGroup
}
var errNotConnected = errors.New("not connected")
// unusable reports whether the client cannot serve requests.
func (c *SSHClient) unusable() bool {
return c == nil || c.sftpCli == nil || c.sshConn == nil || c.closed.Load()
}
// Acquire registers one more user of the client (a panel or a job).
func (c *SSHClient) Acquire() {
if c != nil {
c.users.Add(1)
}
}
// Release drops one user; the last Release closes the client. Connect
// returns a client with one user (the caller).
func (c *SSHClient) Release() error {
if c == nil {
return nil
}
if c.users.Add(-1) <= 0 {
return c.Close()
}
return nil
}
// Users reports the current number of users (for tests and logs).
func (c *SSHClient) Users() int {
if c == nil {
return 0
}
return int(c.users.Load())
}
// Connect establishes an SSH connection to the remote host and opens an SFTP session.
// It uses key-based authentication if IdentityFile is set, otherwise falls back to password auth.
func Connect(host SSHHost) (*SSHClient, error) {
@ -77,6 +122,7 @@ func Connect(host SSHHost) (*SSHClient, error) {
sftpCli: sftpCli,
keepaliveStop: make(chan struct{}),
}
client.users.Store(1)
// Start keepalive goroutine — sends keepalive@openssh.com every 30s
// to prevent the SSH server from dropping the connection during inactivity.
@ -258,56 +304,56 @@ func authMethodsForHost(host SSHHost) ([]ssh.AuthMethod, error) {
// ReadDir reads the contents of a remote directory and returns os.FileInfo entries.
func (c *SSHClient) ReadDir(dirPath string) ([]os.FileInfo, error) {
if c.sftpCli == nil {
return nil, fmt.Errorf("not connected")
if c.unusable() {
return nil, errNotConnected
}
return c.sftpCli.ReadDir(dirPath)
}
// Lstat returns file information without following symlinks.
func (c *SSHClient) Lstat(path string) (os.FileInfo, error) {
if c.sftpCli == nil {
return nil, fmt.Errorf("not connected")
if c.unusable() {
return nil, errNotConnected
}
return c.sftpCli.Lstat(path)
}
// Stat returns file information following symlinks.
func (c *SSHClient) Stat(path string) (os.FileInfo, error) {
if c.sftpCli == nil {
return nil, fmt.Errorf("not connected")
if c.unusable() {
return nil, errNotConnected
}
return c.sftpCli.Stat(path)
}
// ReadLink reads the target of a symbolic link.
func (c *SSHClient) ReadLink(linkPath string) (string, error) {
if c.sftpCli == nil {
return "", fmt.Errorf("not connected")
if c.unusable() {
return "", errNotConnected
}
return c.sftpCli.ReadLink(linkPath)
}
// RealPath resolves a path to its absolute form on the remote server.
func (c *SSHClient) RealPath(p string) (string, error) {
if c.sftpCli == nil {
return "", fmt.Errorf("not connected")
if c.unusable() {
return "", errNotConnected
}
return c.sftpCli.RealPath(p)
}
// ReadFile opens a remote file for reading.
func (c *SSHClient) ReadFile(filePath string) (io.ReadCloser, error) {
if c.sftpCli == nil {
return nil, fmt.Errorf("not connected")
if c.unusable() {
return nil, errNotConnected
}
return c.sftpCli.Open(filePath)
}
// CreateFile opens a remote file for writing, creating it if it doesn't exist.
func (c *SSHClient) CreateFile(filePath string) (io.WriteCloser, error) {
if c.sftpCli == nil {
return nil, fmt.Errorf("not connected")
if c.unusable() {
return nil, errNotConnected
}
return c.sftpCli.Create(filePath)
}
@ -315,8 +361,8 @@ func (c *SSHClient) CreateFile(filePath string) (io.WriteCloser, error) {
// MkdirAll creates a remote directory and any necessary parents.
// If the directory already exists, it returns nil (no error).
func (c *SSHClient) MkdirAll(dirPath string) error {
if c.sftpCli == nil {
return fmt.Errorf("not connected")
if c.unusable() {
return errNotConnected
}
// sftp doesn't have MkdirAll, so we implement it manually
// First check if the path already exists
@ -339,71 +385,72 @@ func (c *SSHClient) MkdirAll(dirPath string) error {
// Mkdir creates a single remote directory.
func (c *SSHClient) Mkdir(dirPath string) error {
if c.sftpCli == nil {
return fmt.Errorf("not connected")
if c.unusable() {
return errNotConnected
}
return c.sftpCli.Mkdir(dirPath)
}
// Remove deletes a remote file.
func (c *SSHClient) Remove(filePath string) error {
if c.sftpCli == nil {
return fmt.Errorf("not connected")
if c.unusable() {
return errNotConnected
}
return c.sftpCli.Remove(filePath)
}
// RemoveDirectory removes a remote directory (must be empty).
func (c *SSHClient) RemoveDirectory(dirPath string) error {
if c.sftpCli == nil {
return fmt.Errorf("not connected")
if c.unusable() {
return errNotConnected
}
return c.sftpCli.RemoveDirectory(dirPath)
}
// Rename moves/renames a remote file or directory.
func (c *SSHClient) Rename(oldPath, newPath string) error {
if c.sftpCli == nil {
return fmt.Errorf("not connected")
if c.unusable() {
return errNotConnected
}
return c.sftpCli.Rename(oldPath, newPath)
}
// Close closes the SFTP session and SSH connection.
// Close closes the SFTP session and SSH connection. It is idempotent and
// safe to call concurrently with other methods, which then return errors.
func (c *SSHClient) Close() error {
if c == nil {
return nil
}
c.closeMu.Lock()
defer c.closeMu.Unlock()
if c.closed.Load() {
return nil
}
c.closed.Store(true)
// Stop the keepalive goroutine first
if c.keepaliveStop != nil {
select {
case <-c.keepaliveStop:
// already closed
default:
close(c.keepaliveStop)
}
close(c.keepaliveStop)
c.keepaliveWg.Wait()
}
var firstErr error
if c.sftpCli != nil {
if err := c.sftpCli.Close(); err != nil {
firstErr = err
}
c.sftpCli = nil
}
if c.sshConn != nil {
if err := c.sshConn.Close(); err != nil && firstErr == nil {
firstErr = err
}
c.sshConn = nil
}
return firstErr
}
// IsConnected returns true if the client has an active connection.
func (c *SSHClient) IsConnected() bool {
return c.sftpCli != nil && c.sshConn != nil
return !c.unusable()
}
// ShellQuote wraps s in single quotes so it's safe to interpolate into a
@ -417,8 +464,8 @@ func ShellQuote(s string) string {
// Exec runs a shell command on the remote server and returns combined output.
func (c *SSHClient) Exec(cmd string) ([]byte, error) {
if c.sshConn == nil {
return nil, fmt.Errorf("not connected")
if c.unusable() {
return nil, errNotConnected
}
session, err := c.sshConn.NewSession()
if err != nil {
@ -431,8 +478,8 @@ func (c *SSHClient) Exec(cmd string) ([]byte, error) {
// ExecWithProgress runs a shell command on the remote server and calls onLine
// for each line of stdout output.
func (c *SSHClient) ExecWithProgress(cmd string, onLine func(line string)) error {
if c.sshConn == nil {
return fmt.Errorf("not connected")
if c.unusable() {
return errNotConnected
}
session, err := c.sshConn.NewSession()
if err != nil {
@ -472,8 +519,8 @@ func (c *SSHClient) SameHostAs(other *SSHClient) bool {
// RemoveRecursive recursively deletes a remote file or directory.
// For directories, it walks and removes all children first.
func (c *SSHClient) RemoveRecursive(path string) error {
if c.sftpCli == nil {
return fmt.Errorf("not connected")
if c.unusable() {
return errNotConnected
}
// Lstat, not Stat: a symlink to a directory must be removed as a link.
@ -527,8 +574,8 @@ func (c *SSHClient) RemoveRecursive(path string) error {
// CopyFileToRemote copies a local file to a remote destination via SFTP.
// It creates parent directories as needed.
func (c *SSHClient) CopyFileToRemote(localPath, remotePath string) error {
if c.sftpCli == nil {
return fmt.Errorf("not connected")
if c.unusable() {
return errNotConnected
}
localFile, err := os.Open(localPath)
@ -560,8 +607,8 @@ func (c *SSHClient) CopyFileToRemote(localPath, remotePath string) error {
// CopyFileFromRemote copies a remote file to a local destination via SFTP.
// It creates parent directories as needed.
func (c *SSHClient) CopyFileFromRemote(remotePath, localPath string) error {
if c.sftpCli == nil {
return fmt.Errorf("not connected")
if c.unusable() {
return errNotConnected
}
remoteFile, err := c.sftpCli.Open(remotePath)
@ -683,10 +730,10 @@ func (c *SSHClient) copyDirFromRemote(remoteDir, localDir string, onFile func(pa
// by streaming the file contents through the local machine. Both SFTP connections
// must be active (connected).
func CopyFileBetweenRemotes(srcClient, dstClient *SSHClient, srcPath, dstPath string) error {
if srcClient.sftpCli == nil {
if srcClient.unusable() {
return fmt.Errorf("source client not connected")
}
if dstClient.sftpCli == nil {
if dstClient.unusable() {
return fmt.Errorf("destination client not connected")
}
if srcClient.SameHostAs(dstClient) && path.Clean(srcPath) == path.Clean(dstPath) {

View file

@ -4,6 +4,7 @@ import (
"os"
"path/filepath"
"testing"
"time"
)
// B1 / N-P0-3: deleting a remote symlink that points to a directory wiped
@ -69,3 +70,65 @@ func TestRemoveRecursiveFileAndDir(t *testing.T) {
}
}
}
// B5 / N-P0-8: Close() concurrently with use raced on the client fields and
// could call a method on a nil *sftp.Client.
func TestCloseRace(t *testing.T) {
_, c, dir := setup(t)
done := make(chan struct{})
panicked := make(chan any, 1)
for w := 0; w < 4; w++ {
go func() {
defer func() {
if r := recover(); r != nil {
panicked <- r
}
done <- struct{}{}
}()
for i := 0; i < 500; i++ {
c.ReadDir(dir)
c.Lstat(dir)
c.IsConnected()
c.Exec("true")
}
}()
}
time.Sleep(5 * time.Millisecond)
go c.Close()
c.Close()
for w := 0; w < 4; w++ {
<-done
}
select {
case r := <-panicked:
t.Fatalf("panic during concurrent Close: %v", r)
default:
}
if c.IsConnected() {
t.Fatal("client still reports connected after Close")
}
if _, err := c.ReadDir(dir); err == nil {
t.Fatal("ReadDir after Close must fail")
}
}
func TestAcquireReleaseClosesOnLastUser(t *testing.T) {
_, c, dir := setup(t)
if c.Users() != 1 {
t.Fatalf("Connect should return one user, got %d", c.Users())
}
c.Acquire() // e.g. mirrored pane
c.Release() // first pane leaves the host
if _, err := c.ReadDir(dir); err != nil {
t.Fatalf("client closed while still in use: %v", err)
}
c.Release() // last user
if c.IsConnected() {
t.Fatal("last Release must close the client")
}
var nilClient *SSHClient
nilClient.Acquire()
if err := nilClient.Release(); err != nil {
t.Fatal(err)
}
}

View file

@ -517,3 +517,33 @@ func TestUP01_ExistingArchiveNeedsConfirm(t *testing.T) {
t.Fatalf("temp files left: %v", leftovers)
}
}
// N-P1-12 / N-P0-8: after mirror (p) both panes share one client; leaving
// the host in one pane closed it under the other.
func TestNP112_MirrorThenLeaveKeepsOtherPaneConnected(t *testing.T) {
m := newTestModel(t, t.TempDir(), t.TempDir())
c := connectTestHost(t)
mountRemote(t, &m, PaneLeft, c, "/")
d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond))
d.Settle(settle)
d.Press("p", "p") // mirror twice: the second used to Close the shared client
d.Settle(settle)
if !c.IsConnected() {
t.Fatal("repeated mirror closed the shared client")
}
d.Press("backspace") // left pane at remote root: leave the host
d.Settle(settle)
if !c.IsConnected() {
t.Fatal("leaving the host in one pane closed the client used by the mirrored pane")
}
mm := cur(t, d)
if err := mm.reloadRemotePane(PaneRight, ""); err != nil {
t.Fatalf("mirrored pane broken: %v", err)
}
d.Press("tab", "backspace") // the mirrored pane leaves too
d.Settle(settle)
if c.IsConnected() {
t.Fatal("client should be closed once no pane uses it")
}
}

View file

@ -2064,9 +2064,13 @@ func (m *Model) goParent() error {
// At remote root — pop remote, disconnect, and return to host list
log.Printf("[NAV] goParent — closing remote mount, returning to host list")
pane.PopRemote()
mount.Client.Close()
// Release, not Close: the other pane (mirror) or a background
// job may still use this client (N-P0-8, N-P1-12).
mount.Client.Release()
if m.ssh != nil {
m.ssh.connectedHosts[mount.Host.Name] = false
if mount.Client.Users() == 0 {
m.ssh.connectedHosts[mount.Host.Name] = false
}
entries := buildSSHHostEntries(m.ssh.store, m.ssh.connectedHosts)
pane.SetEntries(entries, "")
pane.Path = "ssh://"
@ -2603,14 +2607,10 @@ func (m *Model) handleMirrorPane() (tea.Model, tea.Cmd) {
// If active is in a remote mount, clone the remote stack to passive
if mount, ok := active.CurrentRemote(); ok {
// If passive already has a remote connection, clean it up first
if existingMount, exists := passive.CurrentRemote(); exists {
existingMount.Client.Close()
passive.PopRemote()
}
// Clone the mount — don't clone the client, open a new connection
// For simplicity, just set the path; the mount will reconnect on reload
passive.ClearRemotes()
// The passive pane shares the client: take a reference first, then
// drop the passive pane's old mounts (which may be the same client).
mount.Client.Acquire()
releaseMounts(passive.ClearRemotes())
passive.Remote = append(passive.Remote, mount)
passive.Path = active.Path
if err := m.reloadRemotePane(passive.ID, ""); err != nil {
@ -2626,7 +2626,7 @@ func (m *Model) handleMirrorPane() (tea.Model, tea.Cmd) {
}
} else {
// Local directory — simple path copy
passive.ClearRemotes()
releaseMounts(passive.ClearRemotes())
passive.Path = targetPath
if err := m.reloadPane(passive.ID, ""); err != nil {
m.status = fmt.Sprintf("Mirror failed: %v", err)
@ -5778,6 +5778,13 @@ func localFileActionAllowed(p *BrowserPane) error {
return nil
}
// releaseMounts drops the pane's reference on each mount's client.
func releaseMounts(mounts []RemoteMount) {
for _, mt := range mounts {
mt.Client.Release()
}
}
func isArchiveEntry(entry vfs.Entry) bool {
return !entry.IsDir && !entry.IsParent && entry.Category() == "archive"
}
@ -5974,7 +5981,7 @@ func (m *Model) exitSSHMode() (tea.Model, tea.Cmd) {
m.ssh.connectedHosts[mount.Host.Name] = false
}
pane.PopRemote()
mount.Client.Close()
mount.Client.Release()
}
// Close all stored active clients (connections kept alive in host list)
@ -6325,9 +6332,13 @@ func (m *Model) startRemoteDeleteJob(sources []string, client *remote.SSHClient)
log.Printf("[ACTION] startRemoteDeleteJob: job=%d sources=%v", jobID, sources)
// The job holds its own reference so leaving the host in the pane does
// not close the connection under it.
client.Acquire()
return tea.Batch(
func() tea.Msg {
go func() {
defer client.Release()
for i, sourcePath := range sources {
select {
case <-ctx.Done():
@ -6414,9 +6425,13 @@ func (m *Model) startRemoteCopyJob(kind fileOpKind, sources []string, targetDir
log.Printf("[JOB] startRemoteCopyJob: id=%d kind=%d sources=%d targetDir=%s srcRemote=%v dstRemote=%v stats={files=%d bytes=%d}",
jobID, kind, len(sources), targetDir, sourceIsRemote, targetIsRemote, stats.FilesTotal, stats.BytesTotal)
srcClient.Acquire()
dstClient.Acquire()
return tea.Batch(
func() tea.Msg {
go func() {
defer srcClient.Release()
defer dstClient.Release()
doneFiles := 0
var doneBytes int64
totalFiles := 0

View file

@ -18,3 +18,23 @@
0.4. В `Makefile` стоит `.NOTPARALLEL`, потому что `vendor-check` перезаписывает `vendor/`, а `make -j`
(у разработчика `make` — алиас на `make -j24`) запускал сборку параллельно с этим. `release.yml` вызывает
`ci.yml` через `workflow_call` вместо копии шагов.
## Этап 1
- **1.1.** Кроме строки статуса: локальный `vfs.MakeDir` теперь падает на существующем имени (`os.Mkdir` для
последнего компонента). Иначе приёмочный сценарий «F7 с существующим именем → ошибка» невозможен: `MkdirAll`
молча «успевал». Строка фильтра занимает тот же слот, что и статус, — раньше она добавляла строку сверх высоты
терминала. Уровень сообщения (ошибка/предупреждение) определяется по словам в тексте: статус — свободная строка в
~200 местах, протаскивать уровень везде в хотфиксе не стоит (в новом UI будет `notify` с уровнем, §7.6).
- **1.2.** Для теста N-P0-2 введён хук `startProcess` (подставной opener для `xdg-open`); `ExecProcess` (редактор,
запуск) ловит teadriver (`Execs()`), не запуская. Дополнительно заблокированы mkdir в списке хостов `ssh://` и
copy/move *из* списка хостов (та же причина, что N-P2-10).
- **1.7.** Помимо проверки «архив = источник / внутри источника» `CreateArchive` пишет во временный файл рядом с
целью и делает rename только при успехе: частичный архив при ошибке/отмене не остаётся, старый архив при неудаче
не портится (из «как исправлять» U-P0-1). Правка в одном месте (`CreateArchive`), функции форматов не тронуты.
- **1.8.** Вместо `atomic.Pointer` поля `sshConn`/`sftpCli` сделаны неизменяемыми после `Connect`: `Close` под
mutex только выставляет `atomic.Bool closed` и закрывает клиентов (pkg/sftp и x/crypto/ssh после Close
возвращают ошибки, а не паникуют). Это даёт ту же гарантию (нет записи полей → нет гонки, нет nil-разыменования)
меньшей правкой. Счётчик пользователей: `Connect` возвращает клиента с 1 пользователем (панель), `Acquire` —
mirror и remote copy/delete джобы, `Release` вместо `Close` в `goParent`, mirror, `exitSSHMode`; последний
`Release` закрывает. Превью и dir-size по-прежнему без ссылки — после закрытия они получают ошибку, не панику.