steam-backlog-enforcer/steam_backlog_enforcer/_playtime_block.py
Krzysztof kuhy Rudnicki 0c05d71008 Add a daily gaming-time budget with a binary-level cutoff
Accumulates time spent in Steam games and other launchers, and once the
daily budget (default 8h) is spent, shuts Steam down, kills the games, and
makes them unlaunchable until the next 06:00.

The gaming day starts at 06:00 local rather than midnight so a late session
counts against the day it began in; rollover is checked lazily against a
stored day key, so it survives suspend, reboot and daemon restarts with no
timer of its own. Elapsed time comes from wall-clock deltas clamped to two
tick intervals, which keeps suspends, missed ticks and NTP steps honest.

The block is a read-only bind mount of a refusal stub over all four launcher
entry points -- /usr/bin/steam is only a two-line exec wrapper, so masking it
alone leaves bin_steam.sh, Steam's own steam.sh and lutris live. A bind mount
mutates no bytes, umount restores exactly, and a reboot clears it
unconditionally; chmod/rename would leave Steam broken if the daemon died
mid-block. /proc/self/mountinfo is the authority on what is masked, never the
saved state, which is what makes a stale block release even if the state file
was deleted. The mount is deferred one tick past the cutoff so
`steam -shutdown` still works and games close cleanly.

Launchers are matched by cmdline, not comm: /usr/bin/lutris is a python3
script, so the kernel records its comm as "python3" and the existing scan
never sees it. The kill set is wider than the budget predicate, walking down
from each launcher, because a Lutris-launched Wine game carries no SteamAppId.

State is chattr +i'd -- ~/.config is user-writable, so root ownership alone
would not stop `rm` from resetting the counter -- and a missing state file
while mounts are live fails closed rather than lifting the block.

Also fixes a pre-existing bug: do_enforce returned when no game was assigned,
exiting the process. Since the budget is accounted for from inside that loop,
it silently stopped enforcing whenever a game was finished but not rescanned.

Verified on the desktop with a real game: AoE2 counted 18 processes, tripped
at the 60s demo budget, all processes killed, all four paths masked and
refusing, then gaming-unblock restored them byte-identical with
`pacman -Qkk steam lutris` reporting 0 altered files.

1322 tests pass at 100.00% branch coverage; pacman validated the ALPM hook.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QbEaXapjMSkxyzgvbdkUFb
2026-08-04 20:00:08 +02:00

463 lines
14 KiB
Python

