Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

fix(linux): Cicada uses the proxy set in Settings › Network › Network Proxy, and says when that proxy doesn't answer or is Automatic

wquguru8c2784a6f252
diff --git a/linux/cicada/core/aicheck.py b/linux/cicada/core/aicheck.py
index 25856d5..37a3377 100644
--- a/linux/cicada/core/aicheck.py
+++ b/linux/cicada/core/aicheck.py
@@ -46,7 +46,8 @@ class AICheck:
self.steps = {s: State() for s in STEPS}
self.at: float | None = None
self.passive = False
- # ("system",) a proxy is on; ("app", port) a proxy app listens but the system proxy is off; ("none",).
+ # proxy.hint: ("system",) a proxy is in use; ("dead", "host:port") it doesn't answer; ("pac",)
+ # GNOME's is automatic; ("app", port) a proxy app listens but no proxy is set; ("none",).
self.proxy: tuple | None = None
self.balance: float | None = None
@@ -160,6 +161,12 @@ class AICheck:
return None
if self.proxy[0] == "system":
return LF("开了代理也连不上:换一个节点,或检查代理软件是否放过 %@。", host)
+ if self.proxy[0] == "dead":
+ # Linux: the proxy requests go through (the environment's or GNOME's) doesn't answer.
+ return LF("代理 %@ 没有回应。打开代理软件,或在 设置 › 网络 › 网络代理 里改正。", self.proxy[1])
+ if self.proxy[0] == "pac":
+ # GNOME's "automatic" needs a PAC file evaluated, which the app can't: requests go direct.
+ return L("系统代理设成了“自动”,知了用不了。在 设置 › 网络 › 网络代理 里改成“手动”。")
if self.proxy[0] == "app":
# As text: a number would be grouped ("7,890") on the Mac, which keys it this way.
return LF("代理软件在运行(端口 %@),但没开系统代理。在代理软件里打开“系统代理”。", str(self.proxy[1]))
diff --git a/linux/cicada/core/ling.py b/linux/cicada/core/ling.py
index 2e116ef..ad03381 100644
--- a/linux/cicada/core/ling.py
+++ b/linux/cicada/core/ling.py
@@ -151,14 +151,15 @@ class StreamResponse:
class UrlTransport:
- """How requests leave the app: urllib (which honours http_proxy / https_proxy), or a fake in tests.
+ """How requests leave the app: urllib through this computer's proxy (proxy.urlopen: the
+ environment's, else GNOME's manual one), or a fake in tests.
Raises TimeoutError on a timeout and OSError when the network fails."""
@staticmethod
def send(url: str, method: str, body: str | None, headers: dict, timeout: float) -> Response:
req = urllib.request.Request(url, data=body.encode() if body is not None else None, method=method, headers=headers)
try:
- with urllib.request.urlopen(req, timeout=timeout) as r:
+ with proxy.urlopen(req, timeout=timeout) as r:
return Response(r.status, r.read().decode("utf-8", "replace"))
except urllib.error.HTTPError as e:
return Response(e.code, e.read().decode("utf-8", "replace") if e.fp else "",
@@ -176,7 +177,7 @@ class UrlTransport:
raw pieces (OpenRouter's speech streams the PCM bytes themselves)."""
req = urllib.request.Request(url, data=body.encode(), method="POST", headers=headers)
try:
- r = urllib.request.urlopen(req, timeout=timeout)
+ r = proxy.urlopen(req, timeout=timeout)
except urllib.error.HTTPError as e:
return StreamResponse(e.code, iter(()))
except socket.timeout as e:
@@ -243,7 +244,7 @@ class LingClient:
self.seconds: float | None = None # how long the last good check took
# The last time the room voice spoke (or failed to) through this service: (ok, time).
self.last_voice: tuple | None = None
- # Reads this computer's proxy settings to word the "can't reach" hint (never used to connect).
+ # Words the "can't reach" hint from the proxy requests go through (proxy.py).
self.proxy_hint = proxy.hint
# Debug control only: every check ends this way (a reason, or "lowBalance"), for screenshots.
self.simulate: str | None = None
diff --git a/linux/cicada/core/proxy.py b/linux/cicada/core/proxy.py
index 31f039f..b3b0ab2 100644
--- a/linux/cicada/core/proxy.py
+++ b/linux/cicada/core/proxy.py
@@ -1,47 +1,331 @@
-"""Words the "can't reach the AI service" hint (ProxyHint.swift). Read-only on purpose: the app never
-sets or picks a proxy of its own (urllib already goes through `https_proxy` when it is set); it only
-tells the user which of three situations they are in, so the hint says what to do."""
+"""How the app's requests reach the internet, and the words of the "can't reach the AI service" hint
+(ProxyHint.swift). The app never sets a proxy; it uses the one this computer has:
+
+- the environment's `https_proxy` (`http_proxy` for http://), as urllib always did, or `all_proxy`
+ (an HTTP or SOCKS5 proxy);
+- else GNOME's 设置 › 网络 › 网络代理 set to manual, which isn't passed to apps' environments: its
+ HTTPS proxy, else the HTTP one (use-same-proxy, GNOME's default), else its SOCKS host, except for
+ the hosts it says to ignore. The website's proxy help sends Linux users exactly there.
+
+"Automatic" (a PAC file) needs a JavaScript engine to evaluate, so requests go direct then, and the
+hint says so rather than claiming a proxy is on. Every request (AI service, translation, updates)
+goes through `urlopen` here."""
from __future__ import annotations
+import ast
+import fnmatch
+import http.client
+import ipaddress
import os
import socket
+import struct
import subprocess
+import threading
+import time
+import urllib.parse
+import urllib.request
+
+from .support import Log
# Ports common proxy apps listen on (Clash 7890, Clash Verge 7897, SOCKS 1080).
PORTS = (7890, 7897, 1080)
+# A host the hint asks about: any public one (GNOME's ignore list names local ones).
+PROBE_URL = "https://openrouter.ai/"
-def system_proxy_on(env=None, gsettings=None) -> bool:
- """A proxy in the environment (what urllib uses), else GNOME's 设置 › 网络 › 网络代理 set to
- manual or automatic."""
- env = os.environ if env is None else env
- if any((env.get(k) or "").strip() for k in ("https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY")):
- return True
- mode = (gsettings or _gnome_mode)()
- return mode.strip().strip("'\"") in ("manual", "auto")
+class Route:
+ """`kind`: "direct"; "env" (urllib reads the environment itself, no_proxy included); "http" or
+ "socks" through `host`:`port`, from `origin` ("env" or "gnome"). `url` is the HTTP proxy as
+ urllib takes it (credentials in it stay out of logs: `where` is host:port only)."""
+
+ def __init__(self, kind: str, host: str = "", port: int = 0, origin: str = "", url: str = ""):
+ self.kind, self.host, self.port, self.origin, self.url = kind, host, port, origin, url
+
+ @property
+ def where(self) -> str:
+ return "%s:%d" % (self.host, self.port) if self.host else ""
+
+ def key(self) -> tuple:
+ return (self.kind, self.host, self.port, self.origin, self.url)
+ def __eq__(self, other) -> bool:
+ return isinstance(other, Route) and self.key() == other.key()
-def _gnome_mode() -> str:
+ def __repr__(self) -> str:
+ return "Route(%s)" % " ".join(str(p) for p in self.key()[:4] if p)
+
+
+# GNOME's settings
+
+def _gsettings_dump() -> str:
try:
- r = subprocess.run(["gsettings", "get", "org.gnome.system.proxy", "mode"], capture_output=True, text=True, timeout=2)
+ r = subprocess.run(["gsettings", "list-recursively", "org.gnome.system.proxy"],
+ capture_output=True, text=True, timeout=2)
return r.stdout if r.returncode == 0 else ""
except (OSError, subprocess.SubprocessError):
return "" # no gsettings (not GNOME, or the Mac running the tests)
+def parse_gnome(text: str) -> dict:
+ """`gsettings list-recursively org.gnome.system.proxy` as {"mode": "manual", "https.host": …}."""
+ out: dict = {}
+ for line in text.splitlines():
+ parts = line.split(None, 2)
+ if len(parts) != 3 or not parts[0].startswith("org.gnome.system.proxy"):
+ continue
+ child = parts[0][len("org.gnome.system.proxy"):].lstrip(".")
+ raw = parts[2].strip()
+ if raw.startswith("@"): # a typed empty value: "@as []"
+ raw = raw.split(None, 1)[1] if " " in raw else ""
+ raw = {"true": "True", "false": "False"}.get(raw, raw)
+ try:
+ value = ast.literal_eval(raw)
+ except (ValueError, SyntaxError):
+ value = raw
+ out[(child + "." if child else "") + parts[1]] = value
+ return out
+
+
+_gnome_cache: tuple = (0.0, {})
+_gnome_lock = threading.Lock()
+
+
+def gnome(read=None, ttl: float = 3.0) -> dict:
+ """GNOME's proxy settings, read again after `ttl` seconds: partial translations ask several
+ times a second, and a changed setting applies within moments, no restart."""
+ global _gnome_cache
+ if read is not None:
+ return parse_gnome(read())
+ with _gnome_lock:
+ at, value = _gnome_cache
+ if time.monotonic() - at < ttl and at:
+ return value
+ value = parse_gnome(_gsettings_dump())
+ with _gnome_lock:
+ _gnome_cache = (time.monotonic(), value)
+ return value
+
+
+def ignored(host: str, port: int, patterns) -> bool:
+ """GNOME's ignore-hosts (GSimpleProxyResolver's forms): "example.com", ".example.com" and
+ "*.example.com" all match it and its subdomains; an address or a CIDR range; any with ":port"."""
+ host = host.strip("[]").lower().rstrip(".")
+ try:
+ addr = ipaddress.ip_address(host)
+ except ValueError:
+ addr = None
+ for p in patterns or ():
+ p = str(p).strip().lower()
+ if not p:
+ continue
+ want_port = None
+ if p.startswith("[") and "]" in p: # "[::1]:8080"
+ p, _, rest = p[1:].partition("]")
+ want_port = int(rest[1:]) if rest.startswith(":") and rest[1:].isdigit() else None
+ elif p.count(":") == 1: # "example.com:8080" (an IPv6 address has several colons)
+ p, _, pp = p.partition(":")
+ want_port = int(pp) if pp.isdigit() else None
+ if want_port is not None and want_port != port:
+ continue
+ if addr is not None:
+ try:
+ if addr in ipaddress.ip_network(p, strict=False):
+ return True
+ except ValueError:
+ pass
+ continue
+ name = p.lstrip("*").lstrip(".")
+ if not name:
+ continue
+ if host == name or host.endswith("." + name) or fnmatch.fnmatchcase(host, p):
+ return True
+ return False
+
+
+# Which way a request goes
+
+def _env(env, *names) -> str:
+ for n in names:
+ v = (env.get(n) or env.get(n.upper()) or "").strip()
+ if v:
+ return v
+ return ""
+
+
+def _proxy_url(value: str):
+ """("http"|"socks", host, port, url) for a proxy URL, or None when it isn't one we can use."""
+ if "://" not in value:
+ value = "http://" + value
+ u = urllib.parse.urlsplit(value)
+ try:
+ port = u.port
+ except ValueError:
+ return None
+ if not u.hostname:
+ return None
+ if u.scheme in ("http", "https"):
+ return ("http", u.hostname, port or (443 if u.scheme == "https" else 80), value)
+ if u.scheme in ("socks5", "socks5h", "socks"):
+ return ("socks", u.hostname, port or 1080, value)
+ return None
+
+
+def route(url: str, env=None, settings=None) -> Route:
+ """How a request to `url` leaves the app. `env` and `settings` (parse_gnome's) are for tests."""
+ env = os.environ if env is None else env
+ u = urllib.parse.urlsplit(url)
+ if u.scheme not in ("http", "https") or not u.hostname:
+ return Route("direct") # file:// (tests, a local feed)
+ port = u.port or (443 if u.scheme == "https" else 80)
+ if _env(env, u.scheme + "_proxy"):
+ return Route("env", origin="env")
+ every = _env(env, "all_proxy")
+ if every:
+ # urllib ignores all_proxy; Clash's "copy proxy command" sets it, often as socks5://.
+ p = _proxy_url(every)
+ no = _env(env, "no_proxy")
+ if p and not (no and urllib.request.proxy_bypass_environment(u.hostname, {"no": no})):
+ return Route(p[0], p[1], p[2], "env", p[3])
+ if p:
+ return Route("direct")
+ s = gnome() if settings is None else settings
+ if s.get("mode") != "manual" or ignored(u.hostname, port, s.get("ignore-hosts")):
+ return Route("direct")
+
+ def at(child):
+ host, p = str(s.get(child + ".host") or "").strip(), s.get(child + ".port")
+ return (host, int(p)) if host and isinstance(p, int) and 0 < p < 65536 else None
+ if u.scheme == "https":
+ hp = at("https") or (at("http") if s.get("use-same-proxy", True) else None)
+ else:
+ hp = at("http")
+ if hp:
+ return Route("http", hp[0], hp[1], "gnome", "http://%s:%d" % (hp[0] if ":" not in hp[0] else "[%s]" % hp[0], hp[1]))
+ sp = at("socks")
+ if sp:
+ return Route("socks", sp[0], sp[1], "gnome")
+ return Route("direct")
+
+
+# SOCKS5 (RFC 1928), no authentication: the name is resolved by the proxy, as socks5h does.
+
+def _recv(sock, n: int) -> bytes:
+ data = b""
+ while len(data) < n:
+ chunk = sock.recv(n - len(data))
+ if not chunk:
+ raise OSError("SOCKS proxy closed the connection")
+ data += chunk
+ return data
+
+
+def socks5_connect(proxy_host: str, proxy_port: int, host: str, port: int, timeout=None):
+ sock = socket.create_connection((proxy_host, proxy_port), timeout)
+ try:
+ sock.sendall(b"\x05\x01\x00")
+ if _recv(sock, 2) != b"\x05\x00":
+ raise OSError("SOCKS proxy wants authentication")
+ name = host.encode("idna")
+ sock.sendall(b"\x05\x01\x00\x03" + bytes([len(name)]) + name + struct.pack(">H", port))
+ head = _recv(sock, 4)
+ if head[1] != 0:
+ raise OSError("SOCKS proxy refused the connection (%d)" % head[1])
+ _recv(sock, {1: 4, 4: 16}.get(head[3], 0) or _recv(sock, 1)[0])
+ _recv(sock, 2)
+ return sock
+ except BaseException:
+ sock.close()
+ raise
+
+
+def _through(proxy: Route, cls):
+ def connection(host, **kw):
+ c = cls(host, **kw)
+ c._create_connection = lambda addr, timeout=None, source_address=None: socks5_connect(
+ proxy.host, proxy.port, addr[0], addr[1], timeout)
+ return c
+ return connection
+
+
+class _SocksHTTP(urllib.request.HTTPHandler):
+ def __init__(self, proxy: Route):
+ super().__init__()
+ self.proxy = proxy
+
+ def http_open(self, req):
+ return self.do_open(_through(self.proxy, http.client.HTTPConnection), req)
+
+
+class _SocksHTTPS(urllib.request.HTTPSHandler):
+ def __init__(self, proxy: Route):
+ super().__init__()
+ self.proxy = proxy
+
+ def https_open(self, req):
+ return self.do_open(_through(self.proxy, http.client.HTTPSConnection), req, context=self._context)
+
+
+_openers: dict = {}
+_said: list = [None]
+
+
+def opener(r: Route):
+ k = r.key()
+ o = _openers.get(k)
+ if o is None:
+ if r.kind == "env":
+ o = urllib.request.build_opener()
+ elif r.kind == "http":
+ o = urllib.request.build_opener(urllib.request.ProxyHandler({"http": r.url, "https": r.url}))
+ elif r.kind == "socks":
+ o = urllib.request.build_opener(urllib.request.ProxyHandler({}), _SocksHTTP(r), _SocksHTTPS(r))
+ else:
+ o = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ _openers[k] = o
+ return o
+
+
+def urlopen(req, timeout: float):
+ """urllib.request.urlopen, through this computer's proxy (route)."""
+ url = req.full_url if isinstance(req, urllib.request.Request) else req
+ r = route(url)
+ if r.key() != _said[0] and url.startswith("http"): # a file:// test feed would flip it back and forth
+ _said[0] = r.key()
+ Log.d("net: %s%s" % (r.kind, " %s %s" % (r.origin, r.where) if r.where else ""))
+ return opener(r).open(req, timeout=timeout)
+
+
+# The hint
+
def listening(port: int, timeout: float = 0.3) -> bool:
"""Something accepts a TCP connection on 127.0.0.1:`port` within `timeout`. Nothing is sent."""
+ return reachable("127.0.0.1", port, timeout)
+
+
+def reachable(host: str, port: int, timeout: float = 1.0) -> bool:
try:
- with socket.create_connection(("127.0.0.1", port), timeout=timeout):
+ with socket.create_connection((host, port), timeout=timeout):
return True
except OSError:
return False
-def hint(env=None, gsettings=None, probe=listening) -> tuple:
- """("system",), ("app", port) or ("none",): see AICheck.proxy_line."""
- if system_proxy_on(env, gsettings):
+def hint(env=None, gsettings=None, probe=listening, reach=reachable) -> tuple:
+ """("system",) a proxy is in use and answers; ("dead", "host:port") the proxy in use doesn't
+ answer; ("pac",) GNOME's proxy is automatic, which the app can't use; ("app", port) a proxy app
+ listens but no proxy is set; ("none",). See AICheck.proxy_line."""
+ env = os.environ if env is None else env
+ settings = gnome(gsettings) if gsettings is not None else gnome()
+ r = route(PROBE_URL, env, settings)
+ if r.kind == "env":
+ p = _proxy_url(_env(env, "https_proxy"))
+ r = Route(p[0], p[1], p[2], "env", p[3]) if p else r
+ if r.kind in ("http", "socks"):
+ return ("system",) if reach(r.host, r.port) else ("dead", r.where)
+ if r.kind == "env":
return ("system",)
+ if settings.get("mode") == "auto":
+ return ("pac",)
for port in PORTS:
if probe(port):
return ("app", port)
diff --git a/linux/cicada/core/updates.py b/linux/cicada/core/updates.py
index 746f6f2..baabbd1 100644
--- a/linux/cicada/core/updates.py
+++ b/linux/cicada/core/updates.py
@@ -17,7 +17,7 @@ import tempfile
import time
import urllib.request
-from . import jsonfmt
+from . import jsonfmt, proxy
from .support import Log, Paths
# The list, not releases/latest: every platform shares one version, and a release that only ships
@@ -171,7 +171,7 @@ def should_notify(version: str, told: str | None, busy: bool) -> bool:
def _get(url: str, timeout: float = 20):
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/vnd.github+json"})
- return urllib.request.urlopen(req, timeout=timeout) # noqa: S310 - our feed, or file:// in tests
+ return proxy.urlopen(req, timeout=timeout) # our feed, or file:// in tests
def check(current: str) -> tuple:
diff --git a/linux/strings/en.lproj/Linux.strings b/linux/strings/en.lproj/Linux.strings
index 52d6116..2a88060 100644
--- a/linux/strings/en.lproj/Linux.strings
+++ b/linux/strings/en.lproj/Linux.strings
@@ -190,3 +190,6 @@
"电脑声音" = "This computer";
"也听电脑" = "Hear the computer too";
"电脑里放出来的" = "Played by the computer";
+/* The proxy hint for GNOME's proxy (proxy.py). */
+"代理 %@ 没有回应。打开代理软件,或在 设置 › 网络 › 网络代理 里改正。" = "The proxy %@ doesn’t answer. Open your proxy app, or fix it in Settings › Network › Network Proxy.";
+"系统代理设成了“自动”,知了用不了。在 设置 › 网络 › 网络代理 里改成“手动”。" = "The system proxy is set to Automatic, which Cicada can’t use. Set it to Manual in Settings › Network › Network Proxy.";
diff --git a/linux/strings/ja.lproj/Linux.strings b/linux/strings/ja.lproj/Linux.strings
index bf5fcb7..266768e 100644
--- a/linux/strings/ja.lproj/Linux.strings
+++ b/linux/strings/ja.lproj/Linux.strings
@@ -190,3 +190,6 @@
"电脑声音" = "このパソコン";
"也听电脑" = "パソコンも聞く";
"电脑里放出来的" = "パソコンから流れた";
+/* The proxy hint for GNOME's proxy (proxy.py). */
+"代理 %@ 没有回应。打开代理软件,或在 设置 › 网络 › 网络代理 里改正。" = "プロキシ %@ が応答しません。プロキシアプリを開くか、設定 › ネットワーク › ネットワークプロキシ で直してください。";
+"系统代理设成了“自动”,知了用不了。在 设置 › 网络 › 网络代理 里改成“手动”。" = "システムプロキシが「自動」になっていて、Cicada では使えません。設定 › ネットワーク › ネットワークプロキシ で「手動」にしてください。";
diff --git a/linux/strings/ko.lproj/Linux.strings b/linux/strings/ko.lproj/Linux.strings
index 4fadff0..d2faac2 100644
--- a/linux/strings/ko.lproj/Linux.strings
+++ b/linux/strings/ko.lproj/Linux.strings
@@ -190,3 +190,6 @@
"电脑声音" = "이 컴퓨터";
"也听电脑" = "컴퓨터도 듣기";
"电脑里放出来的" = "컴퓨터에서 재생된 말";
+/* The proxy hint for GNOME's proxy (proxy.py). */
+"代理 %@ 没有回应。打开代理软件,或在 设置 › 网络 › 网络代理 里改正。" = "프록시 %@이(가) 응답하지 않아요. 프록시 앱을 열거나 설정 › 네트워크 › 네트워크 프록시에서 고치세요.";
+"系统代理设成了“自动”,知了用不了。在 设置 › 网络 › 网络代理 里改成“手动”。" = "시스템 프록시가 ‘자동’으로 되어 있어 Cicada에서 쓸 수 없어요. 설정 › 네트워크 › 네트워크 프록시에서 ‘수동’으로 바꾸세요.";
diff --git a/linux/tests/test_aicheck.py b/linux/tests/test_aicheck.py
index 343b8c5..f9b0d90 100644
--- a/linux/tests/test_aicheck.py
+++ b/linux/tests/test_aicheck.py
@@ -154,20 +154,32 @@ class Rules(unittest.TestCase):
class ProxyHint(unittest.TestCase):
- def test_three_cases(self):
+ def test_cases(self):
+ # More in test_proxy.py.
nothing = lambda: "" # noqa: E731
- self.assertEqual(("system",), proxy.hint({"https_proxy": "http://10.0.2.2:7890"}, nothing, lambda p: False))
- self.assertEqual(("system",), proxy.hint({}, lambda: "'manual'\n", lambda p: False))
- self.assertEqual(("system",), proxy.hint({}, lambda: "'auto'", lambda p: False))
- self.assertEqual(("app", 7897), proxy.hint({}, lambda: "'none'", lambda p: p == 7897))
- self.assertEqual(("none",), proxy.hint({"https_proxy": " "}, nothing, lambda p: False))
+ up, down = (lambda h, p: True), (lambda h, p: False) # noqa: E731
+ gnome = ("org.gnome.system.proxy mode '%s'\norg.gnome.system.proxy.https host '10.0.2.2'\n"
+ "org.gnome.system.proxy.https port 7890\n")
+ self.assertEqual(("system",), proxy.hint({"https_proxy": "http://10.0.2.2:7890"}, nothing, lambda p: False, up))
+ # GNOME's manual proxy: requests go through it now, so "a proxy is on" is true when it answers.
+ self.assertEqual(("system",), proxy.hint({}, lambda: gnome % "manual", lambda p: False, up))
+ # One that doesn't answer isn't "a proxy is on, try another server".
+ self.assertEqual(("dead", "10.0.2.2:7890"), proxy.hint({}, lambda: gnome % "manual", lambda p: True, down))
+ # Automatic (PAC) isn't used: requests go direct, so it isn't "a proxy is on" either.
+ self.assertEqual(("pac",), proxy.hint({}, lambda: gnome % "auto", lambda p: False, up))
+ self.assertEqual(("app", 7897), proxy.hint({}, lambda: gnome % "none", lambda p: p == 7897, up))
+ self.assertEqual(("none",), proxy.hint({"https_proxy": " "}, nothing, lambda p: False, up))
+ # all_proxy, which urllib ignored, counts now that requests go through it.
+ self.assertEqual(("dead", "127.0.0.1:1"), proxy.hint({"all_proxy": "socks5://127.0.0.1:1"}, nothing, lambda p: False, down))
def test_words(self):
r = AICheck()
r.fail("reach", "unreachable")
for hint, words in ((("system",), "开了代理也连不上:换一个节点,或检查代理软件是否放过 zenmux.ai。"),
(("app", 7890), "代理软件在运行(端口 7890),但没开系统代理。在代理软件里打开“系统代理”。"),
- (("none",), "这台电脑没开代理。在国内通常要开代理才能用 ZenMux。")):
+ (("none",), "这台电脑没开代理。在国内通常要开代理才能用 ZenMux。"),
+ (("dead", "10.0.2.2:7890"), "代理 10.0.2.2:7890 没有回应。打开代理软件,或在 设置 › 网络 › 网络代理 里改正。"),
+ (("pac",), "系统代理设成了“自动”,知了用不了。在 设置 › 网络 › 网络代理 里改成“手动”。")):
r.proxy = hint
self.assertEqual(words, r.proxy_line("ZenMux", "zenmux.ai"))
r.fail("key", "invalidKey")
diff --git a/linux/tests/test_proxy.py b/linux/tests/test_proxy.py
new file mode 100644
index 0000000..bb09a3e
--- /dev/null
+++ b/linux/tests/test_proxy.py
@@ -0,0 +1,198 @@
+"""Which way requests go (proxy.py): the environment's proxy, else GNOME's manual one (HTTPS, the HTTP
+one, else SOCKS), its ignore-hosts, and real requests through a fake HTTP proxy and a fake SOCKS5 one."""
+from __future__ import annotations
+
+import http.server
+import os
+import socket
+import socketserver
+import struct
+import sys
+import threading
+import unittest
+import urllib.request
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.dirname(HERE))
+
+from cicada.core import proxy # noqa: E402
+
+GNOME = """org.gnome.system.proxy autoconfig-url ''
+org.gnome.system.proxy ignore-hosts ['localhost', '127.0.0.0/8', '::1']
+org.gnome.system.proxy mode 'manual'
+org.gnome.system.proxy use-same-proxy true
+org.gnome.system.proxy.http enabled false
+org.gnome.system.proxy.http host '10.0.2.2'
+org.gnome.system.proxy.http port 7891
+org.gnome.system.proxy.https host '10.0.2.2'
+org.gnome.system.proxy.https port 7890
+org.gnome.system.proxy.socks host ''
+org.gnome.system.proxy.socks port 0
+"""
+
+
+def gnome(**changes) -> dict:
+ s = proxy.parse_gnome(GNOME)
+ s.update(changes)
+ return s
+
+
+class Settings(unittest.TestCase):
+ def test_parse(self):
+ s = proxy.parse_gnome(GNOME + "org.gnome.system.proxy.ftp host @as []\n")
+ self.assertEqual("manual", s["mode"])
+ self.assertEqual(["localhost", "127.0.0.0/8", "::1"], s["ignore-hosts"])
+ self.assertIs(True, s["use-same-proxy"])
+ self.assertEqual(("10.0.2.2", 7890), (s["https.host"], s["https.port"]))
+ self.assertEqual([], s["ftp.host"])
+ self.assertEqual({}, proxy.parse_gnome("")) # no gsettings: the Mac running the tests
+
+ def test_ignore_hosts(self):
+ pats = ["localhost", "127.0.0.0/8", "::1", ".corp.example", "*.lan", "intra.example:8080", "10.1.2.3"]
+ for host, port, want in (("localhost", 443, True), ("127.0.0.1", 11434, True), ("::1", 80, True),
+ ("[::1]", 80, True), ("corp.example", 443, True), ("a.corp.example", 443, True),
+ ("x.lan", 443, True), ("intra.example", 8080, True), ("intra.example", 443, False),
+ ("10.1.2.3", 443, True), ("10.1.2.4", 443, False), ("zenmux.ai", 443, False),
+ ("notlocalhost", 443, False)):
+ self.assertEqual(want, proxy.ignored(host, port, pats), host)
+
+
+class Routes(unittest.TestCase):
+ def test_gnome_manual_https(self):
+ r = proxy.route("https://zenmux.ai/api/v1/models", {}, gnome())
+ self.assertEqual(("http", "10.0.2.2", 7890, "gnome"), r.key()[:4])
+ self.assertEqual("http://10.0.2.2:7890", r.url)
+ self.assertEqual("10.0.2.2:7891", proxy.route("http://example.com/", {}, gnome()).where)
+
+ def test_gnome_falls_back_to_http_then_socks(self):
+ s = gnome(**{"https.host": ""})
+ self.assertEqual("10.0.2.2:7891", proxy.route("https://zenmux.ai/", {}, s).where)
+ s = gnome(**{"https.host": "", "use-same-proxy": False, "socks.host": "127.0.0.1", "socks.port": 1080})
+ self.assertEqual(("socks", "127.0.0.1", 1080, "gnome"), proxy.route("https://zenmux.ai/", {}, s).key()[:4])
+ s = gnome(**{"https.host": "", "http.host": ""})
+ self.assertEqual("direct", proxy.route("https://zenmux.ai/", {}, s).kind)
+
+ def test_gnome_ignores_and_other_modes(self):
+ self.assertEqual("direct", proxy.route("http://127.0.0.1:11434/v1", {}, gnome()).kind) # a local service
+ self.assertEqual("direct", proxy.route("https://localhost/", {}, gnome()).kind)
+ self.assertEqual("direct", proxy.route("https://zenmux.ai/", {}, gnome(mode="auto")).kind)
+ self.assertEqual("direct", proxy.route("https://zenmux.ai/", {}, gnome(mode="none")).kind)
+ self.assertEqual("direct", proxy.route("file:///tmp/feed.json", {}, gnome()).kind)
+ self.assertEqual("direct", proxy.route("https://zenmux.ai/", {}, gnome(**{"https.port": 0, "http.host": ""})).kind)
+
+ def test_environment_first(self):
+ env = {"https_proxy": "http://127.0.0.1:7897"}
+ self.assertEqual("env", proxy.route("https://zenmux.ai/", env, gnome()).kind) # urllib reads it
+ self.assertEqual("10.0.2.2:7891", proxy.route("http://example.com/", env, gnome()).where) # no http_proxy
+ self.assertEqual("env", proxy.route("https://zenmux.ai/", {"HTTPS_PROXY": "http://h:1"}, {}).kind)
+ self.assertEqual("10.0.2.2:7890", proxy.route("https://zenmux.ai/", {"https_proxy": " "}, gnome()).where)
+ r = proxy.route("https://zenmux.ai/", {"all_proxy": "socks5://127.0.0.1:7890"}, gnome())
+ self.assertEqual(("socks", "127.0.0.1", 7890, "env"), r.key()[:4])
+ r = proxy.route("https://zenmux.ai/", {"ALL_PROXY": "http://u:[email protected]:7890"}, {})
+ self.assertEqual(("http", "127.0.0.1:7890"), (r.kind, r.where)) # credentials stay out of `where`
+ self.assertEqual("direct", proxy.route("https://zenmux.ai/", {"all_proxy": "socks5://h:1", "no_proxy": "zenmux.ai"}, gnome()).kind)
+
+
+class Hint(unittest.TestCase):
+ def hint(self, env, text, probe=lambda p: False, reach=lambda h, p: True):
+ return proxy.hint(env, lambda: text, probe, reach)
+
+ def test_cases(self):
+ manual = GNOME
+ none = GNOME.replace("'manual'", "'none'")
+ self.assertEqual(("system",), self.hint({"https_proxy": "http://10.0.2.2:7890"}, ""))
+ self.assertEqual(("dead", "10.0.2.2:7890"), self.hint({"https_proxy": "http://10.0.2.2:7890"}, "", reach=lambda h, p: False))
+ self.assertEqual(("system",), self.hint({}, manual))
+ self.assertEqual(("dead", "10.0.2.2:7890"), self.hint({}, manual, reach=lambda h, p: False))
+ self.assertEqual(("pac",), self.hint({}, GNOME.replace("'manual'", "'auto'")))
+ self.assertEqual(("app", 7897), self.hint({}, none, probe=lambda p: p == 7897))
+ self.assertEqual(("none",), self.hint({"https_proxy": " "}, none))
+ self.assertEqual(("none",), self.hint({}, ""))
+
+
+class _Echo(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ body = ("path=" + self.path).encode()
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *a):
+ pass
+
+
+class _Socks(socketserver.BaseRequestHandler):
+ """A SOCKS5 proxy without authentication that remembers the name it was asked for."""
+ asked: list = []
+
+ def handle(self):
+ c = self.request
+ c.recv(3)
+ c.sendall(b"\x05\x00")
+ head = c.recv(4)
+ name = c.recv(c.recv(1)[0]).decode()
+ port = struct.unpack(">H", c.recv(2))[0]
+ _Socks.asked.append((name, port))
+ up = socket.create_connection(("127.0.0.1", port))
+ c.sendall(b"\x05\x00\x00\x01" + socket.inet_aton("127.0.0.1") + struct.pack(">H", port))
+ assert head[1] == 1
+
+ def pipe(a, b):
+ try:
+ while True:
+ d = a.recv(65536)
+ if not d:
+ break
+ b.sendall(d)
+ except OSError:
+ pass
+ finally:
+ try:
+ b.shutdown(socket.SHUT_WR)
+ except OSError:
+ pass
+ t = threading.Thread(target=pipe, args=(up, c), daemon=True)
+ t.start()
+ pipe(c, up)
+ t.join(5)
+ up.close()
+
+
+class Through(unittest.TestCase):
+ """Real requests: the opener a route picks carries them through the proxy."""
+
+ def serve(self, server):
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ self.addCleanup(server.server_close)
+ self.addCleanup(server.shutdown)
+ return server.server_address[1]
+
+ def test_http_proxy(self):
+ # An HTTP proxy gets the absolute URL; the echo server plays the proxy here.
+ port = self.serve(http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Echo))
+ r = proxy.Route("http", "127.0.0.1", port, "gnome", "http://127.0.0.1:%d" % port)
+ with proxy.opener(r).open(urllib.request.Request("http://cicada.invalid/x"), timeout=5) as resp:
+ self.assertEqual(b"path=http://cicada.invalid/x", resp.read())
+
+ def test_socks5(self):
+ web = self.serve(http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Echo))
+ socks = self.serve(socketserver.ThreadingTCPServer(("127.0.0.1", 0), _Socks))
+ r = proxy.Route("socks", "127.0.0.1", socks, "gnome")
+ _Socks.asked.clear()
+ with proxy.opener(r).open(urllib.request.Request("http://localhost:%d/y" % web), timeout=5) as resp:
+ self.assertEqual(b"path=/y", resp.read())
+ self.assertEqual([("localhost", web)], _Socks.asked) # the name, resolved by the proxy
+
+ def test_dead_socks_is_an_oserror(self):
+ s = socket.socket()
+ s.bind(("127.0.0.1", 0))
+ port = s.getsockname()[1]
+ s.close()
+ r = proxy.Route("socks", "127.0.0.1", port, "gnome")
+ with self.assertRaises(OSError):
+ proxy.opener(r).open(urllib.request.Request("https://zenmux.ai/"), timeout=2)
+
+
+if __name__ == "__main__":
+ unittest.main()