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

            
57
use caret::caret_int;
58

            
59
use derive_deftly::Deftly;
60
use itertools::chain;
61
use std::borrow::Cow;
62
use std::collections::BTreeMap;
63
use thiserror::Error;
64
use tor_basic_utils::intern::{GloballyInternable as _, Intern};
65

            
66
pub mod named;
67
pub mod value;
68
pub use value::*;
69

            
70
/// Types we export for macros.
71
#[doc(hidden)]
72
pub mod macro_export {
73
    pub use paste;
74
}
75

            
76
caret_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?
117
const N_RECOGNIZED: usize = 13;
118

            
119
/// A specific, named subversion of a protocol.
120
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
121
pub 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

            
132
impl 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)]
159
pub struct NumberedSubver {
160
    /// The protocol in question
161
    kind: ProtoKind,
162
    /// The version of the protocol
163
    version: u8,
164
}
165

            
166
impl NumberedSubver {
167
    /// Construct a new [`NumberedSubver`]
168
461
    pub fn new(kind: impl Into<ProtoKind>, version: u8) -> Self {
169
461
        Self {
170
461
            kind: kind.into(),
171
461
            version,
172
461
        }
173
461
    }
174
    /// Return the ProtoKind and version for this [`NumberedSubver`].
175
    pub fn into_parts(self) -> (ProtoKind, u8) {
176
        (self.kind, self.version)
177
    }
178
}
179
impl From<NamedSubver> for NumberedSubver {
180
1105
    fn from(value: NamedSubver) -> Self {
181
1105
        Self {
182
1105
            kind: value.kind,
183
1105
            version: value.version.into(),
184
1105
        }
185
1105
    }
186
}
187

            
188
impl From<NamedSubver> for Protocols {
189
    fn from(value: NamedSubver) -> Self {
190
        Self::from_iter([value])
191
    }
192
}
193

            
194
#[cfg(feature = "tor-bytes")]
195
impl tor_bytes::Readable for NumberedSubver {
196
520
    fn take_from(b: &mut tor_bytes::Reader<'_>) -> tor_bytes::Result<Self> {
197
520
        let kind = b.take_u8()?;
198
520
        let version = b.take_u8()?;
199
455
        Ok(Self::new(kind, version))
200
520
    }
201
}
202

            
203
#[cfg(feature = "tor-bytes")]
204
impl tor_bytes::Writeable for NumberedSubver {
205
2
    fn write_onto<B: tor_bytes::Writer + ?Sized>(&self, b: &mut B) -> tor_bytes::EncodeResult<()> {
206
2
        b.write_u8(self.kind.into());
207
2
        b.write_u8(self.version);
208
2
        Ok(())
209
2
    }
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}")]
219
pub 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)]
223
enum 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

            
236
impl Protocol {
237
    /// Return true iff `s` is the name of a protocol we do not recognize.
238
4
    fn is_unrecognized(&self, s: &str) -> bool {
239
4
        match &self.0 {
240
4
            ProtocolInner::Unrecognized(s2) => s2 == s,
241
            _ => false,
242
        }
243
4
    }
244
}
245

            
246
impl<'s> ProtocolInner<'s> {
247
    /// Borrow from a `ProtocolInner`
248
    ///
249
    /// Gives a new owned `ProtocolInner` which borrows from `self`.
250
10670
    fn as_ref(&self) -> ProtocolInner<'_> {
251
        use ProtocolInner as PI;
252
10670
        match self {
253
            PI::Proto(p) => PI::Proto(*p),
254
10670
            PI::Unrecognized(u) => PI::Unrecognized(Cow::Borrowed(u.as_ref())),
255
        }
256
10670
    }
257

            
258
    /// Make a static `ProtocolInner`
259
    ///
260
    /// Returns a new owned `ProtocolInner` describing the same Protocol as `self`.
261
595260
    fn into_static(self) -> ProtocolInner<'static> {
262
        use ProtocolInner as PI;
