probe_test.go 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904
  1. // probe_test.go — parsers sobre fixtures de salidas reales (los MISMOS
  2. // fixtures que internal/adapters/adapters_test.go del servidor: al compartir
  3. // package, estos tests son el test cruzado agente↔servidor) + Build del
  4. // prober local con runner fake.
  5. package probe
  6. import (
  7. "context"
  8. "encoding/json"
  9. "strings"
  10. "testing"
  11. "time"
  12. )
  13. func TestParseProcStat(t *testing.T) {
  14. s, err := ParseProcStat("cpu 4705 356 584 3699 23 0 23 0 0 0\n")
  15. if err != nil {
  16. t.Fatal(err)
  17. }
  18. idle := float64(3699 + 23)
  19. total := idle + float64(4705+356+584+0+23)
  20. if s.Total != total || s.IdleAll != idle {
  21. t.Fatalf("procstat: %+v", s)
  22. }
  23. // Delta → porcentaje
  24. prev := CPUSample{Total: 1000, IdleAll: 500}
  25. cur := CPUSample{Total: 2000, IdleAll: 750}
  26. pct := CPUPercent(prev, cur)
  27. if pct == nil || *pct != 75 {
  28. t.Fatalf("cpu%%: %v", pct)
  29. }
  30. if CPUPercent(cur, prev) != nil {
  31. t.Fatal("contadores reseteados → nil")
  32. }
  33. if _, err := ParseProcStat("basura"); err == nil {
  34. t.Fatal("procstat basura debería dar error")
  35. }
  36. }
  37. func TestParseTempC(t *testing.T) {
  38. if v := ParseTempC("43500\n"); v == nil || *v != 44 {
  39. t.Fatalf("temp: %v", v)
  40. }
  41. if ParseTempC("") != nil || ParseTempC("nan") != nil {
  42. t.Fatal("temp inválida → nil")
  43. }
  44. // #1947: una zona sin sensor declara 0 y el valor llegaba a la UI como
  45. // lectura real (0 C / 32 F plana en el WNDR3700v2).
  46. if v := ParseTempC("0"); v != nil {
  47. t.Fatalf("temp 0 → nil, got %d", *v)
  48. }
  49. if v := ParseTempC("300"); v != nil {
  50. t.Fatalf("temp que redondea a 0 → nil, got %d", *v)
  51. }
  52. if v := ParseTempC("-5000"); v == nil || *v != -5 {
  53. t.Fatalf("temp negativa real: %v", v)
  54. }
  55. }
  56. func TestParseNetDevYBps(t *testing.T) {
  57. out := " eth0: 1000000 0 0 0 0 0 0 0 500000 0\n" +
  58. " lo: 9999999 0 0 0 0 0 0 0 8888888 0\n" +
  59. "br-lan: 7000000 0 0 0 0 0 0 0 6000000 0\n" +
  60. " lan1: 2000000 0 0 0 0 0 0 0 1000000 0\n"
  61. rx, tx := ParseNetDev(out)
  62. if rx != 3000000 || tx != 1500000 { // lo, br-lan excluidos
  63. t.Fatalf("netdev: %v/%v", rx, tx)
  64. }
  65. rxBps, txBps := NetDevBps(1000, 2000, 3000, 6000, 2)
  66. if rxBps == nil || *rxBps != 8000 || txBps == nil || *txBps != 16000 {
  67. t.Fatalf("bps: %v/%v", rxBps, txBps)
  68. }
  69. if a, b := NetDevBps(0, 0, 0, 0, 0); a != nil || b != nil {
  70. t.Fatal("dt=0 → nil")
  71. }
  72. }
  73. func TestParseNetDevIfaces(t *testing.T) {
  74. out := " eth0: 1000000 5 2 0 0 0 0 0 500000 7 1 0 0 0 0 0\n" +
  75. " lan1: 2000000 9 0 0 0 0 0 0 1000000 4 3 0 0 0 0 0\n" +
  76. "basura sin formato\n"
  77. ifaces := ParseNetDevIfaces(out)
  78. if len(ifaces) != 2 {
  79. t.Fatalf("ifaces: %+v", ifaces)
  80. }
  81. e, ok := ifaces["eth0"]
  82. if !ok || e.Rx != 1000000 || e.Tx != 500000 || e.RxErr != 2 || e.TxErr != 1 {
  83. t.Fatalf("eth0: %+v", e)
  84. }
  85. l, ok := ifaces["lan1"]
  86. if !ok || l.RxErr != 0 || l.TxErr != 3 {
  87. t.Fatalf("lan1: %+v", l)
  88. }
  89. if ParseNetDevIfaces("") == nil {
  90. t.Fatal("vacío → mapa no nil")
  91. }
  92. }
  93. func TestIfRates(t *testing.T) {
  94. prev := map[string]IfCounters{"lan1": {Rx: 1000, Tx: 2000}, "wan": {Rx: 500, Tx: 500}}
  95. cur := map[string]IfCounters{"lan1": {Rx: 3000, Tx: 6000}, "wan": {Rx: 400, Tx: 900}, "lan2": {Rx: 10, Tx: 10}}
  96. rates := IfRates(prev, cur, 2)
  97. if len(rates) != 3 {
  98. t.Fatalf("rates: %+v", rates)
  99. }
  100. l1 := rates["lan1"]
  101. if l1.RxBps == nil || *l1.RxBps != 8000 || l1.TxBps == nil || *l1.TxBps != 16000 {
  102. t.Fatalf("lan1 rates: %+v", l1)
  103. }
  104. // Contador reseteado (cur < prev) → 0, no negativo
  105. w := rates["wan"]
  106. if w.RxBps == nil || *w.RxBps != 0 || w.TxBps == nil || *w.TxBps != 1600 {
  107. t.Fatalf("wan reset: %+v", w)
  108. }
  109. // Iface nueva sin previa → sin rate
  110. if rates["lan2"].RxBps != nil || rates["lan2"].TxBps != nil {
  111. t.Fatalf("lan2 nueva: %+v", rates["lan2"])
  112. }
  113. // dt <= 0 → todo sin rate
  114. rates = IfRates(prev, cur, 0)
  115. if rates["lan1"].RxBps != nil {
  116. t.Fatal("dt=0 → nil rates")
  117. }
  118. }
  119. func TestBuildEthPortsConIfaces(t *testing.T) {
  120. layout := []PortLayout{{ID: "lan1", Name: "lan1", Label: "LAN 1", Role: "lan"}}
  121. states := []PortState{{Name: "lan1", Up: true, Speed: "1 Gbps"}}
  122. rxb, txb := 40e6, 12e6
  123. ifaces := map[string]IfRate{
  124. "lan1": {IfCounters: IfCounters{Rx: 1000, Tx: 2000, RxErr: 3}, RxBps: &rxb, TxBps: &txb},
  125. "wlan0": {IfCounters: IfCounters{Rx: 99}}, // no es boca: se ignora
  126. }
  127. ports := BuildEthPorts(layout, states, nil, ifaces, "")
  128. if len(ports) != 1 {
  129. t.Fatalf("ports: %+v", ports)
  130. }
  131. p := ports[0]
  132. if p.Iface != "lan1" || p.RxBytes != 1000 || p.TxBytes != 2000 || p.RxErrs != 3 {
  133. t.Fatalf("stats: %+v", p)
  134. }
  135. if p.RxBps == nil || *p.RxBps != rxb || p.TxBps == nil || *p.TxBps != txb {
  136. t.Fatalf("rates: %+v", p)
  137. }
  138. // Fallback (sin layout) también enriquece
  139. ports = BuildEthPorts(nil, []PortState{{Name: "lan1", Up: true, Speed: "1 Gbps"}}, nil, ifaces, "")
  140. if len(ports) != 1 || ports[0].Iface != "lan1" || ports[0].RxBytes != 1000 {
  141. t.Fatalf("fallback stats: %+v", ports)
  142. }
  143. }
  144. // TestFmtSpeedMbps (#847): 2500 debe ser "2.5 Gbps", no truncar a "2 Gbps".
  145. func TestFmtSpeedMbps(t *testing.T) {
  146. cases := map[int]string{
  147. 10: "10 Mbps",
  148. 100: "100 Mbps",
  149. 1000: "1 Gbps",
  150. 2500: "2.5 Gbps",
  151. 5000: "5 Gbps",
  152. 10000: "10 Gbps",
  153. }
  154. for mbps, want := range cases {
  155. if got := fmtSpeedMbps(mbps); got != want {
  156. t.Errorf("fmtSpeedMbps(%d) = %q, want %q", mbps, got, want)
  157. }
  158. }
  159. }
  160. // TestParsePortStatesDSA (#847): el 4º campo marca el conduit DSA.
  161. func TestParsePortStatesDSA(t *testing.T) {
  162. states := ParsePortStates("eth1 up 2500 dsa\nlan1 up 1000 -\nsfp-wan up 2500\n")
  163. if len(states) != 3 {
  164. t.Fatalf("states: %+v", states)
  165. }
  166. if !states[0].DSA || states[0].Speed != "2.5 Gbps" {
  167. t.Fatalf("conduit eth1: %+v", states[0])
  168. }
  169. if states[1].DSA {
  170. t.Fatalf("lan1 no es conduit: %+v", states[1])
  171. }
  172. if states[2].DSA {
  173. t.Fatalf("línea sin 4º campo no es conduit: %+v", states[2])
  174. }
  175. }
  176. // TestBuildEthPortsSkipsDsaConduit (#847): los conduits DSA se excluyen del
  177. // panel aunque figuren en /sys (su velocidad interna no es una boca usable).
  178. func TestBuildEthPortsSkipsDsaConduit(t *testing.T) {
  179. states := []PortState{
  180. {Name: "lan1", Up: true, Speed: "1 Gbps"},
  181. {Name: "eth1", Up: true, Speed: "150 Mbps", DSA: true},
  182. }
  183. ports := BuildEthPorts(nil, states, nil, nil, "")
  184. if len(ports) != 1 || ports[0].ID != "lan1" {
  185. t.Fatalf("el conduit DSA debe excluirse: %+v", ports)
  186. }
  187. }
  188. func TestParsePingSummary(t *testing.T) {
  189. out := "3 packets transmitted, 3 received, 0% packet loss, time 2003ms\nrtt min/avg/max/mdev = 8.123/9.456/10.999/0.5 ms"
  190. lat, loss := ParsePingSummary(out)
  191. if lat == nil || *lat != 9.456 || loss == nil || *loss != 0 {
  192. t.Fatalf("ping: %v %v", lat, loss)
  193. }
  194. // #1281: busybox (OpenWrt) imprime min/avg/max SIN mdev.
  195. if lat, _ := ParsePingSummary("3 packets transmitted, 3 packets received, 0% packet loss\nround-trip min/avg/max = 6.196/6.326/6.527 ms"); lat == nil || *lat != 6.326 {
  196. t.Errorf("busybox rtt: lat = %v, want 6.326", lat)
  197. }
  198. if lat, loss := ParsePingSummary("round-trip min/avg/max = 10.5/20.4/30.6 ms\n3 packets transmitted, 3 received, 50% packet loss"); lat == nil || *lat != 20.4 || loss == nil || *loss != 50 {
  199. t.Errorf("busybox rtt+loss: lat=%v loss=%v", lat, loss)
  200. }
  201. // #1384: sub-ms LAN ping must survive (0.4 ms, antes redondeado a 0).
  202. if lat, _ := ParsePingSummary("round-trip min/avg/max = 0.3/0.4/0.6 ms"); lat == nil || *lat != 0.4 {
  203. t.Errorf("sub-ms rtt: lat = %v, want 0.4", lat)
  204. }
  205. if lat, _ := ParsePingSummary("2 packets transmitted, 0 received, 100% packet loss"); lat != nil {
  206. t.Fatalf("sin rtt → nil: %v", lat)
  207. }
  208. }
  209. func TestParseDhcp(t *testing.T) {
  210. out := "2000000000 aa:bb:cc:dd:ee:ff 192.168.8.21 imac-de-marc 01:aa:bb:cc:dd:ee:ff\n" +
  211. "2000000001 11:22:33:44:55:66 192.168.8.34 * *\n"
  212. leases := ParseDhcpLeasesFile(out)
  213. if len(leases) != 2 || leases[0].MAC != "AA:BB:CC:DD:EE:FF" || leases[0].Hostname != "imac-de-marc" || leases[1].Hostname != "" {
  214. t.Fatalf("leases: %+v", leases)
  215. }
  216. if leases[0].LeaseExpiresAt == nil || *leases[0].LeaseExpiresAt != 2000000000 {
  217. t.Fatalf("lease expiry: %+v", leases[0].LeaseExpiresAt)
  218. }
  219. ubus := `{"lease":[{"mac":"aa:bb:cc:dd:ee:ff","ip":"192.168.8.21","hostname":"imac","expires":12345}]}`
  220. leases, err := ParseDhcpUbus([]byte(ubus))
  221. if err != nil || len(leases) != 1 || leases[0].IP != "192.168.8.21" || leases[0].LeaseExpiresAt == nil || *leases[0].LeaseExpiresAt != 12345 {
  222. t.Fatalf("ubus dhcp: %v %+v", err, leases)
  223. }
  224. if _, err := ParseDhcpUbus([]byte("Command failed")); err == nil {
  225. t.Fatal("ubus roto debería dar error")
  226. }
  227. }
  228. func TestParseGlClients(t *testing.T) {
  229. // Formato real del Flint2: map mac -> objeto con mac/ip/name/online.
  230. raw := `{"clients":{
  231. "AA:BB:CC:DD:EE:FF":{"mac":"aa:bb:cc:dd:ee:ff","ip":"192.168.8.21","name":"imac","online":true},
  232. "11:22:33:44:55:66":{"mac":"11:22:33:44:55:66","ip":"192.168.8.34","name":"","online":true},
  233. "22:33:44:55:66:77":{"mac":"22:33:44:55:66:77","ip":"192.168.8.40","name":"viejo","online":false},
  234. "33:44:55:66:77:88":{"mac":"33:44:55:66:77:88","ip":"","name":"sinip","online":true}
  235. }}`
  236. leases, err := ParseGlClients([]byte(raw))
  237. if err != nil {
  238. t.Fatalf("parse: %v", err)
  239. }
  240. // Solo deben quedar los ONLINE con IP (2 de 4), ordenados por MAC.
  241. if len(leases) != 2 {
  242. t.Fatalf("esperadas 2, %d: %+v", len(leases), leases)
  243. }
  244. if leases[0].MAC != "11:22:33:44:55:66" || leases[0].IP != "192.168.8.34" {
  245. t.Fatalf("primera %+v", leases[0])
  246. }
  247. if leases[1].MAC != "AA:BB:CC:DD:EE:FF" || leases[1].IP != "192.168.8.21" || leases[1].Hostname != "imac" {
  248. t.Fatalf("segunda %+v", leases[1])
  249. }
  250. // Salida vacía / JSON roto no deben dar entradas.
  251. if got, err := ParseGlClients([]byte("")); err == nil && len(got) != 0 {
  252. t.Fatalf("vacío: %+v", got)
  253. }
  254. if _, err := ParseGlClients([]byte("not json")); err == nil {
  255. t.Fatal("JSON roto debería dar error")
  256. }
  257. }
  258. func TestParseGlClientsHyphenatedMACs(t *testing.T) {
  259. // La caché de gl-clients puede emitir MAC con guiones (#1145): deben salir
  260. // en forma canónica, también cuando solo la clave del mapa trae la MAC.
  261. raw := `{"clients":{
  262. "AA-BB-CC-DD-EE-01":{"mac":"aa-bb-cc-dd-ee-01","ip":"192.168.8.21","name":"uno","online":true},
  263. "aa-bb-cc-dd-ee-02":{"mac":"","ip":"192.168.8.22","name":"dos","online":true},
  264. "basura":{"mac":"tampoco","ip":"192.168.8.23","name":"tres","online":true}
  265. }}`
  266. leases, err := ParseGlClients([]byte(raw))
  267. if err != nil {
  268. t.Fatalf("parse: %v", err)
  269. }
  270. if len(leases) != 2 {
  271. t.Fatalf("esperaba 2 entradas (la inválida se descarta), obtuve %d: %+v", len(leases), leases)
  272. }
  273. if leases[0].MAC != "AA:BB:CC:DD:EE:01" || leases[0].IP != "192.168.8.21" {
  274. t.Errorf("primera: esperaba AA:BB:CC:DD:EE:01, obtuve %+v", leases[0])
  275. }
  276. if leases[1].MAC != "AA:BB:CC:DD:EE:02" || leases[1].IP != "192.168.8.22" {
  277. t.Errorf("segunda: esperaba AA:BB:CC:DD:EE:02, obtuve %+v", leases[1])
  278. }
  279. }
  280. func TestParseArp(t *testing.T) {
  281. out := "IP address HW type Flags HW address Mask Device\n" +
  282. "192.168.1.10 0x1 0x2 aa:bb:cc:dd:ee:ff * br-lan\n" +
  283. "192.168.1.11 0x1 0x0 11:22:33:44:55:66 * br-lan\n" +
  284. "192.168.1.12 0x1 0x2 00:00:00:00:00:00 * br-lan\n" +
  285. "invalid 0x1 0x2 22:33:44:55:66:77 * br-lan\n"
  286. m := ParseArp(out)
  287. if len(m) != 1 || m["AA:BB:CC:DD:EE:FF"] != "192.168.1.10" {
  288. t.Fatalf("arp: %+v", m)
  289. }
  290. if _, ok := m["11:22:33:44:55:66"]; ok {
  291. t.Fatal("entrada incompleta (0x0) no debe aparecer")
  292. }
  293. if _, ok := m["00:00:00:00:00:00"]; ok {
  294. t.Fatal("MAC nula no debe aparecer")
  295. }
  296. if _, ok := m["22:33:44:55:66:77"]; ok {
  297. t.Fatal("IP inválida no debe aparecer")
  298. }
  299. }
  300. func TestParseWireless(t *testing.T) {
  301. out := "A4:83:E7:21:0B:3C -48 5\nEC:71:DB:44:12:8A -72 2.4\n"
  302. m := ParseWirelessClients(out)
  303. if len(m) != 2 || m["A4:83:E7:21:0B:3C"].Band != "5 GHz" || m["A4:83:E7:21:0B:3C"].SignalDbm != -48 || m["EC:71:DB:44:12:8A"].Band != "2.4 GHz" {
  304. t.Fatalf("wireless: %+v", m)
  305. }
  306. sta := `{"radio0":{"up":true,"interfaces":[{"ifname":"wlan0","config":{"mode":"sta"}}]}}`
  307. wifi, err := ParseWirelessUplink([]byte(sta))
  308. if err != nil || !wifi {
  309. t.Fatalf("sta: %v %v", wifi, err)
  310. }
  311. ap := `{"radio0":{"up":true,"interfaces":[{"ifname":"wlan0","config":{"mode":"ap"}}]}}`
  312. wifi, _ = ParseWirelessUplink([]byte(ap))
  313. if wifi {
  314. t.Fatal("solo AP → cable")
  315. }
  316. }
  317. // TestPortPrettyLabel (#1200): etiquetas del panel de bocas. Los patrones
  318. // clásicos conservan formato; los netdev 25.12+ (sfp-lan/sfp-wan) y las
  319. // bocas sin dígitos (lan en UniFi 6 Lite) muestran su nombre real.
  320. func TestPortPrettyLabel(t *testing.T) {
  321. cases := map[string]string{
  322. "lan1": "LAN 1",
  323. "lan10": "LAN 10",
  324. "lan": "LAN",
  325. "wan": "WAN",
  326. "eth0": "ETH 0",
  327. "sfp0": "SFP 0",
  328. "sfp": "SFP",
  329. "sfp-lan": "sfp-lan",
  330. "sfp-wan": "sfp-wan",
  331. "enp3s0": "enp3s0",
  332. }
  333. for name, want := range cases {
  334. if got := portPrettyLabel(name); got != want {
  335. t.Errorf("portPrettyLabel(%q) = %q, want %q", name, got, want)
  336. }
  337. }
  338. }
  339. // TestBuildEthPortsNetdevNames (#1200): BPI-R4 con nombres openwrt,netdev-name
  340. // (25.12+). En board.json, sfp-lan es miembro de lan; sfp-wan no está y llega
  341. // por extras. Antes: "sfp-LAN " (Replace a ciegas) y "SFP -wan" (sufijo
  342. // partido). Ahora: el nombre real de la interfaz.
  343. func TestBuildEthPortsNetdevNames(t *testing.T) {
  344. board := `{"network":{"lan":{"ports":["lan1","lan2","lan3","sfp-lan"],"device":"br-lan"},"wan":{"device":""}}}`
  345. layout, err := ParsePortLayout(board)
  346. if err != nil {
  347. t.Fatalf("layout: %v", err)
  348. }
  349. labels := map[string]string{}
  350. for _, p := range layout {
  351. labels[p.ID] = p.Label
  352. }
  353. if labels["sfp-lan"] != "sfp-lan" {
  354. t.Fatalf("sfp-lan en layout: %q", labels["sfp-lan"])
  355. }
  356. if labels["lan1"] != "LAN 1" {
  357. t.Fatalf("lan1 en layout: %q", labels["lan1"])
  358. }
  359. states := ParsePortStates("lan1 up 1000\nlan2 down -1\nlan3 down -1\nsfp-lan up 10000\nsfp-wan up 2500\neth1 up 100\n")
  360. ports := BuildEthPorts(layout, states, nil, nil, "")
  361. got := map[string]string{}
  362. for _, p := range ports {
  363. got[p.ID] = p.Label
  364. }
  365. if got["sfp-lan"] != "sfp-lan" {
  366. t.Errorf("sfp-lan: %q", got["sfp-lan"])
  367. }
  368. if got["sfp-wan"] != "sfp-wan" {
  369. t.Errorf("sfp-wan: %q", got["sfp-wan"])
  370. }
  371. }
  372. // TestBuildEthPortsBareLan (#1200): UniFi 6 Lite, la boca se llama "lan" a
  373. // secas. Antes el panel salía vacío (0 de 0): ^lan\d+$ no la cogía y phyRe
  374. // (^lan\d+$) la excluía de extras.
  375. func TestBuildEthPortsBareLan(t *testing.T) {
  376. ports := BuildEthPorts(nil, ParsePortStates("lan up 1000\n"), nil, nil, "")
  377. if len(ports) != 1 || ports[0].ID != "lan" || ports[0].Label != "LAN" || !ports[0].Up {
  378. t.Fatalf("boca lan a secas: %+v", ports)
  379. }
  380. }
  381. func TestParsePortsYLayout(t *testing.T) {
  382. // La boca WAN aparece en /sys aunque esté esclavizada al bridge: sin ella
  383. // en los estados sería un device que no existe y BuildEthPorts la
  384. // descartaría (ver TestBuildEthPortsUplinkNoEthernet).
  385. states := ParsePortStates("eth0 up 2500\nlan1 up 1000\nlan2 down -1\nwlan0 up 0\nwan up 1000\n")
  386. if len(states) != 5 || states[0].Speed != "2.5 Gbps" || states[2].Up || states[2].Speed != "—" {
  387. t.Fatalf("states: %+v", states)
  388. }
  389. board := `{"network":{"lan":{"ports":["lan1","lan2","lan3","lan4"],"device":"br-lan"},"wan":{"device":"wan","protocol":"dhcp"}}}`
  390. layout, err := ParsePortLayout(board)
  391. if err != nil || len(layout) != 5 || layout[0].ID != "wan" || layout[1].Label != "LAN 1" {
  392. t.Fatalf("layout: %v %+v", err, layout)
  393. }
  394. // AP en bridge: wan en br-lan → se re-etiqueta LAN 5 y va al final del
  395. // chasis (#2181: el layout la trae delante porque la WAN suele ir a la
  396. // izquierda; puenteada, el panel lee LAN 1..LAN 4, LAN 5).
  397. ports := BuildEthPorts(layout, states, map[string]bool{"wan": true}, nil, "")
  398. if len(ports) != 6 || ports[4].Label != "LAN 5" || ports[4].ID == "wan" {
  399. t.Fatalf("ethports bridge: %+v", ports)
  400. }
  401. foundBridge := map[string]bool{}
  402. for _, p := range ports {
  403. foundBridge[p.ID] = true
  404. }
  405. if !foundBridge["eth0"] {
  406. t.Fatalf("ethports bridge sin eth0 extra: %+v", ports)
  407. }
  408. // Sin layout: fallback heurístico + interfaces físicas no cubiertas (#413/#416)
  409. ports = BuildEthPorts(nil, ParsePortStates("lan2 up 1000\nlan10 up 100\nwan down -1\neth0 up 2500\n"), nil, nil, "")
  410. fallbackIDs := map[string]int{}
  411. for i, p := range ports {
  412. fallbackIDs[p.ID] = i
  413. }
  414. if len(fallbackIDs) != 4 {
  415. t.Fatalf("ethports fallback count: %+v", ports)
  416. }
  417. for _, id := range []string{"wan", "lan2", "lan10", "eth0"} {
  418. if _, ok := fallbackIDs[id]; !ok {
  419. t.Fatalf("falta puerto %s: %+v", id, ports)
  420. }
  421. }
  422. if fallbackIDs["wan"] != 0 {
  423. t.Fatalf("wan no es el primero: %+v", ports)
  424. }
  425. // Con layout: eth0 no está en board.json pero sí en /sys → se añade al final.
  426. ports = BuildEthPorts(layout, []PortState{
  427. {Name: "wan", Up: true, Speed: "1 Gbps"},
  428. {Name: "lan1", Up: true, Speed: "1 Gbps"},
  429. {Name: "lan2", Up: true, Speed: "1 Gbps"},
  430. {Name: "lan3", Up: true, Speed: "1 Gbps"},
  431. {Name: "lan4", Up: true, Speed: "1 Gbps"},
  432. {Name: "eth0", Up: true, Speed: "2.5 Gbps"},
  433. {Name: "sfp0", Up: true, Speed: "10 Gbps"},
  434. }, nil, nil, "")
  435. if len(ports) != 7 {
  436. t.Fatalf("layout + extras: %d ports, %+v", len(ports), ports)
  437. }
  438. found := map[string]bool{}
  439. for _, p := range ports {
  440. found[p.ID] = true
  441. }
  442. for _, id := range []string{"wan", "lan1", "lan2", "lan3", "lan4", "eth0", "sfp0"} {
  443. if !found[id] {
  444. t.Fatalf("falta puerto %s: %+v", id, ports)
  445. }
  446. }
  447. }
  448. func TestParseFdbYRadios(t *testing.T) {
  449. fdb := ParseBridgeFdb("==PORTS==\n0x1 lan1\n0x2 lan2\n==MACS==\n1 aa:bb:cc:dd:ee:ff\n2 11:22:33:44:55:66\n")
  450. if len(fdb) != 2 || fdb["AA:BB:CC:DD:EE:FF"] != "lan1" || fdb["11:22:33:44:55:66"] != "lan2" {
  451. t.Fatalf("fdb: %+v", fdb)
  452. }
  453. radios := ParseRadios("2.4|6|HT20|20|3\n5|36|HT80|23|7\n")
  454. if len(radios) != 2 || radios[0].Name != "2.4 GHz" || radios[0].Clients != 3 || radios[1].WidthMhz != 80 || radios[1].PowerDbm != 23 {
  455. t.Fatalf("radios: %+v", radios)
  456. }
  457. }
  458. // TestParseRadiosNoiseBssid (#1213): el formato nuevo lleva BSSID y ruido de
  459. // iwinfo; el histórico de 5 campos sigue parseando (sin ruido, sin BSSID).
  460. func TestParseRadiosNoiseBssid(t *testing.T) {
  461. radios := ParseRadios("2.4|6|HT20|20|aa:bb:cc:00:00:01|-96|3\n5|36|HT80|23|aa:bb:cc:00:00:02|-91|7\n")
  462. if len(radios) != 2 {
  463. t.Fatalf("radios: %+v", radios)
  464. }
  465. if radios[0].NoiseDbm == nil || *radios[0].NoiseDbm != -96 {
  466. t.Fatalf("ruido 2.4: %+v", radios[0])
  467. }
  468. if radios[0].BSSID != "AA:BB:CC:00:00:01" {
  469. t.Fatalf("bssid 2.4: %+v", radios[0])
  470. }
  471. if radios[1].NoiseDbm == nil || *radios[1].NoiseDbm != -91 || radios[1].Clients != 7 {
  472. t.Fatalf("radio 5: %+v", radios[1])
  473. }
  474. // driver sin ruido ("unknown" → campo vacío) y formato viejo
  475. old := ParseRadios("5|36|HT80|23|aa:bb:cc:00:00:02||7\n")
  476. if len(old) != 1 || old[0].NoiseDbm != nil || old[0].Clients != 7 {
  477. t.Fatalf("radio 5 sin ruido: %+v", old)
  478. }
  479. legacy := ParseRadios("5|36|HT80|23|7\n")
  480. if len(legacy) != 1 || legacy[0].NoiseDbm != nil || legacy[0].BSSID != "" || legacy[0].Clients != 7 {
  481. t.Fatalf("formato viejo: %+v", legacy)
  482. }
  483. }
  484. // TestParseFdbBridgeFdb — #253: formato `bridge fdb show` (puerto por nombre,
  485. // p. ej. eth0/eth1 en GLuON) y puertos ethernet fuera de lanN/wan.
  486. func TestParseFdbBridgeFdb(t *testing.T) {
  487. // bridge fdb show emite "dev <ifname> <mac>" → CmdBridgeFDB lo convierte a
  488. // "<ifname> <mac>"; el parser debe casar por nombre contra ==PORTS==.
  489. fdb := ParseBridgeFdb("==PORTS==\n0x1 eth0\n0x2 eth1\n0x3 lan1\n==MACS==\neth0 aa:bb:cc:dd:ee:01\neth1 bb:cc:dd:ee:ff:02\nlan1 cc:dd:ee:ff:00:03\n")
  490. if len(fdb) != 3 {
  491. t.Fatalf("bridge fdb: esperaba 3 MACs, tengo %+v", fdb)
  492. }
  493. if fdb["AA:BB:CC:DD:EE:01"] != "eth0" || fdb["BB:CC:DD:EE:FF:02"] != "eth1" {
  494. t.Fatalf("bridge fdb eth*: %+v", fdb)
  495. }
  496. if fdb["CC:DD:EE:FF:00:03"] != "lan1" {
  497. t.Fatalf("bridge fdb lan1: %+v", fdb)
  498. }
  499. }
  500. // TestParseBridgeFdbSplit — las MACs aprendidas en puertos del lado
  501. // inalámbrico no son clientes cableados, pero tampoco deben tirarse: el
  502. // hint WirelessSide es lo único que evita que el server las reclasifique
  503. // como cableadas vía el FDB de tránsito del gateway (#rotMAC).
  504. func TestParseBridgeFdbSplit(t *testing.T) {
  505. wired, ws := ParseBridgeFdbSplit("==PORTS==\n0x1 eth0\n0x5 wl0.1\n0x6 wlan0\n0x8 phy0-ap0\n0x9 veth1\n==MACS==\n1 aa:bb:cc:dd:ee:01\n5 12:7c:61:8f:37:ec\n6 bb:bb:bb:bb:bb:01\n8 cc:cc:cc:cc:cc:01\n9 dd:dd:dd:dd:dd:01\n")
  506. if len(wired) != 1 || wired["AA:BB:CC:DD:EE:01"] != "eth0" {
  507. t.Fatalf("wired: %+v", wired)
  508. }
  509. if len(ws) != 3 {
  510. t.Fatalf("wireless-side: %+v", ws)
  511. }
  512. if ws["12:7C:61:8F:37:EC"] != "wl0.1" || ws["BB:BB:BB:BB:BB:01"] != "wlan0" || ws["CC:CC:CC:CC:CC:01"] != "phy0-ap0" {
  513. t.Fatalf("wireless-side puertos: %+v", ws)
  514. }
  515. if _, ok := ws["DD:DD:DD:DD:DD:01"]; ok {
  516. t.Fatalf("veth no es lado inalámbrico: %+v", ws)
  517. }
  518. }
  519. // TestCmdBridgeFdbSinBuiltinCommand — el ash de busybox en Merlin/Asuswrt no
  520. // tiene el builtin `command`: con la guarda antigua `if command -v brctl` el
  521. // test fallaba en esos equipos con "sh: command: not found" y la sección MACS
  522. // salía vacía (el FDB del AP entero desaparecía del server). La sonda debe
  523. // probar brctl y bridge sin depender de builtins opcionales.
  524. func TestCmdBridgeFdbSinBuiltinCommand(t *testing.T) {
  525. if strings.Contains(CmdBridgeFDB, "command -v") {
  526. t.Fatalf("CmdBridgeFDB depende del builtin `command`, ausente en ash de Merlin: %s", CmdBridgeFDB)
  527. }
  528. if !strings.Contains(CmdBridgeFDB, "brctl showmacs") || !strings.Contains(CmdBridgeFDB, "bridge fdb show") {
  529. t.Fatalf("CmdBridgeFDB debe probar brctl y bridge fdb: %s", CmdBridgeFDB)
  530. }
  531. }
  532. // TestParseFdbExcluyeWireless — #253: los puertos inalámbricos (phy*-ap*,
  533. // wlan*, bat*) no deben entrar como clientes cableados.
  534. func TestParseLuCILabels(t *testing.T) {
  535. out := `config switchvlan 'port_labels'
  536. option lan1 'Router/Fritzbox'
  537. option lan2 'Garage door'
  538. config switchvlan 'vlan_labels'
  539. option 1 'LAN'
  540. option 2 'WAN'
  541. config language 'main'
  542. option lang 'es'
  543. `
  544. labels := ParseLuCILabels(out)
  545. if labels == nil {
  546. t.Fatal("con etiquetas debería devolver datos")
  547. }
  548. if labels.PortLabels["lan1"] != "Router/Fritzbox" || labels.PortLabels["lan2"] != "Garage door" {
  549. t.Fatalf("port_labels: %+v", labels.PortLabels)
  550. }
  551. if labels.VlanLabels["1"] != "LAN" || labels.VlanLabels["2"] != "WAN" {
  552. t.Fatalf("vlan_labels: %+v", labels.VlanLabels)
  553. }
  554. if ParseLuCILabels("config language 'main'\n\toption lang 'es'\n") != nil {
  555. t.Fatal("sin port_labels/vlan_labels → nil")
  556. }
  557. if ParseLuCILabels("") != nil {
  558. t.Fatal("vacío → nil")
  559. }
  560. }
  561. func TestParseFdbExcluyeWireless(t *testing.T) {
  562. fdb := ParseBridgeFdb("==PORTS==\n0x1 lan1\n0x5 phy0-ap0\n0x6 wl0\n0x7 wl3\n==MACS==\n1 aa:bb:cc:dd:ee:01\n5 ff:ee:dd:cc:bb:aa\n6 12:7c:61:8f:37:ec\n7 12:7c:61:8f:37:e8\n")
  563. if _, ok := fdb["FF:EE:DD:CC:BB:AA"]; ok {
  564. t.Fatalf("phy0-ap0 no debería contar como cableado: %+v", fdb)
  565. }
  566. // Merlin: las MACs propias de cada radio Broadcom (bit LAA volteado) se
  567. // aprenden en wl0..wl3 y no son clientes cableados.
  568. if _, ok := fdb["12:7C:61:8F:37:EC"]; ok {
  569. t.Fatalf("wl0 no debería contar como cableado: %+v", fdb)
  570. }
  571. if _, ok := fdb["12:7C:61:8F:37:E8"]; ok {
  572. t.Fatalf("wl3 no debería contar como cableado: %+v", fdb)
  573. }
  574. if fdb["AA:BB:CC:DD:EE:01"] != "lan1" {
  575. t.Fatalf("lan1 debería seguir: %+v", fdb)
  576. }
  577. }
  578. // TestParseFdbDenylistPuertos — #506: el allowlist histórico descartaba en
  579. // silencio puertos físicos con nombres no enumerados (las jaulas SFP del
  580. // BPI-R4 se llaman sfp-lan/sfp-wan; también "lan" suelto o usb0). El filtro
  581. // invertido conserva cualquier miembro físico del bridge y solo excluye
  582. // wireless (phy*-ap*, wlan*, wl*) y virtuales (br*, lo, veth*, wg*, túneles).
  583. // #1757: la subinterfaz VLAN (lan1.10, eth0.999) SÍ es un puerto cableado —
  584. // es como se llama el puerto del bridge en un router que segmenta con 802.1Q.
  585. func TestParseFdbDenylistPuertos(t *testing.T) {
  586. out := "==PORTS==\n" +
  587. "1 sfp-lan\n2 sfp-wan\n3 eth1\n4 lan\n5 usb0\n6 swp1\n7 enp2s0\n" +
  588. "8 phy0-ap0\n9 phy1-ap1\n10 wlan0\n11 br-lan\n12 br0\n13 lo\n" +
  589. "14 veth0\n15 wg0\n16 tunl0\n17 tap0\n18 pppoe-wan\n19 lan1.10\n20 eth0.999\n" +
  590. "21 bat0\n22 bat0.40\n" +
  591. "==MACS==\n" +
  592. // sfp-lan resuelto por port_no (vía brctl); el resto por nombre.
  593. "1 aa:00:00:00:00:01\n" +
  594. "sfp-wan aa:00:00:00:00:02\neth1 aa:00:00:00:00:03\nlan aa:00:00:00:00:04\n" +
  595. "usb0 aa:00:00:00:00:05\nswp1 aa:00:00:00:00:06\nenp2s0 aa:00:00:00:00:07\n" +
  596. "phy0-ap0 bb:00:00:00:00:01\nphy1-ap1 bb:00:00:00:00:02\nwlan0 bb:00:00:00:00:03\n" +
  597. "br-lan bb:00:00:00:00:04\nbr0 bb:00:00:00:00:05\nlo bb:00:00:00:00:06\nveth0 bb:00:00:00:00:07\n" +
  598. "wg0 bb:00:00:00:00:08\ntunl0 bb:00:00:00:00:09\ntap0 bb:00:00:00:00:0a\n" +
  599. "pppoe-wan bb:00:00:00:00:0b\nlan1.10 bb:00:00:00:00:0c\neth0.999 bb:00:00:00:00:0d\n" +
  600. "bat0 bb:00:00:00:00:0e\nbat0.40 bb:00:00:00:00:0f\n"
  601. fdb := ParseBridgeFdb(out)
  602. want := map[string]string{
  603. "AA:00:00:00:00:01": "sfp-lan",
  604. "AA:00:00:00:00:02": "sfp-wan",
  605. "AA:00:00:00:00:03": "eth1",
  606. "AA:00:00:00:00:04": "lan",
  607. "AA:00:00:00:00:05": "usb0",
  608. "AA:00:00:00:00:06": "swp1",
  609. "AA:00:00:00:00:07": "enp2s0",
  610. "BB:00:00:00:00:0C": "lan1.10",
  611. "BB:00:00:00:00:0D": "eth0.999",
  612. }
  613. if len(fdb) != len(want) {
  614. t.Fatalf("esperaba %d MACs (solo puertos físicos), tengo %d: %+v", len(want), len(fdb), fdb)
  615. }
  616. for mac, port := range want {
  617. if fdb[mac] != port {
  618. t.Fatalf("MAC %s: esperaba puerto %s, tengo %q", mac, port, fdb[mac])
  619. }
  620. }
  621. }
  622. // ---------------------------------------------------------------------------
  623. // Prober local con runner fake
  624. // ---------------------------------------------------------------------------
  625. // TestProberWirelessWithoutClients (#1092): una unidad SIN clientes
  626. // asociados conserva la sección wireless (radios + BSSIDs propios); antes
  627. // el flag de presencia solo consideraba clientes y el server la veía como
  628. // "sin WiFi" (encontrado en un AP lab de NetGrip).
  629. func TestProberWirelessWithoutClients(t *testing.T) {
  630. run := fakeRunner{outs: map[string]string{
  631. CmdUbusSystemInfo: `{"uptime":90061,"load":[0.1,0.2,0.3],"memory":{"total":256000000,"free":100000000,"buffered":0,"available":128000000}}`,
  632. CmdUbusSystemBoard: `{"model":"GL.iNet Lab","hostname":"lab","release":{"version":"25.12","description":"OpenWrt 25.12"}}`,
  633. CmdProcStat: "cpu 4705 356 584 3699 23 0 23 0 0 0\n",
  634. CmdTemp: "43500\n",
  635. CmdNetDev: " eth0: 1000000 0 0 0 0 0 0 0 500000 0\n",
  636. CmdBridgeMAC: "94:83:c4:00:00:09\n",
  637. // Sin clientes: ningún comando de assoclist/ubus hostapd.
  638. CmdRadios: "2.4|6|HT20|20|0\n",
  639. CmdDhcpFile: "1700000000 ec:71:db:44:12:8a 192.168.8.71 movil *\n",
  640. CmdBridgeFDB: "==PORTS==\n0x1 lan1\n==MACS==\n1 ec:71:db:44:12:8a\n",
  641. CmdPortStates: "lan1 up 1000\nwan down -1\n",
  642. CmdUbusWireless: `{"radio0":{"up":true,"interfaces":[{"ifname":"wlan0","config":{"mode":"ap"}}]}}`,
  643. CmdIwDev: "phy#0\n\tInterface wlan0\n\t\taddr 62:e5:56:b6:94:bd\n\t\tssid temiscira\n\t\ttype AP\n",
  644. }}
  645. p := NewProber(run, Options{GwPingTarget: "192.168.8.1", ScanInterval: ScanDisabled})
  646. pl := p.Build(context.Background(), "lab", "3.0.7")
  647. if pl.Data.Wireless == nil {
  648. t.Fatal("sin clientes la sección wireless no debe descartarse (#1092)")
  649. }
  650. if len(pl.Data.Wireless.OwnBssids) != 1 || pl.Data.Wireless.OwnBssids[0].SSID != "temiscira" {
  651. t.Fatalf("ownBssids perdidos: %+v", pl.Data.Wireless.OwnBssids)
  652. }
  653. if len(pl.Data.Wireless.Radios) != 1 {
  654. t.Fatalf("radios perdidas: %+v", pl.Data.Wireless.Radios)
  655. }
  656. }
  657. type fakeRunner struct{ outs map[string]string }
  658. func (f fakeRunner) Run(_ context.Context, cmd string, _ time.Duration) (string, error) {
  659. if out, ok := f.outs[cmd]; ok {
  660. return out, nil
  661. }
  662. return "", &fakeErr{cmd}
  663. }
  664. type fakeErr struct{ cmd string }
  665. func (e *fakeErr) Error() string { return "no existe: " + e.cmd }
  666. func TestProberBuild(t *testing.T) {
  667. run := fakeRunner{outs: map[string]string{
  668. CmdUbusSystemInfo: `{"uptime":90061,"load":[0.1,0.2,0.3],"memory":{"total":256000000,"free":100000000,"buffered":0,"available":128000000}}`,
  669. CmdUbusSystemBoard: `{"model":"TP-Link EAP225","hostname":"patio","release":{"version":"23.05","description":"OpenWrt 23.05"}}`,
  670. CmdProcStat: "cpu 4705 356 584 3699 23 0 23 0 0 0\n",
  671. CmdTemp: "43500\n",
  672. CmdNetDev: " eth0: 1000000 0 0 0 0 0 0 0 500000 0\n",
  673. CmdBridgeMAC: "94:83:c4:00:00:09\n",
  674. CmdIwinfoAssoc: "EC:71:DB:44:12:8A -55 2.4\n",
  675. CmdRadios: "2.4|6|HT20|20|1\n",
  676. CmdDhcpFile: "1700000000 ec:71:db:44:12:8a 192.168.8.71 movil *\n",
  677. CmdBridgeFDB: "==PORTS==\n0x1 lan1\n==MACS==\n1 ec:71:db:44:12:8a\n",
  678. CmdPortStates: "lan1 up 1000\nwan down -1\n",
  679. CmdUbusWireless: `{"radio0":{"up":true,"interfaces":[{"ifname":"wlan0","config":{"mode":"ap"}}]}}`,
  680. }}
  681. p := NewProber(run, Options{GwPingTarget: "192.168.8.1"})
  682. // Primera muestra: cpu/net sin delta (null), el resto presente
  683. pl := p.Build(context.Background(), "patio", "0.1.0")
  684. if pl.Router != "patio" || pl.Version != "0.1.0" || pl.Ts <= 0 {
  685. t.Fatalf("cabecera: %+v", pl)
  686. }
  687. sd := pl.Data.System
  688. if sd == nil || sd.SysInfo == nil || sd.SysInfo.Uptime != 90061 || sd.Board.Hostname != "patio" {
  689. t.Fatalf("system: %+v", sd)
  690. }
  691. if sd.CPU != nil || sd.RxBps != nil {
  692. t.Fatalf("primera muestra sin delta: %v %v", sd.CPU, sd.RxBps)
  693. }
  694. if sd.Temp == nil || *sd.Temp != 44 || sd.Backhaul != "cable" || sd.BridgeMAC != "94:83:C4:00:00:09" {
  695. t.Fatalf("temp/backhaul/mac: %+v", sd)
  696. }
  697. if pl.Data.Wireless.Clients["EC:71:DB:44:12:8A"].SignalDbm != -55 || len(pl.Data.Wireless.Radios) != 1 {
  698. t.Fatalf("wireless: %+v", pl.Data.Wireless)
  699. }
  700. if len(pl.Data.DHCP.Leases) != 1 || pl.Data.DHCP.Leases[0].IP != "192.168.8.71" {
  701. t.Fatalf("dhcp: %+v", pl.Data.DHCP)
  702. }
  703. if pl.Data.FDB.MACs["EC:71:DB:44:12:8A"] != "lan1" || len(pl.Data.FDB.Ports) == 0 {
  704. t.Fatalf("fdb: %+v", pl.Data.FDB)
  705. }
  706. // Segunda muestra (contadores avanzados): ya hay delta de cpu/net
  707. run.outs[CmdProcStat] = "cpu 4805 356 584 3799 23 0 23 0 0 0\n"
  708. run.outs[CmdNetDev] = " eth0: 2000000 0 0 0 0 0 0 0 1000000 0\n"
  709. pl2 := p.Build(context.Background(), "patio", "0.1.0")
  710. if pl2.Data.System.CPU == nil || pl2.Data.System.RxBps == nil {
  711. t.Fatal("segunda muestra debería tener delta cpu/net")
  712. }
  713. }
  714. func TestProberNetIfOmittedWhenCmdNetDevFails(t *testing.T) {
  715. // Issue #408: si /proc/net/dev no se refresca en un ciclo, NetIf no debe
  716. // enviarse para que el servidor no calcule deltas 0 con contadores viejos.
  717. run := fakeRunner{outs: map[string]string{
  718. CmdUbusSystemInfo: `{"uptime":90061,"load":[0.1,0.2,0.3],"memory":{"total":256000000,"free":100000000,"buffered":0,"available":128000000}}`,
  719. CmdUbusSystemBoard: `{"model":"TP-Link EAP225","hostname":"patio","release":{"version":"23.05","description":"OpenWrt 23.05"}}`,
  720. CmdProcStat: "cpu 4705 356 584 3699 23 0 23 0 0 0\n",
  721. CmdTemp: "43500\n",
  722. CmdNetDev: " eth0: 1000000 0 0 0 0 0 0 0 500000 0\n",
  723. CmdBridgeMAC: "94:83:c4:00:00:09\n",
  724. }}
  725. p := NewProber(run, Options{})
  726. pl := p.Build(context.Background(), "patio", "0.1.0")
  727. if pl.Data.NetIf == nil || pl.Data.NetIf["eth0"].Rx != 1000000 {
  728. t.Fatalf("primera muestra debería incluir NetIf: %+v", pl.Data.NetIf)
  729. }
  730. // Segundo ciclo: /proc/net/dev falla; NetIf debe omitirse.
  731. delete(run.outs, CmdNetDev)
  732. pl2 := p.Build(context.Background(), "patio", "0.1.0")
  733. if pl2.Data.NetIf != nil {
  734. t.Fatalf("CmdNetDev falló: NetIf debería ser nil, got %+v", pl2.Data.NetIf)
  735. }
  736. // Tercer ciclo: /proc/net/dev vuelve; NetIf se reanuda.
  737. run.outs[CmdNetDev] = " eth0: 2000000 0 0 0 0 0 0 0 1000000 0\n"
  738. pl3 := p.Build(context.Background(), "patio", "0.1.0")
  739. if pl3.Data.NetIf == nil || pl3.Data.NetIf["eth0"].Rx != 2000000 {
  740. t.Fatalf("tercera muestra debería incluir NetIf refrescado: %+v", pl3.Data.NetIf)
  741. }
  742. }
  743. func TestProberSondasFallidasSeccionAusente(t *testing.T) {
  744. // Equipo sin ubus/iwinfo/brctl (todo falla salvo /proc): las secciones
  745. // wireless/dhcp/fdb quedan ausentes (nil) → el servidor conserva lo último.
  746. run := fakeRunner{outs: map[string]string{
  747. CmdProcStat: "cpu 4705 356 584 3699 23 0 23 0 0 0\n",
  748. CmdTemp: "43500\n",
  749. CmdNetDev: " eth0: 1000 0 0 0 0 0 0 0 500 0\n",
  750. }}
  751. p := NewProber(run, Options{})
  752. pl := p.Build(context.Background(), "patio", "0.1.0")
  753. if pl.Data.System == nil {
  754. t.Fatal("system debería existir (proc funciona)")
  755. }
  756. if pl.Data.Wireless != nil || pl.Data.DHCP != nil || pl.Data.FDB != nil {
  757. t.Fatalf("secciones fallidas deberían ser nil: %+v", pl.Data)
  758. }
  759. // JSON de las secciones ausentes: omitempty las omite
  760. if strings.Contains(payloadJSON(t, pl), `"wireless"`) {
  761. t.Fatal("wireless ausente no debería serializarse")
  762. }
  763. }
  764. func payloadJSON(t *testing.T, pl *Payload) string {
  765. t.Helper()
  766. data, err := json.Marshal(pl)
  767. if err != nil {
  768. t.Fatal(err)
  769. }
  770. return string(data)
  771. }
  772. func TestParseWanStatus(t *testing.T) {
  773. // Fixture real de `ubus call network.interface.wan status` (PPPoE Digi).
  774. raw := `{"up":true,"proto":"pppoe","l3_device":"pppoe-wan","device":"eth1.20",` +
  775. `"ipv4-address":[{"address":"79.112.56.116","mask":32,"ptpaddress":"10.0.28.237"}],` +
  776. `"route":[{"target":"0.0.0.0","mask":0,"nexthop":"10.0.28.237","source":"0.0.0.0/0"}],` +
  777. `"dns-server":["100.90.1.1","100.100.1.1"]}`
  778. info := ParseWanStatus([]byte(raw))
  779. if info.Proto != "pppoe" {
  780. t.Fatalf("proto=%q, esperaba pppoe", info.Proto)
  781. }
  782. if info.Device != "pppoe-wan" {
  783. t.Fatalf("device=%q, esperaba pppoe-wan", info.Device)
  784. }
  785. if info.IP != "79.112.56.116" {
  786. t.Fatalf("ip=%q, esperaba 79.112.56.116", info.IP)
  787. }
  788. if info.Gateway != "10.0.28.237" {
  789. t.Fatalf("gateway=%q, esperaba 10.0.28.237", info.Gateway)
  790. }
  791. if len(info.DNS) != 2 || info.DNS[0] != "100.90.1.1" || info.DNS[1] != "100.100.1.1" {
  792. t.Fatalf("dns=%v, esperaba [100.90.1.1 100.100.1.1]", info.DNS)
  793. }
  794. }
  795. func TestParseWanStatusVacioYMalFormado(t *testing.T) {
  796. // Router sin interfaz wan (AP) → JSON sin ipv4-address ni rutas.
  797. raw := `{"up":true,"proto":"dhcp"}`
  798. info := ParseWanStatus([]byte(raw))
  799. if info.IP != "" || info.Gateway != "" || len(info.DNS) != 0 {
  800. t.Fatalf("AP sin wan debía quedar vacío: %+v", info)
  801. }
  802. // Malformado → vacío sin error.
  803. if got := ParseWanStatus([]byte("no json")); got.IP != "" || got.Proto != "" {
  804. t.Fatalf("JSON inválido debía quedar vacío: %+v", got)
  805. }
  806. }
  807. func TestParseBridgeVlan(t *testing.T) {
  808. // Fixture típico de OpenWrt con bridge vlan filtering (VLAN 1 PVID +
  809. // VLANs 10/20 tagged en wan, 1 untagged en todos los LAN).
  810. out := `port vlan-id
  811. br-lan 1 PVID Egress Untagged
  812. lan1 1 PVID Egress Untagged
  813. lan2 1 PVID Egress Untagged
  814. lan3 1 PVID Egress Untagged
  815. lan4 1 PVID Egress Untagged
  816. wan 1 PVID Egress Untagged
  817. 10
  818. 20
  819. `
  820. ports := ParseBridgeVlan(out)
  821. if len(ports) != 6 {
  822. t.Fatalf("esperaba 6 puertos, tengo %d: %+v", len(ports), ports)
  823. }
  824. // br-lan: 1 untagged + PVID
  825. br := ports[0]
  826. if br.Port != "br-lan" || len(br.Vlans) != 1 {
  827. t.Fatalf("br-lan: %+v", br)
  828. }
  829. if br.Vlans[0].ID != 1 || br.Vlans[0].Tagged || !br.Vlans[0].PVID {
  830. t.Fatalf("br-lan vlan: %+v", br.Vlans[0])
  831. }
  832. // wan: 3 VLANs (1 untagged+PVID, 10 tagged, 20 tagged)
  833. wan := ports[5]
  834. if wan.Port != "wan" || len(wan.Vlans) != 3 {
  835. t.Fatalf("wan: %+v", wan)
  836. }
  837. if wan.Vlans[0].ID != 1 || wan.Vlans[0].Tagged || !wan.Vlans[0].PVID {
  838. t.Fatalf("wan vlan[0]: %+v", wan.Vlans[0])
  839. }
  840. if wan.Vlans[1].ID != 10 || !wan.Vlans[1].Tagged || wan.Vlans[1].PVID {
  841. t.Fatalf("wan vlan[1]: %+v", wan.Vlans[1])
  842. }
  843. if wan.Vlans[2].ID != 20 || !wan.Vlans[2].Tagged || wan.Vlans[2].PVID {
  844. t.Fatalf("wan vlan[2]: %+v", wan.Vlans[2])
  845. }
  846. }
  847. func TestParseBridgeVlanVacio(t *testing.T) {
  848. // Router sin bridge vlan filtering → salida vacía.
  849. if got := ParseBridgeVlan(""); len(got) != 0 {
  850. t.Fatalf("vacío esperaba [], tengo %+v", got)
  851. }
  852. if got := ParseBridgeVlan("port vlan-id\n"); len(got) != 0 {
  853. t.Fatalf("solo header esperaba [], tengo %+v", got)
  854. }
  855. }
  856. func TestParseBridgeVlanSoloTagged(t *testing.T) {
  857. // Puerto trunk sin PVID (solo tagged).
  858. out := `port vlan-id
  859. eth0 100
  860. 200
  861. 300
  862. `
  863. ports := ParseBridgeVlan(out)
  864. if len(ports) != 1 || ports[0].Port != "eth0" || len(ports[0].Vlans) != 3 {
  865. t.Fatalf("trunk: %+v", ports)
  866. }
  867. for _, v := range ports[0].Vlans {
  868. if !v.Tagged || v.PVID {
  869. t.Fatalf("trunk vlan debía ser tagged sin PVID: %+v", v)
  870. }
  871. }
  872. }
  873. func TestParseEthtoolSFP(t *testing.T) {
  874. // Salida realista de ethtool -m con un SFP monomodo.
  875. out := ` Identifier : 0x03 (SFP)
  876. Extended identifier : 0x04 (GBIC/SFP defined by 2-wire interface ID)
  877. Connector : 0x07 (LC)
  878. Transceiver codes : 0x00 0x00 0x00 0x01 0x00 0x00 0x00 0x00 0x00
  879. Vendor Name : FS.COM
  880. Vendor Part Number : SFP-GE-BX
  881. Vendor Rev :
  882. Vendor SN : F2305060072
  883. Module temperature : 34.5 degrees C / 94.1 degrees F
  884. Module voltage : 3.2950 Volts
  885. Alarm/warning flags implemented : Yes
  886. Laser output power : 0.5230 mW / -2.82 dBm
  887. Laser receiver power : 0.0501 mW / -13.00 dBm
  888. `
  889. sfp := ParseEthtoolSFP(out)
  890. if sfp == nil {
  891. t.Fatal("esperaba SfpInfo no nil")
  892. }
  893. if !sfp.Present {
  894. t.Fatal("esperaba Present=true")
  895. }
  896. if sfp.Temperature != 34.5 {
  897. t.Fatalf("temp=%.1f, esperaba 34.5", sfp.Temperature)
  898. }
  899. if sfp.Voltage != 3.2950 {
  900. t.Fatalf("volt=%.4f, esperaba 3.2950", sfp.Voltage)
  901. }
  902. if sfp.TxPower != -2.82 {
  903. t.Fatalf("txp=%.2f, esperaba -2.82", sfp.TxPower)
  904. }
  905. if sfp.RxPower != -13.00 {
  906. t.Fatalf("rxp=%.2f, esperaba -13.00", sfp.RxPower)
  907. }
  908. if sfp.Vendor != "FS.COM" {
  909. t.Fatalf("vendor=%q, esperaba FS.COM", sfp.Vendor)
  910. }
  911. if sfp.PartNumber != "SFP-GE-BX" {
  912. t.Fatalf("pn=%q, esperaba SFP-GE-BX", sfp.PartNumber)
  913. }
  914. // Sin módulo SFP: salida vacía → nil.
  915. if got := ParseEthtoolSFP(""); got != nil {
  916. t.Fatalf("vacío debía dar nil: %+v", got)
  917. }
  918. // Salida sin datos DOM (solo identifier, sin temp/power) → nil.
  919. if got := ParseEthtoolSFP("Identifier : 0x03 (SFP)\n"); got != nil {
  920. t.Fatalf("sin DOM debía dar nil: %+v", got)
  921. }
  922. }
  923. // TestIsRandomizedMAC (#338): detects locally-administered MACs.
  924. func TestIsRandomizedMAC(t *testing.T) {
  925. cases := map[string]bool{
  926. "AA:BB:CC:DD:EE:FF": true, // 0xAA = 10101010, bit 1 set
  927. "02:11:22:33:44:55": true, // 0x02 = 00000010, bit 1 set
  928. "F6:A1:B2:C3:D4:E5": true, // 0xF6 = 11110110, bit 1 set
  929. "00:11:22:33:44:55": false, // 0x00 = 00000000, bit 1 clear
  930. "DC:A6:32:XX:YY:ZZ": false, // 0xDC = 11011100, bit 1 clear (Raspberry Pi)
  931. "B8:27:EB:11:22:33": false, // 0xB8 = 10111000, bit 1 clear
  932. "B2:AA:BB:CC:DD:EE": true, // 0xB2 = 10110010, bit 1 set (Apple private)
  933. }
  934. for mac, want := range cases {
  935. got := IsRandomizedMAC(mac)
  936. if got != want {
  937. t.Errorf("IsRandomizedMAC(%q) = %v, want %v", mac, got, want)
  938. }
  939. }
  940. // Edge cases
  941. if IsRandomizedMAC("") {
  942. t.Error("empty should be false")
  943. }
  944. if IsRandomizedMAC("X") {
  945. t.Error("single char should be false")
  946. }
  947. }
  948. // TestParseMdnsBrowse (#338): parses umdns browse output.
  949. func TestParseMdnsBrowse(t *testing.T) {
  950. // Empty input
  951. if got := ParseMdnsBrowse(nil); got != nil {
  952. t.Fatalf("nil should return nil, got %+v", got)
  953. }
  954. if got := ParseMdnsBrowse([]byte("{}")); got != nil {
  955. t.Fatalf("empty object should return nil, got %+v", got)
  956. }
  957. // Real umdns browse output (simplified)
  958. raw := `{
  959. "Apple-TV._airplay._tcp.local": {"port": 7000, "ipv4": "192.168.1.50"},
  960. "Apple-TV._raop._tcp.local": {"port": 7000, "ipv4": "192.168.1.50"},
  961. "Printer._ipp._tcp.local": {"port": 631, "ipv4": "192.168.1.60"}
  962. }`
  963. dd := ParseMdnsBrowse([]byte(raw))
  964. if dd == nil {
  965. t.Fatal("should parse valid browse output")
  966. }
  967. // Check services
  968. if svcs, ok := dd.Services["Apple-TV"]; !ok || len(svcs) != 2 {
  969. t.Errorf("Apple-TV services: %v", dd.Services)
  970. }
  971. if svcs, ok := dd.Services["Printer"]; !ok || len(svcs) != 1 {
  972. t.Errorf("Printer services: %v", dd.Services)
  973. }
  974. // Check IP mapping
  975. if host, ok := dd.HostByIP["192.168.1.50"]; !ok || host != "Apple-TV" {
  976. t.Errorf("HostByIP[192.168.1.50] = %q", host)
  977. }
  978. if host, ok := dd.HostByIP["192.168.1.60"]; !ok || host != "Printer" {
  979. t.Errorf("HostByIP[192.168.1.60] = %q", host)
  980. }
  981. }
  982. func TestParseUsteer(t *testing.T) {
  983. // Fixtures con los shapes reales verificados en rt3 (local_info) y
  984. // Flint2 (remote_info / connected_clients).
  985. localInfo := `{
  986. "hostapd.phy0-ap0": {
  987. "bssid": "9c:9d:7e:1b:ea:b3",
  988. "ssid": "temiscira",
  989. "freq": 5260,
  990. "n_assoc": 0,
  991. "noise": -108,
  992. "load": 3,
  993. "max_assoc": 0,
  994. "roam_events": { "source": 0, "target": 0 },
  995. "rrm_nr": ["9c:9d:7e:1b:ea:b3", "temiscira", "9c9d7e1beab3ff5900008034090603023a00"]
  996. },
  997. "hostapd.phy1-ap0": {
  998. "bssid": "9c:9d:7e:1b:ea:b2",
  999. "ssid": "temiscira",
  1000. "freq": 2442,
  1001. "n_assoc": 1,
  1002. "load": 20
  1003. }
  1004. }`
  1005. remoteInfo := `{
  1006. "192.168.1.3#hostapd.phy0-ap0": {
  1007. "bssid": "9c:9d:7e:1b:ea:b3",
  1008. "ssid": "temiscira",
  1009. "freq": 5260,
  1010. "n_assoc": 0,
  1011. "load": 3
  1012. },
  1013. "192.168.1.4#hostapd.phy0-ap0": {
  1014. "bssid": "aa:bb:cc:dd:ee:01",
  1015. "ssid": "temiscira",
  1016. "freq": 5260,
  1017. "n_assoc": 2,
  1018. "load": 40
  1019. }
  1020. }`
  1021. connectedClients := `{
  1022. "hostapd.wlan0": {
  1023. "aa:bb:cc:dd:ee:ff": { "signal": -39 }
  1024. }
  1025. }`
  1026. // 1. Sin remote_info: los APs locales se agrupan por SSID.
  1027. d := ParseUsteer(localInfo, "", "")
  1028. if d == nil {
  1029. t.Fatal("ParseUsteer(local) devolvió nil")
  1030. }
  1031. s, ok := d.SSIDs["temiscira"]
  1032. if !ok {
  1033. t.Fatalf("falta SSID temiscira: %v", d.SSIDs)
  1034. }
  1035. if len(s.APs) != 2 {
  1036. t.Fatalf("esperaba 2 APs locales, obtuve %d", len(s.APs))
  1037. }
  1038. if !s.APs[0].Local || !s.APs[1].Local {
  1039. t.Error("los APs locales deberían tener Local=true")
  1040. }
  1041. // Los BSSID deben ir en mayúsculas. Sin asumir orden (ParseUsteer itera
  1042. // un mapa): comprobar el conjunto de los dos APs locales.
  1043. got := map[string]bool{}
  1044. for _, ap := range s.APs {
  1045. got[ap.BSSID] = true
  1046. }
  1047. for _, want := range []string{"9C:9D:7E:1B:EA:B2", "9C:9D:7E:1B:EA:B3"} {
  1048. if !got[want] {
  1049. t.Errorf("falta el AP local %s (BSSID en mayúsculas): %v", want, s.APs)
  1050. }
  1051. }
  1052. // 2. APs remotos: hostname = IP de la clave, Local=false.
  1053. d = ParseUsteer("", remoteInfo, "")
  1054. if d == nil {
  1055. t.Fatal("ParseUsteer(remote) devolvió nil")
  1056. }
  1057. rs := d.SSIDs["temiscira"]
  1058. if len(rs.APs) != 2 {
  1059. t.Fatalf("esperaba 2 APs remotos, obtuve %d", len(rs.APs))
  1060. }
  1061. if rs.APs[0].Local {
  1062. t.Error("el AP remoto debería tener Local=false")
  1063. }
  1064. if rs.APs[0].Hostname != "192.168.1.3" && rs.APs[1].Hostname != "192.168.1.3" {
  1065. t.Errorf("falta hostname IP en remotos: %+v", rs.APs)
  1066. }
  1067. // 3. connected_clients: si el iface casa con local_info, el cliente se
  1068. // agrupa por SSID con su señal.
  1069. d = ParseUsteer(localInfo, "", `{ "hostapd.phy0-ap0": { "aa:bb:cc:dd:ee:ff": { "signal": -39 } } }`)
  1070. if d == nil {
  1071. t.Fatal("ParseUsteer con clientes devolvió nil")
  1072. }
  1073. cs := d.SSIDs["temiscira"]
  1074. if c, ok := cs.Clients["AA:BB:CC:DD:EE:FF"]; !ok || c.Signal != -39 {
  1075. t.Errorf("cliente no agrupado: %v", cs.Clients)
  1076. }
  1077. // 4. iface sin casar (wlan0 vs phy0-ap0): no se asigna SSID erróneo.
  1078. _ = connectedClients
  1079. d = ParseUsteer(localInfo, "", connectedClients)
  1080. if d != nil && len(d.SSIDs["temiscira"].Clients) != 0 {
  1081. t.Errorf("cliente con iface no resuelto debería omitirse: %v", d.SSIDs["temiscira"].Clients)
  1082. }
  1083. // 5. Sin datos: nil.
  1084. if ParseUsteer("", "", "") != nil {
  1085. t.Error("ParseUsteer vacío debería devolver nil")
  1086. }
  1087. if ParseUsteer("{", "", "") != nil {
  1088. t.Error("ParseUsteer con JSON inválido debería devolver nil")
  1089. }
  1090. }
  1091. // TestParseScanExtraeVecinos (#452): parsea la salida de `iw dev` scan.
  1092. func TestParseScanWidthMhz(t *testing.T) {
  1093. // Bloques HT/VHT reales de `iw dev wlan0 scan` (OpenWrt).
  1094. out := `==IFACE==wlan0
  1095. BSS 11:22:33:44:55:66(on wlan0)
  1096. freq: 2437
  1097. signal: -55.00 dBm
  1098. SSID: ochenta
  1099. HT operation:
  1100. * primary channel: 6
  1101. * secondary channel offset: below
  1102. VHT operation:
  1103. * channel width: 1 (80 MHz)
  1104. BSS aa:bb:cc:dd:ee:ff(on wlan0)
  1105. freq: 2462
  1106. signal: -70.00 dBm
  1107. SSID: cuarenta
  1108. HT operation:
  1109. * primary channel: 11
  1110. * secondary channel offset: above
  1111. BSS 22:33:44:55:66:77(on wlan0)
  1112. freq: 2412
  1113. signal: -80.00 dBm
  1114. SSID: veinte
  1115. HT operation:
  1116. * primary channel: 1
  1117. * secondary channel offset: no secondary
  1118. BSS 33:44:55:66:77:88(on wlan0)
  1119. freq: 5500
  1120. signal: -60.00 dBm
  1121. SSID: ciento60
  1122. HT operation:
  1123. * primary channel: 100
  1124. * secondary channel offset: below
  1125. VHT operation:
  1126. * channel width: 2 (160 MHz)
  1127. `
  1128. got := ParseScan(out)
  1129. widths := map[string]int{}
  1130. for _, s := range got {
  1131. widths[s.SSID] = s.WidthMhz
  1132. }
  1133. if widths["ochenta"] != 80 || widths["cuarenta"] != 40 || widths["veinte"] != 20 || widths["ciento60"] != 160 {
  1134. t.Fatalf("anchos inesperados: %+v de %+v", widths, got)
  1135. }
  1136. }
  1137. func TestParseIwDev(t *testing.T) {
  1138. out := `phy#0
  1139. Interface wlan0
  1140. ifindex 12
  1141. wdev 0x200000000
  1142. addr 62:e5:56:b6:94:bd
  1143. ssid temiscira
  1144. type AP
  1145. channel 6 (2437 MHz), width: 80 MHz, center1: 2437 MHz
  1146. txpower 20.00 dBm
  1147. Interface wlan0-1
  1148. ifindex 13
  1149. wdev 0x200000001
  1150. addr 6a:e5:56:b6:94:bd
  1151. ssid temiscira-guest
  1152. type AP
  1153. channel 6 (2437 MHz), width: 20 MHz, center1: 2437 MHz
  1154. Interface wlan1
  1155. ifindex 14
  1156. wdev 0x200000002
  1157. addr 62:e5:56:b6:94:be
  1158. ssid temiscira
  1159. type AP
  1160. channel 36 (5180 MHz), width: 80 MHz, center1: 5210 MHz
  1161. phy#1
  1162. Interface uap0
  1163. ifindex 20
  1164. addr 62:e5:56:b6:94:bf
  1165. type managed
  1166. `
  1167. got := ParseIwDev(out)
  1168. if len(got) != 3 {
  1169. t.Fatalf("esperaba 3 APs (uap0 managed fuera): %+v", got)
  1170. }
  1171. if got[0].BSSID != "62:E5:56:B6:94:BD" || got[0].SSID != "temiscira" || got[0].Iface != "wlan0" {
  1172. t.Fatalf("bloque 0 mal parseado: %+v", got[0])
  1173. }
  1174. if got[1].SSID != "temiscira-guest" {
  1175. t.Fatalf("guest sin capturar: %+v", got[1])
  1176. }
  1177. }
  1178. func TestParseScanExtraeVecinos(t *testing.T) {
  1179. out := `==IFACE==wlan0
  1180. BSS 00:11:22:33:44:55(on wlan0)
  1181. TSF: 12345
  1182. freq: 2437
  1183. beacon interval: 100 TUs
  1184. capability: ESS (0x0001)
  1185. signal: -62.00 dBm
  1186. last seen: 0 ms
  1187. SSID: vecino-2g
  1188. BSS aa:bb:cc:dd:ee:ff(on wlan0)
  1189. freq: 2462
  1190. signal: -80.00 dBm
  1191. SSID:
  1192. ==IFACE==wlan1
  1193. BSS 11:22:33:44:55:66(on wlan1)
  1194. freq: 5180
  1195. signal: -55.00 dBm
  1196. SSID: vecino-5g
  1197. `
  1198. got := ParseScan(out)
  1199. if len(got) != 3 {
  1200. t.Fatalf("esperaba 3 resultados, got %d: %+v", len(got), got)
  1201. }
  1202. if got[0].Iface != "wlan0" || got[0].BSSID != "00:11:22:33:44:55" || got[0].SSID != "vecino-2g" || got[0].Freq != 2437 || got[0].Channel != 6 || got[0].Signal != -62 {
  1203. t.Errorf("primer scan incorrecto: %+v", got[0])
  1204. }
  1205. if got[1].Channel != 11 {
  1206. t.Errorf("segundo scan channel incorrecto: %+v", got[1])
  1207. }
  1208. if got[2].Iface != "wlan1" || got[2].Channel != 36 || got[2].Signal != -55 {
  1209. t.Errorf("tercer scan incorrecto: %+v", got[2])
  1210. }
  1211. }
  1212. // TestParseScanFreqFloat (#475): iw real imprime "freq: 5260.0"; con Atoi el
  1213. // error se tragaba, Freq quedaba 0 y el flush descartaba todos los BSS.
  1214. func TestParseScanFreqFloat(t *testing.T) {
  1215. out := `==IFACE==wlan1
  1216. BSS 9c:9d:7e:1b:ea:b3(on wlan1)
  1217. last seen: 945720.058s [boottime]
  1218. TSF: 419753678847 usec (4d, 20:35:53)
  1219. freq: 5260.0
  1220. signal: -61.00 dBm
  1221. SSID: vecino-dfs
  1222. BSS 8c:de:f9:33:71:59(on wlan1)
  1223. freq: 5180.0
  1224. signal: -72.00 dBm
  1225. SSID:
  1226. `
  1227. got := ParseScan(out)
  1228. if len(got) != 2 {
  1229. t.Fatalf("esperaba 2 resultados, got %d: %+v", len(got), got)
  1230. }
  1231. if got[0].Freq != 5260 || got[0].Channel != 52 || got[0].Signal != -61 {
  1232. t.Errorf("primer scan incorrecto: %+v", got[0])
  1233. }
  1234. if got[1].Freq != 5180 || got[1].Channel != 36 || got[1].SSID != "" {
  1235. t.Errorf("segundo scan incorrecto: %+v", got[1])
  1236. }
  1237. }
  1238. func TestParseScanVacio(t *testing.T) {
  1239. if got := ParseScan(""); len(got) != 0 {
  1240. t.Fatalf("esperaba [] vacío, got %d", len(got))
  1241. }
  1242. }
  1243. func TestFreqToChannel(t *testing.T) {
  1244. cases := []struct{ freq, want int }{
  1245. {2412, 1}, {2437, 6}, {2462, 11}, {2484, 14},
  1246. {5180, 36}, {5260, 52}, {5500, 100}, {5955, 1},
  1247. }
  1248. for _, c := range cases {
  1249. if got := FreqToChannel(c.freq); got != c.want {
  1250. t.Errorf("FreqToChannel(%d) = %d, want %d", c.freq, got, c.want)
  1251. }
  1252. }
  1253. }
  1254. // TestBoardInfoParsesASUFields: captura real de `ubus call system board` en un
  1255. // Redmi AX6 (rt4). board_name y release.target son los dos valores que ASU
  1256. // necesita para localizar la imagen (#477).
  1257. func TestBoardInfoParsesASUFields(t *testing.T) {
  1258. raw := `{"kernel":"6.12.94","hostname":"rt4","system":"ARMv8 Processor rev 4","model":"Redmi AX6","board_name":"redmi,ax6","rootfs_type":"squashfs","release":{"distribution":"OpenWrt","version":"25.12.5","firmware_url":"https://downloads.openwrt.org/","revision":"r33051-f5dae5ece4","target":"qualcommax/ipq807x","description":"OpenWrt 25.12.5 r33051-f5dae5ece4"}}`
  1259. var b BoardInfo
  1260. if err := json.Unmarshal([]byte(raw), &b); err != nil {
  1261. t.Fatalf("unmarshal board: %v", err)
  1262. }
  1263. if b.BoardName != "redmi,ax6" {
  1264. t.Errorf("BoardName = %q, want redmi,ax6", b.BoardName)
  1265. }
  1266. if b.Release.Target != "qualcommax/ipq807x" {
  1267. t.Errorf("Release.Target = %q, want qualcommax/ipq807x", b.Release.Target)
  1268. }
  1269. if b.Model != "Redmi AX6" || b.Hostname != "rt4" || b.Release.Version != "25.12.5" {
  1270. t.Errorf("campos básicos corruptos: %+v", b)
  1271. }
  1272. }
  1273. func TestParseRadioSections(t *testing.T) {
  1274. out := `wireless.radio0=wifi-device
  1275. wireless.radio0.type='mac80211'
  1276. wireless.radio0.band='2g'
  1277. wireless.radio0.channel='1'
  1278. wireless.default_radio0=wifi-iface
  1279. wireless.radio1=wifi-device
  1280. wireless.radio1.band='5g'
  1281. wireless.radio1.channel='44'
  1282. wireless.default_radio1=wifi-iface
  1283. `
  1284. got := ParseRadioSections(out)
  1285. if len(got) != 2 {
  1286. t.Fatalf("want 2 sections, got %d: %v", len(got), got)
  1287. }
  1288. if got["2.4 GHz"] != "radio0" || got["5 GHz"] != "radio1" {
  1289. t.Errorf("wrong mapping: %v", got)
  1290. }
  1291. }
  1292. func TestParseRadioSectionsLegacyHwmode(t *testing.T) {
  1293. out := `wireless.wifi0=wifi-device
  1294. wireless.wifi0.hwmode='11g'
  1295. wireless.wifi1=wifi-device
  1296. wireless.wifi1.hwmode='11a'
  1297. `
  1298. got := ParseRadioSections(out)
  1299. if got["2.4 GHz"] != "wifi0" || got["5 GHz"] != "wifi1" {
  1300. t.Errorf("wrong legacy hwmode mapping: %v", got)
  1301. }
  1302. }
  1303. func TestParseRadioSectionsEmpty(t *testing.T) {
  1304. if got := ParseRadioSections(""); len(got) != 0 {
  1305. t.Errorf("want empty map, got %v", got)
  1306. }
  1307. if got := ParseRadioSections("network.lan=interface\n"); len(got) != 0 {
  1308. t.Errorf("want empty map for unrelated config, got %v", got)
  1309. }
  1310. }
  1311. // portStatesDSASwitch es la salida de CmdPortStates en una placa con switch DSA
  1312. // (ipq4019, switch DSA): dos bocas de verdad (lan1, lan2) colgando del puerto
  1313. // de CPU eth0, el bridge con sus VLANs, y un módem celular en wwan0.
  1314. const portStatesDSASwitch = `br-lan up 1000 - 1 lan2
  1315. br-lan.10 up 1000 - 1 br-lan
  1316. br-lan.16 up 1000 - 1 br-lan
  1317. eth0 up 1000 dsa 1 -
  1318. lan1 up 1000 - 1 eth0
  1319. lan2 up 1000 - 1 eth0
  1320. lo unknown -1 - 772 -
  1321. phy2-ap0 up -1 - 1 -
  1322. pppoe-isp unknown -1 - 512 -
  1323. wg0 unknown -1 - 65534 -
  1324. wwan0 unknown -1 - 65534 -`
  1325. // boardWanIsAModem: board.json del mismo router. El WAN no es una boca, es el
  1326. // device del módem QMI.
  1327. const boardWanIsAModem = `{"network":{"lan":{"ports":["lan1","lan2"],"protocol":"static"},` +
  1328. `"wan":{"device":"/dev/cdc-wdm0","protocol":"qmi"}}}`
  1329. func TestParsePortStatesTipoYConduit(t *testing.T) {
  1330. states := ParsePortStates(portStatesDSASwitch)
  1331. byName := map[string]PortState{}
  1332. for _, s := range states {
  1333. byName[s.Name] = s
  1334. }
  1335. if got := byName["lan1"]; got.Conduit != "eth0" || got.Type != ARPHRDEther {
  1336. t.Fatalf("lan1: %+v", got)
  1337. }
  1338. if got := byName["eth0"]; got.Conduit != "" {
  1339. t.Fatalf("eth0 no cuelga de nadie: %+v", got)
  1340. }
  1341. if got := byName["wwan0"]; got.Type == ARPHRDEther {
  1342. t.Fatalf("wwan0 no es ethernet: %+v", got)
  1343. }
  1344. // Forma antigua de tres campos: sin tipo ni conduit, y nada se descarta.
  1345. old := ParsePortStates("lan1 up 1000\neth0 up 2500\n")
  1346. if len(old) != 2 || old[0].Type != 0 || old[0].Conduit != "" {
  1347. t.Fatalf("tres campos: %+v", old)
  1348. }
  1349. if ports := BuildEthPorts(nil, old, nil, nil, ""); len(ports) != 2 {
  1350. t.Fatalf("tres campos no debe esconder bocas: %+v", ports)
  1351. }
  1352. }
  1353. func TestBuildEthPortsSoloLasBocasReales(t *testing.T) {
  1354. layout, err := ParsePortLayout(boardWanIsAModem)
  1355. if err != nil {
  1356. t.Fatalf("layout: %v", err)
  1357. }
  1358. ports := BuildEthPorts(layout, ParsePortStates(portStatesDSASwitch), nil, nil, "")
  1359. ids := []string{}
  1360. for _, p := range ports {
  1361. ids = append(ids, p.ID)
  1362. }
  1363. // Antes salían cuatro: WAN (el módem, nunca conectada), LAN 1, LAN 2 y
  1364. // ETH 0 (el puerto de CPU del switch).
  1365. if len(ids) != 2 || ids[0] != "lan1" || ids[1] != "lan2" {
  1366. t.Fatalf("bocas: %v", ids)
  1367. }
  1368. }
  1369. func TestBuildEthPortsUplinkNoEthernet(t *testing.T) {
  1370. // board.json puede nombrar como WAN una interfaz que existe pero no es
  1371. // ethernet (el netdev del módem); tampoco es una boca.
  1372. layout := []PortLayout{
  1373. {ID: "wan", Name: "wwan0", Label: "WAN", Role: "wan"},
  1374. {ID: "lan1", Name: "lan1", Label: "LAN 1", Role: "lan"},
  1375. }
  1376. ports := BuildEthPorts(layout, ParsePortStates(portStatesDSASwitch), nil, nil, "")
  1377. ids := map[string]bool{}
  1378. for _, p := range ports {
  1379. ids[p.ID] = true
  1380. }
  1381. if ids["wan"] || ids["wwan0"] {
  1382. t.Fatalf("el módem no es una boca: %+v", ports)
  1383. }
  1384. // lan2 no está en el layout pero sí en /sys: entra como extra.
  1385. if len(ids) != 2 || !ids["lan1"] || !ids["lan2"] {
  1386. t.Fatalf("bocas: %+v", ports)
  1387. }
  1388. }
  1389. func TestBuildEthPortsMantieneEthSinSwitch(t *testing.T) {
  1390. // Caja sin switch DSA (x86, BPI-R4): nadie declara eth0 como puerto de
  1391. // CPU, así que sigue siendo una boca. Sin layout, el fallback toma eth1
  1392. // como WAN (comportamiento previo, aquí solo interesa que eth0 siga).
  1393. states := ParsePortStates("eth0 up 1000 - 1 -\neth1 up 2500 - 1 -\nlo unknown -1 - 772 -\n")
  1394. ports := BuildEthPorts(nil, states, nil, nil, "")
  1395. ids := map[string]bool{}
  1396. for _, p := range ports {
  1397. ids[p.ID] = true
  1398. }
  1399. if len(ids) != 2 || !ids["eth0"] {
  1400. t.Fatalf("eth0 sin switch debe seguir siendo boca: %+v", ports)
  1401. }
  1402. }
  1403. func TestBuildEthPortsDropsBroadcomGhosts(t *testing.T) {
  1404. // RT-AX92U (Asuswrt/Broadcom, no board.json layout): eth0 is the uplink to
  1405. // the core switch, eth1-4 are real LAN ports (unplugged, so down + speed 0),
  1406. // and eth5/6/7 are internal ghost interfaces the driver exposes with
  1407. // operstate dormant/unknown and unreadable speed. They are not front-panel
  1408. // ports and must not appear in the panel.
  1409. states := ParsePortStates(
  1410. "bcmsw down -1 - 1 -\n" +
  1411. "br0 up -1 - 1 eth0\n" +
  1412. "eth0 up 1000 - 1 -\n" +
  1413. "eth1 down 0 - 1 -\n" +
  1414. "eth2 down 0 - 1 -\n" +
  1415. "eth3 down 0 - 1 -\n" +
  1416. "eth4 down 0 - 1 -\n" +
  1417. "eth5 dormant -1 - 1 -\n" +
  1418. "eth6 unknown -1 - 1 -\n" +
  1419. "eth7 unknown -1 - 1 -\n")
  1420. ports := BuildEthPorts(nil, states, nil, nil, "eth0")
  1421. ids := map[string]bool{}
  1422. for _, p := range ports {
  1423. ids[p.ID] = true
  1424. ids[p.Iface] = true
  1425. }
  1426. for _, want := range []string{"eth1", "eth2", "eth3", "eth4"} {
  1427. if !ids[want] {
  1428. t.Fatalf("real unplugged port %s was dropped: %+v", want, ports)
  1429. }
  1430. }
  1431. for _, ghost := range []string{"eth5", "eth6", "eth7"} {
  1432. if ids[ghost] {
  1433. t.Fatalf("Broadcom ghost interface %s must not be a panel port: %+v", ghost, ports)
  1434. }
  1435. }
  1436. // eth0..eth4 → WAN(eth0) + ETH 1..ETH 4 = 5 entries.
  1437. if len(ports) != 5 {
  1438. t.Fatalf("want 5 ports, got %d: %+v", len(ports), ports)
  1439. }
  1440. }
  1441. // dumpUplinkNotNamedWan: forma de `ubus call network.interface dump` en una placa cuyo enlace
  1442. // recortada a lo que mira el parser y con la IP pública cambiada. El uplink
  1443. // vivo es un PPPoE llamado "isp" sobre la boca lan1; la interfaz que SÍ se
  1444. // llama "wan" es el módem celular, ocioso pero con up=true y sin ruta.
  1445. const dumpUplinkNotNamedWan = `{"interface":[
  1446. {"interface":"lan","up":true,"proto":"static","l3_device":"br-lan.10","device":"br-lan.10",
  1447. "ipv4-address":[{"address":"192.0.2.1","mask":24}],"route":[]},
  1448. {"interface":"wan","up":true,"proto":"qmi","l3_device":"wwan0",
  1449. "ipv4-address":[],"route":[],"dns-server":[]},
  1450. {"interface":"isp","up":true,"proto":"pppoe","l3_device":"pppoe-isp","device":"lan1",
  1451. "ipv4-address":[{"address":"203.0.113.45","mask":32,"ptpaddress":"198.51.100.1"}],
  1452. "route":[{"target":"0.0.0.0","mask":0,"nexthop":"198.51.100.1"}],
  1453. "dns-server":["198.51.100.53","198.51.100.54"]}]}`
  1454. func TestParseWanStatusDumpEligeElUplinkVivo(t *testing.T) {
  1455. info := ParseWanStatus([]byte(dumpUplinkNotNamedWan))
  1456. if info.Proto != "pppoe" || info.Device != "pppoe-isp" {
  1457. t.Fatalf("no eligió el PPPoE vivo: %+v", info)
  1458. }
  1459. if info.Port != "lan1" {
  1460. t.Fatalf("boca del uplink: %q, esperaba lan1", info.Port)
  1461. }
  1462. if info.IP != "203.0.113.45" || info.Gateway != "198.51.100.1" {
  1463. t.Fatalf("ip/gateway: %+v", info)
  1464. }
  1465. if len(info.DNS) != 2 {
  1466. t.Fatalf("dns: %+v", info.DNS)
  1467. }
  1468. }
  1469. func TestParseWanStatusDumpCaeALaLlamadaWan(t *testing.T) {
  1470. // Router normal con el enlace caído: ninguna tiene ruta por defecto, así
  1471. // que manda la que se llama "wan" (WAN caída, no router sin WAN).
  1472. dump := `{"interface":[{"interface":"lan","up":true,"proto":"static","route":[]},
  1473. {"interface":"wan","up":false,"proto":"dhcp","l3_device":"eth1","device":"eth1","route":[]}]}`
  1474. info := ParseWanStatus([]byte(dump))
  1475. if info.Proto != "dhcp" || info.Port != "eth1" {
  1476. t.Fatalf("fallback a la llamada wan: %+v", info)
  1477. }
  1478. // Sin ninguna interfaz utilizable (AP puro) → vacío.
  1479. if got := ParseWanStatus([]byte(`{"interface":[{"interface":"lan","up":true,"route":[]}]}`)); got.Proto != "" || got.Port != "" {
  1480. t.Fatalf("AP sin wan: %+v", got)
  1481. }
  1482. }
  1483. func TestBuildEthPortsMarcaLaBocaDelUplink(t *testing.T) {
  1484. layout, err := ParsePortLayout(boardWanIsAModem)
  1485. if err != nil {
  1486. t.Fatalf("layout: %v", err)
  1487. }
  1488. uplink := ParseWanStatus([]byte(dumpUplinkNotNamedWan)).Port
  1489. ports := BuildEthPorts(layout, ParsePortStates(portStatesDSASwitch), nil, nil, uplink)
  1490. if len(ports) != 2 {
  1491. t.Fatalf("bocas: %+v", ports)
  1492. }
  1493. // lan1 lleva el PPPoE: sale como WAN sin moverse de sitio.
  1494. if ports[0].ID != "wan" || ports[0].Label != "WAN" {
  1495. t.Fatalf("la boca del uplink debía salir como WAN: %+v", ports[0])
  1496. }
  1497. if ports[1].ID != "lan2" {
  1498. t.Fatalf("el resto no se toca: %+v", ports[1])
  1499. }
  1500. }
  1501. func TestBuildEthPortsNoPisaUnaWanDelLayout(t *testing.T) {
  1502. // Guard del #1482: el layout trae una boca WAN cuyo netdev se llama
  1503. // literalmente "wan" (sin identidad física a la que volver), así que el
  1504. // uplink discrepante NO la pisa: mejor la presentación del layout que
  1505. // duplicar el id "wan".
  1506. layout := []PortLayout{
  1507. {ID: "wan", Name: "wan", Label: "WAN", Role: "wan"},
  1508. {ID: "lan1", Name: "lan1", Label: "LAN 1", Role: "lan"},
  1509. }
  1510. states := ParsePortStates("wan up 1000 - 1 -\nlan1 up 1000 - 1 -\n")
  1511. ports := BuildEthPorts(layout, states, nil, nil, "lan1")
  1512. if len(ports) != 2 || ports[0].ID != "wan" || ports[1].ID != "lan1" {
  1513. t.Fatalf("bocas: %+v", ports)
  1514. }
  1515. }
  1516. func TestBuildEthPortsElUplinkPisaLaWanDelLayout(t *testing.T) {
  1517. // #1482: board.json estático con la WAN en eth0 (management) mientras el
  1518. // PPPoE sale por eth2: manda el runtime. La boca del uplink pasa a WAN y
  1519. // la del layout vuelve a su netdev (ETH 0), sin moverse de su sitio.
  1520. layout := []PortLayout{
  1521. {ID: "wan", Name: "eth0", Label: "WAN", Role: "wan"},
  1522. {ID: "lan1", Name: "eth1", Label: "LAN 1", Role: "lan"},
  1523. {ID: "lan2", Name: "eth2", Label: "LAN 2", Role: "lan"},
  1524. }
  1525. states := ParsePortStates("eth0 up 1000 - 1 -\neth1 up 1000 - 1 -\neth2 up 2500 - 1 -\n")
  1526. ports := BuildEthPorts(layout, states, nil, nil, "eth2")
  1527. if len(ports) != 3 {
  1528. t.Fatalf("bocas: %+v", ports)
  1529. }
  1530. if ports[0].ID != "eth0" || ports[0].Label != "ETH 0" {
  1531. t.Fatalf("la WAN del layout debía volver a su netdev: %+v", ports[0])
  1532. }
  1533. if ports[1].ID != "lan1" {
  1534. t.Fatalf("el resto no se toca: %+v", ports[1])
  1535. }
  1536. if ports[2].ID != "wan" || ports[2].Label != "WAN" {
  1537. t.Fatalf("la boca del uplink debía salir como WAN: %+v", ports[2])
  1538. }
  1539. // De acuerdo con el layout: el uplink cae en la propia WAN y nada cambia.
  1540. ports = BuildEthPorts(layout, states, nil, nil, "eth0")
  1541. if ports[0].ID != "wan" || ports[0].Label != "WAN" || ports[2].ID != "lan2" {
  1542. t.Fatalf("uplink acorde al layout no debía tocar nada: %+v", ports)
  1543. }
  1544. }
  1545. func TestBuildEthPortsUplinkEtiquetado(t *testing.T) {
  1546. // Uplink sobre VLAN ("lan1.7"): la boca es la de debajo.
  1547. layout := []PortLayout{{ID: "lan1", Name: "lan1", Label: "LAN 1", Role: "lan"}}
  1548. states := ParsePortStates("lan1 up 1000 - 1 -\n")
  1549. ports := BuildEthPorts(layout, states, nil, nil, "lan1.7")
  1550. if len(ports) != 1 || ports[0].ID != "wan" {
  1551. t.Fatalf("bocas: %+v", ports)
  1552. }
  1553. }
  1554. // A neighbour table with every state that matters: what the kernel has
  1555. // confirmed, and what it merely remembers.
  1556. func TestParseIPNeighSeparatesConfirmedFromRemembered(t *testing.T) {
  1557. out := strings.Join([]string{
  1558. "192.0.2.10 dev br-lan lladdr 02:00:00:00:00:10 REACHABLE",
  1559. "192.0.2.11 dev br-lan lladdr 02:00:00:00:00:11 STALE",
  1560. "192.0.2.12 dev br-lan lladdr 02:00:00:00:00:12 DELAY",
  1561. "192.0.2.13 dev br-lan lladdr 02:00:00:00:00:13 PERMANENT",
  1562. "192.0.2.14 dev br-lan FAILED",
  1563. "192.0.2.15 dev br-lan lladdr 02:00:00:00:00:15 FAILED",
  1564. "192.0.2.16 dev br-lan lladdr 00:00:00:00:00:00 REACHABLE",
  1565. "not-an-ip dev br-lan lladdr 02:00:00:00:00:17 REACHABLE",
  1566. }, "\n")
  1567. arp, stale := ParseIPNeigh(out)
  1568. if len(arp) != 5 {
  1569. t.Fatalf("arp: %+v", arp)
  1570. }
  1571. if arp["02:00:00:00:00:10"] != "192.0.2.10" || arp["02:00:00:00:00:11"] != "192.0.2.11" {
  1572. t.Fatalf("addresses: %+v", arp)
  1573. }
  1574. // A stale entry still resolves an IP; it just proves nothing.
  1575. for _, mac := range []string{"02:00:00:00:00:11", "02:00:00:00:00:15"} {
  1576. if !stale[mac] {
  1577. t.Fatalf("%s should be stale: %+v", mac, stale)
  1578. }
  1579. }
  1580. for _, mac := range []string{"02:00:00:00:00:10", "02:00:00:00:00:12", "02:00:00:00:00:13"} {
  1581. if stale[mac] {
  1582. t.Fatalf("%s is confirmed: %+v", mac, stale)
  1583. }
  1584. }
  1585. // An entry with no lladdr, a null MAC or a broken address is not a host.
  1586. if _, ok := arp["00:00:00:00:00:00"]; ok {
  1587. t.Fatalf("null MAC: %+v", arp)
  1588. }
  1589. if _, ok := arp["02:00:00:00:00:17"]; ok {
  1590. t.Fatalf("invalid IP: %+v", arp)
  1591. }
  1592. }
  1593. // One confirmed address is enough for a host with several of them, whatever
  1594. // order the table lists them in.
  1595. func TestParseIPNeighConfirmedWinsOverStale(t *testing.T) {
  1596. for _, out := range []string{
  1597. "192.0.2.20 dev br-lan lladdr 02:00:00:00:00:20 STALE\n" +
  1598. "192.0.2.21 dev br-lan lladdr 02:00:00:00:00:20 REACHABLE",
  1599. "192.0.2.21 dev br-lan lladdr 02:00:00:00:00:20 REACHABLE\n" +
  1600. "192.0.2.20 dev br-lan lladdr 02:00:00:00:00:20 STALE",
  1601. } {
  1602. arp, stale := ParseIPNeigh(out)
  1603. if stale["02:00:00:00:00:20"] {
  1604. t.Fatalf("a confirmed address must settle the host: %+v", stale)
  1605. }
  1606. if arp["02:00:00:00:00:20"] != "192.0.2.21" {
  1607. t.Fatalf("the confirmed address should be the one kept: %+v", arp)
  1608. }
  1609. }
  1610. }
  1611. func TestParseIPNeighOnGarbage(t *testing.T) {
  1612. arp, stale := ParseIPNeigh("ip: command not found\n\n")
  1613. if len(arp) != 0 || len(stale) != 0 {
  1614. t.Fatalf("garbage: %+v %+v", arp, stale)
  1615. }
  1616. }
  1617. // uciDhcpHosts: the shape `uci show dhcp` prints for host entries, with an
  1618. // anonymous section, a named one, a list of MACs (GL firmware) and an entry
  1619. // with no name. The grep in CmdDhcpReservations also lets through options of
  1620. // other sections, so one is included to prove they are ignored.
  1621. const uciDhcpHosts = `dhcp.@dnsmasq[0].domain='lan'
  1622. dhcp.@host[0]=host
  1623. dhcp.@host[0].name='printer'
  1624. dhcp.@host[0].mac='02:00:00:00:00:01'
  1625. dhcp.@host[0].ip='192.0.2.10'
  1626. dhcp.cfg0abc12=host
  1627. dhcp.cfg0abc12.name='nas'
  1628. dhcp.cfg0abc12.mac='02:00:00:00:00:02' '02:00:00:00:00:03'
  1629. dhcp.cfg0abc12.ip='192.0.2.20'
  1630. dhcp.@host[2]=host
  1631. dhcp.@host[2].mac='02:00:00:00:00:04'
  1632. dhcp.lan=dhcp
  1633. dhcp.lan.interface='lan'`
  1634. func TestParseDhcpReservations(t *testing.T) {
  1635. res := ParseDhcpReservations(uciDhcpHosts)
  1636. if len(res) != 4 {
  1637. t.Fatalf("reservations: %+v", res)
  1638. }
  1639. // Sorted by MAC, uppercase like the leases.
  1640. if res[0].MAC != "02:00:00:00:00:01" || res[0].Name != "printer" || res[0].IP != "192.0.2.10" {
  1641. t.Fatalf("first: %+v", res[0])
  1642. }
  1643. // Both MACs of the list entry share its name and address.
  1644. if res[1].Name != "nas" || res[2].Name != "nas" || res[1].IP != "192.0.2.20" {
  1645. t.Fatalf("mac list: %+v %+v", res[1], res[2])
  1646. }
  1647. // An entry without a name is still a reservation (it pins an address).
  1648. if res[3].MAC != "02:00:00:00:00:04" || res[3].Name != "" {
  1649. t.Fatalf("nameless: %+v", res[3])
  1650. }
  1651. if got := ParseDhcpReservations(""); len(got) != 0 {
  1652. t.Fatalf("empty output: %+v", got)
  1653. }
  1654. }
  1655. func TestParseMdnsHosts(t *testing.T) {
  1656. // Shape of `ubus call umdns hosts`: the ".local" name keys an object
  1657. // with the addresses it resolved to.
  1658. raw := `{"laptop-01.local":{"ipv4":"192.0.2.51","ipv6":"fe80::1"},
  1659. "printer.local":{"ipv4":"192.0.2.10"},
  1660. "no-address.local":{"ipv6":"fe80::2"}}`
  1661. hosts := ParseMdnsHosts([]byte(raw))
  1662. if len(hosts) != 2 {
  1663. t.Fatalf("hosts: %+v", hosts)
  1664. }
  1665. // Keyed by IP, and the mDNS suffix is dropped.
  1666. if hosts["192.0.2.51"] != "laptop-01" || hosts["192.0.2.10"] != "printer" {
  1667. t.Fatalf("hosts: %+v", hosts)
  1668. }
  1669. // An entry with no IPv4 cannot name anything.
  1670. for _, name := range hosts {
  1671. if name == "no-address" {
  1672. t.Fatalf("entry without ipv4 should be skipped: %+v", hosts)
  1673. }
  1674. }
  1675. if got := ParseMdnsHosts([]byte("{}")); len(got) != 0 {
  1676. t.Fatalf("empty: %+v", got)
  1677. }
  1678. if got := ParseMdnsHosts([]byte("not json")); len(got) != 0 {
  1679. t.Fatalf("broken json must not panic: %+v", got)
  1680. }
  1681. }
  1682. // #1485: la interfaz de cada entrada ARP. Con ella el servidor distingue el
  1683. // ARP aprendido en el puerto WAN (primer salto del enlace, ONT en bridge tras
  1684. // PPPoE) del de la LAN.
  1685. func TestParseIPNeighDevs(t *testing.T) {
  1686. out := `192.168.1.1 dev eth2 lladdr C0:49:43:A3:D1:34 REACHABLE
  1687. 192.168.1.60 dev br-lan lladdr AA:BB:CC:00:00:01 STALE
  1688. 192.168.1.61 dev br-lan lladdr AA:BB:CC:00:00:02 DELAY
  1689. 192.168.1.70 dev br-lan FAILED`
  1690. devs := ParseIPNeighDevs(out)
  1691. if got := devs["C0:49:43:A3:D1:34"]; got != "eth2" {
  1692. t.Fatalf("ONT dev %q, want eth2", got)
  1693. }
  1694. // DELAY/REACHABLE cuentan como confirmadas; STALE no prueba presencia.
  1695. if got := devs["AA:BB:CC:00:00:02"]; got != "br-lan" {
  1696. t.Fatalf("DELAY dev %q, want br-lan", got)
  1697. }
  1698. if _, ok := devs["AA:BB:CC:00:00:01"]; ok {
  1699. t.Fatalf("una entrada STALE no debe aportar interfaz")
  1700. }
  1701. if len(devs) != 2 {
  1702. t.Fatalf("devs %v, want 2 entradas", devs)
  1703. }
  1704. }
  1705. // Fallback /proc/net/arp: misma idea con las columnas del fichero.
  1706. func TestParseArpDevs(t *testing.T) {
  1707. out := `IP address HW type Flags HW address Mask Device
  1708. 192.168.1.1 0x1 0x2 c0:49:43:a3:d1:34 * eth2
  1709. 192.168.1.60 0x1 0x2 aa:bb:cc:00:00:01 * br-lan
  1710. 192.168.1.61 0x1 0x0 00:00:00:00:00:00 * br-lan`
  1711. devs := ParseArpDevs(out)
  1712. if devs["C0:49:43:A3:D1:34"] != "eth2" {
  1713. t.Fatalf("ONT dev %q, want eth2", devs["C0:49:43:A3:D1:34"])
  1714. }
  1715. if devs["AA:BB:CC:00:00:01"] != "br-lan" {
  1716. t.Fatalf("cliente dev %q, want br-lan", devs["AA:BB:CC:00:00:01"])
  1717. }
  1718. if len(devs) != 2 {
  1719. t.Fatalf("devs %v, want 2 (la incompleta se descarta)", devs)
  1720. }
  1721. }
  1722. // #2275: la direccion global del uplink viaja en el WanInfo. netifd lista en
  1723. // `ipv6-address` la link-local, la ULA del router y la global del ISP a la
  1724. // vez, asi que quedarse con la primera seria publicar la interfaz equivocada.
  1725. func TestParseWanStatusIPv6(t *testing.T) {
  1726. raw := `{"up":true,"proto":"dhcp","l3_device":"wan","device":"eth0.2",` +
  1727. `"ipv4-address":[{"address":"84.122.5.9","mask":24}],` +
  1728. `"ipv6-address":[` +
  1729. `{"address":"fe80::1","mask":64,"preferred":true,"valid":true},` +
  1730. `{"address":"fd00::1","mask":64,"preferred":9000,"valid":9000},` +
  1731. `{"address":"2a0c:5a80:1234::9","mask":64,"preferred":7200,"valid":7200}],` +
  1732. `"route":[{"target":"0.0.0.0","mask":0,"nexthop":"84.122.5.1"}]}`
  1733. info := ParseWanStatus([]byte(raw))
  1734. if info.IPv6 != "2a0c:5a80:1234::9" {
  1735. t.Fatalf("ipv6=%q, esperaba la global del SP", info.IPv6)
  1736. }
  1737. // Un `preferred` booleano en el dump no puede tirar el resto del parseo.
  1738. if info.IP != "84.122.5.9" || info.Gateway != "84.122.5.1" {
  1739. t.Fatalf("el dump con preferred booleano perdio el lado v4: %+v", info)
  1740. }
  1741. }
  1742. func TestParseWanStatusIPv6SoloNoGlobales(t *testing.T) {
  1743. raw := `{"interface":"wan","up":true,"proto":"dhcp","l3_device":"eth0.2",` +
  1744. `"ipv4-address":[{"address":"192.168.9.7","mask":24}],` +
  1745. `"ipv6-address":[{"address":"fe80::1","mask":64},` +
  1746. `{"address":"fc00::1","mask":64,"preferred":3600}]}`
  1747. info := ParseWanStatus([]byte(raw))
  1748. if info.IPv6 != "" {
  1749. t.Fatalf("ipv6=%q, sin global el campo debe quedar vacio", info.IPv6)
  1750. }
  1751. if info.IP != "192.168.9.7" {
  1752. t.Fatalf("ip=%q, el lado v4 no cambia", info.IP)
  1753. }
  1754. }
  1755. // Una unidad solo v6 (o un ISP con CGNAT y sin v4) conserva la direccion.
  1756. func TestParseWanStatusSoloIPv6(t *testing.T) {
  1757. raw := `{"interface":"wan","up":true,"proto":"dhcpv6","l3_device":"eth0.2",` +
  1758. `"ipv6-address":[{"address":"2a0c:5a80:1234::9","mask":64,"preferred":7200}]}`
  1759. info := ParseWanStatusPreferring([]byte(raw), "wan")
  1760. if info.IPv6 != "2a0c:5a80:1234::9" {
  1761. t.Fatalf("ipv6=%q", info.IPv6)
  1762. }
  1763. if info.IP != "" {
  1764. t.Fatalf("ip=%q, no hay v4 que publicar", info.IP)
  1765. }
  1766. }
  1767. // Deprecada (preferred a cero) solo como ultimo recurso: primero se prefiere
  1768. // una viva, y si no queda ninguna se publica la deprecada en vez de nada.
  1769. func TestParseWanStatusIPv6Deprecada(t *testing.T) {
  1770. both := `{"interface":"wan","up":true,"proto":"dhcp","l3_device":"eth0.2",` +
  1771. `"ipv6-address":[{"address":"2a0c:5a80:1111::1","mask":64,"preferred":0},` +
  1772. `{"address":"2a0c:5a80:2222::1","mask":64,"preferred":1800}]}`
  1773. if got := ParseWanStatus([]byte(both)).IPv6; got != "2a0c:5a80:2222::1" {
  1774. t.Fatalf("ipv6=%q, esperaba la viva y no la deprecada", got)
  1775. }
  1776. only := `{"interface":"wan","up":true,"proto":"dhcp","l3_device":"eth0.2",` +
  1777. `"ipv6-address":[{"address":"2a0c:5a80:1111::1","mask":64,"preferred":0}]}`
  1778. if got := ParseWanStatus([]byte(only)).IPv6; got != "2a0c:5a80:1111::1" {
  1779. t.Fatalf("ipv6=%q, la deprecada se publica cuando no hay otra", got)
  1780. }
  1781. falsy := `{"interface":"wan","up":true,"proto":"dhcp","l3_device":"eth0.2",` +
  1782. `"ipv6-address":[{"address":"2a0c:5a80:1111::1","mask":64,"preferred":false},` +
  1783. `{"address":"2a0c:5a80:3333::1","mask":64,"preferred":true}]}`
  1784. if got := ParseWanStatus([]byte(falsy)).IPv6; got != "2a0c:5a80:3333::1" {
  1785. t.Fatalf("ipv6=%q, `preferred:false` no puede ganar a una viva", got)
  1786. }
  1787. }
  1788. // El hijo que netifd crea para un modem lleva las direcciones que el padre no
  1789. // tiene: si no se copian, el uplink reporta v4 sin v6.
  1790. func TestWithChildFactsCopiaIPv6(t *testing.T) {
  1791. parent := ifaceStatus{Interface: "wwan", Dynamic: true, L3Device: "wwan0"}
  1792. child := ifaceStatus{Interface: "wwan_6", Dynamic: true, L3Device: "wwan0",
  1793. IPV6: []ubusIPv6{{Address: "2a0c:5a80:1234::9", Preferred: []byte("7200")}}}
  1794. got := withChildFacts(child, []ifaceStatus{parent})
  1795. if len(got.IPV6) != 1 || got.IPV6[0].Address != "2a0c:5a80:1234::9" {
  1796. t.Fatalf("ipv6 no copiada del padre: %+v", got.IPV6)
  1797. }
  1798. }