1use indexmap::IndexMap;
2
3use crate::descriptor::router_status::{OrAddress, parse_a_lines};
4use crate::descriptor::{
5 AttrValue, Attributes, DigestEncoding, DigestHash, LineCursor, Protocols,
6 ReadOptions, descriptor_components, descriptor_content, encode_digest, hash_bytes,
7 key_block, lenient, lenient_option, parse_protocol_line, random_crypto_blob,
8};
9use crate::error::{Error, Result};
10use crate::exit_policy::MicroExitPolicy;
11
12const REQUIRED_FIELDS: [&str; 1] = ["onion-key"];
13const SINGLE_FIELDS: [&str; 6] =
14 ["onion-key", "ntor-onion-key", "family", "p", "p6", "pr"];
15const RECOGNIZED_KEYWORDS: [&str; 8] = [
16 "onion-key",
17 "ntor-onion-key",
18 "a",
19 "family",
20 "p",
21 "p6",
22 "pr",
23 "id",
24];
25
26#[derive(Debug, Clone, PartialEq, serde::Serialize)]
27pub struct Microdescriptor {
28 #[serde(skip)]
29 pub raw_contents: Vec<u8>,
30 pub unrecognized_lines: Vec<String>,
31 #[serde(serialize_with = "crate::descriptor::serialize_text_list")]
32 pub annotation_lines: Vec<Vec<u8>>,
33 pub onion_key: Option<String>,
34 pub ntor_onion_key: Option<String>,
35 pub or_addresses: Vec<OrAddress>,
36 pub family: Vec<String>,
37 pub exit_policy: MicroExitPolicy,
38 pub exit_policy_v6: Option<MicroExitPolicy>,
39 pub identifier_type: Option<String>,
40 pub identifier: Option<String>,
41 pub identifiers: IndexMap<String, String>,
42 pub protocols: Protocols,
43}
44
45fn parse_id_lines(
46 entries: &crate::descriptor::Entries,
47) -> Result<IndexMap<String, String>> {
48 let mut identities = IndexMap::new();
49 for entry in entries.values("id") {
50 let parts: Vec<&str> = entry.split_whitespace().collect();
51 let [key_type, key_value, ..] = parts.as_slice() else {
52 return Err(Error::parse(format!(
53 "'id' lines should contain both the key type and digest: id {entry}"
54 )));
55 };
56 if identities
57 .insert(key_type.to_string(), key_value.to_string())
58 .is_some()
59 {
60 return Err(Error::parse(format!(
61 "There can only be one 'id' line per a key type, but '{key_type}' \
62 appeared multiple times"
63 )));
64 }
65 }
66 Ok(identities)
67}
68
69impl Microdescriptor {
70 pub fn parse(content: &[u8], validate: bool) -> Result<Self> {
71 Self::parse_with_annotations(content, validate, Vec::new())
72 }
73
74 pub fn parse_with_annotations(
75 content: &[u8],
76 validate: bool,
77 annotation_lines: Vec<Vec<u8>>,
78 ) -> Result<Self> {
79 let (entries, _) = descriptor_components(content, validate, &[], &[])?;
80 if validate {
81 for keyword in REQUIRED_FIELDS {
82 if !entries.contains(keyword) {
83 return Err(Error::parse(format!(
84 "Microdescriptor must have a '{keyword}' entry"
85 )));
86 }
87 }
88 for keyword in SINGLE_FIELDS {
89 if entries.get(keyword).is_some_and(|values| values.len() > 1) {
90 return Err(Error::parse(format!(
91 "The '{keyword}' entry can only appear once in a microdescriptor"
92 )));
93 }
94 }
95 if entries.first_key() != Some("onion-key") {
96 return Err(Error::parse(
97 "Microdescriptor must start with a 'onion-key' entry",
98 ));
99 }
100 }
101 let mut descriptor = Self {
102 raw_contents: content.to_vec(),
103 unrecognized_lines: entries.unrecognized_lines(&RECOGNIZED_KEYWORDS),
104 annotation_lines,
105 onion_key: None,
106 ntor_onion_key: None,
107 or_addresses: Vec::new(),
108 family: Vec::new(),
109 exit_policy: MicroExitPolicy::new("reject 1-65535").expect("default policy"),
110 exit_policy_v6: None,
111 identifier_type: None,
112 identifier: None,
113 identifiers: IndexMap::new(),
114 protocols: Protocols::new(),
115 };
116 if entries.contains("onion-key") {
117 descriptor.onion_key = lenient_option(
118 validate,
119 key_block(&entries, "onion-key", "RSA PUBLIC KEY")
120 .map(|(_, block)| block),
121 )?;
122 }
123 if let Ok(value) = entries.value("ntor-onion-key") {
124 descriptor.ntor_onion_key = Some(value.to_string());
125 }
126 if entries.contains("a") {
127 descriptor.or_addresses =
128 lenient(validate, parse_a_lines("microdescriptor", &entries))?;
129 }
130 if let Ok(value) = entries.value("family") {
131 descriptor.family = value.split(' ').map(str::to_string).collect();
132 }
133 if let Ok(value) = entries.value("p") {
134 let parsed = lenient_option(
135 validate,
136 MicroExitPolicy::new(value).map_err(|error| {
137 Error::parse(format!(
138 "microdescriptor exit policy is malformed ({error}): p {value}"
139 ))
140 }),
141 )?;
142 if let Some(policy) = parsed {
143 descriptor.exit_policy = policy;
144 }
145 }
146 if let Ok(value) = entries.value("p6") {
147 descriptor.exit_policy_v6 =
148 lenient_option(validate, MicroExitPolicy::new(value))?;
149 }
150 if entries.contains("id") {
151 descriptor.identifiers = lenient(validate, parse_id_lines(&entries))?;
152 if let Some((kind, value)) = descriptor.identifiers.last() {
153 descriptor.identifier_type = Some(kind.clone());
154 descriptor.identifier = Some(value.clone());
155 }
156 }
157 if let Ok(value) = entries.value("pr") {
158 descriptor.protocols = lenient(validate, parse_protocol_line("pr", value))?;
159 }
160 Ok(descriptor)
161 }
162
163 pub fn parse_many(content: &[u8], validate: bool) -> Result<Vec<Self>> {
164 let mut cursor = LineCursor::new(content);
165 let mut descriptors = Vec::new();
166 loop {
167 let annotations =
168 cursor.read_until_keywords(&["onion-key"], ReadOptions::default());
169 let Some(onion_key_line) = cursor.read_line() else {
170 break;
171 };
172 let mut lines: Vec<u8> = onion_key_line.to_vec();
173 loop {
174 let position = cursor.tell();
175 let Some(line) = cursor.read_line() else {
176 break;
177 };
178 if line.starts_with(b"@") || line.starts_with(b"onion-key") {
179 cursor.seek(position);
180 break;
181 }
182 lines.extend_from_slice(line);
183 }
184 let annotation_lines: Vec<Vec<u8>> = annotations
185 .content
186 .split(|byte| *byte == b'\n')
187 .map(|line| line.trim_ascii().to_vec())
188 .filter(|line| !line.is_empty())
189 .collect();
190 descriptors.push(Self::parse_with_annotations(
191 &lines,
192 validate,
193 annotation_lines,
194 )?);
195 }
196 Ok(descriptors)
197 }
198
199 pub fn digest(&self, hash: DigestHash, encoding: DigestEncoding) -> String {
200 encode_digest(&hash_bytes(hash, &self.raw_contents), encoding)
201 }
202
203 pub fn annotations(&self) -> IndexMap<Vec<u8>, Option<Vec<u8>>> {
204 self.annotation_lines
205 .iter()
206 .map(|line| match line.iter().position(|byte| *byte == b' ') {
207 Some(split) => (line[..split].to_vec(), Some(line[split + 1..].to_vec())),
208 None => (line.clone(), None),
209 })
210 .collect()
211 }
212
213 pub fn content(attributes: &Attributes, exclude: &[&str]) -> Vec<u8> {
214 descriptor_content(
215 attributes,
216 exclude,
217 &[(
218 "onion-key",
219 AttrValue::Text(random_crypto_blob(Some("RSA PUBLIC KEY"))),
220 )],
221 &[],
222 )
223 }
224
225 pub fn create(
226 attributes: &Attributes,
227 exclude: &[&str],
228 validate: bool,
229 ) -> Result<Self> {
230 Self::parse(&Self::content(attributes, exclude), validate)
231 }
232}