"""Make Steam and game launchers unlaunchable once the daily budget is spent.
The block is a **read-only bind mount** of a refusal stub over every launcher
entry point. Nothing else here is negotiable, and future changes must not
substitute an alternative:
* ``chmod 000`` and rename-aside both mutate persistent on-disk state that
outlives this process. A crash mid-block leaves Steam unexecutable with no
automatic recovery.
* ``guardctl file-guard`` is an anti-*drift* keeper, not a swapper: it snapshots
the target as canonical and copies canonical back over the target. Pointing it
at a stub would permanently overwrite ``/usr/bin/steam``.
A bind mount mutates zero bytes of the real binary, ``umount`` is a perfect
restore, and a reboot clears every mount unconditionally. That last property is
the whole safety argument: the worst case is "reboot fixes it".
Four targets, because the first three are bypasses of one another —
``/usr/bin/steam`` is a two-line ``exec /usr/lib/steam/steam "$@"`` wrapper, and
Steam ships its own executable bootstrap inside the user's home directory.
``/proc/self/mountinfo`` is the authority on what is currently masked, never the
saved state. That is what makes the block self-healing: a stale mount is
released even if the state file was deleted, and a mount lost to a reboot is
re-applied on the next tick.
**The daemon must keep a shared mount namespace.** Adding ``PrivateMounts=``,
``PrivateTmp=`` or ``ProtectSystem=`` to the systemd unit would make these
mounts invisible outside the service, silently turning the block into a no-op
while the counter kept running. :func:`mounts_are_visible` checks for exactly
that at runtime.
"""
from __future__ import annotations
import contextlib
import logging
import os
from pathlib import Path
import shutil
import signal
import subprocess
from steam_backlog_enforcer._total_block import (
LAUNCHER_PROCESS_NAMES,
STEAM_CLIENT_PROCESS_NAMES,
)
from steam_backlog_enforcer.enforcer import get_pids_by_process_names
logger = logging.getLogger(__name__)
BLOCK_TARGETS: tuple[Path, ...] = (
# Every steam.desktop action uses this path; it is only a wrapper.
Path("/usr/bin/steam"),
# The real bootstrap. Named directly rather than via the
# /usr/lib/steam/steam symlink because mount(2) resolves symlinks, so
# mounting the link would mount here anyway under a misleading name.
Path("/usr/lib/steam/bin_steam.sh"),
# Steam's self-updating bootstrap, owned by the user and independently
# executable.
Path.home() / ".local" / "share" / "Steam" / "steam.sh",
Path("/usr/bin/lutris"),
)
# The stub lives on root-owned tmpfs, NOT in CONFIG_DIR. A bind mount shares the
# inode: a stub in a user-writable directory could be rewritten to exec the real
# bootstrap, and the block would evaporate without a single mount changing.
_STUB_DIR = Path("/run/steam-backlog-enforcer")
STUB_PATH = _STUB_DIR / "gaming-blocked"
MOUNTINFO_PATH = Path("/proc/self/mountinfo")
_INIT_MOUNTINFO_PATH = Path("/proc/1/mountinfo")
# pacman holds this for the whole transaction. Re-mounting mid-transaction is
# what would actually cause the EBUSY the PreTransaction hook exists to avoid.
PACMAN_LOCK = Path("/var/lib/pacman/db.lck")
_PROC = Path("/proc")
# Bind mounts stack, so one umount need not be enough. guard-lib's
# collapse_bind_mount() uses the same bounded loop for the same reason.
_MAX_UMOUNT_PASSES = 20
_MOUNTINFO_MIN_FIELDS = 5
_MOUNTPOINT_FIELD = 4
_STAT_PPID_INDEX = 1
_MAX_PROCESS_TREE_DEPTH = 32
_STUB_MODE = 0o755
_STUB_SCRIPT = """#!/bin/sh
# Installed by steam-backlog-enforcer. Bind-mounted over the real launcher
# while the daily gaming budget is exhausted; removed automatically at 06:00.
echo "Gaming blocked: daily budget used up. Unblocks at 06:00." >&2
exit 1
"""
def block_targets() -> tuple[Path, ...]:
"""Return the launcher paths the block masks.
An accessor rather than a direct import of ``BLOCK_TARGETS``: module-level
constants are bound by value at import time, so a second binding elsewhere
would need its own test patch to stay isolated. Routing every reader through
one function keeps that to a single patch point.
Returns:
The masked launcher paths.
"""
return BLOCK_TARGETS
def _run(cmd: list[str]) -> bool:
"""Run a privileged command, reporting success.
The single subprocess seam in this module, so tests can assert on exact
argv without ever executing ``mount``.
Args:
cmd: Argument vector to execute.
Returns:
True if the command exited zero.
"""
try:
result = subprocess.run(cmd, capture_output=True, check=False, timeout=15)
except (OSError, subprocess.SubprocessError):
logger.exception("Playtime block command failed: %s", cmd)
return False
if result.returncode != 0:
logger.warning("Playtime block command exited %d: %s", result.returncode, cmd)
return result.returncode == 0
def _unescape_mountinfo(field: str) -> str:
"""Decode the octal escapes the kernel writes into mountinfo paths.
Args:
field: A raw mountinfo field.
Returns:
The decoded field.
"""
return (
field.replace(r"\040", " ")
.replace(r"\011", "\t")
.replace(r"\012", "\n")
.replace(r"\134", "\\")
)
def _mountpoints(path: Path) -> set[Path]:
"""Parse *path* as mountinfo and return the mount points it lists.
Args:
path: A mountinfo file.
Returns:
Every mount point named in the file.
"""
try:
raw = path.read_text(encoding="utf-8")
except (OSError, ValueError):
logger.warning("Could not read mountinfo at %s.", path)
return set()
points: set[Path] = set()
for line in raw.splitlines():
fields = line.split(" ")
if len(fields) < _MOUNTINFO_MIN_FIELDS:
continue
points.add(Path(_unescape_mountinfo(fields[_MOUNTPOINT_FIELD])))
return points
def mounted_targets() -> set[Path]:
"""Return the block targets currently masked by a mount.
Read in-process from mountinfo rather than shelling out to ``findmnt``:
this runs on every enforce tick, and a fork per tick is exactly the polling
cost this codebase avoids elsewhere.
Anything mounted on a block target is treated as ours — nothing else on this
system mounts over those paths.
Returns:
The masked targets.
"""
return _mountpoints(MOUNTINFO_PATH) & set(block_targets())
def mounts_are_visible() -> bool:
"""Whether mounts made here are visible to the rest of the system.
A private mount namespace (``PrivateMounts=``, ``ProtectSystem=`` and
friends) would keep every mount inside the service, so the block would do
nothing while the counter kept running — a silent fail-open. Compared
against PID 1's namespace, which is the one that matters.
Returns:
True if no mount we made is missing from PID 1's view.
"""
ours = mounted_targets()
if not ours:
return True
return bool(ours & _mountpoints(_INIT_MOUNTINFO_PATH))
def _ensure_stub() -> bool:
"""Write the refusal stub, replacing any existing copy.
Returns:
True if the stub is present and executable.
"""
try:
_STUB_DIR.mkdir(parents=True, exist_ok=True)
STUB_PATH.write_text(_STUB_SCRIPT, encoding="utf-8")
STUB_PATH.chmod(_STUB_MODE)
except OSError:
logger.exception("Could not write the playtime refusal stub.")
return False
return True
def apply_block() -> list[Path]:
"""Mask every unmasked block target with the refusal stub.
Skipped entirely while pacman holds its database lock: re-mounting during a
transaction is what makes package extraction fail ``EBUSY``. The kill loop is
not gated this way, so enforcement continues regardless.
Returns:
The targets newly masked by this call.
"""
if PACMAN_LOCK.exists():
logger.info("pacman transaction in progress; deferring playtime mounts.")
return []
if not _ensure_stub():
return []
already = mounted_targets()
newly: list[Path] = []
for target in block_targets():
if target in already or not target.exists():
continue
if not _run([_mount_bin(), "--bind", str(STUB_PATH), str(target)]):
continue
if _run([_mount_bin(), "-o", "remount,ro,bind", str(target)]):
newly.append(target)
return newly
def release_block() -> list[Path]:
"""Unmask every masked block target.
Loops per target because bind mounts stack; bounded so a target that cannot
be unmounted cannot spin forever.
Returns:
The targets released by this call.
"""
released: list[Path] = []
for target in mounted_targets():
for _ in range(_MAX_UMOUNT_PASSES):
if target not in mounted_targets():
released.append(target)
break
if not _run([_umount_bin(), "-l", str(target)]):
logger.warning("Could not release playtime mount on %s.", target)
break
return released
def reconcile(*, should_block: bool) -> tuple[list[Path], list[Path]]:
"""Drive the on-disk mount state toward *should_block*.
Idempotent and driven by mountinfo, so it costs one file read per tick when
nothing needs changing. Because it reads the live mount table rather than
saved state, it releases a stale block even if the state file was deleted,
and re-applies a block that a reboot cleared.
Args:
should_block: Whether the launchers should currently be masked.
Returns:
A ``(newly_masked, newly_released)`` pair.
"""
if not should_block:
return [], release_block()
masked = apply_block()
if masked and not mounts_are_visible():
logger.error(
"Playtime mounts are not visible outside this service — the block "
"is not in force. Check the unit for PrivateMounts/ProtectSystem.",
)
return masked, []
def request_steam_shutdown() -> None:
"""Ask Steam to close cleanly, without waiting for it.
``library_hider._shutdown_steam`` polls for up to 30 seconds, which would
stall the 3-second enforce loop for ten ticks. The cutoff sequence gives
Steam its grace period across ticks instead.
"""
steam = shutil.which("steam")
if steam is None:
logger.info("Steam binary not on PATH; skipping clean shutdown.")
return
_run([steam, "-shutdown"])
def steam_and_launcher_pids() -> set[int]:
"""Return PIDs of the Steam client and every known game launcher.
Returns:
The launcher and client PIDs.
"""
names = STEAM_CLIENT_PROCESS_NAMES | LAUNCHER_PROCESS_NAMES
return set(get_pids_by_process_names(names))
def _read_ppid(pid: int) -> int | None:
"""Return the parent PID of *pid*, or ``None`` if it cannot be read.
``/proc/<pid>/stat`` embeds ``comm`` in parentheses and ``comm`` may contain
spaces and parentheses, so the fields after it are found by splitting on the
last ``") "`` rather than by whitespace position.
Args:
pid: Process to inspect.
Returns:
The parent PID, or ``None``.
"""
try:
raw = (_PROC / str(pid) / "stat").read_text(encoding="utf-8")
except (OSError, ValueError):
return None
_, _, rest = raw.rpartition(") ")
fields = rest.split()
if len(fields) <= _STAT_PPID_INDEX:
return None
try:
return int(fields[_STAT_PPID_INDEX])
except ValueError:
return None
def _child_map() -> dict[int, list[int]]:
"""Build a parent-PID to child-PIDs map from ``/proc``.
Returns:
Mapping of parent PID to its direct children.
"""
children: dict[int, list[int]] = {}
try:
entries = list(_PROC.iterdir())
except OSError:
return children
for entry in entries:
if not entry.name.isdigit():
continue
pid = int(entry.name)
ppid = _read_ppid(pid)
if ppid is not None:
children.setdefault(ppid, []).append(pid)
return children
def descendant_pids(roots: set[int]) -> set[int]:
"""Return every process descended from *roots*.
A Lutris-launched Wine game carries no ``SteamAppId`` and its ``comm`` is
the game's own binary, so neither of the budget matchers can see it. Walking
down from the launcher is the only thing that does.
The daemon's own process and its ancestors are excluded, so a misidentified
root cannot make the enforcer kill itself.
Args:
roots: Processes to walk down from.
Returns:
The transitive descendants, excluding *roots* themselves.
"""
children = _child_map()
protected = _own_process_chain()
found: set[int] = set()
frontier = [pid for pid in roots if pid not in protected]
for _ in range(_MAX_PROCESS_TREE_DEPTH):
if not frontier:
break
nxt: list[int] = []
for pid in frontier:
for child in children.get(pid, []):
if child in found or child in protected:
continue
found.add(child)
nxt.append(child)
frontier = nxt
return found
def _own_process_chain() -> set[int]:
"""Return this process and its ancestors.
Returns:
PIDs that must never be signalled.
"""
chain: set[int] = set()
pid: int | None = os.getpid()
for _ in range(_MAX_PROCESS_TREE_DEPTH):
if pid is None or pid <= 0 or pid in chain:
break
chain.add(pid)
pid = _read_ppid(pid)
return chain
def kill_gaming_processes(pids: set[int], *, force: bool) -> list[int]:
"""Signal every process in *pids*, plus everything descended from them.
Args:
pids: Processes to terminate.
force: Send ``SIGKILL`` instead of ``SIGTERM``.
Returns:
The PIDs actually signalled.
"""
protected = _own_process_chain()
targets = (pids | descendant_pids(pids)) - protected
sig = signal.SIGKILL if force else signal.SIGTERM
signalled: list[int] = []
for pid in sorted(targets):
with contextlib.suppress(ProcessLookupError, PermissionError):
os.kill(pid, sig)
signalled.append(pid)
return signalled
def _mount_bin() -> str:
"""Return the ``mount`` executable path.
Returns:
Absolute path to ``mount``.
"""
return shutil.which("mount") or "/usr/bin/mount"
def _umount_bin() -> str:
"""Return the ``umount`` executable path.
Returns:
Absolute path to ``umount``.
"""
return shutil.which("umount") or "/usr/bin/umount"