diff --git a/proxy/event_loop.py b/proxy/event_loop.py index 178676b..969bb39 100644 --- a/proxy/event_loop.py +++ b/proxy/event_loop.py @@ -81,6 +81,16 @@ def install_proactor_socket_guard(loop): _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: diff --git a/proxy/raw_websocket.py b/proxy/raw_websocket.py index d4e5abf..ecfb11c 100644 --- a/proxy/raw_websocket.py +++ b/proxy/raw_websocket.py @@ -8,6 +8,7 @@ import socket as _socket from typing import Dict, Iterable, 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') @@ -60,19 +61,20 @@ def _xor_mask(data: bytes, mask: bytes) -> bytes: int.from_bytes(mask_rep, 'big')).to_bytes(n, 'big') -async def _wait_close(awaitable, timeout): +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((task,), timeout=timeout) + done, _ = await asyncio.wait((completion,), timeout=timeout) if not done: raise asyncio.TimeoutError() return task.result() finally: - if not task.done(): + if cancel_pending and not task.done(): task.cancel() - await asyncio.gather(task, return_exceptions=True) + await completion def set_sock_opts(transport, buffer_size): @@ -275,12 +277,11 @@ class RawWebSocket: finally: try: self.writer.close() - # A silent TLS peer would hold us here for ssl_shutdown_timeout - # (30s) and delay proxy shutdown past the tray's stop timeout - await _wait_close(self.writer.wait_closed(), self.CLOSE_TIMEOUT) + await _wait_close(self.writer.wait_closed(), self.CLOSE_TIMEOUT, + cancel_pending=False) except (asyncio.TimeoutError, asyncio.CancelledError) as exc: try: - self.writer.transport.abort() + abort_transport(self.writer.transport) except Exception: pass if isinstance(exc, asyncio.CancelledError): diff --git a/proxy/tg_ws_proxy.py b/proxy/tg_ws_proxy.py index 3fc4295..740cd70 100644 --- a/proxy/tg_ws_proxy.py +++ b/proxy/tg_ws_proxy.py @@ -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__ == ''): @@ -34,7 +34,9 @@ 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 ClientStreamProtocol, install_proactor_socket_guard, 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 +44,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 @@ -380,11 +383,13 @@ 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 + 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) @@ -424,8 +429,8 @@ 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)) def client_protocol(): return ClientStreamProtocol(client_cb) @@ -570,10 +575,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) diff --git a/utils/tray_common.py b/utils/tray_common.py index 37f21db..613df49 100644 --- a/utils/tray_common.py +++ b/utils/tray_common.py @@ -308,7 +308,7 @@ _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.RLock() +_lifecycle_lock = threading.Lock() def _run_proxy_thread(show_error: Callable[[str], None]) -> None: @@ -385,7 +385,7 @@ def apply_proxy_config(cfg: dict) -> bool: def start_proxy(cfg: dict, on_error: Callable[[str], None]) -> None: - global _proxy_thread, _lifecycle_version + global _lifecycle_version with _lifecycle_lock: previous = _proxy_thread if previous and previous.is_alive() and not _stop_requested.is_set(): @@ -398,22 +398,26 @@ def start_proxy(cfg: dict, on_error: Callable[[str], None]) -> None: # 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 with _lifecycle_lock: if version != _lifecycle_version: return - if not apply_proxy_config(cfg): - from ui.i18n import t - on_error(t("error.dc_config")) + 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 - 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() + from ui.i18n import t + on_error(t("error.dc_config")) def _request_proxy_stop(): @@ -460,9 +464,7 @@ def restart_proxy(cfg: dict, on_error: Callable[[str], None]) -> None: if previous and previous.is_alive(): previous.join() time.sleep(1.0) - with _lifecycle_lock: - if version == _lifecycle_version: - start_proxy(cfg, on_error) + _start_proxy_if_current(cfg, on_error, version) def tg_proxy_url(cfg: dict) -> str: