204 lines
7.3 KiB
Python
204 lines
7.3 KiB
Python
"""Decide which address the public DNS record points at.
|
|||
|
|
|
||
|
|
Reverse proxies normally run on the Proxmox host, so the record must publish the
|
||
|
|
host's public address while the vhost keeps proxying to the guest's private one.
|
||
|
|
"""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import ipaddress
|
||
|
|
import socket
|
||
|
|
from dataclasses import dataclass
|
||
|
|
from typing import Callable, Sequence
|
||
|
|
|
||
|
|
from . import __version__
|
||
|
|
from .config import DnsConfig
|
||
|
|
from .errors import ProxdomainError
|
||
|
|
from .http import Transport, UrllibTransport
|
||
|
|
|
||
|
|
HostnameResolver = Callable[[str], Sequence[str]]
|
||
|
|
TextFetcher = Callable[[str], str]
|
||
|
|
|
||
|
|
|
||
|
|
@dataclass(frozen=True)
|
||
|
|
class ResolvedAddress:
|
||
|
|
address: str
|
||
|
|
source: str
|
||
|
|
|
||
|
|
|
||
|
|
class PublicAddressResolver:
|
||
|
|
"""Resolve the address to publish, according to `[dns] target`.
|
||
|
|
|
||
|
|
The host result is cached for the lifetime of the resolver (one sync run),
|
||
|
|
so a batch of assignments performs at most one detection request.
|
||
|
|
"""
|
||
|
|
|
||
|
|
def __init__(
|
||
|
|
self,
|
||
|
|
config: DnsConfig,
|
||
|
|
*,
|
||
|
|
preference: str = "ipv4",
|
||
|
|
transport: Transport | None = None,
|
||
|
|
fetch_text: TextFetcher | None = None,
|
||
|
|
hostname_resolver: HostnameResolver | None = None,
|
||
|
|
) -> None:
|
||
|
|
self.config = config
|
||
|
|
self.preference = preference
|
||
|
|
self._transport = transport
|
||
|
|
self._fetch_text = fetch_text
|
||
|
|
self._hostname_resolver = hostname_resolver or system_hostname_addresses
|
||
|
|
self._host_cache: ResolvedAddress | None = None
|
||
|
|
|
||
|
|
def resolve(
|
||
|
|
self, *, guest_address: str = "", override: str | None = None
|
||
|
|
) -> ResolvedAddress:
|
||
|
|
if override:
|
||
|
|
return ResolvedAddress(_require_ip(override, "the --address override"), "command line")
|
||
|
|
if self.config.target == "guest":
|
||
|
|
return ResolvedAddress(_require_ip(guest_address, "the guest address"), "guest")
|
||
|
|
if self.config.target == "fixed":
|
||
|
|
return ResolvedAddress(
|
||
|
|
_require_ip(self.config.address, "dns.address"), "dns.address"
|
||
|
|
)
|
||
|
|
if self._host_cache is None:
|
||
|
|
self._host_cache = self._resolve_host()
|
||
|
|
return self._host_cache
|
||
|
|
|
||
|
|
# -- host resolution ------------------------------------------------
|
||
|
|
def _resolve_host(self) -> ResolvedAddress:
|
||
|
|
if self.config.address:
|
||
|
|
return ResolvedAddress(
|
||
|
|
_require_ip(self.config.address, "dns.address"), "dns.address"
|
||
|
|
)
|
||
|
|
if self.config.hostname:
|
||
|
|
return self._from_hostname()
|
||
|
|
return self._detect()
|
||
|
|
|
||
|
|
def _from_hostname(self) -> ResolvedAddress:
|
||
|
|
hostname = self.config.hostname
|
||
|
|
try:
|
||
|
|
raw = self._hostname_resolver(hostname)
|
||
|
|
except OSError as exc:
|
||
|
|
raise ProxdomainError(
|
||
|
|
f"cannot resolve dns.hostname {hostname}: {exc}; "
|
||
|
|
"set dns.address instead"
|
||
|
|
) from exc
|
||
|
|
parsed: list[ipaddress._BaseAddress] = []
|
||
|
|
for value in raw:
|
||
|
|
try:
|
||
|
|
parsed.append(ipaddress.ip_address(str(value)))
|
||
|
|
except ValueError:
|
||
|
|
continue
|
||
|
|
public = [address for address in parsed if address.is_global]
|
||
|
|
chosen = _pick(public or parsed, self.preference)
|
||
|
|
if chosen is None:
|
||
|
|
raise ProxdomainError(
|
||
|
|
f"dns.hostname {hostname} did not resolve to a "
|
||
|
|
f"{self.preference} address; set dns.address instead"
|
||
|
|
)
|
||
|
|
return ResolvedAddress(str(chosen), f"hostname {hostname}")
|
||
|
|
|
||
|
|
def _detect(self) -> ResolvedAddress:
|
||
|
|
urls = self._detect_urls()
|
||
|
|
if not urls:
|
||
|
|
raise ProxdomainError(
|
||
|
|
"dns.target = 'host' has no dns.address, dns.hostname or detection URL; "
|
||
|
|
"set dns.address"
|
||
|
|
)
|
||
|
|
failures: list[str] = []
|
||
|
|
for url in urls:
|
||
|
|
try:
|
||
|
|
text = self._get(url)
|
||
|
|
except ProxdomainError as exc:
|
||
|
|
failures.append(str(exc))
|
||
|
|
continue
|
||
|
|
candidate = extract_address(text)
|
||
|
|
if candidate is None:
|
||
|
|
failures.append(f"{url} returned no IP address")
|
||
|
|
continue
|
||
|
|
address = ipaddress.ip_address(candidate)
|
||
|
|
if not address.is_global:
|
||
|
|
failures.append(f"{url} returned the non-public address {candidate}")
|
||
|
|
continue
|
||
|
|
return ResolvedAddress(str(address), f"detected via {url}")
|
||
|
|
raise ProxdomainError(
|
||
|
|
"cannot determine the Proxmox host's public address: "
|
||
|
|
+ "; ".join(failures)
|
||
|
|
+ "; set dns.address (or dns.hostname) in the config, or pass --address"
|
||
|
|
)
|
||
|
|
|
||
|
|
def _detect_urls(self) -> list[str]:
|
||
|
|
if self.preference == "ipv4":
|
||
|
|
candidates = [self.config.detect_url_v4]
|
||
|
|
elif self.preference == "ipv6":
|
||
|
|
candidates = [self.config.detect_url_v6]
|
||
|
|
else:
|
||
|
|
candidates = [self.config.detect_url_v4, self.config.detect_url_v6]
|
||
|
|
return [url for url in candidates if url]
|
||
|
|
|
||
|
|
def _get(self, url: str) -> str:
|
||
|
|
if self._fetch_text is not None:
|
||
|
|
return self._fetch_text(url)
|
||
|
|
transport = self._transport or UrllibTransport()
|
||
|
|
try:
|
||
|
|
response = transport.request(
|
||
|
|
"GET",
|
||
|
|
url,
|
||
|
|
{
|
||
|
|
"User-Agent": f"proxdomain/{__version__}",
|
||
|
|
"Accept": "text/plain",
|
||
|
|
},
|
||
|
|
None,
|
||
|
|
self.config.detect_timeout,
|
||
|
|
)
|
||
|
|
except ProxdomainError:
|
||
|
|
raise
|
||
|
|
except Exception as exc: # pragma: no cover - defensive around urllib
|
||
|
|
raise ProxdomainError(f"cannot reach {url}: {exc}") from exc
|
||
|
|
if response.status >= 400:
|
||
|
|
raise ProxdomainError(f"GET {url} -> HTTP {response.status}")
|
||
|
|
return response.text()
|
||
|
|
|
||
|
|
|
||
|
|
# ---------------------------------------------------------------------------
|
||
|
|
def extract_address(text: str) -> str | None:
|
||
|
|
"""Accept `203.0.113.10`, `ip=203.0.113.10` (Cloudflare trace) or a sentence."""
|
||
|
|
for line in text.splitlines():
|
||
|
|
candidate_line = line.strip()
|
||
|
|
if not candidate_line:
|
||
|
|
continue
|
||
|
|
if candidate_line.startswith("ip="):
|
||
|
|
candidates = [candidate_line[3:]]
|
||
|
|
else:
|
||
|
|
candidates = candidate_line.replace("=", " ").split()
|
||
|
|
for candidate in candidates:
|
||
|
|
candidate = candidate.strip().strip("\"'")
|
||
|
|
try:
|
||
|
|
return str(ipaddress.ip_address(candidate))
|
||
|
|
except ValueError:
|
||
|
|
continue
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def system_hostname_addresses(hostname: str) -> list[str]:
|
||
|
|
infos = socket.getaddrinfo(hostname, None, type=socket.SOCK_STREAM)
|
||
|
|
seen: list[str] = []
|
||
|
|
for info in infos:
|
||
|
|
value = str(info[4][0])
|
||
|
|
if value not in seen:
|
||
|
|
seen.append(value)
|
||
|
|
return seen
|
||
|
|
|
||
|
|
|
||
|
|
def _pick(addresses: Sequence[ipaddress._BaseAddress], preference: str):
|
||
|
|
wanted = 4 if preference == "ipv4" else 6 if preference == "ipv6" else None
|
||
|
|
if wanted is not None:
|
||
|
|
addresses = [address for address in addresses if address.version == wanted]
|
||
|
|
return addresses[0] if addresses else None
|
||
|
|
|
||
|
|
|
||
|
|
def _require_ip(value: str, label: str) -> str:
|
||
|
|
try:
|
||
|
|
return str(ipaddress.ip_address(str(value).strip()))
|
||
|
|
except ValueError as exc:
|
||
|
|
raise ProxdomainError(f"{label} is not a valid IP address: {value!r}") from exc
|