probe.go 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689
  1. // Package probe — sondas del tier rápido OpenWrt: comandos (los LITERALES que
  2. // internal/adapters/openwrt.go lanza por SSH) + parseo de sus salidas +
  3. // shapes JSON del payload que el agente empuja a POST /api/ingest/agent.
  4. //
  5. // Es la ÚNICA fuente de verdad del parseo: server-go (internal/adapters) lo
  6. // importa con un replace ../agent, y el binario netpulse-agent ejecuta los
  7. // mismos comandos localmente. Solo stdlib (el binario del agente tiene
  8. // objetivo ≤ 3 MB y CGO_ENABLED=0).
  9. package probe
  10. import (
  11. "encoding/json"
  12. "fmt"
  13. "net"
  14. "net/netip"
  15. "os"
  16. "regexp"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "github.com/gnacho/netpulse/agent/macaddr"
  22. )
  23. // ---------------------------------------------------------------------------
  24. // Comandos (idénticos a los del sondeo SSH de openwrt.go)
  25. // ---------------------------------------------------------------------------
  26. const (
  27. CmdProcStat = "grep '^cpu ' /proc/stat"
  28. // CmdProcUptime (#1481): fallback portable de uptime cuando no hay ubus
  29. // (Asuswrt, Linux genérico). Primer campo = segundos desde boot.
  30. CmdProcUptime = "cat /proc/uptime 2>/dev/null"
  31. // CmdTemp (#1484): temperatura de la CPU. En x86 la thermal_zone0 suele ser
  32. // acpitz (ambiente ACPI), así que se elige por `type` con prioridad y la
  33. // primera zona legible queda solo como fallback (ARM/SBC: cpu-thermal).
  34. // Último recurso (#1500): hwmon para equipos SIN thermal zones (Synology
  35. // DSM: k10temp en /sys/class/hwmon, cero zones). Con zones presentes
  36. // mandan las zones: una sola fuente por equipo (#1484).
  37. CmdTemp = `o=""; for w in x86_pkg_temp cpu-thermal cpu_thermal soc-thermal; do for d in /sys/class/thermal/thermal_zone*; do [ "$(cat "$d/type" 2>/dev/null)" = "$w" ] && o=$(cat "$d/temp" 2>/dev/null) && break 2; done; done; [ -n "$o" ] || for f in /sys/class/thermal/thermal_zone*/temp; do [ -r "$f" ] && o=$(cat "$f") && break; done; [ -n "$o" ] || for h in /sys/class/hwmon/hwmon*; do case "$(cat "$h/name" 2>/dev/null)" in k10temp|coretemp|k8temp|cpu_thermal|soc_thermal) [ -r "$h/temp1_input" ] && o=$(cat "$h/temp1_input") && break;; esac; done; printf '%s\n' "$o"`
  38. CmdNetDev = "cat /proc/net/dev | tail -n +3"
  39. // CmdPingWan: latencia + pérdida a internet (solo gateway). %s = target.
  40. CmdPingWan = "ping -c 3 -W 2 %s 2>/dev/null | tail -2"
  41. // CmdPingGateway: ping corto al gateway desde un AP. %s = host gateway.
  42. CmdPingGateway = "ping -c 2 -W 2 %s 2>/dev/null | tail -1"
  43. CmdDhcpUbus = "ubus call dhcp ipv4leases"
  44. // CmdDhcpReservations: the `config host` entries of /etc/config/dhcp. A
  45. // device with a fixed address set on the device itself never asks for a
  46. // lease, so the name the admin pinned here is the only one the router
  47. // has for it. Lines for other sections come through too; the parser
  48. // keeps only the ones it saw declared as host.
  49. CmdDhcpReservations = `uci -q show dhcp 2>/dev/null | grep -E "=host$|\.(mac|name|ip)=" || true`
  50. // CmdDhcpFile: cat del fichero de leases de dnsmasq. Resuelve la ubicación
  51. // real vía UCI (dhcp.@dnsmasq[0].leasefile), porque puede NO ser la
  52. // standard /tmp/dhcp.leases (p. ej. en un SSD montado, #568); si el valor
  53. // UCI no existe o está vacío, cae a /tmp/dhcp.leases. Busybox: test -n y
  54. // comillas simples para $f.
  55. CmdDhcpFile = `f=$(uci -q get dhcp.@dnsmasq[0].leasefile 2>/dev/null); [ -n "$f" ] || f=/tmp/dhcp.leases; cat "$f" 2>/dev/null || true`
  56. // CmdGlClients (GL.iNet): base de clientes completa del firmware. Es un
  57. // SUPERSET de dhcp.leases: incluye equipos con IP estática o sin lease
  58. // DHCP que el dnsmasq del Flint2 no lista (issue #5 bug 1).
  59. CmdGlClients = "ubus call gl-clients list 2>/dev/null || true"
  60. // CmdIwinfoAssoc: "<mac> <sig> <freq>" por cliente wifi asociado.
  61. // #2176: se salta antes de llamar a iwinfo cualquier interfaz en
  62. // operstate `down` (deshabilitada o sin portadora). En mt_wifi el ioctl
  63. // de `iwinfo <if> info` contra una interfaz caída escribe una línea
  64. // KERN_ERR por interfaz y ciclo y llena el log del router.
  65. CmdIwinfoAssoc = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` +
  66. `[ "$(cat /sys/class/net/$i/operstate 2>/dev/null)" != down ] || continue; ` +
  67. `freq=$(iwinfo "$i" info 2>/dev/null | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` +
  68. `iwinfo "$i" assoclist 2>/dev/null | sed -n 's/^\([0-9A-Fa-f:]\{17\}\) *\(-[0-9]*\).*/\1 \2/p' | while read mac sig; do ` +
  69. `echo "$mac $sig $freq"; done; done`
  70. // CmdHostapdClients (#368): clientes por AP vía ubus (una llamada por AP,
  71. // binario pequeñísimo, sin ucode ni libiwinfo). Emite "==AP==<obj>" antes
  72. // del JSON multi-línea de cada get_clients; el parser de Go trocea por la
  73. // marca. Mucho más barato que iwinfo en CPUs justas (MT7621: el ucode de
  74. // iwinfo quemaba 25% de CPU con churn de roaming).
  75. CmdHostapdClients = `for o in $(ubus list 'hostapd.*' 2>/dev/null); do ` +
  76. `echo "==AP==$o"; ubus call "$o" get_clients 2>/dev/null; done; ` +
  77. // #1757: SSID por interfaz AP. `ubus call get_clients` no lo trae y el
  78. // objeto ubus solo da el nombre de la interfaz (phy1-ap2), que es lo
  79. // que necesita la VLAN; el SSID lo pone la ficha del cliente.
  80. `echo "==SSID=="; iw dev 2>/dev/null | awk '/^[ \t]*Interface /{i=$2} /^[ \t]*ssid /{print i, $2}'`
  81. // CmdWirelessCombined (#368): iwinfo en UNA pasada por interfaz (info una
  82. // vez + assoclist una vez) emitiendo clientes y resumen de radio juntos.
  83. // Sustituye a CmdIwinfoAssoc+CmdRadios cuando ubus no está: la mitad de
  84. // spawns. Líneas "C|mac|sig|freq" (clientes) y
  85. // "R|freq|ch|ht|tx|bssid|noise|n" (radio; #1213).
  86. CmdWirelessCombined = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` +
  87. `[ "$(cat /sys/class/net/$i/operstate 2>/dev/null)" != down ] || continue; ` +
  88. `info=$(iwinfo "$i" info 2>/dev/null) || continue; ` +
  89. `echo "$info" | grep -q ESSID || continue; ` +
  90. `freq=$(echo "$info" | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` +
  91. `ch=$(echo "$info" | sed -n 's/.*Channel: \([0-9][0-9]*\).*/\1/p' | head -1); ` +
  92. `ht=$(echo "$info" | sed -n 's/.*HT [Mm]ode: \([A-Za-z0-9]*\).*/\1/p' | head -1); ` +
  93. `tx=$(echo "$info" | sed -n 's/.*Tx-Power: \([0-9]*\).*/\1/p' | head -1); ` +
  94. `bssid=$(echo "$info" | sed -n 's/.*Access Point: \([0-9A-Fa-f:]\{17\}\).*/\1/p' | head -1); ` +
  95. `noise=$(echo "$info" | sed -n 's/.*Noise: \(-\{0,1\}[0-9][0-9]*\).*/\1/p' | head -1); ` +
  96. `al=$(iwinfo "$i" assoclist 2>/dev/null); ` +
  97. `n=$(echo "$al" | grep -c '^[0-9A-Fa-f:]'); ` +
  98. `echo "R|$freq|$ch|$ht|$tx|$bssid|$noise|$n"; ` +
  99. `echo "$al" | sed -n "s/^\([0-9A-Fa-f:]\{17\}\) *\(-[0-9]*\).*/C|\1|\2|$freq/p"; done`
  100. // CmdRadios: "freq|ch|ht|tx|bssid|noise|n" por radio (se agrega por banda
  101. // al parsear). #1213: bssid + noise de iwinfo info.
  102. CmdRadios = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` +
  103. `[ "$(cat /sys/class/net/$i/operstate 2>/dev/null)" != down ] || continue; ` +
  104. `info=$(iwinfo "$i" info 2>/dev/null) || continue; ` +
  105. `echo "$info" | grep -q ESSID || continue; ` +
  106. `freq=$(echo "$info" | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` +
  107. `ch=$(echo "$info" | sed -n 's/.*Channel: \([0-9][0-9]*\).*/\1/p' | head -1); ` +
  108. `ht=$(echo "$info" | sed -n 's/.*HT [Mm]ode: \([A-Za-z0-9]*\).*/\1/p' | head -1); ` +
  109. `tx=$(echo "$info" | sed -n 's/.*Tx-Power: \([0-9]*\).*/\1/p' | head -1); ` +
  110. `bssid=$(echo "$info" | sed -n 's/.*Access Point: \([0-9A-Fa-f:]\{17\}\).*/\1/p' | head -1); ` +
  111. `noise=$(echo "$info" | sed -n 's/.*Noise: \(-\{0,1\}[0-9][0-9]*\).*/\1/p' | head -1); ` +
  112. `n=$(iwinfo "$i" assoclist 2>/dev/null | grep -c '^[0-9A-Fa-f:]'); ` +
  113. `echo "$freq|$ch|$ht|$tx|$bssid|$noise|$n"; done`
  114. // CmdScan (#452): scan pasivo de vecinos con `iw dev`. Lista interfaces,
  115. // emite "==IFACE==<iface>" antes de cada scan y parsea BSS/freq/signal/SSID.
  116. // Si `iw` no está disponible, la sección Scans queda vacía (best-effort).
  117. //
  118. // DEPRECATED (#1338): el bucle monolítico corría con UN solo timeout para
  119. // todas las interfaces y, al expirar, la salida parcial se descartaba
  120. // entera. Una radio lenta (5 GHz en canal DFS, scan pasivo canal a canal)
  121. // dejaba la unidad sin NINGÚN vecino, aunque las demás interfaces sí
  122. // hubieran escaneado. El agente escanea ahora por interfaz con
  123. // CmdScanIface, cada una con su propio presupuesto. Se conserva la
  124. // constante por compatibilidad del módulo (consumidores vendorizados).
  125. CmdScan = `for i in $(iw dev 2>/dev/null | awk '/Interface / {print $2}'); do echo "==IFACE==$i"; iw dev "$i" scan 2>/dev/null; done`
  126. // CmdSurvey (#1214): `iw dev <iface> survey dump` por interfaz, con el
  127. // mismo marcador "==IFACE==" que CmdScan. El server parsea el texto
  128. // crudo con su parser existente: alimenta la lente "Ahora" (ocupación
  129. // por canal en vivo) en unidades agent-only sin SSH. Barato: no saca
  130. // la radio del canal.
  131. CmdSurvey = `for i in $(iw dev 2>/dev/null | awk '/Interface / {print $2}'); do echo "==IFACE==$i"; iw dev "$i" survey dump 2>/dev/null; done`
  132. // CmdIwDev (#1087): `iw dev` a secas, sin scan. Lista las interfaces con
  133. // su MAC y SSID: fuente de los BSSIDs propios para el análisis de
  134. // canales. Barato (no saca la radio del canal).
  135. CmdIwDev = "iw dev 2>/dev/null"
  136. // scanIfaceTimeout (#1338): presupuesto POR INTERFAZ del scan de vecinos.
  137. // Una radio 5 GHz en canal DFS escanea en pasivo canal a canal y puede
  138. // tardar varios segundos; con el presupuesto único de 10 s para todas,
  139. // esa radio lenta mataba el bucle y se perdían también los scans ya
  140. // hechos. Cada interfaz tiene ahora su propio tiempo y un fallo o un
  141. // cuelgue solo vacía su propia sección.
  142. scanIfaceTimeout = 8 * time.Second
  143. // maxScanFallbacks (#1839): reintentos por radio cuando la interfaz
  144. // elegida rechaza el scan. Dos basta para cubrir AP + managed + una
  145. // tercera, y acota el peor caso (3 x 8 s por radio).
  146. maxScanFallbacks = 2
  147. // CmdRadioSections (#500): secciones wifi-device de UCI con su banda, para
  148. // resolver "2.4 GHz" → radio0 (la relación iface→sección no sale de iwinfo).
  149. CmdRadioSections = `uci -q show wireless 2>/dev/null | grep -E "=wifi-device$|\.band=|\.hwmode="`
  150. // CmdUciWireless (#1450): volcado crudo de la configuración wireless, tal
  151. // cual lo emite `uci show wireless`. El server lo parsea con su
  152. // parseUciWireless (vista 802.11r) en unidades agent-only sin SSH: el
  153. // parser NO se duplica en el agente, igual que con CmdSurvey (#1214).
  154. // Solo lectura de /etc/config/wireless, barato (unos pocos KB).
  155. //
  156. // Los campos de SECRETO se descartan antes de enviarlo: a diferencia del
  157. // camino SSH (que los lee y los tira en el server), este volcado viaja en
  158. // cada push y queda persistido en kv agent.state.<slug>. El parser 802.11r
  159. // no usa la PSK, así que filtrarla no quita información a la vista.
  160. CmdUciWireless = `uci -q show wireless 2>/dev/null | ` + uciWirelessSecretsFilter
  161. // uciWirelessSecretsFilter: líneas `option` con secretos fuera del push
  162. // (key/PSK/SAE/contraseñas/RADIUS). Se conserva el resto del volcado tal
  163. // cual. Busybox grep -E soporta la alternancia.
  164. uciWirelessSecretsFilter = `grep -v -E '\.(key|sae_key|wpa_psk|psk|password|secret|radius_secret)='`
  165. // CmdPortStates: "<name> <operstate> <speed> <dsa> <type> <conduit>" por
  166. // interfaz.
  167. // - dsa: "dsa" cuando la interfaz es un conduit DSA (tiene el directorio
  168. // /sys/class/net/<i>/dsa): el puerto CPU interno del switch, no una
  169. // boca usable (#847); "-" si no.
  170. // - type: el ARPHRD del kernel (1 = ethernet). FORK: para no tomar por
  171. // boca un uplink que no lo es (wwan0 de un módem celular).
  172. // - conduit: FORK. La interfaz inferior (lower_*) cuando la hay: en un
  173. // switch DSA las bocas cuelgan de la interfaz de CPU (lan1/lan2 →
  174. // lower_eth0). "-" cuando no hay ninguna.
  175. // Los campos a partir del tercero son opcionales para ParsePortStates.
  176. CmdPortStates = `for d in /sys/class/net/*; do i=$(basename "$d"); ` +
  177. `o=$(cat "$d/operstate" 2>/dev/null || echo unknown); ` +
  178. `s=$(cat "$d/speed" 2>/dev/null || echo -1); ` +
  179. `x=$([ -d "$d/dsa" ] && echo dsa || echo -); ` +
  180. `t=$(cat "$d/type" 2>/dev/null || echo -1); ` +
  181. `c=-; for l in "$d"/lower_*; do [ -e "$l" ] || continue; c=${l##*/lower_}; break; done; ` +
  182. `echo "$i $o $s $x $t $c"; done`
  183. // CmdProcArp (#377): tabla ARP del kernel, "IP dev mac ..." por línea.
  184. CmdProcArp = "cat /proc/net/arp 2>/dev/null"
  185. // CmdIpNeigh: the same neighbour table, but with the state of each entry,
  186. // which /proc/net/arp cannot express -- its flags say ATF_COM for
  187. // REACHABLE and for STALE alike. A STALE neighbour is one the kernel has
  188. // not confirmed since the device last spoke, and it survives long after
  189. // the device is gone, so treating it as presence draws hosts that are no
  190. // longer there. Falls back to /proc/net/arp when `ip` is missing.
  191. CmdIpNeigh = "ip -4 neigh show 2>/dev/null"
  192. // CmdIpNeigh6: la tabla de vecinos IPv6 (NDP). Misma forma que la v4, con
  193. // direcciones fe80:: scoped a la interfaz (#2109).
  194. CmdIpNeigh6 = "ip -6 neigh show 2>/dev/null"
  195. CmdBoardJSON = "cat /etc/board.json 2>/dev/null"
  196. // bridgeDetect: resuelve el nombre del bridge LAN en el router: br-lan,
  197. // br0, o el primer bridge real presente en /sys/class/net (#1435: en
  198. // switches OpenWrt con el bridge renombrado, p.ej. "switch", los dos
  199. // candidatos clásicos no existen y la FDB salía vacía). Si no hay
  200. // bridge, BR queda vacío y los comandos fallan en suave (mismo
  201. // comportamiento que antes en equipos sin bridge).
  202. bridgeDetect = `BR=br-lan; [ -d /sys/class/net/$BR/bridge ] || BR=br0; [ -d /sys/class/net/$BR/bridge ] || { BR=; for d in /sys/class/net/*/bridge; do [ -d "$d" ] || continue; BR=${d%/bridge}; BR=${BR##*/}; break; done; }; `
  203. CmdBrifMembers = bridgeDetect + `ls /sys/class/net/$BR/brif/ 2>/dev/null`
  204. // CmdBridgeFDB: no asume `brctl`: prueba brctl y, si no existe o no aporta,
  205. // `bridge fdb show` (OpenWrt/GLuON modernos usan iproute2). Issue #253.
  206. // SIN `command -v`: el ash de busybox en Merlin/Asuswrt NO tiene el builtin
  207. // `command` ("sh: command: not found"), así que la guarda antigua
  208. // `if command -v brctl` fallaba siempre y caía al branch de `bridge`, que
  209. // allí no existe: la sección MACS salía vacía y el server se quedaba sin
  210. // FDB del AP (todos sus clientes cableados se atribuían al gateway o al
  211. // switch de arriba). Ahora se intentan ambas vías en subshells con stderr
  212. // suprimido; si las dos existen las líneas duplicadas son inofensivas
  213. // (ambas resuelven al mismo ifname en ParseBridgeFdb). El `true` final
  214. // garantiza exit 0 para que el runner no descarte la salida.
  215. // La vía bridge excluye las entradas LOCALES (flag "permanent": la MAC del
  216. // propio bridge registrada en cada puerto) para paridad con brctl ($3=="no"
  217. // allí); sin esto el server ve la MAC propia aprendida en el puerto y lo
  218. // clasifica como uplink, descartando TODOS sus clientes cableados (#506).
  219. //
  220. // CmdBridgeFDB: "==PORTS==<bridge>" (port_no ifname) + "==MACS==<bridge>"
  221. // (port mac [vlan]). El sufijo con el nombre del bridge es el que permite
  222. // leer TODOS los bridges sin mezclar sus tablas de puertos (cada bridge
  223. // numera sus puertos desde 1) y es opcional al parsear, así que la salida
  224. // antigua de un agente viejo sigue valiendo (#1757).
  225. //
  226. // Antes se leía UN solo bridge (br-lan, br0 o el primero). Un router que
  227. // segmenta con subinterfaces 802.1Q tiene un bridge POR segmento: los
  228. // clientes de br-iot/br-guest no aparecían en ninguna tabla y el mapa los
  229. // pintaba sin puerto y sin VLAN.
  230. //
  231. // El tercer campo de MACS es el `vlan <id>` que `bridge fdb show` imprime
  232. // en bridges con VLAN filtering: es la VLAN REAL del cliente, no el PVID
  233. // del puerto por el que entró.
  234. CmdBridgeFDB = `echo "==PORTS=="; for d in /sys/class/net/*; do [ -d "$d/bridge" ] || continue; ` +
  235. `br=$(basename "$d"); echo "==PORTS==$br"; ` +
  236. `for b in "$d"/brif/*; do [ -r "$b/port_no" ] && echo "$(cat $b/port_no) $(basename $b)"; done; done; ` +
  237. `echo "==MACS=="; for d in /sys/class/net/*; do [ -d "$d/bridge" ] || continue; ` +
  238. `br=$(basename "$d"); echo "==MACS==$br"; ` +
  239. `(brctl showmacs "$br" 2>/dev/null | awk 'NR>1 && $3=="no" {print $1, $2}') 2>/dev/null; ` +
  240. `(bridge fdb show br "$br" 2>/dev/null | awk 'NF>=3 && $1!="01:" && $1!="33:33:" && $1!="ff:ff:" && $1!="00:00:00:00:00:00" && $0 !~ /permanent/ {p=""; v=0; for(i=1;i<=NF;i++){ if($i=="dev") p=$(i+1); if($i=="vlan") v=$(i+1) }; if(p!="") print p, $1, v}') 2>/dev/null; done; true`
  241. CmdBridgeMAC = bridgeDetect + "cat /sys/class/net/$BR/address 2>/dev/null"
  242. // CmdIfaceMACs (#1765): "iface mac" de TODAS las interfaces del kernel.
  243. // Un equipo responde por la MAC del bridge, la de cada VLAN, la del puerto
  244. // CPU de un switch DSA y la de cada radio. Las que no son la MAC del router
  245. // guardado en la flota se aprenden en la FDB de un vecino y salían como
  246. // clientes desconocidos sin nombre ni IP. El equipo es la única fuente
  247. // fiable de su propia lista.
  248. CmdIfaceMACs = `for d in /sys/class/net/*; do i=$(basename "$d"); ` +
  249. `[ -r "$d/address" ] && echo "$i $(cat "$d/address" 2>/dev/null)"; done`
  250. CmdUbusSystemBoard = "ubus call system board"
  251. CmdUbusSystemInfo = "ubus call system info"
  252. CmdUbusWireless = "ubus call network.wireless status"
  253. // CmdLuCILabels: etiquetas de puertos/VLANs de LuCI (issue #258). OpenWrt
  254. // snapshots añaden `config switchvlan 'port_labels'` y `'vlan_labels'` en
  255. // /etc/config/luci con nombres amigables para la topología. Se lee el
  256. // fichero crudo (uci show luci sería más ruidoso: todo el paquete).
  257. CmdLuCILabels = "cat /etc/config/luci 2>/dev/null"
  258. // CmdWanStatus: estado de la interfaz WAN (solo gateway) vía ubus.
  259. // Da proto ("pppoe"), IP, gateway (ptpaddress/nexthop) y DNS (issue #276).
  260. CmdWanStatus = "ubus call network.interface.wan status 2>/dev/null || true"
  261. // CmdNetworkDump: estado de TODAS las interfaces, para elegir el uplink
  262. // por la ruta por defecto en vez de por el nombre "wan" (ver pickUplink)
  263. // y saber por qué boca sale internet.
  264. CmdNetworkDump = "ubus call network.interface dump 2>/dev/null || true"
  265. CmdBridgeVlan = "bridge vlan show 2>/dev/null || true"
  266. // CmdUciBridgeVlan: the VLANs as configured, for the routers whose
  267. // firmware carries no `bridge` binary (an optional package, absent on
  268. // plenty of boards that do use VLANs) and for the ones that segment
  269. // with 802.1Q subinterfaces, which the kernel reports all on VLAN 1
  270. // (#1757). Both models are read from `uci show network`.
  271. //
  272. // The section type lines must survive the filter (#1936): `uci show`
  273. // prints `network.lan=interface`, and that is the only place a named
  274. // section says what it is. Without it ParseUciNetworks sees no
  275. // interface at all and the networks view stays empty on every unit.
  276. CmdUciBridgeVlan = `uci -q show network 2>/dev/null | grep -E "=bridge-vlan$|=device$|=interface$|\.(device|vlan|ports|type|name|proto|ipaddr|netmask)=" || true`
  277. // CmdMdnsBrowse (#338): mDNS service discovery via umdns (OpenWrt's
  278. // lightweight mDNS daemon). Returns JSON with hostname -> services.
  279. // Falls back to empty if umdns is not installed.
  280. CmdMdnsBrowse = "ubus call umdns browse 2>/dev/null || echo '{}'"
  281. // CmdMdnsHosts (#338): the plain host records umdns has learned, as
  282. // "<name>.local" -> {ipv4, ipv6}. browse only lists hosts that advertise
  283. // a SERVICE; a device that just announces its name (most laptops and
  284. // phones) appears here and nowhere else, and this is the map that names
  285. // a client with no DHCP hostname.
  286. CmdMdnsHosts = "ubus call umdns hosts 2>/dev/null || echo '{}'"
  287. CmdEthtoolSFP = "ethtool -m %s 2>/dev/null || true"
  288. )
  289. // CmdScanIface (#1338): scan pasivo de UNA interfaz. El agente lo lanza una
  290. // vez por interfaz de `iw dev` (en vez del bucle monolítico de CmdScan) para
  291. // que cada radio tenga su propio presupuesto de tiempo y una interfaz lenta
  292. // o colgada no se lleve por delante los resultados de las demás.
  293. func CmdScanIface(iface string) string {
  294. return `iw dev "` + iface + `" scan 2>/dev/null`
  295. }
  296. // ---------------------------------------------------------------------------
  297. // Shapes parseados (salida de las sondas; contrato del payload del agente)
  298. // ---------------------------------------------------------------------------
  299. // SysInfo: ubus system info (uptime, memoria, load).
  300. type SysInfo struct {
  301. Uptime float64 `json:"uptime"`
  302. Load []float64 `json:"load"`
  303. // Timezone (#1500): nombre IANA ("Asia/Shanghai") que el agente lee de
  304. // /etc/localtime (o /etc/timezone, /etc/TZ). ubus nunca lo da, así que
  305. // sin este campo la ficha mostraba "—" incluso en equipos con ubus.
  306. Timezone string `json:"timezone,omitempty"`
  307. Memory struct {
  308. Total float64 `json:"total"`
  309. Free float64 `json:"free"`
  310. Buffered float64 `json:"buffered"`
  311. Available float64 `json:"available"`
  312. Cached float64 `json:"cached,omitempty"` // cache de ficheros, la rellena el agente (ubus no lo da)
  313. Used float64 `json:"used"` // suma de VmRSS de procesos (#513)
  314. } `json:"memory"`
  315. }
  316. // BoardInfo: ubus system board (metadatos estáticos).
  317. type BoardInfo struct {
  318. Model string `json:"model"`
  319. Hostname string `json:"hostname"`
  320. System string `json:"system"`
  321. // BoardName es el board_name de ubus ("redmi,ax6"): el identificador
  322. // que casa con los perfiles de ASU (#477).
  323. BoardName string `json:"board_name"`
  324. Release struct {
  325. Version string `json:"version"`
  326. Description string `json:"description"`
  327. // Target es el DISTRIB_TARGET ("qualcommax/ipq807x"), lo que ASU
  328. // necesita junto al board_name para localizar la imagen (#477).
  329. Target string `json:"target"`
  330. } `json:"release"`
  331. }
  332. // WanInfo: datos de la conexión WAN (issue #276). Solo el gateway lo rellena;
  333. // los campos vacíos significan "sin datos WAN" (APs/desconocido).
  334. type WanInfo struct {
  335. Proto string `json:"proto,omitempty"` // "pppoe"|"dhcp"|"static"...
  336. Device string `json:"device,omitempty"` // interfaz L3 (p.ej. "pppoe-wan")
  337. IP string `json:"ip,omitempty"` // dirección IPv4 pública
  338. Gateway string `json:"gateway,omitempty"` // puerta de enlace (nexthop/ptpaddress)
  339. DNS []string `json:"dns,omitempty"` // servidores DNS
  340. // IPv6 es la dirección global (sin ULA) de la interfaz WAN cuando el
  341. // origen la conoce: el agente nativo no la sondea todavía, un pusher
  342. // externo sí puede mandarla (#2226). Vacía o ausente con agentes y
  343. // pushers antiguos, que es lo que ya hacían.
  344. IPv6 string `json:"ipv6,omitempty"`
  345. // Port es la interfaz por debajo del protocolo: la boca por la que sale
  346. // internet ("lan1" para un PPPoE sobre esa boca, "eth1.20" con VLAN).
  347. // Vacía cuando el uplink no pasa por ninguna (módem celular).
  348. Port string `json:"port,omitempty"`
  349. }
  350. // DhcpReservation is one `config host` of /etc/config/dhcp: the name and
  351. // address pinned to a MAC (both optional). MAC uppercase, like DhcpLease.
  352. type DhcpReservation struct {
  353. MAC string `json:"mac"`
  354. Name string `json:"name,omitempty"`
  355. IP string `json:"ip,omitempty"`
  356. }
  357. // DhcpLease es {mac, ip, hostname} (mac en mayúsculas) + señales de huella
  358. // DHCP (vendor class y client-id) y expiración del lease cuando se dispone.
  359. type DhcpLease struct {
  360. MAC string `json:"mac"`
  361. IP string `json:"ip"`
  362. Hostname string `json:"hostname"`
  363. VendorClass string `json:"vendorClass,omitempty"`
  364. ClientID string `json:"clientId,omitempty"`
  365. LeaseExpiresAt *int64 `json:"leaseExpiresAt,omitempty"` // Unix segundos; nil si no se conoce
  366. }
  367. // WirelessClient es {signalDbm, band} por MAC + contadores de tráfico de la
  368. // estación cuando el driver los expone (#551). RxBytes/TxBytes son contadores
  369. // ACUMULADOS desde que la estación se asoció (ubus hostapd get_clients →
  370. // hostapd_drv_read_sta_data); el server calcula el delta entre muestras para
  371. // obtener bytes del intervalo. omitempty: ausentes si la fuente no los da
  372. // (iwinfo, drivers sin read_sta_data).
  373. type WirelessClient struct {
  374. SignalDbm int `json:"signalDbm"`
  375. Band string `json:"band"`
  376. RxBytes uint64 `json:"rxBytes,omitempty"`
  377. TxBytes uint64 `json:"txBytes,omitempty"`
  378. // Iface/SSID (#1757): interfaz AP y SSID con la que la estacion esta
  379. // asociada. Permiten al servidor cruzar la estacion con el bridge VLAN
  380. // filtering y saber en que segmento vive. Omitidos cuando la fuente no
  381. // los expone (wl, iwinfo, drivers sin esa salida): el campo es opcional.
  382. Iface string `json:"iface,omitempty"`
  383. SSID string `json:"ssid,omitempty"`
  384. }
  385. // PortState es {name, up, speed} de una interfaz (/sys operstate+speed).
  386. type PortState struct {
  387. Name string `json:"name"`
  388. Up bool `json:"up"`
  389. // Oper is the raw sysfs operstate (up/down/dormant/unknown/...). Kept so
  390. // the panel can tell a real port (up, or down when unplugged) from a
  391. // Broadcom internal ghost interface that never carries user traffic
  392. // (dormant/unknown) and must not be shown as a usable port.
  393. Oper string `json:"oper,omitempty"`
  394. Speed string `json:"speed"` // "1 Gbps" | "2.5 Gbps" | "100 Mbps" | "—"
  395. // DSA: la interfaz es un conduit DSA (puerto CPU interno del switch,
  396. // /sys/class/net/<i>/dsa presente). No es una boca usable: se excluye
  397. // de los puertos del panel (#847).
  398. DSA bool `json:"dsa,omitempty"`
  399. // Type es el ARPHRD de /sys/class/net/<i>/type: 1 = ethernet. 0 o
  400. // negativo = desconocido (salida antigua), y entonces no se descarta
  401. // nada por el tipo. FORK.
  402. Type int `json:"type,omitempty"`
  403. // Conduit es la interfaz inferior (lower_*), vacío si no hay. En un
  404. // switch DSA es el puerto de CPU del que cuelga la boca. FORK.
  405. Conduit string `json:"conduit,omitempty"`
  406. }
  407. // fmtSpeedMbps (#847) formatea la velocidad de enlace: Gbps con decimales
  408. // cuando no es múltiplo de 1000 (2500 → "2.5 Gbps"; antes truncaba a
  409. // entero y mentía "2 Gbps") y Mbps en otro caso.
  410. func fmtSpeedMbps(mbps int) string {
  411. if mbps >= 1000 {
  412. if mbps%1000 == 0 {
  413. return strconv.Itoa(mbps/1000) + " Gbps"
  414. }
  415. return strconv.FormatFloat(float64(mbps)/1000, 'f', 1, 64) + " Gbps"
  416. }
  417. return strconv.Itoa(mbps) + " Mbps"
  418. }
  419. // ARPHRDEther es el /sys/class/net/<i>/type de una interfaz ethernet.
  420. const ARPHRDEther = 1
  421. // PortLayout es una boca del layout canónico (/etc/board.json).
  422. type PortLayout struct {
  423. ID string `json:"id"`
  424. Name string `json:"name"`
  425. Label string `json:"label"`
  426. Role string `json:"role"` // "lan" | "wan"
  427. }
  428. // EthPort es una boca ethernet lista para el detalle ({id, label, up, speed?}
  429. // + contadores por puerto #305: iface física, bytes/errores acumulados y
  430. // rates instantáneos; omitempty para no engordar el contrato viejo).
  431. type EthPort struct {
  432. ID string `json:"id"`
  433. Label string `json:"label"`
  434. Up bool `json:"up"`
  435. Speed string `json:"speed,omitempty"` // solo si up
  436. // Iface física de la boca (/proc/net/dev); puede diferir del id en
  437. // plataformas swconfig ("1" vs "eth0.1").
  438. Iface string `json:"iface,omitempty"`
  439. // Contadores acumulados de la iface (issue #305).
  440. RxBytes uint64 `json:"rxBytes,omitempty"`
  441. TxBytes uint64 `json:"txBytes,omitempty"`
  442. RxErrs uint64 `json:"rxErrors,omitempty"`
  443. TxErrs uint64 `json:"txErrors,omitempty"`
  444. RxBps *float64 `json:"rxBps,omitempty"`
  445. TxBps *float64 `json:"txBps,omitempty"`
  446. // Sfp: diagnóstico digital (DDM/DOM) si la boca tiene módulo óptico
  447. // (#313). nil = sin SFP o sin datos; el servidor lo conserva.
  448. Sfp *SfpInfo `json:"sfp,omitempty"`
  449. }
  450. // SfpInfo: diagnóstico digital (DDM/DOM) de un módulo SFP (#313). Present
  451. // indica si se leyeron datos (ethtool -m devolvió algo parseable).
  452. type SfpInfo struct {
  453. Temperature float64 `json:"temperature"` // grados Celsius
  454. Voltage float64 `json:"voltage,omitempty"` // voltios (3.3 V típico)
  455. TxPower float64 `json:"txPower"` // dBm
  456. RxPower float64 `json:"rxPower"` // dBm (negativo)
  457. Vendor string `json:"vendor,omitempty"` // "FS.COM", "Ubiquiti", ...
  458. PartNumber string `json:"partNumber,omitempty"`
  459. Present bool `json:"present"`
  460. }
  461. // IfCounters son los contadores acumulados de UNA interfaz de /proc/net/dev.
  462. type IfCounters struct {
  463. Rx uint64 // bytes
  464. Tx uint64 // bytes
  465. RxErr uint64
  466. TxErr uint64
  467. }
  468. // IfRate añade a los contadores los rates instantáneos (delta entre muestras;
  469. // punteros nil = primera muestra o iface nueva, sin rate todavía).
  470. type IfRate struct {
  471. IfCounters
  472. RxBps *float64
  473. TxBps *float64
  474. }
  475. // Radio agrega una banda wifi ({name, channel, widthMhz, powerDbm, clients}).
  476. type Radio struct {
  477. Name string `json:"name"` // "5 GHz"|"2.4 GHz"
  478. Channel int `json:"channel"`
  479. WidthMhz int `json:"widthMhz"`
  480. PowerDbm float64 `json:"powerDbm"`
  481. Clients int `json:"clients"`
  482. // Section es la sección UCI de la radio ("radio0"), para que el server
  483. // pueda construir cambios de canal (uci set wireless.<section>.channel).
  484. // Vacía si no se pudo resolver (#500).
  485. Section string `json:"section,omitempty"`
  486. // #1213/#1206: suelo de ruido (dBm, de iwinfo info "Noise") y BSSID de la
  487. // interfaz AP ("Access Point"). Opcionales: drivers que no los reportan →
  488. // nil/vacío y el front no dibuja esas filas. El BSSID es "el sitio donde
  489. // viven" las MACs de interfaz que antes asomaban como clientes.
  490. NoiseDbm *int `json:"noiseDbm,omitempty"`
  491. BSSID string `json:"bssid,omitempty"`
  492. }
  493. // ---------------------------------------------------------------------------
  494. // Sistema: /proc/stat, thermal, /proc/net/dev, ping
  495. // ---------------------------------------------------------------------------
  496. // CPUSample es la muestra agregada de "cpu " de /proc/stat.
  497. type CPUSample struct{ Total, IdleAll float64 }
  498. // ParseProcStat parsea "cpu user nice system idle iowait irq softirq ...".
  499. func ParseProcStat(out string) (CPUSample, error) {
  500. fields := strings.Fields(strings.TrimSpace(out))
  501. if len(fields) < 5 || fields[0] != "cpu" {
  502. return CPUSample{}, fmt.Errorf("/proc/stat inesperado: %q", out)
  503. }
  504. nums := make([]float64, 0, len(fields)-1)
  505. for _, f := range fields[1:] {
  506. n, err := strconv.ParseFloat(f, 64)
  507. if err != nil {
  508. n = 0
  509. }
  510. nums = append(nums, n)
  511. }
  512. get := func(i int) float64 {
  513. if i < len(nums) {
  514. return nums[i]
  515. }
  516. return 0
  517. }
  518. idleAll := get(3) + get(4) // idle + iowait
  519. nonIdle := get(0) + get(1) + get(2) + get(5) + get(6) // user+nice+system+irq+softirq
  520. return CPUSample{Total: idleAll + nonIdle, IdleAll: idleAll}, nil
  521. }
  522. // ParseUptimeSec (#1481): segundos desde boot del primer campo de
  523. // /proc/uptime ("70273.29 269277.55"). 0 si la salida no es parseable: el
  524. // caller lo trata como "sin dato" y conserva el camino ubus cuando existe.
  525. func ParseUptimeSec(out string) float64 {
  526. fields := strings.Fields(strings.TrimSpace(out))
  527. if len(fields) == 0 {
  528. return 0
  529. }
  530. sec, err := strconv.ParseFloat(fields[0], 64)
  531. if err != nil || sec < 0 {
  532. return 0
  533. }
  534. return sec
  535. }
  536. // CPUPercent: % de CPU por delta de muestras (nil si no hay delta válido:
  537. // primera muestra o contadores reseteados).
  538. func CPUPercent(prev, cur CPUSample) *int {
  539. dTotal := cur.Total - prev.Total
  540. dIdle := cur.IdleAll - prev.IdleAll
  541. if dTotal <= 0 {
  542. return nil
  543. }
  544. v := int(float64(dTotal-dIdle)/float64(dTotal)*100 + 0.5)
  545. return &v
  546. }
  547. // ParseTempC: °C del primer thermal zone (nil si la salida no es un entero o
  548. // si el sensor no da una lectura creíble). Un 0 no es una temperatura de CPU:
  549. // las unidades sin sensor (WNDR3700v2, #1947) exponen la zona a 0 y pintarlo
  550. // como dato válido hace creer que la lectura funciona.
  551. func ParseTempC(out string) *int {
  552. milli, err := strconv.Atoi(strings.TrimSpace(out))
  553. if err != nil || milli == 0 {
  554. return nil
  555. }
  556. v := milli / 1000
  557. if milli%1000 >= 500 {
  558. v++
  559. }
  560. if v == 0 {
  561. return nil
  562. }
  563. return &v
  564. }
  565. var netdevSkipRe = regexp.MustCompile(`^(lo|br-|ifb|wg|tun|tap)`)
  566. // ParseNetDev suma rx/tx de las interfaces físicas (excluye lo, bridges,
  567. // ifb, wg, tun/tap para no duplicar contadores).
  568. func ParseNetDev(out string) (rx, tx float64) {
  569. lineRe := regexp.MustCompile(`^\s*([\w.-]+):\s*(.*)$`)
  570. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  571. m := lineRe.FindStringSubmatch(line)
  572. if m == nil || netdevSkipRe.MatchString(m[1]) {
  573. continue
  574. }
  575. fields := strings.Fields(strings.TrimSpace(m[2]))
  576. num := func(i int) float64 {
  577. if i < len(fields) {
  578. n, _ := strconv.ParseFloat(fields[i], 64)
  579. return n
  580. }
  581. return 0
  582. }
  583. rx += num(0)
  584. tx += num(8)
  585. }
  586. return rx, tx
  587. }
  588. // ParseNetDevIfaces devuelve los contadores POR INTERFAZ de /proc/net/dev
  589. // (sin filtrar: el consumidor decide qué ifaces le interesan; las bocas
  590. // físicas se casan por nombre con el layout, issue #305).
  591. func ParseNetDevIfaces(out string) map[string]IfCounters {
  592. res := map[string]IfCounters{}
  593. lineRe := regexp.MustCompile(`^\s*([\w.-]+):\s*(.*)$`)
  594. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  595. m := lineRe.FindStringSubmatch(line)
  596. if m == nil {
  597. continue
  598. }
  599. fields := strings.Fields(strings.TrimSpace(m[2]))
  600. num := func(i int) uint64 {
  601. if i < len(fields) {
  602. n, _ := strconv.ParseUint(fields[i], 10, 64)
  603. return n
  604. }
  605. return 0
  606. }
  607. res[m[1]] = IfCounters{
  608. Rx: num(0), Tx: num(8), // bytes
  609. RxErr: num(2), TxErr: num(10),
  610. }
  611. }
  612. return res
  613. }
  614. // IfRates calcula los rates por interfaz con el delta de contadores entre
  615. // dos muestras separadas dt segundos. Ifaces nuevas o dt <= 0 → nil rates.
  616. // Contadores reseteados (reboot) → max0 dentro de NetDevBps da 0, no negativos.
  617. func IfRates(prev, cur map[string]IfCounters, dt float64) map[string]IfRate {
  618. res := make(map[string]IfRate, len(cur))
  619. for name, c := range cur {
  620. r := IfRate{IfCounters: c}
  621. if p, ok := prev[name]; ok && dt > 0 {
  622. r.RxBps, r.TxBps = NetDevBps(float64(p.Rx), float64(p.Tx), float64(c.Rx), float64(c.Tx), dt)
  623. }
  624. res[name] = r
  625. }
  626. return res
  627. }
  628. // NetDevBps: bps por delta de contadores en dt segundos (nil si dt <= 0 o
  629. // contadores reseteados).
  630. func NetDevBps(prevRx, prevTx, rx, tx, dt float64) (rxBps, txBps *float64) {
  631. if dt <= 0 {
  632. return nil, nil
  633. }
  634. rb := round0(max0((rx - prevRx) * 8 / dt))
  635. tb := round0(max0((tx - prevTx) * 8 / dt))
  636. return &rb, &tb
  637. }
  638. var pingLossRe = regexp.MustCompile(`(\d+(?:\.\d+)?)% packet loss`)
  639. // #1281: GNU iputils imprime min/avg/max/MDEV (4 numeros) pero busybox
  640. // (OpenWrt) imprime min/avg/max (3): la regex exigia los 4 y en OpenWrt
  641. // la latencia salia nil siempre ("—" en Overview y Flota). El avg es el
  642. // segundo numero en ambos formatos.
  643. var pingRTTRe = regexp.MustCompile(`= [\d.]+/([\d.]+)(?:/[\d.]+){1,2} ms`)
  644. // ParsePingSummary extrae (latencia avg redondeada, pérdida %) del resumen de
  645. // ping; cada una es nil si su línea no está.
  646. func ParsePingSummary(out string) (latency, loss *float64) {
  647. if m := pingRTTRe.FindStringSubmatch(out); m != nil {
  648. v, _ := strconv.ParseFloat(m[1], 64)
  649. // #1384: sin redondeo a entero - en LAN el ping es <1 ms y el
  650. // redondeo lo dejaba en 0 (ruido). El formateo es cosa de la UI.
  651. latency = &v
  652. }
  653. if m := pingLossRe.FindStringSubmatch(out); m != nil {
  654. v, _ := strconv.ParseFloat(m[1], 64)
  655. loss = &v
  656. }
  657. return latency, loss
  658. }
  659. // ---------------------------------------------------------------------------
  660. // Clientes (DHCP + wireless)
  661. // ---------------------------------------------------------------------------
  662. // ParseDhcpUbus parsea la respuesta de `ubus call dhcp ipv4leases`
  663. // ({lease: [...]} o {leases: [...]}). Error si no es JSON con esas claves.
  664. func ParseDhcpUbus(raw []byte) ([]DhcpLease, error) {
  665. type leaseJSON struct {
  666. MAC string `json:"mac"`
  667. IPAddr string `json:"ip-address"`
  668. IP string `json:"ip"`
  669. Hostname string `json:"hostname"`
  670. VendorID string `json:"vendorid"`
  671. ClientID string `json:"clientid"`
  672. Expires int64 `json:"expires"` // segundos restantes o absoluto según firmware
  673. }
  674. var data struct {
  675. Lease []leaseJSON `json:"lease"`
  676. Leases []leaseJSON `json:"leases"`
  677. }
  678. if err := json.Unmarshal(raw, &data); err != nil {
  679. return nil, err
  680. }
  681. leases := data.Lease
  682. if leases == nil {
  683. leases = data.Leases
  684. }
  685. if leases == nil {
  686. return nil, fmt.Errorf("ubus dhcp: no lease/leases key")
  687. }
  688. out := make([]DhcpLease, 0, len(leases))
  689. for _, l := range leases {
  690. ip := l.IPAddr
  691. if ip == "" {
  692. ip = l.IP
  693. }
  694. lease := DhcpLease{MAC: strings.ToUpper(l.MAC), IP: ip, Hostname: l.Hostname, VendorClass: l.VendorID, ClientID: l.ClientID}
  695. if l.Expires > 0 {
  696. lease.LeaseExpiresAt = &l.Expires
  697. }
  698. out = append(out, lease)
  699. }
  700. return out, nil
  701. }
  702. // ifaceStatus es una interfaz de `ubus call network.interface[.<x>] status`,
  703. // y cada entrada de `... dump`.
  704. type ifaceStatus struct {
  705. Interface string `json:"interface"`
  706. Up bool `json:"up"`
  707. Proto string `json:"proto"`
  708. L3Device string `json:"l3_device"`
  709. // Device es la interfaz de debajo: para un PPPoE, la boca física.
  710. Device string `json:"device"`
  711. // Dynamic marks an interface netifd created itself — the DHCP child of
  712. // a modem uplink, the DHCPv6 side of a PPPoE one. It holds the address
  713. // and the route its parent has none of, and cannot be configured or
  714. // named in a policy, so it is only ever read through its parent.
  715. Dynamic bool `json:"dynamic"`
  716. IPV4 []ubusIPv4 `json:"ipv4-address"`
  717. // IPV6 es `ipv6-address` del dump: netifd lista ahí todas las
  718. // direcciones del lado v6 (la global del ISP, la ULA del router y la
  719. // link-local), así que elegir una no es quedarse con la primera.
  720. IPV6 []ubusIPv6 `json:"ipv6-address"`
  721. Route []struct {
  722. Target string `json:"target"`
  723. Mask int `json:"mask"`
  724. Nexthop string `json:"nexthop"`
  725. } `json:"route"`
  726. DNS []string `json:"dns-server"`
  727. }
  728. // ubusIPv4 es una entrada de `ipv4-address`.
  729. type ubusIPv4 struct {
  730. Address string `json:"address"`
  731. PtpAddress string `json:"ptpaddress"`
  732. }
  733. // ubusIPv6 es una entrada de `ipv6-address`. Preferred llega crudo porque
  734. // netifd lo escribe de varias formas: segundos de vida, `true` cuando no
  735. // caduca, o ausente. Decodificarlo a int64 abortaría el parseo entero del
  736. // dump con un solo `true`, y con él el estado WAN completo.
  737. type ubusIPv6 struct {
  738. Address string `json:"address"`
  739. Preferred json.RawMessage `json:"preferred"`
  740. }
  741. func (s ifaceStatus) defaultNexthop() string {
  742. for _, r := range s.Route {
  743. if r.Target == "0.0.0.0" && r.Mask == 0 && r.Nexthop != "" {
  744. return r.Nexthop
  745. }
  746. }
  747. return ""
  748. }
  749. // pickUplink elige la interfaz que lleva internet. No vale fiarse del nombre
  750. // "wan": en un router multi-WAN el uplink vivo puede llamarse de cualquier
  751. // forma (un PPPoE llamado "isp" junto a un módem celular que sí se llama
  752. // "wan" y que además reporta up=true estando ocioso), así que manda la ruta
  753. // por defecto. Sin ninguna con ruta, cae a la llamada "wan" para que un
  754. // router normal con el enlace caído siga saliendo como WAN caída y no como
  755. // router sin WAN.
  756. func pickUplink(ifaces []ifaceStatus) (ifaceStatus, bool) {
  757. return pickUplinkPreferring(ifaces, "")
  758. }
  759. // pickUplinkPreferring is pickUplink with the answer supplied from outside.
  760. //
  761. // A policy manager (mwan3) steers with packet marks and leaves the routes
  762. // alone, so the default route still points at the standby link while every
  763. // packet leaves by another one. When something knows which uplink is really
  764. // carrying traffic, that wins; everything else falls through to the route.
  765. func pickUplinkPreferring(ifaces []ifaceStatus, preferred string) (ifaceStatus, bool) {
  766. if preferred != "" {
  767. for _, i := range ifaces {
  768. if i.Interface != preferred {
  769. continue
  770. }
  771. i = withChildFacts(i, ifaces)
  772. if len(i.IPV4) > 0 || i.defaultNexthop() != "" {
  773. return i, true
  774. }
  775. }
  776. }
  777. for _, i := range ifaces {
  778. if i.Up && i.defaultNexthop() != "" {
  779. return i, true
  780. }
  781. }
  782. for _, i := range ifaces {
  783. if i.Interface == "wan" {
  784. return i, true
  785. }
  786. }
  787. return ifaceStatus{}, false
  788. }
  789. // withChildFacts gives an interface whatever netifd spawned underneath it.
  790. // A modem uplink keeps neither address nor route of its own: the child
  791. // sharing its layer-3 device holds both, and reporting the parent without
  792. // them would describe a connection with nothing on it.
  793. func withChildFacts(parent ifaceStatus, ifaces []ifaceStatus) ifaceStatus {
  794. if parent.Dynamic || parent.L3Device == "" {
  795. return parent
  796. }
  797. for _, c := range ifaces {
  798. if !c.Dynamic || c.Interface == parent.Interface || c.L3Device != parent.L3Device {
  799. continue
  800. }
  801. if len(parent.IPV4) == 0 {
  802. parent.IPV4 = c.IPV4
  803. }
  804. if len(parent.IPV6) == 0 {
  805. parent.IPV6 = c.IPV6
  806. }
  807. if len(parent.Route) == 0 {
  808. parent.Route = c.Route
  809. }
  810. if len(parent.DNS) == 0 {
  811. parent.DNS = c.DNS
  812. }
  813. }
  814. return parent
  815. }
  816. func wanInfoFrom(s ifaceStatus) WanInfo {
  817. info := WanInfo{Proto: s.Proto, Device: s.L3Device, Port: s.Device, DNS: s.DNS}
  818. if len(s.IPV4) > 0 {
  819. info.IP = s.IPV4[0].Address
  820. if s.IPV4[0].PtpAddress != "" {
  821. info.Gateway = s.IPV4[0].PtpAddress
  822. }
  823. }
  824. // #2275: la dirección global del lado v6, si el uplink tiene una. El
  825. // campo es opcional en el payload y vacío en un router sin v6.
  826. info.IPv6 = globalIPv6(s.IPV6)
  827. // El gateway real es el nexthop de la ruta por defecto (0.0.0.0/0).
  828. if nh := s.defaultNexthop(); nh != "" {
  829. info.Gateway = nh
  830. }
  831. return info
  832. }
  833. // globalIPv6 elige la dirección que se publica como IPv6 del uplink: la
  834. // primera global, saltando link-local (fe80::/10), ULA (fc00::/7) y loopback.
  835. // Una dirección deprecada (`preferred` a cero) solo se usa cuando no queda
  836. // ninguna otra, de modo que un router en medio de un cambio de prefijo sigue
  837. // reportando algo en vez de nada.
  838. func globalIPv6(addrs []ubusIPv6) string {
  839. fallback := ""
  840. for _, a := range addrs {
  841. raw := strings.TrimSpace(a.Address)
  842. if i := strings.IndexByte(raw, '/'); i >= 0 {
  843. raw = raw[:i]
  844. }
  845. addr, err := netip.ParseAddr(raw)
  846. if err != nil || !addr.Is6() || addr.IsLinkLocalUnicast() || addr.IsPrivate() || addr.IsLoopback() || addr.IsUnspecified() {
  847. continue
  848. }
  849. if deprecatedIPv6(a.Preferred) {
  850. if fallback == "" {
  851. fallback = addr.String()
  852. }
  853. continue
  854. }
  855. return addr.String()
  856. }
  857. return fallback
  858. }
  859. // deprecatedIPv6 dice si la vida preferida del dump marca la dirección como
  860. // deprecada: cero segundos o `false`. Ausente, `null` o `true` significan
  861. // "sin caducidad conocida", que no es lo mismo que deprecada.
  862. func deprecatedIPv6(raw json.RawMessage) bool {
  863. switch strings.TrimSpace(string(raw)) {
  864. case "", "null":
  865. return false
  866. case "false":
  867. return true
  868. }
  869. var seconds int64
  870. if err := json.Unmarshal(raw, &seconds); err == nil {
  871. return seconds == 0
  872. }
  873. return false
  874. }
  875. // ParseWanStatus parsea el estado de la WAN (issue #276). Acepta las dos
  876. // formas: `ubus call network.interface dump` (y entonces elige el uplink
  877. // activo, ver pickUplink) y el status de una sola interfaz. Extrae proto,
  878. // interfaz L3, boca física, IP pública, gateway y DNS; campos vacíos si el
  879. // JSON no trae datos utilizables.
  880. func ParseWanStatus(raw []byte) WanInfo {
  881. return ParseWanStatusPreferring(raw, "")
  882. }
  883. // ParseWanStatusPreferring is ParseWanStatus told which uplink is carrying
  884. // traffic (see pickUplinkPreferring). An empty name behaves exactly as
  885. // before.
  886. func ParseWanStatusPreferring(raw []byte, preferred string) WanInfo {
  887. var dump struct {
  888. Interface []ifaceStatus `json:"interface"`
  889. }
  890. if err := json.Unmarshal(raw, &dump); err == nil && len(dump.Interface) > 0 {
  891. s, ok := pickUplinkPreferring(dump.Interface, preferred)
  892. if !ok {
  893. return WanInfo{}
  894. }
  895. return wanInfoFrom(s)
  896. }
  897. var one ifaceStatus
  898. if json.Unmarshal(raw, &one) != nil {
  899. return WanInfo{}
  900. }
  901. return wanInfoFrom(one)
  902. }
  903. // ParseDhcpReservations parses the host sections of `uci show dhcp`. A host
  904. // entry can carry several MACs (GL firmware stores mac as a list) and they
  905. // all share the entry's name and address. Sorted by MAC so the payload does
  906. // not churn between pushes.
  907. func ParseDhcpReservations(out string) []DhcpReservation {
  908. type entry struct {
  909. name, ip string
  910. macs []string
  911. }
  912. entries := map[string]*entry{}
  913. order := []string{}
  914. get := func(section string) *entry {
  915. e, ok := entries[section]
  916. if !ok {
  917. e = &entry{}
  918. entries[section] = e
  919. order = append(order, section)
  920. }
  921. return e
  922. }
  923. for _, line := range strings.Split(out, "\n") {
  924. line = strings.TrimSpace(line)
  925. key, val, ok := strings.Cut(line, "=")
  926. if !ok || !strings.HasPrefix(key, "dhcp.") {
  927. continue
  928. }
  929. key = strings.TrimPrefix(key, "dhcp.")
  930. val = strings.Trim(val, "'")
  931. section, attr, isAttr := strings.Cut(key, ".")
  932. if !isAttr {
  933. if val == "host" {
  934. get(section)
  935. }
  936. continue
  937. }
  938. e, declared := entries[section]
  939. if !declared {
  940. continue // an option of a section that is not a host entry
  941. }
  942. switch attr {
  943. case "name":
  944. e.name = val
  945. case "ip":
  946. e.ip = val
  947. case "mac":
  948. // A list comes back as 'aa:..' 'bb:..'; a single value plain.
  949. for _, mac := range strings.Fields(strings.ReplaceAll(val, "'", " ")) {
  950. e.macs = append(e.macs, strings.ToUpper(mac))
  951. }
  952. }
  953. }
  954. res := []DhcpReservation{}
  955. for _, section := range order {
  956. e := entries[section]
  957. for _, mac := range e.macs {
  958. res = append(res, DhcpReservation{MAC: mac, Name: e.name, IP: e.ip})
  959. }
  960. }
  961. sort.Slice(res, func(i, j int) bool { return res[i].MAC < res[j].MAC })
  962. return res
  963. }
  964. // ParseDhcpLeasesFile parsea /tmp/dhcp.leases:
  965. // <expiry> <mac> <ip> <hostname> <clientid>
  966. func ParseDhcpLeasesFile(out string) []DhcpLease {
  967. leases := []DhcpLease{}
  968. now := time.Now().Unix()
  969. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  970. if line == "" {
  971. continue
  972. }
  973. p := strings.Fields(line)
  974. if len(p) < 3 {
  975. continue
  976. }
  977. hostname := ""
  978. if len(p) > 3 && p[3] != "*" {
  979. hostname = p[3]
  980. }
  981. clientID := ""
  982. if len(p) > 4 && p[4] != "*" {
  983. clientID = p[4]
  984. }
  985. var exp *int64
  986. if secs, err := strconv.ParseInt(p[0], 10, 64); err == nil && secs > now {
  987. exp = &secs
  988. }
  989. leases = append(leases, DhcpLease{MAC: strings.ToUpper(p[1]), IP: p[2], Hostname: hostname, ClientID: clientID, LeaseExpiresAt: exp})
  990. }
  991. return leases
  992. }
  993. // ParseGlClients parsea la respuesta de `ubus call gl-clients list`
  994. // (GL.iNet Flint2 y similares): {"clients": {"MAC": {mac, ip, name, online, ...}}}.
  995. // Error si no es JSON con esa forma. Solo devuelve entradas ONLINE con IP:
  996. // la base del firmware acumula historial (cientos de entradas) y las offline
  997. // solo servirían para inflar la lista de dispositivos; los equipos que
  998. // necesitan resolución de IP son los que están en la red ahora (issue #5
  999. // bug 1).
  1000. func ParseGlClients(raw []byte) ([]DhcpLease, error) {
  1001. type clientJSON struct {
  1002. MAC string `json:"mac"`
  1003. IP string `json:"ip"`
  1004. Name string `json:"name"`
  1005. Hostname string `json:"hostname"`
  1006. Online bool `json:"online"`
  1007. }
  1008. var data struct {
  1009. Clients map[string]clientJSON `json:"clients"`
  1010. }
  1011. if err := json.Unmarshal(raw, &data); err != nil {
  1012. return nil, err
  1013. }
  1014. if data.Clients == nil {
  1015. return nil, fmt.Errorf("gl-clients: no clients key")
  1016. }
  1017. out := make([]DhcpLease, 0, len(data.Clients))
  1018. for key, c := range data.Clients {
  1019. // El firmware puede emitir MAC con guiones ("AA-BB-...", #1145): se
  1020. // guarda siempre la forma canónica para que el servidor la encuentre.
  1021. mac := macaddr.Normalize(c.MAC)
  1022. if mac == "" {
  1023. mac = macaddr.Normalize(key)
  1024. }
  1025. if mac == "" || c.IP == "" || !c.Online {
  1026. continue
  1027. }
  1028. hostname := c.Hostname
  1029. if hostname == "" {
  1030. hostname = c.Name
  1031. }
  1032. out = append(out, DhcpLease{MAC: mac, IP: c.IP, Hostname: hostname})
  1033. }
  1034. sort.Slice(out, func(i, j int) bool { return out[i].MAC < out[j].MAC })
  1035. return out, nil
  1036. }
  1037. // ParseWirelessClients parsea líneas "<mac> <sig> <freq>" del bucle iwinfo.
  1038. func ParseWirelessClients(out string) map[string]WirelessClient {
  1039. m := map[string]WirelessClient{}
  1040. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  1041. if line == "" {
  1042. continue
  1043. }
  1044. p := strings.Fields(line)
  1045. if len(p) < 2 {
  1046. continue
  1047. }
  1048. freq := 0.0
  1049. if len(p) > 2 {
  1050. freq, _ = strconv.ParseFloat(p[2], 64)
  1051. }
  1052. sig, _ := strconv.Atoi(p[1])
  1053. band := "2.4 GHz"
  1054. if freq >= 5 {
  1055. band = "5 GHz"
  1056. }
  1057. m[strings.ToUpper(p[0])] = WirelessClient{SignalDbm: sig, Band: band}
  1058. }
  1059. return m
  1060. }
  1061. // ParseWirelessUplink: alguna interfaz con config.mode "sta" activa (radio
  1062. // up e ifname asignado = asociada) → uplink inalámbrico. Tolerante con
  1063. // radios/entradas raras; error si la respuesta no es JSON.
  1064. func ParseWirelessUplink(raw []byte) (bool, error) {
  1065. var radios map[string]struct {
  1066. Up bool `json:"up"`
  1067. Interfaces []struct {
  1068. Ifname string `json:"ifname"`
  1069. Config struct {
  1070. Mode string `json:"mode"`
  1071. } `json:"config"`
  1072. } `json:"interfaces"`
  1073. }
  1074. if err := json.Unmarshal(raw, &radios); err != nil {
  1075. return false, err
  1076. }
  1077. for _, r := range radios {
  1078. if !r.Up {
  1079. continue
  1080. }
  1081. for _, itf := range r.Interfaces {
  1082. if itf.Config.Mode == "sta" && itf.Ifname != "" {
  1083. return true, nil
  1084. }
  1085. }
  1086. }
  1087. return false, nil
  1088. }
  1089. // ---------------------------------------------------------------------------
  1090. // Puertos
  1091. // ---------------------------------------------------------------------------
  1092. // ParsePortStates parsea líneas "<name> <operstate> <speed> [dsa] [type]
  1093. // [conduit]". Los campos opcionales que falten dejan su valor por defecto:
  1094. // sin type no se descarta ninguna boca por él.
  1095. func ParsePortStates(out string) []PortState {
  1096. ports := []PortState{}
  1097. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  1098. if line == "" {
  1099. continue
  1100. }
  1101. p := strings.Fields(line)
  1102. if len(p) < 3 {
  1103. continue
  1104. }
  1105. mbps, _ := strconv.Atoi(p[2])
  1106. speed := "—"
  1107. if mbps > 0 {
  1108. speed = fmtSpeedMbps(mbps)
  1109. }
  1110. st := PortState{Name: p[0], Up: p[1] == "up", Oper: p[1], Speed: speed}
  1111. if len(p) > 3 && p[3] == "dsa" {
  1112. st.DSA = true
  1113. }
  1114. if len(p) > 4 {
  1115. st.Type, _ = strconv.Atoi(p[4])
  1116. }
  1117. if len(p) > 5 && p[5] != "-" {
  1118. st.Conduit = p[5]
  1119. }
  1120. ports = append(ports, st)
  1121. }
  1122. return ports
  1123. }
  1124. // ParsePortLayout parsea board.json → [{id, name, label, role}] (WAN
  1125. // normalizado a id 'wan').
  1126. // portPrettyLabel (#1200): etiqueta humana para el panel de bocas. Los
  1127. // patrones clásicos conservan su formato (lan1→"LAN 1", wan→"WAN",
  1128. // eth0→"ETH 0", sfp0→"SFP 0"); cualquier otro nombre físico reconocido
  1129. // muestra su nombre real intacto: los netdev de OpenWrt 25.12+ (sfp-lan,
  1130. // sfp-wan en BPI-R4) y las bocas sin dígitos (lan en UniFi 6 Lite). Ni
  1131. // mayúsculas inyectadas en medio del nombre ni sufijos partidos.
  1132. func portPrettyLabel(name string) string {
  1133. switch {
  1134. case name == "lan":
  1135. return "LAN"
  1136. case name == "wan":
  1137. return "WAN"
  1138. case lanNumRe.MatchString(name):
  1139. return "LAN " + strings.TrimPrefix(name, "lan")
  1140. case ethNumRe.MatchString(name):
  1141. return "ETH " + strings.TrimPrefix(name, "eth")
  1142. case sfpNumRe.MatchString(name):
  1143. if name == "sfp" {
  1144. return "SFP"
  1145. }
  1146. return "SFP " + strings.TrimPrefix(name, "sfp")
  1147. default:
  1148. return name
  1149. }
  1150. }
  1151. var (
  1152. lanNumRe = regexp.MustCompile(`^lan\d+$`)
  1153. ethNumRe = regexp.MustCompile(`^eth\d+$`)
  1154. sfpNumRe = regexp.MustCompile(`^sfp\d*$`)
  1155. )
  1156. func ParsePortLayout(out string) ([]PortLayout, error) {
  1157. var board struct {
  1158. Network struct {
  1159. Lan struct {
  1160. Ports []string `json:"ports"`
  1161. } `json:"lan"`
  1162. Wan struct {
  1163. Device string `json:"device"`
  1164. } `json:"wan"`
  1165. } `json:"network"`
  1166. }
  1167. if err := json.Unmarshal([]byte(out), &board); err != nil {
  1168. return nil, err
  1169. }
  1170. ports := []PortLayout{}
  1171. for _, name := range board.Network.Lan.Ports {
  1172. ports = append(ports, PortLayout{ID: name, Name: name, Label: portPrettyLabel(name), Role: "lan"})
  1173. }
  1174. if wanDev := board.Network.Wan.Device; wanDev != "" {
  1175. ports = append([]PortLayout{{ID: "wan", Name: wanDev, Label: "WAN", Role: "wan"}}, ports...)
  1176. }
  1177. return ports, nil
  1178. }
  1179. // phyRe/skipRe: nombres que pueden ser una boca física y nombres que nunca lo
  1180. // son (bridges, VLANs, túneles, wireless, módems).
  1181. var (
  1182. phyRe = regexp.MustCompile(`^(eth|sfp|en|swp)[0-9a-zA-Z_\-]*$|^(lan|wan)[0-9]*$`)
  1183. skipRe = regexp.MustCompile(`^(lo|br[-_]?|br-lan|br0|docker|veth|wg|tun|tap|ifb|pppoe|wlan|wpan|phy|gre|gretap|erspan|ip6tnl|sit|teql|bond|dummy|nat64|rmnet|usb|wwan)`)
  1184. )
  1185. // switchConduits: puertos de CPU de un switch, deducidos de las propias
  1186. // bocas. En DSA cada boca cuelga de la interfaz de CPU (lan1 y lan2 tienen
  1187. // lower_eth0), que no es una boca física por mucho que se llame eth0.
  1188. //
  1189. // Solo se mira el lower_* de interfaces que parecen bocas: el de un bridge
  1190. // son sus miembros (br-lan → lower_lan2) y el de una VLAN su interfaz padre,
  1191. // relaciones que no señalan ningún puerto de CPU.
  1192. func switchConduits(states []PortState) map[string]bool {
  1193. conduits := map[string]bool{}
  1194. for _, st := range states {
  1195. if st.Conduit == "" || skipRe.MatchString(st.Name) || !phyRe.MatchString(st.Name) {
  1196. continue
  1197. }
  1198. conduits[st.Conduit] = true
  1199. }
  1200. return conduits
  1201. }
  1202. // isEthNetdev: el layout nombra una interfaz de red ethernet de verdad.
  1203. // board.json declara como WAN lo que el router use de uplink, y no siempre es
  1204. // una boca: en un router celular es "/dev/cdc-wdm0",
  1205. // que ni siquiera aparece en /sys/class/net. Un tipo desconocido (salida
  1206. // antigua, sin el campo) cuenta como ethernet: mejor enseñar una boca de más
  1207. // que esconder una real.
  1208. func isEthNetdev(st PortState, ok bool) bool {
  1209. return ok && (st.Type <= 0 || st.Type == ARPHRDEther)
  1210. }
  1211. // BuildEthPorts: layout + estado /sys → []EthPort listo para el detalle.
  1212. // brMembers = miembros del bridge br-lan (AP en bridge re-etiqueta wan→LAN
  1213. // N+1); sin layout, fallback heurístico. ifaces = contadores/rates por iface
  1214. // física (issue #305; nil = sin datos, las bocas salen sin stats). Literal de
  1215. // openwrt.go GetEthPorts.
  1216. //
  1217. // Descarta dos bocas que no existen: el uplink del layout cuando no es una
  1218. // interfaz ethernet (módem celular) y el puerto de CPU del switch. Sin ellos
  1219. // un router así pasa de enseñar cuatro bocas -- WAN (nunca conectada), LAN 1,
  1220. // LAN 2 y ETH 0 -- a las dos que tiene.
  1221. //
  1222. // uplink es la boca por la que sale internet (WanInfo.Port); cuando ninguna
  1223. // boca ha salido como WAN se promueve esa, ver promoteUplink. "" = sin dato,
  1224. // y entonces no se promueve nada.
  1225. func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string]bool, ifaces map[string]IfRate, uplink string) []EthPort {
  1226. applyStats := func(ep *EthPort, iface string) {
  1227. st, ok := ifaces[iface]
  1228. if !ok {
  1229. return
  1230. }
  1231. ep.Iface = iface
  1232. ep.RxBytes, ep.TxBytes = st.Rx, st.Tx
  1233. ep.RxErrs, ep.TxErrs = st.RxErr, st.TxErr
  1234. ep.RxBps, ep.TxBps = st.RxBps, st.TxBps
  1235. }
  1236. byName := map[string]PortState{}
  1237. for _, p := range states {
  1238. byName[p.Name] = p
  1239. }
  1240. conduits := switchConduits(states)
  1241. used := map[string]bool{}
  1242. ports := make([]EthPort, 0, len(states))
  1243. // netdev de cada boca por id, para saber luego cuál lleva el uplink: el
  1244. // id no siempre es el nombre de la interfaz (en swconfig, "1" vs
  1245. // "eth0.1").
  1246. netdev := map[string]string{}
  1247. wanDeclared := false
  1248. if len(layout) > 0 {
  1249. lanCount := 0
  1250. lanNames := map[string]bool{}
  1251. for _, p := range layout {
  1252. if p.Role == "lan" {
  1253. lanCount++
  1254. lanNames[p.Name] = true
  1255. }
  1256. if p.Role == "wan" {
  1257. wanDeclared = true
  1258. }
  1259. }
  1260. bridgedWan := -1
  1261. for _, p := range layout {
  1262. st, ok := byName[p.Name]
  1263. if p.Role == "wan" && !isEthNetdev(st, ok) {
  1264. continue
  1265. }
  1266. up := ok && st.Up
  1267. label := p.Label
  1268. id := p.ID
  1269. if p.Role == "wan" && brMembers[p.Name] {
  1270. // #1949: la "wan" del board.json de un AP de un solo puerto
  1271. // es un miembro del bridge LAN, no una boca WAN. La boca se
  1272. // queda como LAN y con su propio id: con id "wan" la UI la
  1273. // pintaba como enlace a internet aunque el texto dijera LAN.
  1274. if lanNames[p.Name] {
  1275. continue // ya declarada como LAN: no duplicar la boca
  1276. }
  1277. id = p.Name
  1278. label = "LAN " + strconv.Itoa(lanCount+1)
  1279. if id == "wan" {
  1280. // #2181: un netdev llamado literalmente "wan" (FRITZ!Box
  1281. // 4040 y otros) conservaba el id, y la UI pinta como WAN
  1282. // todo puerto con id "wan" (jack, leyenda "Internet
  1283. // link") además de descartarlo del FDB como si fuera la
  1284. // WAN. Una boca puenteada no puede llevar ese id: usa el
  1285. // mismo que su etiqueta, sin pisar una boca LAN existente.
  1286. n := lanCount + 1
  1287. for lanNames["lan"+strconv.Itoa(n)] {
  1288. n++
  1289. }
  1290. id = "lan" + strconv.Itoa(n)
  1291. label = "LAN " + strconv.Itoa(n)
  1292. }
  1293. bridgedWan = len(ports)
  1294. }
  1295. ep := EthPort{ID: id, Label: label, Up: up}
  1296. if up {
  1297. ep.Speed = st.Speed
  1298. }
  1299. applyStats(&ep, p.Name)
  1300. ports = append(ports, ep)
  1301. netdev[ep.ID] = p.Name
  1302. used[p.Name] = true
  1303. }
  1304. // #2181: la ex-WAN puenteada ya no es la primera boca del chasis. El
  1305. // layout la trae delante porque la WAN suele ir a la izquierda, así
  1306. // que se mueve al final para que el panel lea LAN 1..LAN N, LAN N+1.
  1307. if bridgedWan >= 0 && bridgedWan != len(ports)-1 {
  1308. ep := ports[bridgedWan]
  1309. ports = append(append(ports[:bridgedWan:bridgedWan], ports[bridgedWan+1:]...), ep)
  1310. }
  1311. } else {
  1312. // Fallback sin config. #1200: también "lan"/"wan" a secas (UniFi
  1313. // 6 Lite: la boca no se llama lan1 sino lan, y antes el panel
  1314. // salía vacío - 0 de 0 - porque ningún patrón la reconocía).
  1315. lanRe := regexp.MustCompile(`^lan\d*$`)
  1316. lans := []PortState{}
  1317. for _, p := range states {
  1318. if lanRe.MatchString(p.Name) {
  1319. lans = append(lans, p)
  1320. }
  1321. }
  1322. sort.Slice(lans, func(i, j int) bool { return NaturalLess(lans[i].Name, lans[j].Name) })
  1323. for _, p := range lans {
  1324. ep := EthPort{ID: p.Name, Label: portPrettyLabel(p.Name), Up: p.Up}
  1325. if p.Up {
  1326. ep.Speed = p.Speed
  1327. }
  1328. applyStats(&ep, p.Name)
  1329. ports = append(ports, ep)
  1330. netdev[ep.ID] = p.Name
  1331. used[p.Name] = true
  1332. }
  1333. wanName := ""
  1334. if uplink != "" {
  1335. // #1500: con uplink runtime la WAN es esa boca, no la heurística
  1336. // ciega de abajo (un AP bridge sin layout marcaba WAN en eth1
  1337. // teniendo el uplink en eth0). El uplink puede llegar etiquetado
  1338. // ("br0.1"): la boca es la de debajo.
  1339. base := uplink
  1340. if i := strings.LastIndexByte(base, '.'); i > 0 {
  1341. base = base[:i]
  1342. }
  1343. if st, ok := byName[base]; ok && phyRe.MatchString(base) && isEthNetdev(st, ok) && !conduits[base] {
  1344. wanName = base
  1345. } else if len(brMembers) > 0 {
  1346. // Uplink sobre bridge (APs: la ruta default vive en br0): la
  1347. // boca WAN es el miembro con vecino LLDP (la que mira al
  1348. // core) o, en su defecto, el de más rx bytes. Iteración
  1349. // ordenada: empates no deben bailar entre sondeos (#1500).
  1350. names := make([]string, 0, len(brMembers))
  1351. for m := range brMembers {
  1352. names = append(names, m)
  1353. }
  1354. sort.Strings(names)
  1355. bestRx := uint64(0)
  1356. for _, m := range names {
  1357. st, ok := byName[m]
  1358. if !ok || !st.Up || !phyRe.MatchString(m) || !isEthNetdev(st, ok) || conduits[m] {
  1359. continue
  1360. }
  1361. if wanName == "" || ifaces[m].Rx > bestRx {
  1362. wanName, bestRx = m, ifaces[m].Rx
  1363. }
  1364. }
  1365. }
  1366. }
  1367. if wanName == "" {
  1368. if _, ok := byName["wan"]; ok {
  1369. wanName = "wan"
  1370. } else if _, ok := byName["pppoe-wan"]; ok {
  1371. wanName = "eth1"
  1372. } else if st, ok := byName["eth1"]; ok && !st.DSA {
  1373. // #847: un conduit DSA no es la WAN física aunque se llame eth1.
  1374. wanName = "eth1"
  1375. }
  1376. }
  1377. // #1949: un AP con una sola boca fisica no tiene puerto WAN que
  1378. // ensenar. Su uplink es la propia LAN (eth0 dentro de br-lan), asi que
  1379. // etiquetarlo WAN lo pinta como enlace a internet y le cuelga los
  1380. // datos de la conexion (WAX220). Con dos o mas bocas el miembro del
  1381. // bridge que mira al core si distingue y se conserva (#1500: GT-BE98
  1382. // Pro, eth0 con vecino LLDP frente a eth1 y eth3).
  1383. if wanName != "" && brMembers[wanName] && physicalPortCount(states, conduits) < 2 {
  1384. wanName = ""
  1385. }
  1386. if wanName != "" {
  1387. st := byName[wanName]
  1388. ep := EthPort{ID: "wan", Label: "WAN", Up: st.Up}
  1389. if st.Up {
  1390. ep.Speed = st.Speed
  1391. }
  1392. applyStats(&ep, wanName)
  1393. ports = append([]EthPort{ep}, ports...)
  1394. netdev[ep.ID] = wanName
  1395. used[wanName] = true
  1396. }
  1397. }
  1398. // Mejora #413/#416: añadir interfaces físicas que no estén ya cubiertas
  1399. // por el layout/fallback (p. ej. eth0, sfp+ en BPI-R4/UniFi).
  1400. extras := make([]EthPort, 0)
  1401. for _, st := range states {
  1402. if used[st.Name] {
  1403. continue
  1404. }
  1405. // #847: el conduit DSA (puerto CPU interno del switch, /sys .../dsa)
  1406. // no es una boca usable: su velocidad es interna y sin sentido para
  1407. // el usuario (p. ej. 150 Mbps en BPI-R4). Se excluye del panel.
  1408. if st.DSA {
  1409. continue
  1410. }
  1411. if skipRe.MatchString(st.Name) {
  1412. continue
  1413. }
  1414. if !phyRe.MatchString(st.Name) {
  1415. continue
  1416. }
  1417. if conduits[st.Name] {
  1418. continue // puerto de CPU del switch, no una boca
  1419. }
  1420. // Broadcom/Asuswrt internal "ghost" interfaces (eth5/6/7 on an RT-AX92U)
  1421. // pass phyRe and carry no DSA/conduit marker, but their sysfs operstate
  1422. // is dormant/unknown and speed is unreadable: they are not front-panel
  1423. // ports and never carry user traffic. A real port is either "up" (kept
  1424. // here and everywhere) or "down" when unplugged. Oper=="" is legacy
  1425. // three-field output, so nothing is hidden for it.
  1426. if !st.Up && st.Oper != "" && st.Oper != "down" {
  1427. continue
  1428. }
  1429. // #1200: label centralizado en portPrettyLabel - sfp-lan/sfp-wan
  1430. // conservan su nombre (antes "SFP -lan"/"SFP -wan").
  1431. label := portPrettyLabel(st.Name)
  1432. ep := EthPort{ID: st.Name, Label: label, Up: st.Up}
  1433. if st.Up {
  1434. ep.Speed = st.Speed
  1435. }
  1436. applyStats(&ep, st.Name)
  1437. extras = append(extras, ep)
  1438. netdev[ep.ID] = st.Name
  1439. used[st.Name] = true
  1440. }
  1441. if len(extras) > 0 {
  1442. sort.Slice(extras, func(i, j int) bool { return NaturalLess(extras[i].ID, extras[j].ID) })
  1443. // Mantener WAN primero, luego LANs, luego extras.
  1444. ports = append(ports, extras...)
  1445. }
  1446. return promoteUplink(ports, netdev, uplink, brMembers, wanDeclared, physicalPortCount(states, conduits))
  1447. }
  1448. // physicalPortCount cuenta las bocas fisicas del payload: ni bridges, ni VLAN,
  1449. // ni tuneles, ni el puerto de CPU de un switch DSA (#1949).
  1450. func physicalPortCount(states []PortState, conduits map[string]bool) int {
  1451. n := 0
  1452. for _, st := range states {
  1453. if st.DSA || skipRe.MatchString(st.Name) || !phyRe.MatchString(st.Name) || conduits[st.Name] {
  1454. continue
  1455. }
  1456. n++
  1457. }
  1458. return n
  1459. }
  1460. // promoteUplink marca como WAN la boca por la que sale internet cuando
  1461. // ninguna ha salido ya como tal. Hay routers cuyo uplink no entra por una
  1462. // boca WAN dedicada: el PPPoE puede ir sobre una boca llamada "lan1" y el
  1463. // board.json solo declara un módem como WAN, así que sin esto ninguna boca
  1464. // sale con id "wan" -- y la UI marca el uplink y cuelga los datos de la
  1465. // conexión (proto, IP pública, gateway, DNS) justo de esa.
  1466. //
  1467. // La boca conserva su sitio y su iface: las estadísticas y la MAC siguen
  1468. // siendo las suyas, solo cambia cómo se presenta.
  1469. //
  1470. // #1482: cuando el layout YA trae una boca WAN pero el uplink runtime cae
  1471. // en otra distinta, manda netifd: la boca del uplink se promueve y la del
  1472. // layout vuelve a su netdev (ETH n). El layout es una descripción estática
  1473. // del cableado de vendor; el uplink runtime es la verdad de terreno de por
  1474. // dónde sale internet (caso real: board.json con wan en eth0 porque ahí
  1475. // vive el management, y el PPPoE saliendo por eth2). Si la boca WAN del
  1476. // layout no tiene un netdev físico al que volver (no consta, o se llama
  1477. // literalmente "wan"), no se toca nada: antes mantener la presentación del
  1478. // layout que duplicar el id "wan".
  1479. func promoteUplink(ports []EthPort, netdev map[string]string, uplink string, brMembers map[string]bool, wanDeclared bool, physical int) []EthPort {
  1480. if uplink == "" {
  1481. return ports
  1482. }
  1483. // El uplink puede llegar etiquetado ("lan1.7"): la boca es la de debajo.
  1484. base := uplink
  1485. if i := strings.LastIndexByte(base, '.'); i > 0 {
  1486. base = base[:i]
  1487. }
  1488. // #1976: si el layout ya declara una boca WAN y el uplink runtime cae en un
  1489. // miembro del bridge LAN, la unidad está haciendo de puente o de AP y el
  1490. // internet le llega por la LAN. Promover esa boca la pintaba como WAN con
  1491. // el tráfico de la LAN y devolvía la WAN del layout a "ETH n" (WNDR3700v2:
  1492. // la WAN declarada en eth1 se quedaba abajo como "ETH 1" y el puerto del
  1493. // switch eth0 aparecía como WAN y activo). Sin WAN declarada manda el
  1494. // uplink, que es lo que necesitan los AP sin layout (#1500).
  1495. // wanDeclared: la unidad declara WAN y el uplink le llega por el bridge
  1496. // (#1976). physical < 2: un AP de una sola boca no tiene puerto WAN que
  1497. // enseñar (#1949), aunque no haya layout que lo diga.
  1498. if brMembers[base] && (wanDeclared || physical < 2) {
  1499. return ports
  1500. }
  1501. wanIdx, upIdx := -1, -1
  1502. for i := range ports {
  1503. if ports[i].ID == "wan" {
  1504. wanIdx = i
  1505. }
  1506. if upIdx < 0 {
  1507. if n := netdev[ports[i].ID]; n == uplink || n == base {
  1508. upIdx = i
  1509. }
  1510. }
  1511. }
  1512. if wanIdx < 0 {
  1513. // Ninguna boca salió como WAN en el layout: promueve la del uplink.
  1514. if upIdx >= 0 {
  1515. ports[upIdx].ID, ports[upIdx].Label = "wan", "WAN"
  1516. }
  1517. return ports
  1518. }
  1519. if upIdx < 0 || upIdx == wanIdx {
  1520. return ports // sin uplink, o de acuerdo con el layout
  1521. }
  1522. nd := netdev[ports[wanIdx].ID]
  1523. if nd == "" || nd == "wan" {
  1524. return ports // sin netdev físico al que volver: no duplicar la WAN
  1525. }
  1526. ports[wanIdx].ID, ports[wanIdx].Label = nd, portPrettyLabel(nd)
  1527. ports[upIdx].ID, ports[upIdx].Label = "wan", "WAN"
  1528. return ports
  1529. }
  1530. // NaturalLess ordena lan2 < lan10 (localeCompare numeric del JS).
  1531. func NaturalLess(a, b string) bool {
  1532. re := regexp.MustCompile(`^(.*?)(\d+)$`)
  1533. ma, mb := re.FindStringSubmatch(a), re.FindStringSubmatch(b)
  1534. if ma != nil && mb != nil && ma[1] == mb[1] {
  1535. na, _ := strconv.Atoi(ma[2])
  1536. nb, _ := strconv.Atoi(mb[2])
  1537. return na < nb
  1538. }
  1539. return a < b
  1540. }
  1541. // Filtro de puertos del FDB (#506): DENYLIST, no allowlist. El allowlist
  1542. // histórico (lan\d+|wan|eth\d+|swp\d+|en...) descartaba en silencio MACs
  1543. // aprendidas en puertos con nombres no enumerados: las jaulas SFP del BPI-R4
  1544. // se llaman "sfp-lan"/"sfp-wan" (openwrt,netdev-name, 25.12+) y sus
  1545. // dispositivos cableados jamás llegaban a descubrirse. Ahora vale cualquier
  1546. // puerto MIEMBRO del bridge (los no-miembros ya no resuelven en ==PORTS==)
  1547. // salvo los wireless (clientes que llegan por la sección wireless) y las
  1548. // interfaces virtuales.
  1549. var (
  1550. // wl\d+ cubre las radios Broadcom de Asuswrt/Merlin (wl0..wl3): el bridge
  1551. // aprende las MACs propias de cada radio (bit LAA volteado) como entradas
  1552. // externas en esos puertos, y sin excluirlas cada radio aparecía como un
  1553. // cliente "cableado" fantasma del AP. La alternativa wl va anclada (con su
  1554. // subinterfaz VLAN opcional): por prefijo casaría interfaces futuras que
  1555. // solo compartan las letras iniciales.
  1556. fdbWirelessRe = regexp.MustCompile(`^(phy\d+-ap\d*|wlan\d*|wl[0-9]+(\.[0-9]+)?)$`)
  1557. fdbVirtualRe = regexp.MustCompile(`^(br|lo|veth|wg|tun|tap|ppp|sit|ip6|gre|erspan|dummy|macv|ifb|bat[0-9]+)`)
  1558. )
  1559. // fdbPortWired: ¿cuenta este puerto como cableado para el mapa MAC→puerto?
  1560. // La subinterfaz VLAN (eth0.999, lan1.10) SÍ cuenta: es el puerto real del
  1561. // bridge en un router que segmenta con 802.1Q y el FDB lo nombra así (antes se
  1562. // descartaba por llevar punto, y todos los clientes cableados de sus bridges
  1563. // se quedaban sin puerto y sin VLAN, #1757). Lo que no cuenta es una
  1564. // subinterfaz de radio (wl0.1, wlan0.1) ni una interfaz virtual (br*, veth*).
  1565. func fdbPortWired(port string) bool {
  1566. if port == "" || strings.Contains(port, "@") {
  1567. return false
  1568. }
  1569. base := port
  1570. if i := strings.IndexByte(base, '.'); i > 0 {
  1571. base = base[:i]
  1572. }
  1573. return !fdbWirelessRe.MatchString(base) && !fdbVirtualRe.MatchString(base)
  1574. }
  1575. // ParseBridgeFdb parsea la salida ==PORTS==/==MACS== → MAC aprendida → puerto.
  1576. // Acepta dos formatos en ==MACS==: brctl (`<port_no> <mac>`) y
  1577. // `bridge fdb show` (`<ifname> <mac> [vlan <id>]`).
  1578. func ParseBridgeFdb(out string) map[string]string {
  1579. wired, _, _ := ParseBridgeFdbVlans(out)
  1580. return wired
  1581. }
  1582. // ParseBridgeFdbSplit es ParseBridgeFdb devolviendo además las MACs aprendidas
  1583. // en puertos del lado inalámbrico (wl0.1, wlan0, phy0-ap0…): no son clientes
  1584. // cableados, pero tampoco deben tirarse: son la única evidencia de que esa MAC
  1585. // vive detrás de esta radio (MACs rotadas que siguen emitiendo, clientes en
  1586. // backhaul 4-address). Sin este segundo mapa el server las vería únicamente en
  1587. // el FDB de tránsito del gateway y su fallback las dibujaría como cableadas.
  1588. func ParseBridgeFdbSplit(out string) (wired, wirelessSide map[string]string) {
  1589. wired, wirelessSide, _ = ParseBridgeFdbVlans(out)
  1590. return wired, wirelessSide
  1591. }
  1592. // ParseBridgeFdbVlans: lo anterior más la VLAN con la que el bridge aprendió
  1593. // cada MAC (el `vlan <id>` de `bridge fdb show`, solo en bridges con VLAN
  1594. // filtering). Es el dato exacto del segmento de un cliente cableado: el PVID
  1595. // del puerto dice dónde entra la trama sin etiquetar, no en qué VLAN vive el
  1596. // cliente.
  1597. //
  1598. // Las secciones pueden venir con el nombre del bridge detrás de la marca
  1599. // ("==PORTS==br_switch", un bridge por segmento). Sin sufijo se asume una sola
  1600. // tabla, que es lo que emite un agente viejo.
  1601. func ParseBridgeFdbVlans(out string) (wired, wirelessSide map[string]string, vlans map[string]int) {
  1602. wired = map[string]string{}
  1603. wirelessSide = map[string]string{}
  1604. vlans = map[string]int{}
  1605. // bridge → port_no → ifname. La clave "" cubre la salida sin sufijo.
  1606. portNames := map[string]map[string]string{}
  1607. bridge := ""
  1608. section := byte(0)
  1609. ports := func(br string) map[string]string {
  1610. m, ok := portNames[br]
  1611. if !ok {
  1612. m = map[string]string{}
  1613. portNames[br] = m
  1614. }
  1615. return m
  1616. }
  1617. for _, line := range strings.Split(out, "\n") {
  1618. t := strings.TrimSpace(line)
  1619. if strings.HasPrefix(t, "==PORTS==") {
  1620. section = 'p'
  1621. bridge = strings.TrimSpace(strings.TrimPrefix(t, "==PORTS=="))
  1622. continue
  1623. }
  1624. if strings.HasPrefix(t, "==MACS==") {
  1625. section = 'm'
  1626. bridge = strings.TrimSpace(strings.TrimPrefix(t, "==MACS=="))
  1627. continue
  1628. }
  1629. p := strings.Fields(t)
  1630. if len(p) < 2 {
  1631. continue
  1632. }
  1633. switch section {
  1634. case 'p':
  1635. no, name := p[0], p[1]
  1636. if strings.HasPrefix(no, "0x") {
  1637. if n, err := strconv.ParseInt(no[2:], 16, 64); err == nil {
  1638. no = strconv.FormatInt(n, 10)
  1639. }
  1640. }
  1641. m := ports(bridge)
  1642. m[no] = name
  1643. m[name] = name // puerto también localizable por nombre (bridge fdb)
  1644. case 'm':
  1645. no, mac := p[0], p[1]
  1646. m := ports(bridge)
  1647. port, ok := m[no]
  1648. if !ok || mac == "" {
  1649. continue
  1650. }
  1651. mac = strings.ToUpper(mac)
  1652. if len(p) >= 3 {
  1653. if vid, err := strconv.Atoi(p[2]); err == nil && vid > 0 {
  1654. vlans[mac] = vid
  1655. }
  1656. }
  1657. switch {
  1658. case fdbPortWired(port):
  1659. wired[mac] = port
  1660. case fdbPortWirelessSide(port):
  1661. wirelessSide[mac] = port
  1662. }
  1663. }
  1664. }
  1665. return wired, wirelessSide, vlans
  1666. }
  1667. // fdbPortWirelessSide: puertos del bridge que son radios o subinterfaces de
  1668. // radio (wl0.1, wlan0, phy0-ap0). Las interfaces virtuales no inalámbricas
  1669. // (br*, veth*, tun*) NO cuentan: ahí la MAC no llegó por el aire.
  1670. func fdbPortWirelessSide(port string) bool {
  1671. base := port
  1672. if i := strings.IndexAny(base, ".@"); i >= 0 {
  1673. base = base[:i]
  1674. }
  1675. return fdbWirelessRe.MatchString(base)
  1676. }
  1677. // LuCILabels: etiquetas de puertos y VLANs de LuCI (issue #258). OpenWrt
  1678. // snapshots las definen en /etc/config/luci como secciones switchvlan:
  1679. //
  1680. // config switchvlan 'port_labels'
  1681. // option lan1 'Router/Fritzbox'
  1682. // config switchvlan 'vlan_labels'
  1683. // option 1 'LAN'
  1684. //
  1685. // PortLabels mapea interfaz (lan1…) → etiqueta; VlanLabels mapea id de
  1686. // VLAN → etiqueta.
  1687. type LuCILabels struct {
  1688. PortLabels map[string]string `json:"portLabels,omitempty"`
  1689. VlanLabels map[string]string `json:"vlanLabels,omitempty"`
  1690. }
  1691. var (
  1692. luciSectionRe = regexp.MustCompile(`^config\s+(\S+)\s+['"]?([A-Za-z0-9_]+)['"]?`)
  1693. luciOptionRe = regexp.MustCompile(`^option\s+(\S+)\s+['"]?([^'"]*)['"]?$`)
  1694. )
  1695. // ParseLuCILabels parsea /etc/config/luci y extrae las secciones
  1696. // port_labels/vlan_labels. Devuelve nil si no hay ninguna etiqueta.
  1697. func ParseLuCILabels(out string) *LuCILabels {
  1698. var labels LuCILabels
  1699. var section string
  1700. for _, raw := range strings.Split(out, "\n") {
  1701. line := strings.TrimSpace(raw)
  1702. if line == "" || strings.HasPrefix(line, "#") {
  1703. continue
  1704. }
  1705. if m := luciSectionRe.FindStringSubmatch(line); m != nil {
  1706. section = m[2]
  1707. continue
  1708. }
  1709. if section != "port_labels" && section != "vlan_labels" {
  1710. continue
  1711. }
  1712. if m := luciOptionRe.FindStringSubmatch(line); m != nil {
  1713. if m[2] == "" {
  1714. continue
  1715. }
  1716. if section == "port_labels" {
  1717. if labels.PortLabels == nil {
  1718. labels.PortLabels = map[string]string{}
  1719. }
  1720. labels.PortLabels[m[1]] = m[2]
  1721. } else {
  1722. if labels.VlanLabels == nil {
  1723. labels.VlanLabels = map[string]string{}
  1724. }
  1725. labels.VlanLabels[m[1]] = m[2]
  1726. }
  1727. }
  1728. }
  1729. if len(labels.PortLabels) == 0 && len(labels.VlanLabels) == 0 {
  1730. return nil
  1731. }
  1732. return &labels
  1733. }
  1734. // VlanEntry: una VLAN de un puerto del bridge (issue #315). ID es el número
  1735. // de VLAN (1-4094); Tagged=false + Untagged en el wire (Egress Untagged);
  1736. // PVID=true indica que este puerto es el puerto nativo de esta VLAN.
  1737. type VlanEntry struct {
  1738. ID int `json:"id"`
  1739. Tagged bool `json:"tagged"`
  1740. PVID bool `json:"pvid"`
  1741. // Name es la etiqueta que LuCI da a la VLAN (uci show network, #258),
  1742. // rellenada por el servidor al juntarla con VlanLabels (#1757).
  1743. Name string `json:"name,omitempty"`
  1744. // Subnet es la red que sirve la VLAN (192.168.111.1/24), sacada de la
  1745. // interfaz que vive en el bridge (#1757).
  1746. Subnet string `json:"subnet,omitempty"`
  1747. }
  1748. // VlanPort: puerto del bridge con sus VLANs (issue #315).
  1749. type VlanPort struct {
  1750. Port string `json:"port"`
  1751. Vlans []VlanEntry `json:"vlans"`
  1752. }
  1753. var vlanIDRe = regexp.MustCompile(`^(\d+)(.*)$`)
  1754. // ParseBridgeVlan parsea la salida de `bridge vlan show` (issue #315).
  1755. // Formato: líneas "port vlan-id [flags]" o " vlan-id [flags]" (continuation).
  1756. // Flags: "PVID" = puerto nativo; "Egress Untagged" = untagged en salida.
  1757. func ParseBridgeVlan(out string) []VlanPort {
  1758. var ports []VlanPort
  1759. var cur *VlanPort
  1760. for _, raw := range strings.Split(out, "\n") {
  1761. line := strings.TrimRight(raw, "\r\n")
  1762. if line == "" || strings.HasPrefix(line, "port") {
  1763. continue
  1764. }
  1765. trimmed := strings.TrimSpace(line)
  1766. if trimmed == "" {
  1767. continue
  1768. }
  1769. isContinuation := len(line) > 0 && (line[0] == ' ' || line[0] == '\t')
  1770. fields := strings.Fields(trimmed)
  1771. if len(fields) == 0 {
  1772. continue
  1773. }
  1774. var portName string
  1775. var vlanField string
  1776. if isContinuation {
  1777. if cur == nil {
  1778. continue
  1779. }
  1780. vlanField = fields[0]
  1781. } else {
  1782. portName = fields[0]
  1783. if len(fields) < 2 {
  1784. continue
  1785. }
  1786. vlanField = fields[1]
  1787. }
  1788. m := vlanIDRe.FindStringSubmatch(vlanField)
  1789. if m == nil {
  1790. continue
  1791. }
  1792. id, err := strconv.Atoi(m[1])
  1793. if err != nil || id < 1 || id > 4094 {
  1794. continue
  1795. }
  1796. rest := strings.ToLower(m[2])
  1797. if len(fields) > 2 {
  1798. rest += " " + strings.ToLower(strings.Join(fields[2:], " "))
  1799. }
  1800. pvid := strings.Contains(rest, "pvid")
  1801. tagged := !strings.Contains(rest, "egress untagged")
  1802. entry := VlanEntry{ID: id, Tagged: tagged, PVID: pvid}
  1803. if isContinuation {
  1804. cur.Vlans = append(cur.Vlans, entry)
  1805. } else {
  1806. ports = append(ports, VlanPort{Port: portName, Vlans: []VlanEntry{entry}})
  1807. cur = &ports[len(ports)-1]
  1808. }
  1809. }
  1810. return ports
  1811. }
  1812. var nonDigitRe = regexp.MustCompile(`\D`)
  1813. // ParseRadios: líneas "freq|ch|ht|tx|n" agregadas por banda (suma clientes).
  1814. // hostapdClientsJSON es el shape de `ubus call hostapd.<if> get_clients`.
  1815. // El objeto por estación incluye `bytes:{rx,tx}` (acumulados desde la
  1816. // asociación) y `packets` cuando el driver responde a read_sta_data (#551);
  1817. // si no los expone, quedan a cero.
  1818. type hostapdClientsJSON struct {
  1819. Freq float64 `json:"freq"`
  1820. Clients map[string]struct {
  1821. Auth bool `json:"auth"`
  1822. Assoc bool `json:"assoc"`
  1823. Authorized bool `json:"authorized"`
  1824. Signal int `json:"signal"`
  1825. Bytes struct {
  1826. Rx uint64 `json:"rx"`
  1827. Tx uint64 `json:"tx"`
  1828. } `json:"bytes"`
  1829. } `json:"clients"`
  1830. }
  1831. // ParseHostapdClients (#368) parsea el output de CmdHostapdClients: bloques
  1832. // "==AP==hostapd.phy0-ap0" seguidos del JSON de get_clients. Solo cuenta
  1833. // estaciones asociadas y autorizadas (equivalente a iwinfo assoclist); la
  1834. // banda sale del "freq" del bloque (>=5 GHz = "5 GHz"). Mismo shape que
  1835. // ParseWirelessClients. RxBytes/TxBytes son los contadores acumulados de la
  1836. // estación si el driver los reportó (issue #551).
  1837. func ParseHostapdClients(out string) map[string]WirelessClient {
  1838. m := map[string]WirelessClient{}
  1839. // Sección de SSIDs (iw dev) al final de la salida: iface → SSID.
  1840. head := out
  1841. ssidByIface := map[string]string{}
  1842. if i := strings.Index(out, "==SSID=="); i >= 0 {
  1843. head = out[:i]
  1844. for _, line := range strings.Split(out[i:], "\n") {
  1845. p := strings.Fields(line)
  1846. if len(p) == 2 && p[0] != "==SSID==" {
  1847. ssidByIface[p[0]] = p[1]
  1848. }
  1849. }
  1850. }
  1851. for _, chunk := range strings.Split(head, "==AP==") {
  1852. chunk = strings.TrimSpace(chunk)
  1853. if chunk == "" {
  1854. continue
  1855. }
  1856. // La marca lleva el objeto ubus delante; el JSON empieza en "{".
  1857. i := strings.Index(chunk, "{")
  1858. if i < 0 {
  1859. continue
  1860. }
  1861. // #1757: el objeto ubus ES la interfaz AP ("hostapd.phy1-ap2"). Sin
  1862. // este dato el cliente wifi viajaba sin `Iface`, y el mapa no podía
  1863. // casarlo con el puerto del bridge para leer su VLAN: todo cliente
  1864. // wifi de un OpenWrt con hostapd (o sea, casi todos) salía sin VLAN.
  1865. iface := strings.TrimSpace(chunk[:i])
  1866. iface = strings.TrimPrefix(iface, "hostapd.")
  1867. iface = strings.TrimSpace(strings.TrimPrefix(iface, "/"))
  1868. var j hostapdClientsJSON
  1869. if err := json.Unmarshal([]byte(chunk[i:]), &j); err != nil || j.Freq == 0 {
  1870. continue
  1871. }
  1872. freq := j.Freq
  1873. if freq >= 1000 { // ubus get_clients da MHz; iwinfo da GHz
  1874. freq /= 1000
  1875. }
  1876. band := "2.4 GHz"
  1877. if freq >= 5 {
  1878. band = "5 GHz"
  1879. }
  1880. for mac, st := range j.Clients {
  1881. if !st.Assoc || !st.Authorized {
  1882. continue
  1883. }
  1884. m[strings.ToUpper(mac)] = WirelessClient{
  1885. SignalDbm: st.Signal, Band: band, Iface: iface,
  1886. SSID: ssidByIface[iface],
  1887. RxBytes: st.Bytes.Rx, TxBytes: st.Bytes.Tx,
  1888. }
  1889. }
  1890. }
  1891. return m
  1892. }
  1893. // ParseWirelessCombined (#368) parsea CmdWirelessCombined: líneas "C|mac|sig|
  1894. // freq" (clientes, mismo shape que ParseWirelessClients) y "R|freq|ch|ht|tx|n"
  1895. // (radios, mismo shape que ParseRadios, que se reutiliza).
  1896. func ParseWirelessCombined(out string) (map[string]WirelessClient, []Radio) {
  1897. clients := map[string]WirelessClient{}
  1898. var radioLines []string
  1899. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  1900. line = strings.TrimSpace(line)
  1901. switch {
  1902. case strings.HasPrefix(line, "C|"):
  1903. p := strings.Split(line, "|")
  1904. if len(p) < 4 {
  1905. continue
  1906. }
  1907. sig, _ := strconv.Atoi(p[2])
  1908. freq, _ := strconv.ParseFloat(p[3], 64)
  1909. band := "2.4 GHz"
  1910. if freq >= 5 {
  1911. band = "5 GHz"
  1912. }
  1913. clients[strings.ToUpper(p[1])] = WirelessClient{SignalDbm: sig, Band: band}
  1914. case strings.HasPrefix(line, "R|"):
  1915. radioLines = append(radioLines, strings.TrimPrefix(line, "R|"))
  1916. }
  1917. }
  1918. return clients, ParseRadios(strings.Join(radioLines, "\n"))
  1919. }
  1920. func ParseRadios(out string) []Radio {
  1921. byBand := map[string]*Radio{}
  1922. order := []string{}
  1923. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  1924. if line == "" {
  1925. continue
  1926. }
  1927. p := strings.Split(line, "|")
  1928. if len(p) < 5 {
  1929. continue
  1930. }
  1931. freq, _ := strconv.ParseFloat(p[0], 64)
  1932. if freq == 0 {
  1933. continue
  1934. }
  1935. band := "2.4 GHz"
  1936. if freq >= 5 {
  1937. band = "5 GHz"
  1938. }
  1939. width, _ := strconv.Atoi(nonDigitRe.ReplaceAllString(p[2], ""))
  1940. if width == 0 {
  1941. width = 20
  1942. }
  1943. ch, _ := strconv.Atoi(p[1])
  1944. tx, _ := strconv.Atoi(p[3])
  1945. // #1213: formato nuevo "freq|ch|ht|tx|bssid|noise|n" (7 campos);
  1946. // el histórico "freq|ch|ht|tx|n" (5) sigue parseando igual.
  1947. var noise *int
  1948. var bssid string
  1949. n := 0
  1950. if len(p) >= 7 {
  1951. bssid = strings.ToUpper(strings.TrimSpace(p[4]))
  1952. if v, err := strconv.Atoi(strings.TrimSpace(p[5])); err == nil && v != 0 {
  1953. noise = &v
  1954. }
  1955. n, _ = strconv.Atoi(p[6])
  1956. } else {
  1957. n, _ = strconv.Atoi(p[4])
  1958. }
  1959. if cur, ok := byBand[band]; ok {
  1960. cur.Clients += n
  1961. if cur.NoiseDbm == nil {
  1962. cur.NoiseDbm = noise
  1963. }
  1964. if cur.BSSID == "" {
  1965. cur.BSSID = bssid
  1966. }
  1967. } else {
  1968. byBand[band] = &Radio{Name: band, Channel: ch, WidthMhz: width, PowerDbm: float64(tx), Clients: n, NoiseDbm: noise, BSSID: bssid}
  1969. order = append(order, band)
  1970. }
  1971. }
  1972. radios := []Radio{}
  1973. for _, b := range order {
  1974. radios = append(radios, *byBand[b])
  1975. }
  1976. return radios
  1977. }
  1978. // ParseRadioSections parsea la salida de CmdRadioSections y devuelve
  1979. // banda ("2.4 GHz"|"5 GHz"|"6 GHz") → sección UCI ("radio0"). Solo se queda
  1980. // con la primera sección por banda (si hay varias, la primera gana; el
  1981. // channel plan trabaja por banda).
  1982. func ParseRadioSections(out string) map[string]string {
  1983. sections := map[string]string{}
  1984. secBand := map[string]string{}
  1985. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  1986. line = strings.TrimSpace(line)
  1987. if !strings.HasPrefix(line, "wireless.") {
  1988. continue
  1989. }
  1990. parts := strings.SplitN(line, "=", 2)
  1991. if len(parts) != 2 {
  1992. continue
  1993. }
  1994. key := strings.TrimPrefix(parts[0], "wireless.")
  1995. val := strings.Trim(parts[1], "'")
  1996. rel, opt, hasOpt := strings.Cut(key, ".")
  1997. if !hasOpt {
  1998. if val == "wifi-device" {
  1999. secBand[rel] = "" // sección conocida, banda pendiente
  2000. }
  2001. continue
  2002. }
  2003. band, ok := secBand[rel]
  2004. if !ok || band != "" {
  2005. continue
  2006. }
  2007. switch {
  2008. case opt == "band" || (opt == "hwmode" && (val == "11g" || val == "11a")):
  2009. switch {
  2010. case val == "2g" || val == "11g":
  2011. secBand[rel] = "2.4 GHz"
  2012. case val == "5g" || val == "11a":
  2013. secBand[rel] = "5 GHz"
  2014. case val == "6g":
  2015. secBand[rel] = "6 GHz"
  2016. }
  2017. }
  2018. }
  2019. for sec, band := range secBand {
  2020. if band != "" {
  2021. if _, exists := sections[band]; !exists {
  2022. sections[band] = sec
  2023. }
  2024. }
  2025. }
  2026. return sections
  2027. }
  2028. // ParseScan parsea la salida de CmdScan: bloques "==IFACE==<iface>" seguidos de
  2029. // la salida de `iw dev <iface> scan`. Extrae BSS, freq, signal y SSID.
  2030. func ParseScan(out string) []ScanResult {
  2031. var res []ScanResult
  2032. iface := ""
  2033. var current *ScanResult
  2034. // Estado del bloque HT/VHT en curso para el ancho de canal (#1087).
  2035. section := ""
  2036. ht40, vhtWidth := false, 0
  2037. flush := func() {
  2038. if current != nil && current.BSSID != "" && current.Freq > 0 {
  2039. current.Channel = FreqToChannel(current.Freq)
  2040. if current.Channel > 0 {
  2041. switch {
  2042. case vhtWidth > 0:
  2043. current.WidthMhz = vhtWidth
  2044. case ht40:
  2045. current.WidthMhz = 40
  2046. default:
  2047. current.WidthMhz = 20
  2048. }
  2049. res = append(res, *current)
  2050. }
  2051. }
  2052. current = nil
  2053. }
  2054. for _, raw := range strings.Split(out, "\n") {
  2055. line := strings.TrimSpace(raw)
  2056. if strings.HasPrefix(line, "==IFACE==") {
  2057. flush()
  2058. iface = strings.TrimPrefix(line, "==IFACE==")
  2059. continue
  2060. }
  2061. if strings.HasPrefix(line, "BSS ") {
  2062. flush()
  2063. fields := strings.Fields(line)
  2064. if len(fields) < 2 {
  2065. continue
  2066. }
  2067. bssid := strings.ToUpper(strings.Split(fields[1], "(")[0])
  2068. current = &ScanResult{Iface: iface, BSSID: bssid}
  2069. section, ht40, vhtWidth = "", false, 0
  2070. continue
  2071. }
  2072. if current == nil {
  2073. continue
  2074. }
  2075. // Ancho de canal anunciado por el vecino (#1087): HT operation da
  2076. // el salto de 40 MHz; VHT operation el de 80/160.
  2077. switch {
  2078. case strings.HasPrefix(line, "HT operation:"):
  2079. section = "ht"
  2080. continue
  2081. case strings.HasPrefix(line, "VHT operation:"):
  2082. section = "vht"
  2083. continue
  2084. case strings.HasPrefix(line, "HE operation:") || strings.HasPrefix(line, "EHT operation:"):
  2085. section = ""
  2086. continue
  2087. }
  2088. if section == "ht" && strings.Contains(line, "secondary channel offset:") {
  2089. ht40 = !strings.Contains(line, "no secondary")
  2090. continue
  2091. }
  2092. if section == "vht" && strings.Contains(line, "channel width:") {
  2093. // "* channel width: 1 (80 MHz)": 1 = 80 MHz, 2 = 160 MHz.
  2094. re := vhtWidthRe.FindStringSubmatch(line)
  2095. if re != nil {
  2096. n, _ := strconv.Atoi(re[1])
  2097. switch n {
  2098. case 1:
  2099. vhtWidth = 80
  2100. case 2:
  2101. vhtWidth = 160
  2102. }
  2103. }
  2104. continue
  2105. }
  2106. if strings.HasPrefix(line, "freq:") {
  2107. // iw imprime la frecuencia como float ("freq: 5260.0"): Atoi
  2108. // fallaba en silencio, Freq quedaba 0 y el flush descartaba TODOS
  2109. // los BSS (scans siempre vacíos, #475).
  2110. if f, err := strconv.ParseFloat(strings.TrimSpace(strings.TrimPrefix(line, "freq:")), 64); err == nil {
  2111. current.Freq = int(f)
  2112. }
  2113. continue
  2114. }
  2115. if strings.HasPrefix(line, "signal:") {
  2116. v, _ := strconv.ParseFloat(strings.Fields(strings.TrimPrefix(line, "signal:"))[0], 64)
  2117. current.Signal = int(v)
  2118. continue
  2119. }
  2120. if strings.HasPrefix(line, "SSID:") {
  2121. current.SSID = strings.TrimSpace(strings.TrimPrefix(line, "SSID:"))
  2122. continue
  2123. }
  2124. }
  2125. flush()
  2126. return res
  2127. }
  2128. var vhtWidthRe = regexp.MustCompile(`channel width:\s*(\d)\s*\(`)
  2129. // ParseIwDev parsea la salida de CmdIwDev (`iw dev`) y devuelve las
  2130. // interfaces AP de ESTE equipo con su BSSID y SSID (#1087). Los bloques
  2131. // "Interface <name>" traen addr, ssid y type; solo type AP interesa (los
  2132. // STA/clientes managed no son red propia).
  2133. func ParseIwDev(out string) []OwnBSSID {
  2134. var res []OwnBSSID
  2135. iface, addr, ssid, ifType := "", "", "", ""
  2136. flush := func() {
  2137. if iface != "" && addr != "" && ifType == "AP" {
  2138. res = append(res, OwnBSSID{Iface: iface, BSSID: strings.ToUpper(addr), SSID: ssid})
  2139. }
  2140. }
  2141. for _, raw := range strings.Split(out, "\n") {
  2142. line := strings.TrimSpace(raw)
  2143. fields := strings.Fields(line)
  2144. if len(fields) >= 2 && fields[0] == "Interface" {
  2145. flush()
  2146. iface, addr, ssid, ifType = fields[1], "", "", ""
  2147. continue
  2148. }
  2149. if len(fields) >= 2 && fields[0] == "addr" {
  2150. addr = fields[1]
  2151. continue
  2152. }
  2153. if len(fields) >= 2 && fields[0] == "ssid" {
  2154. ssid = strings.TrimSpace(strings.TrimPrefix(line, "ssid"))
  2155. continue
  2156. }
  2157. if len(fields) >= 2 && fields[0] == "type" {
  2158. ifType = fields[1]
  2159. continue
  2160. }
  2161. }
  2162. flush()
  2163. return res
  2164. }
  2165. // IwDevIfaces (#1338) lists EVERY interface of `iw dev` (any type, not only
  2166. // AP like ParseIwDev). Since #1560 the scan groups them by radio with
  2167. // ParseIwDevDetailed instead of scanning each one.
  2168. func IwDevIfaces(out string) []string {
  2169. var res []string
  2170. for _, i := range ParseIwDevDetailed(out) {
  2171. res = append(res, i.Iface)
  2172. }
  2173. return res
  2174. }
  2175. // FreqToChannel convierte frecuencia (MHz) a número de canal 802.11.
  2176. func FreqToChannel(freq int) int {
  2177. switch {
  2178. case freq >= 2412 && freq <= 2484:
  2179. if freq == 2484 {
  2180. return 14
  2181. }
  2182. return (freq-2412)/5 + 1
  2183. case freq >= 5180 && freq <= 5885:
  2184. // 5 GHz UNII-1/2/3: 36, 40, 44, ... 165
  2185. return (freq-5180)/5 + 36
  2186. case freq >= 5955 && freq <= 7115:
  2187. // 6 GHz: 1-229 (PSCO no se soporta en esta fase)
  2188. return (freq-5955)/5 + 1
  2189. }
  2190. return 0
  2191. }
  2192. var (
  2193. sfpTempRe = regexp.MustCompile(`(?i)Module temperature\s*:\s*(-?[\d.]+)`)
  2194. sfpVoltRe = regexp.MustCompile(`(?i)Module voltage\s*:\s*([\d.]+)`)
  2195. sfpTxPwrRe = regexp.MustCompile(`(?i)Laser output power\s*:.*?/\s*(-?[\d.]+)\s*dBm`)
  2196. sfpRxPwrRe = regexp.MustCompile(`(?i)Laser receiver power\s*:.*?/\s*(-?[\d.]+)\s*dBm`)
  2197. sfpVendorRe = regexp.MustCompile(`(?i)Vendor [Nn]ame\s*:\s*(.+)`)
  2198. sfpPNRe = regexp.MustCompile(`(?i)Vendor [Pp]art [Nn]umber\s*:\s*(.+)`)
  2199. )
  2200. // ParseEthtoolSFP parsea la salida de `ethtool -m <iface>` y extrae los
  2201. // valores DDM/DOM del módulo (#313). Devuelve nil si la salida está vacía o
  2202. // no contiene datos de SFP.
  2203. func ParseEthtoolSFP(out string) *SfpInfo {
  2204. if strings.TrimSpace(out) == "" {
  2205. return nil
  2206. }
  2207. info := &SfpInfo{}
  2208. if m := sfpTempRe.FindStringSubmatch(out); m != nil {
  2209. info.Temperature, _ = strconv.ParseFloat(m[1], 64)
  2210. info.Present = true
  2211. }
  2212. if m := sfpVoltRe.FindStringSubmatch(out); m != nil {
  2213. info.Voltage, _ = strconv.ParseFloat(m[1], 64)
  2214. }
  2215. if m := sfpTxPwrRe.FindStringSubmatch(out); m != nil {
  2216. info.TxPower, _ = strconv.ParseFloat(m[1], 64)
  2217. }
  2218. if m := sfpRxPwrRe.FindStringSubmatch(out); m != nil {
  2219. info.RxPower, _ = strconv.ParseFloat(m[1], 64)
  2220. }
  2221. if m := sfpVendorRe.FindStringSubmatch(out); m != nil {
  2222. info.Vendor = strings.TrimSpace(m[1])
  2223. }
  2224. if m := sfpPNRe.FindStringSubmatch(out); m != nil {
  2225. info.PartNumber = strings.TrimSpace(m[1])
  2226. }
  2227. if !info.Present {
  2228. return nil
  2229. }
  2230. return info
  2231. }
  2232. func round0(v float64) float64 { return float64(int64(v + 0.5)) }
  2233. func max0(v float64) float64 {
  2234. if v < 0 {
  2235. return 0
  2236. }
  2237. return v
  2238. }
  2239. // ParseMdnsHosts (#338): parses `ubus call umdns hosts` into IP -> hostname.
  2240. // The trailing ".local" is dropped: it is the mDNS suffix, not part of the
  2241. // name anyone recognises. Entries without an IPv4 are skipped.
  2242. func ParseMdnsHosts(raw []byte) map[string]string {
  2243. var hosts map[string]struct {
  2244. IPv4 string `json:"ipv4"`
  2245. }
  2246. out := map[string]string{}
  2247. if json.Unmarshal(raw, &hosts) != nil {
  2248. return out
  2249. }
  2250. for name, h := range hosts {
  2251. if h.IPv4 == "" {
  2252. continue
  2253. }
  2254. out[h.IPv4] = strings.TrimSuffix(name, ".local")
  2255. }
  2256. return out
  2257. }
  2258. // ParseMdnsBrowse (#338): parsea la salida de `ubus call umdns browse`.
  2259. // Formato típico (JSON):
  2260. //
  2261. // { "hostname._service._tcp.local": { "port": 1234, "txt": [...] }, ... }
  2262. //
  2263. // Extrae: hostname (de la clave, antes del primer punto) y tipos de servicio
  2264. // (el segmento _service._tcp). También recoge IPs si aparecen en registros A.
  2265. func ParseMdnsBrowse(raw []byte) *DiscoveryData {
  2266. return parseMdnsBrowseRecords(raw)
  2267. }
  2268. func appendUnique(slice []string, s string) []string {
  2269. for _, x := range slice {
  2270. if x == s {
  2271. return slice
  2272. }
  2273. }
  2274. return append(slice, s)
  2275. }
  2276. // IsRandomizedMAC returns true if the MAC address has the locally-administered
  2277. // bit set (bit 1 of byte 0). Apple, Google, and Samsung use this for WiFi
  2278. // privacy features — the device appears as a new MAC periodically.
  2279. func IsRandomizedMAC(mac string) bool {
  2280. return macaddr.IsLocallyAdministered(mac)
  2281. }
  2282. // ParseArp parsea /proc/net/arp (#377): cabecera + líneas
  2283. // "IP net/arp HW flags MAC mask device". Devuelve MAC (upper) → IP,
  2284. // ignorando entradas incompletas (flags 0x0) y MACs nulas.
  2285. func ParseArp(out string) map[string]string {
  2286. m := map[string]string{}
  2287. for _, line := range strings.Split(out, "\n") {
  2288. f := strings.Fields(line)
  2289. if len(f) < 4 || f[0] == "IP" {
  2290. continue
  2291. }
  2292. mac := strings.ToUpper(f[3])
  2293. if mac == "" || mac == "00:00:00:00:00:00" {
  2294. continue
  2295. }
  2296. // flags 0x0 = incomplete: el kernel retiene la IP sin vecino válido.
  2297. if f[2] == "0x0" {
  2298. continue
  2299. }
  2300. if net.ParseIP(f[0]) == nil {
  2301. continue
  2302. }
  2303. m[mac] = f[0]
  2304. }
  2305. return m
  2306. }
  2307. // neighConfirmed: the states in which the kernel vouches for the neighbour
  2308. // being there right now. REACHABLE was confirmed within the reachable time;
  2309. // DELAY and PROBE are on their way to being reconfirmed; PERMANENT and NOARP
  2310. // were put there by hand or by a link that needs no resolution.
  2311. //
  2312. // Everything else -- STALE, FAILED, INCOMPLETE, NONE -- is an address the
  2313. // kernel remembers without being able to say the host is still connected.
  2314. var neighConfirmed = map[string]bool{
  2315. "REACHABLE": true, "DELAY": true, "PROBE": true,
  2316. "PERMANENT": true, "NOARP": true,
  2317. }
  2318. // ParseIPNeigh parses `ip neigh show`, whose lines read
  2319. // "IP dev IFACE lladdr MAC STATE" (an entry being resolved has no lladdr).
  2320. // It returns the same MAC→IP map as ParseArp plus the set of MACs whose
  2321. // every entry is unconfirmed: remembered addresses, not present hosts.
  2322. //
  2323. // A MAC with several addresses counts as confirmed when any one of them is,
  2324. // since one confirmed neighbour is enough to prove the host is there.
  2325. func ParseIPNeigh(out string) (arp map[string]string, stale map[string]bool) {
  2326. arp, stale = map[string]string{}, map[string]bool{}
  2327. confirmed := map[string]bool{}
  2328. for _, line := range strings.Split(out, "\n") {
  2329. f := strings.Fields(line)
  2330. // "IP dev IFACE lladdr MAC STATE" is the shortest useful line.
  2331. if len(f) < 6 || net.ParseIP(f[0]) == nil {
  2332. continue
  2333. }
  2334. var mac string
  2335. for i := 1; i+1 < len(f); i++ {
  2336. if f[i] == "lladdr" {
  2337. mac = strings.ToUpper(f[i+1])
  2338. break
  2339. }
  2340. }
  2341. if mac == "" || mac == "00:00:00:00:00:00" {
  2342. continue
  2343. }
  2344. // The state is the last word of the line; an entry without one is
  2345. // not something to claim presence from.
  2346. if neighConfirmed[f[len(f)-1]] {
  2347. // Confirmed wins for good: a later unconfirmed address for the
  2348. // same host must not undo it.
  2349. arp[mac] = f[0]
  2350. confirmed[mac] = true
  2351. delete(stale, mac)
  2352. continue
  2353. }
  2354. if !confirmed[mac] {
  2355. if _, ok := arp[mac]; !ok {
  2356. arp[mac] = f[0]
  2357. }
  2358. stale[mac] = true
  2359. }
  2360. }
  2361. return arp, stale
  2362. }
  2363. // ParseIPNeighDevs devuelve MAC -> interfaz de `ip neigh show` (#1485). Solo
  2364. // entradas confirmadas, con la misma regla que ParseIPNeigh: una entrada STALE
  2365. // no prueba presencia y su interfaz tampoco sirve para atribuir el lado WAN.
  2366. func ParseIPNeighDevs(out string) map[string]string {
  2367. devs := map[string]string{}
  2368. for _, line := range strings.Split(out, "\n") {
  2369. f := strings.Fields(line)
  2370. if len(f) < 6 || net.ParseIP(f[0]) == nil {
  2371. continue
  2372. }
  2373. var mac, dev string
  2374. for i := 1; i+1 < len(f); i++ {
  2375. switch f[i] {
  2376. case "lladdr":
  2377. mac = strings.ToUpper(f[i+1])
  2378. case "dev":
  2379. dev = f[i+1]
  2380. }
  2381. }
  2382. if mac == "" || mac == "00:00:00:00:00:00" || dev == "" {
  2383. continue
  2384. }
  2385. if !neighConfirmed[f[len(f)-1]] {
  2386. continue
  2387. }
  2388. devs[mac] = dev
  2389. }
  2390. return devs
  2391. }
  2392. // ParseIPNeighDevsAll devuelve MAC -> interfaz de `ip neigh show` sin mirar el
  2393. // estado (#2109). ParseIPNeighDevs solo devuelve confirmadas porque su uso es
  2394. // atribuir el lado WAN; el recheck de vecinos necesita la interfaz de una
  2395. // entrada STALE para poder mandarle un echo a una link-local.
  2396. func ParseIPNeighDevsAll(out string) map[string]string {
  2397. devs := map[string]string{}
  2398. for _, line := range strings.Split(out, "\n") {
  2399. f := strings.Fields(line)
  2400. if len(f) < 6 || net.ParseIP(f[0]) == nil {
  2401. continue
  2402. }
  2403. var mac, dev string
  2404. for i := 1; i+1 < len(f); i++ {
  2405. switch f[i] {
  2406. case "lladdr":
  2407. mac = strings.ToUpper(f[i+1])
  2408. case "dev":
  2409. dev = f[i+1]
  2410. }
  2411. }
  2412. if mac == "" || mac == "00:00:00:00:00:00" || dev == "" {
  2413. continue
  2414. }
  2415. devs[mac] = dev
  2416. }
  2417. return devs
  2418. }
  2419. // ParseArpDevs devuelve MAC -> interfaz de /proc/net/arp (#1485), con el mismo
  2420. // filtro de entradas incompletas que ParseArp. Es el fallback cuando el equipo
  2421. // no tiene `ip`.
  2422. func ParseArpDevs(out string) map[string]string {
  2423. devs := map[string]string{}
  2424. for _, line := range strings.Split(out, "\n") {
  2425. f := strings.Fields(line)
  2426. if len(f) < 6 || f[0] == "IP" {
  2427. continue
  2428. }
  2429. mac := strings.ToUpper(f[3])
  2430. if mac == "" || mac == "00:00:00:00:00:00" || f[2] == "0x0" || net.ParseIP(f[0]) == nil {
  2431. continue
  2432. }
  2433. devs[mac] = f[5]
  2434. }
  2435. return devs
  2436. }
  2437. // sumProcRSS returns the total VmRSS (bytes) of every user-space process
  2438. // (/proc/<pid>/status): the memory actually held by processes, excluding the
  2439. // kernel page cache that inflates (total-available) on ubifs/overlay routers.
  2440. func sumProcRSS() float64 {
  2441. entries, err := os.ReadDir("/proc")
  2442. if err != nil {
  2443. return 0
  2444. }
  2445. var total float64
  2446. for _, e := range entries {
  2447. if !allDigits(e.Name()) {
  2448. continue
  2449. }
  2450. b, err := os.ReadFile("/proc/" + e.Name() + "/status")
  2451. if err != nil {
  2452. continue
  2453. }
  2454. for _, line := range strings.Split(string(b), "\n") {
  2455. if !strings.HasPrefix(line, "VmRSS:") {
  2456. continue
  2457. }
  2458. f := strings.Fields(line)
  2459. if len(f) >= 2 {
  2460. if v, err := strconv.ParseFloat(f[1], 64); err == nil {
  2461. total += v * 1024
  2462. }
  2463. }
  2464. break
  2465. }
  2466. }
  2467. return total
  2468. }
  2469. func allDigits(s string) bool {
  2470. for _, r := range s {
  2471. if r < '0' || r > '9' {
  2472. return false
  2473. }
  2474. }
  2475. return s != ""
  2476. }
  2477. // ParseUciBridgeVlans reads the bridge VLANs out of `uci show network`.
  2478. //
  2479. // `bridge vlan show` is the truth, but its binary is part of an optional
  2480. // package and plenty of routers do not carry it — including ones with VLANs
  2481. // configured, where the panel then shows nothing at all. The declared
  2482. // configuration is the next best answer: it is what the router was told to
  2483. // do, and on a healthy box it is what the kernel is doing.
  2484. //
  2485. // A bridge-vlan section names a device, a VLAN id and its ports, each port
  2486. // written "<port>[:u|:t][*]": ":t" tagged, ":u" untagged, a trailing "*"
  2487. // marking the port's own ingress VLAN.
  2488. func ParseUciBridgeVlans(out string) []VlanPort {
  2489. type section struct {
  2490. vlan int
  2491. ports []string
  2492. }
  2493. sections := map[string]*section{}
  2494. order := []string{}
  2495. for _, line := range strings.Split(out, "\n") {
  2496. line = strings.TrimSpace(line)
  2497. if !strings.HasPrefix(line, "network.") {
  2498. continue
  2499. }
  2500. key, val, ok := strings.Cut(strings.TrimPrefix(line, "network."), "=")
  2501. if !ok {
  2502. continue
  2503. }
  2504. val = strings.Trim(val, "'")
  2505. name, attr, isAttr := strings.Cut(key, ".")
  2506. if !isAttr {
  2507. if val == "bridge-vlan" {
  2508. if _, seen := sections[name]; !seen {
  2509. sections[name] = &section{}
  2510. order = append(order, name)
  2511. }
  2512. }
  2513. continue
  2514. }
  2515. sec, ok := sections[name]
  2516. if !ok {
  2517. continue
  2518. }
  2519. switch attr {
  2520. case "vlan":
  2521. if id, err := strconv.Atoi(val); err == nil {
  2522. sec.vlan = id
  2523. }
  2524. case "ports":
  2525. // A list option prints all its values on one line, each in
  2526. // its own quotes.
  2527. for _, part := range strings.Split(val, "' '") {
  2528. if p := strings.TrimSpace(strings.Trim(part, "'")); p != "" {
  2529. sec.ports = append(sec.ports, p)
  2530. }
  2531. }
  2532. }
  2533. }
  2534. // Group by port, the way `bridge vlan show` reports it: the panel is a
  2535. // list of ports, each with the VLANs it carries.
  2536. byPort := map[string][]VlanEntry{}
  2537. portOrder := []string{}
  2538. for _, name := range order {
  2539. sec := sections[name]
  2540. if sec.vlan < 1 || sec.vlan > 4094 {
  2541. continue
  2542. }
  2543. for _, raw := range sec.ports {
  2544. port, entry := parseUciVlanPort(raw, sec.vlan)
  2545. if port == "" {
  2546. continue
  2547. }
  2548. if _, seen := byPort[port]; !seen {
  2549. portOrder = append(portOrder, port)
  2550. }
  2551. byPort[port] = append(byPort[port], entry)
  2552. }
  2553. }
  2554. out2 := make([]VlanPort, 0, len(portOrder))
  2555. for _, port := range portOrder {
  2556. out2 = append(out2, VlanPort{Port: port, Vlans: byPort[port]})
  2557. }
  2558. return out2
  2559. }
  2560. // parseUciVlanPort splits one "<port>[:u|:t][*]" entry.
  2561. func parseUciVlanPort(raw string, vlan int) (string, VlanEntry) {
  2562. name := raw
  2563. entry := VlanEntry{ID: vlan}
  2564. if strings.HasSuffix(name, "*") {
  2565. entry.PVID = true
  2566. name = strings.TrimSuffix(name, "*")
  2567. }
  2568. switch {
  2569. case strings.HasSuffix(name, ":t"):
  2570. entry.Tagged = true
  2571. name = strings.TrimSuffix(name, ":t")
  2572. case strings.HasSuffix(name, ":u"):
  2573. name = strings.TrimSuffix(name, ":u")
  2574. }
  2575. return name, entry
  2576. }