okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-022-refusals: environmental refusals repair or warn instead of blocking (audit items 1-4, 6, 8-10, 12-15)bcf88b738

main
1.1 KiB28 linesraw
1"""HTTP calls to this computer's own servers (127.0.0.1, localhost, ::1) never go through a proxy.
2
3`urllib.request.urlopen` follows the system proxy (HTTP_PROXY, the Windows registry, a PAC file). A school or office PC sends
4`http://127.0.0.1:PORT/health` to that proxy, which cannot reach it, and Strata then reports a healthy server as "did not answer".
5Everything that talks to a local server uses `urlopen` below; any other address is passed on unchanged.
6"""
7
8from __future__ import annotations
9
10import urllib.request
11from urllib.parse import urlsplit
12
13_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
14_LOCAL = {"127.0.0.1", "localhost", "::1"}
15
16
17def is_loopback(url: str) -> bool:
18    try:
19        return (urlsplit(url).hostname or "").lower() in _LOCAL
20    except ValueError:
21        return False
22
23
24def urlopen(request, timeout: float | None = None):
25    url = request if isinstance(request, str) else request.full_url
26    if is_loopback(url):
27        return _OPENER.open(request, timeout=timeout)
28    return urllib.request.urlopen(request, timeout=timeout)