rwebtransport 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/Cargo.lock +666 -0
  2. package/Cargo.toml +31 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +41 -0
  5. package/README.md +550 -0
  6. package/crates/echo-server/Cargo.toml +20 -0
  7. package/crates/echo-server/src/main.rs +666 -0
  8. package/crates/native/Cargo.toml +23 -0
  9. package/crates/native/src/config.rs +129 -0
  10. package/crates/native/src/driver.rs +463 -0
  11. package/crates/native/src/lib.rs +821 -0
  12. package/crates/native/src/server.rs +718 -0
  13. package/crates/native/src/session.rs +1191 -0
  14. package/crates/native/src/tls.rs +96 -0
  15. package/crates/wtcore/Cargo.toml +15 -0
  16. package/crates/wtcore/src/h3.rs +226 -0
  17. package/crates/wtcore/src/lib.rs +9 -0
  18. package/dist/datagrams.d.ts +16 -0
  19. package/dist/errors.d.ts +10 -0
  20. package/dist/index.d.ts +7 -0
  21. package/dist/index.js +1512 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/index.mjs +1473 -0
  24. package/dist/index.mjs.map +1 -0
  25. package/dist/loader.d.ts +2 -0
  26. package/dist/native.d.ts +226 -0
  27. package/dist/server.d.ts +44 -0
  28. package/dist/streams.d.ts +14 -0
  29. package/dist/types.d.ts +24 -0
  30. package/dist/webtransport.d.ts +20 -0
  31. package/package.json +79 -0
  32. package/prebuilds/win32-x64/rwebtransport.node +0 -0
  33. package/scripts/bench.mjs +180 -0
  34. package/scripts/build.js +67 -0
  35. package/scripts/postinstall.js +67 -0
  36. package/scripts/setup-unix.sh +129 -0
  37. package/scripts/setup-windows.ps1 +229 -0
  38. package/vendor/quiche/AGENTS.md +75 -0
  39. package/vendor/quiche/COPYING +23 -0
  40. package/vendor/quiche/Cargo.lock +1212 -0
  41. package/vendor/quiche/Cargo.toml +215 -0
  42. package/vendor/quiche/README.md +466 -0
  43. package/vendor/quiche/examples/Makefile +46 -0
  44. package/vendor/quiche/examples/README.md +20 -0
  45. package/vendor/quiche/examples/cert-big.crt +90 -0
  46. package/vendor/quiche/examples/cert.crt +18 -0
  47. package/vendor/quiche/examples/cert.key +28 -0
  48. package/vendor/quiche/examples/client.c +343 -0
  49. package/vendor/quiche/examples/client.rs +281 -0
  50. package/vendor/quiche/examples/gen-certs.sh +15 -0
  51. package/vendor/quiche/examples/http3-client.c +473 -0
  52. package/vendor/quiche/examples/http3-client.rs +349 -0
  53. package/vendor/quiche/examples/http3-server.c +614 -0
  54. package/vendor/quiche/examples/http3-server.rs +680 -0
  55. package/vendor/quiche/examples/qpack-decode.rs +87 -0
  56. package/vendor/quiche/examples/qpack-encode.rs +88 -0
  57. package/vendor/quiche/examples/rootca.crt +21 -0
  58. package/vendor/quiche/examples/server.c +529 -0
  59. package/vendor/quiche/examples/server.rs +529 -0
  60. package/vendor/quiche/include/quiche.h +1282 -0
  61. package/vendor/quiche/quiche.svg +1 -0
  62. package/vendor/quiche/src/buffers.rs +105 -0
  63. package/vendor/quiche/src/build.rs +66 -0
  64. package/vendor/quiche/src/cid.rs +1079 -0
  65. package/vendor/quiche/src/crypto/boringssl.rs +373 -0
  66. package/vendor/quiche/src/crypto/mod.rs +671 -0
  67. package/vendor/quiche/src/dgram.rs +118 -0
  68. package/vendor/quiche/src/error.rs +263 -0
  69. package/vendor/quiche/src/ffi.rs +2290 -0
  70. package/vendor/quiche/src/flowcontrol.rs +246 -0
  71. package/vendor/quiche/src/frame.rs +2172 -0
  72. package/vendor/quiche/src/h3/AGENTS.md +54 -0
  73. package/vendor/quiche/src/h3/ffi.rs +442 -0
  74. package/vendor/quiche/src/h3/frame.rs +1404 -0
  75. package/vendor/quiche/src/h3/mod.rs +8223 -0
  76. package/vendor/quiche/src/h3/qpack/decoder.rs +288 -0
  77. package/vendor/quiche/src/h3/qpack/encoder.rs +235 -0
  78. package/vendor/quiche/src/h3/qpack/mod.rs +202 -0
  79. package/vendor/quiche/src/h3/qpack/static_table.rs +323 -0
  80. package/vendor/quiche/src/h3/stream.rs +1595 -0
  81. package/vendor/quiche/src/lib.rs +9556 -0
  82. package/vendor/quiche/src/minmax.rs +446 -0
  83. package/vendor/quiche/src/packet.rs +2334 -0
  84. package/vendor/quiche/src/path.rs +1374 -0
  85. package/vendor/quiche/src/pmtud.rs +652 -0
  86. package/vendor/quiche/src/rand.rs +64 -0
  87. package/vendor/quiche/src/range_buf.rs +186 -0
  88. package/vendor/quiche/src/ranges.rs +755 -0
  89. package/vendor/quiche/src/recovery/AGENTS.md +80 -0
  90. package/vendor/quiche/src/recovery/bandwidth.rs +565 -0
  91. package/vendor/quiche/src/recovery/bytes_in_flight.rs +179 -0
  92. package/vendor/quiche/src/recovery/congestion/cubic.rs +1038 -0
  93. package/vendor/quiche/src/recovery/congestion/delivery_rate.rs +514 -0
  94. package/vendor/quiche/src/recovery/congestion/hystart.rs +241 -0
  95. package/vendor/quiche/src/recovery/congestion/mod.rs +361 -0
  96. package/vendor/quiche/src/recovery/congestion/prr.rs +238 -0
  97. package/vendor/quiche/src/recovery/congestion/recovery.rs +1170 -0
  98. package/vendor/quiche/src/recovery/congestion/reno.rs +291 -0
  99. package/vendor/quiche/src/recovery/congestion/test_sender.rs +201 -0
  100. package/vendor/quiche/src/recovery/gcongestion/bbr/bandwidth_sampler.rs +1947 -0
  101. package/vendor/quiche/src/recovery/gcongestion/bbr/windowed_filter.rs +158 -0
  102. package/vendor/quiche/src/recovery/gcongestion/bbr.rs +37 -0
  103. package/vendor/quiche/src/recovery/gcongestion/bbr2/drain.rs +120 -0
  104. package/vendor/quiche/src/recovery/gcongestion/bbr2/mode.rs +318 -0
  105. package/vendor/quiche/src/recovery/gcongestion/bbr2/network_model.rs +784 -0
  106. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_bw.rs +729 -0
  107. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_rtt.rs +175 -0
  108. package/vendor/quiche/src/recovery/gcongestion/bbr2/startup.rs +190 -0
  109. package/vendor/quiche/src/recovery/gcongestion/bbr2.rs +855 -0
  110. package/vendor/quiche/src/recovery/gcongestion/mod.rs +275 -0
  111. package/vendor/quiche/src/recovery/gcongestion/pacer.rs +294 -0
  112. package/vendor/quiche/src/recovery/gcongestion/recovery.rs +1384 -0
  113. package/vendor/quiche/src/recovery/mod.rs +3086 -0
  114. package/vendor/quiche/src/recovery/rtt.rs +152 -0
  115. package/vendor/quiche/src/stream/mod.rs +2210 -0
  116. package/vendor/quiche/src/stream/recv_buf.rs +1236 -0
  117. package/vendor/quiche/src/stream/send_buf.rs +849 -0
  118. package/vendor/quiche/src/test_utils.rs +681 -0
  119. package/vendor/quiche/src/tests.rs +12922 -0
  120. package/vendor/quiche/src/tls/boringssl.rs +375 -0
  121. package/vendor/quiche/src/tls/mod.rs +1245 -0
  122. package/vendor/quiche/src/transport_params.rs +628 -0
