rwebtransport 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/Cargo.lock +666 -666
  2. package/Cargo.toml +31 -31
  3. package/LICENSE +202 -202
  4. package/NOTICE +41 -41
  5. package/README.md +550 -550
  6. package/crates/echo-server/Cargo.toml +20 -20
  7. package/crates/echo-server/src/main.rs +666 -666
  8. package/crates/native/Cargo.toml +23 -23
  9. package/crates/native/src/config.rs +129 -129
  10. package/crates/native/src/driver.rs +463 -463
  11. package/crates/native/src/lib.rs +821 -821
  12. package/crates/native/src/server.rs +718 -718
  13. package/crates/native/src/session.rs +1191 -1191
  14. package/crates/native/src/tls.rs +96 -96
  15. package/crates/wtcore/Cargo.toml +15 -15
  16. package/crates/wtcore/src/h3.rs +226 -226
  17. package/crates/wtcore/src/lib.rs +9 -9
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.mjs.map +1 -1
  20. package/package.json +80 -79
  21. package/prebuilds/darwin-arm64/rwebtransport.node +0 -0
  22. package/prebuilds/linux-arm64/rwebtransport.node +0 -0
  23. package/prebuilds/linux-x64/rwebtransport.node +0 -0
  24. package/prebuilds/win32-x64/rwebtransport.node +0 -0
  25. package/scripts/bench.mjs +180 -180
  26. package/scripts/build.js +67 -67
  27. package/scripts/postinstall.js +67 -67
  28. package/scripts/setup-unix.sh +129 -129
  29. package/scripts/setup-windows.ps1 +229 -229
  30. package/vendor/quiche/AGENTS.md +75 -75
  31. package/vendor/quiche/COPYING +23 -23
  32. package/vendor/quiche/Cargo.lock +1212 -1212
  33. package/vendor/quiche/Cargo.toml +215 -215
  34. package/vendor/quiche/README.md +466 -466
  35. package/vendor/quiche/examples/Makefile +46 -46
  36. package/vendor/quiche/examples/README.md +20 -20
  37. package/vendor/quiche/examples/cert-big.crt +90 -90
  38. package/vendor/quiche/examples/cert.crt +18 -18
  39. package/vendor/quiche/examples/cert.key +28 -28
  40. package/vendor/quiche/examples/client.c +343 -343
  41. package/vendor/quiche/examples/client.rs +281 -281
  42. package/vendor/quiche/examples/gen-certs.sh +15 -15
  43. package/vendor/quiche/examples/http3-client.c +473 -473
  44. package/vendor/quiche/examples/http3-client.rs +349 -349
  45. package/vendor/quiche/examples/http3-server.c +614 -614
  46. package/vendor/quiche/examples/http3-server.rs +680 -680
  47. package/vendor/quiche/examples/qpack-decode.rs +87 -87
  48. package/vendor/quiche/examples/qpack-encode.rs +88 -88
  49. package/vendor/quiche/examples/rootca.crt +21 -21
  50. package/vendor/quiche/examples/server.c +529 -529
  51. package/vendor/quiche/examples/server.rs +529 -529
  52. package/vendor/quiche/include/quiche.h +1282 -1282
  53. package/vendor/quiche/src/buffers.rs +105 -105
  54. package/vendor/quiche/src/build.rs +66 -66
  55. package/vendor/quiche/src/cid.rs +1079 -1079
  56. package/vendor/quiche/src/crypto/boringssl.rs +373 -373
  57. package/vendor/quiche/src/crypto/mod.rs +671 -671
  58. package/vendor/quiche/src/dgram.rs +118 -118
  59. package/vendor/quiche/src/error.rs +263 -263
  60. package/vendor/quiche/src/ffi.rs +2290 -2290
  61. package/vendor/quiche/src/flowcontrol.rs +246 -246
  62. package/vendor/quiche/src/frame.rs +2172 -2172
  63. package/vendor/quiche/src/h3/AGENTS.md +54 -54
  64. package/vendor/quiche/src/h3/ffi.rs +442 -442
  65. package/vendor/quiche/src/h3/frame.rs +1404 -1404
  66. package/vendor/quiche/src/h3/mod.rs +8223 -8223
  67. package/vendor/quiche/src/h3/qpack/decoder.rs +288 -288
  68. package/vendor/quiche/src/h3/qpack/encoder.rs +235 -235
  69. package/vendor/quiche/src/h3/qpack/mod.rs +202 -202
  70. package/vendor/quiche/src/h3/qpack/static_table.rs +323 -323
  71. package/vendor/quiche/src/h3/stream.rs +1595 -1595
  72. package/vendor/quiche/src/lib.rs +9556 -9556
  73. package/vendor/quiche/src/minmax.rs +446 -446
  74. package/vendor/quiche/src/packet.rs +2334 -2334
  75. package/vendor/quiche/src/path.rs +1374 -1374
  76. package/vendor/quiche/src/pmtud.rs +652 -652
  77. package/vendor/quiche/src/rand.rs +64 -64
  78. package/vendor/quiche/src/range_buf.rs +186 -186
  79. package/vendor/quiche/src/ranges.rs +755 -755
  80. package/vendor/quiche/src/recovery/AGENTS.md +80 -80
  81. package/vendor/quiche/src/recovery/bandwidth.rs +565 -565
  82. package/vendor/quiche/src/recovery/bytes_in_flight.rs +179 -179
  83. package/vendor/quiche/src/recovery/congestion/cubic.rs +1038 -1038
  84. package/vendor/quiche/src/recovery/congestion/delivery_rate.rs +514 -514
  85. package/vendor/quiche/src/recovery/congestion/hystart.rs +241 -241
  86. package/vendor/quiche/src/recovery/congestion/mod.rs +361 -361
  87. package/vendor/quiche/src/recovery/congestion/prr.rs +238 -238
  88. package/vendor/quiche/src/recovery/congestion/recovery.rs +1170 -1170
  89. package/vendor/quiche/src/recovery/congestion/reno.rs +291 -291
  90. package/vendor/quiche/src/recovery/congestion/test_sender.rs +201 -201
  91. package/vendor/quiche/src/recovery/gcongestion/bbr/bandwidth_sampler.rs +1947 -1947
  92. package/vendor/quiche/src/recovery/gcongestion/bbr/windowed_filter.rs +158 -158
  93. package/vendor/quiche/src/recovery/gcongestion/bbr.rs +37 -37
  94. package/vendor/quiche/src/recovery/gcongestion/bbr2/drain.rs +120 -120
  95. package/vendor/quiche/src/recovery/gcongestion/bbr2/mode.rs +318 -318
  96. package/vendor/quiche/src/recovery/gcongestion/bbr2/network_model.rs +784 -784
  97. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_bw.rs +729 -729
  98. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_rtt.rs +175 -175
  99. package/vendor/quiche/src/recovery/gcongestion/bbr2/startup.rs +190 -190
  100. package/vendor/quiche/src/recovery/gcongestion/bbr2.rs +855 -855
  101. package/vendor/quiche/src/recovery/gcongestion/mod.rs +275 -275
  102. package/vendor/quiche/src/recovery/gcongestion/pacer.rs +294 -294
  103. package/vendor/quiche/src/recovery/gcongestion/recovery.rs +1384 -1384
  104. package/vendor/quiche/src/recovery/mod.rs +3086 -3086
  105. package/vendor/quiche/src/recovery/rtt.rs +152 -152
  106. package/vendor/quiche/src/stream/mod.rs +2210 -2210
  107. package/vendor/quiche/src/stream/recv_buf.rs +1236 -1236
  108. package/vendor/quiche/src/stream/send_buf.rs +849 -849
  109. package/vendor/quiche/src/test_utils.rs +681 -681
  110. package/vendor/quiche/src/tests.rs +12922 -12922
  111. package/vendor/quiche/src/tls/boringssl.rs +375 -375
  112. package/vendor/quiche/src/tls/mod.rs +1245 -1245
  113. package/vendor/quiche/src/transport_params.rs +628 -628
