kobako 0.29.0 → 0.31.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 (291) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -1
  3. data/CHANGELOG.md +552 -10
  4. data/Cargo.lock +595 -139
  5. data/README.md +126 -564
  6. data/ROADMAP.md +3 -2
  7. data/crates/kobako-runtime/CHANGELOG.md +488 -1
  8. data/crates/kobako-runtime/Cargo.toml +73 -15
  9. data/crates/kobako-runtime/README.md +11 -4
  10. data/crates/kobako-runtime/src/cred.rs +124 -0
  11. data/crates/kobako-runtime/src/dispatch.rs +5 -6
  12. data/crates/kobako-runtime/src/endpoint/buffer.rs +301 -0
  13. data/crates/kobako-runtime/src/endpoint/dispatch.rs +292 -0
  14. data/crates/kobako-runtime/src/endpoint/invoke.rs +181 -0
  15. data/crates/kobako-runtime/src/endpoint.rs +267 -0
  16. data/crates/kobako-runtime/src/errno.rs +391 -0
  17. data/crates/kobako-runtime/src/error.rs +31 -10
  18. data/crates/kobako-runtime/src/filesystem/anon_inodes.rs +52 -0
  19. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +82 -0
  20. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +274 -0
  21. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +248 -0
  22. data/crates/kobako-runtime/src/filesystem/bind.rs +2857 -0
  23. data/crates/kobako-runtime/src/filesystem/overlay/file.rs +89 -0
  24. data/crates/kobako-runtime/src/filesystem/overlay/inode.rs +106 -0
  25. data/crates/kobako-runtime/src/filesystem/overlay/path.rs +263 -0
  26. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +128 -0
  27. data/crates/kobako-runtime/src/filesystem/overlay/stack/dir.rs +238 -0
  28. data/crates/kobako-runtime/src/filesystem/overlay/stack/namei.rs +135 -0
  29. data/crates/kobako-runtime/src/filesystem/overlay/stack/readdir.rs +54 -0
  30. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +316 -739
  31. data/crates/kobako-runtime/src/filesystem/overlay.rs +2627 -1154
  32. data/crates/kobako-runtime/src/filesystem/pipe.rs +224 -0
  33. data/crates/kobako-runtime/src/filesystem/rdir.rs +84 -0
  34. data/crates/kobako-runtime/src/filesystem/tmpfs/seed.rs +32 -0
  35. data/crates/kobako-runtime/src/filesystem/tmpfs/tmpfile.rs +32 -0
  36. data/crates/kobako-runtime/src/filesystem/tmpfs/whiteout.rs +107 -0
  37. data/crates/kobako-runtime/src/filesystem/tmpfs/xattr.rs +22 -0
  38. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +1997 -0
  39. data/crates/kobako-runtime/src/filesystem/wrap.rs +208 -0
  40. data/crates/kobako-runtime/src/filesystem.rs +25 -388
  41. data/crates/kobako-runtime/src/fork.rs +96 -0
  42. data/crates/kobako-runtime/src/grant.rs +3 -0
  43. data/crates/kobako-runtime/src/hashtable.rs +46 -0
  44. data/crates/kobako-runtime/src/lib.rs +27 -11
  45. data/crates/kobako-runtime/src/limits.rs +195 -0
  46. data/crates/kobako-runtime/src/locking/seqlock.rs +66 -0
  47. data/crates/kobako-runtime/src/locking.rs +228 -0
  48. data/crates/kobako-runtime/src/memcg.rs +383 -0
  49. data/crates/kobako-runtime/src/mount.rs +86 -101
  50. data/crates/kobako-runtime/src/net/backends.rs +43 -0
  51. data/crates/kobako-runtime/src/net/connections.rs +179 -0
  52. data/crates/kobako-runtime/src/net/credential.rs +125 -0
  53. data/crates/kobako-runtime/src/net/egress.rs +160 -0
  54. data/crates/kobako-runtime/src/net/family.rs +181 -0
  55. data/crates/kobako-runtime/src/net/http.rs +2733 -0
  56. data/crates/kobako-runtime/src/net/lookup.rs +285 -0
  57. data/crates/kobako-runtime/src/net/mock.rs +251 -0
  58. data/crates/kobako-runtime/src/net/namespace.rs +1366 -0
  59. data/crates/kobako-runtime/src/net/reactor.rs +531 -0
  60. data/crates/kobako-runtime/src/net/resolv/darwin.rs +275 -0
  61. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +469 -0
  62. data/crates/kobako-runtime/src/net/resolv/stub.rs +536 -0
  63. data/crates/kobako-runtime/src/net/resolv/windows.rs +248 -0
  64. data/crates/kobako-runtime/src/net/resolv.rs +227 -0
  65. data/crates/kobako-runtime/src/net/socket.rs +870 -0
  66. data/crates/kobako-runtime/src/net/tcp.rs +1588 -0
  67. data/crates/kobako-runtime/src/net/tls.rs +58 -0
  68. data/crates/kobako-runtime/src/net/transport.rs +279 -0
  69. data/crates/kobako-runtime/src/net/udp.rs +1003 -0
  70. data/crates/kobako-runtime/src/net.rs +42 -0
  71. data/crates/kobako-runtime/src/network/builder.rs +177 -0
  72. data/crates/kobako-runtime/src/network/ruleset.rs +777 -0
  73. data/crates/kobako-runtime/src/network.rs +551 -0
  74. data/crates/kobako-runtime/src/policy.rs +16 -0
  75. data/crates/kobako-runtime/src/profile.rs +37 -16
  76. data/crates/kobako-runtime/src/runtime.rs +3 -5
  77. data/crates/kobako-runtime/src/sched.rs +311 -0
  78. data/crates/kobako-runtime/src/security/entry_policy.rs +22 -0
  79. data/crates/kobako-runtime/src/security/hooks.rs +242 -0
  80. data/crates/kobako-runtime/src/security/mount_policy.rs +158 -0
  81. data/crates/kobako-runtime/src/security.rs +601 -0
  82. data/crates/kobako-runtime/src/snapshot.rs +121 -2
  83. data/crates/kobako-runtime/src/vfs/attr.rs +162 -0
  84. data/crates/kobako-runtime/src/vfs/dentry.rs +1466 -0
  85. data/crates/kobako-runtime/src/vfs/file.rs +1911 -0
  86. data/crates/kobako-runtime/src/vfs/inode.rs +425 -0
  87. data/crates/kobako-runtime/src/vfs/kern_path.rs +213 -0
  88. data/crates/kobako-runtime/src/vfs/mount.rs +60 -0
  89. data/crates/kobako-runtime/src/vfs/namei.rs +5837 -0
  90. data/crates/kobako-runtime/src/vfs/namespace.rs +162 -0
  91. data/crates/kobako-runtime/src/vfs/open_files.rs +69 -0
  92. data/crates/kobako-runtime/src/vfs/openat2.rs +116 -0
  93. data/crates/kobako-runtime/src/vfs/path.rs +64 -0
  94. data/crates/kobako-runtime/src/vfs/readdir.rs +163 -0
  95. data/crates/kobako-runtime/src/vfs/stat.rs +293 -0
  96. data/crates/kobako-runtime/src/vfs/super_block.rs +126 -0
  97. data/crates/kobako-runtime/src/vfs/utimes.rs +299 -0
  98. data/crates/kobako-runtime/src/vfs.rs +63 -0
  99. data/crates/kobako-runtime/src/wait.rs +356 -0
  100. data/crates/kobako-transport/CHANGELOG.md +39 -2
  101. data/crates/kobako-transport/Cargo.toml +3 -3
  102. data/crates/kobako-transport/README.md +8 -8
  103. data/crates/kobako-transport/src/abi.rs +78 -72
  104. data/crates/kobako-transport/src/envelope/bytes.rs +49 -30
  105. data/crates/kobako-transport/src/envelope/call.rs +37 -9
  106. data/crates/kobako-transport/src/envelope/compile_reply.rs +2 -2
  107. data/crates/kobako-transport/src/envelope/error_record.rs +24 -3
  108. data/crates/kobako-transport/src/envelope/fault.rs +2 -2
  109. data/crates/kobako-transport/src/envelope/name.rs +99 -0
  110. data/crates/kobako-transport/src/envelope/outcome.rs +11 -11
  111. data/crates/kobako-transport/src/envelope/preamble.rs +34 -31
  112. data/crates/kobako-transport/src/envelope/reply.rs +29 -29
  113. data/crates/kobako-transport/src/envelope/request.rs +2 -2
  114. data/crates/kobako-transport/src/envelope/run.rs +1 -1
  115. data/crates/kobako-transport/src/envelope/unsupported.rs +12 -12
  116. data/crates/kobako-transport/src/envelope.rs +15 -10
  117. data/crates/kobako-wasmtime/CHANGELOG.md +315 -8
  118. data/crates/kobako-wasmtime/Cargo.toml +35 -15
  119. data/crates/kobako-wasmtime/README.md +11 -6
  120. data/crates/kobako-wasmtime/build/preview2.rs +1339 -0
  121. data/crates/kobako-wasmtime/build.rs +16 -0
  122. data/crates/kobako-wasmtime/src/abi.rs +19 -47
  123. data/crates/kobako-wasmtime/src/ambient.rs +33 -19
  124. data/crates/kobako-wasmtime/src/cache.rs +28 -20
  125. data/crates/kobako-wasmtime/src/config.rs +59 -60
  126. data/crates/kobako-wasmtime/src/driver.rs +63 -145
  127. data/crates/kobako-wasmtime/src/exports.rs +147 -32
  128. data/crates/kobako-wasmtime/src/guest.rs +44 -0
  129. data/crates/kobako-wasmtime/src/guest_binary.rs +14 -0
  130. data/crates/kobako-wasmtime/src/imports.rs +48 -18
  131. data/crates/kobako-wasmtime/src/instance_pre.rs +7 -7
  132. data/crates/kobako-wasmtime/src/invocation.rs +93 -51
  133. data/crates/kobako-wasmtime/src/lib.rs +6 -7
  134. data/crates/kobako-wasmtime/src/limiter.rs +52 -211
  135. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +309 -0
  136. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +70 -57
  137. data/crates/kobako-wasmtime/src/preview1/differential.rs +137 -27
  138. data/crates/kobako-wasmtime/src/preview1/errno.rs +90 -233
  139. data/crates/kobako-wasmtime/src/preview1/fd.rs +1301 -522
  140. data/crates/kobako-wasmtime/src/preview1/memory.rs +126 -150
  141. data/crates/kobako-wasmtime/src/preview1/mount_view/wrap.rs +192 -0
  142. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +1989 -708
  143. data/crates/kobako-wasmtime/src/preview1/path.rs +181 -365
  144. data/crates/kobako-wasmtime/src/preview1/poll.rs +345 -173
  145. data/crates/kobako-wasmtime/src/preview1/sock.rs +10 -25
  146. data/crates/kobako-wasmtime/src/preview1/testsuite-expected.txt +6 -0
  147. data/crates/kobako-wasmtime/src/preview1/testsuite.rs +147 -0
  148. data/crates/kobako-wasmtime/src/preview1.rs +471 -416
  149. data/crates/kobako-wasmtime/src/preview2/abi.rs +227 -0
  150. data/crates/kobako-wasmtime/src/preview2/error.rs +118 -0
  151. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +122 -0
  152. data/crates/kobako-wasmtime/src/preview2/host.rs +3959 -0
  153. data/crates/kobako-wasmtime/src/preview2/http.rs +1503 -0
  154. data/crates/kobako-wasmtime/src/preview2/io.rs +315 -0
  155. data/crates/kobako-wasmtime/src/preview2/sockets.rs +379 -0
  156. data/crates/kobako-wasmtime/src/preview2/table.rs +305 -0
  157. data/crates/kobako-wasmtime/src/preview2.rs +57 -0
  158. data/crates/kobako-wasmtime/src/trap.rs +31 -16
  159. data/crates/kobako-wasmtime/src/wasi.rs +238 -93
  160. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  161. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  162. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  163. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  164. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  165. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  166. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  167. data/crates/kobako-wasmtime/witx/typenames.witx +750 -0
  168. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +441 -0
  169. data/data/kobako.wasm +0 -0
  170. data/ext/kobako/Cargo.toml +1 -1
  171. data/ext/kobako/src/{runtime/errors.rs → errors.rs} +35 -27
  172. data/ext/kobako/src/escape.rs +98 -0
  173. data/ext/kobako/src/{runtime/filesystem → filesystem}/grants.rs +36 -16
  174. data/ext/kobako/src/filesystem/ruby.rs +689 -0
  175. data/ext/kobako/src/filesystem.rs +217 -0
  176. data/ext/kobako/src/gvl.rs +306 -0
  177. data/ext/kobako/src/lib.rs +64 -3
  178. data/ext/kobako/src/network/mock.rs +187 -0
  179. data/ext/kobako/src/network.rs +591 -0
  180. data/ext/kobako/src/runtime/bridge.rs +31 -30
  181. data/ext/kobako/src/runtime/snapshot.rs +5 -5
  182. data/ext/kobako/src/runtime.rs +221 -138
  183. data/ext/kobako/src/wire.rs +42 -0
  184. data/lib/kobako/catalog/extensions.rb +19 -7
  185. data/lib/kobako/catalog/flags.rb +4 -6
  186. data/lib/kobako/catalog/grants.rb +5 -4
  187. data/lib/kobako/catalog/handles.rb +9 -31
  188. data/lib/kobako/catalog/mount.rb +12 -12
  189. data/lib/kobako/catalog/network.rb +35 -0
  190. data/lib/kobako/catalog/replacements.rb +28 -0
  191. data/lib/kobako/catalog/services.rb +7 -21
  192. data/lib/kobako/catalog/snippets.rb +10 -25
  193. data/lib/kobako/catalog.rb +4 -1
  194. data/lib/kobako/codec/{utils.rb → boundary.rb} +5 -3
  195. data/lib/kobako/codec/decoder.rb +12 -12
  196. data/lib/kobako/codec/ext_types.rb +5 -7
  197. data/lib/kobako/codec/handle_walk.rb +5 -47
  198. data/lib/kobako/codec/nesting.rb +7 -7
  199. data/lib/kobako/codec/value_budget.rb +134 -42
  200. data/lib/kobako/codec.rb +1 -1
  201. data/lib/kobako/context.rb +28 -15
  202. data/lib/kobako/errors.rb +15 -12
  203. data/lib/kobako/extension.rb +3 -2
  204. data/lib/kobako/filesystem.rb +53 -15
  205. data/lib/kobako/handle.rb +2 -2
  206. data/lib/kobako/names.rb +28 -0
  207. data/lib/kobako/network.rb +210 -0
  208. data/lib/kobako/outcome.rb +7 -7
  209. data/lib/kobako/payload/arguments.rb +2 -2
  210. data/lib/kobako/pool.rb +47 -25
  211. data/lib/kobako/runtime.rb +3 -2
  212. data/lib/kobako/sandbox.rb +113 -56
  213. data/lib/kobako/sandbox_options.rb +41 -107
  214. data/lib/kobako/snippet/bytecode.rb +1 -1
  215. data/lib/kobako/snippet/source.rb +1 -1
  216. data/lib/kobako/transport/argument_wrap.rb +64 -0
  217. data/lib/kobako/transport/block_failure.rb +1 -1
  218. data/lib/kobako/transport/dispatcher.rb +10 -10
  219. data/lib/kobako/transport/exposure.rb +28 -17
  220. data/lib/kobako/transport/reflection.rb +28 -11
  221. data/lib/kobako/transport/run.rb +13 -28
  222. data/lib/kobako/transport/yielder.rb +3 -10
  223. data/lib/kobako/transport.rb +1 -0
  224. data/lib/kobako/version.rb +1 -1
  225. data/lib/kobako.rb +38 -0
  226. data/release-please-config.json +16 -0
  227. data/sig/core/thread.rbs +6 -0
  228. data/sig/kobako/catalog/extensions.rbs +5 -3
  229. data/sig/kobako/catalog/grants.rbs +7 -4
  230. data/sig/kobako/catalog/handles.rbs +2 -4
  231. data/sig/kobako/catalog/mount.rbs +3 -5
  232. data/sig/kobako/catalog/network.rbs +20 -0
  233. data/sig/kobako/catalog/replacements.rbs +14 -0
  234. data/sig/kobako/catalog/services.rbs +1 -5
  235. data/sig/kobako/catalog/snippets.rbs +3 -5
  236. data/sig/kobako/catalog.rbs +1 -1
  237. data/sig/kobako/codec/boundary.rbs +9 -0
  238. data/sig/kobako/codec/decoder.rbs +1 -1
  239. data/sig/kobako/codec/handle_walk.rbs +0 -6
  240. data/sig/kobako/codec/nesting.rbs +2 -2
  241. data/sig/kobako/codec/value_budget.rbs +48 -5
  242. data/sig/kobako/codec.rbs +1 -2
  243. data/sig/kobako/context.rbs +4 -2
  244. data/sig/kobako/errors.rbs +4 -4
  245. data/sig/kobako/filesystem.rbs +38 -15
  246. data/sig/kobako/guest_yielder.rbs +1 -1
  247. data/sig/kobako/network.rbs +115 -0
  248. data/sig/kobako/outcome.rbs +1 -1
  249. data/sig/kobako/payload/arguments.rbs +1 -1
  250. data/sig/kobako/pool.rbs +8 -4
  251. data/sig/kobako/runtime.rbs +32 -3
  252. data/sig/kobako/sandbox.rbs +22 -7
  253. data/sig/kobako/sandbox_options.rbs +29 -38
  254. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  255. data/sig/kobako/transport/dispatcher.rbs +2 -2
  256. data/sig/kobako/transport/error.rbs +1 -1
  257. data/sig/kobako/transport/exposure.rbs +3 -5
  258. data/sig/kobako/transport/reflection.rbs +12 -2
  259. data/sig/kobako/transport/run.rbs +3 -5
  260. data/sig/kobako/transport/yielder.rbs +0 -3
  261. data/sig/kobako/transport.rbs +2 -2
  262. data/sig/kobako.rbs +13 -0
  263. metadata +131 -34
  264. data/crates/kobako-runtime/src/filesystem/directory/spelling.rs +0 -194
  265. data/crates/kobako-runtime/src/filesystem/directory.rs +0 -1082
  266. data/crates/kobako-runtime/src/filesystem/memory.rs +0 -1100
  267. data/crates/kobako-runtime/src/filesystem/overlay/exclusive.rs +0 -88
  268. data/crates/kobako-runtime/src/filesystem/path.rs +0 -60
  269. data/crates/kobako-runtime/src/filesystem/temporary.rs +0 -167
  270. data/crates/kobako-wasmtime/src/capture.rs +0 -96
  271. data/crates/kobako-wasmtime/src/descriptors.rs +0 -167
  272. data/crates/kobako-wasmtime/src/dispatch.rs +0 -125
  273. data/crates/kobako-wasmtime/src/guest_mem.rs +0 -271
  274. data/crates/kobako-wasmtime/src/io.rs +0 -89
  275. data/crates/kobako-wasmtime/src/preview1/args.rs +0 -60
  276. data/crates/kobako-wasmtime/src/preview1/beneath.rs +0 -188
  277. data/crates/kobako-wasmtime/tests/compile_posture.rs +0 -43
  278. data/crates/kobako-wasmtime/tests/guest_file.rs +0 -1054
  279. data/crates/kobako-wasmtime/tests/preamble_flags.rs +0 -70
  280. data/crates/kobako-wasmtime/tests/snippet_compile.rs +0 -95
  281. data/crates/kobako-wasmtime/tests/support/mod.rs +0 -30
  282. data/crates/kobako-wasmtime/tests/unanswered_call.rs +0 -86
  283. data/crates/kobako-wasmtime/tests/unsupported_call.rs +0 -51
  284. data/ext/kobako/src/runtime/escape.rs +0 -53
  285. data/ext/kobako/src/runtime/filesystem/ruby.rs +0 -400
  286. data/ext/kobako/src/runtime/filesystem.rs +0 -236
  287. data/ext/kobako/src/runtime/gvl.rs +0 -112
  288. data/lib/kobako/constant_name.rb +0 -8
  289. data/sig/kobako/codec/utils.rbs +0 -9
  290. data/sig/kobako/constant_name.rbs +0 -3
  291. /data/ext/kobako/src/{runtime/pinned_value.rs → pinned_value.rs} +0 -0