263
595260
        match self {
264
577804
            PI::Proto(p) => PI::Proto(p),
265
17456
            PI::Unrecognized(u) => PI::Unrecognized(u.to_string().into()),
266
        }
267
595260
    }
268
}
269

            
270
/// Return true if `s` is a valid protocol name.
271
3682
fn is_valid_proto_name(s: &str) -> bool {
272
19892
    (1..=100).contains(&s.len()) && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
273
3682
}
274

            
275
impl std::str::FromStr for Protocol {
276
    type Err = ParseError;
277

            
278
12532652
    fn from_str(s: &str) -> Result<Self, Self::Err> {
279
12532652
        match ProtoKind::from_name(s) {
280
12528970
            Some(p) => Ok(Protocol(ProtocolInner::Proto(p))),
281
            None => {
282
3682
                if is_valid_proto_name(s) {
283
3682
                    Ok(Protocol(ProtocolInner::Unrecognized(s.to_string().into())))
284
                } else {
285
                    Err(ParseError::Malformed)
286
                }
287
            }
288
        }
289
12532652
    }
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)]
296
struct 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)]
306
enum 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
)]
337
pub 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)]
350
struct 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

            
360
impl From<ProtocolsInner> for Protocols {
361
1694873
    fn from(value: ProtocolsInner) -> Self {
362
1694873
        Protocols(value.into_intern())
363
1694873
    }
364
}
365

            
366
impl 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
2340
    pub fn new() -> Self {
375
2340
        Protocols::default()
376
2340
    }
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
1235
    pub fn from_kind_and_versions(kind: ProtoKind, versions: &str) -> Result<Self, ParseError> {
383
1235
        let versions = parse_version_mask(versions, ParseStrictness::Strict)?;
384
1235
        let mut protocols = ProtocolsInner::default();
385

            
386
1235
        if let Some(p) = protocols.recognized.get_mut(usize::from(kind.get())) {
387
1235
            *p = versions;
388
        } else {
389
            return Err(ParseError::Malformed);
390
        }
391

            
392
1235
        Ok(protocols.into())
393
1235
    }
394

            
395
    /// Helper: return true iff this protocol set contains the
396
    /// version `ver` of the protocol represented by the integer `proto`.
397
1612203
    fn supports_recognized_ver(&self, proto: usize, ver: u8) -> bool {
398
1612203
        if usize::from(ver) > MAX_VER {
399
1
            return false;
400
1612202
        }
401
1612202
        if proto >= self.0.recognized.len() {
402
            return false;
403
1612202
        }
404
1612202
        (self.0.recognized[proto] & (1 << ver)) != 0
405
1612203
    }
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
5
    fn supports_unrecognized_ver(&self, proto: &str, ver: u8) -> bool {
412
5
        if usize::from(ver) > MAX_VER {
413
1
            return false;
414
4
        }
415
4
        let ent = self
416
4
            .0
417
4
            .unrecognized
418
4
            .iter()
419
4
            .find(|ent| ent.proto.is_unrecognized(proto));
420
4
        match ent {
421
2
            Some(e) => (e.supported & (1 << ver)) != 0,
422
2
            None => false,
423
        }
424
5
    }
425

            
426
    /// Return true if this list of protocols is empty.