@@ -1,463 +1,463 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- //! The per-session driver thread: a mio event loop that owns the UDP socket and
3
- //! the quiche connection, feeds packets to [`crate::session::WtSession`], and
4
- //! ferries commands in and events out.
5
-
6
- use std::net::{SocketAddr, ToSocketAddrs};
7
- use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering};
8
- use std::sync::mpsc::Receiver;
9
- use std::sync::Arc;
10
- use std::time::Instant;
11
-
12
- use mio::net::UdpSocket;
13
- use mio::{Events, Poll, Token};
14
-
15
- use crate::config::{build_config, ClientConfigParams};
16
- use crate::session::{Ev, WtSession};
17
-
18
- pub const SOCKET_TOKEN: Token = Token(0);
19
- pub const WAKE_TOKEN: Token = Token(1);
20
-
21
- /// Max number of event batches that may be in flight to the JS event loop before
22
- /// the driver stops pulling high-volume data (datagrams + WebTransport stream
23
- /// bytes) out of quiche. This bounds the neon Channel / libuv queue so a hostile
24
- /// server flooding datagrams or stream data cannot grow it without limit (OOM).
25
- /// When exceeded, unread stream data stays in quiche (flow-controlling the peer)
26
- /// and excess datagrams are dropped by quiche's bounded recv queue.
27
- const MAX_INFLIGHT_BATCHES: i64 = 128;
28
-
29
- /// State shared between the driver thread and the JS-facing handle so that
30
- /// synchronous property reads (e.g. `datagrams.maxDatagramSize`) don't require a
31
- /// round trip through the command channel.
32
- #[derive(Default)]
33
- pub struct DriverShared {
34
- pub max_datagram_size: AtomicUsize,
35
- pub ready: AtomicBool,
36
- pub closed: AtomicBool,
37
- /// Event batches emitted but not yet processed by the JS thread. Incremented
38
- /// by the sink before `Channel::send`, decremented inside the JS callback.
39
- pub inflight: AtomicI64,
40
- }
41
-
42
- /// Commands sent from JS (via the neon layer) into the driver thread.
43
- pub enum Command {
44
- OpenStream {
45
- request_id: u64,
46
- bidi: bool,
47
- },
48
- Write {
49
- id: u64,
50
- data: Vec<u8>,
51
- request_id: u64,
52
- },
53
- Fin {
54
- id: u64,
55
- },
56
- ResetStream {
57
- id: u64,
58
- code: u64,
59
- },
60
- StopSending {
61
- id: u64,
62
- code: u64,
63
- },
64
- SetPaused {
65
- id: u64,
66
- paused: bool,
67
- },
68
- SendDatagram {
69
- data: Vec<u8>,
70
- request_id: u64,
71
- },
72
- Close {
73
- code: u32,
74
- reason: Vec<u8>,
75
- },
76
- /// Tear the driver down (the JS handle was closed/GC'd).
77
- Shutdown,
78
- }
79
-
80
- /// Sink for events produced by the driver. Implemented by the neon layer using a
81
- /// `neon::event::Channel`.
82
- pub trait EventSink: Send {
83
- fn emit(&self, events: Vec<Ev>);
84
- }
85
-
86
- /// Everything the driver thread needs to establish a session. DNS resolution,
87
- /// socket bind, TLS/QUIC config, and the quiche handshake all happen on the
88
- /// driver thread (never on the JS event loop).
89
- pub struct SessionSetup {
90
- pub host: String,
91
- pub port: u16,
92
- /// SNI / verification host (None for IP literals).
93
- pub sni: Option<String>,
94
- pub authority: String,
95
- pub path: String,
96
- pub origin: Option<String>,
97
- pub extra_headers: Vec<(String, String)>,
98
- pub config: ClientConfigParams,
99
- }
100
-
101
- /// Entry point for the driver thread. Wraps setup + the event loop in
102
- /// `catch_unwind` so that a panic anywhere (DNS, bind, quiche, the loop) can
103
- /// NEVER crash the Node process and can NEVER silently hang the session: on
104
- /// panic (or a setup failure) we emit an `error` event followed by `closed`, so
105
- /// the JS `ready`/`closed` promises reject.
106
- pub fn run(
107
- setup: SessionSetup,
108
- poll: Poll,
109
- rx: Receiver<Command>,
110
- sink: Box<dyn EventSink>,
111
- shared: Arc<DriverShared>,
112
- ) {
113
- let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
114
- setup_and_run(setup, poll, rx, sink.as_ref(), &shared);
115
- }));
116
- if let Err(payload) = result {
117
- let msg = payload
118
- .downcast_ref::<&str>()
119
- .map(|s| (*s).to_string())
120
- .or_else(|| payload.downcast_ref::<String>().cloned())
121
- .unwrap_or_else(|| "unknown panic".to_string());
122
- shared.closed.store(true, Ordering::Relaxed);
123
- sink.emit(vec![
124
- Ev::Error(format!("rwebtransport internal driver error: {msg}")),
125
- Ev::Closed {
126
- code: 0,
127
- reason: b"driver panic".to_vec(),
128
- remote: false,
129
- },
130
- ]);
131
- }
132
- }
133
-
134
- /// Emit a fatal setup error to JS and mark the session closed.
135
- fn emit_fatal(sink: &dyn EventSink, shared: &Arc<DriverShared>, message: String) {
136
- shared.closed.store(true, Ordering::Relaxed);
137
- sink.emit(vec![
138
- Ev::Error(message),
139
- Ev::Closed {
140
- code: 0,
141
- reason: b"setup failed".to_vec(),
142
- remote: false,
143
- },
144
- ]);
145
- }
146
-
147
- fn random_scid() -> [u8; 16] {
148
- let mut b = [0u8; 16];
149
- if getrandom::getrandom(&mut b).is_err() {
150
- let seed: u128 = std::time::SystemTime::now()
151
- .duration_since(std::time::UNIX_EPOCH)
152
- .map(|d| d.as_nanos())
153
- .unwrap_or(0);
154
- b.copy_from_slice(&seed.to_le_bytes());
155
- }
156
- b
157
- }
158
-
159
- /// Resolve DNS, bind the UDP socket, build the QUIC config, perform the handshake
160
- /// handshake, then run the event loop. Any setup failure is surfaced to JS.
161
- fn setup_and_run(
162
- setup: SessionSetup,
163
- poll: Poll,
164
- rx: Receiver<Command>,
165
- sink: &dyn EventSink,
166
- shared: &Arc<DriverShared>,
167
- ) {
168
- // DNS resolution — potentially blocking, so it runs here (driver thread),
169
- // never on the JS event loop.
170
- let peer = match (setup.host.as_str(), setup.port)
171
- .to_socket_addrs()
172
- .ok()
173
- .and_then(|mut it| it.next())
174
- {
175
- Some(p) => p,
176
- None => {
177
- emit_fatal(
178
- sink,
179
- shared,
180
- format!("failed to resolve {}:{}", setup.host, setup.port),
181
- );
182
- return;
183
- }
184
- };
185
-
186
- let bind: SocketAddr = if peer.is_ipv4() {
187
- "0.0.0.0:0".parse().unwrap()
188
- } else {
189
- "[::]:0".parse().unwrap()
190
- };
191
- let socket = match UdpSocket::bind(bind) {
192
- Ok(s) => s,
193
- Err(e) => {
194
- emit_fatal(sink, shared, format!("failed to bind UDP socket: {e}"));
195
- return;
196
- }
197
- };
198
- let local_addr = match socket.local_addr() {
199
- Ok(a) => a,
200
- Err(e) => {
201
- emit_fatal(sink, shared, format!("failed to read local addr: {e}"));
202
- return;
203
- }
204
- };
205
-
206
- let mut config = match build_config(&setup.config) {
207
- Ok(c) => c,
208
- Err(e) => {
209
- emit_fatal(sink, shared, e);
210
- return;
211
- }
212
- };
213
-
214
- let scid = random_scid();
215
- let scid = quiche::ConnectionId::from_ref(&scid);
216
- let conn = match quiche::connect(setup.sni.as_deref(), &scid, local_addr, peer, &mut config) {
217
- Ok(c) => c,
218
- Err(e) => {
219
- emit_fatal(sink, shared, format!("quiche connect: {e:?}"));
220
- return;
221
- }
222
- };
223
-
224
- let session = WtSession::new_client(
225
- setup.authority,
226
- setup.path,
227
- setup.origin,
228
- setup.extra_headers,
229
- );
230
-
231
- run_inner(poll, socket, local_addr, conn, session, rx, sink, shared);
232
- }
233
-
234
- /// The actual event loop. Runs until the connection closes or a fatal error
235
- /// occurs. Never call this directly from the spawned thread — go through
236
- /// [`run`], which contains the panic boundary.
237
- #[allow(clippy::too_many_arguments)]
238
- fn run_inner(
239
- mut poll: Poll,
240
- mut socket: UdpSocket,
241
- local_addr: std::net::SocketAddr,
242
- mut conn: quiche::Connection,
243
- mut session: WtSession,
244
- rx: Receiver<Command>,
245
- sink: &dyn EventSink,
246
- shared: &Arc<DriverShared>,
247
- ) {
248
- if let Err(e) = poll
249
- .registry()
250
- .register(&mut socket, SOCKET_TOKEN, mio::Interest::READABLE)
251
- {
252
- sink.emit(vec![Ev::Error(format!("failed to register socket: {e}"))]);
253
- return;
254
- }
255
-
256
- let mut events = Events::with_capacity(1024);
257
- let mut recv_buf = vec![0u8; 65_535];
258
- let mut send_buf = vec![0u8; 1350];
259
-
260
- let debug = std::env::var("RWT_DEBUG").is_ok();
261
- // Read once per driver thread (each session spawns a fresh thread), so tests
262
- // can arm/disarm it per-connection via the environment.
263
- let test_panic = std::env::var("RWT_TEST_PANIC").is_ok();
264
- let mut established_logged = false;
265
- if debug {
266
- eprintln!("[rwt-driver] start local={local_addr}");
267
- }
268
-
269
- // Prime the handshake (send the client Initial).
270
- flush_send(&mut conn, &socket, &mut send_buf, debug);
271
-
272
- loop {
273
- let timeout = conn.timeout();
274
- if let Err(e) = poll.poll(&mut events, timeout) {
275
- if e.kind() == std::io::ErrorKind::Interrupted {
276
- continue;
277
- }
278
- sink.emit(vec![Ev::Error(format!("poll error: {e}"))]);
279
- return;
280
- }
281
-
282
- let mut evs: Vec<Ev> = Vec::new();
283
- let mut shutdown = false;
284
-
285
- // 1. Read all datagrams the socket has.
286
- let mut got_packet = false;
287
- loop {
288
- match socket.recv_from(&mut recv_buf) {
289
- Ok((len, from)) => {
290
- got_packet = true;
291
- if debug {
292
- eprintln!("[rwt-driver] recv {len} bytes from {from}");
293
- }
294
- let info = quiche::RecvInfo {
295
- from,
296
- to: local_addr,
297
- };
298
- match conn.recv(&mut recv_buf[..len], info) {
299
- Ok(_) => {}
300
- Err(quiche::Error::Done) => {}
301
- Err(e) => {
302
- if debug {
303
- eprintln!("[rwt-driver] recv err {e:?}");
304
- }
305
- evs.push(Ev::Error(format!("quic recv: {e:?}")));
306
- }
307
- }
308
- }
309
- Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
310
- Err(e) => {
311
- evs.push(Ev::Error(format!("socket recv: {e}")));
312
- break;
313
- }
314
- }
315
- }
316
-
317
- // 2. Fire the timeout if nothing else woke us.
318
- if !got_packet && events.is_empty() {
319
- conn.on_timeout();
320
- }
321
-
322
- // 3. Drain commands.
323
- while let Ok(cmd) = rx.try_recv() {
324
- match cmd {
325
- Command::OpenStream { request_id, bidi } => {
326
- session.open_stream(bidi, request_id, &mut evs)
327
- }
328
- Command::Write {
329
- id,
330
- data,
331
- request_id,
332
- } => session.stream_write(id, data, request_id, &mut evs),
333
- Command::Fin { id } => session.stream_fin(id),
334
- Command::ResetStream { id, code } => session.stream_reset(&mut conn, id, code),
335
- Command::StopSending { id, code } => {
336
- session.stream_stop_sending(&mut conn, id, code)
337
- }
338
- Command::SetPaused { id, paused } => session.set_paused(id, paused),
339
- Command::SendDatagram { data, request_id } => {
340
- session.send_datagram(&mut conn, &data, request_id, &mut evs)
341
- }
342
- Command::Close { code, reason } => session.close(code, reason),
343
- Command::Shutdown => {
344
- shutdown = true;
345
- break;
346
- }
347
- }
348
- }
349
-
350
- if shutdown {
351
- let _ = conn.close(true, 0, b"");
352
- flush_send(&mut conn, &socket, &mut send_buf, debug);
353
- return;
354
- }
355
-
356
- // 4. Drive the session forward.
357
- if conn.is_established() {
358
- // Test-only hook: prove that a panic on the driver thread is
359
- // contained (rejects ready/closed, never crashes Node). Gated behind
360
- // an env var so it is inert in production.
361
- if test_panic {
362
- panic!("RWT_TEST_PANIC: intentional driver-thread panic for containment testing");
363
- }
364
- if debug && !established_logged {
365
- established_logged = true;
366
- eprintln!(
367
- "[rwt-driver] QUIC established, alpn={:?}",
368
- conn.application_proto()
369
- );
370
- }
371
- session.on_established(&mut evs);
372
- }
373
-
374
- // Backpressure: if the JS thread is behind on processing events, stop
375
- // pulling high-volume data out of quiche this iteration. Unread stream
376
- // bytes stay flow-controlled in quiche and excess datagrams are dropped
377
- // by quiche's bounded recv queue, so the event queue cannot grow without
378
- // bound (hostile-flood OOM protection). Control-plane processing (the
379
- // CONNECT response, SETTINGS, session close) always runs.
380
- let backpressured = shared.inflight.load(Ordering::Relaxed) >= MAX_INFLIGHT_BATCHES;
381
-
382
- if !backpressured {
383
- session.on_datagrams(&mut conn, &mut evs);
384
- }
385
-
386
- let readable: Vec<u64> = conn.readable().collect();
387
- for id in readable {
388
- session.on_readable(&mut conn, id, backpressured, &mut evs);
389
- }
390
-
391
- session.flush(&mut conn, &mut evs);
392
-
393
- // 5. Send everything queued.
394
- flush_send(&mut conn, &socket, &mut send_buf, debug);
395
-
396
- // Publish synchronously-readable state.
397
- shared
398
- .max_datagram_size
399
- .store(session.max_datagram_size(&conn), Ordering::Relaxed);
400
- shared.ready.store(session.is_ready(), Ordering::Relaxed);
401
-
402
- // 6. Terminal state?
403
- if conn.is_closed() {
404
- if !session.is_closed() {
405
- let (code, reason, remote) = closure_info(&conn);
406
- session.mark_closed(&mut evs, code, reason, remote);
407
- }
408
- shared.closed.store(true, Ordering::Relaxed);
409
- if !evs.is_empty() {
410
- sink.emit(evs);
411
- }
412
- return;
413
- }
414
-
415
- if !evs.is_empty() {
416
- sink.emit(evs);
417
- }
418
- }
419
- }
420
-
421
- /// Drain quiche's send queue to the socket.
422
- fn flush_send(conn: &mut quiche::Connection, socket: &UdpSocket, out: &mut [u8], debug: bool) {
423
- loop {
424
- match conn.send(out) {
425
- Ok((write, info)) => {
426
- // Ignore pacing (`info.at`); send immediately.
427
- let _ = info.at;
428
- if debug {
429
- eprintln!("[rwt-driver] send {write} bytes to {}", info.to);
430
- }
431
- if let Err(e) = socket.send_to(&out[..write], info.to) {
432
- if debug {
433
- eprintln!("[rwt-driver] send_to err {e}");
434
- }
435
- if e.kind() == std::io::ErrorKind::WouldBlock {
436
- // Socket buffer full; try again on the next wake.
437
- return;
438
- }
439
- }
440
- }
441
- Err(quiche::Error::Done) => return,
442
- Err(e) => {
443
- if debug {
444
- eprintln!("[rwt-driver] send err {e:?}");
445
- }
446
- return;
447
- }
448
- }
449
- }
450
- }
451
-
452
- /// Extract a close code/reason from a terminated connection.
453
- fn closure_info(conn: &quiche::Connection) -> (u32, Vec<u8>, bool) {
454
- if let Some(err) = conn.peer_error() {
455
- return (err.error_code as u32, err.reason.clone(), true);
456
- }
457
- if let Some(err) = conn.local_error() {
458
- return (err.error_code as u32, err.reason.clone(), false);
459
- }
460
- // Idle timeout / no explicit error.
461
- let _ = Instant::now();
462
- (0, Vec::new(), true)
463
- }
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ //! The per-session driver thread: a mio event loop that owns the UDP socket and
3
+ //! the quiche connection, feeds packets to [`crate::session::WtSession`], and
4
+ //! ferries commands in and events out.
5
+
6
+ use std::net::{SocketAddr, ToSocketAddrs};
7
+ use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering};
8
+ use std::sync::mpsc::Receiver;
9
+ use std::sync::Arc;
10
+ use std::time::Instant;
11
+
12
+ use mio::net::UdpSocket;
13
+ use mio::{Events, Poll, Token};
14
+
15
+ use crate::config::{build_config, ClientConfigParams};
16
+ use crate::session::{Ev, WtSession};
17
+
18
+ pub const SOCKET_TOKEN: Token = Token(0);
19
+ pub const WAKE_TOKEN: Token = Token(1);
20
+
21
+ /// Max number of event batches that may be in flight to the JS event loop before
22
+ /// the driver stops pulling high-volume data (datagrams + WebTransport stream
23
+ /// bytes) out of quiche. This bounds the neon Channel / libuv queue so a hostile
24
+ /// server flooding datagrams or stream data cannot grow it without limit (OOM).
25
+ /// When exceeded, unread stream data stays in quiche (flow-controlling the peer)
26
+ /// and excess datagrams are dropped by quiche's bounded recv queue.
27
+ const MAX_INFLIGHT_BATCHES: i64 = 128;
28
+
29
+ /// State shared between the driver thread and the JS-facing handle so that
30
+ /// synchronous property reads (e.g. `datagrams.maxDatagramSize`) don't require a
31
+ /// round trip through the command channel.
32
+ #[derive(Default)]
33
+ pub struct DriverShared {
34
+ pub max_datagram_size: AtomicUsize,
35
+ pub ready: AtomicBool,
36
+ pub closed: AtomicBool,
37
+ /// Event batches emitted but not yet processed by the JS thread. Incremented
38
+ /// by the sink before `Channel::send`, decremented inside the JS callback.
39
+ pub inflight: AtomicI64,
40
+ }
41
+
42
+ /// Commands sent from JS (via the neon layer) into the driver thread.
43
+ pub enum Command {
44
+ OpenStream {
45
+ request_id: u64,
46
+ bidi: bool,
47
+ },
48
+ Write {
49
+ id: u64,
50
+ data: Vec<u8>,
51
+ request_id: u64,
52
+ },
53
+ Fin {
54
+ id: u64,
55
+ },
56
+ ResetStream {
57
+ id: u64,
58
+ code: u64,
59
+ },
60
+ StopSending {
61
+ id: u64,
62
+ code: u64,
63
+ },
64
+ SetPaused {
65
+ id: u64,
66
+ paused: bool,
67
+ },
68
+ SendDatagram {
69
+ data: Vec<u8>,
70
+ request_id: u64,
71
+ },
72
+ Close {
73
+ code: u32,
74
+ reason: Vec<u8>,
75
+ },
76
+ /// Tear the driver down (the JS handle was closed/GC'd).
77
+ Shutdown,
78
+ }
79
+
80
+ /// Sink for events produced by the driver. Implemented by the neon layer using a
81
+ /// `neon::event::Channel`.
82
+ pub trait EventSink: Send {
83
+ fn emit(&self, events: Vec<Ev>);
84
+ }
85
+
86
+ /// Everything the driver thread needs to establish a session. DNS resolution,
87
+ /// socket bind, TLS/QUIC config, and the quiche handshake all happen on the
88
+ /// driver thread (never on the JS event loop).
89
+ pub struct SessionSetup {
90
+ pub host: String,
91
+ pub port: u16,
92
+ /// SNI / verification host (None for IP literals).
93
+ pub sni: Option<String>,
94
+ pub authority: String,
95
+ pub path: String,
96
+ pub origin: Option<String>,
97
+ pub extra_headers: Vec<(String, String)>,
98
+ pub config: ClientConfigParams,
99
+ }
100
+
101
+ /// Entry point for the driver thread. Wraps setup + the event loop in
102
+ /// `catch_unwind` so that a panic anywhere (DNS, bind, quiche, the loop) can
103
+ /// NEVER crash the Node process and can NEVER silently hang the session: on
104
+ /// panic (or a setup failure) we emit an `error` event followed by `closed`, so
105
+ /// the JS `ready`/`closed` promises reject.
106
+ pub fn run(
107
+ setup: SessionSetup,
108
+ poll: Poll,
109
+ rx: Receiver<Command>,
110
+ sink: Box<dyn EventSink>,
111
+ shared: Arc<DriverShared>,
112
+ ) {
113
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
114
+ setup_and_run(setup, poll, rx, sink.as_ref(), &shared);
115
+ }));
116
+ if let Err(payload) = result {
117
+ let msg = payload
118
+ .downcast_ref::<&str>()
119
+ .map(|s| (*s).to_string())
120
+ .or_else(|| payload.downcast_ref::<String>().cloned())
121
+ .unwrap_or_else(|| "unknown panic".to_string());
122
+ shared.closed.store(true, Ordering::Relaxed);
123
+ sink.emit(vec![
124
+ Ev::Error(format!("rwebtransport internal driver error: {msg}")),
125
+ Ev::Closed {
126
+ code: 0,
127
+ reason: b"driver panic".to_vec(),
128
+ remote: false,
129
+ },
130
+ ]);
131
+ }
132
+ }
133
+
134
+ /// Emit a fatal setup error to JS and mark the session closed.
135
+ fn emit_fatal(sink: &dyn EventSink, shared: &Arc<DriverShared>, message: String) {
136
+ shared.closed.store(true, Ordering::Relaxed);
137
+ sink.emit(vec![
138
+ Ev::Error(message),
139
+ Ev::Closed {
140
+ code: 0,
141
+ reason: b"setup failed".to_vec(),
142
+ remote: false,
143
+ },
144
+ ]);
145
+ }
146
+
147
+ fn random_scid() -> [u8; 16] {
148
+ let mut b = [0u8; 16];
149
+ if getrandom::getrandom(&mut b).is_err() {
150
+ let seed: u128 = std::time::SystemTime::now()
151
+ .duration_since(std::time::UNIX_EPOCH)
152
+ .map(|d| d.as_nanos())
153
+ .unwrap_or(0);
154
+ b.copy_from_slice(&seed.to_le_bytes());
155
+ }
156
+ b
157
+ }
158
+
159
+ /// Resolve DNS, bind the UDP socket, build the QUIC config, perform the handshake
160
+ /// handshake, then run the event loop. Any setup failure is surfaced to JS.
161
+ fn setup_and_run(
162
+ setup: SessionSetup,
163
+ poll: Poll,
164
+ rx: Receiver<Command>,
165
+ sink: &dyn EventSink,
166
+ shared: &Arc<DriverShared>,
167
+ ) {
168
+ // DNS resolution — potentially blocking, so it runs here (driver thread),
169
+ // never on the JS event loop.
170
+ let peer = match (setup.host.as_str(), setup.port)
171
+ .to_socket_addrs()
172
+ .ok()
173
+ .and_then(|mut it| it.next())
174
+ {
175
+ Some(p) => p,
176
+ None => {
177
+ emit_fatal(
178
+ sink,
179
+ shared,
180
+ format!("failed to resolve {}:{}", setup.host, setup.port),
181
+ );
182
+ return;
183
+ }
184
+ };
185
+
186
+ let bind: SocketAddr = if peer.is_ipv4() {
187
+ "0.0.0.0:0".parse().unwrap()
188
+ } else {
189
+ "[::]:0".parse().unwrap()
190
+ };
191
+ let socket = match UdpSocket::bind(bind) {
192
+ Ok(s) => s,
193
+ Err(e) => {
194
+ emit_fatal(sink, shared, format!("failed to bind UDP socket: {e}"));
195
+ return;
196
+ }
197
+ };
198
+ let local_addr = match socket.local_addr() {
199
+ Ok(a) => a,
200
+ Err(e) => {
201
+ emit_fatal(sink, shared, format!("failed to read local addr: {e}"));
202
+ return;
203
+ }
204
+ };
205
+
206
+ let mut config = match build_config(&setup.config) {
207
+ Ok(c) => c,
208
+ Err(e) => {
209
+ emit_fatal(sink, shared, e);
210
+ return;
211
+ }
212
+ };
213
+
214
+ let scid = random_scid();
215
+ let scid = quiche::ConnectionId::from_ref(&scid);
216
+ let conn = match quiche::connect(setup.sni.as_deref(), &scid, local_addr, peer, &mut config) {
217
+ Ok(c) => c,
218
+ Err(e) => {
219
+ emit_fatal(sink, shared, format!("quiche connect: {e:?}"));
220
+ return;
221
+ }
222
+ };
223
+
224
+ let session = WtSession::new_client(
225
+ setup.authority,
226
+ setup.path,
227
+ setup.origin,
228
+ setup.extra_headers,
229
+ );
230
+
231
+ run_inner(poll, socket, local_addr, conn, session, rx, sink, shared);
232
+ }
233
+
234
+ /// The actual event loop. Runs until the connection closes or a fatal error
235
+ /// occurs. Never call this directly from the spawned thread — go through
236
+ /// [`run`], which contains the panic boundary.
237
+ #[allow(clippy::too_many_arguments)]
238
+ fn run_inner(
239
+ mut poll: Poll,
240
+ mut socket: UdpSocket,
241
+ local_addr: std::net::SocketAddr,
242
+ mut conn: quiche::Connection,
243
+ mut session: WtSession,
244
+ rx: Receiver<Command>,
245
+ sink: &dyn EventSink,
246
+ shared: &Arc<DriverShared>,
247
+ ) {
248
+ if let Err(e) = poll
249
+ .registry()
250
+ .register(&mut socket, SOCKET_TOKEN, mio::Interest::READABLE)
251
+ {
252
+ sink.emit(vec![Ev::Error(format!("failed to register socket: {e}"))]);
253
+ return;
254
+ }
255
+
256
+ let mut events = Events::with_capacity(1024);
257
+ let mut recv_buf = vec![0u8; 65_535];
258
+ let mut send_buf = vec![0u8; 1350];
259
+
260
+ let debug = std::env::var("RWT_DEBUG").is_ok();
261
+ // Read once per driver thread (each session spawns a fresh thread), so tests
262
+ // can arm/disarm it per-connection via the environment.
263
+ let test_panic = std::env::var("RWT_TEST_PANIC").is_ok();
264
+ let mut established_logged = false;
265
+ if debug {
266
+ eprintln!("[rwt-driver] start local={local_addr}");
267
+ }
268
+
269
+ // Prime the handshake (send the client Initial).
270
+ flush_send(&mut conn, &socket, &mut send_buf, debug);
271
+
272
+ loop {
273
+ let timeout = conn.timeout();
274
+ if let Err(e) = poll.poll(&mut events, timeout) {
275
+ if e.kind() == std::io::ErrorKind::Interrupted {
276
+ continue;
277
+ }
278
+ sink.emit(vec![Ev::Error(format!("poll error: {e}"))]);
279
+ return;
280
+ }
281
+
282
+ let mut evs: Vec<Ev> = Vec::new();
283
+ let mut shutdown = false;
284
+
285
+ // 1. Read all datagrams the socket has.
286
+ let mut got_packet = false;
287
+ loop {
288
+ match socket.recv_from(&mut recv_buf) {
289
+ Ok((len, from)) => {
290
+ got_packet = true;
291
+ if debug {
292
+ eprintln!("[rwt-driver] recv {len} bytes from {from}");
293
+ }
294
+ let info = quiche::RecvInfo {
295
+ from,
296
+ to: local_addr,
297
+ };
298
+ match conn.recv(&mut recv_buf[..len], info) {
299
+ Ok(_) => {}
300
+ Err(quiche::Error::Done) => {}
301
+ Err(e) => {
302
+ if debug {
303
+ eprintln!("[rwt-driver] recv err {e:?}");
304
+ }
305
+ evs.push(Ev::Error(format!("quic recv: {e:?}")));
306
+ }
307
+ }
308
+ }
309
+ Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
310
+ Err(e) => {
311
+ evs.push(Ev::Error(format!("socket recv: {e}")));
312
+ break;
313
+ }
314
+ }
315
+ }
316
+
317
+ // 2. Fire the timeout if nothing else woke us.
318
+ if !got_packet && events.is_empty() {
319
+ conn.on_timeout();
320
+ }
321
+
322
+ // 3. Drain commands.
323
+ while let Ok(cmd) = rx.try_recv() {
324
+ match cmd {
325
+ Command::OpenStream { request_id, bidi } => {
326
+ session.open_stream(bidi, request_id, &mut evs)
327
+ }
328
+ Command::Write {
329
+ id,
330
+ data,
331
+ request_id,
332
+ } => session.stream_write(id, data, request_id, &mut evs),
333
+ Command::Fin { id } => session.stream_fin(id),
334
+ Command::ResetStream { id, code } => session.stream_reset(&mut conn, id, code),
335
+ Command::StopSending { id, code } => {
336
+ session.stream_stop_sending(&mut conn, id, code)
337
+ }
338
+ Command::SetPaused { id, paused } => session.set_paused(id, paused),
339
+ Command::SendDatagram { data, request_id } => {
340
+ session.send_datagram(&mut conn, &data, request_id, &mut evs)
341
+ }
342
+ Command::Close { code, reason } => session.close(code, reason),
343
+ Command::Shutdown => {
344
+ shutdown = true;
345
+ break;
346
+ }
347
+ }
348
+ }
349
+
350
+ if shutdown {
351
+ let _ = conn.close(true, 0, b"");
352
+ flush_send(&mut conn, &socket, &mut send_buf, debug);
353
+ return;
354
+ }
355
+
356
+ // 4. Drive the session forward.
357
+ if conn.is_established() {
358
+ // Test-only hook: prove that a panic on the driver thread is
359
+ // contained (rejects ready/closed, never crashes Node). Gated behind
360
+ // an env var so it is inert in production.
361
+ if test_panic {
362
+ panic!("RWT_TEST_PANIC: intentional driver-thread panic for containment testing");
363
+ }
364
+ if debug && !established_logged {
365
+ established_logged = true;
366
+ eprintln!(
367
+ "[rwt-driver] QUIC established, alpn={:?}",
368
+ conn.application_proto()
369
+ );
370
+ }
371
+ session.on_established(&mut evs);
372
+ }
373
+
374
+ // Backpressure: if the JS thread is behind on processing events, stop
375
+ // pulling high-volume data out of quiche this iteration. Unread stream
376
+ // bytes stay flow-controlled in quiche and excess datagrams are dropped
377
+ // by quiche's bounded recv queue, so the event queue cannot grow without
378
+ // bound (hostile-flood OOM protection). Control-plane processing (the
379
+ // CONNECT response, SETTINGS, session close) always runs.
380
+ let backpressured = shared.inflight.load(Ordering::Relaxed) >= MAX_INFLIGHT_BATCHES;
381
+
382
+ if !backpressured {
383
+ session.on_datagrams(&mut conn, &mut evs);
384
+ }
385
+
386
+ let readable: Vec<u64> = conn.readable().collect();
387
+ for id in readable {
388
+ session.on_readable(&mut conn, id, backpressured, &mut evs);
389
+ }
390
+
391
+ session.flush(&mut conn, &mut evs);
392
+
393
+ // 5. Send everything queued.
394
+ flush_send(&mut conn, &socket, &mut send_buf, debug);
395
+
396
+ // Publish synchronously-readable state.
397
+ shared
398
+ .max_datagram_size
399
+ .store(session.max_datagram_size(&conn), Ordering::Relaxed);
400
+ shared.ready.store(session.is_ready(), Ordering::Relaxed);
401
+
402
+ // 6. Terminal state?
403
+ if conn.is_closed() {
404
+ if !session.is_closed() {
405
+ let (code, reason, remote) = closure_info(&conn);
406
+ session.mark_closed(&mut evs, code, reason, remote);
407
+ }
408
+ shared.closed.store(true, Ordering::Relaxed);
409
+ if !evs.is_empty() {
410
+ sink.emit(evs);
411
+ }
412
+ return;
413
+ }
414
+
415
+ if !evs.is_empty() {
416
+ sink.emit(evs);
417
+ }
418
+ }
419
+ }
420
+
421
+ /// Drain quiche's send queue to the socket.
422
+ fn flush_send(conn: &mut quiche::Connection, socket: &UdpSocket, out: &mut [u8], debug: bool) {
423
+ loop {
424
+ match conn.send(out) {
425
+ Ok((write, info)) => {
426
+ // Ignore pacing (`info.at`); send immediately.
427
+ let _ = info.at;
428
+ if debug {
429
+ eprintln!("[rwt-driver] send {write} bytes to {}", info.to);
430
+ }
431
+ if let Err(e) = socket.send_to(&out[..write], info.to) {
432
+ if debug {
433
+ eprintln!("[rwt-driver] send_to err {e}");
434
+ }
435
+ if e.kind() == std::io::ErrorKind::WouldBlock {
436
+ // Socket buffer full; try again on the next wake.
437
+ return;
438
+ }
439
+ }
440
+ }
441
+ Err(quiche::Error::Done) => return,
442
+ Err(e) => {
443
+ if debug {
444
+ eprintln!("[rwt-driver] send err {e:?}");
445
+ }
446
+ return;
447
+ }
448
+ }
449
+ }
450
+ }
451
+
452
+ /// Extract a close code/reason from a terminated connection.
453
+ fn closure_info(conn: &quiche::Connection) -> (u32, Vec<u8>, bool) {
454
+ if let Some(err) = conn.peer_error() {
455
+ return (err.error_code as u32, err.reason.clone(), true);
456
+ }
457
+ if let Some(err) = conn.local_error() {
458
+ return (err.error_code as u32, err.reason.clone(), false);
459
+ }
460
+ // Idle timeout / no explicit error.
461
+ let _ = Instant::now();
462
+ (0, Vec::new(), true)
463
+ }