@@ -0,0 +1,2857 @@
1
+ //! `Bind`: a Filesystem over a host directory, from which nothing
2
+ //! outside it is reachable.
3
+ //!
4
+ //! The runtime hands a Bind one name at a time and follows every link
5
+ //! itself, so the VFS keeps the guest inside. Each name still resolves
6
+ //! through `cap_std::fs::Dir`, or the host's kernel where it confines a
7
+ //! path itself, which refuses a `..` or a link leading out of the
8
+ //! directory whatever a caller hands over, and answers alike on every
9
+ //! host, Windows among them.
10
+
11
+ mod fid;
12
+ mod lookup;
13
+ mod walk;
14
+
15
+ use std::any::Any;
16
+ use std::io::{self, Read, Seek, SeekFrom, Write};
17
+ use std::path::Path;
18
+ use std::sync::{Arc, Mutex, PoisonError, Weak};
19
+
20
+ use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt, SystemTimeSpec};
21
+ use cap_std::ambient_authority;
22
+ use cap_std::fs::{Dir, OpenOptions as CapOpenOptions};
23
+
24
+ use super::rdir::Rdir;
25
+ use super::{
26
+ DentryOperations, DirEntry, Errno, FileOperations, FileSystemType, FileType, Filesystem,
27
+ Finish, Iattr, InodeOperations, Kiocb, Kstat, Lookup, OpenHow, RenameFlag, SetTime,
28
+ };
29
+ use crate::vfs::{
30
+ generic_file_llseek, generic_read_dir, Dentry, DirContext, Identity, Inode, Whence,
31
+ };
32
+ use fid::{FidCache, OpenDirFid};
33
+
34
+ /// A host directory and everything beneath it. What a guest writes lands
35
+ /// on the host and lasts as long as the directory does.
36
+ ///
37
+ /// Every entry beneath it answers through a Bind too, finding what a call is
38
+ /// about through the dentry it is handed, as Linux's 9p does. A directory is
39
+ /// opened on the host when first asked, as 9p walks to a dentry's fid only
40
+ /// 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.
42
+ #[derive(Clone)]
43
+ pub struct Bind {
44
+ /// The host directory the Bind was made at.
45
+ root: Arc<Dir>,
46
+ fids: Arc<FidCache>,
47
+ /// Whether only the guest changes the directory, so a name it found
48
+ /// stays as found without asking the host again.
49
+ exclusive: bool,
50
+ }
51
+
52
+ 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.
57
+ 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))?;
60
+ Ok(Self {
61
+ root: Arc::new(root),
62
+ fids: Arc::default(),
63
+ exclusive: false,
64
+ })
65
+ }
66
+
67
+ /// This Bind trusting the names it found when `exclusive`, the Host App
68
+ /// vouching that only the guest changes the directory, as gVisor's
69
+ /// exclusive mount skips revalidation. A change made on the host meanwhile
70
+ /// may go unseen.
71
+ pub fn with_exclusive(self, exclusive: bool) -> Self {
72
+ Self { exclusive, ..self }
73
+ }
74
+
75
+ /// The host directory kept for `dentry`, if one is.
76
+ fn find_fid(&self, dentry: &Dentry) -> Option<Arc<Dir>> {
77
+ if dentry.is_root() {
78
+ return Some(self.root.clone());
79
+ }
80
+ OpenDirFid::get(dentry).or_else(|| self.fids.get(dentry))
81
+ }
82
+
83
+ /// The host directory `dentry` names, as 9p's `v9fs_fid_lookup` finds a
84
+ /// fid: the one kept for it, or the names beneath the nearest directory
85
+ /// kept, read from the dentries as `build_path_from_dentry` reads them.
86
+ /// 9p holds the rename lock through a walk; one here compares what it found
87
+ /// with what the dentry recorded instead, as NFS compares a file handle.
88
+ fn fid_lookup(&self, dentry: &Dentry) -> Result<Arc<Dir>, Errno> {
89
+ if let Some(held) = self.find_fid(dentry) {
90
+ return Ok(held);
91
+ }
92
+ let mut names = vec![dentry.name()];
93
+ let mut at = dentry.parent();
94
+ let above = loop {
95
+ if let Some(held) = self.find_fid(&at) {
96
+ break held;
97
+ }
98
+ names.push(at.name());
99
+ at = at.parent();
100
+ };
101
+ names.reverse();
102
+ let recorded = dentry.inode().and_then(|inode| inode.identity());
103
+ let stands = |dir: &Dir| {
104
+ recorded.is_none()
105
+ || dir
106
+ .dir_metadata()
107
+ .is_ok_and(|found| Identity::of(&to_kstat(found)) == recorded)
108
+ };
109
+ let dir = walk::walk(&above, &names)?;
110
+ if !stands(&dir) {
111
+ return Err(Errno::NotFound);
112
+ }
113
+ let dir = Arc::new(dir);
114
+ self.fids.put(dentry, &dir);
115
+ Ok(dir)
116
+ }
117
+
118
+ /// Answer `call` with the directory above `dentry` and the name it
119
+ /// carries as the host spells it.
120
+ fn at<T>(
121
+ &self,
122
+ dentry: &Dentry,
123
+ call: impl FnOnce(&Dir, &str) -> Result<T, Errno>,
124
+ ) -> Result<T, Errno> {
125
+ let (parent, name) = dentry.parent_and_name();
126
+ call(&*self.fid_lookup(&parent)?, to_host_name(&name)?)
127
+ }
128
+
129
+ /// Open the file `dentry` names and keep its descriptor on the inode, so
130
+ /// the entry answers from it however its name changes, as 9p's
131
+ /// `v9fs_open_fid_add` keeps an open fid. What this made is recorded
132
+ /// first, as `->atomic_open` calls `d_instantiate`.
133
+ fn open_file(
134
+ &self,
135
+ dentry: &Dentry,
136
+ how: &OpenHow,
137
+ create: bool,
138
+ ) -> Result<Box<dyn FileOperations>, Errno> {
139
+ let file = self.at(dentry, |dir, name| open_in(dir, name, how, create))?;
140
+ let opened = to_kstat(cap_std::fs::Metadata::from_file(&file).map_err(to_error)?);
141
+ match dentry.inode().map(|inode| inode.identity()) {
142
+ None => dentry.add(Some(Inode::new(
143
+ &opened,
144
+ Arc::new(BindRegular(self.clone())),
145
+ ))),
146
+ // A host path may by now hold another entry than the one judged,
147
+ // which only what opened can tell, as NFS's open compares the file
148
+ // handle it gets back.
149
+ Some(Some(identity)) if Identity::of(&opened) != Some(identity) => {
150
+ return Err(Errno::NotFound)
151
+ }
152
+ Some(_) => {}
153
+ }
154
+ let file = Arc::new(file);
155
+ let inode = dentry.inode().ok_or(Errno::NotFound)?;
156
+ let kept = inode
157
+ .private()
158
+ .get_or_init(|| Arc::new(OpenFids::default()))
159
+ .clone();
160
+ if let Ok(fids) = kept.downcast::<OpenFids>() {
161
+ let mut fids = fids.0.lock().unwrap_or_else(PoisonError::into_inner);
162
+ fids.retain(|(fid, _)| fid.strong_count() > 0);
163
+ fids.push((Arc::downgrade(&file), how.write || how.truncate));
164
+ }
165
+ Ok(Box::new(BindFile { file }))
166
+ }
167
+
168
+ /// Whether the entry `dentry` recorded still stands at its name in the
169
+ /// directory above, as a walk asks each name once the one above it stood.
170
+ /// A host may reuse an inode number for what it made in its place, so the
171
+ /// kind must match too, as NFS compares a file handle's attributes.
172
+ fn stands_as_recorded(&self, dentry: &Dentry) -> Result<bool, Errno> {
173
+ let inode = dentry.inode();
174
+ if inode
175
+ .as_ref()
176
+ .is_some_and(|inode| inode.identity().is_none())
177
+ {
178
+ return Ok(true);
179
+ }
180
+ let found = self.at(dentry, |dir, name| {
181
+ dir.symlink_metadata(name).map_err(to_error)
182
+ });
183
+ match (found, inode) {
184
+ (Ok(found), Some(inode)) => {
185
+ let found = to_kstat(found);
186
+ Ok(
187
+ Identity::of(&found) == inode.identity()
188
+ && found.file_type == inode.file_type(),
189
+ )
190
+ }
191
+ (Ok(_), None) => Ok(false),
192
+ (Err(Errno::NotFound), None) => Ok(true),
193
+ (Err(Errno::NotFound | Errno::NotADirectory | Errno::FilesystemLoop), _) => Ok(false),
194
+ (Err(err), _) => Err(err),
195
+ }
196
+ }
197
+ }
198
+
199
+ /// The names `dir` holds, each with the kind and the identity a stat names.
200
+ /// A Windows listing carries no file index, so there each name is asked of
201
+ /// a stat; one gone by then lists without an identity.
202
+ fn entries_of(dir: &Dir) -> Result<Vec<DirEntry>, Errno> {
203
+ #[cfg(unix)]
204
+ let dev = {
205
+ use cap_std::fs::MetadataExt;
206
+ dir.dir_metadata().map_err(to_error)?.dev()
207
+ };
208
+ dir.entries()
209
+ .map_err(to_error)?
210
+ .map(|entry| {
211
+ let entry = entry.map_err(to_error)?;
212
+ let name = entry
213
+ .file_name()
214
+ .into_string()
215
+ .map_err(|_| Errno::IllegalSequence)?;
216
+ let listed = DirEntry::new(name, to_file_type(entry.file_type().map_err(to_error)?));
217
+ #[cfg(unix)]
218
+ let listed = {
219
+ use std::os::unix::fs::DirEntryExt;
220
+ listed.with_identity(dev, entry.ino())
221
+ };
222
+ #[cfg(not(unix))]
223
+ let listed = match dir.symlink_metadata(&listed.name) {
224
+ Ok(found) => {
225
+ use cap_fs_ext::MetadataExt;
226
+ listed.with_identity(found.dev(), found.ino())
227
+ }
228
+ Err(_) => listed,
229
+ };
230
+ Ok(listed)
231
+ })
232
+ .collect()
233
+ }
234
+
235
+ /// The directory `name` in `dir`, a link there refused as a loop, as
236
+ /// Linux's `RESOLVE_NO_SYMLINKS` refuses one, where the host names it no
237
+ /// directory.
238
+ fn open_dir_nofollow(dir: &Dir, name: &str) -> Result<Dir, Errno> {
239
+ dir.open_dir_nofollow(name)
240
+ .map_err(|err| nofollow_error(dir, name, err))
241
+ }
242
+
243
+ /// Why an open of `name` in `dir` that follows no link failed, a link there
244
+ /// named a loop, as Linux's `O_NOFOLLOW` answers `ELOOP`, where the host
245
+ /// names it otherwise.
246
+ fn nofollow_error(dir: &Dir, name: &str, err: io::Error) -> Errno {
247
+ match dir.symlink_metadata(name) {
248
+ Ok(metadata) if metadata.file_type().is_symlink() => Errno::FilesystemLoop,
249
+ _ => to_error(err),
250
+ }
251
+ }
252
+
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
+ /// The Errno a host failure names. cap-std's own refusal of a path
280
+ /// leading out of the directory carries no OS code. A Bind hands it one name and
281
+ /// no `..`, so that refusal only says a move carried the name out of the
282
+ /// directory as it was opened, as `complete_walk` answers EXDEV, and nothing
283
+ /// stands at it now.
284
+ fn to_error(err: io::Error) -> Errno {
285
+ match err.kind() {
286
+ io::ErrorKind::PermissionDenied if err.raw_os_error().is_none() => Errno::NotFound,
287
+ _ => Errno::from_io_error(&err),
288
+ }
289
+ }
290
+
291
+ fn to_file_type(host: cap_std::fs::FileType) -> FileType {
292
+ if host.is_symlink() {
293
+ FileType::Symlink
294
+ } else if host.is_dir() {
295
+ FileType::Dir
296
+ } else if host.is_file() {
297
+ FileType::RegFile
298
+ } else {
299
+ to_special_file_type(host)
300
+ }
301
+ }
302
+
303
+ /// What a host entry neither a file, a directory, nor a link is, as `st_mode`
304
+ /// names it.
305
+ #[cfg(unix)]
306
+ fn to_special_file_type(host: cap_std::fs::FileType) -> FileType {
307
+ use cap_std::fs::FileTypeExt;
308
+ if host.is_fifo() {
309
+ FileType::Fifo
310
+ } else if host.is_socket() {
311
+ FileType::Sock
312
+ } else if host.is_block_device() {
313
+ FileType::Blkdev
314
+ } else if host.is_char_device() {
315
+ FileType::Chrdev
316
+ } else {
317
+ FileType::Unknown
318
+ }
319
+ }
320
+
321
+ /// Elsewhere a Bind names no kind.
322
+ #[cfg(not(unix))]
323
+ fn to_special_file_type(_host: cap_std::fs::FileType) -> FileType {
324
+ FileType::Unknown
325
+ }
326
+
327
+ /// 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.
331
+ fn to_kstat(metadata: cap_std::fs::Metadata) -> Kstat {
332
+ let file_type = to_file_type(metadata.file_type());
333
+ let size = metadata.len();
334
+ #[cfg(unix)]
335
+ {
336
+ use cap_std::fs::MetadataExt;
337
+ Kstat::new(file_type, size)
338
+ .with_identity(metadata.dev(), metadata.ino())
339
+ .with_nlink(metadata.nlink())
340
+ .with_times(
341
+ unix_time(metadata.atime(), metadata.atime_nsec()),
342
+ unix_time(metadata.mtime(), metadata.mtime_nsec()),
343
+ unix_time(metadata.ctime(), metadata.ctime_nsec()),
344
+ )
345
+ }
346
+ #[cfg(not(unix))]
347
+ {
348
+ use cap_fs_ext::MetadataExt;
349
+ Kstat::new(file_type, size)
350
+ .with_identity(metadata.dev(), metadata.ino())
351
+ .with_nlink(metadata.nlink())
352
+ }
353
+ }
354
+
355
+ /// The time `seconds` and `nanoseconds` after the Unix epoch, as `stat`
356
+ /// reports one; `None` before the epoch, which no guest's clock reads.
357
+ #[cfg(unix)]
358
+ fn unix_time(seconds: i64, nanoseconds: i64) -> Option<std::time::SystemTime> {
359
+ let seconds = u64::try_from(seconds).ok()?;
360
+ let nanoseconds = u32::try_from(nanoseconds).ok()?;
361
+ std::time::UNIX_EPOCH.checked_add(std::time::Duration::new(seconds, nanoseconds))
362
+ }
363
+
364
+ /// `time` as the host takes it, so a time of now is the host's own.
365
+ fn to_host_time(time: Option<SetTime>) -> Option<SystemTimeSpec> {
366
+ time.map(|time| match time {
367
+ SetTime::Now => SystemTimeSpec::SymbolicNow,
368
+ SetTime::At(at) => SystemTimeSpec::Absolute(cap_std::time::SystemTime::from_std(at)),
369
+ })
370
+ }
371
+
372
+ /// The descriptors open on one file, and which were opened to write, as 9p
373
+ /// keeps open fids on `i_private`.
374
+ #[derive(Default)]
375
+ struct OpenFids(Mutex<Vec<(Weak<std::fs::File>, bool)>>);
376
+
377
+ /// A descriptor open on the file `dentry` records, one open to write where
378
+ /// `writable` asks, as 9p's `v9fs_fid_find_inode` finds one.
379
+ fn v9fs_fid_find_inode(dentry: &Dentry, writable: bool) -> Option<Arc<std::fs::File>> {
380
+ let inode = dentry.inode()?;
381
+ let fids = inode.private().get()?.clone().downcast::<OpenFids>().ok()?;
382
+ let fids = fids.0.lock().unwrap_or_else(PoisonError::into_inner);
383
+ fids.iter()
384
+ .filter(|(_, opened_to_write)| *opened_to_write || !writable)
385
+ .find_map(|(fid, _)| fid.upgrade())
386
+ }
387
+
388
+ /// Open `name` in `dir` as `how` asks, made first where `create` says,
389
+ /// refusing one that already stands.
390
+ fn open_in(dir: &Dir, name: &str, how: &OpenHow, create: bool) -> Result<std::fs::File, Errno> {
391
+ let writes = how.write || how.truncate || create;
392
+ #[cfg(target_os = "linux")]
393
+ if !create {
394
+ if let Some(opened) = open_judged(dir, name, how.read, writes)? {
395
+ return Ok(opened);
396
+ }
397
+ }
398
+ let mut open = CapOpenOptions::new();
399
+ // The host refuses one that creates or truncates without writing; the
400
+ // runtime decides what is written, so such opens write here.
401
+ open.read(how.read).write(writes).create_new(create);
402
+ // Only a file or a directory opens: a FIFO would wait for a peer
403
+ // and a device would act on being opened. The host could swap an
404
+ // entry in between, so what opened is checked again before its
405
+ // first use, the open itself never waiting for a peer, nor following
406
+ // a link swapped in, since the runtime follows a link itself.
407
+ open.follow(FollowSymlinks::No);
408
+ #[cfg(unix)]
409
+ {
410
+ use cap_std::fs::OpenOptionsExt;
411
+ use rustix::fs::OFlags;
412
+ open.custom_flags((OFlags::NONBLOCK | OFlags::NOCTTY).bits() as i32);
413
+ }
414
+ let file = dir
415
+ .open_with(name, &open)
416
+ .map_err(|err| nofollow_error(dir, name, err))?;
417
+ match to_file_type(file.metadata().map_err(to_error)?.file_type()) {
418
+ FileType::RegFile => {}
419
+ FileType::Dir => return Err(Errno::IsADirectory),
420
+ _ => return Err(Errno::PermissionDenied),
421
+ }
422
+ #[cfg(unix)]
423
+ {
424
+ use rustix::fs::{fcntl_getfl, fcntl_setfl, OFlags};
425
+ let flags = fcntl_getfl(&file)
426
+ .map_err(io::Error::from)
427
+ .map_err(to_error)?;
428
+ fcntl_setfl(&file, flags - OFlags::NONBLOCK)
429
+ .map_err(io::Error::from)
430
+ .map_err(to_error)?;
431
+ }
432
+ Ok(file.into_std())
433
+ }
434
+
435
+ /// The file standing at `name` in `dir`, held by `O_PATH` first, which opens
436
+ /// nothing, and opened only once it stands as a file, through
437
+ /// `/proc/self/fd`, so what opens is the inode judged and no device swapped
438
+ /// in acts on being opened, as gVisor's directfs reopens its control
439
+ /// descriptor. None where the host has no `/proc` to reopen through.
440
+ #[cfg(target_os = "linux")]
441
+ fn open_judged(
442
+ dir: &Dir,
443
+ name: &str,
444
+ read: bool,
445
+ writes: bool,
446
+ ) -> Result<Option<std::fs::File>, Errno> {
447
+ use rustix::fs::{fstat, open, openat, FileType as HostType, Mode, OFlags};
448
+ use std::os::fd::AsRawFd;
449
+
450
+ let held = openat(
451
+ dir,
452
+ name,
453
+ OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC,
454
+ Mode::empty(),
455
+ )
456
+ .map_err(io::Error::from)
457
+ .map_err(to_error)?;
458
+ let stat = fstat(&held).map_err(io::Error::from).map_err(to_error)?;
459
+ match HostType::from_raw_mode(stat.st_mode) {
460
+ HostType::RegularFile => {}
461
+ HostType::Directory => return Err(Errno::IsADirectory),
462
+ HostType::Symlink => return Err(Errno::FilesystemLoop),
463
+ _ => return Err(Errno::PermissionDenied),
464
+ }
465
+ let access = match (read, writes) {
466
+ (true, true) => OFlags::RDWR,
467
+ (false, true) => OFlags::WRONLY,
468
+ _ => OFlags::RDONLY,
469
+ };
470
+ let reopened = open(
471
+ format!("/proc/self/fd/{}", held.as_raw_fd()).as_str(),
472
+ access | OFlags::CLOEXEC | OFlags::NOCTTY,
473
+ Mode::empty(),
474
+ );
475
+ match reopened {
476
+ Ok(fd) => Ok(Some(std::fs::File::from(fd))),
477
+ Err(rustix::io::Errno::NOENT) => Ok(None),
478
+ Err(err) => Err(to_error(io::Error::from(err))),
479
+ }
480
+ }
481
+
482
+ /// The host may move or remake what a dentry names behind the runtime's
483
+ /// back, so a dentry recording an identity is valid only while the same
484
+ /// entry stands at the path it stands for, as NFS compares the handle a
485
+ /// fresh lookup finds. One recording none has nothing to compare, so nothing
486
+ /// keeps it once its holder lets go.
487
+ impl FileSystemType for Bind {
488
+ /// Its root reports the host directory it holds, as 9p's `fill_super` asks of
489
+ /// the attached fid, and a host that cannot answer makes no instance.
490
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), Errno> {
491
+ sb.set_default_d_op(self.clone());
492
+ let root = to_kstat(self.root.dir_metadata().map_err(to_error)?);
493
+ sb.d_make_root(Inode::new(&root, self));
494
+ Ok(())
495
+ }
496
+ }
497
+
498
+ impl DentryOperations for Bind {
499
+ fn revalidate(&self, _dir: &dyn InodeOperations, dentry: &Dentry) -> Result<bool, Errno> {
500
+ match self.exclusive {
501
+ true => Ok(true),
502
+ false => self.stands_as_recorded(dentry),
503
+ }
504
+ }
505
+
506
+ fn delete(&self, dentry: &Dentry) -> bool {
507
+ dentry
508
+ .inode()
509
+ .is_some_and(|inode| inode.identity().is_none())
510
+ }
511
+ }
512
+
513
+ /// A file of a Bind, or an entry a host holds that is none of the others, as
514
+ /// `v9fs_file_inode_operations_dotl` answers for one.
515
+ struct BindRegular(Bind);
516
+
517
+ /// A link of a Bind, as `v9fs_symlink_inode_operations_dotl` answers for one.
518
+ struct BindLink(Bind);
519
+
520
+ /// What an entry standing at its name in the directory above reports.
521
+ fn stat_at(bind: &Bind, dentry: &Dentry) -> Result<Kstat, Errno> {
522
+ bind.at(dentry, |dir, name| {
523
+ Ok(to_kstat(dir.symlink_metadata(name).map_err(to_error)?))
524
+ })
525
+ }
526
+
527
+ impl InodeOperations for BindRegular {
528
+ /// A file open anywhere answers from the descriptor that holds it, even
529
+ /// once its name is gone.
530
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
531
+ match v9fs_fid_find_inode(dentry, false) {
532
+ Some(file) => Ok(to_kstat(
533
+ cap_std::fs::Metadata::from_file(&file).map_err(to_error)?,
534
+ )),
535
+ None => stat_at(&self.0, dentry),
536
+ }
537
+ }
538
+
539
+ fn setattr(&self, dentry: &Dentry, attr: &Iattr) -> Result<(), Errno> {
540
+ if let Some(len) = attr.size {
541
+ // A truncate made through an open takes that open's descriptor, as
542
+ // 9p takes `ia_file`'s fid; one made by name, one open to write
543
+ // elsewhere.
544
+ let through = attr
545
+ .file
546
+ .and_then(|file| (file as &dyn Any).downcast_ref::<BindFile>())
547
+ .map(|opened| opened.file.clone());
548
+ return match through.or_else(|| v9fs_fid_find_inode(dentry, true)) {
549
+ Some(file) => file.set_len(len).map_err(to_error),
550
+ None => Err(Errno::InvalidInput),
551
+ };
552
+ }
553
+ // A file open anywhere takes them through what holds it, whatever stands
554
+ // at its name by now.
555
+ if let Some(file) = v9fs_fid_find_inode(dentry, false) {
556
+ let mut times = std::fs::FileTimes::new();
557
+ if let Some(atime) = attr.atime {
558
+ times = times.set_accessed(attr.time_of(atime));
559
+ }
560
+ if let Some(mtime) = attr.mtime {
561
+ times = times.set_modified(attr.time_of(mtime));
562
+ }
563
+ return file.set_times(times).map_err(to_error);
564
+ }
565
+ let (atime, mtime) = (to_host_time(attr.atime), to_host_time(attr.mtime));
566
+ self.0.at(dentry, |dir, name| {
567
+ dir.set_symlink_times(name, atime, mtime).map_err(to_error)
568
+ })
569
+ }
570
+
571
+ fn open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
572
+ self.0.open_file(dentry, how, false)
573
+ }
574
+ }
575
+
576
+ impl InodeOperations for BindLink {
577
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
578
+ stat_at(&self.0, dentry)
579
+ }
580
+
581
+ /// Where it points as the host holds it, even outside this directory,
582
+ /// as `->get_link` answers, since the walk judges what a link leads to. A
583
+ /// target that is no valid UTF-8 answers `IllegalSequence`, as a guest path
584
+ /// is one.
585
+ fn get_link(&self, dentry: &Dentry) -> Result<String, Errno> {
586
+ 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)
592
+ })
593
+ }
594
+ }
595
+
596
+ impl InodeOperations for Bind {
597
+ /// A directory answers from its own descriptor, which follows it wherever
598
+ /// it moves and keeps its inode taken while it is open.
599
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
600
+ Ok(to_kstat(
601
+ self.fid_lookup(dentry)?.dir_metadata().map_err(to_error)?,
602
+ ))
603
+ }
604
+
605
+ /// A directory takes the times through the descriptor that holds it, as it
606
+ /// answers for itself.
607
+ fn setattr(&self, dentry: &Dentry, attr: &Iattr) -> Result<(), Errno> {
608
+ let (atime, mtime) = (to_host_time(attr.atime), to_host_time(attr.mtime));
609
+ self.fid_lookup(dentry)?
610
+ .set_times(".", atime, mtime)
611
+ .map_err(to_error)
612
+ }
613
+
614
+ /// What stands at the name `dentry` carries, spelled as the host spells
615
+ /// it, as a lookup hands `d_splice_alias` the inode it found, so
616
+ /// `revalidate` can tell a dentry the host replaced behind the
617
+ /// runtime's back. That costs one host stat a name.
618
+ fn lookup(&self, dentry: &Dentry) -> Result<Lookup, Errno> {
619
+ self.at(dentry, |dir, name| {
620
+ let stored_name = lookup::lookup(dir, name)?;
621
+ match dir.symlink_metadata(&stored_name).map_err(to_error) {
622
+ Ok(found) => {
623
+ let found = to_kstat(found);
624
+ let ops: Arc<dyn InodeOperations> = match found.file_type {
625
+ FileType::Dir => Arc::new(self.clone()),
626
+ FileType::Symlink => Arc::new(BindLink(self.clone())),
627
+ _ => Arc::new(BindRegular(self.clone())),
628
+ };
629
+ let inode = Inode::new(&found, ops);
630
+ match stored_name == name {
631
+ true => Ok(Lookup::Found(inode)),
632
+ false => Ok(Lookup::Spelled {
633
+ name: stored_name,
634
+ inode,
635
+ }),
636
+ }
637
+ }
638
+ Err(Errno::NotFound) => Ok(Lookup::Absent),
639
+ Err(err) => Err(err),
640
+ }
641
+ })
642
+ }
643
+
644
+ fn open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
645
+ let fid = self.fid_lookup(dentry)?;
646
+ if how.read {
647
+ may_read_dir(&fid)?;
648
+ }
649
+ OpenDirFid::set(dentry, &fid);
650
+ Ok(Box::new(BindDir(fid, Rdir::default())))
651
+ }
652
+
653
+ /// A name still in lookup is looked up first, and any name is left to the
654
+ /// VFS unless the open may make it and nothing stands there, as 9p's
655
+ /// `v9fs_vfs_atomic_open_dotl` asks its server before it creates.
656
+ fn atomic_open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Finish, Errno> {
657
+ if dentry.in_lookup() {
658
+ let found = self.lookup(dentry)?;
659
+ if !how.create || !matches!(found, Lookup::Absent) {
660
+ return Ok(Finish::Lookup(found));
661
+ }
662
+ }
663
+ if !how.create {
664
+ return Ok(Finish::NoOpen { created: false });
665
+ }
666
+ let file = self.open_file(dentry, how, true)?;
667
+ Ok(Finish::Open {
668
+ file,
669
+ created: true,
670
+ })
671
+ }
672
+
673
+ fn mkdir(&self, dentry: &Dentry) -> Result<(), Errno> {
674
+ self.at(dentry, |dir, name| dir.create_dir(name).map_err(to_error))
675
+ }
676
+
677
+ fn rmdir(&self, dentry: &Dentry) -> Result<(), Errno> {
678
+ self.at(dentry, |dir, name| dir.remove_dir(name).map_err(to_error))
679
+ }
680
+
681
+ fn unlink(&self, dentry: &Dentry) -> Result<(), Errno> {
682
+ self.at(dentry, |dir, name| dir.remove_file(name).map_err(to_error))
683
+ }
684
+
685
+ /// A host directory takes no lock the runtime's check of the source
686
+ /// holds, so another process of the host's changing it in between is
687
+ /// the host's to rule out. A link moves as itself, as `rename(2)`
688
+ /// moves one.
689
+ fn rename(
690
+ &self,
691
+ old: &Dentry,
692
+ new_dir: &dyn InodeOperations,
693
+ new: &Dentry,
694
+ flags: Option<RenameFlag>,
695
+ ) -> Result<(), Errno> {
696
+ if flags.is_some() {
697
+ return Err(Errno::InvalidInput);
698
+ }
699
+ let target = (new_dir as &dyn Any)
700
+ .downcast_ref::<Self>()
701
+ .ok_or(Errno::CrossesDevices)?;
702
+ self.at(old, |old_dir, old_name| {
703
+ target.at(new, |new_dir, new_name| {
704
+ old_dir
705
+ .rename(old_name, new_dir, new_name)
706
+ .map_err(to_error)
707
+ })
708
+ })
709
+ }
710
+ }
711
+
712
+ /// A host directory, open on the descriptor it holds, as 9p's `v9fs_dir_readdir`
713
+ /// reads the fid in `private_data`, so it follows the directory wherever it
714
+ /// moves.
715
+ struct BindDir(Arc<Dir>, Rdir);
716
+
717
+ impl FileOperations for BindDir {
718
+ fn llseek(
719
+ &mut self,
720
+ dentry: &Dentry,
721
+ pos: u64,
722
+ offset: i64,
723
+ whence: Whence,
724
+ ) -> Result<u64, Errno> {
725
+ generic_file_llseek(dentry, pos, offset, whence)
726
+ }
727
+
728
+ fn read_iter(&mut self, _iocb: &mut Kiocb, _buf: &mut [u8]) -> Result<usize, Errno> {
729
+ generic_read_dir()
730
+ }
731
+
732
+ /// What a listing began with stays on the open directory until it ends, as
733
+ /// 9p's `fid->rdir` holds what the server sent.
734
+ 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))
737
+ }
738
+
739
+ /// Make the host directory's names durable. Windows syncs no directory, so
740
+ /// there the host answers for them itself.
741
+ fn fsync(&mut self, _datasync: bool) -> Result<(), Errno> {
742
+ sync_dir(&self.0)
743
+ }
744
+ }
745
+
746
+ /// `dir` opened to read. cap-std holds a directory for its path alone on Linux,
747
+ /// which reads and syncs nothing, so the host judges reading it only here.
748
+ #[cfg(unix)]
749
+ fn open_to_read(dir: &Dir) -> Result<rustix::fd::OwnedFd, Errno> {
750
+ use rustix::fs::{openat, Mode, OFlags};
751
+
752
+ let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC;
753
+ openat(dir, ".", flags, Mode::empty()).map_err(|err| to_error(io::Error::from(err)))
754
+ }
755
+
756
+ #[cfg(unix)]
757
+ fn sync_dir(dir: &Dir) -> Result<(), Errno> {
758
+ rustix::fs::fsync(open_to_read(dir)?).map_err(|err| to_error(io::Error::from(err)))
759
+ }
760
+
761
+ #[cfg(not(unix))]
762
+ fn sync_dir(_dir: &Dir) -> Result<(), Errno> {
763
+ Ok(())
764
+ }
765
+
766
+ /// Refuse to open `dir` to read unless the host lets it be read, as `may_open`
767
+ /// asks `inode_permission`. A file holds it for what it was opened for, so a
768
+ /// directory reached only for its path answers no such question.
769
+ #[cfg(unix)]
770
+ fn may_read_dir(dir: &Dir) -> Result<(), Errno> {
771
+ open_to_read(dir).map(drop)
772
+ }
773
+
774
+ #[cfg(not(unix))]
775
+ fn may_read_dir(_dir: &Dir) -> Result<(), Errno> {
776
+ Ok(())
777
+ }
778
+
779
+ /// An open host file. The runtime names every offset, so each access seeks
780
+ /// first.
781
+ struct BindFile {
782
+ file: Arc<std::fs::File>,
783
+ }
784
+
785
+ 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)
791
+ }
792
+
793
+ /// The host places the write at the file's end as `O_APPEND` does, so
794
+ /// another writer's append lands before or after it, never over it.
795
+ #[cfg(unix)]
796
+ fn append(&mut self, iocb: &mut Kiocb, buf: &[u8]) -> Result<usize, Errno> {
797
+ use rustix::fs::{fcntl_getfl, fcntl_setfl, OFlags};
798
+
799
+ let mut file = &*self.file;
800
+ let flags = fcntl_getfl(file)
801
+ .map_err(io::Error::from)
802
+ .map_err(to_error)?;
803
+ fcntl_setfl(file, flags | OFlags::APPEND)
804
+ .map_err(io::Error::from)
805
+ .map_err(to_error)?;
806
+ let written = file.write(buf);
807
+ let end = file.stream_position();
808
+ fcntl_setfl(file, flags)
809
+ .map_err(io::Error::from)
810
+ .map_err(to_error)?;
811
+ let written = written.map_err(to_error)?;
812
+ iocb.pos = end.map_err(to_error)?;
813
+ Ok(written)
814
+ }
815
+ }
816
+
817
+ impl FileOperations for BindFile {
818
+ fn llseek(
819
+ &mut self,
820
+ dentry: &Dentry,
821
+ pos: u64,
822
+ offset: i64,
823
+ whence: Whence,
824
+ ) -> Result<u64, Errno> {
825
+ generic_file_llseek(dentry, pos, offset, whence)
826
+ }
827
+
828
+ fn read_iter(&mut self, iocb: &mut Kiocb, buf: &mut [u8]) -> Result<usize, Errno> {
829
+ let mut file = &*self.file;
830
+ file.seek(SeekFrom::Start(iocb.pos)).map_err(to_error)?;
831
+ let read = file.read(buf).map_err(to_error)?;
832
+ iocb.pos += read as u64;
833
+ Ok(read)
834
+ }
835
+
836
+ fn write_iter(&mut self, iocb: &mut Kiocb, buf: &[u8]) -> Result<usize, Errno> {
837
+ let written = match iocb.append {
838
+ true => self.append(iocb, buf)?,
839
+ false => {
840
+ let mut file = &*self.file;
841
+ file.seek(SeekFrom::Start(iocb.pos)).map_err(to_error)?;
842
+ let written = file.write(buf).map_err(to_error)?;
843
+ iocb.pos += written as u64;
844
+ written
845
+ }
846
+ };
847
+ crate::vfs::generic_write_sync(self, iocb, written)
848
+ }
849
+
850
+ fn fsync(&mut self, datasync: bool) -> Result<(), Errno> {
851
+ match datasync {
852
+ true => self.file.sync_data(),
853
+ false => self.file.sync_all(),
854
+ }
855
+ .map_err(to_error)
856
+ }
857
+
858
+ /// Reserve the room on the host, as `v9fs_file_fallocate` asks its server. Only
859
+ /// 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.
861
+ #[cfg(target_os = "linux")]
862
+ fn fallocate(&mut self, offset: u64, len: u64) -> Result<(), Errno> {
863
+ let flags = rustix::fs::FallocateFlags::empty();
864
+ rustix::fs::fallocate(&*self.file, flags, offset, len)
865
+ .map_err(|err| to_error(io::Error::from(err)))
866
+ }
867
+ }
868
+
869
+ #[cfg(test)]
870
+ mod tests {
871
+ use std::fs;
872
+ use std::path::PathBuf;
873
+
874
+ use super::*;
875
+ use crate::vfs::kern_path::{kern_path, KernPath};
876
+
877
+ /// A Bind reports times only where the host names them.
878
+ #[cfg(unix)]
879
+ mod set_times {
880
+ use super::*;
881
+ use crate::filesystem::{Overlay, Tmpfs};
882
+ 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};
885
+
886
+ /// One second past the Unix epoch, which no clock is at.
887
+ fn moment() -> std::time::SystemTime {
888
+ std::time::UNIX_EPOCH + std::time::Duration::from_secs(1)
889
+ }
890
+
891
+ fn set_modified() -> Iattr<'static> {
892
+ Iattr::for_times(None, Some(SetTime::At(moment())))
893
+ }
894
+
895
+ /// The root of `filesystem` mounted to change.
896
+ fn root_of(filesystem: Arc<dyn FileSystemType>) -> VfsPath {
897
+ let mount = Mount::new(
898
+ "/data",
899
+ Filesystem::new(filesystem).expect("the instance must stand"),
900
+ Access::ReadWrite,
901
+ )
902
+ .expect("/data is a guest path");
903
+ VfsPath::root(mount.mnt())
904
+ }
905
+
906
+ /// An Overlay of `lower` beneath an empty upper.
907
+ fn overlay_of(lower: Bind) -> Arc<Overlay> {
908
+ Arc::new(
909
+ Overlay::new(
910
+ vec![Filesystem::new(lower).expect("the instance must stand")],
911
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
912
+ )
913
+ .unwrap_or_else(|_| panic!("the Overlay must stack")),
914
+ )
915
+ }
916
+
917
+ /// What a stat of `path` beneath `root` reports as its modified time, once
918
+ /// it was set.
919
+ fn set_and_read_modified(root: &VfsPath, path: &str) -> Option<std::time::SystemTime> {
920
+ do_utimes_path(&Arc::default(), root, path, false, &set_modified())
921
+ .expect("the time must be set");
922
+ vfs_fstatat(&Arc::default(), root, path, false)
923
+ .ok()
924
+ .and_then(|stat| stat.mtime)
925
+ }
926
+
927
+ /// When the host last changed what `path` holds.
928
+ fn host_modified(path: &std::path::Path) -> Option<std::time::SystemTime> {
929
+ fs::metadata(path).and_then(|found| found.modified()).ok()
930
+ }
931
+
932
+ /// A host directory holding `dir/file.txt`.
933
+ fn host_with_a_file(name: &str) -> HostDir {
934
+ let host = HostDir::new(name);
935
+ fs::create_dir(host.0.join("dir")).expect("the host directory must be made");
936
+ fs::write(host.0.join("dir/file.txt"), "x").expect("the host file must be written");
937
+ host
938
+ }
939
+
940
+ fn bind_of(host: &HostDir) -> Bind {
941
+ Bind::new(&host.0).expect("the host directory must open")
942
+ }
943
+
944
+ // @behavior FS-185
945
+ #[test]
946
+ fn a_built_in_filesystem_keeps_the_times_a_caller_sets() {
947
+ let host = host_with_a_file("set-times");
948
+ let tmpfs: Tmpfs = [("dir/file.txt", "x")].into_iter().collect();
949
+ let roots = [
950
+ root_of(Arc::new(tmpfs)),
951
+ root_of(Arc::new(bind_of(&host))),
952
+ root_of(overlay_of(bind_of(&host))),
953
+ ];
954
+ let answers = roots.map(|root| {
955
+ (
956
+ set_and_read_modified(&root, "dir/file.txt"),
957
+ set_and_read_modified(&root, "dir"),
958
+ )
959
+ });
960
+ let set = Some(moment());
961
+ assert_eq!(
962
+ (answers, host_modified(&host.0.join("dir/file.txt"))),
963
+ ([(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"
966
+ );
967
+ }
968
+
969
+ // @behavior FS-186
970
+ #[test]
971
+ fn a_directory_time_set_through_an_overlay_leaves_its_lower_layer() {
972
+ let host = host_with_a_file("overlay-dir-time");
973
+ let before = host_modified(&host.0.join("dir"));
974
+ let seen = set_and_read_modified(&root_of(overlay_of(bind_of(&host))), "dir");
975
+ assert_eq!(
976
+ (seen, host_modified(&host.0.join("dir")) == before),
977
+ (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"
980
+ );
981
+ }
982
+
983
+ // A guest sees nothing of a link but that it is one, so its times are no more
984
+ // its to set than where it points is to read.
985
+ // @behavior FS-187
986
+ #[test]
987
+ fn a_link_keeps_its_own_times() {
988
+ 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");
990
+ assert_eq!(
991
+ do_utimes_path(
992
+ &Arc::default(),
993
+ &root_of(Arc::new(bind_of(&host))),
994
+ "link",
995
+ false,
996
+ &set_modified(),
997
+ ),
998
+ Err(Errno::Unsupported),
999
+ "vfs::do_utimes_pathfollowing no link of a Bind's link must answer ENOTSUP"
1000
+ );
1001
+ }
1002
+
1003
+ // Another file takes the name, so a time reaching it by name would be seen.
1004
+ // @behavior FS-188
1005
+ #[test]
1006
+ fn a_time_set_through_a_descriptor_reaches_the_file_it_holds() {
1007
+ let host = host_with_a_file("held-time");
1008
+ let root = root_of(Arc::new(bind_of(&host)));
1009
+ let how = OpenHow {
1010
+ read: true,
1011
+ ..OpenHow::default()
1012
+ };
1013
+ let held = filp_open(&Arc::default(), &root, "dir/file.txt", &how)
1014
+ .unwrap_or_else(|_| panic!("the file must open"));
1015
+ let file = host.0.join("dir/file.txt");
1016
+ fs::remove_file(&file).expect("the host removes the file");
1017
+ fs::write(&file, "y").expect("the host makes another");
1018
+ let other_before = host_modified(&file);
1019
+ let answer = do_utimes_fd(&Arc::default(), held.path(), &set_modified());
1020
+ let held_time = held.getattr().ok().and_then(|stat| stat.mtime);
1021
+ assert_eq!(
1022
+ (answer, held_time, host_modified(&file) == other_before),
1023
+ (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"
1026
+ );
1027
+ }
1028
+ }
1029
+
1030
+ /// The host directory at `path` as a Bind, reached through the
1031
+ /// VFS.
1032
+ fn bind_host(path: impl AsRef<Path>) -> KernPath {
1033
+ kern_path(Arc::new(
1034
+ Bind::new(path).expect("the host directory must open"),
1035
+ ))
1036
+ }
1037
+
1038
+ /// A fresh host directory of the test's own, removed when it drops.
1039
+ struct HostDir(PathBuf);
1040
+
1041
+ impl HostDir {
1042
+ fn new(name: &str) -> Self {
1043
+ let path = std::env::temp_dir()
1044
+ .join(format!("kobako-directory-{name}-{}", std::process::id()));
1045
+ let _ = fs::remove_dir_all(&path);
1046
+ fs::create_dir_all(&path).expect("the host directory must be created");
1047
+ Self(path)
1048
+ }
1049
+ }
1050
+
1051
+ impl Drop for HostDir {
1052
+ fn drop(&mut self) {
1053
+ let _ = fs::remove_dir_all(&self.0);
1054
+ }
1055
+ }
1056
+
1057
+ /// A Bind over `depth` nested directories each named `d`, with the file
1058
+ /// `f` at the bottom, and the path to that file.
1059
+ #[cfg(unix)]
1060
+ fn nested_tree(host: &HostDir, depth: usize) -> (Arc<Bind>, String) {
1061
+ let path = vec!["d"; depth].join("/");
1062
+ fs::create_dir_all(host.0.join(&path)).expect("the host tree must be made");
1063
+ fs::write(host.0.join(&path).join("f"), "x").expect("the host file must be written");
1064
+ let bind = Arc::new(Bind::new(&host.0).expect("the host directory must open"));
1065
+ (bind, format!("{path}/f"))
1066
+ }
1067
+
1068
+ // The same move behind each Bind, so the one told apart is what each
1069
+ // asks of the host again.
1070
+ // @behavior FS-207
1071
+ #[cfg(unix)]
1072
+ #[test]
1073
+ fn an_exclusive_bind_keeps_the_directory_it_found() {
1074
+ let size_after_a_move = |name: &str, exclusive: bool| {
1075
+ let host = HostDir::new(name);
1076
+ fs::create_dir(host.0.join("d")).expect("the host directory must be made");
1077
+ fs::write(host.0.join("d/f"), "x").expect("the host file must be written");
1078
+ let bind = Bind::new(&host.0)
1079
+ .expect("the host directory must open")
1080
+ .with_exclusive(exclusive);
1081
+ let root = kern_path(Arc::new(bind));
1082
+ root.vfs_lstat("d/f").expect("the file must stand");
1083
+ fs::rename(host.0.join("d"), host.0.join("moved")).expect("the host move must land");
1084
+ fs::create_dir(host.0.join("d")).expect("the host directory must be made");
1085
+ fs::write(host.0.join("d/f"), "xxxxx").expect("the host file must be written");
1086
+ root.vfs_lstat("d/f").map(|stat| stat.size)
1087
+ };
1088
+ assert_eq!(
1089
+ (
1090
+ size_after_a_move("exclusive-moved", true),
1091
+ size_after_a_move("plain-moved", false)
1092
+ ),
1093
+ (Ok(1), Ok(5)),
1094
+ "a walk through d/f after the host moved another d into place must reach the d it found \
1095
+ through an exclusive Bind, and the new d through one that is not"
1096
+ );
1097
+ }
1098
+
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.
1102
+ // @behavior FS-151
1103
+ #[cfg(unix)]
1104
+ #[test]
1105
+ fn a_walk_keeps_a_bounded_number_of_host_directories_open() {
1106
+ 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
+ let read = OpenHow {
1117
+ read: true,
1118
+ ..OpenHow::default()
1119
+ };
1120
+ let opened = vfs::kern_path::filp_open(&Arc::default(), &root, &file, &read);
1121
+ 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()
1126
+ );
1127
+ }
1128
+
1129
+ // @behavior FS-196
1130
+ #[test]
1131
+ fn a_directory_of_each_built_in_filesystem_answers_its_read_as_a_directory() {
1132
+ use crate::vfs::File;
1133
+ let host = HostDir::new("reads-directory");
1134
+ let read = |fs: Arc<dyn FileSystemType>| {
1135
+ let mount = crate::mount::Mount::new(
1136
+ "/data",
1137
+ Filesystem::new(fs).expect("the instance must stand"),
1138
+ crate::mount::Access::Read,
1139
+ )
1140
+ .expect("/data is a guest path");
1141
+ let mut dir = File::root(mount.mnt(), &Arc::default()).expect("the root opens");
1142
+ (dir.read(&mut [0; 1]).err(), dir.pread(&mut [0; 1], 0).err())
1143
+ };
1144
+ let overlay = crate::filesystem::Overlay::new(
1145
+ vec![
1146
+ Filesystem::new(crate::filesystem::Tmpfs::new()).expect("the instance must stand"),
1147
+ Filesystem::new(crate::filesystem::Tmpfs::new()).expect("the instance must stand"),
1148
+ ],
1149
+ None,
1150
+ )
1151
+ .expect("the Overlay must stack");
1152
+ let refused = Some(Errno::IsADirectory);
1153
+ for answer in [
1154
+ read(Arc::new(crate::filesystem::Tmpfs::new())),
1155
+ read(Arc::new(
1156
+ Bind::new(&host.0).expect("the host directory must open"),
1157
+ )),
1158
+ read(Arc::new(overlay)),
1159
+ ] {
1160
+ assert_eq!(
1161
+ answer,
1162
+ (refused.clone(), refused.clone()),
1163
+ "File::read and pread of a directory of each built-in Filesystem must answer \
1164
+ EISDIR, as generic_read_dir does"
1165
+ );
1166
+ }
1167
+ }
1168
+
1169
+ // Nothing holds `x` between the two stats, so what answers the second is the
1170
+ // negative dentry the first left, asked whether it still holds.
1171
+ // @behavior FS-193
1172
+ #[test]
1173
+ fn a_name_kept_as_absent_shows_what_the_host_made_there() {
1174
+ use crate::vfs::{self, Path as VfsPath};
1175
+ let host = HostDir::new("kept-absent");
1176
+ let mount = crate::mount::Mount::new(
1177
+ "/data",
1178
+ crate::filesystem::Filesystem::new(
1179
+ Bind::new(&host.0).expect("the host directory must open"),
1180
+ )
1181
+ .expect("the instance must stand"),
1182
+ crate::mount::Access::ReadWrite,
1183
+ )
1184
+ .expect("/data is a guest path");
1185
+ let root = VfsPath::root(mount.mnt());
1186
+ let cred = Arc::default();
1187
+ let stat = || vfs::vfs_fstatat(&cred, &root, "x", false).err();
1188
+ let before = stat();
1189
+ fs::write(host.0.join("x"), "x").expect("the host file must be written");
1190
+ assert_eq!(
1191
+ (before, stat()),
1192
+ (Some(Errno::NotFound), None),
1193
+ "vfs::vfs_fstatat of a name kept as absent, once the host made a file there, must \
1194
+ find the file"
1195
+ );
1196
+ }
1197
+
1198
+ // The Bind records nothing it makes, so what stands at the name is known only
1199
+ // to a lookup, which the absent dentry the walk kept must not answer for.
1200
+ // @behavior FS-194
1201
+ #[test]
1202
+ fn a_directory_made_where_a_name_was_kept_as_absent_is_found() {
1203
+ use crate::vfs::{self, Path as VfsPath};
1204
+ let host = HostDir::new("made-at-absent");
1205
+ let mount = crate::mount::Mount::new(
1206
+ "/data",
1207
+ crate::filesystem::Filesystem::new(
1208
+ Bind::new(&host.0).expect("the host directory must open"),
1209
+ )
1210
+ .expect("the instance must stand"),
1211
+ crate::mount::Access::ReadWrite,
1212
+ )
1213
+ .expect("/data is a guest path");
1214
+ let root = VfsPath::root(mount.mnt());
1215
+ let cred = Arc::default();
1216
+ let before = vfs::vfs_fstatat(&cred, &root, "made", false).err();
1217
+ vfs::filename_mkdirat(&cred, &root, "made").expect("the directory must be made");
1218
+ let after = vfs::vfs_fstatat(&cred, &root, "made", false).map(|made| made.file_type);
1219
+ assert_eq!(
1220
+ (before, after),
1221
+ (Some(Errno::NotFound), Ok(FileType::Dir)),
1222
+ "vfs::filename_mkdirat at a name kept as absent must leave the next walk finding \
1223
+ the directory, as d_drop leaves a dentry nothing recorded on"
1224
+ );
1225
+ }
1226
+
1227
+ // Nothing holds `x` between the two opens, so only a walk asking whether
1228
+ // the name it kept still stands finds the directory gone from beneath the
1229
+ // Mount, rather than following what it kept out through the moved one.
1230
+ // @behavior FS-161
1231
+ #[cfg(unix)]
1232
+ #[test]
1233
+ fn a_name_kept_for_the_next_walk_reaches_nothing_the_host_moved_out() {
1234
+ use crate::vfs::{self, OpenHow, Path as VfsPath};
1235
+ let host = HostDir::new("kept-name");
1236
+ fs::create_dir_all(host.0.join("m/x")).expect("the host tree must be made");
1237
+ fs::create_dir(host.0.join("outside")).expect("the host tree must be made");
1238
+ fs::write(host.0.join("m/x/secret"), "s").expect("the host file must be written");
1239
+ let mount = crate::mount::Mount::new(
1240
+ "/data",
1241
+ crate::filesystem::Filesystem::new(
1242
+ Bind::new(host.0.join("m")).expect("the host directory must open"),
1243
+ )
1244
+ .expect("the instance must stand"),
1245
+ crate::mount::Access::Read,
1246
+ )
1247
+ .expect("/data is a guest path");
1248
+ let root = VfsPath::root(mount.mnt());
1249
+ let cred = crate::security::restrict_self(
1250
+ &crate::security::prepare_creds(&[], None),
1251
+ [&crate::grant::Grant::Mount(mount.clone())],
1252
+ )
1253
+ .expect("every Mount stands");
1254
+ let read = OpenHow {
1255
+ read: true,
1256
+ ..OpenHow::default()
1257
+ };
1258
+ let open = || vfs::kern_path::filp_open(&cred, &root, "x/secret", &read).err();
1259
+ let before = open();
1260
+ fs::rename(host.0.join("m/x"), host.0.join("outside/x")).expect("the host must move it");
1261
+ assert_eq!(
1262
+ (before, open()),
1263
+ (None, Some(Errno::NotFound)),
1264
+ "vfs::do_file_open through a name kept since the last walk, once the host moved it \
1265
+ out of the Mount, must answer ENOENT"
1266
+ );
1267
+ }
1268
+
1269
+ // Another writer moves the name the Policy judges, then moves a refused
1270
+ // file onto where it went, between the judgement and the open, so only
1271
+ // telling what opened from what was judged keeps the open from reaching it.
1272
+ // @behavior FS-156
1273
+ #[test]
1274
+ fn an_open_reaches_only_the_entry_it_judged() {
1275
+ use crate::vfs::{self, OpenHow, Path as VfsPath};
1276
+
1277
+ /// Runs what it holds once, as a Policy is asked, then allows it.
1278
+ struct RunsWhenAsked(std::sync::Mutex<Option<Box<dyn FnOnce() + Send>>>);
1279
+
1280
+ impl crate::policy::Policy<crate::mount::MountRequest<'_>> for RunsWhenAsked {
1281
+ fn allows(&self, _request: &crate::mount::MountRequest<'_>) -> bool {
1282
+ let run = self.0.lock().expect("never poisoned").take();
1283
+ if let Some(run) = run {
1284
+ run();
1285
+ }
1286
+ true
1287
+ }
1288
+ }
1289
+
1290
+ let host = HostDir::new("open-identity");
1291
+ for dir in ["public", "archive"] {
1292
+ fs::create_dir(host.0.join(dir)).expect("the host tree must be made");
1293
+ }
1294
+ fs::write(host.0.join("public/x"), "judged").expect("the host file must be written");
1295
+ fs::write(host.0.join("archive/secret"), "refused").expect("the host file must be written");
1296
+ let filesystem = crate::filesystem::Filesystem::new(
1297
+ Bind::new(&host.0).expect("the host directory must open"),
1298
+ )
1299
+ .expect("the instance must stand");
1300
+ let writer =
1301
+ crate::mount::Mount::new("/data", filesystem.clone(), crate::mount::Access::ReadWrite)
1302
+ .expect("/data is a guest path");
1303
+ let writer = VfsPath::root(writer.mnt());
1304
+ let swap = Box::new(move || {
1305
+ let cred = Arc::default();
1306
+ vfs::filename_renameat2(&cred, &writer, "public/x", &writer, "archive/x")
1307
+ .expect("the name must move");
1308
+ vfs::filename_renameat2(&cred, &writer, "archive/secret", &writer, "archive/x")
1309
+ .expect("the refused file must move onto it");
1310
+ });
1311
+ let mount = crate::mount::Mount::new("/data", filesystem, crate::mount::Access::Read)
1312
+ .expect("/data is a guest path")
1313
+ .with_policy(Arc::new(RunsWhenAsked(std::sync::Mutex::new(Some(swap)))));
1314
+ let read = OpenHow {
1315
+ read: true,
1316
+ ..OpenHow::default()
1317
+ };
1318
+ let opened = vfs::kern_path::filp_open(
1319
+ &crate::security::restrict_self(
1320
+ &crate::security::prepare_creds(&[], None),
1321
+ [&crate::grant::Grant::Mount(mount.clone())],
1322
+ )
1323
+ .expect("every Mount stands"),
1324
+ &VfsPath::root(mount.mnt()),
1325
+ "public/x",
1326
+ &read,
1327
+ );
1328
+ assert_eq!(
1329
+ opened.err(),
1330
+ Some(Errno::NotFound),
1331
+ "vfs::do_file_open of a file another writer replaced after the Policy judged it must \
1332
+ answer ENOENT rather than open what stands there now"
1333
+ );
1334
+ }
1335
+
1336
+ // Other walks push what the descriptor walked to out of the bound, so only
1337
+ // a descriptor keeping its own directory still reaches it once the host
1338
+ // moved it.
1339
+ // @behavior FS-152
1340
+ #[cfg(unix)]
1341
+ #[test]
1342
+ fn a_directory_held_open_keeps_its_host_directory_past_the_bound() {
1343
+ use crate::vfs::{self, OpenHow, Path as VfsPath};
1344
+ let host = HostDir::new("held-past-bound");
1345
+ fs::create_dir_all(host.0.join("held")).expect("the host tree must be made");
1346
+ fs::write(host.0.join("held/f"), "x").expect("the host file must be written");
1347
+ let (bind, file) = nested_tree(&host, 100);
1348
+ let mount = crate::mount::Mount::new(
1349
+ "/data",
1350
+ crate::filesystem::Filesystem::new(bind).expect("the instance must stand"),
1351
+ crate::mount::Access::Read,
1352
+ )
1353
+ .expect("/data is a guest path");
1354
+ let root = VfsPath::root(mount.mnt());
1355
+ let cred = Arc::default();
1356
+ let directory = OpenHow {
1357
+ read: true,
1358
+ directory: true,
1359
+ ..OpenHow::default()
1360
+ };
1361
+ let Ok(held) = vfs::kern_path::filp_open(&cred, &root, "held", &directory) else {
1362
+ panic!("the directory must open");
1363
+ };
1364
+ let read = OpenHow {
1365
+ read: true,
1366
+ ..OpenHow::default()
1367
+ };
1368
+ assert!(
1369
+ vfs::kern_path::filp_open(&cred, &root, &file, &read).is_ok(),
1370
+ "the deep file must open"
1371
+ );
1372
+ fs::rename(host.0.join("held"), host.0.join("moved")).expect("the host must move it");
1373
+ assert!(
1374
+ vfs::vfs_fstatat(&cred, held.path(), "f", false).is_ok(),
1375
+ "vfs::vfs_fstatat through a directory held open beneath a Bind, once a walk passed \
1376
+ the bound and the host moved it, must still reach the directory it opened"
1377
+ );
1378
+ }
1379
+
1380
+ // The dentry the descriptor holds names the moved directory, so only a
1381
+ // Bind answering it stale keeps the removal of the new one from
1382
+ // killing it.
1383
+ // @behavior FS-135
1384
+ #[cfg(unix)]
1385
+ #[test]
1386
+ fn a_directory_remade_by_the_host_leaves_the_moved_ones_descriptor_alive() {
1387
+ use crate::mount::Mount;
1388
+ use crate::vfs::{self, OpenHow};
1389
+ let host = HostDir::new("remade");
1390
+ fs::create_dir_all(host.0.join("a")).expect("the host directory must be made");
1391
+ let filesystem = crate::filesystem::Filesystem::new(
1392
+ Bind::new(&host.0).expect("the host directory must open"),
1393
+ )
1394
+ .expect("the instance must stand");
1395
+ let mount = Mount::new("/data", filesystem, crate::mount::Access::ReadWrite)
1396
+ .expect("/data is a guest path");
1397
+ let root = vfs::Path::root(mount.mnt());
1398
+ let how = OpenHow {
1399
+ read: true,
1400
+ directory: true,
1401
+ ..OpenHow::default()
1402
+ };
1403
+ let Ok(opened) = vfs::kern_path::filp_open(&Arc::default(), &root, "a", &how) else {
1404
+ panic!("the directory must open");
1405
+ };
1406
+ let held = opened.path();
1407
+ fs::rename(host.0.join("a"), host.0.join("moved")).expect("the host must move it");
1408
+ fs::create_dir(host.0.join("a")).expect("the host must remake it");
1409
+ vfs::filename_rmdir(&Arc::default(), &root, "a").expect("the new directory must go");
1410
+ assert_eq!(
1411
+ (
1412
+ vfs::filename_mkdirat(&Arc::default(),held, "made"),
1413
+ host.0.join("moved/made").is_dir()
1414
+ ),
1415
+ (Ok(()), true),
1416
+ "vfs::filename_mkdirat through a Bind directory the host moved away, once vfs::filename_rmdir \
1417
+ removed the one remade at its path, must make the directory in the moved one"
1418
+ );
1419
+ }
1420
+
1421
+ /// A Policy refusing everything beneath `/data/refused`.
1422
+ #[cfg(unix)]
1423
+ struct RefusesRefused;
1424
+
1425
+ #[cfg(unix)]
1426
+ impl crate::policy::Policy<crate::mount::MountRequest<'_>> for RefusesRefused {
1427
+ fn allows(&self, request: &crate::mount::MountRequest<'_>) -> bool {
1428
+ !request.path.starts_with("/data/refused")
1429
+ }
1430
+ }
1431
+
1432
+ // The guest's descriptor of `a/d` keeps `a`'s dentry, and the host
1433
+ // directory a walk opened for it, so only a dentry the Bind answers
1434
+ // stale once the host moved `a` keeps a later walk through `a` from
1435
+ // reaching the moved directory while the Policy judges `a`.
1436
+ // @behavior FS-136
1437
+ #[cfg(unix)]
1438
+ #[test]
1439
+ fn a_walk_through_a_held_directory_the_host_moved_reaches_nothing_the_policy_refuses() {
1440
+ use crate::mount::Mount;
1441
+ use crate::vfs::{self, OpenHow};
1442
+ let host = HostDir::new("held-ancestor");
1443
+ fs::create_dir_all(host.0.join("a/d")).expect("the host tree must be made");
1444
+ fs::create_dir_all(host.0.join("refused")).expect("the host tree must be made");
1445
+ fs::write(host.0.join("a/d/secret"), "s").expect("the host file must be written");
1446
+ let filesystem = crate::filesystem::Filesystem::new(
1447
+ Bind::new(&host.0).expect("the host directory must open"),
1448
+ )
1449
+ .expect("the instance must stand");
1450
+ let mount = Mount::new("/data", filesystem, crate::mount::Access::Read)
1451
+ .expect("/data is a guest path")
1452
+ .with_policy(Arc::new(RefusesRefused));
1453
+ let root = vfs::Path::root(mount.mnt());
1454
+ let cred = crate::security::restrict_self(
1455
+ &crate::security::prepare_creds(&[], None),
1456
+ [&crate::grant::Grant::Mount(mount.clone())],
1457
+ )
1458
+ .expect("every Mount stands");
1459
+ let directory = OpenHow {
1460
+ read: true,
1461
+ directory: true,
1462
+ ..OpenHow::default()
1463
+ };
1464
+ let Ok(_held) = vfs::kern_path::filp_open(&cred, &root, "a/d", &directory) else {
1465
+ panic!("a/d must open");
1466
+ };
1467
+ fs::rename(host.0.join("a"), host.0.join("refused/a")).expect("the host must move a");
1468
+ fs::create_dir(host.0.join("a")).expect("the host must remake a");
1469
+ let read = OpenHow {
1470
+ read: true,
1471
+ ..OpenHow::default()
1472
+ };
1473
+ assert_eq!(
1474
+ vfs::kern_path::filp_open(&cred, &root, "a/d/secret", &read).err(),
1475
+ Some(Errno::NotFound),
1476
+ "vfs::do_file_open beneath a Bind Mount with a Policy, through a directory the host moved \
1477
+ beneath a refused path while a descriptor beneath it was held, must answer NotFound"
1478
+ );
1479
+ }
1480
+
1481
+ /// The roots of a Tmpfs, a Bind, and an Overlay, each holding a five byte
1482
+ /// `f`, by name.
1483
+ #[cfg(unix)]
1484
+ fn each_holding_five_bytes(host: &HostDir) -> [(&'static str, crate::vfs::Path); 3] {
1485
+ use crate::filesystem::Filesystem;
1486
+ use crate::filesystem::{Overlay, Tmpfs};
1487
+ use crate::mount::{Access, Mount};
1488
+ fs::write(host.0.join("f"), "hello").expect("the host file must be written");
1489
+ let tmpfs = || [("f", "hello")].into_iter().collect::<Tmpfs>();
1490
+ let overlay = Overlay::new(
1491
+ vec![Filesystem::new(tmpfs()).expect("the instance must stand")],
1492
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
1493
+ )
1494
+ .expect("the Overlay must stack");
1495
+ let root = |filesystem: Arc<dyn FileSystemType>| {
1496
+ let mount = Mount::new(
1497
+ "/data",
1498
+ Filesystem::new(filesystem).expect("the instance must stand"),
1499
+ Access::ReadWrite,
1500
+ )
1501
+ .expect("/data is a guest path");
1502
+ crate::vfs::Path::root(mount.mnt())
1503
+ };
1504
+ [
1505
+ ("Tmpfs", root(Arc::new(tmpfs()))),
1506
+ (
1507
+ "Bind",
1508
+ root(Arc::new(
1509
+ Bind::new(&host.0).expect("the host directory must open"),
1510
+ )),
1511
+ ),
1512
+ ("Overlay", root(Arc::new(overlay))),
1513
+ ]
1514
+ }
1515
+
1516
+ // @behavior FS-141
1517
+ #[cfg(unix)]
1518
+ #[test]
1519
+ fn a_file_removed_while_open_still_reports_itself() {
1520
+ use crate::vfs::{self, OpenHow};
1521
+ let host = HostDir::new("removed-open");
1522
+ let read = OpenHow {
1523
+ read: true,
1524
+ ..OpenHow::default()
1525
+ };
1526
+ for (name, root) in each_holding_five_bytes(&host) {
1527
+ let Ok(mut file) = vfs::kern_path::filp_open(&Arc::default(), &root, "f", &read) else {
1528
+ panic!("{name}'s f must open");
1529
+ };
1530
+ vfs::filename_unlinkat(&Arc::default(), &root, "f").expect("the name must go");
1531
+ let mut buf = [0; 5];
1532
+ assert_eq!(
1533
+ (
1534
+ file.getattr().map(|found| found.size).ok(),
1535
+ file.pread(&mut buf, 0),
1536
+ &buf
1537
+ ),
1538
+ (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"
1541
+ );
1542
+ }
1543
+ }
1544
+
1545
+ // @behavior FS-142
1546
+ #[cfg(unix)]
1547
+ #[test]
1548
+ fn a_file_removed_while_open_can_still_be_sized() {
1549
+ use crate::vfs::{self, OpenHow};
1550
+ let host = HostDir::new("removed-sized");
1551
+ let write = OpenHow {
1552
+ write: true,
1553
+ ..OpenHow::default()
1554
+ };
1555
+ for (name, root) in each_holding_five_bytes(&host) {
1556
+ let Ok(mut file) = vfs::kern_path::filp_open(&Arc::default(), &root, "f", &write)
1557
+ else {
1558
+ panic!("{name}'s f must open");
1559
+ };
1560
+ vfs::filename_unlinkat(&Arc::default(), &root, "f").expect("the name must go");
1561
+ assert_eq!(
1562
+ (
1563
+ file.truncate(2),
1564
+ file.getattr().map(|found| found.size).ok()
1565
+ ),
1566
+ (Ok(()), Some(2)),
1567
+ "File::truncate of a file whose name vfs::filename_unlinkat removed on a {name} \
1568
+ must size what it holds"
1569
+ );
1570
+ }
1571
+ }
1572
+
1573
+ // A dentry the host replaced is dropped by its identity, so the path
1574
+ // reaches the new file while the open one keeps its own descriptor.
1575
+ // @behavior FS-143
1576
+ #[cfg(unix)]
1577
+ #[test]
1578
+ fn a_file_replaced_while_open_answers_apart_from_its_path() {
1579
+ use crate::vfs::{self, OpenHow};
1580
+ let host = HostDir::new("replaced-open");
1581
+ let [_, (_, root), _] = each_holding_five_bytes(&host);
1582
+ let read = OpenHow {
1583
+ read: true,
1584
+ ..OpenHow::default()
1585
+ };
1586
+ let Ok(file) = vfs::kern_path::filp_open(&Arc::default(), &root, "f", &read) else {
1587
+ panic!("f must open");
1588
+ };
1589
+ fs::rename(host.0.join("f"), host.0.join("aside")).expect("the host must move f");
1590
+ fs::write(host.0.join("f"), "longer!").expect("the host must remake f");
1591
+ assert_eq!(
1592
+ (
1593
+ vfs::vfs_fstatat(&Arc::default(), &root, "f", true)
1594
+ .map(|found| found.size)
1595
+ .ok(),
1596
+ file.getattr().map(|found| found.size).ok()
1597
+ ),
1598
+ (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"
1601
+ );
1602
+ }
1603
+
1604
+ // The guest's descriptor of `a` keeps the Overlay's dentry and the
1605
+ // Bind's, whose host directory the host then moved aside; only the
1606
+ // Overlay asking the Bind's dentry drops its own for the `a` remade there.
1607
+ // @behavior FS-139
1608
+ #[cfg(unix)]
1609
+ #[test]
1610
+ fn an_overlay_takes_afresh_a_name_its_bind_layer_no_longer_holds() {
1611
+ use crate::filesystem::Filesystem;
1612
+ use crate::filesystem::{Overlay, Tmpfs};
1613
+ use crate::mount::{Access, Mount};
1614
+ use crate::vfs::{self, OpenHow};
1615
+ let host = HostDir::new("overlay-replaced");
1616
+ fs::create_dir(host.0.join("a")).expect("the host directory must be made");
1617
+ let lower = Filesystem::new(Bind::new(&host.0).expect("the host directory must open"))
1618
+ .expect("the instance must stand");
1619
+ let upper = Filesystem::new(Tmpfs::new()).expect("the instance must stand");
1620
+ let overlay = Overlay::new(vec![lower], Some(upper)).expect("the Overlay must stack");
1621
+ let mount = Mount::new(
1622
+ "/data",
1623
+ Filesystem::new(overlay).expect("the instance must stand"),
1624
+ Access::Read,
1625
+ )
1626
+ .expect("/data is a guest path");
1627
+ let root = vfs::Path::root(mount.mnt());
1628
+ let directory = OpenHow {
1629
+ read: true,
1630
+ directory: true,
1631
+ ..OpenHow::default()
1632
+ };
1633
+ let Ok(_held) = vfs::kern_path::filp_open(&Arc::default(), &root, "a", &directory) else {
1634
+ panic!("a must open");
1635
+ };
1636
+ fs::rename(host.0.join("a"), host.0.join("aside")).expect("the host must move a");
1637
+ fs::create_dir(host.0.join("a")).expect("the host must remake a");
1638
+ fs::write(host.0.join("a/f"), "new").expect("the host file must be written");
1639
+ let read = OpenHow {
1640
+ read: true,
1641
+ ..OpenHow::default()
1642
+ };
1643
+ let Ok(mut file) = vfs::kern_path::filp_open(&Arc::default(), &root, "a/f", &read) else {
1644
+ panic!("a/f must open through the directory the host remade");
1645
+ };
1646
+ let mut buf = [0; 3];
1647
+ assert_eq!(
1648
+ (file.pread(&mut buf, 0), &buf),
1649
+ (Ok(3), b"new"),
1650
+ "vfs::do_file_open through an Overlay over a Bind whose host replaced a directory \
1651
+ a descriptor holds must read the file standing there now"
1652
+ );
1653
+ }
1654
+
1655
+ // The host took the directory after the name was found, so only the open
1656
+ // asking the host answers that it is gone, rather than a descriptor that
1657
+ // fails at its first use.
1658
+ // @behavior FS-166
1659
+ #[test]
1660
+ fn a_directory_that_cannot_open_answers_why() {
1661
+ let host = HostDir::new("gone-before-open");
1662
+ fs::create_dir_all(host.0.join("a")).expect("the host directory must be made");
1663
+ let filesystem = crate::filesystem::Filesystem::new(
1664
+ Bind::new(&host.0).expect("the host directory must open"),
1665
+ )
1666
+ .expect("the instance must stand");
1667
+ let dentries = filesystem.dentries();
1668
+ let root = filesystem.root().expect(crate::vfs::MADE_ROOT).clone();
1669
+ let dir = dentries
1670
+ .alloc_parallel(&root, "a")
1671
+ .expect("no other walk holds the name");
1672
+ dir.lookup_inode(&filesystem, &root)
1673
+ .expect("the name must be found");
1674
+ fs::remove_dir(host.0.join("a")).expect("the host must remove it");
1675
+ let answer = dir
1676
+ .inode_ops()
1677
+ .expect("the name records its directory")
1678
+ .open(&dir, &OpenHow::default());
1679
+ assert_eq!(
1680
+ answer.err(),
1681
+ Some(Errno::NotFound),
1682
+ "InodeOperations::open of a Bind's directory the host removed must answer ENOENT"
1683
+ );
1684
+ }
1685
+
1686
+ // A walk finds what stands at the names now, so only comparing it with what
1687
+ // the dentry recorded keeps another directory from answering for it.
1688
+ // @behavior FS-167
1689
+ #[cfg(unix)]
1690
+ #[test]
1691
+ fn a_directory_the_host_replaced_is_not_walked_to_in_its_place() {
1692
+ let host = HostDir::new("replaced-before-walk");
1693
+ fs::create_dir_all(host.0.join("a")).expect("the host directory must be made");
1694
+ let filesystem = crate::filesystem::Filesystem::new(
1695
+ Bind::new(&host.0).expect("the host directory must open"),
1696
+ )
1697
+ .expect("the instance must stand");
1698
+ let dentries = filesystem.dentries();
1699
+ let root = filesystem.root().expect(crate::vfs::MADE_ROOT).clone();
1700
+ let dir = dentries
1701
+ .alloc_parallel(&root, "a")
1702
+ .expect("no other walk holds the name");
1703
+ dir.lookup_inode(&filesystem, &root)
1704
+ .expect("the name must be found");
1705
+ fs::rename(host.0.join("a"), host.0.join("moved")).expect("the host must move it");
1706
+ fs::create_dir(host.0.join("a")).expect("the host must make another");
1707
+ assert_eq!(
1708
+ dir.getattr().err(),
1709
+ Some(Errno::NotFound),
1710
+ "InodeOperations::getattr of a Bind directory the host replaced must answer ENOENT \
1711
+ rather than what stands there now"
1712
+ );
1713
+ }
1714
+
1715
+ // A host's own rename takes no such flag, so only the refusal keeps a
1716
+ // call asking for one from moving the file as a plain rename would.
1717
+ // @behavior FS-163
1718
+ #[test]
1719
+ fn a_filesystem_taking_no_rename_flag_refuses_one() {
1720
+ let host = HostDir::new("rename-flag");
1721
+ fs::write(host.0.join("a"), "a").expect("the host file must be written");
1722
+ let filesystem = crate::filesystem::Filesystem::new(
1723
+ Bind::new(&host.0).expect("the host directory must open"),
1724
+ )
1725
+ .expect("the instance must stand");
1726
+ let dentries = filesystem.dentries();
1727
+ let root = filesystem.root().expect(crate::vfs::MADE_ROOT).clone();
1728
+ let dir = root.inode().expect("the root stands").ops().clone();
1729
+ let at = |name| {
1730
+ dentries
1731
+ .alloc_parallel(&root, name)
1732
+ .expect("no other walk holds the name")
1733
+ };
1734
+ let answer = dir.rename(
1735
+ &at("a"),
1736
+ dir.as_ref(),
1737
+ &at("b"),
1738
+ Some(RenameFlag::NoReplace),
1739
+ );
1740
+ assert_eq!(
1741
+ (answer, host.0.join("a").exists()),
1742
+ (Err(Errno::InvalidInput), true),
1743
+ "InodeOperations::rename of a Bind asked for a flag must answer EINVAL and move \
1744
+ nothing"
1745
+ );
1746
+ }
1747
+
1748
+ // A directory a Bind has named but not opened yet is walked to by the
1749
+ // names its dentry stands at when first asked, so a move the dentry
1750
+ // followed meanwhile leads to it, as 9p's walk reads them then.
1751
+ #[test]
1752
+ fn a_directory_named_before_a_move_opens_where_its_dentry_went() {
1753
+ let host = HostDir::new("named-then-moved");
1754
+ fs::create_dir_all(host.0.join("a")).expect("the host directory must be made");
1755
+ fs::write(host.0.join("a/note"), "n").expect("the host file must be written");
1756
+ let filesystem = crate::filesystem::Filesystem::new(
1757
+ Bind::new(&host.0).expect("the host directory must open"),
1758
+ )
1759
+ .expect("the instance must stand");
1760
+ let dentries = filesystem.dentries();
1761
+ let root = filesystem.root().expect(crate::vfs::MADE_ROOT).clone();
1762
+ let at = |dir: &Arc<Dentry>, name| {
1763
+ dentries
1764
+ .alloc_parallel(dir, name)
1765
+ .expect("no other walk holds the name")
1766
+ };
1767
+ let a = at(&root, "a");
1768
+ fs::rename(host.0.join("a"), host.0.join("x")).expect("the host must move it");
1769
+ dentries.move_dentry(&a, &at(&root, "x"));
1770
+ let note = at(&a, "note");
1771
+ assert!(
1772
+ matches!(
1773
+ root.inode().expect("the root stands").ops().lookup(&note),
1774
+ Ok(Lookup::Found(inode)) if inode.file_type() == FileType::RegFile
1775
+ ),
1776
+ "a name looked up through Bind in a directory not yet opened, once its dentry moved \
1777
+ with it, must be found where the dentry stands"
1778
+ );
1779
+ }
1780
+
1781
+ /// A host directory of the test's own holding the FIFO `pipe`.
1782
+ #[cfg(unix)]
1783
+ fn make_fifo_host(name: &str) -> HostDir {
1784
+ let host = HostDir::new(name);
1785
+ let made = std::process::Command::new("mkfifo")
1786
+ .arg(host.0.join("pipe"))
1787
+ .status()
1788
+ .expect("mkfifo must run");
1789
+ assert!(made.success(), "the FIFO must be made");
1790
+ host
1791
+ }
1792
+
1793
+ // Opening the FIFO with no writer would wait for one, so only an open
1794
+ // refused before it waits answers within the deadline; `/dev/null`
1795
+ // is a device every unix host holds.
1796
+ // @behavior FS-090
1797
+ #[cfg(unix)]
1798
+ #[test]
1799
+ fn a_directory_opens_only_a_file_or_a_directory() {
1800
+ let host = make_fifo_host("fifo-open");
1801
+ let fifo = bind_host(&host.0);
1802
+ let devices = bind_host("/dev");
1803
+ let (sender, answered) = std::sync::mpsc::channel();
1804
+ std::thread::spawn(move || {
1805
+ let read = OpenHow {
1806
+ read: true,
1807
+ ..OpenHow::default()
1808
+ };
1809
+ let _ = sender.send([
1810
+ fifo.open("pipe", &read).err(),
1811
+ devices.open("null", &read).err(),
1812
+ ]);
1813
+ });
1814
+ assert_eq!(
1815
+ answered.recv_timeout(crate::sched::testing::MAX_WAIT),
1816
+ Ok([Some(Errno::PermissionDenied), Some(Errno::PermissionDenied)]),
1817
+ "a FIFO and a device opened through Bind::open must be refused as permission \
1818
+ denied without waiting"
1819
+ );
1820
+ }
1821
+
1822
+ // The host reports each open of an entry to a watch on its directory, and
1823
+ // an open by O_PATH opens nothing, so a refusal it reports no open for
1824
+ // never acted on the entry.
1825
+ // @behavior FS-208
1826
+ #[cfg(target_os = "linux")]
1827
+ #[test]
1828
+ fn an_entry_refused_as_no_file_is_never_opened() {
1829
+ use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
1830
+
1831
+ let host = make_fifo_host("fifo-never-opened");
1832
+ let dir = Dir::open_ambient_dir(&host.0, cap_std::ambient_authority())
1833
+ .expect("the host directory must open");
1834
+ // SAFETY: inotify_init1 answers a descriptor nothing else owns, or -1.
1835
+ let watch = unsafe { libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC) };
1836
+ assert!(watch >= 0, "the host must give an inotify descriptor");
1837
+ // SAFETY: `watch` was just made and is owned here alone.
1838
+ let watch = unsafe { OwnedFd::from_raw_fd(watch) };
1839
+ let path = std::ffi::CString::new(host.0.as_os_str().as_encoded_bytes())
1840
+ .expect("the host path holds no NUL");
1841
+ // SAFETY: `path` is NUL-terminated and outlives the call.
1842
+ let added =
1843
+ unsafe { libc::inotify_add_watch(watch.as_raw_fd(), path.as_ptr(), libc::IN_OPEN) };
1844
+ assert!(added >= 0, "the host directory must be watched");
1845
+ let read = OpenHow {
1846
+ read: true,
1847
+ ..OpenHow::default()
1848
+ };
1849
+ let refused = open_in(&dir, "pipe", &read, false).err();
1850
+ let mut events = [0u8; 256];
1851
+ // SAFETY: `events` is writable for its whole length.
1852
+ let reported =
1853
+ unsafe { libc::read(watch.as_raw_fd(), events.as_mut_ptr().cast(), events.len()) };
1854
+ assert_eq!(
1855
+ (refused, reported),
1856
+ (Some(Errno::PermissionDenied), -1),
1857
+ "a FIFO a Bind is asked to open must be refused as permission denied with no open \
1858
+ of it reported to a watch on its host directory"
1859
+ );
1860
+ }
1861
+
1862
+ // @behavior FS-091
1863
+ #[cfg(unix)]
1864
+ #[test]
1865
+ fn a_directory_reports_a_fifo_as_one() {
1866
+ let host = make_fifo_host("fifo-type");
1867
+ let directory = bind_host(&host.0);
1868
+ let listed: Vec<_> = directory
1869
+ .iterate_dir()
1870
+ .expect("the directory must list")
1871
+ .into_iter()
1872
+ .map(|entry| entry.file_type)
1873
+ .collect();
1874
+ assert_eq!(
1875
+ (
1876
+ directory.vfs_lstat("pipe").map(|stat| stat.file_type),
1877
+ listed
1878
+ ),
1879
+ (Ok(FileType::Fifo), vec![FileType::Fifo]),
1880
+ "a FIFO beneath a Bind, looked up and listed through the VFS, must answer a FIFO"
1881
+ );
1882
+ }
1883
+
1884
+ // `/dev/null` stands on every unix host, and a socket needs only its file
1885
+ // to stand here, so neither is opened.
1886
+ // @behavior FS-144
1887
+ #[cfg(unix)]
1888
+ #[test]
1889
+ fn a_directory_reports_the_kind_its_host_gives_a_special_file() {
1890
+ let host = HostDir::new("special");
1891
+ let _socket = std::os::unix::net::UnixListener::bind(host.0.join("sock"))
1892
+ .expect("the socket must be bound");
1893
+ let kind = |directory: KernPath, name| directory.vfs_lstat(name).map(|stat| stat.file_type);
1894
+ assert_eq!(
1895
+ (
1896
+ kind(bind_host(&host.0), "sock"),
1897
+ kind(bind_host("/dev"), "null"),
1898
+ ),
1899
+ (Ok(FileType::Sock), Ok(FileType::Chrdev)),
1900
+ "vfs_lstat of a socket and of /dev/null must answer the kind the host \
1901
+ gives each"
1902
+ );
1903
+ }
1904
+
1905
+ // @behavior FS-005
1906
+ #[test]
1907
+ fn a_directory_serves_the_files_of_its_host_directory() {
1908
+ let host = HostDir::new("serves");
1909
+ fs::write(host.0.join("data.csv"), "a,b").expect("the host file must be written");
1910
+
1911
+ let directory = bind_host(&host.0);
1912
+ let mut file = directory
1913
+ .open(
1914
+ "data.csv",
1915
+ &OpenHow {
1916
+ read: true,
1917
+ ..OpenHow::default()
1918
+ },
1919
+ )
1920
+ .expect("the host file must open");
1921
+ let mut buf = [0; 16];
1922
+ let read = file
1923
+ .read_iter(&mut Kiocb::new(0), &mut buf)
1924
+ .expect("the host file must read");
1925
+ assert_eq!(
1926
+ &buf[..read],
1927
+ b"a,b",
1928
+ "a host file read through a Bind's open must read back its content"
1929
+ );
1930
+ }
1931
+
1932
+ // @behavior FS-006
1933
+ #[test]
1934
+ fn a_directory_writes_into_its_host_directory() {
1935
+ let host = HostDir::new("writes");
1936
+ let directory = bind_host(&host.0);
1937
+ directory
1938
+ .open_or_create(
1939
+ "out.txt",
1940
+ &OpenHow {
1941
+ write: true,
1942
+ ..OpenHow::default()
1943
+ },
1944
+ )
1945
+ .expect("a new file must be created")
1946
+ .write_iter(&mut Kiocb::new(0), b"written")
1947
+ .expect("the write must land");
1948
+ assert_eq!(
1949
+ fs::read(host.0.join("out.txt")).expect("the host file must exist"),
1950
+ b"written",
1951
+ "a file created through a Bind's open must land in the host directory"
1952
+ );
1953
+ }
1954
+
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
+ // The host file exists beneath `d`, so only the refusal can keep the
1986
+ // open from reaching it.
1987
+ // @behavior FS-029
1988
+ #[cfg(windows)]
1989
+ #[test]
1990
+ fn a_directory_on_windows_refuses_a_name_holding_a_backslash() {
1991
+ let host = HostDir::new("backslash");
1992
+ fs::create_dir_all(host.0.join("d")).expect("the host directory must be created");
1993
+ fs::write(host.0.join("d").join("f"), "x").expect("the host file must be written");
1994
+ let directory = bind_host(&host.0);
1995
+ assert!(
1996
+ matches!(
1997
+ directory.open(r"d\f", &OpenHow::default()),
1998
+ Err(Errno::InvalidInput)
1999
+ ),
2000
+ "a path holding a backslash opened through a Bind on Windows must be refused as \
2001
+ invalid input"
2002
+ );
2003
+ }
2004
+
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
+ // @behavior FS-153
2041
+ #[cfg(windows)]
2042
+ #[test]
2043
+ fn a_directory_on_windows_refuses_a_name_it_reads_as_another() {
2044
+ let host = HostDir::new("aliases");
2045
+ fs::write(host.0.join("secret"), "x").expect("the host file must be written");
2046
+ let directory = bind_host(&host.0);
2047
+ assert!(
2048
+ ["secret.", "secret:stream", "CON"]
2049
+ .iter()
2050
+ .all(|name| matches!(
2051
+ directory.open(name, &OpenHow::default()),
2052
+ Err(Errno::InvalidInput)
2053
+ )),
2054
+ "a name Windows reads as another, opened through a Bind on Windows, must be refused \
2055
+ as invalid input"
2056
+ );
2057
+ }
2058
+
2059
+ // The host answers ENAMETOOLONG, which only a mapping naming it keeps
2060
+ // from reaching the guest as an EIO.
2061
+ // @behavior FS-065
2062
+ #[test]
2063
+ fn a_directory_answers_a_host_failure_as_the_error_naming_it() {
2064
+ let host = HostDir::new("names");
2065
+ let directory = bind_host(&host.0);
2066
+ let created = directory.open_or_create(
2067
+ &"x".repeat(300),
2068
+ &OpenHow {
2069
+ write: true,
2070
+ ..OpenHow::default()
2071
+ },
2072
+ );
2073
+ assert_eq!(
2074
+ created.map(drop),
2075
+ Err(Errno::InvalidFilename),
2076
+ "a name past the host's limit created through Bind::open must fail as \
2077
+ InvalidFilename, not as an unnamed failure"
2078
+ );
2079
+ }
2080
+
2081
+ // Which offset a host refuses depends on its filesystem: tmpfs, XFS and
2082
+ // 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.
2084
+ // @behavior FS-068
2085
+ #[cfg(any(target_os = "linux", target_os = "macos"))]
2086
+ #[test]
2087
+ fn a_directory_answers_a_host_file_too_large_as_too_large() {
2088
+ assert_eq!(
2089
+ to_error(io::Error::from_raw_os_error(27)),
2090
+ Errno::FileTooLarge,
2091
+ "a host EFBIG through Bind's error mapping must fail as FileTooLarge, \
2092
+ not as an unnamed failure"
2093
+ );
2094
+ }
2095
+
2096
+ // A host out of descriptors cannot be staged without starving the test
2097
+ // process, so the host's own EMFILE, 24 on Linux and macOS alike, is what
2098
+ // the Bind must name.
2099
+ // @behavior FS-209
2100
+ #[cfg(any(target_os = "linux", target_os = "macos"))]
2101
+ #[test]
2102
+ fn a_directory_answers_a_host_out_of_descriptors_as_too_many_open_files() {
2103
+ assert_eq!(
2104
+ to_error(io::Error::from_raw_os_error(24)),
2105
+ Errno::TooManyOpenFiles,
2106
+ "a host EMFILE through a Bind must fail as too many open files, as a host \
2107
+ socket's does, not as an unnamed failure"
2108
+ );
2109
+ }
2110
+
2111
+ // A host refusal Rust folds into another kind is staged by its errno, as
2112
+ // an unlink in another user's sticky directory needs a second user.
2113
+ // @behavior FS-210
2114
+ #[cfg(unix)]
2115
+ #[test]
2116
+ fn a_directory_answers_a_host_refusal_by_the_errno_it_holds() {
2117
+ use rustix::io::Errno as HostErrno;
2118
+ let answers = [
2119
+ HostErrno::PERM,
2120
+ HostErrno::LOOP,
2121
+ HostErrno::BADF,
2122
+ HostErrno::OVERFLOW,
2123
+ HostErrno::NODEV,
2124
+ HostErrno::STALE,
2125
+ HostErrno::ILSEQ,
2126
+ HostErrno::NOTSUP,
2127
+ HostErrno::OPNOTSUPP,
2128
+ ]
2129
+ .map(|errno| to_error(io::Error::from_raw_os_error(errno.raw_os_error())));
2130
+ assert_eq!(
2131
+ answers,
2132
+ [
2133
+ Errno::NotPermitted,
2134
+ Errno::FilesystemLoop,
2135
+ Errno::BadDescriptor,
2136
+ Errno::ValueTooLarge,
2137
+ Errno::NoSuchDevice,
2138
+ Errno::StaleNetworkFileHandle,
2139
+ Errno::IllegalSequence,
2140
+ Errno::Unsupported,
2141
+ Errno::Unsupported,
2142
+ ],
2143
+ "a host EPERM, ELOOP, EBADF, EOVERFLOW, ENODEV, ESTALE, EILSEQ, ENOTSUP, or \
2144
+ EOPNOTSUPP through a Bind must fail under that same name, as Linux answers it, \
2145
+ not as permission denied or an unnamed failure"
2146
+ );
2147
+ }
2148
+
2149
+ // A quota, a file's link count, and a running program cannot be staged
2150
+ // on every host, so the host's own errno stands for each.
2151
+ // @behavior FS-212
2152
+ #[cfg(unix)]
2153
+ #[test]
2154
+ fn a_directory_answers_a_host_out_of_quota_links_or_a_busy_program_by_name() {
2155
+ use rustix::io::Errno as HostErrno;
2156
+ let answers = [HostErrno::DQUOT, HostErrno::MLINK, HostErrno::TXTBSY]
2157
+ .map(|errno| to_error(io::Error::from_raw_os_error(errno.raw_os_error())));
2158
+ assert_eq!(
2159
+ answers,
2160
+ [
2161
+ Errno::QuotaExceeded,
2162
+ Errno::TooManyLinks,
2163
+ Errno::ExecutableFileBusy,
2164
+ ],
2165
+ "a host EDQUOT, EMLINK, or ETXTBSY through a Bind must fail under that same name, \
2166
+ as Linux answers it, not as an unnamed failure"
2167
+ );
2168
+ }
2169
+
2170
+ // Another process holding the file open is staged by its Win32 code.
2171
+ // @behavior FS-211
2172
+ #[cfg(windows)]
2173
+ #[test]
2174
+ fn a_directory_answers_a_host_file_held_without_sharing_as_permission_denied() {
2175
+ let held = windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION as i32;
2176
+ assert_eq!(
2177
+ to_error(io::Error::from_raw_os_error(held)),
2178
+ Errno::PermissionDenied,
2179
+ "a Windows host file another process holds without sharing must fail through a \
2180
+ Bind as permission denied, as wasmtime-wasi answers it, not as an unnamed failure"
2181
+ );
2182
+ }
2183
+
2184
+ // A host down reaches a Bind only on a network filesystem, so the host's
2185
+ // own EHOSTDOWN stands for it here.
2186
+ #[cfg(unix)]
2187
+ #[test]
2188
+ fn a_directory_answers_a_host_down_as_ehostdown() {
2189
+ let down = io::Error::from_raw_os_error(rustix::io::Errno::HOSTDOWN.raw_os_error());
2190
+ assert_eq!(
2191
+ to_error(down),
2192
+ Errno::HostDown,
2193
+ "a host EHOSTDOWN through a Bind must fail as EHOSTDOWN, as Linux hands a network \
2194
+ filesystem's failure on, not as the unreachable host a socket's WASI code reads"
2195
+ );
2196
+ }
2197
+
2198
+ // A Bind's root is the directory cap-std opened for its path alone on Linux,
2199
+ // so a sync of the descriptor it holds would answer EBADF only there.
2200
+ // @behavior FS-171
2201
+ #[test]
2202
+ fn a_binds_root_syncs() {
2203
+ let host = HostDir::new("sync-root");
2204
+ let mount = crate::mount::Mount::new(
2205
+ "/data",
2206
+ Filesystem::new(Bind::new(&host.0).expect("the host directory must open"))
2207
+ .expect("the instance must stand"),
2208
+ crate::mount::Access::Read,
2209
+ )
2210
+ .expect("/data is a guest path");
2211
+ let Ok(mut root) = crate::vfs::File::root(mount.mnt(), &Arc::default()) else {
2212
+ panic!("the root must open");
2213
+ };
2214
+ assert_eq!(
2215
+ root.fsync(false),
2216
+ Ok(()),
2217
+ "File::fsync of a Bind's root must succeed, as Linux syncs a directory"
2218
+ );
2219
+ }
2220
+
2221
+ // A rename moves a name out from under `openat2` only within a race, which
2222
+ // the Linux baseline meets at times and no test can stage, so the answer the
2223
+ // refusal reaches is held here.
2224
+ // @behavior FS-191
2225
+ #[test]
2226
+ fn a_name_carried_out_as_it_is_opened_answers_not_found() {
2227
+ let refused = io::Error::new(io::ErrorKind::PermissionDenied, "a path led outside");
2228
+ assert_eq!(
2229
+ to_error(refused),
2230
+ Errno::NotFound,
2231
+ "cap-std's refusal of a single name leading out of a Bind's directory must answer \
2232
+ ENOENT, as a move carried it away"
2233
+ );
2234
+ }
2235
+
2236
+ // Eviction leaves a walk to reach a directory from one far above it, so only
2237
+ // a path past what the host takes in one call shows it goes on by name.
2238
+ // @behavior FS-190
2239
+ #[cfg(unix)]
2240
+ #[test]
2241
+ fn a_directory_past_the_hosts_path_limit_is_reached() {
2242
+ let host = HostDir::new("past-path-max");
2243
+ let top = Dir::open_ambient_dir(&host.0, ambient_authority()).expect("the host directory");
2244
+ let names = vec!["n".repeat(200); 30];
2245
+ let deepest = names
2246
+ .iter()
2247
+ .fold(top.try_clone().expect("a second handle"), |at, name| {
2248
+ at.create_dir(name)
2249
+ .expect("the host directory must be made");
2250
+ at.open_dir(name).expect("the host directory must open")
2251
+ });
2252
+ deepest
2253
+ .write("key", "x")
2254
+ .expect("the host file must be written");
2255
+ let reached = walk::walk(&top, &names).map(|dir| dir.exists("key"));
2256
+ assert_eq!(
2257
+ reached.ok(),
2258
+ Some(true),
2259
+ "a Bind's walk to a directory 6000 bytes beneath the one it holds must reach it, past \
2260
+ what the host takes in one call"
2261
+ );
2262
+ }
2263
+
2264
+ // Root reads anything, so a host letting this one be read has nothing to
2265
+ // show. Linux reaches a directory for its path alone, so only asking to read
2266
+ // it there makes the host answer; macOS answers on any open.
2267
+ // @behavior FS-189
2268
+ #[cfg(unix)]
2269
+ #[test]
2270
+ fn a_directory_the_host_lets_no_one_read_refuses_an_open_to_read() {
2271
+ use std::os::unix::fs::PermissionsExt;
2272
+
2273
+ let host = HostDir::new("unreadable");
2274
+ let dir = host.0.join("sealed");
2275
+ fs::create_dir(&dir).expect("the host directory must be made");
2276
+ let mode = |mode| fs::Permissions::from_mode(mode);
2277
+ fs::set_permissions(&dir, mode(0o000)).expect("the host directory's mode must be set");
2278
+ let enforced = fs::read_dir(&dir).is_err();
2279
+ let mount = crate::mount::Mount::new(
2280
+ "/data",
2281
+ Filesystem::new(Bind::new(&host.0).expect("the host directory must open"))
2282
+ .expect("the instance must stand"),
2283
+ crate::mount::Access::Read,
2284
+ )
2285
+ .expect("/data is a guest path");
2286
+ let root = crate::vfs::Path::root(mount.mnt());
2287
+ let how = crate::vfs::OpenHow {
2288
+ read: true,
2289
+ directory: true,
2290
+ ..Default::default()
2291
+ };
2292
+ let answer = crate::vfs::kern_path::filp_open(&Arc::default(), &root, "sealed", &how).err();
2293
+ fs::set_permissions(&dir, mode(0o755)).expect("the host directory's mode must be restored");
2294
+ if enforced {
2295
+ assert_eq!(
2296
+ answer,
2297
+ Some(Errno::PermissionDenied),
2298
+ "vfs::do_file_open to read a host directory no one may read must answer EACCES"
2299
+ );
2300
+ }
2301
+ }
2302
+
2303
+ // Linux holds a directory for its path alone, so only asking the host to
2304
+ // read it refuses one no one may read; macOS refuses it on any open. Root
2305
+ // reads anything, so only another user sees the refusal.
2306
+ // @behavior FS-200
2307
+ #[cfg(unix)]
2308
+ #[test]
2309
+ fn a_bind_of_a_directory_the_host_lets_no_one_read_is_refused() {
2310
+ use std::os::unix::fs::PermissionsExt;
2311
+
2312
+ let host = HostDir::new("unreadable-root");
2313
+ let mode = |mode| fs::Permissions::from_mode(mode);
2314
+ fs::set_permissions(&host.0, mode(0o100)).expect("the host directory's mode must be set");
2315
+ let enforced = fs::read_dir(&host.0).is_err();
2316
+ let answer = Bind::new(&host.0).err().map(|err| err.kind());
2317
+ fs::set_permissions(&host.0, mode(0o755))
2318
+ .expect("the host directory's mode must be restored");
2319
+ if enforced {
2320
+ assert_eq!(
2321
+ answer,
2322
+ Some(io::ErrorKind::PermissionDenied),
2323
+ "Bind::new of a host directory no one may read must be refused as permission denied"
2324
+ );
2325
+ }
2326
+ }
2327
+
2328
+ // macOS has no open for a directory's path alone. Root reads anything, so
2329
+ // only a walk run as another user sees the difference.
2330
+ // @behavior FS-172
2331
+ #[cfg(target_os = "linux")]
2332
+ #[test]
2333
+ fn a_directory_a_host_lets_be_searched_reports_itself() {
2334
+ use std::os::unix::fs::PermissionsExt;
2335
+
2336
+ let host = HostDir::new("search-only");
2337
+ fs::create_dir(host.0.join("searched")).expect("the host directory must be made");
2338
+ let mode = |mode| fs::Permissions::from_mode(mode);
2339
+ fs::set_permissions(host.0.join("searched"), mode(0o111))
2340
+ .expect("the host directory's mode must be set");
2341
+ let mount = crate::mount::Mount::new(
2342
+ "/data",
2343
+ Filesystem::new(Bind::new(&host.0).expect("the host directory must open"))
2344
+ .expect("the instance must stand"),
2345
+ crate::mount::Access::Read,
2346
+ )
2347
+ .expect("/data is a guest path");
2348
+ let root = crate::vfs::Path::root(mount.mnt());
2349
+ let found = crate::vfs::vfs_fstatat(&Arc::default(), &root, "searched", false);
2350
+ fs::set_permissions(host.0.join("searched"), mode(0o755))
2351
+ .expect("the host directory's mode must be restored");
2352
+ assert_eq!(
2353
+ found.map(|metadata| metadata.file_type),
2354
+ Ok(FileType::Dir),
2355
+ "vfs::vfs_fstatat of a host directory only searchable must report it, as Linux's stat \
2356
+ needs no read permission on it"
2357
+ );
2358
+ }
2359
+
2360
+ // A host that folds case answers `A` with the entry stored as `a`, so the
2361
+ // VFS finds one entry on both sides; only a host that folds witnesses it.
2362
+ // @behavior FS-205
2363
+ #[test]
2364
+ fn a_rename_to_another_spelling_of_one_name_changes_nothing() {
2365
+ let host = HostDir::new("case-only-rename");
2366
+ fs::write(host.0.join("a"), "x").expect("the host file must be written");
2367
+ if !host.0.join("A").exists() {
2368
+ return;
2369
+ }
2370
+ let mount = crate::mount::Mount::new(
2371
+ "/data",
2372
+ Filesystem::new(Bind::new(&host.0).expect("the host directory must open"))
2373
+ .expect("the instance must stand"),
2374
+ crate::mount::Access::ReadWrite,
2375
+ )
2376
+ .expect("/data is a guest path");
2377
+ let root = crate::vfs::Path::root(mount.mnt());
2378
+ let renamed = crate::vfs::filename_renameat2(&Arc::default(), &root, "a", &root, "A");
2379
+ let stored: Vec<_> = fs::read_dir(&host.0)
2380
+ .expect("the host directory must list")
2381
+ .map(|entry| entry.expect("the entry must read").file_name())
2382
+ .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
+ assert_eq!(
2390
+ (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"
2395
+ );
2396
+ }
2397
+
2398
+ // Linux walks a directory it may only search, so a stat through one
2399
+ // succeeds there; the Bind reads the directory to learn the name's
2400
+ // spelling, which the mode refuses. Root reads anything, so only another
2401
+ // user sees the refusal.
2402
+ // @behavior FS-202
2403
+ #[cfg(unix)]
2404
+ #[test]
2405
+ fn a_name_beneath_a_directory_the_host_lets_only_be_searched_is_refused() {
2406
+ use std::os::unix::fs::PermissionsExt;
2407
+
2408
+ let host = HostDir::new("search-only-name");
2409
+ fs::create_dir(host.0.join("searched")).expect("the host directory must be made");
2410
+ fs::write(host.0.join("searched/x"), "x").expect("the host file must be written");
2411
+ let mode = |mode| fs::Permissions::from_mode(mode);
2412
+ fs::set_permissions(host.0.join("searched"), mode(0o111))
2413
+ .expect("the host directory's mode must be set");
2414
+ let enforced = fs::read_dir(host.0.join("searched")).is_err();
2415
+ let mount = crate::mount::Mount::new(
2416
+ "/data",
2417
+ Filesystem::new(Bind::new(&host.0).expect("the host directory must open"))
2418
+ .expect("the instance must stand"),
2419
+ crate::mount::Access::Read,
2420
+ )
2421
+ .expect("/data is a guest path");
2422
+ let root = crate::vfs::Path::root(mount.mnt());
2423
+ let found = crate::vfs::vfs_fstatat(&Arc::default(), &root, "searched/x", false);
2424
+ fs::set_permissions(host.0.join("searched"), mode(0o755))
2425
+ .expect("the host directory's mode must be restored");
2426
+ if enforced {
2427
+ assert_eq!(
2428
+ found.err(),
2429
+ Some(Errno::PermissionDenied),
2430
+ "vfs::vfs_fstatat of a file beneath a host directory only searchable must \
2431
+ answer EACCES, as the Bind reads the directory to spell the name"
2432
+ );
2433
+ }
2434
+ }
2435
+
2436
+ // Only Linux keeps a name that is not UTF-8; macOS refuses to make one.
2437
+ // @behavior FS-066
2438
+ #[cfg(target_os = "linux")]
2439
+ #[test]
2440
+ fn a_directory_refuses_to_list_a_host_name_that_is_not_utf8() {
2441
+ use std::os::unix::ffi::OsStrExt;
2442
+
2443
+ 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");
2446
+ let directory = bind_host(&host.0);
2447
+ assert_eq!(
2448
+ directory.iterate_dir().map(drop),
2449
+ Err(Errno::IllegalSequence),
2450
+ "a host name that is not UTF-8 listed through iterate_dir must fail as \
2451
+ IllegalSequence, not as an unnamed failure"
2452
+ );
2453
+ }
2454
+
2455
+ // The host file only reads, so a host open asking to write, as one that
2456
+ // creates must, would be refused where nothing is to be created.
2457
+ // @behavior FS-064
2458
+ #[cfg(unix)]
2459
+ #[test]
2460
+ fn a_directory_opens_a_file_already_there_without_writing_to_create_it() {
2461
+ use std::os::unix::fs::PermissionsExt;
2462
+ 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");
2466
+ let directory = bind_host(&host.0);
2467
+ let creates = OpenHow {
2468
+ read: true,
2469
+ ..OpenHow::default()
2470
+ };
2471
+ assert_eq!(
2472
+ (
2473
+ directory.open_or_create("note", &creates).map(drop),
2474
+ directory.open_or_create("new", &creates).map(drop),
2475
+ host.0.join("new").exists()
2476
+ ),
2477
+ (Ok(()), Ok(()), true),
2478
+ "a Bind::open that may create, of a read-only host file already there, must open \
2479
+ it, and of a missing one must create it"
2480
+ );
2481
+ }
2482
+
2483
+ // The link's target is a readable file, so only the refusal of the
2484
+ // link itself keeps the open from reaching it.
2485
+ // @behavior FS-047
2486
+ #[cfg(unix)]
2487
+ #[test]
2488
+ fn a_directory_opens_no_link() {
2489
+ let host = HostDir::new("nofollow");
2490
+ 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");
2492
+ let opened = bind_host(&host.0)
2493
+ .open(
2494
+ "link",
2495
+ &OpenHow {
2496
+ read: true,
2497
+ ..OpenHow::default()
2498
+ },
2499
+ )
2500
+ .map(drop);
2501
+ assert_eq!(
2502
+ opened,
2503
+ Err(Errno::FilesystemLoop),
2504
+ "a host link opened through a Bind must be refused as a link, its target unreached"
2505
+ );
2506
+ }
2507
+
2508
+ // The VFS refuses a link it found before asking the Bind, so only the
2509
+ // Bind's own open sees a link the host put in place after the lookup.
2510
+ // @behavior FS-047
2511
+ #[cfg(unix)]
2512
+ #[test]
2513
+ fn a_directory_refuses_a_link_put_in_place_of_what_it_opens() {
2514
+ let host = HostDir::new("nofollow-swapped");
2515
+ 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");
2517
+ let dir = Dir::open_ambient_dir(&host.0, ambient_authority()).expect("the host directory");
2518
+ let read = OpenHow {
2519
+ read: true,
2520
+ ..OpenHow::default()
2521
+ };
2522
+ assert_eq!(
2523
+ open_in(&dir, "link", &read, false).map(drop),
2524
+ Err(Errno::FilesystemLoop),
2525
+ "a host link standing where a Bind opens a file must be refused as a link, its \
2526
+ target unreached"
2527
+ );
2528
+ }
2529
+
2530
+ // The target's five bytes would show as the link's size if a lookup
2531
+ // that follows none still followed it.
2532
+ // @behavior FS-048
2533
+ #[cfg(unix)]
2534
+ #[test]
2535
+ fn a_directory_reports_a_link_a_lookup_does_not_follow_as_a_link() {
2536
+ let host = HostDir::new("lstat");
2537
+ 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");
2539
+ let directory = bind_host(&host.0);
2540
+ let listed = directory
2541
+ .iterate_dir()
2542
+ .expect("the host directory must list")
2543
+ .into_iter()
2544
+ .find(|entry| entry.name == "link")
2545
+ .map(|entry| entry.file_type);
2546
+ assert_eq!(
2547
+ (
2548
+ directory.vfs_lstat("link").map(|stat| stat.file_type),
2549
+ listed
2550
+ ),
2551
+ (Ok(FileType::Symlink), Some(FileType::Symlink)),
2552
+ "a host link beneath a Bind, looked up through vfs_lstat and listed through \
2553
+ iterate_dir, must report a link"
2554
+ );
2555
+ }
2556
+
2557
+ // A directory's size is the host's to choose, so the host's own stat
2558
+ // is the only witness of it.
2559
+ // @behavior FS-138
2560
+ #[test]
2561
+ fn a_directory_reports_the_size_its_host_reports() {
2562
+ let host = HostDir::new("dir-size");
2563
+ fs::create_dir(host.0.join("sub")).expect("the host directory must be created");
2564
+ fs::write(host.0.join("sub/file"), "hello").expect("the host file must be written");
2565
+ let directory = bind_host(&host.0);
2566
+ assert_eq!(
2567
+ directory.vfs_lstat("sub").map(|stat| stat.size),
2568
+ Ok(fs::metadata(host.0.join("sub"))
2569
+ .expect("the host directory must stand")
2570
+ .len()),
2571
+ "a host directory beneath a Bind looked up through vfs_lstat must report the size \
2572
+ its host reports"
2573
+ );
2574
+ }
2575
+
2576
+ // @behavior FS-028
2577
+ #[test]
2578
+ fn a_directory_refuses_to_remove_a_directory_as_a_file() {
2579
+ let host = HostDir::new("unlink-dir");
2580
+ fs::create_dir(host.0.join("sub")).expect("the host directory must be created");
2581
+ let directory = bind_host(&host.0);
2582
+ assert_eq!(
2583
+ directory.vfs_unlink("sub"),
2584
+ Err(Errno::IsADirectory),
2585
+ "a host directory beneath a Bind removed through vfs_unlink must answer EISDIR"
2586
+ );
2587
+ }
2588
+
2589
+ /// A host directory holding `dir/sub/y` and `secret`, with `dir/in`
2590
+ /// linking to `sub` and `dir/up` to `../secret`.
2591
+ #[cfg(unix)]
2592
+ fn make_links(name: &str) -> HostDir {
2593
+ let host = HostDir::new(name);
2594
+ fs::create_dir_all(host.0.join("dir/sub")).expect("the host directory must be created");
2595
+ fs::write(host.0.join("dir/sub/y"), "inner").expect("the inner file must be written");
2596
+ 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");
2600
+ host
2601
+ }
2602
+
2603
+ // The link leads to a directory inside the host directory, so only
2604
+ // refusing the link itself keeps it from being opened.
2605
+ // @behavior FS-099
2606
+ #[cfg(unix)]
2607
+ #[test]
2608
+ fn a_directory_opens_no_link_as_a_directory_where_asked_not_to_follow() {
2609
+ let host = make_links("open-dir-nofollow");
2610
+ let directory = bind_host(&host.0);
2611
+ let dir = directory.open_dir("dir").expect("the directory must open");
2612
+ assert_eq!(
2613
+ dir.open_dir("in").map(drop),
2614
+ Err(Errno::FilesystemLoop),
2615
+ "a link to a directory opened through Bind::open_dir must be a link loop"
2616
+ );
2617
+ }
2618
+
2619
+ // @behavior FS-114
2620
+ #[cfg(unix)]
2621
+ #[test]
2622
+ fn a_directory_reads_where_a_link_points() {
2623
+ let host = make_links("read-link");
2624
+ let directory = bind_host(&host.0);
2625
+ let dir = directory.open_dir("dir").expect("the directory must open");
2626
+ assert_eq!(
2627
+ (dir.vfs_readlink("up"), dir.vfs_readlink("sub")),
2628
+ (Ok("../secret".to_string()), Err(Errno::InvalidInput)),
2629
+ "vfs_readlink beneath a Bind must answer where a link points as stored, and refuse \
2630
+ a directory with EINVAL"
2631
+ );
2632
+ }
2633
+
2634
+ // @behavior FS-007
2635
+ #[cfg(unix)]
2636
+ #[test]
2637
+ fn a_directory_reaches_nothing_outside_its_host_directory() {
2638
+ let outside = HostDir::new("outside");
2639
+ fs::write(outside.0.join("secret"), "host").expect("the outside file must be written");
2640
+ 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");
2643
+
2644
+ let directory = bind_host(&host.0);
2645
+ assert!(
2646
+ directory
2647
+ .open(
2648
+ "escape",
2649
+ &OpenHow {
2650
+ read: true,
2651
+ ..OpenHow::default()
2652
+ }
2653
+ )
2654
+ .is_err(),
2655
+ "a link out of the host directory opened through a Bind's open must be refused"
2656
+ );
2657
+ }
2658
+
2659
+ // @behavior FS-071
2660
+ #[cfg(unix)]
2661
+ #[test]
2662
+ fn a_directory_reports_the_identity_its_host_gives_a_path() {
2663
+ use std::os::unix::fs::MetadataExt;
2664
+
2665
+ let host = HostDir::new("identity");
2666
+ 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");
2668
+ let directory = bind_host(&host.0);
2669
+ let reported = directory
2670
+ .vfs_lstat("dir")
2671
+ .expect("the directory must stand");
2672
+ assert_eq!(
2673
+ (reported.dev, reported.ino),
2674
+ (expected.dev(), expected.ino()),
2675
+ "a host directory beneath a Bind looked up through vfs_lstat must carry the device \
2676
+ and inode numbers the host reports"
2677
+ );
2678
+ }
2679
+
2680
+ // Two handles racing one-byte appends: a two-step append (read the
2681
+ // length, then write there) loses about half the bytes to the other
2682
+ // handle's writes, so only an append the host places keeps them all.
2683
+ // @behavior FS-069
2684
+ #[cfg(unix)]
2685
+ #[test]
2686
+ fn a_directory_appends_at_its_host_files_end_in_one_step() {
2687
+ let host = HostDir::new("append");
2688
+ fs::write(host.0.join("log.txt"), "").expect("the host file must be written");
2689
+ let directory = bind_host(&host.0);
2690
+
2691
+ let writers: Vec<_> = [b"a", b"b"]
2692
+ .into_iter()
2693
+ .map(|byte| {
2694
+ let directory = directory.clone();
2695
+ std::thread::spawn(move || {
2696
+ let how = OpenHow {
2697
+ write: true,
2698
+ ..OpenHow::default()
2699
+ };
2700
+ let mut file = directory
2701
+ .open("log.txt", &how)
2702
+ .expect("the host file must open to write");
2703
+ for _ in 0..10_000 {
2704
+ file.write_iter(&mut Kiocb::new(0).with_append(), byte)
2705
+ .expect("the append must succeed");
2706
+ }
2707
+ })
2708
+ })
2709
+ .collect();
2710
+ for writer in writers {
2711
+ writer.join().expect("the writer must finish");
2712
+ }
2713
+
2714
+ let written = fs::read(host.0.join("log.txt")).expect("the host file must be read");
2715
+ assert_eq!(
2716
+ (
2717
+ written.iter().filter(|&&b| b == b'a').count(),
2718
+ written.iter().filter(|&&b| b == b'b').count()
2719
+ ),
2720
+ (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"
2723
+ );
2724
+ }
2725
+
2726
+ // ext4 hands a removed directory's inode number to the next one made,
2727
+ // so the number staying unused while open is what the opened directory
2728
+ // keeps. A host that never reuses numbers cannot show that, but every
2729
+ // Linux host lists the removed directory among the process's
2730
+ // descriptors while it is open.
2731
+ // @behavior FS-086
2732
+ #[cfg(target_os = "linux")]
2733
+ #[test]
2734
+ fn a_directory_opened_keeps_its_inode_number_from_the_next_one_made() {
2735
+ use std::os::unix::fs::MetadataExt;
2736
+
2737
+ let host = HostDir::new("held");
2738
+ let ino = |path: &str| {
2739
+ fs::metadata(host.0.join(path))
2740
+ .expect("it must stand")
2741
+ .ino()
2742
+ };
2743
+ fs::create_dir(host.0.join("dir")).expect("the host directory must be made");
2744
+ let first = ino("dir");
2745
+ fs::remove_dir(host.0.join("dir")).expect("the host directory must go");
2746
+ fs::create_dir(host.0.join("dir")).expect("the host directory must be made");
2747
+ let reuses = ino("dir") == first;
2748
+ let first = ino("dir");
2749
+ let directory = bind_host(&host.0);
2750
+ let opened = directory.open_dir("dir").expect("the directory must open");
2751
+ fs::remove_dir(host.0.join("dir")).expect("the host directory must go");
2752
+ let removed = format!("{} (deleted)", host.0.join("dir").display());
2753
+ let held_open = fs::read_dir("/proc/self/fd")
2754
+ .expect("the process's descriptors must list")
2755
+ .filter_map(|entry| fs::read_link(entry.ok()?.path()).ok())
2756
+ .any(|target| target.to_string_lossy() == removed);
2757
+ fs::create_dir(host.0.join("dir")).expect("the host directory must be made");
2758
+ let made = ino("dir");
2759
+ drop(opened);
2760
+ assert!(
2761
+ held_open,
2762
+ "a directory Bind::open_dir opened must stay open once removed"
2763
+ );
2764
+ if !reuses {
2765
+ eprintln!("the host does not reuse inode numbers; nothing more to witness");
2766
+ return;
2767
+ }
2768
+ assert_ne!(
2769
+ made, first,
2770
+ "a directory made where Bind::open_dir holds a removed one open must take \
2771
+ another inode number on a host reusing them"
2772
+ );
2773
+ }
2774
+
2775
+ // Windows refuses to move a directory a handle holds open, so the host
2776
+ // cannot make the move this witnesses there.
2777
+ // @behavior FS-108
2778
+ #[cfg(unix)]
2779
+ #[test]
2780
+ fn a_directory_opened_from_a_directory_follows_it_when_the_host_moves_it() {
2781
+ let host = HostDir::new("opened-moves");
2782
+ fs::create_dir(host.0.join("dir")).expect("the host directory must be made");
2783
+ let directory = bind_host(&host.0);
2784
+ let dir = directory
2785
+ .open_dir("dir")
2786
+ .expect("the host directory must open");
2787
+ fs::rename(host.0.join("dir"), host.0.join("moved")).expect("the host must move it");
2788
+ dir.open_or_create(
2789
+ "made",
2790
+ &OpenHow {
2791
+ write: true,
2792
+ ..OpenHow::default()
2793
+ },
2794
+ )
2795
+ .expect("the file must be made");
2796
+ assert_eq!(
2797
+ (
2798
+ host.0.join("moved/made").is_file(),
2799
+ host.0.join("dir").exists()
2800
+ ),
2801
+ (true, false),
2802
+ "a file made through a directory Bind::open_dir opened before the host moved it \
2803
+ must stand beneath the directory's new host path"
2804
+ );
2805
+ }
2806
+
2807
+ // @behavior FS-081
2808
+ #[test]
2809
+ fn a_directory_spells_names_it_matches_exactly_as_given() {
2810
+ let host = HostDir::new("spelled");
2811
+ fs::create_dir(host.0.join("dir")).expect("the host directory must be made");
2812
+ fs::write(host.0.join("dir/file"), "x").expect("the host file must be written");
2813
+ let directory = bind_host(&host.0);
2814
+ let dir = directory
2815
+ .open_dir("dir")
2816
+ .expect("the host directory must open");
2817
+ assert_eq!(
2818
+ (dir.lookup("file"), dir.lookup("new")),
2819
+ (Ok("file".to_string()), Ok("new".to_string())),
2820
+ "a name asked of Bind::lookup in the spelling its host stores, and one it \
2821
+ does not hold, must come back as given"
2822
+ );
2823
+ }
2824
+
2825
+ // macOS volumes fold case and Unicode form unless formatted
2826
+ // case-sensitive, where every spelling is already the stored one.
2827
+ // @behavior FS-082
2828
+ #[cfg(target_os = "macos")]
2829
+ #[test]
2830
+ fn a_directory_spells_a_path_as_a_folding_host_stores_it() {
2831
+ let host = HostDir::new("folded");
2832
+ fs::create_dir(host.0.join("private")).expect("the host directory must be made");
2833
+ fs::write(host.0.join("private/caf\u{e9}"), "x").expect("the host file must be written");
2834
+ if !host.0.join("PRIVATE").exists() {
2835
+ eprintln!("the host volume matches names exactly; nothing folds to witness");
2836
+ return;
2837
+ }
2838
+ let directory = bind_host(&host.0);
2839
+ let private = directory
2840
+ .open_dir("PRIVATE")
2841
+ .expect("the host directory must open in any case");
2842
+ assert_eq!(
2843
+ (
2844
+ directory.lookup("Private"),
2845
+ private.lookup("CAFE\u{301}"),
2846
+ private.lookup("missing")
2847
+ ),
2848
+ (
2849
+ Ok("private".to_string()),
2850
+ Ok("caf\u{e9}".to_string()),
2851
+ Ok("missing".to_string())
2852
+ ),
2853
+ "a name asked of Bind::lookup in another case and Unicode form on a host \
2854
+ folding both must come back as the host stores it, one it does not hold as given"
2855
+ );
2856
+ }
2857
+ }