Skip to main content

stem/descriptor/
network_status.rs

1use std::cmp::Ordering;
2
3use chrono::{NaiveDateTime, Utc};
4use indexmap::IndexMap;
5use sha1::{Digest, Sha1};
6
7use crate::address::{is_valid_ipv4_address, parse_port};
8use crate::descriptor::router_status::{
9    DocumentContext, RouterStatusEntryCommon, RouterStatusEntryMicroV3,
10    RouterStatusEntryV2, RouterStatusEntryV3, parse_entry_section,
11};
12use crate::descriptor::server::digest_for_signature;
13use crate::descriptor::{
14    AttrValue, Attributes, DigestEncoding, DigestHash, Entries, LineCursor, Protocols,
15    ReadOptions, attr, content_range, descriptor_components, descriptor_content,
16    encode_digest, hash_bytes, key_block, lenient, lenient_option, mappings_for,
17    parse_forty_hex, parse_protocol_line, parse_timestamp_line, random_crypto_blob,
18    random_date, random_fingerprint, random_ipv4_address, random_nickname,
19};
20use crate::error::{Error, Result};
21use crate::formatting::parse_timestamp;
22use crate::validation::{is_valid_fingerprint, is_valid_nickname};
23use crate::version::Version;
24
25const AUTH_START: &str = "dir-source";
26const ROUTERS_START: &str = "r";
27const FOOTER_START: &str = "directory-footer";
28const V2_FOOTER_START: &str = "directory-signature";
29
30const NETWORK_STATUS_V2_FIELDS: [(&str, bool); 10] = [
31    ("network-status-version", true),
32    ("dir-source", true),
33    ("fingerprint", true),
34    ("contact", true),
35    ("dir-signing-key", true),
36    ("client-versions", false),
37    ("server-versions", false),
38    ("published", true),
39    ("dir-options", false),
40    ("directory-signature", true),
41];
42
43struct HeaderField(&'static str, bool, bool, bool);
44
45const HEADER_FIELDS: [HeaderField; 25] = [
46    HeaderField("network-status-version", true, true, true),
47    HeaderField("vote-status", true, true, true),
48    HeaderField("consensus-methods", true, false, false),
49    HeaderField("consensus-method", false, true, false),
50    HeaderField("published", true, false, true),
51    HeaderField("valid-after", true, true, true),
52    HeaderField("fresh-until", true, true, true),
53    HeaderField("valid-until", true, true, true),
54    HeaderField("voting-delay", true, true, true),
55    HeaderField("client-versions", true, true, false),
56    HeaderField("server-versions", true, true, false),
57    HeaderField("package", true, true, false),
58    HeaderField("known-flags", true, true, true),
59    HeaderField("flag-thresholds", true, false, false),
60    HeaderField("shared-rand-participate", true, false, false),
61    HeaderField("shared-rand-commit", true, false, false),
62    HeaderField("shared-rand-previous-value", true, true, false),
63    HeaderField("shared-rand-current-value", true, true, false),
64    HeaderField("bandwidth-file-headers", true, false, false),
65    HeaderField("bandwidth-file-digest", true, false, false),
66    HeaderField("recommended-client-protocols", true, true, false),
67    HeaderField("recommended-relay-protocols", true, true, false),
68    HeaderField("required-client-protocols", true, true, false),
69    HeaderField("required-relay-protocols", true, true, false),
70    HeaderField("params", true, true, false),
71];
72
73const FOOTER_FIELDS: [HeaderField; 3] = [
74    HeaderField("directory-footer", true, true, false),
75    HeaderField("bandwidth-weights", false, true, false),
76    HeaderField("directory-signature", true, true, true),
77];
78
79const KEY_CERTIFICATE_PARAMS: [(&str, bool); 9] = [
80    ("dir-key-certificate-version", true),
81    ("dir-address", false),
82    ("fingerprint", true),
83    ("dir-identity-key", true),
84    ("dir-key-published", true),
85    ("dir-key-expires", true),
86    ("dir-signing-key", true),
87    ("dir-key-crosscert", false),
88    ("dir-key-certification", true),
89];
90
91const DETACHED_SIGNATURE_PARAMS: [(&str, bool, bool); 7] = [
92    ("consensus-digest", true, false),
93    ("valid-after", true, false),
94    ("fresh-until", true, false),
95    ("valid-until", true, false),
96    ("additional-digest", false, true),
97    ("additional-signature", false, true),
98    ("directory-signature", false, true),
99];
100
101const DEFAULT_PARAMS: [(&str, i64); 24] = [
102    ("bwweightscale", 10000),
103    ("cbtdisabled", 0),
104    ("cbtnummodes", 3),
105    ("cbtrecentcount", 20),
106    ("cbtmaxtimeouts", 18),
107    ("cbtmincircs", 100),
108    ("cbtquantile", 80),
109    ("cbtclosequantile", 95),
110    ("cbttestfreq", 60),
111    ("cbtmintimeout", 2000),
112    ("cbtinitialtimeout", 60000),
113    ("cbtlearntimeout", 180),
114    ("cbtmaxopencircs", 10),
115    ("UseOptimisticData", 1),
116    ("Support022HiddenServices", 1),
117    ("usecreatefast", 1),
118    ("max-consensuses-age-to-cache-for-diff", 72),
119    ("try-diff-for-consensus-newer-than", 72),
120    ("onion-key-rotation-days", 28),
121    ("onion-key-grace-period-days", 7),
122    ("hs_service_max_rdv_failures", 2),
123    ("circ_max_cell_queue_size", 50000),
124    ("circpad_max_circ_queued_cells", 1000),
125    ("HiddenServiceEnableIntroDoSDefense", 0),
126];
127
128const MIN_PARAM: i64 = -2147483648;
129const MAX_PARAM: i64 = 2147483647;
130
131fn param_range(key: &str) -> (i64, i64) {
132    match key {
133        "circwindow" => (100, 1000),
134        "CircuitPriorityHalflifeMsec" | "perconnbwrate" | "perconnbwburst" => {
135            (-1, MAX_PARAM)
136        }
137        "refuseunknownexits"
138        | "cbtdisabled"
139        | "UseOptimisticData"
140        | "Support022HiddenServices"
141        | "usecreatefast"
142        | "UseNTorHandshake"
143        | "AllowNonearlyExtend"
144        | "HiddenServiceEnableIntroDoSDefense" => (0, 1),
145        "bwweightscale" | "cbttestfreq" | "AuthDirNumSRVAgreements" => (1, MAX_PARAM),
146        "cbtnummodes" => (1, 20),
147        "cbtrecentcount" => (3, 1000),
148        "cbtmaxtimeouts" => (3, 10000),
149        "cbtmincircs" => (1, 10000),
150        "cbtquantile" => (10, 99),
151        "cbtclosequantile" => (MIN_PARAM, 99),
152        "cbtmintimeout" => (500, MAX_PARAM),
153        "cbtlearntimeout" => (10, 60000),
154        "cbtmaxopencircs" => (0, 14),
155        "FastFlagMinThreshold" => (4, MAX_PARAM),
156        "NumDirectoryGuards" => (0, 10),
157        "NumEntryGuards" => (1, 10),
158        "GuardLifetime" => (2592000, 157766400),
159        "NumNTorsPerTAP" => (1, 100000),
160        "max-consensuses-age-to-cache-for-diff" | "try-diff-for-consensus-newer-than" => {
161            (0, 8192)
162        }
163        "onion-key-rotation-days" | "onion-key-grace-period-days" => (1, 90),
164        "hs_service_max_rdv_failures" => (1, 10),
165        "circ_max_cell_queue_size" => (1000, 4294967295),
166        "circpad_max_circ_queued_cells" => (0, 50000),
167        _ => (MIN_PARAM, MAX_PARAM),
168    }
169}
170
171#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
172pub struct PackageVersion {
173    pub name: String,
174    pub version: String,
175    pub url: String,
176    pub digests: IndexMap<String, String>,
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
180pub struct SharedRandomnessCommitment {
181    pub version: u32,
182    pub algorithm: String,
183    pub identity: String,
184    pub commit: String,
185    pub reveal: Option<String>,
186}
187
188#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
189pub struct DocumentDigest {
190    pub flavor: String,
191    pub algorithm: String,
192    pub digest: String,
193}
194
195#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
196pub struct DocumentSignature {
197    pub method: String,
198    pub identity: String,
199    pub key_digest: String,
200    pub signature: String,
201    pub flavor: Option<String>,
202}
203
204impl DocumentSignature {
205    pub fn new(
206        method: &str,
207        identity: &str,
208        key_digest: &str,
209        signature: &str,
210        flavor: Option<&str>,
211        validate: bool,
212    ) -> Result<Self> {
213        if validate {
214            if !is_valid_fingerprint(identity, false) {
215                return Err(Error::parse(format!(
216                    "Malformed fingerprint ({identity}) in the document signature"
217                )));
218            }
219            if !is_valid_fingerprint(key_digest, false) {
220                return Err(Error::parse(format!(
221                    "Malformed key digest ({key_digest}) in the document signature"
222                )));
223            }
224        }
225        Ok(Self {
226            method: method.to_string(),
227            identity: identity.to_string(),
228            key_digest: key_digest.to_string(),
229            signature: signature.to_string(),
230            flavor: flavor.map(str::to_string),
231        })
232    }
233}
234
235impl PartialOrd for DocumentSignature {
236    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
237        Some(
238            (
239                &self.method,
240                &self.identity,
241                &self.key_digest,
242                &self.signature,
243                &self.flavor,
244            )
245                .cmp(&(
246                    &other.method,
247                    &other.identity,
248                    &other.key_digest,
249                    &other.signature,
250                    &other.flavor,
251                )),
252        )
253    }
254}
255
256fn parse_version_line(entries: &Entries, keyword: &str, expected: u32) -> Result<u32> {
257    let value = entries.value(keyword)?;
258    let version: u32 = value
259        .parse()
260        .ok()
261        .filter(|_| value.bytes().all(|byte| byte.is_ascii_digit()))
262        .ok_or_else(|| {
263            Error::parse(format!(
264                "Document has a non-numeric version: {keyword} {value}"
265            ))
266        })?;
267    match version == expected {
268        true => Ok(version),
269        false => Err(Error::parse(format!(
270            "Expected a version {expected} document, but got version '{value}' instead"
271        ))),
272    }
273}
274
275fn parse_int_mappings(
276    keyword: &str,
277    value: &str,
278    validate: bool,
279) -> Result<IndexMap<String, i64>> {
280    let mut results = IndexMap::new();
281    let mut seen: Vec<String> = Vec::new();
282    let template = |reason: &str| {
283        format!(
284            "Unable to parse network status document's '{keyword}' line ({reason}): \
285            {value}'"
286        )
287    };
288    for (key, mapped) in mappings_for(keyword, value, false, ' ')? {
289        if validate && seen.iter().any(|prior| *prior > key) {
290            return Err(Error::parse(template(
291                "parameters must be sorted by their key",
292            )));
293        }
294        if mapped.starts_with('+') {
295            return Err(Error::parse(template(&format!(
296                "'{mapped}' is a non-numeric value"
297            ))));
298        }
299        let number = mapped.parse::<i64>().map_err(|_| {
300            Error::parse(template(&format!("'{mapped}' is a non-numeric value")))
301        })?;
302        seen.push(key.clone());
303        results.insert(key, number);
304    }
305    Ok(results)
306}
307
308fn unsigned(text: &str) -> Option<u32> {
309    match !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit()) {
310        true => text.parse().ok(),
311        false => None,
312    }
313}
314
315fn parse_packages(entries: &Entries) -> Result<Vec<PackageVersion>> {
316    let mut packages = Vec::new();
317    for value in entries.values("package") {
318        let parts: Vec<&str> = value.splitn(4, ' ').collect();
319        if parts.len() < 3 {
320            return Err(Error::parse(format!(
321                "'package' must at least have a 'PackageName Version URL': {value}"
322            )));
323        }
324        let digests = match parts.get(3) {
325            Some(rest) => mappings_for("package", rest, false, ' ')?
326                .into_iter()
327                .collect(),
328            None => IndexMap::new(),
329        };
330        packages.push(PackageVersion {
331            name: parts[0].to_string(),
332            version: parts[1].to_string(),
333            url: parts[2].to_string(),
334            digests,
335        });
336    }
337    Ok(packages)
338}
339
340fn parse_shared_rand_commits(
341    entries: &Entries,
342) -> Result<Vec<SharedRandomnessCommitment>> {
343    let mut commitments = Vec::new();
344    for value in entries.values("shared-rand-commit") {
345        let parts: Vec<&str> = value.split_whitespace().collect();
346        if parts.len() < 4 {
347            return Err(Error::parse(format!(
348                "'shared-rand-commit' must at least have a 'Version AlgName Identity \
349                Commit': {value}"
350            )));
351        }
352        let version = unsigned(parts[0]).ok_or_else(|| {
353            Error::parse(format!(
354                "The version on our 'shared-rand-commit' line wasn't an integer: {value}"
355            ))
356        })?;
357        commitments.push(SharedRandomnessCommitment {
358            version,
359            algorithm: parts[1].to_string(),
360            identity: parts[2].to_string(),
361            commit: parts[3].to_string(),
362            reveal: parts.get(4).map(|reveal| reveal.to_string()),
363        });
364    }
365    Ok(commitments)
366}
367
368fn parse_shared_rand_value(entries: &Entries, keyword: &str) -> Result<(u32, String)> {
369    let value = entries.value(keyword)?;
370    let parts: Vec<&str> = value.split(' ').collect();
371    match parts.as_slice() {
372        [count, text] if unsigned(count).is_some() => {
373            Ok((unsigned(count).unwrap_or(0), text.to_string()))
374        }
375        _ => Err(Error::parse(format!(
376            "A network status document's '{keyword}' line must be a pair of values, the \
377            first an integer but was '{value}'"
378        ))),
379    }
380}
381
382fn parse_signatures(entries: &Entries, keyword: &str) -> Result<Vec<DocumentSignature>> {
383    let mut signatures = Vec::new();
384    for entry in entries.get(keyword).unwrap_or_default() {
385        let spaces = entry.value.matches(' ').count();
386        if !(1..=2).contains(&spaces) {
387            return Err(Error::parse(format!(
388                "Authority signatures in a network status document are expected to be \
389                of the form 'directory-signature [METHOD] FINGERPRINT KEY_DIGEST', \
390                received: {}",
391                entry.value
392            )));
393        }
394        let (Some(block), Some("SIGNATURE")) =
395            (&entry.block_contents, entry.block_type.as_deref())
396        else {
397            return Err(Error::parse(format!(
398                "'directory-signature' should be followed by a SIGNATURE block, but was \
399                a {}",
400                entry.block_type.as_deref().unwrap_or("None")
401            )));
402        };
403        let parts: Vec<&str> = entry.value.splitn(3, ' ').collect();
404        let (method, fingerprint, key_digest) = match parts.as_slice() {
405            [fingerprint, key_digest] => ("sha1", *fingerprint, *key_digest),
406            [method, fingerprint, key_digest] => (*method, *fingerprint, *key_digest),
407            _ => unreachable!("one or two spaces were checked"),
408        };
409        signatures.push(DocumentSignature::new(
410            method,
411            fingerprint,
412            key_digest,
413            block,
414            None,
415            true,
416        )?);
417    }
418    Ok(signatures)
419}
420
421fn parse_flag_thresholds(entries: &Entries) -> Result<IndexMap<String, f64>> {
422    let value = entries.value("flag-thresholds")?.trim();
423    let mut thresholds = IndexMap::new();
424    let invalid = || {
425        Error::parse(format!(
426            "Network status document's 'flag-thresholds' line is expected to have float \
427            values, got: flag-thresholds {value}"
428        ))
429    };
430    for (key, mapped) in mappings_for("flag-thresholds", value, false, ' ')? {
431        let number = match mapped.strip_suffix('%') {
432            Some(percentage) => percentage.parse::<f64>().map_err(|_| invalid())? / 100.0,
433            None => mapped.parse::<f64>().map_err(|_| invalid())?,
434        };
435        thresholds.insert(key, number);
436    }
437    Ok(thresholds)
438}
439
440fn parse_versions(entries: &Entries, keyword: &str) -> Result<Vec<Version>> {
441    let value = entries.value(keyword)?;
442    value
443        .split(',')
444        .map(|entry| {
445            Version::new(entry).map_err(|_| {
446                Error::parse(format!(
447                    "Network status document's '{keyword}' line had '{entry}', which \
448                    isn't a parsable tor version: {keyword} {value}"
449                ))
450            })
451        })
452        .collect()
453}
454
455fn check_missing_and_disallowed(
456    is_vote: bool,
457    entries: &Entries,
458    fields: &[HeaderField],
459) -> Result<()> {
460    let is_consensus = !is_vote;
461    let (mut missing, mut disallowed) = (Vec::new(), Vec::new());
462    for HeaderField(field, in_votes, in_consensus, mandatory) in fields {
463        let applies = (is_consensus && *in_consensus) || (is_vote && *in_votes);
464        if *mandatory && applies {
465            if !entries.contains(field) {
466                missing.push(*field);
467            }
468        } else if ((is_consensus && !in_consensus) || (is_vote && !in_votes))
469            && entries.contains(field)
470        {
471            disallowed.push(*field);
472        }
473    }
474    if !missing.is_empty() {
475        return Err(Error::parse(format!(
476            "Network status document is missing mandatory field: {}",
477            missing.join(", ")
478        )));
479    }
480    match disallowed.is_empty() {
481        true => Ok(()),
482        false => Err(Error::parse(format!(
483            "Network status document has fields that shouldn't appear in this document \
484            type or version: {}",
485            disallowed.join(", ")
486        ))),
487    }
488}
489
490#[derive(Debug, Clone, PartialEq, serde::Serialize)]
491#[serde(untagged)]
492pub enum RouterEntry {
493    Full(RouterStatusEntryV3),
494    Micro(RouterStatusEntryMicroV3),
495}
496
497impl RouterEntry {
498    pub fn common(&self) -> &RouterStatusEntryCommon {
499        match self {
500            Self::Full(entry) => &entry.common,
501            Self::Micro(entry) => &entry.common,
502        }
503    }
504
505    pub fn bandwidth(&self) -> Option<u64> {
506        match self {
507            Self::Full(entry) => entry.bandwidth,
508            Self::Micro(entry) => entry.bandwidth,
509        }
510    }
511}
512
513#[derive(Debug, Clone, PartialEq, serde::Serialize)]
514pub struct KeyCertificate {
515    #[serde(skip)]
516    pub raw_contents: Vec<u8>,
517    pub unrecognized_lines: Vec<String>,
518    pub version: Option<u32>,
519    pub address: Option<String>,
520    pub dir_port: Option<u16>,
521    pub fingerprint: Option<String>,
522    pub identity_key: Option<String>,
523    pub published: Option<NaiveDateTime>,
524    pub expires: Option<NaiveDateTime>,
525    pub signing_key: Option<String>,
526    pub crosscert: Option<String>,
527    pub certification: Option<String>,
528}
529
530impl KeyCertificate {
531    pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
532        let (entries, _) = descriptor_components(content, validate, &[], &[])?;
533        let raw = String::from_utf8_lossy(content);
534        if validate {
535            if entries.first_key() != Some("dir-key-certificate-version") {
536                return Err(Error::parse(format!(
537                    "Key certificates must start with a 'dir-key-certificate-version' \
538                    line:\n{raw}"
539                )));
540            }
541            if entries.last_key() != Some("dir-key-certification") {
542                return Err(Error::parse(format!(
543                    "Key certificates must end with a 'dir-key-certification' \
544                    line:\n{raw}"
545                )));
546            }
547            for (keyword, mandatory) in KEY_CERTIFICATE_PARAMS {
548                if mandatory && !entries.contains(keyword) {
549                    return Err(Error::parse(format!(
550                        "Key certificates must have a '{keyword}' line:\n{raw}"
551                    )));
552                }
553                let count = entries.get(keyword).map_or(0, <[_]>::len);
554                if count > 1 {
555                    return Err(Error::parse(format!(
556                        "Key certificates can only have a single '{keyword}' line, got \
557                        {count}:\n{raw}"
558                    )));
559                }
560            }
561        }
562        let recognized: Vec<&str> = KEY_CERTIFICATE_PARAMS
563            .iter()
564            .map(|(keyword, _)| *keyword)
565            .collect();
566        let mut certificate = Self {
567            raw_contents: content.to_vec(),
568            unrecognized_lines: entries.unrecognized_lines(&recognized),
569            version: None,
570            address: None,
571            dir_port: None,
572            fingerprint: None,
573            identity_key: None,
574            published: None,
575            expires: None,
576            signing_key: None,
577            crosscert: None,
578            certification: None,
579        };
580        if entries.contains("dir-key-certificate-version") {
581            certificate.version = lenient_option(
582                validate,
583                parse_version_line(&entries, "dir-key-certificate-version", 3),
584            )?;
585        }
586        if let Ok(value) = entries.value("dir-address") {
587            let parsed = value
588                .rsplit_once(':')
589                .ok_or_else(|| {
590                    Error::parse(format!(
591                        "Key certificate's 'dir-address' is expected to be of the form \
592                        ADDRESS:PORT: dir-address {value}"
593                    ))
594                })
595                .and_then(|(address, port)| {
596                    match (is_valid_ipv4_address(address), parse_port(port, false)) {
597                        (true, Some(port)) => Ok((address.to_string(), port)),
598                        (false, _) => Err(Error::parse(format!(
599                            "Key certificate's address isn't a valid IPv4 address: \
600                        dir-address {value}"
601                        ))),
602                        _ => Err(Error::parse(format!(
603                            "Key certificate's dirport is \
604                        invalid: dir-address {value}"
605                        ))),
606                    }
607                });
608            if let Some((address, port)) = lenient_option(validate, parsed)? {
609                certificate.address = Some(address);
610                certificate.dir_port = Some(port);
611            }
612        }
613        if let Ok(value) = entries.value("fingerprint") {
614            certificate.fingerprint =
615                lenient_option(validate, parse_forty_hex("fingerprint", value))?;
616        }
617        for (keyword, kind, target) in [
618            (
619                "dir-identity-key",
620                "RSA PUBLIC KEY",
621                &mut certificate.identity_key,
622            ),
623            (
624                "dir-signing-key",
625                "RSA PUBLIC KEY",
626                &mut certificate.signing_key,
627            ),
628            (
629                "dir-key-crosscert",
630                "ID SIGNATURE",
631                &mut certificate.crosscert,
632            ),
633            (
634                "dir-key-certification",
635                "SIGNATURE",
636                &mut certificate.certification,
637            ),
638        ] {
639            if entries.contains(keyword) {
640                *target = lenient_option(
641                    validate,
642                    key_block(&entries, keyword, kind).map(|(_, block)| block),
643                )?;
644            }
645        }
646        for (keyword, target) in [
647            ("dir-key-published", &mut certificate.published),
648            ("dir-key-expires", &mut certificate.expires),
649        ] {
650            if let Ok(value) = entries.value(keyword) {
651                *target = lenient_option(validate, parse_timestamp_line(keyword, value))?;
652            }
653        }
654        Ok(certificate)
655    }
656
657    pub fn parse_many(content: &[u8], validate: bool) -> Result<Vec<Self>> {
658        let mut cursor = LineCursor::new(content);
659        let mut certificates = Vec::new();
660        loop {
661            let mut body = cursor
662                .read_until_keywords(&["dir-key-certification"], ReadOptions::default())
663                .content;
664            body.extend(
665                cursor
666                    .read_until_keywords(
667                        &["-----END"],
668                        ReadOptions {
669                            inclusive: true,
670                            ..Default::default()
671                        },
672                    )
673                    .content,
674            );
675            if body.is_empty() {
676                break;
677            }
678            certificates.push(Self::parse(&body, validate)?);
679        }
680        Ok(certificates)
681    }
682
683    pub fn content(attributes: &Attributes, exclude: &[&str]) -> Vec<u8> {
684        descriptor_content(
685            attributes,
686            exclude,
687            &[
688                (
689                    "dir-key-certificate-version",
690                    AttrValue::Text("3".to_string()),
691                ),
692                ("fingerprint", AttrValue::Text(random_fingerprint())),
693                ("dir-key-published", AttrValue::Text(random_date())),
694                ("dir-key-expires", AttrValue::Text(random_date())),
695                (
696                    "dir-identity-key",
697                    AttrValue::Text(random_crypto_blob(Some("RSA PUBLIC KEY"))),
698                ),
699                (
700                    "dir-signing-key",
701                    AttrValue::Text(random_crypto_blob(Some("RSA PUBLIC KEY"))),
702                ),
703            ],
704            &[(
705                "dir-key-certification",
706                AttrValue::Text(random_crypto_blob(Some("SIGNATURE"))),
707            )],
708        )
709    }
710
711    pub fn create(
712        attributes: &Attributes,
713        exclude: &[&str],
714        validate: bool,
715    ) -> Result<Self> {
716        Self::parse(&Self::content(attributes, exclude), validate)
717    }
718}
719
720#[derive(Debug, Clone, PartialEq, serde::Serialize)]
721pub struct DirectoryAuthority {
722    #[serde(skip)]
723    pub raw_contents: Vec<u8>,
724    pub unrecognized_lines: Vec<String>,
725    pub nickname: Option<String>,
726    pub v3ident: Option<String>,
727    pub fingerprint: Option<String>,
728    pub hostname: Option<String>,
729    pub address: Option<String>,
730    pub dir_port: Option<u16>,
731    pub or_port: Option<u16>,
732    pub is_legacy: bool,
733    pub contact: Option<String>,
734    pub vote_digest: Option<String>,
735    pub legacy_dir_key: Option<String>,
736    pub is_shared_randomness_participate: bool,
737    pub shared_randomness_commitments: Vec<SharedRandomnessCommitment>,
738    pub shared_randomness_previous_reveal_count: Option<u32>,
739    pub shared_randomness_previous_value: Option<String>,
740    pub shared_randomness_current_reveal_count: Option<u32>,
741    pub shared_randomness_current_value: Option<String>,
742    pub key_certificate: Option<KeyCertificate>,
743}
744
745struct DirSource {
746    nickname: String,
747    v3ident: String,
748    hostname: String,
749    address: String,
750    dir_port: Option<u16>,
751    or_port: u16,
752}
753
754fn parse_dirauth_source(entries: &Entries) -> Result<DirSource> {
755    let value = entries.value("dir-source")?;
756    let parts: Vec<&str> = value.split(' ').collect();
757    if parts.len() < 6 {
758        return Err(Error::parse(format!(
759            "Authority entry's 'dir-source' line must have six values: dir-source {value}"
760        )));
761    }
762    if !is_valid_nickname(parts[0].trim_end_matches(['-', 'l', 'e', 'g', 'a', 'c', 'y']))
763    {
764        return Err(Error::parse(format!(
765            "Authority's nickname is invalid: {}",
766            parts[0]
767        )));
768    }
769    if !is_valid_fingerprint(parts[1], false) {
770        return Err(Error::parse(format!(
771            "Authority's v3ident is invalid: {}",
772            parts[1]
773        )));
774    }
775    if parts[2].is_empty() {
776        return Err(Error::parse(format!(
777            "Authority's hostname can't be blank: dir-source {value}"
778        )));
779    }
780    if !is_valid_ipv4_address(parts[3]) {
781        return Err(Error::parse(format!(
782            "Authority's address isn't a valid IPv4 address: {}",
783            parts[3]
784        )));
785    }
786    let dir_port = parse_port(parts[4], true).ok_or_else(|| {
787        Error::parse(format!("Authority's DirPort is invalid: {}", parts[4]))
788    })?;
789    let or_port = parse_port(parts[5], false).ok_or_else(|| {
790        Error::parse(format!("Authority's ORPort is invalid: {}", parts[5]))
791    })?;
792    Ok(DirSource {
793        nickname: parts[0].to_string(),
794        v3ident: parts[1].to_string(),
795        hostname: parts[2].to_string(),
796        address: parts[3].to_string(),
797        dir_port: Some(dir_port).filter(|port| *port != 0),
798        or_port,
799    })
800}
801
802impl DirectoryAuthority {
803    pub fn parse(content: &[u8], validate: bool, is_vote: bool) -> Result<Self> {
804        let text = String::from_utf8_lossy(content).into_owned();
805        let (key_certificate, authority_content) =
806            match text.find("\ndir-key-certificate-version") {
807                Some(split) => (
808                    Some(KeyCertificate::parse(
809                        &text.as_bytes()[split + 1..],
810                        validate,
811                    )?),
812                    text[..split + 1].to_string(),
813                ),
814                None => (None, text.clone()),
815            };
816        let (entries, _) =
817            descriptor_components(authority_content.as_bytes(), validate, &[], &[])?;
818        if validate {
819            Self::check_constraints(
820                &entries,
821                &authority_content,
822                is_vote,
823                key_certificate.is_some(),
824            )?;
825        }
826        let recognized = [
827            "dir-source",
828            "contact",
829            "legacy-dir-key",
830            "vote-digest",
831            "shared-rand-participate",
832            "shared-rand-commit",
833            "shared-rand-previous-value",
834            "shared-rand-current-value",
835        ];
836        let mut authority = Self {
837            raw_contents: content.to_vec(),
838            unrecognized_lines: entries.unrecognized_lines(&recognized),
839            nickname: None,
840            v3ident: None,
841            fingerprint: None,
842            hostname: None,
843            address: None,
844            dir_port: None,
845            or_port: None,
846            is_legacy: false,
847            contact: None,
848            vote_digest: None,
849            legacy_dir_key: None,
850            is_shared_randomness_participate: entries.contains("shared-rand-participate"),
851            shared_randomness_commitments: Vec::new(),
852            shared_randomness_previous_reveal_count: None,
853            shared_randomness_previous_value: None,
854            shared_randomness_current_reveal_count: None,
855            shared_randomness_current_value: None,
856            key_certificate,
857        };
858        if entries.contains("dir-source")
859            && let Some(source) =
860                lenient_option(validate, parse_dirauth_source(&entries))?
861        {
862            authority.is_legacy = source.nickname.ends_with("-legacy");
863            authority.nickname = Some(source.nickname);
864            authority.fingerprint = Some(source.v3ident.clone());
865            authority.v3ident = Some(source.v3ident);
866            authority.hostname = Some(source.hostname);
867            authority.address = Some(source.address);
868            authority.dir_port = source.dir_port;
869            authority.or_port = Some(source.or_port);
870        }
871        authority.contact = entries.value("contact").ok().map(str::to_string);
872        if let Ok(value) = entries.value("legacy-dir-key") {
873            authority.legacy_dir_key =
874                lenient_option(validate, parse_forty_hex("legacy-dir-key", value))?;
875        }
876        if let Ok(value) = entries.value("vote-digest") {
877            authority.vote_digest =
878                lenient_option(validate, parse_forty_hex("vote-digest", value))?;
879        }
880        if entries.contains("shared-rand-commit") {
881            authority.shared_randomness_commitments =
882                lenient(validate, parse_shared_rand_commits(&entries))?;
883        }
884        if entries.contains("shared-rand-previous-value")
885            && let Some((count, value)) = lenient_option(
886                validate,
887                parse_shared_rand_value(&entries, "shared-rand-previous-value"),
888            )?
889        {
890            authority.shared_randomness_previous_reveal_count = Some(count);
891            authority.shared_randomness_previous_value = Some(value);
892        }
893        if entries.contains("shared-rand-current-value")
894            && let Some((count, value)) = lenient_option(
895                validate,
896                parse_shared_rand_value(&entries, "shared-rand-current-value"),
897            )?
898        {
899            authority.shared_randomness_current_reveal_count = Some(count);
900            authority.shared_randomness_current_value = Some(value);
901        }
902        Ok(authority)
903    }
904
905    fn check_constraints(
906        entries: &Entries,
907        content: &str,
908        is_vote: bool,
909        has_certificate: bool,
910    ) -> Result<()> {
911        if entries.first_key() != Some("dir-source") {
912            return Err(Error::parse(format!(
913                "Authority entries are expected to start with a 'dir-source' \
914                line:\n{content}"
915            )));
916        }
917        let is_legacy = entries
918            .get("dir-source")
919            .and_then(|values| values.first())
920            .is_some_and(|entry| {
921                entry
922                    .value
923                    .split_whitespace()
924                    .next()
925                    .is_some_and(|name| name.ends_with("-legacy"))
926            });
927        let mut required = vec!["dir-source"];
928        let mut excluded: Vec<&str> = Vec::new();
929        if !is_legacy {
930            required.push("contact");
931        }
932        if is_vote {
933            if !has_certificate {
934                return Err(Error::parse(format!(
935                    "Authority votes must have a key certificate:\n{content}"
936                )));
937            }
938            excluded.push("vote-digest");
939        } else {
940            if has_certificate {
941                return Err(Error::parse(format!(
942                    "Authority consensus entries shouldn't have a key \
943                    certificate:\n{content}"
944                )));
945            }
946            if !is_legacy {
947                required.push("vote-digest");
948            }
949            excluded.push("legacy-dir-key");
950        }
951        for keyword in required {
952            if !entries.contains(keyword) {
953                return Err(Error::parse(format!(
954                    "Authority entries must have a '{keyword}' line:\n{content}"
955                )));
956            }
957        }
958        for keyword in entries.keys() {
959            if excluded.contains(&keyword.as_str()) {
960                let label = if is_vote {
961                    "votes"
962                } else {
963                    "consensus entries"
964                };
965                return Err(Error::parse(format!(
966                    "Authority {label} shouldn't have a '{keyword}' line:\n{content}"
967                )));
968            }
969        }
970        for keyword in ["dir-source", "contact", "legacy-dir-key", "vote-digest"] {
971            let count = entries.get(keyword).map_or(0, <[_]>::len);
972            if count > 1 {
973                return Err(Error::parse(format!(
974                    "Authority entries can only have a single '{keyword}' line, got \
975                    {count}:\n{content}"
976                )));
977            }
978        }
979        Ok(())
980    }
981
982    pub fn content(attributes: &Attributes, exclude: &[&str], is_vote: bool) -> Vec<u8> {
983        let mut attributes = attributes.clone();
984        let excludes_digest = exclude.contains(&"vote-digest");
985        if !is_vote
986            && !attributes.iter().any(|(key, _)| key == "vote-digest")
987            && !excludes_digest
988        {
989            attributes.push(attr("vote-digest", &random_fingerprint()));
990        }
991        let mut content = descriptor_content(
992            &attributes,
993            exclude,
994            &[
995                (
996                    "dir-source",
997                    AttrValue::Text(format!(
998                        "{} {} no.place.com {} 9030 9090",
999                        random_nickname(),
1000                        random_fingerprint(),
1001                        random_ipv4_address()
1002                    )),
1003                ),
1004                ("contact", AttrValue::Text("Mike Perry <email>".to_string())),
1005            ],
1006            &[],
1007        );
1008        if is_vote {
1009            content.push(b'\n');
1010            content.extend(KeyCertificate::content(&Vec::new(), &[]));
1011        }
1012        content
1013    }
1014
1015    pub fn create(
1016        attributes: &Attributes,
1017        exclude: &[&str],
1018        validate: bool,
1019        is_vote: bool,
1020    ) -> Result<Self> {
1021        Self::parse(
1022            &Self::content(attributes, exclude, is_vote),
1023            validate,
1024            is_vote,
1025        )
1026    }
1027}
1028
1029#[derive(Debug, Clone, PartialEq, serde::Serialize)]
1030pub struct NetworkStatusDocumentV3 {
1031    #[serde(skip)]
1032    pub raw_contents: Vec<u8>,
1033    pub unrecognized_lines: Vec<String>,
1034    pub version: Option<u32>,
1035    pub version_flavor: String,
1036    pub is_consensus: bool,
1037    pub is_vote: bool,
1038    pub is_microdescriptor: bool,
1039    pub consensus_methods: Vec<u32>,
1040    pub published: Option<NaiveDateTime>,
1041    pub consensus_method: Option<u32>,
1042    pub valid_after: Option<NaiveDateTime>,
1043    pub fresh_until: Option<NaiveDateTime>,
1044    pub valid_until: Option<NaiveDateTime>,
1045    pub vote_delay: Option<u32>,
1046    pub dist_delay: Option<u32>,
1047    pub client_versions: Vec<Version>,
1048    pub server_versions: Vec<Version>,
1049    pub packages: Vec<PackageVersion>,
1050    pub known_flags: Vec<String>,
1051    pub flag_thresholds: IndexMap<String, f64>,
1052    pub recommended_client_protocols: Protocols,
1053    pub recommended_relay_protocols: Protocols,
1054    pub required_client_protocols: Protocols,
1055    pub required_relay_protocols: Protocols,
1056    pub params: IndexMap<String, i64>,
1057    pub shared_randomness_previous_reveal_count: Option<u32>,
1058    pub shared_randomness_previous_value: Option<String>,
1059    pub shared_randomness_current_reveal_count: Option<u32>,
1060    pub shared_randomness_current_value: Option<String>,
1061    pub is_shared_randomness_participate: bool,
1062    pub shared_randomness_commitments: Vec<SharedRandomnessCommitment>,
1063    pub bandwidth_file_headers: IndexMap<String, String>,
1064    pub bandwidth_file_digest: IndexMap<String, String>,
1065    pub signatures: Vec<DocumentSignature>,
1066    pub bandwidth_weights: IndexMap<String, i64>,
1067    pub directory_authorities: Vec<DirectoryAuthority>,
1068    pub routers: IndexMap<String, RouterEntry>,
1069}
1070
1071const HEADER_KEYWORDS: [&str; 24] = [
1072    "network-status-version",
1073    "vote-status",
1074    "consensus-methods",
1075    "consensus-method",
1076    "published",
1077    "valid-after",
1078    "fresh-until",
1079    "valid-until",
1080    "voting-delay",
1081    "client-versions",
1082    "server-versions",
1083    "package",
1084    "known-flags",
1085    "flag-thresholds",
1086    "recommended-client-protocols",
1087    "recommended-relay-protocols",
1088    "required-client-protocols",
1089    "required-relay-protocols",
1090    "params",
1091    "shared-rand-previous-value",
1092    "shared-rand-current-value",
1093    "bandwidth-file-headers",
1094    "bandwidth-file-digest",
1095    "shared-rand-commit",
1096];
1097
1098impl NetworkStatusDocumentV3 {
1099    pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
1100        Self::parse_with_options(content, validate, true)
1101    }
1102
1103    pub fn parse_with_options(
1104        content: &[u8],
1105        validate: bool,
1106        default_params: bool,
1107    ) -> Result<Self> {
1108        let mut cursor = LineCursor::new(content);
1109        let header_bytes = cursor
1110            .read_until_keywords(
1111                &[AUTH_START, ROUTERS_START, FOOTER_START],
1112                ReadOptions::default(),
1113            )
1114            .content;
1115        let (header_entries, _) =
1116            descriptor_components(&header_bytes, validate, &[], &[])?;
1117        let mut document = Self::empty(content);
1118        document.parse_header(&header_entries, validate, default_params)?;
1119        let is_vote = document.is_vote;
1120        let authority_section = parse_entry_section_for(
1121            &mut cursor,
1122            AUTH_START,
1123            &[ROUTERS_START, FOOTER_START, V2_FOOTER_START],
1124            |bytes| DirectoryAuthority::parse(bytes, validate, is_vote),
1125        )?;
1126        document.directory_authorities = authority_section;
1127        if validate && document.is_vote && document.directory_authorities.len() != 1 {
1128            return Err(Error::parse(format!(
1129                "Votes should only have an authority entry for the one that issued it, \
1130                got {}",
1131                document.directory_authorities.len()
1132            )));
1133        }
1134        let context = DocumentContext { is_vote };
1135        let is_micro = document.is_microdescriptor;
1136        let routers = parse_entry_section(
1137            &mut cursor,
1138            validate,
1139            &[FOOTER_START, V2_FOOTER_START],
1140            None,
1141            |bytes| match is_micro {
1142                true => RouterStatusEntryMicroV3::parse_with_document(
1143                    bytes,
1144                    validate,
1145                    Some(context),
1146                )
1147                .map(RouterEntry::Micro),
1148                false => RouterStatusEntryV3::parse_with_document(
1149                    bytes,
1150                    validate,
1151                    Some(context),
1152                )
1153                .map(RouterEntry::Full),
1154            },
1155        )?;
1156        for entry in routers {
1157            if let Some(fingerprint) = entry.common().fingerprint.clone() {
1158                document.routers.insert(fingerprint, entry);
1159            }
1160        }
1161        document.parse_footer(cursor.remaining(), validate)?;
1162        Ok(document)
1163    }
1164
1165    fn empty(content: &[u8]) -> Self {
1166        Self {
1167            raw_contents: content.to_vec(),
1168            unrecognized_lines: Vec::new(),
1169            version: None,
1170            version_flavor: "ns".to_string(),
1171            is_consensus: true,
1172            is_vote: false,
1173            is_microdescriptor: false,
1174            consensus_methods: Vec::new(),
1175            published: None,
1176            consensus_method: None,
1177            valid_after: None,
1178            fresh_until: None,
1179            valid_until: None,
1180            vote_delay: None,
1181            dist_delay: None,
1182            client_versions: Vec::new(),
1183            server_versions: Vec::new(),
1184            packages: Vec::new(),
1185            known_flags: Vec::new(),
1186            flag_thresholds: IndexMap::new(),
1187            recommended_client_protocols: Protocols::new(),
1188            recommended_relay_protocols: Protocols::new(),
1189            required_client_protocols: Protocols::new(),
1190            required_relay_protocols: Protocols::new(),
1191            params: IndexMap::new(),
1192            shared_randomness_previous_reveal_count: None,
1193            shared_randomness_previous_value: None,
1194            shared_randomness_current_reveal_count: None,
1195            shared_randomness_current_value: None,
1196            is_shared_randomness_participate: false,
1197            shared_randomness_commitments: Vec::new(),
1198            bandwidth_file_headers: IndexMap::new(),
1199            bandwidth_file_digest: IndexMap::new(),
1200            signatures: Vec::new(),
1201            bandwidth_weights: IndexMap::new(),
1202            directory_authorities: Vec::new(),
1203            routers: IndexMap::new(),
1204        }
1205    }
1206
1207    fn parse_header(
1208        &mut self,
1209        entries: &Entries,
1210        validate: bool,
1211        default_params: bool,
1212    ) -> Result<()> {
1213        if validate {
1214            for (keyword, values) in entries.iter() {
1215                let is_header_field = HEADER_FIELDS
1216                    .iter()
1217                    .any(|HeaderField(name, ..)| name == keyword);
1218                if values.len() > 1
1219                    && is_header_field
1220                    && keyword != "package"
1221                    && keyword != "shared-rand-commit"
1222                {
1223                    return Err(Error::parse(format!(
1224                        "Network status documents can only have a single '{keyword}' \
1225                        line, got {}",
1226                        values.len()
1227                    )));
1228                }
1229            }
1230        }
1231        if default_params {
1232            self.params = DEFAULT_PARAMS
1233                .iter()
1234                .map(|(key, value)| (key.to_string(), *value))
1235                .collect();
1236        }
1237        self.unrecognized_lines
1238            .extend(entries.unrecognized_lines(&HEADER_KEYWORDS));
1239        if let Ok(value) = entries.value("network-status-version") {
1240            let parsed = (|| -> Result<(u32, String)> {
1241                let (version, flavor) = value.split_once(' ').unwrap_or((value, "ns"));
1242                let number = unsigned(version).ok_or_else(|| {
1243                    Error::parse(format!(
1244                        "Network status document has a non-numeric \
1245                        version: network-status-version {value}"
1246                    ))
1247                })?;
1248                match number == 3 {
1249                    true => Ok((number, flavor.to_string())),
1250                    false => Err(Error::parse(format!(
1251                        "Expected a version 3 network status document, got version \
1252                        '{number}' instead"
1253                    ))),
1254                }
1255            })();
1256            if let Some((version, flavor)) = lenient_option(validate, parsed)? {
1257                self.version = Some(version);
1258                self.is_microdescriptor = flavor == "microdesc";
1259                self.version_flavor = flavor;
1260            }
1261        }
1262        if let Ok(value) = entries.value("vote-status") {
1263            match value {
1264                "consensus" => (self.is_consensus, self.is_vote) = (true, false),
1265                "vote" => (self.is_consensus, self.is_vote) = (false, true),
1266                _ => {
1267                    lenient::<()>(
1268                        validate,
1269                        Err(Error::parse(format!(
1270                            "A network status document's vote-status line can only be \
1271                            'consensus' or 'vote', got '{value}' instead"
1272                        ))),
1273                    )?;
1274                }
1275            }
1276        }
1277        if let Ok(value) = entries.value("consensus-methods") {
1278            let methods: Result<Vec<u32>> = value
1279                .split(' ')
1280                .map(|entry| {
1281                    unsigned(entry).ok_or_else(|| {
1282                        Error::parse(format!(
1283                            "A network status document's consensus-methods must be a \
1284                            list of integer values, but was '{value}'"
1285                        ))
1286                    })
1287                })
1288                .collect();
1289            if let Some(methods) = lenient_option(validate, methods)? {
1290                self.consensus_methods = methods;
1291            }
1292        }
1293        if let Ok(value) = entries.value("consensus-method") {
1294            let parsed = unsigned(value).ok_or_else(|| {
1295                Error::parse(format!(
1296                    "A network status document's consensus-method must \
1297                    be an integer, but was '{value}'"
1298                ))
1299            });
1300            self.consensus_method = lenient_option(validate, parsed)?;
1301        }
1302        for (keyword, target) in [
1303            ("published", &mut self.published),
1304            ("valid-after", &mut self.valid_after),
1305            ("fresh-until", &mut self.fresh_until),
1306            ("valid-until", &mut self.valid_until),
1307        ] {
1308            if let Ok(value) = entries.value(keyword) {
1309                *target = lenient_option(validate, parse_timestamp_line(keyword, value))?;
1310            }
1311        }
1312        if let Ok(value) = entries.value("voting-delay") {
1313            let parts: Vec<&str> = value.split(' ').collect();
1314            match parts.as_slice() {
1315                [vote, dist] if unsigned(vote).is_some() && unsigned(dist).is_some() => {
1316                    self.vote_delay = unsigned(vote);
1317                    self.dist_delay = unsigned(dist);
1318                }
1319                _ => {
1320                    lenient::<()>(
1321                        validate,
1322                        Err(Error::parse(format!(
1323                            "A network status document's 'voting-delay' line must be a \
1324                            pair of integer values, but was '{value}'"
1325                        ))),
1326                    )?;
1327                }
1328            }
1329        }
1330        if entries.contains("client-versions") {
1331            self.client_versions =
1332                lenient(validate, parse_versions(entries, "client-versions"))?;
1333        }
1334        if entries.contains("server-versions") {
1335            self.server_versions =
1336                lenient(validate, parse_versions(entries, "server-versions"))?;
1337        }
1338        if entries.contains("package") {
1339            self.packages = lenient(validate, parse_packages(entries))?;
1340        }
1341        if let Ok(value) = entries.value("known-flags") {
1342            self.known_flags = value
1343                .split(' ')
1344                .filter(|entry| !entry.is_empty())
1345                .map(str::to_string)
1346                .collect();
1347        }
1348        if entries.contains("flag-thresholds") {
1349            self.flag_thresholds = lenient(validate, parse_flag_thresholds(entries))?;
1350        }
1351        for (keyword, target) in [
1352            (
1353                "recommended-client-protocols",
1354                &mut self.recommended_client_protocols,
1355            ),
1356            (
1357                "recommended-relay-protocols",
1358                &mut self.recommended_relay_protocols,
1359            ),
1360            (
1361                "required-client-protocols",
1362                &mut self.required_client_protocols,
1363            ),
1364            (
1365                "required-relay-protocols",
1366                &mut self.required_relay_protocols,
1367            ),
1368        ] {
1369            if let Ok(value) = entries.value(keyword) {
1370                *target = lenient(validate, parse_protocol_line(keyword, value))?;
1371            }
1372        }
1373        if let Ok(value) = entries.value("params")
1374            && !value.is_empty()
1375        {
1376            let parsed = parse_int_mappings("params", value, true).and_then(|params| {
1377                self.check_params_constraints(&params).map(|()| params)
1378            });
1379            if let Some(params) = lenient_option(validate, parsed)? {
1380                self.params = params;
1381            }
1382        }
1383        for (keyword, count_target, value_target) in [
1384            (
1385                "shared-rand-previous-value",
1386                &mut self.shared_randomness_previous_reveal_count,
1387                &mut self.shared_randomness_previous_value,
1388            ),
1389            (
1390                "shared-rand-current-value",
1391                &mut self.shared_randomness_current_reveal_count,
1392                &mut self.shared_randomness_current_value,
1393            ),
1394        ] {
1395            if entries.contains(keyword)
1396                && let Some((count, value)) =
1397                    lenient_option(validate, parse_shared_rand_value(entries, keyword))?
1398            {
1399                *count_target = Some(count);
1400                *value_target = Some(value);
1401            }
1402        }
1403        self.is_shared_randomness_participate =
1404            entries.contains("shared-rand-participate");
1405        if entries.contains("shared-rand-commit") {
1406            self.shared_randomness_commitments =
1407                lenient(validate, parse_shared_rand_commits(entries))?;
1408        }
1409        for (keyword, target) in [
1410            ("bandwidth-file-headers", &mut self.bandwidth_file_headers),
1411            ("bandwidth-file-digest", &mut self.bandwidth_file_digest),
1412        ] {
1413            if let Ok(value) = entries.value(keyword) {
1414                *target = lenient::<Vec<(String, String)>>(
1415                    validate,
1416                    mappings_for(keyword, value, false, ' '),
1417                )?
1418                .into_iter()
1419                .collect();
1420            }
1421        }
1422        if validate {
1423            if !self.meets_consensus_method(7) && entries.contains("params") {
1424                return Err(Error::parse(
1425                    "A network status document's 'params' line should only appear in \
1426                    consensus-method 7 or later",
1427                ));
1428            }
1429            check_missing_and_disallowed(self.is_vote, entries, &HEADER_FIELDS)?;
1430            if self.is_consensus && self.consensus_method.is_none() {
1431                self.consensus_method = Some(1);
1432            } else if self.is_vote && self.consensus_methods.is_empty() {
1433                self.consensus_methods = vec![1];
1434            }
1435        }
1436        Ok(())
1437    }
1438
1439    fn parse_footer(&mut self, content: &[u8], validate: bool) -> Result<()> {
1440        let (entries, _) = descriptor_components(content, validate, &[], &[])?;
1441        self.unrecognized_lines.extend(entries.unrecognized_lines(&[
1442            "directory-footer",
1443            "bandwidth-weights",
1444            "directory-signature",
1445        ]));
1446        if validate {
1447            for (keyword, values) in entries.iter() {
1448                let is_footer_field = FOOTER_FIELDS
1449                    .iter()
1450                    .any(|HeaderField(name, ..)| name == keyword);
1451                if values.len() > 1
1452                    && is_footer_field
1453                    && !(keyword == "directory-signature" && self.is_consensus)
1454                {
1455                    return Err(Error::parse(format!(
1456                        "Network status documents can only have a single '{keyword}' \
1457                        line, got {}",
1458                        values.len()
1459                    )));
1460                }
1461            }
1462        }
1463        if let Ok(value) = entries.value("directory-footer")
1464            && !value.is_empty()
1465        {
1466            lenient::<()>(
1467                validate,
1468                Err(Error::parse(format!(
1469                    "A network status document's 'directory-footer' line shouldn't have \
1470                    any content, got 'directory-footer {value}'"
1471                ))),
1472            )?;
1473        }
1474        if let Ok(value) = entries.value("bandwidth-weights") {
1475            self.bandwidth_weights = lenient(
1476                validate,
1477                parse_int_mappings("bandwidth-weights", value, true),
1478            )?;
1479        }
1480        if entries.contains("directory-signature") {
1481            self.signatures =
1482                lenient(validate, parse_signatures(&entries, "directory-signature"))?;
1483        }
1484        if validate && !entries.is_empty() {
1485            match (self.meets_consensus_method(9), entries.first_key()) {
1486                (true, Some("directory-footer"))
1487                | (false, Some("directory-signature")) => {}
1488                (true, _) => {
1489                    return Err(Error::parse(
1490                        "Network status document's footer should start with a \
1491                        'directory-footer' line in consensus-method 9 or later",
1492                    ));
1493                }
1494                (false, _) => {
1495                    return Err(Error::parse(
1496                        "Network status document's footer should start with a \
1497                        'directory-signature' line prior to consensus-method 9",
1498                    ));
1499                }
1500            }
1501            check_missing_and_disallowed(self.is_vote, &entries, &FOOTER_FIELDS)?;
1502        }
1503        Ok(())
1504    }
1505
1506    fn check_params_constraints(&self, params: &IndexMap<String, i64>) -> Result<()> {
1507        for (key, value) in params {
1508            let (mut minimum, maximum) = param_range(key);
1509            match key.as_str() {
1510                "cbtclosequantile" => {
1511                    minimum = params.get("cbtquantile").copied().unwrap_or(minimum)
1512                }
1513                "cbtinitialtimeout" => {
1514                    minimum = params.get("cbtmintimeout").copied().unwrap_or(minimum)
1515                }
1516                _ => {}
1517            }
1518            if *value < minimum || *value > maximum {
1519                return Err(Error::parse(format!(
1520                    "'{key}' value on the params line must be in the range of {minimum} \
1521                    - {maximum}, was {value}"
1522                )));
1523            }
1524        }
1525        Ok(())
1526    }
1527
1528    pub fn meets_consensus_method(&self, method: u32) -> bool {
1529        match (self.consensus_method, self.consensus_methods.is_empty()) {
1530            (Some(current), _) => current >= method,
1531            (None, false) => self
1532                .consensus_methods
1533                .iter()
1534                .any(|candidate| *candidate >= method),
1535            (None, true) => false,
1536        }
1537    }
1538
1539    pub fn is_valid(&self) -> bool {
1540        let now = Utc::now().naive_utc();
1541        match (self.valid_after, self.valid_until) {
1542            (Some(after), Some(until)) => after < now && now < until,
1543            _ => false,
1544        }
1545    }
1546
1547    pub fn is_fresh(&self) -> bool {
1548        let now = Utc::now().naive_utc();
1549        match (self.valid_after, self.fresh_until) {
1550            (Some(after), Some(fresh)) => after < now && now < fresh,
1551            _ => false,
1552        }
1553    }
1554
1555    pub fn digest(&self, hash: DigestHash, encoding: DigestEncoding) -> Result<String> {
1556        let content =
1557            content_range(&self.raw_contents, None, Some("\ndirectory-signature "))?;
1558        Ok(encode_digest(&hash_bytes(hash, &content), encoding))
1559    }
1560
1561    pub fn validate_signatures(&self, key_certificates: &[KeyCertificate]) -> Result<()> {
1562        let signed = content_range(
1563            &self.raw_contents,
1564            Some("network-status-version"),
1565            Some("directory-signature "),
1566        )?;
1567        let local = Sha1::digest(&signed).to_vec();
1568        let required = self.signatures.len() as f64 / 2.0;
1569        let (mut valid, mut total) = (0usize, 0usize);
1570        for signature in &self.signatures {
1571            let Some(certificate) = key_certificates.iter().find(|certificate| {
1572                certificate.fingerprint.as_deref() == Some(signature.identity.as_str())
1573            }) else {
1574                continue;
1575            };
1576            let Some(signing_key) = &certificate.signing_key else {
1577                continue;
1578            };
1579            total += 1;
1580            if digest_for_signature(signing_key, &signature.signature)
1581                .is_ok_and(|digest| digest == local)
1582            {
1583                valid += 1;
1584            }
1585        }
1586        match (valid as f64) < required {
1587            true => Err(Error::parse(format!(
1588                "Network Status Document has {valid} valid signatures out of {total} \
1589                total, needed {required}"
1590            ))),
1591            false => Ok(()),
1592        }
1593    }
1594
1595    pub fn parse_routers(
1596        content: &[u8],
1597        validate: bool,
1598        is_microdescriptor: bool,
1599    ) -> Result<Vec<RouterEntry>> {
1600        let split = split_document(content);
1601        let header_content: Vec<u8> =
1602            [split.header.as_slice(), split.footer.as_slice()].concat();
1603        let document = Self::parse_bare(&header_content, validate)?;
1604        let context = DocumentContext {
1605            is_vote: document.is_vote,
1606        };
1607        let mut cursor = LineCursor::new(content);
1608        cursor.seek(split.routers_start);
1609        parse_entry_section(
1610            &mut cursor,
1611            validate,
1612            &[],
1613            Some(split.routers_end),
1614            |bytes| match is_microdescriptor {
1615                true => RouterStatusEntryMicroV3::parse_with_document(
1616                    bytes,
1617                    validate,
1618                    Some(context),
1619                )
1620                .map(RouterEntry::Micro),
1621                false => RouterStatusEntryV3::parse_with_document(
1622                    bytes,
1623                    validate,
1624                    Some(context),
1625                )
1626                .map(RouterEntry::Full),
1627            },
1628        )
1629    }
1630
1631    pub fn parse_bare(content: &[u8], validate: bool) -> Result<Self> {
1632        Self::parse(content, validate)
1633    }
1634
1635    pub fn content(
1636        attributes: &Attributes,
1637        exclude: &[&str],
1638        authorities: Option<&[DirectoryAuthority]>,
1639        routers: &[Vec<u8>],
1640    ) -> Vec<u8> {
1641        let mut attributes = attributes.clone();
1642        let is_vote = attributes.iter().any(|(key, value)| {
1643            key == "vote-status"
1644                && matches!(value, AttrValue::Text(text) if text == "vote")
1645        });
1646        let defaults: Vec<(&str, String)> = match is_vote {
1647            true => vec![
1648                ("consensus-methods", "1 9".to_string()),
1649                ("published", random_date()),
1650            ],
1651            false => vec![("consensus-method", "9".to_string())],
1652        };
1653        for (key, value) in defaults {
1654            if !exclude.contains(&key) && !attributes.iter().any(|(name, _)| name == key)
1655            {
1656                attributes.push((key.to_string(), AttrValue::Text(value)));
1657            }
1658        }
1659        let generated_authority;
1660        let authorities = match (authorities, is_vote) {
1661            (Some(authorities), _) => authorities,
1662            (None, true) => {
1663                generated_authority =
1664                    DirectoryAuthority::create(&Vec::new(), &[], true, true).ok();
1665                generated_authority.as_slice()
1666            }
1667            (None, false) => &[],
1668        };
1669        let mut content = descriptor_content(
1670            &attributes,
1671            exclude,
1672            &[
1673                ("network-status-version", AttrValue::Text("3".to_string())),
1674                ("vote-status", AttrValue::Text("consensus".to_string())),
1675                ("consensus-methods", AttrValue::Remove),
1676                ("consensus-method", AttrValue::Remove),
1677                ("published", AttrValue::Remove),
1678                ("valid-after", AttrValue::Text(random_date())),
1679                ("fresh-until", AttrValue::Text(random_date())),
1680                ("valid-until", AttrValue::Text(random_date())),
1681                ("voting-delay", AttrValue::Text("300 300".to_string())),
1682                ("client-versions", AttrValue::Remove),
1683                ("server-versions", AttrValue::Remove),
1684                ("package", AttrValue::Remove),
1685                (
1686                    "known-flags",
1687                    AttrValue::Text(
1688                        "Authority BadExit Exit Fast Guard HSDir Named \
1689                        Running Stable Unnamed V2Dir Valid"
1690                            .to_string(),
1691                    ),
1692                ),
1693                ("params", AttrValue::Remove),
1694            ],
1695            &[
1696                ("directory-footer", AttrValue::Text(String::new())),
1697                ("bandwidth-weights", AttrValue::Remove),
1698                (
1699                    "directory-signature",
1700                    AttrValue::Text(format!(
1701                        "{} {}{}",
1702                        random_fingerprint(),
1703                        random_fingerprint(),
1704                        random_crypto_blob(Some("SIGNATURE"))
1705                    )),
1706                ),
1707            ],
1708        );
1709        let find_footer = |content: &Vec<u8>| -> usize {
1710            let search = |needle: &[u8]| {
1711                content
1712                    .windows(needle.len())
1713                    .position(|window| window == needle)
1714            };
1715            match search(b"\ndirectory-footer")
1716                .or_else(|| search(b"\ndirectory-signature"))
1717            {
1718                Some(position) => position + 1,
1719                None => content.len() + 1,
1720            }
1721        };
1722        for section in [
1723            authorities
1724                .iter()
1725                .map(|authority| authority.raw_contents.clone())
1726                .collect::<Vec<_>>(),
1727            routers.to_vec(),
1728        ] {
1729            if section.is_empty() {
1730                continue;
1731            }
1732            let mut footer_div = find_footer(&content);
1733            if footer_div > content.len() {
1734                content.push(b'\n');
1735                footer_div = content.len();
1736            }
1737            let mut block = section.join(&b'\n');
1738            block.push(b'\n');
1739            content.splice(footer_div..footer_div, block);
1740        }
1741        content
1742    }
1743
1744    pub fn create(
1745        attributes: &Attributes,
1746        exclude: &[&str],
1747        validate: bool,
1748        authorities: Option<&[DirectoryAuthority]>,
1749        routers: &[Vec<u8>],
1750    ) -> Result<Self> {
1751        Self::parse(
1752            &Self::content(attributes, exclude, authorities, routers),
1753            validate,
1754        )
1755    }
1756}
1757
1758fn parse_entry_section_for<T>(
1759    cursor: &mut LineCursor<'_>,
1760    entry_keyword: &str,
1761    section_end_keywords: &[&str],
1762    mut build: impl FnMut(&[u8]) -> Result<T>,
1763) -> Result<Vec<T>> {
1764    let start = cursor.tell();
1765    let first_keyword = cursor.read_line().and_then(|line| {
1766        let text = String::from_utf8_lossy(line).into_owned();
1767        crate::descriptor::split_keyword_line(text.trim_end_matches(['\n', '\r']))
1768            .map(|(keyword, _)| keyword.to_string())
1769    });
1770    cursor.seek(start);
1771    if first_keyword
1772        .is_some_and(|keyword| section_end_keywords.contains(&keyword.as_str()))
1773    {
1774        return Ok(Vec::new());
1775    }
1776    let mut keywords = vec![entry_keyword];
1777    keywords.extend_from_slice(section_end_keywords);
1778    let mut parsed = Vec::new();
1779    loop {
1780        let result = cursor.read_until_keywords(
1781            &keywords,
1782            ReadOptions {
1783                ignore_first: true,
1784                ..Default::default()
1785            },
1786        );
1787        if result.content.is_empty() {
1788            break;
1789        }
1790        parsed.push(build(&result.content)?);
1791        if result
1792            .ending_keyword
1793            .as_deref()
1794            .is_some_and(|keyword| section_end_keywords.contains(&keyword))
1795        {
1796            break;
1797        }
1798    }
1799    Ok(parsed)
1800}
1801
1802struct SplitDocument {
1803    header: Vec<u8>,
1804    footer: Vec<u8>,
1805    routers_start: usize,
1806    routers_end: usize,
1807}
1808
1809fn split_document(content: &[u8]) -> SplitDocument {
1810    let mut cursor = LineCursor::new(content);
1811    let mut header = cursor
1812        .read_until_keywords(
1813            &[ROUTERS_START, FOOTER_START, V2_FOOTER_START],
1814            ReadOptions::default(),
1815        )
1816        .content;
1817    if header.starts_with(b"@type") {
1818        header = header
1819            .splitn(2, |byte| *byte == b'\n')
1820            .nth(1)
1821            .unwrap_or_default()
1822            .to_vec();
1823    }
1824    let routers_start = cursor.tell();
1825    cursor.read_until_keywords(&[FOOTER_START, V2_FOOTER_START], ReadOptions::default());
1826    let routers_end = cursor.tell();
1827    SplitDocument {
1828        header,
1829        footer: cursor.remaining().to_vec(),
1830        routers_start,
1831        routers_end,
1832    }
1833}
1834
1835#[derive(Debug, Clone, PartialEq, serde::Serialize)]
1836pub struct DetachedSignature {
1837    #[serde(skip)]
1838    pub raw_contents: Vec<u8>,
1839    pub unrecognized_lines: Vec<String>,
1840    pub consensus_digest: Option<String>,
1841    pub valid_after: Option<NaiveDateTime>,
1842    pub fresh_until: Option<NaiveDateTime>,
1843    pub valid_until: Option<NaiveDateTime>,
1844    pub additional_digests: Vec<DocumentDigest>,
1845    pub additional_signatures: Vec<DocumentSignature>,
1846    pub signatures: Vec<DocumentSignature>,
1847}
1848
1849impl DetachedSignature {
1850    pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
1851        let (entries, _) = descriptor_components(content, validate, &[], &[])?;
1852        let raw = String::from_utf8_lossy(content);
1853        if validate {
1854            if entries.first_key() != Some("consensus-digest") {
1855                return Err(Error::parse(format!(
1856                    "Detached signatures must start with a 'consensus-digest' \
1857                    line:\n{raw}"
1858                )));
1859            }
1860            for (keyword, mandatory, multiple) in DETACHED_SIGNATURE_PARAMS {
1861                if mandatory && !entries.contains(keyword) {
1862                    return Err(Error::parse(format!(
1863                        "Detached signatures must have a '{keyword}' line:\n{raw}"
1864                    )));
1865                }
1866                let count = entries.get(keyword).map_or(0, <[_]>::len);
1867                if !multiple && count > 1 {
1868                    return Err(Error::parse(format!(
1869                        "Detached signatures can only have a single '{keyword}' line, \
1870                        got {count}:\n{raw}"
1871                    )));
1872                }
1873            }
1874        }
1875        let recognized: Vec<&str> = DETACHED_SIGNATURE_PARAMS
1876            .iter()
1877            .map(|(keyword, _, _)| *keyword)
1878            .collect();
1879        let mut signature = Self {
1880            raw_contents: content.to_vec(),
1881            unrecognized_lines: entries.unrecognized_lines(&recognized),
1882            consensus_digest: None,
1883            valid_after: None,
1884            fresh_until: None,
1885            valid_until: None,
1886            additional_digests: Vec::new(),
1887            additional_signatures: Vec::new(),
1888            signatures: Vec::new(),
1889        };
1890        signature.consensus_digest =
1891            entries.value("consensus-digest").ok().map(str::to_string);
1892        for (keyword, target) in [
1893            ("valid-after", &mut signature.valid_after),
1894            ("fresh-until", &mut signature.fresh_until),
1895            ("valid-until", &mut signature.valid_until),
1896        ] {
1897            if let Ok(value) = entries.value(keyword) {
1898                *target = lenient_option(validate, parse_timestamp_line(keyword, value))?;
1899            }
1900        }
1901        if entries.contains("additional-digest") {
1902            let parsed: Result<Vec<DocumentDigest>> = entries
1903                .values("additional-digest")
1904                .into_iter()
1905                .map(|value| {
1906                    let parts: Vec<&str> = value.split(' ').collect();
1907                    match parts.as_slice() {
1908                        [flavor, algorithm, digest, ..] => Ok(DocumentDigest {
1909                            flavor: flavor.to_string(),
1910                            algorithm: algorithm.to_string(),
1911                            digest: digest.to_string(),
1912                        }),
1913                        _ => Err(Error::parse(format!(
1914                            "additional-digest lines should be of the form \
1915                            'additional-digest [flavor] [algname] [digest]' but was: \
1916                            {value}"
1917                        ))),
1918                    }
1919                })
1920                .collect();
1921            signature.additional_digests = lenient(validate, parsed)?;
1922        }
1923        if entries.contains("additional-signature") {
1924            signature.additional_signatures =
1925                lenient(validate, Self::parse_additional_signatures(&entries))?;
1926        }
1927        if entries.contains("directory-signature") {
1928            signature.signatures =
1929                lenient(validate, parse_signatures(&entries, "directory-signature"))?;
1930        }
1931        Ok(signature)
1932    }
1933
1934    fn parse_additional_signatures(entries: &Entries) -> Result<Vec<DocumentSignature>> {
1935        let mut signatures = Vec::new();
1936        for entry in entries.get("additional-signature").unwrap_or_default() {
1937            let parts: Vec<&str> = entry.value.split(' ').collect();
1938            if parts.len() < 4 {
1939                return Err(Error::parse(format!(
1940                    "additional-signature lines should be of the form \
1941                    'additional-signature [flavor] [algname] [identity] \
1942                    [signing_key_digest]' but was: {}",
1943                    entry.value
1944                )));
1945            }
1946            let (Some(block), Some("SIGNATURE")) =
1947                (&entry.block_contents, entry.block_type.as_deref())
1948            else {
1949                return Err(Error::parse(format!(
1950                    "'additional-signature' should be followed by a SIGNATURE block, \
1951                    but was a {}",
1952                    entry.block_type.as_deref().unwrap_or("None")
1953                )));
1954            };
1955            signatures.push(DocumentSignature::new(
1956                parts[1],
1957                parts[2],
1958                parts[3],
1959                block,
1960                Some(parts[0]),
1961                true,
1962            )?);
1963        }
1964        Ok(signatures)
1965    }
1966
1967    pub fn content(attributes: &Attributes, exclude: &[&str]) -> Vec<u8> {
1968        descriptor_content(
1969            attributes,
1970            exclude,
1971            &[
1972                (
1973                    "consensus-digest",
1974                    AttrValue::Text(
1975                        "6D3CC0EFA408F228410A4A8145E1B0BB0670E442".to_string(),
1976                    ),
1977                ),
1978                ("valid-after", AttrValue::Text(random_date())),
1979                ("fresh-until", AttrValue::Text(random_date())),
1980                ("valid-until", AttrValue::Text(random_date())),
1981            ],
1982            &[],
1983        )
1984    }
1985
1986    pub fn create(
1987        attributes: &Attributes,
1988        exclude: &[&str],
1989        validate: bool,
1990    ) -> Result<Self> {
1991        Self::parse(&Self::content(attributes, exclude), validate)
1992    }
1993
1994    pub fn parse_many(content: &[u8], validate: bool) -> Result<Vec<Self>> {
1995        let mut cursor = LineCursor::new(content);
1996        let mut signatures = Vec::new();
1997        loop {
1998            let body = cursor
1999                .read_until_keywords(
2000                    &["consensus-digest"],
2001                    ReadOptions {
2002                        ignore_first: true,
2003                        ..Default::default()
2004                    },
2005                )
2006                .content;
2007            if body.is_empty() {
2008                break;
2009            }
2010            signatures.push(Self::parse(&body, validate)?);
2011        }
2012        Ok(signatures)
2013    }
2014}
2015
2016#[derive(Debug, Clone, PartialEq, serde::Serialize)]
2017pub struct NetworkStatusDocumentV2 {
2018    #[serde(skip)]
2019    pub raw_contents: Vec<u8>,
2020    pub unrecognized_lines: Vec<String>,
2021    pub version: Option<u32>,
2022    pub hostname: Option<String>,
2023    pub address: Option<String>,
2024    pub dir_port: Option<u16>,
2025    pub fingerprint: Option<String>,
2026    pub contact: Option<String>,
2027    pub signing_key: Option<String>,
2028    pub client_versions: Vec<String>,
2029    pub server_versions: Vec<String>,
2030    pub published: Option<NaiveDateTime>,
2031    pub options: Vec<String>,
2032    pub signing_authority: Option<String>,
2033    pub signature: Option<String>,
2034    pub routers: IndexMap<String, RouterStatusEntryV2>,
2035}
2036
2037impl NetworkStatusDocumentV2 {
2038    pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
2039        let mut cursor = LineCursor::new(content);
2040        let mut document_content = cursor
2041            .read_until_keywords(
2042                &[ROUTERS_START, V2_FOOTER_START],
2043                ReadOptions::default(),
2044            )
2045            .content;
2046        let routers = parse_entry_section(
2047            &mut cursor,
2048            validate,
2049            &[V2_FOOTER_START],
2050            None,
2051            |bytes| RouterStatusEntryV2::parse(bytes, validate),
2052        )?;
2053        document_content.push(b'\n');
2054        document_content.extend_from_slice(cursor.remaining());
2055        let (entries, _) = descriptor_components(&document_content, validate, &[], &[])?;
2056        if validate {
2057            Self::check_constraints(&entries, content)?;
2058        }
2059        let recognized: Vec<&str> = NETWORK_STATUS_V2_FIELDS
2060            .iter()
2061            .map(|(keyword, _)| *keyword)
2062            .collect();
2063        let mut document = Self {
2064            raw_contents: content.to_vec(),
2065            unrecognized_lines: entries.unrecognized_lines(&recognized),
2066            version: None,
2067            hostname: None,
2068            address: None,
2069            dir_port: None,
2070            fingerprint: None,
2071            contact: entries.value("contact").ok().map(str::to_string),
2072            signing_key: None,
2073            client_versions: Vec::new(),
2074            server_versions: Vec::new(),
2075            published: None,
2076            options: Vec::new(),
2077            signing_authority: None,
2078            signature: None,
2079            routers: routers
2080                .into_iter()
2081                .filter_map(|entry| Some((entry.fingerprint.clone()?, entry)))
2082                .collect(),
2083        };
2084        if entries.contains("network-status-version") {
2085            document.version = lenient_option(
2086                validate,
2087                parse_version_line(&entries, "network-status-version", 2),
2088            )?;
2089        }
2090        if let Ok(value) = entries.value("dir-source") {
2091            let parsed = (|| -> Result<(String, String, Option<u16>)> {
2092                let parts: Vec<&str> = value.split_whitespace().collect();
2093                if parts.len() < 3 {
2094                    return Err(Error::parse(format!(
2095                        "The 'dir-source' line of a v2 network status document must \
2096                        have three values: dir-source {value}"
2097                    )));
2098                }
2099                if !is_valid_ipv4_address(parts[1]) {
2100                    return Err(Error::parse(format!(
2101                        "Authority's address isn't a valid IPv4 address: {}",
2102                        parts[1]
2103                    )));
2104                }
2105                let port = parse_port(parts[2], true).ok_or_else(|| {
2106                    Error::parse(format!("Authority's DirPort is invalid: {}", parts[2]))
2107                })?;
2108                Ok((
2109                    parts[0].to_string(),
2110                    parts[1].to_string(),
2111                    Some(port).filter(|port| *port != 0),
2112                ))
2113            })();
2114            if let Some((hostname, address, dir_port)) = lenient_option(validate, parsed)?
2115            {
2116                document.hostname = Some(hostname);
2117                document.address = Some(address);
2118                document.dir_port = dir_port;
2119            }
2120        }
2121        if let Ok(value) = entries.value("fingerprint") {
2122            document.fingerprint =
2123                lenient_option(validate, parse_forty_hex("fingerprint", value))?;
2124        }
2125        if entries.contains("dir-signing-key") {
2126            document.signing_key = lenient_option(
2127                validate,
2128                key_block(&entries, "dir-signing-key", "RSA PUBLIC KEY")
2129                    .map(|(_, block)| block),
2130            )?;
2131        }
2132        if let Ok(value) = entries.value("client-versions") {
2133            document.client_versions = value.split(',').map(str::to_string).collect();
2134        }
2135        if let Ok(value) = entries.value("server-versions") {
2136            document.server_versions = value.split(',').map(str::to_string).collect();
2137        }
2138        if let Ok(value) = entries.value("published") {
2139            document.published =
2140                lenient_option(validate, parse_timestamp_line("published", value))?;
2141        }
2142        if let Ok(value) = entries.value("dir-options") {
2143            document.options = value.split_whitespace().map(str::to_string).collect();
2144        }
2145        if entries.contains("directory-signature")
2146            && let Some((authority, block)) = lenient_option(
2147                validate,
2148                key_block(&entries, "directory-signature", "SIGNATURE"),
2149            )?
2150        {
2151            document.signing_authority = Some(authority);
2152            document.signature = Some(block);
2153        }
2154        if validate
2155            && document.options.iter().any(|option| option == "Versions")
2156            && !(entries.contains("client-versions")
2157                && entries.contains("server-versions"))
2158        {
2159            return Err(Error::parse(format!(
2160                "Version 2 network status documents must have a 'client-versions' and \
2161                'server-versions' when 'Versions' is listed among its dir-options:\n{}",
2162                String::from_utf8_lossy(content)
2163            )));
2164        }
2165        Ok(document)
2166    }
2167
2168    fn check_constraints(entries: &Entries, content: &[u8]) -> Result<()> {
2169        let raw = String::from_utf8_lossy(content);
2170        for (keyword, mandatory) in NETWORK_STATUS_V2_FIELDS {
2171            if mandatory && !entries.contains(keyword) {
2172                return Err(Error::parse(format!(
2173                    "Network status document (v2) must have a '{keyword}' line:\n{raw}"
2174                )));
2175            }
2176            let count = entries.get(keyword).map_or(0, <[_]>::len);
2177            if count > 1 {
2178                return Err(Error::parse(format!(
2179                    "Network status document (v2) can only have a single '{keyword}' \
2180                    line, got {count}:\n{raw}"
2181                )));
2182            }
2183        }
2184        match entries.first_key() {
2185            Some("network-status-version") => Ok(()),
2186            _ => Err(Error::parse(format!(
2187                "Network status document (v2) are expected to start with a \
2188                'network-status-version' line:\n{raw}"
2189            ))),
2190        }
2191    }
2192
2193    pub fn content(attributes: &Attributes, exclude: &[&str]) -> Vec<u8> {
2194        descriptor_content(
2195            attributes,
2196            exclude,
2197            &[
2198                ("network-status-version", AttrValue::Text("2".to_string())),
2199                (
2200                    "dir-source",
2201                    AttrValue::Text(format!(
2202                        "{} {} 80",
2203                        random_ipv4_address(),
2204                        random_ipv4_address()
2205                    )),
2206                ),
2207                ("fingerprint", AttrValue::Text(random_fingerprint())),
2208                (
2209                    "contact",
2210                    AttrValue::Text("arma at mit dot edu".to_string()),
2211                ),
2212                ("published", AttrValue::Text(random_date())),
2213                (
2214                    "dir-signing-key",
2215                    AttrValue::Text(random_crypto_blob(Some("RSA PUBLIC KEY"))),
2216                ),
2217            ],
2218            &[(
2219                "directory-signature",
2220                AttrValue::Text(format!(
2221                    "moria2{}",
2222                    random_crypto_blob(Some("SIGNATURE"))
2223                )),
2224            )],
2225        )
2226    }
2227
2228    pub fn create(
2229        attributes: &Attributes,
2230        exclude: &[&str],
2231        validate: bool,
2232    ) -> Result<Self> {
2233        Self::parse(&Self::content(attributes, exclude), validate)
2234    }
2235}
2236
2237#[derive(Debug, Clone, PartialEq, serde::Serialize)]
2238pub struct BridgeNetworkStatusDocument {
2239    #[serde(skip)]
2240    pub raw_contents: Vec<u8>,
2241    pub published: Option<NaiveDateTime>,
2242    pub routers: IndexMap<String, RouterStatusEntryV2>,
2243}
2244
2245impl BridgeNetworkStatusDocument {
2246    pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
2247        let mut cursor = LineCursor::new(content);
2248        let first = cursor
2249            .read_line()
2250            .map(|line| String::from_utf8_lossy(line).into_owned())
2251            .unwrap_or_default();
2252        let mut published = None;
2253        match first.strip_prefix("published ") {
2254            Some(rest) => {
2255                let rest = rest.trim();
2256                match parse_timestamp(rest) {
2257                    Ok(timestamp) => published = Some(timestamp),
2258                    Err(_) if validate => {
2259                        return Err(Error::parse(format!(
2260                            "Bridge network status document's 'published' time wasn't \
2261                            parsable: {rest}"
2262                        )));
2263                    }
2264                    Err(_) => {}
2265                }
2266            }
2267            None if validate => {
2268                return Err(Error::parse(format!(
2269                    "Bridge network status documents must start with a 'published' \
2270                    line:\n{}",
2271                    String::from_utf8_lossy(content)
2272                )));
2273            }
2274            None => {}
2275        }
2276        let routers = parse_entry_section(&mut cursor, validate, &[], None, |bytes| {
2277            RouterStatusEntryV2::parse(bytes, validate)
2278        })?;
2279        Ok(Self {
2280            raw_contents: content.to_vec(),
2281            published,
2282            routers: routers
2283                .into_iter()
2284                .filter_map(|entry| Some((entry.fingerprint.clone()?, entry)))
2285                .collect(),
2286        })
2287    }
2288}