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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
use crate::preview2::{InputStream, OutputStream, Table, TableError};
use std::any::Any;
use std::sync::Arc;

bitflags::bitflags! {
    pub struct FilePerms: usize {
        const READ = 0b1;
        const WRITE = 0b10;
    }
}

pub(crate) struct File {
    pub file: Arc<cap_std::fs::File>,
    pub perms: FilePerms,
}

impl File {
    pub fn new(file: cap_std::fs::File, perms: FilePerms) -> Self {
        Self {
            file: Arc::new(file),
            perms,
        }
    }
}
pub(crate) trait TableFsExt {
    fn push_file(&mut self, file: File) -> Result<u32, TableError>;
    fn delete_file(&mut self, fd: u32) -> Result<File, TableError>;
    fn is_file(&self, fd: u32) -> bool;
    fn get_file(&self, fd: u32) -> Result<&File, TableError>;

    fn push_dir(&mut self, dir: Dir) -> Result<u32, TableError>;
    fn delete_dir(&mut self, fd: u32) -> Result<Dir, TableError>;
    fn is_dir(&self, fd: u32) -> bool;
    fn get_dir(&self, fd: u32) -> Result<&Dir, TableError>;
}

impl TableFsExt for Table {
    fn push_file(&mut self, file: File) -> Result<u32, TableError> {
        self.push(Box::new(file))
    }
    fn delete_file(&mut self, fd: u32) -> Result<File, TableError> {
        self.delete(fd)
    }
    fn is_file(&self, fd: u32) -> bool {
        self.is::<File>(fd)
    }
    fn get_file(&self, fd: u32) -> Result<&File, TableError> {
        self.get(fd)
    }

    fn push_dir(&mut self, dir: Dir) -> Result<u32, TableError> {
        self.push(Box::new(dir))
    }
    fn delete_dir(&mut self, fd: u32) -> Result<Dir, TableError> {
        self.delete(fd)
    }
    fn is_dir(&self, fd: u32) -> bool {
        self.is::<Dir>(fd)
    }
    fn get_dir(&self, fd: u32) -> Result<&Dir, TableError> {
        self.get(fd)
    }
}

bitflags::bitflags! {
    pub struct DirPerms: usize {
        const READ = 0b1;
        const MUTATE = 0b10;
    }
}

pub(crate) struct Dir {
    pub dir: cap_std::fs::Dir,
    pub perms: DirPerms,
    pub file_perms: FilePerms,
}

impl Dir {
    pub fn new(dir: cap_std::fs::Dir, perms: DirPerms, file_perms: FilePerms) -> Self {
        Dir {
            dir,
            perms,
            file_perms,
        }
    }
}

pub(crate) struct FileInputStream {
    file: Arc<cap_std::fs::File>,
    position: u64,
}
impl FileInputStream {
    pub fn new(file: Arc<cap_std::fs::File>, position: u64) -> Self {
        Self { file, position }
    }
}

#[async_trait::async_trait]
impl InputStream for FileInputStream {
    fn as_any(&self) -> &dyn Any {
        self
    }
    #[cfg(unix)]
    fn pollable_read(&self) -> Option<rustix::fd::BorrowedFd> {
        use cap_std::io_lifetimes::AsFd;
        Some(self.file.as_fd())
    }
    #[cfg(windows)]
    fn pollable_read(&self) -> Option<io_extras::os::windows::BorrowedHandleOrSocket> {
        use io_extras::os::windows::AsHandleOrSocket;
        Some(self.file.as_handle_or_socket())
    }
    async fn read(&mut self, buf: &mut [u8]) -> anyhow::Result<(u64, bool)> {
        use system_interface::fs::FileIoExt;
        let (n, end) = read_result(self.file.read_at(buf, self.position))?;
        self.position = self.position.wrapping_add(n);
        Ok((n, end))
    }
    async fn read_vectored<'a>(
        &mut self,
        bufs: &mut [std::io::IoSliceMut<'a>],
    ) -> anyhow::Result<(u64, bool)> {
        use system_interface::fs::FileIoExt;
        let (n, end) = read_result(self.file.read_vectored_at(bufs, self.position))?;
        self.position = self.position.wrapping_add(n);
        Ok((n, end))
    }
    fn is_read_vectored(&self) -> bool {
        use system_interface::fs::FileIoExt;
        self.file.is_read_vectored_at()
    }
    async fn num_ready_bytes(&self) -> anyhow::Result<u64> {
        // FIXME we ought to be able to do better than this
        Ok(0)
    }
    async fn readable(&self) -> anyhow::Result<()> {
        // FIXME is this the spot to perform the permission check?
        Ok(())
    }
}

