rtlconsole.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. out := e
  87. c.mu.Unlock()
  88. if out.Firmware == "" {
  89. return nil
  90. }
  91. return out
  92. }
  93. // invalidate marca la entrada para re-poll inmediato (reboot detectado por el
  94. // seq del beacon: el bootUnix cacheado ya no es válido).
  95. func (c *rtlConsoleCache) invalidate(slug string) {
  96. c.mu.Lock()
  97. defer c.mu.Unlock()
  98. if e := c.byID[slug]; e != nil {
  99. e.PolledAt = time.Time{}
  100. }
  101. }
  102. // poll consulta la consola del switch (login + /information.json + /cmd time)
  103. // y guarda el resultado. Serial por slug (InFlight) y con timeouts cortos:
  104. // la web del firmware atiende una conexión cada vez.
  105. func (c *rtlConsoleCache) poll(slug, host string) {
  106. entry, err := c.fetch(host)
  107. c.mu.Lock()
  108. e := c.byID[slug]
  109. if e == nil {
  110. e = &rtlConsoleEntry{}
  111. c.byID[slug] = e
  112. }
  113. e.InFlight = false
  114. if err != nil {
  115. e.FailCount++
  116. e.FailedAt = time.Now()
  117. c.mu.Unlock()
  118. log.Printf("[netpulse:rtl] poll %s (%s) falló: %v", slug, host, err)
  119. return
  120. }
  121. e.Firmware = entry.Firmware
  122. e.Model = entry.Model
  123. e.MAC = entry.MAC
  124. e.BootUnix = entry.BootUnix
  125. e.PolledAt = time.Now()
  126. e.FailCount = 0
  127. c.mu.Unlock()
  128. }
  129. // fetch hace login en la consola y lee /information.json (sw_ver/hw_ver) y el
  130. // uptime por POST /cmd "time". Devuelve bootUnix = now - uptimeSec.
  131. func (c *rtlConsoleCache) fetch(host string) (*rtlConsoleEntry, error) {
  132. base := "http://" + host
  133. // No seguir el 302 del login (Location: index.html): necesitamos la
  134. // cookie del Set-Cookie y la respuesta es el propio redirect.
  135. client := &http.Client{
  136. Timeout: 8 * time.Second,
  137. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  138. return http.ErrUseLastResponse
  139. },
  140. }
  141. // 1) login: POST /login pwd=<pass> → 302 + Set-Cookie: session=...
  142. form := url.Values{"pwd": {c.pass}}
  143. req, err := http.NewRequest(http.MethodPost, base+"/login", strings.NewReader(form.Encode()))
  144. if err != nil {
  145. return nil, err
  146. }
  147. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  148. resp, err := client.Do(req)
  149. if err != nil {
  150. return nil, err
  151. }
  152. cookie := ""
  153. for _, ck := range resp.Cookies() {
  154. if ck.Name == "session" && ck.Value != "" {
  155. cookie = ck.Name + "=" + ck.Value
  156. break
  157. }
  158. }
  159. _, _ = io.Copy(io.Discard, resp.Body)
  160. resp.Body.Close()
  161. if resp.StatusCode != http.StatusFound && resp.StatusCode != http.StatusOK {
  162. return nil, fmt.Errorf("login HTTP %d", resp.StatusCode)
  163. }
  164. if cookie == "" {
  165. return nil, fmt.Errorf("login sin cookie de sesión")
  166. }
  167. // 2) /information.json → sw_ver + hw_ver
  168. infoReq, err := http.NewRequest(http.MethodGet, base+"/information.json", nil)
  169. if err != nil {
  170. return nil, err
  171. }
  172. infoReq.Header.Set("Cookie", cookie)
  173. infoResp, err := client.Do(infoReq)
  174. if err != nil {
  175. return nil, err
  176. }
  177. infoBody, _ := io.ReadAll(io.LimitReader(infoResp.Body, 4096))
  178. infoResp.Body.Close()
  179. if infoResp.StatusCode != http.StatusOK {
  180. return nil, fmt.Errorf("information.json HTTP %d", infoResp.StatusCode)
  181. }
  182. var info rtlConsoleInfo
  183. if err := json.Unmarshal(infoBody, &info); err != nil {
  184. return nil, fmt.Errorf("information.json inválido: %w", err)
  185. }
  186. // 3) POST /cmd "time" → uptime en segundos (hex, p. ej. "0x00028e9d").
  187. // El firmware exige Content-Type en todo POST (sin él responde 404).
  188. cmdReq, err := http.NewRequest(http.MethodPost, base+"/cmd", strings.NewReader("time"))
  189. if err != nil {
  190. return nil, err
  191. }
  192. cmdReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  193. cmdReq.Header.Set("Cookie", cookie)
  194. cmdResp, err := client.Do(cmdReq)
  195. if err != nil {
  196. return nil, err
  197. }
  198. cmdBody, _ := io.ReadAll(io.LimitReader(cmdResp.Body, 256))
  199. cmdResp.Body.Close()
  200. if cmdResp.StatusCode != http.StatusOK {
  201. return nil, fmt.Errorf("/cmd time HTTP %d", cmdResp.StatusCode)
  202. }
  203. upSec, err := parseTimeUptime(string(cmdBody))
  204. if err != nil {
  205. return nil, err
  206. }
  207. now := time.Now()
  208. return &rtlConsoleEntry{
  209. Firmware: info.SwVer, Model: info.HwVer, MAC: info.Mac,
  210. BootUnix: now.Add(-time.Duration(upSec) * time.Second),
  211. }, nil
  212. }
  213. // parseTimeUptime extrae el uptime en segundos del cuerpo de POST /cmd time.
  214. // Acepta los dos formatos del firmware RTLPlayground (#785):
  215. //
  216. // - legado: un contador hex único ("0x00028e9d").
  217. // - nuevo (firmwares desde 2026-09-16): dos contadores en líneas o una
  218. // sola línea, "Tick counter: 0x… Sec Counter: 0x…" — el uptime es el
  219. // Sec Counter (el Tick counter es un reloj distinto, no segundos).
  220. func parseTimeUptime(body string) (uint64, error) {
  221. s := strings.TrimSpace(body)
  222. // Formato nuevo: localizar "Sec Counter:" y parsear el hex que sigue.
  223. if i := strings.Index(s, "Sec Counter:"); i >= 0 {
  224. rest := strings.TrimSpace(s[i+len("Sec Counter:"):])
  225. if nl := strings.IndexAny(rest, "\r\n"); nl >= 0 {
  226. rest = rest[:nl]
  227. }
  228. rest = strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(rest, "0x"), "0X"))
  229. if sec, err := strconv.ParseUint(rest, 16, 32); err == nil {
  230. return sec, nil
  231. }
  232. return 0, fmt.Errorf("/cmd time: Sec Counter no es hex (%q)", strings.TrimSpace(body))
  233. }
  234. upHex := strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(s, "0x"), "0X"))
  235. upSec, err := strconv.ParseUint(upHex, 16, 32)
  236. if err != nil {
  237. return 0, fmt.Errorf("/cmd time no es un contador hex (%q): %w", s, err)
  238. }
  239. return upSec, nil
  240. }
  241. // attachSystem adjunta la sección System (board + uptime + MAC) al payload de
  242. // un beacon periódico si hay datos de consola cacheados. Es el punto de
  243. // inyección: polledFromAgent mapea System.Board→board, SysInfo.Uptime→
  244. // uptimeSec y BridgeMAC→brMac, y buildRouter pinta Firmware/Uptime/MAC sin
  245. // cambios en el front.
  246. func (s *server) attachRTLConsole(slug, host string, pl *probe.Payload) {
  247. if s.rtlConsole == nil || pl == nil {
  248. return
  249. }
  250. // #863: toggle por router. La consola del firmware tiene UNA sola sesión
  251. // global: cada login del sondeo regenera session_id y tumba la sesión
  252. // humana. Con el sondeo desactivado este camino no toca la red (los datos
  253. // de sistema llegan por el beacon v1.3+, #865, cuando el firmware lo
  254. // soporta).
  255. if !s.consolePollingEnabled(slug) {
  256. return
  257. }
  258. e := s.rtlConsole.snapshot(slug, host)
  259. if e == nil {
  260. return
  261. }
  262. // Board.Release es un struct anónimo; se rellena campo a campo igual que
  263. // boardWithDesc en los tests de buildRouter.
  264. b := &probe.BoardInfo{}
  265. b.Model = e.Model
  266. b.Release.Description = "RTLPlayground " + e.Firmware
  267. sd := &probe.SystemData{
  268. Board: b,
  269. SysInfo: &probe.SysInfo{Uptime: time.Since(e.BootUnix).Seconds()},
  270. BridgeMAC: strings.ToUpper(e.MAC),
  271. }
  272. pl.Data.System = sd
  273. }
  274. // consolePollingEnabled lee el toggle del router (default ON: cualquier error
  275. // o router desconocido mantiene el comportamiento previo).
  276. func (s *server) consolePollingEnabled(slug string) bool {
  277. if s.db == nil {
  278. return true
  279. }
  280. var v int
  281. if err := s.db.DB.QueryRow("SELECT console_polling FROM routers WHERE id = ?", slug).Scan(&v); err != nil {
  282. return true
  283. }
  284. return v == 1
  285. }