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")]
7
pub(crate) mod build;
8
pub(crate) mod md;
9
pub(crate) mod plain;
10
pub(crate) mod vote;
11

            
12
use super::{
13
    ConsensusFlavor, ConsensusMethod, ConsensusMethods, consensus_methods_comma_separated,
14
};
15
use crate::doc::netstatus::{
16
    IgnoredPublicationTimeSp, NetstatusKwd, ParamValues, Protocols, RelayBandwidth,
17
    RelayBandwidthItem, VoteRelayBandwidthItem,
18
};
19
use crate::encode::{EncodeOrd, ItemEncoder};
20
use crate::parse::parser::Section;
21
use crate::parse2::ItemArgumentParseable;
22
use crate::types::misc::*;
23
use crate::types::policy::PortPolicy;
24
use crate::types::relay_flags::{self, DocRelayFlags, RelayFlag, RelayFlags};
25
use crate::types::version::TorVersion;
26
use crate::{Error, NetdocErrorKind as EK, Result};
27
use derive_deftly::Deftly;
28
use itertools::{Itertools, chain};
29
use std::cmp::Ordering;
30
use std::result::Result as StdResult;
31
use std::{net, time};
32
use tor_basic_utils::intern::{Intern, InternCache};
33
use tor_error::{Bug, internal};
34
use 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]
43
pub 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.
60
static 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)]
80
pub 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

            
95
impl 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
45580
    pub fn iter_cross_product_digests(
104
45580
        items: &[Self],
105
45580
    ) -> impl Iterator<Item = (ConsensusMethod, IdentifiedDigest)> {
106
46096
        items.iter().flat_map(|item| {
107
1376
            Itertools::cartesian_product(
108
1376
                item.consensus_methods.iter().copied(),
109
1376
                item.digests.iter().cloned(),
110
1376
            )
111
1376
        })
112
45580
    }
113
}
114

            
115
impl 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
590514
    fn from_str(s: &str) -> StdResult<Self, void::Void> {
122
590514
        let mut elts = s.splitn(3, ' ');
123
590514
        if elts.next() == Some("Tor") {
124
590512
            if let Some(Ok(v)) = elts.next().map(str::parse) {
125
590512
                return Ok(SoftwareVersion::CTor(v));
126
            }
127
2
        }
128

            
129
2
        Ok(SoftwareVersion::Other(OTHER_VERSION_CACHE.intern_ref(s)))
130
590514
    }
131
}
132

            
133
/// Helper to decode a document digest in the format in which it
134
/// appears in a given kind of routerstatus.
135
trait 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.
148
mod 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
590475
    pub(super) fn from_unparsed(item: UnparsedItem<'_>) -> Result<Protocols, ErrorProblem> {
160
590475
        item.check_no_object()?;
161
590475
        Protocols::from_str_c_compatible(item.args_copy().into_remaining())
162
590475
            .map_err(item.invalid_argument_handler("protocols"))
163
590475
    }
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
67
    pub(super) fn write_item_value_onto(
170
67
        protocols: &Protocols,
171
67
        out: ItemEncoder,
172
67
    ) -> Result<(), Bug> {
173
67
        protocols.write_item_value_onto(out)
174
67
    }
175
}