Merge remote-tracking branch 'origin/main' into feat/steam-touch-controller

This commit is contained in:
maxjivi05 committed 2026-10-08 14:57:02 -04:00
commit 1b31899896
92 files changed
+6434 -2865

No files matched your search

+3 -34
View File
@@ -16,11 +16,6 @@ export QT_QPA_PLATFORMTHEME=lxqt
# The prefs for this are only advisory and a profile can override them; the environment is not.
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
# Firefox seals the size of the shared memory it hands a tab; on Android 16 (Galaxy S25/S26,
# RedMagic) adding the seal fails, Firefox only warns, and the tab refuses the unsealed memory
# ("Shared memory PlatformHandle is not safe to map") and dies on signal 11 - every page. Firefox's
# own switch skips the seals.
export MOZ_SHM_NO_SEALS=1
# pixman composites in software and gives programs shm buffers only, so a Vulkan program on it
# fails at its swapchain. vulkan (or gles2) composite on the GPU and give programs DMA-BUFs, but
# stock wlroots allocates through gbm on a real DRM node and the KGSL stand-in is not one ("unable
@@ -89,35 +84,9 @@ fi
# already running and exit without a word - a desktop with a wallpaper and nothing on it.
# Only the app's own compositor socket (wayland-0) is kept.
find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' -exec rm -rf {} + 2>/dev/null
# fontconfig's rules (sans-serif -> DejaVu Sans and the rest) live as links in /etc/fonts/conf.d,
# and the rootfs has none: applications then find fonts but no default font. Firefox logs
# "no fonts" and draws pages without text.
if [ -d /usr/share/fontconfig/conf.default ] && ! ls /etc/fonts/conf.d/*.conf 2>/dev/null | grep -qv droiddeck; then
for f in /usr/share/fontconfig/conf.default/*.conf; do ln -sf "$f" /etc/fonts/conf.d/; done
echo "== fontconfig: linked $(ls /etc/fonts/conf.d/*.conf | wc -l) default rules"
fi
# Those rules map sans-serif and friends onto whatever a full distribution installs, and this
# rootfs has one family. Naming it outright is what gives every toolkit a default font: without
# one Gecko reports "no fonts" with families found, and draws pages with no text at all.
if [ ! -f /etc/fonts/local.conf ]; then
{ echo '<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd"><fontconfig>'
for generic in sans-serif sans serif monospace mono cursive fantasy system-ui ui-sans-serif; do
case $generic in
serif) face="DejaVu Serif" ;;
mono*|ui-mono) face="DejaVu Sans Mono" ;;
*) face="DejaVu Sans" ;;
esac
printf '<alias binding="weak"><family>%s</family><prefer><family>%s</family></prefer></alias>\n' "$generic" "$face"
done
echo '</fontconfig>'
} > /etc/fonts/local.conf
echo "== fontconfig: wrote local.conf (DejaVu as the default family)"
fi
# The cache in the image was built before those rules existed; rebuild it once, and only once.
if [ ! -f /var/cache/fontconfig/.droiddeck-built ] && command -v fc-cache >/dev/null 2>&1; then
fc-cache -f >/dev/null 2>&1 && touch /var/cache/fontconfig/.droiddeck-built
echo "== fontconfig: cache rebuilt, default sans is $(fc-match sans-serif 2>/dev/null)"
fi
# Fontconfig defaults and Android language fallbacks are set up by droiddeck-session before this
# script or any desktop program starts. The generated defaults live in conf.d, leaving local.conf
# available for the user's own final overrides.
# The menu's "Steam" / "Steam Big Picture" entries and one entry per installed game: all of them
# hand off to the app (droiddeck-steam-launch), since the client cannot draw on this desktop.
export BL_DESKTOP=1
+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:]))
@@ -4,13 +4,14 @@
# Flathub as the remote, this device's architecture.
#
# droiddeck-flatpak install <app-id> the app and whatever runtimes it needs
# droiddeck-flatpak install-bundle <file> a .flatpak file, its runtimes from Flathub
# droiddeck-flatpak uninstall <app-id> the app, then runtimes nothing uses any more
# droiddeck-flatpak update [<app-id>] one app, or everything with an update
# droiddeck-flatpak updates what has one (a "updates" line)
#
# Lines: {"e":"op","i":1,"n":3,"kind":"install","ref":"..."} as each step starts,
# {"e":"progress","i":1,"n":3,"percent":45,"status":"..."} while it runs,
# {"e":"error","message":"..."} and {"e":"done"} at the end. Exit status 0 on success.
# {"e":"error","message":"..."} and {"e":"done"} at the end (with "id" for a bundle). Exit status 0 on success.
import json
import os
import sys
@@ -20,7 +21,7 @@ os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/droiddeck-bwrap")
import gi # noqa: E402
gi.require_version("Flatpak", "1.0")
from gi.repository import Flatpak, GLib # noqa: E402
from gi.repository import Flatpak, Gio, GLib # noqa: E402
REMOTE = "flathub"
@@ -158,6 +159,29 @@ def install(app_id):
return rc
def install_bundle(path):
"""A single-file bundle (flatpak build-bundle), for apps Flathub does not carry."""
inst = installation()
bundle = Gio.File.new_for_path(path)
try:
app_id = Flatpak.BundleRef.new(bundle).get_name()
except GLib.Error as err:
emit(e="error", message="%s is not a Flatpak bundle (%s)" % (os.path.basename(path), err.message))
return 1
if app_ref(inst, app_id) is not None:
emit(e="done", id=app_id, note="already installed")
return 0
t, state = transaction(inst)
t.add_install_bundle(bundle, None)
rc = run(t, state, report_done=False)
if rc == 0 and app_ref(installation(), app_id) is None:
emit(e="error", message="%s did not install; see flatpak-install-bundle.log" % app_id)
return 1
if rc == 0:
emit(e="done", id=app_id)
return rc
def uninstall(app_id):
inst = installation()
ref = app_ref(inst, app_id)
@@ -216,20 +240,22 @@ def updates():
def main():
if len(sys.argv) < 2:
sys.stderr.write(__doc__ or "usage: droiddeck-flatpak install|uninstall|update|updates [app-id]\n")
sys.stderr.write(__doc__ or "usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates [app-id|file]\n")
return 2
cmd, args = sys.argv[1], sys.argv[2:]
if cmd in ("install", "update"):
if cmd in ("install", "install-bundle", "update"):
prepare_rootfs()
if cmd == "install" and args:
return install(args[0])
if cmd == "install-bundle" and args:
return install_bundle(args[0])
if cmd == "uninstall" and args:
return uninstall(args[0])
if cmd == "update":
return update(args[0] if args else None)
if cmd == "updates":
return updates()
sys.stderr.write("usage: droiddeck-flatpak install|uninstall|update|updates [app-id]\n")
sys.stderr.write("usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates [app-id|file]\n")
return 2
+46
View File
@@ -0,0 +1,46 @@
#!/bin/bash
# DroidDeck's fontconfig setup for the Linux runtime. The rootfs ships DejaVu alone and no rules
# for a default family: applications then find fonts but no default, and Firefox logs "no fonts"
# and draws pages without text. DejaVu also has no CJK, Thai or Arabic glyphs, so those draw as
# tofu boxes. The app binds Android's fonts for the session, which adds language-specific fallbacks
# separately. This script links fontconfig's default rules and writes generic DejaVu aliases to an
# owned conf.d file. Fontconfig reads local.conf afterward, so user overrides keep precedence and
# are never replaced.
# The first argument is the root to set up, "/" in a session; the tests point it at a temp tree.
set -u
root=${1:-/}
root=${root%/}
# "/" strips to empty above; put it back so the paths below read as absolute and the test for a
# real session ("/") still holds.
[ -n "$root" ] || root=/
conf_dir=$root/etc/fonts
defaults_dir=$root/usr/share/fontconfig/conf.default
mkdir -p "$conf_dir/conf.d" 2>/dev/null
# The default rules (sans-serif -> DejaVu Sans and the rest) live as links in /etc/fonts/conf.d,
# and the rootfs has none. Linked by name, so a file we ship is never overwritten.
if [ -d "$defaults_dir" ]; then
for f in "$defaults_dir"/*.conf; do
[ -e "$f" ] || continue
[ -e "$conf_dir/conf.d/${f##*/}" ] || ln -sf "$f" "$conf_dir/conf.d/${f##*/}"
done
fi
owned_conf=$conf_dir/conf.d/65-droiddeck-default-fonts.conf
{
echo '<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd"><fontconfig>'
for generic in sans-serif sans serif monospace mono cursive fantasy system-ui ui-sans-serif; do
case $generic in
serif) face="DejaVu Serif" ;;
mono*|ui-mono) face="DejaVu Sans Mono" ;;
*) face="DejaVu Sans" ;;
esac
printf '<alias binding="weak"><family>%s</family><prefer><family>%s</family></prefer></alias>\n' "$generic" "$face"
done
echo '</fontconfig>'
} > "$owned_conf.new"
if ! cmp -s "$owned_conf.new" "$owned_conf" 2>/dev/null; then
mv -f "$owned_conf.new" "$owned_conf"
echo "== fontconfig: wrote DejaVu defaults"
fi
rm -f "$owned_conf.new"
@@ -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 || :
@@ -136,6 +144,9 @@ program_cores() {
}
if [ -z "${BL_INSIDE:-}" ]; then
# Install the shared default-family aliases before Steam, gamescope or the desktop queries fonts.
/usr/local/bin/droiddeck-fonts 2>&1 | sed 's/^/[fonts] /'
# Android's directory binding and language-specific family matches handle CJK and Thai fonts.
device_fonts=/usr/local/share/fonts/android
if [ -d "$device_fonts" ] && [ -d /etc/fonts/conf.d ] && command -v fc-cache >/dev/null 2>&1; then
fonts_rules=$(
@@ -166,6 +177,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 +296,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 +724,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
@@ -206,7 +206,7 @@ BL_DIRECTAUDIO_SETUP = """
bl_directaudio() {
base=$1
[ -n "${BL_DIRECTAUDIO:-}" ] || return 0
[ -d "$BL_DIRECTAUDIO/lib/wine" ] || return 0
[ -d "$BL_DIRECTAUDIO" ] || return 0
version=$("$base/files/bin-arm64/wine" --version 2>/dev/null)
major=${version#wine-}
major=${major%%.*}
@@ -214,10 +214,32 @@ bl_directaudio() {
echo "droiddeck-proton: DirectAudio left off - it is built for Wine 11 and this Proton is '${version:-unknown}'. Pairing them would be silent rather than broken, so it is not worth guessing." >&2
return 0
fi
# Two builds of the driver ship, one per Wine audio interface, and both Wines call themselves
# 11.0: the private mmdevapi table is not versioned, and the wrong set plays silence, not an
# error. Proton's own winepulse.so tells them apart - it imports PsCreateSystemThread only on
# the system-thread table (Proton-CachyOS), never on the classic one (Valve, GE-Proton).
winepulse="$base/files/lib/wine/aarch64-unix/winepulse.so"
if [ ! -f "$winepulse" ]; then
echo "droiddeck-proton: DirectAudio left off - no winepulse.so to read this Proton's audio interface from" >&2
return 0
fi
if grep -aq PsCreateSystemThread "$winepulse"; then set=linux-wine11-systhread; else set=linux-wine11; fi
da="$BL_DIRECTAUDIO/$set"
if [ ! -d "$da/lib/wine" ]; then
echo "droiddeck-proton: DirectAudio left off - no driver set for the $set interface is staged" >&2
return 0
fi
# Wine appends the per-architecture subdirectory to each entry, so the directory holding
# aarch64-unix/ and aarch64-windows/ is what goes here.
WINEDLLPATH="$BL_DIRECTAUDIO/lib/wine${WINEDLLPATH:+:$WINEDLLPATH}"
WINEDLLPATH="$da/lib/wine${WINEDLLPATH:+:$WINEDLLPATH}"
export WINEDLLPATH
# Proton-CachyOS's launcher sets WINE_AUDIO_DRIVER=pulse,alsa (setdefault, so an existing value
# wins), and its mmdevapi reads that variable BEFORE the registry - so the selection below was
# being overridden to pulse on every CachyOS game. Valve's and GE's mmdevapi do not read the
# variable at all and take the registry, which is why both are done. A value the user set for
# the game still wins: the per-game environment is applied after this.
WINE_AUDIO_DRIVER="directaudio,pulse"
export WINE_AUDIO_DRIVER
# mmdevapi only tries the drivers named in the registry; its built-in list is pulse, alsa, oss and
# coreaudio and knows nothing about this one. The key is appended to the prefix's user.reg rather
# than written with `wine reg`, which would start a wineserver here just to set one value.
@@ -226,25 +248,36 @@ bl_directaudio() {
if [ -f "$reg" ]; then
for pair in system32:aarch64-windows syswow64:i386-windows; do
dir="$pfx/drive_c/windows/${pair%%:*}"
src="$BL_DIRECTAUDIO/lib/wine/${pair#*:}/winedirectaudio.drv"
src="$da/lib/wine/${pair#*:}/winedirectaudio.drv"
if [ -d "$dir" ] && [ -f "$src" ] && [ "$(readlink "$dir/winedirectaudio.drv" 2>/dev/null)" != "$src" ]; then
ln -sfn "$src" "$dir/winedirectaudio.drv.bl-new" && mv -f "$dir/winedirectaudio.drv.bl-new" "$dir/winedirectaudio.drv"
fi
done
key='[Software\\\\Wine\\\\Drivers]'
if [ "$(readlink "$pfx/drive_c/windows/system32/winedirectaudio.drv" 2>/dev/null)" != "$BL_DIRECTAUDIO/lib/wine/aarch64-windows/winedirectaudio.drv" ]; then
if [ "$(readlink "$pfx/drive_c/windows/system32/winedirectaudio.drv" 2>/dev/null)" != "$da/lib/wine/aarch64-windows/winedirectaudio.drv" ]; then
echo "droiddeck-proton: DirectAudio could not be placed in the prefix; Proton's own audio stays" >&2
elif ! BL_KEY="$key" awk 'index($0, "[") == 1 { inside = index($0, ENVIRON["BL_KEY"] " ") == 1 } inside && index($0, "\\"Audio\\"=") == 1 { last = $0 } END { exit last != "\\"Audio\\"=\\"directaudio,pulse\\"" }' "$reg" 2>/dev/null; then
printf '\\n%s %s\\n"Audio"="directaudio,pulse"\\n' "$key" "$(date +%s)" >> "$reg"
echo "droiddeck-proton: DirectAudio selected in the prefix" >&2
# Steam runs this tool several times per launch (getcompatpath, run, waitforexitandrun); a
# wineserver from an earlier verb that still holds the registry saves its own copy on exit
# and drops this line. Said out loud so a game that stays on pulse once is explained; it
# takes on the next launch. (Writing through the live server with a bare `wine reg add` was
# tried and withdrawn: a second Wine invocation inside Steam's launch sequence is not safe.)
srv="${BL_WINE_SERVER_BASE:-/tmp/.wine-$(id -u)}/server-$(printf '%x-%x' $(stat -c '%d %i' "$pfx" 2>/dev/null || echo 0 0))/socket"
if [ -S "$srv" ]; then
echo "droiddeck-proton: a wineserver is already running for this prefix; DirectAudio may only engage on the next launch" >&2
fi
fi
else
# A prefix that does not exist yet is created by Proton moments from now, after this runs, so
# the key lands on the NEXT launch of that game. Said out loud because silent audio on a first
# launch would otherwise look like a fault.
# the value lands on the NEXT launch of that game. Said out loud so a first launch on Proton's
# own audio does not look like a fault. (Having Proton create the prefix from here first was
# tried and withdrawn: a second Proton run inside Steam's launch sequence got the launch
# aborted - Steam games bounced back to their page with a half-made prefix.)
echo "droiddeck-proton: no prefix yet - DirectAudio takes effect the next time this game starts" >&2
fi
echo "droiddeck-proton: DirectAudio ready (Wine $major)" >&2
echo "droiddeck-proton: DirectAudio ready (Wine $major, $set)" >&2
}
"""
+811
View File
@@ -0,0 +1,811 @@
/*
* The Steam client lists a whole content directory about ten times per file it creates, moves or
* deletes, to match names case-insensitively. On Android's FUSE storage that made reserving space
* quadratic. Listings under steamapps/ on FUSE are kept for at most DIR_TTL_NS and dropped on any
* inotify event the client's own patched changes don't account for; directory timestamps alone
* can't be trusted, as NTFS volumes report whole seconds. BL_NO_DIR_CACHE=1 turns it off.
*/
#define _GNU_SOURCE
#include <dirent.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/inotify.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <time.h>
#include <unistd.h>
#define DIR_TTL_NS 5000000000LL
#define MAX_LISTINGS 16
#define MAX_ENTRIES 100000
#define MAX_HANDLES 64
#define FUSE_MAGIC 0x65735546
#define WATCHED (IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF | IN_MOVE_SELF | IN_ONLYDIR)
/* The client is 64-bit; 32-bit builds only pass creates through. */
#if __SIZEOF_POINTER__ == 8
_Static_assert(sizeof(struct dirent) == sizeof(struct dirent64), "dirent layouts differ");
struct entry { ino_t ino; unsigned char type; char *name; };
struct listing {
dev_t dev;
ino_t ino;
struct timespec mtime, ctime;
off_t size;
nlink_t nlink;
long long filled;
long long used;
int refs;
int detached;
int wd;
size_t n, cap;
struct entry *e;
char *recs;
size_t len;
};
struct handle {
struct listing *snap;
struct listing *fill;
DIR *real;
size_t pos;
int fd;
int wd;
int dirty;
char *path;
struct dirent64 out;
};
struct expect { int wd; uint32_t mask; const char *name; };
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t oplock = PTHREAD_MUTEX_INITIALIZER;
static struct listing *table[MAX_LISTINGS];
static struct handle *handles[MAX_HANDLES];
static int high_water;
static int cached_listings;
static int changing;
static int notify = -1;
static int forked;
static struct { dev_t dev; int fuse; } devs[8];
static int ndevs;
static long long now_ns(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC_COARSE, &t);
return (long long)t.tv_sec * 1000000000LL + t.tv_nsec;
}
/* A child shares the parent's inotify queue, so it stops keeping listings. */
static void after_fork(void) {
pthread_mutex_init(&lock, NULL);
pthread_mutex_init(&oplock, NULL);
forked = 1;
}
static int enabled(void) {
static int cached = -1;
if (cached < 0) {
const char *off = getenv("BL_NO_DIR_CACHE");
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
strstr(program_invocation_name, "steamrtarm64") != NULL && !(off && strcmp(off, "1") == 0);
if (cached) pthread_atfork(NULL, NULL, after_fork);
}
return cached && !forked;
}
static int eligible(const char *path) {
if (path == NULL || path[0] != '/' || !enabled()) return 0;
const char *s = strstr(path, "/steamapps");
return s && (s[10] == '/' || s[10] == 0);
}
static int on_fuse(dev_t dev, const char *path) {
pthread_mutex_lock(&lock);
for (int i = 0; i < ndevs; i++) {
if (devs[i].dev == dev) {
int fuse = devs[i].fuse;
pthread_mutex_unlock(&lock);
return fuse;
}
}
pthread_mutex_unlock(&lock);
struct statfs fs;
int saved = errno;
int fuse = statfs(path, &fs) == 0 && (unsigned long)fs.f_type == FUSE_MAGIC;
errno = saved;
pthread_mutex_lock(&lock);
if (ndevs < 8) {
devs[ndevs].dev = dev;
devs[ndevs].fuse = fuse;
ndevs++;
}
pthread_mutex_unlock(&lock);
return fuse;
}
static int same(const struct listing *l, const struct stat *st) {
return l->ino == st->st_ino && l->dev == st->st_dev && l->size == st->st_size && l->nlink == st->st_nlink &&
l->mtime.tv_sec == st->st_mtim.tv_sec && l->mtime.tv_nsec == st->st_mtim.tv_nsec &&
l->ctime.tv_sec == st->st_ctim.tv_sec && l->ctime.tv_nsec == st->st_ctim.tv_nsec;
}
static void stamp(struct listing *l, const struct stat *st) {
l->dev = st->st_dev;
l->ino = st->st_ino;
l->size = st->st_size;
l->nlink = st->st_nlink;
l->mtime = st->st_mtim;
l->ctime = st->st_ctim;
}
static void destroy(struct listing *l) {
for (size_t i = 0; i < l->n; i++) free(l->e[i].name);
free(l->e);
free(l->recs);
free(l);
}
static void unref(struct listing *l) {
if (--l->refs == 0 && l->detached) destroy(l);
}
/* The rest is called with lock held. */
static void release(int wd) {
if (wd < 0 || notify < 0) return;
for (int i = 0; i < MAX_LISTINGS; i++)
if (table[i] && table[i]->wd == wd) return;
for (int i = 0; i < high_water; i++)
if (handles[i] && handles[i]->wd == wd) return;
inotify_rm_watch(notify, wd);
}
static void detach(struct listing *l) {
__atomic_sub_fetch(&cached_listings, 1, __ATOMIC_RELEASE);
l->detached = 1;
if (l->refs == 0) destroy(l);
}
/* Takes the listing out of the table; freed now or when its last reader closes. */
static void drop(int slot) {
struct listing *l = table[slot];
int wd = l->wd;
table[slot] = NULL;
detach(l);
release(wd);
}
static void changed(int wd) {
for (int i = 0; i < MAX_LISTINGS; i++)
if (table[i] && (table[i]->wd == wd || wd < 0)) drop(i);
for (int i = 0; i < high_water; i++)
if (handles[i] && (handles[i]->wd == wd || wd < 0)) __atomic_store_n(&handles[i]->dirty, 1, __ATOMIC_RELAXED);
}
/* Applies queued events; the expected ones are the client's own changes, already patched in. */
static void pump(struct expect *x, int nx) {
char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event))));
if (notify < 0 || forked) return;
int saved = errno;
for (;;) {
ssize_t n = read(notify, buf, sizeof(buf));
if (n <= 0) {
if (n < 0 && errno != EAGAIN && errno != EINTR) {
notify = -2;
changed(-1);
}
break;
}
for (char *p = buf; p < buf + n;) {
struct inotify_event *ev = (struct inotify_event *)p;
p += sizeof(*ev) + ev->len;
if (ev->mask & IN_Q_OVERFLOW) {
changed(-1);
continue;
}
int k = 0;
while (k < nx && !(x[k].wd == ev->wd && (ev->mask & x[k].mask) && ev->len && strcmp(ev->name, x[k].name) == 0)) k++;
if (k < nx) {
x[k].wd = -1;
for (int i = 0; i < high_water; i++)
if (handles[i] && handles[i]->wd == ev->wd) __atomic_store_n(&handles[i]->dirty, 1, __ATOMIC_RELAXED);
} else {
changed(ev->wd);
}
}
}
errno = saved;
}
static int watch(const char *path) {
if (notify == -1) notify = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if (notify < 0) {
notify = -2;
return -1;
}
int saved = errno;
int wd = inotify_add_watch(notify, path, WATCHED);
errno = saved;
return wd;
}
static int find(dev_t dev, ino_t ino) {
for (int i = 0; i < MAX_LISTINGS; i++)
if (table[i] && table[i]->dev == dev && table[i]->ino == ino) return i;
return -1;
}
static int push(struct listing *l, ino_t ino, unsigned char type, const char *name) {
if (l->n == l->cap) {
size_t cap = l->cap ? l->cap * 2 : 256;
struct entry *e = realloc(l->e, cap * sizeof(*e));
if (e == NULL) return -1;
l->e = e;
l->cap = cap;
}
char *copy = strdup(name);
if (copy == NULL) return -1;
l->e[l->n++] = (struct entry){ino, type, copy};
return 0;
}
static void install(struct listing *l) {
l->detached = 0;
__atomic_add_fetch(&cached_listings, 1, __ATOMIC_RELEASE);
int slot = find(l->dev, l->ino);
if (slot >= 0) {
struct listing *old = table[slot];
table[slot] = l;
detach(old);
if (old->wd != l->wd) release(old->wd);
return;
}
int victim = -1;
for (int i = 0; i < MAX_LISTINGS; i++) {
if (table[i] == NULL) { victim = i; break; }
if (victim < 0 || table[i]->used < table[victim]->used) victim = i;
}
if (table[victim]) drop(victim);
table[victim] = l;
}
static int registered(DIR *d) {
int n = __atomic_load_n(&high_water, __ATOMIC_ACQUIRE);
for (int i = 0; i < n; i++)
if (__atomic_load_n(&handles[i], __ATOMIC_ACQUIRE) == (struct handle *)d) return i;
return -1;
}
static DIR *wrap(struct handle *h) {
for (int i = 0; i < MAX_HANDLES; i++) {
if (handles[i] == NULL) {
__atomic_store_n(&handles[i], h, __ATOMIC_RELEASE);
if (i >= high_water) __atomic_store_n(&high_water, i + 1, __ATOMIC_RELEASE);
return (DIR *)h;
}
}
return NULL;
}
#define RECLEN(namelen) ((offsetof(struct dirent64, d_name) + (namelen) + 1 + 7) & ~(size_t)7)
/* The listing as packed dirent64 records, built once per version. */
static int records(struct listing *l) {
if (l->recs) return 0;
size_t len = 0;
for (size_t i = 0; i < l->n; i++) len += RECLEN(strlen(l->e[i].name));
char *recs = malloc(len ? len : 1);
if (recs == NULL) return -1;
size_t off = 0;
for (size_t i = 0; i < l->n; i++) {
size_t namelen = strlen(l->e[i].name), reclen = RECLEN(namelen);
struct dirent64 *r = (struct dirent64 *)(recs + off);
memset(r, 0, reclen);
off += reclen;
r->d_ino = l->e[i].ino;
r->d_off = (off_t)off;
r->d_reclen = (unsigned short)reclen;
r->d_type = l->e[i].type;
memcpy(r->d_name, l->e[i].name, namelen + 1);
}
l->recs = recs;
l->len = len;
return 0;
}
/* Lock-free from here on unless noted: a stream is only ever used by one thread at a time. */
static struct handle *lookup(DIR *d) {
return registered(d) >= 0 ? (struct handle *)d : NULL;
}
#define REAL(name) static __typeof__(&name) next_##name
#define NEXT(name) \
if (next_##name == NULL) next_##name = (__typeof__(&name))dlsym(RTLD_NEXT, #name)
REAL(opendir);
REAL(readdir64);
REAL(readdir);
REAL(closedir);
REAL(dirfd);
REAL(rewinddir);
REAL(telldir);
REAL(seekdir);
REAL(mkdir);
REAL(rmdir);
REAL(unlink);
REAL(remove);
REAL(rename);
REAL(link);
REAL(symlink);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
REAL(readdir64_r);
REAL(readdir_r);
/* Resolved before the client starts threads; the calls below only fill gaps for earlier callers. */
__attribute__((constructor)) static void resolve(void) {
NEXT(opendir);
NEXT(readdir64);
NEXT(readdir);
NEXT(closedir);
NEXT(dirfd);
NEXT(rewinddir);
NEXT(telldir);
NEXT(seekdir);
NEXT(mkdir);
NEXT(rmdir);
NEXT(unlink);
NEXT(remove);
NEXT(rename);
NEXT(link);
NEXT(symlink);
NEXT(readdir64_r);
NEXT(readdir_r);
}
#pragma GCC diagnostic pop
/* A reader of the kept listing when it is still current. */
static DIR *hit(const struct stat *st, struct handle *h, long long now) {
pthread_mutex_lock(&lock);
if (!changing) pump(NULL, 0);
int slot = find(st->st_dev, st->st_ino);
if (slot >= 0 && same(table[slot], st) && now - table[slot]->filled < DIR_TTL_NS && records(table[slot]) == 0) {
h->snap = table[slot];
h->snap->refs++;
h->snap->used = now;
DIR *d = wrap(h);
if (d) {
pthread_mutex_unlock(&lock);
return d;
}
unref(h->snap);
h->snap = NULL;
} else if (slot >= 0) {
drop(slot);
}
pthread_mutex_unlock(&lock);
return NULL;
}
/* Registers the stream and its watch before anything is read, so no change goes unseen. */
static int track(struct handle *h, const char *path) {
pthread_mutex_lock(&lock);
h->wd = watch(path);
DIR *d = h->wd >= 0 ? wrap(h) : NULL;
if (d == NULL && h->wd >= 0) release(h->wd);
pthread_mutex_unlock(&lock);
return d != NULL;
}
/* Reads through the real stream, keeping what it returns. */
static void filling(struct handle *h, DIR *real, const struct stat *st, long long now) {
h->real = real;
h->fill = calloc(1, sizeof(*h->fill));
if (h->fill) {
stamp(h->fill, st);
h->fill->filled = now;
h->fill->used = now;
h->fill->wd = h->wd;
}
}
static void untrack(struct handle *h) {
pthread_mutex_lock(&lock);
int i = registered((DIR *)h);
if (i >= 0) __atomic_store_n(&handles[i], NULL, __ATOMIC_RELEASE);
release(h->wd);
pthread_mutex_unlock(&lock);
}
DIR *opendir(const char *path) {
NEXT(opendir);
struct stat st;
if (!eligible(path) || stat(path, &st) != 0 || !S_ISDIR(st.st_mode) || !on_fuse(st.st_dev, path))
return next_opendir(path);
struct handle *h = calloc(1, sizeof(*h));
char *copy = strdup(path);
if (h == NULL || copy == NULL) {
free(h);
free(copy);
return next_opendir(path);
}
h->fd = -1;
h->wd = -1;
h->path = copy;
long long now = now_ns();
DIR *d = hit(&st, h, now);
if (d) return d;
if (!track(h, path)) {
free(h->path);
free(h);
return next_opendir(path);
}
DIR *real = stat(path, &st) == 0 ? next_opendir(path) : NULL;
if (real == NULL) {
untrack(h);
free(h->path);
free(h);
return next_opendir(path);
}
filling(h, real, &st, now);
return (DIR *)h;
}
static void abandon(struct handle *h) {
if (h->fill) destroy(h->fill);
h->fill = NULL;
}
static void finish(struct handle *h) {
struct listing *l = h->fill;
struct stat st;
h->fill = NULL;
int current = stat(h->path, &st) == 0 && same(l, &st);
pthread_mutex_lock(&lock);
if (!changing) pump(NULL, 0);
if (current && !__atomic_load_n(&h->dirty, __ATOMIC_RELAXED)) install(l);
else destroy(l);
pthread_mutex_unlock(&lock);
}
static struct dirent64 *entry(struct handle *h) {
NEXT(readdir64);
if (h->real) {
int saved = errno;
errno = 0;
struct dirent64 *r = next_readdir64(h->real);
int error = errno;
if (h->fill) {
if (r) {
if (h->fill->n >= MAX_ENTRIES || push(h->fill, r->d_ino, r->d_type, r->d_name) != 0) abandon(h);
} else if (error == 0) {
finish(h);
} else {
abandon(h);
}
}
errno = error ? error : saved;
return r;
}
if (h->pos >= h->snap->len) return NULL;
const struct dirent64 *r = (const struct dirent64 *)(h->snap->recs + h->pos);
h->pos += r->d_reclen;
memcpy(&h->out, r, r->d_reclen);
return &h->out;
}
struct dirent64 *readdir64(DIR *d) {
NEXT(readdir64);
struct handle *h = lookup(d);
return h ? entry(h) : next_readdir64(d);
}
struct dirent *readdir(DIR *d) {
NEXT(readdir);
struct handle *h = lookup(d);
return h ? (struct dirent *)entry(h) : next_readdir(d);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
int readdir64_r(DIR *d, struct dirent64 *out, struct dirent64 **result) {
NEXT(readdir64_r);
struct handle *h = lookup(d);
if (h == NULL) return next_readdir64_r(d, out, result);
if (h->real) {
abandon(h);
return next_readdir64_r(h->real, out, result);
}
struct dirent64 *r = entry(h);
if (r) memcpy(out, r, r->d_reclen);
*result = r ? out : NULL;
return 0;
}
int readdir_r(DIR *d, struct dirent *out, struct dirent **result) {
NEXT(readdir_r);
if (lookup(d) == NULL) return next_readdir_r(d, out, result);
return readdir64_r(d, (struct dirent64 *)out, (struct dirent64 **)result);
}
#pragma GCC diagnostic pop
int closedir(DIR *d) {
NEXT(closedir);
pthread_mutex_lock(&lock);
int i = registered(d);
struct handle *h = i >= 0 ? handles[i] : NULL;
if (h) {
__atomic_store_n(&handles[i], NULL, __ATOMIC_RELEASE);
if (h->snap) unref(h->snap);
release(h->wd);
}
pthread_mutex_unlock(&lock);
if (h == NULL) return next_closedir(d);
int r = 0;
if (h->real) r = next_closedir(h->real);
abandon(h);
if (h->fd >= 0) close(h->fd);
free(h->path);
free(h);
return r;
}
int dirfd(DIR *d) {
NEXT(dirfd);
struct handle *h = lookup(d);
if (h == NULL) return next_dirfd(d);
if (h->real) return next_dirfd(h->real);
if (h->fd < 0) h->fd = open(h->path, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
return h->fd;
}
void rewinddir(DIR *d) {
NEXT(rewinddir);
struct handle *h = lookup(d);
if (h == NULL) { next_rewinddir(d); return; }
if (h->real) {
abandon(h);
next_rewinddir(h->real);
} else {
h->pos = 0;
}
}
long telldir(DIR *d) {
NEXT(telldir);
struct handle *h = lookup(d);
if (h == NULL) return next_telldir(d);
return h->real ? next_telldir(h->real) : (long)h->pos;
}
void seekdir(DIR *d, long pos) {
NEXT(seekdir);
struct handle *h = lookup(d);
if (h == NULL) { next_seekdir(d, pos); return; }
if (h->real) {
abandon(h);
next_seekdir(h->real, pos);
} else {
size_t off = 0;
while (off < (size_t)pos && off < h->snap->len) off += ((const struct dirent64 *)(h->snap->recs + off))->d_reclen;
if (off == (size_t)pos) h->pos = off;
}
}
struct side { char dir[PATH_MAX]; const char *name; struct stat before; int known; };
static int split(const char *path, struct side *s) {
size_t n = strlen(path);
while (n > 1 && path[n - 1] == '/') n--;
const char *slash = memrchr(path, '/', n);
if (slash == NULL || (size_t)(slash - path) >= sizeof(s->dir) || slash[1] == 0) return 0;
size_t d = slash == path ? 1 : (size_t)(slash - path);
memcpy(s->dir, path, d);
s->dir[d] = 0;
s->name = slash + 1;
return strchr(s->name, '/') == NULL && strcmp(s->name, ".") != 0 && strcmp(s->name, "..") != 0;
}
static int watching(const char *path) {
return eligible(path) && __atomic_load_n(&cached_listings, __ATOMIC_ACQUIRE) > 0;
}
/* Called with oplock held: the client's tracked changes happen one at a time. */
static void begin(void) {
pthread_mutex_lock(&lock);
pump(NULL, 0);
changing = 1;
pthread_mutex_unlock(&lock);
}
static void before(struct side *s) {
s->known = stat(s->dir, &s->before) == 0;
}
enum { ADDED, REMOVED };
/* Patches the listing after the client's own change, or drops it when unsure. Called with lock held. */
static int patch(struct side *s, int what, uint32_t event, int ok, int error, const char *target, struct expect *x) {
struct stat now;
if (!s->known) return 0;
int slot = find(s->before.st_dev, s->before.st_ino);
if (slot < 0) return 0;
struct listing *l = table[slot];
if (!same(l, &s->before)) {
drop(slot);
return 0;
}
size_t exact = l->n, folded = l->n;
for (size_t i = 0; i < l->n; i++) {
if (strcmp(l->e[i].name, s->name) == 0) { exact = i; break; }
if (folded == l->n && strcasecmp(l->e[i].name, s->name) == 0) folded = i;
}
if (!ok) {
if ((what == ADDED && error == EEXIST && exact == l->n && folded == l->n) || (what == REMOVED && error == ENOENT && exact < l->n))
drop(slot);
return 0;
}
if (stat(s->dir, &now) != 0 || now.st_ino != l->ino) {
drop(slot);
return 0;
}
if (l->refs > 0) {
struct listing *copy = calloc(1, sizeof(*copy));
int failed = copy == NULL;
for (size_t i = 0; !failed && i < l->n; i++) failed = push(copy, l->e[i].ino, l->e[i].type, l->e[i].name) != 0;
if (failed) {
if (copy) destroy(copy);
drop(slot);
return 0;
}
copy->filled = l->filled;
copy->used = l->used;
copy->wd = l->wd;
copy->detached = 0;
stamp(copy, &s->before);
table[slot] = copy;
l->detached = 1;
l = copy;
}
free(l->recs);
l->recs = NULL;
l->len = 0;
int fine = 1, expected = 1;
struct stat t;
if (what == ADDED) {
if (exact < l->n) {
if (lstat(target, &t) == 0) l->e[exact].ino = t.st_ino;
expected = event == IN_MOVED_TO;
} else if (folded < l->n || lstat(target, &t) != 0) {
fine = 0;
} else {
unsigned char type = S_ISDIR(t.st_mode) ? DT_DIR : S_ISLNK(t.st_mode) ? DT_LNK : S_ISREG(t.st_mode) ? DT_REG : DT_UNKNOWN;
fine = l->n < MAX_ENTRIES && push(l, t.st_ino, type, s->name) == 0;
}
} else if (exact < l->n) {
free(l->e[exact].name);
memmove(&l->e[exact], &l->e[exact + 1], (l->n - exact - 1) * sizeof(l->e[0]));
l->n--;
} else {
fine = 0;
}
if (!fine) {
drop(slot);
return 0;
}
stamp(l, &now);
if (!expected) return 0;
*x = (struct expect){l->wd, event, s->name};
return 1;
}
static void end(struct expect *x, int nx) {
pthread_mutex_lock(&lock);
pump(x, nx);
changing = 0;
pthread_mutex_unlock(&lock);
}
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) {
struct side s;
if (!(flags & O_CREAT) || (dirfd != AT_FDCWD && (path == NULL || path[0] != '/')) || !watching(path) || !split(path, &s))
return real(dirfd, path, flags, mode);
pthread_mutex_lock(&oplock);
begin();
before(&s);
int fd = real(dirfd, path, flags, mode);
int saved = errno;
struct expect x;
pthread_mutex_lock(&lock);
int nx = patch(&s, ADDED, IN_CREATE, fd >= 0, saved, path, &x);
pthread_mutex_unlock(&lock);
end(&x, nx);
pthread_mutex_unlock(&oplock);
errno = saved;
return fd;
}
#define ONE_PATH(name, what, event, call, ...) \
int name(const char *path, ##__VA_ARGS__) { \
NEXT(name); \
struct side s; \
if (!watching(path) || !split(path, &s)) return call; \
pthread_mutex_lock(&oplock); \
begin(); \
before(&s); \
int r = call; \
int saved = errno; \
struct expect x; \
pthread_mutex_lock(&lock); \
int nx = patch(&s, what, event, r == 0, saved, what == ADDED ? path : NULL, &x); \
pthread_mutex_unlock(&lock); \
end(&x, nx); \
pthread_mutex_unlock(&oplock); \
errno = saved; \
return r; \
}
ONE_PATH(mkdir, ADDED, IN_CREATE, next_mkdir(path, mode), mode_t mode)
ONE_PATH(rmdir, REMOVED, IN_DELETE, next_rmdir(path))
ONE_PATH(unlink, REMOVED, IN_DELETE, next_unlink(path))
ONE_PATH(remove, REMOVED, IN_DELETE, next_remove(path))
#define TWO_PATHS(name, gone, event) \
int name(const char *from, const char *to) { \
NEXT(name); \
struct side a, b; \
int track_a = gone && watching(from) && split(from, &a), track_b = watching(to) && split(to, &b); \
if (!track_a && !track_b) return next_##name(from, to); \
pthread_mutex_lock(&oplock); \
begin(); \
if (track_a) before(&a); \
if (track_b) before(&b); \
int r = next_##name(from, to); \
int saved = errno; \
struct expect x[2]; \
int nx = 0; \
pthread_mutex_lock(&lock); \
if (track_a) nx += patch(&a, REMOVED, IN_MOVED_FROM, r == 0, saved, NULL, &x[nx]); \
if (track_b) { \
if (track_a && strcmp(a.dir, b.dir) == 0) b.known = stat(b.dir, &b.before) == 0; \
nx += patch(&b, ADDED, event, r == 0, saved, to, &x[nx]); \
} \
pthread_mutex_unlock(&lock); \
end(x, nx); \
pthread_mutex_unlock(&oplock); \
errno = saved; \
return r; \
}
TWO_PATHS(rename, 1, IN_MOVED_TO)
TWO_PATHS(link, 0, IN_CREATE)
TWO_PATHS(symlink, 0, IN_CREATE)
#else
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) {
return real(dirfd, path, flags, mode);
}
#endif
+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;
+16 -4
View File
@@ -36,6 +36,20 @@
int bl_status_without_tracer(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden")));
int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
static int (*real_open)(const char *, int, ...);
static int (*real_openat)(int, const char *, int, ...);
static int via_open(int dirfd, const char *path, int flags, mode_t mode) {
(void)dirfd;
return real_open(path, flags, mode);
}
static int via_openat(int dirfd, const char *path, int flags, mode_t mode) {
return real_openat(dirfd, path, flags, mode);
}
static int retry_without_noatime(int fd, int flags) {
return fd < 0 && errno == EPERM && (flags & O_NOATIME);
@@ -49,7 +63,6 @@ static int is_trace_marker(const char *path) {
}
int open(const char *path, int flags, ...) {
static int (*real_open)(const char *, int, ...);
va_list ap;
mode_t mode;
int fd;
@@ -68,7 +81,7 @@ int open(const char *path, int flags, ...) {
errno = ENOSYS;
return -1;
}
fd = real_open(path, flags, mode);
fd = bl_dircache_create(AT_FDCWD, path, flags, mode, via_open);
if (retry_without_noatime(fd, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
/* A read-only file the Steam client rewrites (perms.c). */
if (fd < 0 && bl_writable_retry(AT_FDCWD, path, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
@@ -76,7 +89,6 @@ int open(const char *path, int flags, ...) {
}
int openat(int dirfd, const char *path, int flags, ...) {
static int (*real_openat)(int, const char *, int, ...);
va_list ap;
mode_t mode;
int fd;
@@ -95,7 +107,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
errno = ENOSYS;
return -1;
}
fd = real_openat(dirfd, path, flags, mode);
fd = bl_dircache_create(dirfd, path, flags, mode, via_openat);
if (retry_without_noatime(fd, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode);
if (fd < 0 && bl_writable_retry(dirfd, path, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode);
return fd;