1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
use crate::file::{FdFlags, FileCaps, FileType, Filestat, OFlags, WasiFile};
use crate::{Error, ErrorExt, SystemTimeSpec};
use bitflags::bitflags;
use std::any::Any;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};

pub enum OpenResult {
    File(Box<dyn WasiFile>),
    Dir(Box<dyn WasiDir>),
}

#[wiggle::async_trait]
pub trait WasiDir: Send + Sync {
    fn as_any(&self) -> &dyn Any;

    async fn open_file(
        &self,
        _symlink_follow: bool,
        _path: &str,
        _oflags: OFlags,
        _read: bool,
        _write: bool,
        _fdflags: FdFlags,
    ) -> Result<OpenResult, Error> {
        Err(Error::not_supported())
    }

    async fn create_dir(&self, _path: &str) -> Result<(), Error> {
        Err(Error::not_supported())
    }

    // XXX the iterator here needs to be asyncified as well!
    async fn readdir(
        &self,
        _cursor: ReaddirCursor,
    ) -> Result<Box<dyn Iterator<Item = Result<ReaddirEntity, Error>> + Send>, Error> {
        Err(Error::not_supported())
    }

    async fn symlink(&self, _old_path: &str, _new_path: &str) -> Result<(), Error> {
        Err(Error::not_supported())
    }

    async fn remove_dir(&self, _path: &str) -> Result<(), Error> {
        Err(Error::not_supported())
    }

    async fn unlink_file(&self, _path: &str) -> Result<(), Error> {
        Err(Error::not_supported())
    }

    async fn read_link(&self, _path: &str) -> Result<PathBuf, Error> {
        Err(Error::not_supported())
    }

    async fn get_filestat(&self) -> Result<Filestat, Error> {
        Err(Error::not_supported())
    }

    async fn get_path_filestat(
        &self,
        _path: &str,
        _follow_symlinks: bool,
    ) -> Result<Filestat, Error> {
        Err(Error::not_supported())
    }

    async fn rename(
        &self,
        _path: &str,
        _dest_dir: &dyn WasiDir,
        _dest_path: &str,
    ) -> Result<(), Error> {
        Err(Error::not_supported())
    }

    async fn hard_link(
        &self,
        _path: &str,
        _target_dir: &dyn WasiDir,
        _target_path: &str,
    ) -> Result<(), Error> {
        Err(Error::not_supported())
    }

    async fn set_times(
        &self,
        _path: &str,
        _atime: Option<SystemTimeSpec>,
        _mtime: Option<SystemTimeSpec>,
        _follow_symlinks: bool,
    ) -> Result<(), Error> {
        Err(Error::not_supported())
    }
}

pub(crate) struct DirEntry {
    caps: RwLock<DirFdStat>,
    preopen_path: Option<PathBuf>, // precondition: PathBuf is valid unicode
    dir: Box<dyn WasiDir>,
}

impl DirEntry {
    pub fn new(
        dir_caps: DirCaps,
        file_caps: FileCaps,
        preopen_path: Option<PathBuf>,
        dir: Box<dyn WasiDir>,
    ) -> Self {
        DirEntry {
            caps: RwLock::new(DirFdStat {
                dir_caps,
                file_caps,
            }),
            preopen_path,
            dir,
        }
    }
    pub fn capable_of_dir(&self, caps: DirCaps) -> Result<(), Error> {
        let fdstat = self.caps.read().unwrap();
        fdstat.capable_of_dir(caps)
    }

    pub fn drop_caps_to(&self, dir_caps: DirCaps, file_caps: FileCaps) -> Result<(), Error> {
        let mut fdstat = self.caps.write().unwrap();
        fdstat.capable_of_dir(dir_caps)?;
        fdstat.capable_of_file(file_caps)?;
        *fdstat = DirFdStat {
            dir_caps,
            file_caps,
        };
        Ok(())
    }
    pub fn child_dir_caps(&self, desired_caps: DirCaps) -> DirCaps {
        self.caps.read().unwrap().dir_caps & desired_caps
    }
    pub fn child_file_caps(&self, desired_caps: FileCaps) -> FileCaps {
        self.caps.read().unwrap().file_caps & desired_caps
    }
    pub fn get_dir_fdstat(&self) -> DirFdStat {
        self.caps.read().unwrap().clone()
    }
    pub fn preopen_path(&self) -> &Option<PathBuf> {
        &self.preopen_path
    }
}

pub trait DirEntryExt {
    fn get_cap(&self, caps: DirCaps) -> Result<&dyn WasiDir, Error>;
}

impl DirEntryExt for DirEntry {
    fn get_cap(&self, caps: DirCaps) -> Result<&dyn WasiDir, Error> {
        self.capable_of_dir(caps)?;
        Ok(&*self.dir)
    }
}

bitflags! {
    pub struct DirCaps: u32 {
        const CREATE_DIRECTORY        = 0b1;
        const CREATE_FILE             = 0b10;
        const LINK_SOURCE             = 0b100;
        const LINK_TARGET             = 0b1000;
        const OPEN                    = 0b10000;
        const READDIR                 = 0b100000;
        const READLINK                = 0b1000000;
        const RENAME_SOURCE           = 0b10000000;
        const RENAME_TARGET           = 0b100000000;
        const SYMLINK                 = 0b1000000000;
        const REMOVE_DIRECTORY        = 0b10000000000;
        const UNLINK_FILE             = 0b100000000000;
        const PATH_FILESTAT_GET       = 0b1000000000000;
        const PATH_FILESTAT_SET_TIMES = 0b10000000000000;
        const FILESTAT_GET            = 0b100000000000000;
        const FILESTAT_SET_TIMES      = 0b1000000000000000;
    }
}

#[derive(Debug, Clone)]
pub struct DirFdStat {
    pub file_caps: FileCaps,
    pub dir_caps: DirCaps,
}

impl DirFdStat {
    pub fn capable_of_dir(&self, caps: DirCaps) -> Result<(), Error> {
        if self.dir_caps.contains(caps) {
            Ok(())
        } else {
            let missing = caps & !self.dir_caps;
            let err = if missing.intersects(DirCaps::READDIR) {
                Error::not_dir()
            } else {
                Error::perm()
            };
            Err(err.context(format!(
                "desired rights {:?}, has {:?}",
                caps, self.dir_caps
            )))
        }
    }
    pub fn capable_of_file(&self, caps: FileCaps) -> Result<(), Error> {
        if self.file_caps.contains(caps) {
            Ok(())
        } else {
            Err(Error::perm().context(format!(
                "desired rights {:?}, has {:?}",
                caps, self.file_caps
            )))
        }
    }
}

pub(crate) trait TableDirExt {
    fn get_dir(&self, fd: u32) -> Result<Arc<DirEntry>, Error>;
}

impl TableDirExt for crate::table::Table {
    fn get_dir(&self, fd: u32) -> Result<Arc<DirEntry>, Error> {
        self.get(fd)
    }
}

#[derive(Debug, Clone)]
pub struct ReaddirEntity {
    pub next: ReaddirCursor,
    pub inode: u64,
    pub name: String,
    pub filetype: FileType,
}

#[derive(Debug, Copy, Clone)]
pub struct ReaddirCursor(u64);
impl From<u64> for ReaddirCursor {
    fn from(c: u64) -> ReaddirCursor {
        ReaddirCursor(c)
    }
}
impl From<ReaddirCursor> for u64 {
    fn from(c: ReaddirCursor) -> u64 {
        c.0
    }
}