// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The places Linux and Windows differ, gathered in one file. //! //! The agent's socket is an `AF_UNIX` stream socket on both: Windows has had //! them since Windows 10 version 1803, and Zig's standard library implements //! them there, but only for a target that says it is at least that version. //! Build for Windows with `-Dtarget=x86_64-windows-gnu.win10_rs4`. const std = @import("std"); const builtin = @import("builtin"); const Io = std.Io; pub const is_windows = builtin.os.tag == .windows; pub const is_linux = builtin.os.tag == .linux; comptime { if (!Io.net.has_unix_sockets) @compileError( "bwgpg needs AF_UNIX sockets; for Windows, build for win10_rs4 or later, " ++ "e.g. -Dtarget=x86_64-windows-gnu.win10_rs4", ); } /// The other end of a Unix socket connection, as the kernel reports it. pub const Peer = struct { pid: i32, uid: u32, }; /// Who is at the other end of `stream`: `SO_PEERCRED` on Linux, null /// elsewhere. pub fn peerOf(stream: Io.net.Stream) ?Peer { switch (builtin.os.tag) { .linux => { const linux = std.os.linux; const Ucred = extern struct { pid: i32, uid: u32, gid: u32 }; var cred: Ucred = undefined; var len: linux.socklen_t = @sizeOf(Ucred); const rc = linux.getsockopt(stream.socket.handle, linux.SOL.SOCKET, linux.SO.PEERCRED, @ptrCast(&cred), &len); if (linux.errno(rc) != .SUCCESS or len != @sizeOf(Ucred)) return null; return .{ .pid = cred.pid, .uid = cred.uid }; }, else => return null, } } /// Whether the process at the other end of `stream` belongs to this user. /// /// On Linux that is asked of the kernel with `SO_PEERCRED`. On Windows there /// is no equivalent the standard library reaches, so the answer rests on /// the socket file living under `%LOCALAPPDATA%`, which only this user and /// the administrators can open. pub fn peerIsSelf(stream: Io.net.Stream) bool { switch (builtin.os.tag) { .linux => { const peer = peerOf(stream) orelse return false; return peer.uid == std.os.linux.getuid(); }, else => return true, } } /// The start time of process `pid`, in clock ticks since boot: field 22 of /// `/proc//stat`. With the pid it names one process for its whole /// life, where the pid alone may be reused by the next. Null when the /// process is gone, or off Linux. pub fn processStartTime(io: Io, pid: i32) ?u64 { if (builtin.os.tag != .linux) return null; var path_buf: [64]u8 = undefined; const path = std.fmt.bufPrint(&path_buf, "/proc/{d}/stat", .{pid}) catch return null; var buf: [1024]u8 = undefined; const text = Io.Dir.cwd().readFile(io, path, &buf) catch return null; return startTimeFromStat(text); } /// Field 22 of a `/proc//stat` line. The second field is the command /// name in parentheses, which may itself hold spaces and parentheses, so /// the fields are counted from the last `)`. pub fn startTimeFromStat(text: []const u8) ?u64 { const close = std.mem.findScalarLast(u8, text, ')') orelse return null; var it = std.mem.tokenizeScalar(u8, text[close + 1 ..], ' '); // After the `)` comes field 3; field 22 is 19 further on. var i: usize = 3; while (it.next()) |field| : (i += 1) { if (i == 22) return std.fmt.parseInt(u64, std.mem.trimEnd(u8, field, "\n"), 10) catch null; } return null; } /// The command line of process `pid`, its arguments joined by spaces and /// cut to 100 bytes: what the user is shown as the name of an SSH session. pub fn processCommand(gpa: std.mem.Allocator, io: Io, pid: i32) std.mem.Allocator.Error![]u8 { if (builtin.os.tag != .linux) return gpa.dupe(u8, "?"); var path_buf: [64]u8 = undefined; const path = std.fmt.bufPrint(&path_buf, "/proc/{d}/cmdline", .{pid}) catch return gpa.dupe(u8, "?"); var buf: [100]u8 = undefined; const raw = Io.Dir.cwd().readFile(io, path, &buf) catch return gpa.dupe(u8, "?"); const out = try gpa.dupe(u8, std.mem.trimEnd(u8, raw, "\x00")); for (out) |*c| { if (c.* == 0 or c.* < 0x20 or c.* == 0x7f) c.* = ' '; } return out; } /// The first descriptor systemd passes to a socket-activated service. const sd_listen_fds_start = 3; pub const ListenFdError = error{ /// systemd passed more sockets than bwgpg's units ask for, or one under /// a name they do not use: a misconfigured unit. UnexpectedListenFds, }; /// The sockets systemd handed this process: the agent's own, and the one /// meant to be forwarded over SSH. pub const ListenFds = struct { main: ?i32 = null, extra: ?i32 = null, pub fn any(fds: ListenFds) bool { return fds.main != null or fds.extra != null; } }; /// The sockets systemd handed this process, if it was socket-activated: /// the check `sd_listen_fds(3)` makes, on `LISTEN_PID` and `LISTEN_FDS`, and /// `sd_listen_fds_with_names(3)`'s reading of `LISTEN_FDNAMES`. A single /// socket without a name is the main one, which is what a unit from before /// the extra socket passes; and a socket named after its unit, as systemd /// names one without `FileDescriptorName`, is the extra one when that unit's /// name says so. Split from the environment and the process ID so that it /// can be tested. pub fn listenFdsFromEnv(env: *const std.process.Environ.Map, pid: i64) ListenFdError!ListenFds { const listen_pid = std.fmt.parseInt(i64, env.get("LISTEN_PID") orelse return .{}, 10) catch return .{}; // The variables are inherited by children; they are only for the // process they name. if (listen_pid != pid) return .{}; const count = std.fmt.parseInt(u32, env.get("LISTEN_FDS") orelse return .{}, 10) catch return .{}; if (count == 0) return .{}; if (count > 2) return error.UnexpectedListenFds; var fds: ListenFds = .{}; var names = std.mem.splitScalar(u8, env.get("LISTEN_FDNAMES") orelse "", ':'); for (0..count) |i| { const fd: i32 = sd_listen_fds_start + @as(i32, @intCast(i)); const name = names.next() orelse ""; if (std.mem.eql(u8, name, "extra") or std.mem.endsWith(u8, name, "-extra.socket")) { if (fds.extra != null) return error.UnexpectedListenFds; fds.extra = fd; } else if (std.mem.eql(u8, name, "main") or name.len == 0 or std.mem.eql(u8, name, "unknown") or std.mem.endsWith(u8, name, ".socket")) { if (fds.main != null) return error.UnexpectedListenFds; fds.main = fd; } else { return error.UnexpectedListenFds; } } return fds; } /// The listening sockets from systemd, on Linux; none elsewhere. Each is /// marked close-on-exec, so pinentry does not inherit it. pub fn systemdListenFds(env: *const std.process.Environ.Map) ListenFdError!ListenFds { if (builtin.os.tag != .linux) return .{}; const linux = std.os.linux; const fds = try listenFdsFromEnv(env, linux.getpid()); for ([_]?i32{ fds.main, fds.extra }) |maybe| { if (maybe) |fd| _ = linux.fcntl(fd, linux.F.SETFD, linux.FD_CLOEXEC); } return fds; } /// Detaches the agent from whoever started it, so that it outlives the git /// command whose signature brought it up and is not killed with that /// command's terminal. pub fn detach() void { switch (builtin.os.tag) { .linux => _ = std.os.linux.setsid(), else => {}, } } /// Writes `bytes` to file descriptor `fd`: gpg's `--status-fd`. Descriptors /// 1 and 2 are standard output and error on every platform; another number /// is honored where descriptors are a thing a parent can hand its child, /// which is not Windows. pub fn writeFd(io: Io, fd: u32, bytes: []const u8) void { const file: Io.File = switch (fd) { 1 => .stdout(), 2 => .stderr(), else => if (is_windows) return else .{ .handle = @intCast(fd), .flags = .{ .nonblocking = false } }, }; var w = file.writer(io, &.{}); w.interface.writeAll(bytes) catch {}; } /// The default name of the pinentry program, and where Gpg4win installs /// it on Windows. pub fn pinentryCandidates(gpa: std.mem.Allocator, env: *const std.process.Environ.Map) ![]const []const u8 { var list: std.ArrayList([]const u8) = .empty; errdefer list.deinit(gpa); if (is_windows) { for ([_][]const u8{ "ProgramFiles(x86)", "ProgramFiles" }) |var_name| { const base = env.get(var_name) orelse continue; try list.append(gpa, try std.fs.path.join(gpa, &.{ base, "Gpg4win", "bin", "pinentry.exe" })); try list.append(gpa, try std.fs.path.join(gpa, &.{ base, "GnuPG", "bin", "pinentry-basic.exe" })); } try list.append(gpa, try gpa.dupe(u8, "pinentry.exe")); } else { for ([_][]const u8{ "pinentry", "pinentry-gnome3", "pinentry-qt", "pinentry-gtk-2", "pinentry-curses", "pinentry-tty" }) |name| { try list.append(gpa, try gpa.dupe(u8, name)); } } return list.toOwnedSlice(gpa); } /// The pinentry to run: the one the config names, else `BWGPG_PINENTRY`, /// else the first of the usual names on `PATH`. Returns null when there is /// none, which on Linux usually means the agent is running under systemd, /// whose `PATH` is not the shell's. /// /// The environment variable is how Home Manager supplies one without owning /// the config: it sets it for the systemd unit and for the session. pub fn findPinentry( gpa: std.mem.Allocator, io: Io, env: *const std.process.Environ.Map, configured: ?[]const u8, ) !?[]u8 { if (configured) |p| return try gpa.dupe(u8, p); if (env.get("BWGPG_PINENTRY")) |p| { if (p.len > 0) return try gpa.dupe(u8, p); } const candidates = try pinentryCandidates(gpa, env); defer { for (candidates) |c| gpa.free(c); gpa.free(candidates); } for (candidates) |c| { if (try findProgram(gpa, io, env, c)) |found| return found; } return null; } /// The gpg to pass everything else to, and where GnuPG installs it on /// Windows. pub fn gpgCandidates(gpa: std.mem.Allocator, env: *const std.process.Environ.Map) ![]const []const u8 { var list: std.ArrayList([]const u8) = .empty; errdefer list.deinit(gpa); if (is_windows) { for ([_][]const u8{ "ProgramFiles(x86)", "ProgramFiles" }) |var_name| { const base = env.get(var_name) orelse continue; try list.append(gpa, try std.fs.path.join(gpa, &.{ base, "GnuPG", "bin", "gpg.exe" })); } try list.append(gpa, try gpa.dupe(u8, "gpg.exe")); } else { try list.append(gpa, try gpa.dupe(u8, "gpg2")); try list.append(gpa, try gpa.dupe(u8, "gpg")); } return list.toOwnedSlice(gpa); } /// Resolves `name` the way spawning it would: as a path if it has a /// separator, otherwise through `PATH`. Returns null when it is not there. pub fn findProgram(gpa: std.mem.Allocator, io: Io, env: *const std.process.Environ.Map, name: []const u8) !?[]u8 { const cwd = Io.Dir.cwd(); if (std.mem.findAny(u8, name, if (is_windows) "/\\" else "/") != null) { cwd.access(io, name, .{}) catch return null; return try gpa.dupe(u8, name); } const path = env.get("PATH") orelse return null; var it = std.mem.tokenizeScalar(u8, path, if (is_windows) ';' else ':'); while (it.next()) |dir| { const candidate = try std.fs.path.join(gpa, &.{ dir, name }); cwd.access(io, candidate, .{}) catch { gpa.free(candidate); continue; }; return candidate; } return null; } test "pinentry comes from the config, then BWGPG_PINENTRY, then PATH" { const gpa = std.testing.allocator; const io = std.testing.io; var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); // An empty PATH, so that nothing is found there. try env.put("PATH", ""); try std.testing.expectEqual(@as(?[]u8, null), try findPinentry(gpa, io, &env, null)); try env.put("BWGPG_PINENTRY", "/nix/store/x-pinentry/bin/pinentry"); const from_env = (try findPinentry(gpa, io, &env, null)).?; defer gpa.free(from_env); try std.testing.expectEqualStrings("/nix/store/x-pinentry/bin/pinentry", from_env); const from_config = (try findPinentry(gpa, io, &env, "/usr/bin/pinentry-tty")).?; defer gpa.free(from_config); try std.testing.expectEqualStrings("/usr/bin/pinentry-tty", from_config); } test "the sockets systemd hands over are taken only by the process named, by name" { const gpa = std.testing.allocator; var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try std.testing.expect(!(try listenFdsFromEnv(&env, 42)).any()); // One socket without a name: the main one, as from an older unit. try env.put("LISTEN_PID", "42"); try env.put("LISTEN_FDS", "1"); const one = try listenFdsFromEnv(&env, 42); try std.testing.expectEqual(@as(?i32, 3), one.main); try std.testing.expectEqual(@as(?i32, null), one.extra); // Inherited by a child, they are not the child's. try std.testing.expect(!(try listenFdsFromEnv(&env, 43)).any()); // Two, named, in either order. try env.put("LISTEN_FDS", "2"); try env.put("LISTEN_FDNAMES", "main:extra"); const two = try listenFdsFromEnv(&env, 42); try std.testing.expectEqual(@as(?i32, 3), two.main); try std.testing.expectEqual(@as(?i32, 4), two.extra); try env.put("LISTEN_FDNAMES", "extra:main"); const swapped = try listenFdsFromEnv(&env, 42); try std.testing.expectEqual(@as(?i32, 4), swapped.main); try std.testing.expectEqual(@as(?i32, 3), swapped.extra); // Two main sockets, a name bwgpg does not use, or too many. try env.put("LISTEN_FDNAMES", "main:main"); try std.testing.expectError(error.UnexpectedListenFds, listenFdsFromEnv(&env, 42)); // Named after their units, as without FileDescriptorName. try env.put("LISTEN_FDNAMES", "bwgpg-agent.socket:bwgpg-agent-extra.socket"); const by_unit = try listenFdsFromEnv(&env, 42); try std.testing.expectEqual(@as(?i32, 3), by_unit.main); try std.testing.expectEqual(@as(?i32, 4), by_unit.extra); try env.put("LISTEN_FDNAMES", "main:bogus"); try std.testing.expectError(error.UnexpectedListenFds, listenFdsFromEnv(&env, 42)); try env.put("LISTEN_FDS", "3"); try std.testing.expectError(error.UnexpectedListenFds, listenFdsFromEnv(&env, 42)); try env.put("LISTEN_FDS", "0"); try std.testing.expect(!(try listenFdsFromEnv(&env, 42)).any()); } test "a process's start time, past a command name with spaces and parentheses" { const line = "1234 (ssh (my) host) S 1 1234 1234 0 -1 4194560 100 0 0 0 1 2 0 0 20 0 1 0 987654 12345678 900\n"; try std.testing.expectEqual(@as(?u64, 987654), startTimeFromStat(line)); try std.testing.expectEqual(@as(?u64, null), startTimeFromStat("no parentheses here")); try std.testing.expectEqual(@as(?u64, null), startTimeFromStat("1 (x) S 1 2")); }