sshpool.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. // sshpool.go — Pool de conexiones SSH persistentes (equivalente Go del
  2. // ControlMaster/ControlPersist del JS, SPEC §7.2): UNA conexión por router,
  3. // reutilizada entre ticks del poller, con reconexión automática y backoff
  4. // exponencial (30 s base, máx 5 min) para no martillear un router caído.
  5. //
  6. // known_hosts con semántica accept-new junto a la clave (como el JS):
  7. // host desconocido → se acepta y se anota; host conocido con clave distinta
  8. // → se rechaza (posible MITM).
  9. package adapters
  10. import (
  11. "context"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "log"
  16. "net"
  17. "os"
  18. "path/filepath"
  19. "strings"
  20. "sync"
  21. "time"
  22. "github.com/gnacho/netpulse/server-go/internal/sshkey"
  23. "golang.org/x/crypto/ssh"
  24. "golang.org/x/crypto/ssh/knownhosts"
  25. )
  26. const (
  27. sshDialTimeout = 4 * time.Second // ConnectTimeout=4 del JS
  28. sshDefaultTimeout = 5 * time.Second // SSH_TIMEOUT_MS del JS
  29. sshBackoffBase = 30 * time.Second
  30. sshBackoffMax = 5 * time.Minute
  31. )
  32. // addrOf devuelve el destino `host:port` para conectar. Los callers pasan el
  33. // host ya con puerto (RouterConfig.SSHAddr, issue #605); si vienen sin puerto
  34. // (back-compat) se asume 22.
  35. func addrOf(host string) string {
  36. if _, _, err := net.SplitHostPort(host); err == nil {
  37. return host
  38. }
  39. return net.JoinHostPort(host, "22")
  40. }
  41. // poolKey es la clave del pool para un host. El mismo router llega unas veces
  42. // como "test-gw.lan" y otras como "test-gw.lan:22" (RouterConfig.SSHAddr), y
  43. // con el string tal cual el pool abría DOS conexiones al mismo equipo, una por
  44. // clave y cada una con su handshake (#1893). El puerto por defecto no
  45. // distingue hosts, así que no forma parte de la clave; uno no estándar sí.
  46. func poolKey(host string) string {
  47. if h, port, err := net.SplitHostPort(host); err == nil && port == "22" {
  48. return h
  49. }
  50. return host
  51. }
  52. // SSHPool gestiona conexiones persistentes a los routers.
  53. type SSHPool struct {
  54. keyPath string
  55. signer ssh.Signer
  56. khPath string
  57. mu sync.Mutex
  58. conns map[string]*sshConn
  59. creds map[string]sshCred
  60. closed bool
  61. dialTCP func(network, addr string, config *ssh.ClientConfig) (*ssh.Client, error)
  62. closeClient func(*ssh.Client) error
  63. }
  64. // sshCred es la credencial de contraseña registrada para un host
  65. // (#1708): las integraciones ssh con fichero compañero <slug>.sshpass
  66. // conectan por contraseña mientras la credencial esté registrada; el resto
  67. // de destinos siguen con la llave del servidor.
  68. type sshCred struct {
  69. user string
  70. password string
  71. }
  72. func (p *SSHPool) closeSSHClient(c *ssh.Client) error {
  73. if c == nil {
  74. return nil
  75. }
  76. if p.closeClient != nil {
  77. return p.closeClient(c)
  78. }
  79. return c.Close()
  80. }
  81. type sshConn struct {
  82. client *ssh.Client
  83. dialing chan struct{}
  84. failures int
  85. notUntil time.Time
  86. }
  87. // NewSSHPool crea el pool cargando la clave privada (ed25519 sin passphrase).
  88. func NewSSHPool(keyPath string) (*SSHPool, error) {
  89. pem, err := os.ReadFile(keyPath)
  90. if err != nil {
  91. return nil, fmt.Errorf("leer clave SSH: %w", err)
  92. }
  93. signer, err := ssh.ParsePrivateKey(pem)
  94. if err != nil {
  95. return nil, fmt.Errorf("parsear clave SSH: %w", err)
  96. }
  97. return &SSHPool{
  98. keyPath: keyPath,
  99. signer: signer,
  100. khPath: sshkey.KnownHostsPath(keyPath),
  101. conns: map[string]*sshConn{},
  102. creds: map[string]sshCred{},
  103. dialTCP: ssh.Dial,
  104. }, nil
  105. }
  106. // SetPassword registra (o borra, con password vacía) la credencial de
  107. // contraseña de un host (#1708). Mientras haya credencial, el dial de ese
  108. // host autentica por contraseña con el usuario dado y la llave del servidor
  109. // queda aparcada. Un cambio de credencial tira la conexión cacheada y el
  110. // backoff del host: la siguiente llamada reconecta con el valor nuevo, sin
  111. // esperar el enfriamiento de un fallo ya resuelto.
  112. func (p *SSHPool) SetPassword(host, user, password string) {
  113. host = poolKey(host)
  114. p.mu.Lock()
  115. defer p.mu.Unlock()
  116. old, had := p.creds[host]
  117. if password == "" {
  118. if !had {
  119. return
  120. }
  121. delete(p.creds, host)
  122. } else {
  123. if had && old.user == user && old.password == password {
  124. return
  125. }
  126. if p.creds == nil {
  127. p.creds = map[string]sshCred{}
  128. }
  129. p.creds[host] = sshCred{user: user, password: password}
  130. }
  131. if e := p.conns[host]; e != nil {
  132. if e.client != nil {
  133. _ = p.closeSSHClient(e.client)
  134. e.client = nil
  135. }
  136. e.failures = 0
  137. e.notUntil = time.Time{}
  138. }
  139. }
  140. // hostKeyCallback implementa accept-new sobre el known_hosts propio.
  141. func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
  142. if _, err := os.Stat(p.khPath); os.IsNotExist(err) {
  143. if err := os.MkdirAll(filepath.Dir(p.khPath), 0o700); err == nil {
  144. _ = os.WriteFile(p.khPath, nil, 0o600)
  145. }
  146. }
  147. // #2014: una sola línea ilegible hace que knownhosts.New rechace el
  148. // fichero entero, y con él el SSH a TODAS las unidades. Se descarta antes
  149. // de cargarlo: el fichero también lo escriben procesos ssh externos, que
  150. // no pueden tomar el lock del paquete.
  151. if dropped, serr := sshkey.SanitizeKnownHosts(p.khPath); serr != nil {
  152. log.Printf("ssh: saneando %s: %v", p.khPath, serr)
  153. } else if dropped > 0 {
  154. log.Printf("ssh: %d entrada(s) ilegible(s) descartada(s) de %s (#2014)", dropped, p.khPath)
  155. }
  156. checker, err := knownhosts.New(p.khPath)
  157. if err != nil {
  158. return nil, err
  159. }
  160. return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  161. err := checker(hostname, remote, key)
  162. if err == nil {
  163. return nil
  164. }
  165. var keyErr *knownhosts.KeyError
  166. if errors.As(err, &keyErr) && len(keyErr.Want) > 0 {
  167. // Clave cambiada (#603): NO se auto-acepta. Una clave distinta en
  168. // un host ya conocido es un evento de seguridad (posible MITM);
  169. // el operador debe confirmar el re-onboard explícitamente tras
  170. // verificar fuera de banda (p. ej. tras un flash del router). El
  171. // error tipado alimenta el estado "host key changed" del router.
  172. oldFP := ""
  173. if len(keyErr.Want) > 0 {
  174. oldFP = ssh.FingerprintSHA256(keyErr.Want[0].Key)
  175. }
  176. newFP := ssh.FingerprintSHA256(key)
  177. log.Printf("ssh %s: host key changed (%s -> %s); re-onboard requerido", hostname, oldFP, newFP)
  178. return &HostKeyChangedError{Host: hostname, OldFP: oldFP, NewFP: newFP}
  179. }
  180. // Host desconocido → accept-new
  181. line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
  182. return sshkey.AppendKnownHosts(p.khPath, []string{line})
  183. }, nil
  184. }
  185. // HostKeyChangedError: el host presenta una clave distinta a la registrada en
  186. // known_hosts. No se auto-acepta: la conexión se rechaza hasta que el admin
  187. // confirme el re-onboard (RemoveHostKey + siguiente sondeo hace TOFU).
  188. type HostKeyChangedError struct {
  189. Host string
  190. OldFP string
  191. NewFP string
  192. }
  193. func (e *HostKeyChangedError) Error() string {
  194. return "ssh host key changed for " + e.Host + " (" + e.OldFP + " -> " + e.NewFP + "); re-onboard required"
  195. }
  196. // SSHAuthError: el host rechazó la autenticación SSH (contraseña o llave
  197. // rechazadas por el servidor). Va con código de error propio en la API
  198. // (ssh_auth_failed, #1708) para que la UI pida revisar la contraseña en vez
  199. // de un fallo genérico de conexión.
  200. type SSHAuthError struct {
  201. Host string
  202. Err error
  203. }
  204. func (e *SSHAuthError) Error() string {
  205. return "ssh " + e.Host + ": authentication rejected: " + e.Err.Error()
  206. }
  207. func (e *SSHAuthError) Unwrap() error { return e.Err }
  208. // isSSHAuthError reconoce el rechazo de autenticación del handshake. La
  209. // librería no exporta un tipo para esto y el texto es estable en x/crypto
  210. // ("ssh: unable to authenticate, attempted methods ...").
  211. func isSSHAuthError(err error) bool {
  212. return err != nil && strings.Contains(err.Error(), "ssh: unable to authenticate")
  213. }
  214. // remoteExited distingue el fallo de un comando que SÍ se ejecutó en el router
  215. // (exit status distinto de cero: `wg: unknown command`, binario ausente) de
  216. // no haber podido ejecutar nada (credencial rechazada, host en backoff,
  217. // timeout de dial, sesión rota). Quien interprete un error para deducir una
  218. // capacidad del router tiene que preguntar esto primero: un dial fallido no
  219. // dice nada del router, solo de nuestro acceso (#2041).
  220. func remoteExited(err error) bool {
  221. var ee *ssh.ExitError
  222. return err != nil && errors.As(err, &ee)
  223. }
  224. // RemoveHostKey elimina las entradas known_hosts de un host (confirmación de
  225. // re-onboard #603). Quita las líneas previas de ese host (la lista de hosts
  226. // de una línea puede ser separada por comas); el siguiente sondeo la vuelve a
  227. // registrar con TOFU.
  228. // Los candidatos son varias formas del mismo destino (#1524): la dirección
  229. // SSH completa (SSHAddr, que Normalize convierte a [host]:puerto en puertos
  230. // no estándar) y el host pelado, porque entradas anteriores a un cambio de
  231. // puerto pueden vivir sin él. Normalizar cada campo de la línea evita depender
  232. // de cómo se escribió cada entrada.
  233. func (p *SSHPool) RemoveHostKey(hostnames ...string) error {
  234. norms := make(map[string]bool, len(hostnames))
  235. for _, h := range hostnames {
  236. if h == "" {
  237. continue
  238. }
  239. norms[knownhosts.Normalize(h)] = true
  240. }
  241. var keep []string
  242. dropped := 0
  243. // #2014: lectura y reescritura bajo el lock del paquete y con rename
  244. // atómico. Antes era ReadFile + os.WriteFile (truncate en sitio): un
  245. // append concurrente caía entre el truncate y la escritura y dejaba una
  246. // línea a medias, que tumbaba el SSH de toda la flota.
  247. err := sshkey.UpdateKnownHosts(p.khPath, func(data []byte) ([]byte, error) {
  248. for _, ln := range strings.Split(string(data), "\n") {
  249. if strings.TrimSpace(ln) == "" {
  250. continue
  251. }
  252. fields := strings.Fields(ln)
  253. if len(fields) == 0 {
  254. continue
  255. }
  256. drop := false
  257. for _, h := range strings.Split(fields[0], ",") {
  258. if norms[knownhosts.Normalize(h)] {
  259. drop = true
  260. break
  261. }
  262. }
  263. if !drop {
  264. keep = append(keep, ln)
  265. continue
  266. }
  267. dropped++
  268. }
  269. if dropped == 0 {
  270. return data, nil
  271. }
  272. return []byte(strings.Join(keep, "\n") + "\n"), nil
  273. })
  274. return err
  275. }
  276. // dial abre (o reabre) la conexión a un host respetando el backoff.
  277. // Single-flight por host: dos llamantes concurrentes comparten el mismo dial.
  278. func (p *SSHPool) dial(host string) (*ssh.Client, error) {
  279. host = poolKey(host)
  280. p.mu.Lock()
  281. if p.closed {
  282. p.mu.Unlock()
  283. return nil, errors.New("ssh pool closed")
  284. }
  285. entry := p.conns[host]
  286. if entry == nil {
  287. entry = &sshConn{}
  288. p.conns[host] = entry
  289. }
  290. if entry.client != nil {
  291. c := entry.client
  292. p.mu.Unlock()
  293. return c, nil
  294. }
  295. if entry.dialing != nil {
  296. ch := entry.dialing
  297. p.mu.Unlock()
  298. <-ch
  299. p.mu.Lock()
  300. if entry.client != nil {
  301. c := entry.client
  302. p.mu.Unlock()
  303. return c, nil
  304. }
  305. p.mu.Unlock()
  306. return nil, errors.New("ssh dial failed")
  307. }
  308. if time.Now().Before(entry.notUntil) {
  309. p.mu.Unlock()
  310. return nil, fmt.Errorf("ssh %s: en backoff tras %d fallos", host, entry.failures)
  311. }
  312. entry.dialing = make(chan struct{})
  313. p.mu.Unlock()
  314. cb, err := p.hostKeyCallback()
  315. if err != nil {
  316. p.mu.Lock()
  317. close(entry.dialing)
  318. entry.dialing = nil
  319. p.mu.Unlock()
  320. return nil, err
  321. }
  322. // Credencial registrada para este host (#1708): contraseña con el
  323. // usuario de la integración en vez de la llave del servidor. Se lee bajo
  324. // lock para no competir con SetPassword.
  325. p.mu.Lock()
  326. cred, hasCred := p.creds[host]
  327. p.mu.Unlock()
  328. cfg := &ssh.ClientConfig{
  329. User: "root",
  330. Auth: []ssh.AuthMethod{ssh.PublicKeys(p.signer)},
  331. HostKeyCallback: cb,
  332. Timeout: sshDialTimeout,
  333. }
  334. if hasCred {
  335. cfg.User = cred.user
  336. cfg.Auth = []ssh.AuthMethod{ssh.Password(cred.password)}
  337. }
  338. client, err := p.dialTCP("tcp", addrOf(host), cfg)
  339. p.mu.Lock()
  340. close(entry.dialing)
  341. entry.dialing = nil
  342. if err != nil {
  343. entry.failures++
  344. backoff := sshBackoffBase << min(entry.failures-1, 4)
  345. if backoff > sshBackoffMax {
  346. backoff = sshBackoffMax
  347. }
  348. entry.notUntil = time.Now().Add(backoff)
  349. // #1893: un "Exit before auth" en dropbear no se podía cruzar con nada,
  350. // porque el server no decía a qué host llamaba ni por qué fallaba. El
  351. // motivo real (host key, auth, timeout, red) va al log del sistema con
  352. // el host y el número de fallos; se registra el primero y cada diez
  353. // para que una unidad apagada no sature el journal.
  354. if entry.failures == 1 || entry.failures%10 == 0 {
  355. log.Printf("[netpulse:ssh] dial %s (user=%s): %v (failure %d, backoff %s)", host, cfg.User, err, entry.failures, backoff)
  356. }
  357. p.mu.Unlock()
  358. if isSSHAuthError(err) {
  359. return nil, &SSHAuthError{Host: host, Err: err}
  360. }
  361. return nil, fmt.Errorf("ssh %s: %w", host, err)
  362. }
  363. if p.closed {
  364. p.mu.Unlock()
  365. _ = p.closeSSHClient(client)
  366. return nil, errors.New("ssh pool closed")
  367. }
  368. // #1893: toda conexión NUEVA queda registrada. Si algo está marcando el
  369. // ciclo de sondeo con conexiones que mueren antes de autenticar, aquí se
  370. // ve el ritmo real de dials por host en vez de suponerlo.
  371. if entry.failures > 0 {
  372. log.Printf("[netpulse:ssh] %s: connection recovered after %d dial failures", host, entry.failures)
  373. }
  374. log.Printf("[netpulse:ssh] %s: new connection established (user=%s)", host, cfg.User)
  375. entry.client = client
  376. entry.failures = 0
  377. entry.notUntil = time.Time{}
  378. p.mu.Unlock()
  379. return client, nil
  380. }
  381. // drop invalida la conexión de un host (la próxima llamada rediala).
  382. func (p *SSHPool) drop(host string) {
  383. host = poolKey(host)
  384. p.mu.Lock()
  385. defer p.mu.Unlock()
  386. if e := p.conns[host]; e != nil && e.client != nil {
  387. // #1893: el descarte explica la reconexión siguiente; sin esta línea un
  388. // dial nuevo no se puede distinguir de una fuga de conexiones.
  389. log.Printf("[netpulse:ssh] %s: connection discarded, next command will redial", host)
  390. _ = p.closeSSHClient(e.client)
  391. e.client = nil
  392. }
  393. }
  394. // sshErrDetail (#1737) saca el motivo real de un comando remoto fallido.
  395. // session.Output descarta el stderr salvo que se le de un destino, y antes se
  396. // tiraba: un reinstall fallido solo decia "Process exited with status 1" y el
  397. // motivo (curl, wget, uci) se quedaba en el router. Se devuelve la ULTIMA
  398. // linea no vacia y recortada, que es la que explica el fallo sin arrastrar el
  399. // ruido del script entero.
  400. // mergeScriptOutput junta stdout y stderr en el orden en que se leen: primero
  401. // lo que el script escribio a la salida normal, despues sus avisos. El journal
  402. // y la caja de la UI enseñan este texto tal cual (#1894).
  403. func mergeScriptOutput(stdout, stderr string) string {
  404. if stderr == "" {
  405. return stdout
  406. }
  407. if stdout != "" && !strings.HasSuffix(stdout, "\n") {
  408. stdout += "\n"
  409. }
  410. return stdout + stderr
  411. }
  412. func sshErrDetail(stderr string) string {
  413. if stderr == "" {
  414. return ""
  415. }
  416. lines := strings.Split(strings.TrimRight(stderr, "\n"), "\n")
  417. for i := len(lines) - 1; i >= 0; i-- {
  418. line := strings.TrimSpace(lines[i])
  419. if line == "" {
  420. continue
  421. }
  422. if len(line) > 300 {
  423. line = line[:300] + "..."
  424. }
  425. return line
  426. }
  427. return ""
  428. }
  429. // Run ejecuta cmd en host con timeout (por defecto 5 s, como el JS).
  430. // Una sesión fallida por canal roto invalida la conexión (reconexión).
  431. func (p *SSHPool) Run(host, cmd string, timeout time.Duration) (string, error) {
  432. return p.run(host, cmd, nil, timeout, false)
  433. }
  434. // RunScript ejecuta un script POSIX por stdin con `sh -s` (#1737). Dropbear
  435. // limita el tamaño de cada string del paquete a MAX_CMD_LEN (9000 bytes) y
  436. // aborta la conexión con "String too long": el cliente SSH solo ve EOF, sin
  437. // exit status ni stderr. El script de reinstalación pasa de 14 KB por argv, así
  438. // que el comando completo viaja por stdin y en argv solo va `sh -s`.
  439. // #1894: el script de reinstalación cuenta todo lo que hace por stderr
  440. // (`warn()` y los `echo ... >&2`), y el pool devolvía solo stdout. Con
  441. // mergeStderr la salida que viaja al journal y a la UI lleva las dos, y se
  442. // devuelve también cuando el script falla: es justo cuando hace falta.
  443. func (p *SSHPool) RunScript(host, script string, timeout time.Duration) (string, error) {
  444. return p.run(host, "sh -s", strings.NewReader(script), timeout, true)
  445. }
  446. // run abre una sesión, ejecuta cmd (alimentando stdin si no es nil) y devuelve
  447. // stdout. Comparte el manejo de stderr, drop por canal roto y timeout entre
  448. // Run y RunScript.
  449. func (p *SSHPool) run(host, cmd string, stdin io.Reader, timeout time.Duration, mergeStderr bool) (string, error) {
  450. if timeout <= 0 {
  451. timeout = sshDefaultTimeout
  452. }
  453. client, err := p.dial(host)
  454. if err != nil {
  455. return "", err
  456. }
  457. session, err := client.NewSession()
  458. if err != nil {
  459. p.drop(host)
  460. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  461. }
  462. defer session.Close()
  463. session.Stdin = stdin
  464. type result struct {
  465. out []byte
  466. err error
  467. stderr string
  468. }
  469. ch := make(chan result, 1)
  470. go func() {
  471. var errBuf strings.Builder
  472. session.Stderr = &errBuf
  473. out, err := session.Output(cmd)
  474. ch <- result{out, err, errBuf.String()}
  475. }()
  476. select {
  477. case res := <-ch:
  478. body := string(res.out)
  479. if mergeStderr {
  480. body = mergeScriptOutput(body, res.stderr)
  481. }
  482. if res.err != nil {
  483. var ee *ssh.ExitError
  484. if !errors.As(res.err, &ee) {
  485. p.drop(host) // canal roto, no exit status
  486. }
  487. // #1894: la salida se devuelve aunque el comando falle. Antes se
  488. // tiraba, y con ella el motivo real del fallo.
  489. if msg := sshErrDetail(res.stderr); msg != "" {
  490. return body, fmt.Errorf("ssh %s: %w: %s", host, res.err, msg)
  491. }
  492. return body, fmt.Errorf("ssh %s: %w", host, res.err)
  493. }
  494. return body, nil
  495. case <-time.After(timeout):
  496. // Timeout: cerrar solo la sesión. NO dropear el cliente entero: el
  497. // pool permite sesiones concurrentes sobre el mismo router y un
  498. // comando lento no debe cortar las demás (issue #205).
  499. _ = session.Close()
  500. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  501. }
  502. }
  503. // RunCtx es Run con cancelación por contexto.
  504. func (p *SSHPool) RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error) {
  505. if timeout <= 0 {
  506. timeout = sshDefaultTimeout
  507. }
  508. client, err := p.dial(host)
  509. if err != nil {
  510. return "", err
  511. }
  512. session, err := client.NewSession()
  513. if err != nil {
  514. p.drop(host)
  515. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  516. }
  517. defer session.Close()
  518. type result struct {
  519. out []byte
  520. err error
  521. stderr string
  522. }
  523. ch := make(chan result, 1)
  524. go func() {
  525. var errBuf strings.Builder
  526. session.Stderr = &errBuf
  527. out, err := session.Output(cmd)
  528. ch <- result{out, err, errBuf.String()}
  529. }()
  530. select {
  531. case res := <-ch:
  532. if res.err != nil {
  533. var ee *ssh.ExitError
  534. if !errors.As(res.err, &ee) {
  535. p.drop(host) // canal roto, no exit status
  536. }
  537. // #1894: misma razón que en run(), la salida vuelve con el error.
  538. if msg := sshErrDetail(res.stderr); msg != "" {
  539. return string(res.out), fmt.Errorf("ssh %s: %w: %s", host, res.err, msg)
  540. }
  541. return string(res.out), fmt.Errorf("ssh %s: %w", host, res.err)
  542. }
  543. return string(res.out), nil
  544. case <-time.After(timeout):
  545. _ = session.Close()
  546. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  547. case <-ctx.Done():
  548. // Cancelación del cliente: cerrar la sesión para abortar el comando
  549. // remoto y liberar la goroutine (issue #204). Sin drop: es una
  550. // cancelación del llamador, no un fallo de la conexión.
  551. _ = session.Close()
  552. return "", ctx.Err()
  553. }
  554. }
  555. // Close cierra todas las conexiones del pool.
  556. func (p *SSHPool) Close() {
  557. p.mu.Lock()
  558. defer p.mu.Unlock()
  559. if p.closed {
  560. return
  561. }
  562. p.closed = true
  563. for _, e := range p.conns {
  564. if e.client != nil {
  565. _ = p.closeSSHClient(e.client)
  566. e.client = nil
  567. }
  568. }
  569. }
  570. func min(a, b int) int {
  571. if a < b {
  572. return a
  573. }
  574. return b
  575. }