427
12415
    pub fn is_empty(&self) -> bool {
428
106210
        self.0.recognized.iter().all(|v| *v == 0)
429
6825
            && self.0.unrecognized.iter().all(|p| p.supported == 0)
430
12415
    }
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
1612071
    pub fn supports_known_subver(&self, proto: ProtoKind, ver: u8) -> bool {
445
1612071
        self.supports_recognized_ver(proto.get() as usize, ver)
446
1612071
    }
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
137
    pub fn supports_subver(&self, proto: &str, ver: u8) -> bool {
460
137
        match ProtoKind::from_name(proto) {
461
132
            Some(p) => self.supports_recognized_ver(p.get() as usize, ver),
462
5
            None => self.supports_unrecognized_ver(proto, ver),
463
        }
464
137
    }
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
1611285
    pub fn supports_named_subver(&self, protover: NamedSubver) -> bool {
475
1611285
        self.supports_known_subver(protover.kind, protover.version.into())
476
1611285
    }
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
780
    pub fn supports_numbered_subver(&self, protover: NumberedSubver) -> bool {
487
780
        self.supports_known_subver(protover.kind, protover.version)
488
780
    }
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
1046
    pub fn difference(&self, other: &Protocols) -> Protocols {
501
1046
        let mut r = ProtocolsInner::default();
502

            
503
1046
        for i in 0..N_RECOGNIZED {
504
13598
            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
1046
        for ent in self.0.unrecognized.iter() {
508
73
            let mut ent = ent.clone();
509
73
            if let Some(other_ent) = other.0.unrecognized.iter().find(|e| e.proto == ent.proto) {
510
2
                ent.supported &= !other_ent.supported;
511
71
            }
512
73
            if ent.supported != 0 {
513
72
                r.unrecognized.push(ent);
514
1
            }
515
        }
516
1046
        Protocols::from(r)
517
1046
    }
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
5986
    pub fn union(&self, other: &Protocols) -> Protocols {
530
5986
        let mut r = (**self.0).clone();
531
5986
        for i in 0..N_RECOGNIZED {
532
77818
            r.recognized[i] |= other.0.recognized[i];
533
        }
534
5986
        for ent in other.0.unrecognized.iter() {
535
9
            if let Some(my_ent) = r.unrecognized.iter_mut().find(|e| e.proto == ent.proto) {
536
2
                my_ent.supported |= ent.supported;
537
            } else {
538
6
                r.unrecognized.push(ent.clone());
539
            }
540
        }
541
5986
        r.unrecognized.sort();
542
5986
        Protocols::from(r)
543
5986
    }
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
21196
    pub fn intersection(&self, other: &Protocols) -> Protocols {
556
21196
        let mut r = ProtocolsInner::default();
557
21196
        for i in 0..N_RECOGNIZED {
558
275548
            r.recognized[i] = self.0.recognized[i] & other.0.recognized[i];
559
        }
560
21196
        for ent in self.0.unrecognized.iter() {
561
8
            if let Some(other_ent) = other.0.unrecognized.iter().find(|e| e.proto == ent.proto) {
562
2
                let supported = ent.supported & other_ent.supported;
563
2
                if supported != 0 {
564
2
                    r.unrecognized.push(SubprotocolEntry {
565
2
                        proto: ent.proto.clone(),
566
2
                        supported,
567
2
                    });
568
                }
569
6
            }
570
        }
571
21196
        r.unrecognized.sort();
572
21196
        Protocols::from(r)
573
21196
    }
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
740944
    pub fn from_str_c_compatible(s: &str) -> Result<Self, ParseError> {
585
740944
        Self::from_str_impl(s, ParseStrictness::CTorCompatible)
586
740944
    }
587
}
588

            
589
impl 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
12532630
    fn add(
602
12532630
        &mut self,
603
12532630
        foundmask: &mut u64,
604
12532630
        ent: SubprotocolEntry,
605
12532630
        strictness: ParseStrictness,
606
12532630
    ) -> Result<(), ParseError> {
607
12532630
        match &ent.proto.0 {
608
            ProtocolInner::Proto(k) => {
609
12528951
                let idx = k.get() as usize;
610
12528951
                assert!(idx < N_RECOGNIZED); // guaranteed by invariant on Protocol::Proto
611
12528951
                let bit = 1 << u64::from(k.get());
612
12528951
                if (*foundmask & bit) != 0 {
613
4
                    match strictness {
614
2
                        ParseStrictness::Strict => return Err(ParseError::Duplicate),
615
2
                        ParseStrictness::CTorCompatible => return Ok(()),
616
                    }
617
12528947
                }
618
12528947
                *foundmask |= bit;
619
12528947
                self.recognized[idx] = ent.supported;
620
            }
621
            ProtocolInner::Unrecognized(_) => {
622
3679
                if ent.supported != 0 {
623
3679
                    self.unrecognized.push(ent);
624
                }
625
            }
626
        }
627
12532626
        Ok(())
628
12532630
    }
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]
634
pub 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
/// ```
658
12541139
fn bitrange(lo: u64, hi: u64) -> u64 {
659
12541139
    assert!(lo <= hi && lo <= 63 && hi <= 63);
660
12541139
    let mut mask = !0;
661
12541139
    mask <<= 63 - hi;
662
12541139
    mask >>= 63 - hi + lo;
663
12541139
    mask <<= lo;
664
12541139
    mask
665
12541139
}
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.
670
25082295
fn is_good_number(n: &str, strictness: ParseStrictness) -> bool {
671
25082295
    if strictness == ParseStrictness::Strict && n.starts_with('0') {
672
7
        return false;
673
25082288
    }
674
25085953
    n.chars().all(|ch| ch.is_ascii_digit())
675
25082295
}
676

            
677
/// Parse a version-list in `versions` into a bitmask.
678
12533887
fn parse_version_mask(versions: &str, strictness: ParseStrictness) -> Result<u64, ParseError> {
679
12533887
    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
1
        return Ok(0);
684
12533886
    }
