transparent_edge.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. from __future__ import annotations
  2. import asyncio
  3. import contextlib
  4. import itertools
  5. import socket
  6. import struct
  7. from dataclasses import dataclass, field
  8. from typing import Awaitable, Callable
  9. from .config import Config
  10. from .protocol import STATUS_OK, TCP_CLOSE, TCP_DATA, TCP_OPEN, TCP_STATUS, UDP_RECV, UDP_SEND, Frame, encode_json
  11. from .relay_client import RelayConnection, RelayManager
  12. SO_ORIGINAL_DST = 80
  13. IP6T_SO_ORIGINAL_DST = 80
  14. IP_RECVORIGDSTADDR = 20
  15. IPV6_RECVORIGDSTADDR = 74
  16. @dataclass(frozen=True)
  17. class TargetAddress:
  18. host: str
  19. port: int
  20. family: int
  21. @dataclass(frozen=True)
  22. class PeerAddress:
  23. host: str
  24. port: int
  25. family: int
  26. def parse_sockaddr(raw: bytes) -> TargetAddress:
  27. if len(raw) < 8:
  28. raise ValueError("invalid transparent destination payload")
  29. family = struct.unpack_from("=H", raw, 0)[0]
  30. port = struct.unpack_from("!H", raw, 2)[0]
  31. if family == socket.AF_INET:
  32. host = socket.inet_ntoa(raw[4:8])
  33. return TargetAddress(host=host, port=port, family=family)
  34. if family == socket.AF_INET6:
  35. if len(raw) < 28:
  36. raise ValueError("invalid IPv6 transparent destination payload")
  37. host = socket.inet_ntop(socket.AF_INET6, raw[8:24])
  38. return TargetAddress(host=host, port=port, family=family)
  39. raise ValueError(f"unsupported family={family}")
  40. class BasePath:
  41. def __init__(self, name: str, on_frame: Callable[["BasePath", str, bytes | None], Awaitable[None]]) -> None:
  42. self.name = name
  43. self.on_frame = on_frame
  44. self.opened = False
  45. self.closed = False
  46. async def open(self, target: TargetAddress) -> None:
  47. raise NotImplementedError
  48. async def send(self, data: bytes) -> None:
  49. raise NotImplementedError
  50. async def close(self) -> None:
  51. raise NotImplementedError
  52. class DirectTcpPath(BasePath):
  53. def __init__(self, name: str, on_frame: Callable[[BasePath, str, bytes | None], Awaitable[None]]) -> None:
  54. super().__init__(name, on_frame)
  55. self.reader: asyncio.StreamReader | None = None
  56. self.writer: asyncio.StreamWriter | None = None
  57. self.pump_task: asyncio.Task | None = None
  58. async def open(self, target: TargetAddress) -> None:
  59. try:
  60. family = socket.AF_INET6 if target.family == socket.AF_INET6 else socket.AF_INET
  61. self.reader, self.writer = await asyncio.open_connection(host=target.host, port=target.port, family=family)
  62. self.opened = True
  63. self.pump_task = asyncio.create_task(self._pump())
  64. await self.on_frame(self, "status", b"ok")
  65. except Exception as exc:
  66. await self.on_frame(self, "status", str(exc).encode())
  67. async def _pump(self) -> None:
  68. assert self.reader is not None
  69. try:
  70. while True:
  71. chunk = await self.reader.read(65536)
  72. if not chunk:
  73. break
  74. await self.on_frame(self, "data", chunk)
  75. except Exception:
  76. pass
  77. finally:
  78. await self.on_frame(self, "close", None)
  79. async def send(self, data: bytes) -> None:
  80. if self.closed or self.writer is None:
  81. return
  82. self.writer.write(data)
  83. await self.writer.drain()
  84. async def close(self) -> None:
  85. if self.closed:
  86. return
  87. self.closed = True
  88. if self.pump_task and self.pump_task is not asyncio.current_task():
  89. self.pump_task.cancel()
  90. with contextlib.suppress(Exception):
  91. await self.pump_task
  92. if self.writer:
  93. self.writer.close()
  94. with contextlib.suppress(Exception):
  95. await self.writer.wait_closed()
  96. class RelayTcpPath(BasePath):
  97. def __init__(self, name: str, on_frame: Callable[[BasePath, str, bytes | None], Awaitable[None]], connection: RelayConnection, session_id: int, stream_id: int) -> None:
  98. super().__init__(name, on_frame)
  99. self.connection = connection
  100. self.session_id = session_id
  101. self.stream_id = stream_id
  102. async def open(self, target: TargetAddress) -> None:
  103. if self.connection.closed:
  104. await self.on_frame(self, "status", b"relay unavailable")
  105. return
  106. self.connection.bind(self.session_id, self.stream_id, self._handle_frame)
  107. try:
  108. await self.connection.send(Frame(TCP_OPEN, self.session_id, self.stream_id, 0, 0, encode_json({"host": target.host, "port": target.port, "family": target.family})))
  109. except Exception as exc:
  110. await self.on_frame(self, "status", str(exc).encode())
  111. async def _handle_frame(self, _conn: RelayConnection, frame: Frame) -> None:
  112. if frame.kind == TCP_STATUS:
  113. if frame.packet_id == STATUS_OK:
  114. self.opened = True
  115. await self.on_frame(self, "status", b"ok")
  116. else:
  117. await self.on_frame(self, "status", frame.payload)
  118. return
  119. if frame.kind == TCP_DATA:
  120. await self.on_frame(self, "data", frame.payload)
  121. return
  122. if frame.kind == TCP_CLOSE:
  123. await self.on_frame(self, "close", None)
  124. async def send(self, data: bytes) -> None:
  125. if self.closed or self.connection.closed:
  126. return
  127. await self.connection.send(Frame(TCP_DATA, self.session_id, self.stream_id, 0, 0, data))
  128. async def close(self) -> None:
  129. if self.closed:
  130. return
  131. self.closed = True
  132. self.connection.unbind(self.session_id, self.stream_id)
  133. if not self.connection.closed:
  134. with contextlib.suppress(Exception):
  135. await self.connection.send(Frame(TCP_CLOSE, self.session_id, self.stream_id, 0, 0, b""))
  136. @dataclass
  137. class TransparentSession:
  138. session_id: int
  139. target: TargetAddress
  140. reader: asyncio.StreamReader
  141. writer: asyncio.StreamWriter
  142. paths: list[BasePath]
  143. warmup_bytes: int
  144. stats: dict[str, int]
  145. target_stats: dict[tuple[str, int], dict[str, int]]
  146. opened_count: int = 0
  147. status_count: int = 0
  148. errors: list[str] = field(default_factory=list)
  149. winner: BasePath | None = None
  150. uplink_bytes: int = 0
  151. open_event: asyncio.Event = field(default_factory=asyncio.Event)
  152. winner_event: asyncio.Event = field(default_factory=asyncio.Event)
  153. closed: bool = False
  154. pump_task: asyncio.Task | None = None
  155. def _record_win(self, winner: BasePath) -> None:
  156. self.stats[winner.name] = self.stats.get(winner.name, 0) + 1
  157. key = (self.target.host, self.target.port)
  158. target_stats = self.target_stats.setdefault(key, {})
  159. target_stats[winner.name] = target_stats.get(winner.name, 0) + 1
  160. direct_wins = self.stats.get("direct", 0)
  161. relay_wins = sum(count for name, count in self.stats.items() if name != "direct")
  162. target_direct = target_stats.get("direct", 0)
  163. target_relay = sum(count for name, count in target_stats.items() if name != "direct")
  164. relay_detail = ", ".join(f"{name}={count}" for name, count in sorted(self.stats.items()) if name != "direct") or "none"
  165. target_detail = ", ".join(f"{name}={count}" for name, count in sorted(target_stats.items()) if name != "direct") or "none"
  166. target_pref = "relay" if target_relay > target_direct else "direct"
  167. print(f"[edge] tcp win session={self.session_id} target={self.target.host}:{self.target.port} winner={winner.name} direct={direct_wins} relay={relay_wins} relay_breakdown={relay_detail} target_pref={target_pref} target_direct={target_direct} target_relay={target_relay} target_breakdown={target_detail}")
  168. async def start(self) -> None:
  169. await asyncio.gather(*(path.open(self.target) for path in self.paths), return_exceptions=True)
  170. await asyncio.wait_for(self.open_event.wait(), timeout=10)
  171. if self.opened_count == 0:
  172. raise ConnectionError(self.errors[0] if self.errors else "all paths failed")
  173. self.pump_task = asyncio.create_task(self._pump_local())
  174. async def _pump_local(self) -> None:
  175. try:
  176. while True:
  177. chunk = await self.reader.read(65536)
  178. if not chunk:
  179. break
  180. self.uplink_bytes += len(chunk)
  181. active = [path for path in self.paths if path.opened and not path.closed]
  182. if not active:
  183. break
  184. if self.winner is None and self.uplink_bytes <= self.warmup_bytes:
  185. await asyncio.gather(*(path.send(chunk) for path in active), return_exceptions=True)
  186. else:
  187. if self.winner is None:
  188. await self.winner_event.wait()
  189. if self.winner:
  190. await self.winner.send(chunk)
  191. except Exception:
  192. pass
  193. finally:
  194. await self.close()
  195. async def handle_path(self, path: BasePath, event: str, payload: bytes | None) -> None:
  196. if self.closed:
  197. return
  198. if event == "status":
  199. self.status_count += 1
  200. if payload == b"ok":
  201. self.opened_count += 1
  202. elif payload is not None:
  203. self.errors.append(payload.decode("utf-8", errors="replace"))
  204. if self.opened_count > 0 or self.status_count == len(self.paths):
  205. self.open_event.set()
  206. return
  207. if event == "data":
  208. if self.winner is None:
  209. self.winner = path
  210. self._record_win(path)
  211. self.winner_event.set()
  212. await self._close_losers(path)
  213. if path is self.winner and payload is not None:
  214. self.writer.write(payload)
  215. await self.writer.drain()
  216. return
  217. if event == "close":
  218. path.closed = True
  219. if self.winner is None:
  220. remaining = [candidate for candidate in self.paths if candidate.opened and not candidate.closed]
  221. if not remaining:
  222. await self.close()
  223. elif path is self.winner:
  224. await self.close()
  225. async def _close_losers(self, winner: BasePath) -> None:
  226. await asyncio.gather(*(path.close() for path in self.paths if path is not winner), return_exceptions=True)
  227. async def close(self) -> None:
  228. if self.closed:
  229. return
  230. self.closed = True
  231. print(f"[edge] session={self.session_id} closed target={self.target.host}:{self.target.port}")
  232. if self.pump_task and self.pump_task is not asyncio.current_task():
  233. self.pump_task.cancel()
  234. with contextlib.suppress(Exception):
  235. await self.pump_task
  236. await asyncio.gather(*(path.close() for path in self.paths), return_exceptions=True)
  237. self.writer.close()
  238. with contextlib.suppress(Exception):
  239. await self.writer.wait_closed()
  240. class DirectUdpPath(BasePath):
  241. def __init__(self, name: str, on_frame: Callable[[BasePath, str, bytes | None], Awaitable[None]], target: TargetAddress) -> None:
  242. super().__init__(name, on_frame)
  243. self.target = target
  244. self.socket: socket.socket | None = None
  245. self.read_task: asyncio.Task | None = None
  246. async def open(self, _target: TargetAddress) -> None:
  247. try:
  248. family = socket.AF_INET6 if self.target.family == socket.AF_INET6 else socket.AF_INET
  249. self.socket = socket.socket(family, socket.SOCK_DGRAM)
  250. self.socket.setblocking(False)
  251. await asyncio.get_running_loop().sock_connect(self.socket, (self.target.host, self.target.port))
  252. self.opened = True
  253. self.read_task = asyncio.create_task(self._pump())
  254. await self.on_frame(self, "status", b"ok")
  255. except Exception as exc:
  256. await self.on_frame(self, "status", str(exc).encode())
  257. async def _pump(self) -> None:
  258. assert self.socket is not None
  259. loop = asyncio.get_running_loop()
  260. try:
  261. while True:
  262. data = await loop.sock_recv(self.socket, 65535)
  263. if not data:
  264. break
  265. await self.on_frame(self, "data", data)
  266. except Exception:
  267. pass
  268. finally:
  269. await self.on_frame(self, "close", None)
  270. async def send(self, data: bytes) -> None:
  271. if self.closed or self.socket is None:
  272. return
  273. await asyncio.get_running_loop().sock_sendall(self.socket, data)
  274. async def close(self) -> None:
  275. if self.closed:
  276. return
  277. self.closed = True
  278. if self.read_task and self.read_task is not asyncio.current_task():
  279. self.read_task.cancel()
  280. with contextlib.suppress(Exception):
  281. await self.read_task
  282. if self.socket:
  283. self.socket.close()
  284. class RelayUdpPath(BasePath):
  285. def __init__(self, name: str, on_frame: Callable[[BasePath, str, bytes | None], Awaitable[None]], connection: RelayConnection, session_id: int, stream_id: int, target: TargetAddress) -> None:
  286. super().__init__(name, on_frame)
  287. self.connection = connection
  288. self.session_id = session_id
  289. self.stream_id = stream_id
  290. self.target = target
  291. async def open(self, _target: TargetAddress) -> None:
  292. if self.connection.closed:
  293. await self.on_frame(self, "status", b"relay unavailable")
  294. return
  295. self.connection.bind(self.session_id, self.stream_id, self._handle_frame)
  296. self.opened = True
  297. await self.on_frame(self, "status", b"ok")
  298. async def _handle_frame(self, _conn: RelayConnection, frame: Frame) -> None:
  299. if frame.kind == UDP_RECV:
  300. await self.on_frame(self, "data", frame.payload)
  301. async def send(self, data: bytes) -> None:
  302. if self.closed or self.connection.closed:
  303. return
  304. meta = encode_json({"host": self.target.host, "port": self.target.port, "family": self.target.family})
  305. payload = meta + data
  306. await self.connection.send(Frame(UDP_SEND, self.session_id, self.stream_id, 0, len(meta), payload))
  307. async def close(self) -> None:
  308. if self.closed:
  309. return
  310. self.closed = True
  311. self.connection.unbind(self.session_id, self.stream_id)
  312. @dataclass
  313. class UdpFlow:
  314. flow_id: int
  315. source: PeerAddress
  316. target: TargetAddress
  317. send_response: Callable[[PeerAddress, bytes], Awaitable[None]]
  318. paths: list[BasePath]
  319. winner: BasePath | None = None
  320. closed: bool = False
  321. last_activity: float = 0.0
  322. async def start(self) -> None:
  323. await asyncio.gather(*(path.open(self.target) for path in self.paths), return_exceptions=True)
  324. async def send(self, payload: bytes) -> None:
  325. self.last_activity = asyncio.get_running_loop().time()
  326. active = [path for path in self.paths if path.opened and not path.closed]
  327. if self.winner is None:
  328. await asyncio.gather(*(path.send(payload) for path in active), return_exceptions=True)
  329. elif not self.winner.closed:
  330. await self.winner.send(payload)
  331. async def handle_path(self, path: BasePath, event: str, payload: bytes | None) -> None:
  332. self.last_activity = asyncio.get_running_loop().time()
  333. if event == "data" and payload is not None:
  334. if self.winner is None:
  335. self.winner = path
  336. print(f"[edge] udp flow={self.flow_id} winner={path.name} target={self.target.host}:{self.target.port}")
  337. if path is self.winner:
  338. await self.send_response(self.source, payload)
  339. if event == "close":
  340. path.closed = True
  341. async def close(self) -> None:
  342. if self.closed:
  343. return
  344. self.closed = True
  345. await asyncio.gather(*(path.close() for path in self.paths), return_exceptions=True)
  346. class TransparentUdpListener:
  347. def __init__(self, edge: "TransparentEdge", family: int, bind_host: str, port: int) -> None:
  348. self.edge = edge
  349. self.family = family
  350. self.bind_host = bind_host
  351. self.port = port
  352. self.socket: socket.socket | None = None
  353. def start(self) -> None:
  354. sock = socket.socket(self.family, socket.SOCK_DGRAM)
  355. sock.setblocking(False)
  356. if self.family == socket.AF_INET:
  357. sock.setsockopt(socket.SOL_IP, IP_RECVORIGDSTADDR, 1)
  358. sock.bind((self.bind_host, self.port))
  359. else:
  360. sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  361. sock.setsockopt(socket.IPPROTO_IPV6, IPV6_RECVORIGDSTADDR, 1)
  362. sock.bind((self.bind_host, self.port, 0, 0))
  363. self.socket = sock
  364. asyncio.get_running_loop().add_reader(sock.fileno(), self._on_readable)
  365. print(f"[edge] transparent udp listening on {sock.getsockname()}")
  366. def _on_readable(self) -> None:
  367. assert self.socket is not None
  368. try:
  369. data, ancdata, _flags, src = self.socket.recvmsg(65535, 512)
  370. except BlockingIOError:
  371. return
  372. except Exception as exc:
  373. print(f"[edge] udp recv failed family={self.family} error={exc!r}")
  374. return
  375. original = None
  376. for level, ctype, cdata in ancdata:
  377. if self.family == socket.AF_INET and level == socket.SOL_IP and ctype == IP_RECVORIGDSTADDR:
  378. original = parse_sockaddr(cdata)
  379. break
  380. if self.family == socket.AF_INET6 and level == socket.IPPROTO_IPV6 and ctype == IPV6_RECVORIGDSTADDR:
  381. original = parse_sockaddr(cdata)
  382. break
  383. if original is None:
  384. print(f"[edge] udp missing original dst family={self.family} src={src}")
  385. return
  386. if self.family == socket.AF_INET:
  387. source = PeerAddress(host=src[0], port=src[1], family=socket.AF_INET)
  388. else:
  389. source = PeerAddress(host=src[0], port=src[1], family=socket.AF_INET6)
  390. asyncio.create_task(self.edge.handle_udp_datagram(source, original, data, self))
  391. async def send_response(self, source: PeerAddress, payload: bytes) -> None:
  392. assert self.socket is not None
  393. if source.family == socket.AF_INET:
  394. self.socket.sendto(payload, (source.host, source.port))
  395. else:
  396. self.socket.sendto(payload, (source.host, source.port, 0, 0))
  397. async def close(self) -> None:
  398. if self.socket is None:
  399. return
  400. asyncio.get_running_loop().remove_reader(self.socket.fileno())
  401. self.socket.close()
  402. self.socket = None
  403. class TransparentEdge:
  404. def __init__(self, listen_host: str, listen_port: int, config: Config) -> None:
  405. self.listen_host = listen_host
  406. self.listen_port = listen_port
  407. self.config = config
  408. self.manager = RelayManager(config)
  409. self.session_ids = itertools.count(1)
  410. self.stream_ids = itertools.count(1)
  411. self.udp_listeners: list[TransparentUdpListener] = []
  412. self.udp_flows: dict[tuple[PeerAddress, TargetAddress], UdpFlow] = {}
  413. self.udp_flow_ids = itertools.count(1)
  414. self.udp_gc_task: asyncio.Task | None = None
  415. self.tcp_win_counts: dict[str, int] = {}
  416. self.tcp_target_wins: dict[tuple[str, int], dict[str, int]] = {}
  417. async def start(self) -> None:
  418. await self.manager.start()
  419. print(f"[edge] relay snapshot: {self.manager.snapshot()}")
  420. server4 = await asyncio.start_server(self._accept, self.listen_host, self.listen_port, family=socket.AF_INET)
  421. sockets = [str(sock.getsockname()) for sock in server4.sockets or []]
  422. server6 = None
  423. if self.listen_host in ("::", "::1", "0.0.0.0", "127.0.0.1"):
  424. host6 = "::1" if self.listen_host == "127.0.0.1" else "::"
  425. try:
  426. server6 = await asyncio.start_server(self._accept, host6, self.listen_port, family=socket.AF_INET6)
  427. sockets.extend(str(sock.getsockname()) for sock in server6.sockets or [])
  428. except Exception as exc:
  429. print(f"[edge] ipv6 tcp listener skipped: {exc!r}")
  430. self._start_udp_listeners()
  431. self.udp_gc_task = asyncio.create_task(self._gc_udp_flows())
  432. print(f"[edge] transparent tcp listening on {', '.join(sockets)}")
  433. if server6 is None:
  434. async with server4:
  435. await server4.serve_forever()
  436. else:
  437. async with server4, server6:
  438. await asyncio.gather(server4.serve_forever(), server6.serve_forever())
  439. def _start_udp_listeners(self) -> None:
  440. binds = []
  441. if self.listen_host == "127.0.0.1":
  442. binds = [(socket.AF_INET, "127.0.0.1"), (socket.AF_INET6, "::1")]
  443. elif self.listen_host == "0.0.0.0":
  444. binds = [(socket.AF_INET, "0.0.0.0"), (socket.AF_INET6, "::")]
  445. else:
  446. family = socket.AF_INET6 if ":" in self.listen_host else socket.AF_INET
  447. binds = [(family, self.listen_host)]
  448. for family, host in binds:
  449. try:
  450. listener = TransparentUdpListener(self, family, host, self.listen_port)
  451. listener.start()
  452. self.udp_listeners.append(listener)
  453. except Exception as exc:
  454. print(f"[edge] udp listener skipped family={family} host={host} error={exc!r}")
  455. async def _accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  456. peer = writer.get_extra_info("peername")
  457. try:
  458. target = self._get_original_dst(writer)
  459. session_id = next(self.session_ids)
  460. session = TransparentSession(session_id=session_id, target=target, reader=reader, writer=writer, paths=[], warmup_bytes=self.config.tcp_warmup_bytes, stats=self.tcp_win_counts, target_stats=self.tcp_target_wins)
  461. paths: list[BasePath] = [DirectTcpPath(name="direct", on_frame=lambda path, event, payload, s=session: self._handle_tcp_session(s, path, event, payload))]
  462. for connection in self.manager.available():
  463. stream_id = next(self.stream_ids)
  464. paths.append(RelayTcpPath(name=connection.node.name, on_frame=lambda path, event, payload, s=session: self._handle_tcp_session(s, path, event, payload), connection=connection, session_id=session_id, stream_id=stream_id))
  465. session.paths = paths
  466. print(f"[edge] accept peer={peer} session={session_id} target={target.host}:{target.port} candidates={[path.name for path in paths]}")
  467. await session.start()
  468. except Exception as exc:
  469. print(f"[edge] accept failed peer={peer} error={exc!r}")
  470. writer.close()
  471. with contextlib.suppress(Exception):
  472. await writer.wait_closed()
  473. async def _handle_tcp_session(self, session: TransparentSession, path: BasePath, event: str, payload: bytes | None) -> None:
  474. await session.handle_path(path, event, payload)
  475. def _get_original_dst(self, writer: asyncio.StreamWriter) -> TargetAddress:
  476. sock = writer.get_extra_info("socket")
  477. if sock is None:
  478. raise RuntimeError("socket unavailable")
  479. family = sock.family
  480. if family == socket.AF_INET:
  481. raw = sock.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16)
  482. return parse_sockaddr(raw)
  483. if family == socket.AF_INET6:
  484. raw = sock.getsockopt(socket.IPPROTO_IPV6, IP6T_SO_ORIGINAL_DST, 128)
  485. return parse_sockaddr(raw)
  486. raise RuntimeError(f"unsupported socket family={family}")
  487. async def handle_udp_datagram(self, source: PeerAddress, target: TargetAddress, payload: bytes, listener: TransparentUdpListener) -> None:
  488. key = (source, target)
  489. flow = self.udp_flows.get(key)
  490. if flow is None:
  491. flow_id = next(self.udp_flow_ids)
  492. paths: list[BasePath] = [DirectUdpPath(name="direct", on_frame=lambda path, event, data, fid=flow_id: self._handle_udp_path(fid, path, event, data), target=target)]
  493. for connection in self.manager.available():
  494. stream_id = next(self.stream_ids)
  495. paths.append(RelayUdpPath(name=connection.node.name, on_frame=lambda path, event, data, fid=flow_id: self._handle_udp_path(fid, path, event, data), connection=connection, session_id=flow_id, stream_id=stream_id, target=target))
  496. flow = UdpFlow(flow_id=flow_id, source=source, target=target, send_response=listener.send_response, paths=paths)
  497. self.udp_flows[key] = flow
  498. print(f"[edge] udp flow={flow_id} target={target.host}:{target.port} candidates={[path.name for path in paths]}")
  499. await flow.start()
  500. await flow.send(payload)
  501. async def _handle_udp_path(self, flow_id: int, path: BasePath, event: str, payload: bytes | None) -> None:
  502. for flow in list(self.udp_flows.values()):
  503. if flow.flow_id == flow_id:
  504. await flow.handle_path(path, event, payload)
  505. break
  506. async def _gc_udp_flows(self) -> None:
  507. loop = asyncio.get_running_loop()
  508. while True:
  509. await asyncio.sleep(30)
  510. now = loop.time()
  511. stale = [key for key, flow in self.udp_flows.items() if flow.last_activity and now - flow.last_activity > 120]
  512. for key in stale:
  513. flow = self.udp_flows.pop(key, None)
  514. if flow:
  515. await flow.close()