4
0

probe_test.go 65 KB

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