1use alloc::collections::VecDeque;
2use alloc::sync::Arc;
3use core::fmt;
4use core::net::{IpAddr, Ipv6Addr, SocketAddr};
5use core::str::FromStr;
6use core::time::Duration;
7use std::fs::{self, OpenOptions};
8use std::io;
9use std::path::{Path, PathBuf};
10use std::sync::{Mutex, PoisonError};
11use std::time::{Instant, SystemTime};
12
13use data_encoding::{HEXLOWER, HEXLOWER_PERMISSIVE};
14use sha2::{Digest as _, Sha256};
15
16use crate::clock::{Clock, from_unix_seconds, unix_seconds};
17use crate::error::Error;
18use crate::file::{self, Access};
19use crate::id::PeerId;
20use crate::key::KeyMaterial;
21use crate::pem;
22use crate::random::Random;
23use crate::waiting::{WaitingQueue, WaitingSettings, WhenFull};
24use coqui_builder::builder::Holds;
25
26pub const FORMAT_VERSION: u32 = 1;
28
29pub const MAX_LABEL: usize = 128;
31
32const MAX_EVENTS: usize = 1024;
34
35pub(crate) const DEFAULT_IPV6_PREFIX: u8 = 64;
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, coqui_builder::Describe)]
45#[map(deny_unknown_fields)]
46#[non_exhaustive]
47pub struct WaitingLimits {
48 #[map(default = WaitingLimits::default().per_source)]
52 pub per_source: usize,
53 #[map(default = WaitingLimits::default().total)]
55 pub total: usize,
56 #[map(default = WaitingLimits::default().rerecord)]
58 pub rerecord: Duration,
59}
60
61impl Default for WaitingLimits {
62 fn default() -> Self {
63 Self {
64 per_source: 16,
65 total: 1_000,
66 rerecord: Duration::from_secs(60),
67 }
68 }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, coqui_builder::Describe)]
76#[map(deny_unknown_fields)]
77#[non_exhaustive]
78pub struct RotationOptions {
79 #[map(default = RotationOptions::default().retire_after)]
81 pub retire_after: Duration,
82 #[map(default = RotationOptions::default().require_approval)]
85 pub require_approval: bool,
86 #[map(default = RotationOptions::default().allow_unproven)]
90 pub allow_unproven: bool,
91}
92
93impl Default for RotationOptions {
94 fn default() -> Self {
95 Self {
96 retire_after: Duration::from_secs(24 * 3600),
97 require_approval: false,
98 allow_unproven: false,
99 }
100 }
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105#[non_exhaustive]
106pub struct InvitationOptions {
107 pub valid_for: Duration,
110 pub uses: u32,
112}
113
114impl Default for InvitationOptions {
115 fn default() -> Self {
116 Self {
117 valid_for: Duration::from_secs(24 * 3600),
118 uses: 1,
119 }
120 }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125#[non_exhaustive]
126pub struct WaitingEntry {
127 pub id: PeerId,
129 pub source: Option<SocketAddr>,
131}
132
133#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
136pub struct InvitationId([u8; 32]);
137
138impl InvitationId {
139 pub fn of(secret: &[u8; 32]) -> Self {
141 Self(Sha256::digest(secret).into())
142 }
143
144 pub fn hex(&self) -> String {
146 HEXLOWER.encode(&self.0)
147 }
148}
149
150impl fmt::Display for InvitationId {
151 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
152 formatter.write_str(&self.hex())
153 }
154}
155
156impl fmt::Debug for InvitationId {
157 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
158 write!(formatter, "InvitationId({})", self.hex())
159 }
160}
161
162impl FromStr for InvitationId {
163 type Err = Error;
164
165 fn from_str(text: &str) -> Result<Self, Error> {
167 let text = text.trim();
168 let mut bytes = [0u8; 32];
169 if text.len() != 64 {
170 return Err(Error::InvalidId);
171 }
172 HEXLOWER_PERMISSIVE
173 .decode_mut(text.as_bytes(), &mut bytes)
174 .map_err(|_| Error::InvalidId)?;
175 Ok(Self(bytes))
176 }
177}
178
179#[derive(Clone, PartialEq, Eq)]
185#[non_exhaustive]
186pub struct Invitation {
187 pub secret: [u8; 32],
189 pub expires: SystemTime,
191 pub uses: u32,
194 pub label: String,
196}
197
198impl Invitation {
199 pub fn id(&self) -> InvitationId {
201 InvitationId::of(&self.secret)
202 }
203}
204
205impl Drop for Invitation {
206 fn drop(&mut self) {
207 zeroize::Zeroize::zeroize(&mut self.secret);
208 }
209}
210
211impl fmt::Debug for Invitation {
212 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
213 formatter
214 .debug_struct("Invitation")
215 .field("id", &self.id())
216 .field("expires", &self.expires)
217 .field("uses", &self.uses)
218 .field("label", &self.label)
219 .finish_non_exhaustive()
220 }
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
225#[non_exhaustive]
226pub struct InvitationEntry {
227 pub id: InvitationId,
229 pub expires: SystemTime,
231 pub uses: u32,
233 pub label: String,
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240#[non_exhaustive]
241pub struct Successor {
242 pub old: PeerId,
244 pub new: PeerId,
246 pub proven: Option<SystemTime>,
248}
249
250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
252#[non_exhaustive]
253pub struct Retiring {
254 pub id: PeerId,
256 pub successor: Option<PeerId>,
258 pub retires: SystemTime,
260}
261
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264#[non_exhaustive]
265pub enum RotationEvent {
266 Announced {
268 old: PeerId,
270 new: PeerId,
272 },
273 Promoted {
275 old: PeerId,
277 new: PeerId,
279 retires: SystemTime,
281 },
282}
283
284#[derive(Debug, Clone)]
344pub struct TrustStore {
345 root: PathBuf,
346 waiting: Arc<Mutex<WaitingQueue>>,
347 events: Arc<Mutex<VecDeque<RotationEvent>>>,
348 clock: Clock,
349 rotation: RotationOptions,
350}
351
352struct Entry {
354 key: KeyMaterial,
355 source: Option<SocketAddr>,
356 successor: Option<PeerId>,
357 retires: Option<u64>,
358 predecessor: Option<PeerId>,
359 proven: Option<u64>,
360}
361
362#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, coqui_builder::Describe)]
370#[builder(setters_on = TrustStoreBuilder)]
371#[map(deny_unknown_fields)]
372#[non_exhaustive]
373pub struct TrustStoreSettings {
374 #[map(default = TrustStoreSettings::default().waiting)]
376 pub waiting: WaitingSettings,
377 #[map(default = TrustStoreSettings::default().rotation)]
379 pub rotation: RotationOptions,
380}
381
382impl TrustStoreSettings {
383 pub fn non_defaults(&self) -> Vec<coqui_builder::NonDefault> {
385 coqui_builder::non_defaults(self)
386 }
387}
388
389#[derive(coqui_builder::Builder, Debug)]
394#[builder(build = TrustStore, fallible)]
395pub struct TrustStoreParts {
396 settings: TrustStoreSettings,
397 #[builder(input)]
398 state_dir: PathBuf,
399 #[builder(input)]
400 clock: Option<Clock>,
401}
402
403impl TryFrom<TrustStoreParts> for TrustStore {
404 type Error = Error;
405
406 fn try_from(parts: TrustStoreParts) -> Result<Self, Error> {
412 let root = parts.state_dir.join("peers");
413 fs::create_dir_all(root.join("accepted")).map_err(Error::Io)?;
414 fs::create_dir_all(root.join("waiting")).map_err(Error::Io)?;
415 Ok(TrustStore {
416 root,
417 waiting: Arc::new(Mutex::new(WaitingQueue::from_settings(
418 parts.settings.waiting,
419 ))),
420 events: Arc::default(),
421 clock: parts.clock.unwrap_or_default(),
422 rotation: parts.settings.rotation,
423 })
424 }
425}
426
427impl TrustStoreBuilder {
428 pub fn limits(mut self, limits: WaitingLimits) -> Self {
430 self.partial_mut()
431 .put("waiting.limits", limits)
432 .expect("waiting.limits is a key of the settings");
433 self
434 }
435
436 pub fn ipv6_prefix(mut self, bits: u8) -> Self {
440 self.partial_mut()
441 .put("waiting.ipv6_prefix", bits)
442 .expect("waiting.ipv6_prefix is a key of the settings");
443 self
444 }
445
446 pub fn when_full(mut self, when_full: WhenFull) -> Self {
449 self.partial_mut()
450 .put("waiting.when_full", when_full)
451 .expect("waiting.when_full is a key of the settings");
452 self
453 }
454
455 pub fn record_interval(mut self, interval: Duration) -> Self {
458 self.partial_mut()
459 .put("waiting.record_interval", interval)
460 .expect("waiting.record_interval is a key of the settings");
461 self
462 }
463}
464
465impl TrustStore {
466 pub fn open(state_dir: &Path) -> Result<Self, Error> {
473 Self::try_from(TrustStoreParts {
474 settings: TrustStoreSettings::default(),
475 state_dir: state_dir.to_path_buf(),
476 clock: None,
477 })
478 }
479
480 #[must_use]
483 pub fn waiting_queue(self, settings: WaitingSettings) -> Self {
484 self.reconfigured(|current| current.waiting = settings)
485 }
486
487 fn queue(&self) -> std::sync::MutexGuard<'_, WaitingQueue> {
489 self.waiting.lock().unwrap_or_else(PoisonError::into_inner)
490 }
491
492 fn reconfigured(mut self, change: impl FnOnce(&mut TrustStoreSettings)) -> Self {
494 let mut settings = self.settings();
495 change(&mut settings);
496 self.waiting = Arc::new(Mutex::new(WaitingQueue::from_settings(settings.waiting)));
497 self.rotation = settings.rotation;
498 self
499 }
500
501 pub fn settings(&self) -> TrustStoreSettings {
503 TrustStoreSettings {
504 waiting: self.queue().settings(),
505 rotation: self.rotation,
506 }
507 }
508
509 pub fn non_defaults(&self) -> Vec<coqui_builder::NonDefault> {
511 self.settings().non_defaults()
512 }
513
514 pub fn rotation(&self) -> RotationOptions {
516 self.rotation
517 }
518
519 pub fn clock(&self) -> &Clock {
521 &self.clock
522 }
523
524 pub fn waiting(&self) -> Result<Vec<WaitingEntry>, Error> {
531 Ok(self
532 .list("waiting")?
533 .into_iter()
534 .map(|id| WaitingEntry {
535 id,
536 source: self.read("waiting", &id).and_then(|entry| entry.source),
537 })
538 .collect())
539 }
540
541 pub fn accepted(&self) -> Result<Vec<PeerId>, Error> {
547 Ok(self
548 .list("accepted")?
549 .into_iter()
550 .filter(|id| self.current(id).is_some())
551 .collect())
552 }
553
554 pub fn accepted_key(&self, id: &PeerId) -> Option<KeyMaterial> {
557 self.current(id).map(|entry| entry.key)
558 }
559
560 pub fn waiting_key(&self, id: &PeerId) -> Option<KeyMaterial> {
562 self.read("waiting", id).map(|entry| entry.key)
563 }
564
565 pub fn accept(&self, id: &PeerId) -> Result<(), Error> {
572 if self.is_accepted(id) {
573 return Err(Error::AlreadyAccepted);
574 }
575 let path = self.existing("waiting", id).ok_or(Error::NotWaiting)?;
576 let text = fs::read_to_string(&path).map_err(|error| {
577 if error.kind() == io::ErrorKind::NotFound {
578 Error::NotWaiting
579 } else {
580 Error::Io(error)
581 }
582 })?;
583 let entry = parse(&text).ok_or(Error::Material)?;
584 if entry.key.id() != *id {
585 return Err(Error::Material);
586 }
587 self.write_current(&entry.key)?;
588 let _ = fs::remove_file(path);
589 Ok(())
590 }
591
592 pub fn accept_key(&self, key: &KeyMaterial) -> Result<PeerId, Error> {
600 key.check()?;
601 let id = key.id();
602 self.write_current(key)?;
603 let _ = fs::remove_file(self.path("waiting", &id));
604 Ok(id)
605 }
606
607 pub fn remove(&self, id: &PeerId) -> Result<bool, Error> {
614 let mut removed = false;
615 if let Some(successor) = self.read("accepted", id).and_then(|entry| entry.successor)
616 && self
617 .read("successors", &successor)
618 .is_some_and(|entry| entry.predecessor == Some(*id))
619 {
620 fs::remove_file(self.path("successors", &successor)).map_err(Error::Io)?;
621 }
622 for section in ["accepted", "waiting", "successors"] {
623 if let Some(path) = self.existing(section, id) {
624 fs::remove_file(path).map_err(Error::Io)?;
625 removed = true;
626 }
627 }
628 Ok(removed)
629 }
630
631 pub fn is_accepted(&self, id: &PeerId) -> bool {
634 self.current(id).is_some()
635 }
636
637 pub fn record_waiting(&self, key: &KeyMaterial, source: Option<SocketAddr>) {
653 if key.check().is_err() {
654 return;
655 }
656 let id = key.id();
657 if self.existing("waiting", &id).is_some() {
658 return;
659 }
660 let Ok(stored) = self.list("waiting") else {
661 return;
662 };
663 let now = Instant::now();
664 let mut queue = self.queue();
665 queue.prune(now, |had| stored.binary_search(had).is_ok());
667 let admission = queue.admit(id, source, stored.len(), now);
668 if !admission.record {
669 return;
670 }
671 for old in &admission.evict {
672 let _ = fs::remove_file(self.path("waiting", old));
673 }
674 let mut text = source.map_or_else(String::new, |s| format!("Source: {s}\n"));
675 text.push_str(&format!("Method: {}\n", key.method));
676 text.push_str(&pem::encode(&key.label, &key.bytes));
677 let _ = write_new(&self.path("waiting", &id), &text);
678 }
679
680 pub fn invite(
688 &self,
689 random: &Random,
690 options: InvitationOptions,
691 label: &str,
692 ) -> Result<Invitation, Error> {
693 let label_ok = label.len() <= MAX_LABEL
694 && label.trim() == label
695 && !label.chars().any(char::is_control);
696 if !label_ok || options.uses == 0 || options.valid_for.is_zero() {
697 return Err(Error::InvalidOptions);
698 }
699 let mut secret = [0u8; 32];
700 random.fill(&mut secret)?;
701 let expires = from_unix_seconds(
702 unix_seconds(self.clock.now()).saturating_add(options.valid_for.as_secs()),
703 );
704 let invitation = Invitation {
705 secret,
706 expires,
707 uses: options.uses,
708 label: label.to_owned(),
709 };
710 fs::create_dir_all(self.root.join("invitations")).map_err(Error::Io)?;
711 write_new(
712 &self.invitation_path(&invitation.id()),
713 &invitation_text(expires, options.uses, label),
714 )
715 .map_err(Error::Io)?;
716 Ok(invitation)
717 }
718
719 pub fn redeem(&self, secret: &[u8; 32]) -> Result<Invitation, Error> {
730 let path = self.invitation_path(&InvitationId::of(secret));
731 let claimed = file::temporary_path(&path);
732 if let Err(error) = fs::rename(&path, &claimed) {
734 return Err(if error.kind() == io::ErrorKind::NotFound {
735 Error::NotInvited
736 } else {
737 Error::Io(error)
738 });
739 }
740 let text = fs::read_to_string(&claimed).ok();
741 if file::retried(|| fs::remove_file(&claimed)).is_err() {
745 return Err(Error::NotInvited);
746 }
747 let (expires, uses, label) = text
748 .as_deref()
749 .and_then(parse_invitation)
750 .ok_or(Error::NotInvited)?;
751 let revoked = self.revoked_path(&InvitationId::of(secret));
752 if revoked.exists() {
753 return Err(Error::NotInvited);
754 }
755 if self.clock.now() >= from_unix_seconds(expires) {
756 return Err(Error::Expired);
757 }
758 let left = uses - 1;
759 if left > 0 {
760 let _ = write_new(
762 &path,
763 &invitation_text(from_unix_seconds(expires), left, &label),
764 );
765 if revoked.exists() {
768 let _ = fs::remove_file(&path);
769 return Err(Error::NotInvited);
770 }
771 }
772 Ok(Invitation {
773 secret: *secret,
774 expires: from_unix_seconds(expires),
775 uses: left,
776 label,
777 })
778 }
779
780 pub fn invitations(&self) -> Result<Vec<InvitationEntry>, Error> {
786 let directory = self.root.join("invitations");
787 let entries = match fs::read_dir(&directory) {
788 Ok(entries) => entries,
789 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
790 Err(error) => return Err(Error::Io(error)),
791 };
792 let mut found = Vec::new();
793 for entry in entries {
794 let path = entry.map_err(Error::Io)?.path();
795 let Some(id) = path
796 .extension()
797 .filter(|extension| *extension == "inv")
798 .and_then(|_| path.file_stem())
799 .and_then(|stem| stem.to_str())
800 .filter(|stem| is_hex_name(stem))
801 .and_then(|stem| stem.parse::<InvitationId>().ok())
802 else {
803 continue;
804 };
805 if let Some((expires, uses, label)) = fs::read_to_string(&path)
806 .ok()
807 .as_deref()
808 .and_then(parse_invitation)
809 {
810 found.push(InvitationEntry {
811 id,
812 expires: from_unix_seconds(expires),
813 uses,
814 label,
815 });
816 }
817 }
818 found.sort_by_key(|entry| entry.id);
819 Ok(found)
820 }
821
822 pub fn revoke_invitation(&self, id: &InvitationId) -> Result<bool, Error> {
830 fs::create_dir_all(self.root.join("invitations")).map_err(Error::Io)?;
831 OpenOptions::new()
832 .create(true)
833 .truncate(false)
834 .write(true)
835 .open(self.revoked_path(id))
836 .map_err(Error::Io)?;
837 match file::retried(|| fs::remove_file(self.invitation_path(id))) {
838 Ok(()) => Ok(true),
839 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
840 Err(error) => Err(Error::Io(error)),
841 }
842 }
843
844 pub fn announce_successor(&self, old: &PeerId, new: &KeyMaterial) -> Result<(), Error> {
855 new.check()?;
856 let new_id = new.id();
857 if new_id == *old {
858 return Err(Error::Material);
859 }
860 let entry = self
861 .current(old)
862 .filter(|entry| entry.retires.is_none())
863 .ok_or(Error::NotAccepted)?;
864 if self.existing("accepted", &new_id).is_some() {
865 return Err(Error::AlreadyAccepted);
866 }
867 if self.successor_key(&new_id).is_some()
870 && self
871 .read("successors", &new_id)
872 .and_then(|pending| pending.predecessor)
873 .is_some_and(|predecessor| predecessor != *old)
874 {
875 return Err(Error::SuccessorTaken);
876 }
877 if let Some(previous) = entry.successor
878 && previous != new_id
879 && self
880 .read("successors", &previous)
881 .is_some_and(|pending| pending.predecessor == Some(*old))
882 {
883 let _ = fs::remove_file(self.path("successors", &previous));
884 }
885 fs::create_dir_all(self.root.join("successors")).map_err(Error::Io)?;
886 let text = format!(
887 "Predecessor: {}\nMethod: {}\n{}",
888 old.hex(),
889 new.method,
890 pem::encode(&new.label, &new.bytes)
891 );
892 replace(&self.path("successors", &new_id), &text).map_err(Error::Io)?;
893 let path = self.existing("accepted", old).ok_or(Error::NotAccepted)?;
894 replace(&path, &accepted_text(&entry.key, Some(&new_id), None)).map_err(Error::Io)?;
895 self.push_event(RotationEvent::Announced {
896 old: *old,
897 new: new_id,
898 });
899 Ok(())
900 }
901
902 pub fn successor_key(&self, new: &PeerId) -> Option<KeyMaterial> {
905 let pending = self.read("successors", new)?;
906 let old = pending.predecessor?;
907 self.current(&old)
908 .filter(|entry| entry.retires.is_none() && entry.successor == Some(*new))
909 .map(|_| pending.key)
910 }
911
912 pub fn prove_successor(&self, new: &PeerId) -> Result<(), Error> {
921 let key = self.successor_key(new).ok_or(Error::NoSuccessor)?;
922 let pending = self.read("successors", new).ok_or(Error::NoSuccessor)?;
923 if pending.proven.is_some() {
924 return Ok(());
925 }
926 let old = pending.predecessor.ok_or(Error::NoSuccessor)?;
927 let text = format!(
928 "Predecessor: {}
929Method: {}
930Proven: {}
931{}",
932 old.hex(),
933 key.method,
934 unix_seconds(self.clock.now()),
935 pem::encode(&key.label, &key.bytes)
936 );
937 replace(&self.path("successors", new), &text).map_err(Error::Io)
938 }
939
940 pub fn promote_successor(&self, new: &PeerId) -> Result<PeerId, Error> {
951 let key = self.successor_key(new).ok_or(Error::NoSuccessor)?;
952 if !self.rotation.allow_unproven
953 && self
954 .read("successors", new)
955 .is_none_or(|pending| pending.proven.is_none())
956 {
957 return Err(Error::NotProven);
958 }
959 let old = self
960 .read("successors", new)
961 .and_then(|entry| entry.predecessor)
962 .ok_or(Error::NoSuccessor)?;
963 let old_entry = self.current(&old).ok_or(Error::NoSuccessor)?;
964 match self.write_accepted(&key) {
965 Ok(()) | Err(Error::AlreadyAccepted) => {}
966 Err(error) => return Err(error),
967 }
968 let retires =
969 unix_seconds(self.clock.now()).saturating_add(self.rotation.retire_after.as_secs());
970 let path = self.existing("accepted", &old).ok_or(Error::NoSuccessor)?;
971 replace(
972 &path,
973 &accepted_text(&old_entry.key, Some(new), Some(retires)),
974 )
975 .map_err(Error::Io)?;
976 let _ = fs::remove_file(self.path("successors", new));
977 self.push_event(RotationEvent::Promoted {
978 old,
979 new: *new,
980 retires: from_unix_seconds(retires),
981 });
982 Ok(old)
983 }
984
985 pub fn successors(&self) -> Result<Vec<Successor>, Error> {
991 Ok(self
992 .list("successors")?
993 .into_iter()
994 .filter(|new| self.successor_key(new).is_some())
995 .filter_map(|new| {
996 let pending = self.read("successors", &new)?;
997 Some(Successor {
998 old: pending.predecessor?,
999 new,
1000 proven: pending.proven.map(from_unix_seconds),
1001 })
1002 })
1003 .collect())
1004 }
1005
1006 pub fn retiring(&self) -> Result<Vec<Retiring>, Error> {
1012 Ok(self
1013 .list("accepted")?
1014 .into_iter()
1015 .filter_map(|id| {
1016 let entry = self.read("accepted", &id)?;
1017 Some(Retiring {
1018 id,
1019 successor: entry.successor,
1020 retires: from_unix_seconds(entry.retires?),
1021 })
1022 })
1023 .collect())
1024 }
1025
1026 pub fn take_rotation_events(&self) -> Vec<RotationEvent> {
1030 self.events
1031 .lock()
1032 .unwrap_or_else(PoisonError::into_inner)
1033 .drain(..)
1034 .collect()
1035 }
1036
1037 fn push_event(&self, event: RotationEvent) {
1038 let mut events = self.events.lock().unwrap_or_else(PoisonError::into_inner);
1039 if events.len() >= MAX_EVENTS {
1040 events.pop_front();
1041 }
1042 events.push_back(event);
1043 }
1044
1045 fn write_current(&self, key: &KeyMaterial) -> Result<(), Error> {
1047 if self.is_accepted(&key.id()) {
1048 return Err(Error::AlreadyAccepted);
1049 }
1050 match self.existing("accepted", &key.id()) {
1051 Some(path) => replace(&path, &accepted_text(key, None, None)).map_err(Error::Io),
1052 None => self.write_accepted(key),
1053 }
1054 }
1055
1056 fn write_accepted(&self, key: &KeyMaterial) -> Result<(), Error> {
1057 match write_new(
1058 &self.path("accepted", &key.id()),
1059 &accepted_text(key, None, None),
1060 ) {
1061 Ok(()) => Ok(()),
1062 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
1063 Err(Error::AlreadyAccepted)
1064 }
1065 Err(error) => Err(Error::Io(error)),
1066 }
1067 }
1068
1069 fn current(&self, id: &PeerId) -> Option<Entry> {
1071 let entry = self.read("accepted", id)?;
1072 match entry.retires {
1073 Some(retires) if self.clock.now() >= from_unix_seconds(retires) => None,
1074 _ => Some(entry),
1075 }
1076 }
1077
1078 fn read(&self, section: &str, id: &PeerId) -> Option<Entry> {
1080 let text = fs::read_to_string(self.existing(section, id)?).ok()?;
1081 parse(&text).filter(|entry| entry.key.id() == *id)
1082 }
1083
1084 fn list(&self, section: &str) -> Result<Vec<PeerId>, Error> {
1085 let entries = match fs::read_dir(self.root.join(section)) {
1086 Ok(entries) => entries,
1087 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
1088 Err(error) => return Err(Error::Io(error)),
1089 };
1090 let mut ids = Vec::new();
1091 for entry in entries {
1092 let path = entry.map_err(Error::Io)?.path();
1093 if path.extension().is_some_and(|extension| extension == "pem")
1094 && let Some(Ok(id)) = path
1095 .file_stem()
1096 .and_then(|stem| stem.to_str())
1097 .filter(|stem| is_hex_name(stem))
1098 .map(str::parse::<PeerId>)
1099 && !ids.contains(&id)
1100 {
1101 ids.push(id);
1102 }
1103 }
1104 ids.sort();
1105 Ok(ids)
1106 }
1107
1108 fn path(&self, section: &str, id: &PeerId) -> PathBuf {
1109 self.root.join(section).join(format!("{}.pem", id.hex()))
1110 }
1111
1112 fn revoked_path(&self, id: &InvitationId) -> PathBuf {
1113 self.root
1114 .join("invitations")
1115 .join(format!("{}.revoked", id.hex()))
1116 }
1117
1118 fn invitation_path(&self, id: &InvitationId) -> PathBuf {
1119 self.root
1120 .join("invitations")
1121 .join(format!("{}.inv", id.hex()))
1122 }
1123
1124 fn existing(&self, section: &str, id: &PeerId) -> Option<PathBuf> {
1126 let path = self.path(section, id);
1127 path.is_file().then_some(path)
1128 }
1129}
1130
1131fn is_hex_name(stem: &str) -> bool {
1133 stem.len() == 64 && HEXLOWER.decode_mut(stem.as_bytes(), &mut [0u8; 32]).is_ok()
1134}
1135
1136pub(crate) fn source_key(address: IpAddr, prefix: u8) -> IpAddr {
1139 match address {
1140 IpAddr::V4(_) => address,
1141 IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
1142 Some(v4) => IpAddr::V4(v4),
1143 None => {
1144 let mask = u128::MAX
1145 .checked_shl(128 - u32::from(prefix.min(128)))
1146 .unwrap_or(0);
1147 IpAddr::V6(Ipv6Addr::from(u128::from(v6) & mask))
1148 }
1149 },
1150 }
1151}
1152
1153fn accepted_text(key: &KeyMaterial, successor: Option<&PeerId>, retires: Option<u64>) -> String {
1155 let mut text = format!("Method: {}\n", key.method);
1156 if let Some(successor) = successor {
1157 text.push_str(&format!("Successor: {}\n", successor.hex()));
1158 }
1159 if let Some(retires) = retires {
1160 text.push_str(&format!("Retires: {retires}\n"));
1161 }
1162 text.push_str(&pem::encode(&key.label, &key.bytes));
1163 text
1164}
1165
1166fn invitation_text(expires: SystemTime, uses: u32, label: &str) -> String {
1167 let mut text = format!("Expires: {}\nUses: {uses}\n", unix_seconds(expires));
1168 if !label.is_empty() {
1169 text.push_str(&format!("Label: {label}\n"));
1170 }
1171 text
1172}
1173
1174fn parse_invitation(text: &str) -> Option<(u64, u32, String)> {
1177 let (mut expires, mut uses, mut label) = (None, None, String::new());
1178 for line in text.lines() {
1179 if let Some(value) = line.strip_prefix("Expires: ") {
1180 expires = value.trim().parse().ok();
1181 } else if let Some(value) = line.strip_prefix("Uses: ") {
1182 uses = value.trim().parse::<u32>().ok().filter(|uses| *uses > 0);
1183 } else if let Some(value) = line.strip_prefix("Label: ") {
1184 value.trim().clone_into(&mut label);
1185 }
1186 }
1187 Some((expires?, uses?, label))
1188}
1189
1190fn parse(text: &str) -> Option<Entry> {
1192 let pem::Block {
1193 headers,
1194 label,
1195 bytes,
1196 ..
1197 } = pem::decode(text)?;
1198 let mut method = None;
1199 let (mut source, mut successor, mut retires) = (None, None, None);
1200 let (mut predecessor, mut proven) = (None, None);
1201 for line in headers {
1202 if let Some(value) = line.strip_prefix("Method: ") {
1203 method = Some(value.trim());
1204 } else if let Some(value) = line.strip_prefix("Source: ") {
1205 source = value.trim().parse().ok();
1206 } else if let Some(value) = line.strip_prefix("Successor: ") {
1207 successor = Some(value.trim().parse().ok()?);
1208 } else if let Some(value) = line.strip_prefix("Retires: ") {
1209 retires = Some(value.trim().parse().ok()?);
1210 } else if let Some(value) = line.strip_prefix("Predecessor: ") {
1211 predecessor = Some(value.trim().parse().ok()?);
1212 } else if let Some(value) = line.strip_prefix("Proven: ") {
1213 proven = Some(value.trim().parse().ok()?);
1214 }
1215 }
1216 Some(Entry {
1217 key: KeyMaterial::new(method?, label, bytes).ok()?,
1218 source,
1219 successor,
1220 retires,
1221 predecessor,
1222 proven,
1223 })
1224}
1225
1226fn write_new(path: &Path, text: &str) -> io::Result<()> {
1228 file::write_new(path, text.as_bytes(), Access::Default)
1229}
1230
1231fn replace(path: &Path, text: &str) -> io::Result<()> {
1233 file::replace(path, text.as_bytes(), Access::Default)
1234}