"""Time sync on Windows: the Windows Time service (w32time) and the time zone (NetOrk/netork#2367). :class:`WindowsTimeSyncMixin` implements napalm-device-types' :class:`~napalm_device_types.time_sync.TimeSyncMixin` for the driver, which carries each script across ``PsrpTransport.run``. **Reading** is one script. The servers and the mode are w32time's registry values (``Type``, ``NtpServer``), where group policy's override the local ones -- the registry, not ``w32tm /query /configuration``, whose text is in the host's language. ``NtpServer`` lists ``name,0xFLAGS`` pairs; the flags are dropped. ``Type NoSync`` takes time from nowhere: no servers. Synchronised is the leap indicator of ``w32tm /query /status`` (``3`` = not synchronised), the one value on the first line whatever the language; a stopped service is not synchronised. The zone is what ``tzutil /g`` reads, the registry's ``TimeZoneInformation`` (``TimeZoneKeyName``), as an IANA name (:mod:`napalm_windows.time_zones`); one with summer time switched off (``DynamicDaylightTimeDisabled``, tzutil's ``_dstoff``) is not that zone, and reads as None. The registry is read anew each time, where ``[TimeZoneInfo]::Local`` is cached for the life of the remote session. **Writing the servers** is what ``w32tm /config /manualpeerlist:"a,0x8 b,0x8" /syncfromflags:manual`` writes -- ``NtpServer`` (``0x8``: client mode, which public servers answer) and ``Type NTP`` -- set with ``Set-ItemProperty``, then ``w32tm /config /update``, after starting the service where it is stopped. No value goes through a native command line, whose quoting Windows PowerShell 5.1 mangles. Two kinds of host are refused before anything is written: a domain member that takes its time from the domain hierarchy (``NT5DS``, ``AllSync``) -- the domain sets its time, not the host -- and a host whose w32time settings come from group policy, which would override the write. **Writing the zone** is ``Set-TimeZone -Id`` (``tzutil /s``), which also switches summer time back on. Windows keeps a Windows zone, which stands for several IANA zones; the IANA name written is kept beside it (``HKLM:\\SOFTWARE\\napalm-windows``, ``IanaTimeZone``) and read back while the host is still in its Windows zone, so the zone reads back as written. A zone changed by hand since reads as its CLDR name. Each write is skipped where the host already has what it would write. """ from __future__ import annotations import json import re from typing import TYPE_CHECKING, Any, ClassVar from napalm_device_types.models import FixStepOutcomeDict from napalm_device_types.time_sync import TIME_SYNC_VALUES, TimeSyncDict, TimeSyncMixin from napalm_windows._powershell import _ps_quote from napalm_windows.time_zones import IANA_TO_WINDOWS, iana_time_zone, windows_time_zone _W32TIME = r"HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters" _TZ_INFO = r"HKLM:\SYSTEM\CurrentControlSet\Control\TimeZoneInformation" _POLICY = r"HKLM:\SOFTWARE\Policies\Microsoft\W32Time\Parameters" #: Where the IANA name of the zone written is kept. MARKER_KEY = r"HKLM:\SOFTWARE\napalm-windows" #: w32time's modes that take time from the domain hierarchy. _DOMAIN_TYPES = frozenset({"nt5ds", "allsync"}) # w32tm runs inside cmd.exe with its stderr merged: in a remote session a line on # stderr would be an error record, and the whole reading would fail. _PS_TIME_SYNC = rf""" $ErrorActionPreference = 'Stop' function V($path, $name) {{ $item = Get-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue if ($item) {{ [string]$item.$name }} }} $svc = Get-Service -Name W32Time -ErrorAction SilentlyContinue $status = $null if ($svc -and [string]$svc.Status -eq 'Running') {{ $status = @(cmd.exe /c 'w32tm /query /status 2>&1') -join "`n" }} [pscustomobject]@{{ type = V '{_W32TIME}' 'Type' ntp_server = V '{_W32TIME}' 'NtpServer' policy_type = V '{_POLICY}' 'Type' policy_server = V '{_POLICY}' 'NtpServer' service = if ($svc) {{ [string]$svc.Status }} else {{ $null }} status = $status zone = V '{_TZ_INFO}' 'TimeZoneKeyName' dst_off = V '{_TZ_INFO}' 'DynamicDaylightTimeDisabled' iana_zone = V '{MARKER_KEY}' 'IanaTimeZone' }} | ConvertTo-Json -Compress """ _PS_SET_SERVERS = f""" $ErrorActionPreference = 'Stop' Set-ItemProperty -Path '{_W32TIME}' -Name NtpServer -Value {{peers}} Set-ItemProperty -Path '{_W32TIME}' -Name Type -Value 'NTP' if ([string](Get-Service -Name W32Time).Status -ne 'Running') {{{{ Start-Service -Name W32Time }}}} $out = @(cmd.exe /c 'w32tm /config /update 2>&1') if ($LASTEXITCODE -ne 0) {{{{ throw ('w32tm /config /update: ' + ($out -join ' ')) }}}} """ _PS_SET_ZONE = """ $ErrorActionPreference = 'Stop' Set-TimeZone -Id {windows} """ _PS_MARK_ZONE = """ if (-not (Test-Path -Path '{key}')) {{ New-Item -Path '{key}' | Out-Null }} Set-ItemProperty -Path '{key}' -Name IanaTimeZone -Value {zone} """ _LEAP = re.compile(r":\s*([0-3])\b") def _servers(value: str | None) -> list[str]: """``NtpServer``'s names in order, without their ``,0xFLAGS``, each once.""" names: list[str] = [] for entry in (value or "").split(): name = entry.split(",", 1)[0].strip() if name and name.lower() not in (n.lower() for n in names): names.append(name) return names def _synchronized(service: str | None, status: str | None) -> bool | None: """The leap indicator, the first line of ``w32tm /query /status``: 3 is unsynchronised.""" if service is None: return None if service.lower() != "running": return False first = (status or "").strip().splitlines()[:1] match = _LEAP.search(first[0]) if first else None return None if match is None else match.group(1) != "3" def _windows_zone(raw: dict[str, Any]) -> str: """``TimeZoneKeyName``, which older Windows pad with NULs.""" return str(raw.get("zone") or "").split("\x00", 1)[0].strip() def _time_zone(raw: dict[str, Any]) -> str | None: """The host's zone as an IANA name: the one written while the host keeps its Windows zone, else CLDR's; None for summer time switched off or a zone not in the table.""" windows, marker = _windows_zone(raw), str(raw.get("iana_zone") or "") if not windows or str(raw.get("dst_off") or "0").strip() != "0": return None if marker and IANA_TO_WINDOWS.get(marker) == windows: return marker return iana_time_zone(windows) class _Reading: """What the reading script said, with group policy applied.""" def __init__(self, raw: dict[str, Any]) -> None: self.raw = raw self.by_policy = bool(raw.get("policy_type") or raw.get("policy_server")) self.type = str(raw.get("policy_type") or raw.get("type") or "").strip().lower() self.servers = _servers(raw.get("policy_server") or raw.get("ntp_server")) def time_sync(self) -> TimeSyncDict: return { "ntp_servers": [] if self.type == "nosync" else self.servers, "timezone": _time_zone(self.raw), "synchronized": _synchronized(self.raw.get("service"), self.raw.get("status")), "daemon": "w32time", } class WindowsTimeSyncMixin(TimeSyncMixin): """w32time's servers and the time zone; the driver carries the scripts.""" time_sync_writes: ClassVar[frozenset[str]] = TIME_SYNC_VALUES if TYPE_CHECKING: # pragma: no cover - declared for type checkers only def _run_raw(self, script: str) -> str: ... def _ts_read(self) -> _Reading: out = self._run_raw(_PS_TIME_SYNC).strip() raw = json.loads(out) if out else None if not isinstance(raw, dict): raise ValueError("the time sync reading came back empty") return _Reading(raw) def get_time_sync(self) -> TimeSyncDict: """w32time's servers, whether it is synchronised, and the zone; one round trip. :raises ValueError: when the reading came back empty. """ return self._ts_read().time_sync() def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict: """``w32tm /config`` with *servers* as manual peers; see the module.""" now = self._ts_read() if now.by_policy: return { "ok": False, "output": "the Windows Time settings come from group policy; " "they are changed there, not on the host", } if now.type in _DOMAIN_TYPES: return { "ok": False, "output": "the host takes its time from the domain hierarchy " f"(w32time Type {now.raw.get('type')}); the domain sets its time sources", } if now.type == "ntp" and [s.lower() for s in now.servers] == [s.lower() for s in servers]: return {"ok": True, "output": "w32time already has these servers"} peers = " ".join(f"{server},0x8" for server in servers) self._run_raw(_PS_SET_SERVERS.format(peers=_ps_quote(peers))) return {"ok": True, "output": f"w32time set to {', '.join(servers)}"} def _write_time_zone(self, zone: str) -> FixStepOutcomeDict: """``Set-TimeZone`` to *zone*'s Windows zone, and *zone* kept beside it; see the module.""" windows = windows_time_zone(zone) if windows is None: return {"ok": False, "output": f"there is no Windows time zone for {zone}"} now = self._ts_read().raw script = "" if _windows_zone(now) != windows or str(now.get("dst_off") or "0").strip() != "0": script += _PS_SET_ZONE.format(windows=_ps_quote(windows)) if script or now.get("iana_zone") != zone: script += _PS_MARK_ZONE.format(key=MARKER_KEY, zone=_ps_quote(zone)) if not script: return {"ok": True, "output": f"the host is in {zone} already"} self._run_raw(script) return {"ok": True, "output": f"time zone set to {windows} ({zone})"}