# 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. """The access point's narrow writes: an SSID's settings, the radios' channels, a VLAN's name. Each runs as checked ``uci`` steps (:mod:`napalm_openwrt.uci_steps`): a refused step raises naming itself, and what was staged before it is reverted, never committed. """ from __future__ import annotations import re from collections.abc import Callable from napalm.base.exceptions import CommandErrorException from napalm_device_types import AUTO_CHANNEL, SsidConfigDict, WirelessWritesMixin from napalm_openwrt.uci_steps import UciStepsMixin, parse_uci_show, uci _WIRELESS = "wireless" _NETWORK = "network" _SHOW_WIRELESS = "uci -q show wireless" _SHOW_NETWORK = "uci -q show network" #: Re-applies the config; enough for an SSID's settings. _WIFI_RELOAD = "wifi reload" #: A full down/up of every radio: ``wifi reload`` does not change the channel a radio #: is on, with many radios and drivers. _WIFI_RESTART = "wifi" #: What a radio's section name may be, so nothing but the channel reaches the shell. _RADIO_NAME = re.compile(r"[A-Za-z0-9_]+") def _flag(value: object) -> str: return "1" if value else "0" def _seconds(value: object) -> str: if isinstance(value, bool) or not isinstance(value, int) or value < 0: raise ValueError(f"max_inactivity must be a number of seconds, not {value!r}") return str(value) #: Each key of ``SsidConfigDict``: the UCI option it is written to, and its value. _SSID_OPTIONS: dict[str, tuple[str, Callable[[object], str]]] = { "encryption": ("encryption", str), "key": ("key", str), "hidden": ("hidden", _flag), "enabled": ("disabled", lambda v: _flag(not v)), "disassoc_low_ack": ("disassoc_low_ack", _flag), "max_inactivity": ("max_inactivity", _seconds), } def ssid_values(config: SsidConfigDict) -> dict[str, str]: """Each key of *config* as the UCI option it is written to, with its value. :raises ValueError: for a key or value the AP does not take. """ unknown = sorted(set(config) - set(_SSID_OPTIONS)) if unknown: raise ValueError(f"not an SSID setting: {', '.join(unknown)}") values: dict[str, str] = {} for key, value in config.items(): option, render = _SSID_OPTIONS[key] values[option] = render(value) return values def channel_changes(channels: dict[str, int]) -> list[str]: """The ``uci set`` of each radio's channel; ``AUTO_CHANNEL`` as ``auto``. :raises ValueError: for a radio name that is no UCI section name, or a channel that is no whole number of at least 0. """ changes = [] for radio, channel in channels.items(): if not _RADIO_NAME.fullmatch(str(radio)): raise ValueError(f"not a radio's section name: {radio!r}") if isinstance(channel, bool) or not isinstance(channel, int) or channel < 0: raise ValueError(f"not a channel: {channel!r}") value = "auto" if channel == AUTO_CHANNEL else str(channel) changes.append(uci("set", f"{_WIRELESS}.{radio}.channel={value}")) return changes class OpenWrtApWritesMixin(WirelessWritesMixin, UciStepsMixin): """``push_ssid_config``, ``set_radio_channels`` and ``set_vlan_name``.""" def push_ssid_config(self, ssid: str, config: SsidConfigDict) -> None: """Write *config* to every wifi-iface whose ``ssid`` is *ssid*, then ``wifi reload``. Partial: a key *config* leaves out is left alone, and an empty *config* sends nothing. ``enabled`` is written as UCI's ``disabled``. :raises ValueError: for a key or value the AP does not take, before anything is sent. :raises CommandErrorException: when no wifi-iface carries *ssid*, or a step is refused; nothing is committed then. """ values = ssid_values(config) if not values: return sections = [ sec for sec in parse_uci_show(self._uci_step(_SHOW_WIRELESS)) if sec.type == "wifi-iface" and sec.options.get("ssid") == [ssid] ] if not sections: raise CommandErrorException(f"{self.hostname}: no wifi-iface carries the SSID {ssid!r}") changes = [ uci("set", f"{sec.ref}.{option}={value}") for sec in sections for option, value in values.items() ] self._uci_apply(_WIRELESS, changes, _WIFI_RELOAD) def set_radio_channels(self, channels: dict[str, int]) -> None: """Set each radio's channel in one commit, then restart wifi once (``wifi``). :raises ValueError: for a radio name or channel the AP cannot take, before anything is sent. :raises CommandErrorException: when a step is refused -- a radio that does not exist; then no radio changes and wifi is not restarted. """ changes = channel_changes(channels) if changes: self._uci_apply(_WIRELESS, changes, _WIFI_RESTART) def set_vlan_name(self, vlan_id: int, name: str) -> bool: """Name every ``bridge-vlan`` section of *vlan_id* *name*. The name is a label only; nothing needs to restart for it. :returns: False when no bridge-vlan carries *vlan_id*. :raises CommandErrorException: when a step is refused; nothing is committed then. """ sections = [ sec for sec in parse_uci_show(self._uci_step(_SHOW_NETWORK)) if sec.type == "bridge-vlan" and sec.options.get("vlan") == [str(int(vlan_id))] ] if not sections: return False self._uci_apply(_NETWORK, [uci("set", f"{sec.ref}.name={name}") for sec in sections], None) return True