socks_edge.py 30 KB

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