1 #![deny(unsafe_op_in_unsafe_fn)]
2 
3 use super::fd::WasiFd;
4 use crate::ffi::{CStr, CString, OsStr, OsString};
5 use crate::fmt;
6 use crate::io::{self, IoSlice, IoSliceMut, SeekFrom};
7 use crate::iter;
8 use crate::mem::{self, ManuallyDrop};
9 use crate::os::raw::c_int;
10 use crate::os::wasi::ffi::{OsStrExt, OsStringExt};
11 use crate::os::wasi::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd};
12 use crate::path::{Path, PathBuf};
13 use crate::ptr;
14 use crate::sync::Arc;
15 use crate::sys::time::SystemTime;
16 use crate::sys::unsupported;
17 use crate::sys_common::{AsInner, FromInner, IntoInner};
18 
19 pub use crate::sys_common::fs::try_exists;
20 
21 pub struct File {
22     fd: WasiFd,
23 }
24 
25 #[derive(Clone)]
26 pub struct FileAttr {
27     meta: wasi::Filestat,
28 }
29 
30 pub struct ReadDir {
31     inner: Arc<ReadDirInner>,
32     cookie: Option<wasi::Dircookie>,
33     buf: Vec<u8>,
34     offset: usize,
35     cap: usize,
36 }
37 
38 struct ReadDirInner {
39     root: PathBuf,
40     dir: File,
41 }
42 
43 pub struct DirEntry {
44     meta: wasi::Dirent,
45     name: Vec<u8>,
46     inner: Arc<ReadDirInner>,
47 }
48 
49 #[derive(Clone, Debug, Default)]
50 pub struct OpenOptions {
51     read: bool,
52     write: bool,
53     append: bool,
54     dirflags: wasi::Lookupflags,
55     fdflags: wasi::Fdflags,
56     oflags: wasi::Oflags,
57     rights_base: Option<wasi::Rights>,
58     rights_inheriting: Option<wasi::Rights>,
59 }
60 
61 #[derive(Clone, PartialEq, Eq, Debug)]
62 pub struct FilePermissions {
63     readonly: bool,
64 }
65 
66 #[derive(PartialEq, Eq, Hash, Debug, Copy, Clone)]
67 pub struct FileType {
68     bits: wasi::Filetype,
69 }
70 
71 #[derive(Debug)]
72 pub struct DirBuilder {}
73 
74 impl FileAttr {
size(&self) -> u6475     pub fn size(&self) -> u64 {
76         self.meta.size
77     }
78 
perm(&self) -> FilePermissions79     pub fn perm(&self) -> FilePermissions {
80         // not currently implemented in wasi yet
81         FilePermissions { readonly: false }
82     }
83 
file_type(&self) -> FileType84     pub fn file_type(&self) -> FileType {
85         FileType { bits: self.meta.filetype }
86     }
87 
modified(&self) -> io::Result<SystemTime>88     pub fn modified(&self) -> io::Result<SystemTime> {
89         Ok(SystemTime::from_wasi_timestamp(self.meta.mtim))
90     }
91 
accessed(&self) -> io::Result<SystemTime>92     pub fn accessed(&self) -> io::Result<SystemTime> {
93         Ok(SystemTime::from_wasi_timestamp(self.meta.atim))
94     }
95 
created(&self) -> io::Result<SystemTime>96     pub fn created(&self) -> io::Result<SystemTime> {
97         Ok(SystemTime::from_wasi_timestamp(self.meta.ctim))
98     }
99 
as_wasi(&self) -> &wasi::Filestat100     pub fn as_wasi(&self) -> &wasi::Filestat {
101         &self.meta
102     }
103 }
104 
105 impl FilePermissions {
readonly(&self) -> bool106     pub fn readonly(&self) -> bool {
107         self.readonly
108     }
109 
set_readonly(&mut self, readonly: bool)110     pub fn set_readonly(&mut self, readonly: bool) {
111         self.readonly = readonly;
112     }
113 }
114 
115 impl FileType {
is_dir(&self) -> bool116     pub fn is_dir(&self) -> bool {
117         self.bits == wasi::FILETYPE_DIRECTORY
118     }
119 
is_file(&self) -> bool120     pub fn is_file(&self) -> bool {
121         self.bits == wasi::FILETYPE_REGULAR_FILE
122     }
123 
is_symlink(&self) -> bool124     pub fn is_symlink(&self) -> bool {
125         self.bits == wasi::FILETYPE_SYMBOLIC_LINK
126     }
127 
bits(&self) -> wasi::Filetype128     pub fn bits(&self) -> wasi::Filetype {
129         self.bits
130     }
131 }
132 
133 impl ReadDir {
new(dir: File, root: PathBuf) -> ReadDir134     fn new(dir: File, root: PathBuf) -> ReadDir {
135         ReadDir {
136             cookie: Some(0),
137             buf: vec![0; 128],
138             offset: 0,
139             cap: 0,
140             inner: Arc::new(ReadDirInner { dir, root }),
141         }
142     }
143 }
144 
145 impl fmt::Debug for ReadDir {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result146     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147         f.debug_struct("ReadDir").finish_non_exhaustive()
148     }
149 }
150 
151 impl Iterator for ReadDir {
152     type Item = io::Result<DirEntry>;
153 
next(&mut self) -> Option<io::Result<DirEntry>>154     fn next(&mut self) -> Option<io::Result<DirEntry>> {
155         loop {
156             // If we've reached the capacity of our buffer then we need to read
157             // some more from the OS, otherwise we pick up at our old offset.
158             let offset = if self.offset == self.cap {
159                 let cookie = self.cookie.take()?;
160                 match self.inner.dir.fd.readdir(&mut self.buf, cookie) {
161                     Ok(bytes) => self.cap = bytes,
162                     Err(e) => return Some(Err(e)),
163                 }
164                 self.offset = 0;
165                 self.cookie = Some(cookie);
166 
167                 // If we didn't actually read anything, this is in theory the
168                 // end of the directory.
169                 if self.cap == 0 {
170                     self.cookie = None;
171                     return None;
172                 }
173 
174                 0
175             } else {
176                 self.offset
177             };
178             let data = &self.buf[offset..self.cap];
179 
180             // If we're not able to read a directory entry then that means it
181             // must have been truncated at the end of the buffer, so reset our
182             // offset so we can go back and reread into the buffer, picking up
183             // where we last left off.
184             let dirent_size = mem::size_of::<wasi::Dirent>();
185             if data.len() < dirent_size {
186                 assert!(self.cookie.is_some());
187                 assert!(self.buf.len() >= dirent_size);
188                 self.offset = self.cap;
189                 continue;
190             }
191             let (dirent, data) = data.split_at(dirent_size);
192             let dirent = unsafe { ptr::read_unaligned(dirent.as_ptr() as *const wasi::Dirent) };
193 
194             // If the file name was truncated, then we need to reinvoke
195             // `readdir` so we truncate our buffer to start over and reread this
196             // descriptor. Note that if our offset is 0 that means the file name
197             // is massive and we need a bigger buffer.
198             if data.len() < dirent.d_namlen as usize {
199                 if offset == 0 {
200                     let amt_to_add = self.buf.capacity();
201                     self.buf.extend(iter::repeat(0).take(amt_to_add));
202                 }
203                 assert!(self.cookie.is_some());
204                 self.offset = self.cap;
205                 continue;
206             }
207             self.cookie = Some(dirent.d_next);
208             self.offset = offset + dirent_size + dirent.d_namlen as usize;
209 
210             let name = &data[..(dirent.d_namlen as usize)];
211 
212             // These names are skipped on all other platforms, so let's skip
213             // them here too
214             if name == b"." || name == b".." {
215                 continue;
216             }
217 
218             return Some(Ok(DirEntry {
219                 meta: dirent,
220                 name: name.to_vec(),
221                 inner: self.inner.clone(),
222             }));
223         }
224     }
225 }
226 
227 impl DirEntry {
path(&self) -> PathBuf228     pub fn path(&self) -> PathBuf {
229         let name = OsStr::from_bytes(&self.name);
230         self.inner.root.join(name)
231     }
232 
file_name(&self) -> OsString233     pub fn file_name(&self) -> OsString {
234         OsString::from_vec(self.name.clone())
235     }
236 
metadata(&self) -> io::Result<FileAttr>237     pub fn metadata(&self) -> io::Result<FileAttr> {
238         metadata_at(&self.inner.dir.fd, 0, OsStr::from_bytes(&self.name).as_ref())
239     }
240 
file_type(&self) -> io::Result<FileType>241     pub fn file_type(&self) -> io::Result<FileType> {
242         Ok(FileType { bits: self.meta.d_type })
243     }
244 
ino(&self) -> wasi::Inode245     pub fn ino(&self) -> wasi::Inode {
246         self.meta.d_ino
247     }
248 }
249 
250 impl OpenOptions {
new() -> OpenOptions251     pub fn new() -> OpenOptions {
252         let mut base = OpenOptions::default();
253         base.dirflags = wasi::LOOKUPFLAGS_SYMLINK_FOLLOW;
254         return base;
255     }
256 
read(&mut self, read: bool)257     pub fn read(&mut self, read: bool) {
258         self.read = read;
259     }
260 
write(&mut self, write: bool)261     pub fn write(&mut self, write: bool) {
262         self.write = write;
263     }
264 
truncate(&mut self, truncate: bool)265     pub fn truncate(&mut self, truncate: bool) {
266         self.oflag(wasi::OFLAGS_TRUNC, truncate);
267     }
268 
create(&mut self, create: bool)269     pub fn create(&mut self, create: bool) {
270         self.oflag(wasi::OFLAGS_CREAT, create);
271     }
272 
create_new(&mut self, create_new: bool)273     pub fn create_new(&mut self, create_new: bool) {
274         self.oflag(wasi::OFLAGS_EXCL, create_new);
275         self.oflag(wasi::OFLAGS_CREAT, create_new);
276     }
277 
directory(&mut self, directory: bool)278     pub fn directory(&mut self, directory: bool) {
279         self.oflag(wasi::OFLAGS_DIRECTORY, directory);
280     }
281 
oflag(&mut self, bit: wasi::Oflags, set: bool)282     fn oflag(&mut self, bit: wasi::Oflags, set: bool) {
283         if set {
284             self.oflags |= bit;
285         } else {
286             self.oflags &= !bit;
287         }
288     }
289 
append(&mut self, append: bool)290     pub fn append(&mut self, append: bool) {
291         self.append = append;
292         self.fdflag(wasi::FDFLAGS_APPEND, append);
293     }
294 
dsync(&mut self, set: bool)295     pub fn dsync(&mut self, set: bool) {
296         self.fdflag(wasi::FDFLAGS_DSYNC, set);
297     }
298 
nonblock(&mut self, set: bool)299     pub fn nonblock(&mut self, set: bool) {
300         self.fdflag(wasi::FDFLAGS_NONBLOCK, set);
301     }
302 
rsync(&mut self, set: bool)303     pub fn rsync(&mut self, set: bool) {
304         self.fdflag(wasi::FDFLAGS_RSYNC, set);
305     }
306 
sync(&mut self, set: bool)307     pub fn sync(&mut self, set: bool) {
308         self.fdflag(wasi::FDFLAGS_SYNC, set);
309     }
310 
fdflag(&mut self, bit: wasi::Fdflags, set: bool)311     fn fdflag(&mut self, bit: wasi::Fdflags, set: bool) {
312         if set {
313             self.fdflags |= bit;
314         } else {
315             self.fdflags &= !bit;
316         }
317     }
318 
fs_rights_base(&mut self, rights: wasi::Rights)319     pub fn fs_rights_base(&mut self, rights: wasi::Rights) {
320         self.rights_base = Some(rights);
321     }
322 
fs_rights_inheriting(&mut self, rights: wasi::Rights)323     pub fn fs_rights_inheriting(&mut self, rights: wasi::Rights) {
324         self.rights_inheriting = Some(rights);
325     }
326 
rights_base(&self) -> wasi::Rights327     fn rights_base(&self) -> wasi::Rights {
328         if let Some(rights) = self.rights_base {
329             return rights;
330         }
331 
332         // If rights haven't otherwise been specified try to pick a reasonable
333         // set. This can always be overridden by users via extension traits, and
334         // implementations may give us fewer rights silently than we ask for. So
335         // given that, just look at `read` and `write` and bucket permissions
336         // based on that.
337         let mut base = 0;
338         if self.read {
339             base |= wasi::RIGHTS_FD_READ;
340             base |= wasi::RIGHTS_FD_READDIR;
341         }
342         if self.write || self.append {
343             base |= wasi::RIGHTS_FD_WRITE;
344             base |= wasi::RIGHTS_FD_DATASYNC;
345             base |= wasi::RIGHTS_FD_ALLOCATE;
346             base |= wasi::RIGHTS_FD_FILESTAT_SET_SIZE;
347         }
348 
349         // FIXME: some of these should probably be read-only or write-only...
350         base |= wasi::RIGHTS_FD_ADVISE;
351         base |= wasi::RIGHTS_FD_FDSTAT_SET_FLAGS;
352         base |= wasi::RIGHTS_FD_FILESTAT_GET;
353         base |= wasi::RIGHTS_FD_FILESTAT_SET_TIMES;
354         base |= wasi::RIGHTS_FD_SEEK;
355         base |= wasi::RIGHTS_FD_SYNC;
356         base |= wasi::RIGHTS_FD_TELL;
357         base |= wasi::RIGHTS_PATH_CREATE_DIRECTORY;
358         base |= wasi::RIGHTS_PATH_CREATE_FILE;
359         base |= wasi::RIGHTS_PATH_FILESTAT_GET;
360         base |= wasi::RIGHTS_PATH_LINK_SOURCE;
361         base |= wasi::RIGHTS_PATH_LINK_TARGET;
362         base |= wasi::RIGHTS_PATH_OPEN;
363         base |= wasi::RIGHTS_PATH_READLINK;
364         base |= wasi::RIGHTS_PATH_REMOVE_DIRECTORY;
365         base |= wasi::RIGHTS_PATH_RENAME_SOURCE;
366         base |= wasi::RIGHTS_PATH_RENAME_TARGET;
367         base |= wasi::RIGHTS_PATH_SYMLINK;
368         base |= wasi::RIGHTS_PATH_UNLINK_FILE;
369         base |= wasi::RIGHTS_POLL_FD_READWRITE;
370 
371         return base;
372     }
373 
rights_inheriting(&self) -> wasi::Rights374     fn rights_inheriting(&self) -> wasi::Rights {
375         self.rights_inheriting.unwrap_or_else(|| self.rights_base())
376     }
377 
lookup_flags(&mut self, flags: wasi::Lookupflags)378     pub fn lookup_flags(&mut self, flags: wasi::Lookupflags) {
379         self.dirflags = flags;
380     }
381 }
382 
383 impl File {
open(path: &Path, opts: &OpenOptions) -> io::Result<File>384     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
385         let (dir, file) = open_parent(path)?;
386         open_at(&dir, &file, opts)
387     }
388 
open_at(&self, path: &Path, opts: &OpenOptions) -> io::Result<File>389     pub fn open_at(&self, path: &Path, opts: &OpenOptions) -> io::Result<File> {
390         open_at(&self.fd, path, opts)
391     }
392 
file_attr(&self) -> io::Result<FileAttr>393     pub fn file_attr(&self) -> io::Result<FileAttr> {
394         self.fd.filestat_get().map(|meta| FileAttr { meta })
395     }
396 
metadata_at(&self, flags: wasi::Lookupflags, path: &Path) -> io::Result<FileAttr>397     pub fn metadata_at(&self, flags: wasi::Lookupflags, path: &Path) -> io::Result<FileAttr> {
398         metadata_at(&self.fd, flags, path)
399     }
400 
fsync(&self) -> io::Result<()>401     pub fn fsync(&self) -> io::Result<()> {
402         self.fd.sync()
403     }
404 
datasync(&self) -> io::Result<()>405     pub fn datasync(&self) -> io::Result<()> {
406         self.fd.datasync()
407     }
408 
truncate(&self, size: u64) -> io::Result<()>409     pub fn truncate(&self, size: u64) -> io::Result<()> {
410         self.fd.filestat_set_size(size)
411     }
412 
read(&self, buf: &mut [u8]) -> io::Result<usize>413     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
414         self.read_vectored(&mut [IoSliceMut::new(buf)])
415     }
416 
read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize>417     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
418         self.fd.read(bufs)
419     }
420 
421     #[inline]
is_read_vectored(&self) -> bool422     pub fn is_read_vectored(&self) -> bool {
423         true
424     }
425 
write(&self, buf: &[u8]) -> io::Result<usize>426     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
427         self.write_vectored(&[IoSlice::new(buf)])
428     }
429 
write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize>430     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
431         self.fd.write(bufs)
432     }
433 
434     #[inline]
is_write_vectored(&self) -> bool435     pub fn is_write_vectored(&self) -> bool {
436         true
437     }
438 
flush(&self) -> io::Result<()>439     pub fn flush(&self) -> io::Result<()> {
440         Ok(())
441     }
442 
seek(&self, pos: SeekFrom) -> io::Result<u64>443     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
444         self.fd.seek(pos)
445     }
446 
duplicate(&self) -> io::Result<File>447     pub fn duplicate(&self) -> io::Result<File> {
448         // https://github.com/CraneStation/wasmtime/blob/master/docs/WASI-rationale.md#why-no-dup
449         unsupported()
450     }
451 
set_permissions(&self, _perm: FilePermissions) -> io::Result<()>452     pub fn set_permissions(&self, _perm: FilePermissions) -> io::Result<()> {
453         // Permissions haven't been fully figured out in wasi yet, so this is
454         // likely temporary
455         unsupported()
456     }
457 
read_link(&self, file: &Path) -> io::Result<PathBuf>458     pub fn read_link(&self, file: &Path) -> io::Result<PathBuf> {
459         read_link(&self.fd, file)
460     }
461 }
462 
463 impl AsInner<WasiFd> for File {
as_inner(&self) -> &WasiFd464     fn as_inner(&self) -> &WasiFd {
465         &self.fd
466     }
467 }
468 
469 impl IntoInner<WasiFd> for File {
into_inner(self) -> WasiFd470     fn into_inner(self) -> WasiFd {
471         self.fd
472     }
473 }
474 
475 impl FromInner<WasiFd> for File {
from_inner(fd: WasiFd) -> File476     fn from_inner(fd: WasiFd) -> File {
477         File { fd }
478     }
479 }
480 
481 impl AsFd for File {
as_fd(&self) -> BorrowedFd<'_>482     fn as_fd(&self) -> BorrowedFd<'_> {
483         self.fd.as_fd()
484     }
485 }
486 
487 impl AsRawFd for File {
as_raw_fd(&self) -> RawFd488     fn as_raw_fd(&self) -> RawFd {
489         self.fd.as_raw_fd()
490     }
491 }
492 
493 impl IntoRawFd for File {
into_raw_fd(self) -> RawFd494     fn into_raw_fd(self) -> RawFd {
495         self.fd.into_raw_fd()
496     }
497 }
498 
499 impl FromRawFd for File {
from_raw_fd(raw_fd: RawFd) -> Self500     unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
501         unsafe { Self { fd: FromRawFd::from_raw_fd(raw_fd) } }
502     }
503 }
504 
505 impl DirBuilder {
new() -> DirBuilder506     pub fn new() -> DirBuilder {
507         DirBuilder {}
508     }
509 
mkdir(&self, p: &Path) -> io::Result<()>510     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
511         let (dir, file) = open_parent(p)?;
512         dir.create_directory(osstr2str(file.as_ref())?)
513     }
514 }
515 
516 impl fmt::Debug for File {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result517     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
518         f.debug_struct("File").field("fd", &self.as_raw_fd()).finish()
519     }
520 }
521 
readdir(p: &Path) -> io::Result<ReadDir>522 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
523     let mut opts = OpenOptions::new();
524     opts.directory(true);
525     opts.read(true);
526     let dir = File::open(p, &opts)?;
527     Ok(ReadDir::new(dir, p.to_path_buf()))
528 }
529 
unlink(p: &Path) -> io::Result<()>530 pub fn unlink(p: &Path) -> io::Result<()> {
531     let (dir, file) = open_parent(p)?;
532     dir.unlink_file(osstr2str(file.as_ref())?)
533 }
534 
rename(old: &Path, new: &Path) -> io::Result<()>535 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
536     let (old, old_file) = open_parent(old)?;
537     let (new, new_file) = open_parent(new)?;
538     old.rename(osstr2str(old_file.as_ref())?, &new, osstr2str(new_file.as_ref())?)
539 }
540 
set_perm(_p: &Path, _perm: FilePermissions) -> io::Result<()>541 pub fn set_perm(_p: &Path, _perm: FilePermissions) -> io::Result<()> {
542     // Permissions haven't been fully figured out in wasi yet, so this is
543     // likely temporary
544     unsupported()
545 }
546 
rmdir(p: &Path) -> io::Result<()>547 pub fn rmdir(p: &Path) -> io::Result<()> {
548     let (dir, file) = open_parent(p)?;
549     dir.remove_directory(osstr2str(file.as_ref())?)
550 }
551 
readlink(p: &Path) -> io::Result<PathBuf>552 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
553     let (dir, file) = open_parent(p)?;
554     read_link(&dir, &file)
555 }
556 
read_link(fd: &WasiFd, file: &Path) -> io::Result<PathBuf>557 fn read_link(fd: &WasiFd, file: &Path) -> io::Result<PathBuf> {
558     // Try to get a best effort initial capacity for the vector we're going to
559     // fill. Note that if it's not a symlink we don't use a file to avoid
560     // allocating gigabytes if you read_link a huge movie file by accident.
561     // Additionally we add 1 to the initial size so if it doesn't change until
562     // when we call `readlink` the returned length will be less than the
563     // capacity, guaranteeing that we got all the data.
564     let meta = metadata_at(fd, 0, file)?;
565     let initial_size = if meta.file_type().is_symlink() {
566         (meta.size() as usize).saturating_add(1)
567     } else {
568         1 // this'll fail in just a moment
569     };
570 
571     // Now that we have an initial guess of how big to make our buffer, call
572     // `readlink` in a loop until it fails or reports it filled fewer bytes than
573     // we asked for, indicating we got everything.
574     let file = osstr2str(file.as_ref())?;
575     let mut destination = vec![0u8; initial_size];
576     loop {
577         let len = fd.readlink(file, &mut destination)?;
578         if len < destination.len() {
579             destination.truncate(len);
580             destination.shrink_to_fit();
581             return Ok(PathBuf::from(OsString::from_vec(destination)));
582         }
583         let amt_to_add = destination.len();
584         destination.extend(iter::repeat(0).take(amt_to_add));
585     }
586 }
587 
symlink(original: &Path, link: &Path) -> io::Result<()>588 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
589     let (link, link_file) = open_parent(link)?;
590     link.symlink(osstr2str(original.as_ref())?, osstr2str(link_file.as_ref())?)
591 }
592 
link(original: &Path, link: &Path) -> io::Result<()>593 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
594     let (original, original_file) = open_parent(original)?;
595     let (link, link_file) = open_parent(link)?;
596     // Pass 0 as the flags argument, meaning don't follow symlinks.
597     original.link(0, osstr2str(original_file.as_ref())?, &link, osstr2str(link_file.as_ref())?)
598 }
599 
stat(p: &Path) -> io::Result<FileAttr>600 pub fn stat(p: &Path) -> io::Result<FileAttr> {
601     let (dir, file) = open_parent(p)?;
602     metadata_at(&dir, wasi::LOOKUPFLAGS_SYMLINK_FOLLOW, &file)
603 }
604 
lstat(p: &Path) -> io::Result<FileAttr>605 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
606     let (dir, file) = open_parent(p)?;
607     metadata_at(&dir, 0, &file)
608 }
609 
metadata_at(fd: &WasiFd, flags: wasi::Lookupflags, path: &Path) -> io::Result<FileAttr>610 fn metadata_at(fd: &WasiFd, flags: wasi::Lookupflags, path: &Path) -> io::Result<FileAttr> {
611     let meta = fd.path_filestat_get(flags, osstr2str(path.as_ref())?)?;
612     Ok(FileAttr { meta })
613 }
614 
canonicalize(_p: &Path) -> io::Result<PathBuf>615 pub fn canonicalize(_p: &Path) -> io::Result<PathBuf> {
616     // This seems to not be in wasi's API yet, and we may need to end up
617     // emulating it ourselves. For now just return an error.
618     unsupported()
619 }
620 
open_at(fd: &WasiFd, path: &Path, opts: &OpenOptions) -> io::Result<File>621 fn open_at(fd: &WasiFd, path: &Path, opts: &OpenOptions) -> io::Result<File> {
622     let fd = fd.open(
623         opts.dirflags,
624         osstr2str(path.as_ref())?,
625         opts.oflags,
626         opts.rights_base(),
627         opts.rights_inheriting(),
628         opts.fdflags,
629     )?;
630     Ok(File { fd })
631 }
632 
633 /// Attempts to open a bare path `p`.
634 ///
635 /// WASI has no fundamental capability to do this. All syscalls and operations
636 /// are relative to already-open file descriptors. The C library, however,
637 /// manages a map of pre-opened file descriptors to their path, and then the C
638 /// library provides an API to look at this. In other words, when you want to
639 /// open a path `p`, you have to find a previously opened file descriptor in a
640 /// global table and then see if `p` is relative to that file descriptor.
641 ///
642 /// This function, if successful, will return two items:
643 ///
644 /// * The first is a `ManuallyDrop<WasiFd>`. This represents a pre-opened file
645 ///   descriptor which we don't have ownership of, but we can use. You shouldn't
646 ///   actually drop the `fd`.
647 ///
648 /// * The second is a path that should be a part of `p` and represents a
649 ///   relative traversal from the file descriptor specified to the desired
650 ///   location `p`.
651 ///
652 /// If successful you can use the returned file descriptor to perform
653 /// file-descriptor-relative operations on the path returned as well. The
654 /// `rights` argument indicates what operations are desired on the returned file
655 /// descriptor, and if successful the returned file descriptor should have the
656 /// appropriate rights for performing `rights` actions.
657 ///
658 /// Note that this can fail if `p` doesn't look like it can be opened relative
659 /// to any pre-opened file descriptor.
open_parent(p: &Path) -> io::Result<(ManuallyDrop<WasiFd>, PathBuf)>660 fn open_parent(p: &Path) -> io::Result<(ManuallyDrop<WasiFd>, PathBuf)> {
661     let p = CString::new(p.as_os_str().as_bytes())?;
662     let mut buf = Vec::<u8>::with_capacity(512);
663     loop {
664         unsafe {
665             let mut relative_path = buf.as_ptr().cast();
666             let mut abs_prefix = ptr::null();
667             let fd = __wasilibc_find_relpath(
668                 p.as_ptr(),
669                 &mut abs_prefix,
670                 &mut relative_path,
671                 buf.capacity(),
672             );
673             if fd == -1 {
674                 if io::Error::last_os_error().raw_os_error() == Some(libc::ENOMEM) {
675                     // Trigger the internal buffer resizing logic of `Vec` by requiring
676                     // more space than the current capacity.
677                     let cap = buf.capacity();
678                     buf.set_len(cap);
679                     buf.reserve(1);
680                     continue;
681                 }
682                 let msg = format!(
683                     "failed to find a pre-opened file descriptor \
684                      through which {:?} could be opened",
685                     p
686                 );
687                 return Err(io::Error::new(io::ErrorKind::Uncategorized, msg));
688             }
689             let relative = CStr::from_ptr(relative_path).to_bytes().to_vec();
690 
691             return Ok((
692                 ManuallyDrop::new(WasiFd::from_raw_fd(fd as c_int)),
693                 PathBuf::from(OsString::from_vec(relative)),
694             ));
695         }
696     }
697 
698     extern "C" {
699         pub fn __wasilibc_find_relpath(
700             path: *const libc::c_char,
701             abs_prefix: *mut *const libc::c_char,
702             relative_path: *mut *const libc::c_char,
703             relative_path_len: libc::size_t,
704         ) -> libc::c_int;
705     }
706 }
707 
osstr2str(f: &OsStr) -> io::Result<&str>708 pub fn osstr2str(f: &OsStr) -> io::Result<&str> {
709     f.to_str()
710         .ok_or_else(|| io::Error::new_const(io::ErrorKind::Uncategorized, &"input must be utf-8"))
711 }
712 
copy(from: &Path, to: &Path) -> io::Result<u64>713 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
714     use crate::fs::File;
715 
716     let mut reader = File::open(from)?;
717     let mut writer = File::create(to)?;
718 
719     io::copy(&mut reader, &mut writer)
720 }
721 
remove_dir_all(path: &Path) -> io::Result<()>722 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
723     let (parent, path) = open_parent(path)?;
724     remove_dir_all_recursive(&parent, &path)
725 }
726 
remove_dir_all_recursive(parent: &WasiFd, path: &Path) -> io::Result<()>727 fn remove_dir_all_recursive(parent: &WasiFd, path: &Path) -> io::Result<()> {
728     // Open up a file descriptor for the directory itself. Note that we don't
729     // follow symlinks here and we specifically open directories.
730     //
731     // At the root invocation of this function this will correctly handle
732     // symlinks passed to the top-level `remove_dir_all`. At the recursive
733     // level this will double-check that after the `readdir` call deduced this
734     // was a directory it's still a directory by the time we open it up.
735     //
736     // If the opened file was actually a symlink then the symlink is deleted,
737     // not the directory recursively.
738     let mut opts = OpenOptions::new();
739     opts.lookup_flags(0);
740     opts.directory(true);
741     opts.read(true);
742     let fd = open_at(parent, path, &opts)?;
743     if fd.file_attr()?.file_type().is_symlink() {
744         return parent.unlink_file(osstr2str(path.as_ref())?);
745     }
746 
747     // this "root" is only used by `DirEntry::path` which we don't use below so
748     // it's ok for this to be a bogus value
749     let dummy_root = PathBuf::new();
750 
751     // Iterate over all the entries in this directory, and travel recursively if
752     // necessary
753     for entry in ReadDir::new(fd, dummy_root) {
754         let entry = entry?;
755         let path = crate::str::from_utf8(&entry.name).map_err(|_| {
756             io::Error::new_const(io::ErrorKind::Uncategorized, &"invalid utf-8 file name found")
757         })?;
758 
759         if entry.file_type()?.is_dir() {
760             remove_dir_all_recursive(&entry.inner.dir.fd, path.as_ref())?;
761         } else {
762             entry.inner.dir.fd.unlink_file(path)?;
763         }
764     }
765 
766     // Once all this directory's contents are deleted it should be safe to
767     // delete the directory tiself.
768     parent.remove_directory(osstr2str(path.as_ref())?)
769 }
770