transparent_edge.py 30 KB

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