Skip to main content

tor_netdoc/doc/netstatus/rs/
each_flavor.rs

1//! router status entries - items that vary by consensus flavor
2//!
3//! **This file is reincluded multiple times**,
4//! by the macros in [`crate::doc::ns_variety_definition_macros`],
5//! once for votes, and once for each consensus flavour.
6//! It is *not* a module `crate::doc::netstatus::rs::each_flavor`.
7//!
8//! Each time this file is included by one of the macros mentioned above,
9//! the `ns_***` macros (such as `ns_const_name!`) may expand to different values.
10//!
11//! See [`crate::doc::ns_variety_definition_macros`].
12
13use super::*;
14use void::ResultVoidExt as _;
15
16impl RouterStatus {
17    /// Return an iterator of ORPort addresses for this routerstatus
18    pub fn addrs(&self) -> impl Iterator<Item = net::SocketAddr> {
19        chain!(
20            [std::net::SocketAddrV4::new(self.r.ip, self.r.or_port).into()],
21            self.a.iter().copied(),
22        )
23    }
24    /// Return the declared bandwidth of this routerstatus in the directory.
25    pub fn bandwidth(&self) -> &RelayBandwidth {
26        &self.w.effective
27    }
28    /// Return the declared bandwidth of this routerstatus in the directory.
29    #[deprecated = "use .bandwidth()"]
30    pub fn weight(&self) -> &RelayBandwidth {
31        self.bandwidth()
32    }
33    /// Return the protovers that this routerstatus says it implements.
34    pub fn protovers(&self) -> &Protocols {
35        &self.protos
36    }
37    /// Return the nickname of this routerstatus.
38    pub fn nickname(&self) -> &str {
39        self.r.nickname.as_str()
40    }
41    /// Return the relay flags of this routerstatus.
42    pub fn flags(&self) -> &RelayFlags {
43        &self.flags.known
44    }
45    /// Return the version of this routerstatus.
46    pub fn version(&self) -> Option<&crate::doc::netstatus::rs::SoftwareVersion> {
47        self.version.as_ref()
48    }
49    /// Return true if the ed25519 identity on this relay reflects a
50    /// true consensus among the authorities.
51    pub fn ed25519_id_is_usable(&self) -> bool {
52        !self.flags.contains(RelayFlag::NoEdConsensus)
53    }
54    /// Return true if this routerstatus is listed with the BadExit flag.
55    pub fn is_flagged_bad_exit(&self) -> bool {
56        self.flags.contains(RelayFlag::BadExit)
57    }
58    /// Return true if this routerstatus is listed with the v2dir flag.
59    pub fn is_flagged_v2dir(&self) -> bool {
60        self.flags.contains(RelayFlag::V2Dir)
61    }
62    /// Return true if this routerstatus is listed with the Exit flag.
63    pub fn is_flagged_exit(&self) -> bool {
64        self.flags.contains(RelayFlag::Exit)
65    }
66    /// Return true if this routerstatus is listed with the Guard flag.
67    pub fn is_flagged_guard(&self) -> bool {
68        self.flags.contains(RelayFlag::Guard)
69    }
70    /// Return true if this routerstatus is listed with the HSDir flag.
71    pub fn is_flagged_hsdir(&self) -> bool {
72        self.flags.contains(RelayFlag::HSDir)
73    }
74    /// Return true if this routerstatus is listed with the Stable flag.
75    pub fn is_flagged_stable(&self) -> bool {
76        self.flags.contains(RelayFlag::Stable)
77    }
78    /// Return true if this routerstatus is listed with the Fast flag.
79    pub fn is_flagged_fast(&self) -> bool {
80        self.flags.contains(RelayFlag::Fast)
81    }
82    /// Return true if this routerstatus is listed with the MiddleOnly flag.
83    pub fn is_flagged_middle_only(&self) -> bool {
84        self.flags.contains(RelayFlag::MiddleOnly)
85    }
86}
87
88impl RouterStatus {
89    /// Return RSA identity for the relay described by this RouterStatus
90    pub fn rsa_identity(&self) -> &RsaIdentity {
91        &self.r.identity
92    }
93
94    /// Return the networkstatus consensus flavor in which this
95    /// routerstatus appears.
96    pub(crate) fn flavor() -> ConsensusFlavor {
97        FLAVOR
98    }
99
100    /// Parse a generic routerstatus from a section.
101    ///
102    /// Requires that the section obeys the right SectionRules,
103    /// matching `consensus_flavor`.
104    pub(crate) fn from_section(sec: &Section<'_, NetstatusKwd>) -> Result<RouterStatus> {
105        use NetstatusKwd::*;
106        // R line
107        let r_item = sec.required(RS_R)?;
108        let nickname = r_item
109            .required_arg(0)?
110            .parse()
111            .map_err(|e: InvalidNickname| {
112                EK::BadArgument.with_msg(e.to_string()).at_pos(r_item.pos())
113            })?;
114        let ident = r_item.required_arg(1)?;
115        let identity = ident.parse::<Base64Fingerprint>()?;
116        // Fields to skip in the "r" line.
117        let n_skip = match FLAVOR {
118            ConsensusFlavor::Microdesc => 0,
119            ConsensusFlavor::Plain => 1,
120        };
121        // We check that the published time is well-formed, but we never use it
122        // for anything in a consensus document.
123        let _ignore_published: time::SystemTime = {
124            // TODO: It's annoying to have to do this allocation, since we
125            // already have a slice that contains both of these arguments.
126            // Instead, we could get a slice of arguments: we'd have to add
127            // a feature for that.
128            let mut p = r_item.required_arg(2 + n_skip)?.to_string();
129            p.push(' ');
130            p.push_str(r_item.required_arg(3 + n_skip)?);
131            p.parse::<Iso8601TimeSp>()?.into()
132        };
133        let ip = r_item.required_arg(4 + n_skip)?.parse::<net::Ipv4Addr>()?;
134        let or_port = r_item.required_arg(5 + n_skip)?.parse::<u16>()?;
135        let _ = r_item.required_arg(6 + n_skip)?.parse::<u16>()?;
136
137        // main address and A lines.
138        let a_items = sec.slice(RS_A);
139        let a = a_items
140            .iter()
141            .map(|a_item| Ok(a_item.required_arg(0)?.parse::<net::SocketAddr>()?))
142            .collect::<Result<Vec<_>>>()?;
143
144        // S line
145        //
146        // Wrong for votes, but this code doesn't run for votes.
147        let flags = DocRelayFlags::from_item_consensus(sec.required(RS_S)?)?;
148
149        // V line
150        let version = sec
151            .maybe(RS_V)
152            .args_as_str()
153            .map(str::parse)
154            .transpose()
155            .void_unwrap();
156
157        // PR line
158        let protos = {
159            let tok = sec.required(RS_PR)?;
160            Protocols::from_str_c_compatible(tok.args_as_str())
161                .map_err(|e| EK::BadArgument.at_pos(tok.pos()).with_source(e))?
162        };
163
164        // W line
165        let weight = sec
166            .get(RS_W)
167            .map(RelayBandwidthItem::from_item)
168            .transpose()?
169            .unwrap_or_else(RelayBandwidthItem::new_no_info);
170
171        // No p line
172        // no ID line
173
174        // Try to find the document digest.  This is in different
175        // places depending on the kind of consensus we're in.
176        let doc_digest: DocDigest = match FLAVOR {
177            ConsensusFlavor::Microdesc => {
178                // M line
179                let m_item = sec.required(RS_M)?;
180                DocDigest::decode(m_item.required_arg(0)?)?
181            }
182            ConsensusFlavor::Plain => DocDigest::decode(r_item.required_arg(2)?)?,
183        };
184
185        ns_choose! { (
186            let r_doc_digest = doc_digest;
187            let m_doc_digest = NotPresent;
188        ) (
189            let r_doc_digest = NotPresent;
190            let m_doc_digest = doc_digest;
191        ) (
192            let r_doc_digest = doc_digest;
193            let m_doc_digest = NotPresent;
194        ) };
195
196        #[allow(clippy::useless_conversion)] // sometimes doc_digest needs into
197        Ok(RouterStatus {
198            r: RouterStatusIntroItem {
199                nickname,
200                identity,
201                or_port,
202                doc_digest: r_doc_digest.into(),
203                publication: IgnoredPublicationTimeSp,
204                ip,
205                dir_port: 0,
206                __non_exhaustive: (),
207            },
208            m: m_doc_digest.into(),
209            a,
210            flags,
211            version,
212            protos,
213            w: weight,
214            port_policy: ns_expr!(None, NotPresent, Void {}),
215            ed25519_id: NotPresent,
216            stats: NotPresent,
217            __non_exhaustive: (),
218        })
219    }
220}
221
222impl FromRsString for DocDigest {
223    fn decode(s: &str) -> Result<DocDigest> {
224        s.parse::<B64>()?
225            .check_len(DOC_DIGEST_LEN..=DOC_DIGEST_LEN)?
226            .as_bytes()
227            .try_into()
228            .map_err(|_| Error::from(internal!("correct length on digest, but unable to convert")))
229    }
230}