LCOV - code coverage report
Current view: top level - waltz/quic - fd_quic.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 2563 3227 79.4 %
Date: 2026-11-15 04:25:17 Functions: 104 119 87.4 %

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

Generated by: LCOV version 1.14