transparent_edge.py 36 KB

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