rwebtransport 0.2.2 → 0.2.3
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.
- package/Cargo.lock +462 -6
- package/README.md +5 -1
- package/crates/native/Cargo.toml +2 -0
- package/crates/native/src/config.rs +56 -7
- package/crates/native/src/driver.rs +5 -0
- package/crates/native/src/lib.rs +71 -47
- package/crates/native/src/parser_memory.rs +202 -0
- package/crates/native/src/server.rs +19 -2
- package/crates/native/src/session.rs +1068 -122
- package/crates/native/src/test_support.rs +119 -0
- package/crates/wtcore/Cargo.toml +1 -0
- package/crates/wtcore/src/h3.rs +85 -37
- package/dist/index.js +133 -37
- package/dist/index.js.map +7 -1
- package/dist/index.mjs +129 -31
- package/dist/index.mjs.map +7 -1
- package/dist/native.d.ts +1 -0
- package/dist/server.d.ts +1 -0
- package/package.json +81 -78
- package/prebuilds/darwin-arm64/rwebtransport.node +0 -0
- package/prebuilds/linux-arm64/rwebtransport.node +0 -0
- package/prebuilds/linux-x64/rwebtransport.node +0 -0
- package/prebuilds/win32-x64/rwebtransport.node +0 -0
- package/scripts/build-ts.js +41 -0
- package/vendor/quiche/src/lib.rs +15 -0
- package/vendor/quiche/src/stream/recv_buf.rs +5 -0
- package/vendor/quiche/src/stream/send_buf.rs +5 -0
|
@@ -12,6 +12,7 @@ pub const H3_ALPN: &[u8] = b"h3";
|
|
|
12
12
|
#[derive(Clone, Debug)]
|
|
13
13
|
pub struct ClientConfigParams {
|
|
14
14
|
pub verify: CertVerification,
|
|
15
|
+
pub expected_ip: Option<std::net::IpAddr>,
|
|
15
16
|
pub max_idle_timeout_ms: u64,
|
|
16
17
|
pub max_udp_payload_size: usize,
|
|
17
18
|
pub initial_max_data: u64,
|
|
@@ -26,6 +27,7 @@ impl Default for ClientConfigParams {
|
|
|
26
27
|
fn default() -> Self {
|
|
27
28
|
Self {
|
|
28
29
|
verify: CertVerification::PkiDefault,
|
|
30
|
+
expected_ip: None,
|
|
29
31
|
max_idle_timeout_ms: 30_000,
|
|
30
32
|
max_udp_payload_size: 1350,
|
|
31
33
|
initial_max_data: 10 * 1024 * 1024,
|
|
@@ -42,7 +44,36 @@ impl Default for ClientConfigParams {
|
|
|
42
44
|
|
|
43
45
|
/// Build a ready-to-use quiche client [`quiche::Config`].
|
|
44
46
|
pub fn build_config(p: &ClientConfigParams) -> Result<quiche::Config, String> {
|
|
45
|
-
let builder = build_client_tls(&p.verify)?;
|
|
47
|
+
let mut builder = build_client_tls(&p.verify)?;
|
|
48
|
+
if matches!(p.verify, CertVerification::PkiDefault) {
|
|
49
|
+
let roots = rustls_native_certs::load_native_certs();
|
|
50
|
+
let mut loaded = 0;
|
|
51
|
+
for der in roots.certs {
|
|
52
|
+
if let Ok(cert) = boring::x509::X509::from_der(der.as_ref()) {
|
|
53
|
+
if builder.cert_store_mut().add_cert(cert).is_ok() {
|
|
54
|
+
loaded += 1;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if loaded == 0 {
|
|
59
|
+
return Err("system certificate store contains no usable roots".into());
|
|
60
|
+
}
|
|
61
|
+
if let Some(ip) = p.expected_ip {
|
|
62
|
+
let bytes: Vec<u8> = match ip {
|
|
63
|
+
std::net::IpAddr::V4(ip) => ip.octets().to_vec(),
|
|
64
|
+
std::net::IpAddr::V6(ip) => ip.octets().to_vec(),
|
|
65
|
+
};
|
|
66
|
+
// The context owns the verification parameter; BoringSSL copies it
|
|
67
|
+
// into the connection and copies the address supplied here.
|
|
68
|
+
let ok = unsafe {
|
|
69
|
+
let param = boring_sys::SSL_CTX_get0_param(builder.as_ptr());
|
|
70
|
+
boring_sys::X509_VERIFY_PARAM_set1_ip(param, bytes.as_ptr(), bytes.len())
|
|
71
|
+
};
|
|
72
|
+
if ok != 1 {
|
|
73
|
+
return Err("failed to configure certificate IP verification".into());
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
46
77
|
let mut config = quiche::Config::with_boring_ssl_ctx_builder(quiche::PROTOCOL_VERSION, builder)
|
|
47
78
|
.map_err(|e| format!("quiche config: {e:?}"))?;
|
|
48
79
|
|
|
@@ -56,12 +87,6 @@ pub fn build_config(p: &ClientConfigParams) -> Result<quiche::Config, String> {
|
|
|
56
87
|
// it a trust anchor set. Hostname verification is wired by quiche's
|
|
57
88
|
// `set_host_name` (X509_VERIFY_PARAM_set1_host).
|
|
58
89
|
config.verify_peer(true);
|
|
59
|
-
#[cfg(unix)]
|
|
60
|
-
{
|
|
61
|
-
// Best-effort system roots. If neither path exists the handshake
|
|
62
|
-
// will fail closed, which is the correct default.
|
|
63
|
-
let _ = config.load_verify_locations_from_directory("/etc/ssl/certs");
|
|
64
|
-
}
|
|
65
90
|
}
|
|
66
91
|
CertVerification::Hashes(_) | CertVerification::Insecure => {
|
|
67
92
|
// Verification is fully handled on the SSL context (custom callback /
|
|
@@ -127,3 +152,27 @@ pub fn build_server_config(cert_path: &str, key_path: &str) -> Result<quiche::Co
|
|
|
127
152
|
|
|
128
153
|
Ok(config)
|
|
129
154
|
}
|
|
155
|
+
|
|
156
|
+
#[cfg(test)]
|
|
157
|
+
mod tests {
|
|
158
|
+
#[test]
|
|
159
|
+
fn certificate_identity_checks_dns_and_ip_sans() {
|
|
160
|
+
use crate::test_support::{exchange, pair};
|
|
161
|
+
for (expected_ip, name, ip_san, accepted) in [
|
|
162
|
+
(Some("127.0.0.1".parse().unwrap()), None, false, false),
|
|
163
|
+
(Some("127.0.0.1".parse().unwrap()), None, true, true),
|
|
164
|
+
(Some("::1".parse().unwrap()), None, false, false),
|
|
165
|
+
(Some("::1".parse().unwrap()), None, true, true),
|
|
166
|
+
(None, Some("localhost"), false, false),
|
|
167
|
+
(None, Some("wrong.example"), false, true),
|
|
168
|
+
] {
|
|
169
|
+
let (mut client, mut server) = pair(expected_ip, name, ip_san);
|
|
170
|
+
exchange(&mut client, &mut server);
|
|
171
|
+
assert_eq!(
|
|
172
|
+
client.is_established(),
|
|
173
|
+
accepted,
|
|
174
|
+
"IP={expected_ip:?}, DNS={name:?}, ip_san={ip_san}"
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -308,6 +308,11 @@ fn run_inner(
|
|
|
308
308
|
loop {
|
|
309
309
|
match socket.recv_from(&mut recv_buf) {
|
|
310
310
|
Ok((len, from)) => {
|
|
311
|
+
// UDP permits empty datagrams. They carry no QUIC packet
|
|
312
|
+
// and must not become fatal errors before authentication.
|
|
313
|
+
if len == 0 {
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
311
316
|
got_packet = true;
|
|
312
317
|
if debug {
|
|
313
318
|
eprintln!("[rwt-driver] recv {len} bytes from {from}");
|
package/crates/native/src/lib.rs
CHANGED
|
@@ -25,8 +25,11 @@
|
|
|
25
25
|
|
|
26
26
|
mod config;
|
|
27
27
|
mod driver;
|
|
28
|
+
mod parser_memory;
|
|
28
29
|
mod server;
|
|
29
30
|
mod session;
|
|
31
|
+
#[cfg(test)]
|
|
32
|
+
mod test_support;
|
|
30
33
|
mod tls;
|
|
31
34
|
|
|
32
35
|
use std::net::IpAddr;
|
|
@@ -142,52 +145,28 @@ struct ParsedUrl {
|
|
|
142
145
|
/// Parse a WebTransport URL WITHOUT resolving DNS (resolution is deferred to the
|
|
143
146
|
/// driver thread so it never blocks the JS event loop).
|
|
144
147
|
fn parse_url(url: &str) -> Result<ParsedUrl, String> {
|
|
145
|
-
let
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
};
|
|
153
|
-
if authority.is_empty() {
|
|
154
|
-
return Err("WebTransport URL has an empty authority".to_string());
|
|
148
|
+
let parsed = url::Url::parse(url).map_err(|e| format!("invalid WebTransport URL: {e}"))?;
|
|
149
|
+
if parsed.scheme() != "https"
|
|
150
|
+
|| parsed.fragment().is_some()
|
|
151
|
+
|| !parsed.username().is_empty()
|
|
152
|
+
|| parsed.password().is_some()
|
|
153
|
+
{
|
|
154
|
+
return Err("WebTransport URL must use HTTPS without credentials or a fragment".into());
|
|
155
155
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
.find(']')
|
|
161
|
-
.ok_or_else(|| "malformed IPv6 authority".to_string())?;
|
|
162
|
-
let host = hstr[..end].to_string();
|
|
163
|
-
let after = &hstr[end + 1..];
|
|
164
|
-
let port = after
|
|
165
|
-
.strip_prefix(':')
|
|
166
|
-
.map(|p| p.parse::<u16>().map_err(|_| "invalid port".to_string()))
|
|
167
|
-
.transpose()?
|
|
168
|
-
.unwrap_or(443);
|
|
169
|
-
(host, port)
|
|
170
|
-
} else if let Some(i) = authority.rfind(':') {
|
|
171
|
-
let host = authority[..i].to_string();
|
|
172
|
-
let port = authority[i + 1..]
|
|
173
|
-
.parse::<u16>()
|
|
174
|
-
.map_err(|_| "invalid port".to_string())?;
|
|
175
|
-
(host, port)
|
|
176
|
-
} else {
|
|
177
|
-
(authority.to_string(), 443)
|
|
156
|
+
let host = match parsed.host().ok_or("WebTransport URL has no host")? {
|
|
157
|
+
url::Host::Domain(name) => name.to_string(),
|
|
158
|
+
url::Host::Ipv4(ip) => ip.to_string(),
|
|
159
|
+
url::Host::Ipv6(ip) => ip.to_string(),
|
|
178
160
|
};
|
|
179
|
-
|
|
180
|
-
let
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
Some(host.clone())
|
|
184
|
-
};
|
|
185
|
-
|
|
161
|
+
let port = parsed.port_or_known_default().ok_or("invalid port")?;
|
|
162
|
+
let authority = parsed[url::Position::BeforeHost..url::Position::AfterPort].to_string();
|
|
163
|
+
let path = parsed[url::Position::BeforePath..url::Position::AfterQuery].to_string();
|
|
164
|
+
let sni = host.parse::<IpAddr>().is_err().then(|| host.clone());
|
|
186
165
|
Ok(ParsedUrl {
|
|
187
166
|
host,
|
|
188
167
|
port,
|
|
189
168
|
sni,
|
|
190
|
-
authority
|
|
169
|
+
authority,
|
|
191
170
|
path,
|
|
192
171
|
})
|
|
193
172
|
}
|
|
@@ -288,6 +267,7 @@ fn connect(mut cx: FunctionContext) -> JsResult<JsBox<SessionHandle>> {
|
|
|
288
267
|
};
|
|
289
268
|
|
|
290
269
|
let params = ClientConfigParams {
|
|
270
|
+
expected_ip: parsed.host.parse().ok(),
|
|
291
271
|
verify,
|
|
292
272
|
..ClientConfigParams::default()
|
|
293
273
|
};
|
|
@@ -445,7 +425,11 @@ fn export_keying_material(mut cx: FunctionContext) -> JsResult<JsUndefined> {
|
|
|
445
425
|
let request_id = to_request_id(cx.argument::<JsNumber>(1)?.value(&mut cx));
|
|
446
426
|
let label = cx.argument::<JsTypedArray<u8>>(2)?.as_slice(&cx).to_vec();
|
|
447
427
|
let context = cx.argument::<JsTypedArray<u8>>(3)?.as_slice(&cx).to_vec();
|
|
448
|
-
let length = cx.argument::<JsNumber>(4)?.value(&mut cx)
|
|
428
|
+
let length = cx.argument::<JsNumber>(4)?.value(&mut cx);
|
|
429
|
+
if !length.is_finite() || length.fract() != 0.0 || !(1.0..=4096.0).contains(&length) {
|
|
430
|
+
return cx.throw_range_error("outputLength must be an integer between 1 and 4096");
|
|
431
|
+
}
|
|
432
|
+
let length = length as u32;
|
|
449
433
|
handle.send(Command::ExportKeyingMaterial {
|
|
450
434
|
request_id,
|
|
451
435
|
label,
|
|
@@ -745,7 +729,11 @@ fn server_export_keying_material(mut cx: FunctionContext) -> JsResult<JsUndefine
|
|
|
745
729
|
let request_id = to_request_id(cx.argument::<JsNumber>(2)?.value(&mut cx));
|
|
746
730
|
let label = cx.argument::<JsTypedArray<u8>>(3)?.as_slice(&cx).to_vec();
|
|
747
731
|
let context = cx.argument::<JsTypedArray<u8>>(4)?.as_slice(&cx).to_vec();
|
|
748
|
-
let length = cx.argument::<JsNumber>(5)?.value(&mut cx)
|
|
732
|
+
let length = cx.argument::<JsNumber>(5)?.value(&mut cx);
|
|
733
|
+
if !length.is_finite() || length.fract() != 0.0 || !(1.0..=4096.0).contains(&length) {
|
|
734
|
+
return cx.throw_range_error("outputLength must be an integer between 1 and 4096");
|
|
735
|
+
}
|
|
736
|
+
let length = length as u32;
|
|
749
737
|
handle.send(ServerCommand::ExportKeyingMaterial {
|
|
750
738
|
session,
|
|
751
739
|
request_id,
|
|
@@ -1056,21 +1044,57 @@ mod tests {
|
|
|
1056
1044
|
// must wake the driver EXACTLY when the decrement crosses back below the cap: not while still at or
|
|
1057
1045
|
// above it (still back-pressured), and not when already below it (a spurious wake). Getting this
|
|
1058
1046
|
// wrong is the stranded-terminal-frame hang.
|
|
1047
|
+
#[test]
|
|
1048
|
+
fn urls_are_canonicalized_without_credentials_or_fragments() {
|
|
1049
|
+
let parsed = super::parse_url("https://example.com:8443?query=1").unwrap();
|
|
1050
|
+
assert_eq!(parsed.host, "example.com");
|
|
1051
|
+
assert_eq!(parsed.port, 8443);
|
|
1052
|
+
assert_eq!(parsed.path, "/?query=1");
|
|
1053
|
+
let parsed = super::parse_url("https://[::1]:8443/a?b=2").unwrap();
|
|
1054
|
+
assert_eq!(parsed.host, "::1");
|
|
1055
|
+
assert_eq!(parsed.authority, "[::1]:8443");
|
|
1056
|
+
assert_eq!(parsed.path, "/a?b=2");
|
|
1057
|
+
assert!(parsed.sni.is_none());
|
|
1058
|
+
for url in [
|
|
1059
|
+
"http://example.com/",
|
|
1060
|
+
"https://user:password@example.com/",
|
|
1061
|
+
"https://example.com/#",
|
|
1062
|
+
"https://[::1]garbage/",
|
|
1063
|
+
] {
|
|
1064
|
+
assert!(super::parse_url(url).is_err());
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1059
1068
|
#[test]
|
|
1060
1069
|
fn release_wakes_only_when_the_decrement_clears_backpressure() {
|
|
1061
1070
|
let mut poll = mio::Poll::new().expect("poll");
|
|
1062
1071
|
let waker = mio::Waker::new(poll.registry(), driver::WAKE_TOKEN).expect("waker");
|
|
1063
1072
|
|
|
1064
1073
|
// Already below the cap: not back-pressured, so no wake.
|
|
1065
|
-
release_inflight_batch(
|
|
1066
|
-
|
|
1074
|
+
release_inflight_batch(
|
|
1075
|
+
&shared_with_inflight(driver::MAX_INFLIGHT_BATCHES - 1),
|
|
1076
|
+
&waker,
|
|
1077
|
+
);
|
|
1078
|
+
assert!(
|
|
1079
|
+
!waker_fired(&mut poll),
|
|
1080
|
+
"no wake when already below the cap"
|
|
1081
|
+
);
|
|
1067
1082
|
|
|
1068
1083
|
// Still at/above the cap after the decrement: still back-pressured, so no wake.
|
|
1069
|
-
release_inflight_batch(
|
|
1070
|
-
|
|
1084
|
+
release_inflight_batch(
|
|
1085
|
+
&shared_with_inflight(driver::MAX_INFLIGHT_BATCHES + 1),
|
|
1086
|
+
&waker,
|
|
1087
|
+
);
|
|
1088
|
+
assert!(
|
|
1089
|
+
!waker_fired(&mut poll),
|
|
1090
|
+
"no wake while still at or above the cap"
|
|
1091
|
+
);
|
|
1071
1092
|
|
|
1072
1093
|
// Exactly at the cap: the decrement crosses below it, clearing back-pressure -> wake.
|
|
1073
1094
|
release_inflight_batch(&shared_with_inflight(driver::MAX_INFLIGHT_BATCHES), &waker);
|
|
1074
|
-
assert!(
|
|
1095
|
+
assert!(
|
|
1096
|
+
waker_fired(&mut poll),
|
|
1097
|
+
"wake exactly when back-pressure clears"
|
|
1098
|
+
);
|
|
1075
1099
|
}
|
|
1076
1100
|
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
//! Allocation accounting shared by every receive parser on a server.
|
|
3
|
+
|
|
4
|
+
use std::ops::Deref;
|
|
5
|
+
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
6
|
+
use std::sync::Arc;
|
|
7
|
+
|
|
8
|
+
pub(crate) struct ParserMemory {
|
|
9
|
+
limit: usize,
|
|
10
|
+
used: AtomicUsize,
|
|
11
|
+
parent: Option<Arc<ParserMemory>>,
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
impl ParserMemory {
|
|
15
|
+
pub(crate) fn new(limit: usize) -> Arc<Self> {
|
|
16
|
+
Arc::new(Self {
|
|
17
|
+
limit,
|
|
18
|
+
used: AtomicUsize::new(0),
|
|
19
|
+
parent: None,
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
pub(crate) fn child(parent: Arc<Self>, limit: usize) -> Arc<Self> {
|
|
24
|
+
Arc::new(Self {
|
|
25
|
+
limit,
|
|
26
|
+
used: AtomicUsize::new(0),
|
|
27
|
+
parent: Some(parent),
|
|
28
|
+
})
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
fn reserve(&self, bytes: usize) -> bool {
|
|
32
|
+
let reserved = self
|
|
33
|
+
.used
|
|
34
|
+
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |used| {
|
|
35
|
+
used.checked_add(bytes).filter(|&next| next <= self.limit)
|
|
36
|
+
})
|
|
37
|
+
.is_ok();
|
|
38
|
+
if !reserved {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
if let Some(parent) = &self.parent {
|
|
42
|
+
if !parent.reserve(bytes) {
|
|
43
|
+
self.used.fetch_sub(bytes, Ordering::Relaxed);
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
true
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
fn release(&self, bytes: usize) {
|
|
51
|
+
self.used.fetch_sub(bytes, Ordering::Relaxed);
|
|
52
|
+
if let Some(parent) = &self.parent {
|
|
53
|
+
parent.release(bytes);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
#[cfg(test)]
|
|
58
|
+
pub(crate) fn used(&self) -> usize {
|
|
59
|
+
self.used.load(Ordering::Relaxed)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
pub(crate) struct ParserBuffer {
|
|
64
|
+
data: Vec<u8>,
|
|
65
|
+
memory: Arc<ParserMemory>,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
impl ParserBuffer {
|
|
69
|
+
pub(crate) fn new(memory: Arc<ParserMemory>) -> Self {
|
|
70
|
+
Self {
|
|
71
|
+
data: Vec::new(),
|
|
72
|
+
memory,
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
pub(crate) fn extend_from_slice(&mut self, bytes: &[u8]) -> Result<(), ()> {
|
|
77
|
+
let needed = self.data.len().checked_add(bytes.len()).ok_or(())?;
|
|
78
|
+
if needed > self.data.capacity() {
|
|
79
|
+
let capacity = needed.checked_next_power_of_two().ok_or(())?;
|
|
80
|
+
// Reserve the whole replacement before allocation: the old and new
|
|
81
|
+
// buffers coexist during growth, and both must fit the budget.
|
|
82
|
+
if !self.memory.reserve(capacity) {
|
|
83
|
+
return Err(());
|
|
84
|
+
}
|
|
85
|
+
let mut replacement = Vec::new();
|
|
86
|
+
if replacement.try_reserve_exact(capacity).is_err() {
|
|
87
|
+
self.memory.release(capacity);
|
|
88
|
+
return Err(());
|
|
89
|
+
}
|
|
90
|
+
// Account for any excess capacity supplied by the allocator too.
|
|
91
|
+
let extra = replacement.capacity() - capacity;
|
|
92
|
+
if extra != 0 && !self.memory.reserve(extra) {
|
|
93
|
+
drop(replacement);
|
|
94
|
+
self.memory.release(capacity);
|
|
95
|
+
return Err(());
|
|
96
|
+
}
|
|
97
|
+
replacement.extend_from_slice(&self.data);
|
|
98
|
+
let old = std::mem::replace(&mut self.data, replacement);
|
|
99
|
+
let old_capacity = old.capacity();
|
|
100
|
+
drop(old);
|
|
101
|
+
self.memory.release(old_capacity);
|
|
102
|
+
}
|
|
103
|
+
self.data.extend_from_slice(bytes);
|
|
104
|
+
Ok(())
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
pub(crate) fn consume(&mut self, bytes: usize) {
|
|
108
|
+
if bytes == self.data.len() {
|
|
109
|
+
self.clear();
|
|
110
|
+
} else {
|
|
111
|
+
self.data.drain(..bytes);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
pub(crate) fn copy_range(&self, range: std::ops::Range<usize>) -> Result<Self, ()> {
|
|
116
|
+
let mut copy = Self::new(self.memory.clone());
|
|
117
|
+
copy.extend_from_slice(&self.data[range])?;
|
|
118
|
+
Ok(copy)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
pub(crate) fn clear(&mut self) {
|
|
122
|
+
let old = std::mem::take(&mut self.data);
|
|
123
|
+
let capacity = old.capacity();
|
|
124
|
+
drop(old);
|
|
125
|
+
self.memory.release(capacity);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
#[cfg(test)]
|
|
129
|
+
pub(crate) fn capacity(&self) -> usize {
|
|
130
|
+
self.data.capacity()
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
impl Deref for ParserBuffer {
|
|
135
|
+
type Target = [u8];
|
|
136
|
+
fn deref(&self) -> &[u8] {
|
|
137
|
+
&self.data
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
impl Drop for ParserBuffer {
|
|
142
|
+
fn drop(&mut self) {
|
|
143
|
+
self.clear();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
#[cfg(test)]
|
|
148
|
+
mod tests {
|
|
149
|
+
use super::*;
|
|
150
|
+
|
|
151
|
+
#[test]
|
|
152
|
+
fn children_enforce_local_and_shared_limits_and_roll_back_refusals() {
|
|
153
|
+
let shared = ParserMemory::new(128);
|
|
154
|
+
let local = ParserMemory::child(shared.clone(), 64);
|
|
155
|
+
let other = ParserMemory::child(shared.clone(), 128);
|
|
156
|
+
let mut a = ParserBuffer::new(local.clone());
|
|
157
|
+
let mut b = ParserBuffer::new(other.clone());
|
|
158
|
+
a.extend_from_slice(&[0; 64]).unwrap();
|
|
159
|
+
assert!(a.extend_from_slice(&[0; 1]).is_err());
|
|
160
|
+
b.extend_from_slice(&[0; 64]).unwrap();
|
|
161
|
+
assert!(b.extend_from_slice(&[0; 1]).is_err());
|
|
162
|
+
assert_eq!(shared.used(), 128);
|
|
163
|
+
assert_eq!(local.used(), 64);
|
|
164
|
+
assert_eq!(other.used(), 64);
|
|
165
|
+
drop(a);
|
|
166
|
+
drop(b);
|
|
167
|
+
assert_eq!(shared.used(), 0);
|
|
168
|
+
assert_eq!(local.used(), 0);
|
|
169
|
+
assert_eq!(other.used(), 0);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
#[test]
|
|
173
|
+
fn charges_capacity_and_releases_on_consumption_and_drop() {
|
|
174
|
+
let memory = ParserMemory::new(128);
|
|
175
|
+
let mut a = ParserBuffer::new(memory.clone());
|
|
176
|
+
a.extend_from_slice(&[1; 33]).unwrap();
|
|
177
|
+
assert_eq!(memory.used(), a.capacity());
|
|
178
|
+
a.consume(32);
|
|
179
|
+
assert_eq!(memory.used(), a.capacity()); // remaining one byte retains capacity
|
|
180
|
+
let mut b = ParserBuffer::new(memory.clone());
|
|
181
|
+
b.extend_from_slice(&[2; 64]).unwrap();
|
|
182
|
+
assert!(a.extend_from_slice(&[3; 64]).is_err());
|
|
183
|
+
assert_eq!(a.len(), 1); // refusal does not mutate the existing buffer
|
|
184
|
+
a.consume(1);
|
|
185
|
+
assert_eq!(memory.used(), b.capacity());
|
|
186
|
+
drop(b);
|
|
187
|
+
assert_eq!(memory.used(), 0);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
#[test]
|
|
191
|
+
fn growth_reserves_old_and_new_allocations_before_allocating() {
|
|
192
|
+
let memory = ParserMemory::new(100);
|
|
193
|
+
let mut buf = ParserBuffer::new(memory.clone());
|
|
194
|
+
buf.extend_from_slice(&[0; 32]).unwrap();
|
|
195
|
+
buf.extend_from_slice(&[0; 1]).unwrap();
|
|
196
|
+
assert_eq!(memory.used(), 64);
|
|
197
|
+
assert!(buf.extend_from_slice(&[0; 32]).is_err());
|
|
198
|
+
assert_eq!(memory.used(), 64);
|
|
199
|
+
buf.clear();
|
|
200
|
+
assert_eq!(memory.used(), 0);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
@@ -22,6 +22,7 @@ use wtcore::h3;
|
|
|
22
22
|
|
|
23
23
|
use crate::config::build_server_config;
|
|
24
24
|
use crate::driver::{DriverShared, SOCKET_TOKEN};
|
|
25
|
+
use crate::parser_memory::ParserMemory;
|
|
25
26
|
use crate::session::{Ev, WtSession};
|
|
26
27
|
|
|
27
28
|
const LOCAL_CONN_ID_LEN: usize = 16;
|
|
@@ -31,6 +32,10 @@ const MAX_INFLIGHT_BATCHES: i64 = 128;
|
|
|
31
32
|
/// source addresses) cannot grow the connection table without bound.
|
|
32
33
|
const MAX_CONNECTIONS: usize = 16_384;
|
|
33
34
|
|
|
35
|
+
/// Aggregate allocation capacity of HTTP/3, classification and capsule parser
|
|
36
|
+
/// buffers across all connections, including handshakes and draining sessions.
|
|
37
|
+
const MAX_PARSER_MEMORY: usize = 64 * 1024 * 1024;
|
|
38
|
+
|
|
34
39
|
/// Maximum UDP packets read per event-loop wake before yielding to the rest of
|
|
35
40
|
/// the loop (timeouts, commands, reaping). Bounds per-wake work so a sustained
|
|
36
41
|
/// inbound flood cannot starve `Shutdown` handling or idle-connection reaping.
|
|
@@ -319,7 +324,12 @@ fn run_inner(
|
|
|
319
324
|
sink: &dyn ServerEventSink,
|
|
320
325
|
shared: &Arc<DriverShared>,
|
|
321
326
|
) {
|
|
322
|
-
let bind: SocketAddr = match
|
|
327
|
+
let bind: SocketAddr = match setup
|
|
328
|
+
.host
|
|
329
|
+
.trim_matches(['[', ']'])
|
|
330
|
+
.parse::<std::net::IpAddr>()
|
|
331
|
+
.map(|ip| SocketAddr::new(ip, setup.port))
|
|
332
|
+
{
|
|
323
333
|
Ok(a) => a,
|
|
324
334
|
Err(e) => {
|
|
325
335
|
sink.emit(vec![ServerMsg::ServerError(format!(
|
|
@@ -367,6 +377,7 @@ fn run_inner(
|
|
|
367
377
|
let mut routing: HashMap<Vec<u8>, Vec<u8>> = HashMap::new();
|
|
368
378
|
let mut sessions: HashMap<u64, Vec<u8>> = HashMap::new();
|
|
369
379
|
let mut next_session_id: u64 = 1;
|
|
380
|
+
let parser_memory = ParserMemory::new(MAX_PARSER_MEMORY);
|
|
370
381
|
|
|
371
382
|
// Per-process secret keying the stateless Retry token (see mint_token).
|
|
372
383
|
let token_secret = random_secret();
|
|
@@ -407,7 +418,9 @@ fn run_inner(
|
|
|
407
418
|
continue;
|
|
408
419
|
}
|
|
409
420
|
// Cap concurrent connections to bound memory under a flood.
|
|
410
|
-
if clients.len() >= MAX_CONNECTIONS
|
|
421
|
+
if clients.len() >= MAX_CONNECTIONS
|
|
422
|
+
|| shared.inflight.load(Ordering::Relaxed) >= MAX_INFLIGHT_BATCHES
|
|
423
|
+
{
|
|
411
424
|
continue;
|
|
412
425
|
}
|
|
413
426
|
|
|
@@ -460,6 +473,7 @@ fn run_inner(
|
|
|
460
473
|
setup.supported_protocols.clone(),
|
|
461
474
|
setup.allowed_origins.clone(),
|
|
462
475
|
setup.response_headers.clone(),
|
|
476
|
+
parser_memory.clone(),
|
|
463
477
|
),
|
|
464
478
|
session_id,
|
|
465
479
|
closed_emitted: false,
|
|
@@ -536,6 +550,9 @@ fn run_inner(
|
|
|
536
550
|
}
|
|
537
551
|
|
|
538
552
|
for ev in evs {
|
|
553
|
+
if std::env::var_os("RWT_DEBUG").is_some() && matches!(ev, Ev::Error(_)) {
|
|
554
|
+
eprintln!("[rwt-server] {ev:?}");
|
|
555
|
+
}
|
|
539
556
|
out.push(ServerMsg::Session(server.session_id, ev));
|
|
540
557
|
}
|
|
541
558
|
|