@@ -0,0 +1,681 @@
1
+ // Copyright (C) 2025, Cloudflare, Inc.
2
+ // All rights reserved.
3
+ //
4
+ // Redistribution and use in source and binary forms, with or without
5
+ // modification, are permitted provided that the following conditions are
6
+ // met:
7
+ //
8
+ // * Redistributions of source code must retain the above copyright notice,
9
+ // this list of conditions and the following disclaimer.
10
+ //
11
+ // * Redistributions in binary form must reproduce the above copyright
12
+ // notice, this list of conditions and the following disclaimer in the
13
+ // documentation and/or other materials provided with the distribution.
14
+ //
15
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16
+ // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17
+ // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18
+ // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19
+ // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20
+ // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21
+ // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22
+ // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23
+ // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24
+ // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25
+ // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
+
27
+ use super::*;
28
+
29
+ use smallvec::smallvec;
30
+
31
+ use crate::recovery::Sent;
32
+
33
+ pub struct Pipe<F = DefaultBufFactory>
34
+ where
35
+ F: BufFactory,
36
+ {
37
+ pub client: Connection<F>,
38
+ pub server: Connection<F>,
39
+ }
40
+
41
+ impl Pipe {
42
+ pub fn default_config(cc_algorithm_name: &str) -> Result<Config> {
43
+ let mut config = Config::new(PROTOCOL_VERSION)?;
44
+ assert_eq!(config.set_cc_algorithm_name(cc_algorithm_name), Ok(()));
45
+ config.load_cert_chain_from_pem_file("examples/cert.crt")?;
46
+ config.load_priv_key_from_pem_file("examples/cert.key")?;
47
+ config.set_application_protos(&[b"proto1", b"proto2"])?;
48
+ config.set_initial_max_data(30);
49
+ config.set_initial_max_stream_data_bidi_local(15);
50
+ config.set_initial_max_stream_data_bidi_remote(15);
51
+ config.set_initial_max_stream_data_uni(10);
52
+ config.set_initial_max_streams_bidi(3);
53
+ config.set_initial_max_streams_uni(3);
54
+ config.set_max_idle_timeout(180_000);
55
+ config.verify_peer(false);
56
+ config.set_ack_delay_exponent(8);
57
+ Ok(config)
58
+ }
59
+
60
+ #[cfg(feature = "boringssl-boring-crate")]
61
+ pub fn default_tls_ctx_builder() -> boring::ssl::SslContextBuilder {
62
+ let mut ctx_builder =
63
+ boring::ssl::SslContextBuilder::new(boring::ssl::SslMethod::tls())
64
+ .unwrap();
65
+ ctx_builder
66
+ .set_certificate_chain_file("examples/cert.crt")
67
+ .unwrap();
68
+ ctx_builder
69
+ .set_private_key_file(
70
+ "examples/cert.key",
71
+ boring::ssl::SslFiletype::PEM,
72
+ )
73
+ .unwrap();
74
+
75
+ ctx_builder
76
+ }
77
+
78
+ pub fn client_addr() -> SocketAddr {
79
+ "127.0.0.1:1234".parse().unwrap()
80
+ }
81
+
82
+ pub fn server_addr() -> SocketAddr {
83
+ "127.0.0.1:4321".parse().unwrap()
84
+ }
85
+
86
+ pub fn new(cc_algorithm_name: &str) -> Result<Pipe> {
87
+ let mut config = Self::default_config(cc_algorithm_name)?;
88
+ Pipe::with_config(&mut config)
89
+ }
90
+
91
+ pub fn with_config(config: &mut Config) -> Result<Pipe> {
92
+ Pipe::<DefaultBufFactory>::with_config_and_buf(config)
93
+ }
94
+
95
+ pub fn with_config_and_scid_lengths(
96
+ config: &mut Config, client_scid_len: usize, server_scid_len: usize,
97
+ ) -> Result<Pipe> {
98
+ Pipe::<DefaultBufFactory>::with_config_and_scid_lengths_and_buf(
99
+ config,
100
+ client_scid_len,
101
+ server_scid_len,
102
+ )
103
+ }
104
+
105
+ pub fn with_client_config(client_config: &mut Config) -> Result<Pipe> {
106
+ Pipe::<DefaultBufFactory>::with_client_config_and_buf(client_config)
107
+ }
108
+
109
+ pub fn with_server_config(server_config: &mut Config) -> Result<Pipe> {
110
+ Pipe::<DefaultBufFactory>::with_server_config_and_buf(server_config)
111
+ }
112
+
113
+ pub fn with_client_and_server_config(
114
+ client_config: &mut Config, server_config: &mut Config,
115
+ ) -> Result<Pipe> {
116
+ Pipe::<DefaultBufFactory>::with_client_and_server_config_and_buf(
117
+ client_config,
118
+ server_config,
119
+ )
120
+ }
121
+ }
122
+
123
+ impl<F: BufFactory> Pipe<F> {
124
+ pub fn new_with_buf(cc_algorithm_name: &str) -> Result<Pipe<F>> {
125
+ let mut config = Pipe::default_config(cc_algorithm_name)?;
126
+ Pipe::with_config_and_buf(&mut config)
127
+ }
128
+
129
+ pub fn with_config_and_buf(config: &mut Config) -> Result<Pipe<F>> {
130
+ let mut client_scid = [0; 16];
131
+ rand::rand_bytes(&mut client_scid[..]);
132
+ let client_scid = ConnectionId::from_ref(&client_scid);
133
+ let client_addr = Pipe::client_addr();
134
+
135
+ let mut server_scid = [0; 16];
136
+ rand::rand_bytes(&mut server_scid[..]);
137
+ let server_scid = ConnectionId::from_ref(&server_scid);
138
+ let server_addr = Pipe::server_addr();
139
+
140
+ Ok(Pipe {
141
+ client: connect_with_buffer_factory(
142
+ Some("quic.tech"),
143
+ &client_scid,
144
+ client_addr,
145
+ server_addr,
146
+ config,
147
+ )?,
148
+ server: accept_with_buf_factory(
149
+ &server_scid,
150
+ None,
151
+ server_addr,
152
+ client_addr,
153
+ config,
154
+ )?,
155
+ })
156
+ }
157
+
158
+ pub fn with_config_and_scid_lengths_and_buf(
159
+ config: &mut Config, client_scid_len: usize, server_scid_len: usize,
160
+ ) -> Result<Pipe<F>> {
161
+ let mut client_scid = vec![0; client_scid_len];
162
+ rand::rand_bytes(&mut client_scid[..]);
163
+ let client_scid = ConnectionId::from_ref(&client_scid);
164
+ let client_addr = Pipe::client_addr();
165
+
166
+ let mut server_scid = vec![0; server_scid_len];
167
+ rand::rand_bytes(&mut server_scid[..]);
168
+ let server_scid = ConnectionId::from_ref(&server_scid);
169
+ let server_addr = Pipe::server_addr();
170
+
171
+ Ok(Pipe {
172
+ client: connect_with_buffer_factory(
173
+ Some("quic.tech"),
174
+ &client_scid,
175
+ client_addr,
176
+ server_addr,
177
+ config,
178
+ )?,
179
+ server: accept_with_buf_factory(
180
+ &server_scid,
181
+ None,
182
+ server_addr,
183
+ client_addr,
184
+ config,
185
+ )?,
186
+ })
187
+ }
188
+
189
+ pub fn with_client_config_and_buf(
190
+ client_config: &mut Config,
191
+ ) -> Result<Pipe<F>> {
192
+ let mut client_scid = [0; 16];
193
+ rand::rand_bytes(&mut client_scid[..]);
194
+ let client_scid = ConnectionId::from_ref(&client_scid);
195
+ let client_addr = Pipe::client_addr();
196
+
197
+ let mut server_scid = [0; 16];
198
+ rand::rand_bytes(&mut server_scid[..]);
199
+ let server_scid = ConnectionId::from_ref(&server_scid);
200
+ let server_addr = Pipe::server_addr();
201
+
202
+ let mut config = Config::new(PROTOCOL_VERSION)?;
203
+ config.load_cert_chain_from_pem_file("examples/cert.crt")?;
204
+ config.load_priv_key_from_pem_file("examples/cert.key")?;
205
+ config.set_application_protos(&[b"proto1", b"proto2"])?;
206
+ config.set_initial_max_data(30);
207
+ config.set_initial_max_stream_data_bidi_local(15);
208
+ config.set_initial_max_stream_data_bidi_remote(15);
209
+ config.set_initial_max_streams_bidi(3);
210
+ config.set_initial_max_streams_uni(3);
211
+ config.set_ack_delay_exponent(8);
212
+
213
+ Ok(Pipe {
214
+ client: connect_with_buffer_factory(
215
+ Some("quic.tech"),
216
+ &client_scid,
217
+ client_addr,
218
+ server_addr,
219
+ client_config,
220
+ )?,
221
+ server: accept_with_buf_factory(
222
+ &server_scid,
223
+ None,
224
+ server_addr,
225
+ client_addr,
226
+ &mut config,
227
+ )?,
228
+ })
229
+ }
230
+
231
+ pub fn with_server_config_and_buf(
232
+ server_config: &mut Config,
233
+ ) -> Result<Pipe<F>> {
234
+ let mut client_scid = [0; 16];
235
+ rand::rand_bytes(&mut client_scid[..]);
236
+ let client_scid = ConnectionId::from_ref(&client_scid);
237
+ let client_addr = Pipe::client_addr();
238
+
239
+ let mut server_scid = [0; 16];
240
+ rand::rand_bytes(&mut server_scid[..]);
241
+ let server_scid = ConnectionId::from_ref(&server_scid);
242
+ let server_addr = Pipe::server_addr();
243
+
244
+ let mut config = Config::new(PROTOCOL_VERSION)?;
245
+ config.set_application_protos(&[b"proto1", b"proto2"])?;
246
+ config.set_initial_max_data(30);
247
+ config.set_initial_max_stream_data_bidi_local(15);
248
+ config.set_initial_max_stream_data_bidi_remote(15);
249
+ config.set_initial_max_streams_bidi(3);
250
+ config.set_initial_max_streams_uni(3);
251
+ config.set_ack_delay_exponent(8);
252
+
253
+ Ok(Pipe {
254
+ client: connect_with_buffer_factory(
255
+ Some("quic.tech"),
256
+ &client_scid,
257
+ client_addr,
258
+ server_addr,
259
+ &mut config,
260
+ )?,
261
+ server: accept_with_buf_factory(
262
+ &server_scid,
263
+ None,
264
+ server_addr,
265
+ client_addr,
266
+ server_config,
267
+ )?,
268
+ })
269
+ }
270
+
271
+ pub fn with_client_and_server_config_and_buf(
272
+ client_config: &mut Config, server_config: &mut Config,
273
+ ) -> Result<Pipe<F>> {
274
+ let mut client_scid = [0; 16];
275
+ rand::rand_bytes(&mut client_scid[..]);
276
+ let client_scid = ConnectionId::from_ref(&client_scid);
277
+ let client_addr = Pipe::client_addr();
278
+
279
+ let mut server_scid = [0; 16];
280
+ rand::rand_bytes(&mut server_scid[..]);
281
+ let server_scid = ConnectionId::from_ref(&server_scid);
282
+ let server_addr = Pipe::server_addr();
283
+
284
+ Ok(Pipe {
285
+ client: connect_with_buffer_factory(
286
+ Some("quic.tech"),
287
+ &client_scid,
288
+ client_addr,
289
+ server_addr,
290
+ client_config,
291
+ )?,
292
+ server: accept_with_buf_factory(
293
+ &server_scid,
294
+ None,
295
+ server_addr,
296
+ client_addr,
297
+ server_config,
298
+ )?,
299
+ })
300
+ }
301
+
302
+ pub fn handshake(&mut self) -> Result<()> {
303
+ while !self.client.is_established() || !self.server.is_established() {
304
+ let flight = emit_flight(&mut self.client)?;
305
+ process_flight(&mut self.server, flight)?;
306
+
307
+ let flight = emit_flight(&mut self.server)?;
308
+ process_flight(&mut self.client, flight)?;
309
+ }
310
+
311
+ Ok(())
312
+ }
313
+
314
+ pub fn advance(&mut self) -> Result<()> {
315
+ let mut client_done = false;
316
+ let mut server_done = false;
317
+
318
+ while !client_done || !server_done {
319
+ match emit_flight(&mut self.client) {
320
+ Ok(flight) => process_flight(&mut self.server, flight)?,
321
+
322
+ Err(Error::Done) => client_done = true,
323
+
324
+ Err(e) => return Err(e),
325
+ };
326
+
327
+ match emit_flight(&mut self.server) {
328
+ Ok(flight) => process_flight(&mut self.client, flight)?,
329
+
330
+ Err(Error::Done) => server_done = true,
331
+
332
+ Err(e) => return Err(e),
333
+ };
334
+ }
335
+
336
+ Ok(())
337
+ }
338
+
339
+ pub fn client_recv(&mut self, buf: &mut [u8]) -> Result<usize> {
340
+ let server_path = &self.server.paths.get_active().unwrap();
341
+ let info = RecvInfo {
342
+ to: server_path.peer_addr(),
343
+ from: server_path.local_addr(),
344
+ };
345
+
346
+ self.client.recv(buf, info)
347
+ }
348
+
349
+ pub fn server_recv(&mut self, buf: &mut [u8]) -> Result<usize> {
350
+ let client_path = &self.client.paths.get_active().unwrap();
351
+ let info = RecvInfo {
352
+ to: client_path.peer_addr(),
353
+ from: client_path.local_addr(),
354
+ };
355
+
356
+ self.server.recv(buf, info)
357
+ }
358
+
359
+ pub fn send_pkt_to_server(
360
+ &mut self, pkt_type: Type, frames: &[frame::Frame], buf: &mut [u8],
361
+ ) -> Result<usize> {
362
+ let written = encode_pkt(&mut self.client, pkt_type, frames, buf)?;
363
+ recv_send(&mut self.server, buf, written)
364
+ }
365
+
366
+ pub fn client_update_key(&mut self) -> Result<()> {
367
+ let crypto_ctx = &mut self.client.crypto_ctx[packet::Epoch::Application];
368
+
369
+ let open_next = crypto_ctx
370
+ .crypto_open
371
+ .as_ref()
372
+ .unwrap()
373
+ .derive_next_packet_key()
374
+ .unwrap();
375
+
376
+ let seal_next = crypto_ctx
377
+ .crypto_seal
378
+ .as_ref()
379
+ .unwrap()
380
+ .derive_next_packet_key()?;
381
+
382
+ let open_prev = crypto_ctx.crypto_open.replace(open_next);
383
+ crypto_ctx.crypto_seal.replace(seal_next);
384
+
385
+ crypto_ctx.key_update = Some(packet::KeyUpdate {
386
+ crypto_open: open_prev.unwrap(),
387
+ pn_on_update: self.client.next_pkt_num,
388
+ update_acked: true,
389
+ timer: Instant::now(),
390
+ });
391
+
392
+ self.client.key_phase = !self.client.key_phase;
393
+
394
+ Ok(())
395
+ }
396
+ }
397
+
398
+ pub fn recv_send<F: BufFactory>(
399
+ conn: &mut Connection<F>, buf: &mut [u8], len: usize,
400
+ ) -> Result<usize> {
401
+ let active_path = conn.paths.get_active()?;
402
+ let info = RecvInfo {
403
+ to: active_path.local_addr(),
404
+ from: active_path.peer_addr(),
405
+ };
406
+
407
+ conn.recv(&mut buf[..len], info)?;
408
+
409
+ let mut off = 0;
410
+
411
+ match conn.send(&mut buf[off..]) {
412
+ Ok((write, _)) => off += write,
413
+
414
+ Err(Error::Done) => (),
415
+
416
+ Err(e) => return Err(e),
417
+ }
418
+
419
+ Ok(off)
420
+ }
421
+
422
+ pub fn process_flight<F: BufFactory>(
423
+ conn: &mut Connection<F>, flight: Vec<(Vec<u8>, SendInfo)>,
424
+ ) -> Result<()> {
425
+ for (mut pkt, si) in flight {
426
+ let info = RecvInfo {
427
+ to: si.to,
428
+ from: si.from,
429
+ };
430
+
431
+ conn.recv(&mut pkt, info)?;
432
+ }
433
+
434
+ Ok(())
435
+ }
436
+
437
+ pub fn emit_flight_with_max_buffer<F: BufFactory>(
438
+ conn: &mut Connection<F>, out_size: usize, from: Option<SocketAddr>,
439
+ to: Option<SocketAddr>,
440
+ ) -> Result<Vec<(Vec<u8>, SendInfo)>> {
441
+ let mut flight = Vec::new();
442
+
443
+ loop {
444
+ let mut out = vec![0u8; out_size];
445
+
446
+ let info = match conn.send_on_path(&mut out, from, to) {
447
+ Ok((written, info)) => {
448
+ out.truncate(written);
449
+ info
450
+ },
451
+
452
+ Err(Error::Done) => break,
453
+
454
+ Err(e) => return Err(e),
455
+ };
456
+
457
+ flight.push((out, info));
458
+ }
459
+
460
+ if flight.is_empty() {
461
+ return Err(Error::Done);
462
+ }
463
+
464
+ Ok(flight)
465
+ }
466
+
467
+ pub fn emit_flight_on_path<F: BufFactory>(
468
+ conn: &mut Connection<F>, from: Option<SocketAddr>, to: Option<SocketAddr>,
469
+ ) -> Result<Vec<(Vec<u8>, SendInfo)>> {
470
+ emit_flight_with_max_buffer(conn, 65535, from, to)
471
+ }
472
+
473
+ pub fn emit_flight<F: BufFactory>(
474
+ conn: &mut Connection<F>,
475
+ ) -> Result<Vec<(Vec<u8>, SendInfo)>> {
476
+ emit_flight_on_path(conn, None, None)
477
+ }
478
+
479
+ pub fn encode_pkt<F: BufFactory>(
480
+ conn: &mut Connection<F>, pkt_type: Type, frames: &[frame::Frame],
481
+ buf: &mut [u8],
482
+ ) -> Result<usize> {
483
+ let mut b = octets::OctetsMut::with_slice(buf);
484
+
485
+ let epoch = pkt_type.to_epoch()?;
486
+
487
+ let crypto_ctx = &mut conn.crypto_ctx[epoch];
488
+
489
+ let pn = conn.next_pkt_num;
490
+ let pn_len = 4;
491
+
492
+ let send_path = conn.paths.get_active()?;
493
+ let active_dcid_seq = send_path
494
+ .active_dcid_seq
495
+ .as_ref()
496
+ .ok_or(Error::InvalidState)?;
497
+ let active_scid_seq = send_path
498
+ .active_scid_seq
499
+ .as_ref()
500
+ .ok_or(Error::InvalidState)?;
501
+
502
+ let hdr = Header {
503
+ ty: pkt_type,
504
+ version: conn.version,
505
+ dcid: ConnectionId::from_ref(
506
+ conn.ids.get_dcid(*active_dcid_seq)?.cid.as_ref(),
507
+ ),
508
+ scid: ConnectionId::from_ref(
509
+ conn.ids.get_scid(*active_scid_seq)?.cid.as_ref(),
510
+ ),
511
+ pkt_num: pn,
512
+ pkt_num_len: pn_len,
513
+ token: conn.token.clone(),
514
+ versions: None,
515
+ key_phase: conn.key_phase,
516
+ };
517
+
518
+ hdr.to_bytes(&mut b)?;
519
+
520
+ let payload_len = frames.iter().fold(0, |acc, x| acc + x.wire_len());
521
+
522
+ if pkt_type != Type::Short {
523
+ let len = pn_len + payload_len + crypto_ctx.crypto_overhead().unwrap();
524
+ b.put_varint(len as u64)?;
525
+ }
526
+
527
+ // Always encode packet number in 4 bytes, to allow encoding packets
528
+ // with empty payloads.
529
+ b.put_u32(pn as u32)?;
530
+
531
+ let payload_offset = b.off();
532
+
533
+ for frame in frames {
534
+ frame.to_bytes(&mut b)?;
535
+ }
536
+
537
+ let aead = match crypto_ctx.crypto_seal {
538
+ Some(ref mut v) => v,
539
+ None => return Err(Error::InvalidState),
540
+ };
541
+
542
+ let written = packet::encrypt_pkt(
543
+ &mut b,
544
+ pn,
545
+ pn_len,
546
+ payload_len,
547
+ payload_offset,
548
+ None,
549
+ aead,
550
+ )?;
551
+
552
+ conn.next_pkt_num += 1;
553
+
554
+ Ok(written)
555
+ }
556
+
557
+ pub fn decode_pkt<F: BufFactory>(
558
+ conn: &mut Connection<F>, buf: &mut [u8],
559
+ ) -> Result<Vec<frame::Frame>> {
560
+ let mut b = octets::OctetsMut::with_slice(buf);
561
+
562
+ let mut hdr = Header::from_bytes(&mut b, conn.source_id().len()).unwrap();
563
+
564
+ let epoch = hdr.ty.to_epoch()?;
565
+
566
+ let aead = conn.crypto_ctx[epoch].crypto_open.as_ref().unwrap();
567
+
568
+ let payload_len = b.cap();
569
+
570
+ packet::decrypt_hdr(&mut b, &mut hdr, aead).unwrap();
571
+
572
+ let pn = packet::decode_pkt_num(
573
+ conn.pkt_num_spaces[epoch].largest_rx_pkt_num,
574
+ hdr.pkt_num,
575
+ hdr.pkt_num_len,
576
+ );
577
+
578
+ let mut payload =
579
+ packet::decrypt_pkt(&mut b, pn, hdr.pkt_num_len, payload_len, aead)
580
+ .unwrap();
581
+
582
+ let mut frames = Vec::new();
583
+
584
+ while payload.cap() > 0 {
585
+ let frame = frame::Frame::from_bytes(&mut payload, hdr.ty)?;
586
+ frames.push(frame);
587
+ }
588
+
589
+ Ok(frames)
590
+ }
591
+
592
+ pub fn create_cid_and_reset_token(
593
+ cid_len: usize,
594
+ ) -> (ConnectionId<'static>, u128) {
595
+ let mut cid = vec![0; cid_len];
596
+ rand::rand_bytes(&mut cid[..]);
597
+ let cid = ConnectionId::from(cid);
598
+
599
+ let mut reset_token = [0; 16];
600
+ rand::rand_bytes(&mut reset_token);
601
+ let reset_token = u128::from_be_bytes(reset_token);
602
+
603
+ (cid, reset_token)
604
+ }
605
+
606
+ pub fn helper_packet_sent(pkt_num: u64, now: Instant, size: usize) -> Sent {
607
+ Sent {
608
+ pkt_num,
609
+ frames: smallvec![],
610
+ time_sent: now,
611
+ time_acked: None,
612
+ time_lost: None,
613
+ size,
614
+ ack_eliciting: true,
615
+ in_flight: true,
616
+ delivered: 0,
617
+ delivered_time: now,
618
+ first_sent_time: now,
619
+ is_app_limited: false,
620
+ tx_in_flight: 0,
621
+ lost: 0,
622
+ has_data: true,
623
+ is_pmtud_probe: false,
624
+ }
625
+ }
626
+
627
+ // Helper function for testing either stream receive or discard.
628
+ pub fn stream_recv_discard<F: BufFactory>(
629
+ conn: &mut Connection<F>, discard: bool, stream_id: u64,
630
+ ) -> Result<(usize, bool)> {
631
+ let mut buf = [0; 65535];
632
+ if discard {
633
+ conn.stream_discard(stream_id, 65535)
634
+ } else {
635
+ conn.stream_recv(stream_id, &mut buf)
636
+ }
637
+ }
638
+
639
+ /// Triggers ACK-based loss detection for packets sent by `sender` before this
640
+ /// call.
641
+ ///
642
+ /// This works by sending multiple PING packets from the sender and having the
643
+ /// receiver ACK them. Since loss detection uses a packet threshold, this
644
+ /// function sends as many packets as needed to ensure any previously
645
+ /// unacknowledged packets from the sender are detected as lost.
646
+ #[cfg(test)]
647
+ pub fn trigger_ack_based_loss<F: BufFactory>(
648
+ sender: &mut Connection<F>, receiver: &mut Connection<F>,
649
+ ) {
650
+ let mut buf = [0; 65535];
651
+
652
+ // Use the active path's packet loss threshold.
653
+ let pkt_thresh = sender
654
+ .paths
655
+ .get_active()
656
+ .unwrap()
657
+ .recovery
658
+ .pkt_thresh()
659
+ .unwrap();
660
+
661
+ for _ in 0..pkt_thresh {
662
+ sender.send_ack_eliciting().unwrap();
663
+ let (len, _) = sender.send(&mut buf).unwrap();
664
+
665
+ let info = RecvInfo {
666
+ to: receiver.paths.get_active().unwrap().local_addr(),
667
+ from: receiver.paths.get_active().unwrap().peer_addr(),
668
+ };
669
+ receiver.recv(&mut buf[..len], info).unwrap();
670
+ }
671
+
672
+ // Receiver sends ACK for the new packets.
673
+ let (ack_len, _) = receiver.send(&mut buf).unwrap();
674
+
675
+ // Sender receives ACK, triggering loss detection.
676
+ let info = RecvInfo {
677
+ to: sender.paths.get_active().unwrap().local_addr(),
678
+ from: sender.paths.get_active().unwrap().peer_addr(),
679
+ };
680
+ sender.recv(&mut buf[..ack_len], info).unwrap();
681
+ }