session close reason

This commit is contained in:
Flowseal
2026-06-23 14:55:25 +03:00
parent 91d39a5ebe
commit fed772049b
2 changed files with 42 additions and 6 deletions
+25
View File
@@ -1,5 +1,6 @@
import os
import ssl
import logging
import base64
import struct
import asyncio
@@ -8,6 +9,8 @@ import socket as _socket
from typing import List, Optional, Tuple
from .config import proxy_config
log = logging.getLogger('tg-mtproto-proxy')
_st_BB = struct.Struct('>BB')
_st_BBH = struct.Struct('>BBH')
@@ -160,6 +163,9 @@ class RawWebSocket:
if opcode == self.OP_CLOSE:
self._closed = True
code, reason = self._parse_close(payload)
log.debug("WS OP_CLOSE from upstream: code=%s reason=%r",
code, reason)
try:
self.writer.write(self._build_frame(
self.OP_CLOSE,
@@ -202,6 +208,25 @@ class RawWebSocket:
except Exception:
pass
_WS_CLOSE_REASONS = {
1000: 'normal', 1001: 'going_away', 1002: 'protocol_error',
1003: 'unsupported_data', 1006: 'abnormal', 1007: 'bad_data',
1008: 'policy_violation', 1009: 'too_big', 1010: 'missing_extension',
1011: 'internal_error',
}
@classmethod
def _parse_close(cls, payload: Optional[bytes]) -> Tuple[Optional[int], str]:
if not payload or len(payload) < 2:
return None, ''
try:
code = int.from_bytes(payload[:2], 'big')
text = payload[2:].decode('utf-8', errors='replace')
name = cls._WS_CLOSE_REASONS.get(code)
return code, f"{text} ({name})" if name else text
except Exception:
return None, ''
@staticmethod
def _build_frame(opcode: int, data: bytes,
mask: bool = False) -> bytes: