kobako 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. checksums.yaml +4 -4
  2. data/.githooks/linux-tests.sh +29 -0
  3. data/.release-please-manifest.json +1 -1
  4. data/CHANGELOG.md +125 -0
  5. data/Cargo.lock +457 -494
  6. data/README.md +2 -3
  7. data/ROADMAP.md +0 -1
  8. data/crates/kobako-runtime/CHANGELOG.md +90 -0
  9. data/crates/kobako-runtime/Cargo.toml +14 -15
  10. data/crates/kobako-runtime/README.md +1 -1
  11. data/crates/kobako-runtime/src/cred.rs +32 -20
  12. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +300 -22
  13. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +56 -22
  14. data/crates/kobako-runtime/src/filesystem/bind/unicode.rs +109 -0
  15. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +33 -14
  16. data/crates/kobako-runtime/src/filesystem/bind.rs +393 -220
  17. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +2 -0
  18. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +9 -10
  19. data/crates/kobako-runtime/src/filesystem/overlay.rs +277 -46
  20. data/crates/kobako-runtime/src/filesystem/rdir.rs +8 -27
  21. data/crates/kobako-runtime/src/filesystem/testing.rs +31 -0
  22. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +47 -13
  23. data/crates/kobako-runtime/src/filesystem.rs +2 -0
  24. data/crates/kobako-runtime/src/fork.rs +239 -16
  25. data/crates/kobako-runtime/src/limits.rs +17 -41
  26. data/crates/kobako-runtime/src/locking/seqlock.rs +29 -3
  27. data/crates/kobako-runtime/src/locking.rs +508 -113
  28. data/crates/kobako-runtime/src/memcg.rs +83 -160
  29. data/crates/kobako-runtime/src/mount.rs +0 -30
  30. data/crates/kobako-runtime/src/net/connections.rs +53 -13
  31. data/crates/kobako-runtime/src/net/egress.rs +44 -24
  32. data/crates/kobako-runtime/src/net/http.rs +888 -456
  33. data/crates/kobako-runtime/src/net/lookup.rs +150 -50
  34. data/crates/kobako-runtime/src/net/namespace.rs +97 -95
  35. data/crates/kobako-runtime/src/net/reactor.rs +298 -203
  36. data/crates/kobako-runtime/src/net/resolv/darwin.rs +8 -3
  37. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +50 -0
  38. data/crates/kobako-runtime/src/net/resolv/stub.rs +29 -23
  39. data/crates/kobako-runtime/src/net/resolv/windows.rs +14 -44
  40. data/crates/kobako-runtime/src/net/resolv.rs +39 -15
  41. data/crates/kobako-runtime/src/net/skbuff.rs +109 -0
  42. data/crates/kobako-runtime/src/net/socket.rs +51 -52
  43. data/crates/kobako-runtime/src/net/task.rs +223 -0
  44. data/crates/kobako-runtime/src/net/tcp.rs +410 -158
  45. data/crates/kobako-runtime/src/net/tls.rs +65 -3
  46. data/crates/kobako-runtime/src/net/transport.rs +72 -47
  47. data/crates/kobako-runtime/src/net/udp.rs +231 -129
  48. data/crates/kobako-runtime/src/net.rs +3 -0
  49. data/crates/kobako-runtime/src/sched.rs +244 -58
  50. data/crates/kobako-runtime/src/security.rs +27 -16
  51. data/crates/kobako-runtime/src/vfs/dentry.rs +80 -41
  52. data/crates/kobako-runtime/src/vfs/file.rs +52 -53
  53. data/crates/kobako-runtime/src/vfs/kern_path.rs +24 -11
  54. data/crates/kobako-runtime/src/vfs/namei.rs +399 -184
  55. data/crates/kobako-runtime/src/vfs/namespace.rs +123 -40
  56. data/crates/kobako-runtime/src/vfs/stat.rs +105 -16
  57. data/crates/kobako-runtime/src/vfs.rs +1 -0
  58. data/crates/kobako-runtime/src/wait.rs +75 -50
  59. data/crates/kobako-transport/CHANGELOG.md +7 -0
  60. data/crates/kobako-transport/Cargo.toml +1 -1
  61. data/crates/kobako-transport/README.md +1 -1
  62. data/crates/kobako-wasmtime/CHANGELOG.md +47 -0
  63. data/crates/kobako-wasmtime/Cargo.toml +27 -6
  64. data/crates/kobako-wasmtime/README.md +3 -3
  65. data/crates/kobako-wasmtime/src/abi.rs +2 -1
  66. data/crates/kobako-wasmtime/src/ambient.rs +11 -2
  67. data/crates/kobako-wasmtime/src/cache/unix.rs +95 -0
  68. data/crates/kobako-wasmtime/src/cache/windows.rs +359 -0
  69. data/crates/kobako-wasmtime/src/cache.rs +88 -103
  70. data/crates/kobako-wasmtime/src/driver.rs +40 -27
  71. data/crates/kobako-wasmtime/src/invocation.rs +21 -7
  72. data/crates/kobako-wasmtime/src/lib.rs +2 -0
  73. data/crates/kobako-wasmtime/src/limiter.rs +78 -25
  74. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +13 -17
  75. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +4 -5
  76. data/crates/kobako-wasmtime/src/preview1/differential.rs +1 -1
  77. data/crates/kobako-wasmtime/src/preview1/fd.rs +23 -19
  78. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +130 -197
  79. data/crates/kobako-wasmtime/src/preview1/path.rs +3 -3
  80. data/crates/kobako-wasmtime/src/preview1/poll.rs +28 -22
  81. data/crates/kobako-wasmtime/src/preview1/random.rs +125 -0
  82. data/crates/kobako-wasmtime/src/preview1/testing.rs +31 -0
  83. data/crates/kobako-wasmtime/src/preview1.rs +85 -9
  84. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +2 -2
  85. data/crates/kobako-wasmtime/src/preview2/host.rs +609 -249
  86. data/crates/kobako-wasmtime/src/preview2/http.rs +299 -215
  87. data/crates/kobako-wasmtime/src/preview2/io.rs +17 -4
  88. data/crates/kobako-wasmtime/src/preview2/table.rs +24 -72
  89. data/crates/kobako-wasmtime/src/trap.rs +68 -23
  90. data/crates/kobako-wasmtime/src/waits.rs +59 -0
  91. data/crates/kobako-wasmtime/src/wasi.rs +91 -10
  92. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
  93. data/data/kobako.wasm +0 -0
  94. data/ext/kobako/Cargo.toml +6 -2
  95. data/ext/kobako/src/escape.rs +332 -26
  96. data/ext/kobako/src/filesystem/grants.rs +5 -7
  97. data/ext/kobako/src/filesystem/ruby.rs +10 -3
  98. data/ext/kobako/src/filesystem.rs +47 -8
  99. data/ext/kobako/src/fork.rs +72 -0
  100. data/ext/kobako/src/gvl.rs +499 -76
  101. data/ext/kobako/src/handoff.rs +490 -0
  102. data/ext/kobako/src/lib.rs +10 -0
  103. data/ext/kobako/src/network.rs +5 -3
  104. data/ext/kobako/src/pinned_value.rs +28 -15
  105. data/ext/kobako/src/runtime/bridge.rs +32 -25
  106. data/ext/kobako/src/runtime.rs +74 -43
  107. data/lib/kobako/catalog/handles.rb +9 -5
  108. data/lib/kobako/codec/decoder.rb +1 -1
  109. data/lib/kobako/codec/state.rb +2 -18
  110. data/lib/kobako/codec/value_budget.rb +4 -4
  111. data/lib/kobako/codec.rb +5 -6
  112. data/lib/kobako/errors.rb +4 -7
  113. data/lib/kobako/filesystem.rb +1 -1
  114. data/lib/kobako/fork.rb +42 -0
  115. data/lib/kobako/handle.rb +1 -2
  116. data/lib/kobako/sandbox.rb +17 -36
  117. data/lib/kobako/sandbox_options.rb +7 -9
  118. data/lib/kobako/usage.rb +4 -2
  119. data/lib/kobako/version.rb +1 -1
  120. data/lib/kobako.rb +2 -2
  121. data/sig/kobako/catalog/handles.rbs +2 -0
  122. data/sig/kobako/codec/state.rbs +0 -4
  123. data/sig/kobako/codec/value_budget.rbs +1 -1
  124. data/sig/kobako/codec.rbs +2 -2
  125. data/sig/kobako/errors.rbs +0 -3
  126. data/sig/kobako/fork.rbs +17 -0
  127. data/sig/kobako/runtime.rbs +2 -2
  128. data/sig/kobako/sandbox.rbs +3 -12
  129. data/sig/kobako/sandbox_options.rbs +0 -2
  130. metadata +15 -4
  131. data/lib/kobako/pool.rb +0 -162
  132. data/sig/core/thread.rbs +0 -6
  133. data/sig/kobako/pool.rbs +0 -46
@@ -1,58 +1,211 @@
1
- //! The host directories a Bind keeps open, each a descriptor of the host's
2
- //! own. A dentry holds the one above it, so keeping one for every dentry would
1
+ //! The host directories Binds keep open, each a descriptor of the host's own.
2
+ //! A dentry holds the one above it, so keeping one for every dentry would
3
3
  //! spend a descriptor per level of depth, which no table of a guest's counts.
4
4
  //! A directory the guest holds open keeps its own; the rest are kept up to a
5
- //! bound, the oldest let go and walked to again when asked, as 9p walks to a
6
- //! dentry it holds no fid for.
5
+ //! bound the process's Binds share, the oldest let go and walked to again
6
+ //! when asked, as 9p walks to a dentry it holds no fid for.
7
+ //!
8
+ //! What is kept is only the room no one else took: a host out of descriptors
9
+ //! makes every kept directory give way before an open is tried once more, as
10
+ //! Linux's `dcache` shrinks under a full `files_stat`. Each is let go one at
11
+ //! a time and closed past the lock, so no call waits on room and none holds
12
+ //! the lock across the host.
7
13
 
8
14
  use std::num::NonZeroUsize;
9
- use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
15
+ use std::sync::{Arc, Mutex, PoisonError, Weak};
10
16
 
