feat(ssh): add Conn with keepalive, states, reconnect and exec (2B.3)

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>
This commit is contained in:
vrubelroman 2026-10-31 23:37:01 +03:00
parent 94002e286f
commit 351970078f
6 changed files with 968 additions and 0 deletions

360
internal/ssh/conn/conn.go Normal file
View file

@ -0,0 +1,360 @@
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})
}
}

View file

@ -0,0 +1,290 @@
package conn
import (
"context"
"errors"
"strings"
"sync"
"testing"
"time"
"vcom/internal/testutil/sshtest"
)
// events collects Conn events.
type events struct {
mu sync.Mutex
ev []Event
}
func (e *events) add(ev Event) {
e.mu.Lock()
e.ev = append(e.ev, ev)
e.mu.Unlock()
}
func (e *events) has(s State) bool {
e.mu.Lock()
defer e.mu.Unlock()
for _, ev := range e.ev {
if ev.State == s {
return true
}
}
return false
}
func (e *events) last() Event {
e.mu.Lock()
defer e.mu.Unlock()
if len(e.ev) == 0 {
return Event{}
}
return e.ev[len(e.ev)-1]
}
// fastKeepalive makes liveness tests take well under a second.
var fastKeepalive = ConnOptions{
KeepaliveInterval: 100 * time.Millisecond,
KeepaliveTimeout: 100 * time.Millisecond,
KeepaliveMaxMiss: 2,
}
func (e *env) connect(addr, password string, o ConnOptions) *Conn {
e.t.Helper()
c, err := e.dialer(DialOptions{}).connect(context.Background(), endpointFor(addr, password), o)
if err != nil {
e.t.Fatalf("connect: %v", err)
}
e.t.Cleanup(c.close)
return c
}
// Ported from the testbed (B6, TestFreezeHangs), N-P1-2: a frozen link was
// never noticed and calls hung forever. Now keepalive marks it Lost within
// interval*(miss+1)+timeout and the hung ReadDir returns ErrConnLost.
func TestFreezeDetectedAsLost(t *testing.T) {
noLeak(t, func(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
var ev events
o := fastKeepalive
o.OnEvent = ev.add
c := e.connect(px.Addr, srv.Password, o)
sc, err := c.Client()
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
if _, err := sc.ReadDir(dir); err != nil {
t.Fatal(err)
}
px.Freeze(true)
defer px.Freeze(false)
start := time.Now()
res := make(chan error, 1)
go func() {
_, err := sc.ReadDir(dir)
res <- c.MapErr(err)
}()
bound := o.KeepaliveInterval*time.Duration(o.KeepaliveMaxMiss+1) + o.KeepaliveTimeout
waitFor(t, bound+500*time.Millisecond, "state Lost", func() bool { return c.State() == Lost })
t.Logf("lost after %v (bound %v)", time.Since(start), bound)
select {
case err := <-res:
if !errors.Is(err, ErrConnLost) {
t.Errorf("hung ReadDir: err = %v, want ErrConnLost", err)
}
case <-time.After(time.Second):
t.Fatal("hung ReadDir did not return after Lost")
}
if !ev.has(Lost) || ev.last().Err == nil || !errors.Is(ev.last().Err, ErrConnLost) {
t.Errorf("events = %+v", ev.ev)
}
if _, err := c.Client(); !errors.Is(err, ErrConnLost) {
t.Errorf("Client() after Lost: %v", err)
}
})
}
func TestReconnectAfterCut(t *testing.T) {
noLeak(t, func(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
var ev events
o := ConnOptions{KeepaliveInterval: time.Hour, OnEvent: ev.add}
c := e.connect(px.Addr, srv.Password, o)
dir := t.TempDir()
gen := c.Gen()
id := c.Identity()
px.CutAfter(1)
sc, _ := c.Client()
_, err := sc.ReadDir(dir)
if err == nil {
t.Fatal("ReadDir across a cut succeeded")
}
if !errors.Is(c.MapErr(err), ErrConnLost) {
t.Errorf("err = %v, want ErrConnLost", c.MapErr(err))
}
waitFor(t, 2*time.Second, "state Lost", func() bool { return c.State() == Lost })
if err := c.Reconnect(context.Background()); err != nil {
t.Fatalf("Reconnect: %v", err)
}
if c.State() != Ready || c.Gen() != gen+1 || c.Identity() != id {
t.Errorf("after reconnect: state %v gen %d (was %d) id %+v", c.State(), c.Gen(), gen, c.Identity())
}
sc2, err := c.Client()
if err != nil {
t.Fatal(err)
}
if _, err := sc2.ReadDir(dir); err != nil {
t.Fatalf("ReadDir after reconnect: %v", err)
}
// The old generation's client stays dead.
if _, err := sc.ReadDir(dir); !errors.Is(c.MapErr(err), ErrConnLost) {
t.Errorf("old-generation client: %v", err)
}
if err := c.Reconnect(context.Background()); err != nil {
t.Errorf("Reconnect on a Ready conn must be a no-op: %v", err)
}
if !ev.has(Connecting) || ev.last().State != Ready {
t.Errorf("events = %+v", ev.ev)
}
c.close()
if err := c.Reconnect(context.Background()); !errors.Is(err, ErrClosed) {
t.Errorf("Reconnect after close: %v", err)
}
if _, err := c.Client(); !errors.Is(err, ErrClosed) {
t.Errorf("Client after close: %v", err)
}
})
}
func TestReconnectFailsWhileServerDown(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
c := e.connect(px.Addr, srv.Password, ConnOptions{KeepaliveInterval: time.Hour})
px.Freeze(true)
defer px.Freeze(false)
px.KillAll()
waitFor(t, 2*time.Second, "state Lost", func() bool { return c.State() == Lost })
c.d.opts.HandshakeTimeout = 200 * time.Millisecond
if err := c.Reconnect(context.Background()); err == nil {
t.Fatal("reconnect through a frozen link succeeded")
}
if c.State() != Lost {
t.Errorf("state = %v, want Lost", c.State())
}
}
func TestProbeMarksLost(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
c := e.connect(px.Addr, srv.Password, ConnOptions{KeepaliveInterval: time.Hour})
if err := c.Probe(context.Background(), time.Second); err != nil {
t.Fatalf("probe on a live link: %v", err)
}
px.Freeze(true)
defer px.Freeze(false)
if err := c.Probe(context.Background(), 100*time.Millisecond); !errors.Is(err, ErrConnLost) {
t.Fatalf("probe on a frozen link: %v", err)
}
if c.State() != Lost {
t.Errorf("state = %v", c.State())
}
}
// N-P2-15 / N-P1-7: Exec had no ctx and no timeout.
func TestExecCancelKills(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(100*time.Millisecond, cancel)
start := time.Now()
_, _, err := c.Exec(ctx, []string{"sleep", "60"}, 0)
if el := time.Since(start); el > time.Second {
t.Errorf("cancel took %v", el)
}
if !errors.Is(err, context.Canceled) {
t.Errorf("err = %v", err)
}
// The connection is still usable.
out, code, err := c.Exec(context.Background(), []string{"echo", "it's ok"}, 0)
if err != nil || code != 0 || string(out) != "it's ok\n" {
t.Errorf("exec after cancel: %q %d %v", out, code, err)
}
}
func TestExecOutputLimit(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
start := time.Now()
out, _, err := c.Exec(context.Background(), []string{"yes"}, 1000)
if !errors.Is(err, ErrOutputLimit) {
t.Fatalf("err = %v, want ErrOutputLimit", err)
}
if len(out) != 1000 || !strings.HasPrefix(string(out), "y\ny\n") {
t.Errorf("output: %d bytes", len(out))
}
if el := time.Since(start); el > 2*time.Second {
t.Errorf("limited exec took %v", el)
}
}
func TestExecExitStatus(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
out, code, err := c.Exec(context.Background(), []string{"sh", "-c", "echo out; echo bad >&2; exit 3"}, 0)
var ee *ExitError
if !errors.As(err, &ee) || code != 3 || ee.Code != 3 || strings.TrimSpace(ee.Stderr) != "bad" || string(out) != "out\n" {
t.Errorf("out=%q code=%d err=%v", out, code, err)
}
if !c.ExecSupported(context.Background()) {
t.Error("ExecSupported = false on a server with exec")
}
}
func TestExecSupportedNoExec(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{NoExec: true})
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
if c.ExecSupported(context.Background()) {
t.Error("ExecSupported = true with ForceCommand internal-sftp")
}
if _, err := c.Client(); err != nil {
t.Errorf("a refused exec must not break the connection: %v", err)
}
}
func TestQuote(t *testing.T) {
got := Quote([]string{"cp", "-r", "a b", "it's", "", "x;rm -rf /", "/ok/path_1.txt"})
want := `cp -r 'a b' 'it'\''s' '' 'x;rm -rf /' /ok/path_1.txt`
if got != want {
t.Errorf("Quote = %s\nwant %s", got, want)
}
}
func TestConnInfo(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
if c.Identity().FingerprintSHA256 == "" || !strings.HasPrefix(c.ServerVersion(), "SSH-2.0-") {
t.Errorf("identity %+v version %q", c.Identity(), c.ServerVersion())
}
if !c.Caps().PosixRename {
t.Logf("caps: %+v", c.Caps())
}
if c.Key() != "u@"+srv.Addr {
t.Errorf("Key = %q", c.Key())
}
}

