#!/usr/bin/env python3 """Native Linux inotify ownership controls on fresh temporary files (CC0).""" import argparse from contextlib import ExitStack import ctypes from datetime import datetime, timezone import errno import hashlib import json import os from pathlib import Path import platform import select import struct import subprocess import tempfile ROOT = Path(__file__).resolve().parent MODIFY, CLOSE_WRITE = 0x2, 0x8 OVERFLOW, IGNORED = 0x4000, 0x8000 MASK_CREATE, MASK_ADD = 0x10000000, 0x20000000 ONESHOT = 0x80000000 HEADER = struct.Struct("=iIII") CASES = ( "alias-replace", "alias-union", "alias-create-guard", "alias-invalid-flags", "alias-remove-union", "alias-union-oneshot", "dup-drain", "dup-close-original", "separate-instances", "directory-outside-alias", "directory-inside-name", ) QUIET_SECONDS = 0.02 PAYLOAD = b"A" * 4096 def require(condition, message): if not condition: raise ValueError(message) def sha(data): return hashlib.sha256(data).hexdigest() def parse_events(data): events, offset = [], 0 while offset < len(data): require(len(data) - offset >= HEADER.size, "truncated event header") wd, mask, cookie, length = HEADER.unpack_from(data, offset) offset += HEADER.size require(length <= len(data) - offset, "truncated event name") raw = data[offset:offset + length] offset += length require(not raw or b"\0" in raw, "unterminated event name") require(not mask & OVERFLOW, "queue overflow invalidates observation") events.append({"wd": wd, "mask": mask, "cookie": cookie, "name": os.fsdecode(raw.split(b"\0", 1)[0])}) return events def drain(fd): select.select([fd], [], [], QUIET_SECONDS) events = [] while True: try: data = os.read(fd, 65536) except BlockingIOError: return events require(bool(data), "unexpected inotify EOF") events.extend(parse_events(data)) class Instance: def __init__(self): self.libc = ctypes.CDLL(None, use_errno=True) self.libc.inotify_init1.argtypes = [ctypes.c_int] self.libc.inotify_init1.restype = ctypes.c_int self.libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32] self.libc.inotify_add_watch.restype = ctypes.c_int self.libc.inotify_rm_watch.argtypes = [ctypes.c_int, ctypes.c_int] self.libc.inotify_rm_watch.restype = ctypes.c_int self.fd = self.libc.inotify_init1(os.O_NONBLOCK | os.O_CLOEXEC) if self.fd < 0: raise OSError(ctypes.get_errno(), "inotify_init1") def add(self, path, mask): ctypes.set_errno(0) wd = self.libc.inotify_add_watch(self.fd, os.fsencode(path), mask) error = ctypes.get_errno() if wd < 0 else 0 return {"return": wd, "errno": error, "errno_name": errno.errorcode.get(error), "requested_mask": mask} def remove(self, wd): ctypes.set_errno(0) result = self.libc.inotify_rm_watch(self.fd, wd) error = ctypes.get_errno() if result < 0 else 0 return {"return": result, "errno": error, "errno_name": errno.errorcode.get(error)} def close(self): if self.fd >= 0: os.close(self.fd) self.fd = -1 def identity(path): stat = path.stat() return {"device": stat.st_dev, "inode": stat.st_ino, "links": stat.st_nlink, "size": stat.st_size} def fdinfo(fd): return [line for line in Path(f"/proc/self/fdinfo/{fd}").read_text().splitlines() if line.startswith("inotify ")] def one_case(directory, case): require(case in CASES, "unknown case") with tempfile.TemporaryDirectory(prefix="hesela-watch-owner-", dir=directory) as tmp, ExitStack() as stack: root = Path(tmp) inside, outside = root / "inside", root / "outside" inside.mkdir() outside.mkdir() path, alias = inside / "payload", outside / "alias" path.write_bytes(PAYLOAD) os.link(path, alias) before = {"path": identity(path), "alias": identity(alias)} require(before["path"] == before["alias"], "hard-link identity mismatch") writer_path = path if case == "directory-inside-name" else alias writer = stack.enter_context(os.fdopen(os.open(writer_path, os.O_RDWR), "r+b", buffering=0)) a = Instance() stack.callback(a.close) initial_target = inside if case.startswith("directory-") else path first = a.add(initial_target, MODIFY) require(first["return"] >= 0, "initial watch failed") calls = {"first_add": first} readers = {"a": a.fd} if case in ("alias-replace", "alias-union", "alias-create-guard", "alias-invalid-flags", "alias-remove-union", "alias-union-oneshot"): flags = {"alias-replace": 0, "alias-union": MASK_ADD, "alias-create-guard": MASK_CREATE, "alias-invalid-flags": MASK_CREATE | MASK_ADD, "alias-remove-union": MASK_ADD, "alias-union-oneshot": MASK_ADD | ONESHOT}[case] calls["second_add"] = a.add(alias, CLOSE_WRITE | flags) if case == "alias-remove-union": calls["remove_via_second_wd"] = a.remove(calls["second_add"]["return"]) elif case in ("dup-drain", "dup-close-original"): duplicate = os.dup(a.fd) stack.callback(os.close, duplicate) # Read the duplicate first; dup is not a new notification instance. readers = {"duplicate": duplicate, "original": a.fd} if case == "dup-close-original": a.close() readers.pop("original") elif case in ("separate-instances", "directory-outside-alias", "directory-inside-name"): b = Instance() stack.callback(b.close) second_mask = MODIFY | CLOSE_WRITE calls["second_add"] = b.add(alias, second_mask) require(calls["second_add"]["return"] >= 0, "independent watch failed") readers["b"] = b.fd configured = {name: fdinfo(fd) for name, fd in readers.items()} configuration_events = {name: drain(fd) for name, fd in readers.items()} require(os.pwrite(writer.fileno(), b"B", 0) == 1, "short pwrite") actual = os.pread(writer.fileno(), len(PAYLOAD) + 1, 0) require(actual == b"B" + PAYLOAD[1:], "full payload comparison failed") write_events = {name: drain(fd) for name, fd in readers.items()} writer.close() close_events = {name: drain(fd) for name, fd in readers.items()} return { "case": case, "calls": calls, "identity_before": before, "identity_after": {"path": identity(path), "alias": identity(alias)}, "write_via": "inside/payload" if writer_path == path else "outside/alias", "pwrite_calls": 1, "changed_bytes": 1, "before_sha256": sha(PAYLOAD), "after_sha256": sha(actual), "fdinfo_after_configuration": configured, "configuration_events": configuration_events, "write_events": write_events, "close_events": close_events, } def projection(row): """Portable behavioral comparison; retain raw descriptors in the capture.""" return { "case": row["case"], "changed_bytes": row["changed_bytes"], "call_outcomes": {key: {"ok": call["return"] >= 0, "errno": call["errno"]} for key, call in row["calls"].items()}, "same_wd": (row["calls"]["first_add"]["return"] == row["calls"]["second_add"]["return"]) if "second_add" in row["calls"] and row["calls"]["second_add"]["return"] >= 0 and row["case"].startswith("alias-") else None, "watch_counts": {key: len(lines) for key, lines in row["fdinfo_after_configuration"].items()}, "events": {phase: {reader: [{"mask": e["mask"], "cookie": e["cookie"], "name": e["name"]} for e in events] for reader, events in row[phase].items()} for phase in ("configuration_events", "write_events", "close_events")}, } def capture(directories, repetitions): require(type(repetitions) is int and repetitions > 0, "positive repetitions required") require(bool(directories), "mount directories required") runs = [] for directory in directories: path = Path(directory).resolve(strict=True) require(path.is_dir(), "directory required") filesystem = subprocess.check_output( ["findmnt", "-n", "-o", "FSTYPE", "--target", str(path)], text=True).strip() runs.append({"directory": str(path), "filesystem": filesystem, "observations": [[one_case(path, case) for case in CASES] for _ in range(repetitions)]}) return { "schema_version": 1, "kind": "native_inotify_ownership_controls", "generated_at": datetime.now(timezone.utc).isoformat(), "environment": {"kernel": platform.release(), "python": platform.python_version(), "libc": list(platform.libc_ver()), "machine": platform.machine()}, "source_sha256": sha(Path(__file__).read_bytes()), "repetitions": repetitions, "cases": list(CASES), "quiet_wait_seconds": QUIET_SECONDS, "scope": "Sequential fresh-file syscalls on one host; no power-loss or backup-product test.", "runs": runs, } def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("--directory", action="append", required=True) p.add_argument("--repetitions", type=int, default=3) p.add_argument("--output", type=Path, required=True) args = p.parse_args() result = capture(args.directory, args.repetitions) args.output.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n") print(json.dumps({"observations": len(args.directory) * args.repetitions * len(CASES), "output": str(args.output)})) if __name__ == "__main__": main()