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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
use crate::fs::{DirBuilder, File, Metadata, OpenOptions, ReadDir};
#[cfg(unix)]
use crate::os::unix::net::{UnixDatagram, UnixListener, UnixStream};
use cap_primitives::fs::{
canonicalize, copy, create_dir, hard_link, open, open_ambient_dir, open_dir, open_parent_dir,
read_base_dir, read_dir, read_link, remove_dir, remove_dir_all, remove_file, remove_open_dir,
remove_open_dir_all, rename, set_permissions, stat, DirOptions, FollowSymlinks, Permissions,
};
use cap_primitives::{ambient_authority, AmbientAuthority};
#[cfg(not(windows))]
use io_lifetimes::{AsFd, BorrowedFd, FromFd, IntoFd, OwnedFd};
#[cfg(windows)]
use io_lifetimes::{AsHandle, BorrowedHandle, FromHandle, IntoHandle, OwnedHandle};
#[cfg(target_os = "wasi")]
use rsix::fs::OpenOptionsExt;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::{fmt, fs};
use unsafe_io::OwnsRaw;
#[cfg(not(windows))]
use {
cap_primitives::fs::symlink,
unsafe_io::os::rsix::{AsRawFd, FromRawFd, IntoRawFd, RawFd},
};
#[cfg(windows)]
use {
cap_primitives::fs::{symlink_dir, symlink_file},
std::os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle},
unsafe_io::os::windows::{AsRawHandleOrSocket, IntoRawHandleOrSocket, RawHandleOrSocket},
};
pub struct Dir {
std_file: fs::File,
}
impl Dir {
#[inline]
pub fn from_std_file(std_file: fs::File, _: AmbientAuthority) -> Self {
Self { std_file }
}
#[inline]
pub fn into_std_file(self) -> fs::File {
self.std_file
}
#[inline]
pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
self.open_with(path, OpenOptions::new().read(true))
}
#[inline]
pub fn open_with<P: AsRef<Path>>(&self, path: P, options: &OpenOptions) -> io::Result<File> {
self._open_with(path.as_ref(), options)
}
#[cfg(not(target_os = "wasi"))]
#[inline]
fn _open_with(&self, path: &Path, options: &OpenOptions) -> io::Result<File> {
let dir = open(&self.std_file, path, options)?;
Ok(File::from_std(dir, ambient_authority()))
}
#[cfg(target_os = "wasi")]
#[inline]
fn _open_with(&self, path: &Path, options: &OpenOptions) -> io::Result<File> {
let dir = options.open_at(&self.std_file, path)?;
Ok(File::from_std(dir, ambient_authority()))
}
#[inline]
pub fn open_dir<P: AsRef<Path>>(&self, path: P) -> io::Result<Self> {
let dir = open_dir(&self.std_file, path.as_ref())?;
Ok(Self::from_std_file(dir, ambient_authority()))
}
#[inline]
pub fn create_dir<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
self._create_dir_one(path.as_ref(), &DirOptions::new())
}
#[inline]
pub fn create_dir_all<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
self._create_dir_all(path.as_ref(), &DirOptions::new())
}
#[inline]
pub fn create_dir_with<P: AsRef<Path>>(
&self,
path: P,
dir_builder: &DirBuilder,
) -> io::Result<()> {
let options = dir_builder.options();
if dir_builder.is_recursive() {
self._create_dir_all(path.as_ref(), options)
} else {
self._create_dir_one(path.as_ref(), options)
}
}
fn _create_dir_one(&self, path: &Path, dir_options: &DirOptions) -> io::Result<()> {
create_dir(&self.std_file, path, dir_options)
}
fn _create_dir_all(&self, path: &Path, dir_options: &DirOptions) -> io::Result<()> {
if path == Path::new("") {
return Ok(());
}
match self._create_dir_one(path, dir_options) {
Ok(()) => return Ok(()),
Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
Err(_) if self.is_dir(path) => return Ok(()),
Err(e) => return Err(e),
}
match path.parent() {
Some(p) => self._create_dir_all(p, dir_options)?,
None => {
return Err(io::Error::new(
io::ErrorKind::Other,
"failed to create whole tree",
))
}
}
match self._create_dir_one(path, dir_options) {
Ok(()) => Ok(()),
Err(_) if self.is_dir(path) => Ok(()),
Err(e) => Err(e),
}
}
#[inline]
pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
self.open_with(
path,
OpenOptions::new().write(true).create(true).truncate(true),
)
}
#[inline]
pub fn canonicalize<P: AsRef<Path>>(&self, path: P) -> io::Result<PathBuf> {
canonicalize(&self.std_file, path.as_ref())
}
#[inline]
pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(
&self,
from: P,
to_dir: &Self,
to: Q,
) -> io::Result<u64> {
copy(&self.std_file, from.as_ref(), &to_dir.std_file, to.as_ref())
}
#[inline]
pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(
&self,
src: P,
dst_dir: &Self,
dst: Q,
) -> io::Result<()> {
hard_link(
&self.std_file,
src.as_ref(),
&dst_dir.std_file,
dst.as_ref(),
)
}
#[inline]
pub fn metadata<P: AsRef<Path>>(&self, path: P) -> io::Result<Metadata> {
stat(&self.std_file, path.as_ref(), FollowSymlinks::Yes)
}
#[inline]
pub fn dir_metadata(&self) -> io::Result<Metadata> {
Metadata::from_file(&self.std_file)
}
#[inline]
pub fn entries(&self) -> io::Result<ReadDir> {
read_base_dir(&self.std_file).map(|inner| ReadDir { inner })
}
#[inline]
pub fn read_dir<P: AsRef<Path>>(&self, path: P) -> io::Result<ReadDir> {
read_dir(&self.std_file, path.as_ref()).map(|inner| ReadDir { inner })
}
#[inline]
pub fn read<P: AsRef<Path>>(&self, path: P) -> io::Result<Vec<u8>> {
let mut file = self.open(path)?;
let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
file.read_to_end(&mut bytes)?;
Ok(bytes)
}
#[inline]
pub fn read_link<P: AsRef<Path>>(&self, path: P) -> io::Result<PathBuf> {
read_link(&self.std_file, path.as_ref())
}
#[inline]
pub fn read_to_string<P: AsRef<Path>>(&self, path: P) -> io::Result<String> {
let mut s = String::new();
self.open(path)?.read_to_string(&mut s)?;
Ok(s)
}
#[inline]
pub fn remove_dir<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
remove_dir(&self.std_file, path.as_ref())
}
#[inline]
pub fn remove_dir_all<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
remove_dir_all(&self.std_file, path.as_ref())
}
#[inline]
pub fn remove_open_dir(self) -> io::Result<()> {
remove_open_dir(self.std_file)
}
#[inline]
pub fn remove_open_dir_all(self) -> io::Result<()> {
remove_open_dir_all(self.std_file)
}
#[inline]
pub fn remove_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
remove_file(&self.std_file, path.as_ref())
}
#[inline]
pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(
&self,
from: P,
to_dir: &Self,
to: Q,
) -> io::Result<()> {
rename(&self.std_file, from.as_ref(), &to_dir.std_file, to.as_ref())
}
#[inline]
pub fn set_permissions<P: AsRef<Path>>(&self, path: P, perm: Permissions) -> io::Result<()> {
set_permissions(&self.std_file, path.as_ref(), perm)
}
#[inline]
pub fn symlink_metadata<P: AsRef<Path>>(&self, path: P) -> io::Result<Metadata> {
stat(&self.std_file, path.as_ref(), FollowSymlinks::No)
}
#[inline]
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(&self, path: P, contents: C) -> io::Result<()> {
let mut file = self.create(path)?;
file.write_all(contents.as_ref())
}
#[cfg(not(windows))]
#[inline]
pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, dst: Q) -> io::Result<()> {
symlink(src.as_ref(), &self.std_file, dst.as_ref())
}
#[cfg(windows)]
#[inline]
pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, dst: Q) -> io::Result<()> {
symlink_file(src.as_ref(), &self.std_file, dst.as_ref())
}
#[cfg(windows)]
#[inline]
pub fn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, dst: Q) -> io::Result<()> {
symlink_dir(src.as_ref(), &self.std_file, dst.as_ref())
}
#[cfg(unix)]
#[inline]
pub fn bind_unix_listener<P: AsRef<Path>>(&self, path: P) -> io::Result<UnixListener> {
todo!(
"Dir::bind_unix_listener({:?}, {})",
self.std_file,
path.as_ref().display()
)
}
#[cfg(unix)]
#[inline]
pub fn connect_unix_stream<P: AsRef<Path>>(&self, path: P) -> io::Result<UnixStream> {
todo!(
"Dir::connect_unix_stream({:?}, {})",
self.std_file,
path.as_ref().display()
)
}
#[cfg(unix)]
#[inline]
pub fn bind_unix_datagram<P: AsRef<Path>>(&self, path: P) -> io::Result<UnixDatagram> {
todo!(
"Dir::bind_unix_datagram({:?}, {})",
self.std_file,
path.as_ref().display()
)
}
#[cfg(unix)]
#[inline]
pub fn connect_unix_datagram<P: AsRef<Path>>(
&self,
_unix_datagram: &UnixDatagram,
path: P,
) -> io::Result<()> {
todo!(
"Dir::connect_unix_datagram({:?}, {})",
self.std_file,
path.as_ref().display()
)
}
#[cfg(unix)]
#[inline]
pub fn send_to_unix_datagram_addr<P: AsRef<Path>>(
&self,
_unix_datagram: &UnixDatagram,
buf: &[u8],
path: P,
) -> io::Result<usize> {
todo!(
"Dir::send_to_unix_datagram_addr({:?}, {:?}, {})",
self.std_file,
buf,
path.as_ref().display()
)
}
#[inline]
pub fn try_clone(&self) -> io::Result<Self> {
let dir = self.std_file.try_clone()?;
Ok(Self::from_std_file(dir, ambient_authority()))
}
#[inline]
pub fn exists<P: AsRef<Path>>(&self, path: P) -> bool {
self.metadata(path).is_ok()
}
#[inline]
pub fn is_file<P: AsRef<Path>>(&self, path: P) -> bool {
self.metadata(path).map(|m| m.is_file()).unwrap_or(false)
}
#[inline]
pub fn is_dir<P: AsRef<Path>>(&self, path: P) -> bool {
self.metadata(path).map(|m| m.is_dir()).unwrap_or(false)
}
#[inline]
pub fn open_ambient_dir<P: AsRef<Path>>(
path: P,
ambient_authority: AmbientAuthority,
) -> io::Result<Self> {
let dir = open_ambient_dir(path.as_ref(), ambient_authority)?;
Ok(Self::from_std_file(dir, ambient_authority))
}
#[inline]
pub fn open_parent_dir(&self, ambient_authority: AmbientAuthority) -> io::Result<Self> {
let dir = open_parent_dir(&self.std_file, ambient_authority)?;
Ok(Self::from_std_file(dir, ambient_authority))
}
#[inline]
pub fn create_ambient_dir_all<P: AsRef<Path>>(
path: P,
_ambient_authority: AmbientAuthority,
) -> io::Result<()> {
fs::create_dir_all(path)
}
}
#[cfg(not(windows))]
impl FromRawFd for Dir {
#[inline]
unsafe fn from_raw_fd(fd: RawFd) -> Self {
Self::from_std_file(fs::File::from_raw_fd(fd), ambient_authority())
}
}
#[cfg(not(windows))]
impl FromFd for Dir {
#[inline]
fn from_fd(fd: OwnedFd) -> Self {
Self::from_std_file(fs::File::from_fd(fd), ambient_authority())
}
}
#[cfg(windows)]
impl FromRawHandle for Dir {
#[inline]
unsafe fn from_raw_handle(handle: RawHandle) -> Self {
Self::from_std_file(fs::File::from_raw_handle(handle), ambient_authority())
}
}
#[cfg(windows)]
impl FromHandle for Dir {
#[inline]
fn from_handle(handle: OwnedHandle) -> Self {
Self::from_std_file(fs::File::from_handle(handle), ambient_authority())
}
}
#[cfg(not(windows))]
impl AsRawFd for Dir {
#[inline]
fn as_raw_fd(&self) -> RawFd {
self.std_file.as_raw_fd()
}
}
#[cfg(not(windows))]
impl AsFd for Dir {
#[inline]
fn as_fd(&self) -> BorrowedFd<'_> {
self.std_file.as_fd()
}
}
#[cfg(windows)]
impl AsRawHandle for Dir {
#[inline]
fn as_raw_handle(&self) -> RawHandle {
self.std_file.as_raw_handle()
}
}
#[cfg(windows)]
impl AsHandle for Dir {
#[inline]
fn as_handle(&self) -> BorrowedHandle<'_> {
self.std_file.as_handle()
}
}
#[cfg(windows)]
impl AsRawHandleOrSocket for Dir {
#[inline]
fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket {
self.std_file.as_raw_handle_or_socket()
}
}
#[cfg(not(windows))]
impl IntoRawFd for Dir {
#[inline]
fn into_raw_fd(self) -> RawFd {
self.std_file.into_raw_fd()
}
}
#[cfg(not(windows))]
impl IntoFd for Dir {
#[inline]
fn into_fd(self) -> OwnedFd {
self.std_file.into_fd()
}
}
#[cfg(windows)]
impl IntoRawHandle for Dir {
#[inline]
fn into_raw_handle(self) -> RawHandle {
self.std_file.into_raw_handle()
}
}
#[cfg(windows)]
impl IntoHandle for Dir {
#[inline]
fn into_handle(self) -> OwnedHandle {
self.std_file.into_handle()
}
}
#[cfg(windows)]
impl IntoRawHandleOrSocket for Dir {
#[inline]
fn into_raw_handle_or_socket(self) -> RawHandleOrSocket {
self.std_file.into_raw_handle_or_socket()
}
}
unsafe impl OwnsRaw for Dir {}
fn initial_buffer_size(file: &File) -> usize {
file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
}
impl fmt::Debug for Dir {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut b = f.debug_struct("Dir");
#[cfg(not(windows))]
b.field("fd", &self.std_file.as_raw_fd());
#[cfg(windows)]
b.field("handle", &self.std_file.as_raw_handle());
b.finish()
}
}