# SPDX-License-Identifier: MIT """Controlled Linux timestamp examples; touches only a private temporary directory.""" import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import platform import stat import subprocess import tempfile import time CASES = ("chmod-only", "set-same-times", "overwrite-restore-mtime") STAMP = 1_700_000_000_123_456_789 PAYLOAD = b"A" * 4096 def require(condition, message): if not condition: raise ValueError(message) def snapshot(path): # O_NOATIME keeps the byte oracle from changing the access timestamp. fd = os.open(path, os.O_RDONLY | os.O_NOATIME) try: data = bytearray() while chunk := os.read(fd, 8192): data.extend(chunk) info = os.fstat(fd) finally: os.close(fd) return { "size": info.st_size, "device": str(info.st_dev), "inode": str(info.st_ino), "mode": oct(stat.S_IMODE(info.st_mode)), "atimeNs": str(info.st_atime_ns), "mtimeNs": str(info.st_mtime_ns), "ctimeNs": str(info.st_ctime_ns), "sha256": hashlib.sha256(data).hexdigest(), } def validate_case(row): require(row["operation"] in CASES, "unknown operation") before, after = row["before"], row["after"] for key in ("device", "inode", "size", "atimeNs", "mtimeNs"): require(before[key] == after[key], "changed invariant: " + key) require(before["size"] == 4096, "unexpected size") require(before["mtimeNs"] == str(STAMP), "filesystem did not retain requested timestamp") require(before["ctimeNs"] != after["ctimeNs"], "ctime change was not observed") require(before["sha256"] == hashlib.sha256(PAYLOAD).hexdigest(), "wrong initial bytes") changed = row["operation"] == "overwrite-restore-mtime" expected = b"B" + PAYLOAD[1:] if changed else PAYLOAD require(after["sha256"] == hashlib.sha256(expected).hexdigest(), "wrong final bytes") require(before["mode"] == "0o600", "wrong initial mode") require(after["mode"] == ("0o640" if row["operation"] == "chmod-only" else "0o600"), "wrong final mode") return { "sameSize": True, "sameMtime": True, "sameInode": True, "ctimeChanged": True, "sameBytes": not changed, } def observe(scratch, repeats=3): require(platform.system() == "Linux", "Linux O_NOATIME required") require(repeats > 0, "repeats must be positive") rows = [] with tempfile.TemporaryDirectory(prefix="hesela-file-times-", dir=scratch) as directory: folder = Path(directory) filesystem = subprocess.run( ["stat", "-f", "-c", "%T", str(folder)], check=True, capture_output=True, text=True, ).stdout.strip() for operation in CASES: for repetition in range(repeats): path = folder / (operation + "-" + str(repetition)) path.write_bytes(PAYLOAD) path.chmod(0o600) os.utime(path, ns=(STAMP, STAMP)) before = snapshot(path) # Separate timestamp ticks; this is not a timing benchmark. time.sleep(1.1) if operation == "chmod-only": path.chmod(0o640) elif operation == "set-same-times": os.utime(path, ns=(STAMP, STAMP)) else: with path.open("r+b") as stream: stream.write(b"B") os.utime(path, ns=(STAMP, STAMP)) row = { "operation": operation, "repetition": repetition + 1, "before": before, "after": snapshot(path), } row["checks"] = validate_case(row) rows.append(row) return { "schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "kind": "controlled local software demonstration", "environment": { "os": platform.system(), "kernel": platform.release(), "machine": platform.machine(), "python": platform.python_version(), "filesystem": filesystem, }, "scriptSha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "repetitionsPerOperation": repeats, "timestampUnit": "nanoseconds since Unix epoch, encoded as decimal strings", "inputRecipe": "4096 ASCII A bytes; overwrite changes only byte zero to B", "byteOracle": "Complete read through O_NOATIME, compared to known payload SHA-256", "scope": "No remount, crash, power failure, birth-time or access-policy experiment; no rsync invocation.", "cases": rows, } if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--scratch", default="/dev/shm") parser.add_argument("--output", required=True) args = parser.parse_args() result = observe(args.scratch) Path(args.output).write_text(json.dumps(result, indent=2) + "\n")