Skip to main content

tor_protover/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3// @@ begin lint list maintained by maint/add_warning @@
4#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6#![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![allow(clippy::cognitive_complexity)] // See arti#2556
15#![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![warn(clippy::or_fun_call)]
28#![deny(clippy::print_stderr)]
29#![deny(clippy::print_stdout)]
30#![warn(clippy::rc_buffer)]
31#![deny(clippy::ref_option_ref)]
32#![warn(clippy::semicolon_if_nothing_returned)]
33#![warn(clippy::trait_duplication_in_bounds)]
34#![deny(clippy::unchecked_time_subtraction)]
35#![deny(clippy::unnecessary_wraps)]
36#![warn(clippy::unseparated_literal_suffix)]
37#![deny(clippy::unwrap_used)]
38#![deny(clippy::mod_module_files)]
39#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40#![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44#![allow(clippy::needless_lifetimes)] // See arti#1765
45#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46#![allow(clippy::collapsible_if)] // See arti#2342
47#![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] // See arti#2571
49#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51
52#![allow(non_upper_case_globals)]
53#![allow(clippy::upper_case_acronyms)]
54// TODO: add to the list maintained by maint/add_warning once it's available on all crates
55#![warn(unnameable_types)]
56
57use caret::caret_int;
58
59use derive_deftly::Deftly;
60use itertools::chain;
61use std::borrow::Cow;
62use std::collections::BTreeMap;
63use thiserror::Error;
64use tor_basic_utils::intern::{GloballyInternable as _, Intern};
65
66pub mod named;
67pub mod value;
68pub use value::*;
69
70/// Types we export for macros.
71#[doc(hidden)]
72pub mod macro_export {
73    pub use paste;
74}
75
76caret_int! {
77    /// A subprotocol.
78    ///
79    /// These names are kept in sync with the names used in consensus
80    /// documents; the values are kept in sync with the values in the
81    /// cbor document format in the walking onions proposal.
82    ///
83    /// For the full semantics of each subprotocol, see tor-spec.txt.
84    #[derive(Hash,Ord,PartialOrd)]
85    pub struct ProtoKind(u8) {
86        /// Initiating and receiving channels, and getting cells on them.
87        Link = 0,
88        /// Different kinds of authenticate cells
89        LinkAuth = 1,
90        /// CREATE cells, CREATED cells, and the encryption that they
91        /// create.
92        Relay = 2,
93        /// Serving and fetching network directory documents.
94        DirCache = 3,
95        /// Serving onion service descriptors
96        HSDir = 4,
97        /// Providing an onion service introduction point
98        HSIntro = 5,
99        /// Providing an onion service rendezvous point
100        HSRend = 6,
101        /// Describing a relay's functionality using router descriptors.
102        Desc = 7,
103        /// Describing a relay's functionality using microdescriptors.
104        Microdesc = 8,
105        /// Describing the network as a consensus directory document.
106        Cons = 9,
107        /// Sending and accepting circuit-level padding
108        Padding = 10,
109        /// Improved means of flow control on circuits.
110        FlowCtrl = 11,
111        /// Multi-path circuit support.
112        Conflux = 12,
113    }
114}
115
116/// How many recognized protocols are there?
117const N_RECOGNIZED: usize = 13;
118
119/// A specific, named subversion of a protocol.
120#[derive(Eq, PartialEq, Copy, Clone, Debug)]
121pub struct NamedSubver {
122    /// The protocol in question
123    ///
124    /// Must be in-range for ProtoKind (0..N_RECOGNIZED).
125    kind: ProtoKind,
126    /// The version of the protocol
127    ///
128    /// Must be in 1..=MAX_VER
129    version: Value,
130}
131
132impl NamedSubver {
133    /// Create a new NamedSubver.
134    ///
135    /// # Panics
136    ///
137    /// Panics if `kind` is unrecognized.
138    const fn new(kind: ProtoKind, version: Value) -> Self {
139        assert!((kind.0 as usize) < N_RECOGNIZED);
140        Self { kind, version }
141    }
142}
143
144/// A subprotocol capability as represented by a (kind, version) tuple.
145///
146/// Does not necessarily represent a real subprotocol capability;
147/// this type is meant for use in other pieces of the protocol.
148///
149/// # Ordering
150///
151/// Instances of `NumberedSubver` are sorted in lexicographic order by
152/// their (kind, version) tuples.
153//
154// TODO: As with most other types in the crate, we should decide how to rename them as as part
155// of #1934.
156//
157// TODO ought use `Value` so as to have an invariant that version is within range?
158#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq)]
159pub struct NumberedSubver {
160    /// The protocol in question
161    kind: ProtoKind,
162    /// The version of the protocol
163    version: u8,
164}
165
166impl NumberedSubver {
167    /// Construct a new [`NumberedSubver`]
168    pub fn new(kind: impl Into<ProtoKind>, version: u8) -> Self {
169        Self {
170            kind: kind.into(),
171            version,
172        }
173    }
174    /// Return the ProtoKind and version for this [`NumberedSubver`].
175    pub fn into_parts(self) -> (ProtoKind, u8) {
176        (self.kind, self.version)
177    }
178}
179impl From<NamedSubver> for NumberedSubver {
180    fn from(value: NamedSubver) -> Self {
181        Self {
182            kind: value.kind,
183            version: value.version.into(),
184        }
185    }
186}
187
188impl From<NamedSubver> for Protocols {
189    fn from(value: NamedSubver) -> Self {
190        Self::from_iter([value])
191    }
192}
193
194#[cfg(feature = "tor-bytes")]
195impl tor_bytes::Readable for NumberedSubver {
196    fn take_from(b: &mut tor_bytes::Reader<'_>) -> tor_bytes::Result<Self> {
197        let kind = b.take_u8()?;
198        let version = b.take_u8()?;
199        Ok(Self::new(kind, version))
200    }
201}
202
203#[cfg(feature = "tor-bytes")]
204impl tor_bytes::Writeable for NumberedSubver {
205    fn write_onto<B: tor_bytes::Writer + ?Sized>(&self, b: &mut B) -> tor_bytes::EncodeResult<()> {
206        b.write_u8(self.kind.into());
207        b.write_u8(self.version);
208        Ok(())
209    }
210}
211
212/// A single recognized or unrecognized protocol.
213///
214/// This does not include the "version" part of a capability;
215/// in a capability like `Relay=7` or `Wombat=42`,
216/// this only represents the `Relay` or `Wombat` part.
217#[derive(Eq, PartialEq, Clone, Debug, Hash, Ord, PartialOrd, derive_more::Display)]
218#[display("{_0}")]
219pub struct Protocol(ProtocolInner<'static>);
220
221/// Representation for a known or unknown protocol.
222#[derive(Eq, PartialEq, Clone, Debug, Hash, Ord, PartialOrd, derive_more::Display)]
223enum ProtocolInner<'s> {
224    /// A known protocol; represented by one of ProtoKind.
225    ///
226    /// ProtoKind must always be in the range 0..N_RECOGNIZED.
227    #[display("{_0}")]
228    Proto(ProtoKind),
229    /// An unknown protocol; represented by its name.
230    ///
231    /// Invariant: is legal syntax, is not a recognized name
232    #[display("{_0}")]
233    Unrecognized(Cow<'s, str>),
234}
235
236impl Protocol {
237    /// Return true iff `s` is the name of a protocol we do not recognize.
238    fn is_unrecognized(&self, s: &str) -> bool {
239        match &self.0 {
240            ProtocolInner::Unrecognized(s2) => s2 == s,
241            _ => false,
242        }
243    }
244}
245
246impl<'s> ProtocolInner<'s> {
247    /// Borrow from a `ProtocolInner`
248    ///
249    /// Gives a new owned `ProtocolInner` which borrows from `self`.
250    fn as_ref(&self) -> ProtocolInner<'_> {
251        use ProtocolInner as PI;
252        match self {
253            PI::Proto(p) => PI::Proto(*p),
254            PI::Unrecognized(u) => PI::Unrecognized(Cow::Borrowed(u.as_ref())),
255        }
256    }
257
258    /// Make a static `ProtocolInner`
259    ///
260    /// Returns a new owned `ProtocolInner` describing the same Protocol as `self`.
261    fn into_static(self) -> ProtocolInner<'static> {
262        use ProtocolInner as PI;
263        match self {
264            PI::Proto(p) => PI::Proto(p),
265            PI::Unrecognized(u) => PI::Unrecognized(u.to_string().into()),
266        }
267    }
268}
269
270/// Return true if `s` is a valid protocol name.
271fn is_valid_proto_name(s: &str) -> bool {
272    (1..=100).contains(&s.len()) && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
273}
274
275impl std::str::FromStr for Protocol {
276    type Err = ParseError;
277
278    fn from_str(s: &str) -> Result<Self, Self::Err> {
279        match ProtoKind::from_name(s) {
280            Some(p) => Ok(Protocol(ProtocolInner::Proto(p))),
281            None => {
282                if is_valid_proto_name(s) {
283                    Ok(Protocol(ProtocolInner::Unrecognized(s.to_string().into())))
284                } else {
285                    Err(ParseError::Malformed)
286                }
287            }
288        }
289    }
290}
291
292/// Representation of a set of versions supported by a protocol.
293///
294/// For now, we only use this type for unrecognized protocols.
295#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
296struct SubprotocolEntry {
297    /// Which protocol's versions does this describe?
298    proto: Protocol,
299    /// A bit-vector defining which versions are supported.  If bit
300    /// `(1<<i)` is set, then protocol version `i` is supported.
301    supported: u64,
302}
303
304/// A degree of strictness with which to parse a Protocols (or one of its components).
305#[derive(Debug, Clone, Copy, PartialEq, Eq)]
306enum ParseStrictness {
307    /// We should enforce all rules declared in the spec.
308    Strict,
309
310    /// We should only enforce rules that are also enforced by C tor.
311    CTorCompatible,
312}
313
314/// A set of supported or required subprotocol versions.
315///
316/// This type supports both recognized subprotocols (listed in ProtoKind),
317/// and unrecognized subprotocols (stored by name).
318///
319/// To construct an instance, use the FromStr trait:
320/// ```
321/// use tor_protover::Protocols;
322/// let p: Result<Protocols,_> = "Link=1-3 LinkAuth=2-3 Relay=1-2".parse();
323/// ```
324///
325/// # Implementation notes
326///
327/// Because the number of distinct `Protocols` sets at any given time
328/// is much smaller than the number of relays, this type is interned in order to
329/// save memory and copying time.
330///
331/// This type is an Arc internally; it is cheap to clone.
332#[derive(Debug, Clone, Default, Eq, PartialEq, Hash)]
333#[cfg_attr(
334    feature = "serde",
335    derive(serde_with::DeserializeFromStr, serde_with::SerializeDisplay)
336)]
337pub struct Protocols(
338    /// We intern ProtocolsInner objects because:
339    ///  - There are very few _distinct_ values in any given set of relays.
340    ///  - Every relay has one.
341    ///  - We often want to copy them when we're remembering information about circuits.
342    Intern<ProtocolsInner>,
343);
344
345/// Inner representation of Protocols.
346///
347/// We make this a separate type so that we can intern it inside an `Intern`
348#[derive(Default, Clone, Debug, Eq, PartialEq, Hash, Deftly)]
349#[derive_deftly(tor_basic_utils::GloballyInternable)]
350struct ProtocolsInner {
351    /// A mapping from protocols' integer encodings to bit-vectors.
352    recognized: [u64; N_RECOGNIZED],
353    /// A vector of unrecognized protocol versions,
354    /// in sorted order.
355    ///
356    /// Every entry in this list has supported != 0.
357    unrecognized: Vec<SubprotocolEntry>,
358}
359
360impl From<ProtocolsInner> for Protocols {
361    fn from(value: ProtocolsInner) -> Self {
362        Protocols(value.into_intern())
363    }
364}
365
366impl Protocols {
367    /// Return a new empty set of protocol versions.
368    ///
369    /// # Warning
370    ///
371    /// To the extend possible, avoid using empty lists to represent the capabilities
372    /// of an unknown target.  Instead, if there is a consensus present, use the
373    /// `required-relay-protocols` field of the consensus.
374    pub fn new() -> Self {
375        Protocols::default()
376    }
377
378    /// Construct a new [`Protocols`] from a single recognized kind and a list of associated versions.
379    ///
380    /// (This method should not usually be needed for new parts of Arti:
381    /// its only use-case is a legacy piece of hsdesc parsing.)
382    pub fn from_kind_and_versions(kind: ProtoKind, versions: &str) -> Result<Self, ParseError> {
383        let versions = parse_version_mask(versions, ParseStrictness::Strict)?;
384        let mut protocols = ProtocolsInner::default();
385
386        if let Some(p) = protocols.recognized.get_mut(usize::from(kind.get())) {
387            *p = versions;
388        } else {
389            return Err(ParseError::Malformed);
390        }
391
392        Ok(protocols.into())
393    }
394
395    /// Helper: return true iff this protocol set contains the
396    /// version `ver` of the protocol represented by the integer `proto`.
397    fn supports_recognized_ver(&self, proto: usize, ver: u8) -> bool {
398        if usize::from(ver) > MAX_VER {
399            return false;
400        }
401        if proto >= self.0.recognized.len() {
402            return false;
403        }
404        (self.0.recognized[proto] & (1 << ver)) != 0
405    }
406    /// Helper: return true iff this protocol set contains version
407    /// `ver` of the unrecognized protocol represented by the string
408    /// `proto`.
409    ///
410    /// Requires that `proto` is not the name of a recognized protocol.
411    fn supports_unrecognized_ver(&self, proto: &str, ver: u8) -> bool {
412        if usize::from(ver) > MAX_VER {
413            return false;
414        }
415        let ent = self
416            .0
417            .unrecognized
418            .iter()
419            .find(|ent| ent.proto.is_unrecognized(proto));
420        match ent {
421            Some(e) => (e.supported & (1 << ver)) != 0,
422            None => false,
423        }
424    }
425
426    /// Return true if this list of protocols is empty.
427    pub fn is_empty(&self) -> bool {
428        self.0.recognized.iter().all(|v| *v == 0)
429            && self.0.unrecognized.iter().all(|p| p.supported == 0)
430    }
431
432    // TODO: Combine these next two functions into one by using a trait.
433    /// Check whether a known protocol version is supported.
434    ///
435    /// ```
436    /// use tor_protover::*;
437    /// let protos: Protocols = "Link=1-3 HSDir=2,4-5".parse().unwrap();
438    ///
439    /// assert!(protos.supports_known_subver(ProtoKind::Link, 2));
440    /// assert!(protos.supports_known_subver(ProtoKind::HSDir, 4));
441    /// assert!(! protos.supports_known_subver(ProtoKind::HSDir, 3));
442    /// assert!(! protos.supports_known_subver(ProtoKind::LinkAuth, 3));
443    /// ```
444    pub fn supports_known_subver(&self, proto: ProtoKind, ver: u8) -> bool {
445        self.supports_recognized_ver(proto.get() as usize, ver)
446    }
447    /// Check whether a protocol version identified by a string is supported.
448    ///
449    /// ```
450    /// use tor_protover::*;
451    /// let protos: Protocols = "Link=1-3 Foobar=7".parse().unwrap();
452    ///
453    /// assert!(protos.supports_subver("Link", 2));
454    /// assert!(protos.supports_subver("Foobar", 7));
455    /// assert!(! protos.supports_subver("Link", 5));
456    /// assert!(! protos.supports_subver("Foobar", 6));
457    /// assert!(! protos.supports_subver("Wombat", 3));
458    /// ```
459    pub fn supports_subver(&self, proto: &str, ver: u8) -> bool {
460        match ProtoKind::from_name(proto) {
461            Some(p) => self.supports_recognized_ver(p.get() as usize, ver),
462            None => self.supports_unrecognized_ver(proto, ver),
463        }
464    }
465
466    /// Check whether a protocol version is supported.
467    ///
468    /// ```
469    /// use tor_protover::*;
470    /// let protos: Protocols = "Link=1-5 Desc=2-4".parse().unwrap();
471    /// assert!(protos.supports_named_subver(named::DESC_FAMILY_IDS)); // Desc=4
472    /// assert!(! protos.supports_named_subver(named::CONFLUX_BASE)); // Conflux=1
473    /// ```
474    pub fn supports_named_subver(&self, protover: NamedSubver) -> bool {
475        self.supports_known_subver(protover.kind, protover.version.into())
476    }
477
478    /// Check whether a numbered subprotocol capability is supported.
479    ///
480    /// ```
481    /// use tor_protover::*;
482    /// let protos: Protocols = "Link=1-5 Desc=2-4".parse().unwrap();
483    /// assert!(protos.supports_numbered_subver(NumberedSubver::new(ProtoKind::Desc, 4)));
484    /// assert!(! protos.supports_numbered_subver(NumberedSubver::new(ProtoKind::Conflux, 1)));
485    /// ```
486    pub fn supports_numbered_subver(&self, protover: NumberedSubver) -> bool {
487        self.supports_known_subver(protover.kind, protover.version)
488    }
489
490    /// Return a Protocols holding every protocol flag that is present in `self`
491    /// but not `other`.
492    ///
493    /// ```
494    /// use tor_protover::*;
495    /// let protos: Protocols = "Desc=2-4 Microdesc=1-5".parse().unwrap();
496    /// let protos2: Protocols = "Desc=3 Microdesc=3".parse().unwrap();
497    /// assert_eq!(protos.difference(&protos2),
498    ///            "Desc=2,4 Microdesc=1-2,4-5".parse().unwrap());
499    /// ```
500    pub fn difference(&self, other: &Protocols) -> Protocols {
501        let mut r = ProtocolsInner::default();
502
503        for i in 0..N_RECOGNIZED {
504            r.recognized[i] = self.0.recognized[i] & !other.0.recognized[i];
505        }
506        // This is not super efficient, but we don't have to do it often.
507        for ent in self.0.unrecognized.iter() {
508            let mut ent = ent.clone();
509            if let Some(other_ent) = other.0.unrecognized.iter().find(|e| e.proto == ent.proto) {
510                ent.supported &= !other_ent.supported;
511            }
512            if ent.supported != 0 {
513                r.unrecognized.push(ent);
514            }
515        }
516        Protocols::from(r)
517    }
518
519    /// Return a Protocols holding every protocol flag that is present in `self`
520    /// or `other` or both.
521    ///
522    /// ```
523    /// use tor_protover::*;
524    /// let protos: Protocols = "Desc=2-4 Microdesc=1-5".parse().unwrap();
525    /// let protos2: Protocols = "Desc=3 Microdesc=10".parse().unwrap();
526    /// assert_eq!(protos.union(&protos2),
527    ///            "Desc=2-4 Microdesc=1-5,10".parse().unwrap());
528    /// ```
529    pub fn union(&self, other: &Protocols) -> Protocols {
530        let mut r = (**self.0).clone();
531        for i in 0..N_RECOGNIZED {
532            r.recognized[i] |= other.0.recognized[i];
533        }
534        for ent in other.0.unrecognized.iter() {
535            if let Some(my_ent) = r.unrecognized.iter_mut().find(|e| e.proto == ent.proto) {
536                my_ent.supported |= ent.supported;
537            } else {
538                r.unrecognized.push(ent.clone());
539            }
540        }
541        r.unrecognized.sort();
542        Protocols::from(r)
543    }
544
545    /// Return a Protocols holding every protocol flag that is present in both `self`
546    /// and `other`.
547    ///
548    /// ```
549    /// use tor_protover::*;
550    /// let protos: Protocols = "Desc=2-4 Microdesc=1-5".parse().unwrap();
551    /// let protos2: Protocols = "Desc=3 Microdesc=10".parse().unwrap();
552    /// assert_eq!(protos.intersection(&protos2),
553    ///            "Desc=3".parse().unwrap());
554    /// ```
555    pub fn intersection(&self, other: &Protocols) -> Protocols {
556        let mut r = ProtocolsInner::default();
557        for i in 0..N_RECOGNIZED {
558            r.recognized[i] = self.0.recognized[i] & other.0.recognized[i];
559        }
560        for ent in self.0.unrecognized.iter() {
561            if let Some(other_ent) = other.0.unrecognized.iter().find(|e| e.proto == ent.proto) {
562                let supported = ent.supported & other_ent.supported;
563                if supported != 0 {
564                    r.unrecognized.push(SubprotocolEntry {
565                        proto: ent.proto.clone(),
566                        supported,
567                    });
568                }
569            }
570        }
571        r.unrecognized.sort();
572        Protocols::from(r)
573    }
574
575    /// As the regular `FromStr` implementation,
576    /// but imitate the result of a the C Tor implementation, which is rather more lax.
577    ///
578    /// The principle differences are:
579    /// - We allow all decimal integer formats, even those starting with 0.
580    /// - We allow (and ignore) the integer '0'.
581    /// - We do not require that there is no more than one `SubprotocolEntry` with a given
582    ///   `ProtoKind`; instead, we ignore all but the first.
583    /// - We permit duplicate bits within the same SubprotocolEntry.
584    pub fn from_str_c_compatible(s: &str) -> Result<Self, ParseError> {
585        Self::from_str_impl(s, ParseStrictness::CTorCompatible)
586    }
587}
588
589impl ProtocolsInner {
590    /// Parsing helper: Try to add a new entry `ent` to this set of protocols.
591    ///
592    /// Uses `foundmask`, a bit mask saying which recognized protocols
593    /// we've already found entries for.  Returns an error if `ent` is
594    /// for a recognized protocol we've already added.
595    ///
596    /// WARNING: This method DOES NOT enforce uniqueness for unrecognized protocols.
597    /// The caller is responsible for doing that in a way appropriate
598    /// for the provided strictness level.
599    ///
600    /// Does not preserve sorting order; the caller must call `self.unrecognized.sort()` before returning.
601    fn add(
602        &mut self,
603        foundmask: &mut u64,
604        ent: SubprotocolEntry,
605        strictness: ParseStrictness,
606    ) -> Result<(), ParseError> {
607        match &ent.proto.0 {
608            ProtocolInner::Proto(k) => {
609                let idx = k.get() as usize;
610                assert!(idx < N_RECOGNIZED); // guaranteed by invariant on Protocol::Proto
611                let bit = 1 << u64::from(k.get());
612                if (*foundmask & bit) != 0 {
613                    match strictness {
614                        ParseStrictness::Strict => return Err(ParseError::Duplicate),
615                        ParseStrictness::CTorCompatible => return Ok(()),
616                    }
617                }
618                *foundmask |= bit;
619                self.recognized[idx] = ent.supported;
620            }
621            ProtocolInner::Unrecognized(_) => {
622                if ent.supported != 0 {
623                    self.unrecognized.push(ent);
624                }
625            }
626        }
627        Ok(())
628    }
629}
630
631/// An error representing a failure to parse a set of protocol versions.
632#[derive(Error, Debug, PartialEq, Eq, Clone)]
633#[non_exhaustive]
634pub enum ParseError {
635    /// A protocol version was not in the range 1..=63.
636    #[error("Protocol version out of range")]
637    OutOfRange,
638    /// Some subprotocol or protocol version appeared more than once.
639    #[error("Duplicate protocol entry")]
640    Duplicate,
641    /// The list of protocol versions was malformed in some other way.
642    #[error("Malformed protocol entry")]
643    Malformed,
644}
645
646/// Helper: return a new u64 in which bits `lo` through `hi` inclusive
647/// are set to 1, and all the other bits are set to 0.
648///
649/// In other words, `bitrange(a,b)` is how we represent the range of
650/// versions `a-b` in a protocol version bitmask.
651///
652/// ```ignore
653/// # use tor_protover::bitrange;
654/// assert_eq!(bitrange(0, 5), 0b111111);
655/// assert_eq!(bitrange(2, 5), 0b111100);
656/// assert_eq!(bitrange(2, 7), 0b11111100);
657/// ```
658fn bitrange(lo: u64, hi: u64) -> u64 {
659    assert!(lo <= hi && lo <= 63 && hi <= 63);
660    let mut mask = !0;
661    mask <<= 63 - hi;
662    mask >>= 63 - hi + lo;
663    mask <<= lo;
664    mask
665}
666
667/// Helper: return true if the provided string is a valid "integer"
668/// in the form accepted by the protover spec.  This may be stricter than
669/// rust's integer parsing format.
670fn is_good_number(n: &str, strictness: ParseStrictness) -> bool {
671    if strictness == ParseStrictness::Strict && n.starts_with('0') {
672        return false;
673    }
674    n.chars().all(|ch| ch.is_ascii_digit())
675}
676
677/// Parse a version-list in `versions` into a bitmask.
678fn parse_version_mask(versions: &str, strictness: ParseStrictness) -> Result<u64, ParseError> {
679    if versions.is_empty() {
680        // We need to handle this case specially, since otherwise
681        // it would be treated below as a single empty value, which
682        // would be rejected.
683        return Ok(0);
684    }
685    // Construct a bitmask based on the comma-separated versions.
686    let mut supported = 0_u64;
687    for ent in versions.split(',') {
688        // Find and parse lo and hi for a single range of versions.
689        // (If this is not a range, but rather a single version v,
690        // treat it as if it were a range v-v.)
691        let (lo_s, hi_s) = ent.split_once('-').unwrap_or((ent, ent));
692
693        if !is_good_number(lo_s, strictness) {
694            return Err(ParseError::Malformed);
695        }
696        if !is_good_number(hi_s, strictness) {
697            return Err(ParseError::Malformed);
698        }
699        let lo: u64 = lo_s.parse().map_err(|_| ParseError::Malformed)?;
700        let hi: u64 = hi_s.parse().map_err(|_| ParseError::Malformed)?;
701        // Make sure that lo and hi are in-bounds and consistent.
702        if lo > (MAX_VER as u64) || hi > (MAX_VER as u64) {
703            return Err(ParseError::OutOfRange);
704        }
705        if lo > hi {
706            return Err(ParseError::Malformed);
707        }
708        let mask = bitrange(lo, hi);
709        // Make sure that no version is included twice.
710        if strictness == ParseStrictness::Strict && (supported & mask) != 0 {
711            return Err(ParseError::Duplicate);
712        }
713        // Ignore bit 0, which can be set for non-strict bitmasks.
714        let mask = mask & !1;
715        // Add the appropriate bits to the mask.
716        supported |= mask;
717    }
718
719    Ok(supported)
720}
721
722/// A single SubprotocolEntry is parsed from a string of the format
723/// Name=Versions, where Versions is a comma-separated list of
724/// integers or ranges of integers.
725impl SubprotocolEntry {
726    /// Parse a [`SubprotocolEntry`] with a given level of strictness.
727    fn from_str(s: &str, strictness: ParseStrictness) -> Result<Self, ParseError> {
728        // split the string on the =.
729        let (name, versions) = s.split_once('=').ok_or(ParseError::Malformed)?;
730
731        // Look up the protocol by name.
732        let proto: Protocol = name.parse()?;
733        Ok(SubprotocolEntry {
734            proto,
735            supported: parse_version_mask(versions, strictness)?,
736        })
737    }
738}
739
740/// A Protocols set can be parsed from a string according to the
741/// format used in Tor consensus documents.
742///
743/// A protocols set is represented by a space-separated list of
744/// entries.  Each entry is of the form `Name=Versions`, where `Name`
745/// is the name of a protocol, and `Versions` is a comma-separated
746/// list of version numbers and version ranges.  Each version range is
747/// a pair of integers separated by `-`.
748///
749/// No protocol name may be listed twice.  No version may be listed
750/// twice for a single protocol.  All versions must be in range 0
751/// through 63 inclusive.
752impl std::str::FromStr for Protocols {
753    type Err = ParseError;
754
755    fn from_str(s: &str) -> Result<Self, ParseError> {
756        Protocols::from_str_impl(s, ParseStrictness::Strict)
757    }
758}
759
760impl Protocols {
761    /// Parse a [`Protocols`] with the requested degree of strictness.
762    fn from_str_impl(s: &str, strictness: ParseStrictness) -> Result<Self, ParseError> {
763        let mut result = ProtocolsInner::default();
764        let mut foundmask = 0_u64;
765        for ent in s.split(' ') {
766            if ent.is_empty() {
767                continue;
768            }
769
770            let s = SubprotocolEntry::from_str(ent, strictness)?;
771            result.add(&mut foundmask, s, strictness)?;
772        }
773        // We require a stable sort here.
774        // We can't use sort_by_key because of lifetime issues.
775        result.unrecognized.sort_by(|a, b| a.proto.cmp(&b.proto));
776        match strictness {
777            ParseStrictness::Strict => {
778                if result
779                    .unrecognized
780                    .windows(2)
781                    .any(|w| w[0].proto == w[1].proto)
782                {
783                    return Err(ParseError::Duplicate);
784                }
785            }
786            ParseStrictness::CTorCompatible => {
787                result.unrecognized.dedup_by(|a, b| a.proto.eq(&b.proto));
788            }
789        }
790
791        Ok(result.into())
792    }
793}
794
795/// Given a bitmask, return a list of the bits set in the mask, as a
796/// String in the format expected by Tor consensus documents.
797///
798/// This implementation constructs ranges greedily.  For example, the
799/// bitmask `0b0111011` will be represented as `0-1,3-5`, and not
800/// `0,1,3,4,5` or `0,1,3-5`.
801///
802/// ```ignore
803/// # use tor_protover::dumpmask;
804/// assert_eq!(dumpmask(0b111111), "0-5");
805/// assert_eq!(dumpmask(0b111100), "2-5");
806/// assert_eq!(dumpmask(0b11111100), "2-7");
807/// ```
808fn dumpmask(mut mask: u64) -> String {
809    /// Helper: push a range (which may be a singleton) onto `v`.
810    fn append(v: &mut Vec<String>, lo: u32, hi: u32) {
811        if lo == hi {
812            v.push(lo.to_string());
813        } else {
814            v.push(format!("{}-{}", lo, hi));
815        }
816    }
817    // We'll be building up our result here, then joining it with
818    // commas.
819    let mut result = Vec::new();
820    // This implementation is a little tricky, but it should be more
821    // efficient than a raw search.  Basically, we're using the
822    // function u64::trailing_zeros to count how large each range of
823    // 1s or 0s is, and then shifting by that amount.
824
825    // How many bits have we already shifted `mask`?
826    let mut shift = 0;
827    while mask != 0 {
828        let zeros = mask.trailing_zeros();
829        mask >>= zeros;
830        shift += zeros;
831        let ones = mask.trailing_ones();
832        append(&mut result, shift, shift + ones - 1);
833        shift += ones;
834        if ones == 64 {
835            // We have to do this check to avoid overflow when formatting
836            // the range `0-63`.
837            break;
838        }
839        mask >>= ones;
840    }
841    result.join(",")
842}
843
844/// The Display trait formats a protocol set in the format expected by Tor
845/// consensus documents.
846///
847/// ```
848/// use tor_protover::*;
849/// let protos: Protocols = "Link=1,2,3 Foobar=7 Relay=2".parse().unwrap();
850/// assert_eq!(format!("{}", protos),
851///            "Foobar=7 Link=1-3 Relay=2");
852/// ```
853impl std::fmt::Display for Protocols {
854    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
855        let mut entries = Vec::new();
856        for (pk, mask) in self.iter_masks() {
857            entries.push(format!("{}={}", pk, dumpmask(mask)));
858        }
859        // This sort is required.
860        entries.sort();
861        write!(f, "{}", entries.join(" "))
862    }
863}
864
865impl Protocols {
866    /// Iterate over all capabilities, known and unknown
867    ///
868    /// Yields each protocol separately, but with all values combined,
869    /// so yields a name (`Protocol`) and bitmask.
870    fn iter_masks(&self) -> impl Iterator<Item = (ProtocolInner<'_>, u64)> + Clone {
871        chain!(
872            self.0.recognized.iter().enumerate().map(|(idx, mask)| {
873                let pk = ProtocolInner::Proto((idx as u8).into());
874                (pk, *mask)
875            }),
876            self.0
877                .unrecognized
878                .iter()
879                .map(|ent| (ent.proto.0.as_ref(), ent.supported)),
880        )
881        .filter(|(_idx, mask)| *mask != 0)
882    }
883
884    /// Iterate over all the specified capabilities
885    ///
886    /// Yields each capability separately, as name (`Protocol`) and value.
887    /// Output is in an arbitrary order.
888    ///
889    /// The output representation is far from compact.
890    /// Depending on the input this could allocate up to 64 a separate `String`s
891    /// for each unknown keyword in `self`.
892    //
893    // We could reduce the separate allocations for each keyword by interning the keywords
894    // individually (but we already intern `Self`) or by inventing a borrowed form of
895    // `Protocol`.  (`Protocol` contains an enum which isn't actually present in `self`,
896    // so we can't yield `&Protocol` here.)
897    //
898    // Or we could allow callers to take advantage of our internal bitmask representation,
899    // perhaps by providing a way to iterate over the `Preotocol`s and the contained `Value`s
900    // separately, and a way to look up whether a `Protocols` contains a `(Protocol, Value)`.
901    //
902    // See also `protostatus_preamble_aggregate` in `tor-dirauth/src/consensus/preamble.rs`
903    // for discussion of the perf at what is currently the only call site.
904    pub fn iter_all(&self) -> impl Iterator<Item = (Protocol, Value)> + Clone {
905        self.iter_masks().flat_map(|(kind, mask)| {
906            // Possibly we could optimise this with `bit-iter` or some such,
907            // if it supports newtypes nicely.
908            Value::iter_all()
909                .filter(move |value| {
910                    let bit = value.to_bit();
911                    (mask & bit) != 0
912                })
913                .map(move |value| (Protocol(kind.clone().into_static()), value))
914        })
915    }
916}
917
918impl FromIterator<(Protocol, Value)> for Protocols {
919    fn from_iter<I>(iter: I) -> Self
920    where
921        I: IntoIterator<Item = (Protocol, Value)>,
922    {
923        let mut out = BTreeMap::<Protocol, u64>::new();
924        for (proto, value) in iter {
925            *out.entry(proto).or_default() |= value.to_bit();
926        }
927        let mut recognized = [0_u64; N_RECOGNIZED];
928        let mut unrecognized = vec![];
929        for (proto, supported) in out {
930            match proto.0 {
931                ProtocolInner::Proto(proto) => recognized[proto.get() as usize] = supported,
932                ProtocolInner::Unrecognized(_) => {
933                    unrecognized.push(SubprotocolEntry { proto, supported });
934                }
935            };
936        }
937        ProtocolsInner {
938            recognized,
939            unrecognized,
940        }
941        .into()
942    }
943}
944
945impl FromIterator<NamedSubver> for Protocols {
946    fn from_iter<T: IntoIterator<Item = NamedSubver>>(iter: T) -> Self {
947        let mut r = ProtocolsInner::default();
948        for named_subver in iter {
949            let proto_idx = usize::from(named_subver.kind.get());
950            let proto_ver = named_subver.version;
951
952            // These are guaranteed by invariants on NamedSubver.
953            assert!(proto_idx < N_RECOGNIZED);
954            r.recognized[proto_idx] |= proto_ver.to_bit();
955        }
956        Protocols::from(r)
957    }
958}
959
960/// Documentation: when is a protocol "supported"?
961///
962/// Arti should consider itself to "support" a protocol if, _as built_,
963/// it implements the protocol completely.
964///
965/// Just having the protocol listed among the [`named`]
966/// protocols is not enough, and neither is an incomplete
967/// or uncompliant implementation.
968///
969/// Similarly, if the protocol is not compiled in,
970/// it is not technically _supported_.
971///
972/// When in doubt, ask yourself:
973/// - If another Tor implementation believed that we implemented this protocol,
974///   and began to speak it to us, would we be able to do so?
975/// - If the protocol were required,
976///   would this software as built actually meet that requirement?
977///
978/// If either answer is no, the protocol is not supported.
979pub mod doc_supported {}
980
981/// Documentation about changing lists of supported versions.
982///
983/// # Warning
984///
985/// You need to be extremely careful when removing
986/// _any_ entry from a list of supported protocols.
987///
988/// If you remove an entry while it still appears as "recommended" in the consensus,
989/// you'll cause all the instances without it to warn.
990///
991/// If you remove an entry while it still appears as "required" in the
992///  consensus, you'll cause all the instances without it to refuse to connect
993/// to the network, and shut down.
994///
995/// If you need to remove a version from a list of supported protocols,
996/// you need to make sure that it is not listed in the _current consensuses_:
997/// just removing it from the list that the authorities vote for is NOT ENOUGH.
998/// You need to remove it from the required list,
999/// and THEN let the authorities upgrade and vote on new
1000/// consensuses without it. Only once those consensuses are out is it safe to
1001/// remove from the list of required protocols.
1002///
1003/// ## Example
1004///
1005/// One concrete example of a very dangerous race that could occur:
1006///
1007/// Suppose that the client supports protocols "HsDir=1-2" and the consensus
1008/// requires protocols "HsDir=1-2".  If the client supported protocol list is
1009/// then changed to "HSDir=2", while the consensus stills lists "HSDir=1-2",
1010/// then these clients, even very recent ones, will shut down because they
1011/// don't support "HSDir=1".
1012///
1013/// And so, changes need to be done in strict sequence as described above.
1014pub mod doc_changing {}
1015
1016#[cfg(test)]
1017mod test {
1018    // @@ begin test lint list maintained by maint/add_warning @@
1019    #![allow(clippy::bool_assert_comparison)]
1020    #![allow(clippy::clone_on_copy)]
1021    #![allow(clippy::dbg_macro)]
1022    #![allow(clippy::mixed_attributes_style)]
1023    #![allow(clippy::print_stderr)]
1024    #![allow(clippy::print_stdout)]
1025    #![allow(clippy::single_char_pattern)]
1026    #![allow(clippy::unwrap_used)]
1027    #![allow(clippy::unchecked_time_subtraction)]
1028    #![allow(clippy::useless_vec)]
1029    #![allow(clippy::needless_pass_by_value)]
1030    #![allow(clippy::string_slice)] // See arti#2571
1031    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
1032    use std::str::FromStr;
1033
1034    use super::*;
1035
1036    #[test]
1037    fn test_bitrange() {
1038        assert_eq!(0b1, bitrange(0, 0));
1039        assert_eq!(0b10, bitrange(1, 1));
1040        assert_eq!(0b11, bitrange(0, 1));
1041        assert_eq!(0b1111110000000, bitrange(7, 12));
1042        assert_eq!(!0, bitrange(0, 63));
1043    }
1044
1045    #[test]
1046    fn test_dumpmask() {
1047        assert_eq!("", dumpmask(0));
1048        assert_eq!("0-5", dumpmask(0b111111));
1049        assert_eq!("4-5", dumpmask(0b110000));
1050        assert_eq!("1,4-5", dumpmask(0b110010));
1051        assert_eq!("0-63", dumpmask(!0));
1052    }
1053
1054    #[test]
1055    fn test_canonical() -> Result<(), ParseError> {
1056        fn t(orig: &str, canonical: &str) -> Result<(), ParseError> {
1057            let protos: Protocols = orig.parse()?;
1058            let enc = format!("{}", protos);
1059            assert_eq!(enc, canonical);
1060            Ok(())
1061        }
1062
1063        t("", "")?;
1064        t(" ", "")?;
1065        t("Link=5,6,7,9 Relay=4-7,2", "Link=5-7,9 Relay=2,4-7")?;
1066        t("FlowCtrl= Padding=8,7 Desc=1-5,6-8", "Desc=1-8 Padding=7-8")?;
1067        t("Zelda=7 Gannon=3,6 Link=4", "Gannon=3,6 Link=4 Zelda=7")?;
1068
1069        Ok(())
1070    }
1071
1072    #[test]
1073    fn test_invalid() {
1074        fn t(s: &str) -> ParseError {
1075            let protos: Result<Protocols, ParseError> = s.parse();
1076            assert!(protos.is_err());
1077            protos.err().unwrap()
1078        }
1079
1080        assert_eq!(t("Link=1-100"), ParseError::OutOfRange);
1081        assert_eq!(t("Zelda=100"), ParseError::OutOfRange);
1082        assert_eq!(t("Link=100-200"), ParseError::OutOfRange);
1083
1084        assert_eq!(t("Link=1,1"), ParseError::Duplicate);
1085        assert_eq!(t("Link=1 Link=1"), ParseError::Duplicate);
1086        assert_eq!(t("Link=1 Link=3"), ParseError::Duplicate);
1087        assert_eq!(t("Zelda=1 Zelda=3"), ParseError::Duplicate);
1088
1089        assert_eq!(t("Link=Zelda"), ParseError::Malformed);
1090        assert_eq!(t("Link=6-2"), ParseError::Malformed);
1091        assert_eq!(t("Link=6-"), ParseError::Malformed);
1092        assert_eq!(t("Link=6-,2"), ParseError::Malformed);
1093        assert_eq!(t("Link=1,,2"), ParseError::Malformed);
1094        assert_eq!(t("Link=6-frog"), ParseError::Malformed);
1095        assert_eq!(t("Link=gannon-9"), ParseError::Malformed);
1096        assert_eq!(t("Link Zelda"), ParseError::Malformed);
1097
1098        assert_eq!(t("Link=01"), ParseError::Malformed);
1099        assert_eq!(t("Link=waffle"), ParseError::Malformed);
1100        assert_eq!(t("Link=1_1"), ParseError::Malformed);
1101    }
1102
1103    #[test]
1104    fn test_ctor_compat() {
1105        for (loose, strict) in &[
1106            // With duplicate entries, those after the first are ignored
1107            ("Link=0-10 Link=25-30", "Link=1-10"),
1108            ("Link=25-30 Link=0-10", "Link=25-30"),
1109            ("Zelda=6-8 Link=1-10 Zelda=6-10", "Link=1-10 Zelda=6-8"),
1110            // The 0 bit and any 0 prefixes are ignored.
1111            ("LinkAuth=0-00040", "LinkAuth=1-40"),
1112            ("Foo=0,3,004,5,0010", "Foo=3-5,10"),
1113            // Duplicate bits are permitted
1114            ("Foo=1-10,2-20,3-5", "Foo=1-20"),
1115            ("Link=1-10,2-20,3-5", "Link=1-20"),
1116            // Value zero is invalid and discarded
1117            ("Link=0-1", "Link=1"),
1118            ("Link=0", ""),
1119        ] {
1120            let p1 = Protocols::from_str_c_compatible(loose).unwrap();
1121            let p2 = Protocols::from_str(strict).unwrap();
1122            assert_eq!(p1, p2);
1123
1124            assert!(Protocols::from_str(loose).is_err());
1125        }
1126    }
1127
1128    #[test]
1129    fn test_supports() -> Result<(), ParseError> {
1130        let p: Protocols = "Link=4,5-7 Padding=2 Lonk=1-3,5".parse()?;
1131
1132        assert!(p.supports_known_subver(ProtoKind::Padding, 2));
1133        assert!(!p.supports_known_subver(ProtoKind::Padding, 1));
1134        assert!(p.supports_known_subver(ProtoKind::Link, 6));
1135        assert!(!p.supports_known_subver(ProtoKind::Link, 255));
1136        assert!(!p.supports_known_subver(ProtoKind::Cons, 1));
1137        assert!(!p.supports_known_subver(ProtoKind::Cons, 0));
1138        assert!(p.supports_subver("Link", 6));
1139        assert!(!p.supports_subver("link", 6));
1140        assert!(!p.supports_subver("Cons", 0));
1141        assert!(p.supports_subver("Lonk", 3));
1142        assert!(!p.supports_subver("Lonk", 4));
1143        assert!(!p.supports_subver("lonk", 3));
1144        assert!(!p.supports_subver("Lonk", 64));
1145
1146        Ok(())
1147    }
1148
1149    #[test]
1150    fn test_difference() -> Result<(), ParseError> {
1151        let p1: Protocols = "Link=1-10 Desc=5-10 Relay=1,3,5,7,9 Other=7-60 Mine=1-20".parse()?;
1152        let p2: Protocols = "Link=3-4 Desc=1-6 Relay=2-6 Other=8 Theirs=20".parse()?;
1153
1154        assert_eq!(
1155            p1.difference(&p2),
1156            Protocols::from_str("Link=1-2,5-10 Desc=7-10 Relay=1,7,9 Other=7,9-60 Mine=1-20")?
1157        );
1158        assert_eq!(
1159            p2.difference(&p1),
1160            Protocols::from_str("Desc=1-4 Relay=2,4,6 Theirs=20")?,
1161        );
1162
1163        let nil = Protocols::default();
1164        assert_eq!(p1.difference(&nil), p1);
1165        assert_eq!(p2.difference(&nil), p2);
1166        assert_eq!(nil.difference(&p1), nil);
1167        assert_eq!(nil.difference(&p2), nil);
1168
1169        Ok(())
1170    }
1171
1172    #[test]
1173    fn test_union() -> Result<(), ParseError> {
1174        let p1: Protocols = "Link=1-10 Desc=5-10 Relay=1,3,5,7,9 Other=7-60 Mine=1-20".parse()?;
1175        let p2: Protocols = "Link=3-4 Desc=1-6 Relay=2-6 Other=2,8 Theirs=20".parse()?;
1176
1177        assert_eq!(
1178            p1.union(&p2),
1179            Protocols::from_str(
1180                "Link=1-10 Desc=1-10 Relay=1-7,9 Other=2,7-60 Theirs=20 Mine=1-20"
1181            )?
1182        );
1183        assert_eq!(
1184            p2.union(&p1),
1185            Protocols::from_str(
1186                "Link=1-10 Desc=1-10 Relay=1-7,9 Other=2,7-60 Theirs=20 Mine=1-20"
1187            )?
1188        );
1189
1190        let nil = Protocols::default();
1191        assert_eq!(p1.union(&nil), p1);
1192        assert_eq!(p2.union(&nil), p2);
1193        assert_eq!(nil.union(&p1), p1);
1194        assert_eq!(nil.union(&p2), p2);
1195
1196        Ok(())
1197    }
1198
1199    #[test]
1200    fn test_intersection() -> Result<(), ParseError> {
1201        let p1: Protocols = "Link=1-10 Desc=5-10 Relay=1,3,5,7,9 Other=7-60 Mine=1-20".parse()?;
1202        let p2: Protocols = "Link=3-4 Desc=1-6 Relay=2-6 Other=2,8 Theirs=20".parse()?;
1203
1204        assert_eq!(
1205            p1.intersection(&p2),
1206            Protocols::from_str("Link=3-4 Desc=5-6 Relay=3,5 Other=8")?
1207        );
1208        assert_eq!(
1209            p2.intersection(&p1),
1210            Protocols::from_str("Link=3-4 Desc=5-6 Relay=3,5 Other=8")?
1211        );
1212
1213        let nil = Protocols::default();
1214        assert_eq!(p1.intersection(&nil), nil);
1215        assert_eq!(p2.intersection(&nil), nil);
1216        assert_eq!(nil.intersection(&p1), nil);
1217        assert_eq!(nil.intersection(&p2), nil);
1218
1219        Ok(())
1220    }
1221
1222    #[test]
1223    fn from_iter() {
1224        use named as n;
1225        let empty: [NamedSubver; 0] = [];
1226        let prs: Protocols = empty.iter().copied().collect();
1227        assert_eq!(prs, Protocols::default());
1228        let prs: Protocols = empty.into_iter().collect();
1229        assert_eq!(prs, Protocols::default());
1230
1231        let prs = [
1232            n::LINK_V3,
1233            n::HSDIR_V3,
1234            n::LINK_V4,
1235            n::LINK_V5,
1236            n::CONFLUX_BASE,
1237        ]
1238        .into_iter()
1239        .collect::<Protocols>();
1240        assert_eq!(prs, "Link=3-5 HSDir=2 Conflux=1".parse().unwrap());
1241    }
1242
1243    #[test]
1244    fn from_iter_all() -> Result<(), ParseError> {
1245        let p1: Protocols = "Link=1-10 Desc=5-10 Relay=1,3,5,7,9 Other=7-60 Mine=1-20".parse()?;
1246        let p2 = p1.iter_all().collect::<Protocols>();
1247        assert_eq!(p1, p2);
1248
1249        let p3 = std::iter::repeat_n(p1.iter_all(), 3)
1250            .flatten()
1251            .collect::<Protocols>();
1252        assert_eq!(p1, p3);
1253        Ok(())
1254    }
1255
1256    #[test]
1257    fn order_numbered_subvers() {
1258        // We rely on this sort order elsewhere in our protocol.
1259        assert!(NumberedSubver::new(5, 7) < NumberedSubver::new(7, 5));
1260        assert!(NumberedSubver::new(7, 5) < NumberedSubver::new(7, 6));
1261        assert!(NumberedSubver::new(7, 6) < NumberedSubver::new(8, 6));
1262    }
1263}