feat(access-point): SSID settings, radio channels, VLAN names, the AP configuration and DHCP leases through declared methods (NetOrk/netork#695)

push_ssid_config, set_radio_channels and set_vlan_name run as checked
uci steps (#35): a refused step raises naming itself and reverts what
was staged. set_radio_channels replaces the undeclared push_radio_channel.

apply_ap_config takes napalm-device-types' ApConfigDict and the parts
the caller found different and writes them as one detached script: the
builder netOrk had in _uci_builders.py, moved here. It answers which
parts it wrote and which it could not, whether the AP restarts, and the
script with every passphrase masked. A passphrase part now writes the
key.

get_dhcp_leases reads dnsmasq's lease file.

Needs napalm-device-types 4.54.0; CI pre-installs it from its branch
until it is on PyPI.
This commit is contained in:
Christian Manivong committed 2026-11-29 20:51:27 +01:00
1 parent dd3e3f1543
commit 634bc9c793
18 files changed
+2108 -40

No files matched your search

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