quic 0.0.6 → 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.
@@ -2,10 +2,13 @@
2
2
  #include "endpoint.h"
3
3
  #include "stream.h"
4
4
 
5
+ #include <errno.h>
6
+ #include <fcntl.h>
5
7
  #include <netinet/in.h>
6
8
  #include <string.h>
7
9
  #include <sys/socket.h>
8
10
  #include <time.h>
11
+ #include <unistd.h>
9
12
 
10
13
  #include <openssl/rand.h>
11
14
 
@@ -57,8 +60,8 @@ static void quic_conn_free(void *ptr) {
57
60
  }
58
61
 
59
62
  static size_t quic_conn_size(const void *ptr) {
60
- (void)ptr;
61
- return sizeof(quic_conn_t);
63
+ const quic_conn_t *c = (const quic_conn_t *)ptr;
64
+ return sizeof(quic_conn_t) + (c->qlog_buf != NULL ? QUIC_QLOG_BUFLEN : 0);
62
65
  }
63
66
 
64
67
  /* owner is the object wrapping this struct, so it needs no mark. */
@@ -69,6 +72,7 @@ static void quic_conn_mark(void *ptr) {
69
72
  rb_gc_mark_movable(c->endpoint_owner);
70
73
  rb_gc_mark_movable(c->error);
71
74
  rb_gc_mark_movable(c->closebuf);
75
+ rb_gc_mark_movable(c->qlog_path);
72
76
  }
73
77
 
74
78
  /* GC.compact may relocate the owner connection object. Follow it so the
@@ -83,6 +87,7 @@ static void quic_conn_compact(void *ptr) {
83
87
  c->endpoint_owner = rb_gc_location(c->endpoint_owner);
84
88
  c->error = rb_gc_location(c->error);
85
89
  c->closebuf = rb_gc_location(c->closebuf);
90
+ c->qlog_path = rb_gc_location(c->qlog_path);
86
91
  }
87
92
 
88
93
  const rb_data_type_t quic_conn_data_type = {
@@ -107,7 +112,13 @@ quic_conn_alloc(VALUE klass) {
107
112
  c->endpoint_owner = Qnil;
108
113
  c->error = Qnil;
109
114
  c->closebuf = Qnil;
110
- return TypedData_Wrap_Struct(klass, &quic_conn_data_type, c);
115
+ c->qlog_path = Qnil;
116
+ c->qlog_fd = -1;
117
+ VALUE self = TypedData_Wrap_Struct(klass, &quic_conn_data_type, c);
118
+ /* Set here so that it names the wrapping object even on one made with
119
+ .allocate, which never reaches a constructor. */
120
+ c->owner = self;
121
+ return self;
111
122
  }
112
123
 
