1use std::borrow::Cow;
2use std::collections::BTreeMap;
3use std::path::Path;
4use std::path::PathBuf;
5use std::sync::Arc;
6use std::sync::Mutex;
7use std::sync::Weak;
8use std::sync::atomic::AtomicBool;
9
10use anyhow::Context as _;
11
12use cryptoki::object::Attribute;
13use cryptoki::object::AttributeType;
14use cryptoki::object::ObjectClass;
15use cryptoki::object::ObjectHandle;
16use cryptoki::session::Session;
17use cryptoki::session::UserType;
18use cryptoki::slot::Slot;
19use cryptoki::slot::TokenInfo;
20use cryptoki::types::AuthPin;
21
22use sequoia_openpgp as openpgp;
23use openpgp::Fingerprint;
24use openpgp::packet::key::PublicParts;
25use openpgp::packet::key::UnspecifiedRole;
26use openpgp::packet;
27
28use crate::Context;
29use crate::Result;
30use crate::KeySelector;
31use crate::TokenSelector;
32
33const TRACE: bool = false;
34
35struct Pkcs11 {
36 inner: Option<cryptoki::context::Pkcs11>,
37}
38
39impl std::fmt::Debug for Pkcs11 {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
41 {
42 if let Some(pkcs11) = self.inner.as_ref() {
43 write!(f, "{:?}", pkcs11)
44 } else {
45 write!(f, "<finalized PKCS11 context>")
46 }
47 }
48}
49
50impl Drop for Pkcs11 {
51 fn drop(&mut self) {
52 if let Some(pkcs11) = self.inner.take() {
53 if let Err(err) = pkcs11.finalize() {
54 eprintln!("Finalizing PKCS11 context: {}", err);
55 }
56 }
57 }
58}
59
60impl std::ops::Deref for Pkcs11 {
61 type Target = cryptoki::context::Pkcs11;
62
63 fn deref(&self) -> &Self::Target {
64 self.inner.as_ref().expect("not finalized")
66 }
67}
68
69impl From<cryptoki::context::Pkcs11> for Pkcs11 {
70 fn from(pkcs11: cryptoki::context::Pkcs11) -> Self {
71 Self {
72 inner: Some(pkcs11),
73 }
74 }
75}
76
77#[derive(Clone, Debug)]
84pub struct Backend {
85 lib: PathBuf,
86 pub(crate) lib_str: String,
88 context: Arc<Pkcs11>,
89}
90
91impl Backend {
92 pub fn context(&self) -> &cryptoki::context::Pkcs11 {
94 &self.context
95 }
96
97 pub fn lib(&self) -> &Path {
99 &self.lib
100 }
101
102 pub fn lib_short(&self) -> &str {
112 let lib = &self.lib_str[..];
113
114 if let Some(i) = lib.rfind('/') {
115 if i < lib.len() - 1 {
117 let file_name = &lib[i + 1 ..];
118
119 if let Some(dot) = file_name.find('.') {
121 let prefix = &file_name[..dot];
122 if let Some(inner) = prefix.strip_prefix("lib") {
124 return inner;
125 } else {
126 return prefix;
127 }
128 }
129 return file_name;
130 }
131 }
132
133 &lib[..]
134 }
135
136 pub fn is_lib(&self, query: &str) -> bool {
146 tracer!(false, "is_lib");
147 t!("Checking if {} matches {}", query, self.lib.display());
148
149 if query.as_bytes() == self.lib.as_os_str().as_encoded_bytes() {
150 t!("Exact match");
152 return true;
153 } else if query.contains(&['/', '\\']) {
154 t!("Not an exact match, and name contains a path separator. Giving up.");
157 return false;
158 };
159
160 let path = PathBuf::from(&self.lib);
161 if let Some(file_name) = path.file_name() {
162 t!("Considering {}",
163 String::from_utf8_lossy(file_name.as_encoded_bytes()));
164 if file_name == query {
165 t!("Match");
167 return true;
168 }
169
170 let query = query.as_bytes();
171 let file_name = file_name.as_encoded_bytes();
172
173 let mut first = true;
174 for (i, c) in file_name.iter().enumerate() {
175 if *c == b'.' {
176 let prefix = &file_name[..i];
177
178 t!("Considering {}",
179 String::from_utf8_lossy(prefix));
180
181 if prefix == query {
182 t!("Match");
183 return true;
184 }
185
186 if first {
187 if prefix.starts_with(b"lib") {
188 let middle = &prefix[3..];
189
190 t!("Considering {}",
191 String::from_utf8_lossy(middle));
192 if middle == query {
193 t!("Match");
194 return true;
195 }
196 }
197 }
198 first = false;
199 }
200 }
201 }
202
203 t!("Not a match");
204 false
205 }
206}
207
208#[derive(Clone, Debug)]
217pub struct Token {
218 backend: Backend,
219 slot: Slot,
220 info: TokenInfo,
221}
222
223impl Token {
224 pub fn backend(&self) -> &Backend {
226 &self.backend
227 }
228
229 pub fn slot(&self) -> &Slot {
231 &self.slot
232 }
233
234 pub fn info(&self) -> &TokenInfo {
240 &self.info
241 }
242
243 pub fn open_ro_session(&self)
253 -> Result<cryptoki::session::Session>
254 {
255 let session = self.backend().context.clone()
256 .open_ro_session(self.slot().clone())?;
257 Ok(session)
258 }
259
260 pub fn open_ro_user_session<P>(&self, pin: P)
265 -> Result<cryptoki::session::Session>
266 where
267 P: Into<AuthPin>
268 {
269 let session = self.open_ro_session()?;
270 session.login(UserType::User, Some(&pin.into()))?;
271 Ok(session)
272 }
273
274 pub fn open_rw_session(&self)
284 -> Result<cryptoki::session::Session>
285 {
286 let session = self.backend().context.clone()
287 .open_rw_session(self.slot().clone())?;
288 Ok(session)
289 }
290
291 pub fn open_rw_user_session<P>(&self, pin: P)
296 -> Result<cryptoki::session::Session>
297 where
298 P: Into<AuthPin>
299 {
300 let session = self.backend().context.clone()
301 .open_rw_session(self.slot().clone())?;
302 session.login(UserType::User, Some(&pin.into()))?;
303 Ok(session)
304 }
305}
306
307impl std::fmt::Display for Token {
308 fn fmt(&self, f: &mut std::fmt::Formatter<'_>)
309 -> std::result::Result<(), std::fmt::Error>
310 {
311 let mut label = self.info().label();
312 if label.is_empty() {
313 label = "<no label>";
314 }
315 let manufacturer_id = self.info().manufacturer_id();
316 let model = self.info().model();
317 let serial_number = self.info().serial_number();
318
319 let product = match (manufacturer_id.is_empty(), model.is_empty()) {
320 (true, true) => Cow::Borrowed("Unknown product"),
321 (true, false) => manufacturer_id.into(),
322 (false, true) => model.into(),
323 (false, false) => {
324 if model.contains(manufacturer_id) {
325 model.into()
326 } else {
327 format!("{} {}", manufacturer_id, model).into()
328 }
329 }
330 };
331
332 let mut id = if serial_number.is_empty() {
333 format!("{} ({})", label, product)
334 } else {
335 format!("{} ({}, serial number: {})", label, product, serial_number)
336 };
337
338 if id.chars().any(|c| c.is_control()) {
339 id = format!("{:?}", id);
341 } else {
342 id = id.replace("\n", "-");
344 id = id.replace("\r", "-");
345 }
346
347 write!(f, "{}", id)
348 }
349}
350
351#[derive(Debug)]
408pub struct Key {
409 token: Token,
410
411 composite_key: Option<Box<Key>>,
416
417 object_class: Option<ObjectClass>,
419 key_unique_id: Option<Vec<u8>>,
420 key_label: Option<Vec<u8>>,
421 key_id: Option<Vec<u8>>,
422 key_url: Option<Vec<u8>>,
423 pub(crate) openpgp_key: Mutex<Option<packet::Key<PublicParts, UnspecifiedRole>>>,
424
425 pub(crate) got_capabilities: AtomicBool,
426 pub(crate) signing_capable: AtomicBool,
427 pub(crate) decryption_capable: AtomicBool,
428}
429
430impl Clone for Key {
431 fn clone(&self) -> Self {
432 Self {
433 token: self.token.clone(),
434 composite_key: self.composite_key.clone(),
435 object_class: self.object_class.clone(),
436 key_unique_id: self.key_unique_id.clone(),
437 key_label: self.key_label.clone(),
438 key_id: self.key_id.clone(),
439 key_url: self.key_url.clone(),
440 openpgp_key: Mutex::new(
441 self.openpgp_key.lock().unwrap().as_ref().map(|k| k.clone())),
442
443 got_capabilities: false.into(),
444 signing_capable: false.into(),
445 decryption_capable: false.into(),
446 }
447 }
448}
449
450impl Key {
451 pub(crate) fn composite_key(&self) -> Option<&Key> {
456 self.composite_key.as_deref()
457 }
458
459 pub(crate) fn combine_with(&mut self, key: Key) {
461 assert!(self.composite_key.is_none());
462 assert!(key.composite_key.is_none());
463 self.composite_key = Some(Box::new(key));
464 }
465
466 pub fn backend(&self) -> &Backend {
468 self.token.backend()
469 }
470
471 pub fn token(&self) -> &Token {
473 &self.token
474 }
475
476 pub fn slot(&self) -> &Slot {
478 self.token.slot()
479 }
480
481 pub fn info(&self) -> &TokenInfo {
487 self.token.info()
488 }
489
490 pub fn object_class(&self) -> Option<ObjectClass> {
496 self.object_class.clone()
497 }
498
499 pub fn key_unique_id(&self) -> Option<&[u8]> {
501 self.key_unique_id.as_deref()
502 }
503
504 pub fn key_unique_id_hex(&self) -> Option<String> {
506 self.key_unique_id()
507 .map(|id| {
508 id.iter()
509 .map(|x| format!("{:02x}", x))
510 .collect::<Vec<String>>()
511 .join("")
512 })
513 }
514
515 pub fn key_label(&self) -> Option<&[u8]> {
517 self.key_label.as_deref()
518 }
519
520 pub fn key_id(&self) -> Option<&[u8]> {
522 self.key_id.as_deref()
523 }
524
525 pub fn key_url(&self) -> Option<&[u8]> {
527 self.key_url.as_deref()
528 }
529
530 pub fn open_ro_session(&self)
533 -> Result<(Session, ObjectHandle)>
534 {
535 let session
536 = self.backend().context().open_ro_session(self.slot().clone())?;
537
538 let mut attrs = Vec::with_capacity(5);
539 if let Some(object_class) = self.object_class {
540 attrs.push(Attribute::Class(object_class));
541 }
542 if let Some(unique_id) = self.key_unique_id() {
543 attrs.push(Attribute::UniqueId(unique_id.to_vec()));
544 }
545 if let Some(label) = self.key_label() {
546 attrs.push(Attribute::Label(label.to_vec()));
547 }
548 if let Some(id) = self.key_id() {
549 attrs.push(Attribute::Id(id.to_vec()));
550 }
551 if let Some(url) = self.key_url() {
552 attrs.push(Attribute::Url(url.to_vec()));
553 }
554
555 let mut objects = session.iter_objects(&attrs)
556 .with_context(|| {
557 format!("Listing {}'s objects",
558 self.backend().lib().display())
559 })?;
560
561 let first = objects.next();
562 let second = objects.next();
563 let object = match (first, second) {
564 (Some(object), None) => object.context("Getting private key")?,
565 (Some(_), Some(_)) => {
566 return Err(anyhow::anyhow!(
567 "Multiple keys correspond to the key descriptor, \
568 cowardly refusing to continue."));
569 }
570 (None, _) => {
571 return Err(anyhow::anyhow!("Key object disappeared"));
572 }
573 };
574 drop(objects);
575
576 Ok((session, object))
577 }
578
579 pub fn from_object(token: Token, session: &Session, object: ObjectHandle)
585 -> Result<Self>
586 {
587 let mut object_class = None;
589 let mut key_unique_id = None;
590 let mut key_label = None;
591 let mut key_id = None;
592 let mut key_url = None;
593
594 let attributes = session.get_attributes(
597 object,
598 &[
599 AttributeType::Class,
600 AttributeType::UniqueId,
601 AttributeType::Label,
602 AttributeType::Id,
603 AttributeType::Url,
604 ])?;
605 for attribute in attributes {
606 if let Attribute::Class(value) = attribute {
607 object_class = Some(value);
608 } else if let Attribute::UniqueId(value) = attribute {
609 key_unique_id = Some(value);
610 } else if let Attribute::Label(value) = attribute {
611 key_label = Some(value);
612 } else if let Attribute::Id(value) = attribute {
613 key_id = Some(value);
614 } else if let Attribute::Url(value) = attribute {
615 key_url = Some(value);
616 } else {
617 unreachable!("get_attributes only returns \
618 requested attributes");
619 }
620 }
621
622 Ok(Self {
623 token,
624 composite_key: None,
625 object_class,
626 key_unique_id,
627 key_label,
628 key_id,
629 key_url,
630 openpgp_key: Mutex::new(None),
631
632 got_capabilities: false.into(),
633 signing_capable: false.into(),
634 decryption_capable: false.into(),
635 })
636 }
637
638 pub fn fingerprint(&self) -> Option<Fingerprint> {
642 self.to_openpgp_key().ok().map(|key| key.fingerprint())
643 }
644}
645
646#[derive(Debug)]
649enum KeyOrToken {
650 Key(Key),
651 Token(Token),
652}
653
654impl KeyOrToken {
655 fn is_key(&self) -> bool {
656 self.key().is_some()
657 }
658
659 fn key(&self) -> Option<&Key> {
660 match self {
661 KeyOrToken::Key(key) => Some(key),
662 KeyOrToken::Token(_) => None,
663 }
664 }
665
666 fn key_unwrap(&self) -> &Key {
667 self.key().expect(
668 "Internal error: looked up a key, got a token")
669 }
670
671 fn key_mut(&mut self) -> Option<&mut Key> {
672 match self {
673 KeyOrToken::Key(key) => Some(key),
674 KeyOrToken::Token(_) => None,
675 }
676 }
677
678 fn key_mut_unwrap(&mut self) -> &mut Key {
679 self.key_mut().expect(
680 "Internal error: looked up a key, got a token")
681 }
682
683 fn into_key_unwrap(self) -> Key {
684 match self {
685 KeyOrToken::Key(key) => key,
686 KeyOrToken::Token(_) =>
687 panic!("Internal error: looked up a token, got a key"),
688 }
689 }
690
691 fn into_token_unwrap(self) -> Token {
692 match self {
693 KeyOrToken::Key(_) =>
694 panic!("Internal error: looked up a token, got a key"),
695 KeyOrToken::Token(token) => token,
696 }
697 }
698
699}
700
701#[derive(Debug, Clone, Eq, PartialEq)]
705enum AllowedMatches {
706 None,
707 One,
708 Any,
709}
710
711#[derive(Debug, Clone, Eq, PartialEq)]
716pub enum SelectorScope {
717 All,
718 PublicKeys,
719 PrivateKeys,
720}
721
722static BACKENDS: Mutex<BTreeMap<PathBuf, Weak<Pkcs11>>>
725 = Mutex::new(BTreeMap::new());
726
727impl Context {
728 pub fn backends(&self) -> Result<&[Backend]> {
734 tracer!(TRACE, "Context::backends");
735
736 if let Some(backends) = self.backends.get() {
737 return Ok(backends);
738 }
739
740 let modules = self.config.modules();
741 let mut backends = Vec::with_capacity(modules.len());
742 let mut load_err = None;
743 let mut init_err = None;
744 for lib in modules {
745 t!("Loading {}", lib.display());
746
747 let mut backend = BACKENDS.lock().unwrap();
749 if let Some(context) = backend.get(lib) {
750 if let Some(context) = context.upgrade() {
751 t!("Loaded {} (cached)", lib.display());
752
753 backends.push(Backend {
754 lib: lib.clone(),
755 lib_str: lib.display().to_string(),
756 context,
757 });
758
759 continue;
760 }
761 }
762
763 let context = match cryptoki::context::Pkcs11::new(lib) {
764 Ok(context) => context,
765 Err(err) => {
766 log::debug!("{}: Error loading {}: {}",
767 func!(), lib.display(), err);
768 if load_err.is_none() {
769 load_err = Some(err);
770 }
771 continue;
772 }
773 };
774
775 match context.initialize(
777 cryptoki::context::CInitializeArgs::new(
778 cryptoki::context::CInitializeFlags::OS_LOCKING_OK))
779 {
780 Ok(context) => context,
781 Err(err) => {
782 log::debug!("{}: Error initializing {}: {}",
783 func!(), lib.display(), err);
784 if init_err.is_none() {
785 init_err = Some(err);
786 }
787 continue;
788 }
789 };
790 t!("Loaded {}", lib.display());
791
792 let context = Arc::new(context.into());
793
794 backend.insert(lib.clone(), Arc::downgrade(&context));
796
797 backends.push(Backend {
798 lib: lib.clone(),
799 lib_str: lib.display().to_string(),
800 context,
801 });
802 }
803
804 if let Some(err) = init_err {
805 return Err(err.into());
806 }
807 if let Some(err) = load_err {
808 return Err(err.into());
809 }
810
811 let _ = self.backends.set(backends);
812 let backends = self.backends.get().expect("just set");
813 Ok(backends)
814 }
815
816 fn select_internal(&self, selector: &KeySelector, key: bool,
825 allowed_matches: AllowedMatches,
826 scope: SelectorScope,
827 get_constituent: bool)
828 -> Result<Vec<KeyOrToken>>
829 {
830 tracer!(TRACE, "Context::select_internal");
831
832 let mut all: Vec<KeyOrToken> = Vec::new();
835 let mut matches: Vec<KeyOrToken> = Vec::new();
836
837 let mut backend_matched = false;
840 let mut backend_names = Vec::new();
841
842 for backend in self.backends()? {
843 backend_names.push(backend.lib_short());
844 if ! selector.backend_matches(&backend) {
845 continue;
846 } else {
847 backend_matched = true;
848 }
849
850 let slots = match backend.context().get_all_slots() {
851 Ok(slots) => slots,
852 Err(err) => {
853 log::debug!("{}: Failed to enumerate slots for {}: {}",
854 func!(), backend.lib().display(), err);
855 continue;
856 }
857 };
858 t!("{} has {} slots", backend.lib().display(), slots.len());
859 'slot_loop: for slot in slots.into_iter() {
860 let info = match backend.context().get_token_info(slot.clone()) {
861 Ok(info) => info,
862 Err(err) => {
863 t!("Failed to get token info for slot {}: {}",
864 slot.id(), err);
865 continue 'slot_loop;
866 }
867 };
868
869 let matches_token =
870 selector.slot_matches(slot.id())
871 && selector.token_label_matches(info.label())
872 && selector.token_serial_number_matches(
873 info.serial_number());
874
875 if ! key {
876 let token = Token {
878 backend: backend.clone(),
879 slot: slot,
880 info: info.clone(),
881 };
882
883 if matches_token {
884 matches.push(KeyOrToken::Token(token));
885 } else {
886 all.push(KeyOrToken::Token(token));
887 }
888 } else {
889 let session = match backend.context().open_ro_session(slot) {
891 Ok(session) => session,
892 Err(err) => {
893 log::debug!(
894 "{}: Warning: {}'s slot {} is unusable: {}",
895 func!(),
896 backend.lib().display(), slot.id(),
897 err);
898 continue 'slot_loop;
899 }
900 };
901
902 let attrs = match scope {
904 SelectorScope::All => &[][..],
905 SelectorScope::PublicKeys => {
906 &[ Attribute::Class(ObjectClass::PUBLIC_KEY) ]
907 }
908 SelectorScope::PrivateKeys => {
909 &[ Attribute::Class(ObjectClass::PRIVATE_KEY) ]
910 }
911 };
912 let objects = match session.iter_objects(attrs) {
913 Ok(objects) => objects,
914 Err(err) => {
915 log::debug!(
916 "{}: Error listing {}'s objects: {}",
917 func!(),
918 backend.lib().display(),
919 err);
920 continue 'slot_loop;
921 }
922 };
923
924 'obj_loop: for (i, object) in objects.enumerate() {
925 let object = match object {
926 Ok(object) => object,
927 Err(err) => {
928 log::debug!(
929 "{}: Error reading object #{}: {}",
930 func!(), i + 1, err);
931 continue 'obj_loop;
932 }
933 };
934
935 let token = Token {
937 backend: backend.clone(),
938 slot: slot,
939 info: info.clone(),
940 };
941 let key = match Key::from_object(
942 token, &session, object)
943 {
944 Ok(key) => key,
945 Err(err) => {
946 t!("Reading object #{}'s attributes: {}",
947 i + i, err);
948 continue 'obj_loop;
949 }
950 };
951 let matches_key_unique_id
952 = selector.key_unique_id_matches(key.key_unique_id());
953
954 let matches_key_label = if let Some(l) = selector.key_label() {
955 Some(l.as_bytes()) == key.key_label()
957 } else {
958 true
960 };
961
962 let matches_key_id = selector.key_id_matches(key.key_id());
963 let matches_key_url = selector.key_url_matches(key.key_url());
964
965 if matches_token
966 && matches_key_unique_id && matches_key_label
967 && matches_key_id && matches_key_url
968 {
969 matches.push(KeyOrToken::Key(key));
970 } else {
971 all.push(KeyOrToken::Key(key));
972 }
973 }
974 }
975 }
976 }
977
978 if key && get_constituent {
980 'next_match: for i in 0..matches.len() {
981 if i >= matches.len() {
982 break;
984 }
985
986 let m = &matches[i];
991 let key = m.key_unwrap();
992 let key_id = if let Some(key_id) = key.key_id() {
993 match String::from_utf8(key_id.to_vec()) {
994 Ok(key_id) => key_id,
995 Err(_err) => {
996 continue;
998 }
999 }
1000 } else {
1001 continue;
1002 };
1003
1004 let map = &[
1007 ("pgp:v6t:", "pgp:v6pq:"),
1008 ("pgp:v4t:", "pgp:v4pq:"),
1009 ];
1010
1011 let mut other_key_id = None;
1012 for (one, other) in map.into_iter().map(|(a, b)| (*a, *b))
1013 .chain(map.into_iter().map(|(a, b)| (*b, *a)))
1015 {
1016 if let Some(suffix) = key_id.strip_prefix(one) {
1017 other_key_id = Some(format!("{}{}", other, suffix));
1018 break;
1019 }
1020 }
1021
1022 let other_key_id = if let Some(other_key_id) = other_key_id {
1023 other_key_id
1024 } else {
1025 continue;
1027 };
1028
1029 if i + 1 < matches.len() {
1034 for j in i + 1..matches.len() {
1035 let other = matches[j].key_unwrap();
1036 if other.key_id() == Some(other_key_id.as_bytes()) {
1037 let other = matches.remove(j).into_key_unwrap();
1039 matches[i].key_mut_unwrap().combine_with(other);
1040 continue 'next_match;
1041 }
1042 }
1043 }
1044
1045 let other = self.select_internal(
1049 &KeySelector::from_key_id(other_key_id),
1050 true, AllowedMatches::One,
1052 SelectorScope::PublicKeys,
1053 false, );
1055 match other {
1056 Ok(results) => {
1057 assert_eq!(results.len(), 1);
1058 let other = results.into_iter().next().unwrap();
1059 let other = other.into_key_unwrap();
1060 matches[i].key_mut_unwrap().combine_with(other);
1061 }
1062 Err(err) => {
1063 log::debug!(
1064 "{}: Warning: {} is a composite key, \
1065 but half the key is missing: {}",
1066 func!(), key_id, err);
1067 }
1068 }
1069 }
1070 }
1071
1072 let obj = if key { "key" } else { "token" };
1073 let objs = if key { "keys" } else { "tokens" };
1074
1075 if allowed_matches == AllowedMatches::None {
1076 if matches.len() == 0 {
1078 Ok(vec![])
1079 } else {
1080 log::debug!("{}: The {} selector {} matches existing {}:",
1081 func!(), obj, selector.args(), objs);
1082 Self::list_matches(matches);
1083
1084 if key {
1085 Err(anyhow::anyhow!(
1086 "The {} selector matches existing {}, choose a \
1087 different label or use --ambiguous-key-label, \
1088 or --random-key-label",
1089 obj, objs))
1090 } else {
1091 Err(anyhow::anyhow!(
1092 "The {} selector matches existing {}", obj, objs))
1093 }
1094 }
1095 } else if allowed_matches == AllowedMatches::One && matches.len() == 0 {
1096 if let (Some(backend), false)
1098 = (selector.backend(), backend_matched)
1099 {
1100 Err(anyhow::anyhow!(
1101 "The specified backend ({}) wasn't loaded (try: {})",
1102 backend, backend_names.join(", ")))
1103 } else {
1104 log::debug!("{}: The {} selector {} does not match any of \
1105 the {}. Known {}:",
1106 func!(), obj, selector.args(), objs, objs);
1107 Self::list_matches(all);
1108
1109 Err(anyhow::anyhow!(
1110 "The specified selector ({}) doesn't match any of the {}",
1111 selector.args(), objs))
1112 }
1113 } else if allowed_matches == AllowedMatches::One && matches.len() > 1 {
1114 log::debug!("{}: The {} selector {} matches multiple {}:",
1116 func!(), obj, selector.args(), objs);
1117 Self::list_matches(matches);
1118
1119 Err(anyhow::anyhow!(
1120 "Multiple {} match {}, try being more specific.",
1121 objs, selector.args()))
1122 } else {
1123 Ok(matches)
1124 }
1125 }
1126
1127 fn list_matches(items: Vec<KeyOrToken>) {
1129 let is_key = items.iter().next()
1130 .map(|o| o.is_key())
1131 .unwrap_or(false);
1132
1133 let list_token = |t: &Token| -> String {
1134 format!("--backend {} --slot {} --token-label {:?} \
1135 --token-serial-number {}",
1136 t.backend().lib_short(), t.slot().id(), t.info().label(),
1137 t.info().serial_number())
1138 };
1139
1140 for obj in items.into_iter() {
1141 match obj {
1142 KeyOrToken::Key(key) => {
1143 assert!(is_key);
1144 let mut bits: Vec<Cow<str>> = Vec::new();
1145 bits.push(list_token(&key.token()).into());
1146 if let Some(key_unique_id) = key.key_unique_id() {
1147 bits.push(Cow::Borrowed("--key-unique-id"));
1148 bits.push(format!(
1149 "{:?}", String::from_utf8_lossy(key_unique_id)).into());
1150 }
1151 if let Some(key_label) = key.key_label() {
1152 bits.push(Cow::Borrowed("--key-label"));
1153 bits.push(format!(
1154 "{:?}", String::from_utf8_lossy(key_label)).into());
1155 }
1156 if let Some(key_id) = key.key_id() {
1157 bits.push(Cow::Borrowed("--key-id"));
1158 bits.push(format!(
1159 "{:?}", String::from_utf8_lossy(key_id)).into());
1160 }
1161 if let Some(key_url) = key.key_url() {
1162 bits.push(Cow::Borrowed("--key-url"));
1163 bits.push(format!(
1164 "{:?}", String::from_utf8_lossy(key_url)).into());
1165 }
1166 eprintln!(" - {}", bits.join(" "));
1167 }
1168 KeyOrToken::Token(token) => {
1169 assert!(! is_key);
1170 eprintln!(" - {}", list_token(&token));
1171 }
1172 }
1173 }
1174 }
1175
1176 pub fn tokens(&self) -> Result<impl Iterator<Item=Token>> {
1178 let matches = self.select_internal(
1179 &KeySelector::unconstrained(), false,
1180 AllowedMatches::Any, SelectorScope::PublicKeys,
1181 false)?;
1183
1184 Ok(matches
1185 .into_iter()
1186 .map(|obj| obj.into_token_unwrap()))
1187 }
1188
1189 pub fn select_one_token(&self, selector: &TokenSelector)
1194 -> Result<Token>
1195 {
1196 let key_selector
1197 = KeySelector::from_token_selector(selector.clone());
1198 let matches = self.select_internal(&key_selector, false,
1199 AllowedMatches::One,
1200 SelectorScope::All,
1201 false)?;
1202
1203 assert_eq!(matches.len(), 1);
1204
1205 let token = matches.into_iter().next().unwrap().into_token_unwrap();
1206
1207 Ok(token)
1208 }
1209
1210 pub fn keys(&self) -> Result<impl Iterator<Item=Key>> {
1212 let matches = self.select_internal(
1213 &KeySelector::unconstrained(), true,
1214 AllowedMatches::Any, SelectorScope::PublicKeys,
1215 true)?;
1217
1218 Ok(matches
1219 .into_iter()
1220 .map(|obj| obj.into_key_unwrap()))
1221 }
1222
1223 pub fn select_one_key(&self, selector: &KeySelector, scope: SelectorScope)
1228 -> Result<Key>
1229 {
1230 let matches = self.select_internal(
1231 &selector, true, AllowedMatches::One, scope,
1232 true)?;
1234
1235 assert_eq!(matches.len(), 1);
1236
1237 let key = matches.into_iter().next().unwrap().into_key_unwrap();
1238
1239 Ok(key)
1240 }
1241
1242 pub fn select_keys(&self, selector: &KeySelector, scope: SelectorScope)
1247 -> Result<Vec<Key>>
1248 {
1249 let matches = self.select_internal(
1250 &selector, true, AllowedMatches::Any, scope,
1251 true)?;
1253
1254 let keys = matches
1255 .into_iter()
1256 .map(|obj| obj.into_key_unwrap())
1257 .collect::<Vec<Key>>();
1258
1259 Ok(keys)
1260 }
1261
1262 pub fn check_no_keys_have_label(&self, label: &str)
1264 -> Result<()>
1265 {
1266 tracer!(TRACE, "config::check_no_keys_have_label");
1267 t!("Checking that the key label {} is unique", label);
1268
1269 let selector = KeySelector::from_key_label(label);
1270 self.select_internal(&selector, true,
1271 AllowedMatches::None,
1272 SelectorScope::All,
1273 false)?;
1275
1276 Ok(())
1277 }
1278
1279 pub fn check_no_keys_have_id(&self, id: &str)
1281 -> Result<()>
1282 {
1283 tracer!(TRACE, "config::check_no_keys_have_id");
1284 t!("Checking that the key ID {} is unique", id);
1285
1286 let selector = KeySelector::from_key_id(id);
1287 self.select_internal(&selector, true,
1288 AllowedMatches::None,
1289 SelectorScope::All,
1290 false)?;
1292
1293 Ok(())
1294 }
1295}