11
17
  use cap_std::fs::Dir;
12
18
  use lru::LruCache;
13
19
 
20
+ use crate::fork::ProcessLocal;
14
21
  use crate::vfs::Dentry;
22
+ use crate::Errno;
15
23
 
16
- /// The most directories a Bind keeps open for walks.
24
+ /// The most directories the process's Binds keep open for walks.
17
25
  const MAX_CACHED_FIDS: NonZeroUsize = NonZeroUsize::new(64).expect("the bound is not zero");
18
26
 
19
- /// A directory, and the dentry it was walked to for.
20
- type CachedFid = (Weak<Dentry>, Arc<Dir>);
27
+ /// A directory, the Bind it was walked to through, and the dentry naming it.
28
+ struct CachedFid {
29
+ owner: usize,
30
+ _dentry: Weak<Dentry>,
31
+ dir: Arc<Dir>,
32
+ }
21
33
 
22
- /// Directories a Bind walked to, by the address of the dentry naming each.
23
- /// Each entry holds that dentry's allocation, so no other can take its address.
24
- pub(super) struct FidCache(Mutex<LruCache<usize, CachedFid>>);
34
+ /// What the process keeps, by the address of the dentry naming each; each
35
+ /// entry holds that dentry's allocation, so no other can take its address.
36
+ /// While a call gives way, nothing more is kept.
37
+ struct Kept {
38
+ fids: LruCache<usize, CachedFid>,
39
+ yielding: usize,
40
+ }
25
41
 
26
- impl Default for FidCache {
42
+ impl Default for Kept {
27
43
  fn default() -> Self {
28
- Self(Mutex::new(LruCache::new(MAX_CACHED_FIDS)))
44
+ Self {
45
+ fids: LruCache::unbounded(),
46
+ yielding: 0,
47
+ }
29
48
  }
30
49
  }
31
50
 
51
+ /// The directories one process keeps for walks. A forked child keeps none of
52
+ /// its parent's: it starts from its own, and never takes the parent's lock.
53
+ pub(super) struct FidCache(ProcessLocal<Kept>);
54
+
55
+ /// The one every Bind keeps its directories in.
56
+ pub(super) static FIDS: FidCache = FidCache::new();
57
+
32
58
  fn key(dentry: &Dentry) -> usize {
33
59
  std::ptr::from_ref(dentry) as usize
34
60
  }
35
61
 
36
62
  impl FidCache {
37
- fn entries(&self) -> MutexGuard<'_, LruCache<usize, CachedFid>> {
38
- self.0.lock().unwrap_or_else(PoisonError::into_inner)
63
+ pub(super) const fn new() -> Self {
64
+ Self(ProcessLocal::new())
65
+ }
66
+
67
+ fn with<R>(&self, f: impl FnOnce(&mut Kept) -> R) -> R {
68
+ self.0
69
+ .with(|kept| f(kept.get_or_insert_with(Kept::default)))
39
70
  }
40
71
 
41
72
  /// The directory kept for `dentry`, now the most recently asked.
42
73
  pub(super) fn get(&self, dentry: &Dentry) -> Option<Arc<Dir>> {
43
- self.entries().get(&key(dentry)).map(|(_, dir)| dir.clone())
74
+ self.with(|kept| kept.fids.get(&key(dentry)).map(|fid| fid.dir.clone()))
44
75
  }
45
76
 
46
- /// Keep `dir` for `dentry`, letting go of the oldest past the bound.
47
- pub(super) fn put(&self, dentry: &Dentry, dir: &Arc<Dir>) {
48
- let entry = (Arc::downgrade(&dentry.get()), dir.clone());
49
- self.entries().put(key(dentry), entry);
77
+ /// Keep `dir` for `dentry`, walked to through `owner`, unless the bound is
78
+ /// reached or a call gives way; what is not kept closes at its last
79
+ /// reference, past the lock.
80
+ pub(super) fn put(&self, owner: &FidOwner, dentry: &Dentry, dir: &Arc<Dir>) {
81
+ let fid = CachedFid {
82
+ owner: owner.id(),
83
+ _dentry: Arc::downgrade(&dentry.get()),
84
+ dir: dir.clone(),
85
+ };
86
+ let replaced =
87
+ self.with(
88
+ |kept| match kept.yielding == 0 && kept.fids.len() < MAX_CACHED_FIDS.get() {
89
+ true => kept.fids.put(key(dentry), fid),
90
+ false => Some(fid),
91
+ },
92
+ );
93
+ drop(replaced);
94
+ }
95
+
96
+ /// Make room for one more, letting the oldest go when the bound is
97
+ /// reached, so a walk's own keep never closes another's.
98
+ pub(super) fn make_room(&self) {
99
+ let oldest = self.with(|kept| match kept.fids.len() < MAX_CACHED_FIDS.get() {
100
+ true => None,
101
+ false => kept.fids.pop_lru(),
102
+ });
103
+ drop(oldest);
104
+ }
105
+
106
+ /// Open through `open`, and when the host is out of descriptors, let
107
+ /// every kept directory go and try once more. One still in use stays open
108
+ /// with whoever holds it, so only the room no one uses is given back.
109
+ pub(super) fn open<T>(&self, open: impl FnMut() -> Result<T, Errno>) -> Result<T, Errno> {
110
+ self.open_or_give_way(open, |err| {
111
+ matches!(
112
+ err,
113
+ Errno::TooManyOpenFiles | Errno::TooManyOpenFilesInSystem
114
+ )
115
+ })
116
+ }
117
+
118
+ /// As `open` does, for an open answering an error of its own that `full`
119
+ /// tells to be the host out of descriptors.
120
+ pub(super) fn open_or_give_way<T, E>(
121
+ &self,
122
+ mut open: impl FnMut() -> Result<T, E>,
123
+ full: impl Fn(&E) -> bool,
124
+ ) -> Result<T, E> {
125
+ match open() {
126
+ Err(err) if full(&err) => {
127
+ let _yielding = Yielding::start(self);
128
+ self.drop_all();
129
+ open()
130
+ }
131
+ answer => answer,
132
+ }
133
+ }
134
+
135
+ /// Let every kept directory go, one at a time and each closed past the
136
+ /// lock, so a fork about to happen hands the child none of them.
137
+ pub(super) fn drop_all(&self) {
138
+ while let Some(fid) = self.with(|kept| kept.fids.pop_lru()) {
139
+ drop(fid);
140
+ }
141
+ }
142
+
143
+ /// Let every directory kept through `owner` go, one at a time.
144
+ fn release(&self, owner: usize) {
145
+ let next = || {
146
+ self.with(|kept| {
147
+ let found = kept.fids.iter().find(|(_, fid)| fid.owner == owner);
148
+ let key = found.map(|(key, _)| *key)?;
149
+ kept.fids.pop(&key)
150
+ })
151
+ };
152
+ while let Some(fid) = next() {
153
+ drop(fid);
154
+ }
50
155
  }
51
156
 
52
157
  /// How many directories are kept.
53
- #[cfg(all(test, unix))]
158
+ #[cfg(test)]
54
159
  pub(super) fn len(&self) -> usize {
55
- self.entries().len()
160
+ self.with(|kept| kept.fids.len())
161
+ }
162
+
163
+ /// How many directories are kept through the owner `id` names, which
164
+ /// may since have been let go.
165
+ #[cfg(test)]
166
+ pub(super) fn kept_by(&self, id: usize) -> usize {
167
+ self.with(|kept| kept.fids.iter().filter(|(_, fid)| fid.owner == id).count())
168
+ }
169
+
170
+ /// Stand in for a fork: what is kept now was kept by another process.
171
+ #[cfg(test)]
172
+ pub(super) fn inherit(&self) {
173
+ self.0.inherit();
174
+ }
175
+ }
176
+
177
+ /// A call giving way, from its first letting go until its open was tried once
178
+ /// more, however that try ends.
179
+ struct Yielding<'a>(&'a FidCache);
180
+
181
+ impl<'a> Yielding<'a> {
182
+ fn start(cache: &'a FidCache) -> Self {
183
+ cache.with(|kept| kept.yielding += 1);
184
+ Self(cache)
185
+ }
186
+ }
187
+
188
+ impl Drop for Yielding<'_> {
189
+ fn drop(&mut self) {
190
+ self.0.with(|kept| kept.yielding -= 1);
191
+ }
192
+ }
193
+
194
+ /// What one Bind's walks keep, let go with the last of its clones, named by
195
+ /// the address of the allocation the Bind shares it through. The Bind drops
196
+ /// its root before this, as the root is its maker's, not the cache's.
197
+ #[derive(Default)]
198
+ pub(super) struct FidOwner;
199
+
200
+ impl FidOwner {
201
+ pub(super) fn id(&self) -> usize {
202
+ std::ptr::from_ref(self) as usize
203
+ }
204
+ }
205
+
206
+ impl Drop for FidOwner {
207
+ fn drop(&mut self) {
208
+ FIDS.release(self.id());
56
209
  }
57
210
  }
