package conn import ( "context" "errors" "fmt" "net" "os" "path/filepath" "sync" "sync/atomic" "time" "github.com/pkg/sftp" "golang.org/x/crypto/ssh" ) // DefaultHandshakeTimeout bounds TCP connect + kex + auth + SFTP init. const DefaultHandshakeTimeout = 20 * time.Second // ErrHandshakeTimeout: the server accepted TCP but did not finish the // handshake in time (N-P1-3). var ErrHandshakeTimeout = errors.New("ssh handshake timed out") // DialOptions configures how connections are established. type DialOptions struct { Prompter Prompter // HandshakeTimeout covers the whole path TCP + kex + auth + SFTP init, // excluding time spent waiting for the Prompter. Default 20s. HandshakeTimeout time.Duration // Home is the home directory for the default known_hosts and identity // files ("" = os.UserHomeDir()). Home string // KnownHostsFiles are read in order. nil means Home/.ssh/known_hosts and // /etc/ssh/ssh_known_hosts. KnownHostsFiles []string // KnownHostsWrite receives AcceptAndSave lines. "" means the first of // KnownHostsFiles (the default user file). Set to "-" for memory only. KnownHostsWrite string // AgentSocket is the ssh-agent socket. "" means $SSH_AUTH_SOCK; "-" // disables the agent. AgentSocket string // DefaultIdentityFiles are tried when the endpoint does not set // IdentitiesOnly. nil means Home/.ssh/id_{ed25519,ecdsa,rsa}. DefaultIdentityFiles []string // Warn receives non-fatal problems (host key kept in memory only, // unreadable identity file). May be nil. Warn func(msg string) } func (o DialOptions) withDefaults() DialOptions { if o.HandshakeTimeout <= 0 { o.HandshakeTimeout = DefaultHandshakeTimeout } if o.Home == "" { o.Home, _ = os.UserHomeDir() } ssh := filepath.Join(o.Home, ".ssh") if o.KnownHostsFiles == nil { o.KnownHostsFiles = []string{filepath.Join(ssh, "known_hosts"), "/etc/ssh/ssh_known_hosts"} } switch o.KnownHostsWrite { case "": if len(o.KnownHostsFiles) > 0 { o.KnownHostsWrite = o.KnownHostsFiles[0] } case "-": o.KnownHostsWrite = "" } switch o.AgentSocket { case "": o.AgentSocket = os.Getenv("SSH_AUTH_SOCK") case "-": o.AgentSocket = "" } if o.DefaultIdentityFiles == nil { for _, n := range []string{"id_ed25519", "id_ecdsa", "id_rsa"} { o.DefaultIdentityFiles = append(o.DefaultIdentityFiles, filepath.Join(ssh, n)) } } return o } // dialer establishes connections. One per Pool (i.e. per process): it owns // the shared agent connection and the session-trusted host keys. type dialer struct { opts DialOptions hosts *knownHosts agent *agentConn dials atomic.Int64 // successful TCP connects, for tests } func newDialer(o DialOptions) *dialer { o = o.withDefaults() return &dialer{ opts: o, hosts: newKnownHosts(o.KnownHostsFiles, o.KnownHostsWrite, o.Warn), agent: &agentConn{sock: o.AgentSocket}, } } func (d *dialer) close() { d.agent.close() } func (d *dialer) warnf(format string, args ...any) { if d.opts.Warn != nil { d.opts.Warn(fmt.Sprintf(format, args...)) } } // link is one established generation of a connection. type link struct { ssh *ssh.Client sftp *sftp.Client id HostIdentity serverVersion string } func (l *link) close() { l.sftp.Close() l.ssh.Close() } // deadlineGate applies the handshake deadline to the raw connection and // pauses it while the Prompter waits for the user. type deadlineGate struct { nc net.Conn timeout time.Duration mu sync.Mutex done bool // handshake finished: never touch deadlines again } func (g *deadlineGate) arm() { g.mu.Lock() defer g.mu.Unlock() if !g.done { g.nc.SetDeadline(time.Now().Add(g.timeout)) } } func (g *deadlineGate) finish() { g.mu.Lock() defer g.mu.Unlock() g.done = true g.nc.SetDeadline(time.Time{}) } func (g *deadlineGate) prompt(fn func() error) error { g.mu.Lock() if !g.done { g.nc.SetDeadline(time.Time{}) } g.mu.Unlock() defer g.arm() return fn() } // sftpOptions: concurrent reads/writes so a transfer is not one packet per // RTT (N-P1-6). var sftpOptions = []sftp.ClientOption{ sftp.UseConcurrentWrites(true), sftp.UseConcurrentReads(true), sftp.MaxConcurrentRequestsPerFile(64), } // dial connects, verifies the host key, authenticates and starts SFTP. // Cancelling ctx closes the socket at once; if the handshake still // completes, the late client is closed here, never leaked (N-P1-3). func (d *dialer) dial(ctx context.Context, ep Endpoint) (*link, error) { timeout := d.opts.HandshakeTimeout tcpTimeout := timeout if ep.ConnectTimeout > 0 && ep.ConnectTimeout < tcpTimeout { tcpTimeout = ep.ConnectTimeout } addr := ep.Addr() nd := net.Dialer{Timeout: tcpTimeout} nc, err := nd.DialContext(ctx, "tcp", addr) if err != nil { if ctx.Err() != nil { return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err()) } return nil, fmt.Errorf("connect %s: %w", ep.Label(), err) } d.dials.Add(1) gate := &deadlineGate{nc: nc, timeout: timeout} gate.arm() stop := context.AfterFunc(ctx, func() { nc.Close() }) var idMu sync.Mutex var id HostIdentity onKey := func(h HostIdentity) { idMu.Lock() defer idMu.Unlock() if id.KeyType == "" { id = h } } cfg := &ssh.ClientConfig{ User: ep.User, Auth: d.authMethods(ctx, ep, gate.prompt), HostKeyCallback: d.hosts.callback(ctx, ep, d.opts.Prompter, gate.prompt, onKey), HostKeyAlgorithms: d.hosts.algorithms(addr), } fail := func(err error) (*link, error) { stop() nc.Close() if ctx.Err() != nil { return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err()) } if errors.Is(err, os.ErrDeadlineExceeded) { return nil, fmt.Errorf("connect %s: %w after %v", ep.Label(), ErrHandshakeTimeout, timeout) } return nil, fmt.Errorf("connect %s: %w", ep.Label(), err) } sc, chans, reqs, err := ssh.NewClientConn(nc, addr, cfg) if err != nil { return fail(err) } client := ssh.NewClient(sc, chans, reqs) sc2, err := sftp.NewClient(client, sftpOptions...) if err != nil { client.Close() return fail(fmt.Errorf("sftp: %w", err)) } l := &link{ssh: client, sftp: sc2, serverVersion: string(client.ServerVersion())} if !stop() { // ctx fired while we were finishing: the caller is gone. l.close() return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err()) } gate.finish() idMu.Lock() l.id = id idMu.Unlock() return l, nil }