1use std::path::{Path, PathBuf};
2use std::sync::{LazyLock, Mutex};
3use std::time::{Duration, Instant};
4
5use base64::Engine;
6use chrono::{Datelike, NaiveDate, NaiveDateTime, TimeDelta};
7use regex::Regex;
8use serde::Deserialize;
9use sha2::{Digest, Sha256};
10use subtle::ConstantTimeEq;
11
12use crate::descriptor::Compression;
13use crate::descriptor::parsing::{Descriptor, DocumentHandler, parse_compressed};
14use crate::download::download;
15use crate::error::{Error, Result};
16
17pub const COLLECTOR_URL: &str = "https://collector.torproject.org/";
18pub const REFRESH_INDEX_RATE: Duration = Duration::from_secs(3600);
19
20const INDEX_TIMESTAMP_FORMAT: &str = "%Y-%m-%d %H:%M";
21const PATH_TIMESTAMP_FORMAT: &str = "%Y-%m-%d-%H-%M-%S";
22
23static YEAR_DATE: LazyLock<Regex> =
24 LazyLock::new(|| Regex::new(r"-(\d{4})-(\d{2})\.").expect("valid pattern"));
25static SECOND_DATE: LazyLock<Regex> = LazyLock::new(|| {
26 Regex::new(r"(\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2})").expect("valid pattern")
27});
28static SHARED_COLLECTOR: LazyLock<CollecTor> = LazyLock::new(CollecTor::new);
29
30#[derive(Debug, Deserialize)]
31struct IndexDirectory {
32 path: Option<String>,
33 #[serde(default)]
34 directories: Vec<IndexDirectory>,
35 #[serde(default)]
36 files: Vec<IndexFile>,
37}
38
39#[derive(Debug, Deserialize)]
40struct IndexFile {
41 path: String,
42 #[serde(default)]
43 types: Vec<String>,
44 size: Option<u64>,
45 sha256: Option<String>,
46 first_published: Option<String>,
47 last_published: Option<String>,
48 last_modified: String,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct CollectorFile {
53 pub path: String,
54 pub types: Vec<String>,
55 pub compression: Compression,
56 pub size: Option<u64>,
57 pub sha256: Option<String>,
58 pub last_modified: NaiveDateTime,
59 pub start: Option<NaiveDateTime>,
60 pub end: Option<NaiveDateTime>,
61}
62
63#[derive(Debug, Clone)]
64pub struct CollectorRequest {
65 pub start: Option<NaiveDateTime>,
66 pub end: Option<NaiveDateTime>,
67 pub cache_to: Option<PathBuf>,
68 pub timeout: Option<Duration>,
69 pub retries: u32,
70 pub document_handler: DocumentHandler,
71 pub validate: bool,
72}
73
74impl Default for CollectorRequest {
75 fn default() -> Self {
76 Self {
77 start: None,
78 end: None,
79 cache_to: None,
80 timeout: None,
81 retries: 3,
82 document_handler: DocumentHandler::Entries,
83 validate: false,
84 }
85 }
86}
87
88fn validate_path(path: &str) -> Result<()> {
89 let invalid =
90 || Error::parse(format!("Unsafe path in the CollecTor index: {path:?}"));
91 let allowed = |character: char| {
92 character.is_ascii_alphanumeric() || "-_.+:".contains(character)
93 };
94 for segment in path.split('/') {
95 if segment.is_empty() || segment == "." || segment == ".." {
96 return Err(invalid());
97 }
98 if !segment.chars().all(allowed) {
99 return Err(invalid());
100 }
101 }
102 Ok(())
103}
104
105fn parse_index_timestamp(value: &str) -> Result<NaiveDateTime> {
106 NaiveDateTime::parse_from_str(value, INDEX_TIMESTAMP_FORMAT)
107 .map_err(|_| Error::parse(format!("Invalid CollecTor timestamp: {value:?}")))
108}
109
110fn guess_compression(path: &str) -> Compression {
111 [Compression::Lzma, Compression::Bzip2, Compression::Gzip]
112 .into_iter()
113 .find(|compression| path.ends_with(compression.extension()))
114 .unwrap_or(Compression::Plaintext)
115}
116
117fn guess_time_range(path: &str) -> (Option<NaiveDateTime>, Option<NaiveDateTime>) {
118 if let Some(captures) = YEAR_DATE.captures(path) {
119 let year = captures[1].parse().ok();
120 let month = captures[2].parse().ok();
121 let start = year
122 .zip(month)
123 .and_then(|(year, month)| NaiveDate::from_ymd_opt(year, month, 1));
124 let Some(start) = start else {
125 return (None, None);
126 };
127 let next = match start.month() {
128 12 => NaiveDate::from_ymd_opt(start.year() + 1, 1, 1),
129 month => NaiveDate::from_ymd_opt(start.year(), month + 1, 1),
130 };
131 let midnight = |date: NaiveDate| date.and_hms_opt(0, 0, 0);
132 return (midnight(start), next.and_then(midnight));
133 }
134 let start = SECOND_DATE.captures(path).and_then(|captures| {
135 NaiveDateTime::parse_from_str(&captures[1], PATH_TIMESTAMP_FORMAT).ok()
136 });
137 match start {
138 Some(start) => (Some(start), Some(start + TimeDelta::seconds(3600))),
139 None => (None, None),
140 }
141}
142
143fn hash_matches(expected_base64: &str, content: &[u8]) -> bool {
144 let Ok(expected) = base64::engine::general_purpose::STANDARD.decode(expected_base64)
145 else {
146 return false;
147 };
148 let actual = Sha256::digest(content);
149 expected.as_slice().ct_eq(actual.as_slice()).into()
150}
151
152impl CollectorFile {
153 fn from_index(path: String, entry: IndexFile) -> Result<Self> {
154 validate_path(&path)?;
155 let last_modified = parse_index_timestamp(&entry.last_modified)?;
156 let (start, end) = match (&entry.first_published, &entry.last_published) {
157 (Some(first), Some(last)) if !first.is_empty() && !last.is_empty() => (
158 Some(parse_index_timestamp(first)?),
159 Some(parse_index_timestamp(last)?),
160 ),
161 _ => guess_time_range(&path),
162 };
163 Ok(Self {
164 compression: guess_compression(&path),
165 path,
166 types: entry
167 .types
168 .into_iter()
169 .map(|kind| match kind.strip_prefix("@type ") {
170 Some(bare) => bare.to_string(),
171 None => kind,
172 })
173 .collect(),
174 size: entry.size,
175 sha256: entry.sha256,
176 last_modified,
177 start,
178 end,
179 })
180 }
181
182 pub fn file_name(&self) -> &str {
183 self.path.rsplit('/').next().unwrap_or(&self.path)
184 }
185
186 fn descriptor_type(&self, requested: Option<&str>) -> Result<String> {
187 if let Some(requested) = requested {
188 return Ok(requested.to_string());
189 }
190 let mut base_types: Vec<&str> = self
191 .types
192 .iter()
193 .filter_map(|descriptor_type| descriptor_type.split(' ').next())
194 .collect();
195 base_types.dedup();
196 match (self.types.first(), base_types.len()) {
197 (None, _) => Err(Error::invalid_input(
198 "Unable to determine this file's descriptor type",
199 )),
200 (Some(first), 1) => Ok(first.clone()),
201 _ => Err(Error::invalid_input(format!(
202 "Unable to disambiguate file's descriptor type from among {}",
203 self.types.join(", ")
204 ))),
205 }
206 }
207
208 pub async fn fetch(
209 &self,
210 base_url: &str,
211 timeout: Option<Duration>,
212 retries: u32,
213 ) -> Result<Vec<u8>> {
214 let content =
215 download(&format!("{base_url}{}", self.path), timeout, retries).await?;
216 let Some(expected) = &self.sha256 else {
217 return Err(Error::DownloadFailed {
218 url: self.path.clone(),
219 message: "the CollecTor index provides no checksum".to_string(),
220 });
221 };
222 match hash_matches(expected, &content) {
223 true => Ok(content),
224 false => Err(Error::DownloadFailed {
225 url: self.path.clone(),
226 message: "content mismatches the checksum in the CollecTor index"
227 .to_string(),
228 }),
229 }
230 }
231
232 pub async fn download_to(
233 &self,
234 base_url: &str,
235 directory: &Path,
236 timeout: Option<Duration>,
237 retries: u32,
238 overwrite: bool,
239 ) -> Result<PathBuf> {
240 let path = directory.join(self.file_name());
241 std::fs::create_dir_all(directory)?;
242 if let Some(prior) = read_regular_file(&path)? {
243 let matches = self
244 .sha256
245 .as_deref()
246 .is_some_and(|expected| hash_matches(expected, &prior));
247 if matches {
248 return Ok(path);
249 }
250 if !overwrite {
251 return Err(Error::Io(std::io::Error::new(
252 std::io::ErrorKind::AlreadyExists,
253 format!(
254 "{} already exists but mismatches CollecTor's checksum",
255 path.display()
256 ),
257 )));
258 }
259 }
260 let content = self.fetch(base_url, timeout, retries).await?;
261 std::fs::write(&path, content)?;
262 Ok(path)
263 }
264
265 pub async fn read(
266 &self,
267 base_url: &str,
268 descriptor_type: Option<&str>,
269 request: &CollectorRequest,
270 ) -> Result<Vec<Descriptor>> {
271 let descriptor_type = self.descriptor_type(descriptor_type)?;
272 let raw = match &request.cache_to {
273 Some(directory) => {
274 let path = self
275 .download_to(
276 base_url,
277 directory,
278 request.timeout,
279 request.retries,
280 false,
281 )
282 .await?;
283 std::fs::read(path)?
284 }
285 None => {
286 self.fetch(base_url, request.timeout, request.retries)
287 .await?
288 }
289 };
290 let parsed = parse_compressed(
291 raw,
292 None,
293 None,
294 request.validate,
295 request.document_handler,
296 )?;
297 Ok(parsed
298 .into_iter()
299 .map(|file| file.descriptor)
300 .filter(|descriptor| {
301 descriptor_type.starts_with(&descriptor.type_annotation().name)
302 })
303 .filter(|descriptor| in_range(descriptor, request))
304 .collect())
305 }
306}
307
308fn read_regular_file(path: &Path) -> Result<Option<Vec<u8>>> {
309 match std::fs::symlink_metadata(path) {
310 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
311 Err(error) => Err(error.into()),
312 Ok(metadata) if !metadata.is_file() => Err(Error::invalid_input(format!(
313 "{} exists but is not a regular file",
314 path.display()
315 ))),
316 Ok(_) => Ok(Some(std::fs::read(path)?)),
317 }
318}
319
320fn in_range(descriptor: &Descriptor, request: &CollectorRequest) -> bool {
321 let Some(published) = descriptor.published() else {
322 return true;
323 };
324 let before_start = request.start.is_some_and(|start| published < start);
325 let after_end = request.end.is_some_and(|end| published > end);
326 !before_start && !after_end
327}
328
329fn flatten_index(
330 directory: IndexDirectory,
331 path: &[String],
332) -> Result<Vec<CollectorFile>> {
333 let mut files = Vec::new();
334 for entry in directory.files {
335 let full_path = [path, std::slice::from_ref(&entry.path)].concat().join("/");
336 files.push(CollectorFile::from_index(full_path, entry)?);
337 }
338 for child in directory.directories {
339 let Some(name) = child.path.clone() else {
340 continue;
341 };
342 let child_path = [path, &[name]].concat();
343 files.extend(flatten_index(child, &child_path)?);
344 }
345 Ok(files)
346}
347
348pub fn parse_index(content: &[u8]) -> Result<Vec<CollectorFile>> {
349 let root: IndexDirectory = serde_json::from_slice(content)
350 .map_err(|error| Error::parse(format!("Invalid CollecTor index: {error}")))?;
351 let mut files = flatten_index(root, &[])?;
352 files.sort_by_key(|file| (file.start.is_none(), file.start));
353 Ok(files)
354}
355
356struct CachedIndex {
357 files: Vec<CollectorFile>,
358 fetched_at: Instant,
359}
360
361pub struct CollecTor {
362 base_url: String,
363 retries: u32,
364 timeout: Option<Duration>,
365 cached: Mutex<Option<CachedIndex>>,
366}
367
368impl Default for CollecTor {
369 fn default() -> Self {
370 Self::new()
371 }
372}
373
374impl CollecTor {
375 pub fn new() -> Self {
376 Self::with_url(COLLECTOR_URL)
377 }
378
379 pub fn with_url(base_url: &str) -> Self {
380 let base_url = match base_url.ends_with('/') {
381 true => base_url.to_string(),
382 false => format!("{base_url}/"),
383 };
384 Self {
385 base_url,
386 retries: 2,
387 timeout: None,
388 cached: Mutex::new(None),
389 }
390 }
391
392 pub fn with_timeout(mut self, timeout: Duration) -> Self {
393 self.timeout = Some(timeout);
394 self
395 }
396
397 pub fn with_retries(mut self, retries: u32) -> Self {
398 self.retries = retries;
399 self
400 }
401
402 pub fn shared() -> &'static CollecTor {
403 &SHARED_COLLECTOR
404 }
405
406 pub fn base_url(&self) -> &str {
407 &self.base_url
408 }
409
410 fn fresh_files(&self) -> Option<Vec<CollectorFile>> {
411 let cached = self
412 .cached
413 .lock()
414 .unwrap_or_else(|error| error.into_inner());
415 cached
416 .as_ref()
417 .filter(|index| index.fetched_at.elapsed() < REFRESH_INDEX_RATE)
418 .map(|index| index.files.clone())
419 }
420
421 pub async fn all_files(&self) -> Result<Vec<CollectorFile>> {
422 if let Some(files) = self.fresh_files() {
423 return Ok(files);
424 }
425 let compression = Compression::Lzma;
426 let url = format!(
427 "{}index/index.json{}",
428 self.base_url,
429 compression.extension()
430 );
431 let compressed = download(&url, self.timeout, self.retries).await?;
432 let files = parse_index(&compression.decompress(&compressed)?)?;
433 let mut cached = self
434 .cached
435 .lock()
436 .unwrap_or_else(|error| error.into_inner());
437 *cached = Some(CachedIndex {
438 files: files.clone(),
439 fetched_at: Instant::now(),
440 });
441 Ok(files)
442 }
443
444 pub async fn files(
445 &self,
446 descriptor_type: Option<&str>,
447 start: Option<NaiveDateTime>,
448 end: Option<NaiveDateTime>,
449 ) -> Result<Vec<CollectorFile>> {
450 Ok(self
451 .all_files()
452 .await?
453 .into_iter()
454 .filter(|file| {
455 start.is_none_or(|start| file.end.is_some_and(|end| end >= start))
456 })
457 .filter(|file| {
458 end.is_none_or(|end| file.start.is_some_and(|start| start <= end))
459 })
460 .filter(|file| {
461 descriptor_type.is_none_or(|wanted| {
462 file.types
463 .iter()
464 .any(|candidate| candidate.starts_with(wanted))
465 })
466 })
467 .collect())
468 }
469
470 async fn collect(
471 &self,
472 descriptor_type: &str,
473 request: &CollectorRequest,
474 ) -> Result<Vec<Descriptor>> {
475 let mut descriptors = Vec::new();
476 for file in self
477 .files(Some(descriptor_type), request.start, request.end)
478 .await?
479 {
480 descriptors.extend(
481 file.read(&self.base_url, Some(descriptor_type), request)
482 .await?,
483 );
484 }
485 Ok(descriptors)
486 }
487
488 pub async fn get_server_descriptors(
489 &self,
490 request: &CollectorRequest,
491 bridge: bool,
492 ) -> Result<Vec<Descriptor>> {
493 match bridge {
494 true => self.collect("bridge-server-descriptor", request).await,
495 false => self.collect("server-descriptor", request).await,
496 }
497 }
498
499 pub async fn get_extrainfo_descriptors(
500 &self,
501 request: &CollectorRequest,
502 bridge: bool,
503 ) -> Result<Vec<Descriptor>> {
504 match bridge {
505 true => self.collect("bridge-extra-info", request).await,
506 false => self.collect("extra-info", request).await,
507 }
508 }
509
510 pub async fn get_microdescriptors(
511 &self,
512 request: &CollectorRequest,
513 ) -> Result<Vec<Descriptor>> {
514 self.collect("microdescriptor", request).await
515 }
516
517 pub async fn get_consensus(
518 &self,
519 request: &CollectorRequest,
520 version: u32,
521 microdescriptor: bool,
522 bridge: bool,
523 ) -> Result<Vec<Descriptor>> {
524 let descriptor_type = match (version, microdescriptor, bridge) {
525 (_, _, true) => "bridge-network-status",
526 (3, false, false) => "network-status-consensus-3",
527 (3, true, false) => "network-status-microdesc-consensus-3",
528 (2, false, false) => "network-status-2",
529 (_, true, false) => {
530 return Err(Error::invalid_input(format!(
531 "Only v3 microdescriptors are available (not version {version})"
532 )));
533 }
534 _ => {
535 return Err(Error::invalid_input(format!(
536 "Only v2 and v3 router status entries are available (not version \
537 {version})"
538 )));
539 }
540 };
541 self.collect(descriptor_type, request).await
542 }
543
544 pub async fn get_key_certificates(
545 &self,
546 request: &CollectorRequest,
547 ) -> Result<Vec<Descriptor>> {
548 self.collect("dir-key-certificate-3", request).await
549 }
550
551 pub async fn get_bandwidth_files(
552 &self,
553 request: &CollectorRequest,
554 ) -> Result<Vec<Descriptor>> {
555 self.collect("bandwidth-file", request).await
556 }
557
558 pub async fn get_exit_lists(
559 &self,
560 request: &CollectorRequest,
561 ) -> Result<Vec<Descriptor>> {
562 self.collect("tordnsel", request).await
563 }
564}