Socket occupation fix

This commit is contained in:
Flowseal
2026-11-23 06:28:14 +03:00
parent 0970820f1f
commit 13d764f809
9 changed files with 295 additions and 41 deletions
+20 -24
View File
@@ -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
from .raw_websocket import RawWebSocket, connect_cf_domains
from .pool import cf_worker_pool
from .network_debug import WsActivity
from .cf_h2 import bridge_h2
from .event_loop import client_setup
log = logging.getLogger('tg-mtproto-proxy')
@@ -162,7 +163,8 @@ async def do_fallback(reader, writer, relay_init, label,
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)
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
@@ -212,9 +214,10 @@ async def _cfproxy_worker_fallback(reader, writer, relay_init, label,
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)
with client_setup(reader, writer):
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)
@@ -226,7 +229,7 @@ async def _cfproxy_worker_fallback(reader, writer, relay_init, label,
return False
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 +241,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=secure)
chosen_domain = base_domain
break
except Exception as exc:
log.warning("[%s] DC%d%s CF proxy failed: %r (host=%s port=%d)",
label, dc, media_tag, exc, domain, 443 if secure else 80)
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 +260,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 +279,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
+42 -1
View File
@@ -4,12 +4,53 @@ import signal
import socket
import sys
import threading
from contextlib import suppress
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:
+3
View File
@@ -451,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:
+74 -5
View File
@@ -1,17 +1,23 @@
import os
import logging
import math
import base64
import struct
import asyncio
import socket as _socket
from typing import List, Optional, Tuple
from typing import Dict, Iterable, List, Optional, Tuple
from .config import proxy_config
from .utils import create_ssl_context
log = logging.getLogger('tg-mtproto-proxy')
CF_TIMEOUT_COOLDOWN = 30.0
CF_CONNECT_TIMEOUTS = (10.0, 6.0, 4.0, 3.0, 3.0)
_cf_timeout_until: Dict[Tuple[str, bool], float] = {}
_st_BB = struct.Struct('>BB')
_st_BBH = struct.Struct('>BBH')
_st_BBQ = struct.Struct('>BBQ')
@@ -100,6 +106,8 @@ class RawWebSocket:
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(
@@ -122,12 +130,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(
@@ -156,7 +163,7 @@ class RawWebSocket:
location=headers.get('location'))
except BaseException as exc:
if writer is not None:
writer.close()
writer.transport.abort()
if isinstance(exc, Exception) and log.isEnabledFor(logging.DEBUG):
if writer is not None:
stage = 'ws_upgrade'
@@ -171,6 +178,14 @@ class RawWebSocket:
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:
self._closed = True
self.writer.transport.abort()
raise
async def send(self, data: bytes):
if self._closed:
raise ConnectionError("WebSocket closed")
@@ -303,3 +318,57 @@ 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()
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]]:
loop = asyncio.get_running_loop()
timeouts = 0
for name, host in candidates:
key = (host, secure)
now = loop.time()
retry_at = _cf_timeout_until.get(key)
if retry_at is not None:
if now < 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=secure, timeout=attempt_timeout)
except (asyncio.TimeoutError, TimeoutError):
now = loop.time()
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 port=%d); retry in %.0fs',
label, host, 443 if secure else 80, 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 port=%d): %r',
label, host, 443 if secure else 80, 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:
return ws, name
return None
+10 -6
View File
@@ -24,7 +24,7 @@ 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 set_sock_opts
from .raw_websocket import reset_cf_timeouts, 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,
@@ -34,7 +34,7 @@ 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_proactor_socket_guard, install_self_pipe_guard
from .event_loop import ClientStreamProtocol, install_proactor_socket_guard, install_self_pipe_guard
from ._aes import Cipher, algorithms, modes
@@ -348,7 +348,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,
@@ -391,6 +391,7 @@ async def _run(stop_event: Optional[asyncio.Event] = None):
_server_stop_event = stop_event
reset_tcp_backoff()
reset_cf_timeouts()
ws_pool.reset()
cf_worker_pool.reset()
_client_tasks.clear()
@@ -426,7 +427,10 @@ async def _run(stop_event: Optional[asyncio.Event] = None):
_client_tasks.add(task)
task.add_done_callback(_client_tasks.discard)
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:
@@ -549,8 +553,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
+29
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):
+6 -2
View File
@@ -1,4 +1,5 @@
"""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
@@ -14,7 +15,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 +31,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 +91,10 @@ 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)
+108 -2
View File
@@ -2,6 +2,7 @@ import asyncio
import unittest
from unittest.mock import AsyncMock, Mock, patch
from proxy import raw_websocket
from proxy.raw_websocket import RawWebSocket, WsHandshakeError, _xor_mask
@@ -199,6 +200,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 +227,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 +239,102 @@ 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):
raw_websocket.reset_cf_timeouts()
self.addCleanup(raw_websocket.reset_cf_timeouts)
async def connect(self, *hosts):
return await raw_websocket.connect_cf_domains(((h, h) for h in hosts), secure=True, 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_end_search_and_later_clients_skip_timed_out_domains(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], 'f')
self.assertEqual([(call.args[0], call.kwargs['timeout']) for call in dial.await_args_list],
[('a', 10), ('http-error', 6), ('b', 6), ('c', 4),
('d', 3), ('e', 3), ('http-error', 10), ('f', 10)])
async def test_timeout_retry_skips_to_other_front_without_waiting(self):
with patch.object(raw_websocket, 'CF_TIMEOUT_COOLDOWN', 0), \
patch.object(RawWebSocket, 'connect', side_effect=asyncio.TimeoutError()):
self.assertIsNone(await self.connect('a'))
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'))
try:
await asyncio.wait_for(started.wait(), 1)
self.assertEqual((await asyncio.wait_for(self.connect('a', 'b'), 1))[1], 'b')
self.assertEqual(connect.await_count, 2)
finally:
release.set()
await retry
with patch.object(RawWebSocket, 'connect', return_value=object()):
self.assertEqual((await self.connect('a'))[1], 'a')
async def test_cancelling_timeout_retry_releases_it_for_next_client(self):
with patch.object(raw_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()):
self.assertEqual((await self.connect('a'))[1], 'a')
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',