195
internal/ssh/conn/exec.go Normal file
View file

@ -0,0 +1,195 @@
package conn
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"sync"
"golang.org/x/crypto/ssh"
)
// DefaultExecLimit caps the captured stdout of Exec (§3.4).
const DefaultExecLimit = 1 << 20
// stderrLimit caps the stderr kept for ExitError.
const stderrLimit = 4 << 10
// ErrOutputLimit: the command printed more than the limit; it was killed
// and the output truncated (N-P2-15).
var ErrOutputLimit = errors.New("command output exceeds limit")
// ExitError is a non-zero exit status.
type ExitError struct {
Code int
Stderr string // first 4 KiB
}
func (e *ExitError) Error() string {
msg := strings.TrimSpace(e.Stderr)
if msg == "" {
return fmt.Sprintf("remote command exited with status %d", e.Code)
}
return fmt.Sprintf("remote command exited with status %d: %s", e.Code, msg)
}
// Quote joins argv into a POSIX shell command line, quoting every argument
// that is not made of safe characters only.
func Quote(argv []string) string {
parts := make([]string, len(argv))
for i, a := range argv {
parts[i] = quoteArg(a)
}
return strings.Join(parts, " ")
}
func quoteArg(a string) string {
if a == "" {
return "''"
}
safe := true
for _, r := range a {
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("-_./=:,+@%", r)) {
safe = false
break
}
}
if safe {
return a
}
return "'" + strings.ReplaceAll(a, "'", `'\''`) + "'"
}
// limitWriter keeps at most limit bytes and calls overflow once when more
// arrive.
type limitWriter struct {
mu sync.Mutex
buf bytes.Buffer
limit int64
over bool
overflow func()
}
func (w *limitWriter) Write(p []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
if w.over {
return 0, ErrOutputLimit
}
room := w.limit - int64(w.buf.Len())
if int64(len(p)) <= room {
return w.buf.Write(p)
}
w.buf.Write(p[:room])
w.over = true
if w.overflow != nil {
go w.overflow()
}
return int(room), ErrOutputLimit
}
func (w *limitWriter) bytes() ([]byte, bool) {
w.mu.Lock()
defer w.mu.Unlock()
return append([]byte(nil), w.buf.Bytes()...), w.over
}
// Exec runs argv on the server (arguments are shell-quoted) and returns its
// stdout (at most limit bytes; <= 0 means DefaultExecLimit) and exit code.
// A non-zero exit returns *ExitError along with the code. Cancelling ctx
// sends SIGKILL and closes the session immediately (N-P1-7); output over
// the limit kills the command and returns ErrOutputLimit with the
// truncated output. Code is -1 when there is no exit status.
func (c *Conn) Exec(ctx context.Context, argv []string, limit int64) ([]byte, int, error) {
if len(argv) == 0 {
return nil, -1, errors.New("exec: empty command")
}
if limit <= 0 {
limit = DefaultExecLimit
}
client, err := c.SSH()
if err != nil {
return nil, -1, err
}
if err := ctx.Err(); err != nil {
return nil, -1, err
}
var (
mu sync.Mutex
sess *ssh.Session
killed bool
)
kill := func() {
mu.Lock()
defer mu.Unlock()
killed = true
if sess != nil {
sess.Signal(ssh.SIGKILL)
sess.Close()
}
}
stdout := &limitWriter{limit: limit, overflow: kill}
stderr := &limitWriter{limit: stderrLimit}
type result struct{ err error }
done := make(chan result, 1)
go func() {
s, err := client.NewSession()
if err != nil {
done <- result{c.MapErr(err)}
return
}
mu.Lock()
if killed {
mu.Unlock()
s.Close()
done <- result{context.Canceled}
return
}
sess = s
mu.Unlock()
defer s.Close()
s.Stdout, s.Stderr = stdout, stderr
done <- result{s.Run(Quote(argv))}
}()
var r result
select {
case r = <-done:
case <-ctx.Done():
kill()
return nil, -1, ctx.Err()
}
out, over := stdout.bytes()
if over {
return out, -1, fmt.Errorf("%w (%d bytes)", ErrOutputLimit, limit)
}
if r.err == nil {
return out, 0, nil
}
var ee *ssh.ExitError
if errors.As(r.err, &ee) {
se, _ := stderr.bytes()
return out, ee.ExitStatus(), &ExitError{Code: ee.ExitStatus(), Stderr: string(se)}
}
return out, -1, c.MapErr(r.err)
}
// ExecSupported reports whether the server runs commands (false for
// `ForceCommand internal-sftp`). Probed with `true`; only a definite answer
// is cached (a cancelled or lost probe is retried next time).
func (c *Conn) ExecSupported(ctx context.Context) bool {
c.execMu.Lock()
defer c.execMu.Unlock()
if c.execKnown {
return c.execOK
}
_, code, err := c.Exec(ctx, []string{"true"}, 64)
if ctx.Err() != nil || errors.Is(err, ErrConnLost) || errors.Is(err, ErrClosed) {
return false
}
c.execKnown, c.execOK = true, err == nil && code == 0
return c.execOK
}

