# 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_scripts` turns the values those parts need into two shell scripts: * **stage** -- the ``uci`` changes, staged but not committed, so the running device is untouched. The call waits for it. A change ``uci`` refuses is recorded with its part; at the end every config is reverted and the script exits 3 with the refusals, so nothing of the configuration applies and the call raises (#54). * **apply** -- the commits, what changes the running device (LuCI's service), and the reloads or the restart. It 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 dataclasses import dataclass from typing import TYPE_CHECKING from napalm.base.exceptions import CommandErrorException 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, quoted and as a word. MASK = "'********'" _MASK_WORD = "********" #: Seconds the stage script may take: a few hundred ``uci`` calls. STAGE_TIMEOUT = 120 #: The stage script's exit status when ``uci`` refused a change. REFUSED = 3 #: The ``uci`` verbs that change a config; a refusal of any is a refused part. A read #: (``get``, ``show``) or a quiet ``-q`` call may fail on purpose, as a test. _STAGE_PRELUDE = """#!/bin/sh rm -f "$0" _refused="${0%/*}/refused" : > "$_refused" _part='' uci() { case "$1" in set|add|add_list|del_list|delete|rename|reorder) ;; *) command uci "$@"; return ;; esac _out=$(command uci "$@" 2>&1) && { [ -z "$_out" ] || echo "$_out"; return 0; } _rc=$? echo "$_part: uci $*: $_out" >> "$_refused" return $_rc }""" _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 _stage_epilogue(configs: set[str]) -> str: """Revert every config and exit ``REFUSED`` with the refusals, if there were any.""" reverts = " ".join(sorted(configs)) or "wireless" return "\n".join( [ 'if [ -s "$_refused" ]; then', f' for _c in {reverts}; do command uci revert "$_c"; done', ' cat "$_refused" >&2', f" exit {REFUSED}", "fi", 'rm -f "$_refused"', ] ) @dataclass(frozen=True) class ApScripts: """The stage and apply scripts of a configuration; both "" when it writes nothing.""" stage: str apply: str applied: list[str] skipped: list[str] restarts: bool 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. Each part's commands follow a ``_part=`` line naming it, so the stage script can say which part a refused change belongs to. 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) + len(plan.actions) plan.commands.append(f"_part={sq(part)}") _build_part(part, config, radios, plan) if len(plan.commands) + len(plan.actions) > before + 1: applied.append(part) else: plan.commands.pop() skipped.append(part) return plan, applied, skipped def _apply_script(plan: Plan, restarts: bool) -> str: """The commits, then what is live, then the reloads -- or the restart, which applies it all.""" lines = ["#!/bin/sh"] lines += [f"uci commit {config_name}" for config_name in sorted(plan.commits)] lines += plan.actions 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) def build_scripts(config: ApConfigDict, parts: list[str], radios: Radios) -> ApScripts: """The stage and apply scripts for *parts*; see the module.""" plan, applied, skipped = build_commands(config, parts, radios) if not applied: return ApScripts("", "", applied, skipped, False) restarts = bool(RESTARTING_PARTS & set(applied)) stage = "\n".join([_STAGE_PRELUDE, *plan.commands, _stage_epilogue(plan.commits)]) return ApScripts(stage, _apply_script(plan, restarts), applied, skipped, restarts) def masked(text: str, config: ApConfigDict) -> str: """*text* with every passphrase of *config* masked: quoted as ``MASK``, bare as a word.""" for ssid in config.get("ssids") or []: if key := ssid.get("key"): text = text.replace(sq(key), MASK).replace(key, _MASK_WORD) return text 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``): staged, then applied detached. 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, or the AP refused a change; then nothing of the configuration is applied, and the message names each refused part with what ``uci`` said (passphrases masked). :raises RuntimeError: when the scripts cannot be written to the AP. """ radios = radios_of(parse_uci_show(self._uci_step(_SHOW_WIRELESS))) scripts = build_scripts(config, list(parts), radios) if not scripts.stage: empty: ApConfigResultDict = { "applied": [], "skipped": scripts.skipped, "restarts": False, "commands": "", "log": "", } return empty workdir = self._write_scripts(scripts) self._stage(workdir, config) self._start_apply(workdir) return { "applied": scripts.applied, "skipped": scripts.skipped, "restarts": scripts.restarts, "commands": masked(f"{scripts.stage}\n{scripts.apply}", config), "log": f"{workdir}/apply.log", } def _write_scripts(self, scripts: ApScripts) -> str: """Write both scripts to the AP from stdin; returns their directory. Root writes them, 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. """ written = self.run_command( f'umask 077 && d=$(mktemp -d {WORKDIR_TEMPLATE}) && cat > "$d/stage.sh" && echo "$d"', privileged=True, stdin=scripts.stage.encode(), ) self._check(written, "could not write the configuration script") workdir = written.stdout.strip() if not _WORKDIR_RE.fullmatch(workdir): raise RuntimeError(f"{self.hostname}: the AP named no work directory: {workdir!r}") self._check( self.run_command( f"umask 077 && cat > {workdir}/apply.sh", privileged=True, stdin=scripts.apply.encode(), ), "could not write the configuration script", ) return workdir def _stage(self, workdir: str, config: ApConfigDict) -> None: """Run the stage script and wait for it; a refusal raises, nothing applied.""" staged = self.run_command(f"sh {workdir}/stage.sh", privileged=True, timeout=STAGE_TIMEOUT) if staged.exit_code == 0: return self.run_command(f"rm -rf {workdir}", privileged=True) said = staged.stderr.strip() or staged.stdout.strip() or f"exit status {staged.exit_code}" raise CommandErrorException( masked( f"{self.hostname}: the AP refused the configuration, nothing of it is applied: " f"{said}", config, ) ) def _start_apply(self, workdir: str) -> None: """Run the apply script detached: it may cut the session. The script goes once it has run; the log stays.""" started = self.run_command( f"( sh {workdir}/apply.sh > {workdir}/apply.log 2>&1 < /dev/null; " f"rm -f {workdir}/apply.sh ) &", privileged=True, ) self._check(started, "could not start the configuration script") logger.info("%s: configuration applying; its log is %s/apply.log", self.hostname, workdir) def _check(self, result: CommandResult, what: str) -> None: if result.exit_code: said = result.stderr.strip() or result.stdout.strip() raise RuntimeError(f"{self.hostname}: {what}: {said}")