RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Implement ConsoleKit2 sessions and a portable login supervisor
oxydizer803e02d9b128
diff --git a/TESTING.md b/TESTING.mdindex 9c0fc35..75d59ed 100644--- a/TESTING.md+++ b/TESTING.md@@ -16,6 +16,9 @@ in `zig build test`.handles, file watching, own executable path) against real processes andtemporary directories.+`zig build test-login-manager` tests ConsoleKit2 session ownership, identity+rejection and private user-bus startup against independent private-bus peers.+`tools/freebsd-cross/check.sh [-Doptimize=ReleaseSafe | test]` cross-builds thetree for FreeBSD on this host (Arch, `bwrap`); run it after touching OSinterfaces, C headers or `src/platform/`. It proves compilation only.diff --git a/build.zig b/build.zigindex 28a11d9..ece0cbc 100644--- a/build.zig+++ b/build.zig@@ -225,7 +225,8 @@ pub fn build(b: *std.Build) void {.transfers = b.option(bool, "transfers", "Build and install the torrent transfers helper (default: on, except on FreeBSD)") orelse (target.result.os.tag != .freebsd),// rediwm-session and rediwm-dm still run on signalfd, epoll, pidfd and Linux VT ioctls; the FreeBSD// port starts the compositor from the console (docs/plans/freebsd.md, D2 and phase 2).- .login_session = b.option(bool, "login-session", "Build and install rediwm-session and rediwm-dm (default: on, except on FreeBSD)") orelse (target.result.os.tag != .freebsd),+ .display_manager = b.option(bool, "display-manager", "Build and install rediwm-dm (default: on, except on FreeBSD)") orelse (target.result.os.tag != .freebsd),+ .login_session = b.option(bool, "login-session", "Build and install rediwm-session (default: on, except on FreeBSD)") orelse (target.result.os.tag != .freebsd),.i18n_tool = i18n_tool,.wayland = wayland,.xkbcommon = xkbcommon,diff --git a/build/context.zig b/build/context.zigindex 4bf675a..e14d7a4 100644--- a/build/context.zig+++ b/build/context.zig@@ -12,6 +12,7 @@ pub const Context = struct {use_llvm: bool,transfers: bool,login_session: bool,+ display_manager: bool,wlroots_prefix: ?[]const u8,i18n_tool: *std.Build.Step.Compile,wayland: *std.Build.Module,diff --git a/build/login_tests.zig b/build/login_tests.zignew file mode 100644index 0000000..3a65492--- /dev/null+++ b/build/login_tests.zig@@ -0,0 +1,28 @@+//! Portable supervisor primitives and the independent ConsoleKit2 bus fixture.+const std = @import("std");+const Context = @import("context.zig").Context;++pub fn add(ctx: Context, test_step: *std.Build.Step) void {+ const b = ctx.b;+ const target = ctx.target;+ const optimize = ctx.optimize;+ const use_llvm = ctx.use_llvm;+ const wayland = ctx.wayland;+ const run_platform_tests = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/platform/mod.zig"), .target = target, .optimize = optimize, .link_libc = true }) }));+ test_step.dependOn(&run_platform_tests.step);+ b.step("test-platform", "Test child handles, file watching and the program's own path").dependOn(&run_platform_tests.step);+ const login_service = b.addExecutable(.{+ .name = "login-manager-test-service",+ .root_module = b.createModule(.{ .root_source_file = b.path("src/login_manager_test_service.zig"), .target = target, .optimize = optimize, .link_libc = true }),+ .use_llvm = use_llvm,+ .use_lld = use_llvm,+ });+ login_service.root_module.addImport("wayland", wayland);+ login_service.root_module.addImport("dbus", ctx.dbus_mod);+ login_service.root_module.addImport("platform", ctx.platform_mod);+ login_service.root_module.linkSystemLibrary("wayland-server", .{});+ const login_integration = b.addSystemCommand(&.{"python3"});+ login_integration.addFileArg(b.path("tests/consolekit.py"));+ login_integration.addArtifactArg(login_service);+ b.step("test-login-manager", "Test ConsoleKit2 login ownership on a private bus").dependOn(&login_integration.step);+}diff --git a/build/session.zig b/build/session.zigindex 2490df9..9cbcbed 100644--- a/build/session.zig+++ b/build/session.zig@@ -10,7 +10,8 @@ pub const Session = struct {};/// rediwm-session, rediwm-dm and the accounts helper. The first two are always-/// described (tests and other steps name them) but installed only with `login_session`.+/// described (tests and other steps name them). Installation needs `login_session`;+/// the DM additionally needs `display_manager`, so FreeBSD can build just the supervisor.pub fn add(ctx: Context) Session {const b = ctx.b;const target = ctx.target;@@ -29,6 +30,7 @@ pub fn add(ctx: Context) Session {.use_llvm = use_llvm,.use_lld = use_llvm,});+ b.step("login-session", "Build the login supervisor").dependOn(&session_supervisor.step);session_supervisor.root_module.addImport("wayland", wayland);session_supervisor.root_module.linkSystemLibrary("wayland-server", .{});if (wlroots_prefix != null) session_supervisor.root_module.addRPathSpecial("$ORIGIN/../lib/rediwm");@@ -82,7 +84,7 @@ pub fn add(ctx: Context) Session {dm.root_module.addImport("wayland_sessions", ws_mod);dm.root_module.linkSystemLibrary("pam", .{});dm.root_module.addCSourceFile(.{ .file = b.path("src/dm/pam.c"), .flags = &.{"-std=c11"} });- if (ctx.login_session) b.installArtifact(dm);+ if (ctx.display_manager and ctx.login_session) b.installArtifact(dm);b.step("rediwm-dm", "Build the display manager").dependOn(&dm.step);const accounts_helper = b.addExecutable(.{diff --git a/build/tests.zig b/build/tests.zigindex 987ea90..131a2d3 100644--- a/build/tests.zig+++ b/build/tests.zig@@ -106,9 +106,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {const i18n_tests = b.addTest(.{ .root_module = i18n_mod });const run_i18n_tests = b.addRunArtifact(i18n_tests);test_step.dependOn(&run_i18n_tests.step);- const run_platform_tests = b.addRunArtifact(b.addTest(.{ .root_module = ctx.platform_mod }));- test_step.dependOn(&run_platform_tests.step);- b.step("test-platform", "Test child handles, file watching and the program's own path").dependOn(&run_platform_tests.step);+ @import("login_tests.zig").add(ctx, test_step);const theme_policy_tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/theme_helper/syscall_policy.zig"), .target = target, .optimize = optimize, .link_libc = true }) });theme_policy_tests.root_module.addImport("platform", ctx.platform_mod);test_step.dependOn(&b.addRunArtifact(theme_policy_tests).step);@@ -284,7 +282,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {dm_tests.root_module.linkSystemLibrary("pam", .{});dm_tests.root_module.addCSourceFile(.{ .file = b.path("src/dm/pam.c"), .flags = &.{"-std=c11"} });const run_dm_tests = b.addRunArtifact(dm_tests);- if (ctx.login_session) test_step.dependOn(&run_dm_tests.step);+ if (ctx.login_session and ctx.display_manager) test_step.dependOn(&run_dm_tests.step);const dm_step = b.step("test-dm", "Run unit tests for rediwm-dm");dm_step.dependOn(&run_dm_tests.step);diff --git a/docs/agent-notes/map.md b/docs/agent-notes/map.mdindex 69ccdf1..aed795a 100644--- a/docs/agent-notes/map.md+++ b/docs/agent-notes/map.md@@ -97,7 +97,7 @@ and `effects/minimize_mesh.zig` (minimize snapshots and deformation),* **Session** (`session/`, `AGENTS.md` there): `lock.zig` (+ `lock_account`,`lock_events`, `lock_input`, `lock_view.zig`), `greeter.zig`, `idle.zig`,`power.zig` (+ `power_*.zig`), `login_manager.zig` (`login_manager/`: service- protocol shared with the supervisor and polkit; currently logind), portals (`settings_portal.zig`,+ logind/ConsoleKit2 protocol shared with the supervisor and polkit), portals (`settings_portal.zig`,`file_chooser.zig`), services.* The desktop icons (`desktop/`), `power_menu.zig`, `osd.zig`,`calendar.zig`, `battery_popup.zig`, `network/popup.zig`, `mini_map.zig`,diff --git a/docs/freebsd-build.md b/docs/freebsd-build.mdindex c981c45..cf71951 100644--- a/docs/freebsd-build.md+++ b/docs/freebsd-build.md@@ -50,7 +50,7 @@ What each is for:zig build testOff by default on FreeBSD: the transfers helper (`-Dtransfers`) and-`rediwm-session`/`rediwm-dm` (`-Dlogin-session`). The install prefix is+`rediwm-session` (`-Dlogin-session`) and `rediwm-dm` (`-Ddisplay-manager`). The install prefix is`/usr/local`, configuration `/usr/local/etc` and run state `/var/run`(`-Dinstall-prefix`, `-Dsysconfdir`, `-Drundir`).@@ -88,4 +88,36 @@ need besides the packages above: `squashfs-tools` (`files_associations`),(`files_torrents`). Several suites are Linux only: `system_monitor` (a seccompguard and `/proc`), `motion_perf` and `editor_visuals` (`/proc`),`battery_*` and `pdf_sandbox` (Linux hook libraries), `steamos_bundle`,-and those that need `rediwm-session` or `rediwm-dm`.+and those that need `rediwm-dm`. The supervisor's portable tests are listed below;+its logind-specific bus fixture and pidfd-based readiness fixture remain Linux only.+++## Console session candidate++The ConsoleKit2 backend and kqueue supervisor compile, but have not yet had+native runtime qualification. Build the supervisor without the display manager:++ zig build -Dlogin-session=true -Ddisplay-manager=false+ zig build test-platform test-monitor test-login-manager+ python3 tests/rediwm_session.py+ python3 tests/session_services.py zig-out/bin/rediwm-session++Enable dbus, ConsoleKit2, seatd and polkit; configure `pam_xdg` for the console+login and join the seatd socket's group. From a real `/dev/ttyv*` console login,+with a private `XDG_RUNTIME_DIR`, start using the installed path:++ export LIBSEAT_BACKEND=seatd+ exec /usr/local/bin/rediwm-session++The supervisor creates its own ConsoleKit2 session, exports its cookie only to+its children, and closes it at logout. It reuses a responding inherited user+bus or starts a private one. The session bus survives compositor restarts.+The legacy polkit helper socket may be absent: the existing fallback checks+root ownership and setuid permissions before launching polkit's helper.++Before enabling the supervisor by default, run the crash/locked-crash and+adopted-child tests above on FreeBSD, and qualify VT switching, console input+isolation, polkit prompts, suspend inhibitors, resume and clean logout on DRM.+`tests/session_bus.py` specifically exercises the logind backend on Linux;+`test-login-manager` exercises ConsoleKit2 with an independent private bus on+either OS. Power/battery/brightness hardware qualification is still separate.diff --git a/docs/plans/freebsd.md b/docs/plans/freebsd.mdindex 28cb5ea..195e1c3 100644--- a/docs/plans/freebsd.md+++ b/docs/plans/freebsd.md@@ -1,10 +1,12 @@# FreeBSD support plan-Status: 2026-11-06, FreeBSD 15.1 only (D1). The tree builds there and the-compositor and apps run headless on GLES2 over a virtio GPU. What is left is-the login and session stack, the Linux-only interfaces, sandboxes, a few-FreeBSD-only test failures and packaging. D1–D5 are decided, D6 waits for-phase 2, D7–D9 are recommendations.+Status: 2026-11-09, FreeBSD 15.1 only (D1). The last native validation was+2026-11-06: the tree builds and the compositor/apps run headless on GLES2 over+a virtio GPU. ConsoleKit2 and the portable supervisor now have implementations+and private-bus coverage; native session qualification is still required. The+remaining work includes battery/brightness, Linux-only interfaces, sandboxes,+FreeBSD-only test failures and packaging. D1–D5 and D8–D9 are decided; D6 waits+for phase 2, D7 remains a recommendation.Goal: run RediWM on FreeBSD: the compositor in a seatd session on DRM, then theshell features and apps, last `rediwm-dm` and packaging. Linux stays the@@ -22,11 +24,27 @@ primary platform; the port must not change Linux behaviour or cost.by the supervisor, power policy and polkit. Its logind backend owns therequests, signal descriptors, identity checks and power-command selection;callers keep their connection lifetimes and owner-generation checks. A- recording transport tests requests without a bus. ConsoleKit2 remains phase 2.+ recording transport tests requests without a bus.Linux Debug/ReleaseSafe, unit tests, polkit, session-bus, supervisor,power-settings and greeter pass; the cross-check passes. Power's two finalhelper-cleanup cases fail identically on clean HEAD (`b9f10be`); its login,inhibitor and action cases pass.+* **Session implementation (2026-11-09, native qualification pending):** the+ ConsoleKit2 backend opens a Wayland user session from a console tty, verifies+ its uid/locality/type/class/remote host, retains its cookie and owning D-Bus+ connection across compositor restarts, and closes it on exit or rejection.+ Power, inhibitors, Lock/LockedHint and polkit lookup use the backend. The+ supervisor uses signalfd on Linux and kqueue on FreeBSD, with shared crash+ and lock-state handling. Process-tree reads live in the proc backends;+ FreeBSD teardown rechecks start stamps after opening handles. A missing+ user bus starts a private dbus-daemon; activation uses that bus without a+ systemd manager. `-Dlogin-session=true -Ddisplay-manager=false` builds this+ candidate; the supervisor remains off by default on FreeBSD until tested there.+ Linux unit/platform/monitor, ConsoleKit2/private-bus, polkit, supervisor,+ power-settings and greeter checks pass, as do FreeBSD compilation checks+ for the supervisor and tests. Monitor's scale-1 workspace idle check fails+ identically on clean `b9f10be`; scale 1.5 passes. Power retains the two+ baseline helper-cleanup failures noted above.* **On 15.1** (HyprBSD VM, Zig 0.17.1): Debug builds in 2.5 minutes,ReleaseSafe in 6.7. `zig build test` passes, and so do `test-monitor` (the`kern.proc` backend and kqueue End/Force), `test-platform`, `test-files`,@@ -35,6 +53,8 @@ primary platform; the port must not change Linux behaviour or cost.`files_browser`, `images_viewer`, `editor`, `launch_placeholder`,`focus_zoom`, `window_snapping`, most appearance, undo, window-rule andprotocol suites). Kqueue child handles work in the Wayland loop.+ The later HyprBSD follow-up also reported nested ReleaseSafe rendering,+ 93 CLI checks and app-activation integration passing.* **Found by running there and fixed:** synthetic input stamped with clock id1 (`CLOCK_VIRTUAL` on FreeBSD); Files' `rm --interactive=never`; a ControlCenter crash on a zoomed camera (also on Linux); tests naming `/bin/true`,@@ -54,8 +74,7 @@ primary platform; the port must not change Linux behaviour or cost.needs a FreeBSD variant; `motion_perf`, `editor_visuals`, `battery_*`,`pdf_sandbox` and `steamos_bundle` are Linux only too. The other failuresalso fail on Linux at HEAD.-* Not tried: a DRM session on real or virtual hardware, a nested session under- Hyprland, `rediwm-msg` outside the tests, `memfd_create`, the transfers+* Not tried: a DRM session on real or virtual hardware, `memfd_create`, the transfershelper's C++ flags under clang and libc++.* Name order follows FreeBSD's libc (`de_DE` is a link to `en_US`, Cyrillic hasno usable weights); the German and Russian order tests skip off Linux (D7).@@ -64,14 +83,14 @@ primary platform; the port must not change Linux behaviour or cost.| Linux interface | Where | FreeBSD || --- | --- | --- |-| pidfd in `child.h` (the C side) | terminal engine, supervisor, dm | kqueue `EVFILT_PROC`/`NOTE_EXIT` like the Zig side. Handles on other processes (client pids, IPC peers, monitor) need an identity check (start time from `kern.proc`; the monitor's actions already do); `Handle.pid()` (fdinfo) has no counterpart. |-| `signalfd`, `epoll` | supervisor, dm | kqueue `EVFILT_SIGNAL`, kqueue. |+| pidfd in `child.h` (the C side) | terminal engine, dm | kqueue `EVFILT_PROC`/`NOTE_EXIT` like the Zig side. Handles on other processes (client pids, IPC peers, monitor) need an identity check (start time from `kern.proc`; the monitor's actions already do); `Handle.pid()` (fdinfo) has no counterpart. |+| `signalfd`, `epoll` | dm | kqueue `EVFILT_SIGNAL`, kqueue. The supervisor is ported. || `/proc/self/fd`, `fdinfo` | spawn paths; fd-as-path opens in `files/properties`, `pdf/print.c`, `pdf/sandbox.c`, `files/terminal/child.c` | `closefrom` for spawn paths; the path form needs `fdescfs` or `*at` calls, per site. || `pty.h`, `SCM_CREDENTIALS`, `/proc` walks | Files terminal engine | `ft_start` refuses on FreeBSD. Port the per-message check (`SCM_CREDS` is sender-attached, so `bash.c` would send it) and the session teardown walk (`kern.proc` by session); needs a FreeBSD to test on. |-| `/proc/<pid>` leftovers | `detectSandbox` (no Flatpak: "not sandboxed"), editor memory probe, `session_restart` (Linux install tool), supervisor teardown tree | A failed read means "not sandboxed" or no check; the supervisor's walk is phase 2. |+| `/proc/<pid>` leftovers | `detectSandbox` (no Flatpak: "not sandboxed"), editor memory probe, `session_restart` (Linux install tool) | A failed read means "not sandboxed" or no check; supervisor teardown uses the proc backend. || `DRM_IOCTL_VERSION` | `Output.zig` | `drmGetVersion`; skipped on FreeBSD (a hypervisor-GPU workaround only). || netlink `KOBJECT_UEVENT` | printer hotplug | devd's seqpacket socket; rescans only today. |-| `gettid`; `fork`/`kill`/`wait4`/`poll` loops | `thumbs`; supervisor and dm | A `platform` wrapper; the loops are replaced in phases 2 and 4. |+| `gettid`; `fork`/`kill`/`wait4`/`poll` loops | `thumbs`; dm | A `platform` wrapper; the DM loop remains phase 4. || `RENAME_EXCHANGE`, `renameat2` | theme helper, transfers helper | Linux only. |Done and not repeated: the Zig side of pidfd, inotify, eventfd, `prctl`,@@ -120,28 +139,25 @@ libinput on libudev-devd. To check on real hardware: VT switching underafter logind confirms the login (`login_bus.zig`: Type=wayland, Class=user,Desktop=rediwm, not remote, same uid), gates the polkit agent, the activationenvironment, following `Lock` and keeping `LockedHint`, and the Files terminal.-Left to do:--* A ConsoleKit2 backend for the shared login-manager interface (P.11 done):- session of a pid, `Lock` signal,- `SetLockedHint`, sleep and lid inhibitors with `PrepareForSleep`, capability- probes, power calls. The existing backend is in `session/login_manager/`;- `login_bus`, `power_*` and `polkit/agent` use the shared boundary.-* A ConsoleKit2 check (D8): local, our uid, Type=wayland, not remote, from a- session `rediwm-session` opens itself. No Desktop property, and a session- without a display device is never active, so "active" cannot be required.+The shared interface is `session/login_manager.zig`. Logind retains its existing+validation; the ConsoleKit2 backend opens its own session and checks local,+same uid, Type=wayland, Class=user and empty remote host. It does not require+Active or Desktop. Its identity is a same-uid assertion, not PAM attestation.+Native qualification must still cover power authorization, inhibitors, daemon+restart, lock-before-sleep and the polkit helper.**Session environment.** `XDG_RUNTIME_DIR` comes from `pam_xdg` (HyprBSD putsit in `/etc/pam.d/system`, which `login` and the DM include and `sshd` does-not). Socket paths must fit `sun_path`'s 103 characters. Nothing starts the-session bus: `rediwm-session` starts `dbus-daemon --session` when nothing-listens, or the start script wraps it in `dbus-run-session`. `dbus`, `seatd`,+not). Socket paths must fit `sun_path`'s 103 characters. `rediwm-session` reuses a responding+inherited user bus or starts a private `dbus-daemon --session`, retaining it+across compositor restarts and removing its socket on exit. `dbus`, `seatd`,ConsoleKit2 and polkitd must be enabled.-**Supervisor.** `rediwm-session` is Linux only (pidfd, signalfd, subreaper,-`std.os.linux`) and not built on FreeBSD. "A crash never unlocks" relies on it-restarting the compositor locked, so its port (phase 2) comes before FreeBSD-claims a lock. Until then, `exec` the session from the login shell (D9).+**Supervisor.** `rediwm-session` now shares the restart/lock-report loop across+Linux and FreeBSD; signals are signalfd/kqueue and child handles are platform+handles. It has compiled for FreeBSD, but the native crash/reap tests and a+DRM run remain required before claiming the lock guarantee. Start with `exec`+from the console login shell so exiting the supervisor ends that login (D9).**What the probe showed** (HyprBSD VM, ConsoleKit2 2.0.0, seatd 0.9.3, polkit128, over ssh and under `ck-launch-session`):@@ -210,18 +226,20 @@ installers (GNU `install -D`, systemd units, Debian/Arch PAM files); FreeBSD's### 1. Compositor runs (finish)-Headless works. Left: a DRM session on the VM's virtio GPU or real hardware, a-nested session under Hyprland, the four pixel suites above, `memfd_create`,-the transfers helper if wanted. `rediwm-session` and `rediwm-dm` stay off-(`-Dlogin-session`, default off there) until phases 2 and 4. Goal: `rediwm`+Headless and nested work. Left: a DRM session on the VM's virtio GPU or real+hardware, the four pixel suites above, `memfd_create`,+the transfers helper if wanted. `rediwm-session` stays off by default+(`-Dlogin-session`) pending native qualification; `rediwm-dm` stays off+(`-Ddisplay-manager`) until phase 4. Goal: `rediwm`and the apps start in a seatd session.### 2. Real session-The ConsoleKit2 login-manager implementation (`rediwm-session` opens the-session; identity, power, suspend, inhibitor; lock follows `Lock`); `pam_xdg`-and the session bus; battery and brightness backends; `rediwm-session`-supervisor on kqueue. Goal: a daily-usable session started from the console.+Qualify the ConsoleKit2/supervisor implementation on FreeBSD: console login,+private/inherited bus, polkit, power and inhibitors, crash while locked,+reaping adopted children, clean logout and VT isolation. Check the `pam_xdg`+setup. Implement battery and brightness backends. Goal: a daily-usable session+started from the console; a cross-build alone does not satisfy this milestone.### 3. Parity@@ -251,10 +269,10 @@ release tarball or a port (D6); FreeBSD in `make-release.sh` verification.* **D8 Login check on FreeBSD:** `rediwm-session` opens the ConsoleKit2 sessionitself (Type=wayland), so the logind check's shape stays minus Desktop and aconsole login needs no relaxation. It proves a process of this user- registered a session, not that PAM did. Recommended.+ registered a session, not that PAM did. Implemented; native validation pending.* **D9 First start path:** `rediwm-session` from a console login (profile or asmall start script), not greetd; the lock's crash guarantee rests on it.- Recommended.+ Implemented; native validation pending.## Validationdiff --git a/src/login_manager_test_service.zig b/src/login_manager_test_service.zignew file mode 100644index 0000000..43d4230--- /dev/null+++ b/src/login_manager_test_service.zig@@ -0,0 +1,38 @@+//! Noninstalled ConsoleKit2 client for private-bus integration tests.+const std = @import("std");+const Service = @import("session/login_manager.zig").Service(@import("session/login_manager/consolekit.zig"));+const Bus = @import("session/login_bus.zig").Client(Service);++pub fn main(init: std.process.Init) !void {+ var arena: std.heap.ArenaAllocator = .init(std.heap.c_allocator);+ defer arena.deinit();+ const allocator = arena.allocator();+ // Only the private test bus, never an implicit system connection.+ const address = init.minimal.environ.getPosix("DBUS_SESSION_BUS_ADDRESS") orelse return error.NoPrivateBus;+ var bus = try Bus.init(allocator, address, address);+ defer bus.deinit();+ const args = init.minimal.args.vector;+ if (args.len > 2 and std.mem.eql(u8, std.mem.span(args[1]), "--user-bus")) {+ var env = try init.minimal.environ.createMap(allocator);+ defer env.deinit();+ bus.user_address = "";+ const user_bus = @import("session/user_bus.zig");+ var daemon = (try user_bus.ensure(init.io, allocator, &bus, &env, std.mem.span(args[2]))).?;+ defer daemon.stop(init.io);+ if (try user_bus.ensure(init.io, allocator, &bus, &env, std.mem.span(args[2])) != null) return error.DuplicateDaemon;+ var lease = try @import("session/private_publication.zig").Publication(Bus).init(allocator, &bus, "", "");+ defer lease.deinit();+ try lease.publish(&.{.{ .key = "WAYLAND_DISPLAY", .value = "wayland-fixture" }});+ // Model the supervisor reaping a failed private bus before final cleanup.+ try daemon.handle.signal(.TERM);+ var fds = [_]std.c.pollfd{.{ .fd = daemon.handle.fd, .events = std.c.POLL.IN, .revents = 0 }};+ if (std.c.poll(&fds, 1, 5000) != 1) return error.DaemonDidNotExit;+ if (@import("platform").child.reap(daemon.child.id.?) == null) return error.DaemonNotReaped;+ try @import("platform").login_io.writeAll(1, "private user bus ready\n");+ return;+ }+ const device = if (args.len > 1) std.mem.span(args[1]) else "/dev/ttyv0";+ const id = try bus.login(allocator, .{ .display_device = device });+ const text = try std.fmt.allocPrint(allocator, "verified {s}\n", .{id});+ try @import("platform").login_io.writeAll(1, text);+}diff --git a/src/platform/AGENTS.md b/src/platform/AGENTS.mdindex 8922a1b..3aab6be 100644--- a/src/platform/AGENTS.md+++ b/src/platform/AGENTS.md@@ -16,6 +16,12 @@ FreeBSD: a part is one file with a `switch (builtin.os.tag)` per functionfails to compile there (`std.os.linux` would issue Linux syscall numbers onany target). FreeBSD notes are in `docs/plans/freebsd.md`.+* `login_io.zig` owns the supervisor's libc I/O; `login_process.zig` owns+ signal delivery, fork/exec and adopted-child reaping. `Signals` preserves+ the old mask for the child. FreeBSD kqueue notifications do not consume+ blocked POSIX signals: `next` consumes them with `sigtimedwait` before the+ old mask is restored. Keep the compositor's status for the main loop.+* **A `Handle` is not a pid.** Hold it for as long as you may signal; a bare`kill(pid)` is only safe while you have not reaped the child. `pid()` isnull once reaped, but an unreaped zombie keeps its pid: check `exited()` too.@@ -66,9 +72,9 @@ any target). FreeBSD notes are in `docs/plans/freebsd.md`.* Nothing here arms a timer or starts a thread; a caller retrying a failed`add` owns that clock.-Still direct Linux calls (later steps of the plan): the supervisor's and the-DM's event loops and process calls (`signalfd`, `epoll`, `poll`, `fork`,-`kill`, `wait4`; neither program is built on FreeBSD), `/proc` walks, the+Still direct Linux calls (later steps of the plan): the DM's event loop and+process calls (`signalfd`, `epoll`, `poll`, `fork`, `kill`, `wait4`; it is not+built on FreeBSD), theterminal's per-message `SCM_CREDENTIALS` check (`files/terminal/engine.c`, whichrefuses to start a terminal on other systems), the DRM driver ioctl in`Output.zig` and the two seccomp policy tables. Everything else outside thisdiff --git a/src/platform/login_io.zig b/src/platform/login_io.zignew file mode 100644index 0000000..e9865ba--- /dev/null+++ b/src/platform/login_io.zig@@ -0,0 +1,84 @@+//! Small libc-based I/O helpers for the login supervisor, on Linux and FreeBSD.+const std = @import("std");+const c = std.c;++pub const Error = error{ FileNotFound, PathAlreadyExists, AccessDenied, ProcessNotFound, WouldBlock, BrokenPipe, ConnectionReset, SymLinkLoop, Unexpected };++pub fn errnoError(err: std.posix.E) Error {+ return switch (err) {+ .NOENT => error.FileNotFound,+ .EXIST => error.PathAlreadyExists,+ .ACCES, .PERM => error.AccessDenied,+ .SRCH => error.ProcessNotFound,+ .AGAIN => error.WouldBlock,+ .PIPE => error.BrokenPipe,+ .CONNRESET => error.ConnectionReset,+ .LOOP => error.SymLinkLoop,+ else => error.Unexpected,+ };+}++pub fn check(rc: anytype) Error!usize {+ if (rc < 0) return errnoError(std.posix.errno(rc));+ return @intCast(rc);+}++pub fn retry(comptime f: anytype, args: anytype) Error!usize {+ while (true) {+ const rc = @call(.auto, f, args);+ if (rc >= 0) return @intCast(rc);+ const err = std.posix.errno(rc);+ if (err != .INTR) return errnoError(err);+ }+}++pub fn close(fd: i32) void {+ _ = c.close(fd);+}++pub fn writeAll(fd: i32, bytes: []const u8) !void {+ var rest = bytes;+ while (rest.len > 0) {+ const n = try retry(c.write, .{ fd, rest.ptr, rest.len });+ if (n == 0) return error.WriteFailed;+ rest = rest[n..];+ }+}++pub fn readAll(allocator: std.mem.Allocator, fd: i32) ![]u8 {+ var out: std.ArrayList(u8) = .empty;+ errdefer out.deinit(allocator);+ while (true) {+ try out.ensureUnusedCapacity(allocator, 4096);+ const spare = out.unusedCapacitySlice();+ const n = try retry(c.read, .{ fd, spare.ptr, spare.len });+ if (n == 0) return out.toOwnedSlice(allocator);+ out.items.len += n;+ }+}++pub fn monotonicMs() i64 {+ var ts: std.posix.timespec = undefined;+ _ = c.clock_gettime(.MONOTONIC, &ts);+ return @as(i64, ts.sec) * 1000 + @divTrunc(ts.nsec, 1_000_000);+}++pub fn openZ(path: [*:0]const u8, flags: std.posix.O, mode: std.posix.mode_t) !i32 {+ return @intCast(try retry(c.openat, .{ std.posix.AT.FDCWD, path, flags, @as(c_uint, mode) }));+}++pub fn unlinkZ(path: [*:0]const u8) !void {+ _ = try check(c.unlinkat(std.posix.AT.FDCWD, path, 0));+}++pub fn renameZ(from: [*:0]const u8, to: [*:0]const u8) !void {+ _ = try check(c.renameat(std.posix.AT.FDCWD, from, std.posix.AT.FDCWD, to));+}++pub fn random(bytes: []u8) !void {+ const libc = struct {+ extern "c" fn getentropy(?*anyopaque, usize) c_int;+ };+ std.debug.assert(bytes.len <= 256);+ _ = try check(libc.getentropy(bytes.ptr, bytes.len));+}diff --git a/src/platform/login_process.zig b/src/platform/login_process.zignew file mode 100644index 0000000..9b963ee--- /dev/null+++ b/src/platform/login_process.zig@@ -0,0 +1,137 @@+//! Signal delivery and child setup for the login supervisor. All waits are+//! event-driven; a FreeBSD kqueue replaces Linux's signalfd.+const std = @import("std");+const builtin = @import("builtin");+const c = std.c;+const io = @import("login_io.zig");+const linux = std.os.linux;++pub const Signals = struct {+ fd: i32,+ old_mask: std.posix.sigset_t,++ pub fn init() !Signals {+ var mask = std.posix.sigemptyset();+ for ([_]std.posix.SIG{ .TERM, .INT, .CHLD }) |sig| std.posix.sigaddset(&mask, sig);+ var old_mask = std.posix.sigemptyset();+ _ = try io.check(c.sigprocmask(std.posix.SIG.BLOCK, &mask, &old_mask));+ errdefer _ = c.sigprocmask(std.posix.SIG.SETMASK, &old_mask, null);+ const fd: i32 = switch (builtin.os.tag) {+ .linux => blk: {+ // libc reserves 1024 bits; the kernel consumes its first 64.+ const rc = linux.signalfd(-1, @ptrCast(&mask), linux.SFD.CLOEXEC | linux.SFD.NONBLOCK);+ if (linux.errno(rc) != .SUCCESS) return error.SignalWatchFailed;+ break :blk @intCast(rc);+ },+ .freebsd => blk: {+ const fd: i32 = @intCast(try io.check(c.kqueue()));+ errdefer io.close(fd);+ _ = try io.check(c.fcntl(fd, c.F.SETFD, @as(c_int, 1)));+ var changes: [3]c.Kevent = undefined;+ for ([_]std.posix.SIG{ .TERM, .INT, .CHLD }, &changes) |sig, *event| {+ event.* = .{ .ident = @backingInt(sig), .filter = c.EVFILT.SIGNAL, .flags = c.EV.ADD | c.EV.CLEAR, .fflags = 0, .data = 0, .udata = 0 };+ }+ var unused: [1]c.Kevent = undefined;+ _ = try io.check(c.kevent(fd, &changes, changes.len, &unused, 0, null));+ break :blk fd;+ },+ else => @compileError("login signal delivery is not ported to this OS"),+ };+ return .{ .fd = fd, .old_mask = old_mask };+ }++ pub fn deinit(self: *Signals) void {+ if (builtin.os.tag == .freebsd) while (self.next() != null) {};+ io.close(self.fd);+ _ = c.sigprocmask(std.posix.SIG.SETMASK, &self.old_mask, null);+ }++ pub fn next(self: *Signals) ?std.posix.SIG {+ switch (builtin.os.tag) {+ .linux => {+ var info: linux.signalfd_siginfo = undefined;+ if (c.read(self.fd, @ptrCast(&info), @sizeOf(@TypeOf(info))) != @sizeOf(@TypeOf(info))) return null;+ return @fromBackingInt(@intCast(info.signo));+ },+ .freebsd => {+ var events: [1]c.Kevent = undefined;+ const now: c.timespec = .{ .sec = 0, .nsec = 0 };+ if (c.kevent(self.fd, &events, 0, &events, 1, &now) <= 0) return null;+ const sig: std.posix.SIG = @fromBackingInt(@intCast(events[0].ident));+ // A kqueue notification does not consume a blocked POSIX+ // signal. Clear it before restoring the old mask at shutdown.+ const bsd = struct {+ extern "c" fn sigtimedwait(*const std.posix.sigset_t, ?*c.siginfo_t, *const c.timespec) c_int;+ };+ var mask = std.posix.sigemptyset();+ std.posix.sigaddset(&mask, sig);+ _ = bsd.sigtimedwait(&mask, null, &now);+ return sig;+ },+ else => unreachable,+ }+ }+};++/// Only async-signal-safe libc calls run between fork and exec.+pub fn spawn(compositor: [:0]const u8, envp: [*:null]const ?[*:0]const u8, session_fd: i32, log_fd: i32, old_mask: *const std.posix.sigset_t) !std.posix.pid_t {+ const pid: std.posix.pid_t = @intCast(try io.check(c.fork()));+ if (pid == 0) {+ _ = c.setsid();+ _ = c.dup2(log_fd, 1);+ _ = c.dup2(log_fd, 2);+ _ = c.fcntl(session_fd, c.F.SETFD, @as(c_int, 0));+ @import("process.zig").defaultSignal(.PIPE);+ _ = c.sigprocmask(std.posix.SIG.SETMASK, old_mask, null);+ const argv = [_:null]?[*:0]const u8{compositor.ptr};+ _ = c.execve(compositor.ptr, &argv, envp);+ c._exit(127);+ }+ return pid;+}++/// Peek before reaping: the main loop owns the compositor's exit status.+pub fn reapAdopted(compositor: std.posix.pid_t) void {+ while (true) {+ var info = std.mem.zeroes(c.siginfo_t);+ switch (builtin.os.tag) {+ .linux => {+ if (linux.errno(linux.waitid(.ALL, 0, &info, linux.W.EXITED | linux.W.NOHANG | linux.W.NOWAIT, null)) != .SUCCESS) return;+ const pid = info.fields.common.first.piduid.pid;+ if (pid == 0 or pid == compositor) return;+ if (linux.errno(linux.waitid(.PID, pid, &info, linux.W.EXITED | linux.W.NOHANG, null)) != .SUCCESS) return;+ },+ .freebsd => {+ const bsd = struct {+ extern "c" fn waitid(c_int, i64, *c.siginfo_t, c_int) c_int;+ };+ // sys/wait.h: P_ALL = 7, P_PID = 0; id_t is int64_t.+ if (bsd.waitid(7, 0, &info, c.W.EXITED | c.W.NOHANG | c.W.NOWAIT) != 0) return;+ if (info.pid == 0 or info.pid == compositor) return;+ if (bsd.waitid(0, info.pid, &info, c.W.EXITED | c.W.NOHANG) != 0) return;+ },+ else => unreachable,+ }+ }+}++/// Kernel-reported controlling terminal; the backend decides which seats it accepts.+pub fn consoleDevice(allocator: std.mem.Allocator) ![]const u8 {+ const libc = struct {+ extern "c" fn ttyname_r(c_int, [*]u8, usize) c_int;+ };+ var buf: [1024]u8 = undefined;+ if (libc.ttyname_r(0, &buf, buf.len) != 0) return error.NotConsoleLogin;+ return allocator.dupe(u8, std.mem.sliceTo(&buf, 0));+}++test "login signal queue consumes a blocked signal before restoring the mask" {+ var signals = try Signals.init();+ defer signals.deinit();+ // Target this thread so other threads in the test runner cannot receive it.+ try std.testing.expectEqual(@as(c_int, 0), c.raise(.TERM));+ var fds = [_]c.pollfd{.{ .fd = signals.fd, .events = c.POLL.IN, .revents = 0 }};+ try std.testing.expectEqual(@as(c_int, 1), c.poll(&fds, 1, 5000));+ try std.testing.expectEqual(std.posix.SIG.TERM, signals.next().?);+ try std.testing.expect(signals.next() == null);+}diff --git a/src/platform/mod.zig b/src/platform/mod.zigindex 0febc58..a541282 100644--- a/src/platform/mod.zig+++ b/src/platform/mod.zig@@ -6,6 +6,8 @@//! syscall filters.//! Callers never test the OS; `std.os.linux` is used only in here (see//! `AGENTS.md` beside this file). No compositor imports.+pub const login_io = @import("login_io.zig");+pub const login_process = @import("login_process.zig");pub const child = @import("child.zig");pub const dirwalk = @import("dirwalk.zig");pub const exe = @import("exe.zig");@@ -22,6 +24,7 @@ pub const system = @import("system.zig");pub const tool = @import("tool.zig");test {+ _ = login_process;_ = child;_ = dirwalk;_ = exe;diff --git a/src/session/AGENTS.md b/src/session/AGENTS.mdindex 1a856dc..0cca16f 100644--- a/src/session/AGENTS.md+++ b/src/session/AGENTS.md@@ -9,6 +9,16 @@ ext-session-lock) are in the root `AGENTS.md`.to that owner, ignore stale replies, and follow only this session's `Lock`.The recording transport tests live in `login_manager/tests.zig`; private-buscoverage is `tests/power.py`, `polkit.py` and `session_bus.py`.+ FreeBSD selects ConsoleKit2. Its session cookie and connection belong to+ the supervisor, survive compositor restarts and close on rejection/exit.+ Failed verification exports no login identity or inherited cookie. Its+ noninstalled private-bus fixture is `tests/consolekit.py` (`test-login-manager`).+* The supervisor's process and signal calls go through `platform.login_*`;+ descendant enumeration goes through `system_monitor/proc.zig`. Recheck+ FreeBSD start stamps after opening handles. `user_bus.zig` starts a missing+ user bus before the supervisor snapshots preexisting children, and stops it+ only after the session. `private_publication.zig` updates that bus without+ systemd's shared-manager lease.* Login appearance is a flattened snapshot in`/var/lib/rediwm-appearance/<uid>/`, provisioned by the DM and written bydiff --git a/src/session/lock_input.zig b/src/session/lock_input.zigindex fb32c5a..935c966 100644--- a/src/session/lock_input.zig+++ b/src/session/lock_input.zig@@ -214,7 +214,11 @@ pub fn activate(self: *Lock, focus: u8) void {// syscall or shell interpolation. Never request an interactive// auth agent behind the locked screen.var argv: [4][]const u8 = undefined;- var child = std.process.spawn(self.server.io, .{ .argv = power_cmd.commandArgv(&argv, if (reboot) .reboot else .poweroff, false, true) }) catch {+ const command = power_cmd.commandArgv(&argv, if (reboot) .reboot else .poweroff, false, true) orelse {+ self.status = i18n.tr("Power service unavailable");+ return;+ };+ var child = std.process.spawn(self.server.io, .{ .argv = command }) catch {self.status = i18n.tr("Power service unavailable");return;};diff --git a/src/session/login_bus.zig b/src/session/login_bus.zigindex eb86a2b..908b82e 100644--- a/src/session/login_bus.zig+++ b/src/session/login_bus.zig@@ -17,166 +17,181 @@ const login_manager = @import("login_manager.zig");const systemd1 = "org.freedesktop.systemd1";const properties = "org.freedesktop.DBus.Properties";-pub const Bus = struct {- allocator: std.mem.Allocator,- loop: *wl.EventLoop,- system_address: []const u8,- user_address: []const u8,- system: ?*Connection = null,- user: ?*Connection = null,-- pub fn init(allocator: std.mem.Allocator, system_address: []const u8, user_address: []const u8) !Bus {- return .{- .allocator = allocator,- .loop = try wl.EventLoop.create(),- .system_address = system_address,- .user_address = user_address,- };- }+pub const Bus = Client(login_manager);++pub fn Client(comptime Login: type) type {+ return struct {+ const Self = @This();+ login_cookie: ?[]u8 = null,+ login_owner: ?[]u8 = null,+ owns_user_bus: bool = false,+ allocator: std.mem.Allocator,+ loop: *wl.EventLoop,+ system_address: []const u8,+ user_address: []const u8,+ system: ?*Connection = null,+ user: ?*Connection = null,++ pub fn init(allocator: std.mem.Allocator, system_address: []const u8, user_address: []const u8) !Self {+ return .{+ .allocator = allocator,+ .loop = try wl.EventLoop.create(),+ .system_address = system_address,+ .user_address = user_address,+ };+ }- pub fn deinit(self: *Bus) void {- if (self.system) |conn| conn.destroy();- if (self.user) |conn| conn.destroy();- self.loop.destroy();- }+ pub fn deinit(self: *Self) void {+ Login.release(self);+ if (self.login_owner) |owner| self.allocator.free(owner);+ if (self.system) |conn| conn.destroy();+ if (self.user) |conn| conn.destroy();+ self.loop.destroy();+ }- const Scope = enum { system, user };+ const Scope = enum { system, user };++ fn connection(self: *Self, scope: Scope) !*Connection {+ const slot = switch (scope) {+ .system => &self.system,+ .user => &self.user,+ };+ if (slot.*) |conn| {+ if (!conn.closed) return conn;+ conn.destroy();+ slot.* = null;+ }+ const conn = try Connection.open(self.allocator, self.loop, switch (scope) {+ .system => self.system_address,+ .user => self.user_address,+ });+ errdefer conn.destroy();+ var reply: Reply = .{ .what = "Hello" };+ _ = try conn.hello(&reply, Reply.callback);+ try self.wait(&reply);+ reply.deinit(self.allocator);+ slot.* = conn;+ return conn;+ }- fn connection(self: *Bus, scope: Scope) !*Connection {- const slot = switch (scope) {- .system => &self.system,- .user => &self.user,- };- if (slot.*) |conn| {- if (!conn.closed) return conn;- conn.destroy();- slot.* = null;+ fn wait(self: *Self, reply: *Reply) !void {+ // The connection's own timer completes every call, so this never blocks forever.+ while (!reply.done) try self.loop.dispatch(-1);+ if (reply.failure) |err| {+ sys.diagnostic("D-Bus {s}: {t}", .{ reply.what, err });+ return err;+ }+ if (reply.error_name) |name| {+ sys.diagnostic("D-Bus {s}: {s}: {s}", .{ reply.what, name, reply.error_text orelse "" });+ return error.DBusError;+ }}- const conn = try Connection.open(self.allocator, self.loop, switch (scope) {- .system => self.system_address,- .user => self.user_address,- });- errdefer conn.destroy();- var reply: Reply = .{ .what = "Hello" };- _ = try conn.hello(&reply, Reply.callback);- try self.wait(&reply);- reply.deinit(self.allocator);- slot.* = conn;- return conn;- }- fn wait(self: *Bus, reply: *Reply) !void {- // The connection's own timer completes every call, so this never blocks forever.- while (!reply.done) try self.loop.dispatch(-1);- if (reply.failure) |err| {- sys.diagnostic("D-Bus {s}: {t}", .{ reply.what, err });- return err;+ /// Caller frees with `reply.deinit`.+ fn call(self: *Self, scope: Scope, destination: []const u8, path: []const u8, interface: []const u8, member: []const u8, signature: []const u8, body: *const wire.Writer) !Reply {+ const conn = try self.connection(scope);+ var reply: Reply = .{ .what = member };+ errdefer reply.deinit(self.allocator);+ reply.allocator = self.allocator;+ _ = try conn.call(destination, path, interface, member, signature, body, &reply, Reply.callback, timeout_ms);+ try self.wait(&reply);+ return reply;}- if (reply.error_name) |name| {- sys.diagnostic("D-Bus {s}: {s}: {s}", .{ reply.what, name, reply.error_text orelse "" });- return error.DBusError;++ fn getProperty(self: *Self, scope: Scope, destination: []const u8, path: []const u8, interface: []const u8, name: []const u8) !Reply {+ var body: wire.Writer = .{ .allocator = self.allocator };+ defer body.deinit();+ try body.string(interface);+ try body.string(name);+ var reply = try self.call(scope, destination, path, properties, "Get", "ss", &body);+ errdefer reply.deinit(self.allocator);+ try reply.expect("v");+ return reply;}- }- /// Caller frees with `reply.deinit`.- fn call(self: *Bus, scope: Scope, destination: []const u8, path: []const u8, interface: []const u8, member: []const u8, signature: []const u8, body: *const wire.Writer) !Reply {- const conn = try self.connection(scope);- var reply: Reply = .{ .what = member };- errdefer reply.deinit(self.allocator);- reply.allocator = self.allocator;- _ = try conn.call(destination, path, interface, member, signature, body, &reply, Reply.callback, timeout_ms);- try self.wait(&reply);- return reply;- }+ pub fn userReady(self: *Self) bool {+ _ = self.connection(.user) catch return false;+ return true;+ }- fn getProperty(self: *Bus, scope: Scope, destination: []const u8, path: []const u8, interface: []const u8, name: []const u8) !Reply {- var body: wire.Writer = .{ .allocator = self.allocator };- defer body.deinit();- try body.string(interface);- try body.string(name);- var reply = try self.call(scope, destination, path, properties, "Get", "ss", &body);- errdefer reply.deinit(self.allocator);- try reply.expect("v");- return reply;- }+ /// Only a verified local Wayland user login of this desktop may publish.+ pub fn login(self: *Self, arena: std.mem.Allocator, context: login_manager.Context) ![]const u8 {+ return Login.login(self, arena, context) catch |err| {+ if (err == error.NotLocalWaylandLogin) sys.diagnostic("not a local Wayland user login", .{});+ return err;+ };+ }- /// Only a verified local Wayland user login of this desktop may publish.- pub fn login(self: *Bus, arena: std.mem.Allocator) ![]const u8 {- return login_manager.login(self, arena) catch |err| {- if (err == error.NotLocalWaylandLogin) sys.diagnostic("not a local Wayland user login", .{});- return err;- };- }+ pub fn conflict(self: *Self, arena: std.mem.Allocator, session: []const u8) !?[]const u8 {+ return Login.conflict(self, arena, session);+ }- pub fn conflict(self: *Bus, arena: std.mem.Allocator, session: []const u8) !?[]const u8 {- return login_manager.conflict(self, arena, session);- }+ /// Blocking transport for the shared login-manager backend.+ pub fn loginCall(self: *Self, request: login_manager.Request) !Reply {+ const conn = try self.connection(.system);+ var reply: Reply = .{ .what = @tagName(request), .allocator = self.allocator };+ errdefer reply.deinit(self.allocator);+ _ = try Login.call(conn, request, if (request == .owner) null else self.login_owner, &reply, Reply.callback, timeout_ms);+ try self.wait(&reply);+ return reply;+ }- /// Blocking transport for the shared login-manager backend.- pub fn loginCall(self: *Bus, request: login_manager.Request) !Reply {- const conn = try self.connection(.system);- var reply: Reply = .{ .what = @tagName(request), .allocator = self.allocator };- errdefer reply.deinit(self.allocator);- _ = try login_manager.call(conn, request, null, &reply, Reply.callback, timeout_ms);- try self.wait(&reply);- return reply;- }+ /// The systemd user manager's environment.+ pub fn environment(self: *Self, arena: std.mem.Allocator) !Env {+ var reply = try self.getProperty(.user, systemd1, "/org/freedesktop/systemd1", systemd1 ++ ".Manager", "Environment");+ defer reply.deinit(self.allocator);+ var r = reply.reader();+ if (!std.mem.eql(u8, try r.variant(), "as")) return error.InvalidReply;+ var list = try r.array(4);+ var env: Env = .empty;+ while (list.offset < list.bytes.len) {+ const assignment = try list.string();+ const eq = std.mem.indexOfScalar(u8, assignment, '=') orelse continue;+ try env.put(arena, try arena.dupe(u8, assignment[0..eq]), try arena.dupe(u8, assignment[eq + 1 ..]));+ }+ return env;+ }- /// The systemd user manager's environment.- pub fn environment(self: *Bus, arena: std.mem.Allocator) !Env {- var reply = try self.getProperty(.user, systemd1, "/org/freedesktop/systemd1", systemd1 ++ ".Manager", "Environment");- defer reply.deinit(self.allocator);- var r = reply.reader();- if (!std.mem.eql(u8, try r.variant(), "as")) return error.InvalidReply;- var list = try r.array(4);- var env: Env = .empty;- while (list.offset < list.bytes.len) {- const assignment = try list.string();- const eq = std.mem.indexOfScalar(u8, assignment, '=') orelse continue;- try env.put(arena, try arena.dupe(u8, assignment[0..eq]), try arena.dupe(u8, assignment[eq + 1 ..]));+ pub fn systemd(self: *Self, values: []const Pair, absent: []const []const u8) !void {+ if (values.len > 0) {+ var body: wire.Writer = .{ .allocator = self.allocator };+ defer body.deinit();+ const list = try body.beginArray(4);+ for (values) |pair| {+ const assignment = try std.fmt.allocPrint(self.allocator, "{s}={s}", .{ pair.key, pair.value });+ defer self.allocator.free(assignment);+ try body.string(assignment);+ }+ try body.endArray(list);+ var reply = try self.call(.user, systemd1, "/org/freedesktop/systemd1", systemd1 ++ ".Manager", "SetEnvironment", "as", &body);+ reply.deinit(self.allocator);+ }+ if (absent.len > 0) {+ var body: wire.Writer = .{ .allocator = self.allocator };+ defer body.deinit();+ const list = try body.beginArray(4);+ for (absent) |key| try body.string(key);+ try body.endArray(list);+ var reply = try self.call(.user, systemd1, "/org/freedesktop/systemd1", systemd1 ++ ".Manager", "UnsetEnvironment", "as", &body);+ reply.deinit(self.allocator);+ }}- return env;- }- pub fn systemd(self: *Bus, values: []const Pair, absent: []const []const u8) !void {- if (values.len > 0) {+ pub fn activation(self: *Self, values: []const Pair) !void {var body: wire.Writer = .{ .allocator = self.allocator };defer body.deinit();- const list = try body.beginArray(4);+ const dict = try body.beginArray(8);for (values) |pair| {- const assignment = try std.fmt.allocPrint(self.allocator, "{s}={s}", .{ pair.key, pair.value });- defer self.allocator.free(assignment);- try body.string(assignment);+ try body.alignTo(8);+ try body.string(pair.key);+ try body.string(pair.value);}- try body.endArray(list);- var reply = try self.call(.user, systemd1, "/org/freedesktop/systemd1", systemd1 ++ ".Manager", "SetEnvironment", "as", &body);- reply.deinit(self.allocator);- }- if (absent.len > 0) {- var body: wire.Writer = .{ .allocator = self.allocator };- defer body.deinit();- const list = try body.beginArray(4);- for (absent) |key| try body.string(key);- try body.endArray(list);- var reply = try self.call(.user, systemd1, "/org/freedesktop/systemd1", systemd1 ++ ".Manager", "UnsetEnvironment", "as", &body);+ try body.endArray(dict);+ var reply = try self.call(.user, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "UpdateActivationEnvironment", "a{ss}", &body);reply.deinit(self.allocator);}- }-- pub fn activation(self: *Bus, values: []const Pair) !void {- var body: wire.Writer = .{ .allocator = self.allocator };- defer body.deinit();- const dict = try body.beginArray(8);- for (values) |pair| {- try body.alignTo(8);- try body.string(pair.key);- try body.string(pair.value);- }- try body.endArray(dict);- var reply = try self.call(.user, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "UpdateActivationEnvironment", "a{ss}", &body);- reply.deinit(self.allocator);- }-};+ };+}/// A completed call, copied out of the borrowed message.const Reply = struct {diff --git a/src/session/login_manager.zig b/src/session/login_manager.zigindex c8a4d14..74facf8 100644--- a/src/session/login_manager.zig+++ b/src/session/login_manager.zig@@ -1,9 +1,12 @@//! Login service boundary shared by the supervisor, power policy and polkit.//! The backend owns service names, method signatures and reply formats. The//! callers own connection lifetime, authorization policy and stale-reply guards.-//! Selection is static: ConsoleKit2 replaces logind here in the next port step.+//! Selection is static: logind on Linux, ConsoleKit2 on FreeBSD.const dbus = @import("dbus");-const backend = @import("login_manager/logind.zig");+const backend = switch (@import("builtin").os.tag) {+ .freebsd => @import("login_manager/consolekit.zig"),+ else => @import("login_manager/logind.zig"),+};const types = @import("login_manager/types.zig");pub const Action = types.Action;@@ -12,29 +15,53 @@ pub const Request = types.Request;pub const Event = types.Event;pub const ActionError = types.ActionError;pub const Api = types.Api;+pub const Context = types.Context;-/// `conn` can also be a recording transport in tests. There is no runtime-/// switch or test hook in the installed programs. An explicit destination pins-/// session and inhibitor requests to the owner whose generation the caller holds.-pub fn call(conn: anytype, request: Request, destination: ?[]const u8, owner: ?*anyopaque, callback: ?dbus.Connection.Callback, timeout_ms: u32) !u32 {- var body: dbus.wire.Writer = .{ .allocator = conn.allocator };- defer body.deinit();- const target = try backend.encode(request, &body);- return conn.callWithFlags(destination orelse target.destination, target.path, target.interface, target.member, target.signature, &body, owner, callback, timeout_ms, target.flags);+pub fn Service(comptime implementation: type) type {+ return struct {+ /// A recording transport can replace conn; no installed runtime hook.+ /// Explicit destinations pin requests to the owner's current generation.+ pub fn call(conn: anytype, request: Request, destination: ?[]const u8, owner: ?*anyopaque, callback: ?dbus.Connection.Callback, timeout_ms: u32) !u32 {+ var body: dbus.wire.Writer = .{ .allocator = conn.allocator };+ defer body.deinit();+ const target = try implementation.encode(request, &body);+ return conn.callWithFlags(destination orelse target.destination, target.path, target.interface, target.member, target.signature, &body, owner, callback, timeout_ms, target.flags);+ }+ pub fn commandArgv(buf: *[4][]const u8, kind: Action, ask_password: bool, no_block: bool) ?[]const []const u8 {+ return implementation.commandArgv(buf, kind, ask_password, no_block);+ }+ pub const login = implementation.login;+ pub const conflict = implementation.conflict;+ pub const release = implementation.release;+ pub const usesCommand = implementation.usesCommand;+ pub const signal = implementation.signal;+ pub const owner_match = implementation.owner_match;+ pub const changedOwner = implementation.changedOwner;+ pub const readSessionPath = implementation.readSessionPath;+ pub const readSessionId = implementation.readSessionId;+ pub const readApi = implementation.readApi;+ pub const actionError = implementation.actionError;+ pub const owns_session = implementation.owns_session;+ };}-pub const login = @import("login_manager/logind_login.zig").login;-pub const conflict = @import("login_manager/logind_login.zig").conflict;-pub const commandArgv = backend.commandArgv;-pub const usesCommand = backend.usesCommand;-pub const signal = backend.signal;-pub const owner_match = backend.owner_match;-pub const changedOwner = backend.changedOwner;-pub const readSessionPath = backend.readSessionPath;-pub const readSessionId = backend.readSessionId;-pub const readApi = backend.readApi;-pub const actionError = backend.actionError;+const Native = Service(backend);+pub const call = Native.call;+pub const commandArgv = Native.commandArgv;+pub const login = Native.login;+pub const conflict = Native.conflict;+pub const release = Native.release;+pub const usesCommand = Native.usesCommand;+pub const signal = Native.signal;+pub const owner_match = Native.owner_match;+pub const changedOwner = Native.changedOwner;+pub const readSessionPath = Native.readSessionPath;+pub const readSessionId = Native.readSessionId;+pub const readApi = Native.readApi;+pub const actionError = Native.actionError;+pub const owns_session = Native.owns_session;test {_ = @import("login_manager/tests.zig");+ _ = @import("login_manager/consolekit_tests.zig");}diff --git a/src/session/login_manager/consolekit.zig b/src/session/login_manager/consolekit.zignew file mode 100644index 0000000..0789f1b--- /dev/null+++ b/src/session/login_manager/consolekit.zig@@ -0,0 +1,179 @@+//! ConsoleKit2 2.x. Protocol checked against upstream's Manager/Session XML.+//! Session identities are object paths (also what polkit's unix-session uses).+const std = @import("std");+const dbus = @import("dbus");+const wire = dbus.wire;+const types = @import("types.zig");+const name = "org.freedesktop.ConsoleKit";+const path = "/org/freedesktop/ConsoleKit/Manager";+const manager = name ++ ".Manager";+const session = name ++ ".Session";+const bus = "org.freedesktop.DBus";+const bus_path = "/org/freedesktop/DBus";+pub const owns_session = true;+pub const login = @import("consolekit_login.zig").login;+pub const conflict = @import("consolekit_login.zig").conflict;+pub const release = @import("consolekit_login.zig").release;+pub const owner_match = "type='signal',sender='org.freedesktop.DBus',path='/org/freedesktop/DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.ConsoleKit'";++pub fn encode(request: types.Request, body: *wire.Writer) !types.Target {+ var target: types.Target = .{ .destination = name, .path = path, .interface = manager, .member = "" };+ switch (request) {+ .session_for_pid => |pid| {+ target.member = "GetSessionForUnixProcess";+ target.signature = "u";+ try body.uint32(pid);+ },+ .session => |id| {+ target.member = "GetSession";+ target.signature = "s";+ // GetId returns a path, but Manager.GetSession takes the short id.+ const prefix = "/org/freedesktop/ConsoleKit/";+ if (!std.mem.startsWith(u8, id, prefix) or id.len == prefix.len or std.mem.indexOfScalar(u8, id[prefix.len..], '/') != null) return error.InvalidSession;+ try body.string(id[prefix.len..]);+ },+ .session_field => |field| {+ target.path = field.path;+ target.interface = session;+ target.member = switch (field.field) {+ .id => "GetId",+ .uid => "GetUnixUser",+ .remote => "GetRemoteHostName",+ .local => "IsLocal",+ .kind => "GetSessionType",+ .class => "GetSessionClass",+ .state => "GetSessionState",+ .desktop => return error.Unsupported,+ };+ },+ .list_sessions => target.member = "GetSessions",+ .locked_hint => |hint| {+ target.path = hint.path;+ target.interface = session;+ target.member = "SetLockedHint";+ target.signature = "b";+ try body.boolean(hint.locked);+ },+ .capability => |kind| target.member = switch (kind) {+ .poweroff => "CanPowerOff",+ .reboot => "CanReboot",+ .@"suspend" => "CanSuspend",+ },+ .action => |action| {+ target.member = switch (action.kind) {+ .poweroff => "PowerOff",+ .reboot => "Reboot",+ .@"suspend" => "Suspend",+ };+ target.signature = "b";+ target.flags = if (action.interactive) wire.flag_allow_interactive_authorization else 0;+ try body.boolean(action.interactive);+ },+ .inhibit => |which| {+ target.member = "Inhibit";+ target.signature = "ssss";+ const args: [4][]const u8 = switch (which) {+ .lid => .{ "handle-lid-switch", "RediWM", "RediWM manages lid actions", "block" },+ .sleep => .{ "sleep", "RediWM", "Lock the screen before sleep", "delay" },+ };+ for (args) |arg| try body.string(arg);+ },+ .list_inhibitors => target.member = "ListInhibitors",+ .inspect => {+ target.interface = "org.freedesktop.DBus.Introspectable";+ target.member = "Introspect";+ },+ .owner => {+ target.destination = bus;+ target.path = bus_path;+ target.interface = bus;+ target.member = "GetNameOwner";+ target.signature = "s";+ try body.string(name);+ },+ .open_session => |context| {+ target.member = "OpenSessionWithParameters";+ target.signature = "a(sv)";+ const array = try body.beginArray(8);+ const parameters = [_][2][]const u8{+ .{ "session-type", "wayland" }, .{ "session-class", "user" },+ .{ "display-device", context.display_device }, .{ "remote-host-name", "" },+ };+ for (parameters) |parameter| {+ try body.alignTo(8);+ try body.string(parameter[0]);+ try body.variant("s");+ try body.string(parameter[1]);+ }+ try body.endArray(array);+ },+ .session_for_cookie, .close_session => |cookie| {+ target.member = if (request == .session_for_cookie) "GetSessionForCookie" else "CloseSession";+ target.signature = "s";+ try body.string(cookie);+ },+ }+ return target;+}++pub fn signal(event: types.Event, sender: ?[]const u8, owner: ?*anyopaque, callback: dbus.Connection.Signal) dbus.Connection.SignalHandler {+ return .{+ .sender = if (event == .owner_changed) bus else sender,+ .path = switch (event) {+ .lock => null,+ .owner_changed => bus_path,+ else => path,+ },+ .interface = switch (event) {+ .lock => session,+ .owner_changed => bus,+ else => manager,+ },+ .member = switch (event) {+ .sleep => "PrepareForSleep",+ .shutdown => "PrepareForShutdown",+ .lock => "Lock",+ .owner_changed => "NameOwnerChanged",+ },+ .owner = owner,+ .callback = callback,+ };+}++pub fn changedOwner(msg: wire.Message) !?[]const u8 {+ var body = msg.body;+ if (!std.mem.eql(u8, try body.string(), name)) return null;+ _ = try body.string();+ return try body.string();+}++pub fn readSessionPath(msg: wire.Message) ![]const u8 {+ if (msg.kind != .method_return) return error.Refused;+ if (!std.mem.eql(u8, msg.headers.signature, "o")) return error.InvalidReply;+ var body = msg.body;+ return body.objectPath();+}+pub const readSessionId = readSessionPath;++pub fn readApi(msg: wire.Message) types.Api {+ if (msg.kind != .method_return) return .{};+ var body = msg.body;+ const xml = body.string() catch return .{};+ return .{ .list_inhibitors = std.mem.indexOf(u8, xml, "ListInhibitors") != null };+}++pub fn actionError(error_name: []const u8) types.ActionError {+ const eq = std.mem.eql;+ if (eq(u8, error_name, bus ++ ".Error.UnknownMethod")) return .unknown_method;+ if (eq(u8, error_name, manager ++ ".Error.Inhibited")) return .inhibited;+ if (eq(u8, error_name, manager ++ ".Error.AuthorizationRequired") or eq(u8, error_name, bus ++ ".Error.InteractiveAuthorizationRequired")) return .authorization_required;+ if (eq(u8, error_name, manager ++ ".Error.InsufficientPermission") or eq(u8, error_name, bus ++ ".Error.AccessDenied")) return .denied;+ return .other;+}++pub fn usesCommand(_: types.Action) bool {+ return false;+}+pub fn commandArgv(_: *[4][]const u8, _: types.Action, _: bool, _: bool) ?[]const []const u8 {+ return null;+}diff --git a/src/session/login_manager/consolekit_login.zig b/src/session/login_manager/consolekit_login.zignew file mode 100644index 0000000..9118d92--- /dev/null+++ b/src/session/login_manager/consolekit_login.zig@@ -0,0 +1,89 @@+//! Own one ConsoleKit2 session for the supervisor's lifetime. Do not adopt a+//! session merely because environment variables claim it belongs to this login.+const std = @import("std");+const types = @import("types.zig");++fn string(bus: anytype, arena: std.mem.Allocator, path: []const u8, field: types.SessionField) ![]const u8 {+ var reply = try bus.loginCall(.{ .session_field = .{ .path = path, .field = field } });+ defer reply.deinit(bus.allocator);+ try reply.expect("s");+ var body = reply.reader();+ return arena.dupe(u8, try body.string());+}++fn user(bus: anytype, path: []const u8) !u32 {+ var reply = try bus.loginCall(.{ .session_field = .{ .path = path, .field = .uid } });+ defer reply.deinit(bus.allocator);+ try reply.expect("u");+ var body = reply.reader();+ return body.uint32();+}++pub fn login(bus: anytype, arena: std.mem.Allocator, context: types.Context) ![]const u8 {+ // This entry point is for a console login. A pty/SSH or nested compositor+ // must not create an apparently local login by asserting its own metadata.+ if (!std.mem.startsWith(u8, context.display_device, "/dev/ttyv")) return error.NotLocalWaylandLogin;+ if (bus.login_cookie != null) return error.SessionAlreadyOpen;+ var owner = try bus.loginCall(.owner);+ defer owner.deinit(bus.allocator);+ try owner.expect("s");+ var owner_body = owner.reader();+ bus.login_owner = try bus.allocator.dupe(u8, try owner_body.string());+ errdefer {+ bus.allocator.free(bus.login_owner.?);+ bus.login_owner = null;+ }++ var opened = try bus.loginCall(.{ .open_session = context });+ defer opened.deinit(bus.allocator);+ try opened.expect("s");+ var cookie_body = opened.reader();+ const cookie = try cookie_body.string();+ if (cookie.len == 0) return error.InvalidReply;+ bus.login_cookie = try bus.allocator.dupe(u8, cookie);+ errdefer release(bus);+ var located = try bus.loginCall(.{ .session_for_cookie = cookie });+ defer located.deinit(bus.allocator);+ try located.expect("o");+ var located_body = located.reader();+ const path = try arena.dupe(u8, try located_body.objectPath());++ var local_reply = try bus.loginCall(.{ .session_field = .{ .path = path, .field = .local } });+ defer local_reply.deinit(bus.allocator);+ try local_reply.expect("b");+ var local_body = local_reply.reader();+ if (!try local_body.boolean() or try user(bus, path) != std.posix.system.getuid() or+ !std.mem.eql(u8, try string(bus, arena, path, .kind), "wayland") or+ !std.mem.eql(u8, try string(bus, arena, path, .class), "user") or+ (try string(bus, arena, path, .remote)).len != 0) return error.NotLocalWaylandLogin;+ // Active is deliberately not required: CK2 sessions without a display+ // device cannot be active. There is no Desktop property to validate.+ return path;+}++pub fn release(bus: anytype) void {+ const cookie = bus.login_cookie orelse return;+ if (bus.loginCall(.{ .close_session = cookie })) |value| {+ var reply = value;+ reply.deinit(bus.allocator);+ } else |_| {}+ bus.allocator.free(cookie);+ bus.login_cookie = null;+}++pub fn conflict(bus: anytype, arena: std.mem.Allocator, ours: []const u8) !?[]const u8 {+ var reply = try bus.loginCall(.list_sessions);+ defer reply.deinit(bus.allocator);+ try reply.expect("ao");+ var body = reply.reader();+ var paths = try body.array(4);+ while (paths.offset < paths.bytes.len) {+ const path = try paths.objectPath();+ if (std.mem.eql(u8, path, ours) or try user(bus, path) != std.posix.system.getuid()) continue;+ const kind = try string(bus, arena, path, .kind);+ if (!std.mem.eql(u8, kind, "wayland") and !std.mem.eql(u8, kind, "x11")) continue;+ if (std.mem.eql(u8, try string(bus, arena, path, .state), "closing")) continue;+ return try arena.dupe(u8, path);+ }+ return null;+}diff --git a/src/session/login_manager/consolekit_tests.zig b/src/session/login_manager/consolekit_tests.zignew file mode 100644index 0000000..f8167ad--- /dev/null+++ b/src/session/login_manager/consolekit_tests.zig@@ -0,0 +1,44 @@+const std = @import("std");+const dbus = @import("dbus");+const login = @import("../login_manager.zig").Service(@import("consolekit.zig"));+const Recording = @import("tests.zig").Recording;+const t = std.testing;++test "ConsoleKit uses legacy interactive booleans for all power actions" {+ var fake: Recording = .{};+ defer fake.deinit();+ const actions = [_]@import("types.zig").Action{ .poweroff, .reboot, .@"suspend" };+ for (actions, [_][]const u8{ "PowerOff", "Reboot", "Suspend" }) |action, method| {+ _ = try login.call(&fake, .{ .action = .{ .kind = action, .interactive = false, .with_flags = true } }, null, null, null, 5000);+ try t.expectEqualStrings("org.freedesktop.ConsoleKit", fake.target.?.destination);+ try t.expectEqualStrings("/org/freedesktop/ConsoleKit/Manager", fake.target.?.path);+ try t.expectEqualStrings(method, fake.target.?.member);+ try t.expectEqualStrings("b", fake.target.?.signature);+ try t.expectEqual(@as(u8, 0), fake.target.?.flags);+ var body = fake.reader();+ try t.expect(!try body.boolean());+ try body.done();+ try t.expect(!login.usesCommand(action));+ }+ try t.expectEqual(.inhibited, login.actionError("org.freedesktop.ConsoleKit.Manager.Error.Inhibited"));+ try t.expectEqual(.authorization_required, login.actionError("org.freedesktop.ConsoleKit.Manager.Error.AuthorizationRequired"));+ try t.expectEqual(.denied, login.actionError("org.freedesktop.ConsoleKit.Manager.Error.InsufficientPermission"));+}++test "ConsoleKit identity stays an object path for polkit, manager receives short id" {+ var fake: Recording = .{};+ defer fake.deinit();+ const path = "/org/freedesktop/ConsoleKit/Session9";+ _ = try login.call(&fake, .{ .session = path }, ":1.19", null, null, 5000);+ try t.expectEqualStrings(":1.19", fake.target.?.destination);+ var body = fake.reader();+ try t.expectEqualStrings("Session9", try body.string());+ try t.expectError(error.InvalidSession, login.call(&fake, .{ .session = "/other/Session9" }, null, null, null, 5000));+ _ = try login.call(&fake, .{ .session_field = .{ .path = path, .field = .id } }, null, null, null, 5000);+ try t.expectEqualStrings("GetId", fake.target.?.member);+ var reply: dbus.wire.Writer = .{ .allocator = t.allocator };+ defer reply.deinit();+ try reply.objectPath(path);+ const msg: dbus.wire.Message = .{ .kind = .method_return, .serial = 1, .headers = .{ .signature = "o" }, .body = .{ .bytes = reply.bytes.items } };+ try t.expectEqualStrings(path, try login.readSessionId(msg));+}diff --git a/src/session/login_manager/logind.zig b/src/session/login_manager/logind.zigindex 374dd09..30039e3 100644--- a/src/session/login_manager/logind.zig+++ b/src/session/login_manager/logind.zig@@ -4,6 +4,10 @@ const dbus = @import("dbus");const wire = dbus.wire;const types = @import("types.zig");const Action = types.Action;+pub const owns_session = false;+pub const login = @import("logind_login.zig").login;+pub const conflict = @import("logind_login.zig").conflict;+pub fn release(_: anytype) void {}const name = "org.freedesktop.login1";const path = "/org/freedesktop/login1";const manager = name ++ ".Manager";@@ -16,6 +20,7 @@ pub const owner_match = "type='signal',sender='org.freedesktop.DBus',path='/org/pub fn encode(request: types.Request, body: *wire.Writer) !types.Target {var target: types.Target = .{ .destination = name, .path = path, .interface = manager, .member = "" };switch (request) {+ .open_session, .close_session, .session_for_cookie => return error.Unsupported,.session_for_pid => |pid| {target.member = "GetSessionByPID";target.signature = "u";@@ -33,6 +38,7 @@ pub fn encode(request: types.Request, body: *wire.Writer) !types.Target {target.signature = "ss";try body.string(session);try body.string(switch (field.field) {+ .local => return error.Unsupported,.id => "Id",.uid => "User",.remote => "Remote",diff --git a/src/session/login_manager/logind_login.zig b/src/session/login_manager/logind_login.zigindex 8303581..4ccbbca 100644--- a/src/session/login_manager/logind_login.zig+++ b/src/session/login_manager/logind_login.zig@@ -13,7 +13,7 @@ fn sessionString(self: anytype, arena: std.mem.Allocator, path: []const u8, fiel/// Only a verified local Wayland user login of this desktop may publish./// Returns the logind session id.-pub fn login(self: anytype, arena: std.mem.Allocator) ![]const u8 {+pub fn login(self: anytype, arena: std.mem.Allocator, _: types.Context) ![]const u8 {var reply = try self.loginCall(.{ .session_for_pid = @intCast(std.posix.system.getpid()) });defer reply.deinit(self.allocator);try reply.expect("o");diff --git a/src/session/login_manager/tests.zig b/src/session/login_manager/tests.zigindex 89d2c10..6362a78 100644--- a/src/session/login_manager/tests.zig+++ b/src/session/login_manager/tests.zig@@ -1,13 +1,13 @@const std = @import("std");const dbus = @import("dbus");-const login = @import("../login_manager.zig");+const login = @import("../login_manager.zig").Service(@import("logind.zig"));const types = @import("types.zig");const wire = dbus.wire;const testing = std.testing;/// Records the actual transport boundary, including borrowed body bytes. No/// real bus or power command can be reached by these checks.-const Recording = struct {+pub const Recording = struct {allocator: std.mem.Allocator = testing.allocator,target: ?types.Target = null,body: std.ArrayList(u8) = .empty,@@ -23,11 +23,11 @@ const Recording = struct {return self.calls;}- fn reader(self: *const Recording) wire.Reader {+ pub fn reader(self: *const Recording) wire.Reader {return .{ .bytes = self.body.items };}- fn deinit(self: *Recording) void {+ pub fn deinit(self: *Recording) void {self.body.deinit(self.allocator);}};diff --git a/src/session/login_manager/types.zig b/src/session/login_manager/types.zigindex 84075f3..3322edb 100644--- a/src/session/login_manager/types.zig+++ b/src/session/login_manager/types.zig@@ -4,8 +4,13 @@ pub const Event = enum { sleep, shutdown, lock, owner_changed };pub const ActionError = enum { unknown_method, inhibited, authorization_required, denied, other };pub const Api = struct { with_flags: bool = false, list_inhibitors: bool = false };-pub const SessionField = enum { id, uid, remote, desktop, kind, class, state };+pub const SessionField = enum { id, uid, remote, local, desktop, kind, class, state };+pub const Context = struct { display_device: []const u8 = "" };+pub const Request = union(enum) {+ open_session: Context,+ close_session: []const u8,+ session_for_cookie: []const u8,session_for_pid: u32,session: []const u8,session_field: struct { path: []const u8, field: SessionField },diff --git a/src/session/login_sys.zig b/src/session/login_sys.zigindex c7e361c..9c957a5 100644--- a/src/session/login_sys.zig+++ b/src/session/login_sys.zig@@ -1,7 +1,6 @@-//! Raw Linux helpers shared by the login supervisor. These are raw syscalls:-//! errors come from `linux.errno(rc)`, never libc errno.+//! Supervisor diagnostics and portable login I/O.const std = @import("std");-const linux = std.os.linux;+const io = @import("platform").login_io;/// Where supervisor diagnostics go: the journal (stderr) until session.log opens.pub var diag_fd: i32 = 2;@@ -16,81 +15,14 @@ pub fn diagnostic(comptime fmt: []const u8, args: anytype) void {writeAll(diag_fd, text) catch {};}-pub fn check(rc: usize) SysError!usize {- return switch (linux.errno(rc)) {- .SUCCESS => rc,- else => |err| errnoError(err),- };-}--/// Retries EINTR; every other failure is mapped through `errnoError`.-pub fn retry(comptime f: anytype, args: anytype) SysError!usize {- while (true) {- const rc = @call(.auto, f, args);- switch (linux.errno(rc)) {- .SUCCESS => return rc,- .INTR => continue,- else => |err| return errnoError(err),- }- }-}--pub fn close(fd: i32) void {- _ = linux.close(fd);-}--pub fn writeAll(fd: i32, bytes: []const u8) !void {- var rest = bytes;- while (rest.len > 0) {- const n = try retry(linux.write, .{ fd, rest.ptr, rest.len });- if (n == 0) return error.WriteFailed;- rest = rest[n..];- }-}--pub fn readAll(allocator: std.mem.Allocator, fd: i32) ![]u8 {- var out: std.ArrayList(u8) = .empty;- errdefer out.deinit(allocator);- while (true) {- try out.ensureUnusedCapacity(allocator, 4096);- const spare = out.unusedCapacitySlice();- const n = try retry(linux.read, .{ fd, spare.ptr, spare.len });- if (n == 0) return out.toOwnedSlice(allocator);- out.items.len += n;- }-}--pub fn monotonicMs() i64 {- var ts: linux.timespec = undefined;- _ = linux.clock_gettime(.MONOTONIC, &ts);- return @as(i64, ts.sec) * 1000 + @divTrunc(ts.nsec, 1_000_000);-}--pub const SysError = error{ FileNotFound, PathAlreadyExists, AccessDenied, ProcessNotFound, WouldBlock, BrokenPipe, ConnectionReset, SymLinkLoop, Unexpected };--pub fn errnoError(err: linux.E) SysError {- return switch (err) {- .NOENT => error.FileNotFound,- .EXIST => error.PathAlreadyExists,- .ACCES, .PERM => error.AccessDenied,- .SRCH => error.ProcessNotFound,- .AGAIN => error.WouldBlock,- .PIPE => error.BrokenPipe,- .CONNRESET => error.ConnectionReset,- .LOOP => error.SymLinkLoop,- else => error.Unexpected,- };-}--pub fn openZ(path: [*:0]const u8, flags: linux.O, mode: linux.mode_t) !i32 {- const rc = try retry(linux.openat, .{ linux.AT.FDCWD, path, flags, mode });- return @intCast(rc);-}--pub fn unlinkZ(path: [*:0]const u8) !void {- _ = try check(linux.unlinkat(linux.AT.FDCWD, path, 0));-}--pub fn renameZ(from: [*:0]const u8, to: [*:0]const u8) !void {- _ = try check(linux.renameat(linux.AT.FDCWD, from, linux.AT.FDCWD, to));-}+pub const check = io.check;+pub const retry = io.retry;+pub const close = io.close;+pub const writeAll = io.writeAll;+pub const readAll = io.readAll;+pub const monotonicMs = io.monotonicMs;+pub const errnoError = io.errnoError;+pub const openZ = io.openZ;+pub const unlinkZ = io.unlinkZ;+pub const renameZ = io.renameZ;+pub const random = io.random;diff --git a/src/session/power.zig b/src/session/power.zigindex 7291435..93a3e54 100644--- a/src/session/power.zig+++ b/src/session/power.zig@@ -1,5 +1,6 @@//! Poweroff/reboot through systemctl (like DMS), or loginctl where systemd is//! not init (elogind, e.g. Artix); suspend through logind.+//! FreeBSD's ConsoleKit2 backend sends all three actions over the system bus.//! Capability probes and preparation signals still use the system bus.//! Requests run as the logged-in user, with normal authorization and inhibitor//! checks. Automatic power commands use --no-ask-password. Suspend uses@@ -89,7 +90,7 @@ pub const Request = struct {/// systemd as init (sd_booted's `/run/systemd/system` test); elogind systems/// have these verbs in loginctl, which only asks logind and never waits for/// the job, so it has no --no-block.-pub fn commandArgv(buf: *[4][]const u8, kind: Kind, ask_password: bool, no_block: bool) []const []const u8 {+pub fn commandArgv(buf: *[4][]const u8, kind: Kind, ask_password: bool, no_block: bool) ?[]const []const u8 {return login.commandArgv(buf, kind.loginAction(), ask_password, no_block);}diff --git a/src/session/power_requests.zig b/src/session/power_requests.zigindex 5c9a309..5be644e 100644--- a/src/session/power_requests.zig+++ b/src/session/power_requests.zig@@ -68,7 +68,7 @@ pub fn beginRequest(self: *Manager, req: Request) void {pub fn startCommand(self: *Manager, req: Request) void {var buf: [4][]const u8 = undefined;- const argv = commandArgv(&buf, req.kind, req.interactive, false);+ const argv = commandArgv(&buf, req.kind, req.interactive, false) orelse unreachable;var child = std.process.spawn(self.server.io, .{.argv = argv,.stdin = .ignore,diff --git a/src/session/private_publication.zig b/src/session/private_publication.zignew file mode 100644index 0000000..d4bee68--- /dev/null+++ b/src/session/private_publication.zig@@ -0,0 +1,60 @@+//! Activation environment for a session bus without a systemd user manager.+//! There is no shared-manager journal: the bus belongs to this console session.+const std = @import("std");+const publication = @import("publication.zig");++pub fn Publication(comptime Bus: type) type {+ return struct {+ bus: *Bus,+ allocator: std.mem.Allocator,+ session: []const u8,+ published: bool = false,+ const Self = @This();+ pub fn init(allocator: std.mem.Allocator, bus: *Bus, _: []const u8, session: []const u8) !Self {+ return .{ .bus = bus, .allocator = allocator, .session = session };+ }+ pub fn acquire(self: *Self) !void {+ if (self.bus.owns_user_bus) return;+ var arena: std.heap.ArenaAllocator = .init(self.allocator);+ defer arena.deinit();+ if (try self.bus.conflict(arena.allocator(), self.session) != null) return error.GraphicalSessionConflict;+ }+ pub fn deinit(self: *Self) void {+ self.restore() catch {};+ }+ pub fn publish(self: *Self, values: []const publication.Pair) !void {+ for (values) |pair| {+ if (std.mem.eql(u8, pair.key, publication.owner_key)) return error.InvalidActivationEnvironment;+ var allowed = false;+ for (publication.allowlist) |key| if (std.mem.eql(u8, key, pair.key)) {+ allowed = true;+ break;+ };+ if (!allowed) return error.InvalidActivationEnvironment;+ }+ try self.acquire();+ self.published = true;+ try self.bus.activation(values);+ }+ pub fn restore(self: *Self) !void {+ if (!self.published) return;+ // A borrowed bus may now belong to another desktop. It has no+ // readable activation environment with which to verify ownership.+ if (!self.bus.owns_user_bus) {+ self.published = false;+ return;+ }+ // Do not activate an app onto a dead display between compositor runs.+ try self.bus.activation(&.{+ .{ .key = "WAYLAND_DISPLAY", .value = "" },+ .{ .key = "DISPLAY", .value = "" },+ .{ .key = "REDIWM_SOCKET", .value = "" },+ });+ self.published = false;+ }+ };+}++test {+ _ = @import("private_publication_tests.zig");+}diff --git a/src/session/private_publication_tests.zig b/src/session/private_publication_tests.zignew file mode 100644index 0000000..adce666--- /dev/null+++ b/src/session/private_publication_tests.zig@@ -0,0 +1,51 @@+const std = @import("std");+const publication = @import("publication.zig");+const Private = @import("private_publication.zig").Publication;+const t = std.testing;++const Bus = struct {+ owns_user_bus: bool = false,+ other_login: bool = false,+ writes: usize = 0,+ display: []const u8 = "other-display",+ pub fn conflict(self: *Bus, _: std.mem.Allocator, _: []const u8) !?[]const u8 {+ return if (self.other_login) "another-session" else null;+ }+ pub fn activation(self: *Bus, values: []const publication.Pair) !void {+ self.writes += 1;+ for (values) |pair| if (std.mem.eql(u8, pair.key, "WAYLAND_DISPLAY")) {+ self.display = pair.value;+ };+ }+};++test "borrowed bus publication refuses another graphical login and never clears its environment" {+ var bus: Bus = .{ .other_login = true };+ var lease = try Private(Bus).init(t.allocator, &bus, "", "ours");+ defer lease.deinit();+ try t.expectError(error.GraphicalSessionConflict, lease.acquire());+ try t.expectError(error.GraphicalSessionConflict, lease.publish(&.{.{ .key = "WAYLAND_DISPLAY", .value = "ours" }}));+ try lease.restore();+ try t.expectEqual(@as(usize, 0), bus.writes);+ try t.expectEqualStrings("other-display", bus.display);+ bus.other_login = false;+ try lease.publish(&.{.{ .key = "WAYLAND_DISPLAY", .value = "ours" }});+ bus.display = "new-desktop";+ try lease.restore();+ try t.expectEqualStrings("new-desktop", bus.display);+ try t.expectEqual(@as(usize, 1), bus.writes);+}++test "owned bus clears its dead display once and rejects non-activation state" {+ var bus: Bus = .{ .owns_user_bus = true, .other_login = true };+ var lease = try Private(Bus).init(t.allocator, &bus, "", "ours");+ defer lease.deinit();+ try lease.acquire();+ try t.expectError(error.InvalidActivationEnvironment, lease.publish(&.{.{ .key = "XDG_SESSION_COOKIE", .value = "secret" }}));+ try t.expectEqual(@as(usize, 0), bus.writes);+ try lease.publish(&.{.{ .key = "WAYLAND_DISPLAY", .value = "ours" }});+ try lease.restore();+ try lease.restore();+ try t.expectEqualStrings("", bus.display);+ try t.expectEqual(@as(usize, 2), bus.writes);+}diff --git a/src/session/publication.zig b/src/session/publication.zigindex f3afdeb..3a0de53 100644--- a/src/session/publication.zig+++ b/src/session/publication.zig@@ -3,7 +3,7 @@//! lets a successor roll back after a supervisor failure. Restoration only//! touches values this lease still owns.const std = @import("std");-const linux = std.os.linux;+const c = std.c;const sys = @import("login_sys.zig");pub const owner_key = "REDIWM_ACTIVATION_OWNER";@@ -63,7 +63,7 @@ pub fn Publication(comptime Bus: type) type {pub fn acquire(self: *Self) !void {const fd = try sys.openZ(self.lock_path, .{ .ACCMODE = .RDWR, .CREAT = true, .NOFOLLOW = true, .CLOEXEC = true }, 0o600);- _ = sys.retry(linux.flock, .{ fd, std.posix.LOCK.EX | std.posix.LOCK.NB }) catch {+ _ = sys.retry(c.flock, .{ fd, std.posix.LOCK.EX | std.posix.LOCK.NB }) catch {sys.close(fd);sys.diagnostic("another RediWM session owns activation publication", .{});return error.PublicationLocked;@@ -192,7 +192,7 @@ fn pairs(arena: std.mem.Allocator, map: std.StringArrayHashMapUnmanaged([]constfn ownerToken(arena: std.mem.Allocator) ![]const u8 {var bytes: [16]u8 = undefined;- _ = try sys.check(linux.getrandom(&bytes, bytes.len, 0));+ try sys.random(&bytes);return std.fmt.allocPrint(arena, "{x}", .{&bytes});}diff --git a/src/session/supervisor.zig b/src/session/supervisor.zigindex a5b83ac..198cea5 100644--- a/src/session/supervisor.zig+++ b/src/session/supervisor.zig@@ -3,21 +3,23 @@//! behind. The supervisor is a child subreaper, so double-forked helpers stay//! in its tree even after compositor failure.const std = @import("std");-const linux = std.os.linux;+const c = std.c;+const proc = @import("../system_monitor/proc.zig");+const login_process = @import("platform").login_process;const sys = @import("login_sys.zig");const publication = @import("publication.zig");const platform = @import("platform");-const Pid = linux.pid_t;+const Pid = std.posix.pid_t;const Handle = platform.child.Handle;-const PidSet = std.AutoArrayHashMapUnmanaged(Pid, void);+const PidSet = proc.Tree;const max_crashes = 5;const crash_window_ms = 60_000;const readiness_timeout_ms = 30_000;/// Abort-like deaths restart; anything else ends the session.-const crash_signals = [_]linux.SIG{ .ILL, .ABRT, .BUS, .FPE, .SEGV };+const crash_signals = [_]std.posix.SIG{ .ILL, .ABRT, .BUS, .FPE, .SEGV };/// Queued ahead of everything else for a compositor whose predecessor crashed/// while locked; `session/activation.zig` takes it before readiness.@@ -43,22 +45,14 @@ pub fn Options(comptime Publication: type) type {pub fn supervise(comptime Publication: type, options: Options(Publication)) !u8 {const allocator = options.allocator;const previous_subreaper = try platform.process.childSubreaper();- try platform.process.setChildSubreaper(true);- defer platform.process.setChildSubreaper(previous_subreaper) catch {};+ if (!previous_subreaper) try platform.process.setChildSubreaper(true);+ defer if (!previous_subreaper) platform.process.setChildSubreaper(false) catch {};- var preexisting = try descendants(allocator, linux.getpid());+ var preexisting = try descendants(allocator, c.getpid());defer preexisting.deinit(allocator);- // Logout signals and child exits arrive through a signalfd; the child gets the old mask back.- var mask = linux.sigemptyset();- linux.sigaddset(&mask, .TERM);- linux.sigaddset(&mask, .INT);- linux.sigaddset(&mask, .CHLD);- var old_mask: linux.sigset_t = undefined;- _ = try sys.check(linux.sigprocmask(linux.SIG.BLOCK, &mask, &old_mask));- defer _ = linux.sigprocmask(linux.SIG.SETMASK, &old_mask, null);- const signal_fd: i32 = @intCast(try sys.check(linux.signalfd(-1, &mask, linux.SFD.CLOEXEC | linux.SFD.NONBLOCK)));- defer sys.close(signal_fd);+ var signals = try login_process.Signals.init();+ defer signals.deinit();var attempts: std.ArrayList(i64) = .empty;defer attempts.deinit(allocator);@@ -84,17 +78,17 @@ pub fn supervise(comptime Publication: type, options: Options(Publication)) !u8try attempts.append(allocator, now);var pair: [2]i32 = undefined;- _ = try sys.check(linux.socketpair(linux.AF.UNIX, linux.SOCK.SEQPACKET | linux.SOCK.CLOEXEC, 0, &pair));+ _ = try sys.check(c.socketpair(std.posix.AF.UNIX, std.posix.SOCK.SEQPACKET | std.posix.SOCK.CLOEXEC, 0, &pair));const parent = pair[0];var parent_open = true;defer if (parent_open) sys.close(parent);const child = pair[1];- if (locked) _ = sys.retry(linux.sendto, .{ parent, lock_request, lock_request.len, linux.MSG.NOSIGNAL, null, 0 }) catch |err| {+ if (locked) _ = sys.retry(c.sendto, .{ parent, lock_request, lock_request.len, std.posix.MSG.NOSIGNAL, null, 0 }) catch |err| {sys.close(child);sys.diagnostic("cannot restart the compositor locked ({t}); ending the session", .{err});return 1;};- const pid = spawn(allocator, options.compositor, options.env, child, options.log_fd, &old_mask) catch |err| {+ const pid = spawn(allocator, options.compositor, options.env, child, options.log_fd, &signals.old_mask) catch |err| {sys.close(child);return err;};@@ -110,34 +104,34 @@ pub fn supervise(comptime Publication: type, options: Options(Publication)) !u8process.close();if (options.publication) |p| p.restore() catch |err| sys.diagnostic("activation cleanup pending: {t}", .{err});}- stopping = try waitForExit(allocator, pid, parent, process, signal_fd, options.publication, &locked);+ stopping = try waitForExit(allocator, pid, parent, process, &signals, options.publication, &locked);}if (stopping) return 0;const raw = status orelse return 1;- if (linux.W.IFSIGNALED(raw)) {- const sig = linux.W.TERMSIG(raw);- if (std.mem.indexOfScalar(linux.SIG, &crash_signals, sig) != null) continue;- return @truncate(128 + @intFromEnum(sig));+ if (std.posix.W.IFSIGNALED(raw)) {+ const sig = std.posix.W.TERMSIG(raw);+ if (std.mem.indexOfScalar(std.posix.SIG, &crash_signals, sig) != null) continue;+ return @truncate(128 + @backingInt(sig));}- return linux.W.EXITSTATUS(raw);+ return std.posix.W.EXITSTATUS(raw);}return 0;}/// Serves readiness handshakes and records lock reports until the compositor/// exits (false) or the supervisor is asked to stop (true).-fn waitForExit(allocator: std.mem.Allocator, compositor: Pid, parent: i32, process: Handle, signal_fd: i32, maybe_publication: anytype, locked: *bool) !bool {+fn waitForExit(allocator: std.mem.Allocator, compositor: Pid, parent: i32, process: Handle, signals: *login_process.Signals, maybe_publication: anytype, locked: *bool) !bool {var deadline: ?i64 = sys.monotonicMs() + readiness_timeout_ms;var parent_open = true;var packet: [16384]u8 = undefined;while (true) {- var fds = [_]linux.pollfd{- .{ .fd = process.fd, .events = linux.POLL.IN, .revents = 0 },- .{ .fd = signal_fd, .events = linux.POLL.IN, .revents = 0 },- .{ .fd = if (parent_open) parent else -1, .events = linux.POLL.IN, .revents = 0 },+ var fds = [_]std.posix.pollfd{+ .{ .fd = process.fd, .events = std.posix.POLL.IN, .revents = 0 },+ .{ .fd = signals.fd, .events = std.posix.POLL.IN, .revents = 0 },+ .{ .fd = if (parent_open) parent else -1, .events = std.posix.POLL.IN, .revents = 0 },};const timeout: i32 = if (deadline) |d| @intCast(@max(0, d - sys.monotonicMs())) else -1;- const ready = try sys.retry(linux.poll, .{ &fds, fds.len, timeout });+ const ready = try sys.retry(c.poll, .{ &fds, fds.len, timeout });if (ready == 0) {sys.diagnostic("compositor readiness timed out", .{});return false;@@ -147,17 +141,15 @@ fn waitForExit(allocator: std.mem.Allocator, compositor: Pid, parent: i32, procereturn false;}if (fds[1].revents != 0) {- var info: linux.signalfd_siginfo = undefined;- const got = linux.read(signal_fd, @ptrCast(&info), @sizeOf(linux.signalfd_siginfo));- if (linux.errno(got) != .SUCCESS or got != @sizeOf(linux.signalfd_siginfo)) continue;- if (info.signo == @intFromEnum(linux.SIG.CHLD)) {+ const sig = signals.next() orelse continue;+ if (sig == .CHLD) {reapAdopted(compositor);continue;}return true;}if (fds[2].revents == 0) continue;- const n = sys.retry(linux.recvfrom, .{ parent, &packet, packet.len, 0, null, null }) catch |err| switch (err) {+ const n = sys.retry(c.recvfrom, .{ parent, &packet, packet.len, 0, null, null }) catch |err| switch (err) {error.ConnectionReset => return false,else => return err,};@@ -170,7 +162,7 @@ fn waitForExit(allocator: std.mem.Allocator, compositor: Pid, parent: i32, procecontinue;}if (maybe_publication) |p| publish(allocator, p, packet[0..n]);- _ = sys.retry(linux.sendto, .{ parent, "ready", 5, linux.MSG.NOSIGNAL, null, 0 }) catch |err| switch (err) {+ _ = sys.retry(c.sendto, .{ parent, "ready", 5, std.posix.MSG.NOSIGNAL, null, 0 }) catch |err| switch (err) {error.BrokenPipe, error.ConnectionReset => return false,else => return err,};@@ -184,24 +176,14 @@ fn waitForExit(allocator: std.mem.Allocator, compositor: Pid, parent: i32, proce/// left hundreds. Peek first (`NOWAIT`): the compositor's own status is/// collected by `stopGroup` and must not be consumed here. A zombie compositor/// can hide others behind it, but then the loop is already ending.-fn reapAdopted(compositor: Pid) void {- while (true) {- var info = std.mem.zeroes(linux.siginfo_t);- const peeked = linux.waitid(.ALL, 0, &info, linux.W.EXITED | linux.W.NOHANG | linux.W.NOWAIT, null);- if (linux.errno(peeked) != .SUCCESS) return;- const pid = info.fields.common.first.piduid.pid;- if (pid == 0 or pid == compositor) return;- var reaped = std.mem.zeroes(linux.siginfo_t);- if (linux.errno(linux.waitid(.PID, pid, &reaped, linux.W.EXITED | linux.W.NOHANG, null)) != .SUCCESS) return;- }-}+const reapAdopted = login_process.reapAdopted;/// A compositor that locked and then crashed may die before its report is/// read; what it left queued still decides how the next one starts.fn drainLockReports(parent: i32, locked: *bool) void {var packet: [16]u8 = undefined;while (true) {- const n = sys.retry(linux.recvfrom, .{ parent, &packet, packet.len, linux.MSG.DONTWAIT, null, null }) catch return;+ const n = sys.retry(c.recvfrom, .{ parent, &packet, packet.len, std.posix.MSG.DONTWAIT, null, null }) catch return;if (n == 0) return;if (lockReport(packet[0..n])) |state| locked.* = state;}@@ -228,69 +210,15 @@ fn parseReadiness(arena: std.mem.Allocator, packet: []const u8) ![]publication.Preturn out;}-fn spawn(allocator: std.mem.Allocator, compositor: [:0]const u8, env: *std.process.Environ.Map, session_fd: i32, log_fd: i32, old_mask: *const linux.sigset_t) !Pid {+fn spawn(allocator: std.mem.Allocator, compositor: [:0]const u8, env: *std.process.Environ.Map, session_fd: i32, log_fd: i32, old_mask: *const std.posix.sigset_t) !Pid {var fd_text: [16]u8 = undefined;try env.put("REDIWM_SESSION_FD", try std.fmt.bufPrint(&fd_text, "{d}", .{session_fd}));const envp = try env.createPosixBlock(allocator, .{});defer envp.deinit(allocator);- const argv = [_:null]?[*:0]const u8{compositor.ptr};-- const rc = try sys.check(linux.fork());- if (rc == 0) {- // Only raw syscalls between fork and exec.- _ = linux.setsid();- _ = linux.dup2(log_fd, 1);- _ = linux.dup2(log_fd, 2);- // The readiness fd is the only descriptor the compositor inherits.- _ = linux.fcntl(session_fd, linux.F.SETFD, 0);- const default: linux.Sigaction = .{ .handler = .{ .handler = linux.SIG.DFL }, .mask = linux.sigemptyset(), .flags = 0 };- _ = linux.sigaction(.PIPE, &default, null);- _ = linux.sigprocmask(linux.SIG.SETMASK, old_mask, null);- _ = linux.execve(compositor.ptr, &argv, envp.slice.ptr);- linux.exit_group(127);- }- return @intCast(rc);+ return login_process.spawn(compositor, envp.slice.ptr, session_fd, log_fd, old_mask);}-/// The owned process tree, read from /proc at teardown, including adopted children.-fn descendants(allocator: std.mem.Allocator, root: Pid) !PidSet {- var result: PidSet = .empty;- errdefer result.deinit(allocator);- var pending: std.ArrayList(Pid) = .empty;- defer pending.deinit(allocator);- try pending.append(allocator, root);- var path_buf: [64]u8 = undefined;- var dirents: [4096]u8 align(8) = undefined;- while (pending.pop()) |pid| {- const task_path = try std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/task", .{pid}, 0);- const dir = sys.openZ(task_path, .{ .ACCMODE = .RDONLY, .DIRECTORY = true, .CLOEXEC = true }, 0) catch continue;- defer sys.close(dir);- while (true) {- const n = sys.check(linux.getdents64(dir, &dirents, dirents.len)) catch break;- if (n == 0) break;- var offset: usize = 0;- while (offset < n) {- const entry: *align(1) const linux.dirent64 = @ptrCast(&dirents[offset]);- offset += entry.reclen;- const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&entry.name)), 0);- if (name[0] == '.') continue;- var children_path: [96]u8 = undefined;- const file = std.fmt.bufPrintSentinel(&children_path, "/proc/{d}/task/{s}/children", .{ pid, name }, 0) catch continue;- const fd = sys.openZ(file, .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, 0) catch continue;- defer sys.close(fd);- const text = sys.readAll(allocator, fd) catch continue;- defer allocator.free(text);- var it = std.mem.tokenizeScalar(u8, text, ' ');- while (it.next()) |token| {- const child = std.fmt.parseInt(Pid, std.mem.trim(u8, token, "\n"), 10) catch continue;- const gop = try result.getOrPut(allocator, child);- if (!gop.found_existing) try pending.append(allocator, child);- }- }- }- }- return result;-}+const descendants = proc.descendants;/// Holds process handles throughout so an exiting or reused PID can never/// redirect a signal to an unrelated process. Returns the compositor's wait@@ -310,51 +238,55 @@ fn stopGroup(allocator: std.mem.Allocator, compositor: Pid, compositor_handle: HawaitExit(allocator, &handles, compositor_handle, 2000);var status: u32 = 0;- const reaped = sys.retry(linux.wait4, .{ compositor, @as(*i32, @ptrCast(&status)), linux.W.NOHANG, null }) catch 0;+ const reaped = sys.retry(c.wait4, .{ compositor, @as(*i32, @ptrCast(&status)), std.posix.W.NOHANG, null }) catch 0;for (handles.keys()) |pid| {var ignored: u32 = 0;- _ = linux.wait4(pid, @ptrCast(&ignored), linux.W.NOHANG, null);+ _ = c.wait4(pid, @ptrCast(&ignored), std.posix.W.NOHANG, null);}if (reaped != compositor) {- sys.diagnostic("killed compositor remains in kernel I/O; leaving it to logind teardown", .{});+ sys.diagnostic("killed compositor remains in kernel I/O; ending supervision", .{});return null;}return status;}fn collect(allocator: std.mem.Allocator, handles: *std.AutoArrayHashMapUnmanaged(Pid, Handle), compositor: Pid, preexisting: *const PidSet) void {- var tree = descendants(allocator, linux.getpid()) catch return;+ var tree = descendants(allocator, c.getpid()) catch return;defer tree.deinit(allocator);- for (tree.keys()) |pid| {+ for (tree.keys(), tree.values()) |pid, stamp| {if (pid == compositor or preexisting.contains(pid) or handles.contains(pid)) continue;const handle = Handle.open(pid) catch continue;+ if (!proc.treeIdentityMatches(pid, stamp)) {+ handle.close();+ continue;+ }handles.put(allocator, pid, handle) catch handle.close();}}-fn send(handles: *const std.AutoArrayHashMapUnmanaged(Pid, Handle), compositor_handle: Handle, sig: linux.SIG) void {+fn send(handles: *const std.AutoArrayHashMapUnmanaged(Pid, Handle), compositor_handle: Handle, sig: std.posix.SIG) void {signalHandle(compositor_handle, sig);for (handles.values()) |handle| signalHandle(handle, sig);}-fn signalHandle(handle: Handle, sig: linux.SIG) void {+fn signalHandle(handle: Handle, sig: std.posix.SIG) void {handle.signal(sig) catch |err| switch (err) {- error.PermissionDenied => sys.diagnostic("privileged descendant must be stopped by logind session teardown", .{}),+ error.PermissionDenied => sys.diagnostic("privileged descendant must be stopped by the login owner", .{}),else => {},};}/// Waits for every handle to become readable (exited), up to `timeout_ms`.fn awaitExit(allocator: std.mem.Allocator, handles: *const std.AutoArrayHashMapUnmanaged(Pid, Handle), compositor_handle: Handle, timeout_ms: i64) void {- const fds = allocator.alloc(linux.pollfd, handles.count() + 1) catch return;+ const fds = allocator.alloc(std.posix.pollfd, handles.count() + 1) catch return;defer allocator.free(fds);- fds[0] = .{ .fd = compositor_handle.fd, .events = linux.POLL.IN, .revents = 0 };- for (handles.values(), fds[1..]) |handle, *p| p.* = .{ .fd = handle.fd, .events = linux.POLL.IN, .revents = 0 };+ fds[0] = .{ .fd = compositor_handle.fd, .events = std.posix.POLL.IN, .revents = 0 };+ for (handles.values(), fds[1..]) |handle, *p| p.* = .{ .fd = handle.fd, .events = std.posix.POLL.IN, .revents = 0 };const deadline = sys.monotonicMs() + timeout_ms;while (true) {const remaining = deadline - sys.monotonicMs();if (remaining <= 0) return;- _ = sys.retry(linux.poll, .{ fds.ptr, fds.len, @as(i32, @intCast(remaining)) }) catch return;+ _ = sys.retry(c.poll, .{ fds.ptr, @as(c.nfds_t, @intCast(fds.len)), @as(i32, @intCast(remaining)) }) catch return;// An exited process stays readable; stop watching it.var live = false;for (fds) |*p| {diff --git a/src/session/user_bus.zig b/src/session/user_bus.zignew file mode 100644index 0000000..58e475e--- /dev/null+++ b/src/session/user_bus.zig@@ -0,0 +1,65 @@+//! A console session needs a user bus even when the OS has no user manager.+//! Reuse a responding inherited bus; otherwise hold a private daemon until the+//! supervisor exits. The daemon survives compositor restarts as a preexisting child.+const std = @import("std");+const platform = @import("platform");+const sys = @import("login_sys.zig");++pub const Daemon = struct {+ child: std.process.Child,+ handle: platform.child.Handle,+ socket_path: [:0]const u8,+ pub fn stop(self: *Daemon, io: std.Io) void {+ defer self.handle.close();+ // The supervisor may already have reaped a failed bus as an adopted+ // child. Never hand its potentially reused numeric pid to Child.kill.+ if (self.handle.exited()) {+ _ = platform.child.reap(self.child.id.?);+ self.child.id = null;+ } else self.child.kill(io);+ sys.unlinkZ(self.socket_path) catch {};+ }+};++pub fn ensure(io: std.Io, arena: std.mem.Allocator, bus: anytype, env: *std.process.Environ.Map, runtime: []const u8) !?Daemon {+ if (bus.user_address.len != 0 and bus.userReady()) {+ try env.put("DBUS_SESSION_BUS_ADDRESS", bus.user_address);+ return null;+ }+ const socket_path = try std.fmt.allocPrintSentinel(arena, "{s}/rediwm-bus-{d}", .{ runtime, std.c.getpid() }, 0);+ if (socket_path.len >= @sizeOf(@FieldType(std.posix.sockaddr.un, "path"))) return error.RuntimePathTooLong;+ const address = try std.fmt.allocPrint(arena, "unix:path={s}", .{socket_path});+ const argument = try std.fmt.allocPrint(arena, "--address={s}", .{address});+ var child = try std.process.spawn(io, .{+ .argv = &.{ "dbus-daemon", "--session", "--nofork", "--nopidfile", "--print-address=1", argument },+ .environ_map = env,+ .stdin = .ignore,+ .stdout = .pipe,+ });+ errdefer {+ child.kill(io);+ sys.unlinkZ(socket_path) catch {};+ }+ const output = child.stdout.?;+ defer output.close(io);+ child.stdout = null;+ var text: [1024]u8 = undefined;+ var used: usize = 0;+ const deadline = sys.monotonicMs() + 5000;+ while (true) {+ const remaining = deadline - sys.monotonicMs();+ if (remaining <= 0 or used == text.len) return error.SessionBusNotReady;+ var fds = [_]std.c.pollfd{.{ .fd = output.handle, .events = std.c.POLL.IN, .revents = 0 }};+ if (try sys.retry(std.c.poll, .{ &fds, 1, @as(c_int, @intCast(remaining)) }) == 0) return error.SessionBusNotReady;+ const n = try sys.retry(std.c.read, .{ output.handle, text[used..].ptr, text.len - used });+ if (n == 0) return error.SessionBusNotReady;+ used += n;+ if (std.mem.indexOfScalar(u8, text[0..used], '\n') != null) break;+ }+ bus.user_address = address;+ if (!bus.userReady()) return error.SessionBusNotReady;+ try env.put("DBUS_SESSION_BUS_ADDRESS", address);+ const handle = try platform.child.Handle.open(child.id.?);+ bus.owns_user_bus = true;+ return .{ .child = child, .handle = handle, .socket_path = socket_path };+}diff --git a/src/session_main.zig b/src/session_main.zigindex 514a74d..3101f4c 100644--- a/src/session_main.zig+++ b/src/session_main.zig@@ -1,22 +1,24 @@//! rediwm-session: the login supervisor. Owns publication, readiness and child//! session lifetime.//!-//! Only a verified logind login can publish to the shared user manager. Nested-//! instances use direct child environments. Helpers must run in the foreground;-//! applications are never restarted independently.+//! Only a verified login can publish activation state: logind uses the shared+//! user manager, ConsoleKit2 a session bus. Unverified instances use direct child+//! environments. Helpers run in the foreground; apps are not restarted separately.const std = @import("std");-const linux = std.os.linux;+const c = @import("c");const sys = @import("session/login_sys.zig");+const login = @import("session/login_manager.zig");const login_bus = @import("session/login_bus.zig");const publication = @import("session/publication.zig");const supervisor = @import("session/supervisor.zig");-const Publication = publication.Publication(login_bus.Bus);+const Publication = if (login.owns_session) @import("session/private_publication.zig").Publication(login_bus.Bus) else publication.Publication(login_bus.Bus);+const user_bus = @import("session/user_bus.zig");const allocator = std.heap.c_allocator;pub fn main(init: std.process.Init) !u8 {// The compositor refuses root too; fail here instead of crash-restarting it.- if (std.os.linux.getuid() == 0 or std.os.linux.geteuid() == 0) {+ if (std.posix.system.getuid() == 0 or std.posix.system.geteuid() == 0) {sys.diagnostic("refusing to run as root; log in as a regular user", .{});return 1;}@@ -25,6 +27,10 @@ pub fn main(init: std.process.Init) !u8 {var env = try environ.createMap(allocator);defer env.deinit();for ([_][]const u8{ "REDIWM_LOGIN_SESSION", "REDIWM_SESSION_PRIMARY", "REDIWM_SESSION_FD" }) |key| _ = env.swapRemove(key);+ if (login.owns_session) {+ _ = env.swapRemove("XDG_SESSION_COOKIE");+ _ = env.swapRemove("XDG_SESSION_ID");+ }var arena_state: std.heap.ArenaAllocator = .init(allocator);defer arena_state.deinit();@@ -41,12 +47,18 @@ pub fn main(init: std.process.Init) !u8 {defer bus.deinit();// Never infer a login from XDG_SESSION_TYPE or XDG_SESSION_ID alone.+ var daemon: ?user_bus.Daemon = null;+ defer if (daemon) |*owned| owned.stop(init.io);var lease: ?Publication = null;defer if (lease) |*p| p.deinit();- loginSession(arena, &bus, runtime_env, &env, &lease) catch |err| {+ loginSession(init.io, arena, &bus, runtime_env, &env, &lease, &daemon) catch |err| {sys.diagnostic("global activation disabled: {t}", .{err});if (lease) |*p| p.deinit();lease = null;+ if (login.owns_session and env.get("REDIWM_LOGIN_SESSION") == null) {+ login.release(&bus);+ for ([_][]const u8{ "XDG_SESSION_COOKIE", "XDG_SESSION_ID", "REDIWM_LOGIN_SESSION", "REDIWM_SESSION_PRIMARY" }) |key| _ = env.swapRemove(key);+ }};const exe_dir = try std.process.executableDirPathAlloc(init.io, arena);@@ -86,18 +98,23 @@ pub fn main(init: std.process.Init) !u8 {});}-fn loginSession(arena: std.mem.Allocator, bus: *login_bus.Bus, runtime_env: ?[]const u8, env: *std.process.Environ.Map, lease: *?Publication) !void {- const session = try bus.login(arena);+fn loginSession(io: std.Io, arena: std.mem.Allocator, bus: *login_bus.Bus, runtime_env: ?[]const u8, env: *std.process.Environ.Map, lease: *?Publication, daemon: *?user_bus.Daemon) !void {+ const context: login.Context = if (login.owns_session) .{ .display_device = try @import("platform").login_process.consoleDevice(arena) } else .{};+ const session = try bus.login(arena, context);const runtime = runtime_env orelse return error.NoRuntimeDir;const runtime_z = try arena.dupeSentinel(u8, runtime, 0);- var info: linux.Statx = undefined;- _ = try sys.check(linux.statx(linux.AT.FDCWD, runtime_z, 0, .{ .UID = true, .MODE = true }, &info));- if (info.uid != linux.getuid() or info.mode & 0o077 != 0) {+ var info: c.struct_stat = undefined;+ _ = try sys.check(c.stat(runtime_z, &info));+ if (info.st_uid != std.posix.system.getuid() or info.st_mode & 0o077 != 0 or info.st_mode & c.S_IFMT != c.S_IFDIR) {sys.diagnostic("runtime directory is not private to this uid", .{});return error.RuntimeDirNotPrivate;}+ if (login.owns_session) {+ try env.put("XDG_SESSION_COOKIE", bus.login_cookie.?);+ daemon.* = try user_bus.ensure(io, arena, bus, env, runtime);+ }try env.put("REDIWM_LOGIN_SESSION", session);- try env.put("XDG_SESSION_ID", session);+ try env.put("XDG_SESSION_ID", if (login.owns_session) std.fs.path.basename(session) else session);if (env.get("DBUS_SESSION_BUS_ADDRESS") == null) {try env.put("DBUS_SESSION_BUS_ADDRESS", try std.fmt.allocPrint(arena, "unix:path={s}/bus", .{runtime}));}@@ -140,7 +157,7 @@ fn makePath(arena: std.mem.Allocator, path: []const u8) !void {while (end <= path.len) : (end += 1) {if (end != path.len and path[end] != '/') continue;const partial = try arena.dupeSentinel(u8, path[0..end], 0);- switch (linux.errno(linux.mkdirat(linux.AT.FDCWD, partial, 0o700))) {+ switch (std.posix.errno(c.mkdirat(c.AT_FDCWD, partial, @as(c.mode_t, 0o700)))) {.SUCCESS, .EXIST => {},else => |err| return sys.errnoError(err),}@@ -148,6 +165,7 @@ fn makePath(arena: std.mem.Allocator, path: []const u8) !void {}test {+ _ = @import("session/private_publication.zig");_ = publication;_ = supervisor;_ = login_bus;diff --git a/src/system_monitor/AGENTS.md b/src/system_monitor/AGENTS.mdindex 6e7d85c..18f6bd8 100644--- a/src/system_monitor/AGENTS.md+++ b/src/system_monitor/AGENTS.md@@ -13,6 +13,9 @@lives in `proc_linux_system.zig`; rates reset with the worker generation.The Linux parsers are pure and testedeverywhere through `proc_linux.zig`.+ `descendants` also supplies the supervisor's teardown tree: Linux walks+ task children; FreeBSD follows parent links in one `kern.proc` snapshot.+ Its start stamps must match after a kqueue handle opens, before signaling.* A snapshot owns its arena. The worker publishes under its mutex through aneventfd; the UI takes ownership. A generation change cancels enumeration andpublication, resets CPU baselines, and wakes the worker. Inactive workersdiff --git a/src/system_monitor/proc.zig b/src/system_monitor/proc.zigindex bac8025..0746b51 100644--- a/src/system_monitor/proc.zig+++ b/src/system_monitor/proc.zig@@ -58,3 +58,16 @@ pub fn isProtected(process: Process, pid: i32) Error!bool {var buf: [4096]u8 = undefined;return protectedName(try process.exePath(&buf));}++pub const Tree = common.Tree;+pub const descendants = backend.descendants;++/// FreeBSD's kqueue handles carry no start stamp; validate the snapshot after+/// opening one. Linux's tree uses zero and its pidfd remains the identity guard.+pub fn treeIdentityMatches(pid: i32, stamp: u64) bool {+ if (builtin.os.tag == .linux) return true;+ const process = Process.open(pid) catch return false;+ defer process.close();+ var buf: [256]u8 = undefined;+ return (process.stat(&buf) catch return false).start == stamp;+}diff --git a/src/system_monitor/proc_common.zig b/src/system_monitor/proc_common.zigindex 8a60f74..eee0a5c 100644--- a/src/system_monitor/proc_common.zig+++ b/src/system_monitor/proc_common.zig@@ -8,6 +8,9 @@ pub const c = @import("c");/// is unreadable or malformed; `Unsupported` means this OS has no backend yet.pub const Error = error{ ProcessExited, PermissionDenied, ReadFailed, DataTooLarge, IdentityUnavailable, Unsupported };+/// Owned descendants; FreeBSD includes start stamps for handle validation.+pub const Tree = std.AutoArrayHashMapUnmanaged(i32, u64);+pub const Identity = struct {pid: i32,/// An opaque start stamp: with the pid it names one process for ever.diff --git a/src/system_monitor/proc_freebsd.zig b/src/system_monitor/proc_freebsd.zigindex 99e54c7..8ed8630 100644--- a/src/system_monitor/proc_freebsd.zig+++ b/src/system_monitor/proc_freebsd.zig@@ -194,3 +194,23 @@ pub fn systemStats(_: []u8) common.System {result.uptime_seconds = @intCast(uptime.tv_sec);return result;}++/// One kern.proc snapshot preserves identity while following parent links.+pub fn descendants(alloc: std.mem.Allocator, root: i32) !common.Tree {+ var list = List.open() orelse return error.ReadFailed;+ defer list.close();+ var tree: common.Tree = .empty;+ errdefer tree.deinit(alloc);+ var changed = true;+ while (changed) {+ changed = false;+ for (list.entries[0..list.count]) |info| {+ if (info.ki_pid <= 0 or info.ki_pid == root or tree.contains(info.ki_pid)) continue;+ if (info.ki_ppid != root and !tree.contains(info.ki_ppid)) continue;+ const stamp = @as(u64, @intCast(@max(info.ki_start.tv_sec, 0))) * 1_000_000 + @as(u64, @intCast(@max(info.ki_start.tv_usec, 0)));+ try tree.put(alloc, info.ki_pid, stamp);+ changed = true;+ }+ }+ return tree;+}diff --git a/src/system_monitor/proc_linux.zig b/src/system_monitor/proc_linux.zigindex 1eedaa5..95055aa 100644--- a/src/system_monitor/proc_linux.zig+++ b/src/system_monitor/proc_linux.zig@@ -10,6 +10,7 @@ const Uids = common.Uids;const Cpu = common.Cpu;const Memory = common.Memory;const readAt = common.readAt;+pub const descendants = @import("proc_linux_children.zig").descendants;pub const systemStats = @import("proc_linux_system.zig").sample;/// comm may contain spaces, newlines and closing parentheses. Field 3 startsdiff --git a/src/system_monitor/proc_linux_children.zig b/src/system_monitor/proc_linux_children.zignew file mode 100644index 0000000..a22c094--- /dev/null+++ b/src/system_monitor/proc_linux_children.zig@@ -0,0 +1,40 @@+//! Linux supervisor teardown walks each descendant's tasks, including helpers+//! forked by threads other than the process leader.+const std = @import("std");+const c = @import("proc_common.zig").c;+const io = @import("platform").login_io;+const Tree = @import("proc_common.zig").Tree;++pub fn descendants(allocator: std.mem.Allocator, root: i32) !Tree {+ var result: Tree = .empty;+ errdefer result.deinit(allocator);+ var pending: std.ArrayList(i32) = .empty;+ defer pending.deinit(allocator);+ try pending.append(allocator, root);+ while (pending.pop()) |pid| {+ var path_buf: [64]u8 = undefined;+ const path = try std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/task", .{pid}, 0);+ const dir = c.opendir(path) orelse continue;+ defer _ = c.closedir(dir);+ while (c.readdir(dir)) |entry| {+ const name = std.mem.sliceTo(entry.*.d_name[0..], 0);+ if (name[0] == '.') continue;+ var children_path: [96]u8 = undefined;+ const file = std.fmt.bufPrintSentinel(&children_path, "/proc/{d}/task/{s}/children", .{ pid, name }, 0) catch continue;+ const fd = io.openZ(file, .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, 0) catch continue;+ defer io.close(fd);+ const text = io.readAll(allocator, fd) catch continue;+ defer allocator.free(text);+ var it = std.mem.tokenizeScalar(u8, text, ' ');+ while (it.next()) |token| {+ const child = std.fmt.parseInt(i32, std.mem.trim(u8, token, "\n"), 10) catch continue;+ const gop = try result.getOrPut(allocator, child);+ if (!gop.found_existing) {+ gop.value_ptr.* = 0; // pidfds pin Linux identities after open.+ try pending.append(allocator, child);+ }+ }+ }+ }+ return result;+}diff --git a/src/system_monitor_tests.zig b/src/system_monitor_tests.zigindex d8529ba..0122130 100644--- a/src/system_monitor_tests.zig+++ b/src/system_monitor_tests.zig@@ -195,3 +195,13 @@ test "monitor worker pause cancels publication and resume starts a fresh CPU intworker.setActive(true);worker.setActive(false);}++test "supervisor tree includes an owned child with its native identity" {+ var child = try std.process.spawn(std.testing.io, .{ .argv = &.{ "/bin/sh", "-c", "sleep 30" } });+ defer child.kill(std.testing.io);+ var tree = try proc.descendants(std.testing.allocator, std.posix.system.getpid());+ defer tree.deinit(std.testing.allocator);+ const stamp = tree.get(child.id.?) orelse return error.ChildMissing;+ try std.testing.expect(proc.treeIdentityMatches(child.id.?, stamp));+ if (stamp != 0) try std.testing.expect(!proc.treeIdentityMatches(child.id.?, stamp + 1));+}diff --git a/tests/consolekit.py b/tests/consolekit.pynew file mode 100644index 0000000..9045f3c--- /dev/null+++ b/tests/consolekit.py@@ -0,0 +1,125 @@+#!/usr/bin/env python3+"""Own and validate ConsoleKit2 logins against an independent private-bus peer.++The client is a noninstalled fixture; no host login or power service is reached.+"""+import os+import subprocess+import sys+import threading+import tempfile+from pathlib import Path++if __name__ == '__main__' and '--private' not in sys.argv:+ raise SystemExit(subprocess.call(['dbus-run-session', '--', sys.executable, __file__, '--private', *sys.argv[1:]]))++from gi.repository import Gio, GLib++NAME = 'org.freedesktop.ConsoleKit'+MANAGER = '/org/freedesktop/ConsoleKit/Manager'+SESSION = '/org/freedesktop/ConsoleKit/Session9'+COOKIE = 'private-fixture-cookie'+++class Fixture:+ def __init__(self):+ self.conn = Gio.DBusConnection.new_for_address_sync(os.environ['DBUS_SESSION_BUS_ADDRESS'],+ Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION, None, None)+ self.conn.call_sync('org.freedesktop.DBus', '/org/freedesktop/DBus', 'org.freedesktop.DBus', 'RequestName',+ GLib.Variant('(su)', (NAME, 4)), None, Gio.DBusCallFlags.NONE, 3000, None)+ self.values = {'GetUnixUser': ('u', os.getuid()), 'IsLocal': ('b', True),+ 'GetSessionType': ('s', 'wayland'), 'GetSessionClass': ('s', 'user'),+ 'GetRemoteHostName': ('s', '')}+ manager_xml = f'''<node><interface name="{NAME}.Manager">+ <method name="OpenSessionWithParameters"><arg type="a(sv)" direction="in"/><arg type="s" direction="out"/></method>+ <method name="GetSessionForCookie"><arg type="s" direction="in"/><arg type="o" direction="out"/></method>+ <method name="CloseSession"><arg type="s" direction="in"/><arg type="b" direction="out"/></method>+ </interface></node>'''+ session_xml = f'<node><interface name="{NAME}.Session">' + ''.join(+ f'<method name="{method}"><arg type="{sig}" direction="out"/></method>'+ for method, (sig, _) in self.values.items()) + '</interface></node>'+ self.conn.register_object(MANAGER, Gio.DBusNodeInfo.new_for_xml(manager_xml).interfaces[0], self.method, None, None)+ self.conn.register_object(SESSION, Gio.DBusNodeInfo.new_for_xml(session_xml).interfaces[0], self.method, None, None)+ self.calls = []+ self.refuse_lookup = False+ self.loop = GLib.MainLoop()+ self.thread = threading.Thread(target=self.loop.run, daemon=True)+ self.thread.start()++ def method(self, _conn, sender, _path, _interface, method, parameters, invocation):+ self.calls.append((method, sender, parameters.unpack()))+ if method == 'OpenSessionWithParameters':+ invocation.return_value(GLib.Variant('(s)', (COOKIE,)))+ elif method == 'GetSessionForCookie':+ if self.refuse_lookup:+ invocation.return_dbus_error(NAME + '.Manager.Error.General', 'no such session')+ else:+ invocation.return_value(GLib.Variant('(o)', (SESSION,)))+ elif method == 'CloseSession':+ invocation.return_value(GLib.Variant('(b)', (True,)))+ else:+ signature, value = self.values[method]+ invocation.return_value(GLib.Variant(f'({signature})', (value,)))++ def run(self, binary, device='/dev/ttyv0'):+ self.calls.clear()+ return subprocess.run([binary, device], text=True, capture_output=True, timeout=15)++ def assert_closed(self):+ methods = [entry[0] for entry in self.calls]+ assert methods[0] == 'OpenSessionWithParameters', self.calls+ assert methods[-1] == 'CloseSession' and methods.count('CloseSession') == 1, self.calls+ assert len({entry[1] for entry in self.calls}) == 1, 'ownership connection changed'+ assert self.calls[-1][2] == (COOKIE,), self.calls++ def close(self):+ self.loop.quit()+ self.thread.join(timeout=2)+ self.conn.close_sync(None)+++def main():+ binary = next(arg for arg in sys.argv[1:] if arg != '--private')+ fixture = Fixture()+ try:+ result = fixture.run(binary)+ assert result.returncode == 0, result.stderr+ assert result.stdout == f'verified {SESSION}\n', result.stdout+ fixture.assert_closed()+ parameters = dict(fixture.calls[0][2][0])+ assert parameters == {'session-type': 'wayland', 'session-class': 'user',+ 'display-device': '/dev/ttyv0', 'remote-host-name': ''}, parameters+ for method, wrong in [('GetUnixUser', os.getuid() + 1), ('IsLocal', False),+ ('GetSessionType', 'x11'), ('GetSessionClass', 'greeter'),+ ('GetRemoteHostName', 'remote.example')]:+ original = fixture.values[method]+ fixture.values[method] = (original[0], wrong)+ try:+ result = fixture.run(binary)+ finally:+ fixture.values[method] = original+ assert result.returncode != 0 and 'NotLocalWaylandLogin' in result.stderr, (method, result)+ assert not result.stdout, result.stdout+ fixture.assert_closed()+ result = fixture.run(binary, '/dev/pts/1')+ assert result.returncode != 0 and not fixture.calls, (result, fixture.calls)+ fixture.refuse_lookup = True+ result = fixture.run(binary)+ assert result.returncode != 0, result+ fixture.assert_closed()+ with tempfile.TemporaryDirectory(prefix='rediwm-consolekit-') as directory:+ env = {**os.environ, 'HOME': directory, 'XDG_RUNTIME_DIR': directory,+ 'XDG_CONFIG_HOME': directory, 'XDG_CACHE_HOME': directory,+ 'XDG_STATE_HOME': directory, 'XDG_DATA_HOME': directory}+ result = subprocess.run([binary, '--user-bus', directory], env=env,+ capture_output=True, text=True, timeout=15)+ assert result.returncode == 0, result.stderr+ assert result.stdout == 'private user bus ready\n', result.stdout+ assert not list(Path(directory).glob('rediwm-bus-*')), 'daemon socket survived cleanup'+ print('PASS: ConsoleKit session ownership, console-only admission, identity checks, and cleanup on rejection')+ finally:+ fixture.close()+++if __name__ == '__main__':+ main()diff --git a/tests/rediwm_session.py b/tests/rediwm_session.pyindex 3116dee..e2ccfc3 100644--- a/tests/rediwm_session.py+++ b/tests/rediwm_session.py@@ -178,6 +178,10 @@ def test_compositor_environment():def zombie_children(pid):"""Direct children of `pid` that have exited but not been waited for."""+ if sys.platform.startswith('freebsd'):+ rows = subprocess.check_output(['ps', '-axo', 'pid=,ppid=,stat='], text=True)+ return [int(parts[0]) for line in rows.splitlines()+ if len(parts := line.split()) == 3 and int(parts[1]) == pid and parts[2].startswith('Z')]children = Path(f"/proc/{pid}/task/{pid}/children").read_text().split()zombies = []for child in children:diff --git a/tests/session_services.py b/tests/session_services.pyindex bcb9adf..6d8365d 100644--- a/tests/session_services.py+++ b/tests/session_services.py@@ -7,6 +7,7 @@ src/session/publication.zig; tests/session_bus.py covers real bus calls.Usage: session_services.py <rediwm-session binary>"""import os+import errnofrom pathlib import Pathimport selectimport shutil@@ -102,6 +103,24 @@ time.sleep(60)self.assert_dead(pid)def assert_dead(self, pid):+ if sys.platform.startswith('freebsd'):+ queue = select.kqueue()+ try:+ event = select.kevent(pid, filter=select.KQ_FILTER_PROC,+ flags=select.KQ_EV_ADD | select.KQ_EV_ONESHOT,+ fflags=select.KQ_NOTE_EXIT)+ try:+ events = queue.control([event], 1, 2)+ self.assertTrue(events, f'owned process {pid} survived')+ if events[0].flags & select.KQ_EV_ERROR:+ self.assertEqual(events[0].data, errno.ESRCH)+ else:+ self.assertTrue(events[0].fflags & select.KQ_NOTE_EXIT)+ except ProcessLookupError:+ pass+ finally:+ queue.close()+ returntry:fd = os.pidfd_open(pid)except ProcessLookupError: