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