Skip to main content

platform/
filesystem.rs

1//! `LocalFileSystem` — this machine's disk.
2
3use std::path::{Path, PathBuf};
4
5use base::interface::exec::{DirEntry, ExecError, FileSystem, Metadata};
6
7pub struct LocalFileSystem;
8
9/// Classify an io error the way the contract's three sentences require: a
10/// permission refusal is the operating system's policy talking, everything
11/// else is the target failing. Nothing here is ever `Unavailable` — the local
12/// disk is the one provider that cannot be out of reach.
13fn failed(path: &Path, e: std::io::Error) -> ExecError {
14    if e.kind() == std::io::ErrorKind::PermissionDenied {
15        ExecError::denied(format!("{}: {e}", path.display()))
16    } else {
17        ExecError::failed(format!("{}: {e}", path.display()))
18    }
19}
20
21#[async_trait::async_trait]
22impl FileSystem for LocalFileSystem {
23    async fn read(&self, path: &Path) -> Result<Vec<u8>, ExecError> {
24        tokio::fs::read(path).await.map_err(|e| failed(path, e))
25    }
26
27    async fn sha256(&self, path: &Path) -> Result<Option<String>, ExecError> {
28        use sha2::Digest;
29        use std::io::Read;
30        let owned = path.to_path_buf();
31        tokio::task::spawn_blocking(move || {
32            let mut file = std::fs::File::open(&owned)?;
33            let mut hasher = sha2::Sha256::new();
34            let mut chunk = vec![0u8; 64 * 1024];
35            loop {
36                match file.read(&mut chunk)? {
37                    0 => return Ok(Some(hex::encode(hasher.finalize()))),
38                    n => hasher.update(&chunk[..n]),
39                }
40            }
41        })
42        .await
43        .map_err(|e| ExecError::failed(format!("{}: {e}", path.display())))?
44        .map_err(|e| failed(path, e))
45    }
46
47    async fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), ExecError> {
48        tokio::fs::write(path, bytes)
49            .await
50            .map_err(|e| failed(path, e))
51    }
52
53    async fn write_not_following(&self, path: &Path, bytes: &[u8]) -> Result<(), ExecError> {
54        let (owned, bytes) = (path.to_path_buf(), bytes.to_vec());
55        let written = tokio::task::spawn_blocking(move || {
56            use std::io::Write;
57            let mut options = std::fs::OpenOptions::new();
58            options.write(true).create(true).truncate(true);
59            #[cfg(unix)]
60            std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, libc::O_NOFOLLOW);
61            options.open(&owned)?.write_all(&bytes)
62        })
63        .await
64        .map_err(|e| ExecError::failed(format!("{}: {e}", path.display())))?;
65        written.map_err(|e| failed(path, e))
66    }
67
68    #[cfg(unix)]
69    async fn write_resolved(
70        &self,
71        path: &Path,
72        bytes: &[u8],
73        create_parents: bool,
74    ) -> Result<(), ExecError> {
75        let (owned, bytes) = (path.to_path_buf(), bytes.to_vec());
76        tokio::task::spawn_blocking(move || {
77            unlinked::write(&owned, &bytes, create_parents).map_err(|e| {
78                if e.raw_os_error() == Some(libc::ELOOP) {
79                    ExecError::failed(format!(
80                        "{}: a symlink took the place of a directory or of the file \
81                         after the path was checked",
82                        owned.display()
83                    ))
84                } else {
85                    failed(&owned, e)
86                }
87            })
88        })
89        .await
90        .map_err(|e| ExecError::failed(format!("{}: {e}", path.display())))?
91    }
92
93    async fn create_dir_all(&self, path: &Path) -> Result<(), ExecError> {
94        tokio::fs::create_dir_all(path)
95            .await
96            .map_err(|e| failed(path, e))
97    }
98
99    async fn read_dir(&self, path: &Path) -> Result<Vec<DirEntry>, ExecError> {
100        let mut rd = tokio::fs::read_dir(path)
101            .await
102            .map_err(|e| failed(path, e))?;
103        let mut out = Vec::new();
104        while let Some(e) = rd.next_entry().await.map_err(|e| failed(path, e))? {
105            let is_dir = e
106                .file_type()
107                .await
108                .map(|t| t.is_dir())
109                .map_err(|e| failed(path, e))?;
110            out.push(DirEntry {
111                path: e.path(),
112                is_dir,
113            });
114        }
115        Ok(out)
116    }
117
118    async fn remove_dir_all(&self, path: &Path) -> Result<(), ExecError> {
119        tokio::fs::remove_dir_all(path)
120            .await
121            .map_err(|e| failed(path, e))
122    }
123
124    async fn metadata(&self, path: &Path) -> Result<Metadata, ExecError> {
125        // `symlink_metadata` rather than `metadata`, because the contract has
126        // an `is_symlink` field and `metadata` follows links — it can never
127        // report one.
128        let m = tokio::fs::symlink_metadata(path)
129            .await
130            .map_err(|e| failed(path, e))?;
131        Ok(Metadata {
132            is_dir: m.is_dir(),
133            is_file: m.is_file(),
134            is_symlink: m.file_type().is_symlink(),
135            len: m.len(),
136        })
137    }
138
139    async fn remove_file(&self, path: &Path) -> Result<(), ExecError> {
140        tokio::fs::remove_file(path)
141            .await
142            .map_err(|e| failed(path, e))
143    }
144
145    async fn rename(&self, from: &Path, to: &Path) -> Result<(), ExecError> {
146        tokio::fs::rename(from, to)
147            .await
148            .map_err(|e| failed(from, e))
149    }
150
151    async fn canonicalize(&self, path: &Path) -> Result<PathBuf, ExecError> {
152        tokio::fs::canonicalize(path)
153            .await
154            .map_err(|e| failed(path, e))
155    }
156
157    async fn read_link(&self, path: &Path) -> Result<PathBuf, ExecError> {
158        tokio::fs::read_link(path)
159            .await
160            .map_err(|e| failed(path, e))
161    }
162}
163
164/// Opening a path one directory at a time, from `/`, following no symlink.
165#[cfg(unix)]
166mod unlinked {
167    use std::ffi::{CString, OsStr};
168    use std::io::{Error, ErrorKind, Write};
169    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
170    use std::os::unix::ffi::OsStrExt;
171    use std::path::{Component, Path};
172
173    #[cfg(any(target_os = "linux", target_os = "android"))]
174    const DIR_FLAGS: libc::c_int = libc::O_PATH | libc::O_DIRECTORY;
175    #[cfg(not(any(target_os = "linux", target_os = "android")))]
176    const DIR_FLAGS: libc::c_int = libc::O_RDONLY | libc::O_DIRECTORY;
177
178    pub(super) fn write(path: &Path, bytes: &[u8], create_parents: bool) -> std::io::Result<()> {
179        let mut components = path.components();
180        if components.next() != Some(Component::RootDir) {
181            return Err(not_resolved(path));
182        }
183        let names = components
184            .map(|c| match c {
185                Component::Normal(name) => c_name(name),
186                _ => Err(not_resolved(path)),
187            })
188            .collect::<std::io::Result<Vec<_>>>()?;
189        let Some((file, dirs)) = names.split_last() else {
190            return Err(not_resolved(path));
191        };
192        let mut dir = open_at(libc::AT_FDCWD, c"/", DIR_FLAGS, 0)?;
193        for name in dirs {
194            let opened = open_at(dir.as_raw_fd(), name, DIR_FLAGS | libc::O_NOFOLLOW, 0)
195                .map_err(|e| as_link_refusal(&dir, name, e));
196            dir = match opened {
197                Err(e) if e.kind() == ErrorKind::NotFound && create_parents => {
198                    // SAFETY: `dir` is an open directory and `name` a NUL-terminated name.
199                    if unsafe { libc::mkdirat(dir.as_raw_fd(), name.as_ptr(), 0o777) } != 0 {
200                        let e = Error::last_os_error();
201                        if e.kind() != ErrorKind::AlreadyExists {
202                            return Err(e);
203                        }
204                    }
205                    open_at(dir.as_raw_fd(), name, DIR_FLAGS | libc::O_NOFOLLOW, 0)?
206                }
207                opened => opened?,
208            };
209        }
210        let flags = libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC | libc::O_NOFOLLOW;
211        let file = open_at(dir.as_raw_fd(), file, flags, 0o666)?;
212        std::fs::File::from(file).write_all(bytes)
213    }
214
215    fn open_at(
216        dir: libc::c_int,
217        name: &std::ffi::CStr,
218        flags: libc::c_int,
219        mode: libc::c_uint,
220    ) -> std::io::Result<OwnedFd> {
221        // SAFETY: `name` is NUL-terminated; a non-negative result is a
222        // descriptor nothing else owns.
223        let fd = unsafe { libc::openat(dir, name.as_ptr(), flags | libc::O_CLOEXEC, mode) };
224        if fd < 0 {
225            return Err(Error::last_os_error());
226        }
227        // SAFETY: as above.
228        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
229    }
230
231    /// macOS answers a directory open that meets a symlink with `ENOTDIR`;
232    /// told apart from a file on the way, it is `ELOOP` as on Linux.
233    fn as_link_refusal(dir: &OwnedFd, name: &std::ffi::CStr, e: Error) -> Error {
234        if e.raw_os_error() != Some(libc::ENOTDIR) {
235            return e;
236        }
237        // SAFETY: `stat` is plain old data the call fills in.
238        let mut stat: libc::stat = unsafe { std::mem::zeroed() };
239        // SAFETY: `dir` is open, `name` NUL-terminated, `stat` writable.
240        let found = unsafe {
241            libc::fstatat(
242                dir.as_raw_fd(),
243                name.as_ptr(),
244                &mut stat,
245                libc::AT_SYMLINK_NOFOLLOW,
246            )
247        };
248        if found == 0 && stat.st_mode & libc::S_IFMT == libc::S_IFLNK {
249            Error::from_raw_os_error(libc::ELOOP)
250        } else {
251            e
252        }
253    }
254
255    fn c_name(name: &OsStr) -> std::io::Result<CString> {
256        CString::new(name.as_bytes()).map_err(|e| Error::new(ErrorKind::InvalidInput, e))
257    }
258
259    fn not_resolved(path: &Path) -> Error {
260        Error::new(
261            ErrorKind::InvalidInput,
262            format!(
263                "{} is not an absolute path with its links resolved",
264                path.display()
265            ),
266        )
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[tokio::test]
275    async fn a_round_trip_through_the_contract_is_a_round_trip_through_the_disk() {
276        let dir = tempfile::tempdir().unwrap();
277        let fs = LocalFileSystem;
278        let f = dir.path().join("a/b/note.txt");
279        fs.create_dir_all(f.parent().unwrap()).await.unwrap();
280        fs.write_str(&f, "hello").await.unwrap();
281        assert_eq!(fs.read_to_string(&f).await.unwrap(), "hello");
282        assert!(fs.metadata(&f).await.unwrap().is_file);
283        assert_eq!(fs.read_dir(f.parent().unwrap()).await.unwrap().len(), 1);
284    }
285
286    #[cfg(unix)]
287    #[tokio::test]
288    async fn removing_a_symlink_removes_the_link_and_not_its_target() {
289        let dir = tempfile::tempdir().unwrap();
290        let target = dir.path().join("target.txt");
291        let link = dir.path().join("link.txt");
292        std::fs::write(&target, "kept").unwrap();
293        std::os::unix::fs::symlink(&target, &link).unwrap();
294        LocalFileSystem.remove_file(&link).await.unwrap();
295        assert!(std::fs::symlink_metadata(&link).is_err());
296        assert_eq!(std::fs::read_to_string(&target).unwrap(), "kept");
297    }
298
299    #[cfg(unix)]
300    #[tokio::test]
301    async fn a_resolved_write_follows_no_symlink_on_the_way() {
302        let dir = tempfile::tempdir().unwrap();
303        let root = std::fs::canonicalize(dir.path()).unwrap();
304        let (real, outside) = (root.join("real"), root.join("outside"));
305        std::fs::create_dir_all(&real).unwrap();
306        std::fs::create_dir_all(&outside).unwrap();
307        std::os::unix::fs::symlink(&outside, root.join("dir-link")).unwrap();
308        std::os::unix::fs::symlink(outside.join("f"), real.join("file-link")).unwrap();
309        let fs = LocalFileSystem;
310
311        fs.write_resolved(&real.join("a/b/new.txt"), b"x", true)
312            .await
313            .unwrap();
314        assert_eq!(std::fs::read(real.join("a/b/new.txt")).unwrap(), b"x");
315        assert!(fs
316            .write_resolved(&real.join("c/new.txt"), b"x", false)
317            .await
318            .is_err());
319        assert!(!real.join("c").exists());
320
321        for (through, created) in [
322            (root.join("dir-link/x"), outside.join("x")),
323            (root.join("dir-link/sub/x"), outside.join("sub")),
324            (real.join("file-link"), outside.join("f")),
325        ] {
326            let e = fs.write_resolved(&through, b"x", true).await.unwrap_err();
327            assert!(e.to_string().contains("symlink"), "{e}");
328            assert!(!created.exists(), "{}", through.display());
329        }
330    }
331
332    #[tokio::test]
333    async fn a_missing_file_is_the_target_failing_not_the_provider() {
334        let dir = tempfile::tempdir().unwrap();
335        let e = LocalFileSystem
336            .read(&dir.path().join("nope"))
337            .await
338            .unwrap_err();
339        assert!(
340            matches!(e, ExecError::Failed(_)),
341            "a host that saw `Unavailable` here would go looking for a broken \
342             execution environment: {e:?}"
343        );
344    }
345
346    /// The reason `metadata` does not use `tokio::fs::metadata`.
347    #[cfg(unix)]
348    #[tokio::test]
349    async fn a_symlink_reports_as_one() {
350        let dir = tempfile::tempdir().unwrap();
351        let target = dir.path().join("target");
352        let link = dir.path().join("link");
353        LocalFileSystem.write_str(&target, "x").await.unwrap();
354        std::os::unix::fs::symlink(&target, &link).unwrap();
355        assert!(LocalFileSystem.metadata(&link).await.unwrap().is_symlink);
356        assert_eq!(
357            LocalFileSystem.canonicalize(&link).await.unwrap(),
358            tokio::fs::canonicalize(&target).await.unwrap(),
359            "and canonicalize resolves it, which is why path safety has to run \
360             on the result rather than the argument"
361        );
362    }
363}