Debian Codegraph @

src/cli/types.rs

raw
1 //! Types used in the command-line parser.
2
3 use std::fmt::Display;
4 use std::fmt::Formatter;
5 use std::io::Read;
6 use std::io::stdin;
7 use std::path::Path;
8 use std::path::PathBuf;
9 use std::str::FromStr;
10 use std::sync::mpsc;
11 use std::thread;
12 use std::time::Duration;
13
14 use anyhow::Context;
15 use anyhow::Result;
16
17 use buffered_reader::BufferedReader;
18 use buffered_reader::File;
19 use buffered_reader::Generic;
20
21 /// Common types for arguments of sq.
22 use clap::ValueEnum;
23
24 use sequoia_openpgp as openpgp;
25 use openpgp::fmt::hex;
26 use openpgp::KeyHandle;
27 use openpgp::packet::UserID;
28 use openpgp::parse::Cookie;
29 use openpgp::types::KeyFlags;
30 use openpgp::types::SymmetricAlgorithm;
31
32 pub mod cert_designator;
33 pub use cert_designator::CertDesignators;
34 pub mod key_designator;
35 pub use key_designator::KeyDesignators;
36 pub mod paths;
37 pub mod userid_designator;
38 pub use userid_designator::UserIDDesignators;
39 pub mod expiration;
40 pub use expiration::Expiration;
41 pub use expiration::ExpirationArg;
42 pub mod profile;
43 pub use profile::Profile;
44 pub mod signature_notations;
45 pub use signature_notations::SignatureNotationsArg;
46 pub mod special_names;
47 pub use special_names::SpecialName;
48 pub mod time;
49 pub use time::Time;
50 pub mod version;
51 pub use version::Version;
52
53 // A local copy of the standard library's AsRef trait.
54 //
55 // We need a local copy of AsRef, as we need to implement AsRef for
56 // UserID, but due to the orphan rule, we can't. Instead we have to
57 // make a local copy of AsRef or UserID. Copying AsRef is less
58 // invasive.
59 pub trait MyAsRef<T>
60 where
61 T: ?Sized,
62 {
63 fn as_ref(&self) -> &T;
64 }
65
66 impl MyAsRef<UserID> for UserID {
67 fn as_ref(&self) -> &UserID {
68 self
69 }
70 }
71
72 impl MyAsRef<UserID> for &UserID {
73 fn as_ref(&self) -> &UserID {
74 self
75 }
76 }
77
78 /// A trait to provide const &str for clap annotations for custom structs
79 pub trait ClapData {
80 /// The clap value name.
81 const VALUE_NAME: &'static str;
82
83 /// The clap help text for required arguments.
84 ///
85 /// Use this as the default help text if the value must be given.
86 const HELP_REQUIRED: &'static str;
87
88 /// The clap help text for optional arguments.
89 ///
90 /// Use this as the default help text if the value must not be
91 /// given, because either:
92 ///
93 /// - there is a default value, or
94 /// - the type is an `Option<T>`.
95 const HELP_OPTIONAL: &'static str;
96 }
97
98 /// Reads from stdin, and prints a warning to stderr if no input is
99 /// read within a certain amount of time.
100 pub struct StdinWarning {
101 do_warn: bool,
102 /// The thing that is being waited for. See `StdinWarning::emit`.
103 thing: &'static str,
104 }
105
106 /// Print a warning if we don't get any input after this amount of
107 /// time.
108 const STDIN_TIMEOUT: Duration = std::time::Duration::new(2, 0);
109
110 impl StdinWarning {
111 /// Emit a custom warning if no input is received.
112 pub fn new(thing: &'static str) -> Self {
113 Self {
114 do_warn: true,
115 thing,
116 }
117 }
118
119 /// Emit a warning that a certificate is expected if no input is
120 /// received.
121 pub fn openpgp() -> Self {
122 Self::new("OpenPGP data")
123 }
124
125 /// Emit a warning that certificates are expected if no input is
126 /// received.
127 pub fn certs() -> Self {
128 Self::new("OpenPGP certificates")
129 }
130
131 pub fn emit(&self) {
132 eprintln!("Waiting for {} on stdin...", self.thing);
133 }
134 }
135
136 impl Read for StdinWarning {
137 fn read(&mut self, mut buf: &mut [u8]) -> std::io::Result<usize> {
138 if self.do_warn {
139 if buf.len() == 0 {
140 return Ok(0);
141 }
142
143 // We may warn the user. We don't want to print the
144 // warning if we read anything. If we try to read two
145 // bytes, we might read one byte, block, print the
146 // warning, and then later read a second byte. That's not
147 // great. Thus, we don't read more than a single byte.
148 buf = &mut buf[..1];
149
150 // Don't warn again.
151 self.do_warn = false;
152
153 thread::scope(|s| {
154 let (sender, receiver) = mpsc::channel::<()>();
155
156 s.spawn(move || {
157 if let Err(mpsc::RecvTimeoutError::Timeout)
158 = receiver.recv_timeout(STDIN_TIMEOUT)
159 {
160 self.emit();
161 }
162 });
163
164 let result = stdin().read(buf);
165 // Force the thread to exit now.
166 drop(sender);
167 result
168 })
169 } else {
170 stdin().read(buf)
171 }
172 }
173 }
174
175 /// A type wrapping an optional PathBuf to use as stdin or file input
176 ///
177 /// When creating `FileOrStdin` from `&str`, providing a `"-"` is interpreted
178 /// as `None`, i.e. read from stdin. Providing other strings is interpreted as
179 /// `Some(PathBuf)`, i.e. read from file.
180 /// Use this if a CLI should allow input from a file and if unset from stdin.
181 ///
182 /// ## Examples
183 /// ```
184 /// use clap::Args;
185 ///
186 /// #[derive(Debug, Args)]
187 /// #[clap(name = "example", about = "an example")]
188 /// pub struct Example {
189 /// #[clap(
190 /// default_value_t = FileOrStdin::default(),
191 /// help = FileOrStdin::HELP_OPTIONAL,
192 /// value_name = FileOrStdin::VALUE_NAME,
193 /// )]
194 /// pub input: FileOrStdin,
195 /// }
196 /// ```
197 #[derive(Clone, Debug, Eq, PartialEq)]
198 pub struct FileOrStdin(Option<PathBuf>);
199
200 impl ClapData for FileOrStdin {
201 const VALUE_NAME: &'static str = "FILE";
202 const HELP_OPTIONAL: &'static str =
203 "Read from FILE or stdin if FILE is '-'";
204 const HELP_REQUIRED: &'static str =
205 "Read from FILE or stdin if omitted";
206 }
207
208 impl FileOrStdin {
209 pub fn new(path: Option<PathBuf>) -> Self {
210 FileOrStdin(path)
211 }
212
213 /// Return a reference to the inner type
214 pub fn inner(&self) -> Option<&PathBuf> {
215 self.0.as_ref()
216 }
217
218 /// Returns `None` if `self.0` is `None`, otherwise calls f with the wrapped
219 /// value and returns the result
220 pub fn and_then<U, F>(self, f: F) -> Option<U>
221 where
222 F: FnOnce(PathBuf) -> Option<U>,
223 {
224 self.0.and_then(|x| f(x))
225 }
226
227 /// Get a boxed BufferedReader for the FileOrStdin
228 ///
229 /// Opens a file if there is Some(PathBuf), else opens stdin.
230 ///
231 /// `thing` is the thing that we expect to read, e.g., "OpenPGP
232 /// certificates" or "a signed message".
233 pub fn open<'a>(&self, thing: &'static str)
234 -> Result<Box<dyn BufferedReader<Cookie> + 'a>>
235 {
236 if let Some(path) = self.inner() {
237 Ok(Box::new(
238 File::with_cookie(path, Default::default())
239 .with_context(|| format!("Failed to open {}", self))?))
240 } else {
241 Ok(Box::new(
242 Generic::with_cookie(
243 StdinWarning::new(thing), None, Default::default())))
244 }
245 }
246
247 /// Return a reference to the optional PathBuf.
248 pub fn path(&self) -> Option<&PathBuf> {
249 self.0.as_ref()
250 }
251 }
252
253 impl Default for FileOrStdin {
254 fn default() -> Self {
255 FileOrStdin(None)
256 }
257 }
258
259 impl From<PathBuf> for FileOrStdin {
260 fn from(value: PathBuf) -> Self {
261 if value == PathBuf::from("-") {
262 FileOrStdin::default()
263 } else {
264 FileOrStdin::new(Some(value))
265 }
266 }
267 }
268
269 impl From<Option<PathBuf>> for FileOrStdin {
270 fn from(value: Option<PathBuf>) -> Self {
271 if let Some(path) = value {
272 FileOrStdin::from(path)
273 } else {
274 FileOrStdin::default()
275 }
276 }
277 }
278
279 impl From<&Path> for FileOrStdin {
280 fn from(value: &Path) -> Self {
281 if Path::new("-") == value {
282 FileOrStdin::default()
283 } else {
284 FileOrStdin::from(value.to_owned())
285 }
286 }
287 }
288
289 impl From<Option<&Path>> for FileOrStdin {
290 fn from(value: Option<&Path>) -> Self {
291 if let Some(path) = value {
292 FileOrStdin::from(path)
293 } else {
294 FileOrStdin::default()
295 }
296 }
297 }
298
299 impl FromStr for FileOrStdin {
300 type Err = anyhow::Error;
301
302 fn from_str(s: &str) -> Result<Self> {
303 if "-" == s {
304 Ok(FileOrStdin(None))
305 } else {
306 Ok(FileOrStdin(Some(PathBuf::from(s))))
307 }
308 }
309 }
310
311 impl Display for FileOrStdin {
312 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
313 match &self.0 {
314 None => write!(f, "-"),
315 Some(path) => write!(f, "{}", path.display()),
316 }
317 }
318 }
319
320 /// A type providing const strings for output to certstore by default
321 ///
322 /// This struct is empty and solely used to provide strings to clap.
323 /// Use this in combination with a [`FileOrStdout`] if a CLI should allow output
324 /// to a file and if unset output to a cert store.
325 ///
326 /// ## Examples
327 /// ```
328 /// use clap::Args;
329 ///
330 /// #[derive(Debug, Args)]
331 /// #[clap(name = "example", about = "an example")]
332 /// pub struct Example {
333 /// #[clap(
334 /// help = FileOrCertStore::HELP_OPTIONAL,
335 /// long,
336 /// value_name = FileOrCertStore::VALUE_NAME,
337 /// )]
338 /// pub output: Option<FileOrStdout>,
339 /// }
340 /// ```
341 #[derive(Clone, Debug, Eq, PartialEq)]
342 pub struct FileOrCertStore{}
343
344 impl ClapData for FileOrCertStore {
345 const VALUE_NAME: &'static str = "FILE";
346 const HELP_REQUIRED: &'static str
347 = "Write to FILE (or stdout if FILE is '-') instead of \
348 importing into the certificate store";
349 const HELP_OPTIONAL: &'static str
350 = "Write to FILE (or stdout when omitted) instead of \
351 importing into the certificate store";
352 }
353
354 /// Designates a certificate by path, by stdin, or by key handle.
355 ///
356 /// Use [`Sq::lookup_one`] to read the certificate.
357 #[derive(Clone, Debug)]
358 pub enum FileStdinOrKeyHandle {
359 FileOrStdin(FileOrStdin),
360 KeyHandle(KeyHandle),
361 }
362
363 impl From<FileOrStdin> for FileStdinOrKeyHandle {
364 fn from(file: FileOrStdin) -> Self {
365 FileStdinOrKeyHandle::FileOrStdin(file)
366 }
367 }
368
369 impl From<&str> for FileStdinOrKeyHandle {
370 fn from(path: &str) -> Self {
371 PathBuf::from(path).into()
372 }
373 }
374
375 impl From<&Path> for FileStdinOrKeyHandle {
376 fn from(path: &Path) -> Self {
377 path.to_path_buf().into()
378 }
379 }
380
381 impl From<PathBuf> for FileStdinOrKeyHandle {
382 fn from(path: PathBuf) -> Self {
383 FileStdinOrKeyHandle::FileOrStdin(path.into())
384 }
385 }
386
387 impl From<&KeyHandle> for FileStdinOrKeyHandle {
388 fn from(kh: &KeyHandle) -> Self {
389 FileStdinOrKeyHandle::KeyHandle(kh.clone())
390 }
391 }
392
393 impl From<KeyHandle> for FileStdinOrKeyHandle {
394 fn from(kh: KeyHandle) -> Self {
395 FileStdinOrKeyHandle::KeyHandle(kh)
396 }
397 }
398
399 impl FileStdinOrKeyHandle {
400 /// Returns whether this contains a `FileOrStdin`.
401 pub fn is_file(&self) -> bool {
402 match self {
403 FileStdinOrKeyHandle::FileOrStdin(_) => true,
404 FileStdinOrKeyHandle::KeyHandle(_) => false,
405 }
406 }
407
408 /// Returns whether this contains a `KeyHandle`.
409 pub fn is_key_handle(&self) -> bool {
410 match self {
411 FileStdinOrKeyHandle::FileOrStdin(_) => false,
412 FileStdinOrKeyHandle::KeyHandle(_) => true,
413 }
414 }
415 }
416
417 /// A type wrapping an optional PathBuf to use as stdout or file output
418 ///
419 /// When creating `FileOrStdout` from `&str`, providing a `"-"` is interpreted
420 /// as `None`, i.e. output to stdout. Providing other strings is interpreted as
421 /// `Some(PathBuf)`, i.e. output to file.
422 /// Use this if a CLI should allow output to a file and if unset output to
423 /// stdout.
424 ///
425 /// ## Examples
426 /// ```
427 /// use clap::Args;
428 ///
429 /// #[derive(Debug, Args)]
430 /// #[clap(name = "example", about = "an example")]
431 /// pub struct Example {
432 /// #[clap(
433 /// default_value_t = FileOrStdout::default(),
434 /// help = FileOrStdout::HELP_OPTIONAL,
435 /// long,
436 /// value_name = FileOrStdout::VALUE_NAME,
437 /// )]
438 /// pub output: FileOrStdout,
439 /// }
440 /// ```
441 #[derive(Clone, Debug, Eq, PartialEq)]
442 pub struct FileOrStdout {
443 path: Option<PathBuf>,
444
445 /// If set, secret keys may be written to this sink.
446 for_secrets: bool,
447 }
448
449 impl ClapData for FileOrStdout {
450 const VALUE_NAME: &'static str = "FILE";
451 const HELP_REQUIRED: &'static str =
452 "Write to FILE or stdout if FILE is '-'";
453 const HELP_OPTIONAL: &'static str =
454 "Write to FILE or stdout if omitted";
455 }
456
457 impl FileOrStdout {
458 pub fn new(path: Option<PathBuf>) -> Self {
459 FileOrStdout {
460 path,
461 ..Default::default()
462 }
463 }
464
465 /// Indicates that we will emit secrets.
466 ///
467 /// Use this to mark outputs where we intend to emit secret keys.
468 pub fn for_secrets(mut self) -> Self {
469 self.for_secrets = true;
470 self
471 }
472
473 /// Queries whether we are configured to emit secrets.
474 pub fn is_for_secrets(&self) -> bool {
475 self.for_secrets
476 }
477
478 /// Return a reference to the optional PathBuf
479 pub fn path(&self) -> Option<&PathBuf> {
480 self.path.as_ref()
481 }
482
483 }
484
485 impl Default for FileOrStdout {
486 fn default() -> Self {
487 FileOrStdout {
488 path: None,
489 for_secrets: false,
490 }
491 }
492 }
493
494 impl From<PathBuf> for FileOrStdout {
495 fn from(value: PathBuf) -> Self {
496 if value == PathBuf::from("-") {
497 FileOrStdout::default()
498 } else {
499 FileOrStdout::new(Some(value))
500 }
501 }
502 }
503
504 impl From<Option<PathBuf>> for FileOrStdout {
505 fn from(value: Option<PathBuf>) -> Self {
506 if let Some(path) = value {
507 FileOrStdout::from(path)
508 } else {
509 FileOrStdout::default()
510 }
511 }
512 }
513
514 impl FromStr for FileOrStdout {
515 type Err = anyhow::Error;
516
517 fn from_str(s: &str) -> Result<Self> {
518 if "-" == s {
519 Ok(FileOrStdout::default())
520 } else {
521 Ok(FileOrStdout::new(Some(PathBuf::from(s))))
522 }
523 }
524 }
525
526 impl Display for FileOrStdout {
527 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
528 match &self.path {
529 Some(path) => write!(f, "{}", path.display()),
530 None => write!(f, "-"),
531 }
532 }
533 }
534
535 #[derive(ValueEnum, Debug, Clone)]
536 pub enum ArmorKind {
537 Auto,
538 Message,
539 #[clap(name = "cert")]
540 PublicKey,
541 #[clap(name = "key")]
542 SecretKey,
543 #[clap(name = "sig")]
544 Signature,
545 File,
546 }
547
548 impl From<ArmorKind> for Option<openpgp::armor::Kind> {
549 fn from(c: ArmorKind) -> Self {
550 match c {
551 ArmorKind::Auto => None,
552 ArmorKind::Message => Some(openpgp::armor::Kind::Message),
553 ArmorKind::PublicKey => Some(openpgp::armor::Kind::PublicKey),
554 ArmorKind::SecretKey => Some(openpgp::armor::Kind::SecretKey),
555 ArmorKind::Signature => Some(openpgp::armor::Kind::Signature),
556 ArmorKind::File => Some(openpgp::armor::Kind::File),
557 }
558 }
559 }
560
561 /// Describes the purpose of the encryption.
562 #[derive(ValueEnum, Clone, Debug)]
563 pub enum EncryptPurpose {
564 /// Selects subkeys marked as suitable for transport encryption.
565 Transport,
566
567 /// Selects those for encrypting data at rest.
568 Storage,
569
570 /// Selects all encryption-capable subkeys.
571 Universal,
572 }
573
574 impl From<EncryptPurpose> for KeyFlags {
575 fn from(p: EncryptPurpose) -> Self {
576 match p {
577 EncryptPurpose::Storage => {
578 KeyFlags::empty().set_storage_encryption()
579 }
580 EncryptPurpose::Transport => {
581 KeyFlags::empty().set_transport_encryption()
582 }
583 EncryptPurpose::Universal => KeyFlags::empty()
584 .set_storage_encryption()
585 .set_transport_encryption(),
586 }
587 }
588 }
589
590 /// Describes the purpose of the encryption.
591 #[derive(Copy, Clone, Debug)]
592 pub enum TrustAmount<T> {
593 /// No trust.
594 None,
595
596 /// Partial trust.
597 Partial,
598
599 /// Full trust.
600 Full,
601
602 /// Double trust.
603 Double,
604
605 /// Other trust amount.
606 Other(T),
607 }
608
609 impl<T: Copy + From<u8>> TrustAmount<T> {
610 /// Returns the trust amount as numeric value.
611 pub fn amount(&self) -> T {
612 match self {
613 TrustAmount::None => 0.into(),
614 // See section 5.2.3.13. Trust Signature of RFC4880 for
615 // the values of partial and full trust.
616 TrustAmount::Partial => 60.into(),
617 TrustAmount::Full => 120.into(),
618 TrustAmount::Double => 240.into(),
619 TrustAmount::Other(a) => *a,
620 }
621 }
622 }
623
624 impl<T: Display + FromStr> FromStr for TrustAmount<T>
625 where
626 <T as FromStr>::Err: std::error::Error + Send + Sync + 'static,
627 {
628 type Err = anyhow::Error;
629
630 fn from_str(s: &str) -> Result<TrustAmount<T>> {
631 if s.eq_ignore_ascii_case("none") {
632 Ok(TrustAmount::None)
633 } else if s.eq_ignore_ascii_case("partial") {
634 Ok(TrustAmount::Partial)
635 } else if s.eq_ignore_ascii_case("full") {
636 Ok(TrustAmount::Full)
637 } else if s.eq_ignore_ascii_case("double") {
638 Ok(TrustAmount::Double)
639 } else {
640 Ok(TrustAmount::Other(s.parse()?))
641 }
642 }
643 }
644
645 impl<T: Display + FromStr> Display for TrustAmount<T> {
646 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
647 match self {
648 TrustAmount::None => f.write_str("none"),
649 TrustAmount::Partial => f.write_str("partial"),
650 TrustAmount::Full => f.write_str("full"),
651 TrustAmount::Double => f.write_str("double"),
652 TrustAmount::Other(a) => write!(f, "{}", a),
653 }
654 }
655 }
656
657 /// Holds a session key as parsed from the command line, with an optional
658 /// algorithm specifier.
659 ///
660 /// This struct does not implement [`Display`] to prevent accidental leaking
661 /// of key material. If you are sure you want to print a session key, use
662 /// [`display_sensitive`].
663 ///
664 /// [`Display`]: std::fmt::Display
665 /// [`display_sensitive`]: SessionKey::display_sensitive
666 #[derive(Debug, Clone)]
667 pub struct SessionKey {
668 pub session_key: openpgp::crypto::SessionKey,
669 pub symmetric_algo: Option<SymmetricAlgorithm>,
670 }
671
672 impl std::str::FromStr for SessionKey {
673 type Err = anyhow::Error;
674
675 /// Parse a session key. The format is: an optional prefix specifying the
676 /// symmetric algorithm as a number, followed by a colon, followed by the
677 /// session key in hexadecimal representation.
678 fn from_str(sk: &str) -> anyhow::Result<Self> {
679 let result = if let Some((algo, sk)) = sk.split_once(':') {
680 let algo = SymmetricAlgorithm::from(algo.parse::<u8>()?);
681 let dsk = hex::decode_pretty(sk)?.into();
682 SessionKey {
683 session_key: dsk,
684 symmetric_algo: Some(algo),
685 }
686 } else {
687 let dsk = hex::decode_pretty(sk)?.into();
688 SessionKey {
689 session_key: dsk,
690 symmetric_algo: None,
691 }
692 };
693 Ok(result)
694 }
695 }
696
697 impl SessionKey {
698 /// Returns an object that implements Display for explicitly opting into
699 /// printing a `SessionKey`.
700 pub fn display_sensitive(&self) -> SessionKeyDisplay {
701 SessionKeyDisplay { csk: self }
702 }
703 }
704
705 /// Helper struct for intentionally printing session keys with format! and {}.
706 ///
707 /// This struct implements the `Display` trait to print the session key. This
708 /// construct requires the user to explicitly call
709 /// [`SessionKey::display_sensitive`]. By requiring the user to opt-in, this
710 /// will hopefully reduce that the chance that the session key is inadvertently
711 /// leaked, e.g., in a log that may be publicly posted.
712 pub struct SessionKeyDisplay<'a> {
713 csk: &'a SessionKey,
714 }
715
716 /// Print the session key without prefix in hexadecimal representation.
717 impl<'a> std::fmt::Display for SessionKeyDisplay<'a> {
718 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
719 let sk = self.csk;
720 write!(f, "{}", hex::encode(&sk.session_key))
721 }
722 }