| 1 |
""" |
| 2 |
This file includes code adapted from HTTPX's utility module |
| 3 |
(https://github.com/encode/httpx/blob/336204f0121a9aefdebac5cacd81f912bafe8057/httpx/_utils.py). |
| 4 |
We implement custom proxy handling to support configurations like `socket_options`, |
| 5 |
which are not currently configurable through the HTTPX client. |
| 6 |
For more context, see: https://github.com/encode/httpx/discussions/3514 |
| 7 |
""" |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
import ipaddress |
| 12 |
from typing import Mapping |
| 13 |
from urllib.request import getproxies |
| 14 |
|
| 15 |
|
| 16 |
def is_ipv4_hostname(hostname: str) -> bool: |
| 17 |
try: |
| 18 |
ipaddress.IPv4Address(hostname.split("/")[0]) |
| 19 |
except Exception: |
| 20 |
return False |
| 21 |
return True |
| 22 |
|
| 23 |
|
| 24 |
def is_ipv6_hostname(hostname: str) -> bool: |
| 25 |
try: |
| 26 |
ipaddress.IPv6Address(hostname.split("/")[0]) |
| 27 |
except Exception: |
| 28 |
return False |
| 29 |
return True |
| 30 |
|
| 31 |
|
| 32 |
def get_environment_proxies() -> Mapping[str, str | None]: |
| 33 |
""" |
| 34 |
Gets the proxy mappings based on environment variables. |
| 35 |
We use our own logic to parse these variables, as HTTPX |
| 36 |
doesn’t allow full configuration of the underlying |
| 37 |
transport when proxies are set via environment variables. |
| 38 |
""" |
| 39 |
|
| 40 |
proxy_info = getproxies() |
| 41 |
mounts: dict[str, str | None] = {} |
| 42 |
|
| 43 |
for scheme in ("http", "https", "all"): |
| 44 |
if proxy_info.get(scheme): |
| 45 |
hostname = proxy_info[scheme] |
| 46 |
mounts[f"{scheme}://"] = hostname if "://" in hostname else f"http://{hostname}" |
| 47 |
|
| 48 |
no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")] |
| 49 |
for hostname in no_proxy_hosts: |
| 50 |
if hostname == "*": |
| 51 |
return {} |
| 52 |
elif hostname: |
| 53 |
if "://" in hostname: |
| 54 |
mounts[hostname] = None |
| 55 |
elif is_ipv4_hostname(hostname): |
| 56 |
mounts[f"all://{hostname}"] = None |
| 57 |
elif is_ipv6_hostname(hostname): |
| 58 |
mounts[f"all://[{hostname}]"] = None |
| 59 |
elif hostname.lower() == "localhost": |
| 60 |
mounts[f"all://{hostname}"] = None |
| 61 |
else: |
| 62 |
mounts[f"all://*{hostname}"] = None |
| 63 |
|
| 64 |
return mounts |