transparent_edge.py 36 KB

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