kobako 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. checksums.yaml +4 -4
  2. data/.githooks/linux-tests.sh +29 -0
  3. data/.release-please-manifest.json +1 -1
  4. data/CHANGELOG.md +125 -0
  5. data/Cargo.lock +457 -494
  6. data/README.md +2 -3
  7. data/ROADMAP.md +0 -1
  8. data/crates/kobako-runtime/CHANGELOG.md +90 -0
  9. data/crates/kobako-runtime/Cargo.toml +14 -15
  10. data/crates/kobako-runtime/README.md +1 -1
  11. data/crates/kobako-runtime/src/cred.rs +32 -20
  12. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +300 -22
  13. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +56 -22
  14. data/crates/kobako-runtime/src/filesystem/bind/unicode.rs +109 -0
  15. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +33 -14
  16. data/crates/kobako-runtime/src/filesystem/bind.rs +393 -220
  17. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +2 -0
  18. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +9 -10
  19. data/crates/kobako-runtime/src/filesystem/overlay.rs +277 -46
  20. data/crates/kobako-runtime/src/filesystem/rdir.rs +8 -27
  21. data/crates/kobako-runtime/src/filesystem/testing.rs +31 -0
  22. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +47 -13
  23. data/crates/kobako-runtime/src/filesystem.rs +2 -0
  24. data/crates/kobako-runtime/src/fork.rs +239 -16
  25. data/crates/kobako-runtime/src/limits.rs +17 -41
  26. data/crates/kobako-runtime/src/locking/seqlock.rs +29 -3
  27. data/crates/kobako-runtime/src/locking.rs +508 -113
  28. data/crates/kobako-runtime/src/memcg.rs +83 -160
  29. data/crates/kobako-runtime/src/mount.rs +0 -30
  30. data/crates/kobako-runtime/src/net/connections.rs +53 -13
  31. data/crates/kobako-runtime/src/net/egress.rs +44 -24
  32. data/crates/kobako-runtime/src/net/http.rs +888 -456
  33. data/crates/kobako-runtime/src/net/lookup.rs +150 -50
  34. data/crates/kobako-runtime/src/net/namespace.rs +97 -95
  35. data/crates/kobako-runtime/src/net/reactor.rs +298 -203
  36. data/crates/kobako-runtime/src/net/resolv/darwin.rs +8 -3
  37. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +50 -0
  38. data/crates/kobako-runtime/src/net/resolv/stub.rs +29 -23
  39. data/crates/kobako-runtime/src/net/resolv/windows.rs +14 -44
  40. data/crates/kobako-runtime/src/net/resolv.rs +39 -15
  41. data/crates/kobako-runtime/src/net/skbuff.rs +109 -0
  42. data/crates/kobako-runtime/src/net/socket.rs +51 -52
  43. data/crates/kobako-runtime/src/net/task.rs +223 -0
  44. data/crates/kobako-runtime/src/net/tcp.rs +410 -158
  45. data/crates/kobako-runtime/src/net/tls.rs +65 -3
  46. data/crates/kobako-runtime/src/net/transport.rs +72 -47
  47. data/crates/kobako-runtime/src/net/udp.rs +231 -129
  48. data/crates/kobako-runtime/src/net.rs +3 -0
  49. data/crates/kobako-runtime/src/sched.rs +244 -58
  50. data/crates/kobako-runtime/src/security.rs +27 -16
  51. data/crates/kobako-runtime/src/vfs/dentry.rs +80 -41
  52. data/crates/kobako-runtime/src/vfs/file.rs +52 -53
  53. data/crates/kobako-runtime/src/vfs/kern_path.rs +24 -11
  54. data/crates/kobako-runtime/src/vfs/namei.rs +399 -184
  55. data/crates/kobako-runtime/src/vfs/namespace.rs +123 -40
  56. data/crates/kobako-runtime/src/vfs/stat.rs +105 -16
  57. data/crates/kobako-runtime/src/vfs.rs +1 -0
  58. data/crates/kobako-runtime/src/wait.rs +75 -50
  59. data/crates/kobako-transport/CHANGELOG.md +7 -0
  60. data/crates/kobako-transport/Cargo.toml +1 -1
  61. data/crates/kobako-transport/README.md +1 -1
  62. data/crates/kobako-wasmtime/CHANGELOG.md +47 -0
  63. data/crates/kobako-wasmtime/Cargo.toml +27 -6
  64. data/crates/kobako-wasmtime/README.md +3 -3
  65. data/crates/kobako-wasmtime/src/abi.rs +2 -1
  66. data/crates/kobako-wasmtime/src/ambient.rs +11 -2
  67. data/crates/kobako-wasmtime/src/cache/unix.rs +95 -0
  68. data/crates/kobako-wasmtime/src/cache/windows.rs +359 -0
  69. data/crates/kobako-wasmtime/src/cache.rs +88 -103
  70. data/crates/kobako-wasmtime/src/driver.rs +40 -27
  71. data/crates/kobako-wasmtime/src/invocation.rs +21 -7
  72. data/crates/kobako-wasmtime/src/lib.rs +2 -0
  73. data/crates/kobako-wasmtime/src/limiter.rs +78 -25
  74. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +13 -17
  75. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +4 -5
  76. data/crates/kobako-wasmtime/src/preview1/differential.rs +1 -1
  77. data/crates/kobako-wasmtime/src/preview1/fd.rs +23 -19
  78. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +130 -197
  79. data/crates/kobako-wasmtime/src/preview1/path.rs +3 -3
  80. data/crates/kobako-wasmtime/src/preview1/poll.rs +28 -22
  81. data/crates/kobako-wasmtime/src/preview1/random.rs +125 -0
  82. data/crates/kobako-wasmtime/src/preview1/testing.rs +31 -0
  83. data/crates/kobako-wasmtime/src/preview1.rs +85 -9
  84. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +2 -2
  85. data/crates/kobako-wasmtime/src/preview2/host.rs +609 -249
  86. data/crates/kobako-wasmtime/src/preview2/http.rs +299 -215
  87. data/crates/kobako-wasmtime/src/preview2/io.rs +17 -4
  88. data/crates/kobako-wasmtime/src/preview2/table.rs +24 -72
  89. data/crates/kobako-wasmtime/src/trap.rs +68 -23
  90. data/crates/kobako-wasmtime/src/waits.rs +59 -0
  91. data/crates/kobako-wasmtime/src/wasi.rs +91 -10
  92. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
  93. data/data/kobako.wasm +0 -0
  94. data/ext/kobako/Cargo.toml +6 -2
  95. data/ext/kobako/src/escape.rs +332 -26
  96. data/ext/kobako/src/filesystem/grants.rs +5 -7
  97. data/ext/kobako/src/filesystem/ruby.rs +10 -3
  98. data/ext/kobako/src/filesystem.rs +47 -8
  99. data/ext/kobako/src/fork.rs +72 -0
  100. data/ext/kobako/src/gvl.rs +499 -76
  101. data/ext/kobako/src/handoff.rs +490 -0
  102. data/ext/kobako/src/lib.rs +10 -0
  103. data/ext/kobako/src/network.rs +5 -3
  104. data/ext/kobako/src/pinned_value.rs +28 -15
  105. data/ext/kobako/src/runtime/bridge.rs +32 -25
  106. data/ext/kobako/src/runtime.rs +74 -43
  107. data/lib/kobako/catalog/handles.rb +9 -5
  108. data/lib/kobako/codec/decoder.rb +1 -1
  109. data/lib/kobako/codec/state.rb +2 -18
  110. data/lib/kobako/codec/value_budget.rb +4 -4
  111. data/lib/kobako/codec.rb +5 -6
  112. data/lib/kobako/errors.rb +4 -7
  113. data/lib/kobako/filesystem.rb +1 -1
  114. data/lib/kobako/fork.rb +42 -0
  115. data/lib/kobako/handle.rb +1 -2
  116. data/lib/kobako/sandbox.rb +17 -36
  117. data/lib/kobako/sandbox_options.rb +7 -9
  118. data/lib/kobako/usage.rb +4 -2
  119. data/lib/kobako/version.rb +1 -1
  120. data/lib/kobako.rb +2 -2
  121. data/sig/kobako/catalog/handles.rbs +2 -0
  122. data/sig/kobako/codec/state.rbs +0 -4
  123. data/sig/kobako/codec/value_budget.rbs +1 -1
  124. data/sig/kobako/codec.rbs +2 -2
  125. data/sig/kobako/errors.rbs +0 -3
  126. data/sig/kobako/fork.rbs +17 -0
  127. data/sig/kobako/runtime.rbs +2 -2
  128. data/sig/kobako/sandbox.rbs +3 -12
  129. data/sig/kobako/sandbox_options.rbs +0 -2
  130. metadata +15 -4
  131. data/lib/kobako/pool.rb +0 -162
  132. data/sig/core/thread.rbs +0 -6
  133. data/sig/kobako/pool.rbs +0 -46
