quic 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5acecd3e782e59b5c380793fa4578eece61bd51c81fcab5467fb190239743763
4
- data.tar.gz: ac7453f336d3540141d4a549ac02d918b36246d47de12e221d7e2267a853f592
3
+ metadata.gz: 0a298ec6146511eeaf50b91381250dfb906beae9c9aa4bdadf1e485147c276af
4
+ data.tar.gz: 5a976fbb254f0670e7c390536da549cba5095869f636b89e21e348910be72fe2
5
5
  SHA512:
6
- metadata.gz: 63730e7e519301b35da42c040b1c0de81d4294bbeecc886e5a90726dd0eaea82ca904768a57c7cd40a0229d29f7cacf8adfede63f6cf323400fff2697f065d88
7
- data.tar.gz: bf37cb7e2bb04a44175fff8e34b661ad17413ddbcfd7ad4811a6b03f16257bb6b582856687bb93a0f5629fb4483a0f314b9cf900b898485ee79a0edbc5544dc5
6
+ metadata.gz: 2be81f8d43f6e67af7aea38bc538dcb24f381d31cace3c1f26c3aabdc777e0e974598741e7779fab126ba6a67e387f9ba02192321183b19208adf9e0dedbc43f
7
+ data.tar.gz: 0b0dc229bd438803f8af9e9b73e03ccfc63b71aaa6e32ef6f6c53f29cd7001343673dab56408de85fa0cac3c4bc264bf70e4160897d137f40caf5f3d838a8d02
data/CHANGELOG.md CHANGED
@@ -1,3 +1,22 @@
1
+ ## [0.0.8] - 2026-12-02
2
+
3
+ ### Added
4
+ - QUIC version 2 ([RFC 9369](https://www.rfc-editor.org/rfc/rfc9369)) and version negotiation ([RFC 9368](https://www.rfc-editor.org/rfc/rfc9368)). `QUIC::Settings` gains `version` (the version a client starts with, default `:v1`), `preferred_versions` and `available_versions` (both default `[:v2, :v1]`). A wrong value raises `ArgumentError` when a connection or an Endpoint is made. ([#32](https://github.com/unasuke/quic-ruby/pull/32))
5
+ - `#negotiated_version` of `QUIC::Connection::Client` and `Server` returns `:v1`, `:v2`, or `nil` before the version is settled. ([#32](https://github.com/unasuke/quic-ruby/pull/32))
6
+ - A client that receives Version Negotiation connects again, as the same `Client` object, with the first of its `preferred_versions` the server offered. `handshake_timeout` counts again from the reconnect, and with `qlog_dir` the client leaves a second qlog file. ([#32](https://github.com/unasuke/quic-ruby/pull/32))
7
+ - `QUIC::Error::VersionNegotiation`, raised when the server offers no version the client can use, or when ngtcp2 finds the version was forced down (before, `QUIC::Error::Unknown`). ([#32](https://github.com/unasuke/quic-ruby/pull/32))
8
+ - `#qlog_path` of `QUIC::Connection::Client` and `Server` returns the absolute path of the connection's qlog file, or `nil` without one, and `#flush_qlog` writes out the qlog records still buffered, so the file can be read while the connection runs. ([#33](https://github.com/unasuke/quic-ruby/pull/33))
9
+ - `#alpn_protocol` of `QUIC::Connection::Client` and `Server` returns the negotiated ALPN protocol (frozen, ASCII-8BIT), and `#cipher_suite` the cipher suite's IANA name such as `"TLS_AES_128_GCM_SHA256"` (frozen, US-ASCII). Both are `nil` until the handshake settles them. ([#37](https://github.com/unasuke/quic-ruby/pull/37))
10
+ - `QUIC::Settings#qlog_max_bytes` caps each qlog file, at 64 MiB by default, which now applies to every `qlog_dir` user; `nil` removes the limit. The record that would take a file past it is dropped with every one after it, and the file, ending with the last whole record, is closed while the connection goes on. A value other than `nil` or an Integer from 1 to 2**63 - 1 raises `ArgumentError` when a connection or an Endpoint is made. ([#38](https://github.com/unasuke/quic-ruby/pull/38))
11
+
12
+ ### Changed
13
+ - With the default settings, a client offers v2 alongside v1, and a server moves a client that offers v2 to v2. A peer that knows only v1 stays on v1. ([#32](https://github.com/unasuke/quic-ruby/pull/32))
14
+ - A server accepts only a client starting with a version in its `preferred_versions` or `available_versions`. `QUIC::Endpoint` answers any other version with Version Negotiation, which now lists its `preferred_versions` (was v1 only), and `Connection::Server.accept` raises `QUIC::Error::Proto`. ([#32](https://github.com/unasuke/quic-ruby/pull/32))
15
+ - `#remote_address` of `QUIC::Connection::Client` and `Server` returns the peer of the connection's current path, so a connection `QUIC::Endpoint` made has one too (was `nil`), and it follows a client that migrates to a new address. Each call returns a new `Addrinfo`, which has no `==`: compare `#to_sockaddr`. It raises `QUIC::Error::InvalidState` when there is no connection behind the object. ([#37](https://github.com/unasuke/quic-ruby/pull/37))
16
+
17
+ ### Fixed
18
+ - The methods of a `QUIC::Connection::Client` or `Server` made with `.allocate` raise `QUIC::Error::InvalidState` instead of crashing the process, and the `quic/ext.h` functions return `QUIC_EXT_ERR_INVALID_STATE` for it (`local_max_streams_bidi` returns 0). ([#32](https://github.com/unasuke/quic-ruby/pull/32))
19
+
1
20
  ## [0.0.7] - 2026-11-08
2
21
 
3
22
  ### Changed
data/README.md CHANGED
@@ -82,7 +82,7 @@ end
82
82
 
83
83
  ### Many connections on one socket
84
84
 
85
- `QUIC::Endpoint` serves many connections on one UDP socket. It routes each datagram to its connection by connection ID, makes a connection for each new client, and answers what no connection can: Version Negotiation for a version it does not support, a Stateless Reset for a packet of a connection it does not know, and CONNECTION_REFUSED beyond `max_connections` (1024 by default) or after `#stop_accepting`. The socket and the I/O loop stay with you:
85
+ `QUIC::Endpoint` serves many connections on one UDP socket. It routes each datagram to its connection by connection ID, makes a connection for each new client, and answers what no connection can: Version Negotiation, listing its `preferred_versions`, for a version its settings do not accept (see [QUIC versions](#quic-versions)), a Stateless Reset for a packet of a connection it does not know, and CONNECTION_REFUSED beyond `max_connections` (1024 by default) or after `#stop_accepting`. The socket and the I/O loop stay with you:
86
86
 
87
87
  ```ruby
88
88
  require "quic"
@@ -143,7 +143,35 @@ settings = QUIC::Settings.default.with(alpn: ["perf"], verify_mode: :none)
143
143
  settings = QUIC::Settings.default.with(alpn: ["h3"], qlog_dir: "/tmp/qlog")
144
144
  ```
145
145
 
146
- It applies to clients, `Connection::Server.accept` and every connection of an Endpoint. `Client.new`, `Server.accept` and `Endpoint.new` raise `ArgumentError` unless it is a writable directory. A file that cannot be opened later, when a connection is made, only costs that connection its qlog. A connection's file is closed as soon as the connection ends, not when the connection is garbage collected.
146
+ It applies to clients, `Connection::Server.accept` and every connection of an Endpoint. `Client.new`, `Server.accept` and `Endpoint.new` raise `ArgumentError` unless it is a writable directory. A file that cannot be opened later, when a connection is made (a symbolic link in its place included), only costs that connection its qlog. A connection's file is closed as soon as the connection ends, not when the connection is garbage collected. A client that connects again after Version Negotiation leaves two files: the first connection's, closed at the reconnect, and the new one's.
147
+
148
+ `Connection#qlog_path` tells where a connection's file is, for a client and a server (an Endpoint's connections included) alike:
149
+
150
+ ```ruby
151
+ client.qlog_path # => "/tmp/qlog/3f1c9a0e5b7d2648.sqlog"
152
+ ```
153
+
154
+ It is an absolute path: a relative `qlog_dir` is expanded against the current directory when the connection is made. It stays the same after the file is closed, and is nil without `qlog_dir` or when the file could not be opened. After a reconnect following Version Negotiation, it is the new file's path.
155
+
156
+ Records are written whole, never cut off in the middle, but they are buffered: up to 16 KiB of them reach the file only when the buffer fills up, when the connection ends or its qlog stops, or on `Connection#flush_qlog`. To read the qlog of a connection that is still going, flush it first, from the thread that drives the connection:
157
+
158
+ ```ruby
159
+ client.flush_qlog
160
+ qlog = File.binread(client.qlog_path)
161
+ qlog = qlog[0, (qlog.rindex("\n") || -1) + 1] # whole records only
162
+ ```
163
+
164
+ A file that another thread reads while the connection writes to it may end in the middle of a record, so a reader keeps what it read up to the last `"\n"` (none at all means no record yet). Read the file with `File.read` or the like, not `mmap`: a failed write can make the file shorter (see below).
165
+
166
+ `qlog_max_bytes` caps each qlog file, at 64 MiB by default (`nil` for no limit):
167
+
168
+ ```ruby
169
+ settings = QUIC::Settings.default.with(alpn: ["h3"], qlog_dir: "/tmp/qlog", qlog_max_bytes: 16 * 1024 * 1024)
170
+ ```
171
+
172
+ The record that would take a file past it is dropped with every one after it, and the file, which ends with the last whole record, is closed; the connection goes on without qlog. The limit counts each file on its own, so a client that connects again after Version Negotiation counts its second file from 0.
173
+
174
+ If a write fails (the disk is full, for example), that connection's qlog stops: its file ends with the last record written in full, and the connection goes on without qlog.
147
175
 
148
176
  ### From other native extensions
149
177
 
@@ -168,6 +196,27 @@ const quic_ext_api *api = get ? get(QUIC_EXT_ABI_MAJOR) : NULL; /* NULL: a diffe
168
196
 
169
197
  A connection given a stream handler with `set_stream_handler` makes no `QUIC::Stream`: the handler receives every stream's data and hands out what to send as `#write_pkt` builds each packet, and `#open_bidi_stream`, `#accept_stream` and the like raise `QUIC::Error::InvalidState`. The comment at the top of [`ext.h`](ext/quic/include/quic/ext.h) states the rules on versions, exceptions and lifetimes.
170
198
 
199
+ ### QUIC versions
200
+
201
+ Both QUIC version 1 ([RFC 9000](https://www.rfc-editor.org/rfc/rfc9000)) and version 2 ([RFC 9369](https://www.rfc-editor.org/rfc/rfc9369)) are supported, written `:v1` and `:v2`. With the default settings on both ends, a client starts with v1 and the server moves the connection to v2 during the handshake (compatible version negotiation, [RFC 9368](https://www.rfc-editor.org/rfc/rfc9368)). A peer that knows only v1 stays on v1.
202
+
203
+ Three settings choose the versions:
204
+
205
+ - `version` (default `:v1`): the version a client starts with. A server does not read it.
206
+ - `preferred_versions` (default `[:v2, :v1]`): the versions in order of preference. A server moves a client to the first of them the client can use, and lists them in its Version Negotiation packets.
207
+ - `available_versions` (default `[:v2, :v1]`): the versions announced in the `version_information` transport parameter.
208
+
209
+ ```ruby
210
+ # Start with v2, and do not fall back to v1.
211
+ settings = QUIC::Settings.default.with(alpn: ["h3"], version: :v2, preferred_versions: [:v2], available_versions: [:v2])
212
+ ```
213
+
214
+ A client's `version` has to be in both lists. A server accepts a client that starts with any version in either list: an Endpoint answers any other version with Version Negotiation, and `Connection::Server.accept` raises `QUIC::Error::Proto`. A wrong value in any of the three raises `ArgumentError` when a connection or an Endpoint is made.
215
+
216
+ When a server answers a client's first packet with Version Negotiation, the client connects again with the first of its `preferred_versions` that the server offered and that is also in its `available_versions`. It stays the same `Client` object, and `#run` goes on as if nothing had happened. `handshake_timeout` counts again from the reconnect, so the handshake can take up to the time until Version Negotiation arrived plus `handshake_timeout`. A client reconnects only once; a second Version Negotiation is ignored ([RFC 9368](https://www.rfc-editor.org/rfc/rfc9368) section 4).
217
+
218
+ `#negotiated_version` returns the version a connection settled on (`:v1` or `:v2`), or `nil` before it is settled. The connection fails with `QUIC::Error::VersionNegotiation` when the server offered no version the client can use (the message lists what it offered), or when ngtcp2 finds that the version was forced down to one the client should not have chosen.
219
+
171
220
  ## Limitations
172
221
 
173
222
  - **No certificate revocation checking.** CRLs and OCSP are not consulted.
@@ -116,6 +116,244 @@ static void quic_client_setup_verify(quic_conn_t *c, VALUE settings_v,
116
116
  c->tls_ctx.verify_certificate = &c->verify_cert.super;
117
117
  }
118
118
 
119
+ /* Raise ArgumentError unless chosen, the version a client starts with, is
120
+ in versions, its list called name. */
121
+ static void quic_client_require_chosen(uint32_t chosen,
122
+ const uint32_t *versions, size_t len,
123
+ const char *name) {
124
+ for (size_t i = 0; i < len; i++) {
125
+ if (versions[i] == chosen)
126
+ return;
127
+ }
128
+ rb_raise(rb_eArgError, "version :%s must be in %s",
129
+ chosen == NGTCP2_PROTO_VER_V2 ? "v2" : "v1", name);
130
+ }
131
+
132
+ /* What a client's ngtcp2_conn is made from: the arguments of _open, read and
133
+ checked before anything is built or freed, so that a bad value changes
134
+ nothing. The VALUEs live on the stack, which keeps them alive. */
135
+ struct quic_client_params {
136
+ VALUE local_sockaddr;
137
+ VALUE remote_sockaddr;
138
+ VALUE server_name;
139
+ VALUE settings_v;
140
+ ngtcp2_settings settings;
141
+ quic_versions_buf vbuf; /* settings points into it */
142
+ ngtcp2_transport_params params;
143
+ };
144
+
145
+ static void quic_client_read_params(VALUE args, struct quic_client_params *p) {
146
+ p->local_sockaddr = rb_hash_aref(args, ID2SYM(rb_intern("local_sockaddr")));
147
+ p->remote_sockaddr = rb_hash_aref(args, ID2SYM(rb_intern("remote_sockaddr")));
148
+ p->server_name = rb_hash_aref(args, ID2SYM(rb_intern("server_name")));
149
+ p->settings_v = rb_hash_aref(args, ID2SYM(rb_intern("settings")));
150
+ VALUE transport_params =
151
+ rb_hash_aref(args, ID2SYM(rb_intern("transport_params")));
152
+
153
+ quic_fill_settings(&p->settings, p->settings_v, &p->vbuf);
154
+ /* ngtcp2 asserts both, so a wrong Settings would abort the process. */
155
+ quic_client_require_chosen(p->vbuf.chosen, p->vbuf.preferred,
156
+ p->vbuf.preferredlen, "preferred_versions");
157
+ quic_client_require_chosen(p->vbuf.chosen, p->vbuf.available,
158
+ p->vbuf.availablelen, "available_versions");
159
+ quic_fill_transport_params(&p->params, transport_params);
160
+ }
161
+
162
+ /* ngtcp2_recv_version_negotiation. Keeps what the server offered for the
163
+ error message and picks the version to switch to; #read_pkt does the rest
164
+ once ngtcp2 has returned, in quic_client_handle_version_negotiation.
165
+ ngtcp2 calls it at most once per ngtcp2_conn, and never for a packet
166
+ that offers the version this one started with. */
167
+ static int quic_client_recv_version_negotiation_cb(ngtcp2_conn *conn,
168
+ const ngtcp2_pkt_hd *hd,
169
+ const uint32_t *sv,
170
+ size_t nsv,
171
+ void *user_data) {
172
+ (void)conn;
173
+ (void)hd;
174
+ quic_conn_t *c = (quic_conn_t *)user_data;
175
+ size_t kept = nsv < QUIC_VN_OFFERED_MAX ? nsv : QUIC_VN_OFFERED_MAX;
176
+ memcpy(c->vn_offered, sv, kept * sizeof(sv[0]));
177
+ c->vn_offeredlen = nsv;
178
+ /* Every candidate is v1 or v2, which ngtcp2_select_version asserts. */
179
+ c->vn_version =
180
+ ngtcp2_select_version(c->vn_candidates, c->vn_candidateslen, sv, nsv);
181
+ return 0;
182
+ }
183
+
184
+ struct quic_client_connect_args {
185
+ quic_conn_t *c;
186
+ struct quic_client_params *p;
187
+ uint32_t chosen;
188
+ uint32_t original;
189
+ };
190
+
191
+ /* Make c's ngtcp2_conn and ptls_t, starting with chosen. original is the
192
+ version the client first started with: chosen itself, or the one Version
193
+ Negotiation turned down. Raises; quic_client_connect cleans up. */
194
+ static VALUE quic_client_connect_body(VALUE arg) {
195
+ struct quic_client_connect_args *a = (struct quic_client_connect_args *)arg;
196
+ quic_conn_t *c = a->c;
197
+ struct quic_client_params *p = a->p;
198
+
199
+ /* Every time, not once: ngtcp2_crypto_picotls_deconfigure_session frees
200
+ what the last session allocated without clearing the pointers, and
201
+ ctx_init clears them along with the last handshake's properties. It
202
+ clears additional_extensions too, which picotls asserts on. */
203
+ ngtcp2_crypto_picotls_ctx_init(&c->cptls);
204
+ /* [0] is filled in by configure_client_session with the QUIC transport
205
+ parameters; [1] terminates the list. */
206
+ c->tls_exts[0].type = UINT16_MAX;
207
+ c->tls_exts[1].type = UINT16_MAX;
208
+ c->cptls.handshake_properties.additional_extensions = c->tls_exts;
209
+
210
+ /* New ones on a reconnect too, as examples/client.cc makes a new
211
+ connection. */
212
+ c->scid.datalen = QUIC_SCID_LEN;
213
+ if (RAND_bytes(c->scid.data, QUIC_SCID_LEN) != 1) {
214
+ rb_raise(rb_eRuntimeError, "RAND_bytes(scid) failed");
215
+ }
216
+ c->dcid.datalen = 8;
217
+ if (RAND_bytes(c->dcid.data, 8) != 1) {
218
+ rb_raise(rb_eRuntimeError, "RAND_bytes(dcid) failed");
219
+ }
220
+
221
+ ngtcp2_callbacks callbacks;
222
+ quic_conn_fill_common_callbacks(&callbacks);
223
+ callbacks.client_initial = ngtcp2_crypto_client_initial_cb;
224
+ callbacks.recv_retry = ngtcp2_crypto_recv_retry_cb;
225
+ callbacks.recv_version_negotiation = quic_client_recv_version_negotiation_cb;
226
+
227
+ /* quic_fill_settings leaves it 0, which ngtcp2 takes as chosen. After a
228
+ reconnect that would make it handle a second Version Negotiation and
229
+ skip the downgrade check, so it is always set. */
230
+ p->settings.original_version = a->original;
231
+
232
+ /* Opened once the caller's values have all been read, so that a bad one
233
+ leaves no file behind. quic_client_connect closes it on failure. */
234
+ quic_conn_open_qlog(c, p->settings_v, &p->settings);
235
+
236
+ /* Built only now: opening the qlog runs Ruby code, and GC.compact may
237
+ move the bytes of an embedded String. */
238
+ ngtcp2_path path = {
239
+ {(struct sockaddr *)RSTRING_PTR(p->local_sockaddr),
240
+ (ngtcp2_socklen)RSTRING_LEN(p->local_sockaddr)},
241
+ {(struct sockaddr *)RSTRING_PTR(p->remote_sockaddr),
242
+ (ngtcp2_socklen)RSTRING_LEN(p->remote_sockaddr)},
243
+ NULL,
244
+ };
245
+
246
+ int rv =
247
+ ngtcp2_conn_client_new(&c->conn, &c->dcid, &c->scid, &path, a->chosen,
248
+ &callbacks, &p->settings, &p->params, NULL, c);
249
+ if (rv != 0)
250
+ quic_raise_ngtcp2_error(rv);
251
+
252
+ /* The TLS session is built last: configure_client_session derives the QUIC
253
+ transport parameters from the conn, so it needs the conn to exist. */
254
+ c->cptls.ptls = ptls_client_new(&c->tls_ctx);
255
+ if (c->cptls.ptls == NULL)
256
+ rb_raise(rb_eRuntimeError, "ptls_client_new failed");
257
+ /* Let ngtcp2's crypto callbacks (add_handshake_data,
258
+ set_encryption_secrets, ...) resolve the ngtcp2_conn from the ptls_t. */
259
+ *ptls_get_data_ptr(c->cptls.ptls) = &c->conn_ref;
260
+ if (ngtcp2_crypto_picotls_configure_client_session(&c->cptls, c->conn) != 0) {
261
+ rb_raise(rb_eRuntimeError,
262
+ "ngtcp2_crypto_picotls_configure_client_session failed");
263
+ }
264
+ c->cptls.handshake_properties.client.negotiated_protocols.list = c->alpn;
265
+ c->cptls.handshake_properties.client.negotiated_protocols.count =
266
+ c->alpn_count;
267
+ /* ptls_set_server_name copies the name. */
268
+ if (ptls_set_server_name(c->cptls.ptls, RSTRING_PTR(p->server_name),
269
+ (size_t)RSTRING_LEN(p->server_name)) != 0) {
270
+ rb_raise(rb_eRuntimeError, "ptls_set_server_name failed");
271
+ }
272
+
273
+ ngtcp2_conn_set_tls_native_handle(c->conn, &c->cptls);
274
+ return Qnil;
275
+ }
276
+
277
+ /* Free c's ngtcp2_conn and ptls_t in quic_conn_free's order and clear the
278
+ pointers, so that nothing frees them again. ngtcp2_conn_del closes the
279
+ qlog file (NGTCP2_QLOG_WRITE_FLAG_FIN); quic_conn_close_qlog covers one
280
+ opened before ngtcp2_conn_client_new failed. Calls no Ruby code. */
281
+ static void quic_client_discard(quic_conn_t *c) {
282
+ if (c->conn != NULL) {
283
+ ngtcp2_conn_del(c->conn);
284
+ c->conn = NULL;
285
+ }
286
+ if (c->cptls.ptls != NULL) {
287
+ ngtcp2_crypto_picotls_deconfigure_session(&c->cptls);
288
+ ptls_free(c->cptls.ptls);
289
+ c->cptls.ptls = NULL;
290
+ }
291
+ quic_conn_close_qlog(c);
292
+ }
293
+
294
+ /* quic_client_connect_body, leaving c with neither an ngtcp2_conn nor a
295
+ ptls_t when it raises. */
296
+ static void quic_client_connect(quic_conn_t *c, struct quic_client_params *p,
297
+ uint32_t chosen, uint32_t original) {
298
+ struct quic_client_connect_args args = {c, p, chosen, original};
299
+ int state = 0;
300
+ rb_protect(quic_client_connect_body, (VALUE)&args, &state);
301
+ if (state != 0) {
302
+ quic_client_discard(c);
303
+ rb_jump_tag(state);
304
+ }
305
+ }
306
+
307
+ /* "no QUIC version in common with the server (offered: 0x00000001, ...)",
308
+ the versions in the order the packet listed them. */
309
+ static VALUE quic_client_no_common_version_error(const quic_conn_t *c) {
310
+ VALUE msg =
311
+ rb_str_new_cstr("no QUIC version in common with the server (offered: ");
312
+ size_t kept = c->vn_offeredlen < QUIC_VN_OFFERED_MAX ? c->vn_offeredlen
313
+ : QUIC_VN_OFFERED_MAX;
314
+ if (kept == 0)
315
+ rb_str_cat_cstr(msg, "none");
316
+ for (size_t i = 0; i < kept; i++) {
317
+ rb_str_catf(msg, "%s0x%08x", i == 0 ? "" : ", ",
318
+ (unsigned int)c->vn_offered[i]);
319
+ }
320
+ if (c->vn_offeredlen > kept)
321
+ rb_str_cat_cstr(msg, ", ...");
322
+ rb_str_cat_cstr(msg, ")");
323
+
324
+ VALUE exc = rb_exc_new_str(rb_eQUICErrorVersionNegotiation, msg);
325
+ rb_ivar_set(exc, rb_intern("@code"),
326
+ INT2NUM(NGTCP2_ERR_RECV_VERSION_NEGOTIATION));
327
+ return exc;
328
+ }
329
+
330
+ void quic_client_handle_version_negotiation(quic_conn_t *c) {
331
+ if (c->vn_version == 0) {
332
+ /* The connection ends here. */
333
+ quic_conn_close_qlog(c);
334
+ rb_exc_raise(quic_client_no_common_version_error(c));
335
+ }
336
+
337
+ /* ngtcp2 drops Version Negotiation once it has processed an Initial, and
338
+ no stream exists before the handshake (there is no 0-RTT), so nothing
339
+ is lost by starting over. Checked all the same. */
340
+ VALUE streams = rb_ivar_get(c->owner, rb_intern("@streams"));
341
+ if (RB_TYPE_P(streams, T_HASH) && RHASH_SIZE(streams) != 0) {
342
+ rb_raise(rb_eQUICErrorInvalidState,
343
+ "Version Negotiation arrived after a stream was opened");
344
+ }
345
+
346
+ struct quic_client_params p;
347
+ quic_client_read_params(rb_ivar_get(c->owner, rb_intern("@open_args")), &p);
348
+
349
+ /* From here on c has no ngtcp2_conn until the new one is made; if that
350
+ fails, quic_conn_get_open says why. */
351
+ c->rebuild_failed = true;
352
+ quic_client_discard(c);
353
+ quic_client_connect(c, &p, c->vn_version, p.vbuf.chosen);
354
+ c->rebuild_failed = false;
355
+ }
356
+
119
357
  static VALUE quic_client_open(int argc, VALUE *argv, VALUE klass) {
120
358
  VALUE opts = Qnil;
121
359
  rb_scan_args(argc, argv, "0:", &opts);
@@ -147,17 +385,32 @@ static VALUE quic_client_open(int argc, VALUE *argv, VALUE klass) {
147
385
  VALUE self = quic_conn_alloc(klass);
148
386
  rb_ivar_set(self, rb_intern("@server_name"), server_name);
149
387
 
388
+ /* What the connection is made from, kept to make it again after Version
389
+ Negotiation. The Strings are frozen copies, so that the caller changing
390
+ its own cannot change what the second connection is made from. */
391
+ VALUE open_args = rb_hash_new();
392
+ rb_hash_aset(open_args, ID2SYM(rb_intern("local_sockaddr")),
393
+ rb_str_new_frozen(local_sockaddr));
394
+ rb_hash_aset(open_args, ID2SYM(rb_intern("remote_sockaddr")),
395
+ rb_str_new_frozen(remote_sockaddr));
396
+ rb_hash_aset(open_args, ID2SYM(rb_intern("server_name")),
397
+ rb_str_new_frozen(server_name));
398
+ rb_hash_aset(open_args, ID2SYM(rb_intern("transport_params")),
399
+ transport_params);
400
+ rb_hash_aset(open_args, ID2SYM(rb_intern("settings")), settings_v);
401
+ rb_obj_freeze(open_args);
402
+ rb_ivar_set(self, rb_intern("@open_args"), open_args);
403
+
150
404
  quic_conn_t *c = quic_conn_get(self);
151
405
  c->owner = self;
152
406
  c->is_server = false;
153
407
 
408
+ /* What follows is set up once and kept across a reconnect. */
409
+
154
410
  /* An empty list means no ALPN extension, matching the old
155
411
  skip-SSL_set_alpn_protos path. */
156
412
  quic_conn_copy_alpn(c, settings_v);
157
413
 
158
- /* quic_conn_alloc already zeroed the struct, but calling ctx_init keeps
159
- the ngtcp2-side initialization explicit and the TLS setup in one place. */
160
- ngtcp2_crypto_picotls_ctx_init(&c->cptls);
161
414
  c->tls_ctx = (ptls_context_t){
162
415
  .random_bytes = ptls_openssl_random_bytes,
163
416
  .get_time = &ptls_get_time,
@@ -177,80 +430,26 @@ static VALUE quic_client_open(int argc, VALUE *argv, VALUE klass) {
177
430
  place before it runs. */
178
431
  quic_client_setup_verify(c, settings_v, server_name);
179
432
 
433
+ /* get_conn reads c->conn, so the ref follows a reconnect. */
180
434
  c->conn_ref.get_conn = quic_conn_get_conn;
181
435
  c->conn_ref.user_data = c;
182
436
 
183
- c->scid.datalen = QUIC_SCID_LEN;
184
- if (RAND_bytes(c->scid.data, QUIC_SCID_LEN) != 1) {
185
- rb_raise(rb_eRuntimeError, "RAND_bytes(scid) failed");
186
- }
187
- c->dcid.datalen = 8;
188
- if (RAND_bytes(c->dcid.data, 8) != 1) {
189
- rb_raise(rb_eRuntimeError, "RAND_bytes(dcid) failed");
190
- }
191
-
192
- ngtcp2_callbacks callbacks;
193
- quic_conn_fill_common_callbacks(&callbacks);
194
- callbacks.client_initial = ngtcp2_crypto_client_initial_cb;
195
- callbacks.recv_retry = ngtcp2_crypto_recv_retry_cb;
196
-
197
- ngtcp2_settings settings;
198
- quic_fill_settings(&settings, settings_v);
199
-
200
- ngtcp2_transport_params params;
201
- quic_fill_transport_params(&params, transport_params);
202
-
203
- /* Opened once the caller's values have all been read, so that a bad one
204
- leaves no file behind. Every raise below closes it first. */
205
- quic_conn_open_qlog(c, settings_v, &settings);
206
-
207
- ngtcp2_path path = {
208
- {(struct sockaddr *)RSTRING_PTR(local_sockaddr),
209
- (ngtcp2_socklen)RSTRING_LEN(local_sockaddr)},
210
- {(struct sockaddr *)RSTRING_PTR(remote_sockaddr),
211
- (ngtcp2_socklen)RSTRING_LEN(remote_sockaddr)},
212
- NULL,
213
- };
214
-
215
- int rv = ngtcp2_conn_client_new(&c->conn, &c->dcid, &c->scid, &path,
216
- NGTCP2_PROTO_VER_V1, &callbacks, &settings,
217
- &params, NULL, c);
218
- if (rv != 0) {
219
- quic_conn_close_qlog(c);
220
- quic_raise_ngtcp2_error(rv);
221
- }
222
-
223
- /* The TLS session is built last: configure_client_session derives the QUIC
224
- transport parameters from the conn, so it needs the conn to exist. */
225
- c->cptls.ptls = ptls_client_new(&c->tls_ctx);
226
- if (c->cptls.ptls == NULL) {
227
- quic_conn_close_qlog(c);
228
- rb_raise(rb_eRuntimeError, "ptls_client_new failed");
229
- }
230
- /* Let ngtcp2's crypto callbacks (add_handshake_data,
231
- set_encryption_secrets, ...) resolve the ngtcp2_conn from the ptls_t. */
232
- *ptls_get_data_ptr(c->cptls.ptls) = &c->conn_ref;
233
- /* [0] is filled in by configure_client_session with the QUIC transport
234
- parameters; [1] terminates the list. */
235
- c->tls_exts[0].type = UINT16_MAX;
236
- c->tls_exts[1].type = UINT16_MAX;
237
- c->cptls.handshake_properties.additional_extensions = c->tls_exts;
238
- if (ngtcp2_crypto_picotls_configure_client_session(&c->cptls, c->conn) != 0) {
239
- quic_conn_close_qlog(c);
240
- rb_raise(rb_eRuntimeError,
241
- "ngtcp2_crypto_picotls_configure_client_session failed");
242
- }
243
- c->cptls.handshake_properties.client.negotiated_protocols.list = c->alpn;
244
- c->cptls.handshake_properties.client.negotiated_protocols.count =
245
- c->alpn_count;
246
- /* ptls_set_server_name copies the name. */
247
- if (ptls_set_server_name(c->cptls.ptls, RSTRING_PTR(server_name),
248
- (size_t)RSTRING_LEN(server_name)) != 0) {
249
- quic_conn_close_qlog(c);
250
- rb_raise(rb_eRuntimeError, "ptls_set_server_name failed");
437
+ struct quic_client_params p;
438
+ quic_client_read_params(open_args, &p);
439
+
440
+ /* What Version Negotiation can switch to: a version the client both
441
+ prefers and announces. */
442
+ c->vn_candidateslen = 0;
443
+ for (size_t i = 0; i < p.vbuf.preferredlen; i++) {
444
+ for (size_t j = 0; j < p.vbuf.availablelen; j++) {
445
+ if (p.vbuf.preferred[i] == p.vbuf.available[j]) {
446
+ c->vn_candidates[c->vn_candidateslen++] = p.vbuf.preferred[i];
447
+ break;
448
+ }
449
+ }
251
450
  }
252
451
 
253
- ngtcp2_conn_set_tls_native_handle(c->conn, &c->cptls);
452
+ quic_client_connect(c, &p, p.vbuf.chosen, p.vbuf.chosen);
254
453
 
255
454
  /* Stream registry: stream_id (Integer) -> QUIC::Stream.
256
455
  Populated by #open_bidi_stream / #open_uni_stream and the stream_open