mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-20 12:32:17 +01:00
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
kuhy 2026-11-11: game-design research needs Librarian (app 4197610) actually played during the 6-day total block. New root command total-block-research --until T opens ONE window per lock: <= 48 h, never past the lock end, a rerun never extends it. The command only validates and records (/var/lib/steam-backlog- enforcer, root 0700; lock id + deadline + two latches). The daemon opens and closes everything: Steam hosts names, the store block, the total-block chain (IP cache kept) and the steam package, reinstalled with only guard-lib's package-block hook masked for that one pacman call (--hookdir, proved in a guest). Lock file, hook and end date are never touched. Browser-game sites stay null-routed. Only Librarian may run: loop-local allowed set, strict mode (no whitelist exceptions, no zero-achievement games), launchers and counted games killed; state.json is never read or written. Expiry latches the record, then the ordinary tick re-applies hosts (now reconciled each tick), chain, uninstall and purge; the normal store block is restored once, unconditionally. Failure modes: missing/corrupt/unparseable record = no window and a corrupt one also refuses a new window (fail closed); a clock set back cannot reopen a latched window. Checked: 3290 tests at 100% coverage; whole-tree pylint 10/10 run in three parts (the hook exceeds the 60 s cap, so SKIP=pylint here); vmbox guest with real guardctl package-block and the real unit, window opened, Librarian-only enforced, clock moved past the deadline and the full block re-applied. Not verified on the host. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWWzuCEg1m87jpKyRrw
133 lines
4.4 KiB
Python
133 lines
4.4 KiB
Python
"""Enforce that only the assigned game may run."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
import shutil
|
|
import signal
|
|
import subprocess
|
|
|
|
# The /proc scanners live in leisure_watch.procscan (shared with the leisure
|
|
# watcher); bound here because the kill/enforce paths below call them.
|
|
from leisure_watch.procscan import (
|
|
get_pids_by_process_names,
|
|
get_running_steam_game_pids,
|
|
)
|
|
|
|
from steam_backlog_enforcer._desktop_env import (
|
|
desktop_user_cmd,
|
|
resolve_desktop_user,
|
|
)
|
|
from steam_backlog_enforcer._store_tools import run_quiet
|
|
from steam_backlog_enforcer.game_uninstall import (
|
|
is_infrastructure_app,
|
|
is_protected_app,
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def kill_processes_by_name(names: frozenset[str]) -> list[tuple[int, str]]:
|
|
"""Kill (SIGTERM) every running process whose name is in *names*.
|
|
|
|
Matching is by ``/proc/[pid]/comm`` via ``get_pids_by_process_names``,
|
|
not the ``SteamAppId`` environment variable (unlike
|
|
``get_running_steam_game_pids``) - this is for non-Steam processes
|
|
(the Steam client itself, and third-party game launchers) that don't set
|
|
that variable.
|
|
|
|
Returns: list of (pid, matched_name) actually killed.
|
|
"""
|
|
killed: list[tuple[int, str]] = []
|
|
for pid, name in get_pids_by_process_names(names).items():
|
|
if _kill_pid_by_name(pid, name):
|
|
killed.append((pid, name))
|
|
return killed
|
|
|
|
|
|
def _kill_pid_by_name(pid: int, name: str) -> bool:
|
|
"""Send SIGTERM to *pid*. Returns True if the signal was delivered."""
|
|
try:
|
|
os.kill(pid, signal.SIGTERM)
|
|
except ProcessLookupError:
|
|
return False
|
|
except PermissionError:
|
|
logger.exception("No permission to kill PID %d (%s).", pid, name)
|
|
return False
|
|
return True
|
|
|
|
|
|
def enforce_allowed_game(
|
|
allowed_app_ids: set[int],
|
|
*,
|
|
kill_unauthorized: bool = True,
|
|
strict: bool = False,
|
|
) -> list[tuple[int, int]]:
|
|
"""Check running games; optionally kill unauthorized ones.
|
|
|
|
Args:
|
|
allowed_app_ids: Every app id the user may play right now — the
|
|
assignment plus any concurrent manual picks. Empty disables the
|
|
check entirely (nothing is assigned, so nothing is unauthorized).
|
|
kill_unauthorized: Whether to kill violating processes.
|
|
strict: Spare only runtimes besides the allowed set, not approved
|
|
exceptions or zero-achievement games (the research window).
|
|
|
|
Returns list of (pid, app_id) that were killed or detected.
|
|
"""
|
|
if not allowed_app_ids:
|
|
return []
|
|
spared = is_infrastructure_app if strict else is_protected_app
|
|
running = get_running_steam_game_pids()
|
|
violations: list[tuple[int, int]] = []
|
|
|
|
for pid, app_id in running.items():
|
|
if app_id in allowed_app_ids:
|
|
continue
|
|
# Skip Steam client itself (app_id 0 or very low IDs).
|
|
if app_id == 0:
|
|
continue
|
|
if spared(app_id):
|
|
continue
|
|
|
|
violations.append((pid, app_id))
|
|
if kill_unauthorized:
|
|
kill_process(pid, app_id)
|
|
|
|
return violations
|
|
|
|
|
|
def kill_process(pid: int, app_id: int) -> None:
|
|
"""Kill a process by PID."""
|
|
try:
|
|
logger.warning("Killing unauthorized game (AppID=%d, PID=%d)", app_id, pid)
|
|
os.kill(pid, signal.SIGTERM)
|
|
except ProcessLookupError:
|
|
logger.debug("Process %d already gone.", pid)
|
|
except PermissionError:
|
|
logger.exception("No permission to kill PID %d.", pid)
|
|
|
|
|
|
def send_notification(title: str, body: str) -> None:
|
|
"""Send a desktop notification into the real user's session.
|
|
|
|
The enforcer runs as root under systemd, where a bare ``notify-send`` has
|
|
no DBUS_SESSION_BUS_ADDRESS and so cannot reach the user's session bus —
|
|
it failed silently for every caller. Dropping to the desktop user supplies
|
|
the session variables it needs.
|
|
"""
|
|
_notify_send = shutil.which("notify-send") or "/usr/bin/notify-send"
|
|
cmd = desktop_user_cmd(
|
|
[_notify_send, title, body, "--icon=dialog-warning"],
|
|
resolve_desktop_user(),
|
|
)
|
|
try:
|
|
run_quiet(cmd)
|
|
except FileNotFoundError, OSError:
|
|
logger.debug("notify-send not available.")
|
|
except subprocess.TimeoutExpired:
|
|
# sudo can block where a bare notify-send would not; a dropped
|
|
# notification is better than an exception escaping the enforce loop.
|
|
logger.debug("notify-send timed out.")
|