RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Extract a shared login-manager interface for the FreeBSD port
oxydizer3d2cb52a3956
diff --git a/docs/agent-notes/map.md b/docs/agent-notes/map.mdindex 58b1d1f..69ccdf1 100644--- a/docs/agent-notes/map.md+++ b/docs/agent-notes/map.md@@ -96,7 +96,8 @@ and `effects/minimize_mesh.zig` (minimize snapshots and deformation),`appearance_*.zig` and `printers_*.zig`.* **Session** (`session/`, `AGENTS.md` there): `lock.zig` (+ `lock_account`,`lock_events`, `lock_input`, `lock_view.zig`), `greeter.zig`, `idle.zig`,- `power.zig` (+ `power_*.zig`, logind), portals (`settings_portal.zig`,+ `power.zig` (+ `power_*.zig`), `login_manager.zig` (`login_manager/`: service+ protocol shared with the supervisor and polkit; currently logind), 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/plans/freebsd.md b/docs/plans/freebsd.mdindex 2d4b038..28cb5ea 100644--- a/docs/plans/freebsd.md+++ b/docs/plans/freebsd.md@@ -16,8 +16,17 @@ primary platform; the port must not change Linux behaviour or cost.directory watching, own path, peer credentials, process attributes, wakedescriptors, rename and stat, `kern.proc` process list, tool lookup), eachwith a FreeBSD half except seccomp. The Linux-side preparation (P.1–P.4,- P.6–P.10) is finished. The IPC allowance check refuses a connector that has+ P.6–P.11) is finished. The IPC allowance check refuses a connector that hasexited or cannot be seen.+* **Login-manager boundary (2026-11-09):** `session/login_manager.zig` is shared+ by the supervisor, power policy and polkit. Its logind backend owns the+ requests, 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.+ Linux Debug/ReleaseSafe, unit tests, polkit, session-bus, supervisor,+ power-settings and greeter pass; the cross-check passes. Power's two final+ helper-cleanup cases fail identically on clean HEAD (`b9f10be`); its login,+ inhibitor and action cases pass.* **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`,@@ -113,12 +122,11 @@ Desktop=rediwm, not remote, same uid), gates the polkit agent, the activationenvironment, following `Lock` and keeping `LockedHint`, and the Files terminal.Left to do:-* One login-manager interface (P.11): logind implementation (today's code,- moved) and a ConsoleKit2 one: session of a pid, `Lock` signal,+* 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. Today logind's names are constants in `power.zig`- imported by `power_*`, and `login_bus.zig` and `polkit/agent.zig` spell them- out.+ 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 asession `rediwm-session` opens itself. No Desktop property, and a sessionwithout a display device is never active, so "active" cannot be required.@@ -199,11 +207,6 @@ installers (GNU `install -D`, systemd units, Debian/Arch PAM files); FreeBSD'shelper socket; the agent could start the setuid helper itself via`rediwm_polkit_spawn`). `/etc/pam.d` and `/run/rediwm-dm` are written by theLinux installers only. Kept on purpose: `/etc/xdg`, `/etc/login.defs`.-11. **Login-manager interface:** move the logind calls of `login_bus`,- `polkit/agent` and `power_*` behind one interface, the logind implementation- unchanged and a recording fake for tests (`tests/power.py`, `polkit.py`,- `rediwm_session.py`, `session_bus.py` as the check). The ConsoleKit2- implementation is phase 2.### 1. Compositor runs (finish)diff --git a/src/polkit/agent.zig b/src/polkit/agent.zigindex 56be034..a2384e0 100644--- a/src/polkit/agent.zig+++ b/src/polkit/agent.zig@@ -3,6 +3,7 @@const std = @import("std");const wl = @import("wayland").server.wl;const dbus = @import("dbus");+const login = @import("../session/login_manager.zig");const activation = @import("../session/activation.zig");const helper_mod = @import("helper.zig");const identity = @import("identity.zig");@@ -204,33 +205,25 @@ pub const Agent = struct {if (self.closing) return;_ = returned(result, "") catch |err| return self.unavailable(err);if (self.session_id != null) return self.queryOwner();- var body: wire.Writer = .{ .allocator = self.allocator };- defer body.deinit();- body.uint32(@intCast(std.posix.system.getpid())) catch |err| return self.unavailable(err);- _ = conn.call("org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "GetSessionByPID", "u", &body, self, sessionPath, 5000) catch |err| self.unavailable(err);+ _ = login.call(conn, .{ .session_for_pid = @intCast(std.posix.system.getpid()) }, null, self, sessionPath, 5000) catch |err| self.unavailable(err);}fn sessionPath(owner: ?*anyopaque, conn: *C, result: C.Failure!wire.Message) void {const self = from(owner);if (self.closing) return;- var msg = returned(result, "o") catch |err| return self.unavailable(err);- const path = msg.body.objectPath() catch |err| return self.unavailable(err);- var body: wire.Writer = .{ .allocator = self.allocator };- defer body.deinit();- body.string("org.freedesktop.login1.Session") catch |err| return self.unavailable(err);- body.string("Id") catch |err| return self.unavailable(err);- _ = conn.call("org.freedesktop.login1", path, "org.freedesktop.DBus.Properties", "Get", "ss", &body, self, sessionId, 5000) catch |err| self.unavailable(err);+ const msg = result catch |err| return self.unavailable(err);+ const path = login.readSessionPath(msg) catch |err| return self.unavailable(err);+ _ = login.call(conn, .{ .session_field = .{ .path = path, .field = .id } }, null, self, sessionId, 5000) catch |err| self.unavailable(err);}fn sessionId(owner: ?*anyopaque, _: *C, result: C.Failure!wire.Message) void {const self = from(owner);if (self.closing) return;- var msg = returned(result, "v") catch |err| return self.unavailable(err);- const sig = msg.body.variant() catch |err| return self.unavailable(err);- if (!std.mem.eql(u8, sig, "s")) return self.unavailable(error.InvalidReply);- const id = msg.body.string() catch |err| return self.unavailable(err);+ const msg = result catch |err| return self.unavailable(err);+ const id = login.readSessionId(msg) catch |err| return self.unavailable(err);if (id.len == 0) return self.unavailable(error.NoSession);self.session_id = self.allocator.dupe(u8, id) catch |err| return self.unavailable(err);self.queryOwner();}+fn queryOwner(self: *Agent) void {self.query_revision = self.owner_revision;var body: wire.Writer = .{ .allocator = self.allocator };diff --git a/src/session/AGENTS.md b/src/session/AGENTS.mdindex f11c076..1a856dc 100644--- a/src/session/AGENTS.md+++ b/src/session/AGENTS.md@@ -3,6 +3,13 @@Cross-cutting lock rules (greeter, crash handling, IPC refusal, clientext-session-lock) are in the root `AGENTS.md`.+* Login-service calls go through `login_manager.zig`; its backend owns method+ signatures, service names, signal descriptors and login identity checks.+ `power_*` retains policy and owner generations: pin session/inhibitor calls+ to that owner, ignore stale replies, and follow only this session's `Lock`.+ The recording transport tests live in `login_manager/tests.zig`; private-bus+ coverage is `tests/power.py`, `polkit.py` and `session_bus.py`.+* Login appearance is a flattened snapshot in`/var/lib/rediwm-appearance/<uid>/`, provisioned by the DM and written bythat account's real desktop session. `login_appearance.zig` reads onlydiff --git a/src/session/login_bus.zig b/src/session/login_bus.zigindex f55c966..eb86a2b 100644--- a/src/session/login_bus.zig+++ b/src/session/login_bus.zig@@ -13,7 +13,7 @@ const Env = publication.Env;const Pair = publication.Pair;const timeout_ms = 3000;-const login1 = "org.freedesktop.login1";+const login_manager = @import("login_manager.zig");const systemd1 = "org.freedesktop.systemd1";const properties = "org.freedesktop.DBus.Properties";@@ -100,82 +100,26 @@ pub const Bus = struct {return reply;}- fn sessionString(self: *Bus, arena: std.mem.Allocator, path: []const u8, name: []const u8) ![]const u8 {- var reply = try self.getProperty(.system, login1, path, login1 ++ ".Session", name);- defer reply.deinit(self.allocator);- var r = reply.reader();- if (!std.mem.eql(u8, try r.variant(), "s")) return error.InvalidReply;- return arena.dupe(u8, try r.string());- }-/// Only a verified local Wayland user login of this desktop may publish.- /// Returns the logind session id.pub fn login(self: *Bus, arena: std.mem.Allocator) ![]const u8 {- var body: wire.Writer = .{ .allocator = self.allocator };- defer body.deinit();- try body.uint32(@intCast(std.os.linux.getpid()));- var reply = try self.call(.system, login1, "/org/freedesktop/login1", login1 ++ ".Manager", "GetSessionByPID", "u", &body);- defer reply.deinit(self.allocator);- try reply.expect("o");- var r = reply.reader();- const path = try arena.dupe(u8, try r.objectPath());-- const uid = blk: {- var user = try self.getProperty(.system, login1, path, login1 ++ ".Session", "User");- defer user.deinit(self.allocator);- var ur = user.reader();- if (!std.mem.eql(u8, try ur.variant(), "(uo)")) return error.InvalidReply;- try ur.alignTo(8);- break :blk try ur.uint32();- };- const remote = blk: {- var value = try self.getProperty(.system, login1, path, login1 ++ ".Session", "Remote");- defer value.deinit(self.allocator);- var vr = value.reader();- if (!std.mem.eql(u8, try vr.variant(), "b")) return error.InvalidReply;- break :blk try vr.boolean();+ return login_manager.login(self, arena) catch |err| {+ if (err == error.NotLocalWaylandLogin) sys.diagnostic("not a local Wayland user login", .{});+ return err;};- const desktop = try self.sessionString(arena, path, "Desktop");- const desktop_ok = std.ascii.eqlIgnoreCase(desktop, "rediwm") or std.ascii.eqlIgnoreCase(desktop, "rediwm-release-safe");- if (uid != std.os.linux.getuid() or- !std.mem.eql(u8, try self.sessionString(arena, path, "Type"), "wayland") or- !std.mem.eql(u8, try self.sessionString(arena, path, "Class"), "user") or- !desktop_ok or remote)- {- sys.diagnostic("not a local Wayland user login", .{});- return error.NotLocalWaylandLogin;- }- return self.sessionString(arena, path, "Id");}- /// Another live graphical login of this uid shares the user bus.pub fn conflict(self: *Bus, arena: std.mem.Allocator, session: []const u8) !?[]const u8 {- const body: wire.Writer = .{ .allocator = self.allocator };- var reply = try self.call(.system, login1, "/org/freedesktop/login1", login1 ++ ".Manager", "ListSessions", "", &body);- defer reply.deinit(self.allocator);- try reply.expect("a(susso)");- var r = reply.reader();- var rows = try r.array(8);- const Row = struct { sid: []const u8, path: []const u8 };- var candidates: std.ArrayList(Row) = .empty;- while (rows.offset < rows.bytes.len) {- try rows.alignTo(8);- const sid = try rows.string();- const uid = try rows.uint32();- _ = try rows.string();- _ = try rows.string();- const path = try rows.objectPath();- if (uid == std.os.linux.getuid() and !std.mem.eql(u8, sid, session)) {- try candidates.append(arena, .{ .sid = try arena.dupe(u8, sid), .path = try arena.dupe(u8, path) });- }- }- for (candidates.items) |row| {- const kind = try self.sessionString(arena, row.path, "Type");- if (!std.mem.eql(u8, kind, "wayland") and !std.mem.eql(u8, kind, "x11")) continue;- if (std.mem.eql(u8, try self.sessionString(arena, row.path, "State"), "closing")) continue;- return row.sid;- }- return null;+ return login_manager.conflict(self, arena, session);+ }++ /// 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.@@ -274,15 +218,15 @@ const Reply = struct {self.endian = msg.body.endian;}- fn expect(self: *const Reply, signature: []const u8) !void {+ pub fn expect(self: *const Reply, signature: []const u8) !void {if (!std.mem.eql(u8, self.signature, signature)) return error.InvalidReply;}- fn reader(self: *const Reply) wire.Reader {+ pub fn reader(self: *const Reply) wire.Reader {return .{ .bytes = self.body, .endian = self.endian };}- fn deinit(self: *Reply, allocator: std.mem.Allocator) void {+ pub fn deinit(self: *Reply, allocator: std.mem.Allocator) void {if (self.error_name) |v| allocator.free(v);if (self.error_text) |v| allocator.free(v);allocator.free(self.signature);diff --git a/src/session/login_manager.zig b/src/session/login_manager.zignew file mode 100644index 0000000..c8a4d14--- /dev/null+++ b/src/session/login_manager.zig@@ -0,0 +1,40 @@+//! 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.+const dbus = @import("dbus");+const backend = @import("login_manager/logind.zig");+const types = @import("login_manager/types.zig");++pub const Action = types.Action;+pub const Inhibitor = types.Inhibitor;+pub const Request = types.Request;+pub const Event = types.Event;+pub const ActionError = types.ActionError;+pub const Api = types.Api;++/// `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 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;++test {+ _ = @import("login_manager/tests.zig");+}diff --git a/src/session/login_manager/logind.zig b/src/session/login_manager/logind.zignew file mode 100644index 0000000..374dd09--- /dev/null+++ b/src/session/login_manager/logind.zig@@ -0,0 +1,192 @@+//! logind/elogind wire protocol. Keep Linux behavior here when adding backends.+const std = @import("std");+const dbus = @import("dbus");+const wire = dbus.wire;+const types = @import("types.zig");+const Action = types.Action;+const name = "org.freedesktop.login1";+const path = "/org/freedesktop/login1";+const manager = name ++ ".Manager";+const session = name ++ ".Session";+const bus = "org.freedesktop.DBus";+const bus_path = "/org/freedesktop/DBus";++pub const owner_match = "type='signal',sender='org.freedesktop.DBus',path='/org/freedesktop/DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.login1'";++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 = "GetSessionByPID";+ target.signature = "u";+ try body.uint32(pid);+ },+ .session => |id| {+ target.member = "GetSession";+ target.signature = "s";+ try body.string(id);+ },+ .session_field => |field| {+ target.path = field.path;+ target.interface = "org.freedesktop.DBus.Properties";+ target.member = "Get";+ target.signature = "ss";+ try body.string(session);+ try body.string(switch (field.field) {+ .id => "Id",+ .uid => "User",+ .remote => "Remote",+ .desktop => "Desktop",+ .kind => "Type",+ .class => "Class",+ .state => "State",+ });+ },+ .list_sessions => target.member = "ListSessions",+ .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.flags = if (action.interactive) wire.flag_allow_interactive_authorization else 0;+ if (action.with_flags) {+ target.member = switch (action.kind) {+ .poweroff => "PowerOffWithFlags",+ .reboot => "RebootWithFlags",+ .@"suspend" => "SuspendWithFlags",+ };+ target.signature = "t";+ // SD_LOGIND_ROOT_CHECK_INHIBITORS: never bypass inhibitor locks.+ try body.uint64(1 << 0);+ } else {+ target.member = switch (action.kind) {+ .poweroff => "PowerOff",+ .reboot => "Reboot",+ .@"suspend" => "Suspend",+ };+ target.signature = "b";+ 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);+ },+ }+ 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();+}++fn returned(msg: wire.Message, signature: []const u8) !wire.Reader {+ if (msg.kind != .method_return) return error.Refused;+ if (!std.mem.eql(u8, msg.headers.signature, signature)) return error.InvalidReply;+ return msg.body;+}++pub fn readSessionPath(msg: wire.Message) ![]const u8 {+ var body = try returned(msg, "o");+ return body.objectPath();+}++pub fn readSessionId(msg: wire.Message) ![]const u8 {+ var body = try returned(msg, "v");+ if (!std.mem.eql(u8, try body.variant(), "s")) return error.InvalidReply;+ return body.string();+}++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 .{+ .with_flags = std.mem.indexOf(u8, xml, "SuspendWithFlags") != null,+ .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, name ++ ".OperationInhibited") or eq(u8, error_name, name ++ ".BlockedByInhibitorLock")) return .inhibited;+ if (eq(u8, error_name, bus ++ ".Error.InteractiveAuthorizationRequired")) return .authorization_required;+ if (eq(u8, error_name, bus ++ ".Error.AccessDenied") or eq(u8, error_name, name ++ ".NotEnoughPrivileges")) return .denied;+ return .other;+}++pub fn usesCommand(kind: Action) bool {+ return kind != .@"suspend";+}++/// systemctl requires systemd as init; elogind's loginctl has no --no-block.+pub fn commandArgv(buf: *[4][]const u8, kind: Action, ask_password: bool, no_block: bool) []const []const u8 {+ std.debug.assert(usesCommand(kind));+ const systemd = std.posix.system.access("/run/systemd/system", std.posix.F_OK) == 0;+ buf[0] = if (systemd) "systemctl" else "loginctl";+ buf[1] = @tagName(kind);+ var len: usize = 2;+ if (!ask_password) {+ buf[len] = "--no-ask-password";+ len += 1;+ }+ if (no_block and systemd) {+ buf[len] = "--no-block";+ len += 1;+ }+ return buf[0..len];+}diff --git a/src/session/login_manager/logind_login.zig b/src/session/login_manager/logind_login.zignew file mode 100644index 0000000..8303581--- /dev/null+++ b/src/session/login_manager/logind_login.zig@@ -0,0 +1,79 @@+//! Blocking login verification and graphical-session contention for logind.+const std = @import("std");+const types = @import("types.zig");++fn sessionString(self: anytype, arena: std.mem.Allocator, path: []const u8, field: types.SessionField) ![]const u8 {+ var reply = try self.loginCall(.{ .session_field = .{ .path = path, .field = field } });+ defer reply.deinit(self.allocator);+ try reply.expect("v");+ var r = reply.reader();+ if (!std.mem.eql(u8, try r.variant(), "s")) return error.InvalidReply;+ return arena.dupe(u8, try r.string());+}++/// 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 {+ var reply = try self.loginCall(.{ .session_for_pid = @intCast(std.posix.system.getpid()) });+ defer reply.deinit(self.allocator);+ try reply.expect("o");+ var r = reply.reader();+ const path = try arena.dupe(u8, try r.objectPath());++ const uid = blk: {+ var user = try self.loginCall(.{ .session_field = .{ .path = path, .field = .uid } });+ defer user.deinit(self.allocator);+ try user.expect("v");+ var ur = user.reader();+ if (!std.mem.eql(u8, try ur.variant(), "(uo)")) return error.InvalidReply;+ try ur.alignTo(8);+ break :blk try ur.uint32();+ };+ const remote = blk: {+ var value = try self.loginCall(.{ .session_field = .{ .path = path, .field = .remote } });+ defer value.deinit(self.allocator);+ try value.expect("v");+ var vr = value.reader();+ if (!std.mem.eql(u8, try vr.variant(), "b")) return error.InvalidReply;+ break :blk try vr.boolean();+ };+ const desktop = try sessionString(self, arena, path, .desktop);+ const desktop_ok = std.ascii.eqlIgnoreCase(desktop, "rediwm") or std.ascii.eqlIgnoreCase(desktop, "rediwm-release-safe");+ if (uid != std.posix.system.getuid() or+ !std.mem.eql(u8, try sessionString(self, arena, path, .kind), "wayland") or+ !std.mem.eql(u8, try sessionString(self, arena, path, .class), "user") or+ !desktop_ok or remote)+ {+ return error.NotLocalWaylandLogin;+ }+ return sessionString(self, arena, path, .id);+}++/// Another live graphical login of this uid shares the user bus.+pub fn conflict(self: anytype, arena: std.mem.Allocator, session: []const u8) !?[]const u8 {+ var reply = try self.loginCall(.list_sessions);+ defer reply.deinit(self.allocator);+ try reply.expect("a(susso)");+ var r = reply.reader();+ var rows = try r.array(8);+ const Row = struct { sid: []const u8, path: []const u8 };+ var candidates: std.ArrayList(Row) = .empty;+ while (rows.offset < rows.bytes.len) {+ try rows.alignTo(8);+ const sid = try rows.string();+ const uid = try rows.uint32();+ _ = try rows.string();+ _ = try rows.string();+ const path = try rows.objectPath();+ if (uid == std.posix.system.getuid() and !std.mem.eql(u8, sid, session)) {+ try candidates.append(arena, .{ .sid = try arena.dupe(u8, sid), .path = try arena.dupe(u8, path) });+ }+ }+ for (candidates.items) |row| {+ const kind = try sessionString(self, arena, row.path, .kind);+ if (!std.mem.eql(u8, kind, "wayland") and !std.mem.eql(u8, kind, "x11")) continue;+ if (std.mem.eql(u8, try sessionString(self, arena, row.path, .state), "closing")) continue;+ return row.sid;+ }+ return null;+}diff --git a/src/session/login_manager/tests.zig b/src/session/login_manager/tests.zignew file mode 100644index 0000000..89d2c10--- /dev/null+++ b/src/session/login_manager/tests.zig@@ -0,0 +1,104 @@+const std = @import("std");+const dbus = @import("dbus");+const login = @import("../login_manager.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 {+ allocator: std.mem.Allocator = testing.allocator,+ target: ?types.Target = null,+ body: std.ArrayList(u8) = .empty,+ calls: u32 = 0,+ timeout: u32 = 0,++ pub fn callWithFlags(self: *Recording, destination: []const u8, path: []const u8, interface: []const u8, member: []const u8, signature: []const u8, body: *const wire.Writer, _: ?*anyopaque, _: ?dbus.Connection.Callback, timeout: u32, flags: u8) !u32 {+ self.target = .{ .destination = destination, .path = path, .interface = interface, .member = member, .signature = signature, .flags = flags };+ self.body.clearRetainingCapacity();+ try self.body.appendSlice(self.allocator, body.bytes.items);+ self.timeout = timeout;+ self.calls += 1;+ return self.calls;+ }++ fn reader(self: *const Recording) wire.Reader {+ return .{ .bytes = self.body.items };+ }++ fn deinit(self: *Recording) void {+ self.body.deinit(self.allocator);+ }+};++test "automatic suspend never prompts or overrides inhibitors in either API" {+ var fake: Recording = .{};+ defer fake.deinit();+ for ([_]bool{ false, true }) |with_flags| {+ _ = try login.call(&fake, .{ .action = .{ .kind = .@"suspend", .interactive = false, .with_flags = with_flags } }, null, null, null, 5000);+ const target = fake.target.?;+ try testing.expectEqualStrings("org.freedesktop.login1", target.destination);+ try testing.expectEqualStrings("/org/freedesktop/login1", target.path);+ try testing.expectEqualStrings("org.freedesktop.login1.Manager", target.interface);+ try testing.expectEqual(@as(u8, 0), target.flags);+ var body = fake.reader();+ if (with_flags) {+ try testing.expectEqualStrings("SuspendWithFlags", target.member);+ try testing.expectEqualStrings("t", target.signature);+ try testing.expectEqual(@as(u64, 1), try body.uint64());+ } else {+ try testing.expectEqualStrings("Suspend", target.member);+ try testing.expectEqualStrings("b", target.signature);+ try testing.expect(!try body.boolean());+ }+ try body.done();+ }+ _ = try login.call(&fake, .{ .action = .{ .kind = .@"suspend", .interactive = true, .with_flags = false } }, null, null, null, 5000);+ try testing.expectEqual(wire.flag_allow_interactive_authorization, fake.target.?.flags);+ var body = fake.reader();+ try testing.expect(try body.boolean());+}++test "session and inhibitor calls remain pinned to the selected service owner" {+ var fake: Recording = .{};+ defer fake.deinit();+ _ = try login.call(&fake, .{ .inhibit = .sleep }, ":1.42", null, null, 5000);+ try testing.expectEqualStrings(":1.42", fake.target.?.destination);+ try testing.expectEqualStrings("Inhibit", fake.target.?.member);+ var body = fake.reader();+ for ([_][]const u8{ "sleep", "RediWM", "Lock the screen before sleep", "delay" }) |arg| try testing.expectEqualStrings(arg, try body.string());+ try body.done();+ _ = try login.call(&fake, .{ .session = "c7" }, ":1.42", null, null, 3000);+ try testing.expectEqualStrings(":1.42", fake.target.?.destination);+ try testing.expectEqualStrings("GetSession", fake.target.?.member);+ try testing.expectEqual(@as(u32, 3000), fake.timeout);+ body = fake.reader();+ try testing.expectEqualStrings("c7", try body.string());+ _ = try login.call(&fake, .{ .locked_hint = .{ .path = "/session/ours", .locked = true } }, ":1.42", null, null, 5000);+ try testing.expectEqualStrings(":1.42", fake.target.?.destination);+ try testing.expectEqualStrings("/session/ours", fake.target.?.path);+ try testing.expectEqualStrings("SetLockedHint", fake.target.?.member);+ body = fake.reader();+ try testing.expect(try body.boolean());+}++test "session identity rejects error replies and wrong property types" {+ var body: wire.Writer = .{ .allocator = testing.allocator };+ defer body.deinit();+ try body.variant("s");+ try body.string("c7");+ var msg: wire.Message = .{ .kind = .method_return, .serial = 1, .headers = .{ .signature = "v" }, .body = .{ .bytes = body.bytes.items } };+ try testing.expectEqualStrings("c7", try login.readSessionId(msg));+ msg.kind = .error_reply;+ try testing.expectError(error.Refused, login.readSessionId(msg));+ msg.kind = .method_return;+ msg.headers.signature = "s";+ try testing.expectError(error.InvalidReply, login.readSessionId(msg));+ body.bytes.clearRetainingCapacity();+ try body.variant("u");+ try body.uint32(7);+ msg.headers.signature = "v";+ msg.body = .{ .bytes = body.bytes.items };+ try testing.expectError(error.InvalidReply, login.readSessionId(msg));+}diff --git a/src/session/login_manager/types.zig b/src/session/login_manager/types.zignew file mode 100644index 0000000..84075f3--- /dev/null+++ b/src/session/login_manager/types.zig@@ -0,0 +1,29 @@+pub const Action = enum { poweroff, reboot, @"suspend" };+pub const Inhibitor = enum { lid, sleep };+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 Request = union(enum) {+ session_for_pid: u32,+ session: []const u8,+ session_field: struct { path: []const u8, field: SessionField },+ list_sessions,+ locked_hint: struct { path: []const u8, locked: bool },+ capability: Action,+ action: struct { kind: Action, interactive: bool, with_flags: bool },+ inhibit: Inhibitor,+ list_inhibitors,+ inspect,+ owner,+};++pub const Target = struct {+ destination: []const u8,+ path: []const u8,+ interface: []const u8,+ member: []const u8,+ signature: []const u8 = "",+ flags: u8 = 0,+};diff --git a/src/session/power.zig b/src/session/power.zigindex 4315867..7291435 100644--- a/src/session/power.zig+++ b/src/session/power.zig@@ -27,21 +27,13 @@ const power_bus = @import("power_bus.zig");const power_requests = @import("power_requests.zig");const log = std.log.scoped(.power);+const login = @import("login_manager.zig");-pub const bus_name = "org.freedesktop.login1";-pub const bus_path = "/org/freedesktop/login1";-pub const bus_interface = "org.freedesktop.login1.Manager";-pub const session_interface = "org.freedesktop.login1.Session";-pub const introspect_interface = "org.freedesktop.DBus.Introspectable";pub const call_timeout_ms: u32 = 5000;/// How long PrepareForSleep waits for the lock to reach the screen. logind/// itself gives up on delay inhibitors after InhibitDelayMaxSec (5 s default).pub const sleep_lock_timeout_ms: i32 = 2000;-/// Enforce active inhibitors even for privileged callers, ensuring we never-/// bypass sleep/shutdown locks taken by package managers, backup tools, etc.-pub const SD_LOGIND_ROOT_CHECK_INHIBITORS: u64 = 1 << 0;-pub const Kind = enum {poweroff,reboot,@@ -54,25 +46,11 @@ pub const Kind = enum {.@"suspend" => i18n.tr("Suspend"),};}- pub fn canMethod(self: Kind) []const u8 {+ pub fn loginAction(self: Kind) login.Action {return switch (self) {- .poweroff => "CanPowerOff",- .reboot => "CanReboot",- .@"suspend" => "CanSuspend",- };- }- pub fn actionMethod(self: Kind) []const u8 {- return switch (self) {- .poweroff => "PowerOff",- .reboot => "Reboot",- .@"suspend" => "Suspend",- };- }- pub fn withFlagsMethod(self: Kind) []const u8 {- return switch (self) {- .poweroff => "PowerOffWithFlags",- .reboot => "RebootWithFlags",- .@"suspend" => "SuspendWithFlags",+ .poweroff => .poweroff,+ .reboot => .reboot,+ .@"suspend" => .@"suspend",};}pub fn inhibitorType(self: Kind) []const u8 {@@ -112,20 +90,7 @@ pub const Request = struct {/// 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 {- std.debug.assert(kind != .@"suspend");- const systemd = std.posix.system.access("/run/systemd/system", std.posix.F_OK) == 0;- buf[0] = if (systemd) "systemctl" else "loginctl";- buf[1] = @tagName(kind);- var len: usize = 2;- if (!ask_password) {- buf[len] = "--no-ask-password";- len += 1;- }- if (no_block and systemd) {- buf[len] = "--no-block";- len += 1;- }- return buf[0..len];+ return login.commandArgv(buf, kind.loginAction(), ask_password, no_block);}/// Only one request may be in flight; a second action while one is@@ -168,7 +133,7 @@ pub const Manager = struct {owner_generation: u64 = 0,owner_changed: bool = false,- pub const Inhibitor = enum { lid, sleep };+ pub const Inhibitor = login.Inhibitor;pub const OwnerRequest = struct { manager: *Manager, generation: u64, inhibitor: Inhibitor = .lid };pub const wantsInhibitor = power_inhibitors.wantsInhibitor;diff --git a/src/session/power_bus.zig b/src/session/power_bus.zigindex a8a0d72..be6b97b 100644--- a/src/session/power_bus.zig+++ b/src/session/power_bus.zig@@ -6,11 +6,8 @@ const dbus = @import("dbus");const wire = dbus.wire;const log = std.log.scoped(.power);const power_mod = @import("power.zig");+const login = @import("login_manager.zig");const Manager = power_mod.Manager;-const bus_name = power_mod.bus_name;-const bus_path = power_mod.bus_path;-const bus_interface = power_mod.bus_interface;-const introspect_interface = power_mod.introspect_interface;const call_timeout_ms = power_mod.call_timeout_ms;const onDisconnect = Manager.onDisconnect;@@ -41,7 +38,7 @@ pub fn onHello(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Connecti_ = result catch |err| {conn.close();const req = self.pending orelse return;- if (req.kind != .@"suspend") return;+ if (login.usesCommand(req.kind.loginAction())) return;self.pending = null;self.failed(req.kind, i18n.tr("Could not reach the system's power service."), err);return;@@ -49,11 +46,8 @@ pub fn onHello(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Connectiself.hello_done = true;self.inspectApi(conn);self.watchSignalOwner(conn) catch return;- _ = conn.addMatch("type='signal',sender='org.freedesktop.DBus',path='/org/freedesktop/DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.login1'", null, null) catch return;- var body: wire.Writer = .{ .allocator = self.allocator };- defer body.deinit();- body.string(bus_name) catch return;- _ = conn.call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetNameOwner", "s", &body, self, onSignalOwner, call_timeout_ms) catch |err| {+ _ = conn.addMatch(login.owner_match, null, null) catch return;+ _ = login.call(conn, .owner, null, self, onSignalOwner, call_timeout_ms) catch |err| {log.warn("could not resolve power signal sender: {}", .{err});};}@@ -71,24 +65,10 @@ pub fn onSignalOwner(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Co}pub fn subscribeSignals(self: *Manager, conn: *dbus.Connection) void {- _ = conn.subscribe(.{- .sender = self.signal_sender orelse return,- .path = bus_path,- .interface = bus_interface,- .member = "PrepareForSleep",- .owner = self,- .callback = onPrepareForSleep,- }, null, null) catch |err| {+ _ = conn.subscribe(login.signal(.sleep, self.signal_sender orelse return, self, onPrepareForSleep), null, null) catch |err| {log.warn("could not subscribe to PrepareForSleep: {}", .{err});};- _ = conn.subscribe(.{- .sender = self.signal_sender orelse return,- .path = bus_path,- .interface = bus_interface,- .member = "PrepareForShutdown",- .owner = self,- .callback = onPrepareForShutdown,- }, null, null) catch |err| {+ _ = conn.subscribe(login.signal(.shutdown, self.signal_sender orelse return, self, onPrepareForShutdown), null, null) catch |err| {log.warn("could not subscribe to PrepareForShutdown: {}", .{err});};}@@ -134,8 +114,7 @@ pub fn onPrepareForShutdown(owner: ?*anyopaque, _: *dbus.Connection, msg: wire.M}pub fn inspectApi(self: *Manager, conn: *dbus.Connection) void {- const body: wire.Writer = .{ .allocator = self.allocator };- _ = conn.call(bus_name, bus_path, introspect_interface, "Introspect", "", &body, self, onIntrospect, call_timeout_ms) catch {+ _ = login.call(conn, .inspect, null, self, onIntrospect, call_timeout_ms) catch {// If Introspect fails immediately, proceed with legacy methodsself.introspect_done = true;self.maybeProbe();@@ -147,14 +126,10 @@ pub fn onIntrospect(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Conconst self: *Manager = @ptrCast(@alignCast(owner orelse return));if (self.closing) return;self.introspect_done = true;- if (result) |*msg| {- if (msg.kind == .method_return) {- var reader = msg.body;- if (reader.string()) |xml| {- self.has_with_flags = std.mem.indexOf(u8, xml, "SuspendWithFlags") != null;- self.has_list_inhibitors = std.mem.indexOf(u8, xml, "ListInhibitors") != null;- } else |_| {}- }+ if (result) |msg| {+ const api = login.readApi(msg);+ self.has_with_flags = api.with_flags;+ self.has_list_inhibitors = api.list_inhibitors;} else |_| {}self.maybeProbe();const req = self.pending orelse return;diff --git a/src/session/power_capabilities.zig b/src/session/power_capabilities.zigindex bb53b86..291a032 100644--- a/src/session/power_capabilities.zig+++ b/src/session/power_capabilities.zig@@ -4,10 +4,8 @@ const i18n = @import("i18n");const dbus = @import("dbus");const wire = dbus.wire;const power_mod = @import("power.zig");+const login = @import("login_manager.zig");const Manager = power_mod.Manager;-const bus_name = power_mod.bus_name;-const bus_path = power_mod.bus_path;-const bus_interface = power_mod.bus_interface;const call_timeout_ms = power_mod.call_timeout_ms;const Kind = power_mod.Kind;const Capability = power_mod.Capability;@@ -68,15 +66,13 @@ pub fn maybeProbe(self: *Manager) void {}pub fn queryProbe(self: *Manager, conn: *dbus.Connection, kind: Kind) void {- var empty: wire.Writer = .{ .allocator = self.allocator };- defer empty.deinit();const Context = struct { mgr: *Manager, kind: Kind };const ctx = self.allocator.create(Context) catch {self.finishProbeReply();return;};ctx.* = .{ .mgr = self, .kind = kind };- _ = conn.call(bus_name, bus_path, bus_interface, kind.canMethod(), "", &empty, ctx, onProbeCapability, call_timeout_ms) catch {+ _ = login.call(conn, .{ .capability = kind.loginAction() }, null, ctx, onProbeCapability, call_timeout_ms) catch {self.allocator.destroy(ctx);self.finishProbeReply();};diff --git a/src/session/power_inhibitors.zig b/src/session/power_inhibitors.zigindex 8557c6d..13a764b 100644--- a/src/session/power_inhibitors.zig+++ b/src/session/power_inhibitors.zig@@ -6,9 +6,8 @@ const wire = dbus.wire;const Lock = @import("lock.zig").Lock;const log = std.log.scoped(.power);const power_mod = @import("power.zig");+const login = @import("login_manager.zig");const Manager = power_mod.Manager;-const bus_path = power_mod.bus_path;-const bus_interface = power_mod.bus_interface;const call_timeout_ms = power_mod.call_timeout_ms;const sleep_lock_timeout_ms = power_mod.sleep_lock_timeout_ms;const Inhibitor = Manager.Inhibitor;@@ -61,18 +60,11 @@ pub fn syncInhibitors(self: *Manager) void {}pub fn acquireInhibitor(self: *Manager, conn: *dbus.Connection, which: Inhibitor) !void {- var body: wire.Writer = .{ .allocator = self.allocator };- defer body.deinit();- 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);const ctx = try self.allocator.create(OwnerRequest);errdefer self.allocator.destroy(ctx);ctx.* = .{ .manager = self, .generation = self.owner_generation, .inhibitor = which };// Address this owner, so a restart cannot give us a stale inhibitor.- _ = try conn.call(self.signal_sender.?, bus_path, bus_interface, "Inhibit", "ssss", &body, ctx, onInhibit, call_timeout_ms);+ _ = try login.call(conn, .{ .inhibit = which }, self.signal_sender.?, ctx, onInhibit, call_timeout_ms);self.inhibitorPending(which).* = true;}diff --git a/src/session/power_requests.zig b/src/session/power_requests.zigindex 868ffc0..5c9a309 100644--- a/src/session/power_requests.zig+++ b/src/session/power_requests.zig@@ -7,12 +7,9 @@ const dbus = @import("dbus");const wire = dbus.wire;const log = std.log.scoped(.power);const power_mod = @import("power.zig");+const login = @import("login_manager.zig");const Manager = power_mod.Manager;-const bus_name = power_mod.bus_name;-const bus_path = power_mod.bus_path;-const bus_interface = power_mod.bus_interface;const call_timeout_ms = power_mod.call_timeout_ms;-const SD_LOGIND_ROOT_CHECK_INHIBITORS = power_mod.SD_LOGIND_ROOT_CHECK_INHIBITORS;const Kind = power_mod.Kind;const Capability = power_mod.Capability;const Request = power_mod.Request;@@ -53,7 +50,7 @@ pub fn beginRequest(self: *Manager, req: Request) void {return;}self.pending = req;- if (req.kind != .@"suspend") {+ if (login.usesCommand(req.kind.loginAction())) {self.startCommand(req);return;}@@ -106,9 +103,8 @@ pub fn commandExited(owner: ?*anyopaque, _: *Child, status: ?u32) void {}pub fn queryCapability(self: *Manager, conn: *dbus.Connection, req: Request) void {- if (req.kind != .@"suspend") return;- const body: wire.Writer = .{ .allocator = self.allocator };- _ = conn.call(bus_name, bus_path, bus_interface, req.kind.canMethod(), "", &body, self, onCapability, call_timeout_ms) catch |err| {+ if (login.usesCommand(req.kind.loginAction())) return;+ _ = login.call(conn, .{ .capability = req.kind.loginAction() }, null, self, onCapability, call_timeout_ms) catch |err| {self.pending = null;self.failed(req.kind, i18n.tr("Could not query logind."), err);};@@ -167,31 +163,10 @@ pub fn onCapability(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Con}pub fn callAction(self: *Manager, conn: *dbus.Connection, req: Request) void {- const msg_flags: u8 = if (req.interactive) wire.flag_allow_interactive_authorization else 0;- var body: wire.Writer = .{ .allocator = self.allocator };- defer body.deinit();-- if (self.has_with_flags) {- body.uint64(SD_LOGIND_ROOT_CHECK_INHIBITORS) catch |err| {- self.pending = null;- self.failed(req.kind, i18n.tr("Could not build the request."), err);- return;- };- _ = conn.callWithFlags(bus_name, bus_path, bus_interface, req.kind.withFlagsMethod(), "t", &body, self, onAction, call_timeout_ms, msg_flags) catch |err| {- self.pending = null;- self.failed(req.kind, i18n.tr("Could not reach logind."), err);- };- } else {- body.boolean(req.interactive) catch |err| {- self.pending = null;- self.failed(req.kind, i18n.tr("Could not build the request."), err);- return;- };- _ = conn.callWithFlags(bus_name, bus_path, bus_interface, req.kind.actionMethod(), "b", &body, self, onAction, call_timeout_ms, msg_flags) catch |err| {- self.pending = null;- self.failed(req.kind, i18n.tr("Could not reach logind."), err);- };- }+ _ = login.call(conn, .{ .action = .{ .kind = req.kind.loginAction(), .interactive = req.interactive, .with_flags = self.has_with_flags } }, null, self, onAction, call_timeout_ms) catch |err| {+ self.pending = null;+ self.failed(req.kind, i18n.tr("Could not reach logind."), err);+ };}pub fn onAction(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {@@ -210,18 +185,17 @@ pub fn onAction(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Connect}const err_name = msg.headers.error_name orelse "";+ const failure = login.actionError(err_name);// If WithFlags is not recognized by this logind instance, fall back to the legacy method.- if (self.has_with_flags and std.mem.eql(u8, err_name, "org.freedesktop.DBus.Error.UnknownMethod")) {+ if (self.has_with_flags and failure == .unknown_method) {log.info("{s}: WithFlags method not found; falling back to legacy method", .{req.kind.label()});self.has_with_flags = false;self.callAction(conn, req);return;}- if (std.mem.eql(u8, err_name, "org.freedesktop.login1.OperationInhibited") or- std.mem.eql(u8, err_name, "org.freedesktop.login1.BlockedByInhibitorLock"))- {+ if (failure == .inhibited) {if (self.has_list_inhibitors) {self.queryInhibitors(conn);return;@@ -234,15 +208,13 @@ pub fn onAction(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Connectself.pending = null;- if (std.mem.eql(u8, err_name, "org.freedesktop.DBus.Error.InteractiveAuthorizationRequired")) {+ if (failure == .authorization_required) {log.warn("{s}: interactive authorization required", .{req.kind.label()});self.report(req.kind, i18n.tr("Interactive authorization required."));return;}- if (std.mem.eql(u8, err_name, "org.freedesktop.DBus.Error.AccessDenied") or- std.mem.eql(u8, err_name, "org.freedesktop.login1.NotEnoughPrivileges"))- {+ if (failure == .denied) {log.warn("{s}: denied by system policy ({s})", .{ req.kind.label(), err_name });self.report(req.kind, i18n.tr("Denied by system policy."));return;@@ -252,8 +224,7 @@ pub fn onAction(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Connect}pub fn queryInhibitors(self: *Manager, conn: *dbus.Connection) void {- const body: wire.Writer = .{ .allocator = self.allocator };- _ = conn.call(bus_name, bus_path, bus_interface, "ListInhibitors", "", &body, self, onListInhibitors, call_timeout_ms) catch {+ _ = login.call(conn, .list_inhibitors, null, self, onListInhibitors, call_timeout_ms) catch {const req = self.pending orelse return;self.pending = null;log.warn("{s}: blocked by an active inhibitor lock", .{req.kind.label()});diff --git a/src/session/power_session.zig b/src/session/power_session.zigindex cae4a67..3db034d 100644--- a/src/session/power_session.zig+++ b/src/session/power_session.zig@@ -6,11 +6,8 @@ const wire = dbus.wire;const Lock = @import("lock.zig").Lock;const log = std.log.scoped(.power);const power_mod = @import("power.zig");+const login = @import("login_manager.zig");const Manager = power_mod.Manager;-const bus_name = power_mod.bus_name;-const bus_path = power_mod.bus_path;-const bus_interface = power_mod.bus_interface;-const session_interface = power_mod.session_interface;const call_timeout_ms = power_mod.call_timeout_ms;const OwnerRequest = Manager.OwnerRequest;@@ -20,13 +17,10 @@ pub fn watchSession(self: *Manager, conn: *dbus.Connection) void {if (self.server.greeter_mode or self.session_path != null or self.session_pending) return;const id = self.server.environ.getPosix("REDIWM_LOGIN_SESSION") orelse return;if (id.len == 0) return;- var body: wire.Writer = .{ .allocator = self.allocator };- defer body.deinit();- body.string(id) catch return;const sender = self.signal_sender orelse return;const ctx = self.allocator.create(OwnerRequest) catch return;ctx.* = .{ .manager = self, .generation = self.owner_generation };- _ = conn.call(sender, bus_path, bus_interface, "GetSession", "s", &body, ctx, onSession, call_timeout_ms) catch |err| {+ _ = login.call(conn, .{ .session = id }, sender, ctx, onSession, call_timeout_ms) catch |err| {self.allocator.destroy(ctx);log.warn("could not look up the logind session: {}", .{err});return;@@ -41,25 +35,18 @@ pub fn onSession(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Connecif (ctx.generation != self.owner_generation) return;self.session_pending = false;if (self.closing) return;- var msg = result catch |err| {+ const msg = result catch |err| {log.warn("could not look up the logind session: {}", .{err});return;};- if (msg.kind != .method_return or !std.mem.eql(u8, msg.headers.signature, "o")) {+ const path = login.readSessionPath(msg) catch {log.warn("logind has no session for this login: {s}", .{msg.headers.error_name orelse "invalid reply"});return;- }- const path = msg.body.objectPath() catch return;+ };self.session_path = self.allocator.dupe(u8, path) catch return;// Every session's Lock comes from the same sender; ours is picked out// by path in the handler, so the registration owns no strings.- _ = conn.subscribe(.{- .sender = self.signal_sender orelse return,- .interface = session_interface,- .member = "Lock",- .owner = self,- .callback = onSessionLock,- }, null, null) catch |err| log.warn("could not follow logind lock requests: {}", .{err});+ _ = conn.subscribe(login.signal(.lock, self.signal_sender orelse return, self, onSessionLock), null, null) catch |err| log.warn("could not follow logind lock requests: {}", .{err});self.syncLockedHint();}@@ -84,10 +71,7 @@ pub fn syncLockedHint(self: *Manager) void {const conn = self.conn orelse return;const sender = self.signal_sender orelse return;if (conn.closed or self.locked_hint == self.locked) return;- var body: wire.Writer = .{ .allocator = self.allocator };- defer body.deinit();- body.boolean(self.locked) catch return;- _ = conn.call(sender, path, session_interface, "SetLockedHint", "b", &body, null, null, call_timeout_ms) catch |err| {+ _ = login.call(conn, .{ .locked_hint = .{ .path = path, .locked = self.locked } }, sender, null, null, call_timeout_ms) catch |err| {log.warn("could not update the session's LockedHint: {}", .{err});return;};@@ -103,10 +87,7 @@ pub fn onDisconnect(owner: ?*anyopaque) void {pub fn onOwnerChanged(owner: ?*anyopaque, conn: *dbus.Connection, msg: wire.Message) anyerror!void {const self: *Manager = @ptrCast(@alignCast(owner orelse return));if (self.closing) return;- var body = msg.body;- if (!std.mem.eql(u8, try body.string(), bus_name)) return;- _ = try body.string();- const next = try body.string();+ const next = try login.changedOwner(msg) orelse return;self.owner_changed = true;conn.unregisterSignalsByOwner(self);try self.watchSignalOwner(conn);@@ -119,12 +100,5 @@ pub fn onOwnerChanged(owner: ?*anyopaque, conn: *dbus.Connection, msg: wire.Mess}pub fn watchSignalOwner(self: *Manager, conn: *dbus.Connection) !void {- try conn.registerSignal(.{- .sender = "org.freedesktop.DBus",- .path = "/org/freedesktop/DBus",- .interface = "org.freedesktop.DBus",- .member = "NameOwnerChanged",- .owner = self,- .callback = onOwnerChanged,- });+ try conn.registerSignal(login.signal(.owner_changed, null, self, onOwnerChanged));}diff --git a/src/ui_tests.zig b/src/ui_tests.zigindex 54ef21b..2bb0158 100644--- a/src/ui_tests.zig+++ b/src/ui_tests.zig@@ -1,6 +1,7 @@// Compositor integration/unit-test root. Shared modules have separate test// targets in build.zig; their roots cannot import compositor code.test {+ _ = @import("session/login_manager.zig");_ = @import("effects/ribbon.zig");_ = @import("effects/move_heading.zig");_ = @import("effects/minimize_mesh.zig");diff --git a/tests/session_bus.py b/tests/session_bus.pyindex 878084d..01bf512 100644--- a/tests/session_bus.py+++ b/tests/session_bus.py@@ -151,16 +151,25 @@ def check_publication(fixture):assert fixture.environment == ORIGINAL, (fixture.environment, log)-def check_foreign_desktop(fixture):- fixture.properties['Desktop'] = GLib.Variant('s', 'GNOME')- try:- report, log = fixture.run_session()- finally:- fixture.properties['Desktop'] = GLib.Variant('s', 'rediwm')- assert report['acked']- assert 'REDIWM_LOGIN_SESSION' not in report['env'], 'host desktop accepted as RediWM login'- assert 'global activation disabled' in log, log- assert fixture.environment == ORIGINAL+def check_login_identity(fixture):+ # Each assertion is independently required before exporting a trusted login.+ for field, value in (+ ('Desktop', GLib.Variant('s', 'GNOME')),+ ('User', GLib.Variant('(uo)', (os.getuid() + 1, '/user/other'))),+ ('Type', GLib.Variant('s', 'x11')),+ ('Class', GLib.Variant('s', 'greeter')),+ ('Remote', GLib.Variant('b', True)),+ ):+ original = fixture.properties[field]+ fixture.properties[field] = value+ try:+ report, log = fixture.run_session()+ finally:+ fixture.properties[field] = original+ assert report['acked']+ assert 'REDIWM_LOGIN_SESSION' not in report['env'], f'untrusted {field} accepted as RediWM login'+ assert 'global activation disabled' in log, log+ assert fixture.environment == ORIGINALdef check_contention(fixture):@@ -191,7 +200,7 @@ def main():fixture = Fixture(os.environ['DBUS_SESSION_BUS_ADDRESS'])try:check_publication(fixture)- check_foreign_desktop(fixture)+ check_login_identity(fixture)check_contention(fixture)check_refusal(fixture)print('PASS: verified logind identity, graphical contention, publication while running, restoration and refusal')