owut_flow.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // owut_flow.go - ciclo owut completo (#761): lista de versiones disponibles,
  2. // instalación del paquete y comando de upgrade desatendido.
  3. //
  4. // `owut upgrade` es no interactivo por diseño (verificado sobre el fuente
  5. // ucode de owut 2026.07): aborta solo si los checks fallan, hace warn sin
  6. // preguntar cuando hay default packages perdidos, y si no hay cambios termina
  7. // con exit 0 sin tocar nada (idempotencia nativa). Sin -V reconstruye la
  8. // versión instalada con los paquetes al día; con -V VERSION salta de versión
  9. // conservando los paquetes instalados (attended sysupgrade vía ASU).
  10. package firmware
  11. import (
  12. "fmt"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. const (
  19. owutVersionsTimeout = 60 * time.Second
  20. owutInstallTimeout = 240 * time.Second
  21. // OwutUpgradeTimeout: build ASU + descarga + verificación + flash. El
  22. // build remoto puede tardar minutos; el flash final mata dropbear y la
  23. // sesión SSH muere con el router reiniciándose (resultado esperado).
  24. OwutUpgradeTimeout = 15 * time.Minute
  25. )
  26. // OwutVersion es una versión destino que ASU puede construir para el router.
  27. type OwutVersion struct {
  28. Version string `json:"version"`
  29. Branch string `json:"branch"`
  30. Latest bool `json:"latest,omitempty"`
  31. Newer bool `json:"newer,omitempty"`
  32. }
  33. var (
  34. owutBranchRe = regexp.MustCompile(`^\s{2}(\S+)\s+release branch\s*$`)
  35. owutVerRe = regexp.MustCompile(`^\s{4}(\S+)(\s+\(latest\))?\s*$`)
  36. )
  37. // ListOwutVersions parsea `owut versions` y devuelve las versiones estables
  38. // (se excluyen -rc* y *-SNAPSHOT) con la marca Latest y Newer respecto a la
  39. // versión instalada actual (vacía = todas sin comparar).
  40. func ListOwutVersions(runner Runner, host, current string) ([]OwutVersion, error) {
  41. if runner == nil || host == "" {
  42. return nil, fmt.Errorf("firmware: empty runner or host")
  43. }
  44. out, err := runner.Run(host, "owut versions 2>&1", owutVersionsTimeout)
  45. if err != nil {
  46. return nil, err
  47. }
  48. return ParseOwutVersions(out, current), nil
  49. }
  50. // ParseOwutVersions interpreta la salida de `owut versions` (función pura,
  51. // testeada): ramas con dos espacios y versiones con cuatro.
  52. func ParseOwutVersions(out, current string) []OwutVersion {
  53. var versions []OwutVersion
  54. branch := ""
  55. for _, line := range strings.Split(out, "\n") {
  56. if m := owutBranchRe.FindStringSubmatch(line); m != nil {
  57. branch = m[1]
  58. continue
  59. }
  60. if m := owutVerRe.FindStringSubmatch(line); m != nil {
  61. v := m[1]
  62. if !stableVersion(v) {
  63. continue
  64. }
  65. versions = append(versions, OwutVersion{
  66. Version: v,
  67. Branch: branch,
  68. Latest: m[2] != "",
  69. Newer: current != "" && VersionCmp(v, current) > 0,
  70. })
  71. }
  72. }
  73. return versions
  74. }
  75. // stableVersion filtra release candidates y snapshots del desplegable
  76. // (incluido el "SNAPSHOT" literal con que cierra cada rama del server ASU).
  77. func stableVersion(v string) bool {
  78. if v == "SNAPSHOT" || !strings.ContainsFunc(v, isDigitRune) {
  79. return false
  80. }
  81. return !strings.Contains(v, "-rc") && !strings.HasSuffix(v, "-SNAPSHOT")
  82. }
  83. func isDigitRune(r rune) bool { return r >= '0' && r <= '9' }
  84. // VersionCmp compara dos versiones OpenWrt ("25.12.5") numéricamente por
  85. // componentes; devuelve -1/0/1. Componentes no numéricos valen 0.
  86. func VersionCmp(a, b string) int {
  87. as := strings.Split(a, ".")
  88. bs := strings.Split(b, ".")
  89. n := len(as)
  90. if len(bs) > n {
  91. n = len(bs)
  92. }
  93. for i := 0; i < n; i++ {
  94. av, bv := 0, 0
  95. if i < len(as) {
  96. av, _ = strconv.Atoi(as[i])
  97. }
  98. if i < len(bs) {
  99. bv, _ = strconv.Atoi(bs[i])
  100. }
  101. if av != bv {
  102. if av < bv {
  103. return -1
  104. }
  105. return 1
  106. }
  107. }
  108. return 0
  109. }
  110. // MajorJump informa de si pasar de current a target cambia de rama mayor
  111. // ("23.05.5" -> "24.10.0" es salto mayor; "23.05.5" -> "23.05.7" no).
  112. func MajorJump(current, target string) bool {
  113. if current == "" || target == "" {
  114. return false
  115. }
  116. cs := strings.Split(current, ".")
  117. ts := strings.Split(target, ".")
  118. if len(cs) == 0 || len(ts) == 0 {
  119. return false
  120. }
  121. return cs[0] != ts[0]
  122. }
  123. // owutInstallCmd detecta el gestor de paquetes del router e instala owut con
  124. // los repositorios PROPIOS del router (los firmware vanilla lo empaquetan).
  125. // En releases sin paquete owut (23.05-) el comando falla con el error del
  126. // gestor; en firmware de fabricante (GL.iNet) el flujo va bloqueado antes
  127. // (cada vendor gestiona sus actualizaciones en su propio panel).
  128. const owutInstallCmd = `if command -v apk >/dev/null 2>&1; then ` +
  129. `apk update >/dev/null 2>&1; ` +
  130. `apk add owut; ` +
  131. `elif command -v opkg >/dev/null 2>&1; then opkg update && opkg install owut; ` +
  132. `else printf '__no_pm__\n'; fi 2>&1; printf '\n__owut_exit__=%d\n' $?`
  133. // InstallOwut instala el paquete owut en el router con el gestor disponible
  134. // (con reintento vía repo oficial para firmware de vendor). Devuelve la
  135. // salida del gestor; error si no hay gestor, falla la instalación o falla el
  136. // transporte SSH.
  137. func InstallOwut(runner Runner, host string) (string, error) {
  138. if runner == nil || host == "" {
  139. return "", fmt.Errorf("firmware: empty runner or host")
  140. }
  141. out, err := runner.Run(host, owutInstallCmd, owutInstallTimeout)
  142. if err != nil {
  143. return out, err
  144. }
  145. exit, raw := extractExitCode(out)
  146. if strings.Contains(raw, "__no_pm__") {
  147. return raw, fmt.Errorf("firmware: the router has neither apk nor opkg")
  148. }
  149. if exit != 0 {
  150. tail := raw
  151. if len(tail) > 300 {
  152. tail = "..." + tail[len(tail)-300:]
  153. }
  154. return raw, fmt.Errorf("owut install failed (exit %d): %s", exit, strings.TrimSpace(tail))
  155. }
  156. return raw, nil
  157. }
  158. // owutRemoveArg decide si el comando lleva -r. owut declara -r como opción
  159. // exclusiva (action "storex") y ademas carga `attendedsysupgrade.owut.remove`
  160. // como si fuera un argumento (argparse.add_config): si la lista ya esta en la
  161. // config UCI, pasar -r repite la opcion y owut aborta con "may only be used
  162. // once per invocation". Por eso solo se emite el flag cuando la lista NO esta
  163. // en UCI (#1978).
  164. func owutRemoveArg(removePkgs []string, removeInUCI bool) string {
  165. if removeInUCI {
  166. return ""
  167. }
  168. if pkgs := sanitizeRemovePkgs(removePkgs); pkgs != "" {
  169. return " -r " + shQuote(pkgs)
  170. }
  171. return ""
  172. }
  173. // OwutCmd describe el comando owut que se quiere construir.
  174. type OwutCmd struct {
  175. // Target es la version destino ("25.12.6"). Vacia o igual a Current
  176. // reconstruye la instalada con los paquetes al dia.
  177. Target string
  178. // Current es la version instalada segun el board info.
  179. Current string
  180. // RemovePkgs son los paquetes fuera de los feeds que ASU debe excluir.
  181. RemovePkgs []string
  182. // RemoveInUCI indica que RemovePkgs ya vive en attendedsysupgrade.owut.remove,
  183. // donde owut la lee sola. En ese caso no se emite -r (#1978).
  184. RemoveInUCI bool
  185. // Force acepta los avisos que owut no deja pasar solos, como los
  186. // downgrades de paquetes de un salto de version mayor (#1978).
  187. Force bool
  188. }
  189. // OwutUpgradeCmd construye el comando de upgrade desatendido.
  190. func OwutUpgradeCmd(o OwutCmd) string {
  191. cmd := "owut upgrade -q"
  192. if o.Target != "" && o.Current != "" && o.Target != o.Current {
  193. cmd += " -V " + shQuote(o.Target)
  194. }
  195. cmd += owutRemoveArg(o.RemovePkgs, o.RemoveInUCI)
  196. if o.Force {
  197. cmd += " --force"
  198. }
  199. return cmd
  200. }
  201. // pkgNameRe: nombre de paquete apk/opkg sano (defensa contra inyección en
  202. // el comando SSH; el shQuote ya protege, esto limita el abuso).
  203. var pkgNameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._+-]*$`)
  204. // sanitizeRemovePkgs filtra y une la lista de exclusiones (máx 20).
  205. func sanitizeRemovePkgs(list []string) string {
  206. var keep []string
  207. for _, p := range list {
  208. p = strings.TrimSpace(p)
  209. if p != "" && pkgNameRe.MatchString(p) && len(keep) < 20 {
  210. keep = append(keep, p)
  211. }
  212. }
  213. return strings.Join(keep, " ")
  214. }
  215. // RunOwutUpgrade ejecuta el comando de upgrade con el wrapper de exit code y
  216. // devuelve (exit, salida, error de transporte). Un error de transporte al
  217. // final del flujo es NORMAL: el sysupgrade reinicia el router y la sesión SSH
  218. // muere sin llegar a escribir la línea de exit (el caller lo interpreta).
  219. func RunOwutUpgrade(runner Runner, host, cmd string) (int, string, error) {
  220. wrapped := cmd + ` 2>&1; printf '\n__owut_exit__=%d\n' $?`
  221. out, err := runner.Run(host, wrapped, OwutUpgradeTimeout)
  222. exit, raw := extractExitCode(out)
  223. return exit, raw, err
  224. }
  225. // owutDownloadTimeout: build remoto ASU + descarga de la imagen al router.
  226. // `owut download` NO flashea: termina por sí solo y la sesión SSH sobrevive.
  227. const owutDownloadTimeout = 10 * time.Minute
  228. // OwutDownloadCmd construye `owut download` (paso intermedio del flujo por
  229. // pasos de #1414): construye la imagen en ASU y la descarga al router SIN
  230. // flashear, para que el admin la revise antes de `owut install`. Sin -q a
  231. // proposito: la salida completa es la revision.
  232. func OwutDownloadCmd(o OwutCmd) string {
  233. cmd := "owut download"
  234. if o.Target != "" && o.Current != "" && o.Target != o.Current {
  235. cmd += " -V " + shQuote(o.Target)
  236. }
  237. cmd += owutRemoveArg(o.RemovePkgs, o.RemoveInUCI)
  238. if o.Force {
  239. cmd += " --force"
  240. }
  241. return cmd
  242. }
  243. // RunOwutDownload ejecuta `owut download` y devuelve salida + exit. El comando
  244. // termina normalmente (no flashea), así que la sesión SSH NO muere: un exit
  245. // distinto de 0 o un error de sesión es fallo real.
  246. func RunOwutDownload(runner Runner, host, cmd string) (int, string, error) {
  247. wrapped := cmd + ` 2>&1; printf '\n__owut_exit__=%d\n' $?`
  248. out, err := runner.Run(host, wrapped, owutDownloadTimeout)
  249. exit, raw := extractExitCode(out)
  250. return exit, raw, err
  251. }
  252. // OwutInstallCmd construye `owut install`: flashea la imagen que `owut
  253. // download` dejó en el router y reinicia (la sesión SSH muere como en el
  254. // upgrade; el resultado se confirma por el board info tras el reboot).
  255. func OwutInstallCmd() string { return "owut install" }
  256. // owutImageCheckCmd: `owut download` deja la imagen en /tmp/firmware.bin
  257. // (su ruta por defecto para download/verify/install) y `owut install` la
  258. // espera ahí. Comprobarla antes de lanzar el flash evita el error crudo de
  259. // sysupgrade cuando no hay nada descargado (#1769).
  260. const owutImageCheckCmd = "test -s /tmp/firmware.bin"
  261. // HasOwutDownloadedImage informa de si el router tiene una imagen descargada
  262. // lista para `owut install`. Tolerante: runner o host vacíos → false. Un
  263. // fallo de transporte también cuenta como "no hay imagen": sin confirmación
  264. // no se flashea.
  265. func HasOwutDownloadedImage(runner Runner, host string) bool {
  266. if runner == nil || host == "" {
  267. return false
  268. }
  269. _, err := runner.Run(host, owutImageCheckCmd, owutDetectTimeout)
  270. return err == nil
  271. }
  272. // Platform es la foto de plataforma de un router: si tiene owut y si lleva
  273. // firmware de fabricante. Vendor != "" significa firmware compilado por el
  274. // vendor con su propia gestión de actualizaciones (GL.iNet): NetPulse NO
  275. // ofrece upgrades ASU ahí, el vendor ya resuelve los suyos en su panel.
  276. type Platform struct {
  277. Owut bool
  278. Vendor string // "" | "gl-inet"
  279. }
  280. // platformDetectCmd: una sola ida SSH resuelve ambas señales. La marca de
  281. // vendor son los repositorios propios (fw.gl-inet.com en apk u opkg): el
  282. // /etc/openwrt_release de los GL op25 es idéntico al vanilla y NO sirve.
  283. // OJO: busybox grep sale con 2 si algún fichero listado no existe (aunque
  284. // haya matches), así que el match se decide por salida (grep -q .), no por
  285. // exit code del primer grep.
  286. const platformDetectCmd = `command -v owut >/dev/null 2>&1 && printf '__owut__\n'; ` +
  287. `grep -hs fw.gl-inet.com /etc/apk/repositories /etc/apk/repositories.d/* /etc/opkg/distfeeds.conf 2>/dev/null | grep -q . && printf '__gl__\n'; true`
  288. // DetectPlatform sondea owut y vendor del router (tolerante: runner/host
  289. // vacíos → Platform vacía).
  290. func DetectPlatform(runner Runner, host string) Platform {
  291. if runner == nil || host == "" {
  292. return Platform{}
  293. }
  294. out, _ := runner.Run(host, platformDetectCmd, owutDetectTimeout)
  295. return ParsePlatform(out)
  296. }
  297. // ParsePlatform interpreta las marcas de platformDetectCmd (función pura).
  298. func ParsePlatform(out string) Platform {
  299. p := Platform{}
  300. if strings.Contains(out, "__owut__") {
  301. p.Owut = true
  302. }
  303. if strings.Contains(out, "__gl__") {
  304. p.Vendor = "gl-inet"
  305. }
  306. return p
  307. }
  308. // stackPreserveCmd garantiza de forma idempotente que los ficheros del
  309. // stack propio presente en el router (netgrip y/o agente NetPulse) estén en
  310. // /etc/sysupgrade.conf: ASU no puede incluir paquetes sin feed en la imagen,
  311. // pero los ficheros listados SOBREVIVEN al flash (el servicio arranca en el
  312. // primer boot; el registro apk se recupera con una reinstalación posterior).
  313. const stackPreserveCmd = `P=/etc/sysupgrade.conf; touch $P; ensure() { grep -qxF "$1" $P || echo "$1" >> $P; }; ` +
  314. `if [ -f /usr/sbin/netgrip ]; then ensure /usr/sbin/netgrip; ensure /etc/init.d/netgrip; ` +
  315. `ensure /usr/libexec/netgrip-restore-rules; ensure /etc/netgrip/; ` +
  316. `for f in /etc/rc.d/*netgrip*; do [ -e "$f" ] && ensure "$f"; done; fi; ` +
  317. `if [ -f /usr/sbin/netpulse-agent ]; then ensure /usr/sbin/netpulse-agent; ensure /etc/netpulse-agent.env; ` +
  318. `ensure /etc/init.d/netpulse-agent; ` +
  319. `for f in /etc/rc.d/*netpulse-agent*; do [ -e "$f" ] && ensure "$f"; done; fi; true`
  320. // EnsureStackPreserved ejecuta la preservación en el router (tolerante: un
  321. // runner nil es no-op; devuelve el error de transporte si falla y el caller
  322. // decide si continúa).
  323. func EnsureStackPreserved(runner Runner, host string) error {
  324. if runner == nil || host == "" {
  325. return nil
  326. }
  327. _, err := runner.Run(host, stackPreserveCmd, owutDetectTimeout)
  328. return err
  329. }
  330. // OpenWrtVersionRe: versión destino válida para -V ("25.12.5", "24.10.2").
  331. // Evita que textos libres guardados como target disparen upgrades sin sentido.
  332. var OpenWrtVersionRe = regexp.MustCompile(`^\d+\.\d+(\.\d+)?(-[a-zA-Z0-9.]+)?$`)
  333. // ValidOpenWrtVersion informa de si target parece una versión OpenWrt.
  334. func ValidOpenWrtVersion(v string) bool {
  335. return OpenWrtVersionRe.MatchString(strings.TrimSpace(v))
  336. }
  337. // shQuote entrecomilla un valor para shell POSIX (single-quote escaping).
  338. func shQuote(v string) string {
  339. return "'" + strings.ReplaceAll(v, "'", `'\''`) + "'"
  340. }