| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304 |
- // rtlconsole.go — #639: sondeo HTTP de la consola de switches RTLPlayground
- // (Keephome KP-9000 con firmware FreeSwitchOS/RTLPlayground) para poblar
- // firmware + uptime en routers cuyo agente es external (beacon UDP, #291).
- //
- // El datagrama del beacon no puede crecer (el banco de código del 8051 está
- // lleno), así que el server consulta la consola web del propio switch con
- // cadencia lenta. La web sirve UNA petición a la vez (uIP/8051), por eso el
- // poll es serial por switch y nunca en paralelo (InFlight).
- //
- // El resultado se cachea por slug con {firmware, bootUnix}: a partir del
- // bootUnix el uptime se deriva del reloj del server entre polls (no hace
- // falta re-consultar cada 30 s), y el poll solo re-sincroniza bootUnix con
- // la cadencia configurada (NETPULSE_RTL_POLL_S, default 300).
- package httpapi
- import (
- "encoding/json"
- "fmt"
- "io"
- "log"
- "net/http"
- "net/url"
- "strconv"
- "strings"
- "sync"
- "time"
- "github.com/gnacho/netpulse/agent/probe"
- )
- // rtlConsoleEntry: resultado del último poll OK de la consola del switch.
- type rtlConsoleEntry struct {
- Firmware string // sw_ver de /information.json ("v0.1.0-e1fa080-dirty")
- Model string // hw_ver ("keepLink KP-9000-9XHML-X V3.1")
- MAC string // mac_address (la que el switch usa en runtime)
- BootUnix time.Time // now - uptimeSec del poll; el uptime se deriva de aquí
- PolledAt time.Time // cuándo se hizo el poll (para la cadencia)
- InFlight bool // hay un poll en curso (serial por slug)
- FailedAt time.Time // último fallo (backoff para no martillear un host no-RTL)
- FailCount int
- }
- // rtlConsoleInfo es la respuesta de /information.json del firmware (solo los
- // campos que necesitamos; el JSON tiene más).
- type rtlConsoleInfo struct {
- SwVer string `json:"sw_ver"`
- HwVer string `json:"hw_ver"`
- Mac string `json:"mac_address"`
- }
- // rtlConsoleCache: estado del sondeo por slug. Protegido por su mutex.
- type rtlConsoleCache struct {
- mu sync.Mutex
- pass string
- sec int // cadencia en segundos
- byID map[string]*rtlConsoleEntry
- }
- func newRtlConsoleCache(pass string, pollSec int) *rtlConsoleCache {
- if pollSec <= 0 {
- pollSec = 300
- }
- if pass == "" {
- pass = "1234"
- }
- return &rtlConsoleCache{pass: pass, sec: pollSec, byID: map[string]*rtlConsoleEntry{}}
- }
- // snapshot devuelve la entrada cacheada para adjuntar System al payload del
- // beacon. Si la entrada es vieja o no existe y no hay poll en curso, lanza el
- // poll en background (no bloquea el handler del beacon). Devuelve nil hasta
- // que el primer poll tenga éxito (el beacon de turno no lleva System).
- func (c *rtlConsoleCache) snapshot(slug, host string) *rtlConsoleEntry {
- now := time.Now()
- c.mu.Lock()
- e := c.byID[slug]
- if e == nil {
- e = &rtlConsoleEntry{}
- c.byID[slug] = e
- }
- needPoll := e.Firmware == "" || now.Sub(e.PolledAt) >= time.Duration(c.sec)*time.Second
- // Backoff tras fallos: reintentar como mucho cada max(sec, 15 min) si el
- // host no habla el protocolo (login fallido), para no martillearlo.
- if needPoll && e.FailCount > 0 && now.Sub(e.FailedAt) < 15*time.Minute {
- needPoll = false
- }
- if needPoll && !e.InFlight {
- e.InFlight = true
- c.mu.Unlock()
- go c.poll(slug, host)
- c.mu.Lock()
- }
- // Copia bajo el lock: el caller lee los campos ya fuera del mutex y el
- // poll en background los puede estar escribiendo en paralelo (#1167).
- out := *e
- c.mu.Unlock()
- if out.Firmware == "" {
- return nil
- }
- return &out
- }
- // invalidate marca la entrada para re-poll inmediato (reboot detectado por el
- // seq del beacon: el bootUnix cacheado ya no es válido).
- func (c *rtlConsoleCache) invalidate(slug string) {
- c.mu.Lock()
- defer c.mu.Unlock()
- if e := c.byID[slug]; e != nil {
- e.PolledAt = time.Time{}
- }
- }
- // poll consulta la consola del switch (login + /information.json + /cmd time)
- // y guarda el resultado. Serial por slug (InFlight) y con timeouts cortos:
- // la web del firmware atiende una conexión cada vez.
- func (c *rtlConsoleCache) poll(slug, host string) {
- entry, err := c.fetch(host)
- c.mu.Lock()
- e := c.byID[slug]
- if e == nil {
- e = &rtlConsoleEntry{}
- c.byID[slug] = e
- }
- e.InFlight = false
- if err != nil {
- e.FailCount++
- e.FailedAt = time.Now()
- c.mu.Unlock()
- log.Printf("[netpulse:rtl] poll %s (%s) falló: %v", slug, host, err)
- return
- }
- e.Firmware = entry.Firmware
- e.Model = entry.Model
- e.MAC = entry.MAC
- e.BootUnix = entry.BootUnix
- e.PolledAt = time.Now()
- e.FailCount = 0
- c.mu.Unlock()
- }
- // fetch hace login en la consola y lee /information.json (sw_ver/hw_ver) y el
- // uptime por POST /cmd "time". Devuelve bootUnix = now - uptimeSec.
- func (c *rtlConsoleCache) fetch(host string) (*rtlConsoleEntry, error) {
- base := "http://" + host
- // No seguir el 302 del login (Location: index.html): necesitamos la
- // cookie del Set-Cookie y la respuesta es el propio redirect.
- client := &http.Client{
- Timeout: 8 * time.Second,
- CheckRedirect: func(req *http.Request, via []*http.Request) error {
- return http.ErrUseLastResponse
- },
- }
- // 1) login: POST /login pwd=<pass> → 302 + Set-Cookie: session=...
- form := url.Values{"pwd": {c.pass}}
- req, err := http.NewRequest(http.MethodPost, base+"/login", strings.NewReader(form.Encode()))
- if err != nil {
- return nil, err
- }
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- resp, err := client.Do(req)
- if err != nil {
- return nil, err
- }
- cookie := ""
- for _, ck := range resp.Cookies() {
- if ck.Name == "session" && ck.Value != "" {
- cookie = ck.Name + "=" + ck.Value
- break
- }
- }
- _, _ = io.Copy(io.Discard, resp.Body)
- resp.Body.Close()
- if resp.StatusCode != http.StatusFound && resp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("login HTTP %d", resp.StatusCode)
- }
- if cookie == "" {
- return nil, fmt.Errorf("login sin cookie de sesión")
- }
- // 2) /information.json → sw_ver + hw_ver
- infoReq, err := http.NewRequest(http.MethodGet, base+"/information.json", nil)
- if err != nil {
- return nil, err
- }
- infoReq.Header.Set("Cookie", cookie)
- infoResp, err := client.Do(infoReq)
- if err != nil {
- return nil, err
- }
- infoBody, _ := io.ReadAll(io.LimitReader(infoResp.Body, 4096))
- infoResp.Body.Close()
- if infoResp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("information.json HTTP %d", infoResp.StatusCode)
- }
- var info rtlConsoleInfo
- if err := json.Unmarshal(infoBody, &info); err != nil {
- return nil, fmt.Errorf("information.json inválido: %w", err)
- }
- // 3) POST /cmd "time" → uptime en segundos (hex, p. ej. "0x00028e9d").
- // El firmware exige Content-Type en todo POST (sin él responde 404).
- cmdReq, err := http.NewRequest(http.MethodPost, base+"/cmd", strings.NewReader("time"))
- if err != nil {
- return nil, err
- }
- cmdReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- cmdReq.Header.Set("Cookie", cookie)
- cmdResp, err := client.Do(cmdReq)
- if err != nil {
- return nil, err
- }
- cmdBody, _ := io.ReadAll(io.LimitReader(cmdResp.Body, 256))
- cmdResp.Body.Close()
- if cmdResp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("/cmd time HTTP %d", cmdResp.StatusCode)
- }
- upSec, err := parseTimeUptime(string(cmdBody))
- if err != nil {
- return nil, err
- }
- now := time.Now()
- return &rtlConsoleEntry{
- Firmware: info.SwVer, Model: info.HwVer, MAC: info.Mac,
- BootUnix: now.Add(-time.Duration(upSec) * time.Second),
- }, nil
- }
- // parseTimeUptime extrae el uptime en segundos del cuerpo de POST /cmd time.
- // Acepta los dos formatos del firmware RTLPlayground (#785):
- //
- // - legado: un contador hex único ("0x00028e9d").
- // - nuevo (firmwares desde 2026-09-16): dos contadores en líneas o una
- // sola línea, "Tick counter: 0x… Sec Counter: 0x…" — el uptime es el
- // Sec Counter (el Tick counter es un reloj distinto, no segundos).
- func parseTimeUptime(body string) (uint64, error) {
- s := strings.TrimSpace(body)
- // Formato nuevo: localizar "Sec Counter:" y parsear el hex que sigue.
- if i := strings.Index(s, "Sec Counter:"); i >= 0 {
- rest := strings.TrimSpace(s[i+len("Sec Counter:"):])
- if nl := strings.IndexAny(rest, "\r\n"); nl >= 0 {
- rest = rest[:nl]
- }
- rest = strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(rest, "0x"), "0X"))
- if sec, err := strconv.ParseUint(rest, 16, 32); err == nil {
- return sec, nil
- }
- return 0, fmt.Errorf("/cmd time: Sec Counter no es hex (%q)", strings.TrimSpace(body))
- }
- upHex := strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(s, "0x"), "0X"))
- upSec, err := strconv.ParseUint(upHex, 16, 32)
- if err != nil {
- return 0, fmt.Errorf("/cmd time no es un contador hex (%q): %w", s, err)
- }
- return upSec, nil
- }
- // attachSystem adjunta la sección System (board + uptime + MAC) al payload de
- // un beacon periódico si hay datos de consola cacheados. Es el punto de
- // inyección: polledFromAgent mapea System.Board→board, SysInfo.Uptime→
- // uptimeSec y BridgeMAC→brMac, y buildRouter pinta Firmware/Uptime/MAC sin
- // cambios en el front.
- func (s *server) attachRTLConsole(slug, host string, pl *probe.Payload) {
- if s.rtlConsole == nil || pl == nil {
- return
- }
- // #863: toggle por router. La consola del firmware tiene UNA sola sesión
- // global: cada login del sondeo regenera session_id y tumba la sesión
- // humana. Con el sondeo desactivado este camino no toca la red (los datos
- // de sistema llegan por el beacon v1.3+, #865, cuando el firmware lo
- // soporta).
- if !s.consolePollingEnabled(slug) {
- return
- }
- e := s.rtlConsole.snapshot(slug, host)
- if e == nil {
- return
- }
- // Board.Release es un struct anónimo; se rellena campo a campo igual que
- // boardWithDesc en los tests de buildRouter.
- b := &probe.BoardInfo{}
- b.Model = e.Model
- b.Release.Description = "RTLPlayground " + e.Firmware
- sd := &probe.SystemData{
- Board: b,
- SysInfo: &probe.SysInfo{Uptime: time.Since(e.BootUnix).Seconds()},
- BridgeMAC: strings.ToUpper(e.MAC),
- }
- pl.Data.System = sd
- }
- // consolePollingEnabled lee el toggle del router (default ON: cualquier error
- // o router desconocido mantiene el comportamiento previo).
- func (s *server) consolePollingEnabled(slug string) bool {
- if s.db == nil {
- return true
- }
- var v int
- if err := s.db.DB.QueryRow("SELECT console_polling FROM routers WHERE id = ?", slug).Scan(&v); err != nil {
- return true
- }
- return v == 1
- }
|