pub(crate) fn read_result(r: Result<usize, std::io::Error>) -> Result<(u64, bool), std::io::Error> {
    match r {
        Ok(0) => Ok((0, true)),
        Ok(n) => Ok((n as u64, false)),
        Err(e) if e.kind() == std::io::ErrorKind::Interrupted => Ok((0, false)),
        Err(e) => Err(e),
    }
}

pub(crate) struct FileOutputStream {
    file: Arc<cap_std::fs::File>,
    position: u64,
}
impl FileOutputStream {
    pub fn new(file: Arc<cap_std::fs::File>, position: u64) -> Self {
        Self { file, position }
    }
}

#[async_trait::async_trait]
impl OutputStream for FileOutputStream {
    fn as_any(&self) -> &dyn Any {
        self
    }

    /// If this stream is writing from a host file descriptor, return it so
    /// that it can be polled with a host poll.
    #[cfg(unix)]
    fn pollable_write(&self) -> Option<rustix::fd::BorrowedFd> {
        use cap_std::io_lifetimes::AsFd;
        Some(self.file.as_fd())
    }

    /// If this stream is writing from a host file descriptor, return it so
    /// that it can be polled with a host poll.
    #[cfg(windows)]
    fn pollable_write(&self) -> Option<io_extras::os::windows::BorrowedHandleOrSocket> {
        use io_extras::os::windows::AsHandleOrSocket;
        Some(self.file.as_handle_or_socket())
    }

    /// Write bytes. On success, returns the number of bytes written.
    async fn write(&mut self, buf: &[u8]) -> anyhow::Result<u64> {
        use system_interface::fs::FileIoExt;
        let n = self.file.write_at(buf, self.position)? as i64 as u64;
        self.position = self.position.wrapping_add(n);
        Ok(n)
    }

    /// Vectored-I/O form of `write`.
    async fn write_vectored<'a>(&mut self, bufs: &[std::io::IoSlice<'a>]) -> anyhow::Result<u64> {
        use system_interface::fs::FileIoExt;
        let n = self.file.write_vectored_at(bufs, self.position)? as i64 as u64;
        self.position = self.position.wrapping_add(n);
        Ok(n)
    }

    /// Test whether vectored I/O writes are known to be optimized in the
    /// underlying implementation.
    fn is_write_vectored(&self) -> bool {
        use system_interface::fs::FileIoExt;
        self.file.is_write_vectored_at()
    }

    /// Test whether this stream is writable.
    async fn writable(&self) -> anyhow::Result<()> {
        // FIXME perm check?
        Ok(())
    }
}

pub(crate) struct FileAppendStream {
    file: Arc<cap_std::fs::File>,
}
impl FileAppendStream {
    pub fn new(file: Arc<cap_std::fs::File>) -> Self {
        Self { file }
    }
}

#[async_trait::async_trait]
impl OutputStream for FileAppendStream {
    fn as_any(&self) -> &dyn Any {
        self
    }

    /// If this stream is writing from a host file descriptor, return it so
    /// that it can be polled with a host poll.
    #[cfg(unix)]
    fn pollable_write(&self) -> Option<rustix::fd::BorrowedFd> {
        use cap_std::io_lifetimes::AsFd;
        Some(self.file.as_fd())
    }

    /// If this stream is writing from a host file descriptor, return it so
    /// that it can be polled with a host poll.
    #[cfg(windows)]
    fn pollable_write(&self) -> Option<io_extras::os::windows::BorrowedHandleOrSocket> {
        use io_extras::os::windows::AsHandleOrSocket;
        Some(self.file.as_handle_or_socket())
    }

    /// Write bytes. On success, returns the number of bytes written.
    async fn write(&mut self, buf: &[u8]) -> anyhow::Result<u64> {
        use system_interface::fs::FileIoExt;
        Ok(self.file.append(buf)? as i64 as u64)
    }

    /// Vectored-I/O form of `write`.
    async fn write_vectored<'a>(&mut self, bufs: &[std::io::IoSlice<'a>]) -> anyhow::Result<u64> {
        use system_interface::fs::FileIoExt;
        let n = self.file.append_vectored(bufs)? as i64 as u64;
        Ok(n)
    }

    /// Test whether vectored I/O writes are known to be optimized in the
    /// underlying implementation.
    fn is_write_vectored(&self) -> bool {
        use system_interface::fs::FileIoExt;
        self.file.is_write_vectored_at()
    }

    /// Test whether this stream is writable.
    async fn writable(&self) -> anyhow::Result<()> {
        // FIXME perm check?
        Ok(())
    }
}