tor_netdoc/types/relay_flags.rs
1//! Relay flags (aka Router Status Flags), eg in network status documents
2
3use std::collections::HashSet;
4use std::fmt::Debug;
5use std::marker::PhantomData;
6use std::str::FromStr;
7
8use enumset::{EnumSet, EnumSetType, enum_set};
9use thiserror::Error;
10
11use tor_error::internal;
12
13use super::Unknown;
14
15/// Raw bits value for [`RelayFlags`]
16pub type RelayFlagsBits = u16;
17
18/// Router flags (aka relay flags), including, maybe, unknown ones
19///
20/// ### PartialEq implementation
21///
22/// `DocRelayFlags` implements `PartialEq`.
23///
24/// Two `DocRelayFlags` which both omit unknown flags (ie, contain `Unknown::Discarded`)
25/// are treated as equal if they contain the same set of *known* flags.
26/// This makes sense, because applications (like clients) that discard flags during netdoc
27/// parsing *want* to completely ignore unknown flags, and want to have a working comparison
28/// function for relay flags (eg to tell if two relays are similar enough).
29///
30/// Two `RelayFlags` only *one* of which retained unknown flags are treated as unequal.
31/// Such a comparison is probably a bug, but panicking would be worse.
32///
33/// ### `FromIterator`
34///
35/// With `feature = "retain-unknown"`, a
36/// a `DocRelayFlags` can be assembled from an iterator of `DocRelayFlag`.
37/// The inputs flags are then deduplicated, and no ordering checks are done.
38///
39/// So the `FromIterator` impl should not be used for parsing.
40#[derive(Debug, Clone, derive_more::Deref, PartialEq)]
41#[non_exhaustive]
42pub struct DocRelayFlags {
43 /// Known flags
44 ///
45 /// Invariant: contains no unknown set bits.
46 #[deref]
47 pub known: RelayFlags,
48
49 /// Unknown flags, if they were parsed
50 ///
51 /// Not sorted.
52 ///
53 /// It is a semantic error to include known flags here.
54 /// The parsing routines will not do so.
55 pub unknown: Unknown<HashSet<String>>,
56}
57
58/// Additional options for the representation of relay flags in network documents
59///
60/// This is a generic argument to `ParserEncoder`
61/// (and will be used for the encoder too).
62pub trait ReprMode: Debug + Copy {
63 /// Flags that should be treated as being present when parsing
64 ///
65 /// Ie, they should be inferred even if they aren't actually listed in the document.
66 ///
67 /// But, when encoding, they should still be emitted.
68 const PARSE_IMPLICIT: RelayFlags;
69
70 /// Flags that should be treated as being present, and won't even be encoded.
71 ///
72 /// These are inferred when parsing, and omitted when encoding.
73 ///
74 /// (During parsing `ENCODE_OMIT` and `PARSE_IMPLICIT` flags are treated the same.)
75 //
76 // TODO if setting this to nonzero, ensure it's actually tested.
77 const ENCODE_OMIT: RelayFlags;
78}
79
80/// How relay flags are represented in `s` in a consensus
81#[derive(Debug, Copy, Clone)]
82#[allow(clippy::exhaustive_structs)]
83pub struct ConsensusRepr;
84
85impl ReprMode for ConsensusRepr {
86 const PARSE_IMPLICIT: RelayFlags = enum_set!(RelayFlag::Running | RelayFlag::Valid);
87 const ENCODE_OMIT: RelayFlags = RelayFlags::empty();
88}
89
90/// How relay flags are represented in `s` in a vote and a `known-flags` line
91#[derive(Debug, Copy, Clone)]
92#[allow(clippy::exhaustive_structs)]
93pub struct NoImplicitRepr;
94
95impl ReprMode for NoImplicitRepr {
96 const PARSE_IMPLICIT: RelayFlags = RelayFlags::empty();
97 const ENCODE_OMIT: RelayFlags = RelayFlags::empty();
98}
99
100/// Set of (known) router status flags
101///
102/// Set of [`RelayFlag`], in a cheap and compact representation.
103///
104/// Can contain only flags known to this implementation.
105/// This is a newtype around a machine integer.
106///
107/// Does not implement `ItemValueParseable`. Parsing (and encoding) is different in
108/// different documents. Use an appropriate parameterised [`ParserEncoder`],
109/// in `#[deftly(netdoc(with))]`.
110///
111/// To also maybe handle unknown flags, use [`DocRelayFlags`].
112///
113/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:s>
114pub type RelayFlags = EnumSet<RelayFlag>;
115
116/// Router status flags - one recognized directory flag on a single relay.
117///
118/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:s>
119///
120/// These flags come from a consensus directory document, and are
121/// used to describe what the authorities believe about the relay.
122/// If the document contained any flags that we _didn't_ recognize,
123/// they are not listed in this type.
124///
125/// TODO SPEC: Make the terminology the same everywhere.
126#[derive(Debug, strum::Display, strum::EnumString, strum::IntoStaticStr, EnumSetType)] //
127#[derive(Hash, Ord, PartialOrd)]
128#[enumset(repr = "u16")] // Must be the same as RelayFlagBits
129#[non_exhaustive]
130pub enum RelayFlag {
131 /// Is this a directory authority?
132 Authority,
133 /// Is this relay marked as a bad exit?
134 ///
135 /// Bad exits can be used as intermediate relays, but not to
136 /// deliver traffic.
137 BadExit,
138 /// Is this relay marked as an exit for weighting purposes?
139 Exit,
140 /// Is this relay considered "fast" above a certain threshold?
141 Fast,
142 /// Is this relay suitable for use as a guard relay?
143 ///
144 /// Clients choose their their initial relays from among the set
145 /// of Guard relays.
146 Guard,
147 /// Does this relay participate on the onion service directory
148 /// ring?
149 HSDir,
150 /// Set if this relay is considered "middle only", not suitable to run
151 /// as an exit or guard relay.
152 ///
153 /// Note that this flag is only used by authorities as part of
154 /// the voting process; clients do not and should not act
155 /// based on whether it is set.
156 MiddleOnly,
157 /// If set, there is no consensus for the ed25519 key for this relay.
158 NoEdConsensus,
159 /// Is this relay considered "stable" enough for long-lived circuits?
160 Stable,
161 /// Set if the authorities are requesting a fresh descriptor for
162 /// this relay.
163 StaleDesc,
164 /// Set if this relay is currently running.
165 ///
166 /// This flag can appear in votes, but in consensuses, every relay
167 /// is assumed to be running.
168 Running,
169 /// Set if this relay is considered "valid" -- allowed to be on
170 /// the network.
171 ///
172 /// This flag can appear in votes, but in consensuses, every relay
173 /// is assumed to be valid.
174 Valid,
175 /// Set if this relay supports a currently recognized version of the
176 /// directory protocol.
177 V2Dir,
178}
179
180/// Parsing helper for a relay flags line (eg `s` item in a routerdesc)
181///
182#[derive(Debug, Clone)]
183pub struct ParserEncoder<'s, M: ReprMode> {
184 /// Flags so far, including the implied ones
185 flags: DocRelayFlags,
186
187 /// The previous argument, if any
188 ///
189 /// Used only for checking that the arguments are sorted, as per the spec.
190 prev: Option<&'s str>,
191
192 /// The mode, which is just a type token
193 repr_mode: PhantomData<M>,
194}
195
196/// Problem parsing a relay flags line
197#[derive(Error, Debug, Clone)]
198#[non_exhaustive]
199pub enum RelayFlagsParseError {
200 /// Flags were not in lexical order by flag name
201 #[error("Flags out of order")]
202 OutOfOrder,
203}
204
205impl DocRelayFlags {
206 /// Create a new `DocRelayFlags` with no known flags and no information about unknown flags
207 pub fn new_empty_unknown_discarded() -> Self {
208 DocRelayFlags {
209 known: RelayFlags::default(),
210 unknown: Unknown::new_discard(),
211 }
212 }
213}
214
215impl<'s, M: ReprMode> ParserEncoder<'s, M> {
216 /// Start parsing relay flags
217 ///
218 /// If `PARSE_IMPLICIT` or `ENCODE_OMIT` contains unknown bits, compile will fail.
219 pub fn new(unknown: Unknown<()>) -> Self {
220 let known = M::PARSE_IMPLICIT | M::ENCODE_OMIT;
221 ParserEncoder {
222 flags: DocRelayFlags {
223 known,
224 unknown: unknown.map(|()| HashSet::new()),
225 },
226 prev: None,
227 repr_mode: PhantomData,
228 }
229 }
230 /// Parse the next relay flag argument
231 pub fn add(&mut self, arg: &'s str) -> Result<(), RelayFlagsParseError> {
232 if let Some(prev) = self.prev {
233 if prev >= arg {
234 // Arguments out of order.
235 return Err(RelayFlagsParseError::OutOfOrder);
236 }
237 }
238 match RelayFlag::from_str(arg) {
239 Ok(fl) => self.flags.known |= fl,
240 Err(_) => self.flags.unknown.with_mut_unknown(|u| {
241 u.insert(arg.to_string());
242 }),
243 }
244
245 self.prev = Some(arg);
246 Ok(())
247 }
248 /// Finish parsing relay flags
249 pub fn finish(self) -> DocRelayFlags {
250 self.flags
251 }
252}
253
254/// Old parser impl
255mod parse_impl {
256 use super::*;
257 use crate::doc::netstatus::NetstatusKwd;
258 use crate::parse::tokenize::Item;
259 use crate::{Error, NetdocErrorKind as EK, Result};
260
261 impl DocRelayFlags {
262 /// Parse a relay-flags entry from an "s" line.
263 pub(crate) fn from_item_consensus(item: &Item<'_, NetstatusKwd>) -> Result<DocRelayFlags> {
264 if item.kwd() != NetstatusKwd::RS_S {
265 return Err(
266 Error::from(internal!("Wrong keyword {:?} for S line", item.kwd()))
267 .at_pos(item.pos()),
268 );
269 }
270 let mut flags = ParserEncoder::<ConsensusRepr>::new(Unknown::new_discard());
271
272 for s in item.args() {
273 flags
274 .add(s)
275 .map_err(|msg| EK::BadArgument.at_pos(item.pos()).with_msg(msg.to_string()))?;
276 }
277
278 Ok(flags.finish())
279 }
280 }
281}
282
283/// New parser impl
284mod parse2_impl {
285 use super::*;
286
287 use crate::parse2::{self, ErrorProblem as EP};
288 use {
289 crate::encode::ItemEncoder, itertools::chain, std::collections::BTreeSet, tor_error::Bug,
290 };
291
292 impl<'s, M: ReprMode> ParserEncoder<'s, M> {
293 /// Parse relay flags
294 #[allow(clippy::needless_pass_by_value)] // we must match trait signature
295 pub(crate) fn from_unparsed(item: parse2::UnparsedItem<'_>) -> Result<DocRelayFlags, EP> {
296 item.check_no_object()?;
297 let mut flags = Self::new(item.parse_options().retain_unknown_values);
298 for arg in item.args_copy() {
299 flags
300 .add(arg)
301 .map_err(item.invalid_argument_handler("flags"))?;
302 }
303 Ok(flags.finish())
304 }
305
306 /// Encode relay flags
307 #[allow(clippy::unnecessary_wraps)] // we must match trait signature
308 #[allow(clippy::redundant_closure)] // rust-clippy/issues#14215 |f| <&'static str>::from(f)
309 pub(crate) fn write_item_value_onto(
310 flags: &DocRelayFlags,
311 mut out: ItemEncoder,
312 ) -> Result<(), Bug> {
313 let set = chain!(
314 flags
315 .known
316 .iter()
317 .filter(|f| !M::ENCODE_OMIT.contains(*f))
318 .map(|f| <&'static str>::from(f)),
319 flags
320 .unknown
321 .as_ref()
322 .only_known()
323 .map(|u| u.iter())
324 .into_iter()
325 .flatten()
326 .map(|s: &String| &**s),
327 )
328 .collect::<BTreeSet<&'_ str>>();
329
330 for f in set {
331 out = out.arg(&f);
332 }
333 Ok(())
334 }
335 }
336}
337
338#[cfg(feature = "retain-unknown")]
339pub use doc_relay_flag::*;
340/// One relay flag that might be known or unknown, iterators, accessors
341#[cfg(feature = "retain-unknown")]
342mod doc_relay_flag {
343 use super::*;
344 use itertools::chain;
345 use std::borrow::{Borrow, Cow};
346 use tor_error::Bug;
347
348 /// One relay flag, known or unknown
349 #[derive(Debug, Clone, Eq, PartialEq, Hash)]
350 #[allow(clippy::exhaustive_enums)] // there are only these two possibilities
351 pub enum DocRelayFlag<'s> {
352 /// Known relay flag (normally found as a bit in [`RelayFlags`])
353 Known(RelayFlag),
354
355 /// Unknown relay flag (stored as strings in [`DocRelayFlags`]).
356 ///
357 /// It is a semantic error to represent a known flag here; see [`DocRelayFlags`].
358 /// A `DocRelayFlag` from a correct `DocRelayFlags` (eg from the parsing routines)
359 /// will not do so.
360 Unknown(Cow<'s, str>),
361 }
362
363 impl<'s> DocRelayFlag<'s> {
364 /// Un-borrow, yielding a `DocRelayFlag<'static>`
365 pub fn into_static(self) -> DocRelayFlag<'static> {
366 match self {
367 DocRelayFlag::Known(f) => DocRelayFlag::Known(f),
368 DocRelayFlag::Unknown(s) => DocRelayFlag::Unknown(s.into_owned().into()),
369 }
370 }
371 }
372
373 impl DocRelayFlags {
374 /// Returns an iterator over all the flags, known and unknown
375 ///
376 /// Throws `Bug` if the `DocRelayFlags` has `Unknown::Discarded`.
377 ///
378 /// Contrast `RelayFlags::iter()` (available on `DocRelayFlags` via `Deref`)
379 /// which yields only the known flags.
380 pub fn iter_incl_unknown(&self) -> Result<impl Iterator<Item = DocRelayFlag<'_>>, Bug> {
381 let unknown = self.unknown.as_ref().into_retained()?;
382 Ok(chain! {
383 self.known.iter().map(DocRelayFlag::Known),
384 unknown.iter().map(|s| DocRelayFlag::Unknown(s.into())),
385 })
386 }
387
388 /// Does this `DocRelayFlags` contain this flag?
389 ///
390 /// Throws `Bug` if the `DocRelayFlags` has `Unknown::Discarded`.
391 ///
392 /// Contrast `RelayFlags::iter()` (available on `DocRelayFlags` via `Deref`)
393 /// checks if a `RelayFlag` (a known flag) is included.
394 pub fn contains_incl_unknown(&self, flag: &DocRelayFlag<'_>) -> Result<bool, Bug> {
395 Ok(match flag {
396 DocRelayFlag::Known(k) => self.known.contains(*k),
397 DocRelayFlag::Unknown(k) => self
398 .unknown
399 .as_ref()
400 .into_retained()?
401 .contains::<str>(k.borrow()),
402 })
403 }
404 }
405
406 impl<'s> FromIterator<DocRelayFlag<'s>> for DocRelayFlags {
407 fn from_iter<I: IntoIterator<Item = DocRelayFlag<'s>>>(input: I) -> Self {
408 let mut known = RelayFlags::new();
409 let mut unknown = HashSet::new();
410 for i in input {
411 match i {
412 DocRelayFlag::Known(f) => known.insert(f),
413 DocRelayFlag::Unknown(f) => unknown.insert(String::from(f)),
414 };
415 }
416 DocRelayFlags {
417 known,
418 unknown: Unknown::Retained(unknown),
419 }
420 }
421 }
422}