local.go 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  1. // local.go — prober local del agente: ejecuta EN EL ROUTER los mismos
  2. // comandos que el servidor lanza por SSH (constantes Cmd* de probe.go) y
  3. // construye el Payload con los shapes parseados. Cada sonda es best-effort:
  4. // si un comando no existe (ubus, iwinfo, brctl...) la sección queda ausente
  5. // y el servidor conserva el último dato bueno (anti-parpadeo).
  6. package probe
  7. import (
  8. "context"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "log/slog"
  13. "net"
  14. "os"
  15. "os/exec"
  16. "sort"
  17. "strings"
  18. "sync"
  19. "time"
  20. )
  21. // Runner ejecuta un comando de shell local y devuelve su stdout.
  22. // timeout 0 = default corto de sonda.
  23. type Runner interface {
  24. Run(ctx context.Context, cmd string, timeout time.Duration) (string, error)
  25. }
  26. // ShellRunner ejecuta con /bin/sh -c (BusyBox ash en OpenWrt).
  27. type ShellRunner struct {
  28. DefaultTimeout time.Duration
  29. }
  30. // Run implementa Runner.
  31. func (s ShellRunner) Run(ctx context.Context, cmd string, timeout time.Duration) (string, error) {
  32. if timeout <= 0 {
  33. timeout = s.DefaultTimeout
  34. if timeout <= 0 {
  35. timeout = 5 * time.Second
  36. }
  37. }
  38. cctx, cancel := context.WithTimeout(ctx, timeout)
  39. defer cancel()
  40. out, err := exec.CommandContext(cctx, "/bin/sh", "-c", cmd).Output()
  41. if err != nil {
  42. // #1839: iw escribe el motivo en stderr ("command failed: Operation
  43. // not supported (-95)") y Output() lo tira. Sin el, un scan rechazado
  44. // y un scan vacio llegan al servidor exactamente igual.
  45. var ee *exec.ExitError
  46. if errors.As(err, &ee) {
  47. if msg := lastLine(ee.Stderr); msg != "" {
  48. return "", fmt.Errorf("%w: %s", err, msg)
  49. }
  50. }
  51. return "", err
  52. }
  53. return string(out), nil
  54. }
  55. // lastLine devuelve la ultima linea no vacia de b.
  56. func lastLine(b []byte) string {
  57. lines := strings.Split(strings.TrimSpace(string(b)), "\n")
  58. for i := len(lines) - 1; i >= 0; i-- {
  59. if line := strings.TrimSpace(lines[i]); line != "" {
  60. return line
  61. }
  62. }
  63. return ""
  64. }
  65. // Options configura las sondas opcionales del prober.
  66. type Options struct {
  67. // WanPingTarget: si no está vacío, ping WAN (latencia + pérdida) — gateway.
  68. WanPingTarget string
  69. // GwPingTarget: si no está vacío, ping corto al gateway (latencia) — AP.
  70. GwPingTarget string
  71. // ScanInterval: mínimo entre scans de vecinos (#591/#699). 0 = usar
  72. // DefaultScanInterval; negativo (ScanDisabled) = sin scans periódicos,
  73. // solo on-demand vía ForceScan (env NETPULSE_SCAN_INTERVAL).
  74. ScanInterval time.Duration
  75. // ActiveUplink names the uplink a policy manager is steering traffic
  76. // through, when the embedder knows. nil or "" = decide from the routes,
  77. // as before.
  78. ActiveUplink func() string
  79. }
  80. // Prober sondea el equipo local y construye payloads. Mantiene el estado de
  81. // deltas (/proc/stat y /proc/net/dev) entre muestras — es el único estado
  82. // del agente y vive solo en RAM.
  83. type Prober struct {
  84. run Runner
  85. opts Options
  86. lastStat *CPUSample
  87. lastNetRx float64
  88. lastNetTx float64
  89. lastNetAt time.Time
  90. hasLastNet bool
  91. // lastNetRaw conserva el último output de /proc/net/dev de probeSystem
  92. // para derivar la sección NetIf (contadores por iface, #305) sin un
  93. // segundo cat.
  94. lastNetRaw string
  95. // lastNetIf/lastNetIfAt: contadores por interfaz del ciclo anterior, para
  96. // publicar la tasa de la WAN y no la suma de todas las bocas (#2048).
  97. lastNetIf map[string]IfCounters
  98. lastNetIfAt time.Time
  99. // lastWan: uplink del último Build, para que probeFDB marque la boca por
  100. // la que sale internet sin repetir la llamada a ubus.
  101. lastWan *WanInfo
  102. // netIfUpdated indica si el último ciclo de probeSystem consiguió
  103. // refrescar /proc/net/dev. Build solo incluye NetIf cuando es true,
  104. // evitando enviar contadores repetidos si CmdNetDev falla o tarda.
  105. netIfUpdated bool
  106. // radiosCache (#368): el resumen de radios (canal/htmode/txpower) cambia
  107. // tan poco que no merece iwinfo en cada ciclo NI en el path de eventos:
  108. // se refresca cada radiosTTL en el sondeo completo y el resto de las
  109. // llamadas reutilizan la última.
  110. radiosMu sync.Mutex
  111. radiosCache []Radio
  112. radiosAt time.Time
  113. // scanMu protege el throttle del scan pasivo de vecinos (#591): el scan
  114. // activo (`iw dev scan`) saca la radio del canal y degrada a los clientes
  115. // si se repite en cada sondeo (cada ~30 s). Se ejecuta como mucho cada
  116. // scanInterval, o antes si el server pide un refresh explícito.
  117. scanMu sync.Mutex
  118. lastScanAt time.Time
  119. scanForced bool
  120. scanInterval time.Duration
  121. // Survey en vivo (#1214): throttle propio de 5 min. No saca la radio
  122. // del canal, pero el texto crudo engorda el push: no va en cada ciclo.
  123. surveyMu sync.Mutex
  124. surveyForced bool
  125. surveyAt time.Time
  126. // Config wireless cruda (#1450): `uci show wireless` para que el server
  127. // pinte 802.11r en flotas agent-only. Se refresca cada uciWirelessTTL
  128. // (la config cambia a mano, no sola) y el valor cacheado se emite en
  129. // TODOS los pushes: un push de evento (BuildWireless) no debe dejar al
  130. // server sin la sección mientras llega el siguiente sondeo completo.
  131. uciWirelessMu sync.Mutex
  132. uciWirelessRaw string
  133. uciWirelessAt time.Time
  134. // stalePing (#2073): recheck activo de vecinos ARP en STALE. El ping a
  135. // cada IP sale del throttle como mucho cada stalePingInterval; el sondeo
  136. // del agente es cada ~30 s y una entrada STALE cambia despacio.
  137. stalePingMu sync.Mutex
  138. stalePingAt time.Time
  139. // presenceAt (#2110): última ronda del barrido de subredes enrutadas.
  140. presenceMu sync.Mutex
  141. presenceAt time.Time
  142. }
  143. // surveyInterval: mínimo entre `iw survey dump` si no hay force (#1214).
  144. const surveyInterval = 5 * time.Minute
  145. // uciWirelessTTL: mínimo entre lecturas de `uci show wireless` (#1450).
  146. // Leer /etc/config/wireless es barato, pero la configuración solo cambia
  147. // cuando alguien la edita: con 5 min el panel sigue fresco y el push no
  148. // engorda en cada ciclo.
  149. const uciWirelessTTL = 5 * time.Minute
  150. const radiosTTL = 5 * time.Minute
  151. const (
  152. // ScanDisabled: sin scans periódicos (solo on-demand vía ForceScan).
  153. // Lo selecciona NETPULSE_SCAN_INTERVAL=0; en un AP con clientes Intel
  154. // cada off-channel gap puede costar un deauth por beacon-loss (#699).
  155. ScanDisabled = -1 * time.Second
  156. // DefaultScanInterval: mínimo entre scans de vecinos si no se configura
  157. // NETPULSE_SCAN_INTERVAL. Los datos de "Análisis de canales" apenas
  158. // cambian; 30 minutos mantienen el mapa razonablemente fresco sin
  159. // martillear el aire con off-channel scans (#591/#699).
  160. DefaultScanInterval = 30 * time.Minute
  161. )
  162. // NewProber crea el prober con el runner dado.
  163. func NewProber(run Runner, opts Options) *Prober {
  164. si := opts.ScanInterval
  165. if si == 0 {
  166. si = DefaultScanInterval
  167. }
  168. return &Prober{run: run, opts: opts, scanInterval: si}
  169. }
  170. // activeUplink asks the embedder which uplink is carrying traffic. Never
  171. // panics on a callback that does: the WAN section is not worth an agent.
  172. func (p *Prober) activeUplink() string {
  173. if p.opts.ActiveUplink == nil {
  174. return ""
  175. }
  176. defer func() { _ = recover() }()
  177. return p.opts.ActiveUplink()
  178. }
  179. // ForceScan pide un scan en el próximo Build (lo usa el runtime cuando el
  180. // server envía "refresh" por SSE): no espera al intervalo del throttle.
  181. func (p *Prober) ForceScan() {
  182. p.scanMu.Lock()
  183. p.scanForced = true
  184. p.scanMu.Unlock()
  185. }
  186. // ForceSurvey pide un survey en el próximo Build (#1214): el runtime lo
  187. // llama cuando el server envía "refresh" por SSE.
  188. func (p *Prober) ForceSurvey() {
  189. p.surveyMu.Lock()
  190. p.surveyForced = true
  191. p.surveyMu.Unlock()
  192. }
  193. // surveyDue decide si toca lanzar CmdSurvey en este sondeo completo: true si
  194. // hay force pendiente o si pasó surveyInterval desde el último intento. Al
  195. // devolver true registra el intento para no repetirlo.
  196. func (p *Prober) surveyDue() bool {
  197. p.surveyMu.Lock()
  198. defer p.surveyMu.Unlock()
  199. if p.surveyForced {
  200. p.surveyForced = false
  201. p.surveyAt = time.Now()
  202. return true
  203. }
  204. if p.surveyAt.IsZero() || time.Since(p.surveyAt) >= surveyInterval {
  205. p.surveyAt = time.Now()
  206. return true
  207. }
  208. return false
  209. }
  210. // refreshUciWireless lee `uci show wireless` si toca (#1450) y lo deja en
  211. // caché para el resto de pushes. Marca el intento aunque falle: un equipo sin
  212. // uci (o un switch sin sección wireless) no reintenta en cada sondeo.
  213. func (p *Prober) refreshUciWireless(ctx context.Context) {
  214. p.uciWirelessMu.Lock()
  215. due := p.uciWirelessAt.IsZero() || time.Since(p.uciWirelessAt) >= uciWirelessTTL
  216. p.uciWirelessMu.Unlock()
  217. if !due {
  218. return
  219. }
  220. out := p.runBest(ctx, CmdUciWireless, 3*time.Second)
  221. p.uciWirelessMu.Lock()
  222. p.uciWirelessAt = time.Now()
  223. if out != "" {
  224. p.uciWirelessRaw = out
  225. }
  226. p.uciWirelessMu.Unlock()
  227. }
  228. // uciWirelessCached devuelve el último volcado bueno de la config wireless
  229. // ("" si nunca se pudo leer).
  230. func (p *Prober) uciWirelessCached() string {
  231. p.uciWirelessMu.Lock()
  232. defer p.uciWirelessMu.Unlock()
  233. return p.uciWirelessRaw
  234. }
  235. // scanDue decide si toca lanzar CmdScan en este sondeo completo: true si hay
  236. // un force pendiente (refresh del server) o si pasó scanInterval desde el
  237. // último intento. Con ScanDisabled los periódicos no corren nunca (solo
  238. // force). La primera Build tras arrancar también escanea (lastScanAt cero),
  239. // salvo desactivado. Al devolver true registra el intento para no repetirlo.
  240. func (p *Prober) scanDue() bool {
  241. p.scanMu.Lock()
  242. defer p.scanMu.Unlock()
  243. if p.scanForced {
  244. p.scanForced = false
  245. p.lastScanAt = time.Now()
  246. return true
  247. }
  248. if p.scanInterval < 0 {
  249. return false
  250. }
  251. if p.lastScanAt.IsZero() || time.Since(p.lastScanAt) >= p.scanInterval {
  252. p.lastScanAt = time.Now()
  253. return true
  254. }
  255. return false
  256. }
  257. // scanNeighbours runs one `iw dev <iface> scan` per physical radio (#1560)
  258. // and logs every cycle (#1559).
  259. //
  260. // The scan is the only probe that takes a radio off-channel, so it is also
  261. // the only one that can drop clients (#1557). Until now it left no trace in
  262. // the log, which made that correlation impossible from a router: the log line
  263. // carries the interfaces, per-radio duration and BSS count to line a drop up
  264. // against the scan that caused it.
  265. func (p *Prober) scanNeighbours(ctx context.Context, iwDev string) ([]ScanResult, []ScanOutcome) {
  266. ifaces := ParseIwDevDetailed(iwDev)
  267. targets := IwDevScanTargets(ifaces)
  268. if len(targets) == 0 {
  269. return nil, nil
  270. }
  271. names := make([]string, len(targets))
  272. for i, t := range targets {
  273. names[i] = t.Iface
  274. }
  275. start := time.Now()
  276. slog.Info("neighbor scan start", "radios", len(targets), "ifaces", strings.Join(names, ","))
  277. var scans []ScanResult
  278. outcomes := make([]ScanOutcome, 0, len(targets))
  279. for _, t := range targets {
  280. at := time.Now()
  281. used, out, err := p.scanWithFallback(ctx, ifaces, t)
  282. got := ParseScan("==IFACE==" + used.Iface + "\n" + out)
  283. scans = append(scans, got...)
  284. oc := ScanOutcome{Iface: used.Iface, Phy: used.Phy, BSS: len(got)}
  285. if err != nil {
  286. oc.Error = err.Error()
  287. }
  288. outcomes = append(outcomes, oc)
  289. slog.Info("neighbor scan radio", "iface", used.Iface, "phy", used.Phy,
  290. "bss", len(got), "duration_ms", time.Since(at).Milliseconds(), "error", oc.Error)
  291. }
  292. slog.Info("neighbor scan done", "bss", len(scans),
  293. "duration_ms", time.Since(start).Milliseconds(), "empty", len(scans) == 0)
  294. return scans, outcomes
  295. }
  296. // scanWithFallback scans the interface chosen for the radio and, when it
  297. // refuses (#1839: on Asuswrt/dhd the AP VAP answers NL80211_CMD_TRIGGER_SCAN
  298. // with "Operation not supported"), tries the other interfaces of the same phy
  299. // in the same cycle. Nothing is remembered between cycles: caching a failure
  300. // would turn one bad scan into a permanent choice.
  301. func (p *Prober) scanWithFallback(ctx context.Context, ifaces []IwDevIface, chosen IwDevIface) (IwDevIface, string, error) {
  302. out, err := p.run.Run(ctx, CmdScanIface(chosen.Iface), scanIfaceTimeout)
  303. if err == nil {
  304. return chosen, out, nil
  305. }
  306. used, lastErr := chosen, err
  307. for i, alt := range IwDevScanAlternates(ifaces, chosen) {
  308. if i >= maxScanFallbacks {
  309. break
  310. }
  311. out, err = p.run.Run(ctx, CmdScanIface(alt.Iface), scanIfaceTimeout)
  312. if err == nil {
  313. slog.Info("neighbor scan fallback", "from", chosen.Iface, "to", alt.Iface,
  314. "phy", alt.Phy, "reason", lastErr.Error())
  315. return alt, out, nil
  316. }
  317. used, lastErr = alt, err
  318. }
  319. return used, "", lastErr
  320. }
  321. // probeVlans reports the bridge VLANs, merging what the kernel says with what
  322. // the configuration declares.
  323. //
  324. // The section has existed in the payload since VLANs were added, but
  325. // nothing ever filled it: only the server's own SSH probe did, and a router
  326. // reached through its agent never takes that path, so its VLAN panel has
  327. // always been empty.
  328. //
  329. // Neither source is enough on its own. `bridge` lives in an optional package,
  330. // so plenty of routers have VLANs only the configuration knows about. And a
  331. // box that segments with 802.1Q subinterfaces (eth0.999 into br-iot) answers
  332. // with every port on VLAN 1, a valid-looking answer that says nothing about
  333. // the real layout. The two views are therefore merged always, the kernel
  334. // owning the flags and the configuration the names, subnets and the VLANs
  335. // that only exist as subinterfaces (#1757).
  336. func (p *Prober) probeVlans(ctx context.Context) ([]VlanPort, []UciNetwork) {
  337. var kernel []VlanPort
  338. if out := p.runBest(ctx, CmdBridgeVlan, 0); out != "" {
  339. kernel = ParseBridgeVlan(out)
  340. }
  341. var declared []VlanPort
  342. var networks []UciNetwork
  343. if out := p.runBest(ctx, CmdUciBridgeVlan, 0); out != "" {
  344. // La misma configuracion alimenta las dos vistas (#1889): una sola
  345. // lectura de `uci show network` por ronda.
  346. // A router uses one model or the other, so the two UCI parsers
  347. // never describe the same port: bridge-vlan sections name bridge
  348. // ports, the subinterface model names bridges and their parents.
  349. declared = MergeVlanPorts(ParseUciBridgeVlans(out), ParseUciNetworkVlans(out))
  350. networks = ParseUciNetworks(out)
  351. }
  352. return MergeVlanPorts(kernel, declared), networks
  353. }
  354. // runBest es best-effort: error → "" (la sección queda ausente).
  355. func (p *Prober) runBest(ctx context.Context, cmd string, timeout time.Duration) string {
  356. out, err := p.run.Run(ctx, cmd, timeout)
  357. if err != nil {
  358. return ""
  359. }
  360. return out
  361. }
  362. // Build ejecuta una ronda de sondas y devuelve el payload listo para empujar.
  363. // router/version los rellena el caller (main) o van aquí por comodidad.
  364. func (p *Prober) Build(ctx context.Context, router, version string) *Payload {
  365. pl := &Payload{
  366. Router: router,
  367. Ts: time.Now().Unix(),
  368. Version: version,
  369. }
  370. // Wan antes que FDB: probeFDB usa la boca del uplink para marcarla.
  371. pl.Data.Wan = p.probeWan(ctx)
  372. pl.Data.Vlans, pl.Data.Networks = p.probeVlans(ctx)
  373. pl.Data.System = p.probeSystem(ctx)
  374. pl.Data.Wireless = p.probeWireless(ctx, true)
  375. pl.Data.DHCP = p.probeDHCP(ctx)
  376. // LLDP antes que FDB (#1500): los puertos con vecino LLDP deciden qué
  377. // miembro de un bridge es el uplink del AP. Una sola sonda por push:
  378. // el resultado se reusa para el payload.
  379. lldpData := p.probeLldp(ctx)
  380. pl.Data.Lldp = lldpData
  381. lldpPorts := map[string]bool{}
  382. if lldpData != nil {
  383. for _, nb := range lldpData.Neighbors {
  384. if nb.Port != "" {
  385. lldpPorts[nb.Port] = true
  386. }
  387. }
  388. }
  389. pl.Data.FDB = p.probeFDB(ctx, lldpPorts, pl.Data.Wireless.GetRadios())
  390. pl.Data.Arp, pl.Data.ArpStale, pl.Data.ArpDevs = p.probeArp(ctx)
  391. pl.Data.Dawn = p.probeDawn(ctx)
  392. pl.Data.Usteer = p.probeUsteer(ctx)
  393. pl.Data.LuCI = p.probeLuCI(ctx)
  394. // ClientBw (#551): tráfico por cliente desde nlbwmon (solo si instalado).
  395. pl.Data.ClientBw = p.probeClientBw(ctx)
  396. // Discovery (#338): mDNS services + randomized MAC detection.
  397. pl.Data.Discovery = p.probeDiscovery(ctx, pl.Data.Wireless)
  398. // NetIf (#305): contadores por iface desde el MISMO /proc/net/dev que
  399. // leyó probeSystem (sin segundo cat). Solo se incluyen si el ciclo actual
  400. // refrescó la muestra; si no, el payload se envía sin NetIf para que el
  401. // servidor no inserte deltas 0 con contadores repetidos (#408).
  402. if p.netIfUpdated {
  403. pl.Data.NetIf = ParseNetDevIfaces(p.lastNetRaw)
  404. p.netIfUpdated = false
  405. }
  406. return pl
  407. }
  408. // BuildWireless es un sondeo rápido de solo wireless + DHCP (Fase 7.1:
  409. // disparado por eventos ubus assoc/disassoc). El servidor conserva el último
  410. // dato bueno de system y FDB (parpadeo suprimido por secciones nil).
  411. func (p *Prober) BuildWireless(ctx context.Context, router, version string) *Payload {
  412. pl := &Payload{
  413. Router: router,
  414. Ts: time.Now().Unix(),
  415. Version: version,
  416. }
  417. pl.Data.Wireless = p.probeWireless(ctx, false)
  418. pl.Data.DHCP = p.probeDHCP(ctx)
  419. pl.Data.Arp, pl.Data.ArpStale, pl.Data.ArpDevs = p.probeArp(ctx)
  420. return pl
  421. }
  422. // probeSystem: sysinfo + board + cpu/temp + netdev + pings + backhaul + MAC
  423. // del bridge. Devuelve nil solo si TODAS las sondas fallaron (equipo sin
  424. // ubus y sin /proc — no pasa en OpenWrt; cubre al fake runner de tests).
  425. func (p *Prober) probeSystem(ctx context.Context) *SystemData {
  426. sd := &SystemData{}
  427. any := false
  428. if out := p.runBest(ctx, CmdUbusSystemInfo, 0); out != "" {
  429. var si SysInfo
  430. if err := json.Unmarshal([]byte(out), &si); err == nil {
  431. if si.Memory.Total > 0 {
  432. // ubus system info no expone la caché de ficheros, la lee el
  433. // agente de /proc/meminfo (fallback silencioso si no existe).
  434. if cached := readMeminfoCachedKB(); cached > 0 {
  435. si.Memory.Cached = float64(cached) * 1024
  436. }
  437. // Y el uso real (lo que el usuario percibe) es la memoria de
  438. // los procesos; así el server no sobreestima en ubifs (#513).
  439. if rss := sumProcRSS(); rss > 0 && rss < si.Memory.Total {
  440. si.Memory.Used = rss
  441. }
  442. }
  443. sd.SysInfo = &si
  444. any = true
  445. }
  446. }
  447. // #1481: fallback portable de uptime sin ubus (Asuswrt, Linux genérico):
  448. // el primer campo de /proc/uptime. Solo rellena el uptime; el resto de
  449. // SysInfo sigue viniendo de ubus cuando existe.
  450. if sd.SysInfo == nil || sd.SysInfo.Uptime == 0 {
  451. if out := p.runBest(ctx, CmdProcUptime, 0); out != "" {
  452. if sec := ParseUptimeSec(out); sec > 0 {
  453. if sd.SysInfo == nil {
  454. sd.SysInfo = &SysInfo{}
  455. }
  456. sd.SysInfo.Uptime = sec
  457. any = true
  458. }
  459. }
  460. }
  461. // #1500: memoria portable de /proc/meminfo cuando ubus no la dio (sin
  462. // esto la ficha pinta RAM 0% en todo target sin ubus). Se rellenan los
  463. // campos crudos y NUNCA Used: el server aplica su fórmula clásica
  464. // (total-free-buffered-cached), la misma semántica que en unidades con
  465. // ubus donde Used es la suma de RSS (#513).
  466. if m := readMeminfoFieldsKB(); m.total > 0 {
  467. if sd.SysInfo == nil {
  468. sd.SysInfo = &SysInfo{}
  469. }
  470. if sd.SysInfo.Memory.Total == 0 {
  471. sd.SysInfo.Memory.Total = float64(m.total) * 1024
  472. sd.SysInfo.Memory.Free = float64(m.free) * 1024
  473. sd.SysInfo.Memory.Buffered = float64(m.buffered) * 1024
  474. sd.SysInfo.Memory.Cached = float64(m.cached) * 1024
  475. sd.SysInfo.Memory.Available = float64(m.avail) * 1024
  476. any = true
  477. }
  478. }
  479. // #1500: zona horaria portable (ubus no la da nunca; la ficha pintaba
  480. // "—" incluso en equipos con ubus).
  481. if tz := readTimezone(); tz != "" {
  482. if sd.SysInfo == nil {
  483. sd.SysInfo = &SysInfo{}
  484. }
  485. if sd.SysInfo.Timezone == "" {
  486. sd.SysInfo.Timezone = tz
  487. }
  488. }
  489. if out := p.runBest(ctx, CmdUbusSystemBoard, 0); out != "" {
  490. var b BoardInfo
  491. if err := json.Unmarshal([]byte(out), &b); err == nil {
  492. sd.Board = &b
  493. any = true
  494. }
  495. }
  496. if out := p.runBest(ctx, CmdProcStat, 0); out != "" {
  497. if cur, err := ParseProcStat(out); err == nil {
  498. if p.lastStat != nil {
  499. sd.CPU = CPUPercent(*p.lastStat, cur)
  500. }
  501. c := cur
  502. p.lastStat = &c
  503. any = true
  504. }
  505. }
  506. if out := p.runBest(ctx, CmdTemp, 0); out != "" {
  507. sd.Temp = ParseTempC(out)
  508. any = true
  509. }
  510. if out := p.runBest(ctx, CmdNetDev, 0); out != "" {
  511. rx, tx := ParseNetDev(out)
  512. now := time.Now()
  513. if p.hasLastNet {
  514. sd.RxBps, sd.TxBps = NetDevBps(p.lastNetRx, p.lastNetTx, rx, tx, now.Sub(p.lastNetAt).Seconds())
  515. // #2048: el agregado suma todas las bocas físicas y en un router
  516. // que enruta cuenta la bajada dos veces (entra por la WAN y sale
  517. // por la LAN). Si el equipo sabe cuál es su WAN, se publica la
  518. // tasa de ESA boca. Sin WAN identificable (AP) manda el agregado.
  519. if p.lastWan != nil && p.lastWan.Port != "" && p.lastNetIf != nil {
  520. rates := IfRates(p.lastNetIf, ParseNetDevIfaces(out), now.Sub(p.lastNetIfAt).Seconds())
  521. if r, ok := rates[p.lastWan.Port]; ok && r.RxBps != nil && r.TxBps != nil {
  522. sd.RxBps, sd.TxBps = r.RxBps, r.TxBps
  523. }
  524. }
  525. }
  526. // Se guarda SIEMPRE, también en la primera muestra, que es la que abre
  527. // la ventana: si no, el ciclo siguiente no tiene con qué comparar.
  528. p.lastNetIf = ParseNetDevIfaces(out)
  529. p.lastNetIfAt = now
  530. p.lastNetRx, p.lastNetTx, p.lastNetAt, p.hasLastNet = rx, tx, now, true
  531. p.lastNetRaw = out
  532. p.netIfUpdated = true
  533. any = true
  534. }
  535. if p.opts.WanPingTarget != "" {
  536. out := p.runBest(ctx, fmt.Sprintf(CmdPingWan, p.opts.WanPingTarget), 10*time.Second)
  537. sd.LatencyMs, sd.LossPct = ParsePingSummary(out)
  538. any = true
  539. } else if p.opts.GwPingTarget != "" {
  540. out := p.runBest(ctx, fmt.Sprintf(CmdPingGateway, p.opts.GwPingTarget), 10*time.Second)
  541. sd.LatencyMs, _ = ParsePingSummary(out)
  542. any = true
  543. }
  544. if out := p.runBest(ctx, CmdUbusWireless, 0); out != "" {
  545. if wifi, err := ParseWirelessUplink([]byte(out)); err == nil {
  546. sd.Backhaul = "cable"
  547. if wifi {
  548. sd.Backhaul = "wifi"
  549. }
  550. any = true
  551. }
  552. }
  553. if out := p.runBest(ctx, CmdBridgeMAC, 0); out != "" {
  554. sd.BridgeMAC = strings.ToUpper(strings.TrimSpace(out))
  555. any = true
  556. }
  557. if out := p.runBest(ctx, CmdIfaceMACs, 0); out != "" {
  558. if macs := ParseIfaceMACs(out); len(macs) > 0 {
  559. sd.IfaceMACs = macs
  560. any = true
  561. }
  562. }
  563. if !any {
  564. return nil
  565. }
  566. return sd
  567. }
  568. // probeWireless: clientes asociados + radios por banda (#368: ubus primero,
  569. // iwinfo combinado en UNA pasada como fallback, radios cacheadas radiosTTL).
  570. // full=false (path de eventos nl80211) evita iwinfo por completo: ubus para
  571. // clientes y radios de caché. nil si no hay fuente wireless.
  572. func (p *Prober) probeWireless(ctx context.Context, full bool) *WirelessData {
  573. wd := &WirelessData{}
  574. any := false
  575. // Clientes: ubus hostapd get_clients (barato, sin ucode).
  576. if out := p.runBest(ctx, CmdHostapdClients, 5*time.Second); out != "" {
  577. wd.Clients = ParseHostapdClients(out)
  578. if len(wd.Clients) > 0 {
  579. any = true
  580. }
  581. }
  582. // Fallback (o APs sin ubus hostapd): iwinfo en UNA pasada por interfaz,
  583. // que además produce el resumen de radios.
  584. combined := ""
  585. combinedRan := false
  586. if !any {
  587. combined = p.runBest(ctx, CmdWirelessCombined, 8*time.Second)
  588. if combined != "" {
  589. clients, radios := ParseWirelessCombined(combined)
  590. // #2176: si el combinado devolvió algo (clientes o resumen de
  591. // radios), la pasada se hizo y repetir iwinfo con el par clásico
  592. // solo duplica los ioctl. En mt_wifi cada ioctl contra una
  593. // interfaz caída escribe una línea KERN_ERR en el log del router.
  594. combinedRan = len(clients) > 0 || len(radios) > 0
  595. wd.Clients = clients
  596. if len(clients) > 0 {
  597. any = true
  598. }
  599. p.radiosMu.Lock()
  600. if len(radios) > 0 {
  601. p.radiosCache, p.radiosAt = radios, time.Now()
  602. } else if time.Since(p.radiosAt) < radiosTTL {
  603. radios = p.radiosCache
  604. }
  605. p.radiosMu.Unlock()
  606. wd.Radios = radios
  607. }
  608. }
  609. // Último recurso (#368): el par de comandos clásico (equipos donde el
  610. // combinado no produjo clientes p. ej. iwinfo sin ESSID en la interfaz).
  611. if !any && !combinedRan {
  612. if out := p.runBest(ctx, CmdIwinfoAssoc, 8*time.Second); out != "" {
  613. wd.Clients = ParseWirelessClients(out)
  614. any = len(wd.Clients) > 0
  615. }
  616. }
  617. // #1481: fallback nl80211 portable sin ubus hostapd ni iwinfo (Asuswrt
  618. // con iw, Linux genérico): station dump por interfaz + radios por phy
  619. // del mismo `iw dev`.
  620. if !any {
  621. if out := p.runBest(ctx, CmdIwStationDump, 8*time.Second); out != "" {
  622. clients, radios := ParseIwWireless(out)
  623. if len(clients) > 0 {
  624. wd.Clients = clients
  625. any = true
  626. }
  627. if len(radios) > 0 {
  628. p.radiosMu.Lock()
  629. p.radiosCache, p.radiosAt = radios, time.Now()
  630. p.radiosMu.Unlock()
  631. wd.Radios = radios
  632. }
  633. }
  634. }
  635. // Broadcom dhd (RT-AX92U con Merlin): nl80211 no expone NADA util — ni
  636. // estaciones ni canal — y la unidad parece vacía aunque tenga clientes
  637. // asociados (visibles en el panel del firmware). `wl` sí los sabe. Solo
  638. // corre cuando los tiers anteriores dejaron huérfanos los clientes o
  639. // ninguna radio trae banda.
  640. {
  641. needWl := !any || len(wd.Radios) == 0
  642. if !needWl {
  643. banded := false
  644. for _, r := range wd.Radios {
  645. if r.Name != "" {
  646. banded = true
  647. break
  648. }
  649. }
  650. needWl = !banded
  651. }
  652. if needWl {
  653. if out := p.runBest(ctx, CmdWlWireless, 8*time.Second); out != "" {
  654. wclients, wradios := ParseWlWireless(out)
  655. if !any && len(wclients) > 0 {
  656. wd.Clients = wclients
  657. any = true
  658. }
  659. if len(wradios) > 0 {
  660. p.radiosMu.Lock()
  661. p.radiosCache, p.radiosAt = wradios, time.Now()
  662. p.radiosMu.Unlock()
  663. wd.Radios = wradios
  664. }
  665. }
  666. }
  667. }
  668. // Radios: solo en el sondeo completo (canal/htmode/txpower casi nunca
  669. // cambian); el path de eventos reutiliza la caché.
  670. if full {
  671. if combined != "" && wd.Radios == nil {
  672. wd.Radios = []Radio{}
  673. }
  674. if combined == "" {
  675. if out := p.runBest(ctx, CmdRadios, 8*time.Second); out != "" {
  676. radios := ParseRadios(out)
  677. // Sección UCI por banda (#500): habilita aplicar cambios de
  678. // canal desde el server. Best-effort: sin uci, sin sección.
  679. if secOut := p.runBest(ctx, CmdRadioSections, 5*time.Second); secOut != "" {
  680. sections := ParseRadioSections(secOut)
  681. for i := range radios {
  682. if sec, ok := sections[radios[i].Name]; ok {
  683. radios[i].Section = sec
  684. }
  685. }
  686. }
  687. p.radiosMu.Lock()
  688. p.radiosCache, p.radiosAt = radios, time.Now()
  689. wd.Radios = p.radiosCache
  690. p.radiosMu.Unlock()
  691. }
  692. }
  693. // `iw dev` a secas, barato y estable: alimenta con UN solo spawn los
  694. // BSSIDs propios (#1087) y la lista de interfaces a escanear (#1338).
  695. iwDev := p.runBest(ctx, CmdIwDev, 5*time.Second)
  696. // Scan pasivo de vecinos (#452): SOLO en sondeo completo y con
  697. // throttle (#591) para no sacar la radio del canal en cada push.
  698. // #1338: un comando POR INTERFAZ, cada una con su propio presupuesto
  699. // (8 s). Antes el bucle completo compartía un timeout de 10 s y, al
  700. // expirar, la salida parcial se descartaba entera: una radio lenta
  701. // (5 GHz en canal DFS, scan pasivo canal a canal) dejaba la unidad
  702. // sin NINGÚN vecino aunque las demás interfaces sí hubieran
  703. // escaneado con éxito.
  704. if p.scanDue() && iwDev != "" {
  705. scans, outcomes := p.scanNeighbours(ctx, iwDev)
  706. if len(scans) > 0 {
  707. wd.Scans = scans
  708. }
  709. if len(outcomes) > 0 {
  710. wd.ScanOutcomes = outcomes
  711. }
  712. }
  713. // BSSIDs propios (#1087), del mismo `iw dev` de arriba.
  714. if iwDev != "" {
  715. wd.OwnBssids = ParseIwDev(iwDev)
  716. }
  717. // Survey en vivo (#1214): ocupación por canal para la lente "Ahora"
  718. // del server en unidades agent-only (sin SSH). Texto crudo: el
  719. // parser vive en el server y así no se duplica.
  720. if p.surveyDue() {
  721. if out := p.runBest(ctx, CmdSurvey, 10*time.Second); out != "" {
  722. wd.SurveyRaw = out
  723. }
  724. }
  725. } else {
  726. p.radiosMu.Lock()
  727. cached := p.radiosCache
  728. p.radiosMu.Unlock()
  729. if len(cached) > 0 {
  730. wd.Radios = cached
  731. if len(wd.Clients) > 0 {
  732. any = true
  733. }
  734. }
  735. }
  736. // #1092: `any` lo marcaban solo los CLIENTES: una unidad sin clientes
  737. // asociados en ese momento descartaba TODA la sección wireless (radios,
  738. // scans, BSSIDs propios) y el server la veía como "sin WiFi". Que haya
  739. // radios o BSSIDs propios también prueba presencia wireless.
  740. if !any && (len(wd.Radios) > 0 || len(wd.OwnBssids) > 0) {
  741. any = true
  742. }
  743. // Config wireless cruda (#1450): alimenta la vista 802.11r del server en
  744. // flotas agent-only. Se refresca solo en el sondeo completo y se emite
  745. // SIEMPRE desde la caché (también en el path de eventos, para que el
  746. // último payload no pierda la sección). No cuenta para `any`: una unidad
  747. // con la config presente pero sin wifi operativa no debe aparecer como
  748. // wireless vivo.
  749. if full {
  750. p.refreshUciWireless(ctx)
  751. }
  752. wd.UciWirelessRaw = p.uciWirelessCached()
  753. if !any {
  754. return nil
  755. }
  756. if wd.Clients == nil {
  757. wd.Clients = map[string]WirelessClient{}
  758. }
  759. if wd.Radios == nil {
  760. wd.Radios = []Radio{}
  761. }
  762. return wd
  763. }
  764. // probeDHCP: ubus dhcp ipv4leases con fallback a /tmp/dhcp.leases, más
  765. // gl-clients (GL.iNet) como superset para resolver IPs sin lease
  766. // (issue #5 bug 1 — el gateway Flint2 llega por esta ruta de agente).
  767. func (p *Prober) probeDHCP(ctx context.Context) *DHCPData {
  768. var dd *DHCPData
  769. if out := p.runBest(ctx, CmdDhcpUbus, 0); out != "" {
  770. if leases, err := ParseDhcpUbus([]byte(out)); err == nil {
  771. dd = &DHCPData{Leases: leases}
  772. }
  773. }
  774. if dd == nil {
  775. out := p.runBest(ctx, CmdDhcpFile, 0)
  776. if out == "" {
  777. return nil
  778. }
  779. dd = &DHCPData{Leases: ParseDhcpLeasesFile(out)}
  780. }
  781. if out := p.runBest(ctx, CmdGlClients, 0); out != "" {
  782. if gl, err := ParseGlClients([]byte(out)); err == nil {
  783. dd.GlClients = gl
  784. }
  785. }
  786. // Names pinned in /etc/config/dhcp: the only ones a client with a fixed
  787. // address of its own ever gets.
  788. if out := p.runBest(ctx, CmdDhcpReservations, 0); out != "" {
  789. dd.Reservations = ParseDhcpReservations(out)
  790. }
  791. return dd
  792. }
  793. // probeWan: estado del uplink (proto, IP pública, gateway, DNS y la boca por
  794. // la que sale), eligiendo la interfaz por su ruta por defecto y no por
  795. // llamarse "wan". nil cuando no hay nada utilizable: un AP sin uplink, o un
  796. // equipo sin ubus. Guarda el resultado para probeFDB.
  797. func (p *Prober) probeWan(ctx context.Context) *WanInfo {
  798. p.lastWan = nil
  799. out := p.runBest(ctx, CmdNetworkDump, 0)
  800. if out == "" {
  801. return nil
  802. }
  803. info := ParseWanStatusPreferring([]byte(out), p.activeUplink())
  804. if info.Proto == "" && info.IP == "" && info.Gateway == "" && info.Port == "" {
  805. return nil
  806. }
  807. p.lastWan = &info
  808. return &info
  809. }
  810. // probeFDB: MACs aprendidas (brctl) + puertos ethernet (layout + /sys).
  811. func (p *Prober) probeFDB(ctx context.Context, lldpPorts map[string]bool, radios []Radio) *FDBData {
  812. fd := &FDBData{}
  813. any := false
  814. if out := p.runBest(ctx, CmdBridgeFDB, 0); out != "" {
  815. fd.MACs, fd.WirelessSide, fd.VLANs = ParseBridgeFdbVlans(out)
  816. fd.WirelessSide = bandTagWirelessSide(fd.WirelessSide, radios)
  817. any = true
  818. }
  819. statesOut := p.runBest(ctx, CmdPortStates, 0)
  820. if statesOut != "" {
  821. states := ParsePortStates(statesOut)
  822. layout := []PortLayout{}
  823. if out := p.runBest(ctx, CmdBoardJSON, 0); out != "" {
  824. if lay, err := ParsePortLayout(out); err == nil {
  825. layout = lay
  826. }
  827. }
  828. members := map[string]bool{}
  829. if out := p.runBest(ctx, CmdBrifMembers, 0); out != "" {
  830. for _, l := range strings.Split(strings.TrimSpace(out), "\n") {
  831. if l != "" {
  832. members[l] = true
  833. }
  834. }
  835. }
  836. // Contadores por iface (#305): absolutos del MISMO /proc/net/dev de
  837. // probeSystem (si ya corrió este ciclo); los rates los computa el
  838. // server con el delta entre payloads.
  839. var ifaces map[string]IfRate
  840. if p.lastNetRaw != "" {
  841. ifaces = map[string]IfRate{}
  842. for name, c := range ParseNetDevIfaces(p.lastNetRaw) {
  843. ifaces[name] = IfRate{IfCounters: c}
  844. }
  845. }
  846. // Boca del uplink: la marca como WAN cuando el layout no trae
  847. // ninguna (PPPoE sobre una boca "lan" y demás).
  848. uplink := ""
  849. if p.lastWan != nil {
  850. uplink = p.lastWan.Port
  851. }
  852. // #1500: sin ubus no hay WanInfo: el uplink sale de la ruta default
  853. // de /proc/net/route. Si cae en un bridge (APs: la default vive en
  854. // br0), la boca física es el miembro con un vecino LLDP (la que
  855. // mira al core) o, en su defecto, el de más rx bytes.
  856. if uplink == "" {
  857. uplink = defaultRouteIface()
  858. }
  859. if uplink != "" && isBridgeIface(uplink) {
  860. if m := bridgeMemberUplink(members, lldpPorts, states, ifaces); m != "" {
  861. uplink = m
  862. }
  863. }
  864. fd.Ports = BuildEthPorts(layout, states, members, ifaces, uplink)
  865. any = true
  866. }
  867. if !any {
  868. return nil
  869. }
  870. if fd.MACs == nil {
  871. fd.MACs = map[string]string{}
  872. }
  873. if fd.Ports == nil {
  874. fd.Ports = []EthPort{}
  875. }
  876. return fd
  877. }
  878. // bandTagWirelessSide convierte el mapa MAC→puerto inalámbrico del FDB en
  879. // MAC→banda, casando la MAC de la interfaz del puerto (o la del padre para
  880. // subinterfaces VLAN como wl0.1) con el BSSID de una radio sondeada en el
  881. // mismo ciclo. Sin radio que casar, la MAC se descarta: mejor no decir nada
  882. // que inventarse una banda. Es el hint que evita que el server clasifique
  883. // como cableado un MAC que solo vive detrás de una radio propia.
  884. func bandTagWirelessSide(side map[string]string, radios []Radio) map[string]string {
  885. if len(side) == 0 {
  886. return nil
  887. }
  888. bandByBSSID := make(map[string]string, len(radios))
  889. for _, r := range radios {
  890. if r.BSSID != "" {
  891. bandByBSSID[strings.ToUpper(r.BSSID)] = r.Name
  892. }
  893. }
  894. addrOf := func(iface string) string {
  895. raw, err := os.ReadFile("/sys/class/net/" + iface + "/address")
  896. if err != nil {
  897. return ""
  898. }
  899. return strings.ToUpper(strings.TrimSpace(string(raw)))
  900. }
  901. baseOf := func(port string) string {
  902. if i := strings.IndexAny(port, ".@"); i >= 0 {
  903. return port[:i]
  904. }
  905. return port
  906. }
  907. // Pasada 1: MACs propias del equipo (BSSID de cada radio + dirección de
  908. // cada interfaz de puerto inalámbrico, ambas con su variante de bit LAA
  909. // volteado: el bridge las aprende como si fueran estaciones externas).
  910. // Lo que cae en este conjunto es identidad, no cliente.
  911. self := map[string]bool{}
  912. addSelf := func(mac string) {
  913. if mac == "" {
  914. return
  915. }
  916. self[mac] = true
  917. if flipped, err := hexFlipLAA(mac); err == nil {
  918. self[flipped] = true
  919. }
  920. }
  921. for bssid := range bandByBSSID {
  922. addSelf(bssid)
  923. }
  924. addrs := map[string]string{}
  925. for _, port := range side {
  926. for _, iface := range []string{port, baseOf(port)} {
  927. if iface == "" {
  928. continue
  929. }
  930. if _, done := addrs[iface]; !done {
  931. addrs[iface] = addrOf(iface)
  932. }
  933. }
  934. }
  935. for _, addr := range addrs {
  936. addSelf(addr)
  937. }
  938. // Pasada 2: banda por MAC casando la dirección del puerto con un BSSID
  939. // sondeado; sin radio que casar (o MAC propia) la MAC se descarta: mejor
  940. // no decir nada que inventarse una banda.
  941. out := make(map[string]string, len(side))
  942. for mac, port := range side {
  943. um := strings.ToUpper(mac)
  944. if self[um] {
  945. continue
  946. }
  947. band := ""
  948. for _, iface := range []string{port, baseOf(port)} {
  949. if a := addrs[iface]; a != "" {
  950. if b, ok := bandByBSSID[a]; ok {
  951. band = b
  952. break
  953. }
  954. }
  955. }
  956. if band != "" {
  957. out[um] = band
  958. }
  959. }
  960. if len(out) == 0 {
  961. return nil
  962. }
  963. return out
  964. }
  965. // hexFlipLAA devuelve la MAC con el bit localmente-administrada (0x02 del
  966. // primer octeto) volteado, en formato colon-upper como el resto del FDB.
  967. func hexFlipLAA(mac string) (string, error) {
  968. b, err := net.ParseMAC(mac)
  969. if err != nil || len(b) == 0 {
  970. return "", err
  971. }
  972. b[0] ^= 0x02
  973. return strings.ToUpper(b.String()), nil
  974. }
  975. // probeLldp: vecinos LLDP de lldpd (#489). Contrato: Available=false cuando
  976. // lldpcli no existe (hint "instala lldpd"); Available=true con Neighbors
  977. // nil si la sonda falla esta ronda (lldpd parado, salida no JSON); [] vacío
  978. // honesto cuando no hay vecinos. Solo en el sondeo completo (Build): los
  979. // pushes event-driven no re-sondean y el server conserva el último bueno.
  980. func (p *Prober) probeLldp(ctx context.Context) *LldpData {
  981. if p.runBest(ctx, CmdLldpCheck, 0) == "" {
  982. return &LldpData{Available: false}
  983. }
  984. out := p.runBest(ctx, CmdLldpNeighbors, 5*time.Second)
  985. neighbors, err := ParseLldpNeighbors([]byte(out))
  986. if out != "" && err != nil {
  987. // #1481: JSON no vacío pero inparseable (lldpd exótico): el mismo
  988. // vecino en texto plano antes de declarar la ronda fallida. Con
  989. // out=="" simplemente no hay vecinos: no se gasta un spawn en el
  990. // texto (review de #1491, es el caso común de unidad sin vecinos).
  991. if txt := p.runBest(ctx, CmdLldpNeighborsText, 5*time.Second); txt != "" {
  992. neighbors, err = ParseLldpNeighborsText(txt), nil
  993. }
  994. }
  995. if err != nil {
  996. // JSON y texto fallaron esta ronda: Available con Neighbors nil
  997. // (el server conserva el último dato bueno).
  998. return &LldpData{Available: true}
  999. }
  1000. d := &LldpData{Available: true, Neighbors: neighbors}
  1001. // #1369: 0 vecinos honestos + binding SOLO a bridge (br-lan) = el caso
  1002. // silencioso de OpenWrt (los frames LLDP no suben al bridge master en
  1003. // nss-dp/DSA). Solo entonces consultamos UCI (un fork extra por ronda
  1004. // cuando sí hay vecinos sería desperdicio).
  1005. if len(neighbors) == 0 && LldpdBridgeOnly(p.runBest(ctx, CmdLldpdIfaces, 0)) {
  1006. d.Hint = HintLldpdBridgeOnly
  1007. }
  1008. return d
  1009. }
  1010. // probeClientBw: contadores por MAC de nlbwmon (#551). Contrato: Available=
  1011. // false cuando nlbw no está instalado (el server usa hostapd bytes); true con
  1012. // Hosts nil si la sonda falla esta ronda; {} vacío honesto si el daemon no
  1013. // tiene datos aún. Solo en el sondeo completo (Build), como LLDP.
  1014. func (p *Prober) probeClientBw(ctx context.Context) *ClientBwData {
  1015. if p.runBest(ctx, CmdNlbwmonCheck, 0) == "" {
  1016. return &ClientBwData{Available: false}
  1017. }
  1018. out := p.runBest(ctx, CmdNlbwmonJSON, 5*time.Second)
  1019. if out == "" {
  1020. return &ClientBwData{Available: true}
  1021. }
  1022. hosts, err := ParseNlbwJSON([]byte(out))
  1023. if err != nil {
  1024. return &ClientBwData{Available: true}
  1025. }
  1026. return &ClientBwData{Available: true, Hosts: hosts}
  1027. }
  1028. // probeLuCI: etiquetas de puertos/VLANs de LuCI (issue #258), si el router
  1029. // las define en /etc/config/luci. Best-effort: sin fichero/sección → nil.
  1030. func (p *Prober) probeLuCI(ctx context.Context) *LuCILabels {
  1031. out := p.runBest(ctx, CmdLuCILabels, 0)
  1032. if out == "" {
  1033. return nil
  1034. }
  1035. return ParseLuCILabels(out)
  1036. }
  1037. // probeDawn: lee el estado de DAWN (roaming/band-steering, Fase 14) vía
  1038. // `ubus call dawn get_network`. Devuelve nil si DAWN no está instalado
  1039. // (fail-soft silencioso — la sección queda ausente en el payload).
  1040. //
  1041. // El output de ubus mezcla campos del AP (channel, freq, etc.) con clientes
  1042. // anidados (MAC → {signal, ht, ...}) en el mismo objeto por BSSID. Los
  1043. // distinguimos por tipo: escalares = metadata del AP, objetos = clientes.
  1044. func (p *Prober) probeDawn(ctx context.Context) *DawnData {
  1045. out := p.runBest(ctx, "ubus call dawn get_network", 5*time.Second)
  1046. if out == "" {
  1047. return nil
  1048. }
  1049. // SSID → BSSID → {campos mixtos}
  1050. var raw map[string]map[string]json.RawMessage
  1051. if err := json.Unmarshal([]byte(out), &raw); err != nil {
  1052. return nil
  1053. }
  1054. ssids := make(map[string]DawnSSID, len(raw))
  1055. for ssid, bssids := range raw {
  1056. var aps []DawnAP
  1057. clients := make(map[string]DawnClient)
  1058. for bssidKey, bssidRaw := range bssids {
  1059. // Parsear todos los campos del BSSID como mapa flexible.
  1060. var fields map[string]json.RawMessage
  1061. if err := json.Unmarshal(bssidRaw, &fields); err != nil {
  1062. continue
  1063. }
  1064. // ¿Tiene "channel"? → es un AP.
  1065. chRaw, hasChannel := fields["channel"]
  1066. if !hasChannel {
  1067. continue
  1068. }
  1069. var channel int
  1070. json.Unmarshal(chRaw, &channel)
  1071. if channel == 0 {
  1072. continue
  1073. }
  1074. ap := DawnAP{BSSID: bssidKey, Channel: channel}
  1075. json.Unmarshal(fields["freq"], &ap.Freq)
  1076. json.Unmarshal(fields["channel_utilization"], &ap.Utilization)
  1077. json.Unmarshal(fields["num_sta"], &ap.Clients)
  1078. json.Unmarshal(fields["ht_support"], &ap.HT)
  1079. json.Unmarshal(fields["vht_support"], &ap.VHT)
  1080. json.Unmarshal(fields["local"], &ap.Local)
  1081. json.Unmarshal(fields["hostname"], &ap.Hostname)
  1082. aps = append(aps, ap)
  1083. // Buscar clientes anidados: cualquier key cuyo valor sea un
  1084. // objeto (empieza con '{') y tenga "signal".
  1085. for mac, valRaw := range fields {
  1086. if mac == "channel" || mac == "freq" || mac == "channel_utilization" ||
  1087. mac == "num_sta" || mac == "ht_support" || mac == "vht_support" ||
  1088. mac == "local" || mac == "hostname" || mac == "iface" ||
  1089. mac == "neighbor_report" || mac == "op_class" {
  1090. continue
  1091. }
  1092. s := strings.TrimSpace(string(valRaw))
  1093. if !strings.HasPrefix(s, "{") {
  1094. continue
  1095. }
  1096. var c struct {
  1097. Signal int `json:"signal"`
  1098. HT bool `json:"ht"`
  1099. VHT bool `json:"vht"`
  1100. }
  1101. if json.Unmarshal(valRaw, &c) == nil && c.Signal < 0 {
  1102. clients[strings.ToUpper(mac)] = DawnClient{
  1103. BSSID: bssidKey, Signal: c.Signal, HT: c.HT, VHT: c.VHT,
  1104. }
  1105. }
  1106. }
  1107. }
  1108. if len(aps) > 0 {
  1109. ssids[ssid] = DawnSSID{APs: aps, Clients: clients}
  1110. }
  1111. }
  1112. if len(ssids) == 0 {
  1113. return nil
  1114. }
  1115. return &DawnData{SSIDs: ssids}
  1116. }
  1117. // probeUsteer: lee el estado de usteer (roaming/steering) vía
  1118. // `ubus call usteer local_info`, `remote_info` y `connected_clients`. Devuelve
  1119. // nil si usteer no está instalado (fail-soft silencioso — la sección queda
  1120. // ausente en el payload).
  1121. func (p *Prober) probeUsteer(ctx context.Context) *UsteerData {
  1122. localOut := p.runBest(ctx, "ubus call usteer local_info", 5*time.Second)
  1123. remoteOut := p.runBest(ctx, "ubus call usteer remote_info", 5*time.Second)
  1124. if localOut == "" && remoteOut == "" {
  1125. return nil
  1126. }
  1127. clientsOut := p.runBest(ctx, "ubus call usteer connected_clients", 5*time.Second)
  1128. return ParseUsteer(localOut, remoteOut, clientsOut)
  1129. }
  1130. // usteerAPRaw es la forma cruda de una entrada de `ubus call usteer
  1131. // local_info` / `remote_info` (por BSSID/iface).
  1132. type usteerAPRaw struct {
  1133. BSSID string `json:"bssid"`
  1134. SSID string `json:"ssid"`
  1135. Freq int `json:"freq"`
  1136. NAssoc int `json:"n_assoc"`
  1137. Load int `json:"load"`
  1138. }
  1139. // usteerClientRaw es la forma cruda de una entrada de `ubus call usteer
  1140. // connected_clients` (por MAC).
  1141. type usteerClientRaw struct {
  1142. Signal int `json:"signal"`
  1143. }
  1144. // ParseUsteer parsea las salidas de `ubus call usteer local_info`,
  1145. // `remote_info` y `connected_clients` a un UsteerData (SSID → APs + clientes).
  1146. // Función pura para testear sin ejecutar ubus.
  1147. //
  1148. // - local_info: {"<iface>": {bssid, ssid, freq, n_assoc, load, ...}} (este router)
  1149. // - remote_info: {"<ip>#<iface>": {...}} (otros routers)
  1150. // - connected_clients: {"<iface>": {"<mac>": {signal, ...}}}
  1151. //
  1152. // Nota: usteer usa el nombre ubus de hostapd (`hostapd.phy0-ap0`) en
  1153. // local_info/remote_info y el ifname (`hostapd.wlan0`) en connected_clients;
  1154. // cuando ambas convenciones no casan, el cliente se omite (no se le asigna un
  1155. // SSID erróneo).
  1156. func ParseUsteer(localOut, remoteOut, clientsOut string) *UsteerData {
  1157. ssids := make(map[string]UsteerSSID)
  1158. ifaceSSID := map[string]string{}
  1159. addAP := func(ssid string, ap UsteerAP) {
  1160. s := ssids[ssid]
  1161. s.APs = append(s.APs, ap)
  1162. if s.Clients == nil {
  1163. s.Clients = map[string]UsteerClient{}
  1164. }
  1165. ssids[ssid] = s
  1166. }
  1167. if localOut != "" {
  1168. var local map[string]usteerAPRaw
  1169. if json.Unmarshal([]byte(localOut), &local) == nil {
  1170. for iface, ap := range local {
  1171. if ap.SSID == "" || ap.BSSID == "" {
  1172. continue
  1173. }
  1174. ifaceSSID[iface] = ap.SSID
  1175. addAP(ap.SSID, UsteerAP{
  1176. BSSID: strings.ToUpper(ap.BSSID), Freq: ap.Freq,
  1177. Load: ap.Load, Clients: ap.NAssoc, Local: true,
  1178. })
  1179. }
  1180. }
  1181. }
  1182. if remoteOut != "" {
  1183. var remote map[string]usteerAPRaw
  1184. if json.Unmarshal([]byte(remoteOut), &remote) == nil {
  1185. for key, ap := range remote {
  1186. if ap.SSID == "" || ap.BSSID == "" {
  1187. continue
  1188. }
  1189. host := key
  1190. if i := strings.IndexByte(key, '#'); i >= 0 {
  1191. host = key[:i]
  1192. }
  1193. addAP(ap.SSID, UsteerAP{
  1194. BSSID: strings.ToUpper(ap.BSSID), Hostname: host, Freq: ap.Freq,
  1195. Load: ap.Load, Clients: ap.NAssoc, Local: false,
  1196. })
  1197. }
  1198. }
  1199. }
  1200. if clientsOut != "" {
  1201. var clients map[string]map[string]usteerClientRaw
  1202. if json.Unmarshal([]byte(clientsOut), &clients) == nil {
  1203. for iface, macs := range clients {
  1204. ssid := ifaceSSID[iface]
  1205. if ssid == "" {
  1206. continue
  1207. }
  1208. s := ssids[ssid]
  1209. if s.Clients == nil {
  1210. s.Clients = map[string]UsteerClient{}
  1211. }
  1212. for mac, c := range macs {
  1213. if c.Signal >= 0 {
  1214. continue // señal 0/positiva = sin datos
  1215. }
  1216. s.Clients[strings.ToUpper(mac)] = UsteerClient{Signal: c.Signal}
  1217. }
  1218. ssids[ssid] = s
  1219. }
  1220. }
  1221. }
  1222. if len(ssids) == 0 {
  1223. return nil
  1224. }
  1225. return &UsteerData{SSIDs: ssids}
  1226. }
  1227. // probeDiscovery (#338): mDNS service discovery + randomized MAC detection.
  1228. // Runs umdns browse; enriches with randomized MACs from wireless clients.
  1229. func (p *Prober) probeDiscovery(ctx context.Context, wireless *WirelessData) *DiscoveryData {
  1230. out, err := p.run.Run(ctx, CmdMdnsBrowse, 5*time.Second)
  1231. var dd *DiscoveryData
  1232. if err == nil && strings.TrimSpace(out) != "" && strings.TrimSpace(out) != "{}" {
  1233. dd = ParseMdnsBrowse([]byte(out))
  1234. }
  1235. if dd == nil {
  1236. dd = &DiscoveryData{}
  1237. }
  1238. // Host records: a device that announces only its name (no service) shows
  1239. // up here and nowhere else. These win over a service instance name,
  1240. // which is the service's label rather than the device's own.
  1241. if out := p.runBest(ctx, CmdMdnsHosts, 5*time.Second); strings.TrimSpace(out) != "" {
  1242. if hosts := ParseMdnsHosts([]byte(out)); len(hosts) > 0 {
  1243. dd.MergeMdnsHosts(hosts)
  1244. }
  1245. }
  1246. // Detect randomized MACs from wireless clients.
  1247. if wireless != nil {
  1248. for mac := range wireless.Clients {
  1249. if IsRandomizedMAC(mac) {
  1250. dd.RandomMACs = append(dd.RandomMACs, mac)
  1251. }
  1252. }
  1253. }
  1254. if len(dd.Services) == 0 && len(dd.HostByIP) == 0 && len(dd.Models) == 0 && len(dd.Manufacturers) == 0 && len(dd.RandomMACs) == 0 {
  1255. return nil
  1256. }
  1257. return dd
  1258. }
  1259. // probeArp: tabla ARP del kernel (#377). nil si no hay fichero (equipo sin
  1260. // ARP, p. ej. contenedor); mapa vacío es resultado real.
  1261. //
  1262. // Reads `ip neigh` first, which carries the state of each entry, and only
  1263. // falls back to /proc/net/arp where `ip` is missing -- there the states are
  1264. // unknowable and the returned stale set is empty, the behaviour agents had
  1265. // before. stale lists the MACs the kernel remembers without confirming.
  1266. func (p *Prober) probeArp(ctx context.Context) (arp map[string]string, stale []string, devs map[string]string) {
  1267. // #2110: despertar las subredes que la unidad enruta ANTES de leer la
  1268. // tabla, para que el mismo `ip neigh` vea lo que el barrido confirmó.
  1269. p.scanPresence(ctx)
  1270. if out := p.runBest(ctx, CmdIpNeigh, 3*time.Second); out != "" {
  1271. m, st := ParseIPNeigh(out)
  1272. if len(m) > 0 {
  1273. // #2073: un vecino STALE es una direccion que el kernel recuerda
  1274. // sin confirmar. Antes de darlo por fantasma se comprueba con un
  1275. // echo corto, que es lo unico que puede resolver el caso de un
  1276. // host cableado con IP estatica que lleva rato en silencio.
  1277. due := p.stalePingDue()
  1278. var fresh string
  1279. m, st, fresh = p.confirmStaleNeighbours(ctx, m, st, due)
  1280. if fresh != "" {
  1281. out = fresh
  1282. }
  1283. // #2109: el mismo recheck sobre la tabla NDP. Un host solo-IPv6
  1284. // (SLAAC, sin lease ni tráfico v4) no tiene entrada en `ip -4
  1285. // neigh`, así que esta pasada es la única que puede confirmarlo.
  1286. for mac, ip := range p.confirmStaleNeighbours6(ctx, due) {
  1287. if _, ok := m[mac]; !ok {
  1288. m[mac] = ip
  1289. }
  1290. delete(st, mac)
  1291. }
  1292. for mac := range st {
  1293. stale = append(stale, mac)
  1294. }
  1295. sort.Strings(stale) // stable payloads, so a diff means a change
  1296. return m, stale, ParseIPNeighDevs(out)
  1297. }
  1298. }
  1299. out := p.runBest(ctx, CmdProcArp, 3*time.Second)
  1300. if out == "" {
  1301. return nil, nil, nil
  1302. }
  1303. m := ParseArp(out)
  1304. if m == nil {
  1305. m = map[string]string{}
  1306. }
  1307. return m, nil, ParseArpDevs(out)
  1308. }
  1309. // Parametros del recheck activo de vecinos (#2073), compartidos por el agente
  1310. // y por el sondeo SSH del servidor. El tope por ronda es deliberado: el caso
  1311. // real son un punado de vecinos idle, no un barrido de subred. Un /24 completo
  1312. // se deja para un arpscan, que necesita raw sockets.
  1313. const (
  1314. StalePingInterval = 60 * time.Second
  1315. StalePingMax = 16
  1316. StalePingTimeout = 1500 * time.Millisecond
  1317. )
  1318. // StalePingTargets devuelve, en orden determinista y con tope, las IPs de los
  1319. // vecinos STALE que merece la pena sondear. Compartida por el agente (ping
  1320. // local, #2073) y el cliente SSH del servidor (ping desde la unidad), para que
  1321. // los dos caminos sondeen lo mismo.
  1322. func StalePingTargets(arp map[string]string, stale map[string]bool) []string {
  1323. macs := make([]string, 0, len(stale))
  1324. for mac := range stale {
  1325. macs = append(macs, mac)
  1326. }
  1327. sort.Strings(macs)
  1328. ips := make([]string, 0, StalePingMax)
  1329. for _, mac := range macs {
  1330. if len(ips) >= StalePingMax {
  1331. break
  1332. }
  1333. if ip := arp[mac]; net.ParseIP(ip) != nil {
  1334. ips = append(ips, ip)
  1335. }
  1336. }
  1337. return ips
  1338. }
  1339. // confirmStaleNeighbours (#2073): manda un echo corto a cada IP de vecino
  1340. // STALE y relee la tabla. El kernel pasa a REACHABLE la entrada cuya respuesta
  1341. // ARP llega, asi que lo que se confirma es la PAREJA IP-MAC: una IP
  1342. // reutilizada por otro equipo no resucita la MAC vieja. Es justo el dato que
  1343. // falta cuando un host cableado con IP estatica lleva rato en silencio, la FDB
  1344. // ha caducado y el ARP solo esta STALE (#2063).
  1345. //
  1346. // Best effort: sin runner, sin vecinos o si la relectura falla, los datos
  1347. // vuelven como estaban. Throttle propio (stalePingInterval) para no lanzar
  1348. // pings en cada sondeo.
  1349. // stalePingDue decide si toca ronda y, si toca, marca el sello. Es el mismo
  1350. // sello para v4 y v6: una ronda de sondeo no debe pagar dos veces el throttle
  1351. // ni dejar la pasada v6 sin turno por haber gastado la v4.
  1352. func (p *Prober) stalePingDue() bool {
  1353. p.stalePingMu.Lock()
  1354. defer p.stalePingMu.Unlock()
  1355. if !p.stalePingAt.IsZero() && time.Since(p.stalePingAt) < StalePingInterval {
  1356. return false
  1357. }
  1358. p.stalePingAt = time.Now()
  1359. return true
  1360. }
  1361. func (p *Prober) confirmStaleNeighbours(ctx context.Context, arp map[string]string, stale map[string]bool, due bool) (map[string]string, map[string]bool, string) {
  1362. if p.run == nil || len(stale) == 0 || !due {
  1363. return arp, stale, ""
  1364. }
  1365. ips := StalePingTargets(arp, stale)
  1366. if len(ips) == 0 {
  1367. return arp, stale, ""
  1368. }
  1369. var wg sync.WaitGroup
  1370. for _, ip := range ips {
  1371. wg.Add(1)
  1372. go func(ip string) {
  1373. defer wg.Done()
  1374. _, _ = p.run.Run(ctx, "ping -c 1 -W 1 "+ip+" >/dev/null 2>&1", StalePingTimeout)
  1375. }(ip)
  1376. }
  1377. wg.Wait()
  1378. out := p.runBest(ctx, CmdIpNeigh, 3*time.Second)
  1379. if out == "" {
  1380. return arp, stale, ""
  1381. }
  1382. fresh, stillStale := ParseIPNeigh(out)
  1383. for mac := range stale {
  1384. if stillStale[mac] {
  1385. continue
  1386. }
  1387. // Respondio: el kernel ya tiene la entrada confirmada. Se copia la IP
  1388. // fresca (puede haber cambiado de direccion) y sale del set stale.
  1389. if ip := fresh[mac]; ip != "" {
  1390. arp[mac] = ip
  1391. }
  1392. delete(stale, mac)
  1393. }
  1394. return arp, stale, out
  1395. }
  1396. // confirmStaleNeighbours6 (#2109): lo mismo sobre `ip -6 neigh`. Mismo tope y
  1397. // mismo throttle, un echo por vecino STALE. La diferencia es que una
  1398. // direccion link-local solo se alcanza indicando la interfaz, que el propio
  1399. // `ip -6 neigh` declara (`dev br-lan`).
  1400. //
  1401. // Devuelve MAC → dirección confirmada. Best effort: sin tabla, sin vecinos o
  1402. // sin respuesta, nada. No toca `arp`: quien llama decide qué hacer con la
  1403. // pareja confirmada.
  1404. func (p *Prober) confirmStaleNeighbours6(ctx context.Context, due bool) map[string]string {
  1405. if p.run == nil || !due {
  1406. return nil
  1407. }
  1408. out := p.runBest(ctx, CmdIpNeigh6, 3*time.Second)
  1409. if out == "" {
  1410. return nil
  1411. }
  1412. arp, stale := ParseIPNeigh(out)
  1413. if len(stale) == 0 {
  1414. return nil
  1415. }
  1416. devs := ParseIPNeighDevsAll(out)
  1417. macs := make([]string, 0, len(stale))
  1418. for mac := range stale {
  1419. macs = append(macs, mac)
  1420. }
  1421. sort.Strings(macs)
  1422. type target struct{ mac, ip, dev string }
  1423. targets := make([]target, 0, StalePingMax)
  1424. for _, mac := range macs {
  1425. ip := arp[mac]
  1426. if net.ParseIP(ip) == nil {
  1427. continue
  1428. }
  1429. targets = append(targets, target{mac: mac, ip: ip, dev: devs[mac]})
  1430. if len(targets) >= StalePingMax {
  1431. break
  1432. }
  1433. }
  1434. if len(targets) == 0 {
  1435. return nil
  1436. }
  1437. var wg sync.WaitGroup
  1438. for _, t := range targets {
  1439. wg.Add(1)
  1440. go func(t target) {
  1441. defer wg.Done()
  1442. _, _ = p.run.Run(ctx, StalePing6Command(t.ip, t.dev), StalePingTimeout)
  1443. }(t)
  1444. }
  1445. wg.Wait()
  1446. fresh, stillStale := ParseIPNeigh(p.runBest(ctx, CmdIpNeigh6, 3*time.Second))
  1447. confirmed := map[string]string{}
  1448. for _, t := range targets {
  1449. if stillStale[t.mac] {
  1450. continue
  1451. }
  1452. if ip := fresh[t.mac]; ip != "" {
  1453. confirmed[t.mac] = ip
  1454. }
  1455. }
  1456. return confirmed
  1457. }
  1458. // StalePing6Command: echo IPv6 con dos caminos porque no todas las unidades traen
  1459. // el mismo binario (`ping -6` en busybox reciente, `ping6` en el resto). Para
  1460. // link-local se añade `-I <iface>`: sin interfaz el kernel no sabe por dónde
  1461. // mandarlo.
  1462. func StalePing6Command(ip, dev string) string {
  1463. iface := ""
  1464. if strings.HasPrefix(strings.ToLower(ip), "fe80:") && dev != "" {
  1465. iface = " -I " + dev
  1466. }
  1467. return fmt.Sprintf(
  1468. "ping -6%s -c 1 -W 1 %s >/dev/null 2>&1 || ping6%s -c 1 -W 1 %s >/dev/null 2>&1",
  1469. iface, ip, iface, ip,
  1470. )
  1471. }