rwebtransport 0.2.3 → 0.2.5

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 (96) hide show
  1. package/Cargo.lock +153 -226
  2. package/Cargo.toml +5 -5
  3. package/README.md +4 -4
  4. package/crates/echo-server/src/bin/gen-test-cert.rs +1 -1
  5. package/crates/native/Cargo.toml +1 -1
  6. package/crates/native/src/config.rs +13 -1
  7. package/crates/native/src/driver.rs +249 -91
  8. package/crates/native/src/lib.rs +9 -10
  9. package/crates/native/src/parser_memory.rs +1 -0
  10. package/crates/native/src/server.rs +197 -182
  11. package/crates/native/src/session.rs +329 -177
  12. package/crates/native/src/test_support.rs +2 -2
  13. package/crates/wtcore/src/h3.rs +166 -10
  14. package/dist/index.js +92 -45
  15. package/dist/index.js.map +2 -2
  16. package/dist/index.mjs +92 -45
  17. package/dist/index.mjs.map +2 -2
  18. package/dist/native.d.ts +9 -4
  19. package/package.json +14 -11
  20. package/prebuilds/darwin-arm64/rwebtransport.node +0 -0
  21. package/prebuilds/linux-arm64/rwebtransport.node +0 -0
  22. package/prebuilds/linux-x64/rwebtransport.node +0 -0
  23. package/prebuilds/win32-x64/rwebtransport.node +0 -0
  24. package/scripts/build-linux-prebuilt.sh +46 -0
  25. package/scripts/build.js +10 -3
  26. package/vendor/quiche/AGENTS.md +10 -0
  27. package/vendor/quiche/Cargo.lock +239 -248
  28. package/vendor/quiche/Cargo.toml +23 -10
  29. package/vendor/quiche/examples/Makefile +4 -4
  30. package/vendor/quiche/examples/client.rs +10 -28
  31. package/vendor/quiche/examples/http3-client.rs +20 -34
  32. package/vendor/quiche/examples/http3-server.rs +47 -78
  33. package/vendor/quiche/examples/server.rs +19 -49
  34. package/vendor/quiche/include/quiche.h +35 -4
  35. package/vendor/quiche/src/build.rs +17 -0
  36. package/vendor/quiche/src/cid.rs +129 -61
  37. package/vendor/quiche/src/crypto/boringssl.rs +98 -86
  38. package/vendor/quiche/src/crypto/mod.rs +64 -77
  39. package/vendor/quiche/src/dgram.rs +2 -3
  40. package/vendor/quiche/src/error.rs +22 -20
  41. package/vendor/quiche/src/ffi.rs +558 -280
  42. package/vendor/quiche/src/flowcontrol.rs +0 -7
  43. package/vendor/quiche/src/frame.rs +134 -135
  44. package/vendor/quiche/src/h3/ffi.rs +73 -60
  45. package/vendor/quiche/src/h3/frame.rs +70 -90
  46. package/vendor/quiche/src/h3/mod.rs +1024 -593
  47. package/vendor/quiche/src/h3/qpack/decoder.rs +248 -34
  48. package/vendor/quiche/src/h3/qpack/dynamic_table.rs +859 -0
  49. package/vendor/quiche/src/h3/qpack/encoder.rs +14 -17
  50. package/vendor/quiche/src/h3/qpack/mod.rs +48 -0
  51. package/vendor/quiche/src/h3/qpack/static_table.rs +86 -73
  52. package/vendor/quiche/src/h3/stream.rs +1009 -194
  53. package/vendor/quiche/src/lib.rs +1346 -1195
  54. package/vendor/quiche/src/minmax.rs +2 -6
  55. package/vendor/quiche/src/packet.rs +420 -552
  56. package/vendor/quiche/src/path.rs +202 -72
  57. package/vendor/quiche/src/pmtud.rs +18 -16
  58. package/vendor/quiche/src/ranges.rs +184 -82
  59. package/vendor/quiche/src/recovery/AGENTS.md +5 -2
  60. package/vendor/quiche/src/recovery/bandwidth.rs +59 -40
  61. package/vendor/quiche/src/recovery/bytes_in_flight.rs +2 -2
  62. package/vendor/quiche/src/recovery/congestion/cubic.rs +38 -47
  63. package/vendor/quiche/src/recovery/congestion/delivery_rate.rs +54 -60
  64. package/vendor/quiche/src/recovery/congestion/hystart.rs +6 -10
  65. package/vendor/quiche/src/recovery/congestion/mod.rs +110 -42
  66. package/vendor/quiche/src/recovery/congestion/prr.rs +4 -1
  67. package/vendor/quiche/src/recovery/congestion/recovery.rs +91 -95
  68. package/vendor/quiche/src/recovery/congestion/reno.rs +17 -12
  69. package/vendor/quiche/src/recovery/congestion/test_sender.rs +8 -27
  70. package/vendor/quiche/src/recovery/gcongestion/bbr/bandwidth_sampler.rs +159 -247
  71. package/vendor/quiche/src/recovery/gcongestion/bbr/windowed_filter.rs +9 -14
  72. package/vendor/quiche/src/recovery/gcongestion/bbr2/drain.rs +18 -15
  73. package/vendor/quiche/src/recovery/gcongestion/bbr2/mode.rs +43 -28
  74. package/vendor/quiche/src/recovery/gcongestion/bbr2/network_model.rs +349 -76
  75. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_bw.rs +147 -195
  76. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_rtt.rs +29 -27
  77. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/global_min.rs +180 -0
  78. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/global_min_tests.rs +221 -0
  79. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/hmm.rs +395 -0
  80. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/hmm_tests.rs +473 -0
  81. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/mod.rs +175 -0
  82. package/vendor/quiche/src/recovery/gcongestion/bbr2/startup.rs +33 -26
  83. package/vendor/quiche/src/recovery/gcongestion/bbr2.rs +107 -60
  84. package/vendor/quiche/src/recovery/gcongestion/mod.rs +64 -11
  85. package/vendor/quiche/src/recovery/gcongestion/pacer.rs +34 -25
  86. package/vendor/quiche/src/recovery/gcongestion/recovery.rs +81 -86
  87. package/vendor/quiche/src/recovery/mod.rs +414 -173
  88. package/vendor/quiche/src/recovery/rtt.rs +8 -5
  89. package/vendor/quiche/src/stream/mod.rs +864 -133
  90. package/vendor/quiche/src/stream/recv_buf.rs +471 -172
  91. package/vendor/quiche/src/stream/send_buf.rs +338 -81
  92. package/vendor/quiche/src/test_utils.rs +78 -64
  93. package/vendor/quiche/src/tests.rs +2559 -1335
  94. package/vendor/quiche/src/tls/boringssl.rs +60 -63
  95. package/vendor/quiche/src/tls/mod.rs +146 -193
  96. package/vendor/quiche/src/transport_params.rs +87 -103
