# 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: `` ``, ``*`` 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)