CLI for SidePulse
Python
Recover eject guard after Disk Arbitration restarts
Peter Kuharb99c029c866c
diff --git a/README.md b/README.mdindex 03549e3..6e21ee2 100644--- a/README.md+++ b/README.md@@ -538,6 +538,11 @@ macOS hibernate or lock-screen mount refusals. By default setup installs itsystem-wide when already running with system permissions, otherwise as aper-user LaunchAgent:+The guard checks whether macOS restarted Disk Arbitration. If it did, the+guard exits and launchd starts it again with a fresh disk session. KeepAlive+must remain enabled for this recovery; an interactive guard run needs a manual+restart after a Disk Arbitration restart.+```shsidepulse setup --sd-eject-guard-scope autosidepulse setup --sd-eject-guard-scope userdiff --git a/src/sidepulse/resources/sd_eject_guard.c b/src/sidepulse/resources/sd_eject_guard.cindex 3161e59..1f02939 100644--- a/src/sidepulse/resources/sd_eject_guard.c+++ b/src/sidepulse/resources/sd_eject_guard.c@@ -6,6 +6,8 @@// mechanism, so a registered client can dissent it right back. This tool does// that, then retries the mount every few seconds; the retries are dissented// while locked and succeed after unlock.+// A Disk Arbitration daemon restart can leave this session registered only+// with the old daemon. Exit when its PID changes so launchd starts a fresh one.//// Build: clang -o "SidePulse Pro Eject Prevention" sd_eject_guard.c \// -framework DiskArbitration -framework CoreFoundation@@ -15,15 +17,44 @@#include <CoreFoundation/CoreFoundation.h>#include <DiskArbitration/DiskArbitration.h>#include <stdio.h>+#include <stdlib.h>#include <string.h>#include <sys/stat.h>#include <unistd.h>#define MOUNT_RETRY_SECONDS 5.0+#define DA_PID_CHECK_SECONDS 0.5#define LOG_TRUNCATE_BYTES (10 * 1024 * 1024)+#ifndef SD_EJECT_GUARD_DA_PIDFILE+#define SD_EJECT_GUARD_DA_PIDFILE "/var/run/diskarbitrationd.pid"+#endifstatic DASessionRef g_session;static bool g_no_mount = false;+static long g_da_pid = 0;++static long disk_arbitration_pid(void) {+ FILE *file = fopen(SD_EJECT_GUARD_DA_PIDFILE, "r");+ if (!file) return 0;+ long pid = 0;+ if (fscanf(file, "%ld", &pid) != 1 || pid <= 0) pid = 0;+ fclose(file);+ return pid;+}++static void check_disk_arbitration(CFRunLoopTimerRef timer, void *ctx) {+ (void)timer;+ (void)ctx;+ long pid = disk_arbitration_pid();+ if (g_da_pid > 0 && pid > 0 && pid != g_da_pid) {+ fprintf(stderr, "diskarbitrationd changed from %ld to %ld; restarting guard\n",+ g_da_pid, pid);+ fflush(stderr);+ // launchd KeepAlive starts a new process with fresh DA callbacks.+ exit(0);+ }+ if (g_da_pid == 0) g_da_pid = pid;+}static void truncate_stdout_if_large(void) {fflush(stdout);@@ -120,6 +151,7 @@ int main(int argc, char **argv) {return 2;}}+ g_da_pid = disk_arbitration_pid();g_session = DASessionCreate(kCFAllocatorDefault);if (!g_session) {fprintf(stderr, "DASessionCreate failed\n");@@ -127,6 +159,14 @@ int main(int argc, char **argv) {}DARegisterDiskEjectApprovalCallback(g_session, NULL, eject_approval, NULL);DASessionScheduleWithRunLoop(g_session, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);+ check_disk_arbitration(NULL, NULL);+ CFRunLoopTimerRef daemon_timer = CFRunLoopTimerCreate(+ kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + DA_PID_CHECK_SECONDS,+ DA_PID_CHECK_SECONDS, 0, 0, check_disk_arbitration, NULL);+ CFRunLoopAddTimer(CFRunLoopGetCurrent(), daemon_timer, kCFRunLoopDefaultMode);+ CFRelease(daemon_timer);+ printf("SidePulse Pro Eject Prevention: watching Disk Arbitration PID %ld\n", g_da_pid);+ fflush(stdout);CFRunLoopRun();return 0;}diff --git a/tests/test_sd_eject_guard.py b/tests/test_sd_eject_guard.pynew file mode 100644index 0000000..1cf7c33--- /dev/null+++ b/tests/test_sd_eject_guard.py@@ -0,0 +1,48 @@+from __future__ import annotations++import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++[email protected](sys.platform == "darwin", "requires macOS Disk Arbitration")+class SdEjectGuardProcessTests(unittest.TestCase):+ def test_restarts_after_disk_arbitration_daemon_changes(self) -> None:+ source = Path(__file__).resolve().parents[1] / "src/sidepulse/resources/sd_eject_guard.c"+ with tempfile.TemporaryDirectory() as tmp:+ base = Path(tmp)+ pidfile = base / "diskarbitrationd.pid"+ binary = base / "sd_eject_guard"+ pidfile.write_text("111\n", encoding="ascii")+ subprocess.run(+ [+ "clang",+ "-O2",+ f'-DSD_EJECT_GUARD_DA_PIDFILE="{pidfile}"',+ "-o",+ str(binary),+ str(source),+ "-framework",+ "DiskArbitration",+ "-framework",+ "CoreFoundation",+ ],+ check=True,+ )++ process = subprocess.Popen(+ [str(binary)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True+ )+ try:+ assert process.stdout is not None+ self.assertIn("watching Disk Arbitration PID 111", process.stdout.readline())+ pidfile.write_text("222\n", encoding="ascii")+ _, error = process.communicate(timeout=5)+ self.assertEqual(process.returncode, 0)+ self.assertIn("changed from 111 to 222; restarting guard", error)+ finally:+ if process.poll() is None:+ process.kill()+ process.communicate()