1use 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
31pub 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
40pub 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
54pub 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
63pub 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
72pub 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
83pub 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
92pub 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
101pub 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
110pub 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
120pub 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
134fn 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
143pub(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
158pub(crate) enum Created {
160 New(File),
161 Refused,
163 Unsupported,
166}
167
168pub(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
188fn 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 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
205struct Whole {
208 back: Option<(Arc<dyn Provider>, String)>,
209 writable: bool,
210 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#[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 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 #[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 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 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 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 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 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 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
410pub 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 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 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 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 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 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 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 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); }
507 }
508}
509
510static VFS_LOCKS: SpinLock<Vec<(usize, String)>> = SpinLock::new(Vec::new());
512
513pub struct FileLock(LockInner);
517
518enum LockInner {
519 Os { _lock: OsFileLock },
520 Vfs { p: Arc<dyn Provider>, path: String },
521}
522
523impl FileLock {
524 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}