summaryrefslogtreecommitdiffstats
path: root/sq/src/commands/autocrypt.rs
blob: 129f438e0420f60aa2c3e4b0aa03b510f2d7b427 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use sequoia_openpgp as openpgp;
use openpgp::{
    Cert,
    Result,
    armor,
    parse::Parse,
    serialize::Serialize,
};
use sequoia_autocrypt as autocrypt;

use crate::{
    Config,
    open_or_stdin,
    sq_cli,
};

pub fn dispatch(config: Config, c: &sq_cli::autocrypt::Command) -> Result<()> {
    use sq_cli::autocrypt::Subcommands::*;

    match &c.subcommand {
        Decode(command) => {
            let input = open_or_stdin(command.io.input.as_deref())?;
            let mut output = config.create_or_stdout_pgp(
                command.io.output.as_deref(),
                command.binary,
                armor::Kind::PublicKey,
            )?;
            let ac = autocrypt::AutocryptHeaders::from_reader(input)?;
            for h in &ac.headers {
                if let Some(ref cert) = h.key {
                    cert.serialize(&mut output)?;
                }
            }
            output.finalize()?;
        }
        EncodeSender(command) => {
            let input = open_or_stdin(command.io.input.as_deref())?;
            let mut output =
                config.create_or_stdout_safe(command.io.output.as_deref())?;
            let cert = Cert::from_reader(input)?;
            let addr = command.address.clone()
                .or_else(|| {
                    cert.with_policy(&config.policy, None)
                        .and_then(|vcert| vcert.primary_userid()).ok()
                        .map(|ca| ca.userid().to_string())
                });
            let ac = autocrypt::AutocryptHeader::new_sender(
                &config.policy,
                &cert,
                &addr.ok_or_else(|| anyhow::anyhow!(
                    "No well-formed primary userid found, use \
                     --address to specify one"))?,
                Some(command.prefer_encrypt.to_string().as_str()))?;
            write!(&mut output, "Autocrypt: ")?;
            ac.serialize(&mut output)?;
        },
    }

    Ok(())
}