steam-backlog-enforcer/steam_backlog_enforcer/_steam_client.py
Krzysztof kuhy Rudnicki 01d750f36d Remove unneeded Steam tools after an uninstall
Steamworks Common Redistributables, Steam Linux Runtime 4.0 and Proton
Experimental stay in PROTECTED_APP_IDS, so no guard ever calls them an
unauthorized game. uninstall_other_games now ends with a step that
uninstalls them, through uninstall_game, only when all of these hold:

- Steam is not running (pgrep steam.sh, as _ensure_steam_running);
- config.vdf parses and has a CompatToolMapping block;
- every installed non-tool appmanifest maps to proton-cachyos-native;
- that tool's toolmanifest.vdf exists.

Anything else keeps all three and logs "kept Steam tools: <reason>";
a running Steam logs "Steam running, deferring tool removal". No game
installed counts as not needed and says so.

- _tool_need.py decides. Every error keeps the tools.
- _vdf_text.py is a stdlib KeyValues parser. The repo had none, and the
  root daemon's system python has no vdf package.
- _steam_client.steam_client_running() returns None when pgrep cannot
  tell. _ensure_steam_running behaves as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:53:11 +01:00

135 lines
4.4 KiB
Python

"""Starting the Steam client as the desktop user, and install-state queries.
Split out of :mod:`steam_backlog_enforcer.game_install` to keep it under the
250-line cap. The enforcer runs as root, so everything here is about resolving
*which* user to become before touching the desktop session.
"""
from __future__ import annotations
import logging
import os
import pwd
import subprocess
import time
from steam_backlog_enforcer._desktop_env import (
desktop_env_args,
desktop_runtime_dir,
desktop_session_ready,
resolve_desktop_user,
)
from steam_backlog_enforcer._steam_launch import steam_is_installed
from steam_backlog_enforcer._steam_process import spawn_detached
from steam_backlog_enforcer._steam_restart_guard import fast_install_running
from steam_backlog_enforcer._steam_state import STEAMAPPS_PATH
logger = logging.getLogger(__name__)
def _get_real_user() -> str | None:
"""Get the desktop user to drop privileges to.
Delegates to the shared resolver so this module honours
STEAM_ENFORCER_DESKTOP_USER. Reading only SUDO_USER/USER returned None
under systemd (which sets neither), so every ``geteuid() == 0 and
real_user`` guard below silently fell through to running as root.
"""
return resolve_desktop_user()
def _get_uid_gid_for_user(username: str) -> tuple[int, int]:
"""Get (uid, gid) for a username."""
try:
pw = pwd.getpwnam(username)
except KeyError:
return 1000, 1000
return pw.pw_uid, pw.pw_gid
def is_game_installed(app_id: int) -> bool:
"""Check if a game is installed by looking for its appmanifest.
A manifest with StateFlags != 4 (FullyInstalled) means the game is
still downloading or queued, which still counts as "install triggered".
"""
manifest = STEAMAPPS_PATH / f"appmanifest_{app_id}.acf"
return manifest.exists()
def steam_client_running() -> bool | None:
"""Whether the Steam main client (``steam.sh``, not just helpers) runs.
Returns:
None when pgrep is missing or fails: callers that delete on "not
running" must treat that as running.
"""
try:
result = subprocess.run(
["/usr/bin/pgrep", "-f", "steam.sh"],
capture_output=True,
text=True,
check=False,
)
except FileNotFoundError:
return None
# pgrep: 0 matched, 1 matched nothing, anything else is its own error.
return {0: True, 1: False}.get(result.returncode)
def _ensure_steam_running() -> None:
"""Start the Steam client if it is not already running.
Does nothing if Steam is not installed - there is no client to start, and
trying anyway only sleeps 15s waiting on a process that died on exec.
"""
if not steam_is_installed():
logger.info("Steam is not installed — skipping client start.")
return
if fast_install_running():
logger.info("steam-game-installer is running — leaving Steam closed.")
return
# None (pgrep cannot tell) falls through to a start, as it always has.
if steam_client_running():
logger.debug("Steam client already running")
return
real_user = _get_real_user()
logger.info("Starting Steam client...")
try:
if os.geteuid() == 0 and real_user and real_user != "root":
uid, _ = _get_uid_gid_for_user(real_user)
# Defer rather than launch a Steam that would come up without a
# runtime dir, and so without working audio, for the session.
if not desktop_session_ready(uid):
logger.info(
"Deferring Steam start: %s does not exist yet.",
desktop_runtime_dir(uid),
)
return
cmd = [
"sudo",
"-u",
real_user,
"env",
*desktop_env_args(real_user, uid),
"steam",
"-silent",
]
else:
cmd = ["steam", "-silent"]
spawn_detached(cmd)
# Give Steam time to initialize and start scanning manifests.
time.sleep(15)
except FileNotFoundError:
logger.exception("Steam executable not found")
# Latches the "no Steam library" warning so a 3s enforce loop logs it once
# rather than once per game per pass. A set (rather than a module-level bool
# reassigned via `global`) keeps the mutation local to the container.
_LIBRARY_WARNED: set[str] = set()