transparent_edge.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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. try:
  99. self.writer.write(data)
  100. await self.writer.drain()
  101. except (BrokenPipeError, ConnectionResetError, RuntimeError, OSError, asyncio.CancelledError) as exc:
  102. await self.close()
  103. raise ConnectionError("relay closed") from exc
  104. async def close(self) -> None:
  105. if self.closed:
  106. return
  107. self.closed = True
  108. if self.pump_task and self.pump_task is not asyncio.current_task():
  109. self.pump_task.cancel()
  110. with contextlib.suppress(Exception):
  111. await self.pump_task
  112. if self.writer:
  113. self.writer.close()
  114. with contextlib.suppress(Exception):
  115. await self.writer.wait_closed()
  116. class RelayTcpPath(BasePath):
  117. def __init__(self, name: str, on_frame: Callable[[BasePath, str, bytes | None], Awaitable[None]], connection: RelayConnection, session_id: int, stream_id: int) -> None:
  118. super().__init__(name, on_frame)
  119. self.connection = connection
  120. self.session_id = session_id
  121. self.stream_id = stream_id
  122. self.unbind_task: asyncio.Task | None = None
  123. async def open(self, target: TargetAddress) -> None:
  124. if self.connection.closed:
  125. await self.on_frame(self, "status", b"relay unavailable")
  126. return
  127. self.connection.bind(self.session_id, self.stream_id, self._handle_frame)
  128. try:
  129. 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})))
  130. except Exception as exc:
  131. self.connection.unbind(self.session_id, self.stream_id)
  132. await self.on_frame(self, "status", str(exc).encode())
  133. async def _handle_frame(self, _conn: RelayConnection, frame: Frame) -> None:
  134. if frame.kind == TCP_STATUS:
  135. if frame.packet_id == STATUS_OK:
  136. self.opened = True
  137. await self.on_frame(self, "status", b"ok")
  138. else:
  139. await self.on_frame(self, "status", frame.payload)
  140. return
  141. if frame.kind == TCP_DATA:
  142. await self.on_frame(self, "data", frame.payload)
  143. return
  144. if frame.kind == TCP_CLOSE:
  145. await self.on_frame(self, "close", None)
  146. async def send(self, data: bytes) -> None:
  147. if self.closed or self.connection.closed:
  148. return
  149. await self.connection.send(Frame(TCP_DATA, self.session_id, self.stream_id, 0, 0, data))
  150. async def close(self) -> None:
  151. if self.closed:
  152. return
  153. self.closed = True
  154. if self.unbind_task is None or self.unbind_task.done():
  155. self.unbind_task = asyncio.create_task(self._delayed_unbind())
  156. if not self.connection.closed:
  157. with contextlib.suppress(Exception):
  158. await self.connection.send(Frame(TCP_CLOSE, self.session_id, self.stream_id, 0, 0, b""))
  159. async def _delayed_unbind(self) -> None:
  160. await asyncio.sleep(0.5)
  161. self.connection.unbind(self.session_id, self.stream_id)
  162. @dataclass
  163. class TransparentSession:
  164. session_id: int
  165. target: TargetAddress
  166. reader: asyncio.StreamReader
  167. writer: asyncio.StreamWriter
  168. paths: list[BasePath]
  169. warmup_initial_bytes: int
  170. warmup_max_bytes: int
  171. loser_grace_ms: int
  172. stats: dict[str, int]
  173. target_stats: dict[tuple[str, int], dict[str, int]]
  174. family_stats: dict[str, dict[str, int]]
  175. opened_count: int = 0
  176. status_count: int = 0
  177. errors: list[str] = field(default_factory=list)
  178. winner: BasePath | None = None
  179. uplink_bytes: int = 0
  180. open_event: asyncio.Event = field(default_factory=asyncio.Event)
  181. winner_event: asyncio.Event = field(default_factory=asyncio.Event)
  182. closed: bool = False
  183. pump_task: asyncio.Task | None = None
  184. loser_close_task: asyncio.Task | None = None
  185. warmup_bytes: int = 0
  186. open_tasks: list[asyncio.Task] = field(default_factory=list)
  187. @staticmethod
  188. def _stability_score(stats: dict[str, int]) -> float:
  189. total = sum(stats.values())
  190. if total < 2:
  191. return 0.0
  192. dominant = max(stats.values())
  193. confidence = min(1.0, total / 20.0)
  194. return max(0.0, ((dominant / total) - 0.5) * 2.0 * confidence)
  195. def _effective_warmup_bytes(self) -> int:
  196. low = max(0, self.warmup_initial_bytes)
  197. high = max(low, self.warmup_max_bytes)
  198. key = (self.target.host, self.target.port)
  199. target_stats = self.target_stats.get(key, {})
  200. family_key = "ipv6" if self.target.family == socket.AF_INET6 else "ipv4"
  201. family_stats = self.family_stats.get(family_key, {})
  202. score = max(self._stability_score(self.stats), self._stability_score(target_stats), self._stability_score(family_stats))
  203. return low + int((high - low) * score)
  204. def _record_win(self, winner: BasePath) -> None:
  205. self.stats[winner.name] = self.stats.get(winner.name, 0) + 1
  206. key = (self.target.host, self.target.port)
  207. target_stats = self.target_stats.setdefault(key, {})
  208. target_stats[winner.name] = target_stats.get(winner.name, 0) + 1
  209. family_key = "ipv6" if self.target.family == socket.AF_INET6 else "ipv4"
  210. family_stats = self.family_stats.setdefault(family_key, {})
  211. family_stats[winner.name] = family_stats.get(winner.name, 0) + 1
  212. direct_wins = grouped_total(self.stats, "direct")
  213. relay_wins = sum(count for name, count in self.stats.items() if winner_group(name) != "direct")
  214. target_direct = grouped_total(target_stats, "direct")
  215. target_relay = sum(count for name, count in target_stats.items() if winner_group(name) != "direct")
  216. family_direct = grouped_total(family_stats, "direct")
  217. family_relay = sum(count for name, count in family_stats.items() if winner_group(name) != "direct")
  218. relay_detail = ", ".join(f"{name}={count}" for name, count in sorted(self.stats.items()) if winner_group(name) != "direct") or "none"
  219. target_detail = ", ".join(f"{name}={count}" for name, count in sorted(target_stats.items()) if winner_group(name) != "direct") or "none"
  220. target_pref = "relay" if target_relay > target_direct else "direct"
  221. family_pref = "relay" if family_relay > family_direct else "direct"
  222. 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}")
  223. async def start(self) -> None:
  224. self.warmup_bytes = self._effective_warmup_bytes()
  225. self.open_tasks = [asyncio.create_task(path.open(self.target)) for path in self.paths]
  226. try:
  227. await asyncio.wait_for(self.open_event.wait(), timeout=15)
  228. except Exception:
  229. for task in self.open_tasks:
  230. if not task.done():
  231. task.cancel()
  232. await asyncio.gather(*self.open_tasks, return_exceptions=True)
  233. self.open_tasks.clear()
  234. raise
  235. if self.opened_count == 0:
  236. raise ConnectionError(self.errors[0] if self.errors else "all paths failed")
  237. self.pump_task = asyncio.create_task(self._pump_local())
  238. async def _pump_local(self) -> None:
  239. try:
  240. while True:
  241. chunk = await self.reader.read(65536)
  242. if not chunk:
  243. break
  244. self.uplink_bytes += len(chunk)
  245. active = [path for path in self.paths if path.opened and not path.closed]
  246. if not active:
  247. break
  248. if self.uplink_bytes <= self.warmup_bytes:
  249. await asyncio.gather(*(path.send(chunk) for path in active), return_exceptions=True)
  250. else:
  251. if self.winner is None:
  252. await self.winner_event.wait()
  253. if self.winner:
  254. await self.winner.send(chunk)
  255. except Exception:
  256. pass
  257. finally:
  258. await self.close()
  259. async def handle_path(self, path: BasePath, event: str, payload: bytes | None) -> None:
  260. if self.closed:
  261. return
  262. if event == "status":
  263. self.status_count += 1
  264. if payload == b"ok":
  265. self.opened_count += 1
  266. elif payload is not None:
  267. self.errors.append(payload.decode("utf-8", errors="replace"))
  268. if self.opened_count > 0 or self.status_count == len(self.paths):
  269. self.open_event.set()
  270. return
  271. if event == "data":
  272. if self.winner is None:
  273. self.winner = path
  274. self._record_win(path)
  275. self.winner_event.set()
  276. if self.loser_grace_ms > 0:
  277. self.loser_close_task = asyncio.create_task(self._close_losers_after_grace(path))
  278. else:
  279. await self._close_losers(path)
  280. if path is self.winner and payload is not None:
  281. self.writer.write(payload)
  282. await self.writer.drain()
  283. return
  284. if event == "close":
  285. path.closed = True
  286. if self.winner is None:
  287. remaining = [candidate for candidate in self.paths if candidate.opened and not candidate.closed]
  288. if not remaining:
  289. await self.close()
  290. elif path is self.winner:
  291. await self.close()
  292. async def _close_losers(self, winner: BasePath) -> None:
  293. await asyncio.gather(*(path.close() for path in self.paths if path is not winner), return_exceptions=True)
  294. async def _close_losers_after_grace(self, winner: BasePath) -> None:
  295. await asyncio.sleep(self.loser_grace_ms / 1000)
  296. if not self.closed:
  297. await self._close_losers(winner)
  298. async def close(self) -> None:
  299. if self.closed:
  300. return
  301. self.closed = True
  302. print(f"[edge] session={self.session_id} closed target={self.target.host}:{self.target.port}")
  303. if self.pump_task and self.pump_task is not asyncio.current_task():
  304. self.pump_task.cancel()
  305. with contextlib.suppress(Exception):
  306. await self.pump_task
  307. if self.loser_close_task and self.loser_close_task is not asyncio.current_task():
  308. self.loser_close_task.cancel()
  309. with contextlib.suppress(Exception):
  310. await self.loser_close_task
  311. pending_open_tasks = [task for task in self.open_tasks if task is not asyncio.current_task() and not task.done()]
  312. for task in pending_open_tasks:
  313. task.cancel()
  314. if pending_open_tasks:
  315. with contextlib.suppress(Exception):
  316. await asyncio.gather(*pending_open_tasks, return_exceptions=True)
  317. await asyncio.gather(*(path.close() for path in self.paths), return_exceptions=True)
  318. self.writer.close()
  319. with contextlib.suppress(Exception):
  320. await self.writer.wait_closed()
  321. class DirectUdpPath(BasePath):
  322. def __init__(self, name: str, on_frame: Callable[[BasePath, str, bytes | None], Awaitable[None]], target: TargetAddress) -> None:
  323. super().__init__(name, on_frame)
  324. self.target = target
  325. self.socket: socket.socket | None = None
  326. self.read_task: asyncio.Task | None = None
  327. async def open(self, _target: TargetAddress) -> None:
  328. try:
  329. family = socket.AF_INET6 if self.target.family == socket.AF_INET6 else socket.AF_INET
  330. self.socket = socket.socket(family, socket.SOCK_DGRAM)
  331. self.socket.setblocking(False)
  332. await asyncio.get_running_loop().sock_connect(self.socket, (self.target.host, self.target.port))
  333. self.opened = True
  334. self.read_task = asyncio.create_task(self._pump())
  335. await self.on_frame(self, "status", b"ok")
  336. except Exception as exc:
  337. await self.on_frame(self, "status", str(exc).encode())
  338. async def _pump(self) -> None:
  339. assert self.socket is not None
  340. loop = asyncio.get_running_loop()
  341. try:
  342. while True:
  343. data = await loop.sock_recv(self.socket, 65535)
  344. if not data:
  345. break
  346. await self.on_frame(self, "data", data)
  347. except Exception:
  348. pass
  349. finally:
  350. await self.on_frame(self, "close", None)
  351. async def send(self, data: bytes) -> None:
  352. if self.closed or self.socket is None:
  353. return
  354. await asyncio.get_running_loop().sock_sendall(self.socket, data)
  355. async def close(self) -> None:
  356. if self.closed:
  357. return
  358. self.closed = True
  359. if self.read_task and self.read_task is not asyncio.current_task():
  360. self.read_task.cancel()
  361. with contextlib.suppress(Exception):
  362. await self.read_task
  363. if self.socket:
  364. self.socket.close()
  365. class RelayUdpPath(BasePath):
  366. 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:
  367. super().__init__(name, on_frame)
  368. self.connection = connection
  369. self.session_id = session_id
  370. self.stream_id = stream_id
  371. self.target = target
  372. self.unbind_task: asyncio.Task | None = None
  373. async def open(self, _target: TargetAddress) -> None:
  374. if self.connection.closed:
  375. await self.on_frame(self, "status", b"relay unavailable")
  376. return
  377. self.connection.bind(self.session_id, self.stream_id, self._handle_frame)
  378. try:
  379. self.opened = True
  380. await self.on_frame(self, "status", b"ok")
  381. except Exception:
  382. self.connection.unbind(self.session_id, self.stream_id)
  383. self.closed = True
  384. raise
  385. async def _handle_frame(self, _conn: RelayConnection, frame: Frame) -> None:
  386. if frame.kind == UDP_RECV:
  387. await self.on_frame(self, "data", frame.payload)
  388. elif frame.kind == TCP_STATUS and frame.packet_id != STATUS_OK:
  389. await self.on_frame(self, "status", frame.payload or b"udp relay error")
  390. async def send(self, data: bytes) -> None:
  391. if self.closed or self.connection.closed:
  392. return
  393. meta = encode_json({"host": self.target.host, "port": self.target.port, "family": self.target.family})
  394. payload = meta + data
  395. try:
  396. await self.connection.send(Frame(UDP_SEND, self.session_id, self.stream_id, 0, len(meta), payload))
  397. except Exception:
  398. self.closed = True
  399. raise
  400. async def close(self) -> None:
  401. if self.closed:
  402. return
  403. self.closed = True
  404. if self.unbind_task is None or self.unbind_task.done():
  405. self.unbind_task = asyncio.create_task(self._delayed_unbind())
  406. async def _delayed_unbind(self) -> None:
  407. await asyncio.sleep(0.5)
  408. self.connection.unbind(self.session_id, self.stream_id)
  409. @dataclass
  410. class UdpFlow:
  411. flow_id: int
  412. source: PeerAddress
  413. target: TargetAddress
  414. send_response: Callable[[PeerAddress, bytes], Awaitable[None]]
  415. paths: list[BasePath]
  416. redundancy: int = 0
  417. always_broadcast: bool = True
  418. copy_interval_ms: int = 0
  419. winner: BasePath | None = None
  420. closed: bool = False
  421. last_activity: float = 0.0
  422. packets_sent: int = 0
  423. packets_received: int = 0
  424. duplicate_responses: int = 0
  425. send_task: asyncio.Task | None = None
  426. async def start(self) -> None:
  427. await asyncio.gather(*(path.open(self.target) for path in self.paths), return_exceptions=True)
  428. async def send(self, payload: bytes) -> None:
  429. self.last_activity = asyncio.get_running_loop().time()
  430. self.packets_sent += 1
  431. active = [path for path in self.paths if path.opened and not path.closed]
  432. if not active:
  433. return
  434. copies = max(1, self.redundancy + 1)
  435. targets = active if self.always_broadcast or self.winner is None or self.winner.closed else [self.winner]
  436. for attempt in range(copies):
  437. await asyncio.gather(*(path.send(payload) for path in targets), return_exceptions=True)
  438. if attempt + 1 < copies and self.copy_interval_ms > 0:
  439. await asyncio.sleep(self.copy_interval_ms / 1000)
  440. async def handle_path(self, path: BasePath, event: str, payload: bytes | None) -> None:
  441. self.last_activity = asyncio.get_running_loop().time()
  442. if event == "data" and payload is not None:
  443. self.packets_received += 1
  444. if self.winner is None:
  445. self.winner = path
  446. mode = "redundant" if self.redundancy > 0 else "single"
  447. print(f"[edge] udp flow={self.flow_id} winner={path.name} target={self.target.host}:{self.target.port} mode={mode} candidates={len(self.paths)}")
  448. elif path is not self.winner:
  449. self.duplicate_responses += 1
  450. if path is self.winner:
  451. await self.send_response(self.source, payload)
  452. if event == "close":
  453. path.closed = True
  454. if path is self.winner:
  455. remaining = [candidate for candidate in self.paths if candidate.opened and not candidate.closed]
  456. self.winner = remaining[0] if remaining else None
  457. async def close(self) -> None:
  458. if self.closed:
  459. return
  460. self.closed = True
  461. if self.send_task and self.send_task is not asyncio.current_task():
  462. self.send_task.cancel()
  463. with contextlib.suppress(Exception):
  464. await self.send_task
  465. print(
  466. f"[edge] udp flow={self.flow_id} closed target={self.target.host}:{self.target.port} "
  467. f"sent={self.packets_sent} received={self.packets_received} dup={self.duplicate_responses}"
  468. )
  469. await asyncio.gather(*(path.close() for path in self.paths), return_exceptions=True)
  470. class TransparentUdpListener:
  471. def __init__(self, edge: "TransparentEdge", family: int, bind_host: str, port: int) -> None:
  472. self.edge = edge
  473. self.family = family
  474. self.bind_host = bind_host
  475. self.port = port
  476. self.socket: socket.socket | None = None
  477. self.udp_packets_received = 0
  478. self.udp_recv_errors = 0
  479. self.udp_parse_errors = 0
  480. self.udp_missing_original = 0
  481. self.udp_self_loop_skipped = 0
  482. self.udp_flows_created = 0
  483. self.last_summary_at = 0.0
  484. def start(self) -> None:
  485. sock = socket.socket(self.family, socket.SOCK_DGRAM)
  486. sock.setblocking(False)
  487. if self.family == socket.AF_INET:
  488. sock.setsockopt(socket.SOL_IP, IP_RECVORIGDSTADDR, 1)
  489. sock.bind((self.bind_host, self.port))
  490. else:
  491. sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  492. sock.setsockopt(socket.IPPROTO_IPV6, IPV6_RECVORIGDSTADDR, 1)
  493. sock.bind((self.bind_host, self.port, 0, 0))
  494. self.socket = sock
  495. asyncio.get_running_loop().add_reader(sock.fileno(), self._on_readable)
  496. print(f"[edge] transparent udp listening on {sock.getsockname()}")
  497. def _log_udp_summary(self, force: bool = False) -> None:
  498. now = asyncio.get_running_loop().time()
  499. if not force and now - self.last_summary_at < 10:
  500. return
  501. self.last_summary_at = now
  502. print(
  503. f"[edge] udp summary family={self.family} bind={self.bind_host}:{self.port} "
  504. f"received={self.udp_packets_received} flows={self.udp_flows_created} "
  505. f"self_loop={self.udp_self_loop_skipped} missing_original={self.udp_missing_original} "
  506. f"parse_error={self.udp_parse_errors} recv_error={self.udp_recv_errors}"
  507. )
  508. def _on_readable(self) -> None:
  509. assert self.socket is not None
  510. try:
  511. data, ancdata, _flags, src = self.socket.recvmsg(65535, 512)
  512. except BlockingIOError:
  513. return
  514. except Exception as exc:
  515. self.udp_recv_errors += 1
  516. print(f"[edge] udp recvmsg error family={self.family} error={exc!r}")
  517. self._log_udp_summary(force=True)
  518. return
  519. self.udp_packets_received += 1
  520. original = None
  521. for level, ctype, cdata in ancdata:
  522. if self.family == socket.AF_INET and level == socket.SOL_IP and ctype == IP_RECVORIGDSTADDR:
  523. try:
  524. original = parse_sockaddr(cdata)
  525. except Exception as exc:
  526. self.udp_parse_errors += 1
  527. print(f"[edge] udp parse original dst error family={self.family} src={src} error={exc!r} raw_len={len(cdata)}")
  528. self._log_udp_summary(force=True)
  529. return
  530. break
  531. if self.family == socket.AF_INET6 and level == socket.IPPROTO_IPV6 and ctype == IPV6_RECVORIGDSTADDR:
  532. try:
  533. original = parse_sockaddr(cdata)
  534. except Exception as exc:
  535. self.udp_parse_errors += 1
  536. print(f"[edge] udp parse original dst error family={self.family} src={src} error={exc!r} raw_len={len(cdata)}")
  537. self._log_udp_summary(force=True)
  538. return
  539. break
  540. if original is None:
  541. self.udp_missing_original += 1
  542. self._log_udp_summary()
  543. return
  544. if self.family == socket.AF_INET:
  545. source = PeerAddress(host=src[0], port=src[1], family=socket.AF_INET)
  546. else:
  547. source = PeerAddress(host=src[0], port=src[1], family=socket.AF_INET6)
  548. if original.port == self.port and (original.host in ("127.0.0.1", "::1") or original.host == self.bind_host):
  549. self.udp_self_loop_skipped += 1
  550. print(
  551. f"[edge] udp self_loop family={self.family} src={source.host}:{source.port} "
  552. f"original={original.host}:{original.port} size={len(data)}"
  553. )
  554. self._log_udp_summary()
  555. return
  556. asyncio.create_task(self.edge.handle_udp_datagram(source, original, data, self))
  557. async def send_response(self, source: PeerAddress, payload: bytes) -> None:
  558. assert self.socket is not None
  559. if source.family == socket.AF_INET:
  560. self.socket.sendto(payload, (source.host, source.port))
  561. else:
  562. self.socket.sendto(payload, (source.host, source.port, 0, 0))
  563. async def close(self) -> None:
  564. if self.socket is None:
  565. return
  566. asyncio.get_running_loop().remove_reader(self.socket.fileno())
  567. self.socket.close()
  568. self.socket = None
  569. class TransparentEdge:
  570. def __init__(self, listen_host: str, listen_port: int, config: Config, enable_udp: bool = False, kernel_mode: str = "auto") -> None:
  571. self.listen_host = listen_host
  572. self.listen_port = listen_port
  573. self.config = config
  574. self.enable_udp = enable_udp
  575. self.kernel_mode = self._resolve_kernel_mode(kernel_mode, config.kernel_mode)
  576. self.manager = RelayManager(config)
  577. self.session_ids = itertools.count(1)
  578. self.stream_ids = itertools.count(1)
  579. self.udp_listeners: list[TransparentUdpListener] = []
  580. self.udp_flows: dict[tuple[PeerAddress, TargetAddress], UdpFlow] = {}
  581. self.udp_flow_ids = itertools.count(1)
  582. self.udp_gc_task: asyncio.Task | None = None
  583. self.tcp_win_counts: dict[str, int] = {}
  584. self.tcp_target_wins: dict[tuple[str, int], dict[str, int]] = {}
  585. self.tcp_family_wins: dict[str, dict[str, int]] = {"ipv4": {}, "ipv6": {}}
  586. def _resolve_kernel_mode(self, cli_kernel_mode: str, config_kernel_mode: str) -> str:
  587. mode = cli_kernel_mode if cli_kernel_mode != "auto" else config_kernel_mode
  588. if mode != "auto":
  589. return mode
  590. try:
  591. if Path("/etc/os-release").exists() and 'VERSION_ID="24' in Path("/etc/os-release").read_text(errors="ignore"):
  592. return "24"
  593. except Exception:
  594. pass
  595. try:
  596. release = os.uname().release
  597. if release.startswith("6."):
  598. return "24"
  599. except Exception:
  600. pass
  601. return "20"
  602. async def start(self) -> None:
  603. if self.kernel_mode == "24":
  604. if self.config.direct_open_timeout == 10.0:
  605. self.config.direct_open_timeout = 6.0
  606. if self.config.relay_open_timeout == 10.0:
  607. self.config.relay_open_timeout = 6.0
  608. if self.config.tcp_connect_happy_eyeballs_delay is None:
  609. self.config.tcp_connect_happy_eyeballs_delay = 0.25
  610. await self.manager.start()
  611. print(f"[edge] kernel_mode={self.kernel_mode} relay snapshot: {self.manager.snapshot()}")
  612. server4 = await asyncio.start_server(self._accept, self.listen_host, self.listen_port, family=socket.AF_INET)
  613. sockets = [str(sock.getsockname()) for sock in server4.sockets or []]
  614. server6 = None
  615. if self.listen_host in ("::", "::1", "0.0.0.0", "127.0.0.1"):
  616. host6 = "::1" if self.listen_host == "127.0.0.1" else "::"
  617. try:
  618. server6 = await asyncio.start_server(self._accept, host6, self.listen_port, family=socket.AF_INET6)
  619. sockets.extend(str(sock.getsockname()) for sock in server6.sockets or [])
  620. except Exception as exc:
  621. print(f"[edge] ipv6 tcp listener skipped: {exc!r}")
  622. if self.enable_udp:
  623. self._start_udp_listeners()
  624. self.udp_gc_task = asyncio.create_task(self._gc_udp_flows())
  625. print(f"[edge] transparent tcp listening on {', '.join(sockets)}")
  626. if server6 is None:
  627. async with server4:
  628. await server4.serve_forever()
  629. else:
  630. async with server4, server6:
  631. await asyncio.gather(server4.serve_forever(), server6.serve_forever())
  632. def _direct_redundancy_for_target(self, target: TargetAddress) -> int:
  633. base = self.config.direct_redundancy
  634. if target.family == socket.AF_INET6 and self.config.direct_redundancy_v6 is not None:
  635. base = self.config.direct_redundancy_v6
  636. elif target.family == socket.AF_INET and self.config.direct_redundancy_v4 is not None:
  637. base = self.config.direct_redundancy_v4
  638. base = max(1, min(base, self.config.direct_max_redundancy))
  639. target_stats = self.tcp_target_wins.get((target.host, target.port), {})
  640. family_key = "ipv6" if target.family == socket.AF_INET6 else "ipv4"
  641. family_stats = self.tcp_family_wins.get(family_key, {})
  642. target_prefers_relay = sum(count for name, count in target_stats.items() if winner_group(name) != "direct") > grouped_total(target_stats, "direct")
  643. family_prefers_relay = sum(count for name, count in family_stats.items() if winner_group(name) != "direct") > grouped_total(family_stats, "direct")
  644. if target_prefers_relay or family_prefers_relay:
  645. return min(self.config.direct_max_redundancy, base + 1)
  646. return base
  647. def _build_direct_paths(self, session: TransparentSession) -> list[BasePath]:
  648. count = self._direct_redundancy_for_target(session.target)
  649. return [
  650. DirectTcpPath(
  651. name=f"direct-{index + 1}" if count > 1 else "direct",
  652. on_frame=lambda path, event, payload, s=session: self._handle_tcp_session(s, path, event, payload),
  653. open_timeout=self.config.direct_open_timeout,
  654. happy_eyeballs_delay=self.config.tcp_connect_happy_eyeballs_delay,
  655. tcp_nodelay=self.config.relay_tcp_nodelay,
  656. )
  657. for index in range(count)
  658. ]
  659. def _build_udp_direct_paths(self, target: TargetAddress, flow_id: int) -> list[BasePath]:
  660. count = max(1, self.config.udp_direct_redundancy)
  661. if target.family == socket.AF_INET6 and self.config.udp_direct_redundancy_v6 is not None:
  662. count = max(1, self.config.udp_direct_redundancy_v6)
  663. elif target.family == socket.AF_INET and self.config.udp_direct_redundancy_v4 is not None:
  664. count = max(1, self.config.udp_direct_redundancy_v4)
  665. return [
  666. DirectUdpPath(
  667. name=f"direct-{index + 1}" if count > 1 else "direct",
  668. on_frame=lambda path, event, data, fid=flow_id: self._handle_udp_path(fid, path, event, data),
  669. target=target,
  670. )
  671. for index in range(count)
  672. ]
  673. def _start_udp_listeners(self) -> None:
  674. binds = []
  675. if self.listen_host == "127.0.0.1":
  676. binds = [(socket.AF_INET, "127.0.0.1"), (socket.AF_INET6, "::1")]
  677. elif self.listen_host == "0.0.0.0":
  678. binds = [(socket.AF_INET, "0.0.0.0"), (socket.AF_INET6, "::")]
  679. else:
  680. family = socket.AF_INET6 if ":" in self.listen_host else socket.AF_INET
  681. binds = [(family, self.listen_host)]
  682. for family, host in binds:
  683. try:
  684. listener = TransparentUdpListener(self, family, host, self.listen_port)
  685. listener.start()
  686. self.udp_listeners.append(listener)
  687. except Exception as exc:
  688. print(f"[edge] udp listener skipped family={family} host={host} error={exc!r}")
  689. async def _accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  690. peer = writer.get_extra_info("peername")
  691. try:
  692. target = self._get_original_dst(writer)
  693. session_id = next(self.session_ids)
  694. session = TransparentSession(session_id=session_id, target=target, reader=reader, writer=writer, paths=[], warmup_initial_bytes=self.config.tcp_warmup_initial_bytes, warmup_max_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)
  695. paths: list[BasePath] = self._build_direct_paths(session)
  696. for connection in self.manager.available():
  697. stream_id = next(self.stream_ids)
  698. 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))
  699. session.paths = paths
  700. print(f"[edge] accept peer={peer} session={session_id} target={target.host}:{target.port} candidates={[path.name for path in paths]}")
  701. await session.start()
  702. except Exception as exc:
  703. print(f"[edge] accept failed peer={peer} error={exc!r}")
  704. writer.close()
  705. with contextlib.suppress(Exception):
  706. await writer.wait_closed()
  707. async def _handle_tcp_session(self, session: TransparentSession, path: BasePath, event: str, payload: bytes | None) -> None:
  708. await session.handle_path(path, event, payload)
  709. def _get_original_dst(self, writer: asyncio.StreamWriter) -> TargetAddress:
  710. sock = writer.get_extra_info("socket")
  711. if sock is None:
  712. raise RuntimeError("socket unavailable")
  713. family = sock.family
  714. if family == socket.AF_INET:
  715. raw = sock.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16)
  716. return parse_sockaddr(raw)
  717. if family == socket.AF_INET6:
  718. raw = sock.getsockopt(socket.IPPROTO_IPV6, IP6T_SO_ORIGINAL_DST, 128)
  719. return parse_sockaddr(raw)
  720. raise RuntimeError(f"unsupported socket family={family}")
  721. async def handle_udp_datagram(self, source: PeerAddress, target: TargetAddress, payload: bytes, listener: TransparentUdpListener) -> None:
  722. if not self.enable_udp:
  723. return
  724. if target.port == self.listen_port and target.host in ("127.0.0.1", "::1", self.listen_host):
  725. return
  726. key = (source, target)
  727. flow = self.udp_flows.get(key)
  728. if flow is None:
  729. flow_id = next(self.udp_flow_ids)
  730. paths: list[BasePath] = self._build_udp_direct_paths(target, flow_id)
  731. for connection in self.manager.available():
  732. stream_id = next(self.stream_ids)
  733. 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))
  734. flow = UdpFlow(
  735. flow_id=flow_id,
  736. source=source,
  737. target=target,
  738. send_response=listener.send_response,
  739. paths=paths,
  740. redundancy=self.config.udp_redundancy,
  741. always_broadcast=self.config.udp_always_broadcast,
  742. copy_interval_ms=self.config.udp_copy_interval_ms,
  743. )
  744. self.udp_flows[key] = flow
  745. listener.udp_flows_created += 1
  746. listener._log_udp_summary(force=True)
  747. print(f"[edge] udp flow={flow_id} source={source.host}:{source.port} target={target.host}:{target.port} redundancy={self.config.udp_redundancy} direct_redundancy={self.config.udp_direct_redundancy} always_broadcast={self.config.udp_always_broadcast} candidates={[path.name for path in paths]}")
  748. await flow.start()
  749. await flow.send(payload)
  750. async def _handle_udp_path(self, flow_id: int, path: BasePath, event: str, payload: bytes | None) -> None:
  751. for flow in list(self.udp_flows.values()):
  752. if flow.flow_id == flow_id:
  753. await flow.handle_path(path, event, payload)
  754. break
  755. async def _gc_udp_flows(self) -> None:
  756. loop = asyncio.get_running_loop()
  757. while True:
  758. await asyncio.sleep(30)
  759. now = loop.time()
  760. stale = [key for key, flow in self.udp_flows.items() if flow.last_activity and now - flow.last_activity > 120]
  761. for key in stale:
  762. flow = self.udp_flows.pop(key, None)
  763. if flow:
  764. await flow.close()