sshpool.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. // RemoveHostKey elimina las entradas known_hosts de un host (confirmación de
  215. // re-onboard #603). Quita las líneas previas de ese host (la lista de hosts
  216. // de una línea puede ser separada por comas); el siguiente sondeo la vuelve a
  217. // registrar con TOFU.
  218. // Los candidatos son varias formas del mismo destino (#1524): la dirección
  219. // SSH completa (SSHAddr, que Normalize convierte a [host]:puerto en puertos
  220. // no estándar) y el host pelado, porque entradas anteriores a un cambio de
  221. // puerto pueden vivir sin él. Normalizar cada campo de la línea evita depender
  222. // de cómo se escribió cada entrada.
  223. func (p *SSHPool) RemoveHostKey(hostnames ...string) error {
  224. norms := make(map[string]bool, len(hostnames))
  225. for _, h := range hostnames {
  226. if h == "" {
  227. continue
  228. }
  229. norms[knownhosts.Normalize(h)] = true
  230. }
  231. var keep []string
  232. dropped := 0
  233. // #2014: lectura y reescritura bajo el lock del paquete y con rename
  234. // atómico. Antes era ReadFile + os.WriteFile (truncate en sitio): un
  235. // append concurrente caía entre el truncate y la escritura y dejaba una
  236. // línea a medias, que tumbaba el SSH de toda la flota.
  237. err := sshkey.UpdateKnownHosts(p.khPath, func(data []byte) ([]byte, error) {
  238. for _, ln := range strings.Split(string(data), "\n") {
  239. if strings.TrimSpace(ln) == "" {
  240. continue
  241. }
  242. fields := strings.Fields(ln)
  243. if len(fields) == 0 {
  244. continue
  245. }
  246. drop := false
  247. for _, h := range strings.Split(fields[0], ",") {
  248. if norms[knownhosts.Normalize(h)] {
  249. drop = true
  250. break
  251. }
  252. }
  253. if !drop {
  254. keep = append(keep, ln)
  255. continue
  256. }
  257. dropped++
  258. }
  259. if dropped == 0 {
  260. return data, nil
  261. }
  262. return []byte(strings.Join(keep, "\n") + "\n"), nil
  263. })
  264. return err
  265. }
  266. // dial abre (o reabre) la conexión a un host respetando el backoff.
  267. // Single-flight por host: dos llamantes concurrentes comparten el mismo dial.
  268. func (p *SSHPool) dial(host string) (*ssh.Client, error) {
  269. host = poolKey(host)
  270. p.mu.Lock()
  271. if p.closed {
  272. p.mu.Unlock()
  273. return nil, errors.New("ssh pool closed")
  274. }
  275. entry := p.conns[host]
  276. if entry == nil {
  277. entry = &sshConn{}
  278. p.conns[host] = entry
  279. }
  280. if entry.client != nil {
  281. c := entry.client
  282. p.mu.Unlock()
  283. return c, nil
  284. }
  285. if entry.dialing != nil {
  286. ch := entry.dialing
  287. p.mu.Unlock()
  288. <-ch
  289. p.mu.Lock()
  290. if entry.client != nil {
  291. c := entry.client
  292. p.mu.Unlock()
  293. return c, nil
  294. }
  295. p.mu.Unlock()
  296. return nil, errors.New("ssh dial failed")
  297. }
  298. if time.Now().Before(entry.notUntil) {
  299. p.mu.Unlock()
  300. return nil, fmt.Errorf("ssh %s: en backoff tras %d fallos", host, entry.failures)
  301. }
  302. entry.dialing = make(chan struct{})
  303. p.mu.Unlock()
  304. cb, err := p.hostKeyCallback()
  305. if err != nil {
  306. p.mu.Lock()
  307. close(entry.dialing)
  308. entry.dialing = nil
  309. p.mu.Unlock()
  310. return nil, err
  311. }
  312. // Credencial registrada para este host (#1708): contraseña con el
  313. // usuario de la integración en vez de la llave del servidor. Se lee bajo
  314. // lock para no competir con SetPassword.
  315. p.mu.Lock()
  316. cred, hasCred := p.creds[host]
  317. p.mu.Unlock()
  318. cfg := &ssh.ClientConfig{
  319. User: "root",
  320. Auth: []ssh.AuthMethod{ssh.PublicKeys(p.signer)},
  321. HostKeyCallback: cb,
  322. Timeout: sshDialTimeout,
  323. }
  324. if hasCred {
  325. cfg.User = cred.user
  326. cfg.Auth = []ssh.AuthMethod{ssh.Password(cred.password)}
  327. }
  328. client, err := p.dialTCP("tcp", addrOf(host), cfg)
  329. p.mu.Lock()
  330. close(entry.dialing)
  331. entry.dialing = nil
  332. if err != nil {
  333. entry.failures++
  334. backoff := sshBackoffBase << min(entry.failures-1, 4)
  335. if backoff > sshBackoffMax {
  336. backoff = sshBackoffMax
  337. }
  338. entry.notUntil = time.Now().Add(backoff)
  339. // #1893: un "Exit before auth" en dropbear no se podía cruzar con nada,
  340. // porque el server no decía a qué host llamaba ni por qué fallaba. El
  341. // motivo real (host key, auth, timeout, red) va al log del sistema con
  342. // el host y el número de fallos; se registra el primero y cada diez
  343. // para que una unidad apagada no sature el journal.
  344. if entry.failures == 1 || entry.failures%10 == 0 {
  345. log.Printf("[netpulse:ssh] dial %s (user=%s): %v (failure %d, backoff %s)", host, cfg.User, err, entry.failures, backoff)
  346. }
  347. p.mu.Unlock()
  348. if isSSHAuthError(err) {
  349. return nil, &SSHAuthError{Host: host, Err: err}
  350. }
  351. return nil, fmt.Errorf("ssh %s: %w", host, err)
  352. }
  353. if p.closed {
  354. p.mu.Unlock()
  355. _ = p.closeSSHClient(client)
  356. return nil, errors.New("ssh pool closed")
  357. }
  358. // #1893: toda conexión NUEVA queda registrada. Si algo está marcando el
  359. // ciclo de sondeo con conexiones que mueren antes de autenticar, aquí se
  360. // ve el ritmo real de dials por host en vez de suponerlo.
  361. if entry.failures > 0 {
  362. log.Printf("[netpulse:ssh] %s: connection recovered after %d dial failures", host, entry.failures)
  363. }
  364. log.Printf("[netpulse:ssh] %s: new connection established (user=%s)", host, cfg.User)
  365. entry.client = client
  366. entry.failures = 0
  367. entry.notUntil = time.Time{}
  368. p.mu.Unlock()
  369. return client, nil
  370. }
  371. // drop invalida la conexión de un host (la próxima llamada rediala).
  372. func (p *SSHPool) drop(host string) {
  373. host = poolKey(host)
  374. p.mu.Lock()
  375. defer p.mu.Unlock()
  376. if e := p.conns[host]; e != nil && e.client != nil {
  377. // #1893: el descarte explica la reconexión siguiente; sin esta línea un
  378. // dial nuevo no se puede distinguir de una fuga de conexiones.
  379. log.Printf("[netpulse:ssh] %s: connection discarded, next command will redial", host)
  380. _ = p.closeSSHClient(e.client)
  381. e.client = nil
  382. }
  383. }
  384. // sshErrDetail (#1737) saca el motivo real de un comando remoto fallido.
  385. // session.Output descarta el stderr salvo que se le de un destino, y antes se
  386. // tiraba: un reinstall fallido solo decia "Process exited with status 1" y el
  387. // motivo (curl, wget, uci) se quedaba en el router. Se devuelve la ULTIMA
  388. // linea no vacia y recortada, que es la que explica el fallo sin arrastrar el
  389. // ruido del script entero.
  390. // mergeScriptOutput junta stdout y stderr en el orden en que se leen: primero
  391. // lo que el script escribio a la salida normal, despues sus avisos. El journal
  392. // y la caja de la UI enseñan este texto tal cual (#1894).
  393. func mergeScriptOutput(stdout, stderr string) string {
  394. if stderr == "" {
  395. return stdout
  396. }
  397. if stdout != "" && !strings.HasSuffix(stdout, "\n") {
  398. stdout += "\n"
  399. }
  400. return stdout + stderr
  401. }
  402. func sshErrDetail(stderr string) string {
  403. if stderr == "" {
  404. return ""
  405. }
  406. lines := strings.Split(strings.TrimRight(stderr, "\n"), "\n")
  407. for i := len(lines) - 1; i >= 0; i-- {
  408. line := strings.TrimSpace(lines[i])
  409. if line == "" {
  410. continue
  411. }
  412. if len(line) > 300 {
  413. line = line[:300] + "..."
  414. }
  415. return line
  416. }
  417. return ""
  418. }
  419. // Run ejecuta cmd en host con timeout (por defecto 5 s, como el JS).
  420. // Una sesión fallida por canal roto invalida la conexión (reconexión).
  421. func (p *SSHPool) Run(host, cmd string, timeout time.Duration) (string, error) {
  422. return p.run(host, cmd, nil, timeout, false)
  423. }
  424. // RunScript ejecuta un script POSIX por stdin con `sh -s` (#1737). Dropbear
  425. // limita el tamaño de cada string del paquete a MAX_CMD_LEN (9000 bytes) y
  426. // aborta la conexión con "String too long": el cliente SSH solo ve EOF, sin
  427. // exit status ni stderr. El script de reinstalación pasa de 14 KB por argv, así
  428. // que el comando completo viaja por stdin y en argv solo va `sh -s`.
  429. // #1894: el script de reinstalación cuenta todo lo que hace por stderr
  430. // (`warn()` y los `echo ... >&2`), y el pool devolvía solo stdout. Con
  431. // mergeStderr la salida que viaja al journal y a la UI lleva las dos, y se
  432. // devuelve también cuando el script falla: es justo cuando hace falta.
  433. func (p *SSHPool) RunScript(host, script string, timeout time.Duration) (string, error) {
  434. return p.run(host, "sh -s", strings.NewReader(script), timeout, true)
  435. }
  436. // run abre una sesión, ejecuta cmd (alimentando stdin si no es nil) y devuelve
  437. // stdout. Comparte el manejo de stderr, drop por canal roto y timeout entre
  438. // Run y RunScript.
  439. func (p *SSHPool) run(host, cmd string, stdin io.Reader, timeout time.Duration, mergeStderr bool) (string, error) {
  440. if timeout <= 0 {
  441. timeout = sshDefaultTimeout
  442. }
  443. client, err := p.dial(host)
  444. if err != nil {
  445. return "", err
  446. }
  447. session, err := client.NewSession()
  448. if err != nil {
  449. p.drop(host)
  450. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  451. }
  452. defer session.Close()
  453. session.Stdin = stdin
  454. type result struct {
  455. out []byte
  456. err error
  457. stderr string
  458. }
  459. ch := make(chan result, 1)
  460. go func() {
  461. var errBuf strings.Builder
  462. session.Stderr = &errBuf
  463. out, err := session.Output(cmd)
  464. ch <- result{out, err, errBuf.String()}
  465. }()
  466. select {
  467. case res := <-ch:
  468. body := string(res.out)
  469. if mergeStderr {
  470. body = mergeScriptOutput(body, res.stderr)
  471. }
  472. if res.err != nil {
  473. var ee *ssh.ExitError
  474. if !errors.As(res.err, &ee) {
  475. p.drop(host) // canal roto, no exit status
  476. }
  477. // #1894: la salida se devuelve aunque el comando falle. Antes se
  478. // tiraba, y con ella el motivo real del fallo.
  479. if msg := sshErrDetail(res.stderr); msg != "" {
  480. return body, fmt.Errorf("ssh %s: %w: %s", host, res.err, msg)
  481. }
  482. return body, fmt.Errorf("ssh %s: %w", host, res.err)
  483. }
  484. return body, nil
  485. case <-time.After(timeout):
  486. // Timeout: cerrar solo la sesión. NO dropear el cliente entero: el
  487. // pool permite sesiones concurrentes sobre el mismo router y un
  488. // comando lento no debe cortar las demás (issue #205).
  489. _ = session.Close()
  490. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  491. }
  492. }
  493. // RunCtx es Run con cancelación por contexto.
  494. func (p *SSHPool) RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error) {
  495. if timeout <= 0 {
  496. timeout = sshDefaultTimeout
  497. }
  498. client, err := p.dial(host)
  499. if err != nil {
  500. return "", err
  501. }
  502. session, err := client.NewSession()
  503. if err != nil {
  504. p.drop(host)
  505. return "", fmt.Errorf("ssh %s: session: %w", host, err)
  506. }
  507. defer session.Close()
  508. type result struct {
  509. out []byte
  510. err error
  511. stderr string
  512. }
  513. ch := make(chan result, 1)
  514. go func() {
  515. var errBuf strings.Builder
  516. session.Stderr = &errBuf
  517. out, err := session.Output(cmd)
  518. ch <- result{out, err, errBuf.String()}
  519. }()
  520. select {
  521. case res := <-ch:
  522. if res.err != nil {
  523. var ee *ssh.ExitError
  524. if !errors.As(res.err, &ee) {
  525. p.drop(host) // canal roto, no exit status
  526. }
  527. // #1894: misma razón que en run(), la salida vuelve con el error.
  528. if msg := sshErrDetail(res.stderr); msg != "" {
  529. return string(res.out), fmt.Errorf("ssh %s: %w: %s", host, res.err, msg)
  530. }
  531. return string(res.out), fmt.Errorf("ssh %s: %w", host, res.err)
  532. }
  533. return string(res.out), nil
  534. case <-time.After(timeout):
  535. _ = session.Close()
  536. return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
  537. case <-ctx.Done():
  538. // Cancelación del cliente: cerrar la sesión para abortar el comando
  539. // remoto y liberar la goroutine (issue #204). Sin drop: es una
  540. // cancelación del llamador, no un fallo de la conexión.
  541. _ = session.Close()
  542. return "", ctx.Err()
  543. }
  544. }
  545. // Close cierra todas las conexiones del pool.
  546. func (p *SSHPool) Close() {
  547. p.mu.Lock()
  548. defer p.mu.Unlock()
  549. if p.closed {
  550. return
  551. }
  552. p.closed = true
  553. for _, e := range p.conns {
  554. if e.client != nil {
  555. _ = p.closeSSHClient(e.client)
  556. e.client = nil
  557. }
  558. }
  559. }
  560. func min(a, b int) int {
  561. if a < b {
  562. return a
  563. }
  564. return b
  565. }