58
211
 
@@ -80,3 +233,128 @@ impl OpenDirFid {
80
233
  }
81
234
  }
82
235
  }
236
+
237
+ #[cfg(test)]
238
+ mod tests {
239
+ use std::cell::Cell;
240
+
241
+ use cap_std::ambient_authority;
242
+
243
+ use super::*;
244
+ use crate::filesystem::Tmpfs;
245
+ use crate::vfs::SuperBlock;
246
+
247
+ /// A host directory, open as each kept one is.
248
+ fn host_dir() -> Arc<Dir> {
249
+ Arc::new(
250
+ Dir::open_ambient_dir(std::env::temp_dir(), ambient_authority())
251
+ .expect("the temporary directory must open"),
252
+ )
253
+ }
254
+
255
+ /// A cache of its own holding one directory, so no other test's walks
256
+ /// reach what this one counts.
257
+ fn keep_one_directory(owner: &FidOwner, sb: &SuperBlock) -> (FidCache, Arc<Dentry>) {
258
+ let cache = FidCache::new();
259
+ let dentry = sb.dentries().alloc_pseudo();
260
+ cache.put(owner, &dentry, &host_dir());
261
+ (cache, dentry)
262
+ }
263
+
264
+ // @behavior FS-217
265
+ #[test]
266
+ fn a_host_out_of_descriptors_makes_the_kept_directories_give_way() {
267
+ let sb = SuperBlock::new(Tmpfs::new()).expect("the instance must stand");
268
+ let owner = FidOwner;
269
+ let (cache, _dentry) = keep_one_directory(&owner, &sb);
270
+ let tries = Cell::new(0);
271
+ let answer = cache.open(|| {
272
+ tries.set(tries.get() + 1);
273
+ match tries.get() {
274
+ 1 => Err(Errno::TooManyOpenFiles),
275
+ _ => Ok(cache.len()),
276
+ }
277
+ });
278
+ assert_eq!(
279
+ (answer, tries.get()),
280
+ (Ok(0), 2),
281
+ "an open refused as EMFILE must let every kept directory go and try once more"
282
+ );
283
+ }
284
+
285
+ // The guest's open directory holds its own host directory, as a `Bind`'s
286
+ // open of one does, so giving way lets go of the cache's alone.
287
+ // @behavior FS-220
288
+ #[test]
289
+ fn a_directory_held_open_answers_after_the_kept_ones_give_way() {
290
+ let sb = SuperBlock::new(Tmpfs::new()).expect("the instance must stand");
291
+ let owner = FidOwner;
292
+ let (cache, _kept) = keep_one_directory(&owner, &sb);
293
+ let held_dentry = sb.dentries().alloc_pseudo();
294
+ let held = host_dir();
295
+ cache.put(&owner, &held_dentry, &held);
296
+ OpenDirFid::set(&held_dentry, &held);
297
+ let mut refused = true;
298
+ let answer = cache.open(|| match std::mem::take(&mut refused) {
299
+ true => Err(Errno::TooManyOpenFiles),
300
+ false => Ok(()),
301
+ });
302
+ let listed = OpenDirFid::get(&held_dentry).map(|dir| dir.entries().is_ok());
303
+ assert_eq!(
304
+ (answer, cache.len(), listed),
305
+ (Ok(()), 0, Some(true)),
306
+ "a directory a guest holds open must still list once an open refused as EMFILE \
307
+ made every kept directory give way"
308
+ );
309
+ }
310
+
311
+ // @behavior FS-218
312
+ #[test]
313
+ fn an_open_refused_again_after_giving_way_answers_the_refusal() {
314
+ let tries = Cell::new(0);
315
+ let answer = FidCache::new().open(|| {
316
+ tries.set(tries.get() + 1);
317
+ Err::<(), _>(Errno::TooManyOpenFilesInSystem)
318
+ });
319
+ assert_eq!(
320
+ (answer, tries.get()),
321
+ (Err(Errno::TooManyOpenFilesInSystem), 2),
322
+ "an open refused as ENFILE twice must answer ENFILE after its one more try"
323
+ );
324
+ }
325
+
326
+ // @behavior FS-219
327
+ #[test]
328
+ fn nothing_is_kept_while_a_call_gives_way() {
329
+ let sb = SuperBlock::new(Tmpfs::new()).expect("the instance must stand");
330
+ let owner = FidOwner;
331
+ let (cache, dentry) = keep_one_directory(&owner, &sb);
332
+ let mut first = true;
333
+ let answer = cache.open(|| match std::mem::take(&mut first) {
334
+ true => Err(Errno::TooManyOpenFiles),
335
+ false => {
336
+ cache.put(&owner, &dentry, &host_dir());
337
+ Ok(())
338
+ }
339
+ });
340
+ assert_eq!(
341
+ (answer, cache.len()),
342
+ (Ok(()), 0),
343
+ "a directory kept while an open refused as EMFILE gives way must not stay kept"
344
+ );
345
+ }
346
+
347
+ // @behavior FS-222
348
+ #[test]
349
+ fn a_forked_child_keeps_none_of_its_parents_directories() {
350
+ let sb = SuperBlock::new(Tmpfs::new()).expect("the instance must stand");
351
+ let owner = FidOwner;
352
+ let (cache, dentry) = keep_one_directory(&owner, &sb);
353
+ cache.inherit();
354
+ assert_eq!(
355
+ (cache.len(), cache.get(&dentry).is_none()),
356
+ (0, true),
357
+ "a forked child must keep none of the directories its parent kept"
358
+ );
359
+ }
360
+ }
@@ -3,15 +3,15 @@
3
3
  //! dentry per name as asked would hold one entry under several.
