1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3#![allow(renamed_and_removed_lints)] #![allow(unknown_lints)] #![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![allow(clippy::cognitive_complexity)] #![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![warn(clippy::or_fun_call)]
28#![deny(clippy::print_stderr)]
29#![deny(clippy::print_stdout)]
30#![warn(clippy::rc_buffer)]
31#![deny(clippy::ref_option_ref)]
32#![warn(clippy::semicolon_if_nothing_returned)]
33#![warn(clippy::trait_duplication_in_bounds)]
34#![deny(clippy::unchecked_time_subtraction)]
35#![deny(clippy::unnecessary_wraps)]
36#![warn(clippy::unseparated_literal_suffix)]
37#![deny(clippy::unwrap_used)]
38#![deny(clippy::mod_module_files)]
39#![allow(clippy::let_unit_value)] #![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] #![allow(clippy::result_large_err)] #![allow(clippy::needless_raw_string_hashes)] #![allow(clippy::needless_lifetimes)] #![allow(mismatched_lifetime_syntaxes)] #![allow(clippy::collapsible_if)] #![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] #![allow(recursion_depth_exceeding_limit)] #![warn(unnameable_types)]
54
55use std::collections::HashMap;
56use std::path::{Path, PathBuf};
57
58use serde::{Deserialize, Serialize};
59use std::borrow::Cow;
60#[cfg(feature = "expand-paths")]
61use {directories::BaseDirs, std::sync::LazyLock};
62
63use tor_error::{ErrorKind, HasKind};
64
65#[cfg(all(test, feature = "expand-paths"))]
66use std::ffi::OsStr;
67
68#[cfg(feature = "address")]
69pub mod addr;
70
71#[cfg(feature = "arti-client")]
72mod arti_client_paths;
73
74#[cfg(feature = "arti-client")]
75pub use arti_client_paths::arti_client_base_resolver;
76
77#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
86#[serde(transparent)]
87pub struct CfgPath(PathInner);
88
89#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
93#[serde(untagged)]
94enum PathInner {
95 Literal(LiteralPath),
97 Shell(String),
99}
100
101#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
102struct LiteralPath {
107 literal: PathBuf,
109}
110
111#[derive(thiserror::Error, Debug, Clone)]
113#[non_exhaustive]
114#[cfg_attr(test, derive(PartialEq))]
115pub enum CfgPathError {
116 #[error("Unrecognized variable {0} in path")]
118 UnknownVar(String),
119 #[error(
121 "Couldn't determine XDG Project Directories, needed to resolve a path; probably, unable to determine HOME directory"
122 )]
123 NoProjectDirs,
124 #[error("Can't construct base directories to resolve a path element")]
126 NoBaseDirs,
127 #[error("Can't find the path to the current binary")]
129 NoProgramPath,
130 #[error("Can't find the directory of the current binary")]
132 NoProgramDir,
133 #[error("Invalid path string: {0:?}")]
137 InvalidString(String),
138 #[error(
140 "Variable interpolation $ is not supported (tor-config/expand-paths feature disabled)); $ must still be doubled"
141 )]
142 VariableInterpolationNotSupported(String),
143 #[error("Home dir ~/ is not supported (tor-config/expand-paths feature disabled)")]
145 HomeDirInterpolationNotSupported(String),
146}
147
148impl HasKind for CfgPathError {
149 fn kind(&self) -> ErrorKind {
150 use CfgPathError as E;
151 use ErrorKind as EK;
152 match self {
153 E::UnknownVar(_) | E::InvalidString(_) => EK::InvalidConfig,
154 E::NoProjectDirs | E::NoBaseDirs => EK::NoHomeDirectory,
155 E::NoProgramPath | E::NoProgramDir => EK::InvalidConfig,
156 E::VariableInterpolationNotSupported(_) | E::HomeDirInterpolationNotSupported(_) => {
157 EK::FeatureDisabled
158 }
159 }
160 }
161}
162
163#[derive(Clone, Debug, Default)]
174pub struct CfgPathResolver {
175 vars: HashMap<String, Result<Cow<'static, Path>, CfgPathError>>,
178}
179
180impl CfgPathResolver {
181 #[cfg(feature = "expand-paths")]
183 fn get_var(&self, var: &str) -> Result<Cow<'static, Path>, CfgPathError> {
184 match self.vars.get(var) {
185 Some(val) => val.clone(),
186 None => Err(CfgPathError::UnknownVar(var.to_owned())),
187 }
188 }
189
190 pub fn set_var(
211 &mut self,
212 var: impl Into<String>,
213 val: Result<Cow<'static, Path>, CfgPathError>,
214 ) {
215 self.vars.insert(var.into(), val);
216 }
217
218 #[cfg(all(test, feature = "expand-paths"))]
220 fn from_pairs<K, V>(vars: impl IntoIterator<Item = (K, V)>) -> CfgPathResolver
221 where
222 K: Into<String>,
223 V: AsRef<OsStr>,
224 {
225 let mut path_resolver = CfgPathResolver::default();
226 for (name, val) in vars.into_iter() {
227 let val = Path::new(val.as_ref()).to_owned();
228 path_resolver.set_var(name, Ok(val.into()));
229 }
230 path_resolver
231 }
232}
233
234impl CfgPath {
235 pub fn new(s: String) -> Self {
237 CfgPath(PathInner::Shell(s))
238 }
239
240 pub fn new_literal<P: Into<PathBuf>>(path: P) -> Self {
242 CfgPath(PathInner::Literal(LiteralPath {
243 literal: path.into(),
244 }))
245 }
246
247 pub fn path(&self, path_resolver: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
252 match &self.0 {
253 PathInner::Shell(s) => expand(s, path_resolver),
254 PathInner::Literal(LiteralPath { literal }) => Ok(literal.clone()),
255 }
256 }
257
258 pub fn as_unexpanded_str(&self) -> Option<&str> {
265 match &self.0 {
266 PathInner::Shell(s) => Some(s),
267 PathInner::Literal(_) => None,
268 }
269 }
270
271 pub fn as_literal_path(&self) -> Option<&Path> {
276 match &self.0 {
277 PathInner::Shell(_) => None,
278 PathInner::Literal(LiteralPath { literal }) => Some(literal),
279 }
280 }
281}
282
283impl std::fmt::Display for CfgPath {
284 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
285 match &self.0 {
286 PathInner::Literal(LiteralPath { literal }) => write!(fmt, "{:?} [exactly]", literal),
287 PathInner::Shell(s) => s.fmt(fmt),
288 }
289 }
290}
291
292#[cfg(feature = "expand-paths")]
296pub fn home() -> Result<&'static Path, CfgPathError> {
297 static HOME_DIR: LazyLock<Option<PathBuf>> =
299 LazyLock::new(|| Some(BaseDirs::new()?.home_dir().to_owned()));
300 HOME_DIR
301 .as_ref()
302 .map(PathBuf::as_path)
303 .ok_or(CfgPathError::NoBaseDirs)
304}
305
306#[cfg(feature = "expand-paths")]
308fn expand(s: &str, path_resolver: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
309 let path = shellexpand::path::full_with_context(
310 s,
311 || home().ok(),
312 |x| path_resolver.get_var(x).map(Some),
313 );
314 Ok(path.map_err(|e| e.cause)?.into_owned())
315}
316
317#[cfg(not(feature = "expand-paths"))]
319fn expand(input: &str, _: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
320 if input.starts_with('~') {
322 return Err(CfgPathError::HomeDirInterpolationNotSupported(input.into()));
323 }
324
325 let mut out = String::with_capacity(input.len());
326 let mut s = input;
327 while let Some((lhs, rhs)) = s.split_once('$') {
328 if let Some(rhs) = rhs.strip_prefix('$') {
329 out += lhs;
331 out += "$";
332 s = rhs;
333 } else {
334 return Err(CfgPathError::VariableInterpolationNotSupported(
335 input.into(),
336 ));
337 }
338 }
339 out += s;
340 Ok(out.into())
341}
342
343#[cfg(all(test, feature = "expand-paths"))]
344mod test {
345 #![allow(clippy::unwrap_used)]
346 use super::*;
347
348 #[test]
349 fn expand_no_op() {
350 let r = CfgPathResolver::from_pairs([("FOO", "foo")]);
351
352 let p = CfgPath::new("Hello/world".to_string());
353 assert_eq!(p.to_string(), "Hello/world".to_string());
354 assert_eq!(p.path(&r).unwrap().to_str(), Some("Hello/world"));
355
356 let p = CfgPath::new("/usr/local/foo".to_string());
357 assert_eq!(p.to_string(), "/usr/local/foo".to_string());
358 assert_eq!(p.path(&r).unwrap().to_str(), Some("/usr/local/foo"));
359 }
360
361 #[cfg(not(target_family = "windows"))]
362 #[test]
363 fn expand_home() {
364 let r = CfgPathResolver::from_pairs([("USER_HOME", home().unwrap())]);
365
366 let p = CfgPath::new("~/.arti/config".to_string());
367 assert_eq!(p.to_string(), "~/.arti/config".to_string());
368
369 let expected = dirs::home_dir().unwrap().join(".arti/config");
370 assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
371
372 let p = CfgPath::new("${USER_HOME}/.arti/config".to_string());
373 assert_eq!(p.to_string(), "${USER_HOME}/.arti/config".to_string());
374 assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
375 }
376
377 #[cfg(target_family = "windows")]
378 #[test]
379 fn expand_home() {
380 let r = CfgPathResolver::from_pairs([("USER_HOME", home().unwrap())]);
381
382 let p = CfgPath::new("~\\.arti\\config".to_string());
383 assert_eq!(p.to_string(), "~\\.arti\\config".to_string());
384
385 let expected = dirs::home_dir().unwrap().join(".arti\\config");
386 assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
387
388 let p = CfgPath::new("${USER_HOME}\\.arti\\config".to_string());
389 assert_eq!(p.to_string(), "${USER_HOME}\\.arti\\config".to_string());
390 assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
391 }
392
393 #[test]
394 fn expand_bogus() {
395 let r = CfgPathResolver::from_pairs([("FOO", "foo")]);
396
397 let p = CfgPath::new("${ARTI_WOMBAT}/example".to_string());
398 assert_eq!(p.to_string(), "${ARTI_WOMBAT}/example".to_string());
399
400 assert!(matches!(p.path(&r), Err(CfgPathError::UnknownVar(_))));
401 assert_eq!(
402 &p.path(&r).unwrap_err().to_string(),
403 "Unrecognized variable ARTI_WOMBAT in path"
404 );
405 }
406
407 #[test]
408 fn literal() {
409 let r = CfgPathResolver::from_pairs([("ARTI_CACHE", "foo")]);
410
411 let p = CfgPath::new_literal(PathBuf::from("${ARTI_CACHE}/literally"));
412 assert_eq!(
414 p.path(&r).unwrap().to_str().unwrap(),
415 "${ARTI_CACHE}/literally"
416 );
417 assert_eq!(p.to_string(), "\"${ARTI_CACHE}/literally\" [exactly]");
418 }
419
420 #[test]
421 #[cfg(feature = "expand-paths")]
422 fn program_dir() {
423 let current_exe = std::env::current_exe().unwrap();
424 let r = CfgPathResolver::from_pairs([("PROGRAM_DIR", current_exe.parent().unwrap())]);
425
426 let p = CfgPath::new("${PROGRAM_DIR}/foo".to_string());
427
428 let mut this_binary = current_exe;
429 this_binary.pop();
430 this_binary.push("foo");
431 let expanded = p.path(&r).unwrap();
432 assert_eq!(expanded, this_binary);
433 }
434
435 #[test]
436 #[cfg(not(feature = "expand-paths"))]
437 fn rejections() {
438 let r = CfgPathResolver::from_pairs([("PROGRAM_DIR", std::env::current_exe().unwrap())]);
439
440 let chk_err = |s: &str, mke: &dyn Fn(String) -> CfgPathError| {
441 let p = CfgPath::new(s.to_string());
442 assert_eq!(p.path(&r).unwrap_err(), mke(s.to_string()));
443 };
444
445 let chk_ok = |s: &str, exp| {
446 let p = CfgPath::new(s.to_string());
447 assert_eq!(p.path(&r), Ok(PathBuf::from(exp)));
448 };
449
450 chk_err(
451 "some/${PROGRAM_DIR}/foo",
452 &CfgPathError::VariableInterpolationNotSupported,
453 );
454 chk_err("~some", &CfgPathError::HomeDirInterpolationNotSupported);
455
456 chk_ok("some$$foo$$bar", "some$foo$bar");
457 chk_ok("no dollars", "no dollars");
458 }
459}
460
461#[cfg(test)]
462mod test_serde {
463 #![allow(clippy::bool_assert_comparison)]
465 #![allow(clippy::clone_on_copy)]
466 #![allow(clippy::dbg_macro)]
467 #![allow(clippy::mixed_attributes_style)]
468 #![allow(clippy::print_stderr)]
469 #![allow(clippy::print_stdout)]
470 #![allow(clippy::single_char_pattern)]
471 #![allow(clippy::unwrap_used)]
472 #![allow(clippy::unchecked_time_subtraction)]
473 #![allow(clippy::useless_vec)]
474 #![allow(clippy::needless_pass_by_value)]
475 #![allow(clippy::string_slice)] use super::*;
479
480 use std::ffi::OsString;
481 use std::fmt::Debug;
482
483 use derive_deftly::Deftly;
484 use tor_config::load::TopLevel;
485
486 #[derive(Serialize, Deserialize, Deftly, Eq, PartialEq, Debug)]
487 #[derive_deftly(tor_config::derive::TorConfig)]
488 #[deftly(tor_config(no_default_trait))]
489 struct TestConfigFile {
490 #[deftly(tor_config(no_default))]
491 p: CfgPath,
492 }
493
494 impl TopLevel for TestConfigFile {
495 type Builder = TestConfigFileBuilder;
496 }
497
498 fn deser_json(json: &str) -> CfgPath {
499 dbg!(json);
500 let TestConfigFile { p } = serde_json::from_str(json).expect("deser json failed");
501 p
502 }
503 fn deser_toml(toml: &str) -> CfgPath {
504 dbg!(toml);
505 let TestConfigFile { p } = toml::from_str(toml).expect("deser toml failed");
506 p
507 }
508 fn deser_toml_cfg(toml: &str) -> CfgPath {
509 dbg!(toml);
510 let mut sources = tor_config::ConfigurationSources::new_empty();
511 sources.push_source(
512 tor_config::ConfigurationSource::from_verbatim(toml.to_string()),
513 tor_config::sources::MustRead::MustRead,
514 );
515 let cfg = sources.load().unwrap();
516
517 dbg!(&cfg);
518 let TestConfigFile { p } = tor_config::load::resolve(&cfg).expect("cfg resolution failed");
519 p
520 }
521
522 #[test]
523 fn test_parse() {
524 fn desers(toml: &str, json: &str) -> Vec<CfgPath> {
525 vec![deser_toml(toml), deser_toml_cfg(toml), deser_json(json)]
526 }
527
528 for cp in desers(r#"p = "string""#, r#"{ "p": "string" }"#) {
529 assert_eq!(cp.as_unexpanded_str(), Some("string"));
530 assert_eq!(cp.as_literal_path(), None);
531 }
532
533 for cp in desers(
534 r#"p = { literal = "lit" }"#,
535 r#"{ "p": {"literal": "lit"} }"#,
536 ) {
537 assert_eq!(cp.as_unexpanded_str(), None);
538 assert_eq!(cp.as_literal_path(), Some(&*PathBuf::from("lit")));
539 }
540 }
541
542 fn non_string_path() -> PathBuf {
543 #[cfg(target_family = "unix")]
544 {
545 use std::os::unix::ffi::OsStringExt;
546 return PathBuf::from(OsString::from_vec(vec![0x80_u8]));
547 }
548
549 #[cfg(target_family = "windows")]
550 {
551 use std::os::windows::ffi::OsStringExt;
552 return PathBuf::from(OsString::from_wide(&[0xD800_u16]));
553 }
554
555 #[allow(unreachable_code)]
556 PathBuf::default()
558 }
559
560 fn test_roundtrip_cases<SER, S, DESER, E, F>(ser: SER, deser: DESER)
561 where
562 SER: Fn(&TestConfigFile) -> Result<S, E>,
563 DESER: Fn(&S) -> Result<TestConfigFile, F>,
564 S: Debug,
565 E: Debug,
566 F: Debug,
567 {
568 let case = |easy, p| {
569 let input = TestConfigFile { p };
570 let s = match ser(&input) {
571 Ok(s) => s,
572 Err(e) if easy => panic!("ser failed {:?} e={:?}", input, e),
573 Err(_) => return,
574 };
575 dbg!(&input, &s);
576 let output = deser(&s).expect("deser failed");
577 assert_eq!(&input, &output, "s={:?}", s);
578 };
579
580 case(true, CfgPath::new("string".into()));
581 case(true, CfgPath::new_literal(PathBuf::from("nice path")));
582 case(true, CfgPath::new_literal(PathBuf::from("path with ✓")));
583
584 case(false, CfgPath::new_literal(non_string_path()));
589 }
590
591 #[test]
592 fn roundtrip_json() {
593 test_roundtrip_cases(
594 |input| serde_json::to_string(&input),
595 |json| serde_json::from_str(json),
596 );
597 }
598
599 #[test]
600 fn roundtrip_toml() {
601 test_roundtrip_cases(|input| toml::to_string(&input), |toml| toml::from_str(toml));
602 }
603
604 #[test]
605 fn roundtrip_mpack() {
606 test_roundtrip_cases(
607 |input| rmp_serde::to_vec(&input),
608 |mpack| rmp_serde::from_slice(mpack),
609 );
610 }
611}