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.
- checksums.yaml +4 -4
- data/.githooks/linux-tests.sh +29 -0
- data/.release-please-manifest.json +1 -1
- data/CHANGELOG.md +125 -0
- data/Cargo.lock +457 -494
- data/README.md +2 -3
- data/ROADMAP.md +0 -1
- data/crates/kobako-runtime/CHANGELOG.md +90 -0
- data/crates/kobako-runtime/Cargo.toml +14 -15
- data/crates/kobako-runtime/README.md +1 -1
- data/crates/kobako-runtime/src/cred.rs +32 -20
- data/crates/kobako-runtime/src/filesystem/bind/fid.rs +300 -22
- data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +56 -22
- data/crates/kobako-runtime/src/filesystem/bind/unicode.rs +109 -0
- data/crates/kobako-runtime/src/filesystem/bind/walk.rs +33 -14
- data/crates/kobako-runtime/src/filesystem/bind.rs +393 -220
- data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +2 -0
- data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +9 -10
- data/crates/kobako-runtime/src/filesystem/overlay.rs +277 -46
- data/crates/kobako-runtime/src/filesystem/rdir.rs +8 -27
- data/crates/kobako-runtime/src/filesystem/testing.rs +31 -0
- data/crates/kobako-runtime/src/filesystem/tmpfs.rs +47 -13
- data/crates/kobako-runtime/src/filesystem.rs +2 -0
- data/crates/kobako-runtime/src/fork.rs +239 -16
- data/crates/kobako-runtime/src/limits.rs +17 -41
- data/crates/kobako-runtime/src/locking/seqlock.rs +29 -3
- data/crates/kobako-runtime/src/locking.rs +508 -113
- data/crates/kobako-runtime/src/memcg.rs +83 -160
- data/crates/kobako-runtime/src/mount.rs +0 -30
- data/crates/kobako-runtime/src/net/connections.rs +53 -13
- data/crates/kobako-runtime/src/net/egress.rs +44 -24
- data/crates/kobako-runtime/src/net/http.rs +888 -456
- data/crates/kobako-runtime/src/net/lookup.rs +150 -50
- data/crates/kobako-runtime/src/net/namespace.rs +97 -95
- data/crates/kobako-runtime/src/net/reactor.rs +298 -203
- data/crates/kobako-runtime/src/net/resolv/darwin.rs +8 -3
- data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +50 -0
- data/crates/kobako-runtime/src/net/resolv/stub.rs +29 -23
- data/crates/kobako-runtime/src/net/resolv/windows.rs +14 -44
- data/crates/kobako-runtime/src/net/resolv.rs +39 -15
- data/crates/kobako-runtime/src/net/skbuff.rs +109 -0
- data/crates/kobako-runtime/src/net/socket.rs +51 -52
- data/crates/kobako-runtime/src/net/task.rs +223 -0
- data/crates/kobako-runtime/src/net/tcp.rs +410 -158
- data/crates/kobako-runtime/src/net/tls.rs +65 -3
- data/crates/kobako-runtime/src/net/transport.rs +72 -47
- data/crates/kobako-runtime/src/net/udp.rs +231 -129
- data/crates/kobako-runtime/src/net.rs +3 -0
- data/crates/kobako-runtime/src/sched.rs +244 -58
- data/crates/kobako-runtime/src/security.rs +27 -16
- data/crates/kobako-runtime/src/vfs/dentry.rs +80 -41
- data/crates/kobako-runtime/src/vfs/file.rs +52 -53
- data/crates/kobako-runtime/src/vfs/kern_path.rs +24 -11
- data/crates/kobako-runtime/src/vfs/namei.rs +399 -184
- data/crates/kobako-runtime/src/vfs/namespace.rs +123 -40
- data/crates/kobako-runtime/src/vfs/stat.rs +105 -16
- data/crates/kobako-runtime/src/vfs.rs +1 -0
- data/crates/kobako-runtime/src/wait.rs +75 -50
- data/crates/kobako-transport/CHANGELOG.md +7 -0
- data/crates/kobako-transport/Cargo.toml +1 -1
- data/crates/kobako-transport/README.md +1 -1
- data/crates/kobako-wasmtime/CHANGELOG.md +47 -0
- data/crates/kobako-wasmtime/Cargo.toml +27 -6
- data/crates/kobako-wasmtime/README.md +3 -3
- data/crates/kobako-wasmtime/src/abi.rs +2 -1
- data/crates/kobako-wasmtime/src/ambient.rs +11 -2
- data/crates/kobako-wasmtime/src/cache/unix.rs +95 -0
- data/crates/kobako-wasmtime/src/cache/windows.rs +359 -0
- data/crates/kobako-wasmtime/src/cache.rs +88 -103
- data/crates/kobako-wasmtime/src/driver.rs +40 -27
- data/crates/kobako-wasmtime/src/invocation.rs +21 -7
- data/crates/kobako-wasmtime/src/lib.rs +2 -0
- data/crates/kobako-wasmtime/src/limiter.rs +78 -25
- data/crates/kobako-wasmtime/src/preview1/descriptors.rs +13 -17
- data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +4 -5
- data/crates/kobako-wasmtime/src/preview1/differential.rs +1 -1
- data/crates/kobako-wasmtime/src/preview1/fd.rs +23 -19
- data/crates/kobako-wasmtime/src/preview1/mount_view.rs +130 -197
- data/crates/kobako-wasmtime/src/preview1/path.rs +3 -3
- data/crates/kobako-wasmtime/src/preview1/poll.rs +28 -22
- data/crates/kobako-wasmtime/src/preview1/random.rs +125 -0
- data/crates/kobako-wasmtime/src/preview1/testing.rs +31 -0
- data/crates/kobako-wasmtime/src/preview1.rs +85 -9
- data/crates/kobako-wasmtime/src/preview2/filesystem.rs +2 -2
- data/crates/kobako-wasmtime/src/preview2/host.rs +609 -249
- data/crates/kobako-wasmtime/src/preview2/http.rs +299 -215
- data/crates/kobako-wasmtime/src/preview2/io.rs +17 -4
- data/crates/kobako-wasmtime/src/preview2/table.rs +24 -72
- data/crates/kobako-wasmtime/src/trap.rs +68 -23
- data/crates/kobako-wasmtime/src/waits.rs +59 -0
- data/crates/kobako-wasmtime/src/wasi.rs +91 -10
- data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
- data/data/kobako.wasm +0 -0
- data/ext/kobako/Cargo.toml +6 -2
- data/ext/kobako/src/escape.rs +332 -26
- data/ext/kobako/src/filesystem/grants.rs +5 -7
- data/ext/kobako/src/filesystem/ruby.rs +10 -3
- data/ext/kobako/src/filesystem.rs +47 -8
- data/ext/kobako/src/fork.rs +72 -0
- data/ext/kobako/src/gvl.rs +499 -76
- data/ext/kobako/src/handoff.rs +490 -0
- data/ext/kobako/src/lib.rs +10 -0
- data/ext/kobako/src/network.rs +5 -3
- data/ext/kobako/src/pinned_value.rs +28 -15
- data/ext/kobako/src/runtime/bridge.rs +32 -25
- data/ext/kobako/src/runtime.rs +74 -43
- data/lib/kobako/catalog/handles.rb +9 -5
- data/lib/kobako/codec/decoder.rb +1 -1
- data/lib/kobako/codec/state.rb +2 -18
- data/lib/kobako/codec/value_budget.rb +4 -4
- data/lib/kobako/codec.rb +5 -6
- data/lib/kobako/errors.rb +4 -7
- data/lib/kobako/filesystem.rb +1 -1
- data/lib/kobako/fork.rb +42 -0
- data/lib/kobako/handle.rb +1 -2
- data/lib/kobako/sandbox.rb +17 -36
- data/lib/kobako/sandbox_options.rb +7 -9
- data/lib/kobako/usage.rb +4 -2
- data/lib/kobako/version.rb +1 -1
- data/lib/kobako.rb +2 -2
- data/sig/kobako/catalog/handles.rbs +2 -0
- data/sig/kobako/codec/state.rbs +0 -4
- data/sig/kobako/codec/value_budget.rbs +1 -1
- data/sig/kobako/codec.rbs +2 -2
- data/sig/kobako/errors.rbs +0 -3
- data/sig/kobako/fork.rbs +17 -0
- data/sig/kobako/runtime.rbs +2 -2
- data/sig/kobako/sandbox.rbs +3 -12
- data/sig/kobako/sandbox_options.rbs +0 -2
- metadata +15 -4
- data/lib/kobako/pool.rb +0 -162
- data/sig/core/thread.rbs +0 -6
- data/sig/kobako/pool.rbs +0 -46
|
@@ -1,33 +1,33 @@
|
|
|
1
1
|
//! An HTTP request the guest sends, as a userspace proxy forwards one: the
|
|
2
2
|
//! namespace judges what the guest named on the guest thread, then a task on
|
|
3
3
|
//! the reactor hands the request to the outbound seam, whose only dialer is
|
|
4
|
-
//! kobako's connector. The
|
|
5
|
-
//!
|
|
6
|
-
//!
|
|
4
|
+
//! kobako's connector. The request's body streams through a buffer the guest
|
|
5
|
+
//! writes into, and the response's body fills a buffer the guest reads
|
|
6
|
+
//! through the wait queue, so a full buffer either way stops its side and the
|
|
7
|
+
//! TCP window pushes back.
|
|
7
8
|
|
|
8
|
-
use std::collections::VecDeque;
|
|
9
9
|
use std::future::{poll_fn, Future};
|
|
10
10
|
use std::io;
|
|
11
11
|
use std::pin::Pin;
|
|
12
|
-
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
|
|
12
|
+
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak};
|
|
13
13
|
use std::task::{Context, Poll, Waker};
|
|
14
14
|
use std::time::{Duration, Instant};
|
|
15
15
|
|
|
16
|
-
use bytes::Bytes;
|
|
16
|
+
use bytes::{Bytes, BytesMut};
|
|
17
17
|
use http_body::Body;
|
|
18
18
|
use http_body_util::combinators::UnsyncBoxBody;
|
|
19
|
-
use http_body_util::
|
|
19
|
+
use http_body_util::BodyExt;
|
|
20
20
|
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
|
21
21
|
|
|
22
22
|
use super::connections::{open, OpenConnections, Place};
|
|
23
23
|
use super::credential::Swap;
|
|
24
|
-
use super::
|
|
24
|
+
use super::skbuff::SkBuffHead;
|
|
25
|
+
use super::task::Task;
|
|
25
26
|
use super::transport::Connector;
|
|
26
27
|
use super::{new_platform_tls, MAX_SOCKET_BUFFER};
|
|
27
28
|
use crate::cred::Cred;
|
|
28
29
|
use crate::errno::CarriedErrno;
|
|
29
30
|
use crate::filesystem::anon_inode_getfile;
|
|
30
|
-
use crate::memcg::MemoryCharge;
|
|
31
31
|
use crate::vfs::{FMode, File, FileOperations, Kiocb, OpenHow, PollMask};
|
|
32
32
|
use crate::wait::{poll_wait, PollTable, WaitQueueHead};
|
|
33
33
|
use crate::Errno;
|
|
@@ -65,8 +65,6 @@ pub enum FieldError {
|
|
|
65
65
|
Forbidden,
|
|
66
66
|
/// The list would outgrow `MAX_FIELD_SIZE`.
|
|
67
67
|
TooLarge,
|
|
68
|
-
/// The list would outgrow the Invocation's memory.
|
|
69
|
-
OutOfMemory,
|
|
70
68
|
}
|
|
71
69
|
|
|
72
70
|
/// The most room one header list the guest builds may take, as wasmtime's
|
|
@@ -76,13 +74,12 @@ pub const MAX_FIELD_SIZE: usize = 128 * 1024;
|
|
|
76
74
|
|
|
77
75
|
/// The most a response's head, or one read of its body, takes in the seam's
|
|
78
76
|
/// read buffer, as hyper's `max_buf_size` bounds it, so a head the guest could
|
|
79
|
-
/// read as a header list fits and a longer one answers a protocol error.
|
|
80
|
-
/// exchange holds it against the Invocation's memory.
|
|
77
|
+
/// read as a header list fits and a longer one answers a protocol error.
|
|
81
78
|
const MAX_READ_BUFFER: usize = MAX_FIELD_SIZE;
|
|
82
79
|
|
|
83
|
-
/// A header list the guest builds or reads
|
|
84
|
-
///
|
|
85
|
-
///
|
|
80
|
+
/// A header list the guest builds or reads. What the guest appends stays
|
|
81
|
+
/// within `MAX_FIELD_SIZE`, and a response's head within the read buffer, so
|
|
82
|
+
/// a list holds a fixed most.
|
|
86
83
|
pub struct Fields {
|
|
87
84
|
list: Mutex<List>,
|
|
88
85
|
}
|
|
@@ -90,7 +87,7 @@ pub struct Fields {
|
|
|
90
87
|
/// A list's entries and the room they take.
|
|
91
88
|
struct List {
|
|
92
89
|
entries: Vec<(String, Vec<u8>)>,
|
|
93
|
-
room:
|
|
90
|
+
room: usize,
|
|
94
91
|
}
|
|
95
92
|
|
|
96
93
|
/// The room `name` and `value` take in a list.
|
|
@@ -107,50 +104,40 @@ fn total_room_of(entries: &[(String, Vec<u8>)]) -> usize {
|
|
|
107
104
|
}
|
|
108
105
|
|
|
109
106
|
impl Fields {
|
|
110
|
-
/// An empty list
|
|
111
|
-
pub fn new(
|
|
112
|
-
|
|
113
|
-
list: Mutex::new(List {
|
|
114
|
-
entries: Vec::new(),
|
|
115
|
-
room: MemoryCharge::empty(cred.memory_budget()),
|
|
116
|
-
}),
|
|
117
|
-
})
|
|
107
|
+
/// An empty list.
|
|
108
|
+
pub fn new() -> Arc<Self> {
|
|
109
|
+
Self::with_entries(Vec::new())
|
|
118
110
|
}
|
|
119
111
|
|
|
120
|
-
/// A list holding `entries`, as a response's headers are handed out
|
|
121
|
-
///
|
|
122
|
-
|
|
123
|
-
pub fn with_entries(
|
|
124
|
-
cred: Arc<Cred>,
|
|
125
|
-
entries: Vec<(String, Vec<u8>)>,
|
|
126
|
-
) -> Result<Arc<Self>, FieldError> {
|
|
112
|
+
/// A list holding `entries`, as a response's headers are handed out; it
|
|
113
|
+
/// may outgrow `MAX_FIELD_SIZE`, which only bounds what the guest appends.
|
|
114
|
+
pub fn with_entries(entries: Vec<(String, Vec<u8>)>) -> Arc<Self> {
|
|
127
115
|
let room = total_room_of(&entries);
|
|
128
|
-
|
|
129
|
-
MemoryCharge::new(cred.memory_budget(), room).map_err(|_| FieldError::OutOfMemory)?;
|
|
130
|
-
Ok(Arc::new(Self {
|
|
116
|
+
Arc::new(Self {
|
|
131
117
|
list: Mutex::new(List { entries, room }),
|
|
132
|
-
})
|
|
118
|
+
})
|
|
133
119
|
}
|
|
134
120
|
|
|
135
121
|
fn list(&self) -> MutexGuard<'_, List> {
|
|
136
122
|
self.list.lock().unwrap_or_else(PoisonError::into_inner)
|
|
137
123
|
}
|
|
138
124
|
|
|
125
|
+
/// The room the entries take, as a request's own parts share it.
|
|
126
|
+
pub fn room(&self) -> usize {
|
|
127
|
+
self.list().room
|
|
128
|
+
}
|
|
129
|
+
|
|
139
130
|
/// Append the header `name` with `value`, once `to_field_name` and
|
|
140
|
-
/// `to_field_value` take them and the list keeps within `MAX_FIELD_SIZE
|
|
141
|
-
/// and the Invocation's memory.
|
|
131
|
+
/// `to_field_value` take them and the list keeps within `MAX_FIELD_SIZE`.
|
|
142
132
|
pub fn append(&self, name: &str, value: Vec<u8>) -> Result<(), FieldError> {
|
|
143
133
|
let name = to_field_name(name)?;
|
|
144
134
|
let value = to_field_value(value)?;
|
|
145
|
-
let room = room_of(&name, &value);
|
|
146
135
|
let mut list = self.list();
|
|
147
|
-
let grown = list.room
|
|
136
|
+
let grown = list.room + room_of(&name, &value);
|
|
148
137
|
if grown > MAX_FIELD_SIZE {
|
|
149
138
|
return Err(FieldError::TooLarge);
|
|
150
139
|
}
|
|
151
|
-
list.room
|
|
152
|
-
.resize(grown)
|
|
153
|
-
.map_err(|_| FieldError::OutOfMemory)?;
|
|
140
|
+
list.room = grown;
|
|
154
141
|
list.entries.push((name, value));
|
|
155
142
|
Ok(())
|
|
156
143
|
}
|
|
@@ -272,7 +259,7 @@ pub struct OutgoingRequest {
|
|
|
272
259
|
pub authority: String,
|
|
273
260
|
pub path_with_query: String,
|
|
274
261
|
pub headers: Vec<(String, Vec<u8>)>,
|
|
275
|
-
pub body:
|
|
262
|
+
pub body: Arc<RequestBody>,
|
|
276
263
|
pub timeouts: Timeouts,
|
|
277
264
|
/// The credentials bound to this request, swapped in only by the default
|
|
278
265
|
/// outbound seam and only on the way out, so no other seam reads a secret.
|
|
@@ -314,80 +301,245 @@ impl OutgoingRequest {
|
|
|
314
301
|
authority: authority.into(),
|
|
315
302
|
path_with_query: "/".to_string(),
|
|
316
303
|
headers: Vec::new(),
|
|
317
|
-
body:
|
|
304
|
+
body: RequestBody::finished(&[]),
|
|
318
305
|
timeouts: Timeouts::default(),
|
|
319
306
|
swaps: Vec::new(),
|
|
320
307
|
}
|
|
321
308
|
}
|
|
322
|
-
|
|
323
|
-
/// The bytes its method, authority, path, and headers hold, as a header
|
|
324
|
-
/// list counts its entries.
|
|
325
|
-
fn room(&self) -> usize {
|
|
326
|
-
self.method.len()
|
|
327
|
-
+ self.authority.len()
|
|
328
|
-
+ self.path_with_query.len()
|
|
329
|
-
+ total_room_of(&self.headers)
|
|
330
|
-
}
|
|
331
309
|
}
|
|
332
310
|
|
|
333
|
-
/// The body a guest writes for a request,
|
|
334
|
-
///
|
|
335
|
-
///
|
|
311
|
+
/// The body a guest writes for a request, streamed to the seam as it is
|
|
312
|
+
/// written, as a pipe holds what its reader has not taken. The host holds at
|
|
313
|
+
/// most one socket buffer of it, so a server slow to take the body stops the
|
|
314
|
+
/// guest's writes and the TCP window pushes back, as wasi-http's
|
|
315
|
+
/// backpressure does.
|
|
336
316
|
pub struct RequestBody {
|
|
337
|
-
|
|
338
|
-
|
|
317
|
+
pipe: Mutex<Pipe>,
|
|
318
|
+
/// Writers waiting for room, as a pipe's `wr_wait`.
|
|
319
|
+
wait: Arc<WaitQueueHead>,
|
|
320
|
+
/// The exchange sending the body, which only the guest moves, so its
|
|
321
|
+
/// writes and polls move it too.
|
|
322
|
+
exchange: OnceLock<Weak<Exchange>>,
|
|
339
323
|
}
|
|
340
324
|
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
325
|
+
struct Pipe {
|
|
326
|
+
queued: BytesMut,
|
|
327
|
+
end: BodyEnd,
|
|
328
|
+
/// The seam's task waiting for what is written next.
|
|
329
|
+
reader: Option<Waker>,
|
|
330
|
+
/// A TRACE carries no content, so a write with any is refused.
|
|
331
|
+
refuses_content: bool,
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/// How far a request body got.
|
|
335
|
+
#[derive(Clone, Copy, PartialEq, Eq)]
|
|
336
|
+
enum BodyEnd {
|
|
337
|
+
Open,
|
|
338
|
+
Finished,
|
|
339
|
+
/// It ended without finishing, which fails its request as the code names.
|
|
340
|
+
Failed(HttpError),
|
|
345
341
|
}
|
|
346
342
|
|
|
347
343
|
impl RequestBody {
|
|
348
|
-
///
|
|
349
|
-
pub fn new(
|
|
350
|
-
let room = MemoryCharge::empty(cred.memory_budget());
|
|
344
|
+
/// A body the guest has written nothing to yet.
|
|
345
|
+
pub fn new() -> Arc<Self> {
|
|
351
346
|
Arc::new(Self {
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
347
|
+
pipe: Mutex::new(Pipe {
|
|
348
|
+
queued: BytesMut::new(),
|
|
349
|
+
end: BodyEnd::Open,
|
|
350
|
+
reader: None,
|
|
351
|
+
refuses_content: false,
|
|
356
352
|
}),
|
|
353
|
+
wait: Arc::default(),
|
|
354
|
+
exchange: OnceLock::new(),
|
|
357
355
|
})
|
|
358
356
|
}
|
|
359
357
|
|
|
360
|
-
|
|
361
|
-
|
|
358
|
+
/// Move the exchange sending the body as far as it goes, so the seam
|
|
359
|
+
/// takes what was written.
|
|
360
|
+
fn move_exchange(&self) -> Option<Arc<Exchange>> {
|
|
361
|
+
let exchange = self.exchange.get()?.upgrade()?;
|
|
362
|
+
exchange.poll_task();
|
|
363
|
+
Some(exchange)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/// A body already finished with `bytes`, as a request built whole sends.
|
|
367
|
+
pub(crate) fn finished(bytes: &[u8]) -> Arc<Self> {
|
|
368
|
+
let body = Self::new();
|
|
369
|
+
{
|
|
370
|
+
let mut pipe = body.pipe();
|
|
371
|
+
pipe.queued.extend_from_slice(bytes);
|
|
372
|
+
pipe.end = BodyEnd::Finished;
|
|
373
|
+
}
|
|
374
|
+
body
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
fn pipe(&self) -> MutexGuard<'_, Pipe> {
|
|
378
|
+
self.pipe.lock().unwrap_or_else(PoisonError::into_inner)
|
|
362
379
|
}
|
|
363
380
|
|
|
364
|
-
/// Allocate the file the guest writes the body through
|
|
365
|
-
/// `anon_inode_getfile` does; it
|
|
366
|
-
pub fn alloc_file(self: &Arc<Self>) -> File {
|
|
381
|
+
/// Allocate the file the guest writes the body through as `cred`, as
|
|
382
|
+
/// `anon_inode_getfile` does; it polls writable while the buffer has room.
|
|
383
|
+
pub fn alloc_file(self: &Arc<Self>, cred: &Arc<Cred>) -> File {
|
|
367
384
|
let how = OpenHow {
|
|
368
385
|
write: true,
|
|
369
386
|
nonblock: true,
|
|
370
387
|
..OpenHow::default()
|
|
371
388
|
};
|
|
372
|
-
anon_inode_getfile(Box::new(RequestBodyFile(self.clone())), &how,
|
|
389
|
+
anon_inode_getfile(Box::new(RequestBodyFile(self.clone())), &how, cred)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/// How many bytes a write takes now: what the buffer has left.
|
|
393
|
+
pub fn room(&self) -> usize {
|
|
394
|
+
MAX_SOCKET_BUFFER.saturating_sub(self.pipe().queued.len())
|
|
373
395
|
}
|
|
374
396
|
|
|
375
|
-
///
|
|
397
|
+
/// Whether the seam took everything written, so a flush is done.
|
|
398
|
+
pub fn is_drained(&self) -> bool {
|
|
399
|
+
self.pipe().queued.is_empty()
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/// Append what of `buf` the buffer has room for: `EAGAIN` while it has
|
|
403
|
+
/// none, and `EPIPE` once the body ended or for a TRACE's content.
|
|
376
404
|
fn write(&self, buf: &[u8]) -> Result<usize, Errno> {
|
|
377
|
-
let mut
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
405
|
+
let mut pipe = self.pipe();
|
|
406
|
+
if pipe.end != BodyEnd::Open || (pipe.refuses_content && !buf.is_empty()) {
|
|
407
|
+
return Err(Errno::BrokenPipe);
|
|
408
|
+
}
|
|
409
|
+
let take = buf.len().min(MAX_SOCKET_BUFFER - pipe.queued.len());
|
|
410
|
+
if take == 0 && !buf.is_empty() {
|
|
411
|
+
return Err(Errno::WouldBlock);
|
|
412
|
+
}
|
|
413
|
+
pipe.queued.extend_from_slice(&buf[..take]);
|
|
414
|
+
let reader = pipe.reader.take();
|
|
415
|
+
drop(pipe);
|
|
416
|
+
if let Some(reader) = reader {
|
|
417
|
+
reader.wake();
|
|
418
|
+
}
|
|
419
|
+
self.move_exchange();
|
|
420
|
+
Ok(take)
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/// End the body, so the seam sends what is left and finishes the request.
|
|
424
|
+
pub fn finish(&self) {
|
|
425
|
+
self.end(BodyEnd::Finished);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/// End the body unfinished, which fails its request with `code`.
|
|
429
|
+
pub fn fail(&self, code: HttpError) {
|
|
430
|
+
self.end(BodyEnd::Failed(code));
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
fn end(&self, end: BodyEnd) {
|
|
434
|
+
let mut pipe = self.pipe();
|
|
435
|
+
if pipe.end != BodyEnd::Open {
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
pipe.end = end;
|
|
439
|
+
let reader = pipe.reader.take();
|
|
440
|
+
drop(pipe);
|
|
441
|
+
if let Some(reader) = reader {
|
|
442
|
+
reader.wake();
|
|
443
|
+
}
|
|
444
|
+
self.wait.wake_up();
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/// Whether the guest finished the body before it was sent.
|
|
448
|
+
fn is_finished(&self) -> bool {
|
|
449
|
+
self.pipe().end == BodyEnd::Finished
|
|
382
450
|
}
|
|
383
451
|
|
|
384
|
-
///
|
|
385
|
-
///
|
|
386
|
-
pub fn
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
452
|
+
/// Whether the guest wrote content the seam has not taken, as a request
|
|
453
|
+
/// policy judges before anything is sent.
|
|
454
|
+
pub(crate) fn has_content(&self) -> bool {
|
|
455
|
+
!self.pipe().queued.is_empty()
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/// Refuse any content written from now on, as a TRACE carries none.
|
|
459
|
+
pub(crate) fn refuse_content(&self) {
|
|
460
|
+
self.pipe().refuses_content = true;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/// The next part of the body for the seam, waking writers the room it
|
|
464
|
+
/// frees.
|
|
465
|
+
fn poll_part(&self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, BodyFailed>>> {
|
|
466
|
+
let mut pipe = self.pipe();
|
|
467
|
+
if !pipe.queued.is_empty() {
|
|
468
|
+
let part = pipe.queued.split().freeze();
|
|
469
|
+
drop(pipe);
|
|
470
|
+
self.wait.wake_up();
|
|
471
|
+
return Poll::Ready(Some(Ok(part)));
|
|
472
|
+
}
|
|
473
|
+
match pipe.end {
|
|
474
|
+
BodyEnd::Finished => Poll::Ready(None),
|
|
475
|
+
BodyEnd::Failed(code) => Poll::Ready(Some(Err(BodyFailed(code)))),
|
|
476
|
+
BodyEnd::Open => {
|
|
477
|
+
pipe.reader = Some(cx.waker().clone());
|
|
478
|
+
Poll::Pending
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
impl std::fmt::Debug for RequestBody {
|
|
485
|
+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
486
|
+
f.debug_struct("RequestBody")
|
|
487
|
+
.field("queued", &self.pipe().queued.len())
|
|
488
|
+
.finish_non_exhaustive()
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/// A body is one stream, the same only as itself.
|
|
493
|
+
impl PartialEq for RequestBody {
|
|
494
|
+
fn eq(&self, other: &Self) -> bool {
|
|
495
|
+
std::ptr::eq(self, other)
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
impl Eq for RequestBody {}
|
|
500
|
+
|
|
501
|
+
/// Why a request body ended unfinished, carried through hyper to the
|
|
502
|
+
/// exchange it fails.
|
|
503
|
+
#[derive(Debug)]
|
|
504
|
+
struct BodyFailed(HttpError);
|
|
505
|
+
|
|
506
|
+
impl std::fmt::Display for BodyFailed {
|
|
507
|
+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
508
|
+
f.write_str("the request body ended unfinished")
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
impl std::error::Error for BodyFailed {}
|
|
513
|
+
|
|
514
|
+
/// A request body as hyper sends it, one part at a time.
|
|
515
|
+
struct StreamedBody(Arc<RequestBody>);
|
|
516
|
+
|
|
517
|
+
impl Body for StreamedBody {
|
|
518
|
+
type Data = Bytes;
|
|
519
|
+
type Error = BodyFailed;
|
|
520
|
+
|
|
521
|
+
fn poll_frame(
|
|
522
|
+
self: Pin<&mut Self>,
|
|
523
|
+
cx: &mut Context<'_>,
|
|
524
|
+
) -> Poll<Option<Result<http_body::Frame<Bytes>, BodyFailed>>> {
|
|
525
|
+
self.0
|
|
526
|
+
.poll_part(cx)
|
|
527
|
+
.map(|part| part.map(|part| part.map(http_body::Frame::data)))
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
fn is_end_stream(&self) -> bool {
|
|
531
|
+
let pipe = self.0.pipe();
|
|
532
|
+
pipe.end == BodyEnd::Finished && pipe.queued.is_empty()
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/// Exact once the guest finished the body, so hyper frames it by its
|
|
536
|
+
/// length, as CRuby's Net::HTTP does; chunked while it still streams.
|
|
537
|
+
fn size_hint(&self) -> http_body::SizeHint {
|
|
538
|
+
let pipe = self.0.pipe();
|
|
539
|
+
match pipe.end {
|
|
540
|
+
BodyEnd::Finished => http_body::SizeHint::with_exact(pipe.queued.len() as u64),
|
|
541
|
+
BodyEnd::Open | BodyEnd::Failed(_) => http_body::SizeHint::default(),
|
|
542
|
+
}
|
|
391
543
|
}
|
|
392
544
|
}
|
|
393
545
|
|
|
@@ -399,8 +551,18 @@ impl FileOperations for RequestBodyFile {
|
|
|
399
551
|
self.0.write(buf)
|
|
400
552
|
}
|
|
401
553
|
|
|
402
|
-
|
|
403
|
-
|
|
554
|
+
/// A wait on the body sleeps on the exchange too, whose socket's wake
|
|
555
|
+
/// moves the seam on to take what is written.
|
|
556
|
+
fn poll(&self, _mode: FMode, mut table: Option<&mut PollTable>) -> PollMask {
|
|
557
|
+
if let Some(exchange) = self.0.move_exchange() {
|
|
558
|
+
poll_wait(&exchange.wait, table.as_deref_mut());
|
|
559
|
+
}
|
|
560
|
+
poll_wait(&self.0.wait, table);
|
|
561
|
+
let pipe = self.0.pipe();
|
|
562
|
+
match pipe.end != BodyEnd::Open || pipe.queued.len() < MAX_SOCKET_BUFFER {
|
|
563
|
+
true => PollMask::OUT,
|
|
564
|
+
false => PollMask::default(),
|
|
565
|
+
}
|
|
404
566
|
}
|
|
405
567
|
|
|
406
568
|
fn is_stream(&self) -> bool {
|
|
@@ -458,7 +620,8 @@ pub struct Response {
|
|
|
458
620
|
pub body: ResponseBody,
|
|
459
621
|
}
|
|
460
622
|
|
|
461
|
-
/// What the outbound seam's send runs as
|
|
623
|
+
/// What the outbound seam's send runs as, polled by the thread that waits
|
|
624
|
+
/// for the response.
|
|
462
625
|
pub type ResponseFuture = Pin<Box<dyn Future<Output = Result<Response, HttpError>> + Send>>;
|
|
463
626
|
|
|
464
627
|
/// The HTTP sender, as wasmtime's `send_request`. It dials only through the
|
|
@@ -487,11 +650,11 @@ enum Phase {
|
|
|
487
650
|
|
|
488
651
|
struct State {
|
|
489
652
|
phase: Phase,
|
|
490
|
-
///
|
|
491
|
-
|
|
492
|
-
///
|
|
493
|
-
|
|
494
|
-
|
|
653
|
+
/// The body the guest reads, never past one socket buffer.
|
|
654
|
+
body: SkBuffHead,
|
|
655
|
+
/// The frame read from the seam that waits for room in the body, copied
|
|
656
|
+
/// out so the seam's own buffer goes free at once.
|
|
657
|
+
pending: Option<Vec<u8>>,
|
|
495
658
|
body_ended: bool,
|
|
496
659
|
body_failed: bool,
|
|
497
660
|
/// The body waited past its timeout for its next part.
|
|
@@ -518,10 +681,6 @@ pub struct Exchange {
|
|
|
518
681
|
task: Mutex<Option<Arc<Task>>>,
|
|
519
682
|
/// The request's place against its Sandbox's cap and the process's.
|
|
520
683
|
place: Mutex<Option<Arc<Place>>>,
|
|
521
|
-
/// What the request, the seam's read buffer, and the response's buffer
|
|
522
|
-
/// hold, reserved against the Invocation's memory until the exchange is
|
|
523
|
-
/// released.
|
|
524
|
-
memory: Mutex<Option<MemoryCharge>>,
|
|
525
684
|
timeouts: Timeouts,
|
|
526
685
|
started: Instant,
|
|
527
686
|
/// When the connector's connect opened, which starts the wait for the
|
|
@@ -530,32 +689,25 @@ pub struct Exchange {
|
|
|
530
689
|
}
|
|
531
690
|
|
|
532
691
|
impl Exchange {
|
|
533
|
-
/// Send `request` through `seam` on the
|
|
692
|
+
/// Send `request` through `seam` on the asking thread, dialing through the
|
|
534
693
|
/// connector `connector_for` makes with the request's place; it counts
|
|
535
694
|
/// against `open_connections` and the process until
|
|
536
695
|
/// released and its connection closed, and a full count answers
|
|
537
|
-
/// `ConnectionLimitReached`.
|
|
538
|
-
/// request, the seam's read buffer, and the response's buffer count
|
|
539
|
-
/// against `cred`'s memory until then.
|
|
696
|
+
/// `ConnectionLimitReached`.
|
|
540
697
|
pub(crate) fn start(
|
|
541
698
|
seam: Arc<dyn Outbound>,
|
|
542
699
|
request: OutgoingRequest,
|
|
543
|
-
connector_for: impl FnOnce(Arc<Place>) -> Connector,
|
|
700
|
+
connector_for: impl FnOnce(Arc<Place>) -> Result<Connector, HttpError>,
|
|
544
701
|
open_connections: &Arc<OpenConnections>,
|
|
545
|
-
cred: &Arc<Cred>,
|
|
546
702
|
) -> Result<Arc<Self>, HttpError> {
|
|
547
|
-
let room = request.room() + request.body.len() + MAX_READ_BUFFER + MAX_SOCKET_BUFFER;
|
|
548
|
-
let memory =
|
|
549
|
-
MemoryCharge::new(cred.memory_budget(), room).map_err(|_| HttpError::Internal)?;
|
|
550
703
|
let place = Arc::new(open(open_connections).ok_or(HttpError::ConnectionLimitReached)?);
|
|
551
|
-
let mut connector = connector_for(place.clone())
|
|
704
|
+
let mut connector = connector_for(place.clone())?;
|
|
552
705
|
let place = Some(place);
|
|
553
|
-
let reactor = Reactor::current().map_err(|_| HttpError::Internal)?;
|
|
554
706
|
let exchange = Arc::new(Self {
|
|
555
707
|
state: Arc::new(Mutex::new(State {
|
|
556
708
|
phase: Phase::Sending,
|
|
557
|
-
|
|
558
|
-
|
|
709
|
+
body: SkBuffHead::default(),
|
|
710
|
+
pending: None,
|
|
559
711
|
body_ended: false,
|
|
560
712
|
body_failed: false,
|
|
561
713
|
body_timed_out: false,
|
|
@@ -565,7 +717,6 @@ impl Exchange {
|
|
|
565
717
|
wait: Arc::default(),
|
|
566
718
|
task: Mutex::new(None),
|
|
567
719
|
place: Mutex::new(place),
|
|
568
|
-
memory: Mutex::new(Some(memory)),
|
|
569
720
|
timeouts: request.timeouts,
|
|
570
721
|
started: Instant::now(),
|
|
571
722
|
connected: connector.connected.clone(),
|
|
@@ -573,18 +724,13 @@ impl Exchange {
|
|
|
573
724
|
// The task holds what it answers into, never the exchange, so the
|
|
574
725
|
// exchange's last hold, which cancels the task, is never the task's.
|
|
575
726
|
let (state, wait) = (exchange.state.clone(), exchange.wait.clone());
|
|
576
|
-
let cred = cred.clone();
|
|
577
727
|
connector.wait = Some(wait.clone());
|
|
728
|
+
let budget = connector.poll_budget.clone();
|
|
729
|
+
let _ = request.body.exchange.set(Arc::downgrade(&exchange));
|
|
578
730
|
let sending = seam.send_request(request, connector);
|
|
579
|
-
let
|
|
731
|
+
let sent = async move {
|
|
580
732
|
match sending.await {
|
|
581
733
|
Ok(response) => {
|
|
582
|
-
let room = total_room_of(&response.head.headers);
|
|
583
|
-
let Ok(head_memory) = MemoryCharge::new(cred.memory_budget(), room) else {
|
|
584
|
-
lock(&state).phase = Phase::Failed(HttpError::Internal);
|
|
585
|
-
wait.wake_up();
|
|
586
|
-
return;
|
|
587
|
-
};
|
|
588
734
|
{
|
|
589
735
|
let mut answered = lock(&state);
|
|
590
736
|
// A head arriving past its timeout finds the exchange
|
|
@@ -592,7 +738,6 @@ impl Exchange {
|
|
|
592
738
|
if answered.phase != Phase::Sending {
|
|
593
739
|
return;
|
|
594
740
|
}
|
|
595
|
-
answered.head_memory = Some(head_memory);
|
|
596
741
|
answered.phase = Phase::Answered(response.head);
|
|
597
742
|
answered.last_part = Some(Instant::now());
|
|
598
743
|
}
|
|
@@ -604,14 +749,18 @@ impl Exchange {
|
|
|
604
749
|
wait.wake_up();
|
|
605
750
|
}
|
|
606
751
|
}
|
|
607
|
-
}
|
|
752
|
+
};
|
|
753
|
+
let task = Arc::new(Task::spending(sent, exchange.wait.clone(), budget));
|
|
608
754
|
*exchange.task.lock().unwrap_or_else(PoisonError::into_inner) = Some(task);
|
|
755
|
+
exchange.poll_task();
|
|
609
756
|
Ok(exchange)
|
|
610
757
|
}
|
|
611
758
|
|
|
612
|
-
/// The exchange's state,
|
|
613
|
-
///
|
|
759
|
+
/// The exchange's state, its request moved as far as it goes and any
|
|
760
|
+
/// timeout that passed having ended its wait, as a timeout read on its
|
|
761
|
+
/// next look rather than by a timer.
|
|
614
762
|
fn state(&self) -> MutexGuard<'_, State> {
|
|
763
|
+
self.poll_task();
|
|
615
764
|
let mut state = lock(&self.state);
|
|
616
765
|
if self.expire(&mut state) {
|
|
617
766
|
drop(state);
|
|
@@ -621,6 +770,20 @@ impl Exchange {
|
|
|
621
770
|
state
|
|
622
771
|
}
|
|
623
772
|
|
|
773
|
+
/// Move the request on, on the thread that looks at the exchange, as its
|
|
774
|
+
/// guest waits on or reads it; the task is let go of before it is polled,
|
|
775
|
+
/// so a cancel never waits on this lock.
|
|
776
|
+
fn poll_task(&self) {
|
|
777
|
+
let task = self
|
|
778
|
+
.task
|
|
779
|
+
.lock()
|
|
780
|
+
.unwrap_or_else(PoisonError::into_inner)
|
|
781
|
+
.clone();
|
|
782
|
+
if let Some(task) = task {
|
|
783
|
+
task.poll();
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
624
787
|
/// Drop the task sending the request, with the connection it holds.
|
|
625
788
|
fn cancel_task(&self) {
|
|
626
789
|
let task = self
|
|
@@ -721,10 +884,7 @@ impl Exchange {
|
|
|
721
884
|
_ => Err(Errno::WouldBlock),
|
|
722
885
|
};
|
|
723
886
|
}
|
|
724
|
-
let n =
|
|
725
|
-
for (slot, byte) in buf.iter_mut().zip(state.body.drain(..n)) {
|
|
726
|
-
*slot = byte;
|
|
727
|
-
}
|
|
887
|
+
let n = state.body.read_into(buf);
|
|
728
888
|
let filler = state.filler.take();
|
|
729
889
|
drop(state);
|
|
730
890
|
if let Some(filler) = filler {
|
|
@@ -734,13 +894,15 @@ impl Exchange {
|
|
|
734
894
|
}
|
|
735
895
|
|
|
736
896
|
/// Let the exchange go, dropping its task with the connection it holds
|
|
737
|
-
/// and the body's buffer. The head stays readable
|
|
738
|
-
///
|
|
897
|
+
/// and the body's buffer. The head stays readable while the guest keeps
|
|
898
|
+
/// the exchange.
|
|
739
899
|
pub fn release(&self) {
|
|
740
900
|
self.cancel_task();
|
|
741
|
-
lock(&self.state)
|
|
901
|
+
let mut state = lock(&self.state);
|
|
902
|
+
state.body.purge();
|
|
903
|
+
state.pending = None;
|
|
904
|
+
drop(state);
|
|
742
905
|
*self.place.lock().unwrap_or_else(PoisonError::into_inner) = None;
|
|
743
|
-
*self.memory.lock().unwrap_or_else(PoisonError::into_inner) = None;
|
|
744
906
|
}
|
|
745
907
|
}
|
|
746
908
|
|
|
@@ -796,40 +958,47 @@ fn lock(state: &Mutex<State>) -> MutexGuard<'_, State> {
|
|
|
796
958
|
state.lock().unwrap_or_else(PoisonError::into_inner)
|
|
797
959
|
}
|
|
798
960
|
|
|
799
|
-
/// Move `body` into the exchange's buffer
|
|
800
|
-
/// buffer, until the body ends or fails, or the exchange lets the task
|
|
801
|
-
///
|
|
961
|
+
/// Move `body` into the exchange's buffer frame by frame, never past one
|
|
962
|
+
/// socket buffer, until the body ends or fails, or the exchange lets the task
|
|
963
|
+
/// go. A frame is copied out of the seam as it is read, then waits until the
|
|
964
|
+
/// body has room for it whole, or goes in at once while the body is empty;
|
|
965
|
+
/// the task takes no further frame while one waits.
|
|
802
966
|
async fn fill_body(state: &Mutex<State>, wait: &WaitQueueHead, mut body: ResponseBody) {
|
|
803
|
-
let mut pending = Bytes::new();
|
|
804
967
|
loop {
|
|
805
|
-
|
|
806
|
-
match poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await {
|
|
807
|
-
Some(Ok(frame)) => {
|
|
808
|
-
pending = frame.into_data().unwrap_or_default();
|
|
809
|
-
continue;
|
|
810
|
-
}
|
|
811
|
-
Some(Err(_)) => lock(state).body_failed = true,
|
|
812
|
-
None => lock(state).body_ended = true,
|
|
813
|
-
}
|
|
814
|
-
wait.wake_up();
|
|
815
|
-
return;
|
|
816
|
-
}
|
|
817
|
-
let room = poll_fn(|cx| {
|
|
968
|
+
let moved = poll_fn(|cx| {
|
|
818
969
|
let mut state = lock(state);
|
|
819
|
-
let
|
|
820
|
-
|
|
821
|
-
|
|
970
|
+
if let Some(frame) = state.pending.take() {
|
|
971
|
+
if state.body.len() + frame.len() <= MAX_SOCKET_BUFFER || state.body.is_empty() {
|
|
972
|
+
state.body.push_buffer(frame);
|
|
973
|
+
state.last_part = Some(Instant::now());
|
|
974
|
+
return Poll::Ready(true);
|
|
975
|
+
}
|
|
976
|
+
state.pending = Some(frame);
|
|
977
|
+
} else if state.pending.is_none() {
|
|
978
|
+
return Poll::Ready(false);
|
|
822
979
|
}
|
|
823
980
|
state.filler = Some(cx.waker().clone());
|
|
824
981
|
Poll::Pending
|
|
825
982
|
})
|
|
826
983
|
.await;
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
984
|
+
if moved {
|
|
985
|
+
wait.wake_up();
|
|
986
|
+
continue;
|
|
987
|
+
}
|
|
988
|
+
match poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await {
|
|
989
|
+
Some(Ok(frame)) => {
|
|
990
|
+
let Ok(data) = frame.into_data() else {
|
|
991
|
+
continue;
|
|
992
|
+
};
|
|
993
|
+
let mut state = lock(state);
|
|
994
|
+
state.pending = Some(data.to_vec()).filter(|frame| !frame.is_empty());
|
|
995
|
+
continue;
|
|
996
|
+
}
|
|
997
|
+
Some(Err(_)) => lock(state).body_failed = true,
|
|
998
|
+
None => lock(state).body_ended = true,
|
|
999
|
+
}
|
|
832
1000
|
wait.wake_up();
|
|
1001
|
+
return;
|
|
833
1002
|
}
|
|
834
1003
|
}
|
|
835
1004
|
|
|
@@ -884,13 +1053,16 @@ impl Outbound for HyperOutbound {
|
|
|
884
1053
|
}
|
|
885
1054
|
|
|
886
1055
|
/// `request` as hyper sends it: the path with its query as the target, a
|
|
887
|
-
/// `host` header naming the authority, and each header
|
|
888
|
-
/// swapped in.
|
|
889
|
-
|
|
1056
|
+
/// `host` header naming the authority, the `close` option, and each header
|
|
1057
|
+
/// with its credentials swapped in. The seam reuses no connection, and says
|
|
1058
|
+
/// so as RFC 9112 § 9.3 asks, so a server runs nothing a body hid behind the
|
|
1059
|
+
/// request the rules judged.
|
|
1060
|
+
fn to_hyper_request(request: OutgoingRequest) -> Result<hyper::Request<StreamedBody>, HttpError> {
|
|
890
1061
|
let mut builder = hyper::Request::builder()
|
|
891
1062
|
.method(request.method.as_str())
|
|
892
1063
|
.uri(request.path_with_query.as_str())
|
|
893
|
-
.header("host", request.authority.as_str())
|
|
1064
|
+
.header("host", request.authority.as_str())
|
|
1065
|
+
.header("connection", "close");
|
|
894
1066
|
for (name, value) in &request.headers {
|
|
895
1067
|
let value = request
|
|
896
1068
|
.swaps
|
|
@@ -898,19 +1070,23 @@ fn to_hyper_request(request: OutgoingRequest) -> Result<hyper::Request<Full<Byte
|
|
|
898
1070
|
.fold(value.clone(), |value, swap| swap.apply(name, &value));
|
|
899
1071
|
builder = builder.header(name.as_str(), value);
|
|
900
1072
|
}
|
|
1073
|
+
// A body still streaming is chunked whatever the method, so hyper never
|
|
1074
|
+
// takes a GET's for empty and leaves what the guest writes unsent.
|
|
1075
|
+
if !request.body.is_finished() {
|
|
1076
|
+
builder = builder.header("transfer-encoding", "chunked");
|
|
1077
|
+
}
|
|
901
1078
|
builder
|
|
902
|
-
.body(
|
|
1079
|
+
.body(StreamedBody(request.body))
|
|
903
1080
|
.map_err(|_| HttpError::ProtocolError)
|
|
904
1081
|
}
|
|
905
1082
|
|
|
906
1083
|
/// Send `request` over `wire` as HTTP/1, driving the connection beside it, and
|
|
907
1084
|
/// answer its response, whose body drives the connection on until it ends.
|
|
908
|
-
async fn send_over<T>(
|
|
909
|
-
wire: Wire<T>,
|
|
910
|
-
request: hyper::Request<Full<Bytes>>,
|
|
911
|
-
) -> Result<Response, HttpError>
|
|
1085
|
+
async fn send_over<T, B>(wire: Wire<T>, request: hyper::Request<B>) -> Result<Response, HttpError>
|
|
912
1086
|
where
|
|
913
1087
|
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
|
|
1088
|
+
B: Body<Data = Bytes> + Send + 'static,
|
|
1089
|
+
B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
|
|
914
1090
|
{
|
|
915
1091
|
let (mut sender, connection) = hyper::client::conn::http1::Builder::new()
|
|
916
1092
|
.max_buf_size(MAX_READ_BUFFER)
|
|
@@ -979,9 +1155,19 @@ impl Body for DrivenBody {
|
|
|
979
1155
|
}
|
|
980
1156
|
|
|
981
1157
|
/// A connection, plain or under TLS, as hyper reads and writes it.
|
|
982
|
-
struct Wire<T>(T);
|
|
1158
|
+
struct Wire<T: AsyncWrite + Unpin>(T);
|
|
983
1159
|
|
|
984
|
-
|
|
1160
|
+
/// A connection let go shuts down first, however far its exchange got, so TLS
|
|
1161
|
+
/// sends the closure alert RFC 8446 § 6.1 asks before a close. It waits for
|
|
1162
|
+
/// no answer, as CRuby's `SSLSocket#sysclose` waits for none.
|
|
1163
|
+
impl<T: AsyncWrite + Unpin> Drop for Wire<T> {
|
|
1164
|
+
fn drop(&mut self) {
|
|
1165
|
+
let mut cx = Context::from_waker(Waker::noop());
|
|
1166
|
+
let _ = Pin::new(&mut self.0).poll_shutdown(&mut cx);
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
impl<T: AsyncRead + AsyncWrite + Unpin> hyper::rt::Read for Wire<T> {
|
|
985
1171
|
fn poll_read(
|
|
986
1172
|
self: Pin<&mut Self>,
|
|
987
1173
|
cx: &mut Context<'_>,
|
|
@@ -1023,8 +1209,8 @@ impl HttpError {
|
|
|
1023
1209
|
/// The code a failed TLS handshake answers, as wasmtime-wasi-http's
|
|
1024
1210
|
/// `p2_error_from_tls` names each: the rustls error it carries, a
|
|
1025
1211
|
/// connection the server ended as `connection-terminated`, and any other
|
|
1026
|
-
/// as `TLS-protocol-error`;
|
|
1027
|
-
///
|
|
1212
|
+
/// as `TLS-protocol-error`; a failure for want of memory is the seam's own
|
|
1213
|
+
/// failure.
|
|
1028
1214
|
pub(crate) fn from_tls(err: &io::Error) -> Self {
|
|
1029
1215
|
match err
|
|
1030
1216
|
.get_ref()
|
|
@@ -1044,8 +1230,8 @@ impl HttpError {
|
|
|
1044
1230
|
}
|
|
1045
1231
|
|
|
1046
1232
|
/// The code an open connection failing with `err` answers: one the peer or
|
|
1047
|
-
/// the Invocation's end cut as `connection-terminated`, and
|
|
1048
|
-
///
|
|
1233
|
+
/// the Invocation's end cut as `connection-terminated`, and a failure for
|
|
1234
|
+
/// want of memory as the seam's own; `None` for a
|
|
1049
1235
|
/// failure the protocol over it names.
|
|
1050
1236
|
fn from_open_connection(err: &Errno) -> Option<Self> {
|
|
1051
1237
|
match err {
|
|
@@ -1058,8 +1244,7 @@ impl HttpError {
|
|
|
1058
1244
|
}
|
|
1059
1245
|
|
|
1060
1246
|
/// The code a connection failing with `err` answers, as wasmtime-wasi-http
|
|
1061
|
-
/// names each;
|
|
1062
|
-
/// failure.
|
|
1247
|
+
/// names each; a failure for want of memory is the seam's own failure.
|
|
1063
1248
|
pub(crate) fn from_errno(err: &Errno) -> Self {
|
|
1064
1249
|
match err {
|
|
1065
1250
|
Errno::OutOfMemory => Self::Internal,
|
|
@@ -1078,6 +1263,11 @@ impl HttpError {
|
|
|
1078
1263
|
/// answers as an open connection's failure does, as the TLS handshake's
|
|
1079
1264
|
/// does, so a failure answers one code wherever in the exchange it lands.
|
|
1080
1265
|
fn from_hyper(err: &hyper::Error) -> Self {
|
|
1266
|
+
if let Some(BodyFailed(code)) =
|
|
1267
|
+
std::error::Error::source(err).and_then(|source| source.downcast_ref::<BodyFailed>())
|
|
1268
|
+
{
|
|
1269
|
+
return *code;
|
|
1270
|
+
}
|
|
1081
1271
|
let failed = std::error::Error::source(err)
|
|
1082
1272
|
.and_then(|source| source.downcast_ref::<io::Error>())
|
|
1083
1273
|
.and_then(io::Error::get_ref)
|
|
@@ -1102,6 +1292,7 @@ impl HttpError {
|
|
|
1102
1292
|
mod tests {
|
|
1103
1293
|
use std::io::{BufRead, BufReader, Read, Write};
|
|
1104
1294
|
use std::net::TcpListener;
|
|
1295
|
+
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
|
1105
1296
|
use std::thread;
|
|
1106
1297
|
use std::time::Duration;
|
|
1107
1298
|
|
|
@@ -1238,6 +1429,22 @@ mod tests {
|
|
|
1238
1429
|
Namespace::for_network(&network, Arc::new(HostInet), Arc::new(HyperOutbound::new()))
|
|
1239
1430
|
}
|
|
1240
1431
|
|
|
1432
|
+
/// A namespace whose one entry holds `endpoints`, over a host that counts
|
|
1433
|
+
/// each dial it is asked for, so a request sending nothing dials nothing.
|
|
1434
|
+
fn counting_namespace(endpoints: Vec<Endpoint>) -> (Namespace, Arc<CountsDials>) {
|
|
1435
|
+
let mut entry = Builder::default();
|
|
1436
|
+
endpoints.into_iter().for_each(|endpoint| {
|
|
1437
|
+
entry.endpoint(endpoint);
|
|
1438
|
+
});
|
|
1439
|
+
let network = Network::new("web", Arc::new(entry)).unwrap();
|
|
1440
|
+
let family = Arc::new(CountsDials::default());
|
|
1441
|
+
let outbound = Arc::new(HyperOutbound::new());
|
|
1442
|
+
(
|
|
1443
|
+
Namespace::for_network(&network, family.clone(), outbound),
|
|
1444
|
+
family,
|
|
1445
|
+
)
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1241
1448
|
fn greeting_request(authority: &str) -> OutgoingRequest {
|
|
1242
1449
|
let mut request = OutgoingRequest::new("GET", Scheme::Http, authority);
|
|
1243
1450
|
request.path_with_query = "/greeting?lang=en".to_string();
|
|
@@ -1246,22 +1453,29 @@ mod tests {
|
|
|
1246
1453
|
|
|
1247
1454
|
/// The exchange's head, then its whole body.
|
|
1248
1455
|
fn read_response(exchange: &Exchange) -> Result<(ResponseHead, Vec<u8>), HttpError> {
|
|
1249
|
-
let head =
|
|
1250
|
-
match exchange.response() {
|
|
1251
|
-
Some(answer) => break answer?,
|
|
1252
|
-
None => thread::sleep(Duration::from_millis(1)),
|
|
1253
|
-
}
|
|
1254
|
-
};
|
|
1456
|
+
let head = settled(exchange)?;
|
|
1255
1457
|
let mut body = Vec::new();
|
|
1256
1458
|
let mut buf = [0; 64];
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1459
|
+
let mut ended = None;
|
|
1460
|
+
crate::sched::testing::wait_until(
|
|
1461
|
+
"the response's body ending, so its server never closed it or its read never woke",
|
|
1462
|
+
|| match exchange.read(&mut buf) {
|
|
1463
|
+
Ok(0) => {
|
|
1464
|
+
ended = Some(Ok(()));
|
|
1465
|
+
true
|
|
1466
|
+
}
|
|
1467
|
+
Ok(n) => {
|
|
1468
|
+
body.extend_from_slice(&buf[..n]);
|
|
1469
|
+
false
|
|
1470
|
+
}
|
|
1471
|
+
Err(Errno::WouldBlock) => false,
|
|
1472
|
+
Err(_) => {
|
|
1473
|
+
ended = Some(Err(HttpError::ConnectionTerminated));
|
|
1474
|
+
true
|
|
1475
|
+
}
|
|
1476
|
+
},
|
|
1477
|
+
);
|
|
1478
|
+
ended.expect("the body ended").map(|()| (head, body))
|
|
1265
1479
|
}
|
|
1266
1480
|
|
|
1267
1481
|
// @behavior NW-225
|
|
@@ -1307,12 +1521,7 @@ mod tests {
|
|
|
1307
1521
|
request.path_with_query = "/".to_string();
|
|
1308
1522
|
let exchange =
|
|
1309
1523
|
crate::net::send(&namespace, &cred, request).expect("the endpoint admits it");
|
|
1310
|
-
let answer =
|
|
1311
|
-
match exchange.response() {
|
|
1312
|
-
Some(answer) => break answer,
|
|
1313
|
-
None => thread::sleep(Duration::from_millis(1)),
|
|
1314
|
-
}
|
|
1315
|
-
};
|
|
1524
|
+
let answer = settled(&exchange);
|
|
1316
1525
|
assert_eq!(
|
|
1317
1526
|
(answer.err(), family.dials()),
|
|
1318
1527
|
(Some(HttpError::TlsProtocol), 0),
|
|
@@ -1358,7 +1567,7 @@ mod tests {
|
|
|
1358
1567
|
// Linux sizes a send buffer as the connection opens, from its
|
|
1359
1568
|
// MSS, up to `tcp_wmem`'s default most of 4 MiB, so a body past
|
|
1360
1569
|
// that always leaves bytes in the upstream's queue.
|
|
1361
|
-
request.body = vec![b'b'; 8 * 1024 * 1024];
|
|
1570
|
+
request.body = RequestBody::finished(&vec![b'b'; 8 * 1024 * 1024]);
|
|
1362
1571
|
let exchange =
|
|
1363
1572
|
crate::net::send(&namespace, &cred, request).expect("the endpoint admits it");
|
|
1364
1573
|
// The peer accepts and never reads, so the request's bytes stay queued.
|
|
@@ -1369,27 +1578,22 @@ mod tests {
|
|
|
1369
1578
|
for upstream in &upstreams {
|
|
1370
1579
|
upstream.lock_host_send_buffer(4096);
|
|
1371
1580
|
}
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1581
|
+
// Each look moves the request on, as its guest's poll does.
|
|
1582
|
+
crate::sched::testing::wait_until(
|
|
1583
|
+
"the request's body queueing on its upstream",
|
|
1584
|
+
|| {
|
|
1585
|
+
exchange.response().is_some()
|
|
1586
|
+
|| upstreams.iter().any(|upstream| !upstream.is_drained())
|
|
1587
|
+
},
|
|
1588
|
+
);
|
|
1380
1589
|
exchange.release();
|
|
1381
1590
|
let while_sending =
|
|
1382
1591
|
crate::net::send(&namespace, &cred, greeting_request(&authority)).err();
|
|
1383
1592
|
let still_sending = upstreams.iter().any(|upstream| !upstream.is_drained());
|
|
1384
1593
|
drop(peer);
|
|
1385
|
-
let
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
Ok(_) => break true,
|
|
1389
|
-
Err(_) if Instant::now() < deadline => thread::sleep(Duration::from_millis(1)),
|
|
1390
|
-
Err(_) => break false,
|
|
1391
|
-
}
|
|
1392
|
-
};
|
|
1594
|
+
let once_closed = crate::sched::testing::holds_within_max_wait(|| {
|
|
1595
|
+
crate::net::send(&namespace, &cred, greeting_request(&authority)).is_ok()
|
|
1596
|
+
});
|
|
1393
1597
|
still_sending.then_some((while_sending, once_closed))
|
|
1394
1598
|
};
|
|
1395
1599
|
assert_eq!(
|
|
@@ -1437,7 +1641,8 @@ mod tests {
|
|
|
1437
1641
|
let cred = prepare_creds(&[], None);
|
|
1438
1642
|
let exchange = crate::net::send(&namespace, &cred, greeting_request("api.example.com"))
|
|
1439
1643
|
.expect("the endpoint admits it");
|
|
1440
|
-
|
|
1644
|
+
// The send polls its request once before it answers, so a lookup that
|
|
1645
|
+
// starts on its thread is recorded by now.
|
|
1441
1646
|
let started_on = family.0.lock().unwrap().clone();
|
|
1442
1647
|
exchange.release();
|
|
1443
1648
|
assert_eq!(
|
|
@@ -1502,8 +1707,7 @@ mod tests {
|
|
|
1502
1707
|
.expect("the endpoints compile");
|
|
1503
1708
|
let cred = prepare_creds(&[], None);
|
|
1504
1709
|
let connect = || {
|
|
1505
|
-
let sock =
|
|
1506
|
-
crate::net::TcpSock::create(&namespace, &cred, crate::net::AddressFamily::Inet)?;
|
|
1710
|
+
let sock = crate::net::TcpSock::create(&namespace, crate::net::AddressFamily::Inet)?;
|
|
1507
1711
|
let addr = "127.0.0.1:4567".parse().ok();
|
|
1508
1712
|
crate::net::sys_connect(&namespace, &cred, sock.as_ref(), addr)
|
|
1509
1713
|
};
|
|
@@ -1513,16 +1717,11 @@ mod tests {
|
|
|
1513
1717
|
.expect("the guest's lookup reaches the resolver");
|
|
1514
1718
|
let past_lookup = connect().err();
|
|
1515
1719
|
drop(lookup);
|
|
1516
|
-
let
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
thread::sleep(Duration::from_millis(1))
|
|
1522
|
-
}
|
|
1523
|
-
Err(err) => panic!("the lookup's place never came back: {err:?}"),
|
|
1524
|
-
}
|
|
1525
|
-
};
|
|
1720
|
+
let mut request = None;
|
|
1721
|
+
crate::sched::testing::wait_until("the lookup's place coming back", || {
|
|
1722
|
+
request = crate::net::send(&namespace, &cred, greeting_request("api.example.com")).ok();
|
|
1723
|
+
request.is_some()
|
|
1724
|
+
});
|
|
1526
1725
|
resolving
|
|
1527
1726
|
.recv_timeout(Duration::from_secs(5))
|
|
1528
1727
|
.expect("the request's lookup reaches the resolver");
|
|
@@ -1555,32 +1754,23 @@ mod tests {
|
|
|
1555
1754
|
let network = Network::new("web", Arc::new(entry)).unwrap();
|
|
1556
1755
|
let namespace =
|
|
1557
1756
|
Namespace::for_network(&network, Arc::new(HostInet), Arc::new(HyperOutbound::new()));
|
|
1558
|
-
let
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
};
|
|
1565
|
-
let request = || greeting_request(&format!("localhost:{port}"));
|
|
1566
|
-
let cramped = crate::net::send(
|
|
1757
|
+
let cred = crate::security::restrict_self(
|
|
1758
|
+
&prepare_creds(&[], None),
|
|
1759
|
+
[&crate::grant::Grant::Network(network.clone())],
|
|
1760
|
+
)
|
|
1761
|
+
.expect("every Mount stands");
|
|
1762
|
+
let exchange = crate::net::send(
|
|
1567
1763
|
&namespace,
|
|
1568
|
-
&
|
|
1569
|
-
|
|
1764
|
+
&cred,
|
|
1765
|
+
greeting_request(&format!("localhost:{port}")),
|
|
1570
1766
|
)
|
|
1571
|
-
.
|
|
1572
|
-
let
|
|
1573
|
-
.map(|exchange| read_response(&exchange).map(|(head, _)| head.status));
|
|
1767
|
+
.expect("an endpoint names the authority");
|
|
1768
|
+
let status = read_response(&exchange).map(|(head, _)| head.status);
|
|
1574
1769
|
assert_eq!(
|
|
1575
|
-
(
|
|
1576
|
-
(
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
vec!["localhost".to_string(), "localhost".to_string()]
|
|
1580
|
-
),
|
|
1581
|
-
"a guest's request must fail before it reaches the server when the Invocation's \
|
|
1582
|
-
memory cannot hold its upstream socket's buffers, reach it with room, and show the \
|
|
1583
|
-
connect policy only the host the guest named, never an address it resolved to"
|
|
1770
|
+
(status, seen.lock().unwrap().clone()),
|
|
1771
|
+
(Ok(200), vec!["localhost".to_string()]),
|
|
1772
|
+
"a guest's request must reach the server, and show the connect policy only the host \
|
|
1773
|
+
the guest named, never an address it resolved to"
|
|
1584
1774
|
);
|
|
1585
1775
|
server.join().unwrap();
|
|
1586
1776
|
}
|
|
@@ -1613,6 +1803,171 @@ mod tests {
|
|
|
1613
1803
|
);
|
|
1614
1804
|
}
|
|
1615
1805
|
|
|
1806
|
+
/// A loopback server that reads no request body, answering each head it
|
|
1807
|
+
/// reads with `hello` until one asks it to close, which it honours in
|
|
1808
|
+
/// stages as RFC 9112 § 9.6 has a server close; it hands back the heads.
|
|
1809
|
+
fn serve_ignoring_bodies() -> (u16, thread::JoinHandle<Vec<Vec<String>>>) {
|
|
1810
|
+
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
1811
|
+
let port = listener.local_addr().unwrap().port();
|
|
1812
|
+
let server = thread::spawn(move || {
|
|
1813
|
+
let (stream, _) = listener.accept().unwrap();
|
|
1814
|
+
stream
|
|
1815
|
+
.set_read_timeout(Some(Duration::from_secs(5)))
|
|
1816
|
+
.unwrap();
|
|
1817
|
+
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
|
1818
|
+
let mut heads = Vec::new();
|
|
1819
|
+
loop {
|
|
1820
|
+
let mut head = Vec::new();
|
|
1821
|
+
let mut line = String::new();
|
|
1822
|
+
while matches!(reader.read_line(&mut line), Ok(read) if read > 0) {
|
|
1823
|
+
if line.trim_end().is_empty() {
|
|
1824
|
+
break;
|
|
1825
|
+
}
|
|
1826
|
+
head.push(line.trim_end().to_string());
|
|
1827
|
+
line.clear();
|
|
1828
|
+
}
|
|
1829
|
+
if head.is_empty() {
|
|
1830
|
+
return heads;
|
|
1831
|
+
}
|
|
1832
|
+
let closes = head
|
|
1833
|
+
.iter()
|
|
1834
|
+
.any(|line| line.eq_ignore_ascii_case("connection: close"));
|
|
1835
|
+
heads.push(head);
|
|
1836
|
+
let _ = (&stream).write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nhello");
|
|
1837
|
+
if closes {
|
|
1838
|
+
let _ = stream.shutdown(std::net::Shutdown::Write);
|
|
1839
|
+
let _ = io::copy(&mut reader, &mut io::sink());
|
|
1840
|
+
return heads;
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
});
|
|
1844
|
+
(port, server)
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
// @behavior NW-241
|
|
1848
|
+
#[test]
|
|
1849
|
+
fn a_request_declares_that_its_connection_carries_no_other() {
|
|
1850
|
+
let bodies = [
|
|
1851
|
+
b"GET /behind HTTP/1.1\r\nhost: api.example.com\r\n\r\n".to_vec(),
|
|
1852
|
+
vec![b'b'; 1 << 20],
|
|
1853
|
+
];
|
|
1854
|
+
let answers = bodies.map(|body| {
|
|
1855
|
+
let (port, server) = serve_ignoring_bodies();
|
|
1856
|
+
let namespace = namespace(vec![Endpoint::new("127.0.0.1", port)
|
|
1857
|
+
.unwrap()
|
|
1858
|
+
.with_addresses(vec![crate::network::Addresses::Local])]);
|
|
1859
|
+
let mut request = greeting_request(&format!("127.0.0.1:{port}"));
|
|
1860
|
+
request.body = RequestBody::finished(&body);
|
|
1861
|
+
let exchange = crate::net::send(&namespace, &prepare_creds(&[], None), request)
|
|
1862
|
+
.expect("the endpoint names the authority");
|
|
1863
|
+
let read = read_response(&exchange).map(|(head, body)| (head.status, body));
|
|
1864
|
+
exchange.release();
|
|
1865
|
+
let heads = server.join().unwrap();
|
|
1866
|
+
let declarations = heads[0]
|
|
1867
|
+
.iter()
|
|
1868
|
+
.filter(|line| line.eq_ignore_ascii_case("connection: close"))
|
|
1869
|
+
.count();
|
|
1870
|
+
(read, declarations, heads.len())
|
|
1871
|
+
});
|
|
1872
|
+
let expected = (Ok((200, b"hello".to_vec())), 1, 1);
|
|
1873
|
+
assert_eq!(
|
|
1874
|
+
answers,
|
|
1875
|
+
[expected.clone(), expected],
|
|
1876
|
+
"a request to a server reading no body must carry connection: close once, have \
|
|
1877
|
+
nothing behind it run, and read the response whole, its body spelling another \
|
|
1878
|
+
request or past the socket's buffers alike"
|
|
1879
|
+
);
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
/// A wire answering `response` once a request's head was written, then
|
|
1883
|
+
/// silent as an open connection is, recording whether it was shut down,
|
|
1884
|
+
/// which is where TLS sends its closure alert.
|
|
1885
|
+
struct RecordsShutdown {
|
|
1886
|
+
response: &'static [u8],
|
|
1887
|
+
written: bool,
|
|
1888
|
+
shut_down: Arc<AtomicBool>,
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
impl AsyncRead for RecordsShutdown {
|
|
1892
|
+
fn poll_read(
|
|
1893
|
+
self: Pin<&mut Self>,
|
|
1894
|
+
_cx: &mut Context<'_>,
|
|
1895
|
+
buf: &mut ReadBuf<'_>,
|
|
1896
|
+
) -> Poll<io::Result<()>> {
|
|
1897
|
+
let this = self.get_mut();
|
|
1898
|
+
if !this.written || this.response.is_empty() {
|
|
1899
|
+
return Poll::Pending;
|
|
1900
|
+
}
|
|
1901
|
+
let n = this.response.len().min(buf.remaining());
|
|
1902
|
+
buf.put_slice(&this.response[..n]);
|
|
1903
|
+
this.response = &this.response[n..];
|
|
1904
|
+
Poll::Ready(Ok(()))
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
impl AsyncWrite for RecordsShutdown {
|
|
1909
|
+
fn poll_write(
|
|
1910
|
+
self: Pin<&mut Self>,
|
|
1911
|
+
_cx: &mut Context<'_>,
|
|
1912
|
+
buf: &[u8],
|
|
1913
|
+
) -> Poll<io::Result<usize>> {
|
|
1914
|
+
self.get_mut().written = true;
|
|
1915
|
+
Poll::Ready(Ok(buf.len()))
|
|
1916
|
+
}
|
|
1917
|
+
|
|
1918
|
+
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
1919
|
+
Poll::Ready(Ok(()))
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
1923
|
+
self.shut_down.store(true, Ordering::SeqCst);
|
|
1924
|
+
Poll::Ready(Ok(()))
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
|
|
1928
|
+
// @behavior NW-240
|
|
1929
|
+
#[test]
|
|
1930
|
+
fn an_exchange_let_go_shuts_its_connection_down() {
|
|
1931
|
+
let responses: [&'static [u8]; 3] = [
|
|
1932
|
+
b"",
|
|
1933
|
+
b"HTTP/1.1 200 OK\r\ncontent-length: 100\r\n\r\nhello",
|
|
1934
|
+
b"HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nhello",
|
|
1935
|
+
];
|
|
1936
|
+
let shut_down = responses.map(|response| {
|
|
1937
|
+
let shut_down = Arc::new(AtomicBool::new(false));
|
|
1938
|
+
let wire = RecordsShutdown {
|
|
1939
|
+
response,
|
|
1940
|
+
written: false,
|
|
1941
|
+
shut_down: shut_down.clone(),
|
|
1942
|
+
};
|
|
1943
|
+
let request = to_hyper_request(greeting_request("api.example.com"))
|
|
1944
|
+
.expect("the request's headers are valid");
|
|
1945
|
+
let mut exchange = Box::pin(async move {
|
|
1946
|
+
let mut body = send_over(Wire(wire), request).await?.body;
|
|
1947
|
+
while poll_fn(|cx| Pin::new(&mut body).poll_frame(cx))
|
|
1948
|
+
.await
|
|
1949
|
+
.is_some()
|
|
1950
|
+
{}
|
|
1951
|
+
Ok::<_, HttpError>(())
|
|
1952
|
+
});
|
|
1953
|
+
let mut cx = Context::from_waker(Waker::noop());
|
|
1954
|
+
// The wire is ready at once, so a few polls take the exchange as
|
|
1955
|
+
// far as its response lets it go.
|
|
1956
|
+
for _ in 0..16 {
|
|
1957
|
+
if exchange.as_mut().poll(&mut cx).is_ready() {
|
|
1958
|
+
break;
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
drop(exchange);
|
|
1962
|
+
shut_down.load(Ordering::SeqCst)
|
|
1963
|
+
});
|
|
1964
|
+
assert_eq!(
|
|
1965
|
+
shut_down, [true; 3],
|
|
1966
|
+
"an HTTP exchange let go before its response, midway through its body, or after its \
|
|
1967
|
+
end must shut its connection down before closing it, so TLS sends its closure alert"
|
|
1968
|
+
);
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1616
1971
|
/// A seam recording the authority each request it is handed names, and
|
|
1617
1972
|
/// answering none.
|
|
1618
1973
|
#[derive(Default)]
|
|
@@ -1694,19 +2049,10 @@ mod tests {
|
|
|
1694
2049
|
greeting_request(&format!("127.0.0.1:{port}")),
|
|
1695
2050
|
)
|
|
1696
2051
|
.expect("the endpoint names the authority");
|
|
1697
|
-
let tight = prepare_creds(&[], Some(MAX_READ_BUFFER + MAX_SOCKET_BUFFER));
|
|
1698
|
-
let unheld = crate::net::send(
|
|
1699
|
-
&namespace,
|
|
1700
|
-
&tight,
|
|
1701
|
-
greeting_request(&format!("127.0.0.1:{port}")),
|
|
1702
|
-
)
|
|
1703
|
-
.err();
|
|
1704
2052
|
assert_eq!(
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
"a response whose head runs past 128 KiB must answer a protocol error
|
|
1708
|
-
whose Invocation cannot hold the seam's read buffer beside the request must fail \
|
|
1709
|
-
before it is sent"
|
|
2053
|
+
read_response(&answer).err(),
|
|
2054
|
+
Some(HttpError::ProtocolError),
|
|
2055
|
+
"a response whose head runs past 128 KiB must answer a protocol error"
|
|
1710
2056
|
);
|
|
1711
2057
|
server.join().unwrap();
|
|
1712
2058
|
}
|
|
@@ -1890,13 +2236,11 @@ mod tests {
|
|
|
1890
2236
|
// @behavior NW-038
|
|
1891
2237
|
#[test]
|
|
1892
2238
|
fn a_request_no_http_endpoint_names_is_denied_unsent() {
|
|
1893
|
-
let
|
|
1894
|
-
listener.set_nonblocking(true).unwrap();
|
|
1895
|
-
let port = listener.local_addr().unwrap().port();
|
|
2239
|
+
let port = 8080;
|
|
1896
2240
|
let raw = Endpoint::new("127.0.0.1", port)
|
|
1897
2241
|
.unwrap()
|
|
1898
2242
|
.with_protocol(Protocol::Tcp);
|
|
1899
|
-
let namespace =
|
|
2243
|
+
let (namespace, family) = counting_namespace(vec![raw]);
|
|
1900
2244
|
let cred = prepare_creds(&[], None);
|
|
1901
2245
|
let answers = [
|
|
1902
2246
|
format!("127.0.0.1:{port}"),
|
|
@@ -1904,12 +2248,11 @@ mod tests {
|
|
|
1904
2248
|
format!("198.18.0.0:{port}"),
|
|
1905
2249
|
]
|
|
1906
2250
|
.map(|authority| crate::net::send(&namespace, &cred, greeting_request(&authority)).err());
|
|
1907
|
-
thread::sleep(Duration::from_millis(20));
|
|
1908
2251
|
assert!(
|
|
1909
2252
|
answers
|
|
1910
2253
|
.iter()
|
|
1911
2254
|
.all(|answer| *answer == Some(HttpError::Denied))
|
|
1912
|
-
&&
|
|
2255
|
+
&& family.dials() == 0,
|
|
1913
2256
|
"a guest's request to an authority only a tcp endpoint names, one no endpoint names, \
|
|
1914
2257
|
or a virtual address must answer Denied, sending nothing, got {answers:?}"
|
|
1915
2258
|
);
|
|
@@ -1918,22 +2261,20 @@ mod tests {
|
|
|
1918
2261
|
// @behavior NW-041
|
|
1919
2262
|
#[test]
|
|
1920
2263
|
fn a_request_carrying_a_header_the_seam_frames_is_refused_unsent() {
|
|
1921
|
-
let
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
let namespace = namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
|
|
2264
|
+
let port = 8080;
|
|
2265
|
+
let (namespace, family) =
|
|
2266
|
+
counting_namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
|
|
1925
2267
|
let cred = prepare_creds(&[], None);
|
|
1926
2268
|
let answers = ["Host", "content-length", "bad name"].map(|name| {
|
|
1927
2269
|
let mut request = greeting_request(&format!("127.0.0.1:{port}"));
|
|
1928
2270
|
request.headers.push((name.to_string(), b"x".to_vec()));
|
|
1929
2271
|
crate::net::send(&namespace, &cred, request).err()
|
|
1930
2272
|
});
|
|
1931
|
-
thread::sleep(Duration::from_millis(20));
|
|
1932
2273
|
assert!(
|
|
1933
2274
|
answers
|
|
1934
2275
|
.iter()
|
|
1935
2276
|
.all(|answer| *answer == Some(HttpError::Denied))
|
|
1936
|
-
&&
|
|
2277
|
+
&& family.dials() == 0,
|
|
1937
2278
|
"a guest's request carrying host, content-length, or a name that is no \
|
|
1938
2279
|
token must answer Denied, sending nothing, got {answers:?}"
|
|
1939
2280
|
);
|
|
@@ -1942,22 +2283,20 @@ mod tests {
|
|
|
1942
2283
|
// @behavior NW-184
|
|
1943
2284
|
#[test]
|
|
1944
2285
|
fn a_request_whose_target_is_not_in_origin_form_is_refused_unsent() {
|
|
1945
|
-
let
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
let namespace = namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
|
|
2286
|
+
let port = 8080;
|
|
2287
|
+
let (namespace, family) =
|
|
2288
|
+
counting_namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
|
|
1949
2289
|
let cred = prepare_creds(&[], None);
|
|
1950
2290
|
let answers = ["http://other.example/x", "*", "", "/a#b"].map(|target| {
|
|
1951
2291
|
let mut request = greeting_request(&format!("127.0.0.1:{port}"));
|
|
1952
2292
|
request.path_with_query = target.to_string();
|
|
1953
2293
|
crate::net::send(&namespace, &cred, request).err()
|
|
1954
2294
|
});
|
|
1955
|
-
thread::sleep(Duration::from_millis(20));
|
|
1956
2295
|
assert!(
|
|
1957
2296
|
answers
|
|
1958
2297
|
.iter()
|
|
1959
2298
|
.all(|answer| *answer == Some(HttpError::Denied))
|
|
1960
|
-
&&
|
|
2299
|
+
&& family.dials() == 0,
|
|
1961
2300
|
"a guest's request whose target is absolute-form, asterisk-form, empty, or \
|
|
1962
2301
|
carries a fragment must answer Denied, sending nothing, got {answers:?}"
|
|
1963
2302
|
);
|
|
@@ -1966,27 +2305,133 @@ mod tests {
|
|
|
1966
2305
|
// @behavior NW-219
|
|
1967
2306
|
#[test]
|
|
1968
2307
|
fn a_request_whose_method_is_not_a_token_is_refused_unsent() {
|
|
1969
|
-
let
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
let namespace = namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
|
|
2308
|
+
let port = 8080;
|
|
2309
|
+
let (namespace, family) =
|
|
2310
|
+
counting_namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
|
|
1973
2311
|
let cred = prepare_creds(&[], None);
|
|
1974
2312
|
let answers = ["", "GET X"].map(|method| {
|
|
1975
2313
|
let mut request = greeting_request(&format!("127.0.0.1:{port}"));
|
|
1976
2314
|
request.method = method.to_string();
|
|
1977
2315
|
crate::net::send(&namespace, &cred, request).err()
|
|
1978
2316
|
});
|
|
1979
|
-
thread::sleep(Duration::from_millis(20));
|
|
1980
2317
|
assert!(
|
|
1981
2318
|
answers
|
|
1982
2319
|
.iter()
|
|
1983
2320
|
.all(|answer| *answer == Some(HttpError::Denied))
|
|
1984
|
-
&&
|
|
2321
|
+
&& family.dials() == 0,
|
|
1985
2322
|
"a guest's request whose method is empty or holds a space must answer Denied, \
|
|
1986
2323
|
sending nothing, got {answers:?}"
|
|
1987
2324
|
);
|
|
1988
2325
|
}
|
|
1989
2326
|
|
|
2327
|
+
/// A bearer credential swapping `kobako-token` for `s3cret`, its source
|
|
2328
|
+
/// counting into `asked` each time it is asked.
|
|
2329
|
+
fn bearer_credential(asked: &Arc<AtomicUsize>) -> crate::network::Credential {
|
|
2330
|
+
let asked = asked.clone();
|
|
2331
|
+
crate::network::Credential::new(
|
|
2332
|
+
crate::network::Placement::Bearer,
|
|
2333
|
+
"kobako-token",
|
|
2334
|
+
Arc::new(move |_: &crate::network::Request<'_>| {
|
|
2335
|
+
asked.fetch_add(1, Ordering::SeqCst);
|
|
2336
|
+
Ok(Some(crate::network::Secret::new("s3cret")))
|
|
2337
|
+
}),
|
|
2338
|
+
)
|
|
2339
|
+
}
|
|
2340
|
+
|
|
2341
|
+
/// A namespace whose one endpoint, `api.example.com` at 443 with no
|
|
2342
|
+
/// rules, binds a bearer credential, beside how often its source was
|
|
2343
|
+
/// asked, the swaps its seam was handed, and the dials its host saw.
|
|
2344
|
+
struct BoundEndpoint {
|
|
2345
|
+
namespace: Namespace,
|
|
2346
|
+
asked: Arc<AtomicUsize>,
|
|
2347
|
+
seam: Arc<RecordsSwaps>,
|
|
2348
|
+
family: Arc<CountsDials>,
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
impl BoundEndpoint {
|
|
2352
|
+
fn new() -> Self {
|
|
2353
|
+
let asked = Arc::new(AtomicUsize::new(0));
|
|
2354
|
+
let mut entry = Builder::default();
|
|
2355
|
+
entry
|
|
2356
|
+
.endpoint(Endpoint::new("api.example.com", 443).unwrap())
|
|
2357
|
+
.credential(bearer_credential(&asked));
|
|
2358
|
+
let network = Network::new("api", Arc::new(entry)).unwrap();
|
|
2359
|
+
let seam = Arc::new(RecordsSwaps::default());
|
|
2360
|
+
let family = Arc::new(CountsDials::default());
|
|
2361
|
+
let namespace = Namespace::for_network(&network, family.clone(), seam.clone());
|
|
2362
|
+
Self {
|
|
2363
|
+
namespace,
|
|
2364
|
+
asked,
|
|
2365
|
+
seam,
|
|
2366
|
+
family,
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
|
|
2370
|
+
/// What `send` answers `method` carrying the placeholder and `body`.
|
|
2371
|
+
fn send(&self, method: &str, body: &[u8]) -> Option<HttpError> {
|
|
2372
|
+
let mut request = OutgoingRequest::new(method, Scheme::Https, "api.example.com:443");
|
|
2373
|
+
request.headers = vec![("authorization".to_string(), b"Bearer kobako-token".to_vec())];
|
|
2374
|
+
request.body = RequestBody::finished(body);
|
|
2375
|
+
match crate::net::send(&self.namespace, &prepare_creds(&[], None), request) {
|
|
2376
|
+
Ok(exchange) => {
|
|
2377
|
+
let _ = read_response(&exchange);
|
|
2378
|
+
None
|
|
2379
|
+
}
|
|
2380
|
+
Err(err) => Some(err),
|
|
2381
|
+
}
|
|
2382
|
+
}
|
|
2383
|
+
|
|
2384
|
+
/// How often the source was asked, how many swaps each request the
|
|
2385
|
+
/// seam was handed carried, and the dials the host saw.
|
|
2386
|
+
fn seen(&self) -> (usize, Vec<usize>, usize) {
|
|
2387
|
+
(
|
|
2388
|
+
self.asked.load(Ordering::SeqCst),
|
|
2389
|
+
self.seam.0.lock().unwrap().iter().map(Vec::len).collect(),
|
|
2390
|
+
self.family.dials(),
|
|
2391
|
+
)
|
|
2392
|
+
}
|
|
2393
|
+
}
|
|
2394
|
+
|
|
2395
|
+
// @behavior NW-242
|
|
2396
|
+
#[test]
|
|
2397
|
+
fn a_connect_request_is_refused_unsent() {
|
|
2398
|
+
let endpoint = BoundEndpoint::new();
|
|
2399
|
+
let answers = ["CONNECT", "connect"].map(|method| endpoint.send(method, b""));
|
|
2400
|
+
assert_eq!(
|
|
2401
|
+
(answers, endpoint.seen()),
|
|
2402
|
+
([Some(HttpError::Denied); 2], (0, Vec::new(), 0)),
|
|
2403
|
+
"a request whose method is CONNECT, in any case, must answer Denied with no \
|
|
2404
|
+
credential asked and nothing sent, its target never being authority-form"
|
|
2405
|
+
);
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
// @behavior NW-243
|
|
2409
|
+
#[test]
|
|
2410
|
+
fn a_credential_is_never_swapped_into_a_trace_request() {
|
|
2411
|
+
let endpoint = BoundEndpoint::new();
|
|
2412
|
+
let answers = ["TRACE", "trace", "GET"].map(|method| endpoint.send(method, b""));
|
|
2413
|
+
let (asked, swaps, _) = endpoint.seen();
|
|
2414
|
+
assert_eq!(
|
|
2415
|
+
(answers, asked, swaps),
|
|
2416
|
+
([None; 3], 1, vec![0, 0, 1]),
|
|
2417
|
+
"a TRACE request over HTTPS, in any case, must go with the placeholder unchanged \
|
|
2418
|
+
and never ask the credential its value, where a GET beside it carries the secret"
|
|
2419
|
+
);
|
|
2420
|
+
}
|
|
2421
|
+
|
|
2422
|
+
// @behavior NW-244
|
|
2423
|
+
#[test]
|
|
2424
|
+
fn a_trace_request_carrying_content_is_refused_unsent() {
|
|
2425
|
+
let endpoint = BoundEndpoint::new();
|
|
2426
|
+
let answers = ["TRACE", "trace"].map(|method| endpoint.send(method, b"content"));
|
|
2427
|
+
assert_eq!(
|
|
2428
|
+
(answers, endpoint.seen()),
|
|
2429
|
+
([Some(HttpError::Denied); 2], (0, Vec::new(), 0)),
|
|
2430
|
+
"a TRACE request carrying a body, in any case, must answer Denied with no \
|
|
2431
|
+
credential asked and nothing sent"
|
|
2432
|
+
);
|
|
2433
|
+
}
|
|
2434
|
+
|
|
1990
2435
|
// @behavior NW-048
|
|
1991
2436
|
#[test]
|
|
1992
2437
|
fn an_https_request_opens_tls_before_any_byte_of_http() {
|
|
@@ -2026,9 +2471,7 @@ mod tests {
|
|
|
2026
2471
|
// @behavior NW-045
|
|
2027
2472
|
#[test]
|
|
2028
2473
|
fn a_request_policy_sees_the_request_and_refuses_it_unsent() {
|
|
2029
|
-
let
|
|
2030
|
-
listener.set_nonblocking(true).unwrap();
|
|
2031
|
-
let port = listener.local_addr().unwrap().port();
|
|
2474
|
+
let port = 8080;
|
|
2032
2475
|
let seen = Arc::new(Mutex::new(Vec::new()));
|
|
2033
2476
|
let recorded = seen.clone();
|
|
2034
2477
|
let mut entry = Builder::default();
|
|
@@ -2048,21 +2491,17 @@ mod tests {
|
|
|
2048
2491
|
false
|
|
2049
2492
|
});
|
|
2050
2493
|
let network = Network::new("web", Arc::new(entry)).unwrap();
|
|
2494
|
+
let family = Arc::new(CountsDials::default());
|
|
2051
2495
|
let namespace =
|
|
2052
|
-
Namespace::for_network(&network,
|
|
2496
|
+
Namespace::for_network(&network, family.clone(), Arc::new(HyperOutbound::new()));
|
|
2053
2497
|
let mut request = greeting_request(&format!("127.0.0.1:{port}"));
|
|
2054
2498
|
request
|
|
2055
2499
|
.headers
|
|
2056
2500
|
.push(("X-Probe".to_string(), b"secret".to_vec()));
|
|
2057
2501
|
let cred = prepare_creds(&[], None);
|
|
2058
2502
|
let answer = crate::net::send(&namespace, &cred, request).err();
|
|
2059
|
-
thread::sleep(Duration::from_millis(20));
|
|
2060
2503
|
assert_eq!(
|
|
2061
|
-
(
|
|
2062
|
-
answer,
|
|
2063
|
-
seen.lock().unwrap().clone(),
|
|
2064
|
-
listener.accept().is_err()
|
|
2065
|
-
),
|
|
2504
|
+
(answer, seen.lock().unwrap().clone(), family.dials() == 0),
|
|
2066
2505
|
(
|
|
2067
2506
|
Some(HttpError::Denied),
|
|
2068
2507
|
vec![(
|
|
@@ -2122,13 +2561,7 @@ mod tests {
|
|
|
2122
2561
|
)]),
|
|
2123
2562
|
)
|
|
2124
2563
|
.endpoint(Endpoint::new("*.example.com", 443).unwrap())
|
|
2125
|
-
.credential(
|
|
2126
|
-
crate::network::Placement::Bearer,
|
|
2127
|
-
"kobako-token",
|
|
2128
|
-
Arc::new(|_: &crate::network::Request<'_>| {
|
|
2129
|
-
Ok(Some(crate::network::Secret::new("s3cret")))
|
|
2130
|
-
}),
|
|
2131
|
-
));
|
|
2564
|
+
.credential(bearer_credential(&Arc::default()));
|
|
2132
2565
|
let network = Network::new("api", Arc::new(entry)).unwrap();
|
|
2133
2566
|
let seam = Arc::new(RecordsSwaps::default());
|
|
2134
2567
|
let family = Arc::new(CountsDials::default());
|
|
@@ -2274,7 +2707,7 @@ mod tests {
|
|
|
2274
2707
|
(
|
|
2275
2708
|
Some(b"Bearer s3cret".to_vec()),
|
|
2276
2709
|
Some(b"kobako-token".to_vec()),
|
|
2277
|
-
|
|
2710
|
+
4,
|
|
2278
2711
|
"Secret(**)".to_string()
|
|
2279
2712
|
),
|
|
2280
2713
|
"the outbound seam must send a request with its credential's placeholder \
|
|
@@ -2309,124 +2742,53 @@ mod tests {
|
|
|
2309
2742
|
|
|
2310
2743
|
// @behavior NW-116
|
|
2311
2744
|
#[test]
|
|
2312
|
-
fn
|
|
2313
|
-
let
|
|
2314
|
-
|
|
2315
|
-
let
|
|
2316
|
-
let
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
let
|
|
2326
|
-
&namespace,
|
|
2327
|
-
&cred,
|
|
2328
|
-
OutgoingRequest::new("GET", Scheme::Http, "api.example.com:80"),
|
|
2329
|
-
)
|
|
2330
|
-
.err();
|
|
2331
|
-
let made = tcp.is_ok();
|
|
2332
|
-
drop(tcp);
|
|
2333
|
-
let again =
|
|
2334
|
-
crate::net::UdpSock::create(&namespace, &cred, crate::net::AddressFamily::Inet).is_ok();
|
|
2335
|
-
assert_eq!(
|
|
2336
|
-
(made, udp, sent, again),
|
|
2337
|
-
(
|
|
2338
|
-
true,
|
|
2339
|
-
Some(Errno::OutOfMemory),
|
|
2340
|
-
Some(HttpError::Internal),
|
|
2341
|
-
true
|
|
2342
|
-
),
|
|
2343
|
-
"with a memory_limit holding one TCP socket's buffers, a UDP socket must answer \
|
|
2344
|
-
ENOMEM and a request fail before it is sent, and a UDP socket must be made once the \
|
|
2345
|
-
TCP socket is gone"
|
|
2346
|
-
);
|
|
2347
|
-
}
|
|
2348
|
-
|
|
2349
|
-
/// A seam answering each request at once with one header of `.0` bytes and
|
|
2350
|
-
/// no body.
|
|
2351
|
-
struct AnswersHeader(usize);
|
|
2352
|
-
|
|
2353
|
-
impl Outbound for AnswersHeader {
|
|
2354
|
-
fn send_request(&self, _: OutgoingRequest, _: Connector) -> ResponseFuture {
|
|
2355
|
-
let size = self.0;
|
|
2356
|
-
Box::pin(async move {
|
|
2357
|
-
Ok(Response {
|
|
2358
|
-
head: ResponseHead {
|
|
2359
|
-
status: 200,
|
|
2360
|
-
headers: vec![("x-large".to_string(), vec![b'v'; size])],
|
|
2361
|
-
},
|
|
2362
|
-
body: http_body_util::Empty::<Bytes>::new()
|
|
2363
|
-
.map_err(|never| match never {})
|
|
2364
|
-
.boxed_unsync(),
|
|
2365
|
-
})
|
|
2366
|
-
})
|
|
2367
|
-
}
|
|
2368
|
-
}
|
|
2369
|
-
|
|
2370
|
-
// @behavior NW-156
|
|
2371
|
-
#[test]
|
|
2372
|
-
fn a_response_head_past_the_invocations_memory_answers_internal_error() {
|
|
2373
|
-
let status = |size: usize| {
|
|
2374
|
-
let mut entry = Builder::default();
|
|
2375
|
-
entry.endpoint(Endpoint::new("api.example.com", 80).unwrap());
|
|
2376
|
-
let network = Network::new("api", Arc::new(entry)).unwrap();
|
|
2377
|
-
let namespace = Namespace::for_network(
|
|
2378
|
-
&network,
|
|
2379
|
-
Arc::new(CountsDials::default()),
|
|
2380
|
-
Arc::new(AnswersHeader(size)),
|
|
2381
|
-
);
|
|
2382
|
-
let cred = prepare_creds(&[], Some(MAX_READ_BUFFER + MAX_SOCKET_BUFFER + 16 * 1024));
|
|
2383
|
-
let exchange = crate::net::send(
|
|
2384
|
-
&namespace,
|
|
2385
|
-
&cred,
|
|
2386
|
-
OutgoingRequest::new("GET", Scheme::Http, "api.example.com:80"),
|
|
2387
|
-
)
|
|
2388
|
-
.expect("an endpoint names the authority");
|
|
2389
|
-
read_response(&exchange).map(|(head, _)| head.status)
|
|
2390
|
-
};
|
|
2391
|
-
assert_eq!(
|
|
2392
|
-
(status(1024), status(64 * 1024)),
|
|
2393
|
-
(Ok(200), Err(HttpError::Internal)),
|
|
2394
|
-
"a response whose head fits the Invocation's memory beside its buffer must be \
|
|
2395
|
-
answered, and one whose 64 KiB head does not must fail as internal"
|
|
2396
|
-
);
|
|
2397
|
-
}
|
|
2398
|
-
|
|
2399
|
-
// @behavior NW-156
|
|
2400
|
-
#[test]
|
|
2401
|
-
fn a_released_response_holds_its_head_until_the_exchange_is_dropped() {
|
|
2402
|
-
let mut entry = Builder::default();
|
|
2403
|
-
entry.endpoint(Endpoint::new("api.example.com", 80).unwrap());
|
|
2404
|
-
let network = Network::new("api", Arc::new(entry)).unwrap();
|
|
2405
|
-
let namespace = Namespace::for_network(
|
|
2406
|
-
&network,
|
|
2407
|
-
Arc::new(CountsDials::default()),
|
|
2408
|
-
Arc::new(AnswersHeader(24 * 1024)),
|
|
2409
|
-
);
|
|
2410
|
-
let cred = prepare_creds(&[], Some(MAX_READ_BUFFER + MAX_SOCKET_BUFFER + 40 * 1024));
|
|
2745
|
+
fn a_body_holds_one_socket_buffer_until_the_guest_reads() {
|
|
2746
|
+
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
2747
|
+
let port = listener.local_addr().unwrap().port();
|
|
2748
|
+
let size = 1 << 20;
|
|
2749
|
+
let server = thread::spawn(move || {
|
|
2750
|
+
let (mut stream, _) = listener.accept().unwrap();
|
|
2751
|
+
let mut head = [0; 1024];
|
|
2752
|
+
let _ = stream.read(&mut head);
|
|
2753
|
+
let header = format!("HTTP/1.1 200 OK\r\ncontent-length: {size}\r\n\r\n");
|
|
2754
|
+
stream.write_all(header.as_bytes()).unwrap();
|
|
2755
|
+
let body = (0..size).map(|i| (i % 251) as u8).collect::<Vec<_>>();
|
|
2756
|
+
let _ = stream.write_all(&body);
|
|
2757
|
+
});
|
|
2758
|
+
let namespace = namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
|
|
2411
2759
|
let exchange = crate::net::send(
|
|
2412
2760
|
&namespace,
|
|
2413
|
-
&
|
|
2414
|
-
|
|
2761
|
+
&prepare_creds(&[], Some(16 * 1024)),
|
|
2762
|
+
greeting_request(&format!("127.0.0.1:{port}")),
|
|
2415
2763
|
)
|
|
2416
2764
|
.expect("an endpoint names the authority");
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2765
|
+
// Each look moves the exchange on, as its guest's poll does, until a
|
|
2766
|
+
// frame waits for room in the body's full buffer.
|
|
2767
|
+
crate::sched::testing::wait_until("a frame waiting for room in the body's buffer", || {
|
|
2768
|
+
exchange.state().pending.is_some()
|
|
2769
|
+
});
|
|
2770
|
+
let held = {
|
|
2771
|
+
let state = exchange.state();
|
|
2772
|
+
state.body.len() + state.pending.as_ref().map_or(0, Vec::len)
|
|
2773
|
+
};
|
|
2774
|
+
let mut body = Vec::new();
|
|
2775
|
+
let mut buf = [0; 4096];
|
|
2776
|
+
let started = std::time::Instant::now();
|
|
2777
|
+
while body.len() < size && started.elapsed() < Duration::from_secs(10) {
|
|
2778
|
+
match exchange.read(&mut buf) {
|
|
2779
|
+
Ok(0) => break,
|
|
2780
|
+
Ok(n) => body.extend_from_slice(&buf[..n]),
|
|
2781
|
+
Err(_) => thread::sleep(Duration::from_millis(1)),
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
server.join().unwrap();
|
|
2785
|
+
let expected = (0..size).map(|i| (i % 251) as u8).collect::<Vec<_>>();
|
|
2786
|
+
assert!(
|
|
2787
|
+
held <= MAX_SOCKET_BUFFER + MAX_READ_BUFFER && body == expected,
|
|
2788
|
+
"a 1 MiB body the guest has not read, under a 16 KiB memory_limit, must hold no \
|
|
2789
|
+
more than one socket buffer and one read, then reach the guest whole and in \
|
|
2790
|
+
order; held {held}, got {} bytes",
|
|
2791
|
+
body.len()
|
|
2430
2792
|
);
|
|
2431
2793
|
}
|
|
2432
2794
|
|
|
@@ -2455,6 +2817,106 @@ mod tests {
|
|
|
2455
2817
|
}
|
|
2456
2818
|
}
|
|
2457
2819
|
|
|
2820
|
+
/// A seam that dials the request's authority, then reads the connection a
|
|
2821
|
+
/// byte at a time, counting each, and never answers.
|
|
2822
|
+
struct ReadsEachByte(Arc<AtomicUsize>);
|
|
2823
|
+
|
|
2824
|
+
impl Outbound for ReadsEachByte {
|
|
2825
|
+
fn send_request(&self, request: OutgoingRequest, connector: Connector) -> ResponseFuture {
|
|
2826
|
+
let reads = self.0.clone();
|
|
2827
|
+
Box::pin(async move {
|
|
2828
|
+
let _held = request;
|
|
2829
|
+
let mut connection = connector.dial().await?;
|
|
2830
|
+
let mut byte = [0; 1];
|
|
2831
|
+
loop {
|
|
2832
|
+
let mut buf = tokio::io::ReadBuf::new(&mut byte);
|
|
2833
|
+
poll_fn(|cx| {
|
|
2834
|
+
tokio::io::AsyncRead::poll_read(Pin::new(&mut connection), cx, &mut buf)
|
|
2835
|
+
})
|
|
2836
|
+
.await
|
|
2837
|
+
.map_err(|_| HttpError::Internal)?;
|
|
2838
|
+
if buf.filled().is_empty() {
|
|
2839
|
+
std::future::pending::<()>().await;
|
|
2840
|
+
}
|
|
2841
|
+
reads.fetch_add(1, Ordering::SeqCst);
|
|
2842
|
+
}
|
|
2843
|
+
})
|
|
2844
|
+
}
|
|
2845
|
+
}
|
|
2846
|
+
|
|
2847
|
+
// A peer that keeps the connection readable, as one sending endless
|
|
2848
|
+
// informational responses, must not hold one look at the request: the
|
|
2849
|
+
// look returns after its budget, and the request wakes its own wait.
|
|
2850
|
+
// @behavior NW-256
|
|
2851
|
+
#[test]
|
|
2852
|
+
fn one_look_at_a_request_reads_its_connection_at_most_128_times() {
|
|
2853
|
+
const SENT: usize = 16 * 1024;
|
|
2854
|
+
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
2855
|
+
let port = listener.local_addr().unwrap().port();
|
|
2856
|
+
let (go, gone) = std::sync::mpsc::channel::<()>();
|
|
2857
|
+
let (done, finished) = std::sync::mpsc::channel::<()>();
|
|
2858
|
+
let peer = thread::spawn(move || {
|
|
2859
|
+
let (mut stream, _) = listener.accept().unwrap();
|
|
2860
|
+
let informational = b"HTTP/1.1 102 Processing\r\n\r\n".repeat(SENT);
|
|
2861
|
+
// Sent once the request connected, so no look before the
|
|
2862
|
+
// measured ones reads it.
|
|
2863
|
+
let _ = gone.recv_timeout(Duration::from_secs(10));
|
|
2864
|
+
stream.write_all(&informational[..SENT]).unwrap();
|
|
2865
|
+
let _ = finished.recv_timeout(Duration::from_secs(10));
|
|
2866
|
+
});
|
|
2867
|
+
let mut entry = Builder::default();
|
|
2868
|
+
entry.endpoint(
|
|
2869
|
+
Endpoint::new("127.0.0.1", port)
|
|
2870
|
+
.unwrap()
|
|
2871
|
+
.with_addresses(vec![crate::network::Addresses::Local]),
|
|
2872
|
+
);
|
|
2873
|
+
let network = Network::new("web", Arc::new(entry)).unwrap();
|
|
2874
|
+
let reads = Arc::new(AtomicUsize::new(0));
|
|
2875
|
+
let seam = Arc::new(ReadsEachByte(reads.clone()));
|
|
2876
|
+
let namespace = Namespace::for_network(&network, Arc::new(HostInet), seam);
|
|
2877
|
+
let exchange = crate::net::send(
|
|
2878
|
+
&namespace,
|
|
2879
|
+
&prepare_creds(&[], None),
|
|
2880
|
+
greeting_request(&format!("127.0.0.1:{port}")),
|
|
2881
|
+
)
|
|
2882
|
+
.expect("the endpoint names the authority");
|
|
2883
|
+
// Each look moves the request on, as its guest's poll does.
|
|
2884
|
+
crate::sched::testing::wait_until("the request connecting to the peer", || {
|
|
2885
|
+
let _ = exchange.response();
|
|
2886
|
+
exchange.connected.get().is_some()
|
|
2887
|
+
});
|
|
2888
|
+
let _ = go.send(());
|
|
2889
|
+
// Once the reactor queued every byte the peer sent, the connection
|
|
2890
|
+
// stays readable for each look that follows.
|
|
2891
|
+
let upstreams = namespace.tcp_sockets().held();
|
|
2892
|
+
crate::sched::testing::wait_until("the reactor queueing every byte the peer sent", || {
|
|
2893
|
+
upstreams.iter().any(|upstream| upstream.unread() == SENT)
|
|
2894
|
+
});
|
|
2895
|
+
let (mut most, mut last) = (0, reads.load(Ordering::SeqCst));
|
|
2896
|
+
let give_up = Instant::now() + crate::sched::testing::MAX_WAIT;
|
|
2897
|
+
let answer = crate::wait::do_poll(
|
|
2898
|
+
|| Some(give_up),
|
|
2899
|
+
|table| {
|
|
2900
|
+
crate::wait::poll_wait(&exchange.wait, table);
|
|
2901
|
+
let _ = exchange.response();
|
|
2902
|
+
let now = reads.load(Ordering::SeqCst);
|
|
2903
|
+
most = most.max(now - last);
|
|
2904
|
+
last = now;
|
|
2905
|
+
(now >= SENT).then_some(())
|
|
2906
|
+
},
|
|
2907
|
+
);
|
|
2908
|
+
let _ = done.send(());
|
|
2909
|
+
peer.join().unwrap();
|
|
2910
|
+
assert_eq!(
|
|
2911
|
+
(answer, most),
|
|
2912
|
+
(Ok(Some(())), 128),
|
|
2913
|
+
"a request whose connection holds 16 KiB read a byte at a time must read at most 128 \
|
|
2914
|
+
times in each look, and wake its own wait until every byte is read, got {} of \
|
|
2915
|
+
{SENT} bytes",
|
|
2916
|
+
reads.load(Ordering::SeqCst)
|
|
2917
|
+
);
|
|
2918
|
+
}
|
|
2919
|
+
|
|
2458
2920
|
/// The answer `exchange` settles on, once it settles. Ten seconds is far
|
|
2459
2921
|
/// past any timeout these tests set, so an exchange still unsettled then
|
|
2460
2922
|
/// is one no timeout was left to end.
|
|
@@ -2525,6 +2987,8 @@ mod tests {
|
|
|
2525
2987
|
let unset_head = timed(Arc::new(DialsThenWaits), Timeouts::default());
|
|
2526
2988
|
let give_up = Instant::now() + Duration::from_secs(10);
|
|
2527
2989
|
let connected = loop {
|
|
2990
|
+
// Each look moves the request on, as its guest's poll does.
|
|
2991
|
+
let _ = unset_head.response();
|
|
2528
2992
|
match unset_head.connected.get() {
|
|
2529
2993
|
Some(at) => break *at,
|
|
2530
2994
|
None if Instant::now() < give_up => thread::sleep(Duration::from_millis(1)),
|
|
@@ -2620,36 +3084,8 @@ mod tests {
|
|
|
2620
3084
|
);
|
|
2621
3085
|
}
|
|
2622
3086
|
|
|
2623
|
-
// @behavior NW-156
|
|
2624
|
-
#[test]
|
|
2625
|
-
fn a_request_in_flight_holds_its_parts_against_the_invocations_memory() {
|
|
2626
|
-
let mut entry = Builder::default();
|
|
2627
|
-
entry.endpoint(Endpoint::new("api.example.com", 80).unwrap());
|
|
2628
|
-
let network = Network::new("api", Arc::new(entry)).unwrap();
|
|
2629
|
-
let namespace = Namespace::for_network(
|
|
2630
|
-
&network,
|
|
2631
|
-
Arc::new(CountsDials::default()),
|
|
2632
|
-
Arc::new(NeverAnswers),
|
|
2633
|
-
);
|
|
2634
|
-
let cred = prepare_creds(&[], Some(MAX_READ_BUFFER + MAX_SOCKET_BUFFER + 40 * 1024));
|
|
2635
|
-
let mut request = OutgoingRequest::new("GET", Scheme::Http, "api.example.com:80");
|
|
2636
|
-
request.path_with_query = format!("/{}", "p".repeat(30 * 1024));
|
|
2637
|
-
let exchange =
|
|
2638
|
-
crate::net::send(&namespace, &cred, request).expect("an endpoint names the authority");
|
|
2639
|
-
let while_sent = MemoryCharge::new(cred.memory_budget(), 20 * 1024).is_ok();
|
|
2640
|
-
exchange.release();
|
|
2641
|
-
let after = MemoryCharge::new(cred.memory_budget(), 20 * 1024).is_ok();
|
|
2642
|
-
assert_eq!(
|
|
2643
|
-
(while_sent, after),
|
|
2644
|
-
(false, true),
|
|
2645
|
-
"a request whose 30 KiB path is under way must hold it against a memory_limit of \
|
|
2646
|
-
its buffer and 40 KiB, so 20 KiB more is refused, and give it back once released"
|
|
2647
|
-
);
|
|
2648
|
-
}
|
|
2649
|
-
|
|
2650
3087
|
mod stress {
|
|
2651
3088
|
use std::task::Context;
|
|
2652
|
-
use std::time::Instant;
|
|
2653
3089
|
|
|
2654
3090
|
use super::*;
|
|
2655
3091
|
|
|
@@ -2687,13 +3123,13 @@ mod tests {
|
|
|
2687
3123
|
}
|
|
2688
3124
|
}
|
|
2689
3125
|
|
|
2690
|
-
//
|
|
2691
|
-
//
|
|
2692
|
-
//
|
|
3126
|
+
// Each look fills a body that never ends, and the guest lets the
|
|
3127
|
+
// exchange go with its body still filling. A request sent after every
|
|
3128
|
+
// one of them must still be answered.
|
|
2693
3129
|
// @behavior NW-082
|
|
2694
3130
|
#[test]
|
|
2695
3131
|
#[ignore = "a stress witness; run by rake crates:stress"]
|
|
2696
|
-
fn
|
|
3132
|
+
fn an_exchange_let_go_while_its_body_fills_leaves_later_requests_answered() {
|
|
2697
3133
|
let mut entry = Builder::default();
|
|
2698
3134
|
entry.endpoint(Endpoint::new("api.example.com", 80).unwrap());
|
|
2699
3135
|
let network = Network::new("api", Arc::new(entry)).unwrap();
|
|
@@ -2719,14 +3155,10 @@ mod tests {
|
|
|
2719
3155
|
let _ = exchange.read(&mut [0; 1]);
|
|
2720
3156
|
}
|
|
2721
3157
|
let last = send();
|
|
2722
|
-
let deadline = Instant::now() + Duration::from_secs(5);
|
|
2723
|
-
while last.response().is_none() && Instant::now() < deadline {
|
|
2724
|
-
thread::sleep(Duration::from_millis(1));
|
|
2725
|
-
}
|
|
2726
3158
|
assert!(
|
|
2727
|
-
last.response().is_some(),
|
|
3159
|
+
crate::sched::testing::holds_within_max_wait(|| last.response().is_some()),
|
|
2728
3160
|
"a request sent after 20,000 exchanges let go while their bodies fill must still \
|
|
2729
|
-
be answered, so no exchange's release
|
|
3161
|
+
be answered, so no exchange's release leaves anything held"
|
|
2730
3162
|
);
|
|
2731
3163
|
}
|
|
2732
3164
|
}
|