pqr 0.1.0

Post-quantum resistant encryption, decryption, and key generation from the command line. Easy to use, with sane defaults.
mod decrypt;
mod encrypt;
mod identity;
mod recipient;
mod shared;

use std::io::{IsTerminal, Read, Write};
use std::process::ExitCode;

use clap::{Args, CommandFactory, Parser, Subcommand};

use shared::{Failure, Result};

/// Post-quantum resistant encryption, decryption, and key generation from the command line.
/// Easy to use, with sane defaults.
///
/// Encrypt: `pqr "text"` or `echo text | pqr` (only you can decrypt it).
/// Decrypt: `pqr -d msg.pgp`, `pqr -d "<armored message>"`, or `pqr -d < msg.pgp`.
#[derive(Parser)]
#[command(version, about, args_conflicts_with_subcommands = true)]
struct Cli {
    #[command(flatten)]
    main: MainArgs,
    #[command(subcommand)]
    command: Option<Cmd>,
}

#[derive(Args)]
struct MainArgs {
    /// Decrypt FILE or a pasted message (reads stdin when omitted).
    #[arg(short, long, conflicts_with = "encrypt")]
    decrypt: bool,
    /// Encrypt TEXT (reads stdin when omitted). Same as bare `pqr`, handy in scripts.
    #[arg(short, long)]
    encrypt: bool,
    /// Which of your keys to use (default: main).
    #[arg(short, long)]
    identity: Option<String>,
    /// Encrypt for someone else: a public key file such as server.pub, or the key text itself.
    #[arg(short, long, value_name = "FILE|KEY", allow_hyphen_values = true)]
    recipient: Option<String>,
    /// Text to encrypt with your key (visible in `ps` and shell history; use stdin for secrets),
    /// or with -d the file or armored message to decrypt.
    #[arg(value_name = "TEXT|FILE", allow_hyphen_values = true)]
    text: Option<String>,
}

#[derive(Subcommand)]
enum Cmd {
    /// Create a key pair and print its armored public key.
    Keygen {
        /// Name for the key pair (default: main).
        #[arg(short, long, default_value = identity::DEFAULT_IDENTITY)]
        identity: String,
    },
}

fn read_stdin() -> Result<Vec<u8>> {
    let mut buf = Vec::new();
    std::io::stdin().read_to_end(&mut buf)?;
    Ok(buf)
}

fn usage_failure() -> Failure {
    let help = Cli::command().render_usage();
    Failure::usage(format!("no input given\n\n{help}"))
}

fn run_encrypt(args: MainArgs) -> Result<()> {
    if args.recipient.is_some() && args.identity.is_some() {
        return Err(Failure::usage("use either -r or -i, not both"));
    }
    let input = match args.text {
        Some(text) => text.into_bytes(),
        None if std::io::stdin().is_terminal() => return Err(usage_failure()),
        None => read_stdin()?,
    };
    let key = match args.recipient {
        Some(value) => recipient::load(&value)?,
        None => identity::load_public(
            args.identity
                .as_deref()
                .unwrap_or(identity::DEFAULT_IDENTITY),
        )?,
    };
    let armored = encrypt::encrypt(&key, &input)?;
    std::io::stdout().write_all(armored.as_bytes())?;
    Ok(())
}

/// Turn the `-d` argument into message bytes: an armored string, else an existing file.
fn message_bytes(arg: &str) -> Result<Vec<u8>> {
    if arg.trim_start().starts_with("-----BEGIN PGP MESSAGE-----") {
        return Ok(arg.as_bytes().to_vec());
    }
    let path = std::path::Path::new(arg);
    if path.is_file() {
        return Ok(std::fs::read(path)?);
    }
    // Never echo the argument: it may be a secret pasted without its armor header.
    Err(Failure::usage("not a file or a PGP message"))
}

fn run_decrypt(args: MainArgs) -> Result<()> {
    if args.recipient.is_some() {
        return Err(Failure::usage("-d cannot be combined with -r"));
    }
    let arg = args.text.clone();
    let name = args
        .identity
        .as_deref()
        .unwrap_or(identity::DEFAULT_IDENTITY);
    let key = identity::load_secret(name)?;
    let input = match arg {
        Some(arg) => message_bytes(&arg)?,
        None if std::io::stdin().is_terminal() => return Err(usage_failure()),
        None => read_stdin()?,
    };
    let plain = decrypt::decrypt(&key, &input)?;
    let mut out = std::io::stdout();
    out.write_all(&plain)?;
    // Keep the shell prompt on its own line when a person reads the output.
    if out.is_terminal() && !plain.ends_with(b"\n") {
        out.write_all(b"\n")?;
    }
    Ok(())
}

/// The positional allows hyphen values so armored messages work; refuse other flag-like
/// text unless the person put `--` before it.
fn refuse_unknown_flag(text: Option<&str>) -> Result<()> {
    let Some(text) = text else { return Ok(()) };
    let armor = text.starts_with("-----BEGIN PGP");
    if text.starts_with('-') && !armor && !std::env::args().any(|a| a == "--") {
        return Err(Failure::usage(format!(
            "unknown option: {text} (use -- before text that starts with -)"
        )));
    }
    Ok(())
}

fn run(cli: Cli) -> Result<()> {
    refuse_unknown_flag(cli.main.text.as_deref())?;
    match cli.command {
        Some(Cmd::Keygen { identity }) => {
            let public = identity::keygen(&identity)?;
            std::io::stdout().write_all(public.as_bytes())?;
            Ok(())
        }
        None if cli.main.decrypt => run_decrypt(cli.main),
        None => run_encrypt(cli.main),
    }
}

fn main() -> ExitCode {
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(err) => {
            // Usage errors exit 1 (not clap's 2); --help and --version exit 0.
            let _ = err.print();
            return ExitCode::from(u8::from(err.use_stderr()));
        }
    };
    // The post-quantum math keeps large buffers on the stack. Windows gives the main
    // thread only 1 MB (Unix gives 8 MB), so run the work on a thread with room to spare.
    let worker = std::thread::Builder::new()
        .stack_size(WORK_STACK_BYTES)
        .spawn(move || run(cli))
        .expect("cannot start the worker thread");
    match worker
        .join()
        .unwrap_or_else(|_| Err(Failure::usage("internal error")))
    {
        Ok(()) => ExitCode::SUCCESS,
        Err(failure) => {
            eprintln!("pqr: {failure}");
            ExitCode::from(failure.code)
        }
    }
}

const WORK_STACK_BYTES: usize = 16 * 1024 * 1024;