1
//! Filesystem + JSON implementation of StateMgr.
2

            
3
#![forbid(unsafe_code)] // if you remove this, enable (or write) miri tests (git grep miri)
4

            
5
mod clean;
6

            
7
use crate::err::{Action, ErrorSource, Resource};
8
use crate::load_store;
9
use crate::{Error, LockStatus, Result, StateMgr};
10
use fs_mistrust::anon_home::PathExt as _;
11
use fs_mistrust::CheckedDir;
12
use futures::FutureExt;
13
use oneshot_fused_workaround as oneshot;
14
use serde::{de::DeserializeOwned, Serialize};
15
use std::path::{Path, PathBuf};
16
use std::sync::{Arc, Mutex};
17
use std::time::SystemTime;
18
use tor_error::warn_report;
19
use 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)]
48
pub struct FsStateMgr {
49
    /// Inner reference-counted object.
50
    inner: Arc<FsStateMgrInner>,
51
}
52

            
53
/// Inner reference-counted object, used by `FsStateMgr`.
54
#[derive(Debug)]
55
struct 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

            
71
impl 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
34
    pub fn from_path_and_mistrust<P: AsRef<Path>>(
79
34
        path: P,
80
34
        mistrust: &fs_mistrust::Mistrust,
81
34
    ) -> Result<Self> {
82
34
        let path = path.as_ref();
83
34
        let dir = path.join("state");
84

            
85
34
        let statepath = mistrust
86
34
            .verifier()
87
34
            .check_content()
88
34
            .make_secure_dir(&dir)
89
34
            .map_err(|e| {
90
                Error::new(
91
                    e,
92
                    Action::Initializing,
93
                    Resource::Directory { dir: dir.clone() },
94
                )
95
34
            })?;
96
34
        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
34
        })?;
103

            
104
34
        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
34
        })?);
114

            
115
34
        let (lock_dropped_tx, lock_dropped_rx) = oneshot::channel();
116
34
        let lock_dropped_rx = lock_dropped_rx.shared();
117
34
        Ok(FsStateMgr {
118
34
            inner: Arc::new(FsStateMgrInner {
119
34
                statepath,
120
34
                lockfile,
121
34
                lock_dropped_tx,
122
34
                lock_dropped_rx,
123
34
            }),
124
34
        })
125
34
    }
126
    /// Like from_path_and_mistrust, but do not verify permissions.
127
    ///
128
    /// Testing only.
129
    #[cfg(test)]
130
14
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
131
14
        Self::from_path_and_mistrust(
132
14
            path,
133
14
            &fs_mistrust::Mistrust::new_dangerously_trust_everyone(),
134
14
        )
135
14
    }
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
1458
    fn rel_filename(&self, key: &str) -> PathBuf {
142
1458
        (sanitize_filename::sanitize(key) + ".json").into()
143
1458
    }
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
184
    pub fn path(&self) -> &Path {
149
184
        self.inner
150
184
            .statepath
151
184
            .as_path()
152
184
            .parent()
153
184
            .expect("No parent directory even after path.join?")
154
184
    }
155

            
156
    /// Remove old and/or obsolete items from this storage manager.
157
    ///
158
    /// Requires that we hold the lock.
159
196
    fn clean(&self, now: SystemTime) {
160
196
        for fname in clean::files_to_delete(self.inner.statepath.as_path(), now) {
161
4
            info!("Deleting obsolete file {}", fname.anonymize_home());
162
4
            if let Err(e) = std::fs::remove_file(&fname) {
163
                warn_report!(e, "Unable to delete {}", fname.anonymize_home(),);
164
4
            }
165
        }
166
196
    }
167

            
168
    /// Operate using a `load_store::Target` for `key` in this state dir
169
76
    fn with_load_store_target<T, F>(&self, key: &str, action: Action, f: F) -> Result<T>
170
76
    where
171
76
        F: FnOnce(load_store::Target<'_>) -> std::result::Result<T, ErrorSource>,
172
76
    {
173
76
        let rel_fname = self.rel_filename(key);
174
76
        f(load_store::Target {
175
76
            dir: &self.inner.statepath,
176
76
            rel_fname: &rel_fname,
177
76
        })
178
76
        .map_err(|source| Error::new(source, action, self.err_resource(key)))
179
76
    }
180

            
181
    /// Return a `Resource` object representing the file with a given key.
182
92
    fn err_resource(&self, key: &str) -> Resource {
183
92
        Resource::File {
184
92
            container: self.path().to_path_buf(),
185
92
            file: PathBuf::from("state").join(self.rel_filename(key)),
186
92
        }
187
92
    }
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

            
203
impl StateMgr for FsStateMgr {
204
1100
    fn can_store(&self) -> bool {
205
1100
        let lockfile = self
206
1100
            .inner
207
1100
            .lockfile
208
1100
            .lock()
209
1100
            .expect("Poisoned lock on state lockfile");
210
1100
        lockfile.owns_lock()
211
1100
    }
212
466
    fn try_lock(&self) -> Result<LockStatus> {
213
466
        let mut lockfile = self
214
466
            .inner
215
466
            .lockfile
216
466
            .lock()
217
466
            .expect("Poisoned lock on state lockfile");
218
466
        if lockfile.owns_lock() {
219
272
            Ok(LockStatus::AlreadyHeld)
220
194
        } else if lockfile
221
194
            .try_lock()
222
194
            .map_err(|e| Error::new(e, Action::Locking, self.err_resource_lock()))?
223
        {
224
192
            self.clean(SystemTime::now());
225
192
            Ok(LockStatus::NewlyAcquired)
226
        } else {
227
2
            Ok(LockStatus::NoLock)
228
        }
229
466
    }
230
2
    fn unlock(&self) -> Result<()> {
231
2
        let mut lockfile = self
232
2
            .inner
233
2
            .lockfile
234
2
            .lock()
235
2
            .expect("Poisoned lock on state lockfile");
236
2
        if lockfile.owns_lock() {
237
2
            lockfile
238
2
                .unlock()
239
2
                .map_err(|e| Error::new(e, Action::Unlocking, self.err_resource_lock()))?;
240
        }
241
2
        Ok(())
242
2
    }
243
48
    fn load<D>(&self, key: &str) -> Result<Option<D>>
244
48
    where
245
48
        D: DeserializeOwned,
246
48
    {
247
48
        self.with_load_store_target(key, Action::Loading, |t| t.load())
248
48
    }
249

            
250
34
    fn store<S>(&self, key: &str, val: &S) -> Result<()>
251
34
    where
252
34
        S: Serialize,
253
34
    {
254
34
        if !self.can_store() {
255
6
            return Err(Error::new(
256
6
                ErrorSource::NoLock,
257
6
                Action::Storing,
258
6
                Resource::Manager,
259
6
            ));
260
28
        }
261
28

            
262
28
        self.with_load_store_target(key, Action::Storing, |t| t.store(val))
263
34
    }
264
}
265

            
266
#[cfg(all(test, not(miri) /* filesystem access */))]
267
mod 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
}