4
4
  //!
5
5
  //! macOS answers the stored name for any spelling. Elsewhere a listing
6
- //! finds the entry by its inode, skipped on a Linux filesystem known to
7
- //! match names exactly; without an inode, a spelling the listing lacks is
8
- //! refused.
6
+ //! finds the entry by its inode, Windows' file index, skipped on a Linux
7
+ //! filesystem known to match names exactly.
9
8
 
10
9
  #[cfg(not(target_os = "macos"))]
11
10
  use std::io;
12
11
 
13
12
  use cap_std::fs::Dir;
14
13
 
14
+ use super::unicode::to_guest_name;
15
15
  use super::{to_error, Errno};
16
16
 
17
17
  /// The name `parent` stores for the entry `name` reaches, a link reached
@@ -19,10 +19,7 @@ use super::{to_error, Errno};
19
19
  pub(super) fn lookup(parent: &Dir, name: &str) -> Result<String, Errno> {
20
20
  #[cfg(target_os = "macos")]
21
21
  {
22
- macos::lookup(parent, name)
23
- .map_err(to_error)?
24
- .into_string()
25
- .map_err(|_| Errno::IllegalSequence)
22
+ to_guest_name(macos::lookup(parent, name).map_err(to_error)?)
26
23
  }
27
24
  #[cfg(not(target_os = "macos"))]
28
25
  {
@@ -30,13 +27,14 @@ pub(super) fn lookup(parent: &Dir, name: &str) -> Result<String, Errno> {
30
27
  if linux::matches_exactly(parent) {
31
28
  return Ok(name.to_string());
32
29
  }
33
- lookup_by_listing(parent, name)
30
+ super::fid::FIDS.open(|| lookup_by_listing(parent, name))
34
31
  }
35
32
  }
36
33
 
37
34
  /// The name a listing of `parent` holds for `name`: itself when listed,
38
35
  /// else the entry sharing its inode. A spelling the listing lacks and no
39
- /// inode ties to a listed name is refused as `EACCES`.
36
+ /// inode ties to a listed name, as a filesystem naming no inodes leaves it,
37
+ /// is refused as `EACCES`.
40
38
  #[cfg(not(target_os = "macos"))]
41
39
  fn lookup_by_listing(parent: &Dir, name: &str) -> Result<String, Errno> {
42
40
  let found = match parent.symlink_metadata(name) {
@@ -46,38 +44,53 @@ fn lookup_by_listing(parent: &Dir, name: &str) -> Result<String, Errno> {
46
44
  };
47
45
  let mut names = Vec::new();
48
46
  for entry in parent.entries().map_err(to_error)? {
47
+ crate::sched::stop_if_fatal()?;
49
48
  let entry = entry.map_err(to_error)?;
50
49
  if entry.file_name() == name {
51
50
  return Ok(name.to_string());
52
51
  }
53
52
  names.push(entry);
54
53
  }
55
- stored_by_inode(names, &found)
54
+ stored_by_inode(parent, names, &found)
56
55
  }
57
56
 
58
- /// The name among `names` sharing the inode of `found`.
57
+ /// The name among `names` sharing the inode of `found`, which each listed
58
+ /// entry carries.
59
59
  #[cfg(all(unix, not(target_os = "macos")))]
60
60
  fn stored_by_inode(
61
+ _parent: &Dir,
61
62
  names: Vec<cap_std::fs::DirEntry>,
62
63
  found: &cap_std::fs::Metadata,
63
64
  ) -> Result<String, Errno> {
64
65
  use cap_std::fs::MetadataExt;
65
66
  use std::os::unix::fs::DirEntryExt;
66
- names
67
- .into_iter()
68
- .find(|entry| entry.ino() == found.ino())
69
- .ok_or(Errno::PermissionDenied)?
70
- .file_name()
71
- .into_string()
72
- .map_err(|_| Errno::IllegalSequence)
67
+ to_guest_name(
68
+ names
69
+ .into_iter()
70
+ .find(|entry| entry.ino() == found.ino())
71
+ .ok_or(Errno::PermissionDenied)?
72
+ .file_name(),
73
+ )
73
74
  }
74
75
 
75
- /// Without an inode nothing ties a spelling to a listed name.
76
+ /// The name among `names` sharing the file index of `found`. A listed entry
77
+ /// carries no file index, so each name is stated as `found` was, from a
78
+ /// handle the stat opens.
76
79
  #[cfg(not(unix))]
77
80
  fn stored_by_inode(
78
- _names: Vec<cap_std::fs::DirEntry>,
79
- _found: &cap_std::fs::Metadata,
81
+ parent: &Dir,
82
+ names: Vec<cap_std::fs::DirEntry>,
83
+ found: &cap_std::fs::Metadata,
80
84
  ) -> Result<String, Errno> {
85
+ use cap_fs_ext::MetadataExt;
86
+ for entry in names {
87
+ crate::sched::stop_if_fatal()?;
88
+ let name = entry.file_name();
89
+ let listed = parent.symlink_metadata(&name);
90
+ if listed.is_ok_and(|listed| listed.ino() == found.ino()) {
91
+ return to_guest_name(name);
92
+ }
93
+ }
81
94
  Err(Errno::PermissionDenied)
82
95
  }
83
96
 
@@ -212,7 +225,7 @@ mod linux {
212
225
  .expect("the host directory must list")
213
226
  .collect::<Result<Vec<_>, _>>()
214
227
  .expect("each listed name must be read");
215
- let answered = stored_by_inode(names, &found);
228
+ let answered = stored_by_inode(&dir, names, &found);
216
229
  let _ = std::fs::remove_dir_all(&path);
217
230
  assert_eq!(
218
231
  answered,
@@ -222,6 +235,27 @@ mod linux {
222
235
  );
223
236
  }
224
237
 
238
+ // @behavior FS-237
239
+ #[test]
240
+ fn a_search_for_a_spelling_past_its_runs_deadline_answers_eintr() {
241
+ let path = std::env::temp_dir().join(format!("kobako-spell-{}", std::process::id()));
242
+ let _ = std::fs::remove_dir_all(&path);
243
+ std::fs::create_dir_all(&path).expect("the host directory must be created");
244
+ std::fs::write(path.join("a"), "x").expect("the host file must be written");
245
+ let dir = Dir::open_ambient_dir(&path, ambient_authority())
246
+ .expect("the host directory must open");
247
+ let found = crate::sched::run_task(Some(std::time::Instant::now()), || {
248
+ lookup_by_listing(&dir, "a")
249
+ });
250
+ let _ = std::fs::remove_dir_all(&path);
251
+ assert_eq!(
252
+ found,
253
+ Err(Errno::Interrupted),
254
+ "a Bind listing a host directory for how it spells a in a run past its deadline \
255
+ must answer EINTR before its next entry"
256
+ );
257
+ }
258
+
225
259
  // A Directory opens its directories as cap-std does, for a path
226
260
  // alone, and a filesystem known to match exactly still spells
227
261
  // without listing. A host on another filesystem has nothing here
@@ -0,0 +1,109 @@
1
+ //! How a guest's names and a host's spell each other, as Linux's CIFS client
2
+ //! converts in `cifs_unicode.c`. A guest name reaches the host only through
3
+ //! `to_host_name`, and a host name or link target reaches the guest only
4
+ //! through `to_guest_name` or `to_guest_target`, so a spelling a host reads
5
+ //! apart from Linux is judged here alone.
6
+ //!
7
+ //! | What the host spells apart | Toward | Answer |
8
+ //! |---|---|---|
9
+ //! | `\`, `:`, a wildcard, a control character, a device's name, or a trailing `.` or space in a name, on Windows | host | refused as invalid input |
10
+ //! | a name no UTF-8 spells | guest | refused as an illegal byte sequence |
11
+ //! | `\` between a link target's names, and its drive or share, on Windows | guest | `/`, and the path rooted at `/` |
12
+ //!
13
+ //! A spelling the host folds to a stored name is the lookup's to answer.
14
+
15
+ use std::ffi::OsString;
16
+
17
+ use super::Errno;
18
+
19
+ /// `name` as `cap_std` takes it. Windows reads some names as other names or
20
+ /// as devices, so there one is refused rather than reached as an entry a
21
+ /// Mount's Policy never saw.
22
+ pub(super) fn to_host_name(name: &str) -> Result<&str, Errno> {
23
+ if cfg!(windows) && is_windows_alias(name) {
24
+ return Err(Errno::InvalidInput);
25
+ }
26
+ Ok(name)
27
+ }
28
+
29
+ /// A name the host holds, as a guest name spells it.
30
+ pub(super) fn to_guest_name(name: OsString) -> Result<String, Errno> {
31
+ name.into_string().map_err(|_| Errno::IllegalSequence)
32
+ }
33
+
34
+ /// A link's `target` as a guest path spells it. Windows separates names
35
+ /// with `\` and roots an absolute path at a drive or a share, so there each
36
+ /// `\` reads as `/` and the drive or share drops, leaving a path rooted at
37
+ /// `/` as on unix.
38
+ pub(super) fn to_guest_target(target: OsString) -> Result<String, Errno> {
39
+ let target = to_guest_name(target)?;
40
+ #[cfg(windows)]
41
+ {
42
+ use std::path::{Component, Path};
43
+ let prefix = match Path::new(&target).components().next() {
44
+ Some(Component::Prefix(prefix)) => prefix.as_os_str().len(),
45
+ _ => 0,
46
+ };
47
+ Ok(target[prefix..].replace('\\', "/"))
48
+ }
49
+ #[cfg(not(windows))]
50
+ Ok(target)
51
+ }
52
+
53
+ /// Whether Windows reads `name` as something else: a `\` as a separator, a `:`
54
+ /// as a stream of a file, a trailing `.` or space as nothing, a wildcard as a
55
+ /// pattern, or a device's name, whatever extension follows, as the device.
56
+ fn is_windows_alias(name: &str) -> bool {
57
+ const DEVICES: [&str; 33] = [
58
+ "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", "CLOCK$", "COM0", "COM1", "COM2", "COM3",
59
+ "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM¹", "COM²", "COM³", "LPT0", "LPT1",
60
+ "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "LPT¹", "LPT²", "LPT³",
61
+ ];
62
+ let reserved = |c: char| c.is_ascii_control() || "\\:*?\"<>|".contains(c);
63
+ let stem = name.split('.').next().unwrap_or(name).trim_end();
64
+ name.contains(reserved)
65
+ || name.ends_with(['.', ' '])
66
+ || DEVICES.contains(&stem.to_uppercase().as_str())
67
+ }
68
+
69
+ #[cfg(test)]
70
+ mod tests {
71
+ use super::*;
72
+
73
+ // Judged on every host, as only Windows's own CI reaches the refusal, and
74
+ // what the host would do with each name is what no other host can show.
75
+ // @behavior FS-153
76
+ #[test]
77
+ fn a_name_windows_reads_as_another_is_told_apart() {
78
+ let aliases = [
79
+ "secret.",
80
+ "secret ",
81
+ "file:stream",
82
+ r"d\f",
83
+ "con",
84
+ "NUL.txt",
85
+ "conin$",
86
+ "com1 .log",
87
+ "a?",
88
+ "a*",
89
+ "a<",
90
+ "a|",
91
+ "a\"",
92
+ "a\u{1}",
93
+ ];
94
+ let plain = ["secret", "file.txt", "console", "com10", ".hidden", "a.b.c"];
95
+ assert_eq!(
96
+ (
97
+ aliases
98
+ .iter()
99
+ .filter(|name| !is_windows_alias(name))
100
+ .count(),
101
+ plain.iter().filter(|name| is_windows_alias(name)).count(),
102
+ ),
103
+ (0, 0),
104
+ "a name a Windows host reads as another name or as a device must be told apart \
105
+ from a plain name, so a Bind there refuses it, and no plain name may be taken \
106
+ for one"
107
+ );
108
+ }
109
+ }