control_socket.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. """Gateway control socket — the gateway-owned local coordination surface: a local-only socket answering
  2. versioned JSON verbs (``identify``, ``status``). A connectable socket with a well-formed ``identify``
  3. answer IS liveness — no PID-reuse heuristics. Never a TCP port: filesystem/pipe ACLs are the auth
  4. boundary. POSIX: ``$HERMES_HOME/gateway.sock`` (or a temp-dir socket + ``gateway.sock.path`` pointer
  5. file when the home path exceeds ``sun_path`` or its filesystem refuses sockets); Windows: named pipe ``\\\\.\\pipe\\hermes-gateway-<hash>``.
  6. Wire contract: ONE request per connection — one JSON line in, one out, then the server closes.
  7. Consumers PREFER the socket and fall back to the state-file/scan layer when it doesn't answer.
  8. """
  9. from __future__ import annotations
  10. import asyncio
  11. import contextlib
  12. import errno
  13. import hashlib
  14. import inspect
  15. import json
  16. import logging
  17. import os
  18. import socket
  19. import stat
  20. import sys
  21. import tempfile
  22. import time
  23. from pathlib import Path
  24. from typing import Any, Callable, Optional
  25. logger = logging.getLogger(__name__)
  26. CONTROL_PROTOCOL_VERSION = 1
  27. _SOCKET_FILENAME = "gateway.sock"
  28. _POINTER_FILENAME = "gateway.sock.path"
  29. _IS_WINDOWS = sys.platform == "win32"
  30. _MAX_UNIX_PATH = 100 # sun_path limit is 104 on macOS/BSD, 108 on Linux; margin for the NUL
  31. # Single-line JSON in/out; bounded so a misbehaving peer can't balloon memory.
  32. _MAX_REQUEST_BYTES = 64 * 1024
  33. _MAX_RESPONSE_BYTES = 512 * 1024
  34. _DEFAULT_CLIENT_TIMEOUT = 2.0
  35. # What a filesystem that cannot host an AF_UNIX node answers: a Docker Desktop (virtiofs) bind mount
  36. # refuses the socket, and an inode a previous container left there can be neither stat'ed nor
  37. # removed from inside (#123761). Not EADDRINUSE: a live sibling must keep failing loudly.
  38. _SOCKET_UNSUPPORTED_ERRNOS = frozenset({errno.EOPNOTSUPP, errno.ENOTSUP})
  39. def _home_hash(home: Path) -> str:
  40. return hashlib.sha256(os.path.normcase(str(Path(home).expanduser().resolve(strict=False))).encode("utf-8")).hexdigest()[:16]
  41. def windows_pipe_name(home: Path) -> str:
  42. """Per-HERMES_HOME named pipe path (Windows transport)."""
  43. return rf"\\.\pipe\hermes-gateway-{_home_hash(home)}"
  44. def _fits_sun_path(path: Path) -> bool:
  45. return len(str(path).encode("utf-8")) <= _MAX_UNIX_PATH
  46. def _private_runtime_dir() -> Optional[Path]:
  47. """``$XDG_RUNTIME_DIR`` when it is what the spec promises: an absolute directory owned by this
  48. user with no group/other access. Other users cannot pre-create names inside it."""
  49. raw = os.environ.get("XDG_RUNTIME_DIR", "")
  50. if _IS_WINDOWS or not raw or not os.path.isabs(raw):
  51. return None
  52. with contextlib.suppress(OSError):
  53. if _private_directory(Path(raw)):
  54. return Path(raw)
  55. return None
  56. def _fallback_socket_path(home: Path) -> Path:
  57. """Short path for homes whose direct socket path exceeds sun_path: the private
  58. ``$XDG_RUNTIME_DIR`` first, then ``tempfile.gettempdir()`` and ``/tmp`` (POSIX); if nothing fits
  59. the first candidate is returned anyway. A squatted shared-temp name is handled at bind time
  60. (``_squat_proof_fallback``)."""
  61. name = f"hermes-gw-{_home_hash(home)}/control.sock"
  62. runtime = _private_runtime_dir()
  63. candidates = ([runtime / name] if runtime else []) + [Path(tempfile.gettempdir()) / name] + (
  64. [] if _IS_WINDOWS else [Path("/tmp") / name]) # no-tmp: ok — AF_UNIX 104-byte path limit needs the short /tmp candidate
  65. return next((c for c in candidates if _fits_sun_path(c)), candidates[0])
  66. def _private_directory(path: Path) -> bool:
  67. info = path.lstat()
  68. return stat.S_ISDIR(info.st_mode) and info.st_uid == os.getuid() and not info.st_mode & 0o077 # windows-footgun: ok — POSIX only
  69. def _squat_proof_fallback(bind_path: Path) -> Path:
  70. """Same ``hermes-gw-<hash>/control.sock`` leaf (what clients authenticate through the private
  71. pointer), under a fresh ``mkdtemp`` root no other user can predict or pre-create."""
  72. root = Path(tempfile.mkdtemp(prefix="hgw-", dir=bind_path.parent.parent))
  73. path = root / bind_path.parent.name / bind_path.name
  74. if not _fits_sun_path(path):
  75. root.rmdir()
  76. raise PermissionError("fallback control directory is squatted and no private path fits sun_path")
  77. path.parent.mkdir(mode=0o700)
  78. return path
  79. def _publish_pointer(pointer_file: Path, bind_path: Path) -> None:
  80. """Replace ``pointer_file`` with one naming ``bind_path``, atomically: the listener is already
  81. accepting, so a client polling for it may read the pointer at any instant, and an empty or
  82. partial pointer is ``invalid_control_pointer`` to it, a refusal rather than "still starting".
  83. The fresh mkstemp inode is 0600 and the rename replaces a symlink rather than following it,
  84. which also heals an older gateway's leftover 0644 pointer."""
  85. fd, tmp = tempfile.mkstemp(prefix=f".{pointer_file.name}.", dir=pointer_file.parent)
  86. try:
  87. with os.fdopen(fd, "w", encoding="utf-8") as pointer:
  88. pointer.write(str(bind_path))
  89. os.replace(tmp, pointer_file)
  90. except BaseException:
  91. with contextlib.suppress(OSError):
  92. os.unlink(tmp)
  93. raise
  94. def resolve_server_socket_path(home: Path) -> tuple[Path, Optional[Path]]:
  95. """Return ``(bind_path, pointer_file)``; pointer_file is set only for the temp-dir fallback."""
  96. direct = Path(home) / _SOCKET_FILENAME
  97. return (direct, None) if _fits_sun_path(direct) else (_fallback_socket_path(home), Path(home) / _POINTER_FILENAME)
  98. def resolve_client_socket_path(home: Path) -> Optional[Path]:
  99. """Where a client should connect for ``home``, or None when nothing exists."""
  100. direct = Path(home) / _SOCKET_FILENAME
  101. with contextlib.suppress(OSError): # an un-stat-able stale inode (#123761) is absent, not an error
  102. if direct.exists():
  103. return direct
  104. with contextlib.suppress(OSError):
  105. pointer = Path(home) / _POINTER_FILENAME
  106. target = pointer.read_text(encoding="utf-8-sig").strip() if pointer.is_file() else ""
  107. if target and Path(target).exists():
  108. return Path(target)
  109. return None
  110. def _detect_supervisor() -> str:
  111. """Supervisor kind for THIS process from its own launch env (not inferred outside-in).
  112. Unlike the outside-in `_detect_supervisor_for_pid` scan, this answers from the process's own launch
  113. context — which is exactly the provenance the 92091 design wants declared rather than inferred. See
  114. #92091.
  115. """
  116. env = os.environ
  117. if env.get("INVOCATION_ID"):
  118. return "systemd"
  119. from gateway.restart import launchd_job_label
  120. if sys.platform == "darwin" and (launchd_job_label(env) or env.get("LAUNCHD_SOCKET")):
  121. return "launchd"
  122. if env.get("HERMES_DESKTOP_MANAGED"):
  123. return "desktop"
  124. return "external" if "--external-supervisor" in sys.argv else "manual"
  125. def _structured_login_subject(value: str) -> bool:
  126. """Whether ``value`` is ``authenticated_subject``'s namespaced login form
  127. ``auth:v1:[provider, issuer, user]`` (gateway.session_identity) — the only identity
  128. a same-user peer may forward a ticket for. Bare labels (``admin``, ``uid:501``) fail:
  129. they can collide with another stored owner representation."""
  130. from gateway.session_identity import parse_authenticated_subject
  131. return parse_authenticated_subject(value) is not None
  132. def launch_supervisor(identity: dict[str, Any]) -> Optional[str]:
  133. """What launched the gateway behind an ``identify`` answer (``manual``, ``desktop``, ``systemd``, ...).
  134. The session runtime protocol folds ``manual`` and ``desktop`` into ``supervisor: "none"``, so the
  135. launch value rides in ``launch_supervisor``. A gateway that predates that field and answers
  136. ``"none"`` is ambiguous: None (unknown), never ``manual``.
  137. """
  138. for key in ("launch_supervisor", "supervisor"):
  139. value = identity.get(key)
  140. if isinstance(value, str) and value and value != "none":
  141. return value
  142. return None
  143. def build_identify_payload() -> dict[str, Any]:
  144. """Default ``identify`` answer, built from gateway.status primitives."""
  145. from gateway.status import _build_pid_record, _get_code_identity_fields, _profile_label_for_home, read_runtime_status
  146. record = _build_pid_record()
  147. supervisor = _detect_supervisor()
  148. payload: dict[str, Any] = {
  149. "protocol": CONTROL_PROTOCOL_VERSION,
  150. **{k: record.get(k) for k in ("kind", "pid", "start_time", "hermes_home")},
  151. "profile": _profile_label_for_home(record.get("hermes_home") or ""),
  152. "supervisor": supervisor, "launch_supervisor": supervisor, **_get_code_identity_fields()}
  153. with contextlib.suppress(Exception):
  154. # served_profiles (multiplex mode) is stamped into runtime status by the runner.
  155. served = (read_runtime_status() or {}).get("served_profiles")
  156. if isinstance(served, list) and served:
  157. payload["served_profiles"] = served
  158. return payload
  159. def build_status_payload() -> dict[str, Any]:
  160. """Default ``status`` answer — current runtime status, answered live."""
  161. from gateway.status import read_runtime_status
  162. return {**(read_runtime_status() or {}), "protocol": CONTROL_PROTOCOL_VERSION,
  163. "answered_at": time.time(), "answering_pid": os.getpid()}
  164. class GatewayControlServer:
  165. """Gateway-owned control socket server (identify/status, v1): ``start()`` after the PID-file claim,
  166. ``stop()`` on shutdown. ``start()`` reports a bind failure as False and the gateway bootstrap
  167. treats that as fatal: local clients attach only with tickets minted on this listener."""
  168. def __init__(self, home: Optional[Path] = None, *,
  169. verb_handlers: Optional[dict[str, Callable[..., dict[str, Any]]]] = None) -> None:
  170. if home is None:
  171. from gateway.status import _get_process_hermes_home
  172. home = _get_process_hermes_home()
  173. # The real directory, as clients canonicalize it: the peer check below refuses any
  174. # symlinked component, so an unresolved symlinked ~/.hermes would never mint tickets.
  175. self._home = Path(home).resolve()
  176. self.ticket_store = None
  177. self.private_handlers = {}
  178. self._server: Optional[asyncio.AbstractServer] = None
  179. self._pipe_server: Any = None # Windows proactor pipe server
  180. self._bind_path: Optional[Path] = None
  181. self._pointer_file: Optional[Path] = None
  182. self._fallback_root: Optional[Path] = None # mkdtemp root created for a squatted fallback
  183. self._file_identities = {}
  184. self._handlers: dict[str, Callable[..., dict[str, Any]]] = {
  185. "identify": build_identify_payload, "status": build_status_payload, **(verb_handlers or {})}
  186. async def start(self) -> bool:
  187. """Bind and start serving. Returns True on success, False otherwise."""
  188. try:
  189. return await (self._start_windows() if _IS_WINDOWS else self._start_posix())
  190. except Exception as exc:
  191. await self.stop()
  192. logger.warning("Gateway control socket failed to start: %s", exc)
  193. return False
  194. async def _start_posix(self) -> bool:
  195. bind_path, pointer_file = resolve_server_socket_path(self._home)
  196. try:
  197. bind_path = await self._bind_posix(bind_path, pointer_file)
  198. except OSError as exc:
  199. # A home that fits sun_path can still refuse the socket (Docker Desktop bind mounts,
  200. # #123761): listen on the same private temp-dir socket + pointer an over-long home uses.
  201. if pointer_file is not None or exc.errno not in _SOCKET_UNSUPPORTED_ERRNOS:
  202. raise
  203. logger.warning("Control socket cannot be created in %s (%s); listening in a private temp directory",
  204. self._home, exc.strerror or exc)
  205. pointer_file = Path(self._home) / _POINTER_FILENAME
  206. bind_path = await self._bind_posix(_fallback_socket_path(self._home), pointer_file)
  207. self._bind_path = bind_path
  208. info = bind_path.lstat()
  209. self._file_identities[bind_path] = (info.st_dev, info.st_ino)
  210. if pointer_file is not None:
  211. _publish_pointer(pointer_file, bind_path)
  212. self._pointer_file = pointer_file
  213. for path in filter(None, (self._bind_path, self._pointer_file)):
  214. info = path.lstat()
  215. self._file_identities[path] = (info.st_dev, info.st_ino)
  216. logger.info("Gateway control socket listening at %s", bind_path)
  217. return True
  218. async def _bind_posix(self, bind_path: Path, pointer_file: Optional[Path]) -> Path:
  219. """Bind the listener at ``bind_path`` (moved to a squat-proof root when its shared-temp
  220. directory is not private) and return where it actually listens."""
  221. if pointer_file is not None:
  222. with contextlib.suppress(FileExistsError):
  223. bind_path.parent.mkdir(mode=0o700)
  224. if not _private_directory(bind_path.parent):
  225. # Another local user pre-created the predictable shared-temp name; bootstrap treats
  226. # a missing listener as fatal, so move to an unpredictable private root instead.
  227. logger.warning("Fallback control directory %s is not private; using a fresh one", bind_path.parent)
  228. bind_path = _squat_proof_fallback(bind_path)
  229. self._fallback_root = bind_path.parent.parent
  230. if bind_path.is_symlink():
  231. raise PermissionError("control socket cannot be a symlink")
  232. # We only get here after winning the PID-file O_EXCL race, so any existing
  233. # file is stale or a collision — never a live sibling.
  234. if bind_path.exists():
  235. if bind_path.lstat().st_uid != os.getuid(): # windows-footgun: ok — POSIX listener
  236. raise PermissionError("control socket belongs to another user")
  237. bind_path.unlink()
  238. # Restrictive umask so the socket is never world-connectable, even for the instant before chmod.
  239. old_umask = os.umask(0o177)
  240. try:
  241. self._server = await asyncio.start_unix_server(self._handle_connection, path=str(bind_path))
  242. finally:
  243. os.umask(old_umask)
  244. with contextlib.suppress(OSError):
  245. os.chmod(bind_path, 0o600)
  246. return bind_path
  247. async def _start_windows(self) -> bool:
  248. from gateway.runtime_bootstrap_windows import NativeControlServer
  249. self._pipe_server = NativeControlServer(self._home, self.handle_request_line)
  250. await asyncio.to_thread(self._pipe_server.start)
  251. return True
  252. async def stop(self) -> None:
  253. """Stop serving and remove the socket/pointer files."""
  254. if self.ticket_store is not None:
  255. self.ticket_store.revoke()
  256. if self._server is not None:
  257. self._server.close()
  258. with contextlib.suppress(Exception):
  259. await self._server.wait_closed()
  260. if self._pipe_server is not None:
  261. with contextlib.suppress(Exception):
  262. await asyncio.to_thread(self._pipe_server.close)
  263. self._server = self._pipe_server = None
  264. self.cleanup_files()
  265. def cleanup_files(self) -> None:
  266. """Best-effort removal of socket + pointer files (atexit-safe)."""
  267. for path in filter(None, (self._bind_path, self._pointer_file)):
  268. with contextlib.suppress(OSError):
  269. info = path.lstat()
  270. if self._file_identities.get(path) == (info.st_dev, info.st_ino):
  271. path.unlink()
  272. self._file_identities.clear()
  273. if self._fallback_root is not None:
  274. with contextlib.suppress(OSError):
  275. (self._fallback_root / f"hermes-gw-{_home_hash(self._home)}").rmdir()
  276. self._fallback_root.rmdir()
  277. self._fallback_root = None
  278. def handle_request_line(self, raw: bytes, peer_subject: Optional[str] = None) -> bytes:
  279. """One JSON request line -> one JSON response line. Never raises (shared by POSIX + pipe)."""
  280. request_id: Any = None
  281. try:
  282. request = json.loads(raw.decode("utf-8"))
  283. if not isinstance(request, dict):
  284. raise ValueError("request must be a JSON object")
  285. request_id, verb = request.get("id"), request.get("verb")
  286. handler = self._handlers.get(verb) if isinstance(verb, str) else None
  287. if isinstance(verb, str) and verb in self.private_handlers:
  288. if (not peer_subject or request.get("protocol") != 1
  289. or set(request) - {"protocol", "verb", "id", "params"}
  290. or not isinstance(request.get("params"), dict)):
  291. raise PermissionError("authenticated private request required")
  292. response = {"ok": True, "protocol": CONTROL_PROTOCOL_VERSION,
  293. "result": self.private_handlers[verb](request["params"], peer_subject)}
  294. elif verb == "session-ticket":
  295. response = {"ok": True, "protocol": CONTROL_PROTOCOL_VERSION,
  296. "result": self._session_ticket(request, peer_subject)}
  297. elif handler is None:
  298. response: dict[str, Any] = {"ok": False, "error": f"unknown verb: {verb!r}",
  299. "protocol": CONTROL_PROTOCOL_VERSION, "supported_verbs": sorted(self._handlers)}
  300. else:
  301. # Verbs that carry arguments (e.g. migrate-profile-identity) declare a ``params``
  302. # parameter; argument-less verbs (identify/status/rescan) keep their bare signature.
  303. params = request.get("params") if isinstance(request.get("params"), dict) else {}
  304. wants_params = "params" in inspect.signature(handler).parameters
  305. response = {"ok": True, "protocol": CONTROL_PROTOCOL_VERSION,
  306. "result": handler(params) if wants_params else handler()}
  307. except Exception as exc:
  308. response = {"ok": False, "error": f"{type(exc).__name__}: {exc}", "protocol": CONTROL_PROTOCOL_VERSION}
  309. if request_id is not None:
  310. response["id"] = request_id
  311. try:
  312. encoded = json.dumps(response, default=str).encode("utf-8")
  313. except Exception:
  314. encoded = b'{"ok": false, "error": "response serialization failed"}'
  315. if len(encoded) > _MAX_RESPONSE_BYTES:
  316. # Structured and distinct: a caller must not read an oversized answer as a drain.
  317. too_large: dict[str, Any] = {"ok": False, "error": "response_too_large", "code": "response_too_large",
  318. "limit": _MAX_RESPONSE_BYTES, "protocol": CONTROL_PROTOCOL_VERSION}
  319. if isinstance(request_id, (int, str)) and len(str(request_id)) <= 128:
  320. too_large["id"] = request_id
  321. encoded = json.dumps(too_large).encode("utf-8")
  322. return encoded + b"\n"
  323. def _session_ticket(self, request: dict, peer_subject: Optional[str]) -> dict:
  324. if not peer_subject or self.ticket_store is None:
  325. raise PermissionError("authenticated runtime bootstrap unavailable")
  326. if set(request) - {"protocol", "verb", "id", "params"} or request.get("protocol") != 1:
  327. raise PermissionError("invalid bootstrap envelope")
  328. params = request.get("params")
  329. if (not isinstance(params, dict) or not {"profile_id", "instance_id", "purpose"} <= set(params)
  330. or set(params) - {"profile_id", "instance_id", "purpose", "scope", "subject", "restart_wait"}
  331. or params.get("restart_wait", "refuse") != "refuse"):
  332. raise PermissionError("invalid bootstrap parameters")
  333. if params["instance_id"] != self.ticket_store.instance_id:
  334. raise PermissionError("stale runtime instance")
  335. # A verified same-user peer may name the principal it acts for (a standalone dashboard
  336. # forwarding a mutation for its authenticated user, #138915): the socket's peer gate
  337. # stays the trust boundary — the forwarded subject only relabels who that same peer is,
  338. # it never admits a less-verified caller. Only a structured login subject is nameable
  339. # (``authenticated_subject``'s ``auth:v1:[provider, issuer, user]`` form); a bare label
  340. # like ``admin`` could collide with another stored owner representation, so it fails closed.
  341. subject = params.get("subject", peer_subject)
  342. if not isinstance(subject, str) or not subject or len(subject) > 256:
  343. raise PermissionError("invalid bootstrap subject")
  344. if subject is not peer_subject and not _structured_login_subject(subject):
  345. raise PermissionError("invalid bootstrap subject")
  346. ticket = self.ticket_store.mint(profile_id=params["profile_id"], subject=subject,
  347. purpose=params["purpose"], scope=params.get("scope", "profile"),
  348. refuse_restart_wait="restart_wait" in params)
  349. return {"ticket": ticket, "expires_in_seconds": 30,
  350. "instance_id": self.ticket_store.instance_id,
  351. "profile_id": params["profile_id"], "runtime_protocol": 1}
  352. def _posix_peer_subject(self, writer) -> Optional[str]:
  353. # The legacy diagnostic channel may operate without bootstrap-safe metadata.
  354. if os.name == "nt":
  355. return None
  356. try:
  357. from hermes_cli.gateway_runtime_discovery import home_mode_unsafe, socket_peer_uid
  358. home = self._home
  359. info = home.lstat()
  360. if (home.absolute() != home.resolve() or not stat.S_ISDIR(info.st_mode)
  361. or info.st_uid != os.getuid() or home_mode_unsafe(info, home)): # windows-footgun: ok — POSIX-only helper
  362. return None
  363. uid = socket_peer_uid(writer.get_extra_info("socket"))
  364. return f"uid:{uid}" if uid == os.getuid() else None # windows-footgun: ok — POSIX-only helper
  365. except OSError:
  366. return None
  367. async def _handle_connection(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  368. try:
  369. raw = await asyncio.wait_for(reader.readline(), timeout=_DEFAULT_CLIENT_TIMEOUT)
  370. if not raw or len(raw) > _MAX_REQUEST_BYTES:
  371. return
  372. # Handlers read disk; keep that off the loop that drives every platform
  373. # adapter so a fast-polling consumer can't stall heartbeats.
  374. response = await asyncio.get_running_loop().run_in_executor(
  375. None, self.handle_request_line, raw.rstrip(b"\n"), self._posix_peer_subject(writer))
  376. writer.write(response)
  377. await asyncio.wait_for(writer.drain(), timeout=_DEFAULT_CLIENT_TIMEOUT)
  378. except (TimeoutError, ConnectionError, OSError):
  379. pass
  380. except Exception:
  381. logger.debug("Control socket connection handler error", exc_info=True)
  382. finally:
  383. with contextlib.suppress(Exception):
  384. writer.close()
  385. class _PipeControlProtocol(asyncio.Protocol):
  386. """One-shot request/response protocol for the Windows named pipe."""
  387. def __init__(self, server: GatewayControlServer) -> None:
  388. self._server = server
  389. self._transport: Any = None
  390. self._buffer = bytearray()
  391. def connection_made(self, transport) -> None: # pragma: no cover - windows
  392. self._transport = transport
  393. def data_received(self, data: bytes) -> None: # pragma: no cover - windows
  394. self._buffer.extend(data)
  395. if len(self._buffer) > _MAX_REQUEST_BYTES:
  396. self._transport.close()
  397. elif b"\n" in self._buffer:
  398. try:
  399. self._transport.write(self._server.handle_request_line(bytes(self._buffer).partition(b"\n")[0]))
  400. finally:
  401. self._transport.close()
  402. def query_gateway_control(home: Path, verb: str, *, params: Optional[dict[str, Any]] = None,
  403. timeout: float = _DEFAULT_CLIENT_TIMEOUT) -> Optional[dict[str, Any]]:
  404. """Ask the gateway serving ``home`` a control verb; returns its ``result`` payload. Any failure (no/stale
  405. socket, timeout, malformed answer, ``ok: false``) returns None so callers fall back to the scan layer.
  406. ``params`` carries verb arguments (e.g. ``{"old": ..., "new": ...}``). Never raises."""
  407. payload: dict[str, Any] = {"verb": verb, "id": 1, "protocol": CONTROL_PROTOCOL_VERSION}
  408. if params:
  409. payload["params"] = params
  410. request = json.dumps(payload).encode("utf-8") + b"\n"
  411. query = _query_windows_pipe if _IS_WINDOWS else _query_unix_socket
  412. try:
  413. raw = query(Path(home), request, timeout)
  414. response = json.loads(raw.decode("utf-8")) if raw else None
  415. except Exception:
  416. return None
  417. result = response.get("result") if isinstance(response, dict) and response.get("ok") is True else None
  418. return result if isinstance(result, dict) else None
  419. def _read_response_line(read: Callable[[], bytes], deadline: float) -> Optional[bytes]:
  420. """Read chunks until a newline, EOF, deadline, or the size cap (-> None)."""
  421. chunks: list[bytes] = []
  422. while time.monotonic() < deadline:
  423. chunk = read()
  424. chunks.append(chunk)
  425. if not chunk or b"\n" in chunk:
  426. break
  427. if sum(len(c) for c in chunks) > _MAX_RESPONSE_BYTES:
  428. return None
  429. return b"".join(chunks).partition(b"\n")[0] or None
  430. def _query_unix_socket(home: Path, request: bytes, timeout: float) -> Optional[bytes]:
  431. path = resolve_client_socket_path(home)
  432. if path is None:
  433. return None
  434. # OSError covers ConnectionRefusedError / FileNotFoundError on connect and socket.timeout on read.
  435. with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock, contextlib.suppress(OSError):
  436. sock.settimeout(timeout)
  437. sock.connect(str(path))
  438. sock.sendall(request)
  439. return _read_response_line(lambda: sock.recv(65536), time.monotonic() + timeout)
  440. return None
  441. def _query_windows_pipe(home: Path, request: bytes, timeout: float) -> Optional[bytes]:
  442. """The native overlapped client checks its deadline per I/O step, but SID verification and the
  443. connect/peer handshake are still synchronous calls into the pipe. Run the exchange on an
  444. abandoned-at-deadline worker so a peer that never answers costs ``timeout``, never forever —
  445. the bound ``_query_unix_socket`` already gets from ``sock.settimeout`` (#132547)."""
  446. from agent.deadline import run_bounded_sync
  447. outcome = run_bounded_sync(lambda: _windows_pipe_exchange(home, request, timeout), timeout, label="control-pipe")
  448. return None if outcome.timed_out else outcome.value
  449. def _windows_pipe_exchange(home: Path, request: bytes, timeout: float) -> Optional[bytes]: # pragma: no cover - wine2e lane
  450. # The server is the native overlapped pipe worker; its client verifies the server's SID and
  451. # speaks the same framing (a plain open() got no answer in the live Windows pipe test).
  452. from gateway.runtime_bootstrap_windows import query_runtime_control
  453. return query_runtime_control(Path(home), request, timeout)
  454. def identify_gateway(home: Path, *, timeout: float = _DEFAULT_CLIENT_TIMEOUT) -> Optional[dict[str, Any]]:
  455. """Convenience wrapper: ``identify`` the gateway serving ``home``."""
  456. return query_gateway_control(home, "identify", timeout=timeout)
  457. def pause_gateway_for_update(home: Path, *, timeout: float = _DEFAULT_CLIENT_TIMEOUT) -> Optional[dict[str, Any]]:
  458. """Ask the gateway serving ``home`` to drain and exit for an update. Returns the ACK ``{"pausing",
  459. "already_stopping", "pid", "drain_timeout"}`` or None when no gateway answers (old gateway without
  460. the verb, no/dead socket) — the caller then uses the legacy signal/tree-kill pause path.
  461. Step 2 of the socket migration (#92091).
  462. """
  463. return query_gateway_control(home, "pause-for-update", timeout=timeout)
  464. def rescan_gateway_profiles(home: Path, *, timeout: float = 8.0) -> Optional[dict[str, Any]]:
  465. """Ask the multiplexer serving ``home`` to reconcile ``profiles/`` now (hot-serve a created profile,
  466. unroute a deleted one). Returns its ``{"served_profiles", "added", "removed", ...}`` answer, or None
  467. when no gateway answers / the gateway predates the verb — callers then rely on the periodic rescan
  468. (or the restart reminder)."""
  469. return query_gateway_control(home, "rescan-profiles", timeout=timeout)
  470. def request_unserve_profile(home: Path, name: str) -> Optional[dict[str, Any]]:
  471. return query_gateway_control(home, "unserve-profile", params={"name": name}, timeout=8.0)
  472. def request_serve_profile_hot(home: Path, name: str) -> Optional[dict[str, Any]]:
  473. return query_gateway_control(home, "serve-profile", params={"name": name}, timeout=8.0)
  474. def migrate_gateway_profile_identity(home: Path, old_name: str, new_name: str, *,
  475. timeout: float = 8.0) -> Optional[dict[str, Any]]:
  476. """Ask the multiplexer serving ``home`` to rekey a renamed profile's in-memory + on-disk routing
  477. from ``agent:<old>:`` to ``agent:<new>:`` now. Returns its ``{"rekeyed": N, ...}`` answer, or None
  478. when no gateway answers / the gateway predates the verb — the CLI's durable DB rewrite still lands,
  479. and a restart reconciles the in-memory copy."""
  480. return query_gateway_control(home, "migrate-profile-identity",
  481. params={"old": old_name, "new": new_name}, timeout=timeout)
  482. def purge_gateway_profile_identity(home: Path, name: str, *,
  483. timeout: float = 8.0) -> Optional[dict[str, Any]]:
  484. """Ask the multiplexer serving ``home`` to drop a deleted profile's routing identity now — the
  485. in-memory index AND the durable rows, neither of which a CLI-side delete can settle: this process
  486. writes its in-memory copy back, so it re-creates what the CLI removed. Returns its
  487. ``{"ok": True, "dropped": N, ...}`` answer, or None when no gateway answers / the gateway predates
  488. the verb."""
  489. return query_gateway_control(home, "purge-profile-identity", params={"name": name}, timeout=timeout)
  490. def reload_gateway_plugins(home: Path, *, profile_home: Optional[Path] = None,
  491. timeout: float = 30.0) -> Optional[dict[str, Any]]:
  492. """Ask the gateway serving ``home`` to force plugin re-discovery for ``profile_home`` (default: ``home``)
  493. and re-wire its live adapters' plugin handlers now (#87770). Returns ``{"reloaded", "plugins",
  494. "adapters_rewired", ...}`` or None when no gateway answers / it predates the verb — callers then
  495. fall back to the restart hint. Tools and prompt sections of the reloaded plugin still apply next
  496. session; only handlers go live."""
  497. params = {"home": str(profile_home or home)}
  498. return query_gateway_control(home, "reload-plugins", params=params, timeout=timeout)