604 lines
24 KiB
Python
604 lines
24 KiB
Python
"""Anonymous, bounded HTTP(S) GETs with an operator-controlled route.
|
|
|
|
Direct requests validate and pin a public destination for every hop. Proxied
|
|
requests rotate the operator pool and never fall back to direct. ``download``
|
|
is the live path; ``fetch_text`` is the direct-only path for background work
|
|
such as refreshing the pool from its list service.
|
|
"""
|
|
|
|
import contextlib
|
|
import os
|
|
import re
|
|
import socket
|
|
import sys
|
|
import tempfile
|
|
from collections.abc import Mapping
|
|
from contextlib import suppress
|
|
from dataclasses import dataclass, field
|
|
from datetime import UTC, datetime, timedelta
|
|
from email.message import Message
|
|
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network, ip_address
|
|
from pathlib import Path
|
|
from queue import Empty, Full, Queue
|
|
from threading import BoundedSemaphore, Thread
|
|
from time import monotonic, sleep
|
|
from urllib.parse import quote, urljoin, urlsplit, urlunsplit
|
|
|
|
import certifi
|
|
from curl_cffi import Curl, CurlECode, CurlError, CurlOpt
|
|
from curl_cffi.curl import CURL_WRITEFUNC_ERROR
|
|
|
|
from identity import Identity
|
|
from proxy import Pool, Proxy, from_env, max_retries, retry_after_seconds
|
|
|
|
__all__ = ["Download", "FetchError", "download", "fetch_text", "POOL"]
|
|
|
|
_MAX_URL_LENGTH = 8192
|
|
_MAX_REDIRECTS = 5
|
|
_MAX_HEADERS = 128 * 1024
|
|
_MAX_BODY = 2 * 1024 * 1024
|
|
_TIMEOUT = 25.0 # Whole request, including DNS, every hop, waits and retries.
|
|
_CONNECT_TIMEOUT_MS = 5000
|
|
_DNS_TIMEOUT = 5.0
|
|
_DNS_SLOTS = BoundedSemaphore(8)
|
|
_PROXY_COOL_SECONDS = 30.0
|
|
_REDIRECT_CODES = {301, 302, 303, 307, 308}
|
|
_REFUSALS = {401, 403, 407, 451}
|
|
_CHALLENGE_MARKERS = (
|
|
'id="challenge-stage"',
|
|
"window._cf_chl_opt",
|
|
"cf-browser-verification",
|
|
"cf-turnstile",
|
|
"/cdn-cgi/challenge-platform/scripts/jsd/main.js",
|
|
)
|
|
|
|
_BAD_URL = re.compile(r"[\x00-\x20\x7f\\]")
|
|
_BAD_ESCAPE = re.compile(r"%(?![0-9a-fA-F]{2})")
|
|
_AUTHORITY = re.compile(r"(\[[0-9a-fA-F:.]+\]|[^:@\[\]]+)(?::([0-9]{1,5}))?\Z")
|
|
_DNS_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\Z")
|
|
_NUMERIC_LABEL = re.compile(r"(?:[0-9]+|0x[0-9a-f]*)\Z")
|
|
_LOCAL_SUFFIXES = {"alt", "internal", "local", "localhost", "onion", "test"}
|
|
_IPV4_SPECIAL = (IPv4Network("192.0.0.0/24"), IPv4Network("192.88.99.0/24"))
|
|
_IPV6_GLOBAL_UNICAST = IPv6Network("2000::/3")
|
|
_IPV6_SPECIAL = (
|
|
IPv6Network("2001::/23"),
|
|
IPv6Network("2002::/16"),
|
|
IPv6Network("3fff::/20"),
|
|
)
|
|
_URI_SAFE = "/!$&'()*+,;=:@%"
|
|
_HTTP_STATUS = re.compile(rb"HTTP/\d+(?:\.\d+)? ([1-5][0-9]{2})(?:[ \r\n]|$)")
|
|
_MEDIA_TYPE = re.compile(r"[a-z0-9!#$%&'*+.^_`|~-]+/[a-z0-9!#$%&'*+.^_`|~-]+\Z")
|
|
|
|
_Address = IPv4Address | IPv6Address
|
|
|
|
|
|
class FetchError(ValueError):
|
|
"""A request failed. ``code`` is a stable classification for the caller."""
|
|
|
|
def __init__(self, code: str, message: str, retry_at: datetime | None = None) -> None:
|
|
super().__init__(message)
|
|
self.code = code
|
|
self.retry_at = retry_at
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class Download:
|
|
url: str
|
|
status: int
|
|
headers: dict[str, str]
|
|
media_type: str
|
|
charset: str | None
|
|
body: bytes
|
|
challenge: bool
|
|
route: str
|
|
proxy: str | None
|
|
proxy_url: str | None = None
|
|
solved: bool = False
|
|
turnstile: str | None = None
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class _Target:
|
|
url: str
|
|
host: str
|
|
port: int
|
|
literal: _Address | None
|
|
|
|
|
|
def _check_url_text(url: str) -> None:
|
|
if not url or len(url) > _MAX_URL_LENGTH or _BAD_URL.search(url):
|
|
raise FetchError("invalid_url", "URL is empty, too long, or contains whitespace, controls or a backslash.")
|
|
|
|
|
|
def _authority(netloc: str) -> tuple[str, int | None, _Address | None]:
|
|
match = _AUTHORITY.fullmatch(netloc)
|
|
if match is None:
|
|
raise FetchError("invalid_url", "Invalid URL authority or port; credentials are not allowed.")
|
|
host, port_text = match.groups()
|
|
port = int(port_text) if port_text else None
|
|
if port is not None and not 1 <= port <= 65535:
|
|
raise FetchError("invalid_url", "URL port must be in 1..65535.")
|
|
bracketed = host.startswith("[")
|
|
if bracketed:
|
|
host = host[1:-1]
|
|
try:
|
|
literal = ip_address(host)
|
|
except ValueError:
|
|
if bracketed:
|
|
raise FetchError("invalid_url", "Invalid IPv6 literal in URL.") from None
|
|
return host, port, None
|
|
if bracketed != isinstance(literal, IPv6Address):
|
|
raise FetchError("invalid_url", "Invalid IP literal in URL.")
|
|
return str(literal), port, literal
|
|
|
|
|
|
def _target(url: str, *, allow_private: bool = False) -> _Target:
|
|
_check_url_text(url)
|
|
try:
|
|
parts = urlsplit(url)
|
|
except ValueError:
|
|
raise FetchError("invalid_url", "Invalid URL.") from None
|
|
if parts.scheme not in {"http", "https"}:
|
|
raise FetchError("invalid_url", "Only absolute HTTP and HTTPS URLs are allowed.")
|
|
host, explicit_port, literal = _authority(parts.netloc)
|
|
if literal is None:
|
|
try:
|
|
host = host.encode("idna").decode("ascii").lower().removesuffix(".")
|
|
except UnicodeError:
|
|
raise FetchError("invalid_url", "Invalid internationalized hostname.") from None
|
|
labels = host.split(".")
|
|
if len(host) > 253 or not labels or any(not _DNS_LABEL.fullmatch(label) for label in labels):
|
|
raise FetchError("invalid_url", "Invalid hostname.")
|
|
if not allow_private and (
|
|
len(labels) < 2
|
|
or _NUMERIC_LABEL.fullmatch(labels[-1])
|
|
or labels[-1] in _LOCAL_SUFFIXES
|
|
or host == "home.arpa"
|
|
or host.endswith(".home.arpa")
|
|
):
|
|
raise FetchError("invalid_url", "Use a fully qualified hostname or a canonical IP literal.")
|
|
|
|
default_port = 443 if parts.scheme == "https" else 80
|
|
port = explicit_port if explicit_port is not None else default_port
|
|
authority = f"[{host}]" if isinstance(literal, IPv6Address) else host
|
|
if port != default_port:
|
|
authority = f"{authority}:{port}"
|
|
if _BAD_ESCAPE.search(parts.path) or _BAD_ESCAPE.search(parts.query):
|
|
raise FetchError("invalid_url", "URL contains an invalid percent escape.")
|
|
try:
|
|
path = quote(parts.path or "/", safe=_URI_SAFE)
|
|
query = quote(parts.query, safe=_URI_SAFE + "?")
|
|
except UnicodeError:
|
|
raise FetchError("invalid_url", "URL contains invalid Unicode.") from None
|
|
canonical = urlunsplit((parts.scheme, authority, path, query, ""))
|
|
_check_url_text(canonical)
|
|
return _Target(canonical, host, port, literal)
|
|
|
|
|
|
def _public(address: _Address) -> bool:
|
|
if not address.is_global or address.is_multicast or address.is_reserved:
|
|
return False
|
|
if isinstance(address, IPv4Address):
|
|
return not any(address in network for network in _IPV4_SPECIAL)
|
|
return address in _IPV6_GLOBAL_UNICAST and not any(address in network for network in _IPV6_SPECIAL)
|
|
|
|
|
|
def _lookup(host: str, port: int, *, allow_private: bool) -> tuple[_Address, ...]:
|
|
try:
|
|
records = socket.getaddrinfo(host + ".", port, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP)
|
|
except OSError:
|
|
raise FetchError("dns", "Could not resolve the destination hostname.") from None
|
|
addresses: dict[_Address, None] = {}
|
|
for family, _, _, _, sockaddr in records:
|
|
if family not in {socket.AF_INET, socket.AF_INET6}:
|
|
raise FetchError("dns", "DNS returned an unsupported address family.")
|
|
if len(sockaddr) == 4 and sockaddr[3]:
|
|
raise FetchError("dns", "Scoped IPv6 addresses are not allowed.")
|
|
try:
|
|
address = ip_address(sockaddr[0])
|
|
except ValueError:
|
|
raise FetchError("dns", "DNS returned an invalid address.") from None
|
|
if not allow_private and not _public(address):
|
|
raise FetchError("private", "The destination resolved to a non-public address.")
|
|
addresses[address] = None
|
|
if not addresses:
|
|
raise FetchError("dns", "DNS returned no addresses for the destination.")
|
|
return tuple(addresses)
|
|
|
|
|
|
def _remaining(deadline: float) -> float:
|
|
remaining = deadline - monotonic()
|
|
if remaining <= 0:
|
|
raise FetchError("timeout", "Request timed out.")
|
|
return remaining
|
|
|
|
|
|
def _resolve(target: _Target, deadline: float, *, allow_private: bool) -> tuple[_Address, ...]:
|
|
if target.literal is not None:
|
|
if not allow_private and not _public(target.literal):
|
|
raise FetchError("private", "The destination address is not public.")
|
|
return (target.literal,)
|
|
if not _DNS_SLOTS.acquire(blocking=False):
|
|
raise FetchError("dns", "DNS resolver is busy.")
|
|
result: Queue[tuple[_Address, ...] | FetchError] = Queue(maxsize=1)
|
|
|
|
def resolve() -> None:
|
|
try:
|
|
outcome = _lookup(target.host, target.port, allow_private=allow_private)
|
|
except FetchError as error:
|
|
outcome = error
|
|
with suppress(Full):
|
|
result.put_nowait(outcome) # The caller may already have given up.
|
|
|
|
# The caller owns the slot, so a getaddrinfo that outlives its deadline
|
|
# cannot starve later lookups.
|
|
try:
|
|
Thread(target=resolve, daemon=True).start()
|
|
except RuntimeError:
|
|
_DNS_SLOTS.release()
|
|
raise FetchError("dns", "Could not start the DNS resolver.") from None
|
|
try:
|
|
addresses = result.get(timeout=min(_remaining(deadline), _DNS_TIMEOUT))
|
|
except Empty:
|
|
raise FetchError("dns", "DNS resolution timed out.") from None
|
|
finally:
|
|
_DNS_SLOTS.release()
|
|
if isinstance(addresses, FetchError):
|
|
raise addresses
|
|
return addresses
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class _Reply:
|
|
body: bytearray = field(default_factory=bytearray)
|
|
status: int = 0
|
|
content_type: bytes = b""
|
|
location: bytes = b""
|
|
duplicate_location: bool = False
|
|
headers_lower: dict[str, str] = field(default_factory=dict)
|
|
cf_mitigated: bool = False
|
|
challenge_stage: bool = False
|
|
headers_complete: bool = False
|
|
header_bytes: int = 0
|
|
too_large: str = ""
|
|
discard_body: bool = False
|
|
head: bytearray = field(default_factory=bytearray)
|
|
|
|
def receive_header(self, line: bytes) -> int:
|
|
self.header_bytes += len(line)
|
|
if self.header_bytes > _MAX_HEADERS:
|
|
self.too_large = "headers"
|
|
return CURL_WRITEFUNC_ERROR
|
|
if status := _HTTP_STATUS.match(line):
|
|
self.status = int(status.group(1))
|
|
self.content_type = self.location = b""
|
|
self.cf_mitigated = self.challenge_stage = self.headers_complete = False
|
|
self.discard_body = not 200 <= self.status < 300
|
|
self.headers_lower.clear()
|
|
elif line in {b"\r\n", b"\n"}:
|
|
self.headers_complete = True
|
|
elif not self.headers_complete:
|
|
name, _, value = line.partition(b":")
|
|
name = name.strip().lower()
|
|
value = value.strip()
|
|
if name == b"content-type":
|
|
self.content_type = value
|
|
elif name == b"location":
|
|
self.duplicate_location = bool(self.location)
|
|
self.location = value
|
|
elif name == b"cf-mitigated" and value.lower() == b"challenge":
|
|
self.cf_mitigated = True
|
|
with contextlib.suppress(UnicodeDecodeError):
|
|
self.headers_lower[name.decode("latin-1")] = value.decode("latin-1")
|
|
return len(line)
|
|
|
|
def receive_body(self, chunk: bytes) -> int:
|
|
"""Write callback: sniff early bytes and keep the body when it is useful."""
|
|
if len(self.head) < 64 * 1024:
|
|
self.head.extend(chunk[: 64 * 1024 - len(self.head)])
|
|
if not (self.cf_mitigated or 200 <= self.status < 300):
|
|
return len(chunk)
|
|
if len(self.body) + len(chunk) > _MAX_BODY:
|
|
self.too_large = "body"
|
|
return CURL_WRITEFUNC_ERROR
|
|
self.body.extend(chunk)
|
|
return len(chunk)
|
|
|
|
|
|
def _curl_error(error: CurlError, proxied: bool) -> FetchError:
|
|
if error.code == CurlECode.OPERATION_TIMEDOUT:
|
|
if proxied:
|
|
# A dead or overloaded exit is the usual cause; another one may answer.
|
|
return FetchError("proxy", "Timed out through the proxy.")
|
|
return FetchError("timeout", "Request timed out.")
|
|
if error.code in {CurlECode.PEER_FAILED_VERIFICATION, CurlECode.SSL_CONNECT_ERROR}:
|
|
return FetchError("tls", "TLS handshake or certificate verification failed.")
|
|
if error.code == CurlECode.BAD_CONTENT_ENCODING:
|
|
return FetchError("encoding", "The server's content encoding could not be decoded.")
|
|
if error.code in {
|
|
CurlECode.PROXY,
|
|
CurlECode.COULDNT_RESOLVE_PROXY,
|
|
CurlECode.COULDNT_CONNECT,
|
|
CurlECode.RECV_ERROR,
|
|
CurlECode.SSL_CONNECT_ERROR,
|
|
}:
|
|
if proxied:
|
|
return FetchError("proxy", "Could not complete the exchange through the proxy.")
|
|
return FetchError("network", "Could not connect to the public destination.")
|
|
return FetchError("network", f"HTTP transfer failed (libcurl error {int(error.code)}).")
|
|
|
|
|
|
_bundle: str | None = None
|
|
|
|
|
|
def _proxy_bundle() -> str | None:
|
|
"""Trust store for an HTTPS proxy: the bundled roots plus MCP_PROXY_CA."""
|
|
global _bundle
|
|
extra = os.environ.get("MCP_PROXY_CA", "").strip()
|
|
if not extra:
|
|
return None
|
|
if _bundle is not None:
|
|
return _bundle
|
|
try:
|
|
root = Path(certifi.where()).read_bytes()
|
|
addition = Path(extra).read_bytes()
|
|
except OSError as error:
|
|
raise FetchError("config", f"MCP_PROXY_CA could not be read: {error.strerror}.") from None
|
|
path = Path(tempfile.gettempdir(), "fetch-mcp-trust.pem")
|
|
path.write_bytes(root + b"\n" + addition)
|
|
_bundle = str(path)
|
|
return _bundle
|
|
|
|
|
|
def _headers(values: Mapping[str, str] | None) -> list[str]:
|
|
if not values:
|
|
return []
|
|
return [f"{name}: {value}" for name, value in values.items() if "\n" not in value and "\r" not in value]
|
|
|
|
|
|
def _request(
|
|
target: _Target,
|
|
proxy: Proxy | None,
|
|
deadline: float,
|
|
headers: list[str],
|
|
cookies: str | None,
|
|
allow_private: bool,
|
|
identity: "Identity | None" = None,
|
|
) -> _Reply:
|
|
pinned = _resolve(target, deadline, allow_private=allow_private) if proxy is None else ()
|
|
timeout_ms = max(1, int(_remaining(deadline) * 1000))
|
|
reply = _Reply()
|
|
curl = Curl()
|
|
try:
|
|
curl.setopt(CurlOpt.URL, target.url)
|
|
curl.setopt(CurlOpt.PROTOCOLS_STR, "http,https")
|
|
curl.setopt(CurlOpt.HTTPGET, 1)
|
|
curl.setopt(CurlOpt.FOLLOWLOCATION, 0)
|
|
if proxy is None:
|
|
curl.setopt(CurlOpt.PROXY, "")
|
|
curl.setopt(CurlOpt.NOPROXY, "*")
|
|
else:
|
|
curl.setopt(CurlOpt.PROXY, f"{proxy.scheme}://{proxy.host}:{proxy.port}")
|
|
curl.setopt(CurlOpt.NOPROXY, "")
|
|
if proxy.user:
|
|
curl.setopt(CurlOpt.PROXYUSERPWD, f"{proxy.user}:{proxy.password}")
|
|
if proxy.scheme == "https" and (bundle := _proxy_bundle()):
|
|
# CAINFO also marks the handle as configured, so perform()
|
|
# does not overwrite the proxy trust store with the bundled one.
|
|
curl.setopt(CurlOpt.CAINFO, bundle)
|
|
curl.setopt(CurlOpt.PROXY_CAINFO, bundle)
|
|
if pinned:
|
|
# Keep the origin authority but hand libcurl only vetted addresses.
|
|
value = ",".join(f"[{ip}]" if isinstance(ip, IPv6Address) else str(ip) for ip in pinned)
|
|
curl.setopt(CurlOpt.RESOLVE, [f"{target.host}:{target.port}:{value}"])
|
|
curl.setopt(CurlOpt.SSL_VERIFYPEER, 1)
|
|
curl.setopt(CurlOpt.SSL_VERIFYHOST, 2)
|
|
curl.setopt(CurlOpt.NETRC, 0)
|
|
curl.setopt(CurlOpt.NOSIGNAL, 1)
|
|
curl.setopt(CurlOpt.TIMEOUT_MS, timeout_ms)
|
|
curl.setopt(CurlOpt.CONNECTTIMEOUT_MS, min(timeout_ms, _CONNECT_TIMEOUT_MS))
|
|
curl.setopt(CurlOpt.ACCEPT_ENCODING, "")
|
|
if identity is not None:
|
|
curl.setopt(CurlOpt.IMPERSONATE, identity.tls)
|
|
if headers:
|
|
curl.setopt(CurlOpt.HTTPHEADER, [line.encode("latin-1") for line in headers])
|
|
if cookies:
|
|
curl.setopt(CurlOpt.COOKIE, cookies)
|
|
curl.setopt(CurlOpt.HEADERFUNCTION, reply.receive_header)
|
|
curl.setopt(CurlOpt.WRITEFUNCTION, reply.receive_body)
|
|
curl.perform()
|
|
except CurlError as error:
|
|
if reply.too_large == "body":
|
|
raise FetchError("too_large", "Decoded response body exceeds 2 MiB.") from None
|
|
if reply.too_large == "headers":
|
|
raise FetchError("too_large", "Response headers exceed 128 KiB.") from None
|
|
if not (reply.discard_body and error.code == CurlECode.WRITE_ERROR):
|
|
raise _curl_error(error, proxy is not None) from None
|
|
finally:
|
|
curl.close()
|
|
return reply
|
|
|
|
|
|
def _content_metadata(raw: bytes) -> tuple[str, str | None]:
|
|
value = raw.decode("latin-1")
|
|
media_type = value.partition(";")[0].strip().lower()
|
|
if not _MEDIA_TYPE.fullmatch(media_type):
|
|
return "application/octet-stream", None
|
|
message = Message()
|
|
message["Content-Type"] = value
|
|
return media_type, message.get_content_charset()
|
|
|
|
|
|
def _redirect(current: _Target, reply: _Reply, *, allow_private: bool) -> _Target:
|
|
if reply.duplicate_location or not reply.location or reply.status in {303} and not reply.location:
|
|
raise FetchError("redirect", "Redirect must have exactly one nonempty Location header.")
|
|
try:
|
|
location = reply.location.decode("utf-8")
|
|
_check_url_text(location)
|
|
return _target(urljoin(current.url, location), allow_private=allow_private)
|
|
except FetchError as error:
|
|
raise FetchError("redirect", f"Unsafe redirect: {error}") from None
|
|
except ValueError:
|
|
raise FetchError("redirect", "Redirect Location is not a valid URL reference.") from None
|
|
|
|
|
|
def _headers_map(reply: _Reply) -> dict[str, str]:
|
|
return {}
|
|
|
|
|
|
def _classify(reply: _Reply) -> bool:
|
|
if reply.cf_mitigated:
|
|
return True
|
|
head = bytes(reply.head).lower()
|
|
return any(marker.encode() in head for marker in _CHALLENGE_MARKERS)
|
|
|
|
|
|
class _Pauses:
|
|
"""Per-site 429 pause, shared by every proxy."""
|
|
|
|
def __init__(self) -> None:
|
|
self._until: dict[str, float] = {}
|
|
|
|
def wait_for(self, host: str) -> float:
|
|
return max(0.0, self._until.get(host, 0.0) - monotonic())
|
|
|
|
def set(self, host: str, seconds: float) -> None:
|
|
self._until[host] = max(self._until.get(host, 0.0), monotonic() + seconds)
|
|
|
|
|
|
_pauses = _Pauses()
|
|
POOL: Pool = Pool(_route="proxy")
|
|
|
|
|
|
def _classify_proxy_failure(error: FetchError) -> bool:
|
|
return error.code == "proxy"
|
|
|
|
|
|
def download(
|
|
url: str,
|
|
*,
|
|
headers: Mapping[str, str] | None = None,
|
|
cookies: str | None = None,
|
|
deadline: float = _TIMEOUT,
|
|
allow_private: bool = False,
|
|
identity: Identity | None = None,
|
|
pin: str | None = None,
|
|
) -> Download:
|
|
"""Fetch a live URL over the configured route, or raise :class:`FetchError`."""
|
|
target = _target(url, allow_private=allow_private)
|
|
until = monotonic() + deadline
|
|
merged = dict(identity.as_headers()) if identity else {}
|
|
merged.update(headers or {})
|
|
wanted = _headers(merged)
|
|
attempts_left = 1 + max_retries()
|
|
last: FetchError | None = None
|
|
visited = {target.url}
|
|
|
|
while attempts_left:
|
|
attempts_left -= 1
|
|
entry = POOL.acquire(pin) if POOL.route == "proxy" else None
|
|
if POOL.route == "proxy" and entry is None:
|
|
raise FetchError("proxy_unavailable", "No proxy in the pool is currently usable.", None) from last
|
|
proxy = entry.proxy if entry is not None else None
|
|
try:
|
|
wait = _pauses.wait_for(target.host)
|
|
if wait:
|
|
if wait > _remaining(until):
|
|
raise FetchError(
|
|
"rate_limited",
|
|
f"{target.host} is rate-limited for {wait:.0f}s.",
|
|
datetime.now(UTC) + timedelta(seconds=wait),
|
|
)
|
|
sleep(wait)
|
|
|
|
for hop in range(_MAX_REDIRECTS + 1):
|
|
reply = _request(target, proxy, until, wanted, cookies, allow_private, identity)
|
|
if not reply.headers_complete or not reply.status:
|
|
raise FetchError("protocol", "The server did not return a valid HTTP response.")
|
|
if reply.status in _REDIRECT_CODES and hop < _MAX_REDIRECTS:
|
|
target = _redirect(target, reply, allow_private=allow_private)
|
|
if target.url in visited:
|
|
raise FetchError("redirect", "HTTP redirect loop.")
|
|
visited.add(target.url)
|
|
continue
|
|
if reply.status in _REDIRECT_CODES:
|
|
raise FetchError("redirect", "Too many HTTP redirects.")
|
|
break
|
|
|
|
if reply.status == 429:
|
|
delay = retry_after_seconds(reply.headers_lower.get("retry-after"))
|
|
pause = min(2.0 if delay is None else delay, 10**8)
|
|
_pauses.set(target.host, pause)
|
|
retry_at = datetime.now(UTC) + timedelta(seconds=pause)
|
|
if pause > _remaining(until) or not attempts_left:
|
|
raise FetchError("rate_limited", f"{target.host} asked to wait {pause:.0f}s.", retry_at)
|
|
continue
|
|
if reply.status in {200, 201, 203, 204, 206} or reply.status == 304:
|
|
media_type, charset = _content_metadata(reply.content_type)
|
|
return Download(
|
|
target.url,
|
|
reply.status,
|
|
dict(reply.headers_lower),
|
|
media_type,
|
|
charset,
|
|
bytes(reply.body),
|
|
_classify(reply),
|
|
POOL.route,
|
|
proxy.label if proxy else None,
|
|
proxy.url if proxy else None,
|
|
)
|
|
if reply.status == 407 and proxy is not None:
|
|
raise FetchError("proxy", "The proxy rejected its credentials (HTTP 407).")
|
|
if reply.status in _REFUSALS:
|
|
detail = "Challenge page" if _classify(reply) else f"HTTP {reply.status}"
|
|
raise FetchError("refused", f"The server refused the request ({detail}).")
|
|
raise FetchError("status", f"HTTP request failed with status {reply.status}.")
|
|
except FetchError as error:
|
|
last = error
|
|
if error.code == "rate_limited":
|
|
# A site pause is not a proxy fault: retry only if the budget allows.
|
|
if attempts_left and (error.retry_at is None or _pauses.wait_for(target.host) <= _remaining(until)):
|
|
continue
|
|
raise
|
|
if not attempts_left or not _classify_proxy_failure(error):
|
|
raise
|
|
if entry is not None:
|
|
POOL.cool(entry, _PROXY_COOL_SECONDS, error.code)
|
|
finally:
|
|
if entry is not None:
|
|
POOL.release(entry)
|
|
raise last or FetchError("network", "Request failed.")
|
|
|
|
|
|
def fetch_text(url: str, *, token: str = "", deadline: float = 20.0) -> str:
|
|
"""Direct GET of a UTF-8 text body (the pool list service). Never proxied."""
|
|
target = _target(url, allow_private=True)
|
|
until = monotonic() + deadline
|
|
for attempt in range(4):
|
|
reply = _request(target, None, until, [f"Authorization: Bearer {token}"] if token else [], None, True)
|
|
if reply.status == 429 and attempt < 3:
|
|
pause = retry_after_seconds(reply.headers_lower.get("retry-after")) or 2.0
|
|
if pause < _remaining(until):
|
|
sleep(pause)
|
|
continue
|
|
if reply.status != 200:
|
|
raise FetchError("status", f"List service answered HTTP {reply.status}.")
|
|
try:
|
|
return bytes(reply.body).decode("utf-8")
|
|
except UnicodeDecodeError:
|
|
raise FetchError("encoding", "List service body is not UTF-8.") from None
|
|
raise FetchError("status", "List service kept answering HTTP 429.")
|
|
|
|
|
|
def _refresh(url: str, token: str) -> str:
|
|
return fetch_text(url, token=token)
|
|
|
|
|
|
def configure() -> Pool:
|
|
"""Read operator settings, publish the pool and start refreshing it."""
|
|
global POOL
|
|
POOL = from_env()
|
|
if POOL.route == "proxy" and not POOL.start(_refresh) and not len(POOL):
|
|
print("fetch-mcp: initial proxy list unavailable; pool empty until refresh", file=sys.stderr, flush=True)
|
|
return POOL
|