fix: 代理探测只看学习站,手填地址只允许公网
This commit is contained in:
+94
-15
@@ -2,12 +2,15 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
import socket
|
||||
from urllib.parse import quote, urlparse
|
||||
|
||||
import httpx
|
||||
|
||||
SCHEMES = ("http", "https", "socks4", "socks5", "socks5h")
|
||||
SOCKS_SCHEMES = ("socks4", "socks5", "socks5h")
|
||||
SCHEMES = ("http", "https", "socks4", "socks5")
|
||||
SOCKS_SCHEMES = ("socks4", "socks5")
|
||||
OFF_SCHEMES = ("", "off", "none", "direct", "close")
|
||||
POOL_SCHEMES = ("pool", "auto")
|
||||
|
||||
@@ -16,6 +19,55 @@ 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()
|
||||
@@ -24,12 +76,19 @@ def parse_proxy(value: str | None) -> str | None:
|
||||
if "://" not in text:
|
||||
text = "http://" + text
|
||||
parsed = urlparse(text)
|
||||
scheme = (parsed.scheme or "").lower()
|
||||
scheme = canonical_scheme(parsed.scheme)
|
||||
if scheme not in SCHEMES:
|
||||
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
|
||||
if not parsed.hostname:
|
||||
raise ProxyError("代理地址不完整")
|
||||
return text
|
||||
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(
|
||||
@@ -46,11 +105,11 @@ def build_proxy_url(
|
||||
auth = f"{user}:{secret}@"
|
||||
else:
|
||||
auth = ""
|
||||
return f"{scheme}://{auth}{host}:{port}"
|
||||
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 = (scheme or "").strip().lower()
|
||||
kind = canonical_scheme(scheme)
|
||||
if kind not in SCHEMES:
|
||||
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
|
||||
address = (host or "").strip()
|
||||
@@ -97,7 +156,7 @@ def view_of(account) -> dict:
|
||||
on = bool(account.proxy_scheme and account.proxy_host and account.proxy_port)
|
||||
return {
|
||||
"enabled": on,
|
||||
"scheme": account.proxy_scheme if on else "off",
|
||||
"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 "",
|
||||
@@ -110,7 +169,7 @@ def summary_of(account) -> str:
|
||||
return "自动"
|
||||
if not (account.proxy_scheme and account.proxy_host and account.proxy_port):
|
||||
return ""
|
||||
return f"{account.proxy_scheme.upper()} {account.proxy_host}:{account.proxy_port}"
|
||||
return f"{canonical_scheme(account.proxy_scheme).upper()} {account.proxy_host}:{account.proxy_port}"
|
||||
|
||||
|
||||
def url_of(account) -> str | None:
|
||||
@@ -138,20 +197,29 @@ def apply(account, scheme: str, host: str = "", port: object = None, username: s
|
||||
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
|
||||
kind, address, number, user = validate_parts(scheme, host, port, username)
|
||||
if password is not None and len(str(password)) > 256:
|
||||
raise ProxyError("代理密码过长")
|
||||
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 = ""
|
||||
@@ -201,17 +269,28 @@ def client_proxy_args(proxy: str | None, *, asynchronous: bool = False) -> dict:
|
||||
|
||||
|
||||
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:
|
||||
if isinstance(exc, (httpx.ProxyError, httpx.ConnectError, httpx.ConnectTimeout)):
|
||||
return True
|
||||
text = f"{type(exc).__name__} {exc}".lower()
|
||||
return "proxy" in text or "socks" in text
|
||||
from python_socks import ProxyConnectionError, ProxyError as SocksProxyError, ProxyTimeoutError
|
||||
|
||||
return isinstance(
|
||||
exc,
|
||||
(
|
||||
httpx.ProxyError,
|
||||
httpx.ConnectError,
|
||||
httpx.ConnectTimeout,
|
||||
SocksProxyError,
|
||||
ProxyConnectionError,
|
||||
ProxyTimeoutError,
|
||||
),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user