Skip to main content

tor_netdoc/doc/netstatus/
rs.rs

1//! Routerstatus-specific parts of networkstatus parsing.
2//!
3//! This is a private module; relevant pieces are re-exported by its
4//! parent.
5
6#[cfg(feature = "build_docs")]
7pub(crate) mod build;
8pub(crate) mod md;
9pub(crate) mod plain;
10pub(crate) mod vote;
11
12use super::{
13    ConsensusFlavor, ConsensusMethod, ConsensusMethods, consensus_methods_comma_separated,
14};
15use crate::doc::netstatus::{
16    IgnoredPublicationTimeSp, NetstatusKwd, ParamValues, Protocols, RelayBandwidth,
17    RelayBandwidthItem, VoteRelayBandwidthItem,
18};
19use crate::encode::{EncodeOrd, ItemEncoder};
20use crate::parse::parser::Section;
21use crate::parse2::ItemArgumentParseable;
22use crate::types::misc::*;
23use crate::types::policy::PortPolicy;
24use crate::types::relay_flags::{self, DocRelayFlags, RelayFlag, RelayFlags};
25use crate::types::version::TorVersion;
26use crate::{Error, NetdocErrorKind as EK, Result};
27use derive_deftly::Deftly;
28use itertools::{Itertools, chain};
29use std::cmp::Ordering;
30use std::result::Result as StdResult;
31use std::{net, time};
32use tor_basic_utils::intern::{Intern, InternCache};
33use tor_error::{Bug, internal};
34use tor_llcrypto::pk::rsa::RsaIdentity;
35
36/// A version as presented in a router status.
37///
38/// This can either be a parsed Tor version, or an unparsed string.
39//
40// TODO: This might want to merge, at some point, with routerdesc::RelayPlatform.
41#[derive(Clone, Debug, Eq, PartialEq, Hash, derive_more::Display)]
42#[non_exhaustive]
43pub enum SoftwareVersion {
44    /// A Tor version
45    #[display("Tor {_0}")]
46    CTor(TorVersion),
47
48    /// A string we couldn't parse.
49    ///
50    /// This may be a C tor version that we couldn't parse,
51    /// or some other software.
52    Other(Intern<str>),
53}
54
55/// A cache of unparsable version strings.
56///
57/// We use this because we expect there not to be very many distinct versions of
58/// relay software in existence.
59// TODO DIRAUTH: Improve the caching here.
60static OTHER_VERSION_CACHE: InternCache<str> = InternCache::new();
61
62/// `m` item in votes
63///
64/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:m>
65///
66/// This is different to the `m` line in microdesc consensuses.
67/// Plain consensuses don't have `m` lines at all.
68///
69/// ### Non-invariants
70///
71///  * There may be overlapping or even contradictory information.
72///  * It might not be sorted.
73///    Users of the structure who need to emit reproducible document encodings.
74///    must sort it.
75///  * These non-invariants apply both within one instance of this struct,
76///    and across multiple instances of it within a `RouterStatus`.
77#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Deftly)]
78#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
79#[allow(clippy::exhaustive_structs)]
80pub struct RouterStatusMdDigestsVote {
81    /// The methods for which this document is applicable.
82    #[deftly(netdoc(with = consensus_methods_comma_separated))]
83    #[deftly(constructor)]
84    pub consensus_methods: ConsensusMethods,
85
86    /// The various hashes of this document.
87    #[deftly(constructor)]
88    pub digests: Vec<IdentifiedDigest>,
89
90    #[doc(hidden)]
91    #[deftly(netdoc(skip))]
92    pub __non_exhaustive: (),
93}
94
95impl RouterStatusMdDigestsVote {
96    /// Yields every `(method, digests)` pair from the `m` items in a vote
97    ///
98    /// ### Performance / security
99    ///
100    /// This iterator can yield many more elements than the vote's textual size,
101    /// and could allocate a string for each one.
102    /// There is a risk of DoS if used on untrusted input.
103    pub fn iter_cross_product_digests(
104        items: &[Self],
105    ) -> impl Iterator<Item = (ConsensusMethod, IdentifiedDigest)> {
106        items.iter().flat_map(|item| {
107            Itertools::cartesian_product(
108                item.consensus_methods.iter().copied(),
109                item.digests.iter().cloned(),
110            )
111        })
112    }
113}
114
115impl std::str::FromStr for SoftwareVersion {
116    // This needs to stay infallible: if any version is unparsable,
117    // then we may reject a consensus needlessly,
118    // since authorities copy versions from what relays say.
119    type Err = void::Void;
120
121    fn from_str(s: &str) -> StdResult<Self, void::Void> {
122        let mut elts = s.splitn(3, ' ');
123        if elts.next() == Some("Tor") {
124            if let Some(Ok(v)) = elts.next().map(str::parse) {
125                return Ok(SoftwareVersion::CTor(v));
126            }
127        }
128
129        Ok(SoftwareVersion::Other(OTHER_VERSION_CACHE.intern_ref(s)))
130    }
131}
132
133/// Helper to decode a document digest in the format in which it
134/// appears in a given kind of routerstatus.
135trait FromRsString: Sized {
136    /// Try to decode the given object.
137    fn decode(s: &str) -> Result<Self>;
138}
139
140/// Implementation for parsing [`tor_protover::Protocols`] via its
141/// [`from_str_c_compatible`](tor_protover::Protocols::from_str_c_compatible)
142/// method.
143///
144/// We use this (for now) for parsing routerstatuses _and nothing else_.
145/// It's okay to be strict about router descriptors and required/recommended versions,
146/// but if we are strict about these lines in a routerstatus, we run the risk of rejecting
147/// stuff that the C tor authorities thought was okay.
148mod protovers_flexible {
149    use tor_error::Bug;
150    use tor_protover::Protocols;
151
152    use crate::{
153        encode::{ItemEncoder, ItemValueEncodable as _},
154        parse2::{ErrorProblem, UnparsedItem},
155    };
156
157    /// Parse a [`Protocols`] using [`Protocols::from_str_c_compatible`].
158    #[expect(clippy::needless_pass_by_value)]
159    pub(super) fn from_unparsed(item: UnparsedItem<'_>) -> Result<Protocols, ErrorProblem> {
160        item.check_no_object()?;
161        Protocols::from_str_c_compatible(item.args_copy().into_remaining())
162            .map_err(item.invalid_argument_handler("protocols"))
163    }
164
165    /// Encode a [`Protocols`] in the usual manner.
166    ///
167    /// (We have to define this because there is no "parse_with", only a "with" that overrides
168    /// parsing _and_ encoding.)
169    pub(super) fn write_item_value_onto(
170        protocols: &Protocols,
171        out: ItemEncoder,
172    ) -> Result<(), Bug> {
173        protocols.write_item_value_onto(out)
174    }
175}