685
    // Construct a bitmask based on the comma-separated versions.
686
12533886
    let mut supported = 0_u64;
687
12533886
    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
12541153
        let (lo_s, hi_s) = ent.split_once('-').unwrap_or((ent, ent));
692

            
693
12541153
        if !is_good_number(lo_s, strictness) {
694
11
            return Err(ParseError::Malformed);
695
12541142
        }
696
12541142
        if !is_good_number(hi_s, strictness) {
697
1
            return Err(ParseError::Malformed);
698
12541141
        }
699
12541141
        let lo: u64 = lo_s.parse().map_err(|_| ParseError::Malformed)?;
700
12541140
        let hi: u64 = hi_s.parse().map_err(|_| ParseError::Malformed)?;
701
        // Make sure that lo and hi are in-bounds and consistent.
702
12541138
        if lo > (MAX_VER as u64) || hi > (MAX_VER as u64) {
703
3
            return Err(ParseError::OutOfRange);
704
12541135
        }
705
12541135
        if lo > hi {
706
1
            return Err(ParseError::Malformed);
707
12541134
        }
708
12541134
        let mask = bitrange(lo, hi);
709
        // Make sure that no version is included twice.
710
12541134
        if strictness == ParseStrictness::Strict && (supported & mask) != 0 {
711
3
            return Err(ParseError::Duplicate);
712
12541131
        }
713
        // Ignore bit 0, which can be set for non-strict bitmasks.
714
12541131
        let mask = mask & !1;
715
        // Add the appropriate bits to the mask.
716
12541131
        supported |= mask;
717
    }
718

            
719
12533864
    Ok(supported)
