| 1 | """Owned GET transport for operation deadlines, including DNS and body reads.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import base64 |
| 6 | from email.message import Message |
| 7 | import http.client as http_client |
| 8 | import io |
| 9 | import json |
| 10 | import os |
| 11 | import re |
| 12 | import shutil |
| 13 | import socket |
| 14 | import ssl |
| 15 | import sys |
| 16 | import tempfile |
| 17 | import threading |
| 18 | import time |
| 19 | from typing import Any, Callable |
| 20 | import urllib.error |
| 21 | from urllib.parse import urlsplit |
| 22 | import urllib.request |
| 23 | from pathlib import Path |
| 24 | |
| 25 | if __package__ in (None, ""): |
| 26 | sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) |
| 27 | |
| 28 | from lib import subproc |
| 29 | |
| 30 | # Reserve TERM and KILL/reap time inside the caller's operation budget. |
| 31 | CLEANUP_GRACE_SECONDS = 0.1 |
| 32 | MAX_RESPONSE_BYTES = 16 * 1024 * 1024 |
| 33 | MAX_ERROR_BODY_BYTES = 64 * 1024 |
| 34 | MAX_META_BYTES = 256 * 1024 |
| 35 | _STREAM_CHUNK_BYTES = 64 * 1024 |
| 36 | _MAX_HEADER_COUNT = 256 |
| 37 | _MAX_HEADER_BYTES = 64 * 1024 |
| 38 | _REDIRECT_POLICY_ATTR = "_last30days_redirect_policy" |
| 39 | _STRICT_HOSTNAME_RE = re.compile( |
| 40 | r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$" |
| 41 | ) |
| 42 | _PRIORITY_RESPONSE_HEADERS = frozenset({ |
| 43 | "retry-after", |
| 44 | "x-l30d-charge-credits", |
| 45 | "x-l30d-session", |
| 46 | "x-l30d-deadline", |
| 47 | "x-rate-limit-retry-after-seconds", |
| 48 | "x-ratelimit-reset", |
| 49 | "x-ratelimit-remaining", |
| 50 | "x-ratelimit-used", |
| 51 | "x-rate-limit-remaining", |
| 52 | "x-rate-limit-reset", |
| 53 | "content-type", |
| 54 | "content-length", |
| 55 | "content-encoding", |
| 56 | "location", |
| 57 | "etag", |
| 58 | "last-modified", |
| 59 | "mcp-session-id", |
| 60 | }) |
| 61 | |
| 62 | |
| 63 | class GetTimeout(TimeoutError): |
| 64 | def __init__(self, message, *, started): |
| 65 | super().__init__(message) |
| 66 | self.started = started |
| 67 | |
| 68 | |
| 69 | class GetLaunchError(OSError): |
| 70 | """GET worker launch failed before the worker received a request.""" |
| 71 | |
| 72 | |
| 73 | class ResponseTooLarge(OSError): |
| 74 | """Raised when an upstream response body exceeds the configured byte limit.""" |
| 75 | |
| 76 | |
| 77 | def _error_record(exc): |
| 78 | if isinstance(exc, urllib.error.URLError): |
| 79 | reason = exc.reason |
| 80 | return {"kind": "URLError", "reason": _error_record(reason) if isinstance(reason, BaseException) else str(reason)} |
| 81 | if isinstance(exc, http_client.IncompleteRead): |
| 82 | return {"kind": "IncompleteRead", "message": str(exc), "expected": exc.expected} |
| 83 | return {"kind": type(exc).__name__, "message": str(exc), "errno": getattr(exc, "errno", None)} |
| 84 | |
| 85 | |
| 86 | def _error_from_record(record): |
| 87 | from lib import public_host |
| 88 | |
| 89 | if record["kind"] == "URLError": |
| 90 | reason = record["reason"] |
| 91 | return urllib.error.URLError(_error_from_record(reason) if isinstance(reason, dict) else reason) |
| 92 | if record["kind"] == "IncompleteRead": |
| 93 | return http_client.IncompleteRead(b"", record.get("expected")) |
| 94 | kinds = { |
| 95 | "gaierror": socket.gaierror, |
| 96 | "TimeoutError": TimeoutError, |
| 97 | "ConnectionResetError": ConnectionResetError, |
| 98 | "ConnectionRefusedError": ConnectionRefusedError, |
| 99 | "NonPublicAddressError": public_host.NonPublicAddressError, |
| 100 | "OSError": OSError, |
| 101 | "ResponseTooLarge": ResponseTooLarge, |
| 102 | "ValueError": ValueError, |
| 103 | "SSLError": ssl.SSLError, |
| 104 | "SSLCertVerificationError": ssl.SSLCertVerificationError, |
| 105 | } |
| 106 | kind = kinds.get(record["kind"], OSError) |
| 107 | if record.get("errno") is not None: |
| 108 | return kind(record["errno"], record["message"]) |
| 109 | return kind(record["message"]) |
| 110 | |
| 111 | |
| 112 | def _url_matches_policy(url: str, policy: dict[str, Any]) -> bool: |
| 113 | """Validate ``url`` against a declarative JSON-serializable redirect policy.""" |
| 114 | from lib import public_host |
| 115 | |
| 116 | if not isinstance(url, str) or not url or url != url.strip(): |
| 117 | return False |
| 118 | if any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in url): |
| 119 | return False |
| 120 | require_public = bool(policy.get("require_public_syntax", True)) |
| 121 | if require_public and not public_host.is_public_address_syntax(url): |
| 122 | return False |
| 123 | try: |
| 124 | parts = urlsplit(url) |
| 125 | port = parts.port |
| 126 | except ValueError: |
| 127 | return False |
| 128 | scheme = parts.scheme.lower() |
| 129 | https_only = bool(policy.get("https_only", False)) |
| 130 | if https_only: |
| 131 | if scheme != "https": |
| 132 | return False |
| 133 | elif scheme not in ("http", "https"): |
| 134 | return False |
| 135 | if parts.username is not None or parts.password is not None or "\\" in parts.netloc: |
| 136 | return False |
| 137 | allowed_ports_raw = policy.get("allowed_ports") |
| 138 | if allowed_ports_raw is not None: |
| 139 | allowed_ports = frozenset(int(p) for p in allowed_ports_raw) |
| 140 | effective_port = port if port is not None else (443 if scheme == "https" else 80) |
| 141 | if effective_port not in allowed_ports: |
| 142 | return False |
| 143 | raw_host = parts.hostname or "" |
| 144 | if not raw_host or not raw_host.isascii(): |
| 145 | return False |
| 146 | host = raw_host[:-1].lower() if raw_host.endswith(".") else raw_host.lower() |
| 147 | exact_hosts = frozenset(str(h).lower() for h in (policy.get("exact_hosts") or ())) |
| 148 | suffix_hosts = tuple(str(s).lower() for s in (policy.get("suffix_hosts") or ())) |
| 149 | if exact_hosts or suffix_hosts: |
| 150 | if require_public: |
| 151 | if len(host) > 253 or not _STRICT_HOSTNAME_RE.fullmatch(host): |
| 152 | return False |
| 153 | if public_host._parse_ip_literal(host) is not None: |
| 154 | return False |
| 155 | return host in exact_hosts or host.endswith(suffix_hosts) |
| 156 | return True |
| 157 | |
| 158 | |
| 159 | def _build_redirect_guard(policy: dict[str, Any]): |
| 160 | """Build a redirect-guard callable from a declarative redirect policy.""" |
| 161 | allow_redirects = bool(policy.get("allow_redirects", True)) |
| 162 | |
| 163 | def _guard(newurl: str) -> bool: |
| 164 | if not allow_redirects: |
| 165 | return False |
| 166 | return _url_matches_policy(newurl, policy) |
| 167 | |
| 168 | return _guard |
| 169 | |
| 170 | |
| 171 | def _serialize_headers(raw_headers) -> list[list[str]]: |
| 172 | if not raw_headers: |
| 173 | return [] |
| 174 | priority: list[tuple[str, str]] = [] |
| 175 | other: list[tuple[str, str]] = [] |
| 176 | for key, value in raw_headers.items(): |
| 177 | k = str(key) |
| 178 | v = str(value) |
| 179 | if k.lower() in _PRIORITY_RESPONSE_HEADERS: |
| 180 | priority.append((k, v)) |
| 181 | else: |
| 182 | other.append((k, v)) |
| 183 | pairs: list[list[str]] = [] |
| 184 | used = 0 |
| 185 | for k, v in (*priority, *other): |
| 186 | if len(pairs) >= _MAX_HEADER_COUNT: |
| 187 | break |
| 188 | pair = [k, v] |
| 189 | # Measure actual ASCII JSON-encoded length (ensure_ascii=True) so |
| 190 | # \uXXXX escaping cannot expand metadata past MAX_META_BYTES and |
| 191 | # stdout stays pure ASCII on Windows cp1252 under python -I. |
| 192 | entry_len = len(json.dumps(pair)) + 2 |
| 193 | if used + entry_len > _MAX_HEADER_BYTES: |
| 194 | if k.lower() in _PRIORITY_RESPONSE_HEADERS: |
| 195 | continue |
| 196 | break |
| 197 | used += entry_len |
| 198 | pairs.append(pair) |
| 199 | return pairs |
| 200 | |
| 201 | |
| 202 | def _declared_content_length(response) -> int | None: |
| 203 | if isinstance(response, http_client.HTTPResponse): |
| 204 | length = response.length |
| 205 | return length if isinstance(length, int) and not isinstance(length, bool) and length >= 0 else None |
| 206 | headers = getattr(response, "headers", None) |
| 207 | if not headers or not hasattr(headers, "get"): |
| 208 | return None |
| 209 | raw = headers.get("Content-Length") |
| 210 | if raw is None or isinstance(raw, bool): |
| 211 | return None |
| 212 | try: |
| 213 | value = int(str(raw).strip()) |
| 214 | except (TypeError, ValueError): |
| 215 | return None |
| 216 | return value if value >= 0 else None |
| 217 | |
| 218 | |
| 219 | def _check_incomplete_read(response, *, truncate: bool) -> None: |
| 220 | if ( |
| 221 | not truncate |
| 222 | and isinstance(response, http_client.HTTPResponse) |
| 223 | and not response.chunked |
| 224 | and getattr(response, "_method", None) != "HEAD" |
| 225 | and isinstance(response.length, int) |
| 226 | and response.length > 0 |
| 227 | ): |
| 228 | raise http_client.IncompleteRead(b"", response.length) |
| 229 | |
| 230 | |
| 231 | def _stream_body_to_file(response, body_path: str, limit: int, *, truncate: bool) -> None: |
| 232 | if not truncate: |
| 233 | declared = _declared_content_length(response) |
| 234 | if declared is not None and declared > limit: |
| 235 | raise ResponseTooLarge( |
| 236 | f"Response Content-Length {declared} exceeds limit of {limit} bytes" |
| 237 | ) |
| 238 | budget = limit if truncate else limit + 1 |
| 239 | total = 0 |
| 240 | write_flags = os.O_WRONLY | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0) |
| 241 | fd = os.open(body_path, write_flags) |
| 242 | with os.fdopen(fd, "wb") as out: |
| 243 | while total < budget: |
| 244 | to_read = min(_STREAM_CHUNK_BYTES, budget - total) |
| 245 | chunk = response.read(to_read) |
| 246 | if not chunk: |
| 247 | break |
| 248 | if not truncate and total + len(chunk) > limit: |
| 249 | raise ResponseTooLarge(f"Response body exceeded limit of {limit} bytes") |
| 250 | if truncate and total + len(chunk) > limit: |
| 251 | chunk = chunk[: limit - total] |
| 252 | out.write(chunk) |
| 253 | total += len(chunk) |
| 254 | _check_incomplete_read(response, truncate=truncate) |
| 255 | |
| 256 | |
| 257 | def _read_body_inline(response, limit: int, *, truncate: bool) -> bytes: |
| 258 | if not truncate: |
| 259 | declared = _declared_content_length(response) |
| 260 | if declared is not None and declared > limit: |
| 261 | raise ResponseTooLarge( |
| 262 | f"Response Content-Length {declared} exceeds limit of {limit} bytes" |
| 263 | ) |
| 264 | read_size = limit if truncate else limit + 1 |
| 265 | data = response.read(read_size) |
| 266 | if data is None: |
| 267 | return b"" |
| 268 | if truncate: |
| 269 | return data[:limit] |
| 270 | if len(data) > limit: |
| 271 | raise ResponseTooLarge(f"Response body exceeded limit of {limit} bytes") |
| 272 | _check_incomplete_read(response, truncate=truncate) |
| 273 | return data |
| 274 | |
| 275 | |
| 276 | def get( |
| 277 | req: urllib.request.Request, |
| 278 | *, |
| 279 | timeout: float, |
| 280 | deadline_monotonic: float, |
| 281 | cancel: threading.Event | None = None, |
| 282 | read_body: bool = True, |
| 283 | read_error_body: bool = True, |
| 284 | with_headers: bool = False, |
| 285 | max_bytes: int = MAX_RESPONSE_BYTES, |
| 286 | public_only: bool | None = None, |
| 287 | redirect_policy: dict[str, Any] | None = None, |
| 288 | bypass_proxy: bool = False, |
| 289 | on_start: Callable[[], None] | None = None, |
| 290 | ): |
| 291 | """Run one GET in a child process killed at the deadline. |
| 292 | |
| 293 | Returns ``(status, body, error)``, or ``(status, body, error, headers)`` |
| 294 | with ``with_headers`` (the response headers as name/value pairs). |
| 295 | """ |
| 296 | from lib import http |
| 297 | |
| 298 | if req.get_method() != "GET": |
| 299 | raise ValueError("bounded transport supports GET only") |
| 300 | if max_bytes <= 0: |
| 301 | raise ValueError("max_bytes must be positive") |
| 302 | effective_public_only = ( |
| 303 | bool(getattr(req, http._PUBLIC_ONLY_ATTR, False)) |
| 304 | if public_only is None |
| 305 | else bool(public_only) |
| 306 | ) |
| 307 | effective_redirect_policy = ( |
| 308 | getattr(req, _REDIRECT_POLICY_ATTR, None) |
| 309 | if redirect_policy is None |
| 310 | else redirect_policy |
| 311 | ) |
| 312 | body_dir: str | None = None |
| 313 | body_path: str | None = None |
| 314 | try: |
| 315 | if read_body or read_error_body: |
| 316 | body_dir = tempfile.mkdtemp(prefix="last30days-bget-") |
| 317 | try: |
| 318 | os.chmod(body_dir, 0o700) |
| 319 | except OSError: |
| 320 | pass |
| 321 | body_path = os.path.join(body_dir, "body.bin") |
| 322 | create_flags = ( |
| 323 | os.O_CREAT |
| 324 | | os.O_EXCL |
| 325 | | os.O_WRONLY |
| 326 | | getattr(os, "O_NOFOLLOW", 0) |
| 327 | | getattr(os, "O_BINARY", 0) |
| 328 | ) |
| 329 | fd = os.open(body_path, create_flags, 0o600) |
| 330 | os.close(fd) |
| 331 | payload: dict[str, Any] = { |
| 332 | "url": req.full_url, |
| 333 | "headers": req.headers, |
| 334 | "unredirected_headers": req.unredirected_hdrs, |
| 335 | "origin_req_host": req.origin_req_host, |
| 336 | "timeout": timeout, |
| 337 | "read_body": read_body, |
| 338 | "read_error_body": read_error_body, |
| 339 | "with_headers": with_headers, |
| 340 | "max_bytes": max_bytes, |
| 341 | "body_path": body_path, |
| 342 | "public_only": effective_public_only, |
| 343 | "redirect_policy": effective_redirect_policy, |
| 344 | "bypass_proxy": bool(bypass_proxy), |
| 345 | } |
| 346 | transport_deadline = deadline_monotonic - 2 * CLEANUP_GRACE_SECONDS |
| 347 | try: |
| 348 | result = subproc.run_with_timeout( |
| 349 | [sys.executable, "-I", "-B", str(Path(__file__).resolve())], |
| 350 | timeout=max(0, transport_deadline - time.monotonic()), |
| 351 | deadline_monotonic=transport_deadline, |
| 352 | input_text=json.dumps(payload), |
| 353 | cancel=cancel, |
| 354 | cleanup_grace=CLEANUP_GRACE_SECONDS, |
| 355 | capture_limit_bytes=MAX_META_BYTES, |
| 356 | on_pid=(lambda _pid: on_start()) if on_start is not None else None, |
| 357 | ) |
| 358 | except subproc.SubprocTimeout as exc: |
| 359 | raise GetTimeout("GET exceeded operation deadline or was cancelled", started=exc.started) from exc |
| 360 | except OSError as exc: |
| 361 | if not getattr(exc, "_last30days_subproc_launch_failed", False): |
| 362 | raise |
| 363 | raise GetLaunchError(*exc.args) from exc |
| 364 | if result.returncode != 0: |
| 365 | raise OSError("bounded GET worker failed") |
| 366 | try: |
| 367 | record = json.loads(result.stdout) |
| 368 | except json.JSONDecodeError as exc: |
| 369 | raise OSError("bounded GET worker returned invalid metadata") from exc |
| 370 | if "error" in record: |
| 371 | raise _error_from_record(record["error"]) |
| 372 | body: bytes | None = None |
| 373 | if record.get("has_body") and body_path is not None: |
| 374 | read_flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0) |
| 375 | fd = os.open(body_path, read_flags) |
| 376 | with os.fdopen(fd, "rb") as fh: |
| 377 | body = fh.read(max_bytes + 1) |
| 378 | if len(body) > max_bytes: |
| 379 | raise ResponseTooLarge(f"Response body exceeded limit of {max_bytes} bytes") |
| 380 | elif record.get("body") is not None: |
| 381 | body = base64.b64decode(record["body"]) |
| 382 | error = None |
| 383 | if record.get("http_error") is not None: |
| 384 | headers = Message() |
| 385 | for key, value in record.get("headers") or []: |
| 386 | headers[key] = value |
| 387 | error = urllib.error.HTTPError( |
| 388 | record["url"], record["status"], record["http_error"], |
| 389 | headers, io.BytesIO(body or b""), |
| 390 | ) |
| 391 | if with_headers: |
| 392 | return record["status"], body, error, list(record.get("headers") or []) |
| 393 | return record["status"], body, error |
| 394 | finally: |
| 395 | if body_dir is not None: |
| 396 | shutil.rmtree(body_dir, ignore_errors=True) |
| 397 | |
| 398 | |
| 399 | def _main(): |
| 400 | from lib import http |
| 401 | |
| 402 | payload = json.load(sys.stdin) |
| 403 | req = urllib.request.Request( |
| 404 | payload["url"], headers=payload["headers"], method="GET", |
| 405 | origin_req_host=payload["origin_req_host"], |
| 406 | ) |
| 407 | for key, value in payload["unredirected_headers"].items(): |
| 408 | req.add_unredirected_header(key, value) |
| 409 | if payload.get("public_only"): |
| 410 | setattr(req, http._PUBLIC_ONLY_ATTR, True) |
| 411 | redirect_policy = payload.get("redirect_policy") |
| 412 | max_bytes = int(payload.get("max_bytes") or MAX_RESPONSE_BYTES) |
| 413 | if max_bytes <= 0: |
| 414 | max_bytes = MAX_RESPONSE_BYTES |
| 415 | body_path = payload.get("body_path") |
| 416 | want_headers = bool(payload.get("with_headers", True)) |
| 417 | error_reason = None |
| 418 | try: |
| 419 | if isinstance(redirect_policy, dict): |
| 420 | if not _url_matches_policy(req.full_url, redirect_policy): |
| 421 | raise urllib.error.URLError("refused URL by redirect policy") |
| 422 | setattr(req, http._REDIRECT_GUARD_ATTR, _build_redirect_guard(redirect_policy)) |
| 423 | try: |
| 424 | response = http.open_request( |
| 425 | req, payload["timeout"], bypass_proxy=bool(payload.get("bypass_proxy")) |
| 426 | ) |
| 427 | except urllib.error.HTTPError as exc: |
| 428 | response = exc |
| 429 | error_reason = str(exc.reason) |
| 430 | with response: |
| 431 | body = None |
| 432 | has_body = False |
| 433 | read_body = payload["read_error_body"] if error_reason is not None else payload["read_body"] |
| 434 | is_error = error_reason is not None |
| 435 | limit = min(max_bytes, MAX_ERROR_BODY_BYTES) if is_error else max_bytes |
| 436 | if read_body: |
| 437 | try: |
| 438 | if body_path: |
| 439 | _stream_body_to_file(response, body_path, limit, truncate=is_error) |
| 440 | has_body = True |
| 441 | else: |
| 442 | body = _read_body_inline(response, limit, truncate=is_error) |
| 443 | except (OSError, http_client.HTTPException): |
| 444 | if not is_error: |
| 445 | raise |
| 446 | result = { |
| 447 | "status": getattr(response, "status", 200) or 200, |
| 448 | "body": base64.b64encode(body).decode("ascii") if body is not None else None, |
| 449 | "has_body": has_body, |
| 450 | "headers": _serialize_headers(response.headers) if (want_headers or is_error) else [], |
| 451 | "url": str(response.geturl())[:4096], |
| 452 | "http_error": error_reason[:512] if error_reason is not None else None, |
| 453 | } |
| 454 | except Exception as exc: |
| 455 | result = {"error": _error_record(exc)} |
| 456 | encoded = json.dumps(result) |
| 457 | if len(encoded) > MAX_META_BYTES and "headers" in result: |
| 458 | result["headers"] = [ |
| 459 | pair for pair in result["headers"] |
| 460 | if pair[0].lower() in _PRIORITY_RESPONSE_HEADERS |
| 461 | ] |
| 462 | encoded = json.dumps(result) |
| 463 | if len(encoded) > MAX_META_BYTES: |
| 464 | result["headers"] = [] |
| 465 | encoded = json.dumps(result) |
| 466 | sys.stdout.write(encoded) |
| 467 | |
| 468 | |
| 469 | if __name__ == "__main__": |
| 470 | _main() |
| 471 |