net_ifaces.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // net_ifaces.go — parseo de las interfaces lógicas en ejecución de OpenWrt
  2. // (`ubus call network.interface dump`) para el descubrimiento de clientes por
  3. // red.
  4. package probe
  5. import "encoding/json"
  6. // NetIface representa una interfaz lógica de OpenWrt reportada por netifd
  7. // (lan, wan, wan6, wwan, wg0...), con su estado y los dispositivos Linux que
  8. // tiene asociados en este momento.
  9. type NetIface struct {
  10. Name string `json:"name"`
  11. Proto string `json:"proto,omitempty"`
  12. Up bool `json:"up"`
  13. Devices []string `json:"devices,omitempty"` // l3_device, luego device; únicos y no vacíos
  14. }
  15. // InterfaceDump agrupa el uplink activo y las interfaces lógicas utilizables
  16. // extraídas de una única lectura de `ubus call network.interface dump`.
  17. type InterfaceDump struct {
  18. Wan WanInfo
  19. Ifaces []NetIface
  20. }
  21. // ParseInterfaceDump decodifica una sola vez la salida de `ubus call
  22. // network.interface dump` (`{"interface":[...]}`) y devuelve el uplink activo
  23. // (prefiriendo preferred si viene indicado) junto con las interfaces lógicas
  24. // utilizables (sin dinámicas ni loopback, manteniendo el orden del dump).
  25. func ParseInterfaceDump(raw []byte, preferred string) InterfaceDump {
  26. if len(raw) == 0 {
  27. return InterfaceDump{}
  28. }
  29. var dump struct {
  30. Interface []ifaceStatus `json:"interface"`
  31. }
  32. if err := json.Unmarshal(raw, &dump); err != nil || len(dump.Interface) == 0 {
  33. return InterfaceDump{}
  34. }
  35. var res InterfaceDump
  36. if s, ok := pickUplinkPreferring(dump.Interface, preferred); ok {
  37. res.Wan = wanInfoFrom(s)
  38. }
  39. out := make([]NetIface, 0, len(dump.Interface))
  40. for _, it := range dump.Interface {
  41. if it.Interface == "" || it.Dynamic {
  42. continue
  43. }
  44. if it.Interface == "loopback" || it.L3Device == "lo" || it.Device == "lo" {
  45. continue
  46. }
  47. var devs []string
  48. if it.L3Device != "" {
  49. devs = append(devs, it.L3Device)
  50. }
  51. if it.Device != "" && it.Device != it.L3Device {
  52. devs = append(devs, it.Device)
  53. }
  54. out = append(out, NetIface{
  55. Name: it.Interface,
  56. Proto: it.Proto,
  57. Up: it.Up,
  58. Devices: devs,
  59. })
  60. }
  61. if len(out) > 0 {
  62. res.Ifaces = out
  63. }
  64. return res
  65. }