fix: 代理探测只看学习站,手填地址只允许公网

This commit is contained in:
2026-11-16 09:29:45 +08:00
parent 89d9452967
commit 990b80c017
7 changed files with 152 additions and 42 deletions
+12 -5
View File
@@ -53,10 +53,7 @@ def source_title(name: str) -> str:
def is_china(country: str | None) -> bool:
text = (country or "").strip()
if not text:
return False
lower = text.lower()
return lower in CHINA or "中国" in text
return text == "中国" or text.lower() in {"cn", "chn", "china"}
def collect_all() -> list[ProxyCandidate]:
@@ -83,6 +80,10 @@ def _normalize_scheme(value: object) -> str:
kind = str(value or "").strip().lower()
if kind == "socks":
kind = "socks5"
if kind == "socks5h":
kind = "socks5"
if kind == "https":
kind = "http"
return kind if kind in SCHEMES else ""
@@ -90,6 +91,12 @@ def _normalize_host(value: object) -> str:
host = str(value or "").strip()
if not host or "://" in host or any(ch.isspace() for ch in host):
return ""
from euniv.proxy import ProxyError, assert_public_host
try:
assert_public_host(host)
except ProxyError:
return ""
return host[:255]
@@ -205,7 +212,7 @@ class ProxyHubCollector(Collector):
"Mcp-Method": "tools/call",
"Mcp-Name": "list_proxies",
}
with httpx.Client(timeout=20, follow_redirects=True) as client:
with httpx.Client(timeout=20, follow_redirects=True, trust_env=False) as client:
response = client.post(self.url, headers=headers, json=body)
response.raise_for_status()
return parse_proxyhub_result(_read_mcp(response))
+94 -15
View File
@@ -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,
),
)
+23 -1
View File
@@ -176,7 +176,7 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
) as client:
for target in PROBE_URLS:
for target in (PROBE_URL,):
started = time.perf_counter()
try:
response = client.get(target)
@@ -201,6 +201,21 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
return True, average, ""
def _direct_reaches_target() -> bool:
"""节点全灭时对照直连,区分代理故障和目标站故障。"""
try:
with sync_httpx_client(
None,
timeout=LATENCY_LIMIT,
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
) as client:
response = client.get(PROBE_URL)
return response.status_code < 500
except Exception:
return False
def _short_reason(exc: BaseException) -> str:
from python_socks import ProxyConnectionError, ProxyTimeoutError
@@ -360,6 +375,12 @@ def _refresh_body() -> dict:
]
results = _probe_many(snapshot)
probed = len(results)
failed = sum(1 for _node_id, ok, _latency, _reason in results if not ok)
if probed >= 3 and failed == probed and not _direct_reaches_target():
results = []
elif probed < 3:
results = [row for row in results if row[1]]
with SessionLocal() as db, _assign_lock:
sync = _sync_row(db)
for node_id, ok, latency, reason in results:
@@ -378,6 +399,7 @@ def _refresh_body() -> dict:
_evict_node(node.id)
sync.checked_at = _now()
sync.running = False
db.flush()
_store_counts(db, sync)
if sync.alive_count:
sync.message = ""