relay_server.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. from __future__ import annotations
  2. import asyncio
  3. import contextlib
  4. import time
  5. from dataclasses import dataclass, field
  6. from typing import Dict
  7. from .protocol import AUTH, PING, PONG, STATUS_ERR, STATUS_OK, TCP_CLOSE, TCP_DATA, TCP_OPEN, TCP_STATUS, UDP_RECV, UDP_SEND, Frame, decode_json, read_frame, write_frame
  8. @dataclass
  9. class TcpSession:
  10. session_id: int
  11. stream_id: int
  12. writer: asyncio.StreamWriter
  13. task: asyncio.Task
  14. @dataclass
  15. class UdpSession:
  16. session_id: int
  17. stream_id: int
  18. transport: asyncio.DatagramTransport | None = None
  19. protocol: "RelayUdpProtocol | None" = None
  20. host: str = ""
  21. port: int = 0
  22. family: int = 0
  23. class RelayUdpProtocol(asyncio.DatagramProtocol):
  24. def __init__(self, channel: "RelayChannel", session_id: int, stream_id: int) -> None:
  25. self.channel = channel
  26. self.session_id = session_id
  27. self.stream_id = stream_id
  28. def datagram_received(self, data: bytes, _addr) -> None:
  29. if self.channel.closed:
  30. return
  31. asyncio.create_task(self.channel.safe_send(Frame(UDP_RECV, self.session_id, self.stream_id, 0, 0, data)))
  32. @dataclass
  33. class RelayChannel:
  34. reader: asyncio.StreamReader
  35. writer: asyncio.StreamWriter
  36. token: str
  37. tcp_sessions: Dict[tuple[int, int], TcpSession] = field(default_factory=dict)
  38. udp_sessions: Dict[tuple[int, int], UdpSession] = field(default_factory=dict)
  39. closed: bool = False
  40. send_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
  41. authed_at: float = 0.0
  42. frame_count: int = 0
  43. async def run(self) -> None:
  44. peer = self.writer.get_extra_info("peername")
  45. authed = False
  46. try:
  47. auth = await read_frame(self.reader)
  48. if auth.kind != AUTH or decode_json(auth.payload).get("token") != self.token:
  49. raise PermissionError("invalid token")
  50. authed = True
  51. self.authed_at = time.monotonic()
  52. await self.safe_send(Frame(AUTH, 0, 0, 0, STATUS_OK, b"ok"))
  53. while True:
  54. frame = await read_frame(self.reader)
  55. self.frame_count += 1
  56. await self.handle(frame)
  57. except asyncio.IncompleteReadError:
  58. if authed:
  59. lived = time.monotonic() - self.authed_at if self.authed_at else 0.0
  60. if lived >= 5 or self.frame_count > 2:
  61. print(f"[relay] disconnected peer={peer} lived={lived:.1f}s")
  62. except asyncio.CancelledError:
  63. pass
  64. except Exception as exc:
  65. if authed:
  66. lived = time.monotonic() - self.authed_at if self.authed_at else 0.0
  67. if lived >= 5 or self.frame_count > 2:
  68. print(f"[relay] channel error peer={peer} lived={lived:.1f}s error={exc!r}")
  69. finally:
  70. await self.close()
  71. async def safe_send(self, frame: Frame) -> bool:
  72. if self.closed:
  73. return False
  74. try:
  75. async with self.send_lock:
  76. if self.closed:
  77. return False
  78. await write_frame(self.writer, frame)
  79. return True
  80. except (BrokenPipeError, ConnectionResetError, RuntimeError, OSError, asyncio.CancelledError):
  81. return False
  82. async def handle(self, frame: Frame) -> None:
  83. key = (frame.session_id, frame.stream_id)
  84. if frame.kind == PING:
  85. await self.safe_send(Frame(PONG, 0, 0, frame.seq, 0, b"pong"))
  86. return
  87. if frame.kind == TCP_OPEN:
  88. meta = decode_json(frame.payload)
  89. family = int(meta.get("family", 0)) or 0
  90. try:
  91. reader, writer = await asyncio.open_connection(meta["host"], int(meta["port"]), family=family or 0)
  92. task = asyncio.create_task(self._tcp_pump(frame.session_id, frame.stream_id, reader))
  93. self.tcp_sessions[key] = TcpSession(frame.session_id, frame.stream_id, writer, task)
  94. await self.safe_send(Frame(TCP_STATUS, frame.session_id, frame.stream_id, 0, STATUS_OK, b"ok"))
  95. except Exception as exc:
  96. await self.safe_send(Frame(TCP_STATUS, frame.session_id, frame.stream_id, 0, STATUS_ERR, str(exc).encode()))
  97. return
  98. if frame.kind == TCP_DATA:
  99. session = self.tcp_sessions.get(key)
  100. if session:
  101. try:
  102. session.writer.write(frame.payload)
  103. await session.writer.drain()
  104. except Exception:
  105. await self._close_tcp(key)
  106. return
  107. if frame.kind == TCP_CLOSE:
  108. await self._close_tcp(key)
  109. return
  110. if frame.kind == UDP_SEND:
  111. session = self.udp_sessions.get(key)
  112. meta = None
  113. payload = frame.payload
  114. if frame.packet_id > 0:
  115. meta = decode_json(frame.payload[: frame.packet_id])
  116. payload = frame.payload[frame.packet_id :]
  117. if session is None:
  118. if meta is None:
  119. return
  120. family = int(meta.get("family", 0)) or 0
  121. transport, protocol = await asyncio.get_running_loop().create_datagram_endpoint(
  122. lambda: RelayUdpProtocol(self, frame.session_id, frame.stream_id),
  123. remote_addr=(meta["host"], int(meta["port"])),
  124. family=family or 0,
  125. )
  126. session = UdpSession(frame.session_id, frame.stream_id, transport, protocol, meta["host"], int(meta["port"]), family)
  127. self.udp_sessions[key] = session
  128. with contextlib.suppress(Exception):
  129. session.transport.sendto(payload)
  130. return
  131. async def _tcp_pump(self, session_id: int, stream_id: int, reader: asyncio.StreamReader) -> None:
  132. try:
  133. while True:
  134. chunk = await reader.read(65536)
  135. if not chunk:
  136. break
  137. sent = await self.safe_send(Frame(TCP_DATA, session_id, stream_id, 0, 0, chunk))
  138. if not sent:
  139. break
  140. except asyncio.CancelledError:
  141. pass
  142. except Exception:
  143. pass
  144. finally:
  145. if not self.closed:
  146. await self.safe_send(Frame(TCP_CLOSE, session_id, stream_id, 0, 0, b""))
  147. await self._close_tcp((session_id, stream_id), from_task=True)
  148. async def _close_tcp(self, key: tuple[int, int], from_task: bool = False) -> None:
  149. session = self.tcp_sessions.pop(key, None)
  150. if session is None:
  151. return
  152. if not from_task and session.task is not asyncio.current_task():
  153. session.task.cancel()
  154. with contextlib.suppress(Exception):
  155. await session.task
  156. session.writer.close()
  157. with contextlib.suppress(Exception):
  158. await session.writer.wait_closed()
  159. async def close(self) -> None:
  160. if self.closed:
  161. return
  162. self.closed = True
  163. for key in list(self.tcp_sessions):
  164. await self._close_tcp(key)
  165. for session in self.udp_sessions.values():
  166. if session.transport:
  167. session.transport.close()
  168. self.udp_sessions.clear()
  169. self.writer.close()
  170. with contextlib.suppress(Exception):
  171. await self.writer.wait_closed()
  172. class RelayServer:
  173. def __init__(self, token: str) -> None:
  174. self.token = token
  175. async def start(self, host: str, port: int) -> None:
  176. server = await asyncio.start_server(self._accept, host, port)
  177. sockets = ", ".join(str(sock.getsockname()) for sock in server.sockets or [])
  178. print(f"[relay] listening on {sockets}")
  179. async with server:
  180. await server.serve_forever()
  181. async def _accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  182. await RelayChannel(reader, writer, self.token).run()