Files
EnuivTools/backend/euniv/proxy.py
T

297 lines
9.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""账号级 HTTP/HTTPS/SOCKS4/SOCKS5 代理。账号密码可选。也可使用代理池。"""
from __future__ import annotations
import ipaddress
import re
import socket
from urllib.parse import quote, urlparse
import httpx
SCHEMES = ("http", "https", "socks4", "socks5")
SOCKS_SCHEMES = ("socks4", "socks5")
OFF_SCHEMES = ("", "off", "none", "direct", "close")
POOL_SCHEMES = ("pool", "auto")
class ProxyError(ValueError):
"""代理配置不符合要求。"""
def canonical_scheme(scheme: str | None) -> str:
kind = (scheme or "").strip().lower()
if kind == "socks5h":
return "socks5"
return kind
def assert_public_host(host: str) -> None:
"""手填和采集都只接受公网地址。"""
address = (host or "").strip()
if not address or any(char in address for char in "@/#?"):
raise ProxyError("代理只允许公网地址")
try:
addresses = [ipaddress.ip_address(address)]
except ValueError:
if not re.fullmatch(r"[A-Za-z0-9.-]+", address) or ".." in address or address.startswith("-"):
raise ProxyError("代理地址不合法")
try:
found = socket.getaddrinfo(address, None)
except OSError as exc:
raise ProxyError("代理地址无法解析") from exc
addresses = []
for item in found:
try:
addresses.append(ipaddress.ip_address(item[4][0]))
except ValueError:
continue
if not addresses:
raise ProxyError("代理地址无法解析")
for ip in addresses:
if (
ip.is_private
or ip.is_loopback
or ip.is_link_local
or ip.is_reserved
or ip.is_multicast
or ip.is_unspecified
):
raise ProxyError("代理只允许公网地址")
def _host_for_url(host: str) -> str:
try:
ipaddress.IPv6Address(host)
except ValueError:
return host
return f"[{host}]"
def parse_proxy(value: str | None) -> str | None:
"""把代理地址规范成内部使用的 URL。空值表示直连。"""
text = (value or "").strip()
if not text:
return None
if "://" not in text:
text = "http://" + text
parsed = urlparse(text)
scheme = canonical_scheme(parsed.scheme)
if scheme not in SCHEMES:
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
if not parsed.hostname:
raise ProxyError("代理地址不完整")
host = _host_for_url(parsed.hostname)
auth = ""
if parsed.username:
user = quote(parsed.username, safe="")
secret = quote(parsed.password or "", safe="")
auth = f"{user}:{secret}@"
port = f":{parsed.port}" if parsed.port else ""
return f"{scheme}://{auth}{host}{port}"
def build_proxy_url(
scheme: str,
host: str,
port: int,
username: str = "",
password: str = "",
) -> str:
scheme, host, port, username = validate_parts(scheme, host, port, username)
if username or password:
user = quote(username, safe="")
secret = quote(password, safe="")
auth = f"{user}:{secret}@"
else:
auth = ""
return f"{scheme}://{auth}{_host_for_url(host)}:{port}"
def validate_parts(scheme: str, host: str, port: object, username: str = "") -> tuple[str, str, int, str]:
kind = canonical_scheme(scheme)
if kind not in SCHEMES:
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
address = (host or "").strip()
if not address or "://" in address or any(ch.isspace() for ch in address):
raise ProxyError("请填写代理地址")
if len(address) > 255:
raise ProxyError("代理地址过长")
if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535:
raise ProxyError("代理端口须为 1 到 65535 的整数")
user = (username or "").strip()
if len(user) > 128:
raise ProxyError("代理账号过长")
return kind, address, port, user
def is_off(scheme: str | None) -> bool:
return (scheme or "").strip().lower() in OFF_SCHEMES
def is_pool(scheme: str | None) -> bool:
return (scheme or "").strip().lower() in POOL_SCHEMES
def uses_pool(account) -> bool:
return bool(getattr(account, "use_proxy_pool", False))
def enabled(account) -> bool:
if uses_pool(account):
return True
return bool(account.proxy_scheme and account.proxy_host and account.proxy_port)
def view_of(account) -> dict:
if uses_pool(account):
return {
"enabled": True,
"scheme": "pool",
"host": "",
"port": None,
"username": "",
"has_password": False,
}
on = bool(account.proxy_scheme and account.proxy_host and account.proxy_port)
return {
"enabled": on,
"scheme": canonical_scheme(account.proxy_scheme) if on else "off",
"host": account.proxy_host or "",
"port": int(account.proxy_port) if account.proxy_port else None,
"username": account.proxy_username or "",
"has_password": bool(account.proxy_password_cipher),
}
def summary_of(account) -> str:
if uses_pool(account):
return "自动"
if not (account.proxy_scheme and account.proxy_host and account.proxy_port):
return ""
return f"{canonical_scheme(account.proxy_scheme).upper()} {account.proxy_host}:{account.proxy_port}"
def url_of(account) -> str | None:
if uses_pool(account) or not (account.proxy_scheme and account.proxy_host and account.proxy_port):
return None
password = ""
if account.proxy_password_cipher:
from euniv.crypto import decrypt_secret
password = decrypt_secret(account.proxy_password_cipher)
return build_proxy_url(
account.proxy_scheme,
account.proxy_host,
int(account.proxy_port),
account.proxy_username or "",
password,
)
def apply(account, scheme: str, host: str = "", port: object = None, username: str = "", password: str | None = None) -> None:
if is_off(scheme):
clear(account)
return
if is_pool(scheme):
clear(account)
account.use_proxy_pool = True
return
kind, address, number, user = validate_parts(scheme, host, port, username)
assert_public_host(address)
if password is not None and len(str(password)) > 256:
raise ProxyError("代理密码过长")
employee_id = getattr(account, "employee_id", "")
changed = (
canonical_scheme(getattr(account, "proxy_scheme", "")) != kind
or (getattr(account, "proxy_host", "") or "") != address
or (getattr(account, "proxy_username", "") or "") != user
or getattr(account, "proxy_port", None) != number
)
if uses_pool(account) and employee_id:
from euniv.proxy_pool import release
release(str(employee_id))
account.use_proxy_pool = False
account.proxy_scheme = kind
account.proxy_host = address
account.proxy_port = number
account.proxy_username = user
if password is None:
if changed:
account.proxy_password_cipher = ""
return
if password == "":
account.proxy_password_cipher = ""
return
from euniv.crypto import encrypt_secret
account.proxy_password_cipher = encrypt_secret(str(password))
def clear(account) -> None:
account.proxy_scheme = ""
account.proxy_host = ""
account.proxy_port = None
account.proxy_username = ""
account.proxy_password_cipher = ""
account.use_proxy_pool = False
employee_id = getattr(account, "employee_id", "")
if employee_id:
from euniv.proxy_pool import release
release(str(employee_id))
def bind_url(account) -> str | None:
if uses_pool(account):
from euniv.proxy_pool import acquire
return acquire(str(account.employee_id))
return url_of(account)
def client_proxy_args(proxy: str | None, *, asynchronous: bool = False) -> dict:
"""httpx 不认 socks4;SOCKS 走 httpx-socks 传输,HTTP/HTTPS 仍用 proxy=。"""
url = parse_proxy(proxy)
if not url:
return {}
scheme = urlparse(url).scheme.lower()
if scheme in SOCKS_SCHEMES:
if asynchronous:
from httpx_socks import AsyncProxyTransport
return {"transport": AsyncProxyTransport.from_url(url)}
from httpx_socks import SyncProxyTransport
return {"transport": SyncProxyTransport.from_url(url)}
return {"proxy": url}
def sync_httpx_client(proxy: str | None = None, **kwargs) -> httpx.Client:
kwargs.setdefault("trust_env", False)
kwargs.update(client_proxy_args(proxy))
return httpx.Client(**kwargs)
def async_httpx_client(proxy: str | None = None, **kwargs) -> httpx.AsyncClient:
kwargs.setdefault("trust_env", False)
kwargs.update(client_proxy_args(proxy, asynchronous=True))
return httpx.AsyncClient(**kwargs)
def is_proxy_failure(exc: BaseException) -> bool:
from python_socks import ProxyConnectionError, ProxyError as SocksProxyError, ProxyTimeoutError
return isinstance(
exc,
(
httpx.ProxyError,
httpx.ConnectError,
httpx.ConnectTimeout,
SocksProxyError,
ProxyConnectionError,
ProxyTimeoutError,
),
)