probe.go 94 KB

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