#!/usr/bin/python3 -I
"""trcc-module-devices — let this seat reach an installed module's USB devices
(run via pkexec).

A module that drives hardware the system guards -- a USB lighting controller
-- names the devices it needs in its ``module.json`` (``0b05:19af``), the user
accepts them on its install screen, and TRCC asks this helper to let the
person at this seat open them.  ``enable`` writes one udev rule file for the
module; ``disable`` removes it and takes the access back at once.

The rule's text is never the caller's.  The caller supplies only the module's
key and the device ids, each checked against a fixed pattern; every line is
built here: the device's USB node and each of its ``hidraw`` nodes,
``MODE="0660"``, ``GROUP="trcc"``, ``TAG+="uaccess"``.  So no caller can
smuggle a ``RUN``, ``PROGRAM`` or ``IMPORT`` into a root-written udev rule --
there is no udev syntax to send.

A hidraw node is matched by its HID device's own name (``KERNELS ==
"0003:0B05:19AF.*"``), never by ``ATTRS{idVendor}``: ATTRS searches every
ancestor, so a hub's ids would match the keyboard plugged into it -- a
keylogger for every program the user runs.  Found driving it on a real
desk: a hub's ``05e3:0608`` matched the Dell keyboard below it.

What it grants is real: every program the user runs can then reach those
devices, as the install screen says.  The polkit action asks for a password
on every use (``auth_admin``); the review behind the signed module index is
what checks a module names only the hardware it drives.

Kept as small as ``trcc-ram-access``:

  * stdlib only — imports NOTHING from the trcc package, so running it as root
    pulls in no untrusted code (``-I``: no user site, no PYTHON* variables).
  * ``enable <key> <vvvv:pppp>...`` (1-16 ids), ``disable <key>`` or
    ``disable-all`` (the packages' uninstall hooks); anything else is refused
    before a file or a process is touched.
  * writes only ``/etc/udev/rules.d/70-trcc-module-<key>.rules`` -- and, on
    SteamOS, ``/etc/atomic-update.conf.d/trcc-module-<key>.conf``, which keeps
    that rule through an OS update (it resets /etc to the new image) -- and
    removes only a file whose first line is TRCC's header for that key, never
    one an admin wrote.
  * runs only udevadm, getfacl and setfacl, from fixed system paths, with a
    fixed environment.
  * ``disable`` also deletes udev's own record of each node it granted
    (``/run/udev/data/c<major>:<minor>`` and its ``uaccess`` tag link) and
    gives the node back to group root if the group is ours -- nothing else
    under ``/run/udev``, no other node.
  * ``disable`` touches nothing unless TRCC's rule was there to remove: its
    password-free twin ``trcc-module-devices-off`` can be run by any program
    in the session.

This file may import nothing from trcc, so what TRCC also spells is gated
equal by tests: the key and id patterns (``core.models.MODULE_KEY`` and
``MODULE_DEVICE``), the group (``DEVICE_GROUP``), SteamOS's keep-list folder
(``_udev.KEEP_LIST_DIR``) and the paths (``_module_devices``).  This file is
the one builder of a module's rule: the Nix package's copy of a built-in
module's is generated from ``rule_text`` (``dev/gen_packaging_setup.py``).

Exit codes: 0 ok · 1 a step failed · 2 bad invocation · 3 not root.
"""
import grp
import os
import re
import subprocess
import sys
from pathlib import Path

KEY = re.compile(r"[a-z][a-z0-9_]{1,30}")
DEVICE = re.compile(r"[0-9a-f]{4}:[0-9a-f]{4}")
#: The most devices one module may name.
MAX_DEVICES = 16
GROUP = "trcc"
RULES_DIR = Path("/etc/udev/rules.d")
RULE_GLOB = "70-trcc-module-*.rules"
#: SteamOS keeps the paths listed in here through an OS update.
KEEP_DIR = Path("/etc/atomic-update.conf.d")

_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"}
_TOOLS = {
    "udevadm": ("/usr/bin/udevadm", "/bin/udevadm", "/usr/sbin/udevadm",
                "/sbin/udevadm"),
    "getfacl": ("/usr/bin/getfacl", "/bin/getfacl"),
    "setfacl": ("/usr/bin/setfacl", "/bin/setfacl"),
}
_USB = Path("/sys/bus/usb/devices")
_HIDRAW = Path("/sys/class/hidraw")
_UDEV_DATA = Path("/run/udev/data")
_UDEV_UACCESS = Path("/run/udev/tags/uaccess")


def header(key: str) -> str:
    """The first line of *key*'s rule file -- how a file is known as TRCC's."""
    return (f"# TRCC module {key} -- written by trcc-module-devices; removing "
            "the module removes it.")


def rule_path(key: str) -> Path:
    return RULES_DIR / f"70-trcc-module-{key}.rules"


def keep_path(key: str) -> Path:
    """*key*'s SteamOS keep-list entry."""
    return KEEP_DIR / f"trcc-module-{key}.conf"


