1use std::ops::Deref;
2
3use chrono::NaiveDateTime;
4use indexmap::IndexMap;
5use rsa::RsaPrivateKey;
6
7use crate::address::{is_valid_ipv4_address, is_valid_ipv6_address, parse_port};
8use crate::descriptor::server::append_router_signature;
9use crate::descriptor::{
10 AttrValue, Attributes, DigestEncoding, DigestHash, Entries, History, LineCursor,
11 ReadOptions, content_range, descriptor_components, descriptor_content, encode_digest,
12 hash_bytes, key_block, lenient, lenient_option, mappings_for, parse_forty_hex,
13 parse_history, parse_timestamp_and_interval, parse_timestamp_line,
14 random_crypto_blob, random_date, random_fingerprint, random_nickname,
15};
16use crate::error::{Error, Result};
17use crate::validation::{is_valid_fingerprint, is_valid_nickname};
18
19const DIR_RESPONSES: [&str; 6] = [
20 "ok",
21 "not-enough-sigs",
22 "unavailable",
23 "not-found",
24 "not-modified",
25 "busy",
26];
27const DIR_STATS: [&str; 16] = [
28 "complete", "timeout", "running", "min", "max", "q1", "q3", "md", "d1", "d2", "d3",
29 "d4", "d6", "d7", "d8", "d9",
30];
31const REQUIRED_FIELDS: [&str; 3] = ["extra-info", "published", "router-signature"];
32const SINGLE_FIELDS: [&str; 33] = [
33 "read-history",
34 "write-history",
35 "geoip-db-digest",
36 "geoip6-db-digest",
37 "bridge-stats-end",
38 "bridge-ips",
39 "dirreq-stats-end",
40 "dirreq-v2-ips",
41 "dirreq-v3-ips",
42 "dirreq-v2-reqs",
43 "dirreq-v3-reqs",
44 "dirreq-v2-share",
45 "dirreq-v3-share",
46 "dirreq-v2-resp",
47 "dirreq-v3-resp",
48 "dirreq-v2-direct-dl",
49 "dirreq-v3-direct-dl",
50 "dirreq-v2-tunneled-dl",
51 "dirreq-v3-tunneled-dl",
52 "dirreq-read-history",
53 "dirreq-write-history",
54 "entry-stats-end",
55 "entry-ips",
56 "cell-stats-end",
57 "cell-processed-cells",
58 "cell-queued-cells",
59 "cell-time-in-queue",
60 "cell-circuits-per-decile",
61 "conn-bi-direct",
62 "exit-stats-end",
63 "exit-kibibytes-written",
64 "exit-kibibytes-read",
65 "exit-streams-opened",
66];
67const RECOGNIZED_KEYWORDS: [&str; 50] = [
68 "extra-info",
69 "geoip-db-digest",
70 "geoip6-db-digest",
71 "transport",
72 "cell-circuits-per-decile",
73 "dirreq-v2-resp",
74 "dirreq-v3-resp",
75 "dirreq-v2-direct-dl",
76 "dirreq-v3-direct-dl",
77 "dirreq-v2-tunneled-dl",
78 "dirreq-v3-tunneled-dl",
79 "dirreq-v2-share",
80 "dirreq-v3-share",
81 "cell-processed-cells",
82 "cell-queued-cells",
83 "cell-time-in-queue",
84 "published",
85 "geoip-start-time",
86 "cell-stats-end",
87 "entry-stats-end",
88 "exit-stats-end",
89 "bridge-stats-end",
90 "dirreq-stats-end",
91 "conn-bi-direct",
92 "read-history",
93 "write-history",
94 "dirreq-read-history",
95 "dirreq-write-history",
96 "exit-kibibytes-written",
97 "exit-kibibytes-read",
98 "exit-streams-opened",
99 "hidserv-stats-end",
100 "hidserv-rend-relayed-cells",
101 "hidserv-dir-onions-seen",
102 "padding-counts",
103 "dirreq-v2-ips",
104 "dirreq-v3-ips",
105 "dirreq-v2-reqs",
106 "dirreq-v3-reqs",
107 "geoip-client-origins",
108 "entry-ips",
109 "bridge-ips",
110 "bridge-ip-versions",
111 "bridge-ip-transports",
112 "identity-ed25519",
113 "router-sig-ed25519",
114 "router-signature",
115 "master-key-ed25519",
116 "router-digest-sha256",
117 "router-digest",
118];
119
120#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
121pub struct StatsPeriod {
122 pub end: NaiveDateTime,
123 pub interval: u64,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
127pub struct Transport {
128 pub address: Option<String>,
129 pub port: Option<u16>,
130 pub args: Option<Vec<String>>,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
134pub struct ConnBiDirect {
135 pub end: NaiveDateTime,
136 pub interval: u64,
137 pub below: u64,
138 pub read: u64,
139 pub write: u64,
140 pub both: u64,
141}
142
143#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
144pub struct DirCounts {
145 pub recognized: IndexMap<String, u64>,
146 pub unknown: IndexMap<String, u64>,
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, Hash)]
150pub enum PortKey {
151 Port(u16),
152 Other,
153}
154
155impl serde::Serialize for PortKey {
156 fn serialize<S: serde::Serializer>(
157 &self,
158 serializer: S,
159 ) -> std::result::Result<S::Ok, S::Error> {
160 match self {
161 Self::Port(port) => serializer.collect_str(port),
162 Self::Other => serializer.serialize_str("other"),
163 }
164 }
165}
166
167#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
168#[serde(untagged)]
169pub enum CountValue {
170 Number(u64),
171 Text(String),
172}
173
174#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
175pub struct HiddenServiceStat {
176 pub value: Option<i64>,
177 pub attributes: IndexMap<String, String>,
178}
179
180#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]
181pub struct ExtraInfoDescriptor {
182 #[serde(skip)]
183 pub raw_contents: Vec<u8>,
184 pub unrecognized_lines: Vec<String>,
185 pub nickname: Option<String>,
186 pub fingerprint: Option<String>,
187 pub published: Option<NaiveDateTime>,
188 pub geoip_db_digest: Option<String>,
189 pub geoip6_db_digest: Option<String>,
190 pub transport: IndexMap<String, Transport>,
191 pub conn_bi_direct: Option<ConnBiDirect>,
192 pub read_history: Option<History>,
193 pub write_history: Option<History>,
194 pub dir_read_history: Option<History>,
195 pub dir_write_history: Option<History>,
196 pub cell_stats: Option<StatsPeriod>,
197 pub cell_processed_cells: Option<Vec<f64>>,
198 pub cell_queued_cells: Option<Vec<f64>>,
199 pub cell_time_in_queue: Option<Vec<f64>>,
200 pub cell_circuits_per_decile: Option<u64>,
201 pub dir_stats: Option<StatsPeriod>,
202 pub dir_v2_ips: Option<IndexMap<String, u64>>,
203 pub dir_v3_ips: Option<IndexMap<String, u64>>,
204 pub dir_v2_share: Option<f64>,
205 pub dir_v3_share: Option<f64>,
206 pub dir_v2_requests: Option<IndexMap<String, u64>>,
207 pub dir_v3_requests: Option<IndexMap<String, u64>>,
208 pub dir_v2_responses: Option<DirCounts>,
209 pub dir_v3_responses: Option<DirCounts>,
210 pub dir_v2_direct_dl: Option<DirCounts>,
211 pub dir_v3_direct_dl: Option<DirCounts>,
212 pub dir_v2_tunneled_dl: Option<DirCounts>,
213 pub dir_v3_tunneled_dl: Option<DirCounts>,
214 pub entry_stats: Option<StatsPeriod>,
215 pub entry_ips: Option<IndexMap<String, u64>>,
216 pub exit_stats: Option<StatsPeriod>,
217 pub exit_kibibytes_written: Option<IndexMap<PortKey, u64>>,
218 pub exit_kibibytes_read: Option<IndexMap<PortKey, u64>>,
219 pub exit_streams_opened: Option<IndexMap<PortKey, u64>>,
220 pub hs_stats_end: Option<NaiveDateTime>,
221 pub hs_rend_cells: Option<HiddenServiceStat>,
222 pub hs_dir_onions_seen: Option<HiddenServiceStat>,
223 pub padding_counts: IndexMap<String, CountValue>,
224 pub padding_counts_period: Option<StatsPeriod>,
225 pub bridge_stats: Option<StatsPeriod>,
226 pub bridge_ips: Option<IndexMap<String, u64>>,
227 pub geoip_start_time: Option<NaiveDateTime>,
228 pub geoip_client_origins: Option<IndexMap<String, u64>>,
229 pub ip_versions: Option<IndexMap<String, u64>>,
230 pub ip_transports: Option<IndexMap<String, u64>>,
231}
232
233#[derive(Debug, Clone, PartialEq, serde::Serialize)]
234pub struct RelayExtraInfoDescriptor {
235 #[serde(flatten)]
236 pub common: ExtraInfoDescriptor,
237 pub ed25519_certificate: Option<String>,
238 pub ed25519_signature: Option<String>,
239 pub signature: Option<String>,
240}
241
242#[derive(Debug, Clone, PartialEq, serde::Serialize)]
243pub struct BridgeExtraInfoDescriptor {
244 #[serde(flatten)]
245 pub common: ExtraInfoDescriptor,
246 pub ed25519_certificate_hash: Option<String>,
247 pub router_digest_sha256: Option<String>,
248 digest: Option<String>,
249}
250
251impl Deref for RelayExtraInfoDescriptor {
252 type Target = ExtraInfoDescriptor;
253
254 fn deref(&self) -> &ExtraInfoDescriptor {
255 &self.common
256 }
257}
258
259impl Deref for BridgeExtraInfoDescriptor {
260 type Target = ExtraInfoDescriptor;
261
262 fn deref(&self) -> &ExtraInfoDescriptor {
263 &self.common
264 }
265}
266
267fn parse_unsigned_text(text: &str) -> Option<u64> {
268 match !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit()) {
269 true => text.parse().ok(),
270 false => None,
271 }
272}
273
274fn parse_period(keyword: &str, value: &str) -> Result<StatsPeriod> {
275 let (end, interval, _) = parse_timestamp_and_interval(keyword, value)?;
276 Ok(StatsPeriod { end, interval })
277}
278
279fn parse_extra_info_line(value: &str) -> Result<(String, String)> {
280 let parts: Vec<&str> = value.split_whitespace().collect();
281 if parts.len() < 2 {
282 return Err(Error::parse(format!(
283 "Extra-info line must have two values: extra-info {value}"
284 )));
285 }
286 if !is_valid_nickname(parts[0]) {
287 return Err(Error::parse(format!(
288 "Extra-info line entry isn't a valid nickname: {}",
289 parts[0]
290 )));
291 }
292 if !is_valid_fingerprint(parts[1], false) {
293 return Err(Error::parse(format!(
294 "Tor relay fingerprints consist of forty hex digits: {}",
295 parts[1]
296 )));
297 }
298 Ok((parts[0].to_string(), parts[1].to_string()))
299}
300
301fn parse_transports(entries: &Entries) -> Result<IndexMap<String, Transport>> {
302 let mut transports = IndexMap::new();
303 for value in entries.values("transport") {
304 if !value.contains(' ') {
305 transports.insert(
306 value.to_string(),
307 Transport {
308 address: None,
309 port: None,
310 args: None,
311 },
312 );
313 continue;
314 }
315 let parts: Vec<&str> = value.split_whitespace().collect();
316 if parts.len() < 2 {
317 return Err(Error::parse(format!(
318 "Transport line is missing its address:port value: transport {value}"
319 )));
320 }
321 let Some((address, port_text)) = parts[1].rsplit_once(':') else {
322 return Err(Error::parse(format!(
323 "Transport line's address:port entry is missing a colon: transport \
324 {value}"
325 )));
326 };
327 if !is_valid_ipv4_address(address) && !is_valid_ipv6_address(address, true) {
328 return Err(Error::parse(format!(
329 "Transport line has a malformed address: transport {value}"
330 )));
331 }
332 let Some(port) = parse_port(port_text, false) else {
333 return Err(Error::parse(format!(
334 "Transport line has a malformed port: transport {value}"
335 )));
336 };
337 transports.insert(
338 parts[0].to_string(),
339 Transport {
340 address: Some(address.to_string()),
341 port: Some(port),
342 args: Some(parts[2..].iter().map(|arg| arg.to_string()).collect()),
343 },
344 );
345 }
346 Ok(transports)
347}
348
349fn parse_padding_counts(
350 value: &str,
351) -> Result<(StatsPeriod, IndexMap<String, CountValue>)> {
352 let (end, interval, remainder) =
353 parse_timestamp_and_interval("padding-counts", value)?;
354 let mut counts = IndexMap::new();
355 for (key, mapped) in mappings_for("padding-counts", &remainder, true, ' ')? {
356 let count = match parse_unsigned_text(&mapped) {
357 Some(number) => CountValue::Number(number),
358 None => CountValue::Text(mapped),
359 };
360 counts.insert(key, count);
361 }
362 Ok((StatsPeriod { end, interval }, counts))
363}
364
365fn parse_dir_counts(keyword: &str, value: &str, is_response: bool) -> Result<DirCounts> {
366 let recognized_set: &[&str] = if is_response {
367 &DIR_RESPONSES
368 } else {
369 &DIR_STATS
370 };
371 let key_type = if is_response { "STATUS" } else { "STAT" };
372 let mut counts = DirCounts::default();
373 for (status, count) in mappings_for(keyword, value, false, ',')? {
374 let Some(number) = parse_unsigned_text(&count) else {
375 return Err(Error::parse(format!(
376 "{keyword} lines should contain {key_type}=COUNT mappings: {keyword} \
377 {value}"
378 )));
379 };
380 match recognized_set.contains(&status.as_str()) {
381 true => counts.recognized.insert(status, number),
382 false => counts.unknown.insert(status, number),
383 };
384 }
385 Ok(counts)
386}
387
388fn parse_dir_share(keyword: &str, value: &str) -> Result<f64> {
389 let Some(percentage) = value.strip_suffix('%') else {
390 return Err(Error::parse(format!(
391 "{keyword} lines should be a percentage: {keyword} {value}"
392 )));
393 };
394 let number: f64 = percentage.parse().map_err(|_| {
395 Error::parse(format!(
396 "{keyword} lines should be a percentage: {keyword} {value}"
397 ))
398 })?;
399 match number < 0.0 {
400 true => Err(Error::parse(format!(
401 "Negative percentage value: {keyword} {value}"
402 ))),
403 false => Ok(number / 100.0),
404 }
405}
406
407fn parse_cell_values(keyword: &str, value: &str) -> Result<Vec<f64>> {
408 match value.is_empty() {
409 true => Ok(Vec::new()),
410 false => value
411 .split(',')
412 .map(|entry| entry.parse::<f64>())
413 .collect::<std::result::Result<Vec<_>, _>>()
414 .map_err(|_| {
415 Error::parse(format!(
416 "Non-numeric entry in {keyword} listing: {keyword} {value}"
417 ))
418 }),
419 }
420}
421
422fn parse_conn_bi_direct(value: &str) -> Result<ConnBiDirect> {
423 let (end, interval, remainder) =
424 parse_timestamp_and_interval("conn-bi-direct", value)?;
425 let stats: Vec<Option<u64>> = remainder.split(',').map(parse_unsigned_text).collect();
426 match stats.as_slice() {
427 [Some(below), Some(read), Some(write), Some(both)] => Ok(ConnBiDirect {
428 end,
429 interval,
430 below: *below,
431 read: *read,
432 write: *write,
433 both: *both,
434 }),
435 _ => Err(Error::parse(format!(
436 "conn-bi-direct line should end with four numeric values: conn-bi-direct \
437 {value}"
438 ))),
439 }
440}
441
442fn parse_port_counts(keyword: &str, value: &str) -> Result<IndexMap<PortKey, u64>> {
443 let mut mappings = IndexMap::new();
444 for (port, stat) in mappings_for(keyword, value, false, ',')? {
445 let key = match port.as_str() {
446 "other" => Some(PortKey::Other),
447 text => parse_port(text, false).map(PortKey::Port),
448 };
449 let (Some(key), Some(count)) = (key, parse_unsigned_text(&stat)) else {
450 return Err(Error::parse(format!(
451 "Entries in {keyword} line should only be PORT=N entries: {keyword} \
452 {value}"
453 )));
454 };
455 mappings.insert(key, count);
456 }
457 Ok(mappings)
458}
459
460fn parse_geoip_counts(keyword: &str, value: &str) -> Result<IndexMap<String, u64>> {
461 let mut usage = IndexMap::new();
462 for (locale, count) in mappings_for(keyword, value, false, ',')? {
463 let is_locale = locale.chars().count() == 2
464 && locale
465 .chars()
466 .all(|character| character.is_ascii_alphanumeric() || character == '?');
467 let (true, Some(number)) = (is_locale, parse_unsigned_text(&count)) else {
468 return Err(Error::parse(format!(
469 "Entries in {keyword} line should only be CC=N entries: {keyword} {value}"
470 )));
471 };
472 usage.insert(locale, number);
473 }
474 Ok(usage)
475}
476
477fn parse_named_counts(
478 keyword: &str,
479 label: &str,
480 value: &str,
481) -> Result<IndexMap<String, u64>> {
482 let mut counts = IndexMap::new();
483 for (name, count) in mappings_for(keyword, value, false, ',')? {
484 let Some(number) = parse_unsigned_text(&count) else {
485 return Err(Error::protocol(format!(
486 "{label} count was non-numeric ({count}): {keyword} {value}"
487 )));
488 };
489 counts.insert(name, number);
490 }
491 Ok(counts)
492}
493
494fn parse_hs_stats(keyword: &str, value: &str) -> Result<HiddenServiceStat> {
495 if value.is_empty() {
496 return Err(Error::parse(format!("'{keyword}' line was blank")));
497 }
498 let (stat_text, remainder) = value.split_once(' ').unwrap_or((value, ""));
499 let stat: i64 = stat_text.parse().map_err(|_| {
500 Error::parse(format!(
501 "'{keyword}' stat was non-numeric ({stat_text}): {keyword} {value}"
502 ))
503 })?;
504 let attributes = mappings_for(keyword, remainder, false, ' ')?
505 .into_iter()
506 .collect();
507 Ok(HiddenServiceStat {
508 value: Some(stat),
509 attributes,
510 })
511}
512
513fn check_constraints(
514 entries: &Entries,
515 required: &[&str],
516 last_keyword: Option<&str>,
517) -> Result<()> {
518 for keyword in required {
519 if !entries.contains(keyword) {
520 return Err(Error::parse(format!(
521 "Extra-info descriptor must have a '{keyword}' entry"
522 )));
523 }
524 }
525 for keyword in required.iter().chain(SINGLE_FIELDS.iter()) {
526 if entries.get(keyword).is_some_and(|values| values.len() > 1) {
527 return Err(Error::parse(format!(
528 "The '{keyword}' entry can only appear once in an extra-info descriptor"
529 )));
530 }
531 }
532 if entries.first_key() != Some("extra-info") {
533 return Err(Error::parse(
534 "Extra-info descriptor must start with a 'extra-info' entry",
535 ));
536 }
537 match last_keyword {
538 Some(last) if entries.last_key() != Some(last) => Err(Error::parse(format!(
539 "Descriptor must end with a '{last}' entry"
540 ))),
541 _ => Ok(()),
542 }
543}
544
545fn parse_stats_end(keyword: &str, value: &str) -> Result<NaiveDateTime> {
546 match value.contains(" (") {
547 true => parse_timestamp_and_interval(keyword, value).map(|(end, _, _)| end),
548 false => parse_timestamp_line(keyword, value),
549 }
550}
551
552macro_rules! assign {
553 ($validate:expr, $entries:expr, $keyword:expr, $target:expr, $parse:expr) => {
554 if let Ok(value) = $entries.value($keyword) {
555 $target = lenient_option($validate, $parse($keyword, value))?;
556 }
557 };
558}
559
560fn parse_common(
561 content: &[u8],
562 entries: &Entries,
563 validate: bool,
564 extra_keywords: &[&str],
565) -> Result<ExtraInfoDescriptor> {
566 let mut recognized: Vec<&str> = RECOGNIZED_KEYWORDS.to_vec();
567 recognized.extend_from_slice(extra_keywords);
568 let mut info = ExtraInfoDescriptor {
569 raw_contents: content.to_vec(),
570 unrecognized_lines: entries.unrecognized_lines(&recognized),
571 ..Default::default()
572 };
573 if let Ok(value) = entries.value("extra-info")
574 && let Some((nickname, fingerprint)) =
575 lenient_option(validate, parse_extra_info_line(value))?
576 {
577 info.nickname = Some(nickname);
578 info.fingerprint = Some(fingerprint);
579 }
580 assign!(
581 validate,
582 entries,
583 "published",
584 info.published,
585 parse_timestamp_line
586 );
587 assign!(
588 validate,
589 entries,
590 "geoip-start-time",
591 info.geoip_start_time,
592 parse_timestamp_line
593 );
594 assign!(
595 validate,
596 entries,
597 "hidserv-stats-end",
598 info.hs_stats_end,
599 parse_stats_end
600 );
601 assign!(
602 validate,
603 entries,
604 "geoip-db-digest",
605 info.geoip_db_digest,
606 parse_forty_hex
607 );
608 assign!(
609 validate,
610 entries,
611 "geoip6-db-digest",
612 info.geoip6_db_digest,
613 parse_forty_hex
614 );
615 if entries.contains("transport") {
616 info.transport = lenient(validate, parse_transports(entries))?;
617 }
618 if let Ok(value) = entries.value("conn-bi-direct") {
619 info.conn_bi_direct = lenient_option(validate, parse_conn_bi_direct(value))?;
620 }
621 assign!(
622 validate,
623 entries,
624 "read-history",
625 info.read_history,
626 parse_history
627 );
628 assign!(
629 validate,
630 entries,
631 "write-history",
632 info.write_history,
633 parse_history
634 );
635 assign!(
636 validate,
637 entries,
638 "dirreq-read-history",
639 info.dir_read_history,
640 parse_history
641 );
642 assign!(
643 validate,
644 entries,
645 "dirreq-write-history",
646 info.dir_write_history,
647 parse_history
648 );
649 assign!(
650 validate,
651 entries,
652 "cell-stats-end",
653 info.cell_stats,
654 parse_period
655 );
656 assign!(
657 validate,
658 entries,
659 "entry-stats-end",
660 info.entry_stats,
661 parse_period
662 );
663 assign!(
664 validate,
665 entries,
666 "exit-stats-end",
667 info.exit_stats,
668 parse_period
669 );
670 assign!(
671 validate,
672 entries,
673 "bridge-stats-end",
674 info.bridge_stats,
675 parse_period
676 );
677 assign!(
678 validate,
679 entries,
680 "dirreq-stats-end",
681 info.dir_stats,
682 parse_period
683 );
684 assign!(
685 validate,
686 entries,
687 "cell-processed-cells",
688 info.cell_processed_cells,
689 parse_cell_values
690 );
691 assign!(
692 validate,
693 entries,
694 "cell-queued-cells",
695 info.cell_queued_cells,
696 parse_cell_values
697 );
698 assign!(
699 validate,
700 entries,
701 "cell-time-in-queue",
702 info.cell_time_in_queue,
703 parse_cell_values
704 );
705 if let Ok(value) = entries.value("cell-circuits-per-decile") {
706 info.cell_circuits_per_decile = lenient_option(
707 validate,
708 crate::descriptor::parse_integer("cell-circuits-per-decile", value, false)
709 .map(|number| number as u64),
710 )?;
711 }
712 assign!(
713 validate,
714 entries,
715 "dirreq-v2-share",
716 info.dir_v2_share,
717 parse_dir_share
718 );
719 assign!(
720 validate,
721 entries,
722 "dirreq-v3-share",
723 info.dir_v3_share,
724 parse_dir_share
725 );
726 for (keyword, target, is_response) in [
727 ("dirreq-v2-resp", &mut info.dir_v2_responses, true),
728 ("dirreq-v3-resp", &mut info.dir_v3_responses, true),
729 ("dirreq-v2-direct-dl", &mut info.dir_v2_direct_dl, false),
730 ("dirreq-v3-direct-dl", &mut info.dir_v3_direct_dl, false),
731 ("dirreq-v2-tunneled-dl", &mut info.dir_v2_tunneled_dl, false),
732 ("dirreq-v3-tunneled-dl", &mut info.dir_v3_tunneled_dl, false),
733 ] {
734 if let Ok(value) = entries.value(keyword) {
735 *target =
736 lenient_option(validate, parse_dir_counts(keyword, value, is_response))?;
737 }
738 }
739 for (keyword, target) in [
740 ("exit-kibibytes-written", &mut info.exit_kibibytes_written),
741 ("exit-kibibytes-read", &mut info.exit_kibibytes_read),
742 ("exit-streams-opened", &mut info.exit_streams_opened),
743 ] {
744 if let Ok(value) = entries.value(keyword) {
745 *target = lenient_option(validate, parse_port_counts(keyword, value))?;
746 }
747 }
748 for (keyword, target) in [
749 ("dirreq-v2-ips", &mut info.dir_v2_ips),
750 ("dirreq-v3-ips", &mut info.dir_v3_ips),
751 ("dirreq-v2-reqs", &mut info.dir_v2_requests),
752 ("dirreq-v3-reqs", &mut info.dir_v3_requests),
753 ("geoip-client-origins", &mut info.geoip_client_origins),
754 ("entry-ips", &mut info.entry_ips),
755 ("bridge-ips", &mut info.bridge_ips),
756 ] {
757 if let Ok(value) = entries.value(keyword) {
758 *target = lenient_option(validate, parse_geoip_counts(keyword, value))?;
759 }
760 }
761 for (keyword, target) in [
762 ("hidserv-rend-relayed-cells", &mut info.hs_rend_cells),
763 ("hidserv-dir-onions-seen", &mut info.hs_dir_onions_seen),
764 ] {
765 if let Ok(value) = entries.value(keyword) {
766 *target = lenient_option(validate, parse_hs_stats(keyword, value))?;
767 }
768 }
769 if let Ok(value) = entries.value("padding-counts")
770 && let Some((period, counts)) =
771 lenient_option(validate, parse_padding_counts(value))?
772 {
773 info.padding_counts_period = Some(period);
774 info.padding_counts = counts;
775 }
776 if let Ok(value) = entries.value("bridge-ip-versions") {
777 info.ip_versions = lenient_option(
778 validate,
779 parse_named_counts("bridge-ip-versions", "IP protocol", value),
780 )?;
781 }
782 if let Ok(value) = entries.value("bridge-ip-transports") {
783 info.ip_transports = lenient_option(
784 validate,
785 parse_named_counts("bridge-ip-transports", "Transport", value),
786 )?;
787 }
788 Ok(info)
789}
790
791impl RelayExtraInfoDescriptor {
792 pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
793 let (entries, _) = descriptor_components(content, validate, &[], &[])?;
794 if validate {
795 check_constraints(&entries, &REQUIRED_FIELDS, Some("router-signature"))?;
796 }
797 let common = parse_common(content, &entries, validate, &[])?;
798 let mut descriptor = Self {
799 common,
800 ed25519_certificate: None,
801 ed25519_signature: None,
802 signature: None,
803 };
804 if entries.contains("identity-ed25519") {
805 descriptor.ed25519_certificate = lenient_option(
806 validate,
807 key_block(&entries, "identity-ed25519", "ED25519 CERT")
808 .map(|(_, block)| block),
809 )?;
810 }
811 descriptor.ed25519_signature =
812 entries.value("router-sig-ed25519").ok().map(str::to_string);
813 if entries.contains("router-signature") {
814 descriptor.signature = lenient_option(
815 validate,
816 key_block(&entries, "router-signature", "SIGNATURE")
817 .map(|(_, block)| block),
818 )?;
819 }
820 Ok(descriptor)
821 }
822
823 pub fn parse_many(content: &[u8], validate: bool) -> Result<Vec<Self>> {
824 split_extrainfo(content, false)
825 .into_iter()
826 .map(|text| Self::parse(&text, validate))
827 .collect()
828 }
829
830 pub fn digest(&self, hash: DigestHash, encoding: DigestEncoding) -> Result<String> {
831 let bytes = match hash {
832 DigestHash::Sha1 => hash_bytes(
833 hash,
834 &content_range(&self.raw_contents, None, Some("\nrouter-signature\n"))?,
835 ),
836 DigestHash::Sha256 => hash_bytes(hash, &self.raw_contents),
837 };
838 Ok(encode_digest(&bytes, encoding))
839 }
840
841 pub fn content(
842 attributes: &Attributes,
843 exclude: &[&str],
844 signing_key: Option<&RsaPrivateKey>,
845 ) -> Result<Vec<u8>> {
846 let header = [
847 (
848 "extra-info",
849 AttrValue::Text(format!(
850 "{} {}",
851 random_nickname(),
852 random_fingerprint()
853 )),
854 ),
855 ("published", AttrValue::Text(random_date())),
856 ];
857 let Some(private_key) = signing_key else {
858 let footer = [(
859 "router-signature",
860 AttrValue::Text(random_crypto_blob(Some("SIGNATURE"))),
861 )];
862 return Ok(descriptor_content(attributes, exclude, &header, &footer));
863 };
864 if attributes.iter().any(|(key, _)| key == "router-signature") {
865 return Err(Error::invalid_input(
866 "Cannot sign the descriptor if a router-signature has been provided",
867 ));
868 }
869 let mut content = descriptor_content(attributes, exclude, &header, &[]);
870 content.extend_from_slice(b"\nrouter-signature\n");
871 append_router_signature(content, private_key)
872 }
873
874 pub fn create(
875 attributes: &Attributes,
876 exclude: &[&str],
877 validate: bool,
878 signing_key: Option<&RsaPrivateKey>,
879 ) -> Result<Self> {
880 Self::parse(&Self::content(attributes, exclude, signing_key)?, validate)
881 }
882}
883
884impl BridgeExtraInfoDescriptor {
885 pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
886 let (entries, _) = descriptor_components(content, validate, &[], &[])?;
887 if validate {
888 let required = ["router-digest", "extra-info", "published"];
889 check_constraints(&entries, &required, None)?;
890 }
891 let common = parse_common(content, &entries, validate, &[])?;
892 let digest = match entries.value("router-digest") {
893 Ok(value) => {
894 lenient_option(validate, parse_forty_hex("router-digest", value))?
895 }
896 Err(_) => None,
897 };
898 Ok(Self {
899 common,
900 ed25519_certificate_hash: entries
901 .value("master-key-ed25519")
902 .ok()
903 .map(str::to_string),
904 router_digest_sha256: entries
905 .value("router-digest-sha256")
906 .ok()
907 .map(str::to_string),
908 digest,
909 })
910 }
911
912 pub fn parse_many(content: &[u8], validate: bool) -> Result<Vec<Self>> {
913 split_extrainfo(content, true)
914 .into_iter()
915 .map(|text| Self::parse(&text, validate))
916 .collect()
917 }
918
919 pub fn digest(&self, hash: DigestHash, encoding: DigestEncoding) -> Result<String> {
920 match (hash, encoding) {
921 (DigestHash::Sha1, DigestEncoding::Hex) => {
922 Ok(self.digest.clone().unwrap_or_default())
923 }
924 (DigestHash::Sha256, DigestEncoding::Base64) => {
925 Ok(self.router_digest_sha256.clone().unwrap_or_default())
926 }
927 _ => Err(Error::invalid_input(
928 "Bridge extrainfo digests are only available as sha1/hex and \
929 sha256/base64",
930 )),
931 }
932 }
933
934 pub fn content(attributes: &Attributes, exclude: &[&str]) -> Vec<u8> {
935 descriptor_content(
936 attributes,
937 exclude,
938 &[
939 (
940 "extra-info",
941 AttrValue::Text(format!(
942 "ec2bridgereaac65a3 {}",
943 random_fingerprint()
944 )),
945 ),
946 ("published", AttrValue::Text(random_date())),
947 ],
948 &[("router-digest", AttrValue::Text(random_fingerprint()))],
949 )
950 }
951
952 pub fn create(
953 attributes: &Attributes,
954 exclude: &[&str],
955 validate: bool,
956 ) -> Result<Self> {
957 Self::parse(&Self::content(attributes, exclude), validate)
958 }
959}
960
961fn split_extrainfo(content: &[u8], is_bridge: bool) -> Vec<Vec<u8>> {
962 let mut cursor = LineCursor::new(content);
963 let mut found = Vec::new();
964 loop {
965 let mut body = if is_bridge {
966 cursor
967 .read_until_keywords(
968 &["router-digest"],
969 ReadOptions {
970 inclusive: true,
971 ..Default::default()
972 },
973 )
974 .content
975 } else {
976 let mut body = cursor
977 .read_until_keywords(&["router-signature"], ReadOptions::default())
978 .content;
979 body.extend(
980 cursor
981 .read_until_keywords(
982 &["-----END"],
983 ReadOptions {
984 inclusive: true,
985 ..Default::default()
986 },
987 )
988 .content,
989 );
990 body
991 };
992 if body.is_empty() {
993 break;
994 }
995 if body.starts_with(b"@type") {
996 body = body
997 .splitn(2, |byte| *byte == b'\n')
998 .nth(1)
999 .unwrap_or_default()
1000 .to_vec();
1001 }
1002 found.push(body);
1003 }
1004 found
1005}