Merge pull request 'feat(access-point): declared AP writes, apply_ap_config and DHCP leases, 0.11.0 (NetOrk/netork#695)' (#55) from feature/declared-ap-methods-695 into main
driver / lowest (push) Successful in 31s
driver / standard (push) Successful in 19s
driver / lint (push) Successful in 19s
driver / types (push) Successful in 1m3s
driver / test (3.13) (push) Successful in 55s
driver / test (3.12) (push) Successful in 1m7s
driver / build (push) Successful in 29s
driver / security (push) Successful in 53s
driver / publish (push) Successful in 28s
CI / driver (push) Successful in 4m38s

This commit was merged in pull request #55.
This commit is contained in:
christianmanivong committed 2026-11-29 22:45:01 +00:00
commit 10a58797d3
17 files changed
+2360 -41

No files matched your search

+33
View File
@@ -7,6 +7,39 @@ recorded here; their history is the git log.
## [Unreleased] ## [Unreleased]
## [0.11.0] - 2026-11-29
### Added
- napalm-device-types' declared AP writes (NetOrk/netork#695), so an application no longer
sends UCI itself:
- `push_ssid_config(ssid, config)` writes the SSID settings it is given (encryption, key,
hidden, enabled, disassoc_low_ack, max_inactivity) to every wifi-iface carrying the
SSID and reloads wifi, each step checked (#35). An SSID no wifi-iface carries raises.
- `set_radio_channels({radio: channel})` sets every radio's channel (`0` is `auto`) in
one commit with one full wifi restart.
- `set_vlan_name(vlan_id, name)` names the VLAN's `bridge-vlan` sections; False where none
carries it.
- `apply_ap_config(config, parts)` writes the parts of an access point's desired
configuration that differ, as one script run detached on the AP: radios, remote
syslog, LuCI, dropbear, the `br-ap` bridge and its VLANs, spanning tree, and each
SSID's VLAN, bands, presence, encryption, key, flags, limits, MAC filter and 802.11r.
It answers which parts it wrote, which it could not (`skipped`: unknown, or a keyed
mode without its key), whether the AP restarts (a new bridge), and the script with
every passphrase masked. The changes are staged by a script the call waits for: a
change the AP refuses raises `CommandErrorException` naming its part, and nothing of
the configuration is applied (#54); the commits, reloads and the restart run detached
afterwards. `wireless/<ssid>/passphrase` now writes the key, where netOrk's own
builder wrote nothing for it.
- `get_dhcp_leases()` (`DhcpLeasesMixin`): dnsmasq's DHCPv4 leases from its lease file;
`[]` where dnsmasq never ran, a raise where the file cannot be read.
### Changed
- Needs napalm-device-types 4.54.0 or later.
### Removed
- `push_radio_channel(radio, channel)`, which no contract declared: `set_radio_channels`
replaces it. A breaking change before 1.0.0.
## [0.10.0] - 2026-11-28 ## [0.10.0] - 2026-11-28
### Added ### Added
+47 -7
View File
@@ -72,6 +72,7 @@ device.close()
| `get_ntp_servers` / `get_ntp_peers` | ✅ | `system.ntp.server` in UCI, every server of the list; none while `system.ntp.enabled` is off -- the same list as `get_time_sync()` | | `get_ntp_servers` / `get_ntp_peers` | ✅ | `system.ntp.server` in UCI, every server of the list; none while `system.ntp.enabled` is off -- the same list as `get_time_sync()` |
| `get_time_sync()` | ✅ | napalm-device-types `TimeSyncMixin`: the servers as above, the zone from `zonename` where the rule in `timezone` is that zone's (else the one zone with that rule, or none); `synchronized` is not readable (None) | | `get_time_sync()` | ✅ | napalm-device-types `TimeSyncMixin`: the servers as above, the zone from `zonename` where the rule in `timezone` is that zone's (else the one zone with that rule, or none); `synchronized` is not readable (None) |
| `get_firmware_offer()` | ✅ | napalm-device-types `FirmwareOfferMixin`: the newest release of the device's own line on the attended sysupgrade server (see *Firmware upgrade*) | | `get_firmware_offer()` | ✅ | napalm-device-types `FirmwareOfferMixin`: the newest release of the device's own line on the attended sysupgrade server (see *Firmware upgrade*) |
| `get_dhcp_leases()` | ✅ | napalm-device-types `DhcpLeasesMixin`: dnsmasq's lease file (`dhcp.@dnsmasq[0].leasefile`, else `/tmp/dhcp.leases`), DHCPv4 leases only, state `active`; `[]` where dnsmasq never ran; raises when the file cannot be read. odhcpd's DHCPv4 leases are not read |
| `get_services_need_restart()` | ❌ | deliberately not offered (NetOrk/netork#2750): an upgrade writes the new files to the overlay while the old ones stay in the read-only image, and `/proc/<pid>/maps` can name those by their `/rom` or `/overlay/upper` path rather than as deleted (Linux before 6.8 shows an overlay file's real path). napalm-device-types' `/proc` scan could then read clean exactly after an upgrade; without the method the caller shows the reading as not made. A reading of OpenWrt's own is #51 | | `get_services_need_restart()` | ❌ | deliberately not offered (NetOrk/netork#2750): an upgrade writes the new files to the overlay while the old ones stay in the read-only image, and `/proc/<pid>/maps` can name those by their `/rom` or `/overlay/upper` path rather than as deleted (Linux before 6.8 shows an overlay file's real path). napalm-device-types' `/proc` scan could then read clean exactly after an upgrade; without the method the caller shows the reading as not made. A reading of OpenWrt's own is #51 |
## Configuration management ## Configuration management
@@ -153,13 +154,52 @@ image.
## Wireless writes ## Wireless writes
`push_mac_acl(ssid_name, mode, macs)` (napalm-device-types `MacAclMixin`) rewrites the Each `uci` step runs on an SSH exec channel of its own, as root, with its exit status
MAC filter of every wifi-iface carrying the SSID and reloads wifi; checked: a refused step raises `CommandErrorException` naming it, what was staged is
`push_radio_channel(radio, channel)` sets a radio's channel (`0` is `auto`) and restarts reverted, and nothing is committed or restarted.
wifi in full. Each `uci` step runs on an SSH exec channel of its own, as root, with its
exit status checked: a refused step raises `CommandErrorException` naming it, what was - `push_mac_acl(ssid_name, mode, macs)` (napalm-device-types `MacAclMixin`) rewrites the
staged is reverted, and nothing is committed or restarted. An SSID no wifi-iface MAC filter of every wifi-iface carrying the SSID and reloads wifi. An SSID no wifi-iface
carries raises too. carries raises.
- `push_ssid_config(ssid, config)` (`WirelessWritesMixin`) writes the settings it is given
-- `encryption`, `key`, `hidden`, `enabled` (as UCI's `disabled`), `disassoc_low_ack`,
`max_inactivity` -- to every wifi-iface carrying the SSID, then `wifi reload`. A key it
is not given is left alone; an SSID no wifi-iface carries raises. Which mode may be
written without its key is the caller's to decide.
- `set_radio_channels({radio: channel})` (`WirelessWritesMixin`) sets every radio's channel
(`0` is `auto`) in one commit and restarts wifi in full once (`wifi`: `wifi reload` does
not change a radio's channel). A radio name that is no UCI section name, or a channel that
is no whole number, raises `ValueError` before anything is sent.
- `set_vlan_name(vlan_id, name)` names every `bridge-vlan` section of the VLAN and commits
`network`; nothing restarts for a label. False where no `bridge-vlan` carries the VLAN.
## AP configuration
`apply_ap_config(config, parts)` (napalm-device-types `ApConfigMixin`) writes the parts of
an `ApConfigDict` the caller names as UCI changes: the radios (country, 5 and 2.4
GHz `htmode`), remote syslog, LuCI (`uhttpd` enabled or stopped), dropbear's port and
password logins, the `br-ap` bridge with VLAN filtering on `eth0` (every VLAN tagged, the
management VLAN untagged where asked), one VLAN of it, its spanning tree, and per SSID its
VLAN (`ap_vlan<vid>`), bands, presence, encryption and key, flags, limits, MAC filter and
802.11r. The radios are found by their `band` in `uci show wireless`. A keyed mode is never
written without its key, a whitelist without MACs is written as no filter, and a part the
driver does not know or whose values are missing comes back in `skipped`.
Two scripts are written as root from stdin into a fresh `mktemp -d` directory
(`/tmp/openwrt-apply.XXXXXX`):
- `stage.sh` stages the changes without committing them, so the running AP is untouched,
and the call waits for it. A change `uci` refuses (`set`, `add`, `add_list`, `delete`,
...) is recorded with its part; at the end every config is reverted and the call raises
`CommandErrorException` naming each refused part and what `uci` said, passphrases
masked. Nothing of the configuration is applied then (NAPALM/napalm-openwrt#54). A quiet
`uci -q` call, such as deleting an option that may be missing, is no refusal. The script
removes itself as it starts, since it holds the passphrases.
- `apply.sh` commits, enables or stops LuCI, and reloads network, wifi, system, dropbear and
the firewall as needed, or restarts the AP when the bridge was rebuilt (`restarts`). It
runs detached, since it may cut the session; its output stays in `apply.log` there.
The result carries both scripts with every passphrase masked.
## Time sync ## Time sync
+315
View File
@@ -0,0 +1,315 @@
# 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/<vid>`` 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}")
+111
View File
@@ -0,0 +1,111 @@
# 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.
"""What the AP-configuration builders share: quoting, the plan they fill, the radios.
No I/O: every function here turns values into shell text.
"""
from __future__ import annotations
from collections.abc import Iterable
from dataclasses import dataclass, field
from napalm_device_types import ApConfigDict, ApSsidConfigDict
from napalm_openwrt.uci_steps import UciSection
#: The bridge every managed AP's SSID VLANs share, and the port it is trunked on.
AP_BRIDGE = "br-ap"
AP_UPLINK_PORT = "eth0"
#: ``band`` (or the old ``hwmode``) of a wifi-device, by the band it names.
_BANDS = {
"2.4GHz": ("2g", "11g", "b", "g", "bg", "bgn"),
"5GHz": ("5g", "11a", "a", "ac", "ax5"),
}
def sq(value: object) -> str:
"""*value* as one single-quoted shell word, whatever it contains.
An SSID name, a passphrase or a MAC goes into the script; a ``'`` in it
would end the quoting and run the rest as root on the AP.
"""
return "'" + str(value).replace("'", "'\\''") + "'"
@dataclass
class Plan:
"""The commands built so far, the configs they stage for a commit, and what runs live.
``commands`` only stage UCI changes, which the device does not run until they are
committed; ``actions`` change the running device and come after the commits.
"""
commands: list[str] = field(default_factory=list)
commits: set[str] = field(default_factory=set)
actions: list[str] = field(default_factory=list)
@dataclass(frozen=True)
class Radios:
"""The AP's 5 GHz and 2.4 GHz radios, by their UCI section name; None without one."""
r5g: str | None = None
r2g: str | None = None
@property
def all(self) -> list[str]:
return [r for r in (self.r2g, self.r5g) if r]
def radios_of(sections: Iterable[UciSection]) -> Radios:
"""The first radio of each band among the ``wifi-device`` sections of ``uci show wireless``."""
found: dict[str, str] = {}
for sec in sections:
if sec.type != "wifi-device":
continue
raw = (sec.options.get("band") or sec.options.get("hwmode") or [""])[0]
for band, words in _BANDS.items():
if raw in words:
found.setdefault(band, sec.name)
return Radios(r5g=found.get("5GHz"), r2g=found.get("2.4GHz"))
def ssid_of(config: ApConfigDict, name: str) -> ApSsidConfigDict | None:
"""The SSID *name* of *config*; None when it has none of that name."""
return next((s for s in config.get("ssids") or [] if s.get("name") == name), None)
def needs_key(encryption: str) -> bool:
"""Whether hostapd needs a local key for *encryption*: every PSK and SAE mode."""
enc = encryption.lower()
return "psk" in enc or "sae" in enc
def keyed_without_key(ssid: ApSsidConfigDict) -> bool:
"""A keyed mode with no key on record: writing it would take the SSID off the
air, and writing ``none`` instead would put it on the air unprotected."""
return needs_key(ssid.get("encryption") or "none") and not ssid.get("key")
def ssid_loop(ssid_name: str, body: Iterable[str]) -> str:
"""A loop over each wireless section that carries *ssid_name*, *body* run as ``$_s``."""
lines = [
"for _s in $(uci show wireless | grep -oE '^wireless\\.[^.]+' | sort -u); do",
f' [ "$(uci -q get $_s.ssid 2>/dev/null)" = {sq(ssid_name)} ] || continue',
*(f" {line}" for line in body),
"done",
]
return "\n".join(lines)
+228
View File
@@ -0,0 +1,228 @@
# 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 network parts of an AP configuration: the ``br-ap`` bridge and its VLANs.
The uplink ``eth0`` is a trunk; each VLAN is a ``bridge-vlan`` of ``br-ap``, and an
SSID's clients reach theirs through an interface ``ap_vlan<vid>`` on ``br-ap.<vid>``.
"""
from __future__ import annotations
from napalm_device_types import ApConfigDict
from napalm_openwrt.ap_config._common import AP_UPLINK_PORT, Plan, sq
# Drop every bridge-vlan section on br-ap before writing our own. Sections may carry
# any name -- a hand-built bridge commonly uses `apbr_vlanN` without the separator
# used here -- so setting our names on top would leave the old sections in place and
# define the same VLAN twice with conflicting port membership.
_PURGE_BRIDGE_VLANS = "\n".join(
[
"n=0",
"while uci -q get network.@bridge-vlan[$n] >/dev/null 2>&1; do",
" if [ \"$(uci -q get network.@bridge-vlan[$n].device 2>/dev/null)\" = 'br-ap' ]; then",
" uci delete network.@bridge-vlan[$n]",
" else",
" n=$((n+1))",
" fi",
"done; true",
]
)
# Every wireless AP interface onto the ap_vlan<vid> of the VLAN its network's device names.
_ATTACH_APS = (
"for iface in $(uci show wireless | grep -oE '^wireless\\.[^.]+' | sort -u); do "
" mode=$(uci -q get $iface.mode 2>/dev/null); [ \"$mode\" != 'ap' ] && continue; "
" net=$(uci -q get $iface.network 2>/dev/null); "
" dev=$(uci -q get network.$net.device 2>/dev/null); "
" vid=$(echo \"$dev\" | grep -oE '[0-9]+$'); "
' [ -n "$vid" ] && uci set $iface.network="ap_vlan$vid"; '
"done; true"
)
# Every device section but br-ap goes.
_DROP_OTHER_DEVICES = "\n".join(
[
"n=0",
"while uci show network.@device[$n] >/dev/null 2>&1; do",
" _nm=$(uci -q get network.@device[$n].name 2>/dev/null)",
" if [ \"$_nm\" = 'br-ap' ]; then",
" n=$((n+1))",
" else",
" uci delete network.@device[$n]",
" fi",
"done; true",
]
)
# The interfaces of the old bridges and 802.1q devices go.
_DROP_OLD_INTERFACES = (
"for iface in $(uci show network | grep -oE 'network\\.[a-z0-9_]+\\.device' | "
"cut -d. -f2); do "
" dev=$(uci -q get network.$iface.device 2>/dev/null); "
" case $dev in br-wlan*|eth0.[0-9]*) uci delete network.$iface;; esac; "
"done; true"
)
def _stp(config: ApConfigDict) -> str:
return "1" if config.get("bridge_stp", True) else "0"
def vlan_port_spec(config: ApConfigDict, vid: int) -> str:
"""The uplink's membership in *vid*: ``u*`` (untagged, PVID) for the management
VLAN when it is to be untagged -- only one VLAN of a port may be -- else ``t``."""
if config.get("management_untagged") and vid == config.get("management_vlan_id"):
return f"{AP_UPLINK_PORT}:u*"
return f"{AP_UPLINK_PORT}:t"
def stp_part(config: ApConfigDict, plan: Plan) -> None:
"""``network/bridge_stp``: on the section whose ``name`` is br-ap, whatever its own
name -- setting it on a section that does not exist would create a second one."""
plan.commands.append(
"\n".join(
[
"for _s in $(uci show network | grep -oE '^network\\.[a-z0-9_]+' "
"| cut -d. -f2 | sort -u); do",
" [ \"$(uci -q get network.$_s.name 2>/dev/null)\" = 'br-ap' ] || continue",
f" uci set network.$_s.stp={sq(_stp(config))}",
"done",
]
)
)
plan.commits.add("network")
def _ssid_vlans(config: ApConfigDict) -> list[int]:
return [vid for s in config.get("ssids") or [] if (vid := s.get("vlan_id"))]
def _management_interface(mvid: int) -> str:
return (
f"_mgmt_sec=''; "
f"for _sec in $(uci show network | grep -oE "
f"'network\\.[a-z0-9_]+\\.device' | cut -d. -f2); do "
f" _d=$(uci -q get network.$_sec.device 2>/dev/null); "
f' [ "$_d" = \'eth0.{mvid}\' ] && _mgmt_sec="$_sec" && break; '
f"done; "
f'if [ -z "$_mgmt_sec" ]; then '
f" _mgmt_sec='mgmt'; uci set network.mgmt=interface; "
f" uci set network.mgmt.proto='dhcp'; "
f"fi; "
f"uci set network.$_mgmt_sec.device='br-ap.{mvid}'; "
f"_proto=$(uci -q get network.$_mgmt_sec.proto 2>/dev/null); "
f"if [ -z \"$_proto\" ]; then uci set network.$_mgmt_sec.proto='dhcp'; fi; "
f"true"
)
def _ap_vlan_interface(vid: int) -> list[str]:
return [
f"uci set network.ap_vlan{vid}=interface",
f"uci set network.ap_vlan{vid}.device='br-ap.{vid}'",
f"uci set network.ap_vlan{vid}.proto='none'",
]
def _lan_zone(networks: list[str]) -> str:
"""The management and SSID networks into the firewall zone ``lan``."""
nets = " ".join(networks)
return (
f"for i in 0 1 2 3 4 5; do "
f" zone=$(uci -q get firewall.@zone[$i].name 2>/dev/null); "
f" [ \"$zone\" != 'lan' ] && continue; "
f" for net in {nets}; do "
f" cur=$(uci -q get firewall.@zone[$i].network 2>/dev/null || true); "
f' echo "$cur" | grep -qw "$net" || '
f' uci add_list firewall.@zone[$i].network="$net"; '
f" done; break; "
f"done; true"
)
def bridge_part(config: ApConfigDict, plan: Plan) -> None:
"""``network/bridge``: br-ap built anew, with every VLAN of management and SSIDs."""
mvid = config.get("management_vlan_id")
ssid_vlans = _ssid_vlans(config)
vlans = sorted({*ssid_vlans, *([mvid] if mvid else [])})
plan.commands += [
"uci set network.apbr=device",
"uci set network.apbr.name='br-ap'",
"uci set network.apbr.type='bridge'",
"uci set network.apbr.vlan_filtering='1'",
f"uci set network.apbr.stp={sq(_stp(config))}",
"uci -q delete network.apbr.ports 2>/dev/null; true",
"uci add_list network.apbr.ports='eth0'",
_PURGE_BRIDGE_VLANS,
]
for vid in vlans:
sec = f"apbr_vlan_{vid}"
plan.commands += [
f"uci set network.{sec}=bridge-vlan",
f"uci set network.{sec}.device='br-ap'",
f"uci set network.{sec}.vlan={sq(vid)}",
f"uci set network.{sec}.ports={sq(vlan_port_spec(config, vid))}",
]
if mvid:
plan.commands.append(_management_interface(mvid))
for vid in ssid_vlans:
if vid != mvid:
plan.commands += _ap_vlan_interface(vid)
plan.commands += [_ATTACH_APS, _DROP_OTHER_DEVICES, _DROP_OLD_INTERFACES]
plan.commands.append(
_lan_zone(["$_mgmt_sec", *sorted({f"ap_vlan{v}" for v in ssid_vlans if v != mvid})])
)
plan.commits.update({"firewall", "network", "wireless"})
def vlan_part(vid: int, config: ApConfigDict, plan: Plan) -> None:
"""``network/vlan/<vid>``: the VLAN on br-ap and its interface.
Reuses whatever section already defines the VLAN -- its name is not ours to
assume -- and creates one only where none does. Unlike the bridge, nothing is
purged: the other VLANs are not being rewritten.
"""
sec = f"apbr_vlan_{vid}"
ports = vlan_port_spec(config, vid)
plan.commands.append(
"\n".join(
[
"_i=0; _found=''",
"while uci -q get network.@bridge-vlan[$_i] >/dev/null 2>&1; do",
' if [ "$(uci -q get network.@bridge-vlan[$_i].device 2>/dev/null)" ='
" 'br-ap' ] &&"
' [ "$(uci -q get network.@bridge-vlan[$_i].vlan 2>/dev/null)" ='
f" {sq(vid)} ]; then",
" _found=$_i; break",
" fi",
" _i=$((_i+1))",
"done",
'if [ -n "$_found" ]; then',
f" uci set network.@bridge-vlan[$_found].ports={sq(ports)}",
"else",
f" uci set network.{sec}=bridge-vlan",
f" uci set network.{sec}.device='br-ap'",
f" uci set network.{sec}.vlan={sq(vid)}",
f" uci set network.{sec}.ports={sq(ports)}",
"fi",
"true",
]
)
)
if vid == (config.get("management_vlan_id") or 0):
plan.commands.append(f"uci set network.mgmt.device='br-ap.{vid}'")
else:
plan.commands += _ap_vlan_interface(vid)
plan.commits.add("network")
+106
View File
@@ -0,0 +1,106 @@
# 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 radio and system parts of an AP configuration, as UCI commands."""
from __future__ import annotations
from collections.abc import Mapping
from napalm_device_types import ApConfigDict
from napalm_openwrt.ap_config._common import Plan, Radios, sq
_DEFAULT_SYSLOG_PORT = 514
def _country(config: ApConfigDict, radios: Radios, plan: Plan) -> None:
if not config.get("country_code") or not radios.all:
return
for radio in (radios.r5g, radios.r2g):
if radio:
plan.commands.append(f"uci set wireless.{radio}.country={sq(config['country_code'])}")
plan.commits.add("wireless")
def _htmode(field: str, radio: str | None, config: ApConfigDict, plan: Plan) -> None:
values: Mapping[str, object] = config
if values.get(field) and radio:
plan.commands.append(f"uci set wireless.{radio}.htmode={sq(values[field])}")
plan.commits.add("wireless")
def radio_part(part: str, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
"""``radio/country`` on every radio, ``radio/5g_htmode`` and ``radio/2g_htmode`` on theirs."""
if part == "radio/country":
_country(config, radios, plan)
elif part == "radio/5g_htmode":
_htmode("htmode_5g", radios.r5g, config, plan)
elif part == "radio/2g_htmode":
_htmode("htmode_2g", radios.r2g, config, plan)
def _syslog(config: ApConfigDict, plan: Plan) -> None:
host = config.get("syslog_host")
if not host:
return
port = config.get("syslog_port") or _DEFAULT_SYSLOG_PORT
plan.commands += [
f"uci set system.@system[0].log_ip={sq(host)}",
f"uci set system.@system[0].log_port={sq(port)}",
"uci set system.@system[0].log_proto='udp'",
"uci set system.@system[0].log_remote='1'",
]
plan.commits.add("system")
def _web_ui(config: ApConfigDict, plan: Plan) -> None:
"""LuCI is served by uhttpd, so the policy is the service state; the listener
config stays as it is, and enabling it again restores exactly what was there."""
if "web_ui" not in config:
return
if config["web_ui"]:
plan.actions.append("/etc/init.d/uhttpd enable && /etc/init.d/uhttpd start")
else:
plan.actions.append("/etc/init.d/uhttpd stop; /etc/init.d/uhttpd disable")
def _ssh_port(config: ApConfigDict, plan: Plan) -> None:
if not config.get("ssh_port"):
return
plan.commands.append(f"uci set dropbear.@dropbear[0].Port={sq(config['ssh_port'])}")
plan.commits.add("dropbear")
def _password_auth(config: ApConfigDict, plan: Plan) -> None:
if "ssh_password_auth" not in config:
return
value = "on" if config["ssh_password_auth"] else "off"
plan.commands.append(f"uci set dropbear.@dropbear[0].PasswordAuth={sq(value)}")
plan.commands.append(f"uci set dropbear.@dropbear[0].RootPasswordAuth={sq(value)}")
plan.commits.add("dropbear")
_SYSTEM_PARTS = {
"system/syslog": _syslog,
"system/web_ui": _web_ui,
"system/ssh_port": _ssh_port,
"system/password_auth": _password_auth,
}
def system_part(part: str, config: ApConfigDict, plan: Plan) -> None:
"""Remote syslog, the web interface, the SSH port and SSH password logins."""
build = _SYSTEM_PARTS.get(part)
if build is not None:
build(config, plan)
+254
View File
@@ -0,0 +1,254 @@
# 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 wireless parts of an AP configuration: ``wireless/<ssid>/<attribute>``.
Each writes every wireless section that carries the SSID. A keyed mode is never
written without its key: the SSID would go off the air, and ``none`` instead
would put it on the air unprotected; such a part is left unwritten.
"""
from __future__ import annotations
from collections.abc import Callable, Mapping
from napalm_device_types import ApConfigDict, ApSsidConfigDict
from napalm_openwrt.ap_config._common import (
Plan,
Radios,
keyed_without_key,
sq,
ssid_loop,
ssid_of,
)
_ALL_BANDS = ["2.4 GHz", "5 GHz"]
def _net(ssid: ApSsidConfigDict) -> str:
return f"ap_vlan{ssid['vlan_id']}"
def _vlan(ssid: ApSsidConfigDict, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
if not ssid.get("vlan_id"):
return
plan.commands.append(ssid_loop(ssid["name"], [f"uci set $_s.network={sq(_net(ssid))}"]))
plan.commits.add("wireless")
def _new_iface(ssid: ApSsidConfigDict, radio: str, indent: str = "") -> list[str]:
"""A new wifi-iface on *radio* for *ssid*, in its VLAN, with its key and hidden flag."""
enc = ssid.get("encryption") or "none"
lines = [
"uci add wireless wifi-iface",
f"uci set wireless.@wifi-iface[-1].device={sq(radio)}",
"uci set wireless.@wifi-iface[-1].mode='ap'",
f"uci set wireless.@wifi-iface[-1].ssid={sq(ssid['name'])}",
f"uci set wireless.@wifi-iface[-1].network={sq(_net(ssid))}",
f"uci set wireless.@wifi-iface[-1].encryption={sq(enc)}",
]
if ssid.get("key") and enc not in ("none", ""):
lines.append(f"uci set wireless.@wifi-iface[-1].key={sq(ssid['key'])}")
if ssid.get("hidden"):
lines.append("uci set wireless.@wifi-iface[-1].hidden='1'")
return [f"{indent}{line}" for line in lines]
def _wanted_radios(ssid: ApSsidConfigDict, radios: Radios) -> list[str]:
bands = ssid.get("bands") or _ALL_BANDS
wanted = []
if any("2.4" in b for b in bands) and radios.r2g:
wanted.append(radios.r2g)
if any("5" in b and "2.4" not in b for b in bands) and radios.r5g:
wanted.append(radios.r5g)
return wanted
def _bands(ssid: ApSsidConfigDict, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
"""The SSID on the radios of its bands: taken off the others, added where missing."""
if not ssid.get("vlan_id") or keyed_without_key(ssid):
return
name = ssid["name"]
wanted = _wanted_radios(ssid, radios)
for radio in (r for r in radios.all if r not in wanted):
plan.commands.append(
ssid_loop(
name,
[
f'[ "$(uci -q get $_s.device 2>/dev/null)" = {sq(radio)} ] || continue',
"uci delete $_s",
],
)
)
for radio in wanted:
plan.commands.append(
"\n".join(
[
"_found=0",
ssid_loop(
name,
[
f'[ "$(uci -q get $_s.device 2>/dev/null)" = {sq(radio)} ] || continue',
"_found=1; break",
],
),
"if [ $_found = 0 ]; then",
*_new_iface(ssid, radio, indent=" "),
"fi",
]
)
)
plan.commits.add("wireless")
def _missing(ssid: ApSsidConfigDict, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
"""A wifi-iface for each band of an SSID the AP does not serve at all."""
if not ssid.get("vlan_id") or keyed_without_key(ssid):
return
for band in ssid.get("bands") or _ALL_BANDS:
radio = radios.r2g if "2.4" in band else radios.r5g
if radio:
plan.commands += _new_iface(ssid, radio)
plan.commits.add("wireless")
def _encryption(ssid: ApSsidConfigDict, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
if keyed_without_key(ssid):
return
enc = ssid.get("encryption") or "none"
body = [f"uci set $_s.encryption={sq(enc)}"]
if ssid.get("key") and enc not in ("none", ""):
body.append(f"uci set $_s.key={sq(ssid['key'])}")
plan.commands.append(ssid_loop(ssid["name"], body))
plan.commits.add("wireless")
def _passphrase(ssid: ApSsidConfigDict, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
"""The key alone, for an SSID whose mode is right and whose key is not."""
if not ssid.get("key") or (ssid.get("encryption") or "none") == "none":
return
plan.commands.append(ssid_loop(ssid["name"], [f"uci set $_s.key={sq(ssid['key'])}"]))
plan.commits.add("wireless")
def _flag(option: str, field: str, invert: bool = False) -> _Builder:
"""A boolean of the SSID as a ``0``/``1`` option; *invert* for ``disabled``."""
def build(ssid: ApSsidConfigDict, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
values: Mapping[str, object] = ssid
if values.get(field) is None:
return
on = bool(values[field]) != invert
plan.commands.append(ssid_loop(ssid["name"], [f"uci set $_s.{option}={sq(int(on))}"]))
plan.commits.add("wireless")
return build
def _max_clients(ssid: ApSsidConfigDict, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
if "max_clients" not in ssid:
return
limit = ssid.get("max_clients")
line = (
f"uci set $_s.maxassoc={sq(limit)}"
if limit is not None
else "uci -q delete $_s.maxassoc 2>/dev/null; true"
)
plan.commands.append(ssid_loop(ssid["name"], [line]))
plan.commits.add("wireless")
def _max_inactivity(
ssid: ApSsidConfigDict, config: ApConfigDict, radios: Radios, plan: Plan
) -> None:
if ssid.get("max_inactivity") is None:
return
seconds = ssid.get("max_inactivity")
plan.commands.append(ssid_loop(ssid["name"], [f"uci set $_s.max_inactivity={sq(seconds)}"]))
plan.commits.add("wireless")
def _acl(ssid: ApSsidConfigDict, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
"""The MAC filter and its list, rebuilt whole.
The wifi-scripts validator takes no ``macfilter`` but ``allow`` and ``deny``:
``disable`` puts netifd in a restart loop with the radios down. Off is the
option left out. A whitelist without MACs would lock every client out, so it
is written as off.
"""
mode = ssid.get("acl_mode") or "off"
macs = sorted(set(ssid.get("acl_macs") or [])) if mode != "off" else []
if mode == "whitelist" and not macs:
mode = "off"
if mode == "off":
body = ["uci -q delete $_s.macfilter", "uci -q delete $_s.maclist"]
else:
body = [
f"uci set $_s.macfilter={sq('allow' if mode == 'whitelist' else 'deny')}",
"uci -q delete $_s.maclist 2>/dev/null",
*(f"uci add_list $_s.maclist={sq(mac)}" for mac in macs),
]
plan.commands.append(ssid_loop(ssid["name"], body))
plan.commits.add("wireless")
def _ft(ssid: ApSsidConfigDict, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
"""802.11r on, in the configuration's mobility domain; or off, which needs none."""
if not ssid.get("fast_transition"):
body = [
"uci -q delete $_s.ieee80211r",
"uci -q delete $_s.mobility_domain",
"uci -q delete $_s.ft_over_ds",
"uci -q delete $_s.ft_psk_generate_local",
]
elif config.get("mobility_domain"):
over_ds = "1" if config.get("ft_over_ds", True) else "0"
body = [
"uci set $_s.ieee80211r='1'",
f"uci set $_s.mobility_domain={sq(config['mobility_domain'])}",
f"uci set $_s.ft_over_ds={sq(over_ds)}",
]
else:
return
plan.commands.append(ssid_loop(ssid["name"], body))
plan.commits.add("wireless")
_Builder = Callable[[ApSsidConfigDict, ApConfigDict, Radios, Plan], None]
_SSID_PARTS: dict[str, _Builder] = {
"vlan": _vlan,
"bands": _bands,
"missing": _missing,
"encryption": _encryption,
"passphrase": _passphrase,
"hidden": _flag("hidden", "hidden"),
"enabled": _flag("disabled", "enabled", invert=True),
"client_isolation": _flag("isolate", "client_isolation"),
"disassoc_low_ack": _flag("disassoc_low_ack", "disassoc_low_ack"),
"max_clients": _max_clients,
"max_inactivity": _max_inactivity,
"acl": _acl,
"ft": _ft,
}
def wireless_part(
ssid_name: str, attribute: str, config: ApConfigDict, radios: Radios, plan: Plan
) -> None:
"""The *attribute* of the SSID *ssid_name*; nothing for an SSID *config* lacks."""
ssid = ssid_of(config, ssid_name)
build = _SSID_PARTS.get(attribute)
if ssid is not None and build is not None:
build(ssid, config, radios, plan)
+155
View File
@@ -0,0 +1,155 @@
# 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
+92
View File
@@ -0,0 +1,92 @@
# 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 leases dnsmasq handed out (napalm-device-types ``DhcpLeasesMixin``).
OpenWrt's DHCP server is dnsmasq; it keeps its live leases in one file, by default
``/tmp/dhcp.leases`` (``dhcp.@dnsmasq[0].leasefile``), a line per lease:
``<end> <mac> <ip> <hostname> <client-id>``, ``*`` for no hostname, end 0 for a lease
that does not end. A lease dnsmasq gave up is gone from the file, so every line holds.
DHCPv6 leases share the file after a ``duid`` line; they name no MAC and are left out.
An AP whose dnsmasq never ran has no file: it serves no leases.
"""
from __future__ import annotations
import re
from typing import TYPE_CHECKING
from napalm.base.exceptions import CommandErrorException
from napalm_device_types import DhcpLeaseDict, DhcpLeasesMixin
if TYPE_CHECKING: # pragma: no cover - typing only
from napalm_device_types import CommandResult
#: The lease file dnsmasq is set to, else its default; nothing where it does not exist.
LEASES_COMMAND = (
"f=$(uci -q get dhcp.@dnsmasq[0].leasefile); f=${f:-/tmp/dhcp.leases}; "
'[ ! -e "$f" ] || cat "$f"'
)
#: What dnsmasq's lease file names as every lease's state: it holds live ones only.
ACTIVE = "active"
_MAC = re.compile(r"[0-9a-f]{2}(:[0-9a-f]{2}){5}")
def parse_dnsmasq_leases(text: str) -> list[DhcpLeaseDict]:
"""The DHCPv4 leases of dnsmasq's lease file *text*, in its order."""
leases: list[DhcpLeaseDict] = []
for line in text.splitlines():
fields = line.split()
if len(fields) < 4 or not fields[0].isdigit():
continue
mac = fields[1].lower()
if not _MAC.fullmatch(mac):
continue
leases.append(
{
"mac": mac,
"ip": fields[2],
"hostname": "" if fields[3] == "*" else fields[3],
"lease_end": int(fields[0]),
"state": ACTIVE,
}
)
return leases
class OpenWrtDhcpLeasesMixin(DhcpLeasesMixin):
"""``get_dhcp_leases``: 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 get_dhcp_leases(self) -> list[DhcpLeaseDict]:
"""The leases dnsmasq holds; [] where it serves none.
:raises CommandErrorException: when the lease file cannot be read.
"""
result = self.run_command(LEASES_COMMAND)
if result.exit_code != 0:
said = result.stderr.strip() or f"exit status {result.exit_code}"
raise CommandErrorException(f"{self.hostname}: the DHCP leases were not read: {said}")
return parse_dnsmasq_leases(result.stdout)
+6
View File
@@ -42,7 +42,10 @@ from napalm_device_types.ssh_host_keys import HostKeyCheck, SshHostKeyMismatch
from netmiko import ConnectHandler from netmiko import ConnectHandler
from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
from napalm_openwrt.ap_config import OpenWrtApConfigMixin
from napalm_openwrt.ap_writes_mixin import OpenWrtApWritesMixin
from napalm_openwrt.config_mixin import OpenWrtConfigMixin from napalm_openwrt.config_mixin import OpenWrtConfigMixin
from napalm_openwrt.dhcp_leases_mixin import OpenWrtDhcpLeasesMixin
from napalm_openwrt.firmware_mixin import OpenWrtFirmwareMixin from napalm_openwrt.firmware_mixin import OpenWrtFirmwareMixin
from napalm_openwrt.interfaces_mixin import OpenWrtInterfaceMixin from napalm_openwrt.interfaces_mixin import OpenWrtInterfaceMixin
from napalm_openwrt.lldp_agent import OpenWrtLldpAgentMixin from napalm_openwrt.lldp_agent import OpenWrtLldpAgentMixin
@@ -77,6 +80,9 @@ class OpenWrtDriver(
OpenWrtInterfaceMixin, OpenWrtInterfaceMixin,
OpenWrtVLANMixin, OpenWrtVLANMixin,
OpenWrtWirelessMixin, OpenWrtWirelessMixin,
OpenWrtApWritesMixin,
OpenWrtApConfigMixin,
OpenWrtDhcpLeasesMixin,
OpenWrtLLDPMixin, OpenWrtLLDPMixin,
OpenWrtConfigMixin, OpenWrtConfigMixin,
OpenWrtTimeSyncMixin, OpenWrtTimeSyncMixin,
+4 -2
View File
@@ -120,8 +120,8 @@ class UciStepsMixin:
raise CommandErrorException(f"{self.hostname}: `{command}` failed: {said}") raise CommandErrorException(f"{self.hostname}: `{command}` failed: {said}")
return result.stdout return result.stdout
def _uci_apply(self, config: str, changes: Sequence[str], restart: str) -> None: def _uci_apply(self, config: str, changes: Sequence[str], restart: str | None) -> None:
"""Stage *changes* to *config*, commit it, then run *restart*. """Stage *changes* to *config*, commit it, then run *restart* (None: nothing to restart).
:raises CommandErrorException: for the first step refused; see the module. :raises CommandErrorException: for the first step refused; see the module.
""" """
@@ -132,6 +132,8 @@ class UciStepsMixin:
except Exception: except Exception:
self._uci_revert(config) self._uci_revert(config)
raise raise
if restart is None:
return
try: try:
self._uci_step(restart) self._uci_step(restart)
except CommandErrorException as exc: except CommandErrorException as exc:
-22
View File
@@ -27,8 +27,6 @@ _WIRELESS = "wireless"
_SHOW_WIRELESS = "uci -q show wireless" _SHOW_WIRELESS = "uci -q show wireless"
#: Re-applies the config; enough for a MAC filter. #: Re-applies the config; enough for a MAC filter.
_WIFI_RELOAD = "wifi reload" _WIFI_RELOAD = "wifi reload"
#: A full down/up of every radio; a channel needs it (see ``push_radio_channel``).
_WIFI_RESTART = "wifi"
_ACL_OPTIONS = ("macfilter", "maclist") _ACL_OPTIONS = ("macfilter", "maclist")
#: The modes ``push_mac_acl`` takes, and the ``macfilter`` each writes ("off" writes none). #: The modes ``push_mac_acl`` takes, and the ``macfilter`` each writes ("off" writes none).
_MACFILTER_BY_MODE = {"whitelist": "allow", "blacklist": "deny", "off": None} _MACFILTER_BY_MODE = {"whitelist": "allow", "blacklist": "deny", "off": None}
@@ -641,26 +639,6 @@ class OpenWrtWirelessMixin(UciStepsMixin):
_flush() _flush()
return entries return entries
def push_radio_channel(self, radio: str, channel: int) -> None:
"""Set a new channel on *radio* via UCI and restart the wireless stack.
Uses ``wifi`` (full down/up cycle) rather than ``wifi reload``.
``wifi reload`` only re-applies the running config without changing
the physical channel on many hardware/driver combinations; a full
restart is required for channel changes to take effect.
Each step's exit status is checked (:mod:`napalm_openwrt.uci_steps`): a
refused ``uci set`` (a radio that does not exist) raises, and wifi is not
restarted for it.
:param radio: UCI radio name, e.g. ``"radio0"``.
:param channel: Channel number to set; ``0`` sets UCI ``auto``.
:raises CommandErrorException: when a step is refused, naming it.
"""
ch_val = "auto" if channel == 0 else str(channel)
change = uci("set", f"{_WIRELESS}.{radio}.channel={ch_val}")
self._uci_apply(_WIRELESS, [change], _WIFI_RESTART)
def push_mac_acl(self, ssid_name: str, mode: str, macs: list[str]) -> None: def push_mac_acl(self, ssid_name: str, mode: str, macs: list[str]) -> None:
"""Rewrite macfilter mode + maclist entries on every wifi-iface matching *ssid_name*. """Rewrite macfilter mode + maclist entries on every wifi-iface matching *ssid_name*.
+2 -2
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "napalm-openwrt" name = "napalm-openwrt"
version = "0.10.0" version = "0.11.0"
description = "NAPALM driver for OpenWrt routers/access-points" description = "NAPALM driver for OpenWrt routers/access-points"
readme = "README.md" readme = "README.md"
license = "Apache-2.0" license = "Apache-2.0"
@@ -21,7 +21,7 @@ classifiers = [
] ]
dependencies = [ dependencies = [
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks "napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
"napalm_device_types>=4.43.0", # ZabbixAgentMixin._revoke_zabbix_agent_sources "napalm_device_types>=4.54.0", # WirelessWritesMixin, ApConfigMixin, DhcpLeasesMixin
"netmiko>=4.0.0", "netmiko>=4.0.0",
"paramiko>=5.0.0", # CVE-2026-44405 "paramiko>=5.0.0", # CVE-2026-44405
"netaddr>=0.7.19", # IPAddress; below it the package has none (CI lowest job) "netaddr>=0.7.19", # IPAddress; below it the package has none (CI lowest job)
+690
View File
@@ -0,0 +1,690 @@
"""``apply_ap_config``: an access point's desired configuration as UCI scripts (NetOrk/netork#695).
netOrk built this script itself, from its AP profile, and uploaded it through the
driver's ``run_command``. The builders moved here unchanged in what they write; what
comes in is napalm-device-types' ``ApConfigDict`` and the parts the caller found
different. ``uci -q show wireless`` is the shape of ``test_wireless_writes``.
The changes are staged by a script the call waits for, so a step the AP refuses is
raised and nothing of it applied (#54); the commits, reloads and the restart run
detached afterwards, since they may cut the session.
"""
from __future__ import annotations
import subprocess
import pytest
from napalm.base.exceptions import CommandErrorException
from napalm_device_types import ApConfigDict, ApSsidConfigDict, CommandResult
from napalm_openwrt.ap_config import MASK, build_commands, build_scripts, masked
from napalm_openwrt.ap_config._common import Radios, radios_of
from napalm_openwrt.uci_steps import parse_uci_show
from tests.unit.test_wireless_writes import SHOW, WIRELESS, _driver
RADIOS = Radios(r5g="radio1", r2g="radio0")
PSK = "correct horse battery"
def _ssid(**fields: object) -> ApSsidConfigDict:
ssid: dict[str, object] = {
"name": "Corp",
"vlan_id": 30,
"bands": ["2.4 GHz", "5 GHz"],
"encryption": "psk2",
"key": PSK,
"hidden": False,
"enabled": True,
"client_isolation": False,
"max_clients": None,
"disassoc_low_ack": None,
"max_inactivity": None,
"acl_mode": "off",
"acl_macs": [],
"fast_transition": False,
}
ssid.update(fields)
return ssid # type: ignore[return-value]
def _config(**fields: object) -> ApConfigDict:
config: dict[str, object] = {
"country_code": "DE",
"htmode_5g": "VHT80",
"htmode_2g": "HT20",
"syslog_host": "192.0.2.10",
"syslog_port": 1514,
"web_ui": True,
"ssh_port": 22,
"ssh_password_auth": False,
"management_vlan_id": 10,
"management_untagged": False,
"bridge_stp": True,
"mobility_domain": "a1b2",
"ft_over_ds": True,
"ssids": [_ssid()],
}
config.update(fields)
return config # type: ignore[return-value]
def _build(parts: list[str], config: ApConfigDict | None = None, radios: Radios = RADIOS):
"""``(stage + apply, applied, skipped, restarts)``; "" when nothing is written."""
scripts = build_scripts(config or _config(), parts, radios)
script = f"{scripts.stage}\n{scripts.apply}" if scripts.stage else ""
return script, scripts.applied, scripts.skipped, scripts.restarts
def _script(parts: list[str], config: ApConfigDict | None = None, radios: Radios = RADIOS) -> str:
return _build(parts, config, radios)[0]
# -- the radios --------------------------------------------------------------------------------
def test_the_radios_are_found_by_their_band():
assert radios_of(parse_uci_show(WIRELESS)) == Radios(r5g="radio1", r2g="radio0")
def test_the_old_hwmode_names_the_band_too():
text = "wireless.wl0=wifi-device\nwireless.wl0.hwmode='11a'\n"
assert radios_of(parse_uci_show(text)) == Radios(r5g="wl0", r2g=None)
# -- radio and system parts --------------------------------------------------------------------
def test_the_country_goes_to_both_radios():
script = _script(["radio/country"])
assert "uci set wireless.radio1.country='DE'" in script
assert "uci set wireless.radio0.country='DE'" in script
def test_the_country_goes_to_the_radios_there_are():
script = _script(["radio/country"], radios=Radios(r2g="radio0"))
assert "uci set wireless.radio0.country='DE'" in script
assert "radio1" not in script
def test_each_htmode_goes_to_its_radio():
script = _script(["radio/5g_htmode", "radio/2g_htmode"])
assert "uci set wireless.radio1.htmode='VHT80'" in script
assert "uci set wireless.radio0.htmode='HT20'" in script
def test_an_htmode_without_its_radio_is_skipped():
_, applied, skipped, _ = _build(["radio/5g_htmode"], radios=Radios(r2g="radio0"))
assert (applied, skipped) == ([], ["radio/5g_htmode"])
def test_remote_syslog():
script = _script(["system/syslog"])
assert "uci set system.@system[0].log_ip='192.0.2.10'" in script
assert "uci set system.@system[0].log_port='1514'" in script
assert "uci set system.@system[0].log_remote='1'" in script
def test_remote_syslog_defaults_to_port_514():
assert "log_port='514'" in _script(["system/syslog"], _config(syslog_port=None))
@pytest.mark.parametrize(
("on", "line"),
[
(True, "/etc/init.d/uhttpd enable && /etc/init.d/uhttpd start"),
(False, "/etc/init.d/uhttpd stop; /etc/init.d/uhttpd disable"),
],
)
def test_the_web_interface_is_the_service_state(on, line):
assert line in _script(["system/web_ui"], _config(web_ui=on))
def test_the_ssh_port():
assert "uci set dropbear.@dropbear[0].Port='2222'" in _script(
["system/ssh_port"], _config(ssh_port=2222)
)
@pytest.mark.parametrize(("allowed", "value"), [(True, "on"), (False, "off")])
def test_password_logins(allowed, value):
script = _script(["system/password_auth"], _config(ssh_password_auth=allowed))
assert f"uci set dropbear.@dropbear[0].PasswordAuth='{value}'" in script
assert f"uci set dropbear.@dropbear[0].RootPasswordAuth='{value}'" in script
@pytest.mark.parametrize(
("part", "missing"),
[
("system/syslog", "syslog_host"),
("system/web_ui", "web_ui"),
("system/ssh_port", "ssh_port"),
("system/password_auth", "ssh_password_auth"),
("radio/country", "country_code"),
],
)
def test_a_part_without_its_value_is_skipped(part, missing):
config = _config()
del config[missing] # type: ignore[misc]
script, applied, skipped, _ = _build([part], config)
assert (script, applied, skipped) == ("", [], [part])
# -- network parts -----------------------------------------------------------------------------
def _ports(script: str, vid: int) -> str:
line = next(c for c in script.splitlines() if f"apbr_vlan_{vid}.ports=" in c)
return line.split("=", 1)[1]
def test_the_bridge_trunks_every_vlan_tagged_by_default():
script = _script(["network/bridge"])
assert _ports(script, 10) == "'eth0:t'"
assert _ports(script, 30) == "'eth0:t'"
def test_the_management_vlan_untagged_when_asked():
script = _script(["network/bridge"], _config(management_untagged=True))
assert _ports(script, 10) == "'eth0:u*'"
assert _ports(script, 30) == "'eth0:t'"
def test_the_bridge_drops_foreign_vlan_sections_before_its_first_vlan():
lines = _script(["network/bridge"]).split("\n")
purge = lines.index(" uci delete network.@bridge-vlan[$n]")
first = next(i for i, c in enumerate(lines) if "network.apbr_vlan_10=bridge-vlan" in c)
assert purge < first
def test_the_bridge_puts_the_networks_into_the_lan_zone():
script = _script(["network/bridge"])
assert "for net in $_mgmt_sec ap_vlan30; do" in script
assert "uci set network.ap_vlan30.device='br-ap.30'" in script
def test_the_bridge_restarts_the_ap_and_reloads_nothing():
script, applied, _, restarts = _build(["network/bridge", "network/vlan/30"])
lines = script.split("\n")
assert restarts is True
assert applied == ["network/bridge", "network/vlan/30"]
assert lines[-1] == "reboot"
assert "uci commit network" in lines
assert not any(line.startswith(("wifi reload", "/etc/init.d/network")) for line in lines)
def test_a_vlan_of_a_rebuilt_bridge_writes_nothing_of_its_own():
script = _script(["network/bridge", "network/vlan/30"])
assert "_found=$_i; break" not in script
def test_one_vlan_reuses_the_section_that_carries_it():
script = _script(["network/vlan/30"])
assert "uci set network.@bridge-vlan[$_found].ports='eth0:t'" in script
assert "uci set network.apbr_vlan_30=bridge-vlan" in script
assert "uci set network.ap_vlan30.device='br-ap.30'" in script
assert "uci delete network.@bridge-vlan[$n]" not in script
def test_the_management_vlan_untagged_on_its_own():
script = _script(["network/vlan/10"], _config(management_untagged=True))
assert "uci set network.@bridge-vlan[$_found].ports='eth0:u*'" in script
assert "uci set network.mgmt.device='br-ap.10'" in script
def test_spanning_tree_on_the_section_named_br_ap():
script = _script(["network/bridge_stp"], _config(bridge_stp=False))
assert "= 'br-ap' ] || continue" in script
assert "uci set network.$_s.stp='0'" in script
# -- wireless parts ----------------------------------------------------------------------------
def _with(**fields: object) -> ApConfigDict:
return _config(ssids=[_ssid(**fields)])
def test_a_whitelist_sets_allow_and_rebuilds_the_list():
script = _script(
["wireless/Corp/acl"], _with(acl_mode="whitelist", acl_macs=["AA:BB:CC:DD:EE:02"])
)
assert "uci set $_s.macfilter='allow'" in script
assert script.index("uci -q delete $_s.maclist") < script.index("uci add_list $_s.maclist")
def test_a_blacklist_sets_deny_even_empty():
script = _script(["wireless/Corp/acl"], _with(acl_mode="blacklist", acl_macs=[]))
assert "uci set $_s.macfilter='deny'" in script
@pytest.mark.parametrize(("mode", "macs"), [("off", ["AA:BB:CC:DD:EE:02"]), ("whitelist", [])])
def test_off_and_an_empty_whitelist_delete_the_filter(mode, macs):
"""``macfilter='disable'`` puts netifd in a restart loop; off is the option left out."""
script = _script(["wireless/Corp/acl"], _with(acl_mode=mode, acl_macs=macs))
assert "uci -q delete $_s.macfilter" in script
assert "macfilter='" not in script
def test_a_missing_ssid_is_created_on_each_band_with_its_key():
script = _script(["wireless/Corp/missing"])
assert script.count("uci add wireless wifi-iface") == 2
assert "uci set wireless.@wifi-iface[-1].device='radio0'" in script
assert "uci set wireless.@wifi-iface[-1].network='ap_vlan30'" in script
assert f"uci set wireless.@wifi-iface[-1].key='{PSK}'" in script
def test_an_open_ssid_is_created_without_a_key():
script = _script(["wireless/Corp/missing"], _with(encryption="none", key=""))
assert "encryption='none'" in script
assert ".key=" not in script
@pytest.mark.parametrize("attribute", ["missing", "bands", "encryption"])
def test_a_keyed_mode_without_its_key_is_not_written(attribute):
"""Off the air with the mode alone, unprotected with ``none``: skipped instead."""
config = _config(ssids=[{**_ssid(), "key": ""}])
script, applied, skipped, _ = _build([f"wireless/Corp/{attribute}"], config)
assert (script, applied, skipped) == ("", [], [f"wireless/Corp/{attribute}"])
def test_the_bands_take_the_ssid_off_a_radio_and_add_it_where_missing():
script = _script(["wireless/Corp/bands"], _with(bands=["5 GHz"]))
assert "= 'radio0' ] || continue\n uci delete $_s" in script
assert "if [ $_found = 0 ]; then\n uci add wireless wifi-iface" in script
assert " uci set wireless.@wifi-iface[-1].device='radio1'" in script
def test_the_encryption_with_its_key():
script = _script(["wireless/Corp/encryption"])
assert "uci set $_s.encryption='psk2'" in script
assert f"uci set $_s.key='{PSK}'" in script
def test_switching_encryption_off_needs_no_key():
script = _script(["wireless/Corp/encryption"], _with(encryption="none", key=""))
assert "uci set $_s.encryption='none'" in script
assert ".key=" not in script
def test_the_passphrase_alone():
script = _script(["wireless/Corp/passphrase"])
assert f"uci set $_s.key='{PSK}'" in script
assert ".encryption=" not in script
@pytest.mark.parametrize(
("attribute", "fields", "line"),
[
("hidden", {"hidden": True}, "uci set $_s.hidden='1'"),
("enabled", {"enabled": False}, "uci set $_s.disabled='1'"),
("enabled", {"enabled": True}, "uci set $_s.disabled='0'"),
("client_isolation", {"client_isolation": True}, "uci set $_s.isolate='1'"),
("max_clients", {"max_clients": 32}, "uci set $_s.maxassoc='32'"),
("max_clients", {"max_clients": None}, "uci -q delete $_s.maxassoc 2>/dev/null; true"),
("disassoc_low_ack", {"disassoc_low_ack": False}, "uci set $_s.disassoc_low_ack='0'"),
("max_inactivity", {"max_inactivity": 300}, "uci set $_s.max_inactivity='300'"),
("vlan", {"vlan_id": 40}, "uci set $_s.network='ap_vlan40'"),
],
)
def test_one_setting_of_an_ssid(attribute, fields, line):
assert line in _script([f"wireless/Corp/{attribute}"], _with(**fields))
@pytest.mark.parametrize(
("attribute", "fields"),
[
("disassoc_low_ack", {"disassoc_low_ack": None}),
("max_inactivity", {"max_inactivity": None}),
("vlan", {"vlan_id": None}),
],
)
def test_a_setting_left_to_the_device_is_skipped(attribute, fields):
_, applied, skipped, _ = _build([f"wireless/Corp/{attribute}"], _with(**fields))
assert (applied, skipped) == ([], [f"wireless/Corp/{attribute}"])
def test_fast_transition_off_removes_it_without_a_domain():
script = _script(["wireless/Corp/ft"], _config(mobility_domain="", ssids=[_ssid()]))
assert "uci -q delete $_s.ieee80211r" in script
assert "uci -q delete $_s.mobility_domain" in script
def test_fast_transition_on_sets_the_domain():
script = _script(["wireless/Corp/ft"], _with(fast_transition=True))
assert "uci set $_s.ieee80211r='1'" in script
assert "uci set $_s.mobility_domain='a1b2'" in script
assert "uci set $_s.ft_over_ds='1'" in script
def test_fast_transition_on_without_a_domain_is_skipped():
config = _config(mobility_domain="", ssids=[_ssid(fast_transition=True)])
assert _build(["wireless/Corp/ft"], config)[2] == ["wireless/Corp/ft"]
@pytest.mark.parametrize(
"part", ["wireless/Nobody/hidden", "system/luci", "wireless/Corp/extra/x", "radio/power"]
)
def test_a_part_the_driver_cannot_write_is_skipped(part):
assert _build([part]) == ("", [], [part], False)
# -- the script --------------------------------------------------------------------------------
def test_commits_come_before_the_reloads_network_first():
lines = _script(["system/ssh_port", "wireless/Corp/hidden", "network/vlan/30"]).split("\n")
assert lines[0] == "#!/bin/sh"
last_commit = max(i for i, c in enumerate(lines) if c.startswith("uci commit "))
assert lines[last_commit - 2 : last_commit + 1] == [
"uci commit dropbear",
"uci commit network",
"uci commit wireless",
]
assert lines[last_commit + 1 :] == [
"/etc/init.d/network reload 2>/dev/null; true",
"wifi reload 2>&1; true",
"/etc/init.d/dropbear restart 2>/dev/null; true",
]
def test_the_system_reload_restarts_logd():
assert "/etc/init.d/log restart 2>/dev/null; true" in _script(["system/syslog"])
def test_nothing_to_write_is_no_script():
assert _build([]) == ("", [], [], False)
def test_every_passphrase_is_masked():
script = _script(["wireless/Corp/encryption"])
shown = masked(script, _config())
assert PSK not in shown
assert f"uci set $_s.key={MASK}" in shown
# -- values reach uci as they are (NetOrk/netork#1463) -----------------------------------------
NASTY = [
"Bob's WiFi",
"a'; touch pwned; echo 'b",
'$(id) `id` "quoted"',
"semi;colon && pipe | back\\slash",
]
def _fake_uci(ssid: str) -> str:
"""A shell ``uci`` that knows one interface with *ssid* and logs every set/add_list."""
quoted = "'" + ssid.replace("'", "'\"'\"'") + "'"
return (
"uci() {\n"
' case "$1" in\n'
' show) echo "wireless.default_radio0.ssid=x" ;;\n'
f' -q) [ "$3" = "wireless.default_radio0.ssid" ] && printf %s {quoted} ;;\n'
' set|add_list) printf \'%s\\n\' "$2" >> "$LOG" ;;\n'
" esac\n"
"}\n"
)
def _run(command: str, ssid: str, tmp_path) -> list[str]:
log = tmp_path / "uci.log"
log.touch()
subprocess.run( # nosec B603 - a fixed /bin/sh on the test's own text
["/bin/sh", "-c", _fake_uci(ssid) + command],
env={"LOG": str(log), "PATH": "/usr/bin:/bin"},
check=True,
cwd=tmp_path,
)
return log.read_text().splitlines()
def _loop(parts: list[str], config: ApConfigDict) -> str:
"""The commands of the parts, without the stage script's own lines around them."""
plan = build_commands(config, parts, RADIOS)[0]
return "\n".join(c for c in plan.commands if not c.startswith("_part="))
@pytest.mark.parametrize("value", NASTY)
def test_a_passphrase_arrives_as_it_is(value, tmp_path):
config = _config(ssids=[_ssid(name="Home", key=value)])
assert _run(_loop(["wireless/Home/encryption"], config), "Home", tmp_path) == [
"wireless.default_radio0.encryption=psk2",
f"wireless.default_radio0.key={value}",
]
assert not (tmp_path / "pwned").exists()
@pytest.mark.parametrize("value", NASTY)
def test_an_ssid_name_is_matched_as_it_is(value, tmp_path):
config = _config(ssids=[_ssid(name=value, hidden=True)])
loop = _loop([f"wireless/{value}/hidden"], config)
assert _run(loop, value, tmp_path) == ["wireless.default_radio0.hidden=1"]
def test_a_mac_arrives_as_it_is(tmp_path):
mac = "AA:BB:CC:DD:EE:01'; touch pwned; echo '"
config = _config(ssids=[_ssid(name="Home", acl_mode="whitelist", acl_macs=[mac])])
loop = _loop(["wireless/Home/acl"], config)
assert _run(loop, "Home", tmp_path)[-1] == f"wireless.default_radio0.maclist={mac}"
assert not (tmp_path / "pwned").exists()
# -- the stage script: a refused step is reported, and nothing applied (#54) -----------------
#: A ``uci`` on PATH that knows one interface serving Corp, logs every call, and
#: refuses those whose words hold $REFUSE.
_FAKE_UCI_BIN = """#!/bin/sh
echo "$*" >> "$LOG"
if [ -n "$REFUSE" ] && echo "$*" | grep -qF -- "$REFUSE"; then
echo "uci: Invalid argument" >&2
exit 1
fi
case "$1" in
show) echo "wireless.default_radio0.ssid='Corp'" ;;
-q) [ "$2" = get ] || exit 0
[ "$3" = wireless.default_radio0.ssid ] && { echo Corp; exit 0; }
exit 1 ;;
esac
exit 0
"""
def _stage(tmp_path, parts: list[str], refuse: str = "", config: ApConfigDict | None = None):
"""Run the stage script of *parts* through /bin/sh against the fake ``uci``."""
bin_dir = tmp_path / "bin"
bin_dir.mkdir(exist_ok=True)
fake = bin_dir / "uci"
fake.write_text(_FAKE_UCI_BIN)
fake.chmod(0o755)
log = tmp_path / "uci.log"
log.touch()
script = tmp_path / "stage.sh"
script.write_text(build_scripts(config or _config(), parts, RADIOS).stage)
done = subprocess.run( # nosec B603 - a fixed /bin/sh on the test's own script
["/bin/sh", str(script)],
env={"LOG": str(log), "REFUSE": refuse, "PATH": f"{bin_dir}:/usr/bin:/bin"},
capture_output=True,
text=True,
cwd=tmp_path,
)
return done, log.read_text().splitlines()
def test_a_stage_that_goes_through_commits_nothing(tmp_path):
"""The commits are the detached script's; staging leaves the device running as it is."""
done, calls = _stage(tmp_path, ["system/ssh_port", "wireless/Corp/hidden"])
assert done.returncode == 0, done.stderr
assert "set dropbear.@dropbear[0].Port=22" in calls
assert not any(c.startswith(("commit", "revert")) for c in calls)
def test_a_refused_step_reverts_every_config_and_names_its_part(tmp_path):
done, calls = _stage(
tmp_path, ["system/ssh_port", "radio/country"], refuse="dropbear.@dropbear[0].Port"
)
assert done.returncode == 3
assert "system/ssh_port: uci set dropbear.@dropbear[0].Port=22" in done.stderr
assert "uci: Invalid argument" in done.stderr
assert "radio/country" not in done.stderr
assert {"revert dropbear", "revert wireless"} <= set(calls)
assert not any(c.startswith("commit") for c in calls)
def test_every_refused_part_is_named(tmp_path):
done, _ = _stage(tmp_path, ["radio/country", "radio/5g_htmode"], refuse="radio1")
assert "radio/country: uci set wireless.radio1.country=DE" in done.stderr
assert "radio/5g_htmode: uci set wireless.radio1.htmode=VHT80" in done.stderr
def test_a_quiet_delete_of_a_missing_option_is_no_refusal(tmp_path):
"""``uci -q delete`` of an option the section lacks exits 1; the builders count on it."""
config = _config(ssids=[_ssid(acl_mode="off")])
done, calls = _stage(tmp_path, ["wireless/Corp/acl"], refuse="-q delete", config=config)
assert done.returncode == 0, done.stderr
assert "-q delete wireless.default_radio0.macfilter" in calls
assert not any(c.startswith("revert") for c in calls)
def test_the_stage_script_removes_itself(tmp_path):
"""It holds the passphrases; the AP keeps it no longer than it runs."""
_stage(tmp_path, ["wireless/Corp/encryption"])
assert not (tmp_path / "stage.sh").exists()
def test_the_detached_script_commits_reloads_and_starts_what_is_live():
scripts = build_scripts(
_config(web_ui=False), ["system/web_ui", "wireless/Corp/hidden"], RADIOS
)
assert "uhttpd" not in scripts.stage
assert scripts.apply.split("\n") == [
"#!/bin/sh",
"uci commit wireless",
"/etc/init.d/uhttpd stop; /etc/init.d/uhttpd disable",
"wifi reload 2>&1; true",
]
# -- apply_ap_config ---------------------------------------------------------------------------
WORKDIR = "/tmp/openwrt-apply.Ab12Cd"
STAGE = f"sh {WORKDIR}/stage.sh"
class _ApplyAp:
"""``run_command`` of an AP: answers the read, makes the work directory, stages."""
def __init__(
self,
made: str = WORKDIR,
write: CommandResult | None = None,
stage: CommandResult | None = None,
) -> None:
self.made, self.write, self.stage = made, write, stage
self.calls: list[tuple[str, bytes | None]] = []
def __call__(
self,
command: str,
*,
privileged: bool = False,
timeout: float = 60,
stdin: bytes | None = None,
) -> CommandResult:
self.calls.append((command, stdin))
if command == SHOW:
return CommandResult(WIRELESS, "", 0)
if "mktemp -d" in command:
return self.write or CommandResult(self.made + "\n", "", 0)
if command == STAGE:
return self.stage or CommandResult("", "", 0)
return CommandResult("", "", 0)
@property
def commands(self) -> list[str]:
return [c for c, _ in self.calls]
def test_the_changes_are_staged_and_waited_for_then_applied_detached():
ap = _ApplyAp()
result = _driver(ap).apply_ap_config(_config(), ["radio/country", "wireless/Corp/encryption"])
(read, _), (write, stage), (write_apply, apply), (run, _), (start, _) = ap.calls
assert read == SHOW
assert write.startswith("umask 077 && d=$(mktemp -d /tmp/openwrt-apply.XXXXXX)")
assert stage is not None and f"key='{PSK}'".encode() in stage
assert write_apply == f"umask 077 && cat > {WORKDIR}/apply.sh"
assert apply is not None and b"uci commit wireless" in apply and PSK.encode() not in apply
assert run == STAGE
assert start == (
f"( sh {WORKDIR}/apply.sh > {WORKDIR}/apply.log 2>&1 < /dev/null; "
f"rm -f {WORKDIR}/apply.sh ) &"
)
assert result["applied"] == ["radio/country", "wireless/Corp/encryption"]
assert result["skipped"] == []
assert result["restarts"] is False
assert result["log"] == f"{WORKDIR}/apply.log"
assert PSK not in result["commands"]
assert "uci set wireless.radio1.country='DE'" in result["commands"]
def test_a_refused_step_raises_names_it_and_applies_nothing():
said = (
f"wireless/Corp/encryption: uci set wireless.default_radio0.key={PSK}: "
"uci: Invalid argument\n"
)
ap = _ApplyAp(stage=CommandResult("", said, 3))
with pytest.raises(CommandErrorException) as caught:
_driver(ap).apply_ap_config(_config(), ["radio/country", "wireless/Corp/encryption"])
message = str(caught.value)
assert "wireless/Corp/encryption" in message and "Invalid argument" in message
assert "nothing of it is applied" in message
assert PSK not in message
assert not any("apply.sh >" in c for c in ap.commands)
assert ap.commands[-1] == f"rm -rf {WORKDIR}"
def test_nothing_to_write_sends_only_the_read():
ap = _ApplyAp()
result = _driver(ap).apply_ap_config(_config(), ["system/luci"])
assert ap.commands == [SHOW]
assert result == {
"applied": [],
"skipped": ["system/luci"],
"restarts": False,
"commands": "",
"log": "",
}
def test_a_failed_write_runs_nothing():
ap = _ApplyAp(write=CommandResult("", "mktemp: No space left on device\n", 1))
with pytest.raises(RuntimeError, match="No space left"):
_driver(ap).apply_ap_config(_config(), ["radio/country"])
assert len(ap.calls) == 2
@pytest.mark.parametrize("made", ["", "/tmp/provision.sh", "/tmp/openwrt-apply.XXXXXX; reboot"])
def test_no_fresh_directory_reported_runs_nothing(made):
ap = _ApplyAp(made=made)
with pytest.raises(RuntimeError, match="no work directory"):
_driver(ap).apply_ap_config(_config(), ["radio/country"])
assert len(ap.calls) == 2
def test_a_bridge_rebuild_says_the_ap_restarts():
ap = _ApplyAp()
result = _driver(ap).apply_ap_config(_config(), ["network/bridge"])
assert result["restarts"] is True
assert result["commands"].endswith("\nreboot")
+177
View File
@@ -0,0 +1,177 @@
"""``push_ssid_config`` and ``set_vlan_name`` (NetOrk/netork#695).
netOrk wrote both itself, as UCI through the driver's ``cli()``, and never looked at
what came back. Here each is a checked step (NAPALM/napalm-openwrt#35): a refused one
raises and reverts what was staged.
``uci -q show wireless`` is the shape of ``test_wireless_writes``; ``uci -q show
network`` the shape OpenWrt 23.05 prints a DSA bridge in, with one anonymous and one
named ``bridge-vlan`` section.
"""
from __future__ import annotations
import pytest
from napalm.base.exceptions import CommandErrorException
from napalm_device_types import CommandResult
from tests.unit.test_wireless_writes import INVALID_ARGUMENT, SHOW, _Ap, _driver, _uci
SHOW_NETWORK = "uci -q show network"
NETWORK = """\
network.loopback=interface
network.loopback.device='lo'
network.loopback.proto='static'
network.apbr=device
network.apbr.name='br-ap'
network.apbr.type='bridge'
network.apbr.ports='eth0'
network.apbr.vlan_filtering='1'
network.@bridge-vlan[0]=bridge-vlan
network.@bridge-vlan[0].device='br-ap'
network.@bridge-vlan[0].vlan='10'
network.@bridge-vlan[0].ports='eth0:u*'
network.apbr_vlan_20=bridge-vlan
network.apbr_vlan_20.device='br-ap'
network.apbr_vlan_20.vlan='20'
network.apbr_vlan_20.ports='eth0:t'
network.apbr_vlan_20.name='Guests'
"""
class _NetAp(_Ap):
def __call__(self, command: str, **kwargs: object) -> CommandResult: # type: ignore[override]
if command == SHOW_NETWORK and command not in self.refuse:
self.commands.append(command)
return CommandResult(NETWORK, "", 0)
return super().__call__(command, **kwargs) # type: ignore[arg-type]
# -- push_ssid_config --------------------------------------------------------------------------
def test_each_setting_is_written_to_every_section_with_the_ssid_then_wifi_reloads():
ap = _Ap()
_driver(ap).push_ssid_config(
"CorpWiFi", {"hidden": True, "enabled": False, "max_inactivity": 300}
)
assert ap.commands == [
SHOW,
_uci("set", "wireless.default_radio0.hidden=1"),
_uci("set", "wireless.default_radio0.disabled=1"),
_uci("set", "wireless.default_radio0.max_inactivity=300"),
_uci("set", "wireless.default_radio1.hidden=1"),
_uci("set", "wireless.default_radio1.disabled=1"),
_uci("set", "wireless.default_radio1.max_inactivity=300"),
_uci("commit", "wireless"),
"wifi reload",
]
def test_encryption_and_key_are_written_as_given():
"""Whether a keyed mode may go without its key is the caller's policy, not the driver's."""
ap = _Ap()
_driver(ap).push_ssid_config(
"Bob's Guest", {"encryption": "sae", "key": "it's a secret", "disassoc_low_ack": False}
)
assert ap.commands[1:4] == [
_uci("set", "wireless.guest.encryption=sae"),
_uci("set", "wireless.guest.key=it's a secret"),
_uci("set", "wireless.guest.disassoc_low_ack=0"),
]
def test_enabled_is_written_as_disabled_off():
ap = _Ap()
_driver(ap).push_ssid_config("Bob's Guest", {"enabled": True})
assert _uci("set", "wireless.guest.disabled=0") in ap.commands
def test_an_empty_config_sends_nothing():
ap = _Ap()
_driver(ap).push_ssid_config("CorpWiFi", {})
assert ap.commands == []
@pytest.mark.parametrize(
"config",
[
{"colour": "blue"},
{"max_inactivity": -1},
{"max_inactivity": "300"},
{"max_inactivity": True},
],
)
def test_a_setting_the_ap_cannot_take_raises_before_anything_is_sent(config):
ap = _Ap()
with pytest.raises(ValueError):
_driver(ap).push_ssid_config("CorpWiFi", config) # type: ignore[arg-type]
assert ap.commands == []
def test_an_ssid_no_section_carries_raises_and_writes_nothing():
ap = _Ap()
with pytest.raises(CommandErrorException, match="no wifi-iface carries the SSID 'Nobody'"):
_driver(ap).push_ssid_config("Nobody", {"hidden": True})
assert ap.commands == [SHOW]
def test_a_refused_step_raises_reverts_and_does_not_reload():
refused = _uci("set", "wireless.default_radio1.hidden=1")
ap = _Ap({refused: INVALID_ARGUMENT})
with pytest.raises(CommandErrorException, match="Invalid argument"):
_driver(ap).push_ssid_config("CorpWiFi", {"hidden": True})
assert ap.commands[-2:] == [refused, _uci("revert", "wireless")]
assert "wifi reload" not in ap.commands
# -- set_vlan_name -----------------------------------------------------------------------------
def test_a_vlan_name_is_set_on_its_bridge_vlan_and_committed():
"""A label only: nothing restarts for it."""
ap = _NetAp()
assert _driver(ap).set_vlan_name(10, "Staff 'A'") is True
assert ap.commands == [
SHOW_NETWORK,
_uci("set", "network.@bridge-vlan[0].name=Staff 'A'"),
_uci("commit", "network"),
]
def test_a_named_section_is_renamed_in_place():
ap = _NetAp()
assert _driver(ap).set_vlan_name(20, "Visitors") is True
assert _uci("set", "network.apbr_vlan_20.name=Visitors") in ap.commands
def test_a_vlan_the_ap_does_not_carry_is_false_and_writes_nothing():
ap = _NetAp()
assert _driver(ap).set_vlan_name(30, "IoT") is False
assert ap.commands == [SHOW_NETWORK]
def test_a_refused_name_raises_and_reverts():
refused = _uci("set", "network.@bridge-vlan[0].name=Staff")
ap = _NetAp({refused: INVALID_ARGUMENT})
with pytest.raises(CommandErrorException, match="Invalid argument"):
_driver(ap).set_vlan_name(10, "Staff")
assert ap.commands[-1] == _uci("revert", "network")
def test_a_failed_read_raises():
ap = _NetAp({SHOW_NETWORK: CommandResult("", "uci: Entry not found\n", 1)})
with pytest.raises(CommandErrorException, match="Entry not found"):
_driver(ap).set_vlan_name(10, "Staff")
+84
View File
@@ -0,0 +1,84 @@
"""``get_dhcp_leases``: dnsmasq's lease file (NetOrk/netork#695).
The text is dnsmasq 2.90's lease file on OpenWrt 23.05, anonymised: two DHCPv4 leases
(one without a hostname, one that does not end), then the DHCPv6 part after its
``duid`` line.
"""
from __future__ import annotations
import pytest
from napalm.base.exceptions import CommandErrorException
from napalm_device_types import CommandResult
from napalm_openwrt.dhcp_leases_mixin import LEASES_COMMAND, parse_dnsmasq_leases
from tests.unit.test_wireless_writes import _driver
LEASES = """\
1764432000 00:00:5e:00:53:01 192.0.2.42 laptop 01:00:00:5e:00:53:01
1764435600 00:00:5E:00:53:02 192.0.2.43 * *
0 00:00:5e:00:53:03 192.0.2.44 printer *
duid 00:01:00:01:2c:5e:9a:10:00:00:5e:00:53:ff
1764432000 1234567 2001:db8::42 laptop 00:01:00:01:2c:5e:9a:11:00:00:5e:00:53:01
"""
def test_each_v4_lease_in_order():
assert parse_dnsmasq_leases(LEASES) == [
{
"mac": "00:00:5e:00:53:01",
"ip": "192.0.2.42",
"hostname": "laptop",
"lease_end": 1764432000,
"state": "active",
},
{
"mac": "00:00:5e:00:53:02",
"ip": "192.0.2.43",
"hostname": "",
"lease_end": 1764435600,
"state": "active",
},
{
"mac": "00:00:5e:00:53:03",
"ip": "192.0.2.44",
"hostname": "printer",
"lease_end": 0,
"state": "active",
},
]
@pytest.mark.parametrize("text", ["", "\n", "garbage\n", "x 00:00:5e:00:53:01 192.0.2.1 a *\n"])
def test_nothing_that_is_no_lease(text):
assert parse_dnsmasq_leases(text) == []
class _Ap:
def __init__(self, answer: CommandResult) -> None:
self.answer = answer
self.commands: list[str] = []
def __call__(self, command: str, **_: object) -> CommandResult:
self.commands.append(command)
return self.answer
def test_the_driver_reads_the_lease_file_dnsmasq_is_set_to():
ap = _Ap(CommandResult(LEASES, "", 0))
leases = _driver(ap).get_dhcp_leases() # type: ignore[arg-type]
assert ap.commands == [LEASES_COMMAND]
assert "uci -q get dhcp.@dnsmasq[0].leasefile" in LEASES_COMMAND
assert [lease["ip"] for lease in leases] == ["192.0.2.42", "192.0.2.43", "192.0.2.44"]
def test_an_ap_that_serves_no_leases_has_none():
"""No lease file is no dnsmasq run since boot: an answer, not a failed read."""
assert _driver(_Ap(CommandResult("", "", 0))).get_dhcp_leases() == [] # type: ignore[arg-type]
def test_a_failed_read_raises():
ap = _Ap(CommandResult("", "cat: can't open '/tmp/dhcp.leases': Permission denied\n", 1))
with pytest.raises(CommandErrorException, match="Permission denied"):
_driver(ap).get_dhcp_leases() # type: ignore[arg-type]
+56 -8
View File
@@ -1,4 +1,4 @@
"""Wireless writes: ``push_mac_acl`` and ``push_radio_channel`` (NAPALM/napalm-openwrt#35). """Wireless writes: ``push_mac_acl`` and ``set_radio_channels`` (NAPALM/napalm-openwrt#35).
Each ``uci`` step runs on an exec channel of its own, with its exit status checked: a Each ``uci`` step runs on an exec channel of its own, with its exit status checked: a
refused step raises and names itself, nothing staged after a refusal is committed, and refused step raises and names itself, nothing staged after a refusal is committed, and
@@ -248,13 +248,13 @@ def test_a_login_other_than_root_is_refused_before_anything_runs():
drv.device.remote_conn_pre.get_transport.assert_not_called() drv.device.remote_conn_pre.get_transport.assert_not_called()
# -- push_radio_channel ------------------------------------------------------------------------ # -- set_radio_channels (NetOrk/netork#695) ---------------------------------------------------
def test_a_channel_is_set_committed_and_wifi_restarted(): def test_a_channel_is_set_committed_and_wifi_restarted():
"""``wifi`` (a full restart), not ``wifi reload``: many radios keep the old channel.""" """``wifi`` (a full restart), not ``wifi reload``: many radios keep the old channel."""
ap = _Ap() ap = _Ap()
_driver(ap).push_radio_channel("radio1", 44) _driver(ap).set_radio_channels({"radio1": 44})
assert ap.commands == [ assert ap.commands == [
_uci("set", "wireless.radio1.channel=44"), _uci("set", "wireless.radio1.channel=44"),
@@ -263,28 +263,71 @@ def test_a_channel_is_set_committed_and_wifi_restarted():
] ]
def test_every_radio_changes_in_one_commit_and_one_restart():
ap = _Ap()
_driver(ap).set_radio_channels({"radio0": 6, "radio1": 36})
assert ap.commands == [
_uci("set", "wireless.radio0.channel=6"),
_uci("set", "wireless.radio1.channel=36"),
_uci("commit", "wireless"),
"wifi",
]
def test_channel_zero_is_auto(): def test_channel_zero_is_auto():
ap = _Ap() ap = _Ap()
_driver(ap).push_radio_channel("radio0", 0) _driver(ap).set_radio_channels({"radio0": 0})
assert ap.commands[0] == _uci("set", "wireless.radio0.channel=auto") assert ap.commands[0] == _uci("set", "wireless.radio0.channel=auto")
def test_no_channels_send_nothing():
ap = _Ap()
_driver(ap).set_radio_channels({})
assert ap.commands == []
@pytest.mark.parametrize(
"channels",
[
{"radio0; reboot": 6},
{"wireless.radio0": 6},
{"": 6},
{"radio0": -1},
{"radio0": "6"},
{"radio0": True},
],
)
def test_a_radio_or_channel_the_ap_cannot_take_raises_before_anything_is_sent(channels):
ap = _Ap()
with pytest.raises(ValueError):
_driver(ap).set_radio_channels(channels)
assert ap.commands == []
def test_a_refused_channel_raises_and_does_not_restart_wifi(): def test_a_refused_channel_raises_and_does_not_restart_wifi():
"""The other radio's change is reverted with it: no radio changes."""
refused = _uci("set", "wireless.radio9.channel=6") refused = _uci("set", "wireless.radio9.channel=6")
ap = _Ap({refused: INVALID_ARGUMENT}) ap = _Ap({refused: INVALID_ARGUMENT})
with pytest.raises(CommandErrorException) as caught: with pytest.raises(CommandErrorException) as caught:
_driver(ap).push_radio_channel("radio9", 6) _driver(ap).set_radio_channels({"radio0": 1, "radio9": 6})
assert refused in str(caught.value) assert refused in str(caught.value)
assert "Invalid argument" in str(caught.value) assert "Invalid argument" in str(caught.value)
assert ap.commands == [refused, _uci("revert", "wireless")] assert ap.commands == [
_uci("set", "wireless.radio0.channel=1"),
refused,
_uci("revert", "wireless"),
]
def test_a_refused_channel_commit_does_not_restart_wifi(): def test_a_refused_channel_commit_does_not_restart_wifi():
ap = _Ap({_uci("commit", "wireless"): IO_ERROR}) ap = _Ap({_uci("commit", "wireless"): IO_ERROR})
with pytest.raises(CommandErrorException, match="I/O error"): with pytest.raises(CommandErrorException, match="I/O error"):
_driver(ap).push_radio_channel("radio0", 6) _driver(ap).set_radio_channels({"radio0": 6})
assert "wifi" not in ap.commands assert "wifi" not in ap.commands
@@ -292,7 +335,12 @@ def test_a_refused_channel_commit_does_not_restart_wifi():
def test_a_failed_wifi_restart_raises_naming_it(): def test_a_failed_wifi_restart_raises_naming_it():
ap = _Ap({"wifi": CommandResult("", "", 1)}) ap = _Ap({"wifi": CommandResult("", "", 1)})
with pytest.raises(CommandErrorException, match="`wifi`.*exit status 1"): with pytest.raises(CommandErrorException, match="`wifi`.*exit status 1"):
_driver(ap).push_radio_channel("radio0", 6) _driver(ap).set_radio_channels({"radio0": 6})
def test_the_undeclared_channel_write_is_gone():
"""``set_radio_channels`` replaces it; nothing calls a name the contract lacks."""
assert not hasattr(OpenWrtDriver, "push_radio_channel")
@pytest.mark.parametrize("mode", ["deny", "Blacklist", "disable", ""]) @pytest.mark.parametrize("mode", ["deny", "Blacklist", "disable", ""])