Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

Report greeter readiness only once the login UI is usable

oxydizer90faaeda28f0
diff --git a/build/session.zig b/build/session.zig
index eb6df68..dbf7adb 100644
--- a/build/session.zig
+++ b/build/session.zig
@@ -80,6 +80,7 @@ pub fn add(ctx: Context) Session {
dm.root_module.linkSystemLibrary("pam", .{});
dm.root_module.addCSourceFile(.{ .file = b.path("src/dm/pam.c"), .flags = &.{"-std=c11"} });
b.installArtifact(dm);
+ b.step("rediwm-dm", "Build the display manager").dependOn(&dm.step);
const accounts_helper = b.addExecutable(.{
.name = "rediwm-accounts-helper",
diff --git a/docs/greeter-readiness.md b/docs/greeter-readiness.md
new file mode 100644
index 0000000..7c9cc99
--- /dev/null
+++ b/docs/greeter-readiness.md
@@ -0,0 +1,58 @@
+# Operational greeter readiness
+
+The built-in greeter reports `ready` over its inherited DM connection only
+after a frame containing its login UI has actually been presented on an
+available output after its black startup veil has cleared, its session is active, its input backend has started, and
+usable keyboard and pointer devices are registered. It also requires a login
+account, a session choice and a connected DM. A submitted frame, backend start,
+headless output, timeout or protocol-injected virtual keyboard cannot satisfy
+this gate.
+
+The DM acknowledges this with a distinct `ready` response, preserving any PAM
+conversation already in progress. The main DM process then sends `READY=1` and
+an operational status to `NOTIFY_SOCKET`, supporting pathname and abstract
+Unix sockets. The greeter never receives that socket. Failed notification does
+not publish success. Redinit's main-PID notification check remains intact.
+
+The default seat policy is `keyboard-pointer`. For an intentionally
+keyboard-only installation, an administrator can set the greeter command in
+`/etc/rediwm/dm.conf` to:
+
+```ini
+greeter_command = /usr/bin/env REDIWM_GREETER_READY_INPUT=keyboard /usr/bin/rediwm --greeter
+```
+
+Use the actual installed binary path. Unknown policy values retain the
+conservative keyboard-and-pointer requirement. Keep the policy fixed in every
+before/after comparison. A touch-only greeter is not supported by this policy:
+the current login field requires a keyboard, and this change adds no onscreen
+keyboard. Devices arriving late re-evaluate readiness without polling.
+
+For redinit's built-in interactive greeter, install the matching
+`redinit/services/gentoo/rediwm-dm.d/readiness.toml` drop-in beside the imported
+service and recompile the graph. Stage 8b must still provide logind, the active
+seat, tmpfiles and required ZFS mounts; this drop-in does not implement those
+dependencies. Autologin and custom greeters retain the existing simple-service
+contract: do not install this drop-in for them. They do not satisfy the
+operational-greeter measurement. The default systemd service is unchanged.
+
+Validation commands after building Debug binaries:
+
+```sh
+zig build test-dm
+python3 tests/dm.py
+python3 tests/greeter.py
+python3 tests/readiness_input.py
+```
+
+`readiness_input.py` runs private compositors and a fake DM, not PAM. It verifies
+that a displayed headless greeter without input stays unready, then uses actual
+nested Wayland keyboard and pointer events to select a session, enter a dummy
+password and submit it. The DM tests separately exercise PAM with private test
+stacks and verify notification sender credentials. Neither substitutes for a
+physical/VM libinput, logind and real-PAM login acceptance check.
+
+Only compare performance after the same readiness gate and input actions pass
+on both builds. Capture the manager's notification timestamp, first presented
+frame, and response to keyboard/pointer actions. Logging and diagnostic builds
+can alter timings. No speed improvement is established by these tests.
diff --git a/src/Output.zig b/src/Output.zig
index 44d7b31..94bad2c 100644
--- a/src/Output.zig
+++ b/src/Output.zig
@@ -60,6 +60,9 @@ const Output = @This();
const log = std.log.scoped(.output);
lock_view: @import("session/lock.zig").View,
+greeter_commit_seq: ?u32 = null,
+greeter_presented: bool = false,
+greeter_unveiled: bool = true,
server: *Server,
wlr_output: *wlr.Output,
wallpaper: ?*sn.Buffer = null,
diff --git a/src/dm/daemon.zig b/src/dm/daemon.zig
index 961773b..30b6fbb 100644
--- a/src/dm/daemon.zig
+++ b/src/dm/daemon.zig
@@ -324,6 +324,10 @@ pub const Daemon = struct {
};
switch (action) {
.none => {},
+ .greeter_ready => @import("notify.zig").greeterReady() catch |err| {
+ log.err("cannot publish greeter readiness: {}", .{err});
+ self.dropGreeter("readiness notification failed");
+ },
.spawn_login => self.beginLogin(parsed.request.login),
.kill_worker => self.killLogin(),
.handoff => self.beginHandoff(),
@@ -447,7 +451,7 @@ pub const Daemon = struct {
};
if (payload.len == 0) return;
const text = payload[1..];
- switch (@as(proto.Report, @enumFromInt(payload[0]))) {
+ switch (@as(proto.Report, @fromBackingInt(@intCast(payload[0])))) {
.auth_ok => self.sendStart(worker, self.config.greeter_command, "", "") catch |err|
log.err("cannot start the greeter: {}", .{err}),
.denied, .failed => log.err("cannot open the greeter account '{s}': {s}", .{ self.config.greeter_user, text }),
@@ -468,7 +472,7 @@ pub const Daemon = struct {
};
if (payload.len == 0) return;
const text = payload[1..];
- switch (@as(proto.Report, @enumFromInt(payload[0]))) {
+ switch (@as(proto.Report, @fromBackingInt(@intCast(payload[0])))) {
.session_started => {
self.session_running = true;
self.session_started_at = monotonicMs();
@@ -476,7 +480,7 @@ pub const Daemon = struct {
.session_failed => log.err("cannot open the session: {s}", .{text}),
.session_ended => log.info("session ended (wait status {s})", .{text}),
else => if (self.user_autologin) {
- if (payload[0] == @intFromEnum(proto.Report.auth_ok)) {
+ if (payload[0] == @backingInt(proto.Report.auth_ok)) {
const session = self.autologin_session.?;
self.sendStart(worker, session.exec, session.id, session.desktops) catch |err|
log.err("cannot start the autologin session: {}", .{err});
diff --git a/src/dm/notify.zig b/src/dm/notify.zig
new file mode 100644
index 0000000..44d4634
--- /dev/null
+++ b/src/dm/notify.zig
@@ -0,0 +1,26 @@
+//! Only the main DM sends readiness; the unprivileged greeter uses its
+//! inherited private IPC connection and never receives the notify socket.
+const std = @import("std");
+const linux = std.os.linux;
+const c = @import("c");
+
+pub fn greeterReady() !void {
+ const raw = c.getenv("NOTIFY_SOCKET") orelse return;
+ const path = std.mem.span(raw);
+ var address: linux.sockaddr.un = .{ .family = linux.AF.UNIX, .path = @splat(0) };
+ if (path.len < 2 or path.len >= address.path.len or
+ (path[0] != '/' and path[0] != '@')) return error.InvalidNotifySocket;
+ @memcpy(address.path[0..path.len], path);
+ if (path[0] == '@') address.path[0] = 0;
+ const fd_result = linux.socket(linux.AF.UNIX, linux.SOCK.DGRAM | linux.SOCK.CLOEXEC | linux.SOCK.NONBLOCK, 0);
+ if (linux.errno(fd_result) != .SUCCESS) return error.NotifySocketFailed;
+ const fd: i32 = @intCast(fd_result);
+ defer _ = linux.close(fd);
+ const message = "READY=1\nSTATUS=Greeter presented; seat input and login interface operational";
+ const len: u32 = @intCast(@offsetOf(linux.sockaddr.un, "path") + path.len + @intFromBool(path[0] != '@'));
+ const result = linux.sendto(fd, message.ptr, message.len, linux.MSG.NOSIGNAL, @ptrCast(&address), len);
+ if (linux.errno(result) != .SUCCESS or result != message.len) return error.NotifySendFailed;
+ var ts: linux.timespec = undefined;
+ if (linux.errno(linux.clock_gettime(.BOOTTIME, &ts)) == .SUCCESS)
+ std.log.info("greeter-operational boottime={d}.{d:0>9}", .{ ts.sec, ts.nsec });
+}
diff --git a/src/dm/state.zig b/src/dm/state.zig
index 4d7140a..ca6866d 100644
--- a/src/dm/state.zig
+++ b/src/dm/state.zig
@@ -13,6 +13,7 @@ pub const Phase = enum { idle, authenticating, prompting, authenticated, startin
pub const Action = enum {
none,
+ greeter_ready,
/// Validate the login's user and start a worker for it.
spawn_login,
/// End the current login worker; nothing it says later is relayed.
@@ -59,6 +60,7 @@ pub const Relay = struct {
worker_fd: c_int = -1,
/// Set by a successful `start`, until `reset`.
session: ?ws.Session = null,
+ ready_reported: bool = false,
pub fn init(gpa: std.mem.Allocator) Relay {
return .{ .arena = .init(gpa) };
@@ -72,11 +74,18 @@ pub const Relay = struct {
pub fn reset(self: *Relay) void {
self.phase = .idle;
self.session = null;
+ self.ready_reported = false;
_ = self.arena.reset(.retain_capacity);
}
pub fn handleGreeterRequest(self: *Relay, req: dm_ipc.Request, io: std.Io, search_dirs: []const []const u8) !Action {
switch (req) {
+ .ready => {
+ if (self.phase == .starting or self.ready_reported) return .drop_greeter;
+ try self.reply(.ready);
+ self.ready_reported = true;
+ return .greeter_ready;
+ },
.login => {
if (self.phase != .idle) return .drop_greeter;
self.phase = .authenticating;
@@ -125,10 +134,10 @@ pub const Relay = struct {
if (payload.len == 0) return error.InvalidReport;
const text = payload[1..];
var clean: [max_text]u8 = undefined;
- switch (@as(proto.Report, @enumFromInt(payload[0]))) {
+ switch (@as(proto.Report, @fromBackingInt(@intCast(payload[0])))) {
.question => {
if (self.phase != .authenticating or text.len == 0) return error.UnexpectedReport;
- const kind: dm_ipc.MessageKind = switch (@as(proto.QuestionKind, @enumFromInt(text[0]))) {
+ const kind: dm_ipc.MessageKind = switch (@as(proto.QuestionKind, @fromBackingInt(@intCast(text[0])))) {
.secret => .secret,
.visible => .visible,
.info => .info,
diff --git a/src/dm/tests.zig b/src/dm/tests.zig
index 3b3a5b1..562fa55 100644
--- a/src/dm/tests.zig
+++ b/src/dm/tests.zig
@@ -65,7 +65,7 @@ const Harness = struct {
fn report(self: *Harness, tag: proto.Report, text: []const u8) !void {
var frame: [256]u8 = undefined;
- frame[0] = @intFromEnum(tag);
+ frame[0] = @backingInt(tag);
@memcpy(frame[1..][0..text.len], text);
try self.relay.handleWorkerMessage(frame[0 .. text.len + 1]);
}
@@ -227,3 +227,16 @@ test "autologin decision table" {
try std.testing.expectEqual(state.AutologinDecision.skip_bad_session, state.checkAutologin(io, "/nonexistent/marker", "valid_user", "nonexistent_session", &.{}, .{}, mockValidator));
try std.testing.expectEqual(state.AutologinDecision.skip_marker_exists, state.checkAutologin(io, "/", "valid_user", "session", &.{}, .{}, mockValidator));
}
+
+test "readiness acknowledgement is separate from an active PAM conversation" {
+ var h: Harness = undefined;
+ try h.init();
+ defer h.deinit();
+ try std.testing.expectEqual(state.Action.spawn_login, try h.request(.{ .login = "alice" }));
+ try std.testing.expectEqual(state.Action.greeter_ready, try h.request(.ready));
+ try std.testing.expectEqual(state.Phase.authenticating, h.relay.phase);
+ var response = try h.greeterGot();
+ defer response.deinit();
+ try std.testing.expect(response.response == .ready);
+ try std.testing.expectEqual(state.Action.drop_greeter, try h.request(.ready));
+}
diff --git a/src/input/devices.zig b/src/input/devices.zig
index 0f7eefa..3d7874b 100644
--- a/src/input/devices.zig
+++ b/src/input/devices.zig
@@ -60,6 +60,7 @@ pub fn addDevice(input: *Input, device: *wlr.InputDevice) void {
.@"switch" => input.lid.addDevice(device),
}
input.updateCapabilities();
+ @import("../session/greeter_ready.zig").check(input.server);
}
pub fn requestSetCursor(
diff --git a/src/output/frame.zig b/src/output/frame.zig
index e543c0d..e43bc2a 100644
--- a/src/output/frame.zig
+++ b/src/output/frame.zig
@@ -326,10 +326,15 @@ pub fn runFrame(output: *Output) void {
output.startup_commit_seq = output.wlr_output.commit_seq +% 1;
output.startup_presented = false;
}
+ if (output.server.greeter_mode and output.lock_view.content_ready and output.greeter_unveiled)
+ output.greeter_commit_seq = output.wlr_output.commit_seq +% 1;
output.startup_committing = true;
committed = output.commitFrameState(&state);
output.startup_committing = false;
- if (!committed) output.startup_commit_seq = null;
+ if (!committed) {
+ output.startup_commit_seq = null;
+ output.greeter_commit_seq = null;
+ }
} else {
committed = false;
}
@@ -438,6 +443,10 @@ pub fn handleRequestState(
pub fn handlePresent(listener: *wl.Listener(*wlr.Output.event.Present), event: *wlr.Output.event.Present) void {
const output: *Output = @fieldParentPtr("present", listener);
+ if (event.presented and output.greeter_commit_seq == event.commit_seq) {
+ output.greeter_presented = true;
+ @import("../session/greeter_ready.zig").check(output.server);
+ }
if (@import("../startup.zig").marks.first_visible_ns != 0 or !event.presented) return;
if (output.startup_commit_seq == null or event.commit_seq != output.startup_commit_seq.?) return;
output.startup_presented = true;
diff --git a/src/reveal.zig b/src/reveal.zig
index daeedb4..8a60125 100644
--- a/src/reveal.zig
+++ b/src/reveal.zig
@@ -149,7 +149,15 @@ pub fn tick(self: *Reveal, output: *Output, now_ms: i64) bool {
fn setVeil(self: *Reveal, output: *Output, alpha: f32) void {
const server = self.server orelse return;
const scene_output = server.scene_outputs.get(output.wlr_output) orelse return;
- if (!server.output_renderer.setVeil(scene_output, alpha)) {
+ // A presented black/fading frame is not an operational greeter.
+ if (alpha != 0) {
+ output.greeter_unveiled = false;
+ output.greeter_presented = false;
+ output.greeter_commit_seq = null;
+ }
+ if (server.output_renderer.setVeil(scene_output, alpha)) {
+ output.greeter_unveiled = alpha == 0;
+ } else {
std.log.scoped(.reveal).warn("could not veil {s}", .{output.wlr_output.name});
}
}
diff --git a/src/server/session.zig b/src/server/session.zig
index 6621da5..87d5d2c 100644
--- a/src/server/session.zig
+++ b/src/server/session.zig
@@ -84,6 +84,7 @@ pub fn handleSessionActive(listener: *wl.Listener(void)) void {
if (session.active) {
log.info("session became active (VT switch back)", .{});
server.reactivateSession();
+ @import("../session/greeter_ready.zig").check(server);
server.startup_tasks.onSessionActive();
} else {
log.info("session became inactive (VT switch away)", .{});
diff --git a/src/session/dm_ipc.zig b/src/session/dm_ipc.zig
index 89fa2eb..692cda2 100644
--- a/src/session/dm_ipc.zig
+++ b/src/session/dm_ipc.zig
@@ -11,6 +11,8 @@ pub const max_frame = 64 * 1024;
pub const request_capacity = 8 * 1024;
pub const Request = union(enum) {
+ /// Presented greeter with usable seat input and login model.
+ ready,
login: []const u8,
/// null answers info/error messages, which carry no response.
answer: ?[]const u8,
@@ -22,6 +24,7 @@ pub const MessageKind = enum { visible, secret, info, @"error" };
pub const Response = union(enum) {
ok,
+ ready,
question: struct { kind: MessageKind, text: []const u8 },
/// Wrong credentials; the conversation is over.
denied: []const u8,
@@ -51,6 +54,8 @@ pub fn parseResponse(allocator: std.mem.Allocator, payload: []const u8) !ParsedR
const v = wire.value;
const response: Response = if (std.mem.eql(u8, v.type, "ok"))
.ok
+ else if (std.mem.eql(u8, v.type, "ready"))
+ .ready
else if (std.mem.eql(u8, v.type, "question"))
.{ .question = .{
.kind = std.meta.stringToEnum(MessageKind, v.kind orelse "") orelse return error.InvalidResponse,
@@ -72,6 +77,7 @@ pub fn encodeRequest(out: []u8, request: Request) ![]u8 {
if (out.len < 4) return error.NoSpaceLeft;
var w: std.Io.Writer = .fixed(out[4..]);
switch (request) {
+ .ready => try std.json.Stringify.value(.{ .type = "ready" }, .{}, &w),
.login => |user| try std.json.Stringify.value(.{ .type = "login", .user = user }, .{}, &w),
.answer => |ans| try std.json.Stringify.value(.{ .type = "answer", .response = ans }, .{}, &w),
.start => |session| try std.json.Stringify.value(.{ .type = "start", .session = session }, .{}, &w),
@@ -104,7 +110,9 @@ pub fn parseRequest(allocator: std.mem.Allocator, payload: []const u8) !ParsedRe
var wire = try std.json.parseFromSlice(RequestWire, allocator, payload, .{ .ignore_unknown_fields = true, .allocate = .alloc_always });
errdefer wire.deinit();
const v = wire.value;
- const request: Request = if (std.mem.eql(u8, v.type, "login"))
+ const request: Request = if (std.mem.eql(u8, v.type, "ready"))
+ .ready
+ else if (std.mem.eql(u8, v.type, "login"))
.{ .login = v.user orelse return error.InvalidRequest }
else if (std.mem.eql(u8, v.type, "answer"))
.{ .answer = v.response }
@@ -122,6 +130,7 @@ pub fn encodeResponse(out: []u8, response: Response) ![]u8 {
if (out.len < 4) return error.NoSpaceLeft;
var w: std.Io.Writer = .fixed(out[4..]);
switch (response) {
+ .ready => try std.json.Stringify.value(.{ .type = "ready" }, .{}, &w),
.ok => try std.json.Stringify.value(.{ .type = "ok" }, .{}, &w),
.question => |q| try std.json.Stringify.value(.{ .type = "question", .kind = @tagName(q.kind), .text = q.text }, .{}, &w),
.denied => |text| try std.json.Stringify.value(.{ .type = "denied", .text = text }, .{}, &w),
diff --git a/src/session/greeter.zig b/src/session/greeter.zig
index 7d47194..97d774d 100644
--- a/src/session/greeter.zig
+++ b/src/session/greeter.zig
@@ -54,6 +54,9 @@ pub const Greeter = struct {
client: ?dm_ipc.Client = null,
source: ?*wl.EventSource = null,
phase: Phase = .idle,
+ ready_sent: bool = false,
+ ready_pending: bool = false,
+ ready_pointer_required: bool = true,
/// The first answer, typed before the daemon asks for it.
pending: [512]u8 = @splat(0),
pending_len: ?usize = null,
@@ -67,6 +70,10 @@ pub const Greeter = struct {
self.* = .{ .arena = .init(gpa), .io = io, .loop = loop };
_ = c.mlock(&self.pending, self.pending.len);
const a = self.arena.allocator();
+ // An explicit administrator choice for keyboard-only seats. Unknown
+ // values keep the conservative desktop keyboard + pointer policy.
+ if (environ.getPosix("REDIWM_GREETER_READY_INPUT")) |policy|
+ self.ready_pointer_required = !std.mem.eql(u8, policy, "keyboard");
if (environ.getPosix("REDIWM_GREETER_FD")) |fd_str| {
if (std.fmt.parseInt(c_int, fd_str, 10)) |fd| {
// Nothing the greeter might spawn inherits the daemon socket.
@@ -184,6 +191,15 @@ pub const Greeter = struct {
self.clearPending();
}
+ /// Called only after presentation and seat readiness, never on a timer.
+ pub fn reportReady(self: *Greeter) void {
+ if (self.ready_sent or self.phase == .starting or self.phase == .done or self.client == null or
+ self.selectedUser() == null or self.selectedSession() == null) return;
+ self.send(.ready) catch return self.lost();
+ self.ready_sent = true;
+ self.ready_pending = true;
+ }
+
fn send(self: *Greeter, request: dm_ipc.Request) !void {
try (if (self.client) |*client| client else return error.NoService).send(request);
}
@@ -229,12 +245,18 @@ pub const Greeter = struct {
}
fn handle(self: *Greeter, response: dm_ipc.Response) ?Event {
+ if (response == .ready) {
+ if (!self.ready_pending) return self.fail("unsolicited readiness acknowledgement");
+ self.ready_pending = false;
+ return null;
+ }
switch (self.phase) {
.cancelling => {
self.phase = .idle;
return null;
},
.starting => return switch (response) {
+ .ready => unreachable,
.ok => blk: {
self.phase = .done;
self.remember();
@@ -244,6 +266,7 @@ pub const Greeter = struct {
.question => self.fail("unexpected question"),
},
.authenticating => switch (response) {
+ .ready => unreachable,
.ok => {
self.clearPending();
return self.start();
diff --git a/src/session/greeter_ready.zig b/src/session/greeter_ready.zig
new file mode 100644
index 0000000..6065af0
--- /dev/null
+++ b/src/session/greeter_ready.zig
@@ -0,0 +1,41 @@
+//! Event-driven operational readiness. No timeouts or synthetic input can
+//! satisfy this gate. Backend start and a submitted frame are insufficient.
+const Server = @import("../Server.zig");
+
+pub fn check(server: *Server) void {
+ if (!server.greeter_mode) return;
+ var visible = false;
+ var outputs = server.outputs.iterator(.forward);
+ while (outputs.next()) |output| {
+ if (output.isAvailable() and !output.power_off and output.greeter_presented and output.greeter_unveiled and output.lock_view.content_ready) {
+ visible = true;
+ break;
+ }
+ }
+ if (!visible) return;
+ if (@import("../startup.zig").marks.input_ready_ns == 0) return;
+ if (server.session) |session| if (!session.active) return;
+ const lock = server.locker orelse return;
+ const greeter = lock.greeter orelse return;
+ var keyboard_ready = false;
+ var keyboards = server.input.keyboards.iterator(.forward);
+ while (keyboards.next()) |keyboard| {
+ if (!keyboard.synthetic and !@import("../input/text_input.zig").isVirtual(keyboard.device)) {
+ keyboard_ready = keyboard.device.toKeyboard().keymap != null;
+ if (keyboard_ready) break;
+ }
+ }
+ if (!keyboard_ready) return;
+ if (greeter.ready_pointer_required) {
+ var pointer_ready = false;
+ var pointers = server.input.pointers.iterator(.forward);
+ while (pointers.next()) |pointer| {
+ if (!@import("../input/devices.zig").blockedVirtual(&server.input, pointer.device)) {
+ pointer_ready = true;
+ break;
+ }
+ }
+ if (!pointer_ready) return;
+ }
+ greeter.reportReady();
+}
diff --git a/src/session/lock_view.zig b/src/session/lock_view.zig
index 7b1fea1..de53f36 100644
--- a/src/session/lock_view.zig
+++ b/src/session/lock_view.zig
@@ -83,6 +83,7 @@ pub const View = struct {
controls_node: *sn.Buffer,
controls_key: ?ControlsKey = null,
revision: u64 = 0,
+ content_ready: bool = false,
width: i32 = 0,
height: i32 = 0,
scale: f32 = 0,
@@ -122,6 +123,7 @@ pub const View = struct {
self.caret.hide();
self.hideControls();
self.revision = 0;
+ self.content_ready = false;
Buffer.drainPool();
}
@@ -177,6 +179,8 @@ pub const View = struct {
if (self.revision == lock.revision and self.width == b.width and self.height == b.height and self.scale == scale) return self.caret.frame(now);
if (b.width <= 0 or b.height <= 0) return false;
// Drop stale pixels before a failed resize allocation.
+ self.content_ready = false;
+ out.greeter_presented = false;
self.ui_node.setBuffer(null);
if (lock.greeter_wallpaper orelse out.server.wallpaper) |image| {
self.wallpaper.setBuffer(&image.base);
@@ -197,6 +201,7 @@ pub const View = struct {
} else null, lock.caret_edit_ms);
self.ui_node.setBuffer(&buf.base);
self.ui_node.setDestSize(b.width, b.height);
+ self.content_ready = true;
self.revision = lock.revision;
self.width = b.width;
self.height = b.height;
diff --git a/src/startup_tasks.zig b/src/startup_tasks.zig
index 0e46582..c0add4e 100644
--- a/src/startup_tasks.zig
+++ b/src/startup_tasks.zig
@@ -29,6 +29,7 @@ pub fn start(self: *Tasks, server: *Server) !void {
if (self.input_pending) server.input.holdCursor() else startup.markInputReady();
if (server.greeter_mode) {
self.complete = true;
+ @import("session/greeter_ready.zig").check(server);
return;
}
self.timer = try server.wl_server.getEventLoop().addTimer(*Tasks, tick, self);
diff --git a/tests/dm.py b/tests/dm.py
index 208c1e3..636c51c 100644
--- a/tests/dm.py
+++ b/tests/dm.py
@@ -13,6 +13,8 @@ import json
import os
from pathlib import Path
import signal
+import socket
+import struct
import subprocess
import sys
import tempfile
@@ -105,8 +107,9 @@ PAM_STACKS = {
class Fixture:
"""A temp dir with PAM stacks, installed sessions and a running daemon."""
- def __init__(self, name, greeter_body=None, greeter_command=None, conf_extra=""):
+ def __init__(self, name, greeter_body=None, greeter_command=None, conf_extra="", env=None):
self.name = name
+ self.env = {**os.environ, **(env or {})}
self.dir = tempfile.TemporaryDirectory(prefix=f"rediwm-dm-{name}-")
self.tmp = tmp = Path(self.dir.name)
pam = tmp / "pam.d"
@@ -151,6 +154,7 @@ date +%s%N > {tmp}/session-ended.txt
[str(DM_BIN), "--test", "--conf", str(self.tmp / "dm.conf"), "--confdir", str(self.tmp / "pam.d"),
"--data-dir", str(self.tmp / "share"), "--marker", str(self.tmp / "autologin-marker")],
stdout=log, stderr=log,
+ env=self.env,
preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_IGN),
)
return self
@@ -223,6 +227,8 @@ finish()
f.path("session-hold").write_text("hold")
f.greeter_result()
f.wait_file("session-started.txt")
+ # Shell redirection creates the file before date writes its timestamp.
+ f.wait(lambda: bool(f.path("session-started.txt").read_text().strip()), "session-started timestamp")
assert int(f.path("greeter-exit-time.txt").read_text()) <= int(f.path("session-started.txt").read_text())
env = dict(line.split("=", 1) for line in f.path("session-env.txt").read_text().splitlines() if "=" in line)
for key, want in {"XDG_SESSION_TYPE": "wayland", "XDG_SESSION_CLASS": "user", "XDG_SESSION_DESKTOP": "rediwm",
@@ -257,6 +263,109 @@ finish()
f.wait(lambda: f.greeter_starts() == 2, "a replacement greeter")
+def test_readiness_notify_uses_daemon_credentials():
+ # The manager must hear nothing merely because a greeter was spawned.
+ # Exercise both sd_notify Unix address forms and then a real PAM exchange.
+ body = """
+if "NOTIFY_SOCKET" in os.environ:
+ finish("notify socket leaked to the greeter")
+open(TMP + "/awaiting-ready", "w").close()
+while not os.path.exists(TMP + "/release-ready"):
+ __import__("time").sleep(0.01)
+send({"type": "ready"})
+expect("ready")
+login("alice", PASSWORD)
+expect("ok")
+send({"type": "cancel"})
+expect("ok")
+finish()
+"""
+ for abstract in (False, True):
+ f = Fixture("notify-abstract" if abstract else "notify-path", body)
+ address = ("\0" + f.tmp.name) if abstract else str(f.path("notify.sock"))
+ with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as notify:
+ notify.setsockopt(socket.SOL_SOCKET, socket.SO_PASSCRED, 1)
+ notify.bind(address)
+ f.env["NOTIFY_SOCKET"] = "@" + address[1:] if abstract else address
+ with f:
+ f.wait_file("awaiting-ready")
+ notify.settimeout(0.2)
+ try:
+ premature = notify.recv(4096)
+ except socket.timeout:
+ pass
+ else:
+ raise AssertionError(f"readiness before greeter's request: {premature!r}")
+ f.path("release-ready").touch()
+ notify.settimeout(10)
+ message, ancillary, flags, _ = notify.recvmsg(4096, socket.CMSG_SPACE(12))
+ assert not flags & (socket.MSG_TRUNC | socket.MSG_CTRUNC), flags
+ fields = dict(line.split("=", 1) for line in message.decode().splitlines())
+ assert fields.get("READY") == "1", fields
+ assert fields.get("STATUS"), fields
+ creds = [struct.unpack("3i", value) for level, kind, value in ancillary
+ if level == socket.SOL_SOCKET and kind == socket.SCM_CREDENTIALS]
+ assert creds == [(f.proc.pid, os.getuid(), os.getgid())], creds
+ f.greeter_result()
+ assert "greeter-operational boottime=" in f.log_path.read_text()
+ notify.settimeout(0.2)
+ try:
+ duplicate = notify.recv(4096)
+ except socket.timeout:
+ pass
+ else:
+ raise AssertionError(f"unexpected repeated notification: {duplicate!r}")
+
+
+def test_readiness_during_authentication_preserves_conversation():
+ body = """
+send({"type": "login", "user": "alice"})
+expect("question", kind="secret")
+send({"type": "ready"})
+expect("ready")
+send({"type": "answer", "response": PASSWORD})
+expect("ok")
+send({"type": "cancel"})
+expect("ok")
+finish()
+"""
+ f = Fixture("ready-during-auth", body)
+ with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as notify:
+ notify.bind(str(f.path("notify.sock")))
+ f.env["NOTIFY_SOCKET"] = str(f.path("notify.sock"))
+ with f:
+ f.greeter_result()
+ notify.settimeout(2)
+ assert b"READY=1\n" in notify.recv(4096)
+ assert "request out of order" not in f.log_path.read_text()
+
+
+def test_duplicate_readiness_replaces_greeter():
+ body = """
+send({"type": "ready"})
+expect("ready")
+open(TMP + "/greeter-done", "w").close()
+send({"type": "ready"})
+quiet()
+"""
+ f = Fixture("ready-duplicate", body)
+ with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as notify:
+ notify.bind(str(f.path("notify.sock")))
+ f.env["NOTIFY_SOCKET"] = str(f.path("notify.sock"))
+ with f:
+ f.wait(lambda: f.greeter_starts() == 2, "replacement after duplicate readiness")
+ assert "request out of order" in f.log_path.read_text()
+ notify.settimeout(2)
+ assert b"READY=1\n" in notify.recv(4096)
+ notify.settimeout(0.2)
+ try:
+ message = notify.recv(4096)
+ except socket.timeout:
+ pass
+ else:
+ raise AssertionError(f"duplicate readiness was published: {message!r}")
+
+
def test_out_of_order_request_replaces_greeter():
body = """
send({"type": "start", "session": "rediwm"})
@@ -377,6 +486,9 @@ def test_real_greeter_connects():
TESTS = [
+ test_readiness_notify_uses_daemon_credentials,
+ test_readiness_during_authentication_preserves_conversation,
+ test_duplicate_readiness_replaces_greeter,
test_login_session_and_logout,
test_cancel_mid_prompt,
test_out_of_order_request_replaces_greeter,
diff --git a/tests/readiness_input.py b/tests/readiness_input.py
new file mode 100644
index 0000000..7b2fff1
--- /dev/null
+++ b/tests/readiness_input.py
@@ -0,0 +1,225 @@
+#!/usr/bin/env python3
+"""Exercise real greeter input through a private parent Wayland compositor.
+
+Parent IPC injects keyboard/pointer events into the child's wl_seat. The
+greeter itself has no IPC or test hook; a socketpair stands in for the DM and
+checks the selected session and typed dummy secret. No PAM or host bus is used.
+"""
+import json
+import os
+from pathlib import Path
+import pwd
+import select
+import socket
+import struct
+import subprocess
+import tempfile
+import time
+
+from ipc_client import IPCClient, spawn_compositor, stop_process
+
+
+ROOT = Path(__file__).resolve().parents[1]
+BINARY = Path(os.environ.get("REDIWM_READINESS_BINARY", ROOT / "zig-out/bin/rediwm"))
+PARENT_BINARY = Path(os.environ.get("REDIWM_PARENT_BINARY", BINARY))
+PASSWORD = "readiness-only-42"
+
+
+def wait_for(predicate, description, timeout=20):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ value = predicate()
+ if value:
+ return value
+ time.sleep(0.05)
+ raise AssertionError(f"timed out waiting for {description}")
+
+
+class Peer:
+ def __init__(self, sock):
+ self.sock = sock
+
+ def read(self, size):
+ data = b""
+ while len(data) < size:
+ chunk = self.sock.recv(size - len(data))
+ assert chunk, "greeter disconnected"
+ data += chunk
+ return data
+
+ def recv(self, timeout=20):
+ self.sock.settimeout(timeout)
+ size = struct.unpack("=I", self.read(4))[0]
+ assert size <= 8192, size
+ return json.loads(self.read(size))
+
+ def send(self, message):
+ payload = json.dumps(message).encode()
+ self.sock.sendall(struct.pack("=I", len(payload)) + payload)
+
+ def quiet(self, timeout=0.4):
+ assert not select.select([self.sock], [], [], timeout)[0], "unsolicited greeter request"
+
+
+def environment(directory, share):
+ env = dict(os.environ)
+ for key in list(env):
+ if key.startswith("REDIWM_") or key in ("WAYLAND_DISPLAY", "DISPLAY", "GREETD_SOCK", "NOTIFY_SOCKET"):
+ env.pop(key, None)
+ for name in ("home", "state", "cache", "config", "data", "runtime"):
+ (directory / name).mkdir(mode=0o700, parents=True, exist_ok=True)
+ env.update(
+ HOME=str(directory / "home"),
+ XDG_RUNTIME_DIR=str(directory / "runtime"),
+ XDG_STATE_HOME=str(directory / "state"),
+ XDG_CACHE_HOME=str(directory / "cache"),
+ XDG_CONFIG_HOME=str(directory / "config"),
+ XDG_DATA_HOME=str(directory / "data"),
+ XDG_DATA_DIRS=str(share),
+ DBUS_SYSTEM_BUS_ADDRESS="unix:path=/nonexistent-rediwm-readiness-system-bus",
+ DBUS_SESSION_BUS_ADDRESS="unix:path=/nonexistent-rediwm-readiness-session-bus",
+ PULSE_SERVER="unix:/nonexistent-rediwm-readiness-audio",
+ WLR_RENDERER="gles2", WLR_RENDERER_ALLOW_SOFTWARE="1",
+ REDIWM_SCALE="1", REDIWM_STARTUP_TIMING="1",
+ REDIWM_GREETER_READY_INPUT="keyboard-pointer",
+ )
+ # Fix selection without depending on another login's saved state.
+ user = pwd.getpwuid(os.getuid()).pw_name
+ state = directory / "state/rediwm"
+ state.mkdir()
+ (state / "greeter.state").write_text(f"user={user}\nsession.{user}=alpha\n")
+ return env, user
+
+
+def launch(directory, env):
+ daemon, child = socket.socketpair()
+ env = dict(env, REDIWM_GREETER_FD=str(child.fileno()))
+ log_path = directory / "greeter.log"
+ with log_path.open("w") as log:
+ process = subprocess.Popen([str(BINARY), "--greeter"], env=env,
+ stdout=log, stderr=log, pass_fds=(child.fileno(),))
+ child.close()
+ return process, Peer(daemon), log_path
+
+
+def assert_no_greeter_ipc(directory):
+ assert not list((directory / "runtime").glob("rediwm-*.sock")), "greeter exposed IPC"
+
+
+def no_input_case(root, share):
+ directory = root / "no-input"
+ env, _ = environment(directory, share)
+ env.update(WLR_BACKENDS="headless", WLR_HEADLESS_OUTPUTS="1")
+ process, peer, log = launch(directory, env)
+ try:
+ wait_for(lambda: "first_presented" in log.read_text(errors="replace"), "headless presentation")
+ assert process.poll() is None, log.read_text()
+ # Presentation alone cannot satisfy readiness, even after event-loop
+ # turns. This is a negative invariant, not a boot-latency measurement.
+ peer.quiet(1)
+ assert_no_greeter_ipc(directory)
+ print("PASS: presented greeter without input devices does not report ready")
+ finally:
+ stop_process(process)
+ peer.sock.close()
+
+
+def nested_case(root, share):
+ parent_dir = root / "parent"
+ parent_dir.mkdir()
+ parent_env, _ = environment(parent_dir, share)
+ parent_env.update(REDIWM_IPC_AUTOMATION="1", REDIWM_DESKTOP_BUILTINS="0")
+ parent, parent_log = spawn_compositor(
+ parent_dir, binary=PARENT_BINARY,
+ config_content='[compositor]\nxwayland = false\n',
+ env_extra=parent_env,
+ )
+ child = peer = None
+ try:
+ with IPCClient(parent_dir / "runtime") as ipc:
+ display = wait_for(lambda: next((p for p in (parent_dir / "runtime").glob("wayland-*")
+ if not p.name.endswith(".lock")), None), "parent Wayland socket")
+ directory = root / "nested"
+ env, user = environment(directory, share)
+ env.update(WLR_BACKENDS="wayland", WAYLAND_DISPLAY=str(display), WAYLAND_DEBUG="client")
+ env.pop("WLR_HEADLESS_OUTPUTS", None)
+ child, peer, log = launch(directory, env)
+ window = wait_for(lambda: next(iter(ipc.get_windows()), None), "nested greeter window")
+ ipc.fullscreen(window["id"])
+ ipc.focus_window(window["id"])
+ ipc.wait_for("window_geometry_settled", window_id=window["id"])
+ ipc.wait_for_frame()
+ message = peer.recv()
+ assert message == {"type": "ready"}, message
+ output = log.read_text(errors="replace")
+ assert "first_presented" in output, "ready preceded presentation"
+ assert "reveal_done" in output, "ready preceded the visible greeter (black/fading veil)"
+ assert "wl_keyboard" in output and "wl_pointer" in output, "nested seat missing input"
+ peer.send({"type": "ready"})
+ peer.quiet()
+ assert_no_greeter_ipc(directory)
+
+ # Coordinates are inside the visible session selector, measured
+ # in the nested output's logical pixels. The resulting 'start'
+ # request must name beta, proving the pointer changed selection.
+ box = ipc.get_window_debug(window["id"])["client_box"]
+ width, height = box["width"], box["height"]
+ scale = min(1, width / 600, height / 900) * 0.85
+ # Enter the nested surface, then move within it so the child
+ # receives wl_pointer.motion in addition to wl_pointer.enter.
+ ipc.move_cursor(box["x"] + width // 2, box["y"] + height // 2)
+ ipc.wait_for_frame()
+ ipc.click_at(round(box["x"] + 120 * scale), round(box["y"] + height - 60 * scale))
+ ipc.wait_for_frame()
+ # Typing returns focus to the password field. Events traverse the
+ # parent's virtual device, Wayland wl_keyboard, and greeter field.
+ ipc.type_text(PASSWORD)
+ ipc.key_down_up(28) # evdev KEY_ENTER
+ message = peer.recv()
+ assert message == {"type": "login", "user": user}, message
+ peer.send({"type": "question", "kind": "secret", "text": "Fixture password:"})
+ message = peer.recv()
+ assert message == {"type": "answer", "response": PASSWORD}, message
+ peer.send({"type": "ok"})
+ message = peer.recv()
+ assert message == {"type": "start", "session": "beta"}, message
+ output = log.read_text(errors="replace")
+ assert ".key(" in output and ".button(" in output, "input did not traverse Wayland"
+ assert "panic:" not in output, output
+ peer.quiet()
+ print("PASS: ready greeter consumes pointer selection and keyboard secret through Wayland")
+ # Do not acknowledge start: no real session or PAM is involved.
+ finally:
+ if child is not None:
+ stop_process(child)
+ if peer is not None:
+ peer.sock.close()
+ stop_process(parent)
+ parent_log.close()
+
+
+def main():
+ if os.getuid() == 0:
+ raise SystemExit("Run as an ordinary user; this test never needs root.")
+ if not BINARY.is_file() or not PARENT_BINARY.is_file():
+ raise SystemExit("Build rediwm first, or set REDIWM_READINESS_BINARY/REDIWM_PARENT_BINARY.")
+ os.umask(0o077)
+ with tempfile.TemporaryDirectory(prefix="rediwm-readiness-input-") as temporary:
+ root = Path(temporary)
+ share = root / "share"
+ sessions = share / "wayland-sessions"
+ sessions.mkdir(parents=True)
+ for name in ("alpha", "beta"):
+ (sessions / (name + ".desktop")).write_text(
+ f"[Desktop Entry]\nName={name.title()}\nExec=/bin/true\nType=Application\n")
+ try:
+ no_input_case(root, share)
+ nested_case(root, share)
+ except BaseException:
+ for path in root.rglob("*.log"):
+ print(f"--- {path.relative_to(root)} ---\n{path.read_text(errors='replace')[-16000:]}")
+ raise
+
+
+if __name__ == "__main__":
+ main()