@@ -7,9 +7,27 @@
7
7
  //! path itself, which refuses a `..` or a link leading out of the
8
8
  //! directory whatever a caller hands over, and answers alike on every
9
9
  //! host, Windows among them.
10
+ //!
11
+ //! A Windows host differs from Linux in each row below, and a Bind answers
12
+ //! there as Linux does:
13
+ //!
14
+ //! | What Windows does apart | How a Bind answers | Where |
15
+ //! |---|---|---|
16
+ //! | spells names and link targets its own way | as a guest spells them | `unicode` |
17
+ //! | folds a name's case | the name the directory stores | `lookup` |
18
+ //! | names an entry by volume and file index | that pair as its identity | `to_kstat` |
19
+ //! | keeps no time a status changed | no such time | `to_kstat` |
20
+ //! | removes a link to a directory only as a directory | the link removed as itself | `unlink` |
21
+ //! | appends only by one write at the end | one such write | `BindFile::append` |
22
+ //! | sets a time only through a handle granted to | a handle reopened for it | `set_held_times` |
23
+ //! | refuses a file another process holds unshared | permission denied | `to_error` |
24
+ //!
25
+ //! A directory a process holds open cannot move there, so what a guest
26
+ //! would see of one moved is never staged on Windows.
10
27
 
11
28
  mod fid;
12
29
  mod lookup;
30
+ mod unicode;
13
31
  mod walk;
14
32
 
15
33
  use std::any::Any;
