1#![cfg_attr(docsrs, feature(doc_auto_cfg, 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#![warn(clippy::cognitive_complexity)]
15#![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#![deny(clippy::print_stderr)]
28#![deny(clippy::print_stdout)]
29#![warn(clippy::rc_buffer)]
30#![deny(clippy::ref_option_ref)]
31#![warn(clippy::semicolon_if_nothing_returned)]
32#![warn(clippy::trait_duplication_in_bounds)]
33#![deny(clippy::unchecked_duration_subtraction)]
34#![deny(clippy::unnecessary_wraps)]
35#![warn(clippy::unseparated_literal_suffix)]
36#![deny(clippy::unwrap_used)]
37#![deny(clippy::mod_module_files)]
38#![allow(clippy::let_unit_value)] #![allow(clippy::uninlined_format_args)]
40#![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)] use std::collections::HashMap;
48use std::path::{Path, PathBuf};
49
50use serde::{Deserialize, Serialize};
51use std::borrow::Cow;
52#[cfg(feature = "expand-paths")]
53use {directories::BaseDirs, std::sync::LazyLock};
54
55use tor_error::{ErrorKind, HasKind};
56
57#[cfg(all(test, feature = "expand-paths"))]
58use std::ffi::OsStr;
59
60#[cfg(feature = "address")]
61pub mod addr;
62
63#[cfg(feature = "arti-client")]
64mod arti_client_paths;
65
66#[cfg(feature = "arti-client")]
67#[cfg_attr(docsrs, doc(cfg(feature = "arti-client")))]
68pub use arti_client_paths::arti_client_base_resolver;
69
70#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
79#[serde(transparent)]
80pub struct CfgPath(PathInner);
81
82#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
86#[serde(untagged)]
87enum PathInner {
88 Literal(LiteralPath),
90 Shell(String),
92}
93
94#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
95struct LiteralPath {
100 literal: PathBuf,
102}
103
104#[derive(thiserror::Error, Debug, Clone)]
106#[non_exhaustive]
107#[cfg_attr(test, derive(PartialEq))]
108pub enum CfgPathError {
109 #[error("Unrecognized variable {0} in path")]
111 UnknownVar(String),
112 #[error(
114 "Couldn't determine XDG Project Directories, needed to resolve a path; probably, unable to determine HOME directory"
115 )]
116 NoProjectDirs,
117 #[error("Can't construct base directories to resolve a path element")]
119 NoBaseDirs,
120 #[error("Can't find the path to the current binary")]
122 NoProgramPath,
123 #[error("Can't find the directory of the current binary")]
125 NoProgramDir,
126 #[error("Invalid path string: {0:?}")]
130 InvalidString(String),
131 #[error(
133 "Variable interpolation $ is not supported (tor-config/expand-paths feature disabled)); $ must still be doubled"
134 )]
135 VariableInterpolationNotSupported(String),
136 #[error("Home dir ~/ is not supported (tor-config/expand-paths feature disabled)")]
138 HomeDirInterpolationNotSupported(String),
139}
140
141impl HasKind for CfgPathError {
142 fn kind(&self) -> ErrorKind {
143 use CfgPathError as E;
144 use ErrorKind as EK;
145 match self {
146 E::UnknownVar(_) | E::InvalidString(_) => EK::InvalidConfig,
147 E::NoProjectDirs | E::NoBaseDirs => EK::NoHomeDirectory,
148 E::NoProgramPath | E::NoProgramDir => EK::InvalidConfig,
149 E::VariableInterpolationNotSupported(_) | E::HomeDirInterpolationNotSupported(_) => {
150 EK::FeatureDisabled
151 }
152 }
153 }
154}
155
156#[derive(Clone, Debug, Default)]
167pub struct CfgPathResolver {
168 vars: HashMap<String, Result<Cow<'static, Path>, CfgPathError>>,
171}
172
173impl CfgPathResolver {
174 #[cfg(feature = "expand-paths")]
176 fn get_var(&self, var: &str) -> Result<Cow<'static, Path>, CfgPathError> {
177 match self.vars.get(var) {
178 Some(val) => val.clone(),
179 None => Err(CfgPathError::UnknownVar(var.to_owned())),
180 }
181 }
182
183 pub fn set_var(
204 &mut self,
205 var: impl Into<String>,
206 val: Result<Cow<'static, Path>, CfgPathError>,
207 ) {
208 self.vars.insert(var.into(), val);
209 }
210
211 #[cfg(all(test, feature = "expand-paths"))]
213 fn from_pairs<K, V>(vars: impl IntoIterator<Item = (K, V)>) -> CfgPathResolver
214 where
215 K: Into<String>,
216 V: AsRef<OsStr>,
217 {
218 let mut path_resolver = CfgPathResolver::default();
219 for (name, val) in vars.into_iter() {
220 let val = Path::new(val.as_ref()).to_owned();
221 path_resolver.set_var(name, Ok(val.into()));
222 }
223 path_resolver
224 }
225}
226
227impl CfgPath {
228 pub fn new(s: String) -> Self {
230 CfgPath(PathInner::Shell(s))
231 }
232
233 pub fn new_literal<P: Into<PathBuf>>(path: P) -> Self {
235 CfgPath(PathInner::Literal(LiteralPath {
236 literal: path.into(),
237 }))
238 }
239
240 pub fn path(&self, path_resolver: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
245 match &self.0 {
246 PathInner::Shell(s) => expand(s, path_resolver),
247 PathInner::Literal(LiteralPath { literal }) => Ok(literal.clone()),
248 }
249 }
250
251 pub fn as_unexpanded_str(&self) -> Option<&str> {
258 match &self.0 {
259 PathInner::Shell(s) => Some(s),
260 PathInner::Literal(_) => None,
261 }
262 }
263
264 pub fn as_literal_path(&self) -> Option<&Path> {
269 match &self.0 {
270 PathInner::Shell(_) => None,
271 PathInner::Literal(LiteralPath { literal }) => Some(literal),
272 }
273 }
274}
275
276impl std::fmt::Display for CfgPath {
277 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278 match &self.0 {
279 PathInner::Literal(LiteralPath { literal }) => write!(fmt, "{:?} [exactly]", literal),
280 PathInner::Shell(s) => s.fmt(fmt),
281 }
282 }
283}
284
285#[cfg(feature = "expand-paths")]
289pub fn home() -> Result<&'static Path, CfgPathError> {
290 static HOME_DIR: LazyLock<Option<PathBuf>> =
292 LazyLock::new(|| Some(BaseDirs::new()?.home_dir().to_owned()));
293 HOME_DIR
294 .as_ref()
295 .map(PathBuf::as_path)
296 .ok_or(CfgPathError::NoBaseDirs)
297}
298
299#[cfg(feature = "expand-paths")]
301fn expand(s: &str, path_resolver: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
302 let path = shellexpand::path::full_with_context(
303 s,
304 || home().ok(),
305 |x| path_resolver.get_var(x).map(Some),
306 );
307 Ok(path.map_err(|e| e.cause)?.into_owned())
308}
309
310#[cfg(not(feature = "expand-paths"))]
312fn expand(input: &str, _: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
313 if input.starts_with('~') {
315 return Err(CfgPathError::HomeDirInterpolationNotSupported(input.into()));
316 }
317
318 let mut out = String::with_capacity(input.len());
319 let mut s = input;
320 while let Some((lhs, rhs)) = s.split_once('$') {
321 if let Some(rhs) = rhs.strip_prefix('$') {
322 out += lhs;
324 out += "$";
325 s = rhs;
326 } else {
327 return Err(CfgPathError::VariableInterpolationNotSupported(
328 input.into(),
329 ));
330 }
331 }
332 out += s;
333 Ok(out.into())
334}
335
336#[cfg(all(test, feature = "expand-paths"))]
337mod test {
338 #![allow(clippy::unwrap_used)]
339 use super::*;
340
341 #[test]
342 fn expand_no_op() {
343 let r = CfgPathResolver::from_pairs([("FOO", "foo")]);
344
345 let p = CfgPath::new("Hello/world".to_string());
346 assert_eq!(p.to_string(), "Hello/world".to_string());
347 assert_eq!(p.path(&r).unwrap().to_str(), Some("Hello/world"));
348
349 let p = CfgPath::new("/usr/local/foo".to_string());
350 assert_eq!(p.to_string(), "/usr/local/foo".to_string());
351 assert_eq!(p.path(&r).unwrap().to_str(), Some("/usr/local/foo"));
352 }
353
354 #[cfg(not(target_family = "windows"))]
355 #[test]
356 fn expand_home() {
357 let r = CfgPathResolver::from_pairs([("USER_HOME", home().unwrap())]);
358
359 let p = CfgPath::new("~/.arti/config".to_string());
360 assert_eq!(p.to_string(), "~/.arti/config".to_string());
361
362 let expected = dirs::home_dir().unwrap().join(".arti/config");
363 assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
364
365 let p = CfgPath::new("${USER_HOME}/.arti/config".to_string());
366 assert_eq!(p.to_string(), "${USER_HOME}/.arti/config".to_string());
367 assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
368 }
369
370 #[cfg(target_family = "windows")]
371 #[test]
372 fn expand_home() {
373 let r = CfgPathResolver::from_pairs([("USER_HOME", home().unwrap())]);
374
375 let p = CfgPath::new("~\\.arti\\config".to_string());
376 assert_eq!(p.to_string(), "~\\.arti\\config".to_string());
377
378 let expected = dirs::home_dir().unwrap().join(".arti\\config");
379 assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
380
381 let p = CfgPath::new("${USER_HOME}\\.arti\\config".to_string());
382 assert_eq!(p.to_string(), "${USER_HOME}\\.arti\\config".to_string());
383 assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
384 }
385
386 #[test]
387 fn expand_bogus() {
388 let r = CfgPathResolver::from_pairs([("FOO", "foo")]);
389
390 let p = CfgPath::new("${ARTI_WOMBAT}/example".to_string());
391 assert_eq!(p.to_string(), "${ARTI_WOMBAT}/example".to_string());
392
393 assert!(matches!(p.path(&r), Err(CfgPathError::UnknownVar(_))));
394 assert_eq!(
395 &p.path(&r).unwrap_err().to_string(),
396 "Unrecognized variable ARTI_WOMBAT in path"
397 );
398 }
399
400 #[test]
401 fn literal() {
402 let r = CfgPathResolver::from_pairs([("ARTI_CACHE", "foo")]);
403
404 let p = CfgPath::new_literal(PathBuf::from("${ARTI_CACHE}/literally"));
405 assert_eq!(
407 p.path(&r).unwrap().to_str().unwrap(),
408 "${ARTI_CACHE}/literally"
409 );
410 assert_eq!(p.to_string(), "\"${ARTI_CACHE}/literally\" [exactly]");
411 }
412
413 #[test]
414 #[cfg(feature = "expand-paths")]
415 fn program_dir() {
416 let current_exe = std::env::current_exe().unwrap();
417 let r = CfgPathResolver::from_pairs([("PROGRAM_DIR", current_exe.parent().unwrap())]);
418
419 let p = CfgPath::new("${PROGRAM_DIR}/foo".to_string());
420
421 let mut this_binary = current_exe;
422 this_binary.pop();
423 this_binary.push("foo");
424 let expanded = p.path(&r).unwrap();
425 assert_eq!(expanded, this_binary);
426 }
427
428 #[test]
429 #[cfg(not(feature = "expand-paths"))]
430 fn rejections() {
431 let r = CfgPathResolver::from_pairs([("PROGRAM_DIR", std::env::current_exe().unwrap())]);
432
433 let chk_err = |s: &str, mke: &dyn Fn(String) -> CfgPathError| {
434 let p = CfgPath::new(s.to_string());
435 assert_eq!(p.path(&r).unwrap_err(), mke(s.to_string()));
436 };
437
438 let chk_ok = |s: &str, exp| {
439 let p = CfgPath::new(s.to_string());
440 assert_eq!(p.path(&r), Ok(PathBuf::from(exp)));
441 };
442
443 chk_err(
444 "some/${PROGRAM_DIR}/foo",
445 &CfgPathError::VariableInterpolationNotSupported,
446 );
447 chk_err("~some", &CfgPathError::HomeDirInterpolationNotSupported);
448
449 chk_ok("some$$foo$$bar", "some$foo$bar");
450 chk_ok("no dollars", "no dollars");
451 }
452}
453
454#[cfg(test)]
455mod test_serde {
456 #![allow(clippy::bool_assert_comparison)]
458 #![allow(clippy::clone_on_copy)]
459 #![allow(clippy::dbg_macro)]
460 #![allow(clippy::mixed_attributes_style)]
461 #![allow(clippy::print_stderr)]
462 #![allow(clippy::print_stdout)]
463 #![allow(clippy::single_char_pattern)]
464 #![allow(clippy::unwrap_used)]
465 #![allow(clippy::unchecked_duration_subtraction)]
466 #![allow(clippy::useless_vec)]
467 #![allow(clippy::needless_pass_by_value)]
468 use super::*;
471
472 use std::ffi::OsString;
473 use std::fmt::Debug;
474
475 use derive_builder::Builder;
476 use tor_config::load::TopLevel;
477 use tor_config::{ConfigBuildError, impl_standard_builder};
478
479 #[derive(Serialize, Deserialize, Builder, Eq, PartialEq, Debug)]
480 #[builder(derive(Serialize, Deserialize, Debug))]
481 #[builder(build_fn(error = "ConfigBuildError"))]
482 struct TestConfigFile {
483 p: CfgPath,
484 }
485
486 impl_standard_builder! { TestConfigFile: !Default }
487
488 impl TopLevel for TestConfigFile {
489 type Builder = TestConfigFileBuilder;
490 }
491
492 fn deser_json(json: &str) -> CfgPath {
493 dbg!(json);
494 let TestConfigFile { p } = serde_json::from_str(json).expect("deser json failed");
495 p
496 }
497 fn deser_toml(toml: &str) -> CfgPath {
498 dbg!(toml);
499 let TestConfigFile { p } = toml::from_str(toml).expect("deser toml failed");
500 p
501 }
502 fn deser_toml_cfg(toml: &str) -> CfgPath {
503 dbg!(toml);
504 let mut sources = tor_config::ConfigurationSources::new_empty();
505 sources.push_source(
506 tor_config::ConfigurationSource::from_verbatim(toml.to_string()),
507 tor_config::sources::MustRead::MustRead,
508 );
509 let cfg = sources.load().unwrap();
510
511 dbg!(&cfg);
512 let TestConfigFile { p } = tor_config::load::resolve(cfg).expect("cfg resolution failed");
513 p
514 }
515
516 #[test]
517 fn test_parse() {
518 fn desers(toml: &str, json: &str) -> Vec<CfgPath> {
519 vec![deser_toml(toml), deser_toml_cfg(toml), deser_json(json)]
520 }
521
522 for cp in desers(r#"p = "string""#, r#"{ "p": "string" }"#) {
523 assert_eq!(cp.as_unexpanded_str(), Some("string"));
524 assert_eq!(cp.as_literal_path(), None);
525 }
526
527 for cp in desers(
528 r#"p = { literal = "lit" }"#,
529 r#"{ "p": {"literal": "lit"} }"#,
530 ) {
531 assert_eq!(cp.as_unexpanded_str(), None);
532 assert_eq!(cp.as_literal_path(), Some(&*PathBuf::from("lit")));
533 }
534 }
535
536 fn non_string_path() -> PathBuf {
537 #[cfg(target_family = "unix")]
538 {
539 use std::os::unix::ffi::OsStringExt;
540 return PathBuf::from(OsString::from_vec(vec![0x80_u8]));
541 }
542
543 #[cfg(target_family = "windows")]
544 {
545 use std::os::windows::ffi::OsStringExt;
546 return PathBuf::from(OsString::from_wide(&[0xD800_u16]));
547 }
548
549 #[allow(unreachable_code)]
550 PathBuf::default()
552 }
553
554 fn test_roundtrip_cases<SER, S, DESER, E, F>(ser: SER, deser: DESER)
555 where
556 SER: Fn(&TestConfigFile) -> Result<S, E>,
557 DESER: Fn(&S) -> Result<TestConfigFile, F>,
558 S: Debug,
559 E: Debug,
560 F: Debug,
561 {
562 let case = |easy, p| {
563 let input = TestConfigFile { p };
564 let s = match ser(&input) {
565 Ok(s) => s,
566 Err(e) if easy => panic!("ser failed {:?} e={:?}", &input, &e),
567 Err(_) => return,
568 };
569 dbg!(&input, &s);
570 let output = deser(&s).expect("deser failed");
571 assert_eq!(&input, &output, "s={:?}", &s);
572 };
573
574 case(true, CfgPath::new("string".into()));
575 case(true, CfgPath::new_literal(PathBuf::from("nice path")));
576 case(true, CfgPath::new_literal(PathBuf::from("path with ✓")));
577
578 case(false, CfgPath::new_literal(non_string_path()));
583 }
584
585 #[test]
586 fn roundtrip_json() {
587 test_roundtrip_cases(
588 |input| serde_json::to_string(&input),
589 |json| serde_json::from_str(json),
590 );
591 }
592
593 #[test]
594 fn roundtrip_toml() {
595 test_roundtrip_cases(|input| toml::to_string(&input), |toml| toml::from_str(toml));
596 }
597
598 #[test]
599 fn roundtrip_mpack() {
600 test_roundtrip_cases(
601 |input| rmp_serde::to_vec(&input),
602 |mpack| rmp_serde::from_slice(mpack),
603 );
604 }
605}