@@ -68,8 +68,7 @@ fn main() {
68
68
  let mut events = mio::Events::with_capacity(1024);
69
69
 
70
70
  // Create the UDP listening socket, and register it with the event loop.
71
- let mut socket =
72
- mio::net::UdpSocket::bind("127.0.0.1:4433".parse().unwrap()).unwrap();
71
+ let mut socket = mio::net::UdpSocket::bind("127.0.0.1:4433".parse().unwrap()).unwrap();
73
72
  poll.registry()
74
73
  .register(&mut socket, mio::Token(0), mio::Interest::READABLE)
75
74
  .unwrap();
@@ -85,13 +84,7 @@ fn main() {
85
84
  .unwrap();
86
85
 
87
86
  config
88
- .set_application_protos(&[
89
- b"hq-interop",
90
- b"hq-29",
91
- b"hq-28",
92
- b"hq-27",
93
- b"http/0.9",
94
- ])
87
+ .set_application_protos(&[b"hq-interop", b"hq-29", b"hq-28", b"hq-27", b"http/0.9"])
95
88
  .unwrap();
96
89
 
97
90
  config.set_max_idle_timeout(5000);
@@ -107,8 +100,7 @@ fn main() {
107
100
  config.enable_early_data();
108
101
 
109
102
  let rng = SystemRandom::new();
110
- let conn_id_seed =
111
- ring::hmac::Key::generate(ring::hmac::HMAC_SHA256, &rng).unwrap();
103
+ let conn_id_seed = ring::hmac::Key::generate(ring::hmac::HMAC_SHA256, &rng).unwrap();
112
104
 
113
105
  let mut clients = ClientMap::new();
114
106
 
@@ -148,7 +140,7 @@ fn main() {
148
140
  }
149
141
 
150
142
  panic!("recv() failed: {e:?}");
151
- },
143
+ }
152
144
  };
153
145
 
154
146
  debug!("got {len} bytes");
