# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import re from typing import Any def _split_uci_list(value: str) -> list[str]: """Split a ``uci show`` option value into its items. List options are rendered space-separated with each item quoted (``ports='lan1:t' 'lan2:t'``); scalar options carry a single quoted value. """ items = re.findall(r"'([^']*)'", value) if items: return [i for i in items if i] stripped = value.strip().strip("'") return [stripped] if stripped else [] def _uci_scalar(value: str) -> str: """Return the single unquoted value of a scalar ``uci show`` option.""" items = _split_uci_list(value) return items[0] if items else "" def _parse_port_spec(spec: str) -> tuple[str, bool]: """Return ``(port, is_tagged)`` for an OpenWrt bridge-vlan port spec. ``eth0:t`` is a tagged member; ``eth0:u*`` (untagged + PVID), ``eth0:*`` and a bare ``eth0`` are untagged members. """ port, _, flags = spec.partition(":") return port, "t" in flags def _uci_sections_of_type(uci_out: str, sec_type: str) -> list[dict[str, str]]: """Collect all ``network`` sections of *sec_type* from ``uci show network``. Handles both anonymous (``network.@bridge-vlan[0]``) and named (``network.apbr_vlan10``) sections — only the former was recognised before, so tool- or hand-provisioned bridges were invisible. Option values are kept raw (quotes included) so that list options stay distinguishable from scalars; use :func:`_uci_scalar` or :func:`_split_uci_list` to read them. """ decl = re.compile(rf"^network\.(\S+)={re.escape(sec_type)}$") option = re.compile(r"^network\.(\S+?)\.(\w+)=(.*)$") section_ids: set[str] = set() for line in uci_out.splitlines(): m = decl.match(line.strip()) if m: section_ids.add(m.group(1)) sections: dict[str, dict[str, str]] = {sid: {} for sid in section_ids} for line in uci_out.splitlines(): m = option.match(line.strip()) if m and m.group(1) in section_ids: sections[m.group(1)][m.group(2)] = m.group(3).strip() return list(sections.values()) class OpenWrtVLANMixin: """Mixin providing VLAN and network-instance NAPALM getters.""" def get_vlans(self) -> dict[str, Any]: """Return VLAN information with proper tagged/untagged separation. Uses ``bridge vlan show`` (DSA-based OpenWrt ≥21.02) for VLAN/port membership and ``uci show network`` for VLAN names. A port marked *PVID Egress Untagged* is an untagged member. All other VLAN memberships for the same port are tagged. Also detects legacy 802.1q sub-interfaces (``eth0.10`` etc.) from ``ip link show``. The parent interface (``eth0``) is added as a tagged member for every such VLAN. """ bridge_out = self._send_command("bridge vlan show") uci_out = self._send_command("uci show network") # vlan_id -> {name, tagged: [], untagged: []} vlans: dict[str, Any] = {} current_port: str | None = None for line in bridge_out.splitlines(): line_s = line.strip() if not line_s or line_s.lower().startswith("port"): continue # Port line: "eth0 1 PVID Egress Untagged" m = re.match(r"^(\S+)\s+(\d+)(.*)", line) if m: current_port = m.group(1) vlan_id = str(int(m.group(2))) flags = m.group(3).upper() vlans.setdefault(vlan_id, {"name": "", "tagged": [], "untagged": []}) if "PVID" in flags or "UNTAGGED" in flags: if current_port not in vlans[vlan_id]["untagged"]: vlans[vlan_id]["untagged"].append(current_port) else: if current_port not in vlans[vlan_id]["tagged"]: vlans[vlan_id]["tagged"].append(current_port) continue # Continuation line with only a VLAN ID (tagged for current_port) m = re.match(r"^(\d+)", line_s) if m and current_port: vlan_id = str(int(m.group(1))) vlans.setdefault(vlan_id, {"name": "", "tagged": [], "untagged": []}) if current_port not in vlans[vlan_id]["tagged"]: vlans[vlan_id]["tagged"].append(current_port) # Enrich with the configured membership from UCI bridge-vlan sections. # On devices whose BusyBox ships without the `bridge` utility this is # the only source that names the physical ports at all — the # sub-interface fallback below can only ever report br-ap/br-ap.N. # Runtime data from `bridge vlan show` describes what the kernel # actually enforces, so it keeps precedence where both are present. for entry in _uci_sections_of_type(uci_out, "bridge-vlan"): if "vlan" not in entry: continue try: vlan_id = str(int(_uci_scalar(entry["vlan"]))) except ValueError: continue vlan = vlans.setdefault(vlan_id, {"name": "", "tagged": [], "untagged": []}) uci_name = _uci_scalar(entry.get("name", "")) if uci_name and not vlan["name"]: vlan["name"] = uci_name for spec in _split_uci_list(entry.get("ports", "")): port, tagged = _parse_port_spec(spec) if port in vlan["tagged"] or port in vlan["untagged"]: continue vlan["tagged" if tagged else "untagged"].append(port) # Also derive VLAN names from UCI network interface sections that # reference subinterfaces like eth0.N or br-ap.N: # network.guest.device='eth0.8' -> VLAN 8 name = "guest" # network.ap_v8.device='br-ap.8' -> VLAN 8 name = "ap_v8" # Only fills in names that are still empty after bridge-vlan lookup. for line in uci_out.splitlines(): m = re.match(r"network\.(\w+)\.device='[\w-]+\.(\d+)'", line.strip()) if m: section_name, vid_str = m.group(1), m.group(2) vlan_id = str(int(vid_str)) if vlan_id in vlans and not vlans[vlan_id]["name"]: vlans[vlan_id]["name"] = section_name # Also detect VLAN sub-interfaces (eth0.10, br-ap.8, ...) from ip link show. # The sub-interface is the untagged egress point; its parent is tagged. link_out = self._send_command("ip link show") for line in link_out.splitlines(): lm = re.match(r"^\d+:\s+(\S+?)[@:]", line) if not lm: continue iface = lm.group(1) vm = re.match(r"^([\w-]+)\.(\d+)$", iface) # allow hyphens (br-ap) if not vm: continue parent = vm.group(1) # e.g. "eth0" or "br-ap" vlan_id = str(int(vm.group(2))) # e.g. "10" vlans.setdefault(vlan_id, {"name": "", "tagged": [], "untagged": []}) # sub-interface itself -> untagged egress if iface not in vlans[vlan_id]["untagged"] and iface not in vlans[vlan_id]["tagged"]: vlans[vlan_id]["untagged"].append(iface) # parent -> tagged trunk if parent not in vlans[vlan_id]["tagged"] and parent not in vlans[vlan_id]["untagged"]: vlans[vlan_id]["tagged"].append(parent) return vlans def delete_vlan(self, vlan_id: int) -> None: """Remove a VLAN from the device by deleting its UCI bridge-vlan section. Finds the ``network.@bridge-vlan[N]`` section whose ``.vlan`` matches *vlan_id*, deletes it and commits. If no matching section is found the method is a no-op (the VLAN may only exist as an eth0.N sub-interface, which cannot be deleted via UCI alone). :param vlan_id: VLAN ID to remove. :raises ValueError: If *vlan_id* is out of the valid range. """ if not 1 <= vlan_id <= 4094: raise ValueError(f"VLAN ID {vlan_id} is out of range (1-4094)") uci_out = self.cli(["uci show network"]).get("uci show network", "") idx = None for line in uci_out.splitlines(): m = re.match(r"network\.@bridge-vlan\[(\d+)\]\.vlan='(\d+)'", line.strip()) if m and int(m.group(2)) == vlan_id: idx = m.group(1) break if idx is None: # No explicit bridge-vlan section -- nothing to delete via UCI return self.cli([ f"uci delete network.@bridge-vlan[{idx}]", "uci commit network", "/etc/init.d/network reload", ]) def get_network_instances(self, name: str = "") -> dict[str, Any]: """Return network instances (Linux network namespaces + default). The ``default`` instance contains all interfaces not assigned to a named namespace. Named namespaces are discovered via ``ip netns list``. Example:: { 'default': { 'name': 'default', 'type': 'DEFAULT_INSTANCE', 'state': {'route_distinguisher': None}, 'interfaces': {'interface': {'br-lan': {}, 'eth0': {}}} } } """ netns_out = self._send_command("ip netns list") iface_list = self._get_interface_list() instances: dict[str, Any] = {} # Named namespaces netns_names: list[str] = [] for line in netns_out.splitlines(): line_s = line.strip() if not line_s: continue # "myns (id: 3)" or just "myns" ns_name = line_s.split()[0] netns_names.append(ns_name) # Interfaces inside the namespace ns_ifaces_out = self._send_command(f"ip netns exec {ns_name} ip link show") ns_ifaces: dict[str, Any] = {} for iline in ns_ifaces_out.splitlines(): im = re.match(r"^\d+:\s+(\S+?)[@:]", iline) if im and im.group(1) != "lo": ns_ifaces[im.group(1)] = {} instances[ns_name] = { "name": ns_name, "type": "L3VRF", "state": {"route_distinguisher": None}, "interfaces": {"interface": ns_ifaces}, } # Default instance: interfaces NOT in any named namespace # (on most OpenWrt devices there are no named namespaces) default_ifaces = {iface: {} for iface in iface_list} instances["default"] = { "name": "default", "type": "DEFAULT_INSTANCE", "state": {"route_distinguisher": None}, "interfaces": {"interface": default_ifaces}, } if name: return {k: v for k, v in instances.items() if k == name} return instances def set_hostname(self, new_hostname: str) -> None: """Set the system hostname via UCI and reload the system service.""" self._send_command( f"uci set system.@system[0].hostname='{new_hostname}' && " f"uci commit system && " f"/etc/init.d/system reload" )