Compare commits

...

20 Commits

Author SHA1 Message Date
Flowseal 3fc8b9ee98 Version bump 2026-11-23 12:17:31 +03:00
Flowseal 4a338a0f5f Fallback CF-worker to HTTP after TimeoutError 2026-11-23 12:14:38 +03:00
Flowseal f42468b77a Move CF-proxy websocket connection to a separate file 2026-11-23 11:56:41 +03:00
Flowseal 45fee6c576 less logs 2026-11-23 11:43:25 +03:00
Flowseal 219f38c07d Fallback CF-proxy to HTTP after TimeoutError 2026-11-23 11:41:24 +03:00
Flowseal c01fad5218 don't split domains by DC in _cf_timeout_until dict 2026-11-23 10:10:02 +03:00
Flowseal 324f69fb9d sync workers pool refill_after with exhausted_until timer 2026-11-23 08:09:05 +03:00
Flowseal efac8b2d20 Pool tests fixes & time measure unification 2026-11-23 08:03:49 +03:00
Flowseal acc451d7ff Restart proxy fixes 2026-11-23 08:01:33 +03:00
enderlit 2ae590ed21 Не запускать второй прокси, пока первый ещё останавливается (#1529) 2026-11-23 07:43:23 +03:00
Flowseal 2c1984f071 #1632 create_ssl_context ca reorder 2026-11-23 07:36:05 +03:00
Flowseal 4ba783c796 time measure unification 2026-11-23 06:32:26 +03:00
Flowseal 13d764f809 Socket occupation fix 2026-11-23 06:29:12 +03:00
mxshooter 0970820f1f CF worker pool: включить cooldown упавших доменов (#1633) 2026-11-23 06:29:22 +03:00
AlexUWP 0c9333bbab Update Dockerfile (#1675) 2026-11-22 16:04:09 +03:00
Flowseal 9f71904e1a Fix verbose logging change needed full restart 2026-11-18 00:23:20 +03:00
Flowseal c053b40014 Extend logging 2026-11-18 00:13:26 +03:00
Flowseal 768d83d10c Fix stale sockets after WinError 2026-11-18 00:13:12 +03:00
XanorCODE 6690b78843 Не зависать при самообновлении в папке без прав записи (#1531) 2026-11-06 13:25:09 +03:00
enderlit dbc8b7811a Fake TLS: маскировать повторённый ClientHello (#1532) 2026-11-06 13:24:50 +03:00
28 changed files with 1485 additions and 165 deletions
+8 -2
View File
@@ -27,7 +27,9 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
TG_WS_PROXY_SECRET="" \
TG_WS_PROXY_DC_IPS="2:149.154.167.220 4:149.154.167.220" \
TG_WS_PROXY_CF_WORKER="" \
TG_WS_PROXY_NO_SECURE=False
TG_WS_PROXY_NO_SECURE=False \
TG_WS_PROXY_PROXY_PROTOCOL=False \
TG_WS_PROXY_FAKE_TLS_DOMAIN=""
RUN apt-get update \
&& apt-get install -y --no-install-recommends tini ca-certificates \
@@ -57,5 +59,9 @@ ENTRYPOINT ["/usr/bin/tini", "--", "/bin/sh", "-lc", "set -eu; args=\"\
then args=\"$args --cfproxy-worker-domain ${TG_WS_PROXY_CF_WORKER}\"; fi; \
if [ \"${TG_WS_PROXY_NO_SECURE}\" = \"True\" ]; \
then args=\"$args --no-secure \"; fi; \
if [ \"${TG_WS_PROXY_PROXY_PROTOCOL}\" = \"True\" ]; \
then args=\"$args --proxy-protocol \"; fi; \
if [ -n \"${TG_WS_PROXY_FAKE_TLS_DOMAIN}\" ]; \
then args=\"$args --fake-tls-domain ${TG_WS_PROXY_FAKE_TLS_DOMAIN} \"; fi; \
exec /opt/venv/bin/python -u proxy/tg_ws_proxy.py $args \"$@\"", "--"]
CMD []
CMD []
+4 -4
View File
@@ -4,8 +4,8 @@
# http://msdn.microsoft.com/en-us/library/ms646997.aspx
VSVersionInfo(
ffi=FixedFileInfo(
filevers=(1, 11, 4, 0),
prodvers=(1, 11, 4, 0),
filevers=(1, 12, 0, 0),
prodvers=(1, 12, 0, 0),
mask=0x3f,
flags=0x0,
OS=0x40004,
@@ -21,12 +21,12 @@ VSVersionInfo(
[
StringStruct(u'CompanyName', u'Flowseal'),
StringStruct(u'FileDescription', u'Telegram Desktop WebSocket Bridge Proxy'),
StringStruct(u'FileVersion', u'1.11.4.0'),
StringStruct(u'FileVersion', u'1.12.0.0'),
StringStruct(u'InternalName', u'TgWsProxy'),
StringStruct(u'LegalCopyright', u'Copyright (c) Flowseal. MIT License.'),
StringStruct(u'OriginalFilename', u'TgWsProxy.exe'),
StringStruct(u'ProductName', u'TG WS Proxy'),
StringStruct(u'ProductVersion', u'1.11.4.0'),
StringStruct(u'ProductVersion', u'1.12.0.0'),
]
)
]
+1 -1
View File
@@ -1,6 +1,6 @@
from .config import parse_dc_ip_list, proxy_config, coerce_domain_list
from .utils import get_link_host, build_github_opener
__version__ = "1.11.4"
__version__ = "1.12.0"
__all__ = ["__version__", "get_link_host", "proxy_config", "parse_dc_ip_list", "build_github_opener", "coerce_domain_list"]
+23 -46
View File
@@ -4,7 +4,6 @@ import struct
import time
from typing import Dict, List, Optional, Set, Tuple
from urllib.parse import urlencode
from .utils import *
from .stats import stats
@@ -14,6 +13,8 @@ from .raw_websocket import RawWebSocket
from .pool import cf_worker_pool
from .network_debug import WsActivity
from .cf_h2 import bridge_h2
from .cf_websocket import cf_prefers_tls, connect_cf_domains
from .event_loop import client_setup
log = logging.getLogger('tg-mtproto-proxy')
@@ -161,8 +162,9 @@ async def do_fallback(reader, writer, relay_init, label,
if ok:
return True
elif method == 'cf':
if is_media and h2_pool is not None and proto_tag is not None:
channel = await h2_pool.open(dc, label)
if is_media and h2_pool is not None and proto_tag is not None and cf_prefers_tls():
with client_setup(reader, writer):
channel = await h2_pool.open(dc, label)
if channel is not None:
stats.connections_h2 += 1
stats.connections_cfproxy += 1
@@ -200,33 +202,15 @@ async def _cfproxy_worker_fallback(reader, writer, relay_init, label,
log.info("[%s] DC%d%s -> CF worker pool hit via %s for %s",
label, dc, media_tag, worker_domain, fallback_dst)
else:
query = urlencode({
'dst': fallback_dst,
'dc': str(dc),
})
path = f'/apiws?{query}'
ws = None
for worker_domain in cf_worker_pool.available_domains(worker_domains):
log.info("[%s] DC%d%s -> trying CF worker %s for %s",
label, dc, media_tag, worker_domain, fallback_dst)
try:
ws = await RawWebSocket.connect(worker_domain, worker_domain,
timeout=10.0, path=path,
secure=not proxy_config.disable_secure)
break
except Exception as exc:
cf_worker_pool.report_failure(worker_domain, exc)
log.warning("[%s] DC%d%s CF worker %s failed: %s",
label, dc, media_tag, worker_domain, repr(exc))
continue
if ws is None:
with client_setup(reader, writer):
connected = await cf_worker_pool.connect_one(worker_domains, fallback_dst, dc, timeout=10.0)
if connected is None:
return False
ws, worker_domain = connected
log.info("[%s] DC%d%s -> CF worker %s for %s", label, dc, media_tag, worker_domain, fallback_dst)
stats.connections_cfproxy += 1
await ws.send(relay_init)
await ws.send_init(relay_init)
await bridge_ws_reencrypt(reader, writer, ws, label, ctx,
dc=dc, is_media=is_media,
splitter=None)
@@ -238,26 +222,18 @@ async def _cfproxy_fallback(reader, writer, relay_init, label,
dc: int, is_media: bool,
splitter=None):
media_tag = ' media' if is_media else ''
ws = None
chosen_domain = None
log.info("[%s] DC%d%s -> trying CF proxy",
label, dc, media_tag)
connect_started = time.monotonic()
secure = not proxy_config.disable_secure
for base_domain in balancer.get_domains_for_dc(dc):
domain = f'kws{dc}.{base_domain}'
try:
ws = await RawWebSocket.connect(domain, domain, timeout=10.0,
secure=not proxy_config.disable_secure)
chosen_domain = base_domain
break
except Exception as exc:
log.warning("[%s] DC%d%s CF proxy failed: %s",
label, dc, media_tag, repr(exc))
if ws is None:
domains = ((base, f'kws{dc}.{base}') for base in balancer.get_domains_for_dc(dc))
with client_setup(reader, writer):
result = await connect_cf_domains(domains, label=label, secure=secure)
if result is None:
return False
ws, chosen_domain = result
log.debug('[%s] WS CONNECT DC%d%s route=cf setup_ms=%.0f',
label, dc, media_tag, (time.monotonic() - connect_started) * 1000)
@@ -265,7 +241,7 @@ async def _cfproxy_fallback(reader, writer, relay_init, label,
log.info("[%s] Switched active CF domain", label)
stats.connections_cfproxy += 1
await ws.send(relay_init)
await ws.send_init(relay_init)
await bridge_ws_reencrypt(reader, writer, ws, label, ctx,
dc=dc, is_media=is_media,
splitter=splitter)
@@ -284,10 +260,11 @@ async def _tcp_fallback(reader, writer, dst, port, relay_init, label, ctx: Crypt
try:
try:
log.info("[%s] TCP fallback to %s:%d", label, dst, port)
rr, rw = await asyncio.wait_for(
asyncio.open_connection(dst, port), timeout=10)
rw.write(relay_init)
await rw.drain()
with client_setup(reader, writer):
rr, rw = await asyncio.wait_for(
asyncio.open_connection(dst, port), timeout=10)
rw.write(relay_init)
await rw.drain()
except Exception as exc:
failures = _tcp_failures.get(key, 0) + 1
_tcp_failures[key] = failures
+3
View File
@@ -12,6 +12,7 @@ from typing import Dict, List, Optional, Set, Tuple
import httpx
from .balancer import balancer
from .cf_websocket import cf_tls_in_cooldown
from .h2_transport import H2Transport
from .stats import stats
from .utils import (
@@ -887,6 +888,8 @@ class CfH2Pool:
log.warning('[%s] H2 unsupported DC%d -> existing WS route', label, dc)
return None
for base_domain in balancer.get_domains_for_dc(dc):
if cf_tls_in_cooldown(base_domain):
continue
host = 'kws%d.%s' % (dc, base_domain)
async with self.locks.setdefault(host, asyncio.Lock()):
if self.closed:
+103
View File
@@ -0,0 +1,103 @@
import asyncio
import logging
import math
import time
from dataclasses import dataclass
from typing import Dict, Iterable, Optional, Tuple
from .raw_websocket import RawWebSocket
log = logging.getLogger('tg-mtproto-proxy')
@dataclass
class CfConStats:
tls: int = 0
no_tls: int = 0
CF_TIMEOUT_COOLDOWN = 30.0
CF_CONNECT_TIMEOUTS = (3.0, 3.0, 5.0, 5.0, 10.0)
_cf_timeout_until: Dict[Tuple[str, bool], float] = {}
_cf_connection_stats = CfConStats()
def reset_cf_timeouts() -> None:
_cf_timeout_until.clear()
_cf_connection_stats.no_tls = 0
_cf_connection_stats.tls = 0
def cf_prefers_tls() -> bool:
return _cf_connection_stats.tls >= _cf_connection_stats.no_tls
def cf_tls_in_cooldown(name: str) -> bool:
retry_at = _cf_timeout_until.get((name, True))
return retry_at is not None and time.monotonic() < retry_at
async def connect_cf_domains(candidates: Iterable[Tuple[str, str]], *, label: str,
secure: bool, path: str = '/apiws', timeout: float = 10.0
) -> Optional[Tuple[RawWebSocket, str]]:
domains = list(candidates)
retry_single_domain = secure and len(domains) == 1
if retry_single_domain:
domains.append(domains[0])
timeouts = 0
tls_first = cf_prefers_tls()
for index, (name, host) in enumerate(domains):
use_tls = secure and (tls_first != bool(timeouts % 2))
if retry_single_domain and index == 1 and timeouts == 0:
# The first try was skipped because of _cf_timeout_until.
use_tls = not tls_first
key = (name, use_tls)
retry_at = _cf_timeout_until.get(key)
if retry_at is not None:
if time.monotonic() < retry_at:
continue
_cf_timeout_until[key] = math.inf
try:
attempt_timeout = min(timeout, CF_CONNECT_TIMEOUTS[timeouts])
ws = await RawWebSocket.connect(host, host, path=path,
secure=use_tls, timeout=attempt_timeout)
except (asyncio.TimeoutError, TimeoutError):
now = time.monotonic()
if retry_at is not None or key not in _cf_timeout_until:
for old_key, until in list(_cf_timeout_until.items()):
if until + CF_TIMEOUT_COOLDOWN <= now:
del _cf_timeout_until[old_key]
_cf_timeout_until[key] = now + CF_TIMEOUT_COOLDOWN
log.warning('[%s] CF WebSocket timed out (host=%s tls=%s); retry in %.0fs',
label, host, use_tls, CF_TIMEOUT_COOLDOWN)
timeouts += 1
if timeouts >= len(CF_CONNECT_TIMEOUTS):
break
continue
except Exception as exc:
log.warning('[%s] CF WebSocket failed (host=%s tls=%s): %r', label, host, use_tls, exc)
ws = None
finally:
if retry_at is not None and _cf_timeout_until.get(key) == math.inf:
_cf_timeout_until[key] = retry_at
_cf_timeout_until.pop(key, None)
if ws is not None:
if use_tls:
_cf_connection_stats.tls += 1
else:
_cf_connection_stats.no_tls += 1
return ws, name
if retry_single_domain:
break
return None
+82
View File
@@ -4,11 +4,93 @@ import signal
import socket
import sys
import threading
from contextlib import contextmanager, suppress
log = logging.getLogger('tg-mtproto-proxy')
class ClientStreamProtocol(asyncio.StreamReaderProtocol):
def __init__(self, client_cb):
super().__init__(asyncio.StreamReader(), client_cb)
self.cancel_setup = None
def eof_received(self):
keep_open = super().eof_received()
if self.cancel_setup is not None:
self.cancel_setup(False)
return keep_open
def connection_lost(self, exc):
super().connection_lost(exc)
if self.cancel_setup is not None:
self.cancel_setup(True)
@contextmanager
def client_setup(reader, writer):
"""Cancel an upstream dial when its client leaves, without reading client bytes."""
if reader.at_eof() or writer.is_closing():
raise asyncio.CancelledError()
protocol = writer.transport.get_protocol()
if not isinstance(protocol, ClientStreamProtocol):
yield
return
task = asyncio.current_task()
def cancel(lost):
if lost or reader.at_eof():
protocol.cancel_setup = None
task.cancel()
protocol.cancel_setup = cancel
try:
yield
finally:
protocol.cancel_setup = None
def _close_proactor_socket(transport, exc):
sock = transport._sock
if sock is None:
return
try:
transport._protocol.connection_lost(exc)
finally:
try:
if sock.fileno() != -1:
with suppress(ConnectionResetError):
sock.shutdown(socket.SHUT_RDWR)
finally:
sock.close()
transport._sock = None
transport._called_connection_lost = True
server, transport._server = transport._server, None
if server is not None:
if sys.version_info >= (3, 13):
server._detach(transport)
else:
server._detach()
def install_proactor_socket_guard(loop):
# https://github.com/Flowseal/tg-ws-proxy/issues/1614
if sys.platform == 'win32' and isinstance(loop, asyncio.ProactorEventLoop):
from asyncio.proactor_events import _ProactorSocketTransport
_ProactorSocketTransport._call_connection_lost = _close_proactor_socket
def abort_transport(transport):
transport.abort()
if sys.platform == 'win32':
from asyncio.proactor_events import _ProactorSocketTransport
if (isinstance(transport, _ProactorSocketTransport)
and getattr(transport, '_write_fut', None) is not None):
transport._closing = False
transport.abort()
def _replace_self_pipe(loop):
reader, writer = socket.socketpair()
try:
+41
View File
@@ -10,6 +10,7 @@ import struct
import time
import logging
from collections import OrderedDict
from typing import Dict, FrozenSet, NamedTuple, Optional, Tuple
from .stats import stats
from .utils import set_x25519
@@ -72,6 +73,43 @@ _SH_RANDOM_OFF = 11
# set once at startup by probe_appdata_len()
_profiled_appdata_len: Optional[int] = None
# A ClientHello passes the timestamp check for TIMESTAMP_TOLERANCE on either
# side of its creation, plus up to a second because the check truncates the
# clock; remembering its random this long refuses any replay
REPLAY_WINDOW = 2 * TIMESTAMP_TOLERANCE + 1
# Only hellos that passed the HMAC check with the secret are stored, so without
# the secret nobody can flood the cache to evict an entry early; reaching the
# limit takes this many genuine handshakes within one window
REPLAY_CACHE_SIZE = 65536
class _ReplayCache:
"""Client randoms of accepted ClientHellos; a repeat is a replay probe.
One cache per process on purpose: it survives proxy restarts, so a hello
accepted just before a restart cannot be replayed right after it.
"""
def __init__(self, window: float = REPLAY_WINDOW, size: int = REPLAY_CACHE_SIZE):
self.window = window
self.size = size
self._expiry: OrderedDict = OrderedDict()
def first_seen(self, client_random: bytes) -> bool:
now = time.monotonic()
# Insertion order is expiry order, so stale entries are at the front
while self._expiry and next(iter(self._expiry.values())) <= now:
self._expiry.popitem(last=False)
if client_random in self._expiry:
return False
if len(self._expiry) >= self.size:
self._expiry.popitem(last=False)
self._expiry[client_random] = now + self.window
return True
replay_cache = _ReplayCache()
class ClientHelloInfo(NamedTuple):
cipher_suites: FrozenSet[int]
@@ -413,6 +451,9 @@ class FakeTlsStream:
def is_closing(self):
return self._writer.is_closing()
def at_eof(self):
return not self._read_buf and self._reader.at_eof()
async def proxy_to_masking_domain(reader, writer, initial_data: bytes,
domain: str, label: str) -> None:
+57 -20
View File
@@ -237,6 +237,7 @@ class _CfWorkerPool:
PER_DC_LIMIT = 1
REFILL_BACKOFF_INITIAL = 1.0
REFILL_BACKOFF_MAX = 3600.0
FAILURE_COOLDOWN = 60.0
def __init__(self):
self._idle: Dict[int, deque] = {}
@@ -245,6 +246,7 @@ class _CfWorkerPool:
self._refill_failures: Dict[int, int] = {}
self._refill_after: Dict[int, float] = {}
self._exhausted_until: Dict[str, float] = {}
self.try_secure_first = True
async def get(self, dc: int, fallback_dst: str,
worker_domains: List[str]
@@ -279,12 +281,22 @@ class _CfWorkerPool:
or ws.writer.transport.is_closing() or ws.reader.at_eof()
or ws.reader.exception() is not None)
def _defer_if_all_workers_paused(self, dc, worker_domains, now):
first_available = min(self._exhausted_until.get(domain, now)
for domain in worker_domains)
if first_available <= now:
return False
self._refill_after[dc] = first_available
return True
def _schedule_refill(self, dc, fallback_dst, worker_domains):
if proxy_config.pool_size <= 0 or not worker_domains:
return
self._schedule_rotation(dc, fallback_dst, worker_domains)
now = time.monotonic()
if (dc in self._refilling
or time.monotonic() < self._refill_after.get(dc, 0)):
or self._defer_if_all_workers_paused(dc, worker_domains, now)
or now < self._refill_after.get(dc, 0)):
return
self._refilling[dc] = asyncio.create_task(self._refill(
dc, fallback_dst, list(worker_domains)))
@@ -298,7 +310,7 @@ class _CfWorkerPool:
return
connected = 0
for _ in range(needed):
result = await self._connect_one(
result = await self.connect_one(
worker_domains, fallback_dst, dc)
if self._refilling.get(dc) is not asyncio.current_task():
if result is not None:
@@ -313,6 +325,9 @@ class _CfWorkerPool:
self._refill_failures.pop(dc, None)
self._refill_after.pop(dc, None)
else:
now = time.monotonic()
if self._defer_if_all_workers_paused(dc, worker_domains, now):
return
failures = self._refill_failures.get(dc, 0) + 1
self._refill_failures[dc] = failures
delay = min(
@@ -320,7 +335,7 @@ class _CfWorkerPool:
* (2 ** min(failures - 1, 12)),
self.REFILL_BACKOFF_MAX,
)
self._refill_after[dc] = time.monotonic() + delay
self._refill_after[dc] = now + delay
log.info("CF worker pool refill failed for DC%d, retry in %.0fs",
dc, delay)
log.debug("CF worker pool refilled DC%d: %d ready",
@@ -370,26 +385,32 @@ class _CfWorkerPool:
if self._rotating.get(dc) is asyncio.current_task():
self._rotating.pop(dc, None)
async def _connect_one(self, worker_domains, fallback_dst, dc):
async def connect_one(self, worker_domains: List[str], fallback_dst: str, dc: int, *,
timeout: float = 8.0) -> Optional[Tuple[RawWebSocket, str]]:
query = urlencode({
'dst': fallback_dst,
'dc': str(dc),
})
path = f'/apiws?{query}'
modes = (False,) if proxy_config.disable_secure else (self.try_secure_first, not self.try_secure_first)
for worker_domain in self.available_domains(worker_domains):
try:
ws = await RawWebSocket.connect(
worker_domain, worker_domain, timeout=8, path=path,
secure=not proxy_config.disable_secure)
for attempt, secure in enumerate(modes, 1):
try:
ws = await RawWebSocket.connect(
worker_domain, worker_domain, timeout=timeout, path=path, secure=secure)
except Exception as exc:
log.debug("CF worker connect DC%d via %s for %s failed (tls=%s): %r",
dc, worker_domain, fallback_dst, secure, exc)
if attempt < len(modes) and isinstance(exc, (asyncio.TimeoutError, TimeoutError)):
continue
self.report_failure(worker_domain, exc)
break
self.try_secure_first = secure
return ws, worker_domain
except Exception as exc:
log.debug("CF worker pool connect DC%d via %s for %s failed: %r",
dc, worker_domain, fallback_dst, exc)
self.report_failure(worker_domain, exc)
return None
def available_domains(self, worker_domains: List[str]) -> List[str]:
now = time.time()
now = time.monotonic()
domains = []
for domain in worker_domains:
if domain in domains:
@@ -404,17 +425,32 @@ class _CfWorkerPool:
return domains
def report_failure(self, worker_domain: str, exc: Exception) -> None:
return # TODO: check status code after daily limit reached
if not isinstance(exc, WsHandshakeError) or exc.status_code != 429:
return
now = time.time()
now = time.monotonic()
if self._exhausted_until.get(worker_domain, 0) > now:
return
exhausted_until = now + (86400 - (now % 86400))
if isinstance(exc, WsHandshakeError):
if exc.status_code == 429:
# Workers free plan reports the daily request limit as 429.
exhausted_until = now + (86400 - (time.time() % 86400))
reason = 'daily request limit'
elif exc.status_code >= 500:
exhausted_until = now + self.FAILURE_COOLDOWN
reason = 'HTTP %d' % exc.status_code
else:
# A challenge or a misconfigured route is not a reason to
# disable the whole domain.
return
elif isinstance(exc, (OSError, asyncio.TimeoutError)):
exhausted_until = now + self.FAILURE_COOLDOWN
reason = repr(exc)
else:
return
self._exhausted_until[worker_domain] = exhausted_until
log.warning(
"CF worker %s reached its request limit, disabled for %d seconds", worker_domain, int(exhausted_until - now))
"CF worker %s disabled for %d seconds: %s",
worker_domain, max(1, int(exhausted_until - now)), reason)
async def _quiet_close(self, ws):
try:
@@ -455,6 +491,7 @@ class _CfWorkerPool:
self._refill_failures.clear()
self._refill_after.clear()
self._exhausted_until.clear()
self.try_secure_first = True
async def close(self):
tasks = list(self._rotating.values()) + list(self._refilling.values())
+61 -19
View File
@@ -7,6 +7,7 @@ import socket as _socket
from typing import List, Optional, Tuple
from .config import proxy_config
from .event_loop import abort_transport
from .utils import create_ssl_context
log = logging.getLogger('tg-mtproto-proxy')
@@ -54,6 +55,22 @@ def _xor_mask(data: bytes, mask: bytes) -> bytes:
int.from_bytes(mask_rep, 'big')).to_bytes(n, 'big')
async def _wait_close(awaitable, timeout, *, cancel_pending=True):
# wait_for() can lose external cancellation when its task finishes at the
# same time on Python < 3.12. wait() leaves cancellation with the caller.
task = asyncio.ensure_future(awaitable)
completion = asyncio.gather(task, return_exceptions=True)
try:
done, _ = await asyncio.wait((completion,), timeout=timeout)
if not done:
raise asyncio.TimeoutError()
return task.result()
finally:
if cancel_pending and not task.done():
task.cancel()
await completion
def set_sock_opts(transport, buffer_size):
sock = transport.get_extra_info('socket')
if sock is None:
@@ -81,6 +98,7 @@ class RawWebSocket:
OP_PONG = 0xA
MAX_MESSAGE_LEN = 16 * 1024 * 1024
CLOSE_TIMEOUT = 2.0
def __init__(self, reader: asyncio.StreamReader,
writer: asyncio.StreamWriter):
@@ -98,20 +116,16 @@ class RawWebSocket:
if sni is None:
sni = domain
reader, writer = await asyncio.wait_for(
(
asyncio.open_connection(
host, 443,
ssl=ssl_context,
server_hostname=sni,
)
if secure
else asyncio.open_connection(host, 80)
),
timeout=min(timeout, 10),
)
port = 443 if secure else 80
tls_options = {'ssl': ssl_context, 'server_hostname': sni} if secure else {}
loop = asyncio.get_running_loop()
deadline = loop.time() + timeout
writer = None
try:
reader, writer = await asyncio.wait_for(
asyncio.open_connection(host, port, **tls_options),
timeout=min(timeout, 10),
)
set_sock_opts(writer.transport, proxy_config.buffer_size)
ws_key = base64.b64encode(os.urandom(16)).decode()
@@ -128,12 +142,11 @@ class RawWebSocket:
)
writer.write(req.encode())
await writer.drain()
await asyncio.wait_for(writer.drain(), deadline - loop.time())
response_lines: list[str] = []
while True:
line = await asyncio.wait_for(reader.readline(),
timeout=timeout)
line = await asyncio.wait_for(reader.readline(), deadline - loop.time())
if line in (b'\r\n', b'\n', b''):
break
response_lines.append(
@@ -160,8 +173,29 @@ class RawWebSocket:
raise WsHandshakeError(status_code, first_line, headers,
location=headers.get('location'))
except BaseException as exc:
if writer is not None:
writer.transport.abort()
if isinstance(exc, Exception) and log.isEnabledFor(logging.DEBUG):
if writer is not None:
stage = 'ws_upgrade'
local = writer.get_extra_info('sockname')
remote = writer.get_extra_info('peername')
else:
stage = 'tcp/tls' if secure else 'tcp'
if isinstance(exc, _socket.gaierror):
stage = 'dns'
local = remote = None
log.debug('WS setup failed: host=%s port=%d stage=%s local=%s remote=%s error=%r',
host, port, stage, local, remote, exc)
raise
async def send_init(self, data: bytes):
try:
await asyncio.wait_for(self.send(data), timeout=10)
except BaseException:
writer.close()
self._closed = True
self.writer.transport.abort()
raise
async def send(self, data: bytes):
@@ -231,13 +265,21 @@ class RawWebSocket:
try:
self.writer.write(
self._build_frame(self.OP_CLOSE, b'', mask=True))
await self.writer.drain()
await _wait_close(self.writer.drain(), self.CLOSE_TIMEOUT)
except Exception:
pass
finally:
try:
self.writer.close()
await self.writer.wait_closed()
await _wait_close(self.writer.wait_closed(), self.CLOSE_TIMEOUT,
cancel_pending=False)
except (asyncio.TimeoutError, asyncio.CancelledError) as exc:
try:
abort_transport(self.writer.transport)
except Exception:
pass
if isinstance(exc, asyncio.CancelledError):
raise
except Exception:
pass
+40 -17
View File
@@ -11,7 +11,7 @@ import argparse
import logging
import socket as _socket
from typing import Optional, Set, Tuple
from typing import Dict, Optional, Tuple
if __name__ == '__main__' and (__package__ is None or __package__ == ''):
@@ -24,17 +24,20 @@ from .utils import *
from .stats import stats
from .config import proxy_config, parse_dc_ip_list, start_cfproxy_domain_refresh, coerce_domain_list
from .bridge import MsgSplitter, CryptoCtx, do_fallback, bridge_ws_reencrypt, reset_tcp_backoff
from .cf_websocket import reset_cf_timeouts
from .raw_websocket import set_sock_opts
from .fake_tls import (
proxy_to_masking_domain, verify_client_hello, parse_client_hello, build_server_hello,
probe_appdata_len, set_profiled_appdata_len, FakeTlsStream, TLS_RECORD_HANDSHAKE,
SERVER_HELLO_DELAY,
SERVER_HELLO_DELAY, replay_cache,
)
from .balancer import balancer
from .pool import ws_pool, cf_worker_pool
from .cf_h2 import CfH2Pool
from .network_debug import log_ws_flow
from .event_loop import install_self_pipe_guard
from .event_loop import (
ClientStreamProtocol, abort_transport, install_proactor_socket_guard, install_self_pipe_guard,
)
from ._aes import Cipher, algorithms, modes
@@ -42,6 +45,7 @@ log = logging.getLogger('tg-mtproto-proxy')
LISTENER_CHECK_INTERVAL = 5.0
LISTENER_RESTART_DELAY = 1.0
CLIENT_CLOSE_TIMEOUT = 2.0
BAD_HANDSHAKE_DRAIN_TIMEOUT = 10.0
BAD_HANDSHAKE_DRAIN_LIMIT = 64 * 1024
cf_h2_pool: Optional[CfH2Pool] = None
@@ -157,11 +161,16 @@ async def _read_client_init(reader, writer, secret, label, masking):
client_hello = tls_header + record_body
tls_result = verify_client_hello(client_hello, secret)
# A recorded hello stays valid for minutes; answering it again would
# tell an active prober that this is a proxy, not the masking site
replayed = (tls_result is not None
and not replay_cache.first_seen(tls_result[0]))
if tls_result is None:
log.debug("[%s] Fake TLS verify failed (size=%d rec=%d) "
if tls_result is None or replayed:
log.debug("[%s] Fake TLS %s (size=%d rec=%d) "
"-> masking",
label, len(client_hello), record_len)
label, "hello replayed" if replayed else "verify failed",
len(client_hello), record_len)
await proxy_to_masking_domain(
reader, writer, client_hello, masking, label)
return None
@@ -343,7 +352,7 @@ async def _handle_client(reader, writer, secret: bytes):
except Exception:
pass
await ws.send(relay_init)
await ws.send_init(relay_init)
await bridge_ws_reencrypt(clt_reader, clt_writer, ws, label, ctx,
dc=dc, is_media=is_media,
@@ -375,15 +384,20 @@ async def _handle_client(reader, writer, secret: bytes):
_server_instance = None
_server_stop_event = None
_client_tasks: Set[asyncio.Task] = set()
_client_tasks: Dict[asyncio.Task, asyncio.StreamWriter] = {}
async def _run(stop_event: Optional[asyncio.Event] = None):
global _server_instance, _server_stop_event, cf_h2_pool
install_self_pipe_guard(asyncio.get_running_loop())
if stop_event is not None and stop_event.is_set():
return
loop = asyncio.get_running_loop()
install_proactor_socket_guard(loop)
install_self_pipe_guard(loop)
_server_stop_event = stop_event
reset_tcp_backoff()
reset_cf_timeouts()
ws_pool.reset()
cf_worker_pool.reset()
_client_tasks.clear()
@@ -416,10 +430,13 @@ async def _run(stop_event: Optional[asyncio.Event] = None):
w.close()
return
task = asyncio.create_task(_handle_client(r, w, secret_bytes))
_client_tasks.add(task)
task.add_done_callback(_client_tasks.discard)
_client_tasks[task] = w
task.add_done_callback(lambda done: _client_tasks.pop(done, None))
server = await asyncio.start_server(client_cb, proxy_config.host, proxy_config.port)
def client_protocol():
return ClientStreamProtocol(client_cb)
server = await loop.create_server(client_protocol, proxy_config.host, proxy_config.port)
_server_instance = server
for sock in server.sockets:
@@ -542,8 +559,8 @@ async def _run(stop_event: Optional[asyncio.Event] = None):
pass
await asyncio.sleep(LISTENER_RESTART_DELAY)
try:
server = await asyncio.start_server(
client_cb, proxy_config.host, proxy_config.port)
server = await loop.create_server(
client_protocol, proxy_config.host, proxy_config.port)
except OSError as exc:
log.error("Failed to restart server: %s", repr(exc))
break
@@ -559,10 +576,16 @@ async def _run(stop_event: Optional[asyncio.Event] = None):
finally:
stopping = True
server.close()
clients = list(_client_tasks)
for task in clients:
clients = _client_tasks.copy()
for task, writer in clients.items():
task.cancel()
await asyncio.gather(*clients, return_exceptions=True)
writer.close()
if clients:
await asyncio.wait(clients, timeout=CLIENT_CLOSE_TIMEOUT)
for writer in clients.values():
if writer.transport.get_write_buffer_size():
abort_transport(writer.transport)
await asyncio.gather(*clients, return_exceptions=True)
for task in (serve_task, watchdog_task, stop_task):
if task is not None:
await _quiet_cancel(task)
+9 -4
View File
@@ -151,11 +151,16 @@ def set_x25519(context: ssl.SSLContext) -> None:
def create_ssl_context(*, check_hostname: bool = True) -> ssl.SSLContext:
context = ssl.create_default_context()
bundle_dir = getattr(sys, '_MEIPASS', None)
cafile = (os.path.join(bundle_dir, 'certifi', 'cacert.pem')
if bundle_dir else certifi.where())
context = ssl.create_default_context(cafile=cafile)
context.load_default_certs()
try:
cafile = (os.path.join(bundle_dir, 'certifi', 'cacert.pem')
if bundle_dir else certifi.where())
context.load_verify_locations(cafile=cafile)
except Exception:
pass
set_x25519(context)
context.check_hostname = check_hostname
return context
+26 -1
View File
@@ -3,12 +3,15 @@ import asyncio
import time
import unittest
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
from unittest.mock import AsyncMock, Mock, patch
from proxy import bridge
from proxy._aes import Cipher, algorithms, modes
from proxy.bridge import MsgSplitter, bridge_ws_reencrypt
from proxy.config import proxy_config
from proxy.network_debug import WsActivity, log_ws_flow
from proxy.utils import (
DC_DEFAULT_IPS,
PROTO_ABRIDGED_INT,
PROTO_INTERMEDIATE_INT,
PROTO_PADDED_INTERMEDIATE_INT,
@@ -38,6 +41,28 @@ def _intermediate(payload: bytes) -> bytes:
return len(payload).to_bytes(4, 'little') + payload
class CfWorkerFallbackTest(unittest.IsolatedAsyncioTestCase):
async def test_pool_miss_connects_through_the_worker_pool(self):
reader = asyncio.StreamReader()
writer = Mock()
writer.is_closing.return_value = False
ws = Mock(send_init=AsyncMock())
domains = ['worker.example']
pool = SimpleNamespace(get=AsyncMock(return_value=None),
connect_one=AsyncMock(return_value=(ws, domains[0])))
ctx = Mock()
with patch.object(proxy_config, 'cfproxy_worker_domains', domains), \
patch.object(bridge, 'cf_worker_pool', pool), \
patch.object(bridge, 'bridge_ws_reencrypt', new_callable=AsyncMock) as relay:
self.assertTrue(await bridge.do_fallback(
reader, writer, b'init', 'test', 2, False, True, ' media', ctx))
pool.get.assert_awaited_once_with(2, DC_DEFAULT_IPS[2], domains)
pool.connect_one.assert_awaited_once_with(domains, DC_DEFAULT_IPS[2], 2, timeout=10.0)
ws.send_init.assert_awaited_once_with(b'init')
relay.assert_awaited_once_with(reader, writer, ws, 'test', ctx, dc=2, is_media=True, splitter=None)
class MsgSplitterTest(unittest.TestCase):
def _split(self, proto_int, packets, chunk_sizes=None):
relay_init = _relay_init()
+21
View File
@@ -13,6 +13,8 @@ from proxy.cf_h2 import (
CfH2Pool, MAX_CHANNEL_REQUESTS, MAX_PACKET, _HttpChannel, _HttpLane,
_ReplayPacket, _encode_reply, _read_packet, bridge_h2,
)
from proxy.cf_websocket import connect_cf_domains, reset_cf_timeouts
from proxy.raw_websocket import RawWebSocket
from proxy.utils import PROTO_TAG_ABRIDGED, PROTO_TAG_INTERMEDIATE, PROTO_TAG_SECURE
class _IdentityCipher:
@@ -962,6 +964,25 @@ class HttpMultiplexTest(unittest.IsolatedAsyncioTestCase):
finally:
await pool.close()
async def test_h2_skips_domain_with_recent_secure_websocket_timeout(self):
reset_cf_timeouts()
self.addCleanup(reset_cf_timeouts)
pool = CfH2Pool()
self.addAsyncCleanup(pool.close)
balancer = _Balancer()
balancer.update_domains_list(['slow.example', 'ready.example'])
balancer.update_domain_for_dc(4, 'slow.example')
with patch.object(RawWebSocket, 'connect', side_effect=[TimeoutError(), ConnectionResetError()]):
self.assertIsNone(await connect_cf_domains(
[('slow.example', 'kws4.slow.example')], label='test', secure=True))
with patch('proxy.cf_h2.balancer', balancer), patch.object(_HttpLane, '_preflight', autospec=True) as preflight:
channel = await pool.open(4, 'test')
self.assertIsNotNone(channel)
self.assertEqual(channel.lane.host, 'kws4.ready.example')
preflight.assert_awaited_once_with(channel.lane)
async def test_hanging_setup_returns_to_ws_and_cleans_up_lane(self):
pool = CfH2Pool()
balancer = _Balancer()
+67
View File
@@ -26,6 +26,35 @@ def _wake_later(loop, callback):
return thread
class ClientSetupTest(unittest.IsolatedAsyncioTestCase):
async def test_fin_cancels_pending_setup_and_closes_accepted_socket(self):
started, cancelled = asyncio.Event(), asyncio.Event()
async def handle(reader, writer):
try:
with event_loop.client_setup(reader, writer):
started.set()
await asyncio.Future()
except asyncio.CancelledError:
cancelled.set()
finally:
writer.close()
await writer.wait_closed()
loop = asyncio.get_running_loop()
server = await loop.create_server(lambda: event_loop.ClientStreamProtocol(handle), '127.0.0.1', 0)
async with server:
peer, writer = await asyncio.open_connection('127.0.0.1', server.sockets[0].getsockname()[1])
try:
await asyncio.wait_for(started.wait(), 1)
writer.write_eof()
await asyncio.wait_for(cancelled.wait(), 1)
self.assertEqual(await asyncio.wait_for(peer.read(1), 1), b'')
finally:
writer.close()
await writer.wait_closed()
@unittest.skipUnless(sys.platform == 'win32', 'Windows proactor self-pipe')
class WindowsSelfPipeTest(unittest.TestCase):
def setUp(self):
@@ -274,5 +303,43 @@ class ProxySelfPipeTest(unittest.IsolatedAsyncioTestCase):
await asyncio.gather(task, return_exceptions=True)
@unittest.skipUnless(sys.platform == 'win32', 'Windows proactor TCP transports')
class WindowsSocketCloseTest(unittest.IsolatedAsyncioTestCase):
async def test_shutdown_reset_still_closes_client_and_accepted_socket(self):
from asyncio.proactor_events import _ProactorSocketTransport
self.addCleanup(setattr, _ProactorSocketTransport, '_call_connection_lost',
_ProactorSocketTransport._call_connection_lost)
loop = asyncio.get_running_loop()
event_loop.install_proactor_socket_guard(loop)
accepted = loop.create_future()
server = await asyncio.start_server(
lambda _, writer: accepted.set_result(writer), '127.0.0.1', 0)
self.addCleanup(server.close)
port = server.sockets[0].getsockname()[1]
_, client = await asyncio.open_connection('127.0.0.1', port)
peer = await asyncio.wait_for(accepted, 1)
sockets = (client.transport._sock, peer.transport._sock)
shutdown = socket.socket.shutdown
def reset_on_shutdown(sock, how):
if sock in sockets:
raise ConnectionResetError(0, 'connection reset', None, 10054)
shutdown(sock, how)
for sock in sockets:
self.addCleanup(sock.close)
with patch.object(socket.socket, 'shutdown', reset_on_shutdown), \
patch.object(loop, 'call_exception_handler') as report:
client.close()
peer.close()
await asyncio.wait_for(asyncio.gather(client.wait_closed(), peer.wait_closed()), 1)
self.assertEqual([sock.fileno() for sock in sockets], [-1, -1])
report.assert_not_called()
server.close()
await asyncio.wait_for(server.wait_closed(), 1)
if __name__ == '__main__':
unittest.main()
+108
View File
@@ -422,5 +422,113 @@ class WrapTlsRecordTest(unittest.TestCase):
self.assertEqual(wrap_tls_record(b''), b'')
class ReplayCacheTest(unittest.TestCase):
def test_second_sighting_within_window_is_a_replay(self):
cache = fake_tls._ReplayCache(window=10, size=8)
self.assertTrue(cache.first_seen(b'a'))
self.assertFalse(cache.first_seen(b'a'))
self.assertTrue(cache.first_seen(b'b'))
def test_entries_expire_after_the_window(self):
cache = fake_tls._ReplayCache(window=10, size=8)
with patch('proxy.fake_tls.time.monotonic', return_value=100.0):
cache.first_seen(b'a')
with patch('proxy.fake_tls.time.monotonic', return_value=110.0):
self.assertTrue(cache.first_seen(b'a'))
def test_size_is_bounded_by_dropping_oldest(self):
cache = fake_tls._ReplayCache(window=10, size=2)
for key in (b'a', b'b', b'c'):
cache.first_seen(key)
self.assertEqual(len(cache._expiry), 2)
self.assertTrue(cache.first_seen(b'a'))
def test_window_covers_the_whole_timestamp_tolerance(self):
self.assertGreaterEqual(fake_tls.REPLAY_WINDOW, 2 * fake_tls.TIMESTAMP_TOLERANCE)
def test_repeat_in_a_full_cache_is_still_a_replay(self):
cache = fake_tls._ReplayCache(window=10, size=2)
cache.first_seen(b'a')
cache.first_seen(b'b')
self.assertFalse(cache.first_seen(b'a'), 'a live entry must not be evicted before the lookup')
self.assertFalse(cache.first_seen(b'b'))
def test_full_cache_evicts_the_oldest_entry_for_a_new_key(self):
cache = fake_tls._ReplayCache(window=10, size=2)
for key in (b'a', b'b', b'c'):
self.assertTrue(cache.first_seen(key))
self.assertEqual(list(cache._expiry), [b'b', b'c'])
self.assertFalse(cache.first_seen(b'b'))
self.assertFalse(cache.first_seen(b'c'))
def test_entry_is_still_a_replay_just_before_expiry(self):
cache = fake_tls._ReplayCache(window=10, size=8)
with patch('proxy.fake_tls.time.monotonic', return_value=100.0):
cache.first_seen(b'a')
with patch('proxy.fake_tls.time.monotonic', return_value=109.999):
self.assertFalse(cache.first_seen(b'a'))
def test_replay_is_refused_for_as_long_as_the_hello_verifies(self):
# The earliest and latest moments one hello passes the timestamp check, with
# verify_client_hello() truncating wall time to whole seconds.
ts = 1_800_000_000
hello = _client_hello(timestamp=ts)
cache = fake_tls._ReplayCache()
clock = {'now': 0.0}
fake_time = Mock(time=lambda: clock['now'], monotonic=lambda: clock['now'])
with patch.object(fake_tls, 'time', fake_time):
clock['now'] = ts - fake_tls.TIMESTAMP_TOLERANCE
first = verify_client_hello(hello, SECRET)
self.assertIsNotNone(first)
self.assertTrue(cache.first_seen(first[0]))
clock['now'] = ts + fake_tls.TIMESTAMP_TOLERANCE + 0.999
replayed = verify_client_hello(hello, SECRET)
self.assertIsNotNone(replayed, 'the hello still passes the timestamp check')
self.assertFalse(cache.first_seen(replayed[0]), 'so the cache must still refuse it')
def test_key_is_new_again_after_the_window(self):
cache = fake_tls._ReplayCache(window=10, size=8)
with patch('proxy.fake_tls.time.monotonic', return_value=100.0):
cache.first_seen(b'a')
with patch('proxy.fake_tls.time.monotonic', return_value=111.0):
self.assertTrue(cache.first_seen(b'a'))
self.assertFalse(cache.first_seen(b'a'))
class ReplayedHelloTest(unittest.IsolatedAsyncioTestCase):
def setUp(self):
# The proxy keeps one process-wide cache; start and end every test with it empty.
fake_tls.replay_cache._expiry.clear()
self.addCleanup(fake_tls.replay_cache._expiry.clear)
async def _handshake(self, hello):
from proxy import tg_ws_proxy
reader = asyncio.StreamReader()
reader.feed_data(hello + wrap_tls_record(os.urandom(64)))
reader.feed_eof()
writer = Mock(drain=AsyncMock())
with patch.object(tg_ws_proxy, 'proxy_to_masking_domain', AsyncMock()) as masking, \
patch.object(tg_ws_proxy.asyncio, 'sleep', AsyncMock()):
result = await tg_ws_proxy._read_client_init(
reader, writer, SECRET, 'test', 'example.com')
return result, writer, masking
async def test_replayed_hello_is_masked_instead_of_answered(self):
hello = _structured_client_hello()
first, first_writer, first_masking = await self._handshake(hello)
second, second_writer, second_masking = await self._handshake(hello)
self.assertIsNotNone(first)
first_masking.assert_not_awaited()
self.assertEqual(first_writer.write.call_args_list[0].args[0][0], TLS_RECORD_HANDSHAKE)
self.assertIsNone(second)
second_masking.assert_awaited_once()
second_writer.write.assert_not_called()
if __name__ == '__main__':
unittest.main()
+33 -2
View File
@@ -1,10 +1,14 @@
"""H2 belongs to CF fallback, never to the direct route."""
import asyncio
import unittest
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock, patch
from proxy import bridge, tg_ws_proxy
from proxy.balancer import _Balancer
from proxy.cf_websocket import reset_cf_timeouts
from proxy.config import proxy_config
from proxy.raw_websocket import RawWebSocket
from proxy.utils import PROTO_TAG_INTERMEDIATE
@@ -14,7 +18,7 @@ class H2RoutingTest(unittest.IsolatedAsyncioTestCase):
writer = Mock()
writer.get_extra_info.return_value = None
writer.wait_closed = AsyncMock()
ws = Mock(send=AsyncMock())
ws = Mock(send_init=AsyncMock())
pool = SimpleNamespace(open=AsyncMock())
with patch.object(proxy_config, 'dc_redirects', {2: '149.154.167.51'}), \
patch.object(proxy_config, 'force_test_dc', False), \
@@ -30,6 +34,7 @@ class H2RoutingTest(unittest.IsolatedAsyncioTestCase):
patch.object(tg_ws_proxy, 'do_fallback', AsyncMock()) as fallback:
await tg_ws_proxy._handle_client(reader, writer, b'')
direct.assert_awaited_once()
ws.send_init.assert_awaited_once()
fallback.assert_not_awaited()
pool.open.assert_not_awaited()
@@ -89,8 +94,34 @@ class H2RoutingTest(unittest.IsolatedAsyncioTestCase):
patch.object(bridge, '_cfproxy_fallback', side_effect=route('ws')), \
patch.object(bridge, '_cfproxy_worker_fallback', side_effect=route('worker')), \
patch.object(bridge, '_tcp_fallback', side_effect=route('tcp')):
writer = Mock()
writer.is_closing.return_value = False
result = await bridge.do_fallback(
Mock(), Mock(), b'', 'test', 2, test_dc, media, '', Mock(),
asyncio.StreamReader(), writer, b'', 'test', 2, test_dc, media, '', Mock(),
h2_pool=pool, proto_tag=PROTO_TAG_INTERMEDIATE)
self.assertTrue(result)
self.assertEqual(calls, expected)
async def test_media_skips_h2_when_cf_websocket_prefers_plaintext(self):
reset_cf_timeouts()
self.addCleanup(reset_cf_timeouts)
balancer = _Balancer()
balancer.update_domains_list(['example.org'])
pool = SimpleNamespace(open=AsyncMock(return_value=None))
writer = Mock()
writer.is_closing.return_value = False
ws = Mock(send_init=AsyncMock())
with patch.object(proxy_config, 'fallback_cfproxy', True), \
patch.object(proxy_config, 'cfproxy_worker_domains', []), \
patch.object(proxy_config, 'disable_secure', False), \
patch.object(bridge, 'balancer', balancer), \
patch.object(bridge, 'bridge_ws_reencrypt', new_callable=AsyncMock), \
patch.object(RawWebSocket, 'connect', side_effect=[TimeoutError(), ws, ws]) as dial:
for media in (False, True):
self.assertTrue(await bridge.do_fallback(
asyncio.StreamReader(), writer, b'', 'test', 2, False, media, '', Mock(),
h2_pool=pool, proto_tag=PROTO_TAG_INTERMEDIATE))
pool.open.assert_not_awaited()
self.assertEqual([call.kwargs['secure'] for call in dial.await_args_list], [True, False, False])
+136 -8
View File
@@ -247,6 +247,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
self.pool.WS_POOL_CHECK_INTERVAL = .01
for name, value in [
('pool_size', 4),
('disable_secure', False),
('dc_redirects', {dc: ip for dc, ip in DC_DEFAULT_IPS.items() if dc != 2}),
('cfproxy_worker_domains', ['worker.example'])]:
patcher = mock.patch.object(proxy_config, name, value)
@@ -260,10 +261,31 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
await asyncio.sleep(.001)
await asyncio.wait_for(wait(), 1)
async def test_connect_one_retries_timeouts_and_starts_with_last_successful_mode(self):
ws = _open_ws()
domains = ['worker.example']
with mock.patch.object(RawWebSocket, 'connect',
side_effect=[TimeoutError(), ws, ws, TimeoutError(), ws]) as dial:
for _ in range(3):
self.assertEqual(await self.pool.connect_one(domains, '192.0.2.2', 2),
(ws, 'worker.example'))
self.assertEqual([call.kwargs['secure'] for call in dial.await_args_list],
[True, False, False, False, True])
self.assertTrue(all(call.args == ('worker.example', 'worker.example')
for call in dial.await_args_list))
self.assertFalse(self.pool._exhausted_until)
async def test_connect_one_never_tries_tls_when_disabled(self):
with mock.patch.object(proxy_config, 'disable_secure', True), \
mock.patch.object(RawWebSocket, 'connect', side_effect=TimeoutError()) as dial:
self.assertIsNone(await self.pool.connect_one(['worker.example'], '192.0.2.2', 2))
dial.assert_awaited_once_with('worker.example', 'worker.example', timeout=8.0,
path='/apiws?dst=192.0.2.2&dc=2', secure=False)
async def test_failed_warmup_recovers_without_new_client_requests(self):
ready = _open_ws()
self.pool.REFILL_BACKOFF_INITIAL = .03
with mock.patch.object(self.pool, '_connect_one',
with mock.patch.object(self.pool, 'connect_one',
side_effect=[None, (ready, 'worker.example')]) as dial:
await self.pool.warmup()
await self.wait_for(lambda: 2 in self.pool._refill_after)
@@ -290,11 +312,13 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
else:
stale.writer.transport.is_closing = lambda: True
self.pool._idle[2] = deque([(stale, created, 'worker.example')])
with mock.patch.object(self.pool, '_connect_one',
with mock.patch.object(self.pool, 'connect_one',
return_value=(ready, 'worker.example')):
self.assertIsNone(await self.pool.get(2, '192.0.2.2', ['worker.example']))
await self.wait_for(lambda: bool(self.pool._idle[2]))
self.assertIs(self.pool._idle[2][0][0], ready)
# Refill and stale connection cleanup run independently.
await self.wait_for(lambda: stale.writer.close.called)
stale.writer.close.assert_called_once()
await self.pool.close()
@@ -302,7 +326,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
stale, ready = _open_ws(), _open_ws()
self.pool.WS_POOL_MAX_AGE = .05
self.pool._idle[2] = deque([(stale, time.monotonic(), 'worker.example')])
with mock.patch.object(self.pool, '_connect_one',
with mock.patch.object(self.pool, 'connect_one',
return_value=(ready, 'worker.example')) as dial:
await self.pool.warmup()
await self.wait_for(lambda: stale.writer.close.called)
@@ -317,7 +341,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
started.set()
await asyncio.Future()
with mock.patch.object(self.pool, '_connect_one', side_effect=connect) as dial:
with mock.patch.object(self.pool, 'connect_one', side_effect=connect) as dial:
for _ in range(10):
self.assertIsNone(await self.pool.get(2, '192.0.2.2', ['worker.example']))
await asyncio.wait_for(started.wait(), 1)
@@ -327,7 +351,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
ready = _open_ws()
self.pool.REFILL_BACKOFF_INITIAL = 1
self.pool.REFILL_BACKOFF_MAX = 2
with mock.patch.object(self.pool, '_connect_one',
with mock.patch.object(self.pool, 'connect_one',
side_effect=[None, None, None, (ready, 'worker.example')]), \
mock.patch.object(self.pool, '_schedule_rotation'):
for failures, delay in enumerate((1, 2, 2), 1):
@@ -348,7 +372,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
async def test_misses_during_backoff_do_not_retry_and_shutdown_cancels_retry(self):
self.pool.REFILL_BACKOFF_INITIAL = 60
with mock.patch.object(self.pool, '_connect_one', return_value=None) as dial:
with mock.patch.object(self.pool, 'connect_one', return_value=None) as dial:
await self.pool.warmup()
await self.wait_for(lambda: 2 in self.pool._refill_after)
for _ in range(10):
@@ -378,8 +402,48 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
self.assertEqual(self.pool._refill_after[2], retry_at)
self.assertFalse(self.pool._refilling)
async def test_all_paused_workers_defer_refill_until_first_expiry(self):
domains = ['later.example', 'first.example']
self.pool._exhausted_until.update({
'later.example': 200, 'first.example': 150, 'unrelated.example': 105,
})
self.pool._refill_after[2] = 180
self.pool._refill_failures[2] = 3
with mock.patch('proxy.pool.time') as clock, \
mock.patch.object(self.pool, '_schedule_rotation'), \
mock.patch.object(RawWebSocket, 'connect', return_value=_open_ws()) as dial:
for now in (100, 149):
clock.monotonic.return_value = now
await self.pool.get(2, '192.0.2.2', domains)
self.assertEqual(self.pool._refill_after[2], 150)
self.assertEqual(self.pool._refill_failures[2], 3)
self.assertNotIn(2, self.pool._refilling)
dial.assert_not_awaited()
clock.monotonic.return_value = 150
await self.pool.get(2, '192.0.2.2', domains)
await self.pool._refilling[2]
dial.assert_awaited_once()
self.assertEqual(self.pool._idle[2][0][2], 'first.example')
self.assertNotIn(2, self.pool._refill_failures)
self.assertNotIn(2, self.pool._refill_after)
async def test_failed_dial_pauses_last_available_worker(self):
self.pool._exhausted_until['paused.example'] = 120
with mock.patch('proxy.pool.time') as clock, \
mock.patch.object(self.pool, '_schedule_rotation'), \
mock.patch.object(RawWebSocket, 'connect', side_effect=OSError()) as dial:
clock.monotonic.return_value = 100
await self.pool.get(2, '192.0.2.2', ['paused.example', 'ready.example'])
await self.pool._refilling[2]
dial.assert_awaited_once()
self.assertEqual(self.pool._exhausted_until['ready.example'],
100 + self.pool.FAILURE_COOLDOWN)
self.assertEqual(self.pool._refill_after[2], 120)
self.assertNotIn(2, self.pool._refill_failures)
async def test_zero_size_and_missing_worker_domains_do_not_start_refills(self):
with mock.patch.object(self.pool, '_connect_one') as dial:
with mock.patch.object(self.pool, 'connect_one') as dial:
with mock.patch.object(proxy_config, 'pool_size', 0):
await self.pool.warmup()
self.assertIsNone(await self.pool.get(2, '192.0.2.2', ['worker.example']))
@@ -405,7 +469,7 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
return ready, 'b.example'
with mock.patch.object(proxy_config, 'pool_size', 1), \
mock.patch.object(pool, '_connect_one', side_effect=connect):
mock.patch.object(pool, 'connect_one', side_effect=connect):
pool._schedule_refill(4, '192.0.2.4', ['b.example'])
await asyncio.wait_for(started.wait(), 1)
await pool.close()
@@ -418,5 +482,69 @@ class CfWorkerPoolTest(unittest.IsolatedAsyncioTestCase):
idle.writer.close.assert_called_once()
class CfWorkerFailureReportTest(unittest.TestCase):
MONOTONIC_NOW = 1000.0
def _report(self, exc):
pool = _CfWorkerPool()
with mock.patch('proxy.pool.time.monotonic', return_value=self.MONOTONIC_NOW):
pool.report_failure('w.example', exc)
return pool
def _available(self, pool, now):
with mock.patch('proxy.pool.time.monotonic', return_value=now):
return pool.available_domains(['w.example'])
def test_429_disables_domain_until_the_next_day(self):
midnight_utc = 20_000 * 86400
with mock.patch('proxy.pool.time.time', return_value=midnight_utc - 30):
pool = self._report(WsHandshakeError(429, '429 Too Many Requests'))
self.assertEqual(self._available(pool, self.MONOTONIC_NOW + 29), [])
self.assertEqual(self._available(pool, self.MONOTONIC_NOW + 30), ['w.example'])
def test_5xx_pauses_domain_for_a_minute(self):
pool = self._report(WsHandshakeError(503, '503 Service Unavailable'))
self.assertEqual(
pool._exhausted_until['w.example'],
self.MONOTONIC_NOW + _CfWorkerPool.FAILURE_COOLDOWN,
)
self.assertEqual(self._available(pool, self.MONOTONIC_NOW), [])
self.assertEqual(
self._available(
pool, self.MONOTONIC_NOW + _CfWorkerPool.FAILURE_COOLDOWN + 1),
['w.example'],
)
def test_network_errors_pause_domain(self):
for exc in (OSError('connection reset'), asyncio.TimeoutError()):
with self.subTest(exc=exc):
pool = self._report(exc)
self.assertEqual(self._available(pool, self.MONOTONIC_NOW), [])
self.assertEqual(
self._available(
pool, self.MONOTONIC_NOW + _CfWorkerPool.FAILURE_COOLDOWN + 1),
['w.example'],
)
def test_client_4xx_keeps_domain_available(self):
for status in (400, 403, 404):
with self.subTest(status=status):
pool = self._report(WsHandshakeError(status, '%d error' % status))
self.assertNotIn('w.example', pool._exhausted_until)
self.assertEqual(self._available(pool, self.MONOTONIC_NOW), ['w.example'])
def test_unknown_errors_are_ignored(self):
pool = self._report(ValueError('unexpected'))
self.assertNotIn('w.example', pool._exhausted_until)
def test_longer_quota_pause_is_not_shortened(self):
with mock.patch('proxy.pool.time.time', return_value=12 * 3600):
pool = self._report(WsHandshakeError(429, '429 Too Many Requests'))
until = pool._exhausted_until['w.example']
with mock.patch('proxy.pool.time.monotonic', return_value=self.MONOTONIC_NOW + 1):
pool.report_failure('w.example', WsHandshakeError(503, '503 error'))
self.assertEqual(pool._exhausted_until['w.example'], until)
if __name__ == '__main__':
unittest.main()
+210 -2
View File
@@ -2,6 +2,7 @@ import asyncio
import unittest
from unittest.mock import AsyncMock, Mock, patch
from proxy import cf_websocket
from proxy.raw_websocket import RawWebSocket, WsHandshakeError, _xor_mask
@@ -15,6 +16,10 @@ def _raw_frame(opcode, data, fin=True):
return bytes([b0, 127]) + n.to_bytes(8, 'big') + data
async def _hang():
await asyncio.Future()
class _NullWriter:
def write(self, data):
pass
@@ -144,6 +149,23 @@ class ParseCloseTest(unittest.TestCase):
class CloseTest(unittest.IsolatedAsyncioTestCase):
async def test_cancellation_when_close_operation_finishes_is_not_lost(self):
for operation in ('drain', 'wait_closed'):
with self.subTest(operation=operation):
task = None
async def finish_and_cancel():
task.cancel()
writer = Mock(drain=AsyncMock(), wait_closed=AsyncMock())
getattr(writer, operation).side_effect = finish_and_cancel
ws = RawWebSocket(asyncio.StreamReader(), writer)
task = asyncio.create_task(ws.close())
with self.assertRaises(asyncio.CancelledError):
await task
writer.close.assert_called_once()
writer.wait_closed.assert_awaited_once()
async def test_peer_close_still_closes_transport_without_another_close_frame(self):
reader = asyncio.StreamReader()
reader.feed_data(_raw_frame(RawWebSocket.OP_CLOSE, b'\x03\xe8'))
@@ -189,6 +211,55 @@ class CloseTest(unittest.IsolatedAsyncioTestCase):
task.cancel()
await asyncio.gather(task, return_exceptions=True)
async def test_silent_peer_does_not_hold_close_until_tls_shutdown_timeout(self):
# TLS wait_closed() waits for the peer's close_notify for up to 30s
writer = Mock(drain=AsyncMock(), wait_closed=AsyncMock(side_effect=_hang))
ws = RawWebSocket(asyncio.StreamReader(), writer)
with patch.object(RawWebSocket, 'CLOSE_TIMEOUT', .01):
await asyncio.wait_for(ws.close(), 1)
writer.close.assert_called_once()
writer.transport.abort.assert_called_once()
async def test_peer_that_stopped_reading_does_not_hold_close_in_drain(self):
writer = Mock(drain=AsyncMock(side_effect=_hang), wait_closed=AsyncMock())
ws = RawWebSocket(asyncio.StreamReader(), writer)
with patch.object(RawWebSocket, 'CLOSE_TIMEOUT', .01):
await asyncio.wait_for(ws.close(), 1)
writer.close.assert_called_once()
writer.wait_closed.assert_awaited_once()
writer.transport.abort.assert_not_called()
async def test_failing_abort_after_timeout_does_not_escape_close(self):
writer = Mock(drain=AsyncMock(), wait_closed=AsyncMock(side_effect=_hang))
writer.transport.abort.side_effect = RuntimeError('transport already gone')
ws = RawWebSocket(asyncio.StreamReader(), writer)
with patch.object(RawWebSocket, 'CLOSE_TIMEOUT', .01):
await asyncio.wait_for(ws.close(), 1)
writer.transport.abort.assert_called_once()
async def test_cancelling_close_during_wait_closed_propagates_without_hanging(self):
waiting = asyncio.Event()
async def wait_closed():
waiting.set()
await asyncio.Future()
writer = Mock(drain=AsyncMock(), wait_closed=AsyncMock(side_effect=wait_closed))
ws = RawWebSocket(asyncio.StreamReader(), writer)
task = asyncio.create_task(ws.close())
await asyncio.wait_for(waiting.wait(), 1)
task.cancel()
with self.assertRaises(asyncio.CancelledError):
await asyncio.wait_for(task, 1)
writer.close.assert_called_once()
writer.transport.abort.assert_called_once()
class HandshakeErrorTest(unittest.TestCase):
def test_redirect_status_codes(self):
@@ -199,6 +270,16 @@ class HandshakeErrorTest(unittest.TestCase):
class HandshakeCleanupTest(unittest.IsolatedAsyncioTestCase):
async def test_init_send_failure_or_cancellation_aborts_transport(self):
for error in (ConnectionResetError(), asyncio.CancelledError()):
with self.subTest(error=type(error)):
writer = Mock(drain=AsyncMock(side_effect=error))
ws = RawWebSocket(asyncio.StreamReader(), writer)
with self.assertRaises(type(error)):
await ws.send_init(b'init')
writer.transport.abort.assert_called_once()
self.assertTrue(ws._closed)
async def test_cancelling_pending_upgrade_closes_socket(self):
reader = asyncio.StreamReader()
writer = Mock(drain=AsyncMock())
@@ -216,7 +297,7 @@ class HandshakeCleanupTest(unittest.IsolatedAsyncioTestCase):
task.cancel()
with self.assertRaises(asyncio.CancelledError):
await task
writer.close.assert_called_once()
writer.transport.abort.assert_called_once()
async def test_failed_upgrade_closes_socket(self):
for error in (ConnectionResetError(), asyncio.TimeoutError()):
@@ -228,7 +309,134 @@ class HandshakeCleanupTest(unittest.IsolatedAsyncioTestCase):
patch('proxy.raw_websocket.set_sock_opts'):
with self.assertRaises(type(error)):
await RawWebSocket.connect('192.0.2.1', 'example.org')
writer.close.assert_called_once()
writer.transport.abort.assert_called_once()
class CfDomainTimeoutTest(unittest.IsolatedAsyncioTestCase):
def setUp(self):
cf_websocket.reset_cf_timeouts()
self.addCleanup(cf_websocket.reset_cf_timeouts)
async def connect(self, *hosts, secure=True):
return await cf_websocket.connect_cf_domains(((h, h) for h in hosts), secure=secure, label='test')
async def test_clients_dial_in_parallel_and_http_responses_do_not_throttle(self):
statuses = iter((101, 429, 101, 503, 429))
started = asyncio.Queue()
release = asyncio.Event()
async def dial(host, *args, **kwargs):
if host == 'preferred':
status = next(statuses)
started.put_nowait(host)
await release.wait()
if status != 101:
raise WsHandshakeError(status, 'unavailable')
return object()
with patch.object(RawWebSocket, 'connect', side_effect=dial):
clients = [asyncio.create_task(self.connect('preferred', 'other')) for _ in range(5)]
try:
for _ in clients:
await asyncio.wait_for(started.get(), 1)
release.set()
results = await asyncio.gather(*clients)
self.assertCountEqual([name for _, name in results], ['preferred'] * 2 + ['other'] * 3)
finally:
for task in clients:
task.cancel()
await asyncio.gather(*clients, return_exceptions=True)
with patch.object(RawWebSocket, 'connect', return_value=object()):
self.assertEqual((await self.connect('preferred'))[1], 'preferred')
async def test_five_timeouts_cover_five_domains_and_cooldown_is_per_mode(self):
hosts = ('a', 'http-error', 'b', 'c', 'd', 'e', 'f')
responses = [asyncio.TimeoutError(), WsHandshakeError(503, 'unavailable'),
TimeoutError(), TimeoutError(), TimeoutError(), TimeoutError(),
WsHandshakeError(429, 'busy'), object()]
with patch.object(RawWebSocket, 'connect', side_effect=responses) as dial:
self.assertIsNone(await self.connect(*hosts))
self.assertEqual((await self.connect(*hosts))[1], 'b')
self.assertEqual(
[(call.args[0], call.kwargs['secure'], call.kwargs['timeout'])
for call in dial.await_args_list],
[('a', True, 3), ('http-error', False, 3), ('b', False, 3),
('c', True, 5), ('d', False, 5), ('e', True, 10),
('http-error', True, 3), ('b', True, 3)],
)
async def test_timeout_retries_same_domain_and_successes_set_first_mode(self):
ws = object()
with patch.object(RawWebSocket, 'connect',
side_effect=[TimeoutError(), ws, ws, TimeoutError(), ws]) as dial:
self.assertEqual(await self.connect('a'), (ws, 'a'))
self.assertEqual(await self.connect('b'), (ws, 'b'))
self.assertEqual(await self.connect('b'), (ws, 'b'))
self.assertEqual(
[(call.args[0], call.kwargs['secure']) for call in dial.await_args_list],
[('a', True), ('a', False), ('b', False), ('b', False), ('b', True)],
)
async def test_single_domain_tries_other_mode_on_timeout_or_cooldown(self):
ws = object()
responses = [WsHandshakeError(503, 'unavailable'), TimeoutError(),
WsHandshakeError(503, 'unavailable'), ws]
with patch.object(RawWebSocket, 'connect', side_effect=responses) as dial:
self.assertIsNone(await self.connect('a'))
self.assertIsNone(await self.connect('a'))
self.assertEqual(await self.connect('a'), (ws, 'a'))
self.assertEqual([call.kwargs['secure'] for call in dial.await_args_list],
[True, True, False, False])
async def test_timeout_retry_skips_to_other_front_without_waiting(self):
with patch.object(cf_websocket, 'CF_TIMEOUT_COOLDOWN', 0), \
patch.object(RawWebSocket, 'connect', side_effect=asyncio.TimeoutError()):
self.assertIsNone(await self.connect('a', secure=False))
started, release = asyncio.Event(), asyncio.Event()
async def dial(host, *args, **kwargs):
if host == 'a':
started.set()
await release.wait()
raise WsHandshakeError(429, 'busy')
return object()
with patch.object(RawWebSocket, 'connect', side_effect=dial) as connect:
retry = asyncio.create_task(self.connect('a', secure=False))
try:
await asyncio.wait_for(started.wait(), 1)
result = await asyncio.wait_for(self.connect('a', 'b', secure=False), 1)
self.assertEqual(result[1], 'b')
self.assertEqual(
[(call.args[0], call.kwargs['secure']) for call in connect.await_args_list],
[('a', False), ('b', False)],
)
finally:
release.set()
await retry
with patch.object(RawWebSocket, 'connect', return_value=object()):
self.assertEqual((await self.connect('a', secure=False))[1], 'a')
async def test_cancelling_timeout_retry_releases_it_for_next_client(self):
with patch.object(cf_websocket, 'CF_TIMEOUT_COOLDOWN', 0), \
patch.object(RawWebSocket, 'connect', side_effect=asyncio.TimeoutError()):
await self.connect('a')
started = asyncio.Event()
async def dial(*args, **kwargs):
started.set()
await asyncio.Future()
with patch.object(RawWebSocket, 'connect', side_effect=dial):
retry = asyncio.create_task(self.connect('a'))
await asyncio.wait_for(started.wait(), 1)
retry.cancel()
with self.assertRaises(asyncio.CancelledError):
await retry
with patch.object(RawWebSocket, 'connect', return_value=object()) as connect:
self.assertEqual((await self.connect('a'))[1], 'a')
connect.assert_awaited_once_with('a', 'a', path='/apiws', secure=True, timeout=3.0)
if __name__ == '__main__':
+3 -1
View File
@@ -14,8 +14,10 @@ class TcpFallbackTest(unittest.IsolatedAsyncioTestCase):
self.remote = Mock(drain=AsyncMock(), wait_closed=AsyncMock())
async def fallback(self, dst='192.0.2.1', port=443):
writer = Mock()
writer.is_closing.return_value = False
return await bridge._tcp_fallback(
Mock(), Mock(), dst, port, b'init', 'test', Mock())
asyncio.StreamReader(), writer, dst, port, b'init', 'test', Mock())
async def test_failure_backoff_doubles_caps_and_skips_new_connections(self):
with patch.object(bridge.asyncio, 'open_connection',
+291
View File
@@ -1,8 +1,13 @@
import asyncio
import threading
import unittest
from unittest import mock
from utils import tray_common
# Captured before tests patch threading.Thread for the proxy thread
_RealThread = threading.Thread
class CheckUpdateAsyncTest(unittest.TestCase):
def test_disabled_check_does_not_start_a_thread(self):
@@ -45,5 +50,291 @@ class CheckUpdateAsyncTest(unittest.TestCase):
self.assertEqual(seen, [])
class _StoppingThread:
"""A proxy thread whose cleanup outlives stop_proxy()'s join timeout."""
def __init__(self, finishes_on_join):
self.alive = True
self.finishes_on_join = finishes_on_join
self.joins = []
def is_alive(self):
return self.alive
def join(self, timeout=None):
self.joins.append(timeout)
if self.finishes_on_join:
self.alive = False
class _FakeLoop:
def __init__(self):
self.stop_requests = 0
def call_soon_threadsafe(self, callback):
self.stop_requests += 1
class ProxyStartupTest(unittest.TestCase):
def test_restart_before_loop_is_ready_does_not_lose_stop(self):
entering_loop = threading.Event()
release_loop = threading.Event()
restarted = threading.Event()
new_event_loop = asyncio.new_event_loop
runs = []
errors = []
def delayed_loop():
entering_loop.set()
if not release_loop.wait(2):
raise AssertionError('proxy startup was not released')
return new_event_loop()
async def run(stop_event):
runs.append(stop_event.is_set())
if len(runs) == 2:
restarted.set()
await stop_event.wait()
with mock.patch.object(tray_common, '_proxy_thread', None), \
mock.patch.object(tray_common, '_async_stop', None), \
mock.patch.object(tray_common, '_stop_requested', threading.Event()), \
mock.patch.object(tray_common, '_lifecycle_version', 0), \
mock.patch.object(tray_common, 'apply_proxy_config', return_value=True), \
mock.patch.object(tray_common.asyncio, 'new_event_loop', side_effect=delayed_loop), \
mock.patch.object(tray_common, '_run', side_effect=run), \
mock.patch.object(tray_common.time, 'sleep'):
click = _RealThread(target=tray_common.restart_proxy, args=({}, errors.append))
try:
tray_common.start_proxy({}, errors.append)
self.assertTrue(entering_loop.wait(1))
click.start()
self.assertTrue(tray_common._stop_requested.wait(1))
release_loop.set()
self.assertTrue(restarted.wait(2))
click.join(2)
self.assertFalse(click.is_alive())
self.assertEqual(runs, [True, False])
self.assertEqual(errors, [])
finally:
release_loop.set()
tray_common.stop_proxy()
if click.ident is not None:
click.join(3)
class ProxyLifecycleTest(unittest.TestCase):
"""Real start/stop/restart with a fake proxy thread: nothing binds a port."""
def setUp(self):
self.created = []
self.started_beside_alive = 0
def new_thread(*args, **kwargs):
current = tray_common._proxy_thread
if any(t.is_alive() for t in self.created) or (current and current.is_alive()):
self.started_beside_alive += 1
thread = _StoppingThread(finishes_on_join=True)
thread.start = lambda: None
self.created.append(thread)
return thread
for patcher in (
mock.patch.object(tray_common, '_proxy_thread', None),
mock.patch.object(tray_common, '_stop_requested', threading.Event()),
mock.patch.object(tray_common, '_lifecycle_version', 0),
mock.patch.object(tray_common, '_async_stop', (_FakeLoop(), threading.Event())),
mock.patch.object(tray_common, 'apply_proxy_config', return_value=True),
mock.patch.object(tray_common.threading, 'Thread', side_effect=new_thread),
mock.patch.object(tray_common.time, 'sleep')):
patcher.start()
self.addCleanup(patcher.stop)
def test_start_does_not_replace_a_running_proxy(self):
running = _StoppingThread(finishes_on_join=False)
tray_common._proxy_thread = running
tray_common.start_proxy({}, lambda message: None)
self.assertIs(tray_common._proxy_thread, running)
self.assertEqual(self.created, [])
def test_restart_waits_for_cleanup_and_starts_automatically(self):
stuck = _StoppingThread(finishes_on_join=False)
tray_common._proxy_thread = stuck
waiting = threading.Event()
finished = threading.Event()
def join(timeout=None):
stuck.joins.append(timeout)
if timeout is None:
waiting.set()
if not finished.wait(2):
raise AssertionError('old proxy was not released')
stuck.alive = False
stuck.join = join
click = _RealThread(target=tray_common.restart_proxy,
args=({}, lambda message: None))
click.start()
try:
self.assertTrue(waiting.wait(1), 'restart must wait for the old proxy')
self.assertEqual(self.created, [])
self.assertTrue(stuck.is_alive())
finally:
finished.set()
click.join(3)
self.assertFalse(click.is_alive())
self.assertEqual(stuck.joins, [None])
self.assertFalse(stuck.is_alive())
self.assertEqual(len(self.created), 1)
self.assertIs(tray_common._proxy_thread, self.created[0])
def test_start_after_stop_timeout_waits_for_cleanup(self):
running = _StoppingThread(finishes_on_join=False)
tray_common._proxy_thread = running
tray_common.stop_proxy()
self.assertIs(tray_common._proxy_thread, running)
running.finishes_on_join = True
tray_common.start_proxy({}, lambda message: None)
self.assertEqual(running.joins, [5, None])
self.assertFalse(running.is_alive())
self.assertEqual(len(self.created), 1)
def test_stop_before_loop_is_ready_still_joins_thread(self):
running = _StoppingThread(finishes_on_join=True)
tray_common._proxy_thread = running
with mock.patch.object(tray_common, '_async_stop', None):
tray_common.stop_proxy()
self.assertTrue(tray_common._stop_requested.is_set())
self.assertEqual(running.joins, [5])
self.assertIsNone(tray_common._proxy_thread)
def test_stop_handles_loop_closed_during_signal(self):
loop = mock.Mock()
loop.call_soon_threadsafe.side_effect = RuntimeError('Event loop is closed')
loop.is_closed.return_value = True
running = _StoppingThread(finishes_on_join=True)
tray_common._proxy_thread = running
with mock.patch.object(tray_common, '_async_stop', (loop, threading.Event())):
tray_common.restart_proxy({}, lambda message: None)
self.assertFalse(running.is_alive())
self.assertEqual(len(self.created), 1)
def test_stop_supersedes_pending_restart(self):
self.check_stop_supersedes(tray_common.restart_proxy)
def test_stop_supersedes_pending_start_after_stop_timeout(self):
tray_common._stop_requested.set()
self.check_stop_supersedes(tray_common.start_proxy)
def check_stop_supersedes(self, action):
running = _StoppingThread(finishes_on_join=False)
tray_common._proxy_thread = running
waiting = threading.Event()
finished = threading.Event()
def join(timeout=None):
if timeout is None:
waiting.set()
if not finished.wait(2):
raise AssertionError('old proxy was not released')
running.alive = False
running.join = join
click = _RealThread(target=action,
args=({}, lambda message: None))
click.start()
try:
self.assertTrue(waiting.wait(1))
# stop_proxy must return even while restart is waiting on cleanup.
stopped = threading.Event()
stop = _RealThread(target=lambda: (tray_common.stop_proxy(), stopped.set()))
stop.start()
try:
self.assertTrue(stopped.wait(1))
finally:
finished.set()
stop.join(3)
finally:
finished.set()
click.join(3)
self.assertFalse(click.is_alive())
self.assertEqual(self.created, [])
def test_latest_restart_uses_latest_config(self):
running = _StoppingThread(finishes_on_join=False)
tray_common._proxy_thread = running
first_waiting = threading.Event()
both_waiting = threading.Event()
finished = threading.Event()
joins = []
def join(timeout=None):
joins.append(timeout)
first_waiting.set()
if len(joins) == 2:
both_waiting.set()
if not finished.wait(2):
raise AssertionError('old proxy was not released')
running.alive = False
running.join = join
clicks = [_RealThread(target=tray_common.restart_proxy,
args=({'port': port}, lambda message: None))
for port in (1080, 1081)]
clicks[0].start()
try:
self.assertTrue(first_waiting.wait(1))
clicks[1].start()
self.assertTrue(both_waiting.wait(1))
finally:
finished.set()
for click in clicks:
if click.ident is not None:
click.join(3)
self.assertTrue(all(not click.is_alive() for click in clicks))
tray_common.apply_proxy_config.assert_called_once_with({'port': 1081})
self.assertEqual(len(self.created), 1)
self.assertEqual(self.started_beside_alive, 0)
def test_normal_stop_then_start(self):
running = _StoppingThread(finishes_on_join=True)
tray_common._proxy_thread = running
tray_common.stop_proxy()
tray_common.start_proxy({}, lambda message: None)
self.assertFalse(running.is_alive())
self.assertEqual(len(self.created), 1)
self.assertIs(tray_common._proxy_thread, self.created[0])
def test_parallel_restarts_never_run_two_proxies_at_once(self):
tray_common._proxy_thread = _StoppingThread(finishes_on_join=True)
both_checked = threading.Barrier(2, timeout=1)
def apply_after_both_checked(cfg):
# Without serialisation both restarts get here before either sets _proxy_thread
try:
both_checked.wait()
except threading.BrokenBarrierError:
pass
return True
tray_common.apply_proxy_config.side_effect = apply_after_both_checked
clicks = [_RealThread(target=tray_common.restart_proxy, args=({}, lambda message: None))
for _ in range(2)]
for click in clicks:
click.start()
for click in clicks:
click.join(5)
# Concurrent requests may coalesce, but never start beside a live proxy.
self.assertEqual(self.started_beside_alive, 0)
self.assertEqual(sum(t.is_alive() for t in self.created), 1)
self.assertIs(tray_common._proxy_thread, self.created[-1])
if __name__ == '__main__':
unittest.main()
+43
View File
@@ -27,6 +27,18 @@ class AssetNameTest(unittest.TestCase):
self.assertEqual(windows_update.asset_name(), expected)
class CanSelfUpdateTest(unittest.TestCase):
def test_writable_folder_leaves_no_files_behind(self):
with tempfile.TemporaryDirectory() as directory, \
mock.patch.object(sys, 'executable', str(Path(directory) / 'app.exe')):
self.assertTrue(windows_update.can_self_update())
self.assertEqual(list(Path(directory).iterdir()), [])
def test_unwritable_folder_is_reported(self):
with mock.patch.object(windows_update.os, 'open', side_effect=PermissionError('denied')):
self.assertFalse(windows_update.can_self_update())
class ApplyUpdateTest(unittest.TestCase):
def setUp(self):
stack = ExitStack()
@@ -61,6 +73,15 @@ class ApplyUpdateTest(unittest.TestCase):
self.assertEqual(self.launch.call_args[0][0], [str(self.exe), '--portable'])
self.assertEqual(self.launch.call_args[1]['creationflags'], 520)
def test_unwritable_folder_fails_before_downloading_or_touching_files(self):
with mock.patch.object(windows_update, 'can_self_update', return_value=False):
with self.assertRaises(PermissionError):
windows_update.apply_update(self.asset, self.prepare)
self.opener.open.assert_not_called()
self.assertEqual(list(self.exe.parent.iterdir()), [self.exe])
self.prepare.assert_not_called()
self.launch.assert_not_called()
def test_missing_or_corrupt_checksum_does_not_replace_or_launch(self):
for digest in ('', 'sha256:' + '0' * 64):
with self.subTest(digest=digest):
@@ -132,6 +153,28 @@ class UpdateFlowTest(unittest.TestCase):
app.update_ctk_form('update', asset=asset)
update.assert_called_once_with(asset)
def _offered_asset(self, writable):
app = self.windows
asset = {'url': 'https://example.invalid/new.exe', 'digest': 'sha256:' + '0' * 64}
with ExitStack() as stack:
stack.enter_context(mock.patch.object(app, 'IS_FROZEN', True))
stack.enter_context(mock.patch.object(app, '_exiting', False))
stack.enter_context(mock.patch.object(app, '_tray_icon', None))
stack.enter_context(mock.patch.object(app, 'get_status', return_value={'has_update': True}))
stack.enter_context(mock.patch.object(app, 'asset_name', return_value='app.exe'))
stack.enter_context(mock.patch.object(app, 'find_asset', return_value=asset))
stack.enter_context(mock.patch.object(app, 'can_self_update', return_value=writable))
form = stack.enter_context(mock.patch.object(app, 'update_ctk_form', return_value='close'))
thread = stack.enter_context(mock.patch.object(app.threading, 'Thread'))
app._trigger_update_flow()
thread.call_args.kwargs['target']()
return asset, form.call_args.kwargs['asset']
def test_update_button_is_offered_only_when_the_folder_is_writable(self):
asset, offered = self._offered_asset(writable=True)
self.assertEqual(offered, asset)
self.assertIsNone(self._offered_asset(writable=False)[1])
def test_failed_launch_recovers_proxy_and_lock_instead_of_exiting(self):
app = self.windows
+3 -3
View File
@@ -9,8 +9,8 @@ from typing import Union
from proxy import coerce_domain_list, parse_dc_ip_list
from ui.i18n import t
UI_ONLY_KEYS = frozenset({
"appearance", "autostart", "check_updates", "language"
LIVE_SETTINGS_KEYS = frozenset({
"appearance", "autostart", "check_updates", "language", "verbose"
})
@@ -21,7 +21,7 @@ class SettingsChange:
@property
def requires_restart(self) -> bool:
return bool(self.changed_keys - UI_ONLY_KEYS)
return bool(self.changed_keys - LIVE_SETTINGS_KEYS)
def prepare_settings(current: dict, values: dict, defaults: dict) -> SettingsChange:
+3
View File
@@ -9,6 +9,7 @@ from tkinter import messagebox
from ui.settings_form import validate_config_form
from ui.i18n import set_language, t
from ui.settings import prepare_settings
from utils.logging_setup import set_verbose_logging
log = logging.getLogger("tg-ws-tray")
@@ -71,6 +72,8 @@ class SettingsDialog:
messagebox.showerror(t("app.error_title"), str(exc), parent=self.root)
return
self.config.update(deepcopy(change.config))
if "verbose" in change.changed_keys:
set_verbose_logging(change.config["verbose"])
set_language(change.config["language"])
changed_keys = change.changed_keys | ({"autostart"} if autostart_changed else set())
log.info("Settings saved: %s", ", ".join(sorted(changed_keys)))
+5 -1
View File
@@ -1,4 +1,4 @@
"""Shared construction and formatting of the rotating log file handler.
"""Shared logging setup for the tray and CLI.
Centralizes the rotation invariant so both the tray and the CLI log paths
behave identically and the file can never grow without bound (issue #885).
@@ -18,6 +18,10 @@ _MIN_BYTES = 32 * 1024
_MIN_BACKUPS = 1
def set_verbose_logging(verbose: bool) -> None:
logging.getLogger().setLevel(logging.DEBUG if verbose else logging.INFO)
def build_log_handler(
path: str,
log_max_mb: float = 5,
+81 -32
View File
@@ -20,7 +20,7 @@ from proxy.utils import DomainCensorFilter
from proxy.tg_ws_proxy import _run
from utils.default_config import default_tray_config
from utils.diagnostics import diagnose_listen_error
from utils.logging_setup import build_log_handler
from utils.logging_setup import build_log_handler, set_verbose_logging
log = logging.getLogger("tg-ws-tray")
@@ -230,9 +230,8 @@ _LOG_FMT_CONSOLE = "%(asctime)s %(levelname)-5s %(message)s"
def setup_logging(verbose: bool = False, log_max_mb: float = 5) -> None:
ensure_dirs()
level = logging.DEBUG if verbose else logging.INFO
set_verbose_logging(verbose)
root = logging.getLogger()
root.setLevel(level)
logging.getLogger('asyncio').setLevel(logging.WARNING)
fh = build_log_handler(str(LOG_FILE), log_max_mb=log_max_mb, backups=1)
@@ -242,7 +241,7 @@ def setup_logging(verbose: bool = False, log_max_mb: float = 5) -> None:
if not IS_FROZEN:
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(level)
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter(_LOG_FMT_CONSOLE, datefmt="%H:%M:%S"))
ch.addFilter(DomainCensorFilter())
root.addHandler(ch)
@@ -305,6 +304,11 @@ def load_icon():
_proxy_thread: Optional[threading.Thread] = None
_async_stop: Optional[Tuple[asyncio.AbstractEventLoop, asyncio.Event]] = None
_stop_requested = threading.Event()
_lifecycle_version = 0
# Tray actions run start/stop/restart from worker threads; serialise them so
# repeated clicks cannot interleave and start two proxies
_lifecycle_lock = threading.Lock()
def _run_proxy_thread(show_error: Callable[[str], None]) -> None:
@@ -314,6 +318,8 @@ def _run_proxy_thread(show_error: Callable[[str], None]) -> None:
asyncio.set_event_loop(loop)
stop_ev = asyncio.Event()
_async_stop = (loop, stop_ev)
if _stop_requested.is_set():
stop_ev.set()
try:
loop.run_until_complete(_run(stop_event=stop_ev))
@@ -336,8 +342,8 @@ def _run_proxy_thread(show_error: Callable[[str], None]) -> None:
*pending, return_exceptions=True
))
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
_async_stop = None
loop.close()
def apply_proxy_config(cfg: dict) -> bool:
@@ -379,43 +385,86 @@ def apply_proxy_config(cfg: dict) -> bool:
def start_proxy(cfg: dict, on_error: Callable[[str], None]) -> None:
global _lifecycle_version
with _lifecycle_lock:
previous = _proxy_thread
if previous and previous.is_alive() and not _stop_requested.is_set():
log.info("Proxy already running")
return
_lifecycle_version += 1
version = _lifecycle_version
# Update recovery can call start_proxy() after a timed-out stop, too.
# Leave the lock free so a later stop can cancel this pending start.
if previous and previous.is_alive():
previous.join()
_start_proxy_if_current(cfg, on_error, version)
def _start_proxy_if_current(cfg: dict, on_error: Callable[[str], None], version: int) -> None:
global _proxy_thread
if _proxy_thread and _proxy_thread.is_alive():
log.info("Proxy already running")
return
with _lifecycle_lock:
if version != _lifecycle_version:
return
if apply_proxy_config(cfg):
pc = proxy_config
log.info("Starting proxy on %s:%d ...", pc.host, pc.port)
_proxy_thread = threading.Thread(
target=_run_proxy_thread, args=(on_error,), daemon=True, name="proxy"
)
_stop_requested.clear()
_proxy_thread.start()
return
if not apply_proxy_config(cfg):
from ui.i18n import t
on_error(t("error.dc_config"))
return
from ui.i18n import t
on_error(t("error.dc_config"))
pc = proxy_config
log.info("Starting proxy on %s:%d ...", pc.host, pc.port)
_proxy_thread = threading.Thread(
target=_run_proxy_thread, args=(on_error,), daemon=True, name="proxy"
)
_proxy_thread.start()
def _request_proxy_stop():
global _lifecycle_version
# Called under _lifecycle_lock. Remember stops issued before the proxy
# thread has published its loop, and invalidate any pending restart.
_lifecycle_version += 1
_stop_requested.set()
handle = _async_stop
if handle:
loop, stop_ev = handle
try:
loop.call_soon_threadsafe(stop_ev.set)
except RuntimeError:
if not loop.is_closed():
raise
return _proxy_thread, _lifecycle_version
def stop_proxy() -> None:
global _proxy_thread, _async_stop
if _async_stop:
loop, stop_ev = _async_stop
loop.call_soon_threadsafe(stop_ev.set)
if _proxy_thread:
_proxy_thread.join(timeout=5)
if _proxy_thread.is_alive():
log.warning("Proxy thread did not stop within timeout; "
"port may still be in use")
_proxy_thread = None
log.info("Proxy stopped")
global _proxy_thread
with _lifecycle_lock:
previous, _ = _request_proxy_stop()
if previous:
previous.join(timeout=5)
with _lifecycle_lock:
# Keep a thread that is still cleaning up, so start_proxy() and the
# next restart see it instead of starting a second proxy beside it
if _proxy_thread is previous and previous and not previous.is_alive():
_proxy_thread = None
if previous and previous.is_alive():
log.warning("Proxy thread did not stop within timeout; "
"port may still be in use")
return
log.info("Proxy stopped")
def restart_proxy(cfg: dict, on_error: Callable[[str], None]) -> None:
log.info("Restarting proxy...")
stop_proxy()
with _lifecycle_lock:
log.info("Restarting proxy...")
previous, version = _request_proxy_stop()
# The old run still owns shared pools and the stop handle. Wait outside
# the lock so stopping or exiting can supersede this restart.
if previous and previous.is_alive():
previous.join()
time.sleep(1.0)
start_proxy(cfg, on_error)
_start_proxy_if_current(cfg, on_error, version)
def tg_proxy_url(cfg: dict) -> str:
+21
View File
@@ -2,9 +2,11 @@
from __future__ import annotations
import ctypes
import os
import subprocess
import sys
import sysconfig
import uuid
from contextlib import suppress
from pathlib import Path
from typing import Callable, Optional
@@ -24,10 +26,29 @@ def asset_name() -> Optional[str]:
return None
def can_self_update() -> bool:
"""Whether the executable's folder is writable.
Neither os.access nor tempfile.mkstemp can be used here: on Windows the
former ignores ACLs and the latter keeps retrying on PermissionError, so
in a folder without write access it hangs instead of failing.
"""
probe = Path(sys.executable).parent / f"TgWsProxy_probe_{uuid.uuid4().hex}"
try:
os.close(os.open(probe, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
except OSError:
return False
with suppress(OSError):
probe.unlink()
return True
def apply_update(asset: dict, before_restart: Callable[[], None]) -> None:
"""Verify, replace and launch; keep the old executable if any step fails."""
exe = Path(sys.executable)
backup = exe.with_name(exe.stem + "_oldtgws.exe")
if not can_self_update():
raise PermissionError(f"No write access to {exe.parent}")
downloaded = download_asset(asset["url"], exe.parent, digest=asset["digest"])
try:
backup.unlink(missing_ok=True)
+2 -2
View File
@@ -45,7 +45,7 @@ from utils.tray_common import (
save_config, start_proxy, stop_proxy, tg_proxy_url,
)
from utils.update_check import find_asset, get_status, RELEASES_PAGE_URL
from utils.windows_update import apply_update, asset_name
from utils.windows_update import apply_update, asset_name, can_self_update
from ui.ctk_tray_ui import (
install_tray_config_buttons, install_tray_config_form,
populate_first_run_window, tray_settings_scroll_and_footer,
@@ -276,7 +276,7 @@ def _trigger_update_flow(icon=None, item=None) -> None:
_tray_icon.menu = _build_menu()
url = (st.get("html_url") or "").strip() or RELEASES_PAGE_URL
ver = st.get("latest") or "?"
asset = find_asset(asset_name()) if IS_FROZEN else None
asset = find_asset(asset_name()) if IS_FROZEN and can_self_update() else None
choice = update_ctk_form(
t("update.available", version=ver),