Skip to content

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

printers

oxydizer31ad79ae55f6
diff --git a/AGENTS.md b/AGENTS.md
index 5fcc234..a5b960a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -4,7 +4,7 @@ Details that are easy to get wrong; read the section for what you touch.
Tests: `TESTING.md`. Area notes are in an `AGENTS.md` beside the code; read
the one for the directory you work in: `src/files`, `src/editor`,
`src/desktop`, `src/input`, `src/control_center`, `src/ui`, `src/session`,
-`src/dm`, `src/accounts_helper`, `scripts`.
+`src/dm`, `src/accounts_helper`, `src/printing`, `scripts`.
## Working rules
diff --git a/README.md b/README.md
index 54f0de3..81a6339 100644
--- a/README.md
+++ b/README.md
@@ -59,6 +59,12 @@ librsvg/GdkPixbuf, PangoCairo, libinput, PAM, libpulse, libpipewire-0.3, Poppler
libseccomp, libarchive, libjpeg, libpng and libwebp. Optional:
Xwayland, `foot`, `brightnessctl`, `gio`/`xdg-open`, `git` (optional).
+Printer support uses an existing CUPS server (`cups`). Installing the optional
+`cups-pk-helper` package enables authorized setup and configuration from
+Settings → Printers; viewing status and submitting ordinary user jobs do not
+require that helper. These are optional runtime packages, not compositor build
+dependencies. RediWM does not install printer drivers or change USB rules.
+
Run from a checkout, `scripts/install.sh` builds that checkout (dependencies,
then `install-session.sh` with the arguments you give it).
diff --git a/TESTING.md b/TESTING.md
index ebed858..98e294f 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -30,6 +30,47 @@ Build first (`zig build`). Integration tests need Python 3 with Pillow, a C
compiler, `wayland-scanner` and wayland-protocols; D-Bus suites need PyGObject,
`dbus-run-session` and `busctl`. Some need extra tools, listed below.
+`zig build test-printers` runs the printing unit suite and
+`tests/printers.py` against the real headless Settings page. It needs the regular
+integration dependencies above, `wl-paste` (`wl-clipboard`), PyGObject/Gio/GLib,
+`dbus-daemon`, and a C compiler capable of a small shared `LD_PRELOAD` fixture.
+It does not require installed CUPS, cups-pk-helper or a printer.
+
+```sh
+zig build test-printers
+REDIWM_TEST_SCALE=1.5 zig build test-printers
+zig build test-printers -Doptimize=ReleaseSafe
+```
+
+The unit suite covers bounded IPP/HTTP, full identities, URI validation and
+matching, sysfs/node evidence, ladder/report privacy, PPD options/dimensions,
+PDFs and language samples, resolution suggestions, preserving defaults/private
+observations, socket-directory watches, notifier credentials and active DNS
+cancellation. Temporary loopback sockets and fixture trees never use a host
+scheduler or USB node.
+
+The integration uses private Unix/TCP schedulers, a private D-Bus helper/service
+manager, and temporary home/XDG directories. For administrative tests a
+noninstalled connect shim redirects only `/run/cups/cups.sock` and its `/var/run`
+alias to the private scheduler; this exercises the production canonical-server
+gate without a compositor test hook. All confirmed PDF/raw/ruler documents end
+in fixture memory. Coverage includes listing/jobs and denial, stopped/empty
+queues, malformed replies and deadlines, responsive IPC/cancel-on-hide, reports,
+remote-read/local-admin isolation, forged notifier rejection, setup/driver
+choices, options/defaults, named rename/removal confirmations, collision/job
+guards, preference migration and idle/hidden/closed lifetime.
+
+The independent [CUPS qualification matrix](docs/plans/printers-qualification.md)
+records actual helper ABI, subscription leases/cancellation and raw bytes through
+synthetic PPD queues in four disposable distro containers. It also records real
+helper rename and option semantics, including IPP/PPD discrepancies that the
+synthetic UI fixture cannot establish. Those commands are separate from the
+normal test target. Real USB/backend printing, physical ruler measurements,
+stock desktop polkit/notifier behavior, application/portal visibility and
+openSUSE qualification remain acceptance gates in the
+[Printers plan](docs/plans/printers.md). No automated test may contact the host
+scheduler, change a host queue/service or print to real hardware.
+
### Common knobs
- Run from a shell with `umask 077`: suites that create their own runtime
diff --git a/build.zig b/build.zig
index 874c8a7..f324818 100644
--- a/build.zig
+++ b/build.zig
@@ -464,6 +464,23 @@ pub fn build(b: *std.Build) void {
const run_ipc_tests = b.addRunArtifact(ipc_tests);
const test_step = b.step("test", "Run the project unit tests");
+ const printing_tests = b.addTest(.{ .root_module = b.createModule(.{
+ .root_source_file = b.path("src/printing/tests.zig"),
+ .target = target,
+ .optimize = optimize,
+ .link_libc = true,
+ }) });
+ printing_tests.root_module.addImport("dbus", dbus_mod);
+ printing_tests.root_module.addImport("wayland", wayland);
+ printing_tests.root_module.linkSystemLibrary("wayland-server", .{});
+ const run_printing_tests = b.addRunArtifact(printing_tests);
+ test_step.dependOn(&run_printing_tests.step);
+ const printers_integration = b.addSystemCommand(&.{"python3"});
+ printers_integration.addFileArg(b.path("tests/printers.py"));
+ printers_integration.step.dependOn(b.getInstallStep());
+ const printers_step = b.step("test-printers", "Test printer diagnostics and private CUPS page lifecycle");
+ printers_step.dependOn(&run_printing_tests.step);
+ printers_step.dependOn(&printers_integration.step);
// Dependency-module tests are not collected by the executable's test root.
const shared_ui_tests = b.addTest(.{ .root_module = ui_mod });
const shared_config_tests = b.addTest(.{ .root_module = config_mod });
diff --git a/docs/plans/printers-qualification.md b/docs/plans/printers-qualification.md
new file mode 100644
index 0000000..038699f
--- /dev/null
+++ b/docs/plans/printers-qualification.md
@@ -0,0 +1,681 @@
+# Printer qualification evidence
+
+Recorded 2026-10-16. These are isolated software compatibility checks for the
+[Printers plan](printers.md), separate from its physical-printer acceptance gates.
+No host CUPS socket, host service, USB device, printer, home directory or project
+checkout was mounted into a container. Packages were installed only in disposable
+rootless Podman containers. The schedulers used private configuration, state,
+spool, cache, log and runtime directories under their container's `/tmp`.
+
+## Distro matrix
+
+The cached release-family images were inspected first with `--network=none`,
+`--read-only` and `--pull=never`. None initially contained CUPS or cups-pk-helper.
+Their packages were then installed from their normal distro repositories inside
+throwaway containers; package versions below are the versions actually observed.
+Arch's base image identified itself as snapshot `20260927.0.600689`, Debian as
+13.7, Ubuntu as 24.04.5, and Fedora as 44.
+
+| Family | CUPS package | cups-pk-helper package | Empty private scheduler | Runtime helper introspection | Raw MIME advertised | `dbus://` subscription |
+| --- | --- | --- | --- | --- | --- | --- |
+| Arch | `2:2.4.20-1` | `0.2.7-2` | Pass | Pass | Pass | Pass |
+| Debian 13 | `2.4.10-3+deb13u2` | `0.2.6-2.1` | Pass | Pass | Pass | Pass |
+| Ubuntu 24.04 | `2.4.7-1.2ubuntu7.14` | `0.2.6-1ubuntu8` | Pass | Pass | Pass | Pass |
+| Fedora 44 | `2.4.19-3.fc44` | `0.2.7-12.fc44` | Pass | Pass | Pass | Pass |
+| openSUSE | Not checked | Not checked | Not checked | Not checked | Not checked | Not checked |
+
+Every checked CUPS package installed `/usr/lib/cups/notifier/dbus`. Each inert
+queue reported `application/vnd.cups-raw`, notification scheme `dbus`, and a
+supported lease range of `0-2147483647`. Creating a printer subscription with
+`notify-recipient-uri=dbus://`, `notify-events=printer-state-changed` and requested
+lease `0` succeeded on all four families. Some creation replies included only the
+subscription ID, so the absence of a lease in that reply is not a refusal.
+
+The Debian packaged `lpadmin(8)` documentation explicitly described the
+`everywhere` model querying the supplied IPP device. Minimal images on the other
+families did not expose that manual through the checked paths. Their actual
+Everywhere queue creation against an IPP device was not exercised. Upstream
+[CUPS lpadmin documentation](https://openprinting.github.io/cups/doc/man-lpadmin.html)
+also describes that model; documentation alone does not qualify discovery or
+creation on real printers.
+
+## Actual helper interface
+
+All four installed helpers were started directly on a private system bus, then
+introspected at destination `org.opensuse.CupsPkHelper.Mechanism`, object path
+`/`, interface `org.opensuse.CupsPkHelper.Mechanism`. The following signatures
+were identical across the two observed helper versions:
+
+| Method | Input signature | Output signature |
+| --- | --- | --- |
+| `DevicesGet` | `iiasas` | `sa{ss}` |
+| `PrinterAdd` | `sssss` | `s` |
+| `PrinterDelete` | `s` | `s` |
+| `PrinterRename` | `ss` | `s` |
+| `PrinterSetDefault` | `s` | `s` |
+| `PrinterSetEnabled` | `sb` | `s` |
+| `PrinterSetAcceptJobs` | `sbs` | `s` |
+| `PrinterAddOptionDefault` | `ssas` | `s` |
+
+This establishes the installed wire interface and executable availability. The
+private bus and scheduler used permissive fixture policies; this does not establish
+a desktop user's stock polkit authorization, service activation, discovery rights
+or successful queue administration through the helper on an installed desktop.
+
+## Subscription lease and byte transport
+
+The follow-up harness queries `Get-Subscription-Attributes` after creation rather
+than assuming that the requested lease was granted. Its raw transport check adds
+one synthetic PPD queue whose only backend copies the job into a private file.
+The PPD declares a deliberately missing PDF filter. One bounded binary payload is
+submitted with `lp -o raw`, then compared byte-for-byte with the captured file.
+This checks CUPS raw bypass through a PPD queue; no hardware backend is installed
+in the fixture's `ServerBin`, and no document is sent to a real printer.
+
+The granted lease was independently queried with `Get-Subscription-Attributes`
+on all four families, and each returned `notify-lease-duration=0`. Explicit
+`Cancel-Subscription` is also exercised before the raw fixture changes its queue.
+Each final comparison passed for the same 35-byte payload, including NUL,
+`0xff`, ESC, LF and CRLF. Debian/Ubuntu used `cmp`; Arch/Fedora minimal images
+lacked `cmp`, so the follow-up compared complete, untruncated `od -An -v -tx1`
+output. The checked backend copies input without invoking filters or opening a
+printer connection.
+
+| Family | Granted lease `0` | Explicit subscription cancellation | Raw bytes through synthetic PPD |
+| --- | --- | --- | --- |
+| Arch / CUPS 2.4.20 | Pass | Pass | Pass, 35 bytes |
+| Debian / CUPS 2.4.10 | Pass | Pass | Pass, 35 bytes |
+| Ubuntu / CUPS 2.4.7 | Pass | Pass | Pass, 35 bytes |
+| Fedora / CUPS 2.4.19 | Pass | Pass | Pass, 35 bytes |
+
+An earlier fixture run replaced `ServerBin` without retaining CUPS's
+`daemon/cups-exec` launcher. Queue changes then triggered a missing-launcher
+notifier retry, and the raw comparison could not run. The final harness retains
+that launcher while keeping hardware and network backends absent, cancels the
+subscription before changing the PPD queue, and bounds the private log size.
+This was a fixture setup failure, not evidence of raw passthrough or a product
+regression. An earlier Debian rename follow-up also encountered a cleanup-only
+race: its raw and lease checks had passed, but removing the private server root
+raced the terminating daemon and exited with status 1. The entire disposable
+container was removed; the documented recipe adds a wait before directory
+removal. Arch/Fedora follow-ups and the corrected final Debian fixture exited 0.
+
+## Rename source review and runtime limit
+
+`PrinterRename(ss) -> s` exists in the installed helper interfaces. The
+[official Debian 0.2.6 source archive](https://deb.debian.org/debian/pool/main/c/cups-pk-helper/cups-pk-helper_0.2.6.orig.tar.xz)
+and [upstream 0.2.7 archive](https://www.freedesktop.org/software/cups-pk-helper/releases/cups-pk-helper-0.2.7.tar.xz)
+were downloaded and `src/cups.c:cph_cups_printer_class_rename` reviewed.
+
+Both implementations check that the destination is absent, reject pending or
+processing jobs, create a replacement queue from the old PPD and selected
+attributes, attempt to move held jobs, then delete the old queue. The procedure
+is not atomic. Several updates/moves/deletion results are ignored; arbitrary
+queue defaults are not comprehensively copied. A concurrent destination creation
+can race the initial check. The 0.2.7 changes in this function only adjust class
+member loop integer types. It must not be described as an atomic or universally
+preserving rename.
+
+Initial private runtime calls in Debian, Arch and Fedora were refused before
+execution: the test bus admitted root but disconnected the packaged polkit
+service after it dropped to its service UID. The fixture policy was corrected
+to admit its container users, and the Debian check was repeated with the same
+private bus also available at the container's conventional system-bus path.
+No host bus or queue was used.
+
+On Debian 13, helper 0.2.6 and CUPS 2.4.10 then demonstrated:
+
+| Check | Actual result |
+| --- | --- |
+| Quiet `RenameSource` to unused `RenameNew` | Empty error string; old name disappeared; `fixture:/source` was preserved under the new name. |
+| `RenameNew` to existing `RenameExisting` | Refused; `RenameNew` retained `fixture:/source` and `RenameExisting` retained `fixture:/existing`. |
+| Rename with a pending job on paused `RenameNew` | Refused; source remained and no destination appeared. The bounded job targeted only the inert fixture backend and was cancelled afterwards. |
+
+Both refusals returned the nonempty error string `successful-ok`. That string
+occupies the helper's error field and is a failure despite its wording; only an
+empty error string denotes success. The final Debian fixture exited 0.
+
+These sequential checks establish the helper's basic rename, collision and
+pending-job behavior in this private root-authorized fixture. They do not
+establish atomicity, preservation of all defaults/history, held-job migration or
+unprivileged desktop authorization. Arch/Fedora rename behavior remains a source
+review plus interface check, rather than a successful runtime rename test.
+
+Source archive SHA-256 values:
+
+* 0.2.6: `959af8f2f5a2761e7e498b61c9caf25ae963335031eae9972d999e9a0d97a228`
+* 0.2.7: `66070ddb448fe9fcee76aa26be2ede5a80f85563e3a4afd59d2bfd79fbe2e831`
+
+## Actual option-setting semantics
+
+A follow-up Debian 13 fixture used CUPS 2.4.10, cups-pk-helper 0.2.6 and a
+synthetic PPD with A4/4x6 media, 203/300 dpi, duplex, color, quality and custom
+Darkness choices. After each helper call, `Get-Printer-Attributes` and the stored
+PPD's `*Default` lines were inspected. No option test submitted a print job.
+
+`PrinterAddOptionDefault` returned an empty error string for canonical media,
+resolution and duplex choices, but CUPS then returned duplicate default
+attributes: the requested 4x6/203 dpi/duplex values followed by the old
+A4/300 dpi/one-sided PPD values. `ipptool` correctly marked those replies as
+invalid due to duplicate attributes. The PPD defaults remained unchanged.
+Using that method with `PageSize`, `Resolution` and `Darkness` similarly stored
+IPP overrides without changing the PPD. A helper success string is therefore
+insufficient evidence that a driver choice was applied consistently.
+
+Those fixture overrides were removed with `PrinterDeleteOptionDefault` before
+checking `PrinterAddOption`, the PPD-aware method. Its observed effects were:
+
+| Method/key/value | Stored PPD after call | Reported IPP default |
+| --- | --- | --- |
+| `PrinterAddOption`, `PageSize=4x6` | `DefaultPageSize: 4x6` | media 4x6 |
+| `PrinterAddOption`, `Resolution=203dpi` | `DefaultResolution: 203dpi` | resolution 203 dpi |
+| `PrinterAddOption`, `Darkness=12` | `DefaultDarkness: 12` | Custom choice verified in PPD |
+| `PrinterAddOption`, `sides=two-sided-long-edge` | `DefaultDuplex: DuplexNoTumble` | two-sided-long-edge |
+| `PrinterAddOption`, `media=iso_a4_210x297mm` | `DefaultPageSize: A4` | A4 |
+| `PrinterAddOption`, `printer-resolution=300dpi` | `DefaultResolution: 300dpi` | resolution 300 dpi |
+| `PrinterAddOption`, `sides=one-sided` | `DefaultDuplex: None` | one-sided |
+| `PrinterAddOption`, `print-color-mode=monochrome` | `DefaultColorModel: Gray` | monochrome |
+| `PrinterAddOption`, `print-quality=4` | `DefaultcupsPrintQuality: Normal`, previously High | normal, also reported before the change |
+
+These PPD-aware replies had one copy of each standard default attribute and
+passed the IPP tool's response checks. Quality needs special care: this fixture reported
+IPP quality `normal` even when its initial PPD quality default was `High`, so
+that IPP field alone did not describe the PPD default. Selecting canonical quality `5` did change the stored PPD back to `High`, but
+IPP quality still reported `normal`.
+
+`PrinterDeleteOptionDefault` was also tested after the PPD setters for
+`PageSize`, `Resolution`, `Darkness`, `media`, `printer-resolution`, `sides`,
+`print-color-mode` and `print-quality`, including a repeated absent `Darkness`
+clear. Every call returned an empty success string. The stored PPD defaults
+survived; nondefault 4x6 media, 203 dpi and duplex remained correct in IPP.
+However, clearing `print-color-mode` reverted the reported IPP default to `color`
+while the PPD remained `Gray`. Clearing before reapplying `monochrome` did not
+repair that IPP field when the PPD was already Gray and the helper consequently
+had no changed PPD to upload. A blanket setter-then-clear sequence is therefore
+not a valid assumption for every canonical field. Default deletion removes an
+IPP override; it does not restore a rewritten PPD's original driver default.
+These checks establish stored PPD changes, not how every application's print
+dialog interprets a conflicting IPP/PPD default.
+
+This behavior matches the helper source's separate default-attribute and
+PPD-editing paths. Upstream
+[`cupsMarkOptions`](https://github.com/OpenPrinting/cups/blob/v2.4.10/cups/ppd-mark.c)
+maps canonical media, resolution, sides, color and quality values to PPD choices.
+The
+[driverless PPD generator](https://github.com/OpenPrinting/cups/blob/v2.4.10/cups/ppd-cache.c)
+also emits standard ColorModel, Duplex and cupsPrintQuality choices, but several
+branches expose resolution through quality presets and a `DefaultResolution`
+line without an editable `Resolution` option. This is source evidence, not a
+runtime driverless-printer qualification; standalone resolution changes can be
+unavailable or ignored on those PPDs. Re-read the actual choice/default before
+reporting a setting as applied.
+
+## Scope still requiring qualification
+
+* The label-printer isolation exercise, an ordinary printer, command-language
+ responses, real paper output and ruler measurements remain manual hardware
+ gates. A synthetic backend cannot establish physical printing or USB access.
+* The shipped distro policies, unprivileged polkit prompts, helper discovery and
+ administration, systemd service start, and end-to-end notifier delivery on
+ installed desktops remain separate checks. These fixtures use a private bus
+ and fixture policies, and do not run a host service manager.
+* Real driverless discovery/creation, device-ID-to-driver matches, and visibility
+ in application/portal print dialogs were not qualified by these containers.
+* No openSUSE image was cached. The release script currently targets Arch,
+ Debian, Ubuntu and Fedora; no openSUSE release qualification is claimed.
+
+## Reproduction and recorded commands
+
+Images used (local image IDs, before package installation):
+
+| Image | Local ID |
+| --- | --- |
+| `docker.io/library/archlinux:latest` | `66e676a0a26efc7da658cc3763b65e9bd1927de617c30fd2db7a5b405d5cfc4d` |
+| `docker.io/library/debian:13` | `36c636ddb9c578b068df381216d26a921c64fc2534e20baf7d0c53fb800b3a74` |
+| `docker.io/library/ubuntu:24.04` | `69f919497cada9a8611f3de61df902d9f94bf20f84552ef5bd93125c38608ef9` |
+| `docker.io/library/fedora:latest` | `ccb55df1d2413428166d80b08aa37a4bdcb61a63d09fff6f8abc0d561f311053` |
+
+Read-only inventory command:
+
+```sh
+podman images --format '{{.Repository}}:{{.Tag}} {{.ID}} {{.Size}}'
+podman run --rm --pull=never --network=none --cap-drop=all \
+ --security-opt=no-new-privileges --read-only --tmpfs /tmp IMAGE \
+ sh -c 'cat /etc/os-release; command -v cupsd || true'
+```
+
+The harness below reproduces the final container-only test recipe from this
+session, with an explicit container guard added. The successful runtime rename
+and option portions were run on Debian; the software matrix above also uses earlier isolated
+Arch/Ubuntu/Fedora runs of the same CUPS checks.
+Save it as a temporary `qualification.sh`, then use each image above and its
+family (`arch`, `debian`, `ubuntu`, `fedora`):
+
+```sh
+podman run --rm --pull=never --security-opt=no-new-privileges \
+ -v /absolute/path/to/qualification.sh:/qualification.sh:ro \
+ IMAGE sh /qualification.sh FAMILY
+```
+
+Package installation needs repository network access inside the disposable
+container. No host directory other than the read-only harness is mounted, and no
+ports or devices are passed through. Debian/Ubuntu package service-start hooks
+are denied with a container-only `policy-rc.d`. Arch's temporary image runs
+`systemd-sysusers` for its packaged CUPS service account because its base image
+has not booted a service manager. The standalone fixture scheduler is explicitly
+started from the harness. The rootless container's UID 0 is not host root.
+
+```sh
+#!/bin/sh
+set -eu
+# This recipe belongs inside a disposable Podman container only.
+[ -e /run/.containerenv ] || { echo "Run through podman, not on the host" >&2; exit 1; }
+family=$1
+qual_root=$(mktemp -d /tmp/rediwm-printer-qualify.XXXXXX)
+cups_pid=
+bus_pid=
+cleanup() {
+ [ -z "$cups_pid" ] || kill "$cups_pid" 2>/dev/null || true
+ [ -z "$bus_pid" ] || kill "$bus_pid" 2>/dev/null || true
+ [ -z "$cups_pid" ] || wait "$cups_pid" 2>/dev/null || true
+ rm -rf "$qual_root"
+}
+trap cleanup EXIT HUP INT TERM
+export SYSTEMD_OFFLINE=1
+case "$family" in
+ arch) pacman -Sy --noconfirm cups cups-pk-helper dbus polkit > "$qual_root/packages.log" 2>&1 || { tail -60 "$qual_root/packages.log"; exit 20; }; pacman -Q cups cups-pk-helper dbus ;;
+ debian|ubuntu)
+ printf '#!/bin/sh\nexit 101\n' > /usr/sbin/policy-rc.d
+ chmod 755 /usr/sbin/policy-rc.d
+ export DEBIAN_FRONTEND=noninteractive
+ apt-get update > "$qual_root/packages.log" 2>&1 && apt-get install -y --no-install-recommends cups-daemon cups-client cups-ipp-utils cups-pk-helper cups-server-common dbus dbus-bin polkitd >> "$qual_root/packages.log" 2>&1 || { tail -60 "$qual_root/packages.log"; exit 20; }
+ dpkg-query -W cups-daemon cups-client cups-pk-helper dbus
+ ;;
+ fedora)
+ dnf -y --setopt=install_weak_deps=False install cups cups-client cups-ipptool cups-pk-helper dbus-daemon polkit > "$qual_root/packages.log" 2>&1 || { tail -60 "$qual_root/packages.log"; exit 20; }
+ rpm -q cups cups-client cups-ipptool cups-pk-helper dbus-daemon
+ ;;
+esac
+printf '\nPACKAGED NOTIFIER\n'
+for path in /usr/lib/cups/notifier/dbus /usr/lib64/cups/notifier/dbus /usr/libexec/cups/notifier/dbus; do
+ [ ! -e "$path" ] || ls -l "$path"
+done
+printf '\nHELPER XML\n'
+for path in /usr/share/dbus-1/interfaces/*Cups* /usr/share/cups-pk-helper/* /usr/share/dbus-1/system-services/*Cups* /usr/share/polkit-1/actions/*cups*; do
+ [ ! -f "$path" ] || { printf '%s\n' "$path"; case "$path" in *.xml) cat "$path" ;; esac; }
+done
+printf '\nEVERYWHERE DOCUMENTATION\n'
+for path in /usr/share/man/man8/lpadmin.8.gz /usr/share/man/en/man8/lpadmin.8.gz; do
+ [ ! -f "$path" ] || zcat "$path" | grep -A6 -B2 everywhere || true
+done
+printf '\nCUPS FILE CONFIG\n'
+cups_user=$(awk '/^User[ \t]/{print $2;exit}' /etc/cups/cups-files.conf)
+cups_group=$(awk '/^Group[ \t]/{print $2;exit}' /etc/cups/cups-files.conf)
+[ -n "$cups_user" ] || cups_user=lp
+[ -n "$cups_group" ] || cups_group=lp
+if [ "$family" = arch ]; then systemd-sysusers /usr/lib/sysusers.d/cups.conf >/dev/null 2>&1 || true; fi
+printf 'SERVICE USER=%s GROUP=%s\n' "$cups_user" "$cups_group"
+mkdir -p "$qual_root/server" "$qual_root/state" "$qual_root/spool" "$qual_root/cache" "$qual_root/tmp" "$qual_root/run" "$qual_root/bin/daemon" "$qual_root/bin/backend" "$qual_root/bin/filter" "$qual_root/bin/notifier"
+# Avoid real USB, DNS-SD and network backends entirely, including discovery.
+for source in /usr/lib/cups/notifier/dbus /usr/lib64/cups/notifier/dbus /usr/libexec/cups/notifier/dbus; do
+ if [ -x "$source" ]; then ln -s "$source" "$qual_root/bin/notifier/dbus"; break; fi
+done
+for source in /usr/lib/cups/daemon/cups-exec /usr/lib64/cups/daemon/cups-exec /usr/libexec/cups/daemon/cups-exec; do
+ if [ -x "$source" ]; then ln -s "$source" "$qual_root/bin/daemon/cups-exec"; break; fi
+done
+chmod 755 "$qual_root" "$qual_root/server" "$qual_root/state" "$qual_root/spool" "$qual_root/cache" "$qual_root/tmp" "$qual_root/run" "$qual_root/bin" "$qual_root/bin/notifier"
+cat > "$qual_root/cups-files.conf" <<CONF
+User $cups_user
+Group $cups_group
+SystemGroup root
+ServerRoot $qual_root/server
+StateDir $qual_root/state
+RequestRoot $qual_root/spool
+CacheDir $qual_root/cache
+TempDir $qual_root/tmp
+ServerBin $qual_root/bin
+DataDir /usr/share/cups
+DocumentRoot /usr/share/cups/doc-root
+ErrorLog $qual_root/error.log
+AccessLog $qual_root/access.log
+PageLog $qual_root/page.log
+Printcap $qual_root/printcap
+CONF
+cat > "$qual_root/cupsd.conf" <<CONF
+Listen $qual_root/run/cups.sock
+Listen 127.0.0.1:8631
+Browsing Off
+WebInterface No
+DefaultAuthType Basic
+LogLevel debug
+MaxLogSize 1048576
+<Location />
+ Order allow,deny
+ Allow all
+</Location>
+<Policy default>
+ <Limit All>
+ Order allow,deny
+ Allow all
+ </Limit>
+</Policy>
+CONF
+# A private bus is used only by this container's notifier/helper checks.
+cat > "$qual_root/bus.conf" <<CONF
+<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+<busconfig><type>system</type><listen>unix:path=$qual_root/run/bus.sock</listen><auth>EXTERNAL</auth><policy context="default"><allow user="*"/><allow own="*"/><allow send_destination="*"/><allow send_type="signal"/><allow receive_sender="*"/></policy></busconfig>
+CONF
+bus_output=$(dbus-daemon --config-file="$qual_root/bus.conf" --fork --print-address=1 --print-pid=1)
+DBUS_SYSTEM_BUS_ADDRESS=$(printf '%s\n' "$bus_output" | head -n1)
+export DBUS_SYSTEM_BUS_ADDRESS
+bus_pid=$(printf '%s\n' "$bus_output" | tail -n1)
+/usr/sbin/cupsd -t -c "$qual_root/cupsd.conf" -s "$qual_root/cups-files.conf"
+/usr/sbin/cupsd -f -c "$qual_root/cupsd.conf" -s "$qual_root/cups-files.conf" > "$qual_root/cupsd.log" 2>&1 &
+cups_pid=$!
+# Single bounded startup wait; no persistent polling.
+sleep 15
+if [ ! -S "$qual_root/run/cups.sock" ]; then cat "$qual_root/cupsd.log" "$qual_root/error.log" 2>/dev/null || true; exit 21; fi
+export CUPS_SERVER="$qual_root/run/cups.sock"
+printf '\nEMPTY SCHEDULER\n'
+lpstat -r
+lpstat -p || true
+cat > "$qual_root/bin/backend/fixture" <<'BACKEND'
+#!/bin/sh
+# An inert, container-only backend: no hardware or network I/O, no jobs sent.
+exit 0
+BACKEND
+chmod 755 "$qual_root/bin/backend/fixture"
+lpadmin -p Qualification -E -v fixture:/never -m raw
+cat > "$qual_root/formats.test" <<'IPP'
+{
+ NAME "Private scheduler formats"
+ OPERATION Get-Printer-Attributes
+ GROUP operation-attributes-tag
+ ATTR charset attributes-charset utf-8
+ ATTR language attributes-natural-language en
+ ATTR uri printer-uri ipp://localhost/printers/Qualification
+ ATTR keyword requested-attributes document-format-supported,ipp-versions-supported,notify-schemes-supported,notify-lease-duration-supported
+ STATUS successful-ok
+ DISPLAY document-format-supported
+ DISPLAY ipp-versions-supported
+ DISPLAY notify-schemes-supported
+ DISPLAY notify-lease-duration-supported
+}
+IPP
+printf '\nRAW FORMAT AND NOTIFY CAPABILITIES\n'
+ipptool -T 3 -tv "ipp://127.0.0.1:8631/printers/Qualification" "$qual_root/formats.test" || true
+printf '\nHELPER RUNTIME INTROSPECTION\n'
+helper=$(sed -n 's/^Exec=//p' /usr/share/dbus-1/system-services/org.opensuse.CupsPkHelper.Mechanism.service)
+for path in /usr/lib/cups-pk-helper-mechanism /usr/libexec/cups-pk-helper-mechanism /usr/lib64/cups-pk-helper-mechanism; do
+ [ ! -x "$path" ] || helper=$path
+done
+if [ -n "$helper" ] && command -v dbus-send >/dev/null; then
+ "$helper" > "$qual_root/helper.log" 2>&1 &
+ helper_pid=$!
+ sleep 1
+ dbus-send --system --reply-timeout=3000 --print-reply --dest=org.opensuse.CupsPkHelper.Mechanism / org.freedesktop.DBus.Introspectable.Introspect || true
+ kill "$helper_pid" 2>/dev/null || true
+ cat "$qual_root/helper.log"
+else
+ printf 'helper executable or dbus-send unavailable\n'
+fi
+printf '\nSUBSCRIPTION CAPABILITY\n'
+cat > "$qual_root/subscribe.test" <<'IPP'
+{
+ NAME "Private scheduler dbus subscription"
+ OPERATION Create-Printer-Subscriptions
+ GROUP operation-attributes-tag
+ ATTR charset attributes-charset utf-8
+ ATTR language attributes-natural-language en
+ ATTR uri printer-uri ipp://localhost/
+ ATTR name requesting-user-name qualification
+ GROUP subscription-attributes-tag
+ ATTR uri notify-recipient-uri dbus://
+ ATTR keyword notify-events printer-state-changed
+ ATTR integer notify-lease-duration 0
+ STATUS successful-ok
+ DISPLAY notify-subscription-id
+ DISPLAY notify-lease-duration
+}
+IPP
+ipptool -T 3 -tv "ipp://127.0.0.1:8631/" "$qual_root/subscribe.test" || true
+printf '\nGRANTED SUBSCRIPTION LEASE\n'
+cat > "$qual_root/subscription-attributes.test" <<'IPP'
+{
+ NAME "Private subscription granted lease"
+ OPERATION Get-Subscription-Attributes
+ GROUP operation-attributes-tag
+ ATTR charset attributes-charset utf-8
+ ATTR language attributes-natural-language en
+ ATTR uri printer-uri ipp://localhost/
+ ATTR name requesting-user-name qualification
+ ATTR integer notify-subscription-id 1
+ STATUS successful-ok
+ DISPLAY notify-lease-duration
+ DISPLAY notify-recipient-uri
+}
+IPP
+ipptool -T 3 -tv "ipp://127.0.0.1:8631/" "$qual_root/subscription-attributes.test" || true
+cat > "$qual_root/cancel-subscription.test" <<'IPP'
+{
+ NAME "Cancel private notification subscription"
+ OPERATION Cancel-Subscription
+ GROUP operation-attributes-tag
+ ATTR charset attributes-charset utf-8
+ ATTR language attributes-natural-language en
+ ATTR uri printer-uri ipp://localhost/
+ ATTR name requesting-user-name qualification
+ ATTR integer notify-subscription-id 1
+ STATUS successful-ok
+}
+IPP
+ipptool -T 3 -tv "ipp://127.0.0.1:8631/" "$qual_root/cancel-subscription.test"
+printf '\nRAW PASSTHROUGH WITH PPD TO FILE-ONLY FIXTURE BACKEND\n'
+mkdir "$qual_root/received"
+chown "$cups_user:$cups_group" "$qual_root/received" "$qual_root/tmp"
+chmod 700 "$qual_root/received"
+cat > "$qual_root/bin/backend/fixture" <<BACKEND
+#!/bin/sh
+if [ \$# -eq 0 ]; then exit 0; fi
+if [ \$# -ge 6 ]; then
+ cat "\$6" > "$qual_root/received/job-\$1.bin"
+else
+ cat > "$qual_root/received/job-\$1.bin"
+fi
+BACKEND
+chmod 755 "$qual_root/bin/backend/fixture"
+cat > "$qual_root/fixture.ppd" <<'PPD'
+*PPD-Adobe: "4.3"
+*FormatVersion: "4.3"
+*FileVersion: "1.0"
+*LanguageVersion: English
+*LanguageEncoding: ISOLatin1
+*PCFileName: "QUALIFY.PPD"
+*Manufacturer: "RediWM test fixture"
+*Product: "(Inert fixture)"
+*ModelName: "Inert fixture"
+*NickName: "Inert fixture"
+*PSVersion: "(3010.000) 0"
+*cupsVersion: 1.1
+*cupsManualCopies: True
+*cupsFilter: "application/pdf 0 deliberately-missing-filter"
+*ColorDevice: True
+*DefaultColorSpace: Gray
+*OpenUI *Resolution/Resolution: PickOne
+*DefaultResolution: 300dpi
+*Resolution 203dpi/203 DPI: "<</HWResolution [203 203]>>setpagedevice"
+*Resolution 300dpi/300 DPI: "<</HWResolution [300 300]>>setpagedevice"
+*CloseUI: *Resolution
+*OpenUI *Darkness/Print Darkness: PickOne
+*DefaultDarkness: 8
+*Darkness 8/Light: ""
+*Darkness 12/Dark: ""
+*CloseUI: *Darkness
+*OpenUI *Duplex/Duplex: PickOne
+*DefaultDuplex: None
+
+*Duplex None/Off: "<</Duplex false>>setpagedevice"
+*Duplex DuplexNoTumble/Long edge: "<</Duplex true /Tumble false>>setpagedevice"
+*CloseUI: *Duplex
+*OpenUI *ColorModel/Color Mode: PickOne
+*DefaultColorModel: RGB
+*ColorModel Gray/Monochrome: "<</ProcessColorModel /DeviceGray>>setpagedevice"
+*ColorModel RGB/Color: "<</ProcessColorModel /DeviceRGB>>setpagedevice"
+*CloseUI: *ColorModel
+*OpenUI *cupsPrintQuality/Quality: PickOne
+*DefaultcupsPrintQuality: High
+*cupsPrintQuality Draft/Draft: ""
+*cupsPrintQuality Normal/Normal: ""
+*cupsPrintQuality High/High: ""
+*CloseUI: *cupsPrintQuality
+*OpenUI *PageSize/Media Size: PickOne
+*DefaultPageSize: A4
+*PageSize A4: "<</PageSize [595 842]>>setpagedevice"
+*PageSize 4x6/4 x 6 inch: "<</PageSize [288 432]>>setpagedevice"
+*ImageableArea 4x6: "0 0 288 432"
+*PaperDimension 4x6: "288 432"
+*ImageableArea A4: "0 0 595 842"
+*PaperDimension A4: "595 842"
+*CloseUI: *PageSize
+PPD
+if ! lpadmin -p QualificationPpd -E -v fixture:/never -P "$qual_root/fixture.ppd"; then
+ tail -40 "$qual_root/error.log"
+ exit 22
+fi
+printf 'RediWM raw passthrough\n\000\377\033%%finite\015\012' > "$qual_root/expected.bin"
+lp -d QualificationPpd -o raw "$qual_root/expected.bin"
+sleep 3
+if [ "$(od -An -v -tx1 "$qual_root/expected.bin")" = "$(od -An -v -tx1 "$qual_root/received/job-1.bin")" ]; then
+ printf 'RAW_PPD_BYTE_COMPARISON=PASS\n'
+ wc -c "$qual_root/expected.bin"
+else
+ printf 'RAW_PPD_BYTE_COMPARISON=FAIL\n'
+ lpstat -l -W all -o || true
+ tail -35 "$qual_root/error.log"
+fi
+printf '\nPRIVATE HELPER RENAME\n'
+mkdir -p /run/dbus
+ln -s "$qual_root/run/bus.sock" /run/dbus/system_bus_socket
+polkit=
+for path in /usr/lib/polkit-1/polkitd /usr/libexec/polkit-1/polkitd; do
+ [ ! -x "$path" ] || polkit=$path
+done
+if [ -n "$polkit" ]; then
+ "$polkit" > "$qual_root/polkit.log" 2>&1 &
+ polkit_pid=$!
+ "$helper" > "$qual_root/rename-helper.log" 2>&1 &
+ rename_helper_pid=$!
+ sleep 5
+ dbus-send --system --reply-timeout=3000 --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.ListNames
+ lpadmin -p RenameSource -E -v fixture:/source -m raw
+ lpadmin -p RenameExisting -E -v fixture:/existing -m raw
+ lpadmin -p RenameSource -o printer-info='Retain this description' -o job-sheets-default=none,none
+ printf 'BEFORE RENAME\n'
+ lpstat -v
+ dbus-send --system --reply-timeout=10000 --print-reply --dest=org.opensuse.CupsPkHelper.Mechanism / org.opensuse.CupsPkHelper.Mechanism.PrinterRename string:RenameSource string:RenameNew || true
+ printf 'AFTER NEW NAME\n'
+ lpstat -v || true
+ dbus-send --system --reply-timeout=10000 --print-reply --dest=org.opensuse.CupsPkHelper.Mechanism / org.opensuse.CupsPkHelper.Mechanism.PrinterRename string:RenameNew string:RenameExisting || true
+ printf 'AFTER COLLISION\n'
+ lpstat -v || true
+ printf 'PENDING JOB GUARD ON PAUSED QUEUE\n'
+ cupsdisable RenameNew || true
+ lp -d RenameNew -o raw "$qual_root/expected.bin" || true
+ lpstat -l -W not-completed -o || true
+ dbus-send --system --reply-timeout=10000 --print-reply --dest=org.opensuse.CupsPkHelper.Mechanism / org.opensuse.CupsPkHelper.Mechanism.PrinterRename string:RenameNew string:RenamePending || true
+ lpstat -v
+ cancel -a RenameNew || true
+ printf 'PRIVATE OPTION SEMANTICS\n'
+ cat > "$qual_root/options.test" <<'IPP'
+{
+ NAME "Actual option defaults"
+ OPERATION Get-Printer-Attributes
+ GROUP operation-attributes-tag
+ ATTR charset attributes-charset utf-8
+ ATTR language attributes-natural-language en
+ ATTR uri printer-uri ipp://localhost/printers/QualificationPpd
+ ATTR keyword requested-attributes media-default,printer-resolution-default,sides-default,print-color-mode-default,print-quality-default,Darkness-default,PageSize-default,Resolution-default
+ STATUS successful-ok
+ DISPLAY media-default
+ DISPLAY printer-resolution-default
+ DISPLAY sides-default
+ DISPLAY print-color-mode-default
+ DISPLAY print-quality-default
+ DISPLAY Darkness-default
+ DISPLAY PageSize-default
+ DISPLAY Resolution-default
+}
+IPP
+ query_options() {
+ printf '\nOPTION SNAPSHOT %s\n' "$1"
+ ipptool -T 3 -tv "ipp://127.0.0.1:8631/printers/QualificationPpd" "$qual_root/options.test" || true
+ grep '^\*Default' "$qual_root/server/ppd/QualificationPpd.ppd"
+ }
+ set_option() {
+ printf '\nSET OPTION method=%s key=%s value=%s\n' "$1" "$2" "$3"
+ dbus-send --system --reply-timeout=10000 --print-reply --dest=org.opensuse.CupsPkHelper.Mechanism / "org.opensuse.CupsPkHelper.Mechanism.$1" string:QualificationPpd "string:$2" "array:string:$3"
+ }
+ query_options baseline
+ set_option PrinterAddOptionDefault media na_index-4x6_4x6in
+ set_option PrinterAddOptionDefault printer-resolution 203dpi
+ set_option PrinterAddOptionDefault sides two-sided-long-edge
+ query_options ipp-default-api
+ set_option PrinterAddOptionDefault PageSize 4x6
+ set_option PrinterAddOptionDefault Resolution 203dpi
+ set_option PrinterAddOptionDefault Darkness 12
+ query_options ppd-keys-default-api
+ printf 'CLEAR PREVIOUS IPP DEFAULT OVERRIDES\n'
+ for key in media printer-resolution sides PageSize Resolution Darkness; do
+ dbus-send --system --reply-timeout=10000 --print-reply --dest=org.opensuse.CupsPkHelper.Mechanism / org.opensuse.CupsPkHelper.Mechanism.PrinterDeleteOptionDefault string:QualificationPpd "string:$key"
+ done
+ query_options cleared-overrides
+ set_option PrinterAddOption PageSize 4x6
+ set_option PrinterAddOption Resolution 203dpi
+ set_option PrinterAddOption Darkness 12
+ query_options ppd-keys-ppd-api
+ set_option PrinterAddOption sides two-sided-long-edge
+ query_options canonical-duplex-positive
+ set_option PrinterAddOption media iso_a4_210x297mm
+ set_option PrinterAddOption printer-resolution 300dpi
+ set_option PrinterAddOption sides one-sided
+ set_option PrinterAddOption print-color-mode monochrome
+ set_option PrinterAddOption print-quality 4
+ query_options canonical-ppd-api
+ printf 'CLEAR ABSENT OVERRIDES AFTER PPD SETTERS\n'
+ for key in PageSize Resolution Darkness media printer-resolution sides print-color-mode print-quality; do
+ printf 'CLEAR AFTER PPD key=%s\n' "$key"
+ dbus-send --system --reply-timeout=10000 --print-reply --dest=org.opensuse.CupsPkHelper.Mechanism / org.opensuse.CupsPkHelper.Mechanism.PrinterDeleteOptionDefault string:QualificationPpd "string:$key"
+ done
+ printf 'REPEAT ABSENT CLEAR Darkness\n'
+ dbus-send --system --reply-timeout=10000 --print-reply --dest=org.opensuse.CupsPkHelper.Mechanism / org.opensuse.CupsPkHelper.Mechanism.PrinterDeleteOptionDefault string:QualificationPpd string:Darkness
+ query_options absent-clear-after-ppd
+ printf 'CANONICAL NONDEFAULTS BEFORE AND AFTER CLEANUP\n'
+ set_option PrinterAddOption media na_index-4x6_4x6in
+ set_option PrinterAddOption printer-resolution 203dpi
+ set_option PrinterAddOption sides two-sided-long-edge
+ set_option PrinterAddOption print-color-mode monochrome
+ set_option PrinterAddOption print-quality 5
+ query_options canonical-nondefaults-before-clear
+ for key in media printer-resolution sides print-color-mode print-quality; do
+ printf 'CLEAR CANONICAL AFTER key=%s\n' "$key"
+ dbus-send --system --reply-timeout=10000 --print-reply --dest=org.opensuse.CupsPkHelper.Mechanism / org.opensuse.CupsPkHelper.Mechanism.PrinterDeleteOptionDefault string:QualificationPpd "string:$key"
+ done
+ query_options canonical-nondefaults-after-clear
+ printf 'CLEANUP BEFORE EACH CANONICAL SETTER\n'
+ for pair in media:na_index-4x6_4x6in printer-resolution:203dpi sides:two-sided-long-edge print-color-mode:monochrome print-quality:5; do
+ key=${pair%%:*}
+ value=${pair#*:}
+ dbus-send --system --reply-timeout=10000 --print-reply --dest=org.opensuse.CupsPkHelper.Mechanism / org.opensuse.CupsPkHelper.Mechanism.PrinterDeleteOptionDefault string:QualificationPpd "string:$key"
+ set_option PrinterAddOption "$key" "$value"
+ done
+ query_options canonical-cleanup-before-set
+
+
+ cat "$qual_root/rename-helper.log" "$qual_root/polkit.log"
+ kill "$rename_helper_pid" "$polkit_pid" 2>/dev/null || true
+else
+ printf 'Private polkit daemon unavailable; rename authorization not exercised\n'
+fi
+printf '\nPRIVATE SCHEDULER LOG TAIL\n'
+tail -12 "$qual_root/error.log" || true
+```
diff --git a/docs/plans/printers.md b/docs/plans/printers.md
index 3f8e692..3a1777f 100644
--- a/docs/plans/printers.md
+++ b/docs/plans/printers.md
@@ -1,7 +1,67 @@
# Plan: Printers page in Settings (setup, status, and "why didn't it print")
-Status: draft, 2026-10-13. Nothing is built. Decisions D1–D6 are proposed,
-not taken. Phase 0 settles the facts marked **(verify)** before any UI work.
+Status: the printer software workflows are implemented, 2026-10-16. Physical
+printer acceptance and stock desktop policy qualification remain open. This
+plan distinguishes implemented behavior, synthetic tests, isolated CUPS checks
+and hardware evidence; a completed CUPS job never establishes paper output.
+
+Implemented scope:
+
+* Settings → Printers lists queues, state/reasons, reported supplies, defaults
+ and the current user's recent jobs. Own jobs can be cancelled. Missing or
+ private attributes and authorization failures remain visible.
+* A bounded IPP codec and cancellable HTTP worker support configured Unix and
+ cleartext TCP CUPS endpoints. System/user `client.conf`, `CUPS_SERVER` and
+ encryption preferences are checked without falling back to a different
+ server. TLS, authentication and escaped configuration syntax are unsupported.
+* Local-default-server administration uses `cups-pk-helper`: discovery, queue
+ creation, enabling/disabling, accepting/rejecting jobs, descriptions, queue
+ rename/removal, connection changes and the system default. Custom Unix and
+ remote schedulers remain read-only for these actions. CUPS service start uses
+ the existing systemd path and reports unavailability on other service managers.
+* Setup combines CUPS discovery, USB evidence and validated typed network
+ addresses. Driverless IPP is preferred when supported evidence is available;
+ IEEE 1284 driver matches are conservative, ambiguous matches need a choice,
+ and raw queues/third-party driver guidance are explicit. Vendor backends must
+ come from the current CUPS discovery result, never arbitrary typed input.
+* Queue-name collisions are checked before administration. Removal and queue
+ rename require separate named confirmations. Rename is the helper's
+ non-atomic clone/delete operation, with known-job guards, refreshed queue
+ checks and migration of personal defaults/private observations after success.
+* Supported IPP values and bounded PPD UI declarations provide media,
+ resolution, colour, duplex, quality and exposed label controls. Driver choices
+ use the PPD-aware helper API and are refreshed for verification. CUPS can
+ report conflicting IPP/PPD defaults; an accepted request is not presented as
+ a verified setting when the resulting value cannot be established.
+* Per-user defaults preserve existing `~/.cups/lpoptions` options, destinations,
+ instances and comments through atomic replacement. `LPDEST`/`PRINTER` overrides
+ remain visible; the privileged system default is a separate action.
+* Explicitly confirmed PDF, raw-language and ruler tests use actual media
+ dimensions, one copy and no banners. PDFs request no scaling or n-up fitting.
+ Language samples run individually, and the user records whether output
+ appeared. Two-axis measurements suggest only a supported resolution. No node
+ write, test print or privileged mutation happens automatically.
+* USB uevents, local socket-directory events, show/Refresh and user actions
+ trigger reloads without polling. Where a verified indefinite `dbus://` lease
+ is available, authenticated CUPS notifier signals also reload the page.
+ Hiding closes local workers/listeners and attempts subscription cancellation
+ without waiting for a reply.
+* Diagnostics retain unknown evidence, mask private identifiers and include
+ bounded distro/CUPS version information and user-recorded test outcomes.
+ Package guidance covers Arch derivatives, Debian/Ubuntu, Fedora and openSUSE;
+ Settings search includes printer terms. Printing adds no root executable,
+ package installer, USB rule writer, filter or driver.
+
+[Qualification evidence](printers-qualification.md) records real isolated CUPS
+and helper checks on Arch, Debian 13, Ubuntu 24.04 and Fedora 44, including raw
+bytes through a synthetic PPD queue. These do not qualify USB/backend hardware,
+real media measurements, stock unprivileged polkit behavior, desktop notifier
+delivery, real driverless creation or application/portal visibility. openSUSE
+has guidance but no release build target or executed qualification image.
+The cancellable resolver uses hosts files and ordinary DNS, not NSS/Avahi mDNS;
+direct `ipps://`/DNS-SD reachability remains unavailable. The repository-wide
+i18n module is still planned (`docs/plans/i18n.md`), so strings follow existing
+English call-site conventions rather than a completed extraction pipeline.
Scope: a Printers page in Settings that lists printers and their jobs, adds
and configures them, and, the part that justifies more than a simple list,
@@ -64,12 +124,14 @@ Goals
test for resolution, and "Copy diagnostic report".
* Works with no CUPS, a stopped CUPS, a socket-activated CUPS, and with no
privileges: what cannot be done says why and what to do.
-* Same behaviour on Arch, Debian/Ubuntu, Fedora and openSUSE (our release
- families); nothing in the page assumes a package manager.
+* Target consistent behavior on the Arch, Debian/Ubuntu and Fedora release
+ families, with guidance for openSUSE. Actual policy/hardware qualification is
+ tracked separately; the page never runs a package manager.
Non-goals
-* No driver of our own (no PPD, no raster filter, no TSPL/ZPL generator);
+* No driver of our own: no shipping PPD, raster filter or document-to-TSPL/ZPL
+ converter. The bounded diagnostic samples above are the only language output;
see "Not in this plan".
* No print dialog: applications print through the Print portal or GTK/Qt
dialogs and CUPS. This page configures what they see.
@@ -85,19 +147,26 @@ Non-goals
### Talk to CUPS over IPP, unprivileged (D1)
-Read and the user-level actions go straight to cupsd over IPP on its unix
-socket (`/run/cups/cups.sock` by default; honour `CUPS_SERVER` and
-`~/.cups/client.conf` like every CUPS client, so tests and unusual setups need
-no hook). A small IPP client in Zig (`src/printing/ipp.zig`: encoder, bounded
-decoder, HTTP/1.1 over the socket), in the spirit of `src/dbus`: no new
+Reads, own-job cancellation and explicit test submissions go straight to the
+configured cupsd over IPP. The default is `/run/cups/cups.sock`; system and user
+`client.conf`, `CUPS_SERVER` and encryption settings determine the actual target.
+Cleartext TCP `host[:port][/version=1.0|1.1]` and supported IPP authorities are
+also accepted. No request silently changes servers. A small IPP client in Zig
+(`src/printing/ipp.zig`: encoder, bounded decoder, HTTP/1.1 transport), in the spirit of `src/dbus`: no new
library, no libcups ABI to match across four distro families, and no
-glib. Operations needed: Get-Printers / Get-Printer-Attributes, Get-Jobs /
-Get-Job-Attributes, Cancel-Job, Cancel-Jobs (own jobs), Print-Job (tests),
-CUPS-Get-Devices, CUPS-Get-PPDs, Pause/Resume-Printer where allowed.
-
-Alternative (not chosen): link libcups. Smaller code, but a new link-time
-dependency in every release tarball and the build containers, for a protocol
-whose subset we need is under 1,000 lines.
+glib. It queries printers, attributes, own jobs, PPD metadata and PPD content,
+cancels an individual own job, submits explicit tests, and creates/inspects/
+cancels notification subscriptions. Discovery and administrative changes use
+the privileged APIs below. Any future cancel-all-own action must use
+Cancel-My-Jobs rather than Cancel-Jobs; that bulk action is not exposed here.
+
+Alternative: link libcups. Its transport, authentication, configuration and
+destination APIs avoid reimplementing substantial compatibility behavior.
+The bounded client supports a documented Unix/cleartext TCP subset, not full
+libcups compatibility. TLS, authentication, escaped client configuration and
+NSS/Avahi mDNS resolution are not implemented. DNS, connect, upload and response
+share one three-second request deadline and the page cancellation path. See the
+qualification findings below before extending compatibility claims.
The decoder treats the response as untrusted (cupsd can be remote through
`CUPS_SERVER`): bounded lengths and counts, no recursion beyond collections,
@@ -107,16 +176,19 @@ a widget.
### Live only while visible, no polling
Same rule as the Services page. The page is live while it is on screen
-(`show` from `printers.build`, `hide` from `selectPage`/`detachSettings`); dark
-means no subscription, no sockets, nothing held. While live:
-
-* **cupsd changes:** a CUPS event subscription if one can be had without
- polling. cupsd can notify over D-Bus (`org.cups.cupsd.Notifier`) once a
- subscription exists, and `Create-Printer-Subscription` with `dbus://` is the
- standard route. **(verify)** that it is present and readable by an
- unprivileged user on each family. Fallback, if not: reload on page
- show, on the user's action, and when a job we started changes; never on a
- timer.
+(`show` from `printers.build`, `hide` from `selectPage`/`detachSettings`). Hiding
+joins the cancellable worker and releases local sockets, matches and watches;
+subscription cancellation is a best-effort nonblocking send. While live:
+
+* **cupsd changes:** a page-owned system-bus listener validates the notifier
+ interface/path/member and authenticates each unique sender through bus
+ credentials. CUPS's notifier does not acquire a well-known service name.
+ The worker requests an indefinite `dbus://` printer subscription and verifies
+ the granted lease, querying it separately when creation omits the duration.
+ If unavailable, finite or unauthorized, the page keeps explicit/action-driven
+ refresh; no polling or renewal timer runs. Default desktop delivery remains a
+ qualification gate. An inotify watch on the local socket's parent also detects
+ daemon disappearance/recreation without contacting a host service manager.
* **USB hotplug:** a kernel uevent listener (netlink `NETLINK_KOBJECT_UEVENT`,
subsystems `usb` and `usbmisc`) that triggers one sysfs rescan. The scan is
a pure function from a sysfs root to a list of printer-class devices
@@ -138,14 +210,16 @@ USB printer
1. **Found on USB.** Interface class 7 from sysfs. Fail text names what was
seen ("a device 0416:5011 is attached but is not a printer class device").
Never read the product string as truth (finding 1 above).
-2. **Kernel device node.** For the matched device: `/dev/usb/lp*` exists and is
- a character device, and the user/CUPS can reach it. Fail: node missing
- (`usblp` not loaded or deliberately blocked), or *a regular file sits where
- the node should be* (finding 2). The page never writes to a node itself; the
- check is `stat`.
-3. **CUPS running.** IPP answers. If not, say whether the socket exists and
- whether the unit is enabled; offer "Start CUPS" only through the same
- privileged path as the rest (D3).
+2. **Backend access path.** Report the matched `/dev/usb/lp*` node, if any,
+ and its file type. A missing `usblp` node is normal for the CUPS libusb
+ backend and for `ipp-usb`; it cannot fail this rung. A queue whose backend
+ explicitly uses that node can fail if it is missing or a regular file.
+ `stat` cannot prove CUPS's access permissions or USB communication; those
+ remain unknown without backend evidence. The page never writes to a node.
+3. **CUPS running.** IPP answers. If not, distinguish installation evidence
+ from a running/reachable scheduler; offer "Start CUPS" only through the
+ existing privileged systemd path (D3). No failed request proves that a unit
+ is disabled or that CUPS is absent.
4. **Queue exists and accepts jobs.** Exists, `printer-state`, `printer-is-
accepting-jobs`, stopped reasons (`printer-state-reasons`).
5. **Backend reaches it.** The queue's device URI points at the device that
@@ -155,15 +229,19 @@ USB printer
6. **Settings fit the media.** Queue default page size and resolution against
what the user says they load (asked once for label printers); mismatch is
the finding-7/9 case.
-7. **Last job printed something.** From the last job: state, sheets
+7. **Last job outcome.** From the last job: state, sheets
completed, `job-state-reasons`, `job-printer-state-message`. A job
`completed` with 0 sheets and a message like "No pages were found." is
- reported as *finished but printed nothing*, pointing at the filter stage
- (item 9), not at USB.
+ reported as *finished; no pages reported*, with the filter message shown.
+ Missing counters, zero counters alone and `completed` do not prove that
+ paper emerged or that it was blank. Omitted/private attributes and absent
+ history stay unknown; this page cannot recover every filter log over IPP.
-Network printer: reachable (IPP Get-Printer-Attributes on its URI, with a short
-deadline) replaces rungs 1–2; the rest apply. A printer reported by DNS-SD but
-not reachable says so (different subnet, VPN, firewall) without scanning.
+Network printer: a bounded Get-Printer-Attributes on an exact `ipp://` device
+URI replaces rungs 1–2; it never scans hosts or ports. TLS, DNS-SD service URIs
+and mDNS-only names cannot be checked by this transport and retain unavailable
+or unknown evidence. CUPS's own backend can still support those connections;
+a direct reachability result is separate from CUPS backend success.
The ladder only *reports*. Each fix is an explicit button, and none runs
unasked.
@@ -178,8 +256,17 @@ unasked.
command-language test chosen from the known-devices table or the printer's
`printer-device-id` (`CMD:` field: `TSPL`, `ZPL`, `EPL`, `CPCL`, `PCL`,
`POSTSCRIPT`, ...). It exercises backend, USB and the printer, and not
- filters or PPD. **(verify)** that cupsd passes it through unchanged on a
- queue that has a PPD on all four families.
+ filters or PPD. Isolated CUPS checks passed a bounded binary payload unchanged
+ through synthetic PPD queues on all four release families; actual printer
+ command execution and backend/USB behavior remain hardware gates.
+
+Implementation refinement: only complete `CMD:`/`COMMAND SET:` tokens count as
+device-ID language evidence. The known-devices table supplies a visible hint,
+never permission to select a language automatically from a shared USB ID. A
+user confirms the language and each individual print. Availability of this
+explicit diagnostic tool does not certify physical output or every installed
+backend/policy. The [isolated raw checks](printers-qualification.md) qualify the
+tested CUPS software path only.
Read together: raw prints and filtered does not → filters/PPD/media; neither
prints → backend/USB/printer/paper. This is finding 5 as a button pair.
@@ -204,23 +291,32 @@ and editable from the driver's options; no ruler.
Sources, in order shown:
-1. Printers CUPS already lists (`CUPS-Get-Devices`: USB, DNS-SD, socket).
+1. Devices returned by the helper's `DevicesGet` CUPS discovery operation
+ (USB, DNS-SD, socket and validated installed vendor backends), through the
+ privileged path. An authorization failure means
+ discovery is unavailable, not that no devices exist.
Devices CUPS lists whose URI is already used by a queue are hidden.
2. Detected USB printers that CUPS did not list (the ladder's rungs 1–2 data):
shown with *why* it is missing ("the kernel driver did not create a
device", "CUPS cannot open it") instead of silently absent.
3. A typed address: `ipp://`, `ipps://`, `socket://`, `lpd://`, and hostnames
- resolving to those. Allow-list of schemes. No `file:`, no `smb:` (the
- latter carries credentials), no scripts or vendor backends the user types.
+ when entered as network addresses. Typed schemes are allow-listed. No
+ `file:`, credential-bearing `smb:`, scripts or arbitrary typed vendor
+ backends are accepted. Discovered vendor URIs must exactly match a current
+ helper result and pass the separate discovered-backend validation.
Driver choice, no driver of ours:
1. **Driverless first:** an IPP Everywhere / AirPrint printer, or a USB printer
exposed over IPP by `ipp-usb` when that is present, is added with the
- `everywhere` model; no PPD. **(verify)** the model name per CUPS version.
-2. **Match by device ID:** `CUPS-Get-PPDs` with the device's IEEE 1284 ID;
- take the best match CUPS ranks (`ppd-match`), show make/model and the
- driver's package name so the user can see what they get.
+ `everywhere` model. CUPS 2.4 documents that model name and queries the IPP
+ device; it can generate a PPD internally, so "driverless" does not mean
+ "no PPD file" on CUPS 2.x. **(verify)** actual add behavior per version.
+2. **Match by device ID:** retrieve PPD metadata and compare the IEEE 1284
+ make/model/device ID conservatively. The documented CUPS-Get-PPDs API
+ does not promise `ppd-match` rankings or a driver package name. Matching
+ and any optional distro package attribution need their own verified
+ implementation; ambiguous matches require an explicit choice.
3. **No match:** say so. Offer a *raw queue* (jobs pass through untouched,
fine for applications that already emit the printer's language), and show
the known-devices note ("this model speaks TSPL; ordinary PDF printing needs
@@ -228,25 +324,34 @@ Driver choice, no driver of ours:
with the project name and URL, not an install command we cannot vouch for.
We do not download or install third-party code.
-New queues are created enabled and accepting, named from the model with
-characters CUPS allows, and *never* silently replace an existing queue of the
-same name (finding 8: the report lost queues to accidents; deleting needs a
-confirmation that names the printer, and "Remove" is separate from "Disable").
+New queues are created enabled and accepting with a unique validated name.
+The UI refreshes names and refuses known collisions before calling the helper;
+"Remove" has a named confirmation and is separate from "Disable". Queue rename
+has its own confirmation and rejects known active/held jobs. The helper itself
+uses a non-atomic clone/delete operation, so concurrent administration remains
+a race; this is not an atomic create-or-rename guarantee. After rename, the page
+checks refreshed queue identities and migrates personal defaults/observations.
+See the [actual helper checks](printers-qualification.md) for collision refusal,
+pending-job refusal and preservation limits.
### Known devices: a small data table
-`src/printing/known_devices.zig` (or an embedded TOML like theme presets), keyed
-by `vid:pid` and optionally IEEE 1284 make/model:
+`src/printing/known_devices.zig` stores bounded hardware observations and a
+third-party driver project link. Its initial entry is:
```
-0416:5011 command_set=TSPL resolution=203 media=4x6 bidirectional=false
- note="Advertises 300 dpi; measured 203. USB class 7, product string 'POS Label Printer'."
+vid:pid=0416:5011 language_hint=TSPL resolution_hint_dpi=203 provisional=true
+note="One unresolved field report; confirm command language and physical scale."
```
-Fields are facts about the *hardware*, never instructions we run. It feeds the
-language probe, the default resolution, the ladder's rung-6 hint, and the
-report. It starts with the one device we have tested and grows by pull request.
-An entry means "verified on that hardware, source in the commit message".
+Fields describe observations about the *hardware*, never instructions we run.
+The initial entry is explicitly **provisional**, sourced from the unresolved
+single-device field report above; it is not a universally verified TSPL/203-dpi
+identification for every device sharing `0416:5011`. Its note calls out both
+the advertised 300 dpi and the reported 203 dpi measurement. It supplies a
+language-probe/media hint, not an automatic language or resolution default.
+Future verified entries need isolated hardware evidence and its source in the
+commit message.
### Privileged actions (D3)
@@ -256,8 +361,13 @@ unprivileged user and a compositor must not have. In order of preference:
1. **`cups-pk-helper`** (`org.opensuse.CupsPkHelper.Mechanism` on the system
bus; it is what GNOME Settings and `system-config-printer` use). Polkit
handles the authorization and our polkit agent already shows the prompt. We
- write no root code. Present on the families we ship for **(verify)** and
- packaged as a recommended, not required, dependency.
+ write no root code. Starting CUPS is a separate service-manager action;
+ cups-pk-helper is not a general service controller. Its installed interface
+ was checked in four isolated release-family containers; stock desktop
+ authorization remains unqualified. It is an optional runtime recommendation
+ documented in README, not a generated binary-library dependency. The helper
+ targets its canonical local server, so custom Unix and remote endpoints are
+ not allowed to administer an unrelated local scheduler.
2. If it is absent: the page is read-only for those actions and says exactly
which package is missing, by name for the detected distro (`/etc/os-release`
`ID`/`ID_LIKE`), without running it.
@@ -278,17 +388,18 @@ user*, with the exact line and where to put it; we do not edit package files.
### Diagnostic report
"Copy diagnostic report" puts plain text on the clipboard; it is never sent
-anywhere. Contents: distro and CUPS version, the ladder with reasons, the
-printer's VID:PID, interface class and node type, queue URI with credentials
-and hostnames of *other* machines masked, queue options, the last N jobs'
-state/sheets/reasons/messages, `printer-state-reasons`, and
-which tests were run with their outcome. No document names, no user names,
-no job content, no log lines we cannot read without root.
+anywhere. It includes allow-listed distro/version information, ladder verdicts,
+USB VID:PID/interface/node evidence, URI scheme/connection class, bounded media
+and resolution data, reported job state/sheets and user-recorded test outcomes.
+Credentials, URI authorities/paths, arbitrary queue/document/user names, USB
+serials and freeform messages are excluded. Known failure messages inform the
+ladder but are not copied verbatim into the report. No job content or privileged
+log read is involved.
### Page layout
-Left: printers (icon, name, state dot, "Default" tag). Right, for the selected
-printer, top to bottom:
+A printer selector leads to the selected queue's details and controls. The
+scrollable content includes:
* header: name, model, status sentence, ink/toner bars if reported;
* ladder (collapsed to one line when everything passes);
@@ -302,31 +413,31 @@ Empty states: CUPS not installed (say what and how, by distro), CUPS stopped,
no printers ("Add a printer" with detected USB first), printer unplugged
(ladder shows rung 1 failing, settings dimmed).
-All controls come from `ui/widgets/` (no hand-drawn controls); text through the
-i18n mechanism; the ladder uses the existing shell icons plus text, never
-colour alone.
-
-## Decisions to take
-
-* **D1** hand-rolled IPP client vs libcups: proposed hand-rolled.
-* **D2** discovery: only what CUPS reports + USB sysfs + typed address:
- proposed yes, no scanning.
-* **D3** privilege path: cups-pk-helper first, no helper of ours unless Phase 0
- proves a need: proposed.
-* **D4** test pair (through driver / skipping filters) and the language
- probe: proposed.
-* **D5** USB quirks: advise only, never edit package files: proposed.
-* **D6** per-user vs system default printer: per-user default lives in
- `~/.cups/lpoptions` and is what applications' dialogs honour; the CUPS-wide
- default needs rights. Proposed: set the per-user default, offer the
- system default only if the privileged path is present.
+All controls come from `ui/widgets/`; the ladder uses text as well as state
+styling. English strings follow current repository conventions. The shared
+i18n/extraction system is still a separate planned dependency.
+
+## Decisions applied
+
+* **D1:** a bounded Zig IPP/HTTP client, with explicit compatibility limits.
+* **D2:** CUPS discovery, USB sysfs and typed allow-listed network addresses;
+ no scans or guessed driver identity.
+* **D3:** the existing cups-pk-helper and systemd APIs; no new root helper.
+* **D4:** separately confirmed driver/raw/ruler samples and one language probe
+ at a time, with user observations distinct from CUPS job state.
+* **D5:** advice only for USB quirks; no package-file or device-node writes.
+* **D6:** preserving per-user defaults, visible environment overrides and a
+ separate privileged system-default action. Applications can retain their own
+ printer choice; this page does not override their print dialogs.
## Phases
-### Phase 0: facts, no UI (small)
+### Phase 0: isolated software evidence captured; hardware gates open
-On the author's printer and on at least one printer that needs no special
-handling; record results in this plan.
+The isolated software checks are recorded below and in the qualification file.
+The manual hardware exercise still requires the author's printer and one
+ordinary printer; it is not part of an automated test or permission to touch
+host queues/services.
* Rebuild a throwaway queue from scratch for the label printer and find the
*minimal* set of changes (quirk vs `usblp` vs udev symlink vs backend choice)
@@ -338,24 +449,87 @@ handling; record results in this plan.
list, PPD list, subscriptions) on a default install.
* Output: facts here, and fixtures for Phase 1 (recorded IPP exchanges).
-### Phase 1: read-only page (medium)
-
-`src/printing/{ipp,cups,usb_sysfs,ladder,known_devices}.zig`,
-`control_center/sections/printers.zig`.
+#### Evidence and remaining gates, 2026-10-16
+
+The host scheduler, its queues/jobs and attached printers were not used for
+qualification. Automated UI exchanges are synthetic. Separate disposable
+containers ran actual CUPS/helper software with private sockets, buses and state;
+their only output backend captured a bounded binary fixture into a private file.
+The [qualification record](printers-qualification.md) contains exact image IDs,
+package versions, commands, outcomes and limits.
+
+Observed software evidence:
+
+* Arch CUPS 2.4.20, Debian 2.4.10, Ubuntu 2.4.7 and Fedora 2.4.19 exposed the
+ tested helper ABI and packaged notifier. Indefinite subscription grants,
+ explicit cancellation and raw bytes through a synthetic PPD queue passed in
+ each container. This does not establish hardware output or stock policy.
+* Debian's real helper renamed an idle throwaway queue, refused an existing
+ destination and refused a paused queue's pending job. Source review of helper
+ 0.2.6/0.2.7 establishes its non-atomic clone/delete behavior and partial error/
+ option-preservation limits; no stronger rename guarantee is claimed.
+* Real helper option checks exposed duplicate IPP defaults from the generic
+ default-attribute API. The PPD-aware API updates actual driver choices.
+ Colour/quality IPP fields can disagree with the PPD, and deleting an override
+ can change reported defaults. The page verifies refreshed driver values and
+ keeps unverified outcomes explicit; the qualification record preserves the
+ actual before/after results rather than inferring success from an empty error.
+* The unit suite covers bounded/hostile codecs and identity, allocation failures,
+ URI validation, driver matching, PPD declarations/dimensions, PDF offsets,
+ language samples, calibration, preserving defaults and private observations,
+ socket watches, notifier credentials and active DNS cancellation.
+* `tests/printers.py` exercises the real Settings UI with private scheduler,
+ helper and service-manager fixtures. It covers confirmed test bytes, setup,
+ defaults/options, guarded rename/removal, failures, remote administration
+ isolation, privacy and idle/hidden/closed worker lifetime. Current validation
+ commands and dependencies are in [TESTING.md](../../TESTING.md).
+
+Useful upstream constraints remain:
+
+* Raw printing/queues and PPD drivers are deprecated. CUPS documents raw jobs
+ as bypassing filters; a CUPS completed state still says nothing about paper.
+ [Printing guidance](https://openprinting.github.io/cups/),
+ [driver migration](https://openprinting.github.io/cups/drivers.html).
+* Default policies place discovery and queue administration behind permissions;
+ own-job cancellation, privacy and retained history also depend on policy.
+ [CUPS policy template](https://github.com/OpenPrinting/cups/blob/v2.4.20/conf/cupsd.conf.in).
+* PPD metadata does not promise ranked matches or package names. `everywhere`
+ queries an IPP device and can generate a PPD on CUPS 2.x.
+ [IPP extensions](https://openprinting.github.io/cups/doc/spec-ipp.html),
+ [lpadmin](https://openprinting.github.io/cups/doc/man-lpadmin.html).
+* libusb can detach the kernel driver and does not require `/dev/usb/lp*`.
+ Source supports separate quirk files, but no isolated hardware evidence shows
+ that this printer needs one. No automatic quirk change is implemented.
+ [USB backend source](https://github.com/OpenPrinting/cups/blob/master/backend/usb-libusb.c).
+
+Open acceptance work: isolate the original label-printer fault, test one ordinary
+printer, verify real driverless discovery/creation and hardware-specific driver
+matches, measure physical media/ruler output, exercise stock unprivileged polkit
+and notifier delivery on installed release-family desktops, and check newly
+created queues in application/portal print dialogs. An openSUSE image/release
+matrix is absent. Shared-USB-ID hints remain provisional; TLS/authenticated
+remote CUPS, mDNS resolution and the repository-wide i18n pipeline are outside
+the implemented subset. No hardware gate is marked passed by the software tests.
+
+### Phase 1: status, diagnostics and explicit tests — software implemented
+
+`src/printing/` and `control_center/sections/printers.zig`.
* Printer list, state in words, jobs, ink/toner.
* The ladder, rungs 1–7, from IPP plus sysfs.
* Cancel own jobs; resume a stopped queue where allowed.
* Hotplug via uevents; CUPS events or action-driven reload.
* Empty states; Copy diagnostic report.
-* Test page through the driver; raw test (Phase 1b if the passthrough check
- needs work).
+* Separately confirmed driver PDF, raw language sample and ruler tests.
+* Acceptance remains open: the software matrix does not establish physical output.
* Gate: ladder verdicts match reality on the label printer for each induced
fault (unplugged, queue stopped, wrong URI, filter fail).
-### Phase 2: set up and configure (medium)
+### Phase 2: setup and configuration — software implemented
-* Add flow (sources, driverless/PPD match/raw), remove, rename, set default.
+* Add flow (discovery/typed URI, driverless/PPD match/raw), guarded removal,
+ descriptions, confirmed queue rename, connection editing and personal/system
+ defaults.
* Driver options as groups from the PPD or IPP `-supported` attributes; media
and resolution in plain words.
* Privileged actions through cups-pk-helper; absence handled.
@@ -364,12 +538,16 @@ handling; record results in this plan.
* Gate: a printer is added, configured, test-printed and removed with no
terminal on Arch and one other family.
-### Phase 3: polish and distro coverage (small)
+### Phase 3: integration implemented; distro/hardware qualification remains
* Per-distro guidance strings (missing package names), `os-release` aware.
* Reload on cupsd restart, graceful loss of CUPS mid-use.
-* `AGENTS.md`, `TESTING.md`, release notes, Settings search keywords, i18n
- extraction for the new strings.
+* `AGENTS.md`, `TESTING.md`, README optional dependencies and Settings search
+ keywords are updated. No printing package is added to generated library
+ `DEPENDS`; release tooling has no optional `RECOMMENDS` facility.
+* Shared i18n extraction remains blocked on the repository-wide i18n project.
+* The isolated software matrix is recorded; stock desktop and hardware gates
+ above remain open.
### Optional: our own helper (only if Phase 0 requires it)
@@ -377,24 +555,29 @@ See D3 item 3. Not scheduled.
## Tests
-* **Unit (Zig):** IPP encode/decode round-trips and hostile inputs (truncated,
- oversized counts, nested collections, bad UTF-8); ladder verdicts as a pure
- function of (sysfs snapshot, IPP snapshot); sysfs scan over fixture trees,
- including the regular-file-at-the-node case and the `0416:5011` "Virtual Com
- Port" string; URI allow-list; report masking.
-* **Integration (`tests/printers.py`):** a fake cupsd on a private unix socket,
- selected through `CUPS_SERVER` (a real CUPS variable, so no test hook), speaking
- the IPP subset above, with scripted failure modes: not running, stopped
- queue, job completed with zero sheets and the "No pages were found." message,
- slow server, garbage reply. The page is driven over IPC like the other
- Settings pages; clicks use the settle/wait rules in `TESTING.md`.
-* **Never** the real cupsd or a real printer in a test: the author has a
- working queue attached. Hardware checks (USB layer, real test prints) are
- manual and written into the Phase 1/2 gate notes.
-* The sysfs layer cannot be faked end to end without a production hook, so it
- is covered by the fixture-tree unit tests plus the manual hardware gate.
-* Cost gate: opening the page makes no wakeups while idle (per-thread context
- switch count), and closing it releases the socket and the listener.
+* `zig build test` includes `src/printing/tests.zig`; `zig build test-printers`
+ also runs the private Settings integration. Run at scale 1 and 1.5, and check
+ the ReleaseSafe build as described in [TESTING.md](../../TESTING.md).
+* Unit fixtures cover bounded IPP/HTTP and collections, response framing and
+ version privacy, full validated identities, URI allow-lists, conservative
+ driver matching, USB/sysfs/node types, pure ladder verdicts/report masking,
+ PPD choices and dimensions, allocation failure, test PDF geometry/xref,
+ language samples, two-axis resolution suggestions, preserving preferences,
+ socket events, notifier authentication and cancellable DNS.
+* `tests/printers.py` uses private Unix/TCP schedulers and a private D-Bus helper/
+ service-manager fixture. A noninstalled `LD_PRELOAD` connect shim redirects
+ only the canonical CUPS socket during administration tests, so the production
+ local-server safety gate is exercised without contacting host CUPS. Confirmed
+ documents terminate in fixture memory; no real print backend is involved.
+* Disposable-container qualification is separate from the normal test target:
+ [exact results and reproduction](printers-qualification.md). Its capture-only
+ backend establishes tested software passthrough, not physical printing.
+* Never run automated tests against the host scheduler or a real printer. The
+ USB layer uses fixture trees; physical USB, paper and desktop policy checks
+ remain explicit manual acceptance work.
+* Idle workers block without periodic queries. Integration checks per-thread
+ context switches and scheduler requests, and verifies that hiding or closing
+ Settings cancels I/O, joins its worker and releases local activity.
## Risks and open questions
@@ -408,8 +591,17 @@ See D3 item 3. Not scheduled.
* cups-pk-helper is not installed everywhere. If it is missing on a family,
D3 item 2 is the user experience there, and it should be acceptable, not an
error.
-* Remote cupsd (`CUPS_SERVER=host`): supported for reading; setup actions are
- disabled with a reason. Encrypted/authenticated remote servers are out.
+* Remote cupsd (`CUPS_SERVER=host`): cleartext reads and bounded user requests
+ are supported; local administrative actions are disabled. TLS/authenticated
+ endpoints are unsupported. The resolver uses ordinary DNS and hosts files,
+ not NSS/Avahi mDNS; direct `ipps://` and DNS-SD reachability stay unavailable.
+* Indefinite subscriptions avoid renewal wakeups. Cancellation is best effort:
+ a failed send or crash can leave a CUPS-owned subscription; local listeners
+ and sockets are still closed. Server-side cleanup/delivery remains part of
+ desktop policy/lifetime qualification.
+* Rename is a helper clone/delete operation, not atomic. Concurrent changes,
+ hidden jobs and arbitrary option/history preservation need care; refresh and
+ named confirmation do not turn it into a transactional server operation.
* Sandboxed callers (`[[sandbox_allow]]`) and the security-context filter are
untouched; the page runs inside the compositor's own process, like the other
Settings pages.
@@ -429,4 +621,6 @@ See D3 item 3. Not scheduled.
* CUPS server administration, sharing, quotas, authenticated remote servers.
* Print preview, a print dialog, a print-to-PDF queue.
* Bluetooth printer pairing and Bluetooth backends.
-* Network scanning or probing of any kind.
+* Network or port scanning, unsolicited device probes, and guessed endpoints.
+ A bounded request to an exact selected/discovered IPP URI is the only direct
+ reachability check.
diff --git a/src/control_center/AGENTS.md b/src/control_center/AGENTS.md
index 416a483..3367fd0 100644
--- a/src/control_center/AGENTS.md
+++ b/src/control_center/AGENTS.md
@@ -38,3 +38,17 @@ Settings is an ordinary window with a compositor-drawn body (`Backend.shell`).
their state (audio: General and Audio), and wallpaper thumbnails go straight
into their tile (`stripWake`). The nav highlights damage the rows they cross,
not the list.
+* **Printers owns its worker only while the page is selected.** `printers.build`
+ starts it lazily; `selectPage` and destruction call `hide`. Socket requests
+ have an absolute deadline and are interrupted through the worker eventfd
+ before joining. USB uevents coalesce into a rescan; no idle timer queries
+ CUPS. State snapshots cross under a mutex; widget strings must be copied
+ into the section arena before the next snapshot replaces them. An older
+ automatic refresh must not clear a newer user action's busy state.
+ Only own jobs are cancellable, rechecked outside the callback; CUPS remains
+ the authority. Reports omit identities and arbitrary status messages.
+ USB libusb queues do not require a usblp node. Read `docs/plans/printers.md`
+ for the unqualified hardware and distribution-policy acceptance gates.
+ Discovered backend URIs must match the current helper catalog exactly;
+ arbitrary typed vendor/file backends are not allowed. PPD settings use
+ `PrinterAddOption` after clearing stale IPP defaults, followed by readback.
diff --git a/src/control_center/panel.zig b/src/control_center/panel.zig
index af6638b..53a395e 100644
--- a/src/control_center/panel.zig
+++ b/src/control_center/panel.zig
@@ -31,6 +31,7 @@ const portal_section = @import("sections/portals.zig");
const desktop_section = @import("sections/desktop.zig");
const input_section = @import("sections/input.zig");
const services_section = @import("sections/services.zig");
+const printers_section = @import("sections/printers.zig");
const systemd = @import("../systemd.zig");
const users_section = @import("sections/users.zig");
const bluetooth_section = @import("sections/bluetooth.zig");
@@ -47,18 +48,19 @@ const default_height = 640;
// .glass-strong uses shared CSS palette and --r-lg.
const theme = @import("ui").theme;
-pub const Page = enum { general, input, displays, audio, network, appearance, shortcuts, desktop, bluetooth, region, users, services };
-const page_labels = [_][]const u8{ "General", "Input", "Displays", "Audio", "Network", "Appearance", "Keyboard Shortcuts", "Desktop", "Bluetooth", "Region & Language", "Users", "Services" };
-const page_names = [_][]const u8{ "general", "input", "displays", "audio", "network", "appearance", "shortcuts", "desktop", "bluetooth", "region", "users", "services" };
+pub const Page = enum { general, input, displays, audio, network, appearance, shortcuts, desktop, bluetooth, region, users, printers, services };
+const page_labels = [_][]const u8{ "General", "Input", "Displays", "Audio", "Network", "Appearance", "Keyboard Shortcuts", "Desktop", "Bluetooth", "Region & Language", "Users", "Printers", "Services" };
+const page_names = [_][]const u8{ "general", "input", "displays", "audio", "network", "appearance", "shortcuts", "desktop", "bluetooth", "region", "users", "printers", "services" };
const page_descriptions = [_][]const u8{
"Everyday controls, all in one place.", "Make your mouse and keyboard feel right.",
"Arrangement, resolution, refresh rate and scaling.", "Volume, microphones and output devices.",
"Wired and wireless connections.", "Make your desktop your own.",
"Choose the keys for your everyday actions.", "Configure your desktop canvas and panning area.",
"Connect and manage your Bluetooth devices.", "Your language, regional formats and calendar preferences.",
- "Review login accounts and automatic-login settings.", "Manage and analyze systemd services.",
+ "Review login accounts and automatic-login settings.", "Printer status, jobs and connection diagnostics.",
+ "Manage and analyze systemd services.",
};
-const page_icons = [_]layout.IconId{ .settings, .mouse, .display, .music, .wifi, .settings, .keyboard, .squares, .bluetooth, .globe, .users, .settings };
+const page_icons = [_]layout.IconId{ .settings, .mouse, .display, .music, .wifi, .settings, .keyboard, .squares, .bluetooth, .globe, .users, .print, .settings };
const max_devices = 16;
pub fn palette() theme.Theme {
@@ -218,6 +220,7 @@ pub const ControlCenter = struct {
network: network_section.Section = .{},
bluetooth: bluetooth_section.Section = .{},
services: services_section.Section = .{},
+ printers: printers_section.Section = .{},
systemd_client: ?*systemd.Client = null,
pub const min_width = 420;
@@ -311,6 +314,7 @@ pub const ControlCenter = struct {
if (cc.systemd_client) |client| client.detachSettings();
cc.welcome.deinit();
cc.services.deinit();
+ cc.printers.deinit();
cc.network.deinit();
if (cc.page == .bluetooth) if (cc.server.bluetooth) |m| m.closed();
cc.bluetooth.deinit();
@@ -434,6 +438,7 @@ pub const ControlCenter = struct {
cc.services.capture();
if (cc.page == .bluetooth and cc.built_page == .bluetooth) cc.bluetooth.capture();
if (cc.page == .network and cc.built_page == .network) cc.network.captureFocus();
+ if (cc.page == .printers and cc.built_page == .printers) cc.printers.capture();
if (cc.page == .appearance) appearance_section.captureItemFocus(&cc.appearance);
ui.input.reset();
const has_services = if (cc.systemd_client) |client| client.available() else false;
@@ -508,6 +513,10 @@ pub const ControlCenter = struct {
services_section.build(&cc.services, cc);
cc.append(cc.services.root);
},
+ .printers => {
+ printers_section.build(&cc.printers, cc);
+ cc.append(cc.printers.root);
+ },
.shortcuts => {
shortcut_section.build(&cc.shortcuts, cc);
for (cc.shortcuts.groups[0..cc.shortcuts.group_count]) |widget| cc.append(widget);
@@ -694,6 +703,7 @@ pub const ControlCenter = struct {
cc.shortcuts.cancel();
// The service list is only kept live while its page is on screen.
if (cc.page == .services and page != .services) if (cc.systemd_client) |client| client.hide();
+ if (cc.page == .printers and page != .printers) cc.printers.hide();
if (cc.page == .network and page != .network) cc.network.clearForm();
if (cc.page == .bluetooth and page != .bluetooth) {
if (cc.server.bluetooth) |m| m.closed();
@@ -705,11 +715,11 @@ pub const ControlCenter = struct {
if (cc.panel_box.width == default_width) _ = cc.toplevel.requestSize(1120, cc.panel_box.height);
if (cc.server.bluetooth) |m| m.opened() else cc.server.bluetooth = @import("../bluetooth.zig").Manager.create(cc.server) catch null;
}
- if (page == .network) {
+ if (page == .network or page == .printers) {
// Start wide enough for the two columns; narrower resized windows
// stack them and keep the same controls accessible.
if (cc.panel_box.width == default_width) _ = cc.toplevel.requestSize(1120, cc.panel_box.height);
- if (cc.server.network) |manager| manager.opened();
+ if (page == .network) if (cc.server.network) |manager| manager.opened();
}
if (cc.panel_box.width < cc.minimumWidth() or cc.panel_box.height < cc.minimumHeight()) {
_ = cc.toplevel.requestSize(@max(cc.panel_box.width, cc.minimumWidth()), @max(cc.panel_box.height, cc.minimumHeight()));
@@ -739,7 +749,7 @@ pub const ControlCenter = struct {
/// Route select keys before panel-level Escape. Tab cycles display fields.
pub fn selectKey(cc: *ControlCenter, key: ui.input.Key, shift: bool) bool {
- if (cc.page != .displays and cc.page != .appearance and cc.page != .desktop and cc.page != .general and cc.page != .users and cc.page != .services and cc.page != .network and cc.page != .bluetooth and cc.page != .region) return false;
+ if (cc.page != .displays and cc.page != .appearance and cc.page != .desktop and cc.page != .general and cc.page != .users and cc.page != .services and cc.page != .printers and cc.page != .network and cc.page != .bluetooth and cc.page != .region) return false;
const dispatcher = &ui.input.current;
if (cc.page == .appearance) {
if (appearance_section.itemKey(&cc.appearance, key)) return true;
@@ -756,7 +766,7 @@ pub const ControlCenter = struct {
}
}
}
- if (cc.is_welcome or cc.page == .users or cc.page == .services or cc.page == .network or cc.page == .bluetooth or cc.page == .region) {
+ if (cc.is_welcome or cc.page == .users or cc.page == .services or cc.page == .printers or cc.page == .network or cc.page == .bluetooth or cc.page == .region) {
const focused = dispatcher.focused;
if (cc.page == .bluetooth and bluetooth_section.key(cc, key)) return true;
if (cc.page == .network and (focused == null or focused.?.kind != .select or !focused.?.kind.select.open)) {
@@ -992,6 +1002,7 @@ pub const ControlCenter = struct {
if (cc.page == .appearance) appearance_section.restoreItemFocus(&cc.appearance);
if (cc.page == .network) network_section.restoreFocus(&cc.network, cc);
if (cc.page == .bluetooth) bluetooth_section.restoreFocus(&cc.bluetooth, cc);
+ if (cc.page == .printers) cc.printers.restoreFocus(cc);
cc.dirty = true;
}
@@ -1006,6 +1017,7 @@ pub const ControlCenter = struct {
.desktop => &.{760},
.bluetooth => &.{ 900, 1000 },
.network => &.{1000},
+ .printers => &.{1050},
.region => &.{900},
.services => &.{ 660, 752, 928, 1040 },
else => &.{},
diff --git a/src/control_center/sections/printers.zig b/src/control_center/sections/printers.zig
new file mode 100644
index 0000000..0d8057d
--- /dev/null
+++ b/src/control_center/sections/printers.zig
@@ -0,0 +1,1311 @@
+//! Printer setup, queue settings and explicit diagnostic print workflows.
+const std = @import("std");
+const ui = @import("ui");
+const panel = @import("../panel.zig");
+const printing = @import("../../printing/client.zig");
+const cups = @import("../../printing/cups.zig");
+const ladder = @import("../../printing/ladder.zig");
+const usb = @import("../../printing/usb_sysfs.zig");
+const admin = @import("../../printing/admin.zig");
+const setup = @import("../../printing/setup.zig");
+const tools = @import("../../printing/tools.zig");
+const preferences = @import("../../printing/preferences.zig");
+const known = @import("../../printing/known_devices.zig");
+const notifier = @import("../../printing/notifier.zig");
+const driver_options = @import("../../printing/options.zig");
+const gpa = @import("../../main.zig").gpa;
+const W = ui.layout.Widget;
+const A = std.mem.Allocator;
+const Form = enum { none, add, connection, remove, test_confirm, test_result, queue_rename };
+const Field = enum { address, name, rename, loaded_width, loaded_height, measured_width, measured_height, raw_dpi, queue_name };
+const field_names = [_][]const u8{ "printers_address", "printers_name", "printers_rename", "printers_loaded_width", "printers_loaded_height", "printers_measured_width", "printers_measured_height", "printers_raw_dpi", "printers_queue_name" };
+const Input = struct { widget: ?*W = null, data: ?ui.layout.TextInputData = null };
+const RangeDraft = struct { name: [128]u8 = undefined, len: usize = 0, range: cups.ipp.Range = .{ .lower = 0, .upper = 0 }, value: f32 = 0 };
+const PendingAdd = struct {
+ arena: std.heap.ArenaAllocator,
+ arguments: admin.Add,
+ fn destroy(self: *PendingAdd) void {
+ self.arena.deinit();
+ gpa.destroy(self);
+ }
+};
+const PendingRename = struct { old: [128]u8 = undefined, old_len: usize = 0, new: [128]u8 = undefined, new_len: usize = 0, after_admin: bool = false };
+const PendingOption = struct { queue: [128]u8 = undefined, queue_len: usize = 0, key: [128]u8 = undefined, key_len: usize = 0, value: [1024]u8 = undefined, value_len: usize = 0, ppd: bool = false, after_admin: bool = false };
+
+pub const Section = struct {
+ arena: std.heap.ArenaAllocator = .init(gpa),
+ root: W = undefined,
+ client: ?*printing.Client = null,
+ administration: ?*admin.Manager = null,
+ listener: ?*notifier.Listener = null,
+ listener_attempted: bool = false,
+ admin_generation: u64 = 0,
+ form: Form = .none,
+ fields: [field_names.len]Input = @splat(.{}),
+ focused_field: ?Field = null,
+ message: []const u8 = "",
+ driver_index: usize = 0,
+ driver_name: [1024]u8 = undefined,
+ driver_name_len: usize = 0,
+ pending_add: ?*PendingAdd = null,
+ pending_rename: ?PendingRename = null,
+ pending_option: ?PendingOption = null,
+ migration_pending: bool = false,
+ queue_refs: []const []const u8 = &.{},
+ driver_refs: []const []const u8 = &.{},
+ device_refs: []const admin.Device = &.{},
+ ranges: [16]RangeDraft = @splat(.{}),
+ range_count: usize = 0,
+ add_discovered: bool = false,
+ add_device_id: [8192]u8 = undefined,
+ add_device_len: usize = 0,
+ language: ?tools.Language = null,
+ test_kind: printing.TestKind = .driver,
+ inches: bool = false,
+ suggested: ?cups.ipp.Resolution = null,
+ show_diagnostics: bool = false,
+ fields_for: [512]u8 = undefined,
+ fields_for_len: usize = 0,
+ probe_address: [8192]u8 = undefined,
+ probe_address_len: usize = 0,
+ option_refs: []const @import("../../printing/options.zig").Option = &.{},
+ selected: [512]u8 = undefined,
+ selected_len: usize = 0,
+ copied: bool = false,
+ pub fn capture(self: *Section) void {
+ self.focused_field = null;
+ if (ui.input.current.focused) |focused| {
+ for (self.fields, 0..) |field, i| if (field.widget == focused) {
+ self.focused_field = @enumFromInt(i);
+ };
+ }
+ }
+ fn saveFields(self: *Section) void {
+ for (&self.fields) |*field| {
+ if (field.widget) |widget| field.data = widget.kind.text_input;
+ field.widget = null;
+ }
+ }
+ pub fn restoreFocus(self: *Section, cc: *panel.ControlCenter) void {
+ if (self.focused_field) |id| if (self.fields[@intFromEnum(id)].widget) |widget| ui.input.current.focus(&cc.root, widget);
+ }
+ pub fn hide(self: *Section) void {
+ self.saveFields();
+ if (self.pending_add) |pending| pending.destroy();
+ self.pending_add = null;
+ self.pending_rename = null;
+ self.pending_option = null;
+ self.migration_pending = false;
+ if (self.administration) |manager| manager.destroy();
+ self.administration = null;
+ if (self.client) |client| client.destroy();
+ self.client = null;
+ if (self.listener) |listener| listener.destroy();
+ self.listener = null;
+ self.listener_attempted = false;
+ self.form = .none;
+ self.focused_field = null;
+ self.copied = false;
+ }
+ pub fn deinit(self: *Section) void {
+ self.hide();
+ for (self.fields) |field| if (field.data) |data| gpa.free(data.value);
+ self.arena.deinit();
+ }
+};
+
+fn text(value: []const u8, dim: bool) W {
+ const t = panel.palette();
+ return .{ .kind = .{ .text = .{ .content = value, .font_size = t.app_text_size, .weight = if (dim) 400 else 600, .color = if (dim) t.dim else t.fg } }, .width = .{ .percent = 1 } };
+}
+fn named(value: W, name: []const u8) W {
+ var result = value;
+ result.name = name;
+ return result;
+}
+fn group(a: A, items: []const W) !W {
+ return .{ .kind = .container, .direction = .column, .gap = 10, .width = .{ .percent = 1 }, .children = try a.dupe(W, items) };
+}
+fn card(a: A, items: []const W) !W {
+ var result = try group(a, items);
+ const t = panel.palette();
+ result.kind = .{ .rect = .{ .color = t.app_item, .radius = t.settings_card_radius, .border_width = 1, .border_color = t.app_item_border } };
+ result.padding = ui.layout.Edges.all(14);
+ return result;
+}
+fn button(cc: *panel.ControlCenter, name: []const u8, label: []const u8, id: usize, disabled: bool, callback: *const fn (?*anyopaque, usize) void) W {
+ return .{ .name = name, .kind = .{ .button = .{ .label = label, .owner = cc, .id = id, .on_click = callback, .state = if (disabled) .disabled else .idle } }, .height = .{ .fixed = 34 } };
+}
+fn changed(raw: *anyopaque) void {
+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(raw));
+ cc.printers.copied = false;
+ if (cc.printers.pending_add != null and !cc.printers.client.?.busy) finishCreate(cc);
+ if (cc.printers.pending_rename) |pending| if (!cc.printers.client.?.busy) {
+ if (pending.after_admin) finishRename(cc) else submitRename(cc);
+ };
+ if (cc.printers.migration_pending and !cc.printers.client.?.busy) {
+ cc.printers.fields_for_len = 0;
+ cc.printers.migration_pending = false;
+ }
+ if (cc.printers.pending_option) |pending| if (pending.after_admin and !cc.printers.client.?.busy) verifyOption(cc);
+ cc.refresh();
+}
+fn adminChanged(raw: *anyopaque) void {
+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(raw));
+ if (cc.printers.administration) |manager| if (manager.generation != cc.printers.admin_generation) {
+ cc.printers.admin_generation = manager.generation;
+ cc.printers.form = .none;
+ if (cc.printers.pending_rename) |*pending| pending.after_admin = true;
+ if (cc.printers.pending_option) |*pending| pending.after_admin = true;
+ if (cc.printers.client) |client| client.act(.refresh) catch client.invalidate();
+ };
+ cc.refresh();
+}
+fn cupsChanged(raw: *anyopaque) void {
+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(raw));
+ if (cc.printers.client) |client| client.invalidate();
+}
+pub fn build(self: *Section, cc: *panel.ControlCenter) void {
+ self.saveFields();
+ self.option_refs = &.{};
+ self.queue_refs = &.{};
+ self.driver_refs = &.{};
+ self.device_refs = &.{};
+ _ = self.arena.reset(.retain_capacity);
+ self.root = tree(self, cc, self.arena.allocator()) catch panel.outOfMemory();
+ const width: f32 = @floatFromInt(cc.panel_box.width - @as(i32, if (cc.panel_box.width < 660) 140 else 308));
+ wrapLabels(self.arena.allocator(), &self.root, @max(width, 80)) catch {};
+}
+/// Widget text is single-line. Explanatory paragraphs become ordinary shared
+/// text widgets so long diagnostic reasons remain readable at narrow widths.
+fn wrapLabels(a: A, widget: *W, available: f32) !void {
+ const width = switch (widget.width) {
+ .fixed => |v| v,
+ .percent => |v| available * v,
+ else => available,
+ };
+ const inner = @max(40, width - widget.padding.left - widget.padding.right);
+ if (widget.kind == .text and widget.name == null) {
+ const style = widget.kind.text;
+ const font: ui.text.Font = if (style.family == .mono) .mono else if (style.weight >= 700) .manrope_heavy else if (style.weight >= 600) .manrope_bold else .manrope;
+ if ((ui.text.measureWidthF(style.content, font, style.font_size, 1) catch 0) <= inner) return;
+ var lines: std.ArrayList(W) = .empty;
+ var start: usize = 0;
+ var last_space: ?usize = null;
+ for (style.content, 0..) |ch, i| {
+ if (ch != ' ') continue;
+ if ((ui.text.measureWidthF(style.content[start..i], font, style.font_size, 1) catch 0) > inner) {
+ const end = last_space orelse i;
+ var line = style;
+ line.content = style.content[start..end];
+ try lines.append(a, .{ .kind = .{ .text = line }, .width = .{ .percent = 1 } });
+ start = end + 1;
+ last_space = null;
+ }
+ last_space = i;
+ }
+ if (start < style.content.len) {
+ if ((ui.text.measureWidthF(style.content[start..], font, style.font_size, 1) catch 0) > inner) if (last_space) |end| {
+ if (end > start) {
+ var line = style;
+ line.content = style.content[start..end];
+ try lines.append(a, .{ .kind = .{ .text = line }, .width = .{ .percent = 1 } });
+ start = end + 1;
+ }
+ };
+ var line = style;
+ line.content = style.content[start..];
+ try lines.append(a, .{ .kind = .{ .text = line }, .width = .{ .percent = 1 } });
+ }
+ widget.kind = .container;
+ widget.direction = .column;
+ widget.gap = 2;
+ widget.children = try lines.toOwnedSlice(a);
+ return;
+ }
+ var fixed: f32 = 0;
+ var flex: usize = 0;
+ if (widget.direction == .row) for (widget.children) |child| {
+ switch (child.width) {
+ .fixed => |v| fixed += v,
+ else => flex += 1,
+ }
+ };
+ const share = if (flex > 0) @max(40, (inner - fixed - widget.gap * @as(f32, @floatFromInt(widget.children.len -| 1))) / @as(f32, @floatFromInt(flex))) else inner;
+ for (widget.children) |*child| try wrapLabels(a, child, if (widget.direction == .row and child.width != .fixed) share else inner);
+}
+fn tree(self: *Section, cc: *panel.ControlCenter, a: A) !W {
+ if (cc.server.greeter_mode) return text("Printers are unavailable in the greeter.", true);
+ if (self.client == null) self.client = printing.Client.create(cc.server.io, cc.server.environ, cc.server.wl_server.getEventLoop(), cc, changed) catch return text("Could not start printer diagnostics.", true);
+ const client = self.client.?;
+ 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.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;
+ }
+ if (self.listener) |listener| if (listener.ready) client.enableSubscriptions();
+ };
+ if (state) |snapshot| if (!snapshot.admin_local) {
+ if (self.administration) |manager| manager.destroy();
+ self.administration = null;
+ if (self.listener) |listener| listener.destroy();
+ self.listener = null;
+ self.listener_attempted = false;
+ };
+ const failure: ?anyerror = if (client.failure) |err| err else if (state) |snapshot| if (snapshot.failure) |err| err else snapshot.action_error else null;
+ const status = if (client.busy) "Loading printers…" else if (failure) |err| cups.failure(err) else "Connected to CUPS.";
+ try content.append(a, named(text(status, true), "printers_status"));
+ try content.append(a, button(cc, "printers_refresh", "Refresh", 0, client.busy, refresh));
+ try content.append(a, button(cc, "printers_add", "Add a printer", 0, !canAdmin(self) or busy(self), addClicked));
+ if (self.message.len > 0) try content.append(a, text(self.message, false));
+ if (self.administration) |manager| try content.append(a, text(manager.status, true)) else try content.append(a, text("Printer setup requires the local default CUPS server and cups-pk-helper.", true));
+ if (state) |snapshot| {
+ if (snapshot.action_error) |err| try content.append(a, text(cups.failure(err), false));
+ if (snapshot.failure != null) {
+ try content.append(a, text(snapshot.platform.missing_cups, true));
+ try content.append(a, button(cc, "printers_start", "Start CUPS", 0, !snapshot.admin_local or busy(self) or self.administration == null, startClicked));
+ }
+ if (self.administration) |manager| if (manager.availability == .missing) try content.append(a, text(snapshot.platform.missing_helper, true));
+ if (self.form == .add or self.form == .connection) try content.append(a, try addForm(self, cc, a, snapshot));
+ if (snapshot.cups) |data| {
+ if (data.printers.len == 0) {
+ try content.append(a, text("No printers configured.", false));
+ } else {
+ const selected = selectIndex(self, data.printers);
+ var choices: std.ArrayList(W) = .empty;
+ const queue_refs = try a.alloc([]const u8, data.printers.len);
+ for (data.printers, 0..) |printer, i| {
+ queue_refs[i] = try a.dupe(u8, printer.name);
+ var row = button(cc, try std.fmt.allocPrint(a, "printers_queue_{d}", .{i}), try std.fmt.allocPrint(a, "{s} · {s}{s}", .{ printer.name, cups.printerState(printer.state), if (std.mem.eql(u8, printer.name, data.user_default)) " · Default" else if (printer.is_default) " · System default" else "" }), i, busy(self), select);
+ row.kind.button.leading_icon = .print;
+ if (i == selected) row.kind.button.variant = .primary;
+ try choices.append(a, row);
+ }
+ self.queue_refs = queue_refs;
+ var detail_items: std.ArrayList(W) = .empty;
+ try details(self, cc, a, &detail_items, snapshot, data, data.printers[selected]);
+ var queue_list = try group(a, choices.items);
+ var detail_list = try group(a, detail_items.items);
+ var columns = try group(a, &.{});
+ if (cc.panel_box.width >= 1050) {
+ queue_list.width = .{ .fixed = 210 };
+ detail_list.width = .{ .flex = 1 };
+ columns.direction = .row;
+ columns.@"align" = .start;
+ }
+ columns.children = try a.dupe(W, &.{ queue_list, detail_list });
+ try content.append(a, columns);
+ }
+ }
+ // Attached printers can still be inspected if CUPS is missing or empty.
+ if (snapshot.usb) |inventory| if (inventory.devices.len > 0) {
+ var devices: std.ArrayList(W) = .empty;
+ try devices.append(a, panel.sectionTitle("Attached USB printers"));
+ for (inventory.devices) |device| {
+ try devices.append(a, text(try std.fmt.allocPrint(a, "{s} {s} ({x:0>4}:{x:0>4})", .{ device.manufacturer, device.product, device.vid, device.pid }), true));
+ if (known.lookup(device.vid, device.pid)) |hint| {
+ try devices.append(a, text(hint.note, true));
+ try devices.append(a, text(hint.driver_project, true));
+ }
+ if (device.nodes.len == 0) try devices.append(a, text("No usblp node was found; CUPS may still use libusb or ipp-usb.", true));
+ }
+ try content.append(a, try card(a, devices.items));
+ };
+ }
+ return group(a, content.items);
+}
+fn selectIndex(self: *Section, printers: []const cups.Printer) usize {
+ for (printers, 0..) |printer, i| if (std.mem.eql(u8, printer.name, self.selected[0..self.selected_len])) return i;
+ self.form = .none;
+ self.selected_len = @min(printers[0].name.len, self.selected.len);
+ @memcpy(self.selected[0..self.selected_len], printers[0].name[0..self.selected_len]);
+ return 0;
+}
+fn splitReasons(a: A, values: []const u8) ![]const []const u8 {
+ var out: std.ArrayList([]const u8) = .empty;
+ var parts = std.mem.splitSequence(u8, values, ", ");
+ while (parts.next()) |part| if (part.len > 0) {
+ try out.append(a, part);
+ };
+ return out.toOwnedSlice(a);
+}
+fn showReasons(a: A, content: *std.ArrayList(W), values: []const u8) !void {
+ for (try splitReasons(a, values)) |reason| {
+ const label = ladder.reasonText(reason) orelse reason;
+ if (!std.mem.eql(u8, reason, "none")) try content.append(a, text(try a.dupe(u8, label), true));
+ }
+}
+fn resolution(value: ?cups.ipp.Resolution) ?ladder.Resolution {
+ const r = value orelse return null;
+ if (r.x <= 0 or r.y <= 0) return null;
+ const x = if (r.units == .dpi) r.x else @divTrunc(@as(i64, r.x) * 254 + 50, 100);
+ const y = if (r.units == .dpi) r.y else @divTrunc(@as(i64, r.y) * 254 + 50, 100);
+ if (x > std.math.maxInt(u32) or y > std.math.maxInt(u32)) return null;
+ return .{ .x_dpi = @intCast(x), .y_dpi = @intCast(y) };
+}
+fn diagnostic(a: A, state: *const printing.State, data: cups.Snapshot, printer: cups.Printer) !ladder.Input {
+ const uri = printer.device_uri;
+ const connection: ladder.Connection = if (std.mem.startsWith(u8, uri, "usb://") or printer.node_kind != null) .usb else if (std.mem.startsWith(u8, uri, "ipp://") or std.mem.startsWith(u8, uri, "ipps://") or std.mem.startsWith(u8, uri, "socket://") or std.mem.startsWith(u8, uri, "lpd://") or std.mem.startsWith(u8, uri, "dnssd://")) .network else .other;
+ var input: ladder.Input = .{
+ .connection = connection,
+ .cups_reachable = true,
+ .network_reachable = printer.network_reachable,
+ .distribution = @tagName(state.platform.distro),
+ .cups_version = data.cups_version,
+ .node_kind = printer.node_kind,
+ .usb_backend = if (printer.node_kind != null) .device_node else .unknown,
+ .settings_consistent = !printer.inconsistent_defaults,
+ .queue = .{ .state = switch (printer.state orelse 0) {
+ 3 => .idle,
+ 4 => .processing,
+ 5 => .stopped,
+ else => .unknown,
+ }, .accepting = printer.accepting, .reasons = try splitReasons(a, printer.reasons), .uri = uri, .default_media = printer.media, .resolution = resolution(printer.resolution) },
+ };
+ if (printer.user.expected_media) |expected| if (mediaFor(printer, state)) |actual| {
+ input.expected_media = if (@abs(expected.width_mm - actual.width_mm) <= 1 and @abs(expected.height_mm - actual.height_mm) <= 1) printer.media else "different-loaded-size";
+ };
+ if (state.usb) |*inventory| {
+ const match = usb.matchQueue(inventory, uri);
+ input.usb = match.device;
+ input.usb_scan_complete = match.conclusive;
+ }
+ for (data.jobs) |job| if (job.own and std.mem.eql(u8, job.printer, printer.name)) {
+ input.last_job = .{
+ .state = switch (job.state orelse 0) {
+ 3 => .pending,
+ 4 => .held,
+ 5 => .processing,
+ 6 => .stopped,
+ 7 => .canceled,
+ 8 => .aborted,
+ 9 => .completed,
+ else => .unknown,
+ },
+ .sheets_completed = if (job.sheets) |n| if (n >= 0) @intCast(n) else null else null,
+ .reasons = try splitReasons(a, job.reasons),
+ .message = job.message,
+ };
+ break;
+ };
+ return input;
+}
+fn details(self: *Section, cc: *panel.ControlCenter, a: A, content: *std.ArrayList(W), state: *const printing.State, data: cups.Snapshot, printer: cups.Printer) !void {
+ if (std.mem.eql(u8, state.selected, printer.name) and !std.mem.eql(u8, self.fields_for[0..self.fields_for_len], printer.name)) {
+ self.fields_for_len = @min(printer.name.len, self.fields_for.len);
+ @memcpy(self.fields_for[0..self.fields_for_len], printer.name[0..self.fields_for_len]);
+ try setField(self, .rename, if (printer.info.len != 0) printer.info else printer.name);
+ try setField(self, .queue_name, printer.name);
+ const media = printer.user.expected_media orelse mediaFor(printer, state) orelse tools.Media{ .width_mm = 0, .height_mm = 0 };
+ try setField(self, .loaded_width, if (media.width_mm > 0) try std.fmt.allocPrint(a, "{d:.2}", .{media.width_mm}) else "");
+ try setField(self, .loaded_height, if (media.height_mm > 0) try std.fmt.allocPrint(a, "{d:.2}", .{media.height_mm}) else "");
+ try setField(self, .measured_width, "");
+ try setField(self, .measured_height, "");
+ try setField(self, .raw_dpi, if (resolution(printer.resolution)) |r| try std.fmt.allocPrint(a, "{d}", .{r.x_dpi}) else "");
+ self.inches = false;
+ self.language = printer.user.language;
+ if (self.language == null) {
+ const detected = tools.detectLanguages(a, printer.device_id) catch &.{};
+ if (detected.len == 1) self.language = detected[0];
+ }
+ self.suggested = null;
+ self.range_count = 0;
+ }
+ if (!std.mem.eql(u8, state.selected, printer.name) and !self.client.?.busy) self.client.?.act(.{ .select = printer.name }) catch {};
+ if (!self.client.?.busy and self.form != .test_confirm and self.form != .test_result) {
+ self.language = printer.user.language;
+ if (self.language == null) {
+ const detected = tools.detectLanguages(a, printer.device_id) catch &.{};
+ if (detected.len == 1) self.language = detected[0];
+ }
+ }
+ var header: std.ArrayList(W) = .empty;
+ try header.append(a, panel.sectionTitle(try a.dupe(u8, if (printer.info.len > 0) printer.info else printer.name)));
+ try header.append(a, text(try std.fmt.allocPrint(a, "Queue: {s}", .{printer.name}), true));
+ try header.append(a, text(try a.dupe(u8, printer.model), true));
+ try header.append(a, named(text(cups.printerState(printer.state), false), "printers_state"));
+ try showReasons(a, &header, printer.reasons);
+ if (printer.message.len > 0) try header.append(a, text(try a.dupe(u8, printer.message), true));
+ for (printer.markers) |marker| {
+ try header.append(a, text(if (marker.level) |level| try std.fmt.allocPrint(a, "{s}: {d}%", .{ marker.name, level }) else try std.fmt.allocPrint(a, "{s}: level unavailable", .{marker.name}), true));
+ if (marker.level) |level| {
+ const fill = try a.create(W);
+ fill.* = .{ .kind = .{ .rect = .{ .color = panel.palette().accent, .radius = 3 } }, .width = .{ .percent = @as(f32, @floatFromInt(level)) / 100 }, .height = .{ .fixed = 6 } };
+ try header.append(a, .{ .kind = .{ .rect = .{ .color = panel.palette().border_soft, .radius = 3 } }, .width = .{ .percent = 1 }, .height = .{ .fixed = 6 }, .children = fill[0..1] });
+ }
+ }
+ try header.append(a, button(cc, "printers_resume", "Resume printer", 0, !canAdmin(self) or busy(self) or printer.state != 5, resumeClicked));
+ try header.append(a, button(cc, "printers_disable", "Disable printer", 0, !canAdmin(self) or busy(self) or printer.state == 5, disableClicked));
+ try header.append(a, button(cc, "printers_accepting", if (printer.accepting == false) "Accept jobs" else "Stop accepting jobs", 0, !canAdmin(self) or busy(self), acceptingClicked));
+ try header.append(a, button(cc, "printers_connection", "Change connection…", 0, !canAdmin(self) or busy(self), connectionClicked));
+ try content.append(a, try card(a, header.items));
+
+ var rows: std.ArrayList(W) = .empty;
+ try rows.append(a, panel.sectionTitle("Connection and print diagnostics"));
+ const input = try diagnostic(a, state, data, printer);
+ const result = ladder.evaluate(input);
+ const layer_names = [_][]const u8{ "Connection", "Device node", "CUPS", "Queue", "Backend", "Media and resolution", "Last job" };
+ try rows.append(a, button(cc, "printers_diagnostics", if (self.show_diagnostics) "Collapse diagnostic ladder" else "Show diagnostic ladder", 0, false, diagnosticsClicked));
+ for (result.rows, layer_names, 0..) |row, name, index| {
+ if (!self.show_diagnostics and result.firstFailure() != index) continue;
+ try rows.append(a, text(try std.fmt.allocPrint(a, "{s} · {s}: {s}", .{ switch (row.verdict) {
+ .pass => "Pass",
+ .fail => "Problem",
+ .unknown => "Unknown",
+ }, name, row.message }), row.verdict != .fail));
+ if (result.firstFailure()) |first| if (result.rows[first].layer == row.layer and row.fix.len > 0) try rows.append(a, text(row.fix, true));
+ }
+ try content.append(a, try card(a, rows.items));
+ var options: std.ArrayList(W) = .empty;
+ try options.append(a, panel.sectionTitle("Queue settings"));
+ try options.append(a, text(try std.fmt.allocPrint(a, "Paper: {s}", .{if (printer.media.len > 0) printer.media else "Unavailable"}), true));
+ if (resolution(printer.resolution)) |r| {
+ try options.append(a, text(try std.fmt.allocPrint(a, "Resolution: {d} × {d} dpi", .{ r.x_dpi, r.y_dpi }), true));
+ } else try options.append(a, text("Resolution: Unavailable", true));
+ if (printer.color.len > 0) try options.append(a, text(try std.fmt.allocPrint(a, "Colour: {s}", .{printer.color}), true));
+ if (printer.sides.len > 0) try options.append(a, text(try std.fmt.allocPrint(a, "Sides: {s}", .{printer.sides}), true));
+ if (std.mem.eql(u8, state.selected, printer.name)) for (state.groups) |option_group| for (option_group.options) |option| {
+ if (!std.mem.eql(u8, option.name, "PageSize")) continue;
+ if (@import("../../printing/options.zig").ppdMargins(state.ppd, option.default orelse continue)) |margins| {
+ try options.append(a, text(try std.fmt.allocPrint(a, "Margins (mm): left {d:.1}, right {d:.1}, top {d:.1}, bottom {d:.1}", .{ margins.left_mm, margins.right_mm, margins.top_mm, margins.bottom_mm }), true));
+ }
+ };
+ var refs: std.ArrayList(@import("../../printing/options.zig").Option) = .empty;
+ if (std.mem.eql(u8, state.selected, printer.name)) for (state.groups) |option_group| {
+ try options.append(a, panel.sectionTitle(try a.dupe(u8, option_group.label)));
+ for (option_group.options) |option| {
+ if (option.source == .ipp and (std.mem.eql(u8, option.name, "print-color-mode") or std.mem.eql(u8, option.name, "print-quality"))) continue;
+ const editable = state.ppd.len > 0 and driver_options.queueEditable(option, state.groups) and (option.range == null or option.source == .ppd);
+ if (option.choices.len == 0) {
+ if (option.range) |range| {
+ if (option.name.len > 128 or range.upper > 16_777_216) continue;
+ var index: ?usize = null;
+ for (self.ranges[0..self.range_count], 0..) |draft, i| if (std.mem.eql(u8, draft.name[0..draft.len], option.name)) {
+ index = i;
+ break;
+ };
+ if (index == null and self.range_count < self.ranges.len) {
+ index = self.range_count;
+ self.range_count += 1;
+ const draft = &self.ranges[index.?];
+ draft.len = option.name.len;
+ @memcpy(draft.name[0..draft.len], option.name);
+ draft.value = @floatFromInt(std.fmt.parseInt(i32, option.default orelse "", 10) catch range.lower);
+ }
+ const draft = &self.ranges[index orelse continue];
+ draft.range = range;
+ draft.value = std.math.clamp(draft.value, @as(f32, @floatFromInt(range.lower)), @as(f32, @floatFromInt(range.upper)));
+ try options.append(a, text(try a.dupe(u8, option.label), false));
+ if (canAdmin(self) and !busy(self) and editable) {
+ try options.append(a, .{ .name = try std.fmt.allocPrint(a, "printers_range_{s}", .{option.name}), .kind = .{ .stepper = .{ .value = draft.value, .min = @floatFromInt(range.lower), .max = @floatFromInt(range.upper), .step = 1, .owner = cc, .id = index.?, .on_change = rangeChanged } }, .width = .{ .percent = 1 }, .height = .{ .fixed = 34 } });
+ try options.append(a, button(cc, try std.fmt.allocPrint(a, "printers_option_{s}_apply", .{option.name}), "Apply value", index.?, false, rangeApply));
+ } else {
+ try options.append(a, text(try std.fmt.allocPrint(a, "{d:.0} (supported {d}–{d})", .{ draft.value, range.lower, range.upper }), true));
+ if (!editable) try options.append(a, text("This range has no selectable queue setting in the current driver.", true));
+ }
+ }
+ continue;
+ }
+ const labels = try a.alloc([]const u8, option.choices.len);
+ var selected: usize = 0;
+ for (option.choices, 0..) |choice, index| {
+ labels[index] = try a.dupe(u8, choice.label);
+ if (option.default) |value| if (std.mem.eql(u8, value, choice.value)) {
+ selected = index;
+ };
+ }
+ const id = refs.items.len;
+ const choices = try a.alloc(@import("../../printing/options.zig").Choice, option.choices.len);
+ for (option.choices, 0..) |choice, i| choices[i] = .{ .value = try a.dupe(u8, choice.value), .label = labels[i] };
+ try refs.append(a, .{ .name = try a.dupe(u8, option.name), .label = try a.dupe(u8, option.label), .choices = choices, .source = option.source });
+ try options.append(a, text(try a.dupe(u8, option.label), false));
+ try options.append(a, .{ .name = try std.fmt.allocPrint(a, "printers_option_{s}", .{option.name}), .kind = .{ .select = .{ .labels = labels, .selected = selected, .disabled = !canAdmin(self) or busy(self) or !editable, .owner = cc, .id = id, .on_change = optionChanged } }, .height = .{ .fixed = 34 }, .width = .{ .percent = 1 } });
+ if (!editable) try options.append(a, text("This capability has no selectable queue default in the current driver.", true));
+ }
+ };
+ self.option_refs = refs.items;
+ try options.append(a, button(cc, "printers_default", if (std.mem.eql(u8, data.user_default, printer.name)) "Your default printer" else "Set as my default", 0, busy(self), defaultClicked));
+ if (preferences.overrideMessage(cc.server.environ)) |message| try options.append(a, text(message, true));
+ try options.append(a, button(cc, "printers_system_default", "Set as system default", 0, !canAdmin(self) or busy(self) or printer.is_default, systemDefaultClicked));
+ try options.append(a, try entry(self, cc, a, .rename, "Display name", ""));
+ try options.append(a, button(cc, "printers_rename_save", "Save display name", 0, !canAdmin(self) or busy(self), renameClicked));
+ try options.append(a, try entry(self, cc, a, .queue_name, "Queue identifier", ""));
+ try options.append(a, button(cc, "printers_queue_rename", "Change queue identifier…", 0, !canAdmin(self) or busy(self) or std.ascii.eqlIgnoreCase(fieldValue(self, .queue_name), printer.name), queueRenameClicked));
+ if (self.form == .queue_rename) {
+ try options.append(a, text(try std.fmt.allocPrint(a, "Change {s} to {s}?", .{ printer.name, fieldValue(self, .queue_name) }), false));
+ try options.append(a, text("CUPS copies the queue and removes its old identifier. Finish all jobs first. Check the resulting driver options afterwards.", true));
+ try options.append(a, button(cc, "printers_queue_rename_confirm", "Change this queue identifier", 0, !canAdmin(self) or busy(self), queueRenameConfirm));
+ try options.append(a, button(cc, "printers_queue_rename_cancel", "Keep identifier", 0, busy(self), dismiss));
+ }
+ try content.append(a, try card(a, options.items));
+
+ var jobs: std.ArrayList(W) = .empty;
+ try jobs.append(a, panel.sectionTitle("Your recent jobs"));
+ var count: usize = 0;
+ for (data.jobs) |job| {
+ if (!job.own or !std.mem.eql(u8, job.printer, printer.name)) continue;
+ count += 1;
+ try jobs.append(a, text(try std.fmt.allocPrint(a, "Job {d} · {s}", .{ job.id, cups.jobState(job.state) }), false));
+ if (job.sheets) |sheets| if (sheets >= 0) try jobs.append(a, text(try std.fmt.allocPrint(a, "{d} completed sheets reported by CUPS", .{sheets}), true));
+ try showReasons(a, &jobs, job.reasons);
+ if (job.message.len > 0) try jobs.append(a, text(try a.dupe(u8, job.message), true));
+ if (job.cancellable()) try jobs.append(a, button(cc, try std.fmt.allocPrint(a, "printers_cancel_{d}", .{job.id}), "Cancel job", @intCast(job.id), self.client.?.busy, cancel));
+ }
+ if (data.jobs_error) |err| try jobs.append(a, text(cups.failure(err), true)) else if (count == 0) try jobs.append(a, text("No recent jobs available for your account.", true));
+ try content.append(a, try card(a, jobs.items));
+ try content.append(a, try toolsForm(self, cc, a, state, printer));
+ if (self.form == .remove) {
+ try content.append(a, text(try std.fmt.allocPrint(a, "Remove printer {s} ({s})? This deletes its queue and settings.", .{ if (printer.info.len > 0) printer.info else printer.name, printer.name }), false));
+ try content.append(a, button(cc, "printers_remove_confirm", "Remove this printer", 0, !canAdmin(self) or busy(self), removeConfirm));
+ try content.append(a, button(cc, "printers_remove_cancel", "Keep printer", 0, busy(self), dismiss));
+ } else try content.append(a, button(cc, "printers_remove", "Remove printer…", 0, !canAdmin(self) or busy(self), removeClicked));
+ try content.append(a, button(cc, "printers_copy_report", if (self.copied) "Report copied" else "Copy diagnostic report", 0, false, copy));
+ try content.append(a, text("Reports omit document names, user names, USB serials and private printer addresses.", true));
+}
+fn owner(raw: ?*anyopaque) *panel.ControlCenter {
+ return @ptrCast(@alignCast(raw.?));
+}
+fn refresh(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ if (cc.printers.administration) |manager| if (manager.availability == .missing and !manager.busy) {
+ manager.destroy();
+ cc.printers.administration = null;
+ };
+ if (cc.printers.listener) |listener| if (listener.conn.closed) {
+ listener.destroy();
+ cc.printers.listener = null;
+ };
+ if (cc.printers.listener == null) cc.printers.listener_attempted = false;
+ if (cc.printers.client) |client| client.refresh();
+ cc.printers.copied = false;
+ cc.refresh();
+}
+fn select(raw: ?*anyopaque, index: usize) void {
+ const cc = owner(raw);
+ if (busy(&cc.printers)) return;
+ const client = cc.printers.client orelse return;
+ const state = client.current orelse return;
+ const data = state.cups orelse return;
+ if (index >= cc.printers.queue_refs.len) return;
+ const name = cc.printers.queue_refs[index];
+ var found = false;
+ for (data.printers) |printer| if (std.mem.eql(u8, printer.name, name)) {
+ found = true;
+ break;
+ };
+ if (!found) return;
+ cc.printers.selected_len = @min(name.len, cc.printers.selected.len);
+ @memcpy(cc.printers.selected[0..cc.printers.selected_len], name[0..cc.printers.selected_len]);
+ cc.printers.copied = false;
+ cc.printers.form = .none;
+ cc.printers.message = "";
+ client.act(.{ .select = name }) catch {};
+ cc.refresh();
+}
+fn cancel(raw: ?*anyopaque, id: usize) void {
+ const cc = owner(raw);
+ if (id > std.math.maxInt(i32)) return;
+ if (cc.printers.client) |client| client.cancelJob(@intCast(id));
+ cc.refresh();
+}
+fn copy(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ const client = cc.printers.client orelse return;
+ const state = client.current orelse return;
+ const data = state.cups orelse return;
+ if (data.printers.len == 0) return;
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const printer = chosen(cc) orelse return;
+ const input = diagnostic(a, state, data, printer) catch return;
+ const report = ladder.report(a, input) catch return;
+ var output: std.Io.Writer.Allocating = .init(a);
+ output.writer.writeAll(report) catch return;
+ output.writer.print("User observations: driver={s}, raw={s}, ruler={s}\n", .{ @tagName(printer.user.driver), @tagName(printer.user.raw), @tagName(printer.user.ruler) }) catch return;
+ if (printer.user.language) |language| output.writer.print("User-confirmed command language: {s}\n", .{language.label()}) catch return;
+ if (printer.user.expected_media) |media| output.writer.print("Loaded media: {d:.2} x {d:.2} mm\n", .{ media.width_mm, media.height_mm }) catch return;
+ var count: usize = 0;
+ for (data.jobs) |job| if (job.own and std.mem.eql(u8, job.printer, printer.name) and count < 10) {
+ output.writer.print("Recent job: state={s}; sheets={d}\n", .{ cups.jobState(job.state), job.sheets orelse -1 }) catch return;
+ count += 1;
+ };
+ @import("../../clipboard.zig").copyText(cc.server, output.written());
+ cc.printers.copied = true;
+ cc.refresh();
+}
+
+fn busy(self: *Section) bool {
+ return (if (self.client) |client| client.busy else true) or (if (self.administration) |manager| manager.busy else false);
+}
+fn canAdmin(self: *Section) bool {
+ const client = self.client orelse return false;
+ const state = client.current orelse return false;
+ const manager = self.administration orelse return false;
+ return state.admin_local and client.failure == null and state.failure == null and state.cups != null and manager.availability == .available;
+}
+fn chosen(cc: *panel.ControlCenter) ?cups.Printer {
+ if (!std.mem.eql(u8, cc.printers.selected[0..cc.printers.selected_len], cc.printers.fields_for[0..cc.printers.fields_for_len])) return null;
+ const client = cc.printers.client orelse return null;
+ const state = client.current orelse return null;
+ const data = state.cups orelse return null;
+ for (data.printers) |printer| if (std.mem.eql(u8, printer.name, cc.printers.selected[0..cc.printers.selected_len])) return printer;
+ return null;
+}
+fn fieldValue(self: *Section, id: Field) []const u8 {
+ const input = self.fields[@intFromEnum(id)];
+ return if (input.widget) |widget| widget.kind.text_input.value else if (input.data) |data| data.value else "";
+}
+fn setField(self: *Section, id: Field, text_value: []const u8) !void {
+ const input = &self.fields[@intFromEnum(id)];
+ const copy_value = try gpa.dupe(u8, text_value);
+ if (input.widget) |widget| input.data = widget.kind.text_input;
+ if (input.data) |*data| {
+ gpa.free(data.value);
+ data.value = copy_value;
+ data.cursor_pos = copy_value.len;
+ data.selection_anchor = null;
+ if (input.widget) |widget| widget.kind.text_input = data.*;
+ } else input.data = .{ .owner = null, .id = @intFromEnum(id), .placeholder = "", .value = copy_value, .cursor_pos = copy_value.len, .on_change = fieldChanged };
+}
+fn entry(self: *Section, cc: *panel.ControlCenter, a: A, id: Field, label: []const u8, initial: []const u8) !W {
+ const input = &self.fields[@intFromEnum(id)];
+ if (input.data == null) try setField(self, id, initial);
+ var data = input.data.?;
+ data.owner = cc;
+ data.id = @intFromEnum(id);
+ data.placeholder = label;
+ data.on_change = fieldChanged;
+ const widget: W = .{ .name = field_names[@intFromEnum(id)], .kind = .{ .text_input = data }, .width = .{ .percent = 1 }, .height = .{ .fixed = 36 } };
+ const container = try group(a, &.{ text(label, true), widget });
+ input.widget = &container.children[1];
+ return container;
+}
+fn fieldChanged(raw: ?*anyopaque, id: usize, _: []const u8) void {
+ const cc = owner(raw);
+ if (id == @intFromEnum(Field.address)) {
+ cc.printers.add_discovered = false;
+ cc.printers.probe_address_len = 0;
+ cc.printers.add_device_len = 0;
+ cc.printers.driver_name_len = 0;
+ cc.printers.driver_index = 0;
+ }
+ cc.printers.suggested = null;
+ cc.refresh();
+}
+fn queueNames(a: A, data: cups.Snapshot) ![]const []const u8 {
+ const names = try a.alloc([]const u8, data.printers.len);
+ for (data.printers, 0..) |printer, i| names[i] = printer.name;
+ return names;
+}
+fn runAdmin(cc: *panel.ControlCenter, action: admin.Action) void {
+ if (busy(&cc.printers) or (action != .start_service and !canAdmin(&cc.printers))) return;
+ if (action == .start_service) {
+ const client = cc.printers.client orelse return;
+ const state = client.current orelse return;
+ if (!state.admin_local) return;
+ }
+ const manager = cc.printers.administration orelse return;
+ manager.request(action) catch |err| {
+ cc.printers.message = switch (err) {
+ error.QueueExists => "A printer with this queue name already exists. Choose another name.",
+ error.InvalidName => "Use letters, numbers, dots, hyphens or underscores for the queue name.",
+ error.InvalidUri, error.UnsupportedScheme => "Enter a supported printer address without credentials.",
+ error.UntrustedDevice => "Find available printers again and choose the current discovered device.",
+ else => "The printer change could not be requested.",
+ };
+ };
+ cc.refresh();
+}
+fn runClient(cc: *panel.ControlCenter, action: printing.Action) void {
+ const client = cc.printers.client orelse return;
+ client.act(action) catch {
+ cc.printers.message = "Wait for the current printer operation to finish.";
+ };
+ cc.refresh();
+}
+fn dismiss(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ cc.printers.form = .none;
+ cc.refresh();
+}
+fn startClicked(raw: ?*anyopaque, _: usize) void {
+ runAdmin(owner(raw), .start_service);
+}
+fn resumeClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ runAdmin(cc, .{ .enabled = .{ .name = (chosen(cc) orelse return).name, .value = true } });
+}
+fn disableClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ runAdmin(cc, .{ .enabled = .{ .name = (chosen(cc) orelse return).name, .value = false } });
+}
+fn acceptingClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ const p = chosen(cc) orelse return;
+ runAdmin(cc, .{ .accepting = .{ .name = p.name, .value = p.accepting == false } });
+}
+fn defaultClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ runClient(cc, .{ .personal_default = (chosen(cc) orelse return).name });
+}
+fn systemDefaultClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ runAdmin(cc, .{ .system_default = (chosen(cc) orelse return).name });
+}
+fn renameClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ runAdmin(cc, .{ .info = .{ .name = (chosen(cc) orelse return).name, .value = fieldValue(&cc.printers, .rename) } });
+}
+fn removeClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ if (chosen(cc) == null) return;
+ cc.printers.form = .remove;
+ cc.refresh();
+}
+fn removeConfirm(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ if (cc.printers.form != .remove) return;
+ runAdmin(cc, .{ .remove = (chosen(cc) orelse return).name });
+}
+fn diagnosticsClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ cc.printers.show_diagnostics = !cc.printers.show_diagnostics;
+ cc.refresh();
+}
+fn optionChanged(raw: ?*anyopaque, id: usize, index: usize) void {
+ const cc = owner(raw);
+ if (id >= cc.printers.option_refs.len) return;
+ const option = cc.printers.option_refs[id];
+ if (index >= option.choices.len) return;
+ const state = cc.printers.client.?.current orelse return;
+ if (state.ppd.len == 0 or !driver_options.queueEditable(option, state.groups)) return;
+ changeOption(cc, option, option.choices[index].value);
+}
+fn changeOption(cc: *panel.ControlCenter, option: driver_options.Option, value: []const u8) void {
+ const printer = chosen(cc) orelse return;
+ if (busy(&cc.printers) or printer.name.len > 127 or option.name.len > 127 or value.len > 1024) return;
+ var pending: PendingOption = .{ .queue_len = printer.name.len, .key_len = option.name.len, .value_len = value.len, .ppd = option.source == .ppd };
+ @memcpy(pending.queue[0..pending.queue_len], printer.name);
+ @memcpy(pending.key[0..pending.key_len], option.name);
+ @memcpy(pending.value[0..pending.value_len], value);
+ cc.printers.pending_option = pending;
+ runAdmin(cc, .{ .ppd_option = .{ .name = printer.name, .key = option.name, .values = &.{value} } });
+ if (cc.printers.administration) |manager| if (!manager.busy) {
+ cc.printers.pending_option = null;
+ };
+}
+fn verifyOption(cc: *panel.ControlCenter) void {
+ const pending = cc.printers.pending_option orelse return;
+ cc.printers.pending_option = null;
+ const client = cc.printers.client orelse return;
+ const state = client.current orelse return;
+ if (state.failure != null or client.failure != null or state.generation != client.generation) return;
+ const data = state.cups orelse return;
+ for (data.printers) |printer| if (std.mem.eql(u8, printer.name, pending.queue[0..pending.queue_len])) {
+ const option: driver_options.Option = .{ .name = pending.key[0..pending.key_len], .source = if (pending.ppd) .ppd else .ipp };
+ const matches = driver_options.settingMatches(state.groups, printer.attributes, option, pending.value[0..pending.value_len]);
+ cc.printers.message = if (matches) |saved| if (saved) "Printer setting verified." else "The driver did not report the requested value. Review its settings before printing." else "CUPS accepted the change; the resulting driver value could not be verified.";
+ return;
+ };
+}
+fn rangeChanged(raw: ?*anyopaque, id: usize, new_value: f32) void {
+ const cc = owner(raw);
+ if (id >= cc.printers.range_count or busy(&cc.printers)) return;
+ cc.printers.ranges[id].value = new_value;
+}
+fn rangeApply(raw: ?*anyopaque, id: usize) void {
+ const cc = owner(raw);
+ if (id >= cc.printers.range_count) return;
+ const draft = cc.printers.ranges[id];
+ if (!std.math.isFinite(draft.value) or draft.value < @as(f32, @floatFromInt(draft.range.lower)) or draft.value > @as(f32, @floatFromInt(draft.range.upper))) return;
+ var buffer: [32]u8 = undefined;
+ const setting = std.fmt.bufPrint(&buffer, "{d}", .{@as(i32, @intFromFloat(@round(draft.value)))}) catch return;
+ runAdmin(cc, .{ .ppd_option = .{ .name = (chosen(cc) orelse return).name, .key = draft.name[0..draft.len], .values = &.{setting} } });
+}
+fn addClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ const state = cc.printers.client.?.current orelse return;
+ const data = state.cups orelse return;
+ cc.printers.form = .add;
+ cc.printers.driver_index = 0;
+ cc.printers.driver_name_len = 0;
+ cc.printers.add_discovered = false;
+ cc.printers.add_device_len = 0;
+ cc.printers.probe_address_len = 0;
+ cc.printers.message = "";
+ const a = cc.printers.arena.allocator();
+ const name = setup.uniqueName(a, "Printer", queueNames(a, data) catch return) catch return;
+ setField(&cc.printers, .name, name) catch return;
+ runClient(cc, .catalog);
+}
+fn addForm(self: *Section, cc: *panel.ControlCenter, a: A, state: *const printing.State) !W {
+ var items: std.ArrayList(W) = .empty;
+ try items.append(a, panel.sectionTitle(if (self.form == .connection) "Change printer connection" else "Add a printer"));
+ try items.append(a, button(cc, "printers_discover", "Find available printers", 0, !canAdmin(self) or busy(self), discoverClicked));
+ if (self.administration) |manager| {
+ const devices = try a.alloc(admin.Device, manager.devices.len);
+ for (manager.devices, 0..) |device, i| devices[i] = .{ .uri = try a.dupe(u8, device.uri), .make_model = try a.dupe(u8, device.make_model), .info = try a.dupe(u8, device.info), .device_id = try a.dupe(u8, device.device_id) };
+ self.device_refs = devices;
+ }
+ for (self.device_refs, 0..) |device, i| {
+ var used = false;
+ if (state.cups) |data| for (data.printers) |printer| if (std.mem.eql(u8, printer.device_uri, device.uri)) {
+ used = true;
+ };
+ if (used and self.form == .add) continue;
+ try items.append(a, button(cc, try std.fmt.allocPrint(a, "printers_device_{d}", .{i}), try cups.clean(a, if (device.info.len > 0) device.info else device.make_model), i, busy(self), deviceClicked));
+ }
+ try items.append(a, try entry(self, cc, a, .address, "Printer address (ipp, ipps, socket or lpd)", ""));
+ try items.append(a, button(cc, "printers_probe", "Check IPP address", 0, busy(self), probeClicked));
+ if (self.form == .connection) {
+ try items.append(a, text("Select an installed USB backend from discovery, or enter a network address. This changes the connection for the selected queue.", true));
+ try items.append(a, button(cc, "printers_connection_apply", "Apply connection", 0, busy(self) or !canAdmin(self), applyConnectionClicked));
+ try items.append(a, button(cc, "printers_add_cancel", "Keep connection", 0, busy(self), dismiss));
+ return card(a, items.items);
+ }
+ try items.append(a, try entry(self, cc, a, .name, "Queue name", "Printer"));
+ const data = state.cups orelse return card(a, items.items);
+ if (data.drivers_error) |err| try items.append(a, text(cups.failure(err), true));
+ const labels = try a.alloc([]const u8, data.drivers.len + 3);
+ labels[0] = "Choose a driver…";
+ labels[1] = "IPP Everywhere / AirPrint";
+ labels[2] = "Raw queue (printer commands only)";
+ const driver_refs = try a.alloc([]const u8, data.drivers.len);
+ for (data.drivers, 0..) |driver, i| labels[i + 3] = try cups.clean(a, try std.fmt.allocPrint(a, "{s} ({s})", .{ if (driver.model.len > 0) driver.model else "Driver", driver.name }));
+ for (data.drivers, 0..) |driver, i| driver_refs[i] = try a.dupe(u8, driver.name);
+ self.driver_refs = driver_refs;
+ if (self.driver_name_len > 0) {
+ self.driver_index = 0;
+ for (data.drivers, 0..) |driver, i| if (std.mem.eql(u8, driver.name, self.driver_name[0..self.driver_name_len])) {
+ self.driver_index = i + 3;
+ break;
+ };
+ }
+ if (self.driver_index == 0 and self.add_device_len > 0) {
+ const ppds = try a.alloc(setup.Ppd, data.drivers.len);
+ for (data.drivers, 0..) |driver, i| ppds[i] = .{ .name = driver.name, .make_model = driver.model, .device_id = driver.device_id };
+ if (setup.driverMatch(self.add_device_id[0..self.add_device_len], ppds)) |match| {
+ self.driver_index = match + 3;
+ self.driver_name_len = @min(data.drivers[match].name.len, self.driver_name.len);
+ @memcpy(self.driver_name[0..self.driver_name_len], data.drivers[match].name[0..self.driver_name_len]);
+ }
+ }
+ if (state.action_error == null and state.probe == true and std.mem.eql(u8, fieldValue(self, .address), self.probe_address[0..self.probe_address_len]) and self.driver_index == 0) self.driver_index = 1;
+ if (self.driver_index >= labels.len) self.driver_index = 0;
+ try items.append(a, .{ .name = "printers_driver", .kind = .{ .select = .{ .labels = labels, .selected = self.driver_index, .disabled = busy(self), .owner = cc, .on_change = driverChanged } }, .height = .{ .fixed = 34 }, .width = .{ .percent = 1 } });
+ try items.append(a, text("A raw queue passes commands unchanged; ordinary PDF printing needs a compatible driver.", true));
+ if (self.driver_index == 0) try items.append(a, text("No unambiguous automatic driver match. Choose a listed driver, check an IPP address, or explicitly choose a raw queue.", true));
+ try items.append(a, button(cc, "printers_create", "Create printer", 0, busy(self) or !canAdmin(self) or self.driver_index == 0, createClicked));
+ try items.append(a, button(cc, "printers_add_cancel", "Cancel setup", 0, busy(self), dismiss));
+ return card(a, items.items);
+}
+fn discoverClicked(raw: ?*anyopaque, _: usize) void {
+ runAdmin(owner(raw), .discover);
+}
+fn deviceClicked(raw: ?*anyopaque, id: usize) void {
+ const cc = owner(raw);
+ if (id >= cc.printers.device_refs.len) return;
+ const device = cc.printers.device_refs[id];
+ setField(&cc.printers, .address, device.uri) catch return;
+ cc.printers.add_discovered = true;
+ cc.printers.add_device_len = @min(device.device_id.len, cc.printers.add_device_id.len);
+ @memcpy(cc.printers.add_device_id[0..cc.printers.add_device_len], device.device_id[0..cc.printers.add_device_len]);
+ cc.printers.driver_index = 0;
+ cc.printers.driver_name_len = 0;
+ const data = cc.printers.client.?.current.?.cups orelse return;
+ const a = cc.printers.arena.allocator();
+ setField(&cc.printers, .name, setup.uniqueName(a, device.make_model, queueNames(a, data) catch return) catch return) catch return;
+ cc.refresh();
+}
+fn normalizedAddress(a: A, input: []const u8) ![]const u8 {
+ const trimmed = std.mem.trim(u8, input, " \t\r\n");
+ if (std.mem.indexOf(u8, trimmed, "://") != null) return a.dupe(u8, trimmed);
+ return std.fmt.allocPrint(a, "ipp://{s}/ipp/print", .{trimmed});
+}
+fn selectedAddress(self: *Section) ![]const u8 {
+ const value = fieldValue(self, .address);
+ return if (self.add_discovered) self.arena.allocator().dupe(u8, value) else normalizedAddress(self.arena.allocator(), value);
+}
+fn connectionClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ const printer = chosen(cc) orelse return;
+ cc.printers.form = .connection;
+ cc.printers.add_discovered = false;
+ cc.printers.add_device_len = 0;
+ cc.printers.probe_address_len = 0;
+ // Existing non-network backends must be selected again from discovery;
+ // historical queue URIs are not proof that the backend is installed now.
+ const address = if (setup.validateUri(printer.device_uri, false)) printer.device_uri else |_| "";
+ setField(&cc.printers, .address, address) catch return;
+ cc.refresh();
+}
+fn applyConnectionClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ if (cc.printers.form != .connection) return;
+ const printer = chosen(cc) orelse return;
+ const uri = selectedAddress(&cc.printers) catch return;
+ runAdmin(cc, .{ .device = .{ .name = printer.name, .uri = uri, .discovered = cc.printers.add_discovered } });
+}
+fn probeClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ const uri = selectedAddress(&cc.printers) catch return;
+ setup.validateUri(uri, cc.printers.add_discovered) catch {
+ cc.printers.message = "Enter a supported printer address without credentials.";
+ cc.refresh();
+ return;
+ };
+ if (!std.mem.startsWith(u8, uri, "ipp://") and !std.mem.startsWith(u8, uri, "ipps://")) {
+ cc.printers.message = "Address checks support IPP printers. Other connections can be tested with an explicit print after setup.";
+ cc.refresh();
+ return;
+ }
+ setField(&cc.printers, .address, uri) catch return;
+ cc.printers.probe_address_len = @min(uri.len, cc.printers.probe_address.len);
+ @memcpy(cc.printers.probe_address[0..cc.printers.probe_address_len], uri[0..cc.printers.probe_address_len]);
+ runClient(cc, .{ .probe = uri });
+}
+fn driverChanged(raw: ?*anyopaque, _: usize, index: usize) void {
+ const cc = owner(raw);
+ cc.printers.driver_index = index;
+ cc.printers.driver_name_len = 0;
+ if (index >= 3) {
+ if (index - 3 >= cc.printers.driver_refs.len) return;
+ const name = cc.printers.driver_refs[index - 3];
+ cc.printers.driver_name_len = @min(name.len, cc.printers.driver_name.len);
+ @memcpy(cc.printers.driver_name[0..cc.printers.driver_name_len], name[0..cc.printers.driver_name_len]);
+ }
+ cc.refresh();
+}
+fn createClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ if (cc.printers.form != .add or busy(&cc.printers) or !canAdmin(&cc.printers) or cc.printers.pending_add != null) return;
+ const state = cc.printers.client.?.current orelse return;
+ const data = state.cups orelse return;
+ const index = cc.printers.driver_index;
+ if (index == 0 or index >= data.drivers.len + 3) return;
+ const uri = selectedAddress(&cc.printers) catch return;
+ const ppd = if (index == 1) "everywhere" else if (index == 2) "raw" else cc.printers.driver_name[0..cc.printers.driver_name_len];
+ const pending = gpa.create(PendingAdd) catch return;
+ pending.* = .{ .arena = .init(gpa), .arguments = undefined };
+ const mem = pending.arena.allocator();
+ pending.arguments = .{ .name = mem.dupe(u8, fieldValue(&cc.printers, .name)) catch {
+ pending.destroy();
+ return;
+ }, .uri = mem.dupe(u8, uri) catch {
+ pending.destroy();
+ return;
+ }, .ppd = mem.dupe(u8, ppd) catch {
+ pending.destroy();
+ return;
+ }, .discovered = cc.printers.add_discovered };
+ pending.arguments.info = pending.arguments.name;
+ cc.printers.pending_add = pending;
+ runClient(cc, .refresh);
+}
+fn finishCreate(cc: *panel.ControlCenter) void {
+ const pending = cc.printers.pending_add orelse return;
+ cc.printers.pending_add = null;
+ defer pending.destroy();
+ const state = cc.printers.client.?.current orelse return;
+ if (state.failure != null or cc.printers.client.?.failure != null or state.generation != cc.printers.client.?.generation) {
+ cc.printers.message = "Could not verify existing printers. Refresh before creating a queue.";
+ return;
+ }
+ const data = state.cups orelse return;
+ var arguments = pending.arguments;
+ arguments.existing_names = queueNames(pending.arena.allocator(), data) catch return;
+ runAdmin(cc, .{ .add = arguments });
+}
+fn queueRenameClicked(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ const name = fieldValue(&cc.printers, .queue_name);
+ if (!setup.validName(name)) {
+ cc.printers.message = "Use letters, numbers, dots, hyphens or underscores for the queue identifier.";
+ cc.refresh();
+ return;
+ }
+ cc.printers.form = .queue_rename;
+ cc.refresh();
+}
+fn queueRenameConfirm(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ if (cc.printers.form != .queue_rename or busy(&cc.printers)) return;
+ const printer = chosen(cc) orelse return;
+ const name = fieldValue(&cc.printers, .queue_name);
+ if (printer.name.len > 127 or !setup.validName(name)) return;
+ var pending: PendingRename = .{ .old_len = printer.name.len, .new_len = name.len };
+ @memcpy(pending.old[0..pending.old_len], printer.name);
+ @memcpy(pending.new[0..pending.new_len], name);
+ cc.printers.pending_rename = pending;
+ runClient(cc, .refresh);
+}
+fn submitRename(cc: *panel.ControlCenter) void {
+ const pending = cc.printers.pending_rename orelse return;
+ const state = cc.printers.client.?.current orelse return;
+ if (state.failure != null or cc.printers.client.?.failure != null or state.generation != cc.printers.client.?.generation) {
+ cc.printers.pending_rename = null;
+ cc.printers.message = "Could not verify existing printers before changing the identifier.";
+ return;
+ }
+ const data = state.cups orelse return;
+ const old = pending.old[0..pending.old_len];
+ if (data.jobs_error != null) {
+ cc.printers.pending_rename = null;
+ cc.printers.message = "Could not verify the printer's jobs. Refresh before changing its identifier.";
+ return;
+ }
+ for (data.jobs) |job| if (job.cancellable() and std.mem.eql(u8, job.printer, old)) {
+ cc.printers.pending_rename = null;
+ cc.printers.message = "Finish or cancel the printer's jobs before changing its identifier.";
+ return;
+ };
+ var source_exists = false;
+ for (data.printers) |printer| if (std.mem.eql(u8, printer.name, old)) {
+ source_exists = true;
+ break;
+ };
+ if (!source_exists) {
+ cc.printers.pending_rename = null;
+ cc.printers.message = "The printer no longer exists. Refresh before retrying.";
+ return;
+ }
+ runAdmin(cc, .{ .rename = .{ .name = old, .new_name = pending.new[0..pending.new_len], .existing_names = queueNames(cc.printers.arena.allocator(), data) catch return } });
+ if (cc.printers.administration) |manager| if (!manager.busy) {
+ cc.printers.pending_rename = null;
+ };
+}
+fn finishRename(cc: *panel.ControlCenter) void {
+ const pending = cc.printers.pending_rename orelse return;
+ cc.printers.pending_rename = null;
+ const state = cc.printers.client.?.current orelse return;
+ if (state.failure != null or cc.printers.client.?.failure != null or state.generation != cc.printers.client.?.generation) return;
+ const data = state.cups orelse return;
+ var old_exists = false;
+ var new_exists = false;
+ for (data.printers) |printer| {
+ if (std.ascii.eqlIgnoreCase(printer.name, pending.old[0..pending.old_len])) old_exists = true;
+ if (std.ascii.eqlIgnoreCase(printer.name, pending.new[0..pending.new_len])) new_exists = true;
+ }
+ if (!old_exists and new_exists) {
+ cc.printers.selected_len = pending.new_len;
+ @memcpy(cc.printers.selected[0..pending.new_len], pending.new[0..pending.new_len]);
+ cc.printers.migration_pending = true;
+ runClient(cc, .{ .rename_preferences = .{ .old = pending.old[0..pending.old_len], .new = pending.new[0..pending.new_len] } });
+ } else cc.printers.message = "The queue identifier change could not be verified. Review the printer list before retrying.";
+}
+fn mediaFor(printer: cups.Printer, state: *const printing.State) ?tools.Media {
+ if (tools.mediaFromKeyword(printer.media)) |media| return media;
+ if (std.mem.eql(u8, state.selected, printer.name)) {
+ for (state.groups) |option_group| for (option_group.options) |option| {
+ if (!std.mem.eql(u8, option.name, "PageSize")) continue;
+ return @import("../../printing/options.zig").ppdMediaDimensions(state.ppd, option.default orelse return null);
+ };
+ }
+ return null;
+}
+fn measurement(self: *Section, id: Field) ?f64 {
+ const result = std.fmt.parseFloat(f64, fieldValue(self, id)) catch return null;
+ if (!std.math.isFinite(result) or result <= 0) return null;
+ return result * @as(f64, if (self.inches) 25.4 else 1);
+}
+fn loadedMedia(self: *Section) ?tools.Media {
+ const media: tools.Media = .{ .width_mm = measurement(self, .loaded_width) orelse return null, .height_mm = measurement(self, .loaded_height) orelse return null };
+ return if (media.valid()) media else null;
+}
+fn toolsForm(self: *Section, cc: *panel.ControlCenter, a: A, state: *const printing.State, printer: cups.Printer) !W {
+ var items: std.ArrayList(W) = .empty;
+ try items.append(a, panel.sectionTitle("Print tests and scale"));
+ try items.append(a, .{ .name = "printers_label", .kind = .{ .checkbox = .{ .label = "This is a label printer", .checked = printer.user.label, .disabled = busy(self), .owner = cc, .on_change = labelChanged } }, .width = .{ .percent = 1 } });
+ try items.append(a, .{ .name = "printers_units", .kind = .{ .select = .{ .labels = &.{ "Millimetres", "Inches" }, .selected = @intFromBool(self.inches), .owner = cc, .on_change = unitsChanged } }, .height = .{ .fixed = 34 }, .width = .{ .percent = 1 } });
+ try items.append(a, try entry(self, cc, a, .loaded_width, "Loaded paper width", ""));
+ try items.append(a, try entry(self, cc, a, .loaded_height, "Loaded paper height", ""));
+ try items.append(a, button(cc, "printers_save_media", "Remember loaded paper size", 0, busy(self) or loadedMedia(self) == null, saveMedia));
+ const language_labels = try a.alloc([]const u8, tools.probe_languages.len + 1);
+ language_labels[0] = "Unknown language — check the self-test sheet";
+ var lang_index: usize = 0;
+ for (tools.probe_languages, 0..) |language, index| {
+ language_labels[index + 1] = language.label();
+ if (self.language == language) lang_index = index + 1;
+ }
+ try items.append(a, .{ .name = "printers_language", .kind = .{ .select = .{ .labels = language_labels, .selected = lang_index, .disabled = busy(self), .owner = cc, .on_change = languageChanged } }, .height = .{ .fixed = 34 }, .width = .{ .percent = 1 } });
+ try items.append(a, text("Check the printer's self-test sheet for its language and real resolution.", true));
+ try items.append(a, try entry(self, cc, a, .raw_dpi, "Raw sample resolution (dpi)", ""));
+ const awaiting_result = self.form == .test_result;
+ try items.append(a, button(cc, "printers_test_page", "Test page through the driver…", @intFromEnum(printing.TestKind.driver), busy(self) or awaiting_result, testClicked));
+ try items.append(a, button(cc, "printers_test_raw", "Test without the driver…", @intFromEnum(printing.TestKind.raw), busy(self) or awaiting_result or self.language == null, testClicked));
+ try items.append(a, button(cc, "printers_probe_language", "Try one language sample…", @intFromEnum(printing.TestKind.raw), busy(self) or awaiting_result, probeLanguage));
+ if (printer.label_media) try items.append(a, text("The driver reports label media.", true));
+ if (printer.user.label or printer.label_media) {
+ try items.append(a, button(cc, "printers_check_scale", "Print a 2 × 3 inch ruler…", @intFromEnum(printing.TestKind.ruler), busy(self) or awaiting_result, testClicked));
+ try items.append(a, text("Measure the rectangle edge to edge in the selected unit. Print scaling is disabled for this test.", true));
+ try items.append(a, try entry(self, cc, a, .measured_width, "Measured rectangle width", ""));
+ try items.append(a, try entry(self, cc, a, .measured_height, "Measured rectangle height", ""));
+ try items.append(a, button(cc, "printers_calibrate", "Check measured scale", 0, busy(self), calibrate));
+ if (self.suggested) |suggestion| {
+ const r = resolution(suggestion).?;
+ try items.append(a, text(try std.fmt.allocPrint(a, "Suggested supported resolution: {d} × {d} dpi", .{ r.x_dpi, r.y_dpi }), false));
+ const selectable = resolutionChoice(state, suggestion) != null;
+ try items.append(a, button(cc, "printers_apply_resolution", "Use suggested resolution", 0, busy(self) or !canAdmin(self) or !selectable, applyResolution));
+ if (!selectable) try items.append(a, text("This driver does not expose the suggested resolution as a queue setting. Review its quality or driver choices.", true));
+ }
+ }
+ if (self.form == .test_confirm) {
+ const media = loadedMedia(self);
+ try items.append(a, text(try std.fmt.allocPrint(a, "Print one {s} test on {s}?", .{ @tagName(self.test_kind), if (printer.info.len != 0) printer.info else printer.name }), false));
+ if (media) |size| try items.append(a, text(try std.fmt.allocPrint(a, "Paper: {d:.2} × {d:.2} mm", .{ size.width_mm, size.height_mm }), true));
+ try items.append(a, text(try std.fmt.allocPrint(a, "Queue paper setting: {s}. Check that this matches the loaded paper.", .{if (printer.media.len > 0) printer.media else "Unavailable"}), true));
+ if (self.test_kind == .raw) try items.append(a, text(try std.fmt.allocPrint(a, "Language: {s}. This sample bypasses the filters and uses the queue's backend.", .{if (self.language) |language| language.label() else "Unknown"}), true));
+ if (self.test_kind == .raw) try items.append(a, text(tools.self_test_help, true));
+ try items.append(a, button(cc, "printers_test_confirm", "Print one test", 0, busy(self) or media == null or (self.test_kind == .raw and (self.language == null or rawDpi(self) == null)), confirmTest));
+ try items.append(a, button(cc, "printers_test_cancel", "Cancel test", 0, busy(self), dismiss));
+ }
+ if (self.form == .test_result) {
+ const valid = state.receipt != null and state.receipt.?.matchesQueue(printer.name) and state.receipt.?.kind == self.test_kind and state.action_error == null;
+ try items.append(a, text("Did the test produce printed output? CUPS completion alone cannot tell.", false));
+ try items.append(a, button(cc, "printers_test_printed", "It printed", 0, busy(self) or !valid, testOutcome));
+ try items.append(a, button(cc, "printers_test_blank", "Blank or no output", 1, busy(self) or !valid, testOutcome));
+ try items.append(a, button(cc, "printers_test_close", "Close test result", 0, busy(self), dismiss));
+ }
+ if (printer.user.raw == .printed and printer.user.driver == .no_output) try items.append(a, text("The raw sample printed but the driver test did not: investigate the driver, filters, paper size and resolution.", false));
+ if (printer.user.raw == .no_output and printer.user.driver == .no_output) try items.append(a, text("Neither test produced output: check the backend, connection, printer and loaded paper.", false));
+ return card(a, items.items);
+}
+fn labelChanged(raw: ?*anyopaque, _: usize, checked: bool) void {
+ const cc = owner(raw);
+ const printer = chosen(cc) orelse return;
+ var prefs = printer.user;
+ prefs.label = checked;
+ runClient(cc, .{ .save = .{ .queue = printer.name, .state = prefs } });
+}
+fn saveMedia(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ const printer = chosen(cc) orelse return;
+ var prefs = printer.user;
+ prefs.expected_media = loadedMedia(&cc.printers) orelse return;
+ runClient(cc, .{ .save = .{ .queue = printer.name, .state = prefs } });
+}
+fn languageChanged(raw: ?*anyopaque, _: usize, index: usize) void {
+ const cc = owner(raw);
+ if (index > tools.probe_languages.len) return;
+ cc.printers.language = if (index == 0) null else tools.probe_languages[index - 1];
+ const printer = chosen(cc) orelse return;
+ var prefs = printer.user;
+ prefs.language = cc.printers.language;
+ runClient(cc, .{ .save = .{ .queue = printer.name, .state = prefs } });
+}
+fn unitsChanged(raw: ?*anyopaque, _: usize, index: usize) void {
+ const cc = owner(raw);
+ if (index > 1 or cc.printers.inches == (index == 1)) return;
+ for ([_]Field{ .loaded_width, .loaded_height, .measured_width, .measured_height }) |id| {
+ const mm = measurement(&cc.printers, id) orelse continue;
+ var buffer: [64]u8 = undefined;
+ const converted = std.fmt.bufPrint(&buffer, "{d:.3}", .{mm / @as(f64, if (index == 1) 25.4 else 1)}) catch continue;
+ setField(&cc.printers, id, converted) catch {};
+ }
+ cc.printers.inches = index == 1;
+ cc.printers.suggested = null;
+ cc.refresh();
+}
+fn testClicked(raw: ?*anyopaque, kind: usize) void {
+ const cc = owner(raw);
+ if (kind > @intFromEnum(printing.TestKind.ruler) or chosen(cc) == null) return;
+ cc.printers.test_kind = @enumFromInt(kind);
+ cc.printers.form = .test_confirm;
+ cc.refresh();
+}
+fn probeLanguage(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ if (cc.printers.language == null) cc.printers.language = .tspl;
+ cc.printers.message = "Choose a language from the self-test sheet or try one sample. Record the outcome before choosing another language.";
+ testClicked(raw, @intFromEnum(printing.TestKind.raw));
+}
+fn confirmTest(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ if (cc.printers.form != .test_confirm or busy(&cc.printers)) return;
+ if (cc.printers.test_kind == .raw and (cc.printers.language == null or rawDpi(&cc.printers) == null)) return;
+ const printer = chosen(cc) orelse return;
+ const state = cc.printers.client.?.current orelse return;
+ const media = loadedMedia(&cc.printers) orelse return;
+ cc.printers.form = .test_result;
+ runClient(cc, .{ .test_print = .{ .queue = printer.name, .kind = cc.printers.test_kind, .media = media, .media_keyword = printer.media, .language = cc.printers.language, .dpi = rawDpi(&cc.printers) orelse 203, .queue_resolution = queueResolution(printer, state) } });
+}
+fn rawDpi(self: *Section) ?u32 {
+ const dpi = std.fmt.parseInt(u32, fieldValue(self, .raw_dpi), 10) catch return null;
+ return if (dpi >= 72 and dpi <= 1200) dpi else null;
+}
+fn testOutcome(raw: ?*anyopaque, result: usize) void {
+ const cc = owner(raw);
+ if (cc.printers.form != .test_result or busy(&cc.printers)) return;
+ const state = cc.printers.client.?.current orelse return;
+ const receipt = state.receipt orelse return;
+ if (receipt.kind != cc.printers.test_kind or state.action_error != null) return;
+ const printer = chosen(cc) orelse return;
+ if (!receipt.matchesQueue(printer.name)) return;
+ var prefs = printer.user;
+ const outcome: preferences.Outcome = if (result == 0) .printed else .no_output;
+ switch (cc.printers.test_kind) {
+ .driver => prefs.driver = outcome,
+ .raw => prefs.raw = outcome,
+ .ruler => {
+ prefs.ruler = outcome;
+ prefs.ruler_resolution = receipt.queue_resolution;
+ },
+ }
+ prefs.language = receipt.language;
+ prefs.expected_media = receipt.media;
+ cc.printers.form = .none;
+ runClient(cc, .{ .save = .{ .queue = printer.name, .state = prefs } });
+}
+fn calibrate(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ if (busy(&cc.printers)) return;
+ const printer = chosen(cc) orelse return;
+ const state = cc.printers.client.?.current orelse return;
+ const options_module = @import("../../printing/options.zig");
+ const receipt_resolution = if (state.receipt) |receipt| if (receipt.kind == .ruler and receipt.matchesQueue(printer.name)) receipt.queue_resolution else null else null;
+ const current_value = receipt_resolution orelse printer.user.ruler_resolution orelse queueResolution(printer, state);
+ const current = current_value orelse {
+ cc.printers.message = "The current printer resolution is unavailable.";
+ cc.refresh();
+ return;
+ };
+ var supported: std.ArrayList(cups.ipp.Resolution) = .empty;
+ const a = cc.printers.arena.allocator();
+ for (printer.attributes) |attr| if (std.mem.eql(u8, attr.name, "printer-resolution-supported")) {
+ if (attr.resolution()) |r| supported.append(a, r) catch return;
+ };
+ if (supported.items.len == 0) supported.appendSlice(a, options_module.resolutionChoices(a, state.groups) catch &.{}) catch return;
+ cc.printers.suggested = tools.suggestResolution(current, supported.items, measurement(&cc.printers, .measured_width) orelse 0, measurement(&cc.printers, .measured_height) orelse 0);
+ cc.printers.message = if (cc.printers.suggested != null) "Review the suggested resolution, then apply it explicitly." else "No supported resolution consistently matches both measurements. Check the ruler and print scaling.";
+ cc.refresh();
+}
+fn queueResolution(printer: cups.Printer, state: *const printing.State) ?cups.ipp.Resolution {
+ for (state.groups) |option_group| for (option_group.options) |option| {
+ if (driver_options.resolutionOption(option) and option.source == .ppd) if (option.default) |setting| return driver_options.parseResolution(setting);
+ };
+ return printer.resolution;
+}
+fn applyResolution(raw: ?*anyopaque, _: usize) void {
+ const cc = owner(raw);
+ const r = cc.printers.suggested orelse return;
+ const state = cc.printers.client.?.current orelse return;
+ const match = resolutionChoice(state, r) orelse return;
+ changeOption(cc, match.option, match.value);
+}
+const ResolutionChoice = struct { option: driver_options.Option, value: []const u8 };
+fn resolutionChoice(state: *const printing.State, r: cups.ipp.Resolution) ?ResolutionChoice {
+ for (state.groups) |option_group| for (option_group.options) |option| {
+ if (option.source != .ppd or !driver_options.resolutionOption(option)) continue;
+ for (option.choices) |choice| {
+ const parsed = driver_options.parseResolution(choice.value) orelse continue;
+ if (parsed.x == r.x and parsed.y == r.y and parsed.units == r.units) {
+ return .{ .option = option, .value = choice.value };
+ }
+ }
+ };
+ return null;
+}
diff --git a/src/printing/AGENTS.md b/src/printing/AGENTS.md
new file mode 100644
index 0000000..58d4099
--- /dev/null
+++ b/src/printing/AGENTS.md
@@ -0,0 +1,20 @@
+# Printing
+
+* `cups.zig` queries the configured Unix or cleartext TCP CUPS endpoint. TLS and
+ authentication are explicit unsupported states; never fall back to a
+ different server. Configuration read failures are not missing files.
+ cups-pk-helper targets its local default server: allow its actions only with
+ the canonical local socket, never a custom Unix or remote CUPS endpoint.
+* IPP and HTTP replies are untrusted and bounded. Socket operations share an
+ absolute deadline and include the worker cancellation fd in every wait.
+* `cups.Snapshot` owns an arena. Parser helpers allocate into that arena;
+ borrowed decoder fields must not escape it. Display strings are sanitized,
+ but URI identity uses the complete validated value, never truncated text.
+* `usb_sysfs` only reads sysfs and stats nodes. A unique serial can identify a
+ USB queue; product strings and VID:PID alone cannot. Missing `usblp` is normal
+ for libusb. Missing/inaccessible evidence stays unknown.
+* The ladder is pure and reports evidence, not physical printing. A CUPS
+ completed state or sheet counter alone cannot establish paper output.
+ Reports exclude arbitrary names, messages, serials and URI authorities/paths.
+* Worker lifetime and widget ownership: `src/control_center/AGENTS.md`.
+ Remaining features and hardware/distro qualification: `docs/plans/printers.md`.
diff --git a/src/printing/admin.zig b/src/printing/admin.zig
new file mode 100644
index 0000000..58ac493
--- /dev/null
+++ b/src/printing/admin.zig
@@ -0,0 +1,789 @@
+//! Page-owned asynchronous printer administration. The installed cups-pk-helper
+//! owns policy and privileged CUPS calls; 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;
+const setup = @import("setup.zig");
+const cups = @import("cups.zig");
+const wire = dbus.wire;
+const a = std.heap.c_allocator;
+
+pub const helper_name = "org.opensuse.CupsPkHelper.Mechanism";
+pub const helper_path = "/";
+pub const Availability = enum { loading, available, missing };
+pub const Device = struct {
+ uri: []const u8 = "",
+ info: []const u8 = "",
+ make_model: []const u8 = "",
+ device_id: []const u8 = "",
+ class: []const u8 = "",
+};
+pub const Add = struct {
+ name: []const u8,
+ uri: []const u8,
+ ppd: []const u8,
+ info: []const u8 = "",
+ location: []const u8 = "",
+ discovered: bool = false,
+ /// Names from a fresh inventory: PrinterAdd itself is an upsert in CUPS,
+ /// which has no create-exclusive primitive. Never knowingly modify a queue.
+ existing_names: []const []const u8 = &.{},
+};
+pub const Toggle = struct { name: []const u8, value: bool };
+pub const Text = struct { name: []const u8, value: []const u8 };
+pub const Option = struct { name: []const u8, key: []const u8, values: []const []const u8 };
+pub const OptionKey = struct { name: []const u8, key: []const u8 };
+pub const Rename = struct { name: []const u8, new_name: []const u8, existing_names: []const []const u8 };
+pub const DeviceChange = struct { name: []const u8, uri: []const u8, discovered: bool = false };
+pub const Action = union(enum) {
+ discover,
+ add: Add,
+ remove: []const u8,
+ enabled: Toggle,
+ accepting: Toggle,
+ system_default: []const u8,
+ info: Text,
+ rename: Rename,
+ device: DeviceChange,
+ option: Option,
+ ppd_option: Option,
+ clear_option: OptionKey,
+ start_service,
+};
+
+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 {
+ owner: *anyopaque,
+ changed: *const fn (*anyopaque) void,
+ bus: ?*dbus.Connection = null,
+ closing: bool = false,
+ availability: Availability = .loading,
+ busy: bool = true,
+ status: []const u8 = "Checking printer administration…",
+ /// Increases after successful mutations or uncertain add/rename results;
+ /// owners refresh CUPS when it changes. Discovery does not reload CUPS.
+ generation: u64 = 0,
+ devices: []const Device = &.{},
+ arena: std.heap.ArenaAllocator = .init(a),
+ stage: Stage = .idle,
+ added_name: [setup.max_name]u8 = undefined,
+ added_len: usize = 0,
+ option_queue: [setup.max_name]u8 = undefined,
+ option_queue_len: usize = 0,
+ option_key: [127]u8 = undefined,
+ option_key_len: usize = 0,
+ option_alias: ?[]const u8 = null,
+ /// Complete validated setter arguments, retained until default cleanup
+ /// 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 {
+ const self = try a.create(Manager);
+ errdefer a.destroy(self);
+ self.* = .{ .owner = owner, .changed = changed };
+ self.bus = dbus.Connection.openSystem(a, loop, env) catch {
+ self.availability = .missing;
+ self.busy = false;
+ self.status = "System bus unavailable; printer administration is unavailable.";
+ return self;
+ };
+ _ = self.bus.?.hello(self, hello) catch {
+ self.bus.?.destroy();
+ self.bus = null;
+ self.availability = .missing;
+ self.busy = false;
+ self.status = "Could not connect to the system bus.";
+ };
+ if (self.bus) |bus| bus.on_disconnect = .{ .owner = self, .callback = disconnected };
+ return self;
+ }
+
+ pub fn destroy(self: *Manager) void {
+ self.closing = true;
+ if (self.bus) |bus| bus.destroy();
+ self.option_body.deinit();
+ self.arena.deinit();
+ a.destroy(self);
+ }
+
+ fn notify(self: *Manager) void {
+ if (!self.closing) self.changed(self.owner);
+ }
+
+ fn disconnected(owner: ?*anyopaque) void {
+ const self: *Manager = @ptrCast(@alignCast(owner.?));
+ if (self.closing) return;
+ self.stage = .idle;
+ self.unavailable("System bus connection lost. Reopen Printers to reconnect.");
+ }
+
+ fn hello(owner: ?*anyopaque, bus: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const self: *Manager = @ptrCast(@alignCast(owner.?));
+ if (self.closing) return;
+ const msg = result catch {
+ self.unavailable("Could not connect to the system bus.");
+ return;
+ };
+ if (msg.kind != .method_return) {
+ self.unavailable("Could not connect to the system bus.");
+ return;
+ }
+ var body: wire.Writer = .{ .allocator = a };
+ defer body.deinit();
+ _ = bus.call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListActivatableNames", "", &body, self, activatable, 5000) catch {
+ self.unavailable("Could not check cups-pk-helper availability.");
+ };
+ }
+
+ fn activatable(owner: ?*anyopaque, bus: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const self: *Manager = @ptrCast(@alignCast(owner.?));
+ if (self.closing) return;
+ const msg = result catch {
+ self.unavailable("Could not check cups-pk-helper availability.");
+ return;
+ };
+ if (msg.kind == .method_return and std.mem.eql(u8, msg.headers.signature, "as")) {
+ var body = msg.body;
+ var names = body.array(4) catch {
+ self.unavailable("Invalid system bus reply.");
+ return;
+ };
+ var found = false;
+ while (names.offset < names.bytes.len) {
+ const value = names.string() catch {
+ self.unavailable("Invalid system bus reply.");
+ return;
+ };
+ found = found or std.mem.eql(u8, value, helper_name);
+ }
+ body.done() catch {
+ self.unavailable("Invalid system bus reply.");
+ return;
+ };
+ if (found) {
+ self.available();
+ return;
+ }
+ }
+ // A manually running helper need not have a service activation file.
+ var body: wire.Writer = .{ .allocator = a };
+ defer body.deinit();
+ body.string(helper_name) catch {
+ self.unavailable("Could not check cups-pk-helper availability.");
+ return;
+ };
+ _ = bus.call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner", "s", &body, self, hasOwner, 5000) catch {
+ self.unavailable("Could not check cups-pk-helper availability.");
+ };
+ }
+
+ fn hasOwner(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const self: *Manager = @ptrCast(@alignCast(owner.?));
+ if (self.closing) return;
+ const msg = result catch {
+ self.unavailable("Could not check cups-pk-helper availability.");
+ return;
+ };
+ if (msg.kind == .method_return and std.mem.eql(u8, msg.headers.signature, "b")) {
+ var body = msg.body;
+ const found = body.boolean() catch false;
+ body.done() catch {
+ self.unavailable("Invalid system bus reply.");
+ return;
+ };
+ if (found) {
+ self.available();
+ return;
+ }
+ }
+ self.unavailable("Install cups-pk-helper to add or configure printers.");
+ }
+
+ fn available(self: *Manager) void {
+ self.availability = .available;
+ self.busy = false;
+ self.status = "Printer administration is available; authorization may be required.";
+ self.notify();
+ }
+
+ fn unavailable(self: *Manager, status: []const u8) void {
+ self.availability = .missing;
+ self.busy = false;
+ self.status = status;
+ self.notify();
+ }
+
+ /// Arguments are encoded/copied before returning. A successful return means
+ /// queued, not authorized or committed; busy/status and changed report that.
+ pub fn request(self: *Manager, action: Action) !void {
+ if (self.closing or self.busy) return error.Busy;
+ switch (action) {
+ .add => |add| try self.requireDiscovered(add.uri, add.discovered),
+ .device => |device| try self.requireDiscovered(device.uri, device.discovered),
+ else => {},
+ }
+ const bus = self.bus orelse return error.Disconnected;
+ if (action != .start_service and self.availability != .available) return error.HelperUnavailable;
+ var body: wire.Writer = .{ .allocator = a };
+ defer body.deinit();
+ var method = try encode(&body, action);
+ self.stage = switch (action) {
+ .discover => .discovery,
+ .add => |add| blk: {
+ self.added_len = add.name.len;
+ @memcpy(self.added_name[0..add.name.len], add.name);
+ break :blk .add;
+ },
+ .start_service => .start_service,
+ .rename => .rename,
+ .device => .device,
+ .ppd_option => |option| blk: {
+ self.option_queue_len = option.name.len;
+ @memcpy(self.option_queue[0..option.name.len], option.name);
+ self.option_key_len = option.key.len;
+ @memcpy(self.option_key[0..option.key.len], option.key);
+ self.option_alias = canonicalAlias(option.key);
+ break :blk .clear_ppd_override;
+ },
+ else => .mutation,
+ };
+ if (action == .ppd_option) {
+ // CUPS must see the PPD update last: deleting a canonical default
+ // after setting it can reset generated defaults such as colour.
+ self.option_body.deinit();
+ self.option_body = body;
+ body = .{ .allocator = a };
+ method = encode(&body, .{ .clear_option = .{
+ .name = self.option_queue[0..self.option_queue_len],
+ .key = self.option_key[0..self.option_key_len],
+ } }) catch |err| {
+ self.option_body.deinit();
+ self.option_body = .{ .allocator = a };
+ self.stage = .idle;
+ return err;
+ };
+ }
+ self.busy = true;
+ self.status = switch (action) {
+ .discover => "Discovering printers; authorization may be required…",
+ .start_service => "Requesting CUPS start; authorization may be required…",
+ else => "Applying printer change; authorization may be required…",
+ };
+ if (action == .start_service) {
+ _ = bus.callWithFlags("org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", method.member, method.signature, &body, self, reply, 120000, 4) catch |err| {
+ self.fail("Could not request CUPS start.");
+ return err;
+ };
+ } else {
+ _ = bus.callWithFlags(helper_name, helper_path, helper_name, method.member, method.signature, &body, self, reply, 120000, 4) catch |err| {
+ self.fail("Could not send printer administration request.");
+ return err;
+ };
+ }
+ }
+
+ fn reply(owner: ?*anyopaque, bus: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const self: *Manager = @ptrCast(@alignCast(owner.?));
+ if (self.closing) return;
+ const msg = result catch |err| {
+ self.fail(if (err == error.Timeout) "Printer administration timed out. Refresh before trying again." else "System bus disconnected during printer administration.");
+ return;
+ };
+ if (msg.kind == .error_reply) {
+ const error_name = msg.headers.error_name orelse "";
+ if (std.mem.eql(u8, error_name, "org.freedesktop.DBus.Error.ServiceUnknown") or std.mem.eql(u8, error_name, "org.freedesktop.DBus.Error.NameHasNoOwner")) {
+ if (self.stage != .start_service) self.availability = .missing;
+ self.fail(if (self.stage == .start_service) "The system service manager is unavailable; start CUPS using your distribution's service tools." else "Install cups-pk-helper to add or configure printers.");
+ } else if (std.mem.indexOf(u8, error_name, "NotPrivileged") != null or std.mem.indexOf(u8, error_name, "AccessDenied") != null or std.mem.indexOf(u8, error_name, "NotAuthorized") != null or std.mem.indexOf(u8, error_name, "InteractiveAuthorizationRequired") != null) {
+ self.fail("Printer administration was not authorized or was cancelled.");
+ } else self.fail("Printer administration failed; refresh and check the printer status.");
+ return;
+ }
+ if (msg.kind != .method_return) {
+ self.fail("Invalid printer administration reply.");
+ return;
+ }
+ if (self.stage == .start_service) {
+ if (!std.mem.eql(u8, msg.headers.signature, "o")) {
+ self.fail("Invalid service-manager reply.");
+ return;
+ }
+ var body = msg.body;
+ _ = body.objectPath() catch {
+ self.fail("Invalid service-manager reply.");
+ return;
+ };
+ body.done() catch {
+ self.fail("Invalid service-manager reply.");
+ return;
+ };
+ self.succeed("CUPS start requested. Refresh to check when it is ready.");
+ return;
+ }
+ const expected = if (self.stage == .discovery) "sa{ss}" else "s";
+ if (!std.mem.eql(u8, msg.headers.signature, expected)) {
+ self.fail("Invalid cups-pk-helper reply.");
+ return;
+ }
+ var body = msg.body;
+ const error_message = body.string() catch {
+ self.fail("Invalid cups-pk-helper reply.");
+ return;
+ };
+ if (error_message.len != 0) {
+ self.fail("CUPS refused the printer change. Check authorization, the address and driver, then refresh.");
+ return;
+ }
+ if (self.stage == .discovery) {
+ self.readDevices(&body) catch {
+ self.fail("Invalid or oversized printer discovery reply.");
+ return;
+ };
+ self.busy = false;
+ self.stage = .idle;
+ self.status = if (self.devices.len == 0) "CUPS discovered no supported printer addresses. You can enter a network address." else "Printer discovery complete.";
+ self.notify();
+ return;
+ }
+ body.done() catch {
+ self.fail("Invalid cups-pk-helper reply.");
+ return;
+ };
+ switch (self.stage) {
+ .add => {
+ self.stage = .enable_added;
+ self.sendAdded(bus, .{ .enabled = .{ .name = self.added_name[0..self.added_len], .value = true } });
+ },
+ .enable_added => {
+ self.stage = .accept_added;
+ self.sendAdded(bus, .{ .accepting = .{ .name = self.added_name[0..self.added_len], .value = true } });
+ },
+ .accept_added => self.succeed("Printer added, enabled and accepting jobs."),
+ .rename => self.succeed("Queue rename request completed. Check the refreshed queues and options."),
+ .device => self.succeed("Printer connection changed."),
+ .clear_ppd_override => {
+ if (self.option_alias != null) {
+ self.stage = .clear_ppd_alias;
+ self.clearOptionAlias(bus);
+ } else {
+ self.stage = .ppd_option;
+ self.sendPpdOption(bus);
+ }
+ },
+ .clear_ppd_alias => {
+ self.stage = .ppd_option;
+ self.sendPpdOption(bus);
+ },
+ .ppd_option => self.succeed("Printer option applied."),
+ else => self.succeed("Printer change applied."),
+ }
+ }
+
+ fn sendAdded(self: *Manager, bus: *dbus.Connection, action: Action) void {
+ var body: wire.Writer = .{ .allocator = a };
+ defer body.deinit();
+ const method = encode(&body, action) catch {
+ self.fail("Printer was added, but could not be enabled. Refresh and resume it.");
+ return;
+ };
+ _ = bus.callWithFlags(helper_name, helper_path, helper_name, method.member, method.signature, &body, self, reply, 120000, 4) catch {
+ self.fail("Printer was added, but could not be enabled. Refresh and resume it.");
+ };
+ }
+
+ fn requireDiscovered(self: *Manager, uri: []const u8, discovered: bool) !void {
+ if (!discovered) return;
+ for (self.devices) |device| if (std.mem.eql(u8, device.uri, uri)) return;
+ return error.UntrustedDevice;
+ }
+
+ fn sendPpdOption(self: *Manager, bus: *dbus.Connection) void {
+ _ = bus.callWithFlags(helper_name, helper_path, helper_name, "PrinterAddOption", "ssas", &self.option_body, self, reply, 120000, wire.flag_allow_interactive_authorization) catch {
+ self.fail("Could not apply the printer option.");
+ };
+ }
+
+ fn clearOptionAlias(self: *Manager, bus: *dbus.Connection) void {
+ var body: wire.Writer = .{ .allocator = a };
+ defer body.deinit();
+ const method = encode(&body, .{ .clear_option = .{
+ .name = self.option_queue[0..self.option_queue_len],
+ .key = self.option_alias.?,
+ } }) catch {
+ self.fail("Could not clear the canonical default override.");
+ return;
+ };
+ _ = bus.callWithFlags(helper_name, helper_path, helper_name, method.member, method.signature, &body, self, reply, 120000, wire.flag_allow_interactive_authorization) catch {
+ self.fail("Could not clear the canonical default override.");
+ };
+ }
+
+ fn fail(self: *Manager, status: []const u8) void {
+ // A chained add may already have changed CUPS; force an inventory reload
+ // and describe its partial result rather than deleting anyone's queue.
+ const partial = self.stage == .enable_added or self.stage == .accept_added;
+ // A timed-out Add can already have created a queue. Close its form and
+ // fetch fresh names before allowing a retry, even without a valid reply.
+ const option_partial = self.stage == .ppd_option;
+ const alias_partial = self.stage == .clear_ppd_alias;
+ if (partial or option_partial or alias_partial or self.stage == .clear_ppd_override or self.stage == .add or self.stage == .rename or self.stage == .device) self.generation +%= 1;
+ self.status = if (partial)
+ "Printer was added, but enabling or accepting jobs failed. Refresh, then resume it and allow jobs."
+ else if (option_partial)
+ "Old printer default override cleared, but the new printer option could not be applied. Refresh and review the option."
+ else if (alias_partial)
+ "Printer default cleanup partly completed, but the new printer option could not be applied. Refresh and review the option."
+ else
+ status;
+ self.busy = false;
+ self.stage = .idle;
+ self.option_body.deinit();
+ self.option_body = .{ .allocator = a };
+ self.option_alias = null;
+ self.notify();
+ }
+
+ fn succeed(self: *Manager, status: []const u8) void {
+ self.generation +%= 1;
+ self.status = status;
+ self.busy = false;
+ self.stage = .idle;
+ self.option_body.deinit();
+ self.option_body = .{ .allocator = a };
+ self.option_alias = null;
+ self.notify();
+ }
+
+ fn readDevices(self: *Manager, body: *wire.Reader) !void {
+ var arena: std.heap.ArenaAllocator = .init(a);
+ errdefer arena.deinit();
+ const mem = arena.allocator();
+ var devices: [128]Device = @splat(.{});
+ var dict = try body.array(8);
+ var count: usize = 0;
+ while (dict.offset < dict.bytes.len) {
+ count += 1;
+ if (count > 2048) return error.TooLarge;
+ try dict.alignTo(8);
+ const key = try dict.string();
+ const value = try dict.string();
+ const colon = std.mem.lastIndexOfScalar(u8, key, ':') orelse continue;
+ const index = std.fmt.parseInt(usize, key[colon + 1 ..], 10) catch continue;
+ if (index >= devices.len) continue;
+ const field = key[0..colon];
+ if (std.mem.eql(u8, field, "device-uri")) {
+ setup.validateUri(value, true) catch continue;
+ if (devices[index].uri.len != 0) return error.InvalidReply;
+ devices[index].uri = try mem.dupe(u8, value);
+ } else if (std.mem.eql(u8, field, "device-id")) {
+ if (value.len > setup.max_uri) return error.TooLarge;
+ // Driver matching must use complete identity, never display
+ // truncation or strings changed by stripping control bytes.
+ if (!std.unicode.utf8ValidateSlice(value)) continue;
+ var valid = true;
+ for (value) |ch| if (ch < 0x20 or ch == 0x7f) {
+ valid = false;
+ break;
+ };
+ if (valid) devices[index].device_id = try mem.dupe(u8, value);
+ } else if (std.mem.eql(u8, field, "device-info")) {
+ devices[index].info = try cups.clean(mem, value);
+ } else if (std.mem.eql(u8, field, "device-make-and-model")) {
+ devices[index].make_model = try cups.clean(mem, value);
+ } else if (std.mem.eql(u8, field, "device-class")) {
+ devices[index].class = try cups.clean(mem, value);
+ }
+ }
+ try body.done();
+ var selected: std.ArrayList(Device) = .empty;
+ for (devices) |device| {
+ if (device.uri.len == 0) continue;
+ var duplicate = false;
+ for (selected.items) |previous| if (std.mem.eql(u8, previous.uri, device.uri)) {
+ duplicate = true;
+ break;
+ };
+ if (!duplicate) try selected.append(mem, device);
+ }
+ const result = try selected.toOwnedSlice(mem);
+ self.arena.deinit();
+ self.arena = arena;
+ self.devices = result;
+ }
+};
+
+const Method = struct { member: []const u8, signature: []const u8 };
+
+fn canonicalAlias(key: []const u8) ?[]const u8 {
+ for ([_][]const u8{ "Resolution", "SetResolution", "JCLResolution", "CNRes_PGP" }) |native| if (std.mem.eql(u8, key, native)) return "printer-resolution";
+ if (std.mem.eql(u8, key, "PageSize") or std.mem.eql(u8, key, "PageRegion")) return "media";
+ if (std.mem.eql(u8, key, "Duplex")) return "sides";
+ if (std.mem.eql(u8, key, "ColorModel")) return "print-color-mode";
+ if (std.mem.eql(u8, key, "cupsPrintQuality")) return "print-quality";
+ return null;
+}
+
+fn name(writer: *wire.Writer, value: []const u8) !void {
+ if (!setup.validName(value)) return error.InvalidName;
+ try writer.string(value);
+}
+
+fn text(writer: *wire.Writer, value: []const u8, limit: usize) !void {
+ if (value.len > limit or !std.unicode.utf8ValidateSlice(value)) return error.InvalidValue;
+ for (value) |ch| if (ch < 0x20 or ch == 0x7f) return error.InvalidValue;
+ try writer.string(value);
+}
+
+fn optionKey(writer: *wire.Writer, value: []const u8) !void {
+ if (value.len == 0 or value.len > 127) return error.InvalidOption;
+ for (value) |ch| if (!std.ascii.isAlphanumeric(ch) and ch != '-' and ch != '_') return error.InvalidOption;
+ try writer.string(value);
+}
+
+/// Method ABI used by installed system-config-printer/cupspk.py for the
+/// cups-pk-helper 0.2.x interface. Discovery is (timeout, limit,
+/// include_schemes, exclude_schemes); every helper method returns an error string.
+fn encode(writer: *wire.Writer, action: Action) !Method {
+ return switch (action) {
+ .discover => blk: {
+ try writer.int(i32, 10);
+ try writer.int(i32, 128);
+ const includes = try writer.beginArray(4);
+ try writer.endArray(includes);
+ const excludes = try writer.beginArray(4);
+ for ([_][]const u8{ "file", "smb", "smbs", "pdf", "pipe", "exec", "command", "beh", "hpfax", "mailto" }) |scheme| try writer.string(scheme);
+ try writer.endArray(excludes);
+ break :blk .{ .member = "DevicesGet", .signature = "iiasas" };
+ },
+ .add => |add| blk: {
+ try name(writer, add.name);
+ if (setup.nameExists(add.name, add.existing_names)) return error.QueueExists;
+ try setup.validateUri(add.uri, add.discovered);
+ try writer.string(add.uri);
+ if (add.ppd.len == 0 or add.ppd.len > 1024) return error.InvalidDriver;
+ try text(writer, add.ppd, 1024);
+ try text(writer, add.info, 512);
+ try text(writer, add.location, 512);
+ break :blk .{ .member = "PrinterAdd", .signature = "sssss" };
+ },
+ .remove => |value| blk: {
+ try name(writer, value);
+ break :blk .{ .member = "PrinterDelete", .signature = "s" };
+ },
+ .enabled => |toggle| blk: {
+ try name(writer, toggle.name);
+ try writer.boolean(toggle.value);
+ break :blk .{ .member = "PrinterSetEnabled", .signature = "sb" };
+ },
+ .accepting => |toggle| blk: {
+ try name(writer, toggle.name);
+ try writer.boolean(toggle.value);
+ try writer.string("");
+ break :blk .{ .member = "PrinterSetAcceptJobs", .signature = "sbs" };
+ },
+ .system_default => |value| blk: {
+ try name(writer, value);
+ break :blk .{ .member = "PrinterSetDefault", .signature = "s" };
+ },
+ .info => |value| blk: {
+ try name(writer, value.name);
+ try text(writer, value.value, 512);
+ break :blk .{ .member = "PrinterSetInfo", .signature = "ss" };
+ },
+ .rename => |value| blk: {
+ try name(writer, value.name);
+ if (!setup.validName(value.new_name)) return error.InvalidName;
+ if (std.ascii.eqlIgnoreCase(value.name, value.new_name)) return error.SameName;
+ if (setup.nameExists(value.new_name, value.existing_names)) return error.QueueExists;
+ try writer.string(value.new_name);
+ break :blk .{ .member = "PrinterRename", .signature = "ss" };
+ },
+ .device => |value| blk: {
+ try name(writer, value.name);
+ try setup.validateUri(value.uri, value.discovered);
+ try writer.string(value.uri);
+ break :blk .{ .member = "PrinterSetDevice", .signature = "ss" };
+ },
+ .option, .ppd_option => |option| blk: {
+ try name(writer, option.name);
+ try optionKey(writer, option.key);
+ if (option.values.len == 0 or option.values.len > 64) return error.InvalidOption;
+ const array = try writer.beginArray(4);
+ for (option.values) |value| try text(writer, value, 1024);
+ try writer.endArray(array);
+ break :blk .{ .member = if (action == .ppd_option) "PrinterAddOption" else "PrinterAddOptionDefault", .signature = "ssas" };
+ },
+ .clear_option => |option| blk: {
+ try name(writer, option.name);
+ try optionKey(writer, option.key);
+ break :blk .{ .member = "PrinterDeleteOptionDefault", .signature = "ss" };
+ },
+ .start_service => blk: {
+ try writer.string("cups.service");
+ try writer.string("replace");
+ break :blk .{ .member = "StartUnit", .signature = "ss" };
+ },
+ };
+}
+
+test "printer administration validates and encodes the actual helper ABI" {
+ std.testing.refAllDecls(Manager);
+ var writer: wire.Writer = .{ .allocator = std.testing.allocator };
+ defer writer.deinit();
+ const discovery = try encode(&writer, .discover);
+ try std.testing.expectEqualStrings("DevicesGet", discovery.member);
+ try std.testing.expectEqualStrings("iiasas", discovery.signature);
+ var reader: wire.Reader = .{ .bytes = writer.bytes.items };
+ try std.testing.expectEqual(@as(i32, 10), try reader.int(i32));
+ try std.testing.expectEqual(@as(i32, 128), try reader.int(i32));
+ const schemes = try reader.array(4);
+ try schemes.done();
+ var excludes = try reader.array(4);
+ for ([_][]const u8{ "file", "smb", "smbs", "pdf", "pipe", "exec", "command", "beh", "hpfax", "mailto" }) |scheme| try std.testing.expectEqualStrings(scheme, try excludes.string());
+ try excludes.done();
+ try reader.done();
+ writer.bytes.clearRetainingCapacity();
+ try std.testing.expectError(error.QueueExists, encode(&writer, .{ .add = .{ .name = "Office", .uri = "ipp://printer/ipp/print", .ppd = "everywhere", .existing_names = &.{"office"} } }));
+ writer.bytes.clearRetainingCapacity();
+ const accepting = try encode(&writer, .{ .accepting = .{ .name = "Office", .value = true } });
+ try std.testing.expectEqualStrings("PrinterSetAcceptJobs", accepting.member);
+ try std.testing.expectEqualStrings("sbs", accepting.signature);
+ reader = .{ .bytes = writer.bytes.items };
+ try std.testing.expectEqualStrings("Office", try reader.string());
+ try std.testing.expect(try reader.boolean());
+ try std.testing.expectEqualStrings("", try reader.string());
+ try reader.done();
+ writer.bytes.clearRetainingCapacity();
+ const renamed = try encode(&writer, .{ .rename = .{ .name = "Office", .new_name = "Office_New", .existing_names = &.{ "Office", "Label" } } });
+ try std.testing.expectEqualStrings("PrinterRename", renamed.member);
+ try std.testing.expectEqualStrings("ss", renamed.signature);
+ reader = .{ .bytes = writer.bytes.items };
+ try std.testing.expectEqualStrings("Office", try reader.string());
+ try std.testing.expectEqualStrings("Office_New", try reader.string());
+ try reader.done();
+ writer.bytes.clearRetainingCapacity();
+ try std.testing.expectError(error.QueueExists, encode(&writer, .{ .rename = .{ .name = "Office", .new_name = "LABEL", .existing_names = &.{ "Office", "Label" } } }));
+ writer.bytes.clearRetainingCapacity();
+ try std.testing.expectError(error.SameName, encode(&writer, .{ .rename = .{ .name = "Office", .new_name = "office", .existing_names = &.{"Office"} } }));
+ writer.bytes.clearRetainingCapacity();
+ try std.testing.expectError(error.InvalidName, encode(&writer, .{ .rename = .{ .name = "Office", .new_name = "New/Office", .existing_names = &.{"Office"} } }));
+ writer.bytes.clearRetainingCapacity();
+ const ppd_option = try encode(&writer, .{ .ppd_option = .{ .name = "Office", .key = "Darkness", .values = &.{"12"} } });
+ try std.testing.expectEqualStrings("PrinterAddOption", ppd_option.member);
+ try std.testing.expectEqualStrings("ssas", ppd_option.signature);
+ reader = .{ .bytes = writer.bytes.items };
+ try std.testing.expectEqualStrings("Office", try reader.string());
+ try std.testing.expectEqualStrings("Darkness", try reader.string());
+ var values = try reader.array(4);
+ try std.testing.expectEqualStrings("12", try values.string());
+ try values.done();
+ try reader.done();
+ writer.bytes.clearRetainingCapacity();
+ const device = try encode(&writer, .{ .device = .{ .name = "Office", .uri = "ipps://printer.local/ipp/print" } });
+ try std.testing.expectEqualStrings("PrinterSetDevice", device.member);
+ try std.testing.expectEqualStrings("ss", device.signature);
+ reader = .{ .bytes = writer.bytes.items };
+ try std.testing.expectEqualStrings("Office", try reader.string());
+ try std.testing.expectEqualStrings("ipps://printer.local/ipp/print", try reader.string());
+ try reader.done();
+}
+
+test "discovery owns complete identities and rejects unsafe backend addresses" {
+ var writer: wire.Writer = .{ .allocator = std.testing.allocator };
+ defer writer.deinit();
+ const dict = try writer.beginArray(8);
+ const fields = [_][2][]const u8{
+ .{ "device-uri:0", "usb://Acme/Label?serial=complete" },
+ .{ "device-info:0", "Label\nprinter\x1b" },
+ .{ "device-uri:1", "file:/tmp/unsafe" },
+ .{ "device-info:1", "Must not be offered" },
+ .{ "device-uri:2", "smb://user:password@private/queue" },
+ .{ "device-uri:3", "usb://Acme/Label?serial=complete" },
+ };
+ for (fields) |field| {
+ try writer.alignTo(8);
+ try writer.string(field[0]);
+ try writer.string(field[1]);
+ }
+ const long_id = "MFG:Acme;" ++ "X" ** 600 ++ ";MDL:Label;";
+ try writer.alignTo(8);
+ try writer.string("device-id:0");
+ try writer.string(long_id);
+ try writer.endArray(dict);
+ var self: Manager = .{ .owner = undefined, .changed = undefined };
+ defer self.arena.deinit();
+ var reader: wire.Reader = .{ .bytes = writer.bytes.items };
+ try self.readDevices(&reader);
+ try std.testing.expectEqual(@as(usize, 1), self.devices.len);
+ try std.testing.expectEqualStrings("usb://Acme/Label?serial=complete", self.devices[0].uri);
+ try std.testing.expectEqualStrings("Labelprinter", self.devices[0].info);
+ try std.testing.expectEqualStrings(long_id, self.devices[0].device_id);
+ writer.bytes.clearRetainingCapacity();
+ try std.testing.expectEqualStrings(long_id, self.devices[0].device_id);
+}
+
+test "failed PPD setter after legacy cleanup reports partial changes and refreshes inventory" {
+ const Recorder = struct {
+ changes: usize = 0,
+ fn changed(raw: *anyopaque) void {
+ const recorder: *@This() = @ptrCast(@alignCast(raw));
+ recorder.changes += 1;
+ }
+ };
+ var recorder: Recorder = .{};
+ var manager: Manager = .{ .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);
+ try std.testing.expectEqual(@as(usize, 1), recorder.changes);
+ try std.testing.expect(!manager.busy);
+ try std.testing.expectEqual(Stage.idle, manager.stage);
+ try std.testing.expect(std.mem.indexOf(u8, manager.status, "new printer option could not be applied") != null);
+}
+
+test "native PPD cleanup aliases are explicit and retain the original setter key" {
+ const pairs = [_][2][]const u8{
+ .{ "Resolution", "printer-resolution" }, .{ "SetResolution", "printer-resolution" },
+ .{ "JCLResolution", "printer-resolution" }, .{ "CNRes_PGP", "printer-resolution" },
+ .{ "PageSize", "media" }, .{ "PageRegion", "media" },
+ .{ "Duplex", "sides" }, .{ "ColorModel", "print-color-mode" },
+ .{ "cupsPrintQuality", "print-quality" },
+ };
+ for (pairs) |pair| {
+ try std.testing.expectEqualStrings(pair[1], canonicalAlias(pair[0]).?);
+ var writer: wire.Writer = .{ .allocator = std.testing.allocator };
+ defer writer.deinit();
+ for ([_][]const u8{ pair[0], canonicalAlias(pair[0]).? }) |key| {
+ writer.bytes.clearRetainingCapacity();
+ const method = try encode(&writer, .{ .clear_option = .{ .name = "Office", .key = key } });
+ try std.testing.expectEqualStrings("PrinterDeleteOptionDefault", method.member);
+ var reader: wire.Reader = .{ .bytes = writer.bytes.items };
+ try std.testing.expectEqualStrings("Office", try reader.string());
+ try std.testing.expectEqualStrings(key, try reader.string());
+ try reader.done();
+ }
+ writer.bytes.clearRetainingCapacity();
+ const method = try encode(&writer, .{ .ppd_option = .{ .name = "Office", .key = pair[0], .values = &.{"Choice"} } });
+ try std.testing.expectEqualStrings("PrinterAddOption", method.member);
+ var reader: wire.Reader = .{ .bytes = writer.bytes.items };
+ try std.testing.expectEqualStrings("Office", try reader.string());
+ try std.testing.expectEqualStrings(pair[0], try reader.string());
+ }
+ try std.testing.expect(canonicalAlias("printer-resolution") == null);
+ try std.testing.expect(canonicalAlias("Darkness") == null);
+}
+
+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 };
+ 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 } }));
+ try std.testing.expectError(error.UntrustedDevice, manager.request(.{ .add = .{ .name = "Label", .uri = "tspl:/dev/usb/lp0", .ppd = "raw", .discovered = true } }));
+ try std.testing.expectError(error.UntrustedDevice, manager.request(.{ .device = .{ .name = "Label", .uri = "usb://Acme/Label?serial=different", .discovered = true } }));
+ // Exact catalog identity passes the guard and reaches the intentionally
+ // absent transport. This unit test never opens a bus or a printer node.
+ try std.testing.expectError(error.Disconnected, manager.request(.{ .add = .{ .name = "Label", .uri = "usb://Acme/Label?serial=complete", .ppd = "raw", .discovered = true } }));
+ try std.testing.expectError(error.Disconnected, manager.request(.{ .device = .{ .name = "Label", .uri = "usb://Acme/Label?serial=complete", .discovered = true } }));
+}
diff --git a/src/printing/client.zig b/src/printing/client.zig
new file mode 100644
index 0000000..077cc44
--- /dev/null
+++ b/src/printing/client.zig
@@ -0,0 +1,468 @@
+//! The Printers page owns this worker and both eventfds. Idle blocks forever;
+//! hiding the page cancels socket I/O, joins the worker, and drops its inventory.
+const std = @import("std");
+const wl = @import("wayland").server.wl;
+const cups = @import("cups.zig");
+const usb = @import("usb_sysfs.zig");
+const http = @import("http.zig");
+const tools = @import("tools.zig");
+const preferences = @import("preferences.zig");
+const options = @import("options.zig");
+const endpoint = @import("endpoint.zig");
+const platform = @import("platform.zig");
+const daemon_watch = @import("daemon_watch.zig");
+const c = @import("native.zig").c;
+const a = std.heap.c_allocator;
+
+pub const State = struct {
+ arena: std.heap.ArenaAllocator = .init(a),
+ generation: u64 = 0,
+ cups: ?cups.Snapshot = null,
+ usb: ?usb.Snapshot = null,
+ failure: ?anyerror = null,
+ action_error: ?anyerror = null,
+ selected: []const u8 = "",
+ groups: []const options.Group = &.{},
+ ppd: []const u8 = "",
+ remote: bool = false,
+ admin_local: bool = false,
+ platform: platform.Info = .{},
+ receipt: ?Receipt = null,
+ probe: ?bool = null,
+ fn destroy(self: *State) void {
+ if (self.cups) |*snapshot| snapshot.deinit();
+ if (self.usb) |snapshot| snapshot.deinit(a);
+ self.arena.deinit();
+ a.destroy(self);
+ }
+};
+
+pub const TestKind = enum { driver, raw, ruler };
+pub const Print = struct { queue: []const u8, kind: TestKind, media: tools.Media, media_keyword: []const u8 = "", language: ?tools.Language = null, dpi: u32 = 203, queue_resolution: ?cups.ipp.Resolution = null };
+pub const Receipt = struct {
+ id: i32,
+ kind: TestKind,
+ media: tools.Media,
+ language: ?tools.Language,
+ queue_resolution: ?cups.ipp.Resolution,
+ queue_name: [128]u8 = @splat(0),
+ queue_len: usize = 0,
+
+ pub fn matchesQueue(self: Receipt, queue: []const u8) bool {
+ return self.queue_len > 0 and self.queue_len <= self.queue_name.len and std.mem.eql(u8, self.queue_name[0..self.queue_len], queue);
+ }
+};
+pub const Save = struct { queue: []const u8, state: preferences.UserState };
+pub const Rename = struct { old: []const u8, new: []const u8 };
+pub const Action = union(enum) { refresh, catalog, select: []const u8, cancel_job: i32, personal_default: []const u8, save: Save, test_print: Print, probe: []const u8, rename_preferences: Rename };
+const Command = struct {
+ arena: std.heap.ArenaAllocator,
+ action: Action,
+ fn create(action: Action) !*Command {
+ const self = try a.create(Command);
+ self.* = .{ .arena = .init(a), .action = action };
+ errdefer self.destroy();
+ const mem = self.arena.allocator();
+ self.action = switch (action) {
+ .select => |value| .{ .select = try mem.dupe(u8, value) },
+ .personal_default => |value| .{ .personal_default = try mem.dupe(u8, value) },
+ .probe => |value| .{ .probe = try mem.dupe(u8, value) },
+ .save => |value| .{ .save = .{ .queue = try mem.dupe(u8, value.queue), .state = value.state } },
+ .rename_preferences => |value| .{ .rename_preferences = .{ .old = try mem.dupe(u8, value.old), .new = try mem.dupe(u8, value.new) } },
+ .test_print => |value| blk: {
+ var copy = value;
+ copy.queue = try mem.dupe(u8, value.queue);
+ copy.media_keyword = try mem.dupe(u8, value.media_keyword);
+ break :blk .{ .test_print = copy };
+ },
+ else => action,
+ };
+ return self;
+ }
+ fn destroy(self: *Command) void {
+ self.arena.deinit();
+ a.destroy(self);
+ }
+};
+
+pub const Client = struct {
+ io: std.Io,
+ env: std.process.Environ,
+ owner: *anyopaque,
+ changed: *const fn (*anyopaque) void,
+ source: ?*wl.EventSource = null,
+ wake_worker: c_int = -1,
+ wake_main: c_int = -1,
+ thread: ?std.Thread = null,
+ stop: std.atomic.Value(bool) = .init(false),
+ reload: std.atomic.Value(bool) = .init(true),
+ command: ?*Command = null,
+ loading: std.atomic.Value(bool) = .init(false),
+ subscriptions: std.atomic.Value(bool) = .init(false),
+ subscription_id: ?i32 = null,
+ subscription_attempted: bool = false,
+ subscription_server: [1024]u8 = undefined,
+ subscription_server_len: usize = 0,
+ subscription_user: [256]u8 = undefined,
+ subscription_user_len: usize = 0,
+ watch: ?daemon_watch.Watch = null,
+ selected_queue: [512]u8 = undefined,
+ selected_len: usize = 0,
+ want_catalog: bool = false,
+ receipt: ?Receipt = null,
+ probe_result: ?bool = null,
+ mutex: c.pthread_mutex_t = undefined,
+ /// Guarded with mutex along with commands and pending snapshots. A USB
+ /// reload begun before a user action must not clear that action's busy flag.
+ generation: u64 = 0,
+ pending: ?*State = null,
+ pending_allocation_failure: ?u64 = null,
+ current: ?*State = null,
+ failure: ?anyerror = null,
+ busy: bool = true,
+
+ pub fn create(io: std.Io, env: std.process.Environ, loop: *wl.EventLoop, owner: *anyopaque, changed: *const fn (*anyopaque) void) !*Client {
+ const self = try a.create(Client);
+ errdefer a.destroy(self);
+ self.* = .{ .io = io, .env = env, .owner = owner, .changed = changed };
+ if (c.pthread_mutex_init(&self.mutex, null) != 0) return error.MutexFailed;
+ errdefer _ = c.pthread_mutex_destroy(&self.mutex);
+ self.wake_worker = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK);
+ if (self.wake_worker < 0) return error.EventFdFailed;
+ errdefer _ = c.close(self.wake_worker);
+ self.wake_main = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK);
+ if (self.wake_main < 0) return error.EventFdFailed;
+ errdefer _ = c.close(self.wake_main);
+ self.source = try loop.addFd(*Client, self.wake_main, .{ .readable = true }, ready, self);
+ errdefer self.source.?.remove();
+ self.thread = try std.Thread.spawn(.{}, run, .{self});
+ self.thread.?.setName(io, "rediwm-printers") catch {};
+ return self;
+ }
+ pub fn destroy(self: *Client) void {
+ self.source.?.remove();
+ self.stop.store(true, .release);
+ signal(self.wake_worker);
+ self.thread.?.join();
+ _ = c.close(self.wake_worker);
+ _ = c.close(self.wake_main);
+ if (self.pending) |state| state.destroy();
+ if (self.current) |state| state.destroy();
+ if (self.command) |command| command.destroy();
+ _ = c.pthread_mutex_destroy(&self.mutex);
+ a.destroy(self);
+ }
+ pub fn refresh(self: *Client) void {
+ self.act(.refresh) catch {};
+ }
+ pub fn invalidate(self: *Client) void {
+ _ = c.pthread_mutex_lock(&self.mutex);
+ self.reload.store(true, .release);
+ if (!self.loading.load(.acquire)) signal(self.wake_worker);
+ _ = c.pthread_mutex_unlock(&self.mutex);
+ }
+ pub fn enableSubscriptions(self: *Client) void {
+ if (self.subscriptions.swap(true, .acq_rel)) return;
+ self.invalidate();
+ }
+ pub fn act(self: *Client, action: Action) !void {
+ if (self.busy) return error.Busy;
+ const command = try Command.create(action);
+ self.busy = true;
+ self.failure = null;
+ _ = c.pthread_mutex_lock(&self.mutex);
+ self.generation +%= 1;
+ self.command = command;
+ self.reload.store(true, .release);
+ signal(self.wake_worker);
+ _ = c.pthread_mutex_unlock(&self.mutex);
+ }
+ pub fn cancelJob(self: *Client, id: i32) void {
+ if (self.busy or id <= 0) return;
+ // Recheck ownership against our current snapshot, outside the widget.
+ const snapshot = if (self.current) |state| state.cups orelse return else return;
+ for (snapshot.jobs) |job| if (job.id == id and job.cancellable()) {
+ self.act(.{ .cancel_job = id }) catch {};
+ return;
+ };
+ }
+ fn ready(_: c_int, _: wl.EventMask, self: *Client) c_int {
+ drain(self.wake_main);
+ _ = c.pthread_mutex_lock(&self.mutex);
+ const state = self.pending;
+ self.pending = null;
+ const generation = self.generation;
+ const allocation_failure = self.pending_allocation_failure;
+ self.pending_allocation_failure = null;
+ _ = c.pthread_mutex_unlock(&self.mutex);
+ if (state) |next| {
+ if (self.current) |previous| previous.destroy();
+ self.current = next;
+ if (next.generation == generation) self.busy = false;
+ }
+ if (allocation_failure) |failed_generation| if (failed_generation == generation) {
+ self.busy = false;
+ self.failure = error.OutOfMemory;
+ };
+ if (state != null or allocation_failure != null) self.changed(self.owner);
+ return 0;
+ }
+ fn publish(self: *Client, state: *State) void {
+ _ = c.pthread_mutex_lock(&self.mutex);
+ if (self.pending) |old| old.destroy();
+ self.pending = state;
+ _ = c.pthread_mutex_unlock(&self.mutex);
+ signal(self.wake_main);
+ }
+ fn load(self: *Client, command: ?*Command, generation: u64) !*State {
+ defer if (command) |item| item.destroy();
+ const state = try a.create(State);
+ state.* = .{};
+ errdefer state.destroy();
+ state.generation = generation;
+ state.usb = usb.scan(a, self.io, .{}) catch null;
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const mem = arena.allocator();
+ state.platform = platform.load(state.arena.allocator(), self.io) catch .{};
+ const socket = cups.server(mem, self.io, self.env) catch |err| {
+ state.failure = err;
+ return state;
+ };
+ if (self.subscription_id != null and !std.mem.eql(u8, socket, self.subscription_server[0..self.subscription_server_len])) self.cancelSubscription();
+ const username = cups.user(mem) catch |err| {
+ state.failure = err;
+ return state;
+ };
+ state.remote = (try endpoint.parseServer(socket)).unix == null;
+ state.admin_local = std.mem.eql(u8, socket, "/run/cups/cups.sock") or std.mem.eql(u8, socket, "/var/run/cups/cups.sock");
+ if (self.watch) |*watch| if (watch.fd < 0) {
+ watch.deinit(a);
+ self.watch = null;
+ };
+ if (self.watch == null) self.watch = daemon_watch.Watch.init(a, socket) catch null;
+ if (command) |item| self.perform(mem, socket, username, item.action) catch |err| {
+ if (err == error.Cancelled) return err;
+ state.action_error = err;
+ };
+ state.cups = cups.load(a, self.io, socket, username, self.wake_worker) catch |err| {
+ if (err == error.Cancelled) return err;
+ state.failure = err;
+ self.subscription_attempted = self.subscription_id != null;
+ return state;
+ };
+ const data = &state.cups.?;
+ const owned = data.arena.allocator();
+ data.user_default = (preferences.defaultPrinter(owned, self.io, self.env) catch null) orelse "";
+ for (data.printers) |*printer| {
+ printer.user = preferences.loadState(owned, self.io, self.env, printer.name) catch .{};
+ if (printer.device_id.len == 0) if (state.usb) |*inventory| {
+ const match = usb.matchQueue(inventory, printer.device_uri);
+ if (match.device) |device| printer.device_id = try owned.dupe(u8, device.device_id);
+ };
+ if (nodePath(printer.device_uri)) |path| printer.node_kind = if (std.Io.Dir.cwd().statFile(self.io, path, .{})) |stat| switch (stat.kind) {
+ .character_device => .character,
+ .file => .regular,
+ else => .other,
+ } else |err| if (err == error.FileNotFound) .missing else .unavailable;
+ }
+ if (self.want_catalog) data.drivers = cups.drivers(owned, self.io, socket, username, self.wake_worker) catch |err| blk: {
+ if (err == error.Cancelled) return err;
+ data.drivers_error = err;
+ break :blk &.{};
+ };
+ if (self.selected_len == 0 and data.printers.len > 0) self.setSelected(data.printers[0].name);
+ state.selected = try owned.dupe(u8, self.selected_queue[0..self.selected_len]);
+ for (data.printers) |*printer| if (std.mem.eql(u8, printer.name, state.selected)) {
+ state.groups = options.parseAttributes(owned, printer.attributes) catch &.{};
+ state.ppd = cups.ppd(owned, self.io, socket, username, printer.name, self.wake_worker) catch |err| blk: {
+ if (err == error.Cancelled) return err;
+ break :blk "";
+ };
+ if (state.ppd.len > 0) {
+ const extra = options.parsePpd(owned, state.ppd) catch &.{};
+ state.groups = try std.mem.concat(owned, options.Group, &.{ state.groups, extra });
+ }
+ if (std.mem.startsWith(u8, printer.device_uri, "ipp://")) {
+ _ = cups.probe(owned, self.io, printer.device_uri, username, self.wake_worker) catch |err| {
+ if (err == error.Cancelled) return err;
+ printer.network_reachable = false;
+ break;
+ };
+ printer.network_reachable = true;
+ }
+ break;
+ };
+ if (!state.remote and self.subscriptions.load(.acquire) and !self.subscription_attempted) {
+ self.subscription_attempted = true;
+ self.subscription_id = cups.subscribe(mem, self.io, socket, username, self.wake_worker) catch null;
+ if (self.subscription_id != null) {
+ self.subscription_server_len = @min(socket.len, self.subscription_server.len);
+ @memcpy(self.subscription_server[0..self.subscription_server_len], socket[0..self.subscription_server_len]);
+ self.subscription_user_len = @min(username.len, self.subscription_user.len);
+ @memcpy(self.subscription_user[0..self.subscription_user_len], username[0..self.subscription_user_len]);
+ }
+ }
+ state.receipt = self.receipt;
+ state.probe = self.probe_result;
+ return state;
+ }
+ fn setSelected(self: *Client, value: []const u8) void {
+ if (!std.mem.eql(u8, value, self.selected_queue[0..self.selected_len])) self.receipt = null;
+ self.selected_len = @min(value.len, self.selected_queue.len);
+ @memcpy(self.selected_queue[0..self.selected_len], value[0..self.selected_len]);
+ }
+ fn perform(self: *Client, mem: std.mem.Allocator, socket: []const u8, username: []const u8, action: Action) !void {
+ switch (action) {
+ .refresh => {},
+ .catalog => self.want_catalog = true,
+ .select => |queue| self.setSelected(queue),
+ .cancel_job => |id| try cups.cancelJob(mem, self.io, socket, username, id, self.wake_worker),
+ .personal_default => |queue| try preferences.setDefault(mem, self.io, self.env, queue),
+ .save => |value| try preferences.saveState(mem, self.io, self.env, value.queue, value.state),
+ .rename_preferences => |value| {
+ self.setSelected(value.new);
+ preferences.renameQueue(mem, self.io, self.env, value.old, value.new) catch return error.PreferencesMigration;
+ },
+ .probe => |uri| {
+ self.probe_result = null;
+ self.probe_result = try cups.probe(mem, self.io, uri, username, self.wake_worker);
+ },
+ .test_print => |value| {
+ self.receipt = null;
+ if (!preferences.validQueue(value.queue)) return error.InvalidPrinterName;
+ const document = if (value.kind == .raw)
+ try tools.rawTest(mem, value.language orelse return error.UnknownLanguage, value.media, value.dpi)
+ else
+ try tools.testPdf(mem, value.media, if (value.kind == .ruler) .ruler else .page);
+ const id = try cups.print(mem, self.io, socket, username, value.queue, value.kind == .raw, value.media_keyword, document, self.wake_worker);
+ var receipt: Receipt = .{ .id = id, .kind = value.kind, .media = value.media, .language = value.language, .queue_resolution = value.queue_resolution, .queue_len = value.queue.len };
+ @memcpy(receipt.queue_name[0..value.queue.len], value.queue);
+ self.receipt = receipt;
+ },
+ }
+ }
+ fn run(self: *Client) void {
+ var netlink = ueventSocket();
+ defer if (netlink >= 0) {
+ _ = c.close(netlink);
+ };
+ defer if (self.watch) |*watch| watch.deinit(a);
+ var rescan_at: ?i64 = null;
+ while (!self.stop.load(.acquire)) {
+ if (self.reload.swap(false, .acq_rel)) {
+ _ = c.pthread_mutex_lock(&self.mutex);
+ const command = self.command;
+ self.command = null;
+ const generation = self.generation;
+ drain(self.wake_worker);
+ const stopping = self.stop.load(.acquire);
+ self.loading.store(true, .release);
+ _ = c.pthread_mutex_unlock(&self.mutex);
+ if (stopping) {
+ if (command) |item| item.destroy();
+ break;
+ }
+ const state = self.load(command, generation) catch |err| {
+ self.loading.store(false, .release);
+ if (err == error.Cancelled) {
+ if (!self.stop.load(.acquire)) self.reload.store(true, .release);
+ } else {
+ _ = c.pthread_mutex_lock(&self.mutex);
+ if (self.command) |queued| queued.destroy();
+ self.command = null;
+ self.reload.store(false, .release);
+ self.pending_allocation_failure = self.generation;
+ _ = c.pthread_mutex_unlock(&self.mutex);
+ signal(self.wake_main);
+ }
+ continue;
+ };
+ self.loading.store(false, .release);
+ self.publish(state);
+ rescan_at = null;
+ }
+ if (self.reload.load(.acquire)) continue;
+ const timeout: c_int = if (rescan_at) |deadline| @intCast(@max(0, deadline - http.nowMs())) else -1;
+ var fds = [_]c.struct_pollfd{ .{ .fd = self.wake_worker, .events = c.POLLIN, .revents = 0 }, .{ .fd = netlink, .events = c.POLLIN, .revents = 0 }, .{ .fd = if (self.watch) |watch| watch.fd else -1, .events = c.POLLIN, .revents = 0 } };
+ const n = c.poll(&fds, fds.len, timeout);
+ if (n < 0) {
+ if (std.posix.errno(n) == .INTR) continue;
+ return;
+ }
+ if (fds[0].revents != 0) drain(self.wake_worker);
+ if (fds[1].revents & (c.POLLERR | c.POLLHUP | c.POLLNVAL) != 0) {
+ _ = c.close(netlink);
+ netlink = -1;
+ }
+ if (fds[1].revents & c.POLLIN != 0 and drainUevents(netlink) and rescan_at == null) rescan_at = http.nowMs() + 300;
+ if (fds[2].revents != 0) if (self.watch) |*watch| if (watch.changed()) {
+ self.cancelSubscription();
+ self.subscription_attempted = false;
+ if (rescan_at == null) rescan_at = http.nowMs() + 100;
+ };
+ if (rescan_at) |deadline| if (http.nowMs() >= deadline) {
+ self.reload.store(true, .release);
+ };
+ }
+ self.cancelSubscription();
+ }
+ fn cancelSubscription(self: *Client) void {
+ if (self.subscription_id) |id| cups.unsubscribeNoWait(self.subscription_server[0..self.subscription_server_len], self.subscription_user[0..self.subscription_user_len], id);
+ self.subscription_id = null;
+ self.subscription_attempted = false;
+ }
+};
+
+fn signal(fd: c_int) void {
+ const one: u64 = 1;
+ _ = c.write(fd, &one, @sizeOf(u64));
+}
+fn nodePath(uri: []const u8) ?[]const u8 {
+ const colon = std.mem.indexOfScalar(u8, uri, ':') orelse return null;
+ const backend = uri[0..colon];
+ if (!std.mem.eql(u8, backend, "file") and !std.mem.eql(u8, backend, "tspl")) return null;
+ var path = uri[colon + 1 ..];
+ if (std.mem.startsWith(u8, path, "//")) {
+ if (!std.mem.startsWith(u8, path, "///")) return null;
+ path = path[2..];
+ }
+ const prefix = "/dev/usb/";
+ if (!std.mem.startsWith(u8, path, prefix) or path.len <= prefix.len or path.len > 255) return null;
+ const leaf = path[prefix.len..];
+ if (std.mem.eql(u8, leaf, ".") or std.mem.eql(u8, leaf, "..")) return null;
+ for (leaf) |ch| if (!std.ascii.isAlphanumeric(ch) and ch != '-' and ch != '_' and ch != '.') return null;
+ return path;
+}
+fn drain(fd: c_int) void {
+ var count: u64 = 0;
+ _ = c.read(fd, &count, @sizeOf(u64));
+}
+fn ueventSocket() c_int {
+ const fd = c.socket(c.AF_NETLINK, c.SOCK_DGRAM | c.SOCK_CLOEXEC | c.SOCK_NONBLOCK, c.NETLINK_KOBJECT_UEVENT);
+ if (fd < 0) return -1;
+ var addr = std.mem.zeroes(c.struct_sockaddr_nl);
+ addr.nl_family = c.AF_NETLINK;
+ addr.nl_groups = 1;
+ if (c.bind(fd, @ptrCast(&addr), @sizeOf(c.struct_sockaddr_nl)) != 0) {
+ _ = c.close(fd);
+ return -1;
+ }
+ return fd;
+}
+fn drainUevents(fd: c_int) bool {
+ var changed = false;
+ for (0..256) |_| {
+ var bytes: [8192]u8 = undefined;
+ var sender: c.struct_sockaddr_nl = undefined;
+ var len: c.socklen_t = @sizeOf(c.struct_sockaddr_nl);
+ const n = c.recvfrom(fd, &bytes, bytes.len, 0, @ptrCast(&sender), &len);
+ if (n <= 0) break;
+ if (sender.nl_pid != 0) continue;
+ var words = std.mem.splitScalar(u8, bytes[0..@intCast(n)], 0);
+ while (words.next()) |word| if (std.mem.eql(u8, word, "SUBSYSTEM=usb") or std.mem.eql(u8, word, "SUBSYSTEM=usbmisc")) {
+ changed = true;
+ };
+ }
+ return changed;
+}
diff --git a/src/printing/cups.zig b/src/printing/cups.zig
new file mode 100644
index 0000000..d8c7c8d
--- /dev/null
+++ b/src/printing/cups.zig
@@ -0,0 +1,690 @@
+//! Local, unprivileged CUPS queries. Snapshots own all data; no document titles
+//! or contents are requested. Administrative operations are deliberately absent.
+const std = @import("std");
+pub const ipp = @import("ipp.zig");
+const http = @import("http.zig");
+const endpoint = @import("endpoint.zig");
+const preferences = @import("preferences.zig");
+const c = @import("native.zig").c;
+const A = std.mem.Allocator;
+pub const max_printers = 128;
+pub const max_jobs = 100;
+const eq = std.mem.eql;
+
+pub const Printer = struct {
+ name: []const u8 = "",
+ info: []const u8 = "",
+ model: []const u8 = "",
+ device_uri: []const u8 = "",
+ state: ?i32 = null,
+ accepting: ?bool = null,
+ reasons: []const u8 = "",
+ message: []const u8 = "",
+ media: []const u8 = "",
+ resolution: ?ipp.Resolution = null,
+ color: []const u8 = "",
+ sides: []const u8 = "",
+ markers: []const Marker = &.{},
+ is_default: bool = false,
+ device_id: []const u8 = "",
+ attributes: []const ipp.Attribute = &.{},
+ network_reachable: ?bool = null,
+ user: preferences.UserState = .{},
+ node_kind: ?@import("usb_sysfs.zig").NodeKind = null,
+ label_media: bool = false,
+ inconsistent_defaults: bool = false,
+};
+pub const Marker = struct { name: []const u8, level: ?i32 };
+pub const Job = struct {
+ id: i32 = 0,
+ printer: []const u8 = "",
+ state: ?i32 = null,
+ sheets: ?i32 = null,
+ reasons: []const u8 = "",
+ message: []const u8 = "",
+ own: bool = false,
+ pub fn cancellable(self: Job) bool {
+ return self.own and self.id > 0 and self.state != null and self.state.? >= 3 and self.state.? <= 6;
+ }
+};
+pub const Snapshot = struct {
+ arena: std.heap.ArenaAllocator,
+ printers: []Printer = &.{},
+ jobs: []Job = &.{},
+ jobs_error: ?anyerror = null,
+ drivers: []const Driver = &.{},
+ drivers_error: ?anyerror = null,
+ user_default: []const u8 = "",
+ cups_version: []const u8 = "",
+ pub fn deinit(self: *Snapshot) void {
+ self.arena.deinit();
+ self.* = undefined;
+ }
+};
+
+/// Reject unsupported remote/encrypted settings explicitly; never contact the
+/// local daemon when the user's CUPS configuration points somewhere else.
+pub fn server(a: A, io: std.Io, env: std.process.Environ) ![]const u8 {
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const mem = arena.allocator();
+ var configured: []const u8 = "/run/cups/cups.sock";
+ var encryption: []const u8 = "IfRequested";
+ const system = try readClientConfig(mem, io, "/etc/cups/client.conf");
+ const system_config = try clientConfig(system);
+ configured = system_config.server orelse configured;
+ encryption = system_config.encryption orelse encryption;
+ if (env.getPosix("HOME")) |home| {
+ const path = try std.fs.path.join(mem, &.{ home, ".cups/client.conf" });
+ const user_config = try clientConfig(try readClientConfig(mem, io, path));
+ configured = user_config.server orelse configured;
+ encryption = user_config.encryption orelse encryption;
+ }
+ configured = env.getPosix("CUPS_SERVER") orelse configured;
+ encryption = env.getPosix("CUPS_ENCRYPTION") orelse encryption;
+ if (!std.ascii.eqlIgnoreCase(encryption, "IfRequested") and !std.ascii.eqlIgnoreCase(encryption, "Never")) return error.UnsupportedServer;
+ _ = try endpoint.parseServer(configured);
+ return a.dupe(u8, configured);
+}
+
+fn readClientConfig(a: A, io: std.Io, path: []const u8) ![]const u8 {
+ return std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(65536)) catch |err| switch (err) {
+ error.FileNotFound => "",
+ else => error.InvalidClientConfiguration,
+ };
+}
+const ClientConfig = struct { server: ?[]const u8 = null, encryption: ?[]const u8 = null };
+fn clientConfig(bytes: []const u8) !ClientConfig {
+ var lines = std.mem.splitScalar(u8, bytes, '\n');
+ var result: ClientConfig = .{};
+ while (lines.next()) |line| {
+ const trimmed = std.mem.trim(u8, line[0 .. std.mem.indexOfScalar(u8, line, '#') orelse line.len], " \t\r");
+ const key_end = std.mem.indexOfAny(u8, trimmed, " \t") orelse trimmed.len;
+ const key = trimmed[0..key_end];
+ if (key.len == 0) continue;
+ const value = std.mem.trim(u8, trimmed[key_end..], " \t");
+ if (std.ascii.eqlIgnoreCase(key, "ServerName")) {
+ // Preserve spaces in Unix paths. Escaped CUPS directives are not
+ // implemented yet: reject them instead of selecting another path.
+ if (value.len == 0 or std.mem.indexOfScalar(u8, value, '\\') != null) return error.InvalidClientConfiguration;
+ result.server = value;
+ } else if (std.ascii.eqlIgnoreCase(key, "Encryption")) {
+ if (value.len == 0 or std.mem.indexOfAny(u8, value, " \t\\") != null) return error.InvalidClientConfiguration;
+ result.encryption = value;
+ }
+ }
+ return result;
+}
+
+pub fn user(a: A) ![]const u8 {
+ var pw: c.struct_passwd = undefined;
+ var result: [*c]c.struct_passwd = null;
+ var buffer: [16384]u8 = undefined;
+ if (c.getpwuid_r(c.getuid(), &pw, &buffer, buffer.len, &result) != 0 or result == null or pw.pw_name == null) return error.NoUser;
+ const value = std.mem.span(pw.pw_name);
+ if (value.len == 0 or value.len > 255 or !std.unicode.utf8ValidateSlice(value)) return error.NoUser;
+ return a.dupe(u8, value);
+}
+
+fn begin(a: A, code: u16, username: []const u8) !ipp.Encoder {
+ return beginTarget(a, code, username, "ipp://localhost/");
+}
+fn beginTarget(a: A, code: u16, username: []const u8, uri: []const u8) !ipp.Encoder {
+ var encoder = try ipp.Encoder.init(a, code, 1);
+ errdefer encoder.deinit();
+ try encoder.group(.operation);
+ try encoder.string(.charset, "attributes-charset", "utf-8");
+ try encoder.string(.natural_language, "attributes-natural-language", "en");
+ // Target precedes other operation attributes (RFC 8011 section 4.1.5).
+ try encoder.string(.uri, "printer-uri", uri);
+ try encoder.string(.name, "requesting-user-name", username);
+ return encoder;
+}
+
+fn requested(encoder: *ipp.Encoder, names: []const []const u8) !void {
+ for (names, 0..) |name, i| try encoder.string(.keyword, if (i == 0) "requested-attributes" else "", name);
+}
+
+fn exchange(a: A, io: std.Io, socket: []const u8, path: []const u8, encoder: *ipp.Encoder, cancel: c_int) !ipp.Message {
+ return exchangeDocument(a, io, socket, path, encoder, &.{}, cancel, null);
+}
+fn exchangeDocument(a: A, io: std.Io, socket: []const u8, path: []const u8, encoder: *ipp.Encoder, document: []const u8, cancel: c_int, info: ?*http.Info) !ipp.Message {
+ if (document.len > 1024 * 1024) return error.DocumentTooLarge;
+ const encoded = try encoder.finish();
+ const configured = try endpoint.parseServer(socket);
+ encoder.bytes.items[1] = configured.version_minor;
+ const body = if (document.len == 0) encoded else try std.mem.concat(a, u8, &.{ encoded, document });
+ const bytes = if (info) |metadata| try http.requestIoInfo(a, io, socket, path, body, cancel, metadata) else try http.requestIo(a, io, socket, path, body, cancel);
+ // bytes belong to the snapshot arena, just like the decoded attributes.
+ var message = try ipp.decode(a, bytes, .{ .allow_duplicate_names = true });
+ if (message.request_id != 1) {
+ message.deinit(a);
+ return error.InvalidResponse;
+ }
+ if (message.code >= 0x100) {
+ const code = message.code;
+ message.deinit(a);
+ return switch (code) {
+ 0x0401, 0x0402, 0x0403 => error.NotAuthorized,
+ 0x0406 => error.NotFound,
+ 0x0501 => error.OperationUnsupported,
+ 0x040b => error.UnsupportedPrintSettings,
+ else => error.IppError,
+ };
+ }
+ return message;
+}
+
+pub fn load(a: A, io: std.Io, socket: []const u8, username: []const u8, cancel: c_int) !Snapshot {
+ var result: Snapshot = .{ .arena = .init(a) };
+ errdefer result.deinit();
+ const mem = result.arena.allocator();
+ var query = try begin(mem, 0x4002, username); // CUPS-Get-Printers
+ defer query.deinit();
+ try requested(&query, &.{ "printer-name", "printer-info", "printer-make-and-model", "printer-device-id", "device-uri", "printer-state", "printer-is-accepting-jobs", "printer-state-reasons", "printer-state-message", "media-default", "media-supported", "media-type-default", "print-darkness-supported", "print-darkness-default", "print-speed-supported", "print-speed-default", "printer-resolution-default", "printer-resolution-supported", "print-color-mode-default", "print-color-mode-supported", "sides-default", "sides-supported", "print-quality-default", "print-quality-supported", "marker-names", "marker-levels", "printer-type", "document-format-supported" });
+ var info: http.Info = .{};
+ var response = exchangeDocument(mem, io, socket, "/", &query, &.{}, cancel, &info) catch |err| switch (err) {
+ // CUPS returns not-found when there are no destinations.
+ error.NotFound => return result,
+ else => return err,
+ };
+ defer response.deinit(mem);
+ result.cups_version = try mem.dupe(u8, info.version());
+ result.printers = try printers(mem, response);
+ var jobs_query = try begin(mem, 0x000a, username); // Get-Jobs
+ defer jobs_query.deinit();
+ try jobs_query.string(.keyword, "which-jobs", "all");
+ try jobs_query.boolean("my-jobs", true);
+ try jobs_query.integer(.integer, "limit", max_jobs);
+ try requested(&jobs_query, &.{ "job-id", "job-printer-uri", "job-state", "job-state-reasons", "job-media-sheets-completed", "job-printer-state-message", "job-originating-user-name" });
+ var job_response = exchange(mem, io, socket, "/", &jobs_query, cancel) catch |err| {
+ if (err == error.Cancelled) return err;
+ result.jobs_error = err;
+ return result;
+ };
+ defer job_response.deinit(mem);
+ result.jobs = try jobs(mem, job_response, username);
+ return result;
+}
+
+pub fn cancelJob(a: A, io: std.Io, socket: []const u8, username: []const u8, id: i32, cancel: c_int) !void {
+ if (id <= 0) return error.InvalidJob;
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ var encoder = try begin(arena.allocator(), 0x0008, username);
+ defer encoder.deinit();
+ try encoder.integer(.integer, "job-id", id);
+ var result = try exchange(arena.allocator(), io, socket, "/jobs/", &encoder, cancel);
+ result.deinit(arena.allocator());
+}
+
+pub const Field = struct {
+ group: ipp.Tag = .operation,
+ name: []const u8,
+ tag: ipp.Tag = .keyword,
+ value: union(enum) { text: []const u8, integer: i32, boolean: bool, raw: []const u8 },
+};
+/// Response and all borrowed fields belong to a caller-owned arena.
+pub fn request(a: A, io: std.Io, socket: []const u8, username: []const u8, code: u16, target: []const u8, path: []const u8, fields: []const Field, document: []const u8, cancel: c_int) !ipp.Message {
+ var encoder = try beginTarget(a, code, username, target);
+ defer encoder.deinit();
+ var group: ipp.Tag = .operation;
+ for (fields) |field| {
+ if (field.group != group) {
+ try encoder.group(field.group);
+ group = field.group;
+ }
+ switch (field.value) {
+ .text => |value| try encoder.string(field.tag, field.name, value),
+ .integer => |value| try encoder.integer(field.tag, field.name, value),
+ .boolean => |value| try encoder.boolean(field.name, value),
+ .raw => |value| try encoder.value(field.tag, field.name, value),
+ }
+ }
+ return exchangeDocument(a, io, socket, path, &encoder, document, cancel, null);
+}
+pub fn queueUri(a: A, name: []const u8) ![]const u8 {
+ if (name.len == 0 or name.len > 255) return error.InvalidPrinterName;
+ var escaped: std.Io.Writer.Allocating = .init(a);
+ errdefer escaped.deinit();
+ try escaped.writer.writeAll("ipp://localhost/printers/");
+ for (name) |ch| {
+ if (std.ascii.isAlphanumeric(ch) or ch == '-' or ch == '_' or ch == '.') try escaped.writer.writeByte(ch) else try escaped.writer.print("%{X:0>2}", .{ch});
+ }
+ return escaped.toOwnedSlice();
+}
+
+pub const Driver = struct { name: []const u8, model: []const u8, device_id: []const u8 };
+pub fn drivers(a: A, io: std.Io, server_name: []const u8, username: []const u8, cancel: c_int) ![]const Driver {
+ var message = try request(a, io, server_name, username, 0x400c, "ipp://localhost/", "/", &.{
+ .{ .name = "limit", .tag = .integer, .value = .{ .integer = 512 } },
+ .{ .name = "requested-attributes", .value = .{ .text = "ppd-name" } },
+ .{ .name = "", .value = .{ .text = "ppd-make-and-model" } },
+ .{ .name = "", .value = .{ .text = "ppd-device-id" } },
+ }, &.{}, cancel);
+ defer message.deinit(a);
+ var out: std.ArrayList(Driver) = .empty;
+ var offset: usize = 0;
+ while (offset < message.attributes.len) {
+ var end = offset + 1;
+ while (end < message.attributes.len and message.attributes[end].group_index == message.attributes[offset].group_index) : (end += 1) {}
+ const attrs = message.attributes[offset..end];
+ offset = end;
+ if (attrs[0].group != .printer) continue;
+ const name = try identity(a, attrs, "ppd-name", 1024);
+ if (name.len == 0) continue;
+ if (out.items.len >= 512) break;
+ try out.append(a, .{ .name = name, .model = try txt(a, attrs, "ppd-make-and-model"), .device_id = try identity(a, attrs, "ppd-device-id", 8192) });
+ }
+ return out.toOwnedSlice(a);
+}
+
+pub fn print(a: A, io: std.Io, server_name: []const u8, username: []const u8, queue: []const u8, raw: bool, media: []const u8, document: []const u8, cancel: c_int) !i32 {
+ const target = try queueUri(a, queue);
+ const path = target["ipp://localhost".len..];
+ var fields: std.ArrayList(Field) = .empty;
+ try fields.appendSlice(a, &.{
+ .{ .name = "job-name", .tag = .name, .value = .{ .text = "RediWM printer test" } },
+ .{ .name = "document-format", .tag = .mime_type, .value = .{ .text = if (raw) "application/vnd.cups-raw" else "application/pdf" } },
+ .{ .name = "ipp-attribute-fidelity", .tag = .boolean, .value = .{ .boolean = true } },
+ });
+ try fields.appendSlice(a, &.{
+ .{ .group = .job, .name = "copies", .tag = .integer, .value = .{ .integer = 1 } },
+ .{ .group = .job, .name = "job-sheets", .value = .{ .text = "none" } },
+ });
+ if (media.len > 0) try fields.append(a, .{ .group = .job, .name = "media", .value = .{ .text = media } });
+ if (!raw) try fields.appendSlice(a, &.{
+ .{ .group = .job, .name = "print-scaling", .value = .{ .text = "none" } },
+ .{ .group = .job, .name = "number-up", .tag = .integer, .value = .{ .integer = 1 } },
+ });
+ var result = try request(a, io, server_name, username, 2, target, path, fields.items, document, cancel);
+ defer result.deinit(a);
+ return int(result.attributes, "job-id") orelse return error.InvalidResponse;
+}
+
+pub fn subscribe(a: A, io: std.Io, server_name: []const u8, username: []const u8, cancel: c_int) !i32 {
+ var result = try request(a, io, server_name, username, 0x0016, "ipp://localhost/", "/", &.{
+ .{ .group = .subscription, .name = "notify-recipient-uri", .tag = .uri, .value = .{ .text = "dbus://" } },
+ .{ .group = .subscription, .name = "notify-events", .value = .{ .text = "printer-state-changed" } },
+ .{ .group = .subscription, .name = "", .value = .{ .text = "printer-config-changed" } },
+ .{ .group = .subscription, .name = "", .value = .{ .text = "printer-added" } },
+ .{ .group = .subscription, .name = "", .value = .{ .text = "printer-deleted" } },
+ .{ .group = .subscription, .name = "", .value = .{ .text = "job-state-changed" } },
+ .{ .group = .subscription, .name = "", .value = .{ .text = "server-restarted" } },
+ .{ .group = .subscription, .name = "notify-lease-duration", .tag = .integer, .value = .{ .integer = 0 } },
+ }, &.{}, cancel);
+ defer result.deinit(a);
+ const id = int(result.attributes, "notify-subscription-id") orelse return error.OperationUnsupported;
+ if (id <= 0) return error.InvalidResponse;
+ var lease = int(result.attributes, "notify-lease-duration");
+ if (lease == null) {
+ var attrs = request(a, io, server_name, username, 0x0018, "ipp://localhost/", "/", &.{
+ .{ .name = "notify-subscription-id", .tag = .integer, .value = .{ .integer = id } },
+ }, &.{}, cancel) catch |err| {
+ unsubscribeNoWait(server_name, username, id);
+ return err;
+ };
+ defer attrs.deinit(a);
+ lease = int(attrs.attributes, "notify-lease-duration");
+ }
+ if (lease != 0) {
+ unsubscribeNoWait(server_name, username, id);
+ return error.OperationUnsupported;
+ }
+ return id;
+}
+pub fn unsubscribe(a: A, io: std.Io, server_name: []const u8, username: []const u8, id: i32, cancel: c_int) !void {
+ var result = try request(a, io, server_name, username, 0x001b, "ipp://localhost/", "/", &.{
+ .{ .name = "notify-subscription-id", .tag = .integer, .value = .{ .integer = id } },
+ }, &.{}, cancel);
+ result.deinit(a);
+}
+pub fn unsubscribeNoWait(server_name: []const u8, username: []const u8, id: i32) void {
+ var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator);
+ defer arena.deinit();
+ var encoder = begin(arena.allocator(), 0x001b, username) catch return;
+ defer encoder.deinit();
+ encoder.integer(.integer, "notify-subscription-id", id) catch return;
+ http.sendNoWait(server_name, "/", encoder.finish() catch return) catch {};
+}
+pub fn ppd(a: A, io: std.Io, server_name: []const u8, username: []const u8, queue: []const u8, cancel: c_int) ![]const u8 {
+ const target = try queueUri(a, queue);
+ var result = try request(a, io, server_name, username, 0x400f, target, "/", &.{}, &.{}, cancel);
+ defer result.deinit(a);
+ if (result.data.len == 0 or result.data.len > 1024 * 1024) return error.NotFound;
+ return result.data;
+}
+pub fn probe(a: A, io: std.Io, uri: []const u8, username: []const u8, cancel: c_int) !bool {
+ const target = try endpoint.parsePrinterUri(uri);
+ var response = try request(a, io, target.server, username, 11, uri, target.resource, &.{
+ .{ .name = "requested-attributes", .value = .{ .text = "printer-state" } },
+ .{ .name = "", .value = .{ .text = "document-format-supported" } },
+ .{ .name = "", .value = .{ .text = "ipp-features-supported" } },
+ }, &.{}, cancel);
+ defer response.deinit(a);
+ var format = false;
+ var everywhere = false;
+ for (response.attributes) |attr| {
+ const text = attr.text() orelse continue;
+ if (eq(u8, attr.name, "document-format-supported") and (eq(u8, text, "image/pwg-raster") or eq(u8, text, "image/urf"))) format = true;
+ if (eq(u8, attr.name, "ipp-features-supported") and eq(u8, text, "ipp-everywhere")) everywhere = true;
+ }
+ return format or everywhere;
+}
+
+fn find(attrs: []const ipp.Attribute, name: []const u8) ?ipp.Attribute {
+ for (attrs) |attr| if (eq(u8, attr.name, name)) return attr;
+ return null;
+}
+fn int(attrs: []const ipp.Attribute, name: []const u8) ?i32 {
+ var result: ?i32 = null;
+ for (attrs) |attr| if (eq(u8, attr.name, name)) {
+ const value = attr.integer() orelse return null;
+ if (result) |previous| if (previous != value) return null;
+ result = value;
+ };
+ return result;
+}
+fn txt(a: A, attrs: []const ipp.Attribute, name: []const u8) ![]const u8 {
+ const attr = find(attrs, name) orelse return "";
+ return clean(a, attr.text() orelse return "");
+}
+fn deviceUri(a: A, attrs: []const ipp.Attribute) ![]const u8 {
+ return identity(a, attrs, "device-uri", 8192);
+}
+fn identity(a: A, attrs: []const ipp.Attribute, name: []const u8, limit: usize) ![]const u8 {
+ const value = (find(attrs, name) orelse return "").text() orelse return "";
+ for (attrs) |attr| if (eq(u8, attr.name, name) and !eq(u8, attr.text() orelse return "", value)) return "";
+ // Identity must never use display truncation or removal of characters.
+ // An unusable URI gives an unknown diagnostic instead of a false mismatch.
+ if (value.len > limit or !std.unicode.utf8ValidateSlice(value)) return "";
+ for (value) |byte| if (byte < 0x20 or byte == 0x7f) return "";
+ var iter = std.unicode.Utf8View.initUnchecked(value).iterator();
+ while (iter.nextCodepoint()) |cp| if ((cp >= 0x80 and cp <= 0x9f) or (cp >= 0x202a and cp <= 0x202e) or (cp >= 0x2066 and cp <= 0x2069)) return "";
+ return a.dupe(u8, value);
+}
+fn conflictingDefaults(attrs: []const ipp.Attribute) bool {
+ for (attrs, 0..) |attr, i| {
+ if (!std.mem.endsWith(u8, attr.name, "-default")) continue;
+ for (attrs[0..i]) |previous| if (eq(u8, attr.name, previous.name) and (attr.tag != previous.tag or !eq(u8, attr.value, previous.value))) return true;
+ }
+ return false;
+}
+pub fn clean(a: A, value: []const u8) ![]const u8 {
+ if (!std.unicode.utf8ValidateSlice(value)) return a.dupe(u8, "Invalid printer text");
+ var list: std.ArrayList(u8) = .empty;
+ errdefer list.deinit(a);
+ var iter = std.unicode.Utf8View.initUnchecked(value).iterator();
+ while (iter.nextCodepointSlice()) |ch| {
+ if (list.items.len + ch.len > 512) break;
+ const cp = std.unicode.utf8Decode(ch) catch unreachable;
+ // Strip controls and directional overrides from all widget text.
+ if (cp < 32 or (cp >= 0x7f and cp <= 0x9f) or (cp >= 0x202a and cp <= 0x202e) or (cp >= 0x2066 and cp <= 0x2069)) continue;
+ try list.appendSlice(a, ch);
+ }
+ return list.toOwnedSlice(a);
+}
+fn reasons(a: A, attrs: []const ipp.Attribute, name: []const u8) ![]const u8 {
+ var out: std.ArrayList(u8) = .empty;
+ for (attrs) |attr| {
+ if (!eq(u8, attr.name, name) or attr.text() == null) continue;
+ const text = try clean(a, attr.text().?);
+ if (out.items.len + text.len + 2 > 2048) break;
+ if (out.items.len != 0) try out.appendSlice(a, ", ");
+ try out.appendSlice(a, text);
+ }
+ return out.toOwnedSlice(a);
+}
+
+pub fn printers(a: A, message: ipp.Message) ![]Printer {
+ var out: std.ArrayList(Printer) = .empty;
+ var offset: usize = 0;
+ while (offset < message.attributes.len) {
+ var end = offset + 1;
+ while (end < message.attributes.len and message.attributes[end].group_index == message.attributes[offset].group_index) : (end += 1) {}
+ const attrs = message.attributes[offset..end];
+ offset = end;
+ if (attrs[0].group != .printer) continue;
+ if (out.items.len == max_printers) return error.TooManyPrinters;
+ const name = try identity(a, attrs, "printer-name", 127);
+ if (!preferences.validQueue(name)) continue;
+ var markers: std.ArrayList(Marker) = .empty;
+ for (attrs) |attr| if (eq(u8, attr.name, "marker-names") and markers.items.len < 32) {
+ try markers.append(a, .{ .name = try clean(a, attr.text() orelse continue), .level = null });
+ };
+ var index: usize = 0;
+ for (attrs) |attr| if (eq(u8, attr.name, "marker-levels") and index < markers.items.len) {
+ const value = attr.integer();
+ markers.items[index].level = if (value != null and value.? >= 0 and value.? <= 100) value else null;
+ index += 1;
+ };
+ try out.append(a, .{
+ .name = name,
+ .info = try txt(a, attrs, "printer-info"),
+ .model = try txt(a, attrs, "printer-make-and-model"),
+ .device_uri = try deviceUri(a, attrs),
+ .state = int(attrs, "printer-state"),
+ .accepting = if (find(attrs, "printer-is-accepting-jobs")) |attr| attr.boolean() else null,
+ .reasons = try reasons(a, attrs, "printer-state-reasons"),
+ .message = try txt(a, attrs, "printer-state-message"),
+ .media = try txt(a, attrs, "media-default"),
+ .resolution = if (find(attrs, "printer-resolution-default")) |attr| attr.resolution() else null,
+ .color = try txt(a, attrs, "print-color-mode-default"),
+ .sides = try txt(a, attrs, "sides-default"),
+ .markers = try markers.toOwnedSlice(a),
+ .is_default = if (int(attrs, "printer-type")) |value| value & 0x20000 != 0 else false,
+ .device_id = try identity(a, attrs, "printer-device-id", 8192),
+ .label_media = if (find(attrs, "media-type-default")) |attr| std.ascii.eqlIgnoreCase(attr.text() orelse "", "labels") else false,
+ .inconsistent_defaults = conflictingDefaults(attrs),
+ .attributes = try a.dupe(ipp.Attribute, attrs),
+ });
+ }
+ return out.toOwnedSlice(a);
+}
+
+pub fn jobs(a: A, message: ipp.Message, username: []const u8) ![]Job {
+ var out: std.ArrayList(Job) = .empty;
+ var offset: usize = 0;
+ while (offset < message.attributes.len) {
+ var end = offset + 1;
+ while (end < message.attributes.len and message.attributes[end].group_index == message.attributes[offset].group_index) : (end += 1) {}
+ const attrs = message.attributes[offset..end];
+ offset = end;
+ if (attrs[0].group != .job) continue;
+ if (out.items.len == max_jobs) return error.TooManyJobs;
+ const uri = try identity(a, attrs, "job-printer-uri", 8192);
+ if (find(attrs, "job-originating-user-name") == null) continue;
+ const owner = try identity(a, attrs, "job-originating-user-name", 255);
+ const segment = uri[(std.mem.lastIndexOfScalar(u8, uri, '/') orelse continue) + 1 ..];
+ const decoded = std.Uri.percentDecodeInPlace(try a.dupe(u8, segment));
+ if (!preferences.validQueue(decoded)) continue;
+ try out.append(a, .{
+ .id = int(attrs, "job-id") orelse continue,
+ .printer = try a.dupe(u8, decoded),
+ .state = int(attrs, "job-state"),
+ .sheets = int(attrs, "job-media-sheets-completed"),
+ .reasons = try reasons(a, attrs, "job-state-reasons"),
+ .message = try txt(a, attrs, "job-printer-state-message"),
+ .own = eq(u8, owner, username),
+ });
+ }
+ std.mem.sort(Job, out.items, {}, struct {
+ fn less(_: void, lhs: Job, rhs: Job) bool {
+ return lhs.id > rhs.id;
+ }
+ }.less);
+ return out.toOwnedSlice(a);
+}
+
+pub fn printerState(value: ?i32) []const u8 {
+ return switch (value orelse 0) {
+ 3 => "Ready",
+ 4 => "Printing",
+ 5 => "Stopped",
+ else => "State unavailable",
+ };
+}
+pub fn jobState(value: ?i32) []const u8 {
+ return switch (value orelse 0) {
+ 3 => "Pending",
+ 4 => "Held",
+ 5 => "Processing",
+ 6 => "Stopped",
+ 7 => "Cancelled",
+ 8 => "Aborted",
+ 9 => "Completed",
+ else => "State unavailable",
+ };
+}
+pub fn failure(err: anyerror) []const u8 {
+ return switch (err) {
+ error.OutOfMemory => "Not enough memory to load printer status. Refresh to check the result.",
+ error.CupsUnavailable => "CUPS is unavailable. Install or start CUPS, then refresh.",
+ error.UnsupportedServer => "This print server requires an unsupported encrypted or authenticated connection.",
+ error.InvalidMedia, error.MediaTooSmall => "Choose the actual paper dimensions before printing this test.",
+ error.InvalidPreferences, error.AmbiguousPreferences => "Printer preferences could not be saved safely. Check the existing preferences file.",
+ error.PreferencesMigration => "The queue changed, but personal preferences could not be moved. Check your default printer.",
+ error.InvalidClientConfiguration => "The CUPS client configuration could not be read or is invalid.",
+ error.NotAuthorized => "CUPS denied permission. The operation requires authorization.",
+ error.Timeout => "CUPS did not respond in time. Refresh to try again.",
+ error.NotFound => "The printer or job no longer exists. Refresh the list.",
+ error.OperationUnsupported => "This CUPS server does not support the requested operation.",
+ error.UnsupportedPrintSettings => "CUPS cannot honor the requested print settings. Check the paper, format and scaling options.",
+ else => "CUPS returned an invalid response or the connection failed. Refresh to try again.",
+ };
+}
+
+test "display text and configuration parsing" {
+ const a = std.testing.allocator;
+ const cleaned = try clean(a, "Ready\x1b\n\xe2\x80\xae printer");
+ defer a.free(cleaned);
+ try std.testing.expectEqualStrings("Ready printer", cleaned);
+ try std.testing.expectEqualStrings("/tmp/private.sock", (try clientConfig("# ServerName ignored\nServerName /tmp/private.sock # comment\n")).server.?);
+ try std.testing.expectError(error.InvalidClientConfiguration, clientConfig("ServerName\n"));
+ try std.testing.expectEqualStrings("Required", (try clientConfig("Encryption Required\n")).encryption.?);
+ try std.testing.expectEqualStrings("/tmp/print server.sock", (try clientConfig("ServerName /tmp/print server.sock\n")).server.?);
+ try std.testing.expectError(error.InvalidClientConfiguration, clientConfig("ServerName /tmp/print\\#server.sock\n"));
+ try std.testing.expect(!(Job{ .id = 1, .state = 5, .own = false }).cancellable());
+}
+
+test "printer parser keeps groups defaults marker levels and safe display text" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var encoder = try ipp.Encoder.init(a, 0, 1);
+ defer encoder.deinit();
+ try encoder.group(.operation);
+ try encoder.string(.name, "printer-name", "Ignored operation attribute");
+ try encoder.group(.printer);
+ try encoder.string(.name, "printer-name", "Office_Printer");
+ try encoder.string(.text, "printer-make-and-model", "Example Laser");
+ try encoder.string(.uri, "device-uri", "usb://Example/Laser?serial=abc");
+ try encoder.integer(.enum_value, "printer-state", 5);
+ try encoder.boolean("printer-is-accepting-jobs", false);
+ try encoder.integer(.integer, "printer-type", 0x20000);
+ try encoder.string(.keyword, "printer-state-reasons", "media-empty-error");
+ try encoder.string(.keyword, "", "toner-low-warning");
+ try encoder.string(.keyword, "media-default", "iso_a4_210x297mm");
+ try encoder.string(.name, "media-default", "iso_a5_148x210mm");
+ try encoder.value(.resolution, "printer-resolution-default", &.{ 0, 0, 2, 88, 0, 0, 2, 88, 3 });
+ try encoder.string(.name, "marker-names", "Black");
+ try encoder.string(.name, "", "Cyan");
+ try encoder.integer(.integer, "marker-levels", 83);
+ try encoder.integer(.integer, "", -2);
+ try encoder.group(.printer);
+ try encoder.string(.name, "printer-name", "Label");
+ try encoder.group(.printer);
+ try encoder.string(.text, "printer-info", "Missing name is skipped");
+ try encoder.group(.printer);
+ try encoder.string(.name, "printer-name", "Office\n_Printer");
+ try encoder.group(.printer);
+ try encoder.string(.name, "printer-name", "Conflicting_Queue");
+ try encoder.string(.name, "printer-name", "Other_Queue");
+ var message = try ipp.decode(a, try encoder.finish(), .{ .allow_duplicate_names = true });
+ defer message.deinit(a);
+ const result = try printers(a, message);
+ try std.testing.expectEqual(@as(usize, 2), result.len);
+ try std.testing.expectEqualStrings("Office_Printer", result[0].name);
+ try std.testing.expectEqualStrings("Example Laser", result[0].model);
+ try std.testing.expectEqualStrings("usb://Example/Laser?serial=abc", result[0].device_uri);
+ try std.testing.expectEqual(@as(?i32, 5), result[0].state);
+ try std.testing.expectEqual(@as(?bool, false), result[0].accepting);
+ try std.testing.expect(result[0].is_default);
+ try std.testing.expectEqualStrings("media-empty-error, toner-low-warning", result[0].reasons);
+ try std.testing.expectEqualStrings("iso_a4_210x297mm", result[0].media);
+ try std.testing.expect(result[0].inconsistent_defaults);
+ try std.testing.expectEqual(@as(i32, 600), result[0].resolution.?.x);
+ try std.testing.expectEqual(@as(usize, 2), result[0].markers.len);
+ try std.testing.expectEqual(@as(?i32, 83), result[0].markers[0].level);
+ try std.testing.expectEqual(@as(?i32, null), result[0].markers[1].level);
+ try std.testing.expectEqualStrings("Label", result[1].name);
+ try std.testing.expect(result[1].state == null and result[1].accepting == null);
+ try std.testing.expect(result[1].markers.len == 0 and !result[1].is_default);
+}
+
+test "job parser preserves zero sheets decodes queue names and checks raw ownership" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var encoder = try ipp.Encoder.init(a, 0, 1);
+ defer encoder.deinit();
+ try encoder.group(.operation);
+ try encoder.group(.job);
+ try encoder.integer(.integer, "job-id", 3);
+ try encoder.string(.uri, "job-printer-uri", "ipp://localhost/printers/Office%5FPrinter");
+ try encoder.string(.name, "job-originating-user-name", "alice");
+ try encoder.integer(.enum_value, "job-state", 9);
+ try encoder.integer(.integer, "job-media-sheets-completed", 0);
+ try encoder.string(.text, "job-printer-state-message", "No pages were found.\n");
+ try encoder.group(.job);
+ try encoder.integer(.integer, "job-id", 99);
+ try encoder.string(.uri, "job-printer-uri", "ipp://localhost/printers/Label");
+ try encoder.string(.name, "job-originating-user-name", "alice\n");
+ try encoder.integer(.enum_value, "job-state", 5);
+ try encoder.group(.job);
+ try encoder.integer(.integer, "job-id", 101);
+ try encoder.string(.uri, "job-printer-uri", "ipp://localhost/printers/Label");
+ // A record without an owner must never acquire cancellation permission.
+ var message = try ipp.decode(a, try encoder.finish(), .{});
+ defer message.deinit(a);
+ const result = try jobs(a, message, "alice");
+ try std.testing.expectEqual(@as(usize, 2), result.len);
+ try std.testing.expectEqual(@as(i32, 99), result[0].id);
+ try std.testing.expect(!result[0].own and !result[0].cancellable());
+ try std.testing.expectEqual(@as(i32, 3), result[1].id);
+ try std.testing.expectEqualStrings("Office_Printer", result[1].printer);
+ try std.testing.expectEqual(@as(?i32, 0), result[1].sheets);
+ try std.testing.expectEqualStrings("No pages were found.", result[1].message);
+ try std.testing.expect(result[1].own and !result[1].cancellable());
+ for (3..7) |state| try std.testing.expect((Job{ .id = 1, .state = @intCast(state), .own = true }).cancellable());
+ try std.testing.expect(!(Job{ .id = 0, .state = 5, .own = true }).cancellable());
+ try std.testing.expect(!(Job{ .id = 1, .own = true }).cancellable());
+}
+
+test "printer and job parsers bound result counts" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var printer_encoder = try ipp.Encoder.init(a, 0, 1);
+ defer printer_encoder.deinit();
+ try printer_encoder.group(.operation);
+ for (0..max_printers + 1) |_| {
+ try printer_encoder.group(.printer);
+ try printer_encoder.string(.name, "printer-name", "Queue");
+ }
+ var printer_message = try ipp.decode(a, try printer_encoder.finish(), .{});
+ defer printer_message.deinit(a);
+ try std.testing.expectError(error.TooManyPrinters, printers(a, printer_message));
+ var job_encoder = try ipp.Encoder.init(a, 0, 1);
+ defer job_encoder.deinit();
+ try job_encoder.group(.operation);
+ for (0..max_jobs + 1) |index| {
+ try job_encoder.group(.job);
+ try job_encoder.integer(.integer, "job-id", @intCast(index + 1));
+ try job_encoder.string(.uri, "job-printer-uri", "ipp://localhost/printers/Queue");
+ try job_encoder.string(.name, "job-originating-user-name", "alice");
+ }
+ var job_message = try ipp.decode(a, try job_encoder.finish(), .{});
+ defer job_message.deinit(a);
+ try std.testing.expectError(error.TooManyJobs, jobs(a, job_message, "alice"));
+}
diff --git a/src/printing/daemon_watch.zig b/src/printing/daemon_watch.zig
new file mode 100644
index 0000000..c0e6360
--- /dev/null
+++ b/src/printing/daemon_watch.zig
@@ -0,0 +1,147 @@
+//! Socket-directory events complement CUPS subscriptions: a daemon can vanish
+//! before sending an IPP notification. This watcher never opens the socket.
+const std = @import("std");
+const endpoint = @import("endpoint.zig");
+const c = @cImport({
+ @cUndef("_FORTIFY_SOURCE");
+ @cInclude("sys/inotify.h");
+ @cInclude("unistd.h");
+});
+const A = std.mem.Allocator;
+
+pub const Watch = struct {
+ fd: c_int,
+ basename: []u8,
+ watch: c_int,
+
+ /// No watcher is needed for a remote server. Missing/inaccessible parent
+ /// directories retain explicit refresh rather than starting a retry timer.
+ pub fn init(a: A, server: []const u8) !?Watch {
+ const target = try endpoint.parseServer(server);
+ const socket = target.unix orelse return null;
+ const parent = std.fs.path.dirname(socket) orelse return null;
+ const name = std.fs.path.basename(socket);
+ if (name.len == 0 or std.mem.eql(u8, name, "/")) return null;
+ const basename = try a.dupe(u8, name);
+ errdefer a.free(basename);
+ const directory = try a.dupeZ(u8, parent);
+ defer a.free(directory);
+ const fd = c.inotify_init1(c.IN_CLOEXEC | c.IN_NONBLOCK);
+ if (fd < 0) {
+ a.free(basename);
+ return null;
+ }
+ const watch = c.inotify_add_watch(fd, directory, c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_TO | c.IN_MOVED_FROM | c.IN_ATTRIB | c.IN_DELETE_SELF | c.IN_MOVE_SELF | c.IN_UNMOUNT);
+ if (watch < 0) {
+ _ = c.close(fd);
+ a.free(basename);
+ return null;
+ }
+ return .{ .fd = fd, .basename = basename, .watch = watch };
+ }
+
+ pub fn deinit(self: *Watch, a: A) void {
+ if (self.fd >= 0) _ = c.close(self.fd);
+ a.free(self.basename);
+ self.* = undefined;
+ }
+
+ /// Drain a bounded burst, coalescing all relevant events into one reload.
+ /// Invalidated watches close immediately so poll cannot spin on an error.
+ pub fn changed(self: *Watch) bool {
+ if (self.fd < 0) return false;
+ var changed_socket = false;
+ var reads: usize = 0;
+ while (reads < 8) : (reads += 1) {
+ var bytes: [8192]u8 = undefined;
+ const n = c.read(self.fd, &bytes, bytes.len);
+ if (n < 0) {
+ const err = std.posix.errno(n);
+ if (err == .INTR) continue;
+ if (err == .AGAIN) return changed_socket;
+ self.close();
+ return true;
+ }
+ if (n == 0) {
+ self.close();
+ return true;
+ }
+ var offset: usize = 0;
+ const data = bytes[0..@intCast(n)];
+ while (data.len - offset >= @sizeOf(c.struct_inotify_event)) {
+ const event = std.mem.bytesToValue(c.struct_inotify_event, data[offset..][0..@sizeOf(c.struct_inotify_event)]);
+ offset += @sizeOf(c.struct_inotify_event);
+ if (event.len > data.len - offset) {
+ self.close();
+ return true;
+ }
+ if (event.mask & c.IN_Q_OVERFLOW != 0) changed_socket = true;
+ if (event.wd == self.watch) {
+ if (event.mask & (c.IN_IGNORED | c.IN_DELETE_SELF | c.IN_MOVE_SELF | c.IN_UNMOUNT) != 0) {
+ self.close();
+ return true;
+ }
+ const name = std.mem.sliceTo(data[offset..][0..event.len], 0);
+ if (std.mem.eql(u8, name, self.basename)) changed_socket = true;
+ }
+ offset += event.len;
+ }
+ if (offset != data.len) {
+ self.close();
+ return true;
+ }
+ }
+ return changed_socket;
+ }
+
+ fn close(self: *Watch) void {
+ if (self.fd >= 0) _ = c.close(self.fd);
+ self.fd = -1;
+ }
+};
+
+test "CUPS socket watcher coalesces exact-name create, rename, delete and parent loss" {
+ const t = std.testing;
+ const io = t.io;
+ var tmp = t.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", t.allocator);
+ defer t.allocator.free(root);
+ const socket = try std.fs.path.join(t.allocator, &.{ root, "cups.sock" });
+ defer t.allocator.free(socket);
+ var watcher = (try Watch.init(t.allocator, socket)).?;
+ defer watcher.deinit(t.allocator);
+ try t.expect(!watcher.changed());
+ try tmp.dir.writeFile(io, .{ .sub_path = "unrelated", .data = "" });
+ try t.expect(!watcher.changed());
+ try tmp.dir.writeFile(io, .{ .sub_path = "cups.sock", .data = "" });
+ try t.expect(watcher.changed());
+ try t.expect(!watcher.changed());
+ try tmp.dir.rename("cups.sock", tmp.dir, "old.sock", io);
+ try t.expect(watcher.changed());
+ try tmp.dir.rename("old.sock", tmp.dir, "cups.sock", io);
+ try t.expect(watcher.changed());
+ try tmp.dir.deleteFile(io, "cups.sock");
+ try t.expect(watcher.changed());
+ // Moving a watched directory invalidates this watcher; it closes the fd
+ // and subsequent calls remain inert until the owner creates a new one.
+ const moved = try std.fmt.allocPrint(t.allocator, "{s}-moved", .{root});
+ defer t.allocator.free(moved);
+ try std.Io.Dir.cwd().rename(root, .cwd(), moved, io);
+ defer std.Io.Dir.cwd().rename(moved, .cwd(), root, io) catch {};
+ try t.expect(watcher.changed());
+ try t.expectEqual(@as(c_int, -1), watcher.fd);
+ try t.expect(!watcher.changed());
+}
+
+test "CUPS socket watcher is absent for remote or unavailable parents" {
+ const t = std.testing;
+ try t.expectEqual(@as(?Watch, null), try Watch.init(t.allocator, "printer.example:631"));
+ var tmp = t.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(t.io, ".", t.allocator);
+ defer t.allocator.free(root);
+ const socket = try std.fs.path.join(t.allocator, &.{ root, "missing", "cups.sock" });
+ defer t.allocator.free(socket);
+ try t.expectEqual(@as(?Watch, null), try Watch.init(t.allocator, socket));
+}
diff --git a/src/printing/endpoint.zig b/src/printing/endpoint.zig
new file mode 100644
index 0000000..8769965
--- /dev/null
+++ b/src/printing/endpoint.zig
@@ -0,0 +1,99 @@
+//! Complete endpoint identity, without credentials, redirects or TLS downgrade.
+const std = @import("std");
+
+pub const Endpoint = struct {
+ unix: ?[]const u8 = null,
+ host: []const u8 = "localhost",
+ authority: []const u8 = "localhost",
+ server: []const u8 = "localhost",
+ uri: []const u8 = "",
+ port: u16 = 631,
+ resource: []const u8 = "/",
+ version_minor: u8 = 1,
+};
+
+/// CUPS_SERVER / ServerName accepts a Unix socket or host[:port][/version=1.1].
+/// IPP versions are retained so requests can honour an explicit 1.0 selection.
+pub fn parseServer(value: []const u8) !Endpoint {
+ if (value.len == 0 or value.len > 1024) return error.UnsupportedServer;
+ if (value[0] == '/') {
+ if (value.len >= 108 or std.mem.indexOfScalar(u8, value, 0) != null) return error.UnsupportedServer;
+ return .{ .unix = value, .server = value };
+ }
+ const rest = if (std.mem.startsWith(u8, value, "ipp://")) value[6..] else value;
+ if (std.mem.indexOf(u8, rest, "://") != null) return error.UnsupportedServer;
+ const slash = std.mem.indexOfScalar(u8, rest, '/') orelse rest.len;
+ var result = try authority(rest[0..slash]);
+ const suffix = rest[slash..];
+ if (suffix.len != 0 and !std.mem.eql(u8, suffix, "/")) {
+ if (std.mem.eql(u8, suffix, "/version=1.0")) result.version_minor = 0 else if (!std.mem.eql(u8, suffix, "/version=1.1")) return error.UnsupportedServer;
+ }
+ return result;
+}
+
+/// Only direct IPP is probed. ipps remains unavailable until TLS can validate
+/// certificates; interpreting it as cleartext would disclose private traffic.
+pub fn parsePrinterUri(uri: []const u8) !Endpoint {
+ if (uri.len > 2048 or !std.mem.startsWith(u8, uri, "ipp://")) return error.UnsupportedServer;
+ const rest = uri[6..];
+ const slash = std.mem.indexOfScalar(u8, rest, '/') orelse rest.len;
+ var result = try authority(rest[0..slash]);
+ result.resource = if (slash == rest.len) "/" else rest[slash..];
+ result.uri = uri;
+ try validateResource(result.resource);
+ return result;
+}
+
+pub fn validateResource(value: []const u8) !void {
+ if (value.len == 0 or value[0] != '/' or value.len > 2048) return error.InvalidResource;
+ for (value) |byte| if (byte < 0x21 or byte > 0x7e or byte == '#') return error.InvalidResource;
+}
+
+fn authority(value: []const u8) !Endpoint {
+ if (value.len == 0 or value.len > 320) return error.UnsupportedServer;
+ for (value) |byte| if (byte <= 0x20 or byte >= 0x7f or byte == '@' or byte == '\\' or byte == '?' or byte == '#') return error.UnsupportedServer;
+ var host = value;
+ var port: u16 = 631;
+ if (value[0] == '[') {
+ const end = std.mem.indexOfScalar(u8, value, ']') orelse return error.UnsupportedServer;
+ host = value[1..end];
+ // Interface identifiers require OS lookup and are deliberately not
+ // accepted in this initial bounded transport.
+ _ = std.Io.net.IpAddress.parseIp6(host, 631) catch return error.UnsupportedServer;
+ if (end + 1 < value.len) {
+ if (value[end + 1] != ':') return error.UnsupportedServer;
+ port = try parsePort(value[end + 2 ..]);
+ }
+ } else {
+ if (std.mem.indexOfScalar(u8, value, ':')) |colon| {
+ host = value[0..colon];
+ port = try parsePort(value[colon + 1 ..]);
+ }
+ _ = std.Io.net.HostName.init(host) catch return error.UnsupportedServer;
+ }
+ return .{ .host = host, .authority = value, .server = value, .port = port };
+}
+
+fn parsePort(value: []const u8) !u16 {
+ if (value.len == 0) return error.UnsupportedServer;
+ for (value) |byte| if (!std.ascii.isDigit(byte)) return error.UnsupportedServer;
+ const port = std.fmt.parseInt(u16, value, 10) catch return error.UnsupportedServer;
+ if (port == 0) return error.UnsupportedServer;
+ return port;
+}
+
+test "CUPS endpoints retain identity and reject encryption, credentials and ambiguity" {
+ const t = std.testing;
+ try t.expectEqualStrings("/tmp/cups.sock", (try parseServer("/tmp/cups.sock")).unix.?);
+ const remote = try parseServer("printer.example:8631/version=1.0");
+ try t.expectEqualStrings("printer.example", remote.host);
+ try t.expectEqual(@as(u16, 8631), remote.port);
+ try t.expectEqual(@as(u8, 0), remote.version_minor);
+ try t.expectEqual(@as(u16, 631), (try parseServer("ipp://[::1]/version=1.1")).port);
+ const printer = try parsePrinterUri("ipp://127.0.0.1:8631/ipp/print?queue=1");
+ try t.expectEqualStrings("/ipp/print?queue=1", printer.resource);
+ for ([_][]const u8{ "", "ipps://printer", "https://printer", "user@printer", "printer:0", "printer:65536", "printer\r\nHost: x", "printer/path", "::1", "[::1]:bad", "printer/version=2.0" }) |bad| try t.expectError(error.UnsupportedServer, parseServer(bad));
+ try t.expectError(error.UnsupportedServer, parsePrinterUri("ipps://printer/ipp/print"));
+ try t.expectError(error.UnsupportedServer, parsePrinterUri("ipp://user:secret@printer/ipp/print"));
+ try t.expectError(error.InvalidResource, parsePrinterUri("ipp://printer/ipp/print#fragment"));
+}
diff --git a/src/printing/http.zig b/src/printing/http.zig
new file mode 100644
index 0000000..c1b8875
--- /dev/null
+++ b/src/printing/http.zig
@@ -0,0 +1,436 @@
+//! Bounded, cancellable HTTP/1.1 over Unix sockets or plain TCP. DNS, connect,
+//! upload and response share one deadline. No credentials or redirects.
+const std = @import("std");
+const c = @import("native.zig").c;
+pub const endpoint = @import("endpoint.zig");
+const A = std.mem.Allocator;
+const max_header = 16 * 1024;
+const max_body = 2 * 1024 * 1024;
+const deadline_ms = 3000;
+
+pub fn nowMs() i64 {
+ var ts: c.struct_timespec = undefined;
+ if (c.clock_gettime(c.CLOCK_MONOTONIC, &ts) != 0) return 0;
+ return ts.tv_sec * 1000 + @divTrunc(ts.tv_nsec, 1_000_000);
+}
+
+fn ready(fd: c_int, events: c_short, cancel: c_int, deadline: i64) !void {
+ while (true) {
+ const remaining = deadline - nowMs();
+ if (remaining <= 0) return error.Timeout;
+ var fds = [_]c.struct_pollfd{ .{ .fd = fd, .events = events, .revents = 0 }, .{ .fd = cancel, .events = c.POLLIN, .revents = 0 } };
+ const n = c.poll(&fds, fds.len, @intCast(remaining));
+ if (n < 0) {
+ if (std.posix.errno(n) == .INTR) continue;
+ return error.ConnectionFailed;
+ }
+ if (n == 0) return error.Timeout;
+ if (fds[1].revents != 0) return error.Cancelled;
+ if (fds[0].revents != 0) return;
+ }
+}
+
+fn sendAll(fd: c_int, bytes: []const u8, cancel: c_int, deadline: i64) !void {
+ var offset: usize = 0;
+ while (offset < bytes.len) {
+ try ready(fd, c.POLLOUT, cancel, deadline);
+ const n = c.send(fd, bytes[offset..].ptr, bytes.len - offset, c.MSG_NOSIGNAL);
+ if (n < 0) {
+ const e = std.posix.errno(n);
+ if (e == .AGAIN or e == .INTR) continue;
+ return error.ConnectionFailed;
+ }
+ if (n == 0) return error.ConnectionFailed;
+ offset += @intCast(n);
+ }
+}
+
+pub const Info = struct {
+ cups_version: [32]u8 = @splat(0),
+ len: usize = 0,
+ pub fn version(self: *const Info) []const u8 {
+ return self.cups_version[0..self.len];
+ }
+};
+
+const Header = struct { body: usize, length: ?usize = null, chunked: bool = false, info: Info = .{} };
+fn header(bytes: []const u8) !?Header {
+ const end = std.mem.indexOf(u8, bytes, "\r\n\r\n") orelse {
+ if (bytes.len > max_header) return error.ResponseTooLarge;
+ return null;
+ };
+ if (end > max_header) return error.ResponseTooLarge;
+ var lines = std.mem.splitSequence(u8, bytes[0..end], "\r\n");
+ const status = lines.next() orelse return error.InvalidHttp;
+ if (!(std.mem.startsWith(u8, status, "HTTP/1.1 ") or std.mem.startsWith(u8, status, "HTTP/1.0 ")) or status.len < 12) return error.InvalidHttp;
+ if (status.len > 12 and status[12] != ' ') return error.InvalidHttp;
+ const code = std.fmt.parseInt(u16, status[9..12], 10) catch return error.InvalidHttp;
+ if (code == 401 or code == 403) return error.NotAuthorized;
+ if (code != 200) return error.HttpError;
+ var h: Header = .{ .body = end + 4 };
+ var content_type = false;
+ while (lines.next()) |line| {
+ const sep = std.mem.indexOfScalar(u8, line, ':') orelse return error.InvalidHttp;
+ const name = line[0..sep];
+ const value = std.mem.trim(u8, line[sep + 1 ..], " \t");
+ if (std.ascii.eqlIgnoreCase(name, "Content-Length")) {
+ if (h.length != null) return error.InvalidHttp;
+ if (value.len == 0) return error.InvalidHttp;
+ for (value) |byte| if (!std.ascii.isDigit(byte)) return error.InvalidHttp;
+ h.length = std.fmt.parseInt(usize, value, 10) catch return error.InvalidHttp;
+ if (h.length.? > max_body) return error.ResponseTooLarge;
+ } else if (std.ascii.eqlIgnoreCase(name, "Transfer-Encoding")) {
+ if (h.chunked or !std.ascii.eqlIgnoreCase(value, "chunked")) return error.InvalidHttp;
+ h.chunked = true;
+ } else if (std.ascii.eqlIgnoreCase(name, "Content-Type")) {
+ const mime = std.mem.trim(u8, value[0 .. std.mem.indexOfScalar(u8, value, ';') orelse value.len], " \t");
+ if (!std.ascii.eqlIgnoreCase(mime, "application/ipp")) return error.InvalidHttp;
+ content_type = true;
+ } else if (std.ascii.eqlIgnoreCase(name, "Server")) {
+ // Keep only the version token. Arbitrary server strings can carry
+ // host names or other private text and never enter a report.
+ if (std.mem.startsWith(u8, value, "CUPS/")) {
+ const rest = value[5..];
+ const end_version = std.mem.indexOfAny(u8, rest, " \t") orelse rest.len;
+ const version = rest[0..end_version];
+ var valid = version.len > 0 and version.len <= h.info.cups_version.len;
+ for (version) |byte| if (!(std.ascii.isDigit(byte) or byte == '.' or byte == '-')) {
+ valid = false;
+ };
+ if (valid) {
+ @memcpy(h.info.cups_version[0..version.len], version);
+ h.info.len = version.len;
+ }
+ }
+ }
+ }
+ if (!content_type or (h.length != null and h.chunked)) return error.InvalidHttp;
+ return h;
+}
+
+/// Validate the complete chunk stream before allocating its decoded body.
+fn chunkSize(bytes: []const u8, output: ?[]u8) !?usize {
+ var offset: usize = 0;
+ var count: usize = 0;
+ var chunks: usize = 0;
+ while (true) {
+ const end = std.mem.indexOfPos(u8, bytes, offset, "\r\n") orelse return null;
+ if (end - offset > 128) return error.InvalidHttp;
+ const line = bytes[offset..end];
+ const len = std.fmt.parseInt(usize, line[0 .. std.mem.indexOfScalar(u8, line, ';') orelse line.len], 16) catch return error.InvalidHttp;
+ offset = end + 2;
+ if (len == 0) {
+ if (bytes.len - offset < 2) return null;
+ // CUPS does not send trailers. Bound and validate any it does.
+ if (!std.mem.startsWith(u8, bytes[offset..], "\r\n")) {
+ const trailer = std.mem.indexOfPos(u8, bytes, offset, "\r\n\r\n") orelse {
+ if (bytes.len - offset > max_header) return error.ResponseTooLarge;
+ return null;
+ };
+ if (trailer - offset > max_header) return error.ResponseTooLarge;
+ }
+ return count;
+ }
+ if (len > max_body - count) return error.ResponseTooLarge;
+ chunks += 1;
+ if (chunks > 16384) return error.ResponseTooLarge;
+ if (len > bytes.len - offset or bytes.len - offset - len < 2) return null;
+ if (!std.mem.eql(u8, bytes[offset + len ..][0..2], "\r\n")) return error.InvalidHttp;
+ if (output) |out| @memcpy(out[count..][0..len], bytes[offset..][0..len]);
+ count += len;
+ offset += len + 2;
+ }
+}
+
+pub fn request(a: A, socket: []const u8, resource: []const u8, body: []const u8, cancel: c_int) ![]u8 {
+ return requestWithIo(a, null, try endpoint.parseServer(socket), resource, body, cancel, null);
+}
+
+pub fn requestIo(a: A, io: std.Io, server: []const u8, resource: []const u8, body: []const u8, cancel: c_int) ![]u8 {
+ return requestWithIo(a, io, try endpoint.parseServer(server), resource, body, cancel, null);
+}
+
+pub fn requestIoInfo(a: A, io: std.Io, server: []const u8, resource: []const u8, body: []const u8, cancel: c_int, info: *Info) ![]u8 {
+ info.* = .{};
+ return requestWithIo(a, io, try endpoint.parseServer(server), resource, body, cancel, info);
+}
+
+/// Probe only the supplied IPP URI; never discover a host or try other ports.
+pub fn requestUri(a: A, io: std.Io, uri: []const u8, body: []const u8, cancel: c_int) ![]u8 {
+ const target = try endpoint.parsePrinterUri(uri);
+ return requestWithIo(a, io, target, target.resource, body, cancel, null);
+}
+
+/// Best-effort cancellation when hiding a local page. There is no waiting,
+/// reply, retained socket, worker or timer. A full send means queued to CUPS,
+/// not acknowledged; failure cannot delay compositor teardown.
+pub fn sendNoWait(server: []const u8, resource: []const u8, body: []const u8) !void {
+ const target = try endpoint.parseServer(server);
+ const socket = target.unix orelse return error.UnsupportedServer;
+ try endpoint.validateResource(resource);
+ if (body.len > 1024) return error.RequestTooLarge;
+ const fd = c.socket(c.AF_UNIX, c.SOCK_STREAM | c.SOCK_NONBLOCK | c.SOCK_CLOEXEC, 0);
+ if (fd < 0) return error.ConnectionFailed;
+ defer _ = c.close(fd);
+ var addr: c.struct_sockaddr_un = std.mem.zeroes(c.struct_sockaddr_un);
+ addr.sun_family = c.AF_UNIX;
+ @memcpy(addr.sun_path[0..socket.len], socket);
+ if (c.connect(fd, @ptrCast(&addr), @intCast(@offsetOf(c.struct_sockaddr_un, "sun_path") + socket.len + 1)) != 0) return error.ConnectionFailed;
+ var packet: [2048]u8 = undefined;
+ const headers = std.fmt.bufPrint(&packet, "POST {s} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/ipp\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n", .{ resource, body.len }) catch return error.RequestTooLarge;
+ if (headers.len + body.len > packet.len) return error.RequestTooLarge;
+ @memcpy(packet[headers.len..][0..body.len], body);
+ const length = headers.len + body.len;
+ const sent = c.send(fd, &packet, length, c.MSG_NOSIGNAL | c.MSG_DONTWAIT);
+ if (sent < 0 or @as(usize, @intCast(sent)) != length) return error.ConnectionFailed;
+}
+
+fn requestWithIo(a: A, io: ?std.Io, target: endpoint.Endpoint, resource: []const u8, body: []const u8, cancel: c_int, info: ?*Info) ![]u8 {
+ try endpoint.validateResource(resource);
+ const deadline = nowMs() + deadline_ms;
+ const fd = if (target.unix) |socket| try connectUnix(socket, cancel, deadline) else try connectTcp(io, target, cancel, deadline);
+ defer _ = c.close(fd);
+ const headers = try std.fmt.allocPrint(a, "POST {s} HTTP/1.1\r\nHost: {s}\r\nContent-Type: application/ipp\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n", .{ resource, target.authority, body.len });
+ defer a.free(headers);
+ try sendAll(fd, headers, cancel, deadline);
+ try sendAll(fd, body, cancel, deadline);
+ return response(a, fd, cancel, deadline, info);
+}
+
+fn connectUnix(socket: []const u8, cancel: c_int, deadline: i64) !c_int {
+ const fd = c.socket(c.AF_UNIX, c.SOCK_STREAM | c.SOCK_NONBLOCK | c.SOCK_CLOEXEC, 0);
+ if (fd < 0) return error.ConnectionFailed;
+ errdefer _ = c.close(fd);
+ var addr: c.struct_sockaddr_un = std.mem.zeroes(c.struct_sockaddr_un);
+ addr.sun_family = c.AF_UNIX;
+ @memcpy(addr.sun_path[0..socket.len], socket);
+ const result = c.connect(fd, @ptrCast(&addr), @intCast(@offsetOf(c.struct_sockaddr_un, "sun_path") + socket.len + 1));
+ if (result < 0) {
+ const e = std.posix.errno(result);
+ if (e == .NOENT or e == .CONNREFUSED) return error.CupsUnavailable;
+ if (e == .ACCES) return error.NotAuthorized;
+ if (e != .INPROGRESS and e != .AGAIN) return error.ConnectionFailed;
+ try connected(fd, cancel, deadline);
+ }
+ return fd;
+}
+
+fn connected(fd: c_int, cancel: c_int, deadline: i64) !void {
+ try ready(fd, c.POLLOUT, cancel, deadline);
+ var sock_error: c_int = 0;
+ var length: c.socklen_t = @sizeOf(c_int);
+ if (c.getsockopt(fd, c.SOL_SOCKET, c.SO_ERROR, &sock_error, &length) != 0 or sock_error != 0) return error.ConnectionFailed;
+}
+
+const Addresses = struct { values: [32]std.Io.net.IpAddress = undefined, count: usize = 0 };
+
+/// Zig's Linux resolver uses cancellable DNS sockets, rather than libc's
+/// blocking getaddrinfo/NSS. Completion uses an eventfd so the existing page
+/// cancellation fd interrupts resolution as well as ordinary socket I/O.
+fn lookup(io: std.Io, host: []const u8, port: u16, done: c_int, result: *Addresses) anyerror!void {
+ defer {
+ var one: u64 = 1;
+ _ = c.write(done, &one, @sizeOf(u64));
+ }
+ const name = try std.Io.net.HostName.init(host);
+ var buffer: [32]std.Io.net.HostName.LookupResult = undefined;
+ var queue: std.Io.Queue(std.Io.net.HostName.LookupResult) = .init(&buffer);
+ var resolver = try io.concurrent(std.Io.net.HostName.lookup, .{ name, io, &queue, .{ .port = port } });
+ defer resolver.cancel(io) catch {};
+ // Drain while resolving: a large local hosts file must not fill the queue
+ // and stall a valid endpoint. Retain a fixed number of addresses only.
+ while (queue.getOne(io)) |value| {
+ if (value == .address and result.count < result.values.len) {
+ result.values[result.count] = value.address;
+ result.count += 1;
+ }
+ } else |err| switch (err) {
+ error.Canceled => return err,
+ error.Closed => {},
+ }
+ try resolver.await(io);
+ if (result.count == 0) return error.UnknownHostName;
+}
+
+fn connectTcp(io: ?std.Io, target: endpoint.Endpoint, cancel: c_int, deadline: i64) !c_int {
+ var addresses: Addresses = .{};
+ if (std.Io.net.IpAddress.parse(target.host, target.port)) |address| {
+ addresses.values[0] = address;
+ addresses.count = 1;
+ } else |_| {
+ const resolver_io = io orelse return error.DnsRequiresIo;
+ const done = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK);
+ if (done < 0) return error.ConnectionFailed;
+ defer _ = c.close(done);
+ var task = try resolver_io.concurrent(lookup, .{ resolver_io, target.host, target.port, done, &addresses });
+ defer task.cancel(resolver_io) catch {};
+ try ready(done, c.POLLIN, cancel, deadline);
+ try task.await(resolver_io);
+ }
+ for (addresses.values[0..addresses.count]) |address| {
+ const family: c_int = if (address == .ip4) c.AF_INET else c.AF_INET6;
+ const fd = c.socket(family, c.SOCK_STREAM | c.SOCK_NONBLOCK | c.SOCK_CLOEXEC, 0);
+ if (fd < 0) continue;
+ const result = switch (address) {
+ .ip4 => |ip| blk: {
+ var addr: std.os.linux.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, ip.port), .addr = @bitCast(ip.bytes) };
+ break :blk c.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr)));
+ },
+ .ip6 => |ip| blk: {
+ var addr: std.os.linux.sockaddr.in6 = .{ .port = std.mem.nativeToBig(u16, ip.port), .flowinfo = ip.flow, .addr = ip.bytes, .scope_id = ip.interface.index };
+ break :blk c.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr)));
+ },
+ };
+ if (result == 0) return fd;
+ const err = std.posix.errno(result);
+ if (err == .INPROGRESS or err == .AGAIN) {
+ connected(fd, cancel, deadline) catch |failure| {
+ _ = c.close(fd);
+ if (failure == error.Timeout or failure == error.Cancelled) return failure;
+ continue;
+ };
+ return fd;
+ }
+ _ = c.close(fd);
+ }
+ return error.CupsUnavailable;
+}
+
+fn response(a: A, fd: c_int, cancel: c_int, deadline: i64, info: ?*Info) ![]u8 {
+ var bytes: std.ArrayList(u8) = .empty;
+ defer bytes.deinit(a);
+ var parsed: ?Header = null;
+ while (true) {
+ try ready(fd, c.POLLIN, cancel, deadline);
+ var scratch: [8192]u8 = undefined;
+ const n = c.recv(fd, &scratch, scratch.len, 0);
+ if (n < 0) {
+ const e = std.posix.errno(n);
+ if (e == .AGAIN or e == .INTR) continue;
+ return error.ConnectionFailed;
+ }
+ if (n > 0) {
+ if (bytes.items.len + @as(usize, @intCast(n)) > max_body + max_header) return error.ResponseTooLarge;
+ try bytes.appendSlice(a, scratch[0..@intCast(n)]);
+ }
+ if (parsed == null) parsed = try header(bytes.items);
+ if (parsed) |h| {
+ if (info) |out| out.* = h.info;
+ const data = bytes.items[h.body..];
+ if (h.chunked) {
+ if (try chunkSize(data, null)) |size| {
+ const out = try a.alloc(u8, size);
+ errdefer a.free(out);
+ _ = try chunkSize(data, out);
+ return out;
+ }
+ } else if (h.length) |len| {
+ if (data.len >= len) return a.dupe(u8, data[0..len]);
+ } else if (n == 0) return a.dupe(u8, data);
+ }
+ if (n == 0) return error.TruncatedResponse;
+ }
+}
+
+test "HTTP bounds, status, framing ambiguity and chunks" {
+ const t = std.testing;
+ try t.expect((try header("HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nContent-Length: 4\r\n\r\n1234")).?.length.? == 4);
+ try t.expectError(error.NotAuthorized, header("HTTP/1.1 403 Forbidden\r\n\r\n"));
+ try t.expectError(error.InvalidHttp, header("HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nContent-Length: 4\r\nTransfer-Encoding: chunked\r\n\r\n"));
+ try t.expectError(error.InvalidHttp, header("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"));
+ try t.expectEqual(@as(?usize, null), try chunkSize("4\r\n12", null));
+ try t.expectEqual(@as(?usize, 5), try chunkSize("2\r\nab\r\n3\r\ncde\r\n0\r\n\r\n", null));
+ var out: [5]u8 = undefined;
+ _ = try chunkSize("2\r\nab\r\n3\r\ncde\r\n0\r\n\r\n", &out);
+ try t.expectEqualStrings("abcde", &out);
+ try t.expectError(error.ResponseTooLarge, chunkSize("fffffffffffffff\r\n", null));
+ const versioned = (try header("HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nServer: CUPS/2.4.20 IPP/2.1\r\nContent-Length: 0\r\n\r\n")).?;
+ try t.expectEqualStrings("2.4.20", versioned.info.version());
+ const hostile = (try header("HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nServer: CUPS/private.example\r\nContent-Length: 0\r\n\r\n")).?;
+ try t.expectEqualStrings("", hostile.info.version());
+}
+
+test "remote loopback HTTP preserves authority, resource and body" {
+ const t = std.testing;
+ const listener = c.socket(c.AF_INET, c.SOCK_STREAM | c.SOCK_CLOEXEC, 0);
+ try t.expect(listener >= 0);
+ defer _ = c.close(listener);
+ var address: std.os.linux.sockaddr.in = .{ .port = 0, .addr = @bitCast([4]u8{ 127, 0, 0, 1 }) };
+ try t.expectEqual(@as(c_int, 0), c.bind(listener, @ptrCast(&address), @sizeOf(@TypeOf(address))));
+ try t.expectEqual(@as(c_int, 0), c.listen(listener, 1));
+ var length: c.socklen_t = @sizeOf(@TypeOf(address));
+ try t.expectEqual(@as(c_int, 0), c.getsockname(listener, @ptrCast(&address), &length));
+ const Fixture = struct {
+ listener: c_int,
+ bytes: [4096]u8 = undefined,
+ count: usize = 0,
+ fn run(self: *@This()) void {
+ ready(self.listener, c.POLLIN, -1, nowMs() + 3000) catch return;
+ const fd = c.accept(self.listener, null, null);
+ if (fd < 0) return;
+ defer _ = c.close(fd);
+ while (self.count < self.bytes.len) {
+ ready(fd, c.POLLIN, -1, nowMs() + 3000) catch return;
+ const n = c.recv(fd, self.bytes[self.count..].ptr, self.bytes.len - self.count, 0);
+ if (n <= 0) return;
+ self.count += @intCast(n);
+ if (std.mem.endsWith(u8, self.bytes[0..self.count], "test-ipp")) break;
+ }
+ const reply = "HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nContent-Length: 5\r\n\r\nreply";
+ _ = c.send(fd, reply, reply.len, c.MSG_NOSIGNAL);
+ }
+ };
+ var fixture: Fixture = .{ .listener = listener };
+ const thread = try std.Thread.spawn(.{}, Fixture.run, .{&fixture});
+ var joined = false;
+ defer if (!joined) thread.join();
+ var host: [128]u8 = undefined;
+ const server = try std.fmt.bufPrint(&host, "localhost:{d}", .{std.mem.bigToNative(u16, address.port)});
+ const reply = try requestIo(t.allocator, t.io, server, "/ipp/print?queue=1", "test-ipp", -1);
+ defer t.allocator.free(reply);
+ thread.join();
+ joined = true;
+ try t.expectEqualStrings("reply", reply);
+ try t.expect(std.mem.startsWith(u8, fixture.bytes[0..fixture.count], "POST /ipp/print?queue=1 HTTP/1.1\r\nHost: localhost:"));
+}
+
+test "DNS cancellation joins the resolver without waiting for its timeout" {
+ const t = std.testing;
+ const Slow = struct {
+ var started: c_int = -1;
+ fn lookup(userdata: ?*anyopaque, _: std.Io.net.HostName, queue: *std.Io.Queue(std.Io.net.HostName.LookupResult), _: std.Io.net.HostName.LookupOptions) std.Io.net.HostName.LookupError!void {
+ const threaded: *std.Io.Threaded = @ptrCast(@alignCast(userdata));
+ const io = threaded.io();
+ defer queue.close(io);
+ var one: u64 = 1;
+ _ = c.write(started, &one, @sizeOf(u64));
+ try std.Io.sleep(io, .fromSeconds(60), .awake);
+ }
+ fn cancelWhenStarted(started_fd: c_int, cancel: c_int) void {
+ ready(started_fd, c.POLLIN, -1, nowMs() + 1000) catch return;
+ var one: u64 = 1;
+ _ = c.write(cancel, &one, @sizeOf(u64));
+ }
+ };
+ var vtable = t.io.vtable.*;
+ vtable.netLookup = Slow.lookup;
+ var io = t.io;
+ io.vtable = &vtable;
+ const cancel = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK);
+ try t.expect(cancel >= 0);
+ defer _ = c.close(cancel);
+ const started = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK);
+ try t.expect(started >= 0);
+ defer _ = c.close(started);
+ Slow.started = started;
+ defer Slow.started = -1;
+ const canceller = try std.Thread.spawn(.{}, Slow.cancelWhenStarted, .{ started, cancel });
+ defer canceller.join();
+ const start = nowMs();
+ try t.expectError(error.Cancelled, requestIo(t.allocator, io, "slow.invalid:631", "/", "test", cancel));
+ try t.expect(nowMs() - start < 1000);
+}
+
+test {
+ _ = endpoint;
+}
diff --git a/src/printing/ipp.zig b/src/printing/ipp.zig
new file mode 100644
index 0000000..7e70303
--- /dev/null
+++ b/src/printing/ipp.zig
@@ -0,0 +1,393 @@
+//! Bounded IPP binary codec (RFC 8010). Decoded slices borrow the input;
+//! callers still sanitize display strings and validate URIs for their use.
+const std = @import("std");
+
+pub const Tag = enum(u8) {
+ operation = 0x01,
+ job = 0x02,
+ end = 0x03,
+ printer = 0x04,
+ unsupported = 0x05,
+ subscription = 0x06,
+ event_notification = 0x07,
+ resource = 0x08,
+ document = 0x09,
+ system = 0x0a,
+ unsupported_value = 0x10,
+ default_value = 0x11,
+ unknown = 0x12,
+ no_value = 0x13,
+ not_settable = 0x15,
+ delete_attribute = 0x16,
+ admin_defined = 0x17,
+ integer = 0x21,
+ boolean = 0x22,
+ enum_value = 0x23,
+ octet_string = 0x30,
+ date_time = 0x31,
+ resolution = 0x32,
+ range = 0x33,
+ begin_collection = 0x34,
+ text_with_language = 0x35,
+ name_with_language = 0x36,
+ end_collection = 0x37,
+ text = 0x41,
+ name = 0x42,
+ keyword = 0x44,
+ uri = 0x45,
+ uri_scheme = 0x46,
+ charset = 0x47,
+ natural_language = 0x48,
+ mime_type = 0x49,
+ member_name = 0x4a,
+ extension = 0x7f,
+ _,
+};
+
+pub const Error = error{ Truncated, InvalidMessage, UnsupportedVersion, TooLarge };
+pub const Limits = struct {
+ max_bytes: usize = 4 * 1024 * 1024,
+ // Includes collection members and additional values, not only names.
+ max_attributes: usize = 16384,
+ max_groups: usize = 1024,
+ max_name: usize = 255,
+ max_value: usize = 32767,
+ max_collection_depth: usize = 8,
+ /// Compatibility for CUPS replies that repeat defaults with different
+ /// value tags. Preserve every record; callers must reject ambiguous
+ /// identity attributes. Collection member names remain strict.
+ allow_duplicate_names: bool = false,
+};
+
+pub const Resolution = struct {
+ x: i32,
+ y: i32,
+ units: enum(u8) { dpi = 3, dpcm = 4 },
+};
+pub const Range = struct { lower: i32, upper: i32 };
+
+pub const Attribute = struct {
+ group: Tag,
+ // Every group delimiter advances this, including consecutive same-tag groups.
+ group_index: usize,
+ name: []const u8,
+ tag: Tag,
+ // Collections contain the encoded members, including their end marker.
+ value: []const u8,
+
+ pub fn integer(self: Attribute) ?i32 {
+ if (self.tag != .integer and self.tag != .enum_value) return null;
+ if (self.value.len != 4) return null;
+ return std.mem.readInt(i32, self.value[0..4], .big);
+ }
+ pub fn boolean(self: Attribute) ?bool {
+ if (self.tag != .boolean or self.value.len != 1 or self.value[0] > 1) return null;
+ return self.value[0] == 1;
+ }
+ pub fn text(self: Attribute) ?[]const u8 {
+ return switch (self.tag) {
+ .text, .name, .keyword, .uri, .uri_scheme, .charset, .natural_language, .mime_type => self.value,
+ .text_with_language, .name_with_language => languageText(self.value) catch null,
+ else => null,
+ };
+ }
+ pub fn resolution(self: Attribute) ?Resolution {
+ if (self.tag != .resolution or self.value.len != 9) return null;
+ if (self.value[8] != 3 and self.value[8] != 4) return null;
+ return .{
+ .x = std.mem.readInt(i32, self.value[0..4], .big),
+ .y = std.mem.readInt(i32, self.value[4..8], .big),
+ .units = @enumFromInt(self.value[8]),
+ };
+ }
+ pub fn range(self: Attribute) ?Range {
+ if (self.tag != .range or self.value.len != 8) return null;
+ return .{
+ .lower = std.mem.readInt(i32, self.value[0..4], .big),
+ .upper = std.mem.readInt(i32, self.value[4..8], .big),
+ };
+ }
+};
+
+pub const Message = struct {
+ version: [2]u8,
+ code: u16,
+ request_id: i32,
+ attributes: []Attribute,
+ group_count: usize,
+ data: []const u8,
+
+ pub fn deinit(self: *Message, allocator: std.mem.Allocator) void {
+ allocator.free(self.attributes);
+ self.* = undefined;
+ }
+};
+
+pub fn decode(allocator: std.mem.Allocator, bytes: []const u8, limits: Limits) !Message {
+ if (bytes.len > limits.max_bytes) return error.TooLarge;
+ var reader: Reader = .{ .bytes = bytes, .limits = limits };
+ const header = try reader.take(8);
+ try checkVersion(header[0..2].*);
+ const request_id = std.mem.readInt(i32, header[4..8], .big);
+ if (request_id <= 0) return error.InvalidMessage;
+ var attributes: std.ArrayList(Attribute) = .empty;
+ errdefer attributes.deinit(allocator);
+ var names = std.StringHashMap(void).init(allocator);
+ defer names.deinit();
+ var group: ?Tag = null;
+ var groups: usize = 0;
+ var previous_name: []const u8 = "";
+ while (true) {
+ const tag: Tag = @enumFromInt(try reader.byte());
+ if (tag == .end) {
+ if (group == null) return error.InvalidMessage;
+ return .{
+ .version = header[0..2].*,
+ .code = std.mem.readInt(u16, header[2..4], .big),
+ .request_id = request_id,
+ .attributes = try attributes.toOwnedSlice(allocator),
+ .group_count = groups,
+ .data = bytes[reader.offset..],
+ };
+ }
+ if (@intFromEnum(tag) < 0x10) {
+ if (!isGroup(tag) or (groups == 0 and tag != .operation) or
+ (groups != 0 and tag == .operation)) return error.InvalidMessage;
+ if (groups >= limits.max_groups) return error.TooLarge;
+ groups += 1;
+ group = tag;
+ previous_name = "";
+ names.clearRetainingCapacity();
+ continue;
+ }
+ if (group == null or tag == .member_name or tag == .end_collection) return error.InvalidMessage;
+ const record = try reader.record(tag);
+ var name = record.name;
+ if (name.len == 0) {
+ if (previous_name.len == 0) return error.InvalidMessage;
+ name = previous_name;
+ } else {
+ if (!validName(name)) return error.InvalidMessage;
+ const result = try names.getOrPut(name);
+ if (result.found_existing and !limits.allow_duplicate_names) return error.InvalidMessage;
+ previous_name = name;
+ }
+ try validateValue(tag, record.value);
+ var value = record.value;
+ if (tag == .begin_collection) {
+ const start = reader.offset;
+ try reader.collection(allocator, 1);
+ value = bytes[start..reader.offset];
+ }
+ try attributes.append(allocator, .{
+ .group = group.?,
+ .group_index = groups - 1,
+ .name = name,
+ .tag = tag,
+ .value = value,
+ });
+ }
+}
+
+const Reader = struct {
+ bytes: []const u8,
+ limits: Limits,
+ offset: usize = 0,
+ records: usize = 0,
+
+ fn take(self: *Reader, count: usize) Error![]const u8 {
+ if (count > self.bytes.len - self.offset) return error.Truncated;
+ defer self.offset += count;
+ return self.bytes[self.offset..][0..count];
+ }
+ fn byte(self: *Reader) Error!u8 {
+ return (try self.take(1))[0];
+ }
+ fn field(self: *Reader, limit: usize) Error![]const u8 {
+ const length = std.mem.readInt(u16, (try self.take(2))[0..2], .big);
+ if (length > 32767 or length > limit) return error.TooLarge;
+ return self.take(length);
+ }
+ const Record = struct { name: []const u8, value: []const u8 };
+ fn record(self: *Reader, tag: Tag) Error!Record {
+ if (@intFromEnum(tag) < 0x10) return error.InvalidMessage;
+ if (self.records >= self.limits.max_attributes) return error.TooLarge;
+ self.records += 1;
+ return .{
+ .name = try self.field(@min(255, self.limits.max_name)),
+ .value = try self.field(self.limits.max_value),
+ };
+ }
+ fn collection(self: *Reader, allocator: std.mem.Allocator, depth: usize) (Error || std.mem.Allocator.Error)!void {
+ // Keep a hard stack bound even if a caller accidentally raises its limit.
+ if (depth > @min(16, self.limits.max_collection_depth)) return error.TooLarge;
+ var names = std.StringHashMap(void).init(allocator);
+ defer names.deinit();
+ var member_started = false;
+ var member_has_value = false;
+ while (true) {
+ const tag: Tag = @enumFromInt(try self.byte());
+ const record_value = try self.record(tag);
+ if (record_value.name.len != 0) return error.InvalidMessage;
+ if (tag == .end_collection) {
+ if (record_value.value.len != 0 or (member_started and !member_has_value)) return error.InvalidMessage;
+ return;
+ }
+ if (tag == .member_name) {
+ if (record_value.value.len > self.limits.max_name or record_value.value.len > 255) return error.TooLarge;
+ if (!validName(record_value.value) or (member_started and !member_has_value)) return error.InvalidMessage;
+ const result = try names.getOrPut(record_value.value);
+ if (result.found_existing) return error.InvalidMessage;
+ member_started = true;
+ member_has_value = false;
+ continue;
+ }
+ if (!member_started) return error.InvalidMessage;
+ try validateValue(tag, record_value.value);
+ if (tag == .begin_collection) try self.collection(allocator, depth + 1);
+ member_has_value = true;
+ }
+ }
+};
+
+pub const Encoder = struct {
+ allocator: std.mem.Allocator,
+ bytes: std.ArrayList(u8) = .empty,
+ groups: usize = 0,
+ attributes: usize = 0,
+ has_name: bool = false,
+ finished: bool = false,
+
+ pub fn init(allocator: std.mem.Allocator, operation: u16, request_id: i32) !Encoder {
+ return initVersion(allocator, .{ 1, 1 }, operation, request_id);
+ }
+ pub fn initVersion(allocator: std.mem.Allocator, version: [2]u8, operation: u16, request_id: i32) !Encoder {
+ try checkVersion(version);
+ if (request_id <= 0) return error.InvalidMessage;
+ var self: Encoder = .{ .allocator = allocator };
+ errdefer self.deinit();
+ var header: [8]u8 = undefined;
+ header[0..2].* = version;
+ std.mem.writeInt(u16, header[2..4], operation, .big);
+ std.mem.writeInt(i32, header[4..8], request_id, .big);
+ try self.bytes.appendSlice(allocator, &header);
+ return self;
+ }
+ pub fn deinit(self: *Encoder) void {
+ self.bytes.deinit(self.allocator);
+ self.* = undefined;
+ }
+ pub fn group(self: *Encoder, tag: Tag) !void {
+ if (self.finished or !isGroup(tag) or (self.groups == 0 and tag != .operation) or
+ (self.groups != 0 and tag == .operation)) return error.InvalidMessage;
+ if (self.groups >= (Limits{}).max_groups) return error.TooLarge;
+ try self.append(&.{@intFromEnum(tag)});
+ self.groups += 1;
+ self.has_name = false;
+ }
+ pub fn string(self: *Encoder, tag: Tag, name: []const u8, data: []const u8) !void {
+ switch (tag) {
+ .text, .name, .keyword, .uri, .uri_scheme, .charset, .natural_language, .mime_type, .octet_string => {},
+ else => return error.InvalidMessage,
+ }
+ try self.value(tag, name, data);
+ }
+ pub fn integer(self: *Encoder, tag: Tag, name: []const u8, number: i32) !void {
+ if (tag != .integer and tag != .enum_value) return error.InvalidMessage;
+ var bytes: [4]u8 = undefined;
+ std.mem.writeInt(i32, &bytes, number, .big);
+ try self.value(tag, name, &bytes);
+ }
+ pub fn boolean(self: *Encoder, name: []const u8, enabled: bool) !void {
+ try self.value(.boolean, name, &.{@intFromBool(enabled)});
+ }
+ /// One non-collection value. An empty name adds a value to the prior name.
+ pub fn value(self: *Encoder, tag: Tag, name: []const u8, data: []const u8) !void {
+ if (self.finished or self.groups == 0 or tag == .begin_collection or
+ tag == .end_collection or tag == .member_name or @intFromEnum(tag) < 0x10) return error.InvalidMessage;
+ if (name.len > 255 or data.len > 32767 or self.attributes >= (Limits{}).max_attributes) return error.TooLarge;
+ if ((name.len == 0 and !self.has_name) or (name.len != 0 and !validName(name))) return error.InvalidMessage;
+ try validateValue(tag, data);
+ const size = 5 + name.len + data.len;
+ if (size > (Limits{}).max_bytes - self.bytes.items.len) return error.TooLarge;
+ try self.bytes.ensureUnusedCapacity(self.allocator, size);
+ self.bytes.appendAssumeCapacity(@intFromEnum(tag));
+ var length: [2]u8 = undefined;
+ std.mem.writeInt(u16, &length, @intCast(name.len), .big);
+ self.bytes.appendSliceAssumeCapacity(&length);
+ self.bytes.appendSliceAssumeCapacity(name);
+ std.mem.writeInt(u16, &length, @intCast(data.len), .big);
+ self.bytes.appendSliceAssumeCapacity(&length);
+ self.bytes.appendSliceAssumeCapacity(data);
+ self.has_name = true;
+ self.attributes += 1;
+ }
+ /// The result remains owned by this encoder until deinit.
+ pub fn finish(self: *Encoder) ![]const u8 {
+ if (self.groups == 0) return error.InvalidMessage;
+ if (!self.finished) {
+ try self.append(&.{@intFromEnum(Tag.end)});
+ self.finished = true;
+ }
+ return self.bytes.items;
+ }
+ fn append(self: *Encoder, bytes: []const u8) !void {
+ if (bytes.len > (Limits{}).max_bytes - self.bytes.items.len) return error.TooLarge;
+ try self.bytes.appendSlice(self.allocator, bytes);
+ }
+};
+
+fn isGroup(tag: Tag) bool {
+ return @intFromEnum(tag) >= 1 and @intFromEnum(tag) < 0x10 and tag != .end;
+}
+fn checkVersion(version: [2]u8) Error!void {
+ if ((version[0] == 1 and version[1] <= 1) or (version[0] == 2 and version[1] <= 2)) return;
+ return error.UnsupportedVersion;
+}
+fn validName(name: []const u8) bool {
+ if (name.len == 0 or name[0] < 'a' or name[0] > 'z') return false;
+ for (name[1..]) |ch| {
+ if (!(ch >= 'a' and ch <= 'z') and !std.ascii.isDigit(ch) and ch != '-' and ch != '_' and ch != '.') return false;
+ }
+ return true;
+}
+fn validText(value: []const u8) bool {
+ return std.unicode.utf8ValidateSlice(value) and std.mem.indexOfScalar(u8, value, 0) == null;
+}
+fn languageText(value: []const u8) Error![]const u8 {
+ if (value.len < 4) return error.InvalidMessage;
+ const language_len = std.mem.readInt(u16, value[0..2], .big);
+ if (language_len == 0 or language_len > 63 or language_len > value.len - 4) return error.InvalidMessage;
+ for (value[2..][0..language_len]) |ch| if (ch <= 0x20 or ch >= 0x7f) return error.InvalidMessage;
+ const tail = value[2 + language_len ..];
+ const text_len = std.mem.readInt(u16, tail[0..2], .big);
+ if (text_len != tail.len - 2 or !validText(tail[2..])) return error.InvalidMessage;
+ return tail[2..];
+}
+fn validateValue(tag: Tag, value: []const u8) Error!void {
+ switch (tag) {
+ .integer, .enum_value => if (value.len != 4) return error.InvalidMessage,
+ .boolean => if (value.len != 1 or value[0] > 1) return error.InvalidMessage,
+ .date_time => if (value.len != 11) return error.InvalidMessage,
+ .resolution => {
+ if (value.len != 9 or (value[8] != 3 and value[8] != 4)) return error.InvalidMessage;
+ if (std.mem.readInt(i32, value[0..4], .big) <= 0 or std.mem.readInt(i32, value[4..8], .big) <= 0) return error.InvalidMessage;
+ },
+ .range => {
+ if (value.len != 8) return error.InvalidMessage;
+ if (std.mem.readInt(i32, value[0..4], .big) > std.mem.readInt(i32, value[4..8], .big)) return error.InvalidMessage;
+ },
+ .begin_collection => if (value.len != 0) return error.InvalidMessage,
+ .text, .name => if (!validText(value)) return error.InvalidMessage,
+ .text_with_language, .name_with_language => _ = try languageText(value),
+ .keyword, .uri, .uri_scheme, .charset, .natural_language, .mime_type => {
+ for (value) |ch| if (ch < 0x20 or ch >= 0x7f) return error.InvalidMessage;
+ },
+ .extension => if (value.len < 4) return error.InvalidMessage,
+ else => if (@intFromEnum(tag) >= 0x10 and @intFromEnum(tag) < 0x20 and value.len != 0) return error.InvalidMessage,
+ }
+}
+
+test {
+ _ = @import("ipp_tests.zig");
+}
diff --git a/src/printing/ipp_tests.zig b/src/printing/ipp_tests.zig
new file mode 100644
index 0000000..2d4c55d
--- /dev/null
+++ b/src/printing/ipp_tests.zig
@@ -0,0 +1,201 @@
+const std = @import("std");
+const ipp = @import("ipp.zig");
+const testing = std.testing;
+
+const header = "\x02\x00\x00\x00\x00\x00\x00\x07";
+const collection =
+ "\x34\x00\x09media-col\x00\x00" ++
+ "\x4a\x00\x00\x00\x0amedia-size" ++
+ "\x34\x00\x00\x00\x00" ++
+ "\x4a\x00\x00\x00\x0bx-dimension" ++
+ "\x21\x00\x00\x00\x04\x00\x00\x52\x08" ++
+ "\x37\x00\x00\x00\x00" ++
+ "\x37\x00\x00\x00\x00";
+
+test "IPP Get-Printers encoding matches wire bytes" {
+ var encoder = try ipp.Encoder.init(testing.allocator, 0x4002, 7);
+ defer encoder.deinit();
+ try encoder.group(.operation);
+ try encoder.string(.charset, "attributes-charset", "utf-8");
+ try encoder.string(.natural_language, "attributes-natural-language", "en");
+ try encoder.string(.keyword, "requested-attributes", "printer-name");
+ try encoder.string(.keyword, "", "printer-state");
+ const bytes = try encoder.finish();
+ try testing.expectEqualStrings(
+ "\x01\x01\x40\x02\x00\x00\x00\x07\x01" ++
+ "\x47\x00\x12attributes-charset\x00\x05utf-8" ++
+ "\x48\x00\x1battributes-natural-language\x00\x02en" ++
+ "\x44\x00\x14requested-attributes\x00\x0cprinter-name" ++
+ "\x44\x00\x00\x00\x0dprinter-state\x03",
+ bytes,
+ );
+ try testing.expectEqualSlices(u8, bytes, try encoder.finish());
+ var message = try ipp.decode(testing.allocator, bytes, .{});
+ defer message.deinit(testing.allocator);
+ try testing.expectEqual(@as(u16, 0x4002), message.code);
+ try testing.expectEqual(@as(i32, 7), message.request_id);
+ try testing.expectEqual(@as(usize, 4), message.attributes.len);
+ try testing.expectEqualStrings("requested-attributes", message.attributes[3].name);
+}
+
+test "IPP repeated printer groups and continuation values stay separate" {
+ const bytes = header ++ "\x01\x04" ++
+ "\x42\x00\x0cprinter-name\x00\x03one" ++
+ "\x23\x00\x0dprinter-state\x00\x04\x00\x00\x00\x03" ++
+ "\x44\x00\x15printer-state-reasons\x00\x04none" ++
+ "\x44\x00\x00\x00\x09toner-low" ++
+ "\x04\x42\x00\x0cprinter-name\x00\x03two\x03payload";
+ var message = try ipp.decode(testing.allocator, bytes, .{});
+ defer message.deinit(testing.allocator);
+ try testing.expectEqual(@as(usize, 3), message.group_count);
+ try testing.expectEqual(@as(usize, 5), message.attributes.len);
+ try testing.expectEqual(@as(usize, 1), message.attributes[0].group_index);
+ try testing.expectEqual(@as(usize, 2), message.attributes[4].group_index);
+ try testing.expectEqualStrings("printer-state-reasons", message.attributes[3].name);
+ try testing.expectEqual(@as(?i32, 3), message.attributes[1].integer());
+ try testing.expectEqualStrings("payload", message.data);
+}
+
+test "IPP duplicate named attributes require explicit compatibility and retain every bounded record" {
+ var encoder = try ipp.Encoder.init(testing.allocator, 0, 7);
+ defer encoder.deinit();
+ try encoder.group(.operation);
+ try encoder.group(.printer);
+ try encoder.string(.name, "printer-resolution-default", "203dpi");
+ const resolution = "\x00\x00\x01\x2c\x00\x00\x01\x2c\x03";
+ try encoder.value(.resolution, "printer-resolution-default", resolution);
+ try encoder.string(.keyword, "media-supported", "iso_a4_210x297mm");
+ try encoder.string(.keyword, "", "na_letter_8.5x11in");
+ const bytes = try encoder.finish();
+ try testing.expectError(error.InvalidMessage, ipp.decode(testing.allocator, bytes, .{}));
+ var message = try ipp.decode(testing.allocator, bytes, .{ .allow_duplicate_names = true });
+ defer message.deinit(testing.allocator);
+ try testing.expectEqual(@as(usize, 4), message.attributes.len);
+ try testing.expectEqualStrings("203dpi", message.attributes[0].text().?);
+ try testing.expectEqual(@as(i32, 300), message.attributes[1].resolution().?.x);
+ try testing.expectEqualStrings(message.attributes[0].name, message.attributes[1].name);
+ try testing.expectEqualStrings(message.attributes[2].name, message.attributes[3].name);
+ try testing.expectEqual(message.attributes[0].group_index, message.attributes[1].group_index);
+ try testing.expectError(error.TooLarge, ipp.decode(testing.allocator, bytes, .{ .allow_duplicate_names = true, .max_attributes = 3 }));
+ try testing.expectError(error.TooLarge, ipp.decode(testing.allocator, bytes, .{ .allow_duplicate_names = true, .max_groups = 1 }));
+ try testing.expectError(error.TooLarge, ipp.decode(testing.allocator, bytes, .{ .allow_duplicate_names = true, .max_value = 5 }));
+}
+
+test "IPP bounded collections preserve following scalar attributes" {
+ const bytes = header ++ "\x01\x04" ++ collection ++
+ "\x34\x00\x00\x00\x00\x37\x00\x00\x00\x00" ++
+ "\x42\x00\x0cprinter-name\x00\x03two\x03";
+ var message = try ipp.decode(testing.allocator, bytes, .{});
+ defer message.deinit(testing.allocator);
+ try testing.expectEqual(@as(usize, 3), message.attributes.len);
+ try testing.expectEqual(ipp.Tag.begin_collection, message.attributes[0].tag);
+ try testing.expectEqualStrings(collection[14..], message.attributes[0].value);
+ try testing.expectEqualStrings("media-col", message.attributes[1].name);
+ try testing.expectEqualStrings("two", message.attributes[2].text().?);
+ try testing.expectError(error.TooLarge, ipp.decode(testing.allocator, bytes, .{ .max_collection_depth = 1 }));
+ try testing.expectError(error.TooLarge, ipp.decode(testing.allocator, bytes, .{ .max_attributes = 4 }));
+}
+
+test "IPP numeric and localized text accessors" {
+ var encoder = try ipp.Encoder.initVersion(testing.allocator, .{ 2, 2 }, 0, 1);
+ defer encoder.deinit();
+ try encoder.group(.operation);
+ try encoder.group(.printer);
+ try encoder.integer(.integer, "marker-levels", -1);
+ try encoder.boolean("printer-is-accepting-jobs", true);
+ try encoder.value(.resolution, "printer-resolution-default", &.{ 0, 0, 0, 203, 0, 0, 0, 203, 3 });
+ try encoder.value(.range, "copies-supported", &.{ 0, 0, 0, 1, 0, 0, 0, 99 });
+ try encoder.value(.text_with_language, "printer-info", "\x00\x02en\x00\x05Hello");
+ var message = try ipp.decode(testing.allocator, try encoder.finish(), .{});
+ defer message.deinit(testing.allocator);
+ try testing.expectEqual(@as(?i32, -1), message.attributes[0].integer());
+ try testing.expectEqual(@as(?bool, true), message.attributes[1].boolean());
+ try testing.expectEqual(@as(i32, 203), message.attributes[2].resolution().?.x);
+ try testing.expectEqual(@as(i32, 99), message.attributes[3].range().?.upper);
+ try testing.expectEqualStrings("Hello", message.attributes[4].text().?);
+ try testing.expect(message.attributes[0].text() == null);
+ try testing.expect(message.attributes[1].integer() == null);
+}
+
+test "IPP every truncated prefix fails without leaking" {
+ const bytes = header ++ "\x01\x04" ++ collection ++ "\x03";
+ for (0..bytes.len) |length| {
+ if (ipp.decode(testing.allocator, bytes[0..length], .{})) |value| {
+ var message = value;
+ defer message.deinit(testing.allocator);
+ return error.TestUnexpectedResult;
+ } else |_| {}
+ }
+}
+
+test "IPP rejects malformed groups names values and collections" {
+ const invalid = [_][]const u8{
+ // Missing operation group, reserved delimiter, attributes outside a group.
+ "\x04\x03",
+ "\x00\x03",
+ "\x21\x00\x01a\x00\x04\x00\x00\x00\x00\x03",
+ "\x01\x04\x01\x03",
+ "\x01\x44\x00\x00\x00\x01a\x03",
+ "\x01\x44\x00\x01A\x00\x01a\x03",
+ "\x01\x44\x00\x01a\x00\x01a\x44\x00\x01a\x00\x01b\x03",
+ "\x01\x44\x00\x01a\x00\x01a\x04\x44\x00\x00\x00\x01b\x03",
+ "\x01\x21\x00\x01a\x00\x01a\x03",
+ "\x01\x22\x00\x01a\x00\x01\x02\x03",
+ "\x01\x12\x00\x01a\x00\x01a\x03",
+ "\x01\x41\x00\x01a\x00\x02\xc0\xaf\x03",
+ "\x01\x42\x00\x01a\x00\x01\x00\x03",
+ "\x01\x35\x00\x01a\x00\x07\x00\x02en\x00\x05x\x03",
+ "\x01\x7f\x00\x01a\x00\x01a\x03",
+ "\x01\x37\x00\x00\x00\x00\x03",
+ "\x01\x4a\x00\x00\x00\x01a\x03",
+ "\x01\x34\x00\x01a\x00\x00\x03",
+ "\x01\x34\x00\x01a\x00\x01a\x37\x00\x00\x00\x00\x03",
+ "\x01\x34\x00\x01a\x00\x00\x21\x00\x00\x00\x04\x00\x00\x00\x00\x37\x00\x00\x00\x00\x03",
+ "\x01\x34\x00\x01a\x00\x00\x4a\x00\x00\x00\x01a\x37\x00\x00\x00\x00\x03",
+ };
+ inline for (invalid) |suffix| try testing.expectError(error.InvalidMessage, ipp.decode(testing.allocator, header ++ suffix, .{}));
+}
+
+test "IPP enforces message field group and record bounds" {
+ const bytes = header ++ "\x01\x04\x44\x00\x01a\x00\x03one\x03";
+ try testing.expectError(error.TooLarge, ipp.decode(testing.allocator, bytes, .{ .max_bytes = bytes.len - 1 }));
+ try testing.expectError(error.TooLarge, ipp.decode(testing.allocator, bytes, .{ .max_groups = 1 }));
+ try testing.expectError(error.TooLarge, ipp.decode(testing.allocator, bytes, .{ .max_attributes = 0 }));
+ try testing.expectError(error.TooLarge, ipp.decode(testing.allocator, bytes, .{ .max_name = 0 }));
+ try testing.expectError(error.TooLarge, ipp.decode(testing.allocator, bytes, .{ .max_value = 2 }));
+ try testing.expectError(error.TooLarge, ipp.decode(testing.allocator, header ++ "\x01\x44\x80\x00", .{}));
+ try testing.expectError(error.TooLarge, ipp.decode(testing.allocator, header ++ "\x01\x44\x00\x01a\xff\xff", .{}));
+ try testing.expectError(error.InvalidMessage, ipp.decode(testing.allocator, "\x01\x01\x00\x00\x00\x00\x00\x00\x01\x03", .{}));
+ try testing.expectError(error.InvalidMessage, ipp.decode(testing.allocator, "\x01\x01\x00\x00\xff\xff\xff\xff\x01\x03", .{}));
+ try testing.expectError(error.UnsupportedVersion, ipp.decode(testing.allocator, "\x03\x00\x00\x00\x00\x00\x00\x01\x01\x03", .{}));
+}
+
+test "IPP encoder rejects invalid sequencing and typed data" {
+ try testing.expectError(error.InvalidMessage, ipp.Encoder.init(testing.allocator, 2, 0));
+ var encoder = try ipp.Encoder.init(testing.allocator, 2, 1);
+ defer encoder.deinit();
+ try testing.expectError(error.InvalidMessage, encoder.finish());
+ try testing.expectError(error.InvalidMessage, encoder.group(.printer));
+ try testing.expectError(error.InvalidMessage, encoder.string(.keyword, "name", "value"));
+ try encoder.group(.operation);
+ try testing.expectError(error.InvalidMessage, encoder.string(.keyword, "", "value"));
+ try testing.expectError(error.InvalidMessage, encoder.integer(.text, "name", 3));
+ try testing.expectError(error.InvalidMessage, encoder.value(.range, "name", &.{ 0, 0, 0, 5, 0, 0, 0, 1 }));
+ try encoder.string(.keyword, "name", "value");
+ _ = try encoder.finish();
+ try testing.expectError(error.InvalidMessage, encoder.group(.printer));
+ try testing.expectError(error.InvalidMessage, encoder.string(.keyword, "other", "value"));
+}
+
+test "IPP decoder releases partial groups and collections on allocation failure" {
+ try testing.checkAllAllocationFailures(testing.allocator, struct {
+ fn run(allocator: std.mem.Allocator) !void {
+ const bytes = header ++ "\x01\x04" ++ collection ++
+ "\x42\x00\x0cprinter-name\x00\x03one" ++
+ "\x04\x42\x00\x0cprinter-name\x00\x03two\x03";
+ var message = try ipp.decode(allocator, bytes, .{});
+ defer message.deinit(allocator);
+ try testing.expectEqual(@as(usize, 3), message.attributes.len);
+ }
+ }.run, .{});
+}
diff --git a/src/printing/known_devices.zig b/src/printing/known_devices.zig
new file mode 100644
index 0000000..e344ee5
--- /dev/null
+++ b/src/printing/known_devices.zig
@@ -0,0 +1,37 @@
+//! Hardware observations, never an automatic language or resolution choice.
+//! Shared USB IDs cover differently branded and configured hardware.
+const std = @import("std");
+const tools = @import("tools.zig");
+
+pub const Device = struct {
+ vid: u16,
+ pid: u16,
+ language_hint: tools.Language,
+ resolution_hint_dpi: u16,
+ provisional: bool,
+ note: []const u8,
+ driver_project: []const u8,
+};
+
+pub const devices = [_]Device{.{
+ .vid = 0x0416,
+ .pid = 0x5011,
+ .language_hint = .tspl,
+ .resolution_hint_dpi = 203,
+ .provisional = true,
+ .driver_project = "Third-party TSPL driver: RunTheWall/tspl-cups-driver — https://github.com/RunTheWall/tspl-cups-driver . Review model compatibility; RediWM does not install it.",
+ .note = "One field report associates this USB ID with TSPL and 4 x 6 inch labels. The unit advertised 300 dpi but reportedly sized correctly at 203 dpi. Rebranded devices may differ; confirm language and resolution on its self-test sheet. This observation has not completed hardware qualification.",
+}};
+
+pub fn lookup(vid: u16, pid: u16) ?*const Device {
+ for (&devices) |*device| if (device.vid == vid and device.pid == pid) return device;
+ return null;
+}
+
+test "a shared USB ID is explicitly provisional evidence" {
+ const hint = lookup(0x0416, 0x5011).?;
+ try std.testing.expect(hint.provisional);
+ try std.testing.expect(std.mem.indexOf(u8, hint.note, "203") != null);
+ try std.testing.expect(std.mem.indexOf(u8, hint.note, "300") != null);
+ try std.testing.expect(lookup(0x0416, 0x5012) == null);
+}
diff --git a/src/printing/ladder.zig b/src/printing/ladder.zig
new file mode 100644
index 0000000..c16d240
--- /dev/null
+++ b/src/printing/ladder.zig
@@ -0,0 +1,391 @@
+//! Evidence-based diagnostics, independent of transport and UI types.
+//! A successful CUPS job is evidence of processing, never proof of a printed page.
+const std = @import("std");
+const usb_sysfs = @import("usb_sysfs.zig");
+
+pub const Verdict = enum { pass, fail, unknown };
+pub const Layer = enum { connection, device_node, cups, queue, backend, settings, last_job };
+pub const Row = struct {
+ layer: Layer,
+ verdict: Verdict,
+ message: []const u8,
+ fix: []const u8 = "",
+};
+pub const Connection = enum { usb, network, other };
+pub const UsbBackend = enum { unknown, libusb, device_node };
+pub const QueueState = enum { unknown, idle, processing, stopped };
+pub const JobState = enum { unknown, pending, held, processing, stopped, canceled, aborted, completed };
+pub const Resolution = struct { x_dpi: u32, y_dpi: u32 };
+pub const Queue = struct {
+ state: QueueState = .unknown,
+ accepting: ?bool = null,
+ reasons: []const []const u8 = &.{},
+ uri: []const u8 = "",
+ default_media: []const u8 = "",
+ resolution: ?Resolution = null,
+};
+pub const Job = struct {
+ state: JobState = .unknown,
+ sheets_completed: ?u32 = null,
+ reasons: []const []const u8 = &.{},
+ /// Used only to classify known failures; never copied into the report.
+ message: []const u8 = "",
+};
+pub const Input = struct {
+ connection: Connection = .other,
+ cups_reachable: ?bool = null,
+ queue: ?Queue = null,
+ last_job: ?Job = null,
+ /// The caller must establish this identity, e.g. using a USB serial.
+ /// An arbitrary printer of the same model is not a match.
+ usb: ?*const usb_sysfs.Device = null,
+ usb_scan_complete: bool = false,
+ usb_backend: UsbBackend = .unknown,
+ /// Direct stat evidence for the exact path used by a node-based queue.
+ /// This does not establish the identity or presence of a USB device.
+ node_kind: ?usb_sysfs.NodeKind = null,
+ settings_consistent: ?bool = null,
+ network_reachable: ?bool = null,
+ backend_match: ?bool = null,
+ expected_media: ?[]const u8 = null,
+ expected_resolution: ?Resolution = null,
+ distribution: []const u8 = "",
+ cups_version: []const u8 = "",
+};
+
+pub const Result = struct {
+ rows: [7]Row,
+
+ pub fn firstFailure(self: Result) ?usize {
+ for (self.rows, 0..) |row, i| if (row.verdict == .fail) return i;
+ return null;
+ }
+};
+
+pub fn evaluate(input: Input) Result {
+ return .{ .rows = .{
+ connectionRow(input),
+ nodeRow(input),
+ cupsRow(input),
+ queueRow(input),
+ backendRow(input),
+ settingsRow(input),
+ jobRow(input.last_job),
+ } };
+}
+
+fn connectionRow(input: Input) Row {
+ switch (input.connection) {
+ .usb => {
+ if (input.usb) |device| return if (device.printer_class)
+ .{ .layer = .connection, .verdict = .pass, .message = "A matching USB printer interface is attached." }
+ else
+ .{ .layer = .connection, .verdict = .fail, .message = "The matching USB device has no printer-class interface.", .fix = "Check the device's USB mode and its self-test instructions." };
+ return if (input.usb_scan_complete)
+ .{ .layer = .connection, .verdict = .fail, .message = "The matching USB printer was not found.", .fix = "Check power, the USB cable, and which printer this queue uses." }
+ else
+ .{ .layer = .connection, .verdict = .unknown, .message = "USB presence or queue-to-device identity could not be established." };
+ },
+ .network => return if (input.network_reachable) |reachable|
+ if (reachable)
+ .{ .layer = .connection, .verdict = .pass, .message = "The printer answered an IPP request." }
+ else
+ .{ .layer = .connection, .verdict = .fail, .message = "The network printer did not answer.", .fix = "Check printer power, the address, and access through the network or VPN." }
+ else
+ .{ .layer = .connection, .verdict = .unknown, .message = "Network reachability has not been checked." },
+ .other => return .{ .layer = .connection, .verdict = .unknown, .message = "This connection has no direct presence check." },
+ }
+}
+
+fn backendKind(input: Input) UsbBackend {
+ if (input.usb_backend != .unknown) return input.usb_backend;
+ if (input.queue) |queue| if (std.mem.startsWith(u8, queue.uri, "usb://")) return .libusb;
+ return .unknown;
+}
+fn nodeRow(input: Input) Row {
+ const layer = Layer.device_node;
+ if (input.connection != .usb) return .{ .layer = layer, .verdict = .unknown, .message = "A USB character device is not applicable to this connection." };
+ if (backendKind(input) == .libusb) return .{ .layer = layer, .verdict = .unknown, .message = "The CUPS USB backend uses libusb; a usblp node is not required." };
+ if (backendKind(input) == .device_node) if (input.node_kind) |kind| return switch (kind) {
+ .regular, .other => .{ .layer = layer, .verdict = .fail, .message = "The queue's device-node path is a regular file or another wrong file type.", .fix = "Have an administrator inspect the node; never write print data to a regular file." },
+ .missing => .{ .layer = layer, .verdict = .fail, .message = "The character-device path used by this queue is missing.", .fix = "Check the usblp driver and the queue's device path; node names can change after reconnection." },
+ .character => .{ .layer = layer, .verdict = .pass, .message = "The queue's character device exists; backend access has not been tested." },
+ .unavailable => .{ .layer = layer, .verdict = .unknown, .message = "The file type of the queue's device-node path could not be read." },
+ };
+ const device = input.usb orelse return .{ .layer = layer, .verdict = .unknown, .message = "No matching USB device is available to identify its node." };
+ var character = false;
+ var regular = false;
+ var inaccessible = false;
+ for (device.nodes) |node| switch (node.kind) {
+ .character => character = true,
+ .regular, .other => regular = true,
+ .unavailable => inaccessible = true,
+ .missing => {},
+ };
+ if (backendKind(input) == .unknown) return .{ .layer = layer, .verdict = .unknown, .message = if (regular)
+ "A matched node path is not a character device; this backend's need for it is unknown."
+ else
+ "This backend's need for a usblp node has not been established." };
+ if (regular) return .{ .layer = layer, .verdict = .fail, .message = "A matched device-node path is a regular file or another wrong file type.", .fix = "Have an administrator inspect the node; never write print data to a regular file." };
+ if (character) return .{ .layer = layer, .verdict = .pass, .message = "A matching character device exists; backend access has not been tested." };
+ if (inaccessible) return .{ .layer = layer, .verdict = .unknown, .message = "The matching device-node file type could not be read." };
+ return .{ .layer = layer, .verdict = .fail, .message = "This backend needs a character device, but no matching node was found.", .fix = "Check the usblp driver and the queue's device path; node names can change after reconnection." };
+}
+fn cupsRow(input: Input) Row {
+ if (input.cups_reachable) |reachable| return if (reachable)
+ .{ .layer = .cups, .verdict = .pass, .message = "CUPS answered an IPP request." }
+ else
+ .{ .layer = .cups, .verdict = .fail, .message = "CUPS did not answer an IPP request.", .fix = "Check the configured CUPS server and whether the print service is installed and available." };
+ return .{ .layer = .cups, .verdict = .unknown, .message = "CUPS availability has not been checked." };
+}
+fn queueRow(input: Input) Row {
+ const queue = input.queue orelse return if (input.cups_reachable == true)
+ .{ .layer = .queue, .verdict = .fail, .message = "The selected queue was not found.", .fix = "Select an existing queue or add the printer again." }
+ else
+ .{ .layer = .queue, .verdict = .unknown, .message = "The queue could not be checked without a CUPS response." };
+ if (queue.state == .stopped) return .{ .layer = .queue, .verdict = .fail, .message = "The printer queue is stopped.", .fix = "Resolve the reported printer problem before resuming the queue." };
+ if (queue.accepting == false) return .{ .layer = .queue, .verdict = .fail, .message = "The printer queue is not accepting new jobs.", .fix = "Enable acceptance of jobs when the printer is ready." };
+ if (queue.accepting == null or queue.state == .unknown) return .{ .layer = .queue, .verdict = .unknown, .message = "The queue exists, but its state or acceptance of jobs is unknown." };
+ return .{ .layer = .queue, .verdict = .pass, .message = "The queue exists, is enabled, and accepts jobs." };
+}
+fn backendRow(input: Input) Row {
+ if (input.backend_match == false) return .{ .layer = .backend, .verdict = .fail, .message = "The queue's device address does not match the selected printer.", .fix = "Check the queue address and USB serial; reconnecting can change a device-node path." };
+ if (input.last_job) |job| {
+ if (hasReason(job.reasons, "printer-unreachable") or ((job.state == .aborted or job.state == .stopped) and hasReason(job.reasons, "connecting-to-device")) or containsAsciiIgnoreCase(job.message, "USB transaction timeout")) return .{
+ .layer = .backend,
+ .verdict = .fail,
+ .message = "The last job reports a backend connection problem.",
+ .fix = "Check the connection and backend address. A timeout alone does not prove that a USB quirk is needed.",
+ };
+ }
+ return .{ .layer = .backend, .verdict = .unknown, .message = if (input.backend_match == true)
+ "The device address matches; successful communication has not been confirmed."
+ else
+ "Backend communication and device identity have not been confirmed." };
+}
+fn settingsRow(input: Input) Row {
+ const queue = input.queue orelse return .{ .layer = .settings, .verdict = .unknown, .message = "Queue media and resolution could not be read." };
+ if (input.settings_consistent == false) return .{ .layer = .settings, .verdict = .fail, .message = "CUPS reports conflicting queue and driver defaults.", .fix = "Reapply the intended paper, resolution or driver option, then refresh to verify the result." };
+ if (input.expected_media) |expected| {
+ if (queue.default_media.len > 0 and !std.mem.eql(u8, expected, queue.default_media)) return .{ .layer = .settings, .verdict = .fail, .message = "The queue's default media differs from the expected media.", .fix = "Choose the paper or label size actually loaded in the printer." };
+ }
+ if (input.expected_resolution) |expected| {
+ if (queue.resolution) |actual| if (expected.x_dpi != actual.x_dpi or expected.y_dpi != actual.y_dpi) return .{ .layer = .settings, .verdict = .fail, .message = "The queue resolution differs from the expected resolution.", .fix = "Confirm resolution using the printer's self-test or a measured ruler test." };
+ }
+ if ((input.expected_media != null and queue.default_media.len == 0) or (input.expected_resolution != null and queue.resolution == null) or (input.expected_media == null and input.expected_resolution == null)) return .{ .layer = .settings, .verdict = .unknown, .message = "Media and resolution need confirmation against what is loaded in the printer." };
+ return .{ .layer = .settings, .verdict = .pass, .message = "The available queue settings match the supplied media or resolution expectations." };
+}
+fn jobRow(job_value: ?Job) Row {
+ const job = job_value orelse return .{ .layer = .last_job, .verdict = .unknown, .message = "No recent job information is available." };
+ if (containsAsciiIgnoreCase(job.message, "No pages were found") or hasReason(job.reasons, "document-format-error") or hasReason(job.reasons, "document-unprintable-error") or hasReason(job.reasons, "cups-filter-error")) return .{ .layer = .last_job, .verdict = .fail, .message = "The last job reports a document or filter failure.", .fix = "Check the document, driver, media size, and resolution. Compare with a test that skips the filters." };
+ if (job.state == .completed and job.sheets_completed == 0) return .{ .layer = .last_job, .verdict = .unknown, .message = "CUPS completed the job with zero sheets reported; physical output is not confirmed.", .fix = "Check the physical output and any document or filter failure; sheet counters can be incomplete." };
+ if (job.state == .aborted or job.state == .stopped) return .{ .layer = .last_job, .verdict = .fail, .message = "The last job was aborted or stopped.", .fix = "Check the job's reported reason before retrying." };
+ if (job.state == .completed) return .{ .layer = .last_job, .verdict = .unknown, .message = "CUPS reports the job completed; physical printed output is not confirmed." };
+ if (job.state == .canceled) return .{ .layer = .last_job, .verdict = .unknown, .message = "The last job was canceled." };
+ return .{ .layer = .last_job, .verdict = .unknown, .message = "The last job has not completed." };
+}
+
+fn containsAsciiIgnoreCase(haystack: []const u8, needle: []const u8) bool {
+ if (needle.len > haystack.len) return false;
+ const bounded = haystack[0..@min(haystack.len, 4096)];
+ if (needle.len > bounded.len) return false;
+ for (0..bounded.len - needle.len + 1) |i| if (std.ascii.eqlIgnoreCase(bounded[i .. i + needle.len], needle)) return true;
+ return false;
+}
+fn hasReason(reasons: []const []const u8, expected: []const u8) bool {
+ for (reasons[0..@min(reasons.len, 64)]) |reason| if (std.mem.eql(u8, reason, expected)) return true;
+ return false;
+}
+
+/// Human-readable status for recognized IPP printer-state-reasons.
+/// Unknown strings are deliberately not echoed into reports or UI labels.
+pub fn reasonText(reason: []const u8) ?[]const u8 {
+ var base = reason;
+ for ([_][]const u8{ "-error", "-warning", "-report" }) |suffix| if (std.mem.endsWith(u8, base, suffix)) {
+ base = base[0 .. base.len - suffix.len];
+ break;
+ };
+ const known = .{
+ .{ "none", "No reported problem" },
+ .{ "media-empty", "Out of paper" },
+ .{ "media-needed", "Paper is needed" },
+ .{ "media-jam", "Paper jam" },
+ .{ "media-low", "Paper is low" },
+ .{ "toner-empty", "Toner is empty" },
+ .{ "toner-low", "Toner is low" },
+ .{ "marker-supply-empty", "Ink or toner is empty" },
+ .{ "marker-supply-low", "Ink or toner is low" },
+ .{ "cover-open", "Cover open" },
+ .{ "door-open", "Door open" },
+ .{ "paused", "Queue paused" },
+ .{ "connecting-to-device", "Connecting to the printer" },
+ .{ "printer-unreachable", "Printer unreachable" },
+ .{ "offline", "Printer offline" },
+ .{ "cups-missing-filter", "A required print filter is missing" },
+ .{ "cups-insecure-filter", "A print filter has unsafe permissions" },
+ .{ "cups-filter-error", "Print filter failed" },
+ .{ "document-format-error", "Document format error" },
+ .{ "document-unprintable-error", "Document could not be printed" },
+ .{ "job-completed-successfully", "Job completed in CUPS" },
+ .{ "job-canceled-by-user", "Job canceled" },
+ .{ "job-canceled-at-device", "Job canceled at the printer" },
+ .{ "job-hold-until-specified", "Job held" },
+ };
+ inline for (known) |entry| if (std.mem.eql(u8, reason, entry[0]) or std.mem.eql(u8, base, entry[0])) return entry[1];
+ return null;
+}
+
+/// Privacy by construction: names, document titles, arbitrary status messages,
+/// URI userinfo/hosts/paths/queries, and USB serial strings are never included.
+/// Known failure classifications preserve useful evidence without copying logs.
+pub fn report(a: std.mem.Allocator, input: Input) ![]u8 {
+ var out: std.Io.Writer.Allocating = .init(a);
+ errdefer out.deinit();
+ try out.writer.writeAll("RediWM printer diagnostics\n");
+ try out.writer.print("Connection: {s}\n", .{@tagName(input.connection)});
+ const distro = distributionName(input.distribution);
+ try out.writer.print("Distribution: {s}\nCUPS version: {s}\n", .{ distro, safeVersion(input.cups_version) });
+ if (input.usb) |device| {
+ try out.writer.print("USB: {x:0>4}:{x:0>4}; printer class: {s}\n", .{ device.vid, device.pid, if (device.printer_class) "07" else "no" });
+ try out.writer.print("Matched device nodes: {d}\n", .{device.nodes.len});
+ for (device.nodes[0..@min(device.nodes.len, 32)]) |node| try out.writer.print(" Node type: {s}\n", .{@tagName(node.kind)});
+ }
+ if (input.node_kind) |kind| try out.writer.print("Queue device-node type: {s}\n", .{@tagName(kind)});
+ if (input.queue) |queue| {
+ try out.writer.print("Queue state: {s}; accepting: {s}\n", .{ @tagName(queue.state), if (queue.accepting) |value| if (value) "yes" else "no" else "unknown" });
+ try out.writer.print("Device URI: {s}\nDefault media: {s}\n", .{ redactedUri(queue.uri), safeMedia(queue.default_media) });
+ if (queue.resolution) |resolution| try out.writer.print("Resolution: {d} x {d} dpi\n", .{ resolution.x_dpi, resolution.y_dpi });
+ try reportReasons(&out.writer, "Printer reason", queue.reasons);
+ }
+ if (input.last_job) |job| {
+ try out.writer.print("Last job state: {s}\n", .{@tagName(job.state)});
+ if (job.sheets_completed) |sheets| try out.writer.print("Completed sheets reported by CUPS: {d}\n", .{sheets});
+ try reportReasons(&out.writer, "Job reason", job.reasons);
+ if (job.message.len > 0) try out.writer.writeAll("Job message: omitted for privacy; recognized failures appear below\n");
+ }
+ for (evaluate(input).rows) |row| try out.writer.print("{s}: {s} - {s}\n", .{ @tagName(row.layer), @tagName(row.verdict), row.message });
+ try out.writer.writeAll("CUPS completion does not confirm physical output. No test prints were started by this report.\n");
+ return out.toOwnedSlice();
+}
+
+fn reportReasons(writer: *std.Io.Writer, label: []const u8, reasons: []const []const u8) !void {
+ var unknown: usize = 0;
+ for (reasons[0..@min(reasons.len, 64)]) |reason| {
+ if (reasonText(reason)) |text| try writer.print("{s}: {s}\n", .{ label, text }) else unknown += 1;
+ }
+ if (unknown > 0) try writer.print("{s}: {d} unrecognized values omitted\n", .{ label, unknown });
+}
+fn distributionName(raw: []const u8) []const u8 {
+ for ([_][]const u8{ "arch", "artix", "cachyos", "debian", "ubuntu", "fedora", "opensuse", "opensuse-leap", "opensuse-tumbleweed" }) |known| if (std.mem.eql(u8, raw, known)) return known;
+ return "unknown";
+}
+fn safeVersion(raw: []const u8) []const u8 {
+ if (raw.len == 0 or raw.len > 32) return "unknown";
+ for (raw) |byte| if (!std.ascii.isDigit(byte) and byte != '.' and byte != '-') return "unknown";
+ return raw;
+}
+fn safeMedia(raw: []const u8) []const u8 {
+ // Exact known keywords only: a standard-looking prefix is insufficient,
+ // since an untrusted server could put a document name or hostname after it.
+ const known_media = [_][]const u8{
+ "A3", "A4", "A5",
+ "A6", "Letter", "Legal",
+ "Executive", "4x6", "4x6.Borderless",
+ "iso_a3_297x420mm", "iso_a4_210x297mm", "iso_a5_148x210mm",
+ "iso_a6_105x148mm", "iso_b5_176x250mm", "iso_c5_162x229mm",
+ "iso_dl_110x220mm", "jis_b5_182x257mm", "na_letter_8.5x11in",
+ "na_legal_8.5x14in", "na_executive_7.25x10.5in", "na_ledger_11x17in",
+ "na_index-4x6_4x6in", "na_number-10_4.125x9.5in", "oe_photo-l_3.5x5in",
+ "oe_photo-2l_5x7in", "om_small-photo_100x150mm", "om_medium-photo_130x180mm",
+ "om_large-photo_200x300mm",
+ };
+ for (known_media) |known| if (std.mem.eql(u8, raw, known)) return known;
+ if (raw.len == 0) return "unknown";
+ return "[unrecognized value omitted]";
+}
+fn redactedUri(uri: []const u8) []const u8 {
+ for ([_][]const u8{ "usb", "ipp", "ipps", "http", "https", "socket", "lpd", "dnssd", "file", "parallel", "serial" }) |scheme| {
+ if (uri.len > scheme.len and uri[scheme.len] == ':' and std.ascii.eqlIgnoreCase(uri[0..scheme.len], scheme)) {
+ if (std.mem.eql(u8, scheme, "usb")) return "usb:[device identity omitted]";
+ if (std.mem.eql(u8, scheme, "file")) return "file:[path omitted]";
+ return "[known URI scheme; credentials, host and path omitted]";
+ }
+ }
+ return "[URI omitted]";
+}
+
+test "libusb does not require usblp; missing evidence does not become a failure" {
+ const result = evaluate(.{ .connection = .usb, .cups_reachable = true, .queue = .{ .state = .idle, .accepting = true, .uri = "usb://Printer/Model" } });
+ try std.testing.expectEqual(Verdict.unknown, result.rows[0].verdict);
+ try std.testing.expectEqual(Verdict.unknown, result.rows[1].verdict);
+ try std.testing.expectEqual(Verdict.pass, result.rows[3].verdict);
+ try std.testing.expectEqual(@as(?usize, null), result.firstFailure());
+}
+
+test "completed empty job points to filter evidence; completed sheets are not proof of output" {
+ var input: Input = .{ .last_job = .{ .state = .completed, .sheets_completed = 0, .message = "No pages were found." } };
+ try std.testing.expectEqual(Verdict.fail, evaluate(input).rows[6].verdict);
+ try std.testing.expect(std.mem.indexOf(u8, evaluate(input).rows[6].message, "filter") != null);
+ input.last_job = .{ .state = .completed, .sheets_completed = 1 };
+ try std.testing.expectEqual(Verdict.unknown, evaluate(input).rows[6].verdict);
+ input.last_job = .{ .state = .completed };
+ try std.testing.expectEqual(Verdict.unknown, evaluate(input).rows[6].verdict);
+ input.last_job = .{ .state = .completed, .sheets_completed = 0 };
+ try std.testing.expectEqual(Verdict.unknown, evaluate(input).rows[6].verdict);
+}
+
+test "stopped queue and explicit media mismatch produce the correct first failing layer" {
+ var input: Input = .{ .cups_reachable = true, .queue = .{ .state = .stopped, .accepting = true, .default_media = "A4" }, .expected_media = "4x6" };
+ try std.testing.expectEqual(@as(?usize, 3), evaluate(input).firstFailure());
+ input.queue.?.state = .idle;
+ try std.testing.expectEqual(@as(?usize, 5), evaluate(input).firstFailure());
+}
+
+test "node-based backends reject impostors while ordinary connecting jobs remain inconclusive" {
+ var nodes = [_]usb_sysfs.Node{.{ .path = "/dev/usb/lp9", .kind = .regular }};
+ var device: usb_sysfs.Device = .{ .name = "1-2", .vid = 0x0416, .pid = 0x5011, .manufacturer = "", .product = "", .serial = "", .driver = "usblp", .nodes = &nodes };
+ var input: Input = .{ .connection = .usb, .usb = &device, .usb_backend = .device_node, .last_job = .{ .state = .processing, .reasons = &.{"connecting-to-device"} } };
+ try std.testing.expectEqual(Verdict.fail, evaluate(input).rows[1].verdict);
+ try std.testing.expectEqual(Verdict.unknown, evaluate(input).rows[4].verdict);
+ nodes[0].kind = .character;
+ try std.testing.expectEqual(Verdict.pass, evaluate(input).rows[1].verdict);
+ nodes[0].kind = .missing;
+ try std.testing.expectEqual(Verdict.fail, evaluate(input).rows[1].verdict);
+ input.usb_backend = .libusb;
+ try std.testing.expectEqual(Verdict.unknown, evaluate(input).rows[1].verdict);
+ input.last_job.?.state = .aborted;
+ try std.testing.expectEqual(Verdict.fail, evaluate(input).rows[4].verdict);
+
+ // An existing file: queue identifies its exact path even when sysfs cannot
+ // establish a corresponding USB identity. Stat evidence is independent.
+ input = .{ .connection = .usb, .usb_backend = .device_node, .queue = .{ .uri = "file:/dev/usb/lp0" }, .node_kind = .regular };
+ try std.testing.expectEqual(Verdict.unknown, evaluate(input).rows[0].verdict);
+ try std.testing.expectEqual(Verdict.fail, evaluate(input).rows[1].verdict);
+ try std.testing.expectEqual(@as(?usize, 1), evaluate(input).firstFailure());
+ input.node_kind = .other;
+ try std.testing.expectEqual(Verdict.fail, evaluate(input).rows[1].verdict);
+ input.node_kind = .missing;
+ try std.testing.expectEqual(Verdict.fail, evaluate(input).rows[1].verdict);
+ input.node_kind = .character;
+ try std.testing.expectEqual(Verdict.pass, evaluate(input).rows[1].verdict);
+ try std.testing.expectEqual(Verdict.unknown, evaluate(input).rows[0].verdict);
+ input.node_kind = .unavailable;
+ try std.testing.expectEqual(Verdict.unknown, evaluate(input).rows[1].verdict);
+ input.usb_backend = .libusb;
+ input.node_kind = .regular;
+ try std.testing.expectEqual(Verdict.unknown, evaluate(input).rows[1].verdict);
+}
+
+test "diagnostic reports redact remote credentials identities messages and unknown reasons" {
+ const a = std.testing.allocator;
+ const text = try report(a, .{
+ .connection = .network,
+ .queue = .{ .uri = "ipp://secret-user:[email protected]/printers/private-queue?token=secret-token", .default_media = "iso_private-user.private-host.example_1x2mm", .reasons = &.{ "media-empty-warning", "private-user\nprivate-document" } },
+ .last_job = .{ .state = .aborted, .message = "private-user printed private-document at private-host.example" },
+ .distribution = "arch\nprivate-host.example",
+ .cups_version = "2.4.10\nsecret-token",
+ });
+ defer a.free(text);
+ for ([_][]const u8{ "secret-user", "secret-password", "private-host", "private-user", "private-document", "secret-token", "private-queue" }) |secret| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "Out of paper") != null);
+}
diff --git a/src/printing/native.zig b/src/printing/native.zig
new file mode 100644
index 0000000..1fe2a48
--- /dev/null
+++ b/src/printing/native.zig
@@ -0,0 +1,12 @@
+pub const c = @cImport({
+ @cUndef("_FORTIFY_SOURCE");
+ @cInclude("sys/socket.h");
+ @cInclude("sys/un.h");
+ @cInclude("sys/eventfd.h");
+ @cInclude("linux/netlink.h");
+ @cInclude("poll.h");
+ @cInclude("unistd.h");
+ @cInclude("pthread.h");
+ @cInclude("time.h");
+ @cInclude("pwd.h");
+});
diff --git a/src/printing/notifier.zig b/src/printing/notifier.zig
new file mode 100644
index 0000000..a547a52
--- /dev/null
+++ b/src/printing/notifier.zig
@@ -0,0 +1,232 @@
+//! Page-owned CUPS change hints on the system bus. The upstream dbus notifier
+//! uses a unique sender, without acquiring org.cups.cupsd.Notifier as a name.
+//! Authenticate that sender through the bus daemon before requesting a reload.
+//! Nothing in a notification is used as printer state or displayed to users.
+const std = @import("std");
+const dbus = @import("dbus");
+const wl = @import("wayland").server.wl;
+const wire = dbus.wire;
+const eq = std.mem.eql;
+const interface = "org.cups.cupsd.Notifier";
+const path = "/org/cups/cupsd/Notifier";
+const rule = "type='signal',interface='" ++ interface ++ "',path='" ++ path ++ "'";
+const bus = "org.freedesktop.DBus";
+const bus_path = "/org/freedesktop/DBus";
+
+pub const Listener = struct {
+ allocator: std.mem.Allocator,
+ conn: *dbus.Connection,
+ owner: *anyopaque,
+ changed: *const fn (*anyopaque) void,
+ uids: [3]u32 = .{ 0, 0, 0 },
+ sender: ?[]u8 = null,
+ pending_sender: ?[]u8 = null,
+ closing: bool = false,
+ /// True once AddMatch succeeds. IPP subscription creation and cancellation
+ /// belong to the cancellable worker, never to a D-Bus callback.
+ ready: bool = false,
+
+ pub fn create(allocator: std.mem.Allocator, io: std.Io, env: std.process.Environ, loop: *wl.EventLoop, owner: *anyopaque, changed: *const fn (*anyopaque) void) !*Listener {
+ const self = try allocator.create(Listener);
+ errdefer allocator.destroy(self);
+ const conn = try dbus.Connection.openSystem(allocator, loop, env);
+ errdefer conn.destroy();
+ self.* = .{ .allocator = allocator, .conn = conn, .owner = owner, .changed = changed };
+ // Read only the local passwd database: NSS and user names from signals
+ // must never introduce an unbounded resolver wait on the compositor.
+ const passwd = std.Io.Dir.cwd().readFileAlloc(io, "/etc/passwd", allocator, .limited(256 * 1024)) catch "";
+ defer if (passwd.len != 0) allocator.free(passwd);
+ self.uids = serviceUids(passwd, @intCast(std.os.linux.getuid()));
+ _ = try conn.hello(self, onHello);
+ return self;
+ }
+
+ pub fn destroy(self: *Listener) void {
+ self.closing = true;
+ // Destroying this private connection atomically removes its matches
+ // from the bus, including when Hello or authentication is pending.
+ self.conn.destroy();
+ if (self.sender) |sender| self.allocator.free(sender);
+ if (self.pending_sender) |sender| self.allocator.free(sender);
+ self.allocator.destroy(self);
+ }
+
+ fn onHello(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const self: *Listener = @ptrCast(@alignCast(owner orelse return));
+ if (self.closing) return;
+ const msg = result catch return;
+ if (!fromBus(msg) or msg.kind != .method_return) return;
+ conn.registerSignal(.{ .path = path, .interface = interface, .owner = self, .callback = onSignal }) catch return;
+ _ = conn.addMatch(rule, self, onMatch) catch return;
+ }
+
+ fn onMatch(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const self: *Listener = @ptrCast(@alignCast(owner orelse return));
+ if (self.closing) return;
+ const msg = result catch return;
+ self.ready = fromBus(msg) and msg.kind == .method_return;
+ // The initial inventory may have completed before AddMatch. Wake the
+ // owner once so it can enable its worker's IPP subscription now.
+ if (self.ready) self.changed(self.owner);
+ }
+
+ fn onSignal(owner: ?*anyopaque, conn: *dbus.Connection, msg: wire.Message) !void {
+ const self: *Listener = @ptrCast(@alignCast(owner orelse return));
+ if (self.closing or !self.ready or msg.kind != .signal or
+ !eq(u8, msg.headers.path orelse "", path) or
+ !eq(u8, msg.headers.interface orelse "", interface) or
+ !knownMember(msg.headers.member orelse "")) return;
+ const sender = msg.headers.sender orelse return;
+ if (sender.len < 2 or sender.len > 255 or sender[0] != ':') return;
+ if (self.sender) |verified| {
+ if (eq(u8, sender, verified)) {
+ self.changed(self.owner);
+ return;
+ }
+ }
+ // One outstanding verification bounds work even if a client floods
+ // signals. Unique sender names cannot change owners on a live bus.
+ if (self.pending_sender != null) return;
+ self.pending_sender = try self.allocator.dupe(u8, sender);
+ errdefer {
+ self.allocator.free(self.pending_sender.?);
+ self.pending_sender = null;
+ }
+ var body: wire.Writer = .{ .allocator = self.allocator };
+ defer body.deinit();
+ try body.string(sender);
+ _ = try conn.call(bus, bus_path, bus, "GetConnectionUnixUser", "s", &body, self, onCredentials, 1500);
+ }
+
+ fn onCredentials(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
+ const self: *Listener = @ptrCast(@alignCast(owner orelse return));
+ if (self.closing) return;
+ const candidate = self.pending_sender orelse return;
+ self.pending_sender = null;
+ var keep = false;
+ defer if (!keep) self.allocator.free(candidate);
+ var msg = result catch return;
+ if (!fromBus(msg) or msg.kind != .method_return or !eq(u8, msg.headers.signature, "u")) return;
+ const uid = msg.body.uint32() catch return;
+ if (!trustedUid(uid, self.uids)) return;
+ if (self.sender) |old| self.allocator.free(old);
+ self.sender = candidate;
+ keep = true;
+ self.changed(self.owner);
+ }
+};
+
+fn fromBus(msg: wire.Message) bool {
+ return eq(u8, msg.headers.sender orelse "", bus);
+}
+
+fn knownMember(member: []const u8) bool {
+ for ([_][]const u8{
+ "ServerRestarted", "ServerStarted", "ServerStopped",
+ "PrinterRestarted", "PrinterShutdown", "PrinterStopped",
+ "PrinterStateChanged", "PrinterFinishingsChanged", "PrinterMediaChanged",
+ "PrinterAdded", "PrinterDeleted", "PrinterModified",
+ "JobState", "JobCreated", "JobCompleted",
+ "JobStopped", "JobConfigChanged", "JobProgress",
+ }) |known| if (eq(u8, known, member)) return true;
+ return false;
+}
+
+fn trustedUid(uid: u32, uids: [3]u32) bool {
+ for (uids) |trusted| if (uid == trusted) return true;
+ return false;
+}
+
+/// Common CUPS service accounts only. Custom users and a CUPS daemon run as
+/// the desktop user safely retain action-driven refresh. A notification is
+/// never a reason to accept another desktop user's sender as a system service.
+fn serviceUids(passwd: []const u8, desktop_uid: u32) [3]u32 {
+ var result: [3]u32 = .{ 0, 0, 0 };
+ var lines = std.mem.splitScalar(u8, passwd, '\n');
+ while (lines.next()) |line| {
+ var fields = std.mem.splitScalar(u8, line, ':');
+ const name = fields.next() orelse continue;
+ if (!eq(u8, name, "lp") and !eq(u8, name, "cups")) continue;
+ _ = fields.next() orelse continue;
+ const uid = std.fmt.parseInt(u32, fields.next() orelse continue, 10) catch continue;
+ if (uid == 0 or uid >= 1000 or uid == desktop_uid) continue;
+ result[if (eq(u8, name, "lp")) @as(usize, 1) else 2] = uid;
+ }
+ return result;
+}
+
+test "notifier hints accept only known members and trusted service credentials" {
+ const t = std.testing;
+ const uids = serviceUids("alex:x:1000:1000::/:/bin/sh\nlp:x:7:7::/:/usr/bin/nologin\ncups:x:209:209::/:/usr/bin/nologin\n", 1000);
+ try t.expect(trustedUid(0, uids));
+ try t.expect(trustedUid(7, uids));
+ try t.expect(trustedUid(209, uids));
+ try t.expect(!trustedUid(1000, uids));
+ try t.expect(knownMember("JobCompleted"));
+ try t.expect(knownMember("ServerRestarted"));
+ try t.expect(!knownMember("PrinterStateChangedInjected"));
+ try t.expectEqual([3]u32{ 0, 0, 0 }, serviceUids("lp:x:1000:1000\ncups:x:99:99\n", 99));
+}
+
+test "notifier creation honours an explicit unavailable bus without contacting the host bus" {
+ const t = std.testing;
+ const display = try wl.Server.create();
+ defer display.destroy();
+ const env: std.process.Environ = .{ .block = .{ .slice = &.{"DBUS_SYSTEM_BUS_ADDRESS=unsupported:tag=x"} } };
+ var callbacks: usize = 0;
+ const Changed = struct {
+ fn changed(owner: *anyopaque) void {
+ const count: *usize = @ptrCast(@alignCast(owner));
+ count.* += 1;
+ }
+ };
+ try t.expectError(error.NoSupportedAddress, Listener.create(t.allocator, t.io, env, display.getEventLoop(), &callbacks, Changed.changed));
+ try t.expectEqual(@as(usize, 0), callbacks);
+}
+
+test "notifier ignores forged credential replies and untrusted desktop senders" {
+ const t = std.testing;
+ const Changed = struct {
+ fn changed(owner: *anyopaque) void {
+ const count: *usize = @ptrCast(@alignCast(owner));
+ count.* += 1;
+ }
+ };
+ // Credential callbacks only need a borrowed connection identity; no socket
+ // or real bus is opened by this test.
+ var conn: dbus.Connection = undefined;
+ var callbacks: usize = 0;
+ var listener: Listener = .{ .allocator = t.allocator, .conn = &conn, .owner = &callbacks, .changed = Changed.changed, .uids = .{ 0, 7, 209 }, .ready = true };
+ defer if (listener.sender) |sender| t.allocator.free(sender);
+ var encoded_uid: [4]u8 = undefined;
+ std.mem.writeInt(u32, &encoded_uid, 0, .little);
+ var reply: wire.Message = .{ .kind = .method_return, .serial = 1, .headers = .{ .sender = ":1.forged", .signature = "u", .reply_serial = 1 }, .body = .{ .bytes = &encoded_uid } };
+ listener.pending_sender = try t.allocator.dupe(u8, ":1.20");
+ Listener.onCredentials(&listener, &conn, reply);
+ try t.expect(listener.sender == null);
+ try t.expect(listener.pending_sender == null);
+ try t.expectEqual(@as(usize, 0), callbacks);
+
+ reply.headers.sender = bus;
+ std.mem.writeInt(u32, &encoded_uid, 1000, .little);
+ listener.pending_sender = try t.allocator.dupe(u8, ":1.20");
+ Listener.onCredentials(&listener, &conn, reply);
+ try t.expect(listener.sender == null);
+ try t.expectEqual(@as(usize, 0), callbacks);
+
+ std.mem.writeInt(u32, &encoded_uid, 7, .little);
+ listener.pending_sender = try t.allocator.dupe(u8, ":1.21");
+ Listener.onCredentials(&listener, &conn, reply);
+ try t.expectEqualStrings(":1.21", listener.sender.?);
+ try t.expectEqual(@as(usize, 1), callbacks);
+ var signal: wire.Message = .{ .kind = .signal, .serial = 2, .headers = .{ .sender = ":1.21", .path = path, .interface = interface, .member = "PrinterStateChanged" }, .body = .{ .bytes = &.{} } };
+ try Listener.onSignal(&listener, &conn, signal);
+ try t.expectEqual(@as(usize, 2), callbacks);
+ signal.headers.interface = "untrusted.Notifier";
+ try Listener.onSignal(&listener, &conn, signal);
+ try t.expectEqual(@as(usize, 2), callbacks);
+ listener.closing = true;
+ signal.headers.interface = interface;
+ try Listener.onSignal(&listener, &conn, signal);
+ try t.expectEqual(@as(usize, 2), callbacks);
+}
diff --git a/src/printing/options.zig b/src/printing/options.zig
new file mode 100644
index 0000000..a891036
--- /dev/null
+++ b/src/printing/options.zig
@@ -0,0 +1,475 @@
+//! Bounded presentation of supported IPP choices and PPD UI declarations.
+//! PPD PostScript, filters, installables, JCL and commands are never evaluated.
+const std = @import("std");
+const ipp = @import("ipp.zig");
+const tools = @import("tools.zig");
+const A = std.mem.Allocator;
+const eq = std.mem.eql;
+
+pub const Choice = struct { value: []const u8 = "", label: []const u8 = "" };
+pub const Option = struct {
+ name: []const u8 = "",
+ label: []const u8 = "",
+ choices: []Choice = &.{},
+ default: ?[]const u8 = null,
+ range: ?ipp.Range = null,
+ source: enum { ipp, ppd } = .ipp,
+};
+pub const Group = struct { name: []const u8 = "", label: []const u8 = "", options: []Option = &.{} };
+const max_options = 256;
+const max_choices = 256;
+const max_groups = 32;
+
+/// Canonical CUPS/PPD resolution choice, retaining physical units exactly.
+/// Localized labels and arbitrary PPD PostScript are never interpreted.
+pub fn parseResolution(value: []const u8) ?ipp.Resolution {
+ if (value.len < 4 or value.len > 32) return null;
+ const dpcm = value.len > 4 and std.ascii.eqlIgnoreCase(value[value.len - 4 ..], "dpcm");
+ const dpi = std.ascii.eqlIgnoreCase(value[value.len - 3 ..], "dpi");
+ if (!dpcm and !dpi) return null;
+ const digits = value[0 .. value.len - @as(usize, if (dpcm) 4 else 3)];
+ const cross = std.mem.indexOfScalar(u8, digits, 'x') orelse digits.len;
+ if (cross == 0) return null;
+ for (digits[0..cross]) |ch| if (!std.ascii.isDigit(ch)) return null;
+ const x = std.fmt.parseInt(i32, digits[0..cross], 10) catch return null;
+ var y = x;
+ if (cross < digits.len) {
+ if (cross + 1 == digits.len) return null;
+ for (digits[cross + 1 ..]) |ch| if (!std.ascii.isDigit(ch)) return null;
+ y = std.fmt.parseInt(i32, digits[cross + 1 ..], 10) catch return null;
+ }
+ const resolution: ipp.Resolution = .{ .x = x, .y = y, .units = if (dpcm) .dpcm else .dpi };
+ _ = tools.dpiValue(resolution) orelse return null;
+ return resolution;
+}
+
+pub fn resolutionOption(option: Option) bool {
+ return eq(u8, option.name, "printer-resolution") or eq(u8, option.name, "Resolution") or eq(u8, option.name, "SetResolution") or eq(u8, option.name, "JCLResolution") or eq(u8, option.name, "CNRes_PGP");
+}
+
+const resolution_keys = [_][]const u8{ "Resolution", "SetResolution", "JCLResolution", "CNRes_PGP" };
+const duplex_keys = [_][]const u8{ "Duplex", "JCLDuplex", "EFDuplex", "KD03Duplex" };
+const color_keys = [_][]const u8{ "ColorModel", "ColorMode", "OutputMode" };
+const quality_keys = [_][]const u8{ "cupsPrintQuality", "PrintQuality", "Quality" };
+
+fn hasPpdChoice(groups: []const Group, names: []const []const u8) bool {
+ for (groups) |group| for (group.options) |option| {
+ if (option.source != .ppd or option.choices.len == 0) continue;
+ for (names) |name| if (eq(u8, option.name, name)) return true;
+ };
+ return false;
+}
+
+/// An advertised IPP job capability does not establish an editable queue/PPD
+/// default. In particular driverless PPDs may advertise resolution without a
+/// selectable Resolution UI, for which CUPS silently ignores queue changes.
+pub fn queueEditable(option: Option, groups: []const Group) bool {
+ if (option.source == .ppd) return true;
+ if (eq(u8, option.name, "printer-resolution")) return hasPpdChoice(groups, &resolution_keys);
+ if (eq(u8, option.name, "media")) return hasPpdChoice(groups, &.{"PageSize"});
+ if (eq(u8, option.name, "sides")) return hasPpdChoice(groups, &duplex_keys);
+ if (eq(u8, option.name, "print-color-mode")) return hasPpdChoice(groups, &color_keys);
+ if (eq(u8, option.name, "print-quality")) return hasPpdChoice(groups, &quality_keys);
+ // Vendor controls have no universal IPP-to-PPD translation. Only the exact
+ // selectable PPD key is safe to offer through the generic option setter.
+ return hasPpdChoice(groups, &.{option.name});
+}
+
+fn ppdDefault(groups: []const Group, name: []const u8) ?[]const u8 {
+ var result: ?[]const u8 = null;
+ for (groups) |group| for (group.options) |option| {
+ if (option.source != .ppd or !eq(u8, option.name, name)) continue;
+ const value = option.default orelse continue;
+ if (result) |previous| if (!eq(u8, previous, value)) return null;
+ result = value;
+ };
+ return result;
+}
+
+fn typedKeywordDefault(attributes: []const ipp.Attribute, name: []const u8) ?[]const u8 {
+ var result: ?[]const u8 = null;
+ for (attributes) |attribute| {
+ // A name-valued root override may precede the real typed metadata;
+ // that duplicate does not establish that the PPD/filter changed.
+ if (attribute.group != .printer or attribute.tag != .keyword or !eq(u8, attribute.name, name)) continue;
+ const value = attribute.text() orelse continue;
+ if (result) |previous| if (!eq(u8, previous, value)) return null;
+ result = value;
+ }
+ return result;
+}
+
+fn qualityValue(value: []const u8) ?i32 {
+ if (std.ascii.eqlIgnoreCase(value, "Draft") or eq(u8, value, "3")) return 3;
+ if (std.ascii.eqlIgnoreCase(value, "Normal") or eq(u8, value, "4")) return 4;
+ if (std.ascii.eqlIgnoreCase(value, "High") or eq(u8, value, "5")) return 5;
+ return null;
+}
+
+/// Verify a queued change against fresh server/PPD evidence. null is missing
+/// or contradictory evidence, false is an observed mismatch. Caller handles
+/// duplicate/default consistency warnings separately, retaining all records.
+pub fn settingMatches(groups: []const Group, attributes: []const ipp.Attribute, option: Option, requested: []const u8) ?bool {
+ if (option.source == .ppd) return eq(u8, ppdDefault(groups, option.name) orelse return null, requested);
+ if (eq(u8, option.name, "printer-resolution")) {
+ const target = tools.dpiValue(parseResolution(requested) orelse return null) orelse return null;
+ var actual: ?struct { x: f64, y: f64 } = null;
+ for (attributes) |attribute| {
+ if (attribute.group != .printer or !eq(u8, attribute.name, "printer-resolution-default")) continue;
+ const value = tools.dpiValue(attribute.resolution() orelse continue) orelse continue;
+ if (actual) |previous| if (@abs(previous.x - value.x) > 1 or @abs(previous.y - value.y) > 1) return null;
+ actual = .{ .x = value.x, .y = value.y };
+ }
+ const value = actual orelse return null;
+ return @abs(value.x - target.x) <= 1 and @abs(value.y - target.y) <= 1;
+ }
+ const keyword: ?[]const u8 = if (eq(u8, option.name, "media")) "media-default" else if (eq(u8, option.name, "sides")) "sides-default" else if (eq(u8, option.name, "print-color-mode")) "print-color-mode-default" else null;
+ if (keyword) |name| return eq(u8, typedKeywordDefault(attributes, name) orelse return null, requested);
+ if (eq(u8, option.name, "print-quality")) {
+ const target = qualityValue(requested) orelse return null;
+ if (ppdDefault(groups, "cupsPrintQuality")) |value| if (qualityValue(value)) |quality| return quality == target;
+ var actual: ?i32 = null;
+ for (attributes) |attribute| {
+ if (attribute.group != .printer or !eq(u8, attribute.name, "print-quality-default")) continue;
+ const value = attribute.integer() orelse continue;
+ if (actual) |previous| if (previous != value) return null;
+ actual = value;
+ }
+ return (actual orelse return null) == target;
+ }
+ if (hasPpdChoice(groups, &.{option.name})) return eq(u8, ppdDefault(groups, option.name) orelse return null, requested);
+ return null;
+}
+
+pub fn resolutionChoices(a: A, groups: []const Group) ![]ipp.Resolution {
+ var result: std.ArrayList(ipp.Resolution) = .empty;
+ errdefer result.deinit(a);
+ for (groups) |group| for (group.options) |option| {
+ if (!resolutionOption(option)) continue;
+ for (option.choices) |choice| {
+ const candidate = parseResolution(choice.value) orelse continue;
+ var duplicate = false;
+ for (result.items) |old| if (std.meta.eql(old, candidate)) {
+ duplicate = true;
+ break;
+ };
+ if (duplicate) continue;
+ if (result.items.len >= 256) return error.TooLarge;
+ try result.append(a, candidate);
+ }
+ };
+ return result.toOwnedSlice(a);
+}
+
+/// Results own their data and may outlive the IPP/PPD input.
+pub fn deinit(a: A, groups: []Group) void {
+ for (groups) |group| {
+ a.free(group.name);
+ a.free(group.label);
+ for (group.options) |option| {
+ a.free(option.name);
+ a.free(option.label);
+ if (option.default) |value| a.free(value);
+ for (option.choices) |choice| {
+ a.free(choice.value);
+ a.free(choice.label);
+ }
+ a.free(option.choices);
+ }
+ a.free(group.options);
+ }
+ a.free(groups);
+}
+
+const Definition = struct { name: []const u8, supported: []const u8, default: []const u8, label: []const u8 };
+const definitions = [_]Definition{
+ .{ .name = "media", .supported = "media-supported", .default = "media-default", .label = "Paper size" },
+ .{ .name = "printer-resolution", .supported = "printer-resolution-supported", .default = "printer-resolution-default", .label = "Resolution" },
+ .{ .name = "sides", .supported = "sides-supported", .default = "sides-default", .label = "Two-sided printing" },
+ .{ .name = "print-color-mode", .supported = "print-color-mode-supported", .default = "print-color-mode-default", .label = "Colour" },
+ .{ .name = "print-quality", .supported = "print-quality-supported", .default = "print-quality-default", .label = "Quality" },
+ .{ .name = "print-darkness", .supported = "print-darkness-supported", .default = "print-darkness-default", .label = "Darkness" },
+ .{ .name = "print-speed", .supported = "print-speed-supported", .default = "print-speed-default", .label = "Speed" },
+};
+
+fn safeText(a: A, value: []const u8) ![]u8 {
+ if (value.len > 512) return error.InvalidOptions;
+ // Older PPDs commonly use ISOLatin1. Keep their UI labels usable without
+ // passing malformed UTF-8 into the widget/text stack.
+ if (!std.unicode.utf8ValidateSlice(value)) {
+ var out: std.Io.Writer.Allocating = .init(a);
+ defer out.deinit();
+ for (value) |ch| {
+ if (ch < 0x20 or ch == 0x7f or (ch >= 0x80 and ch < 0xa0)) {
+ try out.writer.writeByte(' ');
+ } else if (ch < 0x80) {
+ try out.writer.writeByte(ch);
+ } else {
+ try out.writer.writeAll(&.{ 0xc0 | (ch >> 6), 0x80 | (ch & 0x3f) });
+ }
+ }
+ return out.toOwnedSlice();
+ }
+ const copy = try a.dupe(u8, value);
+ for (copy) |*ch| if (ch.* < 0x20 or ch.* == 0x7f) {
+ ch.* = ' ';
+ };
+ return copy;
+}
+fn identifier(value: []const u8) bool {
+ if (value.len == 0 or value.len > 255) return false;
+ for (value) |ch| if (ch < 0x21 or ch > 0x7e or ch == ':' or ch == '/' or ch == '\\' or ch == '"' or ch == '\'') return false;
+ return true;
+}
+fn attributeValue(a: A, attr: ipp.Attribute) !?[]const u8 {
+ if (attr.resolution()) |resolution| {
+ _ = tools.dpiValue(resolution) orelse return null;
+ const suffix = if (resolution.units == .dpi) "dpi" else "dpcm";
+ return if (resolution.x == resolution.y) try std.fmt.allocPrint(a, "{d}{s}", .{ resolution.x, suffix }) else try std.fmt.allocPrint(a, "{d}x{d}{s}", .{ resolution.x, resolution.y, suffix });
+ }
+ if (attr.integer()) |value| return try std.fmt.allocPrint(a, "{d}", .{value});
+ const value = attr.text() orelse return null;
+ if (!identifier(value)) return null;
+ return value;
+}
+fn choiceLabel(name: []const u8, value: []const u8) []const u8 {
+ if (eq(u8, name, "sides")) {
+ if (eq(u8, value, "one-sided")) return "One-sided";
+ if (eq(u8, value, "two-sided-long-edge")) return "Two-sided, long edge";
+ if (eq(u8, value, "two-sided-short-edge")) return "Two-sided, short edge";
+ } else if (eq(u8, name, "print-color-mode")) {
+ if (eq(u8, value, "monochrome")) return "Black and white";
+ if (eq(u8, value, "color")) return "Colour";
+ if (eq(u8, value, "auto")) return "Automatic";
+ } else if (eq(u8, name, "print-quality")) {
+ if (eq(u8, value, "3")) return "Draft";
+ if (eq(u8, value, "4")) return "Normal";
+ if (eq(u8, value, "5")) return "High";
+ }
+ return value;
+}
+fn appendChoice(a: A, choices: *std.ArrayList(Choice), name: []const u8, value: []const u8, label: ?[]const u8) !void {
+ for (choices.items) |choice| if (eq(u8, choice.value, value)) return;
+ if (choices.items.len >= max_choices) return error.TooLarge;
+ var display = label orelse choiceLabel(name, value);
+ if (label == null and eq(u8, name, "media")) {
+ if (tools.mediaFromKeyword(value)) |media| {
+ const paper: []const u8 = if (std.mem.startsWith(u8, value, "iso_a4_")) "A4" else if (std.mem.startsWith(u8, value, "iso_a3_")) "A3" else if (std.mem.startsWith(u8, value, "iso_a5_")) "A5" else if (std.mem.startsWith(u8, value, "na_letter_")) "Letter" else if (std.mem.startsWith(u8, value, "na_legal_")) "Legal" else "Paper";
+ display = try std.fmt.allocPrint(a, "{s} ({d:.1} x {d:.1} mm)", .{ paper, media.width_mm, media.height_mm });
+ }
+ }
+ try choices.append(a, .{ .value = value, .label = try safeText(a, display) });
+}
+
+pub fn parseAttributes(a: A, attributes: []const ipp.Attribute) ![]Group {
+ if (attributes.len > 16384) return error.TooLarge;
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const mem = arena.allocator();
+ var options: std.ArrayList(Option) = .empty;
+ for (definitions) |definition| {
+ var choices: std.ArrayList(Choice) = .empty;
+ var default: ?[]const u8 = null;
+ var saw_default = false;
+ var range: ?ipp.Range = null;
+ for (attributes) |attr| {
+ if (attr.group != .printer) continue;
+ // CUPS can place a name-valued user override before the typed PPD
+ // default. Match its first-occurrence semantics without concealing
+ // the duplicate records from the caller's consistency diagnostics.
+ if (!saw_default and eq(u8, attr.name, definition.default)) {
+ saw_default = true;
+ default = try attributeValue(mem, attr);
+ }
+ if (!eq(u8, attr.name, definition.supported)) continue;
+ if (attr.range()) |r| {
+ if (r.lower < 0 or r.upper < r.lower) continue;
+ range = r;
+ if (@as(i64, r.upper) - r.lower < max_choices) {
+ var n: i64 = r.lower;
+ while (n <= r.upper) : (n += 1) try appendChoice(mem, &choices, definition.name, try std.fmt.allocPrint(mem, "{d}", .{n}), null);
+ }
+ } else if (try attributeValue(mem, attr)) |value| try appendChoice(mem, &choices, definition.name, value, null);
+ }
+ if (choices.items.len != 0 or range != null) try options.append(mem, .{
+ .name = definition.name,
+ .label = definition.label,
+ .choices = choices.items,
+ .default = default,
+ .range = range,
+ });
+ }
+ if (options.items.len == 0) return a.alloc(Group, 0);
+ return clone(a, &.{.{ .name = "general", .label = "Printer settings", .options = options.items }});
+}
+
+fn clone(a: A, source: []const Group) ![]Group {
+ const result = try a.alloc(Group, source.len);
+ @memset(result, .{});
+ errdefer deinit(a, result);
+ for (source, result) |from, *to| {
+ to.name = try a.dupe(u8, from.name);
+ to.label = try safeText(a, from.label);
+ to.options = try a.alloc(Option, from.options.len);
+ @memset(to.options, .{});
+ for (from.options, to.options) |old, *new| {
+ new.name = try a.dupe(u8, old.name);
+ new.label = try safeText(a, old.label);
+ new.default = if (old.default) |value| try a.dupe(u8, value) else null;
+ new.range = old.range;
+ new.source = old.source;
+ new.choices = try a.alloc(Choice, old.choices.len);
+ @memset(new.choices, .{});
+ for (old.choices, new.choices) |choice, *copy| {
+ copy.value = try a.dupe(u8, choice.value);
+ copy.label = try safeText(a, choice.label);
+ }
+ }
+ }
+ return result;
+}
+
+const BuildOption = struct { option: Option, choices: std.ArrayList(Choice) = .empty };
+const BuildGroup = struct { name: []const u8, label: []const u8, options: std.ArrayList(BuildOption) = .empty };
+const NameLabel = struct { name: []const u8, label: []const u8 };
+fn nameLabel(value: []const u8) !NameLabel {
+ const slash = std.mem.indexOfScalar(u8, value, '/') orelse value.len;
+ const name = value[0..slash];
+ if (!identifier(name)) return error.InvalidOptions;
+ return .{ .name = name, .label = if (slash < value.len) value[slash + 1 ..] else name };
+}
+fn ppdLine(raw: []const u8) !?struct { key: []const u8, value: []const u8 } {
+ if (raw.len > 16384) return error.TooLarge;
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0 or line[0] != '*' or std.mem.startsWith(u8, line, "*%")) return null;
+ const colon = std.mem.indexOfScalar(u8, line, ':') orelse return null;
+ var value = std.mem.trim(u8, line[colon + 1 ..], " \t");
+ if (value.len >= 2 and value[0] == '"' and value[value.len - 1] == '"') value = value[1 .. value.len - 1];
+ return .{ .key = line[1..colon], .value = value };
+}
+
+/// Parse only PickOne/Boolean OpenUI declarations, choices and defaults into
+/// their declared groups. PickMany and executable fields are not configuration
+/// choices. Remote PPD download is owned by the caller's bounded transport.
+pub fn parsePpd(a: A, bytes: []const u8) ![]Group {
+ if (bytes.len > 4 * 1024 * 1024) return error.TooLarge;
+ if (!std.mem.startsWith(u8, bytes, "*PPD-Adobe:") or std.mem.indexOfScalar(u8, bytes, 0) != null) return error.InvalidOptions;
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const mem = arena.allocator();
+ var groups: std.ArrayList(BuildGroup) = .empty;
+ try groups.append(mem, .{ .name = "general", .label = "General" });
+ var group: usize = 0;
+ var parents: [8]usize = undefined;
+ var depth: usize = 0;
+ var active: ?usize = null;
+ var option_count: usize = 0;
+ var choice_count: usize = 0;
+ var defaults = std.StringHashMap([]const u8).init(mem);
+ var lines = std.mem.splitScalar(u8, bytes, '\n');
+ while (lines.next()) |raw| {
+ const line = (try ppdLine(raw)) orelse continue;
+ if (eq(u8, line.key, "OpenGroup") or eq(u8, line.key, "OpenSubGroup")) {
+ if (depth >= parents.len or groups.items.len >= max_groups) return error.TooLarge;
+ if (active != null) return error.InvalidOptions;
+ const named = try nameLabel(line.value);
+ parents[depth] = group;
+ depth += 1;
+ group = groups.items.len;
+ try groups.append(mem, .{ .name = named.name, .label = named.label });
+ } else if (eq(u8, line.key, "CloseGroup") or eq(u8, line.key, "CloseSubGroup")) {
+ if (depth == 0 or active != null) return error.InvalidOptions;
+ depth -= 1;
+ group = parents[depth];
+ } else if (std.mem.startsWith(u8, line.key, "OpenUI *")) {
+ if (active != null or option_count >= max_options) return error.InvalidOptions;
+ if (!eq(u8, line.value, "PickOne") and !eq(u8, line.value, "Boolean")) continue;
+ const named = try nameLabel(line.key[8..]);
+ active = groups.items[group].options.items.len;
+ try groups.items[group].options.append(mem, .{ .option = .{ .name = named.name, .label = named.label, .source = .ppd } });
+ option_count += 1;
+ } else if (eq(u8, line.key, "CloseUI")) {
+ active = null;
+ } else if (std.mem.startsWith(u8, line.key, "Default")) {
+ if (identifier(line.key[7..]) and identifier(line.value)) {
+ if (defaults.count() >= 4096 and !defaults.contains(line.key[7..])) return error.TooLarge;
+ try defaults.put(line.key[7..], line.value);
+ }
+ } else if (active) |index| {
+ const built = &groups.items[group].options.items[index];
+ const option = &built.option;
+ const end = std.mem.indexOfScalar(u8, line.key, ' ') orelse continue;
+ if (!eq(u8, line.key[0..end], option.name)) continue;
+ const named = try nameLabel(std.mem.trimStart(u8, line.key[end + 1 ..], " \t"));
+ const count = built.choices.items.len;
+ try appendChoice(mem, &built.choices, option.name, named.name, named.label);
+ if (built.choices.items.len != count) choice_count += 1;
+ if (choice_count > 4096) return error.TooLarge;
+ }
+ }
+ if (depth != 0 or active != null) return error.InvalidOptions;
+ var output: std.ArrayList(Group) = .empty;
+ for (groups.items) |built| {
+ var parsed: std.ArrayList(Option) = .empty;
+ for (built.options.items) |item| {
+ var option = item.option;
+ option.default = defaults.get(option.name);
+ option.choices = item.choices.items;
+ if (option.choices.len != 0) try parsed.append(mem, option);
+ }
+ if (parsed.items.len != 0) try output.append(mem, .{ .name = built.name, .label = built.label, .options = parsed.items });
+ }
+ return clone(a, output.items);
+}
+
+/// PPD PaperDimension is a pair of physical PostScript points; it is data,
+/// unlike the executable PageSize choice body. Never run that PostScript.
+pub fn ppdMediaDimensions(bytes: []const u8, choice: []const u8) ?tools.Media {
+ const dimensions = ppdNumbers(2, bytes, "PaperDimension ", choice) orelse return null;
+ const media: tools.Media = .{ .width_mm = dimensions[0] * 25.4 / 72, .height_mm = dimensions[1] * 25.4 / 72 };
+ return if (media.valid()) media else null;
+}
+
+pub const Margins = struct { left_mm: f64, right_mm: f64, top_mm: f64, bottom_mm: f64 };
+
+/// ImageableArea stores left/bottom/right/top coordinates in physical points.
+/// Keep the declared paper and printable rectangle separate from executable
+/// PageSize bodies; invalid, out-of-paper and conflicting declarations are unknown.
+pub fn ppdMargins(bytes: []const u8, choice: []const u8) ?Margins {
+ const dimensions = ppdNumbers(2, bytes, "PaperDimension ", choice) orelse return null;
+ const area = ppdNumbers(4, bytes, "ImageableArea ", choice) orelse return null;
+ _ = ppdMediaDimensions(bytes, choice) orelse return null;
+ if (area[0] < 0 or area[1] < 0 or area[2] > dimensions[0] or area[3] > dimensions[1] or area[2] <= area[0] or area[3] <= area[1]) return null;
+ return .{
+ .left_mm = area[0] * 25.4 / 72,
+ .bottom_mm = area[1] * 25.4 / 72,
+ .right_mm = (dimensions[0] - area[2]) * 25.4 / 72,
+ .top_mm = (dimensions[1] - area[3]) * 25.4 / 72,
+ };
+}
+
+fn ppdNumbers(comptime count: usize, bytes: []const u8, prefix: []const u8, choice: []const u8) ?[count]f64 {
+ if (bytes.len > 4 * 1024 * 1024 or !identifier(choice)) return null;
+ var result: ?[count]f64 = null;
+ var lines = std.mem.splitScalar(u8, bytes, '\n');
+ while (lines.next()) |raw| {
+ const line = (ppdLine(raw) catch return null) orelse continue;
+ if (!std.mem.startsWith(u8, line.key, prefix)) continue;
+ const named = nameLabel(std.mem.trimStart(u8, line.key[prefix.len..], " \t")) catch continue;
+ if (!eq(u8, named.name, choice)) continue;
+ var numbers = std.mem.tokenizeAny(u8, line.value, " \t");
+ var parsed: [count]f64 = undefined;
+ for (&parsed) |*number| {
+ number.* = std.fmt.parseFloat(f64, numbers.next() orelse return null) catch return null;
+ if (!std.math.isFinite(number.*)) return null;
+ }
+ if (numbers.next() != null) return null;
+ if (result) |previous| if (!std.mem.eql(f64, &previous, &parsed)) return null;
+ result = parsed;
+ }
+ return result;
+}
+
+test {
+ _ = @import("options_tests.zig");
+}
diff --git a/src/printing/options_tests.zig b/src/printing/options_tests.zig
new file mode 100644
index 0000000..62f8d27
--- /dev/null
+++ b/src/printing/options_tests.zig
@@ -0,0 +1,229 @@
+const std = @import("std");
+const options = @import("options.zig");
+const ipp = @import("ipp.zig");
+const a = std.testing.allocator;
+
+const ppd =
+ \\*PPD-Adobe: "4.3"
+ \\*DefaultResolution: 203dpi
+ \\*OpenGroup: General/General options
+ \\*OpenUI *PageSize/Paper size: PickOne
+ \\*DefaultPageSize: Label
+ \\*PageSize Label/4 x 6 inch: "malicious arbitrary PostScript ignored"
+ \\*PageSize A4/A4: "<</PageSize[595 842]>>setpagedevice"
+ \\*CloseUI: *PageSize
+ \\*PaperDimension Label: "288 432"
+ \\*ImageableArea Label: "18 12 264 402"
+ \\*OpenUI *Resolution/Resolution: PickOne
+ \\*Resolution 203dpi/203 dpi: "never execute this"
+ \\*Resolution 300dpi/300 dpi: "never execute this either"
+ \\*CloseUI: *Resolution
+ \\*CloseGroup: General
+ \\*OpenGroup: Label/Label controls
+ \\*OpenUI *Darkness/Print darkness: PickOne
+ \\*Darkness 5/Light: "unused"
+ \\*Darkness 10/Normal: "unused"
+ \\*CloseUI: *Darkness
+ \\*CloseGroup: Label
+;
+
+test "PPD UI choices preserve driver groups without interpreting commands" {
+ const groups = try options.parsePpd(a, ppd);
+ defer options.deinit(a, groups);
+ try std.testing.expectEqual(@as(usize, 2), groups.len);
+ try std.testing.expectEqualStrings("General options", groups[0].label);
+ try std.testing.expectEqualStrings("PageSize", groups[0].options[0].name);
+ try std.testing.expectEqualStrings("Label", groups[0].options[0].default.?);
+ try std.testing.expectEqualStrings("4 x 6 inch", groups[0].options[0].choices[0].label);
+ try std.testing.expectEqualStrings("203dpi", groups[0].options[1].default.?);
+ try std.testing.expectEqualStrings("Label controls", groups[1].label);
+ try std.testing.expectEqualStrings("Darkness", groups[1].options[0].name);
+ const media = options.ppdMediaDimensions(ppd, "Label").?;
+ try std.testing.expectApproxEqAbs(@as(f64, 101.6), media.width_mm, 0.0001);
+ try std.testing.expectApproxEqAbs(@as(f64, 152.4), media.height_mm, 0.0001);
+ try std.testing.expect(options.ppdMediaDimensions(ppd, "Absent") == null);
+ const margins = options.ppdMargins(ppd, "Label").?;
+ try std.testing.expectApproxEqAbs(@as(f64, 6.35), margins.left_mm, 0.0001);
+ try std.testing.expectApproxEqAbs(@as(f64, 8.46666667), margins.right_mm, 0.0001);
+ try std.testing.expectApproxEqAbs(@as(f64, 10.58333333), margins.top_mm, 0.0001);
+ try std.testing.expectApproxEqAbs(@as(f64, 4.23333333), margins.bottom_mm, 0.0001);
+ try std.testing.expect(options.ppdMargins(ppd, "Absent") == null);
+}
+
+test "PPD data is bounded and structurally incomplete options are rejected" {
+ try std.testing.expectError(error.InvalidOptions, options.parsePpd(a, "not a PPD"));
+ try std.testing.expectError(error.InvalidOptions, options.parsePpd(a, "*PPD-Adobe: \"4.3\"\n*OpenUI *X/X: PickOne\n"));
+ try std.testing.expectError(error.InvalidOptions, options.parsePpd(a, "*PPD-Adobe: \"4.3\"\n*CloseGroup: X\n"));
+ try std.testing.expect(options.ppdMediaDimensions("*PaperDimension A4: \"nan 842\"", "A4") == null);
+ for ([_][]const u8{ "-1 0 288 432", "0 0 289 432", "0 0 288 433", "12 0 10 432", "0 5 288 5", "0 0 inf 432", "0 nan 288 432", "0 0 288", "0 0 288 432 1" }) |area| {
+ const invalid = try std.fmt.allocPrint(a, "*PaperDimension Label: \"288 432\"\n*ImageableArea Label: \"{s}\"\n", .{area});
+ defer a.free(invalid);
+ try std.testing.expect(options.ppdMargins(invalid, "Label") == null);
+ }
+ try std.testing.expect(options.ppdMargins("*PaperDimension Label: \"288 432\"\n", "Label") == null);
+ const borderless = options.ppdMargins("*PaperDimension Label: \"288 432\"\n*ImageableArea Label: \"0 0 288 432\"\n", "Label").?;
+ try std.testing.expectEqual(options.Margins{ .left_mm = 0, .right_mm = 0, .top_mm = 0, .bottom_mm = 0 }, borderless);
+}
+
+test "IPP supported options preserve numeric quality and dpcm units" {
+ var enc = try ipp.Encoder.init(a, 0, 1);
+ defer enc.deinit();
+ try enc.group(.operation);
+ try enc.group(.printer);
+ try enc.string(.keyword, "media-supported", "iso_a4_210x297mm");
+ try enc.string(.keyword, "", "na_index-4x6_4x6in");
+ try enc.string(.keyword, "media-default", "na_index-4x6_4x6in");
+ try enc.string(.keyword, "sides-supported", "one-sided");
+ try enc.string(.keyword, "", "two-sided-long-edge");
+ try enc.integer(.enum_value, "print-quality-supported", 3);
+ try enc.integer(.enum_value, "", 4);
+ var resolution: [9]u8 = undefined;
+ std.mem.writeInt(i32, resolution[0..4], 80, .big);
+ std.mem.writeInt(i32, resolution[4..8], 80, .big);
+ resolution[8] = 4;
+ try enc.value(.resolution, "printer-resolution-supported", &resolution);
+ var range: [8]u8 = undefined;
+ std.mem.writeInt(i32, range[0..4], 1, .big);
+ std.mem.writeInt(i32, range[4..8], 5, .big);
+ try enc.value(.range, "print-darkness-supported", &range);
+ var msg = try ipp.decode(a, try enc.finish(), .{});
+ defer msg.deinit(a);
+ const groups = try options.parseAttributes(a, msg.attributes);
+ defer options.deinit(a, groups);
+ try std.testing.expectEqual(@as(usize, 1), groups.len);
+ const list = groups[0].options;
+ try std.testing.expectEqualStrings("media", list[0].name);
+ try std.testing.expectEqualStrings("A4 (210.0 x 297.0 mm)", list[0].choices[0].label);
+ try std.testing.expectEqualStrings("80dpcm", list[1].choices[0].value);
+ try std.testing.expectEqualStrings("Two-sided, long edge", list[2].choices[1].label);
+ try std.testing.expectEqualStrings("Draft", list[3].choices[0].label);
+ try std.testing.expectEqual(@as(usize, 5), list[4].choices.len);
+}
+
+fn allocationFailure(mem: std.mem.Allocator) !void {
+ const groups = try options.parsePpd(mem, ppd);
+ defer options.deinit(mem, groups);
+}
+test "PPD parser cleans up every partially allocated result" {
+ try std.testing.checkAllAllocationFailures(a, allocationFailure, .{});
+}
+
+test "resolution choice helpers preserve exact dpi and dpcm values for calibration" {
+ try std.testing.expectEqual(ipp.Resolution{ .x = 203, .y = 203, .units = .dpi }, options.parseResolution("203dpi").?);
+ try std.testing.expectEqual(ipp.Resolution{ .x = 300, .y = 600, .units = .dpi }, options.parseResolution("300x600dpi").?);
+ try std.testing.expectEqual(ipp.Resolution{ .x = 80, .y = 80, .units = .dpcm }, options.parseResolution("80dpcm").?);
+ for ([_][]const u8{ "Custom", "0dpi", "-203dpi", "300 dpi", "300x600x1200dpi", "300xdpi", "2147483647dpi", "nanDPI", "dpi" }) |invalid| try std.testing.expect(options.parseResolution(invalid) == null);
+ const groups = try options.parsePpd(a, ppd);
+ defer options.deinit(a, groups);
+ const supported = try options.resolutionChoices(a, groups);
+ defer a.free(supported);
+ try std.testing.expectEqualSlices(ipp.Resolution, &.{ .{ .x = 203, .y = 203, .units = .dpi }, .{ .x = 300, .y = 300, .units = .dpi } }, supported);
+}
+
+test "IPP duplicate defaults keep the first CUPS override without discarding typed evidence" {
+ var encoder = try ipp.Encoder.init(a, 0, 1);
+ defer encoder.deinit();
+ try encoder.group(.operation);
+ try encoder.group(.printer);
+ try encoder.string(.name, "printer-resolution-default", "203dpi");
+ const resolution = "\x00\x00\x01\x2c\x00\x00\x01\x2c\x03";
+ try encoder.value(.resolution, "printer-resolution-default", resolution);
+ try encoder.value(.resolution, "printer-resolution-supported", resolution);
+ try encoder.string(.keyword, "media-default", "na_index-4x6_4x6in");
+ try encoder.string(.keyword, "media-default", "iso_a4_210x297mm");
+ try encoder.string(.keyword, "media-supported", "na_index-4x6_4x6in");
+ var message = try ipp.decode(a, try encoder.finish(), .{ .allow_duplicate_names = true });
+ defer message.deinit(a);
+ const groups = try options.parseAttributes(a, message.attributes);
+ defer options.deinit(a, groups);
+ try std.testing.expectEqualStrings("na_index-4x6_4x6in", groups[0].options[0].default.?);
+ try std.testing.expectEqualStrings("203dpi", groups[0].options[1].default.?);
+ try std.testing.expectEqual(@as(i32, 300), message.attributes[1].resolution().?.x);
+}
+
+test "queue editability requires an actual selectable PPD counterpart for IPP job capabilities" {
+ const groups = try options.parsePpd(a, ppd);
+ defer options.deinit(a, groups);
+ try std.testing.expect(options.queueEditable(.{ .name = "PageSize", .source = .ppd }, &.{}));
+ try std.testing.expect(options.queueEditable(.{ .name = "media" }, groups));
+ try std.testing.expect(options.queueEditable(.{ .name = "printer-resolution" }, groups));
+ try std.testing.expect(!options.queueEditable(.{ .name = "sides" }, groups));
+ try std.testing.expect(!options.queueEditable(.{ .name = "print-darkness" }, groups));
+ try std.testing.expect(!options.queueEditable(.{ .name = "print-speed", .range = .{ .lower = 1, .upper = 100 } }, groups));
+ const driverless = try options.parsePpd(a,
+ \\*PPD-Adobe: "4.3"
+ \\*DefaultResolution: 300dpi
+ \\*OpenUI *PageSize/Paper: PickOne
+ \\*PageSize A4/A4: "unused"
+ \\*CloseUI: *PageSize
+ );
+ defer options.deinit(a, driverless);
+ // A DefaultResolution line does not make the generated PPD selectable.
+ try std.testing.expect(!options.queueEditable(.{ .name = "printer-resolution" }, driverless));
+ const aliases = try options.parsePpd(a,
+ \\*PPD-Adobe: "4.3"
+ \\*OpenUI *SetResolution/Resolution: PickOne
+ \\*SetResolution 300dpi/300 dpi: "unused"
+ \\*CloseUI: *SetResolution
+ \\*OpenUI *Duplex/Sides: PickOne
+ \\*Duplex None/One-sided: "unused"
+ \\*CloseUI: *Duplex
+ \\*OpenUI *ColorModel/Colour: PickOne
+ \\*ColorModel RGB/Colour: "unused"
+ \\*CloseUI: *ColorModel
+ \\*OpenUI *cupsPrintQuality/Quality: PickOne
+ \\*cupsPrintQuality Normal/Normal: "unused"
+ \\*CloseUI: *cupsPrintQuality
+ \\*OpenUI *print-speed/Speed: PickOne
+ \\*print-speed 5/5: "unused"
+ \\*CloseUI: *print-speed
+ );
+ defer options.deinit(a, aliases);
+ for ([_][]const u8{ "printer-resolution", "sides", "print-color-mode", "print-quality", "print-speed" }) |name| try std.testing.expect(options.queueEditable(.{ .name = name }, aliases));
+}
+
+test "fresh setting verification uses typed CUPS defaults and exact PPD defaults without trusting name overrides" {
+ const groups = try options.parsePpd(a, ppd);
+ defer options.deinit(a, groups);
+ var encoder = try ipp.Encoder.init(a, 0, 1);
+ defer encoder.deinit();
+ try encoder.group(.operation);
+ try encoder.group(.printer);
+ try encoder.string(.name, "printer-resolution-default", "203dpi");
+ const r300 = "\x00\x00\x01\x2c\x00\x00\x01\x2c\x03";
+ try encoder.value(.resolution, "printer-resolution-default", r300);
+ try encoder.string(.name, "media-default", "na_index-4x6_4x6in");
+ try encoder.string(.keyword, "media-default", "iso_a4_210x297mm");
+ try encoder.string(.name, "sides-default", "two-sided-long-edge");
+ try encoder.string(.keyword, "sides-default", "one-sided");
+ try encoder.string(.name, "print-color-mode-default", "color");
+ try encoder.string(.keyword, "print-color-mode-default", "monochrome");
+ try encoder.string(.name, "print-quality-default", "5");
+ try encoder.integer(.enum_value, "print-quality-default", 4);
+ var message = try ipp.decode(a, try encoder.finish(), .{ .allow_duplicate_names = true });
+ defer message.deinit(a);
+ try std.testing.expectEqual(@as(?bool, false), options.settingMatches(groups, message.attributes, .{ .name = "printer-resolution" }, "203dpi"));
+ try std.testing.expectEqual(@as(?bool, true), options.settingMatches(groups, message.attributes, .{ .name = "printer-resolution" }, "300dpi"));
+ try std.testing.expectEqual(@as(?bool, true), options.settingMatches(groups, message.attributes, .{ .name = "Resolution", .source = .ppd }, "203dpi"));
+ try std.testing.expectEqual(@as(?bool, false), options.settingMatches(groups, message.attributes, .{ .name = "Resolution", .source = .ppd }, "300dpi"));
+ try std.testing.expectEqual(@as(?bool, true), options.settingMatches(groups, message.attributes, .{ .name = "media" }, "iso_a4_210x297mm"));
+ try std.testing.expectEqual(@as(?bool, false), options.settingMatches(groups, message.attributes, .{ .name = "media" }, "na_index-4x6_4x6in"));
+ try std.testing.expectEqual(@as(?bool, false), options.settingMatches(groups, message.attributes, .{ .name = "sides" }, "two-sided-long-edge"));
+ try std.testing.expectEqual(@as(?bool, true), options.settingMatches(groups, message.attributes, .{ .name = "print-color-mode" }, "monochrome"));
+ try std.testing.expectEqual(@as(?bool, true), options.settingMatches(groups, message.attributes, .{ .name = "print-quality" }, "4"));
+ try std.testing.expectEqual(@as(?bool, null), options.settingMatches(groups, message.attributes, .{ .name = "unknown" }, "anything"));
+ try std.testing.expectEqual(@as(?bool, null), options.settingMatches(groups, &.{}, .{ .name = "printer-resolution" }, "300dpi"));
+ const quality = try options.parsePpd(a,
+ \\*PPD-Adobe: "4.3"
+ \\*OpenUI *cupsPrintQuality/Quality: PickOne
+ \\*DefaultcupsPrintQuality: High
+ \\*cupsPrintQuality High/High: "unused"
+ \\*CloseUI: *cupsPrintQuality
+ );
+ defer options.deinit(a, quality);
+ try std.testing.expectEqual(@as(?bool, true), options.settingMatches(quality, message.attributes, .{ .name = "print-quality" }, "5"));
+ try std.testing.expectEqual(@as(?bool, false), options.settingMatches(quality, message.attributes, .{ .name = "print-quality" }, "4"));
+ const dpcm: ipp.Attribute = .{ .group = .printer, .group_index = 0, .name = "printer-resolution-default", .tag = .resolution, .value = "\x00\x00\x00\x50\x00\x00\x00\x50\x04" };
+ try std.testing.expectEqual(@as(?bool, true), options.settingMatches(&.{}, &.{dpcm}, .{ .name = "printer-resolution" }, "203dpi"));
+ try std.testing.expectEqual(@as(?bool, false), options.settingMatches(&.{}, &.{dpcm}, .{ .name = "printer-resolution" }, "203x300dpi"));
+}
diff --git a/src/printing/platform.zig b/src/printing/platform.zig
new file mode 100644
index 0000000..bbf3c2b
--- /dev/null
+++ b/src/printing/platform.zig
@@ -0,0 +1,165 @@
+//! Bounded os-release parsing and package guidance. No package manager, shell,
+//! service mutation or scheduler connection is involved in platform discovery.
+const std = @import("std");
+const A = std.mem.Allocator;
+const Io = std.Io;
+
+pub const Distro = enum { arch, artix, cachyos, debian, ubuntu, fedora, opensuse, generic };
+pub const Info = struct {
+ distro: Distro = .generic,
+ id: []const u8 = "",
+ id_like: []const u8 = "",
+ cups_package: []const u8 = "cups",
+ helper_package: []const u8 = "cups-pk-helper",
+ // A regular executable at a conventional path is evidence of installation,
+ // never evidence that the daemon is running/enabled. null means inaccessible.
+ daemon_installed: ?bool = null,
+ missing_cups: []const u8 = "Printing needs CUPS. Ask your distribution's package manager for its CUPS print-server package, then start the print service.",
+ missing_helper: []const u8 = "Printer administration needs the optional cups-pk-helper package and an authorization policy that permits the action.",
+
+ pub fn deinit(self: *Info, a: A) void {
+ a.free(self.id);
+ a.free(self.id_like);
+ self.* = undefined;
+ }
+};
+
+fn value(raw: []const u8) ![]const u8 {
+ const text = std.mem.trim(u8, raw, " \t\r");
+ if (text.len > 255) return error.InvalidOsRelease;
+ if (text.len == 0) return text;
+ if (text[0] == '\'' or text[0] == '"') {
+ if (text.len < 2 or text[text.len - 1] != text[0]) return error.InvalidOsRelease;
+ return text[1 .. text.len - 1];
+ }
+ if (std.mem.indexOfAny(u8, text, "\"'") != null) return error.InvalidOsRelease;
+ return text;
+}
+
+fn validId(id: []const u8) bool {
+ if (id.len == 0 or id.len > 127) return false;
+ for (id) |ch| if (!std.ascii.isLower(ch) and !std.ascii.isDigit(ch) and ch != '.' and ch != '_' and ch != '-') return false;
+ return true;
+}
+
+fn exact(id: []const u8) ?Distro {
+ const entries = .{ .{ "arch", Distro.arch }, .{ "artix", Distro.artix }, .{ "cachyos", Distro.cachyos }, .{ "debian", Distro.debian }, .{ "ubuntu", Distro.ubuntu }, .{ "fedora", Distro.fedora }, .{ "opensuse", Distro.opensuse }, .{ "opensuse-tumbleweed", Distro.opensuse }, .{ "opensuse-leap", Distro.opensuse }, .{ "suse", Distro.opensuse }, .{ "sles", Distro.opensuse } };
+ inline for (entries) |entry| if (std.mem.eql(u8, id, entry[0])) return entry[1];
+ return null;
+}
+
+/// ID takes precedence over ID_LIKE; derivatives with no ID_LIKE (Artix) are
+/// recognized explicitly. ID_LIKE is an ordered list, never a substring match.
+pub fn parse(a: A, bytes: []const u8) !Info {
+ if (bytes.len > 65536 or std.mem.indexOfScalar(u8, bytes, 0) != null) return error.InvalidOsRelease;
+ var id: []const u8 = "";
+ var like: []const u8 = "";
+ var lines = std.mem.splitScalar(u8, bytes, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0 or line[0] == '#') continue;
+ const separator = std.mem.indexOfScalar(u8, line, '=') orelse continue;
+ const key = line[0..separator];
+ if (std.mem.eql(u8, key, "ID")) {
+ id = try value(line[separator + 1 ..]);
+ if (!validId(id)) return error.InvalidOsRelease;
+ } else if (std.mem.eql(u8, key, "ID_LIKE")) {
+ like = try value(line[separator + 1 ..]);
+ var tokens = std.mem.tokenizeAny(u8, like, " \t");
+ while (tokens.next()) |token| if (!validId(token)) return error.InvalidOsRelease;
+ }
+ }
+ var distro = exact(id) orelse Distro.generic;
+ if (distro == .generic) {
+ var tokens = std.mem.tokenizeAny(u8, like, " \t");
+ while (tokens.next()) |token| if (exact(token)) |known| {
+ distro = known;
+ break;
+ };
+ }
+ var info: Info = .{ .distro = distro };
+ info.id = try a.dupe(u8, id);
+ errdefer a.free(info.id);
+ info.id_like = try a.dupe(u8, like);
+ info.missing_cups = switch (distro) {
+ .arch, .cachyos => "Install the cups package with your distribution's package manager, then start the CUPS print service. RediWM does not install it automatically.",
+ .artix => "Install the cups package and your init system's CUPS service package, then start that service. Artix does not use systemd.",
+ .debian, .ubuntu => "Install the cups package with your distribution's package manager, then start the CUPS print service.",
+ .fedora => "Install the cups package with your distribution's package manager, then start the CUPS print service.",
+ .opensuse => "Install the cups package using your distribution's package manager, then start the CUPS print service. openSUSE release qualification is still pending.",
+ .generic => info.missing_cups,
+ };
+ info.missing_helper = switch (distro) {
+ .arch, .cachyos, .artix => "Install the optional cups-pk-helper package for authorized printer setup and configuration. Printing and user-level status do not require it.",
+ .debian, .ubuntu => "Install the optional cups-pk-helper package for authorized printer setup and configuration. Printing and user-level status do not require it.",
+ .fedora => "Install the optional cups-pk-helper package for authorized printer setup and configuration. Printing and user-level status do not require it.",
+ .opensuse => "Look for the optional cups-pk-helper package in your openSUSE repositories. Availability and authorization depend on the release and local policy.",
+ .generic => info.missing_helper,
+ };
+ return info;
+}
+
+/// Testable filesystem probe. Only stat conventional cupsd paths under root.
+pub fn daemonInstalled(a: A, io: Io, root: []const u8) !?bool {
+ var inaccessible = false;
+ for ([_][]const u8{ "usr/sbin/cupsd", "usr/bin/cupsd", "sbin/cupsd" }) |relative| {
+ const candidate = try std.fs.path.join(a, &.{ root, relative });
+ defer a.free(candidate);
+ const stat = Io.Dir.cwd().statFile(io, candidate, .{}) catch |err| switch (err) {
+ error.FileNotFound, error.NotDir => continue,
+ else => {
+ inaccessible = true;
+ continue;
+ },
+ };
+ if (stat.kind == .file and stat.permissions.toMode() & 0o111 != 0) return true;
+ }
+ return if (inaccessible) null else false;
+}
+
+pub fn load(a: A, io: Io) !Info {
+ const bytes = Io.Dir.cwd().readFileAlloc(io, "/etc/os-release", a, .limited(65536)) catch |err| switch (err) {
+ error.FileNotFound => Io.Dir.cwd().readFileAlloc(io, "/usr/lib/os-release", a, .limited(65536)) catch |fallback_err| switch (fallback_err) {
+ error.FileNotFound => try a.dupe(u8, ""),
+ else => return fallback_err,
+ },
+ else => return err,
+ };
+ defer a.free(bytes);
+ var info = try parse(a, bytes);
+ errdefer info.deinit(a);
+ info.daemon_installed = try daemonInstalled(a, io, "/");
+ return info;
+}
+
+test "distro detection uses exact ID then ordered ID_LIKE and handles Artix without systemd" {
+ const a = std.testing.allocator;
+ const cases = .{ .{ "ID=artix\n", Distro.artix }, .{ "ID=cachyos\nID_LIKE=arch\n", Distro.cachyos }, .{ "ID=ubuntu\nID_LIKE=debian\n", Distro.ubuntu }, .{ "ID=linuxmint\nID_LIKE=\"ubuntu debian\"\n", Distro.ubuntu }, .{ "ID=custom\nID_LIKE='notarch fedora'\n", Distro.fedora }, .{ "ID=opensuse-tumbleweed\n", Distro.opensuse }, .{ "ID=custom\nID_LIKE=notarch\n", Distro.generic } };
+ inline for (cases) |case| {
+ var info = try parse(a, case[0]);
+ defer info.deinit(a);
+ try std.testing.expectEqual(case[1], info.distro);
+ }
+ var artix = try parse(a, "ID=artix\n");
+ defer artix.deinit(a);
+ try std.testing.expect(std.mem.indexOf(u8, artix.missing_cups, "init system") != null);
+}
+
+test "os-release never executes or accepts interpolation and rejects malformed identifiers" {
+ for ([_][]const u8{ "ID=\"$(touch /tmp/never)\"\n", "ID=\"arch\n", "ID=arch\x00\n", "ID_LIKE=\"arch;evil\"\n", "ID=Arch\n" }) |bytes| try std.testing.expectError(error.InvalidOsRelease, parse(std.testing.allocator, bytes));
+}
+
+test "daemon probe distinguishes a regular executable from a directory or plain file" {
+ const a = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", a);
+ defer a.free(root);
+ try std.testing.expectEqual(@as(?bool, false), try daemonInstalled(a, io, root));
+ try tmp.dir.createDirPath(io, "usr/sbin");
+ try tmp.dir.writeFile(io, .{ .sub_path = "usr/sbin/cupsd", .data = "fixture" });
+ try std.testing.expectEqual(@as(?bool, false), try daemonInstalled(a, io, root));
+ try tmp.dir.setFilePermissions(io, "usr/sbin/cupsd", .fromMode(0o700), .{});
+ try std.testing.expectEqual(@as(?bool, true), try daemonInstalled(a, io, root));
+}
diff --git a/src/printing/preferences.zig b/src/printing/preferences.zig
new file mode 100644
index 0000000..17c0a4b
--- /dev/null
+++ b/src/printing/preferences.zig
@@ -0,0 +1,313 @@
+//! Per-user CUPS destination and bounded private diagnostic observations.
+//! All filesystem roots and environment values are passed by the caller.
+const std = @import("std");
+const tools = @import("tools.zig");
+const ipp = @import("ipp.zig");
+const A = std.mem.Allocator;
+const Io = std.Io;
+const max_bytes = 256 * 1024;
+
+pub fn validQueue(queue: []const u8) bool {
+ if (queue.len == 0 or queue.len > 127 or !std.unicode.utf8ValidateSlice(queue)) return false;
+ for (queue) |ch| if (ch <= 0x20 or ch == 0x7f or ch == '/' or ch == '#' or ch == '?' or ch == '\\' or ch == '\"' or ch == '\'') return false;
+ return true;
+}
+
+fn path(a: A, env: std.process.Environ, suffix: []const u8) ![]u8 {
+ const home = env.getPosix("HOME") orelse return error.NoHomeDirectory;
+ if (!std.fs.path.isAbsolute(home)) return error.InvalidHomeDirectory;
+ return std.fs.path.join(a, &.{ home, suffix });
+}
+
+fn read(a: A, io: Io, file_path: []const u8, limit: usize) ![]u8 {
+ return Io.Dir.cwd().readFileAlloc(io, file_path, a, .limited(limit)) catch |err| switch (err) {
+ error.FileNotFound => a.dupe(u8, ""),
+ else => return err,
+ };
+}
+
+const Line = struct { keyword: []const u8, name: []const u8, keyword_start: usize, keyword_end: usize };
+fn destination(line: []const u8) ?Line {
+ var tokens = std.mem.tokenizeAny(u8, line, " \t\r\n");
+ const keyword = tokens.next() orelse return null;
+ if (!std.ascii.eqlIgnoreCase(keyword, "Default") and !std.ascii.eqlIgnoreCase(keyword, "Dest")) return null;
+ const name = tokens.next() orelse return null;
+ const start: usize = @intFromPtr(keyword.ptr) - @intFromPtr(line.ptr);
+ return .{ .keyword = keyword, .name = name, .keyword_start = start, .keyword_end = start + keyword.len };
+}
+
+/// Preserve options (including quoted and escaped values), instances, comments,
+/// unrelated directives, whitespace and newline style. Demote old Default lines
+/// to Dest; promote an existing exact queue line so its options remain attached.
+pub fn patchDefault(a: A, original: []const u8, queue: []const u8) ![]u8 {
+ if (!validQueue(queue)) return error.InvalidQueueName;
+ if (original.len > max_bytes or std.mem.indexOfScalar(u8, original, 0) != null) return error.InvalidPreferences;
+ var out: std.Io.Writer.Allocating = .init(a);
+ defer out.deinit();
+ var offset: usize = 0;
+ var found = false;
+ while (offset < original.len) {
+ const end = if (std.mem.indexOfScalarPos(u8, original, offset, '\n')) |n| n + 1 else original.len;
+ const line = original[offset..end];
+ if (destination(line)) |dest| {
+ const selected = std.mem.eql(u8, std.mem.trimEnd(u8, dest.name, "\n"), queue);
+ if (selected and found) return error.AmbiguousPreferences;
+ if (selected) found = true;
+ if (selected or std.ascii.eqlIgnoreCase(dest.keyword, "Default")) {
+ try out.writer.writeAll(line[0..dest.keyword_start]);
+ try out.writer.writeAll(if (selected) "Default" else "Dest");
+ try out.writer.writeAll(line[dest.keyword_end..]);
+ } else try out.writer.writeAll(line);
+ } else try out.writer.writeAll(line);
+ offset = end;
+ }
+ if (!found) {
+ if (original.len != 0 and original[original.len - 1] != '\n') try out.writer.writeByte('\n');
+ try out.writer.print("Default {s}\n", .{queue});
+ }
+ return out.toOwnedSlice();
+}
+
+/// A queue's instances use the same base identity (Queue/photo). Only the
+/// destination token changes; options, comments and formatting remain bytes.
+pub fn patchRename(a: A, original: []const u8, old: []const u8, new: []const u8) ![]u8 {
+ if (!validQueue(old) or !validQueue(new)) return error.InvalidQueueName;
+ if (original.len > max_bytes or std.mem.indexOfScalar(u8, original, 0) != null) return error.InvalidPreferences;
+ if (std.mem.eql(u8, old, new)) return a.dupe(u8, original);
+ if (std.ascii.eqlIgnoreCase(old, new)) return error.InvalidQueueName;
+ var out: Io.Writer.Allocating = .init(a);
+ defer out.deinit();
+ var offset: usize = 0;
+ while (offset < original.len) {
+ const end = if (std.mem.indexOfScalarPos(u8, original, offset, '\n')) |n| n + 1 else original.len;
+ const line = original[offset..end];
+ if (destination(line)) |dest| {
+ const slash = std.mem.indexOfScalar(u8, dest.name, '/') orelse dest.name.len;
+ const base = dest.name[0..slash];
+ if (std.ascii.eqlIgnoreCase(base, new)) return error.QueuePreferencesExist;
+ if (std.ascii.eqlIgnoreCase(base, old)) {
+ const start: usize = @intFromPtr(dest.name.ptr) - @intFromPtr(line.ptr);
+ out.writer.writeAll(line[0..start]) catch return error.OutOfMemory;
+ out.writer.writeAll(new) catch return error.OutOfMemory;
+ out.writer.writeAll(line[start + base.len ..]) catch return error.OutOfMemory;
+ } else out.writer.writeAll(line) catch return error.OutOfMemory;
+ } else out.writer.writeAll(line) catch return error.OutOfMemory;
+ if (out.written().len > max_bytes) return error.TooLarge;
+ offset = end;
+ }
+ return out.toOwnedSlice();
+}
+
+pub fn defaultPrinter(a: A, io: Io, env: std.process.Environ) !?[]u8 {
+ if (env.getPosix("LPDEST")) |value| if (value.len != 0) return try a.dupe(u8, value);
+ if (env.getPosix("PRINTER")) |value| if (value.len != 0 and !std.mem.eql(u8, value, "lp")) return try a.dupe(u8, value);
+ const file_path = try path(a, env, ".cups/lpoptions");
+ defer a.free(file_path);
+ const bytes = try read(a, io, file_path, max_bytes);
+ defer a.free(bytes);
+ var lines = std.mem.splitScalar(u8, bytes, '\n');
+ var result: ?[]const u8 = null;
+ while (lines.next()) |line| {
+ const dest = destination(line) orelse continue;
+ if (std.ascii.eqlIgnoreCase(dest.keyword, "Default")) result = dest.name;
+ }
+ return if (result) |name| try a.dupe(u8, name) else null;
+}
+
+pub fn overrideMessage(env: std.process.Environ) ?[]const u8 {
+ if (env.getPosix("LPDEST")) |value| if (value.len != 0) return "LPDEST currently overrides the saved default printer.";
+ if (env.getPosix("PRINTER")) |value| if (value.len != 0 and !std.mem.eql(u8, value, "lp")) return "PRINTER currently overrides the saved default printer.";
+ return null;
+}
+
+fn atomicSave(a: A, io: Io, file_path: []const u8, original: []const u8, bytes: []const u8) !void {
+ const parent = std.fs.path.dirname(file_path) orelse return error.InvalidPath;
+ _ = try Io.Dir.cwd().createDirPathStatus(io, parent, .fromMode(0o700));
+ var file = try Io.Dir.cwd().createFileAtomic(io, file_path, .{ .permissions = .fromMode(0o600), .replace = true });
+ defer file.deinit(io);
+ try file.file.writeStreamingAll(io, bytes);
+ try file.file.sync(io);
+ // Another application can also write lpoptions; refuse a detected change
+ // rather than replacing its options from an obsolete read.
+ const check = try read(a, io, file_path, max_bytes);
+ defer a.free(check);
+ if (!std.mem.eql(u8, original, check)) return error.PreferencesChanged;
+ try file.replace(io);
+}
+
+fn atomicCreate(io: Io, file_path: []const u8, bytes: []const u8) !Io.File.Stat {
+ const parent = std.fs.path.dirname(file_path) orelse return error.InvalidPath;
+ _ = try Io.Dir.cwd().createDirPathStatus(io, parent, .fromMode(0o700));
+ var file = try Io.Dir.cwd().createFileAtomic(io, file_path, .{ .permissions = .fromMode(0o600) });
+ defer file.deinit(io);
+ try file.file.writeStreamingAll(io, bytes);
+ try file.file.sync(io);
+ const stat = try file.file.stat(io);
+ file.link(io) catch |err| switch (err) {
+ error.PathAlreadyExists => return error.QueuePreferencesExist,
+ else => return err,
+ };
+ return stat;
+}
+
+fn fileStat(io: Io, file_path: []const u8) !?Io.File.Stat {
+ return Io.Dir.cwd().statFile(io, file_path, .{ .follow_symlinks = false }) catch |err| switch (err) {
+ error.FileNotFound => null,
+ else => return err,
+ };
+}
+
+fn discardCreated(a: A, io: Io, file_path: []const u8, created: Io.File.Stat, bytes: []const u8) void {
+ const stat = (fileStat(io, file_path) catch return) orelse return;
+ if (stat.kind != .file or stat.inode != created.inode or stat.size != created.size or !std.meta.eql(stat.mtime, created.mtime)) return;
+ const current = read(a, io, file_path, 4096) catch return;
+ defer a.free(current);
+ if (std.mem.eql(u8, current, bytes)) Io.Dir.cwd().deleteFile(io, file_path) catch {};
+}
+
+/// Invoke only after a fresh scheduler inventory confirms old absent/new
+/// present. Files are committed separately: create private new-state first,
+/// update lpoptions second. Neither an existing destination nor existing new
+/// state is merged/replaced. Keep old-state as a harmless recovery copy.
+pub fn renameQueue(a: A, io: Io, env: std.process.Environ, old: []const u8, new: []const u8) !void {
+ if (!validQueue(old) or !validQueue(new)) return error.InvalidQueueName;
+ if (std.mem.eql(u8, old, new)) return;
+ const options_path = try path(a, env, ".cups/lpoptions");
+ defer a.free(options_path);
+ const original = try read(a, io, options_path, max_bytes);
+ defer a.free(original);
+ const patched = try patchRename(a, original, old, new);
+ defer a.free(patched);
+ const old_state = try statePath(a, env, old);
+ defer a.free(old_state);
+ const new_state = try statePath(a, env, new);
+ defer a.free(new_state);
+ if (try fileStat(io, new_state) != null) return error.QueuePreferencesExist;
+ const old_stat = try fileStat(io, old_state);
+ if (old_stat) |stat| if (stat.kind != .file) return error.InvalidPreferences;
+ const state_bytes = if (old_stat != null) try read(a, io, old_state, 4096) else try a.dupe(u8, "");
+ defer a.free(state_bytes);
+ if (old_stat != null) _ = try parseState(state_bytes);
+ var created: ?Io.File.Stat = null;
+ var committed = false;
+ defer if (!committed) if (created) |stat| discardCreated(a, io, new_state, stat, state_bytes);
+ if (old_stat != null) created = try atomicCreate(io, new_state, state_bytes);
+ if (!std.mem.eql(u8, original, patched)) try atomicSave(a, io, options_path, original, patched);
+ committed = true;
+}
+
+pub fn setDefault(a: A, io: Io, env: std.process.Environ, queue: []const u8) !void {
+ const file_path = try path(a, env, ".cups/lpoptions");
+ defer a.free(file_path);
+ const original = try read(a, io, file_path, max_bytes);
+ defer a.free(original);
+ const bytes = try patchDefault(a, original, queue);
+ defer a.free(bytes);
+ try atomicSave(a, io, file_path, original, bytes);
+}
+
+pub const Outcome = enum { unknown, printed, no_output };
+pub const UserState = struct {
+ label: bool = false,
+ language: ?tools.Language = null,
+ expected_media: ?tools.Media = null,
+ driver: Outcome = .unknown,
+ raw: Outcome = .unknown,
+ ruler: Outcome = .unknown,
+ /// The queue resolution that produced the measured physical rectangle.
+ /// Calibration must not reinterpret an old ruler at a later queue DPI.
+ ruler_resolution: ?ipp.Resolution = null,
+};
+
+fn statePath(a: A, env: std.process.Environ, queue: []const u8) ![]u8 {
+ if (!validQueue(queue)) return error.InvalidQueueName;
+ var hash: [32]u8 = undefined;
+ std.crypto.hash.sha2.Sha256.hash(queue, &hash, .{});
+ const filename = try std.fmt.allocPrint(a, "{s}.state", .{std.fmt.bytesToHex(hash, .lower)});
+ defer a.free(filename);
+ if (env.getPosix("XDG_STATE_HOME")) |root| {
+ if (!std.fs.path.isAbsolute(root)) return error.InvalidStateDirectory;
+ return std.fs.path.join(a, &.{ root, "rediwm/printers", filename });
+ }
+ const root = try path(a, env, ".local/state/rediwm/printers");
+ defer a.free(root);
+ return std.fs.path.join(a, &.{ root, filename });
+}
+
+pub fn parseState(bytes: []const u8) !UserState {
+ if (bytes.len == 0) return .{};
+ if (bytes.len > 4096) return error.InvalidPreferences;
+ var lines = std.mem.splitScalar(u8, bytes, '\n');
+ if (!std.mem.eql(u8, lines.next() orelse "", "rediwm-printer-state 1")) return error.InvalidPreferences;
+ var state: UserState = .{};
+ var width: ?f64 = null;
+ var height: ?f64 = null;
+ while (lines.next()) |line| {
+ if (line.len == 0) continue;
+ const sep = std.mem.indexOfScalar(u8, line, ' ') orelse return error.InvalidPreferences;
+ const key = line[0..sep];
+ const value = line[sep + 1 ..];
+ if (std.mem.eql(u8, key, "label")) {
+ state.label = if (std.mem.eql(u8, value, "1")) true else if (std.mem.eql(u8, value, "0")) false else return error.InvalidPreferences;
+ } else if (std.mem.eql(u8, key, "language")) {
+ state.language = std.meta.stringToEnum(tools.Language, value) orelse return error.InvalidPreferences;
+ } else if (std.mem.eql(u8, key, "width-mm")) {
+ width = std.fmt.parseFloat(f64, value) catch return error.InvalidPreferences;
+ } else if (std.mem.eql(u8, key, "height-mm")) {
+ height = std.fmt.parseFloat(f64, value) catch return error.InvalidPreferences;
+ } else if (std.mem.eql(u8, key, "driver")) {
+ state.driver = std.meta.stringToEnum(Outcome, value) orelse return error.InvalidPreferences;
+ } else if (std.mem.eql(u8, key, "raw")) {
+ state.raw = std.meta.stringToEnum(Outcome, value) orelse return error.InvalidPreferences;
+ } else if (std.mem.eql(u8, key, "ruler")) {
+ state.ruler = std.meta.stringToEnum(Outcome, value) orelse return error.InvalidPreferences;
+ } else if (std.mem.eql(u8, key, "ruler-resolution")) {
+ var tokens = std.mem.tokenizeScalar(u8, value, ' ');
+ const x = std.fmt.parseInt(i32, tokens.next() orelse return error.InvalidPreferences, 10) catch return error.InvalidPreferences;
+ const y = std.fmt.parseInt(i32, tokens.next() orelse return error.InvalidPreferences, 10) catch return error.InvalidPreferences;
+ const units = tokens.next() orelse return error.InvalidPreferences;
+ if (tokens.next() != null) return error.InvalidPreferences;
+ const resolution: ipp.Resolution = .{ .x = x, .y = y, .units = if (std.mem.eql(u8, units, "dpi")) .dpi else if (std.mem.eql(u8, units, "dpcm")) .dpcm else return error.InvalidPreferences };
+ _ = tools.dpiValue(resolution) orelse return error.InvalidPreferences;
+ state.ruler_resolution = resolution;
+ }
+ }
+ if (width != null or height != null) {
+ const media: tools.Media = .{ .width_mm = width orelse return error.InvalidPreferences, .height_mm = height orelse return error.InvalidPreferences };
+ if (!media.valid()) return error.InvalidPreferences;
+ state.expected_media = media;
+ }
+ return state;
+}
+
+pub fn loadState(a: A, io: Io, env: std.process.Environ, queue: []const u8) !UserState {
+ const file_path = try statePath(a, env, queue);
+ defer a.free(file_path);
+ const bytes = try read(a, io, file_path, 4096);
+ defer a.free(bytes);
+ return parseState(bytes);
+}
+
+pub fn saveState(a: A, io: Io, env: std.process.Environ, queue: []const u8, state: UserState) !void {
+ const file_path = try statePath(a, env, queue);
+ defer a.free(file_path);
+ const original = try read(a, io, file_path, 4096);
+ defer a.free(original);
+ var out: Io.Writer.Allocating = .init(a);
+ defer out.deinit();
+ try out.writer.print("rediwm-printer-state 1\nlabel {d}\ndriver {s}\nraw {s}\nruler {s}\n", .{ @intFromBool(state.label), @tagName(state.driver), @tagName(state.raw), @tagName(state.ruler) });
+ if (state.language) |language| try out.writer.print("language {s}\n", .{@tagName(language)});
+ if (state.expected_media) |media| {
+ if (!media.valid()) return error.InvalidMedia;
+ try out.writer.print("width-mm {d:.4}\nheight-mm {d:.4}\n", .{ media.width_mm, media.height_mm });
+ }
+ if (state.ruler_resolution) |resolution| {
+ _ = tools.dpiValue(resolution) orelse return error.InvalidPreferences;
+ try out.writer.print("ruler-resolution {d} {d} {s}\n", .{ resolution.x, resolution.y, @tagName(resolution.units) });
+ }
+ try atomicSave(a, io, file_path, original, out.written());
+}
+
+test {
+ _ = @import("preferences_tests.zig");
+}
diff --git a/src/printing/preferences_tests.zig b/src/printing/preferences_tests.zig
new file mode 100644
index 0000000..742151f
--- /dev/null
+++ b/src/printing/preferences_tests.zig
@@ -0,0 +1,164 @@
+const std = @import("std");
+const prefs = @import("preferences.zig");
+const a = std.testing.allocator;
+
+test "setting default preserves queue options, other destinations, instances and comments" {
+ const original = "# retain this\nDefault Old media=A4\n Dest New media=Custom\\ Size note=\"keep quoted\"\r\nDest New/photo quality=5\nUnknown verbatim\n";
+ const patched = try prefs.patchDefault(a, original, "New");
+ defer a.free(patched);
+ try std.testing.expectEqualStrings("# retain this\nDest Old media=A4\n Default New media=Custom\\ Size note=\"keep quoted\"\r\nDest New/photo quality=5\nUnknown verbatim\n", patched);
+ const twice = try prefs.patchDefault(a, patched, "New");
+ defer a.free(twice);
+ try std.testing.expectEqualStrings(patched, twice);
+ const appended = try prefs.patchDefault(a, "# no newline", "Printer");
+ defer a.free(appended);
+ try std.testing.expectEqualStrings("# no newline\nDefault Printer\n", appended);
+ try std.testing.expectError(error.InvalidQueueName, prefs.patchDefault(a, original, "New\nDefault Injected"));
+ try std.testing.expectError(error.AmbiguousPreferences, prefs.patchDefault(a, "Dest A x=1\nDest A y=2\n", "A"));
+}
+
+test "private queue state has bounded typed values and rejects malformed media" {
+ const state = try prefs.parseState("rediwm-printer-state 1\nlabel 1\nlanguage tspl\nwidth-mm 101.6\nheight-mm 152.4\ndriver no_output\nraw printed\n");
+ try std.testing.expect(state.label);
+ try std.testing.expectEqual(.tspl, state.language.?);
+ try std.testing.expectEqual(.no_output, state.driver);
+ try std.testing.expectEqual(.printed, state.raw);
+ try std.testing.expectEqual(.unknown, state.ruler);
+ try std.testing.expectEqual(@as(?@import("ipp.zig").Resolution, null), state.ruler_resolution);
+ try std.testing.expectError(error.InvalidPreferences, prefs.parseState("rediwm-printer-state 1\nwidth-mm nan\nheight-mm 152.4\n"));
+ try std.testing.expectError(error.InvalidPreferences, prefs.parseState("rediwm-printer-state 1\nwidth-mm 100\n"));
+ try std.testing.expectError(error.InvalidPreferences, prefs.parseState("rediwm-printer-state 1\nlanguage arbitrary\n"));
+ const ruler = try prefs.parseState("rediwm-printer-state 1\nruler printed\nruler-resolution 80 118 dpcm\n");
+ try std.testing.expectEqual(@import("ipp.zig").Resolution{ .x = 80, .y = 118, .units = .dpcm }, ruler.ruler_resolution.?);
+ for ([_][]const u8{ "0 300 dpi", "300 -1 dpi", "300 300 unknown", "300 300 dpi extra", "300 dpi", "2147483647 300 dpi", "300 nan dpi" }) |invalid| {
+ const bytes = try std.fmt.allocPrint(a, "rediwm-printer-state 1\nruler-resolution {s}\n", .{invalid});
+ defer a.free(bytes);
+ try std.testing.expectError(error.InvalidPreferences, prefs.parseState(bytes));
+ }
+}
+
+test "preference persistence uses only explicit temporary HOME and survives a reload" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", a);
+ defer a.free(root);
+ const home_entry = try std.fmt.allocPrintSentinel(a, "HOME={s}", .{root}, 0);
+ defer a.free(home_entry);
+ const block: [:null]const ?[*:0]const u8 = &.{home_entry};
+ const env: std.process.Environ = .{ .block = .{ .slice = block } };
+ try tmp.dir.createDirPath(io, ".cups");
+ try tmp.dir.writeFile(io, .{ .sub_path = ".cups/lpoptions", .data = "Default Old x=1\nDest New y=2\n" });
+ try prefs.setDefault(a, io, env, "New");
+ const selected = (try prefs.defaultPrinter(a, io, env)).?;
+ defer a.free(selected);
+ try std.testing.expectEqualStrings("New", selected);
+ const written = try tmp.dir.readFileAlloc(io, ".cups/lpoptions", a, .limited(4096));
+ defer a.free(written);
+ try std.testing.expectEqualStrings("Dest Old x=1\nDefault New y=2\n", written);
+ const state: prefs.UserState = .{ .label = true, .language = .tspl, .expected_media = .{ .width_mm = 101.6, .height_mm = 152.4 }, .raw = .printed, .ruler_resolution = .{ .x = 203, .y = 300, .units = .dpi } };
+ try prefs.saveState(a, io, env, "New", state);
+ const loaded = try prefs.loadState(a, io, env, "New");
+ try std.testing.expectEqualDeep(state, loaded);
+ const dpcm_state: prefs.UserState = .{ .ruler = .printed, .ruler_resolution = .{ .x = 80, .y = 118, .units = .dpcm } };
+ try prefs.saveState(a, io, env, "New", dpcm_state);
+ try std.testing.expectEqualDeep(dpcm_state, try prefs.loadState(a, io, env, "New"));
+ const absent = try prefs.loadState(a, io, env, "Other");
+ try std.testing.expectEqualDeep(prefs.UserState{}, absent);
+}
+
+test "environment default overrides are honoured and explained" {
+ const block: [:null]const ?[*:0]const u8 = &.{ "LPDEST=EnvChoice", "PRINTER=Other" };
+ const env: std.process.Environ = .{ .block = .{ .slice = block } };
+ const selected = (try prefs.defaultPrinter(a, std.testing.io, env)).?;
+ defer a.free(selected);
+ try std.testing.expectEqualStrings("EnvChoice", selected);
+ try std.testing.expect(prefs.overrideMessage(env) != null);
+}
+
+test "queue rename preserves destination instances options comments and exact formatting" {
+ const original = "# Old is retained in comments\r\nDefault Old media=A4\r\n dEsT oLd/photo note=\"Old stays in options\" paper=Custom\\ Size\nDest OldExtra media=A5\nUnknown Old\nDest Other quality=5";
+ const renamed = try prefs.patchRename(a, original, "Old", "New");
+ defer a.free(renamed);
+ try std.testing.expectEqualStrings("# Old is retained in comments\r\nDefault New media=A4\r\n dEsT New/photo note=\"Old stays in options\" paper=Custom\\ Size\nDest OldExtra media=A5\nUnknown Old\nDest Other quality=5", renamed);
+ try std.testing.expectError(error.QueuePreferencesExist, prefs.patchRename(a, "Dest Old x=1\nDest nEw/photo x=2\n", "Old", "New"));
+ try std.testing.expectError(error.QueuePreferencesExist, prefs.patchRename(a, "Default New\n", "Old", "New"));
+ try std.testing.expectError(error.InvalidQueueName, prefs.patchRename(a, original, "Old", "Invalid\nInjected"));
+ const untouched = try prefs.patchRename(a, "# absent\nDest Other/photo media=A4\n", "Old", "New");
+ defer a.free(untouched);
+ try std.testing.expectEqualStrings("# absent\nDest Other/photo media=A4\n", untouched);
+}
+
+test "renaming a queue migrates private observations and the per-user default under temporary HOME" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", a);
+ defer a.free(root);
+ const home_entry = try std.fmt.allocPrintSentinel(a, "HOME={s}", .{root}, 0);
+ defer a.free(home_entry);
+ const env: std.process.Environ = .{ .block = .{ .slice = &.{home_entry} } };
+ const state: prefs.UserState = .{ .label = true, .language = .tspl, .expected_media = .{ .width_mm = 101.6, .height_mm = 152.4 }, .driver = .no_output, .raw = .printed };
+ try prefs.saveState(a, io, env, "Old", state);
+ try tmp.dir.createDirPath(io, ".cups");
+ try tmp.dir.writeFile(io, .{ .sub_path = ".cups/lpoptions", .data = "# retain\nDefault Old custom=\"preserve value\"\nDest Old/photo quality=5\nDest Other media=A4\n" });
+ try prefs.renameQueue(a, io, env, "Old", "New");
+ try std.testing.expectEqualDeep(state, try prefs.loadState(a, io, env, "New"));
+ // Keeping the old observation file is deliberate recovery protection.
+ try std.testing.expectEqualDeep(state, try prefs.loadState(a, io, env, "Old"));
+ const selected = (try prefs.defaultPrinter(a, io, env)).?;
+ defer a.free(selected);
+ try std.testing.expectEqualStrings("New", selected);
+ const written = try tmp.dir.readFileAlloc(io, ".cups/lpoptions", a, .limited(4096));
+ defer a.free(written);
+ try std.testing.expectEqualStrings("# retain\nDefault New custom=\"preserve value\"\nDest New/photo quality=5\nDest Other media=A4\n", written);
+}
+
+test "rename collision preflight preserves both sets of preferences and never merges them" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", a);
+ defer a.free(root);
+ const home_entry = try std.fmt.allocPrintSentinel(a, "HOME={s}", .{root}, 0);
+ defer a.free(home_entry);
+ const env: std.process.Environ = .{ .block = .{ .slice = &.{home_entry} } };
+ const old: prefs.UserState = .{ .label = true, .language = .tspl };
+ const new: prefs.UserState = .{ .raw = .printed, .language = .zpl };
+ try prefs.saveState(a, io, env, "Old", old);
+ try prefs.saveState(a, io, env, "New", new);
+ try tmp.dir.createDirPath(io, ".cups");
+ const original = "Default Old copies=2\n";
+ try tmp.dir.writeFile(io, .{ .sub_path = ".cups/lpoptions", .data = original });
+ try std.testing.expectError(error.QueuePreferencesExist, prefs.renameQueue(a, io, env, "Old", "New"));
+ try std.testing.expectEqualDeep(new, try prefs.loadState(a, io, env, "New"));
+ try std.testing.expectEqualDeep(old, try prefs.loadState(a, io, env, "Old"));
+ const written = try tmp.dir.readFileAlloc(io, ".cups/lpoptions", a, .limited(4096));
+ defer a.free(written);
+ try std.testing.expectEqualStrings(original, written);
+ try tmp.dir.writeFile(io, .{ .sub_path = ".cups/lpoptions", .data = "Default Old copies=2\nDest Third/photo quality=5\n" });
+ try std.testing.expectError(error.QueuePreferencesExist, prefs.renameQueue(a, io, env, "Old", "Third"));
+ try std.testing.expectEqualDeep(prefs.UserState{}, try prefs.loadState(a, io, env, "Third"));
+}
+
+test "queue rename without observations neither invents state nor changes unrelated defaults" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", a);
+ defer a.free(root);
+ const home_entry = try std.fmt.allocPrintSentinel(a, "HOME={s}", .{root}, 0);
+ defer a.free(home_entry);
+ const env: std.process.Environ = .{ .block = .{ .slice = &.{home_entry} } };
+ try prefs.renameQueue(a, io, env, "Old", "New");
+ try std.testing.expectEqualDeep(prefs.UserState{}, try prefs.loadState(a, io, env, "New"));
+ try std.testing.expectEqual(@as(?[]u8, null), try prefs.defaultPrinter(a, io, env));
+}
+
+fn renameAllocationFailure(mem: std.mem.Allocator) !void {
+ const result = try prefs.patchRename(mem, "Default Old media=A4\nDest Old/photo note=\"preserve\"\n", "Old", "New");
+ defer mem.free(result);
+}
+test "rename patch releases partial output on allocation failure" {
+ try std.testing.checkAllAllocationFailures(a, renameAllocationFailure, .{});
+}
diff --git a/src/printing/setup.zig b/src/printing/setup.zig
new file mode 100644
index 0000000..cfc1386
--- /dev/null
+++ b/src/printing/setup.zig
@@ -0,0 +1,196 @@
+//! Pure setup validation. A discovered backend is evidence from CUPS, never an
+//! arbitrary program, filesystem path, credential-bearing URI or guessed driver.
+const std = @import("std");
+const A = std.mem.Allocator;
+
+pub const max_name = 127;
+pub const max_uri = 8192;
+
+pub fn validName(value: []const u8) bool {
+ if (value.len == 0 or value.len > max_name or !std.unicode.utf8ValidateSlice(value) or std.mem.eql(u8, value, ".") or std.mem.eql(u8, value, "..")) return false;
+ var iter = std.unicode.Utf8View.initUnchecked(value).iterator();
+ while (iter.nextCodepoint()) |cp| {
+ if (cp < 128) {
+ const ch: u8 = @intCast(cp);
+ if (!std.ascii.isAlphanumeric(ch) and ch != '-' and ch != '_' and ch != '.') return false;
+ } else if (cp <= 0x9f or (cp >= 0x202a and cp <= 0x202e) or (cp >= 0x2066 and cp <= 0x2069)) return false;
+ }
+ return true;
+}
+
+pub fn nameExists(value: []const u8, names: []const []const u8) bool {
+ for (names) |name| if (std.ascii.eqlIgnoreCase(value, name)) return true;
+ return false;
+}
+
+/// CUPS queue names are case-insensitive. Explicit suffixes avoid replacing an
+/// existing queue, including when truncating a long model name.
+pub fn uniqueName(a: A, model: []const u8, names: []const []const u8) ![]const u8 {
+ var base: [max_name]u8 = undefined;
+ var len: usize = 0;
+ for (model) |ch| {
+ if (len == base.len) break;
+ if (std.ascii.isAlphanumeric(ch) or ch == '_' or ch == '.' or ch == '-') {
+ base[len] = ch;
+ len += 1;
+ } else if (len > 0 and base[len - 1] != '-') {
+ base[len] = '-';
+ len += 1;
+ }
+ }
+ while (len > 0 and (base[len - 1] == '-' or base[len - 1] == '.')) len -= 1;
+ if (len == 0) {
+ @memcpy(base[0..7], "Printer");
+ len = 7;
+ }
+ if (!nameExists(base[0..len], names)) return a.dupe(u8, base[0..len]);
+ var candidate: [max_name]u8 = undefined;
+ for (2..10000) |suffix| {
+ var ending: [12]u8 = undefined;
+ const tail = try std.fmt.bufPrint(&ending, "-{d}", .{suffix});
+ const prefix_len = @min(len, max_name - tail.len);
+ @memcpy(candidate[0..prefix_len], base[0..prefix_len]);
+ @memcpy(candidate[prefix_len..][0..tail.len], tail);
+ const name = candidate[0 .. prefix_len + tail.len];
+ if (!nameExists(name, names)) return a.dupe(u8, name);
+ }
+ return error.NoUniqueName;
+}
+
+fn validEscapes(value: []const u8) bool {
+ var i: usize = 0;
+ while (i < value.len) : (i += 1) {
+ const ch = value[i];
+ if (ch < 0x21 or ch > 0x7e or ch == '\\' or ch == '#') return false;
+ if (ch != '%') continue;
+ if (i + 2 >= value.len) return false;
+ const high = std.fmt.charToDigit(value[i + 1], 16) catch return false;
+ const low = std.fmt.charToDigit(value[i + 2], 16) catch return false;
+ const decoded: u8 = high * 16 + low;
+ if (decoded < 0x20 or decoded == 0x7f or decoded == '\\') return false;
+ i += 2;
+ }
+ return true;
+}
+
+/// Typed addresses use a fixed network scheme allow-list. Installed USB/vendor
+/// backends require an exact current CUPS discovery match in admin.Manager too.
+/// No resolver, backend executable or network probe runs here.
+pub fn validateUri(uri: []const u8, discovered: bool) !void {
+ if (uri.len == 0 or uri.len > max_uri or !validEscapes(uri)) return error.InvalidUri;
+ if (discovered and std.mem.indexOf(u8, uri, "://") == null) {
+ const colon = std.mem.indexOfScalar(u8, uri, ':') orelse return error.InvalidUri;
+ const backend = uri[0..colon];
+ for ([_][]const u8{ "ipp", "ipps", "socket", "lpd", "usb", "dnssd" }) |standard| if (std.mem.eql(u8, backend, standard)) return error.InvalidUri;
+ if (backend.len == 0 or backend.len > 64 or !std.ascii.isLower(backend[0])) return error.InvalidUri;
+ for (backend) |ch| if (!std.ascii.isLower(ch) and !std.ascii.isDigit(ch) and ch != '-' and ch != '_' and ch != '+') return error.InvalidUri;
+ for ([_][]const u8{ "file", "smb", "smbs", "pdf", "pipe", "exec", "command", "beh", "hpfax", "mailto" }) |forbidden| if (std.mem.eql(u8, backend, forbidden)) return error.UnsupportedScheme;
+ const path = uri[colon + 1 ..];
+ if (path.len < 2 or path[0] != '/' or path[1] == '/' or std.mem.indexOfScalar(u8, path, '@') != null) return error.InvalidUri;
+ return;
+ }
+ const split = std.mem.indexOf(u8, uri, "://") orelse return error.InvalidUri;
+ const scheme = uri[0..split];
+ const network = std.mem.eql(u8, scheme, "ipp") or std.mem.eql(u8, scheme, "ipps") or
+ std.mem.eql(u8, scheme, "socket") or std.mem.eql(u8, scheme, "lpd");
+ if (!network and !(discovered and (std.mem.eql(u8, scheme, "usb") or std.mem.eql(u8, scheme, "dnssd")))) return error.UnsupportedScheme;
+ const rest = uri[split + 3 ..];
+ const authority_end = std.mem.indexOfAny(u8, rest, "/?") orelse rest.len;
+ const authority = rest[0..authority_end];
+ if (authority.len == 0 or std.mem.indexOfScalar(u8, authority, '@') != null) return error.InvalidUri;
+ if (!network) return;
+ // Percent encoding in a network authority can conceal credentials or alter
+ // the host interpreted by a backend. DNS-SD service names are different.
+ if (std.mem.indexOfScalar(u8, authority, '%') != null) return error.InvalidUri;
+ var host = authority;
+ var port: ?[]const u8 = null;
+ if (authority[0] == '[') {
+ const close = std.mem.indexOfScalar(u8, authority, ']') orelse return error.InvalidUri;
+ if (close < 3) return error.InvalidUri;
+ host = authority[1..close];
+ _ = std.Io.net.IpAddress.parseIp6(host, 631) catch return error.InvalidUri;
+ if (close + 1 < authority.len) {
+ if (authority[close + 1] != ':') return error.InvalidUri;
+ port = authority[close + 2 ..];
+ }
+ } else {
+ if (std.mem.indexOfScalar(u8, authority, ':')) |colon| {
+ host = authority[0..colon];
+ port = authority[colon + 1 ..];
+ }
+ if (host.len == 0 or host[0] == '.' or host[host.len - 1] == '-') return error.InvalidUri;
+ for (host) |ch| if (!std.ascii.isAlphanumeric(ch) and ch != '-' and ch != '.') return error.InvalidUri;
+ _ = std.Io.net.HostName.init(host) catch return error.InvalidUri;
+ }
+ if (port) |text| {
+ if (text.len == 0) return error.InvalidUri;
+ for (text) |ch| if (!std.ascii.isDigit(ch)) return error.InvalidUri;
+ if ((std.fmt.parseInt(u16, text, 10) catch return error.InvalidUri) == 0) return error.InvalidUri;
+ }
+}
+
+pub const Ppd = struct {
+ name: []const u8,
+ make_model: []const u8 = "",
+ device_id: []const u8 = "",
+};
+
+fn idField(id: []const u8, keys: []const []const u8) ?[]const u8 {
+ var fields = std.mem.splitScalar(u8, id, ';');
+ var found: ?[]const u8 = null;
+ while (fields.next()) |field| {
+ const colon = std.mem.indexOfScalar(u8, field, ':') orelse continue;
+ const key = std.mem.trim(u8, field[0..colon], " \t");
+ for (keys) |candidate| if (std.ascii.eqlIgnoreCase(key, candidate)) {
+ const value = std.mem.trim(u8, field[colon + 1 ..], " \t");
+ // Conflicting duplicate identity fields are not evidence of a match.
+ if (found) |previous| {
+ if (!std.ascii.eqlIgnoreCase(previous, value)) return null;
+ }
+ found = value;
+ };
+ }
+ if (found) |value| if (value.len > 0) return value;
+ return null;
+}
+
+fn sameDevice(left: []const u8, right: []const u8) bool {
+ const mfg = &.{ "MFG", "MANUFACTURER" };
+ const model = &.{ "MDL", "MODEL" };
+ const lm = idField(left, mfg) orelse return false;
+ const rm = idField(right, mfg) orelse return false;
+ const ld = idField(left, model) orelse return false;
+ const rd = idField(right, model) orelse return false;
+ if (!std.ascii.eqlIgnoreCase(lm, rm) or !std.ascii.eqlIgnoreCase(ld, rd)) return false;
+ const commands = &.{ "CMD", "COMMAND SET" };
+ const lc = idField(left, commands) orelse return true;
+ const rc = idField(right, commands) orelse return true;
+ var left_commands = std.mem.splitScalar(u8, lc, ',');
+ while (left_commands.next()) |left_command| {
+ var right_commands = std.mem.splitScalar(u8, rc, ',');
+ while (right_commands.next()) |right_command| {
+ const l = std.mem.trim(u8, left_command, " \t");
+ const r = std.mem.trim(u8, right_command, " \t");
+ if (l.len > 0 and std.ascii.eqlIgnoreCase(l, r)) return true;
+ }
+ }
+ return false;
+}
+
+/// Only a unique exact IEEE-1284 manufacturer+model match is automatic.
+/// make_model display text, VID:PID and undocumented ppd-match scores are never
+/// used to guess compatibility. Ambiguous candidates require an explicit choice.
+pub fn driverMatch(device_id: []const u8, ppds: []const Ppd) ?usize {
+ if (device_id.len > max_uri) return null;
+ var result: ?usize = null;
+ for (ppds, 0..) |ppd, index| {
+ if (!sameDevice(device_id, ppd.device_id)) continue;
+ if (result != null) return null;
+ result = index;
+ }
+ return result;
+}
+
+test {
+ _ = @import("setup_tests.zig");
+}
diff --git a/src/printing/setup_tests.zig b/src/printing/setup_tests.zig
new file mode 100644
index 0000000..32734bd
--- /dev/null
+++ b/src/printing/setup_tests.zig
@@ -0,0 +1,59 @@
+const std = @import("std");
+const t = std.testing;
+const setup = @import("setup.zig");
+
+test "printer URI allow-list preserves full identity and excludes credential or file backends" {
+ for ([_][]const u8{ "ipp://printer.local/ipp/print", "ipps://print.example:443/ipp/print", "socket://192.0.2.4:9100", "lpd://print.example/queue", "ipp://[2001:db8::4]:631/ipp/print" }) |uri| try setup.validateUri(uri, false);
+ try setup.validateUri("usb://Acme/Label?serial=123", true);
+ try setup.validateUri("dnssd://Office%20Printer._ipp._tcp.local./?uuid=123", true);
+ try setup.validateUri("tspl:/dev/usb/lp0", true);
+ try setup.validateUri("hp:/usb/Printer?serial=123", true);
+ for ([_][]const u8{ "tspl:/dev/usb/lp0", "hp:/usb/Printer?serial=123" }) |uri| {
+ if (setup.validateUri(uri, false)) return error.TestUnexpectedResult else |_| {}
+ }
+ for ([_][]const u8{ "file:/dev/usb/lp0", "pipe:/tmp/x", "exec:/usr/bin/x", "beh:/1/2/3/usb:x", "../backend:/dev/usb/lp0", "tspl:relative", "smb://host/queue" }) |uri| {
+ if (setup.validateUri(uri, true)) return error.TestUnexpectedResult else |_| {}
+ }
+ for ([_][]const u8{ "file:/tmp/output", "smb://host/queue", "https://host/", "usb://Acme/Label", "dnssd://printer._ipp._tcp.local/", "ipp://user:secret@host/print", "ipp://user%40host/print", "ipp://host/print\n", "ipp://host/%0a", "ipp://host/%00", "ipp://host/%7f", "ipp://host/%5cpath", "ipp://host/%", "ipp://host/#fragment", "ipp://host:0/", "ipp://host:65536/", "ipp://:631/", "ipp:///print", "ipp://[x:1]/", "ipp://[::::]/", "ipp://host:abc/", "ipp://host\\other/", "ipp://host/%zz" }) |uri| {
+ if (setup.validateUri(uri, false)) return error.TestUnexpectedResult else |_| {}
+ }
+ var long: [setup.max_uri + 1]u8 = @splat('a');
+ @memcpy(long[0..6], "ipp://");
+ try t.expectError(error.InvalidUri, setup.validateUri(&long, true));
+}
+
+test "queue names never silently collide after normalization truncation or case folding" {
+ try t.expect(setup.validName("Office-Printer_2.1"));
+ try t.expect(setup.validName("Impressora_é"));
+ try t.expect(setup.validName("打印机"));
+ for ([_][]const u8{ "", ".", "..", "queue/name", "name with spaces", "name#tag", "name\n", "-name?" }) |name| try t.expect(!setup.validName(name));
+ const name = try setup.uniqueName(t.allocator, "Office / Printer", &.{ "Office-Printer", "office-printer-2" });
+ defer t.allocator.free(name);
+ try t.expectEqualStrings("Office-Printer-3", name);
+ const fallback = try setup.uniqueName(t.allocator, "../../", &.{"Printer"});
+ defer t.allocator.free(fallback);
+ try t.expectEqualStrings("Printer-2", fallback);
+ const model: [300]u8 = @splat('X');
+ const first = try setup.uniqueName(t.allocator, &model, &.{});
+ defer t.allocator.free(first);
+ const next = try setup.uniqueName(t.allocator, &model, &.{first});
+ defer t.allocator.free(next);
+ try t.expect(setup.validName(next));
+ try t.expect(next.len == setup.max_name);
+ try t.expect(std.mem.endsWith(u8, next, "-2"));
+}
+
+test "driver matching requires unique full manufacturer and model device identity" {
+ const ppds = [_]setup.Ppd{
+ .{ .name = "acme-laser.ppd", .make_model = "Acme Laser 10", .device_id = "MFG:Acme;MDL:Laser 10;CMD:POSTSCRIPT;" },
+ .{ .name = "other.ppd", .make_model = "Acme Laser 10", .device_id = "MFG:Other;MDL:Laser 10;" },
+ };
+ try t.expectEqual(@as(?usize, 0), setup.driverMatch("MANUFACTURER:acme;MODEL:Laser 10;", &ppds));
+ try t.expectEqual(@as(?usize, null), setup.driverMatch("MFG:Acme;MDL:Laser 100;", &ppds));
+ try t.expectEqual(@as(?usize, null), setup.driverMatch("MDL:Laser 10;", &ppds));
+ try t.expectEqual(@as(?usize, null), setup.driverMatch("MFG:Acme;MDL:Laser 10;MODEL:Other;", &ppds));
+ try t.expectEqual(@as(?usize, null), setup.driverMatch("MFG:Acme;MDL:Laser 10;CMD:TSPL;", &ppds));
+ try t.expectEqual(@as(?usize, 0), setup.driverMatch("MFG:Acme;MDL:Laser 10;CMD:PCL,POSTSCRIPT;", &ppds));
+ try t.expectEqual(@as(?usize, null), setup.driverMatch("MFG:Acme;MDL:Laser 10;", &.{ ppds[0], ppds[0] }));
+ try t.expectEqual(@as(?usize, null), setup.driverMatch("Acme Laser 10", &ppds));
+}
diff --git a/src/printing/tests.zig b/src/printing/tests.zig
new file mode 100644
index 0000000..aee059f
--- /dev/null
+++ b/src/printing/tests.zig
@@ -0,0 +1,16 @@
+test {
+ _ = @import("ipp.zig");
+ _ = @import("cups.zig");
+ _ = @import("http.zig");
+ _ = @import("usb_sysfs.zig");
+ _ = @import("ladder.zig");
+ _ = @import("setup.zig");
+ _ = @import("tools.zig");
+ _ = @import("preferences.zig");
+ _ = @import("known_devices.zig");
+ _ = @import("options.zig");
+ _ = @import("platform.zig");
+ _ = @import("daemon_watch.zig");
+ _ = @import("notifier.zig");
+ _ = @import("admin.zig");
+}
diff --git a/src/printing/tools.zig b/src/printing/tools.zig
new file mode 100644
index 0000000..ee0afb8
--- /dev/null
+++ b/src/printing/tools.zig
@@ -0,0 +1,187 @@
+//! Explicit, single-page diagnostic documents. No transport or automatic print.
+//! These tiny language samples are not a print driver or a raster converter.
+const std = @import("std");
+const ipp = @import("ipp.zig");
+const A = std.mem.Allocator;
+
+pub const Language = enum {
+ tspl,
+ zpl,
+ epl,
+ cpcl,
+ pcl,
+ postscript,
+
+ pub fn label(self: Language) []const u8 {
+ return switch (self) {
+ .tspl => "TSPL",
+ .zpl => "ZPL",
+ .epl => "EPL",
+ .cpcl => "CPCL",
+ .pcl => "PCL",
+ .postscript => "PostScript",
+ };
+ }
+};
+
+/// The UI must confirm each language separately and ask about physical output
+/// before offering another. A USB ID or guessed model is not CMD evidence.
+pub const probe_languages = [_]Language{ .tspl, .zpl, .epl, .cpcl, .pcl, .postscript };
+pub const self_test_help = "Check the printer's manual for its self-test procedure (often hold FEED while powering on). The sheet can identify its command language and physical resolution. A wrong language may print literal commands, waste paper, or require a power cycle; send only one confirmed probe at a time.";
+
+/// Only complete IEEE 1284 CMD/COMMAND SET tokens count. Never substring-match
+/// model names, generic language claims in other fields, or a shared VID:PID.
+pub fn detectLanguages(a: A, device_id: []const u8) ![]Language {
+ if (device_id.len > 16384) return error.TooLarge;
+ var result: std.ArrayList(Language) = .empty;
+ errdefer result.deinit(a);
+ var fields = std.mem.splitScalar(u8, device_id, ';');
+ while (fields.next()) |field| {
+ const colon = std.mem.indexOfScalar(u8, field, ':') orelse continue;
+ const key = std.mem.trim(u8, field[0..colon], " \t\r\n");
+ if (!std.ascii.eqlIgnoreCase(key, "CMD") and !std.ascii.eqlIgnoreCase(key, "COMMAND SET")) continue;
+ var tokens = std.mem.tokenizeAny(u8, field[colon + 1 ..], ", \t\r\n");
+ while (tokens.next()) |token| {
+ const language: Language = if (std.ascii.eqlIgnoreCase(token, "TSPL") or std.ascii.eqlIgnoreCase(token, "TSPL2")) .tspl else if (std.ascii.eqlIgnoreCase(token, "ZPL") or std.ascii.eqlIgnoreCase(token, "ZPLII")) .zpl else if (std.ascii.eqlIgnoreCase(token, "EPL") or std.ascii.eqlIgnoreCase(token, "EPL2")) .epl else if (std.ascii.eqlIgnoreCase(token, "CPCL")) .cpcl else if (std.ascii.eqlIgnoreCase(token, "PCL") or std.ascii.eqlIgnoreCase(token, "PCL5") or std.ascii.eqlIgnoreCase(token, "PCL5e") or std.ascii.eqlIgnoreCase(token, "PCL5c")) .pcl else if (std.ascii.eqlIgnoreCase(token, "POSTSCRIPT") or std.ascii.eqlIgnoreCase(token, "POSTSCRIPT2") or std.ascii.eqlIgnoreCase(token, "POSTSCRIPT3")) .postscript else continue;
+ if (std.mem.indexOfScalar(Language, result.items, language) == null) try result.append(a, language);
+ }
+ }
+ return result.toOwnedSlice(a);
+}
+
+pub const Media = struct {
+ width_mm: f64,
+ height_mm: f64,
+
+ pub fn valid(self: Media) bool {
+ return std.math.isFinite(self.width_mm) and std.math.isFinite(self.height_mm) and
+ self.width_mm >= 12.7 and self.height_mm >= 12.7 and self.width_mm <= 1500 and self.height_mm <= 1500;
+ }
+};
+pub const PdfKind = enum { page, ruler };
+pub const ruler_width_mm = 50.8;
+pub const ruler_height_mm = 76.2;
+
+/// PWG media names end in physical dimensions, for example
+/// iso_a4_210x297mm / na_index-4x6_4x6in / custom_label_101.6x152.4mm.
+/// Legacy PPD names have no such guarantee and require the PPD dimensions.
+pub fn mediaFromKeyword(keyword: []const u8) ?Media {
+ if (keyword.len > 255) return null;
+ const suffix = keyword[(std.mem.lastIndexOfScalar(u8, keyword, '_') orelse return null) + 1 ..];
+ const unit: f64 = if (std.mem.endsWith(u8, suffix, "mm")) 1 else if (std.mem.endsWith(u8, suffix, "in")) 25.4 else return null;
+ const dims = suffix[0 .. suffix.len - 2];
+ const x = std.mem.indexOfScalar(u8, dims, 'x') orelse return null;
+ const media: Media = .{
+ .width_mm = (std.fmt.parseFloat(f64, dims[0..x]) catch return null) * unit,
+ .height_mm = (std.fmt.parseFloat(f64, dims[x + 1 ..]) catch return null) * unit,
+ };
+ return if (media.valid()) media else null;
+}
+
+/// Supply actual queue media dimensions, never silently assume Letter/A4.
+/// PDF points are physical 1/72-inch units. Print at 100%, without fit-to-page.
+pub fn testPdf(a: A, media: Media, kind: PdfKind) ![]u8 {
+ if (!media.valid()) return error.InvalidMedia;
+ const w = media.width_mm * 72 / 25.4;
+ const h = media.height_mm * 72 / 25.4;
+ if (kind == .ruler and (w < 160 or h < 232)) return error.MediaTooSmall;
+ if (kind == .page and (w < 88 or h < 110)) return error.MediaTooSmall;
+ var stream: std.Io.Writer.Allocating = .init(a);
+ defer stream.deinit();
+ const sw = &stream.writer;
+ try sw.print("0 G 0.5 w 8 8 {d:.3} {d:.3} re S\n", .{ w - 16, h - 16 });
+ if (kind == .ruler) {
+ try sw.writeAll("12 12 144 216 re S\nBT /F1 9 Tf 16 222 Td (2 x 3 inches / 50.8 x 76.2 mm) Tj ET\n");
+ // Quarter-inch tick marks along the known-size rectangle.
+ for (1..8) |n| try sw.print("{d} 12 m {d} 17 l S\n", .{ 12 + n * 18, 12 + n * 18 });
+ for (1..12) |n| try sw.print("12 {d} m 17 {d} l S\n", .{ 12 + n * 18, 12 + n * 18 });
+ } else {
+ try sw.writeAll("12 12 72 72 re S\nBT /F1 9 Tf 12 92 Td (1 inch / 25.4 mm square) Tj ET\n");
+ try sw.print("BT /F1 10 Tf 12 {d:.3} Td (RediWM printer test - print at 100%) Tj ET\n", .{h - 24});
+ }
+ var out: std.Io.Writer.Allocating = .init(a);
+ defer out.deinit();
+ const writer = &out.writer;
+ try writer.writeAll("%PDF-1.4\n");
+ var offsets: [6]usize = @splat(0);
+ offsets[1] = out.written().len;
+ try writer.writeAll("1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n");
+ offsets[2] = out.written().len;
+ try writer.writeAll("2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n");
+ offsets[3] = out.written().len;
+ try writer.print("3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 {d:.3} {d:.3}] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >> endobj\n", .{ w, h });
+ offsets[4] = out.written().len;
+ try writer.writeAll("4 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj\n");
+ offsets[5] = out.written().len;
+ try writer.print("5 0 obj << /Length {d} >> stream\n", .{stream.written().len});
+ try writer.writeAll(stream.written());
+ try writer.writeAll("endstream\nendobj\n");
+ const xref = out.written().len;
+ try writer.writeAll("xref\n0 6\n0000000000 65535 f \n");
+ for (offsets[1..]) |offset| try writer.print("{d:0>10} 00000 n \n", .{offset});
+ try writer.print("trailer << /Size 6 /Root 1 0 R >>\nstartxref\n{d}\n%%EOF\n", .{xref});
+ return out.toOwnedSlice();
+}
+
+/// Exactly one tiny sample, no downloaded fonts, bitmaps, firmware, language
+/// switching, saved settings or persistent calibration commands.
+/// References: TSC TSPL/TSPL2 manual; Zebra ZPL/EPL/CPCL programming guides;
+/// HP PCL 5 Printer Language Technical Reference; Adobe PLRM (showpage).
+pub fn rawTest(a: A, language: Language, media: Media, dpi: u32) ![]u8 {
+ if (!media.valid()) return error.InvalidMedia;
+ if (dpi < 72 or dpi > 1200) return error.InvalidResolution;
+ const w: u32 = @intFromFloat(@round(media.width_mm * @as(f64, @floatFromInt(dpi)) / 25.4));
+ const h: u32 = @intFromFloat(@round(media.height_mm * @as(f64, @floatFromInt(dpi)) / 25.4));
+ return switch (language) {
+ .tspl => std.fmt.allocPrint(a, "SIZE {d:.3} mm,{d:.3} mm\r\nCLS\r\nTEXT 10,10,\"1\",0,1,1,\"RediWM TSPL test\"\r\nPRINT 1,1\r\n", .{ media.width_mm, media.height_mm }),
+ .zpl => std.fmt.allocPrint(a, "^XA^PW{d}^LL{d}^FO10,10^A0N,24,20^FDRediWM ZPL test^FS^PQ1^XZ\r\n", .{ w, h }),
+ .epl => std.fmt.allocPrint(a, "\nN\nq{d}\nQ{d},0\nA10,10,0,2,1,1,N,\"RediWM EPL test\"\nP1\n", .{ w, h }),
+ .cpcl => std.fmt.allocPrint(a, "! 0 {d} {d} {d} 1\r\nTEXT 0 0 10 10 RediWM CPCL test\r\nFORM\r\nPRINT\r\n", .{ dpi, dpi, h }),
+ .pcl => a.dupe(u8, "\x1bERediWM PCL test\r\n\x0c\x1bE"),
+ .postscript => std.fmt.allocPrint(a, "%!PS-Adobe-3.0\n%%Pages: 1\n<< /PageSize [{d:.3} {d:.3}] >> setpagedevice\n/Helvetica findfont 10 scalefont setfont\n10 10 moveto (RediWM PostScript test) show\nshowpage\n%%EOF\n", .{ media.width_mm * 72 / 25.4, media.height_mm * 72 / 25.4 }),
+ };
+}
+
+pub fn dpiValue(resolution: ipp.Resolution) ?struct { x: f64, y: f64 } {
+ if (resolution.x <= 0 or resolution.y <= 0) return null;
+ const factor: f64 = if (resolution.units == .dpcm) 2.54 else 1;
+ const x = @as(f64, @floatFromInt(resolution.x)) * factor;
+ const y = @as(f64, @floatFromInt(resolution.y)) * factor;
+ if (x < 36 or y < 36 or x > 9600 or y > 9600) return null;
+ return .{ .x = x, .y = y };
+}
+
+/// A current 300dpi job measuring 1.478 times too large suggests 203dpi:
+/// current * expected / measured. Both axes must agree within 8%; the chosen
+/// supported resolution must explain both measurements within 8%. Never invent
+/// an unsupported choice, or "fix" fit-to-page/aspect/margin errors with dpi.
+pub fn suggestResolution(current: ipp.Resolution, supported: []const ipp.Resolution, measured_width_mm: f64, measured_height_mm: f64) ?ipp.Resolution {
+ if (!std.math.isFinite(measured_width_mm) or !std.math.isFinite(measured_height_mm) or measured_width_mm < 1 or measured_height_mm < 1 or measured_width_mm > 5000 or measured_height_mm > 5000) return null;
+ const current_dpi = dpiValue(current) orelse return null;
+ const rx = measured_width_mm / ruler_width_mm;
+ const ry = measured_height_mm / ruler_height_mm;
+ if (@abs(rx / ry - 1) > 0.08 or (@abs(rx - 1) < 0.03 and @abs(ry - 1) < 0.03)) return null;
+ const target_x = current_dpi.x / rx;
+ const target_y = current_dpi.y / ry;
+ var best: ?ipp.Resolution = null;
+ var best_error: f64 = 0.08;
+ var ambiguous = false;
+ for (supported[0..@min(supported.len, 256)]) |candidate| {
+ const value = dpiValue(candidate) orelse continue;
+ const err = @max(@abs(value.x / target_x - 1), @abs(value.y / target_y - 1));
+ if (err > 0.08) continue;
+ if (best != null and @abs(err - best_error) < 0.01) {
+ const old = dpiValue(best.?).?;
+ if (@abs(old.x - value.x) > 1 or @abs(old.y - value.y) > 1) ambiguous = true;
+ } else if (err < best_error) {
+ best = candidate;
+ best_error = err;
+ ambiguous = false;
+ }
+ }
+ return if (ambiguous) null else best;
+}
+
+test {
+ _ = @import("tools_tests.zig");
+}
diff --git a/src/printing/tools_tests.zig b/src/printing/tools_tests.zig
new file mode 100644
index 0000000..3019b32
--- /dev/null
+++ b/src/printing/tools_tests.zig
@@ -0,0 +1,66 @@
+const std = @import("std");
+const tools = @import("tools.zig");
+const ipp = @import("ipp.zig");
+const a = std.testing.allocator;
+
+test "language detection requires exact complete CMD tokens" {
+ const none = try tools.detectLanguages(a, "MFG:TSPL;MDL:ZPL II;CMD:NOTTSPL, PCLXL, XPOSTSCRIPT;");
+ defer a.free(none);
+ try std.testing.expectEqual(@as(usize, 0), none.len);
+ const found = try tools.detectLanguages(a, "MFG:Acme;CMD:TSPL2,ZPLII,EPL2,CPCL,PCL5e,POSTSCRIPT3,TSPL;MDL:Other;");
+ defer a.free(found);
+ try std.testing.expectEqualSlices(tools.Language, &tools.probe_languages, found);
+}
+
+test "media and PDF use actual physical queue dimensions and valid xref offsets" {
+ const media = tools.mediaFromKeyword("na_index-4x6_4x6in").?;
+ try std.testing.expectApproxEqAbs(@as(f64, 101.6), media.width_mm, 0.00001);
+ try std.testing.expect(tools.mediaFromKeyword("4x5.Borderless") == null);
+ try std.testing.expect(tools.mediaFromKeyword("custom_bad_nanx200mm") == null);
+ const pdf = try tools.testPdf(a, media, .ruler);
+ defer a.free(pdf);
+ try std.testing.expect(std.mem.indexOf(u8, pdf, "/MediaBox [0 0 288.000 432.000]") != null);
+ try std.testing.expect(std.mem.indexOf(u8, pdf, "12 12 144 216 re S") != null);
+ const xref = std.mem.indexOf(u8, pdf, "xref\n0 6\n").?;
+ var rows = std.mem.splitScalar(u8, pdf[xref..], '\n');
+ _ = rows.next();
+ _ = rows.next();
+ _ = rows.next();
+ for (1..6) |n| {
+ const line = rows.next().?;
+ const offset = try std.fmt.parseInt(usize, line[0..10], 10);
+ var buffer: [24]u8 = undefined;
+ const prefix = try std.fmt.bufPrint(&buffer, "{d} 0 obj", .{n});
+ try std.testing.expect(std.mem.startsWith(u8, pdf[offset..], prefix));
+ }
+ const page = try tools.testPdf(a, media, .page);
+ defer a.free(page);
+ try std.testing.expect(std.mem.indexOf(u8, page, "12 12 72 72 re S") != null);
+ try std.testing.expectError(error.MediaTooSmall, tools.testPdf(a, .{ .width_mm = 30, .height_mm = 40 }, .ruler));
+}
+
+test "raw language samples are bounded single documents without automatic transport" {
+ for (tools.probe_languages) |language| {
+ const raw = try tools.rawTest(a, language, .{ .width_mm = 101.6, .height_mm = 152.4 }, 203);
+ defer a.free(raw);
+ try std.testing.expect(raw.len > 10 and raw.len < 512);
+ try std.testing.expect(std.mem.indexOf(u8, raw, "RediWM") != null);
+ }
+ try std.testing.expectError(error.InvalidResolution, tools.rawTest(a, .tspl, .{ .width_mm = 100, .height_mm = 150 }, 0));
+ try std.testing.expectError(error.InvalidMedia, tools.rawTest(a, .tspl, .{ .width_mm = std.math.inf(f64), .height_mm = 150 }, 203));
+}
+
+test "calibration suggests only supported resolution consistent with both physical axes" {
+ const r203: ipp.Resolution = .{ .x = 203, .y = 203, .units = .dpi };
+ const r300: ipp.Resolution = .{ .x = 300, .y = 300, .units = .dpi };
+ const supported = [_]ipp.Resolution{ r203, r300, .{ .x = 600, .y = 600, .units = .dpi } };
+ const ratio: f64 = 300.0 / 203.0;
+ const suggestion = tools.suggestResolution(r300, &supported, 50.8 * ratio, 76.2 * ratio).?;
+ try std.testing.expectEqual(r203, suggestion);
+ try std.testing.expect(tools.suggestResolution(r300, &supported, 50.8, 76.2) == null);
+ try std.testing.expect(tools.suggestResolution(r300, &supported, 50.8 * ratio, 76.2) == null);
+ try std.testing.expect(tools.suggestResolution(r300, &.{r300}, 50.8 * ratio, 76.2 * ratio) == null);
+ try std.testing.expect(tools.suggestResolution(r300, &supported, std.math.nan(f64), 76.2) == null);
+ const dpcm: ipp.Resolution = .{ .x = 80, .y = 80, .units = .dpcm };
+ try std.testing.expectEqual(dpcm, tools.suggestResolution(r300, &.{dpcm}, 50.8 * 300 / 203.2, 76.2 * 300 / 203.2).?);
+}
diff --git a/src/printing/usb_sysfs.zig b/src/printing/usb_sysfs.zig
new file mode 100644
index 0000000..2a370d7
--- /dev/null
+++ b/src/printing/usb_sysfs.zig
@@ -0,0 +1,534 @@
+//! Read-only USB printer inventory. Device nodes are stat'ed, never opened.
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const Io = std.Io;
+
+pub const Roots = struct { sysfs: []const u8 = "/sys", dev: []const u8 = "/dev" };
+pub const NodeKind = enum { missing, character, regular, other, unavailable };
+pub const Node = struct {
+ path: []const u8,
+ kind: NodeKind,
+};
+pub const Device = struct {
+ /// USB topology name, not the product string (which can be misleading).
+ name: []const u8,
+ vid: u16,
+ pid: u16,
+ printer_class: bool = true,
+ manufacturer: []const u8,
+ product: []const u8,
+ serial: []const u8,
+ driver: []const u8,
+ /// Complete validated IEEE 1284 identity, never a display-truncated string.
+ /// Empty means absent, unreadable, invalid, or conflicting interface IDs.
+ device_id: []const u8 = "",
+ nodes: []Node,
+
+ pub fn deinit(self: Device, a: Allocator) void {
+ a.free(self.name);
+ a.free(self.manufacturer);
+ a.free(self.product);
+ a.free(self.serial);
+ a.free(self.driver);
+ a.free(self.device_id);
+ for (self.nodes) |node| a.free(node.path);
+ a.free(self.nodes);
+ }
+};
+pub const Snapshot = struct {
+ devices: []Device,
+ /// False means unavailable, interrupted, or bounded; absence is then inconclusive.
+ complete: bool,
+
+ pub fn deinit(self: Snapshot, a: Allocator) void {
+ for (self.devices) |device| device.deinit(a);
+ a.free(self.devices);
+ }
+};
+
+pub const Match = struct {
+ device: ?*const Device = null,
+ /// A complete scan plus a usable unique serial permits an absence verdict.
+ conclusive: bool = false,
+};
+
+/// CUPS USB URIs identify a device by their percent-encoded `serial` query.
+/// Model names and VID:PID cannot distinguish two printers of the same model.
+/// Missing serials, duplicate serials and unavailable inventory stay unknown.
+pub fn matchQueue(snapshot: *const Snapshot, uri: []const u8) Match {
+ var serial_bytes: [256]u8 = undefined;
+ const serial = queueSerial(uri, &serial_bytes) orelse return .{};
+ var matched: ?*const Device = null;
+ var unidentified = false;
+ for (snapshot.devices) |*device| {
+ if (device.serial.len == 0) unidentified = true;
+ if (!std.mem.eql(u8, device.serial, serial)) continue;
+ if (matched != null) return .{};
+ matched = device;
+ }
+ if (matched) |device| return .{ .device = device, .conclusive = snapshot.complete };
+ return .{ .conclusive = snapshot.complete and !unidentified };
+}
+
+fn queueSerial(uri: []const u8, output: []u8) ?[]const u8 {
+ if (uri.len > 4096 or uri.len < 6 or !std.ascii.eqlIgnoreCase(uri[0..6], "usb://")) return null;
+ const query = std.mem.indexOfScalar(u8, uri, '?') orelse return null;
+ if (std.mem.indexOfScalar(u8, uri[query..], '#') != null) return null;
+ var serial: ?[]const u8 = null;
+ var fields = std.mem.splitScalar(u8, uri[query + 1 ..], '&');
+ var count: usize = 0;
+ while (fields.next()) |field| {
+ count += 1;
+ if (count > 64) return null;
+ const equals = std.mem.indexOfScalar(u8, field, '=') orelse continue;
+ if (!std.mem.eql(u8, field[0..equals], "serial")) continue;
+ if (serial != null) return null;
+ serial = field[equals + 1 ..];
+ }
+ const encoded = serial orelse return null;
+ if (encoded.len == 0) return null;
+ var i: usize = 0;
+ var len: usize = 0;
+ while (i < encoded.len) {
+ if (len == output.len) return null;
+ const byte = encoded[i];
+ if (byte == '%') {
+ if (i + 2 >= encoded.len) return null;
+ output[len] = std.fmt.parseInt(u8, encoded[i + 1 .. i + 3], 16) catch return null;
+ i += 3;
+ } else {
+ // URI query values are not HTML forms: '+' is a literal plus.
+ output[len] = byte;
+ i += 1;
+ }
+ len += 1;
+ }
+ const view = std.unicode.Utf8View.init(output[0..len]) catch return null;
+ var codepoints = view.iterator();
+ while (codepoints.nextCodepoint()) |codepoint| if (forbiddenCodepoint(codepoint)) return null;
+ return output[0..len];
+}
+
+const max_entries = 4096;
+const max_devices = 256;
+const max_nodes = 32;
+
+/// Caller owns the snapshot and supplies Io; no worker, timers, or global state.
+pub fn scan(a: Allocator, io: Io, roots: Roots) !Snapshot {
+ const path = try std.fs.path.join(a, &.{ roots.sysfs, "bus/usb/devices" });
+ defer a.free(path);
+ var result: std.ArrayList(Device) = .empty;
+ errdefer {
+ for (result.items) |device| device.deinit(a);
+ result.deinit(a);
+ }
+ var bus = Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch return .{
+ .devices = try result.toOwnedSlice(a),
+ .complete = false,
+ };
+ defer bus.close(io);
+ var names: std.ArrayList([]const u8) = .empty;
+ defer {
+ for (names.items) |name| a.free(name);
+ names.deinit(a);
+ }
+ var complete = true;
+ var iterator = bus.iterate();
+ while (true) {
+ const entry = (iterator.next(io) catch {
+ complete = false;
+ break;
+ }) orelse break;
+ if (names.items.len == max_entries) {
+ complete = false;
+ break;
+ }
+ // Real sysfs names are short ASCII; reject fixture/path impostors too.
+ if (!safeName(entry.name)) continue;
+ const copy = try a.dupe(u8, entry.name);
+ errdefer a.free(copy);
+ try names.append(a, copy);
+ }
+ std.mem.sort([]const u8, names.items, {}, lessThan);
+ for (names.items) |name| {
+ if (std.mem.indexOfScalar(u8, name, ':') != null) continue;
+ var device_dir = bus.openDir(io, name, .{}) catch continue;
+ defer device_dir.close(io);
+ const vid = hexNumber(device_dir, io, "idVendor", u16) orelse continue;
+ const pid = hexNumber(device_dir, io, "idProduct", u16) orelse continue;
+ var printer = (hexNumber(device_dir, io, "bDeviceClass", u8) orelse 0) == 7;
+ for (names.items) |interface| {
+ if (!interfaceOf(name, interface)) continue;
+ var interface_dir = bus.openDir(io, interface, .{}) catch {
+ complete = false;
+ continue;
+ };
+ defer interface_dir.close(io);
+ if ((hexNumber(interface_dir, io, "bInterfaceClass", u8) orelse 0) == 7) printer = true;
+ }
+ if (!printer) continue;
+ if (result.items.len == max_devices) {
+ complete = false;
+ break;
+ }
+ var nodes: std.ArrayList(Node) = .empty;
+ var driver: []const u8 = try a.dupe(u8, "");
+ var device_id: []const u8 = "";
+ var id_conflict = false;
+ errdefer {
+ a.free(driver);
+ a.free(device_id);
+ for (nodes.items) |node| a.free(node.path);
+ nodes.deinit(a);
+ }
+ for (names.items) |interface| {
+ if (!interfaceOf(name, interface)) continue;
+ var interface_dir = bus.openDir(io, interface, .{}) catch continue;
+ defer interface_dir.close(io);
+ if ((hexNumber(interface_dir, io, "bInterfaceClass", u8) orelse 0) != 7) continue;
+ // Linux usblp exposes its cached ID on the printer interface:
+ // drivers/usb/class/usblp.c ieee1284_id_show. Reading this attribute
+ // never opens a print node or asks the printer for a new ID.
+ mergeDeviceId(a, &device_id, &id_conflict, try readDeviceId(a, interface_dir, io, "ieee1284_id"));
+ if (driver.len == 0) {
+ var link: [1024]u8 = undefined;
+ if (interface_dir.readLink(io, "driver", &link)) |len| {
+ const value = try sanitize(a, std.fs.path.basename(link[0..len]), 128);
+ a.free(driver);
+ driver = value;
+ } else |_| {}
+ }
+ // The interface's own usbmisc children establish identity. Looking
+ // for /dev/usb/lp0 globally can attribute another printer's node.
+ var misc = interface_dir.openDir(io, "usbmisc", .{ .iterate = true }) catch continue;
+ defer misc.close(io);
+ var children = misc.iterate();
+ while (true) {
+ const child = (children.next(io) catch {
+ complete = false;
+ break;
+ }) orelse break;
+ if (!lpName(child.name)) continue;
+ // Compatibility with layouts exposing the interface through
+ // the interface-owned usbmisc child's device symlink.
+ const id_path = try std.fs.path.join(a, &.{ child.name, "device/ieee1284_id" });
+ defer a.free(id_path);
+ mergeDeviceId(a, &device_id, &id_conflict, try readDeviceId(a, misc, io, id_path));
+ if (nodes.items.len == max_nodes) {
+ complete = false;
+ break;
+ }
+ const node_path = try std.fs.path.join(a, &.{ roots.dev, "usb", child.name });
+ errdefer a.free(node_path);
+ var duplicate = false;
+ for (nodes.items) |node| if (std.mem.eql(u8, node.path, node_path)) {
+ duplicate = true;
+ break;
+ };
+ if (duplicate) {
+ a.free(node_path);
+ continue;
+ }
+ const kind: NodeKind = if (Io.Dir.cwd().statFile(io, node_path, .{})) |stat| switch (stat.kind) {
+ .character_device => .character,
+ .file => .regular,
+ else => .other,
+ } else |err| switch (err) {
+ error.FileNotFound => .missing,
+ else => .unavailable,
+ };
+ try nodes.append(a, .{ .path = node_path, .kind = kind });
+ }
+ }
+ const device_name = try a.dupe(u8, name);
+ errdefer a.free(device_name);
+ const manufacturer = try readText(a, device_dir, io, "manufacturer");
+ errdefer a.free(manufacturer);
+ const product = try readText(a, device_dir, io, "product");
+ errdefer a.free(product);
+ const serial = try readText(a, device_dir, io, "serial");
+ errdefer a.free(serial);
+ const owned_nodes = try nodes.toOwnedSlice(a);
+ errdefer {
+ for (owned_nodes) |node| a.free(node.path);
+ a.free(owned_nodes);
+ }
+ try result.append(a, .{
+ .name = device_name,
+ .vid = vid,
+ .pid = pid,
+ .manufacturer = manufacturer,
+ .product = product,
+ .serial = serial,
+ .driver = driver,
+ .device_id = device_id,
+ .nodes = owned_nodes,
+ });
+ }
+ return .{ .devices = try result.toOwnedSlice(a), .complete = complete };
+}
+
+fn lessThan(_: void, lhs: []const u8, rhs: []const u8) bool {
+ return std.mem.order(u8, lhs, rhs) == .lt;
+}
+fn safeName(name: []const u8) bool {
+ if (name.len == 0 or name.len > 128) return false;
+ for (name) |byte| if (!std.ascii.isAlphanumeric(byte) and byte != '-' and byte != '.' and byte != ':') return false;
+ return !std.mem.eql(u8, name, ".") and !std.mem.eql(u8, name, "..");
+}
+fn interfaceOf(device: []const u8, interface: []const u8) bool {
+ return interface.len > device.len and std.mem.startsWith(u8, interface, device) and interface[device.len] == ':';
+}
+fn lpName(name: []const u8) bool {
+ if (!std.mem.startsWith(u8, name, "lp") or name.len < 3 or name.len > 16) return false;
+ for (name[2..]) |byte| if (!std.ascii.isDigit(byte)) return false;
+ return true;
+}
+fn hexNumber(dir: Io.Dir, io: Io, name: []const u8, comptime T: type) ?T {
+ var bytes: [32]u8 = undefined;
+ const raw = dir.readFile(io, name, &bytes) catch return null;
+ return std.fmt.parseInt(T, std.mem.trim(u8, raw, " \t\r\n"), 16) catch null;
+}
+fn readText(a: Allocator, dir: Io.Dir, io: Io, name: []const u8) ![]const u8 {
+ var bytes: [1024]u8 = undefined;
+ const raw = dir.readFile(io, name, &bytes) catch return a.dupe(u8, "");
+ return sanitize(a, std.mem.trimEnd(u8, raw, "\r\n"), 256);
+}
+
+fn readDeviceId(a: Allocator, dir: Io.Dir, io: Io, name: []const u8) ![]const u8 {
+ // The extra bytes distinguish an oversized/truncated file from a complete
+ // 8192-byte identity with an optional sysfs line ending. Never turn a
+ // truncated CMD:NOT_TSPL tail into a different complete language token.
+ var bytes: [8195]u8 = undefined;
+ const raw = dir.readFile(io, name, &bytes) catch return a.dupe(u8, "");
+ if (raw.len == bytes.len) return a.dupe(u8, "");
+ const value = std.mem.trimEnd(u8, raw, "\r\n");
+ if (value.len == 0 or value.len > 8192) return a.dupe(u8, "");
+ const view = std.unicode.Utf8View.init(value) catch return a.dupe(u8, "");
+ var codepoints = view.iterator();
+ while (codepoints.nextCodepoint()) |codepoint| if (forbiddenCodepoint(codepoint)) return a.dupe(u8, "");
+ return a.dupe(u8, value);
+}
+
+fn mergeDeviceId(a: Allocator, current: *[]const u8, conflict: *bool, candidate: []const u8) void {
+ if (conflict.* or candidate.len == 0) {
+ a.free(candidate);
+ return;
+ }
+ if (current.len == 0) {
+ a.free(current.*);
+ current.* = candidate;
+ return;
+ }
+ if (!std.mem.eql(u8, current.*, candidate)) {
+ a.free(current.*);
+ current.* = "";
+ conflict.* = true;
+ }
+ a.free(candidate);
+}
+
+fn forbiddenCodepoint(codepoint: u21) bool {
+ return codepoint < 0x20 or codepoint == 0x7f or (codepoint >= 0x80 and codepoint <= 0x9f) or (codepoint >= 0x202a and codepoint <= 0x202e) or (codepoint >= 0x2066 and codepoint <= 0x2069);
+}
+
+/// Keep valid UTF-8, remove controls, and cap without splitting a codepoint.
+pub fn sanitize(a: Allocator, raw: []const u8, limit: usize) ![]u8 {
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(a);
+ var i: usize = 0;
+ while (i < raw.len and out.items.len < limit) {
+ const byte = raw[i];
+ if (byte < 0x20 or byte == 0x7f) {
+ i += 1;
+ continue;
+ }
+ const len = std.unicode.utf8ByteSequenceLength(byte) catch {
+ try out.append(a, '?');
+ i += 1;
+ continue;
+ };
+ if (i + len > raw.len or !std.unicode.utf8ValidateSlice(raw[i .. i + len])) {
+ try out.append(a, '?');
+ i += 1;
+ continue;
+ }
+ const codepoint = std.unicode.utf8Decode(raw[i .. i + len]) catch unreachable;
+ // C1 controls and directional formatting have no place in labels.
+ if (forbiddenCodepoint(codepoint)) {
+ i += len;
+ continue;
+ }
+ if (out.items.len + len > limit) break;
+ try out.appendSlice(a, raw[i .. i + len]);
+ i += len;
+ }
+ return out.toOwnedSlice(a);
+}
+
+fn fixture(dir: Io.Dir, io: Io, path: []const u8, content: []const u8) !void {
+ if (std.fs.path.dirname(path)) |parent| try dir.createDirPath(io, parent);
+ try dir.writeFile(io, .{ .sub_path = path, .data = content });
+}
+
+test "USB class comes from interfaces; nodes belong to that device and regular files are detected" {
+ const a = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", a);
+ defer a.free(root);
+ const sys = try std.fs.path.join(a, &.{ root, "sys" });
+ defer a.free(sys);
+ const dev = try std.fs.path.join(a, &.{ root, "dev" });
+ defer a.free(dev);
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-2/idVendor", "0416\n");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-2/idProduct", "5011\n");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-2/product", "Virtual\x00 Com Port\n");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-2:1.0/bInterfaceClass", "07\n");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-2:1.0/ieee1284_id", "MFG:Example;MDL:Label;CMD:TSPL;\n");
+ try tmp.dir.createDirPath(io, "sys/bus/usb/devices/1-2:1.0/usbmisc/lp3");
+ try fixture(tmp.dir, io, "dev/usb/lp3", "impostor");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-20/idVendor", "1234");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-20/idProduct", "abcd");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-20:1.0/bInterfaceClass", "07");
+ try tmp.dir.createDirPath(io, "sys/bus/usb/devices/1-20:1.0/usbmisc/lp4");
+ // No dev/usb/lp4: it must never inherit 1-2's lp3.
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/2-1/idVendor", "8888");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/2-1/idProduct", "9999");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/2-1/product", "Printer");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/2-1:1.0/bInterfaceClass", "ff");
+ const snapshot = try scan(a, io, .{ .sysfs = sys, .dev = dev });
+ defer snapshot.deinit(a);
+ try std.testing.expect(snapshot.complete);
+ try std.testing.expectEqual(@as(usize, 2), snapshot.devices.len);
+ try std.testing.expectEqualStrings("Virtual Com Port", snapshot.devices[0].product);
+ try std.testing.expectEqualStrings("MFG:Example;MDL:Label;CMD:TSPL;", snapshot.devices[0].device_id);
+ try std.testing.expectEqualStrings("", snapshot.devices[1].device_id);
+ try std.testing.expectEqual(NodeKind.regular, snapshot.devices[0].nodes[0].kind);
+ try std.testing.expectEqual(NodeKind.missing, snapshot.devices[1].nodes[0].kind);
+ const original = try tmp.dir.readFileAlloc(io, "dev/usb/lp3", a, .limited(32));
+ defer a.free(original);
+ try std.testing.expectEqualStrings("impostor", original);
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-2:1.1/bInterfaceClass", "07\n");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-2:1.1/ieee1284_id", "MFG:Different;MDL:Language;CMD:ZPL;\n");
+ const conflicting = try scan(a, io, .{ .sysfs = sys, .dev = dev });
+ defer conflicting.deinit(a);
+ try std.testing.expectEqualStrings("", conflicting.devices[0].device_id);
+}
+
+test "missing sysfs is inconclusive; sanitization is bounded valid UTF-8" {
+ const a = std.testing.allocator;
+ const snapshot = try scan(a, std.testing.io, .{ .sysfs = "/this-path-does-not-exist-rediwm" });
+ defer snapshot.deinit(a);
+ try std.testing.expect(!snapshot.complete);
+ const clean = try sanitize(a, "A\x00\xff\xc3\xa9\xe2\x80\xaeB", 4);
+ defer a.free(clean);
+ try std.testing.expectEqualStrings("A?é", clean);
+}
+
+test "USB inventory follows sysfs links and releases partial snapshots on allocation failure" {
+ const a = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", a);
+ defer a.free(root);
+ const sys = try std.fs.path.join(a, &.{ root, "sys" });
+ defer a.free(sys);
+ const dev = try std.fs.path.join(a, &.{ root, "dev" });
+ defer a.free(dev);
+ try fixture(tmp.dir, io, "hardware/3-1/idVendor", "0416");
+ try fixture(tmp.dir, io, "hardware/3-1/idProduct", "5011");
+ try fixture(tmp.dir, io, "hardware/3-1/3-1:1.0/bInterfaceClass", "07");
+ try fixture(tmp.dir, io, "hardware/3-1/3-1:1.0/ieee1284_id", "MFG:Example;MDL:Label;CMD:TSPL;\n");
+ try tmp.dir.createDirPath(io, "hardware/3-1/3-1:1.0/usbmisc/lp7");
+ try tmp.dir.symLink(io, "../..", "hardware/3-1/3-1:1.0/usbmisc/lp7/device", .{ .is_directory = true });
+ try tmp.dir.createDirPath(io, "sys/bus/usb/devices");
+ try tmp.dir.symLink(io, "../../../../hardware/3-1", "sys/bus/usb/devices/3-1", .{ .is_directory = true });
+ try tmp.dir.symLink(io, "../../../../hardware/3-1/3-1:1.0", "sys/bus/usb/devices/3-1:1.0", .{ .is_directory = true });
+ try tmp.dir.symLink(io, "../../../../drivers/usblp", "hardware/3-1/3-1:1.0/driver", .{ .is_directory = true });
+ try tmp.dir.createDirPath(io, "dev/usb");
+ // A real character device can be stat'ed without opening it or root/mknod.
+ try tmp.dir.symLink(io, "/dev/null", "dev/usb/lp7", .{});
+ const Case = struct {
+ fn run(allocator: Allocator, roots: Roots) !void {
+ const snapshot = try scan(allocator, std.testing.io, roots);
+ defer snapshot.deinit(allocator);
+ try std.testing.expectEqual(@as(usize, 1), snapshot.devices.len);
+ try std.testing.expectEqualStrings("usblp", snapshot.devices[0].driver);
+ try std.testing.expectEqualStrings("MFG:Example;MDL:Label;CMD:TSPL;", snapshot.devices[0].device_id);
+ try std.testing.expectEqual(NodeKind.character, snapshot.devices[0].nodes[0].kind);
+ }
+ };
+ try std.testing.checkAllAllocationFailures(a, Case.run, .{Roots{ .sysfs = sys, .dev = dev }});
+}
+
+test "USB IEEE 1284 identity stays complete and rejects oversized malformed or controlled data" {
+ const a = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", a);
+ defer a.free(root);
+ const sys = try std.fs.path.join(a, &.{ root, "sys" });
+ defer a.free(sys);
+ const dev = try std.fs.path.join(a, &.{ root, "dev" });
+ defer a.free(dev);
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-1/idVendor", "0416");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-1/idProduct", "5011");
+ try fixture(tmp.dir, io, "sys/bus/usb/devices/1-1:1.0/bInterfaceClass", "07");
+ // The usbmisc fallback is scoped to this interface, not a global lp path.
+ const id_path = "sys/bus/usb/devices/1-1:1.0/usbmisc/lp0/device/ieee1284_id";
+ try fixture(tmp.dir, io, id_path, "MFG:Example;MDL:Label;CMD:TSPL;");
+ {
+ const snapshot = try scan(a, io, .{ .sysfs = sys, .dev = dev });
+ defer snapshot.deinit(a);
+ try std.testing.expectEqualStrings("MFG:Example;MDL:Label;CMD:TSPL;", snapshot.devices[0].device_id);
+ }
+ for ([_][]const u8{ "MFG:Example;CMD:TS\x00PL;", "MFG:Example;CMD:TS\x1bPL;", "MFG:Example;CMD:TS\xffPL;", "MFG:Example;CMD:TS\xe2\x80\xaePL;" }) |invalid| {
+ try fixture(tmp.dir, io, id_path, invalid);
+ const snapshot = try scan(a, io, .{ .sysfs = sys, .dev = dev });
+ defer snapshot.deinit(a);
+ try std.testing.expectEqualStrings("", snapshot.devices[0].device_id);
+ }
+ var long: [8192]u8 = @splat('x');
+ long[0..4].* = "DES:".*;
+ const tail = ";CMD:TSPL;";
+ @memcpy(long[long.len - tail.len ..], tail);
+ try fixture(tmp.dir, io, id_path, &long);
+ {
+ const snapshot = try scan(a, io, .{ .sysfs = sys, .dev = dev });
+ defer snapshot.deinit(a);
+ try std.testing.expectEqualStrings(&long, snapshot.devices[0].device_id);
+ }
+ const oversized = try std.mem.concat(a, u8, &.{ &long, "FAKE" });
+ defer a.free(oversized);
+ try fixture(tmp.dir, io, id_path, oversized);
+ const snapshot = try scan(a, io, .{ .sysfs = sys, .dev = dev });
+ defer snapshot.deinit(a);
+ try std.testing.expectEqualStrings("", snapshot.devices[0].device_id);
+}
+
+test "CUPS USB identity needs a unique decoded serial; model names never establish identity" {
+ const template: Device = .{ .name = "1-2", .vid = 0x0416, .pid = 0x5011, .manufacturer = "", .product = "", .serial = "A B+C", .driver = "", .nodes = &.{} };
+ var devices = [_]Device{template};
+ var snapshot: Snapshot = .{ .devices = &devices, .complete = true };
+ const found = matchQueue(&snapshot, "usb://Vendor/Model?serial=A%20B%2bC&interface=1");
+ try std.testing.expect(found.conclusive);
+ try std.testing.expect(found.device == &devices[0]);
+ try std.testing.expect(matchQueue(&snapshot, "usb://Vendor/Model?serial=unplugged").conclusive);
+ try std.testing.expect(!matchQueue(&snapshot, "usb://Vendor/Model").conclusive);
+ try std.testing.expect(!matchQueue(&snapshot, "usb://Vendor/Model?serial=%ZZ").conclusive);
+ try std.testing.expect(!matchQueue(&snapshot, "usb://Vendor/Model?serial=A%00").conclusive);
+ try std.testing.expect(!matchQueue(&snapshot, "usb://Vendor/Model?serial=A&serial=B").conclusive);
+ snapshot.complete = false;
+ try std.testing.expect(!matchQueue(&snapshot, "usb://Vendor/Model?serial=unplugged").conclusive);
+ snapshot.complete = true;
+ devices[0].serial = "";
+ try std.testing.expect(!matchQueue(&snapshot, "usb://Vendor/Model?serial=unplugged").conclusive);
+ var duplicates = [_]Device{ template, template };
+ snapshot.devices = &duplicates;
+ try std.testing.expect(!matchQueue(&snapshot, "usb://Vendor/Model?serial=A%20B%2BC").conclusive);
+ try std.testing.expect(matchQueue(&snapshot, "usb://Vendor/Model?serial=A%20B%2BC").device == null);
+}
diff --git a/src/start_menu/search.zig b/src/start_menu/search.zig
index 2548a0f..3cec86d 100644
--- a/src/start_menu/search.zig
+++ b/src/start_menu/search.zig
@@ -30,7 +30,7 @@ pub const settings_description = "System preferences, display, appearance and in
pub const loading_id = "rediwm.loading";
pub const loading_name = "Loading applications…";
pub const loading_description = "Scanning installed apps";
-const settings_keywords = "settings;control;panel;preferences;display;appearance;mouse;keyboard";
+const settings_keywords = "settings;control;panel;preferences;display;appearance;mouse;keyboard;printer;printers;printing";
pub fn search(
allocator: Allocator,
diff --git a/src/ui/widgets/text_input.zig b/src/ui/widgets/text_input.zig
index 8e87f39..078ee21 100644
--- a/src/ui/widgets/text_input.zig
+++ b/src/ui/widgets/text_input.zig
@@ -168,7 +168,12 @@ fn alignBoundary(bytes: []const u8, pos: usize) usize {
pub fn deleteSelection(allocator: Allocator, widget: *Widget) !bool {
switch (widget.kind) {
.text_input => |*data| {
- const range = data.selection() orelse return false;
+ const range = data.selection() orelse {
+ // Select All on an empty field leaves a collapsed anchor. It
+ // must not become a selection of the next inserted character.
+ data.selection_anchor = null;
+ return false;
+ };
try removeRange(allocator, widget, range.start, range.end);
widget.kind.text_input.cursor_pos = range.start;
widget.kind.text_input.selection_anchor = null;
@@ -374,6 +379,13 @@ test "typing and deleting replace the selection" {
// With nothing selected it is an ordinary backspace again.
try backspace(allocator, w);
try std.testing.expectEqualStrings("goodby", field.data().value);
+
+ try clear(allocator, w);
+ selectAll(w);
+ try insertText(allocator, w, "7");
+ try insertText(allocator, w, "5");
+ try std.testing.expectEqualStrings("75", field.data().value);
+ try std.testing.expect(field.data().selection_anchor == null);
}
test "double click selects the word under the point, or everything in a gap" {
diff --git a/tests/printers.py b/tests/printers.py
new file mode 100644
index 0000000..99632d9
--- /dev/null
+++ b/tests/printers.py
@@ -0,0 +1,1157 @@
+#!/usr/bin/env python3
+"""Printers Settings against private scripted CUPS and helper fixtures.
+
+Needs the regular headless compositor dependencies and wl-paste. All CUPS
+responses are synthetic; no host queue, service, USB node or printer is used.
+Confirmed test documents terminate in the fixture's memory, without a backend.
+"""
+import os
+import json
+from pathlib import Path
+import pwd
+import socket
+import socketserver
+import struct
+import subprocess
+import tempfile
+import threading
+import time
+import select
+import sys
+
+from ipc_client import IPCClient, spawn_compositor, stop_process
+from power_profiles import wait_for
+from ui_driver import UIDriver
+from xwayland_support import wayland_display_name
+
+
+def attribute(tag, name, value):
+ name = name.encode()
+ if tag in (0x21, 0x23):
+ value = struct.pack('!i', value)
+ elif tag == 0x22:
+ value = bytes([bool(value)])
+ elif tag == 0x32:
+ value = struct.pack('!iiB', *value)
+ else:
+ value = value.encode()
+ return bytes([tag]) + struct.pack('!H', len(name)) + name + struct.pack('!H', len(value)) + value
+
+
+def request_attributes(body):
+ """Decode scalar request fields needed to assert operation ownership."""
+ fields, offset, name = {}, 8, ''
+ while offset < len(body):
+ tag = body[offset]
+ offset += 1
+ if tag == 3:
+ fields['_document'] = body[offset:]
+ break
+ if tag < 0x10:
+ continue
+ length = struct.unpack_from('!H', body, offset)[0]
+ offset += 2
+ if length:
+ name = body[offset:offset + length].decode()
+ offset += length
+ length = struct.unpack_from('!H', body, offset)[0]
+ offset += 2
+ value = body[offset:offset + length]
+ offset += length
+ fields[name] = struct.unpack('!i', value)[0] if tag in (0x21, 0x23) else bool(value[0]) if tag == 0x22 else value.decode()
+ return fields
+
+
+def printer_workers(process):
+ """Read only this test compositor's named printer worker and counters."""
+ workers = {}
+ for task in Path(f'/proc/{process.pid}/task').iterdir():
+ try:
+ if task.joinpath('comm').read_text().strip() != 'rediwm-printers':
+ continue
+ fields = dict(line.split(':', 1) for line in task.joinpath('status').read_text().splitlines())
+ workers[task.name] = (int(fields['voluntary_ctxt_switches']), int(fields['nonvoluntary_ctxt_switches']))
+ except FileNotFoundError:
+ # Other compositor threads may exit during /proc enumeration.
+ continue
+ return workers
+
+
+class Scheduler(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
+ daemon_threads = True
+ block_on_close = False
+
+ def __init__(self, path):
+ self.lock = threading.Lock()
+ self.events = []
+ self.fault = ''
+ self.empty = False
+ self.denied = False
+ self.stopped = False
+ self.cancelled = False
+ self.release = threading.Event()
+ self.username = pwd.getpwuid(os.getuid()).pw_name
+ super().__init__(str(path), Handler)
+ self.thread = threading.Thread(target=self.serve_forever, daemon=True)
+ self.thread.start()
+
+ def configure(self, **values):
+ with self.lock:
+ for key, value in values.items():
+ setattr(self, key, value)
+
+ def calls(self):
+ with self.lock:
+ return list(self.events)
+
+ def reply(self, operation, fields):
+ with self.lock:
+ self.events.append((operation, fields))
+ fault = self.fault
+ empty, stopped, denied = self.empty, self.stopped, self.denied
+ cancelled = self.cancelled
+ if operation == 8 and not denied:
+ self.cancelled = True
+ if fault == 'stall':
+ self.release.wait(12)
+ if fault == 'malformed':
+ return 200, b'not an IPP response'
+ if fault == 'http':
+ return 503, b'fixture unavailable'
+ status = 0x0403 if operation == 8 and denied else 0x0406 if operation == 0x4002 and empty else 0
+ response = struct.pack('!BBHI', 2, 0, status, fields.pop('_request_id'))
+ response += b'\x01' + attribute(0x47, 'attributes-charset', 'utf-8')
+ response += attribute(0x48, 'attributes-natural-language', 'en')
+ if status:
+ response += attribute(0x41, 'status-message', 'Fixture denied cancellation' if denied else 'No destinations')
+ elif operation == 0x4002 and not empty:
+ for index, (name, model) in enumerate((('Label_Test', 'Fixture thermal printer'), ('Office_Test', 'Fixture office printer'))):
+ response += b'\x04'
+ response += attribute(0x42, 'printer-name', name)
+ response += attribute(0x41, 'printer-info', name.replace('_', ' '))
+ response += attribute(0x41, 'printer-make-and-model', model)
+ response += attribute(0x45, 'printer-uri-supported', 'ipp://localhost/printers/' + name)
+ response += attribute(0x45, 'device-uri', 'socket://operator:[email protected]:9100/')
+ response += attribute(0x23, 'printer-state', 5 if stopped and index == 0 else 3)
+ response += attribute(0x22, 'printer-is-accepting-jobs', not (stopped and index == 0))
+ response += attribute(0x44, 'printer-state-reasons', 'media-empty-error' if stopped and index == 0 else 'none')
+ response += attribute(0x41, 'printer-state-message', 'Out of paper' if stopped and index == 0 else 'Ready')
+ response += attribute(0x44, 'media-default', 'na_index-4x6_4x6in')
+ if index:
+ # Largest signed IPP resolution in dpcm used to overflow
+ # the conversion to DPI when this queue was selected.
+ response += attribute(0x32, 'printer-resolution-default', (2147483647, 3, 4))
+ response += attribute(0x49, 'document-format-supported', 'application/pdf')
+ response += attribute(0x42, 'marker-names', 'Black')
+ response += attribute(0x21, 'marker-levels', 42 if index else -1)
+ elif operation == 0x000a and not empty:
+ response += b'\x02'
+ response += attribute(0x21, 'job-id', 17)
+ response += attribute(0x23, 'job-state', 7 if cancelled else 3)
+ response += attribute(0x42, 'job-originating-user-name', self.username)
+ response += attribute(0x42, 'job-name', 'PRIVATE-DOCUMENT-NAME')
+ response += attribute(0x45, 'job-printer-uri', 'ipp://localhost/printers/Label_Test')
+ response += attribute(0x44, 'job-state-reasons', 'job-canceled-by-user' if cancelled else 'job-incoming')
+ response += attribute(0x21, 'job-media-sheets-completed', 0)
+ response += b'\x02'
+ response += attribute(0x21, 'job-id', 16)
+ response += attribute(0x23, 'job-state', 9)
+ response += attribute(0x42, 'job-originating-user-name', self.username)
+ response += attribute(0x42, 'job-name', 'OLDER-PRIVATE-DOCUMENT')
+ response += attribute(0x45, 'job-printer-uri', 'ipp://localhost/printers/Label_Test')
+ response += attribute(0x44, 'job-state-reasons', 'job-completed-successfully')
+ response += attribute(0x21, 'job-media-sheets-completed', 0)
+ response += attribute(0x41, 'job-printer-state-message', 'No pages were found.')
+ # Even a scheduler that ignores my-jobs must not make another
+ # user's pending job cancellable in the page.
+ response += b'\x02'
+ response += attribute(0x21, 'job-id', 18)
+ response += attribute(0x23, 'job-state', 3)
+ response += attribute(0x42, 'job-originating-user-name', 'fixture-other-user')
+ response += attribute(0x42, 'job-name', 'OTHER-PRIVATE-DOCUMENT')
+ response += attribute(0x45, 'job-printer-uri', 'ipp://localhost/printers/Label_Test')
+ return 200, response + b'\x03'
+
+ def close(self):
+ self.release.set()
+ self.shutdown()
+ self.server_close()
+ self.thread.join(timeout=2)
+
+
+class Handler(socketserver.StreamRequestHandler):
+ def handle(self):
+ self.request.settimeout(5)
+ try:
+ line = self.rfile.readline(4096)
+ if not line:
+ return
+ assert line.startswith(b'POST '), line
+ headers = {}
+ while True:
+ line = self.rfile.readline(4096)
+ if line in (b'\r\n', b'\n', b''):
+ break
+ key, value = line.decode().split(':', 1)
+ headers[key.lower()] = value.strip()
+ length = int(headers['content-length'])
+ assert 8 <= length <= 1024 * 1024, length
+ body = self.rfile.read(length)
+ fields = request_attributes(body)
+ fields['_request_id'] = struct.unpack_from('!I', body, 4)[0]
+ operation = struct.unpack_from('!H', body, 2)[0]
+ status, response = self.server.reply(operation, fields)
+ self.wfile.write(f'HTTP/1.1 {status} Fixture\r\nContent-Type: application/ipp\r\nContent-Length: {len(response)}\r\nConnection: close\r\n\r\n'.encode() + response)
+ except (BrokenPipeError, ConnectionResetError, TimeoutError):
+ pass
+
+
+class TcpEndpoint(socketserver.ThreadingTCPServer):
+ """A private loopback scheduler or the one selected printer's IPP endpoint."""
+ daemon_threads = True
+ block_on_close = False
+
+ def __init__(self, scheduler=None):
+ self.scheduler = scheduler
+ self.events = []
+ super().__init__(('127.0.0.1', 0), Handler)
+ self.thread = threading.Thread(target=self.serve_forever, daemon=True)
+ self.thread.start()
+
+ @property
+ def uri(self):
+ return f'ipp://127.0.0.1:{self.server_address[1]}/ipp/print'
+
+ def reply(self, operation, fields):
+ self.events.append((operation, dict(fields)))
+ if self.scheduler:
+ return self.scheduler.reply(operation, fields)
+ assert operation == 11, 'only the explicitly selected printer may be probed'
+ response = struct.pack('!BBHI', 2, 0, 0, fields['_request_id']) + b'\x01'
+ response += attribute(0x47, 'attributes-charset', 'utf-8') + attribute(0x48, 'attributes-natural-language', 'en')
+ response += b'\x04' + attribute(0x23, 'printer-state', 3)
+ response += attribute(0x49, 'document-format-supported', 'application/pdf')
+ response += attribute(0x44, 'ipp-features-supported', 'ipp-everywhere')
+ return 200, response + b'\x03'
+
+ def close(self):
+ self.shutdown()
+ self.server_close()
+ self.thread.join(timeout=2)
+
+
+def run(scale):
+ with tempfile.TemporaryDirectory(prefix='rediwm-printers-') as directory:
+ tmp = Path(directory)
+ scheduler = Scheduler(tmp / 'cups.sock')
+ process, log = spawn_compositor(tmp, scale=scale, config_content='[compositor]\nxwayland = false\n', env_extra={
+ 'CUPS_SERVER': str(tmp / 'cups.sock'), 'CUPS_USER': scheduler.username, 'CUPS_ENCRYPTION': 'Never',
+ 'HOME': str(tmp), 'XDG_CONFIG_HOME': str(tmp / 'config'),
+ 'XDG_DATA_HOME': str(tmp / 'data'), 'XDG_CACHE_HOME': str(tmp / 'cache'),
+ 'DBUS_SESSION_BUS_ADDRESS': '', 'PIPEWIRE_RUNTIME_DIR': str(tmp),
+ 'DBUS_SYSTEM_BUS_ADDRESS': '',
+ 'PULSE_SERVER': 'unix:/nonexistent-rediwm-printers-test-pulse',
+ })
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ ui = UIDriver(ipc)
+
+ def named(name):
+ return ui.find(name, panel='control_center')
+
+ def labels():
+ return [widget.get('label') or '' for widget in ui.widgets('control_center')]
+
+ def click(name):
+ wait_for(lambda: not named(name)['is_disabled'], name + ' enabled')
+ widget = ui.scroll_into_view(name, panel='control_center')
+ ui.click(widget, panel='control_center')
+ if widget['role'] != 'select':
+ ui.wait_settled('control_center')
+
+ def ready():
+ wait_for(lambda: named('printers_status')['label'] == 'Connected to CUPS.', 'CUPS ready', timeout=15)
+
+ def refresh():
+ before = len(scheduler.calls())
+ click('printers_refresh')
+ wait_for(lambda: len(scheduler.calls()) > before, 'refresh reached private CUPS')
+ ready()
+
+ def error_finished():
+ def finished():
+ text = named('printers_status')['label']
+ return text and text not in ('Connected to CUPS.', 'Loading printers…')
+ return wait_for(finished, 'visible CUPS error', timeout=15)
+
+ ipc.open_control_center()
+ ui.wait_settled('control_center')
+ assert not scheduler.calls(), 'CUPS must remain untouched until Printers is shown'
+ assert not printer_workers(process), 'printer worker must not exist before its page is shown'
+ click('printers')
+ ready()
+ assert any(operation == 0x4002 for operation, _ in scheduler.calls())
+ assert any(operation == 0x000a and fields.get('my-jobs') is True and fields.get('which-jobs') == 'all'
+ for operation, fields in scheduler.calls()), scheduler.calls()
+ click('printers_queue_0')
+ assert any('Label' in text for text in labels()), labels()
+ assert any('No pages were found.' in text for text in labels()), labels()
+ assert not any('PRIVATE-DOCUMENT' in text for text in labels()), labels()
+ assert not any(widget.get('name') == 'printers_cancel_18' for widget in ui.widgets()), 'another user\'s job must not be cancellable'
+ if preview := os.environ.get('REDIWM_PRINTERS_PREVIEW'):
+ captured = tmp / 'printers-preview.png'
+ ipc.screenshot(str(captured))
+ Path(preview).write_bytes(captured.read_bytes())
+ click('printers_queue_1')
+ assert 'Resolution: Unavailable' in labels(), 'hostile dpcm resolution must be unavailable, without overflowing'
+ click('printers_queue_0')
+
+ # Check the worker itself, as well as scheduler request count:
+ # an idle timer can wake without issuing a CUPS request.
+ count = len(scheduler.calls())
+ before_idle = printer_workers(process)
+ assert len(before_idle) == 1, before_idle
+ time.sleep(1)
+ assert len(scheduler.calls()) == count, scheduler.calls()
+ after_idle = printer_workers(process)
+ assert before_idle.keys() == after_idle.keys(), 'idle printer worker was replaced or exited'
+ for task, before in before_idle.items():
+ deltas = tuple(after - previous for after, previous in zip(after_idle[task], before))
+ assert all(delta >= 0 for delta in deltas) and sum(deltas) <= 2, f'idle printer worker context switches: {deltas}'
+ print('Printer worker idle context-switch deltas: voluntary=%d involuntary=%d' % deltas)
+
+ click('printers_copy_report')
+ copied = subprocess.check_output(['wl-paste', '--no-newline'], env={
+ **os.environ, 'XDG_RUNTIME_DIR': str(tmp), 'WAYLAND_DISPLAY': wayland_display_name(tmp),
+ }, timeout=5).decode()
+ assert copied.startswith('RediWM printer diagnostics\n'), copied
+ assert 'Queue state: idle; accepting: yes' in copied, copied
+ assert 'Label_Test' not in copied, copied
+ assert 'fixture-password' not in copied and 'private-printer.invalid' not in copied, copied
+ assert 'PRIVATE-DOCUMENT' not in copied, copied
+
+ click('printers_cancel_17')
+ wait_for(lambda: any(operation == 8 and fields.get('job-id') == 17 for operation, fields in scheduler.calls()), 'own job cancellation')
+ ready()
+ scheduler.configure(cancelled=False, denied=True)
+ refresh()
+ click('printers_cancel_17')
+ wait_for(lambda: 'CUPS denied permission. The operation requires authorization.' in labels(), 'cancellation permission error')
+
+ scheduler.configure(denied=False, stopped=True)
+ refresh()
+ assert any('Out of paper' in text for text in labels()), labels()
+ scheduler.configure(empty=True)
+ refresh()
+ assert 'No printers configured.' in labels(), labels()
+ scheduler.configure(empty=False, fault='malformed')
+ click('printers_refresh')
+ error_finished()
+ scheduler.configure(fault='http')
+ click('printers_refresh')
+ error_finished()
+ scheduler.configure(fault='')
+ refresh()
+
+ scheduler.configure(fault='stall')
+ before = len(scheduler.calls())
+ click('printers_refresh')
+ wait_for(lambda: len(scheduler.calls()) > before, 'stalled request reached CUPS')
+ started = time.monotonic()
+ ipc.get_shell_state()
+ assert time.monotonic() - started < 2, 'a stalled CUPS must not block compositor IPC'
+ error_finished()
+ scheduler.configure(fault='')
+ scheduler.release.set()
+ refresh()
+
+ # Leaving the page must cancel an outstanding socket deadline.
+ scheduler.release.clear()
+ scheduler.configure(fault='stall')
+ before = len(scheduler.calls())
+ click('printers_refresh')
+ wait_for(lambda: len(scheduler.calls()) > before, 'in-flight request before hide')
+ started = time.monotonic()
+ click('shortcuts')
+ assert time.monotonic() - started < 2, 'hiding Printers must cancel blocked I/O promptly'
+ assert not printer_workers(process), 'hiding Printers must join its worker'
+ scheduler.configure(fault='')
+ scheduler.release.set()
+ count = len(scheduler.calls())
+ time.sleep(1)
+ assert len(scheduler.calls()) == count, 'hidden Printers must release its activity'
+ click('printers')
+ ready()
+ wait_for(lambda: len(scheduler.calls()) > count, 'refresh when shown again')
+ window = next(window for window in ipc.get_windows() if window.get('app_id') == 'rediwm-settings')
+ ipc.close_window(window['id'])
+ count = len(scheduler.calls())
+ time.sleep(1)
+ assert len(scheduler.calls()) == count, 'closed Settings must stop CUPS work'
+ assert not printer_workers(process), 'closing Settings must join the printer worker'
+ stop_process(process)
+ log.flush()
+ contents = (tmp / 'compositor.log').read_text()
+ assert ' leaked:' not in contents and 'memory address' not in contents, contents[-3000:]
+ print('Printers Settings passed at scale', scale)
+ except Exception:
+ log.flush()
+ Path('/tmp/rediwm-printers-compositor.log').write_text((tmp / 'compositor.log').read_text())
+ raise
+ finally:
+ if process.poll() is None:
+ stop_process(process)
+ log.close()
+ scheduler.close()
+
+
+def endpoint_errors(scale):
+ # An unsupported TCP endpoint is our own listener, so even a regression
+ # cannot contact a real scheduler. It must remain unconnected.
+ with socket.socket() as listener:
+ listener.bind(('127.0.0.1', 0))
+ listener.listen(1)
+ listener.setblocking(False)
+ for endpoint in ('missing', f'ipps://127.0.0.1:{listener.getsockname()[1]}'):
+ with tempfile.TemporaryDirectory(prefix='rediwm-printers-endpoint-') as directory:
+ tmp = Path(directory)
+ configured = str(tmp / 'missing-cups.sock') if endpoint == 'missing' else endpoint
+ process, log = spawn_compositor(tmp, scale=scale, config_content='[compositor]\nxwayland = false\n', env_extra={
+ 'CUPS_SERVER': configured, 'CUPS_ENCRYPTION': 'Never', 'HOME': str(tmp),
+ 'XDG_CONFIG_HOME': str(tmp / 'config'), 'XDG_DATA_HOME': str(tmp / 'data'),
+ 'XDG_CACHE_HOME': str(tmp / 'cache'), 'DBUS_SESSION_BUS_ADDRESS': '',
+ 'DBUS_SYSTEM_BUS_ADDRESS': '',
+ 'PIPEWIRE_RUNTIME_DIR': str(tmp), 'PULSE_SERVER': 'unix:/nonexistent-rediwm-printers-test-pulse',
+ })
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ ui = UIDriver(ipc)
+ ipc.open_control_center()
+ ui.wait_settled('control_center')
+ ui.click(ui.find('printers', panel='control_center'), panel='control_center')
+ def expected_error():
+ text = ui.find('printers_status', panel='control_center').get('label', '') or ''
+ return ('unavailable' in text.lower() or 'not running' in text.lower()) if endpoint == 'missing' else ('encrypted' in text.lower() or 'unsupported' in text.lower() or 'not supported' in text.lower())
+ wait_for(expected_error, 'missing or encrypted server error', timeout=15)
+ try:
+ connection, _ = listener.accept()
+ except BlockingIOError:
+ pass
+ else:
+ connection.close()
+ raise AssertionError('unsupported CUPS_SERVER must fail before a TCP connection')
+ except Exception:
+ log.flush()
+ Path('/tmp/rediwm-printers-endpoint-compositor.log').write_text((tmp / 'compositor.log').read_text())
+ raise
+ finally:
+ stop_process(process)
+ log.close()
+ print('Missing and unsupported CUPS endpoints passed at scale', scale)
+
+
+# Independent private fixture, with no service activation file and no access to
+# the system bus. Its method shapes mirror cups-pk-helper's actual ABI.
+FAKE_HELPER = r'''
+import json, os, sys
+from pathlib import Path
+from gi.repository import Gio, GLib
+name = 'org.opensuse.CupsPkHelper.Mechanism'
+root = Path(os.environ['PRINTER_FIXTURE_ROOT'])
+state_path = root / 'queues.json'
+methods = {
+ 'DevicesGet': ('iiasas', 'sa{ss}'),
+ 'PrinterAdd': ('sssss', 's'), 'PrinterDelete': ('s', 's'),
+ 'PrinterSetEnabled': ('sb', 's'), 'PrinterSetAcceptJobs': ('sbs', 's'),
+ 'PrinterSetDefault': ('s', 's'), 'PrinterSetInfo': ('ss', 's'), 'PrinterRename': ('ss', 's'),
+ 'PrinterSetDevice': ('ss', 's'),
+ 'PrinterAddOptionDefault': ('ssas', 's'), 'PrinterDeleteOptionDefault': ('ss', 's'),
+ 'PrinterAddOption': ('ssas', 's'),
+}
+def signatures(signature):
+ if signature == 'iiasas': return ['i', 'i', 'as', 'as']
+ if signature == 'sa{ss}': return ['s', 'a{ss}']
+ if signature == 'ssas': return ['s', 's', 'as']
+ return list(signature)
+xml = '<node><interface name="' + name + '">'
+for method, (inputs, outputs) in methods.items():
+ xml += '<method name="' + method + '">'
+ for direction, signature in [('in', inputs), ('out', outputs)]:
+ for typ in signatures(signature): xml += '<arg type="' + typ + '" direction="' + direction + '"/>'
+ xml += '</method>'
+xml += '</interface></node>'
+conn = Gio.bus_get_sync(Gio.BusType.SESSION)
+def record(method, args):
+ with (root / 'helper.jsonl').open('a') as output: output.write(json.dumps([method, args]) + '\n')
+def called(connection, sender, path, interface, method, parameters, invocation):
+ args = parameters.unpack()
+ record(method, args)
+ if (root / 'deny').exists():
+ invocation.return_dbus_error(name + '.NotPrivileged', 'Fixture refused authorization')
+ return
+ if method == 'DevicesGet':
+ assert args[0] > 0 and args[1] <= 128 and args[2] == [] and set(args[3]) == {'file', 'smb', 'smbs', 'pdf', 'pipe', 'exec', 'command', 'beh', 'hpfax', 'mailto'}
+ invocation.return_value(GLib.Variant('(sa{ss})', ('', {
+ 'device-uri:0': 'usb://Fixture/Label?serial=setup-only', 'device-info:0': 'Fixture detected label',
+ 'device-make-and-model:0': 'Fixture Label', 'device-id:0': 'MFG:Fixture;MDL:Label;CMD:TSPL;',
+ 'device-class:0': 'direct',
+ 'device-uri:1': os.environ['PRINTER_FIXTURE_NETWORK_URI'], 'device-info:1': 'Fixture network printer',
+ 'device-make-and-model:1': 'Fixture Office', 'device-id:1': 'MFG:Fixture;MDL:Office;CMD:POSTSCRIPT;',
+ 'device-class:1': 'network',
+ # These are unsupported backends, never selectable in the add UI.
+ 'device-uri:2': 'file:/tmp/must-not-print', 'device-info:2': 'Forbidden file backend',
+ 'device-uri:3': 'smb://user:[email protected]/queue', 'device-info:3': 'Forbidden SMB backend',
+ 'device-uri:4': 'tspl:/dev/usb/lp0', 'device-info:4': 'Fixture vendor label',
+ 'device-make-and-model:4': 'Fixture Label', 'device-id:4': 'MFG:Fixture;MDL:Label;CMD:TSPL;',
+ 'device-class:4': 'direct',
+ })))
+ return
+ state = json.loads(state_path.read_text())
+ queues = state['queues']
+ key = args[0]
+ if method == 'PrinterAdd':
+ assert key not in queues, 'the UI must never upsert an existing queue'
+ assert args[1].startswith(('ipp://', 'ipps://', 'socket://', 'lpd://', 'usb://', 'dnssd://', 'tspl:/'))
+ queues[key] = {'uri': args[1], 'ppd': args[2], 'info': args[3], 'enabled': False, 'accepting': False, 'options': {}}
+ elif key not in queues:
+ invocation.return_value(GLib.Variant('(s)', ('Unknown queue',)))
+ return
+ elif method == 'PrinterDelete': del queues[key]
+ elif method == 'PrinterSetEnabled': queues[key]['enabled'] = args[1]
+ elif method == 'PrinterSetAcceptJobs': queues[key]['accepting'] = args[1]
+ elif method == 'PrinterSetDefault': state['default'] = key
+ elif method == 'PrinterSetInfo': queues[key]['info'] = args[1]
+ elif method == 'PrinterSetDevice': queues[key]['uri'] = args[1]
+ elif method == 'PrinterRename':
+ if any(existing.lower() == args[1].lower() for existing in queues):
+ invocation.return_value(GLib.Variant('(s)', ('Queue already exists',)))
+ return
+ queues[args[1]] = queues.pop(key)
+ if state.get('default') == key: state['default'] = args[1]
+ elif method == 'PrinterAddOptionDefault': queues[key].setdefault('overrides', {})[args[1]] = args[2][0]
+ elif method == 'PrinterAddOption':
+ option, value = args[1], args[2][0]
+ queues[key]['options'][option] = value
+ alias = {'Resolution': 'printer-resolution', 'SetResolution': 'printer-resolution', 'JCLResolution': 'printer-resolution', 'CNRes_PGP': 'printer-resolution', 'PageSize': 'media', 'PageRegion': 'media', 'Duplex': 'sides', 'ColorModel': 'print-color-mode', 'cupsPrintQuality': 'print-quality'}.get(option)
+ if alias:
+ if alias == 'media': value = {'A4': 'iso_a4_210x297mm', '4x6': 'na_index-4x6_4x6in'}[value]
+ elif alias == 'sides': value = {'None': 'one-sided', 'DuplexNoTumble': 'two-sided-long-edge'}[value]
+ elif alias == 'print-color-mode': value = {'Gray': 'monochrome', 'RGB': 'color'}[value]
+ elif alias == 'print-quality': value = {'Draft': '3', 'Normal': '4', 'High': '5'}[value]
+ queues[key]['options'][alias] = value
+ elif method == 'PrinterDeleteOptionDefault': queues[key].setdefault('overrides', {}).pop(args[1], None)
+ pending = state_path.with_suffix('.pending')
+ pending.write_text(json.dumps(state))
+ pending.replace(state_path)
+ invocation.return_value(GLib.Variant('(s)', ('',)))
+conn.register_object('/', Gio.DBusNodeInfo.new_for_xml(xml).interfaces[0], called, None, None)
+reply = conn.call_sync('org.freedesktop.DBus', '/org/freedesktop/DBus', 'org.freedesktop.DBus', 'RequestName', GLib.Variant('(su)', (name, 0)), None, Gio.DBusCallFlags.NONE, -1, None)
+assert reply.unpack()[0] == 1
+service_xml = """<node><interface name='org.freedesktop.systemd1.Manager'>
+<method name='StartUnit'><arg type='s' direction='in'/><arg type='s' direction='in'/><arg type='o' direction='out'/></method>
+</interface></node>"""
+def service_called(connection, sender, path, interface, method, parameters, invocation):
+ args = parameters.unpack()
+ assert method == 'StartUnit' and args == ('cups.service', 'replace'), (method, args)
+ record(method, args)
+ invocation.return_value(GLib.Variant('(o)', ('/org/freedesktop/systemd1/job/1',)))
+conn.register_object('/org/freedesktop/systemd1', Gio.DBusNodeInfo.new_for_xml(service_xml).interfaces[0], service_called, None, None)
+reply = conn.call_sync('org.freedesktop.DBus', '/org/freedesktop/DBus', 'org.freedesktop.DBus', 'RequestName', GLib.Variant('(su)', ('org.freedesktop.systemd1', 0)), None, Gio.DBusCallFlags.NONE, -1, None)
+assert reply.unpack()[0] == 1
+def stdin_ready(*_):
+ command = sys.stdin.readline().strip()
+ if command == 'notify':
+ conn.emit_signal(None, '/org/cups/cupsd/Notifier', 'org.cups.cupsd.Notifier', 'PrinterStateChanged', GLib.Variant('(s)', ('Forged desktop-user hint',)))
+ conn.flush_sync(None)
+ print('notified', flush=True)
+ return True
+GLib.io_add_watch(sys.stdin, GLib.IO_IN, stdin_ready)
+print('ready', flush=True)
+GLib.MainLoop().run()
+'''
+
+
+# The helper's actual ABI targets the system's default local scheduler. Redirect
+# only that socket in this noninstalled fixture so production enforces exactly
+# the same canonical-server gate in the test, without touching a host cupsd.
+CUPS_CONNECT_HOOK = r'''
+#define _GNU_SOURCE
+#include <dlfcn.h>
+#include <errno.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+int connect(int fd, const struct sockaddr *address, socklen_t length) {
+ int (*real_connect)(int, const struct sockaddr *, socklen_t) = dlsym(RTLD_NEXT, "connect");
+ if (!real_connect) { errno = EIO; return -1; }
+ if (address && address->sa_family == AF_UNIX && length > offsetof(struct sockaddr_un, sun_path)) {
+ const struct sockaddr_un *local = (const struct sockaddr_un *)address;
+ size_t available = length - offsetof(struct sockaddr_un, sun_path);
+ if (available > sizeof(local->sun_path)) available = sizeof(local->sun_path);
+ size_t size = strnlen(local->sun_path, available);
+ if ((size == 19 && memcmp(local->sun_path, "/run/cups/cups.sock", 19) == 0) ||
+ (size == 23 && memcmp(local->sun_path, "/var/run/cups/cups.sock", 23) == 0)) {
+ const char *redirect = getenv("PRINTER_FIXTURE_CUPS_SOCKET");
+ if (!redirect || !*redirect || strlen(redirect) >= sizeof(local->sun_path)) { errno = EINVAL; return -1; }
+ struct sockaddr_un target = { .sun_family = AF_UNIX };
+ strcpy(target.sun_path, redirect);
+ return real_connect(fd, (const struct sockaddr *)&target, offsetof(struct sockaddr_un, sun_path) + strlen(redirect) + 1);
+ }
+ }
+ return real_connect(fd, address, length);
+}
+'''
+
+
+class SetupScheduler(Scheduler):
+ """Queues shared with the private helper; documents never leave memory."""
+ def __init__(self, path, state):
+ self.state_path = state
+ self.printed = []
+ self.next_job = 40
+ self.active_job = False
+ self.active_job_state = 3
+ self.jobs_denied = False
+ super().__init__(path)
+
+ def state(self):
+ return json.loads(self.state_path.read_text())
+
+ @staticmethod
+ def effective(queue):
+ options = queue.get('options', {})
+ return {
+ 'media': options.get('media', 'iso_a4_210x297mm' if options.get('PageSize') == 'A4' else 'na_index-4x6_4x6in'),
+ 'resolution': options.get('printer-resolution', options.get('Resolution', '300dpi')),
+ 'sides': options.get('sides', 'two-sided-long-edge' if options.get('Duplex') == 'DuplexNoTumble' else 'one-sided'),
+ 'color': options.get('print-color-mode', 'color' if options.get('ColorModel') == 'RGB' else 'monochrome'),
+ 'quality': options.get('print-quality', {'Draft': '3', 'Normal': '4', 'High': '5'}.get(options.get('cupsPrintQuality'), '4')),
+ 'darkness': options.get('Darkness', '8'),
+ }
+
+ def reply(self, operation, fields):
+ with self.lock:
+ self.events.append((operation, dict(fields)))
+ if self.fault == 'http':
+ return 503, b'Fixture CUPS stopped'
+ if operation == 2:
+ self.next_job += 1
+ self.printed.append(dict(fields, id=self.next_job))
+ job = self.next_job
+ status = 0x0403 if operation == 0x000a and self.jobs_denied else 0
+ response = struct.pack('!BBHI', 2, 0, status, fields['_request_id'])
+ response += b'\x01' + attribute(0x47, 'attributes-charset', 'utf-8') + attribute(0x48, 'attributes-natural-language', 'en')
+ if status:
+ return 200, response + attribute(0x41, 'status-message', 'Fixture job query denied') + b'\x03'
+ state = self.state()
+ if operation in (0x4002, 0x000b):
+ for key, queue in state['queues'].items():
+ if operation == 0x000b and not fields.get('printer-uri', '').endswith('/' + key):
+ continue
+ options = self.effective(queue)
+ response += b'\x04' + attribute(0x42, 'printer-name', key)
+ response += attribute(0x41, 'printer-info', queue.get('info', key))
+ response += attribute(0x41, 'printer-make-and-model', 'Fixture thermal printer' if key == 'Label_Test' else 'Fixture office printer')
+ response += attribute(0x45, 'printer-uri-supported', 'ipp://localhost/printers/' + key)
+ response += attribute(0x45, 'device-uri', queue['uri'])
+ response += attribute(0x41, 'printer-device-id', 'MFG:Fixture;MDL:Label;CMD:TSPL;')
+ response += attribute(0x23, 'printer-state', 3 if queue.get('enabled', True) else 5)
+ response += attribute(0x22, 'printer-is-accepting-jobs', queue.get('accepting', True))
+ response += attribute(0x44, 'printer-state-reasons', 'none')
+ response += attribute(0x41, 'printer-state-message', 'Ready')
+ response += attribute(0x23, 'printer-type', 0x20000 if state.get('default') == key else 0)
+ response += attribute(0x44, 'media-default', options['media'])
+ response += attribute(0x44, 'media-supported', 'na_index-4x6_4x6in') + attribute(0x44, '', 'iso_a4_210x297mm')
+ dpi = int(options['resolution'].removesuffix('dpi').split('x')[0])
+ response += attribute(0x32, 'printer-resolution-default', (dpi, dpi, 3))
+ response += attribute(0x32, 'printer-resolution-supported', (203, 203, 3)) + attribute(0x32, '', (300, 300, 3))
+ response += attribute(0x44, 'print-color-mode-default', options['color'])
+ response += attribute(0x44, 'print-color-mode-supported', 'monochrome') + attribute(0x44, '', 'color')
+ response += attribute(0x44, 'sides-default', options['sides'])
+ response += attribute(0x44, 'sides-supported', 'one-sided') + attribute(0x44, '', 'two-sided-long-edge')
+ response += attribute(0x23, 'print-quality-default', int(options['quality']))
+ response += attribute(0x23, 'print-quality-supported', 3) + attribute(0x23, '', 4) + attribute(0x23, '', 5)
+ response += attribute(0x49, 'document-format-supported', 'application/pdf')
+ elif operation == 0x400c:
+ response += b'\x04' + attribute(0x42, 'ppd-name', 'fixture-label.ppd')
+ response += attribute(0x41, 'ppd-make-and-model', 'Fixture Label')
+ response += attribute(0x41, 'ppd-device-id', 'MFG:Fixture;MDL:Label;CMD:TSPL;')
+ response += b'\x04' + attribute(0x42, 'ppd-name', 'fixture-office.ppd')
+ response += attribute(0x41, 'ppd-make-and-model', 'Fixture Office')
+ response += attribute(0x41, 'ppd-device-id', 'MFG:Fixture;MDL:Office;CMD:POSTSCRIPT;')
+ elif operation == 2:
+ response += b'\x02' + attribute(0x21, 'job-id', job) + attribute(0x23, 'job-state', 9)
+ elif operation == 0x000a and self.active_job:
+ response += b'\x02' + attribute(0x21, 'job-id', 19) + attribute(0x23, 'job-state', self.active_job_state)
+ response += attribute(0x42, 'job-originating-user-name', self.username)
+ response += attribute(0x45, 'job-printer-uri', 'ipp://localhost/printers/Label_Test')
+ elif operation == 0x0016:
+ response += b'\x06' + attribute(0x21, 'notify-subscription-id', 23)
+ elif operation == 0x0018:
+ response += b'\x06' + attribute(0x21, 'notify-subscription-id', 23)
+ response += attribute(0x21, 'notify-lease-duration', 0)
+ response += b'\x03'
+ if operation == 0x400f:
+ queue_name = fields.get('printer-uri', '').rsplit('/', 1)[-1]
+ options = self.effective(state['queues'].get(queue_name, {}))
+ response += ('''*PPD-Adobe: "4.3"
+*OpenGroup: General/General options
+*OpenUI *PageSize/Paper size: PickOne
+*DefaultPageSize: {page_size}
+*PageSize 4x6/4 x 6 inch: ""
+*PageSize A4/A4: ""
+*CloseUI: *PageSize
+*PaperDimension 4x6: "288 432"
+*ImageableArea 4x6: "0 0 288 432"
+*PaperDimension A4: "595.276 841.89"
+*ImageableArea A4: "12 12 583.276 829.89"
+*OpenUI *Resolution/Resolution: PickOne
+*DefaultResolution: {resolution}
+*Resolution 203dpi/203 dpi: ""
+*Resolution 300dpi/300 dpi: ""
+*CloseUI: *Resolution
+*OpenUI *Duplex/Two-sided printing: PickOne
+*DefaultDuplex: {duplex}
+*Duplex None/One-sided: ""
+*Duplex DuplexNoTumble/Two-sided, long edge: ""
+*CloseUI: *Duplex
+*OpenUI *ColorModel/Colour: PickOne
+*DefaultColorModel: {color}
+*ColorModel Gray/Black and white: ""
+*ColorModel RGB/Colour: ""
+*CloseUI: *ColorModel
+*OpenUI *cupsPrintQuality/Quality: PickOne
+*DefaultcupsPrintQuality: {quality}
+*cupsPrintQuality Draft/Draft: ""
+*cupsPrintQuality Normal/Normal: ""
+*cupsPrintQuality High/High: ""
+*CloseUI: *cupsPrintQuality
+*CloseGroup: General
+*OpenGroup: Label/Label options
+*OpenUI *Darkness/Darkness: PickOne
+*DefaultDarkness: {darkness}
+*Darkness 8/8: ""
+*Darkness 12/12: ""
+*CloseUI: *Darkness
+*CloseGroup: Label
+'''.format(
+ page_size='A4' if options['media'] == 'iso_a4_210x297mm' else '4x6',
+ resolution=options['resolution'],
+ duplex='DuplexNoTumble' if options['sides'] == 'two-sided-long-edge' else 'None',
+ color='RGB' if options['color'] == 'color' else 'Gray',
+ quality={'3': 'Draft', '4': 'Normal', '5': 'High'}[str(options['quality'])],
+ darkness=options['darkness'],
+ )).encode()
+ return 200, response
+
+
+def setup_and_tools(scale, queue_rename=True, preview=False):
+ with tempfile.TemporaryDirectory(prefix='rediwm-printer-setup-') as directory:
+ tmp = Path(directory)
+ network = TcpEndpoint()
+ state_path = tmp / 'queues.json'
+ state_path.write_text(json.dumps({'queues': {
+ 'Label_Test': {'uri': 'usb://Fixture/Label?serial=existing', 'enabled': False, 'accepting': False, 'info': 'Fixture Label', 'options': {}},
+ 'Office_Test': {'uri': network.uri, 'enabled': True, 'accepting': True, 'info': 'Fixture Office', 'options': {'printer-resolution': '203dpi'}},
+ }, 'default': 'Office_Test'}))
+ scheduler = SetupScheduler(tmp / 'cups.sock', state_path)
+ hook_source = tmp / 'cups_connect.c'
+ hook_source.write_text(CUPS_CONNECT_HOOK)
+ hook = tmp / 'cups_connect.so'
+ subprocess.run(['cc', '-shared', '-fPIC', '-o', str(hook), str(hook_source), '-ldl'], check=True)
+ bus = subprocess.Popen(['dbus-daemon', '--session', '--nofork', '--print-address=1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ helper = None
+ process = log = None
+ try:
+ assert select.select([bus.stdout], [], [], 10)[0], 'private printer bus startup'
+ address = bus.stdout.readline().strip()
+ assert address.startswith('unix:'), address
+ fixture = tmp / 'helper.py'
+ fixture.write_text(FAKE_HELPER)
+ helper = subprocess.Popen([sys.executable, str(fixture)], env={**os.environ, 'DBUS_SESSION_BUS_ADDRESS': address, 'PRINTER_FIXTURE_ROOT': str(tmp), 'PRINTER_FIXTURE_NETWORK_URI': network.uri}, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ assert select.select([helper.stdout], [], [], 10)[0], 'private cups-pk-helper startup'
+ assert helper.stdout.readline().strip() == 'ready', helper.stderr.read() if helper.poll() is not None else 'helper startup failed'
+ process, log = spawn_compositor(tmp, scale=scale, config_content='[compositor]\nxwayland = false\n', env_extra={
+ 'CUPS_SERVER': '/run/cups/cups.sock', 'CUPS_USER': scheduler.username, 'CUPS_ENCRYPTION': 'Never',
+ 'LD_PRELOAD': str(hook), 'PRINTER_FIXTURE_CUPS_SOCKET': str(tmp / 'cups.sock'),
+ 'HOME': str(tmp), 'XDG_CONFIG_HOME': str(tmp / 'config'), 'XDG_DATA_HOME': str(tmp / 'data'), 'XDG_CACHE_HOME': str(tmp / 'cache'),
+ 'DBUS_SESSION_BUS_ADDRESS': '', 'DBUS_SYSTEM_BUS_ADDRESS': address,
+ 'PIPEWIRE_RUNTIME_DIR': str(tmp), 'PULSE_SERVER': 'unix:/nonexistent-rediwm-printers-test-pulse',
+ })
+ with IPCClient(tmp, timeout=15) as ipc:
+ ui = UIDriver(ipc)
+ def labels(): return [widget.get('label') or '' for widget in ui.widgets()]
+ def named(name): return ui.find(name, panel='control_center')
+ def click(name):
+ def enabled():
+ try: return not named(name)['is_disabled']
+ except LookupError: return False
+ try:
+ wait_for(enabled, name + ' enabled', timeout=15)
+ except AssertionError:
+ Path('/tmp/rediwm-printer-setup-widgets.json').write_text(json.dumps(ui.widgets(), indent=2))
+ Path('/tmp/rediwm-printer-setup-failure.png').unlink(missing_ok=True)
+ ipc.screenshot('/tmp/rediwm-printer-setup-failure.png')
+ raise AssertionError(name + ' unavailable; visible labels: ' + repr(labels()))
+ widget = ui.scroll_into_view(name, panel='control_center')
+ ui.click(widget, panel='control_center')
+ if widget['role'] != 'select':
+ ui.wait_settled('control_center')
+ def fill(name, value):
+ click(name)
+ ipc.key(29, True)
+ ipc.key_press('a')
+ ipc.key(29, False)
+ ipc.type_text(value)
+ def calls():
+ path = tmp / 'helper.jsonl'
+ return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else []
+ def called(member, predicate=lambda args: True):
+ return any(method == member and predicate(args) for method, args in calls())
+ def ready(): wait_for(lambda: named('printers_status')['label'] == 'Connected to CUPS.', 'CUPS ready', timeout=15)
+ def quiet_inventory():
+ previous = len(scheduler.calls())
+ since = time.monotonic()
+ def quiet():
+ nonlocal previous, since
+ count = len(scheduler.calls())
+ if count != previous:
+ previous, since = count, time.monotonic()
+ return time.monotonic() - since >= .5
+ wait_for(quiet, 'automatic inventory refresh settles', timeout=10)
+ return previous
+ ipc.open_control_center()
+ ui.wait_settled('control_center')
+ assert not calls() and not scheduler.calls(), 'opening Settings must not administer or contact CUPS'
+ click('printers')
+ ready()
+ click('printers_queue_0')
+ click('printers_resume')
+ wait_for(lambda: called('PrinterSetEnabled', lambda args: args == ['Label_Test', True]), 'resume queue')
+ click('printers_accepting')
+ wait_for(lambda: called('PrinterSetAcceptJobs', lambda args: args == ['Label_Test', True, '']), 'allow jobs')
+ ready()
+ wait_for(lambda: named('printers_accepting')['label'] == 'Stop accepting jobs', 'accepted queue appears in refreshed state')
+ if preview:
+ ui.scroll_into_view('printers_queue_0', panel='control_center')
+ ui.wait_settled('control_center')
+ Path('/tmp/rediwm-printers-setup-top.png').unlink(missing_ok=True)
+ ipc.screenshot('/tmp/rediwm-printers-setup-top.png')
+ wait_for(lambda: any(operation == 0x0016 for operation, _ in scheduler.calls()), 'page-owned CUPS subscription')
+ count = quiet_inventory()
+ helper.stdin.write('notify\n')
+ helper.stdin.flush()
+ assert select.select([helper.stdout], [], [], 5)[0], 'private forged notifier delivery'
+ assert helper.stdout.readline().strip() == 'notified'
+ time.sleep(.4)
+ assert len(scheduler.calls()) == count, f'a desktop user cannot impersonate the privileged CUPS notifier; extra operations: {[hex(operation) for operation, _ in scheduler.calls()[count:]]}'
+
+ # Repair a queue's connection through the helper, first with a
+ # typed network URI and then an exact CUPS-discovered USB URI.
+ click('printers_connection')
+ fill('printers_address', network.uri)
+ click('printers_connection_apply')
+ wait_for(lambda: called('PrinterSetDevice', lambda args: args == ['Label_Test', network.uri]), 'typed connection update')
+ wait_for(lambda: scheduler.state()['queues']['Label_Test']['uri'] == network.uri, 'connection update refresh')
+ click('printers_connection')
+ click('printers_discover')
+ wait_for(lambda: 'Printer discovery complete.' in labels(), 'connection device discovery')
+ click('printers_device_0')
+ click('printers_connection_apply')
+ wait_for(lambda: called('PrinterSetDevice', lambda args: args == ['Label_Test', 'usb://Fixture/Label?serial=setup-only']), 'exact discovered connection update')
+ wait_for(lambda: scheduler.state()['queues']['Label_Test']['uri'] == 'usb://Fixture/Label?serial=setup-only', 'discovered connection commit')
+
+ # All physical-output actions require a separate confirmation.
+ assert not scheduler.printed, 'showing and resuming a queue must never print'
+ click('printers_test_page')
+ assert not scheduler.printed, 'opening print confirmation must not submit a job'
+ click('printers_test_confirm')
+ wait_for(lambda: len(scheduler.printed) == 1, 'confirmed driver test')
+ assert scheduler.printed[0]['document-format'] == 'application/pdf', scheduler.printed
+ assert scheduler.printed[0]['_document'].startswith(b'%PDF-'), scheduler.printed
+ assert scheduler.printed[0]['printer-uri'].endswith('/Label_Test'), scheduler.printed
+ click('printers_test_blank')
+ click('printers_test_raw')
+ assert len(scheduler.printed) == 1, 'raw test must require its own confirmation'
+ click('printers_test_confirm')
+ wait_for(lambda: len(scheduler.printed) == 2, 'confirmed raw language sample')
+ assert scheduler.printed[1]['document-format'] == 'application/vnd.cups-raw', scheduler.printed
+ assert scheduler.printed[1]['_document'].startswith(b'SIZE ') and scheduler.printed[1]['_document'].endswith(b'PRINT 1,1\r\n'), scheduler.printed
+ click('printers_test_printed')
+ wait_for(lambda: any('raw sample printed but the driver test did not' in label for label in labels()), 'driver versus backend result explanation')
+
+ click('printers_label')
+ click('printers_check_scale')
+ assert len(scheduler.printed) == 2, 'ruler must require its own confirmation'
+ click('printers_test_confirm')
+ wait_for(lambda: len(scheduler.printed) == 3, 'confirmed ruler test')
+ assert scheduler.printed[2]['document-format'] == 'application/pdf' and scheduler.printed[2]['_document'].startswith(b'%PDF-'), scheduler.printed
+ assert scheduler.printed[2]['print-scaling'] == 'none', scheduler.printed
+ click('printers_test_printed')
+ ready()
+ click('printers_queue_1')
+ ready()
+ if not named('printers_label')['checked']:
+ click('printers_label')
+ fill('printers_measured_width', '75.074')
+ fill('printers_measured_height', '112.611')
+ click('printers_calibrate')
+ wait_for(lambda: any('No supported resolution' in label for label in labels()), 'the other queue must use its own 203 dpi instead of the first ruler 300 dpi')
+ assert not any(widget.get('name') == 'printers_apply_resolution' for widget in ui.widgets()), 'another queue must not inherit the 300 dpi ruler receipt'
+ click('printers_queue_0')
+ ready()
+ fill('printers_measured_width', '75.074')
+ fill('printers_measured_height', '112.611')
+ click('printers_calibrate')
+ click('printers_apply_resolution')
+ wait_for(lambda: called('PrinterAddOption', lambda args: args[0] == 'Label_Test' and args[1] in ('printer-resolution', 'Resolution') and args[2] in (['203dpi'], ['203x203dpi'])), 'apply only the supported measured resolution')
+ resolution_call = next(call for call in calls() if call[0] == 'PrinterAddOption' and call[1][0] == 'Label_Test' and call[1][1] in ('printer-resolution', 'Resolution'))
+ wait_for(lambda: called('PrinterDeleteOptionDefault', lambda args: args == ['Label_Test', 'printer-resolution']), 'clear obsolete resolution override before PPD update')
+ assert next(i for i, call in enumerate(calls()) if call == ['PrinterDeleteOptionDefault', ['Label_Test', 'printer-resolution']]) < calls().index(resolution_call)
+ ready()
+ click('printers_calibrate')
+ wait_for(lambda: any('Suggested supported resolution:' in label and '203' in label for label in labels()), 'repeat calibration must use the original ruler DPI after its queue default changes')
+ before_native = len(calls())
+ click('printers_option_Resolution')
+ ipc.key_press('Down')
+ ipc.key_press('Return')
+ wait_for(lambda: called('PrinterAddOption', lambda args: args == ['Label_Test', 'Resolution', ['300dpi']]), 'native PPD resolution setting')
+ assert calls()[before_native:] == [
+ ['PrinterDeleteOptionDefault', ['Label_Test', 'Resolution']],
+ ['PrinterDeleteOptionDefault', ['Label_Test', 'printer-resolution']],
+ ['PrinterAddOption', ['Label_Test', 'Resolution', ['300dpi']]],
+ ], 'clear native and canonical overrides before applying the native PPD choice'
+
+ click('printers_option_sides')
+ ipc.key_press('Down')
+ ipc.key_press('Return')
+ wait_for(lambda: called('PrinterAddOption', lambda args: args == ['Label_Test', 'sides', ['two-sided-long-edge']]), 'IPP-supported queue setting through CUPS PPD mapping')
+ wait_for(lambda: called('PrinterDeleteOptionDefault', lambda args: args == ['Label_Test', 'sides']), 'clear obsolete sides override before PPD update')
+ assert next(i for i, call in enumerate(calls()) if call == ['PrinterDeleteOptionDefault', ['Label_Test', 'sides']]) < next(i for i, (method, args) in enumerate(calls()) if method == 'PrinterAddOption' and args[:2] == ['Label_Test', 'sides'])
+ click('printers_option_Darkness')
+ ipc.key_press('Down')
+ ipc.key_press('Return')
+ wait_for(lambda: called('PrinterAddOption', lambda args: args == ['Label_Test', 'Darkness', ['12']]), 'PPD driver-group queue setting')
+ wait_for(lambda: called('PrinterDeleteOptionDefault', lambda args: args == ['Label_Test', 'Darkness']), 'clear obsolete driver-option override')
+ assert next(i for i, call in enumerate(calls()) if call == ['PrinterDeleteOptionDefault', ['Label_Test', 'Darkness']]) < next(i for i, (method, args) in enumerate(calls()) if method == 'PrinterAddOption' and args[:2] == ['Label_Test', 'Darkness'])
+ if preview:
+ ready()
+ ui.scroll_into_view('printers_option_printer-resolution', panel='control_center')
+ ui.wait_settled('control_center')
+ Path('/tmp/rediwm-printers-setup-options.png').unlink(missing_ok=True)
+ ipc.screenshot('/tmp/rediwm-printers-setup-options.png')
+
+ click('printers_default')
+ wait_for(lambda: (tmp / '.cups/lpoptions').exists() and 'Default Label_Test' in (tmp / '.cups/lpoptions').read_text(), 'private per-user default')
+ assert not called('PrinterSetDefault'), 'per-user default must not become a privileged system default'
+ click('printers_system_default')
+ wait_for(lambda: called('PrinterSetDefault', lambda args: args == ['Label_Test']), 'explicit system default')
+ fill('printers_rename', 'Fixture renamed label')
+ click('printers_rename_save')
+ wait_for(lambda: called('PrinterSetInfo', lambda args: args == ['Label_Test', 'Fixture renamed label']), 'safe display name change')
+ assert not called('PrinterDelete'), 'display rename must preserve the queue'
+
+ # Starting the service is a separate, fixed systemd operation;
+ # reading the page or asking the helper must not start it.
+ assert not called('StartUnit'), calls()
+ scheduler.configure(fault='http')
+ click('printers_refresh')
+ click('printers_start')
+ wait_for(lambda: called('StartUnit', lambda args: args == ['cups.service', 'replace']), 'explicit fixed CUPS start')
+ scheduler.configure(fault='')
+ click('printers_refresh')
+ ready()
+
+ # Installed driver choices come from CUPS metadata, never a
+ # guessed ppd-match or package name. Discovery filters schemes.
+ click('printers_add')
+ click('printers_discover')
+ wait_for(lambda: called('DevicesGet'), 'privileged discovery')
+ wait_for(lambda: 'Printer discovery complete.' in labels(), 'discovery finished')
+ assert not any('Forbidden' in label for label in labels()), labels()
+ matched_device = next(widget for widget in ui.widgets() if widget.get('label') == 'Fixture vendor label')
+ click(matched_device['name'])
+ wait_for(lambda: named('printers_driver')['selected_index'] == 3, 'unique IEEE-1284 installed driver match')
+ fill('printers_address', network.uri)
+ fill('printers_name', 'Fixture_New')
+ click('printers_probe')
+ wait_for(lambda: named('printers_driver')['selected_index'] == 1, 'driverless capability choice replaces stale USB evidence')
+ click('printers_create')
+ wait_for(lambda: called('PrinterAdd', lambda args: args[0] == 'Fixture_New'), 'create printer')
+ wait_for(lambda: called('PrinterSetAcceptJobs', lambda args: args == ['Fixture_New', True, '']), 'new queue enabled and accepting')
+ wait_for(lambda: scheduler.state()['queues'].get('Fixture_New', {}).get('accepting') is True, 'new queue acceptance commit')
+ assert len(scheduler.printed) == 3, 'adding a queue must never automatically print'
+ queue = scheduler.state()['queues']['Fixture_New']
+ assert queue['enabled'] and queue['accepting'] and queue['uri'] == network.uri and queue['ppd'] == 'everywhere', queue
+
+ # An explicitly typed existing name must never become an upsert,
+ # including after returning to the add flow a second time.
+ adds = sum(method == 'PrinterAdd' for method, _ in calls())
+ click('printers_add')
+ fill('printers_address', network.uri)
+ fill('printers_name', 'Fixture_New')
+ click('printers_probe')
+ ready()
+ if not named('printers_create')['is_disabled']:
+ click('printers_create')
+ assert sum(method == 'PrinterAdd' for method, _ in calls()) == adds, 'existing queues must never be silently replaced'
+ assert len(scheduler.state()['queues']) == 3, scheduler.state()
+ click('printers_add_cancel')
+
+ # A vendor backend is allowed only as this exact CUPS discovery
+ # result. No node is opened: the private helper stores the URI.
+ click('printers_add')
+ device = next(widget for widget in ui.widgets() if widget.get('label') == 'Fixture vendor label')
+ click(device['name'])
+ fill('printers_name', 'Vendor_Test')
+ click('printers_create')
+ wait_for(lambda: called('PrinterAdd', lambda args: args[:3] == ['Vendor_Test', 'tspl:/dev/usb/lp0', 'fixture-label.ppd']), 'exact CUPS-discovered vendor backend')
+ wait_for(lambda: called('PrinterSetAcceptJobs', lambda args: args == ['Vendor_Test', True, '']), 'vendor queue setup completes')
+ wait_for(lambda: scheduler.state()['queues'].get('Vendor_Test', {}).get('accepting') is True, 'vendor queue acceptance commit')
+ assert len(scheduler.printed) == 3, 'vendor queue setup must not submit a test or open a device node'
+
+ # A refusal remains visible and cannot change another queue.
+ (tmp / 'deny').touch()
+ click('printers_disable')
+ wait_for(lambda: any('not authorized' in label.lower() or 'cancelled' in label.lower() for label in labels()), 'administration authorization refusal')
+ (tmp / 'deny').unlink()
+ assert scheduler.state()['queues']['Label_Test']['enabled'], scheduler.state()
+
+ remove_name = 'Label_Test'
+ if queue_rename:
+ # Native helper rename copies and removes a queue; root
+ # preflight must refuse collisions and active own jobs.
+ fill('printers_queue_name', 'Office_Test')
+ click('printers_queue_rename')
+ click('printers_queue_rename_confirm')
+ wait_for(lambda: any('already exists' in label.lower() for label in labels()), 'queue rename collision refusal')
+ assert not called('PrinterRename'), 'an existing destination must be refused before the helper'
+ scheduler.configure(jobs_denied=True)
+ click('printers_refresh')
+ ready()
+ fill('printers_queue_name', 'Renamed_Label')
+ click('printers_queue_rename')
+ click('printers_queue_rename_confirm')
+ ready()
+ wait_for(lambda: any('verify' in label.lower() and 'jobs' in label.lower() for label in labels()), 'queue rename refuses an unavailable job query')
+ assert not called('PrinterRename'), 'unknown jobs must not be treated as an empty queue'
+ scheduler.configure(jobs_denied=False)
+ for state in (3, 4):
+ scheduler.configure(active_job=True, active_job_state=state)
+ click('printers_refresh')
+ ready()
+ fill('printers_queue_name', 'Renamed_Label')
+ click('printers_queue_rename')
+ click('printers_queue_rename_confirm')
+ ready()
+ wait_for(lambda: any('job' in label.lower() and ('finish' in label.lower() or 'active' in label.lower()) for label in labels()), 'queue rename pending/held-job refusal')
+ assert not called('PrinterRename'), 'finish known pending or held jobs before renaming a queue'
+ scheduler.configure(active_job=False)
+ click('printers_refresh')
+ ready()
+ fill('printers_queue_name', 'Renamed_Label')
+ click('printers_queue_rename')
+ assert not called('PrinterRename'), 'queue rename must require a distinct named confirmation'
+ click('printers_queue_rename_confirm')
+ wait_for(lambda: called('PrinterRename', lambda args: args == ['Label_Test', 'Renamed_Label']), 'confirmed native queue rename')
+ wait_for(lambda: 'Renamed_Label' in scheduler.state()['queues'] and 'Label_Test' not in scheduler.state()['queues'], 'renamed queue identity')
+ wait_for(lambda: 'Default Renamed_Label' in (tmp / '.cups/lpoptions').read_text(), 'renamed user default migration')
+ assert not called('PrinterDelete'), 'native queue rename must not use separate direct delete calls'
+ ready()
+ queue_widget = next(widget for widget in ui.widgets() if (widget.get('name') or '').startswith('printers_queue_') and (widget.get('label') or '').startswith('Renamed_Label'))
+ click(queue_widget['name'])
+ click('printers_copy_report')
+ report = subprocess.check_output(['wl-paste', '--no-newline'], env={**os.environ, 'XDG_RUNTIME_DIR': str(tmp), 'WAYLAND_DISPLAY': wayland_display_name(tmp)}, timeout=5).decode()
+ assert 'driver=no_output, raw=printed, ruler=printed' in report, 'renamed queue must retain user observations'
+ remove_name = 'Renamed_Label'
+
+ # Removal is a distinct, named confirmation, never a disable.
+ click('printers_remove')
+ before_remove = set(scheduler.state()['queues'])
+ assert not called('PrinterDelete'), calls()
+ assert any('Label_Test' in label or 'Fixture renamed label' in label for label in labels()), labels()
+ click('printers_remove_confirm')
+ wait_for(lambda: called('PrinterDelete', lambda args: args == [remove_name]), 'confirmed queue removal')
+ wait_for(lambda: set(scheduler.state()['queues']) == before_remove - {remove_name}, 'confirmed queue removal commit')
+ # A missing helper is an explicit read-only state. Disappearance
+ # during the page's lifetime cannot fall back to direct admin.
+ helper.terminate()
+ helper.wait(timeout=5)
+ click('printers_queue_0')
+ click('printers_disable')
+ wait_for(lambda: any('cups-pk-helper' in label and ('install' in label.lower() or 'unavailable' in label.lower()) for label in labels()), 'missing helper guidance')
+ assert named('printers_add')['is_disabled'] and named('printers_disable')['is_disabled'] and named('printers_connection')['is_disabled'], 'missing helper must disable privileged controls'
+ assert scheduler.state()['queues']['Office_Test']['enabled'], scheduler.state()
+ click('shortcuts')
+ assert not printer_workers(process), 'setup page hide must release worker'
+ if any(operation == 0x0016 for operation, _ in scheduler.calls()):
+ wait_for(lambda: any(operation == 0x001b and fields.get('notify-subscription-id') == 23 for operation, fields in scheduler.calls()), 'subscription cancellation on hide')
+ count = len(scheduler.calls())
+ time.sleep(1)
+ assert len(scheduler.calls()) == count, 'hidden setup page must not retain scheduler activity'
+ stop_process(process)
+ log.flush()
+ contents = (tmp / 'compositor.log').read_text()
+ assert ' leaked:' not in contents and 'memory address' not in contents, contents[-3000:]
+ print('Printer setup, authorization, defaults and confirmed printing passed at scale', scale)
+ except Exception:
+ if (tmp / 'helper.jsonl').exists():
+ Path('/tmp/rediwm-printer-setup-helper.jsonl').write_text((tmp / 'helper.jsonl').read_text())
+ Path('/tmp/rediwm-printer-setup-queues.json').write_text(state_path.read_text())
+ if log:
+ log.flush()
+ Path('/tmp/rediwm-printer-setup-compositor.log').write_text((tmp / 'compositor.log').read_text())
+ if helper and helper.poll() is not None:
+ print(helper.stderr.read())
+ raise
+ finally:
+ if process and process.poll() is None: stop_process(process)
+ if log: log.close()
+ if helper and helper.poll() is None:
+ helper.terminate()
+ helper.wait(timeout=5)
+ bus.terminate()
+ bus.wait(timeout=5)
+ scheduler.close()
+ network.close()
+
+
+def tcp_reading(scale):
+ with tempfile.TemporaryDirectory(prefix='rediwm-printer-tcp-') as directory:
+ tmp = Path(directory)
+ scheduler = Scheduler(tmp / 'source.sock')
+ endpoint = TcpEndpoint(scheduler)
+ process = log = None
+ try:
+ process, log = spawn_compositor(tmp, scale=scale, config_content='[compositor]\nxwayland = false\n', env_extra={
+ 'CUPS_SERVER': f'127.0.0.1:{endpoint.server_address[1]}', 'CUPS_USER': scheduler.username, 'CUPS_ENCRYPTION': 'Never',
+ 'HOME': str(tmp), 'XDG_CONFIG_HOME': str(tmp / 'config'), 'XDG_DATA_HOME': str(tmp / 'data'), 'XDG_CACHE_HOME': str(tmp / 'cache'),
+ 'DBUS_SESSION_BUS_ADDRESS': '', 'DBUS_SYSTEM_BUS_ADDRESS': '',
+ 'PIPEWIRE_RUNTIME_DIR': str(tmp), 'PULSE_SERVER': 'unix:/nonexistent-rediwm-printers-test-pulse',
+ })
+ with IPCClient(tmp, timeout=15) as ipc:
+ ui = UIDriver(ipc)
+ ipc.open_control_center()
+ ui.wait_settled('control_center')
+ ui.click(ui.find('printers', panel='control_center'), panel='control_center')
+ wait_for(lambda: ui.find('printers_status', panel='control_center')['label'] == 'Connected to CUPS.', 'private TCP scheduler', timeout=15)
+ assert any(operation == 0x4002 for operation, _ in endpoint.events), endpoint.events
+ assert ui.find('printers_add', panel='control_center')['is_disabled'], 'remote scheduler must never administer local CUPS'
+ assert any('Label_Test' in (widget.get('label') or '') for widget in ui.widgets()), ui.widgets()
+ print('Private TCP scheduler reading and administration isolation passed at scale', scale)
+ finally:
+ if process: stop_process(process)
+ if log: log.close()
+ endpoint.close()
+ scheduler.close()
+
+
+if __name__ == '__main__':
+ os.umask(0o077)
+ scale = os.environ.get('REDIWM_TEST_SCALE', '1')
+ run(scale)
+ endpoint_errors(scale)
+ tcp_reading(scale)
+ setup_and_tools(scale)