// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Talking to the agent, and starting it when it is not there. //! //! The agent is normally this machine's own. Over SSH it can be another //! machine's: that machine forwards its agent's extra socket to this one //! (`RemoteForward`), and signatures made here are then made by it. The //! socket to talk to is, in order: //! //! 1. `BWGPG_AGENT_SOCKET`, when set, as with `SSH_AUTH_SOCK`. //! 2. `$XDG_RUNTIME_DIR/bwgpg-remote.sock`, when this is an SSH session //! (`SSH_CONNECTION` is set) and the socket is there: the forwarded one. //! 3. This machine's agent socket. //! //! A forwarded agent is never replaced by a local one when it is missing -- //! the local one would have no vault -- and is sent none of this machine's //! environment, whose display and terminal mean nothing to the other. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const Environ = std.process.Environ; const protocol = @import("protocol.zig"); const config_mod = @import("../config.zig"); pub const Error = error{ /// No agent is running and none was to be started. AgentNotRunning, /// An agent was started and never began answering. AgentDidNotStart, /// The agent closed the connection without an answer. AgentFailed, /// This is an SSH session meant to use another machine's agent, and /// nothing is listening on the forwarded socket: a socket file left /// behind by an SSH session that has ended. ForwardedSocketDead, /// The forwarded socket answers, but the agent at its other end does /// not: ssh accepted the connection and then closed it. ForwardedAgentGone, }; /// The name of the socket an SSH `RemoteForward` makes on this machine. pub const remote_socket_name = "bwgpg-remote.sock"; pub const Target = struct { path: []u8, /// Another machine's agent, over SSH. remote: bool, }; /// Which agent socket to use; see the top of this file. The caller frees /// `path`. pub fn target(gpa: Allocator, io: Io, env: *const Environ.Map) !Target { if (env.get("BWGPG_AGENT_SOCKET")) |p| { if (p.len > 0) return .{ .path = try gpa.dupe(u8, p), .remote = true }; } const ssh_connection: []const u8 = env.get("SSH_CONNECTION") orelse ""; if (ssh_connection.len > 0) { if (env.get("XDG_RUNTIME_DIR")) |dir| { const path = try std.fs.path.join(gpa, &.{ dir, remote_socket_name }); if (Io.Dir.cwd().access(io, path, .{})) { return .{ .path = path, .remote = true }; } else |_| gpa.free(path); } } return .{ .path = try config_mod.socketPath(gpa, io, env), .remote = false }; } /// Sends `req` and returns the agent's answer. With `autostart`, an agent /// that is not running is started first. /// /// The request's `env` is filled in from `env` here, so every request /// carries what a pinentry would need. pub fn call( gpa: Allocator, io: Io, env: *const Environ.Map, req: protocol.Request, autostart: bool, ) !std.json.Parsed(protocol.Response) { const t = try target(gpa, io, env); defer gpa.free(t.path); const address = try Io.net.UnixAddress.init(t.path); const stream = address.connect(io) catch |err| blk: { // A socket file with no listener behind it is refused, which 0.16 // has no name for and reports as `Unexpected`; whatever the // reason, nothing is at the other end of this file. if (t.remote) return switch (err) { error.Canceled => err, else => error.ForwardedSocketDead, }; // Whatever the reason -- no socket file, or one left behind by an // agent that died -- the cure is the same: start one, which clears // away a stale socket before it listens. if (!autostart) return error.AgentNotRunning; try start(gpa, io); // It needs a moment to derive nothing and bind a socket; allow it // five seconds, which is far more than it takes. for (0..100) |_| { io.sleep(.fromMilliseconds(50), .awake) catch {}; break :blk address.connect(io) catch continue; } return error.AgentDidNotStart; }; defer stream.close(io); var vars: std.ArrayList(protocol.EnvVar) = .empty; defer vars.deinit(gpa); if (!t.remote) for (protocol.forwarded_env) |name| { if (env.get(name)) |value| try vars.append(gpa, .{ .name = name, .value = value }); }; var full = req; full.env = vars.items; var read_buf: [4096]u8 = undefined; var write_buf: [4096]u8 = undefined; var reader = stream.reader(io, &read_buf); var writer = stream.writer(io, &write_buf); // Over SSH, a forward whose other end is gone accepts the connection and // then closes it, which the request can meet as easily as the answer. protocol.send(gpa, &writer.interface, full) catch |err| switch (err) { error.WriteFailed => return if (t.remote) error.ForwardedAgentGone else err, else => return err, }; return protocol.receive(protocol.Response, gpa, &reader.interface) catch |err| switch (err) { error.EndOfStream, error.ReadFailed => if (t.remote) error.ForwardedAgentGone else error.AgentFailed, else => err, }; } /// Starts `bwgpg agent` in the background. It detaches itself. fn start(gpa: Allocator, io: Io) !void { const self = try std.process.executablePathAlloc(io, gpa); defer gpa.free(self); // Not waited for: it outlives this process, and is reparented when this // one exits. _ = try std.process.spawn(io, .{ .argv = &.{ self, "agent" }, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore, .create_no_window = true, }); } test "the socket to use: the variable, the forward, then the local agent" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const dir = try tmp.dir.realPathFileAlloc(io, ".", gpa); defer gpa.free(dir); var env: Environ.Map = .init(gpa); defer env.deinit(); try env.put("XDG_RUNTIME_DIR", dir); try env.put("BWGPG_RUNTIME_DIR", dir); // Not an SSH session: the local agent. const local = try target(gpa, io, &env); defer gpa.free(local.path); try std.testing.expect(!local.remote); // An SSH session with no forward: still the local agent. try env.put("SSH_CONNECTION", "192.0.2.1 50000 192.0.2.2 22"); const no_forward = try target(gpa, io, &env); defer gpa.free(no_forward.path); try std.testing.expect(!no_forward.remote); // With the forwarded socket there, that one. var f = try tmp.dir.createFile(io, remote_socket_name, .{}); f.close(io); const forwarded = try target(gpa, io, &env); defer gpa.free(forwarded.path); try std.testing.expect(forwarded.remote); try std.testing.expect(std.mem.endsWith(u8, forwarded.path, remote_socket_name)); // And the variable above both. try env.put("BWGPG_AGENT_SOCKET", "/somewhere/else.sock"); const explicit = try target(gpa, io, &env); defer gpa.free(explicit.path); try std.testing.expect(explicit.remote); try std.testing.expectEqualStrings("/somewhere/else.sock", explicit.path); } /// An SSH session with the forwarded socket in `dir`, and the request /// `call` makes through it. fn callForwarded(gpa: Allocator, io: Io, dir: []const u8) !std.json.Parsed(protocol.Response) { var env: Environ.Map = .init(gpa); defer env.deinit(); try env.put("XDG_RUNTIME_DIR", dir); try env.put("BWGPG_RUNTIME_DIR", dir); try env.put("SSH_CONNECTION", "192.0.2.1 50000 192.0.2.2 22"); return call(gpa, io, &env, .{ .op = "status" }, true); } test "a forwarded socket nothing is listening on" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const dir = try tmp.dir.realPathFileAlloc(io, ".", gpa); defer gpa.free(dir); const path = try std.fs.path.join(gpa, &.{ dir, remote_socket_name }); defer gpa.free(path); // What an ended SSH session leaves: the file, with no listener. var server = try (try Io.net.UnixAddress.init(path)).listen(io, .{}); server.deinit(io); try std.testing.expectError(error.ForwardedSocketDead, callForwarded(gpa, io, dir)); } test "a forwarded socket whose far agent does not answer" { const gpa = std.testing.allocator; var threaded: Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io(); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const dir = try tmp.dir.realPathFileAlloc(io, ".", gpa); defer gpa.free(dir); const path = try std.fs.path.join(gpa, &.{ dir, remote_socket_name }); defer gpa.free(path); // What ssh does when the agent at the other end is not there: it // accepts, and closes. var server = try (try Io.net.UnixAddress.init(path)).listen(io, .{}); defer server.deinit(io); const Hangup = struct { fn run(s: *Io.net.Server, task_io: Io) void { const stream = s.accept(task_io) catch return; stream.close(task_io); } }; var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, Hangup.run, .{ &server, io }); try std.testing.expectError(error.ForwardedAgentGone, callForwarded(gpa, io, dir)); }