"""The firewall's time servers and time zone (napalm-device-types, NetOrk/netork#2363). OPNsense keeps both in config.xml: ````, space-separated in the order of *Services → Network Time → General* (``services_ntpd.php``), and ````, an IANA name set on *System → Settings → General* (``system_general.php``). An empty or missing zone runs as ``Etc/UTC`` (``system_timezone_configure``); without time servers OPNsense does not run ntpd at all (``ntpd_enabled``). Both pages are legacy PHP: no API controller reads or writes either value, up to 26.7 and on ``master`` (the initial setup wizard writes the zone, but only together with the hostname, the interfaces and the root password). So the driver reads both from config.xml -- the download ``get_config`` uses -- and asks ntpd over ``/api/ntpd/service/status`` (``ntpq -pnw`` as rows) whether the clock follows a system peer. It writes neither: ``time_sync_writes`` is empty, ``configure_time_sync`` is None, and :data:`TIME_SERVERS_MENU` and :data:`TIME_ZONE_MENU` say, as data, where a person sets them. Nothing here touches which interfaces ntpd serves time on. In an HA pair the configuration sync carries the servers to the backup when its "Network Time" item (``ntpd``) is ticked; the zone is not synchronised. """ from __future__ import annotations # config.xml as the firewall's own API hands it over; ElementTree resolves no external # entities, and expat limits entity expansion since 2.4.1. import xml.etree.ElementTree as ET # nosec B405 from typing import TYPE_CHECKING, Any, ClassVar from napalm_device_types import TimeSyncDict, TimeSyncMixin #: config.xml itself (the newest entry of the configuration history). CONFIG_PATH = "/api/core/backup/download/this" #: ntpd's associations, one row per line of ``ntpq -pnw``. STATUS_PATH = "/api/ntpd/service/status" #: The zone OPNsense runs in when config.xml names none. DEFAULT_ZONE = "Etc/UTC" #: How ``ntpq`` marks the system peer, the source the clock follows. _SYSTEM_PEER = "*" def time_settings(config_xml: str) -> tuple[list[str], str]: """``(servers, zone)`` as *config_xml* names them; no zone is :data:`DEFAULT_ZONE`. :raises xml.etree.ElementTree.ParseError: for a text that is no XML. """ # The firewall's own config.xml: see the import. system = ET.fromstring(config_xml).find("system") # nosec B314 if system is None: return [], DEFAULT_ZONE servers = (system.findtext("timeservers") or "").split() zone = (system.findtext("timezone") or "").strip() return servers, zone or DEFAULT_ZONE def follows_a_peer(status: Any) -> bool | None: """Whether ntpd's *status* answer has a system peer; None for another shape.""" rows = status.get("rows") if isinstance(status, dict) else None if not isinstance(rows, list): return None return any(isinstance(row, dict) and row.get("status") == _SYSTEM_PEER for row in rows) class OPNsenseTimeSyncMixin(TimeSyncMixin): """Read the time servers and the zone; writing them is left to a person.""" #: Neither value has an API that writes it. time_sync_writes: ClassVar[frozenset[str]] = frozenset() configure_time_sync = None # type: ignore[assignment] #: The menu path to the page that lists the time servers ("Time servers"). TIME_SERVERS_MENU: tuple[str, ...] = ("Services", "Network Time", "General") #: The menu path to the page that sets the zone ("Time zone"). TIME_ZONE_MENU: tuple[str, ...] = ("System", "Settings", "General") if TYPE_CHECKING: # pragma: no cover - the driver's REST helpers def _get(self, path: str) -> dict[str, Any]: ... def _get_text(self, path: str) -> str: ... def _time_settings(self) -> tuple[list[str], str]: return time_settings(self._get_text(CONFIG_PATH)) def get_time_sync(self) -> TimeSyncDict: """The servers and zone of config.xml, and whether ntpd follows one of them. ``synchronized`` is False without servers (ntpd does not run then) and None when ntpd's status cannot be read. :raises Exception: when config.xml cannot be read, e.g. by a key without the backup privilege. """ servers, zone = self._time_settings() synchronized: bool | None = False if servers: try: synchronized = follows_a_peer(self._get(STATUS_PATH)) except Exception: # the status is an extra; the settings were read synchronized = None return { "ntp_servers": servers, "timezone": zone, "synchronized": synchronized, "daemon": "ntpd", } def get_ntp_servers(self) -> dict[str, dict[str, Any]]: """The configured servers, in their order, each with an empty dict (NAPALM's shape). The same list as ``get_time_sync()["ntp_servers"]``. :raises Exception: when config.xml cannot be read. """ servers, _zone = self._time_settings() return {server: {} for server in servers}