// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The udev rules a Linux system wants before an unprivileged process //! can open one of these devices. //! //! A `/dev/hidraw*` node is root-owned and mode 0600 by default. //! Enumerating them needs no permission -- the list comes out of //! `/sys/class/hidraw` -- but opening one does, so without a rule a //! user gets `error.AccessDenied` from `Enumerator.next` rather than an //! empty list. See the README. //! //! **The rules are generated here rather than written down**, because //! writing them down is how they come to disagree with the device //! table. `StreamDeck.Type` already knows every vendor and product id //! this library claims; this turns that list into rules, `zig build //! udev` prints them, and `nix/module.nix` carries what it printed. A //! test below checks that the file still says what this function //! produces, so a model added to `Type` and forgotten here stops the //! build rather than quietly becoming unreachable. const std = @import("std"); const StreamDeck = @import("StreamDeck.zig"); /// How wide a net to cast for one vendor. pub const Match = enum { /// One rule for the whole vendor id, covering every model it makes /// including ones that do not exist yet. whole_vendor, /// One rule per product id, because the vendor makes a great deal /// besides Stream Decks. this_product, }; /// The vendors that appear in `StreamDeck.Type`, and how much of each /// belongs to this library. /// /// This is an enum rather than a list of integers so that the switch /// below has to be exhaustive: a model from a third vendor added to /// `Type` fails the comptime check underneath and then fails to /// compile here, rather than being left without a rule and reported as /// a permissions problem by somebody else months later. pub const Vendor = enum(u16) { elgato = 0x0fd9, corsair = 0x1b1c, /// How much of this vendor's catalogue to grant access to. pub fn match(self: Vendor) Match { return switch (self) { // Elgato's `0fd9` is Stream Decks and Stream Deck // accessories and nothing else, so matching the vendor // covers every model including ones not yet released -- // the right trade for a rule that only hands the device to // whoever is already sitting at the machine. .elgato => .whole_vendor, // Corsair's `1b1c` is their whole catalogue: the // keyboards, the mice, the coolers, the power supplies. // Exactly one product of it is a Stream Deck, so the rule // names that product. A vendor-wide rule here would be // granting far more than this library needs. .corsair => .this_product, }; } }; comptime { // Every model's vendor has to be one this file knows what to do // with. Adding a device from a new vendor is then a compile error // naming the vendor, which is the point. for (std.enums.values(StreamDeck.Type)) |t| { _ = std.enums.fromInt(Vendor, t.vendor()) orelse @compileError( "no udev policy for the vendor of " ++ @tagName(t) ++ "; add it to udev.Vendor", ); } } /// Who the device is to be handed to. pub const Owner = union(enum) { /// `uaccess`, which is what a desktop wants: logind gives the /// device to whoever is logged in at the seat and takes it back /// when they log out, so nobody has to be put in a group and a /// remote session cannot reach the deck on somebody's desk. uaccess, /// A group, for a machine with no seat -- one running a daemon /// rather than a desktop. group: []const u8, }; /// Write the rules for every model this library knows. /// /// The output is a udev rules file, one rule per line, ready to be /// written to `/etc/udev/rules.d/`. The file's name has to sort before /// systemd's `73-seat-late.rules`, which is where `uaccess` is acted /// on -- so not NixOS' `services.udev.extraRules`, which lands in /// `99-local.rules` and is read too late for the tag to do anything. pub fn writeRules(w: *std.Io.Writer, owner: Owner) !void { inline for (comptime std.enums.values(Vendor)) |vendor| { switch (vendor.match()) { .whole_vendor => { try w.print("SUBSYSTEM==\"hidraw\", ATTRS{{idVendor}}==\"{x:0>4}\"", .{@backingInt(vendor)}); try writeOwner(w, owner); }, .this_product => { // In product id order, so that the file does not // reshuffle itself when a model is added. Built and // copied out of the comptime block as a value, since a // pointer into a comptime var cannot survive to // runtime. const products = comptime blk: { var buf: [std.enums.values(StreamDeck.Type).len]u16 = undefined; var n: usize = 0; for (std.enums.values(StreamDeck.Type)) |t| { if (t.vendor() != @backingInt(vendor)) continue; buf[n] = t.product(); n += 1; } std.mem.sort(u16, buf[0..n], {}, std.sort.asc(u16)); break :blk buf[0..n].*; }; for (products) |product| { try w.print( "SUBSYSTEM==\"hidraw\", ATTRS{{idVendor}}==\"{x:0>4}\", ATTRS{{idProduct}}==\"{x:0>4}\"", .{ @backingInt(vendor), product }, ); try writeOwner(w, owner); } }, } } } fn writeOwner(w: *std.Io.Writer, owner: Owner) !void { switch (owner) { .uaccess => try w.writeAll(", TAG+=\"uaccess\"\n"), .group => |g| try w.print(", MODE=\"0660\", GROUP=\"{s}\"\n", .{g}), } } /// The rules as a string, for a caller that wants them in one piece. /// The caller owns the result. pub fn rules(alloc: std.mem.Allocator, owner: Owner) ![]u8 { var out: std.Io.Writer.Allocating = .init(alloc); errdefer out.deinit(); try writeRules(&out.writer, owner); return out.toOwnedSlice(); } test "the rules cover every model, and say how" { const alloc = std.testing.allocator; const text = try rules(alloc, .uaccess); defer alloc.free(text); // Elgato gets one rule for the vendor, however many models there // are, and the Galleon gets one naming its product. try std.testing.expect(std.mem.indexOf(u8, text, "ATTRS{idVendor}==\"0fd9\", TAG") != null); try std.testing.expect(std.mem.indexOf( u8, text, "ATTRS{idVendor}==\"1b1c\", ATTRS{idProduct}==\"2b18\"", ) != null); // One line per rule, and no Elgato product ids: matching the // vendor is deliberate and a per-product Elgato rule would mean // this file had changed its mind without anyone saying so. var lines: usize = 0; var it = std.mem.tokenizeScalar(u8, text, '\n'); while (it.next()) |line| { lines += 1; try std.testing.expect(std.mem.startsWith(u8, line, "SUBSYSTEM==\"hidraw\"")); } try std.testing.expectEqual(2, lines); } test "a group replaces uaccess rather than joining it" { const alloc = std.testing.allocator; const text = try rules(alloc, .{ .group = "plugdev" }); defer alloc.free(text); try std.testing.expect(std.mem.indexOf(u8, text, "MODE=\"0660\", GROUP=\"plugdev\"") != null); try std.testing.expect(std.mem.indexOf(u8, text, "uaccess") == null); } test "the NixOS module carries what this generates" { // The module is a file of Nix rather than something generated at // build time, because a NixOS module has to be readable by the // person importing it. That leaves it able to drift, so this is // what stops it: every rule this produces has to appear in the // module, in both of the shapes the module can emit. const module = @embedFile("nixos-module.nix"); const alloc = std.testing.allocator; for ([_]Owner{ .uaccess, .{ .group = "${cfg.group}" } }) |owner| { const text = try rules(alloc, owner); defer alloc.free(text); var it = std.mem.tokenizeScalar(u8, text, '\n'); while (it.next()) |line| { if (std.mem.indexOf(u8, module, line) == null) { std.debug.print("nix/module.nix is missing: {s}\n", .{line}); return error.ModuleOutOfDate; } } } }