1use std::io::Read;
2use std::path::{Path, PathBuf};
3
4use crate::descriptor::bandwidth_file::BandwidthFile;
5use crate::descriptor::extrainfo::{BridgeExtraInfoDescriptor, RelayExtraInfoDescriptor};
6use crate::descriptor::hidden_service::{
7 HiddenServiceDescriptorV2, HiddenServiceDescriptorV3,
8};
9use crate::descriptor::microdescriptor::Microdescriptor;
10use crate::descriptor::network_status::{
11 BridgeNetworkStatusDocument, DetachedSignature, KeyCertificate,
12 NetworkStatusDocumentV2, NetworkStatusDocumentV3, RouterEntry,
13};
14use crate::descriptor::router_status::RouterStatusEntryV2;
15use crate::descriptor::server::{BridgeServerDescriptor, RelayServerDescriptor};
16use crate::descriptor::tordnsel::TorDnsel;
17use crate::descriptor::{Compression, TypeAnnotation};
18use crate::error::{Error, Result};
19use crate::process_inspection::is_tarfile;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum DocumentHandler {
23 Entries,
24 Document,
25 BareDocument,
26}
27
28#[derive(Debug, Clone, PartialEq, serde::Serialize)]
29#[serde(untagged)]
30pub enum Descriptor {
31 RelayServer(Box<RelayServerDescriptor>),
32 BridgeServer(Box<BridgeServerDescriptor>),
33 RelayExtraInfo(Box<RelayExtraInfoDescriptor>),
34 BridgeExtraInfo(Box<BridgeExtraInfoDescriptor>),
35 Microdescriptor(Box<Microdescriptor>),
36 RouterStatusEntryV2(Box<RouterStatusEntryV2>),
37 RouterEntry(Box<RouterEntry>),
38 NetworkStatusV2(Box<NetworkStatusDocumentV2>),
39 NetworkStatusV3(Box<NetworkStatusDocumentV3>),
40 BridgeNetworkStatus(Box<BridgeNetworkStatusDocument>),
41 KeyCertificate(Box<KeyCertificate>),
42 DetachedSignature(Box<DetachedSignature>),
43 TorDnsel(Box<TorDnsel>),
44 HiddenServiceV2(Box<HiddenServiceDescriptorV2>),
45 HiddenServiceV3(Box<HiddenServiceDescriptorV3>),
46 BandwidthFile(Box<BandwidthFile>),
47}
48
49impl Descriptor {
50 pub fn type_annotation(&self) -> TypeAnnotation {
51 let name = match self {
52 Self::RelayServer(_) => "server-descriptor",
53 Self::BridgeServer(_) => "bridge-server-descriptor",
54 Self::RelayExtraInfo(_) => "extra-info",
55 Self::BridgeExtraInfo(_) => "bridge-extra-info",
56 Self::Microdescriptor(_) => "microdescriptor",
57 Self::RouterStatusEntryV2(_) => "network-status-consensus-2",
58 Self::RouterEntry(entry) => match **entry {
59 RouterEntry::Full(_) => "network-status-consensus-3",
60 RouterEntry::Micro(_) => "network-status-microdesc-consensus-3",
61 },
62 Self::NetworkStatusV2(_) => "network-status-2",
63 Self::NetworkStatusV3(document) => {
64 match (document.is_microdescriptor, document.is_vote) {
65 (true, _) => "network-status-microdesc-consensus-3",
66 (false, true) => "network-status-vote-3",
67 (false, false) => "network-status-consensus-3",
68 }
69 }
70 Self::BridgeNetworkStatus(_) => "bridge-network-status",
71 Self::KeyCertificate(_) => "dir-key-certificate-3",
72 Self::DetachedSignature(_) => "detached-signature-3",
73 Self::TorDnsel(_) => "tordnsel",
74 Self::HiddenServiceV2(_) => "hidden-service-descriptor",
75 Self::HiddenServiceV3(_) => "hidden-service-descriptor-3",
76 Self::BandwidthFile(_) => "bandwidth-file",
77 };
78 TypeAnnotation {
79 name: name.to_string(),
80 major_version: 1,
81 minor_version: 0,
82 }
83 }
84
85 pub fn published(&self) -> Option<chrono::NaiveDateTime> {
86 match self {
87 Self::RelayServer(descriptor) => descriptor.published,
88 Self::BridgeServer(descriptor) => descriptor.published,
89 Self::RelayExtraInfo(descriptor) => descriptor.published,
90 Self::BridgeExtraInfo(descriptor) => descriptor.published,
91 Self::RouterEntry(entry) => entry.common().published,
92 Self::RouterStatusEntryV2(entry) => entry.published,
93 Self::NetworkStatusV2(document) => document.published,
94 Self::NetworkStatusV3(document) => document.published,
95 Self::BridgeNetworkStatus(document) => document.published,
96 Self::HiddenServiceV2(descriptor) => descriptor.published,
97 Self::TorDnsel(descriptor) => descriptor.published,
98 Self::KeyCertificate(certificate) => certificate.published,
99 _ => None,
100 }
101 }
102}
103
104#[derive(Debug, Clone, PartialEq)]
105pub struct ParsedFile {
106 pub descriptor: Descriptor,
107 pub path: Option<PathBuf>,
108 pub archive_path: Option<String>,
109}
110
111fn parse_type(descriptor_type: &str) -> Result<(String, u32, u32)> {
112 let invalid = || {
113 Error::invalid_input(
114 "The descriptor_type must be of the form '<type> \
115 <major_version>.<minor_version>'",
116 )
117 };
118 let (name, version) = descriptor_type.split_once(' ').ok_or_else(invalid)?;
119 let (major, minor) = version.split_once('.').ok_or_else(invalid)?;
120 Ok((
121 name.to_string(),
122 major.parse().map_err(|_| invalid())?,
123 minor.parse().map_err(|_| invalid())?,
124 ))
125}
126
127fn boxed<T, U>(items: Vec<T>, wrap: impl Fn(Box<T>) -> U) -> Vec<U> {
128 items.into_iter().map(|item| wrap(Box::new(item))).collect()
129}
130
131fn parse_metrics(
132 name: &str,
133 major: u32,
134 minor: u32,
135 content: &[u8],
136 validate: bool,
137 handler: DocumentHandler,
138) -> Result<Vec<Descriptor>> {
139 if major != 1 {
140 return Err(Error::invalid_input(format!(
141 "Unrecognized metrics descriptor format. type: '{name}', version: \
142 '{major}.{minor}'"
143 )));
144 }
145 Ok(match name {
146 "server-descriptor" => boxed(
147 RelayServerDescriptor::parse_many(content, validate)?,
148 Descriptor::RelayServer,
149 ),
150 "bridge-server-descriptor" => boxed(
151 BridgeServerDescriptor::parse_many(content, validate)?,
152 Descriptor::BridgeServer,
153 ),
154 "extra-info" => boxed(
155 RelayExtraInfoDescriptor::parse_many(content, validate)?,
156 Descriptor::RelayExtraInfo,
157 ),
158 "bridge-extra-info" => boxed(
159 BridgeExtraInfoDescriptor::parse_many(content, validate)?,
160 Descriptor::BridgeExtraInfo,
161 ),
162 "microdescriptor" => boxed(
163 Microdescriptor::parse_many(content, validate)?,
164 Descriptor::Microdescriptor,
165 ),
166 "network-status-2" => match handler {
167 DocumentHandler::Entries => {
168 let document = NetworkStatusDocumentV2::parse(content, validate)?;
169 document
170 .routers
171 .into_values()
172 .map(|entry| Descriptor::RouterStatusEntryV2(Box::new(entry)))
173 .collect()
174 }
175 _ => vec![Descriptor::NetworkStatusV2(Box::new(
176 NetworkStatusDocumentV2::parse(content, validate)?,
177 ))],
178 },
179 "dir-key-certificate-3" => boxed(
180 KeyCertificate::parse_many(content, validate)?,
181 Descriptor::KeyCertificate,
182 ),
183 "network-status-consensus-3" | "network-status-vote-3" => {
184 parse_v3_documents(content, validate, handler, false)?
185 }
186 "network-status-microdesc-consensus-3" => {
187 parse_v3_documents(content, validate, handler, true)?
188 }
189 "bridge-network-status" => match handler {
190 DocumentHandler::Entries => {
191 BridgeNetworkStatusDocument::parse(content, validate)?
192 .routers
193 .into_values()
194 .map(|entry| Descriptor::RouterStatusEntryV2(Box::new(entry)))
195 .collect()
196 }
197 _ => vec![Descriptor::BridgeNetworkStatus(Box::new(
198 BridgeNetworkStatusDocument::parse(content, validate)?,
199 ))],
200 },
201 "detached-signature-3" => vec![Descriptor::DetachedSignature(Box::new(
202 DetachedSignature::parse(content, validate)?,
203 ))],
204 "tordnsel" => boxed(
205 TorDnsel::parse_many(content, validate)?,
206 Descriptor::TorDnsel,
207 ),
208 "hidden-service-descriptor" => boxed(
209 HiddenServiceDescriptorV2::parse_many(content, validate)?,
210 Descriptor::HiddenServiceV2,
211 ),
212 "hidden-service-descriptor-3" => boxed(
213 HiddenServiceDescriptorV3::parse_many(content, validate)?,
214 Descriptor::HiddenServiceV3,
215 ),
216 "bandwidth-file" => vec![Descriptor::BandwidthFile(Box::new(
217 BandwidthFile::parse(content, validate)?,
218 ))],
219 other => {
220 return Err(Error::invalid_input(format!(
221 "Unrecognized metrics descriptor format. type: '{other}', version: \
222 '{major}.{minor}'"
223 )));
224 }
225 })
226}
227
228fn parse_v3_documents(
229 content: &[u8],
230 validate: bool,
231 handler: DocumentHandler,
232 is_microdescriptor: bool,
233) -> Result<Vec<Descriptor>> {
234 match handler {
235 DocumentHandler::Document => {
236 let document = NetworkStatusDocumentV3::parse(content, validate)?;
237 Ok(vec![Descriptor::NetworkStatusV3(Box::new(document))])
238 }
239 DocumentHandler::BareDocument => {
240 let split = bare_document_content(content);
241 let document = NetworkStatusDocumentV3::parse(&split, validate)?;
242 Ok(vec![Descriptor::NetworkStatusV3(Box::new(document))])
243 }
244 DocumentHandler::Entries => Ok(NetworkStatusDocumentV3::parse_routers(
245 content,
246 validate,
247 is_microdescriptor,
248 )?
249 .into_iter()
250 .map(|entry| Descriptor::RouterEntry(Box::new(entry)))
251 .collect()),
252 }
253}
254
255fn bare_document_content(content: &[u8]) -> Vec<u8> {
256 let mut cursor = crate::descriptor::LineCursor::new(content);
257 let mut header = cursor
258 .read_until_keywords(
259 &["r", "directory-footer", "directory-signature"],
260 Default::default(),
261 )
262 .content;
263 if header.starts_with(b"@type") {
264 header = header
265 .splitn(2, |byte| *byte == b'\n')
266 .nth(1)
267 .unwrap_or_default()
268 .to_vec();
269 }
270 cursor.read_until_keywords(
271 &["directory-footer", "directory-signature"],
272 Default::default(),
273 );
274 [header.as_slice(), cursor.remaining()].concat()
275}
276
277pub fn parse_bytes(
278 content: &[u8],
279 descriptor_type: Option<&str>,
280 validate: bool,
281 handler: DocumentHandler,
282 file_name: Option<&str>,
283) -> Result<Vec<Descriptor>> {
284 let first_end = content
285 .iter()
286 .position(|byte| *byte == b'\n')
287 .map_or(content.len(), |index| index + 1);
288 let first_line = String::from_utf8_lossy(&content[..first_end])
289 .trim()
290 .to_string();
291 let annotation = TypeAnnotation::parse(&first_line);
292 let body = match annotation {
293 Some(_) => &content[first_end..],
294 None => content,
295 };
296 if let Some(descriptor_type) = descriptor_type {
297 let (name, major, minor) = parse_type(descriptor_type)?;
298 return parse_metrics(&name, major, minor, body, validate, handler);
299 }
300 if let Some(annotation) = annotation {
301 return parse_metrics(
302 &annotation.name,
303 annotation.major_version,
304 annotation.minor_version,
305 body,
306 validate,
307 handler,
308 );
309 }
310 let name = file_name.unwrap_or("<undefined>");
311 match name {
312 "cached-descriptors" | "cached-descriptors.new" => Ok(boxed(
313 RelayServerDescriptor::parse_many(content, validate)?,
314 Descriptor::RelayServer,
315 )),
316 "cached-extrainfo" | "cached-extrainfo.new" => Ok(boxed(
317 RelayExtraInfoDescriptor::parse_many(content, validate)?,
318 Descriptor::RelayExtraInfo,
319 )),
320 "cached-microdescs" | "cached-microdescs.new" => Ok(boxed(
321 Microdescriptor::parse_many(content, validate)?,
322 Descriptor::Microdescriptor,
323 )),
324 "cached-consensus" => parse_v3_documents(content, validate, handler, false),
325 "cached-microdesc-consensus" => {
326 parse_v3_documents(content, validate, handler, true)
327 }
328 _ => Err(Error::invalid_input(format!(
329 "Unable to determine the descriptor's type. filename: '{name}', first line: \
330 '{first_line}'"
331 ))),
332 }
333}
334
335fn decompress_archive(content: Vec<u8>) -> Result<Vec<u8>> {
336 let compression = match content.as_slice() {
337 [0x1f, 0x8b, ..] => Compression::Gzip,
338 [b'B', b'Z', b'h', ..] => Compression::Bzip2,
339 [0xfd, b'7', b'z', b'X', b'Z', 0x00, ..] => Compression::Lzma,
340 [0x28, 0xb5, 0x2f, 0xfd, ..] => Compression::Zstd,
341 _ => return Ok(content),
342 };
343 compression.decompress(&content)
344}
345
346pub fn parse_path(
347 path: &Path,
348 descriptor_type: Option<&str>,
349 validate: bool,
350 handler: DocumentHandler,
351) -> Result<Vec<ParsedFile>> {
352 let raw = std::fs::read(path)?;
353 parse_compressed(raw, Some(path), descriptor_type, validate, handler)
354}
355
356pub fn parse_compressed(
357 raw: Vec<u8>,
358 path: Option<&Path>,
359 descriptor_type: Option<&str>,
360 validate: bool,
361 handler: DocumentHandler,
362) -> Result<Vec<ParsedFile>> {
363 let content = decompress_archive(raw)?;
364 let absolute = path
365 .map(|path| std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()));
366 let is_archive = is_tarfile_bytes(&content) || path.is_some_and(is_tarfile);
367 if !is_archive {
368 let file_name = path
369 .and_then(|path| path.file_name())
370 .and_then(|name| name.to_str());
371 return Ok(
372 parse_bytes(&content, descriptor_type, validate, handler, file_name)?
373 .into_iter()
374 .map(|descriptor| ParsedFile {
375 descriptor,
376 path: absolute.clone(),
377 archive_path: None,
378 })
379 .collect(),
380 );
381 }
382 let mut results = Vec::new();
383 let mut archive = tar::Archive::new(content.as_slice());
384 for entry in archive.entries()? {
385 let mut entry = entry?;
386 if !entry.header().entry_type().is_file() || entry.size() == 0 {
387 continue;
388 }
389 let archive_path = entry.path()?.to_string_lossy().into_owned();
390 let mut body = Vec::new();
391 entry
392 .by_ref()
393 .take(crate::descriptor::MAX_DECOMPRESSED_LENGTH)
394 .read_to_end(&mut body)?;
395 let name = archive_path.rsplit('/').next();
396 for descriptor in parse_bytes(&body, descriptor_type, validate, handler, name)? {
397 results.push(ParsedFile {
398 descriptor,
399 path: absolute.clone(),
400 archive_path: Some(archive_path.clone()),
401 });
402 }
403 }
404 Ok(results)
405}
406
407fn is_tarfile_bytes(content: &[u8]) -> bool {
408 content.len() >= 512 && &content[257..262] == b"ustar"
409}