mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-23 15:26:19 +01:00
/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>
197 lines
6.8 KiB
Python
197 lines
6.8 KiB
Python
"""Block Steam Store access via /etc/hosts (hosts install script) and iptables.
|
|
|
|
/etc/hosts is protected by guard-lib (~/guard-lib, file-guard instance
|
|
"hosts"): chattr +i, a read-only self-bind-mount, and a systemd path-unit
|
|
watcher. This module checks if the Steam Store domains are already blocked
|
|
in /etc/hosts. If not, it runs the hosts install.sh (which must already
|
|
contain the Steam Store entries in its heredoc), going through guard-lib's
|
|
unlock/relock around any edit. As a belt-and-suspenders fallback, it also
|
|
blocks via iptables.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import subprocess
|
|
|
|
from steam_backlog_enforcer._hosts_lines import (
|
|
comment_out_store_line,
|
|
hosts_fully_blocks_store,
|
|
live_store_lines,
|
|
)
|
|
from steam_backlog_enforcer._hosts_protection import (
|
|
_reblock_hosts,
|
|
rewrite_hosts_lines,
|
|
)
|
|
from steam_backlog_enforcer._store_iptables import (
|
|
_block_store_iptables,
|
|
_is_iptables_blocked,
|
|
_unblock_store_iptables,
|
|
flush_dns_cache,
|
|
)
|
|
from steam_backlog_enforcer._store_tools import (
|
|
BASH,
|
|
HOSTS_INSTALL_SCRIPT,
|
|
SUDO,
|
|
)
|
|
from steam_backlog_enforcer.config import HOSTS_FILE
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# The install script rewrites /etc/hosts and re-applies its guards.
|
|
_HOSTS_INSTALL_TIMEOUT_SECONDS = 120
|
|
|
|
|
|
def is_store_blocked() -> bool:
|
|
"""Check if Steam Store domains are blocked in /etc/hosts or iptables."""
|
|
return hosts_blocks_store() or _is_iptables_blocked()
|
|
|
|
|
|
def hosts_blocks_store() -> bool:
|
|
"""Whether any store line in /etc/hosts is live (either address family).
|
|
|
|
A file read, no subprocess, safe to poll: one live ``::`` line is enough
|
|
to keep the store unreachable.
|
|
"""
|
|
try:
|
|
return bool(live_store_lines(HOSTS_FILE.read_text(encoding="utf-8")))
|
|
except OSError:
|
|
return False
|
|
|
|
|
|
def hosts_fully_block_store() -> bool:
|
|
"""Whether every store domain is sinkholed in both address families."""
|
|
try:
|
|
return hosts_fully_blocks_store(HOSTS_FILE.read_text(encoding="utf-8"))
|
|
except OSError:
|
|
return False
|
|
|
|
|
|
def block_store() -> bool:
|
|
"""Block Steam Store: uncomment hosts entries, or run install script.
|
|
|
|
Returns True if at least one blocking method succeeded.
|
|
"""
|
|
# "Already blocked" needs both families of every domain: a half-done
|
|
# unblock (IPv4 commented, IPv6 live) must still get its lines back.
|
|
if hosts_fully_block_store():
|
|
logger.info("Steam Store already blocked in /etc/hosts.")
|
|
return True
|
|
|
|
# Try quick re-block (uncomment lines) first.
|
|
if _reblock_hosts() and hosts_fully_block_store():
|
|
_block_store_iptables()
|
|
flush_dns_cache()
|
|
return True
|
|
|
|
# Fall back to the full hosts install script.
|
|
hosts_ok = _block_via_hosts_install()
|
|
ipt_ok = _block_store_iptables()
|
|
|
|
if hosts_ok or ipt_ok:
|
|
flush_dns_cache()
|
|
return True
|
|
|
|
logger.error("All store-blocking methods failed.")
|
|
return False
|
|
|
|
|
|
def restore_store_block() -> bool:
|
|
"""Re-enable the normal store block, even if something else also blocks it.
|
|
|
|
:func:`block_store` returns early at "already blocked", and the total
|
|
block's own /etc/hosts section null-routes the same domains: with that
|
|
section back, the normal lines would stay commented out after a research
|
|
window and the store would open the day the lock ends. This always
|
|
uncomments them and rebuilds the store chain.
|
|
|
|
Returns True if at least one layer was restored.
|
|
"""
|
|
hosts_ok = _reblock_hosts()
|
|
ipt_ok = _block_store_iptables()
|
|
flush_dns_cache()
|
|
return hosts_ok or ipt_ok
|
|
|
|
|
|
def _block_via_hosts_install() -> bool:
|
|
"""Run the hosts install.sh to apply /etc/hosts with Steam Store entries.
|
|
|
|
The install script handles: immutable flag removal, bind mount remounting,
|
|
writing the file, re-applying protections, and DoH disabling.
|
|
"""
|
|
if hosts_fully_block_store():
|
|
logger.info("Steam Store already blocked in /etc/hosts.")
|
|
return True
|
|
|
|
if not HOSTS_INSTALL_SCRIPT.exists():
|
|
logger.error("hosts install script not found at %s", HOSTS_INSTALL_SCRIPT)
|
|
return False
|
|
|
|
try:
|
|
logger.info("Running hosts install script to block Steam Store...")
|
|
result = subprocess.run(
|
|
[SUDO, BASH, str(HOSTS_INSTALL_SCRIPT), "--no-flush-dns"],
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=_HOSTS_INSTALL_TIMEOUT_SECONDS,
|
|
check=False,
|
|
)
|
|
except OSError, subprocess.SubprocessError:
|
|
logger.exception("Failed to run hosts install script")
|
|
return False
|
|
if result.returncode == 0:
|
|
logger.info("hosts install script succeeded.")
|
|
return True
|
|
logger.error(
|
|
"hosts install script failed (rc=%d): %s",
|
|
result.returncode,
|
|
result.stderr[-500:] if result.stderr else result.stdout[-500:],
|
|
)
|
|
return False
|
|
|
|
|
|
def unblock_store() -> bool:
|
|
"""Remove Steam Store blocks from both iptables and /etc/hosts."""
|
|
ipt_ok = _unblock_store_iptables()
|
|
hosts_ok = _unblock_hosts()
|
|
flush_dns_cache()
|
|
|
|
if not ipt_ok:
|
|
logger.warning("Failed to remove iptables rules.")
|
|
if not hosts_ok:
|
|
logger.warning("Failed to remove /etc/hosts entries.")
|
|
|
|
return ipt_ok or hosts_ok
|
|
|
|
|
|
# ──────────────────────────────────────────────────────────────
|
|
# /etc/hosts protection helpers
|
|
#
|
|
# /etc/hosts is managed by guard-lib (see ~/guard-lib) as file-guard
|
|
# instance "hosts": chattr +i, a read-only self-bind-mount, and a
|
|
# systemd path-unit watcher. "pacman-unlock" stops the watcher and
|
|
# collapses the bind mount (same primitive guard-lib's own pacman hooks
|
|
# use). Relocking uses "sync", NOT "pacman-relock" - pacman-relock calls
|
|
# fg_enforce, which treats any diff from the (stale) canonical as drift
|
|
# and reverts it; that's correct for pacman's own hook flow (undo
|
|
# unwanted tampering) but wrong here, where *we* are the one legitimately
|
|
# changing content - it would silently undo our own edit. "sync" instead
|
|
# adopts the just-written content as the new canonical.
|
|
# ──────────────────────────────────────────────────────────────
|
|
|
|
|
|
def _unblock_hosts() -> bool:
|
|
"""Comment out Steam Store entries in /etc/hosts."""
|
|
if not is_store_blocked():
|
|
logger.info("Steam Store not blocked in /etc/hosts, nothing to do.")
|
|
return True
|
|
|
|
return rewrite_hosts_lines(
|
|
_comment_out_blocked, "Commented out Steam Store entries in /etc/hosts."
|
|
)
|
|
|
|
|
|
def _comment_out_blocked(line: str) -> str | None:
|
|
"""The line commented out, if it is a live sinkhole of a store domain."""
|
|
return comment_out_store_line(line)
|