1mod rs;
47
48pub mod md;
49#[cfg(feature = "plain-consensus")]
50pub mod plain;
51#[cfg(feature = "ns-vote")]
52pub mod vote;
53
54#[cfg(feature = "build_docs")]
55mod build;
56
57#[cfg(feature = "parse2")]
58use {
59 crate::parse2::{self, ArgumentStream}, };
61
62#[cfg(feature = "parse2")]
63pub use {
64 parse2_impls::ProtoStatusesNetdocParseAccumulator, };
66
67use crate::doc::authcert::{AuthCert, AuthCertKeyIds};
68use crate::parse::keyword::Keyword;
69use crate::parse::parser::{Section, SectionRules, SectionRulesBuilder};
70use crate::parse::tokenize::{Item, ItemResult, NetDocReader};
71use crate::types::misc::*;
72use crate::util::PeekableIterator;
73use crate::{Error, KeywordEncodable, NetdocErrorKind as EK, NormalItemArgument, Pos, Result};
74use std::collections::{BTreeSet, HashMap, HashSet};
75use std::fmt::{self, Display};
76use std::result::Result as StdResult;
77use std::str::FromStr;
78use std::sync::Arc;
79use std::{net, result, time};
80use tor_error::{HasKind, internal};
81use tor_protover::Protocols;
82
83use derive_deftly::{Deftly, define_derive_deftly};
84use digest::Digest;
85use std::sync::LazyLock;
86use tor_checkable::{ExternallySigned, timed::TimerangeBound};
87use tor_llcrypto as ll;
88use tor_llcrypto::pk::rsa::RsaIdentity;
89
90use serde::{Deserialize, Deserializer};
91
92#[cfg(feature = "build_docs")]
93pub use build::MdConsensusBuilder;
94#[cfg(all(feature = "build_docs", feature = "plain-consensus"))]
95pub use build::PlainConsensusBuilder;
96#[cfg(feature = "build_docs")]
97ns_export_each_flavor! {
98 ty: RouterStatusBuilder;
99}
100
101ns_export_each_variety! {
102 ty: RouterStatus, Preamble;
103}
104
105#[deprecated]
106#[cfg(feature = "ns_consensus")]
107pub use PlainConsensus as NsConsensus;
108#[deprecated]
109#[cfg(feature = "ns_consensus")]
110pub use PlainRouterStatus as NsRouterStatus;
111#[deprecated]
112#[cfg(feature = "ns_consensus")]
113pub use UncheckedPlainConsensus as UncheckedNsConsensus;
114#[deprecated]
115#[cfg(feature = "ns_consensus")]
116pub use UnvalidatedPlainConsensus as UnvalidatedNsConsensus;
117
118#[cfg(feature = "ns-vote")]
119pub use rs::RouterStatusMdDigestsVote;
120
121#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Default)]
135#[allow(clippy::exhaustive_structs)]
136pub struct IgnoredPublicationTimeSp;
137
138#[derive(Clone, Debug, Deftly)]
146#[derive_deftly(Lifetime)]
147#[cfg_attr(feature = "parse2", derive_deftly(NetdocParseableFields))]
148pub struct Lifetime {
149 #[cfg_attr(feature = "parse2", deftly(netdoc(single_arg)))]
156 valid_after: Iso8601TimeSp,
157 #[cfg_attr(feature = "parse2", deftly(netdoc(single_arg)))]
165 fresh_until: Iso8601TimeSp,
166 #[cfg_attr(feature = "parse2", deftly(netdoc(single_arg)))]
174 valid_until: Iso8601TimeSp,
175}
176
177define_derive_deftly! {
178 Lifetime:
180
181 impl Lifetime {
182 pub fn new(
184 $( $fname: time::SystemTime, )
185 ) -> Result<Self> {
186 let self_ = Lifetime {
190 $( $fname: $fname.into(), )
191 };
192 if self_.valid_after < self_.fresh_until && self_.fresh_until < self_.valid_until {
193 Ok(self_)
194 } else {
195 Err(EK::InvalidLifetime.err())
196 }
197 }
198 $(
199 ${fattrs doc}
200 pub fn $fname(&self) -> time::SystemTime {
201 *self.$fname
202 }
203 )
204 pub fn valid_at(&self, when: time::SystemTime) -> bool {
206 *self.valid_after <= when && when <= *self.valid_until
207 }
208
209 pub fn voting_period(&self) -> time::Duration {
214 let valid_after = self.valid_after();
215 let fresh_until = self.fresh_until();
216 fresh_until
217 .duration_since(valid_after)
218 .expect("Mis-formed lifetime")
219 }
220 }
221}
222use derive_deftly_template_Lifetime;
223
224#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy)] #[derive(derive_more::From, derive_more::Into, derive_more::Display, derive_more::FromStr)]
236pub struct ConsensusMethod(u32);
237impl NormalItemArgument for ConsensusMethod {}
238
239#[derive(Debug, Clone, Default, Eq, PartialEq)]
246#[cfg_attr(feature = "parse2", derive(Deftly), derive_deftly(ItemValueParseable))]
247#[non_exhaustive]
248pub struct ConsensusMethods {
249 pub methods: BTreeSet<ConsensusMethod>,
251}
252
253#[cfg(feature = "parse2")]
258pub mod consensus_methods_comma_separated {
259 use super::*;
260 use parse2::ArgumentError as AE;
261 use std::result::Result;
262
263 pub fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<ConsensusMethods, AE> {
265 let mut methods = BTreeSet::new();
266 for ent in args.next().ok_or(AE::Missing)?.split(',') {
267 let ent = ent.parse().map_err(|_| AE::Invalid)?;
268 if !methods.insert(ent) {
269 return Err(AE::Invalid);
270 }
271 }
272 Ok(ConsensusMethods { methods })
273 }
274}
275
276#[derive(Debug, Clone, Default, Eq, PartialEq)]
292pub struct NetParams<T> {
293 params: HashMap<String, T>,
295}
296
297impl<T> NetParams<T> {
298 #[allow(unused)]
300 pub fn new() -> Self {
301 NetParams {
302 params: HashMap::new(),
303 }
304 }
305 pub fn get<A: AsRef<str>>(&self, v: A) -> Option<&T> {
307 self.params.get(v.as_ref())
308 }
309 pub fn iter(&self) -> impl Iterator<Item = (&String, &T)> {
311 self.params.iter()
312 }
313 pub fn set(&mut self, k: String, v: T) {
315 self.params.insert(k, v);
316 }
317}
318
319impl<K: Into<String>, T> FromIterator<(K, T)> for NetParams<T> {
320 fn from_iter<I: IntoIterator<Item = (K, T)>>(i: I) -> Self {
321 NetParams {
322 params: i.into_iter().map(|(k, v)| (k.into(), v)).collect(),
323 }
324 }
325}
326
327impl<T> std::iter::Extend<(String, T)> for NetParams<T> {
328 fn extend<I: IntoIterator<Item = (String, T)>>(&mut self, iter: I) {
329 self.params.extend(iter);
330 }
331}
332
333impl<'de, T> Deserialize<'de> for NetParams<T>
334where
335 T: Deserialize<'de>,
336{
337 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
338 where
339 D: Deserializer<'de>,
340 {
341 let params = HashMap::deserialize(deserializer)?;
342 Ok(NetParams { params })
343 }
344}
345
346#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
355pub struct ProtoStatus {
356 recommended: Protocols,
361 required: Protocols,
366}
367
368impl ProtoStatus {
369 pub fn check_protocols(
379 &self,
380 supported_protocols: &Protocols,
381 ) -> StdResult<(), ProtocolSupportError> {
382 let missing_required = self.required.difference(supported_protocols);
384 if !missing_required.is_empty() {
385 return Err(ProtocolSupportError::MissingRequired(missing_required));
386 }
387 let missing_recommended = self.recommended.difference(supported_protocols);
388 if !missing_recommended.is_empty() {
389 return Err(ProtocolSupportError::MissingRecommended(
390 missing_recommended,
391 ));
392 }
393
394 Ok(())
395 }
396}
397
398#[derive(Clone, Debug, thiserror::Error)]
400#[cfg_attr(test, derive(PartialEq))]
401#[non_exhaustive]
402pub enum ProtocolSupportError {
403 #[error("Required protocols are not implemented: {0}")]
405 MissingRequired(Protocols),
406
407 #[error("Recommended protocols are not implemented: {0}")]
411 MissingRecommended(Protocols),
412}
413
414impl ProtocolSupportError {
415 pub fn should_shutdown(&self) -> bool {
417 matches!(self, Self::MissingRequired(_))
418 }
419}
420
421impl HasKind for ProtocolSupportError {
422 fn kind(&self) -> tor_error::ErrorKind {
423 tor_error::ErrorKind::SoftwareDeprecated
424 }
425}
426
427#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
434pub struct ProtoStatuses {
435 client: ProtoStatus,
437 relay: ProtoStatus,
439}
440
441impl ProtoStatuses {
442 pub fn client(&self) -> &ProtoStatus {
444 &self.client
445 }
446
447 pub fn relay(&self) -> &ProtoStatus {
449 &self.relay
450 }
451}
452
453#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
457#[non_exhaustive]
458pub enum ConsensusFlavor {
459 Microdesc,
462 Plain,
467}
468
469impl ConsensusFlavor {
470 pub fn name(&self) -> &'static str {
472 match self {
473 ConsensusFlavor::Plain => "ns", ConsensusFlavor::Microdesc => "microdesc",
475 }
476 }
477 pub fn from_opt_name(name: Option<&str>) -> Result<Self> {
482 match name {
483 Some("microdesc") => Ok(ConsensusFlavor::Microdesc),
484 Some("ns") | None => Ok(ConsensusFlavor::Plain),
485 Some(other) => {
486 Err(EK::BadDocumentType.with_msg(format!("unrecognized flavor {:?}", other)))
487 }
488 }
489 }
490}
491
492#[derive(Debug, Clone)]
494#[non_exhaustive]
495pub struct Signature {
496 pub digestname: String,
501 pub key_ids: AuthCertKeyIds,
504 pub signature: Vec<u8>,
506}
507
508#[derive(Debug, Clone)]
510#[non_exhaustive]
511pub struct SignatureGroup {
512 pub sha256: Option<[u8; 32]>,
514 pub sha1: Option<[u8; 20]>,
516 pub signatures: Vec<Signature>,
518}
519
520#[derive(
522 Debug, Clone, Copy, Eq, PartialEq, derive_more::From, derive_more::Into, derive_more::AsRef,
523)]
524pub struct SharedRandVal([u8; 32]);
526
527#[derive(Debug, Clone, Deftly)]
530#[non_exhaustive]
531#[cfg_attr(feature = "parse2", derive_deftly(ItemValueParseable))]
532#[cfg_attr(feature = "encode", derive_deftly(ItemValueEncodable))]
533pub struct SharedRandStatus {
534 pub n_reveals: u8,
536 pub value: SharedRandVal,
543
544 pub timestamp: Option<Iso8601TimeNoSp>,
548}
549
550#[derive(Debug, Clone)]
554#[non_exhaustive]
555pub struct DirSource {
556 pub nickname: String,
558 pub identity: RsaIdentity,
564 pub ip: net::IpAddr,
566 pub dir_port: u16,
568 pub or_port: u16,
570}
571
572#[non_exhaustive]
574#[derive(Debug, Clone, Copy)]
575pub enum RelayWeight {
576 Unmeasured(u32),
578 Measured(u32),
580}
581
582impl RelayWeight {
583 pub fn is_measured(&self) -> bool {
585 matches!(self, RelayWeight::Measured(_))
586 }
587 pub fn is_nonzero(&self) -> bool {
589 !matches!(self, RelayWeight::Unmeasured(0) | RelayWeight::Measured(0))
590 }
591}
592
593#[derive(Debug, Clone)]
595#[non_exhaustive]
596pub struct ConsensusVoterInfo {
597 pub dir_source: DirSource,
599 pub contact: String,
601 pub vote_digest: Vec<u8>,
604}
605
606#[derive(Debug, Clone)]
608#[non_exhaustive]
609pub struct Footer {
610 pub weights: NetParams<i32>,
616}
617
618pub type MdConsensus = md::Consensus;
621
622pub type UnvalidatedMdConsensus = md::UnvalidatedConsensus;
625
626pub type UncheckedMdConsensus = md::UncheckedConsensus;
629
630#[cfg(feature = "plain-consensus")]
631pub type PlainConsensus = plain::Consensus;
634
635#[cfg(feature = "plain-consensus")]
636pub type UnvalidatedPlainConsensus = plain::UnvalidatedConsensus;
639
640#[cfg(feature = "plain-consensus")]
641pub type UncheckedPlainConsensus = plain::UncheckedConsensus;
644
645decl_keyword! {
646 #[non_exhaustive]
651 #[allow(missing_docs)]
652 pub NetstatusKwd {
653 "network-status-version" => NETWORK_STATUS_VERSION,
655 "vote-status" => VOTE_STATUS,
656 "consensus-methods" => CONSENSUS_METHODS,
657 "consensus-method" => CONSENSUS_METHOD,
658 "published" => PUBLISHED,
659 "valid-after" => VALID_AFTER,
660 "fresh-until" => FRESH_UNTIL,
661 "valid-until" => VALID_UNTIL,
662 "voting-delay" => VOTING_DELAY,
663 "client-versions" => CLIENT_VERSIONS,
664 "server-versions" => SERVER_VERSIONS,
665 "known-flags" => KNOWN_FLAGS,
666 "flag-thresholds" => FLAG_THRESHOLDS,
667 "recommended-client-protocols" => RECOMMENDED_CLIENT_PROTOCOLS,
668 "required-client-protocols" => REQUIRED_CLIENT_PROTOCOLS,
669 "recommended-relay-protocols" => RECOMMENDED_RELAY_PROTOCOLS,
670 "required-relay-protocols" => REQUIRED_RELAY_PROTOCOLS,
671 "params" => PARAMS,
672 "bandwidth-file-headers" => BANDWIDTH_FILE_HEADERS,
673 "bandwidth-file-digest" => BANDWIDTH_FILE_DIGEST,
674 "shared-rand-previous-value" => SHARED_RAND_PREVIOUS_VALUE,
678 "shared-rand-current-value" => SHARED_RAND_CURRENT_VALUE,
679
680 "dir-source" => DIR_SOURCE,
682 "contact" => CONTACT,
683
684 "legacy-dir-key" => LEGACY_DIR_KEY,
686 "shared-rand-participate" => SHARED_RAND_PARTICIPATE,
687 "shared-rand-commit" => SHARED_RAND_COMMIT,
688
689 "vote-digest" => VOTE_DIGEST,
691
692 "dir-key-certificate-version" => DIR_KEY_CERTIFICATE_VERSION,
694
695 "r" => RS_R,
697 "a" => RS_A,
698 "s" => RS_S,
699 "v" => RS_V,
700 "pr" => RS_PR,
701 "w" => RS_W,
702 "p" => RS_P,
703 "m" => RS_M,
704 "id" => RS_ID,
705
706 "directory-footer" => DIRECTORY_FOOTER,
708 "bandwidth-weights" => BANDWIDTH_WEIGHTS,
709 "directory-signature" => DIRECTORY_SIGNATURE,
710 }
711}
712
713static NS_HEADER_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> = LazyLock::new(|| {
715 use NetstatusKwd::*;
716 let mut rules = SectionRules::builder();
717 rules.add(NETWORK_STATUS_VERSION.rule().required().args(1..=2));
718 rules.add(VOTE_STATUS.rule().required().args(1..));
719 rules.add(VALID_AFTER.rule().required());
720 rules.add(FRESH_UNTIL.rule().required());
721 rules.add(VALID_UNTIL.rule().required());
722 rules.add(VOTING_DELAY.rule().args(2..));
723 rules.add(CLIENT_VERSIONS.rule());
724 rules.add(SERVER_VERSIONS.rule());
725 rules.add(KNOWN_FLAGS.rule().required());
726 rules.add(RECOMMENDED_CLIENT_PROTOCOLS.rule().args(1..));
727 rules.add(RECOMMENDED_RELAY_PROTOCOLS.rule().args(1..));
728 rules.add(REQUIRED_CLIENT_PROTOCOLS.rule().args(1..));
729 rules.add(REQUIRED_RELAY_PROTOCOLS.rule().args(1..));
730 rules.add(PARAMS.rule());
731 rules
732});
733static NS_HEADER_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
735 use NetstatusKwd::*;
736 let mut rules = NS_HEADER_RULES_COMMON_.clone();
737 rules.add(CONSENSUS_METHOD.rule().args(1..=1));
738 rules.add(SHARED_RAND_PREVIOUS_VALUE.rule().args(2..));
739 rules.add(SHARED_RAND_CURRENT_VALUE.rule().args(2..));
740 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
741 rules.build()
742});
743static NS_VOTERINFO_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
774 use NetstatusKwd::*;
775 let mut rules = SectionRules::builder();
776 rules.add(DIR_SOURCE.rule().required().args(6..));
777 rules.add(CONTACT.rule().required());
778 rules.add(VOTE_DIGEST.rule().required());
779 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
780 rules.build()
781});
782static NS_ROUTERSTATUS_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> =
784 LazyLock::new(|| {
785 use NetstatusKwd::*;
786 let mut rules = SectionRules::builder();
787 rules.add(RS_A.rule().may_repeat().args(1..));
788 rules.add(RS_S.rule().required());
789 rules.add(RS_V.rule());
790 rules.add(RS_PR.rule().required());
791 rules.add(RS_W.rule());
792 rules.add(RS_P.rule().args(2..));
793 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
794 rules
795 });
796
797static NS_ROUTERSTATUS_RULES_PLAIN: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
799 use NetstatusKwd::*;
800 let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
801 rules.add(RS_R.rule().required().args(8..));
802 rules.build()
803});
804
805static NS_ROUTERSTATUS_RULES_MDCON: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
818 use NetstatusKwd::*;
819 let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
820 rules.add(RS_R.rule().required().args(6..));
821 rules.add(RS_M.rule().required().args(1..));
822 rules.build()
823});
824static NS_FOOTER_RULES: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
826 use NetstatusKwd::*;
827 let mut rules = SectionRules::builder();
828 rules.add(DIRECTORY_FOOTER.rule().required().no_args());
829 rules.add(BANDWIDTH_WEIGHTS.rule());
831 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
832 rules.build()
833});
834
835impl ProtoStatus {
836 fn from_section(
838 sec: &Section<'_, NetstatusKwd>,
839 recommend_token: NetstatusKwd,
840 required_token: NetstatusKwd,
841 ) -> Result<ProtoStatus> {
842 fn parse(t: Option<&Item<'_, NetstatusKwd>>) -> Result<Protocols> {
844 if let Some(item) = t {
845 item.args_as_str()
846 .parse::<Protocols>()
847 .map_err(|e| EK::BadArgument.at_pos(item.pos()).with_source(e))
848 } else {
849 Ok(Protocols::new())
850 }
851 }
852
853 let recommended = parse(sec.get(recommend_token))?;
854 let required = parse(sec.get(required_token))?;
855 Ok(ProtoStatus {
856 recommended,
857 required,
858 })
859 }
860
861 pub fn required_protocols(&self) -> &Protocols {
868 &self.required
869 }
870
871 pub fn recommended_protocols(&self) -> &Protocols {
876 &self.recommended
877 }
878}
879
880impl<T> std::str::FromStr for NetParams<T>
881where
882 T: std::str::FromStr,
883 T::Err: std::error::Error,
884{
885 type Err = Error;
886 fn from_str(s: &str) -> Result<Self> {
887 fn parse_pair<U>(p: &str) -> Result<(String, U)>
889 where
890 U: std::str::FromStr,
891 U::Err: std::error::Error,
892 {
893 let parts: Vec<_> = p.splitn(2, '=').collect();
894 if parts.len() != 2 {
895 return Err(EK::BadArgument
896 .at_pos(Pos::at(p))
897 .with_msg("Missing = in key=value list"));
898 }
899 let num = parts[1].parse::<U>().map_err(|e| {
900 EK::BadArgument
901 .at_pos(Pos::at(parts[1]))
902 .with_msg(e.to_string())
903 })?;
904 Ok((parts[0].to_string(), num))
905 }
906
907 let params = s
908 .split(' ')
909 .filter(|p| !p.is_empty())
910 .map(parse_pair)
911 .collect::<Result<HashMap<_, _>>>()?;
912 Ok(NetParams { params })
913 }
914}
915
916impl FromStr for SharedRandVal {
917 type Err = Error;
918 fn from_str(s: &str) -> Result<Self> {
919 let val: B64 = s.parse()?;
920 let val = SharedRandVal(val.into_array()?);
921 Ok(val)
922 }
923}
924impl Display for SharedRandVal {
925 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
926 Display::fmt(&B64::from(Vec::from(self.0)), f)
927 }
928}
929impl NormalItemArgument for SharedRandVal {}
930
931impl SharedRandStatus {
932 fn from_item(item: &Item<'_, NetstatusKwd>) -> Result<Self> {
935 match item.kwd() {
936 NetstatusKwd::SHARED_RAND_PREVIOUS_VALUE | NetstatusKwd::SHARED_RAND_CURRENT_VALUE => {}
937 _ => {
938 return Err(Error::from(internal!(
939 "wrong keyword {:?} on shared-random value",
940 item.kwd()
941 ))
942 .at_pos(item.pos()));
943 }
944 }
945 let n_reveals: u8 = item.parse_arg(0)?;
946 let value: SharedRandVal = item.parse_arg(1)?;
947 let timestamp = item.parse_optional_arg::<Iso8601TimeNoSp>(2)?;
949 Ok(SharedRandStatus {
950 n_reveals,
951 value,
952 timestamp,
953 })
954 }
955
956 pub fn value(&self) -> &SharedRandVal {
958 &self.value
959 }
960
961 pub fn timestamp(&self) -> Option<std::time::SystemTime> {
963 self.timestamp.map(|t| t.0)
964 }
965}
966
967impl DirSource {
968 fn from_item(item: &Item<'_, NetstatusKwd>) -> Result<Self> {
970 if item.kwd() != NetstatusKwd::DIR_SOURCE {
971 return Err(
972 Error::from(internal!("Bad keyword {:?} on dir-source", item.kwd()))
973 .at_pos(item.pos()),
974 );
975 }
976 let nickname = item.required_arg(0)?.to_string();
977 let identity = item.parse_arg::<Fingerprint>(1)?.into();
978 let ip = item.parse_arg(3)?;
979 let dir_port = item.parse_arg(4)?;
980 let or_port = item.parse_arg(5)?;
981
982 Ok(DirSource {
983 nickname,
984 identity,
985 ip,
986 dir_port,
987 or_port,
988 })
989 }
990}
991
992impl ConsensusVoterInfo {
993 fn from_section(sec: &Section<'_, NetstatusKwd>) -> Result<ConsensusVoterInfo> {
995 use NetstatusKwd::*;
996 #[allow(clippy::unwrap_used)]
999 let first = sec.first_item().unwrap();
1000 if first.kwd() != DIR_SOURCE {
1001 return Err(Error::from(internal!(
1002 "Wrong keyword {:?} at start of voter info",
1003 first.kwd()
1004 ))
1005 .at_pos(first.pos()));
1006 }
1007 let dir_source = DirSource::from_item(sec.required(DIR_SOURCE)?)?;
1008
1009 let contact = sec.required(CONTACT)?.args_as_str().to_string();
1010
1011 let vote_digest = sec.required(VOTE_DIGEST)?.parse_arg::<B16>(0)?.into();
1012
1013 Ok(ConsensusVoterInfo {
1014 dir_source,
1015 contact,
1016 vote_digest,
1017 })
1018 }
1019}
1020
1021impl Default for RelayWeight {
1022 fn default() -> RelayWeight {
1023 RelayWeight::Unmeasured(0)
1024 }
1025}
1026
1027impl RelayWeight {
1028 fn from_item(item: &Item<'_, NetstatusKwd>) -> Result<RelayWeight> {
1030 if item.kwd() != NetstatusKwd::RS_W {
1031 return Err(
1032 Error::from(internal!("Wrong keyword {:?} on W line", item.kwd()))
1033 .at_pos(item.pos()),
1034 );
1035 }
1036
1037 let params = item.args_as_str().parse()?;
1038
1039 Self::from_net_params(¶ms).map_err(|e| e.at_pos(item.pos()))
1040 }
1041
1042 fn from_net_params(params: &NetParams<u32>) -> Result<RelayWeight> {
1046 let bw = params.params.get("Bandwidth");
1047 let unmeas = params.params.get("Unmeasured");
1048
1049 let bw = match bw {
1050 None => return Ok(RelayWeight::Unmeasured(0)),
1051 Some(b) => *b,
1052 };
1053
1054 match unmeas {
1055 None | Some(0) => Ok(RelayWeight::Measured(bw)),
1056 Some(1) => Ok(RelayWeight::Unmeasured(bw)),
1057 _ => Err(EK::BadArgument.with_msg("unmeasured value")),
1058 }
1059 }
1060}
1061
1062#[cfg(feature = "parse2")]
1066mod parse2_impls {
1067 use super::*;
1068 use parse2::ArgumentError as AE;
1069 use parse2::ErrorProblem as EP;
1070 use parse2::{ArgumentStream, ItemArgumentParseable, ItemValueParseable};
1071 use parse2::{KeywordRef, NetdocParseableFields, UnparsedItem};
1072 use paste::paste;
1073 use std::result::Result;
1074
1075 macro_rules! impl_proto_statuses { { $( $rr:ident $cr:ident; )* } => { paste! {
1089 #[derive(Deftly)]
1090 #[derive_deftly(NetdocParseableFields)]
1091 #[allow(unreachable_pub)]
1093 pub struct ProtoStatusesParseHelper {
1094 $(
1095 #[deftly(netdoc(default))]
1096 [<$rr _ $cr _protocols>]: Protocols,
1097 )*
1098 }
1099
1100 pub use ProtoStatusesParseHelperNetdocParseAccumulator
1102 as ProtoStatusesNetdocParseAccumulator;
1103
1104 impl NetdocParseableFields for ProtoStatuses {
1105 type Accumulator = ProtoStatusesNetdocParseAccumulator;
1106 fn is_item_keyword(kw: KeywordRef<'_>) -> bool {
1107 ProtoStatusesParseHelper::is_item_keyword(kw)
1108 }
1109 fn accumulate_item(
1110 acc: &mut Self::Accumulator,
1111 item: UnparsedItem<'_>,
1112 ) -> Result<(), EP> {
1113 ProtoStatusesParseHelper::accumulate_item(acc, item)
1114 }
1115 fn finish(acc: Self::Accumulator) -> Result<Self, EP> {
1116 let parse = ProtoStatusesParseHelper::finish(acc)?;
1117 let mut out = ProtoStatuses::default();
1118 $(
1119 out.$cr.$rr = parse.[< $rr _ $cr _protocols >];
1120 )*
1121 Ok(out)
1122 }
1123 }
1124 } } }
1125
1126 impl_proto_statuses! {
1127 required client;
1128 required relay;
1129 recommended client;
1130 recommended relay;
1131 }
1132
1133 impl ItemValueParseable for NetParams<i32> {
1134 fn from_unparsed(item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
1135 item.check_no_object()?;
1136 item.args_copy()
1137 .into_remaining()
1138 .parse()
1139 .map_err(item.invalid_argument_handler("parameters"))
1140 }
1141 }
1142
1143 impl ItemValueParseable for RelayWeight {
1144 fn from_unparsed(item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
1145 item.check_no_object()?;
1146 (|| {
1147 let params = item.args_copy().into_remaining().parse()?;
1148 Self::from_net_params(¶ms)
1149 })()
1150 .map_err(item.invalid_argument_handler("weights"))
1151 }
1152 }
1153
1154 impl ItemValueParseable for rs::Version {
1155 fn from_unparsed(mut item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
1156 item.check_no_object()?;
1157 item.args_mut()
1158 .into_remaining()
1159 .parse()
1160 .map_err(item.invalid_argument_handler("version"))
1161 }
1162 }
1163
1164 impl ItemArgumentParseable for IgnoredPublicationTimeSp {
1165 fn from_args(a: &mut ArgumentStream) -> Result<IgnoredPublicationTimeSp, AE> {
1166 let mut next_arg = || a.next().ok_or(AE::Missing);
1167 let _: &str = next_arg()?;
1168 let _: &str = next_arg()?;
1169 Ok(IgnoredPublicationTimeSp)
1170 }
1171 }
1172}
1173
1174impl Footer {
1175 fn from_section(sec: &Section<'_, NetstatusKwd>) -> Result<Footer> {
1177 use NetstatusKwd::*;
1178 sec.required(DIRECTORY_FOOTER)?;
1179
1180 let weights = sec
1181 .maybe(BANDWIDTH_WEIGHTS)
1182 .args_as_str()
1183 .unwrap_or("")
1184 .parse()?;
1185
1186 Ok(Footer { weights })
1187 }
1188}
1189
1190enum SigCheckResult {
1192 Valid,
1194 Invalid,
1197 MissingCert,
1200}
1201
1202impl Signature {
1203 fn from_item(item: &Item<'_, NetstatusKwd>) -> Result<Signature> {
1205 if item.kwd() != NetstatusKwd::DIRECTORY_SIGNATURE {
1206 return Err(Error::from(internal!(
1207 "Wrong keyword {:?} for directory signature",
1208 item.kwd()
1209 ))
1210 .at_pos(item.pos()));
1211 }
1212
1213 let (alg, id_fp, sk_fp) = if item.n_args() > 2 {
1214 (
1215 item.required_arg(0)?,
1216 item.required_arg(1)?,
1217 item.required_arg(2)?,
1218 )
1219 } else {
1220 ("sha1", item.required_arg(0)?, item.required_arg(1)?)
1221 };
1222
1223 let digestname = alg.to_string();
1224 let id_fingerprint = id_fp.parse::<Fingerprint>()?.into();
1225 let sk_fingerprint = sk_fp.parse::<Fingerprint>()?.into();
1226 let key_ids = AuthCertKeyIds {
1227 id_fingerprint,
1228 sk_fingerprint,
1229 };
1230 let signature = item.obj("SIGNATURE")?;
1231
1232 Ok(Signature {
1233 digestname,
1234 key_ids,
1235 signature,
1236 })
1237 }
1238
1239 fn matches_cert(&self, cert: &AuthCert) -> bool {
1242 cert.key_ids() == self.key_ids
1243 }
1244
1245 fn find_cert<'a>(&self, certs: &'a [AuthCert]) -> Option<&'a AuthCert> {
1248 certs.iter().find(|&c| self.matches_cert(c))
1249 }
1250
1251 fn check_signature(&self, signed_digest: &[u8], certs: &[AuthCert]) -> SigCheckResult {
1255 match self.find_cert(certs) {
1256 None => SigCheckResult::MissingCert,
1257 Some(cert) => {
1258 let key = cert.signing_key();
1259 match key.verify(signed_digest, &self.signature[..]) {
1260 Ok(()) => SigCheckResult::Valid,
1261 Err(_) => SigCheckResult::Invalid,
1262 }
1263 }
1264 }
1265 }
1266}
1267
1268impl SignatureGroup {
1269 fn list_missing(&self, certs: &[AuthCert]) -> (usize, Vec<&Signature>) {
1276 let mut ok: HashSet<RsaIdentity> = HashSet::new();
1277 let mut missing = Vec::new();
1278 for sig in &self.signatures {
1279 let id_fingerprint = &sig.key_ids.id_fingerprint;
1280 if ok.contains(id_fingerprint) {
1281 continue;
1282 }
1283 if sig.find_cert(certs).is_some() {
1284 ok.insert(*id_fingerprint);
1285 continue;
1286 }
1287
1288 missing.push(sig);
1289 }
1290 (ok.len(), missing)
1291 }
1292
1293 fn could_validate(&self, authorities: &[&RsaIdentity]) -> bool {
1297 let mut signed_by: HashSet<RsaIdentity> = HashSet::new();
1298 for sig in &self.signatures {
1299 let id_fp = &sig.key_ids.id_fingerprint;
1300 if signed_by.contains(id_fp) {
1301 continue;
1303 }
1304 if authorities.contains(&id_fp) {
1305 signed_by.insert(*id_fp);
1306 }
1307 }
1308
1309 signed_by.len() > (authorities.len() / 2)
1310 }
1311
1312 fn validate(&self, n_authorities: usize, certs: &[AuthCert]) -> bool {
1319 let mut ok: HashSet<RsaIdentity> = HashSet::new();
1323
1324 for sig in &self.signatures {
1325 let id_fingerprint = &sig.key_ids.id_fingerprint;
1326 if ok.contains(id_fingerprint) {
1327 continue;
1330 }
1331
1332 let d: Option<&[u8]> = match sig.digestname.as_ref() {
1333 "sha256" => self.sha256.as_ref().map(|a| &a[..]),
1334 "sha1" => self.sha1.as_ref().map(|a| &a[..]),
1335 _ => None, };
1337 if d.is_none() {
1338 continue;
1341 }
1342
1343 #[allow(clippy::unwrap_used)]
1345 match sig.check_signature(d.as_ref().unwrap(), certs) {
1346 SigCheckResult::Valid => {
1347 ok.insert(*id_fingerprint);
1348 }
1349 _ => continue,
1350 }
1351 }
1352
1353 ok.len() > (n_authorities / 2)
1354 }
1355}
1356
1357#[cfg(test)]
1358mod test {
1359 #![allow(clippy::bool_assert_comparison)]
1361 #![allow(clippy::clone_on_copy)]
1362 #![allow(clippy::dbg_macro)]
1363 #![allow(clippy::mixed_attributes_style)]
1364 #![allow(clippy::print_stderr)]
1365 #![allow(clippy::print_stdout)]
1366 #![allow(clippy::single_char_pattern)]
1367 #![allow(clippy::unwrap_used)]
1368 #![allow(clippy::unchecked_time_subtraction)]
1369 #![allow(clippy::useless_vec)]
1370 #![allow(clippy::needless_pass_by_value)]
1371 use super::*;
1373 use hex_literal::hex;
1374 #[cfg(all(feature = "ns-vote", feature = "parse2"))]
1375 use {
1376 crate::parse2::{NetdocSigned as _, ParseInput, parse_netdoc},
1377 std::fs,
1378 };
1379
1380 const CERTS: &str = include_str!("../../testdata/authcerts2.txt");
1381 const CONSENSUS: &str = include_str!("../../testdata/mdconsensus1.txt");
1382
1383 #[cfg(feature = "plain-consensus")]
1384 const PLAIN_CERTS: &str = include_str!("../../testdata2/cached-certs");
1385 #[cfg(feature = "plain-consensus")]
1386 const PLAIN_CONSENSUS: &str = include_str!("../../testdata2/cached-consensus");
1387
1388 fn read_bad(fname: &str) -> String {
1389 use std::fs;
1390 use std::path::PathBuf;
1391 let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
1392 path.push("testdata");
1393 path.push("bad-mdconsensus");
1394 path.push(fname);
1395
1396 fs::read_to_string(path).unwrap()
1397 }
1398
1399 #[test]
1400 fn parse_and_validate_md() -> Result<()> {
1401 use std::net::SocketAddr;
1402 use tor_checkable::{SelfSigned, Timebound};
1403 let mut certs = Vec::new();
1404 for cert in AuthCert::parse_multiple(CERTS)? {
1405 let cert = cert?.check_signature()?.dangerously_assume_timely();
1406 certs.push(cert);
1407 }
1408 let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
1409
1410 assert_eq!(certs.len(), 3);
1411
1412 let (_, _, consensus) = MdConsensus::parse(CONSENSUS)?;
1413 let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
1414
1415 assert!(consensus.authorities_are_correct(&auth_ids));
1417 assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
1419 {
1420 let bad_auth_id = (*b"xxxxxxxxxxxxxxxxxxxx").into();
1423 assert!(!consensus.authorities_are_correct(&[&bad_auth_id]));
1424 }
1425
1426 let missing = consensus.key_is_correct(&[]).err().unwrap();
1427 assert_eq!(3, missing.len());
1428 assert!(consensus.key_is_correct(&certs).is_ok());
1429 let missing = consensus.key_is_correct(&certs[0..1]).err().unwrap();
1430 assert_eq!(2, missing.len());
1431
1432 let same_three_times = vec![certs[0].clone(), certs[0].clone(), certs[0].clone()];
1434 let missing = consensus.key_is_correct(&same_three_times).err().unwrap();
1435
1436 assert_eq!(2, missing.len());
1437 assert!(consensus.is_well_signed(&same_three_times).is_err());
1438
1439 assert!(consensus.key_is_correct(&certs).is_ok());
1440 let consensus = consensus.check_signature(&certs)?;
1441
1442 assert_eq!(6, consensus.relays().len());
1443 let r0 = &consensus.relays()[0];
1444 assert_eq!(
1445 r0.md_digest(),
1446 &hex!("73dabe0a0468f4f7a67810a18d11e36731bb1d2ec3634db459100609f3b3f535")
1447 );
1448 assert_eq!(
1449 r0.rsa_identity().as_bytes(),
1450 &hex!("0a3057af2910415794d8ea430309d9ac5f5d524b")
1451 );
1452 assert!(!r0.weight().is_measured());
1453 assert!(!r0.weight().is_nonzero());
1454 let pv = &r0.protovers();
1455 assert!(pv.supports_subver("HSDir", 2));
1456 assert!(!pv.supports_subver("HSDir", 3));
1457 let ip4 = "127.0.0.1:5002".parse::<SocketAddr>().unwrap();
1458 let ip6 = "[::1]:5002".parse::<SocketAddr>().unwrap();
1459 assert!(r0.addrs().any(|a| a == ip4));
1460 assert!(r0.addrs().any(|a| a == ip6));
1461
1462 Ok(())
1463 }
1464
1465 #[test]
1466 #[cfg(feature = "plain-consensus")]
1467 fn parse_and_validate_ns() -> Result<()> {
1468 use tor_checkable::{SelfSigned, Timebound};
1469 let mut certs = Vec::new();
1470 for cert in AuthCert::parse_multiple(PLAIN_CERTS)? {
1471 let cert = cert?.check_signature()?.dangerously_assume_timely();
1472 certs.push(cert);
1473 }
1474 let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
1475 assert_eq!(certs.len(), 4);
1476
1477 let (_, _, consensus) = PlainConsensus::parse(PLAIN_CONSENSUS)?;
1478 let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
1479 assert!(consensus.authorities_are_correct(&auth_ids));
1481 assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
1483
1484 assert!(consensus.key_is_correct(&certs).is_ok());
1485
1486 let _consensus = consensus.check_signature(&certs)?;
1487
1488 Ok(())
1489 }
1490
1491 #[test]
1492 #[cfg(all(feature = "ns-vote", feature = "parse2"))]
1493 fn parse2_vote() -> anyhow::Result<()> {
1494 let file = "testdata2/v3-status-votes--1";
1495 let text = fs::read_to_string(file)?;
1496
1497 use crate::parse2::poc::netstatus::NetworkStatusSignedVote;
1499
1500 let input = ParseInput::new(&text, file);
1501 let doc: NetworkStatusSignedVote = parse_netdoc(&input)?;
1502
1503 println!("{doc:?}");
1504 println!("{:#?}", doc.inspect_unverified().0.r[0]);
1505
1506 Ok(())
1507 }
1508
1509 #[test]
1510 fn test_bad() {
1511 use crate::Pos;
1512 fn check(fname: &str, e: &Error) {
1513 let content = read_bad(fname);
1514 let res = MdConsensus::parse(&content);
1515 assert!(res.is_err());
1516 assert_eq!(&res.err().unwrap(), e);
1517 }
1518
1519 check(
1520 "bad-flags",
1521 &EK::BadArgument
1522 .at_pos(Pos::from_line(27, 1))
1523 .with_msg("Flags out of order"),
1524 );
1525 check(
1526 "bad-md-digest",
1527 &EK::BadArgument
1528 .at_pos(Pos::from_line(40, 3))
1529 .with_msg("Invalid base64"),
1530 );
1531 check(
1532 "bad-weight",
1533 &EK::BadArgument
1534 .at_pos(Pos::from_line(67, 141))
1535 .with_msg("invalid digit found in string"),
1536 );
1537 check(
1538 "bad-weights",
1539 &EK::BadArgument
1540 .at_pos(Pos::from_line(51, 13))
1541 .with_msg("invalid digit found in string"),
1542 );
1543 check(
1544 "wrong-order",
1545 &EK::WrongSortOrder.at_pos(Pos::from_line(52, 1)),
1546 );
1547 check(
1548 "wrong-start",
1549 &EK::UnexpectedToken
1550 .with_msg("vote-status")
1551 .at_pos(Pos::from_line(1, 1)),
1552 );
1553 check("wrong-version", &EK::BadDocumentVersion.with_msg("10"));
1554 }
1555
1556 fn gettok(s: &str) -> Result<Item<'_, NetstatusKwd>> {
1557 let mut reader = NetDocReader::new(s)?;
1558 let tok = reader.next().unwrap();
1559 assert!(reader.next().is_none());
1560 tok
1561 }
1562
1563 #[test]
1564 fn test_weight() {
1565 let w = gettok("w Unmeasured=1 Bandwidth=6\n").unwrap();
1566 let w = RelayWeight::from_item(&w).unwrap();
1567 assert!(!w.is_measured());
1568 assert!(w.is_nonzero());
1569
1570 let w = gettok("w Bandwidth=10\n").unwrap();
1571 let w = RelayWeight::from_item(&w).unwrap();
1572 assert!(w.is_measured());
1573 assert!(w.is_nonzero());
1574
1575 let w = RelayWeight::default();
1576 assert!(!w.is_measured());
1577 assert!(!w.is_nonzero());
1578
1579 let w = gettok("w Mustelid=66 Cheato=7 Unmeasured=1\n").unwrap();
1580 let w = RelayWeight::from_item(&w).unwrap();
1581 assert!(!w.is_measured());
1582 assert!(!w.is_nonzero());
1583
1584 let w = gettok("r foo\n").unwrap();
1585 let w = RelayWeight::from_item(&w);
1586 assert!(w.is_err());
1587
1588 let w = gettok("r Bandwidth=6 Unmeasured=Frog\n").unwrap();
1589 let w = RelayWeight::from_item(&w);
1590 assert!(w.is_err());
1591
1592 let w = gettok("r Bandwidth=6 Unmeasured=3\n").unwrap();
1593 let w = RelayWeight::from_item(&w);
1594 assert!(w.is_err());
1595 }
1596
1597 #[test]
1598 fn test_netparam() {
1599 let p = "Hello=600 Goodbye=5 Fred=7"
1600 .parse::<NetParams<u32>>()
1601 .unwrap();
1602 assert_eq!(p.get("Hello"), Some(&600_u32));
1603
1604 let p = "Hello=Goodbye=5 Fred=7".parse::<NetParams<u32>>();
1605 assert!(p.is_err());
1606
1607 let p = "Hello=Goodbye Fred=7".parse::<NetParams<u32>>();
1608 assert!(p.is_err());
1609 }
1610
1611 #[test]
1612 fn test_sharedrand() {
1613 let sr =
1614 gettok("shared-rand-previous-value 9 5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4\n")
1615 .unwrap();
1616 let sr = SharedRandStatus::from_item(&sr).unwrap();
1617
1618 assert_eq!(sr.n_reveals, 9);
1619 assert_eq!(
1620 sr.value.0,
1621 hex!("e4ba1d638c96c458532adc6957dc0080d03d37c7e5854087d0da90bf5ff4e72e")
1622 );
1623 assert!(sr.timestamp.is_none());
1624
1625 let sr2 = gettok(
1626 "shared-rand-current-value 9 \
1627 5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4 2022-01-20T12:34:56\n",
1628 )
1629 .unwrap();
1630 let sr2 = SharedRandStatus::from_item(&sr2).unwrap();
1631 assert_eq!(sr2.n_reveals, sr.n_reveals);
1632 assert_eq!(sr2.value.0, sr.value.0);
1633 assert_eq!(
1634 sr2.timestamp.unwrap().0,
1635 humantime::parse_rfc3339("2022-01-20T12:34:56Z").unwrap()
1636 );
1637
1638 let sr = gettok("foo bar\n").unwrap();
1639 let sr = SharedRandStatus::from_item(&sr);
1640 assert!(sr.is_err());
1641 }
1642
1643 #[test]
1644 fn test_protostatus() {
1645 let my_protocols: Protocols = "Link=7 Cons=1-5 Desc=3-10".parse().unwrap();
1646
1647 let outcome = ProtoStatus {
1648 recommended: "Link=7".parse().unwrap(),
1649 required: "Desc=5".parse().unwrap(),
1650 }
1651 .check_protocols(&my_protocols);
1652 assert!(outcome.is_ok());
1653
1654 let outcome = ProtoStatus {
1655 recommended: "Microdesc=4 Link=7".parse().unwrap(),
1656 required: "Desc=5".parse().unwrap(),
1657 }
1658 .check_protocols(&my_protocols);
1659 assert_eq!(
1660 outcome,
1661 Err(ProtocolSupportError::MissingRecommended(
1662 "Microdesc=4".parse().unwrap()
1663 ))
1664 );
1665
1666 let outcome = ProtoStatus {
1667 recommended: "Microdesc=4 Link=7".parse().unwrap(),
1668 required: "Desc=5 Cons=5-12 Wombat=15".parse().unwrap(),
1669 }
1670 .check_protocols(&my_protocols);
1671 assert_eq!(
1672 outcome,
1673 Err(ProtocolSupportError::MissingRequired(
1674 "Cons=6-12 Wombat=15".parse().unwrap()
1675 ))
1676 );
1677 }
1678
1679 #[test]
1680 fn serialize_protostatus() {
1681 let ps = ProtoStatuses {
1682 client: ProtoStatus {
1683 recommended: "Link=1-5 LinkAuth=2-5".parse().unwrap(),
1684 required: "Link=5 LinkAuth=3".parse().unwrap(),
1685 },
1686 relay: ProtoStatus {
1687 recommended: "Wombat=20-30 Knish=20-30".parse().unwrap(),
1688 required: "Wombat=20-22 Knish=25-27".parse().unwrap(),
1689 },
1690 };
1691 let json = serde_json::to_string(&ps).unwrap();
1692 let ps2 = serde_json::from_str(json.as_str()).unwrap();
1693 assert_eq!(ps, ps2);
1694
1695 let ps3: ProtoStatuses = serde_json::from_str(
1696 r#"{
1697 "client":{
1698 "required":"Link=5 LinkAuth=3",
1699 "recommended":"Link=1-5 LinkAuth=2-5"
1700 },
1701 "relay":{
1702 "required":"Wombat=20-22 Knish=25-27",
1703 "recommended":"Wombat=20-30 Knish=20-30"
1704 }
1705 }"#,
1706 )
1707 .unwrap();
1708 assert_eq!(ps, ps3);
1709 }
1710}