firmware_upload.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. // firmware_upload.go — selector de método por unidad e imagen subida desde
  2. // local (#1414). La imagen se guarda en el server y el flujo clásico la sirve
  3. // al agente para su descarga (el agente ya descarga por URL con sha256, sin
  4. // cambios de protocolo).
  5. package httpapi
  6. import (
  7. "context"
  8. "crypto/sha256"
  9. "encoding/hex"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "net/http"
  14. "os"
  15. "path/filepath"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "unicode"
  21. "github.com/gnacho/netpulse/server-go/internal/auth"
  22. "github.com/gnacho/netpulse/server-go/internal/firmware"
  23. )
  24. // maxFirmwareUpload: tope de una imagen subida (las de OpenWrt rondan 8-25 MB;
  25. // 100 MB da margen para perfiles con muchos paquetes empaquetados).
  26. const maxFirmwareUpload = 100 << 20
  27. func validFirmwareID(id string) bool {
  28. if id == "" || id == "." || id == ".." {
  29. return false
  30. }
  31. if strings.ContainsAny(id, `/\`) || strings.Contains(id, "..") {
  32. return false
  33. }
  34. return filepath.Base(id) == id
  35. }
  36. func firmwareUploadPath(dir, id string) (string, bool) {
  37. if !validFirmwareID(id) {
  38. return "", false
  39. }
  40. dest := filepath.Join(dir, id+".bin")
  41. rel, err := filepath.Rel(dir, dest)
  42. if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
  43. return "", false
  44. }
  45. return dest, true
  46. }
  47. func (s *server) registerFirmwareUploadRoutes(mux *http.ServeMux) {
  48. if s.firmware == nil {
  49. return
  50. }
  51. // PUT method: método preferido de la tarjeta (auto/owut/url/upload).
  52. mux.Handle("PUT /api/firmware-upgrades/{routerId}/method", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  53. id := r.PathValue("routerId")
  54. var body struct {
  55. Method string `json:"method"`
  56. }
  57. if st := readJSONBody(w, r, &body); st != 0 {
  58. return
  59. }
  60. if !firmware.ValidMethod(body.Method) {
  61. writeError(w, http.StatusBadRequest, "invalid_method", "method debe ser auto, owut, url o upload")
  62. return
  63. }
  64. if err := firmware.SaveMethod(s.db.DB, id, body.Method); err != nil {
  65. writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
  66. return
  67. }
  68. writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
  69. })))
  70. // POST image: sube una imagen (multipart, campo "image") y la deja como
  71. // target del flujo clásico: URL servida por este mismo server (alcanzable
  72. // por el agente vía NETPULSE_AGENT_URL/PublicURL) + checksum calculado.
  73. mux.Handle("POST /api/firmware-upgrades/{routerId}/image", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  74. id := r.PathValue("routerId")
  75. if !validFirmwareID(id) {
  76. writeError(w, http.StatusBadRequest, "invalid_router_id")
  77. return
  78. }
  79. r.Body = http.MaxBytesReader(w, r.Body, maxFirmwareUpload+(1<<20))
  80. if err := r.ParseMultipartForm(maxFirmwareUpload); err != nil {
  81. if r.MultipartForm != nil {
  82. r.MultipartForm.RemoveAll()
  83. }
  84. var tooLarge *http.MaxBytesError
  85. if errors.As(err, &tooLarge) {
  86. writeError(w, http.StatusRequestEntityTooLarge, "image_too_large", fmt.Sprintf("imagen mayor de %d MB", maxFirmwareUpload>>20))
  87. return
  88. }
  89. writeError(w, http.StatusBadRequest, "invalid_body")
  90. return
  91. }
  92. defer r.MultipartForm.RemoveAll()
  93. f, hdr, err := r.FormFile("image")
  94. if err != nil {
  95. writeError(w, http.StatusBadRequest, "invalid_body", "campo multipart 'image' requerido")
  96. return
  97. }
  98. defer f.Close()
  99. dir := filepath.Join(filepath.Dir(s.db.Path), "firmware-uploads")
  100. if err := os.MkdirAll(dir, 0o700); err != nil {
  101. writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
  102. return
  103. }
  104. dest, valid := firmwareUploadPath(dir, id)
  105. if !valid {
  106. writeError(w, http.StatusBadRequest, "invalid_router_id")
  107. return
  108. }
  109. tmp := dest + ".tmp"
  110. df, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
  111. if err != nil {
  112. writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
  113. return
  114. }
  115. h := sha256.New()
  116. n, copyErr := io.Copy(io.MultiWriter(df, h), io.LimitReader(f, maxFirmwareUpload+1))
  117. closeErr := df.Close()
  118. if copyErr != nil || closeErr != nil {
  119. os.Remove(tmp)
  120. writeError(w, http.StatusInternalServerError, "firmware_error", "no se pudo guardar la imagen")
  121. return
  122. }
  123. if n == 0 || n > maxFirmwareUpload {
  124. os.Remove(tmp)
  125. writeError(w, http.StatusRequestEntityTooLarge, "image_too_large", "imagen vacía o mayor del tope")
  126. return
  127. }
  128. if err := os.Rename(tmp, dest); err != nil {
  129. os.Remove(tmp)
  130. writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
  131. return
  132. }
  133. sum := hex.EncodeToString(h.Sum(nil))
  134. // La URL con la que los AGENTES deben alcanzar al server (#1335):
  135. // la misma cadena de precedencia que el install line.
  136. imgURL := s.agentBaseURL(r) + "/api/firmware-image/" + id
  137. t, _ := s.firmware.GetTarget(id)
  138. if t == nil {
  139. t = &firmware.Target{RouterID: id}
  140. }
  141. t.TargetURL = imgURL
  142. t.Checksum = sum
  143. if err := s.firmware.SetTarget(*t); err != nil {
  144. writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
  145. return
  146. }
  147. writeJSON(w, http.StatusOK, map[string]any{
  148. "ok": true, "checksum": sum, "size": n, "name": hdr.Filename, "url": imgURL,
  149. })
  150. })))
  151. // GET image: sirve la imagen subida. Sin auth de admin a propósito: el
  152. // AGENTE la descarga con su transporte pinned (mismo caso que
  153. // GET /api/agents/{slug}/binary, #1367) y no puede añadir cabeceras.
  154. // La imagen tampoco es secreta (es la que el admin subió para flashear).
  155. mux.HandleFunc("GET /api/firmware-image/{routerId}", s.handleFirmwareImage)
  156. }
  157. // firmwareBackupDir resuelve el directorio de backups de config subidos por
  158. // los agentes (#1414), junto a la BD (misma política que los backups #741).
  159. func (s *server) firmwareBackupDir() string {
  160. return filepath.Join(filepath.Dir(s.db.Path), "backups", "firmware")
  161. }
  162. // maxFirmwareBackupsPerRouter: retención de backups de config por unidad.
  163. const maxFirmwareBackupsPerRouter = 5
  164. // registerFirmwareBackupRoutes: el agente sube el backup de config hecho con
  165. // sysupgrade -b (persistencia real frente al /tmp local, que muere en el
  166. // reboot del flash) y el admin lista/descarga.
  167. func (s *server) registerFirmwareBackupRoutes(mux *http.ServeMux) {
  168. if s.firmware == nil {
  169. return
  170. }
  171. // POST: subida del agente (Bearer, misma auth que firmware-progress).
  172. // Body crudo: el .tar.gz tal cual.
  173. mux.HandleFunc("POST /api/agents/{slug}/firmware-backup", func(w http.ResponseWriter, r *http.Request) {
  174. slug := r.PathValue("slug")
  175. token := bearerToken(r)
  176. if !s.checkAgentToken(slug, token) {
  177. writeError(w, http.StatusUnauthorized, "unauthorized")
  178. return
  179. }
  180. if s.db == nil {
  181. writeError(w, http.StatusServiceUnavailable, "no_db")
  182. return
  183. }
  184. dir := s.firmwareBackupDir()
  185. if err := ensureBackupDir(dir); err != nil {
  186. writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
  187. return
  188. }
  189. name := s.firmwareBackupName(r.Context(), slug)
  190. dest := filepath.Join(dir, name)
  191. df, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, backupFileMode)
  192. if err != nil {
  193. writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
  194. return
  195. }
  196. if err := df.Chmod(backupFileMode); err != nil {
  197. df.Close()
  198. os.Remove(dest)
  199. writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
  200. return
  201. }
  202. n, copyErr := io.Copy(df, io.LimitReader(r.Body, maxFirmwareUpload+1))
  203. closeErr := df.Close()
  204. if copyErr != nil || closeErr != nil {
  205. os.Remove(dest)
  206. writeError(w, http.StatusInternalServerError, "firmware_error", "no se pudo guardar el backup")
  207. return
  208. }
  209. if n == 0 || n > maxFirmwareUpload {
  210. os.Remove(dest)
  211. writeError(w, http.StatusRequestEntityTooLarge, "backup_too_large", "backup vacío o mayor del tope")
  212. return
  213. }
  214. pruneFirmwareBackups(dir, slug)
  215. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "name": name, "size": n})
  216. })
  217. // GET list: backups de config de una unidad (admin).
  218. mux.Handle("GET /api/firmware-backups/{routerId}", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  219. id := r.PathValue("routerId")
  220. if s.db == nil {
  221. writeError(w, http.StatusServiceUnavailable, "no_db")
  222. return
  223. }
  224. entries, err := os.ReadDir(s.firmwareBackupDir())
  225. if err != nil {
  226. writeJSON(w, http.StatusOK, []any{})
  227. return
  228. }
  229. type info struct {
  230. Name string `json:"name"`
  231. Size int64 `json:"size"`
  232. Ts int64 `json:"ts"`
  233. }
  234. out := []info{}
  235. for _, e := range entries {
  236. if e.IsDir() {
  237. continue
  238. }
  239. ts, ok := firmwareBackupTimestamp(e.Name(), id)
  240. if !ok {
  241. continue
  242. }
  243. if fi, err := e.Info(); err == nil {
  244. out = append(out, info{Name: e.Name(), Size: fi.Size(), Ts: ts})
  245. }
  246. }
  247. sort.Slice(out, func(i, j int) bool { return out[i].Ts > out[j].Ts })
  248. writeJSON(w, http.StatusOK, out)
  249. })))
  250. // GET file: descarga de un backup (admin).
  251. mux.Handle("GET /api/firmware-backups/{routerId}/file", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  252. id := r.PathValue("routerId")
  253. name := filepath.Base(r.URL.Query().Get("name"))
  254. if name == "." || name == "" {
  255. writeError(w, http.StatusNotFound, "not_found")
  256. return
  257. }
  258. if _, ok := firmwareBackupTimestamp(name, id); !ok {
  259. writeError(w, http.StatusNotFound, "not_found")
  260. return
  261. }
  262. if s.db == nil {
  263. writeError(w, http.StatusServiceUnavailable, "no_db")
  264. return
  265. }
  266. path := filepath.Join(s.firmwareBackupDir(), name)
  267. st, err := os.Stat(path)
  268. if err != nil || st.IsDir() {
  269. writeError(w, http.StatusNotFound, "not_found")
  270. return
  271. }
  272. w.Header().Set("Content-Type", "application/gzip")
  273. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", name))
  274. http.ServeFile(w, r, path)
  275. })))
  276. }
  277. // pruneFirmwareBackups deja los maxFirmwareBackupsPerRouter más recientes de
  278. // una unidad. El id se compara con el sufijo exacto del nombre, no con un
  279. // prefijo: "netgear-wax220" no debe capturar los backups de
  280. // "netgear-wax220-2" (#1795).
  281. func pruneFirmwareBackups(dir, slug string) {
  282. entries, err := os.ReadDir(dir)
  283. if err != nil {
  284. return
  285. }
  286. type backup struct {
  287. name string
  288. ts int64
  289. }
  290. var mine []backup
  291. for _, e := range entries {
  292. if e.IsDir() {
  293. continue
  294. }
  295. if ts, ok := firmwareBackupTimestamp(e.Name(), slug); ok {
  296. mine = append(mine, backup{name: e.Name(), ts: ts})
  297. }
  298. }
  299. sort.Slice(mine, func(i, j int) bool {
  300. if mine[i].ts == mine[j].ts {
  301. return mine[i].name > mine[j].name
  302. }
  303. return mine[i].ts > mine[j].ts
  304. })
  305. for i := maxFirmwareBackupsPerRouter; i < len(mine); i++ {
  306. os.Remove(filepath.Join(dir, mine[i].name))
  307. }
  308. }
  309. // firmwareBackupTimestamp reconoce el formato nuevo
  310. // (<unidad>-<unix10>-<slug>.tar.gz) y el legacy (<slug>-<unix10>.tar.gz).
  311. // Compara el slug por su límite exacto y devuelve el ts común de ambos.
  312. func firmwareBackupTimestamp(name, slug string) (int64, bool) {
  313. if slug == "" || !strings.HasSuffix(name, ".tar.gz") {
  314. return 0, false
  315. }
  316. stem := strings.TrimSuffix(name, ".tar.gz")
  317. if strings.HasSuffix(stem, "-"+slug) {
  318. prefix := strings.TrimSuffix(stem, "-"+slug)
  319. if i := strings.LastIndexByte(prefix, '-'); i > 0 {
  320. if ts, ok := parseBackupTimestamp(prefix[i+1:]); ok {
  321. return ts, true
  322. }
  323. }
  324. }
  325. legacyPrefix := slug + "-"
  326. if strings.HasPrefix(stem, legacyPrefix) {
  327. if ts, ok := parseBackupTimestamp(strings.TrimPrefix(stem, legacyPrefix)); ok {
  328. return ts, true
  329. }
  330. }
  331. return 0, false
  332. }
  333. func parseBackupTimestamp(s string) (int64, bool) {
  334. if len(s) != 10 {
  335. return 0, false
  336. }
  337. for _, r := range s {
  338. if r < '0' || r > '9' {
  339. return 0, false
  340. }
  341. }
  342. ts, err := strconv.ParseInt(s, 10, 64)
  343. return ts, err == nil
  344. }
  345. // firmwareBackupName usa el nombre visible de la unidad para que el archivo
  346. // se reconozca fuera de la UI, y mantiene el slug al final para resolverlo
  347. // sin ambigüedad. Si la unidad ya no existe, cae al slug.
  348. func (s *server) firmwareBackupName(ctx context.Context, slug string) string {
  349. label := slug
  350. if s.adapter != nil {
  351. for _, router := range s.adapter.GetRouters(ctx) {
  352. if router.ID == slug && strings.TrimSpace(router.Name) != "" {
  353. label = router.Name
  354. break
  355. }
  356. }
  357. }
  358. return firmwareBackupFileName(label, slug, time.Now().Unix())
  359. }
  360. func firmwareBackupFileName(label, slug string, ts int64) string {
  361. return fmt.Sprintf("%s-%d-%s.tar.gz", sanitizeBackupLabel(label), ts, slug)
  362. }
  363. func sanitizeBackupLabel(label string) string {
  364. var b strings.Builder
  365. lastDash := false
  366. for _, r := range strings.TrimSpace(label) {
  367. ok := unicode.IsLetter(r) || unicode.IsDigit(r) || r == '.' || r == '_'
  368. if ok {
  369. b.WriteRune(r)
  370. lastDash = false
  371. continue
  372. }
  373. if !lastDash {
  374. b.WriteByte('-')
  375. lastDash = true
  376. }
  377. }
  378. out := strings.Trim(b.String(), "-.")
  379. if out == "" {
  380. return "netpulse"
  381. }
  382. return out
  383. }
  384. const (
  385. backupDirMode = 0o770
  386. backupFileMode = 0o640
  387. )
  388. func ensureBackupDir(path string) error {
  389. if err := os.MkdirAll(path, backupDirMode); err != nil {
  390. return err
  391. }
  392. return os.Chmod(path, backupDirMode)
  393. }
  394. // handleFirmwareImage sirve la imagen subida de un router. El id se sanea:
  395. // solo nombre base (sin separadores ni puntos dobles) dentro del directorio
  396. // de uploads.
  397. func (s *server) handleFirmwareImage(w http.ResponseWriter, r *http.Request) {
  398. id := r.PathValue("routerId")
  399. if !validFirmwareID(id) {
  400. writeError(w, http.StatusNotFound, "not_found")
  401. return
  402. }
  403. if s.db == nil {
  404. writeError(w, http.StatusServiceUnavailable, "no_db")
  405. return
  406. }
  407. dir := filepath.Join(filepath.Dir(s.db.Path), "firmware-uploads")
  408. path, valid := firmwareUploadPath(dir, id)
  409. if !valid {
  410. writeError(w, http.StatusNotFound, "not_found")
  411. return
  412. }
  413. st, err := os.Stat(path)
  414. if err != nil || st.IsDir() {
  415. writeError(w, http.StatusNotFound, "not_found")
  416. return
  417. }
  418. w.Header().Set("Content-Type", "application/octet-stream")
  419. w.Header().Set("Content-Length", fmt.Sprintf("%d", st.Size()))
  420. http.ServeFile(w, r, path)
  421. }