View file

@ -105,6 +105,23 @@ func endpointFor(addr, password string) Endpoint {
return Endpoint{Alias: "test", User: "u", Host: host, Port: p, Password: password}
}
// proxy starts a proxy in front of srv and trusts srv's keys at the proxy
// address too.
func (e *env) proxy(srv *sshtest.Server) *sshtest.Proxy {
px := sshtest.NewProxy(e.t, srv.Addr)
old, _ := os.ReadFile(e.kh)
var pubs []ssh.PublicKey
for _, k := range srv.HostKeys {
pubs = append(pubs, k.PublicKey())
}
e.trust(px.Addr, pubs...)
added, _ := os.ReadFile(e.kh)
if err := os.WriteFile(e.kh, append(old, added...), 0o600); err != nil {
e.t.Fatal(err)
}
return px
}
// startTrusted starts a server whose host keys are in known_hosts.
func (e *env) startTrusted(o sshtest.Options) *sshtest.Server {
srv := sshtest.Start(e.t, o)

View file

@ -0,0 +1,83 @@
package conn
import (
"context"
"errors"
"fmt"
"time"
)
// errKeepalive is the reason recorded when keepalives go unanswered.
var errKeepalive = errors.New("no reply to keepalive")
// keepalive sends keepalive@openssh.com every interval. KeepaliveMaxMiss
// unanswered requests in a row (each waits KeepaliveTimeout) close the SSH
// client: every pending request fails at once and the state becomes Lost
// (N-P1-2). Worst-case detection: interval*(maxMiss+1) + timeout.
func (c *Conn) keepalive(g *generation) {
t := time.NewTicker(c.opts.KeepaliveInterval)
defer t.Stop()
miss := 0
for {
select {
case <-g.done:
return
case <-t.C:
}
if c.ping(g, c.opts.KeepaliveTimeout) {
miss = 0
continue
}
miss++
if miss >= c.opts.KeepaliveMaxMiss {
c.lose(g, fmt.Errorf("%w (%d × %v)", errKeepalive, miss, c.opts.KeepaliveTimeout))
return
}
}
}
// ping sends one keepalive and reports whether a reply (any reply: OpenSSH
// and x/crypto servers answer "failure" to unknown global requests) arrived
// within timeout. A request stuck on a dead link finishes when the client
// is closed (it is not tracked in c.wg: Probe may run concurrently with
// close, and WaitGroup.Add must not race with Wait).
func (c *Conn) ping(g *generation, timeout time.Duration) bool {
res := make(chan error, 1)
go func() {
_, _, err := g.ssh.SendRequest("keepalive@openssh.com", true, nil)
res <- err
}()
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case err := <-res:
return err == nil
case <-timer.C:
return false
case <-g.done:
return false
}
}
// Probe is the operation watchdog (§3.4): when an SFTP call has hung for a
// long time, sftpfs sends an out-of-band keepalive. No reply within timeout
// marks the connection Lost (closing it, so the hung call returns) and
// returns ErrConnLost. ctx only bounds the wait; it does not mark anything.
func (c *Conn) Probe(ctx context.Context, timeout time.Duration) error {
if err := c.Err(); err != nil {
return err
}
g := c.cur.Load()
ok := make(chan bool, 1)
go func() { ok <- c.ping(g, timeout) }()
select {
case alive := <-ok:
if alive {
return nil
}
c.lose(g, fmt.Errorf("%w (probe, %v)", errKeepalive, timeout))
return c.Err()
case <-ctx.Done():
return ctx.Err()
}
}

