Skip to main content

coqui_access_kit/file/
mod.rs

1//! Private files: written whole and atomically, read within a bound, told apart by stamp;
2//! and [`FileTable`], a [`Table`](crate::Table) kept in one of them in a serde format the
3//! caller supplies through a [`Codec`].
4//!
5//! Needs the `file` feature.
6
7mod source;
8mod table;
9
10pub use source::{FileSource, Source};
11pub use table::{Codec, CodecError, DEFAULT_MAX_BYTES, FileTable};
12
13use std::fs::{self, OpenOptions};
14use std::io::{ErrorKind, Read, Write};
15use std::path::{Path, PathBuf};
16use std::sync::atomic::{AtomicU64, Ordering};
17use std::time::{SystemTime, UNIX_EPOCH};
18
19/// Which writing of a file is there: told apart from any other by when it was written, how
20/// long it is and, on Unix, which inode it is (every writing here is a new file put in the
21/// old one's place, and a coarse clock alone cannot tell two apart).
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct Stamp {
24    modified: Option<SystemTime>,
25    length: u64,
26    inode: u64,
27}
28
29/// The stamp of the file at `path`; `None` when there is no such file.
30///
31/// # Errors
32///
33/// Returns an error when the file's metadata cannot be read for another reason.
34pub fn stamp(path: &Path) -> Result<Option<Stamp>, String> {
35    match fs::metadata(path) {
36        Ok(metadata) => {
37            #[cfg(unix)]
38            let inode = std::os::unix::fs::MetadataExt::ino(&metadata);
39            #[cfg(not(unix))]
40            let inode = 0;
41            Ok(Some(Stamp {
42                modified: metadata.modified().ok(),
43                length: metadata.len(),
44                inode,
45            }))
46        }
47        Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
48        Err(_) => Err("file metadata is unavailable".to_owned()),
49    }
50}
51
52/// Reads the UTF-8 text of the file at `path`, refusing more than `max_bytes`. `None` when
53/// there is no such file: nothing has been kept yet.
54///
55/// # Errors
56///
57/// Returns an error, without the path, when the file is unreadable, too long or not UTF-8.
58pub fn read_bounded(path: &Path, max_bytes: usize) -> Result<Option<String>, String> {
59    let file = match fs::File::open(path) {
60        Ok(file) => file,
61        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),
62        Err(_) => return Err("file cannot be read".to_owned()),
63    };
64    let mut bytes = Vec::new();
65    file.take(max_bytes as u64 + 1)
66        .read_to_end(&mut bytes)
67        .map_err(|_| "file cannot be read".to_owned())?;
68    if bytes.len() > max_bytes {
69        return Err(format!("file exceeds the {max_bytes} byte limit"));
70    }
71    String::from_utf8(bytes)
72        .map(Some)
73        .map_err(|_| "file is not UTF-8".to_owned())
74}
75
76/// Writes `bytes` as the file at `path`: beside it first and then in its place, so it is
77/// never there half written, readable by its owner alone (`0600` on Unix), and never
78/// written through a link or into a file someone else can read.
79///
80/// # Errors
81///
82/// Returns an error when the file cannot be created, written or put in place.
83pub fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
84    static WRITTEN: AtomicU64 = AtomicU64::new(0);
85    let nth = WRITTEN.fetch_add(1, Ordering::Relaxed);
86    let moment = SystemTime::now()
87        .duration_since(UNIX_EPOCH)
88        .map_or(0, |since| since.as_nanos());
89    let mut beside = path.as_os_str().to_owned();
90    beside.push(format!(".{}.{moment:x}.{nth}.new", std::process::id()));
91    let beside = PathBuf::from(beside);
92    let mut options = OpenOptions::new();
93    options.write(true).create_new(true);
94    #[cfg(unix)]
95    {
96        use std::os::unix::fs::OpenOptionsExt;
97        options.mode(0o600);
98    }
99    options
100        .open(&beside)
101        .and_then(|mut file| {
102            file.write_all(bytes)?;
103            file.sync_all()
104        })
105        .and_then(|()| fs::rename(&beside, path))
106        .map_err(|error| {
107            let _ = fs::remove_file(&beside);
108            format!("{}: could not be written: {error}", path.display())
109        })
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn files_are_written_whole_private_and_read_back_within_a_bound() {
118        let directory = tempfile::tempdir().unwrap();
119        let file = directory.path().join("kept.dat");
120        assert_eq!(read_bounded(&file, 100), Ok(None));
121        assert_eq!(stamp(&file), Ok(None));
122        write_private(&file, b"first").unwrap();
123        write_private(&file, b"second, and longer").unwrap();
124        assert_eq!(
125            read_bounded(&file, 100),
126            Ok(Some("second, and longer".to_owned()))
127        );
128        assert!(read_bounded(&file, 5).is_err());
129        assert!(stamp(&file).unwrap().is_some());
130        #[cfg(unix)]
131        {
132            use std::os::unix::fs::PermissionsExt;
133            let mode = fs::metadata(&file).unwrap().permissions().mode();
134            assert_eq!(mode & 0o777, 0o600);
135            for _ in 0..20 {
136                write_private(&file, b"one").unwrap();
137                let first = stamp(&file).unwrap();
138                write_private(&file, b"two").unwrap();
139                assert_ne!(stamp(&file).unwrap(), first);
140            }
141        }
142        assert_eq!(fs::read_dir(directory.path()).unwrap().count(), 1);
143        let nowhere = directory.path().join("missing").join("kept.dat");
144        assert!(write_private(&nowhere, b"x").is_err());
145    }
146
147    #[test]
148    fn invalid_utf8_is_refused() {
149        let directory = tempfile::tempdir().unwrap();
150        let file = directory.path().join("bad");
151        fs::write(&file, [0xff, 0xfe]).unwrap();
152        assert!(read_bounded(&file, 10).is_err());
153    }
154}