Keepalive with a per-reply timeout marks a frozen link Lost and closes it so hung SFTP calls fail with ErrConnLost (N-P1-2). Reconnect installs a new generation in the same Conn. Exec takes a ctx (SIGKILL + close on cancel) and an output limit (N-P2-15, N-P1-7). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
360 lines
9.5 KiB
Go
360 lines
9.5 KiB
Go
package conn
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/pkg/sftp"
|
|
"golang.org/x/crypto/ssh"
|
|
)
|
|
|
|
var (
|
|
// ErrConnLost: the connection died (keepalive timeout, network cut,
|
|
// server gone). The operation may be retried after Reconnect. sftpfs maps
|
|
// it to vfs.ErrConnLost.
|
|
ErrConnLost = errors.New("connection lost")
|
|
// ErrClosed: the connection was closed by the pool.
|
|
ErrClosed = errors.New("connection closed")
|
|
)
|
|
|
|
// State of a Conn.
|
|
type State uint32
|
|
|
|
const (
|
|
Connecting State = iota
|
|
Ready
|
|
Lost
|
|
Closed
|
|
)
|
|
|
|
func (s State) String() string {
|
|
switch s {
|
|
case Connecting:
|
|
return "connecting"
|
|
case Ready:
|
|
return "ready"
|
|
case Lost:
|
|
return "lost"
|
|
case Closed:
|
|
return "closed"
|
|
}
|
|
return fmt.Sprintf("State(%d)", uint32(s))
|
|
}
|
|
|
|
// Event reports a state change (ConnStateChanged). main forwards it to the
|
|
// UI with program.Send; it is called from connection goroutines and must not
|
|
// block.
|
|
type Event struct {
|
|
Key string // Endpoint.Key()
|
|
State State
|
|
Gen uint64 // generation the state refers to
|
|
Err error // why the connection was lost (Lost), nil otherwise
|
|
}
|
|
|
|
// Defaults for keepalive (§3.4).
|
|
const (
|
|
DefaultKeepaliveInterval = 15 * time.Second
|
|
DefaultKeepaliveTimeout = 10 * time.Second
|
|
DefaultKeepaliveMaxMiss = 2
|
|
)
|
|
|
|
// ConnOptions tune liveness detection of one connection.
|
|
type ConnOptions struct {
|
|
KeepaliveInterval time.Duration // default 15s, or Endpoint.ServerAliveInterval
|
|
KeepaliveTimeout time.Duration // per keepalive reply; default 10s
|
|
KeepaliveMaxMiss int // default 2, or Endpoint.ServerAliveCountMax
|
|
OnEvent func(Event)
|
|
}
|
|
|
|
func (o ConnOptions) withDefaults(ep Endpoint) ConnOptions {
|
|
if o.KeepaliveInterval <= 0 {
|
|
o.KeepaliveInterval = ep.ServerAliveInterval
|
|
}
|
|
if o.KeepaliveInterval <= 0 {
|
|
o.KeepaliveInterval = DefaultKeepaliveInterval
|
|
}
|
|
if o.KeepaliveTimeout <= 0 {
|
|
o.KeepaliveTimeout = DefaultKeepaliveTimeout
|
|
}
|
|
if o.KeepaliveMaxMiss <= 0 {
|
|
o.KeepaliveMaxMiss = ep.ServerAliveCountMax
|
|
}
|
|
if o.KeepaliveMaxMiss <= 0 {
|
|
o.KeepaliveMaxMiss = DefaultKeepaliveMaxMiss
|
|
}
|
|
return o
|
|
}
|
|
|
|
// ConnCaps are server capabilities detected at connect time.
|
|
type ConnCaps struct {
|
|
PosixRename bool // posix-rename@openssh.com: atomic Rename(Replace)
|
|
Fsync bool // fsync@openssh.com
|
|
StatVFS bool // statvfs@openssh.com
|
|
Hardlink bool // hardlink@openssh.com
|
|
}
|
|
|
|
// Conn is one logical connection to an endpoint. Its fields are never reset:
|
|
// the current *sftp.Client sits in an atomic pointer and, once the
|
|
// connection dies, keeps returning errors instead of disappearing (N-P0-8).
|
|
// Reconnect installs a new generation in the same Conn, so leases stay
|
|
// valid. Only the Pool closes a Conn.
|
|
type Conn struct {
|
|
d *dialer
|
|
ep Endpoint
|
|
key string
|
|
opts ConnOptions
|
|
|
|
state atomic.Uint32
|
|
gen atomic.Uint64
|
|
sftp atomic.Pointer[sftp.Client]
|
|
cur atomic.Pointer[generation]
|
|
|
|
mu sync.Mutex // serializes state transitions
|
|
lostBy error
|
|
|
|
reconnectMu sync.Mutex // one reconnect at a time
|
|
|
|
execMu sync.Mutex
|
|
execKnown bool
|
|
execOK bool
|
|
|
|
wg sync.WaitGroup // per-generation goroutines
|
|
}
|
|
|
|
// generation is one live link plus its lifetime signal.
|
|
type generation struct {
|
|
*link
|
|
gen uint64
|
|
caps ConnCaps
|
|
done chan struct{} // closed when the link has ended
|
|
}
|
|
|
|
func newGeneration(l *link, gen uint64) *generation {
|
|
g := &generation{link: l, gen: gen, done: make(chan struct{})}
|
|
_, g.caps.PosixRename = l.sftp.HasExtension("posix-rename@openssh.com")
|
|
_, g.caps.Fsync = l.sftp.HasExtension("fsync@openssh.com")
|
|
_, g.caps.StatVFS = l.sftp.HasExtension("statvfs@openssh.com")
|
|
_, g.caps.Hardlink = l.sftp.HasExtension("hardlink@openssh.com")
|
|
return g
|
|
}
|
|
|
|
// connect dials ep and returns a Ready Conn with keepalive running.
|
|
func (d *dialer) connect(ctx context.Context, ep Endpoint, o ConnOptions) (*Conn, error) {
|
|
c := &Conn{d: d, ep: ep, key: ep.Key(), opts: o.withDefaults(ep)}
|
|
c.state.Store(uint32(Connecting))
|
|
l, err := d.dial(ctx, ep)
|
|
if err != nil {
|
|
c.state.Store(uint32(Closed))
|
|
return nil, err
|
|
}
|
|
c.mu.Lock()
|
|
c.install(l)
|
|
c.mu.Unlock()
|
|
c.emit(Event{Key: c.key, State: Ready, Gen: c.gen.Load()})
|
|
return c, nil
|
|
}
|
|
|
|
// install makes l the current generation; c.mu is held.
|
|
func (c *Conn) install(l *link) {
|
|
gen := c.gen.Add(1)
|
|
g := newGeneration(l, gen)
|
|
c.cur.Store(g)
|
|
c.sftp.Store(l.sftp)
|
|
c.lostBy = nil
|
|
c.state.Store(uint32(Ready))
|
|
c.wg.Add(2)
|
|
go func() {
|
|
defer c.wg.Done()
|
|
err := l.ssh.Wait()
|
|
close(g.done)
|
|
if err == nil {
|
|
err = io.EOF
|
|
}
|
|
c.lose(g, err)
|
|
}()
|
|
go func() {
|
|
defer c.wg.Done()
|
|
c.keepalive(g)
|
|
}()
|
|
}
|
|
|
|
// lose marks generation g as Lost (if it is still current and Ready) and
|
|
// closes its SSH client, failing every pending request at once.
|
|
func (c *Conn) lose(g *generation, why error) {
|
|
c.mu.Lock()
|
|
if c.cur.Load() != g || c.State() != Ready {
|
|
c.mu.Unlock()
|
|
return
|
|
}
|
|
c.lostBy = fmt.Errorf("%w: %v", ErrConnLost, why)
|
|
c.state.Store(uint32(Lost))
|
|
err := c.lostBy
|
|
c.mu.Unlock()
|
|
g.ssh.Close()
|
|
g.sftp.Close()
|
|
c.emit(Event{Key: c.key, State: Lost, Gen: g.gen, Err: err})
|
|
}
|
|
|
|
func (c *Conn) emit(e Event) {
|
|
if c.opts.OnEvent != nil {
|
|
c.opts.OnEvent(e)
|
|
}
|
|
}
|
|
|
|
// State returns the current state.
|
|
func (c *Conn) State() State { return State(c.state.Load()) }
|
|
|
|
// Gen is the generation number; it grows with every successful Reconnect.
|
|
func (c *Conn) Gen() uint64 { return c.gen.Load() }
|
|
|
|
// Key is the pool key (Endpoint.Key()).
|
|
func (c *Conn) Key() string { return c.key }
|
|
|
|
// Endpoint returns the endpoint this connection was dialed with.
|
|
func (c *Conn) Endpoint() Endpoint { return c.ep }
|
|
|
|
// Err explains the current state: why it was lost, ErrClosed, or nil.
|
|
func (c *Conn) Err() error {
|
|
switch c.State() {
|
|
case Closed:
|
|
return ErrClosed
|
|
case Lost, Connecting:
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if c.lostBy != nil {
|
|
return c.lostBy
|
|
}
|
|
return ErrConnLost
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Client returns the SFTP client of the current generation, or an error
|
|
// wrapping ErrConnLost / ErrClosed when the connection is not Ready. The
|
|
// client is safe for concurrent use; after the connection dies its calls
|
|
// fail (map them with MapErr).
|
|
func (c *Conn) Client() (*sftp.Client, error) {
|
|
if err := c.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return c.sftp.Load(), nil
|
|
}
|
|
|
|
// SSH returns the SSH client of the current generation (for exec and port
|
|
// forwarding), with the same rules as Client.
|
|
func (c *Conn) SSH() (*ssh.Client, error) {
|
|
if err := c.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return c.cur.Load().ssh, nil
|
|
}
|
|
|
|
// Identity is the host key of the server; it does not change across
|
|
// reconnects (a different key fails the reconnect).
|
|
func (c *Conn) Identity() HostIdentity { return c.cur.Load().id }
|
|
|
|
// ServerVersion is the server's SSH version banner, e.g.
|
|
// "SSH-2.0-OpenSSH_9.6" (sftpfs uses it for the symlink argument order).
|
|
func (c *Conn) ServerVersion() string { return c.cur.Load().serverVersion }
|
|
|
|
// Caps returns the SFTP extensions of the current generation. Exec support
|
|
// is probed separately (ExecSupported) because it needs a round trip.
|
|
func (c *Conn) Caps() ConnCaps { return c.cur.Load().caps }
|
|
|
|
// MapErr turns errors caused by a dead connection into ErrConnLost (wrapped,
|
|
// so the original stays visible); other errors are returned unchanged.
|
|
func (c *Conn) MapErr(err error) error {
|
|
if err == nil || errors.Is(err, ErrConnLost) || errors.Is(err, ErrClosed) {
|
|
return err
|
|
}
|
|
if errors.Is(err, sftp.ErrSSHFxConnectionLost) || errors.Is(err, net.ErrClosed) {
|
|
return fmt.Errorf("%w: %v", ErrConnLost, err)
|
|
}
|
|
if st := c.State(); st != Ready && (errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF)) {
|
|
if st == Closed {
|
|
return fmt.Errorf("%w: %v", ErrClosed, err)
|
|
}
|
|
return fmt.Errorf("%w: %v", ErrConnLost, err)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// ErrIdentityChanged: on reconnect the server presented a different host key
|
|
// than the original connection (the Volume would no longer be the same).
|
|
var ErrIdentityChanged = errors.New("server host key differs from the original connection")
|
|
|
|
// Reconnect dials a new generation if the connection is Lost. It is a
|
|
// single attempt (Pool.Reconnect adds backoff); concurrent calls are
|
|
// serialized and a call on a Ready connection is a no-op. Operations started
|
|
// on the old generation keep failing with ErrConnLost.
|
|
func (c *Conn) Reconnect(ctx context.Context) error {
|
|
c.reconnectMu.Lock()
|
|
defer c.reconnectMu.Unlock()
|
|
c.mu.Lock()
|
|
switch c.State() {
|
|
case Closed:
|
|
c.mu.Unlock()
|
|
return ErrClosed
|
|
case Ready:
|
|
c.mu.Unlock()
|
|
return nil
|
|
}
|
|
c.state.Store(uint32(Connecting))
|
|
gen := c.gen.Load()
|
|
c.mu.Unlock()
|
|
c.emit(Event{Key: c.key, State: Connecting, Gen: gen})
|
|
|
|
l, err := c.d.dial(ctx, c.ep)
|
|
if err == nil && l.id != c.Identity() {
|
|
l.close()
|
|
err = fmt.Errorf("reconnect %s: %w (was %s, now %s)", c.ep.Label(), ErrIdentityChanged,
|
|
c.Identity().FingerprintSHA256, l.id.FingerprintSHA256)
|
|
}
|
|
c.mu.Lock()
|
|
if c.State() == Closed {
|
|
c.mu.Unlock()
|
|
if err == nil {
|
|
l.close()
|
|
}
|
|
return ErrClosed
|
|
}
|
|
if err != nil {
|
|
c.lostBy = fmt.Errorf("%w: %v", ErrConnLost, err)
|
|
c.state.Store(uint32(Lost))
|
|
lostBy := c.lostBy
|
|
c.mu.Unlock()
|
|
c.emit(Event{Key: c.key, State: Lost, Gen: gen, Err: lostBy})
|
|
return err
|
|
}
|
|
c.install(l)
|
|
gen = c.gen.Load()
|
|
c.mu.Unlock()
|
|
c.emit(Event{Key: c.key, State: Ready, Gen: gen})
|
|
return nil
|
|
}
|
|
|
|
// close shuts the connection down for good and waits for its goroutines.
|
|
// Only the Pool calls it.
|
|
func (c *Conn) close() {
|
|
c.mu.Lock()
|
|
if c.State() == Closed {
|
|
c.mu.Unlock()
|
|
return
|
|
}
|
|
c.state.Store(uint32(Closed))
|
|
g := c.cur.Load()
|
|
c.mu.Unlock()
|
|
if g != nil {
|
|
g.close()
|
|
}
|
|
c.wg.Wait()
|
|
if g != nil {
|
|
c.emit(Event{Key: c.key, State: Closed, Gen: g.gen})
|
|
}
|
|
}
|