720
12533887
}
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.
725
impl SubprotocolEntry {
726
    /// Parse a [`SubprotocolEntry`] with a given level of strictness.
727
12532653
    fn from_str(s: &str, strictness: ParseStrictness) -> Result<Self, ParseError> {
728
        // split the string on the =.
729
12532653
        let (name, versions) = s.split_once('=').ok_or(ParseError::Malformed)?;
730

            
731
        // Look up the protocol by name.
732
12532652
        let proto: Protocol = name.parse()?;
733
        Ok(SubprotocolEntry {
734
12532652
            proto,
735
12532652
            supported: parse_version_mask(versions, strictness)?,
736
        })
737
12532653
    }
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.
752
impl std::str::FromStr for Protocols {
753
    type Err = ParseError;
754

            
755
854742
    fn from_str(s: &str) -> Result<Self, ParseError> {
756
854742
        Protocols::from_str_impl(s, ParseStrictness::Strict)
757
854742
    }
758
}
759

            
760
impl Protocols {
761
    /// Parse a [`Protocols`] with the requested degree of strictness.
762
1595686
    fn from_str_impl(s: &str, strictness: ParseStrictness) -> Result<Self, ParseError> {
763
1595686
        let mut result = ProtocolsInner::default();
764
1595686
        let mut foundmask = 0_u64;
765
1595686
        for ent in s.split(' ') {
766
12824312
            if ent.is_empty() {
767
291659
                continue;
768
12532653
            }
769

            
770
12532653
            let s = SubprotocolEntry::from_str(ent, strictness)?;
771
12532630
            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
1595661
        result.unrecognized.sort_by(|a, b| a.proto.cmp(&b.proto));
776
1595661
        match strictness {
777
            ParseStrictness::Strict => {
778
854717
                if result
779
854717
                    .unrecognized
780
854717
                    .windows(2)
781
665
                    .any(|w| w[0].proto == w[1].proto)
782
                {
783
2
                    return Err(ParseError::Duplicate);
784
854715
                }
785
            }
786
            ParseStrictness::CTorCompatible => {
787
740944
                result.unrecognized.dedup_by(|a, b| a.proto.eq(&b.proto));
788
            }
789
        }
790

            
791
1595659
        Ok(result.into())
792
1595686
    }
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
/// ```
808
109147
fn dumpmask(mut mask: u64) -> String {
809
    /// Helper: push a range (which may be a singleton) onto `v`.
810
109215
    fn append(v: &mut Vec<String>, lo: u32, hi: u32) {
811
109215
        if lo == hi {
812
42712
            v.push(lo.to_string());
813
        } else {
814
66503
            v.push(format!("{}-{}", lo, hi));
815
        }
816
109215
    }
817
    // We'll be building up our result here, then joining it with
818
    // commas.
819
109147
    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
109147
    let mut shift = 0;
827
218361
    while mask != 0 {
828
109215
        let zeros = mask.trailing_zeros();
829
109215
        mask >>= zeros;
830
109215
        shift += zeros;
831
109215
        let ones = mask.trailing_ones();
832
109215
        append(&mut result, shift, shift + ones - 1);
833
109215
        shift += ones;
834
109215
        if ones == 64 {
835
            // We have to do this check to avoid overflow when formatting
836
            // the range `0-63`.
837
1
            break;
838
109214
        }
839
109214
        mask >>= ones;
840
    }
841
109147
    result.join(",")
842
109147
}
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
/// ```
853
impl std::fmt::Display for Protocols {
854
21065
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
855
21065
        let mut entries = Vec::new();
856
21065
        for (pk, mask) in self.iter_masks() {
857
109142
            entries.push(format!("{}={}", pk, dumpmask(mask)));
858
        }
859
        // This sort is required.
860
21065
        entries.sort();
861
21065
        write!(f, "{}", entries.join(" "))
862
21065
    }
863
}
864

            
865
impl 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
68387
    fn iter_masks(&self) -> impl Iterator<Item = (ProtocolInner<'_>, u64)> + Clone {
871
68387
        chain!(
872
889057
            self.0.recognized.iter().enumerate().map(|(idx, mask)| {
873
889057
                let pk = ProtocolInner::Proto((idx as u8).into());
874
889057
                (pk, *mask)
875
889057
            }),
876
68387
            self.0
877
68387
                .unrecognized
878
68387
                .iter()
879
10670
                .map(|ent| (ent.proto.0.as_ref(), ent.supported)),
880
        )
881
899727
        .filter(|(_idx, mask)| *mask != 0)
882
68387
    }
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
47322
    pub fn iter_all(&self) -> impl Iterator<Item = (Protocol, Value)> + Clone {
905
53264
        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
6672
            Value::iter_all()
909
420336
                .filter(move |value| {
910
420336
                    let bit = value.to_bit();
911
420336
                    (mask & bit) != 0
912
420336
                })
913
9532
                .map(move |value| (Protocol(kind.clone().into_static()), value))
914
6672
        })
915
47322
    }
