socks_edge.py 26 KB

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