steam-backlog-enforcer/steam_backlog_enforcer/_hosts_protection.py
Krzysztof kuhy Rudnicki e24e927a14 Unblock the store in both address families
/etc/hosts blocks every store domain as 0.0.0.0 and ::. Unblock and
re-block only matched the 0.0.0.0 line, so the live :: line kept the
store blocked while the job said Success. Lines now match on the exact
sinkhole address and hostname, re-block treats a half block as not
blocked, and a failed hosts write still re-locks the file.

Todo: 85af719b

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

114 lines
3.3 KiB
Python

"""Toggling the protected/immutable flag on /etc/hosts around edits.
Leaf helpers: they call nothing else in the blocker, so extracting them
introduces no cycle. Split to keep both files under the 250-line cap.
"""
from __future__ import annotations
import contextlib
import logging
import subprocess
from typing import TYPE_CHECKING
from steam_backlog_enforcer._hosts_lines import uncomment_store_line
from steam_backlog_enforcer._store_tools import (
GUARDCTL,
SUDO,
TEE,
)
from steam_backlog_enforcer.config import HOSTS_FILE
if TYPE_CHECKING:
from collections.abc import Callable
logger = logging.getLogger(__name__)
def _disable_hosts_protection() -> None:
"""Temporarily unlock /etc/hosts so its content can be edited.
Guard-lib: stop watcher, collapse bind mount, chattr -i.
"""
subprocess.run(
[SUDO, GUARDCTL, "file-guard", "pacman-unlock", "hosts"],
capture_output=True,
timeout=10,
check=False,
)
def _enable_hosts_protection() -> None:
"""Re-lock /etc/hosts, adopting its current content as the new canonical.
Guard-lib: chattr +i, reapply bind mount, restart watcher.
"""
subprocess.run(
[SUDO, GUARDCTL, "file-guard", "sync", "hosts"],
capture_output=True,
timeout=10,
check=False,
)
def _sudo_write_hosts(content: str) -> None:
"""Write *content* to /etc/hosts via ``sudo tee``."""
subprocess.run(
[SUDO, TEE, str(HOSTS_FILE)],
input=content.encode(),
stdout=subprocess.DEVNULL,
timeout=10,
check=True,
)
def rewrite_hosts_lines(
rewrite: Callable[[str], str | None], done_message: str
) -> bool:
"""Apply ``rewrite`` to every /etc/hosts line, under the protection dance.
``rewrite`` returns the replacement for a line, or ``None`` to keep it.
The file is only written -- and ``done_message`` only logged -- when a
line actually changed; protection is lifted before and restored after
either way.
Returns:
Whether the edit (or the no-op) completed without an OSError.
"""
try:
_disable_hosts_protection()
content = HOSTS_FILE.read_text(encoding="utf-8")
new_lines = []
changed = False
for line in content.splitlines(keepends=True):
replacement = rewrite(line)
if replacement is None:
new_lines.append(line)
else:
new_lines.append(replacement)
changed = True
if changed:
_sudo_write_hosts("".join(new_lines))
logger.info(done_message)
except OSError, subprocess.SubprocessError:
logger.exception("Failed to modify /etc/hosts")
return False
finally:
# Re-lock even after a failed write: never leave /etc/hosts open.
with contextlib.suppress(OSError, subprocess.SubprocessError):
_enable_hosts_protection()
return True
def _uncomment_blocked(line: str) -> str | None:
"""The line made live again, if it is a commented-out store sinkhole."""
return uncomment_store_line(line)
def _reblock_hosts() -> bool:
"""Uncomment Steam Store entries in /etc/hosts."""
return rewrite_hosts_lines(
_uncomment_blocked, "Re-enabled Steam Store entries in /etc/hosts."
)