View file

@ -60,3 +60,26 @@
ещё и из `/etc/ssh/ssh_known_hosts`.
- Тест `TestKeyboardInteractiveUsesPrompter` использует свой мини-сервер в `helpers_test.go` (у `sshtest` нет KI);
`sshtest` не трогал, чтобы не выходить из своей зоны.
## 2B.3 `ssh/conn` Conn
- **`ErrConnLost`/`ErrClosed` живут в `conn`**, а не в `vfs`: `conn` не может импортировать `vfs` (его пишет
разработчик A, и `sftpfs → conn` — обратное направление). `sftpfs` (2B.5) маппит `conn.ErrConnLost` →
`vfs.ErrConnLost`. Для классификации ошибок SFTP есть `(*Conn).MapErr(err)`: `sftp.ErrSSHFxConnectionLost`,
`net.ErrClosed` → `ErrConnLost` всегда; `io.EOF`/`ErrUnexpectedEOF` — только если состояние уже не `Ready`
(EOF чтения файла — не обрыв).
- **`Conn.Close` не экспортирован** (`close()`), закрывает только Pool — по D3/§3.3 это гарантия на уровне API, а не
дисциплины.
- **Смерть обнаруживается двумя путями:** keepalive (`interval × (maxMiss+1) + timeout` в худшем случае) и
`ssh.Client.Wait()` (обрыв TCP/`CutAfter` → `Lost` сразу, без ожидания keepalive).
- **Watchdog операций** (§3.4) разделён: `Conn.Probe(ctx, timeout)` — внеочередной keepalive, нет ответа → `Lost`;
решение «вызов висит дольше 30 с» принимает `sftpfs.call` (2B.5).
- **`Reconnect` — одна попытка** на уровне `Conn` (backoff — в `Pool.Reconnect`, 2B.4); вызовы сериализуются, на
`Ready` — no-op. Новый host key при переподключении → ошибка `ErrIdentityChanged` (иначе `Volume()` = отпечаток
ключа перестал бы быть правдой). События: `Connecting` → `Ready`/`Lost`, и `Closed` при закрытии пулом.
- **Exec:** `Exec(ctx, argv, limit) ([]byte, int, error)` — аргументы экранируются (`conn.Quote`), ненулевой код →
`*ExitError{Code, Stderr(≤4 КиБ)}` вместе с кодом; превышение лимита убивает команду (`SIGKILL` + закрытие
сессии) и возвращает усечённый вывод с `ErrOutputLimit`. `Caps()` не содержит `Exec` (нужен round trip), вместо
этого `ExecSupported(ctx)` — проба `true`, кэшируется только определённый ответ.
- Тест-сервер `sshtest` не обрабатывает `signal`; отмена проверяется по клиенту (возврат < 1 с, соединение живо),
процесс `sleep` на стороне стенда добивается при остановке сервера.