Debian Codegraph @

contrib/libngtcp2/ngtcp2/lib/ngtcp2_conn.c

raw symbols SCIP
1 /*
2 * ngtcp2
3 *
4 * Copyright (c) 2017 ngtcp2 contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25 #include "ngtcp2_conn.h"
26
27 #include <string.h>
28 #include <assert.h>
29
30 #include "ngtcp2_macro.h"
31 #include "ngtcp2_log.h"
32 #include "ngtcp2_cid.h"
33 #include "ngtcp2_conv.h"
34 #include "ngtcp2_vec.h"
35 #include "ngtcp2_addr.h"
36 #include "ngtcp2_path.h"
37 #include "ngtcp2_rcvry.h"
38 #include "ngtcp2_unreachable.h"
39 #include "ngtcp2_net.h"
40 #include "ngtcp2_transport_params.h"
41 #include "ngtcp2_settings.h"
42 #include "ngtcp2_callbacks.h"
43 #include "ngtcp2_tstamp.h"
44 #include "ngtcp2_frame_chain.h"
45 #include "ngtcp2_conn_info.h"
46
47 /* NGTCP2_FLOW_WINDOW_RTT_FACTOR is the factor of RTT when flow
48 control window auto-tuning is triggered. */
49 #define NGTCP2_FLOW_WINDOW_RTT_FACTOR 2
50 /* NGTCP2_FLOW_WINDOW_SCALING_FACTOR is the growth factor of flow
51 control window. */
52 #define NGTCP2_FLOW_WINDOW_SCALING_FACTOR 2
53 /* NGTCP2_MIN_COALESCED_PAYLOADLEN is the minimum length of QUIC
54 packet payload that should be coalesced to a long packet. */
55 #define NGTCP2_MIN_COALESCED_PAYLOADLEN 128
56 /* NGTCP2_MAX_ACK_PER_PKT is the maximum number of ACK frame per an
57 incoming QUIC packet to process. ACK frames that exceed this limit
58 are not processed. */
59 #define NGTCP2_MAX_ACK_PER_PKT 1
60
61 ngtcp2_objalloc_def(strm, ngtcp2_strm, oplent)
62
63 /*
64 * conn_local_stream returns nonzero if |stream_id| indicates that it
65 * is the stream initiated by local endpoint.
66 */
67 static int conn_local_stream(ngtcp2_conn *conn, int64_t stream_id) {
68 return (uint8_t)(stream_id & 1) == conn->server;
69 }
70
71 /*
72 * bidi_stream returns nonzero if |stream_id| is a bidirectional
73 * stream ID.
74 */
75 static int bidi_stream(int64_t stream_id) { return (stream_id & 0x2) == 0; }
76
77 static void conn_update_timestamp(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
78 assert(conn->log.last_ts <= ts);
79 assert(conn->qlog.last_ts <= ts);
80
81 conn->log.last_ts = ts;
82 conn->qlog.last_ts = ts;
83 }
84
85 /*
86 * conn_is_tls_handshake_completed returns nonzero if TLS handshake
87 * has completed and 1 RTT keys are available.
88 */
89 static int conn_is_tls_handshake_completed(ngtcp2_conn *conn) {
90 return (conn->flags & NGTCP2_CONN_FLAG_TLS_HANDSHAKE_COMPLETED) &&
91 conn->pktns.crypto.rx.ckm && conn->pktns.crypto.tx.ckm;
92 }
93
94 static int conn_call_recv_client_initial(ngtcp2_conn *conn,
95 const ngtcp2_cid *dcid) {
96 int rv;
97
98 assert(conn->callbacks.recv_client_initial);
99
100 rv = conn->callbacks.recv_client_initial(conn, dcid, conn->user_data);
101 if (rv != 0) {
102 return NGTCP2_ERR_CALLBACK_FAILURE;
103 }
104
105 return 0;
106 }
107
108 static int conn_call_handshake_completed(ngtcp2_conn *conn) {
109 int rv;
110
111 if (!conn->callbacks.handshake_completed) {
112 return 0;
113 }
114
115 rv = conn->callbacks.handshake_completed(conn, conn->user_data);
116 if (rv != 0) {
117 return NGTCP2_ERR_CALLBACK_FAILURE;
118 }
119
120 return 0;
121 }
122
123 static int conn_call_recv_stream_data(ngtcp2_conn *conn, ngtcp2_strm *strm,
124 uint32_t flags, uint64_t offset,
125 const uint8_t *data, size_t datalen) {
126 int rv;
127
128 if (!conn->callbacks.recv_stream_data) {
129 return 0;
130 }
131
132 rv = conn->callbacks.recv_stream_data(conn, flags, strm->stream_id, offset,
133 data, datalen, conn->user_data,
134 strm->stream_user_data);
135 if (rv != 0) {
136 return NGTCP2_ERR_CALLBACK_FAILURE;
137 }
138
139 return 0;
140 }
141
142 static int conn_call_recv_crypto_data(ngtcp2_conn *conn,
143 ngtcp2_encryption_level encryption_level,
144 uint64_t offset, const uint8_t *data,
145 size_t datalen) {
146 int rv;
147
148 assert(conn->callbacks.recv_crypto_data);
149
150 rv = conn->callbacks.recv_crypto_data(conn, encryption_level, offset, data,
151 datalen, conn->user_data);
152 switch (rv) {
153 case 0:
154 case NGTCP2_ERR_CRYPTO:
155 case NGTCP2_ERR_REQUIRED_TRANSPORT_PARAM:
156 case NGTCP2_ERR_MALFORMED_TRANSPORT_PARAM:
157 case NGTCP2_ERR_TRANSPORT_PARAM:
158 case NGTCP2_ERR_PROTO:
159 case NGTCP2_ERR_VERSION_NEGOTIATION_FAILURE:
160 case NGTCP2_ERR_NOMEM:
161 case NGTCP2_ERR_CALLBACK_FAILURE:
162 return rv;
163 default:
164 return NGTCP2_ERR_CALLBACK_FAILURE;
165 }
166 }
167
168 static int conn_call_stream_open(ngtcp2_conn *conn, ngtcp2_strm *strm) {
169 int rv;
170
171 if (!conn->callbacks.stream_open) {
172 return 0;
173 }
174
175 rv = conn->callbacks.stream_open(conn, strm->stream_id, conn->user_data);
176 if (rv != 0) {
177 return NGTCP2_ERR_CALLBACK_FAILURE;
178 }
179
180 return 0;
181 }
182
183 static int conn_call_stream_close(ngtcp2_conn *conn, ngtcp2_strm *strm) {
184 int rv;
185 uint32_t flags = NGTCP2_STREAM_CLOSE_FLAG_NONE;
186
187 if (!conn->callbacks.stream_close) {
188 return 0;
189 }
190
191 if (strm->flags & NGTCP2_STRM_FLAG_APP_ERROR_CODE_SET) {
192 flags |= NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET;
193 }
194
195 rv = conn->callbacks.stream_close(conn, flags, strm->stream_id,
196 strm->app_error_code, conn->user_data,
197 strm->stream_user_data);
198 if (rv != 0) {
199 return NGTCP2_ERR_CALLBACK_FAILURE;
200 }
201
202 return 0;
203 }
204
205 static int conn_call_stream_reset(ngtcp2_conn *conn, int64_t stream_id,
206 uint64_t final_size, uint64_t app_error_code,
207 void *stream_user_data) {
208 int rv;
209
210 if (!conn->callbacks.stream_reset) {
211 return 0;
212 }
213
214 rv = conn->callbacks.stream_reset(conn, stream_id, final_size, app_error_code,
215 conn->user_data, stream_user_data);
216 if (rv != 0) {
217 return NGTCP2_ERR_CALLBACK_FAILURE;
218 }
219
220 return 0;
221 }
222
223 static int conn_call_extend_max_local_streams_bidi(ngtcp2_conn *conn,
224 uint64_t max_streams) {
225 int rv;
226
227 if (!conn->callbacks.extend_max_local_streams_bidi) {
228 return 0;
229 }
230
231 rv = conn->callbacks.extend_max_local_streams_bidi(conn, max_streams,
232 conn->user_data);
233 if (rv != 0) {
234 return NGTCP2_ERR_CALLBACK_FAILURE;
235 }
236
237 return 0;
238 }
239
240 static int conn_call_extend_max_local_streams_uni(ngtcp2_conn *conn,
241 uint64_t max_streams) {
242 int rv;
243
244 if (!conn->callbacks.extend_max_local_streams_uni) {
245 return 0;
246 }
247
248 rv = conn->callbacks.extend_max_local_streams_uni(conn, max_streams,
249 conn->user_data);
250 if (rv != 0) {
251 return NGTCP2_ERR_CALLBACK_FAILURE;
252 }
253
254 return 0;
255 }
256
257 static int conn_call_get_new_connection_id(ngtcp2_conn *conn, ngtcp2_cid *cid,
258 uint8_t *token, size_t cidlen) {
259 int rv;
260
261 assert(conn->callbacks.get_new_connection_id);
262
263 rv = conn->callbacks.get_new_connection_id(conn, cid, token, cidlen,
264 conn->user_data);
265 if (rv != 0) {
266 return NGTCP2_ERR_CALLBACK_FAILURE;
267 }
268
269 return 0;
270 }
271
272 static int conn_call_remove_connection_id(ngtcp2_conn *conn,
273 const ngtcp2_cid *cid) {
274 int rv;
275
276 if (!conn->callbacks.remove_connection_id) {
277 return 0;
278 }
279
280 rv = conn->callbacks.remove_connection_id(conn, cid, conn->user_data);
281 if (rv != 0) {
282 return NGTCP2_ERR_CALLBACK_FAILURE;
283 }
284
285 return 0;
286 }
287
288 static int conn_call_begin_path_validation(ngtcp2_conn *conn,
289 const ngtcp2_pv *pv) {
290 int rv;
291 uint32_t flags = NGTCP2_PATH_VALIDATION_FLAG_NONE;
292 const ngtcp2_path *fallback_path = NULL;
293
294 if (!pv || !conn->callbacks.begin_path_validation) {
295 return 0;
296 }
297
298 if (pv->flags & NGTCP2_PV_FLAG_PREFERRED_ADDR) {
299 flags |= NGTCP2_PATH_VALIDATION_FLAG_PREFERRED_ADDR;
300 }
301
302 if (pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) {
303 fallback_path = &pv->fallback_dcid.ps.path;
304 }
305
306 rv = conn->callbacks.begin_path_validation(conn, flags, &pv->dcid.ps.path,
307 fallback_path, conn->user_data);
308 if (rv != 0) {
309 return NGTCP2_ERR_CALLBACK_FAILURE;
310 }
311
312 return 0;
313 }
314
315 static int conn_call_path_validation(ngtcp2_conn *conn, const ngtcp2_pv *pv,
316 ngtcp2_path_validation_result res) {
317 int rv;
318 uint32_t flags = NGTCP2_PATH_VALIDATION_FLAG_NONE;
319 const ngtcp2_path *fallback_path = NULL;
320
321 if (!conn->callbacks.path_validation) {
322 return 0;
323 }
324
325 if (pv->flags & NGTCP2_PV_FLAG_PREFERRED_ADDR) {
326 flags |= NGTCP2_PATH_VALIDATION_FLAG_PREFERRED_ADDR;
327 }
328
329 if (pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) {
330 fallback_path = &pv->fallback_dcid.ps.path;
331 }
332
333 if (conn->server && fallback_path &&
334 (ngtcp2_addr_cmp(&pv->dcid.ps.path.remote, &fallback_path->remote) &
335 (NGTCP2_ADDR_CMP_FLAG_ADDR | NGTCP2_ADDR_CMP_FLAG_FAMILY))) {
336 flags |= NGTCP2_PATH_VALIDATION_FLAG_NEW_TOKEN;
337 }
338
339 rv = conn->callbacks.path_validation(conn, flags, &pv->dcid.ps.path,
340 fallback_path, res, conn->user_data);
341 if (rv != 0) {
342 return NGTCP2_ERR_CALLBACK_FAILURE;
343 }
344
345 return 0;
346 }
347
348 static int conn_call_select_preferred_addr(ngtcp2_conn *conn,
349 ngtcp2_path *dest) {
350 int rv;
351
352 if (!conn->callbacks.select_preferred_addr) {
353 return 0;
354 }
355
356 assert(conn->remote.transport_params);
357 assert(conn->remote.transport_params->preferred_addr_present);
358
359 rv = conn->callbacks.select_preferred_addr(
360 conn, dest, &conn->remote.transport_params->preferred_addr,
361 conn->user_data);
362 if (rv != 0) {
363 return NGTCP2_ERR_CALLBACK_FAILURE;
364 }
365
366 return 0;
367 }
368
369 static int conn_call_extend_max_remote_streams_bidi(ngtcp2_conn *conn,
370 uint64_t max_streams) {
371 int rv;
372
373 if (!conn->callbacks.extend_max_remote_streams_bidi) {
374 return 0;
375 }
376
377 rv = conn->callbacks.extend_max_remote_streams_bidi(conn, max_streams,
378 conn->user_data);
379 if (rv != 0) {
380 return NGTCP2_ERR_CALLBACK_FAILURE;
381 }
382
383 return 0;
384 }
385
386 static int conn_call_extend_max_remote_streams_uni(ngtcp2_conn *conn,
387 uint64_t max_streams) {
388 int rv;
389
390 if (!conn->callbacks.extend_max_remote_streams_uni) {
391 return 0;
392 }
393
394 rv = conn->callbacks.extend_max_remote_streams_uni(conn, max_streams,
395 conn->user_data);
396 if (rv != 0) {
397 return NGTCP2_ERR_CALLBACK_FAILURE;
398 }
399
400 return 0;
401 }
402
403 static int conn_call_extend_max_stream_data(ngtcp2_conn *conn,
404 ngtcp2_strm *strm,
405 int64_t stream_id,
406 uint64_t datalen) {
407 int rv;
408
409 if (!conn->callbacks.extend_max_stream_data) {
410 return 0;
411 }
412
413 rv = conn->callbacks.extend_max_stream_data(
414 conn, stream_id, datalen, conn->user_data, strm->stream_user_data);
415 if (rv != 0) {
416 return NGTCP2_ERR_CALLBACK_FAILURE;
417 }
418
419 return 0;
420 }
421
422 static int conn_call_dcid_status(ngtcp2_conn *conn,
423 ngtcp2_connection_id_status_type type,
424 const ngtcp2_dcid *dcid) {
425 int rv;
426
427 if (!conn->callbacks.dcid_status) {
428 return 0;
429 }
430
431 rv = conn->callbacks.dcid_status(
432 conn, type, dcid->seq, &dcid->cid,
433 (dcid->flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT) ? dcid->token : NULL,
434 conn->user_data);
435 if (rv != 0) {
436 return NGTCP2_ERR_CALLBACK_FAILURE;
437 }
438
439 return 0;
440 }
441
442 static int conn_call_activate_dcid(ngtcp2_conn *conn, const ngtcp2_dcid *dcid) {
443 return conn_call_dcid_status(conn, NGTCP2_CONNECTION_ID_STATUS_TYPE_ACTIVATE,
444 dcid);
445 }
446
447 static int conn_call_deactivate_dcid(ngtcp2_conn *conn,
448 const ngtcp2_dcid *dcid) {
449 return conn_call_dcid_status(
450 conn, NGTCP2_CONNECTION_ID_STATUS_TYPE_DEACTIVATE, dcid);
451 }
452
453 static int conn_call_stream_stop_sending(ngtcp2_conn *conn, int64_t stream_id,
454 uint64_t app_error_code,
455 void *stream_user_data) {
456 int rv;
457
458 if (!conn->callbacks.stream_stop_sending) {
459 return 0;
460 }
461
462 rv = conn->callbacks.stream_stop_sending(conn, stream_id, app_error_code,
463 conn->user_data, stream_user_data);
464 if (rv != 0) {
465 return NGTCP2_ERR_CALLBACK_FAILURE;
466 }
467
468 return 0;
469 }
470
471 static void conn_call_delete_crypto_aead_ctx(ngtcp2_conn *conn,
472 ngtcp2_crypto_aead_ctx *aead_ctx) {
473 if (!aead_ctx->native_handle) {
474 return;
475 }
476
477 assert(conn->callbacks.delete_crypto_aead_ctx);
478
479 conn->callbacks.delete_crypto_aead_ctx(conn, aead_ctx, conn->user_data);
480 }
481
482 static void
483 conn_call_delete_crypto_cipher_ctx(ngtcp2_conn *conn,
484 ngtcp2_crypto_cipher_ctx *cipher_ctx) {
485 if (!cipher_ctx->native_handle) {
486 return;
487 }
488
489 assert(conn->callbacks.delete_crypto_cipher_ctx);
490
491 conn->callbacks.delete_crypto_cipher_ctx(conn, cipher_ctx, conn->user_data);
492 }
493
494 static int conn_call_client_initial(ngtcp2_conn *conn) {
495 int rv;
496
497 assert(conn->callbacks.client_initial);
498
499 rv = conn->callbacks.client_initial(conn, conn->user_data);
500 if (rv != 0) {
501 return NGTCP2_ERR_CALLBACK_FAILURE;
502 }
503
504 return 0;
505 }
506
507 static int conn_call_get_path_challenge_data(ngtcp2_conn *conn, uint8_t *data) {
508 int rv;
509
510 assert(conn->callbacks.get_path_challenge_data);
511
512 rv = conn->callbacks.get_path_challenge_data(conn, data, conn->user_data);
513 if (rv != 0) {
514 return NGTCP2_ERR_CALLBACK_FAILURE;
515 }
516
517 return 0;
518 }
519
520 static int conn_call_recv_version_negotiation(ngtcp2_conn *conn,
521 const ngtcp2_pkt_hd *hd,
522 const uint32_t *sv, size_t nsv) {
523 int rv;
524
525 if (!conn->callbacks.recv_version_negotiation) {
526 return 0;
527 }
528
529 rv = conn->callbacks.recv_version_negotiation(conn, hd, sv, nsv,
530 conn->user_data);
531 if (rv != 0) {
532 return NGTCP2_ERR_CALLBACK_FAILURE;
533 }
534
535 return 0;
536 }
537
538 static int conn_call_recv_retry(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd) {
539 int rv;
540
541 assert(conn->callbacks.recv_retry);
542
543 rv = conn->callbacks.recv_retry(conn, hd, conn->user_data);
544 if (rv != 0) {
545 return NGTCP2_ERR_CALLBACK_FAILURE;
546 }
547
548 return 0;
549 }
550
551 static int
552 conn_call_recv_stateless_reset(ngtcp2_conn *conn,
553 const ngtcp2_pkt_stateless_reset *sr) {
554 int rv;
555
556 if (!conn->callbacks.recv_stateless_reset) {
557 return 0;
558 }
559
560 rv = conn->callbacks.recv_stateless_reset(conn, sr, conn->user_data);
561 if (rv != 0) {
562 return NGTCP2_ERR_CALLBACK_FAILURE;
563 }
564
565 return 0;
566 }
567
568 static int conn_call_recv_new_token(ngtcp2_conn *conn, const uint8_t *token,
569 size_t tokenlen) {
570 int rv;
571
572 if (!conn->callbacks.recv_new_token) {
573 return 0;
574 }
575
576 rv = conn->callbacks.recv_new_token(conn, token, tokenlen, conn->user_data);
577 if (rv != 0) {
578 return NGTCP2_ERR_CALLBACK_FAILURE;
579 }
580
581 return 0;
582 }
583
584 static int conn_call_handshake_confirmed(ngtcp2_conn *conn) {
585 int rv;
586
587 if (!conn->callbacks.handshake_confirmed) {
588 return 0;
589 }
590
591 rv = conn->callbacks.handshake_confirmed(conn, conn->user_data);
592 if (rv != 0) {
593 return NGTCP2_ERR_CALLBACK_FAILURE;
594 }
595
596 return 0;
597 }
598
599 static int conn_call_recv_datagram(ngtcp2_conn *conn,
600 const ngtcp2_datagram *fr) {
601 const uint8_t *data;
602 size_t datalen;
603 int rv;
604 uint32_t flags = NGTCP2_DATAGRAM_FLAG_NONE;
605
606 if (!conn->callbacks.recv_datagram) {
607 return 0;
608 }
609
610 if (fr->datacnt) {
611 assert(fr->datacnt == 1);
612
613 data = fr->data->base;
614 datalen = fr->data->len;
615 } else {
616 data = NULL;
617 datalen = 0;
618 }
619
620 if (!conn_is_tls_handshake_completed(conn)) {
621 flags |= NGTCP2_DATAGRAM_FLAG_0RTT;
622 }
623
624 rv =
625 conn->callbacks.recv_datagram(conn, flags, data, datalen, conn->user_data);
626 if (rv != 0) {
627 return NGTCP2_ERR_CALLBACK_FAILURE;
628 }
629
630 return 0;
631 }
632
633 static int
634 conn_call_update_key(ngtcp2_conn *conn, uint8_t *rx_secret, uint8_t *tx_secret,
635 ngtcp2_crypto_aead_ctx *rx_aead_ctx, uint8_t *rx_iv,
636 ngtcp2_crypto_aead_ctx *tx_aead_ctx, uint8_t *tx_iv,
637 const uint8_t *current_rx_secret,
638 const uint8_t *current_tx_secret, size_t secretlen) {
639 int rv;
640
641 assert(conn->callbacks.update_key);
642
643 rv = conn->callbacks.update_key(
644 conn, rx_secret, tx_secret, rx_aead_ctx, rx_iv, tx_aead_ctx, tx_iv,
645 current_rx_secret, current_tx_secret, secretlen, conn->user_data);
646 if (rv != 0) {
647 return NGTCP2_ERR_CALLBACK_FAILURE;
648 }
649
650 return 0;
651 }
652
653 static int conn_call_version_negotiation(ngtcp2_conn *conn, uint32_t version,
654 const ngtcp2_cid *dcid) {
655 int rv;
656
657 assert(conn->callbacks.version_negotiation);
658
659 rv =
660 conn->callbacks.version_negotiation(conn, version, dcid, conn->user_data);
661 if (rv != 0) {
662 return NGTCP2_ERR_CALLBACK_FAILURE;
663 }
664
665 return 0;
666 }
667
668 static int conn_call_recv_rx_key(ngtcp2_conn *conn,
669 ngtcp2_encryption_level level) {
670 int rv;
671
672 if (!conn->callbacks.recv_rx_key) {
673 return 0;
674 }
675
676 rv = conn->callbacks.recv_rx_key(conn, level, conn->user_data);
677 if (rv != 0) {
678 return NGTCP2_ERR_CALLBACK_FAILURE;
679 }
680
681 return 0;
682 }
683
684 static int conn_call_recv_tx_key(ngtcp2_conn *conn,
685 ngtcp2_encryption_level level) {
686 int rv;
687
688 if (!conn->callbacks.recv_tx_key) {
689 return 0;
690 }
691
692 rv = conn->callbacks.recv_tx_key(conn, level, conn->user_data);
693 if (rv != 0) {
694 return NGTCP2_ERR_CALLBACK_FAILURE;
695 }
696
697 return 0;
698 }
699
700 /*
701 * pktns_init initializes |pktns|. It assumes that the object pointed
702 * by |pktns| is zero-cleared.
703 */
704 static void pktns_init(ngtcp2_pktns *pktns, ngtcp2_pktns_id pktns_id,
705 ngtcp2_rst *rst, ngtcp2_cc *cc, int64_t initial_pkt_num,
706 ngtcp2_log *log, ngtcp2_qlog *qlog,
707 ngtcp2_objalloc *rtb_entry_objalloc,
708 ngtcp2_objalloc *frc_objalloc, const ngtcp2_mem *mem) {
709 ngtcp2_gaptr_init(&pktns->rx.pngap, mem);
710
711 pktns->tx.last_pkt_num = initial_pkt_num - 1;
712 pktns->tx.non_ack_pkt_start_ts = UINT64_MAX;
713 pktns->rx.max_ack_eliciting_pkt_num = -1;
714 pktns->id = pktns_id;
715
716 ngtcp2_acktr_init(&pktns->acktr, log, mem);
717
718 ngtcp2_strm_init(&pktns->crypto.strm, 0, NGTCP2_STRM_FLAG_NONE, 0, 0, NULL,
719 frc_objalloc, mem);
720
721 ngtcp2_rtb_init(&pktns->rtb, rst, cc, initial_pkt_num, log, qlog,
722 rtb_entry_objalloc, frc_objalloc, mem);
723 }
724
725 static int pktns_new(ngtcp2_pktns **ppktns, ngtcp2_pktns_id pktns_id,
726 ngtcp2_rst *rst, ngtcp2_cc *cc, int64_t initial_pkt_num,
727 ngtcp2_log *log, ngtcp2_qlog *qlog,
728 ngtcp2_objalloc *rtb_entry_objalloc,
729 ngtcp2_objalloc *frc_objalloc, const ngtcp2_mem *mem) {
730 *ppktns = ngtcp2_mem_calloc(mem, 1, sizeof(ngtcp2_pktns));
731 if (*ppktns == NULL) {
732 return NGTCP2_ERR_NOMEM;
733 }
734
735 pktns_init(*ppktns, pktns_id, rst, cc, initial_pkt_num, log, qlog,
736 rtb_entry_objalloc, frc_objalloc, mem);
737
738 return 0;
739 }
740
741 static int cycle_less(const ngtcp2_pq_entry *lhs, const ngtcp2_pq_entry *rhs) {
742 ngtcp2_strm *ls = ngtcp2_struct_of(lhs, ngtcp2_strm, pe);
743 ngtcp2_strm *rs = ngtcp2_struct_of(rhs, ngtcp2_strm, pe);
744
745 if (ls->cycle == rs->cycle) {
746 return ls->stream_id < rs->stream_id;
747 }
748
749 return rs->cycle - ls->cycle <= 1;
750 }
751
752 static void delete_buffed_pkts(ngtcp2_pkt_chain *pc, const ngtcp2_mem *mem) {
753 ngtcp2_pkt_chain *next;
754
755 for (; pc;) {
756 next = pc->next;
757 ngtcp2_pkt_chain_del(pc, mem);
758 pc = next;
759 }
760 }
761
762 static void delete_buf_chain(ngtcp2_buf_chain *bufchain,
763 const ngtcp2_mem *mem) {
764 ngtcp2_buf_chain *next;
765
766 for (; bufchain;) {
767 next = bufchain->next;
768 ngtcp2_buf_chain_del(bufchain, mem);
769 bufchain = next;
770 }
771 }
772
773 static void pktns_free(ngtcp2_pktns *pktns, const ngtcp2_mem *mem) {
774 delete_buf_chain(pktns->crypto.tx.data, mem);
775
776 delete_buffed_pkts(pktns->rx.buffed_pkts, mem);
777
778 ngtcp2_frame_chain_list_objalloc_del(pktns->tx.frq, pktns->rtb.frc_objalloc,
779 mem);
780
781 ngtcp2_crypto_km_del(pktns->crypto.rx.ckm, mem);
782 ngtcp2_crypto_km_del(pktns->crypto.tx.ckm, mem);
783
784 ngtcp2_rtb_free(&pktns->rtb);
785 ngtcp2_strm_free(&pktns->crypto.strm);
786 ngtcp2_acktr_free(&pktns->acktr);
787 ngtcp2_gaptr_free(&pktns->rx.pngap);
788 }
789
790 static void pktns_del(ngtcp2_pktns *pktns, const ngtcp2_mem *mem) {
791 if (pktns == NULL) {
792 return;
793 }
794
795 pktns_free(pktns, mem);
796
797 ngtcp2_mem_free(mem, pktns);
798 }
799
800 static int cid_less(const ngtcp2_ksl_key *lhs, const ngtcp2_ksl_key *rhs) {
801 return ngtcp2_cid_less(lhs, rhs);
802 }
803
804 ngtcp2_ksl_search_def(cid_less, cid_less)
805
806 static int retired_ts_less(const ngtcp2_pq_entry *lhs,
807 const ngtcp2_pq_entry *rhs) {
808 const ngtcp2_scid *a = ngtcp2_struct_of(lhs, ngtcp2_scid, pe);
809 const ngtcp2_scid *b = ngtcp2_struct_of(rhs, ngtcp2_scid, pe);
810
811 return a->retired_ts < b->retired_ts;
812 }
813
814 /*
815 * conn_reset_conn_stat_cc resets congestion state in |cstat|.
816 */
817 static void conn_reset_conn_stat_cc(ngtcp2_conn *conn,
818 ngtcp2_conn_stat *cstat) {
819 cstat->latest_rtt = 0;
820 cstat->min_rtt = UINT64_MAX;
821 cstat->smoothed_rtt = conn->local.settings.initial_rtt;
822 cstat->rttvar = conn->local.settings.initial_rtt / 2;
823 cstat->first_rtt_sample_ts = UINT64_MAX;
824 cstat->pto_count = 0;
825 cstat->loss_detection_timer = UINT64_MAX;
826 cstat->max_tx_udp_payload_size =
827 ngtcp2_conn_get_path_max_tx_udp_payload_size(conn);
828 cstat->cwnd = ngtcp2_cc_compute_initcwnd(cstat->max_tx_udp_payload_size);
829 cstat->ssthresh = UINT64_MAX;
830 cstat->congestion_recovery_start_ts = UINT64_MAX;
831 cstat->bytes_in_flight = 0;
832 cstat->delivery_rate_sec = 0;
833 cstat->pacing_interval_m = 0;
834 cstat->send_quantum = 64 * 1024;
835 }
836
837 /*
838 * reset_conn_stat_recovery resets the fields related to the recovery
839 * function
840 */
841 static void reset_conn_stat_recovery(ngtcp2_conn_stat *cstat) {
842 /* Initializes them with UINT64_MAX. */
843 memset(cstat->loss_time, 0xff, sizeof(cstat->loss_time));
844 memset(cstat->last_tx_pkt_ts, 0xff, sizeof(cstat->last_tx_pkt_ts));
845 }
846
847 /*
848 * conn_reset_conn_stat resets |cstat|. The following fields are not
849 * reset: initial_rtt and max_udp_payload_size.
850 */
851 static void conn_reset_conn_stat(ngtcp2_conn *conn, ngtcp2_conn_stat *cstat) {
852 conn_reset_conn_stat_cc(conn, cstat);
853 reset_conn_stat_recovery(cstat);
854 }
855
856 static void delete_scid(ngtcp2_ksl *scids, const ngtcp2_mem *mem) {
857 ngtcp2_ksl_it it;
858
859 for (it = ngtcp2_ksl_begin(scids); !ngtcp2_ksl_it_end(&it);
860 ngtcp2_ksl_it_next(&it)) {
861 ngtcp2_mem_free(mem, ngtcp2_ksl_it_get(&it));
862 }
863 }
864
865 /*
866 * compute_pto computes PTO.
867 */
868 static ngtcp2_duration compute_pto(ngtcp2_duration smoothed_rtt,
869 ngtcp2_duration rttvar,
870 ngtcp2_duration max_ack_delay) {
871 ngtcp2_duration var = ngtcp2_max_uint64(4 * rttvar, NGTCP2_GRANULARITY);
872 return smoothed_rtt + var + max_ack_delay;
873 }
874
875 /*
876 * conn_compute_initial_pto computes PTO using the initial RTT.
877 */
878 static ngtcp2_duration conn_compute_initial_pto(ngtcp2_conn *conn,
879 ngtcp2_pktns *pktns) {
880 ngtcp2_duration initial_rtt = conn->local.settings.initial_rtt;
881 ngtcp2_duration max_ack_delay;
882
883 if (pktns->id == NGTCP2_PKTNS_ID_APPLICATION &&
884 conn->remote.transport_params) {
885 max_ack_delay = conn->remote.transport_params->max_ack_delay;
886 } else {
887 max_ack_delay = 0;
888 }
889 return compute_pto(initial_rtt, initial_rtt / 2, max_ack_delay);
890 }
891
892 /*
893 * conn_compute_pto computes the current PTO.
894 */
895 static ngtcp2_duration conn_compute_pto(ngtcp2_conn *conn,
896 ngtcp2_pktns *pktns) {
897 ngtcp2_conn_stat *cstat = &conn->cstat;
898 ngtcp2_duration max_ack_delay;
899
900 if (pktns->id == NGTCP2_PKTNS_ID_APPLICATION &&
901 conn->remote.transport_params) {
902 max_ack_delay = conn->remote.transport_params->max_ack_delay;
903 } else {
904 max_ack_delay = 0;
905 }
906 return compute_pto(cstat->smoothed_rtt, cstat->rttvar, max_ack_delay);
907 }
908
909 ngtcp2_duration ngtcp2_conn_compute_pto(ngtcp2_conn *conn,
910 ngtcp2_pktns *pktns) {
911 return conn_compute_pto(conn, pktns);
912 }
913
914 /*
915 * conn_compute_pv_timeout_pto returns path validation timeout using
916 * the given |pto|.
917 */
918 static ngtcp2_duration conn_compute_pv_timeout_pto(ngtcp2_conn *conn,
919 ngtcp2_duration pto) {
920 ngtcp2_duration initial_pto = conn_compute_initial_pto(conn, &conn->pktns);
921
922 return 3 * ngtcp2_max_uint64(pto, initial_pto);
923 }
924
925 /*
926 * conn_compute_pv_timeout returns path validation timeout.
927 */
928 static ngtcp2_duration conn_compute_pv_timeout(ngtcp2_conn *conn) {
929 return conn_compute_pv_timeout_pto(conn,
930 conn_compute_pto(conn, &conn->pktns));
931 }
932
933 static void conn_handle_tx_ecn(ngtcp2_conn *conn, ngtcp2_pkt_info *pi,
934 uint16_t *prtb_entry_flags, ngtcp2_pktns *pktns,
935 const ngtcp2_pkt_hd *hd, ngtcp2_tstamp ts) {
936 assert(pi);
937
938 if (pi->ecn != NGTCP2_ECN_NOT_ECT) {
939 /* We have already made a transition of validation state and
940 deceided to send UDP datagram with ECN bit set. Coalesced QUIC
941 packets also bear ECN bits set. */
942 if (pktns->tx.ecn.start_pkt_num == INT64_MAX) {
943 pktns->tx.ecn.start_pkt_num = hd->pkt_num;
944 }
945
946 ++pktns->tx.ecn.validation_pkt_sent;
947
948 if (prtb_entry_flags) {
949 *prtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ECN;
950 }
951
952 ++pktns->tx.ecn.ect0;
953
954 return;
955 }
956
957 switch (conn->tx.ecn.state) {
958 case NGTCP2_ECN_STATE_TESTING:
959 if (conn->tx.ecn.validation_start_ts == UINT64_MAX) {
960 assert(0 == pktns->tx.ecn.validation_pkt_sent);
961 assert(0 == pktns->tx.ecn.validation_pkt_lost);
962
963 conn->tx.ecn.validation_start_ts = ts;
964 } else if (ts - conn->tx.ecn.validation_start_ts >=
965 3 * conn_compute_pto(conn, pktns)) {
966 conn->tx.ecn.state = NGTCP2_ECN_STATE_UNKNOWN;
967 break;
968 }
969
970 if (pktns->tx.ecn.start_pkt_num == INT64_MAX) {
971 pktns->tx.ecn.start_pkt_num = hd->pkt_num;
972 }
973
974 ++pktns->tx.ecn.validation_pkt_sent;
975
976 if (++conn->tx.ecn.dgram_sent == NGTCP2_ECN_MAX_NUM_VALIDATION_PKTS) {
977 conn->tx.ecn.state = NGTCP2_ECN_STATE_UNKNOWN;
978 }
979 /* fall through */
980 case NGTCP2_ECN_STATE_CAPABLE:
981 /* pi is provided per UDP datagram. */
982 assert(NGTCP2_ECN_NOT_ECT == pi->ecn);
983
984 pi->ecn = NGTCP2_ECN_ECT_0;
985
986 if (prtb_entry_flags) {
987 *prtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ECN;
988 }
989
990 ++pktns->tx.ecn.ect0;
991 break;
992 case NGTCP2_ECN_STATE_UNKNOWN:
993 case NGTCP2_ECN_STATE_FAILED:
994 break;
995 default:
996 ngtcp2_unreachable();
997 }
998 }
999
1000 static void conn_reset_ecn_validation_state(ngtcp2_conn *conn) {
1001 ngtcp2_pktns *in_pktns = conn->in_pktns;
1002 ngtcp2_pktns *hs_pktns = conn->hs_pktns;
1003 ngtcp2_pktns *pktns = &conn->pktns;
1004
1005 conn->tx.ecn.state = NGTCP2_ECN_STATE_TESTING;
1006 conn->tx.ecn.validation_start_ts = UINT64_MAX;
1007 conn->tx.ecn.dgram_sent = 0;
1008
1009 if (in_pktns) {
1010 in_pktns->tx.ecn.start_pkt_num = INT64_MAX;
1011 in_pktns->tx.ecn.validation_pkt_sent = 0;
1012 in_pktns->tx.ecn.validation_pkt_lost = 0;
1013 }
1014
1015 if (hs_pktns) {
1016 hs_pktns->tx.ecn.start_pkt_num = INT64_MAX;
1017 hs_pktns->tx.ecn.validation_pkt_sent = 0;
1018 hs_pktns->tx.ecn.validation_pkt_lost = 0;
1019 }
1020
1021 pktns->tx.ecn.start_pkt_num = INT64_MAX;
1022 pktns->tx.ecn.validation_pkt_sent = 0;
1023 pktns->tx.ecn.validation_pkt_lost = 0;
1024 }
1025
1026 /* server_default_available_versions is the default available_versions
1027 field sent by server. */
1028 static uint8_t server_default_available_versions[] = {0, 0, 0, 1};
1029
1030 /*
1031 * available_versions_init writes |versions| of length |versionslen|
1032 * in network byte order to the buffer pointed by |buf|, suitable for
1033 * sending in available_versions field of version_information QUIC
1034 * transport parameter. This function returns the pointer to the one
1035 * beyond the last byte written.
1036 */
1037 static void *available_versions_init(void *buf, const uint32_t *versions,
1038 size_t versionslen) {
1039 size_t i;
1040
1041 for (i = 0; i < versionslen; ++i) {
1042 buf = ngtcp2_put_uint32be(buf, versions[i]);
1043 }
1044
1045 return 0;
1046 }
1047
1048 static void
1049 conn_set_local_transport_params(ngtcp2_conn *conn,
1050 const ngtcp2_transport_params *params) {
1051 ngtcp2_transport_params *p = &conn->local.transport_params;
1052 uint32_t chosen_version = p->version_info.chosen_version;
1053
1054 *p = *params;
1055
1056 if (conn->server) {
1057 p->version_info.chosen_version = chosen_version;
1058 } else {
1059 p->version_info.chosen_version = conn->client_chosen_version;
1060 }
1061 p->version_info.available_versions = conn->vneg.available_versions;
1062 p->version_info.available_versionslen = conn->vneg.available_versionslen;
1063 p->version_info_present = 1;
1064 }
1065
1066 static void conn_update_skip_pkt(ngtcp2_conn *conn, ngtcp2_pktns *pktns) {
1067 const int64_t min_gap = 3;
1068 uint8_t r;
1069 int64_t gap;
1070
1071 assert(INT64_MAX != pktns->tx.skip_pkt.next_pkt_num);
1072
1073 conn->callbacks.rand(&r, 1, &conn->local.settings.rand_ctx);
1074
1075 if (1ll << pktns->tx.skip_pkt.exponent >
1076 (NGTCP2_MAX_PKT_NUM - min_gap) / ((int64_t)r + 1)) {
1077 pktns->tx.skip_pkt.next_pkt_num = INT64_MAX;
1078 return;
1079 }
1080
1081 gap = ((int64_t)r + 1) * (1ll << pktns->tx.skip_pkt.exponent++) + min_gap;
1082
1083 if (pktns->tx.last_pkt_num > NGTCP2_MAX_PKT_NUM - gap) {
1084 pktns->tx.skip_pkt.next_pkt_num = INT64_MAX;
1085 return;
1086 }
1087
1088 pktns->tx.skip_pkt.next_pkt_num = pktns->tx.last_pkt_num + gap;
1089
1090 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON, "next skip pkn=%" PRId64,
1091 pktns->tx.skip_pkt.next_pkt_num);
1092 }
1093
1094 static int conn_handle_skip_pkt(ngtcp2_conn *conn, ngtcp2_pktns *pktns,
1095 ngtcp2_tstamp ts) {
1096 ngtcp2_rtb_entry *rtbent;
1097 ngtcp2_pkt_hd hd;
1098 int rv;
1099
1100 assert(NGTCP2_PKTNS_ID_APPLICATION == pktns->id);
1101
1102 if (pktns->tx.last_pkt_num + 1 != pktns->tx.skip_pkt.next_pkt_num) {
1103 return 0;
1104 }
1105
1106 ngtcp2_pkt_hd_init(&hd, 0, NGTCP2_PKT_1RTT, NULL, NULL,
1107 pktns->tx.skip_pkt.next_pkt_num, 0, 0);
1108
1109 rv = ngtcp2_rtb_entry_objalloc_new(&rtbent, &hd, NULL, ts, 0,
1110 NGTCP2_RTB_ENTRY_FLAG_SKIP,
1111 &conn->rtb_entry_objalloc);
1112 if (rv != 0) {
1113 assert(ngtcp2_err_is_fatal(rv));
1114 return rv;
1115 }
1116
1117 rv = ngtcp2_rtb_add(&pktns->rtb, rtbent, &conn->cstat);
1118 if (rv != 0) {
1119 ngtcp2_rtb_entry_objalloc_del(rtbent, &conn->rtb_entry_objalloc,
1120 &conn->frc_objalloc, conn->mem);
1121 return rv;
1122 }
1123
1124 ++pktns->tx.last_pkt_num;
1125
1126 conn_update_skip_pkt(conn, pktns);
1127
1128 return 0;
1129 }
1130
1131 static size_t buflen_align(size_t buflen) {
1132 return (buflen + 0x7) & (size_t)~0x7;
1133 }
1134
1135 static void *buf_align(void *buf) {
1136 return (void *)((uintptr_t)((uint8_t *)buf + 0x7) & (uintptr_t)~0x7);
1137 }
1138
1139 static void *buf_advance(void *buf, size_t n) { return (uint8_t *)buf + n; }
1140
1141 static int conn_new(ngtcp2_conn **pconn, const ngtcp2_cid *dcid,
1142 const ngtcp2_cid *scid, const ngtcp2_path *path,
1143 uint32_t client_chosen_version, int callbacks_version,
1144 const ngtcp2_callbacks *callbacks, int settings_version,
1145 const ngtcp2_settings *settings,
1146 int transport_params_version,
1147 const ngtcp2_transport_params *params,
1148 const ngtcp2_mem *mem, void *user_data, int server) {
1149 int rv;
1150 ngtcp2_scid *scident;
1151 void *buf, *tokenbuf;
1152 size_t buflen;
1153 uint8_t fixed_bit_byte;
1154 size_t i;
1155 uint32_t *preferred_versions;
1156 ngtcp2_settings settingsbuf;
1157 ngtcp2_transport_params paramsbuf;
1158 ngtcp2_callbacks callbacksbuf;
1159 uint64_t seed;
1160 (void)settings_version;
1161
1162 settings =
1163 ngtcp2_settings_convert_to_latest(&settingsbuf, settings_version, settings);
1164 params = ngtcp2_transport_params_convert_to_latest(
1165 &paramsbuf, transport_params_version, params);
1166 callbacks = ngtcp2_callbacks_convert_to_latest(&callbacksbuf,
1167 callbacks_version, callbacks);
1168
1169 assert(settings->max_window <= NGTCP2_MAX_VARINT);
1170 assert(settings->max_stream_window <= NGTCP2_MAX_VARINT);
1171 assert(settings->max_tx_udp_payload_size >= NGTCP2_MAX_UDP_PAYLOAD_SIZE);
1172 assert(settings->max_tx_udp_payload_size <= NGTCP2_MAX_TX_UDP_PAYLOAD_SIZE);
1173 assert(settings->initial_pkt_num <= INT32_MAX);
1174 assert(settings->initial_rtt);
1175 assert(params->active_connection_id_limit >=
1176 NGTCP2_DEFAULT_ACTIVE_CONNECTION_ID_LIMIT);
1177 assert(params->active_connection_id_limit <=
1178 NGTCP2_DCIDTR_MAX_UNUSED_DCID_SIZE);
1179 assert(params->initial_max_data <= NGTCP2_MAX_VARINT);
1180 assert(params->initial_max_stream_data_bidi_local <= NGTCP2_MAX_VARINT);
1181 assert(params->initial_max_stream_data_bidi_remote <= NGTCP2_MAX_VARINT);
1182 assert(params->initial_max_stream_data_uni <= NGTCP2_MAX_VARINT);
1183 assert((server && params->original_dcid_present) ||
1184 (!server && !params->original_dcid_present));
1185 assert(!params->initial_scid_present);
1186 assert(server || !params->stateless_reset_token_present);
1187 assert(server || !params->preferred_addr_present);
1188 assert(server || !params->retry_scid_present);
1189 assert(params->max_idle_timeout != UINT64_MAX);
1190 assert(params->max_ack_delay < (1 << 14) * NGTCP2_MILLISECONDS);
1191 assert(server || callbacks->client_initial);
1192 assert(!server || callbacks->recv_client_initial);
1193 assert(callbacks->recv_crypto_data);
1194 assert(callbacks->encrypt);
1195 assert(callbacks->decrypt);
1196 assert(callbacks->hp_mask);
1197 assert(server || callbacks->recv_retry);
1198 assert(callbacks->rand);
1199 assert(callbacks->get_new_connection_id);
1200 assert(callbacks->update_key);
1201 assert(callbacks->delete_crypto_aead_ctx);
1202 assert(callbacks->delete_crypto_cipher_ctx);
1203 assert(callbacks->get_path_challenge_data);
1204 assert(!server || !ngtcp2_is_reserved_version(client_chosen_version));
1205
1206 for (i = 0; i < settings->pmtud_probeslen; ++i) {
1207 assert(settings->pmtud_probes[i] > NGTCP2_MAX_UDP_PAYLOAD_SIZE);
1208 assert(settings->pmtud_probes[i] <= NGTCP2_MAX_TX_UDP_PAYLOAD_SIZE);
1209 }
1210
1211 if (mem == NULL) {
1212 mem = ngtcp2_mem_default();
1213 }
1214
1215 buflen = sizeof(ngtcp2_conn);
1216 if (settings->qlog_write) {
1217 buflen = buflen_align(buflen);
1218 buflen += NGTCP2_QLOG_BUFLEN;
1219 }
1220
1221 if (settings->pmtud_probeslen) {
1222 buflen = buflen_align(buflen);
1223 buflen += sizeof(settings->pmtud_probes[0]) * settings->pmtud_probeslen;
1224 }
1225
1226 if (settings->preferred_versionslen) {
1227 buflen = buflen_align(buflen);
1228 buflen +=
1229 sizeof(settings->preferred_versions[0]) * settings->preferred_versionslen;
1230 }
1231
1232 if (settings->available_versionslen) {
1233 buflen = buflen_align(buflen);
1234 buflen +=
1235 sizeof(settings->available_versions[0]) * settings->available_versionslen;
1236 } else if (server) {
1237 if (settings->preferred_versionslen) {
1238 buflen = buflen_align(buflen);
1239 buflen += sizeof(settings->preferred_versions[0]) *
1240 settings->preferred_versionslen;
1241 }
1242 } else if (!ngtcp2_is_reserved_version(client_chosen_version)) {
1243 buflen = buflen_align(buflen);
1244 buflen += sizeof(client_chosen_version);
1245 }
1246
1247 buf = ngtcp2_mem_calloc(mem, 1, buflen);
1248 if (buf == NULL) {
1249 return NGTCP2_ERR_NOMEM;
1250 }
1251
1252 *pconn = buf;
1253 buf = buf_advance(buf, sizeof(ngtcp2_conn));
1254
1255 (*pconn)->server = server;
1256
1257 ngtcp2_objalloc_frame_chain_init(&(*pconn)->frc_objalloc, 16, mem);
1258 ngtcp2_objalloc_rtb_entry_init(&(*pconn)->rtb_entry_objalloc, 16, mem);
1259 ngtcp2_objalloc_strm_init(&(*pconn)->strm_objalloc, 16, mem);
1260
1261 ngtcp2_dcidtr_init(&(*pconn)->dcid.dtr);
1262
1263 ngtcp2_gaptr_init(&(*pconn)->dcid.seqgap, mem);
1264
1265 ngtcp2_ksl_init(&(*pconn)->scid.set, cid_less, ksl_cid_less_search,
1266 sizeof(ngtcp2_cid), mem);
1267
1268 ngtcp2_pq_init(&(*pconn)->scid.used, retired_ts_less, mem);
1269
1270 callbacks->rand((uint8_t *)&seed, sizeof(seed), &settings->rand_ctx);
1271 ngtcp2_map_init(&(*pconn)->strms, seed, mem);
1272
1273 callbacks->rand((uint8_t *)&seed, sizeof(seed), &settings->rand_ctx);
1274 ngtcp2_pcg32_init(&(*pconn)->pcg, seed);
1275
1276 ngtcp2_pq_init(&(*pconn)->tx.strmq, cycle_less, mem);
1277
1278 ngtcp2_idtr_init(&(*pconn)->remote.bidi.idtr, mem);
1279
1280 ngtcp2_idtr_init(&(*pconn)->remote.uni.idtr, mem);
1281
1282 ngtcp2_static_ringbuf_path_challenge_init(&(*pconn)->rx.path_challenge);
1283
1284 ngtcp2_log_init(&(*pconn)->log, scid, settings->log_printf,
1285 settings->initial_ts, user_data);
1286 ngtcp2_qlog_init(&(*pconn)->qlog, settings->qlog_write, settings->initial_ts,
1287 user_data);
1288 if ((*pconn)->qlog.write) {
1289 buf = buf_align(buf);
1290 ngtcp2_buf_init(&(*pconn)->qlog.buf, buf, NGTCP2_QLOG_BUFLEN);
1291 buf = buf_advance(buf, NGTCP2_QLOG_BUFLEN);
1292 }
1293
1294 (*pconn)->local.settings = *settings;
1295
1296 if (settings->tokenlen) {
1297 tokenbuf = ngtcp2_mem_malloc(mem, settings->tokenlen);
1298 if (tokenbuf == NULL) {
1299 rv = NGTCP2_ERR_NOMEM;
1300 goto fail_token;
1301 }
1302 memcpy(tokenbuf, settings->token, settings->tokenlen);
1303 (*pconn)->local.settings.token = tokenbuf;
1304 } else {
1305 (*pconn)->local.settings.token = NULL;
1306 }
1307
1308 if (settings->pmtud_probeslen) {
1309 (*pconn)->local.settings.pmtud_probes = buf_align(buf);
1310 buf = ngtcp2_cpymem(
1311 (uint16_t *)(*pconn)->local.settings.pmtud_probes, settings->pmtud_probes,
1312 sizeof(settings->pmtud_probes[0]) * settings->pmtud_probeslen);
1313 }
1314
1315 if (!(*pconn)->local.settings.original_version) {
1316 (*pconn)->local.settings.original_version = client_chosen_version;
1317 }
1318
1319 ngtcp2_dcid_init(&(*pconn)->dcid.current, 0, dcid, NULL);
1320 ngtcp2_dcid_set_path(&(*pconn)->dcid.current, path);
1321
1322 assert((size_t)path->local.addrlen <= sizeof((*pconn)->hs_local_addr));
1323
1324 memcpy(&(*pconn)->hs_local_addr, path->local.addr,
1325 (size_t)path->local.addrlen);
1326
1327 rv = ngtcp2_gaptr_push(&(*pconn)->dcid.seqgap, 0, 1);
1328 if (rv != 0) {
1329 goto fail_seqgap_push;
1330 }
1331
1332 conn_reset_conn_stat(*pconn, &(*pconn)->cstat);
1333 (*pconn)->cstat.initial_rtt = settings->initial_rtt;
1334
1335 ngtcp2_rst_init(&(*pconn)->rst);
1336
1337 (*pconn)->cc_algo = settings->cc_algo;
1338
1339 switch (settings->cc_algo) {
1340 case NGTCP2_CC_ALGO_RENO:
1341 ngtcp2_cc_reno_init(&(*pconn)->reno, &(*pconn)->log, &(*pconn)->cstat);
1342
1343 break;
1344 case NGTCP2_CC_ALGO_CUBIC:
1345 ngtcp2_cc_cubic_init(&(*pconn)->cubic, &(*pconn)->log, &(*pconn)->cstat,
1346 &(*pconn)->rst);
1347
1348 break;
1349 case NGTCP2_CC_ALGO_BBR:
1350 ngtcp2_cc_bbr_init(&(*pconn)->bbr, &(*pconn)->log, &(*pconn)->cstat,
1351 &(*pconn)->rst, settings->initial_ts, &(*pconn)->pcg);
1352
1353 break;
1354 default:
1355 ngtcp2_unreachable();
1356 }
1357
1358 ngtcp2_static_ringbuf_path_history_init(&(*pconn)->path_history);
1359
1360 ngtcp2_ratelim_init(&(*pconn)->glitch_rlim, settings->glitch_ratelim_burst,
1361 settings->glitch_ratelim_rate, settings->initial_ts);
1362
1363 (*pconn)->callbacks = *callbacks;
1364
1365 rv = pktns_new(&(*pconn)->in_pktns, NGTCP2_PKTNS_ID_INITIAL, &(*pconn)->rst,
1366 &(*pconn)->cc, settings->initial_pkt_num, &(*pconn)->log,
1367 &(*pconn)->qlog, &(*pconn)->rtb_entry_objalloc,
1368 &(*pconn)->frc_objalloc, mem);
1369 if (rv != 0) {
1370 goto fail_in_pktns_init;
1371 }
1372
1373 rv = pktns_new(&(*pconn)->hs_pktns, NGTCP2_PKTNS_ID_HANDSHAKE, &(*pconn)->rst,
1374 &(*pconn)->cc, settings->initial_pkt_num, &(*pconn)->log,
1375 &(*pconn)->qlog, &(*pconn)->rtb_entry_objalloc,
1376 &(*pconn)->frc_objalloc, mem);
1377 if (rv != 0) {
1378 goto fail_hs_pktns_init;
1379 }
1380
1381 pktns_init(&(*pconn)->pktns, NGTCP2_PKTNS_ID_APPLICATION, &(*pconn)->rst,
1382 &(*pconn)->cc, settings->initial_pkt_num, &(*pconn)->log,
1383 &(*pconn)->qlog, &(*pconn)->rtb_entry_objalloc,
1384 &(*pconn)->frc_objalloc, mem);
1385
1386 conn_update_skip_pkt(*pconn, &(*pconn)->pktns);
1387
1388 scident = ngtcp2_mem_malloc(mem, sizeof(*scident));
1389 if (scident == NULL) {
1390 rv = NGTCP2_ERR_NOMEM;
1391 goto fail_scident;
1392 }
1393
1394 /* Set stateless reset token later if it is available in the local
1395 transport parameters */
1396 ngtcp2_scid_init(scident, 0, scid);
1397
1398 rv = ngtcp2_ksl_insert(&(*pconn)->scid.set, NULL, &scident->cid, scident);
1399 if (rv != 0) {
1400 goto fail_scid_set_insert;
1401 }
1402
1403 scident = NULL;
1404
1405 if (settings->preferred_versionslen) {
1406 if (!server && !ngtcp2_is_reserved_version(client_chosen_version)) {
1407 for (i = 0; i < settings->preferred_versionslen; ++i) {
1408 if (settings->preferred_versions[i] == client_chosen_version) {
1409 break;
1410 }
1411 }
1412
1413 assert(i < settings->preferred_versionslen);
1414 }
1415
1416 preferred_versions = buf_align(buf);
1417 buf = buf_advance(preferred_versions, sizeof(preferred_versions[0]) *
1418 settings->preferred_versionslen);
1419
1420 for (i = 0; i < settings->preferred_versionslen; ++i) {
1421 assert(ngtcp2_is_supported_version(settings->preferred_versions[i]));
1422
1423 preferred_versions[i] = settings->preferred_versions[i];
1424 }
1425
1426 (*pconn)->vneg.preferred_versions = preferred_versions;
1427 (*pconn)->vneg.preferred_versionslen = settings->preferred_versionslen;
1428 }
1429
1430 (*pconn)->local.settings.preferred_versions = NULL;
1431 (*pconn)->local.settings.preferred_versionslen = 0;
1432
1433 if (settings->available_versionslen) {
1434 if (!server && !ngtcp2_is_reserved_version(client_chosen_version)) {
1435 for (i = 0; i < settings->available_versionslen; ++i) {
1436 if (settings->available_versions[i] == client_chosen_version) {
1437 break;
1438 }
1439 }
1440
1441 assert(i < settings->available_versionslen);
1442 }
1443
1444 for (i = 0; i < settings->available_versionslen; ++i) {
1445 assert(ngtcp2_is_reserved_version(settings->available_versions[i]) ||
1446 ngtcp2_is_supported_version(settings->available_versions[i]));
1447 }
1448
1449 (*pconn)->vneg.available_versions = buf_align(buf);
1450 (*pconn)->vneg.available_versionslen =
1451 sizeof(uint32_t) * settings->available_versionslen;
1452
1453 buf = available_versions_init((*pconn)->vneg.available_versions,
1454 settings->available_versions,
1455 settings->available_versionslen);
1456 } else if (server) {
1457 if (settings->preferred_versionslen) {
1458 (*pconn)->vneg.available_versions = buf_align(buf);
1459 (*pconn)->vneg.available_versionslen =
1460 sizeof(uint32_t) * settings->preferred_versionslen;
1461
1462 buf = available_versions_init((*pconn)->vneg.available_versions,
1463 settings->preferred_versions,
1464 settings->preferred_versionslen);
1465 } else {
1466 (*pconn)->vneg.available_versions = server_default_available_versions;
1467 (*pconn)->vneg.available_versionslen =
1468 sizeof(server_default_available_versions);
1469 }
1470 } else if (!ngtcp2_is_reserved_version(client_chosen_version)) {
1471 (*pconn)->vneg.available_versions = buf_align(buf);
1472 (*pconn)->vneg.available_versionslen = sizeof(uint32_t);
1473
1474 buf = available_versions_init((*pconn)->vneg.available_versions,
1475 &client_chosen_version, 1);
1476 }
1477
1478 (*pconn)->local.settings.available_versions = NULL;
1479 (*pconn)->local.settings.available_versionslen = 0;
1480
1481 (*pconn)->client_chosen_version = client_chosen_version;
1482
1483 conn_set_local_transport_params(*pconn, params);
1484
1485 callbacks->rand(&fixed_bit_byte, 1, &settings->rand_ctx);
1486 if (fixed_bit_byte & 1) {
1487 (*pconn)->flags |= NGTCP2_CONN_FLAG_CLEAR_FIXED_BIT;
1488 }
1489
1490 (*pconn)->keep_alive.last_ts = UINT64_MAX;
1491 (*pconn)->keep_alive.timeout = UINT64_MAX;
1492
1493 (*pconn)->oscid = *scid;
1494 (*pconn)->mem = mem;
1495 (*pconn)->user_data = user_data;
1496 (*pconn)->idle_ts = settings->initial_ts;
1497 (*pconn)->handshake_confirmed_ts = UINT64_MAX;
1498 (*pconn)->crypto.key_update.confirmed_ts = UINT64_MAX;
1499 (*pconn)->tx.last_max_data_ts = UINT64_MAX;
1500 (*pconn)->tx.pacing.next_ts = UINT64_MAX;
1501 (*pconn)->tx.last_blocked_offset = UINT64_MAX;
1502 (*pconn)->rx.preferred_addr.pkt_num = -1;
1503 (*pconn)->early.discard_started_ts = UINT64_MAX;
1504
1505 conn_reset_ecn_validation_state(*pconn);
1506
1507 ngtcp2_qlog_start(&(*pconn)->qlog,
1508 server
1509 ? ((*pconn)->local.transport_params.retry_scid_present
1510 ? &(*pconn)->local.transport_params.retry_scid
1511 : &(*pconn)->local.transport_params.original_dcid)
1512 : dcid,
1513 server);
1514
1515 return 0;
1516
1517 fail_scid_set_insert:
1518 ngtcp2_mem_free(mem, scident);
1519 fail_scident:
1520 pktns_del((*pconn)->hs_pktns, mem);
1521 fail_hs_pktns_init:
1522 pktns_del((*pconn)->in_pktns, mem);
1523 fail_in_pktns_init:
1524 ngtcp2_gaptr_free(&(*pconn)->dcid.seqgap);
1525 fail_seqgap_push:
1526 ngtcp2_mem_free(mem, (uint8_t *)(*pconn)->local.settings.token);
1527 fail_token:
1528 ngtcp2_mem_free(mem, *pconn);
1529
1530 *pconn = NULL;
1531
1532 return rv;
1533 }
1534
1535 int ngtcp2_conn_client_new_versioned(
1536 ngtcp2_conn **pconn, const ngtcp2_cid *dcid, const ngtcp2_cid *scid,
1537 const ngtcp2_path *path, uint32_t client_chosen_version,
1538 int callbacks_version, const ngtcp2_callbacks *callbacks,
1539 int settings_version, const ngtcp2_settings *settings,
1540 int transport_params_version, const ngtcp2_transport_params *params,
1541 const ngtcp2_mem *mem, void *user_data) {
1542 int rv;
1543
1544 rv = conn_new(pconn, dcid, scid, path, client_chosen_version,
1545 callbacks_version, callbacks, settings_version, settings,
1546 transport_params_version, params, mem, user_data, 0);
1547 if (rv != 0) {
1548 return rv;
1549 }
1550 (*pconn)->rcid = *dcid;
1551 (*pconn)->state = NGTCP2_CS_CLIENT_INITIAL;
1552 (*pconn)->local.bidi.next_stream_id = 0;
1553 (*pconn)->local.uni.next_stream_id = 2;
1554 (*pconn)->flags |= NGTCP2_CONN_FLAG_CRUMBLE_INITIAL_CRYPTO;
1555
1556 rv = ngtcp2_conn_commit_local_transport_params(*pconn);
1557 if (rv != 0) {
1558 ngtcp2_conn_del(*pconn);
1559 *pconn = NULL;
1560
1561 return rv;
1562 }
1563
1564 return 0;
1565 }
1566
1567 int ngtcp2_conn_server_new_versioned(
1568 ngtcp2_conn **pconn, const ngtcp2_cid *dcid, const ngtcp2_cid *scid,
1569 const ngtcp2_path *path, uint32_t client_chosen_version,
1570 int callbacks_version, const ngtcp2_callbacks *callbacks,
1571 int settings_version, const ngtcp2_settings *settings,
1572 int transport_params_version, const ngtcp2_transport_params *params,
1573 const ngtcp2_mem *mem, void *user_data) {
1574 int rv;
1575
1576 rv = conn_new(pconn, dcid, scid, path, client_chosen_version,
1577 callbacks_version, callbacks, settings_version, settings,
1578 transport_params_version, params, mem, user_data, 1);
1579 if (rv != 0) {
1580 return rv;
1581 }
1582
1583 (*pconn)->state = NGTCP2_CS_SERVER_INITIAL;
1584 (*pconn)->local.bidi.next_stream_id = 1;
1585 (*pconn)->local.uni.next_stream_id = 3;
1586
1587 if ((*pconn)->local.settings.tokenlen) {
1588 /* Usage of token lifts amplification limit */
1589 (*pconn)->dcid.current.flags |= NGTCP2_DCID_FLAG_PATH_VALIDATED;
1590 }
1591
1592 return 0;
1593 }
1594
1595 /*
1596 * conn_fc_credits returns the number of bytes allowed to be sent to
1597 * the given stream. Both connection and stream level flow control
1598 * credits are considered.
1599 */
1600 static uint64_t conn_fc_credits(ngtcp2_conn *conn, ngtcp2_strm *strm) {
1601 return ngtcp2_min_uint64(strm->tx.max_offset - strm->tx.offset,
1602 conn->tx.max_offset - conn->tx.offset);
1603 }
1604
1605 /*
1606 * conn_enforce_flow_control returns the number of bytes allowed to be
1607 * sent to the given stream. |len| might be shorted because of
1608 * available flow control credits.
1609 */
1610 static uint64_t conn_enforce_flow_control(ngtcp2_conn *conn, ngtcp2_strm *strm,
1611 uint64_t len) {
1612 uint64_t fc_credits = conn_fc_credits(conn, strm);
1613 return ngtcp2_min_uint64(len, fc_credits);
1614 }
1615
1616 static int delete_strms_each(void *data, void *ptr) {
1617 ngtcp2_conn *conn = ptr;
1618 ngtcp2_strm *s = data;
1619
1620 ngtcp2_strm_free(s);
1621 ngtcp2_objalloc_strm_release(&conn->strm_objalloc, s);
1622
1623 return 0;
1624 }
1625
1626 static void conn_vneg_crypto_free(ngtcp2_conn *conn) {
1627 if (conn->vneg.rx.ckm) {
1628 conn_call_delete_crypto_aead_ctx(conn, &conn->vneg.rx.ckm->aead_ctx);
1629 }
1630 conn_call_delete_crypto_cipher_ctx(conn, &conn->vneg.rx.hp_ctx);
1631
1632 if (conn->vneg.tx.ckm) {
1633 conn_call_delete_crypto_aead_ctx(conn, &conn->vneg.tx.ckm->aead_ctx);
1634 }
1635 conn_call_delete_crypto_cipher_ctx(conn, &conn->vneg.tx.hp_ctx);
1636
1637 ngtcp2_crypto_km_del(conn->vneg.rx.ckm, conn->mem);
1638 ngtcp2_crypto_km_del(conn->vneg.tx.ckm, conn->mem);
1639 }
1640
1641 void ngtcp2_conn_del(ngtcp2_conn *conn) {
1642 if (conn == NULL) {
1643 return;
1644 }
1645
1646 ngtcp2_qlog_end(&conn->qlog);
1647
1648 if (conn->early.ckm) {
1649 conn_call_delete_crypto_aead_ctx(conn, &conn->early.ckm->aead_ctx);
1650 }
1651 conn_call_delete_crypto_cipher_ctx(conn, &conn->early.hp_ctx);
1652
1653 if (conn->crypto.key_update.old_rx_ckm) {
1654 conn_call_delete_crypto_aead_ctx(
1655 conn, &conn->crypto.key_update.old_rx_ckm->aead_ctx);
1656 }
1657 if (conn->crypto.key_update.new_rx_ckm) {
1658 conn_call_delete_crypto_aead_ctx(
1659 conn, &conn->crypto.key_update.new_rx_ckm->aead_ctx);
1660 }
1661 if (conn->crypto.key_update.new_tx_ckm) {
1662 conn_call_delete_crypto_aead_ctx(
1663 conn, &conn->crypto.key_update.new_tx_ckm->aead_ctx);
1664 }
1665
1666 if (conn->pktns.crypto.rx.ckm) {
1667 conn_call_delete_crypto_aead_ctx(conn,
1668 &conn->pktns.crypto.rx.ckm->aead_ctx);
1669 }
1670 conn_call_delete_crypto_cipher_ctx(conn, &conn->pktns.crypto.rx.hp_ctx);
1671
1672 if (conn->pktns.crypto.tx.ckm) {
1673 conn_call_delete_crypto_aead_ctx(conn,
1674 &conn->pktns.crypto.tx.ckm->aead_ctx);
1675 }
1676 conn_call_delete_crypto_cipher_ctx(conn, &conn->pktns.crypto.tx.hp_ctx);
1677
1678 if (conn->hs_pktns) {
1679 if (conn->hs_pktns->crypto.rx.ckm) {
1680 conn_call_delete_crypto_aead_ctx(
1681 conn, &conn->hs_pktns->crypto.rx.ckm->aead_ctx);
1682 }
1683 conn_call_delete_crypto_cipher_ctx(conn, &conn->hs_pktns->crypto.rx.hp_ctx);
1684
1685 if (conn->hs_pktns->crypto.tx.ckm) {
1686 conn_call_delete_crypto_aead_ctx(
1687 conn, &conn->hs_pktns->crypto.tx.ckm->aead_ctx);
1688 }
1689 conn_call_delete_crypto_cipher_ctx(conn, &conn->hs_pktns->crypto.tx.hp_ctx);
1690 }
1691 if (conn->in_pktns) {
1692 if (conn->in_pktns->crypto.rx.ckm) {
1693 conn_call_delete_crypto_aead_ctx(
1694 conn, &conn->in_pktns->crypto.rx.ckm->aead_ctx);
1695 }
1696 conn_call_delete_crypto_cipher_ctx(conn, &conn->in_pktns->crypto.rx.hp_ctx);
1697
1698 if (conn->in_pktns->crypto.tx.ckm) {
1699 conn_call_delete_crypto_aead_ctx(
1700 conn, &conn->in_pktns->crypto.tx.ckm->aead_ctx);
1701 }
1702 conn_call_delete_crypto_cipher_ctx(conn, &conn->in_pktns->crypto.tx.hp_ctx);
1703 }
1704
1705 conn_call_delete_crypto_aead_ctx(conn, &conn->crypto.retry_aead_ctx);
1706
1707 ngtcp2_transport_params_del(conn->remote.transport_params, conn->mem);
1708 ngtcp2_transport_params_del(conn->remote.pending_transport_params, conn->mem);
1709
1710 conn_vneg_crypto_free(conn);
1711
1712 ngtcp2_mem_free(conn->mem, conn->crypto.decrypt_buf.base);
1713 ngtcp2_mem_free(conn->mem, conn->crypto.decrypt_hp_buf.base);
1714 ngtcp2_mem_free(conn->mem, (uint8_t *)conn->local.settings.token);
1715
1716 ngtcp2_crypto_km_del(conn->crypto.key_update.old_rx_ckm, conn->mem);
1717 ngtcp2_crypto_km_del(conn->crypto.key_update.new_rx_ckm, conn->mem);
1718 ngtcp2_crypto_km_del(conn->crypto.key_update.new_tx_ckm, conn->mem);
1719 ngtcp2_crypto_km_del(conn->early.ckm, conn->mem);
1720
1721 pktns_free(&conn->pktns, conn->mem);
1722 pktns_del(conn->hs_pktns, conn->mem);
1723 pktns_del(conn->in_pktns, conn->mem);
1724
1725 ngtcp2_pmtud_del(conn->pmtud);
1726 ngtcp2_pv_del(conn->pv);
1727
1728 ngtcp2_mem_free(conn->mem, (uint8_t *)conn->rx.ccerr.reason);
1729
1730 ngtcp2_idtr_free(&conn->remote.uni.idtr);
1731 ngtcp2_idtr_free(&conn->remote.bidi.idtr);
1732 ngtcp2_pq_free(&conn->tx.strmq);
1733 ngtcp2_map_each(&conn->strms, delete_strms_each, (void *)conn);
1734 ngtcp2_map_free(&conn->strms);
1735
1736 ngtcp2_pq_free(&conn->scid.used);
1737 delete_scid(&conn->scid.set, conn->mem);
1738 ngtcp2_ksl_free(&conn->scid.set);
1739 ngtcp2_gaptr_free(&conn->dcid.seqgap);
1740
1741 ngtcp2_objalloc_free(&conn->strm_objalloc);
1742 ngtcp2_objalloc_free(&conn->rtb_entry_objalloc);
1743 ngtcp2_objalloc_free(&conn->frc_objalloc);
1744
1745 ngtcp2_mem_free(conn->mem, conn);
1746 }
1747
1748 /*
1749 * conn_compute_ack_delay computes ACK delay for outgoing protected
1750 * ACK.
1751 */
1752 static ngtcp2_duration conn_compute_ack_delay(ngtcp2_conn *conn) {
1753 return ngtcp2_min_uint64(
1754 conn->local.transport_params.max_ack_delay,
1755 ngtcp2_max_uint64(conn->cstat.smoothed_rtt / 8, NGTCP2_NANOSECONDS));
1756 }
1757
1758 /*
1759 * conn_ppe_write_frame writes |fr| to |ppe|. If |hd_logged| is not
1760 * NULL and |*hd_logged| is zero, packet header is logged, and 1 is
1761 * assigned to |*hd_logged|.
1762 *
1763 * This function returns 0 if it succeeds, or one of the following
1764 * negative error codes:
1765 *
1766 * NGTCP2_ERR_NOBUF
1767 * Buffer is too small.
1768 */
1769 static int conn_ppe_write_frame_hd_log(ngtcp2_conn *conn, ngtcp2_ppe *ppe,
1770 int *hd_logged, const ngtcp2_pkt_hd *hd,
1771 ngtcp2_frame *fr) {
1772 int rv;
1773
1774 rv = ngtcp2_ppe_encode_frame(ppe, fr);
1775 if (rv != 0) {
1776 assert(NGTCP2_ERR_NOBUF == rv);
1777 return rv;
1778 }
1779
1780 if (hd_logged && !*hd_logged) {
1781 *hd_logged = 1;
1782 ngtcp2_log_tx_pkt_hd(&conn->log, hd);
1783 ngtcp2_qlog_pkt_sent_start(&conn->qlog);
1784 }
1785
1786 ngtcp2_log_tx_fr(&conn->log, hd, fr);
1787 ngtcp2_qlog_write_frame(&conn->qlog, fr);
1788
1789 return 0;
1790 }
1791
1792 /*
1793 * conn_ppe_write_frame writes |fr| to |ppe|.
1794 *
1795 * This function returns 0 if it succeeds, or one of the following
1796 * negative error codes:
1797 *
1798 * NGTCP2_ERR_NOBUF
1799 * Buffer is too small.
1800 */
1801 static int conn_ppe_write_frame(ngtcp2_conn *conn, ngtcp2_ppe *ppe,
1802 const ngtcp2_pkt_hd *hd, ngtcp2_frame *fr) {
1803 return conn_ppe_write_frame_hd_log(conn, ppe, NULL, hd, fr);
1804 }
1805
1806 /*
1807 * conn_on_pkt_sent is called when new non-ACK-only packet is sent.
1808 *
1809 * This function returns 0 if it succeeds, or one of the following
1810 * negative error codes:
1811 *
1812 * NGTCP2_ERR_NOMEM
1813 * Out of memory
1814 */
1815 static int conn_on_pkt_sent(ngtcp2_conn *conn, ngtcp2_pktns *pktns,
1816 ngtcp2_rtb_entry *ent) {
1817 ngtcp2_rtb *rtb = &pktns->rtb;
1818 ngtcp2_cc_pkt cc_pkt;
1819 int rv;
1820
1821 if ((ent->flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) &&
1822 conn->cc.on_pkt_sent) {
1823 conn->cc.on_pkt_sent(
1824 &conn->cc, &conn->cstat,
1825 ngtcp2_cc_pkt_init(&cc_pkt, ent->hd.pkt_num, ent->pktlen, pktns->id,
1826 ent->ts, /* lost = */ 0,
1827 /* tx_in_flight = */ 0, /* is_app_limited = */ 0));
1828 }
1829
1830 /* This function implements OnPacketSent, but it handles only
1831 non-ACK-only packet. */
1832 rv = ngtcp2_rtb_add(rtb, ent, &conn->cstat);
1833 if (rv != 0) {
1834 return rv;
1835 }
1836
1837 if (ent->flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) {
1838 conn->cstat.last_tx_pkt_ts[pktns->id] = ent->ts;
1839 }
1840
1841 ngtcp2_conn_set_loss_detection_timer(conn, ent->ts);
1842
1843 return 0;
1844 }
1845
1846 /*
1847 * pktns_select_pkt_numlen selects shortest packet number encoding for
1848 * the next packet number based on the largest acknowledged packet
1849 * number. It returns the number of bytes to encode the packet
1850 * number.
1851 */
1852 static size_t pktns_select_pkt_numlen(ngtcp2_pktns *pktns) {
1853 int64_t pkt_num = pktns->tx.last_pkt_num + 1;
1854 ngtcp2_rtb *rtb = &pktns->rtb;
1855 int64_t n = pkt_num - rtb->largest_acked_tx_pkt_num;
1856
1857 if (NGTCP2_MAX_PKT_NUM / 2 < n) {
1858 return 4;
1859 }
1860
1861 n = n * 2 - 1;
1862
1863 if (n > 0xffffff) {
1864 return 4;
1865 }
1866 if (n > 0xffff) {
1867 return 3;
1868 }
1869 if (n > 0xff) {
1870 return 2;
1871 }
1872 return 1;
1873 }
1874
1875 /*
1876 * conn_cwnd_is_zero returns nonzero if the number of bytes the local
1877 * endpoint can sent at this time is zero.
1878 */
1879 static int conn_cwnd_is_zero(ngtcp2_conn *conn) {
1880 uint64_t bytes_in_flight = conn->cstat.bytes_in_flight;
1881 uint64_t cwnd = conn->cstat.cwnd;
1882
1883 if (bytes_in_flight >= cwnd) {
1884 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_LDC,
1885 "cwnd limited bytes_in_flight=%lu cwnd=%lu",
1886 bytes_in_flight, cwnd);
1887 }
1888
1889 return bytes_in_flight >= cwnd;
1890 }
1891
1892 /*
1893 * conn_retry_early_payloadlen returns the estimated wire length of
1894 * the first STREAM frame of 0-RTT packet which should be
1895 * retransmitted due to Retry packet.
1896 */
1897 static uint64_t conn_retry_early_payloadlen(ngtcp2_conn *conn) {
1898 ngtcp2_frame_chain *frc;
1899 ngtcp2_strm *strm;
1900 uint64_t len;
1901
1902 if (conn->flags & NGTCP2_CONN_FLAG_EARLY_DATA_REJECTED) {
1903 return 0;
1904 }
1905
1906 for (; !ngtcp2_pq_empty(&conn->tx.strmq);) {
1907 strm = ngtcp2_conn_tx_strmq_top(conn);
1908 if (ngtcp2_strm_streamfrq_empty(strm)) {
1909 ngtcp2_conn_tx_strmq_pop(conn);
1910 continue;
1911 }
1912
1913 frc = ngtcp2_strm_streamfrq_top(strm);
1914
1915 len = ngtcp2_vec_len(frc->fr.stream.data, frc->fr.stream.datacnt) +
1916 NGTCP2_STREAM_OVERHEAD;
1917
1918 /* Take the min because in conn_should_pad_pkt we take max in
1919 order to deal with unbreakable DATAGRAM. */
1920 return ngtcp2_min_uint64(len, NGTCP2_MIN_COALESCED_PAYLOADLEN);
1921 }
1922
1923 return 0;
1924 }
1925
1926 /*
1927 * conn_verify_dcid verifies that destination connection ID in |hd| is
1928 * valid for the connection. If it is successfully verified and the
1929 * remote endpoint uses new DCID in the packet, nonzero value is
1930 * assigned to |*pnew_cid_used| if it is not NULL. Otherwise 0 is
1931 * assigned to it.
1932 *
1933 * This function returns 0 if it succeeds, or one of the following
1934 * negative error codes:
1935 *
1936 * NGTCP2_ERR_NOMEM
1937 * Out of memory.
1938 * NGTCP2_ERR_INVALID_ARGUMENT
1939 * |dcid| is not known to the local endpoint.
1940 */
1941 static int conn_verify_dcid(ngtcp2_conn *conn, int *pnew_cid_used,
1942 const ngtcp2_pkt_hd *hd) {
1943 ngtcp2_ksl_it it;
1944 ngtcp2_scid *scid;
1945 int rv;
1946
1947 it = ngtcp2_ksl_lower_bound(&conn->scid.set, &hd->dcid);
1948 if (ngtcp2_ksl_it_end(&it)) {
1949 return NGTCP2_ERR_INVALID_ARGUMENT;
1950 }
1951
1952 scid = ngtcp2_ksl_it_get(&it);
1953 if (!ngtcp2_cid_eq(&scid->cid, &hd->dcid)) {
1954 return NGTCP2_ERR_INVALID_ARGUMENT;
1955 }
1956
1957 if (!(scid->flags & NGTCP2_SCID_FLAG_USED)) {
1958 scid->flags |= NGTCP2_SCID_FLAG_USED;
1959
1960 if (scid->pe.index == NGTCP2_PQ_BAD_INDEX) {
1961 rv = ngtcp2_pq_push(&conn->scid.used, &scid->pe);
1962 if (rv != 0) {
1963 return rv;
1964 }
1965 }
1966
1967 if (pnew_cid_used) {
1968 *pnew_cid_used = 1;
1969 }
1970 } else if (pnew_cid_used) {
1971 *pnew_cid_used = 0;
1972 }
1973
1974 return 0;
1975 }
1976
1977 /*
1978 * conn_should_pad_pkt returns nonzero if the packet should be padded.
1979 * |type| is the type of packet. |left| is the space left in packet
1980 * buffer. |write_datalen| is the number of bytes which will be sent
1981 * in the next, coalesced 0-RTT packet.
1982 */
1983 static int conn_should_pad_pkt(ngtcp2_conn *conn, uint8_t type, size_t left,
1984 uint64_t write_datalen, int ack_eliciting,
1985 int require_padding) {
1986 uint64_t min_payloadlen;
1987
1988 if (type == NGTCP2_PKT_INITIAL) {
1989 if (conn->server) {
1990 if (!ack_eliciting) {
1991 return 0;
1992 }
1993
1994 if ((conn->hs_pktns->crypto.tx.ckm &&
1995 (conn->hs_pktns->rtb.probe_pkt_left ||
1996 !ngtcp2_strm_streamfrq_empty(&conn->hs_pktns->crypto.strm) ||
1997 !ngtcp2_acktr_empty(&conn->hs_pktns->acktr))) ||
1998 conn->pktns.crypto.tx.ckm) {
1999 /* If we have something to send in Handshake or 1RTT packet,
2000 then add PADDING in that packet. */
2001 min_payloadlen = NGTCP2_MIN_COALESCED_PAYLOADLEN;
2002 } else {
2003 return 1;
2004 }
2005 } else {
2006 if (conn->hs_pktns->crypto.tx.ckm &&
2007 (conn->hs_pktns->rtb.probe_pkt_left ||
2008 !ngtcp2_strm_streamfrq_empty(&conn->hs_pktns->crypto.strm) ||
2009 !ngtcp2_acktr_empty(&conn->hs_pktns->acktr))) {
2010 /* If we have something to send in Handshake packet, then add
2011 PADDING in Handshake packet. */
2012 min_payloadlen = NGTCP2_MIN_COALESCED_PAYLOADLEN;
2013 } else if (conn->early.ckm && write_datalen > 0) {
2014 /* If we have something to send in 0RTT packet, then add
2015 PADDING in that packet. Take maximum in case that
2016 write_datalen includes DATAGRAM which cannot be split. */
2017 min_payloadlen =
2018 ngtcp2_max_uint64(write_datalen, NGTCP2_MIN_COALESCED_PAYLOADLEN);
2019 } else {
2020 return 1;
2021 }
2022 }
2023 } else {
2024 assert(type == NGTCP2_PKT_HANDSHAKE);
2025
2026 if (!require_padding) {
2027 return 0;
2028 }
2029
2030 if (!conn->pktns.crypto.tx.ckm) {
2031 return 1;
2032 }
2033
2034 /* We might send Handshake packet even if exceeding CWND. In that
2035 case, we do not write non-probe 1RTT packet. */
2036 if (conn_cwnd_is_zero(conn) && conn->pktns.rtb.probe_pkt_left == 0) {
2037 return 1;
2038 }
2039
2040 min_payloadlen = NGTCP2_MIN_COALESCED_PAYLOADLEN;
2041 }
2042
2043 /* TODO the next packet type should be taken into account */
2044 return left <
2045 /* TODO Assuming that pkt_num is encoded in 1 byte. */
2046 NGTCP2_MIN_LONG_HEADERLEN + conn->dcid.current.cid.datalen +
2047 conn->oscid.datalen + NGTCP2_PKT_LENGTHLEN - 1 + min_payloadlen +
2048 NGTCP2_MAX_AEAD_OVERHEAD;
2049 }
2050
2051 static void conn_restart_timer_on_write(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
2052 conn->idle_ts = ts;
2053 conn->flags &= (uint32_t)~NGTCP2_CONN_FLAG_RESTART_IDLE_TIMER_ON_WRITE;
2054 }
2055
2056 static void conn_restart_timer_on_read(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
2057 conn->idle_ts = ts;
2058 conn->flags |= NGTCP2_CONN_FLAG_RESTART_IDLE_TIMER_ON_WRITE;
2059 }
2060
2061 /*
2062 * conn_keep_alive_enabled returns nonzero if keep-alive is enabled.
2063 */
2064 static int conn_keep_alive_enabled(ngtcp2_conn *conn) {
2065 return conn->keep_alive.last_ts != UINT64_MAX &&
2066 conn->keep_alive.timeout != UINT64_MAX;
2067 }
2068
2069 /*
2070 * conn_keep_alive_expired returns nonzero if keep-alive timer has
2071 * expired.
2072 */
2073 static int conn_keep_alive_expired(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
2074 return ngtcp2_tstamp_elapsed(conn->keep_alive.last_ts,
2075 conn->keep_alive.timeout, ts);
2076 }
2077
2078 /*
2079 * conn_keep_alive_expiry returns the expiry time of keep-alive timer.
2080 */
2081 static ngtcp2_tstamp conn_keep_alive_expiry(ngtcp2_conn *conn) {
2082 if ((conn->flags & NGTCP2_CONN_FLAG_KEEP_ALIVE_CANCELLED) ||
2083 !(conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_COMPLETED) ||
2084 !conn_keep_alive_enabled(conn) ||
2085 conn->keep_alive.last_ts >= UINT64_MAX - conn->keep_alive.timeout) {
2086 return UINT64_MAX;
2087 }
2088
2089 return conn->keep_alive.last_ts + conn->keep_alive.timeout;
2090 }
2091
2092 /*
2093 * conn_cancel_expired_keep_alive_timer cancels the expired keep-alive
2094 * timer.
2095 */
2096 static void conn_cancel_expired_keep_alive_timer(ngtcp2_conn *conn,
2097 ngtcp2_tstamp ts) {
2098 if (!(conn->flags & NGTCP2_CONN_FLAG_KEEP_ALIVE_CANCELLED) &&
2099 conn_keep_alive_expired(conn, ts)) {
2100 conn->flags |= NGTCP2_CONN_FLAG_KEEP_ALIVE_CANCELLED;
2101 }
2102 }
2103
2104 /*
2105 * conn_update_keep_alive_last_ts updates the base time point of
2106 * keep-alive timer.
2107 */
2108 static void conn_update_keep_alive_last_ts(ngtcp2_conn *conn,
2109 ngtcp2_tstamp ts) {
2110 conn->keep_alive.last_ts = ts;
2111 conn->flags &= (uint32_t)~NGTCP2_CONN_FLAG_KEEP_ALIVE_CANCELLED;
2112 }
2113
2114 void ngtcp2_conn_set_keep_alive_timeout(ngtcp2_conn *conn,
2115 ngtcp2_duration timeout) {
2116 if (timeout == 0) {
2117 timeout = UINT64_MAX;
2118 }
2119
2120 conn->keep_alive.timeout = timeout;
2121 }
2122
2123 static void conn_cancel_expired_pkt_tx_timer(ngtcp2_conn *conn,
2124 ngtcp2_tstamp ts) {
2125 if (conn->tx.pacing.next_ts == UINT64_MAX) {
2126 return;
2127 }
2128
2129 if (conn->tx.pacing.next_ts > ts) {
2130 return;
2131 }
2132
2133 if (ts > conn->tx.pacing.next_ts) {
2134 conn->tx.pacing.compensation += ts - conn->tx.pacing.next_ts;
2135 }
2136
2137 conn->tx.pacing.next_ts = UINT64_MAX;
2138 }
2139
2140 static int conn_pacing_pkt_tx_allowed(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
2141 if (conn->tx.pacing.next_ts == UINT64_MAX) {
2142 return 1;
2143 }
2144
2145 if (conn->tx.pacing.next_ts > ts) {
2146 return 0;
2147 }
2148
2149 conn->tx.pacing.compensation += ts - conn->tx.pacing.next_ts;
2150 conn->tx.pacing.next_ts = UINT64_MAX;
2151
2152 return 1;
2153 }
2154
2155 static uint8_t conn_pkt_flags(ngtcp2_conn *conn) {
2156 if (conn->remote.transport_params &&
2157 conn->remote.transport_params->grease_quic_bit &&
2158 (conn->flags & NGTCP2_CONN_FLAG_CLEAR_FIXED_BIT)) {
2159 return NGTCP2_PKT_FLAG_FIXED_BIT_CLEAR;
2160 }
2161
2162 return NGTCP2_PKT_FLAG_NONE;
2163 }
2164
2165 static uint8_t conn_pkt_flags_long(ngtcp2_conn *conn) {
2166 return NGTCP2_PKT_FLAG_LONG_FORM | conn_pkt_flags(conn);
2167 }
2168
2169 static uint8_t conn_pkt_flags_short(ngtcp2_conn *conn) {
2170 return (uint8_t)(conn_pkt_flags(conn) | ((conn->pktns.crypto.tx.ckm->flags &
2171 NGTCP2_CRYPTO_KM_FLAG_KEY_PHASE_ONE)
2172 ? NGTCP2_PKT_FLAG_KEY_PHASE
2173 : NGTCP2_PKT_FLAG_NONE));
2174 }
2175
2176 /*
2177 * conn_cut_crypto_frame splits frc->fr.stream by removing
2178 * |removed_data| from frc->fr.stream.data[0]. frc->fr.stream.data[0]
2179 * must contain |removed_data|, and frc->fr.stream.datacnt >= 1. New
2180 * ngtcp2_frame_chain object that contains |removed_data| is created,
2181 * and pushed to |crypto_strm| via ngtcp2_strm_streamfrq_push. If
2182 * there are data following the removed part of data, new
2183 * ngtcp2_frame_chain object is created for it, and frc->next points
2184 * to the object.
2185 *
2186 * This function returns 0 if it succeeds, or one of the following
2187 * negative error codes:
2188 *
2189 * NGTCP2_ERR_NOMEM
2190 * Out of memory
2191 */
2192 static int conn_cut_crypto_frame(ngtcp2_conn *conn, ngtcp2_frame_chain *frc,
2193 ngtcp2_strm *crypto_strm,
2194 const ngtcp2_vec *removed_data) {
2195 ngtcp2_vec *data = frc->fr.stream.data;
2196 size_t datacnt = frc->fr.stream.datacnt;
2197 size_t ndatacnt;
2198 ngtcp2_frame_chain *right_frc = NULL, *removed_frc;
2199 size_t offset;
2200 int rv;
2201
2202 assert(datacnt);
2203 assert(data[0].base < removed_data->base);
2204 assert(ngtcp2_vec_end(removed_data) <= ngtcp2_vec_end(&data[0]));
2205
2206 offset = (size_t)(removed_data->base - data->base);
2207
2208 rv = ngtcp2_frame_chain_stream_datacnt_objalloc_new(
2209 &removed_frc, 1, &conn->frc_objalloc, conn->mem);
2210 if (rv != 0) {
2211 return rv;
2212 }
2213
2214 /* ngtcp2_frame_chain for the removed data */
2215 removed_frc->fr.stream.type = NGTCP2_FRAME_CRYPTO;
2216 removed_frc->fr.stream.flags = 0;
2217 removed_frc->fr.stream.fin = 0;
2218 removed_frc->fr.stream.stream_id = 0;
2219 removed_frc->fr.stream.offset = frc->fr.stream.offset + offset;
2220 removed_frc->fr.stream.datacnt = 1;
2221 removed_frc->fr.stream.data[0] = (ngtcp2_vec){
2222 .base = data->base + offset,
2223 .len = removed_data->len,
2224 };
2225
2226 rv = ngtcp2_strm_streamfrq_push(crypto_strm, removed_frc);
2227 if (rv != 0) {
2228 ngtcp2_frame_chain_objalloc_del(removed_frc, &conn->frc_objalloc,
2229 conn->mem);
2230 return rv;
2231 }
2232
2233 if (data[0].len == offset + removed_data->len) {
2234 ndatacnt = datacnt - 1;
2235 } else {
2236 ndatacnt = datacnt;
2237 }
2238
2239 if (ndatacnt) {
2240 /* ngtcp2_frame_chain after the removed data */
2241 rv = ngtcp2_frame_chain_stream_datacnt_objalloc_new(
2242 &right_frc, ndatacnt, &conn->frc_objalloc, conn->mem);
2243 if (rv != 0) {
2244 return rv;
2245 }
2246
2247 right_frc->fr.stream.type = NGTCP2_FRAME_CRYPTO;
2248 right_frc->fr.stream.offset =
2249 removed_frc->fr.stream.offset + removed_frc->fr.stream.data->len;
2250 right_frc->fr.stream.datacnt = 0;
2251 ngtcp2_vec_split(right_frc->fr.stream.data, &right_frc->fr.stream.datacnt,
2252 data, &datacnt, offset + removed_data->len, ndatacnt);
2253
2254 assert(ndatacnt == right_frc->fr.stream.datacnt);
2255 assert(1 == datacnt);
2256 }
2257
2258 frc->fr.stream.datacnt = 1;
2259 frc->fr.stream.data[0].len = offset;
2260 frc->next = right_frc;
2261
2262 return 0;
2263 }
2264
2265 /*
2266 * conn_crumble_initial_crypto splits CRYPTO frame (*pfrc)->fr.stream
2267 * into pieces and adds PADDING and PING frames, and reorder those
2268 * frames. Those frames are encoded in the buffer pointed by |data|
2269 * and |offsets|. |data| is the pointer to the array of ngtcp2_vec of
2270 * at least NGTCP2_MAX_STREAM_DATACNT. |offsets| contains the CRYPTO
2271 * offset of the corresponding ngtcp2_vec in |data|, and it also
2272 * should have the capacity at least NGTCP2_MAX_STREAM_DATACNT
2273 * uint64_t. |left| is the number of bytes available for the current
2274 * packet. |crypto_offset| is the next smallest CRYPTO offset.
2275 * |crypto_strm| is the CRYPTO stream.
2276 *
2277 * This function returns the number of objects written to |data| and
2278 * |offsets|, or one of the following negative error codes:
2279 *
2280 * NGTCP2_ERR_NOMEM
2281 * Out of memory
2282 */
2283 static ngtcp2_ssize
2284 conn_crumble_initial_crypto(ngtcp2_conn *conn, ngtcp2_frame_chain **pfrc,
2285 ngtcp2_vec *data, uint64_t *offsets,
2286 ngtcp2_strm *crypto_strm, size_t left,
2287 uint64_t crypto_offset) {
2288 ngtcp2_vec server_name;
2289 ngtcp2_vec removed_data;
2290 size_t max_add_frames = 10;
2291 size_t single_crypto_overhead =
2292 1 + ngtcp2_put_uvarintlen(crypto_offset + left - 1) +
2293 ngtcp2_put_uvarintlen(left);
2294 size_t total_crypto_overhead = single_crypto_overhead * max_add_frames;
2295 size_t datacnt;
2296 size_t i;
2297 int rv;
2298
2299 if (left <= total_crypto_overhead) {
2300 return 0;
2301 }
2302
2303 left -= total_crypto_overhead;
2304
2305 left = ngtcp2_pkt_crypto_max_datalen(crypto_offset, left, left);
2306 if (left == (size_t)-1) {
2307 return 0;
2308 }
2309
2310 rv = ngtcp2_strm_streamfrq_pop(crypto_strm, pfrc, left);
2311 if (rv != 0) {
2312 assert(ngtcp2_err_is_fatal(rv));
2313 return rv;
2314 }
2315
2316 if (*pfrc == NULL) {
2317 return 0;
2318 }
2319
2320 assert(crypto_offset == (*pfrc)->fr.stream.offset);
2321
2322 ngtcp2_vec_copy(data, (*pfrc)->fr.stream.data, (*pfrc)->fr.stream.datacnt);
2323 datacnt = (*pfrc)->fr.stream.datacnt;
2324
2325 offsets[0] = (*pfrc)->fr.stream.offset;
2326
2327 for (i = 1; i < datacnt; ++i) {
2328 offsets[i] = offsets[i - 1] + data[i - 1].len;
2329 }
2330
2331 if (datacnt < NGTCP2_MAX_STREAM_DATACNT &&
2332 ngtcp2_pkt_find_server_name(&server_name, data) && server_name.len > 1) {
2333 if (ngtcp2_strm_streamfrq_empty(crypto_strm) ||
2334 ngtcp2_strm_streamfrq_unacked_offset(crypto_strm) == (uint64_t)-1) {
2335 datacnt = ngtcp2_pkt_split_vec_at(
2336 data, datacnt, offsets,
2337 (size_t)(server_name.base - data[0].base) + server_name.len / 2);
2338 } else {
2339 /* If we have another data to send (most likely in the another
2340 packet), remove the part of SNI from this packet. */
2341 datacnt = ngtcp2_pkt_remove_vec_partial(
2342 &removed_data, data, datacnt, offsets, &conn->pcg, &server_name);
2343
2344 rv = conn_cut_crypto_frame(conn, *pfrc, crypto_strm, &removed_data);
2345 if (rv != 0) {
2346 ngtcp2_frame_chain_objalloc_del(*pfrc, &conn->frc_objalloc, conn->mem);
2347 return rv;
2348 }
2349
2350 /* Add the length of removed data to total_crypto_overhead so
2351 that we can use them for inter CRYPTO frames padding. */
2352 total_crypto_overhead += removed_data.len;
2353 }
2354 }
2355
2356 if (datacnt < max_add_frames + 1) {
2357 max_add_frames -= datacnt - 1;
2358
2359 datacnt = ngtcp2_pkt_split_vec_rand(data, datacnt, offsets, &conn->pcg,
2360 max_add_frames);
2361 }
2362
2363 for (i = 1; i < datacnt; ++i) {
2364 total_crypto_overhead -= 1 + ngtcp2_put_uvarintlen(offsets[i]) +
2365 ngtcp2_put_uvarintlen(data[i].len);
2366 }
2367
2368 datacnt = ngtcp2_pkt_append_ping_and_padding(data, datacnt, &conn->pcg,
2369 total_crypto_overhead);
2370
2371 ngtcp2_pkt_permutate_vec(data, datacnt, offsets, &conn->pcg);
2372
2373 return (ngtcp2_ssize)datacnt;
2374 }
2375
2376 static size_t conn_dgram_padding(ngtcp2_conn *conn, ngtcp2_ppe *ppe) {
2377 if (conn->local.settings.no_tx_udp_payload_size_shaping) {
2378 return ngtcp2_ppe_dgram_padding_size(
2379 ppe, conn->local.settings.max_tx_udp_payload_size);
2380 }
2381
2382 return ngtcp2_ppe_dgram_padding(ppe);
2383 }
2384
2385 static size_t conn_min_pktlen(ngtcp2_conn *conn);
2386
2387 /*
2388 * conn_write_handshake_pkt writes handshake packet in the buffer
2389 * pointed by |dest| whose length is |destlen|. |dgram_offset| is the
2390 * offset in UDP datagram payload where this QUIC packet is positioned
2391 * at. |type| specifies long packet type. It should be either
2392 * NGTCP2_PKT_INITIAL or NGTCP2_PKT_HANDSHAKE_PKT.
2393 *
2394 * |write_datalen| is the minimum length of application data ready to
2395 * send in subsequent 0RTT packet.
2396 *
2397 * This function returns the number of bytes written in |dest| if it
2398 * succeeds, or one of the following negative error codes:
2399 *
2400 * NGTCP2_ERR_NOMEM
2401 * Out of memory.
2402 * NGTCP2_ERR_CALLBACK_FAILURE
2403 * User-defined callback function failed.
2404 */
2405 static ngtcp2_ssize
2406 conn_write_handshake_pkt(ngtcp2_conn *conn, ngtcp2_pkt_info *pi, uint8_t *dest,
2407 size_t destlen, size_t dgram_offset, uint8_t type,
2408 uint8_t flags, uint64_t write_datalen,
2409 ngtcp2_tstamp ts) {
2410 int rv;
2411 ngtcp2_ppe ppe;
2412 ngtcp2_pkt_hd hd;
2413 ngtcp2_frame_chain *frq = NULL, **pfrc = &frq;
2414 ngtcp2_frame_chain *nfrc;
2415 ngtcp2_ack_range ack_ranges[NGTCP2_MAX_ACK_RANGES];
2416 ngtcp2_frame lfr;
2417 ngtcp2_ssize spktlen;
2418 ngtcp2_crypto_cc cc;
2419 ngtcp2_rtb_entry *rtbent;
2420 ngtcp2_pktns *pktns;
2421 size_t left;
2422 uint16_t rtb_entry_flags = NGTCP2_RTB_ENTRY_FLAG_NONE;
2423 int require_padding = (flags & NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING) != 0;
2424 int pkt_empty = 1;
2425 int min_padded = 0;
2426 int padded = 0;
2427 int hd_logged = 0;
2428 uint64_t crypto_offset;
2429 ngtcp2_ssize num_reclaimed;
2430 uint32_t version;
2431
2432 switch (type) {
2433 case NGTCP2_PKT_INITIAL:
2434 if (!conn->in_pktns) {
2435 return 0;
2436 }
2437 assert(conn->in_pktns->crypto.tx.ckm);
2438 pktns = conn->in_pktns;
2439 version = conn->negotiated_version ? conn->negotiated_version
2440 : conn->client_chosen_version;
2441 if (version == conn->client_chosen_version) {
2442 cc.ckm = pktns->crypto.tx.ckm;
2443 cc.hp_ctx = pktns->crypto.tx.hp_ctx;
2444 } else {
2445 assert(conn->vneg.version == version);
2446
2447 cc.ckm = conn->vneg.tx.ckm;
2448 cc.hp_ctx = conn->vneg.tx.hp_ctx;
2449 }
2450 break;
2451 case NGTCP2_PKT_HANDSHAKE:
2452 if (!conn->hs_pktns || !conn->hs_pktns->crypto.tx.ckm) {
2453 return 0;
2454 }
2455 pktns = conn->hs_pktns;
2456 version = conn->negotiated_version;
2457 cc.ckm = pktns->crypto.tx.ckm;
2458 cc.hp_ctx = pktns->crypto.tx.hp_ctx;
2459 break;
2460 default:
2461 ngtcp2_unreachable();
2462 }
2463
2464 cc.aead = pktns->crypto.ctx.aead;
2465 cc.hp = pktns->crypto.ctx.hp;
2466 cc.encrypt = conn->callbacks.encrypt;
2467 cc.hp_mask = conn->callbacks.hp_mask;
2468
2469 ngtcp2_pkt_hd_init(
2470 &hd, conn_pkt_flags_long(conn), type, &conn->dcid.current.cid, &conn->oscid,
2471 pktns->tx.last_pkt_num + 1, pktns_select_pkt_numlen(pktns), version);
2472
2473 if (!conn->server && type == NGTCP2_PKT_INITIAL &&
2474 conn->local.settings.tokenlen) {
2475 hd.token = conn->local.settings.token;
2476 hd.tokenlen = conn->local.settings.tokenlen;
2477 }
2478
2479 ngtcp2_ppe_init(&ppe, dest, destlen, dgram_offset, &cc);
2480
2481 rv = ngtcp2_ppe_encode_hd(&ppe, &hd);
2482 if (rv != 0) {
2483 assert(NGTCP2_ERR_NOBUF == rv);
2484 return 0;
2485 }
2486
2487 if (!ngtcp2_ppe_ensure_hp_sample(&ppe)) {
2488 return 0;
2489 }
2490
2491 lfr.ack.ranges = ack_ranges;
2492 if (ngtcp2_acktr_create_ack_frame(&pktns->acktr, &lfr.ack, type, ts,
2493 /* ack_delay = */ 0,
2494 NGTCP2_DEFAULT_ACK_DELAY_EXPONENT) == 0) {
2495 rv = conn_ppe_write_frame_hd_log(conn, &ppe, &hd_logged, &hd, &lfr);
2496 if (rv != 0) {
2497 assert(NGTCP2_ERR_NOBUF == rv);
2498 } else {
2499 ngtcp2_acktr_commit_ack(&pktns->acktr);
2500 ngtcp2_acktr_add_ack(&pktns->acktr, hd.pkt_num, lfr.ack.largest_ack);
2501 pkt_empty = 0;
2502 }
2503 }
2504
2505 /* Server requires at least NGTCP2_MAX_UDP_PAYLOAD_SIZE bytes in
2506 order to send ack-eliciting Initial packet. */
2507 if (!conn->server || type != NGTCP2_PKT_INITIAL ||
2508 destlen >= NGTCP2_MAX_UDP_PAYLOAD_SIZE) {
2509 build_pkt:
2510 for (; !ngtcp2_strm_streamfrq_empty(&pktns->crypto.strm);) {
2511 crypto_offset = ngtcp2_strm_streamfrq_unacked_offset(&pktns->crypto.strm);
2512 if (crypto_offset == (uint64_t)-1) {
2513 ngtcp2_strm_streamfrq_clear(&pktns->crypto.strm);
2514 break;
2515 }
2516
2517 left = ngtcp2_ppe_left(&ppe);
2518 if (left == 0) {
2519 break;
2520 }
2521
2522 if (type == NGTCP2_PKT_INITIAL &&
2523 (conn->flags & NGTCP2_CONN_FLAG_CRUMBLE_INITIAL_CRYPTO)) {
2524 ngtcp2_vec data[NGTCP2_MAX_STREAM_DATACNT];
2525 uint64_t offsets[NGTCP2_MAX_STREAM_DATACNT];
2526 ngtcp2_ssize datacnt;
2527 size_t i;
2528
2529 datacnt = conn_crumble_initial_crypto(
2530 conn, &nfrc, data, offsets, &pktns->crypto.strm, left, crypto_offset);
2531 if (datacnt < 0) {
2532 assert(ngtcp2_err_is_fatal((int)datacnt));
2533 ngtcp2_frame_chain_list_objalloc_del(frq, &conn->frc_objalloc,
2534 conn->mem);
2535
2536 return datacnt;
2537 }
2538
2539 if (datacnt == 0) {
2540 break;
2541 }
2542
2543 for (i = 0; i < (size_t)datacnt; ++i) {
2544 if (data[i].base == NULL) {
2545 if (data[i].len == 0) {
2546 lfr.ping.type = NGTCP2_FRAME_PING;
2547 } else {
2548 lfr.padding = (ngtcp2_padding){
2549 .type = NGTCP2_FRAME_PADDING,
2550 .len = data[i].len,
2551 };
2552 }
2553 } else {
2554 lfr.stream = (ngtcp2_stream){
2555 .type = NGTCP2_FRAME_CRYPTO,
2556 .offset = offsets[i],
2557 .datacnt = 1,
2558 .data = &data[i],
2559 };
2560 }
2561
2562 rv = conn_ppe_write_frame_hd_log(conn, &ppe, &hd_logged, &hd, &lfr);
2563 if (rv != 0) {
2564 ngtcp2_unreachable();
2565 }
2566 }
2567 } else {
2568 left = ngtcp2_pkt_crypto_max_datalen(crypto_offset, left, left);
2569 if (left == (size_t)-1) {
2570 break;
2571 }
2572
2573 rv = ngtcp2_strm_streamfrq_pop(&pktns->crypto.strm, &nfrc, left);
2574 if (rv != 0) {
2575 assert(ngtcp2_err_is_fatal(rv));
2576 ngtcp2_frame_chain_list_objalloc_del(frq, &conn->frc_objalloc,
2577 conn->mem);
2578 return rv;
2579 }
2580
2581 if (nfrc == NULL) {
2582 break;
2583 }
2584
2585 rv =
2586 conn_ppe_write_frame_hd_log(conn, &ppe, &hd_logged, &hd, &nfrc->fr);
2587 if (rv != 0) {
2588 ngtcp2_unreachable();
2589 }
2590 }
2591
2592 *pfrc = nfrc;
2593
2594 for (; nfrc->next;) {
2595 nfrc = nfrc->next;
2596 }
2597
2598 pfrc = &nfrc->next;
2599
2600 pkt_empty = 0;
2601 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
2602 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
2603 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
2604 }
2605
2606 if (!(rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) &&
2607 pktns->rtb.num_retransmittable && pktns->rtb.probe_pkt_left) {
2608 num_reclaimed = ngtcp2_rtb_reclaim_on_pto(
2609 &pktns->rtb, conn, pktns,
2610 !conn->server && type == NGTCP2_PKT_INITIAL ? 2 : 1);
2611 if (num_reclaimed < 0) {
2612 ngtcp2_frame_chain_list_objalloc_del(frq, &conn->frc_objalloc,
2613 conn->mem);
2614 return num_reclaimed;
2615 }
2616 if (num_reclaimed) {
2617 goto build_pkt;
2618 }
2619 /* We had pktns->rtb.num_retransmittable > 0 but the contents of
2620 those packets have been acknowledged (i.e., retransmission in
2621 another packet). For server, in this case, we don't have to
2622 send any probe packet. Client needs to send probe packets
2623 until it knows that server has completed address
2624 validation. */
2625 if (pktns->rtb.num_pto_eliciting == 0 &&
2626 (conn->server ||
2627 (conn->flags & NGTCP2_CONN_FLAG_SERVER_ADDR_VERIFIED))) {
2628 pktns->rtb.probe_pkt_left = 0;
2629 ngtcp2_conn_set_loss_detection_timer(conn, ts);
2630 /* TODO If packet is empty, we should return now if cwnd is
2631 zero. */
2632 }
2633 }
2634
2635 if (!(rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) &&
2636 pktns->rtb.probe_pkt_left) {
2637 lfr.ping.type = NGTCP2_FRAME_PING;
2638
2639 rv = conn_ppe_write_frame_hd_log(conn, &ppe, &hd_logged, &hd, &lfr);
2640 if (rv != 0) {
2641 assert(rv == NGTCP2_ERR_NOBUF);
2642 } else {
2643 rtb_entry_flags |=
2644 NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING | NGTCP2_RTB_ENTRY_FLAG_PROBE;
2645 pkt_empty = 0;
2646 }
2647 }
2648
2649 if (!pkt_empty) {
2650 if (!(rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING)) {
2651 if (ngtcp2_tstamp_elapsed(pktns->tx.non_ack_pkt_start_ts,
2652 conn->cstat.smoothed_rtt, ts)) {
2653 lfr.ping.type = NGTCP2_FRAME_PING;
2654
2655 rv = conn_ppe_write_frame_hd_log(conn, &ppe, &hd_logged, &hd, &lfr);
2656 if (rv != 0) {
2657 assert(rv == NGTCP2_ERR_NOBUF);
2658 } else {
2659 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING;
2660 pktns->tx.non_ack_pkt_start_ts = UINT64_MAX;
2661 pkt_empty = 0;
2662 }
2663 } else if (pktns->tx.non_ack_pkt_start_ts == UINT64_MAX) {
2664 pktns->tx.non_ack_pkt_start_ts = ts;
2665 }
2666 } else {
2667 pktns->tx.non_ack_pkt_start_ts = UINT64_MAX;
2668 }
2669 }
2670 }
2671
2672 if (pkt_empty && !require_padding) {
2673 return 0;
2674 }
2675
2676 /* If we cannot write another packet, then we need to add padding to
2677 Initial here. */
2678 if (conn_should_pad_pkt(
2679 conn, type, ngtcp2_ppe_left(&ppe), write_datalen,
2680 (rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) != 0,
2681 require_padding)) {
2682 lfr.padding.type = NGTCP2_FRAME_PADDING;
2683 lfr.padding.len = conn_dgram_padding(conn, &ppe);
2684 } else if (pkt_empty) {
2685 return 0;
2686 } else {
2687 lfr.padding.type = NGTCP2_FRAME_PADDING;
2688 lfr.padding.len = ngtcp2_ppe_padding_size(&ppe, conn_min_pktlen(conn));
2689 min_padded = 1;
2690 }
2691
2692 if (lfr.padding.len) {
2693 if (!min_padded ||
2694 (rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING)) {
2695 padded = 1;
2696 }
2697 ngtcp2_log_tx_fr(&conn->log, &hd, &lfr);
2698 ngtcp2_qlog_write_frame(&conn->qlog, &lfr);
2699 }
2700
2701 spktlen = ngtcp2_ppe_final(&ppe, NULL);
2702 if (spktlen < 0) {
2703 assert(ngtcp2_err_is_fatal((int)spktlen));
2704 ngtcp2_frame_chain_list_objalloc_del(frq, &conn->frc_objalloc, conn->mem);
2705 return spktlen;
2706 }
2707
2708 ngtcp2_qlog_pkt_sent_end(&conn->qlog, &hd, (size_t)spktlen);
2709
2710 if ((rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) || padded) {
2711 if (pi) {
2712 conn_handle_tx_ecn(conn, pi, &rtb_entry_flags, pktns, &hd, ts);
2713 }
2714
2715 rv =
2716 ngtcp2_rtb_entry_objalloc_new(&rtbent, &hd, frq, ts, (size_t)spktlen,
2717 rtb_entry_flags, &conn->rtb_entry_objalloc);
2718 if (rv != 0) {
2719 assert(ngtcp2_err_is_fatal(rv));
2720 ngtcp2_frame_chain_list_objalloc_del(frq, &conn->frc_objalloc, conn->mem);
2721 return rv;
2722 }
2723
2724 rv = conn_on_pkt_sent(conn, pktns, rtbent);
2725 if (rv != 0) {
2726 ngtcp2_rtb_entry_objalloc_del(rtbent, &conn->rtb_entry_objalloc,
2727 &conn->frc_objalloc, conn->mem);
2728 return rv;
2729 }
2730
2731 if ((rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) &&
2732 (conn->flags & NGTCP2_CONN_FLAG_RESTART_IDLE_TIMER_ON_WRITE)) {
2733 conn_restart_timer_on_write(conn, ts);
2734 }
2735 } else if (pi && conn->tx.ecn.state == NGTCP2_ECN_STATE_CAPABLE) {
2736 conn_handle_tx_ecn(conn, pi, NULL, pktns, &hd, ts);
2737 }
2738
2739 if (pktns->rtb.probe_pkt_left &&
2740 (rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING)) {
2741 --pktns->rtb.probe_pkt_left;
2742 }
2743
2744 conn_update_keep_alive_last_ts(conn, ts);
2745
2746 conn->dcid.current.bytes_sent += (uint64_t)spktlen;
2747
2748 conn->tx.pacing.pktlen += (size_t)spktlen;
2749
2750 ++conn->cstat.pkt_sent;
2751 conn->cstat.bytes_sent += (uint64_t)spktlen;
2752
2753 ngtcp2_qlog_metrics_updated(&conn->qlog, &conn->cstat);
2754
2755 ++pktns->tx.last_pkt_num;
2756
2757 return spktlen;
2758 }
2759
2760 /*
2761 * conn_write_ack_pkt writes QUIC packet for type |type| which only
2762 * includes ACK frame in the buffer pointed by |dest| whose length is
2763 * |destlen|.
2764 *
2765 * This function returns the number of bytes written in |dest| if it
2766 * succeeds, or one of the following negative error codes:
2767 *
2768 * NGTCP2_ERR_CALLBACK_FAILURE
2769 * User-defined callback function failed.
2770 * NGTCP2_ERR_NOMEM
2771 * Out of memory.
2772 */
2773 static ngtcp2_ssize conn_write_ack_pkt(ngtcp2_conn *conn, ngtcp2_pkt_info *pi,
2774 uint8_t *dest, size_t destlen,
2775 uint8_t type, ngtcp2_tstamp ts) {
2776 ngtcp2_pktns *pktns;
2777 ngtcp2_duration ack_delay;
2778 uint64_t ack_delay_exponent;
2779 ngtcp2_ssize spktlen;
2780 ngtcp2_ack_range ack_ranges[NGTCP2_MAX_ACK_RANGES];
2781 ngtcp2_frame fr;
2782
2783 assert(!(conn->flags & NGTCP2_CONN_FLAG_PPE_PENDING));
2784
2785 switch (type) {
2786 case NGTCP2_PKT_INITIAL:
2787 assert(conn->server);
2788 pktns = conn->in_pktns;
2789 ack_delay = 0;
2790 ack_delay_exponent = NGTCP2_DEFAULT_ACK_DELAY_EXPONENT;
2791 break;
2792 case NGTCP2_PKT_HANDSHAKE:
2793 pktns = conn->hs_pktns;
2794 ack_delay = 0;
2795 ack_delay_exponent = NGTCP2_DEFAULT_ACK_DELAY_EXPONENT;
2796 break;
2797 case NGTCP2_PKT_1RTT:
2798 pktns = &conn->pktns;
2799 ack_delay = conn_compute_ack_delay(conn);
2800 ack_delay_exponent = conn->local.transport_params.ack_delay_exponent;
2801 break;
2802 default:
2803 ngtcp2_unreachable();
2804 }
2805
2806 if (!pktns->crypto.tx.ckm) {
2807 return 0;
2808 }
2809
2810 fr.ack.ranges = ack_ranges;
2811 if (ngtcp2_acktr_create_ack_frame(&pktns->acktr, &fr.ack, type, ts, ack_delay,
2812 ack_delay_exponent) != 0) {
2813 return 0;
2814 }
2815
2816 spktlen = ngtcp2_conn_write_single_frame_pkt(
2817 conn, pi, dest, destlen, type, NGTCP2_WRITE_PKT_FLAG_NONE,
2818 &conn->dcid.current.cid, &fr, NGTCP2_RTB_ENTRY_FLAG_NONE, NULL, ts);
2819
2820 if (spktlen <= 0) {
2821 return spktlen;
2822 }
2823
2824 conn->dcid.current.bytes_sent += (uint64_t)spktlen;
2825
2826 return spktlen;
2827 }
2828
2829 static void conn_discard_pktns(ngtcp2_conn *conn, ngtcp2_pktns **ppktns,
2830 ngtcp2_tstamp ts) {
2831 ngtcp2_pktns *pktns = *ppktns;
2832 uint64_t bytes_in_flight;
2833
2834 bytes_in_flight = pktns->rtb.cc_bytes_in_flight;
2835
2836 assert(conn->cstat.bytes_in_flight >= bytes_in_flight);
2837
2838 conn->cstat.bytes_in_flight -= bytes_in_flight;
2839 conn->cstat.pto_count = 0;
2840 conn->cstat.last_tx_pkt_ts[pktns->id] = UINT64_MAX;
2841 conn->cstat.loss_time[pktns->id] = UINT64_MAX;
2842
2843 conn_call_delete_crypto_aead_ctx(conn, &pktns->crypto.rx.ckm->aead_ctx);
2844 conn_call_delete_crypto_cipher_ctx(conn, &pktns->crypto.rx.hp_ctx);
2845 conn_call_delete_crypto_aead_ctx(conn, &pktns->crypto.tx.ckm->aead_ctx);
2846 conn_call_delete_crypto_cipher_ctx(conn, &pktns->crypto.tx.hp_ctx);
2847
2848 pktns_del(pktns, conn->mem);
2849 *ppktns = NULL;
2850
2851 ngtcp2_conn_set_loss_detection_timer(conn, ts);
2852 }
2853
2854 void ngtcp2_conn_discard_initial_state(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
2855 if (!conn->in_pktns) {
2856 return;
2857 }
2858
2859 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CON,
2860 "discarding Initial packet number space");
2861
2862 conn_discard_pktns(conn, &conn->in_pktns, ts);
2863
2864 conn_vneg_crypto_free(conn);
2865
2866 memset(&conn->vneg.rx, 0, sizeof(conn->vneg.rx));
2867 memset(&conn->vneg.tx, 0, sizeof(conn->vneg.tx));
2868 }
2869
2870 void ngtcp2_conn_discard_handshake_state(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
2871 if (!conn->hs_pktns) {
2872 return;
2873 }
2874
2875 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CON,
2876 "discarding Handshake packet number space");
2877
2878 conn_discard_pktns(conn, &conn->hs_pktns, ts);
2879 }
2880
2881 /*
2882 * conn_discard_early_key discards early key.
2883 */
2884 static void conn_discard_early_key(ngtcp2_conn *conn) {
2885 assert(conn->early.ckm);
2886
2887 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CON, "discarding early key");
2888
2889 conn_call_delete_crypto_aead_ctx(conn, &conn->early.ckm->aead_ctx);
2890 conn_call_delete_crypto_cipher_ctx(conn, &conn->early.hp_ctx);
2891 memset(&conn->early.hp_ctx, 0, sizeof(conn->early.hp_ctx));
2892
2893 ngtcp2_crypto_km_del(conn->early.ckm, conn->mem);
2894 conn->early.ckm = NULL;
2895 }
2896
2897 /*
2898 * conn_write_handshake_ack_pkts writes packets which contain ACK
2899 * frame only. This function writes at most 2 packets for each
2900 * Initial and Handshake packet.
2901 */
2902 static ngtcp2_ssize conn_write_handshake_ack_pkts(ngtcp2_conn *conn,
2903 ngtcp2_pkt_info *pi,
2904 uint8_t *dest, size_t destlen,
2905 ngtcp2_tstamp ts) {
2906 ngtcp2_ssize res = 0, nwrite = 0;
2907
2908 /* In the most cases, client sends ACK in conn_write_handshake_pkt.
2909 This function is only called when it is CWND limited or pacing
2910 limited. It is not required for client to send ACK for server
2911 Initial. This is because once it gets server Initial, it gets
2912 Handshake tx key and discards Initial key. The only good reason
2913 to send ACK is give server RTT measurement early. */
2914 if (conn->server && conn->in_pktns) {
2915 nwrite =
2916 conn_write_ack_pkt(conn, pi, dest, destlen, NGTCP2_PKT_INITIAL, ts);
2917 if (nwrite < 0) {
2918 assert(nwrite != NGTCP2_ERR_NOBUF);
2919 return nwrite;
2920 }
2921
2922 res += nwrite;
2923 dest += nwrite;
2924 destlen -= (size_t)nwrite;
2925 }
2926
2927 if (conn->hs_pktns->crypto.tx.ckm) {
2928 nwrite =
2929 conn_write_ack_pkt(conn, pi, dest, destlen, NGTCP2_PKT_HANDSHAKE, ts);
2930 if (nwrite < 0) {
2931 assert(nwrite != NGTCP2_ERR_NOBUF);
2932 return nwrite;
2933 }
2934
2935 res += nwrite;
2936
2937 if (!conn->server && nwrite) {
2938 ngtcp2_conn_discard_initial_state(conn, ts);
2939 }
2940 }
2941
2942 return res;
2943 }
2944
2945 /*
2946 * conn_write_client_initial writes Initial packet in the buffer
2947 * pointed by |dest| whose length is |destlen|.
2948 *
2949 * This function returns the number of bytes written in |dest| if it
2950 * succeeds, or one of the following negative error codes:
2951 *
2952 * NGTCP2_ERR_NOMEM
2953 * Out of memory.
2954 * NGTCP2_ERR_CALLBACK_FAILURE
2955 * User-defined callback function failed.
2956 */
2957 static ngtcp2_ssize conn_write_client_initial(ngtcp2_conn *conn,
2958 ngtcp2_pkt_info *pi,
2959 uint8_t *dest, size_t destlen,
2960 uint64_t early_datalen,
2961 ngtcp2_tstamp ts) {
2962 int rv;
2963
2964 rv = conn_call_client_initial(conn);
2965 if (rv != 0) {
2966 return rv;
2967 }
2968
2969 return conn_write_handshake_pkt(
2970 conn, pi, dest, destlen, 0, NGTCP2_PKT_INITIAL, NGTCP2_WRITE_PKT_FLAG_NONE,
2971 early_datalen, ts);
2972 }
2973
2974 /*
2975 * dcid_tx_left returns the maximum number of bytes that server is
2976 * allowed to send to an unvalidated path associated to |dcid|.
2977 */
2978 static uint64_t dcid_tx_left(ngtcp2_dcid *dcid) {
2979 if (dcid->flags & NGTCP2_DCID_FLAG_PATH_VALIDATED) {
2980 return SIZE_MAX;
2981 }
2982 /* From QUIC spec: Prior to validating the client address, servers
2983 MUST NOT send more than three times as many bytes as the number
2984 of bytes they have received. */
2985 assert(dcid->bytes_recv * 3 >= dcid->bytes_sent);
2986
2987 return dcid->bytes_recv * 3 - dcid->bytes_sent;
2988 }
2989
2990 /*
2991 * conn_server_tx_left returns the maximum number of bytes that server
2992 * is allowed to send to an unvalidated path.
2993 */
2994 static uint64_t conn_server_tx_left(ngtcp2_conn *conn, ngtcp2_dcid *dcid) {
2995 assert(conn->server);
2996
2997 /* If pv->dcid has the current path, use conn->dcid.current. This
2998 is because conn->dcid.current gets update for bytes_recv and
2999 bytes_sent. */
3000 if (ngtcp2_path_eq(&dcid->ps.path, &conn->dcid.current.ps.path)) {
3001 return dcid_tx_left(&conn->dcid.current);
3002 }
3003
3004 return dcid_tx_left(dcid);
3005 }
3006
3007 /*
3008 * conn_write_handshake_pkts writes Initial and Handshake packets in
3009 * the buffer pointed by |dest| whose length is |destlen|.
3010 *
3011 * This function returns the number of bytes written in |dest| if it
3012 * succeeds, or one of the following negative error codes:
3013 *
3014 * NGTCP2_ERR_NOMEM
3015 * Out of memory.
3016 * NGTCP2_ERR_CALLBACK_FAILURE
3017 * User-defined callback function failed.
3018 */
3019 static ngtcp2_ssize conn_write_handshake_pkts(ngtcp2_conn *conn,
3020 ngtcp2_pkt_info *pi,
3021 uint8_t *dest, size_t destlen,
3022 uint64_t write_datalen,
3023 ngtcp2_tstamp ts) {
3024 ngtcp2_ssize nwrite;
3025 ngtcp2_ssize res = 0;
3026 ngtcp2_rtb_entry *rtbent;
3027 uint8_t wflags = NGTCP2_WRITE_PKT_FLAG_NONE;
3028 ngtcp2_conn_stat *cstat = &conn->cstat;
3029 ngtcp2_ksl_it it;
3030
3031 /* As a client, we would like to discard Initial packet number space
3032 when sending the first Handshake packet. When sending Handshake
3033 packet, it should be one of 1) sending ACK, 2) sending PTO probe
3034 packet, or 3) sending CRYPTO. If we have pending acknowledgement
3035 for Initial, then do not discard Initial packet number space.
3036 Otherwise, if either 1) or 2) is satisfied, discard Initial
3037 packet number space. When sending Handshake CRYPTO, it indicates
3038 that client has received Handshake CRYPTO from server. Initial
3039 packet number space is discarded because 1) is met. If there is
3040 pending Initial ACK, Initial packet number space is discarded
3041 after writing the first Handshake packet.
3042 */
3043 if (!conn->server && conn->hs_pktns->crypto.tx.ckm && conn->in_pktns &&
3044 !ngtcp2_acktr_require_active_ack(&conn->in_pktns->acktr,
3045 /* max_ack_delay = */ 0, ts) &&
3046 (ngtcp2_acktr_require_active_ack(&conn->hs_pktns->acktr,
3047 /* max_ack_delay = */ 0, ts) ||
3048 conn->hs_pktns->rtb.probe_pkt_left)) {
3049 /* Discard Initial state here so that Handshake packet is not
3050 padded. */
3051 ngtcp2_conn_discard_initial_state(conn, ts);
3052 } else if (conn->in_pktns) {
3053 nwrite =
3054 conn_write_handshake_pkt(conn, pi, dest, destlen, 0, NGTCP2_PKT_INITIAL,
3055 NGTCP2_WRITE_PKT_FLAG_NONE, write_datalen, ts);
3056 if (nwrite < 0) {
3057 assert(nwrite != NGTCP2_ERR_NOBUF);
3058 return nwrite;
3059 }
3060
3061 if (nwrite == 0) {
3062 if (conn->server &&
3063 (conn->in_pktns->rtb.probe_pkt_left ||
3064 !ngtcp2_strm_streamfrq_empty(&conn->in_pktns->crypto.strm))) {
3065 if (cstat->loss_detection_timer != UINT64_MAX &&
3066 conn_server_tx_left(conn, &conn->dcid.current) <
3067 NGTCP2_MAX_UDP_PAYLOAD_SIZE) {
3068 ngtcp2_log_info(
3069 &conn->log, NGTCP2_LOG_EVENT_LDC,
3070 "loss detection timer canceled due to amplification limit");
3071 ngtcp2_conn_cancel_loss_detection_timer(conn);
3072 }
3073
3074 return 0;
3075 }
3076 } else {
3077 res += nwrite;
3078 dest += nwrite;
3079 destlen -= (size_t)nwrite;
3080
3081 if (conn->server) {
3082 it = ngtcp2_rtb_head(&conn->in_pktns->rtb);
3083 if (!ngtcp2_ksl_it_end(&it)) {
3084 rtbent = ngtcp2_ksl_it_get(&it);
3085 if (rtbent->flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) {
3086 wflags |= NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING;
3087 }
3088 }
3089 } else {
3090 wflags |= NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING;
3091 }
3092 }
3093 }
3094
3095 nwrite =
3096 conn_write_handshake_pkt(conn, pi, dest, destlen, (size_t)res,
3097 NGTCP2_PKT_HANDSHAKE, wflags, write_datalen, ts);
3098 if (nwrite < 0) {
3099 assert(nwrite != NGTCP2_ERR_NOBUF);
3100 return nwrite;
3101 }
3102
3103 res += nwrite;
3104
3105 if (!conn->server && conn->hs_pktns->crypto.tx.ckm && nwrite) {
3106 /* We don't need to send further Initial packet if we have
3107 Handshake key and sent something with it. So discard initial
3108 state here. */
3109 ngtcp2_conn_discard_initial_state(conn, ts);
3110 }
3111
3112 return res;
3113 }
3114
3115 /*
3116 * conn_initial_stream_rx_offset returns the initial maximum offset of
3117 * data for a stream denoted by |stream_id|.
3118 */
3119 static uint64_t conn_initial_stream_rx_offset(ngtcp2_conn *conn,
3120 int64_t stream_id) {
3121 int local_stream = conn_local_stream(conn, stream_id);
3122
3123 if (bidi_stream(stream_id)) {
3124 if (local_stream) {
3125 return conn->local.transport_params.initial_max_stream_data_bidi_local;
3126 }
3127 return conn->local.transport_params.initial_max_stream_data_bidi_remote;
3128 }
3129
3130 if (local_stream) {
3131 return 0;
3132 }
3133 return conn->local.transport_params.initial_max_stream_data_uni;
3134 }
3135
3136 /*
3137 * conn_should_send_max_stream_data returns nonzero if MAX_STREAM_DATA
3138 * frame should be send for |strm|.
3139 */
3140 static int conn_should_send_max_stream_data(ngtcp2_conn *conn,
3141 ngtcp2_strm *strm) {
3142 uint64_t inc = strm->rx.unsent_max_offset - strm->rx.max_offset;
3143 (void)conn;
3144
3145 return strm->rx.window < 4 * inc;
3146 }
3147
3148 /*
3149 * conn_should_send_max_data returns nonzero if MAX_DATA frame should
3150 * be sent.
3151 */
3152 static int conn_should_send_max_data(ngtcp2_conn *conn) {
3153 uint64_t inc = conn->rx.unsent_max_offset - conn->rx.max_offset;
3154
3155 return conn->rx.window < 4 * inc;
3156 }
3157
3158 /*
3159 * conn_required_num_new_connection_id returns the number of
3160 * additional connection ID the local endpoint has to provide to the
3161 * remote endpoint.
3162 */
3163 static size_t conn_required_num_new_connection_id(ngtcp2_conn *conn) {
3164 uint64_t n;
3165 size_t len = ngtcp2_ksl_len(&conn->scid.set);
3166 size_t lim;
3167
3168 if (len >= NGTCP2_MAX_SCID_POOL_SIZE) {
3169 return 0;
3170 }
3171
3172 assert(NGTCP2_MAX_SCID_POOL_SIZE >= conn->scid.num_in_flight);
3173
3174 lim = NGTCP2_MAX_SCID_POOL_SIZE - conn->scid.num_in_flight;
3175 if (lim == 0) {
3176 return 0;
3177 }
3178
3179 assert(conn->remote.transport_params);
3180 assert(conn->remote.transport_params->active_connection_id_limit);
3181
3182 /* len includes retired CID. We don't provide extra CID if doing so
3183 exceeds NGTCP2_MAX_SCID_POOL_SIZE. */
3184
3185 n = conn->remote.transport_params->active_connection_id_limit +
3186 conn->scid.num_retired;
3187
3188 n = ngtcp2_min_uint64(NGTCP2_MAX_SCID_POOL_SIZE, n) - len;
3189
3190 return (size_t)ngtcp2_min_uint64(lim, n);
3191 }
3192
3193 /*
3194 * conn_enqueue_new_connection_id generates additional connection IDs
3195 * and prepares to send them to the remote endpoint.
3196 *
3197 * This function returns 0 if it succeeds, or one of the following
3198 * negative error codes:
3199 *
3200 * NGTCP2_ERR_NOMEM
3201 * Out of memory.
3202 * NGTCP2_ERR_CALLBACK_FAILURE
3203 * User-defined callback function failed.
3204 */
3205 static int conn_enqueue_new_connection_id(ngtcp2_conn *conn) {
3206 size_t i, need = conn_required_num_new_connection_id(conn);
3207 size_t cidlen = conn->oscid.datalen;
3208 ngtcp2_cid cid;
3209 uint64_t seq;
3210 int rv;
3211 uint8_t token[NGTCP2_STATELESS_RESET_TOKENLEN];
3212 ngtcp2_frame_chain *nfrc;
3213 ngtcp2_pktns *pktns = &conn->pktns;
3214 ngtcp2_scid *scid;
3215 ngtcp2_ksl_it it;
3216
3217 for (i = 0; i < need; ++i) {
3218 rv = conn_call_get_new_connection_id(conn, &cid, token, cidlen);
3219 if (rv != 0) {
3220 return rv;
3221 }
3222
3223 if (cid.datalen != cidlen) {
3224 return NGTCP2_ERR_CALLBACK_FAILURE;
3225 }
3226
3227 /* Assert uniqueness */
3228 it = ngtcp2_ksl_lower_bound(&conn->scid.set, &cid);
3229 if (!ngtcp2_ksl_it_end(&it) &&
3230 ngtcp2_cid_eq(ngtcp2_ksl_it_key(&it), &cid)) {
3231 return NGTCP2_ERR_CALLBACK_FAILURE;
3232 }
3233
3234 seq = ++conn->scid.last_seq;
3235
3236 scid = ngtcp2_mem_malloc(conn->mem, sizeof(*scid));
3237 if (scid == NULL) {
3238 return NGTCP2_ERR_NOMEM;
3239 }
3240
3241 ngtcp2_scid_init(scid, seq, &cid);
3242
3243 rv = ngtcp2_ksl_insert(&conn->scid.set, NULL, &scid->cid, scid);
3244 if (rv != 0) {
3245 ngtcp2_mem_free(conn->mem, scid);
3246 return rv;
3247 }
3248
3249 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
3250 if (rv != 0) {
3251 return rv;
3252 }
3253
3254 nfrc->fr.new_connection_id.type = NGTCP2_FRAME_NEW_CONNECTION_ID;
3255 nfrc->fr.new_connection_id.seq = seq;
3256 nfrc->fr.new_connection_id.retire_prior_to = 0;
3257 nfrc->fr.new_connection_id.cid = cid;
3258 memcpy(nfrc->fr.new_connection_id.stateless_reset_token, token,
3259 sizeof(token));
3260 nfrc->next = pktns->tx.frq;
3261 pktns->tx.frq = nfrc;
3262
3263 assert(NGTCP2_MAX_SCID_POOL_SIZE > conn->scid.num_in_flight);
3264
3265 ++conn->scid.num_in_flight;
3266 }
3267
3268 return 0;
3269 }
3270
3271 static int dcidtr_on_deactivate(const ngtcp2_dcid *dcid, void *user_data) {
3272 return conn_call_deactivate_dcid(user_data, dcid);
3273 }
3274
3275 /*
3276 * conn_remove_retired_connection_id removes the already retired
3277 * connection ID. It waits PTO before actually removing a connection
3278 * ID after it receives RETIRE_CONNECTION_ID from peer to catch
3279 * reordered packets.
3280 *
3281 * This function returns 0 if it succeeds, or one of the following
3282 * negative error codes:
3283 *
3284 * NGTCP2_ERR_NOMEM
3285 * Out of memory.
3286 * NGTCP2_ERR_CALLBACK_FAILURE
3287 * User-defined callback function failed.
3288 */
3289 static int conn_remove_retired_connection_id(ngtcp2_conn *conn,
3290 ngtcp2_duration pto,
3291 ngtcp2_tstamp ts) {
3292 ngtcp2_duration timeout = pto;
3293 ngtcp2_scid *scid;
3294 int rv;
3295
3296 for (; !ngtcp2_pq_empty(&conn->scid.used);) {
3297 scid = ngtcp2_struct_of(ngtcp2_pq_top(&conn->scid.used), ngtcp2_scid, pe);
3298
3299 if (!ngtcp2_tstamp_elapsed(scid->retired_ts, timeout, ts)) {
3300 break;
3301 }
3302
3303 assert(scid->flags & NGTCP2_SCID_FLAG_RETIRED);
3304
3305 rv = conn_call_remove_connection_id(conn, &scid->cid);
3306 if (rv != 0) {
3307 return rv;
3308 }
3309
3310 ngtcp2_ksl_remove(&conn->scid.set, NULL, &scid->cid);
3311 ngtcp2_pq_pop(&conn->scid.used);
3312 ngtcp2_mem_free(conn->mem, scid);
3313
3314 assert(conn->scid.num_retired);
3315 --conn->scid.num_retired;
3316 }
3317
3318 rv = ngtcp2_dcidtr_remove_stale_retired_dcid(&conn->dcid.dtr, timeout, ts,
3319 dcidtr_on_deactivate, conn);
3320 if (rv != 0) {
3321 return rv;
3322 }
3323
3324 return 0;
3325 }
3326
3327 /*
3328 * conn_min_pktlen returns the minimum length of packet this endpoint
3329 * sends. It may underestimate the length because this does not take
3330 * into account header protection sample.
3331 */
3332 static size_t conn_min_pktlen(ngtcp2_conn *conn) {
3333 return conn->oscid.datalen + NGTCP2_MIN_PKT_EXPANDLEN;
3334 }
3335
3336 /*
3337 * conn_handle_unconfirmed_key_update_from_remote deals with key
3338 * update which has not been confirmed yet and initiated by the remote
3339 * endpoint.
3340 *
3341 * If key update was initiated by the remote endpoint, acknowledging a
3342 * packet encrypted with the new key completes key update procedure.
3343 */
3344 static void conn_handle_unconfirmed_key_update_from_remote(ngtcp2_conn *conn,
3345 int64_t largest_ack,
3346 ngtcp2_tstamp ts) {
3347 if (!(conn->flags & NGTCP2_CONN_FLAG_KEY_UPDATE_NOT_CONFIRMED) ||
3348 (conn->flags & NGTCP2_CONN_FLAG_KEY_UPDATE_INITIATOR) ||
3349 largest_ack < conn->pktns.crypto.rx.ckm->pkt_num) {
3350 return;
3351 }
3352
3353 conn->flags &= (uint32_t)~NGTCP2_CONN_FLAG_KEY_UPDATE_NOT_CONFIRMED;
3354 conn->crypto.key_update.confirmed_ts = ts;
3355
3356 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CRY, "key update confirmed");
3357 }
3358
3359 static uint64_t conn_tx_strmq_first_cycle(ngtcp2_conn *conn);
3360
3361 /*
3362 * strm_should_send_stream_data_blocked returns nonzero if
3363 * STREAM_DATA_BLOCKED frame should be sent to |strm|.
3364 */
3365 static int strm_should_send_stream_data_blocked(ngtcp2_strm *strm) {
3366 return strm->tx.offset == strm->tx.max_offset &&
3367 strm->tx.last_blocked_offset != strm->tx.max_offset;
3368 }
3369
3370 /*
3371 * conn_should_send_data_blocked returns nonzero if DATA_BLOCKED frame
3372 * should be sent.
3373 */
3374 static int conn_should_send_data_blocked(ngtcp2_conn *conn) {
3375 return conn->tx.offset == conn->tx.max_offset &&
3376 conn->tx.last_blocked_offset != conn->tx.max_offset;
3377 }
3378
3379 /*
3380 * conn_reset_ppe_pending clears NGTCP2_CONN_FLAG_PPE_PENDING flag and
3381 * nullifies conn->pkt.
3382 */
3383 static void conn_reset_ppe_pending(ngtcp2_conn *conn) {
3384 conn->flags &= (uint32_t)~NGTCP2_CONN_FLAG_PPE_PENDING;
3385
3386 memset(&conn->pkt, 0, sizeof(conn->pkt));
3387 }
3388
3389 /*
3390 * conn_write_pkt writes a protected packet in the buffer pointed by
3391 * |dest| whose length if |destlen|. |dgram_offset| is the offset in
3392 * UDP datagram payload where this QUIC packet is positioned at.
3393 * |type| specifies the type of packet. It can be NGTCP2_PKT_1RTT or
3394 * NGTCP2_PKT_0RTT.
3395 *
3396 * This function can send new stream data. In order to send stream
3397 * data, specify the underlying stream and parameters to
3398 * |vmsg|->stream. If |vmsg|->stream.fin is set to nonzero, it
3399 * signals that the given data is the final portion of the stream.
3400 * |vmsg|->stream.data vector of length |vmsg|->stream.datacnt
3401 * specifies stream data to send. The number of bytes sent to the
3402 * stream is assigned to *|vmsg|->stream.pdatalen. If 0 length STREAM
3403 * data is sent, 0 is assigned to it. The caller should initialize
3404 * *|vmsg|->stream.pdatalen to -1.
3405 *
3406 * If |require_padding| is nonzero, padding bytes are added to occupy
3407 * the remaining packet payload.
3408 *
3409 * This function returns the number of bytes written in |dest| if it
3410 * succeeds, or one of the following negative error codes:
3411 *
3412 * NGTCP2_ERR_NOMEM
3413 * Out of memory.
3414 * NGTCP2_ERR_CALLBACK_FAILURE
3415 * User-defined callback function failed.
3416 * NGTCP2_ERR_STREAM_DATA_BLOCKED
3417 * Stream data could not be written because of flow control.
3418 */
3419 static ngtcp2_ssize conn_write_pkt(ngtcp2_conn *conn, ngtcp2_pkt_info *pi,
3420 uint8_t *dest, size_t destlen,
3421 size_t dgram_offset, ngtcp2_vmsg *vmsg,
3422 uint8_t type, uint8_t flags,
3423 ngtcp2_tstamp ts) {
3424 int rv = 0;
3425 ngtcp2_crypto_cc *cc = &conn->pkt.cc;
3426 ngtcp2_ppe *ppe = &conn->pkt.ppe;
3427 ngtcp2_pkt_hd *hd = &conn->pkt.hd;
3428 ngtcp2_ack_range ack_ranges[NGTCP2_MAX_ACK_RANGES];
3429 ngtcp2_frame lfr;
3430 ngtcp2_ssize nwrite;
3431 ngtcp2_frame_chain **pfrc, *nfrc, *frc;
3432 ngtcp2_rtb_entry *ent;
3433 ngtcp2_strm *strm;
3434 int pkt_empty = 1;
3435 uint64_t ndatalen = 0;
3436 uint64_t wdatalen;
3437 int send_stream = 0;
3438 int stream_blocked = 0;
3439 int send_datagram = 0;
3440 ngtcp2_pktns *pktns = &conn->pktns;
3441 size_t left;
3442 uint64_t datalen = 0;
3443 ngtcp2_vec data[NGTCP2_MAX_STREAM_DATACNT];
3444 size_t datacnt;
3445 uint16_t rtb_entry_flags = NGTCP2_RTB_ENTRY_FLAG_NONE;
3446 int hd_logged = 0;
3447 ngtcp2_path_challenge_entry *pcent;
3448 uint8_t hd_flags = NGTCP2_PKT_FLAG_NONE;
3449 int require_padding = (flags & NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING) != 0;
3450 int write_more = (flags & NGTCP2_WRITE_PKT_FLAG_MORE) != 0;
3451 int ppe_pending = (conn->flags & NGTCP2_CONN_FLAG_PPE_PENDING) != 0;
3452 size_t min_pktlen = conn_min_pktlen(conn);
3453 int min_padded = 0;
3454 int padded = 0;
3455 uint64_t crypto_offset;
3456 uint64_t stream_offset;
3457 ngtcp2_ssize num_reclaimed;
3458 uint64_t target_max_data;
3459 ngtcp2_conn_stat *cstat = &conn->cstat;
3460 uint64_t delta;
3461 const ngtcp2_cid *scid = NULL;
3462 int keep_alive_expired = 0;
3463 uint32_t version = 0;
3464
3465 /* Return 0 if destlen is less than minimum packet length which can
3466 trigger Stateless Reset */
3467 if (destlen < min_pktlen) {
3468 return 0;
3469 }
3470
3471 if (vmsg) {
3472 switch (vmsg->type) {
3473 case NGTCP2_VMSG_TYPE_STREAM:
3474 datalen = ngtcp2_vec_len(vmsg->stream.data, vmsg->stream.datacnt);
3475 ndatalen = conn_enforce_flow_control(conn, vmsg->stream.strm, datalen);
3476 /* 0 length STREAM frame is allowed */
3477 if (ndatalen || datalen == 0) {
3478 send_stream = 1;
3479 } else {
3480 stream_blocked = 1;
3481 }
3482 break;
3483 case NGTCP2_VMSG_TYPE_DATAGRAM:
3484 datalen = ngtcp2_vec_len(vmsg->datagram.data, vmsg->datagram.datacnt);
3485 send_datagram = 1;
3486 break;
3487 default:
3488 break;
3489 }
3490 }
3491
3492 if (!ppe_pending) {
3493 switch (type) {
3494 case NGTCP2_PKT_1RTT:
3495 hd_flags = conn_pkt_flags_short(conn);
3496 scid = NULL;
3497 cc->aead = pktns->crypto.ctx.aead;
3498 cc->hp = pktns->crypto.ctx.hp;
3499 cc->ckm = pktns->crypto.tx.ckm;
3500 cc->hp_ctx = pktns->crypto.tx.hp_ctx;
3501
3502 assert(conn->negotiated_version);
3503
3504 version = conn->negotiated_version;
3505
3506 /* transport parameter is only valid after handshake completion
3507 which means we don't know how many connection ID that remote
3508 peer can accept before handshake completion. Because server
3509 can use remote transport parameters sending stream data in
3510 0.5 RTT, it is also allowed to use remote transport
3511 parameters here. */
3512 if (conn->oscid.datalen &&
3513 (conn->server || conn_is_tls_handshake_completed(conn))) {
3514 rv = conn_enqueue_new_connection_id(conn);
3515 if (rv != 0) {
3516 return rv;
3517 }
3518 }
3519
3520 break;
3521 case NGTCP2_PKT_0RTT:
3522 assert(!conn->server);
3523 if (!conn->early.ckm) {
3524 return 0;
3525 }
3526 hd_flags = conn_pkt_flags_long(conn);
3527 scid = &conn->oscid;
3528 cc->aead = conn->early.ctx.aead;
3529 cc->hp = conn->early.ctx.hp;
3530 cc->ckm = conn->early.ckm;
3531 cc->hp_ctx = conn->early.hp_ctx;
3532 version = conn->client_chosen_version;
3533 break;
3534 default:
3535 /* Unreachable */
3536 ngtcp2_unreachable();
3537 }
3538
3539 cc->encrypt = conn->callbacks.encrypt;
3540 cc->hp_mask = conn->callbacks.hp_mask;
3541
3542 if (conn_should_send_max_data(conn)) {
3543 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
3544 if (rv != 0) {
3545 return rv;
3546 }
3547
3548 if (conn->local.settings.max_window &&
3549 conn->tx.last_max_data_ts != UINT64_MAX &&
3550 ts - conn->tx.last_max_data_ts <
3551 NGTCP2_FLOW_WINDOW_RTT_FACTOR * cstat->smoothed_rtt &&
3552 conn->local.settings.max_window > conn->rx.window) {
3553 target_max_data = NGTCP2_FLOW_WINDOW_SCALING_FACTOR * conn->rx.window;
3554 if (target_max_data > conn->local.settings.max_window) {
3555 target_max_data = conn->local.settings.max_window;
3556 }
3557
3558 delta = target_max_data - conn->rx.window;
3559 if (conn->rx.unsent_max_offset + delta > NGTCP2_MAX_VARINT) {
3560 delta = NGTCP2_MAX_VARINT - conn->rx.unsent_max_offset;
3561 }
3562
3563 conn->rx.window = target_max_data;
3564 } else {
3565 delta = 0;
3566 }
3567
3568 conn->tx.last_max_data_ts = ts;
3569
3570 nfrc->fr.max_data = (ngtcp2_max_data){
3571 .type = NGTCP2_FRAME_MAX_DATA,
3572 .max_data = conn->rx.unsent_max_offset + delta,
3573 };
3574 nfrc->next = pktns->tx.frq;
3575 pktns->tx.frq = nfrc;
3576
3577 conn->rx.max_offset = conn->rx.unsent_max_offset =
3578 nfrc->fr.max_data.max_data;
3579 }
3580
3581 rv = conn_handle_skip_pkt(conn, pktns, ts);
3582 if (rv != 0) {
3583 return rv;
3584 }
3585
3586 ngtcp2_pkt_hd_init(hd, hd_flags, type, &conn->dcid.current.cid, scid,
3587 pktns->tx.last_pkt_num + 1,
3588 pktns_select_pkt_numlen(pktns), version);
3589
3590 ngtcp2_ppe_init(ppe, dest, destlen, dgram_offset, cc);
3591
3592 rv = ngtcp2_ppe_encode_hd(ppe, hd);
3593 if (rv != 0) {
3594 assert(NGTCP2_ERR_NOBUF == rv);
3595 return 0;
3596 }
3597
3598 if (!ngtcp2_ppe_ensure_hp_sample(ppe)) {
3599 return 0;
3600 }
3601
3602 if (ngtcp2_ringbuf_len(&conn->rx.path_challenge.rb)) {
3603 pcent = ngtcp2_ringbuf_get(&conn->rx.path_challenge.rb, 0);
3604
3605 /* PATH_RESPONSE is bound to the path that the corresponding
3606 PATH_CHALLENGE is received. */
3607 if (ngtcp2_path_eq(&conn->dcid.current.ps.path, &pcent->ps.path)) {
3608 lfr.path_response.type = NGTCP2_FRAME_PATH_RESPONSE;
3609 memcpy(lfr.path_response.data, pcent->data,
3610 sizeof(lfr.path_response.data));
3611
3612 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &lfr);
3613 if (rv != 0) {
3614 assert(NGTCP2_ERR_NOBUF == rv);
3615 } else {
3616 ngtcp2_ringbuf_pop_front(&conn->rx.path_challenge.rb);
3617
3618 pkt_empty = 0;
3619 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING;
3620 require_padding = require_padding || !conn->server ||
3621 destlen >= NGTCP2_MAX_UDP_PAYLOAD_SIZE;
3622 /* We don't retransmit PATH_RESPONSE. */
3623
3624 /* Include PING to make a packet non-probing as per
3625 https://datatracker.ietf.org/doc/html/rfc9000#section-9.3.3
3626
3627 An endpoint that receives a PATH_CHALLENGE on an active
3628 path SHOULD send a non-probing packet in response. */
3629 lfr.ping.type = NGTCP2_FRAME_PING;
3630 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &lfr);
3631 if (rv != 0) {
3632 assert(NGTCP2_ERR_NOBUF == rv);
3633 }
3634 }
3635 }
3636 }
3637
3638 lfr.ack.ranges = ack_ranges;
3639 if (ngtcp2_acktr_create_ack_frame(
3640 &pktns->acktr, &lfr.ack, type, ts, conn_compute_ack_delay(conn),
3641 conn->local.transport_params.ack_delay_exponent) == 0) {
3642 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &lfr);
3643 if (rv != 0) {
3644 assert(NGTCP2_ERR_NOBUF == rv);
3645 } else {
3646 ngtcp2_acktr_commit_ack(&pktns->acktr);
3647 ngtcp2_acktr_add_ack(&pktns->acktr, hd->pkt_num, lfr.ack.largest_ack);
3648 assert(NGTCP2_PKT_1RTT == type);
3649 conn_handle_unconfirmed_key_update_from_remote(conn,
3650 lfr.ack.largest_ack, ts);
3651 pkt_empty = 0;
3652 }
3653 }
3654
3655 build_pkt:
3656 for (pfrc = &pktns->tx.frq; *pfrc;) {
3657 if ((*pfrc)->binder &&
3658 ((*pfrc)->binder->flags & NGTCP2_FRAME_CHAIN_BINDER_FLAG_ACK)) {
3659 frc = *pfrc;
3660 *pfrc = (*pfrc)->next;
3661 ngtcp2_frame_chain_objalloc_del(frc, &conn->frc_objalloc, conn->mem);
3662 continue;
3663 }
3664
3665 switch ((*pfrc)->fr.hd.type) {
3666 case NGTCP2_FRAME_RESET_STREAM:
3667 strm =
3668 ngtcp2_conn_find_stream(conn, (*pfrc)->fr.reset_stream.stream_id);
3669 if (strm == NULL ||
3670 !ngtcp2_strm_require_retransmit_reset_stream(strm)) {
3671 frc = *pfrc;
3672 *pfrc = (*pfrc)->next;
3673 ngtcp2_frame_chain_objalloc_del(frc, &conn->frc_objalloc, conn->mem);
3674 continue;
3675 }
3676 break;
3677 case NGTCP2_FRAME_STOP_SENDING:
3678 strm =
3679 ngtcp2_conn_find_stream(conn, (*pfrc)->fr.stop_sending.stream_id);
3680 if (strm == NULL ||
3681 !ngtcp2_strm_require_retransmit_stop_sending(strm)) {
3682 frc = *pfrc;
3683 *pfrc = (*pfrc)->next;
3684 ngtcp2_frame_chain_objalloc_del(frc, &conn->frc_objalloc, conn->mem);
3685 continue;
3686 }
3687 break;
3688 case NGTCP2_FRAME_STREAM:
3689 ngtcp2_unreachable();
3690 case NGTCP2_FRAME_MAX_STREAMS_BIDI:
3691 if ((*pfrc)->fr.max_streams.max_streams <
3692 conn->remote.bidi.max_streams) {
3693 frc = *pfrc;
3694 *pfrc = (*pfrc)->next;
3695 ngtcp2_frame_chain_objalloc_del(frc, &conn->frc_objalloc, conn->mem);
3696 continue;
3697 }
3698 break;
3699 case NGTCP2_FRAME_MAX_STREAMS_UNI:
3700 if ((*pfrc)->fr.max_streams.max_streams <
3701 conn->remote.uni.max_streams) {
3702 frc = *pfrc;
3703 *pfrc = (*pfrc)->next;
3704 ngtcp2_frame_chain_objalloc_del(frc, &conn->frc_objalloc, conn->mem);
3705 continue;
3706 }
3707 break;
3708 case NGTCP2_FRAME_MAX_STREAM_DATA:
3709 strm =
3710 ngtcp2_conn_find_stream(conn, (*pfrc)->fr.max_stream_data.stream_id);
3711 if (strm == NULL || !ngtcp2_strm_require_retransmit_max_stream_data(
3712 strm, &(*pfrc)->fr.max_stream_data)) {
3713 frc = *pfrc;
3714 *pfrc = (*pfrc)->next;
3715 ngtcp2_frame_chain_objalloc_del(frc, &conn->frc_objalloc, conn->mem);
3716 continue;
3717 }
3718 break;
3719 case NGTCP2_FRAME_MAX_DATA:
3720 if ((*pfrc)->fr.max_data.max_data < conn->rx.max_offset) {
3721 frc = *pfrc;
3722 *pfrc = (*pfrc)->next;
3723 ngtcp2_frame_chain_objalloc_del(frc, &conn->frc_objalloc, conn->mem);
3724 continue;
3725 }
3726 break;
3727 case NGTCP2_FRAME_STREAM_DATA_BLOCKED:
3728 strm = ngtcp2_conn_find_stream(
3729 conn, (*pfrc)->fr.stream_data_blocked.stream_id);
3730 if (strm == NULL || !ngtcp2_strm_require_retransmit_stream_data_blocked(
3731 strm, &(*pfrc)->fr.stream_data_blocked)) {
3732 frc = *pfrc;
3733 *pfrc = (*pfrc)->next;
3734 ngtcp2_frame_chain_objalloc_del(frc, &conn->frc_objalloc, conn->mem);
3735 continue;
3736 }
3737 break;
3738 case NGTCP2_FRAME_DATA_BLOCKED:
3739 if ((*pfrc)->fr.data_blocked.offset != conn->tx.max_offset) {
3740 frc = *pfrc;
3741 *pfrc = (*pfrc)->next;
3742 ngtcp2_frame_chain_objalloc_del(frc, &conn->frc_objalloc, conn->mem);
3743 continue;
3744 }
3745 break;
3746 case NGTCP2_FRAME_CRYPTO:
3747 ngtcp2_unreachable();
3748 }
3749
3750 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &(*pfrc)->fr);
3751 if (rv != 0) {
3752 assert(NGTCP2_ERR_NOBUF == rv);
3753 break;
3754 }
3755
3756 pkt_empty = 0;
3757 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
3758 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
3759 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
3760 pfrc = &(*pfrc)->next;
3761 }
3762
3763 if (*pfrc == NULL) {
3764 for (; !ngtcp2_strm_streamfrq_empty(&pktns->crypto.strm);) {
3765 left = ngtcp2_ppe_left(ppe);
3766
3767 crypto_offset =
3768 ngtcp2_strm_streamfrq_unacked_offset(&pktns->crypto.strm);
3769 if (crypto_offset == (uint64_t)-1) {
3770 ngtcp2_strm_streamfrq_clear(&pktns->crypto.strm);
3771 break;
3772 }
3773
3774 left = ngtcp2_pkt_crypto_max_datalen(crypto_offset, left, left);
3775
3776 if (left == (size_t)-1) {
3777 break;
3778 }
3779
3780 rv = ngtcp2_strm_streamfrq_pop(&pktns->crypto.strm, &nfrc, left);
3781 if (rv != 0) {
3782 assert(ngtcp2_err_is_fatal(rv));
3783 return rv;
3784 }
3785
3786 if (nfrc == NULL) {
3787 break;
3788 }
3789
3790 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &nfrc->fr);
3791 if (rv != 0) {
3792 ngtcp2_unreachable();
3793 }
3794
3795 *pfrc = nfrc;
3796 pfrc = &(*pfrc)->next;
3797
3798 pkt_empty = 0;
3799 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
3800 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
3801 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
3802 }
3803 }
3804
3805 if (*pfrc == NULL) {
3806 for (; !ngtcp2_pq_empty(&conn->tx.strmq);) {
3807 strm = ngtcp2_conn_tx_strmq_top(conn);
3808
3809 if (strm->flags & NGTCP2_STRM_FLAG_SEND_RESET_STREAM) {
3810 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
3811 if (rv != 0) {
3812 return rv;
3813 }
3814
3815 nfrc->fr.reset_stream = (ngtcp2_reset_stream){
3816 .type = NGTCP2_FRAME_RESET_STREAM,
3817 .stream_id = strm->stream_id,
3818 .app_error_code = strm->tx.reset_stream_app_error_code,
3819 .final_size = strm->tx.offset,
3820 };
3821 *pfrc = nfrc;
3822
3823 strm->flags &= ~NGTCP2_STRM_FLAG_SEND_RESET_STREAM;
3824
3825 rv =
3826 conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &nfrc->fr);
3827 if (rv != 0) {
3828 assert(NGTCP2_ERR_NOBUF == rv);
3829
3830 break;
3831 }
3832
3833 pkt_empty = 0;
3834 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
3835 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
3836 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
3837 pfrc = &(*pfrc)->next;
3838 }
3839
3840 if (strm->flags & NGTCP2_STRM_FLAG_SEND_STOP_SENDING) {
3841 if ((strm->flags & NGTCP2_STRM_FLAG_SHUT_RD) &&
3842 ngtcp2_strm_rx_offset(strm) == strm->rx.last_offset) {
3843 strm->flags &= ~NGTCP2_STRM_FLAG_SEND_STOP_SENDING;
3844 } else {
3845 rv = conn_call_stream_stop_sending(
3846 conn, strm->stream_id, strm->tx.stop_sending_app_error_code,
3847 strm->stream_user_data);
3848 if (rv != 0) {
3849 assert(ngtcp2_err_is_fatal(rv));
3850
3851 return rv;
3852 }
3853
3854 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
3855 if (rv != 0) {
3856 return rv;
3857 }
3858
3859 nfrc->fr.stop_sending = (ngtcp2_stop_sending){
3860 .type = NGTCP2_FRAME_STOP_SENDING,
3861 .stream_id = strm->stream_id,
3862 .app_error_code = strm->tx.stop_sending_app_error_code,
3863 };
3864 *pfrc = nfrc;
3865
3866 strm->flags &= ~NGTCP2_STRM_FLAG_SEND_STOP_SENDING;
3867
3868 rv =
3869 conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &nfrc->fr);
3870 if (rv != 0) {
3871 assert(NGTCP2_ERR_NOBUF == rv);
3872
3873 break;
3874 }
3875
3876 pkt_empty = 0;
3877 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
3878 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
3879 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
3880 pfrc = &(*pfrc)->next;
3881 }
3882 }
3883
3884 if (!(strm->flags & NGTCP2_STRM_FLAG_SHUT_WR) &&
3885 strm_should_send_stream_data_blocked(strm)) {
3886 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
3887 if (rv != 0) {
3888 return rv;
3889 }
3890
3891 nfrc->fr.stream_data_blocked = (ngtcp2_stream_data_blocked){
3892 .type = NGTCP2_FRAME_STREAM_DATA_BLOCKED,
3893 .stream_id = strm->stream_id,
3894 .offset = strm->tx.max_offset,
3895 };
3896 *pfrc = nfrc;
3897
3898 strm->tx.last_blocked_offset = strm->tx.max_offset;
3899
3900 rv =
3901 conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &nfrc->fr);
3902 if (rv != 0) {
3903 assert(NGTCP2_ERR_NOBUF == rv);
3904
3905 break;
3906 }
3907
3908 pkt_empty = 0;
3909 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
3910 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
3911 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
3912 pfrc = &(*pfrc)->next;
3913 }
3914
3915 if (!(strm->flags &
3916 (NGTCP2_STRM_FLAG_SHUT_RD | NGTCP2_STRM_FLAG_STOP_SENDING)) &&
3917 conn_should_send_max_stream_data(conn, strm)) {
3918 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
3919 if (rv != 0) {
3920 assert(ngtcp2_err_is_fatal(rv));
3921 return rv;
3922 }
3923
3924 if (conn->local.settings.max_stream_window &&
3925 strm->tx.last_max_stream_data_ts != UINT64_MAX &&
3926 ts - strm->tx.last_max_stream_data_ts <
3927 NGTCP2_FLOW_WINDOW_RTT_FACTOR * cstat->smoothed_rtt &&
3928 conn->local.settings.max_stream_window > strm->rx.window) {
3929 target_max_data =
3930 NGTCP2_FLOW_WINDOW_SCALING_FACTOR * strm->rx.window;
3931 if (target_max_data > conn->local.settings.max_stream_window) {
3932 target_max_data = conn->local.settings.max_stream_window;
3933 }
3934
3935 delta = target_max_data - strm->rx.window;
3936 if (strm->rx.unsent_max_offset + delta > NGTCP2_MAX_VARINT) {
3937 delta = NGTCP2_MAX_VARINT - strm->rx.unsent_max_offset;
3938 }
3939
3940 strm->rx.window = target_max_data;
3941 } else {
3942 delta = 0;
3943 }
3944
3945 strm->tx.last_max_stream_data_ts = ts;
3946
3947 nfrc->fr.max_stream_data = (ngtcp2_max_stream_data){
3948 .type = NGTCP2_FRAME_MAX_STREAM_DATA,
3949 .stream_id = strm->stream_id,
3950 .max_stream_data = strm->rx.unsent_max_offset + delta,
3951 };
3952 *pfrc = nfrc;
3953
3954 strm->rx.max_offset = strm->rx.unsent_max_offset =
3955 nfrc->fr.max_stream_data.max_stream_data;
3956
3957 rv =
3958 conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &nfrc->fr);
3959 if (rv != 0) {
3960 assert(NGTCP2_ERR_NOBUF == rv);
3961 break;
3962 }
3963
3964 pkt_empty = 0;
3965 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
3966 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
3967 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
3968 pfrc = &(*pfrc)->next;
3969 }
3970
3971 if (ngtcp2_strm_streamfrq_empty(strm)) {
3972 ngtcp2_conn_tx_strmq_pop(conn);
3973 continue;
3974 }
3975
3976 stream_offset = ngtcp2_strm_streamfrq_unacked_offset(strm);
3977 if (stream_offset == (uint64_t)-1) {
3978 ngtcp2_strm_streamfrq_clear(strm);
3979 ngtcp2_conn_tx_strmq_pop(conn);
3980 continue;
3981 }
3982
3983 left = ngtcp2_ppe_left(ppe);
3984
3985 left = ngtcp2_pkt_stream_max_datalen(strm->stream_id, stream_offset,
3986 left, left);
3987
3988 if (left == (size_t)-1) {
3989 break;
3990 }
3991
3992 rv = ngtcp2_strm_streamfrq_pop(strm, &nfrc, left);
3993 if (rv != 0) {
3994 assert(ngtcp2_err_is_fatal(rv));
3995 return rv;
3996 }
3997
3998 if (nfrc == NULL) {
3999 /* TODO Why? */
4000 break;
4001 }
4002
4003 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &nfrc->fr);
4004 if (rv != 0) {
4005 ngtcp2_unreachable();
4006 }
4007
4008 *pfrc = nfrc;
4009 pfrc = &(*pfrc)->next;
4010
4011 pkt_empty = 0;
4012 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
4013 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
4014 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
4015
4016 if (ngtcp2_strm_streamfrq_empty(strm)) {
4017 ngtcp2_conn_tx_strmq_pop(conn);
4018 continue;
4019 }
4020
4021 ngtcp2_conn_tx_strmq_pop(conn);
4022 ++strm->cycle;
4023 rv = ngtcp2_conn_tx_strmq_push(conn, strm);
4024 if (rv != 0) {
4025 assert(ngtcp2_err_is_fatal(rv));
4026 return rv;
4027 }
4028 }
4029 }
4030
4031 /* Write MAX_STREAMS after RESET_STREAM so that we can extend
4032 stream ID space in one packet. */
4033 if (*pfrc == NULL &&
4034 conn->remote.bidi.unsent_max_streams > conn->remote.bidi.max_streams) {
4035 rv = conn_call_extend_max_remote_streams_bidi(
4036 conn, conn->remote.bidi.unsent_max_streams);
4037 if (rv != 0) {
4038 assert(ngtcp2_err_is_fatal(rv));
4039 return rv;
4040 }
4041
4042 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
4043 if (rv != 0) {
4044 assert(ngtcp2_err_is_fatal(rv));
4045 return rv;
4046 }
4047 nfrc->fr.max_streams = (ngtcp2_max_streams){
4048 .type = NGTCP2_FRAME_MAX_STREAMS_BIDI,
4049 .max_streams = conn->remote.bidi.unsent_max_streams,
4050 };
4051 *pfrc = nfrc;
4052
4053 conn->remote.bidi.max_streams = conn->remote.bidi.unsent_max_streams;
4054
4055 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &(*pfrc)->fr);
4056 if (rv != 0) {
4057 assert(NGTCP2_ERR_NOBUF == rv);
4058 } else {
4059 pkt_empty = 0;
4060 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
4061 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
4062 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
4063 pfrc = &(*pfrc)->next;
4064 }
4065 }
4066
4067 if (*pfrc == NULL &&
4068 conn->remote.uni.unsent_max_streams > conn->remote.uni.max_streams) {
4069 rv = conn_call_extend_max_remote_streams_uni(
4070 conn, conn->remote.uni.unsent_max_streams);
4071 if (rv != 0) {
4072 assert(ngtcp2_err_is_fatal(rv));
4073 return rv;
4074 }
4075
4076 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
4077 if (rv != 0) {
4078 assert(ngtcp2_err_is_fatal(rv));
4079 return rv;
4080 }
4081 nfrc->fr.max_streams = (ngtcp2_max_streams){
4082 .type = NGTCP2_FRAME_MAX_STREAMS_UNI,
4083 .max_streams = conn->remote.uni.unsent_max_streams,
4084 };
4085 *pfrc = nfrc;
4086
4087 conn->remote.uni.max_streams = conn->remote.uni.unsent_max_streams;
4088
4089 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &(*pfrc)->fr);
4090 if (rv != 0) {
4091 assert(NGTCP2_ERR_NOBUF == rv);
4092 } else {
4093 pkt_empty = 0;
4094 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
4095 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
4096 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
4097 pfrc = &(*pfrc)->next;
4098 }
4099 }
4100
4101 if (pktns->tx.frq == NULL && !send_stream && !send_datagram &&
4102 !(rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) &&
4103 pktns->rtb.num_retransmittable && pktns->rtb.probe_pkt_left) {
4104 num_reclaimed = ngtcp2_rtb_reclaim_on_pto(&pktns->rtb, conn, pktns, 1);
4105 if (num_reclaimed < 0) {
4106 return num_reclaimed;
4107 }
4108 if (num_reclaimed) {
4109 goto build_pkt;
4110 }
4111
4112 /* We had pktns->rtb.num_retransmittable > 0 but we were unable
4113 to reclaim any frame. In this case, we do not have to send
4114 any probe packet. */
4115 if (pktns->rtb.num_pto_eliciting == 0) {
4116 pktns->rtb.probe_pkt_left = 0;
4117 ngtcp2_conn_set_loss_detection_timer(conn, ts);
4118
4119 if (pkt_empty && conn_cwnd_is_zero(conn) && !require_padding) {
4120 return 0;
4121 }
4122 }
4123 }
4124 } else {
4125 pfrc = conn->pkt.pfrc;
4126 rtb_entry_flags |= conn->pkt.rtb_entry_flags;
4127 pkt_empty = conn->pkt.pkt_empty;
4128 hd_logged = conn->pkt.hd_logged;
4129 require_padding = conn->pkt.require_padding;
4130 }
4131
4132 left = ngtcp2_ppe_left(ppe);
4133
4134 if (*pfrc == NULL && send_stream && ngtcp2_pq_empty(&conn->tx.strmq) &&
4135 (wdatalen = ngtcp2_pkt_stream_max_datalen(
4136 vmsg->stream.strm->stream_id, vmsg->stream.strm->tx.offset, ndatalen,
4137 left)) != (size_t)-1 &&
4138 (wdatalen == ndatalen || wdatalen >= NGTCP2_MIN_STREAM_DATALEN) &&
4139 (wdatalen || datalen == 0)) {
4140 ndatalen = wdatalen;
4141 datacnt = ngtcp2_vec_copy_at_most(data, NGTCP2_MAX_STREAM_DATACNT,
4142 vmsg->stream.data, vmsg->stream.datacnt,
4143 (size_t)ndatalen);
4144 ndatalen = ngtcp2_vec_len(data, datacnt);
4145
4146 assert((datacnt == 0 && datalen == 0) || (datacnt && datalen));
4147
4148 rv = ngtcp2_frame_chain_stream_datacnt_objalloc_new(
4149 &nfrc, datacnt, &conn->frc_objalloc, conn->mem);
4150 if (rv != 0) {
4151 assert(ngtcp2_err_is_fatal(rv));
4152 return rv;
4153 }
4154
4155 nfrc->fr.stream.type = NGTCP2_FRAME_STREAM;
4156 nfrc->fr.stream.flags = 0;
4157 nfrc->fr.stream.fin = 0;
4158 nfrc->fr.stream.stream_id = vmsg->stream.strm->stream_id;
4159 nfrc->fr.stream.offset = vmsg->stream.strm->tx.offset;
4160 nfrc->fr.stream.datacnt = datacnt;
4161 ngtcp2_vec_copy(nfrc->fr.stream.data, data, datacnt);
4162
4163 nfrc->fr.stream.fin = (vmsg->stream.flags & NGTCP2_WRITE_STREAM_FLAG_FIN) &&
4164 ndatalen == datalen;
4165
4166 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &nfrc->fr);
4167 if (rv != 0) {
4168 ngtcp2_unreachable();
4169 }
4170
4171 *pfrc = nfrc;
4172 pfrc = &(*pfrc)->next;
4173
4174 pkt_empty = 0;
4175 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
4176 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
4177 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
4178
4179 vmsg->stream.strm->tx.offset += ndatalen;
4180 conn->tx.offset += ndatalen;
4181 vmsg->stream.strm->flags |= NGTCP2_STRM_FLAG_ANY_SENT;
4182
4183 if (nfrc->fr.stream.fin) {
4184 ngtcp2_strm_shutdown(vmsg->stream.strm, NGTCP2_STRM_FLAG_SHUT_WR);
4185 }
4186
4187 if (vmsg->stream.pdatalen) {
4188 *vmsg->stream.pdatalen = (ngtcp2_ssize)ndatalen;
4189 }
4190 } else {
4191 send_stream = 0;
4192 }
4193
4194 if (vmsg && vmsg->type == NGTCP2_VMSG_TYPE_STREAM &&
4195 ((stream_blocked && *pfrc == NULL) ||
4196 (send_stream &&
4197 !(vmsg->stream.strm->flags & NGTCP2_STRM_FLAG_SHUT_WR)))) {
4198 if (conn_should_send_data_blocked(conn)) {
4199 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
4200 if (rv != 0) {
4201 assert(ngtcp2_err_is_fatal(rv));
4202
4203 return rv;
4204 }
4205
4206 nfrc->fr.data_blocked = (ngtcp2_data_blocked){
4207 .type = NGTCP2_FRAME_DATA_BLOCKED,
4208 .offset = conn->tx.offset,
4209 };
4210
4211 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &nfrc->fr);
4212 if (rv != 0) {
4213 assert(NGTCP2_ERR_NOBUF == rv);
4214
4215 /* We cannot add nfrc to pktns->tx.frq here. */
4216 ngtcp2_frame_chain_objalloc_del(nfrc, &conn->frc_objalloc, conn->mem);
4217 } else {
4218 *pfrc = nfrc;
4219 pfrc = &(*pfrc)->next;
4220
4221 pkt_empty = 0;
4222 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
4223 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
4224 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
4225
4226 conn->tx.last_blocked_offset = conn->tx.max_offset;
4227 }
4228 }
4229
4230 strm = vmsg->stream.strm;
4231
4232 if (strm_should_send_stream_data_blocked(strm)) {
4233 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
4234 if (rv != 0) {
4235 assert(ngtcp2_err_is_fatal(rv));
4236
4237 return rv;
4238 }
4239
4240 nfrc->fr.stream_data_blocked = (ngtcp2_stream_data_blocked){
4241 .type = NGTCP2_FRAME_STREAM_DATA_BLOCKED,
4242 .stream_id = strm->stream_id,
4243 .offset = strm->tx.max_offset,
4244 };
4245
4246 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &nfrc->fr);
4247 if (rv != 0) {
4248 assert(NGTCP2_ERR_NOBUF == rv);
4249
4250 /* We cannot add nfrc to pktns->tx.frq here. */
4251 ngtcp2_frame_chain_objalloc_del(nfrc, &conn->frc_objalloc, conn->mem);
4252
4253 if (!ngtcp2_strm_is_tx_queued(strm)) {
4254 strm->cycle = conn_tx_strmq_first_cycle(conn);
4255 rv = ngtcp2_conn_tx_strmq_push(conn, strm);
4256 if (rv != 0) {
4257 return rv;
4258 }
4259 }
4260 } else {
4261 *pfrc = nfrc;
4262 pfrc = &(*pfrc)->next;
4263
4264 pkt_empty = 0;
4265 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
4266 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
4267 NGTCP2_RTB_ENTRY_FLAG_RETRANSMITTABLE;
4268
4269 strm->tx.last_blocked_offset = strm->tx.max_offset;
4270 }
4271 }
4272 }
4273
4274 if (*pfrc == NULL && send_datagram &&
4275 left >= ngtcp2_pkt_datagram_framelen((size_t)datalen)) {
4276 if (conn->callbacks.ack_datagram || conn->callbacks.lost_datagram) {
4277 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
4278 if (rv != 0) {
4279 assert(ngtcp2_err_is_fatal(rv));
4280 return rv;
4281 }
4282
4283 nfrc->fr.datagram.type = NGTCP2_FRAME_DATAGRAM_LEN;
4284 nfrc->fr.datagram.dgram_id = vmsg->datagram.dgram_id;
4285 nfrc->fr.datagram.datacnt = vmsg->datagram.datacnt;
4286 nfrc->fr.datagram.data = (ngtcp2_vec *)vmsg->datagram.data;
4287
4288 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &nfrc->fr);
4289 assert(rv == 0);
4290
4291 /* Because DATAGRAM will not be retransmitted, we do not use
4292 data anymore. Just nullify it. The only reason to keep
4293 track a frame is keep dgram_id to pass it to
4294 ngtcp2_ack_datagram or ngtcp2_lost_datagram callbacks. */
4295 nfrc->fr.datagram.datacnt = 0;
4296 nfrc->fr.datagram.data = NULL;
4297
4298 *pfrc = nfrc;
4299 pfrc = &(*pfrc)->next;
4300 } else {
4301 lfr.datagram.type = NGTCP2_FRAME_DATAGRAM_LEN;
4302 lfr.datagram.datacnt = vmsg->datagram.datacnt;
4303 lfr.datagram.data = (ngtcp2_vec *)vmsg->datagram.data;
4304
4305 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &lfr);
4306 assert(rv == 0);
4307 }
4308
4309 pkt_empty = 0;
4310 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING |
4311 NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
4312 NGTCP2_RTB_ENTRY_FLAG_DATAGRAM;
4313
4314 if (vmsg->datagram.paccepted) {
4315 *vmsg->datagram.paccepted = 1;
4316 }
4317 } else {
4318 send_datagram = 0;
4319 }
4320
4321 if (pkt_empty) {
4322 if (*pfrc == NULL && rv == 0 && stream_blocked &&
4323 (write_more || !require_padding) &&
4324 ngtcp2_conn_get_max_data_left(conn)) {
4325 if (write_more) {
4326 conn->pkt.pfrc = pfrc;
4327 conn->pkt.pkt_empty = pkt_empty;
4328 conn->pkt.rtb_entry_flags = rtb_entry_flags;
4329 conn->pkt.hd_logged = hd_logged;
4330 conn->pkt.require_padding = require_padding;
4331 conn->flags |= NGTCP2_CONN_FLAG_PPE_PENDING;
4332 }
4333
4334 return NGTCP2_ERR_STREAM_DATA_BLOCKED;
4335 }
4336
4337 keep_alive_expired =
4338 type == NGTCP2_PKT_1RTT && conn_keep_alive_expired(conn, ts);
4339
4340 if (conn->pktns.rtb.probe_pkt_left == 0 && !keep_alive_expired &&
4341 !require_padding) {
4342 conn_reset_ppe_pending(conn);
4343
4344 return 0;
4345 }
4346 } else if (write_more) {
4347 conn->pkt.pfrc = pfrc;
4348 conn->pkt.pkt_empty = pkt_empty;
4349 conn->pkt.rtb_entry_flags = rtb_entry_flags;
4350 conn->pkt.hd_logged = hd_logged;
4351 conn->pkt.require_padding = require_padding;
4352 conn->flags |= NGTCP2_CONN_FLAG_PPE_PENDING;
4353
4354 assert(vmsg);
4355
4356 switch (vmsg->type) {
4357 case NGTCP2_VMSG_TYPE_STREAM:
4358 if (send_stream) {
4359 if (ngtcp2_ppe_left(ppe)) {
4360 return NGTCP2_ERR_WRITE_MORE;
4361 }
4362 break;
4363 }
4364
4365 if (*pfrc == NULL && ngtcp2_conn_get_max_data_left(conn) &&
4366 stream_blocked) {
4367 return NGTCP2_ERR_STREAM_DATA_BLOCKED;
4368 }
4369 break;
4370 case NGTCP2_VMSG_TYPE_DATAGRAM:
4371 if (send_datagram && ngtcp2_ppe_left(ppe)) {
4372 return NGTCP2_ERR_WRITE_MORE;
4373 }
4374 /* If DATAGRAM cannot be written due to insufficient space,
4375 continue to create a packet with the hope that application
4376 calls ngtcp2_conn_writev_datagram again. */
4377 break;
4378 default:
4379 ngtcp2_unreachable();
4380 }
4381 }
4382
4383 if (!(rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING)) {
4384 if (ngtcp2_tstamp_elapsed(pktns->tx.non_ack_pkt_start_ts,
4385 cstat->smoothed_rtt, ts) ||
4386 keep_alive_expired || conn->pktns.rtb.probe_pkt_left) {
4387 lfr.ping.type = NGTCP2_FRAME_PING;
4388
4389 rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &lfr);
4390 if (rv != 0) {
4391 assert(rv == NGTCP2_ERR_NOBUF);
4392 /* TODO If buffer is too small, PING cannot be written if
4393 packet is still empty. */
4394 } else {
4395 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING;
4396 if (conn->pktns.rtb.probe_pkt_left) {
4397 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_PROBE;
4398 } else {
4399 rtb_entry_flags |= NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING;
4400 }
4401 pktns->tx.non_ack_pkt_start_ts = UINT64_MAX;
4402 }
4403 } else if (pktns->tx.non_ack_pkt_start_ts == UINT64_MAX) {
4404 pktns->tx.non_ack_pkt_start_ts = ts;
4405 }
4406 } else {
4407 pktns->tx.non_ack_pkt_start_ts = UINT64_MAX;
4408 }
4409
4410 /* TODO Push STREAM frame back to ngtcp2_strm if there is an error
4411 before ngtcp2_rtb_entry is safely created and added. */
4412 if ((flags & (NGTCP2_WRITE_PKT_FLAG_PADDING_IF_NOT_EMPTY)) &&
4413 (rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING)) {
4414 lfr.padding.len = ngtcp2_ppe_padding_size(ppe, destlen);
4415 } else if (require_padding) {
4416 lfr.padding.len = conn_dgram_padding(conn, ppe);
4417 } else {
4418 lfr.padding.len = ngtcp2_ppe_padding_size(ppe, min_pktlen);
4419 min_padded = 1;
4420 }
4421
4422 if (lfr.padding.len) {
4423 if (!min_padded ||
4424 (rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING)) {
4425 padded = 1;
4426 }
4427 lfr.padding.type = NGTCP2_FRAME_PADDING;
4428 ngtcp2_log_tx_fr(&conn->log, hd, &lfr);
4429 ngtcp2_qlog_write_frame(&conn->qlog, &lfr);
4430 }
4431
4432 nwrite = ngtcp2_ppe_final(ppe, NULL);
4433 if (nwrite < 0) {
4434 assert(ngtcp2_err_is_fatal((int)nwrite));
4435 return nwrite;
4436 }
4437
4438 ++cc->ckm->use_count;
4439
4440 ngtcp2_qlog_pkt_sent_end(&conn->qlog, hd, (size_t)nwrite);
4441
4442 /* TODO ack-eliciting vs needs-tracking */
4443 /* probe packet needs tracking but it does not need ACK, could be lost. */
4444 if ((rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) || padded) {
4445 if (pi) {
4446 conn_handle_tx_ecn(conn, pi, &rtb_entry_flags, pktns, hd, ts);
4447 }
4448
4449 rv =
4450 ngtcp2_rtb_entry_objalloc_new(&ent, hd, NULL, ts, (size_t)nwrite,
4451 rtb_entry_flags, &conn->rtb_entry_objalloc);
4452 if (rv != 0) {
4453 assert(ngtcp2_err_is_fatal(rv));
4454 return rv;
4455 }
4456
4457 if (*pfrc != pktns->tx.frq) {
4458 ent->frc = pktns->tx.frq;
4459 pktns->tx.frq = *pfrc;
4460 *pfrc = NULL;
4461 }
4462
4463 rv = conn_on_pkt_sent(conn, pktns, ent);
4464 if (rv != 0) {
4465 assert(ngtcp2_err_is_fatal(rv));
4466 ngtcp2_rtb_entry_objalloc_del(ent, &conn->rtb_entry_objalloc,
4467 &conn->frc_objalloc, conn->mem);
4468 return rv;
4469 }
4470
4471 if ((rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) &&
4472 (conn->flags & NGTCP2_CONN_FLAG_RESTART_IDLE_TIMER_ON_WRITE)) {
4473 conn_restart_timer_on_write(conn, ts);
4474 }
4475 } else if (pi && conn->tx.ecn.state == NGTCP2_ECN_STATE_CAPABLE) {
4476 conn_handle_tx_ecn(conn, pi, NULL, pktns, hd, ts);
4477 }
4478
4479 conn_reset_ppe_pending(conn);
4480
4481 if (pktns->rtb.probe_pkt_left &&
4482 (rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING)) {
4483 --pktns->rtb.probe_pkt_left;
4484
4485 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON, "probe pkt size=%td",
4486 nwrite);
4487 }
4488
4489 conn_update_keep_alive_last_ts(conn, ts);
4490
4491 conn->dcid.current.bytes_sent += (uint64_t)nwrite;
4492
4493 conn->tx.pacing.pktlen += (size_t)nwrite;
4494
4495 ++conn->cstat.pkt_sent;
4496 conn->cstat.bytes_sent += (uint64_t)nwrite;
4497
4498 ngtcp2_qlog_metrics_updated(&conn->qlog, &conn->cstat);
4499
4500 ++pktns->tx.last_pkt_num;
4501
4502 return nwrite;
4503 }
4504
4505 ngtcp2_ssize ngtcp2_conn_write_single_frame_pkt(
4506 ngtcp2_conn *conn, ngtcp2_pkt_info *pi, uint8_t *dest, size_t destlen,
4507 uint8_t type, uint8_t flags, const ngtcp2_cid *dcid, ngtcp2_frame *fr,
4508 uint16_t rtb_entry_flags, const ngtcp2_path *path, ngtcp2_tstamp ts) {
4509 int rv;
4510 ngtcp2_ppe ppe;
4511 ngtcp2_pkt_hd hd;
4512 ngtcp2_frame lfr;
4513 ngtcp2_ssize nwrite;
4514 ngtcp2_crypto_cc cc;
4515 ngtcp2_pktns *pktns;
4516 uint8_t hd_flags;
4517 ngtcp2_rtb_entry *rtbent;
4518 int padded = 0;
4519 const ngtcp2_cid *scid;
4520 uint32_t version;
4521
4522 switch (type) {
4523 case NGTCP2_PKT_INITIAL:
4524 pktns = conn->in_pktns;
4525 hd_flags = conn_pkt_flags_long(conn);
4526 scid = &conn->oscid;
4527 version = conn->negotiated_version ? conn->negotiated_version
4528 : conn->client_chosen_version;
4529 if (version == conn->client_chosen_version) {
4530 cc.ckm = pktns->crypto.tx.ckm;
4531 cc.hp_ctx = pktns->crypto.tx.hp_ctx;
4532 } else {
4533 assert(version == conn->vneg.version);
4534
4535 cc.ckm = conn->vneg.tx.ckm;
4536 cc.hp_ctx = conn->vneg.tx.hp_ctx;
4537 }
4538 break;
4539 case NGTCP2_PKT_HANDSHAKE:
4540 pktns = conn->hs_pktns;
4541 hd_flags = conn_pkt_flags_long(conn);
4542 scid = &conn->oscid;
4543 version = conn->negotiated_version;
4544 cc.ckm = pktns->crypto.tx.ckm;
4545 cc.hp_ctx = pktns->crypto.tx.hp_ctx;
4546 break;
4547 case NGTCP2_PKT_1RTT:
4548 pktns = &conn->pktns;
4549 hd_flags = conn_pkt_flags_short(conn);
4550 scid = NULL;
4551 version = conn->negotiated_version;
4552 cc.ckm = pktns->crypto.tx.ckm;
4553 cc.hp_ctx = pktns->crypto.tx.hp_ctx;
4554
4555 rv = conn_handle_skip_pkt(conn, pktns, ts);
4556 if (rv != 0) {
4557 return rv;
4558 }
4559
4560 break;
4561 default:
4562 /* We don't support 0-RTT packet in this function. */
4563 ngtcp2_unreachable();
4564 }
4565
4566 cc.aead = pktns->crypto.ctx.aead;
4567 cc.hp = pktns->crypto.ctx.hp;
4568 cc.encrypt = conn->callbacks.encrypt;
4569 cc.hp_mask = conn->callbacks.hp_mask;
4570
4571 ngtcp2_pkt_hd_init(&hd, hd_flags, type, dcid, scid,
4572 pktns->tx.last_pkt_num + 1, pktns_select_pkt_numlen(pktns),
4573 version);
4574
4575 ngtcp2_ppe_init(&ppe, dest, destlen, 0, &cc);
4576
4577 rv = ngtcp2_ppe_encode_hd(&ppe, &hd);
4578 if (rv != 0) {
4579 assert(NGTCP2_ERR_NOBUF == rv);
4580 return 0;
4581 }
4582
4583 if (!ngtcp2_ppe_ensure_hp_sample(&ppe)) {
4584 return 0;
4585 }
4586
4587 ngtcp2_log_tx_pkt_hd(&conn->log, &hd);
4588 ngtcp2_qlog_pkt_sent_start(&conn->qlog);
4589
4590 rv = conn_ppe_write_frame(conn, &ppe, &hd, fr);
4591 if (rv != 0) {
4592 assert(NGTCP2_ERR_NOBUF == rv);
4593 return 0;
4594 }
4595
4596 lfr.padding.type = NGTCP2_FRAME_PADDING;
4597 if (flags & NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING_FULL) {
4598 lfr.padding.len = ngtcp2_ppe_dgram_padding_size(&ppe, destlen);
4599 } else if (flags & NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING) {
4600 lfr.padding.len = conn_dgram_padding(conn, &ppe);
4601 } else {
4602 switch (fr->hd.type) {
4603 case NGTCP2_FRAME_PATH_CHALLENGE:
4604 case NGTCP2_FRAME_PATH_RESPONSE:
4605 if (!conn->server || destlen >= NGTCP2_MAX_UDP_PAYLOAD_SIZE) {
4606 lfr.padding.len = conn_dgram_padding(conn, &ppe);
4607 } else {
4608 lfr.padding.len = 0;
4609 }
4610 break;
4611 default:
4612 lfr.padding.len = ngtcp2_ppe_padding_size(&ppe, conn_min_pktlen(conn));
4613 }
4614 }
4615 if (lfr.padding.len) {
4616 padded = 1;
4617 ngtcp2_log_tx_fr(&conn->log, &hd, &lfr);
4618 ngtcp2_qlog_write_frame(&conn->qlog, &lfr);
4619 }
4620
4621 nwrite = ngtcp2_ppe_final(&ppe, NULL);
4622 if (nwrite < 0) {
4623 return nwrite;
4624 }
4625
4626 if (type == NGTCP2_PKT_1RTT) {
4627 ++cc.ckm->use_count;
4628 }
4629
4630 ngtcp2_qlog_pkt_sent_end(&conn->qlog, &hd, (size_t)nwrite);
4631
4632 /* Do this when we are sure that there is no error. */
4633 switch (fr->hd.type) {
4634 case NGTCP2_FRAME_ACK:
4635 case NGTCP2_FRAME_ACK_ECN:
4636 ngtcp2_acktr_commit_ack(&pktns->acktr);
4637 ngtcp2_acktr_add_ack(&pktns->acktr, hd.pkt_num, fr->ack.largest_ack);
4638 if (type == NGTCP2_PKT_1RTT) {
4639 conn_handle_unconfirmed_key_update_from_remote(conn, fr->ack.largest_ack,
4640 ts);
4641 }
4642
4643 if (!(flags & (NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING_FULL |
4644 NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING))) {
4645 padded = 0;
4646 }
4647
4648 break;
4649 case NGTCP2_FRAME_CONNECTION_CLOSE:
4650 case NGTCP2_FRAME_CONNECTION_CLOSE_APP:
4651 /* Clear padded so that we never store the terminal packet in
4652 ngtcp2_rtb. */
4653 padded = 0;
4654
4655 break;
4656 }
4657
4658 if (((rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) || padded) &&
4659 (!path || ngtcp2_path_eq(&conn->dcid.current.ps.path, path))) {
4660 if (pi && (conn->tx.ecn.state == NGTCP2_ECN_STATE_CAPABLE ||
4661 !(rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_PMTUD_PROBE))) {
4662 conn_handle_tx_ecn(conn, pi, &rtb_entry_flags, pktns, &hd, ts);
4663 }
4664
4665 rv =
4666 ngtcp2_rtb_entry_objalloc_new(&rtbent, &hd, NULL, ts, (size_t)nwrite,
4667 rtb_entry_flags, &conn->rtb_entry_objalloc);
4668 if (rv != 0) {
4669 return rv;
4670 }
4671
4672 rv = conn_on_pkt_sent(conn, pktns, rtbent);
4673 if (rv != 0) {
4674 ngtcp2_rtb_entry_objalloc_del(rtbent, &conn->rtb_entry_objalloc,
4675 &conn->frc_objalloc, conn->mem);
4676 return rv;
4677 }
4678
4679 if (rtb_entry_flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING) {
4680 if (conn->flags & NGTCP2_CONN_FLAG_RESTART_IDLE_TIMER_ON_WRITE) {
4681 conn_restart_timer_on_write(conn, ts);
4682 }
4683
4684 if (pktns->rtb.probe_pkt_left && path &&
4685 ngtcp2_path_eq(&conn->dcid.current.ps.path, path)) {
4686 --pktns->rtb.probe_pkt_left;
4687
4688 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON, "probe pkt size=%td",
4689 nwrite);
4690 }
4691 }
4692 } else if (pi && conn->tx.ecn.state == NGTCP2_ECN_STATE_CAPABLE) {
4693 conn_handle_tx_ecn(conn, pi, NULL, pktns, &hd, ts);
4694 }
4695
4696 if (path && ngtcp2_path_eq(&conn->dcid.current.ps.path, path)) {
4697 conn_update_keep_alive_last_ts(conn, ts);
4698 }
4699
4700 if (!padded) {
4701 switch (fr->hd.type) {
4702 case NGTCP2_FRAME_ACK:
4703 case NGTCP2_FRAME_ACK_ECN:
4704 break;
4705 default:
4706 conn->tx.pacing.pktlen += (size_t)nwrite;
4707 }
4708 } else {
4709 conn->tx.pacing.pktlen += (size_t)nwrite;
4710 }
4711
4712 ++conn->cstat.pkt_sent;
4713 conn->cstat.bytes_sent += (uint64_t)nwrite;
4714
4715 ngtcp2_qlog_metrics_updated(&conn->qlog, &conn->cstat);
4716
4717 ++pktns->tx.last_pkt_num;
4718
4719 return nwrite;
4720 }
4721
4722 /*
4723 * conn_process_early_rtb makes any pending 0RTT packet 1RTT packet.
4724 */
4725 static void conn_process_early_rtb(ngtcp2_conn *conn) {
4726 ngtcp2_rtb_entry *ent;
4727 ngtcp2_rtb *rtb = &conn->pktns.rtb;
4728 ngtcp2_ksl_it it;
4729
4730 for (it = ngtcp2_rtb_head(rtb); !ngtcp2_ksl_it_end(&it);
4731 ngtcp2_ksl_it_next(&it)) {
4732 ent = ngtcp2_ksl_it_get(&it);
4733
4734 if ((ent->hd.flags & NGTCP2_PKT_FLAG_LONG_FORM) == 0 ||
4735 ent->hd.type != NGTCP2_PKT_0RTT) {
4736 continue;
4737 }
4738
4739 /* 0-RTT packet is retransmitted as a 1RTT packet. */
4740 ent->hd.flags &= (uint8_t)~NGTCP2_PKT_FLAG_LONG_FORM;
4741 ent->hd.type = NGTCP2_PKT_1RTT;
4742 }
4743 }
4744
4745 /*
4746 * conn_handshake_remnants_left returns nonzero if there may be
4747 * handshake packets the local endpoint has to send, including new
4748 * packets and lost ones.
4749 */
4750 static int conn_handshake_remnants_left(ngtcp2_conn *conn) {
4751 ngtcp2_pktns *in_pktns = conn->in_pktns;
4752 ngtcp2_pktns *hs_pktns = conn->hs_pktns;
4753
4754 return !conn_is_tls_handshake_completed(conn) ||
4755 (in_pktns && (in_pktns->rtb.num_pto_eliciting ||
4756 !ngtcp2_strm_streamfrq_empty(&in_pktns->crypto.strm))) ||
4757 (hs_pktns && (hs_pktns->rtb.num_pto_eliciting ||
4758 !ngtcp2_strm_streamfrq_empty(&hs_pktns->crypto.strm)));
4759 }
4760
4761 /*
4762 * conn_enqueue_retire_connection_id enqueues RETIRE_CONNECTION_ID
4763 * frame with |seq|.
4764 *
4765 * This function returns 0 if it succeeds, or one of the following
4766 * negative error codes:
4767 *
4768 * NGTCP2_ERR_NOMEM
4769 * Out of memory.
4770 */
4771 static int conn_enqueue_retire_connection_id(ngtcp2_conn *conn, uint64_t seq) {
4772 ngtcp2_pktns *pktns = &conn->pktns;
4773 ngtcp2_frame_chain *nfrc;
4774 int rv;
4775
4776 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
4777 if (rv != 0) {
4778 return rv;
4779 }
4780
4781 nfrc->fr.retire_connection_id = (ngtcp2_retire_connection_id){
4782 .type = NGTCP2_FRAME_RETIRE_CONNECTION_ID,
4783 .seq = seq,
4784 };
4785 nfrc->next = pktns->tx.frq;
4786 pktns->tx.frq = nfrc;
4787
4788 return 0;
4789 }
4790
4791 static int dcidtr_on_retire(const ngtcp2_dcid *dcid, void *user_data) {
4792 return conn_enqueue_retire_connection_id(user_data, dcid->seq);
4793 }
4794
4795 /*
4796 * conn_retire_active_dcid retires the activated |dcid|.
4797 *
4798 * This function returns 0 if it succeeds, or one of the following
4799 * negative error codes:
4800 *
4801 * NGTCP2_ERR_NOMEM
4802 * Out of memory
4803 */
4804 static int conn_retire_active_dcid(ngtcp2_conn *conn, const ngtcp2_dcid *dcid,
4805 ngtcp2_tstamp ts) {
4806 int rv;
4807
4808 assert(dcid->cid.datalen);
4809
4810 rv = ngtcp2_dcidtr_retire_active_dcid(&conn->dcid.dtr, dcid, ts,
4811 dcidtr_on_deactivate, conn);
4812 if (rv != 0) {
4813 return rv;
4814 }
4815
4816 return conn_enqueue_retire_connection_id(conn, dcid->seq);
4817 }
4818
4819 /*
4820 * conn_bind_dcid stores the DCID to |*pdcid| bound to |path|. If
4821 * such DCID is not found, bind the new DCID to |path| and stores it
4822 * to |*pdcid|. If a remote endpoint uses zero-length connection ID,
4823 * the pointer to conn->dcid.current is assigned to |*pdcid|.
4824 *
4825 * This function returns 0 if it succeeds, or one of the following
4826 * negative error codes:
4827 *
4828 * NGTCP2_ERR_CONN_ID_BLOCKED
4829 * No unused DCID is available
4830 * NGTCP2_ERR_NOMEM
4831 * Out of memory
4832 */
4833 static int conn_bind_dcid(ngtcp2_conn *conn, ngtcp2_dcid **pdcid,
4834 const ngtcp2_path *path, ngtcp2_tstamp ts) {
4835 assert(!ngtcp2_path_eq(&conn->dcid.current.ps.path, path));
4836 assert(!conn->pv || !ngtcp2_path_eq(&conn->pv->dcid.ps.path, path));
4837 assert(!conn->pv || !(conn->pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) ||
4838 !ngtcp2_path_eq(&conn->pv->fallback_dcid.ps.path, path));
4839
4840 *pdcid = ngtcp2_dcidtr_find_bound_dcid(&conn->dcid.dtr, path);
4841 if (*pdcid) {
4842 return 0;
4843 }
4844
4845 if (conn->dcid.current.cid.datalen == 0) {
4846 *pdcid = ngtcp2_dcidtr_bind_zerolen_dcid(&conn->dcid.dtr, path);
4847
4848 return 0;
4849 }
4850
4851 if (ngtcp2_dcidtr_unused_empty(&conn->dcid.dtr)) {
4852 return NGTCP2_ERR_CONN_ID_BLOCKED;
4853 }
4854
4855 return ngtcp2_dcidtr_bind_dcid(&conn->dcid.dtr, pdcid, path, ts,
4856 dcidtr_on_retire, conn);
4857 }
4858
4859 static int conn_start_pmtud(ngtcp2_conn *conn) {
4860 int rv;
4861 size_t hard_max_udp_payload_size;
4862
4863 assert(!conn->local.settings.no_pmtud);
4864 assert(!conn->pmtud);
4865 assert(conn_is_tls_handshake_completed(conn));
4866 assert(conn->remote.transport_params);
4867 assert(conn->remote.transport_params->max_udp_payload_size >=
4868 NGTCP2_MAX_UDP_PAYLOAD_SIZE);
4869
4870 hard_max_udp_payload_size = (size_t)ngtcp2_min_uint64(
4871 conn->remote.transport_params->max_udp_payload_size,
4872 (uint64_t)conn->local.settings.max_tx_udp_payload_size);
4873
4874 rv =
4875 ngtcp2_pmtud_new(&conn->pmtud, conn->dcid.current.max_udp_payload_size,
4876 hard_max_udp_payload_size, conn->pktns.tx.last_pkt_num + 1,
4877 conn->local.settings.pmtud_probes,
4878 conn->local.settings.pmtud_probeslen, conn->mem);
4879 if (rv != 0) {
4880 return rv;
4881 }
4882
4883 if (ngtcp2_pmtud_finished(conn->pmtud)) {
4884 ngtcp2_conn_stop_pmtud(conn);
4885 }
4886
4887 return 0;
4888 }
4889
4890 int ngtcp2_conn_start_pmtud(ngtcp2_conn *conn) {
4891 return conn_start_pmtud(conn);
4892 }
4893
4894 void ngtcp2_conn_stop_pmtud(ngtcp2_conn *conn) {
4895 if (!conn->pmtud) {
4896 return;
4897 }
4898
4899 ngtcp2_pmtud_del(conn->pmtud);
4900
4901 conn->pmtud = NULL;
4902 }
4903
4904 static ngtcp2_ssize conn_write_pmtud_probe(ngtcp2_conn *conn,
4905 ngtcp2_pkt_info *pi, uint8_t *dest,
4906 size_t destlen, ngtcp2_tstamp ts) {
4907 size_t probelen;
4908 ngtcp2_ssize nwrite;
4909 ngtcp2_frame lfr;
4910
4911 assert(conn->pmtud);
4912 assert(!ngtcp2_pmtud_finished(conn->pmtud));
4913
4914 if (!ngtcp2_pmtud_require_probe(conn->pmtud)) {
4915 return 0;
4916 }
4917
4918 probelen = ngtcp2_pmtud_probelen(conn->pmtud);
4919 if (probelen > destlen) {
4920 return 0;
4921 }
4922
4923 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON,
4924 "sending PMTUD probe packet len=%zu", probelen);
4925
4926 lfr.ping.type = NGTCP2_FRAME_PING;
4927
4928 nwrite = ngtcp2_conn_write_single_frame_pkt(
4929 conn, pi, dest, probelen, NGTCP2_PKT_1RTT,
4930 NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING_FULL, &conn->dcid.current.cid, &lfr,
4931 NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING | NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING |
4932 NGTCP2_RTB_ENTRY_FLAG_PMTUD_PROBE,
4933 NULL, ts);
4934 if (nwrite < 0) {
4935 return nwrite;
4936 }
4937
4938 assert(nwrite);
4939
4940 ngtcp2_pmtud_probe_sent(conn->pmtud, conn_compute_pto(conn, &conn->pktns),
4941 ts);
4942
4943 return nwrite;
4944 }
4945
4946 /*
4947 * conn_stop_pv stops the path validation which is currently running.
4948 * This function does nothing if no path validation is currently being
4949 * performed.
4950 *
4951 * This function returns 0 if it succeeds, or one of the following
4952 * negative error codes:
4953 *
4954 * NGTCP2_ERR_NOMEM
4955 * Out of memory
4956 */
4957 static int conn_stop_pv(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
4958 int rv = 0;
4959 ngtcp2_pv *pv = conn->pv;
4960
4961 if (pv == NULL) {
4962 return 0;
4963 }
4964
4965 if (pv->dcid.cid.datalen && pv->dcid.seq != conn->dcid.current.seq) {
4966 rv = conn_retire_active_dcid(conn, &pv->dcid, ts);
4967 if (rv != 0) {
4968 goto fin;
4969 }
4970 }
4971
4972 if ((pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) &&
4973 pv->fallback_dcid.cid.datalen &&
4974 pv->fallback_dcid.seq != conn->dcid.current.seq &&
4975 pv->fallback_dcid.seq != pv->dcid.seq) {
4976 rv = conn_retire_active_dcid(conn, &pv->fallback_dcid, ts);
4977 if (rv != 0) {
4978 goto fin;
4979 }
4980 }
4981
4982 fin:
4983 ngtcp2_pv_del(pv);
4984 conn->pv = NULL;
4985
4986 return rv;
4987 }
4988
4989 /*
4990 * conn_abort_pv aborts the current path validation and frees
4991 * resources allocated for it. This function assumes that conn->pv is
4992 * not NULL.
4993 *
4994 * This function returns 0 if it succeeds, or one of the following
4995 * negative error codes:
4996 *
4997 * NGTCP2_ERR_NOMEM
4998 * Out of memory
4999 * NGTCP2_ERR_CALLBACK_FAILURE
5000 * User-defined callback function failed.
5001 */
5002 static int conn_abort_pv(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
5003 ngtcp2_pv *pv = conn->pv;
5004 int rv;
5005
5006 assert(pv);
5007
5008 if (!(pv->flags & NGTCP2_PV_FLAG_DONT_CARE)) {
5009 rv = conn_call_path_validation(conn, pv,
5010 NGTCP2_PATH_VALIDATION_RESULT_ABORTED);
5011 if (rv != 0) {
5012 return rv;
5013 }
5014 }
5015
5016 return conn_stop_pv(conn, ts);
5017 }
5018
5019 static size_t conn_shape_udp_payload(ngtcp2_conn *conn, const ngtcp2_dcid *dcid,
5020 size_t payloadlen) {
5021 if (conn->remote.transport_params &&
5022 conn->remote.transport_params->max_udp_payload_size) {
5023 assert(conn->remote.transport_params->max_udp_payload_size >=
5024 NGTCP2_MAX_UDP_PAYLOAD_SIZE);
5025
5026 payloadlen = (size_t)ngtcp2_min_uint64(
5027 (uint64_t)payloadlen,
5028 conn->remote.transport_params->max_udp_payload_size);
5029 }
5030
5031 payloadlen =
5032 ngtcp2_min_size(payloadlen, conn->local.settings.max_tx_udp_payload_size);
5033
5034 if (conn->local.settings.no_tx_udp_payload_size_shaping) {
5035 return payloadlen;
5036 }
5037
5038 return ngtcp2_min_size(payloadlen, dcid->max_udp_payload_size);
5039 }
5040
5041 static void conn_reset_congestion_state(ngtcp2_conn *conn, ngtcp2_tstamp ts);
5042
5043 /*
5044 * conn_on_path_validation_failed is called when path validation
5045 * fails. This function may delete |pv|.
5046 *
5047 * This function returns 0 if it succeeds, or one of the following
5048 * negative error codes:
5049 *
5050 * NGTCP2_ERR_NOMEM
5051 * Out of memory
5052 * NGTCP2_ERR_CALLBACK_FAILURE
5053 * User-defined callback function failed.
5054 */
5055 static int conn_on_path_validation_failed(ngtcp2_conn *conn, ngtcp2_pv *pv,
5056 ngtcp2_tstamp ts) {
5057 int rv;
5058
5059 if (!(pv->flags & NGTCP2_PV_FLAG_DONT_CARE)) {
5060 rv = conn_call_path_validation(conn, pv,
5061 NGTCP2_PATH_VALIDATION_RESULT_FAILURE);
5062 if (rv != 0) {
5063 return rv;
5064 }
5065 }
5066
5067 if (pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) {
5068 ngtcp2_dcid_copy(&conn->dcid.current, &pv->fallback_dcid);
5069 conn_reset_congestion_state(conn, ts);
5070 }
5071
5072 return conn_stop_pv(conn, ts);
5073 }
5074
5075 /*
5076 * conn_write_path_challenge writes a packet which includes
5077 * PATH_CHALLENGE frame into |dest| of length |destlen|.
5078 *
5079 * This function returns the number of bytes written to |dest|, or one
5080 * of the following negative error codes:
5081 *
5082 * NGTCP2_ERR_NOMEM
5083 * Out of memory
5084 * NGTCP2_ERR_CALLBACK_FAILURE
5085 * User-defined callback function failed.
5086 */
5087 static ngtcp2_ssize conn_write_path_challenge(ngtcp2_conn *conn,
5088 ngtcp2_path *path,
5089 ngtcp2_pkt_info *pi,
5090 uint8_t *dest, size_t destlen,
5091 ngtcp2_tstamp ts) {
5092 ngtcp2_ssize nwrite;
5093 ngtcp2_tstamp expiry;
5094 ngtcp2_pv *pv = conn->pv;
5095 ngtcp2_frame lfr;
5096 ngtcp2_duration timeout, initial_pto;
5097 uint8_t flags;
5098 uint64_t tx_left;
5099 int rv;
5100
5101 if (ngtcp2_pv_validation_timed_out(pv, ts)) {
5102 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PTV,
5103 "path validation was timed out");
5104 rv = conn_on_path_validation_failed(conn, pv, ts);
5105 if (rv != 0) {
5106 return rv;
5107 }
5108
5109 /* We might set path to the one which we just failed validate.
5110 Set it to the current path here. */
5111 if (path) {
5112 ngtcp2_path_copy(path, &conn->dcid.current.ps.path);
5113 }
5114
5115 return 0;
5116 }
5117
5118 ngtcp2_pv_handle_entry_expiry(pv, ts);
5119
5120 if (!ngtcp2_pv_should_send_probe(pv)) {
5121 return 0;
5122 }
5123
5124 rv = conn_call_get_path_challenge_data(conn, lfr.path_challenge.data);
5125 if (rv != 0) {
5126 return rv;
5127 }
5128
5129 lfr.path_challenge.type = NGTCP2_FRAME_PATH_CHALLENGE;
5130
5131 initial_pto = conn_compute_initial_pto(conn, &conn->pktns);
5132 timeout = conn_compute_pto(conn, &conn->pktns);
5133 timeout = ngtcp2_max_uint64(timeout, initial_pto);
5134 expiry = ts + timeout * (1ULL << pv->round);
5135
5136 destlen = ngtcp2_min_size(destlen, NGTCP2_MAX_UDP_PAYLOAD_SIZE);
5137
5138 if (conn->server) {
5139 if (!(pv->dcid.flags & NGTCP2_DCID_FLAG_PATH_VALIDATED)) {
5140 tx_left = conn_server_tx_left(conn, &pv->dcid);
5141 destlen = (size_t)ngtcp2_min_uint64((uint64_t)destlen, tx_left);
5142 if (destlen == 0) {
5143 return 0;
5144 }
5145 }
5146
5147 if (destlen < NGTCP2_MAX_UDP_PAYLOAD_SIZE) {
5148 flags = NGTCP2_PV_ENTRY_FLAG_UNDERSIZED;
5149 } else {
5150 flags = NGTCP2_PV_ENTRY_FLAG_NONE;
5151 }
5152 } else {
5153 flags = NGTCP2_PV_ENTRY_FLAG_NONE;
5154 }
5155
5156 ngtcp2_pv_add_entry(pv, lfr.path_challenge.data, expiry, flags, ts);
5157
5158 nwrite = ngtcp2_conn_write_single_frame_pkt(
5159 conn, pi, dest, destlen, NGTCP2_PKT_1RTT, NGTCP2_WRITE_PKT_FLAG_NONE,
5160 &pv->dcid.cid, &lfr,
5161 NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING | NGTCP2_RTB_ENTRY_FLAG_PTO_ELICITING,
5162 &pv->dcid.ps.path, ts);
5163 if (nwrite <= 0) {
5164 return nwrite;
5165 }
5166
5167 if (path) {
5168 ngtcp2_path_copy(path, &pv->dcid.ps.path);
5169 }
5170
5171 if (ngtcp2_path_eq(&pv->dcid.ps.path, &conn->dcid.current.ps.path)) {
5172 conn->dcid.current.bytes_sent += (uint64_t)nwrite;
5173 } else {
5174 pv->dcid.bytes_sent += (uint64_t)nwrite;
5175 }
5176
5177 return nwrite;
5178 }
5179
5180 /*
5181 * conn_write_path_response writes a packet which includes
5182 * PATH_RESPONSE frame into |dest| of length |destlen|.
5183 *
5184 * This function returns the number of bytes written to |dest|, or one
5185 * of the following negative error codes:
5186 *
5187 * NGTCP2_ERR_NOMEM
5188 * Out of memory
5189 * NGTCP2_ERR_CALLBACK_FAILURE
5190 * User-defined callback function failed.
5191 */
5192 static ngtcp2_ssize conn_write_path_response(ngtcp2_conn *conn,
5193 ngtcp2_path *path,
5194 ngtcp2_pkt_info *pi, uint8_t *dest,
5195 size_t destlen, ngtcp2_tstamp ts) {
5196 ngtcp2_pv *pv = conn->pv;
5197 ngtcp2_path_challenge_entry *pcent = NULL;
5198 ngtcp2_dcid *dcid = NULL;
5199 ngtcp2_frame lfr;
5200 ngtcp2_ssize nwrite;
5201 int rv;
5202 uint64_t tx_left;
5203
5204 for (; ngtcp2_ringbuf_len(&conn->rx.path_challenge.rb);) {
5205 pcent = ngtcp2_ringbuf_get(&conn->rx.path_challenge.rb, 0);
5206
5207 if (ngtcp2_path_eq(&conn->dcid.current.ps.path, &pcent->ps.path)) {
5208 /* Send PATH_RESPONSE from conn_write_pkt. */
5209 return 0;
5210 }
5211
5212 if (pv) {
5213 if (ngtcp2_path_eq(&pv->dcid.ps.path, &pcent->ps.path)) {
5214 dcid = &pv->dcid;
5215 break;
5216 }
5217 if ((pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) &&
5218 ngtcp2_path_eq(&pv->fallback_dcid.ps.path, &pcent->ps.path)) {
5219 dcid = &pv->fallback_dcid;
5220 break;
5221 }
5222 }
5223
5224 if (conn->server) {
5225 break;
5226 }
5227
5228 /* Client does not expect to respond to path validation against
5229 unknown path */
5230 ngtcp2_ringbuf_pop_front(&conn->rx.path_challenge.rb);
5231 pcent = NULL;
5232 }
5233
5234 if (pcent == NULL) {
5235 return 0;
5236 }
5237
5238 if (dcid == NULL) {
5239 /* client is expected to have |path| in conn->dcid.current or
5240 conn->pv. */
5241 assert(conn->server);
5242
5243 rv = conn_bind_dcid(conn, &dcid, &pcent->ps.path, ts);
5244 if (rv != 0) {
5245 if (ngtcp2_err_is_fatal(rv)) {
5246 return rv;
5247 }
5248 return 0;
5249 }
5250 }
5251
5252 destlen = ngtcp2_min_size(destlen, NGTCP2_MAX_UDP_PAYLOAD_SIZE);
5253
5254 if (conn->server && !(dcid->flags & NGTCP2_DCID_FLAG_PATH_VALIDATED)) {
5255 tx_left = conn_server_tx_left(conn, dcid);
5256 destlen = (size_t)ngtcp2_min_uint64((uint64_t)destlen, tx_left);
5257 if (destlen == 0) {
5258 return 0;
5259 }
5260 }
5261
5262 lfr.path_response.type = NGTCP2_FRAME_PATH_RESPONSE;
5263 memcpy(lfr.path_response.data, pcent->data, sizeof(lfr.path_response.data));
5264
5265 nwrite = ngtcp2_conn_write_single_frame_pkt(
5266 conn, pi, dest, destlen, NGTCP2_PKT_1RTT, NGTCP2_WRITE_PKT_FLAG_NONE,
5267 &dcid->cid, &lfr, NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING, &pcent->ps.path, ts);
5268 if (nwrite <= 0) {
5269 return nwrite;
5270 }
5271
5272 if (path) {
5273 ngtcp2_path_copy(path, &pcent->ps.path);
5274 }
5275
5276 ngtcp2_ringbuf_pop_front(&conn->rx.path_challenge.rb);
5277
5278 dcid->bytes_sent += (uint64_t)nwrite;
5279
5280 return nwrite;
5281 }
5282
5283 ngtcp2_ssize ngtcp2_conn_write_pkt_versioned(ngtcp2_conn *conn,
5284 ngtcp2_path *path,
5285 int pkt_info_version,
5286 ngtcp2_pkt_info *pi, uint8_t *dest,
5287 size_t destlen, ngtcp2_tstamp ts) {
5288 return ngtcp2_conn_writev_stream_versioned(
5289 conn, path, pkt_info_version, pi, dest, destlen,
5290 /* pdatalen = */ NULL, NGTCP2_WRITE_STREAM_FLAG_NONE,
5291 /* stream_id = */ -1,
5292 /* datav = */ NULL, /* datavcnt = */ 0, ts);
5293 }
5294
5295 /*
5296 * conn_on_version_negotiation is called when Version Negotiation
5297 * packet is received. The function decodes the data in the buffer
5298 * pointed by |payload| whose length is |payloadlen| as Version
5299 * Negotiation packet payload. The packet header is given in |hd|.
5300 *
5301 * This function returns 0 if it succeeds, or one of the following
5302 * negative error codes:
5303 *
5304 * NGTCP2_ERR_NOMEM
5305 * Out of memory.
5306 * NGTCP2_ERR_CALLBACK_FAILURE
5307 * User-defined callback function failed.
5308 * NGTCP2_ERR_INVALID_ARGUMENT
5309 * Packet payload is badly formatted.
5310 */
5311 static int conn_on_version_negotiation(ngtcp2_conn *conn,
5312 const ngtcp2_pkt_hd *hd,
5313 const uint8_t *payload,
5314 size_t payloadlen) {
5315 uint32_t sv[16];
5316 uint32_t *p;
5317 int rv = 0;
5318 size_t nsv;
5319 size_t i;
5320
5321 if (payloadlen % sizeof(uint32_t)) {
5322 return NGTCP2_ERR_INVALID_ARGUMENT;
5323 }
5324
5325 /* Version Negotiation packet is ignored if client has reacted upon
5326 Version Negotiation packet. */
5327 if (conn->local.settings.original_version != conn->client_chosen_version) {
5328 return NGTCP2_ERR_INVALID_ARGUMENT;
5329 }
5330
5331 if (payloadlen > sizeof(sv)) {
5332 p = ngtcp2_mem_malloc(conn->mem, payloadlen);
5333 if (p == NULL) {
5334 return NGTCP2_ERR_NOMEM;
5335 }
5336 } else {
5337 p = sv;
5338 }
5339
5340 nsv = ngtcp2_pkt_decode_version_negotiation(p, payload, payloadlen);
5341
5342 ngtcp2_log_rx_vn(&conn->log, hd, p, nsv);
5343
5344 ngtcp2_qlog_version_negotiation_pkt_received(&conn->qlog, hd, p, nsv);
5345
5346 if (!ngtcp2_is_reserved_version(conn->local.settings.original_version)) {
5347 for (i = 0; i < nsv; ++i) {
5348 if (p[i] == conn->local.settings.original_version) {
5349 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
5350 "ignore Version Negotiation because it contains the "
5351 "original version");
5352
5353 rv = NGTCP2_ERR_INVALID_ARGUMENT;
5354 goto fin;
5355 }
5356 }
5357 }
5358
5359 rv = conn_call_recv_version_negotiation(conn, hd, p, nsv);
5360 if (rv != 0) {
5361 goto fin;
5362 }
5363
5364 fin:
5365 if (p != sv) {
5366 ngtcp2_mem_free(conn->mem, p);
5367 }
5368
5369 return rv;
5370 }
5371
5372 static uint64_t conn_tx_strmq_first_cycle(ngtcp2_conn *conn) {
5373 ngtcp2_strm *strm;
5374
5375 if (ngtcp2_pq_empty(&conn->tx.strmq)) {
5376 return 0;
5377 }
5378
5379 strm = ngtcp2_struct_of(ngtcp2_pq_top(&conn->tx.strmq), ngtcp2_strm, pe);
5380 return strm->cycle;
5381 }
5382
5383 uint64_t ngtcp2_conn_tx_strmq_first_cycle(ngtcp2_conn *conn) {
5384 ngtcp2_strm *strm;
5385
5386 if (ngtcp2_pq_empty(&conn->tx.strmq)) {
5387 return 0;
5388 }
5389
5390 strm = ngtcp2_struct_of(ngtcp2_pq_top(&conn->tx.strmq), ngtcp2_strm, pe);
5391 return strm->cycle;
5392 }
5393
5394 /*
5395 * conn_on_retry is called when Retry packet is received. The
5396 * function decodes the data in the buffer pointed by |pkt| whose
5397 * length is |pktlen| as Retry packet. The length of long packet
5398 * header is given in |hdpktlen|. |pkt| includes packet header.
5399 *
5400 * This function returns 0 if it succeeds, or one of the following
5401 * negative error codes:
5402 *
5403 * NGTCP2_ERR_NOMEM
5404 * Out of memory.
5405 * NGTCP2_ERR_CALLBACK_FAILURE
5406 * User-defined callback function failed.
5407 * NGTCP2_ERR_INVALID_ARGUMENT
5408 * Packet payload is badly formatted.
5409 * NGTCP2_ERR_PROTO
5410 * ODCID does not match; or Token is empty.
5411 */
5412 static int conn_on_retry(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
5413 size_t hdpktlen, const uint8_t *pkt, size_t pktlen,
5414 ngtcp2_tstamp ts) {
5415 int rv;
5416 ngtcp2_pkt_retry retry;
5417 ngtcp2_pktns *in_pktns = conn->in_pktns;
5418 ngtcp2_rtb *rtb = &conn->pktns.rtb;
5419 ngtcp2_rtb *in_rtb;
5420 char cidbuf[sizeof(retry.odcid.data) * 2 + 1];
5421 uint8_t *token;
5422
5423 if (!in_pktns || (conn->flags & NGTCP2_CONN_FLAG_RECV_RETRY)) {
5424 return NGTCP2_ERR_DISCARD_PKT;
5425 }
5426
5427 in_rtb = &in_pktns->rtb;
5428
5429 rv = ngtcp2_pkt_decode_retry(&retry, pkt + hdpktlen, pktlen - hdpktlen);
5430 if (rv != 0) {
5431 return rv;
5432 }
5433
5434 retry.odcid = conn->dcid.current.cid;
5435
5436 rv = ngtcp2_pkt_verify_retry_tag(
5437 conn->client_chosen_version, &retry, pkt, pktlen, conn->callbacks.encrypt,
5438 &conn->crypto.retry_aead, &conn->crypto.retry_aead_ctx);
5439 if (rv != 0) {
5440 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
5441 "unable to verify Retry packet integrity");
5442 return rv;
5443 }
5444
5445 ngtcp2_log_infof(
5446 &conn->log, NGTCP2_LOG_EVENT_PKT, "odcid=0x%s",
5447 ngtcp2_encode_hex_cstr(cidbuf, retry.odcid.data, retry.odcid.datalen));
5448
5449 if (retry.tokenlen == 0) {
5450 return NGTCP2_ERR_PROTO;
5451 }
5452
5453 if (ngtcp2_cid_eq(&conn->dcid.current.cid, &hd->scid)) {
5454 return 0;
5455 }
5456
5457 ngtcp2_qlog_retry_pkt_received(&conn->qlog, hd, &retry);
5458
5459 /* DCID must be updated before invoking callback because client
5460 generates new initial keys there. */
5461 conn->dcid.current.cid = hd->scid;
5462 conn->retry_scid = hd->scid;
5463
5464 conn->flags |= NGTCP2_CONN_FLAG_RECV_RETRY;
5465
5466 rv = conn_call_recv_retry(conn, hd);
5467 if (rv != 0) {
5468 return rv;
5469 }
5470
5471 conn->state = NGTCP2_CS_CLIENT_INITIAL;
5472
5473 /* Just freeing memory is dangerous because we might free twice. */
5474
5475 rv = ngtcp2_rtb_reclaim_on_retry(rtb, conn, &conn->pktns, &conn->cstat);
5476 if (rv != 0) {
5477 return rv;
5478 }
5479
5480 rv = ngtcp2_rtb_reclaim_on_retry(in_rtb, conn, in_pktns, &conn->cstat);
5481 if (rv != 0) {
5482 return rv;
5483 }
5484
5485 ngtcp2_mem_free(conn->mem, (uint8_t *)conn->local.settings.token);
5486 conn->local.settings.token = NULL;
5487 conn->local.settings.tokenlen = 0;
5488
5489 token = ngtcp2_mem_malloc(conn->mem, retry.tokenlen);
5490 if (token == NULL) {
5491 return NGTCP2_ERR_NOMEM;
5492 }
5493
5494 ngtcp2_cpymem(token, retry.token, retry.tokenlen);
5495
5496 conn->local.settings.token = token;
5497 conn->local.settings.tokenlen = retry.tokenlen;
5498
5499 reset_conn_stat_recovery(&conn->cstat);
5500 conn_reset_congestion_state(conn, ts);
5501 conn_reset_ecn_validation_state(conn);
5502
5503 return 0;
5504 }
5505
5506 int ngtcp2_conn_detect_lost_pkt(ngtcp2_conn *conn, ngtcp2_pktns *pktns,
5507 ngtcp2_conn_stat *cstat, ngtcp2_tstamp ts) {
5508 return ngtcp2_rtb_detect_lost_pkt(&pktns->rtb, conn, pktns, cstat, ts);
5509 }
5510
5511 /*
5512 * conn_recv_ack processes received ACK frame |fr|. |pkt_ts| is the
5513 * timestamp when packet is received. |ts| should be the current
5514 * time. Usually they are the same, but for buffered packets,
5515 * |pkt_ts| would be earlier than |ts|. This function needs to be
5516 * called after |fr| is validated by ngtcp2_pkt_validate_ack.
5517 *
5518 * This function returns 0 if it succeeds, or one of the following
5519 * negative error codes:
5520 *
5521 * NGTCP2_ERR_NOMEM
5522 * Out of memory
5523 * NGTCP2_ERR_PROTO
5524 * |fr| acknowledges a packet this endpoint has not sent.
5525 * NGTCP2_ERR_CALLBACK_FAILURE
5526 * User callback failed.
5527 */
5528 static int conn_recv_ack(ngtcp2_conn *conn, ngtcp2_pktns *pktns, ngtcp2_ack *fr,
5529 ngtcp2_tstamp pkt_ts, ngtcp2_tstamp ts) {
5530 ngtcp2_ssize num_acked;
5531 ngtcp2_conn_stat *cstat = &conn->cstat;
5532
5533 if (pktns->tx.last_pkt_num < fr->largest_ack) {
5534 return NGTCP2_ERR_PROTO;
5535 }
5536
5537 ngtcp2_acktr_recv_ack(&pktns->acktr, fr);
5538
5539 num_acked =
5540 ngtcp2_rtb_recv_ack(&pktns->rtb, fr, &conn->cstat, conn, pktns, pkt_ts, ts);
5541 if (num_acked <= 0) {
5542 return (int)num_acked;
5543 }
5544
5545 pktns->rtb.probe_pkt_left = 0;
5546
5547 if (cstat->pto_count &&
5548 (conn->server || (conn->flags & NGTCP2_CONN_FLAG_SERVER_ADDR_VERIFIED))) {
5549 /* Reset PTO count but no less than 2 to avoid frequent probe
5550 packet transmission. */
5551 cstat->pto_count = ngtcp2_min_size(cstat->pto_count, 2);
5552 }
5553
5554 ngtcp2_conn_set_loss_detection_timer(conn, ts);
5555
5556 return 0;
5557 }
5558
5559 /*
5560 * conn_assign_recved_ack_delay_unscaled assigns
5561 * fr->ack_delay_unscaled.
5562 */
5563 static void assign_recved_ack_delay_unscaled(ngtcp2_ack *fr,
5564 uint64_t ack_delay_exponent) {
5565 const ngtcp2_tstamp max_ack_delay = ((1 << 14) - 1) * NGTCP2_MILLISECONDS;
5566 uint64_t exp = (1ULL << ack_delay_exponent) * NGTCP2_MICROSECONDS;
5567
5568 if (fr->ack_delay > max_ack_delay / exp) {
5569 fr->ack_delay_unscaled = max_ack_delay;
5570 return;
5571 }
5572
5573 fr->ack_delay_unscaled = fr->ack_delay * exp;
5574 }
5575
5576 /*
5577 * conn_recv_max_stream_data processes received MAX_STREAM_DATA frame
5578 * |fr|.
5579 *
5580 * This function returns 0 if it succeeds, or one of the following
5581 * negative error codes:
5582 *
5583 * NGTCP2_ERR_STREAM_STATE
5584 * Stream ID indicates that it is a local stream, and the local
5585 * endpoint has not initiated it; or stream is peer initiated
5586 * unidirectional stream.
5587 * NGTCP2_ERR_STREAM_LIMIT
5588 * Stream ID exceeds allowed limit.
5589 * NGTCP2_ERR_NOMEM
5590 * Out of memory.
5591 * NGTCP2_ERR_INTERNAL
5592 * Suspicious remote endpoint activity exceeded threshold.
5593 */
5594 static int conn_recv_max_stream_data(ngtcp2_conn *conn,
5595 const ngtcp2_max_stream_data *fr,
5596 ngtcp2_tstamp ts) {
5597 ngtcp2_strm *strm;
5598 ngtcp2_idtr *idtr;
5599 int local_stream = conn_local_stream(conn, fr->stream_id);
5600 int bidi = bidi_stream(fr->stream_id);
5601 int rv;
5602
5603 if (bidi) {
5604 if (local_stream) {
5605 if (conn->local.bidi.next_stream_id <= fr->stream_id) {
5606 return NGTCP2_ERR_STREAM_STATE;
5607 }
5608 } else if (conn->remote.bidi.max_streams <
5609 ngtcp2_ord_stream_id(fr->stream_id)) {
5610 return NGTCP2_ERR_STREAM_LIMIT;
5611 }
5612
5613 idtr = &conn->remote.bidi.idtr;
5614 } else {
5615 if (!local_stream || conn->local.uni.next_stream_id <= fr->stream_id) {
5616 return NGTCP2_ERR_STREAM_STATE;
5617 }
5618
5619 idtr = &conn->remote.uni.idtr;
5620 }
5621
5622 strm = ngtcp2_conn_find_stream(conn, fr->stream_id);
5623 if (strm == NULL) {
5624 if (local_stream) {
5625 /* Stream has been closed. */
5626 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
5627 return NGTCP2_ERR_INTERNAL;
5628 }
5629
5630 return 0;
5631 }
5632
5633 rv = ngtcp2_idtr_open(idtr, fr->stream_id);
5634 if (rv != 0) {
5635 if (ngtcp2_err_is_fatal(rv)) {
5636 return rv;
5637 }
5638 assert(rv == NGTCP2_ERR_STREAM_IN_USE);
5639 /* Stream has been closed. */
5640 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
5641 return NGTCP2_ERR_INTERNAL;
5642 }
5643
5644 return 0;
5645 }
5646
5647 strm = ngtcp2_objalloc_strm_get(&conn->strm_objalloc);
5648 if (strm == NULL) {
5649 return NGTCP2_ERR_NOMEM;
5650 }
5651 rv = ngtcp2_conn_init_stream(conn, strm, fr->stream_id, NULL);
5652 if (rv != 0) {
5653 ngtcp2_objalloc_strm_release(&conn->strm_objalloc, strm);
5654 return rv;
5655 }
5656
5657 rv = conn_call_stream_open(conn, strm);
5658 if (rv != 0) {
5659 return rv;
5660 }
5661 }
5662
5663 if (strm->tx.max_offset >= fr->max_stream_data) {
5664 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
5665 return NGTCP2_ERR_INTERNAL;
5666 }
5667
5668 return 0;
5669 }
5670
5671 strm->tx.max_offset = fr->max_stream_data;
5672
5673 /* Don't call callback if stream is half-closed local */
5674 if (strm->flags & NGTCP2_STRM_FLAG_SHUT_WR) {
5675 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
5676 return NGTCP2_ERR_INTERNAL;
5677 }
5678
5679 return 0;
5680 }
5681
5682 rv = conn_call_extend_max_stream_data(conn, strm, fr->stream_id,
5683 fr->max_stream_data);
5684 if (rv != 0) {
5685 return rv;
5686 }
5687
5688 return 0;
5689 }
5690
5691 /*
5692 * conn_recv_max_data processes received MAX_DATA frame |fr|.
5693 */
5694 static void conn_recv_max_data(ngtcp2_conn *conn, const ngtcp2_max_data *fr) {
5695 conn->tx.max_offset = ngtcp2_max_uint64(conn->tx.max_offset, fr->max_data);
5696 }
5697
5698 /*
5699 * should_buffer_1rtt_pkt returns nonzero if 1RTT packet |pkt| of
5700 * length |pktlen| should be buffered.
5701 */
5702 static int should_buffer_1rtt_pkt(const uint8_t *pkt, size_t pktlen) {
5703 /* A packet starting with 21 bytes zeros are most likely padding
5704 bytes. */
5705 return pktlen >= NGTCP2_MIN_QUIC_PKTLEN &&
5706 (pkt[0] != 0 || memcmp(pkt, pkt + 1, NGTCP2_MIN_QUIC_PKTLEN - 1) != 0);
5707 }
5708
5709 /*
5710 * conn_buffer_pkt buffers |pkt| of length |pktlen|, chaining it from
5711 * |*ppc|.
5712 *
5713 * This function returns 0 if it succeeds, or one of the following
5714 * negative error codes:
5715 *
5716 * NGTCP2_ERR_NOMEM
5717 * Out of memory.
5718 */
5719 static int conn_buffer_pkt(ngtcp2_conn *conn, ngtcp2_pktns *pktns,
5720 const ngtcp2_path *path, const ngtcp2_pkt_info *pi,
5721 const uint8_t *pkt, size_t pktlen, size_t dgramlen,
5722 ngtcp2_tstamp ts) {
5723 int rv;
5724 ngtcp2_pkt_chain **ppc = &pktns->rx.buffed_pkts, *pc;
5725 size_t i;
5726 for (i = 0; *ppc && i < NGTCP2_MAX_NUM_BUFFED_RX_PKTS;
5727 ppc = &(*ppc)->next, ++i)
5728 ;
5729
5730 if (i == NGTCP2_MAX_NUM_BUFFED_RX_PKTS) {
5731 return 0;
5732 }
5733
5734 rv =
5735 ngtcp2_pkt_chain_new(&pc, path, pi, pkt, pktlen, dgramlen, ts, conn->mem);
5736 if (rv != 0) {
5737 return rv;
5738 }
5739
5740 *ppc = pc;
5741
5742 return 0;
5743 }
5744
5745 static int ensure_decrypt_buffer(ngtcp2_vec *vec, size_t n, size_t initial,
5746 const ngtcp2_mem *mem) {
5747 uint8_t *nbuf;
5748 size_t len;
5749
5750 if (vec->len >= n) {
5751 return 0;
5752 }
5753
5754 len = vec->len == 0 ? initial : vec->len * 2;
5755 for (; len < n; len *= 2)
5756 ;
5757 nbuf = ngtcp2_mem_realloc(mem, vec->base, len);
5758 if (nbuf == NULL) {
5759 return NGTCP2_ERR_NOMEM;
5760 }
5761 vec->base = nbuf;
5762 vec->len = len;
5763
5764 return 0;
5765 }
5766
5767 /*
5768 * conn_ensure_decrypt_hp_buffer ensures that
5769 * conn->crypto.decrypt_hp_buf has at least |n| bytes space.
5770 *
5771 * This function returns 0 if it succeeds, or one of the following
5772 * negative error codes:
5773 *
5774 * NGTCP2_ERR_NOMEM
5775 * Out of memory.
5776 */
5777 static int conn_ensure_decrypt_hp_buffer(ngtcp2_conn *conn, size_t n) {
5778 return ensure_decrypt_buffer(&conn->crypto.decrypt_hp_buf, n, 256, conn->mem);
5779 }
5780
5781 /*
5782 * conn_ensure_decrypt_buffer ensures that conn->crypto.decrypt_buf
5783 * has at least |n| bytes space.
5784 *
5785 * This function returns 0 if it succeeds, or one of the following
5786 * negative error codes:
5787 *
5788 * NGTCP2_ERR_NOMEM
5789 * Out of memory.
5790 */
5791 static int conn_ensure_decrypt_buffer(ngtcp2_conn *conn, size_t n) {
5792 return ensure_decrypt_buffer(&conn->crypto.decrypt_buf, n, 2048, conn->mem);
5793 }
5794
5795 /*
5796 * decrypt_pkt decrypts the data pointed by |payload| whose length is
5797 * |payloadlen|, and writes plaintext data to the buffer pointed by
5798 * |dest|. The buffer pointed by |aad| is the Additional
5799 * Authenticated Data, and its length is |aadlen|. |pkt_num| is used
5800 * to create a nonce. |ckm| is the cryptographic key, and iv to use.
5801 * |decrypt| is a callback function which actually decrypts a packet.
5802 *
5803 * This function returns the number of bytes written in |dest| if it
5804 * succeeds, or one of the following negative error codes:
5805 *
5806 * NGTCP2_ERR_CALLBACK_FAILURE
5807 * User callback failed.
5808 * NGTCP2_ERR_DECRYPT
5809 * Failed to decrypt a packet.
5810 */
5811 static ngtcp2_ssize decrypt_pkt(uint8_t *dest, const ngtcp2_crypto_aead *aead,
5812 const uint8_t *payload, size_t payloadlen,
5813 const uint8_t *aad, size_t aadlen,
5814 int64_t pkt_num, ngtcp2_crypto_km *ckm,
5815 ngtcp2_decrypt decrypt) {
5816 /* TODO nonce is limited to 64 bytes. */
5817 uint8_t nonce[64];
5818 int rv;
5819
5820 assert(sizeof(nonce) >= ckm->iv.len);
5821
5822 ngtcp2_crypto_create_nonce(nonce, ckm->iv.base, ckm->iv.len, pkt_num);
5823
5824 rv = decrypt(dest, aead, &ckm->aead_ctx, payload, payloadlen, nonce,
5825 ckm->iv.len, aad, aadlen);
5826
5827 if (rv != 0) {
5828 if (rv == NGTCP2_ERR_DECRYPT) {
5829 return rv;
5830 }
5831 return NGTCP2_ERR_CALLBACK_FAILURE;
5832 }
5833
5834 assert(payloadlen >= aead->max_overhead);
5835
5836 return (ngtcp2_ssize)(payloadlen - aead->max_overhead);
5837 }
5838
5839 /*
5840 * decrypt_hp decryptes packet header. The packet number starts at
5841 * |pkt| + |pkt_num_offset|. The entire plaintext QUIC packet header
5842 * will be written to the buffer pointed by |dest| whose capacity is
5843 * |destlen|.
5844 *
5845 * This function returns the number of bytes written to |dest|, or one
5846 * of the following negative error codes:
5847 *
5848 * NGTCP2_ERR_PROTO
5849 * Packet is badly formatted
5850 * NGTCP2_ERR_CALLBACK_FAILURE
5851 * User-defined callback function failed; or it does not return
5852 * expected result.
5853 */
5854 static ngtcp2_ssize
5855 decrypt_hp(ngtcp2_pkt_hd *hd, uint8_t *dest, const ngtcp2_crypto_cipher *hp,
5856 const uint8_t *pkt, size_t pktlen, size_t pkt_num_offset,
5857 const ngtcp2_crypto_cipher_ctx *hp_ctx, ngtcp2_hp_mask hp_mask) {
5858 size_t sample_offset;
5859 uint8_t *p = dest;
5860 uint8_t mask[NGTCP2_HP_SAMPLELEN];
5861 size_t i;
5862 int rv;
5863
5864 assert(hp_mask);
5865
5866 if (pkt_num_offset + 4 + NGTCP2_HP_SAMPLELEN > pktlen) {
5867 return NGTCP2_ERR_PROTO;
5868 }
5869
5870 p = ngtcp2_cpymem(p, pkt, pkt_num_offset);
5871
5872 sample_offset = pkt_num_offset + 4;
5873
5874 rv = hp_mask(mask, hp, hp_ctx, pkt + sample_offset);
5875 if (rv != 0) {
5876 return NGTCP2_ERR_CALLBACK_FAILURE;
5877 }
5878
5879 if (hd->flags & NGTCP2_PKT_FLAG_LONG_FORM) {
5880 dest[0] = (uint8_t)(dest[0] ^ (mask[0] & 0x0f));
5881 } else {
5882 dest[0] = (uint8_t)(dest[0] ^ (mask[0] & 0x1f));
5883 if (dest[0] & NGTCP2_SHORT_KEY_PHASE_BIT) {
5884 hd->flags |= NGTCP2_PKT_FLAG_KEY_PHASE;
5885 }
5886 }
5887
5888 hd->pkt_numlen = (size_t)((dest[0] & NGTCP2_PKT_NUMLEN_MASK) + 1);
5889
5890 for (i = 0; i < 4; ++i) {
5891 *p++ = *(pkt + pkt_num_offset + i) ^ mask[i + 1];
5892 }
5893
5894 p -= 4;
5895 hd->pkt_num = ngtcp2_get_pkt_num(p, hd->pkt_numlen);
5896 p += hd->pkt_numlen;
5897
5898 return p - dest;
5899 }
5900
5901 /*
5902 * conn_emit_pending_crypto_data delivers pending stream data to the
5903 * application due to packet reordering.
5904 *
5905 * This function returns 0 if it succeeds, or one of the following
5906 * negative error codes:
5907 *
5908 * NGTCP2_ERR_CALLBACK_FAILURE
5909 * User callback failed
5910 * NGTCP2_ERR_CRYPTO
5911 * TLS backend reported error
5912 */
5913 static int
5914 conn_emit_pending_crypto_data(ngtcp2_conn *conn,
5915 ngtcp2_encryption_level encryption_level,
5916 ngtcp2_strm *strm, uint64_t rx_offset) {
5917 size_t datalen;
5918 const uint8_t *data;
5919 int rv;
5920 uint64_t offset;
5921
5922 if (!strm->rx.rob) {
5923 return 0;
5924 }
5925
5926 for (;;) {
5927 datalen = ngtcp2_rob_data_at(strm->rx.rob, &data, rx_offset);
5928 if (datalen == 0) {
5929 assert(rx_offset == ngtcp2_strm_rx_offset(strm));
5930 return 0;
5931 }
5932
5933 offset = rx_offset;
5934 rx_offset += datalen;
5935
5936 rv =
5937 conn_call_recv_crypto_data(conn, encryption_level, offset, data, datalen);
5938 if (rv != 0) {
5939 return rv;
5940 }
5941
5942 ngtcp2_rob_pop(strm->rx.rob, rx_offset - datalen, datalen);
5943 }
5944 }
5945
5946 /*
5947 * conn_recv_connection_close is called when CONNECTION_CLOSE or
5948 * APPLICATION_CLOSE frame is received.
5949 */
5950 static int conn_recv_connection_close(ngtcp2_conn *conn,
5951 ngtcp2_connection_close *fr) {
5952 ngtcp2_ccerr *ccerr = &conn->rx.ccerr;
5953
5954 conn->state = NGTCP2_CS_DRAINING;
5955 if (fr->type == NGTCP2_FRAME_CONNECTION_CLOSE) {
5956 ccerr->type = NGTCP2_CCERR_TYPE_TRANSPORT;
5957 } else {
5958 ccerr->type = NGTCP2_CCERR_TYPE_APPLICATION;
5959 }
5960 ccerr->error_code = fr->error_code;
5961 ccerr->frame_type = fr->frame_type;
5962
5963 if (!fr->reasonlen) {
5964 ccerr->reasonlen = 0;
5965
5966 return 0;
5967 }
5968
5969 if (ccerr->reason == NULL) {
5970 ccerr->reason = ngtcp2_mem_malloc(conn->mem, NGTCP2_CCERR_MAX_REASONLEN);
5971 if (ccerr->reason == NULL) {
5972 return NGTCP2_ERR_NOMEM;
5973 }
5974 }
5975
5976 ccerr->reasonlen = ngtcp2_min_size(fr->reasonlen, NGTCP2_CCERR_MAX_REASONLEN);
5977 ngtcp2_cpymem((uint8_t *)ccerr->reason, fr->reason, ccerr->reasonlen);
5978
5979 return 0;
5980 }
5981
5982 static void conn_recv_path_challenge(ngtcp2_conn *conn, const ngtcp2_path *path,
5983 ngtcp2_path_challenge *fr) {
5984 ngtcp2_path_challenge_entry *ent;
5985
5986 /* client only responds to PATH_CHALLENGE from the current path or
5987 path which client is migrating to. */
5988 if (!conn->server && !ngtcp2_path_eq(&conn->dcid.current.ps.path, path) &&
5989 (!conn->pv || !ngtcp2_path_eq(&conn->pv->dcid.ps.path, path))) {
5990 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CON,
5991 "discard PATH_CHALLENGE from the path which is not current "
5992 "or endpoint is migrating to");
5993 return;
5994 }
5995
5996 ent = ngtcp2_ringbuf_push_front(&conn->rx.path_challenge.rb);
5997 ngtcp2_path_challenge_entry_init(ent, path, fr->data);
5998 }
5999
6000 /*
6001 * conn_reset_congestion_state resets congestion state.
6002 */
6003 static void conn_reset_congestion_state(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
6004 conn_reset_conn_stat_cc(conn, &conn->cstat);
6005
6006 if (conn->cc.reset) {
6007 conn->cc.reset(&conn->cc, &conn->cstat, ts);
6008 }
6009
6010 if (conn->hs_pktns) {
6011 ngtcp2_rtb_reset_cc_state(&conn->hs_pktns->rtb,
6012 conn->hs_pktns->tx.last_pkt_num + 1);
6013 }
6014 ngtcp2_rtb_reset_cc_state(&conn->pktns.rtb, conn->pktns.tx.last_pkt_num + 1);
6015 ngtcp2_rst_reset(&conn->rst);
6016
6017 conn->tx.pacing.next_ts = UINT64_MAX;
6018 conn->tx.pacing.compensation = 0;
6019 }
6020
6021 /*
6022 * conn_server_preferred_addr_migration returns nonzero if
6023 * |local_addr| equals to one of the preferred addresses.
6024 */
6025 static int conn_server_preferred_addr_migration(const ngtcp2_conn *conn,
6026 const ngtcp2_addr *local_addr) {
6027 const ngtcp2_preferred_addr *paddr;
6028
6029 assert(conn->server);
6030
6031 if (!conn->local.transport_params.preferred_addr_present) {
6032 return 0;
6033 }
6034
6035 paddr = &conn->local.transport_params.preferred_addr;
6036
6037 switch (local_addr->addr->sa_family) {
6038 case NGTCP2_AF_INET:
6039 if (!paddr->ipv4_present) {
6040 return 0;
6041 }
6042
6043 return ngtcp2_sockaddr_eq((const ngtcp2_sockaddr *)&paddr->ipv4,
6044 local_addr->addr);
6045 case NGTCP2_AF_INET6:
6046 if (!paddr->ipv6_present) {
6047 return 0;
6048 }
6049
6050 return ngtcp2_sockaddr_eq((const ngtcp2_sockaddr *)&paddr->ipv6,
6051 local_addr->addr);
6052 }
6053
6054 return 0;
6055 }
6056
6057 static int conn_recv_path_response(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
6058 ngtcp2_path_response *fr, ngtcp2_tstamp ts) {
6059 int rv;
6060 ngtcp2_pv *pv = conn->pv, *npv = NULL;
6061 uint8_t ent_flags;
6062
6063 if (!pv) {
6064 return 0;
6065 }
6066
6067 rv = ngtcp2_pv_validate(pv, &ent_flags, fr->data);
6068 if (rv != 0) {
6069 assert(!ngtcp2_err_is_fatal(rv));
6070
6071 return 0;
6072 }
6073
6074 if (!(pv->flags & NGTCP2_PV_FLAG_DONT_CARE)) {
6075 if (pv->dcid.seq != conn->dcid.current.seq ||
6076 !ngtcp2_path_eq(&pv->dcid.ps.path, &conn->dcid.current.ps.path)) {
6077 if (conn->dcid.current.cid.datalen &&
6078 pv->dcid.seq != conn->dcid.current.seq) {
6079 rv = conn_retire_active_dcid(conn, &conn->dcid.current, ts);
6080 if (rv != 0) {
6081 return rv;
6082 }
6083 }
6084
6085 if (conn->dcid.current.flags & NGTCP2_DCID_FLAG_PATH_VALIDATED) {
6086 ngtcp2_conn_add_path_history(conn, &conn->dcid.current, ts);
6087 }
6088
6089 ngtcp2_dcid_copy(&conn->dcid.current, &pv->dcid);
6090
6091 conn_reset_congestion_state(conn, ts);
6092 conn_reset_ecn_validation_state(conn);
6093
6094 if (conn->server && conn->rx.preferred_addr.pkt_num == -1 &&
6095 conn_server_preferred_addr_migration(
6096 conn, &conn->dcid.current.ps.path.local)) {
6097 conn->rx.preferred_addr.pkt_num = hd->pkt_num;
6098 }
6099 }
6100
6101 assert(ngtcp2_path_eq(&pv->dcid.ps.path, &conn->dcid.current.ps.path));
6102
6103 conn->dcid.current.flags |= NGTCP2_DCID_FLAG_PATH_VALIDATED;
6104
6105 if (!conn->local.settings.no_pmtud) {
6106 ngtcp2_conn_stop_pmtud(conn);
6107
6108 if (!(ent_flags & NGTCP2_PV_ENTRY_FLAG_UNDERSIZED)) {
6109 rv = conn_start_pmtud(conn);
6110 if (rv != 0) {
6111 return rv;
6112 }
6113 }
6114 }
6115
6116 if (!(ent_flags & NGTCP2_PV_ENTRY_FLAG_UNDERSIZED)) {
6117 rv = conn_call_path_validation(conn, pv,
6118 NGTCP2_PATH_VALIDATION_RESULT_SUCCESS);
6119 if (rv != 0) {
6120 return rv;
6121 }
6122 }
6123 }
6124
6125 if (ent_flags & NGTCP2_PV_ENTRY_FLAG_UNDERSIZED) {
6126 assert(conn->server);
6127
6128 /* Validate path again */
6129 rv = ngtcp2_pv_new(&npv, &pv->dcid, conn_compute_pv_timeout(conn),
6130 NGTCP2_PV_FLAG_NONE, &conn->log, conn->mem);
6131 if (rv != 0) {
6132 return rv;
6133 }
6134
6135 npv->dcid.flags |= NGTCP2_DCID_FLAG_PATH_VALIDATED;
6136
6137 if (pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) {
6138 ngtcp2_pv_set_fallback(npv, &pv->fallback_dcid, pv->fallback_pto);
6139 }
6140 } else if (pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) {
6141 rv = ngtcp2_pv_new(&npv, &pv->fallback_dcid,
6142 conn_compute_pv_timeout_pto(conn, pv->fallback_pto),
6143 NGTCP2_PV_FLAG_DONT_CARE, &conn->log, conn->mem);
6144 if (rv != 0) {
6145 return rv;
6146 }
6147 }
6148
6149 if (pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) {
6150 /* Unset the flag bit so that conn_stop_pv does not retire
6151 DCID. */
6152 pv->flags &= (uint8_t)~NGTCP2_PV_FLAG_FALLBACK_PRESENT;
6153 }
6154
6155 rv = conn_stop_pv(conn, ts);
6156 if (rv != 0) {
6157 ngtcp2_pv_del(npv);
6158 return rv;
6159 }
6160
6161 conn->pv = npv;
6162
6163 return conn_call_begin_path_validation(conn, conn->pv);
6164 }
6165
6166 /*
6167 * pktns_pkt_num_is_duplicate returns nonzero if |pkt_num| is
6168 * duplicated packet number.
6169 */
6170 static int pktns_pkt_num_is_duplicate(ngtcp2_pktns *pktns, int64_t pkt_num) {
6171 return ngtcp2_gaptr_is_pushed(&pktns->rx.pngap, (uint64_t)pkt_num, 1);
6172 }
6173
6174 /*
6175 * pktns_commit_recv_pkt_num marks packet number |pkt_num| as
6176 * received. It stores |pkt_num| and its reception timestamp |ts| in
6177 * order to send its ACK. It also increase ECN counts from |pi|.
6178 * |require_ack| is nonzero if the received packet is ack-eliciting.
6179 *
6180 * It returns 0 if it succeeds, or one of the following negative error
6181 * codes:
6182 *
6183 * NGTCP2_ERR_NOMEM
6184 * Out of memory
6185 * NGTCP2_ERR_PROTO
6186 * Same packet number has already been added.
6187 */
6188 static int pktns_commit_recv_pkt_num(ngtcp2_pktns *pktns, int64_t pkt_num,
6189 const ngtcp2_pkt_info *pi, int require_ack,
6190 ngtcp2_tstamp ts) {
6191 ngtcp2_acktr *acktr = &pktns->acktr;
6192 ngtcp2_range r;
6193 int rv;
6194
6195 rv = ngtcp2_gaptr_push(&pktns->rx.pngap, (uint64_t)pkt_num, 1);
6196 if (rv != 0) {
6197 return rv;
6198 }
6199
6200 if (ngtcp2_ksl_len(&pktns->rx.pngap.gap) > 256) {
6201 ngtcp2_gaptr_drop_first_gap(&pktns->rx.pngap);
6202 }
6203
6204 if (require_ack) {
6205 if (pktns->rx.max_ack_eliciting_pkt_num != -1) {
6206 if (pkt_num < pktns->rx.max_ack_eliciting_pkt_num) {
6207 ngtcp2_acktr_immediate_ack(&pktns->acktr);
6208 } else if (pkt_num != pktns->rx.max_ack_eliciting_pkt_num + 1) {
6209 r = ngtcp2_gaptr_get_first_gap_after(
6210 &pktns->rx.pngap, (uint64_t)pktns->rx.max_ack_eliciting_pkt_num);
6211
6212 if (r.begin < (uint64_t)pkt_num) {
6213 ngtcp2_acktr_immediate_ack(&pktns->acktr);
6214 }
6215 }
6216 }
6217
6218 if (pktns->rx.max_ack_eliciting_pkt_num < pkt_num) {
6219 pktns->rx.max_ack_eliciting_pkt_num = pkt_num;
6220 }
6221 }
6222
6223 ngtcp2_acktr_increase_ecn_counts(acktr, pi);
6224
6225 rv = ngtcp2_acktr_add(acktr, pkt_num, require_ack, ts);
6226 if (rv != 0) {
6227 assert(rv != NGTCP2_ERR_INVALID_ARGUMENT);
6228 return rv;
6229 }
6230
6231 return 0;
6232 }
6233
6234 /*
6235 * verify_token verifies |hd| contains |token| in its token field. It
6236 * returns 0 if it succeeds, or NGTCP2_ERR_PROTO.
6237 */
6238 static int verify_token(const uint8_t *token, size_t tokenlen,
6239 const ngtcp2_pkt_hd *hd) {
6240 if (tokenlen == hd->tokenlen && ngtcp2_cmemeq(token, hd->token, tokenlen)) {
6241 return 0;
6242 }
6243 return NGTCP2_ERR_PROTO;
6244 }
6245
6246 /*
6247 * vneg_available_versions_includes returns nonzero if
6248 * |available_versions| of length |available_versionslen| includes
6249 * |version|. |available_versions| is the wire image of
6250 * available_versions field of version_information transport
6251 * parameter, and each version is encoded in network byte order.
6252 */
6253 static int vneg_available_versions_includes(const uint8_t *available_versions,
6254 size_t available_versionslen,
6255 uint32_t version) {
6256 size_t i;
6257 uint32_t v;
6258
6259 assert(!(available_versionslen & 0x3));
6260
6261 if (available_versionslen == 0) {
6262 return 0;
6263 }
6264
6265 for (i = 0; i < available_versionslen; i += sizeof(uint32_t)) {
6266 available_versions = ngtcp2_get_uint32be(&v, available_versions);
6267
6268 if (version == v) {
6269 return 1;
6270 }
6271 }
6272
6273 return 0;
6274 }
6275
6276 /*
6277 * conn_verify_fixed_bit verifies that fixed bit in |hd| is
6278 * acceptable.
6279 *
6280 * This function returns 0 if it succeeds, or one of the following
6281 * negative error codes:
6282 *
6283 * NGTCP2_ERR_INVALID_ARGUMENT
6284 * Clearing fixed bit is not permitted.
6285 */
6286 static int conn_verify_fixed_bit(ngtcp2_conn *conn, ngtcp2_pkt_hd *hd) {
6287 if (!(hd->flags & NGTCP2_PKT_FLAG_FIXED_BIT_CLEAR)) {
6288 return 0;
6289 }
6290
6291 if (conn->server) {
6292 switch (hd->type) {
6293 case NGTCP2_PKT_INITIAL:
6294 case NGTCP2_PKT_0RTT:
6295 case NGTCP2_PKT_HANDSHAKE:
6296 /* RFC 9287 requires that a token from NEW_TOKEN. */
6297 if (!(conn->flags & NGTCP2_CONN_FLAG_INITIAL_PKT_PROCESSED) &&
6298 (conn->local.settings.token_type != NGTCP2_TOKEN_TYPE_NEW_TOKEN ||
6299 !conn->local.settings.tokenlen)) {
6300 return NGTCP2_ERR_INVALID_ARGUMENT;
6301 }
6302
6303 break;
6304 }
6305 }
6306
6307 /* TODO we have no information that we enabled grease_quic_bit in
6308 the previous connection. */
6309 if (!conn->local.transport_params.grease_quic_bit) {
6310 return NGTCP2_ERR_INVALID_ARGUMENT;
6311 }
6312
6313 return 0;
6314 }
6315
6316 static int conn_recv_crypto(ngtcp2_conn *conn,
6317 ngtcp2_encryption_level encryption_level,
6318 ngtcp2_strm *strm, const ngtcp2_stream *fr,
6319 ngtcp2_tstamp ts);
6320
6321 static ngtcp2_ssize conn_recv_pkt(ngtcp2_conn *conn, const ngtcp2_path *path,
6322 const ngtcp2_pkt_info *pi, const uint8_t *pkt,
6323 size_t pktlen, size_t dgramlen,
6324 ngtcp2_tstamp pkt_ts, ngtcp2_tstamp ts);
6325
6326 static int conn_process_buffered_protected_pkt(ngtcp2_conn *conn,
6327 ngtcp2_pktns *pktns,
6328 ngtcp2_tstamp ts);
6329
6330 /*
6331 * conn_recv_handshake_pkt processes received packet |pkt| whose
6332 * length is |pktlen| during handshake period. The buffer pointed by
6333 * |pkt| might contain multiple packets. This function only processes
6334 * one packet. |pkt_ts| is the timestamp when packet is received.
6335 * |ts| should be the current time. Usually they are the same, but
6336 * for buffered packets, |pkt_ts| would be earlier than |ts|.
6337 *
6338 * This function returns the number of bytes it reads if it succeeds,
6339 * or one of the following negative error codes:
6340 *
6341 * NGTCP2_ERR_RECV_VERSION_NEGOTIATION
6342 * Version Negotiation packet is received.
6343 * NGTCP2_ERR_NOMEM
6344 * Out of memory.
6345 * NGTCP2_ERR_CALLBACK_FAILURE
6346 * User-defined callback function failed.
6347 * NGTCP2_ERR_DISCARD_PKT
6348 * Packet was discarded because plain text header was malformed;
6349 * or its payload could not be decrypted.
6350 * NGTCP2_ERR_FRAME_FORMAT
6351 * Frame is badly formatted
6352 * NGTCP2_ERR_ACK_FRAME
6353 * ACK frame is malformed.
6354 * NGTCP2_ERR_CRYPTO
6355 * TLS stack reported error.
6356 * NGTCP2_ERR_PROTO
6357 * Generic QUIC protocol error.
6358 * NGTCP2_ERR_INTERNAL
6359 * Suspicious remote endpoint activity exceeded threshold.
6360 *
6361 * In addition to the above error codes, error codes returned from
6362 * conn_recv_pkt are also returned.
6363 */
6364 static ngtcp2_ssize
6365 conn_recv_handshake_pkt(ngtcp2_conn *conn, const ngtcp2_path *path,
6366 const ngtcp2_pkt_info *pi, const uint8_t *pkt,
6367 size_t pktlen, size_t dgramlen, ngtcp2_tstamp pkt_ts,
6368 ngtcp2_tstamp ts) {
6369 ngtcp2_ssize nread;
6370 ngtcp2_pkt_hd hd;
6371 ngtcp2_frame_decoder frd;
6372 ngtcp2_frame fr;
6373 int rv;
6374 int require_ack = 0;
6375 size_t hdpktlen;
6376 const uint8_t *payload;
6377 size_t payloadlen;
6378 ngtcp2_ssize nwrite;
6379 ngtcp2_crypto_aead *aead;
6380 ngtcp2_crypto_cipher *hp;
6381 ngtcp2_crypto_km *ckm;
6382 ngtcp2_crypto_cipher_ctx *hp_ctx;
6383 ngtcp2_hp_mask hp_mask;
6384 ngtcp2_decrypt decrypt;
6385 ngtcp2_pktns *pktns;
6386 ngtcp2_strm *crypto;
6387 ngtcp2_encryption_level encryption_level;
6388 int invalid_reserved_bits = 0;
6389 size_t num_ack_processed = 0;
6390
6391 if (!(pkt[0] & NGTCP2_HEADER_FORM_BIT)) {
6392 /* Ignore 1RTT packet unless server's first Handshake packet has
6393 been transmitted. */
6394 if (conn->state == NGTCP2_CS_SERVER_INITIAL ||
6395 !should_buffer_1rtt_pkt(pkt, pktlen)) {
6396 return (ngtcp2_ssize)pktlen;
6397 }
6398
6399 if (conn->pktns.crypto.rx.ckm) {
6400 return 0;
6401 }
6402
6403 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON,
6404 "buffering 1RTT packet len=%zu", pktlen);
6405
6406 rv =
6407 conn_buffer_pkt(conn, &conn->pktns, path, pi, pkt, pktlen, dgramlen, ts);
6408 if (rv != 0) {
6409 assert(ngtcp2_err_is_fatal(rv));
6410 return rv;
6411 }
6412 return (ngtcp2_ssize)pktlen;
6413 }
6414
6415 nread = ngtcp2_pkt_decode_hd_long(&hd, pkt, pktlen);
6416 if (nread < 0) {
6417 return NGTCP2_ERR_DISCARD_PKT;
6418 }
6419
6420 switch (hd.type) {
6421 case NGTCP2_PKT_VERSION_NEGOTIATION:
6422 hdpktlen = (size_t)nread;
6423
6424 ngtcp2_log_rx_pkt_hd(&conn->log, &hd);
6425
6426 if (conn->server) {
6427 return NGTCP2_ERR_DISCARD_PKT;
6428 }
6429
6430 /* Receiving Version Negotiation packet after getting Handshake
6431 packet from server is invalid. */
6432 if (conn->flags & NGTCP2_CONN_FLAG_INITIAL_PKT_PROCESSED) {
6433 return NGTCP2_ERR_DISCARD_PKT;
6434 }
6435
6436 if (!ngtcp2_cid_eq(&conn->oscid, &hd.dcid)) {
6437 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
6438 "packet was ignored because of mismatched DCID");
6439 return NGTCP2_ERR_DISCARD_PKT;
6440 }
6441
6442 if (!ngtcp2_cid_eq(&conn->dcid.current.cid, &hd.scid)) {
6443 /* Just discard invalid Version Negotiation packet */
6444 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
6445 "packet was ignored because of mismatched SCID");
6446 return NGTCP2_ERR_DISCARD_PKT;
6447 }
6448 rv =
6449 conn_on_version_negotiation(conn, &hd, pkt + hdpktlen, pktlen - hdpktlen);
6450 if (rv != 0) {
6451 if (ngtcp2_err_is_fatal(rv)) {
6452 return rv;
6453 }
6454 return NGTCP2_ERR_DISCARD_PKT;
6455 }
6456 return NGTCP2_ERR_RECV_VERSION_NEGOTIATION;
6457 case NGTCP2_PKT_RETRY:
6458 hdpktlen = (size_t)nread;
6459
6460 ngtcp2_log_rx_pkt_hd(&conn->log, &hd);
6461
6462 if (conn->server) {
6463 return NGTCP2_ERR_DISCARD_PKT;
6464 }
6465
6466 if (conn_verify_fixed_bit(conn, &hd) != 0) {
6467 return NGTCP2_ERR_DISCARD_PKT;
6468 }
6469
6470 /* Receiving Retry packet after getting Initial packet from server
6471 is invalid. */
6472 if (conn->flags & NGTCP2_CONN_FLAG_INITIAL_PKT_PROCESSED) {
6473 return NGTCP2_ERR_DISCARD_PKT;
6474 }
6475
6476 if (conn->client_chosen_version != hd.version) {
6477 return NGTCP2_ERR_DISCARD_PKT;
6478 }
6479
6480 rv = conn_on_retry(conn, &hd, hdpktlen, pkt, pktlen, ts);
6481 if (rv != 0) {
6482 if (ngtcp2_err_is_fatal(rv)) {
6483 return rv;
6484 }
6485 return NGTCP2_ERR_DISCARD_PKT;
6486 }
6487 return (ngtcp2_ssize)pktlen;
6488 }
6489
6490 if (pktlen < (size_t)nread + hd.len) {
6491 return NGTCP2_ERR_DISCARD_PKT;
6492 }
6493
6494 pktlen = (size_t)nread + hd.len;
6495
6496 if (!ngtcp2_is_supported_version(hd.version)) {
6497 return NGTCP2_ERR_DISCARD_PKT;
6498 }
6499
6500 if (conn->server) {
6501 if (hd.version != conn->client_chosen_version &&
6502 (!conn->negotiated_version || hd.version != conn->negotiated_version)) {
6503 return NGTCP2_ERR_DISCARD_PKT;
6504 }
6505 } else if (hd.version != conn->client_chosen_version &&
6506 conn->negotiated_version &&
6507 hd.version != conn->negotiated_version) {
6508 return NGTCP2_ERR_DISCARD_PKT;
6509 }
6510
6511 if (conn_verify_fixed_bit(conn, &hd) != 0) {
6512 return NGTCP2_ERR_DISCARD_PKT;
6513 }
6514
6515 /* Quoted from spec: if subsequent packets of those types include a
6516 different Source Connection ID, they MUST be discarded. */
6517 if ((conn->flags & NGTCP2_CONN_FLAG_INITIAL_PKT_PROCESSED) &&
6518 !ngtcp2_cid_eq(&conn->dcid.current.cid, &hd.scid)) {
6519 ngtcp2_log_rx_pkt_hd(&conn->log, &hd);
6520 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
6521 "packet was ignored because of mismatched SCID");
6522 return NGTCP2_ERR_DISCARD_PKT;
6523 }
6524
6525 switch (hd.type) {
6526 case NGTCP2_PKT_0RTT:
6527 if (!conn->server) {
6528 return NGTCP2_ERR_DISCARD_PKT;
6529 }
6530
6531 if (hd.version != conn->client_chosen_version) {
6532 return NGTCP2_ERR_DISCARD_PKT;
6533 }
6534
6535 if (conn->flags & NGTCP2_CONN_FLAG_INITIAL_PKT_PROCESSED) {
6536 if (conn->early.ckm) {
6537 ngtcp2_ssize nread2;
6538 /* TODO Avoid to parse header twice. */
6539 nread2 =
6540 conn_recv_pkt(conn, path, pi, pkt, pktlen, dgramlen, pkt_ts, ts);
6541 if (nread2 < 0) {
6542 return nread2;
6543 }
6544 }
6545
6546 /* Discard 0-RTT packet if we don't have a key to decrypt it. */
6547 return (ngtcp2_ssize)pktlen;
6548 }
6549
6550 /* Buffer re-ordered 0-RTT packet. */
6551 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON,
6552 "buffering 0-RTT packet len=%zu", pktlen);
6553
6554 rv = conn_buffer_pkt(conn, conn->in_pktns, path, pi, pkt, pktlen, dgramlen,
6555 ts);
6556 if (rv != 0) {
6557 assert(ngtcp2_err_is_fatal(rv));
6558 return rv;
6559 }
6560
6561 return (ngtcp2_ssize)pktlen;
6562 case NGTCP2_PKT_INITIAL:
6563 if (!conn->in_pktns) {
6564 ngtcp2_log_info(
6565 &conn->log, NGTCP2_LOG_EVENT_PKT,
6566 "Initial packet is discarded because keys have been discarded");
6567 return (ngtcp2_ssize)pktlen;
6568 }
6569
6570 assert(conn->in_pktns);
6571
6572 if (conn->server) {
6573 if (dgramlen < NGTCP2_MAX_UDP_PAYLOAD_SIZE) {
6574 ngtcp2_log_infof(
6575 &conn->log, NGTCP2_LOG_EVENT_PKT,
6576 "Initial packet was ignored because it is included in UDP datagram "
6577 "less than %d bytes: %zu bytes",
6578 NGTCP2_MAX_UDP_PAYLOAD_SIZE, dgramlen);
6579 return NGTCP2_ERR_DISCARD_PKT;
6580 }
6581 if (conn->local.settings.tokenlen) {
6582 rv = verify_token(conn->local.settings.token,
6583 conn->local.settings.tokenlen, &hd);
6584 if (rv != 0) {
6585 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
6586 "packet was ignored because token is invalid");
6587 return NGTCP2_ERR_DISCARD_PKT;
6588 }
6589 }
6590 if ((conn->flags & NGTCP2_CONN_FLAG_INITIAL_PKT_PROCESSED) == 0) {
6591 /* Set rcid here so that it is available to callback. If this
6592 packet is discarded later in this function and no packet is
6593 processed in this connection attempt so far, connection
6594 will be dropped. */
6595 conn->rcid = hd.dcid;
6596
6597 rv = conn_call_recv_client_initial(conn, &hd.dcid);
6598 if (rv != 0) {
6599 return rv;
6600 }
6601 }
6602 } else {
6603 if (hd.tokenlen != 0) {
6604 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
6605 "packet was ignored because token is not empty");
6606 return NGTCP2_ERR_DISCARD_PKT;
6607 }
6608
6609 if (hd.version != conn->client_chosen_version &&
6610 !conn->negotiated_version && conn->vneg.version != hd.version) {
6611 if (!vneg_available_versions_includes(conn->vneg.available_versions,
6612 conn->vneg.available_versionslen,
6613 hd.version)) {
6614 return NGTCP2_ERR_DISCARD_PKT;
6615 }
6616
6617 /* Install new Initial keys using QUIC version = hd.version */
6618 rv = conn_call_version_negotiation(
6619 conn, hd.version,
6620 (conn->flags & NGTCP2_CONN_FLAG_RECV_RETRY) ? &conn->dcid.current.cid
6621 : &conn->rcid);
6622 if (rv != 0) {
6623 return rv;
6624 }
6625
6626 assert(conn->vneg.version == hd.version);
6627 }
6628 }
6629
6630 pktns = conn->in_pktns;
6631 crypto = &pktns->crypto.strm;
6632 encryption_level = NGTCP2_ENCRYPTION_LEVEL_INITIAL;
6633
6634 if (hd.version == conn->client_chosen_version) {
6635 ckm = pktns->crypto.rx.ckm;
6636 hp_ctx = &pktns->crypto.rx.hp_ctx;
6637 } else {
6638 assert(conn->vneg.version == hd.version);
6639
6640 ckm = conn->vneg.rx.ckm;
6641 hp_ctx = &conn->vneg.rx.hp_ctx;
6642 }
6643
6644 break;
6645 case NGTCP2_PKT_HANDSHAKE:
6646 if (hd.version != conn->negotiated_version) {
6647 return NGTCP2_ERR_DISCARD_PKT;
6648 }
6649
6650 if (!conn->hs_pktns->crypto.rx.ckm) {
6651 if (conn->server) {
6652 ngtcp2_log_info(
6653 &conn->log, NGTCP2_LOG_EVENT_PKT,
6654 "Handshake packet at this point is unexpected and discarded");
6655 return (ngtcp2_ssize)pktlen;
6656 }
6657 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON,
6658 "buffering Handshake packet len=%zu", pktlen);
6659
6660 rv = conn_buffer_pkt(conn, conn->hs_pktns, path, pi, pkt, pktlen,
6661 dgramlen, ts);
6662 if (rv != 0) {
6663 assert(ngtcp2_err_is_fatal(rv));
6664 return rv;
6665 }
6666 return (ngtcp2_ssize)pktlen;
6667 }
6668
6669 pktns = conn->hs_pktns;
6670 crypto = &pktns->crypto.strm;
6671 encryption_level = NGTCP2_ENCRYPTION_LEVEL_HANDSHAKE;
6672 ckm = pktns->crypto.rx.ckm;
6673 hp_ctx = &pktns->crypto.rx.hp_ctx;
6674
6675 break;
6676 default:
6677 ngtcp2_unreachable();
6678 }
6679
6680 hp_mask = conn->callbacks.hp_mask;
6681 decrypt = conn->callbacks.decrypt;
6682 aead = &pktns->crypto.ctx.aead;
6683 hp = &pktns->crypto.ctx.hp;
6684
6685 assert(ckm);
6686 assert(hp_mask);
6687 assert(decrypt);
6688
6689 rv = conn_ensure_decrypt_hp_buffer(conn, (size_t)nread + 4);
6690 if (rv != 0) {
6691 return rv;
6692 }
6693
6694 nwrite = decrypt_hp(&hd, conn->crypto.decrypt_hp_buf.base, hp, pkt, pktlen,
6695 (size_t)nread, hp_ctx, hp_mask);
6696 if (nwrite < 0) {
6697 if (ngtcp2_err_is_fatal((int)nwrite)) {
6698 return nwrite;
6699 }
6700 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
6701 "could not decrypt packet number");
6702 return NGTCP2_ERR_DISCARD_PKT;
6703 }
6704
6705 hdpktlen = (size_t)nwrite;
6706 payload = pkt + hdpktlen;
6707 payloadlen = hd.len - hd.pkt_numlen;
6708
6709 hd.pkt_num = ngtcp2_pkt_adjust_pkt_num(pktns->acktr.max_pkt_num, hd.pkt_num,
6710 hd.pkt_numlen);
6711 if (hd.pkt_num > NGTCP2_MAX_PKT_NUM) {
6712 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_PKT,
6713 "pkn=%" PRId64 " is greater than maximum pkn", hd.pkt_num);
6714 return NGTCP2_ERR_DISCARD_PKT;
6715 }
6716
6717 ngtcp2_log_rx_pkt_hd(&conn->log, &hd);
6718
6719 rv = ngtcp2_pkt_verify_reserved_bits(conn->crypto.decrypt_hp_buf.base[0]);
6720 if (rv != 0) {
6721 invalid_reserved_bits = 1;
6722
6723 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
6724 "packet has incorrect reserved bits");
6725
6726 /* Will return error after decrypting payload */
6727 }
6728
6729 if (pktns_pkt_num_is_duplicate(pktns, hd.pkt_num)) {
6730 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
6731 "packet was discarded because of duplicated packet number");
6732 return NGTCP2_ERR_DISCARD_PKT;
6733 }
6734
6735 rv = conn_ensure_decrypt_buffer(conn, payloadlen);
6736 if (rv != 0) {
6737 return rv;
6738 }
6739
6740 nwrite = decrypt_pkt(conn->crypto.decrypt_buf.base, aead, payload, payloadlen,
6741 conn->crypto.decrypt_hp_buf.base, hdpktlen, hd.pkt_num,
6742 ckm, decrypt);
6743 if (nwrite < 0) {
6744 if (ngtcp2_err_is_fatal((int)nwrite)) {
6745 return nwrite;
6746 }
6747 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
6748 "could not decrypt packet payload");
6749 return NGTCP2_ERR_DISCARD_PKT;
6750 }
6751
6752 if (invalid_reserved_bits) {
6753 return NGTCP2_ERR_PROTO;
6754 }
6755
6756 if (!conn->server && hd.version != conn->client_chosen_version &&
6757 !conn->negotiated_version) {
6758 conn->negotiated_version = hd.version;
6759
6760 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON,
6761 "the negotiated version is 0x%08x",
6762 conn->negotiated_version);
6763 }
6764
6765 payload = conn->crypto.decrypt_buf.base;
6766 payloadlen = (size_t)nwrite;
6767
6768 switch (hd.type) {
6769 case NGTCP2_PKT_INITIAL:
6770 if (!conn->server ||
6771 ((conn->flags & NGTCP2_CONN_FLAG_INITIAL_PKT_PROCESSED) &&
6772 !ngtcp2_cid_eq(&conn->rcid, &hd.dcid))) {
6773 rv = conn_verify_dcid(conn, NULL, &hd);
6774 if (rv != 0) {
6775 if (ngtcp2_err_is_fatal(rv)) {
6776 return rv;
6777 }
6778 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
6779 "packet was ignored because of mismatched DCID");
6780 return NGTCP2_ERR_DISCARD_PKT;
6781 }
6782 }
6783 break;
6784 case NGTCP2_PKT_HANDSHAKE:
6785 rv = conn_verify_dcid(conn, NULL, &hd);
6786 if (rv != 0) {
6787 if (ngtcp2_err_is_fatal(rv)) {
6788 return rv;
6789 }
6790 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
6791 "packet was ignored because of mismatched DCID");
6792 return NGTCP2_ERR_DISCARD_PKT;
6793 }
6794 break;
6795 default:
6796 ngtcp2_unreachable();
6797 }
6798
6799 if (payloadlen == 0) {
6800 /* QUIC packet must contain at least one frame */
6801 if (hd.type == NGTCP2_PKT_INITIAL) {
6802 return NGTCP2_ERR_DISCARD_PKT;
6803 }
6804 return NGTCP2_ERR_PROTO;
6805 }
6806
6807 if (hd.type == NGTCP2_PKT_INITIAL &&
6808 !(conn->flags & NGTCP2_CONN_FLAG_INITIAL_PKT_PROCESSED)) {
6809 conn->flags |= NGTCP2_CONN_FLAG_INITIAL_PKT_PROCESSED;
6810 if (!conn->server) {
6811 conn->dcid.current.cid = hd.scid;
6812 }
6813 }
6814
6815 ngtcp2_qlog_pkt_received_start(&conn->qlog);
6816
6817 for (; payloadlen;) {
6818 nread = ngtcp2_frame_decoder_decode(&frd, &fr, payload, payloadlen);
6819 if (nread < 0) {
6820 return nread;
6821 }
6822
6823 payload += nread;
6824 payloadlen -= (size_t)nread;
6825
6826 switch (fr.hd.type) {
6827 case NGTCP2_FRAME_ACK:
6828 case NGTCP2_FRAME_ACK_ECN:
6829 fr.ack.ack_delay = 0;
6830 fr.ack.ack_delay_unscaled = 0;
6831
6832 rv =
6833 ngtcp2_pkt_validate_ack(&fr.ack, conn->local.settings.initial_pkt_num);
6834 if (rv != 0) {
6835 return rv;
6836 }
6837
6838 break;
6839 }
6840
6841 ngtcp2_log_rx_fr(&conn->log, &hd, &fr);
6842
6843 switch (fr.hd.type) {
6844 case NGTCP2_FRAME_ACK:
6845 case NGTCP2_FRAME_ACK_ECN:
6846 if (num_ack_processed >= NGTCP2_MAX_ACK_PER_PKT) {
6847 break;
6848 }
6849 if (!conn->server && hd.type == NGTCP2_PKT_HANDSHAKE) {
6850 conn->flags |= NGTCP2_CONN_FLAG_SERVER_ADDR_VERIFIED;
6851 }
6852 rv = conn_recv_ack(conn, pktns, &fr.ack, pkt_ts, ts);
6853 if (rv != 0) {
6854 return rv;
6855 }
6856 ++num_ack_processed;
6857 break;
6858 case NGTCP2_FRAME_PADDING:
6859 break;
6860 case NGTCP2_FRAME_CRYPTO:
6861 if (!conn->server && !conn->negotiated_version &&
6862 ngtcp2_vec_len(fr.stream.data, fr.stream.datacnt)) {
6863 conn->negotiated_version = hd.version;
6864
6865 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON,
6866 "the negotiated version is 0x%08x",
6867 conn->negotiated_version);
6868 }
6869
6870 rv = conn_recv_crypto(conn, encryption_level, crypto, &fr.stream, ts);
6871 if (rv != 0) {
6872 return rv;
6873 }
6874 require_ack = 1;
6875 break;
6876 case NGTCP2_FRAME_CONNECTION_CLOSE:
6877 rv = conn_recv_connection_close(conn, &fr.connection_close);
6878 if (rv != 0) {
6879 return rv;
6880 }
6881 break;
6882 case NGTCP2_FRAME_PING:
6883 ++conn->cstat.ping_recv;
6884 require_ack = 1;
6885 break;
6886 default:
6887 return NGTCP2_ERR_PROTO;
6888 }
6889
6890 ngtcp2_qlog_write_frame(&conn->qlog, &fr);
6891 }
6892
6893 if (hd.type == NGTCP2_PKT_HANDSHAKE) {
6894 /* Successful processing of Handshake packet from a remote
6895 endpoint validates its source address. */
6896 conn->dcid.current.flags |= NGTCP2_DCID_FLAG_PATH_VALIDATED;
6897 }
6898
6899 ngtcp2_qlog_pkt_received_end(&conn->qlog, &hd, pktlen);
6900
6901 rv = pktns_commit_recv_pkt_num(pktns, hd.pkt_num, pi, require_ack, pkt_ts);
6902 if (rv != 0) {
6903 return rv;
6904 }
6905
6906 /* Initial and Handshake are always acknowledged without delay. No
6907 need to call ngtcp2_acktr_immediate_ack(). */
6908
6909 conn_restart_timer_on_read(conn, ts);
6910
6911 ngtcp2_qlog_metrics_updated(&conn->qlog, &conn->cstat);
6912
6913 return conn->state == NGTCP2_CS_DRAINING ? NGTCP2_ERR_DRAINING
6914 : (ngtcp2_ssize)pktlen;
6915 }
6916
6917 static int is_unrecoverable_error(int liberr) {
6918 switch (liberr) {
6919 case NGTCP2_ERR_CRYPTO:
6920 case NGTCP2_ERR_REQUIRED_TRANSPORT_PARAM:
6921 case NGTCP2_ERR_MALFORMED_TRANSPORT_PARAM:
6922 case NGTCP2_ERR_TRANSPORT_PARAM:
6923 case NGTCP2_ERR_VERSION_NEGOTIATION_FAILURE:
6924 case NGTCP2_ERR_INTERNAL:
6925 return 1;
6926 }
6927
6928 return 0;
6929 }
6930
6931 /*
6932 * conn_recv_handshake_cpkt processes compound packet during
6933 * handshake. The buffer pointed by |pkt| might contain multiple
6934 * packets. The 1RTT packet must be the last one because it does not
6935 * have payload length field.
6936 *
6937 * This function returns the same error code returned by
6938 * conn_recv_handshake_pkt.
6939 */
6940 static ngtcp2_ssize conn_recv_handshake_cpkt(ngtcp2_conn *conn,
6941 const ngtcp2_path *path,
6942 const ngtcp2_pkt_info *pi,
6943 const uint8_t *pkt, size_t pktlen,
6944 ngtcp2_tstamp ts) {
6945 ngtcp2_ssize nread;
6946 size_t dgramlen = pktlen;
6947 const uint8_t *origpkt = pkt;
6948 uint32_t version;
6949
6950 if (ngtcp2_path_eq(&conn->dcid.current.ps.path, path)) {
6951 conn->dcid.current.bytes_recv += dgramlen;
6952 }
6953
6954 while (pktlen) {
6955 nread =
6956 conn_recv_handshake_pkt(conn, path, pi, pkt, pktlen, dgramlen, ts, ts);
6957 if (nread < 0) {
6958 if (ngtcp2_err_is_fatal((int)nread)) {
6959 return nread;
6960 }
6961
6962 if (nread == NGTCP2_ERR_DRAINING) {
6963 return NGTCP2_ERR_DRAINING;
6964 }
6965
6966 if ((pkt[0] & NGTCP2_HEADER_FORM_BIT) && pktlen > 4) {
6967 /* Not a Version Negotiation packet */
6968 ngtcp2_get_uint32be(&version, &pkt[1]);
6969 if (ngtcp2_pkt_get_type_long(version, pkt[0]) == NGTCP2_PKT_INITIAL) {
6970 if (conn->server) {
6971 if (is_unrecoverable_error((int)nread)) {
6972 /* If server gets crypto error from TLS stack, it is
6973 unrecoverable, therefore drop connection. */
6974 return nread;
6975 }
6976
6977 ++conn->cstat.pkt_discarded;
6978
6979 /* If server discards first Initial, then drop connection
6980 state. This is because SCID in packet might be corrupted
6981 and the current connection state might wrongly discard
6982 valid packet and prevent the handshake from
6983 completing. */
6984 if (conn->in_pktns && conn->in_pktns->acktr.max_pkt_num == -1) {
6985 return NGTCP2_ERR_DROP_CONN;
6986 }
6987
6988 return (ngtcp2_ssize)dgramlen;
6989 }
6990 /* client */
6991 if (is_unrecoverable_error((int)nread)) {
6992 /* If client gets crypto error from TLS stack, it is
6993 unrecoverable, therefore drop connection. */
6994 return nread;
6995 }
6996
6997 ++conn->cstat.pkt_discarded;
6998
6999 return (ngtcp2_ssize)dgramlen;
7000 }
7001 }
7002
7003 if (nread == NGTCP2_ERR_DISCARD_PKT) {
7004 ++conn->cstat.pkt_discarded;
7005 return (ngtcp2_ssize)dgramlen;
7006 }
7007
7008 return nread;
7009 }
7010
7011 if (nread == 0) {
7012 assert(!(pkt[0] & NGTCP2_HEADER_FORM_BIT));
7013 return pkt - origpkt;
7014 }
7015
7016 assert(pktlen >= (size_t)nread);
7017 pkt += nread;
7018 pktlen -= (size_t)nread;
7019
7020 ++conn->cstat.pkt_recv;
7021 conn->cstat.bytes_recv += (uint64_t)nread;
7022
7023 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_PKT,
7024 "read packet %td left %zu", nread, pktlen);
7025 }
7026
7027 return (ngtcp2_ssize)dgramlen;
7028 }
7029
7030 int ngtcp2_conn_init_stream(ngtcp2_conn *conn, ngtcp2_strm *strm,
7031 int64_t stream_id, void *stream_user_data) {
7032 int rv;
7033 uint64_t max_rx_offset;
7034 uint64_t max_tx_offset;
7035 int local_stream = conn_local_stream(conn, stream_id);
7036
7037 assert(conn->remote.transport_params);
7038
7039 if (bidi_stream(stream_id)) {
7040 if (local_stream) {
7041 max_rx_offset =
7042 conn->local.transport_params.initial_max_stream_data_bidi_local;
7043 max_tx_offset =
7044 conn->remote.transport_params->initial_max_stream_data_bidi_remote;
7045 } else {
7046 max_rx_offset =
7047 conn->local.transport_params.initial_max_stream_data_bidi_remote;
7048 max_tx_offset =
7049 conn->remote.transport_params->initial_max_stream_data_bidi_local;
7050 }
7051 } else if (local_stream) {
7052 max_rx_offset = 0;
7053 max_tx_offset = conn->remote.transport_params->initial_max_stream_data_uni;
7054 } else {
7055 max_rx_offset = conn->local.transport_params.initial_max_stream_data_uni;
7056 max_tx_offset = 0;
7057 }
7058
7059 ngtcp2_strm_init(strm, stream_id, NGTCP2_STRM_FLAG_NONE, max_rx_offset,
7060 max_tx_offset, stream_user_data, &conn->frc_objalloc,
7061 conn->mem);
7062
7063 rv =
7064 ngtcp2_map_insert(&conn->strms, (ngtcp2_map_key_type)strm->stream_id, strm);
7065 if (rv != 0) {
7066 assert(rv != NGTCP2_ERR_INVALID_ARGUMENT);
7067 goto fail;
7068 }
7069
7070 return 0;
7071
7072 fail:
7073 ngtcp2_strm_free(strm);
7074 return rv;
7075 }
7076
7077 /*
7078 * conn_emit_pending_stream_data passes buffered ordered stream data
7079 * to the application. |rx_offset| is the first offset to deliver to
7080 * the application. This function assumes that the data up to
7081 * |rx_offset| has been delivered already. This function only passes
7082 * the ordered data without any gap. If there is a gap, it stops
7083 * providing the data to the application, and returns.
7084 *
7085 * This function returns 0 if it succeeds, or one of the following
7086 * negative error codes:
7087 *
7088 * NGTCP2_ERR_CALLBACK_FAILURE
7089 * User callback failed.
7090 * NGTCP2_ERR_NOMEM
7091 * Out of memory.
7092 */
7093 static int conn_emit_pending_stream_data(ngtcp2_conn *conn, ngtcp2_strm *strm,
7094 uint64_t rx_offset) {
7095 size_t datalen;
7096 const uint8_t *data;
7097 int rv;
7098 uint64_t offset;
7099 uint32_t sdflags;
7100 int handshake_completed = conn_is_tls_handshake_completed(conn);
7101
7102 if (!strm->rx.rob) {
7103 return 0;
7104 }
7105
7106 for (;;) {
7107 /* Stop calling callback if application has called
7108 ngtcp2_conn_shutdown_stream_read() inside the callback.
7109 Because it doubly counts connection window. */
7110 if (strm->flags & NGTCP2_STRM_FLAG_STOP_SENDING) {
7111 return 0;
7112 }
7113
7114 datalen = ngtcp2_rob_data_at(strm->rx.rob, &data, rx_offset);
7115 if (datalen == 0) {
7116 assert(rx_offset == ngtcp2_strm_rx_offset(strm));
7117 return 0;
7118 }
7119
7120 offset = rx_offset;
7121 rx_offset += datalen;
7122
7123 sdflags = NGTCP2_STREAM_DATA_FLAG_NONE;
7124 if ((strm->flags & NGTCP2_STRM_FLAG_SHUT_RD) &&
7125 rx_offset == strm->rx.last_offset) {
7126 sdflags |= NGTCP2_STREAM_DATA_FLAG_FIN;
7127 }
7128 if (!handshake_completed) {
7129 sdflags |= NGTCP2_STREAM_DATA_FLAG_0RTT;
7130 }
7131
7132 rv = conn_call_recv_stream_data(conn, strm, sdflags, offset, data, datalen);
7133 if (rv != 0) {
7134 return rv;
7135 }
7136
7137 /* ngtcp2_conn_shutdown_stream_read from a callback will free
7138 strm->rx.rob. */
7139 if (!strm->rx.rob) {
7140 return 0;
7141 }
7142
7143 ngtcp2_rob_pop(strm->rx.rob, rx_offset - datalen, datalen);
7144 }
7145 }
7146
7147 /*
7148 * conn_recv_crypto is called when CRYPTO frame |fr| is received.
7149 * |rx_offset_base| is the offset in the entire TLS handshake stream.
7150 * fr->offset specifies the offset in each encryption level.
7151 * |max_rx_offset| is, if it is nonzero, the maximum offset in the
7152 * entire TLS handshake stream that |fr| can carry.
7153 * |encryption_level| is the encryption level where this data is
7154 * received.
7155 *
7156 * This function returns 0 if it succeeds, or one of the following
7157 * negative error codes:
7158 *
7159 * NGTCP2_ERR_PROTO
7160 * CRYPTO frame has invalid offset.
7161 * NGTCP2_ERR_NOMEM
7162 * Out of memory.
7163 * NGTCP2_ERR_CRYPTO
7164 * TLS stack reported error.
7165 * NGTCP2_ERR_FRAME_ENCODING
7166 * The end offset exceeds the maximum value.
7167 * NGTCP2_ERR_CALLBACK_FAILURE
7168 * User-defined callback function failed.
7169 * NGTCP2_ERR_INTERNAL
7170 * Suspicious remote endpoint activity exceeded threshold.
7171 */
7172 static int conn_recv_crypto(ngtcp2_conn *conn,
7173 ngtcp2_encryption_level encryption_level,
7174 ngtcp2_strm *crypto, const ngtcp2_stream *fr,
7175 ngtcp2_tstamp ts) {
7176 uint64_t fr_end_offset;
7177 uint64_t rx_offset;
7178 int rv;
7179 ngtcp2_ssize nwrite;
7180
7181 if (fr->datacnt == 0) {
7182 if (encryption_level != NGTCP2_ENCRYPTION_LEVEL_INITIAL &&
7183 ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7184 return NGTCP2_ERR_INTERNAL;
7185 }
7186
7187 return 0;
7188 }
7189
7190 fr_end_offset = fr->offset + fr->data[0].len;
7191
7192 if (NGTCP2_MAX_VARINT < fr_end_offset) {
7193 return NGTCP2_ERR_FRAME_ENCODING;
7194 }
7195
7196 rx_offset = ngtcp2_strm_rx_offset(crypto);
7197
7198 if (fr_end_offset <= rx_offset) {
7199 if (encryption_level != NGTCP2_ENCRYPTION_LEVEL_INITIAL &&
7200 ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7201 return NGTCP2_ERR_INTERNAL;
7202 }
7203
7204 if (conn->server &&
7205 !(conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_EARLY_RETRANSMIT) &&
7206 encryption_level == NGTCP2_ENCRYPTION_LEVEL_INITIAL) {
7207 /* https://datatracker.ietf.org/doc/html/rfc9002#section-6.2.3:
7208 Speeding Up Handshake Completion
7209
7210 When a server receives an Initial packet containing duplicate
7211 CRYPTO data, it can assume the client did not receive all of
7212 the server's CRYPTO data sent in Initial packets, or the
7213 client's estimated RTT is too small. ... To speed up
7214 handshake completion under these conditions, an endpoint MAY
7215 send a packet containing unacknowledged CRYPTO data earlier
7216 than the PTO expiry, subject to address validation limits;
7217 ... */
7218 conn->flags |= NGTCP2_CONN_FLAG_HANDSHAKE_EARLY_RETRANSMIT;
7219 conn->in_pktns->rtb.probe_pkt_left = 1;
7220 conn->hs_pktns->rtb.probe_pkt_left = 1;
7221 }
7222 return 0;
7223 }
7224
7225 crypto->rx.last_offset =
7226 ngtcp2_max_uint64(crypto->rx.last_offset, fr_end_offset);
7227
7228 /* TODO Before dispatching incoming data to TLS stack, make sure
7229 that previous data in previous encryption level has been
7230 completely sent to TLS stack. Usually, if data is left, it is an
7231 error because key is generated after consuming all data in the
7232 previous encryption level. */
7233 if (fr->offset <= rx_offset) {
7234 size_t ncut = (size_t)(rx_offset - fr->offset);
7235 const uint8_t *data = fr->data[0].base + ncut;
7236 size_t datalen = fr->data[0].len - ncut;
7237 uint64_t offset = rx_offset;
7238
7239 rx_offset += datalen;
7240 ngtcp2_strm_update_rx_offset(crypto, rx_offset);
7241
7242 rv =
7243 conn_call_recv_crypto_data(conn, encryption_level, offset, data, datalen);
7244 if (rv != 0) {
7245 return rv;
7246 }
7247
7248 rv =
7249 conn_emit_pending_crypto_data(conn, encryption_level, crypto, rx_offset);
7250 if (rv != 0) {
7251 return rv;
7252 }
7253
7254 return 0;
7255 }
7256
7257 if (fr_end_offset - rx_offset > NGTCP2_MAX_REORDERED_CRYPTO_DATA) {
7258 return NGTCP2_ERR_CRYPTO_BUFFER_EXCEEDED;
7259 }
7260
7261 nwrite = ngtcp2_strm_recv_reordering(crypto, fr->data[0].base,
7262 fr->data[0].len, fr->offset);
7263 if (nwrite < 0) {
7264 return (int)nwrite;
7265 }
7266
7267 if (encryption_level != NGTCP2_ENCRYPTION_LEVEL_INITIAL && nwrite == 0 &&
7268 ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7269 return NGTCP2_ERR_INTERNAL;
7270 }
7271
7272 return 0;
7273 }
7274
7275 /*
7276 * conn_max_data_violated returns nonzero if receiving |datalen|
7277 * violates connection flow control on local endpoint.
7278 */
7279 static int conn_max_data_violated(ngtcp2_conn *conn, uint64_t datalen) {
7280 return conn->rx.max_offset - conn->rx.offset < datalen;
7281 }
7282
7283 /*
7284 * conn_recv_stream is called when STREAM frame |fr| is received.
7285 *
7286 * This function returns 0 if it succeeds, or one of the following
7287 * negative error codes:
7288 *
7289 * NGTCP2_ERR_STREAM_STATE
7290 * STREAM frame is received for a local stream which is not
7291 * initiated; or STREAM frame is received for a local
7292 * unidirectional stream
7293 * NGTCP2_ERR_STREAM_LIMIT
7294 * STREAM frame has remote stream ID which is strictly greater
7295 * than the allowed limit.
7296 * NGTCP2_ERR_NOMEM
7297 * Out of memory.
7298 * NGTCP2_ERR_CALLBACK_FAILURE
7299 * User-defined callback function failed.
7300 * NGTCP2_ERR_FLOW_CONTROL
7301 * Flow control limit is violated; or the end offset of stream
7302 * data is beyond the NGTCP2_MAX_VARINT.
7303 * NGTCP2_ERR_FINAL_SIZE
7304 * STREAM frame has strictly larger end offset than it is
7305 * permitted.
7306 * NGTCP2_ERR_INTERNAL
7307 * Suspicious remote endpoint activity exceeded threshold.
7308 */
7309 static int conn_recv_stream(ngtcp2_conn *conn, const ngtcp2_stream *fr,
7310 ngtcp2_tstamp ts) {
7311 int rv;
7312 ngtcp2_strm *strm;
7313 ngtcp2_idtr *idtr;
7314 uint64_t rx_offset, fr_end_offset;
7315 int local_stream;
7316 int bidi;
7317 uint64_t datalen = ngtcp2_vec_len(fr->data, fr->datacnt);
7318 uint32_t sdflags = NGTCP2_STREAM_DATA_FLAG_NONE;
7319 ngtcp2_ssize nwrite;
7320 int new_strm = 0;
7321
7322 local_stream = conn_local_stream(conn, fr->stream_id);
7323 bidi = bidi_stream(fr->stream_id);
7324
7325 if (bidi) {
7326 if (local_stream) {
7327 if (conn->local.bidi.next_stream_id <= fr->stream_id) {
7328 return NGTCP2_ERR_STREAM_STATE;
7329 }
7330 } else if (conn->remote.bidi.max_streams <
7331 ngtcp2_ord_stream_id(fr->stream_id)) {
7332 return NGTCP2_ERR_STREAM_LIMIT;
7333 }
7334
7335 idtr = &conn->remote.bidi.idtr;
7336 } else {
7337 if (local_stream) {
7338 return NGTCP2_ERR_STREAM_STATE;
7339 }
7340 if (conn->remote.uni.max_streams < ngtcp2_ord_stream_id(fr->stream_id)) {
7341 return NGTCP2_ERR_STREAM_LIMIT;
7342 }
7343
7344 idtr = &conn->remote.uni.idtr;
7345 }
7346
7347 if (NGTCP2_MAX_VARINT - datalen < fr->offset) {
7348 return NGTCP2_ERR_FLOW_CONTROL;
7349 }
7350
7351 strm = ngtcp2_conn_find_stream(conn, fr->stream_id);
7352 if (strm == NULL) {
7353 if (local_stream) {
7354 /* The stream has been closed. */
7355 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7356 return NGTCP2_ERR_INTERNAL;
7357 }
7358
7359 return 0;
7360 }
7361
7362 rv = ngtcp2_idtr_open(idtr, fr->stream_id);
7363 if (rv != 0) {
7364 if (ngtcp2_err_is_fatal(rv)) {
7365 return rv;
7366 }
7367 assert(rv == NGTCP2_ERR_STREAM_IN_USE);
7368 /* The stream has been closed. */
7369 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7370 return NGTCP2_ERR_INTERNAL;
7371 }
7372
7373 return 0;
7374 }
7375
7376 strm = ngtcp2_objalloc_strm_get(&conn->strm_objalloc);
7377 if (strm == NULL) {
7378 return NGTCP2_ERR_NOMEM;
7379 }
7380
7381 rv = ngtcp2_conn_init_stream(conn, strm, fr->stream_id, NULL);
7382 if (rv != 0) {
7383 ngtcp2_objalloc_strm_release(&conn->strm_objalloc, strm);
7384 return rv;
7385 }
7386
7387 new_strm = 1;
7388
7389 if (!bidi) {
7390 ngtcp2_strm_shutdown(strm, NGTCP2_STRM_FLAG_SHUT_WR);
7391 strm->flags |= NGTCP2_STRM_FLAG_FIN_ACKED;
7392 }
7393
7394 rv = conn_call_stream_open(conn, strm);
7395 if (rv != 0) {
7396 return rv;
7397 }
7398 }
7399
7400 fr_end_offset = fr->offset + datalen;
7401
7402 if (strm->rx.max_offset < fr_end_offset) {
7403 return NGTCP2_ERR_FLOW_CONTROL;
7404 }
7405
7406 if (strm->rx.last_offset < fr_end_offset) {
7407 uint64_t len = fr_end_offset - strm->rx.last_offset;
7408
7409 if (conn_max_data_violated(conn, len)) {
7410 return NGTCP2_ERR_FLOW_CONTROL;
7411 }
7412
7413 conn->rx.offset += len;
7414
7415 if (strm->flags & NGTCP2_STRM_FLAG_STOP_SENDING) {
7416 ngtcp2_conn_extend_max_offset(conn, len);
7417 }
7418 }
7419
7420 rx_offset = ngtcp2_strm_rx_offset(strm);
7421
7422 if (fr->fin) {
7423 if (strm->flags & NGTCP2_STRM_FLAG_SHUT_RD) {
7424 if (strm->rx.last_offset != fr_end_offset) {
7425 return NGTCP2_ERR_FINAL_SIZE;
7426 }
7427
7428 if (strm->flags & NGTCP2_STRM_FLAG_RESET_STREAM_RECVED) {
7429 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7430 return NGTCP2_ERR_INTERNAL;
7431 }
7432
7433 return 0;
7434 }
7435
7436 if (rx_offset == fr_end_offset) {
7437 if (!new_strm && ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7438 return NGTCP2_ERR_INTERNAL;
7439 }
7440
7441 return 0;
7442 }
7443 } else if (strm->rx.last_offset > fr_end_offset) {
7444 return NGTCP2_ERR_FINAL_SIZE;
7445 } else {
7446 strm->rx.last_offset = fr_end_offset;
7447
7448 ngtcp2_strm_shutdown(strm, NGTCP2_STRM_FLAG_SHUT_RD);
7449 }
7450 } else {
7451 if ((strm->flags & NGTCP2_STRM_FLAG_SHUT_RD) &&
7452 strm->rx.last_offset < fr_end_offset) {
7453 return NGTCP2_ERR_FINAL_SIZE;
7454 }
7455
7456 strm->rx.last_offset =
7457 ngtcp2_max_uint64(strm->rx.last_offset, fr_end_offset);
7458
7459 if (fr_end_offset <= rx_offset) {
7460 if (!new_strm && ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7461 return NGTCP2_ERR_INTERNAL;
7462 }
7463
7464 return 0;
7465 }
7466
7467 if (strm->flags & NGTCP2_STRM_FLAG_RESET_STREAM_RECVED) {
7468 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7469 return NGTCP2_ERR_INTERNAL;
7470 }
7471
7472 return 0;
7473 }
7474 }
7475
7476 if (fr->offset <= rx_offset) {
7477 size_t ncut = (size_t)(rx_offset - fr->offset);
7478 uint64_t offset = rx_offset;
7479 const uint8_t *data;
7480 int fin;
7481
7482 if (fr->datacnt) {
7483 data = fr->data[0].base + ncut;
7484 datalen -= ncut;
7485
7486 rx_offset += datalen;
7487 ngtcp2_strm_update_rx_offset(strm, rx_offset);
7488 } else {
7489 data = NULL;
7490 datalen = 0;
7491 }
7492
7493 if (strm->flags & NGTCP2_STRM_FLAG_STOP_SENDING) {
7494 return ngtcp2_conn_close_stream_if_shut_rdwr(conn, strm);
7495 }
7496
7497 fin = (strm->flags & NGTCP2_STRM_FLAG_SHUT_RD) &&
7498 rx_offset == strm->rx.last_offset;
7499
7500 assert(fin || datalen);
7501
7502 if (fin) {
7503 sdflags |= NGTCP2_STREAM_DATA_FLAG_FIN;
7504 }
7505 if (!conn_is_tls_handshake_completed(conn)) {
7506 sdflags |= NGTCP2_STREAM_DATA_FLAG_0RTT;
7507 }
7508 rv = conn_call_recv_stream_data(conn, strm, sdflags, offset, data,
7509 (size_t)datalen);
7510 if (rv != 0) {
7511 return rv;
7512 }
7513
7514 rv = conn_emit_pending_stream_data(conn, strm, rx_offset);
7515 if (rv != 0) {
7516 return rv;
7517 }
7518 } else if (fr->datacnt && !(strm->flags & NGTCP2_STRM_FLAG_STOP_SENDING)) {
7519 nwrite = ngtcp2_strm_recv_reordering(strm, fr->data[0].base,
7520 fr->data[0].len, fr->offset);
7521 if (nwrite < 0) {
7522 return (int)nwrite;
7523 }
7524
7525 if (nwrite == 0 && ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7526 return NGTCP2_ERR_INTERNAL;
7527 }
7528 }
7529 return ngtcp2_conn_close_stream_if_shut_rdwr(conn, strm);
7530 }
7531
7532 /*
7533 * conn_reset_stream adds RESET_STREAM frame to the transmission
7534 * queue.
7535 *
7536 * This function returns 0 if it succeeds, or one of the following
7537 * negative error codes:
7538 *
7539 * NGTCP2_ERR_NOMEM
7540 * Out of memory.
7541 */
7542 static int conn_reset_stream(ngtcp2_conn *conn, ngtcp2_strm *strm,
7543 uint64_t app_error_code) {
7544 strm->flags |= NGTCP2_STRM_FLAG_SEND_RESET_STREAM;
7545 strm->tx.reset_stream_app_error_code = app_error_code;
7546
7547 if (ngtcp2_strm_is_tx_queued(strm)) {
7548 return 0;
7549 }
7550
7551 strm->cycle = conn_tx_strmq_first_cycle(conn);
7552
7553 return ngtcp2_conn_tx_strmq_push(conn, strm);
7554 }
7555
7556 /*
7557 * conn_stop_sending adds STOP_SENDING frame to the transmission
7558 * queue.
7559 *
7560 * This function returns 0 if it succeeds, or one of the following
7561 * negative error codes:
7562 *
7563 * NGTCP2_ERR_NOMEM
7564 * Out of memory.
7565 */
7566 static int conn_stop_sending(ngtcp2_conn *conn, ngtcp2_strm *strm,
7567 uint64_t app_error_code) {
7568 strm->flags |= NGTCP2_STRM_FLAG_SEND_STOP_SENDING;
7569 strm->tx.stop_sending_app_error_code = app_error_code;
7570
7571 if (ngtcp2_strm_is_tx_queued(strm)) {
7572 return 0;
7573 }
7574
7575 strm->cycle = conn_tx_strmq_first_cycle(conn);
7576
7577 return ngtcp2_conn_tx_strmq_push(conn, strm);
7578 }
7579
7580 /*
7581 * handle_max_remote_streams_extension extends
7582 * |*punsent_max_remote_streams| by |n| if a condition allows it.
7583 */
7584 static void
7585 handle_max_remote_streams_extension(uint64_t *punsent_max_remote_streams,
7586 size_t n) {
7587 if (
7588 #if SIZE_MAX == UINT64_MAX
7589 NGTCP2_MAX_STREAMS < n ||
7590 #endif /* SIZE_MAX == UINT64_MAX */
7591 *punsent_max_remote_streams > (uint64_t)(NGTCP2_MAX_STREAMS - n)) {
7592 *punsent_max_remote_streams = NGTCP2_MAX_STREAMS;
7593 } else {
7594 *punsent_max_remote_streams += n;
7595 }
7596 }
7597
7598 /*
7599 * conn_recv_reset_stream is called when RESET_STREAM |fr| is
7600 * received.
7601 *
7602 * This function returns 0 if it succeeds, or one of the following
7603 * negative error codes:
7604 *
7605 * NGTCP2_ERR_STREAM_STATE
7606 * RESET_STREAM frame is received to the local stream which is not
7607 * initiated.
7608 * NGTCP2_ERR_STREAM_LIMIT
7609 * RESET_STREAM frame has remote stream ID which is strictly
7610 * greater than the allowed limit.
7611 * NGTCP2_ERR_PROTO
7612 * RESET_STREAM frame is received to the local unidirectional
7613 * stream
7614 * NGTCP2_ERR_NOMEM
7615 * Out of memory.
7616 * NGTCP2_ERR_CALLBACK_FAILURE
7617 * User-defined callback function failed.
7618 * NGTCP2_ERR_FLOW_CONTROL
7619 * Flow control limit is violated; or the final size is beyond the
7620 * NGTCP2_MAX_VARINT.
7621 * NGTCP2_ERR_FINAL_SIZE
7622 * The final offset is strictly larger than it is permitted.
7623 * NGTCP2_ERR_INTERNAL
7624 * Suspicious remote endpoint activity exceeded threshold.
7625 */
7626 static int conn_recv_reset_stream(ngtcp2_conn *conn,
7627 const ngtcp2_reset_stream *fr,
7628 ngtcp2_tstamp ts) {
7629 ngtcp2_strm *strm;
7630 int local_stream = conn_local_stream(conn, fr->stream_id);
7631 int bidi = bidi_stream(fr->stream_id);
7632 uint64_t datalen;
7633 ngtcp2_idtr *idtr;
7634 int rv;
7635
7636 /* TODO share this piece of code */
7637 if (bidi) {
7638 if (local_stream) {
7639 if (conn->local.bidi.next_stream_id <= fr->stream_id) {
7640 return NGTCP2_ERR_STREAM_STATE;
7641 }
7642 } else if (conn->remote.bidi.max_streams <
7643 ngtcp2_ord_stream_id(fr->stream_id)) {
7644 return NGTCP2_ERR_STREAM_LIMIT;
7645 }
7646
7647 idtr = &conn->remote.bidi.idtr;
7648 } else {
7649 if (local_stream) {
7650 return NGTCP2_ERR_PROTO;
7651 }
7652 if (conn->remote.uni.max_streams < ngtcp2_ord_stream_id(fr->stream_id)) {
7653 return NGTCP2_ERR_STREAM_LIMIT;
7654 }
7655
7656 idtr = &conn->remote.uni.idtr;
7657 }
7658
7659 if (NGTCP2_MAX_VARINT < fr->final_size) {
7660 return NGTCP2_ERR_FLOW_CONTROL;
7661 }
7662
7663 strm = ngtcp2_conn_find_stream(conn, fr->stream_id);
7664 if (strm == NULL) {
7665 if (local_stream) {
7666 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7667 return NGTCP2_ERR_INTERNAL;
7668 }
7669
7670 return 0;
7671 }
7672
7673 rv = ngtcp2_idtr_open(idtr, fr->stream_id);
7674 if (rv != 0) {
7675 if (ngtcp2_err_is_fatal(rv)) {
7676 return rv;
7677 }
7678 assert(rv == NGTCP2_ERR_STREAM_IN_USE);
7679
7680 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7681 return NGTCP2_ERR_INTERNAL;
7682 }
7683
7684 return 0;
7685 }
7686
7687 if (conn_initial_stream_rx_offset(conn, fr->stream_id) < fr->final_size ||
7688 conn_max_data_violated(conn, fr->final_size)) {
7689 return NGTCP2_ERR_FLOW_CONTROL;
7690 }
7691
7692 /* Stream is reset before we create ngtcp2_strm object. */
7693 strm = ngtcp2_objalloc_strm_get(&conn->strm_objalloc);
7694 if (strm == NULL) {
7695 return NGTCP2_ERR_NOMEM;
7696 }
7697 rv = ngtcp2_conn_init_stream(conn, strm, fr->stream_id, NULL);
7698 if (rv != 0) {
7699 ngtcp2_objalloc_strm_release(&conn->strm_objalloc, strm);
7700 return rv;
7701 }
7702
7703 rv = conn_call_stream_open(conn, strm);
7704 if (rv != 0) {
7705 return rv;
7706 }
7707 }
7708
7709 if ((strm->flags & NGTCP2_STRM_FLAG_SHUT_RD)) {
7710 if (strm->rx.last_offset != fr->final_size) {
7711 return NGTCP2_ERR_FINAL_SIZE;
7712 }
7713 } else if (strm->rx.last_offset > fr->final_size) {
7714 return NGTCP2_ERR_FINAL_SIZE;
7715 }
7716
7717 if (strm->flags & NGTCP2_STRM_FLAG_RESET_STREAM_RECVED) {
7718 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7719 return NGTCP2_ERR_INTERNAL;
7720 }
7721
7722 return 0;
7723 }
7724
7725 if (strm->rx.max_offset < fr->final_size) {
7726 return NGTCP2_ERR_FLOW_CONTROL;
7727 }
7728
7729 datalen = fr->final_size - strm->rx.last_offset;
7730
7731 if (conn_max_data_violated(conn, datalen)) {
7732 return NGTCP2_ERR_FLOW_CONTROL;
7733 }
7734
7735 rv = conn_call_stream_reset(conn, fr->stream_id, fr->final_size,
7736 fr->app_error_code, strm->stream_user_data);
7737 if (rv != 0) {
7738 return rv;
7739 }
7740
7741 /* Extend connection flow control window for the amount of data
7742 which are not passed to application. */
7743 if (!(strm->flags & NGTCP2_STRM_FLAG_STOP_SENDING)) {
7744 ngtcp2_conn_extend_max_offset(conn, strm->rx.last_offset -
7745 ngtcp2_strm_rx_offset(strm));
7746 }
7747
7748 conn->rx.offset += datalen;
7749 ngtcp2_conn_extend_max_offset(conn, datalen);
7750
7751 strm->rx.last_offset = fr->final_size;
7752 strm->flags |=
7753 NGTCP2_STRM_FLAG_SHUT_RD | NGTCP2_STRM_FLAG_RESET_STREAM_RECVED;
7754
7755 ngtcp2_strm_set_app_error_code(strm, fr->app_error_code);
7756
7757 return ngtcp2_conn_close_stream_if_shut_rdwr(conn, strm);
7758 }
7759
7760 /*
7761 * conn_recv_stop_sending is called when STOP_SENDING |fr| is received.
7762 *
7763 * This function returns 0 if it succeeds, or one of the following
7764 * negative error codes:
7765 *
7766 * NGTCP2_ERR_STREAM_STATE
7767 * STOP_SENDING frame is received for a local stream which is not
7768 * initiated; or STOP_SENDING frame is received for a local
7769 * unidirectional stream.
7770 * NGTCP2_ERR_STREAM_LIMIT
7771 * STOP_SENDING frame has remote stream ID which is strictly
7772 * greater than the allowed limit.
7773 * NGTCP2_ERR_NOMEM
7774 * Out of memory.
7775 * NGTCP2_ERR_CALLBACK_FAILURE
7776 * User-defined callback function failed.
7777 * NGTCP2_ERR_INTERNAL
7778 * Suspicious remote endpoint activity exceeded threshold.
7779 */
7780 static int conn_recv_stop_sending(ngtcp2_conn *conn,
7781 const ngtcp2_stop_sending *fr,
7782 ngtcp2_tstamp ts) {
7783 int rv;
7784 ngtcp2_strm *strm;
7785 ngtcp2_idtr *idtr;
7786 int local_stream = conn_local_stream(conn, fr->stream_id);
7787 int bidi = bidi_stream(fr->stream_id);
7788
7789 if (bidi) {
7790 if (local_stream) {
7791 if (conn->local.bidi.next_stream_id <= fr->stream_id) {
7792 return NGTCP2_ERR_STREAM_STATE;
7793 }
7794 } else if (conn->remote.bidi.max_streams <
7795 ngtcp2_ord_stream_id(fr->stream_id)) {
7796 return NGTCP2_ERR_STREAM_LIMIT;
7797 }
7798
7799 idtr = &conn->remote.bidi.idtr;
7800 } else {
7801 if (!local_stream || conn->local.uni.next_stream_id <= fr->stream_id) {
7802 return NGTCP2_ERR_STREAM_STATE;
7803 }
7804
7805 idtr = &conn->remote.uni.idtr;
7806 }
7807
7808 strm = ngtcp2_conn_find_stream(conn, fr->stream_id);
7809 if (strm == NULL) {
7810 if (local_stream) {
7811 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7812 return NGTCP2_ERR_INTERNAL;
7813 }
7814
7815 return 0;
7816 }
7817 rv = ngtcp2_idtr_open(idtr, fr->stream_id);
7818 if (rv != 0) {
7819 if (ngtcp2_err_is_fatal(rv)) {
7820 return rv;
7821 }
7822 assert(rv == NGTCP2_ERR_STREAM_IN_USE);
7823
7824 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7825 return NGTCP2_ERR_INTERNAL;
7826 }
7827
7828 return 0;
7829 }
7830
7831 /* STOP_SENDING frame is received before we create ngtcp2_strm
7832 object. */
7833 strm = ngtcp2_objalloc_strm_get(&conn->strm_objalloc);
7834 if (strm == NULL) {
7835 return NGTCP2_ERR_NOMEM;
7836 }
7837 rv = ngtcp2_conn_init_stream(conn, strm, fr->stream_id, NULL);
7838 if (rv != 0) {
7839 ngtcp2_objalloc_strm_release(&conn->strm_objalloc, strm);
7840 return rv;
7841 }
7842
7843 rv = conn_call_stream_open(conn, strm);
7844 if (rv != 0) {
7845 return rv;
7846 }
7847 }
7848
7849 if (strm->flags & NGTCP2_STRM_FLAG_STOP_SENDING_RECVED) {
7850 if (ngtcp2_ratelim_drain(&conn->glitch_rlim, 1, ts) != 0) {
7851 return NGTCP2_ERR_INTERNAL;
7852 }
7853
7854 return 0;
7855 }
7856
7857 ngtcp2_strm_set_app_error_code(strm, fr->app_error_code);
7858
7859 /* No RESET_STREAM is required if we have sent FIN and all data have
7860 been acknowledged. */
7861 if (!ngtcp2_strm_is_all_tx_data_fin_acked(strm) &&
7862 !(strm->flags & NGTCP2_STRM_FLAG_RESET_STREAM)) {
7863 strm->flags |= NGTCP2_STRM_FLAG_RESET_STREAM;
7864
7865 rv = conn_reset_stream(conn, strm, fr->app_error_code);
7866 if (rv != 0) {
7867 return rv;
7868 }
7869 }
7870
7871 strm->flags |=
7872 NGTCP2_STRM_FLAG_SHUT_WR | NGTCP2_STRM_FLAG_STOP_SENDING_RECVED;
7873
7874 ngtcp2_strm_streamfrq_clear(strm);
7875
7876 return ngtcp2_conn_close_stream_if_shut_rdwr(conn, strm);
7877 }
7878
7879 /*
7880 * check_stateless_reset returns nonzero if Stateless Reset |sr|
7881 * coming via |path| is valid against |dcid|.
7882 */
7883 static int check_stateless_reset(const ngtcp2_dcid *dcid,
7884 const ngtcp2_path *path,
7885 const ngtcp2_pkt_stateless_reset *sr) {
7886 return ngtcp2_dcid_verify_stateless_reset_token(
7887 dcid, path, sr->stateless_reset_token) == 0;
7888 }
7889
7890 /*
7891 * conn_on_stateless_reset decodes Stateless Reset from the buffer
7892 * pointed by |payload| whose length is |payloadlen|. |payload|
7893 * should start after first byte of packet.
7894 *
7895 * If Stateless Reset is decoded, and the Stateless Reset Token is
7896 * validated, the connection is closed.
7897 *
7898 * This function returns 0 if it succeeds, or one of the following
7899 * negative error codes:
7900 *
7901 * NGTCP2_ERR_INVALID_ARGUMENT
7902 * Could not decode Stateless Reset; or Stateless Reset Token does
7903 * not match; or No stateless reset token is available.
7904 * NGTCP2_ERR_CALLBACK_FAILURE
7905 * User callback failed.
7906 */
7907 static int conn_on_stateless_reset(ngtcp2_conn *conn, const ngtcp2_path *path,
7908 const uint8_t *payload, size_t payloadlen) {
7909 int rv;
7910 ngtcp2_pv *pv = conn->pv;
7911 ngtcp2_pkt_stateless_reset sr;
7912
7913 rv = ngtcp2_pkt_decode_stateless_reset(&sr, payload, payloadlen);
7914 if (rv != 0) {
7915 return rv;
7916 }
7917
7918 if (!check_stateless_reset(&conn->dcid.current, path, &sr) &&
7919 (!pv || (!check_stateless_reset(&pv->dcid, path, &sr) &&
7920 (!(pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) ||
7921 !check_stateless_reset(&pv->fallback_dcid, path, &sr))))) {
7922 rv = ngtcp2_dcidtr_verify_stateless_reset(&conn->dcid.dtr, path,
7923 sr.stateless_reset_token);
7924 if (rv != 0) {
7925 return rv;
7926 }
7927 }
7928
7929 conn->state = NGTCP2_CS_DRAINING;
7930
7931 ngtcp2_log_rx_sr(&conn->log, &sr);
7932
7933 ngtcp2_qlog_stateless_reset_pkt_received(&conn->qlog, &sr);
7934
7935 return conn_call_recv_stateless_reset(conn, &sr);
7936 }
7937
7938 /*
7939 * conn_recv_max_streams processes the incoming MAX_STREAMS frame
7940 * |fr|.
7941 *
7942 * This function returns 0 if it succeeds, or one of the following
7943 * negative error codes:
7944 *
7945 * NGTCP2_ERR_CALLBACK_FAILURE
7946 * User callback failed.
7947 * NGTCP2_ERR_FRAME_ENCODING
7948 * The maximum streams field exceeds the maximum value.
7949 */
7950 static int conn_recv_max_streams(ngtcp2_conn *conn,
7951 const ngtcp2_max_streams *fr) {
7952 uint64_t n;
7953
7954 if (fr->max_streams > NGTCP2_MAX_STREAMS) {
7955 return NGTCP2_ERR_FRAME_ENCODING;
7956 }
7957
7958 n = ngtcp2_min_uint64(fr->max_streams, NGTCP2_MAX_STREAMS);
7959
7960 if (fr->type == NGTCP2_FRAME_MAX_STREAMS_BIDI) {
7961 if (conn->local.bidi.max_streams < n) {
7962 conn->local.bidi.max_streams = n;
7963 return conn_call_extend_max_local_streams_bidi(conn, n);
7964 }
7965 return 0;
7966 }
7967
7968 if (conn->local.uni.max_streams < n) {
7969 conn->local.uni.max_streams = n;
7970 return conn_call_extend_max_local_streams_uni(conn, n);
7971 }
7972 return 0;
7973 }
7974
7975 /*
7976 * conn_recv_new_connection_id processes the incoming
7977 * NEW_CONNECTION_ID frame |fr|.
7978 *
7979 * This function returns 0 if it succeeds, or one of the following
7980 * negative error codes:
7981 *
7982 * NGTCP2_ERR_PROTO
7983 * |fr| has the duplicated sequence number with different CID or
7984 * token; or DCID is zero-length.
7985 */
7986 static int conn_recv_new_connection_id(ngtcp2_conn *conn,
7987 const ngtcp2_new_connection_id *fr) {
7988 size_t len;
7989 ngtcp2_pv *pv = conn->pv;
7990 int rv;
7991 int found = 0;
7992 size_t extra_dcid = 0;
7993
7994 if (conn->dcid.current.cid.datalen == 0) {
7995 return NGTCP2_ERR_PROTO;
7996 }
7997
7998 if (fr->retire_prior_to > fr->seq) {
7999 return NGTCP2_ERR_FRAME_ENCODING;
8000 }
8001
8002 rv = ngtcp2_dcid_verify_uniqueness(&conn->dcid.current, fr->seq, &fr->cid,
8003 fr->stateless_reset_token);
8004 if (rv != 0) {
8005 return rv;
8006 }
8007 if (ngtcp2_cid_eq(&conn->dcid.current.cid, &fr->cid)) {
8008 found = 1;
8009 }
8010
8011 if (pv) {
8012 rv = ngtcp2_dcid_verify_uniqueness(&pv->dcid, fr->seq, &fr->cid,
8013 fr->stateless_reset_token);
8014 if (rv != 0) {
8015 return rv;
8016 }
8017 if (ngtcp2_cid_eq(&pv->dcid.cid, &fr->cid)) {
8018 found = 1;
8019 }
8020 }
8021
8022 rv = ngtcp2_dcidtr_verify_token_uniqueness(
8023 &conn->dcid.dtr, &found, fr->seq, &fr->cid, fr->stateless_reset_token);
8024 if (rv != 0) {
8025 return rv;
8026 }
8027
8028 if (conn->dcid.retire_prior_to < fr->retire_prior_to) {
8029 conn->dcid.retire_prior_to = fr->retire_prior_to;
8030
8031 rv = ngtcp2_dcidtr_retire_inactive_dcid_prior_to(
8032 &conn->dcid.dtr, fr->retire_prior_to, dcidtr_on_retire, conn);
8033 if (rv != 0) {
8034 return rv;
8035 }
8036 } else if (fr->seq < conn->dcid.retire_prior_to) {
8037 /* If packets are reordered, we might have retire_prior_to which
8038 is larger than fr->seq.
8039
8040 A malicious peer might send crafted NEW_CONNECTION_ID to force
8041 local endpoint to create lots of RETIRE_CONNECTION_ID frames.
8042 For example, a peer might send seq = 50000 and retire_prior_to
8043 = 50000. Then send NEW_CONNECTION_ID frames with seq <
8044 50000. */
8045 if (ngtcp2_dcidtr_check_retired_seq_tracked(&conn->dcid.dtr, fr->seq)) {
8046 return 0;
8047 }
8048
8049 rv = ngtcp2_dcidtr_track_retired_seq(&conn->dcid.dtr, fr->seq);
8050 if (rv != 0) {
8051 return rv;
8052 }
8053
8054 return conn_enqueue_retire_connection_id(conn, fr->seq);
8055 }
8056
8057 if (found) {
8058 return 0;
8059 }
8060
8061 if (ngtcp2_gaptr_is_pushed(&conn->dcid.seqgap, fr->seq, 1)) {
8062 return 0;
8063 }
8064
8065 rv = ngtcp2_gaptr_push(&conn->dcid.seqgap, fr->seq, 1);
8066 if (rv != 0) {
8067 return rv;
8068 }
8069
8070 if (ngtcp2_ksl_len(&conn->dcid.seqgap.gap) > 32) {
8071 ngtcp2_gaptr_drop_first_gap(&conn->dcid.seqgap);
8072 }
8073
8074 len = ngtcp2_dcidtr_inactive_len(&conn->dcid.dtr);
8075
8076 if (conn->dcid.current.seq >= conn->dcid.retire_prior_to) {
8077 ++extra_dcid;
8078 }
8079 if (pv) {
8080 if (pv->dcid.seq != conn->dcid.current.seq &&
8081 pv->dcid.seq >= conn->dcid.retire_prior_to) {
8082 ++extra_dcid;
8083 }
8084 if ((pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) &&
8085 pv->fallback_dcid.seq != conn->dcid.current.seq &&
8086 pv->fallback_dcid.seq >= conn->dcid.retire_prior_to) {
8087 ++extra_dcid;
8088 }
8089 }
8090
8091 if (conn->local.transport_params.active_connection_id_limit <=
8092 len + extra_dcid) {
8093 return NGTCP2_ERR_CONNECTION_ID_LIMIT;
8094 }
8095
8096 if (len >= NGTCP2_DCIDTR_MAX_UNUSED_DCID_SIZE) {
8097 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CON, "too many connection ID");
8098 return 0;
8099 }
8100
8101 ngtcp2_dcidtr_push_unused(&conn->dcid.dtr, fr->seq, &fr->cid,
8102 fr->stateless_reset_token);
8103
8104 return 0;
8105 }
8106
8107 /*
8108 * conn_post_process_recv_new_connection_id handles retirement request
8109 * of active DCIDs.
8110 *
8111 * This function returns 0 if it succeeds, or one of the following
8112 * negative error codes:
8113 *
8114 * NGTCP2_ERR_NOMEM
8115 * Out of memory.
8116 * NGTCP2_ERR_CALLBACK_FAILURE
8117 * User-defined callback function failed.
8118 */
8119 static int conn_post_process_recv_new_connection_id(ngtcp2_conn *conn,
8120 ngtcp2_tstamp ts) {
8121 ngtcp2_pv *pv = conn->pv;
8122 ngtcp2_dcid dcid;
8123 int rv;
8124
8125 if (conn->dcid.current.seq < conn->dcid.retire_prior_to) {
8126 if (ngtcp2_dcidtr_unused_empty(&conn->dcid.dtr)) {
8127 return 0;
8128 }
8129
8130 rv = conn_retire_active_dcid(conn, &conn->dcid.current, ts);
8131 if (rv != 0) {
8132 return rv;
8133 }
8134
8135 ngtcp2_dcidtr_pop_unused_cid_token(&conn->dcid.dtr, &dcid);
8136
8137 if (pv) {
8138 if (conn->dcid.current.seq == pv->dcid.seq) {
8139 ngtcp2_dcid_copy_cid_token(&pv->dcid, &dcid);
8140 }
8141 if ((pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) &&
8142 conn->dcid.current.seq == pv->fallback_dcid.seq) {
8143 ngtcp2_dcid_copy_cid_token(&pv->fallback_dcid, &dcid);
8144 }
8145 }
8146
8147 ngtcp2_dcid_copy_cid_token(&conn->dcid.current, &dcid);
8148
8149 rv = conn_call_activate_dcid(conn, &conn->dcid.current);
8150 if (rv != 0) {
8151 return rv;
8152 }
8153 }
8154
8155 if (pv) {
8156 if (pv->dcid.seq < conn->dcid.retire_prior_to) {
8157 if (ngtcp2_dcidtr_unused_empty(&conn->dcid.dtr)) {
8158 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PTV,
8159 "path migration is aborted because connection ID is"
8160 "retired and no unused connection ID is available");
8161
8162 return conn_abort_pv(conn, ts);
8163 }
8164
8165 rv = conn_retire_active_dcid(conn, &pv->dcid, ts);
8166 if (rv != 0) {
8167 return rv;
8168 }
8169
8170 ngtcp2_dcidtr_pop_unused_cid_token(&conn->dcid.dtr, &dcid);
8171
8172 if ((pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) &&
8173 pv->dcid.seq == pv->fallback_dcid.seq) {
8174 ngtcp2_dcid_copy_cid_token(&pv->fallback_dcid, &dcid);
8175 }
8176
8177 ngtcp2_dcid_copy_cid_token(&pv->dcid, &dcid);
8178
8179 rv = conn_call_activate_dcid(conn, &pv->dcid);
8180 if (rv != 0) {
8181 return rv;
8182 }
8183 }
8184 if ((pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) &&
8185 pv->fallback_dcid.seq < conn->dcid.retire_prior_to) {
8186 if (ngtcp2_dcidtr_unused_empty(&conn->dcid.dtr)) {
8187 /* Now we have no fallback dcid. */
8188 return conn_abort_pv(conn, ts);
8189 }
8190
8191 rv = conn_retire_active_dcid(conn, &pv->fallback_dcid, ts);
8192 if (rv != 0) {
8193 return rv;
8194 }
8195
8196 ngtcp2_dcidtr_pop_unused_cid_token(&conn->dcid.dtr, &dcid);
8197 ngtcp2_dcid_copy_cid_token(&pv->fallback_dcid, &dcid);
8198
8199 rv = conn_call_activate_dcid(conn, &pv->fallback_dcid);
8200 if (rv != 0) {
8201 return rv;
8202 }
8203 }
8204 }
8205
8206 return 0;
8207 }
8208
8209 /*
8210 * conn_recv_retire_connection_id processes the incoming
8211 * RETIRE_CONNECTION_ID frame |fr|. |hd| is a packet header which
8212 * |fr| is included.
8213 *
8214 * This function returns 0 if it succeeds, or one of the following
8215 * negative error codes:
8216 *
8217 * NGTCP2_ERR_NOMEM
8218 * Out of memory.
8219 * NGTCP2_ERR_PROTO
8220 * SCID is zero-length.
8221 * NGTCP2_ERR_FRAME_ENCODING
8222 * Attempt to retire CID which is used as DCID to send this frame.
8223 */
8224 static int conn_recv_retire_connection_id(ngtcp2_conn *conn,
8225 const ngtcp2_pkt_hd *hd,
8226 const ngtcp2_retire_connection_id *fr,
8227 ngtcp2_tstamp ts) {
8228 ngtcp2_ksl_it it;
8229 ngtcp2_scid *scid;
8230
8231 if (conn->oscid.datalen == 0 || conn->scid.last_seq < fr->seq) {
8232 return NGTCP2_ERR_PROTO;
8233 }
8234
8235 for (it = ngtcp2_ksl_begin(&conn->scid.set); !ngtcp2_ksl_it_end(&it);
8236 ngtcp2_ksl_it_next(&it)) {
8237 scid = ngtcp2_ksl_it_get(&it);
8238 if (scid->seq == fr->seq) {
8239 if (ngtcp2_cid_eq(&scid->cid, &hd->dcid)) {
8240 return NGTCP2_ERR_PROTO;
8241 }
8242
8243 if (!(scid->flags & NGTCP2_SCID_FLAG_RETIRED)) {
8244 scid->flags |= NGTCP2_SCID_FLAG_RETIRED;
8245 ++conn->scid.num_retired;
8246 }
8247
8248 if (scid->pe.index != NGTCP2_PQ_BAD_INDEX) {
8249 ngtcp2_pq_remove(&conn->scid.used, &scid->pe);
8250 scid->pe.index = NGTCP2_PQ_BAD_INDEX;
8251 }
8252
8253 scid->retired_ts = ts;
8254
8255 return ngtcp2_pq_push(&conn->scid.used, &scid->pe);
8256 }
8257 }
8258
8259 return 0;
8260 }
8261
8262 /*
8263 * conn_recv_new_token processes the incoming NEW_TOKEN frame |fr|.
8264 *
8265 * This function returns 0 if it succeeds, or one of the following
8266 * negative error codes:
8267 *
8268 * NGTCP2_ERR_FRAME_ENCODING
8269 * Token is empty
8270 * NGTCP2_ERR_PROTO:
8271 * Server received NEW_TOKEN.
8272 */
8273 static int conn_recv_new_token(ngtcp2_conn *conn, const ngtcp2_new_token *fr) {
8274 if (conn->server) {
8275 return NGTCP2_ERR_PROTO;
8276 }
8277
8278 if (fr->tokenlen == 0) {
8279 return NGTCP2_ERR_FRAME_ENCODING;
8280 }
8281
8282 return conn_call_recv_new_token(conn, fr->token, fr->tokenlen);
8283 }
8284
8285 /*
8286 * conn_recv_streams_blocked_bidi processes the incoming
8287 * STREAMS_BLOCKED (0x16).
8288 *
8289 * This function returns 0 if it succeeds, or one of the following
8290 * negative error codes:
8291 *
8292 * NGTCP2_ERR_FRAME_ENCODING
8293 * Maximum Streams is larger than advertised value.
8294 */
8295 static int conn_recv_streams_blocked_bidi(ngtcp2_conn *conn,
8296 ngtcp2_streams_blocked *fr) {
8297 if (fr->max_streams > conn->remote.bidi.max_streams) {
8298 return NGTCP2_ERR_FRAME_ENCODING;
8299 }
8300
8301 return 0;
8302 }
8303
8304 /*
8305 * conn_recv_streams_blocked_uni processes the incoming
8306 * STREAMS_BLOCKED (0x17).
8307 *
8308 * This function returns 0 if it succeeds, or one of the following
8309 * negative error codes:
8310 *
8311 * NGTCP2_ERR_FRAME_ENCODING
8312 * Maximum Streams is larger than advertised value.
8313 */
8314 static int conn_recv_streams_blocked_uni(ngtcp2_conn *conn,
8315 ngtcp2_streams_blocked *fr) {
8316 if (fr->max_streams > conn->remote.uni.max_streams) {
8317 return NGTCP2_ERR_FRAME_ENCODING;
8318 }
8319
8320 return 0;
8321 }
8322
8323 /*
8324 * conn_recv_stream_data_blocked processes the incoming
8325 * STREAM_DATA_BLOCKED frame |fr|.
8326 *
8327 * This function returns 0 if it succeeds, or one of the following
8328 * negative error codes:
8329 *
8330 * NGTCP2_ERR_STREAM_STATE
8331 * STREAM_DATA_BLOCKED is received for a local stream which is not
8332 * initiated; or it is received for a local unidirectional stream.
8333 * NGTCP2_ERR_STREAM_LIMIT
8334 * STREAM_DATA_BLOCKED has remote stream ID which is strictly
8335 * greater than the allowed limit.
8336 * NGTCP2_ERR_FLOW_CONTROL
8337 * STREAM_DATA_BLOCKED frame violates flow control limit.
8338 * NGTCP2_ERR_FINAL_SIZE
8339 * The offset is strictly larger than it is permitted.
8340 * NGTCP2_ERR_NOMEM
8341 * Out of memory.
8342 * NGTCP2_ERR_CALLBACK_FAILURE
8343 * User-defined callback function failed.
8344 */
8345 static int conn_recv_stream_data_blocked(ngtcp2_conn *conn,
8346 ngtcp2_stream_data_blocked *fr) {
8347 int rv;
8348 ngtcp2_strm *strm;
8349 ngtcp2_idtr *idtr;
8350 int local_stream = conn_local_stream(conn, fr->stream_id);
8351 int bidi = bidi_stream(fr->stream_id);
8352 uint64_t datalen;
8353
8354 if (bidi) {
8355 if (local_stream) {
8356 if (conn->local.bidi.next_stream_id <= fr->stream_id) {
8357 return NGTCP2_ERR_STREAM_STATE;
8358 }
8359 } else if (conn->remote.bidi.max_streams <
8360 ngtcp2_ord_stream_id(fr->stream_id)) {
8361 return NGTCP2_ERR_STREAM_LIMIT;
8362 }
8363
8364 idtr = &conn->remote.bidi.idtr;
8365 } else {
8366 if (local_stream) {
8367 return NGTCP2_ERR_STREAM_STATE;
8368 }
8369 if (conn->remote.uni.max_streams < ngtcp2_ord_stream_id(fr->stream_id)) {
8370 return NGTCP2_ERR_STREAM_LIMIT;
8371 }
8372
8373 idtr = &conn->remote.uni.idtr;
8374 }
8375
8376 strm = ngtcp2_conn_find_stream(conn, fr->stream_id);
8377 if (strm == NULL) {
8378 if (local_stream) {
8379 return 0;
8380 }
8381
8382 rv = ngtcp2_idtr_open(idtr, fr->stream_id);
8383 if (rv != 0) {
8384 if (ngtcp2_err_is_fatal(rv)) {
8385 return rv;
8386 }
8387 assert(rv == NGTCP2_ERR_STREAM_IN_USE);
8388 return 0;
8389 }
8390
8391 /* Frame is received before we create ngtcp2_strm object. */
8392 strm = ngtcp2_objalloc_strm_get(&conn->strm_objalloc);
8393 if (strm == NULL) {
8394 return NGTCP2_ERR_NOMEM;
8395 }
8396 rv = ngtcp2_conn_init_stream(conn, strm, fr->stream_id, NULL);
8397 if (rv != 0) {
8398 ngtcp2_objalloc_strm_release(&conn->strm_objalloc, strm);
8399 return rv;
8400 }
8401
8402 if (!bidi) {
8403 ngtcp2_strm_shutdown(strm, NGTCP2_STRM_FLAG_SHUT_WR);
8404 strm->flags |= NGTCP2_STRM_FLAG_FIN_ACKED;
8405 }
8406
8407 rv = conn_call_stream_open(conn, strm);
8408 if (rv != 0) {
8409 return rv;
8410 }
8411 }
8412
8413 if (strm->rx.max_offset < fr->offset) {
8414 return NGTCP2_ERR_FLOW_CONTROL;
8415 }
8416
8417 if (fr->offset <= strm->rx.last_offset) {
8418 return 0;
8419 }
8420
8421 if (strm->flags & NGTCP2_STRM_FLAG_SHUT_RD) {
8422 return NGTCP2_ERR_FINAL_SIZE;
8423 }
8424
8425 datalen = fr->offset - strm->rx.last_offset;
8426 if (datalen) {
8427 if (conn_max_data_violated(conn, datalen)) {
8428 return NGTCP2_ERR_FLOW_CONTROL;
8429 }
8430
8431 conn->rx.offset += datalen;
8432
8433 if (strm->flags & NGTCP2_STRM_FLAG_STOP_SENDING) {
8434 ngtcp2_conn_extend_max_offset(conn, datalen);
8435 }
8436 }
8437
8438 strm->rx.last_offset = fr->offset;
8439
8440 return 0;
8441 }
8442
8443 /*
8444 * conn_recv_data_blocked processes the incoming DATA_BLOCKED frame
8445 * |fr|.
8446 *
8447 * This function returns 0 if it succeeds, or one of the following
8448 * negative error codes:
8449 *
8450 * NGTCP2_ERR_FLOW_CONTROL
8451 * It violates connection-level flow control limit.
8452 */
8453 static int conn_recv_data_blocked(ngtcp2_conn *conn, ngtcp2_data_blocked *fr) {
8454 if (conn->rx.max_offset < fr->offset) {
8455 return NGTCP2_ERR_FLOW_CONTROL;
8456 }
8457
8458 return 0;
8459 }
8460
8461 /*
8462 * conn_select_preferred_addr asks a client application to select a
8463 * server address from preferred addresses received from server. If a
8464 * client chooses the address, path validation will start.
8465 *
8466 * This function returns 0 if it succeeds, or one of the following
8467 * negative error codes:
8468 *
8469 * NGTCP2_ERR_NOMEM
8470 * Out of memory.
8471 * NGTCP2_ERR_CALLBACK_FAILURE
8472 * User-defined callback function failed.
8473 */
8474 static int conn_select_preferred_addr(ngtcp2_conn *conn) {
8475 ngtcp2_path_storage ps;
8476 int rv;
8477 ngtcp2_pv *pv;
8478 ngtcp2_dcid dcid;
8479
8480 if (ngtcp2_dcidtr_unused_empty(&conn->dcid.dtr)) {
8481 return 0;
8482 }
8483
8484 ngtcp2_path_storage_zero(&ps);
8485 ngtcp2_addr_copy(&ps.path.local, &conn->dcid.current.ps.path.local);
8486
8487 rv = conn_call_select_preferred_addr(conn, &ps.path);
8488 if (rv != 0) {
8489 return rv;
8490 }
8491
8492 if (ngtcp2_addr_empty(&ps.path.remote) ||
8493 ngtcp2_addr_eq(&conn->dcid.current.ps.path.remote, &ps.path.remote)) {
8494 return 0;
8495 }
8496
8497 assert(conn->pv == NULL);
8498
8499 ngtcp2_dcidtr_pop_unused(&conn->dcid.dtr, &dcid);
8500 ngtcp2_dcid_set_path(&dcid, &ps.path);
8501
8502 rv = ngtcp2_pv_new(&pv, &dcid, conn_compute_pv_timeout(conn),
8503 NGTCP2_PV_FLAG_PREFERRED_ADDR, &conn->log, conn->mem);
8504 if (rv != 0) {
8505 return rv;
8506 }
8507
8508 conn->pv = pv;
8509
8510 rv = conn_call_activate_dcid(conn, &pv->dcid);
8511 if (rv != 0) {
8512 return rv;
8513 }
8514
8515 return conn_call_begin_path_validation(conn, conn->pv);
8516 }
8517
8518 /*
8519 * conn_recv_handshake_done processes the incoming HANDSHAKE_DONE
8520 * frame |fr|.
8521 *
8522 * This function returns 0 if it succeeds, or one of the following
8523 * negative error codes:
8524 *
8525 * NGTCP2_ERR_PROTO
8526 * Server received HANDSHAKE_DONE frame.
8527 * NGTCP2_ERR_NOMEM
8528 * Out of memory.
8529 * NGTCP2_ERR_CALLBACK_FAILURE
8530 * User-defined callback function failed.
8531 */
8532 static int conn_recv_handshake_done(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
8533 int rv;
8534
8535 if (conn->server) {
8536 return NGTCP2_ERR_PROTO;
8537 }
8538
8539 if (conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED) {
8540 return 0;
8541 }
8542
8543 conn->flags |= NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED |
8544 NGTCP2_CONN_FLAG_SERVER_ADDR_VERIFIED;
8545
8546 conn->handshake_confirmed_ts = ts;
8547
8548 ngtcp2_conn_discard_handshake_state(conn, ts);
8549
8550 assert(conn->remote.transport_params);
8551
8552 if (conn->remote.transport_params->preferred_addr_present) {
8553 rv = conn_select_preferred_addr(conn);
8554 if (rv != 0) {
8555 return rv;
8556 }
8557 }
8558
8559 rv = conn_call_handshake_confirmed(conn);
8560 if (rv != 0) {
8561 return rv;
8562 }
8563
8564 /* Re-arm loss detection timer after handshake has been
8565 confirmed. */
8566 ngtcp2_conn_set_loss_detection_timer(conn, ts);
8567
8568 return 0;
8569 }
8570
8571 /*
8572 * conn_recv_datagram processes the incoming DATAGRAM frame |fr|.
8573 *
8574 * This function returns 0 if it succeeds, or one of the following
8575 * negative error codes:
8576 *
8577 * NGTCP2_ERR_CALLBACK_FAILURE
8578 * User-defined callback function failed.
8579 */
8580 static int conn_recv_datagram(ngtcp2_conn *conn, ngtcp2_datagram *fr) {
8581 assert(conn->local.transport_params.max_datagram_frame_size);
8582
8583 return conn_call_recv_datagram(conn, fr);
8584 }
8585
8586 /*
8587 * conn_key_phase_changed returns nonzero if |hd| indicates that the
8588 * key phase has unexpected value.
8589 */
8590 static int conn_key_phase_changed(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd) {
8591 ngtcp2_pktns *pktns = &conn->pktns;
8592
8593 return !(pktns->crypto.rx.ckm->flags & NGTCP2_CRYPTO_KM_FLAG_KEY_PHASE_ONE) ^
8594 !(hd->flags & NGTCP2_PKT_FLAG_KEY_PHASE);
8595 }
8596
8597 static int conn_initiate_key_update(ngtcp2_conn *conn, ngtcp2_tstamp ts);
8598
8599 /*
8600 * conn_prepare_key_update installs new updated keys.
8601 */
8602 static int conn_prepare_key_update(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
8603 int rv;
8604 ngtcp2_tstamp confirmed_ts = conn->crypto.key_update.confirmed_ts;
8605 ngtcp2_duration pto = conn_compute_pto(conn, &conn->pktns);
8606 ngtcp2_pktns *pktns = &conn->pktns;
8607 ngtcp2_crypto_km *rx_ckm = pktns->crypto.rx.ckm;
8608 ngtcp2_crypto_km *tx_ckm = pktns->crypto.tx.ckm;
8609 ngtcp2_crypto_km *new_rx_ckm, *new_tx_ckm;
8610 ngtcp2_crypto_aead_ctx rx_aead_ctx = {0}, tx_aead_ctx = {0};
8611 size_t secretlen, ivlen;
8612
8613 if ((conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED) &&
8614 tx_ckm->use_count >= pktns->crypto.ctx.max_encryption &&
8615 conn_initiate_key_update(conn, ts) != 0) {
8616 return NGTCP2_ERR_AEAD_LIMIT_REACHED;
8617 }
8618
8619 if ((conn->flags & NGTCP2_CONN_FLAG_KEY_UPDATE_NOT_CONFIRMED) ||
8620 ngtcp2_tstamp_not_elapsed(confirmed_ts, pto, ts)) {
8621 return 0;
8622 }
8623
8624 if (conn->crypto.key_update.new_rx_ckm ||
8625 conn->crypto.key_update.new_tx_ckm) {
8626 assert(conn->crypto.key_update.new_rx_ckm);
8627 assert(conn->crypto.key_update.new_tx_ckm);
8628 return 0;
8629 }
8630
8631 secretlen = rx_ckm->secret.len;
8632 ivlen = rx_ckm->iv.len;
8633
8634 rv = ngtcp2_crypto_km_nocopy_new(&conn->crypto.key_update.new_rx_ckm,
8635 secretlen, ivlen, conn->mem);
8636 if (rv != 0) {
8637 return rv;
8638 }
8639
8640 rv = ngtcp2_crypto_km_nocopy_new(&conn->crypto.key_update.new_tx_ckm,
8641 secretlen, ivlen, conn->mem);
8642 if (rv != 0) {
8643 return rv;
8644 }
8645
8646 new_rx_ckm = conn->crypto.key_update.new_rx_ckm;
8647 new_tx_ckm = conn->crypto.key_update.new_tx_ckm;
8648
8649 rv = conn_call_update_key(
8650 conn, new_rx_ckm->secret.base, new_tx_ckm->secret.base, &rx_aead_ctx,
8651 new_rx_ckm->iv.base, &tx_aead_ctx, new_tx_ckm->iv.base, rx_ckm->secret.base,
8652 tx_ckm->secret.base, secretlen);
8653 if (rv != 0) {
8654 return rv;
8655 }
8656
8657 new_rx_ckm->aead_ctx = rx_aead_ctx;
8658 new_tx_ckm->aead_ctx = tx_aead_ctx;
8659
8660 if (!(rx_ckm->flags & NGTCP2_CRYPTO_KM_FLAG_KEY_PHASE_ONE)) {
8661 new_rx_ckm->flags |= NGTCP2_CRYPTO_KM_FLAG_KEY_PHASE_ONE;
8662 new_tx_ckm->flags |= NGTCP2_CRYPTO_KM_FLAG_KEY_PHASE_ONE;
8663 }
8664
8665 if (conn->crypto.key_update.old_rx_ckm) {
8666 conn_call_delete_crypto_aead_ctx(
8667 conn, &conn->crypto.key_update.old_rx_ckm->aead_ctx);
8668 ngtcp2_crypto_km_del(conn->crypto.key_update.old_rx_ckm, conn->mem);
8669 conn->crypto.key_update.old_rx_ckm = NULL;
8670 }
8671
8672 return 0;
8673 }
8674
8675 /*
8676 * conn_rotate_keys rotates keys. The current key moves to old key,
8677 * and new key moves to the current key. If the local endpoint
8678 * initiated this key update, pass nonzero as |initiator|.
8679 */
8680 static void conn_rotate_keys(ngtcp2_conn *conn, int64_t pkt_num,
8681 int initiator) {
8682 ngtcp2_pktns *pktns = &conn->pktns;
8683
8684 assert(conn->crypto.key_update.new_rx_ckm);
8685 assert(conn->crypto.key_update.new_tx_ckm);
8686 assert(!conn->crypto.key_update.old_rx_ckm);
8687 assert(!(conn->flags & NGTCP2_CONN_FLAG_PPE_PENDING));
8688
8689 conn->crypto.key_update.old_rx_ckm = pktns->crypto.rx.ckm;
8690
8691 pktns->crypto.rx.ckm = conn->crypto.key_update.new_rx_ckm;
8692 conn->crypto.key_update.new_rx_ckm = NULL;
8693 pktns->crypto.rx.ckm->pkt_num = pkt_num;
8694
8695 assert(pktns->crypto.tx.ckm);
8696
8697 conn_call_delete_crypto_aead_ctx(conn, &pktns->crypto.tx.ckm->aead_ctx);
8698 ngtcp2_crypto_km_del(pktns->crypto.tx.ckm, conn->mem);
8699
8700 pktns->crypto.tx.ckm = conn->crypto.key_update.new_tx_ckm;
8701 conn->crypto.key_update.new_tx_ckm = NULL;
8702 pktns->crypto.tx.ckm->pkt_num = pktns->tx.last_pkt_num + 1;
8703
8704 conn->flags |= NGTCP2_CONN_FLAG_KEY_UPDATE_NOT_CONFIRMED;
8705 if (initiator) {
8706 conn->flags |= NGTCP2_CONN_FLAG_KEY_UPDATE_INITIATOR;
8707 }
8708 }
8709
8710 /*
8711 * conn_path_validation_in_progress returns nonzero if path validation
8712 * against |path| is underway.
8713 */
8714 static int conn_path_validation_in_progress(ngtcp2_conn *conn,
8715 const ngtcp2_path *path) {
8716 ngtcp2_pv *pv = conn->pv;
8717
8718 return pv && ngtcp2_path_eq(&pv->dcid.ps.path, path);
8719 }
8720
8721 /*
8722 * conn_recv_non_probing_pkt_on_new_path is called when non-probing
8723 * packet is received via new path. It starts path validation against
8724 * the new path.
8725 *
8726 * This function returns 0 if it succeeds, or one of the following
8727 * negative error codes:
8728 *
8729 * NGTCP2_ERR_CONN_ID_BLOCKED
8730 * No DCID is available
8731 * NGTCP2_ERR_NOMEM
8732 * Out of memory
8733 */
8734 static int conn_recv_non_probing_pkt_on_new_path(ngtcp2_conn *conn,
8735 const ngtcp2_path *path,
8736 size_t dgramlen,
8737 int new_cid_used,
8738 ngtcp2_tstamp ts) {
8739 ngtcp2_dcid dcid;
8740 ngtcp2_pv *pv = NULL;
8741 int rv;
8742 ngtcp2_duration pto;
8743 int local_addr_eq;
8744 int pref_addr_migration;
8745 uint32_t remote_addr_cmp;
8746 const ngtcp2_path_history_entry *validated_path;
8747
8748 assert(conn->server);
8749
8750 if (conn->pv && (conn->pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) &&
8751 ngtcp2_path_eq(&conn->pv->fallback_dcid.ps.path, path)) {
8752 /* If new path equals fallback path, that means connection
8753 migrated back to the original path. Fallback path is
8754 considered to be validated. */
8755 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PTV,
8756 "path is migrated back to the original path");
8757 ngtcp2_dcid_copy(&conn->dcid.current, &conn->pv->fallback_dcid);
8758 conn_reset_congestion_state(conn, ts);
8759 conn->dcid.current.bytes_recv += dgramlen;
8760 conn_reset_ecn_validation_state(conn);
8761
8762 rv = conn_abort_pv(conn, ts);
8763 if (rv != 0) {
8764 return rv;
8765 }
8766
8767 /* Run PMTUD just in case if it is prematurely aborted */
8768 assert(!conn->pmtud);
8769
8770 if (!conn->local.settings.no_pmtud) {
8771 return conn_start_pmtud(conn);
8772 }
8773
8774 return 0;
8775 }
8776
8777 remote_addr_cmp =
8778 ngtcp2_addr_cmp(&conn->dcid.current.ps.path.remote, &path->remote);
8779 local_addr_eq =
8780 ngtcp2_addr_eq(&conn->dcid.current.ps.path.local, &path->local);
8781 pref_addr_migration =
8782 !local_addr_eq && conn_server_preferred_addr_migration(conn, &path->local);
8783
8784 /*
8785 * When to change DCID? RFC 9002 section 9.5 says:
8786 *
8787 * An endpoint MUST NOT reuse a connection ID when sending from more
8788 * than one local address -- for example, when initiating connection
8789 * migration as described in Section 9.2 or when probing a new
8790 * network path as described in Section 9.1.
8791 *
8792 * Similarly, an endpoint MUST NOT reuse a connection ID when
8793 * sending to more than one destination address. Due to network
8794 * changes outside the control of its peer, an endpoint might
8795 * receive packets from a new source address with the same
8796 * Destination Connection ID field value, in which case it MAY
8797 * continue to use the current connection ID with the new remote
8798 * address while still sending from the same local address.
8799 */
8800 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CON,
8801 "non-probing packet was received from new remote address");
8802
8803 if (ngtcp2_dcidtr_pop_bound_dcid(&conn->dcid.dtr, &dcid, path) == 0) {
8804 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CON,
8805 "Found DCID which has already been bound to the new path");
8806
8807 if (dcid.cid.datalen) {
8808 rv = conn_call_activate_dcid(conn, &dcid);
8809 if (rv != 0) {
8810 return rv;
8811 }
8812 }
8813 } else {
8814 if (conn->dcid.current.cid.datalen &&
8815 ((new_cid_used && remote_addr_cmp) || !local_addr_eq)) {
8816 /* New DCID is required. */
8817 if (ngtcp2_dcidtr_unused_empty(&conn->dcid.dtr)) {
8818 return NGTCP2_ERR_CONN_ID_BLOCKED;
8819 }
8820
8821 ngtcp2_dcidtr_pop_unused(&conn->dcid.dtr, &dcid);
8822
8823 rv = conn_call_activate_dcid(conn, &dcid);
8824 if (rv != 0) {
8825 return rv;
8826 }
8827 } else {
8828 /* Use the current DCID if a remote endpoint does not change
8829 DCID. */
8830 ngtcp2_dcid_copy(&dcid, &conn->dcid.current);
8831 dcid.bytes_sent = 0;
8832 dcid.bytes_recv = 0;
8833 dcid.flags &= (uint8_t)~NGTCP2_DCID_FLAG_PATH_VALIDATED;
8834 }
8835
8836 ngtcp2_dcid_set_path(&dcid, path);
8837 }
8838
8839 dcid.bytes_recv += dgramlen;
8840
8841 validated_path = ngtcp2_conn_find_path_history(conn, path, ts);
8842 if (!validated_path) {
8843 pto = conn_compute_pto(conn, &conn->pktns);
8844
8845 rv = ngtcp2_pv_new(&pv, &dcid, conn_compute_pv_timeout_pto(conn, pto),
8846 NGTCP2_PV_FLAG_NONE, &conn->log, conn->mem);
8847 if (rv != 0) {
8848 return rv;
8849 }
8850
8851 if (conn->pv && (conn->pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT)) {
8852 ngtcp2_pv_set_fallback(pv, &conn->pv->fallback_dcid,
8853 conn->pv->fallback_pto);
8854 /* Unset the flag bit so that conn_stop_pv does not retire
8855 DCID. */
8856 conn->pv->flags &= (uint8_t)~NGTCP2_PV_FLAG_FALLBACK_PRESENT;
8857 } else if (!pref_addr_migration) {
8858 ngtcp2_pv_set_fallback(pv, &conn->dcid.current, pto);
8859 }
8860 }
8861
8862 if (!pref_addr_migration || validated_path) {
8863 if (conn->dcid.current.flags & NGTCP2_DCID_FLAG_PATH_VALIDATED) {
8864 ngtcp2_conn_add_path_history(conn, &conn->dcid.current, ts);
8865 }
8866
8867 ngtcp2_dcid_copy(&conn->dcid.current, &dcid);
8868
8869 if (!local_addr_eq || (remote_addr_cmp & (NGTCP2_ADDR_CMP_FLAG_ADDR |
8870 NGTCP2_ADDR_CMP_FLAG_FAMILY))) {
8871 conn_reset_congestion_state(conn, ts);
8872 }
8873
8874 conn_reset_ecn_validation_state(conn);
8875
8876 ngtcp2_conn_stop_pmtud(conn);
8877
8878 if (validated_path) {
8879 ngtcp2_dcid_apply_validated_path(&conn->dcid.current, validated_path);
8880
8881 if (!conn->local.settings.no_pmtud) {
8882 rv = conn_start_pmtud(conn);
8883 if (rv != 0) {
8884 return rv;
8885 }
8886 }
8887 }
8888 }
8889
8890 if (conn->pv) {
8891 ngtcp2_log_info(
8892 &conn->log, NGTCP2_LOG_EVENT_PTV,
8893 "path migration is aborted because new migration has started");
8894 rv = conn_abort_pv(conn, ts);
8895 if (rv != 0) {
8896 return rv;
8897 }
8898 }
8899
8900 conn->pv = pv;
8901
8902 return conn_call_begin_path_validation(conn, conn->pv);
8903 }
8904
8905 /*
8906 * conn_recv_pkt_from_new_path is called when a 1RTT packet is
8907 * received from new path (not current path). This packet would be a
8908 * packet which only contains probing frame, or reordered packet, or a
8909 * path is being validated.
8910 *
8911 * This function returns 0 if it succeeds, or one of the following
8912 * negative error codes:
8913 *
8914 * NGTCP2_ERR_CONN_ID_BLOCKED
8915 * No unused DCID is available
8916 * NGTCP2_ERR_NOMEM
8917 * Out of memory
8918 */
8919 static int conn_recv_pkt_from_new_path(ngtcp2_conn *conn,
8920 const ngtcp2_path *path, size_t dgramlen,
8921 int path_challenge_recved,
8922 ngtcp2_tstamp ts) {
8923 ngtcp2_pv *pv = conn->pv;
8924 ngtcp2_dcid *bound_dcid;
8925 int rv;
8926
8927 if (pv) {
8928 if (ngtcp2_path_eq(&pv->dcid.ps.path, path)) {
8929 pv->dcid.bytes_recv += dgramlen;
8930 return 0;
8931 }
8932
8933 if ((pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) &&
8934 ngtcp2_path_eq(&pv->fallback_dcid.ps.path, path)) {
8935 pv->fallback_dcid.bytes_recv += dgramlen;
8936 return 0;
8937 }
8938 }
8939
8940 if (!path_challenge_recved) {
8941 return 0;
8942 }
8943
8944 rv = conn_bind_dcid(conn, &bound_dcid, path, ts);
8945 if (rv != 0) {
8946 return rv;
8947 }
8948
8949 bound_dcid->bytes_recv += dgramlen;
8950
8951 return 0;
8952 }
8953
8954 /*
8955 * conn_recv_delayed_handshake_pkt processes the received Handshake
8956 * packet which is received after handshake completed. This function
8957 * does the minimal job, and its purpose is send acknowledgement of
8958 * this packet to the peer. We assume that hd->type ==
8959 * NGTCP2_PKT_HANDSHAKE.
8960 *
8961 * This function returns 0 if it succeeds, or one of the following
8962 * negative error codes:
8963 *
8964 * NGTCP2_ERR_FRAME_ENCODING
8965 * Frame is badly formatted; or frame type is unknown.
8966 * NGTCP2_ERR_NOMEM
8967 * Out of memory
8968 * NGTCP2_ERR_DISCARD_PKT
8969 * Packet was discarded.
8970 * NGTCP2_ERR_ACK_FRAME
8971 * ACK frame is malformed.
8972 * NGTCP2_ERR_PROTO
8973 * Frame that is not allowed in Handshake packet is received.
8974 */
8975 static int
8976 conn_recv_delayed_handshake_pkt(ngtcp2_conn *conn, const ngtcp2_pkt_info *pi,
8977 const ngtcp2_pkt_hd *hd, size_t pktlen,
8978 const uint8_t *payload, size_t payloadlen,
8979 ngtcp2_tstamp pkt_ts, ngtcp2_tstamp ts) {
8980 ngtcp2_ssize nread;
8981 ngtcp2_frame_decoder frd;
8982 ngtcp2_frame fr;
8983 int rv;
8984 int require_ack = 0;
8985 ngtcp2_pktns *pktns;
8986 size_t num_ack_processed = 0;
8987
8988 assert(hd->type == NGTCP2_PKT_HANDSHAKE);
8989
8990 pktns = conn->hs_pktns;
8991
8992 if (payloadlen == 0) {
8993 /* QUIC packet must contain at least one frame */
8994 return NGTCP2_ERR_PROTO;
8995 }
8996
8997 ngtcp2_qlog_pkt_received_start(&conn->qlog);
8998
8999 for (; payloadlen;) {
9000 nread = ngtcp2_frame_decoder_decode(&frd, &fr, payload, payloadlen);
9001 if (nread < 0) {
9002 return (int)nread;
9003 }
9004
9005 payload += nread;
9006 payloadlen -= (size_t)nread;
9007
9008 switch (fr.hd.type) {
9009 case NGTCP2_FRAME_ACK:
9010 case NGTCP2_FRAME_ACK_ECN:
9011 fr.ack.ack_delay = 0;
9012 fr.ack.ack_delay_unscaled = 0;
9013
9014 rv =
9015 ngtcp2_pkt_validate_ack(&fr.ack, conn->local.settings.initial_pkt_num);
9016 if (rv != 0) {
9017 return rv;
9018 }
9019
9020 break;
9021 }
9022
9023 ngtcp2_log_rx_fr(&conn->log, hd, &fr);
9024
9025 switch (fr.hd.type) {
9026 case NGTCP2_FRAME_ACK:
9027 case NGTCP2_FRAME_ACK_ECN:
9028 if (num_ack_processed >= NGTCP2_MAX_ACK_PER_PKT) {
9029 break;
9030 }
9031 if (!conn->server) {
9032 conn->flags |= NGTCP2_CONN_FLAG_SERVER_ADDR_VERIFIED;
9033 }
9034 rv = conn_recv_ack(conn, pktns, &fr.ack, pkt_ts, ts);
9035 if (rv != 0) {
9036 return rv;
9037 }
9038 ++num_ack_processed;
9039 break;
9040 case NGTCP2_FRAME_PADDING:
9041 break;
9042 case NGTCP2_FRAME_CONNECTION_CLOSE:
9043 rv = conn_recv_connection_close(conn, &fr.connection_close);
9044 if (rv != 0) {
9045 return rv;
9046 }
9047 break;
9048 case NGTCP2_FRAME_PING:
9049 ++conn->cstat.ping_recv;
9050 /* fall through */
9051 case NGTCP2_FRAME_CRYPTO:
9052 require_ack = 1;
9053 break;
9054 default:
9055 return NGTCP2_ERR_PROTO;
9056 }
9057
9058 ngtcp2_qlog_write_frame(&conn->qlog, &fr);
9059 }
9060
9061 ngtcp2_qlog_pkt_received_end(&conn->qlog, hd, pktlen);
9062
9063 rv = pktns_commit_recv_pkt_num(pktns, hd->pkt_num, pi, require_ack, pkt_ts);
9064 if (rv != 0) {
9065 return rv;
9066 }
9067
9068 /* Initial and Handshake are always acknowledged without delay. No
9069 need to call ngtcp2_acktr_immediate_ack(). */
9070
9071 conn_restart_timer_on_read(conn, ts);
9072
9073 ngtcp2_qlog_metrics_updated(&conn->qlog, &conn->cstat);
9074
9075 return 0;
9076 }
9077
9078 /*
9079 * conn_recv_pkt processes a packet contained in the buffer pointed by
9080 * |pkt| of length |pktlen|. |pkt| may contain multiple QUIC packets.
9081 * This function only processes the first packet. |pkt_ts| is the
9082 * timestamp when packet is received. |ts| should be the current
9083 * time. Usually they are the same, but for buffered packets,
9084 * |pkt_ts| would be earlier than |ts|.
9085 *
9086 * This function returns the number of bytes processed if it succeeds,
9087 * or one of the following negative error codes:
9088 *
9089 * NGTCP2_ERR_DISCARD_PKT
9090 * Packet was discarded because plain text header was malformed;
9091 * or its payload could not be decrypted.
9092 * NGTCP2_ERR_PROTO
9093 * Packet is badly formatted; or 0RTT packet contains other than
9094 * PADDING or STREAM frames; or other QUIC protocol violation is
9095 * found.
9096 * NGTCP2_ERR_CALLBACK_FAILURE
9097 * User-defined callback function failed.
9098 * NGTCP2_ERR_NOMEM
9099 * Out of memory.
9100 * NGTCP2_ERR_FRAME_ENCODING
9101 * Frame is badly formatted; or frame type is unknown.
9102 * NGTCP2_ERR_ACK_FRAME
9103 * ACK frame is malformed.
9104 * NGTCP2_ERR_STREAM_STATE
9105 * Frame is received to the local stream which is not initiated.
9106 * NGTCP2_ERR_STREAM_LIMIT
9107 * Frame has remote stream ID which is strictly greater than the
9108 * allowed limit.
9109 * NGTCP2_ERR_FLOW_CONTROL
9110 * Flow control limit is violated.
9111 * NGTCP2_ERR_FINAL_SIZE
9112 * Frame has strictly larger end offset than it is permitted.
9113 * NGTCP2_ERR_INTERNAL
9114 * Suspicious remote endpoint activity exceeded threshold.
9115 */
9116 static ngtcp2_ssize conn_recv_pkt(ngtcp2_conn *conn, const ngtcp2_path *path,
9117 const ngtcp2_pkt_info *pi, const uint8_t *pkt,
9118 size_t pktlen, size_t dgramlen,
9119 ngtcp2_tstamp pkt_ts, ngtcp2_tstamp ts) {
9120 ngtcp2_pkt_hd hd;
9121 int rv = 0;
9122 size_t hdpktlen;
9123 const uint8_t *payload;
9124 size_t payloadlen;
9125 ngtcp2_ssize nread, nwrite;
9126 ngtcp2_frame_decoder frd;
9127 ngtcp2_frame fr;
9128 int require_ack = 0;
9129 ngtcp2_crypto_aead *aead;
9130 ngtcp2_crypto_cipher *hp;
9131 ngtcp2_crypto_km *ckm;
9132 ngtcp2_crypto_cipher_ctx *hp_ctx;
9133 ngtcp2_hp_mask hp_mask;
9134 ngtcp2_decrypt decrypt;
9135 ngtcp2_pktns *pktns;
9136 int non_probing_pkt = 0;
9137 int key_phase_bit_changed = 0;
9138 int force_decrypt_failure = 0;
9139 int recv_ncid = 0;
9140 int new_cid_used = 0;
9141 int path_challenge_recved = 0;
9142 size_t num_ack_processed = 0;
9143
9144 if (pkt[0] & NGTCP2_HEADER_FORM_BIT) {
9145 nread = ngtcp2_pkt_decode_hd_long(&hd, pkt, pktlen);
9146 if (nread < 0) {
9147 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9148 "could not decode long header");
9149 return NGTCP2_ERR_DISCARD_PKT;
9150 }
9151
9152 if (pktlen < (size_t)nread + hd.len) {
9153 return NGTCP2_ERR_DISCARD_PKT;
9154 }
9155
9156 assert(conn->negotiated_version);
9157
9158 if (hd.version != conn->client_chosen_version &&
9159 hd.version != conn->negotiated_version) {
9160 return NGTCP2_ERR_DISCARD_PKT;
9161 }
9162
9163 if (conn_verify_fixed_bit(conn, &hd) != 0) {
9164 return NGTCP2_ERR_DISCARD_PKT;
9165 }
9166
9167 pktlen = (size_t)nread + hd.len;
9168
9169 /* Quoted from spec: if subsequent packets of those types include
9170 a different Source Connection ID, they MUST be discarded. */
9171 if (!ngtcp2_cid_eq(&conn->dcid.current.cid, &hd.scid)) {
9172 ngtcp2_log_rx_pkt_hd(&conn->log, &hd);
9173 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9174 "packet was ignored because of mismatched SCID");
9175 return NGTCP2_ERR_DISCARD_PKT;
9176 }
9177
9178 switch (hd.type) {
9179 case NGTCP2_PKT_INITIAL:
9180 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9181 "delayed Initial packet was discarded");
9182 return (ngtcp2_ssize)pktlen;
9183 case NGTCP2_PKT_HANDSHAKE:
9184 if (hd.version != conn->negotiated_version) {
9185 return NGTCP2_ERR_DISCARD_PKT;
9186 }
9187
9188 if (!conn->hs_pktns) {
9189 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9190 "delayed Handshake packet was discarded");
9191 return (ngtcp2_ssize)pktlen;
9192 }
9193
9194 pktns = conn->hs_pktns;
9195 aead = &pktns->crypto.ctx.aead;
9196 hp = &pktns->crypto.ctx.hp;
9197 ckm = pktns->crypto.rx.ckm;
9198 hp_ctx = &pktns->crypto.rx.hp_ctx;
9199 hp_mask = conn->callbacks.hp_mask;
9200 decrypt = conn->callbacks.decrypt;
9201 break;
9202 case NGTCP2_PKT_0RTT:
9203 if (!conn->server || hd.version != conn->client_chosen_version) {
9204 return NGTCP2_ERR_DISCARD_PKT;
9205 }
9206
9207 if (!conn->early.ckm) {
9208 return (ngtcp2_ssize)pktlen;
9209 }
9210
9211 pktns = &conn->pktns;
9212 aead = &conn->early.ctx.aead;
9213 hp = &conn->early.ctx.hp;
9214 ckm = conn->early.ckm;
9215 hp_ctx = &conn->early.hp_ctx;
9216 hp_mask = conn->callbacks.hp_mask;
9217 decrypt = conn->callbacks.decrypt;
9218 break;
9219 default:
9220 ngtcp2_log_rx_pkt_hd(&conn->log, &hd);
9221 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_PKT,
9222 "packet type 0x%02x was ignored", hd.type);
9223 return (ngtcp2_ssize)pktlen;
9224 }
9225 } else {
9226 nread = ngtcp2_pkt_decode_hd_short(&hd, pkt, pktlen, conn->oscid.datalen);
9227 if (nread < 0) {
9228 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9229 "could not decode short header");
9230 return NGTCP2_ERR_DISCARD_PKT;
9231 }
9232
9233 if (conn_verify_fixed_bit(conn, &hd) != 0) {
9234 return NGTCP2_ERR_DISCARD_PKT;
9235 }
9236
9237 pktns = &conn->pktns;
9238 aead = &pktns->crypto.ctx.aead;
9239 hp = &pktns->crypto.ctx.hp;
9240 ckm = pktns->crypto.rx.ckm;
9241 hp_ctx = &pktns->crypto.rx.hp_ctx;
9242 hp_mask = conn->callbacks.hp_mask;
9243 decrypt = conn->callbacks.decrypt;
9244 }
9245
9246 rv = conn_ensure_decrypt_hp_buffer(conn, (size_t)nread + 4);
9247 if (rv != 0) {
9248 return rv;
9249 }
9250
9251 nwrite = decrypt_hp(&hd, conn->crypto.decrypt_hp_buf.base, hp, pkt, pktlen,
9252 (size_t)nread, hp_ctx, hp_mask);
9253 if (nwrite < 0) {
9254 if (ngtcp2_err_is_fatal((int)nwrite)) {
9255 return nwrite;
9256 }
9257 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9258 "could not decrypt packet number");
9259 return NGTCP2_ERR_DISCARD_PKT;
9260 }
9261
9262 hdpktlen = (size_t)nwrite;
9263 payload = pkt + hdpktlen;
9264 payloadlen = pktlen - hdpktlen;
9265
9266 hd.pkt_num = ngtcp2_pkt_adjust_pkt_num(pktns->acktr.max_pkt_num, hd.pkt_num,
9267 hd.pkt_numlen);
9268 if (hd.pkt_num > NGTCP2_MAX_PKT_NUM) {
9269 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_PKT,
9270 "pkn=%" PRId64 " is greater than maximum pkn", hd.pkt_num);
9271 return NGTCP2_ERR_DISCARD_PKT;
9272 }
9273
9274 ngtcp2_log_rx_pkt_hd(&conn->log, &hd);
9275
9276 if (hd.type == NGTCP2_PKT_1RTT) {
9277 if (conn->server && conn->rx.preferred_addr.pkt_num != -1 &&
9278 conn->rx.preferred_addr.pkt_num < hd.pkt_num &&
9279 ngtcp2_sockaddr_eq((const ngtcp2_sockaddr *)&conn->hs_local_addr,
9280 path->local.addr)) {
9281 ngtcp2_log_infof(
9282 &conn->log, NGTCP2_LOG_EVENT_PKT,
9283 "pkt=%" PRId64
9284 " is discarded because it was received on handshake local "
9285 "address after preferred address migration",
9286 hd.pkt_num);
9287 return NGTCP2_ERR_DISCARD_PKT;
9288 }
9289
9290 key_phase_bit_changed = conn_key_phase_changed(conn, &hd);
9291 }
9292
9293 rv = conn_ensure_decrypt_buffer(conn, payloadlen);
9294 if (rv != 0) {
9295 return rv;
9296 }
9297
9298 if (key_phase_bit_changed) {
9299 assert(hd.type == NGTCP2_PKT_1RTT);
9300
9301 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT, "unexpected KEY_PHASE");
9302
9303 if (ckm->pkt_num > hd.pkt_num) {
9304 if (conn->crypto.key_update.old_rx_ckm) {
9305 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9306 "decrypting with old key");
9307 ckm = conn->crypto.key_update.old_rx_ckm;
9308 } else {
9309 force_decrypt_failure = 1;
9310 }
9311 } else if (pktns->acktr.max_pkt_num < hd.pkt_num) {
9312 assert(ckm->pkt_num < hd.pkt_num);
9313 if (!conn->crypto.key_update.new_rx_ckm) {
9314 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9315 "new key is not available");
9316 force_decrypt_failure = 1;
9317 } else {
9318 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9319 "decrypting with new key");
9320 ckm = conn->crypto.key_update.new_rx_ckm;
9321 }
9322 } else {
9323 force_decrypt_failure = 1;
9324 }
9325 }
9326
9327 nwrite = decrypt_pkt(conn->crypto.decrypt_buf.base, aead, payload, payloadlen,
9328 conn->crypto.decrypt_hp_buf.base, hdpktlen, hd.pkt_num,
9329 ckm, decrypt);
9330
9331 if (force_decrypt_failure) {
9332 nwrite = NGTCP2_ERR_DECRYPT;
9333 }
9334
9335 if (nwrite < 0) {
9336 if (ngtcp2_err_is_fatal((int)nwrite)) {
9337 return nwrite;
9338 }
9339
9340 assert(NGTCP2_ERR_DECRYPT == nwrite);
9341
9342 if (hd.type == NGTCP2_PKT_1RTT &&
9343 ++conn->crypto.decryption_failure_count >=
9344 pktns->crypto.ctx.max_decryption_failure) {
9345 return NGTCP2_ERR_AEAD_LIMIT_REACHED;
9346 }
9347
9348 if (hd.flags & NGTCP2_PKT_FLAG_LONG_FORM) {
9349 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9350 "could not decrypt packet payload");
9351 return NGTCP2_ERR_DISCARD_PKT;
9352 }
9353
9354 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9355 "could not decrypt packet payload");
9356 return NGTCP2_ERR_DISCARD_PKT;
9357 }
9358
9359 rv = ngtcp2_pkt_verify_reserved_bits(conn->crypto.decrypt_hp_buf.base[0]);
9360 if (rv != 0) {
9361 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9362 "packet has incorrect reserved bits");
9363
9364 return NGTCP2_ERR_PROTO;
9365 }
9366
9367 if (pktns_pkt_num_is_duplicate(pktns, hd.pkt_num)) {
9368 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9369 "packet was discarded because of duplicated packet number");
9370 return NGTCP2_ERR_DISCARD_PKT;
9371 }
9372
9373 payload = conn->crypto.decrypt_buf.base;
9374 payloadlen = (size_t)nwrite;
9375
9376 if (payloadlen == 0) {
9377 /* QUIC packet must contain at least one frame */
9378 return NGTCP2_ERR_PROTO;
9379 }
9380
9381 if (hd.flags & NGTCP2_PKT_FLAG_LONG_FORM) {
9382 switch (hd.type) {
9383 case NGTCP2_PKT_HANDSHAKE:
9384 rv = conn_verify_dcid(conn, NULL, &hd);
9385 if (rv != 0) {
9386 if (ngtcp2_err_is_fatal(rv)) {
9387 return rv;
9388 }
9389 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9390 "packet was ignored because of mismatched DCID");
9391 return NGTCP2_ERR_DISCARD_PKT;
9392 }
9393
9394 rv = conn_recv_delayed_handshake_pkt(conn, pi, &hd, pktlen, payload,
9395 payloadlen, pkt_ts, ts);
9396 if (rv < 0) {
9397 return (ngtcp2_ssize)rv;
9398 }
9399
9400 return (ngtcp2_ssize)pktlen;
9401 case NGTCP2_PKT_0RTT:
9402 if (!ngtcp2_cid_eq(&conn->rcid, &hd.dcid)) {
9403 rv = conn_verify_dcid(conn, NULL, &hd);
9404 if (rv != 0) {
9405 if (ngtcp2_err_is_fatal(rv)) {
9406 return rv;
9407 }
9408 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9409 "packet was ignored because of mismatched DCID");
9410 return NGTCP2_ERR_DISCARD_PKT;
9411 }
9412 }
9413 break;
9414 default:
9415 /* Unreachable */
9416 ngtcp2_unreachable();
9417 }
9418 } else {
9419 rv = conn_verify_dcid(conn, &new_cid_used, &hd);
9420 if (rv != 0) {
9421 if (ngtcp2_err_is_fatal(rv)) {
9422 return rv;
9423 }
9424 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9425 "packet was ignored because of mismatched DCID");
9426 return NGTCP2_ERR_DISCARD_PKT;
9427 }
9428 }
9429
9430 ngtcp2_qlog_pkt_received_start(&conn->qlog);
9431
9432 for (; payloadlen;) {
9433 nread = ngtcp2_frame_decoder_decode(&frd, &fr, payload, payloadlen);
9434 if (nread < 0) {
9435 return nread;
9436 }
9437
9438 payload += nread;
9439 payloadlen -= (size_t)nread;
9440
9441 switch (fr.hd.type) {
9442 case NGTCP2_FRAME_ACK:
9443 case NGTCP2_FRAME_ACK_ECN:
9444 if ((hd.flags & NGTCP2_PKT_FLAG_LONG_FORM) &&
9445 hd.type == NGTCP2_PKT_0RTT) {
9446 return NGTCP2_ERR_PROTO;
9447 }
9448 assert(conn->remote.transport_params);
9449 assign_recved_ack_delay_unscaled(
9450 &fr.ack, conn->remote.transport_params->ack_delay_exponent);
9451
9452 rv =
9453 ngtcp2_pkt_validate_ack(&fr.ack, conn->local.settings.initial_pkt_num);
9454 if (rv != 0) {
9455 return rv;
9456 }
9457
9458 break;
9459 }
9460
9461 ngtcp2_log_rx_fr(&conn->log, &hd, &fr);
9462
9463 if (hd.type == NGTCP2_PKT_0RTT) {
9464 switch (fr.hd.type) {
9465 case NGTCP2_FRAME_PADDING:
9466 case NGTCP2_FRAME_PING:
9467 case NGTCP2_FRAME_RESET_STREAM:
9468 case NGTCP2_FRAME_STOP_SENDING:
9469 case NGTCP2_FRAME_STREAM:
9470 case NGTCP2_FRAME_MAX_DATA:
9471 case NGTCP2_FRAME_MAX_STREAM_DATA:
9472 case NGTCP2_FRAME_MAX_STREAMS_BIDI:
9473 case NGTCP2_FRAME_MAX_STREAMS_UNI:
9474 case NGTCP2_FRAME_DATA_BLOCKED:
9475 case NGTCP2_FRAME_STREAM_DATA_BLOCKED:
9476 case NGTCP2_FRAME_STREAMS_BLOCKED_BIDI:
9477 case NGTCP2_FRAME_STREAMS_BLOCKED_UNI:
9478 case NGTCP2_FRAME_NEW_CONNECTION_ID:
9479 case NGTCP2_FRAME_PATH_CHALLENGE:
9480 case NGTCP2_FRAME_CONNECTION_CLOSE:
9481 case NGTCP2_FRAME_CONNECTION_CLOSE_APP:
9482 case NGTCP2_FRAME_DATAGRAM:
9483 case NGTCP2_FRAME_DATAGRAM_LEN:
9484 break;
9485 default:
9486 return NGTCP2_ERR_PROTO;
9487 }
9488 }
9489
9490 switch (fr.hd.type) {
9491 case NGTCP2_FRAME_ACK:
9492 case NGTCP2_FRAME_ACK_ECN:
9493 case NGTCP2_FRAME_PADDING:
9494 case NGTCP2_FRAME_CONNECTION_CLOSE:
9495 case NGTCP2_FRAME_CONNECTION_CLOSE_APP:
9496 break;
9497 default:
9498 require_ack = 1;
9499 }
9500
9501 switch (fr.hd.type) {
9502 case NGTCP2_FRAME_ACK:
9503 case NGTCP2_FRAME_ACK_ECN:
9504 if (num_ack_processed >= NGTCP2_MAX_ACK_PER_PKT) {
9505 break;
9506 }
9507 if (!conn->server) {
9508 conn->flags |= NGTCP2_CONN_FLAG_SERVER_ADDR_VERIFIED;
9509 }
9510 rv = conn_recv_ack(conn, pktns, &fr.ack, pkt_ts, ts);
9511 if (rv != 0) {
9512 return rv;
9513 }
9514 non_probing_pkt = 1;
9515 ++num_ack_processed;
9516 break;
9517 case NGTCP2_FRAME_STREAM:
9518 rv = conn_recv_stream(conn, &fr.stream, ts);
9519 if (rv != 0) {
9520 return rv;
9521 }
9522 non_probing_pkt = 1;
9523 break;
9524 case NGTCP2_FRAME_CRYPTO:
9525 rv = conn_recv_crypto(conn, NGTCP2_ENCRYPTION_LEVEL_1RTT,
9526 &pktns->crypto.strm, &fr.stream, ts);
9527 if (rv != 0) {
9528 return rv;
9529 }
9530 non_probing_pkt = 1;
9531 break;
9532 case NGTCP2_FRAME_RESET_STREAM:
9533 rv = conn_recv_reset_stream(conn, &fr.reset_stream, ts);
9534 if (rv != 0) {
9535 return rv;
9536 }
9537 non_probing_pkt = 1;
9538 break;
9539 case NGTCP2_FRAME_STOP_SENDING:
9540 rv = conn_recv_stop_sending(conn, &fr.stop_sending, ts);
9541 if (rv != 0) {
9542 return rv;
9543 }
9544 non_probing_pkt = 1;
9545 break;
9546 case NGTCP2_FRAME_MAX_STREAM_DATA:
9547 rv = conn_recv_max_stream_data(conn, &fr.max_stream_data, ts);
9548 if (rv != 0) {
9549 return rv;
9550 }
9551 non_probing_pkt = 1;
9552 break;
9553 case NGTCP2_FRAME_MAX_DATA:
9554 conn_recv_max_data(conn, &fr.max_data);
9555 non_probing_pkt = 1;
9556 break;
9557 case NGTCP2_FRAME_MAX_STREAMS_BIDI:
9558 case NGTCP2_FRAME_MAX_STREAMS_UNI:
9559 rv = conn_recv_max_streams(conn, &fr.max_streams);
9560 if (rv != 0) {
9561 return rv;
9562 }
9563 non_probing_pkt = 1;
9564 break;
9565 case NGTCP2_FRAME_CONNECTION_CLOSE:
9566 case NGTCP2_FRAME_CONNECTION_CLOSE_APP:
9567 rv = conn_recv_connection_close(conn, &fr.connection_close);
9568 if (rv != 0) {
9569 return rv;
9570 }
9571 break;
9572 case NGTCP2_FRAME_PING:
9573 ++conn->cstat.ping_recv;
9574 non_probing_pkt = 1;
9575 break;
9576 case NGTCP2_FRAME_PATH_CHALLENGE:
9577 conn_recv_path_challenge(conn, path, &fr.path_challenge);
9578 path_challenge_recved = 1;
9579 break;
9580 case NGTCP2_FRAME_PATH_RESPONSE:
9581 rv = conn_recv_path_response(conn, &hd, &fr.path_response, ts);
9582 if (rv != 0) {
9583 return rv;
9584 }
9585 break;
9586 case NGTCP2_FRAME_NEW_CONNECTION_ID:
9587 rv = conn_recv_new_connection_id(conn, &fr.new_connection_id);
9588 if (rv != 0) {
9589 return rv;
9590 }
9591 recv_ncid = 1;
9592 break;
9593 case NGTCP2_FRAME_RETIRE_CONNECTION_ID:
9594 rv =
9595 conn_recv_retire_connection_id(conn, &hd, &fr.retire_connection_id, ts);
9596 if (rv != 0) {
9597 return rv;
9598 }
9599 non_probing_pkt = 1;
9600 break;
9601 case NGTCP2_FRAME_NEW_TOKEN:
9602 rv = conn_recv_new_token(conn, &fr.new_token);
9603 if (rv != 0) {
9604 return rv;
9605 }
9606 non_probing_pkt = 1;
9607 break;
9608 case NGTCP2_FRAME_HANDSHAKE_DONE:
9609 rv = conn_recv_handshake_done(conn, ts);
9610 if (rv != 0) {
9611 return rv;
9612 }
9613 non_probing_pkt = 1;
9614 break;
9615 case NGTCP2_FRAME_STREAMS_BLOCKED_BIDI:
9616 rv = conn_recv_streams_blocked_bidi(conn, &fr.streams_blocked);
9617 if (rv != 0) {
9618 return rv;
9619 }
9620 non_probing_pkt = 1;
9621 break;
9622 case NGTCP2_FRAME_STREAMS_BLOCKED_UNI:
9623 rv = conn_recv_streams_blocked_uni(conn, &fr.streams_blocked);
9624 if (rv != 0) {
9625 return rv;
9626 }
9627 non_probing_pkt = 1;
9628 break;
9629 case NGTCP2_FRAME_STREAM_DATA_BLOCKED:
9630 rv = conn_recv_stream_data_blocked(conn, &fr.stream_data_blocked);
9631 if (rv != 0) {
9632 return rv;
9633 }
9634 non_probing_pkt = 1;
9635 break;
9636 case NGTCP2_FRAME_DATA_BLOCKED:
9637 rv = conn_recv_data_blocked(conn, &fr.data_blocked);
9638 if (rv != 0) {
9639 return rv;
9640 }
9641 non_probing_pkt = 1;
9642 break;
9643 case NGTCP2_FRAME_DATAGRAM:
9644 case NGTCP2_FRAME_DATAGRAM_LEN:
9645 if ((uint64_t)nread >
9646 conn->local.transport_params.max_datagram_frame_size) {
9647 return NGTCP2_ERR_PROTO;
9648 }
9649 rv = conn_recv_datagram(conn, &fr.datagram);
9650 if (rv != 0) {
9651 return rv;
9652 }
9653 non_probing_pkt = 1;
9654 break;
9655 }
9656
9657 ngtcp2_qlog_write_frame(&conn->qlog, &fr);
9658 }
9659
9660 ngtcp2_qlog_pkt_received_end(&conn->qlog, &hd, pktlen);
9661
9662 if (recv_ncid) {
9663 rv = conn_post_process_recv_new_connection_id(conn, ts);
9664 if (rv != 0) {
9665 return rv;
9666 }
9667 }
9668
9669 if (conn->server && hd.type == NGTCP2_PKT_1RTT &&
9670 !ngtcp2_path_eq(&conn->dcid.current.ps.path, path)) {
9671 if (non_probing_pkt && pktns->acktr.max_pkt_num < hd.pkt_num &&
9672 !conn_path_validation_in_progress(conn, path)) {
9673 rv = conn_recv_non_probing_pkt_on_new_path(conn, path, dgramlen,
9674 new_cid_used, ts);
9675 if (rv != 0) {
9676 if (ngtcp2_err_is_fatal(rv)) {
9677 return rv;
9678 }
9679
9680 /* DCID is not available. Just continue. */
9681 assert(NGTCP2_ERR_CONN_ID_BLOCKED == rv);
9682 }
9683 } else {
9684 rv = conn_recv_pkt_from_new_path(conn, path, dgramlen,
9685 path_challenge_recved, ts);
9686 if (rv != 0) {
9687 if (ngtcp2_err_is_fatal(rv)) {
9688 return rv;
9689 }
9690
9691 /* DCID is not available. Just continue. */
9692 assert(NGTCP2_ERR_CONN_ID_BLOCKED == rv);
9693 }
9694 }
9695 }
9696
9697 if (hd.type == NGTCP2_PKT_1RTT) {
9698 if (ckm == conn->crypto.key_update.new_rx_ckm) {
9699 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CON, "rotate keys");
9700 conn_rotate_keys(conn, hd.pkt_num, /* initiator = */ 0);
9701 } else if (ckm->pkt_num > hd.pkt_num) {
9702 ckm->pkt_num = hd.pkt_num;
9703 }
9704
9705 if (conn->server && conn->early.ckm &&
9706 conn->early.discard_started_ts == UINT64_MAX) {
9707 conn->early.discard_started_ts = ts;
9708 }
9709
9710 if (ngtcp2_path_eq(&conn->dcid.current.ps.path, path)) {
9711 conn_update_keep_alive_last_ts(conn, ts);
9712 }
9713 }
9714
9715 rv = pktns_commit_recv_pkt_num(pktns, hd.pkt_num, pi, require_ack, pkt_ts);
9716 if (rv != 0) {
9717 return rv;
9718 }
9719
9720 if (require_ack &&
9721 (++pktns->acktr.rx_npkt >= conn->local.settings.ack_thresh ||
9722 (pi->ecn & NGTCP2_ECN_MASK) == NGTCP2_ECN_CE)) {
9723 ngtcp2_acktr_immediate_ack(&pktns->acktr);
9724 }
9725
9726 conn_restart_timer_on_read(conn, ts);
9727
9728 ngtcp2_qlog_metrics_updated(&conn->qlog, &conn->cstat);
9729
9730 return conn->state == NGTCP2_CS_DRAINING ? NGTCP2_ERR_DRAINING
9731 : (ngtcp2_ssize)pktlen;
9732 }
9733
9734 /*
9735 * conn_process_buffered_protected_pkt processes buffered 0RTT or 1RTT
9736 * packets.
9737 *
9738 * This function returns 0 if it succeeds, or the same negative error
9739 * codes from conn_recv_pkt.
9740 */
9741 static int conn_process_buffered_protected_pkt(ngtcp2_conn *conn,
9742 ngtcp2_pktns *pktns,
9743 ngtcp2_tstamp ts) {
9744 ngtcp2_ssize nread;
9745 ngtcp2_pkt_chain **ppc, *next;
9746 int rv;
9747
9748 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CON,
9749 "processing buffered protected packet");
9750
9751 for (ppc = &pktns->rx.buffed_pkts; *ppc;) {
9752 next = (*ppc)->next;
9753 nread = conn_recv_pkt(conn, &(*ppc)->path.path, &(*ppc)->pi, (*ppc)->pkt,
9754 (*ppc)->pktlen, (*ppc)->dgramlen, (*ppc)->ts, ts);
9755 if (nread < 0 && !ngtcp2_err_is_fatal((int)nread) &&
9756 nread != NGTCP2_ERR_DRAINING) {
9757 /* TODO We don't know this is the first QUIC packet in a
9758 datagram. */
9759 rv = conn_on_stateless_reset(conn, &(*ppc)->path.path, (*ppc)->pkt,
9760 (*ppc)->pktlen);
9761 if (rv == 0) {
9762 ngtcp2_pkt_chain_del(*ppc, conn->mem);
9763 *ppc = next;
9764 return NGTCP2_ERR_DRAINING;
9765 }
9766 }
9767
9768 ngtcp2_pkt_chain_del(*ppc, conn->mem);
9769 *ppc = next;
9770 if (nread < 0) {
9771 if (nread == NGTCP2_ERR_DISCARD_PKT) {
9772 ++conn->cstat.pkt_discarded;
9773 continue;
9774 }
9775 return (int)nread;
9776 }
9777 }
9778
9779 return 0;
9780 }
9781
9782 /*
9783 * conn_process_buffered_handshake_pkt processes buffered Handshake
9784 * packets.
9785 *
9786 * This function returns 0 if it succeeds, or the same negative error
9787 * codes from conn_recv_handshake_pkt.
9788 */
9789 static int conn_process_buffered_handshake_pkt(ngtcp2_conn *conn,
9790 ngtcp2_tstamp ts) {
9791 ngtcp2_pktns *pktns = conn->hs_pktns;
9792 ngtcp2_ssize nread;
9793 ngtcp2_pkt_chain **ppc, *next;
9794
9795 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CON,
9796 "processing buffered handshake packet");
9797
9798 for (ppc = &pktns->rx.buffed_pkts; *ppc;) {
9799 next = (*ppc)->next;
9800 nread = conn_recv_handshake_pkt(conn, &(*ppc)->path.path, &(*ppc)->pi,
9801 (*ppc)->pkt, (*ppc)->pktlen,
9802 (*ppc)->dgramlen, (*ppc)->ts, ts);
9803 ngtcp2_pkt_chain_del(*ppc, conn->mem);
9804 *ppc = next;
9805 if (nread < 0) {
9806 if (nread == NGTCP2_ERR_DISCARD_PKT) {
9807 ++conn->cstat.pkt_discarded;
9808 continue;
9809 }
9810 return (int)nread;
9811 }
9812 }
9813
9814 return 0;
9815 }
9816
9817 static void conn_sync_stream_id_limit(ngtcp2_conn *conn) {
9818 ngtcp2_transport_params *params = conn->remote.transport_params;
9819
9820 assert(params);
9821
9822 conn->local.bidi.max_streams = params->initial_max_streams_bidi;
9823 conn->local.uni.max_streams = params->initial_max_streams_uni;
9824 }
9825
9826 static int strm_set_max_offset(void *data, void *ptr) {
9827 ngtcp2_conn *conn = ptr;
9828 ngtcp2_transport_params *params = conn->remote.transport_params;
9829 ngtcp2_strm *strm = data;
9830 uint64_t max_offset;
9831 int rv;
9832
9833 assert(params);
9834
9835 if (!conn_local_stream(conn, strm->stream_id)) {
9836 return 0;
9837 }
9838
9839 if (bidi_stream(strm->stream_id)) {
9840 max_offset = params->initial_max_stream_data_bidi_remote;
9841 } else {
9842 max_offset = params->initial_max_stream_data_uni;
9843 }
9844
9845 if (strm->tx.max_offset < max_offset) {
9846 strm->tx.max_offset = max_offset;
9847
9848 /* Don't call callback if stream is half-closed local */
9849 if (strm->flags & NGTCP2_STRM_FLAG_SHUT_WR) {
9850 return 0;
9851 }
9852
9853 rv = conn_call_extend_max_stream_data(conn, strm, strm->stream_id,
9854 strm->tx.max_offset);
9855 if (rv != 0) {
9856 return rv;
9857 }
9858 }
9859
9860 return 0;
9861 }
9862
9863 static int conn_sync_stream_data_limit(ngtcp2_conn *conn) {
9864 return ngtcp2_map_each(&conn->strms, strm_set_max_offset, conn);
9865 }
9866
9867 /*
9868 * conn_handshake_completed is called once cryptographic handshake has
9869 * completed.
9870 *
9871 * This function returns 0 if it succeeds, or one of the following
9872 * negative error codes:
9873 *
9874 * NGTCP2_ERR_CALLBACK_FAILURE
9875 * User callback failed.
9876 */
9877 static int conn_handshake_completed(ngtcp2_conn *conn) {
9878 int rv;
9879
9880 conn->flags |= NGTCP2_CONN_FLAG_HANDSHAKE_COMPLETED;
9881
9882 rv = conn_call_handshake_completed(conn);
9883 if (rv != 0) {
9884 return rv;
9885 }
9886
9887 if (conn->local.bidi.max_streams > 0) {
9888 rv = conn_call_extend_max_local_streams_bidi(conn,
9889 conn->local.bidi.max_streams);
9890 if (rv != 0) {
9891 return rv;
9892 }
9893 }
9894 if (conn->local.uni.max_streams > 0) {
9895 rv =
9896 conn_call_extend_max_local_streams_uni(conn, conn->local.uni.max_streams);
9897 if (rv != 0) {
9898 return rv;
9899 }
9900 }
9901
9902 return 0;
9903 }
9904
9905 /*
9906 * conn_recv_cpkt processes compound packet after handshake. The
9907 * buffer pointed by |pkt| might contain multiple packets. The 1RTT
9908 * packet must be the last one because it does not have payload length
9909 * field.
9910 *
9911 * This function returns 0 if it succeeds, or the same negative error
9912 * codes from conn_recv_pkt except for NGTCP2_ERR_DISCARD_PKT.
9913 */
9914 static int conn_recv_cpkt(ngtcp2_conn *conn, const ngtcp2_path *path,
9915 const ngtcp2_pkt_info *pi, const uint8_t *pkt,
9916 size_t pktlen, ngtcp2_tstamp ts) {
9917 ngtcp2_ssize nread;
9918 int rv;
9919 const uint8_t *origpkt = pkt;
9920 size_t dgramlen = pktlen;
9921
9922 if (ngtcp2_path_eq(&conn->dcid.current.ps.path, path)) {
9923 conn->dcid.current.bytes_recv += dgramlen;
9924 }
9925
9926 if (conn->server && conn->local.transport_params.disable_active_migration &&
9927 !ngtcp2_addr_eq(&conn->dcid.current.ps.path.local, &path->local) &&
9928 !conn_server_preferred_addr_migration(conn, &path->local)) {
9929 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_PKT,
9930 "packet is discarded because active migration is disabled");
9931
9932 return 0;
9933 }
9934
9935 while (pktlen) {
9936 nread = conn_recv_pkt(conn, path, pi, pkt, pktlen, dgramlen, ts, ts);
9937 if (nread < 0) {
9938 if (ngtcp2_err_is_fatal((int)nread)) {
9939 return (int)nread;
9940 }
9941
9942 if (nread == NGTCP2_ERR_DRAINING) {
9943 return NGTCP2_ERR_DRAINING;
9944 }
9945
9946 if (origpkt == pkt) {
9947 rv = conn_on_stateless_reset(conn, path, origpkt, dgramlen);
9948 if (rv == 0) {
9949 return NGTCP2_ERR_DRAINING;
9950 }
9951 }
9952 if (nread == NGTCP2_ERR_DISCARD_PKT) {
9953 ++conn->cstat.pkt_discarded;
9954 return 0;
9955 }
9956 return (int)nread;
9957 }
9958
9959 assert(pktlen >= (size_t)nread);
9960 pkt += nread;
9961 pktlen -= (size_t)nread;
9962
9963 ++conn->cstat.pkt_recv;
9964 conn->cstat.bytes_recv += (uint64_t)nread;
9965
9966 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_PKT,
9967 "read packet %td left %zu", nread, pktlen);
9968 }
9969
9970 return 0;
9971 }
9972
9973 /*
9974 * conn_enqueue_handshake_done enqueues HANDSHAKE_DONE frame for
9975 * transmission.
9976 */
9977 static int conn_enqueue_handshake_done(ngtcp2_conn *conn) {
9978 ngtcp2_pktns *pktns = &conn->pktns;
9979 ngtcp2_frame_chain *nfrc;
9980 int rv;
9981
9982 assert(conn->server);
9983
9984 rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
9985 if (rv != 0) {
9986 return rv;
9987 }
9988
9989 nfrc->fr.handshake_done.type = NGTCP2_FRAME_HANDSHAKE_DONE;
9990 nfrc->next = pktns->tx.frq;
9991 pktns->tx.frq = nfrc;
9992
9993 return 0;
9994 }
9995
9996 /**
9997 * @function
9998 *
9999 * `conn_read_handshake` performs QUIC cryptographic handshake by
10000 * reading given data. |pkt| points to the buffer to read and
10001 * |pktlen| is the length of the buffer. |path| is the network path.
10002 *
10003 * This function returns the number of bytes processed. Unless the
10004 * last packet is 1RTT packet and an application decryption key has
10005 * been installed, it returns |pktlen| if it succeeds. If it finds
10006 * 1RTT packet and an application decryption key has been installed,
10007 * it returns the number of bytes just before 1RTT packet begins.
10008 *
10009 * This function returns the number of bytes processed if it succeeds,
10010 * or one of the following negative error codes: (TBD).
10011 */
10012 static ngtcp2_ssize conn_read_handshake(ngtcp2_conn *conn,
10013 const ngtcp2_path *path,
10014 const ngtcp2_pkt_info *pi,
10015 const uint8_t *pkt, size_t pktlen,
10016 ngtcp2_tstamp ts) {
10017 int rv;
10018 ngtcp2_ssize nread;
10019
10020 switch (conn->state) {
10021 case NGTCP2_CS_CLIENT_INITIAL:
10022 /* TODO Better to log something when we ignore input */
10023 return (ngtcp2_ssize)pktlen;
10024 case NGTCP2_CS_CLIENT_WAIT_HANDSHAKE:
10025 nread = conn_recv_handshake_cpkt(conn, path, pi, pkt, pktlen, ts);
10026 if (nread < 0) {
10027 return nread;
10028 }
10029
10030 if (conn->state == NGTCP2_CS_CLIENT_INITIAL) {
10031 /* Retry packet was received */
10032 return (ngtcp2_ssize)pktlen;
10033 }
10034
10035 assert(conn->hs_pktns);
10036
10037 if (conn->hs_pktns->crypto.rx.ckm && conn->in_pktns) {
10038 rv = conn_process_buffered_handshake_pkt(conn, ts);
10039 if (rv != 0) {
10040 return rv;
10041 }
10042 }
10043
10044 if (conn_is_tls_handshake_completed(conn) &&
10045 !(conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_COMPLETED)) {
10046 rv = conn_handshake_completed(conn);
10047 if (rv != 0) {
10048 return rv;
10049 }
10050
10051 rv = conn_process_buffered_protected_pkt(conn, &conn->pktns, ts);
10052 if (rv != 0) {
10053 return rv;
10054 }
10055 }
10056
10057 return nread;
10058 case NGTCP2_CS_SERVER_INITIAL:
10059 nread = conn_recv_handshake_cpkt(conn, path, pi, pkt, pktlen, ts);
10060 if (nread < 0) {
10061 return nread;
10062 }
10063
10064 /*
10065 * Client Hello might not fit into single Initial packet (e.g.,
10066 * resuming session with client authentication). If we get Client
10067 * Initial which does not increase offset or it is 0RTT packet
10068 * buffered, perform address validation in order to buffer
10069 * validated data only.
10070 */
10071 if (ngtcp2_strm_rx_offset(&conn->in_pktns->crypto.strm) == 0) {
10072 if (conn->in_pktns->crypto.strm.rx.rob &&
10073 ngtcp2_rob_data_buffered(conn->in_pktns->crypto.strm.rx.rob)) {
10074 /* Address has been validated with token */
10075 if (conn->local.settings.tokenlen) {
10076 return nread;
10077 }
10078 return NGTCP2_ERR_RETRY;
10079 }
10080 /* If CRYPTO frame is not processed, just drop connection. */
10081 return NGTCP2_ERR_DROP_CONN;
10082 }
10083
10084 /* Process re-ordered 0-RTT packets which arrived before Initial
10085 packet. */
10086 if (conn->early.ckm) {
10087 assert(conn->in_pktns);
10088
10089 rv = conn_process_buffered_protected_pkt(conn, conn->in_pktns, ts);
10090 if (rv != 0) {
10091 return rv;
10092 }
10093 }
10094
10095 return nread;
10096 case NGTCP2_CS_SERVER_WAIT_HANDSHAKE:
10097 nread = conn_recv_handshake_cpkt(conn, path, pi, pkt, pktlen, ts);
10098 if (nread < 0) {
10099 return nread;
10100 }
10101
10102 if (conn->hs_pktns->crypto.rx.ckm) {
10103 rv = conn_process_buffered_handshake_pkt(conn, ts);
10104 if (rv != 0) {
10105 return rv;
10106 }
10107 }
10108
10109 if (conn->hs_pktns->acktr.max_pkt_num != -1) {
10110 ngtcp2_conn_discard_initial_state(conn, ts);
10111 }
10112
10113 if (!conn_is_tls_handshake_completed(conn)) {
10114 /* If server hits amplification limit, it cancels loss detection
10115 timer. If server receives a packet from client, the limit is
10116 increased and server can send more. If server has
10117 ack-eliciting Initial or Handshake packets, it should resend
10118 it if timer fired but timer is not armed in this case. So
10119 instead of resending Initial/Handshake packets, if server has
10120 1RTT data to send, it might send them and then might hit
10121 amplification limit again until it hits stream data limit.
10122 Initial/Handshake data is not resent. In order to avoid this
10123 situation, try to arm loss detection and check the expiry
10124 here so that on next write call, we can resend
10125 Initial/Handshake first. */
10126 if (conn->cstat.loss_detection_timer == UINT64_MAX) {
10127 ngtcp2_conn_set_loss_detection_timer(conn, ts);
10128 if (ngtcp2_conn_loss_detection_expiry(conn) <= ts) {
10129 rv = ngtcp2_conn_on_loss_detection_timer(conn, ts);
10130 if (rv != 0) {
10131 return rv;
10132 }
10133 }
10134 }
10135
10136 if ((size_t)nread < pktlen) {
10137 /* We have 1RTT packet and application rx key, but the
10138 handshake has not completed yet. */
10139 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON,
10140 "buffering 1RTT packet len=%zu",
10141 pktlen - (size_t)nread);
10142
10143 rv = conn_buffer_pkt(conn, &conn->pktns, path, pi, pkt + nread,
10144 pktlen - (size_t)nread, pktlen, ts);
10145 if (rv != 0) {
10146 assert(ngtcp2_err_is_fatal(rv));
10147 return rv;
10148 }
10149
10150 return (ngtcp2_ssize)pktlen;
10151 }
10152
10153 return nread;
10154 }
10155
10156 if (!(conn->flags & NGTCP2_CONN_FLAG_TRANSPORT_PARAM_RECVED)) {
10157 return NGTCP2_ERR_REQUIRED_TRANSPORT_PARAM;
10158 }
10159
10160 rv = conn_handshake_completed(conn);
10161 if (rv != 0) {
10162 return rv;
10163 }
10164 conn->state = NGTCP2_CS_POST_HANDSHAKE;
10165
10166 rv = conn_call_activate_dcid(conn, &conn->dcid.current);
10167 if (rv != 0) {
10168 return rv;
10169 }
10170
10171 rv = conn_process_buffered_protected_pkt(conn, &conn->pktns, ts);
10172 if (rv != 0) {
10173 return rv;
10174 }
10175
10176 ngtcp2_conn_discard_handshake_state(conn, ts);
10177
10178 rv = conn_enqueue_handshake_done(conn);
10179 if (rv != 0) {
10180 return rv;
10181 }
10182
10183 if (!conn->local.settings.no_pmtud) {
10184 rv = conn_start_pmtud(conn);
10185 if (rv != 0) {
10186 return rv;
10187 }
10188 }
10189
10190 conn->handshake_confirmed_ts = ts;
10191
10192 /* Re-arm loss detection timer here after handshake has been
10193 confirmed. */
10194 ngtcp2_conn_set_loss_detection_timer(conn, ts);
10195
10196 return nread;
10197 case NGTCP2_CS_CLOSING:
10198 return NGTCP2_ERR_CLOSING;
10199 case NGTCP2_CS_DRAINING:
10200 return NGTCP2_ERR_DRAINING;
10201 default:
10202 return (ngtcp2_ssize)pktlen;
10203 }
10204 }
10205
10206 int ngtcp2_conn_read_pkt_versioned(ngtcp2_conn *conn, const ngtcp2_path *path,
10207 int pkt_info_version,
10208 const ngtcp2_pkt_info *pi,
10209 const uint8_t *pkt, size_t pktlen,
10210 ngtcp2_tstamp ts) {
10211 int rv = 0;
10212 ngtcp2_ssize nread = 0;
10213 const ngtcp2_pkt_info zero_pi = {0};
10214 (void)pkt_info_version;
10215
10216 assert(!(conn->flags & NGTCP2_CONN_FLAG_PPE_PENDING));
10217
10218 conn_update_timestamp(conn, ts);
10219
10220 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON, "recv packet len=%zu",
10221 pktlen);
10222
10223 if (pktlen == 0) {
10224 return 0;
10225 }
10226
10227 /* client does not expect a packet from unknown path. */
10228 if (!conn->server && !ngtcp2_path_eq(&conn->dcid.current.ps.path, path) &&
10229 (!conn->pv || !ngtcp2_path_eq(&conn->pv->dcid.ps.path, path)) &&
10230 !ngtcp2_dcidtr_check_path_retired(&conn->dcid.dtr, path)) {
10231 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CON,
10232 "ignore packet from unknown path");
10233 ++conn->cstat.pkt_discarded;
10234
10235 return 0;
10236 }
10237
10238 if (!pi) {
10239 pi = &zero_pi;
10240 }
10241
10242 switch (conn->state) {
10243 case NGTCP2_CS_CLIENT_INITIAL:
10244 case NGTCP2_CS_CLIENT_WAIT_HANDSHAKE:
10245 nread = conn_read_handshake(conn, path, pi, pkt, pktlen, ts);
10246 if (nread < 0) {
10247 return (int)nread;
10248 }
10249
10250 if ((size_t)nread == pktlen) {
10251 return 0;
10252 }
10253
10254 assert(conn->pktns.crypto.rx.ckm);
10255
10256 pkt += nread;
10257 pktlen -= (size_t)nread;
10258
10259 break;
10260 case NGTCP2_CS_SERVER_INITIAL:
10261 case NGTCP2_CS_SERVER_WAIT_HANDSHAKE:
10262 if (!ngtcp2_path_eq(&conn->dcid.current.ps.path, path)) {
10263 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_CON,
10264 "ignore packet from unknown path during handshake");
10265
10266 if (conn->state == NGTCP2_CS_SERVER_INITIAL &&
10267 ngtcp2_strm_rx_offset(&conn->in_pktns->crypto.strm) == 0 &&
10268 (!conn->in_pktns->crypto.strm.rx.rob ||
10269 !ngtcp2_rob_data_buffered(conn->in_pktns->crypto.strm.rx.rob))) {
10270 return NGTCP2_ERR_DROP_CONN;
10271 }
10272
10273 return 0;
10274 }
10275
10276 nread = conn_read_handshake(conn, path, pi, pkt, pktlen, ts);
10277 if (nread < 0) {
10278 return (int)nread;
10279 }
10280
10281 if ((size_t)nread == pktlen) {
10282 return 0;
10283 }
10284
10285 assert(conn->pktns.crypto.rx.ckm);
10286
10287 pkt += nread;
10288 pktlen -= (size_t)nread;
10289
10290 break;
10291 case NGTCP2_CS_CLOSING:
10292 return NGTCP2_ERR_CLOSING;
10293 case NGTCP2_CS_DRAINING:
10294 return NGTCP2_ERR_DRAINING;
10295 case NGTCP2_CS_POST_HANDSHAKE:
10296 rv = conn_prepare_key_update(conn, ts);
10297 if (rv != 0) {
10298 return rv;
10299 }
10300 break;
10301 default:
10302 ngtcp2_unreachable();
10303 }
10304
10305 return conn_recv_cpkt(conn, path, pi, pkt, pktlen, ts);
10306 }
10307
10308 /*
10309 * conn_check_pkt_num_exhausted returns nonzero if packet number is
10310 * exhausted in at least one of packet number space.
10311 */
10312 static int conn_check_pkt_num_exhausted(ngtcp2_conn *conn) {
10313 ngtcp2_pktns *in_pktns = conn->in_pktns;
10314 ngtcp2_pktns *hs_pktns = conn->hs_pktns;
10315
10316 return (in_pktns && in_pktns->tx.last_pkt_num == NGTCP2_MAX_PKT_NUM) ||
10317 (hs_pktns && hs_pktns->tx.last_pkt_num == NGTCP2_MAX_PKT_NUM) ||
10318 conn->pktns.tx.last_pkt_num == NGTCP2_MAX_PKT_NUM;
10319 }
10320
10321 /*
10322 * conn_retransmit_retry_early retransmits 0RTT packet after Retry is
10323 * received from server.
10324 */
10325 static ngtcp2_ssize
10326 conn_retransmit_retry_early(ngtcp2_conn *conn, ngtcp2_pkt_info *pi,
10327 uint8_t *dest, size_t destlen, size_t dgram_offset,
10328 uint8_t flags, ngtcp2_tstamp ts) {
10329 return conn_write_pkt(conn, pi, dest, destlen, dgram_offset, NULL,
10330 NGTCP2_PKT_0RTT, flags, ts);
10331 }
10332
10333 /*
10334 * conn_handshake_probe_left returns nonzero if there are probe
10335 * packets to be sent for Initial or Handshake packet number space
10336 * left.
10337 */
10338 static int conn_handshake_probe_left(ngtcp2_conn *conn) {
10339 return (conn->in_pktns && conn->in_pktns->rtb.probe_pkt_left) ||
10340 conn->hs_pktns->rtb.probe_pkt_left;
10341 }
10342
10343 /*
10344 * conn_validate_early_transport_params_limits validates that the
10345 * limits in transport parameters remembered by client for early data
10346 * are not reduced. This function is only used by client and should
10347 * only be called when early data is accepted by server.
10348 */
10349 static int conn_validate_early_transport_params_limits(ngtcp2_conn *conn) {
10350 const ngtcp2_transport_params *params = conn->remote.transport_params;
10351
10352 assert(!conn->server);
10353 assert(params);
10354
10355 if (conn->early.transport_params.active_connection_id_limit >
10356 params->active_connection_id_limit ||
10357 conn->early.transport_params.initial_max_data >
10358 params->initial_max_data ||
10359 conn->early.transport_params.initial_max_stream_data_bidi_local >
10360 params->initial_max_stream_data_bidi_local ||
10361 conn->early.transport_params.initial_max_stream_data_bidi_remote >
10362 params->initial_max_stream_data_bidi_remote ||
10363 conn->early.transport_params.initial_max_stream_data_uni >
10364 params->initial_max_stream_data_uni ||
10365 conn->early.transport_params.initial_max_streams_bidi >
10366 params->initial_max_streams_bidi ||
10367 conn->early.transport_params.initial_max_streams_uni >
10368 params->initial_max_streams_uni ||
10369 conn->early.transport_params.max_datagram_frame_size >
10370 params->max_datagram_frame_size) {
10371 return NGTCP2_ERR_PROTO;
10372 }
10373
10374 return 0;
10375 }
10376
10377 /*
10378 * conn_write_handshake writes QUIC handshake packets to the buffer
10379 * pointed by |dest| of length |destlen|. |write_datalen| specifies
10380 * the expected length of 0RTT packet payload. Specify 0 to
10381 * |write_datalen| if there is no such data.
10382 *
10383 * This function returns the number of bytes written to the buffer, or
10384 * one of the following negative error codes:
10385 *
10386 * NGTCP2_ERR_PKT_NUM_EXHAUSTED
10387 * Packet number is exhausted.
10388 * NGTCP2_ERR_NOMEM
10389 * Out of memory
10390 * NGTCP2_ERR_REQUIRED_TRANSPORT_PARAM
10391 * Required transport parameter is missing.
10392 * NGTCP2_CS_CLOSING
10393 * Connection is in closing state.
10394 * NGTCP2_CS_DRAINING
10395 * Connection is in draining state.
10396 *
10397 * In addition to the above negative error codes, the same error codes
10398 * from conn_recv_pkt may also be returned.
10399 */
10400 static ngtcp2_ssize conn_write_handshake(ngtcp2_conn *conn, ngtcp2_pkt_info *pi,
10401 uint8_t *dest, size_t destlen,
10402 uint8_t wflags, uint64_t write_datalen,
10403 ngtcp2_tstamp ts) {
10404 int rv;
10405 ngtcp2_ssize res = 0, nwrite = 0, early_spktlen = 0;
10406 size_t origlen = destlen;
10407 uint64_t pending_early_datalen;
10408 ngtcp2_preferred_addr *paddr;
10409
10410 switch (conn->state) {
10411 case NGTCP2_CS_CLIENT_INITIAL:
10412 pending_early_datalen = conn_retry_early_payloadlen(conn);
10413 if (pending_early_datalen) {
10414 write_datalen = pending_early_datalen;
10415 }
10416
10417 if (!(conn->flags & NGTCP2_CONN_FLAG_RECV_RETRY)) {
10418 nwrite =
10419 conn_write_client_initial(conn, pi, dest, destlen, write_datalen, ts);
10420 if (nwrite <= 0) {
10421 return nwrite;
10422 }
10423 } else {
10424 nwrite =
10425 conn_write_handshake_pkt(conn, pi, dest, destlen, 0, NGTCP2_PKT_INITIAL,
10426 NGTCP2_WRITE_PKT_FLAG_NONE, write_datalen, ts);
10427 if (nwrite < 0) {
10428 return nwrite;
10429 }
10430 }
10431
10432 if (pending_early_datalen) {
10433 early_spktlen = conn_retransmit_retry_early(
10434 conn, pi, dest + nwrite, destlen - (size_t)nwrite, (size_t)nwrite,
10435 wflags | (nwrite ? NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING
10436 : NGTCP2_WRITE_PKT_FLAG_NONE),
10437 ts);
10438
10439 if (early_spktlen < 0) {
10440 assert(ngtcp2_err_is_fatal((int)early_spktlen));
10441 return early_spktlen;
10442 }
10443 }
10444
10445 conn->state = NGTCP2_CS_CLIENT_WAIT_HANDSHAKE;
10446
10447 res = nwrite + early_spktlen;
10448
10449 return res;
10450 case NGTCP2_CS_CLIENT_WAIT_HANDSHAKE:
10451 pending_early_datalen = 0;
10452
10453 if (!conn_handshake_probe_left(conn) && conn_cwnd_is_zero(conn)) {
10454 destlen = 0;
10455 } else {
10456 if (!(conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_COMPLETED)) {
10457 pending_early_datalen = conn_retry_early_payloadlen(conn);
10458 if (pending_early_datalen) {
10459 write_datalen = pending_early_datalen;
10460 }
10461 }
10462
10463 nwrite =
10464 conn_write_handshake_pkts(conn, pi, dest, destlen, write_datalen, ts);
10465 if (nwrite < 0) {
10466 return nwrite;
10467 }
10468
10469 res += nwrite;
10470 dest += nwrite;
10471 destlen -= (size_t)nwrite;
10472 }
10473
10474 if (!conn_is_tls_handshake_completed(conn)) {
10475 if (pending_early_datalen &&
10476 !(conn->flags & NGTCP2_CONN_FLAG_EARLY_DATA_REJECTED)) {
10477 nwrite = conn_retransmit_retry_early(
10478 conn, pi, dest, destlen, (size_t)res,
10479 wflags | ((nwrite &&
10480 ngtcp2_pkt_get_type_long(
10481 conn->negotiated_version ? conn->negotiated_version
10482 : conn->client_chosen_version,
10483 *(dest - nwrite)) == NGTCP2_PKT_INITIAL)
10484 ? NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING
10485 : NGTCP2_WRITE_PKT_FLAG_NONE),
10486 ts);
10487 if (nwrite < 0) {
10488 return nwrite;
10489 }
10490
10491 res += nwrite;
10492 }
10493
10494 if (res == 0) {
10495 nwrite = conn_write_handshake_ack_pkts(conn, pi, dest, origlen, ts);
10496 if (nwrite < 0) {
10497 return nwrite;
10498 }
10499 res = nwrite;
10500 }
10501
10502 return res;
10503 }
10504
10505 if (!(conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_COMPLETED)) {
10506 return res;
10507 }
10508
10509 if (!(conn->flags & NGTCP2_CONN_FLAG_TRANSPORT_PARAM_RECVED)) {
10510 return NGTCP2_ERR_REQUIRED_TRANSPORT_PARAM;
10511 }
10512
10513 if ((conn->flags & NGTCP2_CONN_FLAG_EARLY_KEY_INSTALLED) &&
10514 !(conn->flags & NGTCP2_CONN_FLAG_EARLY_DATA_REJECTED)) {
10515 rv = conn_validate_early_transport_params_limits(conn);
10516 if (rv != 0) {
10517 return rv;
10518 }
10519 }
10520
10521 /* Server might increase stream data limits. Extend it if we have
10522 streams created for early data. */
10523 rv = conn_sync_stream_data_limit(conn);
10524 if (rv != 0) {
10525 return rv;
10526 }
10527
10528 conn->state = NGTCP2_CS_POST_HANDSHAKE;
10529
10530 assert(conn->remote.transport_params);
10531
10532 if (conn->remote.transport_params->preferred_addr_present) {
10533 assert(!ngtcp2_dcidtr_unused_full(&conn->dcid.dtr));
10534
10535 paddr = &conn->remote.transport_params->preferred_addr;
10536 ngtcp2_dcidtr_push_unused(&conn->dcid.dtr, 1, &paddr->cid,
10537 paddr->stateless_reset_token);
10538
10539 rv = ngtcp2_gaptr_push(&conn->dcid.seqgap, 1, 1);
10540 if (rv != 0) {
10541 return (ngtcp2_ssize)rv;
10542 }
10543 }
10544
10545 if (conn->remote.transport_params->stateless_reset_token_present) {
10546 assert(conn->dcid.current.seq == 0);
10547 assert(!(conn->dcid.current.flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT));
10548 ngtcp2_dcid_set_token(
10549 &conn->dcid.current,
10550 conn->remote.transport_params->stateless_reset_token);
10551 }
10552
10553 rv = conn_call_activate_dcid(conn, &conn->dcid.current);
10554 if (rv != 0) {
10555 return rv;
10556 }
10557
10558 conn_process_early_rtb(conn);
10559
10560 if (!conn->local.settings.no_pmtud) {
10561 rv = conn_start_pmtud(conn);
10562 if (rv != 0) {
10563 return rv;
10564 }
10565 }
10566
10567 return res;
10568 case NGTCP2_CS_SERVER_INITIAL:
10569 nwrite =
10570 conn_write_handshake_pkts(conn, pi, dest, destlen, write_datalen, ts);
10571 if (nwrite < 0) {
10572 return nwrite;
10573 }
10574
10575 if (nwrite) {
10576 conn->state = NGTCP2_CS_SERVER_WAIT_HANDSHAKE;
10577 }
10578
10579 return nwrite;
10580 case NGTCP2_CS_SERVER_WAIT_HANDSHAKE:
10581 if (conn_handshake_probe_left(conn) || !conn_cwnd_is_zero(conn)) {
10582 nwrite =
10583 conn_write_handshake_pkts(conn, pi, dest, destlen, write_datalen, ts);
10584 if (nwrite < 0) {
10585 return nwrite;
10586 }
10587
10588 res += nwrite;
10589 }
10590
10591 if (res == 0) {
10592 nwrite = conn_write_handshake_ack_pkts(conn, pi, dest, origlen, ts);
10593 if (nwrite < 0) {
10594 return nwrite;
10595 }
10596
10597 res += nwrite;
10598 }
10599
10600 return res;
10601 case NGTCP2_CS_CLOSING:
10602 return NGTCP2_ERR_CLOSING;
10603 case NGTCP2_CS_DRAINING:
10604 return NGTCP2_ERR_DRAINING;
10605 default:
10606 return 0;
10607 }
10608 }
10609
10610 /**
10611 * @function
10612 *
10613 * `conn_client_write_handshake` writes client side handshake data and
10614 * 0RTT packet.
10615 *
10616 * In order to send STREAM data in 0RTT packet, specify
10617 * |vmsg|->stream. |vmsg|->stream.strm, |vmsg|->stream.fin,
10618 * |vmsg|->stream.data, and |vmsg|->stream.datacnt are stream to which
10619 * 0-RTT data is sent, whether it is a last data chunk in this stream,
10620 * a vector of 0-RTT data, and its number of elements respectively.
10621 * The amount of 0RTT data sent is assigned to
10622 * *|vmsg|->stream.pdatalen. If no data is sent, -1 is assigned.
10623 * Note that 0 length STREAM frame is allowed in QUIC, so 0 might be
10624 * assigned to *|vmsg|->stream.pdatalen.
10625 *
10626 * This function returns 0 if it cannot write any frame because buffer
10627 * is too small, or packet is congestion limited. Application should
10628 * keep reading and wait for congestion window to grow.
10629 *
10630 * This function returns the number of bytes written to the buffer
10631 * pointed by |dest| if it succeeds, or one of the following negative
10632 * error codes: (TBD).
10633 */
10634 static ngtcp2_ssize
10635 conn_client_write_handshake(ngtcp2_conn *conn, ngtcp2_pkt_info *pi,
10636 uint8_t *dest, size_t destlen, uint8_t wflags,
10637 ngtcp2_vmsg *vmsg, ngtcp2_tstamp ts) {
10638 int send_stream = 0;
10639 int send_datagram = 0;
10640 ngtcp2_ssize spktlen, early_spktlen;
10641 uint64_t datalen;
10642 uint64_t write_datalen = 0;
10643 int ppe_pending = (conn->flags & NGTCP2_CONN_FLAG_PPE_PENDING) != 0;
10644 uint32_t version;
10645
10646 assert(!conn->server);
10647
10648 /* conn->early.ckm might be created in the first call of
10649 conn_handshake(). Check it later. */
10650 if (vmsg) {
10651 switch (vmsg->type) {
10652 case NGTCP2_VMSG_TYPE_STREAM:
10653 datalen = ngtcp2_vec_len(vmsg->stream.data, vmsg->stream.datacnt);
10654 send_stream = conn_retry_early_payloadlen(conn) == 0;
10655 if (send_stream) {
10656 write_datalen = ngtcp2_min_uint64(datalen + NGTCP2_STREAM_OVERHEAD,
10657 NGTCP2_MIN_COALESCED_PAYLOADLEN);
10658
10659 if (vmsg->stream.flags & NGTCP2_WRITE_STREAM_FLAG_MORE) {
10660 wflags |= NGTCP2_WRITE_PKT_FLAG_MORE;
10661 }
10662 } else {
10663 vmsg = NULL;
10664 }
10665 break;
10666 case NGTCP2_VMSG_TYPE_DATAGRAM:
10667 datalen = ngtcp2_vec_len(vmsg->datagram.data, vmsg->datagram.datacnt);
10668 send_datagram = conn_retry_early_payloadlen(conn) == 0;
10669 if (send_datagram) {
10670 write_datalen = datalen + NGTCP2_DATAGRAM_OVERHEAD;
10671
10672 if (vmsg->datagram.flags & NGTCP2_WRITE_DATAGRAM_FLAG_MORE) {
10673 wflags |= NGTCP2_WRITE_PKT_FLAG_MORE;
10674 }
10675 } else {
10676 vmsg = NULL;
10677 }
10678 break;
10679 }
10680 }
10681
10682 if (!ppe_pending) {
10683 spktlen =
10684 conn_write_handshake(conn, pi, dest, destlen, wflags, write_datalen, ts);
10685
10686 if (spktlen < 0) {
10687 return spktlen;
10688 }
10689
10690 if ((conn->flags & NGTCP2_CONN_FLAG_EARLY_DATA_REJECTED) ||
10691 !conn->early.ckm || (!send_stream && !send_datagram)) {
10692 return spktlen;
10693 }
10694
10695 /* If spktlen > 0, we are making a compound packet. If Initial
10696 packet is written, we have to pad bytes to 0-RTT packet. */
10697 version = conn->negotiated_version ? conn->negotiated_version
10698 : conn->client_chosen_version;
10699 if (spktlen > 0 &&
10700 ngtcp2_pkt_get_type_long(version, dest[0]) == NGTCP2_PKT_INITIAL) {
10701 wflags |= NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING;
10702 }
10703 } else {
10704 assert(!conn->pktns.crypto.rx.ckm);
10705 assert(!conn->pktns.crypto.tx.ckm);
10706 assert(conn->early.ckm);
10707
10708 spktlen = conn->pkt.hs_spktlen;
10709 }
10710
10711 dest += spktlen;
10712 destlen -= (size_t)spktlen;
10713
10714 if (conn_cwnd_is_zero(conn)) {
10715 return spktlen;
10716 }
10717
10718 early_spktlen = conn_write_pkt(conn, pi, dest, destlen, (size_t)spktlen, vmsg,
10719 NGTCP2_PKT_0RTT, wflags, ts);
10720 if (early_spktlen < 0) {
10721 switch (early_spktlen) {
10722 case NGTCP2_ERR_STREAM_DATA_BLOCKED:
10723 if (!(wflags & NGTCP2_WRITE_PKT_FLAG_MORE)) {
10724 if (spktlen) {
10725 return spktlen;
10726 }
10727
10728 break;
10729 }
10730 /* fall through */
10731 case NGTCP2_ERR_WRITE_MORE:
10732 conn->pkt.hs_spktlen = spktlen;
10733 break;
10734 }
10735 return early_spktlen;
10736 }
10737
10738 return spktlen + early_spktlen;
10739 }
10740
10741 void ngtcp2_conn_tls_handshake_completed(ngtcp2_conn *conn) {
10742 conn->flags |= NGTCP2_CONN_FLAG_TLS_HANDSHAKE_COMPLETED;
10743 if (conn->server) {
10744 conn->flags |= NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED;
10745 }
10746 }
10747
10748 int ngtcp2_conn_get_handshake_completed(ngtcp2_conn *conn) {
10749 return conn_is_tls_handshake_completed(conn) &&
10750 (conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_COMPLETED);
10751 }
10752
10753 int ngtcp2_accept(ngtcp2_pkt_hd *dest, const uint8_t *pkt, size_t pktlen) {
10754 ngtcp2_ssize nread;
10755 ngtcp2_pkt_hd hd, *p;
10756
10757 if (dest) {
10758 p = dest;
10759 } else {
10760 p = &hd;
10761 }
10762
10763 if (pktlen == 0 || (pkt[0] & NGTCP2_HEADER_FORM_BIT) == 0) {
10764 return NGTCP2_ERR_INVALID_ARGUMENT;
10765 }
10766
10767 nread = ngtcp2_pkt_decode_hd_long(p, pkt, pktlen);
10768 if (nread < 0) {
10769 return (int)nread;
10770 }
10771
10772 switch (p->type) {
10773 case NGTCP2_PKT_INITIAL:
10774 break;
10775 case NGTCP2_PKT_0RTT:
10776 /* 0-RTT packet may arrive before Initial packet due to
10777 re-ordering. ngtcp2 does not buffer 0RTT packet unless the
10778 very first Initial packet is received or token is received.
10779 Previously, we returned NGTCP2_ERR_RETRY here, so that client
10780 can resend 0RTT data. But it incurs 1RTT already and
10781 diminishes the value of 0RTT. Therefore, we just discard the
10782 packet here for now. */
10783 default:
10784 return NGTCP2_ERR_INVALID_ARGUMENT;
10785 }
10786
10787 if (pktlen < NGTCP2_MAX_UDP_PAYLOAD_SIZE ||
10788 (p->tokenlen == 0 && p->dcid.datalen < NGTCP2_MIN_INITIAL_DCIDLEN)) {
10789 return NGTCP2_ERR_INVALID_ARGUMENT;
10790 }
10791
10792 return 0;
10793 }
10794
10795 int ngtcp2_conn_install_initial_key(
10796 ngtcp2_conn *conn, const ngtcp2_crypto_aead_ctx *rx_aead_ctx,
10797 const uint8_t *rx_iv, const ngtcp2_crypto_cipher_ctx *rx_hp_ctx,
10798 const ngtcp2_crypto_aead_ctx *tx_aead_ctx, const uint8_t *tx_iv,
10799 const ngtcp2_crypto_cipher_ctx *tx_hp_ctx, size_t ivlen) {
10800 ngtcp2_pktns *pktns = conn->in_pktns;
10801 int rv;
10802
10803 assert(ivlen >= 8);
10804 assert(pktns);
10805
10806 conn_call_delete_crypto_cipher_ctx(conn, &pktns->crypto.rx.hp_ctx);
10807 pktns->crypto.rx.hp_ctx.native_handle = NULL;
10808
10809 if (pktns->crypto.rx.ckm) {
10810 conn_call_delete_crypto_aead_ctx(conn, &pktns->crypto.rx.ckm->aead_ctx);
10811 ngtcp2_crypto_km_del(pktns->crypto.rx.ckm, conn->mem);
10812 pktns->crypto.rx.ckm = NULL;
10813 }
10814
10815 conn_call_delete_crypto_cipher_ctx(conn, &pktns->crypto.tx.hp_ctx);
10816 pktns->crypto.tx.hp_ctx.native_handle = NULL;
10817
10818 if (pktns->crypto.tx.ckm) {
10819 conn_call_delete_crypto_aead_ctx(conn, &pktns->crypto.tx.ckm->aead_ctx);
10820 ngtcp2_crypto_km_del(pktns->crypto.tx.ckm, conn->mem);
10821 pktns->crypto.tx.ckm = NULL;
10822 }
10823
10824 rv = ngtcp2_crypto_km_new(&pktns->crypto.rx.ckm, NULL, 0, NULL, rx_iv, ivlen,
10825 conn->mem);
10826 if (rv != 0) {
10827 return rv;
10828 }
10829
10830 rv = ngtcp2_crypto_km_new(&pktns->crypto.tx.ckm, NULL, 0, NULL, tx_iv, ivlen,
10831 conn->mem);
10832 if (rv != 0) {
10833 ngtcp2_crypto_km_del(pktns->crypto.rx.ckm, conn->mem);
10834 pktns->crypto.rx.ckm = NULL;
10835
10836 return rv;
10837 }
10838
10839 /* Take owner ship after we are sure that no failure occurs, so that
10840 caller can delete these contexts on failure. */
10841 pktns->crypto.rx.ckm->aead_ctx = *rx_aead_ctx;
10842 pktns->crypto.rx.hp_ctx = *rx_hp_ctx;
10843 pktns->crypto.tx.ckm->aead_ctx = *tx_aead_ctx;
10844 pktns->crypto.tx.hp_ctx = *tx_hp_ctx;
10845
10846 return 0;
10847 }
10848
10849 int ngtcp2_conn_install_vneg_initial_key(
10850 ngtcp2_conn *conn, uint32_t version,
10851 const ngtcp2_crypto_aead_ctx *rx_aead_ctx, const uint8_t *rx_iv,
10852 const ngtcp2_crypto_cipher_ctx *rx_hp_ctx,
10853 const ngtcp2_crypto_aead_ctx *tx_aead_ctx, const uint8_t *tx_iv,
10854 const ngtcp2_crypto_cipher_ctx *tx_hp_ctx, size_t ivlen) {
10855 int rv;
10856
10857 assert(ivlen >= 8);
10858
10859 conn_call_delete_crypto_cipher_ctx(conn, &conn->vneg.rx.hp_ctx);
10860 conn->vneg.rx.hp_ctx.native_handle = NULL;
10861
10862 if (conn->vneg.rx.ckm) {
10863 conn_call_delete_crypto_aead_ctx(conn, &conn->vneg.rx.ckm->aead_ctx);
10864 ngtcp2_crypto_km_del(conn->vneg.rx.ckm, conn->mem);
10865 conn->vneg.rx.ckm = NULL;
10866 }
10867
10868 conn_call_delete_crypto_cipher_ctx(conn, &conn->vneg.tx.hp_ctx);
10869 conn->vneg.tx.hp_ctx.native_handle = NULL;
10870
10871 if (conn->vneg.tx.ckm) {
10872 conn_call_delete_crypto_aead_ctx(conn, &conn->vneg.tx.ckm->aead_ctx);
10873 ngtcp2_crypto_km_del(conn->vneg.tx.ckm, conn->mem);
10874 conn->vneg.tx.ckm = NULL;
10875 }
10876
10877 rv = ngtcp2_crypto_km_new(&conn->vneg.rx.ckm, NULL, 0, NULL, rx_iv, ivlen,
10878 conn->mem);
10879 if (rv != 0) {
10880 return rv;
10881 }
10882
10883 rv = ngtcp2_crypto_km_new(&conn->vneg.tx.ckm, NULL, 0, NULL, tx_iv, ivlen,
10884 conn->mem);
10885 if (rv != 0) {
10886 ngtcp2_crypto_km_del(conn->vneg.rx.ckm, conn->mem);
10887 conn->vneg.rx.ckm = NULL;
10888
10889 return rv;
10890 }
10891
10892 /* Take owner ship after we are sure that no failure occurs, so that
10893 caller can delete these contexts on failure. */
10894 conn->vneg.rx.ckm->aead_ctx = *rx_aead_ctx;
10895 conn->vneg.rx.hp_ctx = *rx_hp_ctx;
10896 conn->vneg.tx.ckm->aead_ctx = *tx_aead_ctx;
10897 conn->vneg.tx.hp_ctx = *tx_hp_ctx;
10898 conn->vneg.version = version;
10899
10900 return 0;
10901 }
10902
10903 int ngtcp2_conn_install_rx_handshake_key(
10904 ngtcp2_conn *conn, const ngtcp2_crypto_aead_ctx *aead_ctx, const uint8_t *iv,
10905 size_t ivlen, const ngtcp2_crypto_cipher_ctx *hp_ctx) {
10906 ngtcp2_pktns *pktns = conn->hs_pktns;
10907 int rv;
10908
10909 assert(ivlen >= 8);
10910 assert(pktns);
10911 assert(!pktns->crypto.rx.hp_ctx.native_handle);
10912 assert(!pktns->crypto.rx.ckm);
10913
10914 rv = ngtcp2_crypto_km_new(&pktns->crypto.rx.ckm, NULL, 0, aead_ctx, iv, ivlen,
10915 conn->mem);
10916 if (rv != 0) {
10917 return rv;
10918 }
10919
10920 pktns->crypto.rx.hp_ctx = *hp_ctx;
10921
10922 rv = conn_call_recv_rx_key(conn, NGTCP2_ENCRYPTION_LEVEL_HANDSHAKE);
10923 if (rv != 0) {
10924 ngtcp2_crypto_km_del(pktns->crypto.rx.ckm, conn->mem);
10925 pktns->crypto.rx.ckm = NULL;
10926
10927 memset(&pktns->crypto.rx.hp_ctx, 0, sizeof(pktns->crypto.rx.hp_ctx));
10928
10929 return rv;
10930 }
10931
10932 return 0;
10933 }
10934
10935 int ngtcp2_conn_install_tx_handshake_key(
10936 ngtcp2_conn *conn, const ngtcp2_crypto_aead_ctx *aead_ctx, const uint8_t *iv,
10937 size_t ivlen, const ngtcp2_crypto_cipher_ctx *hp_ctx) {
10938 ngtcp2_pktns *pktns = conn->hs_pktns;
10939 int rv;
10940
10941 assert(ivlen >= 8);
10942 assert(pktns);
10943 assert(!pktns->crypto.tx.hp_ctx.native_handle);
10944 assert(!pktns->crypto.tx.ckm);
10945
10946 rv = ngtcp2_crypto_km_new(&pktns->crypto.tx.ckm, NULL, 0, aead_ctx, iv, ivlen,
10947 conn->mem);
10948 if (rv != 0) {
10949 return rv;
10950 }
10951
10952 pktns->crypto.tx.hp_ctx = *hp_ctx;
10953
10954 if (conn->server) {
10955 rv = ngtcp2_conn_commit_local_transport_params(conn);
10956 if (rv != 0) {
10957 goto fail;
10958 }
10959 }
10960
10961 rv = conn_call_recv_tx_key(conn, NGTCP2_ENCRYPTION_LEVEL_HANDSHAKE);
10962 if (rv != 0) {
10963 goto fail;
10964 }
10965
10966 return 0;
10967
10968 fail:
10969 /* If this function fails, aead_ctx and hp_ctx are still owned by
10970 the caller. Delete the install key to remove the any reference
10971 to them. */
10972 ngtcp2_crypto_km_del(pktns->crypto.tx.ckm, conn->mem);
10973 pktns->crypto.tx.ckm = NULL;
10974
10975 memset(&pktns->crypto.tx.hp_ctx, 0, sizeof(pktns->crypto.tx.hp_ctx));
10976
10977 return rv;
10978 }
10979
10980 int ngtcp2_conn_install_0rtt_key(ngtcp2_conn *conn,
10981 const ngtcp2_crypto_aead_ctx *aead_ctx,
10982 const uint8_t *iv, size_t ivlen,
10983 const ngtcp2_crypto_cipher_ctx *hp_ctx) {
10984 int rv;
10985
10986 assert(ivlen >= 8);
10987 assert(!conn->early.hp_ctx.native_handle);
10988 assert(!conn->early.ckm);
10989
10990 rv = ngtcp2_crypto_km_new(&conn->early.ckm, NULL, 0, aead_ctx, iv, ivlen,
10991 conn->mem);
10992 if (rv != 0) {
10993 return rv;
10994 }
10995
10996 conn->early.hp_ctx = *hp_ctx;
10997
10998 conn->flags |= NGTCP2_CONN_FLAG_EARLY_KEY_INSTALLED;
10999
11000 if (conn->server) {
11001 rv = conn_call_recv_rx_key(conn, NGTCP2_ENCRYPTION_LEVEL_0RTT);
11002 } else {
11003 rv = conn_call_recv_tx_key(conn, NGTCP2_ENCRYPTION_LEVEL_0RTT);
11004 }
11005 if (rv != 0) {
11006 ngtcp2_crypto_km_del(conn->early.ckm, conn->mem);
11007 conn->early.ckm = NULL;
11008
11009 memset(&conn->early.hp_ctx, 0, sizeof(conn->early.hp_ctx));
11010
11011 return rv;
11012 }
11013
11014 return 0;
11015 }
11016
11017 int ngtcp2_conn_install_rx_key(ngtcp2_conn *conn, const uint8_t *secret,
11018 size_t secretlen,
11019 const ngtcp2_crypto_aead_ctx *aead_ctx,
11020 const uint8_t *iv, size_t ivlen,
11021 const ngtcp2_crypto_cipher_ctx *hp_ctx) {
11022 ngtcp2_pktns *pktns = &conn->pktns;
11023 int rv;
11024
11025 assert(ivlen >= 8);
11026 assert(!pktns->crypto.rx.hp_ctx.native_handle);
11027 assert(!pktns->crypto.rx.ckm);
11028
11029 rv = ngtcp2_crypto_km_new(&pktns->crypto.rx.ckm, secret, secretlen, aead_ctx,
11030 iv, ivlen, conn->mem);
11031 if (rv != 0) {
11032 return rv;
11033 }
11034
11035 pktns->crypto.rx.hp_ctx = *hp_ctx;
11036
11037 if (!conn->server) {
11038 if (conn->remote.pending_transport_params) {
11039 ngtcp2_transport_params_del(conn->remote.transport_params, conn->mem);
11040
11041 conn->remote.transport_params = conn->remote.pending_transport_params;
11042 conn->remote.pending_transport_params = NULL;
11043 conn_sync_stream_id_limit(conn);
11044 conn->tx.max_offset = conn->remote.transport_params->initial_max_data;
11045 }
11046
11047 if (conn->early.ckm) {
11048 conn_discard_early_key(conn);
11049 }
11050 }
11051
11052 rv = conn_call_recv_rx_key(conn, NGTCP2_ENCRYPTION_LEVEL_1RTT);
11053 if (rv != 0) {
11054 ngtcp2_crypto_km_del(pktns->crypto.rx.ckm, conn->mem);
11055 pktns->crypto.rx.ckm = NULL;
11056
11057 memset(&pktns->crypto.rx.hp_ctx, 0, sizeof(pktns->crypto.rx.hp_ctx));
11058
11059 return rv;
11060 }
11061
11062 return 0;
11063 }
11064
11065 int ngtcp2_conn_install_tx_key(ngtcp2_conn *conn, const uint8_t *secret,
11066 size_t secretlen,
11067 const ngtcp2_crypto_aead_ctx *aead_ctx,
11068 const uint8_t *iv, size_t ivlen,
11069 const ngtcp2_crypto_cipher_ctx *hp_ctx) {
11070 ngtcp2_pktns *pktns = &conn->pktns;
11071 int rv;
11072
11073 assert(ivlen >= 8);
11074 assert(!pktns->crypto.tx.hp_ctx.native_handle);
11075 assert(!pktns->crypto.tx.ckm);
11076
11077 rv = ngtcp2_crypto_km_new(&pktns->crypto.tx.ckm, secret, secretlen, aead_ctx,
11078 iv, ivlen, conn->mem);
11079 if (rv != 0) {
11080 return rv;
11081 }
11082
11083 pktns->crypto.tx.hp_ctx = *hp_ctx;
11084
11085 if (conn->server) {
11086 if (conn->remote.pending_transport_params) {
11087 ngtcp2_transport_params_del(conn->remote.transport_params, conn->mem);
11088
11089 conn->remote.transport_params = conn->remote.pending_transport_params;
11090 conn->remote.pending_transport_params = NULL;
11091 conn_sync_stream_id_limit(conn);
11092 conn->tx.max_offset = conn->remote.transport_params->initial_max_data;
11093 }
11094 } else if (conn->early.ckm) {
11095 conn_discard_early_key(conn);
11096 }
11097
11098 rv = conn_call_recv_tx_key(conn, NGTCP2_ENCRYPTION_LEVEL_1RTT);
11099 if (rv != 0) {
11100 ngtcp2_crypto_km_del(pktns->crypto.tx.ckm, conn->mem);
11101 pktns->crypto.tx.ckm = NULL;
11102
11103 memset(&pktns->crypto.tx.hp_ctx, 0, sizeof(pktns->crypto.tx.hp_ctx));
11104
11105 return rv;
11106 }
11107
11108 return 0;
11109 }
11110
11111 static int conn_initiate_key_update(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
11112 ngtcp2_tstamp confirmed_ts = conn->crypto.key_update.confirmed_ts;
11113 ngtcp2_duration pto = conn_compute_pto(conn, &conn->pktns);
11114
11115 assert(conn->state == NGTCP2_CS_POST_HANDSHAKE);
11116
11117 if (!(conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED) ||
11118 (conn->flags & NGTCP2_CONN_FLAG_KEY_UPDATE_NOT_CONFIRMED) ||
11119 !conn->crypto.key_update.new_tx_ckm ||
11120 !conn->crypto.key_update.new_rx_ckm ||
11121 ngtcp2_tstamp_not_elapsed(confirmed_ts, 3 * pto, ts)) {
11122 return NGTCP2_ERR_INVALID_STATE;
11123 }
11124
11125 conn_rotate_keys(conn, NGTCP2_MAX_PKT_NUM, /* initiator = */ 1);
11126
11127 return 0;
11128 }
11129
11130 int ngtcp2_conn_initiate_key_update(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
11131 conn_update_timestamp(conn, ts);
11132
11133 return conn_initiate_key_update(conn, ts);
11134 }
11135
11136 ngtcp2_tstamp ngtcp2_conn_loss_detection_expiry(ngtcp2_conn *conn) {
11137 return conn->cstat.loss_detection_timer;
11138 }
11139
11140 ngtcp2_tstamp ngtcp2_conn_internal_expiry(ngtcp2_conn *conn) {
11141 ngtcp2_tstamp res = UINT64_MAX, ts;
11142 ngtcp2_duration pto = conn_compute_pto(conn, &conn->pktns);
11143 ngtcp2_scid *scid;
11144
11145 if (conn->pv) {
11146 res = ngtcp2_pv_next_expiry(conn->pv);
11147 }
11148
11149 if (conn->pmtud) {
11150 res = ngtcp2_min_uint64(res, conn->pmtud->expiry);
11151 }
11152
11153 if (!ngtcp2_pq_empty(&conn->scid.used)) {
11154 scid = ngtcp2_struct_of(ngtcp2_pq_top(&conn->scid.used), ngtcp2_scid, pe);
11155 if (scid->retired_ts != UINT64_MAX) {
11156 res = ngtcp2_min_uint64(res, scid->retired_ts + pto);
11157 }
11158 }
11159
11160 ts = ngtcp2_dcidtr_earliest_retired_ts(&conn->dcid.dtr);
11161 if (ts != UINT64_MAX) {
11162 res = ngtcp2_min_uint64(res, ts + pto);
11163 }
11164
11165 if (conn->dcid.current.cid.datalen) {
11166 ts = ngtcp2_dcidtr_earliest_bound_ts(&conn->dcid.dtr);
11167 if (ts != UINT64_MAX) {
11168 res = ngtcp2_min_uint64(res, ts + 3 * pto);
11169 }
11170 }
11171
11172 if (conn->server && conn->early.ckm &&
11173 conn->early.discard_started_ts != UINT64_MAX) {
11174 res = ngtcp2_min_uint64(res, conn->early.discard_started_ts + 3 * pto);
11175 }
11176
11177 return res;
11178 }
11179
11180 ngtcp2_tstamp ngtcp2_conn_ack_delay_expiry(ngtcp2_conn *conn) {
11181 ngtcp2_acktr *acktr = &conn->pktns.acktr;
11182
11183 if (!(acktr->flags & NGTCP2_ACKTR_FLAG_CANCEL_TIMER) &&
11184 acktr->first_unacked_ts != UINT64_MAX) {
11185 return acktr->first_unacked_ts + conn_compute_ack_delay(conn);
11186 }
11187 return UINT64_MAX;
11188 }
11189
11190 static ngtcp2_tstamp conn_handshake_expiry(ngtcp2_conn *conn) {
11191 if (conn_is_tls_handshake_completed(conn) ||
11192 conn->local.settings.handshake_timeout == UINT64_MAX ||
11193 conn->local.settings.initial_ts >=
11194 UINT64_MAX - conn->local.settings.handshake_timeout) {
11195 return UINT64_MAX;
11196 }
11197
11198 return conn->local.settings.initial_ts +
11199 conn->local.settings.handshake_timeout;
11200 }
11201
11202 ngtcp2_tstamp ngtcp2_conn_get_expiry(ngtcp2_conn *conn) {
11203 ngtcp2_tstamp res = ngtcp2_min_uint64(ngtcp2_conn_loss_detection_expiry(conn),
11204 ngtcp2_conn_ack_delay_expiry(conn));
11205 res = ngtcp2_min_uint64(res, ngtcp2_conn_internal_expiry(conn));
11206 res = ngtcp2_min_uint64(res, ngtcp2_conn_lost_pkt_expiry(conn));
11207 res = ngtcp2_min_uint64(res, conn_keep_alive_expiry(conn));
11208 res = ngtcp2_min_uint64(res, conn_handshake_expiry(conn));
11209 res = ngtcp2_min_uint64(res, ngtcp2_conn_get_idle_expiry(conn));
11210 return ngtcp2_min_uint64(res, conn->tx.pacing.next_ts);
11211 }
11212
11213 int ngtcp2_conn_handle_expiry(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
11214 int rv;
11215 ngtcp2_duration pto;
11216
11217 conn_update_timestamp(conn, ts);
11218
11219 pto = conn_compute_pto(conn, &conn->pktns);
11220
11221 assert(!(conn->flags & NGTCP2_CONN_FLAG_PPE_PENDING));
11222
11223 if (ngtcp2_conn_get_idle_expiry(conn) <= ts) {
11224 return NGTCP2_ERR_IDLE_CLOSE;
11225 }
11226
11227 ngtcp2_conn_cancel_expired_ack_delay_timer(conn, ts);
11228
11229 conn_cancel_expired_keep_alive_timer(conn, ts);
11230
11231 conn_cancel_expired_pkt_tx_timer(conn, ts);
11232
11233 ngtcp2_conn_remove_lost_pkt(conn, ts);
11234
11235 if (conn->pv) {
11236 ngtcp2_pv_cancel_expired_timer(conn->pv, ts);
11237 }
11238
11239 if (conn->pmtud) {
11240 ngtcp2_pmtud_handle_expiry(conn->pmtud, ts);
11241 if (ngtcp2_pmtud_finished(conn->pmtud)) {
11242 ngtcp2_conn_stop_pmtud(conn);
11243 }
11244 }
11245
11246 if (ngtcp2_conn_loss_detection_expiry(conn) <= ts) {
11247 rv = ngtcp2_conn_on_loss_detection_timer(conn, ts);
11248 if (rv != 0) {
11249 return rv;
11250 }
11251 }
11252
11253 if (conn->dcid.current.cid.datalen) {
11254 rv = ngtcp2_dcidtr_retire_stale_bound_dcid(&conn->dcid.dtr, 3 * pto, ts,
11255 dcidtr_on_retire, conn);
11256 if (rv != 0) {
11257 return rv;
11258 }
11259 }
11260
11261 rv = conn_remove_retired_connection_id(conn, pto, ts);
11262 if (rv != 0) {
11263 return rv;
11264 }
11265
11266 if (conn->server && conn->early.ckm &&
11267 ngtcp2_tstamp_elapsed(conn->early.discard_started_ts, 3 * pto, ts)) {
11268 conn_discard_early_key(conn);
11269 }
11270
11271 if (!conn_is_tls_handshake_completed(conn) &&
11272 ngtcp2_tstamp_elapsed(conn->local.settings.initial_ts,
11273 conn->local.settings.handshake_timeout, ts)) {
11274 return NGTCP2_ERR_HANDSHAKE_TIMEOUT;
11275 }
11276
11277 return 0;
11278 }
11279
11280 static void acktr_cancel_expired_ack_delay_timer(ngtcp2_acktr *acktr,
11281 ngtcp2_duration max_ack_delay,
11282 ngtcp2_tstamp ts) {
11283 if (!(acktr->flags & NGTCP2_ACKTR_FLAG_CANCEL_TIMER) &&
11284 ngtcp2_tstamp_elapsed(acktr->first_unacked_ts, max_ack_delay, ts)) {
11285 acktr->flags |= NGTCP2_ACKTR_FLAG_CANCEL_TIMER;
11286 }
11287 }
11288
11289 void ngtcp2_conn_cancel_expired_ack_delay_timer(ngtcp2_conn *conn,
11290 ngtcp2_tstamp ts) {
11291 ngtcp2_duration ack_delay = conn_compute_ack_delay(conn);
11292
11293 if (conn->in_pktns) {
11294 acktr_cancel_expired_ack_delay_timer(&conn->in_pktns->acktr, 0, ts);
11295 }
11296 if (conn->hs_pktns) {
11297 acktr_cancel_expired_ack_delay_timer(&conn->hs_pktns->acktr, 0, ts);
11298 }
11299 acktr_cancel_expired_ack_delay_timer(&conn->pktns.acktr, ack_delay, ts);
11300 }
11301
11302 ngtcp2_tstamp ngtcp2_conn_lost_pkt_expiry(ngtcp2_conn *conn) {
11303 ngtcp2_tstamp res = UINT64_MAX, ts;
11304
11305 if (conn->in_pktns) {
11306 ts = ngtcp2_rtb_lost_pkt_ts(&conn->in_pktns->rtb);
11307 if (ts != UINT64_MAX) {
11308 ts += conn_compute_pto(conn, conn->in_pktns) * 3;
11309 res = ngtcp2_min_uint64(res, ts);
11310 }
11311 }
11312
11313 if (conn->hs_pktns) {
11314 ts = ngtcp2_rtb_lost_pkt_ts(&conn->hs_pktns->rtb);
11315 if (ts != UINT64_MAX) {
11316 ts += conn_compute_pto(conn, conn->hs_pktns) * 3;
11317 res = ngtcp2_min_uint64(res, ts);
11318 }
11319 }
11320
11321 ts = ngtcp2_rtb_lost_pkt_ts(&conn->pktns.rtb);
11322 if (ts != UINT64_MAX) {
11323 ts += conn_compute_pto(conn, &conn->pktns) * 3;
11324 res = ngtcp2_min_uint64(res, ts);
11325 }
11326
11327 return res;
11328 }
11329
11330 void ngtcp2_conn_remove_lost_pkt(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
11331 ngtcp2_duration timeout;
11332
11333 if (conn->in_pktns) {
11334 timeout = conn_compute_pto(conn, conn->in_pktns) * 3;
11335 ngtcp2_rtb_remove_expired_lost_pkt(&conn->in_pktns->rtb, timeout, ts);
11336 }
11337 if (conn->hs_pktns) {
11338 timeout = conn_compute_pto(conn, conn->hs_pktns) * 3;
11339 ngtcp2_rtb_remove_expired_lost_pkt(&conn->hs_pktns->rtb, timeout, ts);
11340 }
11341 timeout = conn_compute_pto(conn, &conn->pktns) * 3;
11342 ngtcp2_rtb_remove_expired_lost_pkt(&conn->pktns.rtb, timeout, ts);
11343 }
11344
11345 /*
11346 * select_preferred_version selects the most preferred version.
11347 * |fallback_version| is chosen if no preference is made, or
11348 * |preferred_versions| does not include any of |chosen_version| or
11349 * |available_versions|. |chosen_version| is treated as an extra
11350 * other version.
11351 */
11352 static uint32_t select_preferred_version(const uint32_t *preferred_versions,
11353 size_t preferred_versionslen,
11354 uint32_t chosen_version,
11355 const uint8_t *available_versions,
11356 size_t available_versionslen,
11357 uint32_t fallback_version) {
11358 size_t i, j;
11359 const uint8_t *p;
11360 uint32_t v;
11361
11362 if (!preferred_versionslen ||
11363 (!available_versionslen && chosen_version == fallback_version)) {
11364 return fallback_version;
11365 }
11366
11367 for (i = 0; i < preferred_versionslen; ++i) {
11368 if (preferred_versions[i] == chosen_version) {
11369 return chosen_version;
11370 }
11371 for (j = 0, p = available_versions; j < available_versionslen;
11372 j += sizeof(uint32_t)) {
11373 p = ngtcp2_get_uint32be(&v, p);
11374
11375 if (preferred_versions[i] == v) {
11376 return v;
11377 }
11378 }
11379 }
11380
11381 return fallback_version;
11382 }
11383
11384 /*
11385 * conn_client_validate_transport_params validates |params| as client.
11386 * |params| must be sent with Encrypted Extensions.
11387 *
11388 * This function returns 0 if it succeeds, or one of the following
11389 * negative error codes:
11390 *
11391 * NGTCP2_ERR_TRANSPORT_PARAM
11392 * params contains preferred address but server chose zero-length
11393 * connection ID.
11394 * NGTCP2_ERR_VERSION_NEGOTIATION_FAILURE
11395 * Validation against version negotiation parameters failed.
11396 */
11397 static int
11398 conn_client_validate_transport_params(ngtcp2_conn *conn,
11399 const ngtcp2_transport_params *params) {
11400 if (!params->original_dcid_present) {
11401 return NGTCP2_ERR_REQUIRED_TRANSPORT_PARAM;
11402 }
11403
11404 if (!ngtcp2_cid_eq(&conn->rcid, &params->original_dcid)) {
11405 return NGTCP2_ERR_TRANSPORT_PARAM;
11406 }
11407
11408 if (conn->flags & NGTCP2_CONN_FLAG_RECV_RETRY) {
11409 if (!params->retry_scid_present) {
11410 return NGTCP2_ERR_TRANSPORT_PARAM;
11411 }
11412 if (!ngtcp2_cid_eq(&conn->retry_scid, &params->retry_scid)) {
11413 return NGTCP2_ERR_TRANSPORT_PARAM;
11414 }
11415 } else if (params->retry_scid_present) {
11416 return NGTCP2_ERR_TRANSPORT_PARAM;
11417 }
11418
11419 if (params->preferred_addr_present && conn->dcid.current.cid.datalen == 0) {
11420 return NGTCP2_ERR_TRANSPORT_PARAM;
11421 }
11422
11423 if (params->version_info_present) {
11424 if (conn->negotiated_version != params->version_info.chosen_version) {
11425 return NGTCP2_ERR_VERSION_NEGOTIATION_FAILURE;
11426 }
11427
11428 assert(vneg_available_versions_includes(conn->vneg.available_versions,
11429 conn->vneg.available_versionslen,
11430 conn->negotiated_version));
11431 } else if (conn->client_chosen_version != conn->negotiated_version) {
11432 return NGTCP2_ERR_VERSION_NEGOTIATION_FAILURE;
11433 }
11434
11435 /* When client reacted upon Version Negotiation */
11436 if (conn->local.settings.original_version != conn->client_chosen_version) {
11437 if (!params->version_info_present) {
11438 assert(conn->client_chosen_version == conn->negotiated_version);
11439
11440 /* QUIC v1 is treated specially. If version_info is missing, no
11441 further validation is necessary. See
11442 https://datatracker.ietf.org/doc/html/rfc9368#section-8
11443 */
11444 if (conn->client_chosen_version == NGTCP2_PROTO_VER_V1) {
11445 return 0;
11446 }
11447
11448 return NGTCP2_ERR_VERSION_NEGOTIATION_FAILURE;
11449 }
11450
11451 /* Server choose original version after Version Negotiation. RFC
11452 9368 does not say this particular case, but this smells like
11453 misbehaved server because server should accept original_version
11454 in the original connection. */
11455 if (conn->local.settings.original_version ==
11456 params->version_info.chosen_version) {
11457 return NGTCP2_ERR_VERSION_NEGOTIATION_FAILURE;
11458 }
11459
11460 /* Check version downgrade on incompatible version negotiation. */
11461 if (params->version_info.available_versionslen == 0) {
11462 return NGTCP2_ERR_VERSION_NEGOTIATION_FAILURE;
11463 }
11464
11465 if (conn->client_chosen_version !=
11466 select_preferred_version(conn->vneg.preferred_versions,
11467 conn->vneg.preferred_versionslen,
11468 params->version_info.chosen_version,
11469 params->version_info.available_versions,
11470 params->version_info.available_versionslen,
11471 /* fallback_version = */ 0)) {
11472 return NGTCP2_ERR_VERSION_NEGOTIATION_FAILURE;
11473 }
11474 }
11475
11476 return 0;
11477 }
11478
11479 uint32_t
11480 ngtcp2_conn_server_negotiate_version(ngtcp2_conn *conn,
11481 const ngtcp2_version_info *version_info) {
11482 assert(conn->server);
11483 assert(conn->client_chosen_version == version_info->chosen_version);
11484
11485 return select_preferred_version(
11486 conn->vneg.preferred_versions, conn->vneg.preferred_versionslen,
11487 version_info->chosen_version, version_info->available_versions,
11488 version_info->available_versionslen, version_info->chosen_version);
11489 }
11490
11491 int ngtcp2_conn_set_remote_transport_params(
11492 ngtcp2_conn *conn, const ngtcp2_transport_params *params) {
11493 int rv;
11494
11495 /* We expect this function is called once per QUIC connection, but
11496 GnuTLS server seems to call TLS extension callback twice if it
11497 sends HelloRetryRequest. In practice, same QUIC transport
11498 parameters are sent in the 2nd client flight, just returning 0
11499 would cause no harm. */
11500 if (conn->flags & NGTCP2_CONN_FLAG_TRANSPORT_PARAM_RECVED) {
11501 return 0;
11502 }
11503
11504 if (!params->initial_scid_present) {
11505 return NGTCP2_ERR_REQUIRED_TRANSPORT_PARAM;
11506 }
11507
11508 /* Assume that ngtcp2_transport_params_decode sets default value if
11509 active_connection_id_limit is omitted. */
11510 if (params->active_connection_id_limit <
11511 NGTCP2_DEFAULT_ACTIVE_CONNECTION_ID_LIMIT) {
11512 return NGTCP2_ERR_TRANSPORT_PARAM;
11513 }
11514
11515 /* We assume that conn->dcid.current.cid is still the initial one.
11516 This requires that transport parameter must be fed into
11517 ngtcp2_conn as early as possible. */
11518 if (!ngtcp2_cid_eq(&conn->dcid.current.cid, &params->initial_scid)) {
11519 return NGTCP2_ERR_TRANSPORT_PARAM;
11520 }
11521
11522 if (params->max_udp_payload_size < NGTCP2_MAX_UDP_PAYLOAD_SIZE) {
11523 return NGTCP2_ERR_TRANSPORT_PARAM;
11524 }
11525
11526 if (conn->server) {
11527 if (params->original_dcid_present ||
11528 params->stateless_reset_token_present ||
11529 params->preferred_addr_present || params->retry_scid_present) {
11530 return NGTCP2_ERR_TRANSPORT_PARAM;
11531 }
11532
11533 if (params->version_info_present) {
11534 if (!vneg_available_versions_includes(
11535 params->version_info.available_versions,
11536 params->version_info.available_versionslen,
11537 params->version_info.chosen_version)) {
11538 return NGTCP2_ERR_TRANSPORT_PARAM;
11539 }
11540
11541 if (params->version_info.chosen_version != conn->client_chosen_version) {
11542 return NGTCP2_ERR_VERSION_NEGOTIATION_FAILURE;
11543 }
11544
11545 conn->negotiated_version =
11546 ngtcp2_conn_server_negotiate_version(conn, &params->version_info);
11547 if (conn->negotiated_version != conn->client_chosen_version) {
11548 rv = conn_call_version_negotiation(conn, conn->negotiated_version,
11549 &conn->rcid);
11550 if (rv != 0) {
11551 return rv;
11552 }
11553 }
11554 } else {
11555 conn->negotiated_version = conn->client_chosen_version;
11556 }
11557
11558 conn->local.transport_params.version_info.chosen_version =
11559 conn->negotiated_version;
11560
11561 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON,
11562 "the negotiated version is 0x%08x",
11563 conn->negotiated_version);
11564 } else {
11565 rv = conn_client_validate_transport_params(conn, params);
11566 if (rv != 0) {
11567 return rv;
11568 }
11569 }
11570
11571 ngtcp2_log_remote_tp(&conn->log, params);
11572
11573 ngtcp2_qlog_parameters_set_transport_params(&conn->qlog, params, conn->server,
11574 NGTCP2_QLOG_SIDE_REMOTE);
11575
11576 if ((conn->server && conn->pktns.crypto.tx.ckm) ||
11577 (!conn->server && conn->pktns.crypto.rx.ckm)) {
11578 ngtcp2_transport_params_del(conn->remote.transport_params, conn->mem);
11579 conn->remote.transport_params = NULL;
11580
11581 rv = ngtcp2_transport_params_copy_new(&conn->remote.transport_params,
11582 params, conn->mem);
11583 if (rv != 0) {
11584 return rv;
11585 }
11586 conn_sync_stream_id_limit(conn);
11587 conn->tx.max_offset = conn->remote.transport_params->initial_max_data;
11588 } else {
11589 assert(!conn->remote.pending_transport_params);
11590
11591 rv = ngtcp2_transport_params_copy_new(
11592 &conn->remote.pending_transport_params, params, conn->mem);
11593 if (rv != 0) {
11594 return rv;
11595 }
11596 }
11597
11598 conn->flags |= NGTCP2_CONN_FLAG_TRANSPORT_PARAM_RECVED;
11599
11600 return 0;
11601 }
11602
11603 int ngtcp2_conn_decode_and_set_remote_transport_params(ngtcp2_conn *conn,
11604 const uint8_t *data,
11605 size_t datalen) {
11606 ngtcp2_transport_params params;
11607 int rv;
11608
11609 rv = ngtcp2_transport_params_decode(&params, data, datalen);
11610 if (rv != 0) {
11611 return rv;
11612 }
11613
11614 return ngtcp2_conn_set_remote_transport_params(conn, &params);
11615 }
11616
11617 const ngtcp2_transport_params *
11618 ngtcp2_conn_get_remote_transport_params(ngtcp2_conn *conn) {
11619 if (conn->remote.pending_transport_params) {
11620 return conn->remote.pending_transport_params;
11621 }
11622
11623 return conn->remote.transport_params;
11624 }
11625
11626 ngtcp2_ssize ngtcp2_conn_encode_0rtt_transport_params(ngtcp2_conn *conn,
11627 uint8_t *dest,
11628 size_t destlen) {
11629 ngtcp2_transport_params params, *src;
11630
11631 if (conn->server) {
11632 src = &conn->local.transport_params;
11633 } else {
11634 assert(conn->remote.transport_params);
11635
11636 src = conn->remote.transport_params;
11637 }
11638
11639 ngtcp2_transport_params_default(&params);
11640
11641 params.initial_max_streams_bidi = src->initial_max_streams_bidi;
11642 params.initial_max_streams_uni = src->initial_max_streams_uni;
11643 params.initial_max_stream_data_bidi_local =
11644 src->initial_max_stream_data_bidi_local;
11645 params.initial_max_stream_data_bidi_remote =
11646 src->initial_max_stream_data_bidi_remote;
11647 params.initial_max_stream_data_uni = src->initial_max_stream_data_uni;
11648 params.initial_max_data = src->initial_max_data;
11649 params.active_connection_id_limit = src->active_connection_id_limit;
11650 params.max_datagram_frame_size = src->max_datagram_frame_size;
11651
11652 if (conn->server) {
11653 params.max_idle_timeout = src->max_idle_timeout;
11654 params.max_udp_payload_size = src->max_udp_payload_size;
11655 params.disable_active_migration = src->disable_active_migration;
11656 }
11657
11658 return ngtcp2_transport_params_encode(dest, destlen, &params);
11659 }
11660
11661 int ngtcp2_conn_decode_and_set_0rtt_transport_params(ngtcp2_conn *conn,
11662 const uint8_t *data,
11663 size_t datalen) {
11664 ngtcp2_transport_params params;
11665 int rv;
11666
11667 rv = ngtcp2_transport_params_decode(&params, data, datalen);
11668 if (rv != 0) {
11669 return rv;
11670 }
11671
11672 return ngtcp2_conn_set_0rtt_remote_transport_params(conn, &params);
11673 }
11674
11675 int ngtcp2_conn_set_0rtt_remote_transport_params(
11676 ngtcp2_conn *conn, const ngtcp2_transport_params *params) {
11677 ngtcp2_transport_params *p;
11678
11679 assert(!conn->server);
11680 assert(!conn->remote.transport_params);
11681
11682 /* Assume that all pointer fields in p are NULL */
11683 p = ngtcp2_mem_calloc(conn->mem, 1, sizeof(*p));
11684 if (p == NULL) {
11685 return NGTCP2_ERR_NOMEM;
11686 }
11687
11688 conn->remote.transport_params = p;
11689
11690 ngtcp2_transport_params_default(conn->remote.transport_params);
11691
11692 p->initial_max_streams_bidi = params->initial_max_streams_bidi;
11693 p->initial_max_streams_uni = params->initial_max_streams_uni;
11694 p->initial_max_stream_data_bidi_local =
11695 params->initial_max_stream_data_bidi_local;
11696 p->initial_max_stream_data_bidi_remote =
11697 params->initial_max_stream_data_bidi_remote;
11698 p->initial_max_stream_data_uni = params->initial_max_stream_data_uni;
11699 p->initial_max_data = params->initial_max_data;
11700 /* we might hit garbage, then set the sane default. */
11701 p->active_connection_id_limit =
11702 ngtcp2_max_uint64(NGTCP2_DEFAULT_ACTIVE_CONNECTION_ID_LIMIT,
11703 params->active_connection_id_limit);
11704 p->max_datagram_frame_size = params->max_datagram_frame_size;
11705
11706 /* we might hit garbage, then set the sane default. */
11707 if (params->max_udp_payload_size) {
11708 p->max_udp_payload_size = ngtcp2_max_uint64(NGTCP2_MAX_UDP_PAYLOAD_SIZE,
11709 params->max_udp_payload_size);
11710 }
11711
11712 /* These parameters are treated specially. If server accepts early
11713 data, it must not set values for these parameters that are
11714 smaller than these remembered values. */
11715 conn->early.transport_params = (ngtcp2_early_transport_params){
11716 .initial_max_streams_bidi = params->initial_max_streams_bidi,
11717 .initial_max_streams_uni = params->initial_max_streams_uni,
11718 .initial_max_stream_data_bidi_local =
11719 params->initial_max_stream_data_bidi_local,
11720 .initial_max_stream_data_bidi_remote =
11721 params->initial_max_stream_data_bidi_remote,
11722 .initial_max_stream_data_uni = params->initial_max_stream_data_uni,
11723 .initial_max_data = params->initial_max_data,
11724 .active_connection_id_limit = params->active_connection_id_limit,
11725 .max_datagram_frame_size = params->max_datagram_frame_size,
11726 };
11727
11728 conn_sync_stream_id_limit(conn);
11729
11730 conn->tx.max_offset = p->initial_max_data;
11731
11732 ngtcp2_qlog_parameters_set_transport_params(&conn->qlog, p, conn->server,
11733 NGTCP2_QLOG_SIDE_REMOTE);
11734
11735 return 0;
11736 }
11737
11738 int ngtcp2_conn_set_local_transport_params_versioned(
11739 ngtcp2_conn *conn, int transport_params_version,
11740 const ngtcp2_transport_params *params) {
11741 ngtcp2_transport_params paramsbuf;
11742
11743 params = ngtcp2_transport_params_convert_to_latest(
11744 &paramsbuf, transport_params_version, params);
11745
11746 assert(conn->server);
11747 assert(params->active_connection_id_limit >=
11748 NGTCP2_DEFAULT_ACTIVE_CONNECTION_ID_LIMIT);
11749 assert(params->active_connection_id_limit <=
11750 NGTCP2_DCIDTR_MAX_UNUSED_DCID_SIZE);
11751
11752 if (conn->hs_pktns == NULL || conn->hs_pktns->crypto.tx.ckm) {
11753 return NGTCP2_ERR_INVALID_STATE;
11754 }
11755
11756 conn_set_local_transport_params(conn, params);
11757
11758 return 0;
11759 }
11760
11761 int ngtcp2_conn_commit_local_transport_params(ngtcp2_conn *conn) {
11762 const ngtcp2_mem *mem = conn->mem;
11763 ngtcp2_transport_params *params = &conn->local.transport_params;
11764 ngtcp2_scid *scident;
11765 int rv;
11766
11767 assert(1 == ngtcp2_ksl_len(&conn->scid.set));
11768
11769 params->initial_scid = conn->oscid;
11770 params->initial_scid_present = 1;
11771
11772 if (conn->oscid.datalen == 0) {
11773 params->preferred_addr_present = 0;
11774 }
11775
11776 if (conn->server && params->preferred_addr_present) {
11777 scident = ngtcp2_mem_malloc(mem, sizeof(*scident));
11778 if (scident == NULL) {
11779 return NGTCP2_ERR_NOMEM;
11780 }
11781
11782 ngtcp2_scid_init(scident, 1, &params->preferred_addr.cid);
11783
11784 rv = ngtcp2_ksl_insert(&conn->scid.set, NULL, &scident->cid, scident);
11785 if (rv != 0) {
11786 ngtcp2_mem_free(mem, scident);
11787 return rv;
11788 }
11789
11790 conn->scid.last_seq = 1;
11791 }
11792
11793 conn->rx.window = conn->rx.unsent_max_offset = conn->rx.max_offset =
11794 params->initial_max_data;
11795 conn->remote.bidi.unsent_max_streams = params->initial_max_streams_bidi;
11796 conn->remote.bidi.max_streams = params->initial_max_streams_bidi;
11797 conn->remote.uni.unsent_max_streams = params->initial_max_streams_uni;
11798 conn->remote.uni.max_streams = params->initial_max_streams_uni;
11799
11800 conn->flags |= NGTCP2_CONN_FLAG_LOCAL_TRANSPORT_PARAMS_COMMITTED;
11801
11802 ngtcp2_qlog_parameters_set_transport_params(&conn->qlog, params, conn->server,
11803 NGTCP2_QLOG_SIDE_LOCAL);
11804
11805 return 0;
11806 }
11807
11808 const ngtcp2_transport_params *
11809 ngtcp2_conn_get_local_transport_params(ngtcp2_conn *conn) {
11810 return &conn->local.transport_params;
11811 }
11812
11813 ngtcp2_ssize ngtcp2_conn_encode_local_transport_params(ngtcp2_conn *conn,
11814 uint8_t *dest,
11815 size_t destlen) {
11816 return ngtcp2_transport_params_encode(dest, destlen,
11817 &conn->local.transport_params);
11818 }
11819
11820 int ngtcp2_conn_open_bidi_stream(ngtcp2_conn *conn, int64_t *pstream_id,
11821 void *stream_user_data) {
11822 int rv;
11823 ngtcp2_strm *strm;
11824
11825 if (ngtcp2_conn_get_streams_bidi_left(conn) == 0) {
11826 return NGTCP2_ERR_STREAM_ID_BLOCKED;
11827 }
11828
11829 strm = ngtcp2_objalloc_strm_get(&conn->strm_objalloc);
11830 if (strm == NULL) {
11831 return NGTCP2_ERR_NOMEM;
11832 }
11833
11834 rv = ngtcp2_conn_init_stream(conn, strm, conn->local.bidi.next_stream_id,
11835 stream_user_data);
11836 if (rv != 0) {
11837 ngtcp2_objalloc_strm_release(&conn->strm_objalloc, strm);
11838 return rv;
11839 }
11840
11841 *pstream_id = conn->local.bidi.next_stream_id;
11842 conn->local.bidi.next_stream_id += 4;
11843
11844 return 0;
11845 }
11846
11847 int ngtcp2_conn_open_uni_stream(ngtcp2_conn *conn, int64_t *pstream_id,
11848 void *stream_user_data) {
11849 int rv;
11850 ngtcp2_strm *strm;
11851
11852 if (ngtcp2_conn_get_streams_uni_left(conn) == 0) {
11853 return NGTCP2_ERR_STREAM_ID_BLOCKED;
11854 }
11855
11856 strm = ngtcp2_objalloc_strm_get(&conn->strm_objalloc);
11857 if (strm == NULL) {
11858 return NGTCP2_ERR_NOMEM;
11859 }
11860
11861 rv = ngtcp2_conn_init_stream(conn, strm, conn->local.uni.next_stream_id,
11862 stream_user_data);
11863 if (rv != 0) {
11864 ngtcp2_objalloc_strm_release(&conn->strm_objalloc, strm);
11865 return rv;
11866 }
11867 ngtcp2_strm_shutdown(strm, NGTCP2_STRM_FLAG_SHUT_RD);
11868
11869 *pstream_id = conn->local.uni.next_stream_id;
11870 conn->local.uni.next_stream_id += 4;
11871
11872 return 0;
11873 }
11874
11875 ngtcp2_strm *ngtcp2_conn_find_stream(ngtcp2_conn *conn, int64_t stream_id) {
11876 return ngtcp2_map_find(&conn->strms, (uint64_t)stream_id);
11877 }
11878
11879 ngtcp2_ssize ngtcp2_conn_write_stream_versioned(
11880 ngtcp2_conn *conn, ngtcp2_path *path, int pkt_info_version,
11881 ngtcp2_pkt_info *pi, uint8_t *dest, size_t destlen, ngtcp2_ssize *pdatalen,
11882 uint32_t flags, int64_t stream_id, const uint8_t *data, size_t datalen,
11883 ngtcp2_tstamp ts) {
11884 ngtcp2_vec datav, *v;
11885 size_t datacnt;
11886
11887 if (datalen == 0) {
11888 v = NULL;
11889 datacnt = 0;
11890 } else {
11891 datav.len = datalen;
11892 datav.base = (uint8_t *)data;
11893 v = &datav;
11894 datacnt = 1;
11895 }
11896
11897 return ngtcp2_conn_writev_stream_versioned(conn, path, pkt_info_version, pi,
11898 dest, destlen, pdatalen, flags,
11899 stream_id, v, datacnt, ts);
11900 }
11901
11902 static ngtcp2_ssize
11903 conn_write_vmsg_wrapper(ngtcp2_conn *conn, ngtcp2_path *path,
11904 int pkt_info_version, ngtcp2_pkt_info *pi,
11905 uint8_t *dest, size_t destlen, uint8_t wflags,
11906 ngtcp2_vmsg *vmsg, ngtcp2_tstamp ts) {
11907 ngtcp2_conn_stat *cstat = &conn->cstat;
11908 ngtcp2_ssize nwrite;
11909
11910 nwrite = ngtcp2_conn_write_vmsg(conn, path, pkt_info_version, pi, dest,
11911 destlen, wflags, vmsg, ts);
11912 if (nwrite < 0) {
11913 return nwrite;
11914 }
11915
11916 if (cstat->bytes_in_flight >= cstat->cwnd) {
11917 conn->rst.is_cwnd_limited = 1;
11918 } else if ((cstat->cwnd >= cstat->ssthresh ||
11919 cstat->bytes_in_flight * 2 < cstat->cwnd) &&
11920 nwrite == 0 && conn_pacing_pkt_tx_allowed(conn, ts) &&
11921 (conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_COMPLETED) &&
11922 /* Because NGTCP2_CONN_FLAG_AGGREGATE_PKTS is set after a
11923 packet is produced, if it is set, we are sure that we
11924 are not app-limited. */
11925 !(conn->flags & NGTCP2_CONN_FLAG_AGGREGATE_PKTS)) {
11926 conn->rst.app_limited =
11927 ngtcp2_max_uint64(conn->rst.delivered + cstat->bytes_in_flight, 1);
11928 }
11929
11930 return nwrite;
11931 }
11932
11933 ngtcp2_ssize ngtcp2_conn_writev_stream_versioned(
11934 ngtcp2_conn *conn, ngtcp2_path *path, int pkt_info_version,
11935 ngtcp2_pkt_info *pi, uint8_t *dest, size_t destlen, ngtcp2_ssize *pdatalen,
11936 uint32_t flags, int64_t stream_id, const ngtcp2_vec *datav, size_t datavcnt,
11937 ngtcp2_tstamp ts) {
11938 ngtcp2_vmsg vmsg, *pvmsg;
11939 ngtcp2_strm *strm;
11940 int64_t datalen;
11941 uint8_t wflags;
11942
11943 if (pdatalen) {
11944 *pdatalen = -1;
11945 }
11946
11947 if (stream_id != -1) {
11948 strm = ngtcp2_conn_find_stream(conn, stream_id);
11949 if (strm == NULL) {
11950 return NGTCP2_ERR_STREAM_NOT_FOUND;
11951 }
11952
11953 if (strm->flags & NGTCP2_STRM_FLAG_SHUT_WR) {
11954 return NGTCP2_ERR_STREAM_SHUT_WR;
11955 }
11956
11957 datalen = ngtcp2_vec_len_varint(datav, datavcnt);
11958 if (datalen == -1) {
11959 return NGTCP2_ERR_INVALID_ARGUMENT;
11960 }
11961
11962 if (datalen == 0 && !(flags & NGTCP2_WRITE_STREAM_FLAG_FIN) &&
11963 (strm->flags & NGTCP2_STRM_FLAG_ANY_SENT)) {
11964 pvmsg = NULL;
11965 } else {
11966 if ((uint64_t)datalen > NGTCP2_MAX_VARINT - strm->tx.offset ||
11967 (uint64_t)datalen > NGTCP2_MAX_VARINT - conn->tx.offset) {
11968 return NGTCP2_ERR_INVALID_ARGUMENT;
11969 }
11970
11971 vmsg = (ngtcp2_vmsg){
11972 .type = NGTCP2_VMSG_TYPE_STREAM,
11973 .stream =
11974 {
11975 .strm = strm,
11976 .data = datav,
11977 .datacnt = datavcnt,
11978 .pdatalen = pdatalen,
11979 .flags = flags,
11980 },
11981 };
11982
11983 pvmsg = &vmsg;
11984 }
11985 } else {
11986 pvmsg = NULL;
11987 }
11988
11989 if (flags & NGTCP2_WRITE_STREAM_FLAG_PADDING) {
11990 wflags = NGTCP2_WRITE_PKT_FLAG_PADDING_IF_NOT_EMPTY;
11991 } else {
11992 wflags = NGTCP2_WRITE_PKT_FLAG_NONE;
11993 }
11994
11995 return conn_write_vmsg_wrapper(conn, path, pkt_info_version, pi, dest,
11996 destlen, wflags, pvmsg, ts);
11997 }
11998
11999 ngtcp2_ssize ngtcp2_conn_write_datagram_versioned(
12000 ngtcp2_conn *conn, ngtcp2_path *path, int pkt_info_version,
12001 ngtcp2_pkt_info *pi, uint8_t *dest, size_t destlen, int *paccepted,
12002 uint32_t flags, uint64_t dgram_id, const uint8_t *data, size_t datalen,
12003 ngtcp2_tstamp ts) {
12004 ngtcp2_vec datav, *v;
12005 size_t datacnt;
12006
12007 if (datalen == 0) {
12008 v = NULL;
12009 datacnt = 0;
12010 } else {
12011 datav.len = datalen;
12012 datav.base = (uint8_t *)data;
12013 v = &datav;
12014 datacnt = 1;
12015 }
12016
12017 return ngtcp2_conn_writev_datagram_versioned(conn, path, pkt_info_version, pi,
12018 dest, destlen, paccepted, flags,
12019 dgram_id, v, datacnt, ts);
12020 }
12021
12022 ngtcp2_ssize ngtcp2_conn_writev_datagram_versioned(
12023 ngtcp2_conn *conn, ngtcp2_path *path, int pkt_info_version,
12024 ngtcp2_pkt_info *pi, uint8_t *dest, size_t destlen, int *paccepted,
12025 uint32_t flags, uint64_t dgram_id, const ngtcp2_vec *datav, size_t datavcnt,
12026 ngtcp2_tstamp ts) {
12027 ngtcp2_vmsg vmsg;
12028 int64_t datalen;
12029 uint8_t wflags;
12030
12031 if (paccepted) {
12032 *paccepted = 0;
12033 }
12034
12035 if (conn->remote.transport_params == NULL ||
12036 conn->remote.transport_params->max_datagram_frame_size == 0) {
12037 return NGTCP2_ERR_INVALID_STATE;
12038 }
12039
12040 datalen = ngtcp2_vec_len_varint(datav, datavcnt);
12041 if (datalen == -1
12042 #if SIZE_MAX < UINT64_MAX
12043 || (uint64_t)datalen > SIZE_MAX
12044 #endif /* SIZE_MAX < UINT64_MAX */
12045 ) {
12046 return NGTCP2_ERR_INVALID_ARGUMENT;
12047 }
12048
12049 if (conn->remote.transport_params->max_datagram_frame_size <
12050 ngtcp2_pkt_datagram_framelen((size_t)datalen)) {
12051 return NGTCP2_ERR_INVALID_ARGUMENT;
12052 }
12053
12054 vmsg = (ngtcp2_vmsg){
12055 .type = NGTCP2_VMSG_TYPE_DATAGRAM,
12056 .datagram =
12057 {
12058 .data = datav,
12059 .datacnt = datavcnt,
12060 .dgram_id = dgram_id,
12061 .paccepted = paccepted,
12062 .flags = flags,
12063 },
12064 };
12065
12066 if (flags & NGTCP2_WRITE_DATAGRAM_FLAG_PADDING) {
12067 wflags = NGTCP2_WRITE_PKT_FLAG_PADDING_IF_NOT_EMPTY;
12068 } else {
12069 wflags = NGTCP2_WRITE_PKT_FLAG_NONE;
12070 }
12071
12072 return conn_write_vmsg_wrapper(conn, path, pkt_info_version, pi, dest,
12073 destlen, wflags, &vmsg, ts);
12074 }
12075
12076 ngtcp2_ssize ngtcp2_conn_write_vmsg(ngtcp2_conn *conn, ngtcp2_path *path,
12077 int pkt_info_version, ngtcp2_pkt_info *pi,
12078 uint8_t *dest, size_t destlen,
12079 uint8_t wflags, ngtcp2_vmsg *vmsg,
12080 ngtcp2_tstamp ts) {
12081 ngtcp2_ssize nwrite;
12082 size_t origlen;
12083 size_t origdestlen = destlen;
12084 int rv;
12085 int ppe_pending = (conn->flags & NGTCP2_CONN_FLAG_PPE_PENDING) != 0;
12086 ngtcp2_conn_stat *cstat = &conn->cstat;
12087 ngtcp2_ssize res = 0;
12088 uint64_t server_tx_left;
12089 int64_t prev_in_pkt_num = -1;
12090 ngtcp2_ksl_it it;
12091 ngtcp2_rtb_entry *rtbent;
12092 (void)pkt_info_version;
12093
12094 conn_update_timestamp(conn, ts);
12095
12096 if (path) {
12097 ngtcp2_path_copy(path, &conn->dcid.current.ps.path);
12098 }
12099
12100 origlen = destlen =
12101 conn_shape_udp_payload(conn, &conn->dcid.current, destlen);
12102
12103 if (!ppe_pending && pi) {
12104 pi->ecn = NGTCP2_ECN_NOT_ECT;
12105 }
12106
12107 switch (conn->state) {
12108 case NGTCP2_CS_CLIENT_INITIAL:
12109 case NGTCP2_CS_CLIENT_WAIT_HANDSHAKE:
12110 if (!conn_pacing_pkt_tx_allowed(conn, ts)) {
12111 assert(!ppe_pending);
12112
12113 return conn_write_handshake_ack_pkts(conn, pi, dest, origlen, ts);
12114 }
12115
12116 nwrite =
12117 conn_client_write_handshake(conn, pi, dest, destlen, wflags, vmsg, ts);
12118 /* We might be unable to write a packet because of depletion of
12119 congestion window budget, perhaps due to packet loss that
12120 shrinks the window drastically. Then continue if we are in
12121 post-handshake. There, we might be able to write packets
12122 exceeding CWND to avoid deadlock. */
12123 if (nwrite < 0) {
12124 return nwrite;
12125 }
12126 if (conn->state != NGTCP2_CS_POST_HANDSHAKE) {
12127 return nwrite;
12128 }
12129
12130 if (nwrite) {
12131 assert(dest[0] & NGTCP2_HEADER_FORM_BIT);
12132 assert(conn->negotiated_version);
12133
12134 if (ngtcp2_pkt_get_type_long(conn->negotiated_version, dest[0]) ==
12135 NGTCP2_PKT_INITIAL) {
12136 wflags |= NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING;
12137 }
12138
12139 res = nwrite;
12140 dest += nwrite;
12141 destlen -= (size_t)nwrite;
12142 }
12143 /* Break here so that we can coalesces 1RTT packet. */
12144 break;
12145 case NGTCP2_CS_SERVER_INITIAL:
12146 case NGTCP2_CS_SERVER_WAIT_HANDSHAKE:
12147 if (!conn_pacing_pkt_tx_allowed(conn, ts)) {
12148 assert(!ppe_pending);
12149
12150 if (!(conn->dcid.current.flags & NGTCP2_DCID_FLAG_PATH_VALIDATED)) {
12151 server_tx_left = conn_server_tx_left(conn, &conn->dcid.current);
12152 if (server_tx_left == 0) {
12153 return 0;
12154 }
12155
12156 origlen = (size_t)ngtcp2_min_uint64((uint64_t)origlen, server_tx_left);
12157 }
12158
12159 return conn_write_handshake_ack_pkts(conn, pi, dest, origlen, ts);
12160 }
12161
12162 if (!ppe_pending) {
12163 if (!(conn->dcid.current.flags & NGTCP2_DCID_FLAG_PATH_VALIDATED)) {
12164 server_tx_left = conn_server_tx_left(conn, &conn->dcid.current);
12165 if (server_tx_left == 0) {
12166 if (cstat->loss_detection_timer != UINT64_MAX) {
12167 ngtcp2_log_info(
12168 &conn->log, NGTCP2_LOG_EVENT_LDC,
12169 "loss detection timer canceled due to amplification limit");
12170 ngtcp2_conn_cancel_loss_detection_timer(conn);
12171 }
12172
12173 return 0;
12174 }
12175
12176 destlen = (size_t)ngtcp2_min_uint64((uint64_t)destlen, server_tx_left);
12177 }
12178
12179 if (conn->in_pktns) {
12180 it = ngtcp2_rtb_head(&conn->in_pktns->rtb);
12181 if (!ngtcp2_ksl_it_end(&it)) {
12182 rtbent = ngtcp2_ksl_it_get(&it);
12183 prev_in_pkt_num = rtbent->hd.pkt_num;
12184 }
12185 }
12186
12187 nwrite = conn_write_handshake(conn, pi, dest, destlen, wflags,
12188 /* write_datalen = */ 0, ts);
12189 if (nwrite < 0) {
12190 return nwrite;
12191 }
12192
12193 res = nwrite;
12194 dest += nwrite;
12195 destlen -= (size_t)nwrite;
12196
12197 if (conn->in_pktns && nwrite > 0) {
12198 it = ngtcp2_rtb_head(&conn->in_pktns->rtb);
12199 if (!ngtcp2_ksl_it_end(&it)) {
12200 rtbent = ngtcp2_ksl_it_get(&it);
12201 if (rtbent->hd.pkt_num != prev_in_pkt_num &&
12202 (rtbent->flags & NGTCP2_RTB_ENTRY_FLAG_ACK_ELICITING)) {
12203 wflags |= NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING;
12204 }
12205 }
12206 }
12207 }
12208 if (conn->pktns.crypto.tx.ckm == NULL) {
12209 return res;
12210 }
12211 break;
12212 case NGTCP2_CS_POST_HANDSHAKE:
12213 if (!conn_pacing_pkt_tx_allowed(conn, ts)) {
12214 assert(!ppe_pending);
12215
12216 if (conn->server &&
12217 !(conn->dcid.current.flags & NGTCP2_DCID_FLAG_PATH_VALIDATED)) {
12218 server_tx_left = conn_server_tx_left(conn, &conn->dcid.current);
12219 if (server_tx_left == 0) {
12220 return 0;
12221 }
12222
12223 origlen = (size_t)ngtcp2_min_uint64((uint64_t)origlen, server_tx_left);
12224 }
12225
12226 return conn_write_ack_pkt(conn, pi, dest, origlen, NGTCP2_PKT_1RTT, ts);
12227 }
12228
12229 break;
12230 case NGTCP2_CS_CLOSING:
12231 return NGTCP2_ERR_CLOSING;
12232 case NGTCP2_CS_DRAINING:
12233 return NGTCP2_ERR_DRAINING;
12234 default:
12235 return 0;
12236 }
12237
12238 assert(conn->pktns.crypto.tx.ckm);
12239
12240 if (conn_check_pkt_num_exhausted(conn)) {
12241 return NGTCP2_ERR_PKT_NUM_EXHAUSTED;
12242 }
12243
12244 if (vmsg) {
12245 switch (vmsg->type) {
12246 case NGTCP2_VMSG_TYPE_STREAM:
12247 if (vmsg->stream.flags & NGTCP2_WRITE_STREAM_FLAG_MORE) {
12248 wflags |= NGTCP2_WRITE_PKT_FLAG_MORE;
12249 }
12250 break;
12251 case NGTCP2_VMSG_TYPE_DATAGRAM:
12252 if (vmsg->datagram.flags & NGTCP2_WRITE_DATAGRAM_FLAG_MORE) {
12253 wflags |= NGTCP2_WRITE_PKT_FLAG_MORE;
12254 }
12255 break;
12256 default:
12257 break;
12258 }
12259 }
12260
12261 if (ppe_pending) {
12262 res = conn->pkt.hs_spktlen;
12263 /* dest and destlen have already been adjusted in ppe in the first
12264 run. They are adjusted for probe packet later. */
12265 nwrite = conn_write_pkt(conn, pi, dest, destlen, (size_t)res, vmsg,
12266 NGTCP2_PKT_1RTT, wflags, ts);
12267 goto fin;
12268 } else {
12269 conn->pkt.require_padding =
12270 (wflags & NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING);
12271
12272 if (conn->state == NGTCP2_CS_POST_HANDSHAKE) {
12273 rv = conn_prepare_key_update(conn, ts);
12274 if (rv != 0) {
12275 return rv;
12276 }
12277 }
12278
12279 if (!conn->pktns.rtb.probe_pkt_left && conn_cwnd_is_zero(conn)) {
12280 destlen = 0;
12281 } else {
12282 if (res == 0 && !(conn->flags & NGTCP2_CONN_FLAG_AGGREGATE_PKTS)) {
12283 nwrite =
12284 conn_write_path_response(conn, path, pi, dest, origdestlen, ts);
12285 if (nwrite) {
12286 goto fin;
12287 }
12288
12289 if (conn->pv) {
12290 nwrite =
12291 conn_write_path_challenge(conn, path, pi, dest, origdestlen, ts);
12292 if (nwrite) {
12293 goto fin;
12294 }
12295 }
12296
12297 if (conn->pmtud &&
12298 (conn->dcid.current.flags & NGTCP2_DCID_FLAG_PATH_VALIDATED) &&
12299 (!conn->hs_pktns ||
12300 ngtcp2_strm_streamfrq_empty(&conn->hs_pktns->crypto.strm))) {
12301 nwrite = conn_write_pmtud_probe(conn, pi, dest, origdestlen, ts);
12302 if (nwrite) {
12303 goto fin;
12304 }
12305 }
12306 }
12307 }
12308
12309 if (conn->server &&
12310 !(conn->dcid.current.flags & NGTCP2_DCID_FLAG_PATH_VALIDATED)) {
12311 server_tx_left = conn_server_tx_left(conn, &conn->dcid.current);
12312 origlen = (size_t)ngtcp2_min_uint64((uint64_t)origlen, server_tx_left);
12313 destlen = (size_t)ngtcp2_min_uint64((uint64_t)destlen, server_tx_left);
12314
12315 if (server_tx_left == 0 &&
12316 conn->cstat.loss_detection_timer != UINT64_MAX) {
12317 ngtcp2_log_info(
12318 &conn->log, NGTCP2_LOG_EVENT_LDC,
12319 "loss detection timer canceled due to amplification limit");
12320 ngtcp2_conn_cancel_loss_detection_timer(conn);
12321 }
12322 }
12323 }
12324
12325 if (res == 0) {
12326 if (conn_handshake_remnants_left(conn)) {
12327 if (conn_handshake_probe_left(conn) ||
12328 /* Allow exceeding CWND if an Handshake packet needs to be
12329 sent in order to avoid dead lock. In some situation,
12330 typically for client, 1 RTT packets may occupy in-flight
12331 bytes (e.g., some large requests and PMTUD), and
12332 Handshake packet loss shrinks CWND, and we may get in the
12333 situation that we are unable to send Handshake packet. */
12334 (conn->hs_pktns->rtb.num_pto_eliciting == 0 &&
12335 !ngtcp2_strm_streamfrq_empty(&conn->hs_pktns->crypto.strm))) {
12336 destlen = origlen;
12337 }
12338 nwrite = conn_write_handshake_pkts(conn, pi, dest, destlen,
12339 /* write_datalen = */ 0, ts);
12340 if (nwrite < 0) {
12341 return nwrite;
12342 }
12343 if (nwrite > 0) {
12344 /* This makes 1RTT packet padded. If 1RTT packet is not going
12345 to be sent, packet is already padded. */
12346 if (ngtcp2_pkt_get_type_long(conn->negotiated_version, dest[0]) ==
12347 NGTCP2_PKT_INITIAL) {
12348 wflags |= NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING;
12349 }
12350
12351 res = nwrite;
12352 dest += nwrite;
12353 destlen -= (size_t)nwrite;
12354
12355 /* We only exceed CWND to avoid deadlock. Do no write 1RTT
12356 packet if CWND is depleted. */
12357 if (conn_cwnd_is_zero(conn) && conn->pktns.rtb.probe_pkt_left == 0) {
12358 goto fin;
12359 }
12360 } else if (destlen == 0) {
12361 res = conn_write_handshake_ack_pkts(conn, pi, dest, origlen, ts);
12362 if (res) {
12363 return res;
12364 }
12365 }
12366 }
12367 }
12368
12369 if (conn->pktns.rtb.probe_pkt_left) {
12370 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_CON,
12371 "transmit probe pkt left=%zu",
12372 conn->pktns.rtb.probe_pkt_left);
12373
12374 nwrite = conn_write_pkt(conn, pi, dest, destlen, (size_t)res, vmsg,
12375 NGTCP2_PKT_1RTT, wflags, ts);
12376
12377 goto fin;
12378 }
12379
12380 nwrite = conn_write_pkt(conn, pi, dest, destlen, (size_t)res, vmsg,
12381 NGTCP2_PKT_1RTT, wflags, ts);
12382 if (nwrite) {
12383 assert(nwrite != NGTCP2_ERR_NOBUF);
12384 goto fin;
12385 }
12386
12387 if (res == 0) {
12388 nwrite = conn_write_ack_pkt(conn, pi, dest, origlen, NGTCP2_PKT_1RTT, ts);
12389 }
12390
12391 fin:
12392 if (nwrite >= 0) {
12393 res += nwrite;
12394 return res;
12395 }
12396
12397 switch (nwrite) {
12398 case NGTCP2_ERR_STREAM_DATA_BLOCKED:
12399 if (!(wflags & NGTCP2_WRITE_PKT_FLAG_MORE)) {
12400 if (res) {
12401 return res;
12402 }
12403
12404 break;
12405 }
12406 /* fall through */
12407 case NGTCP2_ERR_WRITE_MORE:
12408 conn->pkt.hs_spktlen = res;
12409 break;
12410 }
12411
12412 return nwrite;
12413 }
12414
12415 static ngtcp2_ssize
12416 conn_write_connection_close(ngtcp2_conn *conn, ngtcp2_pkt_info *pi,
12417 uint8_t *dest, size_t destlen, uint8_t pkt_type,
12418 uint64_t error_code, const uint8_t *reason,
12419 size_t reasonlen, ngtcp2_tstamp ts) {
12420 ngtcp2_pktns *in_pktns = conn->in_pktns;
12421 ngtcp2_pktns *hs_pktns = conn->hs_pktns;
12422 ngtcp2_ssize res = 0, nwrite;
12423 ngtcp2_frame fr;
12424 uint8_t flags = NGTCP2_WRITE_PKT_FLAG_NONE;
12425
12426 fr.connection_close = (ngtcp2_connection_close){
12427 .type = NGTCP2_FRAME_CONNECTION_CLOSE,
12428 .error_code = error_code,
12429 .reasonlen = reasonlen,
12430 .reason = (uint8_t *)reason,
12431 };
12432
12433 if (!(conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED) &&
12434 pkt_type != NGTCP2_PKT_INITIAL) {
12435 if (in_pktns && conn->server) {
12436 nwrite = ngtcp2_conn_write_single_frame_pkt(
12437 conn, pi, dest, destlen, NGTCP2_PKT_INITIAL, NGTCP2_WRITE_PKT_FLAG_NONE,
12438 &conn->dcid.current.cid, &fr, NGTCP2_RTB_ENTRY_FLAG_NONE, NULL, ts);
12439 if (nwrite < 0) {
12440 return nwrite;
12441 }
12442
12443 dest += nwrite;
12444 destlen -= (size_t)nwrite;
12445 res += nwrite;
12446 }
12447
12448 if (pkt_type != NGTCP2_PKT_HANDSHAKE && hs_pktns &&
12449 hs_pktns->crypto.tx.ckm) {
12450 nwrite = ngtcp2_conn_write_single_frame_pkt(
12451 conn, pi, dest, destlen, NGTCP2_PKT_HANDSHAKE,
12452 NGTCP2_WRITE_PKT_FLAG_NONE, &conn->dcid.current.cid, &fr,
12453 NGTCP2_RTB_ENTRY_FLAG_NONE, NULL, ts);
12454 if (nwrite < 0) {
12455 return nwrite;
12456 }
12457
12458 dest += nwrite;
12459 destlen -= (size_t)nwrite;
12460 res += nwrite;
12461 }
12462 }
12463
12464 if (!conn->server && pkt_type == NGTCP2_PKT_INITIAL) {
12465 flags = NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING;
12466 }
12467
12468 nwrite = ngtcp2_conn_write_single_frame_pkt(
12469 conn, pi, dest, destlen, pkt_type, flags, &conn->dcid.current.cid, &fr,
12470 NGTCP2_RTB_ENTRY_FLAG_NONE, NULL, ts);
12471
12472 if (nwrite < 0) {
12473 return nwrite;
12474 }
12475
12476 res += nwrite;
12477
12478 if (res == 0) {
12479 return NGTCP2_ERR_NOBUF;
12480 }
12481
12482 return res;
12483 }
12484
12485 ngtcp2_ssize ngtcp2_conn_write_connection_close_pkt(
12486 ngtcp2_conn *conn, ngtcp2_path *path, ngtcp2_pkt_info *pi, uint8_t *dest,
12487 size_t destlen, uint64_t error_code, const uint8_t *reason, size_t reasonlen,
12488 ngtcp2_tstamp ts) {
12489 ngtcp2_pktns *in_pktns = conn->in_pktns;
12490 ngtcp2_pktns *hs_pktns = conn->hs_pktns;
12491 uint8_t pkt_type;
12492 ngtcp2_ssize nwrite;
12493 uint64_t server_tx_left;
12494
12495 if (conn_check_pkt_num_exhausted(conn)) {
12496 return NGTCP2_ERR_PKT_NUM_EXHAUSTED;
12497 }
12498
12499 switch (conn->state) {
12500 case NGTCP2_CS_CLIENT_INITIAL:
12501 return NGTCP2_ERR_INVALID_STATE;
12502 case NGTCP2_CS_CLOSING:
12503 case NGTCP2_CS_DRAINING:
12504 return 0;
12505 default:
12506 break;
12507 }
12508
12509 if (path) {
12510 ngtcp2_path_copy(path, &conn->dcid.current.ps.path);
12511 }
12512
12513 destlen = conn_shape_udp_payload(conn, &conn->dcid.current, destlen);
12514
12515 if (pi) {
12516 pi->ecn = NGTCP2_ECN_NOT_ECT;
12517 }
12518
12519 if (conn->server) {
12520 server_tx_left = conn_server_tx_left(conn, &conn->dcid.current);
12521 destlen = (size_t)ngtcp2_min_uint64((uint64_t)destlen, server_tx_left);
12522 }
12523
12524 if (conn->state == NGTCP2_CS_POST_HANDSHAKE ||
12525 (conn->server && conn->pktns.crypto.tx.ckm)) {
12526 pkt_type = NGTCP2_PKT_1RTT;
12527 } else if (hs_pktns && hs_pktns->crypto.tx.ckm) {
12528 pkt_type = NGTCP2_PKT_HANDSHAKE;
12529 } else if (in_pktns && in_pktns->crypto.tx.ckm) {
12530 pkt_type = NGTCP2_PKT_INITIAL;
12531 } else {
12532 /* This branch is taken if server has not read any Initial packet
12533 from client. */
12534 return NGTCP2_ERR_INVALID_STATE;
12535 }
12536
12537 nwrite = conn_write_connection_close(conn, pi, dest, destlen, pkt_type,
12538 error_code, reason, reasonlen, ts);
12539 if (nwrite < 0) {
12540 return nwrite;
12541 }
12542
12543 conn->state = NGTCP2_CS_CLOSING;
12544
12545 return nwrite;
12546 }
12547
12548 ngtcp2_ssize ngtcp2_conn_write_application_close_pkt(
12549 ngtcp2_conn *conn, ngtcp2_path *path, ngtcp2_pkt_info *pi, uint8_t *dest,
12550 size_t destlen, uint64_t app_error_code, const uint8_t *reason,
12551 size_t reasonlen, ngtcp2_tstamp ts) {
12552 ngtcp2_ssize nwrite;
12553 ngtcp2_ssize res = 0;
12554 ngtcp2_frame fr;
12555 uint64_t server_tx_left;
12556
12557 if (conn_check_pkt_num_exhausted(conn)) {
12558 return NGTCP2_ERR_PKT_NUM_EXHAUSTED;
12559 }
12560
12561 switch (conn->state) {
12562 case NGTCP2_CS_CLIENT_INITIAL:
12563 return NGTCP2_ERR_INVALID_STATE;
12564 case NGTCP2_CS_CLOSING:
12565 case NGTCP2_CS_DRAINING:
12566 return 0;
12567 default:
12568 break;
12569 }
12570
12571 if (path) {
12572 ngtcp2_path_copy(path, &conn->dcid.current.ps.path);
12573 }
12574
12575 destlen = conn_shape_udp_payload(conn, &conn->dcid.current, destlen);
12576
12577 if (pi) {
12578 pi->ecn = NGTCP2_ECN_NOT_ECT;
12579 }
12580
12581 if (conn->server) {
12582 server_tx_left = conn_server_tx_left(conn, &conn->dcid.current);
12583 destlen = (size_t)ngtcp2_min_uint64((uint64_t)destlen, server_tx_left);
12584 }
12585
12586 if (!(conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED)) {
12587 nwrite = conn_write_connection_close(
12588 conn, pi, dest, destlen,
12589 conn->hs_pktns->crypto.tx.ckm ? NGTCP2_PKT_HANDSHAKE : NGTCP2_PKT_INITIAL,
12590 NGTCP2_APPLICATION_ERROR, NULL, 0, ts);
12591 if (nwrite < 0) {
12592 return nwrite;
12593 }
12594 res = nwrite;
12595 dest += nwrite;
12596 destlen -= (size_t)nwrite;
12597 }
12598
12599 if (conn->state != NGTCP2_CS_POST_HANDSHAKE &&
12600 (!conn->server || !conn->pktns.crypto.tx.ckm)) {
12601 return res;
12602 }
12603
12604 assert(conn->pktns.crypto.tx.ckm);
12605
12606 fr.connection_close = (ngtcp2_connection_close){
12607 .type = NGTCP2_FRAME_CONNECTION_CLOSE_APP,
12608 .error_code = app_error_code,
12609 .reasonlen = reasonlen,
12610 .reason = (uint8_t *)reason,
12611 };
12612
12613 nwrite = ngtcp2_conn_write_single_frame_pkt(
12614 conn, pi, dest, destlen, NGTCP2_PKT_1RTT, NGTCP2_WRITE_PKT_FLAG_NONE,
12615 &conn->dcid.current.cid, &fr, NGTCP2_RTB_ENTRY_FLAG_NONE, NULL, ts);
12616
12617 if (nwrite < 0) {
12618 return nwrite;
12619 }
12620
12621 res += nwrite;
12622
12623 if (res == 0) {
12624 return NGTCP2_ERR_NOBUF;
12625 }
12626
12627 conn->state = NGTCP2_CS_CLOSING;
12628
12629 return res;
12630 }
12631
12632 static void ccerr_init(ngtcp2_ccerr *ccerr, ngtcp2_ccerr_type type,
12633 uint64_t error_code, const uint8_t *reason,
12634 size_t reasonlen) {
12635 *ccerr = (ngtcp2_ccerr){
12636 .type = type,
12637 .error_code = error_code,
12638 .reason = (uint8_t *)reason,
12639 .reasonlen = reasonlen,
12640 };
12641 }
12642
12643 void ngtcp2_ccerr_default(ngtcp2_ccerr *ccerr) {
12644 ccerr_init(ccerr, NGTCP2_CCERR_TYPE_TRANSPORT, NGTCP2_NO_ERROR, NULL, 0);
12645 }
12646
12647 void ngtcp2_ccerr_set_transport_error(ngtcp2_ccerr *ccerr, uint64_t error_code,
12648 const uint8_t *reason, size_t reasonlen) {
12649 ccerr_init(ccerr, NGTCP2_CCERR_TYPE_TRANSPORT, error_code, reason, reasonlen);
12650 }
12651
12652 void ngtcp2_ccerr_set_liberr(ngtcp2_ccerr *ccerr, int liberr,
12653 const uint8_t *reason, size_t reasonlen) {
12654 switch (liberr) {
12655 case NGTCP2_ERR_RECV_VERSION_NEGOTIATION:
12656 ccerr_init(ccerr, NGTCP2_CCERR_TYPE_VERSION_NEGOTIATION, NGTCP2_NO_ERROR,
12657 reason, reasonlen);
12658
12659 return;
12660 case NGTCP2_ERR_IDLE_CLOSE:
12661 ccerr_init(ccerr, NGTCP2_CCERR_TYPE_IDLE_CLOSE, NGTCP2_NO_ERROR, reason,
12662 reasonlen);
12663
12664 return;
12665 case NGTCP2_ERR_DROP_CONN:
12666 ccerr_init(ccerr, NGTCP2_CCERR_TYPE_DROP_CONN, NGTCP2_NO_ERROR, reason,
12667 reasonlen);
12668
12669 return;
12670 case NGTCP2_ERR_RETRY:
12671 ccerr_init(ccerr, NGTCP2_CCERR_TYPE_RETRY, NGTCP2_NO_ERROR, reason,
12672 reasonlen);
12673
12674 return;
12675 }
12676
12677 ngtcp2_ccerr_set_transport_error(
12678 ccerr, ngtcp2_err_infer_quic_transport_error_code(liberr), reason,
12679 reasonlen);
12680 }
12681
12682 void ngtcp2_ccerr_set_tls_alert(ngtcp2_ccerr *ccerr, uint8_t tls_alert,
12683 const uint8_t *reason, size_t reasonlen) {
12684 ngtcp2_ccerr_set_transport_error(ccerr, NGTCP2_CRYPTO_ERROR | tls_alert,
12685 reason, reasonlen);
12686 }
12687
12688 void ngtcp2_ccerr_set_application_error(ngtcp2_ccerr *ccerr,
12689 uint64_t error_code,
12690 const uint8_t *reason,
12691 size_t reasonlen) {
12692 ccerr_init(ccerr, NGTCP2_CCERR_TYPE_APPLICATION, error_code, reason,
12693 reasonlen);
12694 }
12695
12696 ngtcp2_ssize ngtcp2_conn_write_connection_close_versioned(
12697 ngtcp2_conn *conn, ngtcp2_path *path, int pkt_info_version,
12698 ngtcp2_pkt_info *pi, uint8_t *dest, size_t destlen, const ngtcp2_ccerr *ccerr,
12699 ngtcp2_tstamp ts) {
12700 (void)pkt_info_version;
12701
12702 conn_update_timestamp(conn, ts);
12703
12704 switch (ccerr->type) {
12705 case NGTCP2_CCERR_TYPE_TRANSPORT:
12706 return ngtcp2_conn_write_connection_close_pkt(
12707 conn, path, pi, dest, destlen, ccerr->error_code, ccerr->reason,
12708 ccerr->reasonlen, ts);
12709 case NGTCP2_CCERR_TYPE_APPLICATION:
12710 return ngtcp2_conn_write_application_close_pkt(
12711 conn, path, pi, dest, destlen, ccerr->error_code, ccerr->reason,
12712 ccerr->reasonlen, ts);
12713 default:
12714 return 0;
12715 }
12716 }
12717
12718 int ngtcp2_conn_in_closing_period(ngtcp2_conn *conn) {
12719 return conn->state == NGTCP2_CS_CLOSING;
12720 }
12721
12722 int ngtcp2_conn_in_draining_period(ngtcp2_conn *conn) {
12723 return conn->state == NGTCP2_CS_DRAINING;
12724 }
12725
12726 int ngtcp2_conn_close_stream(ngtcp2_conn *conn, ngtcp2_strm *strm) {
12727 int rv;
12728
12729 rv = conn_call_stream_close(conn, strm);
12730 if (rv != 0) {
12731 return rv;
12732 }
12733
12734 rv = ngtcp2_map_remove(&conn->strms, (ngtcp2_map_key_type)strm->stream_id);
12735 if (rv != 0) {
12736 assert(rv != NGTCP2_ERR_INVALID_ARGUMENT);
12737 return rv;
12738 }
12739
12740 if (ngtcp2_strm_is_tx_queued(strm)) {
12741 ngtcp2_pq_remove(&conn->tx.strmq, &strm->pe);
12742 }
12743
12744 ngtcp2_strm_free(strm);
12745 ngtcp2_objalloc_strm_release(&conn->strm_objalloc, strm);
12746
12747 return 0;
12748 }
12749
12750 int ngtcp2_conn_close_stream_if_shut_rdwr(ngtcp2_conn *conn,
12751 ngtcp2_strm *strm) {
12752 if ((strm->flags & NGTCP2_STRM_FLAG_SHUT_RDWR) ==
12753 NGTCP2_STRM_FLAG_SHUT_RDWR &&
12754 ((strm->flags & NGTCP2_STRM_FLAG_RESET_STREAM_RECVED) ||
12755 ngtcp2_strm_rx_offset(strm) == strm->rx.last_offset) &&
12756 (((strm->flags & NGTCP2_STRM_FLAG_RESET_STREAM) &&
12757 (strm->flags & NGTCP2_STRM_FLAG_RESET_STREAM_ACKED)) ||
12758 ngtcp2_strm_is_all_tx_data_fin_acked(strm))) {
12759 return ngtcp2_conn_close_stream(conn, strm);
12760 }
12761 return 0;
12762 }
12763
12764 /*
12765 * conn_shutdown_stream_write closes send stream with error code
12766 * |app_error_code|. RESET_STREAM frame is scheduled.
12767 *
12768 * This function returns 0 if it succeeds, or one of the following
12769 * negative error codes:
12770 *
12771 * NGTCP2_ERR_NOMEM
12772 * Out of memory.
12773 */
12774 static int conn_shutdown_stream_write(ngtcp2_conn *conn, ngtcp2_strm *strm,
12775 uint64_t app_error_code) {
12776 ngtcp2_strm_set_app_error_code(strm, app_error_code);
12777
12778 if ((strm->flags & NGTCP2_STRM_FLAG_RESET_STREAM) ||
12779 ngtcp2_strm_is_all_tx_data_fin_acked(strm)) {
12780 return 0;
12781 }
12782
12783 /* Set this flag so that we don't accidentally send DATA to this
12784 stream. */
12785 strm->flags |= NGTCP2_STRM_FLAG_SHUT_WR | NGTCP2_STRM_FLAG_RESET_STREAM;
12786
12787 ngtcp2_strm_streamfrq_clear(strm);
12788
12789 return conn_reset_stream(conn, strm, app_error_code);
12790 }
12791
12792 /*
12793 * conn_shutdown_stream_read closes read stream with error code
12794 * |app_error_code|. STOP_SENDING frame is scheduled.
12795 *
12796 * This function returns 0 if it succeeds, or one of the following
12797 * negative error codes:
12798 *
12799 * NGTCP2_ERR_NOMEM
12800 * Out of memory.
12801 */
12802 static int conn_shutdown_stream_read(ngtcp2_conn *conn, ngtcp2_strm *strm,
12803 uint64_t app_error_code) {
12804 ngtcp2_strm_set_app_error_code(strm, app_error_code);
12805
12806 if (strm->flags &
12807 (NGTCP2_STRM_FLAG_STOP_SENDING | NGTCP2_STRM_FLAG_RESET_STREAM_RECVED)) {
12808 return 0;
12809 }
12810 if ((strm->flags & NGTCP2_STRM_FLAG_SHUT_RD) &&
12811 ngtcp2_strm_rx_offset(strm) == strm->rx.last_offset) {
12812 return 0;
12813 }
12814
12815 /* Extend connection flow control window for the amount of data
12816 which are not passed to application. */
12817 if (!(strm->flags & NGTCP2_STRM_FLAG_RESET_STREAM_RECVED)) {
12818 ngtcp2_conn_extend_max_offset(conn, strm->rx.last_offset -
12819 ngtcp2_strm_rx_offset(strm));
12820 }
12821
12822 strm->flags |= NGTCP2_STRM_FLAG_STOP_SENDING;
12823
12824 ngtcp2_strm_discard_reordered_data(strm);
12825
12826 return conn_stop_sending(conn, strm, app_error_code);
12827 }
12828
12829 int ngtcp2_conn_shutdown_stream(ngtcp2_conn *conn, uint32_t flags,
12830 int64_t stream_id, uint64_t app_error_code) {
12831 int rv;
12832 ngtcp2_strm *strm;
12833 (void)flags;
12834
12835 strm = ngtcp2_conn_find_stream(conn, stream_id);
12836 if (strm == NULL) {
12837 return 0;
12838 }
12839
12840 if (bidi_stream(stream_id) || !conn_local_stream(conn, stream_id)) {
12841 rv = conn_shutdown_stream_read(conn, strm, app_error_code);
12842 if (rv != 0) {
12843 return rv;
12844 }
12845 }
12846
12847 if (bidi_stream(stream_id) || conn_local_stream(conn, stream_id)) {
12848 rv = conn_shutdown_stream_write(conn, strm, app_error_code);
12849 if (rv != 0) {
12850 return rv;
12851 }
12852 }
12853
12854 return 0;
12855 }
12856
12857 int ngtcp2_conn_shutdown_stream_write(ngtcp2_conn *conn, uint32_t flags,
12858 int64_t stream_id,
12859 uint64_t app_error_code) {
12860 ngtcp2_strm *strm;
12861 (void)flags;
12862
12863 if (!bidi_stream(stream_id) && !conn_local_stream(conn, stream_id)) {
12864 return NGTCP2_ERR_INVALID_ARGUMENT;
12865 }
12866
12867 strm = ngtcp2_conn_find_stream(conn, stream_id);
12868 if (strm == NULL) {
12869 return 0;
12870 }
12871
12872 return conn_shutdown_stream_write(conn, strm, app_error_code);
12873 }
12874
12875 int ngtcp2_conn_shutdown_stream_read(ngtcp2_conn *conn, uint32_t flags,
12876 int64_t stream_id,
12877 uint64_t app_error_code) {
12878 ngtcp2_strm *strm;
12879 (void)flags;
12880
12881 if (!bidi_stream(stream_id) && conn_local_stream(conn, stream_id)) {
12882 return NGTCP2_ERR_INVALID_ARGUMENT;
12883 }
12884
12885 strm = ngtcp2_conn_find_stream(conn, stream_id);
12886 if (strm == NULL) {
12887 return 0;
12888 }
12889
12890 return conn_shutdown_stream_read(conn, strm, app_error_code);
12891 }
12892
12893 /*
12894 * conn_extend_max_stream_offset extends stream level flow control
12895 * window by |datalen| of the stream denoted by |strm|.
12896 *
12897 * This function returns 0 if it succeeds, or one of the following
12898 * negative error codes:
12899 *
12900 * NGTCP2_ERR_NOMEM
12901 * Out of memory.
12902 */
12903 static int conn_extend_max_stream_offset(ngtcp2_conn *conn, ngtcp2_strm *strm,
12904 uint64_t datalen) {
12905 ngtcp2_strm *top;
12906
12907 if (datalen > NGTCP2_MAX_VARINT ||
12908 strm->rx.unsent_max_offset > NGTCP2_MAX_VARINT - datalen) {
12909 strm->rx.unsent_max_offset = NGTCP2_MAX_VARINT;
12910 } else {
12911 strm->rx.unsent_max_offset += datalen;
12912 }
12913
12914 if (!(strm->flags &
12915 (NGTCP2_STRM_FLAG_SHUT_RD | NGTCP2_STRM_FLAG_STOP_SENDING)) &&
12916 !ngtcp2_strm_is_tx_queued(strm) &&
12917 conn_should_send_max_stream_data(conn, strm)) {
12918 if (!ngtcp2_pq_empty(&conn->tx.strmq)) {
12919 top = ngtcp2_conn_tx_strmq_top(conn);
12920 strm->cycle = top->cycle;
12921 }
12922 strm->cycle = conn_tx_strmq_first_cycle(conn);
12923 return ngtcp2_conn_tx_strmq_push(conn, strm);
12924 }
12925
12926 return 0;
12927 }
12928
12929 int ngtcp2_conn_extend_max_stream_offset(ngtcp2_conn *conn, int64_t stream_id,
12930 uint64_t datalen) {
12931 ngtcp2_strm *strm;
12932
12933 if (!bidi_stream(stream_id) && conn_local_stream(conn, stream_id)) {
12934 return NGTCP2_ERR_INVALID_ARGUMENT;
12935 }
12936
12937 strm = ngtcp2_conn_find_stream(conn, stream_id);
12938 if (strm == NULL) {
12939 return 0;
12940 }
12941
12942 return conn_extend_max_stream_offset(conn, strm, datalen);
12943 }
12944
12945 void ngtcp2_conn_extend_max_offset(ngtcp2_conn *conn, uint64_t datalen) {
12946 if (NGTCP2_MAX_VARINT < datalen ||
12947 conn->rx.unsent_max_offset > NGTCP2_MAX_VARINT - datalen) {
12948 conn->rx.unsent_max_offset = NGTCP2_MAX_VARINT;
12949 return;
12950 }
12951
12952 conn->rx.unsent_max_offset += datalen;
12953 }
12954
12955 void ngtcp2_conn_extend_max_streams_bidi(ngtcp2_conn *conn, size_t n) {
12956 handle_max_remote_streams_extension(&conn->remote.bidi.unsent_max_streams, n);
12957 }
12958
12959 void ngtcp2_conn_extend_max_streams_uni(ngtcp2_conn *conn, size_t n) {
12960 handle_max_remote_streams_extension(&conn->remote.uni.unsent_max_streams, n);
12961 }
12962
12963 const ngtcp2_cid *ngtcp2_conn_get_dcid(ngtcp2_conn *conn) {
12964 return &conn->dcid.current.cid;
12965 }
12966
12967 const ngtcp2_cid *ngtcp2_conn_get_client_initial_dcid(ngtcp2_conn *conn) {
12968 return &conn->rcid;
12969 }
12970
12971 uint32_t ngtcp2_conn_get_client_chosen_version(ngtcp2_conn *conn) {
12972 return conn->client_chosen_version;
12973 }
12974
12975 uint32_t ngtcp2_conn_get_negotiated_version(ngtcp2_conn *conn) {
12976 return conn->negotiated_version;
12977 }
12978
12979 static int delete_strms_pq_each(void *data, void *ptr) {
12980 ngtcp2_conn *conn = ptr;
12981 ngtcp2_strm *s = data;
12982
12983 if (ngtcp2_strm_is_tx_queued(s)) {
12984 ngtcp2_pq_remove(&conn->tx.strmq, &s->pe);
12985 }
12986
12987 ngtcp2_strm_free(s);
12988 ngtcp2_objalloc_strm_release(&conn->strm_objalloc, s);
12989
12990 return 0;
12991 }
12992
12993 /*
12994 * conn_discard_early_data_state discards any connection states which
12995 * are altered by any operations during early data transfer.
12996 */
12997 static void conn_discard_early_data_state(ngtcp2_conn *conn) {
12998 ngtcp2_frame_chain **pfrc, *frc;
12999
13000 ngtcp2_rtb_remove_early_data(&conn->pktns.rtb, &conn->cstat);
13001
13002 ngtcp2_map_each(&conn->strms, delete_strms_pq_each, conn);
13003 ngtcp2_map_clear(&conn->strms);
13004
13005 conn->tx.offset = 0;
13006 conn->tx.last_blocked_offset = UINT64_MAX;
13007
13008 conn->rx.unsent_max_offset = conn->rx.max_offset =
13009 conn->local.transport_params.initial_max_data;
13010
13011 conn->remote.bidi.unsent_max_streams = conn->remote.bidi.max_streams =
13012 conn->local.transport_params.initial_max_streams_bidi;
13013
13014 conn->remote.uni.unsent_max_streams = conn->remote.uni.max_streams =
13015 conn->local.transport_params.initial_max_streams_uni;
13016
13017 if (conn->server) {
13018 conn->local.bidi.next_stream_id = 1;
13019 conn->local.uni.next_stream_id = 3;
13020 } else {
13021 conn->local.bidi.next_stream_id = 0;
13022 conn->local.uni.next_stream_id = 2;
13023 }
13024
13025 for (pfrc = &conn->pktns.tx.frq; *pfrc;) {
13026 frc = *pfrc;
13027 *pfrc = (*pfrc)->next;
13028 ngtcp2_frame_chain_objalloc_del(frc, &conn->frc_objalloc, conn->mem);
13029 }
13030 }
13031
13032 int ngtcp2_conn_tls_early_data_rejected(ngtcp2_conn *conn) {
13033 if (conn->flags & NGTCP2_CONN_FLAG_EARLY_DATA_REJECTED) {
13034 return 0;
13035 }
13036
13037 conn->flags |= NGTCP2_CONN_FLAG_EARLY_DATA_REJECTED;
13038
13039 conn_discard_early_data_state(conn);
13040
13041 if (conn->callbacks.tls_early_data_rejected) {
13042 return conn->callbacks.tls_early_data_rejected(conn, conn->user_data);
13043 }
13044
13045 if (conn->early.ckm) {
13046 conn_discard_early_key(conn);
13047 }
13048
13049 return 0;
13050 }
13051
13052 int ngtcp2_conn_get_tls_early_data_rejected(ngtcp2_conn *conn) {
13053 return (conn->flags & NGTCP2_CONN_FLAG_EARLY_DATA_REJECTED) != 0;
13054 }
13055
13056 void ngtcp2_conn_update_rtt(ngtcp2_conn *conn, ngtcp2_duration rtt,
13057 ngtcp2_duration ack_delay, ngtcp2_tstamp ts) {
13058 ngtcp2_conn_stat *cstat = &conn->cstat;
13059
13060 assert(rtt > 0);
13061
13062 if (cstat->min_rtt == UINT64_MAX) {
13063 cstat->latest_rtt = rtt;
13064 cstat->min_rtt = rtt;
13065 cstat->smoothed_rtt = rtt;
13066 cstat->rttvar = rtt / 2;
13067 cstat->first_rtt_sample_ts = ts;
13068 } else {
13069 if (conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED) {
13070 assert(conn->remote.transport_params);
13071
13072 ack_delay = ngtcp2_min_uint64(
13073 ack_delay, conn->remote.transport_params->max_ack_delay);
13074 } else if (ack_delay > 0 && rtt >= cstat->min_rtt &&
13075 rtt < cstat->min_rtt + ack_delay) {
13076 /* Ignore RTT sample if adjusting ack_delay causes the sample
13077 less than min_rtt before handshake confirmation. */
13078 ngtcp2_log_infof(
13079 &conn->log, NGTCP2_LOG_EVENT_LDC,
13080 "ignore rtt sample because ack_delay is too large latest_rtt=%" PRIu64
13081 " min_rtt=%" PRIu64 " ack_delay=%" PRIu64,
13082 rtt / NGTCP2_MILLISECONDS, cstat->min_rtt / NGTCP2_MILLISECONDS,
13083 ack_delay / NGTCP2_MILLISECONDS);
13084 return;
13085 }
13086
13087 cstat->latest_rtt = rtt;
13088 cstat->min_rtt = ngtcp2_min_uint64(cstat->min_rtt, rtt);
13089
13090 if (rtt >= cstat->min_rtt + ack_delay) {
13091 rtt -= ack_delay;
13092 }
13093
13094 cstat->rttvar = (cstat->rttvar * 3 + (cstat->smoothed_rtt < rtt
13095 ? rtt - cstat->smoothed_rtt
13096 : cstat->smoothed_rtt - rtt)) /
13097 4;
13098 cstat->smoothed_rtt = (cstat->smoothed_rtt * 7 + rtt) / 8;
13099 }
13100
13101 ngtcp2_log_infof(
13102 &conn->log, NGTCP2_LOG_EVENT_LDC,
13103 "latest_rtt=%" PRIu64 " min_rtt=%" PRIu64 " smoothed_rtt=%" PRIu64
13104 " rttvar=%" PRIu64 " ack_delay=%" PRIu64,
13105 cstat->latest_rtt / NGTCP2_MILLISECONDS,
13106 cstat->min_rtt / NGTCP2_MILLISECONDS,
13107 cstat->smoothed_rtt / NGTCP2_MILLISECONDS,
13108 cstat->rttvar / NGTCP2_MILLISECONDS, ack_delay / NGTCP2_MILLISECONDS);
13109 }
13110
13111 void ngtcp2_conn_get_conn_info_versioned(ngtcp2_conn *conn,
13112 int conn_info_version,
13113 ngtcp2_conn_info *cinfo) {
13114 ngtcp2_conn_info_init_versioned(conn_info_version, cinfo, &conn->cstat);
13115 }
13116
13117 static void conn_get_loss_time_and_pktns(ngtcp2_conn *conn,
13118 ngtcp2_tstamp *ploss_time,
13119 ngtcp2_pktns **ppktns) {
13120 ngtcp2_pktns *const ns[] = {conn->hs_pktns, &conn->pktns};
13121 ngtcp2_conn_stat *cstat = &conn->cstat;
13122 ngtcp2_duration *loss_time = cstat->loss_time + 1;
13123 ngtcp2_tstamp earliest_loss_time = cstat->loss_time[NGTCP2_PKTNS_ID_INITIAL];
13124 ngtcp2_pktns *pktns = conn->in_pktns;
13125 size_t i;
13126
13127 for (i = 0; i < ngtcp2_arraylen(ns); ++i) {
13128 if (ns[i] == NULL || loss_time[i] >= earliest_loss_time) {
13129 continue;
13130 }
13131
13132 earliest_loss_time = loss_time[i];
13133 pktns = ns[i];
13134 }
13135
13136 if (ploss_time) {
13137 *ploss_time = earliest_loss_time;
13138 }
13139 if (ppktns) {
13140 *ppktns = pktns;
13141 }
13142 }
13143
13144 static ngtcp2_tstamp conn_get_earliest_pto_expiry(ngtcp2_conn *conn,
13145 ngtcp2_tstamp ts) {
13146 ngtcp2_pktns *const ns[] = {conn->in_pktns, conn->hs_pktns, &conn->pktns};
13147 size_t i;
13148 ngtcp2_tstamp earliest_ts = UINT64_MAX, t;
13149 ngtcp2_conn_stat *cstat = &conn->cstat;
13150 ngtcp2_tstamp *times = cstat->last_tx_pkt_ts;
13151 ngtcp2_duration duration =
13152 compute_pto(cstat->smoothed_rtt, cstat->rttvar, /* max_ack_delay = */ 0) *
13153 (1ULL << cstat->pto_count);
13154
13155 for (i = NGTCP2_PKTNS_ID_INITIAL; i < NGTCP2_PKTNS_ID_MAX; ++i) {
13156 if (ns[i] == NULL || ns[i]->rtb.num_pto_eliciting == 0 ||
13157 (times[i] == UINT64_MAX ||
13158 (i == NGTCP2_PKTNS_ID_APPLICATION &&
13159 !(conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED)))) {
13160 continue;
13161 }
13162
13163 t = times[i] + duration;
13164
13165 if (i == NGTCP2_PKTNS_ID_APPLICATION) {
13166 assert(conn->remote.transport_params);
13167 t += conn->remote.transport_params->max_ack_delay *
13168 (1ULL << cstat->pto_count);
13169 }
13170
13171 if (t < earliest_ts) {
13172 earliest_ts = t;
13173 }
13174 }
13175
13176 if (earliest_ts == UINT64_MAX) {
13177 return ts + duration;
13178 }
13179
13180 return earliest_ts;
13181 }
13182
13183 void ngtcp2_conn_set_loss_detection_timer(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
13184 ngtcp2_conn_stat *cstat = &conn->cstat;
13185 ngtcp2_duration timeout;
13186 ngtcp2_pktns *in_pktns = conn->in_pktns;
13187 ngtcp2_pktns *hs_pktns = conn->hs_pktns;
13188 ngtcp2_pktns *pktns = &conn->pktns;
13189 ngtcp2_tstamp earliest_loss_time;
13190
13191 conn_get_loss_time_and_pktns(conn, &earliest_loss_time, NULL);
13192
13193 if (earliest_loss_time != UINT64_MAX) {
13194 cstat->loss_detection_timer = earliest_loss_time;
13195
13196 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_LDC,
13197 "loss_detection_timer=%" PRIu64
13198 " nonzero crypto loss time",
13199 cstat->loss_detection_timer);
13200 return;
13201 }
13202
13203 if ((!in_pktns || in_pktns->rtb.num_pto_eliciting == 0) &&
13204 (!hs_pktns || hs_pktns->rtb.num_pto_eliciting == 0) &&
13205 (pktns->rtb.num_pto_eliciting == 0 ||
13206 !(conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED)) &&
13207 (conn->server ||
13208 (conn->flags & (NGTCP2_CONN_FLAG_SERVER_ADDR_VERIFIED |
13209 NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED)))) {
13210 if (cstat->loss_detection_timer != UINT64_MAX) {
13211 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_LDC,
13212 "loss detection timer canceled");
13213 ngtcp2_conn_cancel_loss_detection_timer(conn);
13214 }
13215 return;
13216 }
13217
13218 cstat->loss_detection_timer = conn_get_earliest_pto_expiry(conn, ts);
13219
13220 timeout =
13221 cstat->loss_detection_timer > ts ? cstat->loss_detection_timer - ts : 0;
13222
13223 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_LDC,
13224 "loss_detection_timer=%" PRIu64 " timeout=%" PRIu64,
13225 cstat->loss_detection_timer, timeout / NGTCP2_MILLISECONDS);
13226 }
13227
13228 void ngtcp2_conn_cancel_loss_detection_timer(ngtcp2_conn *conn) {
13229 ngtcp2_conn_stat *cstat = &conn->cstat;
13230
13231 cstat->loss_detection_timer = UINT64_MAX;
13232 cstat->pto_count = 0;
13233 }
13234
13235 int ngtcp2_conn_on_loss_detection_timer(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
13236 ngtcp2_conn_stat *cstat = &conn->cstat;
13237 int rv;
13238 ngtcp2_pktns *in_pktns = conn->in_pktns;
13239 ngtcp2_pktns *hs_pktns = conn->hs_pktns;
13240 ngtcp2_tstamp earliest_loss_time;
13241 ngtcp2_pktns *loss_pktns = NULL;
13242
13243 switch (conn->state) {
13244 case NGTCP2_CS_CLOSING:
13245 case NGTCP2_CS_DRAINING:
13246 ngtcp2_conn_cancel_loss_detection_timer(conn);
13247 return 0;
13248 default:
13249 break;
13250 }
13251
13252 if (cstat->loss_detection_timer == UINT64_MAX) {
13253 return 0;
13254 }
13255
13256 conn_get_loss_time_and_pktns(conn, &earliest_loss_time, &loss_pktns);
13257
13258 ngtcp2_log_info(&conn->log, NGTCP2_LOG_EVENT_LDC,
13259 "loss detection timer fired");
13260
13261 if (earliest_loss_time != UINT64_MAX) {
13262 assert(loss_pktns);
13263
13264 rv = ngtcp2_conn_detect_lost_pkt(conn, loss_pktns, cstat, ts);
13265 if (rv != 0) {
13266 return rv;
13267 }
13268 ngtcp2_conn_set_loss_detection_timer(conn, ts);
13269 return 0;
13270 }
13271
13272 if (!conn->server && !conn_is_tls_handshake_completed(conn)) {
13273 if (hs_pktns->crypto.tx.ckm) {
13274 hs_pktns->rtb.probe_pkt_left = 1;
13275 } else {
13276 in_pktns->rtb.probe_pkt_left = 1;
13277 }
13278 } else {
13279 if (in_pktns && in_pktns->rtb.num_pto_eliciting) {
13280 in_pktns->rtb.probe_pkt_left = 1;
13281
13282 assert(hs_pktns);
13283
13284 if (conn->server && hs_pktns->rtb.num_pto_eliciting) {
13285 /* let server coalesce packets */
13286 hs_pktns->rtb.probe_pkt_left = 1;
13287 }
13288 } else if (hs_pktns && hs_pktns->rtb.num_pto_eliciting) {
13289 hs_pktns->rtb.probe_pkt_left = 2;
13290 } else {
13291 conn->pktns.rtb.probe_pkt_left = 2;
13292 }
13293 }
13294
13295 ++cstat->pto_count;
13296
13297 ngtcp2_log_infof(&conn->log, NGTCP2_LOG_EVENT_LDC, "pto_count=%zu",
13298 cstat->pto_count);
13299
13300 ngtcp2_conn_set_loss_detection_timer(conn, ts);
13301
13302 return 0;
13303 }
13304
13305 static int conn_buffer_crypto_data(ngtcp2_conn *conn, const uint8_t **pdata,
13306 ngtcp2_pktns *pktns, const uint8_t *data,
13307 size_t datalen) {
13308 int rv;
13309 ngtcp2_buf_chain **pbufchain = &pktns->crypto.tx.data;
13310
13311 if (*pbufchain) {
13312 for (; (*pbufchain)->next; pbufchain = &(*pbufchain)->next)
13313 ;
13314
13315 if (ngtcp2_buf_left(&(*pbufchain)->buf) < datalen) {
13316 pbufchain = &(*pbufchain)->next;
13317 }
13318 }
13319
13320 if (!*pbufchain) {
13321 rv = ngtcp2_buf_chain_new(pbufchain, ngtcp2_max_size(1024, datalen),
13322 conn->mem);
13323 if (rv != 0) {
13324 return rv;
13325 }
13326 }
13327
13328 *pdata = (*pbufchain)->buf.last;
13329 (*pbufchain)->buf.last = ngtcp2_cpymem((*pbufchain)->buf.last, data, datalen);
13330
13331 return 0;
13332 }
13333
13334 int ngtcp2_conn_submit_crypto_data(ngtcp2_conn *conn,
13335 ngtcp2_encryption_level encryption_level,
13336 const uint8_t *data, const size_t datalen) {
13337 ngtcp2_pktns *pktns;
13338 ngtcp2_frame_chain *frc;
13339 int rv;
13340
13341 if (datalen == 0) {
13342 return 0;
13343 }
13344
13345 switch (encryption_level) {
13346 case NGTCP2_ENCRYPTION_LEVEL_INITIAL:
13347 assert(conn->in_pktns);
13348 pktns = conn->in_pktns;
13349 break;
13350 case NGTCP2_ENCRYPTION_LEVEL_HANDSHAKE:
13351 assert(conn->hs_pktns);
13352 pktns = conn->hs_pktns;
13353 break;
13354 case NGTCP2_ENCRYPTION_LEVEL_1RTT:
13355 pktns = &conn->pktns;
13356 break;
13357 default:
13358 return NGTCP2_ERR_INVALID_ARGUMENT;
13359 }
13360
13361 rv = conn_buffer_crypto_data(conn, &data, pktns, data, datalen);
13362 if (rv != 0) {
13363 return rv;
13364 }
13365
13366 rv = ngtcp2_frame_chain_stream_datacnt_objalloc_new(
13367 &frc, 1, &conn->frc_objalloc, conn->mem);
13368 if (rv != 0) {
13369 return rv;
13370 }
13371
13372 frc->fr.stream.type = NGTCP2_FRAME_CRYPTO;
13373 frc->fr.stream.flags = 0;
13374 frc->fr.stream.fin = 0;
13375 frc->fr.stream.stream_id = 0;
13376 frc->fr.stream.offset = pktns->crypto.tx.offset;
13377 frc->fr.stream.datacnt = 1;
13378 frc->fr.stream.data[0] = (ngtcp2_vec){
13379 .base = (uint8_t *)data,
13380 .len = datalen,
13381 };
13382
13383 rv = ngtcp2_strm_streamfrq_push(&pktns->crypto.strm, frc);
13384 if (rv != 0) {
13385 ngtcp2_frame_chain_objalloc_del(frc, &conn->frc_objalloc, conn->mem);
13386 return rv;
13387 }
13388
13389 pktns->crypto.strm.tx.offset += datalen;
13390 pktns->crypto.tx.offset += datalen;
13391
13392 return 0;
13393 }
13394
13395 int ngtcp2_conn_submit_new_token(ngtcp2_conn *conn, const uint8_t *token,
13396 size_t tokenlen) {
13397 int rv;
13398 ngtcp2_frame_chain *nfrc;
13399
13400 assert(conn->server);
13401 assert(token);
13402 assert(tokenlen);
13403
13404 rv = ngtcp2_frame_chain_new_token_objalloc_new(
13405 &nfrc, token, tokenlen, &conn->frc_objalloc, conn->mem);
13406 if (rv != 0) {
13407 return rv;
13408 }
13409
13410 nfrc->next = conn->pktns.tx.frq;
13411 conn->pktns.tx.frq = nfrc;
13412
13413 return 0;
13414 }
13415
13416 ngtcp2_strm *ngtcp2_conn_tx_strmq_top(ngtcp2_conn *conn) {
13417 assert(!ngtcp2_pq_empty(&conn->tx.strmq));
13418 return ngtcp2_struct_of(ngtcp2_pq_top(&conn->tx.strmq), ngtcp2_strm, pe);
13419 }
13420
13421 void ngtcp2_conn_tx_strmq_pop(ngtcp2_conn *conn) {
13422 ngtcp2_strm *strm = ngtcp2_conn_tx_strmq_top(conn);
13423 assert(strm);
13424 ngtcp2_pq_pop(&conn->tx.strmq);
13425 strm->pe.index = NGTCP2_PQ_BAD_INDEX;
13426 }
13427
13428 int ngtcp2_conn_tx_strmq_push(ngtcp2_conn *conn, ngtcp2_strm *strm) {
13429 return ngtcp2_pq_push(&conn->tx.strmq, &strm->pe);
13430 }
13431
13432 static int conn_has_uncommitted_preferred_addr_cid(ngtcp2_conn *conn) {
13433 return conn->server &&
13434 !(conn->flags & NGTCP2_CONN_FLAG_LOCAL_TRANSPORT_PARAMS_COMMITTED) &&
13435 conn->oscid.datalen &&
13436 conn->local.transport_params.preferred_addr_present;
13437 }
13438
13439 size_t ngtcp2_conn_get_scid(ngtcp2_conn *conn, ngtcp2_cid *dest) {
13440 ngtcp2_cid *origdest = dest;
13441 ngtcp2_ksl_it it;
13442 ngtcp2_scid *scid;
13443
13444 if (dest == NULL) {
13445 return ngtcp2_ksl_len(&conn->scid.set) +
13446 (size_t)conn_has_uncommitted_preferred_addr_cid(conn);
13447 }
13448
13449 for (it = ngtcp2_ksl_begin(&conn->scid.set); !ngtcp2_ksl_it_end(&it);
13450 ngtcp2_ksl_it_next(&it)) {
13451 scid = ngtcp2_ksl_it_get(&it);
13452 *dest++ = scid->cid;
13453 }
13454
13455 if (conn_has_uncommitted_preferred_addr_cid(conn)) {
13456 *dest++ = conn->local.transport_params.preferred_addr.cid;
13457 }
13458
13459 return (size_t)(dest - origdest);
13460 }
13461
13462 static size_t conn_get_num_active_dcid(ngtcp2_conn *conn) {
13463 size_t n = 1; /* for conn->dcid.current */
13464 ngtcp2_pv *pv = conn->pv;
13465
13466 if (conn->dcid.current.cid.datalen == 0) {
13467 return n;
13468 }
13469
13470 if (pv) {
13471 if (pv->dcid.seq != conn->dcid.current.seq) {
13472 ++n;
13473 }
13474 if ((pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) &&
13475 pv->fallback_dcid.seq != conn->dcid.current.seq &&
13476 pv->fallback_dcid.seq != pv->dcid.seq) {
13477 ++n;
13478 }
13479 }
13480
13481 n += ngtcp2_dcidtr_retired_len(&conn->dcid.dtr);
13482
13483 return n;
13484 }
13485
13486 static void copy_dcid_to_cid_token(ngtcp2_cid_token *dest,
13487 const ngtcp2_dcid *src) {
13488 dest->seq = src->seq;
13489 dest->cid = src->cid;
13490 ngtcp2_path_storage_init2(&dest->ps, &src->ps.path);
13491 if ((dest->token_present =
13492 (src->flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT) != 0)) {
13493 memcpy(dest->token, src->token, NGTCP2_STATELESS_RESET_TOKENLEN);
13494 }
13495 }
13496
13497 size_t ngtcp2_conn_get_active_dcid(ngtcp2_conn *conn, ngtcp2_cid_token *dest) {
13498 ngtcp2_pv *pv = conn->pv;
13499 ngtcp2_cid_token *orig = dest;
13500 ngtcp2_dcid *dcid;
13501 size_t len, i;
13502
13503 if (!(conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_COMPLETED)) {
13504 return 0;
13505 }
13506
13507 if (dest == NULL) {
13508 return conn_get_num_active_dcid(conn);
13509 }
13510
13511 copy_dcid_to_cid_token(dest, &conn->dcid.current);
13512 ++dest;
13513
13514 if (conn->dcid.current.cid.datalen == 0) {
13515 return 1;
13516 }
13517
13518 if (pv) {
13519 if (pv->dcid.seq != conn->dcid.current.seq) {
13520 copy_dcid_to_cid_token(dest, &pv->dcid);
13521 ++dest;
13522 }
13523 if ((pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) &&
13524 pv->fallback_dcid.seq != conn->dcid.current.seq &&
13525 pv->fallback_dcid.seq != pv->dcid.seq) {
13526 copy_dcid_to_cid_token(dest, &pv->fallback_dcid);
13527 ++dest;
13528 }
13529 }
13530
13531 len = ngtcp2_ringbuf_len(&conn->dcid.dtr.retired.rb);
13532 for (i = 0; i < len; ++i) {
13533 dcid = ngtcp2_ringbuf_get(&conn->dcid.dtr.retired.rb, i);
13534 copy_dcid_to_cid_token(dest, dcid);
13535 ++dest;
13536 }
13537
13538 return (size_t)(dest - orig);
13539 }
13540
13541 void ngtcp2_conn_set_local_addr(ngtcp2_conn *conn, const ngtcp2_addr *addr) {
13542 ngtcp2_addr *dest = &conn->dcid.current.ps.path.local;
13543
13544 assert(addr->addrlen <=
13545 (ngtcp2_socklen)sizeof(conn->dcid.current.ps.local_addrbuf));
13546 ngtcp2_addr_copy(dest, addr);
13547 }
13548
13549 void ngtcp2_conn_set_path_user_data(ngtcp2_conn *conn, void *path_user_data) {
13550 conn->dcid.current.ps.path.user_data = path_user_data;
13551 }
13552
13553 const ngtcp2_path *ngtcp2_conn_get_path(ngtcp2_conn *conn) {
13554 return &conn->dcid.current.ps.path;
13555 }
13556
13557 size_t ngtcp2_conn_get_max_tx_udp_payload_size(ngtcp2_conn *conn) {
13558 return conn->local.settings.max_tx_udp_payload_size;
13559 }
13560
13561 size_t ngtcp2_conn_get_path_max_tx_udp_payload_size(ngtcp2_conn *conn) {
13562 if (conn->local.settings.no_tx_udp_payload_size_shaping) {
13563 return ngtcp2_conn_get_max_tx_udp_payload_size(conn);
13564 }
13565
13566 return conn->dcid.current.max_udp_payload_size;
13567 }
13568
13569 static int conn_initiate_migration_precheck(ngtcp2_conn *conn,
13570 const ngtcp2_addr *local_addr) {
13571 if (!(conn->flags & NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED) ||
13572 conn->remote.transport_params->disable_active_migration ||
13573 conn->dcid.current.cid.datalen == 0 ||
13574 (conn->pv && (conn->pv->flags & NGTCP2_PV_FLAG_PREFERRED_ADDR))) {
13575 return NGTCP2_ERR_INVALID_STATE;
13576 }
13577
13578 if (ngtcp2_dcidtr_unused_empty(&conn->dcid.dtr)) {
13579 return NGTCP2_ERR_CONN_ID_BLOCKED;
13580 }
13581
13582 if (ngtcp2_addr_eq(&conn->dcid.current.ps.path.local, local_addr)) {
13583 return NGTCP2_ERR_INVALID_ARGUMENT;
13584 }
13585
13586 return 0;
13587 }
13588
13589 int ngtcp2_conn_initiate_immediate_migration(ngtcp2_conn *conn,
13590 const ngtcp2_path *path,
13591 ngtcp2_tstamp ts) {
13592 int rv;
13593 ngtcp2_dcid dcid;
13594 ngtcp2_pv *pv;
13595 const ngtcp2_path_history_entry *validated_path;
13596
13597 assert(!conn->server);
13598
13599 conn_update_timestamp(conn, ts);
13600
13601 rv = conn_initiate_migration_precheck(conn, &path->local);
13602 if (rv != 0) {
13603 return rv;
13604 }
13605
13606 ngtcp2_conn_stop_pmtud(conn);
13607
13608 if (conn->pv) {
13609 rv = conn_abort_pv(conn, ts);
13610 if (rv != 0) {
13611 return rv;
13612 }
13613 }
13614
13615 rv = conn_retire_active_dcid(conn, &conn->dcid.current, ts);
13616 if (rv != 0) {
13617 return rv;
13618 }
13619
13620 ngtcp2_dcidtr_pop_unused(&conn->dcid.dtr, &dcid);
13621 ngtcp2_dcid_set_path(&dcid, path);
13622
13623 if (conn->dcid.current.flags & NGTCP2_DCID_FLAG_PATH_VALIDATED) {
13624 ngtcp2_conn_add_path_history(conn, &conn->dcid.current, ts);
13625 }
13626
13627 ngtcp2_dcid_copy(&conn->dcid.current, &dcid);
13628
13629 conn_reset_congestion_state(conn, ts);
13630 conn_reset_ecn_validation_state(conn);
13631
13632 validated_path = ngtcp2_conn_find_path_history(conn, path, ts);
13633 if (validated_path) {
13634 ngtcp2_dcid_apply_validated_path(&conn->dcid.current, validated_path);
13635
13636 if (!conn->local.settings.no_pmtud) {
13637 rv = conn_start_pmtud(conn);
13638 if (rv != 0) {
13639 return rv;
13640 }
13641 }
13642 } else {
13643 /* TODO It might be better to add a new flag which indicates that
13644 a connection should be closed if this path validation failed.
13645 The current design allows an application to continue, by
13646 migrating into yet another path. */
13647 rv = ngtcp2_pv_new(&pv, &dcid, conn_compute_pv_timeout(conn),
13648 NGTCP2_PV_FLAG_NONE, &conn->log, conn->mem);
13649 if (rv != 0) {
13650 return rv;
13651 }
13652
13653 conn->pv = pv;
13654 }
13655
13656 rv = conn_call_activate_dcid(conn, &conn->dcid.current);
13657 if (rv != 0) {
13658 return rv;
13659 }
13660
13661 return conn_call_begin_path_validation(conn, conn->pv);
13662 }
13663
13664 int ngtcp2_conn_initiate_migration(ngtcp2_conn *conn, const ngtcp2_path *path,
13665 ngtcp2_tstamp ts) {
13666 int rv;
13667 ngtcp2_dcid dcid;
13668 ngtcp2_pv *pv;
13669
13670 assert(!conn->server);
13671
13672 if (ngtcp2_conn_find_path_history(conn, path, ts)) {
13673 return ngtcp2_conn_initiate_immediate_migration(conn, path, ts);
13674 }
13675
13676 conn_update_timestamp(conn, ts);
13677
13678 rv = conn_initiate_migration_precheck(conn, &path->local);
13679 if (rv != 0) {
13680 return rv;
13681 }
13682
13683 if (conn->pv) {
13684 rv = conn_abort_pv(conn, ts);
13685 if (rv != 0) {
13686 return rv;
13687 }
13688 }
13689
13690 ngtcp2_dcidtr_pop_unused(&conn->dcid.dtr, &dcid);
13691 ngtcp2_dcid_set_path(&dcid, path);
13692
13693 rv = ngtcp2_pv_new(&pv, &dcid, conn_compute_pv_timeout(conn),
13694 NGTCP2_PV_FLAG_NONE, &conn->log, conn->mem);
13695 if (rv != 0) {
13696 return rv;
13697 }
13698
13699 conn->pv = pv;
13700
13701 rv = conn_call_activate_dcid(conn, &pv->dcid);
13702 if (rv != 0) {
13703 return rv;
13704 }
13705
13706 return conn_call_begin_path_validation(conn, conn->pv);
13707 }
13708
13709 uint64_t ngtcp2_conn_get_max_data_left(ngtcp2_conn *conn) {
13710 return conn->tx.max_offset - conn->tx.offset;
13711 }
13712
13713 uint64_t ngtcp2_conn_get_max_stream_data_left(ngtcp2_conn *conn,
13714 int64_t stream_id) {
13715 ngtcp2_strm *strm = ngtcp2_conn_find_stream(conn, stream_id);
13716
13717 if (strm == NULL) {
13718 return 0;
13719 }
13720
13721 return strm->tx.max_offset - strm->tx.offset;
13722 }
13723
13724 uint64_t ngtcp2_conn_get_streams_bidi_left(ngtcp2_conn *conn) {
13725 uint64_t n = ngtcp2_ord_stream_id(conn->local.bidi.next_stream_id);
13726
13727 return n > conn->local.bidi.max_streams
13728 ? 0
13729 : conn->local.bidi.max_streams - n + 1;
13730 }
13731
13732 uint64_t ngtcp2_conn_get_streams_uni_left(ngtcp2_conn *conn) {
13733 uint64_t n = ngtcp2_ord_stream_id(conn->local.uni.next_stream_id);
13734
13735 return n > conn->local.uni.max_streams ? 0
13736 : conn->local.uni.max_streams - n + 1;
13737 }
13738
13739 uint64_t ngtcp2_conn_get_cwnd_left(ngtcp2_conn *conn) {
13740 uint64_t bytes_in_flight = conn->cstat.bytes_in_flight;
13741 uint64_t cwnd = conn->cstat.cwnd;
13742
13743 if (cwnd > bytes_in_flight) {
13744 return cwnd - bytes_in_flight;
13745 }
13746
13747 return 0;
13748 }
13749
13750 ngtcp2_tstamp ngtcp2_conn_get_idle_expiry(ngtcp2_conn *conn) {
13751 ngtcp2_duration trpto;
13752 ngtcp2_duration idle_timeout;
13753
13754 /* TODO Remote max_idle_timeout becomes effective after handshake
13755 completion. */
13756
13757 if (!conn_is_tls_handshake_completed(conn) ||
13758 conn->remote.transport_params->max_idle_timeout == 0 ||
13759 (conn->local.transport_params.max_idle_timeout &&
13760 conn->local.transport_params.max_idle_timeout <
13761 conn->remote.transport_params->max_idle_timeout)) {
13762 idle_timeout = conn->local.transport_params.max_idle_timeout;
13763 } else {
13764 idle_timeout = conn->remote.transport_params->max_idle_timeout;
13765 }
13766
13767 if (idle_timeout == 0) {
13768 return UINT64_MAX;
13769 }
13770
13771 trpto = 3 * conn_compute_pto(conn, conn_is_tls_handshake_completed(conn)
13772 ? &conn->pktns
13773 : conn->hs_pktns);
13774
13775 idle_timeout = ngtcp2_max_uint64(idle_timeout, trpto);
13776
13777 if (conn->idle_ts >= UINT64_MAX - idle_timeout) {
13778 return UINT64_MAX;
13779 }
13780
13781 return conn->idle_ts + idle_timeout;
13782 }
13783
13784 ngtcp2_duration ngtcp2_conn_get_pto(ngtcp2_conn *conn) {
13785 return conn_compute_pto(conn, conn_is_tls_handshake_completed(conn)
13786 ? &conn->pktns
13787 : conn->hs_pktns);
13788 }
13789
13790 void ngtcp2_conn_set_initial_crypto_ctx(ngtcp2_conn *conn,
13791 const ngtcp2_crypto_ctx *ctx) {
13792 assert(conn->in_pktns);
13793 conn->in_pktns->crypto.ctx = *ctx;
13794 }
13795
13796 const ngtcp2_crypto_ctx *ngtcp2_conn_get_initial_crypto_ctx(ngtcp2_conn *conn) {
13797 assert(conn->in_pktns);
13798 return &conn->in_pktns->crypto.ctx;
13799 }
13800
13801 void ngtcp2_conn_set_retry_aead(ngtcp2_conn *conn,
13802 const ngtcp2_crypto_aead *aead,
13803 const ngtcp2_crypto_aead_ctx *aead_ctx) {
13804 assert(!conn->crypto.retry_aead_ctx.native_handle);
13805
13806 conn->crypto.retry_aead = *aead;
13807 conn->crypto.retry_aead_ctx = *aead_ctx;
13808 }
13809
13810 void ngtcp2_conn_set_crypto_ctx(ngtcp2_conn *conn,
13811 const ngtcp2_crypto_ctx *ctx) {
13812 assert(conn->hs_pktns);
13813 conn->hs_pktns->crypto.ctx = *ctx;
13814 conn->pktns.crypto.ctx = *ctx;
13815 }
13816
13817 const ngtcp2_crypto_ctx *ngtcp2_conn_get_crypto_ctx(ngtcp2_conn *conn) {
13818 return &conn->pktns.crypto.ctx;
13819 }
13820
13821 void ngtcp2_conn_set_0rtt_crypto_ctx(ngtcp2_conn *conn,
13822 const ngtcp2_crypto_ctx *ctx) {
13823 conn->early.ctx = *ctx;
13824 }
13825
13826 const ngtcp2_crypto_ctx *ngtcp2_conn_get_0rtt_crypto_ctx(ngtcp2_conn *conn) {
13827 return &conn->early.ctx;
13828 }
13829
13830 void *ngtcp2_conn_get_tls_native_handle(ngtcp2_conn *conn) {
13831 return conn->crypto.tls_native_handle;
13832 }
13833
13834 void ngtcp2_conn_set_tls_native_handle(ngtcp2_conn *conn,
13835 void *tls_native_handle) {
13836 conn->crypto.tls_native_handle = tls_native_handle;
13837 }
13838
13839 const ngtcp2_ccerr *ngtcp2_conn_get_ccerr(ngtcp2_conn *conn) {
13840 return &conn->rx.ccerr;
13841 }
13842
13843 void ngtcp2_conn_set_tls_error(ngtcp2_conn *conn, int liberr) {
13844 conn->crypto.tls_error = liberr;
13845 }
13846
13847 int ngtcp2_conn_get_tls_error(ngtcp2_conn *conn) {
13848 return conn->crypto.tls_error;
13849 }
13850
13851 void ngtcp2_conn_set_tls_alert(ngtcp2_conn *conn, uint8_t alert) {
13852 conn->crypto.tls_alert = alert;
13853 }
13854
13855 uint8_t ngtcp2_conn_get_tls_alert(ngtcp2_conn *conn) {
13856 return conn->crypto.tls_alert;
13857 }
13858
13859 int ngtcp2_conn_is_local_stream(ngtcp2_conn *conn, int64_t stream_id) {
13860 return conn_local_stream(conn, stream_id);
13861 }
13862
13863 int ngtcp2_conn_is_server(ngtcp2_conn *conn) { return conn->server; }
13864
13865 int ngtcp2_conn_after_retry(ngtcp2_conn *conn) {
13866 return (conn->flags & NGTCP2_CONN_FLAG_RECV_RETRY) != 0;
13867 }
13868
13869 int ngtcp2_conn_set_stream_user_data(ngtcp2_conn *conn, int64_t stream_id,
13870 void *stream_user_data) {
13871 ngtcp2_strm *strm = ngtcp2_conn_find_stream(conn, stream_id);
13872
13873 if (strm == NULL) {
13874 return NGTCP2_ERR_STREAM_NOT_FOUND;
13875 }
13876
13877 strm->stream_user_data = stream_user_data;
13878
13879 return 0;
13880 }
13881
13882 void *ngtcp2_conn_get_stream_user_data(ngtcp2_conn *conn, int64_t stream_id) {
13883 ngtcp2_strm *strm = ngtcp2_conn_find_stream(conn, stream_id);
13884
13885 if (strm == NULL) {
13886 return NULL;
13887 }
13888
13889 return strm->stream_user_data;
13890 }
13891
13892 void ngtcp2_conn_update_pkt_tx_time(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
13893 ngtcp2_duration wait, d;
13894
13895 conn_update_timestamp(conn, ts);
13896
13897 if (conn->tx.pacing.pktlen == 0) {
13898 return;
13899 }
13900
13901 wait = (ngtcp2_duration)((conn->tx.pacing.pktlen *
13902 conn->cstat.pacing_interval_m) >>
13903 10);
13904
13905 d = ngtcp2_min_uint64(wait / 2, conn->tx.pacing.compensation);
13906 wait -= d;
13907 conn->tx.pacing.compensation -= d;
13908
13909 conn->tx.pacing.next_ts = ts + wait;
13910 conn->tx.pacing.pktlen = 0;
13911 }
13912
13913 size_t ngtcp2_conn_get_send_quantum(ngtcp2_conn *conn) {
13914 return conn->cstat.send_quantum;
13915 }
13916
13917 size_t ngtcp2_conn_get_stream_loss_count(ngtcp2_conn *conn, int64_t stream_id) {
13918 ngtcp2_strm *strm = ngtcp2_conn_find_stream(conn, stream_id);
13919
13920 if (strm == NULL) {
13921 return 0;
13922 }
13923
13924 return strm->tx.loss_count;
13925 }
13926
13927 void ngtcp2_conn_add_path_history(ngtcp2_conn *conn, const ngtcp2_dcid *dcid,
13928 ngtcp2_tstamp ts) {
13929 ngtcp2_path_history_entry *ent;
13930
13931 ent = ngtcp2_ringbuf_push_front(&conn->path_history.rb);
13932 ngtcp2_path_storage_init2(&ent->ps, &dcid->ps.path);
13933 ent->max_udp_payload_size = dcid->max_udp_payload_size;
13934 ent->ts = ts;
13935 }
13936
13937 ngtcp2_ssize ngtcp2_conn_write_aggregate_pkt_versioned(
13938 ngtcp2_conn *conn, ngtcp2_path *path, int pkt_info_version,
13939 ngtcp2_pkt_info *pi, uint8_t *buf, size_t buflen, size_t *pgsolen,
13940 ngtcp2_write_pkt write_pkt, ngtcp2_tstamp ts) {
13941 ngtcp2_ssize nwrite;
13942
13943 buflen = ngtcp2_min_size(buflen, ngtcp2_conn_get_send_quantum(conn));
13944
13945 nwrite = ngtcp2_conn_write_aggregate_pkt2_versioned(
13946 conn, path, pkt_info_version, pi, buf, buflen, pgsolen, write_pkt, 0, ts);
13947 if (nwrite < 0) {
13948 return nwrite;
13949 }
13950
13951 ngtcp2_conn_update_pkt_tx_time(conn, ts);
13952
13953 return nwrite;
13954 }
13955
13956 ngtcp2_ssize ngtcp2_conn_write_aggregate_pkt2_versioned(
13957 ngtcp2_conn *conn, ngtcp2_path *path, int pkt_info_version,
13958 ngtcp2_pkt_info *pi, uint8_t *buf, size_t buflen, size_t *pgsolen,
13959 ngtcp2_write_pkt write_pkt, size_t num_pkts, ngtcp2_tstamp ts) {
13960 size_t max_udp_payloadlen = ngtcp2_conn_get_max_tx_udp_payload_size(conn);
13961 size_t path_max_udp_payloadlen =
13962 ngtcp2_conn_get_path_max_tx_udp_payload_size(conn);
13963 ngtcp2_ssize nwrite;
13964 uint8_t *wbuf = buf;
13965 size_t wbuflen;
13966 ngtcp2_ecn_state ecn_state;
13967 int first_pkt;
13968 ngtcp2_pkt_info pi_discard;
13969 ngtcp2_path_storage path_discard;
13970 (void)pkt_info_version;
13971
13972 assert(buflen >= path_max_udp_payloadlen);
13973
13974 if (num_pkts == 0) {
13975 num_pkts = SIZE_MAX;
13976 }
13977
13978 for (;;) {
13979 ecn_state = conn->tx.ecn.state;
13980
13981 wbuflen = buflen >= max_udp_payloadlen ? max_udp_payloadlen
13982 : path_max_udp_payloadlen;
13983
13984 nwrite = write_pkt(conn, path, pi, wbuf, wbuflen, ts, conn->user_data);
13985 if (nwrite < 0) {
13986 break;
13987 }
13988
13989 if (nwrite == 0) {
13990 nwrite = wbuf - buf;
13991 break;
13992 }
13993
13994 first_pkt = buf == wbuf;
13995 wbuf += nwrite;
13996 buflen -= (size_t)nwrite;
13997
13998 --num_pkts;
13999
14000 if (first_pkt) {
14001 assert(!(conn->flags & NGTCP2_CONN_FLAG_AGGREGATE_PKTS));
14002
14003 *pgsolen = (size_t)nwrite;
14004
14005 if ((size_t)nwrite != path_max_udp_payloadlen ||
14006 buflen < path_max_udp_payloadlen || ecn_state != conn->tx.ecn.state ||
14007 num_pkts == 0) {
14008 nwrite = wbuf - buf;
14009 break;
14010 }
14011
14012 /* All aggregated packets should share the same path and pi.
14013 Pass the placeholder values to the callback because they
14014 might be overwritten by later calls, especially pi is set to
14015 empty when no packet is produced. */
14016 if (path) {
14017 ngtcp2_path_storage_zero(&path_discard);
14018 path = &path_discard.path;
14019 }
14020
14021 if (pi) {
14022 pi = &pi_discard;
14023 }
14024
14025 conn->flags |= NGTCP2_CONN_FLAG_AGGREGATE_PKTS;
14026
14027 continue;
14028 }
14029
14030 if (buflen < path_max_udp_payloadlen || (size_t)nwrite < *pgsolen ||
14031 ecn_state != conn->tx.ecn.state || num_pkts == 0) {
14032 nwrite = wbuf - buf;
14033 break;
14034 }
14035 }
14036
14037 conn->flags &= ~NGTCP2_CONN_FLAG_AGGREGATE_PKTS;
14038
14039 return nwrite;
14040 }
14041
14042 ngtcp2_tstamp ngtcp2_conn_get_timestamp(const ngtcp2_conn *conn) {
14043 return conn->log.last_ts;
14044 }
14045
14046 const ngtcp2_path_history_entry *
14047 ngtcp2_conn_find_path_history(ngtcp2_conn *conn, const ngtcp2_path *path,
14048 ngtcp2_tstamp ts) {
14049 ngtcp2_ringbuf *rb = &conn->path_history.rb;
14050 size_t i, len = ngtcp2_ringbuf_len(rb);
14051 ngtcp2_path_history_entry *ent;
14052
14053 for (i = 0; i < len; ++i) {
14054 ent = ngtcp2_ringbuf_get(rb, i);
14055 if (ngtcp2_tstamp_elapsed(ent->ts, 10 * NGTCP2_MINUTES, ts)) {
14056 return NULL;
14057 }
14058
14059 if (ngtcp2_path_eq(path, &ent->ps.path)) {
14060 return ent;
14061 }
14062 }
14063
14064 return NULL;
14065 }
14066
14067 void ngtcp2_path_challenge_entry_init(ngtcp2_path_challenge_entry *pcent,
14068 const ngtcp2_path *path,
14069 const uint8_t *data) {
14070 ngtcp2_path_storage_init2(&pcent->ps, path);
14071 memcpy(pcent->data, data, sizeof(pcent->data));
14072 }
14073
14074 /* The functions prefixed with ngtcp2_pkt_ are usually put inside
14075 ngtcp2_pkt.c. This function uses encryption construct and uses
14076 test data defined only in ngtcp2_conn_test.c, so it is written
14077 here. */
14078 ngtcp2_ssize ngtcp2_pkt_write_connection_close(
14079 uint8_t *dest, size_t destlen, uint32_t version, const ngtcp2_cid *dcid,
14080 const ngtcp2_cid *scid, uint64_t error_code, const uint8_t *reason,
14081 size_t reasonlen, ngtcp2_encrypt encrypt, const ngtcp2_crypto_aead *aead,
14082 const ngtcp2_crypto_aead_ctx *aead_ctx, const uint8_t *iv,
14083 ngtcp2_hp_mask hp_mask, const ngtcp2_crypto_cipher *hp,
14084 const ngtcp2_crypto_cipher_ctx *hp_ctx) {
14085 ngtcp2_pkt_hd hd;
14086 ngtcp2_crypto_km ckm;
14087 ngtcp2_crypto_cc cc;
14088 ngtcp2_ppe ppe;
14089 ngtcp2_frame fr;
14090 int rv;
14091
14092 ngtcp2_pkt_hd_init(&hd, NGTCP2_PKT_FLAG_LONG_FORM, NGTCP2_PKT_INITIAL, dcid,
14093 scid, /* pkt_num = */ 0, /* pkt_numlen = */ 1, version);
14094
14095 ngtcp2_vec_init(&ckm.secret, NULL, 0);
14096 ngtcp2_vec_init(&ckm.iv, iv, 12);
14097 ckm.aead_ctx = *aead_ctx;
14098 ckm.pkt_num = 0;
14099 ckm.flags = NGTCP2_CRYPTO_KM_FLAG_NONE;
14100
14101 cc.aead = *aead;
14102 cc.hp = *hp;
14103 cc.ckm = &ckm;
14104 cc.hp_ctx = *hp_ctx;
14105 cc.encrypt = encrypt;
14106 cc.hp_mask = hp_mask;
14107
14108 ngtcp2_ppe_init(&ppe, dest, destlen, 0, &cc);
14109
14110 rv = ngtcp2_ppe_encode_hd(&ppe, &hd);
14111 if (rv != 0) {
14112 assert(NGTCP2_ERR_NOBUF == rv);
14113 return rv;
14114 }
14115
14116 if (!ngtcp2_ppe_ensure_hp_sample(&ppe)) {
14117 return NGTCP2_ERR_NOBUF;
14118 }
14119
14120 fr.connection_close = (ngtcp2_connection_close){
14121 .type = NGTCP2_FRAME_CONNECTION_CLOSE,
14122 .error_code = error_code,
14123 .reasonlen = reasonlen,
14124 .reason = (uint8_t *)reason,
14125 };
14126
14127 rv = ngtcp2_ppe_encode_frame(&ppe, &fr);
14128 if (rv != 0) {
14129 assert(NGTCP2_ERR_NOBUF == rv);
14130 return rv;
14131 }
14132
14133 return ngtcp2_ppe_final(&ppe, NULL);
14134 }
14135
14136 int ngtcp2_is_bidi_stream(int64_t stream_id) { return bidi_stream(stream_id); }
14137
14138 uint32_t ngtcp2_select_version(const uint32_t *preferred_versions,
14139 size_t preferred_versionslen,
14140 const uint32_t *offered_versions,
14141 size_t offered_versionslen) {
14142 size_t i, j;
14143
14144 if (!preferred_versionslen || !offered_versionslen) {
14145 return 0;
14146 }
14147
14148 for (i = 0; i < preferred_versionslen; ++i) {
14149 assert(ngtcp2_is_supported_version(preferred_versions[i]));
14150
14151 for (j = 0; j < offered_versionslen; ++j) {
14152 if (preferred_versions[i] == offered_versions[j]) {
14153 return preferred_versions[i];
14154 }
14155 }
14156 }
14157
14158 return 0;
14159 }