# 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 configuration applied as desired state (``ApConfigMixin``). The caller names the parts that differ; :func:`build_script` turns the values those parts need into one shell script of ``uci`` commands, the commits and the reloads that apply them. The script reconfigures the AP and may cut the session -- rebuilding the bridge restarts the AP -- so it runs detached, its output in a log on the AP. """ from __future__ import annotations import logging import re from typing import TYPE_CHECKING from napalm_device_types import ( ApConfigDict, ApConfigMixin, ApConfigResultDict, ap_config_ssid_part, ap_config_vlan_part, is_ap_config_part, ) from napalm_openwrt.ap_config._common import Plan, Radios, radios_of, sq from napalm_openwrt.ap_config._network import bridge_part, stp_part, vlan_part from napalm_openwrt.ap_config._system import radio_part, system_part from napalm_openwrt.ap_config._wireless import wireless_part from napalm_openwrt.uci_steps import UciStepsMixin, parse_uci_show if TYPE_CHECKING: # pragma: no cover - typing only from napalm_device_types import CommandResult logger = logging.getLogger(__name__) #: The parts that restart the AP: a new bridge takes effect only with a restart. RESTARTING_PARTS = frozenset({"network/bridge"}) #: On the AP: the directory ``mktemp -d`` makes for one apply, and what its name looks like. WORKDIR_TEMPLATE = "/tmp/openwrt-apply.XXXXXX" # nosec B108 - on the AP, root's own 0700 dir _WORKDIR_RE = re.compile(r"/tmp/openwrt-apply\.[A-Za-z0-9]{6}") # nosec B108 #: What a passphrase shows as in the script the result carries. MASK = "'********'" _SHOW_WIRELESS = "uci -q show wireless" #: The reloads that apply each committed config; network first, the firewall last. _RELOADS = { "network": ["/etc/init.d/network reload 2>/dev/null; true"], "wireless": ["wifi reload 2>&1; true"], "system": [ "/etc/init.d/system reload 2>/dev/null; true", "/etc/init.d/sysntpd restart 2>/dev/null; true", # logd reads the remote-syslog target and the zone at startup only. "/etc/init.d/log restart 2>/dev/null; true", ], "dropbear": ["/etc/init.d/dropbear restart 2>/dev/null; true"], "firewall": ["/etc/init.d/firewall reload 2>/dev/null; true"], } def _build_part(part: str, config: ApConfigDict, radios: Radios, plan: Plan) -> None: if part.startswith("radio/"): radio_part(part, config, radios, plan) elif part.startswith("system/"): system_part(part, config, plan) elif part == "network/bridge": bridge_part(config, plan) elif part == "network/bridge_stp": stp_part(config, plan) elif (vid := ap_config_vlan_part(part)) is not None: vlan_part(vid, config, plan) elif (ssid := ap_config_ssid_part(part)) is not None: wireless_part(ssid[0], ssid[1], config, radios, plan) def build_commands( config: ApConfigDict, parts: list[str], radios: Radios ) -> tuple[Plan, list[str], list[str]]: """The commands for *parts*, and which parts they write and which they cannot. A VLAN is part of the bridge: with ``network/bridge`` among the parts, a ``network/vlan/`` is written by it. """ plan = Plan() applied: list[str] = [] skipped: list[str] = [] rebuilds_bridge = "network/bridge" in parts for part in parts: if not is_ap_config_part(part): skipped.append(part) continue if rebuilds_bridge and ap_config_vlan_part(part) is not None: applied.append(part) continue before = len(plan.commands) _build_part(part, config, radios, plan) (applied if len(plan.commands) > before else skipped).append(part) return plan, applied, skipped def build_script( config: ApConfigDict, parts: list[str], radios: Radios ) -> tuple[str, list[str], list[str], bool]: """The script for *parts*: ``(script, applied, skipped, restarts)``; "" when it writes nothing. A script that restarts the AP reloads nothing first: the restart applies it all. """ plan, applied, skipped = build_commands(config, parts, radios) if not plan.commands: return "", applied, skipped, False restarts = bool(RESTARTING_PARTS & set(applied)) lines = ["#!/bin/sh", *plan.commands] lines += [f"uci commit {config_name}" for config_name in sorted(plan.commits)] if restarts: lines.append("reboot") else: for config_name, reloads in _RELOADS.items(): if config_name in plan.commits: lines += reloads return "\n".join(lines), applied, skipped, restarts def masked(script: str, config: ApConfigDict) -> str: """*script* with every passphrase of *config* as ``MASK``.""" for ssid in config.get("ssids") or []: if key := ssid.get("key"): script = script.replace(sq(key), MASK) return script class OpenWrtApConfigMixin(ApConfigMixin, UciStepsMixin): """``apply_ap_config``: see the module.""" if TYPE_CHECKING: # pragma: no cover - the driver's hostname: str def run_command( self, command: str, *, privileged: bool = False, timeout: float = 60, stdin: bytes | None = None, ) -> CommandResult: ... def apply_ap_config(self, config: ApConfigDict, parts: list[str]) -> ApConfigResultDict: """Write the *parts* of *config* (``ApConfigMixin``) with one detached script. The radios are read first (``uci show wireless``): the 5 GHz and 2.4 GHz ones by their ``band``. A part whose values *config* lacks, or that this driver does not know, is written not at all and comes back in ``skipped``. :raises CommandErrorException: when the radios cannot be read. :raises RuntimeError: when the script cannot be written to the AP. """ radios = radios_of(parse_uci_show(self._uci_step(_SHOW_WIRELESS))) script, applied, skipped, restarts = build_script(config, list(parts), radios) if not script: return {"applied": [], "skipped": skipped, "restarts": False, "commands": "", "log": ""} workdir = self._run_detached(script) return { "applied": applied, "skipped": skipped, "restarts": restarts, "commands": masked(script, config), "log": f"{workdir}/apply.log", } def _run_detached(self, script: str) -> str: """Write *script* to the AP from stdin and run it detached; returns its directory. Root writes the script, passphrases and all, into a directory of its own (``mktemp -d``: mode 0700, a name nobody knows in advance), never to a fixed /tmp name another account could have placed or could swap between the write and the run. The script goes once it has run; the log stays. """ written = self.run_command( f'umask 077 && d=$(mktemp -d {WORKDIR_TEMPLATE}) && cat > "$d/apply.sh" && echo "$d"', privileged=True, stdin=script.encode(), ) if written.exit_code: raise RuntimeError( f"{self.hostname}: could not write the configuration script: " f"{written.stderr.strip() or written.stdout.strip()}" ) workdir = written.stdout.strip() if not _WORKDIR_RE.fullmatch(workdir): raise RuntimeError(f"{self.hostname}: the AP named no work directory: {workdir!r}") started = self.run_command( f"( sh {workdir}/apply.sh > {workdir}/apply.log 2>&1 < /dev/null; " f"rm -f {workdir}/apply.sh ) &", privileged=True, ) if started.exit_code: raise RuntimeError( f"{self.hostname}: could not start the configuration script: " f"{started.stderr.strip() or started.stdout.strip()}" ) logger.info( "%s: configuration script started; its log is %s/apply.log", self.hostname, workdir ) return workdir