| 1 | """Read only the two Cage GUI helpers' bounded, machine-code diagnostic logs.""" |
| 2 | from collections import deque |
| 3 | from datetime import datetime, timedelta, timezone |
| 4 | import heapq |
| 5 | import itertools |
| 6 | import json |
| 7 | import os |
| 8 | from pathlib import Path |
| 9 | import re |
| 10 | import stat |
| 11 | |
| 12 | root = Path.home() / "Library/Logs/Cage" |
| 13 | entries = [] |
| 14 | order = itertools.count() |
| 15 | cutoff = datetime.now(timezone.utc) - timedelta(days=14) |
| 16 | if root.exists(): |
| 17 | directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) |
| 18 | try: |
| 19 | info = os.fstat(directory) |
| 20 | if info.st_uid != os.getuid() or info.st_mode & 0o077: |
| 21 | raise ValueError("diagnostic_directory_invalid") |
| 22 | for source in ("window", "clipboard"): |
| 23 | |
| 24 | |
| 25 | for suffix in ("-4", "-3", "-2", "-1", ""): |
| 26 | try: |
| 27 | fd = os.open(source + suffix + ".jsonl", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) |
| 28 | except FileNotFoundError: |
| 29 | continue |
| 30 | with os.fdopen(fd, "r", encoding="utf-8", errors="replace") as stream: |
| 31 | info = os.fstat(stream.fileno()) |
| 32 | if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_nlink != 1 or info.st_size > (1 << 20) + 4096: |
| 33 | raise ValueError("diagnostic_file_invalid") |
| 34 | for line in stream: |
| 35 | if len(line) > 4096: |
| 36 | continue |
| 37 | try: |
| 38 | value = json.loads(line) |
| 39 | time = datetime.fromisoformat(value["time"].replace("Z", "+00:00")) |
| 40 | reason = value["reason"] |
| 41 | if time.tzinfo is None or time < cutoff or value["source"] != source or not re.fullmatch(r"[a-zA-Z][a-zA-Z0-9_]{0,95}", reason): |
| 42 | continue |
| 43 | entry = (time, next(order), dict(time=value["time"], source=source, reason=reason)) |
| 44 | heapq.heappush(entries, entry) |
| 45 | if len(entries) > 150: |
| 46 | heapq.heappop(entries) |
| 47 | except (ValueError, KeyError, TypeError, AttributeError): |
| 48 | continue |
| 49 | finally: |
| 50 | os.close(directory) |
| 51 | lines = deque() |
| 52 | size = 0 |
| 53 | for _, _, entry in sorted(entries): |
| 54 | line = json.dumps(entry, ensure_ascii=True) + "\n" |
| 55 | lines.append(line) |
| 56 | size += len(line.encode()) |
| 57 | while len(lines) > 150 or size > 48 << 10: |
| 58 | size -= len(lines.popleft().encode()) |
| 59 | print(json.dumps(dict(version=1, lines="".join(lines)))) |