| 1 |
#![doc(html_favicon_url = "https://docs.sequoia-pgp.org/favicon.png")] |
| 2 |
#![doc(html_logo_url = "https://docs.sequoia-pgp.org/logo.svg")] |
| 3 |
|
| 4 |
#![allow(rustdoc::invalid_rust_codeblocks)] |
| 5 |
#![allow(rustdoc::broken_intra_doc_links)] |
| 6 |
#![allow(rustdoc::bare_urls)] |
| 7 |
#![doc = include_str!("../README.md")] |
| 8 |
|
| 9 |
use anyhow::Context as _; |
| 10 |
|
| 11 |
use std::borrow::Borrow; |
| 12 |
use std::path::Path; |
| 13 |
use std::str::FromStr; |
| 14 |
use std::time::SystemTime; |
| 15 |
|
| 16 |
use once_cell::sync::OnceCell; |
| 17 |
|
| 18 |
use sequoia_openpgp as openpgp; |
| 19 |
|
| 20 |
use openpgp::Result; |
| 21 |
use openpgp::Cert; |
| 22 |
use openpgp::parse::Parse; |
| 23 |
use openpgp::cert::prelude::*; |
| 24 |
|
| 25 |
use clap::FromArgMatches; |
| 26 |
|
| 27 |
// XXX: This could be its own crate, or preferably integrated into |
| 28 |
// toml_edit. |
| 29 |
mod toml_edit_tree; |
| 30 |
|
| 31 |
#[macro_use] mod macros; |
| 32 |
#[macro_use] mod log; |
| 33 |
|
| 34 |
mod sq; |
| 35 |
use sq::Sq; |
| 36 |
|
| 37 |
mod common; |
| 38 |
use common::PreferredUserID; |
| 39 |
pub mod utils; |
| 40 |
|
| 41 |
mod cli; |
| 42 |
use cli::SECONDS_IN_DAY; |
| 43 |
use cli::SECONDS_IN_YEAR; |
| 44 |
use cli::types::Time; |
| 45 |
use cli::types::Version; |
| 46 |
use cli::types::paths::StateDirectory; |
| 47 |
|
| 48 |
mod commands; |
| 49 |
pub mod compat; |
| 50 |
pub mod config; |
| 51 |
pub mod output; |
| 52 |
pub use output::Model; |
| 53 |
|
| 54 |
/// Converts sequoia_openpgp types for rendering. |
| 55 |
pub trait Convert<T> { |
| 56 |
/// Performs the conversion. |
| 57 |
fn convert(self) -> T; |
| 58 |
} |
| 59 |
|
| 60 |
impl Convert<humantime::FormattedDuration> for std::time::Duration { |
| 61 |
fn convert(self) -> humantime::FormattedDuration { |
| 62 |
humantime::format_duration(self) |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
impl Convert<humantime::FormattedDuration> for openpgp::types::Duration { |
| 67 |
fn convert(self) -> humantime::FormattedDuration { |
| 68 |
humantime::format_duration(self.into()) |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
impl Convert<chrono::DateTime<chrono::offset::Utc>> for std::time::SystemTime { |
| 73 |
fn convert(self) -> chrono::DateTime<chrono::offset::Utc> { |
| 74 |
chrono::DateTime::<chrono::offset::Utc>::from(self) |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
impl Convert<chrono::DateTime<chrono::offset::Utc>> for openpgp::types::Timestamp { |
| 79 |
fn convert(self) -> chrono::DateTime<chrono::offset::Utc> { |
| 80 |
std::time::SystemTime::from(self).convert() |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
/// Loads one TSK from every given file. |
| 85 |
fn load_keys<I, II>(files: I) -> openpgp::Result<Vec<Cert>> |
| 86 |
where |
| 87 |
I: Iterator<Item=II>, |
| 88 |
II: AsRef<Path>, |
| 89 |
{ |
| 90 |
let mut certs = vec![]; |
| 91 |
for f in files { |
| 92 |
let f = f.as_ref(); |
| 93 |
let cert = Cert::from_file(f) |
| 94 |
.context(format!("Failed to load key from file {}", f.display()))?; |
| 95 |
if ! cert.is_tsk() { |
| 96 |
return Err(anyhow::anyhow!( |
| 97 |
"Cert in file {} does not contain secret keys", f.display())); |
| 98 |
} |
| 99 |
certs.push(cert); |
| 100 |
} |
| 101 |
Ok(certs) |
| 102 |
} |
| 103 |
|
| 104 |
/// Loads one or more certs from every given file. |
| 105 |
fn load_certs<I, II>(files: I) -> openpgp::Result<Vec<Cert>> |
| 106 |
where |
| 107 |
I: Iterator<Item=II>, |
| 108 |
II: AsRef<Path>, |
| 109 |
{ |
| 110 |
let mut certs = vec![]; |
| 111 |
for f in files { |
| 112 |
let f = f.as_ref(); |
| 113 |
for maybe_cert in CertParser::from_file(f) |
| 114 |
.context(format!("Failed to load certs from file {}", f.display()))? |
| 115 |
{ |
| 116 |
certs.push(maybe_cert.context( |
| 117 |
format!("A cert from file {} is bad", f.display()) |
| 118 |
)?); |
| 119 |
} |
| 120 |
} |
| 121 |
Ok(certs) |
| 122 |
} |
| 123 |
|
| 124 |
/// Prints a warning if the user supplied "help" or "-help" to an |
| 125 |
/// positional argument. |
| 126 |
/// |
| 127 |
/// This should be used wherever a positional argument is followed by |
| 128 |
/// an optional positional argument. |
| 129 |
#[allow(dead_code)] |
| 130 |
fn help_warning(arg: &str) { |
| 131 |
if arg == "help" { |
| 132 |
weprintln!("Warning: \"help\" is not a subcommand here. \ |
| 133 |
Did you mean --help?"); |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
fn main() { |
| 138 |
if let Err(e) = real_main() { |
| 139 |
print_error_chain(&e); |
| 140 |
std::process::exit(1); |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
fn real_main() -> Result<()> { |
| 145 |
// In the future, we want to support multiple versions of the CLI |
| 146 |
// in a single binary. To support this, we have to parse |
| 147 |
// --cli-version before parsing the arguments! To make this |
| 148 |
// unambiguous, we require that --cli-version be the very first |
| 149 |
// argument, and parse it by hand. |
| 150 |
let mut skip_2 = false; |
| 151 |
if let Some(arg1) = std::env::args_os().nth(1) { |
| 152 |
if arg1.as_encoded_bytes() == &b"--cli-version"[..] { |
| 153 |
if let Some(arg2) = std::env::args_os().nth(2) { |
| 154 |
let version: Version |
| 155 |
= String::from_utf8(arg2.clone().into_encoded_bytes()) |
| 156 |
.map_err(Into::<anyhow::Error>::into) |
| 157 |
.and_then(|s| Ok(Version::from_str(&s)?)) |
| 158 |
.with_context(|| { |
| 159 |
format!("Parsing {:?}", |
| 160 |
String::from_utf8_lossy(arg2.as_encoded_bytes())) |
| 161 |
})?; |
| 162 |
|
| 163 |
// The version of the CLI that we implement. |
| 164 |
let cli_version: Version = Version::new( |
| 165 |
usize::from_str(env!("CARGO_PKG_VERSION_MAJOR")).unwrap(), |
| 166 |
usize::from_str(env!("CARGO_PKG_VERSION_MINOR")).unwrap(), |
| 167 |
usize::from_str(env!("CARGO_PKG_VERSION_PATCH")).unwrap()); |
| 168 |
|
| 169 |
if ! cli_version.is_acceptable_for(&version) { |
| 170 |
return Err(anyhow::anyhow!( |
| 171 |
"The required CLI version, {}, is not compatible with \ |
| 172 |
this version of sq, which implements version {} of \ |
| 173 |
the CLI", |
| 174 |
version, cli_version)); |
| 175 |
} |
| 176 |
|
| 177 |
skip_2 = true; |
| 178 |
} else { |
| 179 |
return Err(anyhow::anyhow!( |
| 180 |
"--cli-version missing required argument")); |
| 181 |
} |
| 182 |
} |
| 183 |
}; |
| 184 |
|
| 185 |
let mut cli = cli::build(true); |
| 186 |
let matches = if skip_2 { |
| 187 |
// Skip --cli-version and the version string. |
| 188 |
let args = std::env::args_os().enumerate().filter_map(|(i, arg)| { |
| 189 |
if i == 1 || i == 2 { |
| 190 |
None |
| 191 |
} else { |
| 192 |
Some(arg) |
| 193 |
} |
| 194 |
}); |
| 195 |
cli.clone().try_get_matches_from(args) |
| 196 |
} else { |
| 197 |
cli.clone().try_get_matches() |
| 198 |
}; |
| 199 |
|
| 200 |
let matches = match matches { |
| 201 |
Ok(matches) => matches, |
| 202 |
Err(mut err) => { |
| 203 |
// Warning: hack ahead! |
| 204 |
// |
| 205 |
// We want to hide global options in the help output for |
| 206 |
// subcommands, and we want to include values from the |
| 207 |
// configuration file in the help output. |
| 208 |
// |
| 209 |
// If we are showing the help output, we only want to |
| 210 |
// display the global options at the top-level; for |
| 211 |
// subcommands we hide the global options to not overwhelm |
| 212 |
// the user. |
| 213 |
// |
| 214 |
// Ideally, clap would provide a mechanism to only show |
| 215 |
// the help output for global options at the level they |
| 216 |
// are defined at. That's not the case. |
| 217 |
// |
| 218 |
// We can use `err` to figure out if we are showing the |
| 219 |
// help output, but it doesn't tell us what subcommand we |
| 220 |
// are showing the help for. Instead (and here's the |
| 221 |
// hack!), we compare the output. If it is the output for |
| 222 |
// the top-level `--help` or `-h`, then we are showing the |
| 223 |
// help for the top-level. If not, then we are showing |
| 224 |
// the help for a subcommand. In the former case, we |
| 225 |
// unhide the global options. |
| 226 |
use clap::error::ErrorKind; |
| 227 |
if err.kind() == ErrorKind::DisplayHelp |
| 228 |
|| err.kind() == ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand |
| 229 |
{ |
| 230 |
// We want to try to parse the configuration file. To |
| 231 |
// that end, we first need to find the path to it. |
| 232 |
let mut config = config::ConfigFile::default(); |
| 233 |
if let Some(augmentations) = cli::config::find_home().and_then( |
| 234 |
|home| config.read_and_augment(&home).ok()) |
| 235 |
{ |
| 236 |
cli::config::set_augmentations(augmentations); |
| 237 |
} |
| 238 |
|
| 239 |
let output = err.render(); |
| 240 |
let output = if output == cli.render_long_help() { |
| 241 |
Some(cli::build(false).render_long_help()) |
| 242 |
} else if output == cli.render_help() { |
| 243 |
Some(cli::build(false).render_help()) |
| 244 |
} else { |
| 245 |
// Redo the parse so that the help message will |
| 246 |
// include any augmentations. |
| 247 |
err = cli::build(true).try_get_matches().unwrap_err(); |
| 248 |
None |
| 249 |
}; |
| 250 |
|
| 251 |
if let Some(output) = output { |
| 252 |
if err.use_stderr() { |
| 253 |
eprint!("{}", output); |
| 254 |
} else { |
| 255 |
print!("{}", output); |
| 256 |
} |
| 257 |
std::process::exit(err.exit_code()); |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
// Print the error message. |
| 262 |
err.print()?; |
| 263 |
|
| 264 |
// Then, figure out if this is a usage message, and |
| 265 |
// extract the usage string. |
| 266 |
if let Some(usage) = err.context() |
| 267 |
.find_map(|(kind, value)| |
| 268 |
(kind == clap::error::ContextKind::Usage) |
| 269 |
.then_some(value)) |
| 270 |
{ |
| 271 |
print_examples(&cli, usage)?; |
| 272 |
} |
| 273 |
|
| 274 |
// Finally, exit with an error code. |
| 275 |
std::process::exit(err.exit_code()); |
| 276 |
} |
| 277 |
}; |
| 278 |
let c = cli::SqCommand::from_arg_matches(&matches)?; |
| 279 |
|
| 280 |
let home = match &c.home { |
| 281 |
Some(StateDirectory::Absolute(p)) => |
| 282 |
Some(sequoia_directories::Home::new(p.clone())?), |
| 283 |
None | Some(StateDirectory::Default) => |
| 284 |
Some(sequoia_directories::Home::default() |
| 285 |
.ok_or(anyhow::anyhow!("no default SEQUOIA_HOME \ |
| 286 |
on this platform"))? |
| 287 |
.clone()), |
| 288 |
Some(StateDirectory::None) => None, |
| 289 |
}; |
| 290 |
|
| 291 |
// Parse the configuration file. |
| 292 |
let mut config_file = config::ConfigFile::default_config(home.as_ref())?; |
| 293 |
let mut config = if let Some(home) = &home { |
| 294 |
// Sanity check `cli::config::find_home`. |
| 295 |
debug_assert_eq!(home.location(), |
| 296 |
cli::config::find_home().unwrap().location()); |
| 297 |
|
| 298 |
config_file.read(home) |
| 299 |
.with_context(|| format!( |
| 300 |
"while reading configuration file {}", |
| 301 |
config::ConfigFile::file_name(home).display()))? |
| 302 |
} else { |
| 303 |
Default::default() |
| 304 |
}; |
| 305 |
|
| 306 |
config.init_verbose(c.verbose, matches.value_source("verbose")); |
| 307 |
config.init_quiet(c.quiet, matches.value_source("quiet")); |
| 308 |
|
| 309 |
let time_is_now = c.time.is_none(); |
| 310 |
let time: SystemTime = if let Some(t) = c.time.as_ref() { |
| 311 |
t.to_system_time(std::time::SystemTime::now())? |
| 312 |
} else { |
| 313 |
std::time::SystemTime::now() |
| 314 |
}; |
| 315 |
|
| 316 |
let policy_as_of: SystemTime = if let Some(t) = c.policy_as_of.clone() { |
| 317 |
t.to_system_time(time)? |
| 318 |
} else { |
| 319 |
time.clone() |
| 320 |
}; |
| 321 |
|
| 322 |
let mut policy = config.policy(policy_as_of)?; |
| 323 |
|
| 324 |
let known_notations_store = c.known_notation.clone(); |
| 325 |
let known_notations = known_notations_store |
| 326 |
.iter() |
| 327 |
.map(|n| n.as_str()) |
| 328 |
.collect::<Vec<&str>>(); |
| 329 |
policy.good_critical_notations(&known_notations); |
| 330 |
|
| 331 |
let mut password_cache = Vec::new(); |
| 332 |
for password_file in &c.password_file { |
| 333 |
let password = std::fs::read(&password_file) |
| 334 |
.with_context(|| { |
| 335 |
format!("Reading {}", password_file.display()) |
| 336 |
})?; |
| 337 |
password_cache.push(password.into()); |
| 338 |
}; |
| 339 |
|
| 340 |
#[allow(deprecated)] |
| 341 |
let sq = Sq { |
| 342 |
config_file, |
| 343 |
config, |
| 344 |
overwrite: c.overwrite, |
| 345 |
batch: c.batch, |
| 346 |
time, |
| 347 |
time_is_now, |
| 348 |
policy_as_of, |
| 349 |
policy: &policy, |
| 350 |
home, |
| 351 |
cert_store_path: c.cert_store.clone(), |
| 352 |
keyrings: c.keyring.clone(), |
| 353 |
keyring_tsks: Default::default(), |
| 354 |
cert_store: OnceCell::new(), |
| 355 |
trust_roots: c.trust_roots.clone(), |
| 356 |
trust_root_local: Default::default(), |
| 357 |
key_store_path: c.key_store.clone(), |
| 358 |
key_store: OnceCell::new(), |
| 359 |
password_cache: password_cache.into(), |
| 360 |
}; |
| 361 |
|
| 362 |
match commands::dispatch(sq, c, &matches) { |
| 363 |
Ok(()) => Ok(()), |
| 364 |
Err(err) => { |
| 365 |
use clap::error::ErrorFormatter; |
| 366 |
|
| 367 |
if err.is::<clap::Error>() { |
| 368 |
// We want to go from an ArgMatches to the |
| 369 |
// corresponding Command. Given an ArgMatches, we can |
| 370 |
// walk down it, to get the name of each (sub)command. |
| 371 |
// Then we can walk down the top-level Command to get |
| 372 |
// the |
| 373 |
|
| 374 |
// Recover the subcommands, e.g., &["key", "list"]. |
| 375 |
let mut m = &matches; |
| 376 |
let mut trail = Vec::new(); |
| 377 |
while let Some((name, matches)) = m.subcommand() { |
| 378 |
trail.push(name); |
| 379 |
m = matches; |
| 380 |
} |
| 381 |
|
| 382 |
// Get the corresponding command in `cli`. |
| 383 |
let mut command = Some(&mut cli); |
| 384 |
for intermediate in trail.into_iter() { |
| 385 |
if let Some(c) = command { |
| 386 |
command = c.find_subcommand_mut(intermediate); |
| 387 |
} |
| 388 |
} |
| 389 |
|
| 390 |
let err = err.downcast::<clap::Error>().unwrap(); |
| 391 |
let exit_code = err.exit_code(); |
| 392 |
if let Some(mut command) = command { |
| 393 |
let err = err.format(&mut command); |
| 394 |
|
| 395 |
err.print()?; |
| 396 |
|
| 397 |
if let Some(examples) = command.get_after_help() { |
| 398 |
weprintln!("\n{}", examples); |
| 399 |
} |
| 400 |
} else { |
| 401 |
// Ummm... something went wrong: we should be able |
| 402 |
// to find the subcommand. But let's not panic. |
| 403 |
// Just show the error, and quit. |
| 404 |
if err.use_stderr() { |
| 405 |
eprintln!( |
| 406 |
"{}", |
| 407 |
clap::error::RichFormatter::format_error(&err)); |
| 408 |
} else { |
| 409 |
println!( |
| 410 |
"{}", |
| 411 |
clap::error::RichFormatter::format_error(&err)); |
| 412 |
} |
| 413 |
} |
| 414 |
|
| 415 |
std::process::exit(exit_code); |
| 416 |
} else { |
| 417 |
Err(err) |
| 418 |
} |
| 419 |
} |
| 420 |
} |
| 421 |
} |
| 422 |
|
| 423 |
// Sometimes the same error cascades, e.g.: |
| 424 |
// |
| 425 |
// ``` |
| 426 |
// $ sq-wot --time 20230110T0406 --keyring sha1.pgp path B5FA089BA76FE3E17DC11660960E53286738F94C 231BC4AB9D8CAB86D1622CE02C0CE554998EECDB FABA8485B2D4D5BF1582AA963A8115E774FA9852 "<[email protected]>" |
| 427 |
// [ ] FABA8485B2D4D5BF1582AA963A8115E774FA9852 <[email protected]>: not authenticated (0%) |
| 428 |
// ◯ B5FA089BA76FE3E17DC11660960E53286738F94C ("<[email protected]>") |
| 429 |
// │ No adequate certification found. |
| 430 |
// │ No binding signature at time 2023-01-10T04:06:00Z |
| 431 |
// │ No binding signature at time 2023-01-10T04:06:00Z |
| 432 |
// │ No binding signature at time 2023-01-10T04:06:00Z |
| 433 |
// ... |
| 434 |
// ``` |
| 435 |
// |
| 436 |
// Compress these. |
| 437 |
fn error_chain(err: &anyhow::Error) -> Vec<String> { |
| 438 |
let mut errs = std::iter::once(err.to_string()) |
| 439 |
.chain(err.chain().map(|source| source.to_string())) |
| 440 |
.collect::<Vec<String>>(); |
| 441 |
errs.dedup(); |
| 442 |
errs |
| 443 |
} |
| 444 |
|
| 445 |
/// Prints the error and causes, if any. |
| 446 |
pub fn print_error_chain(err: &anyhow::Error) { |
| 447 |
weprintln!(); |
| 448 |
weprintln!(initial_indent=" Error: ", "{}", err); |
| 449 |
|
| 450 |
if err.backtrace().status() == std::backtrace::BacktraceStatus::Captured { |
| 451 |
weprintln!(); |
| 452 |
weprintln!(initial_indent=" ", "{}", err.backtrace()); |
| 453 |
} |
| 454 |
err.chain().skip(1).for_each( |
| 455 |
|cause| weprintln!(initial_indent="because: ", "{}", cause)); |
| 456 |
} |
| 457 |
|
| 458 |
/// Returns the error chain as a string. |
| 459 |
/// |
| 460 |
/// The error and causes are separated by `error_separator`. The |
| 461 |
/// causes are separated by `cause_separator`, or, if that is `None`, |
| 462 |
/// `error_separator`. |
| 463 |
pub fn display_error_chain<'a, E, C>(err: E, |
| 464 |
error_separator: &str, |
| 465 |
cause_separator: C) |
| 466 |
-> String |
| 467 |
where E: Borrow<anyhow::Error>, |
| 468 |
C: Into<Option<&'a str>> |
| 469 |
{ |
| 470 |
let err = err.borrow(); |
| 471 |
let cause_separator = cause_separator.into(); |
| 472 |
|
| 473 |
let error_chain = error_chain(err); |
| 474 |
match error_chain.len() { |
| 475 |
0 => unreachable!(), |
| 476 |
1 => { |
| 477 |
error_chain.into_iter().next().expect("have one") |
| 478 |
} |
| 479 |
2 => { |
| 480 |
format!("{}{}{}", |
| 481 |
error_chain[0], |
| 482 |
error_separator, |
| 483 |
error_chain[1]) |
| 484 |
} |
| 485 |
_ => { |
| 486 |
if let Some(cause_separator) = cause_separator { |
| 487 |
format!("{}{}{}", |
| 488 |
error_chain[0], |
| 489 |
error_separator, |
| 490 |
error_chain[1..].join(cause_separator)) |
| 491 |
} else { |
| 492 |
error_chain.join(error_separator) |
| 493 |
} |
| 494 |
} |
| 495 |
} |
| 496 |
|
| 497 |
} |
| 498 |
|
| 499 |
pub fn one_line_error_chain<E>(err: E) -> String |
| 500 |
where E: Borrow<anyhow::Error>, |
| 501 |
{ |
| 502 |
display_error_chain(err, ": ", ", because ") |
| 503 |
} |
| 504 |
|
| 505 |
/// Given a `clap::Command` and a usage string, try to augment the |
| 506 |
/// usage message with relevant examples. |
| 507 |
fn print_examples(cli: &clap::Command, usage: impl ToString) -> Result<()> { |
| 508 |
// First, find the invoked subcommand. |
| 509 |
let usage = usage.to_string(); |
| 510 |
let prefix = usage.find("sq "); |
| 511 |
let subcommands = if let Some(i) = prefix { |
| 512 |
usage[i + 3..].split(" ") |
| 513 |
// Split, but only take the parts that do not denote options |
| 514 |
// or flags. |
| 515 |
.take_while(|p| p.chars().all(|c| c.is_alphabetic())) |
| 516 |
} else { |
| 517 |
// Odd... |
| 518 |
return Ok(()); |
| 519 |
}; |
| 520 |
|
| 521 |
// Now traverse the CLI tree to find the subcommand. |
| 522 |
let mut cmd = cli; |
| 523 |
for sub in subcommands { |
| 524 |
cmd = if let Some(c) = cmd.get_subcommands() |
| 525 |
.find(|c| c.get_name() == sub) |
| 526 |
{ |
| 527 |
c |
| 528 |
} else { |
| 529 |
// Very odd... |
| 530 |
return Ok(()); |
| 531 |
}; |
| 532 |
} |
| 533 |
|
| 534 |
// And print the examples, if any. |
| 535 |
if let Some(examples) = cmd.get_after_help() { |
| 536 |
weprintln!("\n{}", examples); |
| 537 |
} |
| 538 |
|
| 539 |
Ok(()) |
| 540 |
} |
| 541 |
|
| 542 |
#[cfg(test)] |
| 543 |
mod test { |
| 544 |
use super::*; |
| 545 |
|
| 546 |
// Run some clap tests. |
| 547 |
#[test] |
| 548 |
fn verify_app() { |
| 549 |
let cli = cli::build(true); |
| 550 |
cli.debug_assert(); |
| 551 |
} |
| 552 |
} |