browser_harness_dirs.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. """Per-profile runtime and tmp dirs for browser-harness daemons (Browser Use mode).
  2. A multiplexed gateway serves every profile from one process. The harness names a daemon by
  3. ``BU_NAME`` alone and reuses any live one, so each served profile gets its own runtime dir (daemon
  4. sockets) and tmp dir (screenshots, debug overlays, logs). A runtime dir too long for a 64-character
  5. session's AF_UNIX socket moves to a private short dir under ``$XDG_RUNTIME_DIR`` or the socket temp
  6. root; outside a served profile, so does a default runtime dir whose socket for the call's own
  7. ``BU_NAME`` would overflow (a deep HOME).
  8. ``browser_use_cli._base_subprocess_env`` applies the result through ``namespace_harness_dirs``, and
  9. ``browser_exec`` calls ``fit_default_socket_dir`` once the call's ``BU_NAME`` is final.
  10. """
  11. from __future__ import annotations
  12. import hashlib
  13. import os
  14. import stat
  15. import sys
  16. from pathlib import Path
  17. from typing import Optional
  18. # browser_harness/_ipc.py: a shared runtime dir names a daemon socket ``<dir>/bu-<BU_NAME>.sock`` and
  19. # BU_NAME may be 64 characters, so the dir gets sun_path (macOS 104 bytes, Linux 108, with the NUL)
  20. # minus 73 (`/bu-` + 64 + `.sock`).
  21. _MACOS_SOCKET_DIR_BUDGET = 103 - len("/bu-.sock") - 64
  22. _LINUX_SOCKET_DIR_BUDGET = 107 - len("/bu-.sock") - 64
  23. # The env keys that, with BU_NAME, identify one harness daemon (a served profile's dirs are its own).
  24. HARNESS_DIR_KEYS = ("BH_RUNTIME_DIR", "BH_RUNTIME_DIR_SHARED", "BH_TMP_DIR", "BH_TMP_DIR_SHARED")
  25. def daemon_identity(env: dict) -> tuple[str, ...]:
  26. """``(*HARNESS_DIR_KEYS values, BU_NAME)`` of the daemon a call with ``env`` drives."""
  27. return (*(env.get(k, "") for k in HARNESS_DIR_KEYS), env.get("BU_NAME", "default"))
  28. def daemon_env(env: dict, identity: tuple[str, ...]) -> dict:
  29. """``env`` re-pointed at the daemon ``identity`` names (its own dirs and BU_NAME)."""
  30. *dirs, name = identity
  31. target = {k: v for k, v in env.items() if k not in HARNESS_DIR_KEYS}
  32. target.update((k, v) for k, v in zip(HARNESS_DIR_KEYS, dirs) if v)
  33. return {**target, "BU_NAME": name}
  34. def socket_dir_budget(platform: str) -> Optional[int]:
  35. """The runtime-dir byte budget on ``platform`` (a ``sys.platform`` value) where the harness binds
  36. AF_UNIX sockets, else None."""
  37. if platform == "darwin":
  38. return _MACOS_SOCKET_DIR_BUDGET
  39. if platform.startswith("linux"):
  40. return _LINUX_SOCKET_DIR_BUDGET
  41. return None # Windows: the harness serves over loopback TCP (port files), no sun_path
  42. def fits_socket_budget(resolved_dir: str, budget: Optional[int]) -> bool:
  43. """Whether a 64-character session's socket under ``resolved_dir`` (the absolute, symlink-resolved
  44. path the harness binds) fits ``budget``; no budget means no sun_path limit."""
  45. return budget is None or len(resolved_dir.encode()) <= budget
  46. def harness_pid_file(env: dict) -> Path:
  47. """Where the harness publishes the pid of the daemon a call with ``env`` drives
  48. (browser_harness ``_ipc``): ``<runtime dir>/bu-<BU_NAME>.pid``, or ``bu.pid`` in an isolated
  49. runtime dir that is not shared between names."""
  50. isolated = env.get("BH_RUNTIME_DIR") or env.get("BH_TMP_DIR")
  51. runtime = Path(isolated).expanduser() if isolated else Path(_harness_home(env)) / "runtime"
  52. shared = not isolated or env.get("BH_RUNTIME_DIR_SHARED") == "1"
  53. return runtime / (f"bu-{env.get('BU_NAME', 'default')}.pid" if shared else "bu.pid")
  54. def namespace_harness_dirs(env: dict, tag: str) -> None:
  55. """Give served profile ``tag`` its own harness runtime and tmp dirs in the child ``env``. An empty
  56. ``tag`` (outside a served-profile scope) leaves ``env`` unchanged."""
  57. if not tag:
  58. return
  59. root = _harness_home(env)
  60. leaf = f"p-{hashlib.sha256(tag.encode()).hexdigest()[:12]}"
  61. base = env.get("BH_RUNTIME_DIR") or env.get("BH_TMP_DIR") or str(Path(root) / "runtime")
  62. runtime = str(Path(base) / leaf)
  63. env["BH_RUNTIME_DIR"] = socket_fit_runtime_dir(runtime, base, tag)
  64. env["BH_RUNTIME_DIR_SHARED"] = "1" # several BU_NAMEs share the dir: keep bu-<name> stems
  65. # Screenshots, debug overlays and daemon logs (paths.tmp_dir): the profile's own, never shared.
  66. env["BH_TMP_DIR"] = str(Path(env.get("BH_TMP_DIR") or str(Path(root) / "tmp")) / leaf)
  67. env["BH_TMP_DIR_SHARED"] = "1"
  68. def _harness_home(env: dict) -> str:
  69. """browser-harness ``paths.home_dir()``, resolved against the child's env."""
  70. root = env.get("BH_HOME") or env.get("BROWSER_HARNESS_HOME")
  71. if not root:
  72. xdg = env.get("XDG_CONFIG_HOME")
  73. root = str(Path(xdg) / "browser-harness") if xdg else str(
  74. Path(env.get("HOME") or Path.home()) / ".config" / "browser-harness")
  75. return str(Path(root).expanduser())
  76. def fit_default_socket_dir(env: dict) -> None:
  77. """Outside a served profile the harness binds ``<home>/runtime/bu-<BU_NAME>.sock``. Under a deep
  78. HOME (a container's profile home ``$HERMES_HOME/home``, a long account home) that path overflows
  79. sun_path and every call dies with ``AF_UNIX path too long``; such a call's runtime dir moves to a
  80. private short dir. Judged on the call's own BU_NAME so a socket that already binds keeps its
  81. path (and its live daemon). A runtime/tmp dir already set (a served profile's, or exported by
  82. the user) is left alone."""
  83. if env.get("BH_RUNTIME_DIR") or env.get("BH_TMP_DIR"):
  84. return
  85. budget = socket_dir_budget(sys.platform)
  86. if budget is None:
  87. return
  88. root = _harness_home(env)
  89. stem_budget = budget + 64 - len(env.get("BU_NAME") or "default") # budget assumes a 64-char name
  90. if fits_socket_budget(str((Path(root) / "runtime").resolve()), stem_budget):
  91. return
  92. short = _claim_short_dir(f"{root}\0", stem_budget)
  93. if short:
  94. env["BH_RUNTIME_DIR"] = short
  95. env["BH_RUNTIME_DIR_SHARED"] = "1" # several BU_NAMEs share the dir: keep bu-<name> stems
  96. def socket_fit_runtime_dir(runtime: str, base: str, tag: str) -> str:
  97. """``runtime`` unless the socket the harness binds under it would be too long for a 64-character
  98. session. The harness binds ``Path(BH_RUNTIME_DIR).expanduser().resolve()``, so the length is
  99. judged on that path (a short relative or symlinked spelling can still resolve deep); a dir that
  100. fits is returned as given. Otherwise the served profile gets a private short dir
  101. (``_claim_short_dir``) keyed by base and profile; if none fits or can be claimed safely the long
  102. path stays (shorter names only)."""
  103. budget = socket_dir_budget(sys.platform)
  104. if fits_socket_budget(str(Path(runtime).expanduser().resolve()), budget):
  105. return runtime
  106. return _claim_short_dir(f"{base}\0{tag}", budget) or runtime
  107. def _claim_short_dir(key: str, budget: Optional[int]) -> Optional[str]:
  108. """A private ``hbh-<12 hex>`` dir (keyed by uid and ``key``) that fits ``budget``: under the
  109. user's private ``$XDG_RUNTIME_DIR`` first, else the short socket temp root; None when no
  110. candidate fits or can be claimed safely."""
  111. from hermes_constants import socket_safe_tmpdir
  112. getuid = getattr(os, "getuid", lambda: 0)
  113. digest = hashlib.sha256(f"{getuid()}\0{key}".encode()).hexdigest()[:12]
  114. # socket_safe_tmpdir() caps the root at 50 bytes for Chrome's longer socket names; ours needs a
  115. # root of at most 17-21, which a Hermes scratch TMPDIR exceeds, so the sticky system root follows.
  116. # A container or macOS has no XDG_RUNTIME_DIR, which is why the shared roots stay as fallbacks.
  117. xdg = [xdg_dir] if (xdg_dir := private_user_runtime_dir()) else []
  118. roots = dict.fromkeys(os.path.realpath(r) for r in (*xdg, socket_safe_tmpdir(), "/tmp")) # no-tmp: ok — AF_UNIX sun_path budget; dir claimed 0700 and ownership-checked
  119. for root in roots:
  120. short = os.path.join(root, f"hbh-{digest}")
  121. if fits_socket_budget(short, budget) and claim_private_dir(short):
  122. return short
  123. return None
  124. def private_user_runtime_dir() -> Optional[str]:
  125. """``$XDG_RUNTIME_DIR`` (a system-unit gateway has none: ``/run/user/<uid>`` then) when it is
  126. what the spec promises: an absolute real directory owned by this uid with no group/other access,
  127. so no other user can pre-create a name inside it."""
  128. getuid = getattr(os, "getuid", None)
  129. if getuid is None:
  130. return None
  131. raw = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{getuid()}"
  132. if not os.path.isabs(raw):
  133. return None
  134. try:
  135. st = os.lstat(raw)
  136. except OSError:
  137. return None
  138. ours = stat.S_ISDIR(st.st_mode) and st.st_uid == getuid()
  139. return raw if ours and not st.st_mode & 0o077 else None
  140. def claim_private_dir(path: str) -> bool:
  141. """Create ``path`` 0700, or accept an existing one only when it is a real directory (not a
  142. symlink) owned by this uid and closed to group/other: the temp root is world-writable, and the
  143. harness resolves symlinks and only chmods a dir it created itself."""
  144. try:
  145. os.mkdir(path, 0o700)
  146. return True
  147. except FileExistsError:
  148. pass
  149. except OSError:
  150. return False
  151. try:
  152. st = os.lstat(path)
  153. except OSError:
  154. return False
  155. return (stat.S_ISDIR(st.st_mode) and st.st_uid == getattr(os, "getuid", lambda: -1)()
  156. and not st.st_mode & 0o077)