socks_edge.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. from __future__ import annotations
  2. import asyncio
  3. import contextlib
  4. import itertools
  5. import socket
  6. import struct
  7. from dataclasses import dataclass, field
  8. from typing import Dict
  9. from .config import Config, RelayNode
  10. from .protocol import AUTH, STATUS_OK, TCP_CLOSE, TCP_DATA, TCP_OPEN, TCP_STATUS, UDP_RECV, UDP_SEND, Frame, decode_json, encode_json, read_frame, write_frame
  11. from .scheduler import Scheduler
  12. SOCKS_VERSION = 5
  13. async def read_exact(reader: asyncio.StreamReader, size: int) -> bytes:
  14. return await reader.readexactly(size)
  15. @dataclass(eq=False)
  16. class RelayLink:
  17. node: RelayNode
  18. reader: asyncio.StreamReader
  19. writer: asyncio.StreamWriter
  20. pump: asyncio.Task | None = None
  21. closed_event: asyncio.Event = field(default_factory=asyncio.Event)
  22. maintain_task: asyncio.Task | None = None
  23. tcp_sessions: Dict[tuple[int, int], "TcpRaceSession"] = field(default_factory=dict)
  24. udp_server: "UdpAssociateServer | None" = None
  25. closed: bool = False
  26. async def start(self) -> None:
  27. await write_frame(self.writer, Frame(AUTH, 0, 0, 0, 0, encode_json({"token": self.node.token})))
  28. frame = await read_frame(self.reader)
  29. if frame.kind != AUTH or frame.packet_id != STATUS_OK:
  30. raise ConnectionError(f"relay auth failed: {self.node.name}")
  31. self.closed = False
  32. self.closed_event.clear()
  33. self.pump = asyncio.create_task(self._pump())
  34. async def _pump(self) -> None:
  35. try:
  36. while True:
  37. frame = await read_frame(self.reader)
  38. key = (frame.session_id, frame.stream_id)
  39. if frame.kind in (TCP_STATUS, TCP_DATA, TCP_CLOSE):
  40. session = self.tcp_sessions.get(key)
  41. if session:
  42. await session.handle_frame(self, frame)
  43. elif frame.kind == UDP_RECV and self.udp_server:
  44. await self.udp_server.handle_from_relay(frame, self)
  45. except (asyncio.IncompleteReadError, ConnectionResetError, BrokenPipeError, OSError):
  46. pass
  47. except Exception:
  48. pass
  49. finally:
  50. await self.close()
  51. async def send(self, frame: Frame) -> None:
  52. if self.closed:
  53. raise ConnectionError(f"relay closed: {self.node.name}")
  54. try:
  55. await write_frame(self.writer, frame)
  56. except (BrokenPipeError, ConnectionResetError, RuntimeError, OSError, asyncio.CancelledError) as exc:
  57. await self.close()
  58. raise ConnectionError(f"relay closed: {self.node.name}") from exc
  59. async def close(self) -> None:
  60. if self.closed:
  61. return
  62. self.closed = True
  63. self.closed_event.set()
  64. if self.pump and self.pump is not asyncio.current_task():
  65. self.pump.cancel()
  66. with contextlib.suppress(Exception):
  67. await self.pump
  68. self.writer.close()
  69. with contextlib.suppress(Exception):
  70. await self.writer.wait_closed()
  71. @dataclass
  72. class UdpFlowState:
  73. flow_id: int
  74. client_addr: tuple[str, int]
  75. target_host: str
  76. target_port: int
  77. created_at: float
  78. last_activity: float
  79. packets_sent: int = 0
  80. packets_received: int = 0
  81. duplicate_responses: int = 0
  82. winner_name: str | None = None
  83. candidate_names: tuple[str, ...] = ()
  84. link_streams: dict[str, int] = field(default_factory=dict)
  85. initialized_links: set[str] = field(default_factory=set)
  86. direct_sockets: dict[str, socket.socket] = field(default_factory=dict)
  87. direct_tasks: dict[str, asyncio.Task] = field(default_factory=dict)
  88. direct_failures: set[str] = field(default_factory=set)
  89. relay_failures: dict[str, int] = field(default_factory=dict)
  90. relay_error_seen: set[str] = field(default_factory=set)
  91. path_last_seen: dict[str, float] = field(default_factory=dict)
  92. def touch(self, now: float) -> None:
  93. self.last_activity = now
  94. @dataclass
  95. class TcpRaceSession:
  96. session_id: int
  97. stream_id: int
  98. target_host: str
  99. target_port: int
  100. local_reader: asyncio.StreamReader
  101. local_writer: asyncio.StreamWriter
  102. links: list[RelayLink]
  103. warmup_bytes: int
  104. winning_link: RelayLink | None = None
  105. winner_name: str | None = None
  106. opened: int = 0
  107. open_errors: list[str] = field(default_factory=list)
  108. uplink_bytes: int = 0
  109. closed: bool = False
  110. open_event: asyncio.Event = field(default_factory=asyncio.Event)
  111. winner_event: asyncio.Event = field(default_factory=asyncio.Event)
  112. pump_task: asyncio.Task | None = None
  113. win_counts: Dict[str, int] = field(default_factory=dict)
  114. async def start(self) -> None:
  115. meta = encode_json({"host": self.target_host, "port": self.target_port})
  116. for link in self.links:
  117. link.tcp_sessions[(self.session_id, self.stream_id)] = self
  118. await link.send(Frame(TCP_OPEN, self.session_id, self.stream_id, 0, 0, meta))
  119. await asyncio.wait_for(self.open_event.wait(), timeout=10)
  120. if self.opened == 0:
  121. raise ConnectionError(self.open_errors[0] if self.open_errors else "all relays failed")
  122. self.pump_task = asyncio.create_task(self._pump_local())
  123. async def _pump_local(self) -> None:
  124. try:
  125. while True:
  126. chunk = await self.local_reader.read(65536)
  127. if not chunk:
  128. break
  129. self.uplink_bytes += len(chunk)
  130. if self.winning_link is None and self.uplink_bytes <= self.warmup_bytes:
  131. await asyncio.gather(*(link.send(Frame(TCP_DATA, self.session_id, self.stream_id, 0, 0, chunk)) for link in self.links if not link.closed), return_exceptions=True)
  132. else:
  133. if self.winning_link is None:
  134. await self.winner_event.wait()
  135. if self.winning_link:
  136. await self.winning_link.send(Frame(TCP_DATA, self.session_id, self.stream_id, 0, 0, chunk))
  137. except Exception:
  138. pass
  139. finally:
  140. await self.close()
  141. async def handle_frame(self, link: RelayLink, frame: Frame) -> None:
  142. if self.closed:
  143. return
  144. if frame.kind == TCP_STATUS:
  145. if frame.packet_id == STATUS_OK:
  146. self.opened += 1
  147. else:
  148. self.open_errors.append(frame.payload.decode("utf-8", errors="replace"))
  149. if self.opened > 0 or len(self.open_errors) == len(self.links):
  150. self.open_event.set()
  151. return
  152. if frame.kind == TCP_DATA:
  153. if self.winning_link is None:
  154. self.winning_link = link
  155. self.winner_name = link.node.name
  156. self.win_counts[link.node.name] = self.win_counts.get(link.node.name, 0) + 1
  157. node_total = self.win_counts[link.node.name]
  158. relay_detail = ", ".join(f"{name}={count}" for name, count in sorted(self.win_counts.items())) or "none"
  159. print(f"[edge] tcp win session={self.session_id} target={self.target_host}:{self.target_port} winner={link.node.name} node_total={node_total} win_breakdown={relay_detail}")
  160. self.winner_event.set()
  161. await self._close_losers(except_link=link)
  162. if link is self.winning_link:
  163. self.local_writer.write(frame.payload)
  164. await self.local_writer.drain()
  165. return
  166. if frame.kind == TCP_CLOSE:
  167. if self.winning_link is None:
  168. self.winning_link = link
  169. self.winner_event.set()
  170. if link is self.winning_link:
  171. await self.close()
  172. async def _close_losers(self, except_link: RelayLink) -> None:
  173. await asyncio.gather(*(link.send(Frame(TCP_CLOSE, self.session_id, self.stream_id, 0, 0, b"")) for link in self.links if link is not except_link and not link.closed), return_exceptions=True)
  174. async def close(self) -> None:
  175. if self.closed:
  176. return
  177. self.closed = True
  178. if self.pump_task and self.pump_task is not asyncio.current_task():
  179. self.pump_task.cancel()
  180. with contextlib.suppress(Exception):
  181. await self.pump_task
  182. await asyncio.gather(*(link.send(Frame(TCP_CLOSE, self.session_id, self.stream_id, 0, 0, b"")) for link in self.links if not link.closed), return_exceptions=True)
  183. for link in self.links:
  184. link.tcp_sessions.pop((self.session_id, self.stream_id), None)
  185. self.local_writer.close()
  186. with contextlib.suppress(Exception):
  187. await self.local_writer.wait_closed()
  188. class UdpAssociateServer(asyncio.DatagramProtocol):
  189. def __init__(self, edge: "SocksEdge") -> None:
  190. self.edge = edge
  191. self.transport: asyncio.DatagramTransport | None = None
  192. self.client_addr = None
  193. self.associate_peer = None
  194. self.packet_counter = itertools.count(1)
  195. self.client_flows: dict[tuple[tuple[str, int], str, int], UdpFlowState] = {}
  196. self.flow_counter = itertools.count(1)
  197. self.last_summary_at = 0.0
  198. self.win_counts: Dict[str, int] = {}
  199. self.relay_error_counts: Dict[str, int] = {}
  200. def connection_made(self, transport) -> None:
  201. self.transport = transport
  202. def register_associate(self, peer) -> None:
  203. peer_text = f"{peer[0]}:{peer[1]}" if isinstance(peer, tuple) and len(peer) >= 2 else str(peer)
  204. if self.associate_peer != peer_text:
  205. print(f"[edge] udp associate peer={peer_text}")
  206. self.associate_peer = peer_text
  207. def datagram_received(self, data: bytes, addr) -> None:
  208. if len(data) < 10:
  209. return
  210. if self.client_addr is None:
  211. self.client_addr = addr
  212. print(f"[edge] udp client bound addr={addr[0]}:{addr[1]}")
  213. elif addr != self.client_addr:
  214. print(f"[edge] udp client rebound old={self.client_addr[0]}:{self.client_addr[1]} new={addr[0]}:{addr[1]}")
  215. self._reset_client_state(addr)
  216. host, port, payload = self._parse_socks_udp(data)
  217. loop = asyncio.get_running_loop()
  218. now = loop.time()
  219. flow_key = ((addr[0], addr[1]), host, port)
  220. flow = self.client_flows.get(flow_key)
  221. if flow is None:
  222. flow = UdpFlowState(
  223. flow_id=next(self.flow_counter),
  224. client_addr=(addr[0], addr[1]),
  225. target_host=host,
  226. target_port=port,
  227. created_at=now,
  228. last_activity=now,
  229. )
  230. self.client_flows[flow_key] = flow
  231. flow.touch(now)
  232. flow.packets_sent += 1
  233. packet_id = next(self.packet_counter)
  234. asyncio.create_task(self.edge.forward_udp(flow, payload, packet_id, self))
  235. self._log_udp_summary()
  236. def _reset_client_state(self, addr) -> None:
  237. old_addr = self.client_addr
  238. remapped_flows: dict[tuple[tuple[str, int], str, int], UdpFlowState] = {}
  239. for flow in list(self.client_flows.values()):
  240. flow.client_addr = (addr[0], addr[1])
  241. remapped_flows[((addr[0], addr[1]), flow.target_host, flow.target_port)] = flow
  242. self.client_flows = remapped_flows
  243. self.client_addr = addr
  244. print(f"[edge] udp client rebound migrated old={old_addr[0]}:{old_addr[1]} new={addr[0]}:{addr[1]} flows={len(self.client_flows)}")
  245. async def handle_from_relay(self, frame: Frame, link: RelayLink) -> None:
  246. if self.transport is None or self.client_addr is None:
  247. return
  248. flow = self.edge.udp_flow_sessions.get((frame.session_id, frame.stream_id))
  249. if flow is None:
  250. return
  251. await self._deliver_flow_packet(flow, frame.packet_id, frame.payload, link.node.name)
  252. async def handle_from_direct(self, flow: UdpFlowState, path_name: str, payload: bytes) -> None:
  253. if self.transport is None or self.client_addr is None:
  254. return
  255. await self._deliver_flow_packet(flow, 0, payload, path_name)
  256. async def _deliver_flow_packet(self, flow: UdpFlowState, packet_id: int, payload: bytes, source_name: str) -> None:
  257. if self.transport is None or self.client_addr is None:
  258. return
  259. packet = self._build_socks_udp(flow.target_host, flow.target_port, payload)
  260. now = asyncio.get_running_loop().time()
  261. flow.touch(now)
  262. flow.path_last_seen[source_name] = now
  263. flow.packets_received += 1
  264. if flow.winner_name is None:
  265. flow.winner_name = source_name
  266. self.win_counts[source_name] = self.win_counts.get(source_name, 0) + 1
  267. self._log_udp_summary(force=True)
  268. elif flow.winner_name != source_name:
  269. flow.duplicate_responses += 1
  270. winner_last_seen = flow.path_last_seen.get(flow.winner_name, 0.0)
  271. if winner_last_seen and now - winner_last_seen >= (self.edge.config.udp_failover_idle_ms / 1000):
  272. flow.winner_name = source_name
  273. self.win_counts[source_name] = self.win_counts.get(source_name, 0) + 1
  274. self._log_udp_summary(force=True)
  275. if flow.winner_name == source_name:
  276. self.transport.sendto(packet, self.client_addr)
  277. def set_flow_candidates(self, flow: UdpFlowState, candidate_names: tuple[str, ...]) -> None:
  278. if not flow.candidate_names:
  279. flow.candidate_names = candidate_names
  280. def note_unsent(self, flow: UdpFlowState, packet_id: int) -> None:
  281. flow.touch(asyncio.get_running_loop().time())
  282. flow.relay_failures["unsent"] = flow.relay_failures.get("unsent", 0) + 1
  283. self._log_udp_summary(force=True)
  284. def _log_udp_summary(self, force: bool = False) -> None:
  285. now = asyncio.get_running_loop().time()
  286. if not force and now - self.last_summary_at < 10:
  287. return
  288. self.last_summary_at = now
  289. active_flows = len(self.client_flows)
  290. winners = sum(1 for flow in self.client_flows.values() if flow.winner_name)
  291. packets_sent = sum(flow.packets_sent for flow in self.client_flows.values())
  292. packets_received = sum(flow.packets_received for flow in self.client_flows.values())
  293. duplicates = sum(flow.duplicate_responses for flow in self.client_flows.values())
  294. direct_paths = sum(len(flow.direct_sockets) for flow in self.client_flows.values())
  295. relay_candidates = sum(len(flow.link_streams) for flow in self.client_flows.values())
  296. candidate_names: list[str] = []
  297. seen_candidates: set[str] = set()
  298. for flow in sorted(self.client_flows.values(), key=lambda item: item.flow_id):
  299. for name in flow.candidate_names:
  300. if name in seen_candidates:
  301. continue
  302. seen_candidates.add(name)
  303. candidate_names.append(name)
  304. direct_wins = sum(1 for flow in self.client_flows.values() if flow.winner_name and flow.winner_name.startswith("direct"))
  305. relay_wins = winners - direct_wins
  306. sample_flows = [
  307. f"{flow.flow_id}:{flow.winner_name or 'pending'}"
  308. for flow in sorted(self.client_flows.values(), key=lambda item: item.flow_id)
  309. if flow.winner_name
  310. ][:5]
  311. winner_detail = ", ".join(sample_flows) or "none"
  312. relay_errors: list[str] = []
  313. for flow in self.client_flows.values():
  314. for name, count in flow.relay_failures.items():
  315. relay_errors.append(f"{name}={count}")
  316. relay_error_detail = ", ".join(sorted(relay_errors)) or "none"
  317. if self.client_addr:
  318. print(
  319. f"[edge] udp summary bind={self.client_addr[0]}:{self.client_addr[1]} flows={active_flows} winners={winners} "
  320. f"winner_breakdown=direct={direct_wins},relay={relay_wins} sample={winner_detail} "
  321. f"candidates={candidate_names or ['none']} "
  322. f"sent={packets_sent} recv={packets_received} dup={duplicates} "
  323. f"direct_paths={direct_paths} relay_paths={relay_candidates} relay_errors={relay_error_detail}"
  324. )
  325. else:
  326. print(
  327. f"[edge] udp summary bind=unbound flows={active_flows} winners={winners} "
  328. f"winner_breakdown=direct={direct_wins},relay={relay_wins} sample={winner_detail} "
  329. f"candidates={candidate_names or ['none']} "
  330. f"sent={packets_sent} recv={packets_received} dup={duplicates} "
  331. f"direct_paths={direct_paths} relay_paths={relay_candidates} relay_errors={relay_error_detail}"
  332. )
  333. def _parse_socks_udp(self, packet: bytes) -> tuple[str, int, bytes]:
  334. atyp = packet[3]
  335. offset = 4
  336. if atyp == 1:
  337. host = socket.inet_ntoa(packet[offset:offset + 4])
  338. offset += 4
  339. elif atyp == 3:
  340. size = packet[offset]
  341. offset += 1
  342. host = packet[offset:offset + size].decode()
  343. offset += size
  344. else:
  345. raise ValueError("unsupported udp atyp")
  346. port = struct.unpack("!H", packet[offset:offset + 2])[0]
  347. offset += 2
  348. return host, port, packet[offset:]
  349. def _build_socks_udp(self, host: str, port: int, payload: bytes) -> bytes:
  350. try:
  351. addr = socket.inet_aton(host)
  352. header = b"\x00\x00\x00\x01" + addr + struct.pack("!H", port)
  353. except OSError:
  354. raw = host.encode()
  355. header = b"\x00\x00\x00\x03" + bytes([len(raw)]) + raw + struct.pack("!H", port)
  356. return header + payload
  357. class SocksEdge:
  358. def __init__(self, listen_host: str, listen_port: int, config: Config) -> None:
  359. self.listen_host = listen_host
  360. self.listen_port = listen_port
  361. self.config = config
  362. self.scheduler = Scheduler(config)
  363. self.links: list[RelayLink] = []
  364. self.session_ids = itertools.count(1)
  365. self.udp_stream_ids = itertools.count(1)
  366. self.udp_flow_sessions: dict[tuple[int, int], UdpFlowState] = {}
  367. self.udp_server: UdpAssociateServer | None = None
  368. async def start(self) -> None:
  369. await self.scheduler.start()
  370. await self._connect_relays()
  371. server = await asyncio.start_server(self._accept, self.listen_host, self.listen_port)
  372. sockets = ", ".join(str(sock.getsockname()) for sock in server.sockets or [])
  373. print(f"[edge] socks5 listening on {sockets}")
  374. async with server:
  375. await server.serve_forever()
  376. async def _connect_relays(self) -> None:
  377. loop = asyncio.get_running_loop()
  378. transport, protocol = await loop.create_datagram_endpoint(lambda: UdpAssociateServer(self), local_addr=(self.listen_host, 0))
  379. self.udp_server = protocol
  380. self.udp_transport = transport
  381. for node in self.config.relays:
  382. link = RelayLink(node=node, reader=None, writer=None) # type: ignore[arg-type]
  383. link.udp_server = protocol
  384. self.links.append(link)
  385. link.maintain_task = asyncio.create_task(self._maintain_link(link))
  386. async def _maintain_link(self, link: RelayLink) -> None:
  387. backoff = 1.0
  388. while True:
  389. try:
  390. reader, writer = await asyncio.open_connection(link.node.host, link.node.port)
  391. sock = writer.get_extra_info("socket")
  392. if sock is not None:
  393. with contextlib.suppress(OSError):
  394. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  395. link.reader = reader
  396. link.writer = writer
  397. await link.start()
  398. backoff = 1.0
  399. await link.closed_event.wait()
  400. except asyncio.CancelledError:
  401. raise
  402. except Exception:
  403. await asyncio.sleep(backoff)
  404. backoff = min(10.0, backoff * 2)
  405. async def _accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  406. try:
  407. peer = writer.get_extra_info("peername")
  408. _host, _port, udp_mode = await self._handshake(reader, writer, peer)
  409. if udp_mode:
  410. return
  411. except Exception:
  412. writer.close()
  413. with contextlib.suppress(Exception):
  414. await writer.wait_closed()
  415. def _selected_links(self) -> list[RelayLink]:
  416. chosen = {node.name for node in self.scheduler.choose()}
  417. links = [link for link in self.links if link.node.name in chosen and not link.closed]
  418. return links or [link for link in self.links if not link.closed][:1]
  419. def _selected_udp_links(self) -> list[RelayLink]:
  420. online = [link for link in self.links if not link.closed and link.writer is not None]
  421. if not online:
  422. return []
  423. ordered = sorted(online, key=lambda link: self.scheduler.scores.get(link.node.name).score if link.node.name in self.scheduler.scores else 999999.0)
  424. return ordered
  425. def _udp_direct_redundancy_for_target(self, target_host: str) -> int:
  426. base = self.config.udp_direct_redundancy
  427. if ":" in target_host and self.config.udp_direct_redundancy_v6 is not None:
  428. base = self.config.udp_direct_redundancy_v6
  429. elif ":" not in target_host and self.config.udp_direct_redundancy_v4 is not None:
  430. base = self.config.udp_direct_redundancy_v4
  431. return max(1, base)
  432. async def _ensure_udp_direct_paths(self, flow: UdpFlowState, udp_server: UdpAssociateServer) -> None:
  433. target_count = self._udp_direct_redundancy_for_target(flow.target_host)
  434. for index in range(target_count):
  435. name = f"direct-{index + 1}" if target_count > 1 else "direct"
  436. if name in flow.direct_sockets or name in flow.direct_failures:
  437. continue
  438. try:
  439. family = socket.AF_INET6 if ":" in flow.target_host else socket.AF_INET
  440. sock = socket.socket(family, socket.SOCK_DGRAM)
  441. sock.setblocking(False)
  442. await asyncio.get_running_loop().sock_connect(sock, (flow.target_host, flow.target_port))
  443. flow.direct_sockets[name] = sock
  444. flow.direct_tasks[name] = asyncio.create_task(self._pump_udp_direct(flow, name, sock, udp_server))
  445. except Exception as exc:
  446. flow.direct_failures.add(name)
  447. print(f"[edge] udp direct open error flow={flow.flow_id} path={name} target={flow.target_host}:{flow.target_port} error={exc!r}")
  448. async def _pump_udp_direct(self, flow: UdpFlowState, path_name: str, sock: socket.socket, udp_server: UdpAssociateServer) -> None:
  449. loop = asyncio.get_running_loop()
  450. try:
  451. while True:
  452. data = await loop.sock_recv(sock, 65535)
  453. if not data:
  454. break
  455. await udp_server.handle_from_direct(flow, path_name, data)
  456. except Exception:
  457. pass
  458. finally:
  459. flow.direct_tasks.pop(path_name, None)
  460. flow.direct_sockets.pop(path_name, None)
  461. with contextlib.suppress(Exception):
  462. sock.close()
  463. async def forward_udp(self, flow: UdpFlowState, payload: bytes, packet_id: int, udp_server: UdpAssociateServer) -> None:
  464. await self._ensure_udp_direct_paths(flow, udp_server)
  465. meta = encode_json({"host": flow.target_host, "port": flow.target_port})
  466. links = self._selected_udp_links()
  467. direct_names = tuple(name for name in sorted(flow.direct_sockets))
  468. relay_names = tuple(link.node.name for link in links)
  469. candidate_names = direct_names + relay_names
  470. udp_server.set_flow_candidates(flow, candidate_names)
  471. if not candidate_names:
  472. udp_server.note_unsent(flow, packet_id)
  473. return
  474. active_direct_names = list(direct_names)
  475. active_links = links
  476. if not (self.config.udp_always_broadcast or flow.winner_name is None):
  477. winner_last_seen = flow.path_last_seen.get(flow.winner_name, 0.0) if flow.winner_name else 0.0
  478. if winner_last_seen and asyncio.get_running_loop().time() - winner_last_seen >= (self.config.udp_failover_idle_ms / 1000):
  479. flow.winner_name = None
  480. active_direct_names = [name for name in active_direct_names if name == flow.winner_name]
  481. active_links = [link for link in active_links if link.node.name == flow.winner_name]
  482. if not active_direct_names and not active_links:
  483. if direct_names:
  484. active_direct_names = [direct_names[0]]
  485. elif links:
  486. active_links = links[:1]
  487. copies = max(1, self.config.udp_redundancy + 1)
  488. sent_any = False
  489. for attempt in range(copies):
  490. for path_name in active_direct_names:
  491. sock = flow.direct_sockets.get(path_name)
  492. if sock is None:
  493. continue
  494. try:
  495. await asyncio.get_running_loop().sock_sendall(sock, payload)
  496. sent_any = True
  497. except Exception as exc:
  498. flow.direct_failures.add(path_name)
  499. flow.direct_sockets.pop(path_name, None)
  500. task = flow.direct_tasks.pop(path_name, None)
  501. if task is not None:
  502. task.cancel()
  503. with contextlib.suppress(Exception):
  504. sock.close()
  505. flow.relay_failures[path_name] = flow.relay_failures.get(path_name, 0) + 1
  506. if path_name not in flow.relay_error_seen:
  507. flow.relay_error_seen.add(path_name)
  508. print(
  509. f"[edge] udp relay error flow={flow.flow_id} relay={path_name} error={exc!r}"
  510. )
  511. for link in active_links:
  512. stream_id = flow.link_streams.get(link.node.name)
  513. if stream_id is None:
  514. stream_id = next(self.udp_stream_ids)
  515. flow.link_streams[link.node.name] = stream_id
  516. self.udp_flow_sessions[(flow.flow_id, stream_id)] = flow
  517. include_meta = link.node.name not in flow.initialized_links
  518. body = (meta + payload) if include_meta else payload
  519. meta_len = len(meta) if include_meta else 0
  520. try:
  521. await link.send(Frame(UDP_SEND, flow.flow_id, stream_id, 0, meta_len, body))
  522. flow.initialized_links.add(link.node.name)
  523. sent_any = True
  524. except Exception as exc:
  525. flow.link_streams.pop(link.node.name, None)
  526. self.udp_flow_sessions.pop((flow.flow_id, stream_id), None)
  527. flow.relay_failures[link.node.name] = flow.relay_failures.get(link.node.name, 0) + 1
  528. if link.node.name not in flow.relay_error_seen:
  529. flow.relay_error_seen.add(link.node.name)
  530. print(
  531. f"[edge] udp relay error flow={flow.flow_id} relay={link.node.name} error={exc!r}"
  532. )
  533. if attempt + 1 < copies and self.config.udp_copy_interval_ms > 0:
  534. await asyncio.sleep(self.config.udp_copy_interval_ms / 1000)
  535. if not sent_any:
  536. udp_server.note_unsent(flow, packet_id)
  537. async def _handshake(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, peer) -> tuple[str, int, bool]:
  538. version, methods_len = (await read_exact(reader, 2))
  539. if version != SOCKS_VERSION:
  540. raise ValueError("unsupported socks version")
  541. await read_exact(reader, methods_len)
  542. writer.write(b"\x05\x00")
  543. await writer.drain()
  544. version, command, _, atyp = await read_exact(reader, 4)
  545. if version != SOCKS_VERSION:
  546. raise ValueError("unsupported socks version")
  547. if atyp == 1:
  548. host = socket.inet_ntoa(await read_exact(reader, 4))
  549. elif atyp == 3:
  550. size = (await read_exact(reader, 1))[0]
  551. host = (await read_exact(reader, size)).decode()
  552. else:
  553. raise ValueError("unsupported atyp")
  554. port = struct.unpack("!H", await read_exact(reader, 2))[0]
  555. peer_text = f"{peer[0]}:{peer[1]}" if isinstance(peer, tuple) and len(peer) >= 2 else str(peer)
  556. if command == 1:
  557. print(f"[edge] socks handshake peer={peer_text} command=connect target={host}:{port}")
  558. writer.write(b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00")
  559. await writer.drain()
  560. return host, port, False
  561. if command == 3 and self.udp_server and self.udp_server.transport:
  562. bind_host, bind_port = self.udp_server.transport.get_extra_info("sockname")[:2]
  563. self.udp_server.register_associate(peer)
  564. print(f"[edge] socks handshake peer={peer_text} command=udp_associate target={host}:{port} bind={bind_host}:{bind_port}")
  565. writer.write(b"\x05\x00\x00\x01" + socket.inet_aton(bind_host) + struct.pack("!H", bind_port))
  566. await writer.drain()
  567. return host, port, True
  568. raise ValueError("unsupported socks command")