4
0

vlan_network.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. package probe
  2. import (
  3. "fmt"
  4. "net"
  5. "regexp"
  6. "strconv"
  7. "strings"
  8. )
  9. // uciSection is one `network.<name>` section of `uci show network`, with the
  10. // section type kept under "@type". Anonymous sections keep their printed name
  11. // (@device[0]) so the declaration order is preserved.
  12. type uciSection map[string]string
  13. // uciNetworkSections splits `uci show network` into its sections, in the order
  14. // the configuration declares them. Shared by the VLAN view (#1757) and the
  15. // networks view (#1889), which read the same configuration for different
  16. // purposes and must never disagree about what it says.
  17. func uciNetworkSections(out string) (map[string]uciSection, []string) {
  18. sections := map[string]uciSection{}
  19. order := []string{}
  20. for _, line := range strings.Split(out, "\n") {
  21. line = strings.TrimSpace(line)
  22. if !strings.HasPrefix(line, "network.") {
  23. continue
  24. }
  25. key, val, ok := strings.Cut(strings.TrimPrefix(line, "network."), "=")
  26. if !ok {
  27. continue
  28. }
  29. val = strings.Trim(val, "'")
  30. name, attr, isAttr := strings.Cut(key, ".")
  31. if _, seen := sections[name]; !seen {
  32. sections[name] = uciSection{}
  33. order = append(order, name)
  34. }
  35. if !isAttr {
  36. sections[name]["@type"] = val
  37. continue
  38. }
  39. sections[name][attr] = val
  40. }
  41. return sections, order
  42. }
  43. // vlanSubifRe matches an 802.1Q subinterface: the parent device and the VLAN
  44. // id in its name, the way Linux and OpenWrt build them (eth0.666).
  45. var vlanSubifRe = regexp.MustCompile(`^([^.]+)\.(\d{1,4})$`)
  46. // ParseUciNetworkVlans derives the VLANs of a router that segments with
  47. // 802.1Q subinterfaces instead of bridge VLAN filtering (#1757).
  48. //
  49. // `bridge vlan show` only knows about bridges with vlan_filtering enabled. A
  50. // box that creates one bridge per network and feeds it a tagged subinterface
  51. // (eth0.999 into br-iot) reports every bridge on its default VLAN 1, so the
  52. // kernel view is blind to the real segmentation and the panel shows a flat
  53. // list of ports. The configuration is the only place that says which VLAN a
  54. // bridge carries, which interface it belongs to and what subnet it serves, so
  55. // it is read as a source of its own and merged with the kernel output, never
  56. // as a fallback.
  57. func ParseUciNetworkVlans(out string) []VlanPort {
  58. sections, order := uciNetworkSections(out)
  59. // Interfaces first: they carry the name and the subnet of whatever device
  60. // they sit on.
  61. type netinfo struct {
  62. label string
  63. subnet string
  64. }
  65. byDevice := map[string]netinfo{}
  66. for _, name := range order {
  67. s := sections[name]
  68. if s["@type"] != "interface" {
  69. continue
  70. }
  71. dev := s["device"]
  72. if dev == "" {
  73. dev = s["ifname"]
  74. }
  75. if dev == "" {
  76. continue
  77. }
  78. if _, seen := byDevice[dev]; seen {
  79. continue
  80. }
  81. byDevice[dev] = netinfo{label: name, subnet: vlanSubnet(s["ipaddr"], s["netmask"])}
  82. }
  83. byPort := map[string][]VlanEntry{}
  84. portOrder := []string{}
  85. add := func(port string, e VlanEntry) {
  86. if _, seen := byPort[port]; !seen {
  87. portOrder = append(portOrder, port)
  88. }
  89. byPort[port] = append(byPort[port], e)
  90. }
  91. for _, name := range order {
  92. s := sections[name]
  93. // The section type is what matters, not the header: a named device
  94. // section prints as `network.x=device`, an anonymous one as
  95. // `network.@device[0]=device`, and both declare type 'bridge'.
  96. if s["type"] != "bridge" {
  97. continue
  98. }
  99. bridge := s["name"]
  100. if bridge == "" {
  101. continue
  102. }
  103. info := byDevice[bridge]
  104. native := true
  105. for _, port := range splitUciList(s["ports"]) {
  106. m := vlanSubifRe.FindStringSubmatch(port)
  107. if m == nil {
  108. continue
  109. }
  110. vid, err := strconv.Atoi(m[2])
  111. if err != nil || vid < 1 || vid > 4094 {
  112. continue
  113. }
  114. native = false
  115. // The bridge carries the VLAN the subinterface tags on the parent
  116. // port: the members of the VLAN are the ports of the bridge.
  117. add(bridge, VlanEntry{ID: vid, PVID: true, Name: info.label, Subnet: info.subnet})
  118. // The subinterface itself is the bridge port the forwarding
  119. // database reports for every device behind it, so it needs its own
  120. // entry: without it the topology has no way to colour a device that
  121. // hangs from eth0.999 (#1757).
  122. add(port, VlanEntry{ID: vid, PVID: true, Name: info.label, Subnet: info.subnet})
  123. add(m[1], VlanEntry{ID: vid, Tagged: true})
  124. }
  125. // No subinterface among the members: the bridge is a plain untagged
  126. // network, which still has a name and a subnet worth showing.
  127. if native {
  128. add(bridge, VlanEntry{ID: 1, PVID: true, Name: info.label, Subnet: info.subnet})
  129. }
  130. }
  131. // An interface bound straight to a subinterface, with no bridge in
  132. // between (eth0.50 for a PPPoE or a routed VLAN).
  133. for _, name := range order {
  134. s := sections[name]
  135. if s["@type"] != "interface" {
  136. continue
  137. }
  138. dev := s["device"]
  139. m := vlanSubifRe.FindStringSubmatch(dev)
  140. if m == nil {
  141. continue
  142. }
  143. vid, err := strconv.Atoi(m[2])
  144. if err != nil || vid < 1 || vid > 4094 {
  145. continue
  146. }
  147. add(dev, VlanEntry{ID: vid, PVID: true, Name: name, Subnet: vlanSubnet(s["ipaddr"], s["netmask"])})
  148. }
  149. res := make([]VlanPort, 0, len(portOrder))
  150. for _, port := range portOrder {
  151. res = append(res, VlanPort{Port: port, Vlans: byPort[port]})
  152. }
  153. return res
  154. }
  155. // MergeVlanPorts unions two views of the same VLAN tables, keeping the order
  156. // of the kernel one. Where both describe the same port and VLAN, the kernel
  157. // owns the flags (it is what the box is doing) and the declared view fills in
  158. // what the kernel cannot know: the name of the network and its subnet.
  159. func MergeVlanPorts(kernel, declared []VlanPort) []VlanPort {
  160. if len(declared) == 0 {
  161. return kernel
  162. }
  163. if len(kernel) == 0 {
  164. return labelVlanPorts(declared)
  165. }
  166. idx := make(map[string]int, len(kernel)+len(declared))
  167. out := make([]VlanPort, 0, len(kernel)+len(declared))
  168. for _, p := range kernel {
  169. idx[p.Port] = len(out)
  170. out = append(out, VlanPort{Port: p.Port, Vlans: append([]VlanEntry(nil), p.Vlans...)})
  171. }
  172. for _, p := range declared {
  173. if i, ok := idx[p.Port]; ok {
  174. out[i].Vlans = mergeVlanEntries(out[i].Vlans, p.Vlans)
  175. continue
  176. }
  177. idx[p.Port] = len(out)
  178. out = append(out, VlanPort{Port: p.Port, Vlans: append([]VlanEntry(nil), p.Vlans...)})
  179. }
  180. return labelVlanPorts(out)
  181. }
  182. // labelVlanPorts names the VLANs of the ports that only carry the id. The name
  183. // of a network is declared once, on the pseudo-port of its subinterface
  184. // (br_switch.777), while the ports that actually carry it (a radio AP, an
  185. // uplink) come from the kernel with the id and nothing else: the wifi panel of
  186. // a dumb AP showed "777" with no way to know which network that was (#1757).
  187. //
  188. // An id that names exactly one network on the whole box inherits that name.
  189. // Two different networks sharing a number stay unnamed: a wrong name is worse
  190. // than no name.
  191. func labelVlanPorts(ports []VlanPort) []VlanPort {
  192. names := map[int]map[string]bool{}
  193. subnets := map[int]map[string]bool{}
  194. note := func(m map[int]map[string]bool, id int, v string) {
  195. if v == "" {
  196. return
  197. }
  198. if m[id] == nil {
  199. m[id] = map[string]bool{}
  200. }
  201. m[id][v] = true
  202. }
  203. for _, p := range ports {
  204. for _, e := range p.Vlans {
  205. note(names, e.ID, e.Name)
  206. note(subnets, e.ID, e.Subnet)
  207. }
  208. }
  209. only := func(m map[int]map[string]bool, id int) string {
  210. if len(m[id]) != 1 {
  211. return ""
  212. }
  213. for v := range m[id] {
  214. return v
  215. }
  216. return ""
  217. }
  218. for i := range ports {
  219. for j := range ports[i].Vlans {
  220. e := &ports[i].Vlans[j]
  221. if e.Name == "" {
  222. e.Name = only(names, e.ID)
  223. }
  224. if e.Subnet == "" {
  225. e.Subnet = only(subnets, e.ID)
  226. }
  227. }
  228. }
  229. return ports
  230. }
  231. func mergeVlanEntries(kernel, declared []VlanEntry) []VlanEntry {
  232. // A bridge without vlan_filtering answers every port with VLAN 1. That is
  233. // not a wrong answer, it is answering a different question, and keeping
  234. // it beside the real VLANs of the port would leave them invisible.
  235. if vlanOnlyDefault(kernel) && vlanHasReal(declared) {
  236. return append([]VlanEntry(nil), declared...)
  237. }
  238. res := append([]VlanEntry(nil), kernel...)
  239. byID := make(map[int]int, len(res))
  240. for i, e := range res {
  241. byID[e.ID] = i
  242. }
  243. for _, d := range declared {
  244. i, ok := byID[d.ID]
  245. if !ok {
  246. byID[d.ID] = len(res)
  247. res = append(res, d)
  248. continue
  249. }
  250. if res[i].Name == "" {
  251. res[i].Name = d.Name
  252. }
  253. if res[i].Subnet == "" {
  254. res[i].Subnet = d.Subnet
  255. }
  256. }
  257. return res
  258. }
  259. // splitUciList splits a uci list value as `uci show` prints it: every item
  260. // quoted on the same line.
  261. func splitUciList(val string) []string {
  262. var out []string
  263. for _, part := range strings.Split(val, "' '") {
  264. // UCI imprime una lista como 'a' 'b' o como 'a b': las dos formas son
  265. // la misma lista y quedarse con la cadena entera inventaba un puerto
  266. // que no existe (#1889).
  267. for _, p := range strings.Fields(strings.Trim(part, "'")) {
  268. out = append(out, p)
  269. }
  270. }
  271. return out
  272. }
  273. // vlanSubnet renders an address and a netmask as CIDR. Any missing or
  274. // malformed piece is dropped rather than guessed.
  275. func vlanSubnet(ip, mask string) string {
  276. if ip == "" {
  277. return ""
  278. }
  279. m := net.ParseIP(mask).To4()
  280. if m == nil {
  281. return ip
  282. }
  283. ones, bits := net.IPMask(m).Size()
  284. if bits != 32 {
  285. return ip
  286. }
  287. return fmt.Sprintf("%s/%d", ip, ones)
  288. }
  289. // vlanOnlyDefault: the kernel reported nothing but the default VLAN.
  290. func vlanOnlyDefault(entries []VlanEntry) bool {
  291. if len(entries) == 0 {
  292. return false
  293. }
  294. for _, e := range entries {
  295. if e.ID != 1 {
  296. return false
  297. }
  298. }
  299. return true
  300. }
  301. // vlanHasReal: the view carries at least one VLAN other than the default.
  302. func vlanHasReal(entries []VlanEntry) bool {
  303. for _, e := range entries {
  304. if e.ID != 1 {
  305. return true
  306. }
  307. }
  308. return false
  309. }