probe.go 91 KB

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