Line data Source code
1 : #include "fd_quic.h"
2 : #include "fd_quic_ack_tx.h"
3 : #include "fd_quic_common.h"
4 : #include "fd_quic_conn_id.h"
5 : #include "fd_quic_enum.h"
6 : #include "fd_quic_pkt_meta.h"
7 : #include "fd_quic_private.h"
8 : #include "fd_quic_conn.h"
9 : #include "fd_quic_conn_map.h"
10 : #include "fd_quic_proto.h"
11 : #include "fd_quic_proto.c"
12 : #include "fd_quic_retry.h"
13 : #include "fd_quic_svc_q.h"
14 :
15 : #define FD_TEMPL_FRAME_CTX fd_quic_frame_ctx_t
16 : #include "templ/fd_quic_frame_handler_decl.h"
17 : #include "templ/fd_quic_frames_templ.h"
18 : #include "templ/fd_quic_undefs.h"
19 :
20 : #include "fd_quic_pretty_print.c"
21 :
22 : #include "crypto/fd_quic_crypto_suites.h"
23 : #include "templ/fd_quic_transport_params.h"
24 : #include "templ/fd_quic_parse_util.h"
25 : #include "tls/fd_quic_tls.h"
26 :
27 : #include <fcntl.h> /* for keylog open(2) */
28 : #include <unistd.h> /* for keylog close(2) */
29 :
30 : #include "../../ballet/hex/fd_hex.h"
31 : #include "../../ballet/x509/fd_x509_mock.h"
32 : #include "../../tango/tempo/fd_tempo.h"
33 : #include "../../util/log/fd_dtrace.h"
34 :
35 : #include "../../disco/metrics/generated/fd_metrics_enums.h"
36 :
37 : /* Declare map type for stream_id -> stream* */
38 : #define MAP_NAME fd_quic_stream_map
39 38987325 : #define MAP_KEY stream_id
40 20778234 : #define MAP_T fd_quic_stream_map_t
41 25133614 : #define MAP_KEY_NULL FD_QUIC_STREAM_ID_UNUSED
42 17172308 : #define MAP_KEY_INVAL(key) ((key)==MAP_KEY_NULL)
43 : #define MAP_QUERY_OPT 1
44 : #include "../../util/tmpl/fd_map_dynamic.c"
45 :
46 :
47 : /* FD_QUIC_MAX_STREAMS_ALWAYS_UNLESS_ACKED */
48 : /* Defines whether a MAX_STREAMS frame is sent even if it was just */
49 : /* sent */
50 : /* They take very little space, and a dropped MAX_STREAMS frame can */
51 : /* be very consequential */
52 : /* Even when set, QUIC won't send this frame if the client has ackd */
53 : /* the most recent value */
54 6917611 : # define FD_QUIC_MAX_STREAMS_ALWAYS_UNLESS_ACKED 0
55 :
56 : /* Construction API ***************************************************/
57 :
58 : FD_QUIC_API FD_FN_CONST ulong
59 252 : fd_quic_align( void ) {
60 252 : return FD_QUIC_ALIGN;
61 252 : }
62 :
63 : /* fd_quic_footprint_ext returns footprint of QUIC memory region given
64 : limits. Also writes byte offsets to given layout struct. */
65 : static ulong
66 : fd_quic_footprint_ext( fd_quic_limits_t const * limits,
67 396 : fd_quic_layout_t * layout ) {
68 396 : memset( layout, 0, sizeof(fd_quic_layout_t) );
69 396 : if( FD_UNLIKELY( !limits ) ) return 0UL;
70 :
71 396 : ulong conn_cnt = limits->conn_cnt;
72 396 : ulong conn_id_cnt = limits->conn_id_cnt;
73 396 : ulong log_depth = limits->log_depth;
74 396 : ulong handshake_cnt = limits->handshake_cnt;
75 396 : ulong inflight_frame_cnt = limits->inflight_frame_cnt;
76 396 : ulong tx_buf_sz = limits->tx_buf_sz;
77 396 : ulong stream_pool_cnt = limits->stream_pool_cnt;
78 396 : ulong inflight_res_cnt = limits->min_inflight_frame_cnt_conn * conn_cnt;
79 396 : if( FD_UNLIKELY( conn_cnt ==0UL ) ) return 0UL;
80 396 : if( FD_UNLIKELY( handshake_cnt ==0UL ) ) return 0UL;
81 396 : if( FD_UNLIKELY( inflight_frame_cnt==0UL ) ) return 0UL;
82 :
83 396 : if( FD_UNLIKELY( inflight_res_cnt > inflight_frame_cnt ) ) return 0UL;
84 :
85 393 : if( FD_UNLIKELY( conn_id_cnt < FD_QUIC_MIN_CONN_ID_CNT ))
86 0 : return 0UL;
87 :
88 393 : layout->meta_sz = sizeof(fd_quic_layout_t);
89 :
90 393 : ulong offs = 0;
91 :
92 : /* allocate space for fd_quic_t */
93 393 : offs += sizeof(fd_quic_t);
94 :
95 : /* allocate space for state */
96 393 : offs = fd_ulong_align_up( offs, alignof(fd_quic_state_t) );
97 393 : offs += sizeof(fd_quic_state_t);
98 :
99 : /* allocate space for connections */
100 393 : offs = fd_ulong_align_up( offs, fd_quic_conn_align() );
101 393 : layout->conns_off = offs;
102 393 : ulong conn_footprint = fd_quic_conn_footprint( limits );
103 393 : if( FD_UNLIKELY( !conn_footprint ) ) { FD_LOG_WARNING(( "invalid fd_quic_conn_footprint" )); return 0UL; }
104 393 : layout->conn_footprint = conn_footprint;
105 393 : ulong conn_foot_tot = conn_cnt * conn_footprint;
106 393 : offs += conn_foot_tot;
107 :
108 : /* allocate space for conn IDs */
109 393 : offs = fd_ulong_align_up( offs, fd_quic_conn_map_align() );
110 393 : layout->conn_map_off = offs;
111 393 : ulong slot_cnt_bound = (ulong)( FD_QUIC_DEFAULT_SPARSITY * (double)conn_cnt * (double)conn_id_cnt );
112 393 : int lg_slot_cnt = fd_ulong_find_msb( slot_cnt_bound - 1 ) + 1;
113 393 : layout->lg_slot_cnt = lg_slot_cnt;
114 393 : ulong conn_map_footprint = fd_quic_conn_map_footprint( lg_slot_cnt );
115 393 : if( FD_UNLIKELY( !conn_map_footprint ) ) { FD_LOG_WARNING(( "invalid fd_quic_conn_map_footprint" )); return 0UL; }
116 393 : offs += conn_map_footprint;
117 :
118 : /* allocate space for handshake pool */
119 393 : offs = fd_ulong_align_up( offs, fd_quic_tls_hs_pool_align() );
120 393 : layout->hs_pool_off = offs;
121 393 : ulong hs_pool_fp = fd_quic_tls_hs_pool_footprint( limits->handshake_cnt );
122 393 : if( FD_UNLIKELY( !hs_pool_fp ) ) { FD_LOG_WARNING(( "invalid fd_quic_tls_hs_pool_footprint" )); return 0UL; }
123 393 : offs += hs_pool_fp;
124 :
125 : /* allocate space for stream pool */
126 393 : if( stream_pool_cnt && tx_buf_sz ) {
127 336 : offs = fd_ulong_align_up( offs, fd_quic_stream_pool_align() );
128 336 : layout->stream_pool_off = offs;
129 336 : ulong stream_pool_footprint = fd_quic_stream_pool_footprint( stream_pool_cnt, tx_buf_sz );
130 336 : if( FD_UNLIKELY( !stream_pool_footprint ) ) { FD_LOG_WARNING(( "invalid fd_quic_stream_pool_footprint" )); return 0UL; }
131 336 : offs += stream_pool_footprint;
132 336 : } else {
133 57 : layout->stream_pool_off = 0UL;
134 57 : }
135 :
136 : /* allocate space for pkt_meta_pool */
137 393 : if( inflight_frame_cnt ) {
138 393 : offs = fd_ulong_align_up( offs, fd_quic_pkt_meta_pool_align() );
139 393 : layout->pkt_meta_pool_off = offs;
140 393 : ulong pkt_meta_footprint = fd_quic_pkt_meta_pool_footprint( inflight_frame_cnt );
141 393 : if( FD_UNLIKELY( !pkt_meta_footprint ) ) { FD_LOG_WARNING(( "invalid fd_quic_pkt_meta_pool_footprint" )); return 0UL; }
142 393 : offs += pkt_meta_footprint;
143 393 : } else {
144 0 : layout->pkt_meta_pool_off = 0UL;
145 0 : }
146 :
147 : /* allocate space for quic_log_buf */
148 393 : offs = fd_ulong_align_up( offs, fd_quic_log_buf_align() );
149 393 : layout->log_off = offs;
150 393 : ulong log_footprint = fd_quic_log_buf_footprint( log_depth );
151 393 : if( FD_UNLIKELY( !log_footprint ) ) { FD_LOG_WARNING(( "invalid fd_quic_log_buf_footprint for depth %lu", log_depth )); return 0UL; }
152 393 : offs += log_footprint;
153 :
154 : /* allocate space for service timers */
155 393 : offs = fd_ulong_align_up( offs, fd_quic_svc_timers_align() );
156 393 : layout->svc_timers_off = offs;
157 393 : ulong svc_timers_footprint = fd_quic_svc_timers_footprint( limits->conn_cnt );
158 393 : if( FD_UNLIKELY( !svc_timers_footprint ) ) { FD_LOG_WARNING(( "invalid fd_quic_svc_timers_footprint" )); return 0UL; }
159 393 : offs += svc_timers_footprint;
160 :
161 393 : return offs;
162 393 : }
163 :
164 : FD_QUIC_API ulong
165 111 : fd_quic_footprint( fd_quic_limits_t const * limits ) {
166 111 : fd_quic_layout_t layout;
167 111 : return fd_quic_footprint_ext( limits, &layout );
168 111 : }
169 :
170 : FD_QUIC_API void *
171 : fd_quic_new( void * mem,
172 57 : fd_quic_limits_t const * limits ) {
173 :
174 : /* Argument checks */
175 :
176 57 : if( FD_UNLIKELY( !mem ) ) {
177 0 : FD_LOG_WARNING(( "NULL mem" ));
178 0 : return NULL;
179 0 : }
180 :
181 57 : ulong align = fd_quic_align();
182 57 : if( FD_UNLIKELY( !fd_ulong_is_aligned( (ulong)mem, align ) ) ) {
183 0 : FD_LOG_WARNING(( "misaligned mem" ));
184 0 : return NULL;
185 0 : }
186 :
187 57 : if( FD_UNLIKELY( !limits ) ) {
188 0 : FD_LOG_WARNING(( "NULL limits" ));
189 0 : return NULL;
190 0 : }
191 :
192 57 : if( FD_UNLIKELY( ( limits->conn_cnt ==0UL )
193 57 : | ( limits->conn_cnt >=UINT_MAX )
194 57 : | ( limits->handshake_cnt ==0UL )
195 57 : | ( limits->inflight_frame_cnt==0UL ) ) ) {
196 0 : FD_LOG_WARNING(( "invalid limits" ));
197 0 : return NULL;
198 0 : }
199 :
200 57 : fd_quic_layout_t layout;
201 57 : ulong footprint = fd_quic_footprint_ext( limits, &layout );
202 57 : if( FD_UNLIKELY( !footprint ) ) {
203 0 : FD_LOG_WARNING(( "invalid footprint for config" ));
204 0 : return NULL;
205 0 : }
206 :
207 57 : fd_quic_t * quic = (fd_quic_t *)mem;
208 :
209 : /* Clear fd_quic_t memory region */
210 57 : fd_memset( quic, 0, footprint );
211 :
212 : /* Defaults */
213 57 : quic->config.idle_timeout = FD_QUIC_DEFAULT_IDLE_TIMEOUT;
214 57 : quic->config.ack_delay = FD_QUIC_DEFAULT_ACK_DELAY;
215 57 : quic->config.retry_ttl = FD_QUIC_DEFAULT_RETRY_TTL;
216 57 : quic->config.tls_hs_ttl = FD_QUIC_DEFAULT_TLS_HS_TTL;
217 :
218 : /* Copy layout descriptors */
219 57 : quic->limits = *limits;
220 57 : quic->layout = layout;
221 :
222 : /* Init log buffer (persists across init calls) */
223 57 : void * shmlog = (void *)( (ulong)quic + quic->layout.log_off );
224 57 : if( FD_UNLIKELY( !fd_quic_log_buf_new( shmlog, limits->log_depth ) ) ) {
225 0 : return NULL;
226 0 : }
227 :
228 57 : FD_COMPILER_MFENCE();
229 57 : quic->magic = FD_QUIC_MAGIC;
230 57 : FD_COMPILER_MFENCE();
231 :
232 57 : return quic;
233 57 : }
234 :
235 : FD_QUIC_API fd_quic_limits_t *
236 : fd_quic_limits_from_env( int * pargc,
237 : char *** pargv,
238 0 : fd_quic_limits_t * limits ) {
239 :
240 0 : if( FD_UNLIKELY( !limits ) ) return NULL;
241 :
242 0 : limits->conn_cnt = fd_env_strip_cmdline_ulong( pargc, pargv, "--quic-conns", "QUIC_CONN_CNT", 512UL );
243 0 : limits->conn_id_cnt = fd_env_strip_cmdline_ulong( pargc, pargv, "--quic-conn-ids", "QUIC_CONN_ID_CNT", 16UL );
244 0 : limits->stream_pool_cnt = fd_env_strip_cmdline_uint ( pargc, pargv, "--quic-streams", "QUIC_STREAM_CNT", 8UL );
245 0 : limits->handshake_cnt = fd_env_strip_cmdline_uint ( pargc, pargv, "--quic-handshakes", "QUIC_HANDSHAKE_CNT", 512UL );
246 0 : limits->inflight_frame_cnt = fd_env_strip_cmdline_ulong( pargc, pargv, "--quic-inflight-pkts", "QUIC_MAX_INFLIGHT_PKTS", 2500UL );
247 0 : limits->tx_buf_sz = fd_env_strip_cmdline_ulong( pargc, pargv, "--quic-tx-buf-sz", "QUIC_TX_BUF_SZ", 4096UL );
248 :
249 0 : return limits;
250 0 : }
251 :
252 : FD_QUIC_API fd_quic_config_t *
253 : fd_quic_config_from_env( int * pargc,
254 : char *** pargv,
255 0 : fd_quic_config_t * cfg ) {
256 :
257 0 : if( FD_UNLIKELY( !cfg ) ) return NULL;
258 :
259 0 : char const * keylog_file = fd_env_strip_cmdline_cstr( pargc, pargv, NULL, "SSLKEYLOGFILE", NULL );
260 0 : long idle_timeout_ms = fd_env_strip_cmdline_long( pargc, pargv, "--idle-timeout", NULL, 3000UL );
261 0 : ulong initial_rx_max_stream_data = fd_env_strip_cmdline_ulong(
262 0 : pargc,
263 0 : pargv,
264 0 : "--quic-initial-rx-max-stream-data",
265 0 : "QUIC_INITIAL_RX_MAX_STREAM_DATA",
266 0 : FD_QUIC_DEFAULT_INITIAL_RX_MAX_STREAM_DATA
267 0 : );
268 0 : cfg->retry = fd_env_strip_cmdline_contains( pargc, pargv, "--quic-retry" );
269 :
270 0 : if( keylog_file ) {
271 0 : fd_cstr_ncpy( cfg->keylog_file, keylog_file, sizeof(cfg->keylog_file) );
272 0 : } else {
273 0 : cfg->keylog_file[0]='\0';
274 0 : }
275 :
276 0 : cfg->idle_timeout = idle_timeout_ms * (long)1e6;
277 0 : cfg->initial_rx_max_stream_data = initial_rx_max_stream_data;
278 :
279 0 : return cfg;
280 0 : }
281 :
282 : FD_QUIC_API fd_aio_t const *
283 48 : fd_quic_get_aio_net_rx( fd_quic_t * quic ) {
284 48 : fd_aio_new( &quic->aio_rx, quic, fd_quic_aio_cb_receive );
285 48 : return &quic->aio_rx;
286 48 : }
287 :
288 : FD_QUIC_API void
289 : fd_quic_set_aio_net_tx( fd_quic_t * quic,
290 198 : fd_aio_t const * aio_tx ) {
291 :
292 198 : if( aio_tx ) {
293 156 : quic->aio_tx = *aio_tx;
294 156 : } else {
295 42 : memset( &quic->aio_tx, 0, sizeof(fd_aio_t) );
296 42 : }
297 198 : }
298 :
299 : /* initialize everything that mutates during runtime */
300 : static void
301 6924520 : fd_quic_stream_init( fd_quic_stream_t * stream ) {
302 6924520 : stream->context = NULL;
303 :
304 6924520 : stream->unacked_low = 0;
305 6924520 : stream->tx_buf.head = 0;
306 6924520 : stream->tx_sent = 0;
307 :
308 6924520 : stream->stream_flags = 0;
309 : /* don't update next here, since it's still in use */
310 :
311 6924520 : stream->state = 0;
312 :
313 6924520 : stream->tx_max_stream_data = 0;
314 6924520 : stream->tx_tot_data = 0;
315 :
316 6924520 : stream->rx_tot_data = 0;
317 :
318 6924520 : stream->upd_pkt_number = 0;
319 6924520 : }
320 :
321 : FD_QUIC_API fd_quic_t *
322 57 : fd_quic_join( void * shquic ) {
323 :
324 57 : if( FD_UNLIKELY( !shquic ) ) {
325 0 : FD_LOG_WARNING(( "null shquic" ));
326 0 : return NULL;
327 0 : }
328 57 : if( FD_UNLIKELY( !fd_ulong_is_aligned( (ulong)shquic, FD_QUIC_ALIGN ) ) ) {
329 0 : FD_LOG_WARNING(( "misaligned quic" ));
330 0 : return NULL;
331 0 : }
332 :
333 57 : fd_quic_t * quic = (fd_quic_t *)shquic;
334 57 : if( FD_UNLIKELY( quic->magic != FD_QUIC_MAGIC ) ) {
335 0 : FD_LOG_WARNING(( "bad magic" ));
336 0 : return NULL;
337 0 : }
338 :
339 57 : return quic;
340 57 : }
341 :
342 : FD_QUIC_API void *
343 51 : fd_quic_leave( fd_quic_t * quic ) {
344 51 : return (void *)quic;
345 51 : }
346 :
347 : FD_QUIC_API fd_quic_t *
348 180 : fd_quic_init( fd_quic_t * quic ) {
349 :
350 180 : fd_quic_limits_t const * limits = &quic->limits;
351 180 : fd_quic_config_t * config = &quic->config;
352 :
353 180 : if( FD_UNLIKELY( !config->role ) ) { FD_LOG_WARNING(( "cfg.role not set" )); return NULL; }
354 180 : if( FD_UNLIKELY( !config->idle_timeout ) ) { FD_LOG_WARNING(( "zero cfg.idle_timeout" )); return NULL; }
355 180 : if( FD_UNLIKELY( !config->ack_delay ) ) { FD_LOG_WARNING(( "zero cfg.ack_delay" )); return NULL; }
356 180 : if( FD_UNLIKELY( !config->retry_ttl ) ) { FD_LOG_WARNING(( "zero cfg.retry_ttl" )); return NULL; }
357 :
358 180 : do {
359 180 : ulong x = 0U;
360 5940 : for( ulong i=0UL; i<32UL; i++ ) x |= quic->config.identity_public_key[i];
361 :
362 180 : if( FD_UNLIKELY( !x ) ) {
363 0 : FD_LOG_WARNING(( "cfg.identity_public_key not set" ));
364 0 : return NULL;
365 0 : }
366 180 : } while(0);
367 :
368 180 : switch( config->role ) {
369 90 : case FD_QUIC_ROLE_SERVER:
370 90 : if( FD_UNLIKELY( config->keep_alive ) ) { FD_LOG_WARNING(( "server keep-alive not supported" )); return NULL; }
371 90 : break;
372 90 : case FD_QUIC_ROLE_CLIENT:
373 90 : break;
374 0 : default:
375 0 : FD_LOG_WARNING(( "invalid cfg.role" ));
376 0 : return NULL;
377 180 : }
378 :
379 180 : if( FD_UNLIKELY( !config->ack_threshold ) ) {
380 9 : config->ack_threshold = FD_QUIC_DEFAULT_ACK_THRESHOLD;
381 9 : }
382 :
383 180 : fd_quic_layout_t layout = {0};
384 180 : if( FD_UNLIKELY( !fd_quic_footprint_ext( &quic->limits, &layout ) ) ) {
385 0 : FD_LOG_CRIT(( "fd_quic_footprint_ext failed" ));
386 0 : }
387 180 : if( FD_UNLIKELY( 0!=memcmp( &layout, &quic->layout, sizeof(fd_quic_layout_t) ) ) ) {
388 0 : FD_LOG_HEXDUMP_WARNING(( "saved layout", &quic->layout, sizeof(fd_quic_layout_t) ));
389 0 : FD_LOG_HEXDUMP_WARNING(( "derived layout", &layout, sizeof(fd_quic_layout_t) ));
390 0 : FD_LOG_CRIT(( "fd_quic_layout changed. Memory corruption?" ));
391 0 : }
392 :
393 : /* Reset state */
394 :
395 180 : fd_quic_state_t * state = fd_quic_get_state( quic );
396 180 : memset( state, 0, sizeof(fd_quic_state_t) );
397 :
398 180 : void * shmlog = (void *)( (ulong)quic + layout.log_off );
399 180 : if( FD_UNLIKELY( !fd_quic_log_tx_join( state->log_tx, shmlog ) ) ) {
400 0 : FD_LOG_CRIT(( "fd_quic_log_tx_join failed, indicating memory corruption" ));
401 0 : }
402 :
403 : /* State: Initialize packet meta pool */
404 180 : if( layout.pkt_meta_pool_off ) {
405 180 : ulong pkt_meta_cnt = limits->inflight_frame_cnt;
406 180 : ulong pkt_meta_laddr = (ulong)quic + layout.pkt_meta_pool_off;
407 180 : fd_quic_pkt_meta_t * pkt_meta_pool = fd_quic_pkt_meta_pool_new( (void*)pkt_meta_laddr, pkt_meta_cnt );
408 180 : state->pkt_meta_pool = fd_quic_pkt_meta_pool_join( pkt_meta_pool );
409 180 : fd_quic_pkt_meta_ds_init_pool( pkt_meta_pool, pkt_meta_cnt );
410 180 : }
411 :
412 : /* State: initialize each connection, and add to free list */
413 :
414 180 : ulong conn_laddr = (ulong)quic + layout.conns_off;
415 :
416 : /* used for indexing */
417 180 : state->conn_base = conn_laddr;
418 180 : state->conn_sz = layout.conn_footprint;
419 :
420 : /* initialize free_conns */
421 180 : state->free_conn_list = 0;
422 :
423 180 : fd_quic_conn_t _catch[1] = {{.conn_idx = UINT_MAX }};
424 180 : fd_quic_conn_t * last = _catch;
425 301152 : for( ulong j = 0; j < limits->conn_cnt; ++j ) {
426 300972 : void * conn_mem = (void *)( conn_laddr );
427 300972 : conn_laddr += layout.conn_footprint;
428 :
429 300972 : fd_quic_conn_t * conn = fd_quic_conn_new( conn_mem, quic, limits );
430 300972 : if( FD_UNLIKELY( !conn ) ) {
431 0 : FD_LOG_WARNING(( "NULL conn" ));
432 0 : return NULL;
433 0 : }
434 :
435 : /* used for indexing */
436 300972 : conn->conn_idx = (uint)j;
437 300972 : conn->free_conn_next = UINT_MAX;
438 :
439 : /* add to free list */
440 300972 : last->free_conn_next = (uint)j;
441 :
442 300972 : last = conn;
443 300972 : }
444 :
445 : /* State: Initialize conn ID map */
446 :
447 180 : ulong conn_map_laddr = (ulong)quic + layout.conn_map_off;
448 180 : state->conn_map = fd_quic_conn_map_join( fd_quic_conn_map_new( (void *)conn_map_laddr, layout.lg_slot_cnt, (ulong)fd_tickcount() ) );
449 180 : if( FD_UNLIKELY( !state->conn_map ) ) {
450 0 : FD_LOG_WARNING(( "NULL conn_map" ));
451 0 : return NULL;
452 0 : }
453 :
454 : /* State: Initialize service queue */
455 180 : ulong svc_base = (ulong)quic + layout.svc_timers_off;
456 180 : state->svc_timers = fd_quic_svc_timers_init( (void *)svc_base, limits->conn_cnt, state );
457 :
458 : /* Check TX AIO */
459 :
460 180 : if( FD_UNLIKELY( !quic->aio_tx.send_func ) ) {
461 0 : FD_LOG_WARNING(( "NULL aio_tx" ));
462 0 : return NULL;
463 0 : }
464 :
465 : /* State: Initialize TLS */
466 :
467 180 : fd_quic_tls_cfg_t tls_cfg = {
468 180 : .max_concur_handshakes = limits->handshake_cnt,
469 :
470 : /* set up callbacks */
471 180 : .secret_cb = fd_quic_tls_cb_secret,
472 180 : .handshake_complete_cb = fd_quic_tls_cb_handshake_complete,
473 180 : .peer_params_cb = fd_quic_tls_cb_peer_params,
474 :
475 180 : .signer = {
476 180 : .ctx = config->sign_ctx,
477 180 : .sign_fn = config->sign,
478 180 : },
479 :
480 180 : .cert_public_key = quic->config.identity_public_key,
481 :
482 180 : .alpn = config->alpn,
483 180 : .alpn_sz = config->alpn_sz,
484 180 : };
485 :
486 : /* State: Initialize handshake pool */
487 :
488 180 : if( FD_UNLIKELY( !fd_quic_tls_new( state->tls, &tls_cfg ) ) ) {
489 0 : FD_DEBUG( FD_LOG_WARNING( ( "fd_quic_tls_new failed" ) ) );
490 0 : return NULL;
491 0 : }
492 :
493 180 : ulong hs_pool_laddr = (ulong)quic + layout.hs_pool_off;
494 180 : fd_quic_tls_hs_t * hs_pool = fd_quic_tls_hs_pool_join( fd_quic_tls_hs_pool_new( (void *)hs_pool_laddr, limits->handshake_cnt ) );
495 180 : if( FD_UNLIKELY( !hs_pool ) ) {
496 0 : FD_LOG_WARNING(( "fd_quic_tls_hs_pool_new failed" ));
497 0 : return NULL;
498 0 : }
499 180 : state->hs_pool = hs_pool;
500 :
501 : /* State: Initialize TLS handshake cache */
502 180 : if( FD_UNLIKELY( !fd_quic_tls_hs_cache_join( fd_quic_tls_hs_cache_new( &state->hs_cache ) ) ) ) {
503 0 : FD_LOG_WARNING(( "fd_quic_tls_hs_cache_new failed" ));
504 0 : return NULL;
505 0 : }
506 :
507 :
508 180 : if( layout.stream_pool_off ) {
509 168 : ulong stream_pool_cnt = limits->stream_pool_cnt;
510 168 : ulong tx_buf_sz = limits->tx_buf_sz;
511 168 : ulong stream_pool_laddr = (ulong)quic + layout.stream_pool_off;
512 168 : state->stream_pool = fd_quic_stream_pool_new( (void*)stream_pool_laddr, stream_pool_cnt, tx_buf_sz );
513 168 : }
514 :
515 : /* generate a secure random number as seed for fd_rng */
516 180 : uint rng_seed = 0;
517 180 : int rng_seed_ok = !!fd_rng_secure( &rng_seed, sizeof(rng_seed) );
518 180 : if( FD_UNLIKELY( !rng_seed_ok ) ) {
519 0 : FD_LOG_ERR(( "fd_rng_secure failed" ));
520 0 : }
521 180 : fd_rng_new( state->_rng, rng_seed, 0UL );
522 :
523 : /* use rng to generate secret bytes for future RETRY token generation */
524 180 : int rng1_ok = !!fd_rng_secure( state->retry_secret, FD_QUIC_RETRY_SECRET_SZ );
525 180 : int rng2_ok = !!fd_rng_secure( state->retry_iv, FD_QUIC_RETRY_IV_SZ );
526 180 : if( FD_UNLIKELY( !rng1_ok || !rng2_ok ) ) {
527 0 : FD_LOG_ERR(( "fd_rng_secure failed" ));
528 0 : return NULL;
529 0 : }
530 :
531 : /* Initialize transport params */
532 :
533 180 : fd_quic_transport_params_t * tp = &state->transport_params;
534 :
535 : /* initial max streams is zero */
536 : /* we will send max_streams and max_data frames later to allow the peer to */
537 : /* send us data */
538 180 : ulong initial_max_streams_uni = quic->config.role==FD_QUIC_ROLE_SERVER ? 1UL<<60 : 0;
539 180 : ulong initial_max_stream_data = config->initial_rx_max_stream_data;
540 :
541 180 : long max_ack_delay_ns = config->ack_delay * 2L;
542 180 : long max_ack_delay_ms = max_ack_delay_ns / (long)1e6;
543 :
544 180 : long idle_timeout_ns = config->idle_timeout;
545 180 : long idle_timeout_ms = idle_timeout_ns / (long)1e6;
546 :
547 180 : memset( tp, 0, sizeof(fd_quic_transport_params_t) );
548 180 : FD_QUIC_TRANSPORT_PARAM_SET( tp, max_idle_timeout_ms, (ulong)idle_timeout_ms );
549 180 : FD_QUIC_TRANSPORT_PARAM_SET( tp, max_udp_payload_size, FD_QUIC_MAX_PAYLOAD_SZ ); /* TODO */
550 180 : FD_QUIC_TRANSPORT_PARAM_SET( tp, initial_max_data, (1UL<<62)-1UL );
551 180 : FD_QUIC_TRANSPORT_PARAM_SET( tp, initial_max_stream_data_uni, initial_max_stream_data );
552 180 : FD_QUIC_TRANSPORT_PARAM_SET( tp, initial_max_streams_bidi, 0 );
553 180 : FD_QUIC_TRANSPORT_PARAM_SET( tp, initial_max_streams_uni, initial_max_streams_uni );
554 180 : FD_QUIC_TRANSPORT_PARAM_SET( tp, ack_delay_exponent, 0 );
555 180 : FD_QUIC_TRANSPORT_PARAM_SET( tp, max_ack_delay, (ulong)max_ack_delay_ms );
556 180 : /* */tp->disable_active_migration_present = 1;
557 180 : if( config->max_datagram_frame_size && quic->cb.datagram_rx ) {
558 6 : FD_QUIC_TRANSPORT_PARAM_SET( tp, max_datagram_frame_size, config->max_datagram_frame_size );
559 6 : }
560 :
561 : /* Compute max inflight pkt cnt per conn */
562 180 : state->max_inflight_frame_cnt_conn = limits->inflight_frame_cnt - limits->min_inflight_frame_cnt_conn * (limits->conn_cnt-1);
563 :
564 180 : return quic;
565 180 : }
566 :
567 : FD_QUIC_API void
568 : fd_quic_set_identity_public_key( fd_quic_t * quic,
569 0 : uchar const public_key[ static 32 ] ) {
570 0 : memcpy( quic->config.identity_public_key, public_key, 32UL );
571 0 : fd_quic_state_t * state = fd_quic_get_state( quic );
572 0 : fd_tls_t * tls = &state->tls->tls;
573 0 : memcpy( tls->cert_public_key, public_key, 32UL );
574 0 : fd_x509_mock_cert( tls->cert_x509, tls->cert_public_key );
575 0 : }
576 :
577 : /* fd_quic_enc_level_to_pn_space maps of encryption level in [0,4) to
578 : packet number space. */
579 : static uint
580 28233322 : fd_quic_enc_level_to_pn_space( uint enc_level ) {
581 : /* TODO improve this map */
582 28233322 : static uchar const el2pn_map[] = { 0, 2, 1, 2 };
583 :
584 28233322 : if( FD_UNLIKELY( enc_level >= 4U ) )
585 0 : FD_LOG_ERR(( "fd_quic_enc_level_to_pn_space called with invalid enc_level" ));
586 :
587 28233322 : return el2pn_map[ enc_level ];
588 28233322 : }
589 :
590 : /* This code is directly from rfc9000 A.3 */
591 : FD_FN_CONST ulong
592 : fd_quic_reconstruct_pkt_num( ulong pktnum_comp,
593 : ulong pktnum_sz,
594 7100280 : ulong exp_pkt_number ) {
595 7100280 : ulong pn_nbits = pktnum_sz << 3u;
596 7100280 : ulong pn_win = 1ul << pn_nbits;
597 7100280 : ulong pn_hwin = pn_win >> 1ul;
598 7100280 : ulong pn_mask = pn_win - 1ul;
599 : // The incoming packet number should be greater than
600 : // exp_pkt_number - pn_hwin and less than or equal to
601 : // exp_pkt_number + pn_hwin
602 : //
603 : // This means we cannot just strip the trailing bits from
604 : // exp_pkt_number and add the truncated_pn because that might
605 : // yield a value outside the window.
606 : //
607 : // The following code calculates a candidate value and
608 : // makes sure it's within the packet number window.
609 : // Note the extra checks to prevent overflow and underflow.
610 7100280 : ulong candidate_pn = ( exp_pkt_number & ~pn_mask ) | pktnum_comp;
611 7100280 : if( candidate_pn + pn_hwin <= exp_pkt_number &&
612 7100280 : candidate_pn + pn_win < ( 1ul << 62ul ) ) {
613 0 : return candidate_pn + pn_win;
614 0 : }
615 :
616 7100280 : if( candidate_pn > exp_pkt_number + pn_hwin &&
617 7100280 : candidate_pn >= pn_win ) {
618 0 : return candidate_pn - pn_win;
619 0 : }
620 :
621 7100280 : return candidate_pn;
622 7100280 : }
623 :
624 : /* fd_quic_svc_prep_schedule sets conn->svc_meta.next_timeout to
625 : min of current and provided expiry time. */
626 : static inline void
627 : fd_quic_svc_prep_schedule( fd_quic_conn_t * conn,
628 160762277 : long expiry ) {
629 160762277 : conn->svc_meta.next_timeout = fd_long_min( conn->svc_meta.next_timeout, expiry );
630 160762277 : }
631 :
632 : /* fd_quic_svc_prep_schedule_now sets conn->svc_meta.next_timeout to
633 : current time. For when state is not already available */
634 : static inline void
635 6942763 : fd_quic_svc_prep_schedule_now( fd_quic_conn_t * conn ) {
636 6942763 : fd_quic_state_t * state = fd_quic_get_state( conn->quic );
637 6942763 : fd_quic_svc_prep_schedule( conn, state->now );
638 6942763 : }
639 :
640 : /* Scheduling helper. Retrieves timers from conn to call schedule */
641 : static inline void
642 6930631 : fd_quic_svc_schedule1( fd_quic_conn_t * conn ) {
643 6930631 : fd_quic_state_t * state = fd_quic_get_state( conn->quic );
644 6930631 : fd_quic_svc_timers_schedule( state->svc_timers, conn, state->now );
645 6930631 : }
646 :
647 : /* Validation Helper */
648 : static inline void
649 146615451 : svc_cnt_eq_alloc_conn( fd_quic_svc_timers_t * timers, fd_quic_t * quic ) {
650 146615451 : ulong const event_cnt = fd_quic_svc_timers_cnt_events( timers );
651 146615451 : ulong const conn_cnt = quic->metrics.conn_alloc_cnt;
652 146615451 : if( FD_UNLIKELY( event_cnt != conn_cnt ) ) {
653 0 : FD_LOG_CRIT(( "only %lu out of %lu connections are in timer", event_cnt, conn_cnt ));
654 0 : }
655 146615451 : }
656 : /* validates the free conn list doesn't cycle, point nowhere, leak, or point to live conn */
657 : static void
658 123 : fd_quic_conn_free_validate( fd_quic_t * quic ) {
659 123 : fd_quic_state_t * state = fd_quic_get_state( quic );
660 :
661 : /* initialize visited */
662 123 : fd_quic_conn_validate_init( quic );
663 :
664 123 : ulong cnt = 0UL;
665 123 : uint node = state->free_conn_list;
666 765 : while( node!=UINT_MAX ) {
667 642 : FD_TEST( node < quic->limits.conn_cnt );
668 642 : fd_quic_conn_t * conn = fd_quic_conn_at_idx( state, node );
669 642 : FD_TEST( conn->state == FD_QUIC_CONN_STATE_INVALID );
670 642 : conn->visited = 1U;
671 642 : node = conn->free_conn_next;
672 642 : cnt++;
673 642 : FD_TEST( cnt <= quic->limits.conn_cnt );
674 642 : }
675 :
676 300855 : for( ulong j=0UL; j < quic->limits.conn_cnt; j++ ) {
677 300732 : fd_quic_conn_t * conn = fd_quic_conn_at_idx( state, j );
678 300732 : FD_TEST( conn->conn_idx==j );
679 300732 : if( conn->state == FD_QUIC_CONN_STATE_INVALID ) {
680 642 : FD_TEST( conn->visited );
681 300090 : } else {
682 300090 : FD_TEST( !conn->visited );
683 300090 : }
684 300732 : }
685 123 : }
686 :
687 : void
688 123 : fd_quic_state_validate( fd_quic_t * quic ) {
689 123 : fd_quic_state_t * state = fd_quic_get_state( quic );
690 :
691 : /* init visited for svc_timers_validate to use */
692 123 : fd_quic_conn_validate_init( quic );
693 123 : FD_TEST( fd_quic_svc_timers_validate( state->svc_timers, quic ) );
694 :
695 123 : fd_quic_conn_free_validate( quic );
696 123 : }
697 :
698 : fd_quic_conn_t *
699 : fd_quic_conn_query( fd_quic_conn_map_t * map,
700 7106343 : ulong conn_id ) {
701 7106343 : fd_quic_conn_map_t sentinel = {0};
702 7106343 : if( !conn_id ) return NULL;
703 7106343 : fd_quic_conn_map_t * entry = fd_quic_conn_map_query( map, conn_id, &sentinel );
704 7106343 : fd_quic_conn_t * conn = entry->conn;
705 7106343 : if( conn ) {
706 7094247 : if( FD_UNLIKELY( conn->state==FD_QUIC_CONN_STATE_INVALID ) ) {
707 0 : FD_LOG_CRIT(( "Conn ID %016lx at %p is in map but in free state", conn_id, (void *)conn ));
708 0 : }
709 7094247 : }
710 7106343 : return conn;
711 7106343 : }
712 :
713 : /* Helpers for generating fd_quic_log entries */
714 :
715 : static fd_quic_log_hdr_t
716 0 : fd_quic_log_conn_hdr( fd_quic_conn_t const * conn ) {
717 0 : fd_quic_log_hdr_t hdr = {
718 0 : .conn_id = conn->our_conn_id,
719 0 : .flags = 0
720 0 : };
721 0 : return hdr;
722 0 : }
723 :
724 : static fd_quic_log_hdr_t
725 : fd_quic_log_full_hdr( fd_quic_conn_t const * conn,
726 15 : fd_quic_pkt_t const * pkt ) {
727 15 : fd_quic_log_hdr_t hdr = {
728 15 : .conn_id = conn->our_conn_id,
729 15 : .pkt_num = pkt->pkt_number,
730 15 : .ip4_saddr = pkt->ip4->saddr,
731 15 : .udp_sport = pkt->udp->net_sport,
732 15 : .enc_level = (uchar)pkt->enc_level,
733 15 : .flags = 0
734 15 : };
735 15 : return hdr;
736 15 : }
737 :
738 : inline static void
739 : fd_quic_set_conn_state( fd_quic_conn_t * conn,
740 372834 : uint state ) {
741 372834 : FD_COMPILER_MFENCE();
742 372834 : uint old_state = conn->state;
743 372834 : conn->quic->metrics.conn_state_cnt[ old_state ]--;
744 372834 : conn->quic->metrics.conn_state_cnt[ state ]++;
745 372834 : conn->state = state;
746 372834 : FD_COMPILER_MFENCE();
747 372834 : }
748 :
749 :
750 : /* fd_quic_conn_error sets the connection state to aborted. This does
751 : not destroy the connection object. Rather, it will eventually cause
752 : the connection to be freed during a later fd_quic_service call.
753 : reason is an RFC 9000 QUIC error code. error_line is the source line
754 : of code in fd_quic.c */
755 :
756 : static void
757 : fd_quic_conn_error1( fd_quic_conn_t * conn,
758 15 : uint reason ) {
759 15 : if( FD_UNLIKELY( !conn || conn->state == FD_QUIC_CONN_STATE_DEAD ) ) return;
760 :
761 15 : fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_ABORT );
762 15 : conn->reason = reason;
763 :
764 : /* set connection to be serviced ASAP */
765 15 : fd_quic_svc_prep_schedule_now( conn );
766 15 : fd_quic_svc_schedule1( conn );
767 15 : }
768 :
769 : static void
770 : fd_quic_conn_error( fd_quic_conn_t * conn,
771 : uint reason,
772 0 : uint error_line ) {
773 0 : fd_quic_conn_error1( conn, reason );
774 :
775 0 : fd_quic_state_t * state = fd_quic_get_state( conn->quic );
776 :
777 0 : ulong sig = fd_quic_log_sig( FD_QUIC_EVENT_CONN_QUIC_CLOSE );
778 0 : fd_quic_log_error_t * frame = fd_quic_log_tx_prepare( state->log_tx );
779 0 : *frame = (fd_quic_log_error_t) {
780 0 : .hdr = fd_quic_log_conn_hdr( conn ),
781 0 : .code = { reason, 0UL },
782 0 : .src_file = "fd_quic.c",
783 0 : .src_line = error_line,
784 0 : };
785 0 : fd_quic_log_tx_submit( state->log_tx, sizeof(fd_quic_log_error_t), sig, (long)state->now );
786 0 : }
787 :
788 : static void
789 : fd_quic_frame_error( fd_quic_frame_ctx_t const * ctx,
790 : uint reason,
791 15 : uint error_line ) {
792 15 : fd_quic_t * quic = ctx->quic;
793 15 : fd_quic_conn_t * conn = ctx->conn;
794 15 : fd_quic_pkt_t const * pkt = ctx->pkt;
795 15 : fd_quic_state_t * state = fd_quic_get_state( quic );
796 :
797 15 : fd_quic_conn_error1( conn, reason );
798 :
799 15 : uint tls_reason = 0U;
800 15 : if( conn->tls_hs ) tls_reason = conn->tls_hs->hs.base.reason;
801 :
802 15 : ulong sig = fd_quic_log_sig( FD_QUIC_EVENT_CONN_QUIC_CLOSE );
803 15 : fd_quic_log_error_t * frame = fd_quic_log_tx_prepare( state->log_tx );
804 15 : *frame = (fd_quic_log_error_t) {
805 15 : .hdr = fd_quic_log_full_hdr( conn, pkt ),
806 15 : .code = { reason, tls_reason },
807 15 : .src_file = "fd_quic.c",
808 15 : .src_line = error_line,
809 15 : };
810 15 : fd_quic_log_tx_submit( state->log_tx, sizeof(fd_quic_log_error_t), sig, state->now );
811 15 : }
812 :
813 : /* returns the encoding level we should use for the next tx quic packet
814 : or all 1's if nothing to tx */
815 : static uint
816 14177736 : fd_quic_tx_enc_level( fd_quic_conn_t * conn, int acks ) {
817 14177736 : uint app_pn_space = fd_quic_enc_level_to_pn_space( fd_quic_enc_level_appdata_id );
818 14177736 : ulong app_pkt_number = conn->pkt_number[app_pn_space];
819 :
820 : /* fd_quic_tx_enc_level( ... )
821 : check status - if closing, set based on handshake complete
822 : check for acks
823 : find lowest enc level
824 : check for hs_data
825 : find lowest enc level
826 : if any, use lowest
827 : else
828 : if stream data, use 1-rtt
829 : else
830 : nothing to do */
831 :
832 : /* check status */
833 14177736 : switch( conn->state ) {
834 0 : case FD_QUIC_CONN_STATE_DEAD:
835 : /* do not send on dead connection at all */
836 0 : return ~0u;
837 :
838 6 : case FD_QUIC_CONN_STATE_ABORT:
839 12042 : case FD_QUIC_CONN_STATE_CLOSE_PENDING:
840 : /* use handshake or app enc level depending on handshake complete */
841 12042 : if( !(conn->flags & FD_QUIC_CONN_FLAGS_CLOSE_SENT ) ) {
842 6021 : if( conn->handshake_complete ) {
843 6018 : return fd_quic_enc_level_appdata_id;
844 6018 : } else if( fd_uint_extract_bit( conn->keys_avail, fd_quic_enc_level_handshake_id ) ) {
845 0 : return fd_quic_enc_level_handshake_id;
846 3 : } else if( fd_uint_extract_bit( conn->keys_avail, fd_quic_enc_level_initial_id ) ) {
847 3 : return fd_quic_enc_level_initial_id;
848 3 : }
849 6021 : }
850 6021 : return ~0u;
851 :
852 : /* TODO consider this optimization... but we want to ack all handshakes, even if there is stream_data */
853 14099112 : case FD_QUIC_CONN_STATE_ACTIVE:
854 14099112 : if( FD_LIKELY( !conn->tls_hs ) ) {
855 : /* optimization for case where we have stream data to send */
856 :
857 : /* find stream data to send */
858 14086974 : fd_quic_stream_t * sentinel = conn->send_streams;
859 14086974 : fd_quic_stream_t * stream = sentinel->next;
860 14086974 : if( !stream->sentinel && stream->upd_pkt_number >= app_pkt_number ) {
861 6935461 : return fd_quic_enc_level_appdata_id;
862 6935461 : }
863 14086974 : }
864 14177736 : }
865 :
866 : /* pick enc_level of oldest ACK not yet sent */
867 7230233 : fd_quic_ack_gen_t * ack_gen = conn->ack_gen;
868 7230233 : fd_quic_ack_t const * oldest_ack = fd_quic_ack_queue_ele( ack_gen, ack_gen->tail );
869 7230233 : uint ack_enc_level = oldest_ack->enc_level; /* speculative load (might be invalid) */
870 7230233 : if( (ack_gen->head != ack_gen->tail) & acks & fd_uint_extract_bit( conn->keys_avail, (int)ack_enc_level ) ) {
871 134477 : return ack_enc_level;
872 134477 : }
873 :
874 : /* Check for handshake data to send */
875 7095756 : uint min_keyed_enc_level = (uint)fd_uint_find_lsb_w_default( conn->keys_avail, (int)~0u );
876 7095756 : if( FD_UNLIKELY( conn->tls_hs ) ) {
877 54573 : fd_quic_tls_hs_data_t * hs_data = NULL;
878 :
879 : /* Starting at min_keyed_enc_level guarantees keys are avail if we return in this loop
880 : - The discard order specified by RFC 9001 Section 4.9 prevents gaps in key availability
881 : - get_hs_data returning non-null means keys were avail at some point for this enc_level */
882 175740 : for( uint i = min_keyed_enc_level; i < 4; ++i ) {
883 139380 : hs_data = fd_quic_tls_get_hs_data( conn->tls_hs, i );
884 139380 : if( hs_data ) {
885 : /* offset within stream */
886 60585 : ulong offset = conn->hs_sent_bytes[i];
887 : /* skip packets we've sent */
888 163413 : while( hs_data && hs_data->offset + hs_data->data_sz <= offset ) {
889 102828 : hs_data = fd_quic_tls_get_next_hs_data( conn->tls_hs, hs_data );
890 102828 : }
891 60585 : if( hs_data ) {
892 18213 : return i;
893 18213 : }
894 60585 : }
895 139380 : }
896 54573 : }
897 :
898 : /* handshake done? */
899 7077543 : if( FD_UNLIKELY( conn->handshake_done_send ) ) return fd_quic_enc_level_appdata_id;
900 :
901 : /* find stream data to send */
902 7071477 : fd_quic_stream_t * sentinel = conn->send_streams;
903 7071477 : fd_quic_stream_t * stream = sentinel->next;
904 7071477 : if( (!stream->sentinel) & (stream->upd_pkt_number >= app_pkt_number) & fd_uint_extract_bit( conn->keys_avail, fd_quic_enc_level_appdata_id ) ) {
905 0 : return fd_quic_enc_level_appdata_id;
906 0 : }
907 :
908 : /* only allow 1-RTT "flag" frames when we have the keys, to prevent e.g. early 1-RTT PINGs */
909 7071477 : uint flags_pending = conn->flags & ~(FD_QUIC_CONN_FLAGS_CLOSE_SENT | FD_QUIC_CONN_FLAGS_PING_SENT);
910 7071477 : if( ( flags_pending != 0U )
911 7071477 : & ( conn->upd_pkt_number >= app_pkt_number )
912 7071477 : & fd_uint_extract_bit( conn->keys_avail, fd_quic_enc_level_appdata_id ) ) {
913 6153 : return fd_quic_enc_level_appdata_id;
914 6153 : }
915 :
916 : /* nothing to send */
917 7065324 : return ~0u;
918 7071477 : }
919 :
920 : /* Include frame code generator */
921 :
922 : #include "templ/fd_quic_frame.c"
923 :
924 : /* handle single v1 frames */
925 : /* returns bytes consumed */
926 : ulong
927 : fd_quic_handle_v1_frame( fd_quic_t * quic,
928 : fd_quic_conn_t * conn,
929 : fd_quic_pkt_t * pkt,
930 : uint pkt_type,
931 : uchar const * buf,
932 132679654 : ulong buf_sz ) {
933 132679654 : if( conn->state == FD_QUIC_CONN_STATE_DEAD ) return FD_QUIC_PARSE_FAIL;
934 132679654 : if( FD_UNLIKELY( buf_sz<1UL ) ) return FD_QUIC_PARSE_FAIL;
935 :
936 : /* Frame ID is technically a varint but it's sufficient to look at the
937 : first byte. */
938 132679654 : uint id = buf[0];
939 :
940 132679654 : FD_DTRACE_PROBE_4( quic_handle_frame, id, conn->our_conn_id, pkt_type, pkt->pkt_number );
941 :
942 132679654 : fd_quic_frame_ctx_t frame_context[1] = {{ quic, conn, pkt, 0UL }};
943 132679654 : if( FD_UNLIKELY( !fd_quic_frame_type_allowed( pkt_type, id ) ) ) {
944 0 : FD_DTRACE_PROBE_4( quic_err_frame_not_allowed, id, conn->our_conn_id, pkt_type, pkt->pkt_number );
945 0 : fd_quic_frame_error( frame_context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
946 0 : return FD_QUIC_PARSE_FAIL;
947 0 : }
948 132679654 : quic->metrics.frame_rx_cnt[ fd_quic_frame_metric_id[ id ] ]++;
949 :
950 132679654 : pkt->ack_flag |= fd_uint_if( fd_quic_frame_type_flags[ id ]&FD_QUIC_FRAME_FLAG_N, 0U, ACK_FLAG_RQD );
951 :
952 : /* tail call to frame handler */
953 132679654 : switch( id ) {
954 :
955 0 : # define F(T,MID,NAME,...) \
956 132679654 : case T: return fd_quic_interpret_##NAME##_frame( frame_context, buf, buf_sz );
957 132679654 : FD_QUIC_FRAME_TYPES(F)
958 0 : # undef F
959 :
960 0 : default:
961 : /* FIXME this should be unreachable, but gracefully handle this case as defense-in-depth */
962 : /* unknown frame types are PROTOCOL_VIOLATION errors */
963 0 : FD_DEBUG( FD_LOG_DEBUG(( "unexpected frame type: %u", id )); )
964 0 : fd_quic_frame_error( frame_context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
965 0 : return FD_QUIC_PARSE_FAIL;
966 132679654 : }
967 :
968 132679654 : }
969 :
970 : fd_quic_t *
971 48 : fd_quic_fini( fd_quic_t * quic ) {
972 :
973 48 : if( FD_UNLIKELY( !quic ) ) {
974 0 : FD_LOG_WARNING(("NULL quic"));
975 0 : return NULL;
976 0 : }
977 :
978 : /* Derive memory layout */
979 :
980 48 : fd_quic_layout_t layout = {0};
981 48 : fd_quic_footprint_ext( &quic->limits, &layout );
982 :
983 48 : fd_quic_state_t * state = fd_quic_get_state( quic );
984 :
985 : /* Free conns */
986 :
987 48 : ulong conn_laddr = (ulong)quic + layout.conns_off;
988 426 : for( ulong i=0; i < quic->limits.conn_cnt; i++ ) {
989 378 : fd_quic_conn_t * conn = (fd_quic_conn_t *)( conn_laddr );
990 378 : conn_laddr += layout.conn_footprint;
991 :
992 378 : if( conn->state ) fd_quic_conn_free( quic, conn );
993 378 : }
994 :
995 : /* Deinit TLS */
996 :
997 48 : fd_quic_tls_hs_pool_delete( fd_quic_tls_hs_pool_leave( state->hs_pool ) ); state->hs_pool = NULL;
998 48 : fd_quic_tls_delete( state->tls );
999 48 : fd_quic_tls_hs_cache_delete( fd_quic_tls_hs_cache_leave( &state->hs_cache ) );
1000 :
1001 :
1002 : /* Delete conn ID map */
1003 :
1004 48 : fd_quic_conn_map_delete( fd_quic_conn_map_leave( state->conn_map ) );
1005 48 : state->conn_map = NULL;
1006 :
1007 : /* Clear join-lifetime memory regions */
1008 :
1009 48 : memset( state, 0, sizeof(fd_quic_state_t) );
1010 :
1011 48 : return quic;
1012 48 : }
1013 :
1014 : void *
1015 51 : fd_quic_delete( fd_quic_t * quic ) {
1016 :
1017 51 : if( FD_UNLIKELY( !quic ) ) {
1018 0 : FD_LOG_WARNING(( "NULL quic" ));
1019 0 : return NULL;
1020 0 : }
1021 :
1022 51 : if( FD_UNLIKELY( !fd_ulong_is_aligned( (ulong)quic, fd_quic_align() ) ) ) {
1023 0 : FD_LOG_WARNING(( "misaligned quic" ));
1024 0 : return NULL;
1025 0 : }
1026 :
1027 51 : if( FD_UNLIKELY( quic->magic!=FD_QUIC_MAGIC ) ) {
1028 0 : FD_LOG_WARNING(( "bad magic" ));
1029 0 : return NULL;
1030 0 : }
1031 :
1032 51 : void * shmlog = (void *)( (ulong)quic + quic->layout.log_off );
1033 51 : if( FD_UNLIKELY( !fd_quic_log_buf_delete( shmlog ) ) ) {
1034 0 : FD_LOG_WARNING(( "fd_quic_log_buf_delete failed" ));
1035 0 : return NULL;
1036 0 : }
1037 :
1038 51 : FD_COMPILER_MFENCE();
1039 51 : FD_VOLATILE( quic->magic ) = 0UL;
1040 51 : FD_COMPILER_MFENCE();
1041 :
1042 51 : return (void *)quic;
1043 51 : }
1044 :
1045 : fd_quic_stream_t *
1046 6924520 : fd_quic_conn_new_stream( fd_quic_conn_t * conn ) {
1047 6924520 : if( FD_UNLIKELY( !conn->stream_map ) ) {
1048 : /* QUIC config is receive-only */
1049 0 : return NULL;
1050 0 : }
1051 :
1052 6924520 : fd_quic_t * quic = conn->quic;
1053 6924520 : fd_quic_state_t * state = fd_quic_get_state( quic );
1054 6924520 : if( FD_UNLIKELY( !state->stream_pool ) ) return NULL;
1055 :
1056 6924520 : ulong next_stream_id = conn->tx_next_stream_id;
1057 :
1058 : /* The user is responsible for calling this, for setting limits, */
1059 : /* and for setting stream_pool size */
1060 : /* Only current use cases for QUIC client is for testing */
1061 : /* So leaving this question unanswered for now */
1062 :
1063 : /* peer imposed limit on streams */
1064 6924520 : ulong peer_sup_stream_id = conn->tx_sup_stream_id;
1065 :
1066 : /* is connection inactive */
1067 6924520 : if( FD_UNLIKELY( conn->state != FD_QUIC_CONN_STATE_ACTIVE ||
1068 6924520 : next_stream_id >= peer_sup_stream_id ) ) {
1069 : /* this is a normal condition which occurs whenever we run up to
1070 : the peer advertised limit and represents one form of flow control */
1071 0 : return NULL;
1072 0 : }
1073 :
1074 : /* obtain a stream from stream_pool */
1075 6924520 : fd_quic_stream_t * stream = fd_quic_stream_pool_alloc( state->stream_pool );
1076 :
1077 6924520 : if( FD_UNLIKELY( !stream ) ) {
1078 : /* no streams available in the stream pool */
1079 0 : return NULL;
1080 0 : }
1081 :
1082 : /* add to map of stream ids */
1083 6924520 : fd_quic_stream_map_t * entry = fd_quic_stream_map_insert( conn->stream_map, next_stream_id );
1084 6924520 : if( FD_UNLIKELY( !entry ) ) {
1085 : /* return stream to pool */
1086 0 : fd_quic_stream_pool_free( state->stream_pool, stream );
1087 0 : FD_LOG_INFO(( "stream map insert failed" ));
1088 0 : return NULL;
1089 0 : }
1090 :
1091 6924520 : fd_quic_stream_init( stream );
1092 6924520 : FD_QUIC_STREAM_LIST_INIT_STREAM( stream );
1093 :
1094 : /* stream tx_buf already set */
1095 6924520 : stream->conn = conn;
1096 6924520 : stream->stream_id = next_stream_id;
1097 6924520 : stream->context = NULL;
1098 :
1099 : /* set the max stream data to the appropriate initial value */
1100 6924520 : stream->tx_max_stream_data = conn->tx_initial_max_stream_data_uni;
1101 :
1102 : /* set state depending on stream type */
1103 6924520 : stream->state = FD_QUIC_STREAM_STATE_RX_FIN;
1104 6924520 : stream->stream_flags = 0u;
1105 :
1106 6924520 : memset( stream->tx_ack, 0, fd_quic_stream_tx_ack_bufsz( stream ) );
1107 :
1108 : /* insert into used streams */
1109 6924520 : FD_QUIC_STREAM_LIST_REMOVE( stream );
1110 6924520 : FD_QUIC_STREAM_LIST_INSERT_BEFORE( conn->used_streams, stream );
1111 :
1112 : /* generate a new stream id */
1113 6924520 : conn->tx_next_stream_id = next_stream_id + 4U;
1114 :
1115 : /* assign the stream to the entry */
1116 6924520 : entry->stream = stream;
1117 :
1118 : /* update metrics */
1119 6924520 : quic->metrics.stream_opened_cnt++;
1120 6924520 : quic->metrics.stream_active_cnt++;
1121 :
1122 6924520 : FD_DEBUG( FD_LOG_DEBUG(( "Created stream with ID %lu", next_stream_id )) );
1123 6924520 : return stream;
1124 6924520 : }
1125 :
1126 : int
1127 : fd_quic_stream_send( fd_quic_stream_t * stream,
1128 : void const * data,
1129 : ulong data_sz,
1130 6924592 : int fin ) {
1131 6924592 : if( FD_UNLIKELY( stream->state & FD_QUIC_STREAM_STATE_TX_FIN ) ) {
1132 0 : return FD_QUIC_SEND_ERR_FIN;
1133 0 : }
1134 :
1135 6924592 : fd_quic_conn_t * conn = stream->conn;
1136 :
1137 6924592 : fd_quic_buffer_t * tx_buf = &stream->tx_buf;
1138 :
1139 : /* are we allowed to send? */
1140 6924592 : ulong stream_id = stream->stream_id;
1141 :
1142 : /* stream_id & 2 == 0 is bidir
1143 : stream_id & 1 == 0 is client */
1144 6924592 : if( FD_UNLIKELY( ( ( (uint)stream_id & 2u ) == 2u ) &
1145 6924592 : ( ( (uint)stream_id & 1u ) != (uint)conn->server ) ) ) {
1146 0 : return FD_QUIC_SEND_ERR_INVAL_STREAM;
1147 0 : }
1148 :
1149 6924592 : if( FD_UNLIKELY( conn->state != FD_QUIC_CONN_STATE_ACTIVE ) ) {
1150 0 : if( conn->state == FD_QUIC_CONN_STATE_HANDSHAKE ||
1151 0 : conn->state == FD_QUIC_CONN_STATE_HANDSHAKE_COMPLETE ) {
1152 0 : return FD_QUIC_SEND_ERR_STREAM_STATE;
1153 0 : }
1154 0 : return FD_QUIC_SEND_ERR_INVAL_CONN;
1155 0 : }
1156 :
1157 : /* how many bytes are we allowed to send on the stream and on the connection? */
1158 6924592 : ulong allowed_stream = stream->tx_max_stream_data - stream->tx_tot_data;
1159 6924592 : ulong allowed_conn = conn->tx_max_data - conn->tx_tot_data;
1160 6924592 : ulong allowed = fd_ulong_min( allowed_conn, allowed_stream );
1161 :
1162 6924592 : if( data_sz > fd_quic_buffer_avail( tx_buf ) ) {
1163 0 : return FD_QUIC_SEND_ERR_FLOW;
1164 0 : }
1165 :
1166 6924592 : if( data_sz > allowed ) {
1167 0 : return FD_QUIC_SEND_ERR_FLOW;
1168 0 : }
1169 :
1170 : /* store data from data into tx_buf */
1171 6924592 : fd_quic_buffer_store( tx_buf, data, data_sz );
1172 :
1173 : /* adjust flow control limits on stream and connection */
1174 6924592 : stream->tx_tot_data += data_sz;
1175 6924592 : conn->tx_tot_data += data_sz;
1176 :
1177 : /* insert into send list */
1178 6924592 : if( !FD_QUIC_STREAM_ACTION( stream ) ) {
1179 6924592 : FD_QUIC_STREAM_LIST_REMOVE( stream );
1180 6924592 : FD_QUIC_STREAM_LIST_INSERT_BEFORE( conn->send_streams, stream );
1181 6924592 : }
1182 6924592 : stream->stream_flags |= FD_QUIC_STREAM_FLAGS_UNSENT; /* we have unsent data */
1183 6924592 : stream->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING; /* schedule tx */
1184 :
1185 : /* don't actually set fin flag if we didn't add the last
1186 : byte to the buffer */
1187 6924592 : if( fin ) {
1188 6924478 : fd_quic_stream_fin( stream );
1189 6924478 : }
1190 :
1191 : /* schedule send */
1192 6924592 : fd_quic_svc_prep_schedule_now( conn );
1193 6924592 : fd_quic_svc_schedule1( conn );
1194 :
1195 6924592 : return FD_QUIC_SUCCESS;
1196 6924592 : }
1197 :
1198 : void
1199 6924484 : fd_quic_stream_fin( fd_quic_stream_t * stream ) {
1200 6924484 : if( FD_UNLIKELY( stream->state & FD_QUIC_STREAM_STATE_TX_FIN ) ) {
1201 0 : return;
1202 0 : }
1203 :
1204 6924484 : fd_quic_conn_t * conn = stream->conn;
1205 :
1206 : /* insert into send list */
1207 6924484 : if( !FD_QUIC_STREAM_ACTION( stream ) ) {
1208 6 : FD_QUIC_STREAM_LIST_REMOVE( stream );
1209 6 : FD_QUIC_STREAM_LIST_INSERT_BEFORE( conn->send_streams, stream );
1210 6 : }
1211 6924484 : stream->stream_flags |= FD_QUIC_STREAM_FLAGS_TX_FIN; /* state immediately updated */
1212 6924484 : stream->state |= FD_QUIC_STREAM_STATE_TX_FIN; /* state immediately updated */
1213 6924484 : stream->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING; /* update to be sent in next packet */
1214 :
1215 : /* TODO update metrics */
1216 6924484 : }
1217 :
1218 : void
1219 0 : fd_quic_conn_set_rx_max_data( fd_quic_conn_t * conn, ulong rx_max_data ) {
1220 : /* cannot reduce max_data, and cannot increase beyond max varint */
1221 0 : if( rx_max_data > conn->srx->rx_max_data && rx_max_data < (1UL<<62)-1UL ) {
1222 0 : conn->srx->rx_max_data = rx_max_data;
1223 0 : conn->flags |= FD_QUIC_CONN_FLAGS_MAX_DATA;
1224 0 : conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
1225 0 : fd_quic_svc_prep_schedule_now( conn );
1226 0 : fd_quic_svc_schedule1( conn );
1227 0 : }
1228 0 : }
1229 :
1230 : /* packet processing */
1231 :
1232 : /* fd_quic_conn_free_pkt_meta frees all pkt_meta associated with
1233 : enc_level. Returns the number of freed pkt_meta. */
1234 : static ulong
1235 : fd_quic_conn_free_pkt_meta( fd_quic_conn_t * conn,
1236 97248 : uint enc_level ) {
1237 97248 : fd_quic_pkt_meta_tracker_t * tracker = &conn->pkt_meta_tracker;
1238 97248 : fd_quic_pkt_meta_t * pool = tracker->pool;
1239 97248 : fd_quic_pkt_meta_ds_t * sent = &tracker->sent_pkt_metas[enc_level];
1240 :
1241 97248 : fd_quic_pkt_meta_t * prev = NULL;
1242 97248 : for( fd_quic_pkt_meta_ds_fwd_iter_t iter = fd_quic_pkt_meta_ds_fwd_iter_init( sent, pool );
1243 121539 : !fd_quic_pkt_meta_ds_fwd_iter_done( iter );
1244 97248 : iter = fd_quic_pkt_meta_ds_fwd_iter_next( iter, pool ) ) {
1245 24291 : fd_quic_pkt_meta_t * e = fd_quic_pkt_meta_ds_fwd_iter_ele( iter, pool );
1246 24291 : if( FD_LIKELY( prev ) ) {
1247 6186 : fd_quic_pkt_meta_pool_ele_release( pool, prev );
1248 6186 : }
1249 24291 : prev = e;
1250 24291 : }
1251 97248 : if( FD_LIKELY( prev ) ) {
1252 18105 : fd_quic_pkt_meta_pool_ele_release( pool, prev );
1253 18105 : }
1254 :
1255 :
1256 : /* Instead of paying log(n) to maintain the treap structure during ele_remove
1257 : on each iteration, we've returned all pkt_meta to the pool, but left them
1258 : in the treap. Then, we reinitialize the treap, in constant time deleting
1259 : all elements that were in the 'old treap'. This function now runs in linear
1260 : time, instead of O(n*lg(n)). */
1261 :
1262 97248 : ulong pre_ele_cnt = fd_quic_pkt_meta_ds_ele_cnt( sent );
1263 :
1264 97248 : fd_quic_pkt_meta_ds_clear( tracker, enc_level );
1265 97248 : conn->used_pkt_meta -= pre_ele_cnt;
1266 :
1267 97248 : return pre_ele_cnt;
1268 97248 : }
1269 :
1270 : /* reclaim and free all pkt_meta for a given encryption level,
1271 : and return the number affected. */
1272 : static ulong
1273 48552 : fd_quic_reclaim_pkt_meta_level( fd_quic_conn_t * conn, uint enc_level ) {
1274 48552 : fd_quic_pkt_meta_tracker_t * tracker = &conn->pkt_meta_tracker;
1275 48552 : fd_quic_pkt_meta_t * pool = tracker->pool;
1276 48552 : fd_quic_pkt_meta_ds_t * sent = &tracker->sent_pkt_metas[enc_level];
1277 :
1278 48552 : for( fd_quic_pkt_meta_ds_fwd_iter_t iter = fd_quic_pkt_meta_ds_fwd_iter_init( sent, pool );
1279 54627 : !fd_quic_pkt_meta_ds_fwd_iter_done( iter );
1280 48552 : iter = fd_quic_pkt_meta_ds_fwd_iter_next( iter, pool ) ) {
1281 6075 : fd_quic_pkt_meta_t * e = fd_quic_pkt_meta_ds_fwd_iter_ele( iter, pool );
1282 6075 : fd_quic_reclaim_pkt_meta( conn, e, enc_level );
1283 6075 : }
1284 :
1285 48552 : return fd_quic_conn_free_pkt_meta( conn, enc_level );
1286 48552 : }
1287 :
1288 :
1289 : /* fd_quic_abandon_enc_level frees all resources associated encryption
1290 : levels less or equal to enc_level. Returns the number of freed
1291 : pkt_meta. */
1292 :
1293 : ulong
1294 : fd_quic_abandon_enc_level( fd_quic_conn_t * conn,
1295 24276 : uint enc_level ) {
1296 24276 : if( FD_LIKELY( !fd_uint_extract_bit( conn->keys_avail, (int)enc_level ) ) ) return 0UL;
1297 24276 : FD_DEBUG( FD_LOG_DEBUG(( "conn=%p abandoning enc_level=%u", (void *)conn, enc_level )); )
1298 :
1299 24276 : fd_quic_ack_gen_abandon_enc_level( conn->ack_gen, enc_level );
1300 :
1301 24276 : ulong freed = 0UL;
1302 72828 : for( uint j = 0; j <= enc_level; ++j ) {
1303 48552 : conn->keys_avail = fd_uint_clear_bit( conn->keys_avail, (int)j );
1304 : /* treat all packets as ACKed (freeing handshake data, etc.) */
1305 48552 : freed += fd_quic_reclaim_pkt_meta_level( conn, j );
1306 48552 : }
1307 :
1308 24276 : return freed;
1309 24276 : }
1310 :
1311 : static void
1312 : fd_quic_gen_initial_secret_and_keys(
1313 : fd_quic_conn_t * conn,
1314 : fd_quic_conn_id_t const * dst_conn_id,
1315 6108 : int is_server ) {
1316 :
1317 6108 : fd_quic_gen_initial_secrets(
1318 6108 : &conn->secrets,
1319 6108 : dst_conn_id->conn_id, dst_conn_id->sz,
1320 6108 : is_server );
1321 :
1322 6108 : fd_quic_gen_keys(
1323 6108 : &conn->keys[ fd_quic_enc_level_initial_id ][ 0 ],
1324 6108 : conn->secrets.secret[ fd_quic_enc_level_initial_id ][ 0 ] );
1325 :
1326 6108 : fd_quic_gen_keys(
1327 6108 : &conn->keys[ fd_quic_enc_level_initial_id ][ 1 ],
1328 6108 : conn->secrets.secret[ fd_quic_enc_level_initial_id ][ 1 ] );
1329 6108 : }
1330 :
1331 : static ulong
1332 : fd_quic_send_retry( fd_quic_t * quic,
1333 : fd_quic_pkt_t * pkt,
1334 : fd_quic_conn_id_t const * odcid,
1335 : fd_quic_conn_id_t const * scid,
1336 6 : ulong new_conn_id ) {
1337 :
1338 6 : fd_quic_state_t * state = fd_quic_get_state( quic );
1339 :
1340 6 : long expire_at = state->now + quic->config.retry_ttl;
1341 6 : uchar retry_pkt[ FD_QUIC_RETRY_LOCAL_SZ ];
1342 6 : ulong retry_pkt_sz = fd_quic_retry_create( retry_pkt, pkt, state->_rng, state->retry_secret, state->retry_iv, odcid, scid, new_conn_id, expire_at );
1343 :
1344 6 : quic->metrics.retry_tx_cnt++;
1345 :
1346 6 : uchar * tx_ptr = retry_pkt + retry_pkt_sz;
1347 6 : if( FD_UNLIKELY( fd_quic_tx_buffered_raw(
1348 6 : quic,
1349 : // these are state variable's normally updated on a conn, but irrelevant in retry so we
1350 : // just size it exactly as the encoded retry packet
1351 6 : &tx_ptr,
1352 6 : retry_pkt,
1353 : // encode buffer
1354 6 : &pkt->ip4->net_id,
1355 6 : pkt->ip4->saddr,
1356 6 : pkt->udp->net_sport,
1357 6 : pkt->ip4->daddr,
1358 6 : pkt->udp->net_dport ) == FD_QUIC_FAILED ) ) {
1359 0 : return FD_QUIC_PARSE_FAIL;
1360 0 : }
1361 6 : return 0UL;
1362 6 : }
1363 :
1364 : /* fd_quic_tls_hs_cache_evict evicts the oldest tls_hs if it's exceeded its ttl
1365 : Assumes cache is non-empty
1366 : and returns 1 if evicted, otherwise returns 0. */
1367 : static int
1368 : fd_quic_tls_hs_cache_evict( fd_quic_t * quic,
1369 6 : fd_quic_state_t * state ) {
1370 :
1371 6 : fd_quic_tls_hs_t* hs_to_free = fd_quic_tls_hs_cache_ele_peek_head( &state->hs_cache, state->hs_pool );
1372 :
1373 6 : if( state->now < hs_to_free->birthtime + quic->config.tls_hs_ttl ) {
1374 : /* oldest is too young to evict */
1375 3 : quic->metrics.hs_err_alloc_fail_cnt++;
1376 3 : return 0;
1377 3 : }
1378 :
1379 3 : fd_quic_cb_conn_final(quic, hs_to_free->context);
1380 3 : fd_quic_conn_free( quic, hs_to_free->context );
1381 3 : quic->metrics.hs_evicted_cnt++;
1382 3 : return 1;
1383 6 : }
1384 :
1385 : /* fd_quic_handle_v1_initial handles an "Initial"-type packet.
1386 : Valid for both server and client. Initial packets are used to
1387 : establish QUIC conns and wrap the TLS handshake flow among other
1388 : things. */
1389 :
1390 : ulong
1391 : fd_quic_handle_v1_initial( fd_quic_t * quic,
1392 : fd_quic_conn_t ** p_conn,
1393 : fd_quic_pkt_t * pkt,
1394 : fd_quic_conn_id_t const * dcid,
1395 : fd_quic_conn_id_t const * peer_scid,
1396 : uchar * cur_ptr,
1397 18213 : ulong cur_sz ) {
1398 18213 : fd_quic_conn_t * conn = *p_conn;
1399 :
1400 18213 : if( FD_UNLIKELY( conn && !fd_uint_extract_bit( conn->keys_avail, fd_quic_enc_level_initial_id ) ) ) {
1401 0 : quic->metrics.pkt_no_key_cnt[ fd_quic_enc_level_initial_id ]++;
1402 0 : return FD_QUIC_PARSE_FAIL;
1403 0 : }
1404 :
1405 18213 : fd_quic_state_t * state = fd_quic_get_state( quic );
1406 18213 : fd_quic_metrics_t * metrics = &quic->metrics;
1407 :
1408 : /* Initial packets are de-facto unencrypted. Packet protection is
1409 : still applied, albeit with publicly known encryption keys.
1410 :
1411 : RFC 9001 specifies use of the TLS_AES_128_GCM_SHA256_ID suite for
1412 : initial secrets and keys. */
1413 :
1414 : /* Parse initial packet */
1415 :
1416 18213 : fd_quic_initial_t initial[1] = {0};
1417 18213 : ulong rc = fd_quic_decode_initial( initial, cur_ptr, cur_sz );
1418 18213 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
1419 0 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_decode_initial failed" )) );
1420 0 : return FD_QUIC_PARSE_FAIL;
1421 0 : }
1422 :
1423 : /* Check bounds on initial */
1424 :
1425 : /* len indicated the number of bytes after the packet number offset
1426 : so verify this value is within the packet */
1427 18213 : ulong pn_offset = initial->pkt_num_pnoff;
1428 18213 : ulong body_sz = initial->len; /* length of packet number, frames, and auth tag */
1429 18213 : ulong tot_sz = pn_offset + body_sz;
1430 18213 : if( FD_UNLIKELY( tot_sz > cur_sz ) ) {
1431 0 : FD_DEBUG( FD_LOG_DEBUG(( "Bogus initial packet length" )) );
1432 0 : return FD_QUIC_PARSE_FAIL;
1433 0 : }
1434 :
1435 : /* count received token len */
1436 18213 : int const token_len_match = initial->token_len == sizeof(fd_quic_retry_token_t);
1437 18213 : ulong const token_len_idx = fd_ulong_if( !!initial->token_len,
1438 18213 : fd_ulong_if( token_len_match, 1, 2 ),
1439 18213 : 0 );
1440 18213 : metrics->initial_token_len_cnt[ token_len_idx ]++;
1441 :
1442 : /* Check it is valid for a token to be present in an initial packet in the current context.
1443 :
1444 : quic->config.role == FD_QUIC_ROLE_CLIENT
1445 : - Indicates the client received an initial packet with a token from a server. "Initial packets
1446 : sent by the server MUST set the Token Length field to 0; clients that receive an Initial packet
1447 : with a non-zero Token Length field MUST either discard the packet or generate a connection
1448 : error of type PROTOCOL_VIOLATION (RFC 9000, Section 17.2.2)"
1449 :
1450 : quic->config.retry == false
1451 : - Indicates the server is not configured to retry, but a client attached a token to this
1452 : initial packet. NEW_TOKEN frames are not supported, so this implementation treats the presence
1453 : of a token when retry is disabled as an error. */
1454 18213 : if( FD_UNLIKELY( initial->token_len > 0 &&
1455 18213 : ( quic->config.role == FD_QUIC_ROLE_CLIENT || !quic->config.retry ) ) ) {
1456 0 : FD_DEBUG( FD_LOG_DEBUG(( "Rejecting initial with token" )); )
1457 0 : return FD_QUIC_PARSE_FAIL;
1458 0 : }
1459 :
1460 :
1461 18213 : ulong scid; /* outgoing scid */
1462 18213 : fd_quic_conn_id_t odcid; /* dst conn id from client's original Initial */
1463 :
1464 : /* Do we have a conn object for this dest conn ID?
1465 : If not, sanity check, send/verify retry if needed */
1466 18213 : if( FD_UNLIKELY( !conn ) ) {
1467 : /* if we're a client, and no conn, discard */
1468 6075 : if( quic->config.role == FD_QUIC_ROLE_CLIENT ) {
1469 : /* connection may have been torn down */
1470 0 : FD_DEBUG( FD_LOG_DEBUG(( "unknown connection ID" )); )
1471 0 : metrics->pkt_no_conn_cnt[ fd_quic_enc_level_initial_id ]++;
1472 0 : FD_DTRACE_PROBE_2( fd_quic_handle_v1_initial_no_conn , state->now, pkt->pkt_number );
1473 0 : return FD_QUIC_PARSE_FAIL;
1474 0 : }
1475 :
1476 : /* According to RFC 9000 Section 14.1, INITIAL packets less than a
1477 : certain length must be discarded, and the connection may be closed.
1478 : (Mitigates UDP amplification) */
1479 6075 : if( pkt->datagram_sz < FD_QUIC_INITIAL_PAYLOAD_SZ_MIN ) {
1480 : /* can't trust the included values, so can't reply */
1481 0 : return FD_QUIC_PARSE_FAIL;
1482 0 : }
1483 :
1484 : /* Early check: Is conn free? */
1485 6075 : if( FD_UNLIKELY( state->free_conn_list==UINT_MAX ) ) {
1486 0 : FD_DEBUG( FD_LOG_DEBUG(( "ignoring conn request: no free conn slots" )) );
1487 0 : metrics->conn_err_no_slots_cnt++;
1488 0 : return FD_QUIC_PARSE_FAIL; /* FIXME better error code? */
1489 0 : }
1490 :
1491 :
1492 : /* Primary objective is to send or verify retry.
1493 : We'll also select the scid we'll use from now on.
1494 :
1495 : Rules for selecting the SCID:
1496 : - No retry token, accepted: generate new random ID
1497 : - No retry token, retry request: generate new random ID
1498 : - Retry token, accepted: reuse SCID from retry token */
1499 6075 : if( !quic->config.retry ) {
1500 6063 : scid = fd_rng_ulong( state->_rng );
1501 6063 : } else { /* retry configured */
1502 :
1503 : /* Need to send retry? Do so before more work */
1504 12 : if( initial->token_len != sizeof(fd_quic_retry_token_t) ) {
1505 :
1506 6 : ulong new_conn_id_u64 = fd_rng_ulong( state->_rng );
1507 6 : if( FD_UNLIKELY( fd_quic_send_retry(
1508 6 : quic, pkt,
1509 6 : dcid, peer_scid, new_conn_id_u64 ) ) ) {
1510 0 : return FD_QUIC_FAILED;
1511 0 : }
1512 6 : return (initial->pkt_num_pnoff + initial->len);
1513 6 : } else {
1514 : /* This Initial packet is in response to our Retry.
1515 : Validate the relevant fields of this post-retry INITIAL packet,
1516 : i.e. retry src conn id, ip, port
1517 : Also populate odcid and scid from the retry data */
1518 6 : int retry_ok = fd_quic_retry_server_verify( pkt, initial, &odcid, &scid, state->retry_secret, state->retry_iv, state->now, quic->config.retry_ttl );
1519 6 : if( FD_UNLIKELY( retry_ok!=FD_QUIC_SUCCESS ) ) {
1520 0 : metrics->conn_err_retry_fail_cnt++;
1521 : /* No need to set conn error, no conn object exists */
1522 0 : return FD_QUIC_PARSE_FAIL;
1523 6 : };
1524 6 : }
1525 12 : }
1526 6075 : }
1527 :
1528 : /* Determine decryption keys, related data */
1529 :
1530 : /* Placeholder for generated crypto material before allocating conn */
1531 18207 : fd_quic_crypto_keys_t _rx_keys[1];
1532 18207 : fd_quic_crypto_secrets_t _secrets[1];
1533 :
1534 : /* Conditional inputs to decryption stage */
1535 18207 : fd_quic_crypto_keys_t * rx_keys = NULL;
1536 18207 : fd_quic_crypto_secrets_t * secrets = NULL;
1537 18207 : ulong exp_pkt_num;
1538 :
1539 18207 : if( !conn ) {
1540 : /* no conn, generate secret and rx keys */
1541 6069 : rx_keys = _rx_keys;
1542 6069 : secrets = _secrets;
1543 6069 : exp_pkt_num = 0;
1544 :
1545 6069 : fd_quic_gen_initial_secrets(
1546 6069 : secrets,
1547 6069 : dcid->conn_id, dcid->sz,
1548 6069 : /* is_server */ 1 );
1549 6069 : fd_quic_gen_keys(
1550 6069 : rx_keys,
1551 6069 : secrets->secret[ fd_quic_enc_level_initial_id ][ 0 ] );
1552 12138 : } else {
1553 : /* conn, use existing keys/secrets */
1554 12138 : rx_keys = &conn->keys[ fd_quic_enc_level_initial_id ][0];
1555 12138 : secrets = &conn->secrets;
1556 12138 : exp_pkt_num = conn->exp_pkt_number[0];
1557 12138 : }
1558 :
1559 : /* Decrypt incoming packet */
1560 :
1561 : /* header protection needs the offset to the packet number */
1562 :
1563 18207 : # if !FD_QUIC_DISABLE_CRYPTO
1564 : /* this decrypts the header */
1565 18207 : if( FD_UNLIKELY(
1566 18207 : fd_quic_crypto_decrypt_hdr( cur_ptr, cur_sz,
1567 18207 : pn_offset,
1568 18207 : rx_keys ) != FD_QUIC_SUCCESS ) ) {
1569 : /* As this is an INITIAL packet, change the status to DEAD, and allow
1570 : it to be reaped */
1571 0 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_crypto_decrypt_hdr failed" )) );
1572 0 : quic->metrics.pkt_decrypt_fail_cnt[ fd_quic_enc_level_initial_id ]++;
1573 0 : return FD_QUIC_PARSE_FAIL;
1574 0 : }
1575 18207 : # endif /* !FD_QUIC_DISABLE_CRYPTO */
1576 :
1577 18207 : ulong pkt_number_sz = fd_quic_h0_pkt_num_len( cur_ptr[0] ) + 1u;
1578 18207 : ulong pktnum_comp = fd_quic_pktnum_decode( cur_ptr+pn_offset, pkt_number_sz );
1579 :
1580 : /* reconstruct packet number */
1581 18207 : ulong pkt_number = fd_quic_reconstruct_pkt_num( pktnum_comp, pkt_number_sz, exp_pkt_num );
1582 :
1583 18207 : # if !FD_QUIC_DISABLE_CRYPTO
1584 : /* NOTE from rfc9002 s3
1585 : It is permitted for some packet numbers to never be used, leaving intentional gaps. */
1586 : /* this decrypts the header and payload */
1587 18207 : if( FD_UNLIKELY(
1588 18207 : fd_quic_crypto_decrypt( cur_ptr, tot_sz,
1589 18207 : pn_offset,
1590 18207 : pkt_number,
1591 18207 : rx_keys ) != FD_QUIC_SUCCESS ) ) {
1592 0 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_crypto_decrypt failed" )) );
1593 0 : FD_DTRACE_PROBE_2( quic_err_decrypt_initial_pkt, pkt->ip4, pkt->pkt_number );
1594 0 : quic->metrics.pkt_decrypt_fail_cnt[ fd_quic_enc_level_initial_id ]++;
1595 0 : return FD_QUIC_PARSE_FAIL;
1596 0 : }
1597 18207 : # endif /* FD_QUIC_DISABLE_CRYPTO */
1598 :
1599 : /* set packet number on the context */
1600 18207 : pkt->pkt_number = pkt_number;
1601 :
1602 18207 : if( FD_UNLIKELY( body_sz < pkt_number_sz + FD_QUIC_CRYPTO_TAG_SZ ) ) {
1603 0 : return FD_QUIC_PARSE_FAIL;
1604 0 : }
1605 :
1606 : /* If no conn, create one. Due to previous checks, role must be server
1607 : and this must be response to Retry (if needed). */
1608 18207 : if( FD_UNLIKELY( !conn ) ) {
1609 :
1610 : /* Save peer's conn ID, which we will use to address peer with. */
1611 6069 : fd_quic_conn_id_t peer_conn_id = {0};
1612 6069 : fd_memcpy( peer_conn_id.conn_id, initial->src_conn_id, FD_QUIC_MAX_CONN_ID_SZ );
1613 6069 : peer_conn_id.sz = initial->src_conn_id_len;
1614 :
1615 : /* Prepare QUIC-TLS transport params object (sent as a TLS extension).
1616 : Take template from state and mutate certain params in-place.
1617 :
1618 : See RFC 9000 Section 18 */
1619 :
1620 : /* TODO Each transport param is a TLV tuple. This allows serializing
1621 : most transport params ahead of time. Only the conn-specific
1622 : differences will have to be appended here. */
1623 :
1624 6069 : fd_quic_transport_params_t tp[1] = { state->transport_params };
1625 :
1626 6069 : if( !quic->config.retry ) {
1627 : /* assume no retry */
1628 6063 : tp->retry_source_connection_id_present = 0;
1629 :
1630 : /* Send orig conn ID back to client (server only) */
1631 :
1632 6063 : tp->original_destination_connection_id_present = 1;
1633 6063 : tp->original_destination_connection_id_len = dcid->sz;
1634 6063 : fd_memcpy( tp->original_destination_connection_id,
1635 6063 : dcid->conn_id,
1636 6063 : dcid->sz );
1637 6063 : } else { /* retry configured */
1638 :
1639 : /* From rfc 9000:
1640 :
1641 : Figure 8 shows a similar handshake that includes a Retry packet.
1642 :
1643 : Client Server
1644 : Initial: DCID=S1, SCID=C1 ->
1645 : <- Retry: DCID=C1, SCID=S2
1646 : Initial: DCID=S2, SCID=C1 ->
1647 : <- Initial: DCID=C1, SCID=S3
1648 : ...
1649 : 1-RTT: DCID=S3 ->
1650 : <- 1-RTT: DCID=C1
1651 :
1652 : Figure 8: Use of Connection IDs in a Handshake with Retry
1653 : In both cases (Figures 7 and 8), the client sets the value of the
1654 : initial_source_connection_id transport parameter to C1.
1655 :
1656 : When the handshake does not include a Retry (Figure 7), the server
1657 : sets original_destination_connection_id to S1 (note that this value
1658 : is chosen by the client) and initial_source_connection_id to S3. In
1659 : this case, the server does not include a retry_source_connection_id
1660 : transport parameter.
1661 :
1662 : When the handshake includes a Retry (Figure 8), the server sets
1663 : original_destination_connection_id to S1, retry_source_connection_id
1664 : to S2, and initial_source_connection_id to S3. */
1665 6 : tp->original_destination_connection_id_present = 1;
1666 6 : tp->original_destination_connection_id_len = odcid.sz;
1667 6 : memcpy( tp->original_destination_connection_id,
1668 6 : odcid.conn_id,
1669 6 : odcid.sz );
1670 :
1671 : /* Client echoes back the SCID we sent via Retry. Safe to trust
1672 : because we signed the Retry Token. (Length and content validated
1673 : in fd_quic_retry_server_verify) */
1674 6 : tp->retry_source_connection_id_present = 1;
1675 6 : tp->retry_source_connection_id_len = FD_QUIC_CONN_ID_SZ;
1676 6 : FD_STORE( ulong, tp->retry_source_connection_id, scid );
1677 :
1678 6 : metrics->conn_retry_cnt++;
1679 6 : }
1680 :
1681 : /* Repeat the conn ID we picked in transport params (this is done
1682 : to authenticate conn IDs via TLS by including them in TLS-
1683 : protected data).
1684 :
1685 : Per spec, this field should be the source conn ID field we've set
1686 : on the first Initial packet we've sent. At this point, we might
1687 : not have sent an Initial packet yet -- so this field should hold
1688 : a value we are about to pick.
1689 :
1690 : fd_quic_conn_create will set conn->initial_source_conn_id to
1691 : the random new_conn_id we've created earlier. */
1692 :
1693 6069 : tp->initial_source_connection_id_present = 1;
1694 6069 : tp->initial_source_connection_id_len = FD_QUIC_CONN_ID_SZ;
1695 6069 : FD_STORE( ulong, tp->initial_source_connection_id, scid );
1696 :
1697 : /* tls hs available? After decrypting because might evict another hs */
1698 6069 : if( FD_UNLIKELY( !fd_quic_tls_hs_pool_free( state->hs_pool ) ) ) {
1699 : /* try evicting, 0 if oldest is too young so fail */
1700 0 : if( !fd_quic_tls_hs_cache_evict( quic, state )) {
1701 0 : return FD_QUIC_PARSE_FAIL;
1702 0 : }
1703 0 : }
1704 :
1705 : /* Allocate new conn */
1706 6069 : conn = fd_quic_conn_create( quic,
1707 6069 : scid,
1708 6069 : &peer_conn_id,
1709 6069 : pkt->ip4->saddr,
1710 6069 : pkt->udp->net_sport,
1711 6069 : pkt->ip4->daddr,
1712 6069 : pkt->udp->net_dport,
1713 6069 : 1 /* server */ );
1714 :
1715 6069 : if( FD_UNLIKELY( !conn ) ) { /* no free connections */
1716 : /* TODO send failure back to origin? */
1717 : /* FIXME unreachable? conn_cnt already checked above */
1718 0 : FD_DEBUG( FD_LOG_WARNING( ( "failed to allocate QUIC conn" ) ) );
1719 0 : return FD_QUIC_PARSE_FAIL;
1720 0 : }
1721 6069 : FD_DEBUG( FD_LOG_DEBUG(( "new connection allocated" )) );
1722 :
1723 : /* set the value for the caller */
1724 6069 : *p_conn = conn;
1725 :
1726 : /* Create a TLS handshake */
1727 6069 : fd_quic_tls_hs_t * tls_hs = fd_quic_tls_hs_new(
1728 6069 : fd_quic_tls_hs_pool_ele_acquire( state->hs_pool ),
1729 6069 : state->tls,
1730 6069 : (void*)conn,
1731 6069 : 1 /*is_server*/,
1732 6069 : tp,
1733 6069 : state->now );
1734 6069 : fd_quic_tls_hs_cache_ele_push_tail( &state->hs_cache, tls_hs, state->hs_pool );
1735 :
1736 6069 : conn->tls_hs = tls_hs;
1737 6069 : quic->metrics.hs_created_cnt++;
1738 :
1739 : /* copy secrets and rx keys */
1740 6069 : conn->secrets = *secrets;
1741 6069 : conn->keys[ fd_quic_enc_level_initial_id ][0] = *rx_keys;
1742 :
1743 : /* generate tx keys */
1744 6069 : fd_quic_gen_keys(
1745 6069 : &conn->keys[ fd_quic_enc_level_initial_id ][ 1 ],
1746 6069 : secrets->secret[ fd_quic_enc_level_initial_id ][ 1 ] );
1747 6069 : }
1748 :
1749 18207 : if( FD_UNLIKELY( !conn->host.ip_addr ) ) {
1750 : /* Lock src IP address in place (previously chosen by layer-4 based
1751 : on the route table) */
1752 0 : conn->host.ip_addr = pkt->ip4->daddr;
1753 0 : }
1754 :
1755 : /* check if reply conn id needs to change */
1756 18207 : if( FD_UNLIKELY( !( conn->server | conn->established ) ) ) {
1757 : /* switch to the source connection id for future replies */
1758 :
1759 : /* replace peer 0 connection id */
1760 6069 : conn->peer_cids[0].sz = initial->src_conn_id_len;
1761 6069 : fd_memcpy( conn->peer_cids[0].conn_id, initial->src_conn_id, FD_QUIC_MAX_CONN_ID_SZ );
1762 :
1763 : /* don't repeat this procedure */
1764 6069 : conn->established = 1;
1765 6069 : }
1766 :
1767 : /* handle frames */
1768 18207 : ulong payload_off = pn_offset + pkt_number_sz;
1769 18207 : uchar const * frame_ptr = cur_ptr + payload_off;
1770 18207 : ulong frame_sz = body_sz - pkt_number_sz - FD_QUIC_CRYPTO_TAG_SZ; /* total size of all frames in packet */
1771 48552 : while( frame_sz != 0UL ) {
1772 30345 : rc = fd_quic_handle_v1_frame( quic,
1773 30345 : conn,
1774 30345 : pkt,
1775 30345 : FD_QUIC_PKT_TYPE_INITIAL,
1776 30345 : frame_ptr,
1777 30345 : frame_sz );
1778 30345 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
1779 0 : FD_DEBUG( FD_LOG_DEBUG(( "Failed to handle frame (Initial, frame=0x%02x)", frame_ptr[0] )) );
1780 0 : quic->metrics.frame_rx_err_cnt++;
1781 0 : return FD_QUIC_PARSE_FAIL;
1782 0 : }
1783 :
1784 30345 : if( FD_UNLIKELY( rc==0UL || rc>frame_sz ) ) {
1785 0 : fd_quic_conn_error( conn, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
1786 0 : return FD_QUIC_PARSE_FAIL;
1787 0 : }
1788 :
1789 : /* next frame, and remaining size */
1790 30345 : frame_ptr += rc;
1791 30345 : frame_sz -= rc;
1792 30345 : }
1793 :
1794 : /* update last activity */
1795 18207 : conn->last_activity = state->now;
1796 18207 : conn->flags &= ~( FD_QUIC_CONN_FLAGS_PING_SENT | FD_QUIC_CONN_FLAGS_PING );
1797 :
1798 : /* update expected packet number */
1799 18207 : conn->exp_pkt_number[0] = fd_ulong_max( conn->exp_pkt_number[0], pkt_number+1UL );
1800 :
1801 : /* insert into service queue */
1802 18207 : fd_quic_svc_prep_schedule( conn, state->now );
1803 :
1804 : /* return number of bytes consumed */
1805 18207 : return tot_sz;
1806 18207 : }
1807 :
1808 : ulong
1809 : fd_quic_handle_v1_handshake(
1810 : fd_quic_t * quic,
1811 : fd_quic_conn_t * conn,
1812 : fd_quic_pkt_t * pkt,
1813 : uchar * cur_ptr,
1814 : ulong cur_sz
1815 12138 : ) {
1816 12138 : fd_quic_state_t * state = fd_quic_get_state( quic );
1817 12138 : if( FD_UNLIKELY( !conn ) ) {
1818 0 : quic->metrics.pkt_no_conn_cnt[ fd_quic_enc_level_handshake_id ]++;
1819 0 : FD_DTRACE_PROBE_2( fd_quic_handle_v1_handshake_no_conn , state->now, pkt->pkt_number );
1820 0 : return FD_QUIC_PARSE_FAIL;
1821 0 : }
1822 :
1823 12138 : if( FD_UNLIKELY( !fd_uint_extract_bit( conn->keys_avail, fd_quic_enc_level_handshake_id ) ) ) {
1824 0 : quic->metrics.pkt_no_key_cnt[ fd_quic_enc_level_handshake_id ]++;
1825 0 : return FD_QUIC_PARSE_FAIL;
1826 0 : }
1827 :
1828 : /* do parse here */
1829 12138 : fd_quic_handshake_t handshake[1];
1830 12138 : ulong rc = fd_quic_decode_handshake( handshake, cur_ptr, cur_sz );
1831 12138 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
1832 0 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_decode_handshake failed" )) );
1833 0 : return FD_QUIC_PARSE_FAIL;
1834 0 : }
1835 :
1836 : /* check bounds on handshake */
1837 :
1838 : /* len indicated the number of bytes after the packet number offset
1839 : so verify this value is within the packet */
1840 12138 : ulong len = (ulong)( handshake->pkt_num_pnoff + handshake->len );
1841 12138 : if( FD_UNLIKELY( len > cur_sz ) ) {
1842 0 : FD_DEBUG( FD_LOG_DEBUG(( "Handshake packet bounds check failed" )); )
1843 0 : return FD_QUIC_PARSE_FAIL;
1844 0 : }
1845 :
1846 : /* connection ids should already be in the relevant structures */
1847 :
1848 : /* TODO prepare most of the transport parameters, and only append the
1849 : necessary differences */
1850 :
1851 : /* fetch TLS handshake */
1852 12138 : fd_quic_tls_hs_t * tls_hs = conn->tls_hs;
1853 12138 : if( FD_UNLIKELY( !tls_hs ) ) {
1854 0 : FD_DEBUG( FD_LOG_DEBUG(( "no tls handshake" )) );
1855 0 : return FD_QUIC_PARSE_FAIL;
1856 0 : }
1857 :
1858 : /* decryption */
1859 :
1860 : /* header protection needs the offset to the packet number */
1861 12138 : ulong pn_offset = handshake->pkt_num_pnoff;
1862 :
1863 12138 : ulong body_sz = handshake->len; /* not a protected field */
1864 : /* length of payload + num packet bytes */
1865 :
1866 12138 : # if !FD_QUIC_DISABLE_CRYPTO
1867 : /* this decrypts the header */
1868 12138 : if( FD_UNLIKELY(
1869 12138 : fd_quic_crypto_decrypt_hdr( cur_ptr, cur_sz,
1870 12138 : pn_offset,
1871 12138 : &conn->keys[2][0] ) != FD_QUIC_SUCCESS ) ) {
1872 0 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_crypto_decrypt_hdr failed" )) );
1873 0 : quic->metrics.pkt_decrypt_fail_cnt[ fd_quic_enc_level_handshake_id ]++;
1874 0 : return FD_QUIC_PARSE_FAIL;
1875 0 : }
1876 12138 : # endif /* !FD_QUIC_DISABLE_CRYPTO */
1877 :
1878 : /* number of bytes in the packet header */
1879 12138 : ulong pkt_number_sz = fd_quic_h0_pkt_num_len( cur_ptr[0] ) + 1u;
1880 12138 : ulong tot_sz = pn_offset + body_sz; /* total including header and payload */
1881 :
1882 : /* now we have decrypted packet number */
1883 12138 : ulong pktnum_comp = fd_quic_pktnum_decode( cur_ptr+pn_offset, pkt_number_sz );
1884 :
1885 : /* reconstruct packet number */
1886 12138 : ulong pkt_number = fd_quic_reconstruct_pkt_num( pktnum_comp, pkt_number_sz, conn->exp_pkt_number[1] );
1887 :
1888 : /* NOTE from rfc9002 s3
1889 : It is permitted for some packet numbers to never be used, leaving intentional gaps. */
1890 :
1891 12138 : # if !FD_QUIC_DISABLE_CRYPTO
1892 : /* this decrypts the header and payload */
1893 12138 : if( FD_UNLIKELY(
1894 12138 : fd_quic_crypto_decrypt( cur_ptr, tot_sz,
1895 12138 : pn_offset,
1896 12138 : pkt_number,
1897 12138 : &conn->keys[2][0] ) != FD_QUIC_SUCCESS ) ) {
1898 : /* remove connection from map, and insert into free list */
1899 0 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_crypto_decrypt failed" )) );
1900 0 : FD_DTRACE_PROBE_3( quic_err_decrypt_handshake_pkt, pkt->ip4, conn->our_conn_id, pkt->pkt_number );
1901 0 : quic->metrics.pkt_decrypt_fail_cnt[ fd_quic_enc_level_handshake_id ]++;
1902 0 : return FD_QUIC_PARSE_FAIL;
1903 0 : }
1904 12138 : # endif /* FD_QUIC_DISABLE_CRYPTO */
1905 :
1906 : /* set packet number on the context */
1907 12138 : pkt->pkt_number = pkt_number;
1908 :
1909 : /* check body size large enough for required elements */
1910 12138 : if( FD_UNLIKELY( body_sz < pkt_number_sz + FD_QUIC_CRYPTO_TAG_SZ ) ) {
1911 0 : return FD_QUIC_PARSE_FAIL;
1912 0 : }
1913 :
1914 : /* handle frames */
1915 12138 : ulong payload_off = pn_offset + pkt_number_sz;
1916 12138 : uchar const * frame_ptr = cur_ptr + payload_off;
1917 12138 : ulong frame_sz = body_sz - pkt_number_sz - FD_QUIC_CRYPTO_TAG_SZ; /* total size of all frames in packet */
1918 66759 : while( frame_sz != 0UL ) {
1919 54621 : rc = fd_quic_handle_v1_frame( quic,
1920 54621 : conn,
1921 54621 : pkt,
1922 54621 : FD_QUIC_PKT_TYPE_HANDSHAKE,
1923 54621 : frame_ptr,
1924 54621 : frame_sz );
1925 54621 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
1926 0 : FD_DEBUG( FD_LOG_DEBUG(( "Failed to handle frame (Handshake, frame=0x%02x)", frame_ptr[0] )) );
1927 0 : quic->metrics.frame_rx_err_cnt++;
1928 0 : return FD_QUIC_PARSE_FAIL;
1929 0 : }
1930 :
1931 54621 : if( FD_UNLIKELY( rc == 0UL || rc > frame_sz ) ) {
1932 0 : fd_quic_conn_error( conn, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
1933 0 : return FD_QUIC_PARSE_FAIL;
1934 0 : }
1935 :
1936 : /* next frame and remaining size */
1937 54621 : frame_ptr += rc;
1938 54621 : frame_sz -= rc;
1939 54621 : }
1940 :
1941 : /* RFC 9000 Section 17.2.2.1. Abandoning Initial Packets
1942 : > A server stops sending and processing Initial packets when it
1943 : > receives its first Handshake packet.
1944 :
1945 : RFC 9001 Section 4.9.1 Discarding Initial Keys
1946 : > a server MUST discard Initial keys when it first successfully processes a Handshake packet */
1947 12138 : if( FD_LIKELY( quic->config.role==FD_QUIC_ROLE_SERVER ) ) fd_quic_abandon_enc_level( conn, fd_quic_enc_level_initial_id );
1948 :
1949 : /* update last activity */
1950 12138 : conn->last_activity = fd_quic_get_state( quic )->now;
1951 12138 : conn->flags &= ~( FD_QUIC_CONN_FLAGS_PING_SENT | FD_QUIC_CONN_FLAGS_PING );
1952 :
1953 : /* update expected packet number */
1954 12138 : conn->exp_pkt_number[1] = fd_ulong_max( conn->exp_pkt_number[1], pkt_number+1UL );
1955 :
1956 : /* return number of bytes consumed */
1957 12138 : return tot_sz;
1958 12138 : }
1959 :
1960 : ulong
1961 : fd_quic_handle_v1_retry(
1962 : fd_quic_t * quic,
1963 : fd_quic_conn_t * conn,
1964 : fd_quic_pkt_t const * pkt,
1965 : uchar const * cur_ptr,
1966 : ulong cur_sz
1967 6 : ) {
1968 6 : (void)pkt;
1969 6 : fd_quic_state_t * state = fd_quic_get_state( quic );
1970 :
1971 6 : if( FD_UNLIKELY( quic->config.role == FD_QUIC_ROLE_SERVER ) ) {
1972 : /* RFC 9000 Section 5.2.2: servers MUST drop incoming packets for
1973 : which the RFC does not specify behavior */
1974 0 : return FD_QUIC_PARSE_FAIL;
1975 0 : }
1976 :
1977 6 : if( FD_UNLIKELY( !conn ) ) {
1978 0 : FD_DTRACE_PROBE_2( fd_quic_handle_v1_retry_no_conn, state->now, pkt->pkt_number );
1979 0 : quic->metrics.pkt_no_conn_cnt[1]++;
1980 0 : return FD_QUIC_PARSE_FAIL;
1981 0 : }
1982 :
1983 6 : fd_quic_conn_id_t const * orig_dst_conn_id = &conn->peer_cids[0];
1984 6 : uchar const * retry_token = NULL;
1985 6 : ulong retry_token_sz = 0UL;
1986 :
1987 6 : int rc = fd_quic_retry_client_verify(
1988 6 : cur_ptr, cur_sz,
1989 6 : orig_dst_conn_id,
1990 6 : &conn->retry_src_conn_id,
1991 6 : &retry_token, &retry_token_sz
1992 6 : );
1993 6 : if( FD_UNLIKELY( rc!=FD_QUIC_SUCCESS ) ) {
1994 0 : quic->metrics.conn_err_retry_fail_cnt++;
1995 0 : return FD_QUIC_PARSE_FAIL;
1996 0 : }
1997 :
1998 : /* Update the peer using the retry src conn id */
1999 6 : conn->peer_cids[0] = conn->retry_src_conn_id;
2000 :
2001 : /* Re-send the ClientHello */
2002 6 : conn->hs_sent_bytes[fd_quic_enc_level_initial_id] = 0;
2003 :
2004 : /* Need to regenerate keys using the retry source connection id */
2005 6 : fd_quic_gen_initial_secret_and_keys( conn, &conn->retry_src_conn_id, /* is_server */ 0 );
2006 :
2007 : /* The token length is the remaining bytes in the retry packet after subtracting known fields. */
2008 6 : conn->token_len = retry_token_sz;
2009 6 : fd_memcpy( &conn->token, retry_token, conn->token_len );
2010 :
2011 : /* have to rewind the handshake data */
2012 6 : uint enc_level = fd_quic_enc_level_initial_id;
2013 6 : conn->hs_sent_bytes[enc_level] = 0;
2014 :
2015 : /* send the INITIAL */
2016 6 : conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
2017 :
2018 6 : fd_quic_svc_prep_schedule_now( conn );
2019 :
2020 6 : return cur_sz;
2021 6 : }
2022 :
2023 : int
2024 : fd_quic_lazy_ack_pkt( fd_quic_t * quic,
2025 : fd_quic_conn_t * conn,
2026 132625015 : fd_quic_pkt_t const * pkt ) {
2027 132625015 : if( pkt->ack_flag & ACK_FLAG_CANCEL ) {
2028 0 : return FD_QUIC_ACK_TX_CANCEL;
2029 0 : }
2030 :
2031 132625015 : fd_quic_state_t * state = fd_quic_get_state( quic );
2032 132625015 : fd_quic_ack_gen_t * ack_gen = conn->ack_gen;
2033 132625015 : int res = fd_quic_ack_pkt( conn->ack_gen, pkt->pkt_number, pkt->enc_level, state->now );
2034 132625015 : conn->ack_gen->is_elicited |= fd_uchar_if( pkt->ack_flag & ACK_FLAG_RQD, 1, 0 );
2035 :
2036 : /* Trigger immediate ACK send? */
2037 132625015 : int ack_sz_threshold_hit = conn->unacked_sz > quic->config.ack_threshold;
2038 132625015 : int force_instant_ack =
2039 132625015 : ( !!(pkt->ack_flag & ACK_FLAG_RQD) ) &
2040 132625015 : ( ( pkt->enc_level == fd_quic_enc_level_initial_id ) |
2041 132625015 : ( pkt->enc_level == fd_quic_enc_level_handshake_id ) );
2042 132625015 : if( ack_sz_threshold_hit | force_instant_ack ) {
2043 130076 : conn->unacked_sz = 0UL;
2044 130076 : fd_quic_svc_prep_schedule( conn, state->now );
2045 132494939 : } else if( ack_gen->is_elicited ) {
2046 132372549 : fd_quic_svc_prep_schedule( conn, state->now + quic->config.ack_delay );
2047 132372549 : }
2048 :
2049 132625015 : return res;
2050 132625015 : }
2051 :
2052 : /* This thunk works around a compiler bug (bogus stringop-overflow warning) in GCC 11 */
2053 : __attribute__((noinline)) static void
2054 96 : fd_quic_key_update_derive1( fd_quic_conn_t * conn ) {
2055 96 : fd_quic_key_update_derive( &conn->secrets, conn->new_keys );
2056 96 : }
2057 :
2058 : static void
2059 96 : fd_quic_key_update_complete( fd_quic_conn_t * conn ) {
2060 : /* Key updates are only possible for 1-RTT packets, which are appdata */
2061 96 : ulong const enc_level = fd_quic_enc_level_appdata_id;
2062 :
2063 : /* Update payload keys */
2064 96 : memcpy( conn->keys[enc_level][0].pkt_key, conn->new_keys[0].pkt_key, FD_AES_128_KEY_SZ );
2065 96 : memcpy( conn->keys[enc_level][0].iv, conn->new_keys[0].iv, FD_AES_GCM_IV_SZ );
2066 96 : memcpy( conn->keys[enc_level][1].pkt_key, conn->new_keys[1].pkt_key, FD_AES_128_KEY_SZ );
2067 96 : memcpy( conn->keys[enc_level][1].iv, conn->new_keys[1].iv, FD_AES_GCM_IV_SZ );
2068 :
2069 : /* Update IVs */
2070 96 : memcpy( conn->secrets.secret[enc_level][0], conn->secrets.new_secret[0], FD_QUIC_SECRET_SZ );
2071 96 : memcpy( conn->secrets.secret[enc_level][1], conn->secrets.new_secret[1], FD_QUIC_SECRET_SZ );
2072 :
2073 : /* Packet header encryption keys are not updated */
2074 :
2075 : /* Wind up for next key phase update */
2076 96 : conn->key_phase = !conn->key_phase;
2077 96 : conn->key_update = 0;
2078 96 : fd_quic_key_update_derive1( conn );
2079 :
2080 96 : FD_DEBUG( FD_LOG_DEBUG(( "key update completed" )); )
2081 96 : }
2082 :
2083 : ulong
2084 : fd_quic_handle_v1_one_rtt( fd_quic_t * quic,
2085 : fd_quic_conn_t * conn,
2086 : fd_quic_pkt_t * pkt,
2087 : uchar * const cur_ptr,
2088 7075944 : ulong const tot_sz ) {
2089 7075944 : fd_quic_state_t * state = fd_quic_get_state( quic );
2090 :
2091 7075944 : if( !conn ) {
2092 6009 : quic->metrics.pkt_no_conn_cnt[ fd_quic_enc_level_appdata_id ]++;
2093 6009 : FD_DTRACE_PROBE_2( fd_quic_handle_v1_one_rtt_no_conn , state->now, pkt->pkt_number );
2094 6009 : FD_DEBUG( FD_LOG_DEBUG(( "one_rtt failed: no connection found" )) );
2095 6009 : return FD_QUIC_PARSE_FAIL;
2096 6009 : }
2097 :
2098 7069935 : if( FD_UNLIKELY( !fd_uint_extract_bit( conn->keys_avail, fd_quic_enc_level_appdata_id ) ) ) {
2099 0 : quic->metrics.pkt_no_key_cnt[ fd_quic_enc_level_appdata_id ]++;
2100 0 : return FD_QUIC_PARSE_FAIL;
2101 0 : }
2102 :
2103 7069935 : if( FD_UNLIKELY( tot_sz < (1+FD_QUIC_CONN_ID_SZ+1) ) ) {
2104 : /* One-RTT header: 1 byte
2105 : DCID: FD_QUIC_CONN_ID_SZ
2106 : Pkt number: 1-4 bytes */
2107 0 : quic->metrics.pkt_decrypt_fail_cnt[ fd_quic_enc_level_appdata_id ]++;
2108 0 : return FD_QUIC_PARSE_FAIL;
2109 0 : }
2110 7069935 : ulong pn_offset = 1UL + FD_QUIC_CONN_ID_SZ;
2111 :
2112 7069935 : pkt->enc_level = fd_quic_enc_level_appdata_id;
2113 :
2114 7069935 : # if !FD_QUIC_DISABLE_CRYPTO
2115 7069935 : if( FD_UNLIKELY(
2116 7069935 : fd_quic_crypto_decrypt_hdr( cur_ptr, tot_sz,
2117 7069935 : pn_offset,
2118 7069935 : &conn->keys[3][0] ) != FD_QUIC_SUCCESS ) ) {
2119 0 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_crypto_decrypt_hdr failed" )) );
2120 0 : quic->metrics.pkt_decrypt_fail_cnt[ fd_quic_enc_level_appdata_id ]++;
2121 0 : return FD_QUIC_PARSE_FAIL;
2122 0 : }
2123 7069935 : # endif /* !FD_QUIC_DISABLE_CRYPTO */
2124 :
2125 7069935 : uint pkt_number_sz = fd_quic_h0_pkt_num_len( cur_ptr[0] ) + 1u;
2126 7069935 : uint key_phase = fd_quic_one_rtt_key_phase( cur_ptr[0] );
2127 :
2128 : /* reconstruct packet number */
2129 7069935 : ulong pktnum_comp = fd_quic_pktnum_decode( cur_ptr+pn_offset, pkt_number_sz );
2130 7069935 : ulong pkt_number = fd_quic_reconstruct_pkt_num( pktnum_comp, pkt_number_sz, conn->exp_pkt_number[2] );
2131 :
2132 : /* NOTE from rfc9002 s3
2133 : It is permitted for some packet numbers to never be used, leaving intentional gaps. */
2134 :
2135 : /* is current packet in the current key phase? */
2136 7069935 : int current_key_phase = conn->key_phase == key_phase;
2137 :
2138 7069935 : # if !FD_QUIC_DISABLE_CRYPTO
2139 : /* If the key phase bit flips, decrypt with the new pair of keys
2140 : instead. Note that the key phase bit is untrusted at this point. */
2141 7069935 : fd_quic_crypto_keys_t * keys = current_key_phase ? &conn->keys[3][0] : &conn->new_keys[0];
2142 :
2143 : /* this decrypts the header and payload */
2144 7069935 : if( FD_UNLIKELY(
2145 7069935 : fd_quic_crypto_decrypt( cur_ptr, tot_sz,
2146 7069935 : pn_offset,
2147 7069935 : pkt_number,
2148 7069935 : keys ) != FD_QUIC_SUCCESS ) ) {
2149 : /* remove connection from map, and insert into free list */
2150 0 : FD_DTRACE_PROBE_3( quic_err_decrypt_1rtt_pkt, pkt->ip4, conn->our_conn_id, pkt->pkt_number );
2151 0 : quic->metrics.pkt_decrypt_fail_cnt[ fd_quic_enc_level_appdata_id ]++;
2152 0 : return FD_QUIC_PARSE_FAIL;
2153 0 : }
2154 7069935 : # endif /* !FD_QUIC_DISABLE_CRYPTO */
2155 :
2156 : /* set packet number on the context */
2157 7069935 : pkt->pkt_number = pkt_number;
2158 :
2159 7069935 : if( !current_key_phase ) {
2160 : /* Decryption succeeded. Commit the key phase update and throw
2161 : away the old keys. (May cause a few decryption failures if old
2162 : packets get reordered past the current incoming packet) */
2163 96 : fd_quic_key_update_complete( conn );
2164 96 : }
2165 :
2166 : /* handle frames */
2167 7069935 : ulong payload_off = pn_offset + pkt_number_sz;
2168 7069935 : uchar const * frame_ptr = cur_ptr + payload_off;
2169 7069935 : ulong payload_sz = tot_sz - pn_offset - pkt_number_sz; /* includes auth tag */
2170 7069935 : if( FD_UNLIKELY( payload_sz<FD_QUIC_CRYPTO_TAG_SZ ) ) return FD_QUIC_PARSE_FAIL;
2171 7069935 : ulong frame_sz = payload_sz - FD_QUIC_CRYPTO_TAG_SZ; /* total size of all frames in packet */
2172 14139888 : while( frame_sz != 0UL ) {
2173 7069953 : ulong rc = fd_quic_handle_v1_frame(
2174 7069953 : quic, conn, pkt, FD_QUIC_PKT_TYPE_ONE_RTT,
2175 7069953 : frame_ptr, frame_sz );
2176 7069953 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
2177 0 : FD_DEBUG( FD_LOG_DEBUG(( "Failed to handle frame (1-RTT, frame=0x%02x)", frame_ptr[0] )) );
2178 0 : quic->metrics.frame_rx_err_cnt++;
2179 0 : return FD_QUIC_PARSE_FAIL;
2180 0 : }
2181 :
2182 7069953 : if( FD_UNLIKELY( rc == 0UL || rc > frame_sz ) ) {
2183 0 : FD_LOG_WARNING(( "fd_quic_handle_v1_frame returned invalid size" ));
2184 0 : fd_quic_conn_error( conn, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
2185 0 : return FD_QUIC_PARSE_FAIL;
2186 0 : }
2187 :
2188 : /* next frame, and remaining size */
2189 7069953 : frame_ptr += rc;
2190 7069953 : frame_sz -= rc;
2191 7069953 : }
2192 :
2193 : /* update last activity */
2194 7069935 : conn->last_activity = state->now;
2195 :
2196 : /* update expected packet number */
2197 7069935 : conn->exp_pkt_number[2] = fd_ulong_max( conn->exp_pkt_number[2], pkt_number+1UL );
2198 :
2199 7069935 : return tot_sz;
2200 7069935 : }
2201 :
2202 :
2203 : static inline int
2204 : fd_quic_src_ip_allowed( fd_quic_conn_t const * conn,
2205 7106307 : uint src_ip ) {
2206 7106307 : if( !conn ) return 1;
2207 7094223 : if( FD_LIKELY( conn->peer[0].ip_addr==src_ip ) ) return 1;
2208 :
2209 6 : FD_DEBUG( FD_LOG_DEBUG(( "Rejected packet with non-sticky peer IPv4 address; conn=%u expected=" FD_IP4_ADDR_FMT " got=" FD_IP4_ADDR_FMT,
2210 6 : conn->conn_idx,
2211 6 : FD_IP4_ADDR_FMT_ARGS( conn->peer[0].ip_addr ),
2212 6 : FD_IP4_ADDR_FMT_ARGS( src_ip ) )); )
2213 6 : return 0;
2214 7094223 : }
2215 :
2216 : /* process v1 quic packets
2217 : returns number of bytes consumed, or FD_QUIC_PARSE_FAIL upon error */
2218 :
2219 : ulong
2220 : fd_quic_process_quic_packet_v1( fd_quic_t * quic,
2221 : fd_quic_pkt_t * pkt,
2222 : uchar * cur_ptr,
2223 7106307 : ulong cur_sz ) {
2224 :
2225 : /* bounds check packet size */
2226 7106307 : if( FD_UNLIKELY( cur_sz < FD_QUIC_SHORTEST_PKT ) ) {
2227 0 : quic->metrics.pkt_undersz_cnt++;
2228 0 : return FD_QUIC_PARSE_FAIL;
2229 0 : }
2230 7106307 : if( FD_UNLIKELY( cur_sz > 1500 ) ) {
2231 0 : quic->metrics.pkt_oversz_cnt++;
2232 0 : return FD_QUIC_PARSE_FAIL;
2233 0 : }
2234 :
2235 7106307 : pkt->ack_flag = 0U;
2236 7106307 : pkt->rtt_pkt_number = 0UL;
2237 7106307 : pkt->rtt_ack_time = 0L;
2238 7106307 : pkt->rtt_ack_delay = 0UL;
2239 :
2240 7106307 : fd_quic_state_t * state = fd_quic_get_state( quic );
2241 7106307 : fd_quic_conn_t * conn = NULL;
2242 :
2243 :
2244 : /* keep end */
2245 7106307 : uchar * orig_ptr = cur_ptr;
2246 :
2247 : /* No need for cur_sz check, since we are safe from the above check.
2248 : Decrementing cur_sz is done in the long header branch, the short header
2249 : branch parses the first byte again using the parser generator.
2250 : */
2251 7106307 : uchar hdr_form = fd_quic_h0_hdr_form( *cur_ptr );
2252 7106307 : ulong rc;
2253 :
2254 7106307 : if( hdr_form ) { /* long header */
2255 30357 : fd_quic_long_hdr_t long_hdr[1];
2256 30357 : rc = fd_quic_decode_long_hdr( long_hdr, cur_ptr+1, cur_sz-1 );
2257 30357 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
2258 0 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_decode_long_hdr failed" )); )
2259 0 : quic->metrics.pkt_quic_hdr_err_cnt++;
2260 0 : return FD_QUIC_PARSE_FAIL;
2261 0 : }
2262 :
2263 30357 : fd_quic_conn_id_t dcid = fd_quic_conn_id_new( long_hdr->dst_conn_id, long_hdr->dst_conn_id_len );
2264 30357 : if( dcid.sz == FD_QUIC_CONN_ID_SZ ) {
2265 30357 : conn = fd_quic_conn_query( state->conn_map, fd_ulong_load_8( dcid.conn_id ) );
2266 30357 : }
2267 30357 : fd_quic_conn_id_t scid = fd_quic_conn_id_new( long_hdr->src_conn_id, long_hdr->src_conn_id_len );
2268 :
2269 30357 : uchar long_packet_type = fd_quic_h0_long_packet_type( *cur_ptr );
2270 :
2271 : /* encryption level matches that of TLS */
2272 30357 : pkt->enc_level = long_packet_type; /* V2 uses an indirect mapping */
2273 :
2274 : /* initialize packet number to unused value */
2275 30357 : pkt->pkt_number = FD_QUIC_PKT_NUM_UNUSED;
2276 :
2277 30357 : if( FD_UNLIKELY( !fd_quic_src_ip_allowed( conn, pkt->ip4->saddr ) ) ) {
2278 0 : quic->metrics.pkt_wrong_src_cnt++;
2279 0 : return FD_QUIC_PARSE_FAIL;
2280 0 : }
2281 :
2282 30357 : switch( long_packet_type ) {
2283 18213 : case FD_QUIC_PKT_TYPE_INITIAL:
2284 18213 : rc = fd_quic_handle_v1_initial( quic, &conn, pkt, &dcid, &scid, cur_ptr, cur_sz );
2285 18213 : if( FD_UNLIKELY( !conn ) ) {
2286 : /* FIXME not really a fail - Could be a retry */
2287 6 : return FD_QUIC_PARSE_FAIL;
2288 6 : }
2289 18207 : break;
2290 18207 : case FD_QUIC_PKT_TYPE_HANDSHAKE:
2291 12138 : rc = fd_quic_handle_v1_handshake( quic, conn, pkt, cur_ptr, cur_sz );
2292 12138 : break;
2293 6 : case FD_QUIC_PKT_TYPE_RETRY:
2294 6 : rc = fd_quic_handle_v1_retry( quic, conn, pkt, cur_ptr, cur_sz );
2295 6 : break;
2296 0 : case FD_QUIC_PKT_TYPE_ZERO_RTT:
2297 : /* fd_quic does not support 0-RTT */
2298 0 : rc = FD_QUIC_PARSE_FAIL;
2299 0 : break;
2300 30357 : }
2301 :
2302 30351 : fd_quic_svc_timers_schedule( state->svc_timers, conn, state->now );
2303 :
2304 30351 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
2305 0 : FD_DEBUG( FD_LOG_DEBUG(( "Rejected packet (type=%d)", long_packet_type )); )
2306 0 : return FD_QUIC_PARSE_FAIL;
2307 0 : }
2308 :
2309 7075950 : } else { /* short header */
2310 : /* encryption level of short header packets is fd_quic_enc_level_appdata_id */
2311 7075950 : pkt->enc_level = fd_quic_enc_level_appdata_id;
2312 :
2313 : /* initialize packet number to unused value */
2314 7075950 : pkt->pkt_number = FD_QUIC_PKT_NUM_UNUSED;
2315 :
2316 : /* find connection id */
2317 7075950 : ulong dst_conn_id = fd_ulong_load_8( cur_ptr+1 );
2318 7075950 : conn = fd_quic_conn_query( state->conn_map, dst_conn_id );
2319 :
2320 7075950 : if( FD_UNLIKELY( !fd_quic_src_ip_allowed( conn, pkt->ip4->saddr ) ) ) {
2321 6 : quic->metrics.pkt_wrong_src_cnt++;
2322 6 : return FD_QUIC_PARSE_FAIL;
2323 6 : }
2324 :
2325 7075944 : rc = fd_quic_handle_v1_one_rtt( quic, conn, pkt, cur_ptr, cur_sz );
2326 :
2327 7075944 : fd_quic_svc_timers_schedule( state->svc_timers, conn, state->now );
2328 :
2329 7075944 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
2330 6009 : return FD_QUIC_PARSE_FAIL;
2331 6009 : }
2332 7075944 : }
2333 :
2334 7100286 : if( FD_UNLIKELY( rc == 0UL ) ) {
2335 : /* this is an error because it causes infinite looping */
2336 0 : return FD_QUIC_PARSE_FAIL;
2337 0 : }
2338 7100286 : cur_ptr += rc;
2339 :
2340 : /* if we get here we parsed all the frames, so ack the packet */
2341 7100286 : int ack_type = fd_quic_lazy_ack_pkt( quic, conn, pkt );
2342 7100286 : quic->metrics.ack_tx[ ack_type ]++;
2343 :
2344 : /* fd_quic_lazy_ack_pkt may have prepped schedule */
2345 7100286 : fd_quic_svc_timers_schedule( state->svc_timers, conn, state->now );
2346 :
2347 7100286 : if( pkt->rtt_ack_time ) {
2348 54 : fd_quic_sample_rtt( conn, (long)pkt->rtt_ack_time, (long)pkt->rtt_ack_delay );
2349 54 : }
2350 :
2351 : /* return bytes consumed */
2352 7100286 : return (ulong)( cur_ptr - orig_ptr );
2353 7100286 : }
2354 :
2355 :
2356 : /* version negotiation packet has version 0 */
2357 : static inline int
2358 18219 : is_version_invalid( fd_quic_t * quic, uint version ) {
2359 18219 : if( version == 0 ) {
2360 : /* TODO implement version negotiation */
2361 0 : quic->metrics.pkt_verneg_cnt++;
2362 0 : FD_DEBUG( FD_LOG_DEBUG(( "Got version negotiation packet" )) );
2363 0 : return 1;
2364 0 : }
2365 :
2366 : /* 0x?a?a?a?au is intended to force version negotiation
2367 : TODO implement */
2368 18219 : if( ( version & 0x0a0a0a0au ) == 0x0a0a0a0au ) {
2369 : /* at present, ignore */
2370 0 : quic->metrics.pkt_verneg_cnt++;
2371 0 : FD_DEBUG( FD_LOG_DEBUG(( "Got version negotiation packet (forced)" )) );
2372 0 : return 1;
2373 0 : }
2374 :
2375 18219 : if( version != 1 ) {
2376 : /* cannot interpret length, so discard entire packet */
2377 : /* TODO send version negotiation */
2378 0 : quic->metrics.pkt_verneg_cnt++;
2379 0 : FD_DEBUG( FD_LOG_DEBUG(( "Got unknown version QUIC packet" )) );
2380 0 : return 1;
2381 0 : }
2382 18219 : return 0;
2383 18219 : }
2384 :
2385 : static inline void
2386 : fd_quic_process_packet_impl( fd_quic_t * quic,
2387 : uchar * data,
2388 : ulong data_sz,
2389 7087938 : long now ) {
2390 7087938 : fd_quic_get_state( quic )->now = now;
2391 7087938 : quic->metrics.net_rx_byte_cnt += data_sz;
2392 7087938 : quic->metrics.net_rx_pkt_cnt++;
2393 :
2394 7087938 : ulong rc = 0;
2395 :
2396 : /* holds the remainder of the packet*/
2397 7087938 : uchar * cur_ptr = data;
2398 7087938 : ulong cur_sz = data_sz;
2399 :
2400 7087938 : if( FD_UNLIKELY( data_sz > 0xffffu ) ) {
2401 0 : FD_DTRACE_PROBE( quic_err_rx_oversz );
2402 0 : quic->metrics.pkt_oversz_cnt++;
2403 0 : return;
2404 0 : }
2405 :
2406 7087938 : fd_quic_pkt_t pkt = { .datagram_sz = (uint)data_sz };
2407 :
2408 7087938 : pkt.rcv_time = now;
2409 7087938 : pkt.rtt_pkt_number = 0;
2410 7087938 : pkt.rtt_ack_time = 0;
2411 :
2412 : /* parse ip, udp */
2413 :
2414 7087938 : rc = fd_quic_decode_ip4( pkt.ip4, cur_ptr, cur_sz );
2415 7087938 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
2416 : /* TODO count failure */
2417 0 : FD_DTRACE_PROBE( quic_err_rx_net_hdr );
2418 0 : quic->metrics.pkt_net_hdr_err_cnt++;
2419 0 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_decode_ip4 failed" )) );
2420 0 : return;
2421 0 : }
2422 :
2423 : /* check version, tot_len, protocol, checksum? */
2424 7087938 : if( FD_UNLIKELY( pkt.ip4->protocol != FD_IP4_HDR_PROTOCOL_UDP ) ) {
2425 0 : FD_DTRACE_PROBE( quic_err_rx_net_hdr );
2426 0 : quic->metrics.pkt_net_hdr_err_cnt++;
2427 0 : FD_DEBUG( FD_LOG_DEBUG(( "Packet is not UDP" )) );
2428 0 : return;
2429 0 : }
2430 :
2431 : /* verify ip4 packet isn't truncated
2432 : * AF_XDP can silently do this */
2433 7087938 : if( FD_UNLIKELY( pkt.ip4->net_tot_len > cur_sz ) ) {
2434 0 : FD_DTRACE_PROBE( quic_err_rx_net_hdr );
2435 0 : quic->metrics.pkt_net_hdr_err_cnt++;
2436 0 : FD_DEBUG( FD_LOG_DEBUG(( "IPv4 header indicates truncation" )) );
2437 0 : return;
2438 0 : }
2439 :
2440 : /* update pointer + size */
2441 7087938 : cur_ptr += rc;
2442 7087938 : cur_sz -= rc;
2443 :
2444 7087938 : rc = fd_quic_decode_udp( pkt.udp, cur_ptr, cur_sz );
2445 7087938 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
2446 : /* TODO count failure */
2447 0 : FD_DTRACE_PROBE( quic_err_rx_net_hdr );
2448 0 : quic->metrics.pkt_net_hdr_err_cnt++;
2449 0 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_decode_udp failed" )) );
2450 0 : return;
2451 0 : }
2452 :
2453 : /* sanity check udp length */
2454 7087938 : if( FD_UNLIKELY( pkt.udp->net_len < sizeof(fd_udp_hdr_t) ||
2455 7087938 : pkt.udp->net_len > cur_sz ) ) {
2456 0 : FD_DTRACE_PROBE( quic_err_rx_net_hdr );
2457 0 : quic->metrics.pkt_net_hdr_err_cnt++;
2458 0 : FD_DEBUG( FD_LOG_DEBUG(( "UDP header indicates truncation" )) );
2459 0 : return;
2460 0 : }
2461 :
2462 : /* update pointer + size */
2463 7087938 : cur_ptr += rc;
2464 7087938 : cur_sz = pkt.udp->net_len - rc; /* replace with udp length */
2465 :
2466 : /* cur_ptr[0..cur_sz-1] should be payload */
2467 :
2468 : /* filter */
2469 : /* check dst eth address, ip address? probably not necessary */
2470 : /* usually look up port here, but let's jump straight into decoding as-if
2471 : quic */
2472 :
2473 : /* update counters */
2474 :
2475 : /* shortest valid quic payload? */
2476 7087938 : if( FD_UNLIKELY( cur_sz < FD_QUIC_SHORTEST_PKT ) ) {
2477 0 : FD_DTRACE_PROBE( quic_err_rx_net_hdr );
2478 0 : quic->metrics.pkt_net_hdr_err_cnt++;
2479 0 : FD_DEBUG( FD_LOG_DEBUG(( "Undersize QUIC packet" )) );
2480 0 : return;
2481 0 : }
2482 :
2483 7087938 : fd_quic_state_t * state = fd_quic_get_state( quic );
2484 :
2485 : /* short packets don't have version */
2486 7087938 : int long_pkt = !!( (uint)cur_ptr[0] & 0x80u );
2487 :
2488 7087938 : if( long_pkt ) {
2489 : /* version at offset 1..4 */
2490 18219 : uint version = fd_uint_bswap( FD_LOAD( uint, cur_ptr + 1 ) );
2491 : /* we only support version 1 */
2492 18219 : if( FD_UNLIKELY( is_version_invalid( quic, version ) ) ) {
2493 0 : return;
2494 0 : }
2495 :
2496 : /* multiple QUIC packets in a UDP packet */
2497 : /* shortest valid quic payload? */
2498 18219 : ulong pkt_idx;
2499 48570 : for( pkt_idx=0UL; pkt_idx<FD_QUIC_PKT_COALESCE_LIMIT; pkt_idx++ ) {
2500 : /* Are we done? Omit short packet handling that follows */
2501 48570 : if( FD_UNLIKELY( cur_sz < FD_QUIC_SHORTEST_PKT ) ) return;
2502 :
2503 : /* short packet requires different handling */
2504 36369 : int short_pkt = !( (uint)cur_ptr[0] & 0x80u );
2505 :
2506 36369 : if( FD_UNLIKELY( short_pkt ) ) break;
2507 :
2508 : /* check version */
2509 30357 : uint cur_version = fd_uint_bswap( FD_LOAD( uint, cur_ptr + 1 ) );
2510 :
2511 30357 : if( cur_version != version ) {
2512 : /* multiple versions in a single connection is a violation, and by
2513 : extension so is multiple versions in a single udp datagram
2514 : these are silently ignored
2515 :
2516 : for reference
2517 : all quic packets in a udp datagram must be for the same connection id
2518 : (section 12.2) and therefore the same connection
2519 : all packets on a connection must be of the same version (5.2) */
2520 0 : quic->metrics.pkt_quic_hdr_err_cnt++;
2521 0 : FD_DEBUG( FD_LOG_DEBUG(( "Mixed QUIC versions in packet" )) );
2522 0 : return;
2523 0 : }
2524 :
2525 30357 : rc = fd_quic_process_quic_packet_v1( quic, &pkt, cur_ptr, cur_sz );
2526 30357 : svc_cnt_eq_alloc_conn( state->svc_timers, quic );
2527 :
2528 : /* 0UL means no progress, so fail */
2529 30357 : if( FD_UNLIKELY( ( rc == FD_QUIC_PARSE_FAIL ) |
2530 30357 : ( rc == 0UL ) ) ) {
2531 6 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_process_quic_packet_v1 failed (stuck=%d)", rc==0UL )) );
2532 6 : return;
2533 6 : }
2534 :
2535 30351 : if( FD_UNLIKELY( rc > cur_sz ) ) {
2536 0 : FD_DEBUG( FD_LOG_WARNING(( "fd_quic_process_quic_packet_v1 read too much" )) );
2537 0 : return;
2538 0 : }
2539 :
2540 : /* return code (rc) is the number of bytes consumed */
2541 30351 : cur_sz -= rc;
2542 30351 : cur_ptr += rc;
2543 30351 : }
2544 6012 : if( pkt_idx==FD_QUIC_PKT_COALESCE_LIMIT ) {
2545 : /* too many packets in a single udp datagram */
2546 0 : return;
2547 0 : }
2548 6012 : }
2549 :
2550 : /* above can drop out of loop if a short packet is detected */
2551 7075731 : if( FD_UNLIKELY( cur_sz < FD_QUIC_SHORTEST_PKT ) ) return;
2552 :
2553 : /* short header packet
2554 : only one_rtt packets currently have short headers */
2555 7075731 : fd_quic_process_quic_packet_v1( quic, &pkt, cur_ptr, cur_sz );
2556 7075731 : svc_cnt_eq_alloc_conn( state->svc_timers, quic );
2557 7075731 : }
2558 :
2559 : void
2560 : fd_quic_process_packet( fd_quic_t * quic,
2561 : uchar * data,
2562 : ulong data_sz,
2563 7087938 : long now ) {
2564 7087938 : long now_ticks = fd_tickcount();
2565 7087938 : fd_quic_process_packet_impl( quic, data, data_sz, now );
2566 7087938 : long delta_ticks = fd_tickcount() - now_ticks;
2567 7087938 : fd_histf_sample( quic->metrics.receive_duration, (ulong)delta_ticks );
2568 7087938 : }
2569 :
2570 : /* main receive-side entry point */
2571 : int
2572 : fd_quic_aio_cb_receive( void * context,
2573 : fd_aio_pkt_info_t const * batch,
2574 : ulong batch_cnt,
2575 : ulong * opt_batch_idx,
2576 7087935 : int flush ) {
2577 7087935 : (void)flush;
2578 :
2579 7087935 : fd_quic_t * quic = context;
2580 7087935 : long now = fd_quic_get_state( quic )->now;
2581 :
2582 : /* this aio interface is configured as one-packet per buffer
2583 : so batch[0] refers to one buffer
2584 : as such, we simply forward each individual packet to a handling function */
2585 14175870 : for( ulong j = 0; j < batch_cnt; ++j ) {
2586 7087935 : fd_quic_process_packet( quic, batch[ j ].buf, batch[ j ].buf_sz, now );
2587 7087935 : }
2588 :
2589 : /* the assumption here at present is that any packet that could not be processed
2590 : is simply dropped
2591 : hence, all packets were consumed */
2592 7087935 : if( FD_LIKELY( opt_batch_idx ) ) {
2593 0 : *opt_batch_idx = batch_cnt;
2594 0 : }
2595 :
2596 7087935 : return FD_AIO_SUCCESS;
2597 7087935 : }
2598 :
2599 : void
2600 : fd_quic_tls_cb_alert( fd_quic_tls_hs_t * hs,
2601 : void * context,
2602 0 : int alert ) {
2603 0 : (void)hs;
2604 0 : fd_quic_conn_t * conn = (fd_quic_conn_t *)context;
2605 0 : (void)conn;
2606 0 : (void)alert;
2607 0 : FD_DEBUG( FD_LOG_DEBUG(( "TLS callback: %s", conn->server ? "SERVER" : "CLIENT" ));
2608 0 : FD_LOG_DEBUG(( "TLS alert: (%d-%s)", alert, fd_tls_alert_cstr( (uint)alert ) )); );
2609 :
2610 : /* TODO store alert to reply to peer */
2611 0 : }
2612 :
2613 : void
2614 : fd_quic_tls_cb_secret( fd_quic_tls_hs_t * hs,
2615 : void * context,
2616 24276 : fd_quic_tls_secret_t const * secret ) {
2617 :
2618 24276 : fd_quic_conn_t * conn = (fd_quic_conn_t*)context;
2619 24276 : fd_quic_t * quic = conn->quic;
2620 :
2621 : /* look up suite */
2622 : /* set secrets */
2623 24276 : FD_TEST( secret->enc_level < FD_QUIC_NUM_ENC_LEVELS );
2624 :
2625 24276 : uint enc_level = secret->enc_level;
2626 :
2627 24276 : fd_quic_crypto_secrets_t * crypto_secret = &conn->secrets;
2628 :
2629 24276 : memcpy( crypto_secret->secret[enc_level][0], secret->read_secret, FD_QUIC_SECRET_SZ );
2630 24276 : memcpy( crypto_secret->secret[enc_level][1], secret->write_secret, FD_QUIC_SECRET_SZ );
2631 :
2632 24276 : conn->keys_avail = fd_uint_set_bit( conn->keys_avail, (int)enc_level );
2633 :
2634 : /* gen local keys */
2635 24276 : fd_quic_gen_keys(
2636 24276 : &conn->keys[enc_level][0],
2637 24276 : conn->secrets.secret[enc_level][0] );
2638 :
2639 : /* gen peer keys */
2640 24276 : fd_quic_gen_keys(
2641 24276 : &conn->keys[enc_level][1],
2642 24276 : conn->secrets.secret[enc_level][1] );
2643 :
2644 24276 : if( enc_level==fd_quic_enc_level_appdata_id ) {
2645 12138 : fd_quic_key_update_derive( &conn->secrets, conn->new_keys );
2646 12138 : }
2647 :
2648 : /* Key logging */
2649 :
2650 24276 : void * keylog_ctx = quic->cb.quic_ctx;
2651 24276 : fd_quic_cb_tls_keylog_t keylog_fn = quic->cb.tls_keylog;
2652 24276 : if( FD_UNLIKELY( keylog_fn ) ) {
2653 : /* Ignore stdout, stderr, stdin */
2654 :
2655 24276 : uchar const * recv_secret = secret->read_secret;
2656 24276 : uchar const * send_secret = secret->write_secret;
2657 :
2658 24276 : uchar const * client_secret = hs->is_server ? recv_secret : send_secret;
2659 24276 : uchar const * server_secret = hs->is_server ? send_secret : recv_secret;
2660 :
2661 24276 : char buf[256];
2662 24276 : char * s;
2663 24276 : switch( enc_level ) {
2664 12138 : case FD_TLS_LEVEL_HANDSHAKE:
2665 12138 : /* 0 chars */ s = fd_cstr_init( buf );
2666 12138 : /* 0+32 chars */ s = fd_cstr_append_cstr( s, "CLIENT_HANDSHAKE_TRAFFIC_SECRET " );
2667 12138 : /* 32+64 chars */ s = fd_hex_encode( s, hs->hs.base.client_random, 32UL );
2668 12138 : /* 96+ 1 chars */ s = fd_cstr_append_char( s, ' ' );
2669 12138 : /* 97+64 chars */ s = fd_hex_encode( s, client_secret, 32UL );
2670 12138 : /* 161 chars */ fd_cstr_fini( s );
2671 12138 : keylog_fn( keylog_ctx, buf );
2672 12138 : /* 0 chars */ s = fd_cstr_init( buf );
2673 12138 : /* 0+32 chars */ s = fd_cstr_append_cstr( s, "SERVER_HANDSHAKE_TRAFFIC_SECRET " );
2674 12138 : /* 32+64 chars */ s = fd_hex_encode( s, hs->hs.base.client_random, 32UL );
2675 12138 : /* 96+ 1 chars */ s = fd_cstr_append_char( s, ' ' );
2676 12138 : /* 97+64 chars */ s = fd_hex_encode( s, server_secret, 32UL );
2677 12138 : /* 161 chars */ fd_cstr_fini( s );
2678 12138 : keylog_fn( keylog_ctx, buf );
2679 12138 : break;
2680 12138 : case FD_TLS_LEVEL_APPLICATION:
2681 12138 : /* 0 chars */ s = fd_cstr_init( buf );
2682 12138 : /* 0+24 chars */ s = fd_cstr_append_cstr( s, "CLIENT_TRAFFIC_SECRET_0 " );
2683 12138 : /* 24+64 chars */ s = fd_hex_encode( s, hs->hs.base.client_random, 32UL );
2684 12138 : /* 88+ 1 chars */ s = fd_cstr_append_char( s, ' ' );
2685 12138 : /* 89+64 chars */ s = fd_hex_encode( s, client_secret, 32UL );
2686 12138 : /* 153 chars */ fd_cstr_fini( s );
2687 12138 : keylog_fn( keylog_ctx, buf );
2688 12138 : /* 0 chars */ s = fd_cstr_init( buf );
2689 12138 : /* 0+24 chars */ s = fd_cstr_append_cstr( s, "SERVER_TRAFFIC_SECRET_0 " );
2690 12138 : /* 24+64 chars */ s = fd_hex_encode( s, hs->hs.base.client_random, 32UL );
2691 12138 : /* 88+ 1 chars */ s = fd_cstr_append_char( s, ' ' );
2692 12138 : /* 89+64 chars */ s = fd_hex_encode( s, server_secret, 32UL );
2693 12138 : /* 153 chars */ fd_cstr_fini( s );
2694 12138 : keylog_fn( keylog_ctx, buf );
2695 12138 : break;
2696 24276 : }
2697 24276 : }
2698 :
2699 24276 : }
2700 :
2701 : void
2702 : fd_quic_apply_peer_params( fd_quic_conn_t * conn,
2703 12144 : fd_quic_transport_params_t const * peer_tp ) {
2704 : /* flow control parameters */
2705 12144 : conn->tx_max_data = peer_tp->initial_max_data;
2706 12144 : conn->tx_initial_max_stream_data_uni= peer_tp->initial_max_stream_data_uni;
2707 :
2708 12144 : if( !conn->server ) {
2709 : /* verify retry_src_conn_id */
2710 6072 : uint retry_src_conn_id_sz = conn->retry_src_conn_id.sz;
2711 6072 : if( retry_src_conn_id_sz ) {
2712 6 : if( FD_UNLIKELY( !peer_tp->retry_source_connection_id_present
2713 6 : || peer_tp->retry_source_connection_id_len != retry_src_conn_id_sz
2714 6 : || 0 != memcmp( peer_tp->retry_source_connection_id,
2715 6 : conn->retry_src_conn_id.conn_id,
2716 6 : retry_src_conn_id_sz ) ) ) {
2717 0 : fd_quic_conn_error( conn, FD_QUIC_CONN_REASON_TRANSPORT_PARAMETER_ERROR, __LINE__ );
2718 0 : return;
2719 0 : }
2720 6066 : } else {
2721 6066 : if( FD_UNLIKELY( peer_tp->retry_source_connection_id_present ) ) {
2722 0 : fd_quic_conn_error( conn, FD_QUIC_CONN_REASON_TRANSPORT_PARAMETER_ERROR, __LINE__ );
2723 0 : return;
2724 0 : }
2725 6066 : }
2726 6072 : }
2727 :
2728 : /* max datagram size */
2729 12144 : ulong tx_max_datagram_sz = peer_tp->max_udp_payload_size;
2730 12144 : if( tx_max_datagram_sz < FD_QUIC_INITIAL_PAYLOAD_SZ_MAX ) {
2731 3 : tx_max_datagram_sz = FD_QUIC_INITIAL_PAYLOAD_SZ_MAX;
2732 3 : }
2733 12144 : if( tx_max_datagram_sz > FD_QUIC_INITIAL_PAYLOAD_SZ_MAX ) {
2734 12141 : tx_max_datagram_sz = FD_QUIC_INITIAL_PAYLOAD_SZ_MAX;
2735 12141 : }
2736 12144 : conn->tx_max_datagram_sz = (uint)tx_max_datagram_sz;
2737 12144 : conn->tx_max_datagram_frame_sz = fd_ulong_if(
2738 12144 : peer_tp->max_datagram_frame_size_present,
2739 12144 : peer_tp->max_datagram_frame_size,
2740 12144 : 0UL );
2741 :
2742 : /* initial max_streams */
2743 :
2744 12144 : if( conn->server ) {
2745 6072 : conn->tx_sup_stream_id = ( (ulong)peer_tp->initial_max_streams_uni << 2UL ) + FD_QUIC_STREAM_TYPE_UNI_SERVER;
2746 6072 : } else {
2747 6072 : conn->tx_sup_stream_id = ( (ulong)peer_tp->initial_max_streams_uni << 2UL ) + FD_QUIC_STREAM_TYPE_UNI_CLIENT;
2748 6072 : }
2749 :
2750 : /* set the max_idle_timeout to the min of our and peer max_idle_timeout */
2751 12144 : if( peer_tp->max_idle_timeout_ms ) {
2752 12138 : long peer_max_idle_timeout_ns = fd_long_sat_mul( (long)peer_tp->max_idle_timeout_ms, (long)1e6);
2753 12138 : conn->idle_timeout_ns = fd_long_min( peer_max_idle_timeout_ns, conn->idle_timeout_ns );
2754 12138 : }
2755 :
2756 : /* set ack_delay_exponent so we can properly interpret peer's ack_delays
2757 : if unspecified, the value is 3 */
2758 12144 : ulong peer_ack_delay_exponent = fd_ulong_if(
2759 12144 : peer_tp->ack_delay_exponent_present,
2760 12144 : peer_tp->ack_delay_exponent,
2761 12144 : 3UL );
2762 :
2763 12144 : conn->peer_ack_delay_scale = (float)( 1UL << peer_ack_delay_exponent ) * 1e3f;
2764 :
2765 : /* peer max ack delay in microseconds
2766 : peer_tp->max_ack_delay is milliseconds */
2767 12144 : float peer_max_ack_delay_us = (float)fd_ulong_if(
2768 12144 : peer_tp->max_ack_delay_present,
2769 12144 : peer_tp->max_ack_delay * 1000UL,
2770 12144 : 25000UL );
2771 12144 : conn->peer_max_ack_delay_ns = peer_max_ack_delay_us * 1e3f;
2772 :
2773 12144 : conn->transport_params_set = 1;
2774 12144 : }
2775 :
2776 : void
2777 : fd_quic_tls_cb_peer_params( void * context,
2778 : uchar const * peer_tp_enc,
2779 12141 : ulong peer_tp_enc_sz ) {
2780 12141 : fd_quic_conn_t * conn = (fd_quic_conn_t*)context;
2781 :
2782 : /* decode peer transport parameters */
2783 12141 : fd_quic_transport_params_t peer_tp[1] = {0};
2784 12141 : int rc = fd_quic_decode_transport_params( peer_tp, peer_tp_enc, peer_tp_enc_sz );
2785 12141 : if( FD_UNLIKELY( rc != 0 ) ) {
2786 0 : FD_DEBUG( FD_LOG_NOTICE(( "fd_quic_decode_transport_params failed" )); )
2787 : /* failed to parse transport params */
2788 0 : fd_quic_conn_error( conn, FD_QUIC_CONN_REASON_TRANSPORT_PARAMETER_ERROR, __LINE__ );
2789 0 : return;
2790 0 : }
2791 :
2792 12141 : fd_quic_apply_peer_params( conn, peer_tp );
2793 12141 : }
2794 :
2795 : void
2796 : fd_quic_tls_cb_handshake_complete( fd_quic_tls_hs_t * hs,
2797 12138 : void * context ) {
2798 12138 : (void)hs;
2799 12138 : fd_quic_conn_t * conn = (fd_quic_conn_t *)context;
2800 :
2801 : /* need to send quic handshake completion */
2802 12138 : switch( conn->state ) {
2803 0 : case FD_QUIC_CONN_STATE_ABORT:
2804 0 : case FD_QUIC_CONN_STATE_CLOSE_PENDING:
2805 0 : case FD_QUIC_CONN_STATE_DEAD:
2806 : /* ignore */
2807 0 : return;
2808 :
2809 12138 : case FD_QUIC_CONN_STATE_HANDSHAKE:
2810 12138 : if( FD_UNLIKELY( !conn->transport_params_set ) ) { /* unreachable */
2811 0 : FD_LOG_WARNING(( "Handshake marked as completed but transport params are not set. This is a bug!" ));
2812 0 : fd_quic_conn_error( conn, FD_QUIC_CONN_REASON_INTERNAL_ERROR, __LINE__ );
2813 0 : return;
2814 0 : }
2815 12138 : conn->handshake_complete = 1;
2816 12138 : fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_HANDSHAKE_COMPLETE );
2817 12138 : return;
2818 :
2819 0 : default:
2820 0 : FD_LOG_WARNING(( "handshake in unexpected state: %u", conn->state ));
2821 12138 : }
2822 12138 : }
2823 :
2824 : static ulong
2825 : fd_quic_handle_crypto_frame( fd_quic_frame_ctx_t * context,
2826 : fd_quic_crypto_frame_t * crypto,
2827 : uchar const * p,
2828 60696 : ulong p_sz ) {
2829 : /* determine whether any of the data was already provided */
2830 60696 : fd_quic_conn_t * conn = context->conn;
2831 60696 : fd_quic_tls_hs_t * tls_hs = conn->tls_hs;
2832 60696 : uint enc_level = context->pkt->enc_level;
2833 :
2834 : /* offset expected */
2835 60696 : ulong rcv_off = crypto->offset; /* in [0,2^62-1] */
2836 60696 : ulong rcv_sz = crypto->length; /* in [0,2^62-1] */
2837 60696 : ulong rcv_hi = rcv_off + rcv_sz; /* in [0,2^63-1] */
2838 :
2839 60696 : if( FD_UNLIKELY( rcv_sz > p_sz ) ) {
2840 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
2841 0 : return FD_QUIC_PARSE_FAIL;
2842 0 : }
2843 :
2844 60696 : if( !tls_hs ) {
2845 : /* Handshake already completed. Ignore frame */
2846 : /* TODO consider aborting conn if too many unsolicited crypto frames arrive */
2847 0 : return rcv_sz;
2848 0 : }
2849 :
2850 60696 : if( enc_level < tls_hs->rx_enc_level ) {
2851 0 : return rcv_sz;
2852 0 : }
2853 :
2854 60696 : if( enc_level > tls_hs->rx_enc_level ) {
2855 : /* Discard data from any previous handshake level. Currently only
2856 : happens at the Initial->Handshake encryption level change. */
2857 12138 : tls_hs->rx_enc_level = (uchar)enc_level;
2858 12138 : tls_hs->rx_off = 0;
2859 12138 : tls_hs->rx_sz = 0;
2860 12138 : }
2861 :
2862 60696 : if( rcv_off > tls_hs->rx_sz ) {
2863 0 : context->pkt->ack_flag |= ACK_FLAG_CANCEL;
2864 0 : return rcv_sz;
2865 0 : }
2866 :
2867 60696 : if( rcv_hi < tls_hs->rx_off ) {
2868 0 : return rcv_sz;
2869 0 : }
2870 :
2871 60696 : if( rcv_hi > FD_QUIC_TLS_RX_DATA_SZ ) {
2872 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_CRYPTO_BUFFER_EXCEEDED, __LINE__ );
2873 0 : return FD_QUIC_PARSE_FAIL;
2874 0 : }
2875 :
2876 60696 : if( rcv_hi > tls_hs->rx_sz ) tls_hs->rx_sz = (ushort)rcv_hi;
2877 60696 : fd_memcpy( tls_hs->rx_hs_buf + rcv_off, p, rcv_sz );
2878 :
2879 60696 : int provide_rc = fd_quic_tls_process( conn->tls_hs );
2880 60696 : if( provide_rc == FD_QUIC_FAILED ) {
2881 : /* if TLS fails, ABORT connection */
2882 :
2883 : /* if TLS returns an error, we present that as reason:
2884 : FD_QUIC_CONN_REASON_CRYPTO_BASE + tls-alert
2885 : otherwise, send INTERNAL_ERROR */
2886 3 : uint alert = conn->tls_hs->alert;
2887 3 : uint reason = conn->tls_hs->hs.base.reason;
2888 3 : FD_DTRACE_PROBE_3( quic_handle_crypto_frame, conn->our_conn_id, alert, reason );
2889 3 : if( alert == 0u ) {
2890 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_INTERNAL_ERROR, __LINE__ );
2891 3 : } else {
2892 3 : FD_DEBUG(
2893 3 : FD_LOG_DEBUG(( "QUIC TLS handshake failed (alert %u-%s; reason %u-%s)",
2894 3 : alert, fd_tls_alert_cstr( alert ),
2895 3 : reason, fd_tls_reason_cstr( reason ) ));
2896 3 : )
2897 3 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_CRYPTO_BASE + alert, __LINE__ );
2898 3 : }
2899 3 : return FD_QUIC_PARSE_FAIL;
2900 3 : }
2901 :
2902 60693 : return rcv_sz;
2903 60696 : }
2904 :
2905 : static int
2906 : fd_quic_svc_poll( fd_quic_t * quic,
2907 : fd_quic_conn_t * conn,
2908 7071339 : long now ) {
2909 7071339 : fd_quic_state_t * state = fd_quic_get_state( quic );
2910 7071339 : if( FD_UNLIKELY( conn->state == FD_QUIC_CONN_STATE_INVALID ) ) {
2911 : /* connection shouldn't have been scheduled,
2912 : and is now removed, so just continue */
2913 0 : FD_LOG_CRIT(( "Invalid conn in schedule" ));
2914 0 : return 1;
2915 0 : }
2916 :
2917 7071339 : if( FD_UNLIKELY( now >= conn->last_activity + ( conn->idle_timeout_ns / 2 ) ) ) {
2918 48 : if( FD_UNLIKELY( now >= conn->last_activity + conn->idle_timeout_ns ) ) {
2919 24 : if( FD_LIKELY( conn->state != FD_QUIC_CONN_STATE_DEAD ) ) {
2920 : /* rfc9000 10.1 Idle Timeout
2921 : "... the connection is silently closed and its state is discarded
2922 : when it remains idle for longer than the minimum of the
2923 : max_idle_timeout value advertised by both endpoints." */
2924 24 : FD_DEBUG( FD_LOG_WARNING(("%s conn %p conn_idx: %u closing due to idle timeout=%gms last_activity=%ld now=%ld",
2925 24 : conn->server?"SERVER":"CLIENT",
2926 24 : (void *)conn, conn->conn_idx,
2927 24 : (double)conn->idle_timeout_ns / 1e6,
2928 24 : conn->last_activity,
2929 24 : now
2930 24 : )); )
2931 :
2932 24 : fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_DEAD );
2933 24 : quic->metrics.conn_timeout_cnt++;
2934 24 : }
2935 24 : } else if( quic->config.keep_alive & !!(conn->let_die_time_ns > now) ) {
2936 : /* send PING */
2937 12 : if( !( conn->flags & ( FD_QUIC_CONN_FLAGS_PING | FD_QUIC_CONN_FLAGS_PING_SENT ) ) ) {
2938 12 : conn->flags |= FD_QUIC_CONN_FLAGS_PING;
2939 12 : conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING; /* update to be sent in next packet */
2940 12 : }
2941 12 : }
2942 48 : }
2943 :
2944 7071339 : if( FD_UNLIKELY( conn->state == FD_QUIC_CONN_STATE_DEAD ) ) {
2945 24 : fd_quic_cb_conn_final( quic, conn ); /* inform user before freeing */
2946 24 : fd_quic_conn_free( quic, conn );
2947 24 : return 1; /* do NOT reschedule freed connection */
2948 24 : }
2949 :
2950 : /* state cannot be DEAD here */
2951 7071315 : fd_quic_conn_service( quic, conn, now );
2952 :
2953 : /* dead? don't reinsert, just clean up */
2954 7071315 : switch( conn->state ) {
2955 0 : case FD_QUIC_CONN_STATE_INVALID:
2956 : /* skip entirely */
2957 0 : break;
2958 12024 : case FD_QUIC_CONN_STATE_DEAD:
2959 12024 : fd_quic_cb_conn_final( quic, conn ); /* inform user before freeing */
2960 12024 : fd_quic_conn_free( quic, conn );
2961 12024 : break;
2962 7059291 : default: {
2963 : /* Should we schedule for keep-alive or timeout?
2964 : 1. If keep_alive not configured, for timeout
2965 : 2. Else, if we've crossed the halfway point, we must have just pinged,
2966 : and should therefore schedule timeout. Otherwise, we should schedule
2967 : for the keep-alive time. */
2968 7059291 : long const timeout_ns = conn->idle_timeout_ns;
2969 7059291 : long const last_activity = conn->last_activity;
2970 7059291 : int const keep_alive = quic->config.keep_alive & (now < last_activity+timeout_ns/2L);
2971 7059291 : fd_quic_svc_prep_schedule( conn, last_activity + (timeout_ns>>keep_alive) );
2972 7059291 : fd_quic_svc_timers_schedule( state->svc_timers, conn, state->now );
2973 7059291 : break;
2974 0 : }
2975 7071315 : }
2976 :
2977 7071315 : return 1;
2978 7071315 : }
2979 :
2980 : int
2981 : fd_quic_service( fd_quic_t * quic,
2982 139509363 : long now ) {
2983 139509363 : fd_quic_state_t * state = fd_quic_get_state( quic );
2984 :
2985 139509363 : state->now = now;
2986 139509363 : long now_ticks = fd_tickcount();
2987 :
2988 139509363 : fd_quic_svc_timers_t * timers = state->svc_timers;
2989 139509363 : svc_cnt_eq_alloc_conn( timers, quic );
2990 139509363 : fd_quic_svc_event_t next = fd_quic_svc_timers_next( timers, now, 1 /* pop */);
2991 139509363 : if( FD_UNLIKELY( next.conn == NULL ) ) {
2992 132438024 : return 0;
2993 132438024 : }
2994 :
2995 7071339 : int cnt = fd_quic_svc_poll( quic, next.conn, now );
2996 :
2997 7071339 : long delta_ticks = fd_tickcount() - now_ticks;
2998 :
2999 7071339 : fd_histf_sample( quic->metrics.service_duration, (ulong)delta_ticks );
3000 :
3001 7071339 : return cnt;
3002 139509363 : }
3003 :
3004 : static inline ulong FD_FN_UNUSED
3005 7106301 : fd_quic_conn_tx_buf_remaining( fd_quic_conn_t * conn ) {
3006 7106301 : return (ulong)( sizeof( conn->tx_buf_conn ) - (ulong)( conn->tx_ptr - conn->tx_buf_conn ) );
3007 7106301 : }
3008 :
3009 : ulong
3010 : fd_quic_conn_tx_dgram( fd_quic_conn_t * conn,
3011 : uchar * pkt,
3012 : ulong pkt_sz,
3013 : uchar const * dgram,
3014 9 : ulong dgram_sz ) {
3015 9 : if( FD_UNLIKELY( !conn || !pkt || (!dgram && dgram_sz) ) ) return 0UL;
3016 9 : if( FD_UNLIKELY( conn->state!=FD_QUIC_CONN_STATE_ACTIVE ) ) return 0UL;
3017 9 : if( FD_UNLIKELY( !fd_uint_extract_bit( conn->keys_avail, fd_quic_enc_level_appdata_id ) ) ) return 0UL;
3018 9 : if( FD_UNLIKELY( dgram_sz>USHORT_MAX ) ) return 0UL;
3019 :
3020 : /* RFC 9221 Section 3: max_datagram_frame_size covers the complete
3021 : DATAGRAM frame, including type and length fields. */
3022 9 : ulong const len_sz = fd_quic_varint_min_sz( dgram_sz );
3023 9 : ulong const frame_sz = 1UL + len_sz + dgram_sz;
3024 9 : if( FD_UNLIKELY( !conn->tx_max_datagram_frame_sz ||
3025 9 : frame_sz>conn->tx_max_datagram_frame_sz ) ) return 0UL;
3026 :
3027 6 : uint const pn_space = fd_quic_enc_level_to_pn_space( fd_quic_enc_level_appdata_id );
3028 6 : ulong const pkt_num = conn->pkt_number[ pn_space ];
3029 6 : uint const pn_sz = 4U;
3030 6 : uint const pn_sz_enc= pn_sz-1U;
3031 :
3032 6 : fd_quic_conn_id_t const * peer_conn_id = &conn->peer_cids[0];
3033 6 : if( FD_UNLIKELY( peer_conn_id->sz>FD_QUIC_MAX_CONN_ID_SZ ) ) return 0UL;
3034 :
3035 6 : fd_quic_state_t * state = fd_quic_get_state( conn->quic );
3036 6 : uchar * scratch = state->crypt_scratch;
3037 6 : ulong scratch_sz = sizeof( state->crypt_scratch );
3038 :
3039 6 : int const key_phase_upd = (int)conn->key_update;
3040 6 : uint const key_phase_tx = conn->key_phase ^ (uint)key_phase_upd;
3041 6 : fd_quic_one_rtt_t one_rtt = {0};
3042 6 : one_rtt.h0 = fd_quic_one_rtt_h0( 0, !!key_phase_tx, pn_sz_enc );
3043 6 : one_rtt.dst_conn_id_len = peer_conn_id->sz;
3044 6 : one_rtt.pkt_num = pkt_num;
3045 6 : fd_memcpy( one_rtt.dst_conn_id, peer_conn_id->conn_id, peer_conn_id->sz );
3046 :
3047 6 : ulong const hdr_sz = fd_quic_encode_one_rtt( scratch, scratch_sz, &one_rtt );
3048 6 : if( FD_UNLIKELY( hdr_sz==FD_QUIC_ENCODE_FAIL ) ) return 0UL;
3049 :
3050 6 : ulong padding = 0UL;
3051 6 : ulong const protected_payload_sz = frame_sz + FD_QUIC_CRYPTO_TAG_SZ;
3052 6 : ulong const sample_min_sz = FD_QUIC_CRYPTO_SAMPLE_OFFSET_FROM_PKT_NUM_START +
3053 6 : FD_QUIC_CRYPTO_SAMPLE_SZ;
3054 6 : if( protected_payload_sz+pn_sz < sample_min_sz ) {
3055 0 : padding = sample_min_sz - pn_sz - protected_payload_sz;
3056 0 : }
3057 :
3058 6 : ulong const plain_sz = frame_sz + padding;
3059 6 : ulong const out_sz = hdr_sz + plain_sz + FD_QUIC_CRYPTO_TAG_SZ;
3060 6 : if( FD_UNLIKELY(
3061 6 : out_sz>pkt_sz ||
3062 6 : out_sz>conn->tx_max_datagram_sz ||
3063 6 : hdr_sz+plain_sz>scratch_sz
3064 6 : ) ) {
3065 3 : return 0UL;
3066 3 : }
3067 :
3068 3 : uchar * p = scratch + hdr_sz;
3069 3 : *p++ = 0x31U; /* DATAGRAM with an explicit Length field */
3070 3 : p += fd_quic_varint_encode( p, dgram_sz );
3071 3 : if( dgram_sz ) fd_memcpy( p, dgram, dgram_sz );
3072 3 : p += dgram_sz;
3073 3 : fd_memset( p, 0, padding );
3074 :
3075 : #if FD_QUIC_DISABLE_CRYPTO
3076 : fd_memcpy( pkt, scratch, hdr_sz+plain_sz );
3077 : fd_memset( pkt+hdr_sz+plain_sz, 0, FD_QUIC_CRYPTO_TAG_SZ );
3078 : #else
3079 3 : ulong cipher_sz = pkt_sz;
3080 3 : fd_quic_crypto_keys_t * hp_keys = &conn->keys[fd_quic_enc_level_appdata_id][1];
3081 3 : fd_quic_crypto_keys_t * pkt_keys = key_phase_upd ? &conn->new_keys[1] : hp_keys;
3082 3 : int enc_res = fd_quic_crypto_encrypt(
3083 3 : pkt,
3084 3 : &cipher_sz,
3085 3 : scratch, hdr_sz,
3086 3 : scratch + hdr_sz,
3087 3 : plain_sz,
3088 3 : pkt_keys, hp_keys,
3089 3 : pkt_num
3090 3 : );
3091 3 : if( FD_UNLIKELY( enc_res!=FD_QUIC_SUCCESS ) ) return 0UL;
3092 3 : if( FD_UNLIKELY( cipher_sz!=out_sz ) ) return 0UL;
3093 3 : #endif
3094 :
3095 3 : conn->pkt_number[ pn_space ] = pkt_num + 1UL;
3096 3 : return out_sz;
3097 3 : }
3098 :
3099 : /* attempt to transmit buffered data
3100 :
3101 : prior to call, conn->tx_ptr points to the first free byte in tx_buf
3102 : the data in tx_buf..tx_ptr is prepended by networking headers
3103 : and put on the wire
3104 :
3105 : returns 0 if successful, or 1 otherwise */
3106 : uint
3107 : fd_quic_tx_buffered_raw(
3108 : fd_quic_t * quic,
3109 : uchar ** tx_ptr_ptr,
3110 : uchar * tx_buf,
3111 : ushort * ipv4_id,
3112 : uint dst_ipv4_addr,
3113 : ushort dst_udp_port,
3114 : uint src_ipv4_addr,
3115 : ushort src_udp_port
3116 14147382 : ) {
3117 :
3118 : /* TODO leave space at front of tx_buf for header
3119 : then encode directly into it to avoid 1 copy */
3120 14147382 : uchar *tx_ptr = *tx_ptr_ptr;
3121 14147382 : long payload_sz = tx_ptr - tx_buf;
3122 :
3123 : /* nothing to do */
3124 14147382 : if( FD_UNLIKELY( payload_sz<=0L ) ) {
3125 7059225 : return 0u;
3126 7059225 : }
3127 :
3128 7088157 : fd_quic_config_t * config = &quic->config;
3129 7088157 : fd_quic_state_t * state = fd_quic_get_state( quic );
3130 :
3131 7088157 : uchar * const crypt_scratch = state->crypt_scratch;
3132 :
3133 7088157 : uchar * cur_ptr = state->crypt_scratch;
3134 7088157 : ulong cur_sz = sizeof( state->crypt_scratch );
3135 :
3136 : /* TODO much of this may be prepared ahead of time */
3137 7088157 : fd_quic_pkt_t pkt;
3138 :
3139 7088157 : pkt.ip4->verihl = FD_IP4_VERIHL(4,5);
3140 7088157 : pkt.ip4->tos = (uchar)(config->net.dscp << 2); /* could make this per-connection or per-stream */
3141 7088157 : pkt.ip4->net_tot_len = (ushort)( 20 + 8 + payload_sz );
3142 7088157 : pkt.ip4->net_id = *ipv4_id;
3143 7088157 : pkt.ip4->net_frag_off = 0x4000u; /* don't fragment */
3144 7088157 : pkt.ip4->ttl = 64; /* TODO make configurable */
3145 7088157 : pkt.ip4->protocol = FD_IP4_HDR_PROTOCOL_UDP;
3146 7088157 : pkt.ip4->check = 0;
3147 7088157 : pkt.ip4->saddr = src_ipv4_addr;
3148 7088157 : pkt.ip4->daddr = dst_ipv4_addr;
3149 7088157 : pkt.udp->net_sport = src_udp_port;
3150 7088157 : pkt.udp->net_dport = dst_udp_port;
3151 7088157 : pkt.udp->net_len = (ushort)( 8 + payload_sz );
3152 7088157 : pkt.udp->check = 0x0000;
3153 7088157 : *ipv4_id = (ushort)( *ipv4_id + 1 );
3154 :
3155 7088157 : ulong rc = fd_quic_encode_ip4( cur_ptr, cur_sz, pkt.ip4 );
3156 7088157 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
3157 0 : FD_LOG_ERR(( "fd_quic_encode_ip4 failed with buffer overrun" ));
3158 0 : }
3159 :
3160 : /* Compute checksum over network byte order header */
3161 7088157 : fd_ip4_hdr_t * ip4_encoded = (fd_ip4_hdr_t *)fd_type_pun( cur_ptr );
3162 7088157 : ip4_encoded->check = (ushort)fd_ip4_hdr_check_fast( ip4_encoded );
3163 :
3164 7088157 : cur_ptr += rc;
3165 7088157 : cur_sz -= rc;
3166 :
3167 7088157 : rc = fd_quic_encode_udp( cur_ptr, cur_sz, pkt.udp );
3168 7088157 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
3169 0 : FD_LOG_ERR(( "fd_quic_encode_udp failed with buffer overrun" ));
3170 0 : }
3171 :
3172 7088157 : cur_ptr += rc;
3173 7088157 : cur_sz -= rc;
3174 :
3175 : /* need enough space for payload */
3176 7088157 : if( FD_UNLIKELY( (ulong)payload_sz > cur_sz ) ) {
3177 0 : FD_LOG_WARNING(( "%s : payload too big for buffer", __func__ ));
3178 :
3179 : /* reset buffer, since we can't use its contents */
3180 0 : *tx_ptr_ptr = tx_buf;
3181 0 : return FD_QUIC_FAILED;
3182 0 : }
3183 7088157 : fd_memcpy( cur_ptr, tx_buf, (ulong)payload_sz );
3184 :
3185 7088157 : cur_ptr += (ulong)payload_sz;
3186 7088157 : cur_sz -= (ulong)payload_sz;
3187 :
3188 7088157 : fd_aio_pkt_info_t aio_buf = { .buf = crypt_scratch, .buf_sz = (ushort)( cur_ptr - crypt_scratch ) };
3189 7088157 : int aio_rc = fd_aio_send( &quic->aio_tx, &aio_buf, 1, NULL, 1 );
3190 7088157 : if( aio_rc == FD_AIO_ERR_AGAIN ) {
3191 : /* transient condition - try later */
3192 0 : return FD_QUIC_FAILED;
3193 7088157 : } else if( aio_rc != FD_AIO_SUCCESS ) {
3194 0 : FD_LOG_WARNING(( "Fatal error reported by aio peer" ));
3195 : /* fallthrough to reset buffer */
3196 0 : }
3197 :
3198 : /* after send, reset tx_ptr and tx_sz */
3199 7088157 : *tx_ptr_ptr = tx_buf;
3200 :
3201 7088157 : quic->metrics.net_tx_pkt_cnt += aio_rc==FD_AIO_SUCCESS;
3202 7088157 : if( FD_LIKELY( aio_rc==FD_AIO_SUCCESS ) ) {
3203 7088157 : quic->metrics.net_tx_byte_cnt += aio_buf.buf_sz;
3204 7088157 : }
3205 :
3206 7088157 : return FD_QUIC_SUCCESS; /* success */
3207 7088157 : }
3208 :
3209 : uint
3210 : fd_quic_tx_buffered( fd_quic_t * quic,
3211 14147376 : fd_quic_conn_t * conn ) {
3212 14147376 : fd_quic_net_endpoint_t const * endpoint = conn->peer;
3213 14147376 : return fd_quic_tx_buffered_raw(
3214 14147376 : quic,
3215 14147376 : &conn->tx_ptr,
3216 14147376 : conn->tx_buf_conn,
3217 14147376 : &conn->ipv4_id,
3218 14147376 : endpoint->ip_addr,
3219 14147376 : endpoint->udp_port,
3220 14147376 : conn->host.ip_addr,
3221 14147376 : conn->host.udp_port);
3222 14147376 : }
3223 :
3224 : static inline int
3225 : fd_quic_conn_can_acquire_pkt_meta( fd_quic_conn_t * conn,
3226 13943747 : fd_quic_pkt_meta_tracker_t * tracker ) {
3227 13943747 : fd_quic_state_t * state = fd_quic_get_state( conn->quic );
3228 13943747 : fd_quic_metrics_t * metrics = &conn->quic->metrics;
3229 :
3230 13943747 : ulong pool_free = fd_quic_pkt_meta_pool_free( tracker->pool );
3231 13943747 : if( !pool_free || conn->used_pkt_meta >= state->max_inflight_frame_cnt_conn ) {
3232 48 : if( !pool_free ) {
3233 45 : metrics->frame_tx_alloc_cnt[FD_METRICS_ENUM_FRAME_TX_ALLOC_RESULT_V_FAIL_EMPTY_POOL_IDX]++;
3234 45 : } else {
3235 3 : metrics->frame_tx_alloc_cnt[FD_METRICS_ENUM_FRAME_TX_ALLOC_RESULT_V_FAIL_CONNECTION_MAX_IDX]++;
3236 3 : }
3237 48 : return 0;
3238 48 : }
3239 13943699 : metrics->frame_tx_alloc_cnt[FD_METRICS_ENUM_FRAME_TX_ALLOC_RESULT_V_SUCCESS_IDX]++;
3240 :
3241 13943699 : return 1;
3242 13943747 : }
3243 :
3244 : /* fd_quic_gen_frame_store_pkt_meta stores a pkt_meta into tracker.
3245 : Value and type take the passed args; all other fields are copied
3246 : from pkt_meta_tmpl. Returns 1 if successful, 0 if not.
3247 : Failure reasons include empty pkt_meta pool, or this conn reached
3248 : its pkt_meta limit. Theoretically only need latter, but let's be safe! */
3249 : static inline int
3250 : fd_quic_gen_frame_store_pkt_meta( const fd_quic_pkt_meta_t * pkt_meta_tmpl,
3251 : uchar type,
3252 : fd_quic_pkt_meta_value_t value,
3253 : fd_quic_pkt_meta_tracker_t * tracker,
3254 6984001 : fd_quic_conn_t * conn ) {
3255 6984001 : if( !fd_quic_conn_can_acquire_pkt_meta( conn, tracker ) ) return 0;
3256 :
3257 6983956 : conn->used_pkt_meta++;
3258 6983956 : fd_quic_pkt_meta_t * pkt_meta = fd_quic_pkt_meta_pool_ele_acquire( tracker->pool );
3259 6983956 : *pkt_meta = *pkt_meta_tmpl;
3260 6983956 : FD_QUIC_PKT_META_SET_TYPE( pkt_meta, type );
3261 6983956 : pkt_meta->val = value;
3262 6983956 : fd_quic_pkt_meta_insert( &tracker->sent_pkt_metas[pkt_meta->enc_level], pkt_meta, tracker->pool );
3263 6983956 : return 1;
3264 6984001 : }
3265 :
3266 : static ulong
3267 : fd_quic_gen_close_frame( fd_quic_conn_t * conn,
3268 : uchar * payload_ptr,
3269 : uchar * payload_end,
3270 : const fd_quic_pkt_meta_t * pkt_meta_tmpl,
3271 12024 : fd_quic_pkt_meta_tracker_t * tracker ) {
3272 :
3273 12024 : if( conn->flags & FD_QUIC_CONN_FLAGS_CLOSE_SENT ) return 0UL;
3274 12024 : conn->flags |= FD_QUIC_CONN_FLAGS_CLOSE_SENT;
3275 :
3276 12024 : ulong frame_sz;
3277 12024 : if( conn->reason != 0u || conn->state == FD_QUIC_CONN_STATE_PEER_CLOSE ) {
3278 6006 : fd_quic_conn_close_0_frame_t frame = {
3279 6006 : .error_code = conn->reason,
3280 6006 : .frame_type = 0u, /* we do not know the frame in question */
3281 6006 : .reason_phrase_length = 0u /* no reason phrase */
3282 6006 : };
3283 6006 : frame_sz = fd_quic_encode_conn_close_0_frame( payload_ptr,
3284 6006 : (ulong)( payload_end - payload_ptr ),
3285 6006 : &frame );
3286 6018 : } else {
3287 6018 : fd_quic_conn_close_1_frame_t frame = {
3288 6018 : .error_code = conn->app_reason,
3289 6018 : .reason_phrase_length = 0u /* no reason phrase */
3290 6018 : };
3291 6018 : frame_sz = fd_quic_encode_conn_close_1_frame( payload_ptr,
3292 6018 : (ulong)( payload_end - payload_ptr ),
3293 6018 : &frame );
3294 6018 : }
3295 :
3296 12024 : if( FD_UNLIKELY( frame_sz == FD_QUIC_PARSE_FAIL ) ) {
3297 0 : FD_LOG_WARNING(( "fd_quic_encode_conn_close_frame failed, but space should have been available" ));
3298 0 : return 0UL;
3299 0 : }
3300 :
3301 : /* create and save pkt_meta, return 0 if fail */
3302 12024 : if( !fd_quic_gen_frame_store_pkt_meta( pkt_meta_tmpl,
3303 12024 : FD_QUIC_PKT_META_TYPE_CLOSE,
3304 12024 : (fd_quic_pkt_meta_value_t){0}, /* value doesn't matter */
3305 12024 : tracker,
3306 12024 : conn )) return 0UL;
3307 :
3308 12024 : return frame_sz;
3309 12024 : }
3310 :
3311 : static uchar *
3312 : fd_quic_gen_handshake_frames( fd_quic_conn_t * conn,
3313 : uchar * payload_ptr,
3314 : uchar * payload_end,
3315 : const fd_quic_pkt_meta_t * pkt_meta_tmpl,
3316 7094367 : fd_quic_pkt_meta_tracker_t * tracker ) {
3317 7094367 : uint enc_level = pkt_meta_tmpl->enc_level;
3318 7094367 : fd_quic_tls_hs_data_t * hs_data = fd_quic_tls_get_hs_data( conn->tls_hs, enc_level );
3319 7094367 : if( !hs_data ) return payload_ptr;
3320 :
3321 : /* confirm we have pkt_meta space */
3322 24282 : if( !fd_quic_conn_can_acquire_pkt_meta( conn, tracker ) ) return payload_ptr;
3323 :
3324 24282 : ulong hs_offset = 0; /* offset within the current hs_data */
3325 24282 : ulong sent_offset = conn->hs_sent_bytes[enc_level];
3326 24282 : ulong ackd_offset = conn->hs_ackd_bytes[enc_level];
3327 : /* offset within stream */
3328 24282 : ulong offset = fd_ulong_max( sent_offset, ackd_offset );
3329 :
3330 : /* track pkt_meta values */
3331 24282 : ulong offset_lo = offset;
3332 24282 : ulong offset_hi = offset;
3333 :
3334 145674 : while( hs_data ) {
3335 : /* skip data we've sent */
3336 121392 : if( hs_data->offset + hs_data->data_sz <= offset ) {
3337 60696 : hs_data = fd_quic_tls_get_next_hs_data( conn->tls_hs, hs_data );
3338 60696 : continue;
3339 60696 : }
3340 :
3341 60696 : if( FD_UNLIKELY( hs_data->offset > offset ) ) {
3342 : /* we have a gap - this shouldn't happen */
3343 0 : FD_LOG_WARNING(( "%s - gap in TLS handshake data", __func__ ));
3344 : /* TODO should probably tear down connection */
3345 0 : break;
3346 0 : }
3347 :
3348 : /* encode hs_data into frame */
3349 60696 : hs_offset = offset - hs_data->offset;
3350 :
3351 : /* handshake data to send */
3352 60696 : uchar const * cur_data = hs_data->data + hs_offset;
3353 60696 : ulong cur_data_sz = hs_data->data_sz - hs_offset;
3354 :
3355 : /* 9 bytes header + cur_data_sz */
3356 60696 : if( payload_ptr + 9UL + cur_data_sz > payload_end ) break;
3357 : /* FIXME reduce cur_data_sz if it doesn't fit in frame
3358 : Practically don't need to, because fd_tls generates a small amount of data */
3359 :
3360 60696 : payload_ptr[0] = 0x06; /* CRYPTO frame */
3361 60696 : uint offset_varint = 0x80U | ( fd_uint_bswap( (uint)offset & 0x3fffffffU ) );
3362 60696 : uint length_varint = 0x80U | ( fd_uint_bswap( (uint)cur_data_sz & 0x3fffffffU ) );
3363 60696 : FD_STORE( uint, payload_ptr+1, offset_varint );
3364 60696 : FD_STORE( uint, payload_ptr+5, length_varint );
3365 60696 : payload_ptr += 9;
3366 :
3367 60696 : fd_memcpy( payload_ptr, cur_data, cur_data_sz );
3368 60696 : payload_ptr += cur_data_sz;
3369 :
3370 : /* update pkt_meta values */
3371 60696 : offset_hi += cur_data_sz;
3372 :
3373 : /* move to next hs_data */
3374 60696 : offset += cur_data_sz;
3375 60696 : conn->hs_sent_bytes[enc_level] += cur_data_sz;
3376 :
3377 : /* TODO load more hs_data into a crypto frame, if available
3378 : currently tricky, because encode_crypto_frame copies payload */
3379 60696 : }
3380 :
3381 : /* update packet meta */
3382 24282 : if( offset_hi > offset_lo ) {
3383 24282 : fd_quic_gen_frame_store_pkt_meta( pkt_meta_tmpl,
3384 24282 : FD_QUIC_PKT_META_TYPE_HS_DATA,
3385 24282 : (fd_quic_pkt_meta_value_t){
3386 24282 : .range = {
3387 24282 : .offset_lo = offset_lo,
3388 24282 : .offset_hi = offset_hi
3389 24282 : }
3390 24282 : },
3391 24282 : tracker,
3392 24282 : conn );
3393 24282 : }
3394 :
3395 24282 : return payload_ptr;
3396 24282 : }
3397 :
3398 : static ulong
3399 : fd_quic_gen_handshake_done_frame( fd_quic_conn_t * conn,
3400 : uchar * payload_ptr,
3401 : uchar * payload_end,
3402 : const fd_quic_pkt_meta_t * pkt_meta_tmpl,
3403 7064016 : fd_quic_pkt_meta_tracker_t * tracker ) {
3404 7064016 : FD_DTRACE_PROBE_1( quic_gen_handshake_done_frame, conn->our_conn_id );
3405 7064016 : if( conn->handshake_done_send==0 ) return 0UL;
3406 6069 : conn->handshake_done_send = 0;
3407 6069 : if( FD_UNLIKELY( conn->handshake_done_ackd ) ) return 0UL;
3408 6069 : if( FD_UNLIKELY( payload_ptr >= payload_end ) ) return 0UL;
3409 : /* send handshake done frame */
3410 6069 : payload_ptr[0] = 0x1E;
3411 :
3412 : /* record the send for retx */
3413 6069 : if( !fd_quic_gen_frame_store_pkt_meta( pkt_meta_tmpl,
3414 6069 : FD_QUIC_PKT_META_TYPE_HS_DONE,
3415 6069 : (fd_quic_pkt_meta_value_t){0}, /* value doesn't matter */
3416 6069 : tracker,
3417 6069 : conn) ) return 0UL;
3418 :
3419 6069 : return 1UL;
3420 6069 : }
3421 :
3422 : static ulong
3423 : fd_quic_gen_max_data_frame( fd_quic_conn_t * conn,
3424 : uchar * payload_ptr,
3425 : uchar * payload_end,
3426 : const fd_quic_pkt_meta_t * pkt_meta_tmpl,
3427 6917611 : fd_quic_pkt_meta_tracker_t * tracker ) {
3428 6917611 : fd_quic_conn_stream_rx_t * srx = conn->srx;
3429 :
3430 6917611 : if( !( conn->flags & FD_QUIC_CONN_FLAGS_MAX_DATA ) ) return 0UL;
3431 0 : if( srx->rx_max_data <= srx->rx_max_data_ackd ) return 0UL; /* peer would ignore anyway */
3432 :
3433 : /* send max_data frame */
3434 0 : fd_quic_max_data_frame_t frame = { .max_data = srx->rx_max_data };
3435 :
3436 : /* attempt to write into buffer */
3437 0 : ulong frame_sz = fd_quic_encode_max_data_frame( payload_ptr,
3438 0 : (ulong)( payload_end - payload_ptr ),
3439 0 : &frame );
3440 0 : if( FD_UNLIKELY( frame_sz==FD_QUIC_ENCODE_FAIL ) ) return 0UL;
3441 :
3442 : /* acquire and set a pkt_meta, return 0 if not successful */
3443 0 : if( !fd_quic_gen_frame_store_pkt_meta( pkt_meta_tmpl,
3444 0 : FD_QUIC_PKT_META_TYPE_MAX_DATA,
3445 0 : (fd_quic_pkt_meta_value_t){
3446 0 : .scalar = srx->rx_max_data
3447 0 : },
3448 0 : tracker,
3449 0 : conn ) ) return 0UL;
3450 :
3451 0 : conn->upd_pkt_number = pkt_meta_tmpl->key.pkt_num;
3452 0 : return frame_sz;
3453 0 : }
3454 :
3455 : static ulong
3456 : fd_quic_gen_max_streams_frame( fd_quic_conn_t * conn,
3457 : uchar * payload_ptr,
3458 : uchar * payload_end,
3459 : const fd_quic_pkt_meta_t * pkt_meta_tmpl,
3460 6917611 : fd_quic_pkt_meta_tracker_t * tracker ) {
3461 6917611 : fd_quic_conn_stream_rx_t * srx = conn->srx;
3462 :
3463 : /* 0x02 Client-Initiated, Unidirectional
3464 : 0x03 Server-Initiated, Unidirectional */
3465 6917611 : ulong max_streams_unidir = srx->rx_sup_stream_id >> 2;
3466 :
3467 6917611 : uint flags = conn->flags;
3468 6917611 : if( !FD_QUIC_MAX_STREAMS_ALWAYS_UNLESS_ACKED ) {
3469 6917611 : if( !( flags & FD_QUIC_CONN_FLAGS_MAX_STREAMS_UNIDIR ) ) return 0UL;
3470 0 : if( max_streams_unidir <= srx->rx_max_streams_unidir_ackd ) return 0UL;
3471 0 : }
3472 :
3473 0 : fd_quic_max_streams_frame_t max_streams = {
3474 0 : .type = 0x13, /* unidirectional */
3475 0 : .max_streams = max_streams_unidir
3476 0 : };
3477 0 : ulong frame_sz = fd_quic_encode_max_streams_frame( payload_ptr,
3478 0 : (ulong)( payload_end - payload_ptr ),
3479 0 : &max_streams );
3480 0 : if( FD_UNLIKELY( frame_sz==FD_QUIC_ENCODE_FAIL ) ) return 0UL;
3481 :
3482 0 : if( !fd_quic_gen_frame_store_pkt_meta( pkt_meta_tmpl,
3483 0 : FD_QUIC_PKT_META_TYPE_MAX_STREAMS_UNIDIR,
3484 0 : (fd_quic_pkt_meta_value_t){0}, /* value doesn't matter */
3485 0 : tracker,
3486 0 : conn ) ) return 0UL;
3487 :
3488 0 : conn->flags = flags & (~FD_QUIC_CONN_FLAGS_MAX_STREAMS_UNIDIR);
3489 0 : conn->upd_pkt_number = pkt_meta_tmpl->key.pkt_num;
3490 0 : return frame_sz;
3491 0 : }
3492 :
3493 : static ulong
3494 : fd_quic_gen_ping_frame( fd_quic_conn_t * conn,
3495 : uchar * payload_ptr,
3496 : uchar * payload_end,
3497 : const fd_quic_pkt_meta_t * pkt_meta_tmpl,
3498 6917611 : fd_quic_pkt_meta_tracker_t * tracker ) {
3499 :
3500 6917611 : if( ~conn->flags & FD_QUIC_CONN_FLAGS_PING ) return 0UL;
3501 6165 : if( conn->flags & FD_QUIC_CONN_FLAGS_PING_SENT ) return 0UL;
3502 :
3503 6165 : fd_quic_ping_frame_t ping = {0};
3504 6165 : ulong frame_sz = fd_quic_encode_ping_frame( payload_ptr,
3505 6165 : (ulong)( payload_end - payload_ptr ),
3506 6165 : &ping );
3507 6165 : if( FD_UNLIKELY( frame_sz==FD_QUIC_ENCODE_FAIL ) ) return 0UL;
3508 6165 : conn->flags |= FD_QUIC_CONN_FLAGS_PING_SENT;
3509 6165 : conn->flags &= ~FD_QUIC_CONN_FLAGS_PING;
3510 :
3511 6165 : conn->upd_pkt_number = pkt_meta_tmpl->key.pkt_num;
3512 : /* record the send for retx, 0 if fail */
3513 6165 : if( !fd_quic_gen_frame_store_pkt_meta( pkt_meta_tmpl,
3514 6165 : FD_QUIC_PKT_META_TYPE_PING,
3515 6165 : (fd_quic_pkt_meta_value_t){0}, /* value doesn't matter */
3516 6165 : tracker,
3517 6165 : conn ) ) return 0UL;
3518 :
3519 6120 : return frame_sz;
3520 6165 : }
3521 :
3522 : uchar *
3523 : fd_quic_gen_stream_frames( fd_quic_conn_t * conn,
3524 : uchar * payload_ptr,
3525 : uchar * payload_end,
3526 : fd_quic_pkt_meta_t * pkt_meta_tmpl,
3527 7051944 : fd_quic_pkt_meta_tracker_t * tracker ) {
3528 :
3529 : /* loop serves two purposes:
3530 : 1. finds a stream with data to send
3531 : 2. appends max_stream_data frames as necessary */
3532 7051944 : fd_quic_stream_t * sentinel = conn->send_streams;
3533 7051944 : fd_quic_stream_t * cur_stream = sentinel->next;
3534 7051944 : ulong pkt_num = pkt_meta_tmpl->key.pkt_num;
3535 13987408 : while( !cur_stream->sentinel ) {
3536 : /* required, since cur_stream may get removed from list */
3537 6935467 : fd_quic_stream_t * nxt_stream = cur_stream->next;
3538 6935467 : _Bool sent_all_data = 1u;
3539 :
3540 6935467 : if( cur_stream->upd_pkt_number >= pkt_num ) {
3541 :
3542 : /* any stream data? */
3543 6935467 : if( FD_LIKELY( FD_QUIC_STREAM_ACTION( cur_stream ) ) ) {
3544 :
3545 : /* data_avail is the number of stream bytes available for sending.
3546 : fin_flag_set is 1 if no more bytes will get added to the stream. */
3547 6935464 : ulong const data_avail = cur_stream->tx_buf.head - cur_stream->tx_sent;
3548 6935464 : int const fin_flag_set = !!(cur_stream->state & FD_QUIC_STREAM_STATE_TX_FIN);
3549 6935464 : ulong const stream_id = cur_stream->stream_id;
3550 6935464 : ulong const stream_off = cur_stream->tx_sent;
3551 :
3552 : /* No information to send? */
3553 6935464 : if( data_avail==0u && !fin_flag_set ) break;
3554 :
3555 : /* No space to write frame?
3556 : (Buffer should fit max stream header size and at least 1 byte of data) */
3557 6935464 : if( payload_ptr+FD_QUIC_MAX_FOOTPRINT( stream_e_frame )+1 > payload_end ) break;
3558 :
3559 : /* check pkt_meta availability */
3560 6935464 : if( !fd_quic_conn_can_acquire_pkt_meta( conn, tracker ) ) break;
3561 :
3562 : /* Leave placeholder for frame/stream type */
3563 6935461 : uchar * const frame_type_p = payload_ptr++;
3564 6935461 : uint frame_type = 0x0a; /* stream frame with length */
3565 :
3566 : /* Encode stream ID */
3567 6935461 : payload_ptr += fd_quic_varint_encode( payload_ptr, stream_id );
3568 :
3569 : /* Optionally encode offset */
3570 6935461 : if( stream_off>0 ) {
3571 16899 : frame_type |= 0x04; /* with offset field */
3572 16899 : payload_ptr += fd_quic_varint_encode( payload_ptr, stream_off );
3573 16899 : }
3574 :
3575 : /* Leave placeholder for length length */
3576 6935461 : uchar * data_sz_p = payload_ptr;
3577 6935461 : payload_ptr += 2;
3578 :
3579 : /* Stream metadata */
3580 6935461 : ulong data_max = (ulong)payload_end - (ulong)payload_ptr; /* assume no underflow */
3581 6935461 : ulong data_sz = fd_ulong_min( data_avail, data_max );
3582 6935461 : /* */ data_sz = fd_ulong_min( data_sz, 0x3fffUL ); /* max 2 byte varint */
3583 6935461 : /* */ sent_all_data = data_sz == data_avail;
3584 6935461 : _Bool fin = fin_flag_set && sent_all_data;
3585 :
3586 : /* Finish encoding stream header */
3587 6935461 : ushort data_sz_varint = fd_ushort_bswap( (ushort)( 0x4000u | (uint)data_sz ) );
3588 6935461 : FD_STORE( ushort, data_sz_p, data_sz_varint );
3589 6935461 : frame_type |= fin;
3590 6935461 : *frame_type_p = (uchar)frame_type;
3591 :
3592 : /* Write stream payload */
3593 6935461 : fd_quic_buffer_t * tx_buf = &cur_stream->tx_buf;
3594 6935461 : fd_quic_buffer_load( tx_buf, stream_off, payload_ptr, data_sz );
3595 6935461 : payload_ptr += data_sz;
3596 :
3597 : /* Update stream metadata */
3598 6935461 : cur_stream->tx_sent += data_sz;
3599 6935461 : cur_stream->upd_pkt_number = fd_ulong_if( fin, pkt_num, FD_QUIC_PKT_NUM_PENDING );
3600 6935461 : cur_stream->stream_flags &= fd_uint_if( fin, ~FD_QUIC_STREAM_FLAGS_ACTION, UINT_MAX );
3601 :
3602 : /* Packet metadata for potential retransmits */
3603 6935461 : pkt_meta_tmpl->key.stream_id = cur_stream->stream_id;
3604 6935461 : fd_quic_gen_frame_store_pkt_meta( pkt_meta_tmpl,
3605 6935461 : FD_QUIC_PKT_META_TYPE_STREAM,
3606 6935461 : (fd_quic_pkt_meta_value_t){
3607 6935461 : .range = {
3608 6935461 : .offset_lo = stream_off,
3609 6935461 : .offset_hi = stream_off + data_sz
3610 6935461 : }
3611 6935461 : },
3612 6935461 : tracker,
3613 6935461 : conn );
3614 6935461 : }
3615 6935467 : }
3616 :
3617 6935464 : if( sent_all_data ) {
3618 6918649 : cur_stream->stream_flags &= ~FD_QUIC_STREAM_FLAGS_ACTION;
3619 6918649 : FD_QUIC_STREAM_LIST_REMOVE( cur_stream );
3620 6918649 : FD_QUIC_STREAM_LIST_INSERT_BEFORE( conn->used_streams, cur_stream );
3621 6918649 : }
3622 :
3623 6935464 : cur_stream = nxt_stream;
3624 6935464 : }
3625 :
3626 7051944 : return payload_ptr;
3627 7051944 : }
3628 :
3629 : uchar *
3630 : fd_quic_gen_frames( fd_quic_conn_t * conn,
3631 : uchar * payload_ptr,
3632 : uchar * payload_end,
3633 : fd_quic_pkt_meta_t * pkt_meta_tmpl,
3634 7106391 : long now ) {
3635 :
3636 7106391 : uint closing = 0U;
3637 7106391 : switch( conn->state ) {
3638 6003 : case FD_QUIC_CONN_STATE_PEER_CLOSE:
3639 6006 : case FD_QUIC_CONN_STATE_ABORT:
3640 12024 : case FD_QUIC_CONN_STATE_CLOSE_PENDING:
3641 12024 : closing = 1u;
3642 7106391 : }
3643 :
3644 7106391 : fd_quic_pkt_meta_tracker_t * tracker = &conn->pkt_meta_tracker;
3645 :
3646 7106391 : payload_ptr = fd_quic_gen_ack_frames( conn->ack_gen, payload_ptr, payload_end, pkt_meta_tmpl->enc_level, now );
3647 7106391 : if( conn->ack_gen->head == conn->ack_gen->tail ) conn->unacked_sz = 0UL;
3648 :
3649 7106391 : if( FD_UNLIKELY( closing ) ) {
3650 12024 : payload_ptr += fd_quic_gen_close_frame( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
3651 7094367 : } else {
3652 7094367 : payload_ptr = fd_quic_gen_handshake_frames( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
3653 7094367 : if( pkt_meta_tmpl->enc_level == fd_quic_enc_level_appdata_id ) {
3654 7064016 : payload_ptr += fd_quic_gen_handshake_done_frame( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
3655 7064016 : if( conn->upd_pkt_number >= pkt_meta_tmpl->key.pkt_num ) {
3656 6917611 : payload_ptr += fd_quic_gen_max_data_frame ( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
3657 6917611 : payload_ptr += fd_quic_gen_max_streams_frame( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
3658 6917611 : payload_ptr += fd_quic_gen_ping_frame ( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
3659 6917611 : }
3660 7064016 : if( FD_LIKELY( !conn->tls_hs ) ) {
3661 7051935 : payload_ptr = fd_quic_gen_stream_frames( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
3662 7051935 : }
3663 7064016 : }
3664 7094367 : }
3665 :
3666 7106391 : fd_quic_svc_prep_schedule( conn, pkt_meta_tmpl->expiry );
3667 :
3668 7106391 : return payload_ptr;
3669 7106391 : }
3670 :
3671 : /* transmit
3672 : looks at each of the following dependent on state, and creates
3673 : a packet to transmit:
3674 : acks
3675 : handshake data (tls)
3676 : handshake done
3677 : ping
3678 : stream data */
3679 : static void
3680 : fd_quic_conn_tx( fd_quic_t * quic,
3681 7071435 : fd_quic_conn_t * conn ) {
3682 :
3683 7071435 : if( FD_UNLIKELY( conn->state == FD_QUIC_CONN_STATE_DEAD ) ) return;
3684 :
3685 7071435 : fd_quic_state_t * state = fd_quic_get_state( quic );
3686 :
3687 : /* used for encoding frames into before encrypting */
3688 7071435 : uchar * crypt_scratch = state->crypt_scratch;
3689 7071435 : ulong crypt_scratch_sz = sizeof( state->crypt_scratch );
3690 :
3691 : /* max packet size */
3692 : /* TODO probably should be called tx_max_udp_payload_sz */
3693 7071435 : ulong tx_max_datagram_sz = conn->tx_max_datagram_sz;
3694 :
3695 7071435 : if( conn->tx_ptr != conn->tx_buf_conn ) {
3696 0 : fd_quic_tx_buffered( quic, conn );
3697 0 : fd_quic_svc_prep_schedule( conn, state->now );
3698 0 : return;
3699 0 : }
3700 :
3701 : /* choose enc_level to tx at */
3702 : /* this function accepts an argument "acks"
3703 : * We want to minimize the number of packets that carry only acks.
3704 : * fd_quic_tx_enc_level determines whether a packet needs sending,
3705 : * and when encryption level should be used.
3706 : * If "acks" is set to 1 (true), fd_quic_tx_enc_level checks for acks.
3707 : * Otherwise, it does not check for acks
3708 : * We set "acks" only on the first call in this function. All subsequent
3709 : * calls do not set it.
3710 : * This ensures that ack-only packets only occur when nothing else needs
3711 : * to be sent */
3712 7071435 : uint enc_level = fd_quic_tx_enc_level( conn, 1 /* acks */ );
3713 :
3714 : /* nothing to send / bad state? */
3715 7071435 : if( enc_level == ~0u ) return;
3716 :
3717 7071429 : int key_phase_upd = (int)conn->key_update;
3718 7071429 : uint key_phase = conn->key_phase;
3719 7071429 : int key_phase_tx = (int)key_phase ^ key_phase_upd;
3720 :
3721 : /* get time */
3722 7071429 : long now = state->now;
3723 :
3724 : /* initialize expiry and tx_time */
3725 7071429 : long expiry = now + fd_quic_calc_expiry_duration( conn, 0 /* use PTO */, conn->server );
3726 7071429 : fd_quic_pkt_meta_t pkt_meta_tmpl[1] = {{.expiry = expiry, .tx_time = now}};
3727 :
3728 14177730 : while( enc_level != ~0u ) {
3729 : /* RFC 9000 Section 17.2.2.1. Abandoning Initial Packets
3730 : > A client stops both sending and processing Initial packets when
3731 : > it sends its first Handshake packet.
3732 :
3733 : RFC 9001 Section 4.9.1 Discarding Initial Keys
3734 : > a client MUST discard Initial keys when it first sends a Handshake packet */
3735 7106391 : if( FD_UNLIKELY( (quic->config.role==FD_QUIC_ROLE_CLIENT) & (enc_level==fd_quic_enc_level_handshake_id) ) ) {
3736 6069 : fd_quic_abandon_enc_level( conn, fd_quic_enc_level_initial_id );
3737 6069 : }
3738 :
3739 7106391 : uint initial_pkt = 0; /* is this the first initial packet? */
3740 :
3741 : /* remaining in datagram */
3742 : /* invariant: tx_ptr >= tx_buf */
3743 7106391 : ulong datagram_rem = tx_max_datagram_sz - (ulong)( conn->tx_ptr - conn->tx_buf_conn );
3744 :
3745 : /* encode into here */
3746 : /* this is the start of a new quic packet
3747 : cur_ptr points at the next byte to fill with a quic pkt */
3748 : /* currently, cur_ptr just points at the start of crypt_scratch
3749 : each quic packet gets encrypted into tx_buf, and the space in
3750 : crypt_scratch is reused */
3751 7106391 : uchar * cur_ptr = crypt_scratch;
3752 7106391 : ulong cur_sz = crypt_scratch_sz;
3753 :
3754 : /* TODO determine actual datagrams size to use */
3755 7106391 : cur_sz = fd_ulong_min( cur_sz, datagram_rem );
3756 :
3757 : /* determine pn_space */
3758 7106391 : uint pn_space = fd_quic_enc_level_to_pn_space( enc_level );
3759 7106391 : pkt_meta_tmpl->pn_space = (uchar)pn_space;
3760 7106391 : pkt_meta_tmpl->enc_level = (uchar)(enc_level&0x3);
3761 :
3762 : /* get next packet number
3763 : Returned to pool if not sent as gaps are harmful for ACK frame
3764 : compression. */
3765 7106391 : ulong pkt_number = conn->pkt_number[pn_space];
3766 7106391 : FD_QUIC_PKT_META_SET_PKT_NUM( pkt_meta_tmpl, pkt_number );
3767 :
3768 : /* are we the client initial packet? */
3769 7106391 : ulong hs_data_offset = conn->hs_sent_bytes[enc_level];
3770 7106391 : initial_pkt = (uint)( hs_data_offset == 0 ) & (uint)( !conn->server ) & (uint)( enc_level == fd_quic_enc_level_initial_id );
3771 :
3772 : /* current peer endpoint */
3773 7106391 : fd_quic_conn_id_t const * peer_conn_id = &conn->peer_cids[0];
3774 :
3775 : /* our current conn_id */
3776 7106391 : ulong conn_id = conn->our_conn_id;
3777 7106391 : uint const pkt_num_len = 4u; /* 4-byte packet number */
3778 7106391 : uint const pkt_num_len_enc = pkt_num_len - 1; /* -1 offset for protocol */
3779 :
3780 :
3781 : /* encode packet header (including packet number)
3782 : While encoding, remember where the 'length' field is, if one
3783 : exists. We'll have to update it later. */
3784 7106391 : uchar * hdr_ptr = cur_ptr;
3785 7106391 : ulong hdr_sz = 0UL;
3786 7106391 : uchar _hdr_len_field[2]; /* if no len field exists, catch the write here */
3787 7106391 : uchar * hdr_len_field = _hdr_len_field;
3788 7106391 : switch( enc_level ) {
3789 18216 : case fd_quic_enc_level_initial_id: {
3790 18216 : fd_quic_initial_t initial = {0};
3791 18216 : initial.h0 = fd_quic_initial_h0( pkt_num_len_enc );
3792 18216 : initial.version = 1;
3793 18216 : initial.dst_conn_id_len = peer_conn_id->sz;
3794 : // .dst_conn_id
3795 18216 : initial.src_conn_id_len = FD_QUIC_CONN_ID_SZ;
3796 : // .src_conn_id
3797 : // .token - below
3798 18216 : initial.len = 0x3fff; /* use 2 byte varint encoding */
3799 18216 : initial.pkt_num = pkt_number;
3800 :
3801 18216 : fd_memcpy( initial.dst_conn_id, peer_conn_id->conn_id, peer_conn_id->sz );
3802 18216 : memcpy( initial.src_conn_id, &conn_id, FD_QUIC_CONN_ID_SZ );
3803 :
3804 : /* Initial packets sent by the server MUST set the Token Length field to 0. */
3805 18216 : initial.token = conn->token;
3806 18216 : if( conn->quic->config.role == FD_QUIC_ROLE_CLIENT && conn->token_len ) {
3807 15 : initial.token_len = conn->token_len;
3808 18201 : } else {
3809 18201 : initial.token_len = 0;
3810 18201 : }
3811 :
3812 18216 : hdr_sz = fd_quic_encode_initial( cur_ptr, cur_sz, &initial );
3813 18216 : hdr_len_field = cur_ptr + hdr_sz - 6; /* 2 byte len, 4 byte packet number */
3814 18216 : FD_DTRACE_PROBE_2( quic_encode_initial, initial.src_conn_id, initial.dst_conn_id );
3815 18216 : break;
3816 0 : }
3817 :
3818 12138 : case fd_quic_enc_level_handshake_id: {
3819 12138 : fd_quic_handshake_t handshake = {0};
3820 12138 : handshake.h0 = fd_quic_handshake_h0( pkt_num_len_enc );
3821 12138 : handshake.version = 1;
3822 :
3823 : /* destination */
3824 12138 : fd_memcpy( handshake.dst_conn_id, peer_conn_id->conn_id, peer_conn_id->sz );
3825 12138 : handshake.dst_conn_id_len = peer_conn_id->sz;
3826 :
3827 : /* source */
3828 12138 : FD_STORE( ulong, handshake.src_conn_id, conn_id );
3829 12138 : handshake.src_conn_id_len = sizeof(ulong);
3830 :
3831 12138 : handshake.len = 0x3fff; /* use 2 byte varint encoding */
3832 12138 : handshake.pkt_num = pkt_number;
3833 :
3834 12138 : hdr_sz = fd_quic_encode_handshake( cur_ptr, cur_sz, &handshake );
3835 12138 : hdr_len_field = cur_ptr + hdr_sz - 6; /* 2 byte len, 4 byte packet number */
3836 12138 : FD_DTRACE_PROBE_2( quic_encode_handshake, handshake.src_conn_id, handshake.dst_conn_id );
3837 12138 : break;
3838 0 : }
3839 :
3840 7076037 : case fd_quic_enc_level_appdata_id:
3841 7076037 : {
3842 7076037 : fd_quic_one_rtt_t one_rtt = {0};
3843 7076037 : one_rtt.h0 = fd_quic_one_rtt_h0( /* spin */ 0, !!key_phase_tx, pkt_num_len_enc );
3844 :
3845 : /* destination */
3846 7076037 : fd_memcpy( one_rtt.dst_conn_id, peer_conn_id->conn_id, peer_conn_id->sz );
3847 7076037 : one_rtt.dst_conn_id_len = peer_conn_id->sz;
3848 :
3849 7076037 : one_rtt.pkt_num = pkt_number;
3850 :
3851 7076037 : hdr_sz = fd_quic_encode_one_rtt( cur_ptr, cur_sz, &one_rtt );
3852 7076037 : FD_DTRACE_PROBE_2( quic_encode_one_rtt, one_rtt.dst_conn_id, one_rtt.pkt_num );
3853 7076037 : break;
3854 0 : }
3855 :
3856 0 : default:
3857 0 : FD_LOG_ERR(( "%s - logic error: unexpected enc_level", __func__ ));
3858 7106391 : }
3859 :
3860 : /* if we don't have reasonable amt of space for a new packet, tx to free space */
3861 7106391 : const ulong min_rqd = 64;
3862 7106391 : if( FD_UNLIKELY( hdr_sz==FD_QUIC_ENCODE_FAIL || hdr_sz + min_rqd > cur_sz ) ) {
3863 : /* try to free space */
3864 0 : fd_quic_tx_buffered( quic, conn );
3865 :
3866 : /* we have lots of space, so try again */
3867 0 : if( conn->tx_buf_conn == conn->tx_ptr ) {
3868 0 : enc_level = fd_quic_tx_enc_level( conn, 0 /* acks */ );
3869 0 : continue;
3870 0 : }
3871 :
3872 : /* reschedule, since some data was unable to be sent */
3873 : /* TODO might want to add a backoff here */
3874 0 : fd_quic_svc_prep_schedule( conn, now );
3875 :
3876 0 : break;
3877 0 : }
3878 :
3879 7106391 : cur_ptr += hdr_sz;
3880 7106391 : cur_sz -= hdr_sz;
3881 :
3882 : /* start writing payload, leaving room for header and expansion
3883 : due to varint coding */
3884 :
3885 7106391 : uchar * payload_ptr = cur_ptr;
3886 7106391 : ulong payload_sz = cur_sz;
3887 : /* payload_end leaves room for TAG */
3888 7106391 : uchar * payload_end = payload_ptr + payload_sz - FD_QUIC_CRYPTO_TAG_SZ;
3889 :
3890 7106391 : uchar * const frame_start = payload_ptr;
3891 7106391 : payload_ptr = fd_quic_gen_frames( conn, frame_start, payload_end, pkt_meta_tmpl, now );
3892 7106391 : if( FD_UNLIKELY( payload_ptr < frame_start ) ) FD_LOG_CRIT(( "fd_quic_gen_frames failed" ));
3893 :
3894 : /* did we add any frames? */
3895 :
3896 7106391 : if( payload_ptr==frame_start ) {
3897 : /* we have data to add, but none was added, presumably due
3898 : so space in the datagram */
3899 90 : ulong free_bytes = (ulong)( payload_end - payload_ptr );
3900 : /* sanity check */
3901 90 : if( free_bytes > 64 ) {
3902 : /* we should have been able to fit data into 64 bytes
3903 : so stop trying here */
3904 90 : break;
3905 90 : }
3906 :
3907 : /* try to free space */
3908 0 : fd_quic_tx_buffered( quic, conn );
3909 :
3910 : /* we have lots of space, so try again */
3911 0 : if( conn->tx_buf_conn == conn->tx_ptr ) {
3912 0 : enc_level = fd_quic_tx_enc_level( conn, 0 /* acks */ );
3913 0 : continue;
3914 0 : }
3915 0 : }
3916 :
3917 : /* first initial frame is padded to FD_QUIC_INITIAL_PAYLOAD_SZ_MIN
3918 : all short quic packets are padded so 16 bytes of sample are available */
3919 7106301 : uint tot_frame_sz = (uint)( payload_ptr - frame_start );
3920 7106301 : uint base_pkt_len = (uint)tot_frame_sz + pkt_num_len + FD_QUIC_CRYPTO_TAG_SZ;
3921 7106301 : uint padding = ( initial_pkt && (base_pkt_len < FD_QUIC_INITIAL_PAYLOAD_SZ_MIN) )
3922 7106301 : ? FD_QUIC_INITIAL_PAYLOAD_SZ_MIN - base_pkt_len : 0u;
3923 :
3924 7106301 : if( base_pkt_len + padding < FD_QUIC_CRYPTO_SAMPLE_OFFSET_FROM_PKT_NUM_START + FD_QUIC_CRYPTO_SAMPLE_SZ ) {
3925 0 : padding = FD_QUIC_CRYPTO_SAMPLE_SZ + FD_QUIC_CRYPTO_SAMPLE_OFFSET_FROM_PKT_NUM_START - base_pkt_len;
3926 0 : }
3927 :
3928 : /* this length includes the packet number length (pkt_number_len_enc+1),
3929 : padding and the final TAG */
3930 7106301 : uint quic_pkt_len = base_pkt_len + padding;
3931 :
3932 : /* set the length on the packet header */
3933 7106301 : uint quic_pkt_len_varint = 0x4000u | fd_uint_min( quic_pkt_len, 0x3fff );
3934 7106301 : FD_STORE( ushort, hdr_len_field, fd_ushort_bswap( (ushort)quic_pkt_len_varint ) );
3935 :
3936 : /* add padding */
3937 7106301 : if( padding ) {
3938 6075 : fd_memset( payload_ptr, 0, padding );
3939 6075 : payload_ptr += padding;
3940 6075 : }
3941 :
3942 : /* everything successful up to here
3943 : encrypt into tx_ptr,tx_ptr+tx_sz */
3944 :
3945 : #if FD_QUIC_DISABLE_CRYPTO
3946 : ulong quic_pkt_sz = hdr_sz + tot_frame_sz + padding;
3947 : fd_memcpy( conn->tx_ptr, hdr_ptr, quic_pkt_sz );
3948 : conn->tx_ptr += quic_pkt_sz;
3949 :
3950 : /* append MAC tag */
3951 : memset( conn->tx_ptr, 0, FD_QUIC_CRYPTO_TAG_SZ );
3952 : conn->tx_ptr += FD_QUIC_CRYPTO_TAG_SZ;
3953 : #else
3954 7106301 : ulong cipher_text_sz = fd_quic_conn_tx_buf_remaining( conn );
3955 7106301 : ulong frames_sz = (ulong)( payload_ptr - frame_start ); /* including padding */
3956 :
3957 7106301 : fd_quic_crypto_keys_t * hp_keys = &conn->keys[enc_level][1];
3958 7106301 : fd_quic_crypto_keys_t * pkt_keys = key_phase_upd ? &conn->new_keys[1] : &conn->keys[enc_level][1];
3959 :
3960 7106301 : if( FD_UNLIKELY( fd_quic_crypto_encrypt( conn->tx_ptr, &cipher_text_sz, hdr_ptr, hdr_sz,
3961 7106301 : frame_start, frames_sz, pkt_keys, hp_keys, pkt_number ) != FD_QUIC_SUCCESS ) ) {
3962 0 : FD_LOG_WARNING(( "fd_quic_crypto_encrypt failed" ));
3963 :
3964 : /* this situation is unlikely to improve, so kill the connection */
3965 0 : fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_DEAD );
3966 0 : fd_quic_svc_prep_schedule_now( conn );
3967 0 : quic->metrics.conn_aborted_cnt++;
3968 0 : break;
3969 0 : }
3970 :
3971 7106301 : conn->tx_ptr += cipher_text_sz;
3972 7106301 : #endif
3973 :
3974 : /* we have committed the packet into the buffer, so inc pkt_number */
3975 7106301 : conn->pkt_number[pn_space]++;
3976 :
3977 7106301 : if( enc_level == fd_quic_enc_level_appdata_id ) {
3978 : /* short header must be last in datagram
3979 : so send in packet immediately */
3980 7075947 : fd_quic_tx_buffered( quic, conn );
3981 :
3982 7075947 : if( conn->tx_ptr == conn->tx_buf_conn ) {
3983 7075947 : enc_level = fd_quic_tx_enc_level( conn, 0 /* acks */ );
3984 7075947 : continue;
3985 7075947 : }
3986 :
3987 : /* TODO count here */
3988 :
3989 : /* drop packet */
3990 : /* this is a workaround for leaving a short=header-packet in the buffer
3991 : for the next tx_conn call. Next time around the tx_conn call will
3992 : not be aware that the buffer cannot be added to */
3993 0 : conn->tx_ptr = conn->tx_buf_conn;
3994 :
3995 0 : break;
3996 7075947 : }
3997 :
3998 : /* Refresh enc_level in case we can coalesce another packet */
3999 30354 : enc_level = fd_quic_tx_enc_level( conn, 0 /* acks */ );
4000 30354 : FD_DEBUG( if( enc_level!=~0u) FD_LOG_DEBUG(( "Attempting to append enc_level=%u packet", enc_level )); )
4001 30354 : }
4002 :
4003 : /* try to send? */
4004 7071429 : fd_quic_tx_buffered( quic, conn );
4005 7071429 : }
4006 :
4007 : void
4008 7071435 : fd_quic_conn_service( fd_quic_t * quic, fd_quic_conn_t * conn, long now ) {
4009 :
4010 : /* Send new rtt measurement probe? */
4011 7071435 : if( FD_UNLIKELY( now > conn->last_ack + (long)conn->rtt_period_ns ) ) {
4012 : /* send PING */
4013 12012 : if( !( conn->flags & ( FD_QUIC_CONN_FLAGS_PING | FD_QUIC_CONN_FLAGS_PING_SENT ) ) ) {
4014 12012 : conn->flags |= FD_QUIC_CONN_FLAGS_PING;
4015 12012 : conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING; /* update to be sent in next packet */
4016 12012 : }
4017 12012 : }
4018 :
4019 : /* handle expiry on pkt_meta */
4020 7071435 : fd_quic_pkt_meta_retry( quic, conn, 0 /* don't force */, ~0u /* all enc_levels */ );
4021 :
4022 : /* check state
4023 : need reset?
4024 : need close?
4025 : need acks?
4026 : replies?
4027 : data to send?
4028 : dead */
4029 7071435 : switch( conn->state ) {
4030 12144 : case FD_QUIC_CONN_STATE_HANDSHAKE:
4031 24282 : case FD_QUIC_CONN_STATE_HANDSHAKE_COMPLETE:
4032 24282 : {
4033 24282 : if( conn->tls_hs ) {
4034 : /* if we're the server, we send "handshake-done" frame */
4035 24282 : if( conn->state == FD_QUIC_CONN_STATE_HANDSHAKE_COMPLETE && conn->server ) {
4036 6069 : conn->handshake_done_send = 1;
4037 :
4038 : /* move straight to ACTIVE */
4039 6069 : fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_ACTIVE );
4040 :
4041 : /* RFC 9001 4.9.2. Discarding Handshake Keys
4042 : > An endpoint MUST discard its Handshake keys when the
4043 : > TLS handshake is confirmed
4044 : RFC 9001 4.1.2. Handshake Confirmed
4045 : > [...] the TLS handshake is considered confirmed at the
4046 : > server when the handshake completes */
4047 6069 : fd_quic_abandon_enc_level( conn, fd_quic_enc_level_handshake_id );
4048 :
4049 : /* user callback */
4050 6069 : fd_quic_cb_conn_new( quic, conn );
4051 :
4052 : /* clear out hs_data here, as we don't need it anymore */
4053 6069 : fd_quic_tls_clear_hs_data( conn->tls_hs, fd_quic_enc_level_appdata_id );
4054 6069 : }
4055 :
4056 : /* if we're the client, fd_quic_conn_tx will flush the hs
4057 : buffer so we can receive the HANDSHAKE_DONE frame, and
4058 : transition from CONN_STATE HANDSHAKE_COMPLETE to ACTIVE. */
4059 24282 : }
4060 :
4061 : /* do we have data to transmit? */
4062 24282 : fd_quic_conn_tx( quic, conn );
4063 :
4064 24282 : break;
4065 12144 : }
4066 :
4067 6018 : case FD_QUIC_CONN_STATE_CLOSE_PENDING:
4068 12021 : case FD_QUIC_CONN_STATE_PEER_CLOSE:
4069 : /* user requested close, and may have set a reason code */
4070 : /* transmit the failure reason */
4071 12021 : fd_quic_conn_tx( quic, conn );
4072 :
4073 : /* schedule another fd_quic_conn_service to free the conn */
4074 12021 : fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_DEAD ); /* TODO need draining state wait for 3 * TPO */
4075 12021 : quic->metrics.conn_closed_cnt++;
4076 :
4077 12021 : break;
4078 :
4079 3 : case FD_QUIC_CONN_STATE_ABORT:
4080 : /* transmit the failure reason */
4081 3 : fd_quic_conn_tx( quic, conn );
4082 :
4083 : /* schedule another fd_quic_conn_service to free the conn */
4084 3 : fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_DEAD );
4085 3 : quic->metrics.conn_aborted_cnt++;
4086 :
4087 3 : break;
4088 :
4089 7035129 : case FD_QUIC_CONN_STATE_ACTIVE:
4090 : /* do we have data to transmit? */
4091 7035129 : fd_quic_conn_tx( quic, conn );
4092 :
4093 7035129 : break;
4094 :
4095 0 : case FD_QUIC_CONN_STATE_DEAD:
4096 0 : case FD_QUIC_CONN_STATE_INVALID:
4097 : /* fall thru */
4098 0 : default:
4099 0 : FD_LOG_CRIT(( "invalid conn state %u", conn->state ));
4100 0 : return;
4101 7071435 : }
4102 :
4103 : /* check routing and arp for this connection */
4104 :
4105 7071435 : }
4106 :
4107 : void
4108 : fd_quic_conn_free( fd_quic_t * quic,
4109 12174 : fd_quic_conn_t * conn ) {
4110 12174 : if( FD_UNLIKELY( !conn ) ) {
4111 0 : FD_LOG_WARNING(( "NULL conn" ));
4112 0 : return;
4113 0 : }
4114 12174 : if( FD_UNLIKELY( conn->state == FD_QUIC_CONN_STATE_INVALID ) ) {
4115 0 : FD_LOG_CRIT(( "double free detected" ));
4116 0 : return;
4117 0 : }
4118 :
4119 12174 : FD_COMPILER_MFENCE();
4120 12174 : fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_INVALID );
4121 12174 : FD_COMPILER_MFENCE();
4122 :
4123 12174 : fd_quic_state_t * state = fd_quic_get_state( quic );
4124 :
4125 : /* remove connection id from conn_map */
4126 :
4127 12174 : fd_quic_conn_map_t * entry = fd_quic_conn_map_query( state->conn_map, conn->our_conn_id, NULL );
4128 12174 : if( FD_LIKELY( entry ) ) fd_quic_conn_map_remove( state->conn_map, entry );
4129 :
4130 : /* no need to remove this connection from the events queue
4131 : free is called from two places:
4132 : fini - service will never be called again. All events are destroyed
4133 : service - removes event before calling free. Event only allowed to be
4134 : enqueued once */
4135 :
4136 : /* free pkt_meta */
4137 60870 : for( uint j=0; j<=fd_quic_enc_level_appdata_id; ++j ) fd_quic_conn_free_pkt_meta( conn, j );
4138 :
4139 : /* remove all stream ids from map, and free stream */
4140 :
4141 : /* remove used streams */
4142 12174 : fd_quic_stream_t * used_sentinel = conn->used_streams;
4143 18306 : while( 1 ) {
4144 18306 : fd_quic_stream_t * stream = used_sentinel->next;
4145 :
4146 18306 : if( FD_UNLIKELY( stream == used_sentinel ) ) break;
4147 :
4148 6132 : fd_quic_tx_stream_free( quic, conn, stream, FD_QUIC_STREAM_NOTIFY_CONN );
4149 6132 : }
4150 :
4151 : /* remove send streams */
4152 12174 : fd_quic_stream_t * send_sentinel = conn->send_streams;
4153 18180 : while( 1 ) {
4154 18180 : fd_quic_stream_t * stream = send_sentinel->next;
4155 :
4156 18180 : if( FD_UNLIKELY( stream == send_sentinel ) ) break;
4157 :
4158 6006 : fd_quic_tx_stream_free( quic, conn, stream, FD_QUIC_STREAM_NOTIFY_CONN );
4159 6006 : }
4160 :
4161 : /* if any stream map entries are left over, remove them
4162 : this should not occur, so this branch should not execute
4163 : but if a stream doesn't get cleaned up properly, this fixes
4164 : the stream map */
4165 12174 : if( FD_UNLIKELY( conn->stream_map && fd_quic_stream_map_key_cnt( conn->stream_map ) > 0 ) ) {
4166 0 : FD_LOG_WARNING(( "stream_map not empty. cnt: %lu",
4167 0 : (ulong)fd_quic_stream_map_key_cnt( conn->stream_map ) ));
4168 0 : while( fd_quic_stream_map_key_cnt( conn->stream_map ) > 0 ) {
4169 0 : int removed = 0;
4170 0 : for( ulong j = 0; j < fd_quic_stream_map_slot_cnt( conn->stream_map ); ++j ) {
4171 0 : if( conn->stream_map[j].stream_id != FD_QUIC_STREAM_ID_UNUSED ) {
4172 0 : fd_quic_stream_map_remove( conn->stream_map, &conn->stream_map[j] );
4173 0 : removed = 1;
4174 0 : j--; /* retry this entry */
4175 0 : }
4176 0 : }
4177 0 : if( !removed ) {
4178 0 : FD_LOG_WARNING(( "None removed. Remain: %lu",
4179 0 : (ulong)fd_quic_stream_map_key_cnt( conn->stream_map ) ));
4180 0 : break;
4181 0 : }
4182 0 : }
4183 0 : }
4184 :
4185 12174 : if( conn->tls_hs ) {
4186 : /* free tls-hs */
4187 42 : fd_quic_tls_hs_delete( conn->tls_hs );
4188 :
4189 : /* Remove the handshake from the cache before releasing it */
4190 42 : fd_quic_tls_hs_cache_ele_remove( &state->hs_cache, conn->tls_hs, state->hs_pool);
4191 42 : fd_quic_tls_hs_pool_ele_release( state->hs_pool, conn->tls_hs );
4192 42 : }
4193 12174 : conn->tls_hs = NULL;
4194 :
4195 : /* remove from service queue */
4196 12174 : fd_quic_svc_timers_cancel( state->svc_timers, conn );
4197 :
4198 : /* put connection back in free list */
4199 12174 : conn->free_conn_next = state->free_conn_list;
4200 12174 : state->free_conn_list = conn->conn_idx;
4201 :
4202 12174 : quic->metrics.conn_alloc_cnt--;
4203 :
4204 : /* clear keys */
4205 12174 : memset( &conn->secrets, 0, sizeof(fd_quic_crypto_secrets_t) );
4206 12174 : memset( conn->keys, 0, sizeof( conn->keys ) );
4207 12174 : memset( conn->new_keys, 0, sizeof( conn->new_keys ) );
4208 12174 : }
4209 :
4210 : fd_quic_conn_t *
4211 : fd_quic_connect( fd_quic_t * quic,
4212 : uint dst_ip_addr,
4213 : ushort dst_udp_port,
4214 : uint src_ip_addr,
4215 : ushort src_udp_port,
4216 6108 : long now ) {
4217 6108 : fd_quic_state_t * state = fd_quic_get_state( quic );
4218 6108 : state->now = now;
4219 :
4220 6108 : if( FD_UNLIKELY( !fd_quic_tls_hs_pool_free( state->hs_pool ) ) ) {
4221 : /* try evicting, 0 if oldest is too young so fail */
4222 6 : if( !fd_quic_tls_hs_cache_evict( quic, state ) ) {
4223 3 : return NULL;
4224 3 : }
4225 6 : }
4226 :
4227 6105 : fd_rng_t * rng = state->_rng;
4228 :
4229 : /* create conn ids for us and them
4230 : client creates connection id for the peer, peer immediately replaces it */
4231 6105 : ulong our_conn_id_u64 = fd_rng_ulong( rng );
4232 6105 : fd_quic_conn_id_t peer_conn_id; fd_quic_conn_id_rand( &peer_conn_id, rng );
4233 :
4234 6105 : fd_quic_conn_t * conn = fd_quic_conn_create(
4235 6105 : quic,
4236 6105 : our_conn_id_u64,
4237 6105 : &peer_conn_id,
4238 6105 : dst_ip_addr,
4239 6105 : dst_udp_port,
4240 6105 : src_ip_addr,
4241 6105 : src_udp_port,
4242 6105 : 0 /* client */ );
4243 :
4244 6105 : if( FD_UNLIKELY( !conn ) ) {
4245 3 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_conn_create failed" )) );
4246 3 : return NULL;
4247 3 : }
4248 :
4249 : /* Prepare QUIC-TLS transport params object (sent as a TLS extension).
4250 : Take template from state and mutate certain params in-place.
4251 :
4252 : See RFC 9000 Section 18 */
4253 :
4254 6102 : fd_quic_transport_params_t tp[1] = { state->transport_params };
4255 :
4256 : /* The original_destination_connection_id is omitted by clients.
4257 : Since this is a mutable field, explicitly clear it here. */
4258 :
4259 6102 : tp->original_destination_connection_id_present = 0;
4260 6102 : tp->original_destination_connection_id_len = 0;
4261 :
4262 : /* Similarly, explicitly zero out retry fields. */
4263 6102 : tp->retry_source_connection_id_present = 0;
4264 6102 : tp->retry_source_connection_id_len = 0;
4265 :
4266 : /* Repeat source conn ID -- rationale see fd_quic_handle_v1_initial */
4267 :
4268 6102 : FD_STORE( ulong, tp->initial_source_connection_id, conn->initial_source_conn_id );
4269 6102 : tp->initial_source_connection_id_present = 1;
4270 6102 : tp->initial_source_connection_id_len = FD_QUIC_CONN_ID_SZ;
4271 :
4272 : /* Create a TLS handshake (free>0 validated above) */
4273 :
4274 6102 : fd_quic_tls_hs_t * tls_hs = fd_quic_tls_hs_new(
4275 6102 : fd_quic_tls_hs_pool_ele_acquire( state->hs_pool ),
4276 6102 : state->tls,
4277 6102 : (void*)conn,
4278 6102 : 0 /*is_server*/,
4279 6102 : tp,
4280 6102 : now );
4281 6102 : if( FD_UNLIKELY( tls_hs->alert ) ) {
4282 0 : FD_LOG_WARNING(( "fd_quic_tls_hs_client_new failed" ));
4283 : /* free hs and the conn */
4284 0 : fd_quic_tls_hs_delete( tls_hs );
4285 0 : fd_quic_tls_hs_pool_ele_release( state->hs_pool, tls_hs );
4286 0 : fd_quic_conn_free( quic, conn );
4287 0 : return NULL;
4288 0 : }
4289 6102 : fd_quic_tls_hs_cache_ele_push_tail( &state->hs_cache, tls_hs, state->hs_pool );
4290 :
4291 6102 : quic->metrics.hs_created_cnt++;
4292 6102 : conn->tls_hs = tls_hs;
4293 :
4294 6102 : fd_quic_gen_initial_secret_and_keys( conn, &peer_conn_id, /* is_server */ 0 );
4295 :
4296 : /* set "called_conn_new" to indicate we should call conn_final
4297 : upon teardown */
4298 6102 : conn->called_conn_new = 1;
4299 :
4300 6102 : fd_quic_svc_prep_schedule( conn, now );
4301 6102 : fd_quic_svc_timers_schedule( state->svc_timers, conn, now );
4302 :
4303 : /* everything initialized */
4304 6102 : return conn;
4305 :
4306 6102 : }
4307 :
4308 : fd_quic_conn_t *
4309 : fd_quic_conn_create( fd_quic_t * quic,
4310 : ulong our_conn_id,
4311 : fd_quic_conn_id_t const * peer_conn_id,
4312 : uint peer_ip_addr,
4313 : ushort peer_udp_port,
4314 : uint self_ip_addr,
4315 : ushort self_udp_port,
4316 312297 : int server ) {
4317 312297 : if( FD_UNLIKELY( !our_conn_id ) ) return NULL;
4318 312297 : if( FD_UNLIKELY( !peer_ip_addr ) ) return NULL;
4319 :
4320 312297 : fd_quic_config_t * config = &quic->config;
4321 312297 : fd_quic_state_t * state = fd_quic_get_state( quic );
4322 :
4323 : /* fetch top of connection free list */
4324 312297 : uint conn_idx = state->free_conn_list;
4325 312297 : if( FD_UNLIKELY( conn_idx==UINT_MAX ) ) {
4326 3 : FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_conn_create failed: no free conn slots" )) );
4327 3 : quic->metrics.conn_err_no_slots_cnt++;
4328 3 : return NULL;
4329 3 : }
4330 312294 : if( FD_UNLIKELY( conn_idx >= quic->limits.conn_cnt ) ) {
4331 0 : FD_LOG_CRIT(( "Conn free list corruption detected" ));
4332 0 : return NULL;
4333 0 : }
4334 312294 : fd_quic_conn_t * conn = fd_quic_conn_at_idx( state, conn_idx );
4335 312294 : if( FD_UNLIKELY( conn->state != FD_QUIC_CONN_STATE_INVALID ) ) {
4336 0 : FD_LOG_CRIT(( "conn %p not free, this is a bug", (void *)conn ));
4337 0 : return NULL;
4338 0 : }
4339 :
4340 : /* insert into conn map */
4341 312294 : fd_quic_conn_map_t * insert_entry = fd_quic_conn_map_insert( state->conn_map, our_conn_id );
4342 :
4343 : /* if insert failed (should be impossible) fail, and do not remove connection
4344 : from free list */
4345 312294 : if( FD_UNLIKELY( insert_entry == NULL ) ) {
4346 : /* FIXME This has ~1e-6 probability of happening with 10M conns
4347 : Retry generating our_conn_id instead of logging a warning */
4348 0 : FD_LOG_WARNING(( "fd_quic_conn_create failed: failed to register new conn ID %lu with map size %lu", our_conn_id, fd_quic_conn_map_key_cnt( state->conn_map ) ));
4349 0 : return NULL;
4350 0 : }
4351 :
4352 : /* set connection map insert_entry to new connection */
4353 312294 : insert_entry->conn = conn;
4354 :
4355 : /* remove from free list */
4356 312294 : state->free_conn_list = conn->free_conn_next;
4357 312294 : conn->free_conn_next = UINT_MAX;
4358 :
4359 : /* if conn not marked free, skip */
4360 312294 : if( FD_UNLIKELY( conn->state != FD_QUIC_CONN_STATE_INVALID ) ) {
4361 0 : FD_LOG_CRIT(( "conn %p not free, this is a bug", (void *)conn ));
4362 0 : return NULL;
4363 0 : }
4364 :
4365 : /* initialize connection members */
4366 312294 : fd_quic_conn_clear( conn );
4367 :
4368 312294 : conn->server = !!server;
4369 312294 : conn->our_conn_id = our_conn_id;
4370 312294 : conn->host = (fd_quic_net_endpoint_t){
4371 312294 : .ip_addr = self_ip_addr, /* may be 0, if outgoing */
4372 312294 : .udp_port = self_udp_port,
4373 312294 : };
4374 312294 : conn->conn_gen++;
4375 :
4376 :
4377 : /* pkt_meta */
4378 312294 : fd_quic_pkt_meta_tracker_init( &conn->pkt_meta_tracker,
4379 312294 : quic->limits.inflight_frame_cnt,
4380 312294 : state->pkt_meta_pool );
4381 :
4382 : /* Initialize streams */
4383 312294 : FD_QUIC_STREAM_LIST_SENTINEL( conn->send_streams );
4384 312294 : FD_QUIC_STREAM_LIST_SENTINEL( conn->used_streams );
4385 :
4386 : /* initialize stream_id members */
4387 312294 : fd_quic_conn_stream_rx_t * srx = conn->srx;
4388 312294 : fd_quic_transport_params_t * our_tp = &state->transport_params;
4389 312294 : srx->rx_hi_stream_id = server ? FD_QUIC_STREAM_TYPE_UNI_CLIENT : FD_QUIC_STREAM_TYPE_UNI_SERVER;
4390 312294 : srx->rx_sup_stream_id = server ? FD_QUIC_STREAM_TYPE_UNI_CLIENT : FD_QUIC_STREAM_TYPE_UNI_SERVER;
4391 312294 : conn->tx_next_stream_id = server ? FD_QUIC_STREAM_TYPE_UNI_SERVER : FD_QUIC_STREAM_TYPE_UNI_CLIENT;
4392 312294 : conn->tx_sup_stream_id = server ? FD_QUIC_STREAM_TYPE_UNI_SERVER : FD_QUIC_STREAM_TYPE_UNI_CLIENT;
4393 :
4394 312294 : srx->rx_max_data = our_tp->initial_max_data;
4395 :
4396 312294 : if( state->transport_params.initial_max_streams_uni_present ) {
4397 312294 : srx->rx_sup_stream_id = (state->transport_params.initial_max_streams_uni<<2) + FD_QUIC_STREAM_TYPE_UNI_CLIENT;
4398 312294 : }
4399 312294 : if( state->transport_params.initial_max_data ) {
4400 312294 : srx->rx_max_data = state->transport_params.initial_max_data;
4401 312294 : }
4402 :
4403 : /* points to free tx space */
4404 312294 : conn->tx_ptr = conn->tx_buf_conn;
4405 :
4406 312294 : conn->keys_avail = fd_uint_set_bit( 0U, fd_quic_enc_level_initial_id );
4407 :
4408 : /* Packet numbers left as 0
4409 : rfc9000: s12.3:
4410 : Packet numbers in each packet space start at 0.
4411 : Subsequent packets sent in the same packet number space
4412 : MUST increase the packet number by at least 1
4413 : rfc9002: s3
4414 : It is permitted for some packet numbers to never be used, leaving intentional gaps. */
4415 :
4416 312294 : fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_HANDSHAKE );
4417 :
4418 : /* start with minimum supported max datagram */
4419 : /* peers may allow more */
4420 312294 : conn->tx_max_datagram_sz = FD_QUIC_INITIAL_PAYLOAD_SZ_MAX;
4421 :
4422 : /* initial source connection id */
4423 312294 : conn->initial_source_conn_id = our_conn_id;
4424 :
4425 : /* peer connection id */
4426 312294 : conn->peer_cids[0] = *peer_conn_id;
4427 312294 : conn->peer[0].ip_addr = peer_ip_addr;
4428 312294 : conn->peer[0].udp_port = peer_udp_port;
4429 :
4430 312294 : fd_quic_ack_gen_init( conn->ack_gen );
4431 :
4432 : /* initial rtt */
4433 : /* overridden when acks start returning */
4434 312294 : fd_rtt_estimate_t * rtt = conn->rtt;
4435 :
4436 312294 : ulong peer_ack_delay_exponent = 3UL; /* by spec, default is 3 */
4437 312294 : conn->peer_ack_delay_scale = (float)( 1UL << peer_ack_delay_exponent ) * 1e3f;
4438 312294 : conn->peer_max_ack_delay_ns = 0.0f; /* starts at zero, since peers respond immediately to */
4439 : /* INITIAL and HANDSHAKE */
4440 : /* updated when we get transport parameters */
4441 312294 : rtt->smoothed_rtt = FD_QUIC_INITIAL_RTT_US * 1e3f;
4442 312294 : rtt->latest_rtt = FD_QUIC_INITIAL_RTT_US * 1e3f;
4443 312294 : rtt->min_rtt = FD_QUIC_INITIAL_RTT_US * 1e3f;
4444 312294 : rtt->var_rtt = FD_QUIC_INITIAL_RTT_US * 1e3f * 0.5f;
4445 312294 : conn->rtt_period_ns = FD_QUIC_RTT_PERIOD_US * 1e3f;
4446 :
4447 : /* idle timeout */
4448 312294 : conn->idle_timeout_ns = config->idle_timeout;
4449 312294 : conn->last_activity = state->now;
4450 312294 : if( !conn->last_activity ) FD_LOG_CRIT(( "last activity: %ld", conn->last_activity ));
4451 312294 : conn->let_die_time_ns = LONG_MAX;
4452 :
4453 : /* update metrics */
4454 312294 : quic->metrics.conn_alloc_cnt++;
4455 312294 : quic->metrics.conn_created_cnt++;
4456 :
4457 312294 : fd_quic_svc_timers_init_conn( conn );
4458 :
4459 : /* prep idle timeout or keep alive at idle timeout/2 */
4460 312294 : long delay = quic->config.idle_timeout>>(quic->config.keep_alive);
4461 312294 : fd_quic_svc_prep_schedule( conn, state->now+delay );
4462 :
4463 : /* return connection */
4464 312294 : return conn;
4465 312294 : }
4466 :
4467 : long
4468 192093 : fd_quic_get_next_wakeup( fd_quic_t * quic ) {
4469 192093 : fd_quic_state_t * state = fd_quic_get_state( quic );
4470 192093 : long now = state->now;
4471 192093 : fd_quic_svc_event_t next = fd_quic_svc_timers_next( state->svc_timers, now, 0 );
4472 192093 : return next.timeout;
4473 192093 : }
4474 :
4475 : /* frame handling function default definitions */
4476 : static ulong
4477 : fd_quic_handle_padding_frame(
4478 : fd_quic_frame_ctx_t * ctx FD_PARAM_UNUSED,
4479 : fd_quic_padding_frame_t * data FD_PARAM_UNUSED,
4480 : uchar const * const p0,
4481 6069 : ulong p_sz ) {
4482 6069 : uchar const * p = p0;
4483 6069 : uchar const * const p_end = p + p_sz;
4484 6008316 : while( p<p_end && p[0]==0 ) p++;
4485 6069 : return (ulong)( p - p0 );
4486 6069 : }
4487 :
4488 : static ulong
4489 : fd_quic_handle_ping_frame(
4490 : fd_quic_frame_ctx_t * ctx,
4491 : fd_quic_ping_frame_t * data FD_PARAM_UNUSED,
4492 : uchar const * p0,
4493 6240 : ulong p_sz ) {
4494 6240 : FD_DTRACE_PROBE_1( quic_handle_ping_frame, ctx->conn->our_conn_id );
4495 : /* skip pings and pads */
4496 6240 : uchar const * p = p0;
4497 6240 : uchar const * const p_end = p + p_sz;
4498 10020 : while( p < p_end && ((uint)p[0] & 0xfeu) == 0 ) p++;
4499 6240 : return (ulong)( p - p0 );
4500 6240 : }
4501 :
4502 : /* Retry packet metadata
4503 : This will force pkt_meta to be returned to the free list
4504 : for use. It does so by finding unack'ed packet metadata
4505 : and setting the data up for retransmission.
4506 : force_below_pkt_num will force retry of all frames
4507 : with pkt_num < force_below_pkt_num.
4508 : 'arg_enc_level' is the enc_level to retry, or can be
4509 : set to ~0u for all enc_levels.
4510 : */
4511 : void
4512 : fd_quic_pkt_meta_retry( fd_quic_t * quic,
4513 : fd_quic_conn_t * conn,
4514 : ulong force_below_pkt_num,
4515 7205984 : uint arg_enc_level ) {
4516 7205984 : fd_quic_conn_stream_rx_t * srx = conn->srx;
4517 :
4518 7205984 : long now = fd_quic_get_state( quic )->now;
4519 :
4520 7205984 : fd_quic_pkt_meta_tracker_t * tracker = &conn->pkt_meta_tracker;
4521 7205984 : fd_quic_pkt_meta_t * pool = tracker->pool;
4522 :
4523 : /* used for metric tracking */
4524 7205984 : ulong prev_retx_pkt_num[FD_QUIC_NUM_ENC_LEVELS] = { ~0ul, ~0ul, ~0ul, ~0ul };
4525 :
4526 7205984 : long const pto_duration = fd_quic_calc_expiry_duration( conn, 0, conn->server );
4527 7205984 : long const loss_duration = fd_quic_calc_expiry_duration( conn, 1, conn->server );
4528 :
4529 7206038 : while(1) {
4530 : /* find earliest expiring pkt_meta, over smallest pkt number at each enc_level */
4531 7206038 : fd_quic_pkt_meta_t * pkt_meta = NULL;
4532 7206038 : long expiry = LONG_MAX;
4533 36030190 : for( uint j=0u; j<4u; ++j ) {
4534 : /* if arg_enc_level set, only consider that enc_level */
4535 28824152 : if( !(arg_enc_level==~0u) & !(j==arg_enc_level) ) continue;
4536 :
4537 28420523 : fd_quic_pkt_meta_t * pkt_meta_cand = fd_quic_pkt_meta_min( &tracker->sent_pkt_metas[j], pool );
4538 28420523 : if( !pkt_meta_cand ) continue;
4539 :
4540 6814658 : uint const pn_space = fd_quic_enc_level_to_pn_space( j );
4541 6814658 : ulong const highest_acked = conn->highest_acked[pn_space];
4542 6814658 : long const cand_duration = fd_long_if( pkt_meta_cand->key.pkt_num < highest_acked, loss_duration, pto_duration );
4543 :
4544 6814658 : pkt_meta_cand->expiry = fd_long_min( pkt_meta_cand->tx_time + cand_duration, pkt_meta_cand->expiry );
4545 :
4546 6814658 : if( !pkt_meta || pkt_meta_cand->expiry < expiry ) {
4547 6814658 : pkt_meta = pkt_meta_cand;
4548 6814658 : expiry = pkt_meta_cand->expiry;
4549 6814658 : }
4550 6814658 : }
4551 :
4552 7206038 : if( !pkt_meta ) return;
4553 :
4554 6814658 : uint const enc_level = pkt_meta->enc_level;
4555 6814658 : ulong const pkt_num = pkt_meta->key.pkt_num;
4556 :
4557 : /* Continue until nothing expired nor to be skipped */
4558 6814658 : if( !!(pkt_num >= force_below_pkt_num) & !!(expiry > now) ) {
4559 : /* safe even when expiry is LONG_MAX, because prep_schedule takes min */
4560 6814604 : fd_quic_svc_prep_schedule( conn, expiry );
4561 6814604 : return;
4562 6814604 : };
4563 :
4564 54 : quic->metrics.pkt_retransmissions_cnt[enc_level] += !(pkt_meta->key.pkt_num == prev_retx_pkt_num[enc_level]);
4565 54 : prev_retx_pkt_num[enc_level] = pkt_num;
4566 :
4567 54 : uint type = pkt_meta->key.type;
4568 54 : FD_DTRACE_PROBE_4( quic_pkt_meta_retry, conn->our_conn_id, pkt_num, expiry, type);
4569 : /* set the data to retry */
4570 54 : switch( type ) {
4571 0 : case FD_QUIC_PKT_META_TYPE_HS_DATA:
4572 0 : do {
4573 0 : ulong offset = fd_ulong_max( conn->hs_ackd_bytes[enc_level], pkt_meta->val.range.offset_lo );
4574 0 : if( offset < conn->hs_sent_bytes[enc_level] ) {
4575 0 : conn->hs_sent_bytes[enc_level] = offset;
4576 0 : conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
4577 0 : }
4578 0 : } while(0);
4579 0 : break;
4580 :
4581 39 : case FD_QUIC_PKT_META_TYPE_STREAM:
4582 39 : do {
4583 39 : ulong stream_id = pkt_meta->key.stream_id;
4584 :
4585 : /* find the stream */
4586 39 : fd_quic_stream_t * stream = NULL;
4587 39 : fd_quic_stream_map_t * stream_entry = fd_quic_stream_map_query( conn->stream_map, stream_id, NULL );
4588 39 : if( FD_LIKELY( stream_entry && stream_entry->stream &&
4589 39 : ( stream_entry->stream->stream_flags & FD_QUIC_STREAM_FLAGS_DEAD ) == 0 ) ) {
4590 36 : stream = stream_entry->stream;
4591 :
4592 : /* do not try sending data that has been acked */
4593 36 : ulong offset = fd_ulong_max( pkt_meta->val.range.offset_lo, stream->unacked_low );
4594 :
4595 : /* This pkt_meta may be stale: when ACK-driven loss detection
4596 : force-retries an earlier pkt_meta for the same stream, the
4597 : retransmitted data can be ACKed (advancing unacked_low)
4598 : before this pkt_meta expires. Skip the retry if the
4599 : stream has nothing left to send. */
4600 36 : if( FD_UNLIKELY( offset>=stream->tx_buf.head &&
4601 36 : !( stream->state & FD_QUIC_STREAM_STATE_TX_FIN ) ) ) {
4602 3 : break;
4603 3 : }
4604 :
4605 : /* any data left to retry? */
4606 33 : stream->tx_sent = fd_ulong_min( stream->tx_sent, offset );
4607 :
4608 : /* We must have something to send if the stream was found */
4609 33 : if( !( (stream->tx_sent < stream->tx_buf.head) | (stream->state & FD_QUIC_STREAM_STATE_TX_FIN) ) ) {
4610 0 : FD_LOG_CRIT(( "unexpected retry for completed stream %lu", stream_id ));
4611 0 : }
4612 :
4613 : /* insert into send list */
4614 33 : FD_QUIC_STREAM_LIST_REMOVE( stream );
4615 33 : FD_QUIC_STREAM_LIST_INSERT_BEFORE( conn->send_streams, stream );
4616 :
4617 : /* set the data to go out on the next packet */
4618 33 : stream->stream_flags |= FD_QUIC_STREAM_FLAGS_UNSENT; /* we have unsent data */
4619 33 : stream->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
4620 33 : }
4621 39 : } while(0);
4622 39 : break;
4623 :
4624 39 : case FD_QUIC_PKT_META_TYPE_HS_DONE:
4625 0 : if( FD_LIKELY( !conn->handshake_done_ackd ) ) {
4626 0 : conn->handshake_done_send = 1;
4627 0 : conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
4628 0 : }
4629 0 : break;
4630 :
4631 0 : case FD_QUIC_PKT_META_TYPE_MAX_DATA:
4632 0 : if( srx->rx_max_data_ackd < srx->rx_max_data ) {
4633 0 : conn->flags |= FD_QUIC_CONN_FLAGS_MAX_DATA;
4634 0 : conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
4635 0 : }
4636 0 : break;
4637 :
4638 0 : case FD_QUIC_PKT_META_TYPE_MAX_STREAMS_UNIDIR:
4639 0 : do {
4640 : /* do we still need to send? */
4641 : /* get required value */
4642 0 : ulong max_streams_unidir = srx->rx_sup_stream_id >> 2;
4643 :
4644 0 : if( max_streams_unidir > srx->rx_max_streams_unidir_ackd ) {
4645 : /* set the data to go out on the next packet */
4646 0 : conn->flags |= FD_QUIC_CONN_FLAGS_MAX_STREAMS_UNIDIR;
4647 0 : conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
4648 0 : }
4649 0 : } while(0);
4650 0 : break;
4651 :
4652 0 : case FD_QUIC_PKT_META_TYPE_CLOSE:
4653 0 : conn->flags &= ~FD_QUIC_CONN_FLAGS_CLOSE_SENT;
4654 0 : conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
4655 0 : break;
4656 :
4657 15 : case FD_QUIC_PKT_META_TYPE_PING:
4658 15 : conn->flags = ( conn->flags & ~FD_QUIC_CONN_FLAGS_PING_SENT )
4659 15 : | FD_QUIC_CONN_FLAGS_PING;
4660 15 : conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
4661 15 : break;
4662 54 : }
4663 :
4664 : /* reschedule to ensure the data gets processed */
4665 54 : fd_quic_svc_prep_schedule_now( conn );
4666 :
4667 54 : fd_quic_pkt_meta_remove( &tracker->sent_pkt_metas[enc_level], pool, pkt_meta );
4668 54 : conn->used_pkt_meta--;
4669 54 : }
4670 7205984 : }
4671 :
4672 : /* reclaim resources associated with packet metadata
4673 : this is called in response to received acks */
4674 : void
4675 : fd_quic_reclaim_pkt_meta( fd_quic_conn_t * conn,
4676 : fd_quic_pkt_meta_t * pkt_meta,
4677 6966469 : uint enc_level ) {
4678 6966469 : fd_quic_conn_stream_rx_t * srx = conn->srx;
4679 :
4680 6966469 : uint type = pkt_meta->key.type;
4681 6966469 : fd_quic_range_t range = pkt_meta->val.range;
4682 :
4683 6966469 : switch( type ) {
4684 :
4685 6036 : case FD_QUIC_PKT_META_TYPE_PING:
4686 6036 : do {
4687 6036 : conn->flags &= ~( FD_QUIC_CONN_FLAGS_PING | FD_QUIC_CONN_FLAGS_PING_SENT );
4688 6036 : } while(0);
4689 6036 : break;
4690 :
4691 25182 : case FD_QUIC_PKT_META_TYPE_HS_DATA:
4692 25182 : do {
4693 : /* Note that tls_hs could already be freed */
4694 : /* is this ack'ing the next consecutive bytes?
4695 : if so, we can increase the ack'd bytes
4696 : if not, we retransmit the bytes expected to be ack'd
4697 : we assume a gap means a dropped packet, and
4698 : this policy allows us to free up the pkt_meta here */
4699 25182 : ulong hs_ackd_bytes = conn->hs_ackd_bytes[enc_level];
4700 25182 : if( range.offset_lo <= hs_ackd_bytes ) {
4701 25182 : hs_ackd_bytes = conn->hs_ackd_bytes[enc_level]
4702 25182 : = fd_ulong_max( hs_ackd_bytes, range.offset_hi );
4703 :
4704 : /* remove any unused hs_data */
4705 25182 : fd_quic_tls_hs_data_t * hs_data = NULL;
4706 :
4707 25182 : hs_data = fd_quic_tls_get_hs_data( conn->tls_hs, enc_level );
4708 85872 : while( hs_data && hs_data->offset + hs_data->data_sz <= hs_ackd_bytes ) {
4709 60690 : fd_quic_tls_pop_hs_data( conn->tls_hs, enc_level );
4710 60690 : hs_data = fd_quic_tls_get_hs_data( conn->tls_hs, enc_level );
4711 60690 : }
4712 25182 : } else {
4713 0 : conn->hs_sent_bytes[enc_level] =
4714 0 : fd_ulong_min( conn->hs_sent_bytes[enc_level], hs_ackd_bytes );
4715 0 : conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
4716 0 : }
4717 25182 : } while(0);
4718 25182 : break;
4719 :
4720 6063 : case FD_QUIC_PKT_META_TYPE_HS_DONE:
4721 6063 : do {
4722 6063 : conn->handshake_done_ackd = 1;
4723 6063 : conn->handshake_done_send = 0;
4724 6063 : if( FD_LIKELY( conn->tls_hs ) ) {
4725 6063 : fd_quic_state_t * state = fd_quic_get_state( conn->quic );
4726 6063 : fd_quic_tls_hs_delete( conn->tls_hs );
4727 6063 : fd_quic_tls_hs_cache_ele_remove( &state->hs_cache, conn->tls_hs, state->hs_pool );
4728 6063 : fd_quic_tls_hs_pool_ele_release( state->hs_pool, conn->tls_hs );
4729 6063 : conn->tls_hs = NULL;
4730 6063 : }
4731 6063 : } while(0);
4732 6063 : break;
4733 :
4734 0 : case FD_QUIC_PKT_META_TYPE_MAX_DATA:
4735 0 : do {
4736 0 : ulong max_data_ackd = pkt_meta->val.scalar;
4737 :
4738 : /* ack can only increase max_data_ackd */
4739 0 : max_data_ackd = fd_ulong_max( max_data_ackd, srx->rx_max_data_ackd );
4740 :
4741 : /* max_data_ackd > rx_max_data is a protocol violation */
4742 0 : if( FD_UNLIKELY( max_data_ackd > srx->rx_max_data ) ) {
4743 : /* this is a protocol violation, so inform the peer */
4744 0 : fd_quic_conn_error( conn, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
4745 0 : return;
4746 0 : }
4747 :
4748 : /* clear flag only if acked value == current value */
4749 0 : if( FD_LIKELY( max_data_ackd == srx->rx_max_data ) ) {
4750 0 : conn->flags &= ~FD_QUIC_CONN_FLAGS_MAX_DATA;
4751 0 : }
4752 :
4753 : /* set the ackd value */
4754 0 : srx->rx_max_data_ackd = max_data_ackd;
4755 0 : } while(0);
4756 0 : break;
4757 :
4758 0 : case FD_QUIC_PKT_META_TYPE_MAX_STREAMS_UNIDIR:
4759 0 : do {
4760 0 : ulong max_streams_unidir_ackd = pkt_meta->val.scalar;
4761 :
4762 : /* ack can only increase max_streams_unidir_ackd */
4763 0 : max_streams_unidir_ackd = fd_ulong_max( max_streams_unidir_ackd, srx->rx_max_streams_unidir_ackd );
4764 :
4765 : /* get required value */
4766 0 : ulong max_streams_unidir = srx->rx_sup_stream_id >> 2;
4767 :
4768 : /* clear flag only if acked value == current value */
4769 0 : if( FD_LIKELY( max_streams_unidir_ackd == max_streams_unidir ) ) {
4770 0 : conn->flags &= ~FD_QUIC_CONN_FLAGS_MAX_STREAMS_UNIDIR;
4771 0 : }
4772 :
4773 : /* set the ackd value */
4774 0 : srx->rx_max_streams_unidir_ackd = max_streams_unidir_ackd;
4775 0 : } while(0);
4776 0 : break;
4777 :
4778 6929188 : case FD_QUIC_PKT_META_TYPE_STREAM:
4779 6929188 : do {
4780 6929188 : ulong stream_id = pkt_meta->key.stream_id;
4781 6929188 : fd_quic_range_t range = pkt_meta->val.range;
4782 :
4783 : /* find the stream */
4784 6929188 : fd_quic_stream_t * stream = NULL;
4785 6929188 : fd_quic_stream_map_t * stream_entry = fd_quic_stream_map_query( conn->stream_map, stream_id, NULL );
4786 6929188 : if( FD_LIKELY( stream_entry && stream_entry->stream &&
4787 6929188 : ( stream_entry->stream->stream_flags & FD_QUIC_STREAM_FLAGS_DEAD ) == 0 ) ) {
4788 6929188 : stream = stream_entry->stream;
4789 :
4790 6929188 : ulong tx_tail = stream->unacked_low;
4791 6929188 : ulong tx_sent = stream->tx_sent;
4792 :
4793 : /* ignore bytes which were already acked */
4794 6929188 : range.offset_lo = fd_ulong_max( range.offset_lo, tx_tail );
4795 :
4796 : /* verify offset_hi */
4797 6929188 : if( FD_UNLIKELY( range.offset_hi > stream->tx_buf.head ) ) {
4798 : /* offset_hi in the pkt_meta (the highest byte offset in the packet */
4799 : /* should never exceed tx_buf.head - the highest byte offset in the */
4800 : /* stream */
4801 0 : fd_quic_conn_error( conn, FD_QUIC_CONN_REASON_INTERNAL_ERROR, __LINE__ );
4802 0 : return;
4803 0 : }
4804 :
4805 6929188 : uchar * tx_ack = stream->tx_ack;
4806 : /* did they ack the first unacked byte? */
4807 6929188 : if( FD_LIKELY( range.offset_lo == tx_tail ) ) {
4808 : /* move tail to first unacked byte */
4809 6929179 : tx_tail = range.offset_hi;
4810 6929224 : while( tx_tail < tx_sent ) {
4811 : /* TODO - optimize this for larger strides */
4812 : /* can we skip a whole byte? */
4813 16863 : if( ( tx_tail & 7ul ) == 0ul && tx_tail + 8ul <= tx_sent && tx_ack[tx_tail>>3ul] == 0xffu ) {
4814 30 : tx_tail += 8ul;
4815 16833 : } else {
4816 16833 : if( tx_ack[tx_tail>>3ul] & ( 1u << ( tx_tail & 7u ) ) ) {
4817 15 : tx_tail++;
4818 16818 : } else {
4819 16818 : break;
4820 16818 : }
4821 16833 : }
4822 16863 : }
4823 6929179 : stream->unacked_low = tx_tail;
4824 6929179 : } else {
4825 : /* mark this range as acked in tx_ack, so we can skip it later */
4826 : /* TODO optimize this for larger strides */
4827 711 : for( ulong k = range.offset_lo; k < range.offset_hi; ) {
4828 702 : if( ( k & 7ul ) == 0ul && k + 8ul <= range.offset_hi ) {
4829 : /* set whole byte */
4830 651 : tx_ack[k>>3ul] = 0xffu;
4831 651 : k += 8ul;
4832 651 : } else {
4833 : /* compiler is not smart enough to know ( 1u << ( k & 7u ) ) fits in a uchar */
4834 51 : tx_ack[k>>3ul] |= (uchar)( 1ul << ( k & 7ul ) );
4835 51 : k++;
4836 51 : }
4837 702 : }
4838 9 : }
4839 :
4840 : /* For convenience */
4841 6929188 : uint fin_state_mask = FD_QUIC_STREAM_STATE_TX_FIN | FD_QUIC_STREAM_STATE_RX_FIN;
4842 :
4843 : /* Free stream if it's done:
4844 : 1. peer has acked every data byte user has tried to send
4845 : 2. peer has acked the fin --> user has fin'd */
4846 6929188 : if( tx_tail == stream->tx_buf.head &&
4847 6929188 : ( stream->state & fin_state_mask ) == fin_state_mask ) {
4848 : /* fd_quic_tx_stream_free also notifies the user */
4849 6912346 : fd_quic_tx_stream_free( conn->quic, conn, stream, FD_QUIC_STREAM_NOTIFY_END );
4850 6912346 : }
4851 6929188 : }
4852 6929188 : } while(0);
4853 6929188 : break;
4854 6966469 : }
4855 6966469 : }
4856 :
4857 : /* process ack range
4858 : applies to pkt_number in [largest_ack - ack_range, largest_ack] */
4859 : void
4860 : fd_quic_process_ack_range( fd_quic_conn_t * conn,
4861 : fd_quic_frame_ctx_t * context,
4862 : uint enc_level,
4863 : ulong largest_ack,
4864 : ulong ack_range,
4865 : int is_largest,
4866 : long now,
4867 134660 : ulong ack_delay ) {
4868 134660 : fd_quic_pkt_t * pkt = context->pkt;
4869 :
4870 : /* inclusive range */
4871 134660 : ulong hi = largest_ack;
4872 134660 : ulong lo = largest_ack - ack_range;
4873 134660 : FD_DTRACE_PROBE_4( quic_process_ack_range, conn->our_conn_id, enc_level, lo, hi );
4874 :
4875 134660 : fd_quic_pkt_meta_tracker_t * tracker = &conn->pkt_meta_tracker;
4876 134660 : fd_quic_pkt_meta_t * pool = tracker->pool;
4877 134660 : fd_quic_pkt_meta_ds_t * sent = &tracker->sent_pkt_metas[enc_level];
4878 :
4879 : /* start at oldest sent */
4880 134660 : for( fd_quic_pkt_meta_ds_fwd_iter_t iter = fd_quic_pkt_meta_ds_idx_ge( sent, lo, pool );
4881 7095054 : !fd_quic_pkt_meta_ds_fwd_iter_done( iter );
4882 6960475 : iter = fd_quic_pkt_meta_ds_fwd_iter_next( iter, pool ) ) {
4883 6960475 : fd_quic_pkt_meta_t * e = fd_quic_pkt_meta_ds_fwd_iter_ele( iter, pool );
4884 6960475 : if( FD_UNLIKELY( e->key.pkt_num > hi ) ) break;
4885 6960394 : if( is_largest && e->key.pkt_num == hi && hi >= pkt->rtt_pkt_number ) {
4886 134537 : pkt->rtt_pkt_number = hi;
4887 134537 : pkt->rtt_ack_time = now - e->tx_time; /* in ns */
4888 134537 : pkt->rtt_ack_delay = ack_delay; /* in peer units */
4889 134537 : }
4890 6960394 : fd_quic_reclaim_pkt_meta( conn, e, enc_level );
4891 6960394 : }
4892 :
4893 134660 : conn->used_pkt_meta -= fd_quic_pkt_meta_remove_range( sent, pool, lo, hi );
4894 134660 : }
4895 :
4896 : static ulong
4897 : fd_quic_handle_ack_frame( fd_quic_frame_ctx_t * context,
4898 : fd_quic_ack_frame_t * data,
4899 : uchar const * p,
4900 134531 : ulong p_sz ) {
4901 134531 : fd_quic_conn_t * conn = context->conn;
4902 134531 : uint enc_level = context->pkt->enc_level;
4903 134531 : uint pn_space = fd_quic_enc_level_to_pn_space( enc_level );
4904 134531 : ulong const largest_ack = data->largest_ack;
4905 :
4906 134531 : if( FD_UNLIKELY( data->first_ack_range > largest_ack ) ) {
4907 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
4908 0 : return FD_QUIC_PARSE_FAIL;
4909 0 : }
4910 :
4911 134531 : if( FD_UNLIKELY( largest_ack >= conn->pkt_number[pn_space] ) ) {
4912 3 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
4913 3 : return FD_QUIC_PARSE_FAIL;
4914 3 : }
4915 :
4916 : /* update highest_acked */
4917 134528 : conn->highest_acked[pn_space] = fd_ulong_max( conn->highest_acked[pn_space], largest_ack );
4918 :
4919 134528 : fd_quic_state_t * state = fd_quic_get_state( conn->quic );
4920 134528 : long const now = state->now;
4921 134528 : /******/ conn->last_ack = now;
4922 :
4923 : /* RFC 9002, Section 6.1: We declare a packet p lost if either:
4924 : 1. It was 'skipped': at least three packets were sent after p but before
4925 : the highest ack'ed packet in this ack frame, e.g. (p x y z highest_acked).
4926 : 2. It 'expired': p was sent at least time-threshold time ago.
4927 : Time-threshold is computed in calc_expiry, and typically differs from
4928 : pkt_meta->expiry.
4929 :
4930 : Let skip_ceil be the smallest pkt_num such that any unacked pkt_meta
4931 : with pkt_num < skip_ceil is 'skipped' as defined above. We compute this
4932 : before removing acked packets from the tracker.
4933 :
4934 : We unfortunately can't just use 'largest_ack-3' because 1) largest_ack'd
4935 : may have been previously acknowledged and 2) we may have skipped pkt_nums.
4936 : */
4937 134528 : ulong skip_ceil = 0UL;
4938 134528 : if( FD_LIKELY( largest_ack > 0UL ) ) {
4939 563044 : #define FD_QUIC_K_PACKET_THRESHOLD 3
4940 116249 : fd_quic_pkt_meta_tracker_t * tracker = &conn->pkt_meta_tracker;
4941 116249 : fd_quic_pkt_meta_t * pool = tracker->pool;
4942 116249 : fd_quic_pkt_meta_ds_t * sent = &tracker->sent_pkt_metas[enc_level];
4943 :
4944 116249 : uint pkt_num_changes = 0;
4945 116249 : ulong prev_pkt_num = ~0UL;
4946 116249 : fd_quic_pkt_meta_ds_fwd_iter_t start = fd_quic_pkt_meta_ds_idx_le( sent, pool, largest_ack-1 );
4947 116249 : for( fd_quic_pkt_meta_ds_rev_iter_t iter = start; /* rev<>fwd iter */
4948 446795 : !!(pkt_num_changes<FD_QUIC_K_PACKET_THRESHOLD) & !fd_quic_pkt_meta_ds_rev_iter_done(iter);
4949 330546 : iter=fd_quic_pkt_meta_ds_rev_iter_next( iter, pool ) ) {
4950 330546 : fd_quic_pkt_meta_t * e = fd_quic_pkt_meta_ds_rev_iter_ele( iter, pool );
4951 330546 : pkt_num_changes += !(e->key.pkt_num==prev_pkt_num);
4952 330546 : prev_pkt_num = e->key.pkt_num;
4953 330546 : }
4954 116249 : skip_ceil = fd_ulong_if( pkt_num_changes==FD_QUIC_K_PACKET_THRESHOLD, prev_pkt_num, 0UL );
4955 116249 : }
4956 :
4957 : /* track lowest packet acked */
4958 134528 : ulong low_ack_pkt_number = largest_ack - data->first_ack_range;
4959 :
4960 : /* process ack range
4961 : applies to pkt_number in [largest_ack - first_ack_range, largest_ack] */
4962 134528 : fd_quic_process_ack_range( conn,
4963 134528 : context,
4964 134528 : enc_level,
4965 134528 : largest_ack,
4966 134528 : data->first_ack_range,
4967 134528 : 1 /* is_largest */,
4968 134528 : now,
4969 134528 : data->ack_delay );
4970 :
4971 134528 : uchar const * p_str = p;
4972 134528 : uchar const * p_end = p + p_sz;
4973 :
4974 134528 : ulong ack_range_count = data->ack_range_count;
4975 :
4976 : /* cur_pkt_number holds the packet number of the lowest processed
4977 : and acknowledged packet
4978 : This should always be a valid packet number >= 0 */
4979 134528 : ulong cur_pkt_number = largest_ack - data->first_ack_range;
4980 :
4981 : /* walk thru ack ranges */
4982 134528 : for( ulong j = 0UL; j < ack_range_count; ++j ) {
4983 0 : if( FD_UNLIKELY( p_end <= p ) ) {
4984 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
4985 0 : return FD_QUIC_PARSE_FAIL;
4986 0 : }
4987 :
4988 0 : fd_quic_ack_range_frag_t ack_range[1];
4989 0 : ulong rc = fd_quic_decode_ack_range_frag( ack_range, p, (ulong)( p_end - p ) );
4990 0 : if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
4991 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
4992 0 : return FD_QUIC_PARSE_FAIL;
4993 0 : }
4994 :
4995 : /* ensure we have ulong local vars, regardless of ack_range definition */
4996 0 : ulong gap = (ulong)ack_range->gap;
4997 0 : ulong length = (ulong)ack_range->length;
4998 :
4999 : /* sanity check before unsigned arithmetic */
5000 0 : if( FD_UNLIKELY( ( gap > ( ~0x3UL ) ) |
5001 0 : ( length > ( ~0x3UL ) ) ) ) {
5002 : /* This is an unreasonably large value, so fail with protocol violation
5003 : It's also likely impossible due to the encoding method */
5004 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
5005 0 : return FD_QUIC_PARSE_FAIL;
5006 0 : }
5007 :
5008 : /* The number of packet numbers to skip (they are not being acked) is
5009 : ack_range->gap + 2
5010 : This is +1 to get from the lowest acked packet to the highest unacked packet
5011 : and +1 because the count of packets in the gap is (ack_range->gap+1) */
5012 0 : ulong skip = gap + 2UL;
5013 :
5014 : /* verify the skip and length values are valid */
5015 0 : if( FD_UNLIKELY( skip + length > cur_pkt_number ) ) {
5016 : /* this is a protocol violation, so inform the peer */
5017 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
5018 0 : return FD_QUIC_PARSE_FAIL;
5019 0 : }
5020 :
5021 : /* track lowest */
5022 0 : ulong lo_pkt_number = cur_pkt_number - skip - length;
5023 0 : low_ack_pkt_number = fd_ulong_min( low_ack_pkt_number, lo_pkt_number );
5024 :
5025 : /* process ack range */
5026 0 : fd_quic_process_ack_range( conn,
5027 0 : context,
5028 0 : enc_level,
5029 0 : cur_pkt_number - skip,
5030 0 : length,
5031 0 : 0 /* is_largest */,
5032 0 : now,
5033 0 : 0 /* ack_delay not used here */ );
5034 :
5035 : /* Find the next lowest processed and acknowledged packet number
5036 : This should get us to the next lowest processed and acknowledged packet
5037 : number */
5038 0 : cur_pkt_number -= skip + length;
5039 :
5040 0 : p += rc;
5041 0 : }
5042 :
5043 : /* Process packets declared lost for either:
5044 : 1. 'skipped': see skip_ceil computation above
5045 : 2. 'expired': checked inside pkt_meta_retry */
5046 134528 : fd_quic_pkt_meta_retry( conn->quic, conn, skip_ceil, enc_level );
5047 :
5048 : /* ECN counts
5049 : we currently ignore them, but we must process them to get to the following bytes */
5050 134528 : if( data->type & 1U ) {
5051 0 : if( FD_UNLIKELY( p_end <= p ) ) {
5052 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
5053 0 : return FD_QUIC_PARSE_FAIL;
5054 0 : }
5055 :
5056 0 : fd_quic_ecn_counts_frag_t ecn_counts[1];
5057 0 : ulong rc = fd_quic_decode_ecn_counts_frag( ecn_counts, p, (ulong)( p_end - p ) );
5058 0 : if( rc == FD_QUIC_PARSE_FAIL ) {
5059 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
5060 0 : return FD_QUIC_PARSE_FAIL;
5061 0 : }
5062 :
5063 0 : p += rc;
5064 0 : }
5065 :
5066 134528 : return (ulong)( p - p_str );
5067 134528 : }
5068 :
5069 : static ulong
5070 : fd_quic_handle_reset_stream_frame(
5071 : fd_quic_frame_ctx_t * context,
5072 : fd_quic_reset_stream_frame_t * data,
5073 : uchar const * p FD_PARAM_UNUSED,
5074 0 : ulong p_sz FD_PARAM_UNUSED ) {
5075 : /* TODO implement */
5076 0 : FD_DTRACE_PROBE_4( quic_handle_reset_stream_frame, context->conn->our_conn_id, data->stream_id, data->app_proto_err_code, data->final_size );
5077 0 : return 0UL;
5078 0 : }
5079 :
5080 : static ulong
5081 : fd_quic_handle_stop_sending_frame(
5082 : fd_quic_frame_ctx_t * context,
5083 : fd_quic_stop_sending_frame_t * data,
5084 : uchar const * p FD_PARAM_UNUSED,
5085 0 : ulong p_sz FD_PARAM_UNUSED ) {
5086 0 : FD_DTRACE_PROBE_3( quic_handle_stop_sending_frame, context->conn->our_conn_id, data->stream_id, data->app_proto_err_code );
5087 0 : return 0UL;
5088 0 : }
5089 :
5090 : static ulong
5091 : fd_quic_handle_new_token_frame(
5092 : fd_quic_frame_ctx_t * context,
5093 : fd_quic_new_token_frame_t * data,
5094 : uchar const * p FD_PARAM_UNUSED,
5095 0 : ulong p_sz FD_PARAM_UNUSED ) {
5096 : /* FIXME A server MUST treat receipt of a NEW_TOKEN frame as a connection error of type PROTOCOL_VIOLATION. */
5097 0 : (void)data;
5098 0 : FD_DTRACE_PROBE_1( quic_handle_new_token_frame, context->conn->our_conn_id );
5099 0 : return 0UL;
5100 0 : }
5101 :
5102 : void
5103 : fd_quic_tx_stream_free( fd_quic_t * quic,
5104 : fd_quic_conn_t * conn,
5105 : fd_quic_stream_t * stream,
5106 6924487 : int code ) {
5107 :
5108 : /* TODO rename FD_QUIC_NOTIFY_END to FD_QUIC_STREAM_NOTIFY_END et al */
5109 6924487 : if( FD_LIKELY( stream->state != FD_QUIC_STREAM_STATE_DEAD ) ) {
5110 6924487 : fd_quic_cb_stream_notify( quic, stream, stream->context, code );
5111 6924487 : stream->state = FD_QUIC_STREAM_STATE_DEAD;
5112 6924487 : }
5113 :
5114 6924487 : ulong stream_id = stream->stream_id;
5115 :
5116 : /* remove from stream map */
5117 6924487 : fd_quic_stream_map_t * stream_map = conn->stream_map;
5118 6924487 : fd_quic_stream_map_t * stream_entry = fd_quic_stream_map_query( stream_map, stream_id, NULL );
5119 6924487 : if( FD_LIKELY( stream_entry ) ) {
5120 6924487 : if( FD_LIKELY( stream_entry->stream ) ) {
5121 6924487 : stream_entry->stream->stream_flags = FD_QUIC_STREAM_FLAGS_DEAD;
5122 6924487 : }
5123 6924487 : fd_quic_stream_map_remove( stream_map, stream_entry );
5124 6924487 : }
5125 :
5126 : /* remove from list - idempotent */
5127 6924487 : FD_QUIC_STREAM_LIST_REMOVE( stream );
5128 6924487 : stream->stream_flags = FD_QUIC_STREAM_FLAGS_DEAD;
5129 6924487 : stream->stream_id = ~0UL;
5130 :
5131 : /* add to stream_pool */
5132 6924487 : fd_quic_state_t * state = fd_quic_get_state( quic );
5133 6924487 : fd_quic_stream_pool_free( state->stream_pool, stream );
5134 :
5135 6924487 : }
5136 :
5137 :
5138 : static inline __attribute__((always_inline)) ulong
5139 : fd_quic_handle_stream_frame(
5140 : fd_quic_frame_ctx_t * context,
5141 : uchar const * p,
5142 : ulong p_sz,
5143 : ulong stream_id,
5144 : ulong offset,
5145 : ulong data_sz,
5146 132460010 : int fin ) {
5147 132460010 : fd_quic_t * quic = context->quic;
5148 132460010 : fd_quic_conn_t * conn = context->conn;
5149 132460010 : fd_quic_pkt_t * pkt = context->pkt;
5150 :
5151 132460010 : FD_DTRACE_PROBE_5( quic_handle_stream_frame, conn->our_conn_id, stream_id, offset, data_sz, fin );
5152 :
5153 : /* stream_id type check */
5154 132460010 : ulong stream_type = stream_id & 3UL;
5155 132460010 : if( FD_UNLIKELY( stream_type != ( conn->server ? FD_QUIC_STREAM_TYPE_UNI_CLIENT : FD_QUIC_STREAM_TYPE_UNI_SERVER ) ) ) {
5156 0 : FD_DEBUG( FD_LOG_DEBUG(( "Received forbidden stream type" )); )
5157 : /* Technically should switch between STREAM_LIMIT_ERROR and STREAM_STATE_ERROR here */
5158 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_STREAM_LIMIT_ERROR, __LINE__ );
5159 0 : return FD_QUIC_PARSE_FAIL;
5160 0 : }
5161 :
5162 : /* length check */
5163 132460010 : if( FD_UNLIKELY( data_sz > p_sz ) ) {
5164 0 : FD_DEBUG( FD_LOG_DEBUG(( "Stream header indicates %lu bytes length, but only have %lu", data_sz, p_sz )); )
5165 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
5166 0 : return FD_QUIC_PARSE_FAIL;
5167 0 : }
5168 :
5169 132460010 : conn->unacked_sz += data_sz;
5170 :
5171 : /* stream_id outside allowed range - protocol error */
5172 132460010 : if( FD_UNLIKELY( stream_id >= conn->srx->rx_sup_stream_id ) ) {
5173 3 : FD_DEBUG( FD_LOG_DEBUG(( "Stream ID violation detected" )); )
5174 3 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_STREAM_LIMIT_ERROR, __LINE__ );
5175 3 : return FD_QUIC_PARSE_FAIL;
5176 3 : }
5177 :
5178 : /* A receiver MUST close the connection with an error of type FLOW_CONTROL_ERROR if the sender
5179 : violates the advertised connection or stream data limits */
5180 132460007 : if( FD_UNLIKELY( quic->config.initial_rx_max_stream_data < offset + data_sz ) ) {
5181 3 : FD_DEBUG( FD_LOG_DEBUG(( "Stream data limit exceeded" )); )
5182 3 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FLOW_CONTROL_ERROR, __LINE__ );
5183 3 : return FD_QUIC_PARSE_FAIL;
5184 3 : }
5185 :
5186 132460004 : int rx_res = fd_quic_cb_stream_rx( quic, conn, stream_id, offset, p, data_sz, fin );
5187 132460004 : pkt->ack_flag |= fd_uint_if( rx_res==FD_QUIC_SUCCESS, 0U, ACK_FLAG_CANCEL );
5188 :
5189 : /* packet bytes consumed */
5190 132460004 : return data_sz;
5191 132460007 : }
5192 :
5193 : static ulong
5194 : fd_quic_handle_stream_8_frame(
5195 : fd_quic_frame_ctx_t * context,
5196 : fd_quic_stream_8_frame_t * data,
5197 : uchar const * p,
5198 0 : ulong p_sz ) {
5199 0 : return fd_quic_handle_stream_frame( context, p, p_sz, data->stream_id, 0UL, p_sz, data->type&1 );
5200 0 : }
5201 :
5202 : static ulong
5203 : fd_quic_handle_stream_a_frame(
5204 : fd_quic_frame_ctx_t * context,
5205 : fd_quic_stream_a_frame_t * data,
5206 : uchar const * p,
5207 132443129 : ulong p_sz ) {
5208 132443129 : return fd_quic_handle_stream_frame( context, p, p_sz, data->stream_id, 0UL, data->length, data->type&1 );
5209 132443129 : }
5210 :
5211 : static ulong
5212 : fd_quic_handle_stream_c_frame(
5213 : fd_quic_frame_ctx_t * context,
5214 : fd_quic_stream_c_frame_t * data,
5215 : uchar const * p,
5216 0 : ulong p_sz ) {
5217 0 : return fd_quic_handle_stream_frame( context, p, p_sz, data->stream_id, data->offset, p_sz, data->type&1 );
5218 0 : }
5219 :
5220 : static ulong
5221 : fd_quic_handle_stream_e_frame(
5222 : fd_quic_frame_ctx_t * context,
5223 : fd_quic_stream_e_frame_t * data,
5224 : uchar const * p,
5225 16881 : ulong p_sz ) {
5226 16881 : return fd_quic_handle_stream_frame( context, p, p_sz, data->stream_id, data->offset, data->length, data->type&1 );
5227 16881 : }
5228 :
5229 : static ulong
5230 : fd_quic_handle_max_data_frame(
5231 : fd_quic_frame_ctx_t * context,
5232 : fd_quic_max_data_frame_t * data,
5233 : uchar const * p FD_PARAM_UNUSED,
5234 6 : ulong p_sz FD_PARAM_UNUSED ) {
5235 6 : fd_quic_conn_t * conn = context->conn;
5236 :
5237 6 : ulong max_data_old = conn->tx_max_data;
5238 6 : ulong max_data_new = data->max_data;
5239 6 : FD_DTRACE_PROBE_3( quic_handle_max_data_frame, conn->our_conn_id, max_data_new, max_data_old );
5240 :
5241 : /* max data is only allowed to increase the limit. Transgressing frames
5242 : are silently ignored */
5243 6 : conn->tx_max_data = fd_ulong_max( max_data_old, max_data_new );
5244 6 : return 0; /* no additional bytes consumed from buffer */
5245 6 : }
5246 :
5247 : static ulong
5248 : fd_quic_handle_max_stream_data_frame(
5249 : fd_quic_frame_ctx_t * context,
5250 : fd_quic_max_stream_data_frame_t * data,
5251 : uchar const * p FD_PARAM_UNUSED,
5252 0 : ulong p_sz FD_PARAM_UNUSED ) {
5253 : /* FIXME unsupported for now */
5254 0 : FD_DTRACE_PROBE_3( quic_handle_max_stream_data_frame, context->conn->our_conn_id, data->stream_id, data->max_stream_data );
5255 0 : return 0;
5256 0 : }
5257 :
5258 : static ulong
5259 : fd_quic_handle_max_streams_frame(
5260 : fd_quic_frame_ctx_t * context,
5261 : fd_quic_max_streams_frame_t * data,
5262 : uchar const * p FD_PARAM_UNUSED,
5263 9 : ulong p_sz FD_PARAM_UNUSED ) {
5264 9 : fd_quic_conn_t * conn = context->conn;
5265 9 : FD_DTRACE_PROBE_3( quic_handle_max_streams_frame, conn->our_conn_id, data->type, data->max_streams );
5266 :
5267 9 : if( data->type == 0x13 ) {
5268 : /* Only handle unidirectional streams */
5269 6 : ulong type = (ulong)conn->server | 2UL;
5270 : /* Receipt of a frame that permits opening of a stream larger than this limit (2^60)
5271 : MUST be treated as a connection error of type FRAME_ENCODING_ERROR. */
5272 6 : if( FD_UNLIKELY( data->max_streams > FD_QUIC_STREAM_COUNT_MAX ) ) {
5273 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
5274 0 : return FD_QUIC_PARSE_FAIL;
5275 0 : }
5276 6 : ulong peer_sup_stream_id = data->max_streams * 4UL + type;
5277 6 : conn->tx_sup_stream_id = fd_ulong_max( peer_sup_stream_id, conn->tx_sup_stream_id );
5278 6 : }
5279 :
5280 9 : return 0;
5281 9 : }
5282 :
5283 : static ulong
5284 : fd_quic_handle_data_blocked_frame(
5285 : fd_quic_frame_ctx_t * context,
5286 : fd_quic_data_blocked_frame_t * data,
5287 : uchar const * p FD_PARAM_UNUSED,
5288 0 : ulong p_sz FD_PARAM_UNUSED ) {
5289 0 : FD_DTRACE_PROBE_2( quic_handle_data_blocked, context->conn->our_conn_id, data->max_data );
5290 :
5291 : /* Since we do not do runtime allocations, we will not attempt
5292 : to find more memory in the case of DATA_BLOCKED. */
5293 0 : return 0;
5294 0 : }
5295 :
5296 : static ulong
5297 : fd_quic_handle_stream_data_blocked_frame(
5298 : fd_quic_frame_ctx_t * context,
5299 : fd_quic_stream_data_blocked_frame_t * data,
5300 : uchar const * p FD_PARAM_UNUSED,
5301 0 : ulong p_sz FD_PARAM_UNUSED ) {
5302 0 : FD_DTRACE_PROBE_3( quic_handle_stream_data_blocked, context->conn->our_conn_id, data->stream_id, data->max_stream_data );
5303 :
5304 : /* Since we do not do runtime allocations, we will not attempt
5305 : to find more memory in the case of STREAM_DATA_BLOCKED.*/
5306 0 : (void)data;
5307 0 : return 0;
5308 0 : }
5309 :
5310 : static ulong
5311 : fd_quic_handle_streams_blocked_frame(
5312 : fd_quic_frame_ctx_t * context,
5313 : fd_quic_streams_blocked_frame_t * data,
5314 : uchar const * p FD_PARAM_UNUSED,
5315 0 : ulong p_sz FD_PARAM_UNUSED ) {
5316 0 : FD_DTRACE_PROBE_2( quic_handle_streams_blocked_frame, context->conn->our_conn_id, data->max_streams );
5317 :
5318 : /* STREAMS_BLOCKED should be sent by client when it wants
5319 : to use a new stream, but is unable to due to the max_streams
5320 : value
5321 : We can support this in the future, but as of 2024-Dec, the
5322 : Agave TPU client does not currently use it */
5323 0 : return 0;
5324 0 : }
5325 :
5326 : static ulong
5327 : fd_quic_handle_new_conn_id_frame(
5328 : fd_quic_frame_ctx_t * context,
5329 : fd_quic_new_conn_id_frame_t * data,
5330 : uchar const * p FD_PARAM_UNUSED,
5331 0 : ulong p_sz FD_PARAM_UNUSED ) {
5332 : /* FIXME This is a mandatory feature but we don't support it yet */
5333 0 : FD_DTRACE_PROBE_1( quic_handle_new_conn_id_frame, context->conn->our_conn_id );
5334 0 : (void)data;
5335 0 : return 0;
5336 0 : }
5337 :
5338 : static ulong
5339 : fd_quic_handle_retire_conn_id_frame(
5340 : fd_quic_frame_ctx_t * context,
5341 : fd_quic_retire_conn_id_frame_t * data,
5342 : uchar const * p FD_PARAM_UNUSED,
5343 0 : ulong p_sz FD_PARAM_UNUSED ) {
5344 : /* FIXME This is a mandatory feature but we don't support it yet */
5345 0 : FD_DTRACE_PROBE_1( quic_handle_retire_conn_id_frame, context->conn->our_conn_id );
5346 0 : (void)data;
5347 0 : FD_DEBUG( FD_LOG_DEBUG(( "retire_conn_id requested" )); )
5348 0 : return 0;
5349 0 : }
5350 :
5351 : static ulong
5352 : fd_quic_handle_path_challenge_frame(
5353 : fd_quic_frame_ctx_t * context,
5354 : fd_quic_path_challenge_frame_t * data,
5355 : uchar const * p FD_PARAM_UNUSED,
5356 0 : ulong p_sz FD_PARAM_UNUSED ) {
5357 : /* FIXME The recipient of this frame MUST generate a PATH_RESPONSE frame (Section 19.18) containing the same Data value. */
5358 0 : FD_DTRACE_PROBE_1( quic_handle_path_challenge_frame, context->conn->our_conn_id );
5359 0 : (void)data;
5360 0 : return 0UL;
5361 0 : }
5362 :
5363 : static ulong
5364 : fd_quic_handle_path_response_frame(
5365 : fd_quic_frame_ctx_t * context,
5366 : fd_quic_path_response_frame_t * data,
5367 : uchar const * p FD_PARAM_UNUSED,
5368 0 : ulong p_sz FD_PARAM_UNUSED ) {
5369 : /* We don't generate PATH_CHALLENGE frames, so this frame should never arrive */
5370 0 : FD_DTRACE_PROBE_1( quic_handle_path_response_frame, context->conn->our_conn_id );
5371 0 : (void)data;
5372 0 : return 0UL;
5373 0 : }
5374 :
5375 : static void
5376 6012 : fd_quic_handle_conn_close_frame( fd_quic_conn_t * conn ) {
5377 : /* frame type 0x1c means no error, or only error at quic level
5378 : frame type 0x1d means error at application layer
5379 : TODO provide APP with this info */
5380 6012 : FD_DEBUG( FD_LOG_DEBUG(( "peer requested close" )) );
5381 :
5382 6012 : switch( conn->state ) {
5383 0 : case FD_QUIC_CONN_STATE_PEER_CLOSE:
5384 0 : case FD_QUIC_CONN_STATE_ABORT:
5385 9 : case FD_QUIC_CONN_STATE_CLOSE_PENDING:
5386 9 : return;
5387 :
5388 6003 : default:
5389 6003 : fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_PEER_CLOSE );
5390 6012 : }
5391 :
5392 6003 : conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
5393 6003 : fd_quic_svc_prep_schedule_now( conn );
5394 6003 : }
5395 :
5396 : static ulong
5397 : fd_quic_handle_conn_close_0_frame(
5398 : fd_quic_frame_ctx_t * context,
5399 : fd_quic_conn_close_0_frame_t * data,
5400 : uchar const * p,
5401 0 : ulong p_sz ) {
5402 0 : (void)p;
5403 :
5404 0 : ulong reason_phrase_length = data->reason_phrase_length;
5405 0 : if( FD_UNLIKELY( reason_phrase_length > p_sz ) ) {
5406 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
5407 0 : return FD_QUIC_PARSE_FAIL;
5408 0 : }
5409 :
5410 : /* the information here can be invaluable for debugging */
5411 0 : FD_DEBUG(
5412 0 : char reason_buf[256] = {0};
5413 0 : ulong reason_len = fd_ulong_min( sizeof(reason_buf)-1, reason_phrase_length );
5414 0 : memcpy( reason_buf, p, reason_len );
5415 :
5416 0 : FD_LOG_WARNING(( "fd_quic_handle_conn_close_frame - "
5417 0 : "error_code: %lu "
5418 0 : "frame_type: %lx "
5419 0 : "reason: %s "
5420 0 : "peer " FD_IP4_ADDR_FMT ":%u "
5421 0 : "conn_id %lu",
5422 0 : data->error_code,
5423 0 : data->frame_type,
5424 0 : reason_buf,
5425 0 : FD_IP4_ADDR_FMT_ARGS(context->conn->peer->ip_addr),
5426 0 : context->conn->peer->udp_port,
5427 0 : context->conn->our_conn_id ));
5428 0 : );
5429 :
5430 0 : fd_quic_handle_conn_close_frame( context->conn );
5431 :
5432 0 : return reason_phrase_length;
5433 0 : }
5434 :
5435 : static ulong
5436 : fd_quic_handle_conn_close_1_frame(
5437 : fd_quic_frame_ctx_t * context,
5438 : fd_quic_conn_close_1_frame_t * data,
5439 : uchar const * p,
5440 6012 : ulong p_sz ) {
5441 6012 : (void)p;
5442 :
5443 6012 : ulong reason_phrase_length = data->reason_phrase_length;
5444 6012 : if( FD_UNLIKELY( reason_phrase_length > p_sz ) ) {
5445 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
5446 0 : return FD_QUIC_PARSE_FAIL;
5447 0 : }
5448 :
5449 : /* the information here can be invaluable for debugging */
5450 6012 : FD_DEBUG(
5451 6012 : char reason_buf[256] = {0};
5452 6012 : ulong reason_len = fd_ulong_min( sizeof(reason_buf)-1, reason_phrase_length );
5453 6012 : memcpy( reason_buf, p, reason_len );
5454 :
5455 6012 : FD_LOG_WARNING(( "fd_quic_handle_conn_close_frame - "
5456 6012 : "error_code: %lu "
5457 6012 : "reason: %s "
5458 6012 : "peer " FD_IP4_ADDR_FMT ":%u "
5459 6012 : "conn_id %lu",
5460 6012 : data->error_code,
5461 6012 : reason_buf,
5462 6012 : FD_IP4_ADDR_FMT_ARGS(context->conn->peer->ip_addr),
5463 6012 : context->conn->peer->udp_port,
5464 6012 : context->conn->our_conn_id ));
5465 6012 : );
5466 :
5467 6012 : fd_quic_handle_conn_close_frame( context->conn );
5468 :
5469 6012 : return reason_phrase_length;
5470 6012 : }
5471 :
5472 : static ulong
5473 : fd_quic_handle_handshake_done_frame(
5474 : fd_quic_frame_ctx_t * context,
5475 : fd_quic_handshake_done_frame_t * data,
5476 : uchar const * p FD_PARAM_UNUSED,
5477 6069 : ulong p_sz FD_PARAM_UNUSED ) {
5478 6069 : fd_quic_conn_t * conn = context->conn;
5479 6069 : (void)data;
5480 :
5481 : /* servers must treat receipt of HANDSHAKE_DONE as a protocol violation */
5482 6069 : if( FD_UNLIKELY( conn->server ) ) {
5483 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
5484 0 : return FD_QUIC_PARSE_FAIL;
5485 0 : }
5486 :
5487 6069 : if( conn->state == FD_QUIC_CONN_STATE_HANDSHAKE ) {
5488 : /* still handshaking... assume packet was reordered */
5489 0 : context->pkt->ack_flag |= ACK_FLAG_CANCEL;
5490 0 : return 0UL;
5491 6069 : } else if( conn->state != FD_QUIC_CONN_STATE_HANDSHAKE_COMPLETE ) {
5492 : /* duplicate frame or conn closing? */
5493 0 : return 0UL;
5494 0 : }
5495 :
5496 : /* Instantly acknowledge the first HANDSHAKE_DONE frame */
5497 6069 : fd_quic_svc_prep_schedule_now( conn );
5498 :
5499 : /* RFC 9001 4.9.2. Discarding Handshake Keys
5500 : > An endpoint MUST discard its Handshake keys when the
5501 : > TLS handshake is confirmed
5502 : RFC 9001 4.1.2. Handshake Confirmed
5503 : > At the client, the handshake is considered confirmed when a
5504 : > HANDSHAKE_DONE frame is received. */
5505 6069 : fd_quic_abandon_enc_level( conn, fd_quic_enc_level_handshake_id );
5506 :
5507 6069 : if( FD_UNLIKELY( !conn->tls_hs ) ) {
5508 : /* sanity check */
5509 0 : return 0;
5510 0 : }
5511 :
5512 : /* eliminate any remaining hs_data at application level */
5513 6069 : fd_quic_tls_clear_hs_data( conn->tls_hs, fd_quic_enc_level_appdata_id );
5514 :
5515 : /* we shouldn't be receiving this unless handshake is complete */
5516 6069 : fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_ACTIVE );
5517 :
5518 : /* user callback */
5519 6069 : fd_quic_cb_conn_hs_complete( conn->quic, conn );
5520 :
5521 : /* Deallocate tls_hs once completed */
5522 6069 : if( FD_LIKELY( conn->tls_hs ) ) {
5523 6069 : fd_quic_state_t * state = fd_quic_get_state( conn->quic );
5524 6069 : fd_quic_tls_hs_delete( conn->tls_hs );
5525 6069 : fd_quic_tls_hs_cache_ele_remove( &state->hs_cache, conn->tls_hs, state->hs_pool );
5526 6069 : fd_quic_tls_hs_pool_ele_release( state->hs_pool, conn->tls_hs );
5527 6069 : conn->tls_hs = NULL;
5528 6069 : }
5529 :
5530 6069 : return 0;
5531 6069 : }
5532 :
5533 : static ulong
5534 : fd_quic_handle_datagram( fd_quic_frame_ctx_t * context,
5535 : uchar const * data,
5536 : ulong data_sz,
5537 12 : ulong header_sz ) {
5538 12 : fd_quic_t * quic = context->quic;
5539 12 : ulong max_frame_sz = quic->config.max_datagram_frame_size;
5540 12 : if( FD_UNLIKELY( !max_frame_sz || !quic->cb.datagram_rx ) ) {
5541 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
5542 0 : return FD_QUIC_PARSE_FAIL;
5543 0 : }
5544 12 : if( FD_UNLIKELY( header_sz+data_sz > max_frame_sz ) ) {
5545 3 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
5546 3 : return FD_QUIC_PARSE_FAIL;
5547 3 : }
5548 9 : quic->cb.datagram_rx( context->conn, data, data_sz, quic->cb.quic_ctx );
5549 9 : return data_sz;
5550 12 : }
5551 :
5552 : static ulong
5553 : fd_quic_handle_datagram_0_frame(
5554 : fd_quic_frame_ctx_t * context,
5555 : fd_quic_datagram_0_frame_t * frame FD_PARAM_UNUSED,
5556 : uchar const * p,
5557 3 : ulong p_sz ) {
5558 3 : return fd_quic_handle_datagram( context, p, p_sz, context->frame_sz );
5559 3 : }
5560 :
5561 : static ulong
5562 : fd_quic_handle_datagram_1_frame(
5563 : fd_quic_frame_ctx_t * context,
5564 : fd_quic_datagram_1_frame_t * frame,
5565 : uchar const * p,
5566 9 : ulong p_sz ) {
5567 9 : if( FD_UNLIKELY( frame->length>p_sz ) ) {
5568 0 : fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
5569 0 : return FD_QUIC_PARSE_FAIL;
5570 0 : }
5571 9 : return fd_quic_handle_datagram( context, p, frame->length, context->frame_sz );
5572 9 : }
5573 :
5574 : /* initiate the shutdown of a connection
5575 : may select a reason code */
5576 : void
5577 : fd_quic_conn_close( fd_quic_conn_t * conn,
5578 6030 : uint app_reason ) {
5579 6030 : if( FD_UNLIKELY( !conn ) ) return;
5580 :
5581 6030 : switch( conn->state ) {
5582 6 : case FD_QUIC_CONN_STATE_INVALID:
5583 6 : case FD_QUIC_CONN_STATE_DEAD:
5584 6 : case FD_QUIC_CONN_STATE_ABORT:
5585 6 : return; /* close has no effect in these states */
5586 :
5587 6024 : default:
5588 6024 : {
5589 6024 : fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_CLOSE_PENDING );
5590 6024 : conn->app_reason = app_reason;
5591 6024 : }
5592 6030 : }
5593 :
5594 : /* set connection to be serviced ASAP */
5595 6024 : fd_quic_svc_prep_schedule_now( conn );
5596 6024 : fd_quic_svc_schedule1( conn );
5597 6024 : }
5598 :
5599 : void
5600 : fd_quic_conn_let_die( fd_quic_conn_t * conn,
5601 : long keep_alive_duration,
5602 3 : long now ) {
5603 3 : fd_quic_get_state( conn->quic )->now = now;
5604 3 : conn->let_die_time_ns = fd_long_sat_add( now, keep_alive_duration );
5605 : /* If we've missed the keep-alive time, schedule for immediate servicing */
5606 3 : if( FD_UNLIKELY( conn->last_activity+conn->idle_timeout_ns/2L < now ) ) {
5607 0 : fd_quic_svc_prep_schedule( conn, now );
5608 0 : fd_quic_svc_schedule1( conn );
5609 0 : }
5610 3 : }
|