probe_test.go 66 KB

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