def keep_text(key: str) -> str:
    """*key*'s keep-list entry: TRCC's header, then its rule's path."""
    return f"{header(key)}\n{rule_path(key)}\n"


def rule_text(key: str, devices: list[str]) -> str:
    """*key*'s rule file: its header, then each device's two lines."""
    lines = [header(key),
             "# The user at this seat and the trcc group reach these devices.", ""]
    grant = f'MODE="0660", GROUP="{GROUP}", TAG+="uaccess"'
    for device in devices:
        vid, pid = device.split(":")
        lines += [f'SUBSYSTEM=="hidraw", KERNELS=="{hid_name(device)}.*", {grant}',
                  f'SUBSYSTEM=="usb", ATTR{{idVendor}}=="{vid}", '
                  f'ATTR{{idProduct}}=="{pid}", {grant}']
    return "\n".join(lines) + "\n"


def hid_name(device: str) -> str:
    """The kernel's name for a USB HID device of *device*, less its instance:
    ``0003:0B05:19AF`` -- bus 3 is USB, the ids in upper case."""
    vid, pid = device.split(":")
    return f"0003:{vid.upper()}:{pid.upper()}"


def devices_in(text: str) -> list[str]:
    """The device ids a rule file of ours names, read back from its lines."""
    found = re.findall(r'ATTR\{idVendor\}=="([0-9a-f]{4})", '
                       r'ATTR\{idProduct\}=="([0-9a-f]{4})"', text)
    return [f"{vid}:{pid}" for vid, pid in found]


def _tool(name: str) -> str | None:
    return next((p for p in _TOOLS[name] if os.path.isfile(p)), None)


def _run(*argv: str) -> bool:
    try:
        return subprocess.run(argv, env=_ENV, timeout=30, check=False,
                              stdout=subprocess.DEVNULL,
                              stderr=subprocess.DEVNULL).returncode == 0
    except (OSError, subprocess.SubprocessError):
        return False


def _read(*argv: str) -> str | None:
    """A tool's output, or None if it failed."""
    try:
        result = subprocess.run(argv, env=_ENV, timeout=30, check=False,
                                capture_output=True, text=True)
    except (OSError, subprocess.SubprocessError):
        return None
    return result.stdout if result.returncode == 0 else None


def _put(target: Path, text: str) -> None:
    """*text* into *target*, atomically, root-owned 0644."""
    target.parent.mkdir(parents=True, exist_ok=True)
    tmp = target.with_name(f".{target.name}.tmp")
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        f.write(text)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, target)


def _take(key: str, target: Path) -> str | None:
    """Remove *target* if TRCC wrote it for *key*: its text, or None when
    there was nothing of TRCC's there."""
    try:
        text = target.read_text(encoding="utf-8")
    except FileNotFoundError:
        return None
    if text.partition("\n")[0] != header(key):
        return None
    target.unlink()
    return text


def write(key: str, devices: list[str], root: Path = Path("/")) -> None:
    """*key*'s rule file -- and on SteamOS its keep-list entry, so an OS
    update does not throw the rule away."""
    _put(root / rule_path(key).relative_to("/"), rule_text(key, devices))
    if (root / KEEP_DIR.relative_to("/")).is_dir():
        _put(root / keep_path(key).relative_to("/"), keep_text(key))


def remove(key: str, root: Path = Path("/")) -> list[str] | None:
    """*key*'s rule file and keep-list entry, only if TRCC wrote them: the
    devices the rule named, or None when there was no rule of TRCC's."""
    _take(key, root / keep_path(key).relative_to("/"))
    text = _take(key, root / rule_path(key).relative_to("/"))
    return None if text is None else devices_in(text)


def keys_written(root: Path = Path("/")) -> list[str]:
    """Every module key with a rule file of ours -- for ``disable-all``."""
    keys = []
    for path in sorted((root / RULES_DIR.relative_to("/")).glob(RULE_GLOB)):
        key = path.name[len("70-trcc-module-"):-len(".rules")]
        if KEY.fullmatch(key):
            keys.append(key)
    return keys


def _attr(path: Path, name: str) -> str:
    try:
        return (path / name).read_text(encoding="utf-8").strip()
    except OSError:
        return ""


def device_nodes(devices: list[str], usb: Path = _USB,
                 hidraw: Path = _HIDRAW) -> list[str]:
    """``/dev`` nodes of the attached *devices*: each one's USB node and each
    ``hidraw`` node of its own -- by its HID device's name, as the rule
    matches, never a node of a device plugged in below it."""
    wanted, nodes = set(devices), []
    for dev in sorted(usb.glob("*")):
        if f"{_attr(dev, 'idVendor')}:{_attr(dev, 'idProduct')}" not in wanted:
            continue
        busnum, devnum = _attr(dev, "busnum"), _attr(dev, "devnum")
        if busnum.isdigit() and devnum.isdigit():
            nodes.append(f"/dev/bus/usb/{int(busnum):03d}/{int(devnum):03d}")
    names = {hid_name(device) for device in devices}
    for node in sorted(hidraw.glob("hidraw*")):
        if (node / "device").resolve().name.rpartition(".")[0] in names:
            nodes.append(f"/dev/{node.name}")
    return nodes


