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,5 +1,5 @@
1
1
  //! A name lookup the guest asked for, judged as a DNS proxy judges a query,
2
- //! then resolved as a task on the reactor, its waiter woken through the
2
+ //! then resolved on the thread that waits for it, woken through the
3
3
  //! lookup's wait queue so the deadline ends the wait. Linux leaves resolution
4
4
  //! to userspace, where a process's own query ends with it, so the Resolver is
5
5
  //! a backend beside the Protocol Family, and dropping a lookup cancels its
@@ -12,8 +12,8 @@ use std::pin::Pin;
12
12
  use std::sync::{Arc, Mutex, PoisonError};
13
13
  use std::task::{Context, Poll};
14
14
 
15
- use super::connections::{open, OpenConnections, Place};
16
- use super::reactor::{Reactor, Task};
15
+ use super::connections::{open, ConnectionBudget, OpenConnections, Place};
16
+ use super::task::Task;
17
17
  use super::Namespace;
18
18
  use crate::cred::Cred;
19
19
  use crate::filesystem::anon_inode_getfile;
@@ -21,8 +21,12 @@ use crate::network::{Host, Name};
21
21
  use crate::vfs::{FMode, File, FileOperations, OpenHow, PollMask};
22
22
  use crate::wait::{poll_wait, PollTable, WaitQueueHead};
23
23
 
24
- /// A name's addresses still coming, which the reactor polls, as reqwest's
25
- /// `Resolving` is.
24
+ /// glibc's `NS_MAXCDNAME`: the most bytes a name takes on the wire, its
25
+ /// length bytes and root label counted.
26
+ pub(crate) const NS_MAXCDNAME: usize = 255;
27
+
28
+ /// A name's addresses still coming, which the asking thread polls as it
29
+ /// waits, as reqwest's `Resolving` is.
26
30
  pub type Resolving = Pin<Box<dyn Future<Output = Result<Vec<IpAddr>, LookupError>> + Send>>;
27
31
 
28
32
  /// What answers a name, as userspace's `getaddrinfo` does in Linux, apart
@@ -68,60 +72,66 @@ pub struct NameLookup {
68
72
  of_address: bool,
69
73
  answer: Answer,
70
74
  wait: Arc<WaitQueueHead>,
71
- /// The query under way on the reactor, cancelled as the lookup drops.
72
- query: Option<Arc<Task>>,
75
+ /// The query under way, moved by whoever asks for the answer and
76
+ /// cancelled as the lookup drops.
77
+ query: Option<Task>,
73
78
  }
74
79
 
