probe.go 93 KB

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