# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause """Canonical hostname normalization shared by URL, config, and source rules.""" import ipaddress import re from urllib.parse import urlsplit LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\Z") PATTERN_LABEL = re.compile(r"[a-z0-9*?\[\]-]+\Z") def normalize_hostname( value: str, *, from_url: bool = False, allow_patterns: bool = False ) -> str: """Return the canonical IDNA hostname or IP literal. Bare hostnames are required by default. ``from_url=True`` extracts a hostname from a URL, including bracketed IPv6 literals. ``allow_patterns`` permits sender-side ignored-hostname glob patterns; it must not be used for receiver allow/block entries or allowed target hosts. Whitespace and malformed hosts are rejected. Callers normalizing config collections may strip surrounding whitespace before calling this function. :raises ValueError: If the hostname is missing or malformed. """ if not isinstance(value, str) or not value or value != value.strip(): raise ValueError("Enter a hostname, without a URL or whitespace.") if from_url: try: hostname = urlsplit(value).hostname except ValueError as exc: raise ValueError("Invalid hostname.") from exc if hostname is None: raise ValueError("Invalid hostname.") else: hostname = value hostname = hostname.lower().rstrip(".") try: return str(ipaddress.ip_address(hostname)) except ValueError: pass try: hostname = hostname.encode("idna").decode("ascii").lower() except (UnicodeError, ValueError) as exc: raise ValueError("Invalid hostname.") from exc label_pattern = PATTERN_LABEL if allow_patterns else LABEL if ( not hostname or len(hostname) > 253 or any(not label_pattern.fullmatch(label) for label in hostname.split(".")) ): raise ValueError("Invalid hostname.") return hostname