tor_netdoc/doc/
netstatus.rs

1//! Parsing implementation for networkstatus documents.
2//!
3//! In Tor, a networkstatus documents describes a complete view of the
4//! relays in the network: how many there are, how to contact them,
5//! and so forth.
6//!
7//! A networkstatus document can either be a "votes" -- an authority's
8//! view of the network, used as input to the voting process -- or a
9//! "consensus" -- a combined view of the network based on multiple
10//! authorities' votes, and signed by multiple authorities.
11//!
12//! A consensus document can itself come in two different flavors: a
13//! plain (unflavoured) consensus has references to router descriptors, and
14//! a "microdesc"-flavored consensus ("md") has references to
15//! microdescriptors.
16//!
17//! To keep an up-to-date view of the network, clients download
18//! microdescriptor-flavored consensuses periodically, and then
19//! download whatever microdescriptors the consensus lists that the
20//! client doesn't already have.
21//!
22//! For full information about the network status format, see
23//! [dir-spec.txt](https://spec.torproject.org/dir-spec).
24//!
25//! # Limitations
26//!
27//! NOTE: The consensus format has changes time, using a
28//! "consensus-method" mechanism.  This module is does not yet handle all
29//! all historical consensus-methods.
30//!
31//! NOTE: This module _does_ parse some fields that are not in current
32//! use, like relay nicknames, and the "published" times on
33//! microdescriptors. We should probably decide whether we actually
34//! want to do this.
35//!
36//! TODO: This module doesn't implement vote parsing at all yet.
37//!
38//! TODO: This module doesn't implement plain consensuses.
39//!
40//! TODO: More testing is needed!
41//!
42//! TODO: There should be accessor functions for most of the fields here.
43//! As with the other tor-netdoc types, I'm deferring those till I know what
44//! they should be.
45
46mod 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}, //
60};
61
62#[cfg(feature = "parse2")]
63pub use {
64    parse2_impls::ProtoStatusesNetdocParseAccumulator, //
65};
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/// `publiscation` field in routerstatus entry intro item other than in votes
122///
123/// Two arguments which are both ignored.
124/// This used to be an ISO8601 timestamp in anomalous two-argument format.
125///
126/// Nowadays, according to the spec, it can be a dummy value.
127/// So it can be a unit type.
128///
129/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:r>,
130/// except in votes which use [`Iso8601TimeSp`] instead.
131///
132/// **Not the same as** the `published` item:
133/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:published>
134#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Default)]
135#[allow(clippy::exhaustive_structs)]
136pub struct IgnoredPublicationTimeSp;
137
138/// The lifetime of a networkstatus document.
139///
140/// In a consensus, this type describes when the consensus may safely
141/// be used.  In a vote, this type describes the proposed lifetime for a
142/// consensus.
143///
144/// Aggregate of three netdoc preamble fields.
145#[derive(Clone, Debug, Deftly)]
146#[derive_deftly(Lifetime)]
147#[cfg_attr(feature = "parse2", derive_deftly(NetdocParseableFields))]
148pub struct Lifetime {
149    /// `valid-after` --- Time at which the document becomes valid
150    ///
151    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:published>
152    ///
153    /// (You might see a consensus a little while before this time,
154    /// since voting tries to finish up before the.)
155    #[cfg_attr(feature = "parse2", deftly(netdoc(single_arg)))]
156    valid_after: Iso8601TimeSp,
157    /// `fresh-until` --- Time after which there is expected to be a better version
158    /// of this consensus
159    ///
160    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:published>
161    ///
162    /// You can use the consensus after this time, but there is (or is
163    /// supposed to be) a better one by this point.
164    #[cfg_attr(feature = "parse2", deftly(netdoc(single_arg)))]
165    fresh_until: Iso8601TimeSp,
166    /// `valid-until` --- Time after which this consensus is expired.
167    ///
168    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:published>
169    ///
170    /// You should try to get a better consensus after this time,
171    /// though it's okay to keep using this one if no more recent one
172    /// can be found.
173    #[cfg_attr(feature = "parse2", deftly(netdoc(single_arg)))]
174    valid_until: Iso8601TimeSp,
175}
176
177define_derive_deftly! {
178    /// Bespoke derive for `Lifetime`, for `new` and accessors
179    Lifetime:
180
181    impl Lifetime {
182        /// Construct a new Lifetime.
183        pub fn new(
184            $( $fname: time::SystemTime, )
185        ) -> Result<Self> {
186            // Make this now because otherwise literal `valid_after` here in the body
187            // has the wrong span - the compiler refuses to look at the argument.
188            // But we can refer to the field names.
189            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        /// Return true if this consensus is officially valid at the provided time.
205        pub fn valid_at(&self, when: time::SystemTime) -> bool {
206            *self.valid_after <= when && when <= *self.valid_until
207        }
208
209        /// Return the voting period implied by this lifetime.
210        ///
211        /// (The "voting period" is the amount of time in between when a consensus first
212        /// becomes valid, and when the next consensus is expected to become valid)
213        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/// A single consensus method
225///
226/// These are integers, but we don't do arithmetic on them.
227///
228/// As defined here:
229/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:consensus-methods>
230/// <https://spec.torproject.org/dir-spec/computing-consensus.html#flavor:microdesc>
231///
232/// As used in a `consensus-method` item:
233/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:consensus-method>
234#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy)] //
235#[derive(derive_more::From, derive_more::Into, derive_more::Display, derive_more::FromStr)]
236pub struct ConsensusMethod(u32);
237impl NormalItemArgument for ConsensusMethod {}
238
239/// A set of consensus methods
240///
241/// Implements `ItemValueParseable` as required for `consensus-methods`,
242/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:consensus-methods>
243///
244/// There is also [`consensus_methods_comma_separated`] for `m` lines in votes.
245#[derive(Debug, Clone, Default, Eq, PartialEq)]
246#[cfg_attr(feature = "parse2", derive(Deftly), derive_deftly(ItemValueParseable))]
247#[non_exhaustive]
248pub struct ConsensusMethods {
249    /// Consensus methods.
250    pub methods: BTreeSet<ConsensusMethod>,
251}
252
253/// Module for use with parse2's `with`, to parse one argument of comma-separated consensus methods
254///
255/// As found in an `m` item in a vote:
256/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:m>
257#[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    /// Parse
264    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/// A set of named network parameters.
277///
278/// These are used to describe current settings for the Tor network,
279/// current weighting parameters for path selection, and so on.  They're
280/// encoded with a space-separated K=V format.
281///
282/// A `NetParams<i32>` is part of the validated directory manager configuration,
283/// where it is built (in the builder-pattern sense) from a transparent HashMap.
284///
285/// As found in `params` in a network status:
286/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:params>
287///
288/// The same syntax is also used, and this type used for parsing, in various other places,
289/// for example routerstatus entry `w` items (bandwith weights):
290/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:w>
291#[derive(Debug, Clone, Default, Eq, PartialEq)]
292pub struct NetParams<T> {
293    /// Map from keys to values.
294    params: HashMap<String, T>,
295}
296
297impl<T> NetParams<T> {
298    /// Create a new empty list of NetParams.
299    #[allow(unused)]
300    pub fn new() -> Self {
301        NetParams {
302            params: HashMap::new(),
303        }
304    }
305    /// Retrieve a given network parameter, if it is present.
306    pub fn get<A: AsRef<str>>(&self, v: A) -> Option<&T> {
307        self.params.get(v.as_ref())
308    }
309    /// Return an iterator over all key value pairs in an arbitrary order.
310    pub fn iter(&self) -> impl Iterator<Item = (&String, &T)> {
311        self.params.iter()
312    }
313    /// Set or replace the value of a network parameter.
314    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/// A list of subprotocol versions that implementors should/must provide.
347///
348/// This struct represents a pair of (optional) items:
349/// `recommended-FOO-protocols` and `required-FOO-protocols`.
350///
351/// Each consensus has two of these: one for relays, and one for clients.
352///
353/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:required-relay-protocols>
354#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
355pub struct ProtoStatus {
356    /// Set of protocols that are recommended; if we're missing a protocol
357    /// in this list we should warn the user.
358    ///
359    /// `recommended-client-protocols` or `recommended-relay-protocols`
360    recommended: Protocols,
361    /// Set of protocols that are required; if we're missing a protocol
362    /// in this list we should refuse to start.
363    ///
364    /// `required-client-protocols` or `required-relay-protocols`
365    required: Protocols,
366}
367
368impl ProtoStatus {
369    /// Check whether the list of supported protocols
370    /// is sufficient to satisfy this list of recommendations and requirements.
371    ///
372    /// If any required protocol is missing, returns [`ProtocolSupportError::MissingRequired`].
373    ///
374    /// Otherwise, if no required protocol is missing, but some recommended protocol is missing,
375    /// returns [`ProtocolSupportError::MissingRecommended`].
376    ///
377    /// Otherwise, if no recommended or required protocol is missing, returns `Ok(())`.
378    pub fn check_protocols(
379        &self,
380        supported_protocols: &Protocols,
381    ) -> StdResult<(), ProtocolSupportError> {
382        // Required protocols take precedence, so we check them first.
383        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/// A subprotocol that is recommended or required in the consensus was not present.
399#[derive(Clone, Debug, thiserror::Error)]
400#[cfg_attr(test, derive(PartialEq))]
401#[non_exhaustive]
402pub enum ProtocolSupportError {
403    /// At least one required protocol was not in our list of supported protocols.
404    #[error("Required protocols are not implemented: {0}")]
405    MissingRequired(Protocols),
406
407    /// At least one recommended protocol was not in our list of supported protocols.
408    ///
409    /// Also implies that no _required_ protocols were missing.
410    #[error("Recommended protocols are not implemented: {0}")]
411    MissingRecommended(Protocols),
412}
413
414impl ProtocolSupportError {
415    /// Return true if the suggested behavior for this error is a shutdown.
416    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/// A set of recommended and required protocols when running
428/// in various scenarios.
429///
430/// Represents the collection of four items: `{recommended,required}-{client,relay}-protocols`.
431///
432/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:required-relay-protocols>
433#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
434pub struct ProtoStatuses {
435    /// Lists of recommended and required subprotocol versions for clients
436    client: ProtoStatus,
437    /// Lists of recommended and required subprotocol versions for relays
438    relay: ProtoStatus,
439}
440
441impl ProtoStatuses {
442    /// Return the list of recommended and required protocols for running as a client.
443    pub fn client(&self) -> &ProtoStatus {
444        &self.client
445    }
446
447    /// Return the list of recommended and required protocols for running as a relay.
448    pub fn relay(&self) -> &ProtoStatus {
449        &self.relay
450    }
451}
452
453/// A recognized 'flavor' of consensus document.
454///
455/// <https://spec.torproject.org/dir-spec/computing-consensus.html#flavors>
456#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
457#[non_exhaustive]
458pub enum ConsensusFlavor {
459    /// A "microdesc"-flavored consensus.  This is the one that
460    /// clients and relays use today.
461    Microdesc,
462    /// A "networkstatus"-flavored consensus.  It's used for
463    /// historical and network-health purposes.  Instead of listing
464    /// microdescriptor digests, it lists digests of full relay
465    /// descriptors.
466    Plain,
467}
468
469impl ConsensusFlavor {
470    /// Return the name of this consensus flavor.
471    pub fn name(&self) -> &'static str {
472        match self {
473            ConsensusFlavor::Plain => "ns", // spec bug, now baked in
474            ConsensusFlavor::Microdesc => "microdesc",
475        }
476    }
477    /// Try to find the flavor whose name is `name`.
478    ///
479    /// For historical reasons, an unnamed flavor indicates an "Plain"
480    /// document.
481    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/// The signature of a single directory authority on a networkstatus document.
493#[derive(Debug, Clone)]
494#[non_exhaustive]
495pub struct Signature {
496    /// The name of the digest algorithm used to make the signature.
497    ///
498    /// Currently sha1 and sh256 are recognized.  Here we only support
499    /// sha256.
500    pub digestname: String,
501    /// Fingerprints of the keys for the authority that made
502    /// this signature.
503    pub key_ids: AuthCertKeyIds,
504    /// The signature itself.
505    pub signature: Vec<u8>,
506}
507
508/// A collection of signatures that can be checked on a networkstatus document
509#[derive(Debug, Clone)]
510#[non_exhaustive]
511pub struct SignatureGroup {
512    /// The sha256 of the document itself
513    pub sha256: Option<[u8; 32]>,
514    /// The sha1 of the document itself
515    pub sha1: Option<[u8; 20]>,
516    /// The signatures listed on the document.
517    pub signatures: Vec<Signature>,
518}
519
520/// A shared random value produced by the directory authorities.
521#[derive(
522    Debug, Clone, Copy, Eq, PartialEq, derive_more::From, derive_more::Into, derive_more::AsRef,
523)]
524// (This doesn't need to use CtByteArray; we don't really need to compare these.)
525pub struct SharedRandVal([u8; 32]);
526
527/// A shared-random value produced by the directory authorities,
528/// along with meta-information about that value.
529#[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    /// How many authorities revealed shares that contributed to this value.
535    pub n_reveals: u8,
536    /// The current random value.
537    ///
538    /// The properties of the secure shared-random system guarantee
539    /// that this value isn't predictable before it first becomes
540    /// live, and that a hostile party could not have forced it to
541    /// have any more than a small number of possible random values.
542    pub value: SharedRandVal,
543
544    /// The time when this SharedRandVal becomes (or became) the latest.
545    ///
546    /// (This is added per proposal 342, assuming that gets accepted.)
547    pub timestamp: Option<Iso8601TimeNoSp>,
548}
549
550/// Description of an authority's identity and address.
551///
552/// (Corresponds to a dir-source line.)
553#[derive(Debug, Clone)]
554#[non_exhaustive]
555pub struct DirSource {
556    /// human-readable nickname for this authority.
557    pub nickname: String,
558    /// Fingerprint for the _authority_ identity key of this
559    /// authority.
560    ///
561    /// This is the same key as the one that signs the authority's
562    /// certificates.
563    pub identity: RsaIdentity,
564    /// IP address for the authority
565    pub ip: net::IpAddr,
566    /// HTTP directory port for this authority
567    pub dir_port: u16,
568    /// OR port for this authority.
569    pub or_port: u16,
570}
571
572/// Recognized weight fields on a single relay in a consensus
573#[non_exhaustive]
574#[derive(Debug, Clone, Copy)]
575pub enum RelayWeight {
576    /// An unmeasured weight for a relay.
577    Unmeasured(u32),
578    /// An measured weight for a relay.
579    Measured(u32),
580}
581
582impl RelayWeight {
583    /// Return true if this weight is the result of a successful measurement
584    pub fn is_measured(&self) -> bool {
585        matches!(self, RelayWeight::Measured(_))
586    }
587    /// Return true if this weight is nonzero
588    pub fn is_nonzero(&self) -> bool {
589        !matches!(self, RelayWeight::Unmeasured(0) | RelayWeight::Measured(0))
590    }
591}
592
593/// All information about a single authority, as represented in a consensus
594#[derive(Debug, Clone)]
595#[non_exhaustive]
596pub struct ConsensusVoterInfo {
597    /// Contents of the dirsource line about an authority
598    pub dir_source: DirSource,
599    /// Human-readable contact information about the authority
600    pub contact: String,
601    /// Digest of the vote that the authority cast to contribute to
602    /// this consensus.
603    pub vote_digest: Vec<u8>,
604}
605
606/// The signed footer of a consensus netstatus.
607#[derive(Debug, Clone)]
608#[non_exhaustive]
609pub struct Footer {
610    /// Weights to be applied to certain classes of relays when choosing
611    /// for different roles.
612    ///
613    /// For example, we want to avoid choosing exits for non-exit
614    /// roles when overall the proportion of exits is small.
615    pub weights: NetParams<i32>,
616}
617
618/// A consensus document that lists relays along with their
619/// microdescriptor documents.
620pub type MdConsensus = md::Consensus;
621
622/// An MdConsensus that has been parsed and checked for timeliness,
623/// but not for signatures.
624pub type UnvalidatedMdConsensus = md::UnvalidatedConsensus;
625
626/// An MdConsensus that has been parsed but not checked for signatures
627/// and timeliness.
628pub type UncheckedMdConsensus = md::UncheckedConsensus;
629
630#[cfg(feature = "plain-consensus")]
631/// A consensus document that lists relays along with their
632/// router descriptor documents.
633pub type PlainConsensus = plain::Consensus;
634
635#[cfg(feature = "plain-consensus")]
636/// An PlainConsensus that has been parsed and checked for timeliness,
637/// but not for signatures.
638pub type UnvalidatedPlainConsensus = plain::UnvalidatedConsensus;
639
640#[cfg(feature = "plain-consensus")]
641/// An PlainConsensus that has been parsed but not checked for signatures
642/// and timeliness.
643pub type UncheckedPlainConsensus = plain::UncheckedConsensus;
644
645decl_keyword! {
646    /// Keywords that can be used in votes and consensuses.
647    // TODO: This is public because otherwise we can't use it in the
648    // ParseRouterStatus crate.  But I'd rather find a way to make it
649    // private.
650    #[non_exhaustive]
651    #[allow(missing_docs)]
652    pub NetstatusKwd {
653        // Header
654        "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        // "package" is now ignored.
675
676        // header in consensus, voter section in vote?
677        "shared-rand-previous-value" => SHARED_RAND_PREVIOUS_VALUE,
678        "shared-rand-current-value" => SHARED_RAND_CURRENT_VALUE,
679
680        // Voter section (both)
681        "dir-source" => DIR_SOURCE,
682        "contact" => CONTACT,
683
684        // voter section (vote, but not consensus)
685        "legacy-dir-key" => LEGACY_DIR_KEY,
686        "shared-rand-participate" => SHARED_RAND_PARTICIPATE,
687        "shared-rand-commit" => SHARED_RAND_COMMIT,
688
689        // voter section (consensus, but not vote)
690        "vote-digest" => VOTE_DIGEST,
691
692        // voter cert beginning (but only the beginning)
693        "dir-key-certificate-version" => DIR_KEY_CERTIFICATE_VERSION,
694
695        // routerstatus
696        "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        // footer
707        "directory-footer" => DIRECTORY_FOOTER,
708        "bandwidth-weights" => BANDWIDTH_WEIGHTS,
709        "directory-signature" => DIRECTORY_SIGNATURE,
710    }
711}
712
713/// Shared parts of rules for all kinds of netstatus headers
714static 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});
733/// Rules for parsing the header of a consensus.
734static 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});
743/*
744/// Rules for parsing the header of a vote.
745static NS_HEADER_RULES_VOTE: SectionRules<NetstatusKwd> = {
746    use NetstatusKwd::*;
747    let mut rules = NS_HEADER_RULES_COMMON_.clone();
748    rules.add(CONSENSUS_METHODS.rule().args(1..));
749    rules.add(FLAG_THRESHOLDS.rule());
750    rules.add(BANDWIDTH_FILE_HEADERS.rule());
751    rules.add(BANDWIDTH_FILE_DIGEST.rule().args(1..));
752    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
753    rules
754};
755/// Rules for parsing a single voter's information in a vote.
756static NS_VOTERINFO_RULES_VOTE: SectionRules<NetstatusKwd> = {
757    use NetstatusKwd::*;
758    let mut rules = SectionRules::new();
759    rules.add(DIR_SOURCE.rule().required().args(6..));
760    rules.add(CONTACT.rule().required());
761    rules.add(LEGACY_DIR_KEY.rule().args(1..));
762    rules.add(SHARED_RAND_PARTICIPATE.rule().no_args());
763    rules.add(SHARED_RAND_COMMIT.rule().may_repeat().args(4..));
764    rules.add(SHARED_RAND_PREVIOUS_VALUE.rule().args(2..));
765    rules.add(SHARED_RAND_CURRENT_VALUE.rule().args(2..));
766    // then comes an entire cert: When we implement vote parsing,
767    // we should use the authcert code for handling that.
768    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
769    rules
770};
771 */
772/// Rules for parsing a single voter's information in a consensus
773static 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});
782/// Shared rules for parsing a single routerstatus
783static 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
797/// Rules for parsing a single routerstatus in an NS consensus
798static 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
805/*
806/// Rules for parsing a single routerstatus in a vote
807static NS_ROUTERSTATUS_RULES_VOTE: SectionRules<NetstatusKwd> = {
808    use NetstatusKwd::*;
809        let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
810        rules.add(RS_R.rule().required().args(8..));
811        rules.add(RS_M.rule().may_repeat().args(2..));
812        rules.add(RS_ID.rule().may_repeat().args(2..)); // may-repeat?
813        rules
814    };
815*/
816/// Rules for parsing a single routerstatus in a microdesc consensus
817static 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});
824/// Rules for parsing consensus fields from a footer.
825static 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    // consensus only
830    rules.add(BANDWIDTH_WEIGHTS.rule());
831    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
832    rules.build()
833});
834
835impl ProtoStatus {
836    /// Construct a ProtoStatus from two chosen keywords in a section.
837    fn from_section(
838        sec: &Section<'_, NetstatusKwd>,
839        recommend_token: NetstatusKwd,
840        required_token: NetstatusKwd,
841    ) -> Result<ProtoStatus> {
842        /// Helper: extract a Protocols entry from an item's arguments.
843        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    /// Return the protocols that are listed as "required" in this `ProtoStatus`.
862    ///
863    /// Implementations may assume that relays on the network implement all the
864    /// protocols in the relays' required-protocols list.  Implementations should
865    /// refuse to start if they do not implement all the protocols on their own
866    /// (client or relay) required-protocols list.
867    pub fn required_protocols(&self) -> &Protocols {
868        &self.required
869    }
870
871    /// Return the protocols that are listed as "recommended" in this `ProtoStatus`.
872    ///
873    /// Implementations should warn if they do not implement all the protocols
874    /// on their own (client or relay) recommended-protocols list.
875    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        /// Helper: parse a single K=V pair.
888        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    /// Parse a current or previous shared rand value from a given
933    /// SharedRandPreviousValue or SharedRandCurrentValue.
934    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        // Added in proposal 342
948        let timestamp = item.parse_optional_arg::<Iso8601TimeNoSp>(2)?;
949        Ok(SharedRandStatus {
950            n_reveals,
951            value,
952            timestamp,
953        })
954    }
955
956    /// Return the actual shared random value.
957    pub fn value(&self) -> &SharedRandVal {
958        &self.value
959    }
960
961    /// Return the timestamp (if any) associated with this `SharedRandValue`.
962    pub fn timestamp(&self) -> Option<std::time::SystemTime> {
963        self.timestamp.map(|t| t.0)
964    }
965}
966
967impl DirSource {
968    /// Parse a "dir-source" item
969    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    /// Parse a single ConsensusVoterInfo from a voter info section.
994    fn from_section(sec: &Section<'_, NetstatusKwd>) -> Result<ConsensusVoterInfo> {
995        use NetstatusKwd::*;
996        // this unwrap should be safe because if there is not at least one
997        // token in the section, the section is unparsable.
998        #[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    /// Parse a routerweight from a "w" line.
1029    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(&params).map_err(|e| e.at_pos(item.pos()))
1040    }
1041
1042    /// Parse a routerweight from partially-parsed `w` line in the form of a `NetParams`
1043    ///
1044    /// This function is the common part shared between `parse2` and `parse`.
1045    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/// `parse2` impls for types in this module
1063///
1064/// Separate module to save on repeated `cfg` and for a separate namespace.
1065#[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    /// Implements `NetdocParseableFields` for `ProtoStatuses`
1076    ///
1077    /// We have this macro so that it's impossible to write things like
1078    /// ```text
1079    ///      ProtoStatuses {
1080    ///          client: ProtoStatus {
1081    ///              recommended: something something recommended_relay_versions something,
1082    /// ```
1083    ///
1084    /// (The structure of `ProtoStatuses` means the normal parse2 derive won't work for it.
1085    /// Note the bug above: the recommended *relay* version info is put in the *client* field.
1086    /// Preventing this bug must involve: avoiding writing twice the field name elements,
1087    /// such as `relay` and `client`, during this kind of construction/conversion.)
1088    macro_rules! impl_proto_statuses { { $( $rr:ident $cr:ident; )* } => { paste! {
1089        #[derive(Deftly)]
1090        #[derive_deftly(NetdocParseableFields)]
1091        // Only ProtoStatusesParseNetdocParseAccumulator is exposed.
1092        #[allow(unreachable_pub)]
1093        pub struct ProtoStatusesParseHelper {
1094            $(
1095                #[deftly(netdoc(default))]
1096                [<$rr _ $cr _protocols>]: Protocols,
1097            )*
1098        }
1099
1100        /// Partially parsed `ProtoStatuses`
1101        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(&params)
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    /// Parse a directory footer from a footer section.
1176    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
1190/// Result of checking a single authority signature.
1191enum SigCheckResult {
1192    /// The signature checks out.  Great!
1193    Valid,
1194    /// The signature is invalid; no additional information could make it
1195    /// valid.
1196    Invalid,
1197    /// We can't check the signature because we don't have a
1198    /// certificate with the right signing key.
1199    MissingCert,
1200}
1201
1202impl Signature {
1203    /// Parse a Signature from a directory-signature section
1204    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    /// Return true if this signature has the identity key and signing key
1240    /// that match a given cert.
1241    fn matches_cert(&self, cert: &AuthCert) -> bool {
1242        cert.key_ids() == self.key_ids
1243    }
1244
1245    /// If possible, find the right certificate for checking this signature
1246    /// from among a slice of certificates.
1247    fn find_cert<'a>(&self, certs: &'a [AuthCert]) -> Option<&'a AuthCert> {
1248        certs.iter().find(|&c| self.matches_cert(c))
1249    }
1250
1251    /// Try to check whether this signature is a valid signature of a
1252    /// provided digest, given a slice of certificates that might contain
1253    /// its signing key.
1254    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    // TODO: these functions are pretty similar and could probably stand to be
1270    // refactored a lot.
1271
1272    /// Helper: Return a pair of the number of possible authorities'
1273    /// signatures in this object for which we _could_ find certs, and
1274    /// a list of the signatures we couldn't find certificates for.
1275    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    /// Given a list of authority identity key fingerprints, return true if
1294    /// this signature group is _potentially_ well-signed according to those
1295    /// authorities.
1296    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                // Already found this in the list.
1302                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    /// Return true if the signature group defines a valid signature.
1313    ///
1314    /// A signature is valid if it signed by more than half of the
1315    /// authorities.  This API requires that `n_authorities` is the number of
1316    /// authorities we believe in, and that every cert in `certs` belongs
1317    /// to a real authority.
1318    fn validate(&self, n_authorities: usize, certs: &[AuthCert]) -> bool {
1319        // A set of the authorities (by identity) who have have signed
1320        // this document.  We use a set here in case `certs` has more
1321        // than one certificate for a single authority.
1322        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                // We already checked at least one signature using this
1328                // authority's identity fingerprint.
1329                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, // We don't know how to find this digest.
1336            };
1337            if d.is_none() {
1338                // We don't support this kind of digest for this kind
1339                // of document.
1340                continue;
1341            }
1342
1343            // Unwrap should be safe because of above `d.is_none()` check
1344            #[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    // @@ begin test lint list maintained by maint/add_warning @@
1360    #![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    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
1372    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        // The set of authorities we know _could_ validate this cert.
1416        assert!(consensus.authorities_are_correct(&auth_ids));
1417        // A subset would also work.
1418        assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
1419        {
1420            // If we only believe in an authority that isn't listed,
1421            // that won't work.
1422            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        // here is a trick that had better not work.
1433        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        // The set of authorities we know _could_ validate this cert.
1480        assert!(consensus.authorities_are_correct(&auth_ids));
1481        // A subset would also work.
1482        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        // TODO replace the poc struct here when we have parsing of proper whole votes
1498        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}