tor_persist/
fs.rs

1//! Filesystem + JSON implementation of StateMgr.
2
3#![forbid(unsafe_code)] // if you remove this, enable (or write) miri tests (git grep miri)
4
5mod clean;
6
7use crate::err::{Action, ErrorSource, Resource};
8use crate::load_store;
9use crate::{Error, LockStatus, Result, StateMgr};
10use fs_mistrust::anon_home::PathExt as _;
11use fs_mistrust::CheckedDir;
12use futures::FutureExt;
13use oneshot_fused_workaround as oneshot;
14use serde::{de::DeserializeOwned, Serialize};
15use std::path::{Path, PathBuf};
16use std::sync::{Arc, Mutex};
17use std::time::SystemTime;
18use tor_error::warn_report;
19use tracing::info;
20
21/// Implementation of StateMgr that stores state as JSON files on disk.
22///
23/// # Locking
24///
25/// This manager uses a lock file to determine whether it's allowed to
26/// write to the disk.  Only one process should write to the disk at
27/// a time, though any number may read from the disk.
28///
29/// By default, every `FsStateMgr` starts out unlocked, and only able
30/// to read.  Use [`FsStateMgr::try_lock()`] to lock it.
31///
32/// # Limitations
33///
34/// 1. This manager only accepts objects that can be serialized as
35///    JSON documents.  Some types (like maps with non-string keys) can't
36///    be serialized as JSON.
37///
38/// 2. This manager normalizes keys to an fs-safe format before saving
39///    data with them.  This keeps you from accidentally creating or
40///    reading files elsewhere in the filesystem, but it doesn't prevent
41///    collisions when two keys collapse to the same fs-safe filename.
42///    Therefore, you should probably only use ascii keys that are
43///    fs-safe on all systems.
44///
45/// NEVER use user-controlled or remote-controlled data for your keys.
46#[cfg_attr(docsrs, doc(cfg(not(target_arch = "wasm32"))))]
47#[derive(Clone, Debug)]
48pub struct FsStateMgr {
49    /// Inner reference-counted object.
50    inner: Arc<FsStateMgrInner>,
51}
52
53/// Inner reference-counted object, used by `FsStateMgr`.
54#[derive(Debug)]
55struct FsStateMgrInner {
56    /// Directory in which we store state files.
57    statepath: CheckedDir,
58    /// Lockfile to achieve exclusive access to state files.
59    lockfile: Mutex<fslock::LockFile>,
60    /// A oneshot sender that is used to alert other tasks when this lock is
61    /// finally dropped.
62    ///
63    /// It is a sender for Void because we never actually want to send anything here;
64    /// we only want to generate canceled events.
65    #[allow(dead_code)] // the only purpose of this field is to be dropped.
66    lock_dropped_tx: oneshot::Sender<void::Void>,
67    /// Cloneable handle which resolves when this lock is dropped.
68    lock_dropped_rx: futures::future::Shared<oneshot::Receiver<void::Void>>,
69}
70
71impl FsStateMgr {
72    /// Construct a new `FsStateMgr` to store data in `path`.
73    ///
74    /// This function will try to create `path` if it does not already
75    /// exist.
76    ///
77    /// All files must be "private" according to the rules specified in `mistrust`.
78    pub fn from_path_and_mistrust<P: AsRef<Path>>(
79        path: P,
80        mistrust: &fs_mistrust::Mistrust,
81    ) -> Result<Self> {
82        let path = path.as_ref();
83        let dir = path.join("state");
84
85        let statepath = mistrust
86            .verifier()
87            .check_content()
88            .make_secure_dir(&dir)
89            .map_err(|e| {
90                Error::new(
91                    e,
92                    Action::Initializing,
93                    Resource::Directory { dir: dir.clone() },
94                )
95            })?;
96        let lockpath = statepath.join("state.lock").map_err(|e| {
97            Error::new(
98                e,
99                Action::Initializing,
100                Resource::Directory { dir: dir.clone() },
101            )
102        })?;
103
104        let lockfile = Mutex::new(fslock::LockFile::open(&lockpath).map_err(|e| {
105            Error::new(
106                e,
107                Action::Initializing,
108                Resource::File {
109                    container: dir,
110                    file: "state.lock".into(),
111                },
112            )
113        })?);
114
115        let (lock_dropped_tx, lock_dropped_rx) = oneshot::channel();
116        let lock_dropped_rx = lock_dropped_rx.shared();
117        Ok(FsStateMgr {
118            inner: Arc::new(FsStateMgrInner {
119                statepath,
120                lockfile,
121                lock_dropped_tx,
122                lock_dropped_rx,
123            }),
124        })
125    }
126    /// Like from_path_and_mistrust, but do not verify permissions.
127    ///
128    /// Testing only.
129    #[cfg(test)]
130    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
131        Self::from_path_and_mistrust(
132            path,
133            &fs_mistrust::Mistrust::new_dangerously_trust_everyone(),
134        )
135    }
136
137    /// Return a filename, relative to the top of this directory, to use for
138    /// storing data with `key`.
139    ///
140    /// See "Limitations" section on [`FsStateMgr`] for caveats.
141    fn rel_filename(&self, key: &str) -> PathBuf {
142        (sanitize_filename::sanitize(key) + ".json").into()
143    }
144    /// Return the top-level directory for this storage manager.
145    ///
146    /// (This is the same directory passed to
147    /// [`FsStateMgr::from_path_and_mistrust`].)
148    pub fn path(&self) -> &Path {
149        self.inner
150            .statepath
151            .as_path()
152            .parent()
153            .expect("No parent directory even after path.join?")
154    }
155
156    /// Remove old and/or obsolete items from this storage manager.
157    ///
158    /// Requires that we hold the lock.
159    fn clean(&self, now: SystemTime) {
160        for fname in clean::files_to_delete(self.inner.statepath.as_path(), now) {
161            info!("Deleting obsolete file {}", fname.anonymize_home());
162            if let Err(e) = std::fs::remove_file(&fname) {
163                warn_report!(e, "Unable to delete {}", fname.anonymize_home(),);
164            }
165        }
166    }
167
168    /// Operate using a `load_store::Target` for `key` in this state dir
169    fn with_load_store_target<T, F>(&self, key: &str, action: Action, f: F) -> Result<T>
170    where
171        F: FnOnce(load_store::Target<'_>) -> std::result::Result<T, ErrorSource>,
172    {
173        let rel_fname = self.rel_filename(key);
174        f(load_store::Target {
175            dir: &self.inner.statepath,
176            rel_fname: &rel_fname,
177        })
178        .map_err(|source| Error::new(source, action, self.err_resource(key)))
179    }
180
181    /// Return a `Resource` object representing the file with a given key.
182    fn err_resource(&self, key: &str) -> Resource {
183        Resource::File {
184            container: self.path().to_path_buf(),
185            file: PathBuf::from("state").join(self.rel_filename(key)),
186        }
187    }
188
189    /// Return a `Resource` object representing our lock file.
190    fn err_resource_lock(&self) -> Resource {
191        Resource::File {
192            container: self.path().to_path_buf(),
193            file: "state.lock".into(),
194        }
195    }
196
197    /// Return a handle which resolves when the file is unlocked
198    pub fn wait_for_unlock(&self) -> impl futures::Future<Output = ()> + Send + Sync + 'static {
199        self.inner.lock_dropped_rx.clone().map(|_| ())
200    }
201}
202
203impl StateMgr for FsStateMgr {
204    fn can_store(&self) -> bool {
205        let lockfile = self
206            .inner
207            .lockfile
208            .lock()
209            .expect("Poisoned lock on state lockfile");
210        lockfile.owns_lock()
211    }
212    fn try_lock(&self) -> Result<LockStatus> {
213        let mut lockfile = self
214            .inner
215            .lockfile
216            .lock()
217            .expect("Poisoned lock on state lockfile");
218        if lockfile.owns_lock() {
219            Ok(LockStatus::AlreadyHeld)
220        } else if lockfile
221            .try_lock()
222            .map_err(|e| Error::new(e, Action::Locking, self.err_resource_lock()))?
223        {
224            self.clean(SystemTime::now());
225            Ok(LockStatus::NewlyAcquired)
226        } else {
227            Ok(LockStatus::NoLock)
228        }
229    }
230    fn unlock(&self) -> Result<()> {
231        let mut lockfile = self
232            .inner
233            .lockfile
234            .lock()
235            .expect("Poisoned lock on state lockfile");
236        if lockfile.owns_lock() {
237            lockfile
238                .unlock()
239                .map_err(|e| Error::new(e, Action::Unlocking, self.err_resource_lock()))?;
240        }
241        Ok(())
242    }
243    fn load<D>(&self, key: &str) -> Result<Option<D>>
244    where
245        D: DeserializeOwned,
246    {
247        self.with_load_store_target(key, Action::Loading, |t| t.load())
248    }
249
250    fn store<S>(&self, key: &str, val: &S) -> Result<()>
251    where
252        S: Serialize,
253    {
254        if !self.can_store() {
255            return Err(Error::new(
256                ErrorSource::NoLock,
257                Action::Storing,
258                Resource::Manager,
259            ));
260        }
261
262        self.with_load_store_target(key, Action::Storing, |t| t.store(val))
263    }
264}
265
266#[cfg(all(test, not(miri) /* filesystem access */))]
267mod test {
268    // @@ begin test lint list maintained by maint/add_warning @@
269    #![allow(clippy::bool_assert_comparison)]
270    #![allow(clippy::clone_on_copy)]
271    #![allow(clippy::dbg_macro)]
272    #![allow(clippy::mixed_attributes_style)]
273    #![allow(clippy::print_stderr)]
274    #![allow(clippy::print_stdout)]
275    #![allow(clippy::single_char_pattern)]
276    #![allow(clippy::unwrap_used)]
277    #![allow(clippy::unchecked_duration_subtraction)]
278    #![allow(clippy::useless_vec)]
279    #![allow(clippy::needless_pass_by_value)]
280    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
281    use super::*;
282    use std::{collections::HashMap, time::Duration};
283
284    #[test]
285    fn simple() -> Result<()> {
286        let dir = tempfile::TempDir::new().unwrap();
287        let store = FsStateMgr::from_path(dir.path())?;
288
289        assert_eq!(store.try_lock()?, LockStatus::NewlyAcquired);
290        let stuff: HashMap<_, _> = vec![("hello".to_string(), "world".to_string())]
291            .into_iter()
292            .collect();
293        store.store("xyz", &stuff)?;
294
295        let stuff2: Option<HashMap<String, String>> = store.load("xyz")?;
296        let nothing: Option<HashMap<String, String>> = store.load("abc")?;
297
298        assert_eq!(Some(stuff), stuff2);
299        assert!(nothing.is_none());
300
301        assert_eq!(dir.path(), store.path());
302
303        drop(store); // Do this to release the fs lock.
304        let store = FsStateMgr::from_path(dir.path())?;
305        let stuff3: Option<HashMap<String, String>> = store.load("xyz")?;
306        assert_eq!(stuff2, stuff3);
307
308        let stuff4: HashMap<_, _> = vec![("greetings".to_string(), "humans".to_string())]
309            .into_iter()
310            .collect();
311
312        assert!(matches!(
313            store.store("xyz", &stuff4).unwrap_err().source(),
314            ErrorSource::NoLock
315        ));
316
317        assert_eq!(store.try_lock()?, LockStatus::NewlyAcquired);
318        store.store("xyz", &stuff4)?;
319
320        let stuff5: Option<HashMap<String, String>> = store.load("xyz")?;
321        assert_eq!(Some(stuff4), stuff5);
322
323        Ok(())
324    }
325
326    #[test]
327    fn clean_successful() -> Result<()> {
328        let dir = tempfile::TempDir::new().unwrap();
329        let statedir = dir.path().join("state");
330        let store = FsStateMgr::from_path(dir.path())?;
331
332        assert_eq!(store.try_lock()?, LockStatus::NewlyAcquired);
333        let fname = statedir.join("numbat.toml");
334        let fname2 = statedir.join("quoll.json");
335        std::fs::write(fname, "we no longer use toml files.").unwrap();
336        std::fs::write(fname2, "{}").unwrap();
337
338        let count = statedir.read_dir().unwrap().count();
339        assert_eq!(count, 3); // two files, one lock.
340
341        // Now we can make sure that "clean" actually removes the right file.
342        store.clean(SystemTime::now() + Duration::from_secs(365 * 86400));
343        let lst: Vec<_> = statedir.read_dir().unwrap().collect();
344        assert_eq!(lst.len(), 2); // one file, one lock.
345        assert!(lst
346            .iter()
347            .any(|ent| ent.as_ref().unwrap().file_name() == "quoll.json"));
348
349        Ok(())
350    }
351
352    #[cfg(target_family = "unix")]
353    #[test]
354    fn permissions() -> Result<()> {
355        use std::fs::Permissions;
356        use std::os::unix::fs::PermissionsExt;
357
358        let ro_dir = Permissions::from_mode(0o500);
359        let rw_dir = Permissions::from_mode(0o700);
360        let unusable = Permissions::from_mode(0o000);
361
362        let dir = tempfile::TempDir::new().unwrap();
363        let statedir = dir.path().join("state");
364        let store = FsStateMgr::from_path(dir.path())?;
365
366        assert_eq!(store.try_lock()?, LockStatus::NewlyAcquired);
367        let fname = statedir.join("numbat.toml");
368        let fname2 = statedir.join("quoll.json");
369        std::fs::write(fname, "we no longer use toml files.").unwrap();
370        std::fs::write(&fname2, "{}").unwrap();
371
372        // Make the store directory read-only and make sure that we can't delete from it.
373        std::fs::set_permissions(&statedir, ro_dir).unwrap();
374        store.clean(SystemTime::now() + Duration::from_secs(365 * 86400));
375        let lst: Vec<_> = statedir.read_dir().unwrap().collect();
376        if lst.len() == 2 {
377            // We must be root.  Don't do any more tests here.
378            return Ok(());
379        }
380        assert_eq!(lst.len(), 3); // We can't remove the file, but we didn't freak out. Great!
381                                  // Try failing to read a mode-0 file.
382        std::fs::set_permissions(&statedir, rw_dir).unwrap();
383        std::fs::set_permissions(fname2, unusable).unwrap();
384
385        let h: Result<Option<HashMap<String, u32>>> = store.load("quoll");
386        assert!(h.is_err());
387        assert!(matches!(h.unwrap_err().source(), ErrorSource::IoError(_)));
388
389        Ok(())
390    }
391
392    #[test]
393    fn locking() {
394        let dir = tempfile::TempDir::new().unwrap();
395        let store1 = FsStateMgr::from_path(dir.path()).unwrap();
396        let store2 = FsStateMgr::from_path(dir.path()).unwrap();
397
398        // Nobody has the lock; store1 will take it.
399        assert_eq!(store1.try_lock().unwrap(), LockStatus::NewlyAcquired);
400        assert_eq!(store1.try_lock().unwrap(), LockStatus::AlreadyHeld);
401        assert!(store1.can_store());
402
403        // store1 has the lock; store2 will try to get it and fail.
404        assert!(!store2.can_store());
405        assert_eq!(store2.try_lock().unwrap(), LockStatus::NoLock);
406        assert!(!store2.can_store());
407
408        // Store 1 will drop the lock.
409        store1.unlock().unwrap();
410        assert!(!store1.can_store());
411        assert!(!store2.can_store());
412
413        // Now store2 can get the lock.
414        assert_eq!(store2.try_lock().unwrap(), LockStatus::NewlyAcquired);
415        assert!(store2.can_store());
416        assert!(!store1.can_store());
417    }
418
419    #[test]
420    fn errors() {
421        let dir = tempfile::TempDir::new().unwrap();
422        let store = FsStateMgr::from_path(dir.path()).unwrap();
423
424        // file not found is not an error.
425        let nonesuch: Result<Option<String>> = store.load("Hello");
426        assert!(matches!(nonesuch, Ok(None)));
427
428        // bad utf8 is an error.
429        let file: PathBuf = ["state", "Hello.json"].iter().collect();
430        std::fs::write(dir.path().join(&file), b"hello world \x00\xff").unwrap();
431        let bad_utf8: Result<Option<String>> = store.load("Hello");
432        assert!(bad_utf8.is_err());
433        assert_eq!(
434            bad_utf8.unwrap_err().to_string(),
435            format!(
436                "IO error while loading persistent data on {} in {}",
437                file.to_string_lossy(),
438                dir.path().anonymize_home(),
439            ),
440        );
441    }
442}