1use std::borrow::Cow;
2use std::path::Path;
3use std::path::PathBuf;
4use std::sync::Arc;
5use std::sync::Mutex;
6use std::sync::atomic::AtomicBool;
7
8use anyhow::Context as _;
9
10use cryptoki::context::Pkcs11;
11use cryptoki::object::Attribute;
12use cryptoki::object::AttributeType;
13use cryptoki::object::ObjectClass;
14use cryptoki::object::ObjectHandle;
15use cryptoki::session::Session;
16use cryptoki::session::UserType;
17use cryptoki::slot::Slot;
18use cryptoki::slot::TokenInfo;
19use cryptoki::types::AuthPin;
20
21use sequoia_openpgp as openpgp;
22use openpgp::Fingerprint;
23use openpgp::packet::key::PublicParts;
24use openpgp::packet::key::UnspecifiedRole;
25use openpgp::packet;
26
27use crate::Context;
28use crate::Result;
29use crate::KeySelector;
30use crate::TokenSelector;
31
32const TRACE: bool = false;
33
34#[derive(Clone, Debug)]
41pub struct Backend {
42 lib: PathBuf,
43 pub(crate) lib_str: String,
45 context: Arc<Pkcs11>,
46}
47
48impl Backend {
49 pub fn context(&self) -> &Pkcs11 {
51 &self.context
52 }
53
54 pub fn lib(&self) -> &Path {
56 &self.lib
57 }
58
59 pub fn lib_short(&self) -> &str {
69 let lib = &self.lib_str[..];
70
71 if let Some(i) = lib.rfind('/') {
72 if i < lib.len() - 1 {
74 let file_name = &lib[i + 1 ..];
75
76 if let Some(dot) = file_name.find('.') {
78 let prefix = &file_name[..dot];
79 if let Some(inner) = prefix.strip_prefix("lib") {
81 return inner;
82 } else {
83 return prefix;
84 }
85 }
86 return file_name;
87 }
88 }
89
90 &lib[..]
91 }
92
93 pub fn is_lib(&self, query: &str) -> bool {
103 tracer!(false, "is_lib");
104 t!("Checking if {} matches {}", query, self.lib.display());
105
106 if query.as_bytes() == self.lib.as_os_str().as_encoded_bytes() {
107 t!("Exact match");
109 return true;
110 } else if query.contains(&['/', '\\']) {
111 t!("Not an exact match, and name contains a path separator. Giving up.");
114 return false;
115 };
116
117 let path = PathBuf::from(&self.lib);
118 if let Some(file_name) = path.file_name() {
119 t!("Considering {}",
120 String::from_utf8_lossy(file_name.as_encoded_bytes()));
121 if file_name == query {
122 t!("Match");
124 return true;
125 }
126
127 let query = query.as_bytes();
128 let file_name = file_name.as_encoded_bytes();
129
130 let mut first = true;
131 for (i, c) in file_name.iter().enumerate() {
132 if *c == b'.' {
133 let prefix = &file_name[..i];
134
135 t!("Considering {}",
136 String::from_utf8_lossy(prefix));
137
138 if prefix == query {
139 t!("Match");
140 return true;
141 }
142
143 if first {
144 if prefix.starts_with(b"lib") {
145 let middle = &prefix[3..];
146
147 t!("Considering {}",
148 String::from_utf8_lossy(middle));
149 if middle == query {
150 t!("Match");
151 return true;
152 }
153 }
154 }
155 first = false;
156 }
157 }
158 }
159
160 t!("Not a match");
161 false
162 }
163}
164
165#[derive(Clone, Debug)]
174pub struct Token {
175 backend: Backend,
176 slot: Slot,
177 info: TokenInfo,
178}
179
180impl Token {
181 pub fn backend(&self) -> &Backend {
183 &self.backend
184 }
185
186 pub fn slot(&self) -> &Slot {
188 &self.slot
189 }
190
191 pub fn info(&self) -> &TokenInfo {
197 &self.info
198 }
199
200 pub fn open_ro_session(&self)
210 -> Result<cryptoki::session::Session>
211 {
212 let session = self.backend().context.clone()
213 .open_ro_session(self.slot().clone())?;
214 Ok(session)
215 }
216
217 pub fn open_ro_user_session<P>(&self, pin: P)
222 -> Result<cryptoki::session::Session>
223 where
224 P: Into<AuthPin>
225 {
226 let session = self.open_ro_session()?;
227 session.login(UserType::User, Some(&pin.into()))?;
228 Ok(session)
229 }
230
231 pub fn open_rw_session(&self)
241 -> Result<cryptoki::session::Session>
242 {
243 let session = self.backend().context.clone()
244 .open_rw_session(self.slot().clone())?;
245 Ok(session)
246 }
247
248 pub fn open_rw_user_session<P>(&self, pin: P)
253 -> Result<cryptoki::session::Session>
254 where
255 P: Into<AuthPin>
256 {
257 let session = self.backend().context.clone()
258 .open_rw_session(self.slot().clone())?;
259 session.login(UserType::User, Some(&pin.into()))?;
260 Ok(session)
261 }
262}
263
264impl std::fmt::Display for Token {
265 fn fmt(&self, f: &mut std::fmt::Formatter<'_>)
266 -> std::result::Result<(), std::fmt::Error>
267 {
268 let mut label = self.info().label();
269 if label.is_empty() {
270 label = "<no label>";
271 }
272 let manufacturer_id = self.info().manufacturer_id();
273 let model = self.info().model();
274 let serial_number = self.info().serial_number();
275
276 let product = match (manufacturer_id.is_empty(), model.is_empty()) {
277 (true, true) => Cow::Borrowed("Unknown product"),
278 (true, false) => manufacturer_id.into(),
279 (false, true) => model.into(),
280 (false, false) => {
281 if model.contains(manufacturer_id) {
282 model.into()
283 } else {
284 format!("{} {}", manufacturer_id, model).into()
285 }
286 }
287 };
288
289 let mut id = if serial_number.is_empty() {
290 format!("{} ({})", label, product)
291 } else {
292 format!("{} ({}, serial number: {})", label, product, serial_number)
293 };
294
295 if id.chars().any(|c| c.is_control()) {
296 id = format!("{:?}", id);
298 } else {
299 id = id.replace("\n", "-");
301 id = id.replace("\r", "-");
302 }
303
304 write!(f, "{}", id)
305 }
306}
307
308#[derive(Debug)]
365pub struct Key {
366 token: Token,
367
368 composite_key: Option<Box<Key>>,
373
374 object_class: Option<ObjectClass>,
376 key_unique_id: Option<Vec<u8>>,
377 key_label: Option<Vec<u8>>,
378 key_id: Option<Vec<u8>>,
379 key_url: Option<Vec<u8>>,
380 pub(crate) openpgp_key: Mutex<Option<packet::Key<PublicParts, UnspecifiedRole>>>,
381
382 pub(crate) got_capabilities: AtomicBool,
383 pub(crate) signing_capable: AtomicBool,
384 pub(crate) decryption_capable: AtomicBool,
385}
386
387impl Clone for Key {
388 fn clone(&self) -> Self {
389 Self {
390 token: self.token.clone(),
391 composite_key: self.composite_key.clone(),
392 object_class: self.object_class.clone(),
393 key_unique_id: self.key_unique_id.clone(),
394 key_label: self.key_label.clone(),
395 key_id: self.key_id.clone(),
396 key_url: self.key_url.clone(),
397 openpgp_key: Mutex::new(
398 self.openpgp_key.lock().unwrap().as_ref().map(|k| k.clone())),
399
400 got_capabilities: false.into(),
401 signing_capable: false.into(),
402 decryption_capable: false.into(),
403 }
404 }
405}
406
407impl Key {
408 pub(crate) fn composite_key(&self) -> Option<&Key> {
413 self.composite_key.as_deref()
414 }
415
416 pub(crate) fn combine_with(&mut self, key: Key) {
418 assert!(self.composite_key.is_none());
419 assert!(key.composite_key.is_none());
420 self.composite_key = Some(Box::new(key));
421 }
422
423 pub fn backend(&self) -> &Backend {
425 self.token.backend()
426 }
427
428 pub fn token(&self) -> &Token {
430 &self.token
431 }
432
433 pub fn slot(&self) -> &Slot {
435 self.token.slot()
436 }
437
438 pub fn info(&self) -> &TokenInfo {
444 self.token.info()
445 }
446
447 pub fn object_class(&self) -> Option<ObjectClass> {
453 self.object_class.clone()
454 }
455
456 pub fn key_unique_id(&self) -> Option<&[u8]> {
458 self.key_unique_id.as_deref()
459 }
460
461 pub fn key_unique_id_hex(&self) -> Option<String> {
463 self.key_unique_id()
464 .map(|id| {
465 id.iter()
466 .map(|x| format!("{:02x}", x))
467 .collect::<Vec<String>>()
468 .join("")
469 })
470 }
471
472 pub fn key_label(&self) -> Option<&[u8]> {
474 self.key_label.as_deref()
475 }
476
477 pub fn key_id(&self) -> Option<&[u8]> {
479 self.key_id.as_deref()
480 }
481
482 pub fn key_url(&self) -> Option<&[u8]> {
484 self.key_url.as_deref()
485 }
486
487 pub fn open_ro_session(&self)
490 -> Result<(Session, ObjectHandle)>
491 {
492 let session
493 = self.backend().context().open_ro_session(self.slot().clone())?;
494
495 let mut attrs = Vec::with_capacity(5);
496 if let Some(object_class) = self.object_class {
497 attrs.push(Attribute::Class(object_class));
498 }
499 if let Some(unique_id) = self.key_unique_id() {
500 attrs.push(Attribute::UniqueId(unique_id.to_vec()));
501 }
502 if let Some(label) = self.key_label() {
503 attrs.push(Attribute::Label(label.to_vec()));
504 }
505 if let Some(id) = self.key_id() {
506 attrs.push(Attribute::Id(id.to_vec()));
507 }
508 if let Some(url) = self.key_url() {
509 attrs.push(Attribute::Url(url.to_vec()));
510 }
511
512 let mut objects = session.iter_objects(&attrs)
513 .with_context(|| {
514 format!("Listing {}'s objects",
515 self.backend().lib().display())
516 })?;
517
518 let first = objects.next();
519 let second = objects.next();
520 let object = match (first, second) {
521 (Some(object), None) => object.context("Getting private key")?,
522 (Some(_), Some(_)) => {
523 return Err(anyhow::anyhow!(
524 "Multiple keys correspond to the key descriptor, \
525 cowardly refusing to continue."));
526 }
527 (None, _) => {
528 return Err(anyhow::anyhow!("Key object disappeared"));
529 }
530 };
531 drop(objects);
532
533 Ok((session, object))
534 }
535
536 pub fn from_object(token: Token, session: &Session, object: ObjectHandle)
542 -> Result<Self>
543 {
544 let mut object_class = None;
546 let mut key_unique_id = None;
547 let mut key_label = None;
548 let mut key_id = None;
549 let mut key_url = None;
550
551 let attributes = session.get_attributes(
554 object,
555 &[
556 AttributeType::Class,
557 AttributeType::UniqueId,
558 AttributeType::Label,
559 AttributeType::Id,
560 AttributeType::Url,
561 ])?;
562 for attribute in attributes {
563 if let Attribute::Class(value) = attribute {
564 object_class = Some(value);
565 } else if let Attribute::UniqueId(value) = attribute {
566 key_unique_id = Some(value);
567 } else if let Attribute::Label(value) = attribute {
568 key_label = Some(value);
569 } else if let Attribute::Id(value) = attribute {
570 key_id = Some(value);
571 } else if let Attribute::Url(value) = attribute {
572 key_url = Some(value);
573 } else {
574 unreachable!("get_attributes only returns \
575 requested attributes");
576 }
577 }
578
579 Ok(Self {
580 token,
581 composite_key: None,
582 object_class,
583 key_unique_id,
584 key_label,
585 key_id,
586 key_url,
587 openpgp_key: Mutex::new(None),
588
589 got_capabilities: false.into(),
590 signing_capable: false.into(),
591 decryption_capable: false.into(),
592 })
593 }
594
595 pub fn fingerprint(&self) -> Option<Fingerprint> {
599 self.to_openpgp_key().ok().map(|key| key.fingerprint())
600 }
601}
602
603#[derive(Debug)]
606enum KeyOrToken {
607 Key(Key),
608 Token(Token),
609}
610
611impl KeyOrToken {
612 fn is_key(&self) -> bool {
613 self.key().is_some()
614 }
615
616 fn key(&self) -> Option<&Key> {
617 match self {
618 KeyOrToken::Key(key) => Some(key),
619 KeyOrToken::Token(_) => None,
620 }
621 }
622
623 fn key_unwrap(&self) -> &Key {
624 self.key().expect(
625 "Internal error: looked up a key, got a token")
626 }
627
628 fn key_mut(&mut self) -> Option<&mut Key> {
629 match self {
630 KeyOrToken::Key(key) => Some(key),
631 KeyOrToken::Token(_) => None,
632 }
633 }
634
635 fn key_mut_unwrap(&mut self) -> &mut Key {
636 self.key_mut().expect(
637 "Internal error: looked up a key, got a token")
638 }
639
640 fn into_key_unwrap(self) -> Key {
641 match self {
642 KeyOrToken::Key(key) => key,
643 KeyOrToken::Token(_) =>
644 panic!("Internal error: looked up a token, got a key"),
645 }
646 }
647
648 fn into_token_unwrap(self) -> Token {
649 match self {
650 KeyOrToken::Key(_) =>
651 panic!("Internal error: looked up a token, got a key"),
652 KeyOrToken::Token(token) => token,
653 }
654 }
655
656}
657
658#[derive(Debug, Clone, Eq, PartialEq)]
662enum AllowedMatches {
663 None,
664 One,
665 Any,
666}
667
668#[derive(Debug, Clone, Eq, PartialEq)]
673pub enum SelectorScope {
674 All,
675 PublicKeys,
676 PrivateKeys,
677}
678
679impl Context {
680 pub fn backends(&self) -> Result<&[Backend]> {
686 tracer!(TRACE, "Context::backends");
687
688 if let Some(backends) = self.backends.get() {
689 return Ok(backends);
690 }
691
692 let modules = self.config.modules();
693 let mut backends = Vec::with_capacity(modules.len());
694 let mut load_err = None;
695 let mut init_err = None;
696 for lib in modules {
697 t!("Loading {}", lib.display());
698
699 let context = match Pkcs11::new(lib) {
700 Ok(context) => context,
701 Err(err) => {
702 log::debug!("{}: Error loading {}: {}",
703 func!(), lib.display(), err);
704 if load_err.is_none() {
705 load_err = Some(err);
706 }
707 continue;
708 }
709 };
710
711 match context.initialize(
712 cryptoki::context::CInitializeArgs::new(
713 cryptoki::context::CInitializeFlags::OS_LOCKING_OK))
714 {
715 Ok(context) => context,
716 Err(err) => {
717 log::debug!("{}: Error initializing {}: {}",
718 func!(), lib.display(), err);
719 if init_err.is_none() {
720 init_err = Some(err);
721 }
722 continue;
723 }
724 };
725 t!("Loaded {}", lib.display());
726
727 backends.push(Backend {
728 lib: lib.clone(),
729 lib_str: lib.display().to_string(),
730 context: Arc::new(context),
731 });
732 }
733
734 if let Some(err) = init_err {
735 return Err(err.into());
736 }
737 if let Some(err) = load_err {
738 return Err(err.into());
739 }
740
741 let _ = self.backends.set(backends);
742 let backends = self.backends.get().expect("just set");
743 Ok(backends)
744 }
745
746 fn select_internal(&self, selector: &KeySelector, key: bool,
755 allowed_matches: AllowedMatches,
756 scope: SelectorScope,
757 get_constituent: bool)
758 -> Result<Vec<KeyOrToken>>
759 {
760 tracer!(TRACE, "Context::select_internal");
761
762 let mut all: Vec<KeyOrToken> = Vec::new();
765 let mut matches: Vec<KeyOrToken> = Vec::new();
766
767 let mut backend_matched = false;
770 let mut backend_names = Vec::new();
771
772 for backend in self.backends()? {
773 backend_names.push(backend.lib_short());
774 if ! selector.backend_matches(&backend) {
775 continue;
776 } else {
777 backend_matched = true;
778 }
779
780 let slots = match backend.context().get_all_slots() {
781 Ok(slots) => slots,
782 Err(err) => {
783 log::debug!("{}: Failed to enumerate slots for {}: {}",
784 func!(), backend.lib().display(), err);
785 continue;
786 }
787 };
788 t!("{} has {} slots", backend.lib().display(), slots.len());
789 'slot_loop: for slot in slots.into_iter() {
790 let info = match backend.context().get_token_info(slot.clone()) {
791 Ok(info) => info,
792 Err(err) => {
793 t!("Failed to get token info for slot {}: {}",
794 slot.id(), err);
795 continue 'slot_loop;
796 }
797 };
798
799 let matches_token =
800 selector.slot_matches(slot.id())
801 && selector.token_label_matches(info.label())
802 && selector.token_serial_number_matches(
803 info.serial_number());
804
805 if ! key {
806 let token = Token {
808 backend: backend.clone(),
809 slot: slot,
810 info: info.clone(),
811 };
812
813 if matches_token {
814 matches.push(KeyOrToken::Token(token));
815 } else {
816 all.push(KeyOrToken::Token(token));
817 }
818 } else {
819 let session = match backend.context().open_ro_session(slot) {
821 Ok(session) => session,
822 Err(err) => {
823 log::debug!(
824 "{}: Warning: {}'s slot {} is unusable: {}",
825 func!(),
826 backend.lib().display(), slot.id(),
827 err);
828 continue 'slot_loop;
829 }
830 };
831
832 let attrs = match scope {
834 SelectorScope::All => &[][..],
835 SelectorScope::PublicKeys => {
836 &[ Attribute::Class(ObjectClass::PUBLIC_KEY) ]
837 }
838 SelectorScope::PrivateKeys => {
839 &[ Attribute::Class(ObjectClass::PRIVATE_KEY) ]
840 }
841 };
842 let objects = match session.iter_objects(attrs) {
843 Ok(objects) => objects,
844 Err(err) => {
845 log::debug!(
846 "{}: Error listing {}'s objects: {}",
847 func!(),
848 backend.lib().display(),
849 err);
850 continue 'slot_loop;
851 }
852 };
853
854 'obj_loop: for (i, object) in objects.enumerate() {
855 let object = match object {
856 Ok(object) => object,
857 Err(err) => {
858 log::debug!(
859 "{}: Error reading object #{}: {}",
860 func!(), i + 1, err);
861 continue 'obj_loop;
862 }
863 };
864
865 let token = Token {
867 backend: backend.clone(),
868 slot: slot,
869 info: info.clone(),
870 };
871 let key = match Key::from_object(
872 token, &session, object)
873 {
874 Ok(key) => key,
875 Err(err) => {
876 t!("Reading object #{}'s attributes: {}",
877 i + i, err);
878 continue 'obj_loop;
879 }
880 };
881 let matches_key_unique_id
882 = selector.key_unique_id_matches(key.key_unique_id());
883
884 let matches_key_label = if let Some(l) = selector.key_label() {
885 Some(l.as_bytes()) == key.key_label()
887 } else {
888 true
890 };
891
892 let matches_key_id = selector.key_id_matches(key.key_id());
893 let matches_key_url = selector.key_url_matches(key.key_url());
894
895 if matches_token
896 && matches_key_unique_id && matches_key_label
897 && matches_key_id && matches_key_url
898 {
899 matches.push(KeyOrToken::Key(key));
900 } else {
901 all.push(KeyOrToken::Key(key));
902 }
903 }
904 }
905 }
906 }
907
908 if key && get_constituent {
910 'next_match: for i in 0..matches.len() {
911 if i >= matches.len() {
912 break;
914 }
915
916 let m = &matches[i];
921 let key = m.key_unwrap();
922 let key_id = if let Some(key_id) = key.key_id() {
923 match String::from_utf8(key_id.to_vec()) {
924 Ok(key_id) => key_id,
925 Err(_err) => {
926 continue;
928 }
929 }
930 } else {
931 continue;
932 };
933
934 let map = &[
937 ("pgp:v6t:", "pgp:v6pq:"),
938 ("pgp:v4t:", "pgp:v4pq:"),
939 ];
940
941 let mut other_key_id = None;
942 for (one, other) in map.into_iter().map(|(a, b)| (*a, *b))
943 .chain(map.into_iter().map(|(a, b)| (*b, *a)))
945 {
946 if let Some(suffix) = key_id.strip_prefix(one) {
947 other_key_id = Some(format!("{}{}", other, suffix));
948 break;
949 }
950 }
951
952 let other_key_id = if let Some(other_key_id) = other_key_id {
953 other_key_id
954 } else {
955 continue;
957 };
958
959 if i + 1 < matches.len() {
964 for j in i + 1..matches.len() {
965 let other = matches[j].key_unwrap();
966 if other.key_id() == Some(other_key_id.as_bytes()) {
967 let other = matches.remove(j).into_key_unwrap();
969 matches[i].key_mut_unwrap().combine_with(other);
970 continue 'next_match;
971 }
972 }
973 }
974
975 let other = self.select_internal(
979 &KeySelector::from_key_id(other_key_id),
980 true, AllowedMatches::One,
982 SelectorScope::PublicKeys,
983 false, );
985 match other {
986 Ok(results) => {
987 assert_eq!(results.len(), 1);
988 let other = results.into_iter().next().unwrap();
989 let other = other.into_key_unwrap();
990 matches[i].key_mut_unwrap().combine_with(other);
991 }
992 Err(err) => {
993 log::debug!(
994 "{}: Warning: {} is a composite key, \
995 but half the key is missing: {}",
996 func!(), key_id, err);
997 }
998 }
999 }
1000 }
1001
1002 let obj = if key { "key" } else { "token" };
1003 let objs = if key { "keys" } else { "tokens" };
1004
1005 if allowed_matches == AllowedMatches::None {
1006 if matches.len() == 0 {
1008 Ok(vec![])
1009 } else {
1010 log::debug!("{}: The {} selector {} matches existing {}:",
1011 func!(), obj, selector.args(), objs);
1012 Self::list_matches(matches);
1013
1014 if key {
1015 Err(anyhow::anyhow!(
1016 "The {} selector matches existing {}, choose a \
1017 different label or use --ambiguous-key-label, \
1018 or --random-key-label",
1019 obj, objs))
1020 } else {
1021 Err(anyhow::anyhow!(
1022 "The {} selector matches existing {}", obj, objs))
1023 }
1024 }
1025 } else if allowed_matches == AllowedMatches::One && matches.len() == 0 {
1026 if let (Some(backend), false)
1028 = (selector.backend(), backend_matched)
1029 {
1030 Err(anyhow::anyhow!(
1031 "The specified backend ({}) wasn't loaded (try: {})",
1032 backend, backend_names.join(", ")))
1033 } else {
1034 log::debug!("{}: The {} selector {} does not match any of \
1035 the {}. Known {}:",
1036 func!(), obj, selector.args(), objs, objs);
1037 Self::list_matches(all);
1038
1039 Err(anyhow::anyhow!(
1040 "The specified selector ({}) doesn't match any of the {}",
1041 selector.args(), objs))
1042 }
1043 } else if allowed_matches == AllowedMatches::One && matches.len() > 1 {
1044 log::debug!("{}: The {} selector {} matches multiple {}:",
1046 func!(), obj, selector.args(), objs);
1047 Self::list_matches(matches);
1048
1049 Err(anyhow::anyhow!(
1050 "Multiple {} match {}, try being more specific.",
1051 objs, selector.args()))
1052 } else {
1053 Ok(matches)
1054 }
1055 }
1056
1057 fn list_matches(items: Vec<KeyOrToken>) {
1059 let is_key = items.iter().next()
1060 .map(|o| o.is_key())
1061 .unwrap_or(false);
1062
1063 let list_token = |t: &Token| -> String {
1064 format!("--backend {} --slot {} --token-label {:?} \
1065 --token-serial-number {}",
1066 t.backend().lib_short(), t.slot().id(), t.info().label(),
1067 t.info().serial_number())
1068 };
1069
1070 for obj in items.into_iter() {
1071 match obj {
1072 KeyOrToken::Key(key) => {
1073 assert!(is_key);
1074 let mut bits: Vec<Cow<str>> = Vec::new();
1075 bits.push(list_token(&key.token()).into());
1076 if let Some(key_unique_id) = key.key_unique_id() {
1077 bits.push(Cow::Borrowed("--key-unique-id"));
1078 bits.push(format!(
1079 "{:?}", String::from_utf8_lossy(key_unique_id)).into());
1080 }
1081 if let Some(key_label) = key.key_label() {
1082 bits.push(Cow::Borrowed("--key-label"));
1083 bits.push(format!(
1084 "{:?}", String::from_utf8_lossy(key_label)).into());
1085 }
1086 if let Some(key_id) = key.key_id() {
1087 bits.push(Cow::Borrowed("--key-id"));
1088 bits.push(format!(
1089 "{:?}", String::from_utf8_lossy(key_id)).into());
1090 }
1091 if let Some(key_url) = key.key_url() {
1092 bits.push(Cow::Borrowed("--key-url"));
1093 bits.push(format!(
1094 "{:?}", String::from_utf8_lossy(key_url)).into());
1095 }
1096 eprintln!(" - {}", bits.join(" "));
1097 }
1098 KeyOrToken::Token(token) => {
1099 assert!(! is_key);
1100 eprintln!(" - {}", list_token(&token));
1101 }
1102 }
1103 }
1104 }
1105
1106 pub fn tokens(&self) -> Result<impl Iterator<Item=Token>> {
1108 let matches = self.select_internal(
1109 &KeySelector::unconstrained(), false,
1110 AllowedMatches::Any, SelectorScope::PublicKeys,
1111 false)?;
1113
1114 Ok(matches
1115 .into_iter()
1116 .map(|obj| obj.into_token_unwrap()))
1117 }
1118
1119 pub fn select_one_token(&self, selector: &TokenSelector)
1124 -> Result<Token>
1125 {
1126 let key_selector
1127 = KeySelector::from_token_selector(selector.clone());
1128 let matches = self.select_internal(&key_selector, false,
1129 AllowedMatches::One,
1130 SelectorScope::All,
1131 false)?;
1132
1133 assert_eq!(matches.len(), 1);
1134
1135 let token = matches.into_iter().next().unwrap().into_token_unwrap();
1136
1137 Ok(token)
1138 }
1139
1140 pub fn keys(&self) -> Result<impl Iterator<Item=Key>> {
1142 let matches = self.select_internal(
1143 &KeySelector::unconstrained(), true,
1144 AllowedMatches::Any, SelectorScope::PublicKeys,
1145 true)?;
1147
1148 Ok(matches
1149 .into_iter()
1150 .map(|obj| obj.into_key_unwrap()))
1151 }
1152
1153 pub fn select_one_key(&self, selector: &KeySelector, scope: SelectorScope)
1158 -> Result<Key>
1159 {
1160 let matches = self.select_internal(
1161 &selector, true, AllowedMatches::One, scope,
1162 true)?;
1164
1165 assert_eq!(matches.len(), 1);
1166
1167 let key = matches.into_iter().next().unwrap().into_key_unwrap();
1168
1169 Ok(key)
1170 }
1171
1172 pub fn select_keys(&self, selector: &KeySelector, scope: SelectorScope)
1177 -> Result<Vec<Key>>
1178 {
1179 let matches = self.select_internal(
1180 &selector, true, AllowedMatches::Any, scope,
1181 true)?;
1183
1184 let keys = matches
1185 .into_iter()
1186 .map(|obj| obj.into_key_unwrap())
1187 .collect::<Vec<Key>>();
1188
1189 Ok(keys)
1190 }
1191
1192 pub fn check_no_keys_have_label(&self, label: &str)
1194 -> Result<()>
1195 {
1196 tracer!(TRACE, "config::check_no_keys_have_label");
1197 t!("Checking that the key label {} is unique", label);
1198
1199 let selector = KeySelector::from_key_label(label);
1200 self.select_internal(&selector, true,
1201 AllowedMatches::None,
1202 SelectorScope::All,
1203 false)?;
1205
1206 Ok(())
1207 }
1208
1209 pub fn check_no_keys_have_id(&self, id: &str)
1211 -> Result<()>
1212 {
1213 tracer!(TRACE, "config::check_no_keys_have_id");
1214 t!("Checking that the key ID {} is unique", id);
1215
1216 let selector = KeySelector::from_key_id(id);
1217 self.select_internal(&selector, true,
1218 AllowedMatches::None,
1219 SelectorScope::All,
1220 false)?;
1222
1223 Ok(())
1224 }
1225}