// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Deciding what a gpg command line is asking for. //! //! bwgpg stands in for gpg as `gpg.program`, so it is handed whatever git //! would hand gpg. It handles one thing itself: a detached signature, which //! is what `git commit -S` and `git tag -s` ask for with `--status-fd=2 -bsau //! `. Everything else goes to the real gpg unchanged, which is how //! `git verify-commit` and `git log --show-signature` keep working. //! //! So the parse has one job, and it has to get it right on the command lines //! gpg accepts: clustered short options (`-bsau KEY`), an option's value //! glued on (`-uKEY`, `--local-user=KEY`) or in the next argument, and `--` //! ending the options. An option taking a value that is not in the tables //! below would have its value read as a file name, which matters only for a //! signing command line, and only if it names that file first. const std = @import("std"); const testing = std.testing; pub const Mode = enum { /// Not a signing operation: hand the whole command line to gpg. passthrough, /// A detached signature, which bwgpg makes itself. detach_sign, /// A signing operation bwgpg cannot make: an inline or clear-signed /// message, a text-mode signature, or signing combined with encryption. unsupported_sign, }; pub const Parsed = struct { mode: Mode = .passthrough, /// The key selector: the last `-u`/`--local-user`, or `--default-key` if /// there was none. key_selector: ?[]const u8 = null, armor: bool = false, status_fd: ?u32 = null, output: ?[]const u8 = null, /// The file to sign, when it is not standard input. input: ?[]const u8 = null, /// More than one input file, which a detached signature cannot cover. extra_inputs: bool = false, }; /// Short options that take a value. const short_with_value = "uroRfzN"; /// Long options that take a value, when it is given as the next argument /// rather than after `=`. Only the ones that could plausibly appear beside a /// signing command; the rest are passed through untouched anyway. const long_with_value = [_][]const u8{ "local-user", "default-key", "recipient", "hidden-recipient", "output", "status-fd", "logger-fd", "attribute-fd", "command-fd", "passphrase-fd", "passphrase-file", "passphrase", "homedir", "keyring", "trustdb-name", "digest-algo", "cipher-algo", "compress-algo", "compress-level", "keyserver", "trust-model", "comment", "set-filename", "faked-system-time", "encrypt-to", "sig-notation", "set-notation", "keyid-format", "list-options", "verify-options", "export-options", "import-options", "pinentry-mode", "default-recipient", "agent-program", "display", "ttyname", "ttytype", "lc-ctype", "lc-messages", "recipient-file", "status-file", "logger-file", "personal-digest-preferences", "weak-digest", "sig-keyserver-url", "hidden-encrypt-to", "s2k-digest-algo", "s2k-cipher-algo", "s2k-mode", "s2k-count", "options", }; fn longTakesValue(name: []const u8) bool { for (long_with_value) |candidate| { if (std.mem.eql(u8, candidate, name)) return true; } return false; } const Flags = struct { sign: bool = false, detach: bool = false, clear: bool = false, encrypt: bool = false, text: bool = false, default_key: ?[]const u8 = null, }; /// Classifies `args`, which excludes the program name. pub fn parse(args: []const []const u8) Parsed { var out: Parsed = .{}; var f: Flags = .{}; var i: usize = 0; var options_done = false; while (i < args.len) : (i += 1) { const arg = args[i]; if (options_done or arg.len < 2 or arg[0] != '-') { // A lone "-" is standard input, which is the default anyway. if (std.mem.eql(u8, arg, "-")) continue; if (out.input == null) out.input = arg else out.extra_inputs = true; continue; } if (std.mem.eql(u8, arg, "--")) { options_done = true; continue; } if (arg[1] == '-') { const body = arg[2..]; const eq = std.mem.findScalar(u8, body, '='); const name = if (eq) |e| body[0..e] else body; var value: ?[]const u8 = if (eq) |e| body[e + 1 ..] else null; if (value == null and longTakesValue(name) and i + 1 < args.len) { i += 1; value = args[i]; } applyLong(&out, &f, name, value); continue; } // A cluster of short options. One that takes a value takes the rest // of the cluster, or the next argument when it ends the cluster. var j: usize = 1; while (j < arg.len) : (j += 1) { const c = arg[j]; if (std.mem.findScalar(u8, short_with_value, c) != null) { const value: ?[]const u8 = if (j + 1 < arg.len) arg[j + 1 ..] else if (i + 1 < args.len) blk: { i += 1; break :blk args[i]; } else null; applyShort(&out, &f, c, value); break; } applyShort(&out, &f, c, null); } } if (out.key_selector == null) out.key_selector = f.default_key; if (f.sign or f.detach or f.clear) { out.mode = if (f.detach and !f.clear and !f.encrypt and !f.text) .detach_sign else .unsupported_sign; } return out; } fn applyShort(out: *Parsed, f: *Flags, c: u8, value: ?[]const u8) void { switch (c) { 's' => f.sign = true, 'b' => f.detach = true, 'a' => out.armor = true, 'e', 'c' => f.encrypt = true, 't' => f.text = true, 'u' => out.key_selector = value, 'o' => out.output = value, else => {}, } } fn applyLong(out: *Parsed, f: *Flags, name: []const u8, value: ?[]const u8) void { const eql = std.mem.eql; if (eql(u8, name, "sign")) { f.sign = true; } else if (eql(u8, name, "detach-sign")) { f.detach = true; } else if (eql(u8, name, "clearsign") or eql(u8, name, "clear-sign")) { f.clear = true; } else if (eql(u8, name, "encrypt") or eql(u8, name, "symmetric")) { f.encrypt = true; } else if (eql(u8, name, "textmode")) { f.text = true; } else if (eql(u8, name, "no-textmode")) { f.text = false; } else if (eql(u8, name, "armor") or eql(u8, name, "armour")) { out.armor = true; } else if (eql(u8, name, "no-armor") or eql(u8, name, "no-armour")) { out.armor = false; } else if (eql(u8, name, "local-user")) { out.key_selector = value; } else if (eql(u8, name, "default-key")) { f.default_key = value; } else if (eql(u8, name, "output")) { out.output = value; } else if (eql(u8, name, "status-fd")) { out.status_fd = if (value) |v| std.fmt.parseInt(u32, v, 10) catch null else null; } } test "what git commit -S sends" { const p = parse(&.{ "--status-fd=2", "-bsau", "536FCACF39ACEAB9D79316CB1BB9EB7EA602265B" }); try testing.expectEqual(Mode.detach_sign, p.mode); try testing.expectEqualStrings("536FCACF39ACEAB9D79316CB1BB9EB7EA602265B", p.key_selector.?); try testing.expect(p.armor); try testing.expectEqual(@as(?u32, 2), p.status_fd); try testing.expectEqual(@as(?[]const u8, null), p.input); } test "values glued on, in the next argument, and after =" { const a = parse(&.{ "-b", "-a", "-uKEY" }); try testing.expectEqual(Mode.detach_sign, a.mode); try testing.expectEqualStrings("KEY", a.key_selector.?); const b = parse(&.{ "--detach-sign", "--local-user", "KEY", "--armor", "--status-fd", "1", "file.txt" }); try testing.expectEqual(Mode.detach_sign, b.mode); try testing.expectEqualStrings("KEY", b.key_selector.?); try testing.expectEqual(@as(?u32, 1), b.status_fd); try testing.expectEqualStrings("file.txt", b.input.?); const c = parse(&.{ "--local-user=KEY", "-b", "-o", "out.sig", "--", "-weird-name" }); try testing.expectEqualStrings("KEY", c.key_selector.?); try testing.expectEqualStrings("out.sig", c.output.?); try testing.expectEqualStrings("-weird-name", c.input.?); try testing.expect(!c.armor); } test "default-key stands in for a missing local-user" { const p = parse(&.{ "--default-key", "DEF", "-bs" }); try testing.expectEqualStrings("DEF", p.key_selector.?); const q = parse(&.{ "--default-key", "DEF", "-u", "USR", "-bs" }); try testing.expectEqualStrings("USR", q.key_selector.?); const r = parse(&.{"-bs"}); try testing.expectEqual(@as(?[]const u8, null), r.key_selector); } test "verification and everything else pass through" { try testing.expectEqual(Mode.passthrough, parse(&.{ "--status-fd=1", "--verify", "/tmp/sig", "-" }).mode); try testing.expectEqual(Mode.passthrough, parse(&.{ "--list-keys", "--with-colons" }).mode); try testing.expectEqual(Mode.passthrough, parse(&.{ "-d", "file.gpg" }).mode); try testing.expectEqual(Mode.passthrough, parse(&.{}).mode); // An option value that happens to look like a command is not one. try testing.expectEqual(Mode.passthrough, parse(&.{ "--comment", "-s", "--list-keys" }).mode); } test "signing bwgpg does not do is reported rather than attempted" { try testing.expectEqual(Mode.unsupported_sign, parse(&.{ "-s", "file" }).mode); try testing.expectEqual(Mode.unsupported_sign, parse(&.{ "--clearsign", "file" }).mode); try testing.expectEqual(Mode.unsupported_sign, parse(&.{ "-bse", "-r", "X" }).mode); try testing.expectEqual(Mode.unsupported_sign, parse(&.{ "-bt", "file" }).mode); } test "a detached signature of two files is flagged" { const p = parse(&.{ "-b", "one", "two" }); try testing.expect(p.extra_inputs); }