916
}
917

            
918
impl FromIterator<(Protocol, Value)> for Protocols {
919
138
    fn from_iter<I>(iter: I) -> Self
920
138
    where
921
138
        I: IntoIterator<Item = (Protocol, Value)>,
922
    {
923
138
        let mut out = BTreeMap::<Protocol, u64>::new();
924
138
        for (proto, value) in iter {
925
1892
            *out.entry(proto).or_default() |= value.to_bit();
926
        }
927
138
        let mut recognized = [0_u64; N_RECOGNIZED];
928
138
        let mut unrecognized = vec![];
929
138
        for (proto, supported) in out {
930
1110
            match proto.0 {
931
1086
                ProtocolInner::Proto(proto) => recognized[proto.get() as usize] = supported,
932
                ProtocolInner::Unrecognized(_) => {
933
24
                    unrecognized.push(SubprotocolEntry { proto, supported });
934
                }
935
            };
936
        }
937
138
        ProtocolsInner {
938
138
            recognized,
939
138
            unrecognized,
940
138
        }
941
138
        .into()
942
138
    }
943
}
944

            
945
impl FromIterator<NamedSubver> for Protocols {
946
17585
    fn from_iter<T: IntoIterator<Item = NamedSubver>>(iter: T) -> Self {
947
17585
        let mut r = ProtocolsInner::default();
948
17585
        for named_subver in iter {
949
126076
            let proto_idx = usize::from(named_subver.kind.get());
950
126076
            let proto_ver = named_subver.version;
951

            
952
            // These are guaranteed by invariants on NamedSubver.
953
126076
            assert!(proto_idx < N_RECOGNIZED);
954
126076
            r.recognized[proto_idx] |= proto_ver.to_bit();
955
        }
956
17585
        Protocols::from(r)
957
17585
    }
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.
979
pub 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
/// consensuses without it. Only once those consensuses are out is it safe to
/// remove from the list of required protocols.
///
/// ## Example
///
/// One concrete example of a very dangerous race that could occur:
///
/// Suppose that the client supports protocols "HsDir=1-2" and the consensus
/// requires protocols "HsDir=1-2".  If the client supported protocol list is
/// then changed to "HSDir=2", while the consensus stills lists "HSDir=1-2",
/// then these clients, even very recent ones, will shut down because they
/// don't support "HSDir=1".
///
/// And so, changes need to be done in strict sequence as described above.
pub mod doc_changing {}
#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use std::str::FromStr;
    use super::*;
    #[test]
    fn test_bitrange() {
        assert_eq!(0b1, bitrange(0, 0));
        assert_eq!(0b10, bitrange(1, 1));
        assert_eq!(0b11, bitrange(0, 1));
        assert_eq!(0b1111110000000, bitrange(7, 12));
        assert_eq!(!0, bitrange(0, 63));
    }
    #[test]
    fn test_dumpmask() {
        assert_eq!("", dumpmask(0));
        assert_eq!("0-5", dumpmask(0b111111));
        assert_eq!("4-5", dumpmask(0b110000));
        assert_eq!("1,4-5", dumpmask(0b110010));
        assert_eq!("0-63", dumpmask(!0));
    }
    #[test]
    fn test_canonical() -> Result<(), ParseError> {
        fn t(orig: &str, canonical: &str) -> Result<(), ParseError> {
            let protos: Protocols = orig.parse()?;
            let enc = format!("{}", protos);
            assert_eq!(enc, canonical);
            Ok(())
        }
        t("", "")?;
        t(" ", "")?;
        t("Link=5,6,7,9 Relay=4-7,2", "Link=5-7,9 Relay=2,4-7")?;
        t("FlowCtrl= Padding=8,7 Desc=1-5,6-8", "Desc=1-8 Padding=7-8")?;
        t("Zelda=7 Gannon=3,6 Link=4", "Gannon=3,6 Link=4 Zelda=7")?;
        Ok(())
    }
    #[test]
    fn test_invalid() {
        fn t(s: &str) -> ParseError {
            let protos: Result<Protocols, ParseError> = s.parse();
            assert!(protos.is_err());
            protos.err().unwrap()
        }
        assert_eq!(t("Link=1-100"), ParseError::OutOfRange);
        assert_eq!(t("Zelda=100"), ParseError::OutOfRange);
        assert_eq!(t("Link=100-200"), ParseError::OutOfRange);
        assert_eq!(t("Link=1,1"), ParseError::Duplicate);
        assert_eq!(t("Link=1 Link=1"), ParseError::Duplicate);
        assert_eq!(t("Link=1 Link=3"), ParseError::Duplicate);
        assert_eq!(t("Zelda=1 Zelda=3"), ParseError::Duplicate);
        assert_eq!(t("Link=Zelda"), ParseError::Malformed);
        assert_eq!(t("Link=6-2"), ParseError::Malformed);
        assert_eq!(t("Link=6-"), ParseError::Malformed);
        assert_eq!(t("Link=6-,2"), ParseError::Malformed);
        assert_eq!(t("Link=1,,2"), ParseError::Malformed);
        assert_eq!(t("Link=6-frog"), ParseError::Malformed);
        assert_eq!(t("Link=gannon-9"), ParseError::Malformed);
        assert_eq!(t("Link Zelda"), ParseError::Malformed);
        assert_eq!(t("Link=01"), ParseError::Malformed);
        assert_eq!(t("Link=waffle"), ParseError::Malformed);
        assert_eq!(t("Link=1_1"), ParseError::Malformed);
    }
    #[test]
    fn test_ctor_compat() {
        for (loose, strict) in &[
            // With duplicate entries, those after the first are ignored
            ("Link=0-10 Link=25-30", "Link=1-10"),
            ("Link=25-30 Link=0-10", "Link=25-30"),
            ("Zelda=6-8 Link=1-10 Zelda=6-10", "Link=1-10 Zelda=6-8"),
            // The 0 bit and any 0 prefixes are ignored.
            ("LinkAuth=0-00040", "LinkAuth=1-40"),
            ("Foo=0,3,004,5,0010", "Foo=3-5,10"),
            // Duplicate bits are permitted
            ("Foo=1-10,2-20,3-5", "Foo=1-20"),
            ("Link=1-10,2-20,3-5", "Link=1-20"),
            // Value zero is invalid and discarded
            ("Link=0-1", "Link=1"),
            ("Link=0", ""),
        ] {
            let p1 = Protocols::from_str_c_compatible(loose).unwrap();
            let p2 = Protocols::from_str(strict).unwrap();
            assert_eq!(p1, p2);
            assert!(Protocols::from_str(loose).is_err());
        }
    }
    #[test]
    fn test_supports() -> Result<(), ParseError> {
        let p: Protocols = "Link=4,5-7 Padding=2 Lonk=1-3,5".parse()?;
        assert!(p.supports_known_subver(ProtoKind::Padding, 2));
        assert!(!p.supports_known_subver(ProtoKind::Padding, 1));
        assert!(p.supports_known_subver(ProtoKind::Link, 6));
        assert!(!p.supports_known_subver(ProtoKind::Link, 255));
        assert!(!p.supports_known_subver(ProtoKind::Cons, 1));
        assert!(!p.supports_known_subver(ProtoKind::Cons, 0));
        assert!(p.supports_subver("Link", 6));
        assert!(!p.supports_subver("link", 6));
        assert!(!p.supports_subver("Cons", 0));
        assert!(p.supports_subver("Lonk", 3));
        assert!(!p.supports_subver("Lonk", 4));
        assert!(!p.supports_subver("lonk", 3));
        assert!(!p.supports_subver("Lonk", 64));
        Ok(())
    }
    #[test]
    fn test_difference() -> Result<(), ParseError> {
        let p1: Protocols = "Link=1-10 Desc=5-10 Relay=1,3,5,7,9 Other=7-60 Mine=1-20".parse()?;
        let p2: Protocols = "Link=3-4 Desc=1-6 Relay=2-6 Other=8 Theirs=20".parse()?;
        assert_eq!(
            p1.difference(&p2),
            Protocols::from_str("Link=1-2,5-10 Desc=7-10 Relay=1,7,9 Other=7,9-60 Mine=1-20")?
        );
        assert_eq!(
            p2.difference(&p1),
            Protocols::from_str("Desc=1-4 Relay=2,4,6 Theirs=20")?,
        );
        let nil = Protocols::default();
        assert_eq!(p1.difference(&nil), p1);
        assert_eq!(p2.difference(&nil), p2);
        assert_eq!(nil.difference(&p1), nil);
        assert_eq!(nil.difference(&p2), nil);
        Ok(())
    }
    #[test]
    fn test_union() -> Result<(), ParseError> {
        let p1: Protocols = "Link=1-10 Desc=5-10 Relay=1,3,5,7,9 Other=7-60 Mine=1-20".parse()?;
        let p2: Protocols = "Link=3-4 Desc=1-6 Relay=2-6 Other=2,8 Theirs=20".parse()?;
        assert_eq!(
            p1.union(&p2),
            Protocols::from_str(
                "Link=1-10 Desc=1-10 Relay=1-7,9 Other=2,7-60 Theirs=20 Mine=1-20"
            )?
        );
        assert_eq!(
            p2.union(&p1),
            Protocols::from_str(
                "Link=1-10 Desc=1-10 Relay=1-7,9 Other=2,7-60 Theirs=20 Mine=1-20"
            )?
        );
        let nil = Protocols::default();
        assert_eq!(p1.union(&nil), p1);
        assert_eq!(p2.union(&nil), p2);
        assert_eq!(nil.union(&p1), p1);
        assert_eq!(nil.union(&p2), p2);
        Ok(())
    }
    #[test]
    fn test_intersection() -> Result<(), ParseError> {
        let p1: Protocols = "Link=1-10 Desc=5-10 Relay=1,3,5,7,9 Other=7-60 Mine=1-20".parse()?;
        let p2: Protocols = "Link=3-4 Desc=1-6 Relay=2-6 Other=2,8 Theirs=20".parse()?;
        assert_eq!(
            p1.intersection(&p2),
            Protocols::from_str("Link=3-4 Desc=5-6 Relay=3,5 Other=8")?
        );
        assert_eq!(
            p2.intersection(&p1),
            Protocols::from_str("Link=3-4 Desc=5-6 Relay=3,5 Other=8")?
        );
        let nil = Protocols::default();
        assert_eq!(p1.intersection(&nil), nil);
        assert_eq!(p2.intersection(&nil), nil);
        assert_eq!(nil.intersection(&p1), nil);
        assert_eq!(nil.intersection(&p2), nil);
        Ok(())
    }
    #[test]
    fn from_iter() {
        use named as n;
        let empty: [NamedSubver; 0] = [];
        let prs: Protocols = empty.iter().copied().collect();
        assert_eq!(prs, Protocols::default());
        let prs: Protocols = empty.into_iter().collect();
        assert_eq!(prs, Protocols::default());
        let prs = [
            n::LINK_V3,
            n::HSDIR_V3,
            n::LINK_V4,
            n::LINK_V5,
            n::CONFLUX_BASE,
        ]
        .into_iter()
        .collect::<Protocols>();
        assert_eq!(prs, "Link=3-5 HSDir=2 Conflux=1".parse().unwrap());
    }
    #[test]
    fn from_iter_all() -> Result<(), ParseError> {
        let p1: Protocols = "Link=1-10 Desc=5-10 Relay=1,3,5,7,9 Other=7-60 Mine=1-20".parse()?;
        let p2 = p1.iter_all().collect::<Protocols>();
        assert_eq!(p1, p2);
        let p3 = std::iter::repeat_n(p1.iter_all(), 3)
            .flatten()
            .collect::<Protocols>();
        assert_eq!(p1, p3);
        Ok(())
    }
    #[test]
    fn order_numbered_subvers() {
        // We rely on this sort order elsewhere in our protocol.
        assert!(NumberedSubver::new(5, 7) < NumberedSubver::new(7, 5));
        assert!(NumberedSubver::new(7, 5) < NumberedSubver::new(7, 6));
        assert!(NumberedSubver::new(7, 6) < NumberedSubver::new(8, 6));
    }
}