transparent_edge.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. opened_count: int = 0
  145. status_count: int = 0
  146. errors: list[str] = field(default_factory=list)
  147. winner: BasePath | None = None
  148. uplink_bytes: int = 0
  149. open_event: asyncio.Event = field(default_factory=asyncio.Event)
  150. winner_event: asyncio.Event = field(default_factory=asyncio.Event)
  151. closed: bool = False
  152. pump_task: asyncio.Task | None = None
  153. async def start(self) -> None:
  154. await asyncio.gather(*(path.open(self.target) for path in self.paths), return_exceptions=True)
  155. await asyncio.wait_for(self.open_event.wait(), timeout=10)
  156. if self.opened_count == 0:
  157. raise ConnectionError(self.errors[0] if self.errors else "all paths failed")
  158. self.pump_task = asyncio.create_task(self._pump_local())
  159. async def _pump_local(self) -> None:
  160. try:
  161. while True:
  162. chunk = await self.reader.read(65536)
  163. if not chunk:
  164. break
  165. self.uplink_bytes += len(chunk)
  166. active = [path for path in self.paths if path.opened and not path.closed]
  167. if not active:
  168. break
  169. if self.winner is None and self.uplink_bytes <= self.warmup_bytes:
  170. await asyncio.gather(*(path.send(chunk) for path in active), return_exceptions=True)
  171. else:
  172. if self.winner is None:
  173. await self.winner_event.wait()
  174. if self.winner:
  175. await self.winner.send(chunk)
  176. except Exception:
  177. pass
  178. finally:
  179. await self.close()
  180. async def handle_path(self, path: BasePath, event: str, payload: bytes | None) -> None:
  181. if self.closed:
  182. return
  183. if event == "status":
  184. self.status_count += 1
  185. if payload == b"ok":
  186. self.opened_count += 1
  187. elif payload is not None:
  188. self.errors.append(payload.decode("utf-8", errors="replace"))
  189. if self.opened_count > 0 or self.status_count == len(self.paths):
  190. self.open_event.set()
  191. return
  192. if event == "data":
  193. if self.winner is None:
  194. self.winner = path
  195. print(f"[edge] session={self.session_id} winner={path.name} target={self.target.host}:{self.target.port}")
  196. self.winner_event.set()
  197. await self._close_losers(path)
  198. if path is self.winner and payload is not None:
  199. self.writer.write(payload)
  200. await self.writer.drain()
  201. return
  202. if event == "close":
  203. path.closed = True
  204. if self.winner is None:
  205. remaining = [candidate for candidate in self.paths if candidate.opened and not candidate.closed]
  206. if not remaining:
  207. await self.close()
  208. elif path is self.winner:
  209. await self.close()
  210. async def _close_losers(self, winner: BasePath) -> None:
  211. await asyncio.gather(*(path.close() for path in self.paths if path is not winner), return_exceptions=True)
  212. async def close(self) -> None:
  213. if self.closed:
  214. return
  215. self.closed = True
  216. print(f"[edge] session={self.session_id} closed target={self.target.host}:{self.target.port}")
  217. if self.pump_task and self.pump_task is not asyncio.current_task():
  218. self.pump_task.cancel()
  219. with contextlib.suppress(Exception):
  220. await self.pump_task
  221. await asyncio.gather(*(path.close() for path in self.paths), return_exceptions=True)
  222. self.writer.close()
  223. with contextlib.suppress(Exception):
  224. await self.writer.wait_closed()
  225. class DirectUdpPath(BasePath):
  226. def __init__(self, name: str, on_frame: Callable[[BasePath, str, bytes | None], Awaitable[None]], target: TargetAddress) -> None:
  227. super().__init__(name, on_frame)
  228. self.target = target
  229. self.socket: socket.socket | None = None
  230. self.read_task: asyncio.Task | None = None
  231. async def open(self, _target: TargetAddress) -> None:
  232. try:
  233. family = socket.AF_INET6 if self.target.family == socket.AF_INET6 else socket.AF_INET
  234. self.socket = socket.socket(family, socket.SOCK_DGRAM)
  235. self.socket.setblocking(False)
  236. await asyncio.get_running_loop().sock_connect(self.socket, (self.target.host, self.target.port))
  237. self.opened = True
  238. self.read_task = asyncio.create_task(self._pump())
  239. await self.on_frame(self, "status", b"ok")
  240. except Exception as exc:
  241. await self.on_frame(self, "status", str(exc).encode())
  242. async def _pump(self) -> None:
  243. assert self.socket is not None
  244. loop = asyncio.get_running_loop()
  245. try:
  246. while True:
  247. data = await loop.sock_recv(self.socket, 65535)
  248. if not data:
  249. break
  250. await self.on_frame(self, "data", data)
  251. except Exception:
  252. pass
  253. finally:
  254. await self.on_frame(self, "close", None)
  255. async def send(self, data: bytes) -> None:
  256. if self.closed or self.socket is None:
  257. return
  258. await asyncio.get_running_loop().sock_sendall(self.socket, data)
  259. async def close(self) -> None:
  260. if self.closed:
  261. return
  262. self.closed = True
  263. if self.read_task and self.read_task is not asyncio.current_task():
  264. self.read_task.cancel()
  265. with contextlib.suppress(Exception):
  266. await self.read_task
  267. if self.socket:
  268. self.socket.close()
  269. class RelayUdpPath(BasePath):
  270. 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:
  271. super().__init__(name, on_frame)
  272. self.connection = connection
  273. self.session_id = session_id
  274. self.stream_id = stream_id
  275. self.target = target
  276. async def open(self, _target: TargetAddress) -> None:
  277. if self.connection.closed:
  278. await self.on_frame(self, "status", b"relay unavailable")
  279. return
  280. self.connection.bind(self.session_id, self.stream_id, self._handle_frame)
  281. self.opened = True
  282. await self.on_frame(self, "status", b"ok")
  283. async def _handle_frame(self, _conn: RelayConnection, frame: Frame) -> None:
  284. if frame.kind == UDP_RECV:
  285. await self.on_frame(self, "data", frame.payload)
  286. async def send(self, data: bytes) -> None:
  287. if self.closed or self.connection.closed:
  288. return
  289. meta = encode_json({"host": self.target.host, "port": self.target.port, "family": self.target.family})
  290. payload = meta + data
  291. await self.connection.send(Frame(UDP_SEND, self.session_id, self.stream_id, 0, len(meta), payload))
  292. async def close(self) -> None:
  293. if self.closed:
  294. return
  295. self.closed = True
  296. self.connection.unbind(self.session_id, self.stream_id)
  297. @dataclass
  298. class UdpFlow:
  299. flow_id: int
  300. source: PeerAddress
  301. target: TargetAddress
  302. send_response: Callable[[PeerAddress, bytes], Awaitable[None]]
  303. paths: list[BasePath]
  304. winner: BasePath | None = None
  305. closed: bool = False
  306. last_activity: float = 0.0
  307. async def start(self) -> None:
  308. await asyncio.gather(*(path.open(self.target) for path in self.paths), return_exceptions=True)
  309. async def send(self, payload: bytes) -> None:
  310. self.last_activity = asyncio.get_running_loop().time()
  311. active = [path for path in self.paths if path.opened and not path.closed]
  312. if self.winner is None:
  313. await asyncio.gather(*(path.send(payload) for path in active), return_exceptions=True)
  314. elif not self.winner.closed:
  315. await self.winner.send(payload)
  316. async def handle_path(self, path: BasePath, event: str, payload: bytes | None) -> None:
  317. self.last_activity = asyncio.get_running_loop().time()
  318. if event == "data" and payload is not None:
  319. if self.winner is None:
  320. self.winner = path
  321. print(f"[edge] udp flow={self.flow_id} winner={path.name} target={self.target.host}:{self.target.port}")
  322. if path is self.winner:
  323. await self.send_response(self.source, payload)
  324. if event == "close":
  325. path.closed = True
  326. async def close(self) -> None:
  327. if self.closed:
  328. return
  329. self.closed = True
  330. await asyncio.gather(*(path.close() for path in self.paths), return_exceptions=True)
  331. class TransparentUdpListener:
  332. def __init__(self, edge: "TransparentEdge", family: int, bind_host: str, port: int) -> None:
  333. self.edge = edge
  334. self.family = family
  335. self.bind_host = bind_host
  336. self.port = port
  337. self.socket: socket.socket | None = None
  338. def start(self) -> None:
  339. sock = socket.socket(self.family, socket.SOCK_DGRAM)
  340. sock.setblocking(False)
  341. if self.family == socket.AF_INET:
  342. sock.setsockopt(socket.SOL_IP, IP_RECVORIGDSTADDR, 1)
  343. sock.bind((self.bind_host, self.port))
  344. else:
  345. sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  346. sock.setsockopt(socket.IPPROTO_IPV6, IPV6_RECVORIGDSTADDR, 1)
  347. sock.bind((self.bind_host, self.port, 0, 0))
  348. self.socket = sock
  349. asyncio.get_running_loop().add_reader(sock.fileno(), self._on_readable)
  350. print(f"[edge] transparent udp listening on {sock.getsockname()}")
  351. def _on_readable(self) -> None:
  352. assert self.socket is not None
  353. try:
  354. data, ancdata, _flags, src = self.socket.recvmsg(65535, 512)
  355. except BlockingIOError:
  356. return
  357. except Exception as exc:
  358. print(f"[edge] udp recv failed family={self.family} error={exc!r}")
  359. return
  360. original = None
  361. for level, ctype, cdata in ancdata:
  362. if self.family == socket.AF_INET and level == socket.SOL_IP and ctype == IP_RECVORIGDSTADDR:
  363. original = parse_sockaddr(cdata)
  364. break
  365. if self.family == socket.AF_INET6 and level == socket.IPPROTO_IPV6 and ctype == IPV6_RECVORIGDSTADDR:
  366. original = parse_sockaddr(cdata)
  367. break
  368. if original is None:
  369. print(f"[edge] udp missing original dst family={self.family} src={src}")
  370. return
  371. if self.family == socket.AF_INET:
  372. source = PeerAddress(host=src[0], port=src[1], family=socket.AF_INET)
  373. else:
  374. source = PeerAddress(host=src[0], port=src[1], family=socket.AF_INET6)
  375. asyncio.create_task(self.edge.handle_udp_datagram(source, original, data, self))
  376. async def send_response(self, source: PeerAddress, payload: bytes) -> None:
  377. assert self.socket is not None
  378. if source.family == socket.AF_INET:
  379. self.socket.sendto(payload, (source.host, source.port))
  380. else:
  381. self.socket.sendto(payload, (source.host, source.port, 0, 0))
  382. async def close(self) -> None:
  383. if self.socket is None:
  384. return
  385. asyncio.get_running_loop().remove_reader(self.socket.fileno())
  386. self.socket.close()
  387. self.socket = None
  388. class TransparentEdge:
  389. def __init__(self, listen_host: str, listen_port: int, config: Config) -> None:
  390. self.listen_host = listen_host
  391. self.listen_port = listen_port
  392. self.config = config
  393. self.manager = RelayManager(config)
  394. self.session_ids = itertools.count(1)
  395. self.stream_ids = itertools.count(1)
  396. self.udp_listeners: list[TransparentUdpListener] = []
  397. self.udp_flows: dict[tuple[PeerAddress, TargetAddress], UdpFlow] = {}
  398. self.udp_flow_ids = itertools.count(1)
  399. self.udp_gc_task: asyncio.Task | None = None
  400. async def start(self) -> None:
  401. await self.manager.start()
  402. print(f"[edge] relay snapshot: {self.manager.snapshot()}")
  403. server4 = await asyncio.start_server(self._accept, self.listen_host, self.listen_port, family=socket.AF_INET)
  404. sockets = [str(sock.getsockname()) for sock in server4.sockets or []]
  405. server6 = None
  406. if self.listen_host in ("::", "::1", "0.0.0.0", "127.0.0.1"):
  407. host6 = "::1" if self.listen_host == "127.0.0.1" else "::"
  408. try:
  409. server6 = await asyncio.start_server(self._accept, host6, self.listen_port, family=socket.AF_INET6)
  410. sockets.extend(str(sock.getsockname()) for sock in server6.sockets or [])
  411. except Exception as exc:
  412. print(f"[edge] ipv6 tcp listener skipped: {exc!r}")
  413. self._start_udp_listeners()
  414. self.udp_gc_task = asyncio.create_task(self._gc_udp_flows())
  415. print(f"[edge] transparent tcp listening on {', '.join(sockets)}")
  416. if server6 is None:
  417. async with server4:
  418. await server4.serve_forever()
  419. else:
  420. async with server4, server6:
  421. await asyncio.gather(server4.serve_forever(), server6.serve_forever())
  422. def _start_udp_listeners(self) -> None:
  423. binds = []
  424. if self.listen_host == "127.0.0.1":
  425. binds = [(socket.AF_INET, "127.0.0.1"), (socket.AF_INET6, "::1")]
  426. elif self.listen_host == "0.0.0.0":
  427. binds = [(socket.AF_INET, "0.0.0.0"), (socket.AF_INET6, "::")]
  428. else:
  429. family = socket.AF_INET6 if ":" in self.listen_host else socket.AF_INET
  430. binds = [(family, self.listen_host)]
  431. for family, host in binds:
  432. try:
  433. listener = TransparentUdpListener(self, family, host, self.listen_port)
  434. listener.start()
  435. self.udp_listeners.append(listener)
  436. except Exception as exc:
  437. print(f"[edge] udp listener skipped family={family} host={host} error={exc!r}")
  438. async def _accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  439. peer = writer.get_extra_info("peername")
  440. try:
  441. target = self._get_original_dst(writer)
  442. session_id = next(self.session_ids)
  443. session = TransparentSession(session_id=session_id, target=target, reader=reader, writer=writer, paths=[], warmup_bytes=self.config.tcp_warmup_bytes)
  444. paths: list[BasePath] = [DirectTcpPath(name="direct", on_frame=lambda path, event, payload, s=session: self._handle_tcp_session(s, path, event, payload))]
  445. for connection in self.manager.available():
  446. stream_id = next(self.stream_ids)
  447. 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))
  448. session.paths = paths
  449. print(f"[edge] accept peer={peer} session={session_id} target={target.host}:{target.port} candidates={[path.name for path in paths]}")
  450. await session.start()
  451. except Exception as exc:
  452. print(f"[edge] accept failed peer={peer} error={exc!r}")
  453. writer.close()
  454. with contextlib.suppress(Exception):
  455. await writer.wait_closed()
  456. async def _handle_tcp_session(self, session: TransparentSession, path: BasePath, event: str, payload: bytes | None) -> None:
  457. await session.handle_path(path, event, payload)
  458. def _get_original_dst(self, writer: asyncio.StreamWriter) -> TargetAddress:
  459. sock = writer.get_extra_info("socket")
  460. if sock is None:
  461. raise RuntimeError("socket unavailable")
  462. family = sock.family
  463. if family == socket.AF_INET:
  464. raw = sock.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16)
  465. return parse_sockaddr(raw)
  466. if family == socket.AF_INET6:
  467. raw = sock.getsockopt(socket.IPPROTO_IPV6, IP6T_SO_ORIGINAL_DST, 128)
  468. return parse_sockaddr(raw)
  469. raise RuntimeError(f"unsupported socket family={family}")
  470. async def handle_udp_datagram(self, source: PeerAddress, target: TargetAddress, payload: bytes, listener: TransparentUdpListener) -> None:
  471. key = (source, target)
  472. flow = self.udp_flows.get(key)
  473. if flow is None:
  474. flow_id = next(self.udp_flow_ids)
  475. 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)]
  476. for connection in self.manager.available():
  477. stream_id = next(self.stream_ids)
  478. 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))
  479. flow = UdpFlow(flow_id=flow_id, source=source, target=target, send_response=listener.send_response, paths=paths)
  480. self.udp_flows[key] = flow
  481. print(f"[edge] udp flow={flow_id} target={target.host}:{target.port} candidates={[path.name for path in paths]}")
  482. await flow.start()
  483. await flow.send(payload)
  484. async def _handle_udp_path(self, flow_id: int, path: BasePath, event: str, payload: bytes | None) -> None:
  485. for flow in list(self.udp_flows.values()):
  486. if flow.flow_id == flow_id:
  487. await flow.handle_path(path, event, payload)
  488. break
  489. async def _gc_udp_flows(self) -> None:
  490. loop = asyncio.get_running_loop()
  491. while True:
  492. await asyncio.sleep(30)
  493. now = loop.time()
  494. stale = [key for key, flow in self.udp_flows.items() if flow.last_activity and now - flow.last_activity > 120]
  495. for key in stale:
  496. flow = self.udp_flows.pop(key, None)
  497. if flow:
  498. await flow.close()