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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    fidl_fuchsia_io as fio,
    fuchsia_fs::{directory::*, file::*, node::OpenError},
    fuchsia_zircon::{Event, Status},
    std::path::Path,
    tracing::debug,
};

// A convenience wrapper over a FIDL DirectoryProxy.
// Functions of this struct do not tolerate FIDL errors and will panic when they encounter them.
pub struct Directory {
    proxy: fio::DirectoryProxy,
}

impl Directory {
    // Opens a path in the namespace as a Directory.
    pub fn from_namespace(
        path: impl AsRef<Path>,
        flags: fio::OpenFlags,
    ) -> Result<Directory, Status> {
        let path = path.as_ref().to_str().unwrap();
        match fuchsia_fs::directory::open_in_namespace(path, flags) {
            Ok(proxy) => Ok(Directory { proxy }),
            Err(OpenError::OpenError(s)) => {
                debug!(%path, status = %s, "from_namespace failed");
                Err(s)
            }
            Err(OpenError::SendOpenRequest(e)) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during open: {}", e);
                }
            }
            Err(OpenError::OnOpenEventStreamClosed) => Err(Status::PEER_CLOSED),
            Err(OpenError::Namespace(s)) => Err(s),
            Err(e) => panic!("Unexpected error during open: {}", e),
        }
    }

    // Open a directory in the parent dir with the given |filename|.
    pub async fn open_directory(
        &self,
        filename: &str,
        flags: fio::OpenFlags,
    ) -> Result<Directory, Status> {
        match fuchsia_fs::directory::open_directory(&self.proxy, filename, flags).await {
            Ok(proxy) => Ok(Directory { proxy }),
            Err(OpenError::OpenError(s)) => {
                debug!(%filename, ?flags, status = %s, "open_directory failed");
                Err(s)
            }
            Err(OpenError::SendOpenRequest(e)) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during open: {}", e);
                }
            }
            Err(OpenError::OnOpenEventStreamClosed) => Err(Status::PEER_CLOSED),
            Err(e) => panic!("Unexpected error during open: {}", e),
        }
    }

    // Open a file in the parent dir with the given |filename|.
    pub async fn open_file(&self, filename: &str, flags: fio::OpenFlags) -> Result<File, Status> {
        match fuchsia_fs::directory::open_file(&self.proxy, filename, flags).await {
            Ok(proxy) => Ok(File { proxy }),
            Err(OpenError::OpenError(s)) => {
                debug!(%filename, ?flags, status = %s, "open_file failed");
                Err(s)
            }
            Err(OpenError::SendOpenRequest(e)) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during open: {}", e);
                }
            }
            Err(OpenError::OnOpenEventStreamClosed) => Err(Status::PEER_CLOSED),
            Err(e) => panic!("Unexpected error during open: {}", e),
        }
    }

    // Creates a directory named |filename| within this directory.
    pub async fn create_directory(
        &self,
        filename: &str,
        flags: fio::OpenFlags,
    ) -> Result<Directory, Status> {
        match fuchsia_fs::directory::create_directory(&self.proxy, filename, flags).await {
            Ok(proxy) => Ok(Directory { proxy }),
            Err(OpenError::OpenError(s)) => {
                debug!(%filename, ?flags, status = %s, "create_directory failed");
                Err(s)
            }
            Err(OpenError::SendOpenRequest(e)) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during create: {}", e);
                }
            }
            Err(OpenError::OnOpenEventStreamClosed) => Err(Status::PEER_CLOSED),
            Err(e) => panic!("Unexpected error during create: {}", e),
        }
    }

    // Sync a directory
    pub async fn sync_directory(&self) -> Result<(), Status> {
        match self.proxy.sync().await {
            Ok(_) => Ok(()),
            Err(e) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during sync: {}", e);
                }
            }
        }
    }

    // Delete a file from the directory
    pub async fn remove(&self, filename: &str) -> Result<(), Status> {
        match self.proxy.unlink(filename, &fio::UnlinkOptions::default()).await {
            Ok(result) => Status::ok(match result {
                Ok(()) => 0,
                Err(status) => status,
            }),
            Err(e) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during remove: {}", e);
                }
            }
        }
    }

    // Renames |src_name| inside the directory to be |dst_name| within |dst_parent|.
    // Neither |src_name| nor |dst_name| may contain '/' except at the end of either string.
    pub async fn rename(
        &self,
        src_name: &str,
        dst_parent: &Directory,
        dst_name: &str,
    ) -> Result<(), Status> {
        let dst_token = match dst_parent.proxy.get_token().await {
            Ok((_raw_status_code, Some(handle))) => Ok(handle),
            Ok((_raw_status_code, None)) => {
                panic!("No handle");
            }
            Err(e) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during rename: {}", e);
                }
            }
        }?;
        match self.proxy.rename(src_name, Event::from(dst_token), dst_name).await {
            Ok(_) => Ok(()),
            Err(e) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during rename: {}", e);
                }
            }
        }
    }

    // Return a list of filenames in the directory
    pub async fn entries(&self) -> Result<Vec<String>, Status> {
        match fuchsia_fs::directory::readdir(&self.proxy).await {
            Ok(entries) => Ok(entries.iter().map(|entry| entry.name.clone()).collect()),
            Err(fuchsia_fs::directory::EnumerateError::Fidl(_, e)) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error reading dirents: {}", e);
                }
            }
            Err(fuchsia_fs::directory::EnumerateError::ReadDirents(s)) => Err(s),
            Err(e) => {
                panic!("Unexpected error reading dirents: {}", e);
            }
        }
    }
}

