socks_edge.py 27 KB

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