// SPDX-FileCopyrightText: © 2024 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! A stand-in for `systemd-journald`, for tests. //! //! It binds the same kind of socket journald binds, receives what `Message` //! sends, and decodes the journal's native wire format back into fields, so a //! test can assert on what actually crossed the socket rather than on what //! the library believed it wrote. //! //! This is only reachable from a test build; `root.zig` does not export it. const std = @import("std"); const Allocator = std.mem.Allocator; const ControlMessage = @import("cmsghdr.zig").ControlMessage; const linux = std.os.linux; const AF = linux.AF; const F = linux.F; const SCM = linux.SCM; const SOCK = linux.SOCK; const SOL = linux.SOL; const fd_t = linux.fd_t; const sockaddr = linux.sockaddr; /// One field of a journal entry, in the order it was written. pub const Field = struct { key: []const u8, value: []const u8, }; /// A decoded entry, owning its field names and values. pub const Entry = struct { arena: std.heap.ArenaAllocator, fields: []const Field, /// The seals in force on the memfd when it arrived. journald relies on /// these: a sender that can still write to the payload could change it /// after journald has decided to trust it. seals: u32, pub fn deinit(self: *Entry) void { self.arena.deinit(); } /// The value of the first field named `key`, or null. pub fn get(self: *const Entry, key: []const u8) ?[]const u8 { for (self.fields) |field| { if (std.mem.eql(u8, field.key, key)) return field.value; } return null; } /// How many fields are named `key`. pub fn count(self: *const Entry, key: []const u8) usize { var n: usize = 0; for (self.fields) |field| { if (std.mem.eql(u8, field.key, key)) n += 1; } return n; } }; pub const FakeJournal = struct { socket: fd_t, /// Bind a datagram socket at `path`. Nothing is listening until this /// returns, so it has to be called before the logger that talks to it. pub fn init(path: []const u8) !FakeJournal { var addr: sockaddr.un = undefined; if (path.len >= addr.path.len) return error.PathTooLong; addr.family = AF.UNIX; @memcpy(addr.path[0..path.len], path); addr.path[path.len] = 0; const socket: fd_t = socket: { const rc = linux.socket(AF.UNIX, SOCK.DGRAM | SOCK.CLOEXEC, 0); switch (linux.errno(rc)) { .SUCCESS => break :socket @intCast(rc), else => return error.SocketFailed, } }; errdefer _ = linux.close(socket); { const rc = linux.bind( socket, @ptrCast(&addr), @sizeOf(sockaddr.un), ); switch (linux.errno(rc)) { .SUCCESS => {}, else => return error.BindFailed, } } return .{ .socket = socket }; } pub fn deinit(self: *const FakeJournal) void { _ = linux.close(self.socket); } /// Receive one entry. The datagram carries no payload of its own: the /// whole message is the memfd passed as `SCM_RIGHTS`, which is read here /// and decoded. pub fn receive(self: *const FakeJournal, allocator: Allocator) !Entry { var control: ControlMessage(fd_t) = undefined; var msghdr = linux.msghdr{ .name = null, .namelen = 0, .iov = undefined, .iovlen = 0, .control = control.mutablePtr(), .controllen = control.len(), .flags = 0, }; { const rc = linux.recvmsg(self.socket, &msghdr, 0); switch (linux.errno(rc)) { .SUCCESS => {}, else => return error.ReceiveFailed, } } // The kernel reports what it wrote, which is the header plus the // descriptor; the buffer is larger than that because it reserves the // padding a second control message would start after. if (msghdr.controllen < @TypeOf(control).content_len) return error.NoControlMessage; const header = control.header().*; if (header.level != SOL.SOCKET) return error.UnexpectedControlLevel; if (header.type != SCM.RIGHTS) return error.UnexpectedControlType; const memfd = control.data().*; defer _ = linux.close(memfd); const seals: u32 = seals: { const rc = linux.fcntl(memfd, F.GET_SEALS, 0); switch (linux.errno(rc)) { .SUCCESS => break :seals @intCast(rc), else => return error.GetSealsFailed, } }; var arena: std.heap.ArenaAllocator = .init(allocator); errdefer arena.deinit(); const payload = try readAll(arena.allocator(), memfd); const fields = try decode(arena.allocator(), payload); return .{ .arena = arena, .fields = fields, .seals = seals }; } }; /// Decode a message that has not been sent, by reading its memfd directly. /// Lets a test assert on the encoding without a journal at the other end. pub fn decodeMemfd(allocator: Allocator, memfd: fd_t) ![]const Field { return decode(allocator, try readAll(allocator, memfd)); } /// Read the whole memfd. `lseek` to the end gives the size because the sender /// has sealed it against growing and shrinking by this point. pub fn readAll(allocator: Allocator, memfd: fd_t) ![]const u8 { const size: usize = size: { const rc = linux.lseek(memfd, 0, linux.SEEK.END); switch (linux.errno(rc)) { .SUCCESS => break :size @intCast(rc), else => return error.SeekFailed, } }; const buf = try allocator.alloc(u8, size); var read: usize = 0; while (read < size) { const rc = linux.pread(memfd, buf.ptr + read, size - read, @intCast(read)); switch (linux.errno(rc)) { .SUCCESS => {}, else => return error.ReadFailed, } // A short read of zero before the end means the file is smaller than // the seek said, which would make everything after it a lie. if (rc == 0) return error.ShortRead; read += rc; } return buf; } /// Decode the journal's native format: a field is its name, a newline, its /// length as a little endian `u64`, that many bytes, and a newline. /// /// The plain `KEY=VALUE\n` form the protocol also allows is deliberately not /// accepted: this library never writes it, so meeting one here is a bug /// rather than something to be lenient about. fn decode(allocator: Allocator, payload: []const u8) ![]const Field { var fields: std.ArrayList(Field) = .empty; var rest = payload; while (rest.len > 0) { const newline = std.mem.findScalar(u8, rest, '\n') orelse return error.TruncatedKey; const key = rest[0..newline]; rest = rest[newline + 1 ..]; if (std.mem.findScalar(u8, key, '=') != null) return error.UnexpectedTextField; if (rest.len < @sizeOf(u64)) return error.TruncatedLength; const len = std.mem.readInt(u64, rest[0..@sizeOf(u64)], .little); rest = rest[@sizeOf(u64)..]; if (len > rest.len) return error.TruncatedValue; const value = rest[0..@intCast(len)]; rest = rest[@intCast(len)..]; if (rest.len < 1 or rest[0] != '\n') return error.MissingValueTerminator; rest = rest[1..]; try fields.append(allocator, .{ .key = key, .value = value }); } return fields.toOwnedSlice(allocator); }