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

Generated by: LCOV version 1.14