@@ -29,7 +47,8 @@ use super::{
29
47
  use crate::vfs::{
30
48
  generic_file_llseek, generic_read_dir, Dentry, DirContext, Identity, Inode, Whence,
31
49
  };
32
- use fid::{FidCache, OpenDirFid};
50
+ use fid::{FidOwner, OpenDirFid, FIDS};
51
+ use unicode::{to_guest_name, to_guest_target, to_host_name};
33
52
 
34
53
  /// A host directory and everything beneath it. What a guest writes lands
35
54
  /// on the host and lasts as long as the directory does.
@@ -38,25 +57,39 @@ use fid::{FidCache, OpenDirFid};
38
57
  /// about through the dentry it is handed, as Linux's 9p does. A directory is
39
58
  /// opened on the host when first asked, as 9p walks to a dentry's fid only
40
59
  /// when a call needs one. One a guest holds open holds a host descriptor; the
41
- /// others a walk asked about hold one only up to a bound.
60
+ /// others a walk asked about hold one only up to a bound every Bind shares.
42
61
  #[derive(Clone)]
43
62
  pub struct Bind {
44
- /// The host directory the Bind was made at.
63
+ /// The host directory the Bind was made at, let go before what its walks
64
+ /// kept.
45
65
  root: Arc<Dir>,
46
- fids: Arc<FidCache>,
66
+ fids: Arc<FidOwner>,
47
67
  /// Whether only the guest changes the directory, so a name it found
48
68
  /// stays as found without asking the host again.
49
69
  exclusive: bool,
50
70
  }
51
71
 
52
72
  impl Bind {
53
- /// Open the host directory at `path`, the one place this Filesystem
54
- /// reaches outside itself. One the host lets no one read is refused, so its
55
- /// root answers an open to read as any directory beneath it does, on every
56
- /// host alike.
73
+ /// Let go of every host directory the process's Binds keep for walks,
74
+ /// as a process about to fork does, so the child inherits none of them.
75
+ /// A directory a guest holds open stays with the guest.
76
+ pub fn drop_kept_directories() {
77
+ FIDS.drop_all();
78
+ }
79
+
80
+ /// Open the host directory at `path` now, the one place this Filesystem
81
+ /// reaches outside itself, so it stays the directory standing there as
82
+ /// it is made. One the host lets no one read is refused, so its root
83
+ /// answers an open to read as any directory beneath it does, on every host
84
+ /// alike. A host out of descriptors makes the directories Binds keep give
85
+ /// way first; a refusal answers the host's own errno.
57
86
  pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
58
- let root = Dir::open_ambient_dir(path, ambient_authority())?;
59
- may_read_dir(&root).map_err(|_| io::Error::from(io::ErrorKind::PermissionDenied))?;
87
+ let path = path.as_ref();
88
+ let root = FIDS.open_or_give_way(
89
+ || Dir::open_ambient_dir(path, ambient_authority()),
90
+ host_out_of_descriptors,
91
+ )?;
92
+ FIDS.open_or_give_way(|| readable(&root), host_out_of_descriptors)?;
60
93
  Ok(Self {
61
94
  root: Arc::new(root),
62
95
  fids: Arc::default(),
@@ -77,7 +110,7 @@ impl Bind {
77
110
  if dentry.is_root() {
78
111
  return Some(self.root.clone());
79
112
  }
80
- OpenDirFid::get(dentry).or_else(|| self.fids.get(dentry))
113
+ OpenDirFid::get(dentry).or_else(|| FIDS.get(dentry))
81
114
  }
82
115
 
83
116
  /// The host directory `dentry` names, as 9p's `v9fs_fid_lookup` finds a
@@ -106,12 +139,13 @@ impl Bind {
106
139
  .dir_metadata()
107
140
  .is_ok_and(|found| Identity::of(&to_kstat(found)) == recorded)
108
141
  };
142
+ FIDS.make_room();
109
143
  let dir = walk::walk(&above, &names)?;
110
144
  if !stands(&dir) {
111
145
  return Err(Errno::NotFound);
112
146
  }
113
147
  let dir = Arc::new(dir);
114
- self.fids.put(dentry, &dir);
148
+ FIDS.put(&self.fids, dentry, &dir);
115
149
  Ok(dir)
116
150
  }
117
151
 
@@ -205,14 +239,11 @@ fn entries_of(dir: &Dir) -> Result<Vec<DirEntry>, Errno> {
205
239
  use cap_std::fs::MetadataExt;
206
240
  dir.dir_metadata().map_err(to_error)?.dev()
207
241
  };
208
- dir.entries()
209
- .map_err(to_error)?
242
+ FIDS.open(|| dir.entries().map_err(to_error))?
210
243
  .map(|entry| {
244
+ crate::sched::stop_if_fatal()?;
211
245
  let entry = entry.map_err(to_error)?;
212
- let name = entry
213
- .file_name()
214
- .into_string()
215
- .map_err(|_| Errno::IllegalSequence)?;
246
+ let name = to_guest_name(entry.file_name())?;
216
247
  let listed = DirEntry::new(name, to_file_type(entry.file_type().map_err(to_error)?));
217
248
  #[cfg(unix)]
218
249
  let listed = {
@@ -250,32 +281,6 @@ fn nofollow_error(dir: &Dir, name: &str, err: io::Error) -> Errno {
250
281
  }
251
282
  }
252
283
 
253
- /// `name` as `cap_std` takes it. Windows reads some names as other names or as
254
- /// devices, so there one is refused rather than reached as an entry a Mount's
255
- /// Policy never saw.
256
- fn to_host_name(name: &str) -> Result<&str, Errno> {
257
- if cfg!(windows) && is_windows_alias(name) {
258
- return Err(Errno::InvalidInput);
259
- }
260
- Ok(name)
261
- }
262
-
263
- /// Whether Windows reads `name` as something else: a `\` as a separator, a `:`
264
- /// as a stream of a file, a trailing `.` or space as nothing, a wildcard as a
265
- /// pattern, or a device's name, whatever extension follows, as the device.
266
- fn is_windows_alias(name: &str) -> bool {
267
- const DEVICES: [&str; 33] = [
268
- "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", "CLOCK$", "COM0", "COM1", "COM2", "COM3",
269
- "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM¹", "COM²", "COM³", "LPT0", "LPT1",
270
- "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "LPT¹", "LPT²", "LPT³",
271
- ];
272
- let reserved = |c: char| c.is_ascii_control() || "\\:*?\"<>|".contains(c);
273
- let stem = name.split('.').next().unwrap_or(name).trim_end();
274
- name.contains(reserved)
275
- || name.ends_with(['.', ' '])
276
- || DEVICES.contains(&stem.to_uppercase().as_str())
277
- }
278
-
279
284
  /// The Errno a host failure names. cap-std's own refusal of a path
280
285
  /// leading out of the directory carries no OS code. A Bind hands it one name and
281
286
  /// no `..`, so that refusal only says a move carried the name out of the
@@ -325,9 +330,9 @@ fn to_special_file_type(_host: cap_std::fs::FileType) -> FileType {
325
330
  }
326
331
 
327
332
  /// What a host entry is, with the size the host reports. The host names
328
- /// its identity and link count everywhere, and its times on unix. Windows
329
- /// names the identity by volume and file index, which cap-std reads from the
330
- /// handle each of its stats opens.
333
+ /// its identity, link count, and times everywhere. Windows names the
334
+ /// identity by volume and file index, which cap-std reads from the handle
335
+ /// each of its stats opens, and keeps no time an entry's status changed.
331
336
  fn to_kstat(metadata: cap_std::fs::Metadata) -> Kstat {
332
337
  let file_type = to_file_type(metadata.file_type());
333
338
  let size = metadata.len();
@@ -349,6 +354,11 @@ fn to_kstat(metadata: cap_std::fs::Metadata) -> Kstat {
349
354
  Kstat::new(file_type, size)
350
355
  .with_identity(metadata.dev(), metadata.ino())
351
356
  .with_nlink(metadata.nlink())
357
+ .with_times(
358
+ metadata.accessed().ok().map(|at| at.into_std()),
359
+ metadata.modified().ok().map(|at| at.into_std()),
360
+ None,
361
+ )
352
362
  }
353
363
  }
354
364
 
@@ -369,6 +379,43 @@ fn to_host_time(time: Option<SetTime>) -> Option<SystemTimeSpec> {
369
379
  })
370
380
  }
371
381
 
382
+ /// Set `times` on the file `held` holds, as `futimens` does on any open
383
+ /// descriptor.
384
+ #[cfg(unix)]
385
+ fn set_held_times(held: &std::fs::File, times: std::fs::FileTimes) -> io::Result<()> {
386
+ held.set_times(times)
387
+ }
388
+
389
+ /// Set `times` on the file `held` holds, as `futimens` does on any open
390
+ /// descriptor. Windows sets a time only through a handle granted to change
391
+ /// attributes, which one opened to read lacks, so the time goes through a
392
+ /// handle reopened from `held` for that alone, reaching the same file
393
+ /// whatever now stands at its name.
394
+ #[cfg(windows)]
395
+ fn set_held_times(held: &std::fs::File, times: std::fs::FileTimes) -> io::Result<()> {
396
+ use std::os::windows::io::{AsRawHandle, FromRawHandle};
397
+ use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
398
+ use windows_sys::Win32::Storage::FileSystem::{
399
+ ReOpenFile, FILE_FLAG_BACKUP_SEMANTICS, FILE_SHARE_DELETE, FILE_SHARE_READ,
400
+ FILE_SHARE_WRITE, FILE_WRITE_ATTRIBUTES,
401
+ };
402
+
403
+ // SAFETY: `held` owns a live handle for the call's length; the handle
404
+ // ReOpenFile answers is a new one, owned from here by the File made of it.
405
+ let reopened = unsafe {
406
+ ReOpenFile(
407
+ held.as_raw_handle(),
408
+ FILE_WRITE_ATTRIBUTES,
409
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
410
+ FILE_FLAG_BACKUP_SEMANTICS,
411
+ )
412
+ };
413
+ if reopened == INVALID_HANDLE_VALUE {
414
+ return Err(io::Error::last_os_error());
415
+ }
416
+ unsafe { std::fs::File::from_raw_handle(reopened) }.set_times(times)
417
+ }
418
+
372
419
  /// The descriptors open on one file, and which were opened to write, as 9p
373
420
  /// keeps open fids on `i_private`.
374
421
  #[derive(Default)]
@@ -388,6 +435,16 @@ fn v9fs_fid_find_inode(dentry: &Dentry, writable: bool) -> Option<Arc<std::fs::F
388
435
  /// Open `name` in `dir` as `how` asks, made first where `create` says,
389
436
  /// refusing one that already stands.
390
437
  fn open_in(dir: &Dir, name: &str, how: &OpenHow, create: bool) -> Result<std::fs::File, Errno> {
438
+ FIDS.open(|| open_in_once(dir, name, how, create))
439
+ }
440
+
441
+ /// One try at `open_in`, which the host may refuse for want of descriptors.
442
+ fn open_in_once(
443
+ dir: &Dir,
444
+ name: &str,
445
+ how: &OpenHow,
446
+ create: bool,
447
+ ) -> Result<std::fs::File, Errno> {
391
448
  let writes = how.write || how.truncate || create;
392
449
  #[cfg(target_os = "linux")]
393
450
  if !create {
@@ -560,7 +617,7 @@ impl InodeOperations for BindRegular {
560
617
  if let Some(mtime) = attr.mtime {
561
618
  times = times.set_modified(attr.time_of(mtime));
562
619
  }
563
- return file.set_times(times).map_err(to_error);
620
+ return set_held_times(&file, times).map_err(to_error);
564
621
  }
565
622
  let (atime, mtime) = (to_host_time(attr.atime), to_host_time(attr.mtime));
566
623
  self.0.at(dentry, |dir, name| {
@@ -584,11 +641,11 @@ impl InodeOperations for BindLink {
584
641
  /// is one.
585
642
  fn get_link(&self, dentry: &Dentry) -> Result<String, Errno> {
586
643
  self.0.at(dentry, |dir, name| {
587
- dir.read_link_contents(name)
588
- .map_err(to_error)?
589
- .into_os_string()
590
- .into_string()
591
- .map_err(|_| Errno::IllegalSequence)
644
+ to_guest_target(
645
+ dir.read_link_contents(name)
646
+ .map_err(to_error)?
647
+ .into_os_string(),
648
+ )
592
649
  })
593
650
  }
594
651
  }
@@ -647,7 +704,10 @@ impl InodeOperations for Bind {
647
704
  may_read_dir(&fid)?;
648
705
  }
649
706
  OpenDirFid::set(dentry, &fid);
650
- Ok(Box::new(BindDir(fid, Rdir::default())))
707
+ Ok(Box::new(BindDir {
708
+ fid,
709
+ cache: Rdir::default(),
710
+ }))
651
711
  }
652
712
 
653
713
  /// A name still in lookup is looked up first, and any name is left to the
@@ -678,8 +738,12 @@ impl InodeOperations for Bind {
678
738
  self.at(dentry, |dir, name| dir.remove_dir(name).map_err(to_error))
679
739
  }
680
740
 
741
+ /// Whatever stands at the name and is no directory goes, a link to a
742
+ /// directory included, which Windows removes as a directory.
681
743
  fn unlink(&self, dentry: &Dentry) -> Result<(), Errno> {
682
- self.at(dentry, |dir, name| dir.remove_file(name).map_err(to_error))
744
+ self.at(dentry, |dir, name| {
745
+ dir.remove_file_or_symlink(name).map_err(to_error)
746
+ })
683
747
  }
684
748
 
685
749
  /// A host directory takes no lock the runtime's check of the source
@@ -712,7 +776,11 @@ impl InodeOperations for Bind {
712
776
  /// A host directory, open on the descriptor it holds, as 9p's `v9fs_dir_readdir`
713
777
  /// reads the fid in `private_data`, so it follows the directory wherever it
714
778
  /// moves.
715
- struct BindDir(Arc<Dir>, Rdir);
779
+ struct BindDir {
780
+ fid: Arc<Dir>,
781
+ /// What a listing began with, as 9p's `fid->rdir` holds it.
782
+ cache: Rdir,
783
+ }
716
784
 
717
785
  impl FileOperations for BindDir {
718
786
  fn llseek(
@@ -729,17 +797,21 @@ impl FileOperations for BindDir {
729
797
  generic_read_dir()
730
798
  }
731
799
 
800
+ fn has_iterate_shared(&self) -> bool {
801
+ true
802
+ }
803
+
732
804
  /// What a listing began with stays on the open directory until it ends, as
733
805
  /// 9p's `fid->rdir` holds what the server sent.
734
806
  fn iterate_shared(&mut self, dentry: &Dentry, ctx: &mut DirContext<'_>) -> Result<(), Errno> {
735
- let dir = self.0.clone();
736
- self.1.iterate_shared(dentry, ctx, || entries_of(&dir))
807
+ let dir = self.fid.clone();
808
+ self.cache.iterate_shared(dentry, ctx, || entries_of(&dir))
737
809
  }
738
810
 
739
811
  /// Make the host directory's names durable. Windows syncs no directory, so
740
812
  /// there the host answers for them itself.
741
813
  fn fsync(&mut self, _datasync: bool) -> Result<(), Errno> {
742
- sync_dir(&self.0)
814
+ sync_dir(&self.fid)
743
815
  }
744
816
  }
745
817
 
@@ -747,10 +819,37 @@ impl FileOperations for BindDir {
747
819
  /// which reads and syncs nothing, so the host judges reading it only here.
748
820
  #[cfg(unix)]
749
821
  fn open_to_read(dir: &Dir) -> Result<rustix::fd::OwnedFd, Errno> {
822
+ FIDS.open(|| open_to_read_once(dir).map_err(to_error))
823
+ }
824
+
825
+ /// One try at `open_to_read`, answering the host's own error.
826
+ #[cfg(unix)]
827
+ fn open_to_read_once(dir: &Dir) -> io::Result<rustix::fd::OwnedFd> {
750
828
  use rustix::fs::{openat, Mode, OFlags};
751
829
 
752
830
  let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC;
753
- openat(dir, ".", flags, Mode::empty()).map_err(|err| to_error(io::Error::from(err)))
831
+ openat(dir, ".", flags, Mode::empty()).map_err(io::Error::from)
832
+ }
833
+
834
+ /// Whether the host lets `dir` be read, answering the host's own error when
835
+ /// it does not.
836
+ #[cfg(unix)]
837
+ fn readable(dir: &Dir) -> io::Result<()> {
838
+ open_to_read_once(dir).map(drop)
839
+ }
840
+
841
+ #[cfg(not(unix))]
842
+ fn readable(_dir: &Dir) -> io::Result<()> {
843
+ Ok(())
844
+ }
845
+
846
+ /// Whether the host refused for want of descriptors, its process's or its
847
+ /// machine's.
848
+ fn host_out_of_descriptors(err: &io::Error) -> bool {
849
+ matches!(
850
+ Errno::from_io_error(err),
851
+ Errno::TooManyOpenFiles | Errno::TooManyOpenFilesInSystem
852
+ )
754
853
  }
755
854
 
756
855
  #[cfg(unix)]
@@ -783,11 +882,16 @@ struct BindFile {
783
882
  }
784
883
 
785
884
  impl BindFile {
786
- /// Windows has no append to switch one handle to for a single write,
787
- /// so an append that could land over another writer's is refused.
788
- #[cfg(not(unix))]
789
- fn append(&mut self, _iocb: &mut Kiocb, _buf: &[u8]) -> Result<usize, Errno> {
790
- Err(Errno::Unsupported)
885
+ /// The host places the write at the file's end: a write at the offset of
886
+ /// all ones bits does, as a handle opened with `FILE_APPEND_DATA` would,
887
+ /// so another writer's append lands before or after it, never over it.
888
+ #[cfg(windows)]
889
+ fn append(&mut self, iocb: &mut Kiocb, buf: &[u8]) -> Result<usize, Errno> {
890
+ use std::os::windows::fs::FileExt;
891
+
892
+ let written = self.file.seek_write(buf, u64::MAX).map_err(to_error)?;
893
+ iocb.pos = (&*self.file).stream_position().map_err(to_error)?;
894
+ Ok(written)
791
895
  }
792
896
 
793
897
  /// The host places the write at the file's end as `O_APPEND` does, so
@@ -857,7 +961,7 @@ impl FileOperations for BindFile {
857
961
 
858
962
  /// Reserve the room on the host, as `v9fs_file_fallocate` asks its server. Only
859
963
  /// Linux grows a file in one step without shortening one a peer just grew, so
860
- /// elsewhere this refuses, as an append that cannot land in one step does.
964
+ /// elsewhere this refuses rather than take two steps a peer could land between.
861
965
  #[cfg(target_os = "linux")]
862
966
  fn fallocate(&mut self, offset: u64, len: u64) -> Result<(), Errno> {
863
967
  let flags = rustix::fs::FallocateFlags::empty();
@@ -875,13 +979,11 @@ mod tests {
875
979
  use crate::vfs::kern_path::{kern_path, KernPath};
876
980
 
877
981
  /// A Bind reports times only where the host names them.
878
- #[cfg(unix)]
879
982
  mod set_times {
880
983
  use super::*;
881
984
  use crate::filesystem::{Overlay, Tmpfs};
882
985
  use crate::mount::{Access, Mount};
883
- use crate::vfs::kern_path::filp_open;
884
- use crate::vfs::{do_utimes_fd, do_utimes_path, vfs_fstatat, OpenHow, Path as VfsPath};
986
+ use crate::vfs::{do_utimes_path, vfs_fstatat, Path as VfsPath};
885
987
 
886
988
  /// One second past the Unix epoch, which no clock is at.
887
989
  fn moment() -> std::time::SystemTime {
@@ -961,8 +1063,8 @@ mod tests {
961
1063
  assert_eq!(
962
1064
  (answers, host_modified(&host.0.join("dir/file.txt"))),
963
1065
  ([(set, set); 3], set),
964
- "vfs::do_utimes_pathon a file and a directory of a Tmpfs, a Bind, and an Overlay must \
965
- keep the time, a Bind's on the host"
1066
+ "a modified time set on a file and a directory of a Tmpfs, a Bind, and an Overlay \
1067
+ must read back from a stat, and a Bind's must reach its host entry"
966
1068
  );
967
1069
  }
968
1070
 
@@ -975,8 +1077,8 @@ mod tests {
975
1077
  assert_eq!(
976
1078
  (seen, host_modified(&host.0.join("dir")) == before),
977
1079
  (Some(moment()), true),
978
- "vfs::do_utimes_pathon a directory through an Overlay must show the time and leave the \
979
- lower Layer's directory as it was"
1080
+ "a modified time set on a directory through an Overlay must read back from a stat and \
1081
+ leave the lower Layer's directory as it was"
980
1082
  );
981
1083
  }
982
1084
 
@@ -986,7 +1088,7 @@ mod tests {
986
1088
  #[test]
987
1089
  fn a_link_keeps_its_own_times() {
988
1090
  let host = host_with_a_file("link-time");
989
- std::os::unix::fs::symlink("dir", host.0.join("link")).expect("the link must be made");
1091
+ crate::filesystem::testing::symlink("dir", host.0.join("link"));
990
1092
  assert_eq!(
991
1093
  do_utimes_path(
992
1094
  &Arc::default(),
@@ -996,7 +1098,7 @@ mod tests {
996
1098
  &set_modified(),
997
1099
  ),
998
1100
  Err(Errno::Unsupported),
999
- "vfs::do_utimes_pathfollowing no link of a Bind's link must answer ENOTSUP"
1101
+ "setting the times of a Bind's link without following it must answer ENOTSUP"
1000
1102
  );
1001
1103
  }
1002
1104
 
@@ -1004,6 +1106,9 @@ mod tests {
1004
1106
  // @behavior FS-188
1005
1107
  #[test]
1006
1108
  fn a_time_set_through_a_descriptor_reaches_the_file_it_holds() {
1109
+ use crate::vfs::kern_path::filp_open;
1110
+ use crate::vfs::{do_utimes_fd, OpenHow};
1111
+
1007
1112
  let host = host_with_a_file("held-time");
1008
1113
  let root = root_of(Arc::new(bind_of(&host)));
1009
1114
  let how = OpenHow {
@@ -1021,8 +1126,8 @@ mod tests {
1021
1126
  assert_eq!(
1022
1127
  (answer, held_time, host_modified(&file) == other_before),
1023
1128
  (Ok(()), Some(moment()), true),
1024
- "vfs::do_utimes_fd through a Bind's descriptor must set the file it holds, and leave \
1025
- what took its name"
1129
+ "a time set through a Bind's descriptor must reach the file it holds, and leave what \
1130
+ took its name"
1026
1131
  );
1027
1132
  }
1028
1133
  }
@@ -1056,7 +1161,6 @@ mod tests {
1056
1161
 
1057
1162
  /// A Bind over `depth` nested directories each named `d`, with the file
1058
1163
  /// `f` at the bottom, and the path to that file.
1059
- #[cfg(unix)]
1060
1164
  fn nested_tree(host: &HostDir, depth: usize) -> (Arc<Bind>, String) {
1061
1165
  let path = vec!["d"; depth].join("/");
1062
1166
  fs::create_dir_all(host.0.join(&path)).expect("the host tree must be made");
@@ -1096,33 +1200,58 @@ mod tests {
1096
1200
  );
1097
1201
  }
1098
1202
 
1099
- // Counted on the Bind, as a count of the process's descriptors would see
1100
- // every other test's. Past the bound the walk still lands, so nothing a
1101
- // guest reaches depends on what was kept.
1203
+ // Counted on the cache, as a count of the process's descriptors would see
1204
+ // every other test's; the bound holds for whatever they keep. Past the
1205
+ // bound each walk still lands, so nothing a guest reaches depends on what
1206
+ // was kept.
1102
1207
  // @behavior FS-151
1103
- #[cfg(unix)]
1104
1208
  #[test]
1105
- fn a_walk_keeps_a_bounded_number_of_host_directories_open() {
1209
+ fn the_binds_of_a_process_keep_a_bounded_number_of_host_directories_open() {
1106
1210
  use crate::vfs::{self, OpenHow, Path as VfsPath};
1107
- let host = HostDir::new("bounded-fids");
1108
- let (bind, file) = nested_tree(&host, 200);
1109
- let mount = crate::mount::Mount::new(
1110
- "/data",
1111
- crate::filesystem::Filesystem::new(bind.clone()).expect("the instance must stand"),
1112
- crate::mount::Access::Read,
1113
- )
1114
- .expect("/data is a guest path");
1115
- let root = VfsPath::root(mount.mnt());
1116
1211
  let read = OpenHow {
1117
1212
  read: true,
1118
1213
  ..OpenHow::default()
1119
1214
  };
1120
- let opened = vfs::kern_path::filp_open(&Arc::default(), &root, &file, &read);
1215
+ let hosts = [
1216
+ HostDir::new("bounded-fids-a"),
1217
+ HostDir::new("bounded-fids-b"),
1218
+ ];
1219
+ let opened = hosts.iter().map(|host| {
1220
+ let (bind, file) = nested_tree(host, 100);
1221
+ let mount = crate::mount::Mount::new(
1222
+ "/data",
1223
+ crate::filesystem::Filesystem::new(bind.clone()).expect("the instance must stand"),
1224
+ crate::mount::Access::Read,
1225
+ )
1226
+ .expect("/data is a guest path");
1227
+ let root = VfsPath::root(mount.mnt());
1228
+ let file = vfs::kern_path::filp_open(&Arc::default(), &root, &file, &read);
1229
+ (file.is_ok(), bind)
1230
+ });
1231
+ let (opened, binds): (Vec<_>, Vec<_>) = opened.unzip();
1121
1232
  assert!(
1122
- opened.is_ok() && bind.fids.len() <= 64,
1123
- "vfs::do_file_open 200 directories beneath a Bind must land and keep at most 64 of \
1124
- them open, keeping {}",
1125
- bind.fids.len()
1233
+ opened.iter().all(|&opened| opened) && FIDS.len() <= 64,
1234
+ "an open of a file 100 directories beneath each of two binds must land, the process \
1235
+ keeping at most 64 of those directories open, keeping {}",
1236
+ FIDS.len()
1237
+ );
1238
+ drop(binds);
1239
+ }
1240
+
1241
+ // @behavior FS-221
1242
+ #[test]
1243
+ fn a_bind_let_go_closes_the_directories_its_walks_kept() {
1244
+ let host = HostDir::new("released-fids");
1245
+ let (bind, file) = nested_tree(&host, 8);
1246
+ let owner = bind.fids.id();
1247
+ let root = kern_path(bind);
1248
+ root.vfs_lstat(&file).expect("the file must stand");
1249
+ let kept = FIDS.kept_by(owner);
1250
+ drop(root);
1251
+ assert_eq!(
1252
+ (kept > 0, FIDS.kept_by(owner)),
1253
+ (true, 0),
1254
+ "a Bind let go after a walk 8 directories deep must close every directory it kept"
1126
1255
  );
1127
1256
  }
1128
1257
 
@@ -1418,6 +1547,42 @@ mod tests {
1418
1547
  );
1419
1548
  }
1420
1549
 
1550
+ // A Windows host refuses to move a directory a process holds open.
1551
+ // @behavior FS-225
1552
+ #[cfg(unix)]
1553
+ #[test]
1554
+ fn a_bind_reads_the_directory_standing_where_it_was_made() {
1555
+ use crate::mount::Mount;
1556
+ use crate::vfs::{self, OpenHow};
1557
+ let host = HostDir::new("made-over");
1558
+ let (made, moved) = (host.0.join("root"), host.0.join("moved"));
1559
+ fs::create_dir_all(made.join("d0")).expect("the host directory must be made");
1560
+ fs::write(made.join("d0/note.txt"), "hello").expect("the host file must be written");
1561
+ let filesystem =
1562
+ crate::filesystem::Filesystem::new(Bind::new(&made).expect("the root must open"))
1563
+ .expect("the instance must stand");
1564
+ let mount = Mount::new("/data", filesystem, crate::mount::Access::Read)
1565
+ .expect("/data is a guest path");
1566
+ fs::rename(&made, &moved).expect("the host must move it");
1567
+ fs::create_dir_all(made.join("d0")).expect("the host must make another");
1568
+ fs::write(made.join("d0/note.txt"), "other").expect("the other file must be written");
1569
+ let read = OpenHow {
1570
+ read: true,
1571
+ ..OpenHow::default()
1572
+ };
1573
+ let root = vfs::Path::root(mount.mnt());
1574
+ let mut note = vfs::kern_path::filp_open(&Arc::default(), &root, "d0/note.txt", &read)
1575
+ .unwrap_or_else(|err| panic!("the note must open, got {err:?}"));
1576
+ let mut text = [0; 5];
1577
+ let read = note.read(&mut text);
1578
+ assert_eq!(
1579
+ (read, &text),
1580
+ (Ok(5), b"hello"),
1581
+ "a file read through a Bind whose host directory was moved away and replaced by \
1582
+ another must read the directory the Bind was made over"
1583
+ );
1584
+ }
1585
+
1421
1586
  /// A Policy refusing everything beneath `/data/refused`.
1422
1587
  #[cfg(unix)]
1423
1588
  struct RefusesRefused;
@@ -1480,7 +1645,6 @@ mod tests {
1480
1645
 
1481
1646
  /// The roots of a Tmpfs, a Bind, and an Overlay, each holding a five byte
1482
1647
  /// `f`, by name.
1483
- #[cfg(unix)]
1484
1648
  fn each_holding_five_bytes(host: &HostDir) -> [(&'static str, crate::vfs::Path); 3] {
1485
1649
  use crate::filesystem::Filesystem;
1486
1650
  use crate::filesystem::{Overlay, Tmpfs};
@@ -1514,7 +1678,6 @@ mod tests {
1514
1678
  }
1515
1679
 
1516
1680
  // @behavior FS-141
1517
- #[cfg(unix)]
1518
1681
  #[test]
1519
1682
  fn a_file_removed_while_open_still_reports_itself() {
1520
1683
  use crate::vfs::{self, OpenHow};
@@ -1536,14 +1699,13 @@ mod tests {
1536
1699
  &buf
1537
1700
  ),
1538
1701
  (Some(5), Ok(5), b"hello"),
1539
- "File::getattr and File::pread of a file whose name \
1540
- vfs::filename_unlinkat removed on a {name} must answer what it holds"
1702
+ "a stat and a read of an open file on a {name} whose name was removed must \
1703
+ answer what it holds"
1541
1704
  );
1542
1705
  }
1543
1706
  }
1544
1707
 
1545
1708
  // @behavior FS-142
1546
- #[cfg(unix)]
1547
1709
  #[test]
1548
1710
  fn a_file_removed_while_open_can_still_be_sized() {
1549
1711
  use crate::vfs::{self, OpenHow};
@@ -1564,8 +1726,8 @@ mod tests {
1564
1726
  file.getattr().map(|found| found.size).ok()
1565
1727
  ),
1566
1728
  (Ok(()), Some(2)),
1567
- "File::truncate of a file whose name vfs::filename_unlinkat removed on a {name} \
1568
- must size what it holds"
1729
+ "a truncate of an open file on a {name} whose name was removed must size what it \
1730
+ holds"
1569
1731
  );
1570
1732
  }
1571
1733
  }
@@ -1573,7 +1735,6 @@ mod tests {
1573
1735
  // A dentry the host replaced is dropped by its identity, so the path
1574
1736
  // reaches the new file while the open one keeps its own descriptor.
1575
1737
  // @behavior FS-143
1576
- #[cfg(unix)]
1577
1738
  #[test]
1578
1739
  fn a_file_replaced_while_open_answers_apart_from_its_path() {
1579
1740
  use crate::vfs::{self, OpenHow};
@@ -1596,8 +1757,8 @@ mod tests {
1596
1757
  file.getattr().map(|found| found.size).ok()
1597
1758
  ),
1598
1759
  (Some(7), Some(5)),
1599
- "vfs::vfs_fstatat of a path the host replaced under an open File must answer the new \
1600
- file, and File::getattr the one it holds"
1760
+ "a stat of a path the host replaced under an open file must answer the new file, and \
1761
+ a stat of the open file the one it holds"
1601
1762
  );
1602
1763
  }
1603
1764
 
@@ -1952,36 +2113,6 @@ mod tests {
1952
2113
  );
1953
2114
  }
1954
2115
 
1955
- // The file is opened to write, so only the refusal keeps the append
1956
- // from taking the two steps another writer could land between.
1957
- // @behavior FS-093
1958
- #[cfg(windows)]
1959
- #[test]
1960
- fn a_directory_on_windows_refuses_to_append() {
1961
- let host = HostDir::new("append");
1962
- fs::write(host.0.join("f"), "x").expect("the host file must be written");
1963
- let directory = bind_host(&host.0);
1964
- let mut file = directory
1965
- .open(
1966
- "f",
1967
- &OpenHow {
1968
- write: true,
1969
- ..OpenHow::default()
1970
- },
1971
- )
1972
- .expect("the host file must open");
1973
- assert_eq!(
1974
- (
1975
- file.write_iter(&mut Kiocb::new(0).with_append(), b"y")
1976
- .err(),
1977
- fs::read(host.0.join("f")).expect("the host file must read")
1978
- ),
1979
- (Some(Errno::Unsupported), b"x".to_vec()),
1980
- "an append through a Bind file on Windows must be refused as unsupported and \
1981
- leave the file as it was"
1982
- );
1983
- }
1984
-
1985
2116
  // The host file exists beneath `d`, so only the refusal can keep the
1986
2117
  // open from reaching it.
1987
2118
  // @behavior FS-029
@@ -2002,41 +2133,6 @@ mod tests {
2002
2133
  );
2003
2134
  }
2004
2135
 
2005
- // Judged on every host, as only Windows's own CI reaches the refusal, and
2006
- // what the host would do with each name is what no other host can show.
2007
- // @behavior FS-153
2008
- #[test]
2009
- fn a_name_windows_reads_as_another_is_told_apart() {
2010
- let aliases = [
2011
- "secret.",
2012
- "secret ",
2013
- "file:stream",
2014
- r"d\f",
2015
- "con",
2016
- "NUL.txt",
2017
- "conin$",
2018
- "com1 .log",
2019
- "a?",
2020
- "a*",
2021
- "a<",
2022
- "a|",
2023
- "a\"",
2024
- "a\u{1}",
2025
- ];
2026
- let plain = ["secret", "file.txt", "console", "com10", ".hidden", "a.b.c"];
2027
- assert_eq!(
2028
- (
2029
- aliases
2030
- .iter()
2031
- .filter(|name| !is_windows_alias(name))
2032
- .count(),
2033
- plain.iter().filter(|name| is_windows_alias(name)).count(),
2034
- ),
2035
- (0, 0),
2036
- "is_windows_alias must name every spelling Windows reads as another, and no plain name"
2037
- );
2038
- }
2039
-
2040
2136
  // @behavior FS-153
2041
2137
  #[cfg(windows)]
2042
2138
  #[test]
@@ -2080,13 +2176,14 @@ mod tests {
2080
2176
 
2081
2177
  // Which offset a host refuses depends on its filesystem: tmpfs, XFS and
2082
2178
  // overlay keep files up to `i64::MAX`. The host's own EFBIG, 27 on Linux
2083
- // and macOS alike, is what the Bind must name.
2179
+ // and macOS alike and `ERROR_FILE_TOO_LARGE` on Windows, is what the Bind
2180
+ // must name.
2084
2181
  // @behavior FS-068
2085
- #[cfg(any(target_os = "linux", target_os = "macos"))]
2086
2182
  #[test]
2087
2183
  fn a_directory_answers_a_host_file_too_large_as_too_large() {
2184
+ let too_large = if cfg!(windows) { 223 } else { 27 };
2088
2185
  assert_eq!(
2089
- to_error(io::Error::from_raw_os_error(27)),
2186
+ to_error(io::Error::from_raw_os_error(too_large)),
2090
2187
  Errno::FileTooLarge,
2091
2188
  "a host EFBIG through Bind's error mapping must fail as FileTooLarge, \
2092
2189
  not as an unnamed failure"
@@ -2236,7 +2333,6 @@ mod tests {
2236
2333
  // Eviction leaves a walk to reach a directory from one far above it, so only
2237
2334
  // a path past what the host takes in one call shows it goes on by name.
2238
2335
  // @behavior FS-190
2239
- #[cfg(unix)]
2240
2336
  #[test]
2241
2337
  fn a_directory_past_the_hosts_path_limit_is_reached() {
2242
2338
  let host = HostDir::new("past-path-max");
@@ -2380,18 +2476,11 @@ mod tests {
2380
2476
  .expect("the host directory must list")
2381
2477
  .map(|entry| entry.expect("the entry must read").file_name())
2382
2478
  .collect();
2383
- // Windows reports no inode, so nothing ties `A` to the stored `a` and
2384
- // the spelling is refused rather than followed.
2385
- let answered = match cfg!(windows) {
2386
- true => Err(Errno::PermissionDenied),
2387
- false => Ok(()),
2388
- };
2389
2479
  assert_eq!(
2390
2480
  (renamed, stored),
2391
- (answered, vec![std::ffi::OsString::from("a")]),
2392
- "vfs::filename_renameat2 of `a` to `A` on a Bind of a host that folds case must \
2393
- leave `a` spelled as it was, as vfs_rename finds one entry, refusing it only \
2394
- where the host ties no spelling to the entry"
2481
+ (Ok(()), vec![std::ffi::OsString::from("a")]),
2482
+ "a rename of `a` to `A` on a Bind of a host that folds case must succeed and leave \
2483
+ `a` spelled as it was, since both spellings name one entry"
2395
2484
  );
2396
2485
  }
2397
2486
 
@@ -2433,16 +2522,24 @@ mod tests {
2433
2522
  }
2434
2523
  }
2435
2524
 
2436
- // Only Linux keeps a name that is not UTF-8; macOS refuses to make one.
2525
+ // Linux keeps a name of any bytes and Windows one of a lone UTF-16
2526
+ // surrogate, which no UTF-8 spells; macOS refuses to make either.
2437
2527
  // @behavior FS-066
2438
- #[cfg(target_os = "linux")]
2528
+ #[cfg(not(target_os = "macos"))]
2439
2529
  #[test]
2440
2530
  fn a_directory_refuses_to_list_a_host_name_that_is_not_utf8() {
2441
- use std::os::unix::ffi::OsStrExt;
2442
-
2531
+ #[cfg(unix)]
2532
+ let name = {
2533
+ use std::os::unix::ffi::OsStrExt;
2534
+ std::ffi::OsStr::from_bytes(b"\xff").to_os_string()
2535
+ };
2536
+ #[cfg(windows)]
2537
+ let name = {
2538
+ use std::os::windows::ffi::OsStringExt;
2539
+ std::ffi::OsString::from_wide(&[0xD800])
2540
+ };
2443
2541
  let host = HostDir::new("ilseq");
2444
- fs::write(host.0.join(std::ffi::OsStr::from_bytes(b"\xff")), "")
2445
- .expect("the host file must be written");
2542
+ fs::write(host.0.join(name), "").expect("the host file must be written");
2446
2543
  let directory = bind_host(&host.0);
2447
2544
  assert_eq!(
2448
2545
  directory.iterate_dir().map(drop),
@@ -2455,14 +2552,16 @@ mod tests {
2455
2552
  // The host file only reads, so a host open asking to write, as one that
2456
2553
  // creates must, would be refused where nothing is to be created.
2457
2554
  // @behavior FS-064
2458
- #[cfg(unix)]
2459
2555
  #[test]
2460
2556
  fn a_directory_opens_a_file_already_there_without_writing_to_create_it() {
2461
- use std::os::unix::fs::PermissionsExt;
2462
2557
  let host = HostDir::new("create-existing");
2463
- fs::write(host.0.join("note"), "x").expect("the host file must be written");
2464
- fs::set_permissions(host.0.join("note"), fs::Permissions::from_mode(0o444))
2465
- .expect("the host file must become read-only");
2558
+ let note = host.0.join("note");
2559
+ fs::write(&note, "x").expect("the host file must be written");
2560
+ let mut read_only = fs::metadata(&note)
2561
+ .expect("the host file must stand")
2562
+ .permissions();
2563
+ read_only.set_readonly(true);
2564
+ fs::set_permissions(&note, read_only).expect("the host file must become read-only");
2466
2565
  let directory = bind_host(&host.0);
2467
2566
  let creates = OpenHow {
2468
2567
  read: true,
@@ -2483,12 +2582,11 @@ mod tests {
2483
2582
  // The link's target is a readable file, so only the refusal of the
2484
2583
  // link itself keeps the open from reaching it.
2485
2584
  // @behavior FS-047
2486
- #[cfg(unix)]
2487
2585
  #[test]
2488
2586
  fn a_directory_opens_no_link() {
2489
2587
  let host = HostDir::new("nofollow");
2490
2588
  fs::write(host.0.join("target"), "x").expect("the host file must be written");
2491
- std::os::unix::fs::symlink("target", host.0.join("link")).expect("the link must be made");
2589
+ crate::filesystem::testing::symlink("target", host.0.join("link"));
2492
2590
  let opened = bind_host(&host.0)
2493
2591
  .open(
2494
2592
  "link",
@@ -2508,12 +2606,11 @@ mod tests {
2508
2606
  // The VFS refuses a link it found before asking the Bind, so only the
2509
2607
  // Bind's own open sees a link the host put in place after the lookup.
2510
2608
  // @behavior FS-047
2511
- #[cfg(unix)]
2512
2609
  #[test]
2513
2610
  fn a_directory_refuses_a_link_put_in_place_of_what_it_opens() {
2514
2611
  let host = HostDir::new("nofollow-swapped");
2515
2612
  fs::write(host.0.join("target"), "x").expect("the host file must be written");
2516
- std::os::unix::fs::symlink("target", host.0.join("link")).expect("the link must be made");
2613
+ crate::filesystem::testing::symlink("target", host.0.join("link"));
2517
2614
  let dir = Dir::open_ambient_dir(&host.0, ambient_authority()).expect("the host directory");
2518
2615
  let read = OpenHow {
2519
2616
  read: true,
@@ -2530,12 +2627,11 @@ mod tests {
2530
2627
  // The target's five bytes would show as the link's size if a lookup
2531
2628
  // that follows none still followed it.
2532
2629
  // @behavior FS-048
2533
- #[cfg(unix)]
2534
2630
  #[test]
2535
2631
  fn a_directory_reports_a_link_a_lookup_does_not_follow_as_a_link() {
2536
2632
  let host = HostDir::new("lstat");
2537
2633
  fs::write(host.0.join("target"), "hello").expect("the host file must be written");
2538
- std::os::unix::fs::symlink("target", host.0.join("link")).expect("the link must be made");
2634
+ crate::filesystem::testing::symlink("target", host.0.join("link"));
2539
2635
  let directory = bind_host(&host.0);
2540
2636
  let listed = directory
2541
2637
  .iterate_dir()
@@ -2588,22 +2684,19 @@ mod tests {
2588
2684
 
2589
2685
  /// A host directory holding `dir/sub/y` and `secret`, with `dir/in`
2590
2686
  /// linking to `sub` and `dir/up` to `../secret`.
2591
- #[cfg(unix)]
2592
2687
  fn make_links(name: &str) -> HostDir {
2593
2688
  let host = HostDir::new(name);
2594
2689
  fs::create_dir_all(host.0.join("dir/sub")).expect("the host directory must be created");
2595
2690
  fs::write(host.0.join("dir/sub/y"), "inner").expect("the inner file must be written");
2596
2691
  fs::write(host.0.join("secret"), "outer").expect("the outer file must be written");
2597
- std::os::unix::fs::symlink("sub", host.0.join("dir/in")).expect("the link must be made");
2598
- std::os::unix::fs::symlink("../secret", host.0.join("dir/up"))
2599
- .expect("the link must be made");
2692
+ crate::filesystem::testing::symlink("sub", host.0.join("dir/in"));
2693
+ crate::filesystem::testing::symlink("../secret", host.0.join("dir/up"));
2600
2694
  host
2601
2695
  }
2602
2696
 
2603
2697
  // The link leads to a directory inside the host directory, so only
2604
2698
  // refusing the link itself keeps it from being opened.
2605
2699
  // @behavior FS-099
2606
- #[cfg(unix)]
2607
2700
  #[test]
2608
2701
  fn a_directory_opens_no_link_as_a_directory_where_asked_not_to_follow() {
2609
2702
  let host = make_links("open-dir-nofollow");
@@ -2617,7 +2710,6 @@ mod tests {
2617
2710
  }
2618
2711
 
2619
2712
  // @behavior FS-114
2620
- #[cfg(unix)]
2621
2713
  #[test]
2622
2714
  fn a_directory_reads_where_a_link_points() {
2623
2715
  let host = make_links("read-link");
@@ -2631,15 +2723,76 @@ mod tests {
2631
2723
  );
2632
2724
  }
2633
2725
 
2726
+ // Windows removes a link to a directory only as a directory, so a file's
2727
+ // removal alone would leave it standing there.
2728
+ // @behavior FS-240
2729
+ #[test]
2730
+ fn a_directory_removes_a_link_to_a_directory_as_itself() {
2731
+ let host = make_links("unlink-dir-link");
2732
+ let directory = bind_host(&host.0);
2733
+ let dir = directory.open_dir("dir").expect("the directory must open");
2734
+ assert_eq!(
2735
+ (
2736
+ dir.vfs_unlink("in"),
2737
+ host.0.join("dir/in").symlink_metadata().is_err(),
2738
+ host.0.join("dir/sub/y").is_file()
2739
+ ),
2740
+ (Ok(()), true, true),
2741
+ "vfs_unlink of a link to a directory beneath a Bind must remove the link and leave \
2742
+ the directory it leads to and what that holds"
2743
+ );
2744
+ }
2745
+
2746
+ // A link to a directory is no directory, so rename(2) replaces it as it
2747
+ // would a file; a host taking it for its target would refuse the move.
2748
+ // @behavior FS-241
2749
+ #[test]
2750
+ fn a_directory_moves_a_file_onto_a_link_to_a_directory() {
2751
+ let host = make_links("rename-onto-dir-link");
2752
+ fs::write(host.0.join("dir/f"), "moved").expect("the host file must be written");
2753
+ let directory = bind_host(&host.0);
2754
+ let dir = directory.open_dir("dir").expect("the directory must open");
2755
+ assert_eq!(
2756
+ (
2757
+ dir.rename("f", &dir, "in"),
2758
+ fs::read_to_string(host.0.join("dir/in")).ok(),
2759
+ host.0.join("dir/sub/y").is_file()
2760
+ ),
2761
+ (Ok(()), Some("moved".to_string()), true),
2762
+ "a rename beneath a Bind of a file onto a link to a directory must put the file \
2763
+ in the link's place and leave the directory it led to"
2764
+ );
2765
+ }
2766
+
2767
+ // Windows stores each link's target with `\`, so only the Bind's reading
2768
+ // spells it as a guest path.
2769
+ // @behavior FS-239
2770
+ #[cfg(windows)]
2771
+ #[test]
2772
+ fn a_directory_reads_a_windows_link_as_a_guest_path() {
2773
+ let host = make_links("read-windows-link");
2774
+ crate::filesystem::testing::symlink(host.0.join("secret"), host.0.join("dir/far"));
2775
+ let directory = bind_host(&host.0);
2776
+ let dir = directory.open_dir("dir").expect("the directory must open");
2777
+ let far = dir.vfs_readlink("far").expect("the link must read");
2778
+ assert_eq!(
2779
+ (
2780
+ dir.vfs_readlink("up"),
2781
+ far.starts_with('/') && !far.contains('\\') && far.ends_with("/secret")
2782
+ ),
2783
+ (Ok("../secret".to_string()), true),
2784
+ "vfs_readlink of a Windows host link beneath a Bind must read `..\\secret` as \
2785
+ `../secret`, and a target on a drive as a path from `/`, not `{far}`"
2786
+ );
2787
+ }
2788
+
2634
2789
  // @behavior FS-007
2635
- #[cfg(unix)]
2636
2790
  #[test]
2637
2791
  fn a_directory_reaches_nothing_outside_its_host_directory() {
2638
2792
  let outside = HostDir::new("outside");
2639
2793
  fs::write(outside.0.join("secret"), "host").expect("the outside file must be written");
2640
2794
  let host = HostDir::new("confined");
2641
- std::os::unix::fs::symlink(outside.0.join("secret"), host.0.join("escape"))
2642
- .expect("the link must be created");
2795
+ crate::filesystem::testing::symlink(outside.0.join("secret"), host.0.join("escape"));
2643
2796
 
2644
2797
  let directory = bind_host(&host.0);
2645
2798
  assert!(
@@ -2656,22 +2809,44 @@ mod tests {
2656
2809
  );
2657
2810
  }
2658
2811
 
2659
- // @behavior FS-071
2812
+ /// The device and inode numbers the host gives `path`.
2660
2813
  #[cfg(unix)]
2661
- #[test]
2662
- fn a_directory_reports_the_identity_its_host_gives_a_path() {
2814
+ fn host_identity(path: &Path) -> (u64, u64) {
2663
2815
  use std::os::unix::fs::MetadataExt;
2816
+ let found = fs::metadata(path).expect("the host must stat it");
2817
+ (found.dev(), found.ino())
2818
+ }
2819
+
2820
+ /// The volume serial number and file index the host gives `path`, which
2821
+ /// Windows names only on a handle opened to it; std reads them on nightly
2822
+ /// alone.
2823
+ #[cfg(windows)]
2824
+ fn host_identity(path: &Path) -> (u64, u64) {
2825
+ use cap_fs_ext::MetadataExt;
2826
+ let parent = cap_std::fs::Dir::open_ambient_dir(
2827
+ path.parent().expect("the path has a parent"),
2828
+ cap_std::ambient_authority(),
2829
+ )
2830
+ .expect("the host directory must open");
2831
+ let found = parent
2832
+ .metadata(path.file_name().expect("the path names an entry"))
2833
+ .expect("the host must stat it");
2834
+ (found.dev(), found.ino())
2835
+ }
2664
2836
 
2837
+ // @behavior FS-071
2838
+ #[test]
2839
+ fn a_directory_reports_the_identity_its_host_gives_a_path() {
2665
2840
  let host = HostDir::new("identity");
2666
2841
  fs::create_dir(host.0.join("dir")).expect("the host directory must be made");
2667
- let expected = fs::metadata(host.0.join("dir")).expect("the host must stat it");
2842
+ let expected = host_identity(&host.0.join("dir"));
2668
2843
  let directory = bind_host(&host.0);
2669
2844
  let reported = directory
2670
2845
  .vfs_lstat("dir")
2671
2846
  .expect("the directory must stand");
2672
2847
  assert_eq!(
2673
2848
  (reported.dev, reported.ino),
2674
- (expected.dev(), expected.ino()),
2849
+ expected,
2675
2850
  "a host directory beneath a Bind looked up through vfs_lstat must carry the device \
2676
2851
  and inode numbers the host reports"
2677
2852
  );
@@ -2681,7 +2856,6 @@ mod tests {
2681
2856
  // length, then write there) loses about half the bytes to the other
2682
2857
  // handle's writes, so only an append the host places keeps them all.
2683
2858
  // @behavior FS-069
2684
- #[cfg(unix)]
2685
2859
  #[test]
2686
2860
  fn a_directory_appends_at_its_host_files_end_in_one_step() {
2687
2861
  let host = HostDir::new("append");
@@ -2718,8 +2892,7 @@ mod tests {
2718
2892
  written.iter().filter(|&&b| b == b'b').count()
2719
2893
  ),
2720
2894
  (10_000, 10_000),
2721
- "two handles appending to one host file through a Bind's FileOperations::write_iter must each \
2722
- keep every byte"
2895
+ "two handles appending to one host file through a Bind must each keep every byte"
2723
2896
  );
2724
2897
  }
2725
2898