From f42468b77a36e5f75b23d6432dd61bdd056ed7b1 Mon Sep 17 00:00:00 2001 From: Flowseal Date: Mon, 23 Nov 2026 11:56:41 +0300 Subject: [PATCH] Move CF-proxy websocket connection to a separate file --- proxy/bridge.py | 3 +- proxy/cf_h2.py | 2 +- proxy/cf_websocket.py | 103 ++++++++++++++++++++++++++++++++++++ proxy/raw_websocket.py | 96 +-------------------------------- proxy/tg_ws_proxy.py | 3 +- tests/test_cf_h2.py | 3 +- tests/test_h2_routing.py | 3 +- tests/test_raw_websocket.py | 12 ++--- 8 files changed, 119 insertions(+), 106 deletions(-) create mode 100644 proxy/cf_websocket.py diff --git a/proxy/bridge.py b/proxy/bridge.py index 67d04ba..f09c4a2 100644 --- a/proxy/bridge.py +++ b/proxy/bridge.py @@ -10,10 +10,11 @@ from .utils import * from .stats import stats from .balancer import balancer from .config import proxy_config -from .raw_websocket import RawWebSocket, cf_prefers_tls, connect_cf_domains +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 diff --git a/proxy/cf_h2.py b/proxy/cf_h2.py index 87feccf..b7ad23a 100644 --- a/proxy/cf_h2.py +++ b/proxy/cf_h2.py @@ -12,8 +12,8 @@ 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 .raw_websocket import cf_tls_in_cooldown from .stats import stats from .utils import ( DC_DEFAULT_IPS, PROTO_TAG_ABRIDGED, diff --git a/proxy/cf_websocket.py b/proxy/cf_websocket.py new file mode 100644 index 0000000..02ad85e --- /dev/null +++ b/proxy/cf_websocket.py @@ -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 diff --git a/proxy/raw_websocket.py b/proxy/raw_websocket.py index 6a1df4c..74408b2 100644 --- a/proxy/raw_websocket.py +++ b/proxy/raw_websocket.py @@ -1,30 +1,17 @@ import os import logging -import math import base64 import struct -import time import asyncio import socket as _socket -from dataclasses import dataclass -from typing import Dict, Iterable, List, Optional, Tuple +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') -@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() - _st_BB = struct.Struct('>BB') _st_BBH = struct.Struct('>BBH') @@ -351,84 +338,3 @@ class RawWebSocket: return opcode, _xor_mask(payload, mask_key), fin payload = await self.reader.readexactly(length) return opcode, payload, fin - - -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 diff --git a/proxy/tg_ws_proxy.py b/proxy/tg_ws_proxy.py index 740cd70..ae8274e 100644 --- a/proxy/tg_ws_proxy.py +++ b/proxy/tg_ws_proxy.py @@ -24,7 +24,8 @@ 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 .raw_websocket import reset_cf_timeouts, set_sock_opts +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, diff --git a/tests/test_cf_h2.py b/tests/test_cf_h2.py index b464227..8514748 100644 --- a/tests/test_cf_h2.py +++ b/tests/test_cf_h2.py @@ -13,7 +13,8 @@ from proxy.cf_h2 import ( CfH2Pool, MAX_CHANNEL_REQUESTS, MAX_PACKET, _HttpChannel, _HttpLane, _ReplayPacket, _encode_reply, _read_packet, bridge_h2, ) -from proxy.raw_websocket import RawWebSocket, connect_cf_domains, reset_cf_timeouts +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: diff --git a/tests/test_h2_routing.py b/tests/test_h2_routing.py index 8aff7c4..706430d 100644 --- a/tests/test_h2_routing.py +++ b/tests/test_h2_routing.py @@ -6,8 +6,9 @@ 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, reset_cf_timeouts +from proxy.raw_websocket import RawWebSocket from proxy.utils import PROTO_TAG_INTERMEDIATE diff --git a/tests/test_raw_websocket.py b/tests/test_raw_websocket.py index 7cf941e..fbc1151 100644 --- a/tests/test_raw_websocket.py +++ b/tests/test_raw_websocket.py @@ -2,7 +2,7 @@ import asyncio import unittest from unittest.mock import AsyncMock, Mock, patch -from proxy import raw_websocket +from proxy import cf_websocket from proxy.raw_websocket import RawWebSocket, WsHandshakeError, _xor_mask @@ -314,11 +314,11 @@ class HandshakeCleanupTest(unittest.IsolatedAsyncioTestCase): class CfDomainTimeoutTest(unittest.IsolatedAsyncioTestCase): def setUp(self): - raw_websocket.reset_cf_timeouts() - self.addCleanup(raw_websocket.reset_cf_timeouts) + cf_websocket.reset_cf_timeouts() + self.addCleanup(cf_websocket.reset_cf_timeouts) async def connect(self, *hosts, secure=True): - return await raw_websocket.connect_cf_domains(((h, h) for h in hosts), secure=secure, label='test') + 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)) @@ -389,7 +389,7 @@ class CfDomainTimeoutTest(unittest.IsolatedAsyncioTestCase): [True, True, False, False]) async def test_timeout_retry_skips_to_other_front_without_waiting(self): - with patch.object(raw_websocket, 'CF_TIMEOUT_COOLDOWN', 0), \ + 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)) @@ -419,7 +419,7 @@ class CfDomainTimeoutTest(unittest.IsolatedAsyncioTestCase): 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(raw_websocket, 'CF_TIMEOUT_COOLDOWN', 0), \ + with patch.object(cf_websocket, 'CF_TIMEOUT_COOLDOWN', 0), \ patch.object(RawWebSocket, 'connect', side_effect=asyncio.TimeoutError()): await self.connect('a') started = asyncio.Event()