113
124
  /* Re-raise the exception a callback left in c->pending_exc, if any. Called
@@ -121,11 +132,7 @@ static void quic_conn_raise_pending(quic_conn_t *c) {
121
132
  rb_exc_raise(exc);
122
133
  }
123
134
 
124
- /* Run body(arg) under rb_protect. An exception is kept in c->pending_exc
125
- (the first one wins; ngtcp2 stops at the first failing callback anyway)
126
- and turned into NGTCP2_ERR_CALLBACK_FAILURE, so that it never unwinds
127
- through ngtcp2. */
128
- static int quic_conn_protect(quic_conn_t *c, VALUE (*body)(VALUE), void *arg) {
135
+ int quic_conn_protect(quic_conn_t *c, VALUE (*body)(VALUE), void *arg) {
129
136
  int state = 0;
130
137
  rb_protect(body, (VALUE)arg, &state);
131
138
  if (state == 0)
@@ -142,7 +149,21 @@ quic_conn_t *quic_conn_get(VALUE self) {
142
149
  return c;
143
150
  }
144
151
 
145
- ngtcp2_conn *quic_conn_ptr(VALUE owner) { return quic_conn_get(owner)->conn; }
152
+ quic_conn_t *quic_conn_get_open(VALUE self) {
153
+ quic_conn_t *c = quic_conn_get(self);
154
+ if (c->conn == NULL) {
155
+ rb_raise(rb_eQUICErrorInvalidState,
156
+ c->rebuild_failed
157
+ ? "the connection could not be rebuilt after Version "
158
+ "Negotiation"
159
+ : "the connection was never opened");
160
+ }
161
+ return c;
162
+ }
163
+
164
+ ngtcp2_conn *quic_conn_ptr(VALUE owner) {
165
+ return quic_conn_get_open(owner)->conn;
166
+ }
146
167
 
147
168
  ngtcp2_tstamp quic_now(void) {
148
169
  struct timespec ts;
@@ -257,8 +278,99 @@ void quic_fill_transport_params(ngtcp2_transport_params *params, VALUE tp) {
257
278
  quic_get_uint64_field(tp, "active_connection_id_limit");
258
279
  }
259
280
 
260
- void quic_fill_settings(ngtcp2_settings *settings, VALUE st) {
281
+ /* The version sym (:v1 or :v2) names, or 0 for any other value. */
282
+ static uint32_t quic_version_from_sym(VALUE sym) {
283
+ if (sym == ID2SYM(rb_intern("v1")))
284
+ return NGTCP2_PROTO_VER_V1;
285
+ if (sym == ID2SYM(rb_intern("v2")))
286
+ return NGTCP2_PROTO_VER_V2;
287
+ return 0;
288
+ }
289
+
290
+ /* Read the list settings_v.<name> into out. Without duplicates, no more
291
+ than two entries get through: a third valid one repeats one of them. */
292
+ static size_t quic_read_version_list(VALUE settings_v, const char *name,
293
+ uint32_t out[2]) {
294
+ VALUE ary = rb_funcall(settings_v, rb_intern(name), 0);
295
+ long len = RB_TYPE_P(ary, T_ARRAY) ? RARRAY_LEN(ary) : 0;
296
+ bool valid = len > 0;
297
+ for (long i = 0; valid && i < len; i++) {
298
+ valid = quic_version_from_sym(RARRAY_AREF(ary, i)) != 0;
299
+ }
300
+ if (!valid) {
301
+ rb_raise(rb_eArgError,
302
+ "%s must be a non-empty Array of :v1 and :v2 (got %+" PRIsVALUE
303
+ ")",
304
+ name, ary);
305
+ }
306
+
307
+ size_t n = 0;
308
+ for (long i = 0; i < len; i++) {
309
+ VALUE sym = RARRAY_AREF(ary, i);
310
+ uint32_t version = quic_version_from_sym(sym);
311
+ for (size_t j = 0; j < n; j++) {
312
+ if (out[j] == version) {
313
+ rb_raise(rb_eArgError, "%s lists %+" PRIsVALUE " more than once", name,
314
+ sym);
315
+ }
316
+ }
317
+ out[n++] = version;
318
+ }
319
+ return n;
320
+ }
321
+
322
+ void quic_read_versions(VALUE settings_v, quic_versions_buf *vbuf) {
323
+ VALUE version = rb_funcall(settings_v, rb_intern("version"), 0);
324
+ vbuf->chosen = quic_version_from_sym(version);
325
+ if (vbuf->chosen == 0) {
326
+ rb_raise(rb_eArgError, "version must be :v1 or :v2 (got %+" PRIsVALUE ")",
327
+ version);
328
+ }
329
+ vbuf->preferredlen =
330
+ quic_read_version_list(settings_v, "preferred_versions", vbuf->preferred);
331
+ vbuf->availablelen =
332
+ quic_read_version_list(settings_v, "available_versions", vbuf->available);
333
+ }
334
+
335
+ bool quic_versions_accept(const quic_versions_buf *vbuf, uint32_t version) {
336
+ for (size_t i = 0; i < vbuf->preferredlen; i++) {
337
+ if (vbuf->preferred[i] == version)
338
+ return true;
339
+ }
340
+ for (size_t i = 0; i < vbuf->availablelen; i++) {
341
+ if (vbuf->available[i] == version)
342
+ return true;
343
+ }
344
+ return false;
345
+ }
346
+
347
+ uint64_t quic_read_qlog_max_bytes(VALUE settings_v) {
348
+ VALUE v = rb_funcall(settings_v, rb_intern("qlog_max_bytes"), 0);
349
+ if (NIL_P(v))
350
+ return 0;
351
+ /* Sorted out before any conversion: NUM2ULL would round 1.5 down, raise
352
+ TypeError or RangeError rather than ArgumentError, and take 2**63. */
353
+ if (RB_INTEGER_TYPE_P(v) && RTEST(rb_funcall(v, '>', 1, INT2FIX(0))) &&
354
+ RTEST(rb_funcall(v, rb_intern("<="), 1, LL2NUM(INT64_MAX)))) {
355
+ return (uint64_t)NUM2LL(v);
356
+ }
357
+ rb_raise(rb_eArgError,
358
+ "qlog_max_bytes must be a positive Integer or nil (got %+" PRIsVALUE
359
+ ")",
360
+ v);
361
+ }
362
+
363
+ void quic_fill_settings(ngtcp2_settings *settings, VALUE st,
364
+ quic_versions_buf *vbuf) {
365
+ quic_read_versions(st, vbuf);
366
+ /* Only checked here, so that a wrong value raises when a connection or
367
+ an Endpoint is made, with or without qlog_dir. */
368
+ quic_read_qlog_max_bytes(st);
261
369
  ngtcp2_settings_default(settings);
370
+ settings->preferred_versions = vbuf->preferred;
371
+ settings->preferred_versionslen = vbuf->preferredlen;
372
+ settings->available_versions = vbuf->available;
373
+ settings->available_versionslen = vbuf->availablelen;
262
374
  settings->initial_ts = quic_now();
263
375
  settings->cc_algo =
264
376
  quic_cc_algo_from_sym(rb_funcall(st, rb_intern("cc_algo"), 0));
@@ -272,41 +384,150 @@ void quic_fill_settings(ngtcp2_settings *settings, VALUE st) {
272
384
  settings->no_pmtud = RTEST(no_pmtud) ? 1 : 0;
273
385
  }
274
386
 
275
- /* ngtcp2_settings.qlog_write. Touches no Ruby object, so it needs no
387
+ /* Write len bytes of data to the end of c's qlog file, retrying short
388
+ writes and EINTR. Moves qlog_committed past the last '\n' written: ngtcp2
389
+ writes '\n' only at the end of a record, so that is where the last whole
390
+ record ends. On a failure, truncates the file back to qlog_committed and
391
+ returns false; the caller closes it. */
392
+ static bool quic_qlog_write_all(quic_conn_t *c, const uint8_t *data,
393
+ size_t len) {
394
+ off_t start = c->qlog_written;
395
+ size_t done = 0;
396
+ while (done < len) {
397
+ ssize_t n = write(c->qlog_fd, data + done, len - done);
398
+ if (n < 0 && errno == EINTR)
399
+ continue;
400
+ if (n <= 0) {
401
+ if (ftruncate(c->qlog_fd, c->qlog_committed) != 0) {
402
+ /* Nothing more to do: the caller closes the file all the same. */
403
+ }
404
+ return false;
405
+ }
406
+ for (size_t i = done + (size_t)n; i > done; i--) {
407
+ if (data[i - 1] == '\n') {
408
+ c->qlog_committed = start + (off_t)i;
409
+ break;
410
+ }
411
+ }
412
+ done += (size_t)n;
413
+ c->qlog_written = start + (off_t)done;
414
+ }
415
+ return true;
416
+ }
417
+
418
+ /* Write out the records in c's qlog buffer. Returns false when that failed
419
+ and closed the file. */
420
+ static bool quic_qlog_flush(quic_conn_t *c) {
421
+ if (c->qlog_fd < 0)
422
+ return false;
423
+ size_t len = c->qlog_buflen;
424
+ c->qlog_buflen = 0;
425
+ if (len > 0 && !quic_qlog_write_all(c, c->qlog_buf, len)) {
426
+ quic_conn_close_qlog(c);
427
+ return false;
428
+ }
429
+ return true;
430
+ }
431
+
432
+ /* ngtcp2_settings.qlog_write: data is one whole record, or nothing with
433
+ NGTCP2_QLOG_WRITE_FLAG_FIN. Touches no Ruby object, so it needs no
276
434
  rb_protect. A write error only costs qlog. */
277
435
  static void quic_qlog_write_cb(void *user_data, uint32_t flags,
278
436
  const void *data, size_t datalen) {
279
437
  quic_conn_t *c = (quic_conn_t *)user_data;
280
- if (c->qlog == NULL)
438
+ /* Closed already: ngtcp2 goes on logging after the connection ends. */
439
+ if (c->qlog_fd < 0)
281
440
  return;
282
- fwrite(data, 1, datalen, c->qlog);
441
+ if (c->qlog_max_bytes > 0) {
442
+ /* Before the record goes anywhere. Every record taken so far fits, so
443
+ writing out the buffer on closing stays within the limit too. In
444
+ uint64_t, so that nothing overflows near INT64_MAX. */
445
+ uint64_t used = (uint64_t)c->qlog_written + c->qlog_buflen;
446
+ if (used > c->qlog_max_bytes || c->qlog_max_bytes - used < datalen) {
447
+ /* This record and every one after it are dropped. Closing frees the
448
+ buffer, so nothing below may run. */
449
+ quic_conn_close_qlog(c);
450
+ return;
451
+ }
452
+ }
453
+ if (datalen > QUIC_QLOG_BUFLEN - c->qlog_buflen) {
454
+ /* A failure closed the file and freed the buffer. */
455
+ if (!quic_qlog_flush(c))
456
+ return;
457
+ }
458
+ if (datalen > QUIC_QLOG_BUFLEN) {
459
+ /* Larger than the buffer (no ngtcp2 record is): written as it is, after
460
+ the records before it. */
461
+ if (!quic_qlog_write_all(c, (const uint8_t *)data, datalen)) {
462
+ quic_conn_close_qlog(c);
463
+ return;
464
+ }
465
+ } else if (datalen > 0) {
466
+ memcpy(c->qlog_buf + c->qlog_buflen, data, datalen);
467
+ c->qlog_buflen += datalen;
468
+ }
283
469
  if (flags & NGTCP2_QLOG_WRITE_FLAG_FIN)
284
470
  quic_conn_close_qlog(c);
285
471
  }
286
472
 
287
473
  void quic_conn_close_qlog(quic_conn_t *c) {
288
- if (c->qlog == NULL)
474
+ if (c->qlog_fd < 0)
289
475
  return;
290
- fclose(c->qlog);
291
- c->qlog = NULL;
476
+ size_t len = c->qlog_buflen;
477
+ c->qlog_buflen = 0;
478
+ if (len > 0)
479
+ quic_qlog_write_all(c, c->qlog_buf, len);
480
+ close(c->qlog_fd);
481
+ /* Right away: a reconnect after Version Negotiation may open its new file
482
+ under the same number. */
483
+ c->qlog_fd = -1;
484
+ xfree(c->qlog_buf);
485
+ c->qlog_buf = NULL;
292
486
  }
293
487
 
294
488
  void quic_conn_open_qlog(quic_conn_t *c, VALUE settings_v,
295
489
  ngtcp2_settings *settings) {
490
+ /* A reconnect after Version Negotiation drops the last file's path. */
491
+ c->qlog_path = Qnil;
296
492
  VALUE dir = quic_path_value(rb_funcall(settings_v, rb_intern("qlog_dir"), 0),
297
493
  "qlog_dir");
298
494
  if (NIL_P(dir))
299
495
  return;
496
+ /* quic_fill_settings has checked it already. Read before the file is
497
+ opened all the same, so that nothing is left open if it raised. */
498
+ uint64_t max_bytes = quic_read_qlog_max_bytes(settings_v);
300
499
 
301
500
  char hex[NGTCP2_MAX_CIDLEN * 2 + 1];
302
501
  for (size_t i = 0; i < c->scid.datalen; i++) {
303
502
  snprintf(hex + i * 2, 3, "%02x", c->scid.data[i]);
304
503
  }
305
504
  hex[c->scid.datalen * 2] = '\0';
306
- VALUE path = rb_sprintf("%" PRIsVALUE "/%s.sqlog", dir, hex);
307
- c->qlog = fopen(StringValueCStr(path), "w");
308
- if (c->qlog != NULL)
309
- settings->qlog_write = quic_qlog_write_cb;
505
+ /* File.expand_path: against the current directory now, so that the path
506
+ keeps naming this file after a chdir. Symbolic links are left as they
507
+ are. */
508
+ VALUE path = rb_file_expand_path(
509
+ rb_sprintf("%" PRIsVALUE "/%s.sqlog", dir, hex), Qnil);
510
+ /* Allocated first, since xmalloc may raise and leave an open fd behind. */
511
+ uint8_t *buf = xmalloc(QUIC_QLOG_BUFLEN);
512
+ /* O_NOFOLLOW: qlog_dir may be shared, like /tmp, and a symbolic link
513
+ someone else left there must not be followed. 0666 and the umask give
514
+ the permissions fopen(path, "w") did. The String's bytes are not kept:
515
+ GC.compact may move them. */
516
+ int fd = open(StringValueCStr(path),
517
+ O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0666);
518
+ if (fd < 0) {
519
+ xfree(buf);
520
+ return;
521
+ }
522
+ c->qlog_path = rb_obj_freeze(path);
523
+ c->qlog_fd = fd;
524
+ c->qlog_buf = buf;
525
+ c->qlog_buflen = 0;
526
+ c->qlog_written = 0;
527
+ c->qlog_committed = 0;
528
+ /* Per file: after Version Negotiation the new file counts from 0. */
529
+ c->qlog_max_bytes = max_bytes;
530
+ settings->qlog_write = quic_qlog_write_cb;
310
531
  }
311
532
 
312
533
  /* Validate a path setting (ca_file, ca_path, ...) and return it as a String,
@@ -373,91 +594,87 @@ void quic_conn_copy_alpn(quic_conn_t *c, VALUE settings_v) {
373
594
  &c->alpn_count, &c->alpn_buf);
374
595
  }
375
596
 
376
- /* Shared helper: look up the QUIC::Stream registered for stream_id in the
377
- owner connection's @streams Hash. Returns Qnil if not found (which can
378
- happen if the stream was already removed by a previous stream_close
379
- callback). */
380
- static VALUE quic_conn_lookup_stream(quic_conn_t *c, int64_t stream_id) {
381
- VALUE streams = rb_ivar_get(c->owner, rb_intern("@streams"));
382
- return rb_hash_aref(streams, LL2NUM(stream_id));
597
+ void quic_conn_give_back_peer_stream(ngtcp2_conn *conn, int64_t stream_id) {
598
+ if (!ngtcp2_conn_is_local_stream2(conn, stream_id) &&
599
+ ngtcp2_is_bidi_stream(stream_id)) {
600
+ ngtcp2_conn_extend_max_streams_bidi(conn, 1);
601
+ }
383
602
  }
384
603
 
385
- /* ngtcp2 stream callbacks. The Ruby-touching part of each is a *_body
386
- function run under rb_protect by quic_conn_protect, so that an exception
387
- (a frozen @streams, an allocation failure, ...) never unwinds through
388
- ngtcp2. The callback then returns NGTCP2_ERR_CALLBACK_FAILURE and the
389
- exception is re-raised once ngtcp2 has returned. */
604
+ /* The ngtcp2 stream callbacks hand each stream to the stream handler (the
605
+ quic_handler_* functions below) or, without one, to its QUIC::Stream
606
+ (quic_stream_on_* in stream.c). */
390
607
 
391
- /* The arguments of a stream callback, handed to its body through
392
- rb_protect's single VALUE. Each body reads only the fields it needs. */
393
- struct quic_stream_cb_args {
394
- quic_conn_t *c;
395
- int64_t stream_id;
396
- uint32_t flags;
397
- const uint8_t *data;
398
- size_t datalen;
399
- uint64_t acked;
400
- uint64_t app_error_code;
401
- };
402
-
403
- static VALUE quic_stream_open_body(VALUE arg) {
404
- struct quic_stream_cb_args *a = (struct quic_stream_cb_args *)arg;
405
- VALUE streams = rb_ivar_get(a->c->owner, rb_intern("@streams"));
406
- if (!NIL_P(rb_hash_aref(streams, LL2NUM(a->stream_id)))) {
407
- return Qnil; /* already known (opened by this endpoint) */
608
+ static int quic_handler_recv_stream_data(quic_conn_t *c, ngtcp2_conn *conn,
609
+ uint32_t flags, int64_t stream_id,
610
+ const uint8_t *data, size_t datalen) {
611
+ size_t consumed = 0;
612
+ int fin = (flags & NGTCP2_STREAM_DATA_FLAG_FIN) != 0;
613
+ if (c->handler->recv_stream_data(c->handler_ud, stream_id, data, datalen, fin,
614
+ c->now, &consumed) < 0) {
615
+ return NGTCP2_ERR_CALLBACK_FAILURE;
408
616
  }
409
- VALUE stream = quic_stream_new(a->stream_id, a->c->owner);
410
- rb_hash_aset(streams, LL2NUM(a->stream_id), stream);
411
- return Qnil;
617
+ /* What the handler consumed outright (for HTTP/3, everything but the
618
+ request body) goes straight back to the peer as credit. */
619
+ if (consumed > 0) {
620
+ if (ngtcp2_conn_extend_max_stream_offset(conn, stream_id, consumed) != 0) {
621
+ return NGTCP2_ERR_CALLBACK_FAILURE;
622
+ }
623
+ ngtcp2_conn_extend_max_offset(conn, consumed);
624
+ }
625
+ return 0;
412
626
  }
413
627
 
414
- void quic_conn_give_back_peer_stream(ngtcp2_conn *conn, int64_t stream_id) {
415
- if (!ngtcp2_conn_is_local_stream2(conn, stream_id) &&
416
- ngtcp2_is_bidi_stream(stream_id)) {
417
- ngtcp2_conn_extend_max_streams_bidi(conn, 1);
418
- }
628
+ static int quic_handler_acked_stream_data(quic_conn_t *c, int64_t stream_id,
629
+ uint64_t datalen) {
630
+ return c->handler->acked_stream_data(c->handler_ud, stream_id, datalen) < 0
631
+ ? NGTCP2_ERR_CALLBACK_FAILURE
632
+ : 0;
633
+ }
634
+
635
+ static int quic_handler_stream_close(quic_conn_t *c, ngtcp2_conn *conn,
636
+ uint32_t flags, int64_t stream_id,
637
+ uint64_t app_error_code) {
638
+ /* The handler keeps no stream waiting for the application, so the peer
639
+ gets its stream back at once. */
640
+ quic_conn_give_back_peer_stream(conn, stream_id);
641
+ int has_code = (flags & NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET) != 0;
642
+ return c->handler->stream_close(c->handler_ud, stream_id, has_code,
643
+ app_error_code) < 0
644
+ ? NGTCP2_ERR_CALLBACK_FAILURE
645
+ : 0;
646
+ }
647
+
648
+ static int quic_handler_stream_reset(quic_conn_t *c, int64_t stream_id,
649
+ uint64_t final_size,
650
+ uint64_t app_error_code) {
651
+ return c->handler->stream_reset(c->handler_ud, stream_id, final_size,
652
+ app_error_code) < 0
653
+ ? NGTCP2_ERR_CALLBACK_FAILURE
654
+ : 0;
419
655
  }
420
656
 
657
+ /* A handler built against ABI 1.0 lacks recv_stop_sending, and learns of
658
+ STOP_SENDING only when #write_pkt finds the send side shut
659
+ (stream_shut_write) or the stream closes. */
660
+ static int quic_handler_recv_stop_sending(quic_conn_t *c, int64_t stream_id,
661
+ uint64_t app_error_code) {
662
+ if (!QUIC_EXT_HANDLER_HAS(c->handler, recv_stop_sending))
663
+ return 0;
664
+ return c->handler->recv_stop_sending(c->handler_ud, stream_id,
665
+ app_error_code) < 0
666
+ ? NGTCP2_ERR_CALLBACK_FAILURE
667
+ : 0;
668
+ }
669
+
670
+ /* Called only for a stream the peer opened. */
421
671
  static int quic_stream_open_cb(ngtcp2_conn *conn, int64_t stream_id,
422
672
  void *user_data) {
423
673
  (void)conn;
424
674
  quic_conn_t *c = (quic_conn_t *)user_data;
425
675
  if (c->handler)
426
676
  return 0; /* the handler keeps its own stream state */
427
- struct quic_stream_cb_args a = {.c = c, .stream_id = stream_id};
428
- return quic_conn_protect(c, quic_stream_open_body, &a);
429
- }
430
-
431
- static VALUE quic_recv_stream_data_body(VALUE arg) {
432
- struct quic_stream_cb_args *a = (struct quic_stream_cb_args *)arg;
433
- quic_conn_t *c = a->c;
434
- VALUE stream = quic_conn_lookup_stream(c, a->stream_id);
435
- if (NIL_P(stream))
436
- return Qnil;
437
-
438
- quic_stream_t *s;
439
- TypedData_Get_Struct(stream, quic_stream_t, &quic_stream_data_type, s);
440
-
441
- /* Surface peer-initiated streams to #accept_stream. The low stream-id bit
442
- marks the initiator (0 == client, 1 == server), so a client queues the
443
- odd ids and a server the even ones. Push once, on first data arrival,
444
- then mark so later data does not re-enqueue. */
445
- bool peer_initiated =
446
- c->is_server ? !(a->stream_id & 0x01) : (a->stream_id & 0x01);
447
- if (!s->accept_queued && peer_initiated) {
448
- VALUE accept_queue = rb_ivar_get(c->owner, rb_intern("@accept_queue"));
449
- rb_ary_push(accept_queue, stream);
450
- s->accept_queued = true;
451
- }
452
-
453
- if (a->datalen > 0) {
454
- VALUE recv_buffer = rb_ivar_get(stream, rb_intern("@recv_buffer"));
455
- rb_str_buf_cat(recv_buffer, (const char *)a->data, (long)a->datalen);
456
- }
457
- if (a->flags & NGTCP2_STREAM_DATA_FLAG_FIN) {
458
- s->fin_received = true;
459
- }
460
- return Qnil;
677
+ return quic_stream_on_open(c, stream_id);
461
678
  }
462
679
 
463
680
  static int quic_recv_stream_data_cb(ngtcp2_conn *conn, uint32_t flags,
@@ -465,64 +682,11 @@ static int quic_recv_stream_data_cb(ngtcp2_conn *conn, uint32_t flags,
465
682
  const uint8_t *data, size_t datalen,
466
683
  void *user_data, void *stream_user_data) {
467
684
  (void)offset;
468
- (void)stream_user_data;
469
685
  quic_conn_t *c = (quic_conn_t *)user_data;
470
- if (c->handler) {
471
- size_t consumed = 0;
472
- int fin = (flags & NGTCP2_STREAM_DATA_FLAG_FIN) != 0;
473
- if (c->handler->recv_stream_data(c->handler_ud, stream_id, data, datalen,
474
- fin, c->now, &consumed) < 0) {
475
- return NGTCP2_ERR_CALLBACK_FAILURE;
476
- }
477
- /* What the handler consumed outright (for HTTP/3, everything but the
478
- request body) goes straight back to the peer as credit. */
479
- if (consumed > 0) {
480
- if (ngtcp2_conn_extend_max_stream_offset(conn, stream_id, consumed) !=
481
- 0) {
482
- return NGTCP2_ERR_CALLBACK_FAILURE;
483
- }
484
- ngtcp2_conn_extend_max_offset(conn, consumed);
485
- }
486
- return 0;
487
- }
488
- struct quic_stream_cb_args a = {
489
- .c = c,
490
- .stream_id = stream_id,
491
- .flags = flags,
492
- .data = data,
493
- .datalen = datalen,
494
- };
495
- return quic_conn_protect(c, quic_recv_stream_data_body, &a);
496
- }
497
-
498
- static VALUE quic_acked_stream_data_offset_body(VALUE arg) {
499
- struct quic_stream_cb_args *a = (struct quic_stream_cb_args *)arg;
500
- VALUE stream = quic_conn_lookup_stream(a->c, a->stream_id);
501
- if (NIL_P(stream))
502
- return Qnil;
503
-
504
- quic_stream_t *s;
505
- TypedData_Get_Struct(stream, quic_stream_t, &quic_stream_data_type, s);
506
- s->acked_offset += a->acked;
507
-
508
- /* Shift any head Chunks of @pending_chunks whose end-offset is fully
509
- covered by acked_offset. Each Chunk's start-offset in the stream is
510
- pending_shifted (after previous shifts); its end-offset is
511
- pending_shifted + RSTRING_LEN(head). A stopped stream's
512
- @pending_chunks is empty, and acks for what it sent before shift
513
- nothing. */
514
- VALUE pending = rb_ivar_get(stream, rb_intern("@pending_chunks"));
515
- while (RARRAY_LEN(pending) > 0) {
516
- VALUE head = RARRAY_AREF(pending, 0);
517
- uint64_t head_end = s->pending_shifted + (uint64_t)RSTRING_LEN(head);
518
- if (head_end <= s->acked_offset) {
519
- rb_ary_shift(pending);
520
- s->pending_shifted = head_end;
521
- } else {
522
- break;
523
- }
524
- }
525
- return Qnil;
686
+ if (c->handler)
687
+ return quic_handler_recv_stream_data(c, conn, flags, stream_id, data,
688
+ datalen);
689
+ return quic_stream_on_recv_data(c, stream_user_data, flags, data, datalen);
526
690
  }
527
691
 
528
692
  static int quic_acked_stream_data_offset_cb(ngtcp2_conn *conn,
@@ -530,150 +694,45 @@ static int quic_acked_stream_data_offset_cb(ngtcp2_conn *conn,
530
694
  uint64_t datalen, void *user_data,
531
695
  void *stream_user_data) {
532
696
  (void)conn;
533
- (void)offset;
534
- (void)stream_user_data;
535
697
  quic_conn_t *c = (quic_conn_t *)user_data;
536
- if (c->handler) {
537
- return c->handler->acked_stream_data(c->handler_ud, stream_id, datalen) < 0
538
- ? NGTCP2_ERR_CALLBACK_FAILURE
539
- : 0;
540
- }
541
- struct quic_stream_cb_args a = {
542
- .c = c, .stream_id = stream_id, .acked = datalen};
543
- return quic_conn_protect(c, quic_acked_stream_data_offset_body, &a);
544
- }
545
-
546
- static VALUE quic_stream_close_body(VALUE arg) {
547
- struct quic_stream_cb_args *a = (struct quic_stream_cb_args *)arg;
548
- VALUE streams = rb_ivar_get(a->c->owner, rb_intern("@streams"));
549
- VALUE stream = rb_hash_aref(streams, LL2NUM(a->stream_id));
550
- if (NIL_P(stream)) {
551
- quic_conn_give_back_peer_stream(a->c->conn, a->stream_id);
552
- return Qnil;
553
- }
554
-
555
- quic_stream_t *s;
556
- TypedData_Get_Struct(stream, quic_stream_t, &quic_stream_data_type, s);
557
- s->closed = true;
558
- if (a->flags & NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET) {
559
- s->close_has_app_error_code = true;
560
- s->close_app_error_code = a->app_error_code;
561
- }
562
- /* A stream still waiting in @accept_queue holds on to what it received.
563
- Were the peer given its stream back now, it could open and close
564
- streams until the queue had used up our memory, so it gets the stream
565
- back only once the application has accepted this one
566
- (QUIC::Stream#_accepted). */
567
- if (s->accept_queued && !s->accepted) {
568
- s->peer_stream_held = true;
569
- } else {
570
- quic_conn_give_back_peer_stream(a->c->conn, a->stream_id);
571
- }
572
- rb_hash_delete(streams, LL2NUM(a->stream_id));
573
- return Qnil;
698
+ if (c->handler)
699
+ return quic_handler_acked_stream_data(c, stream_id, datalen);
700
+ quic_stream_on_acked(stream_user_data, offset, datalen);
701
+ return 0;
574
702
  }
575
703
 
576
704
  static int quic_stream_close_cb(ngtcp2_conn *conn, uint32_t flags,
577
705
  int64_t stream_id, uint64_t app_error_code,
578
706
  void *user_data, void *stream_user_data) {
579
- (void)stream_user_data;
580
707
  quic_conn_t *c = (quic_conn_t *)user_data;
581
- if (c->handler) {
582
- /* The handler keeps no stream waiting for the application, so the peer
583
- gets its stream back at once. */
584
- quic_conn_give_back_peer_stream(conn, stream_id);
585
- int has_code = (flags & NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET) != 0;
586
- return c->handler->stream_close(c->handler_ud, stream_id, has_code,
587
- app_error_code) < 0
588
- ? NGTCP2_ERR_CALLBACK_FAILURE
589
- : 0;
590
- }
591
- struct quic_stream_cb_args a = {
592
- .c = c,
593
- .stream_id = stream_id,
594
- .flags = flags,
595
- .app_error_code = app_error_code,
596
- };
597
- return quic_conn_protect(c, quic_stream_close_body, &a);
598
- }
599
-
600
- static VALUE quic_stream_reset_body(VALUE arg) {
601
- struct quic_stream_cb_args *a = (struct quic_stream_cb_args *)arg;
602
- VALUE stream = quic_conn_lookup_stream(a->c, a->stream_id);
603
- if (NIL_P(stream))
604
- return Qnil;
605
-
606
- quic_stream_t *s;
607
- TypedData_Get_Struct(stream, quic_stream_t, &quic_stream_data_type, s);
608
- s->reset = true;
609
- s->close_app_error_code = a->app_error_code;
610
- s->close_has_app_error_code = true;
611
- return Qnil;
708
+ if (c->handler)
709
+ return quic_handler_stream_close(c, conn, flags, stream_id, app_error_code);
710
+ return quic_stream_on_close(c, stream_user_data, stream_id, flags,
711
+ app_error_code);
612
712
  }
613
713
 
614
714
  static int quic_stream_reset_cb(ngtcp2_conn *conn, int64_t stream_id,
615
715
  uint64_t final_size, uint64_t app_error_code,
616
716
  void *user_data, void *stream_user_data) {
617
717
  (void)conn;
618
- (void)stream_user_data;
619
718
  quic_conn_t *c = (quic_conn_t *)user_data;
620
- if (c->handler) {
621
- return c->handler->stream_reset(c->handler_ud, stream_id, final_size,
622
- app_error_code) < 0
623
- ? NGTCP2_ERR_CALLBACK_FAILURE
624
- : 0;
625
- }
626
- struct quic_stream_cb_args a = {
627
- .c = c, .stream_id = stream_id, .app_error_code = app_error_code};
628
- return quic_conn_protect(c, quic_stream_reset_body, &a);
629
- }
630
-
631
- /* Nothing queued on stream can go out any more: drop it all, and have
632
- #write_pkt skip the stream from now on. ngtcp2 retransmits no STREAM
633
- frame of a stream it has reset, so it no longer reads the bytes it was
634
- given either. */
635
- static void quic_stream_stop(VALUE stream) {
636
- quic_stream_t *s;
637
- TypedData_Get_Struct(stream, quic_stream_t, &quic_stream_data_type, s);
638
- s->stopped = true;
639
- rb_ary_clear(rb_ivar_get(stream, rb_intern("@pending_chunks")));
640
- }
641
-
642
- static VALUE quic_recv_stop_sending_body(VALUE arg) {
643
- struct quic_stream_cb_args *a = (struct quic_stream_cb_args *)arg;
644
- VALUE stream = quic_conn_lookup_stream(a->c, a->stream_id);
645
- if (NIL_P(stream))
646
- return Qnil;
647
-
648
- quic_stream_t *s;
649
- TypedData_Get_Struct(stream, quic_stream_t, &quic_stream_data_type, s);
650
- s->stop_app_error_code = a->app_error_code;
651
- quic_stream_stop(stream);
652
- return Qnil;
719
+ if (c->handler)
720
+ return quic_handler_stream_reset(c, stream_id, final_size, app_error_code);
721
+ quic_stream_on_reset(stream_user_data, app_error_code);
722
+ return 0;
653
723
  }
654
724
 
655
725
  /* The peer sent STOP_SENDING. ngtcp2 shuts the send side and sends
656
- RESET_STREAM itself once this returns. A stream handler hears of it here
657
- (recv_stop_sending). One built against ABI 1.0 lacks that member, and
658
- learns of it only when #write_pkt finds the send side shut
659
- (stream_shut_write) or the stream closes. */
726
+ RESET_STREAM itself once this returns. */
660
727
  static int quic_recv_stop_sending_cb(ngtcp2_conn *conn, int64_t stream_id,
661
728
  uint64_t app_error_code, void *user_data,
662
729
  void *stream_user_data) {
663
730
  (void)conn;
664
- (void)stream_user_data;
665
731
  quic_conn_t *c = (quic_conn_t *)user_data;
666
- if (c->handler) {
667
- if (!QUIC_EXT_HANDLER_HAS(c->handler, recv_stop_sending))
668
- return 0;
669
- return c->handler->recv_stop_sending(c->handler_ud, stream_id,
670
- app_error_code) < 0
671
- ? NGTCP2_ERR_CALLBACK_FAILURE
672
- : 0;
673
- }
674
- struct quic_stream_cb_args a = {
675
- .c = c, .stream_id = stream_id, .app_error_code = app_error_code};
676
- return quic_conn_protect(c, quic_recv_stop_sending_body, &a);
732
+ if (c->handler)
733
+ return quic_handler_recv_stop_sending(c, stream_id, app_error_code);
734
+ quic_stream_on_recv_stop_sending(c, stream_user_data, app_error_code);
735
+ return 0;
677
736
  }
678
737
 
679
738
  /* The callbacks below matter only to a stream handler. Without one, the
@@ -761,142 +820,6 @@ void quic_conn_fill_common_callbacks(ngtcp2_callbacks *callbacks) {
761
820
  callbacks->handshake_completed = quic_handshake_completed_cb;
762
821
  }
763
822
 
764
- /* Find the first stream in @streams, stopped ones aside, that has either
765
- pending bytes or a pending FIN to flush. Phase 4 minimum: linear scan,
766
- take the first match (no round-robin). Sets *out_datav to the byte slice
767
- to send, *out_datavcnt to 0 or 1, *out_flags to
768
- NGTCP2_WRITE_STREAM_FLAG_FIN when applicable. Returns the stream's Ruby
769
- VALUE (or Qnil if no candidate). */
770
- static VALUE quic_conn_pick_send_stream(VALUE self, ngtcp2_vec *out_datav,
771
- size_t *out_datavcnt,
772
- uint32_t *out_flags,
773
- int64_t *out_stream_id) {
774
- VALUE streams = rb_ivar_get(self, rb_intern("@streams"));
775
- VALUE stream_values = rb_funcall(streams, rb_intern("values"), 0);
776
-
777
- for (long i = 0; i < RARRAY_LEN(stream_values); i++) {
778
- VALUE st = RARRAY_AREF(stream_values, i);
779
- quic_stream_t *s;
780
- TypedData_Get_Struct(st, quic_stream_t, &quic_stream_data_type, s);
781
- if (s->fin_flushed || s->stopped)
782
- continue;
783
-
784
- VALUE pending = rb_ivar_get(st, rb_intern("@pending_chunks"));
785
- uint64_t position = s->sent_offset - s->pending_shifted;
786
- long chunks_count = RARRAY_LEN(pending);
787
-
788
- /* Walk pending Chunks to find the one containing the next unsent byte. */
789
- long chunk_idx = -1;
790
- long offset_in_chunk = 0;
791
- for (long j = 0; j < chunks_count; j++) {
792
- VALUE chunk = RARRAY_AREF(pending, j);
793
- long clen = RSTRING_LEN(chunk);
794
- if (position < (uint64_t)clen) {
795
- chunk_idx = j;
796
- offset_in_chunk = (long)position;
797
- break;
798
- }
799
- position -= (uint64_t)clen;
800
- }
801
-
802
- if (chunk_idx >= 0) {
803
- VALUE chunk = RARRAY_AREF(pending, chunk_idx);
804
- out_datav->base = (uint8_t *)RSTRING_PTR(chunk) + offset_in_chunk;
805
- out_datav->len = (size_t)(RSTRING_LEN(chunk) - offset_in_chunk);
806
- *out_datavcnt = 1;
807
- *out_stream_id = s->stream_id;
808
- /* Attach FIN if this is the LAST chunk and we're going to send all
809
- remaining bytes of it (ngtcp2 may encode less, in which case FIN
810
- won't actually be flushed and we'll retry next call). */
811
- *out_flags = (s->fin_sent && chunk_idx == chunks_count - 1)
812
- ? NGTCP2_WRITE_STREAM_FLAG_FIN
813
- : 0;
814
- return st;
815
- }
816
-
817
- if (s->fin_sent && !s->fin_flushed) {
818
- /* No data to send but a pending FIN-only frame. */
819
- out_datav->base = NULL;
820
- out_datav->len = 0;
821
- *out_datavcnt = 0;
822
- *out_stream_id = s->stream_id;
823
- *out_flags = NGTCP2_WRITE_STREAM_FLAG_FIN;
824
- return st;
825
- }
826
- }
827
-
828
- return Qnil;
829
- }
830
-
831
- /* #write_pkt for the QUIC::Stream mode. If any stream has pending bytes or
832
- a pending FIN, route the packet through ngtcp2_conn_writev_stream so the
833
- stream data gets framed alongside connection-level frames. Falls back to
834
- conn-only when no stream is queued. Returns what ngtcp2 returned. */
835
- static ngtcp2_ssize quic_conn_write_pkt_streams(VALUE self, quic_conn_t *c,
836
- ngtcp2_path *path,
837
- ngtcp2_pkt_info *pi,
838
- uint8_t *dest, size_t destlen) {
839
- ngtcp2_vec datav;
840
- size_t datavcnt = 0;
841
- uint32_t writev_flags = 0;
842
- int64_t send_stream_id = -1;
843
- VALUE selected_stream = quic_conn_pick_send_stream(
844
- self, &datav, &datavcnt, &writev_flags, &send_stream_id);
845
-
846
- ngtcp2_ssize pdatalen = -1;
847
- ngtcp2_ssize n = ngtcp2_conn_writev_stream(
848
- c->conn, path, pi, dest, destlen, &pdatalen, writev_flags, send_stream_id,
849
- &datav, datavcnt, c->now);
850
-
851
- if ((n == NGTCP2_ERR_STREAM_DATA_BLOCKED || n == NGTCP2_ERR_STREAM_SHUT_WR) &&
852
- NIL_P(c->pending_exc)) {
853
- /* DATA_BLOCKED: the stream's queued data is beyond what the peer's flow
854
- control lets through right now. Keep it queued; it follows once the
855
- peer extends its window (MAX_STREAM_DATA / MAX_DATA).
856
- SHUT_WR: ngtcp2 shut the stream's send side without recv_stop_sending
857
- marking the stream, as #reset does. What is queued can never go out,
858
- so drop it.
859
- Either way, build the packet without the stream's data, so that ACKs
860
- and other frames still go out. */
861
- if (n == NGTCP2_ERR_STREAM_SHUT_WR)
862
- quic_stream_stop(selected_stream);
863
- selected_stream = Qnil;
864
- datavcnt = 0;
865
- writev_flags = 0;
866
- pdatalen = -1;
867
- n = ngtcp2_conn_writev_stream(c->conn, path, pi, dest, destlen, &pdatalen,
868
- 0, -1, NULL, 0, c->now);
869
- }
870
-
871
- if (n < 0 || !NIL_P(c->pending_exc))
872
- return n;
873
-
874
- /* Update the selected stream's accounting only when we actually sent
875
- bytes. pdatalen >= 0 means ngtcp2 framed that many data bytes into the
876
- packet; if 0, no data was framed (but the packet may still contain ACK
877
- or other frames). */
878
- if (!NIL_P(selected_stream) && pdatalen > 0) {
879
- quic_stream_t *s;
880
- TypedData_Get_Struct(selected_stream, quic_stream_t, &quic_stream_data_type,
881
- s);
882
- s->sent_offset += (uint64_t)pdatalen;
883
- /* FIN is only actually written when all requested data fits in the
884
- frame (see ngtcp2 docs on NGTCP2_WRITE_STREAM_FLAG_FIN). */
885
- if ((writev_flags & NGTCP2_WRITE_STREAM_FLAG_FIN) &&
886
- (size_t)pdatalen == datav.len) {
887
- s->fin_flushed = true;
888
- }
889
- } else if (!NIL_P(selected_stream) && datavcnt == 0 && n > 0 &&
890
- (writev_flags & NGTCP2_WRITE_STREAM_FLAG_FIN)) {
891
- /* FIN-only packet (no data) was successfully written. */
892
- quic_stream_t *s;
893
- TypedData_Get_Struct(selected_stream, quic_stream_t, &quic_stream_data_type,
894
- s);
895
- s->fin_flushed = true;
896
- }
897
- return n;
898
- }
899
-
900
823
  /* The number of vectors #write_pkt asks a stream handler for per packet. */
901
824
  #define QUIC_HANDLER_VECCNT 16
902
825
 
@@ -961,15 +884,15 @@ ngtcp2_ssize quic_conn_write_pkt_raw(VALUE self, quic_conn_t *c,
961
884
  c->now = quic_now();
962
885
  return c->handler ? quic_conn_write_pkt_handler(c, path, &pi, dest,
963
886
  QUIC_WRITE_PKT_BUFLEN)
964
- : quic_conn_write_pkt_streams(self, c, path, &pi, dest,
965
- QUIC_WRITE_PKT_BUFLEN);
887
+ : quic_streams_write_pkt(self, c, path, &pi, dest,
888
+ QUIC_WRITE_PKT_BUFLEN);
966
889
  }
967
890
 
968
891
  static VALUE quic_conn_write_pkt(int argc, VALUE *argv, VALUE self) {
969
892
  VALUE buffer = Qnil;
970
893
  rb_scan_args(argc, argv, "01", &buffer);
971
894
 
972
- quic_conn_t *c = quic_conn_get(self);
895
+ quic_conn_t *c = quic_conn_get_open(self);
973
896
 
974
897
  if (NIL_P(buffer)) {
975
898
  /* rb_str_buf_new returns an ASCII-8BIT (binary) String per CRuby spec,
@@ -1018,7 +941,7 @@ static VALUE quic_conn_write_pkt(int argc, VALUE *argv, VALUE self) {
1018
941
  peer. */
1019
942
  VALUE
1020
943
  quic_conn_error_new(quic_conn_t *c, int rv) {
1021
- if (rv != NGTCP2_ERR_CRYPTO)
944
+ if (rv != NGTCP2_ERR_CRYPTO || c->conn == NULL)
1022
945
  return quic_ngtcp2_error_new(rv);
1023
946
 
1024
947
  /* 0 means "not set" to ngtcp2; close_notify (0) is never sent for a
@@ -1063,6 +986,12 @@ static VALUE quic_read_pkt_body(VALUE arg) {
1063
986
  int rv = quic_conn_read_pkt_raw(a->c, &a->path,
1064
987
  (const uint8_t *)RSTRING_PTR(a->packet),
1065
988
  (size_t)RSTRING_LEN(a->packet));
989
+ /* Ahead of everything below, which reads c->conn: a failed reconnect
990
+ leaves none. Only a client gets this error. */
991
+ if (rv == NGTCP2_ERR_RECV_VERSION_NEGOTIATION && !a->c->is_server) {
992
+ quic_client_handle_version_negotiation(a->c);
993
+ return Qnil;
994
+ }
1066
995
  /* The peer closed or reset the connection; ngtcp2 logs nothing more. */
1067
996
  if (ngtcp2_conn_in_draining_period2(a->c->conn))
1068
997
  quic_conn_close_qlog(a->c);
@@ -1101,7 +1030,7 @@ static VALUE quic_conn_read_pkt(int argc, VALUE *argv, VALUE self) {
1101
1030
  quic_require_sockaddr(local_sockaddr, "local_sockaddr");
1102
1031
  quic_require_sockaddr(remote_sockaddr, "remote_sockaddr");
1103
1032
 
1104
- quic_conn_t *c = quic_conn_get(self);
1033
+ quic_conn_t *c = quic_conn_get_open(self);
1105
1034
 
1106
1035
  struct quic_read_pkt_args args;
1107
1036
  args.c = c;
@@ -1118,22 +1047,85 @@ static VALUE quic_conn_read_pkt(int argc, VALUE *argv, VALUE self) {
1118
1047
  }
1119
1048
 
1120
1049
  static VALUE quic_conn_handshake_completed_p(VALUE self) {
1121
- quic_conn_t *c = quic_conn_get(self);
1050
+ quic_conn_t *c = quic_conn_get_open(self);
1122
1051
  return ngtcp2_conn_get_handshake_completed2(c->conn) ? Qtrue : Qfalse;
1123
1052
  }
1124
1053
 
1054
+ /* :v1 or :v2 once the version is settled, nil before: a server settles it
1055
+ on the client's transport parameters, a client on the server's first
1056
+ Initial. */
1057
+ static VALUE quic_conn_negotiated_version(VALUE self) {
1058
+ quic_conn_t *c = quic_conn_get_open(self);
1059
+ uint32_t version = ngtcp2_conn_get_negotiated_version2(c->conn);
1060
+ switch (version) {
1061
+ case 0:
1062
+ return Qnil;
1063
+ case NGTCP2_PROTO_VER_V1:
1064
+ return ID2SYM(rb_intern("v1"));
1065
+ case NGTCP2_PROTO_VER_V2:
1066
+ return ID2SYM(rb_intern("v2"));
1067
+ default:
1068
+ rb_raise(rb_eRuntimeError, "unexpected QUIC version 0x%08x",
1069
+ (unsigned int)version);
1070
+ }
1071
+ }
1072
+
1073
+ /* The peer of the current path, as a sockaddr String for Pump#remote_address
1074
+ to make an Addrinfo of. A copy: ngtcp2's path storage changes on the next
1075
+ read_pkt and goes away with the connection. On a server, ngtcp2 switches
1076
+ the current path to a new peer address before validating it, and back if
1077
+ the validation fails. */
1078
+ static VALUE quic_conn_remote_sockaddr(VALUE self) {
1079
+ quic_conn_t *c = quic_conn_get_open(self);
1080
+ const ngtcp2_path *path = ngtcp2_conn_get_path2(c->conn);
1081
+ return rb_str_new((const char *)path->remote.addr,
1082
+ (long)path->remote.addrlen);
1083
+ }
1084
+
1085
+ /* The ALPN protocol the handshake settled on, frozen ASCII-8BIT, or nil
1086
+ before it is settled: a server settles it on the first ClientHello, a
1087
+ client on the server's EncryptedExtensions. A client stays at nil when
1088
+ the server sent no ALPN. picotls keeps it NUL-terminated without a length,
1089
+ and sends it by strlen, so strlen is its length here too. */
1090
+ static VALUE quic_conn_alpn_protocol(VALUE self) {
1091
+ quic_conn_t *c = quic_conn_get_open(self);
1092
+ /* The constructors make the ptls_t after the ngtcp2_conn, so one that
1093
+ failed in between leaves no TLS session to ask. */
1094
+ if (c->cptls.ptls == NULL)
1095
+ return Qnil;
1096
+ const char *proto = ptls_get_negotiated_protocol(c->cptls.ptls);
1097
+ if (proto == NULL)
1098
+ return Qnil;
1099
+ return rb_obj_freeze(rb_str_new(proto, (long)strlen(proto)));
1100
+ }
1101
+
1102
+ /* The cipher suite's IANA name (e.g. "TLS_AES_128_GCM_SHA256"), an interned
1103
+ US-ASCII String, or nil before it is settled: a server settles it on the
1104
+ first ClientHello, a client on the first ServerHello (or
1105
+ HelloRetryRequest). */
1106
+ static VALUE quic_conn_cipher_suite(VALUE self) {
1107
+ quic_conn_t *c = quic_conn_get_open(self);
1108
+ if (c->cptls.ptls == NULL) /* as in quic_conn_alpn_protocol */
1109
+ return Qnil;
1110
+ ptls_cipher_suite_t *cs = ptls_get_cipher(c->cptls.ptls);
1111
+ if (cs == NULL)
1112
+ return Qnil;
1113
+ return rb_enc_interned_str(cs->name, (long)strlen(cs->name),
1114
+ rb_usascii_encoding());
1115
+ }
1116
+
1125
1117
  static VALUE quic_conn_in_closing_period_p(VALUE self) {
1126
- quic_conn_t *c = quic_conn_get(self);
1118
+ quic_conn_t *c = quic_conn_get_open(self);
1127
1119
  return ngtcp2_conn_in_closing_period2(c->conn) ? Qtrue : Qfalse;
1128
1120
  }
1129
1121
 
1130
1122
  static VALUE quic_conn_in_draining_period_p(VALUE self) {
1131
- quic_conn_t *c = quic_conn_get(self);
1123
+ quic_conn_t *c = quic_conn_get_open(self);
1132
1124
  return ngtcp2_conn_in_draining_period2(c->conn) ? Qtrue : Qfalse;
1133
1125
  }
1134
1126
 
1135
1127
  static VALUE quic_conn_expiry(VALUE self) {
1136
- quic_conn_t *c = quic_conn_get(self);
1128
+ quic_conn_t *c = quic_conn_get_open(self);
1137
1129
  ngtcp2_tstamp t = ngtcp2_conn_get_expiry2(c->conn);
1138
1130
  if (t == UINT64_MAX)
1139
1131
  return Qnil;
@@ -1144,7 +1136,7 @@ static VALUE quic_conn_expiry(VALUE self) {
1144
1136
  read_pkt or handle_expiry to advance ngtcp2 state, then write_pkt to flush.
1145
1137
  */
1146
1138
  static VALUE quic_conn_handle_expiry(VALUE self) {
1147
- quic_conn_t *c = quic_conn_get(self);
1139
+ quic_conn_t *c = quic_conn_get_open(self);
1148
1140
  c->now = quic_now();
1149
1141
  int rv = ngtcp2_conn_handle_expiry(c->conn, c->now);
1150
1142
  /* Timed out idle: the connection ends without a CONNECTION_CLOSE. */
@@ -1165,64 +1157,47 @@ static void quic_conn_require_stream_mode(quic_conn_t *c) {
1165
1157
  }
1166
1158
 
1167
1159
  static VALUE quic_conn_open_bidi_stream(VALUE self) {
1168
- quic_conn_t *c = quic_conn_get(self);
1160
+ quic_conn_t *c = quic_conn_get_open(self);
1169
1161
  quic_conn_require_stream_mode(c);
1170
1162
 
1171
1163
  int64_t stream_id;
1172
1164
  int rv = ngtcp2_conn_open_bidi_stream(c->conn, &stream_id, NULL);
1173
1165
  if (rv != 0)
1174
1166
  quic_raise_ngtcp2_error(rv);
1175
-
1176
- VALUE stream = quic_stream_new(stream_id, self);
1177
- VALUE streams = rb_ivar_get(self, rb_intern("@streams"));
1178
- rb_hash_aset(streams, LL2NUM(stream_id), stream);
1179
- return stream;
1167
+ return quic_stream_open_local(self, c, stream_id);
1180
1168
  }
1181
1169
 
1182
1170
  static VALUE quic_conn_open_uni_stream(VALUE self) {
1183
- quic_conn_t *c = quic_conn_get(self);
1171
+ quic_conn_t *c = quic_conn_get_open(self);
1184
1172
  quic_conn_require_stream_mode(c);
1185
1173
 
1186
1174
  int64_t stream_id;
1187
1175
  int rv = ngtcp2_conn_open_uni_stream(c->conn, &stream_id, NULL);
1188
1176
  if (rv != 0)
1189
1177
  quic_raise_ngtcp2_error(rv);
1190
-
1191
- VALUE stream = quic_stream_new(stream_id, self);
1192
- VALUE streams = rb_ivar_get(self, rb_intern("@streams"));
1193
- rb_hash_aset(streams, LL2NUM(stream_id), stream);
1194
- return stream;
1195
- }
1196
-
1197
- /* Send an application CONNECTION_CLOSE (frame type 0x1d) to the peer and
1198
- transition the underlying ngtcp2_conn to the closing period. One UDP
1199
- datagram is written to the bound socket, once: nothing sends it again
1200
- for packets the peer keeps sending (an Endpoint does, for its own
1201
- connections), and #write_pkt raises QUIC::Error::Closed from here on.
1202
- Calling #close on a connection that is already in the closing or
1203
- draining period is a no-op (= returns nil without doing any I/O). */
1204
- static VALUE quic_conn_close_m(int argc, VALUE *argv, VALUE self) {
1205
- VALUE opts = Qnil;
1206
- rb_scan_args(argc, argv, "0:", &opts);
1207
-
1208
- uint64_t error_code = 0;
1178
+ return quic_stream_open_local(self, c, stream_id);
1179
+ }
1180
+
1181
+ /* #_close(error_code, reason), behind Pump#close: build an application
1182
+ CONNECTION_CLOSE (frame type 0x1d) carrying error_code (nil: 0) and
1183
+ reason (nil: none), and transition the underlying ngtcp2_conn to the
1184
+ closing period. Returns the packet, for Pump#close to send through the
1185
+ bound socket once: nothing sends it again for packets the peer keeps
1186
+ sending (an Endpoint does, for its own connections), and #write_pkt
1187
+ raises QUIC::Error::Closed from here on. Returns nil when there is
1188
+ nothing to send: the connection is already in the closing or draining
1189
+ period, it is an Endpoint's, or ngtcp2 could not build the packet. */
1190
+ static VALUE quic_conn_close_m(VALUE self, VALUE error_code_v, VALUE reason_v) {
1191
+ uint64_t error_code = NIL_P(error_code_v) ? 0 : NUM2ULL(error_code_v);
1209
1192
  const uint8_t *reason_ptr = (const uint8_t *)"";
1210
1193
  size_t reason_len = 0;
1211
-
1212
- if (!NIL_P(opts)) {
1213
- VALUE error_code_v = rb_hash_aref(opts, ID2SYM(rb_intern("error_code")));
1214
- VALUE reason_v = rb_hash_aref(opts, ID2SYM(rb_intern("reason")));
1215
- if (!NIL_P(error_code_v)) {
1216
- error_code = NUM2ULL(error_code_v);
1217
- }
1218
- if (!NIL_P(reason_v)) {
1219
- Check_Type(reason_v, T_STRING);
1220
- reason_ptr = (const uint8_t *)RSTRING_PTR(reason_v);
1221
- reason_len = (size_t)RSTRING_LEN(reason_v);
1222
- }
1194
+ if (!NIL_P(reason_v)) {
1195
+ Check_Type(reason_v, T_STRING);
1196
+ reason_ptr = (const uint8_t *)RSTRING_PTR(reason_v);
1197
+ reason_len = (size_t)RSTRING_LEN(reason_v);
1223
1198
  }
1224
1199
 
1225
- quic_conn_t *c = quic_conn_get(self);
1200
+ quic_conn_t *c = quic_conn_get_open(self);
1226
1201
 
1227
1202
  /* Idempotent: a subsequent #close after the conn already entered the
1228
1203
  closing/draining period does not emit another CONNECTION_CLOSE. */
@@ -1244,8 +1219,9 @@ static VALUE quic_conn_close_m(int argc, VALUE *argv, VALUE self) {
1244
1219
  return Qnil;
1245
1220
  }
1246
1221
 
1247
- VALUE sock = rb_ivar_get(self, rb_intern("@sock"));
1248
- if (NIL_P(sock)) {
1222
+ /* Checked here, not by Pump#close, so that it comes after the cases
1223
+ above, which need no socket. */
1224
+ if (NIL_P(rb_ivar_get(self, rb_intern("@sock")))) {
1249
1225
  rb_raise(rb_eQUICErrorNotBound,
1250
1226
  "%" PRIsVALUE "#bind(sock) has not been called",
1251
1227
  rb_obj_class(self));
@@ -1266,8 +1242,9 @@ static VALUE quic_conn_close_m(int argc, VALUE *argv, VALUE self) {
1266
1242
  ngtcp2_ssize n = ngtcp2_conn_write_connection_close(
1267
1243
  c->conn, &path_storage.path, &pi, dest, (size_t)QUIC_WRITE_PKT_BUFLEN,
1268
1244
  &ccerr, quic_now());
1269
- /* The connection ends here whatever ngtcp2 returned, and the
1270
- CONNECTION_CLOSE, if one was built, is in the qlog already. */
1245
+ /* The connection ends here whatever ngtcp2 returned. ngtcp2 has logged
1246
+ the CONNECTION_CLOSE, if one was built, and closing the qlog writes it
1247
+ out. */
1271
1248
  quic_conn_close_qlog(c);
1272
1249
 
1273
1250
  /* Pre-handshake or otherwise not in a state where CONNECTION_CLOSE can be
@@ -1288,8 +1265,7 @@ static VALUE quic_conn_close_m(int argc, VALUE *argv, VALUE self) {
1288
1265
  }
1289
1266
 
1290
1267
  rb_str_set_len(buffer, n);
1291
- rb_funcall(sock, rb_intern("send"), 2, buffer, INT2NUM(0));
1292
- return Qnil;
1268
+ return buffer;
1293
1269
  }
1294
1270
 
1295
1271
  /* Why an Endpoint closed this connection; see quic_conn_t.error. Always nil
@@ -1298,6 +1274,20 @@ static VALUE quic_conn_error_m(VALUE self) {
1298
1274
  return quic_conn_get(self)->error;
1299
1275
  }
1300
1276
 
1277
+ /* See quic_conn_t.qlog_path. */
1278
+ static VALUE quic_conn_qlog_path(VALUE self) {
1279
+ return quic_conn_get(self)->qlog_path;
1280
+ }
1281
+
1282
+ /* Write out the qlog records buffered so far, without fsync. Keeps the GVL:
1283
+ it is at most QUIC_QLOG_BUFLEN bytes, as when ngtcp2's qlog_write fills
1284
+ the buffer, and the GVL is what keeps two threads off the buffer. A
1285
+ failure stops the qlog as it does anywhere else, and raises nothing. */
1286
+ static VALUE quic_conn_flush_qlog_m(VALUE self) {
1287
+ quic_qlog_flush(quic_conn_get(self));
1288
+ return Qnil;
1289
+ }
1290
+
1301
1291
  void quic_conn_define_shared_methods(VALUE klass) {
1302
1292
  rb_define_method(klass, "write_pkt", quic_conn_write_pkt, -1);
1303
1293
  rb_define_method(klass, "read_pkt", quic_conn_read_pkt, -1);
@@ -1305,12 +1295,24 @@ void quic_conn_define_shared_methods(VALUE klass) {
1305
1295
  rb_define_method(klass, "handle_expiry", quic_conn_handle_expiry, 0);
1306
1296
  rb_define_method(klass, "handshake_completed?",
1307
1297
  quic_conn_handshake_completed_p, 0);
1298
+ rb_define_method(klass, "negotiated_version", quic_conn_negotiated_version,
1299
+ 0);
1300
+ rb_define_method(klass, "alpn_protocol", quic_conn_alpn_protocol, 0);
1301
+ rb_define_method(klass, "cipher_suite", quic_conn_cipher_suite, 0);
1308
1302
  rb_define_method(klass, "in_closing_period?", quic_conn_in_closing_period_p,
1309
1303
  0);
1310
1304
  rb_define_method(klass, "in_draining_period?", quic_conn_in_draining_period_p,
1311
1305
  0);
1312
1306
  rb_define_method(klass, "open_bidi_stream", quic_conn_open_bidi_stream, 0);
1313
1307
  rb_define_method(klass, "open_uni_stream", quic_conn_open_uni_stream, 0);
1314
- rb_define_method(klass, "close", quic_conn_close_m, -1);
1308
+ /* #close itself is Pump's (lib/quic/connection.rb), which sends what
1309
+ #_close returns; defining it here would hide Pump's. */
1310
+ rb_define_private_method(klass, "_close", quic_conn_close_m, 2);
1311
+ /* Likewise #remote_address is Pump's, which makes an Addrinfo of what
1312
+ #_remote_sockaddr returns. */
1313
+ rb_define_private_method(klass, "_remote_sockaddr", quic_conn_remote_sockaddr,
1314
+ 0);
1315
1315
  rb_define_method(klass, "error", quic_conn_error_m, 0);
1316
+ rb_define_method(klass, "qlog_path", quic_conn_qlog_path, 0);
1317
+ rb_define_method(klass, "flush_qlog", quic_conn_flush_qlog_m, 0);
1316
1318
  }