blob: 4e55069ca88e85ca7714e83c779afd589a504137 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# 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
|