relay_server.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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, encode_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. authed_kind: str = "normal"
  44. async def run(self) -> None:
  45. peer = self.writer.get_extra_info("peername")
  46. authed = False
  47. try:
  48. auth = await read_frame(self.reader)
  49. if auth.kind != AUTH:
  50. return
  51. try:
  52. payload = decode_json(auth.payload) if auth.payload else {}
  53. except Exception:
  54. return
  55. if payload.get("token") != self.token:
  56. return
  57. authed = True
  58. self.authed_at = time.monotonic()
  59. self.authed_kind = payload.get("purpose", "normal")
  60. ack_payload = {"status": "ok", "kind": self.authed_kind}
  61. await self.safe_send(Frame(AUTH, 0, 0, 0, STATUS_OK, encode_json(ack_payload)))
  62. while True:
  63. frame = await read_frame(self.reader)
  64. self.frame_count += 1
  65. await self.handle(frame)
  66. except asyncio.IncompleteReadError:
  67. if authed and self.authed_kind != "probe":
  68. lived = time.monotonic() - self.authed_at if self.authed_at else 0.0
  69. if lived >= 15 or self.frame_count > 20:
  70. print(f"[relay] session closed peer={peer} kind={self.authed_kind} lived={lived:.1f}s frames={self.frame_count}")
  71. except asyncio.CancelledError:
  72. pass
  73. except Exception as exc:
  74. if authed and self.authed_kind != "probe":
  75. lived = time.monotonic() - self.authed_at if self.authed_at else 0.0
  76. print(f"[relay] session error peer={peer} kind={self.authed_kind} lived={lived:.1f}s frames={self.frame_count} error={exc!r}")
  77. finally:
  78. await self.close()
  79. async def safe_send(self, frame: Frame) -> bool:
  80. if self.closed:
  81. return False
  82. try:
  83. async with self.send_lock:
  84. if self.closed:
  85. return False
  86. await write_frame(self.writer, frame)
  87. return True
  88. except (BrokenPipeError, ConnectionResetError, RuntimeError, OSError, asyncio.CancelledError):
  89. return False
  90. async def handle(self, frame: Frame) -> None:
  91. key = (frame.session_id, frame.stream_id)
  92. if frame.kind == PING:
  93. await self.safe_send(Frame(PONG, 0, 0, frame.seq, 0, b"pong"))
  94. return
  95. if frame.kind == AUTH:
  96. return
  97. if frame.kind == TCP_OPEN:
  98. try:
  99. meta = decode_json(frame.payload) if frame.payload else {}
  100. family = int(meta.get("family", 0)) or 0
  101. reader, writer = await asyncio.open_connection(meta["host"], int(meta["port"]), family=family or 0)
  102. task = asyncio.create_task(self._tcp_pump(frame.session_id, frame.stream_id, reader))
  103. self.tcp_sessions[key] = TcpSession(frame.session_id, frame.stream_id, writer, task)
  104. await self.safe_send(Frame(TCP_STATUS, frame.session_id, frame.stream_id, 0, STATUS_OK, b"ok"))
  105. except Exception as exc:
  106. await self.safe_send(Frame(TCP_STATUS, frame.session_id, frame.stream_id, 0, STATUS_ERR, str(exc).encode()))
  107. return
  108. if frame.kind == TCP_DATA:
  109. session = self.tcp_sessions.get(key)
  110. if session:
  111. try:
  112. session.writer.write(frame.payload)
  113. await session.writer.drain()
  114. except Exception:
  115. await self._close_tcp(key)
  116. return
  117. if frame.kind == TCP_CLOSE:
  118. await self._close_tcp(key)
  119. return
  120. if frame.kind == UDP_SEND:
  121. session = self.udp_sessions.get(key)
  122. meta = None
  123. payload = frame.payload
  124. if frame.packet_id > 0 and frame.packet_id <= len(frame.payload):
  125. try:
  126. meta = decode_json(frame.payload[: frame.packet_id])
  127. payload = frame.payload[frame.packet_id :]
  128. except Exception:
  129. if session is None:
  130. return
  131. payload = frame.payload
  132. if session is None:
  133. if meta is None:
  134. return
  135. try:
  136. family = int(meta.get("family", 0)) or 0
  137. transport, protocol = await asyncio.get_running_loop().create_datagram_endpoint(
  138. lambda: RelayUdpProtocol(self, frame.session_id, frame.stream_id),
  139. remote_addr=(meta["host"], int(meta["port"])),
  140. family=family or 0,
  141. )
  142. session = UdpSession(frame.session_id, frame.stream_id, transport, protocol, meta["host"], int(meta["port"]), family)
  143. self.udp_sessions[key] = session
  144. except Exception as exc:
  145. await self.safe_send(Frame(TCP_STATUS, frame.session_id, frame.stream_id, 0, STATUS_ERR, str(exc).encode()))
  146. return
  147. if session.transport is not None:
  148. with contextlib.suppress(Exception):
  149. session.transport.sendto(payload)
  150. return
  151. async def _tcp_pump(self, session_id: int, stream_id: int, reader: asyncio.StreamReader) -> None:
  152. try:
  153. while True:
  154. chunk = await reader.read(65536)
  155. if not chunk:
  156. break
  157. sent = await self.safe_send(Frame(TCP_DATA, session_id, stream_id, 0, 0, chunk))
  158. if not sent:
  159. break
  160. except asyncio.CancelledError:
  161. pass
  162. except Exception:
  163. pass
  164. finally:
  165. if not self.closed:
  166. await self.safe_send(Frame(TCP_CLOSE, session_id, stream_id, 0, 0, b""))
  167. await self._close_tcp((session_id, stream_id), from_task=True)
  168. async def _close_tcp(self, key: tuple[int, int], from_task: bool = False) -> None:
  169. session = self.tcp_sessions.pop(key, None)
  170. if session is None:
  171. return
  172. if not from_task and session.task is not asyncio.current_task():
  173. session.task.cancel()
  174. with contextlib.suppress(Exception):
  175. await session.task
  176. session.writer.close()
  177. with contextlib.suppress(Exception):
  178. await session.writer.wait_closed()
  179. async def close(self) -> None:
  180. if self.closed:
  181. return
  182. self.closed = True
  183. for key in list(self.tcp_sessions):
  184. await self._close_tcp(key)
  185. for session in self.udp_sessions.values():
  186. if session.transport:
  187. session.transport.close()
  188. self.udp_sessions.clear()
  189. self.writer.close()
  190. with contextlib.suppress(Exception):
  191. await self.writer.wait_closed()
  192. class RelayServer:
  193. def __init__(self, token: str) -> None:
  194. self.token = token
  195. async def start(self, host: str, port: int) -> None:
  196. server = await asyncio.start_server(self._accept, host, port)
  197. sockets = ", ".join(str(sock.getsockname()) for sock in server.sockets or [])
  198. print(f"[relay] listening on {sockets}")
  199. async with server:
  200. await server.serve_forever()
  201. async def _accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  202. await RelayChannel(reader, writer, self.token).run()