75
80
  impl NameLookup {
76
81
  /// A lookup of `name` through `resolver` holding one of
77
- /// `open_connections`' places; a full count answers at once as a temporary
78
- /// failure.
82
+ /// `open_connections`' places and spending one of `budget` before the
83
+ /// query leaves; a full count or a spent budget answers at once as a
84
+ /// temporary failure, asking no resolver.
79
85
  pub(crate) fn start(
80
86
  resolver: Arc<dyn Resolver>,
81
87
  name: String,
82
88
  open_connections: &Arc<OpenConnections>,
89
+ budget: &ConnectionBudget,
83
90
  ) -> Result<Arc<Self>, LookupError> {
84
91
  let place = open(open_connections).ok_or(LookupError::Again)?;
85
- Self::start_holding(resolver, name, Arc::new(place))
92
+ budget.spend().map_err(|_| LookupError::Again)?;
93
+ Ok(Self::start_holding(resolver, name, Arc::new(place)))
86
94
  }
87
95
 
88
96
  /// A lookup of `name` through `resolver` holding `place`, which its
89
- /// caller already counts. The query holds the place until it answers or
90
- /// the lookup drops and cancels it, so a lookup nobody waits for gives its
91
- /// place back at once. A reactor the process cannot start answers as a
92
- /// resolver out of resources does.
97
+ /// caller already counts, its query sent on the asking thread. The query
98
+ /// holds the place until it answers or the lookup drops and cancels it,
99
+ /// so a lookup nobody waits for gives its place back at once.
93
100
  pub(crate) fn start_holding(
94
101
  resolver: Arc<dyn Resolver>,
95
102
  name: String,
96
103
  place: Arc<Place>,
97
- ) -> Result<Arc<Self>, LookupError> {
98
- let reactor = Reactor::current().map_err(|_| LookupError::Again)?;
104
+ ) -> Arc<Self> {
99
105
  let answer = Answer::default();
100
106
  let wait = Arc::<WaitQueueHead>::default();
101
107
  let resolving = resolver.resolve(&name);
102
108
  let (answering, waking) = (answer.clone(), wait.clone());
103
- let query = reactor.spawn(async move {
104
- let _place = place;
105
- let found = match resolving.await {
106
- Ok(addresses) if addresses.is_empty() => Err(LookupError::NoName),
107
- Ok(mut addresses) => {
108
- // Each real address once, so each takes one virtual one.
109
- let mut seen = HashSet::new();
110
- addresses.retain(|ip| seen.insert(*ip));
111
- Ok(addresses)
112
- }
113
- failed => failed,
114
- };
115
- *answering.lock().unwrap_or_else(PoisonError::into_inner) = Some(found);
116
- waking.wake_up();
117
- });
118
- Ok(Arc::new(Self {
109
+ let query = Task::new(
110
+ async move {
111
+ let _place = place;
112
+ let found = match resolving.await {
113
+ Ok(addresses) if addresses.is_empty() => Err(LookupError::NoName),
114
+ Ok(mut addresses) => {
115
+ // Each real address once, so each takes one virtual one.
116
+ let mut seen = HashSet::new();
117
+ addresses.retain(|ip| seen.insert(*ip));
118
+ Ok(addresses)
119
+ }
120
+ failed => failed,
121
+ };
122
+ *answering.lock().unwrap_or_else(PoisonError::into_inner) = Some(found);
123
+ waking.wake_up();
124
+ },
125
+ wait.clone(),
126
+ );
127
+ query.poll();
128
+ Arc::new(Self {
119
129
  name,
120
130
  of_address: false,
121
131
  answer,
122
132
  wait,
123
133
  query: Some(query),
124
- }))
134
+ })
125
135
  }
126
136
 
127
137
  /// A lookup answered at once, with no query, as a refused name is.
@@ -152,9 +162,9 @@ impl NameLookup {
152
162
  self.of_address
153
163
  }
154
164
 
155
- /// The answer for a task on the reactor, which the lookup's wait queue
156
- /// wakes once it arrives; the answer is read again once the task is
157
- /// added, so none arrives unseen.
165
+ /// The answer for a request waiting on the lookup, which the lookup's
166
+ /// wait queue wakes once it arrives; the answer is read again once the
167
+ /// request is added, so none arrives unseen.
158
168
  pub(crate) fn poll_answer(
159
169
  &self,
160
170
  cx: &mut Context<'_>,
@@ -163,7 +173,7 @@ impl NameLookup {
163
173
  return Poll::Ready(answer);
164
174
  }
165
175
  self.wait.add(cx.waker());
166
- match self.answer() {
176
+ match self.answered() {
167
177
  Some(answer) => Poll::Ready(answer),
168
178
  None => Poll::Pending,
169
179
  }
@@ -175,8 +185,15 @@ impl NameLookup {
175
185
  }
176
186
 
177
187
  /// The real addresses the name resolved to, or why it has none; `None`
178
- /// while the lookup is under way.
188
+ /// while the lookup is under way. Asking moves the query on.
179
189
  pub fn answer(&self) -> Option<Result<Vec<IpAddr>, LookupError>> {
190
+ if let Some(query) = &self.query {
191
+ query.poll();
192
+ }
193
+ self.answered()
194
+ }
195
+
196
+ fn answered(&self) -> Option<Result<Vec<IpAddr>, LookupError>> {
180
197
  self.answer
181
198
  .lock()
182
199
  .unwrap_or_else(PoisonError::into_inner)
@@ -195,14 +212,6 @@ impl NameLookup {
195
212
  }
196
213
  }
197
214
 
198
- impl Drop for NameLookup {
199
- fn drop(&mut self) {
200
- if let Some(query) = &self.query {
201
- query.cancel();
202
- }
203
- }
204
- }
205
-
206
215
  /// What answers for a lookup's file.
207
216
  struct LookupFile(Arc<NameLookup>);
208
217
 
@@ -226,20 +235,34 @@ impl FileOperations for LookupFile {
226
235
  /// mapped one. Each entry's `resolve` policy and the endpoints judge any
227
236
  /// other, as a DNS proxy judges a query before it forwards one; a refused or
228
237
  /// unmatched name answers as NXDOMAIN before any query, as a real one would.
238
+ /// A name no DNS query can carry answers NXDOMAIN too, the lookup keeping
239
+ /// none of it, as glibc's `res_hnok` refuses it whatever the Resolver.
229
240
  /// A name the Invocation already translated answers its first real addresses
230
- /// again, with no query, so a resolver cannot rebind it.
241
+ /// again, with no query, so a resolver cannot rebind it. Only a query spends
242
+ /// the connection budget.
231
243
  pub fn resolve(net: &Namespace, name: &str) -> Result<Arc<NameLookup>, LookupError> {
232
244
  let name = match Host::parse(name).ok_or(LookupError::InvalidName)? {
233
245
  Host::Address(ip) => return Ok(NameLookup::from_address(ip.to_canonical())),
234
246
  Host::Name(name) => name,
235
247
  };
248
+ if name.len() + 2 > NS_MAXCDNAME {
249
+ return Ok(NameLookup::with_answer(
250
+ String::new(),
251
+ Err(LookupError::NoName),
252
+ ));
253
+ }
236
254
  if !allows_lookup(net, &name) || !net.ruleset().admits_name(&name) {
237
255
  return Ok(NameLookup::with_answer(name, Err(LookupError::NoName)));
238
256
  }
239
257
  let translated = net.real_addresses_of(&name);
240
258
  match translated.is_empty() {
241
259
  false => Ok(NameLookup::with_answer(name, Ok(translated))),
242
- true => NameLookup::start(net.resolver().clone(), name, net.open_connections()),
260
+ true => NameLookup::start(
261
+ net.resolver().clone(),
262
+ name,
263
+ net.open_connections(),
264
+ net.connection_budget(),
265
+ ),
243
266
  }
244
267
  }
245
268
 
@@ -255,9 +278,11 @@ pub(crate) fn allows_lookup(net: &Namespace, name: &str) -> bool {
255
278
  #[cfg(test)]
256
279
  mod tests {
257
280
  use std::sync::mpsc;
281
+ use std::time::Duration;
258
282
 
259
283
  use super::super::connections::open_within;
260
284
  use super::super::family::testing::StallsLookups;
285
+ use super::super::reactor::{Reactor, Ready};
261
286
  use super::*;
262
287
 
263
288
  // @behavior NW-085
@@ -269,8 +294,7 @@ mod tests {
269
294
  let process = OpenConnections::new(Some(1));
270
295
  let place = open_within(&invocation, &process).expect("both counts have room");
271
296
  let lookup =
272
- NameLookup::start_holding(resolver.clone(), "slow.test".into(), Arc::new(place))
273
- .expect("the lookup starts");
297
+ NameLookup::start_holding(resolver.clone(), "slow.test".into(), Arc::new(place));
274
298
  drop(lookup);
275
299
  assert_eq!(
276
300
  (
@@ -282,4 +306,80 @@ mod tests {
282
306
  query and give its place back to the invocation's count and the process's at once"
283
307
  );
284
308
  }
309
+
310
+ /// A resolver whose query holds each poll until the test lets it go, as a
311
+ /// slow certificate check holds the thread polling it, telling as it
312
+ /// starts.
313
+ struct TakesLong {
314
+ polling: Mutex<mpsc::Sender<()>>,
315
+ release: Arc<Mutex<mpsc::Receiver<()>>>,
316
+ }
317
+
318
+ impl Resolver for TakesLong {
319
+ fn resolve(&self, _name: &str) -> Resolving {
320
+ let polling = self.polling.lock().unwrap().clone();
321
+ let release = self.release.clone();
322
+ Box::pin(std::future::poll_fn(move |_| {
323
+ let _ = polling.send(());
324
+ // The test lets go once it heard the other socket, or drops
325
+ // its end as it fails.
326
+ let _ = release.lock().unwrap().recv();
327
+ Poll::Ready(Ok(Vec::new()))
328
+ }))
329
+ }
330
+ }
331
+
332
+ /// A socket that tells of each change.
333
+ struct TellsEvents(Mutex<mpsc::Sender<()>>);
334
+
335
+ impl Ready for TellsEvents {
336
+ fn on_event(&self, _events: PollMask) {
337
+ let _ = self.0.lock().unwrap().send(());
338
+ }
339
+
340
+ fn abort(&self) {}
341
+ }
342
+
343
+ // One sandbox's lookup taking long holds only the thread that waits on
344
+ // it, so another sandbox's socket hears its peer at once.
345
+ // @behavior NW-236
346
+ #[test]
347
+ fn a_slow_lookup_delays_no_other_socket() {
348
+ let (polling, polled) = mpsc::channel();
349
+ let invocation = OpenConnections::new(None);
350
+ let place = open(&invocation).expect("the count has room");
351
+ let (release, released) = mpsc::channel();
352
+ let resolver = Arc::new(TakesLong {
353
+ polling: Mutex::new(polling),
354
+ release: Arc::new(Mutex::new(released)),
355
+ });
356
+ let asking = std::thread::spawn(move || {
357
+ let lookup = NameLookup::start_holding(resolver, "slow.test".into(), Arc::new(place));
358
+ while lookup.answer().is_none() {}
359
+ });
360
+ polled
361
+ .recv_timeout(Duration::from_secs(5))
362
+ .expect("the lookup's query is polled");
363
+ let (tx, rx) = mpsc::channel();
364
+ let ready: Arc<dyn Ready> = Arc::new(TellsEvents(Mutex::new(tx)));
365
+ let addr = "127.0.0.1:0".parse().unwrap();
366
+ let mut socket = mio::net::UdpSocket::bind(addr).expect("a UDP socket binds");
367
+ let _registration = Reactor::current()
368
+ .expect("a reactor starts")
369
+ .register(&mut socket, Arc::downgrade(&ready), false)
370
+ .expect("the socket registers");
371
+ while rx.try_recv().is_ok() {}
372
+ std::net::UdpSocket::bind(addr)
373
+ .expect("a UDP socket binds")
374
+ .send_to(b"x", socket.local_addr().unwrap())
375
+ .expect("the datagram goes");
376
+ let heard = rx.recv_timeout(crate::sched::testing::MAX_WAIT).is_ok();
377
+ drop(release);
378
+ crate::sched::testing::join("the asking thread", asking);
379
+ assert!(
380
+ heard,
381
+ "a socket whose peer sent must be woken while another Sandbox's lookup is held in \
382
+ its resolver, since only the thread waiting on that lookup polls it"
383
+ );
384
+ }
285
385
  }
@@ -8,13 +8,12 @@
8
8
  use std::net::{IpAddr, Ipv4Addr, SocketAddr};
9
9
  use std::sync::{Arc, Mutex, PoisonError, Weak};
10
10
 
11
+ use super::connections::ConnectionBudget;
11
12
  use super::egress::EgressProxy;
12
13
  use super::http::{HyperOutbound, Outbound};
13
14
  use super::lookup::{LookupError, NameLookup, Resolver};
14
15
  use super::socket::{BindHash, LOCAL_ADDRESS, VIRTUAL_BASE, VIRTUAL_SIZE};
15
16
  use super::{Backends, OpenConnections, ProtocolFamily, TcpSock};
16
- use crate::cred::Cred;
17
- use crate::memcg::MemoryCharge;
18
17
  use crate::network::{EntryError, Name, Network, Protocol, Ruleset};
19
18
  use crate::policy::Policy;
20
19
 
@@ -36,8 +35,8 @@ pub struct Namespace {
36
35
  outbound: Arc<dyn Outbound>,
37
36
  open_connections: Arc<OpenConnections>,
38
37
  /// How many more connections this Invocation may make, worked out from
39
- /// its connection limit; `None` makes no count.
40
- connection_budget: Mutex<Option<usize>>,
38
+ /// its connection limit.
39
+ connection_budget: Arc<ConnectionBudget>,
41
40
  translations: Mutex<Translations>,
42
41
  /// The virtual ports TCP sockets hold, and those UDP sockets hold, as
43
42
  /// TCP keeps its `bhash` and UDP its `udp_table`.
@@ -49,12 +48,10 @@ pub struct Namespace {
49
48
  }
50
49
 
51
50
  /// Each real address a name looked up resolved to, with the name, at its
52
- /// virtual address's offset from the bottom of the range, and the memory
53
- /// they hold against the Invocation's, given back as the namespace goes.
51
+ /// virtual address's offset from the bottom of the range.
54
52
  #[derive(Default)]
55
53
  struct Translations {
56
54
  entries: Vec<(String, IpAddr)>,
57
- memory: Option<MemoryCharge>,
58
55
  }
59
56
 
60
57
  impl Translations {
@@ -150,7 +147,7 @@ impl Namespace {
150
147
  resolver: backends.resolver().clone(),
151
148
  outbound: Arc::new(HyperOutbound::new()),
152
149
  open_connections,
153
- connection_budget: Mutex::new(connection_limit),
150
+ connection_budget: ConnectionBudget::new(connection_limit),
154
151
  translations: Mutex::default(),
155
152
  tcp_ports: BindHash::new(),
156
153
  udp_ports: BindHash::new(),
@@ -190,26 +187,10 @@ impl Namespace {
190
187
  .collect()
191
188
  }
192
189
 
193
- /// `connect`, made only while the Invocation has a connection left and
194
- /// counted once it is, as a budget of subrequests is spent;
195
- /// `refused`, dialing nothing, once none is left.
196
- pub(crate) fn within_connection_budget<T, E>(
197
- &self,
198
- refused: E,
199
- connect: impl FnOnce() -> Result<T, E>,
200
- ) -> Result<T, E> {
201
- let mut left = self
202
- .connection_budget
203
- .lock()
204
- .unwrap_or_else(PoisonError::into_inner);
205
- if *left == Some(0) {
206
- return Err(refused);
207
- }
208
- let made = connect()?;
209
- if let Some(n) = left.as_mut() {
210
- *n -= 1;
211
- }
212
- Ok(made)
190
+ /// The connections this Invocation may still make, each spent as a lookup
191
+ /// or a dial is about to leave the host.
192
+ pub(crate) fn connection_budget(&self) -> &Arc<ConnectionBudget> {
193
+ &self.connection_budget
213
194
  }
214
195
 
215
196
  /// The virtual ports `protocol`'s sockets hold here.
@@ -225,12 +206,10 @@ impl Namespace {
225
206
  /// range and never reused; a name already handed them keeps them, as a
226
207
  /// fake-IP pool answers a known host; a lookup of an address keeps it as
227
208
  /// itself. `None` while the lookup is under way, its failure once it
228
- /// failed, and `Again` once the range cannot hold them all or
229
- /// `cred`'s memory cannot hold the entries, which the table keeps until
230
- /// the Invocation ends.
209
+ /// failed, and `Again` once the range cannot hold them all. The table
210
+ /// keeps the entries until the Invocation ends.
231
211
  pub fn alloc_virtual_addresses(
232
212
  &self,
233
- cred: &Arc<Cred>,
234
213
  lookup: &NameLookup,
235
214
  ) -> Option<Result<Vec<IpAddr>, LookupError>> {
236
215
  let real = match lookup.answer()? {
@@ -257,24 +236,9 @@ impl Namespace {
257
236
  else {
258
237
  return Some(Err(LookupError::Again));
259
238
  };
260
- let entries = real
261
- .into_iter()
262
- .map(|ip| (lookup.name().to_string(), ip))
263
- .collect::<Vec<_>>();
264
- let held = entries
265
- .iter()
266
- .map(|entry| std::mem::size_of_val(entry) + entry.0.len())
267
- .sum::<usize>();
268
- let charged = match &mut translations.memory {
269
- Some(memory) => memory.resize(memory.bytes() + held),
270
- None => MemoryCharge::new(cred.memory_budget(), held).map(|memory| {
271
- translations.memory = Some(memory);
272
- }),
273
- };
274
- if charged.is_err() {
275
- return Some(Err(LookupError::Again));
276
- }
277
- translations.entries.extend(entries);
239
+ translations
240
+ .entries
241
+ .extend(real.into_iter().map(|ip| (lookup.name().to_string(), ip)));
278
242
  let first = u32::try_from(first).expect("below the end of the range");
279
243
  Some(Ok((first..end).map(to_virtual).collect()))
280
244
  }
@@ -364,6 +328,7 @@ mod tests {
364
328
  use super::super::socket::{sys_bind, sys_connect, AddressFamily};
365
329
  use super::super::UdpSock;
366
330
  use super::*;
331
+ use crate::cred::Cred;
367
332
  use crate::grant::Grant;
368
333
  use crate::network::Connection;
369
334
  use crate::network::{Addresses, Endpoint, Entry, Policies};
@@ -594,9 +559,10 @@ mod tests {
594
559
  request.path_with_query = "/".to_string();
595
560
  let exchange =
596
561
  crate::net::send(&namespace, &cred, request).expect("the endpoint admits it");
597
- while exchange.response().is_none() {
598
- std::thread::sleep(Duration::from_millis(1));
599
- }
562
+ crate::sched::testing::wait_until(
563
+ "the request answering, so its dial never settled",
564
+ || exchange.response().is_some(),
565
+ );
600
566
  let dialed = family.dials();
601
567
  let socket = dial(&namespace, &cred, "127.0.0.1:4568".parse().unwrap());
602
568
  assert_eq!(
@@ -722,13 +688,10 @@ mod tests {
722
688
  let held = held.unwrap_or_default();
723
689
  // The reactor may hold the socket a moment longer for an event
724
690
  // already under way.
725
- let deadline = std::time::Instant::now() + Duration::from_secs(2);
726
- while held.strong_count() > 0 && std::time::Instant::now() < deadline {
727
- std::thread::sleep(Duration::from_millis(1));
728
- }
691
+ let let_go = crate::sched::testing::holds_within_max_wait(|| held.strong_count() == 0);
729
692
  assert_eq!(
730
- (orphaned, held.strong_count() > 0),
731
- (true, false),
693
+ (orphaned, let_go),
694
+ (true, true),
732
695
  "a socket released with bytes still queued to send must hold itself while it sends, \
733
696
  and the Invocation's namespace dropping must let it go"
734
697
  );
@@ -740,7 +703,7 @@ mod tests {
740
703
  cred: &Arc<Cred>,
741
704
  addr: SocketAddr,
742
705
  ) -> Result<Arc<TcpSock>, Errno> {
743
- let sock = TcpSock::create(namespace, cred, AddressFamily::Inet)?;
706
+ let sock = TcpSock::create(namespace, AddressFamily::Inet)?;
744
707
  sys_connect(namespace, cred, sock.as_ref(), Some(addr)).map(|()| sock)
745
708
  }
746
709
 
@@ -750,14 +713,15 @@ mod tests {
750
713
  cred: &Arc<Cred>,
751
714
  addr: Option<SocketAddr>,
752
715
  ) -> Result<Arc<UdpSock>, Errno> {
753
- let sock = UdpSock::create(namespace, cred, AddressFamily::Inet)?;
716
+ let sock = UdpSock::create(namespace, AddressFamily::Inet)?;
754
717
  sys_connect(namespace, cred, sock.as_ref(), addr).map(|()| sock)
755
718
  }
756
719
 
757
720
  fn settle(sock: &TcpSock) {
758
- while matches!(sock.take_connect_outcome(), Err(Errno::WouldBlock)) {
759
- std::thread::sleep(Duration::from_millis(1));
760
- }
721
+ crate::sched::testing::wait_until(
722
+ "a connect settling, so the reactor never woke its socket",
723
+ || !matches!(sock.take_connect_outcome(), Err(Errno::WouldBlock)),
724
+ );
761
725
  }
762
726
 
763
727
  // @behavior NW-018
@@ -805,7 +769,7 @@ mod tests {
805
769
  let (namespace, cred, family, seen) = namespace(&[true]);
806
770
  let ipv6 = dial(&namespace, &cred, "[::1]:4567".parse().unwrap()).err();
807
771
  let unmapped = dial(&namespace, &cred, "198.18.5.5:4567".parse().unwrap()).err();
808
- let sock = UdpSock::new(&cred).expect("an unbounded socket is made");
772
+ let sock = UdpSock::new();
809
773
  let bound = sys_bind(&namespace, &cred, sock.as_ref(), "[::]:0".parse().unwrap()).err();
810
774
  let judged = seen
811
775
  .lock()
@@ -910,12 +874,15 @@ mod tests {
910
874
 
911
875
  /// The answer `lookup` settles on.
912
876
  fn wait_for_answer(lookup: &NameLookup) -> Result<Vec<IpAddr>, LookupError> {
913
- loop {
914
- if let Some(answer) = lookup.answer() {
915
- return answer;
916
- }
917
- std::thread::sleep(Duration::from_millis(1));
918
- }
877
+ let mut answer = None;
878
+ crate::sched::testing::wait_until(
879
+ "a lookup answering, so its resolver never answered or never woke it",
880
+ || {
881
+ answer = lookup.answer();
882
+ answer.is_some()
883
+ },
884
+ );
885
+ answer.expect("the lookup answered")
919
886
  }
920
887
 
921
888
  #[test]
@@ -948,7 +915,7 @@ mod tests {
948
915
  let lookup = resolve(namespace, name).expect("the lookup starts");
949
916
  wait_for_answer(&lookup).expect("the name resolves");
950
917
  namespace
951
- .alloc_virtual_addresses(&prepare_creds(&[], None), &lookup)
918
+ .alloc_virtual_addresses(&lookup)
952
919
  .expect("the lookup settled")
953
920
  .expect("the range has room")
954
921
  .into_iter()
@@ -987,6 +954,34 @@ mod tests {
987
954
  );
988
955
  }
989
956
 
957
+ // @behavior NW-250
958
+ #[test]
959
+ fn a_name_no_dns_query_carries_answers_nxdomain_unasked() {
960
+ let family = Arc::new(ResolvesNames {
961
+ answers: Mutex::new(vec!["127.0.0.1".parse().unwrap()]),
962
+ ..ResolvesNames::default()
963
+ });
964
+ let namespace = resolving_namespace(vec![tcp("*.example.com", 443)], "", family.clone());
965
+ let name_of = |len: usize| {
966
+ let prefix = vec!["a".repeat(60); 5].join(".");
967
+ format!("{}.example.com", &prefix[..len - ".example.com".len()])
968
+ };
969
+ let answers =
970
+ [254, 253].map(|len| wait_for_answer(&resolve(&namespace, &name_of(len)).unwrap()));
971
+ assert_eq!(
972
+ (answers, family.lookups.load(Ordering::SeqCst)),
973
+ (
974
+ [
975
+ Err(LookupError::NoName),
976
+ Ok(vec!["127.0.0.1".parse().unwrap()])
977
+ ],
978
+ 1
979
+ ),
980
+ "a lookup of a 254-byte name, past the 255 bytes a DNS query carries, must answer \
981
+ name-unresolvable without asking the resolver, while a 253-byte one is asked"
982
+ );
983
+ }
984
+
990
985
  /// A resolver failing each name by the kind its first label spells.
991
986
  struct FailsByKind;
992
987
 
@@ -1127,24 +1122,37 @@ mod tests {
1127
1122
 
1128
1123
  // @behavior NW-149
1129
1124
  #[test]
1130
- fn a_virtual_address_is_held_against_the_invocations_memory() {
1125
+ fn a_names_virtual_addresses_run_out_at_the_ranges_end() {
1126
+ let every = (0..MAX_NAMED_ADDRESSES)
1127
+ .map(|offset| IpAddr::V4(Ipv4Addr::from(0x0A00_0000 + offset)))
1128
+ .collect::<Vec<_>>();
1131
1129
  let family = Arc::new(ResolvesNames {
1132
- answers: Mutex::new(vec!["127.0.0.1".parse().unwrap()]),
1130
+ answers: Mutex::new(every),
1133
1131
  ..ResolvesNames::default()
1134
1132
  });
1135
- let namespace = resolving_namespace(vec![tcp("cache.internal", 6379)], "", family);
1136
- let lookup = resolve(&namespace, "cache.internal").expect("the lookup starts");
1137
- wait_for_answer(&lookup).expect("the name resolves");
1138
- let full = namespace.alloc_virtual_addresses(&prepare_creds(&[], Some(0)), &lookup);
1139
- let roomy = namespace.alloc_virtual_addresses(&prepare_creds(&[], None), &lookup);
1133
+ let namespace = resolving_namespace(
1134
+ vec![tcp("cache.internal", 6379), tcp("db.internal", 5432)],
1135
+ "",
1136
+ family.clone(),
1137
+ );
1138
+ let handed = |name: &str| {
1139
+ let lookup = resolve(&namespace, name).expect("the lookup starts");
1140
+ wait_for_answer(&lookup).expect("the name resolves");
1141
+ namespace
1142
+ .alloc_virtual_addresses(&lookup)
1143
+ .expect("the lookup answered")
1144
+ .map(|addresses| addresses.len())
1145
+ };
1146
+ let filled = handed("cache.internal");
1147
+ *family.answers.lock().unwrap() = vec!["127.0.0.1".parse().unwrap()];
1148
+ let past = handed("db.internal");
1149
+ let kept = handed("cache.internal");
1150
+ let every = MAX_NAMED_ADDRESSES as usize;
1140
1151
  assert_eq!(
1141
- (full, roomy),
1142
- (
1143
- Some(Err(LookupError::Again)),
1144
- Some(Ok(vec!["198.18.0.0".parse().unwrap()]))
1145
- ),
1146
- "a lookup must answer temporary-failure when the Invocation's memory cannot hold \
1147
- the name's entry, and hand out the bottom of the range once it can"
1152
+ (filled, past, kept),
1153
+ (Ok(every), Err(LookupError::Again), Ok(every)),
1154
+ "a lookup must answer temporary-failure once the names took every virtual address \
1155
+ below the local one, and a name already handed its addresses must keep them"
1148
1156
  );
1149
1157
  }
1150
1158
 
@@ -1176,9 +1184,7 @@ mod tests {
1176
1184
  let second = resolve_virtual_addresses(&namespace, "cache.internal");
1177
1185
  let cred = prepare_creds(&[], None);
1178
1186
  let sock = dial(&namespace, &cred, second[1]).expect("the endpoint leads there");
1179
- while matches!(sock.take_connect_outcome(), Err(Errno::WouldBlock)) {
1180
- std::thread::sleep(Duration::from_millis(1));
1181
- }
1187
+ settle(&sock);
1182
1188
  refusing.store(true, Ordering::SeqCst);
1183
1189
  let refused = wait_for_answer(&resolve(&namespace, "cache.internal").expect("it answers"));
1184
1190
  assert_eq!(
@@ -1233,9 +1239,7 @@ mod tests {
1233
1239
  let cred = prepare_creds(&[], None);
1234
1240
  let at = resolve_virtual_addresses(&namespace, "Cache.Internal.");
1235
1241
  let sock = dial(&namespace, &cred, at[0]).expect("the endpoint leads there");
1236
- while matches!(sock.take_connect_outcome(), Err(Errno::WouldBlock)) {
1237
- std::thread::sleep(Duration::from_millis(1));
1238
- }
1242
+ settle(&sock);
1239
1243
  let private = dial(&namespace, &cred, at[1]).err();
1240
1244
  let public_only = resolve_virtual_addresses(&namespace, "api.internal");
1241
1245
  let local_refused = dial(&namespace, &cred, public_only[0]).err();
@@ -1290,9 +1294,7 @@ mod tests {
1290
1294
  *family.answers.lock().unwrap() = vec!["127.0.0.1".parse().unwrap()];
1291
1295
  let cred = prepare_creds(&[], None);
1292
1296
  let sock = dial(&namespace, &cred, at).expect("the endpoint leads there");
1293
- while matches!(sock.take_connect_outcome(), Err(Errno::WouldBlock)) {
1294
- std::thread::sleep(Duration::from_millis(1));
1295
- }
1297
+ settle(&sock);
1296
1298
  assert_eq!(
1297
1299
  (
1298
1300
  family.lookups.load(Ordering::SeqCst),