feat: agent bridge wayland and gamescope coverage (#406)

* feat: run a guest agent in every session for commands, focus and the Steam client's DevTools

* feat: give the agent bridge game, input, UI and experiment commands behind a Setup toggle

* feat: droiddeckctl commands for the new bridge, a scenario runner and contract tests

* feat: run cleanup steps after every scenario run so a failure cannot leak into the next

* feat: restart a session that died between scenario runs with start --reuse

* fix: give droiddeckctl stop its own, longer wait for the session's logs

* fix: harden debugging tools access and output
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-08 03:50:58 +00:00
1 parent 37e89c5b4d
commit d231564f8e
42 files changed
+3787 -168

No files matched your search

+687
View File
@@ -0,0 +1,687 @@
#!/usr/bin/python3
"""The guest side of the agent bridge (docs/agent-control.md).
Started by droiddeck-session inside the session, so whatever it runs has the session's own
environment: DISPLAY, the games' Xwayland, XDG_RUNTIME_DIR, and the preloads every guest process
gets - which is what lets it reach the Steam client's DevTools port, open to guest processes only.
The app talks to it through files under $BL_LAUNCH_DIR/agent (the session root, the same path on
both sides):
req/<id>.json a request the app wrote (tmp + rename)
resp/<id>.json the answer, written the same way
hello.json this daemon is up: pid, version, what it can do
focus.json gamescope's focus and every server's top-level windows, rewritten on change
cdp-port the client's DevTools port, written by droiddeck-session
Requests: ping, exec, focus, cdp, quit. Each answer is {"ok": true, ...} or
{"ok": false, "error": {"code", "message"}}.
"""
import base64
import json
import math
import os
import selectors
import signal
import socket
import struct
import subprocess
import sys
import threading
import time
import urllib.request
import urllib.parse
from pathlib import Path
VERSION = 1
OUTPUT_CAP = 256 * 1024
REQUEST_CAP = 256 * 1024
RESPONSE_CAP = 1024 * 1024
FOCUS_PROPS = (
"GAMESCOPE_FOCUSED_APP", "GAMESCOPE_FOCUSED_WINDOW", "GAMESCOPE_FOCUSABLE_APPS",
"GAMESCOPE_FOCUSABLE_WINDOWS", "GAMESCOPECTRL_BASELAYER_APPID",
)
WINDOW_PROPS = (
"STEAM_GAME", "WM_STATE", "_NET_WM_PID", "WM_CLASS", "_NET_WM_WINDOW_OPACITY", "STEAM_OVERLAY",
"GAMESCOPE_EXTERNAL_OVERLAY", "STEAM_INPUT_FOCUS", "_NET_WM_STATE",
)
MAP_STATE = ("unmapped", "unviewable", "viewable")
WM_STATES = {0: "withdrawn", 1: "normal", 3: "iconic"}
def log(message):
print("== agent: " + message, flush=True)
def write_json(path, value):
tmp = path.with_name(path.name + ".tmp")
with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600), "w") as stream:
os.fchmod(stream.fileno(), 0o600)
json.dump(value, stream, separators=(",", ":"))
os.replace(tmp, path)
class AgentError(Exception):
def __init__(self, code, message):
super().__init__(message)
self.code = code
# --- X11: just enough of the protocol for root properties, the window tree and events ---------
class X:
"""One connection to an Xwayland server. The rootfs has xprop but no python X library."""
def __init__(self, display):
num = display.lstrip(":").split(".")[0]
last = None
for address in ("\0/tmp/.X11-unix/X" + num, "/tmp/.X11-unix/X" + num):
try:
self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.s.settimeout(3)
self.s.connect(address)
break
except OSError as e:
last = e
self.s.close()
else:
raise last
self.s.sendall(struct.pack("<BxHHHHxx", 0x6C, 11, 0, 0, 0))
head = self._read(8)
if head[0] != 1:
raise OSError("X connection refused on " + display)
setup = self._read(struct.unpack_from("<H", head, 6)[0] * 4)
vendor = struct.unpack_from("<H", setup, 16)[0]
formats = setup[21]
self.root = struct.unpack_from("<I", setup, 32 + (vendor + 3) // 4 * 4 + formats * 8)[0]
self.events = []
self._atoms = {}
self._names = {}
def close(self):
try:
self.s.close()
except OSError:
pass
def _read(self, n):
buf = b""
while len(buf) < n:
chunk = self.s.recv(n - len(buf))
if not chunk:
raise OSError("X connection closed")
buf += chunk
return buf
def request(self, data):
"""Send one request and return its reply, or None for an X error (a window that went)."""
self.s.sendall(data)
while True:
head = self._read(32)
if head[0] == 0:
return None
if head[0] == 1:
return head + self._read(struct.unpack_from("<I", head, 4)[0] * 4)
self.events.append(head)
def next_event(self):
if self.events:
return self.events.pop(0)
while True:
head = self._read(32)
if head[0] > 1:
return head
def atom(self, name):
if name not in self._atoms:
n = name.encode()
pad = (4 - len(n) % 4) % 4
r = self.request(struct.pack("<BBHHxx", 16, 0, 2 + (len(n) + pad) // 4, len(n)) + n + b"\0" * pad)
self._atoms[name] = struct.unpack_from("<I", r, 8)[0] if r else 0
return self._atoms[name]
def atom_name(self, atom):
if atom not in self._names:
r = self.request(struct.pack("<BxHI", 17, 2, atom))
self._names[atom] = r[32:32 + struct.unpack_from("<H", r, 8)[0]].decode(errors="replace") if r else str(atom)
return self._names[atom]
def select(self, window, mask):
self.s.sendall(struct.pack("<BxHIII", 2, 4, window, 0x800, mask))
def children(self, window):
r = self.request(struct.pack("<BxHI", 15, 2, window))
if not r:
return []
n = struct.unpack_from("<H", r, 16)[0]
return list(struct.unpack_from("<%dI" % n, r, 32))
def attributes(self, window):
r = self.request(struct.pack("<BxHI", 3, 2, window))
return (r[26], r[27], struct.unpack_from("<H", r, 12)[0]) if r else None
def geometry(self, window):
r = self.request(struct.pack("<BxHI", 14, 2, window))
return struct.unpack_from("<hhHH", r, 12) if r else None
def prop(self, window, name, length=1024):
atom = self.atom(name)
if not atom:
return None
r = self.request(struct.pack("<BBHIIIII", 20, 0, 6, window, atom, 0, 0, length))
if not r or r[1] == 0:
return None
fmt, n = r[1], struct.unpack_from("<I", r, 16)[0]
data = r[32:32 + n * fmt // 8]
if fmt == 32:
return list(struct.unpack("<%dI" % n, data))
return data
def windows(x):
"""Top-level windows that are mapped or carry an app id: what gamescope picks focus from."""
out = []
for win in x.children(x.root):
attrs = x.attributes(win)
if not attrs:
continue
props = {name: x.prop(win, name) for name in WINDOW_PROPS}
if attrs[0] != 2 and not props["STEAM_GAME"]:
continue
geo = x.geometry(win) or (0, 0, 0, 0)
cls = props["WM_CLASS"]
state = props["WM_STATE"]
entry = {
"window": win,
"map": MAP_STATE[attrs[0]] if attrs[0] < 3 else attrs[0],
"overrideRedirect": bool(attrs[1]),
"inputOnly": attrs[2] == 2,
"geometry": [geo[0], geo[1], geo[2], geo[3]],
"appId": props["STEAM_GAME"][0] if props["STEAM_GAME"] else None,
"wmState": WM_STATES.get(state[0], state[0]) if state else None,
"pid": props["_NET_WM_PID"][0] if props["_NET_WM_PID"] else None,
"class": cls.split(b"\0")[-2].decode(errors="replace") if cls and b"\0" in cls else None,
}
if props["_NET_WM_WINDOW_OPACITY"]:
entry["opacity"] = props["_NET_WM_WINDOW_OPACITY"][0]
for key, name in (("overlay", "STEAM_OVERLAY"), ("externalOverlay", "GAMESCOPE_EXTERNAL_OVERLAY"),
("inputFocus", "STEAM_INPUT_FOCUS")):
if props[name]:
entry[key] = props[name][0]
if props["_NET_WM_STATE"]:
entry["netState"] = [x.atom_name(a).replace("_NET_WM_STATE_", "") for a in props["_NET_WM_STATE"]]
out.append(entry)
return out
def displays():
seen = []
for d in (os.environ.get("DISPLAY"), os.environ.get("STEAM_GAME_DISPLAY_0")):
if d and d not in seen:
seen.append(d)
return seen
def focus_snapshot():
"""gamescope's focus as Steam sees it (root properties on the client's server) and every
server's windows. GAMESCOPE_FOCUSABLE_WINDOWS is the list the client orders the base layer
from: a game missing there stays behind the client however healthy its window looks."""
shown = displays()
if not shown:
raise AgentError("NO_DISPLAY", "This session has no X display")
snap = {"t": int(time.time() * 1000), "displays": {}}
for i, d in enumerate(shown):
x = X(d)
try:
if i == 0:
values = {name: x.prop(x.root, name) for name in FOCUS_PROPS}
trip = values["GAMESCOPE_FOCUSABLE_WINDOWS"] or []
snap["focusedApp"] = (values["GAMESCOPE_FOCUSED_APP"] or [None])[0]
snap["focusedWindow"] = (values["GAMESCOPE_FOCUSED_WINDOW"] or [None])[0]
snap["focusableApps"] = values["GAMESCOPE_FOCUSABLE_APPS"] or []
snap["focusableWindows"] = [
{"window": trip[k], "appId": trip[k + 1], "pid": trip[k + 2]} for k in range(0, len(trip) - 2, 3)
]
snap["baselayerAppIds"] = values["GAMESCOPECTRL_BASELAYER_APPID"] or []
snap["displays"][d] = windows(x)
finally:
x.close()
return snap
class FocusWatcher(threading.Thread):
"""Rewrites focus.json when gamescope's focus properties change, and every few seconds when
the windows do (a window can change without any root property moving)."""
def __init__(self, path):
super().__init__(daemon=True, name="focus")
self.path = path
self.changed = threading.Event()
self.last = None
self.seq = 0
def run(self):
threading.Thread(target=self.listen, daemon=True, name="focus-events").start()
while True:
self.changed.wait(timeout=5)
self.changed.clear()
time.sleep(0.2) # let a burst of property changes settle
try:
snap = focus_snapshot()
except (OSError, AgentError) as e:
log("focus snapshot failed: %s" % e)
time.sleep(2)
continue
body = {k: v for k, v in snap.items() if k != "t"}
if body == self.last:
continue
self.last = body
self.seq += 1
snap["seq"] = self.seq
write_json(self.path, snap)
def listen(self):
while True:
try:
x = X(os.environ["DISPLAY"])
wanted = {x.atom(name) for name in FOCUS_PROPS}
x.select(x.root, 0x400000) # PropertyChangeMask
self.changed.set()
while True:
event = x.next_event()
if event[0] & 0x7F == 28 and struct.unpack_from("<I", event, 8)[0] in wanted:
self.changed.set()
except OSError as e:
log("focus events: %s; reconnecting" % e)
time.sleep(2)
# --- Steam client DevTools (CDP) -----------------------------------------------------------------
class WebSocket:
"""A minimal RFC 6455 client: text frames out, text frames in. Enough for CDP."""
def __init__(self, url, timeout):
target = urllib.parse.urlsplit(url)
if (target.scheme != "ws" or target.hostname not in ("127.0.0.1", "::1", "localhost")
or target.username is not None or target.password is not None or target.fragment):
raise AgentError("INVALID_TARGET", "DevTools targets must use a loopback WebSocket")
hostport = target.netloc
path = target.path or "/"
if target.query:
path += "?" + target.query
host = "127.0.0.1" if target.hostname == "localhost" else target.hostname
self.s = socket.create_connection((host, target.port or 80), timeout=timeout)
try:
self._handshake(path, hostport)
except Exception:
self.s.close()
raise
def _handshake(self, path, hostport):
key = base64.b64encode(os.urandom(16)).decode()
self.s.sendall((
"GET %s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
"Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n" % (path, hostport, key)
).encode())
head = b""
while b"\r\n\r\n" not in head:
chunk = self.s.recv(4096)
if not chunk:
raise OSError("DevTools closed the connection during the handshake")
head += chunk
if len(head) > 16 * 1024:
raise AgentError("RESPONSE_TOO_LARGE", "The DevTools handshake exceeds 16 KiB")
status = head.split(b"\r\n", 1)[0]
if b" 101 " not in status:
raise OSError("DevTools refused the WebSocket: " + status.decode(errors="replace"))
self.buffer = head.split(b"\r\n\r\n", 1)[1]
def _read(self, n):
while len(self.buffer) < n:
chunk = self.s.recv(65536)
if not chunk:
raise OSError("DevTools closed the connection")
self.buffer += chunk
data, self.buffer = self.buffer[:n], self.buffer[n:]
return data
def send(self, text):
payload = text.encode()
header = bytearray([0x81])
n = len(payload)
if n < 126:
header.append(0x80 | n)
elif n < 65536:
header.append(0x80 | 126)
header += struct.pack(">H", n)
else:
header.append(0x80 | 127)
header += struct.pack(">Q", n)
mask = os.urandom(4)
header += mask
self.s.sendall(bytes(header) + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)))
def recv(self):
message = b""
while True:
b0, b1 = self._read(2)
n = b1 & 0x7F
if n == 126:
n = struct.unpack(">H", self._read(2))[0]
elif n == 127:
n = struct.unpack(">Q", self._read(8))[0]
if n > RESPONSE_CAP or len(message) + n > RESPONSE_CAP:
raise AgentError("RESPONSE_TOO_LARGE", "The DevTools response exceeds 1 MiB")
mask = self._read(4) if b1 & 0x80 else None
data = self._read(n)
if mask:
data = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
op = b0 & 0x0F
if op == 8:
raise OSError("DevTools closed the WebSocket")
if op == 9: # ping
continue
if op in (0, 1, 2):
message += data
if b0 & 0x80:
return message.decode(errors="replace")
def close(self):
try:
self.s.close()
except OSError:
pass
def cdp_port(agent_dir):
try:
port = (agent_dir / "cdp-port").read_text().strip()
except OSError:
port = os.environ.get("BL_CDP_PORT", "")
if not port.isdigit():
raise AgentError("NO_DEVTOOLS", "The Steam client's DevTools port is not known (no Steam client in this session yet)")
return int(port)
def cdp_targets(agent_dir, timeout=5):
url = "http://127.0.0.1:%d/json" % cdp_port(agent_dir)
try:
with urllib.request.urlopen(url, timeout=timeout) as r:
data = r.read(RESPONSE_CAP + 1)
if len(data) > RESPONSE_CAP:
raise AgentError("RESPONSE_TOO_LARGE", "The DevTools response exceeds 1 MiB")
return json.loads(data.decode())
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach the client's DevTools at %s: %s" % (url, e))
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15):
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
want = target or "SharedJSContext"
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
if not match:
names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets}))
raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names))
ws = WebSocket(match[0]["webSocketDebuggerUrl"], timeout)
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {
"expression": expression, "returnByValue": True, "awaitPromise": await_promise,
"userGesture": True,
}}))
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
message = json.loads(ws.recv())
if message.get("id") != 1:
continue
if "error" in message:
raise AgentError("CDP_ERROR", json.dumps(message["error"]))
result = message.get("result", {})
if result.get("exceptionDetails"):
details = result["exceptionDetails"]
text = (details.get("exception") or {}).get("description") or details.get("text") or "exception"
raise AgentError("JS_EXCEPTION", text)
value = result.get("result", {})
return {"target": match[0].get("title"), "type": value.get("type"),
"value": value.get("value"), "description": value.get("description")}
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
finally:
ws.close()
# --- Game processes ------------------------------------------------------------------------------
def game_pids(app_id):
"""Our processes started for this Steam app (Steam sets SteamAppId / SteamGameId in their
environment, and Proton's wine processes inherit it)."""
wanted = [("SteamAppId=%s" % app_id).encode(), ("SteamGameId=%s" % app_id).encode()]
me = os.getpid()
pids = []
for entry in os.listdir("/proc"):
if not entry.isdigit() or int(entry) == me:
continue
try:
with open("/proc/%s/environ" % entry, "rb") as f:
env = f.read().split(b"\0")
except OSError:
continue
if any(w in env for w in wanted):
pids.append(int(entry))
return pids
def quit_game(agent_dir, app_id, timeout):
if not str(app_id).isdigit():
raise AgentError("INVALID_APP_ID", "appId must be a decimal Steam app id")
steps = []
if game_pids(app_id):
try:
cdp_eval(agent_dir, "SteamClient.Apps.TerminateApp(%s, false)" % json.dumps(str(app_id)), timeout=5)
steps.append("client")
except AgentError as e:
steps.append("client unavailable: %s" % e)
deadline = time.monotonic() + timeout
while game_pids(app_id) and time.monotonic() < deadline:
time.sleep(0.5)
left = game_pids(app_id)
if left:
steps.append("SIGTERM %s" % left)
for pid in left:
try:
os.kill(pid, signal.SIGTERM)
except OSError:
pass
end = time.monotonic() + 5
while game_pids(app_id) and time.monotonic() < end:
time.sleep(0.5)
left = game_pids(app_id)
if left:
steps.append("SIGKILL %s" % left)
for pid in left:
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
time.sleep(1)
return {"appId": int(app_id), "steps": steps, "remaining": game_pids(app_id)}
# --- Requests ------------------------------------------------------------------------------------
def run_exec(req):
argv = req.get("argv")
if not isinstance(argv, list) or not argv or not all(isinstance(a, str) and "\0" not in a for a in argv):
raise AgentError("INVALID_REQUEST", "exec needs argv, a non-empty list of strings")
timeout = request_timeout(req, 30)
env = dict(os.environ)
extra_env = req.get("env") if req.get("env") is not None else {}
if not isinstance(extra_env, dict) or any("\0" in str(k) or "=" in str(k) or "\0" in str(v) for k, v in extra_env.items()):
raise AgentError("INVALID_REQUEST", "env must be an object with valid environment entries")
env.update({str(k): str(v) for k, v in extra_env.items()})
stdin = req.get("stdin")
if stdin is not None and not isinstance(stdin, str):
raise AgentError("INVALID_REQUEST", "stdin must be a string")
started = time.monotonic()
try:
proc = subprocess.Popen(
argv, cwd=req.get("cwd") or None, env=env, start_new_session=True,
stdin=subprocess.PIPE if stdin is not None else subprocess.DEVNULL,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
except OSError as e:
raise AgentError("EXEC_FAILED", "%s: %s" % (argv[0], e))
captured = {"stdout": bytearray(), "stderr": bytearray()}
truncated = {"stdout": False, "stderr": False}
pending = memoryview(stdin.encode()) if stdin is not None else memoryview(b"")
deadline = started + timeout
timed_out = False
try:
with selectors.DefaultSelector() as selector:
for stream, name in ((proc.stdout, "stdout"), (proc.stderr, "stderr")):
os.set_blocking(stream.fileno(), False)
selector.register(stream, selectors.EVENT_READ, name)
if proc.stdin is not None:
os.set_blocking(proc.stdin.fileno(), False)
if pending:
selector.register(proc.stdin, selectors.EVENT_WRITE, "stdin")
else:
proc.stdin.close()
while selector.get_map() or proc.poll() is None:
remaining = deadline - time.monotonic()
if remaining <= 0:
timed_out = True
break
for key, _ in selector.select(min(0.1, remaining)):
stream, name = key.fileobj, key.data
if name == "stdin":
try:
pending = pending[os.write(stream.fileno(), pending[:65536]):]
except BrokenPipeError:
pending = pending[len(pending):]
if not pending:
selector.unregister(stream)
stream.close()
else:
data = os.read(stream.fileno(), 65536)
if not data:
selector.unregister(stream)
stream.close()
continue
available = OUTPUT_CAP - len(captured[name])
captured[name].extend(data[:available])
truncated[name] |= len(data) > available
if timed_out:
try:
os.killpg(proc.pid, signal.SIGKILL)
except ProcessLookupError:
pass
proc.wait(timeout=5)
finally:
if proc.poll() is None:
try:
os.killpg(proc.pid, signal.SIGKILL)
except ProcessLookupError:
pass
proc.wait(timeout=5)
for stream in (proc.stdin, proc.stdout, proc.stderr):
if stream is not None:
stream.close()
def text(name):
return {"text": captured[name].decode(errors="replace"), "truncated": truncated[name]}
return {"exitCode": proc.returncode, "timedOut": timed_out,
"seconds": round(time.monotonic() - started, 3), "stdout": text("stdout"), "stderr": text("stderr")}
def request_timeout(req, default):
try:
timeout = float(req.get("timeout", default))
except (TypeError, ValueError):
raise AgentError("INVALID_REQUEST", "timeout must be a positive number no greater than 600 seconds")
if not math.isfinite(timeout) or not 0 < timeout <= 600:
raise AgentError("INVALID_REQUEST", "timeout must be a positive number no greater than 600 seconds")
return timeout
def handle(agent_dir, req):
kind = req.get("kind")
if kind == "ping":
return {"pid": os.getpid(), "version": VERSION, "displays": displays()}
if kind == "exec":
return run_exec(req)
if kind == "focus":
return focus_snapshot()
if kind == "cdp":
if req.get("op") == "targets":
return {"targets": [{k: t.get(k) for k in ("title", "url", "type")} for t in cdp_targets(agent_dir)]}
expression = req.get("expression")
if not isinstance(expression, str) or not expression:
raise AgentError("INVALID_REQUEST", "cdp eval needs an expression")
return cdp_eval(agent_dir, expression, req.get("target"), bool(req.get("awaitPromise", True)),
request_timeout(req, 15))
if kind == "quit":
return quit_game(agent_dir, req.get("appId"), request_timeout(req, 15))
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
def answer(agent_dir, path):
rid = path.stem
try:
with path.open("rb") as stream:
data = stream.read(REQUEST_CAP + 1)
if len(data) > REQUEST_CAP:
raise ValueError("The request exceeds 256 KiB")
req = json.loads(data)
if not isinstance(req, dict):
raise ValueError("The request must be a JSON object")
except (OSError, ValueError) as e:
req = None
result = {"ok": False, "error": {"code": "INVALID_REQUEST", "message": str(e)}}
finally:
try:
path.unlink()
except OSError:
pass
if req is not None:
try:
result = dict(handle(agent_dir, req), ok=True)
except AgentError as e:
result = {"ok": False, "error": {"code": e.code, "message": str(e)}}
except Exception as e: # an answer of some kind always goes back
result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
write_json(agent_dir / "resp" / (rid + ".json"), result)
def serve(agent_dir, focus=True, poll=0.1):
(agent_dir / "req").mkdir(parents=True, exist_ok=True)
(agent_dir / "resp").mkdir(parents=True, exist_ok=True)
can_focus = focus and bool(os.environ.get("DISPLAY"))
if can_focus:
FocusWatcher(agent_dir / "focus.json").start()
write_json(agent_dir / "hello.json", {"pid": os.getpid(), "version": VERSION, "started": int(time.time() * 1000),
"displays": displays(), "focus": can_focus})
log("serving %s (focus %s)" % (agent_dir, "on" if can_focus else "off"))
taken = set()
while True:
for path in sorted((agent_dir / "req").glob("*.json")):
if path.name in taken:
continue
taken.add(path.name)
threading.Thread(target=lambda p=path: (answer(agent_dir, p), taken.discard(p.name)),
daemon=True, name="req").start()
time.sleep(poll)
def main(argv):
base = os.environ.get("BL_LAUNCH_DIR")
if not base:
print("BL_LAUNCH_DIR is not set", file=sys.stderr)
return 2
serve(Path(base) / "agent", focus="--no-focus" not in argv)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
@@ -97,6 +97,14 @@ export GAMESCOPE_FORCE_VULKAN_REALTIME=${BL_GAMESCOPE_REALTIME:-0}
# A sleep that starts no process. Under proot every exec is a traced execve plus the loader's
# opens and maps, and the watchers below poll for the whole session: `sleep 1` in a loop was 60
# execs a minute each. read -t on a pipe nothing ever writes to waits in bash itself.
# The agent bridge's guest side (docs/agent-control.md): runs what the app's agent provider asks
# for inside this session and publishes gamescope's focus. Its files live under the session root
# ($BL_LAUNCH_DIR/agent), which the app empties before each session.
start_agent() {
[ -n "${BL_LAUNCH_DIR:-}" ] && [ -x /usr/local/bin/droiddeck-agent ] || return 0
mkdir -p "$BL_LAUNCH_DIR/agent"
/usr/local/bin/droiddeck-agent "$@" 2>&1 &
}
nap() {
[ -n "${bl_nap_fd:-}" ] || exec {bl_nap_fd}<> <(:)
read -r -t "$1" -u "$bl_nap_fd" _ 2>/dev/null || :
@@ -166,6 +174,7 @@ if [ -z "${BL_INSIDE:-}" ]; then
# into the app's: no gamescope in between.
if [ "$mode" = lxqt ]; then
step "starting the desktop"
start_agent --no-focus
[ -x /usr/local/bin/droiddeck-desktop ] || { echo "== the desktop package is not installed"; exit 66; }
cores=$(program_cores)
if [ -n "$cores" ]; then
@@ -284,6 +293,8 @@ if [ -n "${BL_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard
/usr/local/bin/droiddeck-clipboard "$BL_ANDROID_CLIPBOARD" &
fi
start_agent
case $mode in
desktop)
exec pcmanfm
@@ -710,6 +721,8 @@ BUSCONF
export BL_CDP_GUARD=$BL_CDP_PORT
echo "== steam: devtools port $BL_CDP_PORT, guest processes only"
fi
# The agent bridge drives the client through it (droiddeck-agent's cdp requests).
[ -n "${BL_LAUNCH_DIR:-}" ] && mkdir -p "$BL_LAUNCH_DIR/agent" && echo "$BL_CDP_PORT" > "$BL_LAUNCH_DIR/agent/cdp-port"
droiddeck-steam-compat "$steam_root" 2>&1 &
# The client exits 42 when it has updated itself and wants a fresh start (steam.sh does this).
# BL_STEAM_UI=desktop = the client's desktop UI (a window, the library as a list), which the
+65 -22
View File
@@ -41,6 +41,19 @@ static const char *net_dir(void) {
return dir;
}
static int loopback_family(const struct sockaddr *address, socklen_t length) {
if (address && address->sa_family == AF_INET && length >= sizeof(struct sockaddr_in)) {
return ((const struct sockaddr_in *)address)->sin_addr.s_addr == htonl(INADDR_LOOPBACK) ? AF_INET : 0;
}
if (address && address->sa_family == AF_INET6 && length >= sizeof(struct sockaddr_in6)) {
const struct in6_addr *ip = &((const struct sockaddr_in6 *)address)->sin6_addr;
if (IN6_IS_ADDR_LOOPBACK(ip)) return AF_INET6;
if (IN6_IS_ADDR_V4MAPPED(ip) && ip->s6_addr[12] == 127 && ip->s6_addr[13] == 0 &&
ip->s6_addr[14] == 0 && ip->s6_addr[15] == 1) return AF_INET;
}
return 0;
}
/* Record that this process owns a loopback socket on its local port; peer is the far end's port,
* 0 for a listening socket. */
static void record_port(int fd, unsigned peer) {
@@ -49,12 +62,11 @@ static void record_port(int fd, unsigned peer) {
if (getsockname(fd, (struct sockaddr *)&ss, &len) != 0) {
return;
}
int family = loopback_family((struct sockaddr *)&ss, len);
if (!family) return;
unsigned port;
if (ss.ss_family == AF_INET) {
struct sockaddr_in *in = (struct sockaddr_in *)&ss;
if (in->sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
return;
}
port = ntohs(in->sin_port);
} else if (ss.ss_family == AF_INET6) {
port = ntohs(((struct sockaddr_in6 *)&ss)->sin6_port);
@@ -64,14 +76,21 @@ static void record_port(int fd, unsigned peer) {
if (port == 0) {
return;
}
struct stat socket_stat;
if (fstat(fd, &socket_stat) != 0) return;
char path[300];
snprintf(path, sizeof(path), "%s/p%u", net_dir(), port);
char line[64];
int n = snprintf(line, sizeof(line), "%d %d %d %u\n", (int)getpid(), (int)getppid(), (int)getuid(), peer);
int out = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
char staged[360];
snprintf(staged, sizeof(staged), "%s.tmp.%d.%d", path, (int)getpid(), fd);
char line[128];
int n = snprintf(line, sizeof(line), "%d %d %d %u %d %llu %d\n", (int)getpid(), (int)getppid(),
(int)getuid(), peer, fd, (unsigned long long)socket_stat.st_ino, family);
int out = open(staged, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0600);
if (out >= 0) {
if (write(out, line, n) != n) { /* best effort */ }
int complete = write(out, line, n) == n;
close(out);
if (complete) rename(staged, path);
unlink(staged);
}
}
@@ -98,6 +117,7 @@ typedef int (*bind_fn)(int, const struct sockaddr *, socklen_t);
typedef int (*listen_fn)(int, int);
typedef int (*connect_fn)(int, const struct sockaddr *, socklen_t);
typedef int (*accept4_fn)(int, struct sockaddr *, socklen_t *, int);
static unsigned guarded_port(void);
/* udevmon.c: a stand-in for the netlink socket the sandbox refuses, bound here without the kernel. */
__attribute__((visibility("hidden"))) int bl_udevmon_stand_in(int fd);
@@ -112,6 +132,18 @@ int bind(int fd, const struct sockaddr *addr, socklen_t len) {
}
return 0;
}
struct sockaddr_storage local;
unsigned guarded = guarded_port();
if (guarded && addr_port(addr, len) == guarded && len <= sizeof(local)) {
memcpy(&local, addr, len);
if (addr->sa_family == AF_INET) {
((struct sockaddr_in *)&local)->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr = (struct sockaddr *)&local;
} else if (addr->sa_family == AF_INET6) {
((struct sockaddr_in6 *)&local)->sin6_addr = in6addr_loopback;
addr = (struct sockaddr *)&local;
}
}
int ret = real(fd, addr, len);
if (ret == 0) record_port(fd, 0);
return ret;
@@ -135,22 +167,20 @@ static unsigned local_port(int fd) {
}
static void bind_before_loopback_connect(int fd, const struct sockaddr *addr, socklen_t len) {
if (!addr || addr->sa_family != AF_INET || len < sizeof(struct sockaddr_in) ||
((const struct sockaddr_in *)addr)->sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
return;
}
if (!loopback_family(addr, len)) return;
struct sockaddr_storage ss;
socklen_t slen = sizeof(ss);
if (getsockname(fd, (struct sockaddr *)&ss, &slen) != 0 || ss.ss_family != AF_INET ||
((struct sockaddr_in *)&ss)->sin_port != 0) {
if (getsockname(fd, (struct sockaddr *)&ss, &slen) != 0 || ss.ss_family != addr->sa_family ||
addr_port((struct sockaddr *)&ss, slen) != 0) {
return;
}
struct sockaddr_in local;
memset(&local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
struct sockaddr_storage local;
if (len > sizeof(local)) return;
memcpy(&local, addr, len);
if (addr->sa_family == AF_INET) ((struct sockaddr_in *)&local)->sin_port = 0;
else ((struct sockaddr_in6 *)&local)->sin6_port = 0;
int saved = errno;
bind(fd, (struct sockaddr *)&local, sizeof(local));
bind(fd, (struct sockaddr *)&local, len);
errno = saved;
}
@@ -165,6 +195,11 @@ static unsigned guarded_port(void) {
}
static int guest_peer(int fd) {
struct sockaddr_storage address;
socklen_t length = sizeof(address);
if (getpeername(fd, (struct sockaddr *)&address, &length) != 0) return 0;
int family = loopback_family((struct sockaddr *)&address, length);
if (!family) return 0;
unsigned peer = peer_port(fd);
if (peer == 0) {
return 0;
@@ -179,26 +214,34 @@ static int guest_peer(int fd) {
if (in < 0) {
return 0;
}
char buf[64];
char buf[128];
int n = read(in, buf, sizeof(buf) - 1);
close(in);
if (n <= 0) {
return 0;
}
buf[n] = '\0';
int pid = atoi(buf);
return pid > 0 && (kill(pid, 0) == 0 || errno != ESRCH);
int pid, parent, uid, descriptor, recorded_family;
unsigned destination;
unsigned long long inode;
if (sscanf(buf, "%d %d %d %u %d %llu %d", &pid, &parent, &uid, &destination, &descriptor,
&inode, &recorded_family) != 7 || pid <= 0 || descriptor < 0 || destination != guarded_port() ||
recorded_family != family) return 0;
snprintf(path, sizeof(path), "/proc/%d/fd/%d", pid, descriptor);
return stat(path, &st) == 0 && S_ISSOCK(st.st_mode) && (unsigned long long)st.st_ino == inode;
}
int connect(int fd, const struct sockaddr *addr, socklen_t len) {
static connect_fn real;
if (!real) real = (connect_fn)dlsym(RTLD_NEXT, "connect");
bind_before_loopback_connect(fd, addr, len);
unsigned peer = loopback_family(addr, len) ? addr_port(addr, len) : 0;
if (peer) record_port(fd, peer);
int ret = real(fd, addr, len);
if (ret == 0 || errno == EINPROGRESS) {
/* The caller goes on to test for EINPROGRESS, which the bookkeeping must not disturb. */
int saved = errno;
record_port(fd, addr_port(addr, len));
record_port(fd, peer);
errno = saved;
}
return ret;