def named_users(acl: str) -> list[str]:
    """The uids of ``getfacl -cpn``'s named-user entries (``user:1000:rw-``)."""
    uids = []
    for line in acl.splitlines():
        tag, _, rest = line.partition(":")
        uid = rest.partition(":")[0]
        if tag == "user" and uid.isdigit():     # ``user::`` is the owner
            uids.append(uid)
    return uids


def udev_record(node: str) -> str:
    """udev's name for *node*'s record: ``c189:3`` -- a char device, its
    major and minor number."""
    rdev = Path(node).stat().st_rdev
    return f"c{os.major(rdev)}:{os.minor(rdev)}"


def _gid(group: str) -> int | None:
    try:
        return grp.getgrnam(group).gr_gid
    except KeyError:
        return None


def forget(node: str, data: Path = _UDEV_DATA, uaccess: Path = _UDEV_UACCESS) -> None:
    """Drop udev's record of *node*, and our group from it, so the ``add``
    that follows rebuilds both from the rules as they are now.

    udev tags cannot be unset: once our rule tagged a node ``uaccess``, the
    tag stays in its record after the rule is deleted, and
    ``73-seat-late.rules`` grants the seat's user again on the node's next
    ``change`` -- from anything that triggers udev.  Driven on systemd 259: a
    hub re-granted on 5 of 5 change events.  A record dropped and rebuilt is
    what a replug does to it, without touching the device.
    """
    record = udev_record(node)
    for path in (data / record, uaccess / record):
        path.unlink(missing_ok=True)
    if (ours := _gid(GROUP)) is not None and Path(node).stat().st_gid == ours:
        os.chown(node, -1, 0)


def apply(enabled: bool, devices: list[str]) -> bool:
    """Make the rule take effect now, without a replug.

    Enabling re-triggers the devices, so the new rule reaches them.
    Disabling forgets each granted node's udev record (``forget``), rebuilds
    it with an ``add``, and only then takes the named-USER ACL entries away
    -- after udev has settled, so no event still in flight grants them back.
    Only USER entries, as systemd's own ``devnode_acl`` resets a uaccess node
    -- a GROUP entry is never a uaccess grant, and an admin's stays.  Any
    other rule that tags the device (OpenRGB's, an admin's) grants it again
    on the rebuild -- which is the truth.
    """
    udevadm = _tool("udevadm")
    if udevadm is None:
        return False
    ok = _run(udevadm, "control", "--reload")
    nodes = [] if enabled else device_nodes(devices)
    if enabled:
        ok &= _run(udevadm, "trigger", "--subsystem-match=hidraw", "--action=change")
    else:
        for node in nodes:
            try:
                forget(node)
            except OSError:
                ok = False
        for node in nodes:
            if node.startswith("/dev/hidraw"):
                ok &= _run(udevadm, "trigger", "--action=add",
                           str(_HIDRAW / node.removeprefix("/dev/")))
    action = "--action=change" if enabled else "--action=add"
    for device in devices:
        vid, pid = device.split(":")
        ok &= _run(udevadm, "trigger", "--subsystem-match=usb",
                   f"--attr-match=idVendor={vid}", f"--attr-match=idProduct={pid}",
                   action)
    ok &= _run(udevadm, "settle", "--timeout=10")
    getfacl, setfacl = _tool("getfacl"), _tool("setfacl")
    if not enabled and getfacl is not None and setfacl is not None:
        for node in nodes:
            if (acl := _read(getfacl, "-cpn", node)) is None:
                ok = False
            elif users := named_users(acl):
                ok &= _run(setfacl, "-x", ",".join(f"u:{u}" for u in users),
                           node)
    return ok


def parse(argv: list[str]) -> tuple[str, list[str]] | None:
    """``(action, words)`` for a valid command line, else None -- the whole
    check, before anything is touched."""
    match argv:
        case ["enable", key, *devices] if (
                KEY.fullmatch(key) and 0 < len(devices) <= MAX_DEVICES
                and len(set(devices)) == len(devices)
                and all(DEVICE.fullmatch(d) for d in devices)):
            return "enable", [key, *devices]
        case ["disable", key] if KEY.fullmatch(key):
            return "disable", [key]
        case ["disable-all"]:
            return "disable-all", []
    return None


def main() -> int:
    if (parsed := parse(sys.argv[1:])) is None:
        return 2                       # argv-locked: refused before anything runs
    if os.geteuid() != 0:
        return 3
    action, words = parsed
    try:
        if action == "enable":
            key, devices = words[0], words[1:]
            write(key, devices)
            return 0 if apply(True, devices) else 1
        removed: list[str] = []
        found = False
        for key in (words if action == "disable" else keys_written()):
            if (devices := remove(key)) is not None:
                found = True
                removed += devices
    except OSError:
        return 1
    if not found:
        return 0                       # nothing of TRCC's: touch nothing
    return 0 if apply(False, removed) else 1


if __name__ == "__main__":
    sys.exit(main())
