Skip to main content

plat/
guarded.rs

1// guarded -- the public file functions: a name with a scheme goes to its vfs provider
2// (vfs.rs), any other name is checked against the app's permissions (policy.rs) and then
3// handed to the OS call (win_sys.rs, linux_sys.rs, web_files.rs: the *_raw functions, which
4// the platform layer uses for its own system files)
5//
6// trash(path) moves into the trash (trash.rs) and counts as writing the path.
7// A refused path looks like a missing or unreadable one: 0 / None / false.
8// File and FileLock hold an OS file (also behind a folder mount: os_path) or a stream of a
9// mount (Provider::open: MemFs, Bundle, ZipFs, Overlay, Sub; other providers: the whole file,
10// read at the start and written back by sync and drop); a FileLock on a mount without OS
11// files holds inside this process only.
12// File::create_new and AtomicFile's sibling on a mount: Provider::create_new (the check and the
13// creation in one step: MemFs, Overlay, Sub, content://), else the OS's exclusive create of
14// os_path; a provider with neither has no File::create_new.
15// AtomicFile is write_file in pieces: a sibling (OS: OsAtomic of win_sys / linux_sys /
16// web_files / android_files; mounts: "NAME.tmp-.." in the mount) put in place by commit,
17// removed when dropped; content:// (no rename over a document): the bytes in memory, written
18// in place by commit (aio.rs builds the async writes and copies on it).
19
20use alloc::boxed::Box;
21use alloc::string::String;
22use alloc::sync::Arc;
23use alloc::vec::Vec;
24
25use rt::sync::SpinLock;
26
27use crate::policy::{fs_allowed, FS_READ, FS_WRITE};
28use crate::vfs::{self, Opened, Provider, Route, Stream};
29use crate::{OsFile, OsFileLock, FO_READ, FO_RW, FO_WRITE};
30
31/// 0 missing, 1 file, 2 directory  [plat_file_exists]
32pub fn file_exists(path: &str) -> u32 {
33    match vfs::route(path) {
34        Route::Os => if fs_allowed(path, FS_READ) { crate::file_exists_raw(path) } else { 0 },
35        Route::Vfs(p, rest) => p.kind(&rest),
36        Route::Bad => 0,
37    }
38}
39
40/// Some(0) only for a missing path, Some(1/2) for file/directory, None for other errors.  A
41/// folder mount answers for its OS file; other mounts have only their kind (0 for missing and
42/// for errors alike).
43pub fn file_exists_checked(path: &str) -> Option<u32> {
44    match vfs::route(path) {
45        Route::Os => if fs_allowed(path, FS_READ) { crate::file_exists_checked_raw(path) } else { None },
46        Route::Vfs(p, rest) => match p.os_path(&rest) {
47            Some(o) => file_exists_checked(&o),
48            None => Some(p.kind(&rest)),
49        },
50        Route::Bad => None,
51    }
52}
53
54/// create a directory and its missing parents; an existing directory is fine  [plat_mkdir]
55pub fn mkdir(path: &str) -> bool {
56    match vfs::route(path) {
57        Route::Os => fs_allowed(path, FS_WRITE) && crate::mkdir_raw(path),
58        Route::Vfs(p, rest) => p.mkdir(&rest),
59        Route::Bad => false,
60    }
61}
62
63/// a file or an empty directory  [plat_delete]
64pub fn delete(path: &str) -> bool {
65    match vfs::route(path) {
66        Route::Os => fs_allowed(path, FS_WRITE) && crate::delete_raw(path),
67        Route::Vfs(p, rest) => p.delete(&rest),
68        Route::Bad => false,
69    }
70}
71
72/// move a file or folder into the trash (Windows: the recycle bin; Linux: the freedesktop
73/// trash) -> false: it stays where it was, never deleted for good (trash.rs).  Counts as
74/// writing the path; a vfs name needs a folder mount.
75pub fn trash(path: &str) -> bool {
76    match vfs::route(path) {
77        Route::Os => fs_allowed(path, FS_WRITE) && crate::trash::trash_raw(path),
78        Route::Vfs(p, rest) => !rest.is_empty() && p.os_path(&rest).is_some_and(|o| fs_allowed(&o, FS_WRITE) && crate::trash::trash_raw(&o)),
79        Route::Bad => false,
80    }
81}
82
83/// rename, replacing an existing target (both names on the OS or in the same mount)  [plat_rename]
84pub fn rename(old: &str, new: &str) -> bool {
85    match (vfs::route(old), vfs::route(new)) {
86        (Route::Os, Route::Os) => fs_allowed(old, FS_WRITE) && fs_allowed(new, FS_WRITE) && crate::rename_raw(old, new),
87        (Route::Vfs(p, a), Route::Vfs(q, b)) if Arc::ptr_eq(&p, &q) => p.rename(&a, &b),
88        _ => false,
89    }
90}
91
92/// f(name, is_dir, size_lo) for every entry except "." and ".."  [plat_dir_list]
93pub fn dir_list(path: &str, f: &mut dyn FnMut(&str, bool, u32)) -> bool {
94    match vfs::route(path) {
95        Route::Os => fs_allowed(path, FS_READ) && crate::dir_list_raw(path, f),
96        Route::Vfs(p, rest) => p.list(&rest, &mut |n, d, s| f(n, d, s as u32)),
97        Route::Bad => false,
98    }
99}
100
101/// the contents of a file  [plat_file_read]
102pub fn read_file(path: &str) -> Option<Vec<u8>> {
103    match vfs::route(path) {
104        Route::Os => if fs_allowed(path, FS_READ) { crate::read_file_raw(path) } else { None },
105        Route::Vfs(p, rest) => p.read(&rest),
106        Route::Bad => None,
107    }
108}
109
110/// Write an exclusively created sibling, flush it, then replace path (a mount: its own way of
111/// replacing a file; missing folders are created). [plat_file_write]
112pub fn write_file(path: &str, data: &[u8]) -> bool {
113    match vfs::route(path) {
114        Route::Os => fs_allowed(path, FS_WRITE) && crate::write_file_raw(path, data),
115        Route::Vfs(p, rest) => !rest.is_empty() && p.write(&rest, data),
116        Route::Bad => false,
117    }
118}
119
120// ---------------------------------------------------------------- streaming files
121
122/// an open file (closed when dropped): an OS file, or a stream of a vfs mount
123pub struct File(Inner);
124
125enum Inner {
126    Os(OsFile),
127    Vfs(Box<dyn Stream>),
128}
129
130fn mode_ok(mode: u32) -> bool {
131    matches!(mode, FO_READ | FO_WRITE | FO_RW)
132}
133
134// a checked OS file
135fn os_open(path: &str, mode: u32) -> Option<File> {
136    if mode_ok(mode) && fs_allowed(path, if mode == FO_READ { FS_READ } else { FS_WRITE }) {
137        OsFile::open_raw(path, mode).map(|f| File(Inner::Os(f)))
138    } else {
139        None
140    }
141}
142
143/// (vfs) File::open on a provider: its own stream, its OS file, else the whole file
144pub(crate) fn open_in(p: &Arc<dyn Provider>, path: &str, mode: u32) -> Option<File> {
145    if !mode_ok(mode) {
146        return None;
147    }
148    match p.open(path, mode) {
149        Opened::File(s) => Some(File(Inner::Vfs(s))),
150        Opened::Refused => None,
151        Opened::Generic => match p.os_path(path) {
152            Some(o) => os_open(&o, mode),
153            None => whole(p, path, mode),
154        },
155    }
156}
157
158// what create_new_in made of a name
159pub(crate) enum Created {
160    New(File),
161    // taken or refused
162    Refused,
163    // no step that checks and creates at once: neither Provider::create_new nor the OS's
164    // exclusive create (no os_path, or a system without one: Android, the browser)
165    Unsupported,
166}
167
168/// (vfs) a file created on a provider where nothing was, in one step: the provider's own
169/// create_new, else the OS's exclusive create of its os_path
170pub(crate) fn create_new_in(p: &Arc<dyn Provider>, path: &str) -> Created {
171    if path.is_empty() {
172        return Created::Refused;
173    }
174    match p.create_new(path) {
175        Opened::File(s) => Created::New(File(Inner::Vfs(s))),
176        Opened::Refused => Created::Refused,
177        Opened::Generic => match p.os_path(path) {
178            #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
179            Some(o) => match fs_allowed(&o, FS_WRITE).then(|| OsFile::create_new_raw(&o)).flatten() {
180                Some(f) => Created::New(File(Inner::Os(f))),
181                None => Created::Refused,
182            },
183            _ => Created::Unsupported,
184        },
185    }
186}
187
188// a provider without streams: the file read at the start, written back by sync and drop
189fn whole(p: &Arc<dyn Provider>, path: &str, mode: u32) -> Option<File> {
190    let data = match (mode, p.kind(path)) {
191        (_, 2) => return None,
192        (FO_READ, 1) | (FO_RW, 1) => p.read(path)?,
193        (FO_READ, _) => return None,
194        _ => Vec::new(),
195    };
196    // FO_WRITE truncates, FO_RW creates; an existing file is written back once, which also
197    // tells a read-only provider
198    if mode != FO_READ && (path.is_empty() || !p.write(path, &data)) {
199        return None;
200    }
201    let back = (mode != FO_READ).then(|| (p.clone(), String::from(path)));
202    Some(File(Inner::Vfs(Box::new(Whole { writable: back.is_some(), back, st: SpinLock::new((data, false)) }))))
203}
204
205/// a file kept in memory: written back to back (provider, path) when it changed; without
206/// back read-only, or an anonymous file (open_temp on a mount without OS files)
207struct Whole {
208    back: Option<(Arc<dyn Provider>, String)>,
209    writable: bool,
210    // the bytes, changed since the last write-back
211    st: SpinLock<(Vec<u8>, bool)>,
212}
213
214impl Whole {
215    fn anon() -> Whole {
216        Whole { back: None, writable: true, st: SpinLock::new((Vec::new(), false)) }
217    }
218}
219
220impl Stream for Whole {
221    fn deferred(&self) -> bool {
222        true
223    }
224
225    fn read_at(&self, off: u64, buf: &mut [u8]) -> Option<usize> {
226        let g = self.st.lock();
227        let off = usize::try_from(off).unwrap_or(usize::MAX).min(g.0.len());
228        let n = (g.0.len() - off).min(buf.len());
229        buf[..n].copy_from_slice(&g.0[off..off + n]);
230        Some(n)
231    }
232
233    fn write_at(&self, off: u64, buf: &[u8]) -> Option<usize> {
234        if !self.writable {
235            return None;
236        }
237        let mut g = self.st.lock();
238        let n = vfs::write_vec(&mut g.0, off, buf)?;
239        g.1 = true;
240        Some(n)
241    }
242
243    fn size(&self) -> Option<u64> {
244        Some(self.st.lock().0.len() as u64)
245    }
246
247    fn set_len(&self, len: u64) -> bool {
248        if !self.writable {
249            return false;
250        }
251        let mut g = self.st.lock();
252        g.1 = true;
253        vfs::set_len_vec(&mut g.0, len)
254    }
255
256    fn sync(&self) -> bool {
257        let Some((p, path)) = &self.back else { return true };
258        let mut g = self.st.lock();
259        if !g.1 {
260            return true;
261        }
262        let ok = p.write(path, &g.0);
263        g.1 &= !ok;
264        ok
265    }
266}
267
268impl Drop for Whole {
269    fn drop(&mut self) {
270        self.sync();
271    }
272}
273
274// (fs.rs: Dir, set_file_times / set_file_mode) a File of an OS file opened there; the OS file
275// behind a File
276#[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
277impl File {
278    pub(crate) fn from_os(f: OsFile) -> File {
279        File(Inner::Os(f))
280    }
281
282    pub(crate) fn os(&self) -> Option<&OsFile> {
283        match &self.0 {
284            Inner::Os(f) => Some(f),
285            Inner::Vfs(_) => None,
286        }
287    }
288}
289
290impl File {
291    /// FO_READ (existing, read only), FO_WRITE (create / truncate), FO_RW (open or create);
292    /// on every mount (vfs.rs)
293    pub fn open(path: &str, mode: u32) -> Option<File> {
294        match vfs::route(path) {
295            Route::Os => os_open(path, mode),
296            Route::Vfs(p, rest) => open_in(&p, &rest, mode),
297            Route::Bad => None,
298        }
299    }
300
301    /// Create a named file exclusively; never open an existing path.  A mount: the
302    /// provider's own check-and-create (Provider::create_new: mem://, content://, overlays) or
303    /// the OS's of a folder mount; None on a provider with neither.
304    #[cfg(any(windows, target_os = "linux", target_vendor = "apple"))]
305    pub fn create_new(path: &str) -> Option<File> {
306        match vfs::route(path) {
307            Route::Os if fs_allowed(path, FS_WRITE) => OsFile::create_new_raw(path).map(|f| File(Inner::Os(f))),
308            Route::Vfs(p, rest) => match create_new_in(&p, &rest) {
309                Created::New(f) => Some(f),
310                _ => None,
311            },
312            _ => None,
313        }
314    }
315
316    /// a new file without a lasting name in dir (None = temp_dir) that disappears when it is
317    /// closed (also after a crash); a mount without OS files: a file in memory  [plat_file_open_temp]
318    pub fn open_temp(dir: Option<&str>) -> Option<File> {
319        let temp_os = |d: &str| if fs_allowed(d, FS_WRITE) { OsFile::open_temp_raw(Some(d)).map(|f| File(Inner::Os(f))) } else { None };
320        let Some(d) = dir else { return OsFile::open_temp_raw(None).map(|f| File(Inner::Os(f))) };
321        match vfs::route(d) {
322            Route::Os => temp_os(d),
323            Route::Vfs(p, rest) => match p.os_path(&rest) {
324                Some(o) => temp_os(&o),
325                None => (p.kind(&rest) == 2).then(|| File(Inner::Vfs(Box::new(Whole::anon())))),
326            },
327            Route::Bad => None,
328        }
329    }
330
331    /// bytes read at off (fewer at the end of the file), None on an error before any byte
332    pub fn read_at(&self, off: u64, buf: &mut [u8]) -> Option<usize> {
333        match &self.0 {
334            Inner::Os(f) => f.read_at(off, buf),
335            Inner::Vfs(s) => s.read_at(off, buf),
336        }
337    }
338
339    /// bytes written at off (the file grows as needed), None on an error before any byte
340    pub fn write_at(&self, off: u64, buf: &[u8]) -> Option<usize> {
341        match &self.0 {
342            Inner::Os(f) => f.write_at(off, buf),
343            Inner::Vfs(s) => s.write_at(off, buf),
344        }
345    }
346
347    /// (crash paths: plat::log) write_at without allocating or taking a lock: an OS file's write
348    /// call; a mount's stream and the browser's files (memory under a lock) -> None
349    pub(crate) fn write_at_crash(&self, off: u64, buf: &[u8]) -> Option<usize> {
350        #[cfg(target_arch = "wasm32")]
351        let _ = (off, buf);
352        match &self.0 {
353            #[cfg(not(target_arch = "wasm32"))]
354            Inner::Os(f) => f.write_at(off, buf),
355            _ => None,
356        }
357    }
358
359    pub fn size(&self) -> Option<u64> {
360        match &self.0 {
361            Inner::Os(f) => f.size(),
362            Inner::Vfs(s) => s.size(),
363        }
364    }
365
366    /// write cached data to the disk (a mount: where its readers find it)
367    pub fn sync(&self) -> bool {
368        match &self.0 {
369            Inner::Os(f) => f.sync(),
370            Inner::Vfs(s) => s.sync(),
371        }
372    }
373
374    /// cut or extend the file to `len` bytes
375    pub fn set_len(&self, len: u64) -> bool {
376        match &self.0 {
377            #[cfg(any(windows, target_os = "linux", target_os = "android", target_vendor = "apple"))]
378            Inner::Os(f) => f.set_len(len),
379            #[cfg(not(any(windows, target_os = "linux", target_os = "android", target_vendor = "apple")))]
380            Inner::Os(_) => false,
381            Inner::Vfs(s) => s.set_len(len),
382        }
383    }
384}
385
386impl Stream for File {
387    fn read_at(&self, off: u64, buf: &mut [u8]) -> Option<usize> {
388        File::read_at(self, off, buf)
389    }
390    fn write_at(&self, off: u64, buf: &[u8]) -> Option<usize> {
391        File::write_at(self, off, buf)
392    }
393    fn size(&self) -> Option<u64> {
394        File::size(self)
395    }
396    fn set_len(&self, len: u64) -> bool {
397        File::set_len(self, len)
398    }
399    fn sync(&self) -> bool {
400        File::sync(self)
401    }
402    fn deferred(&self) -> bool {
403        match &self.0 {
404            Inner::Vfs(s) => s.deferred(),
405            _ => false,
406        }
407    }
408}
409
410// ---------------------------------------------------------------- atomic streaming writes
411
412/// The streaming form of write_file: the bytes go into a sibling of the target, commit puts
413/// it in place in one step (readers see the old file or all of the new one); dropped without
414/// commit, the sibling is removed and the target is unchanged.  Checked and routed like
415/// write_file when it is created.  OS paths: an exclusive "NAME.tmp-PID-SEQ-TIME" beside the
416/// file, fsync and rename (Linux keeps the old file's access bits; the browser: in memory until
417/// commit).  Mounts: a "NAME.tmp-.." file of the mount, renamed by the provider (one without
418/// rename gets the whole file written); a provider whose rename cannot replace a file
419/// (`atomic_rename() == false`, content://) gets the bytes written in place at commit.
420pub struct AtomicFile(Option<AtomicInner>);
421
422enum AtomicInner {
423    Os(crate::OsAtomic),
424    Vfs { p: Arc<dyn Provider>, tmp: String, dst: String, f: Option<File> },
425    // a provider without rename over a file (content://): the bytes, written at commit
426    InPlace { p: Arc<dyn Provider>, dst: String, buf: SpinLock<Vec<u8>> },
427}
428
429static ATOMIC_SEQ: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
430
431impl AtomicFile {
432    /// a writer of path (None: refused, a folder, an invalid name, or the sibling could not be
433    /// created)
434    pub fn create(path: &str) -> Option<AtomicFile> {
435        match vfs::route(path) {
436            Route::Os => {
437                if !fs_allowed(path, FS_WRITE) {
438                    return None;
439                }
440                crate::OsAtomic::begin(path).map(|a| AtomicFile(Some(AtomicInner::Os(a))))
441            }
442            Route::Vfs(p, rest) => {
443                if rest.is_empty() || p.kind(&rest) == 2 {
444                    return None;
445                }
446                if !p.atomic_rename() {
447                    return Some(AtomicFile(Some(AtomicInner::InPlace { p, dst: rest, buf: SpinLock::new(Vec::new()) })));
448                }
449                if let Some((dir, _)) = rest.rsplit_once('/') {
450                    p.mkdir(dir);
451                }
452                for _ in 0..16 {
453                    let seq = ATOMIC_SEQ.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
454                    let tmp = alloc::format!("{rest}.tmp-{seq:x}-{:x}", crate::time_us() as u32);
455                    // the sibling is created where nothing was, in one step: an entry another
456                    // writer made under that name is never taken over (or removed by drop)
457                    let f = match create_new_in(&p, &tmp) {
458                        Created::New(f) => f,
459                        Created::Refused if p.kind(&tmp) != 0 => continue,
460                        Created::Refused => return None,
461                        // no such step: the name is this process's own (sequence and time)
462                        Created::Unsupported if p.kind(&tmp) != 0 => continue,
463                        Created::Unsupported => open_in(&p, &tmp, FO_WRITE)?,
464                    };
465                    return Some(AtomicFile(Some(AtomicInner::Vfs { p, tmp, dst: rest, f: Some(f) })));
466                }
467                None
468            }
469            Route::Bad => None,
470        }
471    }
472
473    /// bytes written at off (the file grows as needed), None on an error
474    pub fn write_at(&self, off: u64, data: &[u8]) -> Option<usize> {
475        match self.0.as_ref()? {
476            AtomicInner::Os(a) => a.write_at(off, data),
477            AtomicInner::Vfs { f, .. } => f.as_ref()?.write_at(off, data),
478            AtomicInner::InPlace { buf, .. } => vfs::write_vec(&mut buf.lock(), off, data),
479        }
480    }
481
482    /// put the written file in place -> false: the target is unchanged, the sibling gone
483    pub fn commit(mut self) -> bool {
484        match self.0.take() {
485            None => false,
486            Some(AtomicInner::Os(a)) => a.commit(),
487            Some(AtomicInner::Vfs { p, tmp, dst, f }) => {
488                let ok = f.is_some_and(|f| f.sync());
489                // a provider without rename: the whole file under the new name
490                let ok = ok && (p.rename(&tmp, &dst) || p.read(&tmp).is_some_and(|d| p.write(&dst, &d)));
491                if p.kind(&tmp) == 1 {
492                    p.delete(&tmp);
493                }
494                ok
495            }
496            Some(AtomicInner::InPlace { p, dst, buf }) => p.write(&dst, &buf.lock()),
497        }
498    }
499}
500
501impl Drop for AtomicFile {
502    fn drop(&mut self) {
503        if let Some(AtomicInner::Vfs { p, tmp, f, .. }) = &mut self.0 {
504            drop(f.take());
505            p.delete(tmp); // not committed: the sibling goes (an OsAtomic removes its own)
506        }
507    }
508}
509
510// the FileLocks of mounts without OS files: provider (address) and path
511static VFS_LOCKS: SpinLock<Vec<(usize, String)>> = SpinLock::new(Vec::new());
512
513/// Nonblocking exclusive sidecar lock; drop releases it.  All cooperating writers must lock
514/// the same path before checking and replacing data.  OS files: across processes (Windows: an
515/// exclusive handle, Linux: flock); a mount without OS files: inside this process.
516pub struct FileLock(LockInner);
517
518enum LockInner {
519    Os { _lock: OsFileLock },
520    Vfs { p: Arc<dyn Provider>, path: String },
521}
522
523impl FileLock {
524    /// Open or create without truncating. None means busy, invalid path, refused or I/O failure.
525    pub fn acquire(path: &str) -> Option<Self> {
526        let os = |o: &str| if fs_allowed(o, FS_WRITE) { OsFileLock::acquire_raw(o).map(|l| FileLock(LockInner::Os { _lock: l })) } else { None };
527        let (p, rest) = match vfs::route(path) {
528            Route::Os => return os(path),
529            Route::Vfs(p, rest) => match p.os_path(&rest) {
530                Some(o) => return os(&o),
531                None => (p, rest),
532            },
533            Route::Bad => return None,
534        };
535        let key = Arc::as_ptr(&p) as *const () as usize;
536        let mut g = VFS_LOCKS.lock();
537        if rest.is_empty() || g.iter().any(|(k, n)| *k == key && *n == rest) {
538            return None;
539        }
540        match p.kind(&rest) {
541            1 => {}
542            0 if p.write(&rest, &[]) => {}
543            _ => return None,
544        }
545        g.push((key, rest.clone()));
546        Some(FileLock(LockInner::Vfs { p, path: rest }))
547    }
548}
549
550impl Drop for FileLock {
551    fn drop(&mut self) {
552        if let LockInner::Vfs { p, path } = &self.0 {
553            let key = Arc::as_ptr(p) as *const () as usize;
554            VFS_LOCKS.lock().retain(|(k, n)| !(*k == key && n == path));
555        }
556    }
557}