RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Printing: move libcups out of the compositor into rediwm-cups
oxydizer0ddc238f5963
diff --git a/build.zig b/build.zigindex 24afba6..78e4365 100644--- a/build.zig+++ b/build.zig@@ -184,8 +184,6 @@ pub fn build(b: *std.Build) void {compositor.root_module.addImport("c_libinput", c_headers.libinput);compositor.root_module.addImport("c_png", c_headers.png);compositor.root_module.linkSystemLibrary("wayland-server", .{});- compositor.root_module.linkSystemLibrary("cups", .{});- compositor.root_module.addCSourceFile(.{ .file = b.path("src/printing/direct.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-deprecated-declarations" } });compositor.root_module.linkSystemLibrary("xkbcommon", .{});compositor.root_module.linkSystemLibrary("pixman-1", .{});compositor.root_module.linkSystemLibrary("freetype2", .{});@@ -286,6 +284,7 @@ pub fn build(b: *std.Build) void {const zig_tests = tests.addZig(ctx, session);@import("build/keys.zig").add(ctx, zig_tests.test_step, &.{ compositor.root_module, zig_tests.ui_tests_module });@import("build/firewall.zig").add(ctx, zig_tests.test_step, &.{ compositor.root_module, zig_tests.ui_tests_module });+ @import("build/printing.zig").add(ctx);const ui_tests_module = zig_tests.ui_tests_module;const ipc_tests_module = zig_tests.ipc_tests_module;const files_tests = zig_tests.files_tests;diff --git a/build/printing.zig b/build/printing.zignew file mode 100644index 0000000..4c19d35--- /dev/null+++ b/build/printing.zig@@ -0,0 +1,16 @@+//! rediwm-cups: the only program linked against libcups. The compositor reads+//! printers over native IPP and, for administration without cups-pk-helper,+//! starts this helper, so libcups and the TLS and crypto libraries behind it+//! stay out of every session's address space (src/printing/AGENTS.md).+const std = @import("std");+const Context = @import("context.zig").Context;+pub fn add(ctx: Context) void {+ const b = ctx.b;+ const helper = b.addExecutable(.{ .name = "rediwm-cups", .root_module = b.createModule(.{ .root_source_file = b.path("src/cups_main.zig"), .target = ctx.target, .optimize = ctx.optimize, .link_libc = true }), .use_llvm = ctx.use_llvm, .use_lld = ctx.use_llvm });+ helper.root_module.addImport("platform", ctx.platform_mod);+ helper.root_module.addImport("c", ctx.c.libc);+ helper.root_module.linkSystemLibrary("cups", .{});+ helper.root_module.addCSourceFile(.{ .file = b.path("src/printing/direct.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-deprecated-declarations" } });+ b.installArtifact(helper);+ b.step("cups-helper", "Build the CUPS administration helper").dependOn(&helper.step);+}diff --git a/build/tests.zig b/build/tests.zigindex f38925e..d4e09f5 100644--- a/build/tests.zig+++ b/build/tests.zig@@ -62,8 +62,6 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {ui_tests_module.addImport("wlroots", wlroots);ui_tests_module.addImport("pixman", pixman);ui_tests_module.linkSystemLibrary("wayland-server", .{});- ui_tests_module.linkSystemLibrary("cups", .{});- ui_tests_module.addCSourceFile(.{ .file = b.path("src/printing/direct.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-deprecated-declarations" } });ui_tests_module.linkSystemLibrary("xkbcommon", .{});ui_tests_module.linkSystemLibrary("pixman-1", .{});ui_tests_module.linkSystemLibrary("freetype2", .{});@@ -140,8 +138,6 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {printing_tests.root_module.addImport("install_paths", ctx.layout.options);printing_tests.root_module.addImport("wayland", wayland);printing_tests.root_module.linkSystemLibrary("wayland-server", .{});- printing_tests.root_module.linkSystemLibrary("cups", .{});- printing_tests.root_module.addCSourceFile(.{ .file = b.path("src/printing/direct.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-deprecated-declarations" } });const run_printing_tests = b.addRunArtifact(printing_tests);test_step.dependOn(&run_printing_tests.step);// NetworkManager parsing that needs no compositor: addresses, profile read/write.diff --git a/docs/agent-notes/map.md b/docs/agent-notes/map.mdindex cdfd531..7c17d1c 100644--- a/docs/agent-notes/map.md+++ b/docs/agent-notes/map.md@@ -33,6 +33,7 @@ or a lowercase directory named after a TitleCase host (`Dock.zig` → `dock/`).| `rediwm-firewall-helper` | `src/firewall_main.zig` | root firewall helper (`firewall_helper/`, `firewall/AGENTS.md`); Settings uses `control_center/sections/firewall_client.zig` || `rediwm-theme` | `src/theme_main.zig` | theme archive helper (`theme_helper/`) || `rediwm-keys` | `src/keys_main.zig` | unprivileged SSH metadata and operations (`keys/`, `keys_helper.zig`); Settings uses `keys/client.zig` |+| `rediwm-cups` | `src/cups_main.zig` | the only libcups user: unprivileged CUPS administration when cups-pk-helper is absent (`printing/direct.c`, protocol in `printing/direct_protocol.zig`, client `printing/direct.zig`; `build/printing.zig`) |`build.zig` holds the options, the shared modules, the compositor and`rediwm-msg`; `build/` the rest: `apps.zig` (the programs above), `data.zig`diff --git a/docs/wiki/Home.md b/docs/wiki/Home.mdindex 5d3bddf..8bcd50c 100644--- a/docs/wiki/Home.md+++ b/docs/wiki/Home.md@@ -33,6 +33,7 @@ no waybar/greeter/launcher/notification daemon to wire up.| `rediwm-share-picker` | screen sharing picker || `rediwm-accounts-helper` | root helper for account management, runs under `pkexec` || `rediwm-keys` | unprivileged helper that reads `~/.ssh` for Settings → Keys & Certificates |+| `rediwm-cups` | unprivileged helper for printer administration through libcups (only when cups-pk-helper is not installed); keeps libcups and gnutls out of the compositor |## Other docs in the repodiff --git a/src/control_center/sections/printers.zig b/src/control_center/sections/printers.zigindex 7d6a8c4..756ceb6 100644--- a/src/control_center/sections/printers.zig+++ b/src/control_center/sections/printers.zig@@ -312,7 +312,7 @@ fn tree(self: *Section, cc: *panel.ControlCenter, a: A) !W {var content: std.ArrayList(W) = .empty;const state = client.current;if (state) |snapshot| if (snapshot.admin_local) {- if (self.administration == null) self.administration = admin.Manager.create(cc.server.wl_server.getEventLoop(), cc.server.environ, cc, adminChanged) catch null;+ if (self.administration == null) self.administration = admin.Manager.create(cc.server.io, cc.server.wl_server.getEventLoop(), cc.server.environ, cc, adminChanged) catch null;if (!self.listener_attempted) {self.listener_attempted = true;self.listener = notifier.Listener.create(gpa, cc.server.io, cc.server.environ, cc.server.wl_server.getEventLoop(), cc, cupsChanged) catch null;diff --git a/src/cups_main.zig b/src/cups_main.zignew file mode 100644index 0000000..46b1080--- /dev/null+++ b/src/cups_main.zig@@ -0,0 +1,184 @@+//! rediwm-cups: printer administration through libcups, in a process of its own+//! so the compositor never maps libcups and the TLS and crypto libraries it+//! pulls in (gnutls, nettle, p11-kit, ...). The Printers page starts it on the+//! first administration request when no cups-pk-helper is present and kills it+//! with the page. It runs as the desktop user, never as root, talks only on its+//! stdin socketpair (`printing/direct_protocol.zig`) and sleeps in poll(2) when+//! idle: the C worker (`printing/direct.c`) does the CUPS I/O on its own threads+//! and wakes this loop through its eventfd.+const std = @import("std");+const c = @import("c");+const platform = @import("platform");+const proto = @import("printing/direct_protocol.zig");+const secure = @import("network/secure_allocator.zig").allocator;++const Native = opaque {};+extern fn rediwm_cups_create() ?*Native;+extern fn rediwm_cups_destroy(*Native) void;+extern fn rediwm_cups_fd(*Native) c_int;+extern fn rediwm_cups_submit(*Native, [*:0]const u8, c_int, [*]const [*:0]const u8, c_int) c_int;+extern fn rediwm_cups_state(*Native) c_int;+extern fn rediwm_cups_result(*Native) c_int;+extern fn rediwm_cups_device(*Native, c_int, c_int) ?[*:0]const u8;+extern fn rediwm_cups_credentials(*Native, [*:0]const u8, [*]const u8, c_ulong) void;+extern fn rediwm_cups_cancel(*Native) void;+extern fn rediwm_cups_finish(*Native) void;++const socket = 0;++/// Fewest arguments each method `direct.c` implements reads. A method not in+/// this list is refused: `execute` would send an unrelated IPP request for it.+fn minimumArguments(method: []const u8) ?usize {+ const table = [_]struct { []const u8, usize }{+ .{ "DevicesGet", 0 },+ .{ "PrinterAdd", 5 },+ .{ "PrinterDelete", 1 },+ .{ "PrinterSetEnabled", 2 },+ .{ "PrinterSetAcceptJobs", 2 },+ .{ "PrinterSetDefault", 1 },+ .{ "PrinterSetInfo", 2 },+ .{ "PrinterSetDevice", 2 },+ .{ "PrinterRename", 2 },+ .{ "PrinterAddOption", 3 },+ .{ "PrinterAddOptionDefault", 3 },+ .{ "PrinterDeleteOptionDefault", 2 },+ };+ for (table) |entry| if (std.mem.eql(u8, entry[0], method)) return entry[1];+ return null;+}++var frame: [proto.max_command]u8 = undefined;++const Chooser = struct {+ secret: []u8,+ /// A password is received straight into the locked page, every other+ /// payload into the plain buffer.+ pub fn destination(self: Chooser, kind: u8, len: usize) ?[]u8 {+ if (kind == @intFromEnum(proto.Command.credentials)) return if (len <= proto.max_credentials) self.secret else null;+ return if (len <= frame.len) &frame else null;+ }+};++const Session = struct {+ worker: *Native,+ discovery: bool = false,+ /// The last state sent to the compositor; 0 after it sent something that+ /// moves the worker on, so the next password prompt is reported again.+ reported: c_int = 2,++ fn command(self: *Session, kind: u8, payload: []u8) !void {+ switch (@as(proto.Command, @enumFromInt(kind))) {+ .submit => try self.submit(payload),+ .credentials => try self.credentials(payload),+ .cancel => rediwm_cups_cancel(self.worker),+ .finish => rediwm_cups_finish(self.worker),+ _ => return error.UnknownCommand,+ }+ }++ fn submit(self: *Session, payload: []const u8) !void {+ if (payload.len < 2) return error.BadFrame;+ var list: [proto.max_args + 1][:0]const u8 = undefined;+ const count = proto.strings(payload[1..], &list) orelse return error.BadFrame;+ if (count == 0) return error.BadFrame;+ const method = list[0];+ const needed = minimumArguments(method) orelse return error.UnknownMethod;+ if (count - 1 < needed) return error.BadFrame;+ var args: [proto.max_args][*:0]const u8 = undefined;+ for (list[1..count], 0..) |value, i| args[i] = value.ptr;+ self.discovery = std.mem.eql(u8, method, "DevicesGet");+ if (rediwm_cups_submit(self.worker, method.ptr, @intCast(count - 1), &args, @intFromBool(payload[0] != 0)) != 0) return error.Busy;+ self.reported = 0;+ }++ /// `payload` is the locked page; it is wiped as soon as the worker has its copy.+ fn credentials(self: *Session, payload: []u8) !void {+ defer std.crypto.secureZero(u8, payload);+ const nul = std.mem.indexOfScalar(u8, payload, 0) orelse return error.BadFrame;+ const password = payload[nul + 1 ..];+ if (nul == 0 or nul > proto.max_user or password.len > proto.max_password) return error.BadFrame;+ if (std.mem.indexOfScalar(u8, password, 0) != null) return error.BadFrame;+ rediwm_cups_credentials(self.worker, @ptrCast(payload.ptr), password.ptr, password.len);+ self.reported = 0;+ }++ /// The worker changed state (its eventfd fired): tell the compositor about+ /// a password prompt or the end of the request, once each.+ fn changed(self: *Session) !void {+ var counter: u64 = 0;+ _ = c.read(rediwm_cups_fd(self.worker), &counter, @sizeOf(u64));+ const state = rediwm_cups_state(self.worker);+ if (state == 0 or state == self.reported) return;+ self.reported = state;+ if (state == 1) return report(1, 0);+ const result = rediwm_cups_result(self.worker);+ if (self.discovery and result == 0) try self.devices();+ try report(2, result);+ }++ fn devices(self: *Session) !void {+ var bytes: [proto.max_report]u8 = undefined;+ for (0..proto.max_devices) |i| {+ if (rediwm_cups_device(self.worker, @intCast(i), 0) == null) break;+ var used: usize = 0;+ for (0..5) |field| {+ const value = std.mem.span(rediwm_cups_device(self.worker, @intCast(i), @intCast(field)) orelse return error.BadDevice);+ if (used + value.len + 1 > bytes.len) return error.BadDevice;+ @memcpy(bytes[used..][0..value.len], value);+ bytes[used + value.len] = 0;+ used += value.len + 1;+ }+ if (!proto.send(socket, @intFromEnum(proto.Report.device), &.{bytes[0..used]})) return error.PeerGone;+ }+ }+};++fn report(state: u8, result: c_int) !void {+ var body: [5]u8 = undefined;+ body[0] = state;+ std.mem.writeInt(i32, body[1..5], result, .little);+ if (!proto.send(socket, @intFromEnum(proto.Report.state), &.{&body})) return error.PeerGone;+}++fn run() !void {+ try platform.process.denyDumps();+ try platform.process.noNewPrivileges();+ platform.process.ignoreBrokenPipes();+ platform.process.dieWithParent(.KILL);+ if (std.c.geteuid() == 0) return error.RunAsDesktopUser;+ const secret = try secure.alloc(u8, proto.max_credentials);+ defer secure.free(secret);+ const worker = rediwm_cups_create() orelse return error.WorkerFailed;+ defer rediwm_cups_destroy(worker);+ var session: Session = .{ .worker = worker };+ var receiver: proto.Receiver = .{};+ const chooser: Chooser = .{ .secret = secret };+ var fds = [2]c.struct_pollfd{+ .{ .fd = socket, .events = c.POLLIN, .revents = 0 },+ .{ .fd = rediwm_cups_fd(worker), .events = c.POLLIN, .revents = 0 },+ };+ while (true) {+ const ready = c.poll(&fds, fds.len, -1);+ if (ready < 0) {+ if (std.posix.errno(ready) == .INTR) continue;+ return error.PollFailed;+ }+ if (fds[1].revents != 0) try session.changed();+ if (fds[0].revents == 0) continue;+ // Level-triggered: whatever is left after one frame is read next time round.+ switch (receiver.read(socket, chooser)) {+ .again => {},+ .frame => try session.command(receiver.kind, receiver.payload()),+ // The compositor went away: its page is gone, so is this request.+ .closed => return,+ .invalid => return error.BadFrame,+ }+ }+}++pub fn main() void {+ run() catch |err| {+ std.debug.print("rediwm-cups: {s}\n", .{@errorName(err)});+ std.process.exit(1);+ };+}diff --git a/src/printing/AGENTS.md b/src/printing/AGENTS.mdindex 7d8b6fe..c6a6862 100644--- a/src/printing/AGENTS.md+++ b/src/printing/AGENTS.md@@ -4,15 +4,35 @@authentication are explicit unsupported states; never fall back to adifferent server. Configuration read failures are not missing files.Both administration backends target the canonical local socket, never a- custom Unix or remote endpoint. `admin.zig` selects the helper when present,- otherwise `direct.zig`/`direct.c` use libcups in a page-owned worker. Never- retry an uncertain mutation through another backend. The native worker alone- uses libcups (including its thread-local authentication state); UI credentials- use locked storage and are wiped on submit/cancel/hide. A chain may reuse its- CUPS connection, but completion closes it and wipes the worker password.- The deadline watcher owns a duplicated socket descriptor, never a borrowed- descriptor that libcups could close/reuse during authentication. It has no- timed wakeups while idle or waiting for user input.+ custom Unix or remote endpoint. `admin.zig` selects cups-pk-helper when+ present, otherwise `direct.zig` runs the `rediwm-cups` helper+ (`src/cups_main.zig` + `direct.c`, frames in `direct_protocol.zig`). Never+ retry an uncertain mutation through another backend.+* **The compositor never links libcups.** libcups drags in gnutls, nettle,+ p11-kit and friends, which would be mapped in every session for a page used+ rarely; only `rediwm-cups` links it (`build/printing.zig`), and the compositor+ stays free of it (check `ldd`; `tests/printers_direct.py` checks the mappings).+ The helper starts on the first administration request (a read-only page never+ starts it), dies with `Worker.destroy` (SIGKILL: instant, even mid-prompt) and+ with the compositor (EOF on its socket, PDEATHSIG). A helper that dies fails+ the request in flight as uncertain, never retried; the next request starts a+ fresh one. It runs as the desktop user, non-dumpable, never as root, and+ refuses methods and argument counts `direct.c` does not implement.+* Inside the helper, `direct.c`'s worker alone uses libcups (including its+ thread-local authentication state). UI credentials use locked storage and are+ wiped on submit/cancel/hide; they travel from that storage into a `sendmsg`+ iovec (no copy) and are received into a locked page, never the plain frame+ buffer (`Receiver` picks the destination by frame kind, reading exactly the+ bytes a frame lacks). A chain may reuse its CUPS connection, but completion+ closes it and wipes the worker password. The deadline watcher owns a+ duplicated socket descriptor, never a borrowed descriptor that libcups could+ close/reuse during authentication. The helper has no timed wakeups while idle+ or waiting for user input: its loop sleeps in `poll(-1)`. Keep `direct.c`'s C+ API stable: `tests/printers_direct.py` drives it directly through ctypes.+* `Worker` callbacks may free the worker: the frame reader handles one frame per+ event-loop call and touches nothing after the callback. The helper's state+ frames are checked against the request state (a prompt only while a request+ runs); anything else drops the connection.* IPP and HTTP replies are untrusted and bounded. Socket operations share anabsolute deadline and include the worker cancellation fd in every wait.* `cups.Snapshot` owns an arena. Parser helpers allocate into that arena;diff --git a/src/printing/admin.zig b/src/printing/admin.zigindex 714b975..e0a0e07 100644--- a/src/printing/admin.zig+++ b/src/printing/admin.zig@@ -1,6 +1,6 @@//! Page-owned asynchronous printer administration. Use the installed helper-//! for polkit authorization, or a local libcups worker for CUPS authentication.-//! RediWM never becomes root or runs a shell. Destruction closes outstanding requests before releasing their owner.+//! for polkit authorization, or `rediwm-cups` (libcups in a process of its own)+//! for CUPS authentication. RediWM never becomes root or runs a shell. Destruction closes outstanding requests before releasing their owner.const std = @import("std");const dbus = @import("dbus");const wl = @import("wayland").server.wl;@@ -56,6 +56,7 @@ pub const Action = union(enum) {const Stage = enum { idle, discovery, mutation, add, rename, device, enable_added, accept_added, ppd_option, clear_ppd_override, clear_ppd_alias, start_service };pub const Manager = struct {+ io: std.Io,owner: *anyopaque,changed: *const fn (*anyopaque) void,bus: ?*dbus.Connection = null,@@ -83,10 +84,10 @@ pub const Manager = struct {/// finishes. At most 64 bounded values; never borrowed from page widgets.option_body: wire.Writer = .{ .allocator = a },- pub fn create(loop: *wl.EventLoop, env: std.process.Environ, owner: *anyopaque, changed: *const fn (*anyopaque) void) !*Manager {+ pub fn create(io: std.Io, loop: *wl.EventLoop, env: std.process.Environ, owner: *anyopaque, changed: *const fn (*anyopaque) void) !*Manager {const self = try a.create(Manager);errdefer a.destroy(self);- self.* = .{ .owner = owner, .changed = changed, .loop = loop, .status = @import("i18n").tr("Checking printer administration…") };+ self.* = .{ .io = io, .owner = owner, .changed = changed, .loop = loop, .status = @import("i18n").tr("Checking printer administration…") };self.bus = dbus.Connection.openSystem(a, loop, env) catch {self.useDirect();return self;@@ -209,7 +210,7 @@ pub const Manager = struct {self.unavailable(@import("i18n").tr("Could not start CUPS administration."));return;};- self.worker = direct.Worker.create(loop, self, directReady) catch {+ self.worker = direct.Worker.create(self.io, loop, self, directReady) catch {self.unavailable(@import("i18n").tr("Could not start CUPS administration."));return;};@@ -804,7 +805,7 @@ test "discovery owns complete identities and rejects unsafe backend addresses" {try writer.string("device-id:0");try writer.string(long_id);try writer.endArray(dict);- var self: Manager = .{ .owner = undefined, .changed = undefined };+ var self: Manager = .{ .io = std.testing.io, .owner = undefined, .changed = undefined };defer self.arena.deinit();var reader: wire.Reader = .{ .bytes = writer.bytes.items };try self.readDevices(&reader);@@ -825,7 +826,7 @@ test "failed PPD setter after legacy cleanup reports partial changes and refresh}};var recorder: Recorder = .{};- var manager: Manager = .{ .owner = &recorder, .changed = Recorder.changed, .stage = .ppd_option, .busy = true };+ var manager: Manager = .{ .io = std.testing.io, .owner = &recorder, .changed = Recorder.changed, .stage = .ppd_option, .busy = true };defer manager.arena.deinit();manager.fail("Fixture denied setter");try std.testing.expectEqual(@as(u64, 1), manager.generation);@@ -868,7 +869,7 @@ test "native PPD cleanup aliases are explicit and retain the original setter key}test "a discovered add must use the complete URI in this manager's discovery catalog" {- var manager: Manager = .{ .owner = undefined, .changed = undefined, .busy = false, .availability = .available };+ var manager: Manager = .{ .io = std.testing.io, .owner = undefined, .changed = undefined, .busy = false, .availability = .available };defer manager.arena.deinit();manager.devices = &.{.{ .uri = "usb://Acme/Label?serial=complete" }};try std.testing.expectError(error.UntrustedDevice, manager.request(.{ .add = .{ .name = "Label", .uri = "usb://Acme/Label?serial=different", .ppd = "raw", .discovered = true } }));diff --git a/src/printing/direct.zig b/src/printing/direct.zigindex 99bc172..9bf0489 100644--- a/src/printing/direct.zig+++ b/src/printing/direct.zig@@ -1,104 +1,290 @@-//! Adapter for the private native libcups worker. The validated helper-shaped-//! arguments are an internal command format, not a D-Bus dependency.+//! Client of `rediwm-cups`, the helper process that holds libcups, so the+//! compositor itself never maps libcups, gnutls or the other crypto libraries.+//! The validated helper-shaped arguments are an internal command format, not a+//! D-Bus dependency. The helper is started by the first request and killed by+//! `destroy`; if it dies, the request in flight fails and the next one starts a+//! fresh one. Frames are in `direct_protocol.zig`.const std = @import("std");const wire = @import("dbus").wire;const wl = @import("wayland").server.wl;+const c = @import("c");+const platform = @import("platform");+const proto = @import("direct_protocol.zig");const a = std.heap.c_allocator;-const Native = opaque {};-extern fn rediwm_cups_create() ?*Native;-extern fn rediwm_cups_destroy(*Native) void;-extern fn rediwm_cups_fd(*Native) c_int;-extern fn rediwm_cups_submit(*Native, [*:0]const u8, c_int, [*]const [*:0]const u8, c_int) c_int;-extern fn rediwm_cups_state(*Native) c_int;-extern fn rediwm_cups_result(*Native) c_int;-extern fn rediwm_cups_device(*Native, c_int, c_int) ?[*:0]const u8;-extern fn rediwm_cups_credentials(*Native, [*:0]const u8, [*]const u8, c_ulong) void;-extern fn rediwm_cups_cancel(*Native) void;-extern fn rediwm_cups_finish(*Native) void;-extern "c" fn read(c_int, *anyopaque, usize) isize;-pub const Worker = struct {- native: *Native,+pub const helper_name = "rediwm-cups";++/// The helper's pidfd on the event loop: it reaps the process whenever it ends+/// and, while the worker still owns it, reports an unexpected death.+const Proc = struct {+ pid: platform.child.Pid,+ handle: platform.child.Handle,source: *wl.EventSource,+ worker: ?*Worker,++ fn watch(loop: *wl.EventLoop, pid: platform.child.Pid, worker: *Worker) !*Proc {+ const self = try a.create(Proc);+ errdefer a.destroy(self);+ const handle = try platform.child.Handle.open(pid);+ errdefer handle.close();+ self.* = .{ .pid = pid, .handle = handle, .source = undefined, .worker = worker };+ self.source = try loop.addFd(*Proc, handle.fd, .{ .readable = true }, exited, self);+ return self;+ }++ /// Ends the process; the watch stays until the exit is collected, and+ /// nobody is told about it.+ fn kill(self: *Proc) void {+ self.worker = null;+ self.handle.signal(.KILL) catch {};+ }++ fn exited(_: c_int, _: wl.EventMask, self: *Proc) c_int {+ _ = platform.child.reap(self.pid);+ const worker = self.worker;+ self.source.remove();+ self.handle.close();+ a.destroy(self);+ if (worker) |w| {+ w.proc = null;+ w.lost();+ }+ return 0;+ }+};++pub const Worker = struct {+ io: std.Io,+ loop: *wl.EventLoop,owner: *anyopaque,callback: *const fn (*anyopaque) void,+ exe_buffer: [4096]u8 = undefined,+ exe: [:0]const u8 = undefined,+ sock: c_int = -1,+ source: ?*wl.EventSource = null,+ proc: ?*Proc = null,+ receiver: proto.Receiver = .{},+ inbound: [proto.max_report]u8 = undefined,+ /// What the helper last reported: 0 working, 1 wants a password, 2 done.+ /// Like the C worker's, it starts at 2 and `submit` moves it to 0.+ state_value: c_int = 2,+ result_value: c_int = 0,discovery: bool = false,+ arena: std.heap.ArenaAllocator = .init(a),+ found: std.ArrayList([5][]const u8) = .empty,- pub fn create(loop: *wl.EventLoop, owner: *anyopaque, callback: *const fn (*anyopaque) void) !*Worker {+ /// Finds the helper but does not start it.+ pub fn create(io: std.Io, loop: *wl.EventLoop, owner: *anyopaque, callback: *const fn (*anyopaque) void) !*Worker {const self = try a.create(Worker);errdefer a.destroy(self);- const native = rediwm_cups_create() orelse return error.WorkerFailed;- errdefer rediwm_cups_destroy(native);- self.* = .{ .native = native, .source = undefined, .owner = owner, .callback = callback };- self.source = try loop.addFd(*Worker, rediwm_cups_fd(native), .{ .readable = true }, ready, self);+ self.* = .{ .io = io, .loop = loop, .owner = owner, .callback = callback };+ self.exe = platform.exe.sibling(&self.exe_buffer, helper_name) orelse return error.NoExecutable;+ if (c.access(self.exe.ptr, c.X_OK) != 0) return error.NoExecutable;return self;}++ /// Kills the helper, even in the middle of a request or a password prompt.+ /// No callback follows.pub fn destroy(self: *Worker) void {- self.source.remove();- rediwm_cups_destroy(self.native);+ self.dropConnection();+ self.found.deinit(a);+ self.arena.deinit();a.destroy(self);}- fn ready(fd: c_int, _: wl.EventMask, self: *Worker) c_int {- var value: u64 = 0;- _ = read(fd, &value, @sizeOf(u64));++ pub fn state(self: *Worker) c_int {+ return self.state_value;+ }++ pub fn result(self: *Worker) c_int {+ return self.result_value;+ }++ fn connect(self: *Worker) !void {+ if (self.sock >= 0) return;+ var pair: [2]c_int = undefined;+ if (c.socketpair(c.AF_UNIX, c.SOCK_STREAM | c.SOCK_CLOEXEC, 0, &pair) != 0) return error.SocketFailed;+ // The helper's end is its stdin; ours must not outlive this call in the child.+ defer _ = c.close(pair[1]);+ errdefer _ = c.close(pair[0]);+ var process = try std.process.spawn(self.io, .{+ .argv = &.{self.exe},+ .stdin = .{ .file = .{ .handle = pair[1], .flags = .{ .nonblocking = false } } },+ .stdout = .ignore,+ });+ const pid = process.id.?;+ process.id = null;+ const proc = Proc.watch(self.loop, pid, self) catch |err| {+ platform.child.killAndReap(pid);+ return err;+ };+ const source = self.loop.addFd(*Worker, pair[0], .{ .readable = true }, readable, self) catch |err| {+ proc.kill();+ return err;+ };+ self.sock = pair[0];+ self.source = source;+ self.proc = proc;+ self.receiver = .{};+ }++ fn dropConnection(self: *Worker) void {+ if (self.source) |source| source.remove();+ self.source = null;+ if (self.sock >= 0) _ = c.close(self.sock);+ self.sock = -1;+ if (self.proc) |proc| proc.kill();+ self.proc = null;+ }++ /// The helper ended or broke the protocol. A request in flight fails as an+ /// uncertain result (the callback comes last: it may free the worker).+ fn lost(self: *Worker) void {+ self.dropConnection();+ if (self.state_value == 2) return;+ self.state_value = 2;+ self.result_value = 1;self.callback(self.owner);+ }++ /// Ends the helper without reporting it here: its socket then reads as+ /// closed, which `lost` turns into a failed request on the next loop turn.+ fn poison(self: *Worker) void {+ if (self.proc) |proc| proc.handle.signal(.KILL) catch {};+ }++ pub fn destination(self: *Worker, _: u8, len: usize) ?[]u8 {+ return if (len <= self.inbound.len) &self.inbound else null;+ }++ fn readable(_: c_int, _: wl.EventMask, self: *Worker) c_int {+ // One frame per call: the callback may free the worker, and the loop+ // is level-triggered, so a second frame is simply the next call.+ switch (self.receiver.read(self.sock, self)) {+ .again => {},+ .frame => self.deliver(),+ .closed, .invalid => self.lost(),+ }return 0;}- pub fn state(self: *Worker) c_int {- return rediwm_cups_state(self.native);++ fn deliver(self: *Worker) void {+ const payload = self.receiver.payload();+ switch (@as(proto.Report, @enumFromInt(self.receiver.kind))) {+ .state => {+ // A prompt is only valid while a request runs, and an end for one+ // that is running or waiting for a password. Anything else means+ // the helper is confused: do not trust it.+ const next: u8 = if (payload.len == 5) payload[0] else 0;+ const valid = switch (self.state_value) {+ 0 => next == 1 or next == 2,+ 1 => next == 2,+ else => false,+ };+ if (!valid) return self.lost();+ self.state_value = next;+ self.result_value = std.mem.readInt(i32, payload[1..5], .little);+ self.callback(self.owner);+ },+ .device => {+ var fields: [5][:0]const u8 = undefined;+ const count = proto.strings(payload, &fields) orelse return self.lost();+ if (count != 5 or !self.discovery or self.state_value != 0 or self.found.items.len >= proto.max_devices) return self.lost();+ var device: [5][]const u8 = undefined;+ const mem = self.arena.allocator();+ for (fields, 0..) |field, i| device[i] = mem.dupe(u8, field) catch return self.lost();+ self.found.append(a, device) catch return self.lost();+ },+ _ => self.lost(),+ }}- pub fn result(self: *Worker) c_int {- return rediwm_cups_result(self.native);++ fn clearDevices(self: *Worker) void {+ self.found.clearRetainingCapacity();+ _ = self.arena.reset(.retain_capacity);}+pub fn cancel(self: *Worker) void {- rediwm_cups_cancel(self.native);+ if (self.sock >= 0 and !proto.send(self.sock, @intFromEnum(proto.Command.cancel), &.{})) self.poison();}+pub fn finish(self: *Worker) void {- rediwm_cups_finish(self.native);+ if (self.sock >= 0 and !proto.send(self.sock, @intFromEnum(proto.Command.finish), &.{})) self.poison();}++ /// The password goes from the caller's locked storage into the socket+ /// without being copied, and the helper receives it into a locked page.pub fn credentials(self: *Worker, user: []const u8, password: []const u8) !void {- if (user.len == 0 or user.len > 255 or password.len >= 4096) return error.InvalidCredentials;+ if (user.len == 0 or user.len > proto.max_user or password.len > proto.max_password) return error.InvalidCredentials;for (user) |ch| if (ch < 0x21 or ch == 0x7f) return error.InvalidCredentials;if (std.mem.indexOfScalar(u8, password, 0) != null) return error.InvalidCredentials;- const name = try a.dupeSentinel(u8, user, 0);- defer a.free(name);- rediwm_cups_credentials(self.native, name, password.ptr, password.len);+ if (self.state_value != 1 or self.sock < 0) return;+ const nul = [_]u8{0};+ if (!proto.send(self.sock, @intFromEnum(proto.Command.credentials), &.{ user, &nul, password })) return self.poison();+ self.state_value = 0;}++ fn appendString(list: *std.ArrayList(u8), value: []const u8) !void {+ if (std.mem.indexOfScalar(u8, value, 0) != null) return error.InvalidArgument;+ try list.appendSlice(a, value);+ try list.append(a, 0);+ }+pub fn submit(self: *Worker, method: []const u8, signature: []const u8, bytes: []const u8, reset: bool) !void {- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const mem = arena.allocator();- var args: std.ArrayList([*:0]const u8) = .empty;- var reader: wire.Reader = .{ .bytes = bytes };- self.discovery = std.mem.eql(u8, method, "DevicesGet");- if (!self.discovery) {+ if (self.state_value != 2) return error.Busy;+ var payload: std.ArrayList(u8) = .empty;+ defer payload.deinit(a);+ try payload.append(a, @intFromBool(reset));+ try appendString(&payload, method);+ const discovery = std.mem.eql(u8, method, "DevicesGet");+ if (!discovery) {+ var reader: wire.Reader = .{ .bytes = bytes };+ var count: usize = 0;var i: usize = 0;while (i < signature.len) : (i += 1) switch (signature[i]) {- 's' => try args.append(mem, try mem.dupeSentinel(u8, try reader.string(), 0)),- 'b' => try args.append(mem, if (try reader.boolean()) "true" else "false"),+ 's' => {+ count += 1;+ try appendString(&payload, try reader.string());+ },+ 'b' => {+ count += 1;+ try appendString(&payload, if (try reader.boolean()) "true" else "false");+ },'a' => {i += 1;if (i >= signature.len or signature[i] != 's') return error.InvalidSignature;var values = try reader.array(4);- while (values.offset < values.bytes.len) try args.append(mem, try mem.dupeSentinel(u8, try values.string(), 0));+ while (values.offset < values.bytes.len) {+ count += 1;+ try appendString(&payload, try values.string());+ }},else => return error.InvalidSignature,};try reader.done();+ if (count > proto.max_args) return error.TooManyArguments;+ }+ if (payload.items.len > proto.max_command) return error.RequestTooLarge;+ try self.connect();+ if (!proto.send(self.sock, @intFromEnum(proto.Command.submit), &.{payload.items})) {+ self.dropConnection();+ return error.WorkerFailed;}- if (rediwm_cups_submit(self.native, try mem.dupeSentinel(u8, method, 0), @intCast(args.items.len), args.items.ptr, @intFromBool(reset)) != 0) return error.OutOfMemory;+ self.discovery = discovery;+ if (discovery) self.clearDevices();+ self.state_value = 0;+ self.result_value = 0;}+pub fn devices(self: *Worker, writer: *wire.Writer) !void {const dict = try writer.beginArray(8);const names = [_][]const u8{ "device-uri", "device-info", "device-make-and-model", "device-id", "device-class" };- for (0..128) |i| {- if (rediwm_cups_device(self.native, @intCast(i), 0) == null) break;- for (names, 0..) |name, j| {- const value = rediwm_cups_device(self.native, @intCast(i), @intCast(j)) orelse return error.InvalidReply;+ for (self.found.items, 0..) |device, i| {+ for (names, device) |name, value| {var key: [64]u8 = undefined;try writer.alignTo(8);try writer.string(try std.fmt.bufPrint(&key, "{s}:{d}", .{ name, i }));- try writer.string(std.mem.span(value));+ try writer.string(value);}}try writer.endArray(dict);diff --git a/src/printing/direct_protocol.zig b/src/printing/direct_protocol.zignew file mode 100644index 0000000..cc68644--- /dev/null+++ b/src/printing/direct_protocol.zig@@ -0,0 +1,209 @@+//! The wire format between the compositor and `rediwm-cups`, the helper that+//! holds libcups (and, through it, gnutls and the crypto libraries). Frames+//! travel on a stream socketpair: kind (u8), payload length (u32, little+//! endian), payload. Each side caps lengths before it reads a payload, and a+//! frame it cannot place is a protocol error: the connection is dropped.+//!+//! compositor -> helper: `submit` (reset byte, then NUL-terminated method and+//! arguments), `credentials` (user NUL password bytes), `cancel`, `finish`.+//! helper -> compositor: `state` (u8 state, i32 result: 1 wants a password, 2+//! finished), `device` (five NUL-terminated strings of a discovery result,+//! sent before the `state` frame that ends a successful discovery).+const std = @import("std");+const c = @import("c");++pub const header_len = 5;+/// Largest payload the helper accepts: 68 arguments of at most a few KiB.+pub const max_command = 128 * 1024;+/// Largest payload the compositor accepts: five strings of at most 8192 bytes.+pub const max_report = 48 * 1024;+/// Arguments after the method name (direct.c's own limit).+pub const max_args = 68;+/// Longest user name and password, as `credentials` carries them (`user NUL+/// password`). The helper's receive page for them is this big.+pub const max_user = 255;+pub const max_password = 4095;+pub const max_credentials = max_user + 1 + max_password;+/// Discovery results the compositor keeps (direct.c's own limit).+pub const max_devices = 128;++pub const Command = enum(u8) { submit = 1, credentials, cancel, finish, _ };+pub const Report = enum(u8) { state = 0x81, device, _ };++pub fn header(kind: u8, len: usize) [header_len]u8 {+ var bytes: [header_len]u8 = undefined;+ bytes[0] = kind;+ std.mem.writeInt(u32, bytes[1..5], @intCast(len), .little);+ return bytes;+}++/// Sends one frame whose payload is `parts` joined, in a single nonblocking+/// `sendmsg`: the parts are not copied, so a password goes from the caller's+/// locked storage to the kernel. A stream cannot carry half a frame, so false+/// (full, or the peer is gone) means the connection must be dropped.+pub fn send(fd: c_int, kind: u8, parts: []const []const u8) bool {+ var vec: [8]c.struct_iovec = undefined;+ if (parts.len + 1 > vec.len) return false;+ var total: usize = 0;+ for (parts) |part| total += part.len;+ var head = header(kind, total);+ vec[0] = .{ .iov_base = &head, .iov_len = header_len };+ for (parts, 1..) |part, i| vec[i] = .{ .iov_base = @constCast(part.ptr), .iov_len = part.len };+ var message = std.mem.zeroes(c.struct_msghdr);+ message.msg_iov = &vec;+ message.msg_iovlen = @intCast(parts.len + 1);+ while (true) {+ const sent = c.sendmsg(fd, &message, c.MSG_DONTWAIT | c.MSG_NOSIGNAL);+ if (sent < 0 and std.posix.errno(sent) == .INTR) continue;+ return sent >= 0 and @as(usize, @intCast(sent)) == total + header_len;+ }+}++/// Splits `payload` into its NUL-terminated strings, which stay in place.+/// Null when it does not end with a NUL or holds more than `out` can take.+pub fn strings(payload: []const u8, out: [][:0]const u8) ?usize {+ if (payload.len == 0) return 0;+ if (payload[payload.len - 1] != 0) return null;+ var count: usize = 0;+ var start: usize = 0;+ for (payload, 0..) |byte, i| {+ if (byte != 0) continue;+ if (count == out.len) return null;+ out[count] = payload[start..i :0];+ count += 1;+ start = i + 1;+ }+ return count;+}++/// Reassembles frames from a nonblocking stream. It reads exactly the bytes+/// the current frame still lacks, never beyond it, so a payload lands only+/// in the buffer `chooser` picked for its kind. That is how the helper keeps a+/// password in its locked page and nowhere else.+pub const Receiver = struct {+ head: [header_len]u8 = undefined,+ have: usize = 0,+ parsed: bool = false,+ complete: bool = false,+ kind: u8 = 0,+ len: usize = 0,+ got: usize = 0,+ body: []u8 = &.{},++ pub const Result = enum { frame, again, closed, invalid };++ /// `chooser.destination(kind, len)` returns the buffer for a payload of+ /// `len` bytes (at least that long), or null to refuse the frame.+ pub fn read(self: *Receiver, fd: c_int, chooser: anytype) Result {+ if (self.complete) self.* = .{};+ while (self.have < header_len) switch (chunk(fd, self.head[self.have..])) {+ .data => |n| self.have += n,+ .again => return .again,+ .closed => return .closed,+ };+ if (!self.parsed) {+ self.kind = self.head[0];+ self.len = std.mem.readInt(u32, self.head[1..5], .little);+ self.body = chooser.destination(self.kind, self.len) orelse return .invalid;+ if (self.body.len < self.len) return .invalid;+ self.parsed = true;+ }+ while (self.got < self.len) switch (chunk(fd, self.body[self.got..self.len])) {+ .data => |n| self.got += n,+ .again => return .again,+ .closed => return .closed,+ };+ self.complete = true;+ return .frame;+ }++ /// The payload of the frame `read` just completed.+ pub fn payload(self: *const Receiver) []u8 {+ return self.body[0..self.len];+ }+};++const Chunk = union(enum) { data: usize, again, closed };++fn chunk(fd: c_int, buffer: []u8) Chunk {+ while (true) {+ const n = c.recv(fd, buffer.ptr, buffer.len, c.MSG_DONTWAIT);+ if (n > 0) return .{ .data = @intCast(n) };+ if (n == 0) return .closed;+ switch (std.posix.errno(n)) {+ .INTR => continue,+ .AGAIN => return .again,+ else => return .closed,+ }+ }+}++test "frames are reassembled from partial writes and routed by kind" {+ var pair: [2]c_int = undefined;+ try std.testing.expectEqual(@as(c_int, 0), c.socketpair(c.AF_UNIX, c.SOCK_STREAM | c.SOCK_CLOEXEC, 0, &pair));+ defer _ = c.close(pair[0]);+ defer _ = c.close(pair[1]);+ var plain: [64]u8 = undefined;+ var secret: [16]u8 = undefined;+ const Chooser = struct {+ plain: []u8,+ secret: []u8,+ pub fn destination(self: @This(), kind: u8, len: usize) ?[]u8 {+ if (kind == @intFromEnum(Command.credentials)) return if (len <= self.secret.len) self.secret else null;+ return if (len <= self.plain.len) self.plain else null;+ }+ };+ const chooser: Chooser = .{ .plain = &plain, .secret = &secret };+ var receiver: Receiver = .{};+ try std.testing.expectEqual(Receiver.Result.again, receiver.read(pair[1], chooser));++ // A frame in two writes, split inside the header and again in the payload.+ const head = header(@intFromEnum(Command.submit), 6);+ try std.testing.expect(send(pair[0], @intFromEnum(Command.cancel), &.{}));+ try std.testing.expectEqual(Receiver.Result.frame, receiver.read(pair[1], chooser));+ try std.testing.expectEqual(@intFromEnum(Command.cancel), receiver.kind);+ try std.testing.expectEqual(@as(usize, 0), receiver.payload().len);+ try std.testing.expectEqual(@as(isize, 2), c.send(pair[0], &head, 2, 0));+ try std.testing.expectEqual(Receiver.Result.again, receiver.read(pair[1], chooser));+ try std.testing.expectEqual(@as(isize, 3), c.send(pair[0], head[2..].ptr, 3, 0));+ try std.testing.expectEqual(@as(isize, 3), c.send(pair[0], "abc", 3, 0));+ try std.testing.expectEqual(Receiver.Result.again, receiver.read(pair[1], chooser));+ try std.testing.expectEqual(@as(isize, 3), c.send(pair[0], "de\x00", 3, 0));+ try std.testing.expectEqual(Receiver.Result.frame, receiver.read(pair[1], chooser));+ try std.testing.expectEqualStrings("abcde\x00", receiver.payload());++ // Credentials never touch the plain buffer, and the next frame is read cleanly.+ try std.testing.expect(send(pair[0], @intFromEnum(Command.credentials), &.{ "root", "\x00", "hunter2" }));+ try std.testing.expect(send(pair[0], @intFromEnum(Command.finish), &.{}));+ @memset(&plain, 0);+ try std.testing.expectEqual(Receiver.Result.frame, receiver.read(pair[1], chooser));+ try std.testing.expectEqualStrings("root\x00hunter2", receiver.payload());+ try std.testing.expect(receiver.payload().ptr == &secret);+ try std.testing.expect(std.mem.allEqual(u8, &plain, 0));+ try std.testing.expectEqual(Receiver.Result.frame, receiver.read(pair[1], chooser));+ try std.testing.expectEqual(@intFromEnum(Command.finish), receiver.kind);++ // A length the chooser refuses is a protocol error, not a short read.+ try std.testing.expect(send(pair[0], @intFromEnum(Command.credentials), &.{"xxxxxxxxxxxxxxxxx"}));+ try std.testing.expectEqual(Receiver.Result.invalid, receiver.read(pair[1], chooser));++ // A peer that went away, even in the middle of a frame, is `closed`.+ var gone: [2]c_int = undefined;+ try std.testing.expectEqual(@as(c_int, 0), c.socketpair(c.AF_UNIX, c.SOCK_STREAM | c.SOCK_CLOEXEC, 0, &gone));+ defer _ = c.close(gone[1]);+ receiver = .{};+ try std.testing.expectEqual(@as(isize, 3), c.send(gone[0], &head, 3, 0));+ _ = c.close(gone[0]);+ try std.testing.expectEqual(Receiver.Result.closed, receiver.read(gone[1], chooser));+}++test "strings splits NUL-terminated payloads and refuses anything else" {+ var out: [3][:0]const u8 = undefined;+ try std.testing.expectEqual(@as(?usize, 0), strings("", &out));+ try std.testing.expectEqual(@as(?usize, 3), strings("a\x00\x00bc\x00", &out));+ try std.testing.expectEqualStrings("a", out[0]);+ try std.testing.expectEqualStrings("", out[1]);+ try std.testing.expectEqualStrings("bc", out[2]);+ try std.testing.expectEqual(@as(?usize, null), strings("a\x00b", &out));+ try std.testing.expectEqual(@as(?usize, null), strings("a\x00b\x00c\x00d\x00", &out));+}diff --git a/src/printing/tests.zig b/src/printing/tests.zigindex aee059f..7240f65 100644--- a/src/printing/tests.zig+++ b/src/printing/tests.zig@@ -13,4 +13,5 @@ test {_ = @import("daemon_watch.zig");_ = @import("notifier.zig");_ = @import("admin.zig");+ _ = @import("direct_protocol.zig");}diff --git a/tests/printers_direct.py b/tests/printers_direct.pyindex be32fb5..fb82d48 100644--- a/tests/printers_direct.py+++ b/tests/printers_direct.py@@ -2,7 +2,9 @@"""Direct libcups against private scripted schedulers, never the host CUPS.The native API checks exercise actual libcups HTTP/IPP and authentication. The-UI check runs the real Settings page with no helper on its private system bus.+UI check runs the real Settings page with no cups-pk-helper on its private+system bus: administration then goes through the rediwm-cups helper process,+which must be the only process that maps libcups."""import base64import ctypes@@ -267,6 +269,31 @@ def native_tests():print('Direct libcups operations, authentication retry and cancellation passed', flush=True)+def helper_pids(compositor, zombies=False):+ """rediwm-cups children of the compositor; a zombie counts only if asked."""+ found = []+ for entry in Path('/proc').iterdir():+ if not entry.name.isdigit():+ continue+ try:+ stat = entry.joinpath('stat').read_text()+ except OSError:+ continue+ comm = stat[stat.index('(') + 1:stat.rindex(')')]+ fields = stat[stat.rindex(')') + 2:].split()+ if comm == 'rediwm-cups' and int(fields[1]) == compositor and (zombies or fields[0] != 'Z'):+ found.append(int(entry.name))+ return found+++def mapped(pid, library):+ return library in Path(f'/proc/{pid}/maps').read_text()+++def linked(program, library):+ return library in subprocess.run(['ldd', str(program)], capture_output=True, text=True, check=True).stdout++def ui_test(scale):with tempfile.TemporaryDirectory(prefix='rediwm-direct-ui-') as directory:tmp = Path(directory)@@ -293,9 +320,16 @@ def ui_test(scale):ui.wait_settled('control_center')click('printers')wait_for(lambda: cups_ready(ui), 'direct page loaded', timeout=15)+ assert not helper_pids(process.pid), 'a read-only page must not start the administration helper'click('printers_resume')wait_for(lambda: scheduler.state()['queues']['Label_Test']['enabled'], 'helper-absent resume')wait_for(lambda: cups_ready(ui), 'refresh after resume')+ helpers = helper_pids(process.pid)+ assert len(helpers) == 1, helpers+ # The helper is non-dumpable, so its maps are not readable: check the link.+ assert linked('zig-out/bin/rediwm-cups', 'libcups') and not linked('zig-out/bin/rediwm', 'libcups')+ for library in ('libcups', 'libgnutls', 'libnettle', 'libp11-kit'):+ assert not mapped(process.pid, library), f'the compositor must not map {library}'scheduler.auth = Trueclick('printers_manage')click('printers_accepting')@@ -313,12 +347,23 @@ def ui_test(scale):wait_for(lambda: any(w.get('name') == 'printers_auth_password' for w in ui.widgets()), 'new operation must request fresh credentials')click('printers_auth_cancel')wait_for(lambda: not any(w.get('name') == 'printers_auth_password' for w in ui.widgets()), 'cancel clears prompt')- # Hide while a second prompt is outstanding; worker joins promptly.+ # The helper dying while a password prompt is outstanding fails that+ # request and leaves the page usable: the next one starts a new helper.+ click('printers_accepting')+ wait_for(lambda: any(w.get('name') == 'printers_auth_password' for w in ui.widgets()), 'prompt before the helper dies')+ helpers = helper_pids(process.pid)+ assert len(helpers) == 1, helpers+ os.kill(helpers[0], 9)+ wait_for(lambda: not any(w.get('name') == 'printers_auth_password' for w in ui.widgets()), 'helper death ends the prompt')+ wait_for(lambda: not helper_pids(process.pid, zombies=True), 'dead helper is reaped', timeout=5)+ # Hide while a second prompt is outstanding; the new helper's request+ # ends promptly with the page.click('printers_accepting')wait_for(lambda: any(w.get('name') == 'printers_auth_password' for w in ui.widgets()), 'hide challenge')start = time.monotonic()click('general')assert time.monotonic() - start < 3+ wait_for(lambda: not helper_pids(process.pid, zombies=True), 'hiding the page ends the helper', timeout=5)assert scheduler.state()['queues']['Label_Test']['accepting']scheduler.auth = Falseclick('printers')@@ -327,6 +372,11 @@ def ui_test(scale):click('printers_discover')wait_for(lambda: any(w.get('name') == 'printers_device_0' for w in ui.widgets()), 'direct discovery')assert not any(w.get('name') == 'printers_device_1' for w in ui.widgets()), 'unsafe backend URI must be filtered'+ # The helper dying between requests is invisible: the next one starts a new helper.+ helpers = helper_pids(process.pid)+ assert len(helpers) == 1, helpers+ os.kill(helpers[0], 9)+ wait_for(lambda: not helper_pids(process.pid, zombies=True), 'killed helper is reaped', timeout=5)click('printers_device_0')click('printers_name')ipc.key(29, True); ipc.key_press('a'); ipc.key(29, False)@@ -337,10 +387,13 @@ def ui_test(scale):assert created['enabled'] and created['uri'] == 'usb://Fixture/Label?serial=direct'assert not scheduler.printed, 'administration must not print a document'wait_for(lambda: cups_ready(ui), 'direct add refreshed')- # Both native threads must sleep without timed wakes at idle.+ # The helper's three threads (poll loop, CUPS worker, I/O watchdog) must+ # sleep without timed wakes at idle.+ helpers = helper_pids(process.pid)+ assert len(helpers) == 1, helpersdef counters():result = {}- for task in Path(f'/proc/{process.pid}/task').iterdir():+ for task in Path(f'/proc/{helpers[0]}/task').iterdir():try:if task.joinpath('comm').read_text().strip() not in ('rediwm-cups', 'rediwm-cups-io'): continuefields = dict(line.split(':', 1) for line in task.joinpath('status').read_text().splitlines())@@ -350,7 +403,7 @@ def ui_test(scale):time.sleep(.3)before = counters()time.sleep(.6)- assert len(before) == 2 and counters() == before, 'native administration must not poll at idle'+ assert len(before) == 3 and counters() == before, 'native administration must not poll at idle'finally:if process: stop_process(process)if log: log.close()