firmware_backup_ssh.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. package httpapi
  2. // #1899: copia de config en unidades OpenWrt que NO tienen agente (solo SSH).
  3. // Hasta aquí el botón "Backup config" pedía al agente un sysupgrade -b por SSE
  4. // y el agente subía el tar.gz; una unidad solo SSH no tenía camino. El server
  5. // ya sabe hablar con esa unidad por SSH, así que el backup lo hace él y lo
  6. // guarda en el mismo almacén que lista y descarga la UI.
  7. import (
  8. "context"
  9. "errors"
  10. "net/http"
  11. "os"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "github.com/gnacho/netpulse/server-go/internal/adapters"
  16. "github.com/gnacho/netpulse/server-go/internal/auth"
  17. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  18. )
  19. // sshBackupMarker separa la salida del script de los bytes del archivo: si
  20. // algo se cuela por stdout antes, el servidor toma lo que viene detrás.
  21. const sshBackupMarker = "__netpulse_backup__"
  22. // sshConfigBackupCmd crea el tar.gz con sysupgrade, lo vuelca en crudo tras el
  23. // marcador y borra el temporal SIEMPRE: en el router /tmp es tmpfs, o sea RAM
  24. // (#1897). Nada de base64: la imagen de fábrica de OpenWrt no trae ese applet
  25. // ni instala coreutils-base64, y con él el backup fallaba con "base64: not
  26. // found" (#1935). El pool lee stdout con session.Output, que devuelve bytes sin
  27. // tocar, así que el tar.gz sobrevive al canal.
  28. const sshConfigBackupCmd = `tmp=/tmp/netpulse-config-backup-$$.tar.gz
  29. sysupgrade --create-backup "$tmp" >/dev/null 2>&1
  30. rc=$?
  31. if [ $rc -eq 0 ] && [ -s "$tmp" ]; then
  32. echo "` + sshBackupMarker + `"
  33. cat "$tmp"
  34. fi
  35. rm -f "$tmp"
  36. exit $rc`
  37. // sshConfigBackupTimeout: sysupgrade empaqueta /etc y puede tardar en unidades
  38. // lentas; el agente tiene un presupuesto parecido en su flujo.
  39. const sshConfigBackupTimeout = 120 * time.Second
  40. // routerConfigBackupSshCapable: mismo criterio que la página de firmware:
  41. // OpenWrt vanilla. Un managed-switch o un external SNMP no tienen sysupgrade.
  42. func routerConfigBackupSshCapable(rc adapters.RouterConfig) bool {
  43. return rc.Type == "" || rc.Type == "openwrt"
  44. }
  45. func configBackupSshCapable(rows []adapters.RouterConfig, id string) bool {
  46. for _, rc := range rows {
  47. if rc.ID == id {
  48. return routerConfigBackupSshCapable(rc)
  49. }
  50. }
  51. return false
  52. }
  53. // sshBackupError lleva el código HTTP de cada fallo del camino SSH, para que
  54. // el handler manual (#1899) y el backup programado (#1924) compartan la misma
  55. // implementación sin depender del texto del error.
  56. type sshBackupError struct {
  57. status int
  58. code string
  59. msg string
  60. }
  61. func (e *sshBackupError) Error() string { return e.msg }
  62. // backupConfigOverSsh crea la copia en la unidad y la guarda en el almacén que
  63. // lista y descarga la UI. Es el mismo camino para el botón manual y para el
  64. // tick semanal: una sola implementación, un solo almacén.
  65. func (s *server) backupConfigOverSsh(ctx context.Context, id, host string) (string, int, error) {
  66. out, err := s.pool.Run(host, sshConfigBackupCmd, sshConfigBackupTimeout)
  67. if err != nil {
  68. return "", 0, &sshBackupError{http.StatusBadGateway, "ssh_backup_failed", err.Error()}
  69. }
  70. data, err := decodeSshBackup(out)
  71. if err != nil {
  72. return "", 0, &sshBackupError{http.StatusBadGateway, "backup_invalid", err.Error()}
  73. }
  74. if len(data) > maxFirmwareUpload {
  75. return "", 0, &sshBackupError{http.StatusRequestEntityTooLarge, "backup_too_large", "backup mayor del tope"}
  76. }
  77. dir := s.firmwareBackupDir()
  78. if err := ensureBackupDir(dir); err != nil {
  79. return "", 0, &sshBackupError{http.StatusInternalServerError, "firmware_error", err.Error()}
  80. }
  81. name := s.firmwareBackupName(ctx, id)
  82. if err := os.WriteFile(filepath.Join(dir, name), data, backupFileMode); err != nil {
  83. return "", 0, &sshBackupError{http.StatusInternalServerError, "firmware_error", err.Error()}
  84. }
  85. pruneFirmwareBackups(dir, id)
  86. return name, len(data), nil
  87. }
  88. // decodeSshBackup: bytes del tar.gz que la unidad volcó tras el marcador. No
  89. // hay decodificador de por medio (#1935), así que el único control posible es
  90. // que lo recibido sea un gzip: cabecera 1f 8b.
  91. func decodeSshBackup(out string) ([]byte, error) {
  92. i := strings.Index(out, sshBackupMarker)
  93. if i < 0 {
  94. return nil, errors.New("the unit returned no backup")
  95. }
  96. rest := out[i+len(sshBackupMarker):]
  97. if j := strings.IndexByte(rest, '\n'); j >= 0 {
  98. rest = rest[j+1:]
  99. } else {
  100. rest = ""
  101. }
  102. if rest == "" {
  103. return nil, errors.New("the unit returned no backup")
  104. }
  105. if len(rest) < 2 || rest[0] != 0x1f || rest[1] != 0x8b {
  106. return nil, errors.New("the unit output is not a valid backup")
  107. }
  108. return []byte(rest), nil
  109. }
  110. func (s *server) registerFirmwareBackupSshRoutes(mux *http.ServeMux) {
  111. mux.Handle("POST /api/firmware-backups/{routerId}", auth.RequireAdmin(http.HandlerFunc(s.handleFirmwareBackupSsh)))
  112. }
  113. func (s *server) handleFirmwareBackupSsh(w http.ResponseWriter, r *http.Request) {
  114. // #2112: la copia se genera en la unidad por SSH antes de responder.
  115. setLongWriteDeadline(w, configBackupWriteCeiling)
  116. id := r.PathValue("routerId")
  117. if s.db == nil || s.pool == nil {
  118. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  119. return
  120. }
  121. if !configBackupSshCapable(routerstore.ListRouters(s.db.DB), id) {
  122. writeError(w, http.StatusUnprocessableEntity, "not_openwrt",
  123. "esta unidad no es un OpenWrt gestionable por SSH: su copia se hace con su propio mecanismo")
  124. return
  125. }
  126. host := s.hostOfRouter(id)
  127. if host == "" {
  128. writeError(w, http.StatusNotFound, "not_found", "no hay router con ese id")
  129. return
  130. }
  131. name, size, err := s.backupConfigOverSsh(r.Context(), id, host)
  132. if err != nil {
  133. var be *sshBackupError
  134. if errors.As(err, &be) {
  135. writeJSON(w, be.status, map[string]any{"error": be.code, "message": be.msg})
  136. return
  137. }
  138. writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
  139. return
  140. }
  141. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "name": name, "size": size})
  142. }