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
@@ -93,8 +93,8 @@ struct Query {
93
93
  replies: NonNull<Replies>,
94
94
  }
95
95
 
96
- // The handle is used only by the task that owns the query, one thread at a
97
- // time, as the reactor runs a task.
96
+ // The handle is used only by the lookup that owns the query, one thread at a
97
+ // time, as the lookup's future is polled under one lock.
98
98
  unsafe impl Send for Query {}
99
99
 
100
100
  impl Query {
@@ -128,7 +128,8 @@ impl Query {
128
128
  });
129
129
  }
130
130
  let fd = unsafe { DNSServiceRefSockFD(sd_ref) };
131
- match reactor.register(&mut SourceFd(&fd), waker) {
131
+ // The daemon's replies arrive on the descriptor; nothing writes to it.
132
+ match reactor.register(&mut SourceFd(&fd), waker, false) {
132
133
  Ok(registration) => Ok(Self {
133
134
  sd_ref,
134
135
  fd,
@@ -254,6 +255,10 @@ impl Future for Queries {
254
255
  // read again at once.
255
256
  loop {
256
257
  let changed = self.waker.poll_changed(cx);
258
+ // A stopped reactor brings no reply again.
259
+ if let Poll::Ready(Err(_)) = changed {
260
+ return Poll::Ready(Err(LookupError::Again));
261
+ }
257
262
  self.queries.iter_mut().for_each(Query::take_replies);
258
263
  if self.queries.iter().all(|query| query.replies().answered) {
259
264
  break;
@@ -467,3 +467,53 @@ fn a_config_holding_a_byte_no_encoding_spells_still_reads() {
467
467
  glibc reads it as bytes"
468
468
  );
469
469
  }
470
+
471
+ #[test]
472
+ fn a_child_forked_on_the_drawing_thread_draws_query_ids_of_its_own() {
473
+ draw_id();
474
+ let mut ends = [0; 2];
475
+ // SAFETY: a pipe into two descriptors this test owns.
476
+ assert_eq!(unsafe { libc::pipe(ends.as_mut_ptr()) }, 0, "a pipe opens");
477
+ // SAFETY: the child only draws, writes, and exits, never returning to
478
+ // the harness.
479
+ let child = unsafe { libc::fork() };
480
+ if child == 0 {
481
+ let code =
482
+ match std::panic::catch_unwind(|| -> [u16; 4] { std::array::from_fn(|_| draw_id()) }) {
483
+ // SAFETY: writing IDs this child owns to its pipe.
484
+ Ok(ids) => unsafe {
485
+ i32::from(
486
+ libc::write(ends[1], ids.as_ptr().cast(), size_of_val(&ids))
487
+ != size_of_val(&ids) as isize,
488
+ )
489
+ },
490
+ Err(_) => 1,
491
+ };
492
+ // SAFETY: the child ends here.
493
+ unsafe { libc::_exit(code) };
494
+ }
495
+ let parent: [u16; 4] = std::array::from_fn(|_| draw_id());
496
+ let mut drawn = [0u16; 4];
497
+ let mut status = 0;
498
+ // SAFETY: reading into a buffer this test owns, then reaping the child.
499
+ let read = unsafe {
500
+ libc::close(ends[1]);
501
+ let read = libc::read(ends[0], drawn.as_mut_ptr().cast(), size_of_val(&drawn));
502
+ libc::close(ends[0]);
503
+ libc::waitpid(child, &mut status, 0);
504
+ read
505
+ };
506
+ assert_eq!(
507
+ (
508
+ read,
509
+ libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0
510
+ ),
511
+ (size_of_val(&drawn) as isize, true),
512
+ "a forked child must draw and send its query IDs"
513
+ );
514
+ assert_ne!(
515
+ drawn, parent,
516
+ "a child forked on the thread that drew query IDs must draw IDs of its own, so workers \
517
+ forked from one server never send the same sequence"
518
+ );
519
+ }
@@ -4,14 +4,11 @@
4
4
  //! comes truncated. Its sockets wait on the reactor, so dropping the query
5
5
  //! closes them, which glibc's blocking `getaddrinfo` cannot offer.
6
6
 
7
- use std::collections::hash_map::RandomState;
8
7
  use std::collections::{HashMap, HashSet};
9
8
  use std::fmt;
10
9
  use std::future::poll_fn;
11
- use std::hash::{BuildHasher, Hasher};
12
10
  use std::io::{self, Read, Write};
13
11
  use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
14
- use std::sync::atomic::{AtomicU64, Ordering};
15
12
  use std::sync::{Arc, Weak};
16
13
  use std::task::Poll;
17
14
  use std::time::{Duration, Instant};
@@ -21,7 +18,7 @@ use simple_dns::rdata::RData;
21
18
  use simple_dns::{Name, Packet, PacketFlag, Question, CLASS, QCLASS, QTYPE, RCODE, TYPE};
22
19
 
23
20
  use super::ReadyWaker;
24
- use crate::net::lookup::{LookupError, Resolving};
21
+ use crate::net::lookup::{LookupError, Resolving, NS_MAXCDNAME};
25
22
  use crate::net::reactor::{Reactor, Ready, Registration};
26
23
 
27
24
  /// glibc's `RES_TIMEOUT`, `RES_DFLRETRY`, `RES_MAXRETRANS`, `RES_MAXRETRY`,
@@ -39,9 +36,7 @@ const NAMESERVER_PORT: u16 = 53;
39
36
  /// server truncates.
40
37
  const PACKETSZ: usize = 512;
41
38
 
42
- /// glibc's `NS_MAXCDNAME` and `NS_MAXLABEL`: the most bytes a name takes on
43
- /// the wire, and a label holds.
44
- const NS_MAXCDNAME: usize = 255;
39
+ /// glibc's `NS_MAXLABEL`: the most bytes a label holds.
45
40
  const NS_MAXLABEL: usize = 63;
46
41
 
47
42
  pub(super) fn resolve(name: &str) -> Resolving {
@@ -369,12 +364,14 @@ fn is_on_chain(chain: &HashSet<String>, name: &Name<'_>) -> bool {
369
364
  chain.contains(&name.to_string().to_ascii_lowercase())
370
365
  }
371
366
 
372
- /// Draw a query ID no off-path sender can guess, as `res_mkquery` does.
367
+ /// Draw a query ID no off-path sender can guess, as `res_mkquery` does,
368
+ /// from the kernel each time: no state is kept for a forked child to draw
369
+ /// the same IDs from.
373
370
  fn draw_id() -> u16 {
374
- static COUNT: AtomicU64 = AtomicU64::new(0);
375
- let mut hasher = RandomState::new().build_hasher();
376
- hasher.write_u64(COUNT.fetch_add(1, Ordering::Relaxed));
377
- hasher.finish() as u16
371
+ let mut id = [0; 2];
372
+ rustix::rand::getrandom(&mut id, rustix::rand::GetRandomFlags::empty())
373
+ .expect("getrandom must answer two bytes once the kernel's pool is ready");
374
+ u16::from_ne_bytes(id)
378
375
  }
379
376
 
380
377
  /// A socket the reactor watches, waited on until a deadline.
@@ -391,14 +388,19 @@ impl WatchedSocket<mio::net::UdpSocket> {
391
388
  let socket = mio::net::UdpSocket::bind(super::any_address_of(server))
392
389
  .map_err(|err| io::Error::other(Unopened(err)))?;
393
390
  socket.connect(server)?;
394
- Self::watch(socket)
391
+ Self::watch(socket, false)
395
392
  }
396
393
 
397
394
  async fn send(&mut self, bytes: &[u8], deadline: Instant) -> io::Result<()> {
398
395
  loop {
399
396
  match self.socket.send(bytes) {
400
- Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
401
- sent => return sent.map(drop),
397
+ Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
398
+ self.registration.set_nospace(&mut self.socket, true);
399
+ }
400
+ sent => {
401
+ self.registration.set_nospace(&mut self.socket, false);
402
+ return sent.map(drop);
403
+ }
402
404
  }
403
405
  if !self.wait_for_change(deadline).await {
404
406
  return Err(io::ErrorKind::TimedOut.into());
@@ -447,8 +449,10 @@ impl WatchedSocket<mio::net::UdpSocket> {
447
449
  }
448
450
 
449
451
  impl WatchedSocket<mio::net::TcpStream> {
452
+ /// Watched for room until it reads, as its connect and its question
453
+ /// both wait on the stream turning writable.
450
454
  fn connect_tcp(server: SocketAddr) -> io::Result<Self> {
451
- Self::watch(mio::net::TcpStream::connect(server)?)
455
+ Self::watch(mio::net::TcpStream::connect(server)?, true)
452
456
  }
453
457
 
454
458
  async fn write_all(&mut self, mut bytes: &[u8], deadline: Instant) -> io::Result<()> {
@@ -475,6 +479,7 @@ impl WatchedSocket<mio::net::TcpStream> {
475
479
  /// Fill `buffer`; `false` when the stream ends or the deadline passes
476
480
  /// first.
477
481
  async fn read_exact(&mut self, mut buffer: &mut [u8], deadline: Instant) -> io::Result<bool> {
482
+ self.registration.set_nospace(&mut self.socket, false);
478
483
  while !buffer.is_empty() {
479
484
  match self.socket.read(buffer) {
480
485
  Ok(0) => return Ok(false),
@@ -492,10 +497,10 @@ impl WatchedSocket<mio::net::TcpStream> {
492
497
  }
493
498
 
494
499
  impl<S: Source> WatchedSocket<S> {
495
- fn watch(mut socket: S) -> io::Result<Self> {
500
+ fn watch(mut socket: S, nospace: bool) -> io::Result<Self> {
496
501
  let waker = Arc::new(ReadyWaker::default());
497
502
  let ready = Arc::downgrade(&waker) as Weak<dyn Ready>;
498
- let registration = Reactor::current()?.register(&mut socket, ready)?;
503
+ let registration = Reactor::current()?.register(&mut socket, ready, nospace)?;
499
504
  Ok(Self {
500
505
  socket,
501
506
  registration,
@@ -503,14 +508,15 @@ impl<S: Source> WatchedSocket<S> {
503
508
  })
504
509
  }
505
510
 
506
- /// Wait until the socket changes, `false` once `deadline` passes first.
507
- /// The timer goes with the wait it bounds, whether it ends or is
508
- /// cancelled.
511
+ /// Wait until the socket changes, `false` once `deadline` passes first
512
+ /// or the reactor watching it stopped, so the next question opens a
513
+ /// socket of its own. The timer goes with the wait it bounds, whether it
514
+ /// ends or is cancelled.
509
515
  async fn wait_for_change(&self, deadline: Instant) -> bool {
510
516
  let mut timer = None;
511
517
  poll_fn(|cx| {
512
- if self.waker.poll_changed(cx).is_ready() {
513
- return Poll::Ready(true);
518
+ if let Poll::Ready(changed) = self.waker.poll_changed(cx) {
519
+ return Poll::Ready(changed.is_ok());
514
520
  }
515
521
  if Instant::now() >= deadline {
516
522
  return Poll::Ready(false);
@@ -3,13 +3,13 @@
3
3
  //! `GetAddrInfoExCancel` cancels it. The routine runs on a system thread even
4
4
  //! after a cancel, so it holds its own reference to what it writes.
5
5
 
6
- use std::cell::{Cell, UnsafeCell};
6
+ use std::cell::UnsafeCell;
7
7
  use std::future::Future;
8
8
  use std::io;
9
9
  use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
10
10
  use std::pin::Pin;
11
11
  use std::ptr::{null, null_mut};
12
- use std::sync::atomic::{AtomicU8, Ordering};
12
+ use std::sync::atomic::{AtomicBool, Ordering};
13
13
  use std::sync::{Arc, Mutex, OnceLock, PoisonError};
14
14
  use std::task::{Context, Poll, Waker};
15
15
 
@@ -52,12 +52,12 @@ struct QueryContext {
52
52
  overlapped: UnsafeCell<OVERLAPPED>,
53
53
  result: UnsafeCell<*mut ADDRINFOEXW>,
54
54
  handle: UnsafeCell<HANDLE>,
55
- /// Whether the query is pending, being cancelled, or done. A cancel and
56
- /// the routine's end exclude each other, so no cancel follows a routine
57
- /// that marked the query done; one racing Windows' own completion,
58
- /// before the routine marks it, answers `WSA_INVALID_HANDLE` as
59
- /// `GetAddrInfoExCancel` documents.
60
- phase: AtomicU8,
55
+ /// Whether the routine ran, so a cancel after it is skipped. A cancel
56
+ /// racing the routine answers `WSA_INVALID_HANDLE` as
57
+ /// `GetAddrInfoExCancel` documents, and the routine never waits for it,
58
+ /// as .NET's `NameResolutionPal` leaves the two: a cancel may itself wait
59
+ /// for the routine to finish.
60
+ completed: AtomicBool,
61
61
  state: Mutex<State>,
62
62
  }
63
63
 
@@ -66,16 +66,6 @@ struct QueryContext {
66
66
  unsafe impl Send for QueryContext {}
67
67
  unsafe impl Sync for QueryContext {}
68
68
 
69
- const PENDING: u8 = 0;
70
- const CANCELLING: u8 = 1;
71
- const DONE: u8 = 2;
72
-
73
- thread_local! {
74
- /// Whether this thread is inside `GetAddrInfoExCancel`, which may run the
75
- /// routine on it before returning.
76
- static IN_CANCEL: Cell<bool> = const { Cell::new(false) };
77
- }
78
-
79
69
  #[derive(Default)]
80
70
  struct State {
81
71
  answer: Option<Result<Vec<IpAddr>, LookupError>>,
@@ -88,37 +78,17 @@ impl QueryContext {
88
78
  overlapped: UnsafeCell::new(unsafe { std::mem::zeroed() }),
89
79
  result: UnsafeCell::new(null_mut()),
90
80
  handle: UnsafeCell::new(null_mut()),
91
- phase: AtomicU8::new(PENDING),
81
+ completed: AtomicBool::new(false),
92
82
  state: Mutex::default(),
93
83
  }
94
84
  }
95
85
 
96
- /// Mark the query done, waiting out a cancel another thread is making,
97
- /// so the handle stays valid for as long as that cancel names it.
98
- fn end(&self) {
99
- loop {
100
- match self
101
- .phase
102
- .compare_exchange(PENDING, DONE, Ordering::AcqRel, Ordering::Acquire)
103
- {
104
- Ok(_) | Err(DONE) => return,
105
- Err(_) if IN_CANCEL.get() => return,
106
- Err(_) => std::thread::yield_now(),
107
- }
108
- }
109
- }
110
-
111
- /// Cancel the query unless it already ended.
86
+ /// Cancel the query unless its routine already ran. The context outlives
87
+ /// the call, held by the canceller, so the handle it names is always
88
+ /// readable.
112
89
  fn cancel(&self) {
113
- let claimed = self
114
- .phase
115
- .compare_exchange(PENDING, CANCELLING, Ordering::AcqRel, Ordering::Acquire)
116
- .is_ok();
117
- if claimed {
118
- IN_CANCEL.set(true);
90
+ if !self.completed.load(Ordering::Acquire) {
119
91
  unsafe { GetAddrInfoExCancel(self.handle.get()) };
120
- IN_CANCEL.set(false);
121
- self.phase.store(DONE, Ordering::Release);
122
92
  }
123
93
  }
124
94
 
@@ -129,7 +99,7 @@ impl QueryContext {
129
99
  /// Take the query's outcome, `error` being its Winsock code, and wake
130
100
  /// whoever waits for it.
131
101
  fn finish(&self, error: u32) {
132
- self.end();
102
+ self.completed.store(true, Ordering::Release);
133
103
  let result = unsafe { std::mem::replace(&mut *self.result.get(), null_mut()) };
134
104
  let answer = match error {
135
105
  0 => Ok(unsafe { addresses_of(result) }),
@@ -87,30 +87,55 @@ fn is_reachable(dest: &IpAddr, local: &[IpAddr]) -> bool {
87
87
  /// while no task waited, so a task that reads after it learns of it.
88
88
  #[cfg(unix)]
89
89
  #[derive(Default)]
90
- struct ReadyWaker(Mutex<(bool, Option<Waker>)>);
90
+ struct ReadyWaker(Mutex<WakerState>);
91
+
92
+ #[cfg(unix)]
93
+ #[derive(Default)]
94
+ struct WakerState {
95
+ changed: bool,
96
+ /// The reactor watching the socket stopped, so no change comes again.
97
+ aborted: bool,
98
+ waker: Option<Waker>,
99
+ }
91
100
 
92
101
  #[cfg(unix)]
93
102
  impl ReadyWaker {
94
- /// Ready once the socket changed since the last ready answer; otherwise
95
- /// the task waits for the next change.
96
- fn poll_changed(&self, cx: &mut Context<'_>) -> Poll<()> {
97
- let mut state = self.0.lock().unwrap_or_else(PoisonError::into_inner);
98
- if std::mem::take(&mut state.0) {
99
- return Poll::Ready(());
103
+ /// Ready once the socket changed since the last ready answer, and
104
+ /// `ECONNABORTED` for good once the reactor watching it stopped;
105
+ /// otherwise the task waits for the next change.
106
+ fn poll_changed(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
107
+ let mut state = self.state();
108
+ if state.aborted {
109
+ return Poll::Ready(Err(io::ErrorKind::ConnectionAborted.into()));
100
110
  }
101
- state.1 = Some(cx.waker().clone());
111
+ if std::mem::take(&mut state.changed) {
112
+ return Poll::Ready(Ok(()));
113
+ }
114
+ state.waker = Some(cx.waker().clone());
102
115
  Poll::Pending
103
116
  }
117
+
118
+ fn state(&self) -> std::sync::MutexGuard<'_, WakerState> {
119
+ self.0.lock().unwrap_or_else(PoisonError::into_inner)
120
+ }
121
+
122
+ fn wake(&self, mark: impl FnOnce(&mut WakerState)) {
123
+ let mut state = self.state();
124
+ mark(&mut state);
125
+ if let Some(waker) = state.waker.take() {
126
+ waker.wake();
127
+ }
128
+ }
104
129
  }
105
130
 
106
131
  #[cfg(unix)]
107
132
  impl Ready for ReadyWaker {
108
- fn on_event(&self) {
109
- let mut state = self.0.lock().unwrap_or_else(PoisonError::into_inner);
110
- state.0 = true;
111
- if let Some(waker) = state.1.take() {
112
- waker.wake();
113
- }
133
+ fn on_event(&self, _events: crate::vfs::PollMask) {
134
+ self.wake(|state| state.changed = true);
135
+ }
136
+
137
+ fn abort(&self) {
138
+ self.wake(|state| state.aborted = true);
114
139
  }
115
140
  }
116
141
 
@@ -204,7 +229,6 @@ mod tests {
204
229
  }
205
230
 
206
231
  // @behavior NW-228
207
- #[cfg(unix)]
208
232
  #[test]
209
233
  fn a_name_no_query_can_carry_answers_no_name() {
210
234
  let long_label = format!("{}.test.", "a".repeat(64));
@@ -0,0 +1,109 @@
1
+ //! The bytes a stream holds, as Linux's `sk_buff_head` chains a socket's
2
+ //! buffers: each push is a buffer of its own, sized to what it holds, freed
3
+ //! once wholly read.
4
+
5
+ use std::collections::VecDeque;
6
+
7
+ /// A stream's queued bytes, oldest first.
8
+ #[derive(Default)]
9
+ pub(crate) struct SkBuffHead {
10
+ buffers: VecDeque<Vec<u8>>,
11
+ /// How much of the oldest buffer was read already.
12
+ offset: usize,
13
+ len: usize,
14
+ }
15
+
16
+ impl SkBuffHead {
17
+ /// The bytes it holds unread.
18
+ pub(crate) fn len(&self) -> usize {
19
+ self.len
20
+ }
21
+
22
+ pub(crate) fn is_empty(&self) -> bool {
23
+ self.len == 0
24
+ }
25
+
26
+ /// Queue `bytes` as one buffer of their own.
27
+ pub(crate) fn push(&mut self, bytes: &[u8]) {
28
+ self.push_buffer(bytes.to_vec());
29
+ }
30
+
31
+ /// Queue `buffer` as it is, as `__skb_queue_tail` links an `sk_buff`.
32
+ pub(crate) fn push_buffer(&mut self, buffer: Vec<u8>) {
33
+ if buffer.is_empty() {
34
+ return;
35
+ }
36
+ self.len += buffer.len();
37
+ self.buffers.push_back(buffer);
38
+ }
39
+
40
+ /// The oldest unread bytes, as one slice.
41
+ pub(crate) fn front(&self) -> &[u8] {
42
+ self.buffers
43
+ .front()
44
+ .map_or(&[], |buffer| &buffer[self.offset..])
45
+ }
46
+
47
+ /// Mark `n` of the oldest bytes read, freeing each buffer wholly read.
48
+ pub(crate) fn advance(&mut self, mut n: usize) {
49
+ n = n.min(self.len);
50
+ self.len -= n;
51
+ while n > 0 {
52
+ let Some(buffer) = self.buffers.front() else {
53
+ break;
54
+ };
55
+ let left = buffer.len() - self.offset;
56
+ if n < left {
57
+ self.offset += n;
58
+ return;
59
+ }
60
+ n -= left;
61
+ self.buffers.pop_front();
62
+ self.offset = 0;
63
+ }
64
+ }
65
+
66
+ /// Copy the oldest bytes into `buf`, as many as fit, and free what was
67
+ /// wholly read; answers how many it copied.
68
+ pub(crate) fn read_into(&mut self, buf: &mut [u8]) -> usize {
69
+ let mut copied = 0;
70
+ while copied < buf.len() && !self.is_empty() {
71
+ let front = self.front();
72
+ let n = front.len().min(buf.len() - copied);
73
+ buf[copied..copied + n].copy_from_slice(&front[..n]);
74
+ copied += n;
75
+ self.advance(n);
76
+ }
77
+ copied
78
+ }
79
+
80
+ /// Free every buffer, as `__skb_queue_purge` does.
81
+ pub(crate) fn purge(&mut self) {
82
+ *self = Self::default();
83
+ }
84
+ }
85
+
86
+ #[cfg(test)]
87
+ mod tests {
88
+ use super::*;
89
+
90
+ #[test]
91
+ fn a_queue_answers_its_bytes_in_order_and_frees_each_buffer_wholly_read() {
92
+ let mut queue = SkBuffHead::default();
93
+ queue.push(b"hello");
94
+ queue.push(b"world");
95
+ let mut buf = [0; 7];
96
+ let copied = queue.read_into(&mut buf);
97
+ assert_eq!(
98
+ (
99
+ &buf[..copied],
100
+ queue.len(),
101
+ queue.buffers.len(),
102
+ queue.front()
103
+ ),
104
+ (&b"hellowo"[..], 3, 1, &b"rld"[..]),
105
+ "a queue of two 5-byte buffers read 7 bytes into must answer them in order, \
106
+ keep only the buffer still partly unread, and answer its rest first"
107
+ );
108
+ }
109
+ }