Skip to main content

stem/descriptor/
mod.rs

1pub mod bandwidth_file;
2pub mod certificate;
3pub mod collector;
4pub mod export;
5pub mod extrainfo;
6pub mod hidden_service;
7pub mod microdescriptor;
8pub mod network_status;
9pub mod parsing;
10pub mod reader;
11pub mod remote;
12pub mod router_status;
13pub mod server;
14pub mod tordnsel;
15
16use std::collections::HashMap;
17use std::io::Read;
18
19use base64::Engine;
20use base64::alphabet::STANDARD;
21use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
22use chrono::NaiveDateTime;
23use indexmap::IndexMap;
24use sha1::Sha1;
25use sha2::{Digest, Sha256};
26
27use crate::error::{Error, Result};
28use crate::formatting::parse_timestamp;
29
30pub const MAX_DECOMPRESSED_LENGTH: u64 = 1 << 29;
31const MAX_PROTOCOL_VERSIONS: u32 = 4096;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum DigestHash {
35    Sha1,
36    Sha256,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum DigestEncoding {
41    Hex,
42    Base64,
43}
44
45pub fn hash_bytes(hash: DigestHash, content: &[u8]) -> Vec<u8> {
46    match hash {
47        DigestHash::Sha1 => Sha1::digest(content).to_vec(),
48        DigestHash::Sha256 => Sha256::digest(content).to_vec(),
49    }
50}
51
52pub fn encode_digest(digest: &[u8], encoding: DigestEncoding) -> String {
53    match encoding {
54        DigestEncoding::Hex => hex::encode_upper(digest),
55        DigestEncoding::Base64 => truncated_base64(digest),
56    }
57}
58
59pub fn truncated_base64(content: &[u8]) -> String {
60    base64::engine::general_purpose::STANDARD
61        .encode(content)
62        .trim_end_matches('=')
63        .to_string()
64}
65
66pub fn decode_base64(content: &str) -> Result<Vec<u8>> {
67    let config = GeneralPurposeConfig::new()
68        .with_decode_padding_mode(DecodePaddingMode::Indifferent)
69        .with_decode_allow_trailing_bits(true);
70    let engine = GeneralPurpose::new(&STANDARD, config);
71    let cleaned: String = content.chars().filter(|c| !c.is_whitespace()).collect();
72    engine
73        .decode(cleaned.trim_end_matches('='))
74        .map_err(|error| Error::parse(format!("Invalid base64 content ({error})")))
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum Compression {
79    Plaintext,
80    Gzip,
81    Bzip2,
82    Lzma,
83    Zstd,
84}
85
86impl Compression {
87    pub fn extension(self) -> &'static str {
88        match self {
89            Self::Plaintext => ".txt",
90            Self::Gzip => ".gz",
91            Self::Bzip2 => ".bz2",
92            Self::Lzma => ".xz",
93            Self::Zstd => ".zst",
94        }
95    }
96
97    pub fn encoding(self) -> &'static str {
98        match self {
99            Self::Plaintext => "identity",
100            Self::Gzip => "gzip",
101            Self::Bzip2 => "bzip2",
102            Self::Lzma => "x-tor-lzma",
103            Self::Zstd => "x-zstd",
104        }
105    }
106
107    pub fn name(self) -> &'static str {
108        match self {
109            Self::Plaintext => "plaintext",
110            Self::Gzip => "gzip",
111            Self::Bzip2 => "bzip2",
112            Self::Lzma => "lzma",
113            Self::Zstd => "zstd",
114        }
115    }
116
117    pub fn from_encoding(encoding: &str) -> Option<Self> {
118        [
119            Self::Plaintext,
120            Self::Gzip,
121            Self::Bzip2,
122            Self::Lzma,
123            Self::Zstd,
124        ]
125        .into_iter()
126        .find(|candidate| candidate.encoding() == encoding.trim().to_lowercase())
127        .or(match encoding.trim().to_lowercase().as_str() {
128            "deflate" => Some(Self::Gzip),
129            _ => None,
130        })
131    }
132
133    pub fn decompress(self, content: &[u8]) -> Result<Vec<u8>> {
134        let failure = |error: String| {
135            Error::Io(std::io::Error::other(format!(
136                "Failed to decompress as {}: {error}",
137                self.name()
138            )))
139        };
140        let mut output = Vec::new();
141        match self {
142            Self::Plaintext => return Ok(content.to_vec()),
143            Self::Gzip => match content.starts_with(&[0x1f, 0x8b]) {
144                true => flate2::read::MultiGzDecoder::new(content)
145                    .take(MAX_DECOMPRESSED_LENGTH + 1)
146                    .read_to_end(&mut output)
147                    .map(|_| ())
148                    .map_err(|error| failure(error.to_string()))?,
149                false => flate2::read::ZlibDecoder::new(content)
150                    .take(MAX_DECOMPRESSED_LENGTH + 1)
151                    .read_to_end(&mut output)
152                    .map(|_| ())
153                    .map_err(|error| failure(error.to_string()))?,
154            },
155            Self::Bzip2 => {
156                bzip2_rs::DecoderReader::new(content)
157                    .take(MAX_DECOMPRESSED_LENGTH + 1)
158                    .read_to_end(&mut output)
159                    .map_err(|error| failure(error.to_string()))?;
160            }
161            Self::Lzma => {
162                let mut reader = std::io::BufReader::new(content);
163                let xz = lzma_rs::xz_decompress(&mut reader, &mut output);
164                if xz.is_err() {
165                    output.clear();
166                    let mut reader = std::io::BufReader::new(content);
167                    lzma_rs::lzma_decompress(&mut reader, &mut output)
168                        .map_err(|error| failure(error.to_string()))?;
169                }
170            }
171            Self::Zstd => {
172                let mut decoder = ruzstd::decoding::StreamingDecoder::new(content)
173                    .map_err(|error| failure(error.to_string()))?;
174                (&mut decoder)
175                    .take(MAX_DECOMPRESSED_LENGTH + 1)
176                    .read_to_end(&mut output)
177                    .map_err(|error| failure(error.to_string()))?;
178            }
179        }
180        match output.len() as u64 > MAX_DECOMPRESSED_LENGTH {
181            true => Err(failure(
182                "decompressed content exceeded the size limit".to_string(),
183            )),
184            false => Ok(output),
185        }
186    }
187}
188
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub struct Entry {
191    pub value: String,
192    pub block_type: Option<String>,
193    pub block_contents: Option<String>,
194}
195
196#[derive(Debug, Clone, Default)]
197pub struct Entries {
198    entries: IndexMap<String, Vec<Entry>>,
199}
200
201impl Entries {
202    pub fn get(&self, keyword: &str) -> Option<&[Entry]> {
203        self.entries.get(keyword).map(Vec::as_slice)
204    }
205
206    pub fn contains(&self, keyword: &str) -> bool {
207        self.entries.contains_key(keyword)
208    }
209
210    pub fn keys(&self) -> impl Iterator<Item = &String> {
211        self.entries.keys()
212    }
213
214    pub fn iter(&self) -> impl Iterator<Item = (&String, &Vec<Entry>)> {
215        self.entries.iter()
216    }
217
218    pub fn first_key(&self) -> Option<&str> {
219        self.entries.keys().next().map(String::as_str)
220    }
221
222    pub fn last_key(&self) -> Option<&str> {
223        self.entries.keys().next_back().map(String::as_str)
224    }
225
226    pub fn len(&self) -> usize {
227        self.entries.len()
228    }
229
230    pub fn is_empty(&self) -> bool {
231        self.entries.is_empty()
232    }
233
234    pub fn entry(&self, keyword: &str) -> Result<&Entry> {
235        self.get(keyword).and_then(<[Entry]>::first).ok_or_else(|| {
236            Error::parse(format!("Descriptor must have a '{keyword}' entry"))
237        })
238    }
239
240    pub fn value(&self, keyword: &str) -> Result<&str> {
241        self.entry(keyword).map(|entry| entry.value.as_str())
242    }
243
244    pub fn values(&self, keyword: &str) -> Vec<&str> {
245        self.get(keyword)
246            .map(|entries| entries.iter().map(|entry| entry.value.as_str()).collect())
247            .unwrap_or_default()
248    }
249
250    pub fn push(&mut self, keyword: &str, entry: Entry) {
251        self.entries
252            .entry(keyword.to_string())
253            .or_default()
254            .push(entry);
255    }
256
257    pub fn unrecognized_lines(&self, recognized: &[&str]) -> Vec<String> {
258        let mut lines = Vec::new();
259        for (keyword, entries) in &self.entries {
260            if recognized.contains(&keyword.as_str()) {
261                continue;
262            }
263            for entry in entries {
264                let mut line = format!("{keyword} {}", entry.value);
265                if let Some(block) = &entry.block_contents {
266                    line.push('\n');
267                    line.push_str(block);
268                }
269                lines.push(line);
270            }
271        }
272        lines
273    }
274}
275
276fn is_keyword_character(character: char) -> bool {
277    character.is_ascii_alphanumeric() || character == '-'
278}
279
280pub fn split_keyword_line(line: &str) -> Option<(&str, &str)> {
281    let keyword_end = line
282        .find(|character: char| !is_keyword_character(character))
283        .unwrap_or(line.len());
284    if keyword_end == 0 {
285        return None;
286    }
287    let (keyword, rest) = line.split_at(keyword_end);
288    match rest.is_empty() {
289        true => Some((keyword, "")),
290        false => {
291            let value = rest.trim_start_matches([' ', '\t']);
292            (value.len() != rest.len()).then_some((keyword, value))
293        }
294    }
295}
296
297fn pgp_block_type(line: &str) -> Option<&str> {
298    let inner = line.strip_prefix("-----BEGIN ")?.strip_suffix("-----")?;
299    let is_type = !inner.is_empty()
300        && inner.chars().all(|character| {
301            is_keyword_character(character) || character == ' ' || character == '\t'
302        });
303    is_type.then_some(inner)
304}
305
306fn pseudo_pgp_block(
307    remaining: &mut std::collections::VecDeque<&str>,
308) -> Result<Option<(String, String)>> {
309    let Some(block_type) = remaining.front().and_then(|line| pgp_block_type(line)) else {
310        return Ok(None);
311    };
312    let block_type = block_type.to_string();
313    let end_line = format!("-----END {block_type}-----");
314    let mut block_lines: Vec<&str> = Vec::new();
315    loop {
316        let Some(line) = remaining.pop_front() else {
317            return Err(Error::parse(format!(
318                "Unterminated pgp style block (looking for '{end_line}'):\n{}",
319                block_lines.join("\n")
320            )));
321        };
322        block_lines.push(line);
323        if line == end_line {
324            return Ok(Some((block_type, block_lines.join("\n"))));
325        }
326    }
327}
328
329pub fn descriptor_components(
330    raw_contents: &[u8],
331    validate: bool,
332    extra_keywords: &[&str],
333    non_ascii_fields: &[&str],
334) -> Result<(Entries, Vec<String>)> {
335    let text = String::from_utf8_lossy(raw_contents);
336    let mut entries = Entries::default();
337    let mut extra_entries = Vec::new();
338    let mut remaining: std::collections::VecDeque<&str> = text.split('\n').collect();
339    while let Some(raw_line) = remaining.pop_front() {
340        let line = raw_line.strip_prefix("opt ").unwrap_or(raw_line);
341        if line.is_empty() {
342            continue;
343        }
344        let Some((keyword, value)) = split_keyword_line(line) else {
345            match validate {
346                true => {
347                    return Err(Error::parse(format!(
348                        "Line contains invalid characters: {line}"
349                    )));
350                }
351                false => continue,
352            }
353        };
354        let block = match pseudo_pgp_block(&mut remaining) {
355            Ok(block) => block,
356            Err(error) if validate => return Err(error),
357            Err(_) => continue,
358        };
359        if validate && !non_ascii_fields.contains(&keyword) && !value.is_ascii() {
360            let replaced: String = value
361                .chars()
362                .map(|character| if character.is_ascii() { character } else { '?' })
363                .collect();
364            return Err(Error::parse(format!(
365                "'{keyword}' line had non-ascii content: {replaced}"
366            )));
367        }
368        if extra_keywords.contains(&keyword) {
369            extra_entries.push(format!("{keyword} {value}"));
370            continue;
371        }
372        let (block_type, block_contents) = match block {
373            Some((kind, contents)) => (Some(kind), Some(contents)),
374            None => (None, None),
375        };
376        entries.push(
377            keyword,
378            Entry {
379                value: value.to_string(),
380                block_type,
381                block_contents,
382            },
383        );
384    }
385    Ok((entries, extra_entries))
386}
387
388pub fn lenient<T: Default>(validate: bool, result: Result<T>) -> Result<T> {
389    match result {
390        Ok(value) => Ok(value),
391        Err(error) if validate => Err(error),
392        Err(_) => Ok(T::default()),
393    }
394}
395
396pub fn lenient_option<T>(validate: bool, result: Result<T>) -> Result<Option<T>> {
397    match result {
398        Ok(value) => Ok(Some(value)),
399        Err(error) if validate => Err(error),
400        Err(_) => Ok(None),
401    }
402}
403
404pub fn bytes_for_block(content: &str) -> Result<Vec<u8>> {
405    let lines: Vec<&str> = content.split('\n').collect();
406    let body = match lines.len() {
407        0..=2 => "".to_string(),
408        count => lines[1..count - 1].concat(),
409    };
410    decode_base64(&body)
411}
412
413pub fn key_block(
414    entries: &Entries,
415    keyword: &str,
416    expected_type: &str,
417) -> Result<(String, String)> {
418    let entry = entries.entry(keyword)?;
419    match (&entry.block_contents, &entry.block_type) {
420        (Some(contents), Some(block_type))
421            if block_type == expected_type && !contents.is_empty() =>
422        {
423            Ok((entry.value.clone(), contents.clone()))
424        }
425        _ => Err(Error::parse(format!(
426            "'{keyword}' should be followed by a {expected_type} block, but was a {}",
427            entry.block_type.as_deref().unwrap_or("None")
428        ))),
429    }
430}
431
432pub fn parse_integer(keyword: &str, value: &str, allow_negative: bool) -> Result<i64> {
433    let number: i64 = value.trim().parse().map_err(|_| {
434        Error::parse(format!("{keyword} must have a numeric value: {value}"))
435    })?;
436    match number < 0 && !allow_negative {
437        true => Err(Error::parse(format!(
438            "{keyword} must have a positive value: {value}"
439        ))),
440        false => Ok(number),
441    }
442}
443
444pub fn parse_unsigned(keyword: &str, value: &str) -> Result<u64> {
445    let is_digits = !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit());
446    match is_digits {
447        true => value.parse().map_err(|_| {
448            Error::parse(format!("{keyword} value is out of range: {value}"))
449        }),
450        false => Err(Error::parse(format!(
451            "{keyword} must have a numeric value: {value}"
452        ))),
453    }
454}
455
456pub fn parse_timestamp_line(keyword: &str, value: &str) -> Result<NaiveDateTime> {
457    parse_timestamp(value).map_err(|_| {
458        Error::parse(format!(
459            "Timestamp on {keyword} line wasn't parsable: {keyword} {value}"
460        ))
461    })
462}
463
464pub fn parse_forty_hex(keyword: &str, value: &str) -> Result<String> {
465    match crate::validation::is_hex_digits(value, 40) {
466        true => Ok(value.to_string()),
467        false => Err(Error::parse(format!(
468            "{keyword} line had an invalid value (should be 40 hex characters): \
469            {keyword} {value}"
470        ))),
471    }
472}
473
474pub fn mappings_for(
475    keyword: &str,
476    value: &str,
477    require_value: bool,
478    divider: char,
479) -> Result<Vec<(String, String)>> {
480    if value.is_empty() {
481        return Ok(Vec::new());
482    }
483    value
484        .split(divider)
485        .map(|entry| {
486            let Some((key, mapped)) = entry.split_once('=') else {
487                return Err(Error::parse(format!(
488                    "'{keyword}' should be a series of 'key=value' pairs but was: {value}"
489                )));
490            };
491            match require_value && mapped.is_empty() {
492                true => Err(Error::parse(format!(
493                    "'{keyword}' line's {key} mapping had a blank value: {value}"
494                ))),
495                false => Ok((key.to_string(), mapped.to_string())),
496            }
497        })
498        .collect()
499}
500
501pub type Protocols = IndexMap<String, Vec<u32>>;
502
503pub fn serialize_optional_text<S: serde::Serializer>(
504    bytes: &Option<Vec<u8>>,
505    serializer: S,
506) -> std::result::Result<S::Ok, S::Error> {
507    match bytes {
508        Some(bytes) => serializer.serialize_str(&String::from_utf8_lossy(bytes)),
509        None => serializer.serialize_none(),
510    }
511}
512
513pub fn serialize_text_list<S: serde::Serializer>(
514    lines: &[Vec<u8>],
515    serializer: S,
516) -> std::result::Result<S::Ok, S::Error> {
517    let texts: Vec<String> = lines
518        .iter()
519        .map(|line| String::from_utf8_lossy(line).into_owned())
520        .collect();
521    serde::Serialize::serialize(&texts, serializer)
522}
523
524pub fn serialize_hex<S: serde::Serializer, B: AsRef<[u8]>>(
525    bytes: &B,
526    serializer: S,
527) -> std::result::Result<S::Ok, S::Error> {
528    serializer.serialize_str(&hex::encode(bytes))
529}
530
531pub fn serialize_optional_hex<S: serde::Serializer>(
532    bytes: &Option<Vec<u8>>,
533    serializer: S,
534) -> std::result::Result<S::Ok, S::Error> {
535    match bytes {
536        Some(bytes) => serializer.serialize_str(&hex::encode(bytes)),
537        None => serializer.serialize_none(),
538    }
539}
540
541pub fn parse_protocol_line(keyword: &str, value: &str) -> Result<Protocols> {
542    let mut protocols = Protocols::new();
543    for (name, versions) in mappings_for(keyword, value, false, ' ')? {
544        if versions.is_empty() {
545            continue;
546        }
547        let mut expanded = Vec::new();
548        for entry in versions.split(',') {
549            let (first, last) = entry.split_once('-').unwrap_or((entry, entry));
550            let (Ok(first), Ok(last)) =
551                (parse_protocol_number(first), parse_protocol_number(last))
552            else {
553                return Err(Error::parse(format!(
554                    "Protocol values should be a number or number range, but was: \
555                    {keyword} {value}"
556                )));
557            };
558            if last >= first && last - first >= MAX_PROTOCOL_VERSIONS {
559                return Err(Error::parse(format!(
560                    "Protocol version range is too large: {keyword} {value}"
561                )));
562            }
563            expanded.extend(first..=last);
564        }
565        protocols.insert(name, expanded);
566    }
567    Ok(protocols)
568}
569
570fn parse_protocol_number(entry: &str) -> std::result::Result<u32, ()> {
571    match !entry.is_empty() && entry.bytes().all(|byte| byte.is_ascii_digit()) {
572        true => entry.parse().map_err(|_| ()),
573        false => Err(()),
574    }
575}
576
577pub fn content_range(
578    content: &[u8],
579    start: Option<&str>,
580    end: Option<&str>,
581) -> Result<Vec<u8>> {
582    let find = |needle: &str, from: usize| -> Result<usize> {
583        content[from..]
584            .windows(needle.len())
585            .position(|window| window == needle.as_bytes())
586            .map(|position| position + from)
587            .ok_or_else(|| {
588                Error::parse(format!(
589                    "'{needle}' is not present within our descriptor content"
590                ))
591            })
592    };
593    let start_index = match start {
594        Some(start) => find(start, 0)?,
595        None => 0,
596    };
597    let end_index = match end {
598        Some(end) => find(end, start_index)? + end.len(),
599        None => content.len(),
600    };
601    Ok(content[start_index..end_index].to_vec())
602}
603
604#[derive(Debug, Clone, PartialEq, Eq)]
605pub struct TypeAnnotation {
606    pub name: String,
607    pub major_version: u32,
608    pub minor_version: u32,
609}
610
611impl std::fmt::Display for TypeAnnotation {
612    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
613        write!(
614            formatter,
615            "@type {} {}.{}",
616            self.name, self.major_version, self.minor_version
617        )
618    }
619}
620
621impl TypeAnnotation {
622    pub fn parse(line: &str) -> Option<Self> {
623        let rest = line.trim().strip_prefix("@type ")?;
624        let (name, version) = rest.split_once(' ')?;
625        let (major, minor) = version.split_once('.')?;
626        Some(Self {
627            name: name.to_string(),
628            major_version: major.parse().ok()?,
629            minor_version: minor.parse().ok()?,
630        })
631    }
632}
633
634pub struct LineCursor<'a> {
635    content: &'a [u8],
636    position: usize,
637}
638
639impl<'a> LineCursor<'a> {
640    pub fn new(content: &'a [u8]) -> Self {
641        Self {
642            content,
643            position: 0,
644        }
645    }
646
647    pub fn tell(&self) -> usize {
648        self.position
649    }
650
651    pub fn seek(&mut self, position: usize) {
652        self.position = position.min(self.content.len());
653    }
654
655    pub fn is_finished(&self) -> bool {
656        self.position >= self.content.len()
657    }
658
659    pub fn read_line(&mut self) -> Option<&'a [u8]> {
660        if self.is_finished() {
661            return None;
662        }
663        let rest = &self.content[self.position..];
664        let length = rest
665            .iter()
666            .position(|byte| *byte == b'\n')
667            .map_or(rest.len(), |index| index + 1);
668        self.position += length;
669        Some(&rest[..length])
670    }
671
672    pub fn remaining(&self) -> &'a [u8] {
673        &self.content[self.position..]
674    }
675
676    pub fn read_until_keywords(
677        &mut self,
678        keywords: &[&str],
679        options: ReadOptions,
680    ) -> ReadResult {
681        let mut content: Vec<u8> = Vec::new();
682        let mut ending_keyword = None;
683        if options.ignore_first
684            && let Some(first) = self.read_line()
685        {
686            content.extend_from_slice(first);
687        }
688        loop {
689            let last_position = self.position;
690            if options.end_position.is_some_and(|end| last_position >= end) {
691                break;
692            }
693            let Some(line) = self.read_line() else {
694                break;
695            };
696            let text = String::from_utf8_lossy(line);
697            let trimmed = text.trim_end_matches(['\n', '\r']);
698            let keyword = split_keyword_line(trimmed)
699                .map(|(keyword, _)| keyword)
700                .filter(|keyword| keywords.contains(keyword));
701            if let Some(keyword) = keyword {
702                ending_keyword = Some(keyword.to_string());
703                if options.inclusive {
704                    content.extend_from_slice(line);
705                } else {
706                    self.position = last_position;
707                }
708                break;
709            }
710            content.extend_from_slice(line);
711        }
712        ReadResult {
713            content,
714            ending_keyword,
715        }
716    }
717}
718
719#[derive(Debug, Clone, Copy, Default)]
720pub struct ReadOptions {
721    pub inclusive: bool,
722    pub ignore_first: bool,
723    pub end_position: Option<usize>,
724}
725
726pub struct ReadResult {
727    pub content: Vec<u8>,
728    pub ending_keyword: Option<String>,
729}
730
731pub fn parse_key_value_counts(value: &str) -> HashMap<String, String> {
732    value
733        .split(' ')
734        .filter_map(|entry| entry.split_once('='))
735        .map(|(key, mapped)| (key.to_string(), mapped.to_string()))
736        .collect()
737}
738
739#[derive(Debug, Clone)]
740pub enum AttrValue {
741    Remove,
742    Text(String),
743    Lines(Vec<String>),
744}
745
746pub type Attributes = Vec<(String, AttrValue)>;
747pub type Template<'a> = &'a [(&'a str, AttrValue)];
748
749pub fn attr(keyword: &str, value: &str) -> (String, AttrValue) {
750    (keyword.to_string(), AttrValue::Text(value.to_string()))
751}
752
753fn render_line(keyword: &str, value: &AttrValue, lines: &mut Vec<String>) {
754    match value {
755        AttrValue::Remove => {}
756        AttrValue::Lines(values) => {
757            lines.extend(values.iter().map(|entry| format!("{keyword} {entry}")))
758        }
759        AttrValue::Text(text) if text.is_empty() => lines.push(keyword.to_string()),
760        AttrValue::Text(text) if text.starts_with('\n') => {
761            lines.push(format!("{keyword}{text}"))
762        }
763        AttrValue::Text(text) => lines.push(format!("{keyword} {text}")),
764    }
765}
766
767pub fn descriptor_content(
768    attributes: &Attributes,
769    exclude: &[&str],
770    header: Template<'_>,
771    footer: Template<'_>,
772) -> Vec<u8> {
773    let mut remaining: Attributes = attributes.clone();
774    let mut sections: [Vec<String>; 2] = [Vec::new(), Vec::new()];
775    for (lines, template) in sections.iter_mut().zip([header, footer]) {
776        for (keyword, default) in template {
777            if exclude.contains(keyword) {
778                continue;
779            }
780            let value = match remaining.iter().position(|(name, _)| name == keyword) {
781                Some(index) => remaining.remove(index).1,
782                None => default.clone(),
783            };
784            render_line(keyword, &value, lines);
785        }
786    }
787    let mut extra = Vec::new();
788    for (keyword, value) in &remaining {
789        if let AttrValue::Text(text) = value {
790            extra.push(format!("{keyword} {text}"));
791        } else {
792            render_line(keyword, value, &mut extra);
793        }
794    }
795    let [header_lines, footer_lines] = sections;
796    [header_lines, extra, footer_lines]
797        .concat()
798        .join("\n")
799        .into_bytes()
800}
801
802pub fn random_nickname() -> String {
803    let number: u64 = rand::random::<u64>() % 100_000_000_000_000;
804    format!("Unnamed{number}").chars().take(19).collect()
805}
806
807pub fn random_fingerprint() -> String {
808    hex::encode_upper(rand::random::<[u8; 20]>())
809}
810
811pub fn random_ipv4_address() -> String {
812    let octets: [u8; 4] = rand::random();
813    format!("{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
814}
815
816pub fn random_date() -> String {
817    let random = |low: u32, high: u32| low + rand::random::<u32>() % (high - low + 1);
818    format!(
819        "{}-{:02}-{:02} {:02}:{:02}:{:02}",
820        random(2000, 2015),
821        random(1, 12),
822        random(1, 20),
823        random(0, 23),
824        random(0, 59),
825        random(0, 59)
826    )
827}
828
829pub fn split_into_lines(content: &str, size: usize) -> Vec<String> {
830    crate::formatting::split_by_length(content, size)
831}
832
833pub fn random_crypto_blob(block_type: Option<&str>) -> String {
834    let encoded =
835        base64::engine::general_purpose::STANDARD.encode(rand::random::<[u8; 140]>());
836    let blob = split_into_lines(&encoded, 64).join("\n");
837    match block_type {
838        Some(kind) => format!("\n-----BEGIN {kind}-----\n{blob}\n-----END {kind}-----"),
839        None => blob,
840    }
841}
842
843#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
844pub struct History {
845    pub end: NaiveDateTime,
846    pub interval: u64,
847    pub values: Vec<i64>,
848}
849
850pub fn parse_timestamp_and_interval(
851    keyword: &str,
852    content: &str,
853) -> Result<(NaiveDateTime, u64, String)> {
854    let malformed =
855        || Error::parse(format!("Malformed {keyword} line: {keyword} {content}"));
856    let mut search_end = content.len();
857    let (timestamp, interval, remainder) = loop {
858        let Some(open) = content[..search_end].rfind(" (") else {
859            return Err(malformed());
860        };
861        let rest = &content[open + 2..];
862        let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
863        let after = &rest[digits..];
864        if digits > 0
865            && let Some(tail) = after.strip_prefix(" s)")
866            && (tail.is_empty() || tail.starts_with(' '))
867        {
868            break (
869                &content[..open],
870                &rest[..digits],
871                tail.strip_prefix(' ').unwrap_or(""),
872            );
873        }
874        search_end = open;
875    };
876    let interval = interval.parse::<u64>().map_err(|_| {
877        Error::parse(format!(
878            "{keyword} line's interval wasn't a number: {keyword} {content}"
879        ))
880    })?;
881    let timestamp = parse_timestamp(timestamp).map_err(|_| {
882        Error::parse(format!(
883            "{keyword} line's timestamp wasn't parsable: {keyword} {content}"
884        ))
885    })?;
886    Ok((timestamp, interval, remainder.to_string()))
887}
888
889pub fn parse_history(keyword: &str, value: &str) -> Result<History> {
890    let (end, interval, remainder) = parse_timestamp_and_interval(keyword, value)?;
891    let values = match remainder.is_empty() {
892        true => Vec::new(),
893        false => remainder
894            .split(',')
895            .map(|entry| entry.parse::<i64>())
896            .collect::<std::result::Result<Vec<_>, _>>()
897            .map_err(|_| {
898                Error::parse(format!(
899                    "{keyword} line has non-numeric values: {keyword} {value}"
900                ))
901            })?,
902    };
903    Ok(History {
904        end,
905        interval,
906        values,
907    })
908}
909
910pub fn parse_bytes_line(raw: &[u8], keyword: &str) -> Option<Vec<u8>> {
911    raw.split(|byte| *byte == b'\n').find_map(|line| {
912        let line = line.strip_prefix(b"opt ").unwrap_or(line);
913        let rest = line.strip_prefix(keyword.as_bytes())?;
914        match rest.first() {
915            None => Some(Vec::new()),
916            Some(b' ' | b'\t') => Some(rest.trim_ascii_start().to_vec()),
917            _ => None,
918        }
919    })
920}
921
922pub use parsing::{Descriptor, DocumentHandler, ParsedFile, parse_bytes, parse_path};