rtlconsole.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. // rtlconsole.go — #639: sondeo HTTP de la consola de switches RTLPlayground
  2. // (Keephome KP-9000 con firmware FreeSwitchOS/RTLPlayground) para poblar
  3. // firmware + uptime en routers cuyo agente es external (beacon UDP, #291).
  4. //
  5. // El datagrama del beacon no puede crecer (el banco de código del 8051 está
  6. // lleno), así que el server consulta la consola web del propio switch con
  7. // cadencia lenta. La web sirve UNA petición a la vez (uIP/8051), por eso el
  8. // poll es serial por switch y nunca en paralelo (InFlight).
  9. //
  10. // El resultado se cachea por slug con {firmware, bootUnix}: a partir del
  11. // bootUnix el uptime se deriva del reloj del server entre polls (no hace
  12. // falta re-consultar cada 30 s), y el poll solo re-sincroniza bootUnix con
  13. // la cadencia configurada (NETPULSE_RTL_POLL_S, default 300).
  14. package httpapi
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "io"
  19. "log"
  20. "net/http"
  21. "net/url"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "time"
  26. "github.com/gnacho/netpulse/agent/probe"
  27. )
  28. // rtlConsoleEntry: resultado del último poll OK de la consola del switch.
  29. type rtlConsoleEntry struct {
  30. Firmware string // sw_ver de /information.json ("v0.1.0-e1fa080-dirty")
  31. Model string // hw_ver ("keepLink KP-9000-9XHML-X V3.1")
  32. MAC string // mac_address (la que el switch usa en runtime)
  33. BootUnix time.Time // now - uptimeSec del poll; el uptime se deriva de aquí
  34. PolledAt time.Time // cuándo se hizo el poll (para la cadencia)
  35. InFlight bool // hay un poll en curso (serial por slug)
  36. FailedAt time.Time // último fallo (backoff para no martillear un host no-RTL)
  37. FailCount int
  38. }
  39. // rtlConsoleInfo es la respuesta de /information.json del firmware (solo los
  40. // campos que necesitamos; el JSON tiene más).
  41. type rtlConsoleInfo struct {
  42. SwVer string `json:"sw_ver"`
  43. HwVer string `json:"hw_ver"`
  44. Mac string `json:"mac_address"`
  45. }
  46. // rtlConsoleCache: estado del sondeo por slug. Protegido por su mutex.
  47. type rtlConsoleCache struct {
  48. mu sync.Mutex
  49. pass string
  50. sec int // cadencia en segundos
  51. byID map[string]*rtlConsoleEntry
  52. }
  53. func newRtlConsoleCache(pass string, pollSec int) *rtlConsoleCache {
  54. if pollSec <= 0 {
  55. pollSec = 300
  56. }
  57. if pass == "" {
  58. pass = "1234"
  59. }
  60. return &rtlConsoleCache{pass: pass, sec: pollSec, byID: map[string]*rtlConsoleEntry{}}
  61. }
  62. // snapshot devuelve la entrada cacheada para adjuntar System al payload del
  63. // beacon. Si la entrada es vieja o no existe y no hay poll en curso, lanza el
  64. // poll en background (no bloquea el handler del beacon). Devuelve nil hasta
  65. // que el primer poll tenga éxito (el beacon de turno no lleva System).
  66. func (c *rtlConsoleCache) snapshot(slug, host string) *rtlConsoleEntry {
  67. now := time.Now()
  68. c.mu.Lock()
  69. e := c.byID[slug]
  70. if e == nil {
  71. e = &rtlConsoleEntry{}
  72. c.byID[slug] = e
  73. }
  74. needPoll := e.Firmware == "" || now.Sub(e.PolledAt) >= time.Duration(c.sec)*time.Second
  75. // Backoff tras fallos: reintentar como mucho cada max(sec, 15 min) si el
  76. // host no habla el protocolo (login fallido), para no martillearlo.
  77. if needPoll && e.FailCount > 0 && now.Sub(e.FailedAt) < 15*time.Minute {
  78. needPoll = false
  79. }
  80. if needPoll && !e.InFlight {
  81. e.InFlight = true
  82. c.mu.Unlock()
  83. go c.poll(slug, host)
  84. c.mu.Lock()
  85. }
  86. // Copia bajo el lock: el caller lee los campos ya fuera del mutex y el
  87. // poll en background los puede estar escribiendo en paralelo (#1167).
  88. out := *e
  89. c.mu.Unlock()
  90. if out.Firmware == "" {
  91. return nil
  92. }
  93. return &out
  94. }
  95. // invalidate marca la entrada para re-poll inmediato (reboot detectado por el
  96. // seq del beacon: el bootUnix cacheado ya no es válido).
  97. func (c *rtlConsoleCache) invalidate(slug string) {
  98. c.mu.Lock()
  99. defer c.mu.Unlock()
  100. if e := c.byID[slug]; e != nil {
  101. e.PolledAt = time.Time{}
  102. }
  103. }
  104. // poll consulta la consola del switch (login + /information.json + /cmd time)
  105. // y guarda el resultado. Serial por slug (InFlight) y con timeouts cortos:
  106. // la web del firmware atiende una conexión cada vez.
  107. func (c *rtlConsoleCache) poll(slug, host string) {
  108. entry, err := c.fetch(host)
  109. c.mu.Lock()
  110. e := c.byID[slug]
  111. if e == nil {
  112. e = &rtlConsoleEntry{}
  113. c.byID[slug] = e
  114. }
  115. e.InFlight = false
  116. if err != nil {
  117. e.FailCount++
  118. e.FailedAt = time.Now()
  119. c.mu.Unlock()
  120. log.Printf("[netpulse:rtl] poll %s (%s) falló: %v", slug, host, err)
  121. return
  122. }
  123. e.Firmware = entry.Firmware
  124. e.Model = entry.Model
  125. e.MAC = entry.MAC
  126. e.BootUnix = entry.BootUnix
  127. e.PolledAt = time.Now()
  128. e.FailCount = 0
  129. c.mu.Unlock()
  130. }
  131. // fetch hace login en la consola y lee /information.json (sw_ver/hw_ver) y el
  132. // uptime por POST /cmd "time". Devuelve bootUnix = now - uptimeSec.
  133. func (c *rtlConsoleCache) fetch(host string) (*rtlConsoleEntry, error) {
  134. base := "http://" + host
  135. // No seguir el 302 del login (Location: index.html): necesitamos la
  136. // cookie del Set-Cookie y la respuesta es el propio redirect.
  137. client := &http.Client{
  138. Timeout: 8 * time.Second,
  139. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  140. return http.ErrUseLastResponse
  141. },
  142. }
  143. // 1) login: POST /login pwd=<pass> → 302 + Set-Cookie: session=...
  144. form := url.Values{"pwd": {c.pass}}
  145. req, err := http.NewRequest(http.MethodPost, base+"/login", strings.NewReader(form.Encode()))
  146. if err != nil {
  147. return nil, err
  148. }
  149. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  150. resp, err := client.Do(req)
  151. if err != nil {
  152. return nil, err
  153. }
  154. cookie := ""
  155. for _, ck := range resp.Cookies() {
  156. if ck.Name == "session" && ck.Value != "" {
  157. cookie = ck.Name + "=" + ck.Value
  158. break
  159. }
  160. }
  161. _, _ = io.Copy(io.Discard, resp.Body)
  162. resp.Body.Close()
  163. if resp.StatusCode != http.StatusFound && resp.StatusCode != http.StatusOK {
  164. return nil, fmt.Errorf("login HTTP %d", resp.StatusCode)
  165. }
  166. if cookie == "" {
  167. return nil, fmt.Errorf("login sin cookie de sesión")
  168. }
  169. // 2) /information.json → sw_ver + hw_ver
  170. infoReq, err := http.NewRequest(http.MethodGet, base+"/information.json", nil)
  171. if err != nil {
  172. return nil, err
  173. }
  174. infoReq.Header.Set("Cookie", cookie)
  175. infoResp, err := client.Do(infoReq)
  176. if err != nil {
  177. return nil, err
  178. }
  179. infoBody, _ := io.ReadAll(io.LimitReader(infoResp.Body, 4096))
  180. infoResp.Body.Close()
  181. if infoResp.StatusCode != http.StatusOK {
  182. return nil, fmt.Errorf("information.json HTTP %d", infoResp.StatusCode)
  183. }
  184. var info rtlConsoleInfo
  185. if err := json.Unmarshal(infoBody, &info); err != nil {
  186. return nil, fmt.Errorf("information.json inválido: %w", err)
  187. }
  188. // 3) POST /cmd "time" → uptime en segundos (hex, p. ej. "0x00028e9d").
  189. // El firmware exige Content-Type en todo POST (sin él responde 404).
  190. cmdReq, err := http.NewRequest(http.MethodPost, base+"/cmd", strings.NewReader("time"))
  191. if err != nil {
  192. return nil, err
  193. }
  194. cmdReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  195. cmdReq.Header.Set("Cookie", cookie)
  196. cmdResp, err := client.Do(cmdReq)
  197. if err != nil {
  198. return nil, err
  199. }
  200. cmdBody, _ := io.ReadAll(io.LimitReader(cmdResp.Body, 256))
  201. cmdResp.Body.Close()
  202. if cmdResp.StatusCode != http.StatusOK {
  203. return nil, fmt.Errorf("/cmd time HTTP %d", cmdResp.StatusCode)
  204. }
  205. upSec, err := parseTimeUptime(string(cmdBody))
  206. if err != nil {
  207. return nil, err
  208. }
  209. now := time.Now()
  210. return &rtlConsoleEntry{
  211. Firmware: info.SwVer, Model: info.HwVer, MAC: info.Mac,
  212. BootUnix: now.Add(-time.Duration(upSec) * time.Second),
  213. }, nil
  214. }
  215. // parseTimeUptime extrae el uptime en segundos del cuerpo de POST /cmd time.
  216. // Acepta los dos formatos del firmware RTLPlayground (#785):
  217. //
  218. // - legado: un contador hex único ("0x00028e9d").
  219. // - nuevo (firmwares desde 2026-09-16): dos contadores en líneas o una
  220. // sola línea, "Tick counter: 0x… Sec Counter: 0x…" — el uptime es el
  221. // Sec Counter (el Tick counter es un reloj distinto, no segundos).
  222. func parseTimeUptime(body string) (uint64, error) {
  223. s := strings.TrimSpace(body)
  224. // Formato nuevo: localizar "Sec Counter:" y parsear el hex que sigue.
  225. if i := strings.Index(s, "Sec Counter:"); i >= 0 {
  226. rest := strings.TrimSpace(s[i+len("Sec Counter:"):])
  227. if nl := strings.IndexAny(rest, "\r\n"); nl >= 0 {
  228. rest = rest[:nl]
  229. }
  230. rest = strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(rest, "0x"), "0X"))
  231. if sec, err := strconv.ParseUint(rest, 16, 32); err == nil {
  232. return sec, nil
  233. }
  234. return 0, fmt.Errorf("/cmd time: Sec Counter no es hex (%q)", strings.TrimSpace(body))
  235. }
  236. upHex := strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(s, "0x"), "0X"))
  237. upSec, err := strconv.ParseUint(upHex, 16, 32)
  238. if err != nil {
  239. return 0, fmt.Errorf("/cmd time no es un contador hex (%q): %w", s, err)
  240. }
  241. return upSec, nil
  242. }
  243. // attachSystem adjunta la sección System (board + uptime + MAC) al payload de
  244. // un beacon periódico si hay datos de consola cacheados. Es el punto de
  245. // inyección: polledFromAgent mapea System.Board→board, SysInfo.Uptime→
  246. // uptimeSec y BridgeMAC→brMac, y buildRouter pinta Firmware/Uptime/MAC sin
  247. // cambios en el front.
  248. func (s *server) attachRTLConsole(slug, host string, pl *probe.Payload) {
  249. if s.rtlConsole == nil || pl == nil {
  250. return
  251. }
  252. // #863: toggle por router. La consola del firmware tiene UNA sola sesión
  253. // global: cada login del sondeo regenera session_id y tumba la sesión
  254. // humana. Con el sondeo desactivado este camino no toca la red (los datos
  255. // de sistema llegan por el beacon v1.3+, #865, cuando el firmware lo
  256. // soporta).
  257. if !s.consolePollingEnabled(slug) {
  258. return
  259. }
  260. e := s.rtlConsole.snapshot(slug, host)
  261. if e == nil {
  262. return
  263. }
  264. // Board.Release es un struct anónimo; se rellena campo a campo igual que
  265. // boardWithDesc en los tests de buildRouter.
  266. b := &probe.BoardInfo{}
  267. b.Model = e.Model
  268. b.Release.Description = "RTLPlayground " + e.Firmware
  269. sd := &probe.SystemData{
  270. Board: b,
  271. SysInfo: &probe.SysInfo{Uptime: time.Since(e.BootUnix).Seconds()},
  272. BridgeMAC: strings.ToUpper(e.MAC),
  273. }
  274. pl.Data.System = sd
  275. }
  276. // consolePollingEnabled lee el toggle del router (default ON: cualquier error
  277. // o router desconocido mantiene el comportamiento previo).
  278. func (s *server) consolePollingEnabled(slug string) bool {
  279. if s.db == nil {
  280. return true
  281. }
  282. var v int
  283. if err := s.db.DB.QueryRow("SELECT console_polling FROM routers WHERE id = ?", slug).Scan(&v); err != nil {
  284. return true
  285. }
  286. return v == 1
  287. }