transparent_edge.py 37 KB

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