// A convenience wrapper over a FIDL FileProxy.
// Functions of this struct do not tolerate FIDL errors and will panic when they encounter them.
#[derive(Debug)]
pub struct File {
    proxy: fio::FileProxy,
}

impl File {
    // Set the length of the file
    pub async fn truncate(&self, length: u64) -> Result<(), Status> {
        match self.proxy.resize(length).await {
            Ok(result) => result.map_err(Status::from_raw),
            Err(e) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during truncate: {}", e);
                }
            }
        }
    }

    // Write the contents of `data` to the file.
    pub async fn write(&self, data: &[u8]) -> Result<(), Status> {
        match write(&self.proxy, data).await {
            Ok(()) => Ok(()),
            Err(WriteError::Fidl(e)) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during write: {}", e);
                }
            }
            Err(WriteError::WriteError(s)) => Err(s),
            Err(e) => panic!("Unexpected error during write: {:?}", e),
        }
    }

    // Get the size of this file as it exists on disk
    pub async fn size_on_disk(&self) -> Result<u64, Status> {
        match self.proxy.get_attr().await {
            Ok((raw_status_code, attr)) => {
                Status::ok(raw_status_code)?;
                Ok(attr.storage_size)
            }
            Err(e) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during size_on_disk: {}", e)
                }
            }
        }
    }

    // Get the uncompressed size of this file (as it would exist in memory)
    pub async fn uncompressed_size(&self) -> Result<u64, Status> {
        match self.proxy.get_attr().await {
            Ok((raw_status_code, attr)) => {
                Status::ok(raw_status_code)?;
                Ok(attr.content_size)
            }
            Err(e) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during size_on_disk: {}", e)
                }
            }
        }
    }

    // Read `num_bytes` of the file from the current offset.
    // This function may return less bytes than expected.
    pub async fn read_num_bytes(&self, num_bytes: u64) -> Result<Vec<u8>, Status> {
        match read_num_bytes(&self.proxy, num_bytes).await {
            Ok(data) => Ok(data),
            Err(ReadError::Fidl(e)) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during read_exact_num_bytes: {}", e);
                }
            }
            Err(ReadError::ReadError(s)) => Err(s),
            Err(e) => panic!("Unexpected error during read: {:?}", e),
        }
    }

    // Read from the current offset until EOF
    pub async fn read_until_eof(&self) -> Result<Vec<u8>, Status> {
        match read(&self.proxy).await {
            Ok(data) => Ok(data),
            Err(ReadError::Fidl(e)) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during read_until_eof: {}", e);
                }
            }
            Err(ReadError::ReadError(s)) => Err(s),
            Err(e) => panic!("Unexpected error during read_until_eof: {:?}", e),
        }
    }

    // Set the offset of the file
    pub async fn seek(&self, origin: fio::SeekOrigin, offset: u64) -> Result<(), Status> {
        match self.proxy.seek(origin, offset as i64).await {
            Ok(result) => result.map_err(Status::from_raw).map(|_: u64| ()),
            Err(e) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during seek: {}", e);
                }
            }
        }
    }

    // Gracefully close the file by informing the filesystem
    pub async fn close(self) -> Result<(), Status> {
        match self.proxy.close().await {
            Ok(result) => result.map_err(Status::from_raw),
            Err(e) => {
                if e.is_closed() {
                    Err(Status::PEER_CLOSED)
                } else {
                    panic!("Unexpected FIDL error during close: {}", e);
                }
            }
        }
    }
}

impl Clone for Directory {
    fn clone(&self) -> Self {
        let new_proxy =
            clone_no_describe(&self.proxy, Some(fio::OpenFlags::CLONE_SAME_RIGHTS)).unwrap();
        Self { proxy: new_proxy }
    }
}