@@ -156,16 +148,13 @@ fn main() {
156
148
  let pkt_buf = &mut buf[..len];
157
149
 
158
150
  // Parse the QUIC packet's header.
159
- let hdr = match quiche::Header::from_slice(
160
- pkt_buf,
161
- quiche::MAX_CONN_ID_LEN,
162
- ) {
151
+ let hdr = match quiche::Header::from_slice(pkt_buf, quiche::MAX_CONN_ID_LEN) {
163
152
  Ok(v) => v,
164
153
 
165
154
  Err(e) => {
166
155
  error!("Parsing packet header failed: {e:?}");
167
156
  continue 'read;
168
- },
157
+ }
169
158
  };
170
159
 
171
160
  trace!("got packet {hdr:?}");
@@ -176,9 +165,7 @@ fn main() {
176
165
 
177
166
  // Lookup a connection based on the packet's connection ID. If there
178
167
  // is no connection matching, create a new one.
179
- let client = if !clients.contains_key(&hdr.dcid) &&
180
- !clients.contains_key(&conn_id)
181
- {
168
+ let client = if !clients.contains_key(&hdr.dcid) && !clients.contains_key(&conn_id) {
182
169
  if hdr.ty != quiche::Type::Initial {
183
170
  error!("Packet is not Initial");
184
171
  continue 'read;
@@ -187,9 +174,7 @@ fn main() {
187
174
  if !quiche::version_is_supported(hdr.version) {
188
175
  warn!("Doing version negotiation");
189
176
 
190
- let len =
191
- quiche::negotiate_version(&hdr.scid, &hdr.dcid, &mut out)
192
- .unwrap();
177
+ let len = quiche::negotiate_version(&hdr.scid, &hdr.dcid, &mut out).unwrap();
193
178
 
194
179
  let out = &out[..len];
195
180
 
@@ -261,14 +246,8 @@ fn main() {
261
246
 
262
247
  debug!("New connection: dcid={:?} scid={:?}", hdr.dcid, scid);
263
248
 
264
- let conn = quiche::accept(
265
- &scid,
266
- odcid.as_ref(),
267
- local_addr,
268
- from,
269
- &mut config,
270
- )
271
- .unwrap();
249
+ let conn =
250
+ quiche::accept(&scid, odcid.as_ref(), local_addr, from, &mut config).unwrap();
272
251
 
273
252
  let client = Client {
274
253
  conn,
@@ -298,7 +277,7 @@ fn main() {
298
277
  Err(e) => {
299
278
  error!("{} recv failed: {:?}", client.conn.trace_id(), e);
300
279
  continue 'read;
301
- },
280
+ }
302
281
  };
303
282
 
304
283
  debug!("{} processed {} bytes", client.conn.trace_id(), read);
@@ -311,14 +290,8 @@ fn main() {
311
290
 
312
291
  // Process all readable streams.
313
292
  for s in client.conn.readable() {
314
- while let Ok((read, fin)) =
315
- client.conn.stream_recv(s, &mut buf)
316
- {
317
- debug!(
318
- "{} received {} bytes",
319
- client.conn.trace_id(),
320
- read
321
- );
293
+ while let Ok((read, fin)) = client.conn.stream_recv(s, &mut buf) {
294
+ debug!("{} received {} bytes", client.conn.trace_id(), read);
322
295
 
323
296
  let stream_buf = &buf[..read];
324
297
 
@@ -347,14 +320,14 @@ fn main() {
347
320
  Err(quiche::Error::Done) => {
348
321
  debug!("{} done writing", client.conn.trace_id());
349
322
  break;
350
- },
323
+ }
351
324
 
352
325
  Err(e) => {
353
326
  error!("{} send failed: {:?}", client.conn.trace_id(), e);
354
327
 
355
328
  client.conn.close(false, 0x1, b"fail").ok();
356
329
  break;
357
- },
330
+ }
358
331
  };
359
332
 
360
333
  if let Err(e) = socket.send_to(&out[..write], send_info.to) {
@@ -418,9 +391,7 @@ fn mint_token(hdr: &quiche::Header, src: &net::SocketAddr) -> Vec<u8> {
418
391
  ///
419
392
  /// Note that this function is only an example and doesn't do any cryptographic
420
393
  /// authenticate of the token. *It should not be used in production system*.
421
- fn validate_token<'a>(
422
- src: &net::SocketAddr, token: &'a [u8],
423
- ) -> Option<quiche::ConnectionId<'a>> {
394
+ fn validate_token<'a>(src: &net::SocketAddr, token: &'a [u8]) -> Option<quiche::ConnectionId<'a>> {
424
395
  if token.len() < 6 {
425
396
  return None;
426
397
  }
@@ -467,8 +438,7 @@ fn handle_stream(client: &mut Client, stream_id: u64, buf: &[u8], root: &str) {
467
438
  stream_id
468
439
  );
469
440
 
470
- let body = std::fs::read(path.as_path())
471
- .unwrap_or_else(|_| b"Not Found!\r\n".to_vec());
441
+ let body = std::fs::read(path.as_path()).unwrap_or_else(|_| b"Not Found!\r\n".to_vec());
472
442
 
473
443
  info!(
474
444
  "{} sending response of size {} on stream {}",
@@ -485,7 +455,7 @@ fn handle_stream(client: &mut Client, stream_id: u64, buf: &[u8], root: &str) {
485
455
  Err(e) => {
486
456
  error!("{} stream send failed {:?}", conn.trace_id(), e);
487
457
  return;
488
- },
458
+ }
489
459
  };
490
460
 
491
461
  if written < body.len() {
@@ -518,7 +488,7 @@ fn handle_writable(client: &mut Client, stream_id: u64) {
518
488
 
519
489
  error!("{} stream send failed {:?}", conn.trace_id(), e);
520
490
  return;
521
- },
491
+ }
522
492
  };
523
493
 
524
494
  resp.written += written;
@@ -137,6 +137,7 @@ enum quiche_error {
137
137
 
138
138
  /// An invalid DCID was used when connecting to a remote peer.
139
139
  QUICHE_ERR_INVALID_DCID_INITIALIZATION = -23,
140
+ QUICHE_ERR_STREAM_MEMORY_LIMIT = -24,
140
141
  };
141
142
 
142
143
  // Returns a human readable string with the quiche version number.
@@ -168,6 +169,9 @@ int quiche_config_load_verify_locations_from_file(quiche_config *config,
168
169
  int quiche_config_load_verify_locations_from_directory(quiche_config *config,
169
170
  const char *path);
170
171
 
172
+ // Configures the TLS curve preference list (colon-separated, e.g. "X25519MLKEM768:X25519:P-256:P-384").
173
+ int quiche_config_set_curves_list(quiche_config *config, const char *curves);
174
+
171
175
  // Configures whether to verify the peer's certificate.
172
176
  void quiche_config_verify_peer(quiche_config *config, bool v);
173
177
 
@@ -234,6 +238,21 @@ int quiche_config_set_cc_algorithm_name(quiche_config *config, const char *algo)
234
238
  // Sets the initial cwnd for the connection in terms of packet count.
235
239
  void quiche_config_set_initial_congestion_window_packets(quiche_config *config, size_t packets);
236
240
 
241
+ // Sets the fixed congestion window in bytes for congestion_window_unchecked.
242
+ // Select the controller using quiche_config_set_cc_algorithm_name(config,
243
+ // "congestion_window_unchecked") in builds with the
244
+ // congestion_window_unchecked_available feature.
245
+ // Defaults to SIZE_MAX. Other congestion control algorithms are unchanged.
246
+ // Recovery probes can bypass the fixed window.
247
+ void quiche_config_set_unchecked_congestion_window(quiche_config *config, size_t window);
248
+
249
+ // Sets the number of sent packets that can be tracked for loss detection
250
+ // before the connection is closed with a PROTOCOL_VIOLATION error. The limit
251
+ // should be larger than the expected maximum congestion window, in packets.
252
+ // The value 0 disables this limit, so the memory used to track sent packets is
253
+ // no longer bounded. The default is 22000.
254
+ void quiche_config_set_max_outstanding_sent_packets(quiche_config *config, size_t max_packets);
255
+
237
256
  enum quiche_cc_algorithm {
238
257
  QUICHE_CC_RENO = 0,
239
258
  QUICHE_CC_CUBIC = 1,
@@ -253,8 +272,7 @@ void quiche_config_enable_pacing(quiche_config *config, bool v);
253
272
  void quiche_config_set_enable_cubic_idle_restart_fix(quiche_config *config,
254
273
  bool v);
255
274
 
256
- // Configures whether to use the initial max data value as the initial flow
257
- // control window for streams and the connection (disabled by default).
275
+ // Deprecated: this is now always enabled and this function is a no-op.
258
276
  void quiche_config_set_use_initial_max_data_as_flow_control_win(
259
277
  quiche_config *config, bool v);
260
278
 
@@ -842,8 +860,10 @@ ssize_t quiche_conn_send_ack_eliciting_on_path(quiche_conn *conn,
842
860
  const struct sockaddr *local, socklen_t local_len,
843
861
  const struct sockaddr *peer, socklen_t peer_len);
844
862
 
845
- // Returns true if there are retired source connection ids and fill the parameters
846
- bool quiche_conn_retired_scid_next(const quiche_conn *conn, const uint8_t **out, size_t *out_len);
863
+ // Drains and collects all currently retired source connection IDs into an
864
+ // iterator. The caller must use quiche_connection_id_iter_next() to iterate and
865
+ // quiche_connection_id_iter_free() to free the iterator.
866
+ quiche_connection_id_iter *quiche_conn_retired_scid_iter(quiche_conn *conn);
847
867
 
848
868
  // Returns the number of source Connection IDs that are retired.
849
869
  size_t quiche_conn_retired_scids(const quiche_conn *conn);
@@ -888,6 +908,7 @@ enum quiche_path_event_type {
888
908
  QUICHE_PATH_EVENT_CLOSED,
889
909
  QUICHE_PATH_EVENT_REUSED_SOURCE_CONNECTION_ID,
890
910
  QUICHE_PATH_EVENT_PEER_MIGRATED,
911
+ QUICHE_PATH_EVENT_PMTU_UPDATED,
891
912
  };
892
913
 
893
914
  typedef struct quiche_path_event quiche_path_event;
@@ -926,6 +947,13 @@ void quiche_path_event_peer_migrated(const quiche_path_event *ev,
926
947
  struct sockaddr_storage *local, socklen_t *local_len,
927
948
  struct sockaddr_storage *peer, socklen_t *peer_len);
928
949
 
950
+ // Should be called if the quiche_path_event_type(...) returns QUICHE_PATH_EVENT_PMTU_UPDATED.
951
+ // Sets "pmtu" to the current validated PMTU limit for normal application traffic.
952
+ void quiche_path_event_pmtu_updated(const quiche_path_event *ev,
953
+ struct sockaddr_storage *local, socklen_t *local_len,
954
+ struct sockaddr_storage *peer, socklen_t *peer_len,
955
+ size_t *pmtu);
956
+
929
957
  // Frees the path event object.
930
958
  void quiche_path_event_free(quiche_path_event *ev);
931
959
 
@@ -1125,6 +1153,9 @@ void quiche_h3_config_set_qpack_blocked_streams(quiche_h3_config *config, uint64
1125
1153
  // Sets the `SETTINGS_ENABLE_CONNECT_PROTOCOL` setting.
1126
1154
  void quiche_h3_config_enable_extended_connect(quiche_h3_config *config, bool enabled);
1127
1155
 
1156
+ // Sets the maximum size for the payload of PRIORITY_UPDATE frames.
1157
+ void quiche_h3_config_set_max_priority_update_size(quiche_h3_config *config, uint64_t v);
1158
+
1128
1159
  // Frees the HTTP/3 config object.
1129
1160
  void quiche_h3_config_free(quiche_h3_config *config);
1130
1161
 
@@ -44,7 +44,24 @@ fn target_dir_path() -> std::path::PathBuf {
44
44
  }
45
45
 
46
46
  fn main() {
47
+ // Emit `cfg(boring_v5)` if boring version 5.x is detected. This
48
+ // is used to pick which APIs to expect and to guide test
49
+ // expectations. (Larger post-quantum key shares are enabled by
50
+ // default in boring 5.x but not boring 4.x.) 4.x is the assumed
51
+ // default.
52
+ //
53
+ // `boring-sys` >= 5.2 emits `cargo:version_major=<N>` from its
54
+ // build script, which cargo surfaces here as
55
+ // `DEP_BORINGSSL_VERSION_MAJOR`. When absent (boring-sys < 5.2,
56
+ // or the `boringssl-boring-crate` feature is off) we assume 4.x.
57
+ //
58
+ // The cfg is always registered (even when the backend feature is
59
+ // off) so rustc doesn't warn about unknown cfg names.
60
+ println!("cargo::rustc-check-cfg=cfg(boring_v5)");
47
61
  if cfg!(feature = "boringssl-boring-crate") {
62
+ if std::env::var("DEP_BORINGSSL_VERSION_MAJOR").ok().as_deref() == Some("5") {
63
+ println!("cargo:rustc-cfg=boring_v5");
64
+ }
48
65
  println!("cargo:rustc-link-lib=static=ssl");
49
66
  println!("cargo:rustc-link-lib=static=crypto");
50
67
  }
@@ -166,7 +166,7 @@ impl BoundedNonEmptyConnectionIdVecDeque {
166
166
  return Err(Error::IdLimit);
167
167
  }
168
168
  self.inner.push_back(e);
169
- },
169
+ }
170
170
  };
171
171
  Ok(())
172
172
  }
@@ -179,23 +179,43 @@ impl BoundedNonEmptyConnectionIdVecDeque {
179
179
 
180
180
  /// Removes the element in the collection having the provided `seq`.
181
181
  ///
182
- /// If this method is called when there remains a single element in the
183
- /// collection, this method raises an [`OutOfIdentifiers`].
182
+ /// If the element is the last one remaining in the collection, this method
183
+ /// raises an [`OutOfIdentifiers`].
184
184
  ///
185
185
  /// Returns `Some` if the element was in the collection and removed, or
186
186
  /// `None` if it was not and nothing was modified.
187
187
  ///
188
188
  /// [`OutOfIdentifiers`]: enum.Error.html#OutOfIdentifiers
189
189
  fn remove(&mut self, seq: u64) -> Result<Option<ConnectionIdEntry>> {
190
+ let index = match self.inner.iter().position(|e| e.seq == seq) {
191
+ Some(i) => i,
192
+ None => return Ok(None),
193
+ };
194
+
190
195
  if self.inner.len() <= 1 {
191
196
  return Err(Error::OutOfIdentifiers);
192
197
  }
193
198
 
194
- Ok(self
195
- .inner
196
- .iter()
197
- .position(|e| e.seq == seq)
198
- .and_then(|index| self.inner.remove(index)))
199
+ Ok(self.inner.remove(index))
200
+ }
201
+
202
+ /// Removes all elements in the collection with sequence numbers less than
203
+ /// `retire_prior_to`. The inspect closure is run on each element before it
204
+ /// is removed.
205
+ ///
206
+ /// The deque is in arrival order (not necessarily sorted by seq), so we
207
+ /// have to check each entry.
208
+ fn retire_prior_to<F>(&mut self, retire_prior_to: u64, mut inspect: F)
209
+ where
210
+ F: FnMut(&mut ConnectionIdEntry),
211
+ {
212
+ self.inner.retain_mut(|e| {
213
+ if e.seq < retire_prior_to {
214
+ inspect(e);
215
+ return false;
216
+ }
217
+ true
218
+ });
199
219
  }
200
220
  }
201
221
 
@@ -244,8 +264,10 @@ impl ConnectionIdentifiers {
244
264
  /// connection ID limit and initial source Connection ID. The destination
245
265
  /// Connection ID is set to the empty one.
246
266
  pub fn new(
247
- mut destination_conn_id_limit: usize, initial_scid: &ConnectionId,
248
- initial_path_id: usize, reset_token: Option<u128>,
267
+ mut destination_conn_id_limit: usize,
268
+ initial_scid: &ConnectionId,
269
+ initial_path_id: usize,
270
+ reset_token: Option<u128>,
249
271
  ) -> ConnectionIdentifiers {
250
272
  // It must be at least 2.
251
273
  if destination_conn_id_limit < 2 {
@@ -258,8 +280,7 @@ impl ConnectionIdentifiers {
258
280
  // Record the zero-length SCID status.
259
281
  let zero_length_scid = initial_scid.is_empty();
260
282
 
261
- let initial_scid =
262
- ConnectionId::from_ref(initial_scid.as_ref()).into_owned();
283
+ let initial_scid = ConnectionId::from_ref(initial_scid.as_ref()).into_owned();
263
284
 
264
285
  // We need to track up to (2 * source_conn_id_limit - 1) source
265
286
  // Connection IDs when the host wants to force their renewal.
@@ -284,8 +305,7 @@ impl ConnectionIdentifiers {
284
305
  );
285
306
 
286
307
  // Guard against overflow.
287
- let value =
288
- (destination_conn_id_limit as u64) * RETIRED_CONN_ID_LIMIT_MULTIPLIER;
308
+ let value = (destination_conn_id_limit as u64) * RETIRED_CONN_ID_LIMIT_MULTIPLIER;
289
309
  let size = cmp::min(usize::MAX as u64, value) as usize;
290
310
  // Because we already inserted the initial SCID.
291
311
  let next_scid_seq = 1;
@@ -357,8 +377,12 @@ impl ConnectionIdentifiers {
357
377
  /// [`InvalidState`]: enum.Error.html#InvalidState
358
378
  /// [`IdLimit`]: enum.Error.html#IdLimit
359
379
  pub fn new_scid(
360
- &mut self, cid: ConnectionId<'static>, reset_token: Option<u128>,
361
- advertise: bool, path_id: Option<usize>, retire_if_needed: bool,
380
+ &mut self,
381
+ cid: ConnectionId<'static>,
382
+ reset_token: Option<u128>,
383
+ advertise: bool,
384
+ path_id: Option<usize>,
385
+ retire_if_needed: bool,
362
386
  ) -> Result<u64> {
363
387
  if self.zero_length_scid {
364
388
  return Err(Error::InvalidState);
@@ -406,7 +430,9 @@ impl ConnectionIdentifiers {
406
430
 
407
431
  /// Sets the initial destination identifier.
408
432
  pub fn set_initial_dcid(
409
- &mut self, cid: ConnectionId<'static>, reset_token: Option<u128>,
433
+ &mut self,
434
+ cid: ConnectionId<'static>,
435
+ reset_token: Option<u128>,
410
436
  path_id: Option<usize>,
411
437
  ) {
412
438
  // Record the zero-length DCID status.
@@ -429,8 +455,12 @@ impl ConnectionIdentifiers {
429
455
  /// sequence number of retired DCIDs that were linked to their respective
430
456
  /// Path ID.
431
457
  pub fn new_dcid(
432
- &mut self, cid: ConnectionId<'static>, seq: u64, reset_token: u128,
433
- retire_prior_to: u64, retired_path_ids: &mut SmallVec<[(u64, usize); 1]>,
458
+ &mut self,
459
+ cid: ConnectionId<'static>,
460
+ seq: u64,
461
+ reset_token: u128,
462
+ retire_prior_to: u64,
463
+ retired_path_ids: &mut SmallVec<[(u64, usize); 1]>,
434
464
  ) -> Result<()> {
435
465
  if self.zero_length_dcid {
436
466
  return Err(Error::InvalidState);
@@ -442,10 +472,8 @@ impl ConnectionIdentifiers {
442
472
  // sequence number is used for different connection IDs, the endpoint
443
473
  // MAY treat that receipt as a connection error of type
444
474
  // PROTOCOL_VIOLATION.
445
- if let Some(e) = self.dcids.iter().find(|e| e.cid == cid || e.seq == seq)
446
- {
447
- if e.cid != cid || e.seq != seq || e.reset_token != Some(reset_token)
448
- {
475
+ if let Some(e) = self.dcids.iter().find(|e| e.cid == cid || e.seq == seq) {
476
+ if e.cid != cid || e.seq != seq || e.reset_token != Some(reset_token) {
449
477
  return Err(Error::InvalidFrame);
450
478
  }
451
479
  // The identifier is already there, nothing to do.
@@ -490,8 +518,8 @@ impl ConnectionIdentifiers {
490
518
  // After processing a NEW_CONNECTION_ID frame and adding and retiring
491
519
  // active connection IDs, if the number of active connection IDs exceeds
492
520
  // the value advertised in its active_connection_id_limit transport
493
- // parameter, an endpoint MUST close the connection with an error of type
494
- // CONNECTION_ID_LIMIT_ERROR.
521
+ // parameter, an endpoint MUST close the connection with an error of
522
+ // type CONNECTION_ID_LIMIT_ERROR.
495
523
  if retire_prior_to > self.largest_peer_retire_prior_to {
496
524
  let retired = &mut self.retire_dcid_seqs;
497
525
 
@@ -503,23 +531,18 @@ impl ConnectionIdentifiers {
503
531
 
504
532
  // To avoid exceeding the capacity of the inner `VecDeque`, we first
505
533
  // remove the elements and then insert the new one.
506
- let index = self
507
- .dcids
508
- .inner
509
- .partition_point(|e| e.seq < retire_prior_to);
510
-
511
- for e in self.dcids.inner.drain(..index) {
534
+ self.dcids.retire_prior_to(retire_prior_to, |e| {
512
535
  if let Some(pid) = e.path_id {
513
536
  retired_path_ids.push((e.seq, pid));
514
537
  }
515
538
 
516
539
  if let Err(e) = retired.insert(e.seq) {
517
- // Delay propagating the error as we need to try to insert
518
- // the new DCID first.
519
- retired_dcid_queue_err = Some(e);
520
- break;
540
+ // Keep the first error we encounter and report it _after_
541
+ // inserting the new DCID. We still have to process the
542
+ // remaining retired DCIDs.
543
+ retired_dcid_queue_err.get_or_insert(e);
521
544
  }
522
- }
545
+ });
523
546
 
524
547
  self.largest_peer_retire_prior_to = retire_prior_to;
525
548
  }
@@ -547,9 +570,7 @@ impl ConnectionIdentifiers {
547
570
  /// Returns the path ID that was associated to the retired CID, if any.
548
571
  ///
549
572
  /// [`InvalidState`]: enum.Error.html#InvalidState
550
- pub fn retire_scid(
551
- &mut self, seq: u64, pkt_dcid: &ConnectionId,
552
- ) -> Result<Option<usize>> {
573
+ pub fn retire_scid(&mut self, seq: u64, pkt_dcid: &ConnectionId) -> Result<Option<usize>> {
553
574
  if seq >= self.next_scid_seq {
554
575
  return Err(Error::InvalidState);
555
576
  }
@@ -606,9 +627,7 @@ impl ConnectionIdentifiers {
606
627
 
607
628
  /// Updates the Source Connection ID entry with the provided sequence number
608
629
  /// to indicate that it is now linked to the provided path ID.
609
- pub fn link_scid_to_path_id(
610
- &mut self, dcid_seq: u64, path_id: usize,
611
- ) -> Result<()> {
630
+ pub fn link_scid_to_path_id(&mut self, dcid_seq: u64, path_id: usize) -> Result<()> {
612
631
  let e = self.scids.get_mut(dcid_seq).ok_or(Error::InvalidState)?;
613
632
  e.path_id = Some(path_id);
614
633
  Ok(())
@@ -616,9 +635,7 @@ impl ConnectionIdentifiers {
616
635
 
617
636
  /// Updates the Destination Connection ID entry with the provided sequence
618
637
  /// number to indicate that it is now linked to the provided path ID.
619
- pub fn link_dcid_to_path_id(
620
- &mut self, dcid_seq: u64, path_id: usize,
621
- ) -> Result<()> {
638
+ pub fn link_dcid_to_path_id(&mut self, dcid_seq: u64, path_id: usize) -> Result<()> {
622
639
  let e = self.dcids.get_mut(dcid_seq).ok_or(Error::InvalidState)?;
623
640
  e.path_id = Some(path_id);
624
641
  Ok(())
@@ -660,9 +677,7 @@ impl ConnectionIdentifiers {
660
677
  /// Finds the sequence number of the Source Connection ID having the
661
678
  /// provided value and the identifier of the path using it, if any.
662
679
  #[inline]
663
- pub fn find_scid_seq(
664
- &self, scid: &ConnectionId,
665
- ) -> Option<(u64, Option<usize>)> {
680
+ pub fn find_scid_seq(&self, scid: &ConnectionId) -> Option<(u64, Option<usize>)> {
666
681
  self.scids.iter().find_map(|e| {
667
682
  if e.cid == *scid {
668
683
  Some((e.seq, e.path_id))
@@ -716,9 +731,7 @@ impl ConnectionIdentifiers {
716
731
  /// source Connection ID set that need to be advertised to the peer through
717
732
  /// NEW_CONNECTION_ID frames.
718
733
  #[inline]
719
- pub fn mark_advertise_new_scid_seq(
720
- &mut self, scid_seq: u64, advertise: bool,
721
- ) {
734
+ pub fn mark_advertise_new_scid_seq(&mut self, scid_seq: u64, advertise: bool) {
722
735
  if advertise {
723
736
  self.advertise_new_scid_seqs.push_back(scid_seq);
724
737
  } else if let Some(index) = self
@@ -734,9 +747,7 @@ impl ConnectionIdentifiers {
734
747
  /// retired destination Connection ID set that need to be advertised to the
735
748
  /// peer through RETIRE_CONNECTION_ID frames.
736
749
  #[inline]
737
- pub fn mark_retire_dcid_seq(
738
- &mut self, dcid_seq: u64, retire: bool,
739
- ) -> Result<()> {
750
+ pub fn mark_retire_dcid_seq(&mut self, dcid_seq: u64, retire: bool) -> Result<()> {
740
751
  if retire {
741
752
  self.retire_dcid_seqs.insert(dcid_seq)?;
742
753
  } else {
@@ -794,9 +805,7 @@ impl ConnectionIdentifiers {
794
805
 
795
806
  /// Gets the NEW_CONNECTION_ID frame related to the source connection ID
796
807
  /// with sequence `seq_num`.
797
- pub fn get_new_connection_id_frame_for(
798
- &self, seq_num: u64,
799
- ) -> Result<frame::Frame> {
808
+ pub fn get_new_connection_id_frame_for(&self, seq_num: u64) -> Result<frame::Frame> {
800
809
  let e = self.scids.get(seq_num).ok_or(Error::InvalidState)?;
801
810
  Ok(frame::Frame::NewConnectionId {
802
811
  seq_num,
@@ -957,6 +966,8 @@ mod tests {
957
966
 
958
967
  // Trying to remove the last DCID triggers an error.
959
968
  assert_eq!(ids.retire_dcid(2), Err(Error::OutOfIdentifiers));
969
+ assert_eq!(ids.retire_dcid(0), Err(Error::InvalidState));
970
+ assert_eq!(ids.retire_dcid(1), Err(Error::InvalidState));
960
971
  assert_eq!(ids.available_dcids(), 0);
961
972
  assert!(!ids.has_retire_dcids());
962
973
  assert_eq!(ids.dcids.len(), 1);
@@ -988,15 +999,18 @@ mod tests {
988
999
  assert!(ids.new_dcid(dcid, 4, rt, 3, &mut retired_path_ids).is_ok());
989
1000
  assert_eq!(ids.dcids.len(), 2);
990
1001
 
991
- // Insert DCID #1 (e.g due to packet reordering).
1002
+ // Insert DCID #1 (e.g due to packet reordering). It should be discarded
1003
+ // due to `largest_peer_retire_prior_to`.
992
1004
  let (dcid, rt) = create_cid_and_reset_token(16);
993
1005
  assert!(ids.new_dcid(dcid, 1, rt, 0, &mut retired_path_ids).is_ok());
994
1006
  assert_eq!(ids.dcids.len(), 2);
1007
+ assert!(ids.get_dcid(1).is_err());
995
1008
 
996
1009
  // Try inserting DCID #1 again (e.g. due to retransmission).
997
1010
  let (dcid, rt) = create_cid_and_reset_token(16);
998
1011
  assert!(ids.new_dcid(dcid, 1, rt, 0, &mut retired_path_ids).is_ok());
999
1012
  assert_eq!(ids.dcids.len(), 2);
1013
+ assert!(ids.get_dcid(1).is_err());
1000
1014
  }
1001
1015
 
1002
1016
  #[test]
@@ -1033,12 +1047,57 @@ mod tests {
1033
1047
 
1034
1048
  // Retire prior to DCID that was just retired.
1035
1049
  //
1036
- // This is largely to test that the `partition_point()` call above
1037
- // returns a meaningful value even if the actual sequence that is
1038
- // searched isn't present in the list.
1050
+ // This is largely to test that `retire_prior_to()` works correctly even
1051
+ // if the actual sequence that is searched isn't present in the list.
1039
1052
  let (dcid, rt) = create_cid_and_reset_token(16);
1040
1053
  assert!(ids.new_dcid(dcid, 5, rt, 3, &mut retired_path_ids).is_ok());
1041
1054
  assert_eq!(ids.dcids.len(), 2);
1055
+
1056
+ // Retire all current DCIDs while adding a new one
1057
+ let (dcid, rt) = create_cid_and_reset_token(16);
1058
+ assert!(ids.new_dcid(dcid, 6, rt, 6, &mut retired_path_ids).is_ok());
1059
+ assert_eq!(ids.dcids.len(), 1);
1060
+ }
1061
+
1062
+ #[test]
1063
+ fn new_dcid_partial_retire_out_of_order() {
1064
+ let (scid, _) = create_cid_and_reset_token(16);
1065
+ let (dcid, _) = create_cid_and_reset_token(16);
1066
+
1067
+ let mut retired_path_ids = SmallVec::new();
1068
+
1069
+ let mut ids = ConnectionIdentifiers::new(5, &scid, 0, None);
1070
+ ids.set_initial_dcid(dcid, None, Some(0));
1071
+
1072
+ assert_eq!(ids.available_dcids(), 0);
1073
+ assert_eq!(ids.dcids.len(), 1);
1074
+
1075
+ // Insert 5 DCIDs where some are out of order
1076
+ let seq_nums = [5, 3, 2, 19, 8];
1077
+ for &seq in &seq_nums {
1078
+ let (dcid, rt) = create_cid_and_reset_token(16);
1079
+ assert!(ids
1080
+ .new_dcid(dcid, seq, rt, 1, &mut retired_path_ids)
1081
+ .is_ok());
1082
+ }
1083
+ assert_eq!(ids.dcids.len(), 5);
1084
+
1085
+ // Trigger a retire of sequence numbers 2 and 3, inserting #20
1086
+ let (dcid, rt) = create_cid_and_reset_token(16);
1087
+ assert!(ids.new_dcid(dcid, 20, rt, 4, &mut retired_path_ids).is_ok());
1088
+ assert_eq!(ids.dcids.len(), 4);
1089
+ assert!(ids.get_dcid(20).is_ok());
1090
+
1091
+ for &seq in &seq_nums {
1092
+ let dcid = ids.get_dcid(seq);
1093
+ assert_eq!(dcid.is_ok(), seq >= 4);
1094
+ }
1095
+
1096
+ // Check that the DCID deque maintains insertion order
1097
+ let seq_iter = ids.dcids.inner.iter().map(|e| e.seq);
1098
+ for (seq, expected) in seq_iter.zip([5, 19, 8, 20]) {
1099
+ assert_eq!(seq, expected);
1100
+ }
1042
1101
  }
1043
1102
 
1044
1103
  #[test]
@@ -1072,8 +1131,17 @@ mod tests {
1072
1131
  assert_eq!(ids.pop_retired_scid(), None);
1073
1132
 
1074
1133
  assert_eq!(ids.retire_scid(1, &scid3), Ok(None));
1134
+ assert_eq!(ids.scids.len(), 1);
1135
+
1136
+ // The peer may retransmit RETIRE_CONNECTION_ID.
1137
+ assert_eq!(ids.retire_scid(1, &scid3), Ok(None));
1138
+ assert_eq!(ids.scids.len(), 1);
1075
1139
 
1076
1140
  assert_eq!(ids.pop_retired_scid(), Some(scid2));
1077
1141
  assert_eq!(ids.pop_retired_scid(), None);
1142
+
1143
+ // The last SCID cannot be retired.
1144
+ assert_eq!(ids.retire_scid(2, &scid3), Err(Error::OutOfIdentifiers));
1145
+ assert_eq!(ids.scids.len(), 1);
1078
1146
  }
1079
1147
  }