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;
24
25pub const FORMAT_VERSION: u32 = 1;
27
28pub const MAX_LABEL: usize = 128;
30
31const MAX_EVENTS: usize = 1024;
33
34pub(crate) const DEFAULT_IPV6_PREFIX: u8 = 64;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct WaitingLimits {
41 pub per_source: usize,
44 pub total: usize,
46 pub rerecord: Duration,
48}
49
50impl Default for WaitingLimits {
51 fn default() -> Self {
52 Self {
53 per_source: 16,
54 total: 1_000,
55 rerecord: Duration::from_secs(60),
56 }
57 }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct RotationOptions {
63 pub retire_after: Duration,
65 pub require_approval: bool,
68 pub allow_unproven: bool,
72}
73
74impl Default for RotationOptions {
75 fn default() -> Self {
76 Self {
77 retire_after: Duration::from_secs(24 * 3600),
78 require_approval: false,
79 allow_unproven: false,
80 }
81 }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub struct InvitationOptions {
87 pub valid_for: Duration,
90 pub uses: u32,
92}
93
94impl Default for InvitationOptions {
95 fn default() -> Self {
96 Self {
97 valid_for: Duration::from_secs(24 * 3600),
98 uses: 1,
99 }
100 }
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub struct WaitingEntry {
106 pub id: PeerId,
108 pub source: Option<SocketAddr>,
110}
111
112#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
115pub struct InvitationId([u8; 32]);
116
117impl InvitationId {
118 pub fn of(secret: &[u8; 32]) -> Self {
120 Self(Sha256::digest(secret).into())
121 }
122
123 pub fn hex(&self) -> String {
125 HEXLOWER.encode(&self.0)
126 }
127}
128
129impl fmt::Display for InvitationId {
130 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
131 formatter.write_str(&self.hex())
132 }
133}
134
135impl fmt::Debug for InvitationId {
136 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137 write!(formatter, "InvitationId({})", self.hex())
138 }
139}
140
141impl FromStr for InvitationId {
142 type Err = Error;
143
144 fn from_str(text: &str) -> Result<Self, Error> {
146 let text = text.trim();
147 let mut bytes = [0u8; 32];
148 if text.len() != 64 {
149 return Err(Error::InvalidId);
150 }
151 HEXLOWER_PERMISSIVE
152 .decode_mut(text.as_bytes(), &mut bytes)
153 .map_err(|_| Error::InvalidId)?;
154 Ok(Self(bytes))
155 }
156}
157
158#[derive(Clone, PartialEq, Eq)]
164pub struct Invitation {
165 pub secret: [u8; 32],
167 pub expires: SystemTime,
169 pub uses: u32,
172 pub label: String,
174}
175
176impl Invitation {
177 pub fn id(&self) -> InvitationId {
179 InvitationId::of(&self.secret)
180 }
181}
182
183impl Drop for Invitation {
184 fn drop(&mut self) {
185 zeroize::Zeroize::zeroize(&mut self.secret);
186 }
187}
188
189impl fmt::Debug for Invitation {
190 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
191 formatter
192 .debug_struct("Invitation")
193 .field("id", &self.id())
194 .field("expires", &self.expires)
195 .field("uses", &self.uses)
196 .field("label", &self.label)
197 .finish_non_exhaustive()
198 }
199}
200
201#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct InvitationEntry {
204 pub id: InvitationId,
206 pub expires: SystemTime,
208 pub uses: u32,
210 pub label: String,
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub struct Successor {
218 pub old: PeerId,
220 pub new: PeerId,
222 pub proven: Option<SystemTime>,
224}
225
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub struct Retiring {
229 pub id: PeerId,
231 pub successor: Option<PeerId>,
233 pub retires: SystemTime,
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
239#[non_exhaustive]
240pub enum RotationEvent {
241 Announced {
243 old: PeerId,
245 new: PeerId,
247 },
248 Promoted {
250 old: PeerId,
252 new: PeerId,
254 retires: SystemTime,
256 },
257}
258
259#[derive(Debug, Clone)]
319pub struct TrustStore {
320 root: PathBuf,
321 waiting: Arc<Mutex<WaitingQueue>>,
322 events: Arc<Mutex<VecDeque<RotationEvent>>>,
323 clock: Clock,
324 rotation: RotationOptions,
325}
326
327struct Entry {
329 key: KeyMaterial,
330 source: Option<SocketAddr>,
331 successor: Option<PeerId>,
332 retires: Option<u64>,
333 predecessor: Option<PeerId>,
334 proven: Option<u64>,
335}
336
337impl TrustStore {
338 pub fn open(state_dir: &Path) -> Result<Self, Error> {
344 let root = state_dir.join("peers");
345 fs::create_dir_all(root.join("accepted")).map_err(Error::Io)?;
346 fs::create_dir_all(root.join("waiting")).map_err(Error::Io)?;
347 Ok(Self {
348 root,
349 waiting: Arc::new(Mutex::new(WaitingQueue::new(WaitingLimits::default()))),
350 events: Arc::default(),
351 clock: Clock::system(),
352 rotation: RotationOptions::default(),
353 })
354 }
355
356 #[must_use]
359 pub fn with_limits(mut self, limits: WaitingLimits) -> Self {
360 let prefix = self.queue().ipv6_prefix();
361 self.waiting = Arc::new(Mutex::new(
362 WaitingQueue::new(limits).with_ipv6_prefix(prefix),
363 ));
364 self
365 }
366
367 #[must_use]
372 pub fn with_ipv6_prefix(mut self, bits: u8) -> Self {
373 let limits = self.queue().limits();
374 self.waiting = Arc::new(Mutex::new(WaitingQueue::new(limits).with_ipv6_prefix(bits)));
375 self
376 }
377
378 fn queue(&self) -> std::sync::MutexGuard<'_, WaitingQueue> {
380 self.waiting.lock().unwrap_or_else(PoisonError::into_inner)
381 }
382
383 #[must_use]
386 pub fn with_clock(mut self, clock: Clock) -> Self {
387 self.clock = clock;
388 self
389 }
390
391 #[must_use]
393 pub fn with_rotation(mut self, options: RotationOptions) -> Self {
394 self.rotation = options;
395 self
396 }
397
398 pub fn rotation(&self) -> RotationOptions {
400 self.rotation
401 }
402
403 pub fn clock(&self) -> &Clock {
405 &self.clock
406 }
407
408 pub fn waiting(&self) -> Result<Vec<WaitingEntry>, Error> {
415 Ok(self
416 .list("waiting")?
417 .into_iter()
418 .map(|id| WaitingEntry {
419 id,
420 source: self.read("waiting", &id).and_then(|entry| entry.source),
421 })
422 .collect())
423 }
424
425 pub fn accepted(&self) -> Result<Vec<PeerId>, Error> {
431 Ok(self
432 .list("accepted")?
433 .into_iter()
434 .filter(|id| self.current(id).is_some())
435 .collect())
436 }
437
438 pub fn accepted_key(&self, id: &PeerId) -> Option<KeyMaterial> {
441 self.current(id).map(|entry| entry.key)
442 }
443
444 pub fn waiting_key(&self, id: &PeerId) -> Option<KeyMaterial> {
446 self.read("waiting", id).map(|entry| entry.key)
447 }
448
449 pub fn accept(&self, id: &PeerId) -> Result<(), Error> {
456 if self.is_accepted(id) {
457 return Err(Error::AlreadyAccepted);
458 }
459 let path = self.existing("waiting", id).ok_or(Error::NotWaiting)?;
460 let text = fs::read_to_string(&path).map_err(|error| {
461 if error.kind() == io::ErrorKind::NotFound {
462 Error::NotWaiting
463 } else {
464 Error::Io(error)
465 }
466 })?;
467 let entry = parse(&text).ok_or(Error::Material)?;
468 if entry.key.id() != *id {
469 return Err(Error::Material);
470 }
471 self.write_current(&entry.key)?;
472 let _ = fs::remove_file(path);
473 Ok(())
474 }
475
476 pub fn accept_key(&self, key: &KeyMaterial) -> Result<PeerId, Error> {
484 key.check()?;
485 let id = key.id();
486 self.write_current(key)?;
487 let _ = fs::remove_file(self.path("waiting", &id));
488 Ok(id)
489 }
490
491 pub fn remove(&self, id: &PeerId) -> Result<bool, Error> {
498 let mut removed = false;
499 if let Some(successor) = self.read("accepted", id).and_then(|entry| entry.successor)
500 && self
501 .read("successors", &successor)
502 .is_some_and(|entry| entry.predecessor == Some(*id))
503 {
504 fs::remove_file(self.path("successors", &successor)).map_err(Error::Io)?;
505 }
506 for section in ["accepted", "waiting", "successors"] {
507 if let Some(path) = self.existing(section, id) {
508 fs::remove_file(path).map_err(Error::Io)?;
509 removed = true;
510 }
511 }
512 Ok(removed)
513 }
514
515 pub fn is_accepted(&self, id: &PeerId) -> bool {
518 self.current(id).is_some()
519 }
520
521 pub fn record_waiting(&self, key: &KeyMaterial, source: Option<SocketAddr>) {
535 if key.check().is_err() {
536 return;
537 }
538 let id = key.id();
539 if self.existing("waiting", &id).is_some() {
540 return;
541 }
542 let Ok(stored) = self.list("waiting") else {
543 return;
544 };
545 let now = Instant::now();
546 let mut queue = self.queue();
547 queue.prune(now, |had| stored.binary_search(had).is_ok());
549 let admission = queue.admit(id, source, stored.len(), now);
550 if !admission.record {
551 return;
552 }
553 for old in &admission.evict {
554 let _ = fs::remove_file(self.path("waiting", old));
555 }
556 let mut text = source.map_or_else(String::new, |s| format!("Source: {s}\n"));
557 text.push_str(&format!("Method: {}\n", key.method));
558 text.push_str(&pem::encode(&key.label, &key.bytes));
559 let _ = write_new(&self.path("waiting", &id), &text);
560 }
561
562 pub fn invite(
570 &self,
571 random: &Random,
572 options: InvitationOptions,
573 label: &str,
574 ) -> Result<Invitation, Error> {
575 let label_ok = label.len() <= MAX_LABEL
576 && label.trim() == label
577 && !label.chars().any(char::is_control);
578 if !label_ok || options.uses == 0 || options.valid_for.is_zero() {
579 return Err(Error::InvalidOptions);
580 }
581 let mut secret = [0u8; 32];
582 random.fill(&mut secret)?;
583 let expires = from_unix_seconds(
584 unix_seconds(self.clock.now()).saturating_add(options.valid_for.as_secs()),
585 );
586 let invitation = Invitation {
587 secret,
588 expires,
589 uses: options.uses,
590 label: label.to_owned(),
591 };
592 fs::create_dir_all(self.root.join("invitations")).map_err(Error::Io)?;
593 write_new(
594 &self.invitation_path(&invitation.id()),
595 &invitation_text(expires, options.uses, label),
596 )
597 .map_err(Error::Io)?;
598 Ok(invitation)
599 }
600
601 pub fn redeem(&self, secret: &[u8; 32]) -> Result<Invitation, Error> {
612 let path = self.invitation_path(&InvitationId::of(secret));
613 let claimed = file::temporary_path(&path);
614 if let Err(error) = fs::rename(&path, &claimed) {
616 return Err(if error.kind() == io::ErrorKind::NotFound {
617 Error::NotInvited
618 } else {
619 Error::Io(error)
620 });
621 }
622 let text = fs::read_to_string(&claimed).ok();
623 if file::retried(|| fs::remove_file(&claimed)).is_err() {
627 return Err(Error::NotInvited);
628 }
629 let (expires, uses, label) = text
630 .as_deref()
631 .and_then(parse_invitation)
632 .ok_or(Error::NotInvited)?;
633 let revoked = self.revoked_path(&InvitationId::of(secret));
634 if revoked.exists() {
635 return Err(Error::NotInvited);
636 }
637 if self.clock.now() >= from_unix_seconds(expires) {
638 return Err(Error::Expired);
639 }
640 let left = uses - 1;
641 if left > 0 {
642 let _ = write_new(
644 &path,
645 &invitation_text(from_unix_seconds(expires), left, &label),
646 );
647 if revoked.exists() {
650 let _ = fs::remove_file(&path);
651 return Err(Error::NotInvited);
652 }
653 }
654 Ok(Invitation {
655 secret: *secret,
656 expires: from_unix_seconds(expires),
657 uses: left,
658 label,
659 })
660 }
661
662 pub fn invitations(&self) -> Result<Vec<InvitationEntry>, Error> {
668 let directory = self.root.join("invitations");
669 let entries = match fs::read_dir(&directory) {
670 Ok(entries) => entries,
671 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
672 Err(error) => return Err(Error::Io(error)),
673 };
674 let mut found = Vec::new();
675 for entry in entries {
676 let path = entry.map_err(Error::Io)?.path();
677 let Some(id) = path
678 .extension()
679 .filter(|extension| *extension == "inv")
680 .and_then(|_| path.file_stem())
681 .and_then(|stem| stem.to_str())
682 .filter(|stem| is_hex_name(stem))
683 .and_then(|stem| stem.parse::<InvitationId>().ok())
684 else {
685 continue;
686 };
687 if let Some((expires, uses, label)) = fs::read_to_string(&path)
688 .ok()
689 .as_deref()
690 .and_then(parse_invitation)
691 {
692 found.push(InvitationEntry {
693 id,
694 expires: from_unix_seconds(expires),
695 uses,
696 label,
697 });
698 }
699 }
700 found.sort_by_key(|entry| entry.id);
701 Ok(found)
702 }
703
704 pub fn revoke_invitation(&self, id: &InvitationId) -> Result<bool, Error> {
712 fs::create_dir_all(self.root.join("invitations")).map_err(Error::Io)?;
713 OpenOptions::new()
714 .create(true)
715 .truncate(false)
716 .write(true)
717 .open(self.revoked_path(id))
718 .map_err(Error::Io)?;
719 match file::retried(|| fs::remove_file(self.invitation_path(id))) {
720 Ok(()) => Ok(true),
721 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
722 Err(error) => Err(Error::Io(error)),
723 }
724 }
725
726 pub fn announce_successor(&self, old: &PeerId, new: &KeyMaterial) -> Result<(), Error> {
737 new.check()?;
738 let new_id = new.id();
739 if new_id == *old {
740 return Err(Error::Material);
741 }
742 let entry = self
743 .current(old)
744 .filter(|entry| entry.retires.is_none())
745 .ok_or(Error::NotAccepted)?;
746 if self.existing("accepted", &new_id).is_some() {
747 return Err(Error::AlreadyAccepted);
748 }
749 if self.successor_key(&new_id).is_some()
752 && self
753 .read("successors", &new_id)
754 .and_then(|pending| pending.predecessor)
755 .is_some_and(|predecessor| predecessor != *old)
756 {
757 return Err(Error::SuccessorTaken);
758 }
759 if let Some(previous) = entry.successor
760 && previous != new_id
761 && self
762 .read("successors", &previous)
763 .is_some_and(|pending| pending.predecessor == Some(*old))
764 {
765 let _ = fs::remove_file(self.path("successors", &previous));
766 }
767 fs::create_dir_all(self.root.join("successors")).map_err(Error::Io)?;
768 let text = format!(
769 "Predecessor: {}\nMethod: {}\n{}",
770 old.hex(),
771 new.method,
772 pem::encode(&new.label, &new.bytes)
773 );
774 replace(&self.path("successors", &new_id), &text).map_err(Error::Io)?;
775 let path = self.existing("accepted", old).ok_or(Error::NotAccepted)?;
776 replace(&path, &accepted_text(&entry.key, Some(&new_id), None)).map_err(Error::Io)?;
777 self.push_event(RotationEvent::Announced {
778 old: *old,
779 new: new_id,
780 });
781 Ok(())
782 }
783
784 pub fn successor_key(&self, new: &PeerId) -> Option<KeyMaterial> {
787 let pending = self.read("successors", new)?;
788 let old = pending.predecessor?;
789 self.current(&old)
790 .filter(|entry| entry.retires.is_none() && entry.successor == Some(*new))
791 .map(|_| pending.key)
792 }
793
794 pub fn prove_successor(&self, new: &PeerId) -> Result<(), Error> {
803 let key = self.successor_key(new).ok_or(Error::NoSuccessor)?;
804 let pending = self.read("successors", new).ok_or(Error::NoSuccessor)?;
805 if pending.proven.is_some() {
806 return Ok(());
807 }
808 let old = pending.predecessor.ok_or(Error::NoSuccessor)?;
809 let text = format!(
810 "Predecessor: {}
811Method: {}
812Proven: {}
813{}",
814 old.hex(),
815 key.method,
816 unix_seconds(self.clock.now()),
817 pem::encode(&key.label, &key.bytes)
818 );
819 replace(&self.path("successors", new), &text).map_err(Error::Io)
820 }
821
822 pub fn promote_successor(&self, new: &PeerId) -> Result<PeerId, Error> {
833 let key = self.successor_key(new).ok_or(Error::NoSuccessor)?;
834 if !self.rotation.allow_unproven
835 && self
836 .read("successors", new)
837 .is_none_or(|pending| pending.proven.is_none())
838 {
839 return Err(Error::NotProven);
840 }
841 let old = self
842 .read("successors", new)
843 .and_then(|entry| entry.predecessor)
844 .ok_or(Error::NoSuccessor)?;
845 let old_entry = self.current(&old).ok_or(Error::NoSuccessor)?;
846 match self.write_accepted(&key) {
847 Ok(()) | Err(Error::AlreadyAccepted) => {}
848 Err(error) => return Err(error),
849 }
850 let retires =
851 unix_seconds(self.clock.now()).saturating_add(self.rotation.retire_after.as_secs());
852 let path = self.existing("accepted", &old).ok_or(Error::NoSuccessor)?;
853 replace(
854 &path,
855 &accepted_text(&old_entry.key, Some(new), Some(retires)),
856 )
857 .map_err(Error::Io)?;
858 let _ = fs::remove_file(self.path("successors", new));
859 self.push_event(RotationEvent::Promoted {
860 old,
861 new: *new,
862 retires: from_unix_seconds(retires),
863 });
864 Ok(old)
865 }
866
867 pub fn successors(&self) -> Result<Vec<Successor>, Error> {
873 Ok(self
874 .list("successors")?
875 .into_iter()
876 .filter(|new| self.successor_key(new).is_some())
877 .filter_map(|new| {
878 let pending = self.read("successors", &new)?;
879 Some(Successor {
880 old: pending.predecessor?,
881 new,
882 proven: pending.proven.map(from_unix_seconds),
883 })
884 })
885 .collect())
886 }
887
888 pub fn retiring(&self) -> Result<Vec<Retiring>, Error> {
894 Ok(self
895 .list("accepted")?
896 .into_iter()
897 .filter_map(|id| {
898 let entry = self.read("accepted", &id)?;
899 Some(Retiring {
900 id,
901 successor: entry.successor,
902 retires: from_unix_seconds(entry.retires?),
903 })
904 })
905 .collect())
906 }
907
908 pub fn take_rotation_events(&self) -> Vec<RotationEvent> {
912 self.events
913 .lock()
914 .unwrap_or_else(PoisonError::into_inner)
915 .drain(..)
916 .collect()
917 }
918
919 fn push_event(&self, event: RotationEvent) {
920 let mut events = self.events.lock().unwrap_or_else(PoisonError::into_inner);
921 if events.len() >= MAX_EVENTS {
922 events.pop_front();
923 }
924 events.push_back(event);
925 }
926
927 fn write_current(&self, key: &KeyMaterial) -> Result<(), Error> {
929 if self.is_accepted(&key.id()) {
930 return Err(Error::AlreadyAccepted);
931 }
932 match self.existing("accepted", &key.id()) {
933 Some(path) => replace(&path, &accepted_text(key, None, None)).map_err(Error::Io),
934 None => self.write_accepted(key),
935 }
936 }
937
938 fn write_accepted(&self, key: &KeyMaterial) -> Result<(), Error> {
939 match write_new(
940 &self.path("accepted", &key.id()),
941 &accepted_text(key, None, None),
942 ) {
943 Ok(()) => Ok(()),
944 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
945 Err(Error::AlreadyAccepted)
946 }
947 Err(error) => Err(Error::Io(error)),
948 }
949 }
950
951 fn current(&self, id: &PeerId) -> Option<Entry> {
953 let entry = self.read("accepted", id)?;
954 match entry.retires {
955 Some(retires) if self.clock.now() >= from_unix_seconds(retires) => None,
956 _ => Some(entry),
957 }
958 }
959
960 fn read(&self, section: &str, id: &PeerId) -> Option<Entry> {
962 let text = fs::read_to_string(self.existing(section, id)?).ok()?;
963 parse(&text).filter(|entry| entry.key.id() == *id)
964 }
965
966 fn list(&self, section: &str) -> Result<Vec<PeerId>, Error> {
967 let entries = match fs::read_dir(self.root.join(section)) {
968 Ok(entries) => entries,
969 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
970 Err(error) => return Err(Error::Io(error)),
971 };
972 let mut ids = Vec::new();
973 for entry in entries {
974 let path = entry.map_err(Error::Io)?.path();
975 if path.extension().is_some_and(|extension| extension == "pem")
976 && let Some(Ok(id)) = path
977 .file_stem()
978 .and_then(|stem| stem.to_str())
979 .filter(|stem| is_hex_name(stem))
980 .map(str::parse::<PeerId>)
981 && !ids.contains(&id)
982 {
983 ids.push(id);
984 }
985 }
986 ids.sort();
987 Ok(ids)
988 }
989
990 fn path(&self, section: &str, id: &PeerId) -> PathBuf {
991 self.root.join(section).join(format!("{}.pem", id.hex()))
992 }
993
994 fn revoked_path(&self, id: &InvitationId) -> PathBuf {
995 self.root
996 .join("invitations")
997 .join(format!("{}.revoked", id.hex()))
998 }
999
1000 fn invitation_path(&self, id: &InvitationId) -> PathBuf {
1001 self.root
1002 .join("invitations")
1003 .join(format!("{}.inv", id.hex()))
1004 }
1005
1006 fn existing(&self, section: &str, id: &PeerId) -> Option<PathBuf> {
1008 let path = self.path(section, id);
1009 path.is_file().then_some(path)
1010 }
1011}
1012
1013fn is_hex_name(stem: &str) -> bool {
1015 stem.len() == 64 && HEXLOWER.decode_mut(stem.as_bytes(), &mut [0u8; 32]).is_ok()
1016}
1017
1018pub(crate) fn source_key(address: IpAddr, prefix: u8) -> IpAddr {
1021 match address {
1022 IpAddr::V4(_) => address,
1023 IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
1024 Some(v4) => IpAddr::V4(v4),
1025 None => {
1026 let mask = u128::MAX
1027 .checked_shl(128 - u32::from(prefix.min(128)))
1028 .unwrap_or(0);
1029 IpAddr::V6(Ipv6Addr::from(u128::from(v6) & mask))
1030 }
1031 },
1032 }
1033}
1034
1035fn accepted_text(key: &KeyMaterial, successor: Option<&PeerId>, retires: Option<u64>) -> String {
1037 let mut text = format!("Method: {}\n", key.method);
1038 if let Some(successor) = successor {
1039 text.push_str(&format!("Successor: {}\n", successor.hex()));
1040 }
1041 if let Some(retires) = retires {
1042 text.push_str(&format!("Retires: {retires}\n"));
1043 }
1044 text.push_str(&pem::encode(&key.label, &key.bytes));
1045 text
1046}
1047
1048fn invitation_text(expires: SystemTime, uses: u32, label: &str) -> String {
1049 let mut text = format!("Expires: {}\nUses: {uses}\n", unix_seconds(expires));
1050 if !label.is_empty() {
1051 text.push_str(&format!("Label: {label}\n"));
1052 }
1053 text
1054}
1055
1056fn parse_invitation(text: &str) -> Option<(u64, u32, String)> {
1059 let (mut expires, mut uses, mut label) = (None, None, String::new());
1060 for line in text.lines() {
1061 if let Some(value) = line.strip_prefix("Expires: ") {
1062 expires = value.trim().parse().ok();
1063 } else if let Some(value) = line.strip_prefix("Uses: ") {
1064 uses = value.trim().parse::<u32>().ok().filter(|uses| *uses > 0);
1065 } else if let Some(value) = line.strip_prefix("Label: ") {
1066 value.trim().clone_into(&mut label);
1067 }
1068 }
1069 Some((expires?, uses?, label))
1070}
1071
1072fn parse(text: &str) -> Option<Entry> {
1074 let pem::Block {
1075 headers,
1076 label,
1077 bytes,
1078 ..
1079 } = pem::decode(text)?;
1080 let mut method = None;
1081 let (mut source, mut successor, mut retires) = (None, None, None);
1082 let (mut predecessor, mut proven) = (None, None);
1083 for line in headers {
1084 if let Some(value) = line.strip_prefix("Method: ") {
1085 method = Some(value.trim());
1086 } else if let Some(value) = line.strip_prefix("Source: ") {
1087 source = value.trim().parse().ok();
1088 } else if let Some(value) = line.strip_prefix("Successor: ") {
1089 successor = Some(value.trim().parse().ok()?);
1090 } else if let Some(value) = line.strip_prefix("Retires: ") {
1091 retires = Some(value.trim().parse().ok()?);
1092 } else if let Some(value) = line.strip_prefix("Predecessor: ") {
1093 predecessor = Some(value.trim().parse().ok()?);
1094 } else if let Some(value) = line.strip_prefix("Proven: ") {
1095 proven = Some(value.trim().parse().ok()?);
1096 }
1097 }
1098 Some(Entry {
1099 key: KeyMaterial::new(method?, label, bytes).ok()?,
1100 source,
1101 successor,
1102 retires,
1103 predecessor,
1104 proven,
1105 })
1106}
1107
1108fn write_new(path: &Path, text: &str) -> io::Result<()> {
1110 file::write_new(path, text.as_bytes(), Access::Default)
1111}
1112
1113fn replace(path: &Path, text: &str) -> io::Result<()> {
1115 file::replace(path, text.as_bytes(), Access::Default)
1116}