LCOV - code coverage report
Current view: top level - waltz/quic - fd_quic.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 0 3151 0.0 %
Date: 2026-03-19 18:19:27 Functions: 0 113 0.0 %

          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           0 : #define MAP_KEY               stream_id
      40           0 : #define MAP_T                 fd_quic_stream_map_t
      41           0 : #define MAP_KEY_NULL          FD_QUIC_STREAM_ID_UNUSED
      42           0 : #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           0 : # define FD_QUIC_MAX_STREAMS_ALWAYS_UNLESS_ACKED 0
      55             : 
      56             : /* Construction API ***************************************************/
      57             : 
      58             : FD_QUIC_API FD_FN_CONST ulong
      59           0 : fd_quic_align( void ) {
      60           0 :   return FD_QUIC_ALIGN;
      61           0 : }
      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           0 :                        fd_quic_layout_t *       layout ) {
      68           0 :   memset( layout, 0, sizeof(fd_quic_layout_t) );
      69           0 :   if( FD_UNLIKELY( !limits ) ) return 0UL;
      70             : 
      71           0 :   ulong  conn_cnt           = limits->conn_cnt;
      72           0 :   ulong  conn_id_cnt        = limits->conn_id_cnt;
      73           0 :   ulong  log_depth          = limits->log_depth;
      74           0 :   ulong  handshake_cnt      = limits->handshake_cnt;
      75           0 :   ulong  inflight_frame_cnt = limits->inflight_frame_cnt;
      76           0 :   ulong  tx_buf_sz          = limits->tx_buf_sz;
      77           0 :   ulong  stream_pool_cnt    = limits->stream_pool_cnt;
      78           0 :   ulong  inflight_res_cnt   = limits->min_inflight_frame_cnt_conn * conn_cnt;
      79           0 :   if( FD_UNLIKELY( conn_cnt          ==0UL ) ) return 0UL;
      80           0 :   if( FD_UNLIKELY( handshake_cnt     ==0UL ) ) return 0UL;
      81           0 :   if( FD_UNLIKELY( inflight_frame_cnt==0UL ) ) return 0UL;
      82             : 
      83           0 :   if( FD_UNLIKELY( inflight_res_cnt > inflight_frame_cnt ) ) return 0UL;
      84             : 
      85           0 :   if( FD_UNLIKELY( conn_id_cnt < FD_QUIC_MIN_CONN_ID_CNT ))
      86           0 :     return 0UL;
      87             : 
      88           0 :   layout->meta_sz = sizeof(fd_quic_layout_t);
      89             : 
      90           0 :   ulong offs  = 0;
      91             : 
      92             :   /* allocate space for fd_quic_t */
      93           0 :   offs += sizeof(fd_quic_t);
      94             : 
      95             :   /* allocate space for state */
      96           0 :   offs  = fd_ulong_align_up( offs, alignof(fd_quic_state_t) );
      97           0 :   offs += sizeof(fd_quic_state_t);
      98             : 
      99             :   /* allocate space for connections */
     100           0 :   offs                    = fd_ulong_align_up( offs, fd_quic_conn_align() );
     101           0 :   layout->conns_off       = offs;
     102           0 :   ulong conn_footprint    = fd_quic_conn_footprint( limits );
     103           0 :   if( FD_UNLIKELY( !conn_footprint ) ) { FD_LOG_WARNING(( "invalid fd_quic_conn_footprint" )); return 0UL; }
     104           0 :   layout->conn_footprint  = conn_footprint;
     105           0 :   ulong conn_foot_tot     = conn_cnt * conn_footprint;
     106           0 :   offs                   += conn_foot_tot;
     107             : 
     108             :   /* allocate space for conn IDs */
     109           0 :   offs                     = fd_ulong_align_up( offs, fd_quic_conn_map_align() );
     110           0 :   layout->conn_map_off     = offs;
     111           0 :   ulong slot_cnt_bound     = (ulong)( FD_QUIC_DEFAULT_SPARSITY * (double)conn_cnt * (double)conn_id_cnt );
     112           0 :   int     lg_slot_cnt      = fd_ulong_find_msb( slot_cnt_bound - 1 ) + 1;
     113           0 :   layout->lg_slot_cnt      = lg_slot_cnt;
     114           0 :   ulong conn_map_footprint = fd_quic_conn_map_footprint( lg_slot_cnt );
     115           0 :   if( FD_UNLIKELY( !conn_map_footprint ) ) { FD_LOG_WARNING(( "invalid fd_quic_conn_map_footprint" )); return 0UL; }
     116           0 :   offs                    += conn_map_footprint;
     117             : 
     118             :   /* allocate space for handshake pool */
     119           0 :   offs                 = fd_ulong_align_up( offs, fd_quic_tls_hs_pool_align() );
     120           0 :   layout->hs_pool_off  = offs;
     121           0 :   ulong hs_pool_fp     = fd_quic_tls_hs_pool_footprint( limits->handshake_cnt );
     122           0 :   if( FD_UNLIKELY( !hs_pool_fp ) ) { FD_LOG_WARNING(( "invalid fd_quic_tls_hs_pool_footprint" )); return 0UL; }
     123           0 :   offs                += hs_pool_fp;
     124             : 
     125             :   /* allocate space for stream pool */
     126           0 :   if( stream_pool_cnt && tx_buf_sz ) {
     127           0 :     offs                    = fd_ulong_align_up( offs, fd_quic_stream_pool_align() );
     128           0 :     layout->stream_pool_off = offs;
     129           0 :     ulong stream_pool_footprint = fd_quic_stream_pool_footprint( stream_pool_cnt, tx_buf_sz );
     130           0 :     if( FD_UNLIKELY( !stream_pool_footprint ) ) { FD_LOG_WARNING(( "invalid fd_quic_stream_pool_footprint" )); return 0UL; }
     131           0 :     offs                   += stream_pool_footprint;
     132           0 :   } else {
     133           0 :     layout->stream_pool_off = 0UL;
     134           0 :   }
     135             : 
     136             :   /* allocate space for pkt_meta_pool */
     137           0 :   if( inflight_frame_cnt ) {
     138           0 :     offs                      = fd_ulong_align_up( offs, fd_quic_pkt_meta_pool_align() );
     139           0 :     layout->pkt_meta_pool_off = offs;
     140           0 :     ulong pkt_meta_footprint  = fd_quic_pkt_meta_pool_footprint( inflight_frame_cnt );
     141           0 :     if( FD_UNLIKELY( !pkt_meta_footprint ) ) { FD_LOG_WARNING(( "invalid fd_quic_pkt_meta_pool_footprint" )); return 0UL; }
     142           0 :     offs += pkt_meta_footprint;
     143           0 :   } else {
     144           0 :     layout->pkt_meta_pool_off = 0UL;
     145           0 :   }
     146             : 
     147             :   /* allocate space for quic_log_buf */
     148           0 :   offs = fd_ulong_align_up( offs, fd_quic_log_buf_align() );
     149           0 :   layout->log_off = offs;
     150           0 :   ulong log_footprint = fd_quic_log_buf_footprint( log_depth );
     151           0 :   if( FD_UNLIKELY( !log_footprint ) ) { FD_LOG_WARNING(( "invalid fd_quic_log_buf_footprint for depth %lu", log_depth )); return 0UL; }
     152           0 :   offs += log_footprint;
     153             : 
     154             :   /* allocate space for service timers */
     155           0 :   offs                       = fd_ulong_align_up( offs, fd_quic_svc_timers_align() );
     156           0 :   layout->svc_timers_off     = offs;
     157           0 :   ulong svc_timers_footprint = fd_quic_svc_timers_footprint( limits->conn_cnt );
     158           0 :   if( FD_UNLIKELY( !svc_timers_footprint ) ) { FD_LOG_WARNING(( "invalid fd_quic_svc_timers_footprint" )); return 0UL; }
     159           0 :   offs                       += svc_timers_footprint;
     160             : 
     161           0 :   return offs;
     162           0 : }
     163             : 
     164             : FD_QUIC_API ulong
     165           0 : fd_quic_footprint( fd_quic_limits_t const * limits ) {
     166           0 :   fd_quic_layout_t layout;
     167           0 :   return fd_quic_footprint_ext( limits, &layout );
     168           0 : }
     169             : 
     170             : FD_QUIC_API void *
     171             : fd_quic_new( void * mem,
     172           0 :              fd_quic_limits_t const * limits ) {
     173             : 
     174             :   /* Argument checks */
     175             : 
     176           0 :   if( FD_UNLIKELY( !mem ) ) {
     177           0 :     FD_LOG_WARNING(( "NULL mem" ));
     178           0 :     return NULL;
     179           0 :   }
     180             : 
     181           0 :   ulong align = fd_quic_align();
     182           0 :   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           0 :   if( FD_UNLIKELY( !limits ) ) {
     188           0 :     FD_LOG_WARNING(( "NULL limits" ));
     189           0 :     return NULL;
     190           0 :   }
     191             : 
     192           0 :   if( FD_UNLIKELY( ( limits->conn_cnt          ==0UL )
     193           0 :                  | ( limits->conn_cnt          >=UINT_MAX )
     194           0 :                  | ( limits->handshake_cnt     ==0UL )
     195           0 :                  | ( limits->inflight_frame_cnt==0UL ) ) ) {
     196           0 :     FD_LOG_WARNING(( "invalid limits" ));
     197           0 :     return NULL;
     198           0 :   }
     199             : 
     200           0 :   fd_quic_layout_t layout;
     201           0 :   ulong footprint = fd_quic_footprint_ext( limits, &layout );
     202           0 :   if( FD_UNLIKELY( !footprint ) ) {
     203           0 :     FD_LOG_WARNING(( "invalid footprint for config" ));
     204           0 :     return NULL;
     205           0 :   }
     206             : 
     207           0 :   fd_quic_t * quic = (fd_quic_t *)mem;
     208             : 
     209             :   /* Clear fd_quic_t memory region */
     210           0 :   fd_memset( quic, 0, footprint );
     211             : 
     212             :   /* Defaults */
     213           0 :   quic->config.idle_timeout = FD_QUIC_DEFAULT_IDLE_TIMEOUT;
     214           0 :   quic->config.ack_delay    = FD_QUIC_DEFAULT_ACK_DELAY;
     215           0 :   quic->config.retry_ttl    = FD_QUIC_DEFAULT_RETRY_TTL;
     216           0 :   quic->config.tls_hs_ttl   = FD_QUIC_DEFAULT_TLS_HS_TTL;
     217             : 
     218             :   /* Copy layout descriptors */
     219           0 :   quic->limits = *limits;
     220           0 :   quic->layout = layout;
     221             : 
     222             :   /* Init log buffer (persists across init calls) */
     223           0 :   void * shmlog = (void *)( (ulong)quic + quic->layout.log_off );
     224           0 :   if( FD_UNLIKELY( !fd_quic_log_buf_new( shmlog, limits->log_depth ) ) ) {
     225           0 :     return NULL;
     226           0 :   }
     227             : 
     228           0 :   FD_COMPILER_MFENCE();
     229           0 :   quic->magic = FD_QUIC_MAGIC;
     230           0 :   FD_COMPILER_MFENCE();
     231             : 
     232           0 :   return quic;
     233           0 : }
     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           0 : fd_quic_get_aio_net_rx( fd_quic_t * quic ) {
     284           0 :   fd_aio_new( &quic->aio_rx, quic, fd_quic_aio_cb_receive );
     285           0 :   return &quic->aio_rx;
     286           0 : }
     287             : 
     288             : FD_QUIC_API void
     289             : fd_quic_set_aio_net_tx( fd_quic_t *      quic,
     290           0 :                         fd_aio_t const * aio_tx ) {
     291             : 
     292           0 :   if( aio_tx ) {
     293           0 :     quic->aio_tx = *aio_tx;
     294           0 :   } else {
     295           0 :     memset( &quic->aio_tx, 0, sizeof(fd_aio_t) );
     296           0 :   }
     297           0 : }
     298             : 
     299             : /* initialize everything that mutates during runtime */
     300             : static void
     301           0 : fd_quic_stream_init( fd_quic_stream_t * stream ) {
     302           0 :   stream->context            = NULL;
     303             : 
     304           0 :   stream->unacked_low        = 0;
     305           0 :   stream->tx_buf.head        = 0;
     306           0 :   stream->tx_sent            = 0;
     307             : 
     308           0 :   stream->stream_flags       = 0;
     309             :   /* don't update next here, since it's still in use */
     310             : 
     311           0 :   stream->state              = 0;
     312             : 
     313           0 :   stream->tx_max_stream_data = 0;
     314           0 :   stream->tx_tot_data        = 0;
     315             : 
     316           0 :   stream->rx_tot_data        = 0;
     317             : 
     318           0 :   stream->upd_pkt_number     = 0;
     319           0 : }
     320             : 
     321             : FD_QUIC_API fd_quic_t *
     322           0 : fd_quic_join( void * shquic ) {
     323             : 
     324           0 :   if( FD_UNLIKELY( !shquic ) ) {
     325           0 :     FD_LOG_WARNING(( "null shquic" ));
     326           0 :     return NULL;
     327           0 :   }
     328           0 :   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           0 :   fd_quic_t * quic = (fd_quic_t *)shquic;
     334           0 :   if( FD_UNLIKELY( quic->magic != FD_QUIC_MAGIC ) ) {
     335           0 :     FD_LOG_WARNING(( "bad magic" ));
     336           0 :     return NULL;
     337           0 :   }
     338             : 
     339           0 :   return quic;
     340           0 : }
     341             : 
     342             : FD_QUIC_API void *
     343           0 : fd_quic_leave( fd_quic_t * quic ) {
     344           0 :   return (void *)quic;
     345           0 : }
     346             : 
     347             : FD_QUIC_API fd_quic_t *
     348           0 : fd_quic_init( fd_quic_t * quic ) {
     349             : 
     350           0 :   fd_quic_limits_t const * limits = &quic->limits;
     351           0 :   fd_quic_config_t       * config = &quic->config;
     352             : 
     353           0 :   if( FD_UNLIKELY( !config->role          ) ) { FD_LOG_WARNING(( "cfg.role not set"      )); return NULL; }
     354           0 :   if( FD_UNLIKELY( !config->idle_timeout  ) ) { FD_LOG_WARNING(( "zero cfg.idle_timeout" )); return NULL; }
     355           0 :   if( FD_UNLIKELY( !config->ack_delay     ) ) { FD_LOG_WARNING(( "zero cfg.ack_delay"    )); return NULL; }
     356           0 :   if( FD_UNLIKELY( !config->retry_ttl     ) ) { FD_LOG_WARNING(( "zero cfg.retry_ttl"    )); return NULL; }
     357             : 
     358           0 :   do {
     359           0 :     ulong x = 0U;
     360           0 :     for( ulong i=0UL; i<32UL; i++ ) x |= quic->config.identity_public_key[i];
     361             : 
     362           0 :     if( FD_UNLIKELY( !x ) ) {
     363           0 :       FD_LOG_WARNING(( "cfg.identity_public_key not set" ));
     364           0 :       return NULL;
     365           0 :     }
     366           0 :   } while(0);
     367             : 
     368           0 :   switch( config->role ) {
     369           0 :   case FD_QUIC_ROLE_SERVER:
     370           0 :     if( FD_UNLIKELY( config->keep_alive ) ) { FD_LOG_WARNING(( "server keep-alive not supported" )); return NULL; }
     371           0 :     break;
     372           0 :   case FD_QUIC_ROLE_CLIENT:
     373           0 :     break;
     374           0 :   default:
     375           0 :     FD_LOG_WARNING(( "invalid cfg.role" ));
     376           0 :     return NULL;
     377           0 :   }
     378             : 
     379           0 :   if( FD_UNLIKELY( !config->ack_threshold ) ) {
     380           0 :     config->ack_threshold = FD_QUIC_DEFAULT_ACK_THRESHOLD;
     381           0 :   }
     382             : 
     383           0 :   fd_quic_layout_t layout = {0};
     384           0 :   if( FD_UNLIKELY( !fd_quic_footprint_ext( &quic->limits, &layout ) ) ) {
     385           0 :     FD_LOG_CRIT(( "fd_quic_footprint_ext failed" ));
     386           0 :   }
     387           0 :   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           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
     396           0 :   memset( state, 0, sizeof(fd_quic_state_t) );
     397             : 
     398           0 :   void * shmlog = (void *)( (ulong)quic + layout.log_off );
     399           0 :   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           0 :   if( layout.pkt_meta_pool_off ) {
     405           0 :     ulong pkt_meta_cnt                 = limits->inflight_frame_cnt;
     406           0 :     ulong pkt_meta_laddr               = (ulong)quic + layout.pkt_meta_pool_off;
     407           0 :     fd_quic_pkt_meta_t * pkt_meta_pool = fd_quic_pkt_meta_pool_new( (void*)pkt_meta_laddr, pkt_meta_cnt );
     408           0 :     state->pkt_meta_pool               = fd_quic_pkt_meta_pool_join( pkt_meta_pool );
     409           0 :     fd_quic_pkt_meta_ds_init_pool( pkt_meta_pool, pkt_meta_cnt );
     410           0 :   }
     411             : 
     412             :   /* State: initialize each connection, and add to free list */
     413             : 
     414           0 :   ulong conn_laddr = (ulong)quic + layout.conns_off;
     415             : 
     416             :   /* used for indexing */
     417           0 :   state->conn_base = conn_laddr;
     418           0 :   state->conn_sz   = layout.conn_footprint;
     419             : 
     420             :   /* initialize free_conns */
     421           0 :   state->free_conn_list = 0;
     422             : 
     423           0 :   fd_quic_conn_t   _catch[1] = {{.conn_idx = UINT_MAX }};
     424           0 :   fd_quic_conn_t * last      = _catch;
     425           0 :   for( ulong j = 0; j < limits->conn_cnt; ++j ) {
     426           0 :     void * conn_mem  = (void *)( conn_laddr );
     427           0 :     conn_laddr      += layout.conn_footprint;
     428             : 
     429           0 :     fd_quic_conn_t * conn = fd_quic_conn_new( conn_mem, quic, limits );
     430           0 :     if( FD_UNLIKELY( !conn ) ) {
     431           0 :       FD_LOG_WARNING(( "NULL conn" ));
     432           0 :       return NULL;
     433           0 :     }
     434             : 
     435             :     /* used for indexing */
     436           0 :     conn->conn_idx  = (uint)j;
     437           0 :     conn->free_conn_next = UINT_MAX;
     438             : 
     439             :     /* add to free list */
     440           0 :     last->free_conn_next = (uint)j;
     441             : 
     442           0 :     last = conn;
     443           0 :   }
     444             : 
     445             :   /* State: Initialize conn ID map */
     446             : 
     447           0 :   ulong  conn_map_laddr = (ulong)quic + layout.conn_map_off;
     448           0 :   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           0 :   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           0 :   ulong svc_base    = (ulong)quic + layout.svc_timers_off;
     456           0 :   state->svc_timers = fd_quic_svc_timers_init( (void *)svc_base, limits->conn_cnt, state );
     457             : 
     458             :   /* Check TX AIO */
     459             : 
     460           0 :   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           0 :   fd_quic_tls_cfg_t tls_cfg = {
     468           0 :     .max_concur_handshakes = limits->handshake_cnt,
     469             : 
     470             :     /* set up callbacks */
     471           0 :     .secret_cb             = fd_quic_tls_cb_secret,
     472           0 :     .handshake_complete_cb = fd_quic_tls_cb_handshake_complete,
     473           0 :     .peer_params_cb        = fd_quic_tls_cb_peer_params,
     474             : 
     475           0 :     .signer = {
     476           0 :       .ctx     = config->sign_ctx,
     477           0 :       .sign_fn = config->sign,
     478           0 :     },
     479             : 
     480           0 :     .cert_public_key       = quic->config.identity_public_key,
     481           0 :   };
     482             : 
     483             :   /* State: Initialize handshake pool */
     484             : 
     485           0 :   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           0 :   ulong  hs_pool_laddr       = (ulong)quic + layout.hs_pool_off;
     491           0 :   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           0 :   if( FD_UNLIKELY( !hs_pool ) ) {
     493           0 :     FD_LOG_WARNING(( "fd_quic_tls_hs_pool_new failed" ));
     494           0 :     return NULL;
     495           0 :   }
     496           0 :   state->hs_pool = hs_pool;
     497             : 
     498             :   /* State: Initialize TLS handshake cache */
     499           0 :   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           0 :   if( layout.stream_pool_off ) {
     506           0 :     ulong stream_pool_cnt = limits->stream_pool_cnt;
     507           0 :     ulong tx_buf_sz       = limits->tx_buf_sz;
     508           0 :     ulong stream_pool_laddr = (ulong)quic + layout.stream_pool_off;
     509           0 :     state->stream_pool = fd_quic_stream_pool_new( (void*)stream_pool_laddr, stream_pool_cnt, tx_buf_sz );
     510           0 :   }
     511             : 
     512             :   /* generate a secure random number as seed for fd_rng */
     513           0 :   uint rng_seed = 0;
     514           0 :   int rng_seed_ok = !!fd_rng_secure( &rng_seed, sizeof(rng_seed) );
     515           0 :   if( FD_UNLIKELY( !rng_seed_ok ) ) {
     516           0 :     FD_LOG_ERR(( "fd_rng_secure failed" ));
     517           0 :   }
     518           0 :   fd_rng_new( state->_rng, rng_seed, 0UL );
     519             : 
     520             :   /* use rng to generate secret bytes for future RETRY token generation */
     521           0 :   int rng1_ok = !!fd_rng_secure( state->retry_secret, FD_QUIC_RETRY_SECRET_SZ );
     522           0 :   int rng2_ok = !!fd_rng_secure( state->retry_iv,     FD_QUIC_RETRY_IV_SZ     );
     523           0 :   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           0 :   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           0 :   ulong initial_max_streams_uni = quic->config.role==FD_QUIC_ROLE_SERVER ? 1UL<<60 : 0;
     536           0 :   ulong initial_max_stream_data = config->initial_rx_max_stream_data;
     537             : 
     538           0 :   long max_ack_delay_ns = config->ack_delay * 2L;
     539           0 :   long max_ack_delay_ms = max_ack_delay_ns / (long)1e6;
     540             : 
     541           0 :   long idle_timeout_ns  = config->idle_timeout;
     542           0 :   long idle_timeout_ms  = idle_timeout_ns / (long)1e6;
     543             : 
     544           0 :   memset( tp, 0, sizeof(fd_quic_transport_params_t) );
     545           0 :   FD_QUIC_TRANSPORT_PARAM_SET( tp, max_idle_timeout_ms,               (ulong)idle_timeout_ms  );
     546           0 :   FD_QUIC_TRANSPORT_PARAM_SET( tp, max_udp_payload_size,              FD_QUIC_MAX_PAYLOAD_SZ  ); /* TODO */
     547           0 :   FD_QUIC_TRANSPORT_PARAM_SET( tp, initial_max_data,                  (1UL<<62)-1UL           );
     548           0 :   FD_QUIC_TRANSPORT_PARAM_SET( tp, initial_max_stream_data_uni,       initial_max_stream_data );
     549           0 :   FD_QUIC_TRANSPORT_PARAM_SET( tp, initial_max_streams_bidi,          0                       );
     550           0 :   FD_QUIC_TRANSPORT_PARAM_SET( tp, initial_max_streams_uni,           initial_max_streams_uni );
     551           0 :   FD_QUIC_TRANSPORT_PARAM_SET( tp, ack_delay_exponent,                0                       );
     552           0 :   FD_QUIC_TRANSPORT_PARAM_SET( tp, max_ack_delay,                     (ulong)max_ack_delay_ms );
     553           0 :   /*                         */tp->disable_active_migration_present = 1;
     554             : 
     555             :   /* Compute max inflight pkt cnt per conn */
     556           0 :   state->max_inflight_frame_cnt_conn = limits->inflight_frame_cnt - limits->min_inflight_frame_cnt_conn * (limits->conn_cnt-1);
     557             : 
     558           0 :   return quic;
     559           0 : }
     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           0 : fd_quic_enc_level_to_pn_space( uint enc_level ) {
     575             :   /* TODO improve this map */
     576           0 :   static uchar const el2pn_map[] = { 0, 2, 1, 2 };
     577             : 
     578           0 :   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           0 :   return el2pn_map[ enc_level ];
     582           0 : }
     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           0 :                              ulong exp_pkt_number ) {
     589           0 :   ulong pn_nbits     = pktnum_sz << 3u;
     590           0 :   ulong pn_win       = 1ul << pn_nbits;
     591           0 :   ulong pn_hwin      = pn_win >> 1ul;
     592           0 :   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           0 :   ulong candidate_pn = ( exp_pkt_number & ~pn_mask ) | pktnum_comp;
     605           0 :   if( candidate_pn + pn_hwin <= exp_pkt_number &&
     606           0 :       candidate_pn + pn_win  < ( 1ul << 62ul ) ) {
     607           0 :     return candidate_pn + pn_win;
     608           0 :   }
     609             : 
     610           0 :   if( candidate_pn >  exp_pkt_number + pn_hwin &&
     611           0 :       candidate_pn >= pn_win ) {
     612           0 :     return candidate_pn - pn_win;
     613           0 :   }
     614             : 
     615           0 :   return candidate_pn;
     616           0 : }
     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           0 :                            long             expiry ) {
     623           0 :   conn->svc_meta.next_timeout = fd_long_min( conn->svc_meta.next_timeout, expiry );
     624           0 : }
     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           0 : fd_quic_svc_prep_schedule_now( fd_quic_conn_t * conn ) {
     630           0 :   fd_quic_state_t * state = fd_quic_get_state( conn->quic );
     631           0 :   fd_quic_svc_prep_schedule( conn, state->now );
     632           0 : }
     633             : 
     634             : /* Scheduling helper. Retrieves timers from conn to call schedule */
     635             : static inline void
     636           0 : fd_quic_svc_schedule1( fd_quic_conn_t * conn ) {
     637           0 :   fd_quic_state_t * state = fd_quic_get_state( conn->quic );
     638           0 :   fd_quic_svc_timers_schedule( state->svc_timers, conn, state->now );
     639           0 : }
     640             : 
     641             : /* Validation Helper */
     642             : static inline void
     643           0 : svc_cnt_eq_alloc_conn( fd_quic_svc_timers_t * timers, fd_quic_t * quic ) {
     644           0 :   ulong const event_cnt = fd_quic_svc_timers_cnt_events( timers );
     645           0 :   ulong const conn_cnt  = quic->metrics.conn_alloc_cnt;
     646           0 :   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           0 : }
     650             : /* validates the free conn list doesn't cycle, point nowhere, leak, or point to live conn */
     651             : static void
     652           0 : fd_quic_conn_free_validate( fd_quic_t * quic ) {
     653           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
     654             : 
     655             :   /* initialize visited */
     656           0 :   fd_quic_conn_validate_init( quic );
     657             : 
     658           0 :   ulong cnt  = 0UL;
     659           0 :   uint  node = state->free_conn_list;
     660           0 :   while( node!=UINT_MAX ) {
     661           0 :     FD_TEST( node < quic->limits.conn_cnt );
     662           0 :     fd_quic_conn_t * conn = fd_quic_conn_at_idx( state, node );
     663           0 :     FD_TEST( conn->state == FD_QUIC_CONN_STATE_INVALID );
     664           0 :     conn->visited = 1U;
     665           0 :     node = conn->free_conn_next;
     666           0 :     cnt++;
     667           0 :     FD_TEST( cnt <= quic->limits.conn_cnt );
     668           0 :   }
     669             : 
     670           0 :   for( ulong j=0UL; j < quic->limits.conn_cnt; j++ ) {
     671           0 :     fd_quic_conn_t * conn = fd_quic_conn_at_idx( state, j );
     672           0 :     FD_TEST( conn->conn_idx==j );
     673           0 :     if( conn->state == FD_QUIC_CONN_STATE_INVALID ) {
     674           0 :       FD_TEST( conn->visited );
     675           0 :     } else {
     676           0 :       FD_TEST( !conn->visited );
     677           0 :     }
     678           0 :   }
     679           0 : }
     680             : 
     681             : void
     682           0 : fd_quic_state_validate( fd_quic_t * quic ) {
     683           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
     684             : 
     685             :   /* init visited for svc_timers_validate to use */
     686           0 :   fd_quic_conn_validate_init( quic );
     687           0 :   FD_TEST( fd_quic_svc_timers_validate( state->svc_timers, quic ) );
     688             : 
     689           0 :   fd_quic_conn_free_validate( quic );
     690           0 : }
     691             : 
     692             : fd_quic_conn_t *
     693             : fd_quic_conn_query( fd_quic_conn_map_t * map,
     694           0 :                     ulong                conn_id ) {
     695           0 :   fd_quic_conn_map_t sentinel = {0};
     696           0 :   if( !conn_id ) return NULL;
     697           0 :   fd_quic_conn_map_t * entry = fd_quic_conn_map_query( map, conn_id, &sentinel );
     698           0 :   fd_quic_conn_t *     conn  = entry->conn;
     699           0 :   if( conn ) {
     700           0 :     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           0 :   }
     704           0 :   return conn;
     705           0 : }
     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           0 :                       fd_quic_pkt_t const *  pkt ) {
     721           0 :   fd_quic_log_hdr_t hdr = {
     722           0 :     .conn_id   = conn->our_conn_id,
     723           0 :     .pkt_num   = pkt->pkt_number,
     724           0 :     .ip4_saddr = pkt->ip4->saddr,
     725           0 :     .udp_sport = pkt->udp->net_sport,
     726           0 :     .enc_level = (uchar)pkt->enc_level,
     727           0 :     .flags     = 0
     728           0 :   };
     729           0 :   return hdr;
     730           0 : }
     731             : 
     732             : inline static void
     733             : fd_quic_set_conn_state( fd_quic_conn_t * conn,
     734           0 :                         uint             state ) {
     735           0 :   FD_COMPILER_MFENCE();
     736           0 :   uint old_state = conn->state;
     737           0 :   conn->quic->metrics.conn_state_cnt[ old_state ]--;
     738           0 :   conn->quic->metrics.conn_state_cnt[ state     ]++;
     739           0 :   conn->state = state;
     740           0 :   FD_COMPILER_MFENCE();
     741           0 : }
     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           0 :                      uint             reason ) {
     753           0 :   if( FD_UNLIKELY( !conn || conn->state == FD_QUIC_CONN_STATE_DEAD ) ) return;
     754             : 
     755           0 :   fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_ABORT );
     756           0 :   conn->reason = reason;
     757             : 
     758             :   /* set connection to be serviced ASAP */
     759           0 :   fd_quic_svc_prep_schedule_now( conn );
     760           0 :   fd_quic_svc_schedule1( conn );
     761           0 : }
     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           0 :                      uint                        error_line ) {
     786           0 :   fd_quic_t *           quic  = ctx->quic;
     787           0 :   fd_quic_conn_t *      conn  = ctx->conn;
     788           0 :   fd_quic_pkt_t const * pkt   = ctx->pkt;
     789           0 :   fd_quic_state_t *     state = fd_quic_get_state( quic );
     790             : 
     791           0 :   fd_quic_conn_error1( conn, reason );
     792             : 
     793           0 :   uint tls_reason = 0U;
     794           0 :   if( conn->tls_hs ) tls_reason = conn->tls_hs->hs.base.reason;
     795             : 
     796           0 :   ulong                 sig   = fd_quic_log_sig( FD_QUIC_EVENT_CONN_QUIC_CLOSE );
     797           0 :   fd_quic_log_error_t * frame = fd_quic_log_tx_prepare( state->log_tx );
     798           0 :   *frame = (fd_quic_log_error_t) {
     799           0 :     .hdr      = fd_quic_log_full_hdr( conn, pkt ),
     800           0 :     .code     = { reason, tls_reason },
     801           0 :     .src_file = "fd_quic.c",
     802           0 :     .src_line = error_line,
     803           0 :   };
     804           0 :   fd_quic_log_tx_submit( state->log_tx, sizeof(fd_quic_log_error_t), sig, state->now );
     805           0 : }
     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           0 : fd_quic_tx_enc_level( fd_quic_conn_t * conn, int acks ) {
     811           0 :   uint  app_pn_space   = fd_quic_enc_level_to_pn_space( fd_quic_enc_level_appdata_id );
     812           0 :   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           0 :   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           0 :     case FD_QUIC_CONN_STATE_ABORT:
     833           0 :     case FD_QUIC_CONN_STATE_CLOSE_PENDING:
     834             :       /* use handshake or app enc level depending on handshake complete */
     835           0 :       if( !(conn->flags & FD_QUIC_CONN_FLAGS_CLOSE_SENT ) ) {
     836           0 :         if( conn->handshake_complete ) {
     837           0 :           return fd_quic_enc_level_appdata_id;
     838           0 :         } 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           0 :         } else if( fd_uint_extract_bit( conn->keys_avail, fd_quic_enc_level_initial_id ) ) {
     841           0 :           return fd_quic_enc_level_initial_id;
     842           0 :         }
     843           0 :       }
     844           0 :       return ~0u;
     845             : 
     846             :       /* TODO consider this optimization... but we want to ack all handshakes, even if there is stream_data */
     847           0 :     case FD_QUIC_CONN_STATE_ACTIVE:
     848           0 :       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           0 :         fd_quic_stream_t * sentinel = conn->send_streams;
     853           0 :         fd_quic_stream_t * stream   = sentinel->next;
     854           0 :         if( !stream->sentinel && stream->upd_pkt_number >= app_pkt_number ) {
     855           0 :           return fd_quic_enc_level_appdata_id;
     856           0 :         }
     857           0 :       }
     858           0 :   }
     859             : 
     860             :   /* pick enc_level of oldest ACK not yet sent */
     861           0 :   fd_quic_ack_gen_t *   ack_gen    = conn->ack_gen;
     862           0 :   fd_quic_ack_t const * oldest_ack = fd_quic_ack_queue_ele( ack_gen, ack_gen->tail );
     863           0 :   uint ack_enc_level = oldest_ack->enc_level; /* speculative load (might be invalid) */
     864           0 :   if( (ack_gen->head != ack_gen->tail) & acks & fd_uint_extract_bit( conn->keys_avail, (int)ack_enc_level ) ) {
     865           0 :     return ack_enc_level;
     866           0 :   }
     867             : 
     868             :   /* Check for handshake data to send */
     869           0 :   uint min_keyed_enc_level = (uint)fd_uint_find_lsb_w_default( conn->keys_avail, (int)~0u );
     870           0 :   if( FD_UNLIKELY( conn->tls_hs ) ) {
     871           0 :     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           0 :     for( uint i = min_keyed_enc_level; i < 4; ++i ) {
     877           0 :       hs_data = fd_quic_tls_get_hs_data( conn->tls_hs, i );
     878           0 :       if( hs_data ) {
     879             :         /* offset within stream */
     880           0 :         ulong offset = conn->hs_sent_bytes[i];
     881             :         /* skip packets we've sent */
     882           0 :         while( hs_data && hs_data->offset + hs_data->data_sz <= offset ) {
     883           0 :           hs_data = fd_quic_tls_get_next_hs_data( conn->tls_hs, hs_data );
     884           0 :         }
     885           0 :         if( hs_data ) {
     886           0 :           return i;
     887           0 :         }
     888           0 :       }
     889           0 :     }
     890           0 :   }
     891             : 
     892             :   /* handshake done? */
     893           0 :   if( FD_UNLIKELY( conn->handshake_done_send ) ) return fd_quic_enc_level_appdata_id;
     894             : 
     895             :   /* find stream data to send */
     896           0 :   fd_quic_stream_t * sentinel = conn->send_streams;
     897           0 :   fd_quic_stream_t * stream   = sentinel->next;
     898           0 :   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           0 :   uint flags_pending = conn->flags & ~(FD_QUIC_CONN_FLAGS_CLOSE_SENT | FD_QUIC_CONN_FLAGS_PING_SENT);
     904           0 :   if( ( flags_pending != 0U )
     905           0 :       & ( conn->upd_pkt_number >= app_pkt_number )
     906           0 :       & fd_uint_extract_bit( conn->keys_avail, fd_quic_enc_level_appdata_id ) ) {
     907           0 :     return fd_quic_enc_level_appdata_id;
     908           0 :   }
     909             : 
     910             :   /* nothing to send */
     911           0 :   return ~0u;
     912           0 : }
     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           0 :                          ulong             buf_sz ) {
     927           0 :   if( conn->state == FD_QUIC_CONN_STATE_DEAD ) return FD_QUIC_PARSE_FAIL;
     928           0 :   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           0 :   uint id = buf[0];
     933             : 
     934           0 :   FD_DTRACE_PROBE_4( quic_handle_frame, id, conn->our_conn_id, pkt_type, pkt->pkt_number );
     935             : 
     936           0 :   fd_quic_frame_ctx_t frame_context[1] = {{ quic, conn, pkt }};
     937           0 :   if( FD_UNLIKELY( !fd_quic_frame_type_allowed( pkt_type, id ) ) ) {
     938           0 :     FD_DTRACE_PROBE_4( quic_err_frame_not_allowed, id, conn->our_conn_id, pkt_type, pkt->pkt_number );
     939           0 :     fd_quic_frame_error( frame_context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
     940           0 :     return FD_QUIC_PARSE_FAIL;
     941           0 :   }
     942           0 :   quic->metrics.frame_rx_cnt[ fd_quic_frame_metric_id[ id ] ]++;
     943             : 
     944           0 :   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           0 :   switch( id ) {
     948             : 
     949           0 : # define F(T,MID,NAME,...) \
     950           0 :     case T: return fd_quic_interpret_##NAME##_frame( frame_context, buf, buf_sz );
     951           0 :   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           0 :   }
     961             : 
     962           0 : }
     963             : 
     964             : fd_quic_t *
     965           0 : fd_quic_fini( fd_quic_t * quic ) {
     966             : 
     967           0 :   if( FD_UNLIKELY( !quic ) ) {
     968           0 :     FD_LOG_WARNING(("NULL quic"));
     969           0 :     return NULL;
     970           0 :   }
     971             : 
     972             :   /* Derive memory layout */
     973             : 
     974           0 :   fd_quic_layout_t layout = {0};
     975           0 :   fd_quic_footprint_ext( &quic->limits, &layout );
     976             : 
     977           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
     978             : 
     979             :   /* Free conns */
     980             : 
     981           0 :   ulong conn_laddr = (ulong)quic + layout.conns_off;
     982           0 :   for( ulong i=0; i < quic->limits.conn_cnt; i++ ) {
     983           0 :     fd_quic_conn_t * conn  = (fd_quic_conn_t *)( conn_laddr );
     984           0 :     conn_laddr            += layout.conn_footprint;
     985             : 
     986           0 :     if( conn->state ) fd_quic_conn_free( quic, conn );
     987           0 :   }
     988             : 
     989             :   /* Deinit TLS */
     990             : 
     991           0 :   fd_quic_tls_hs_pool_delete( fd_quic_tls_hs_pool_leave( state->hs_pool ) ); state->hs_pool = NULL;
     992           0 :   fd_quic_tls_delete( state->tls );
     993           0 :   fd_quic_tls_hs_cache_delete( fd_quic_tls_hs_cache_leave( &state->hs_cache ) );
     994             : 
     995             : 
     996             :   /* Delete conn ID map */
     997             : 
     998           0 :   fd_quic_conn_map_delete( fd_quic_conn_map_leave( state->conn_map ) );
     999           0 :   state->conn_map = NULL;
    1000             : 
    1001             :   /* Clear join-lifetime memory regions */
    1002             : 
    1003           0 :   memset( state, 0, sizeof(fd_quic_state_t) );
    1004             : 
    1005           0 :   return quic;
    1006           0 : }
    1007             : 
    1008             : void *
    1009           0 : fd_quic_delete( fd_quic_t * quic ) {
    1010             : 
    1011           0 :   if( FD_UNLIKELY( !quic ) ) {
    1012           0 :     FD_LOG_WARNING(( "NULL quic" ));
    1013           0 :     return NULL;
    1014           0 :   }
    1015             : 
    1016           0 :   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           0 :   if( FD_UNLIKELY( quic->magic!=FD_QUIC_MAGIC ) ) {
    1022           0 :     FD_LOG_WARNING(( "bad magic" ));
    1023           0 :     return NULL;
    1024           0 :   }
    1025             : 
    1026           0 :   void * shmlog = (void *)( (ulong)quic + quic->layout.log_off );
    1027           0 :   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           0 :   FD_COMPILER_MFENCE();
    1033           0 :   FD_VOLATILE( quic->magic ) = 0UL;
    1034           0 :   FD_COMPILER_MFENCE();
    1035             : 
    1036           0 :   return (void *)quic;
    1037           0 : }
    1038             : 
    1039             : fd_quic_stream_t *
    1040           0 : fd_quic_conn_new_stream( fd_quic_conn_t * conn ) {
    1041           0 :   if( FD_UNLIKELY( !conn->stream_map ) ) {
    1042             :     /* QUIC config is receive-only */
    1043           0 :     return NULL;
    1044           0 :   }
    1045             : 
    1046           0 :   fd_quic_t * quic = conn->quic;
    1047           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
    1048           0 :   if( FD_UNLIKELY( !state->stream_pool ) ) return NULL;
    1049             : 
    1050           0 :   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           0 :   ulong peer_sup_stream_id = conn->tx_sup_stream_id;
    1059             : 
    1060             :   /* is connection inactive */
    1061           0 :   if( FD_UNLIKELY( conn->state != FD_QUIC_CONN_STATE_ACTIVE ||
    1062           0 :                    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           0 :   fd_quic_stream_t * stream = fd_quic_stream_pool_alloc( state->stream_pool );
    1070             : 
    1071           0 :   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           0 :   fd_quic_stream_map_t * entry = fd_quic_stream_map_insert( conn->stream_map, next_stream_id );
    1078           0 :   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           0 :   fd_quic_stream_init( stream );
    1086           0 :   FD_QUIC_STREAM_LIST_INIT_STREAM( stream );
    1087             : 
    1088             :   /* stream tx_buf already set */
    1089           0 :   stream->conn      = conn;
    1090           0 :   stream->stream_id = next_stream_id;
    1091           0 :   stream->context   = NULL;
    1092             : 
    1093             :   /* set the max stream data to the appropriate initial value */
    1094           0 :   stream->tx_max_stream_data = conn->tx_initial_max_stream_data_uni;
    1095             : 
    1096             :   /* set state depending on stream type */
    1097           0 :   stream->state        = FD_QUIC_STREAM_STATE_RX_FIN;
    1098           0 :   stream->stream_flags = 0u;
    1099             : 
    1100           0 :   memset( stream->tx_ack, 0, stream->tx_buf.cap >> 3ul );
    1101             : 
    1102             :   /* insert into used streams */
    1103           0 :   FD_QUIC_STREAM_LIST_REMOVE( stream );
    1104           0 :   FD_QUIC_STREAM_LIST_INSERT_BEFORE( conn->used_streams, stream );
    1105             : 
    1106             :   /* generate a new stream id */
    1107           0 :   conn->tx_next_stream_id = next_stream_id + 4U;
    1108             : 
    1109             :   /* assign the stream to the entry */
    1110           0 :   entry->stream = stream;
    1111             : 
    1112             :   /* update metrics */
    1113           0 :   quic->metrics.stream_opened_cnt++;
    1114           0 :   quic->metrics.stream_active_cnt++;
    1115             : 
    1116           0 :   FD_DEBUG( FD_LOG_DEBUG(( "Created stream with ID %lu", next_stream_id )) );
    1117           0 :   return stream;
    1118           0 : }
    1119             : 
    1120             : int
    1121             : fd_quic_stream_send( fd_quic_stream_t *  stream,
    1122             :                      void const *        data,
    1123             :                      ulong               data_sz,
    1124           0 :                      int                 fin ) {
    1125           0 :   if( FD_UNLIKELY( stream->state & FD_QUIC_STREAM_STATE_TX_FIN ) ) {
    1126           0 :     return FD_QUIC_SEND_ERR_FIN;
    1127           0 :   }
    1128             : 
    1129           0 :   fd_quic_conn_t * conn = stream->conn;
    1130             : 
    1131           0 :   fd_quic_buffer_t * tx_buf = &stream->tx_buf;
    1132             : 
    1133             :   /* are we allowed to send? */
    1134           0 :   ulong stream_id = stream->stream_id;
    1135             : 
    1136             :   /* stream_id & 2 == 0 is bidir
    1137             :      stream_id & 1 == 0 is client */
    1138           0 :   if( FD_UNLIKELY( ( ( (uint)stream_id & 2u ) == 2u ) &
    1139           0 :                    ( ( (uint)stream_id & 1u ) != (uint)conn->server ) ) ) {
    1140           0 :     return FD_QUIC_SEND_ERR_INVAL_STREAM;
    1141           0 :   }
    1142             : 
    1143           0 :   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           0 :   ulong allowed_stream = stream->tx_max_stream_data - stream->tx_tot_data;
    1153           0 :   ulong allowed_conn   = conn->tx_max_data - conn->tx_tot_data;
    1154           0 :   ulong allowed        = fd_ulong_min( allowed_conn, allowed_stream );
    1155             : 
    1156           0 :   if( data_sz > fd_quic_buffer_avail( tx_buf ) ) {
    1157           0 :     return FD_QUIC_SEND_ERR_FLOW;
    1158           0 :   }
    1159             : 
    1160           0 :   if( data_sz > allowed ) {
    1161           0 :     return FD_QUIC_SEND_ERR_FLOW;
    1162           0 :   }
    1163             : 
    1164             :   /* store data from data into tx_buf */
    1165           0 :   fd_quic_buffer_store( tx_buf, data, data_sz );
    1166             : 
    1167             :   /* adjust flow control limits on stream and connection */
    1168           0 :   stream->tx_tot_data += data_sz;
    1169           0 :   conn->tx_tot_data   += data_sz;
    1170             : 
    1171             :   /* insert into send list */
    1172           0 :   if( !FD_QUIC_STREAM_ACTION( stream ) ) {
    1173           0 :     FD_QUIC_STREAM_LIST_REMOVE( stream );
    1174           0 :     FD_QUIC_STREAM_LIST_INSERT_BEFORE( conn->send_streams, stream );
    1175           0 :   }
    1176           0 :   stream->stream_flags   |= FD_QUIC_STREAM_FLAGS_UNSENT; /* we have unsent data */
    1177           0 :   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           0 :   if( fin ) {
    1182           0 :     fd_quic_stream_fin( stream );
    1183           0 :   }
    1184             : 
    1185             :   /* schedule send */
    1186           0 :   fd_quic_svc_prep_schedule_now( conn );
    1187           0 :   fd_quic_svc_schedule1( conn );
    1188             : 
    1189           0 :   return FD_QUIC_SUCCESS;
    1190           0 : }
    1191             : 
    1192             : void
    1193           0 : fd_quic_stream_fin( fd_quic_stream_t * stream ) {
    1194           0 :   if( FD_UNLIKELY( stream->state & FD_QUIC_STREAM_STATE_TX_FIN ) ) {
    1195           0 :     return;
    1196           0 :   }
    1197             : 
    1198           0 :   fd_quic_conn_t * conn = stream->conn;
    1199             : 
    1200             :   /* insert into send list */
    1201           0 :   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           0 :   stream->stream_flags   |= FD_QUIC_STREAM_FLAGS_TX_FIN; /* state immediately updated */
    1206           0 :   stream->state          |= FD_QUIC_STREAM_STATE_TX_FIN; /* state immediately updated */
    1207           0 :   stream->upd_pkt_number  = FD_QUIC_PKT_NUM_PENDING;     /* update to be sent in next packet */
    1208             : 
    1209             :   /* TODO update metrics */
    1210           0 : }
    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           0 :                             uint             enc_level ) {
    1231           0 :   fd_quic_pkt_meta_tracker_t * tracker = &conn->pkt_meta_tracker;
    1232           0 :   fd_quic_pkt_meta_t         * pool    = tracker->pool;
    1233           0 :   fd_quic_pkt_meta_ds_t      * sent = &tracker->sent_pkt_metas[enc_level];
    1234             : 
    1235           0 :   fd_quic_pkt_meta_t * prev = NULL;
    1236           0 :   for( fd_quic_pkt_meta_ds_fwd_iter_t iter = fd_quic_pkt_meta_ds_fwd_iter_init( sent, pool );
    1237           0 :                                              !fd_quic_pkt_meta_ds_fwd_iter_done( iter );
    1238           0 :                                              iter = fd_quic_pkt_meta_ds_fwd_iter_next( iter, pool ) ) {
    1239           0 :     fd_quic_pkt_meta_t * e = fd_quic_pkt_meta_ds_fwd_iter_ele( iter, pool );
    1240           0 :     if( FD_LIKELY( prev ) ) {
    1241           0 :       fd_quic_pkt_meta_pool_ele_release( pool, prev );
    1242           0 :     }
    1243           0 :     prev = e;
    1244           0 :   }
    1245           0 :   if( FD_LIKELY( prev ) ) {
    1246           0 :     fd_quic_pkt_meta_pool_ele_release( pool, prev );
    1247           0 :   }
    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           0 :   ulong pre_ele_cnt = fd_quic_pkt_meta_ds_ele_cnt( sent );
    1257             : 
    1258           0 :   fd_quic_pkt_meta_ds_clear( tracker, enc_level );
    1259           0 :   conn->used_pkt_meta -= pre_ele_cnt;
    1260             : 
    1261           0 :   return pre_ele_cnt;
    1262           0 : }
    1263             : 
    1264             : /* reclaim and free all pkt_meta for a given encryption level,
    1265             :    and return the number affected. */
    1266             : static ulong
    1267           0 : fd_quic_reclaim_pkt_meta_level( fd_quic_conn_t * conn, uint enc_level ) {
    1268           0 :   fd_quic_pkt_meta_tracker_t * tracker  = &conn->pkt_meta_tracker;
    1269           0 :   fd_quic_pkt_meta_t         * pool     = tracker->pool;
    1270           0 :   fd_quic_pkt_meta_ds_t      * sent     = &tracker->sent_pkt_metas[enc_level];
    1271             : 
    1272           0 :   for( fd_quic_pkt_meta_ds_fwd_iter_t iter = fd_quic_pkt_meta_ds_fwd_iter_init( sent, pool );
    1273           0 :                                              !fd_quic_pkt_meta_ds_fwd_iter_done( iter );
    1274           0 :                                              iter = fd_quic_pkt_meta_ds_fwd_iter_next( iter, pool ) ) {
    1275           0 :     fd_quic_pkt_meta_t * e = fd_quic_pkt_meta_ds_fwd_iter_ele( iter, pool );
    1276           0 :     fd_quic_reclaim_pkt_meta( conn, e, enc_level );
    1277           0 :   }
    1278             : 
    1279           0 :   return fd_quic_conn_free_pkt_meta( conn, enc_level );
    1280           0 : }
    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           0 :                            uint             enc_level ) {
    1290           0 :   if( FD_LIKELY( !fd_uint_extract_bit( conn->keys_avail, (int)enc_level ) ) ) return 0UL;
    1291           0 :   FD_DEBUG( FD_LOG_DEBUG(( "conn=%p abandoning enc_level=%u", (void *)conn, enc_level )); )
    1292             : 
    1293           0 :   fd_quic_ack_gen_abandon_enc_level( conn->ack_gen, enc_level );
    1294             : 
    1295           0 :   ulong freed = 0UL;
    1296           0 :   for( uint j = 0; j <= enc_level; ++j ) {
    1297           0 :     conn->keys_avail = fd_uint_clear_bit( conn->keys_avail, (int)j );
    1298             :     /* treat all packets as ACKed (freeing handshake data, etc.) */
    1299           0 :     freed += fd_quic_reclaim_pkt_meta_level( conn, j );
    1300           0 :   }
    1301             : 
    1302           0 :   return freed;
    1303           0 : }
    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           0 :     int                       is_server ) {
    1310             : 
    1311           0 :   fd_quic_gen_initial_secrets(
    1312           0 :       &conn->secrets,
    1313           0 :       dst_conn_id->conn_id, dst_conn_id->sz,
    1314           0 :       is_server );
    1315             : 
    1316           0 :   fd_quic_gen_keys(
    1317           0 :       &conn->keys[ fd_quic_enc_level_initial_id ][ 0 ],
    1318           0 :       conn->secrets.secret[ fd_quic_enc_level_initial_id ][ 0 ] );
    1319             : 
    1320           0 :   fd_quic_gen_keys(
    1321           0 :       &conn->keys[ fd_quic_enc_level_initial_id ][ 1 ],
    1322           0 :       conn->secrets.secret[ fd_quic_enc_level_initial_id ][ 1 ] );
    1323           0 : }
    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           0 :                     ulong                     new_conn_id ) {
    1331             : 
    1332           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
    1333             : 
    1334           0 :   long  expire_at = state->now + quic->config.retry_ttl;
    1335           0 :   uchar retry_pkt[ FD_QUIC_RETRY_LOCAL_SZ ];
    1336           0 :   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           0 :   quic->metrics.retry_tx_cnt++;
    1339             : 
    1340           0 :   uchar * tx_ptr = retry_pkt         + retry_pkt_sz;
    1341           0 :   if( FD_UNLIKELY( fd_quic_tx_buffered_raw(
    1342           0 :         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           0 :         &tx_ptr,
    1346           0 :         retry_pkt,
    1347             :         // encode buffer
    1348           0 :         &pkt->ip4->net_id,
    1349           0 :         pkt->ip4->saddr,
    1350           0 :         pkt->udp->net_sport,
    1351           0 :         pkt->ip4->daddr,
    1352           0 :         pkt->udp->net_dport ) == FD_QUIC_FAILED ) ) {
    1353           0 :     return FD_QUIC_PARSE_FAIL;
    1354           0 :   }
    1355           0 :   return 0UL;
    1356           0 : }
    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           0 :                             fd_quic_state_t * state ) {
    1364             : 
    1365           0 :   fd_quic_tls_hs_t* hs_to_free = fd_quic_tls_hs_cache_ele_peek_head( &state->hs_cache, state->hs_pool );
    1366             : 
    1367           0 :   if( state->now < hs_to_free->birthtime + quic->config.tls_hs_ttl ) {
    1368             :     /* oldest is too young to evict */
    1369           0 :     quic->metrics.hs_err_alloc_fail_cnt++;
    1370           0 :     return 0;
    1371           0 :   }
    1372             : 
    1373           0 :   fd_quic_conn_free( quic, hs_to_free->context );
    1374           0 :   quic->metrics.hs_evicted_cnt++;
    1375           0 :   return 1;
    1376           0 : }
    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           0 :                            ulong                     cur_sz ) {
    1391           0 :   fd_quic_conn_t * conn = *p_conn;
    1392             : 
    1393           0 :   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           0 :   fd_quic_state_t   * state   = fd_quic_get_state( quic );
    1399           0 :   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           0 :   fd_quic_initial_t initial[1] = {0};
    1410           0 :   ulong rc = fd_quic_decode_initial( initial, cur_ptr, cur_sz );
    1411           0 :   if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
    1412           0 :     FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_decode_initial failed" )) );
    1413           0 :     return FD_QUIC_PARSE_FAIL;
    1414           0 :   }
    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           0 :   ulong pn_offset = initial->pkt_num_pnoff;
    1421           0 :   ulong body_sz   = initial->len;  /* length of packet number, frames, and auth tag */
    1422           0 :   ulong tot_sz    = pn_offset + body_sz;
    1423           0 :   if( FD_UNLIKELY( tot_sz > cur_sz ) ) {
    1424           0 :     FD_DEBUG( FD_LOG_DEBUG(( "Bogus initial packet length" )) );
    1425           0 :     return FD_QUIC_PARSE_FAIL;
    1426           0 :   }
    1427             : 
    1428             :   /* count received token len */
    1429           0 :   int   const token_len_match = initial->token_len == sizeof(fd_quic_retry_token_t);
    1430           0 :   ulong const token_len_idx   = fd_ulong_if( !!initial->token_len,
    1431           0 :                                              fd_ulong_if( token_len_match, 1, 2 ),
    1432           0 :                                              0 );
    1433           0 :   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           0 :   if( FD_UNLIKELY( initial->token_len > 0 &&
    1448           0 :                    ( quic->config.role == FD_QUIC_ROLE_CLIENT || !quic->config.retry ) ) ) {
    1449           0 :     FD_DEBUG( FD_LOG_DEBUG(( "Rejecting initial with token" )); )
    1450           0 :     return FD_QUIC_PARSE_FAIL;
    1451           0 :   }
    1452             : 
    1453             : 
    1454           0 :   ulong             scid;  /* outgoing scid */
    1455           0 :   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           0 :   if( FD_UNLIKELY( !conn ) ) {
    1460             :     /* if we're a client, and no conn, discard */
    1461           0 :     if( quic->config.role == FD_QUIC_ROLE_CLIENT ) {
    1462             :       /* connection may have been torn down */
    1463           0 :       FD_DEBUG( FD_LOG_DEBUG(( "unknown connection ID" )); )
    1464           0 :       metrics->pkt_no_conn_cnt[ fd_quic_enc_level_initial_id ]++;
    1465           0 :       FD_DTRACE_PROBE_2( fd_quic_handle_v1_initial_no_conn , state->now, pkt->pkt_number );
    1466           0 :       return FD_QUIC_PARSE_FAIL;
    1467           0 :     }
    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           0 :     if( pkt->datagram_sz < FD_QUIC_INITIAL_PAYLOAD_SZ_MIN ) {
    1473             :       /* can't trust the included values, so can't reply */
    1474           0 :       return FD_QUIC_PARSE_FAIL;
    1475           0 :     }
    1476             : 
    1477             :     /* Early check: Is conn free? */
    1478           0 :     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           0 :     if( !quic->config.retry ) {
    1493           0 :       scid = fd_rng_ulong( state->_rng );
    1494           0 :     } else { /* retry configured */
    1495             : 
    1496             :       /* Need to send retry? Do so before more work */
    1497           0 :       if( initial->token_len != sizeof(fd_quic_retry_token_t) ) {
    1498             : 
    1499           0 :         ulong new_conn_id_u64 = fd_rng_ulong( state->_rng );
    1500           0 :         if( FD_UNLIKELY( fd_quic_send_retry(
    1501           0 :               quic, pkt,
    1502           0 :               dcid, peer_scid, new_conn_id_u64 ) ) ) {
    1503           0 :           return FD_QUIC_FAILED;
    1504           0 :         }
    1505           0 :         return (initial->pkt_num_pnoff + initial->len);
    1506           0 :       } 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           0 :         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           0 :         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           0 :         };
    1517           0 :       }
    1518           0 :     }
    1519           0 :   }
    1520             : 
    1521             :   /* Determine decryption keys, related data */
    1522             : 
    1523             :   /* Placeholder for generated crypto material before allocating conn */
    1524           0 :   fd_quic_crypto_keys_t    _rx_keys[1];
    1525           0 :   fd_quic_crypto_secrets_t _secrets[1];
    1526             : 
    1527             :   /* Conditional inputs to decryption stage */
    1528           0 :   fd_quic_crypto_keys_t *    rx_keys = NULL;
    1529           0 :   fd_quic_crypto_secrets_t * secrets = NULL;
    1530           0 :   ulong                      exp_pkt_num;
    1531             : 
    1532           0 :   if( !conn ) {
    1533             :     /* no conn, generate secret and rx keys */
    1534           0 :     rx_keys     = _rx_keys;
    1535           0 :     secrets     = _secrets;
    1536           0 :     exp_pkt_num = 0;
    1537             : 
    1538           0 :     fd_quic_gen_initial_secrets(
    1539           0 :         secrets,
    1540           0 :         dcid->conn_id, dcid->sz,
    1541           0 :         /* is_server */ 1 );
    1542           0 :     fd_quic_gen_keys(
    1543           0 :         rx_keys,
    1544           0 :         secrets->secret[ fd_quic_enc_level_initial_id ][ 0 ] );
    1545           0 :   } else {
    1546             :     /* conn, use existing keys/secrets */
    1547           0 :     rx_keys     = &conn->keys[ fd_quic_enc_level_initial_id ][0];
    1548           0 :     secrets     = &conn->secrets;
    1549           0 :     exp_pkt_num = conn->exp_pkt_number[0];
    1550           0 :   }
    1551             : 
    1552             :   /* Decrypt incoming packet */
    1553             : 
    1554             :   /* header protection needs the offset to the packet number */
    1555             : 
    1556           0 : # if !FD_QUIC_DISABLE_CRYPTO
    1557             :   /* this decrypts the header */
    1558           0 :   if( FD_UNLIKELY(
    1559           0 :         fd_quic_crypto_decrypt_hdr( cur_ptr, cur_sz,
    1560           0 :                                     pn_offset,
    1561           0 :                                     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           0 : # endif /* !FD_QUIC_DISABLE_CRYPTO */
    1569             : 
    1570           0 :   ulong pkt_number_sz = fd_quic_h0_pkt_num_len( cur_ptr[0] ) + 1u;
    1571           0 :   ulong pktnum_comp   = fd_quic_pktnum_decode( cur_ptr+pn_offset, pkt_number_sz );
    1572             : 
    1573             :   /* reconstruct packet number */
    1574           0 :   ulong pkt_number = fd_quic_reconstruct_pkt_num( pktnum_comp, pkt_number_sz, exp_pkt_num );
    1575             : 
    1576           0 : # 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           0 :   if( FD_UNLIKELY(
    1581           0 :         fd_quic_crypto_decrypt( cur_ptr, tot_sz,
    1582           0 :                                 pn_offset,
    1583           0 :                                 pkt_number,
    1584           0 :                                 rx_keys ) != FD_QUIC_SUCCESS ) ) {
    1585           0 :     FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_crypto_decrypt failed" )) );
    1586           0 :     FD_DTRACE_PROBE_2( quic_err_decrypt_initial_pkt, pkt->ip4, pkt->pkt_number );
    1587           0 :     quic->metrics.pkt_decrypt_fail_cnt[ fd_quic_enc_level_initial_id ]++;
    1588           0 :     return FD_QUIC_PARSE_FAIL;
    1589           0 :   }
    1590           0 : # endif /* FD_QUIC_DISABLE_CRYPTO */
    1591             : 
    1592             :   /* set packet number on the context */
    1593           0 :   pkt->pkt_number = pkt_number;
    1594             : 
    1595           0 :   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           0 :   if( FD_UNLIKELY( !conn ) ) {
    1602             : 
    1603             :     /* Save peer's conn ID, which we will use to address peer with. */
    1604           0 :     fd_quic_conn_id_t peer_conn_id = {0};
    1605           0 :     fd_memcpy( peer_conn_id.conn_id, initial->src_conn_id, FD_QUIC_MAX_CONN_ID_SZ );
    1606           0 :     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           0 :     fd_quic_transport_params_t tp[1] = { state->transport_params };
    1618             : 
    1619           0 :     if( !quic->config.retry ) {
    1620             :       /* assume no retry */
    1621           0 :       tp->retry_source_connection_id_present = 0;
    1622             : 
    1623             :       /* Send orig conn ID back to client (server only) */
    1624             : 
    1625           0 :       tp->original_destination_connection_id_present = 1;
    1626           0 :       tp->original_destination_connection_id_len     = dcid->sz;
    1627           0 :       fd_memcpy( tp->original_destination_connection_id,
    1628           0 :           dcid->conn_id,
    1629           0 :           dcid->sz );
    1630           0 :     } 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           0 :       tp->original_destination_connection_id_present = 1;
    1659           0 :       tp->original_destination_connection_id_len     = odcid.sz;
    1660           0 :       memcpy( tp->original_destination_connection_id,
    1661           0 :               odcid.conn_id,
    1662           0 :               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           0 :       tp->retry_source_connection_id_present = 1;
    1668           0 :       tp->retry_source_connection_id_len     = FD_QUIC_CONN_ID_SZ;
    1669           0 :       FD_STORE( ulong, tp->retry_source_connection_id, scid );
    1670             : 
    1671           0 :       metrics->conn_retry_cnt++;
    1672           0 :     }
    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           0 :     tp->initial_source_connection_id_present = 1;
    1687           0 :     tp->initial_source_connection_id_len     = FD_QUIC_CONN_ID_SZ;
    1688           0 :     FD_STORE( ulong, tp->initial_source_connection_id, scid );
    1689             : 
    1690             :     /* tls hs available? After decrypting because might evict another hs */
    1691           0 :     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           0 :     conn = fd_quic_conn_create( quic,
    1700           0 :         scid,
    1701           0 :         &peer_conn_id,
    1702           0 :         pkt->ip4->saddr,
    1703           0 :         pkt->udp->net_sport,
    1704           0 :         pkt->ip4->daddr,
    1705           0 :         pkt->udp->net_dport,
    1706           0 :         1 /* server */ );
    1707             : 
    1708           0 :     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           0 :     FD_DEBUG( FD_LOG_DEBUG(( "new connection allocated" )) );
    1715             : 
    1716             :     /* set the value for the caller */
    1717           0 :     *p_conn = conn;
    1718             : 
    1719             :     /* Create a TLS handshake */
    1720           0 :     fd_quic_tls_hs_t * tls_hs = fd_quic_tls_hs_new(
    1721           0 :         fd_quic_tls_hs_pool_ele_acquire( state->hs_pool ),
    1722           0 :         state->tls,
    1723           0 :         (void*)conn,
    1724           0 :         1 /*is_server*/,
    1725           0 :         tp,
    1726           0 :         state->now );
    1727           0 :     fd_quic_tls_hs_cache_ele_push_tail( &state->hs_cache, tls_hs, state->hs_pool );
    1728             : 
    1729           0 :     conn->tls_hs = tls_hs;
    1730           0 :     quic->metrics.hs_created_cnt++;
    1731             : 
    1732             :     /* copy secrets and rx keys */
    1733           0 :     conn->secrets = *secrets;
    1734           0 :     conn->keys[ fd_quic_enc_level_initial_id ][0] = *rx_keys;
    1735             : 
    1736             :     /* generate tx keys */
    1737           0 :     fd_quic_gen_keys(
    1738           0 :         &conn->keys[ fd_quic_enc_level_initial_id ][ 1 ],
    1739           0 :         secrets->secret[ fd_quic_enc_level_initial_id ][ 1 ] );
    1740           0 :   }
    1741             : 
    1742           0 :   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           0 :     conn->host.ip_addr = pkt->ip4->daddr;
    1746           0 :   }
    1747             : 
    1748             :   /* check if reply conn id needs to change */
    1749           0 :   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           0 :                conn->peer_cids[0].sz =     initial->src_conn_id_len;
    1754           0 :     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           0 :     conn->established = 1;
    1758           0 :   }
    1759             : 
    1760             :   /* handle frames */
    1761           0 :   ulong         payload_off = pn_offset + pkt_number_sz;
    1762           0 :   uchar const * frame_ptr   = cur_ptr + payload_off;
    1763           0 :   ulong         frame_sz    = body_sz - pkt_number_sz - FD_QUIC_CRYPTO_TAG_SZ; /* total size of all frames in packet */
    1764           0 :   while( frame_sz != 0UL ) {
    1765           0 :     rc = fd_quic_handle_v1_frame( quic,
    1766           0 :                                   conn,
    1767           0 :                                   pkt,
    1768           0 :                                   FD_QUIC_PKT_TYPE_INITIAL,
    1769           0 :                                   frame_ptr,
    1770           0 :                                   frame_sz );
    1771           0 :     if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
    1772           0 :       FD_DEBUG( FD_LOG_DEBUG(( "Failed to handle frame (Initial, frame=0x%02x)", frame_ptr[0] )) );
    1773           0 :       quic->metrics.frame_rx_err_cnt++;
    1774           0 :       return FD_QUIC_PARSE_FAIL;
    1775           0 :     }
    1776             : 
    1777           0 :     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           0 :     frame_ptr += rc;
    1784           0 :     frame_sz  -= rc;
    1785           0 :   }
    1786             : 
    1787             :   /* update last activity */
    1788           0 :   conn->last_activity = state->now;
    1789           0 :   conn->flags &= ~( FD_QUIC_CONN_FLAGS_PING_SENT | FD_QUIC_CONN_FLAGS_PING );
    1790             : 
    1791             :   /* update expected packet number */
    1792           0 :   conn->exp_pkt_number[0] = fd_ulong_max( conn->exp_pkt_number[0], pkt_number+1UL );
    1793             : 
    1794             :   /* insert into service queue */
    1795           0 :   fd_quic_svc_prep_schedule( conn, state->now );
    1796             : 
    1797             :   /* return number of bytes consumed */
    1798           0 :   return tot_sz;
    1799           0 : }
    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           0 : ) {
    1809           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
    1810           0 :   if( FD_UNLIKELY( !conn ) ) {
    1811           0 :     quic->metrics.pkt_no_conn_cnt[ fd_quic_enc_level_handshake_id ]++;
    1812           0 :     FD_DTRACE_PROBE_2( fd_quic_handle_v1_handshake_no_conn , state->now, pkt->pkt_number );
    1813           0 :     return FD_QUIC_PARSE_FAIL;
    1814           0 :   }
    1815             : 
    1816           0 :   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           0 :   fd_quic_handshake_t handshake[1];
    1823           0 :   ulong rc = fd_quic_decode_handshake( handshake, cur_ptr, cur_sz );
    1824           0 :   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           0 :   ulong len = (ulong)( handshake->pkt_num_pnoff + handshake->len );
    1834           0 :   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           0 :   fd_quic_tls_hs_t * tls_hs = conn->tls_hs;
    1846           0 :   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           0 :   ulong    pn_offset        = handshake->pkt_num_pnoff;
    1855             : 
    1856           0 :   ulong    body_sz          = handshake->len;  /* not a protected field */
    1857             :                                                /* length of payload + num packet bytes */
    1858             : 
    1859           0 : # if !FD_QUIC_DISABLE_CRYPTO
    1860             :   /* this decrypts the header */
    1861           0 :   if( FD_UNLIKELY(
    1862           0 :         fd_quic_crypto_decrypt_hdr( cur_ptr, cur_sz,
    1863           0 :                                     pn_offset,
    1864           0 :                                     &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           0 : # endif /* !FD_QUIC_DISABLE_CRYPTO */
    1870             : 
    1871             :   /* number of bytes in the packet header */
    1872           0 :   ulong pkt_number_sz = fd_quic_h0_pkt_num_len( cur_ptr[0] ) + 1u;
    1873           0 :   ulong tot_sz        = pn_offset + body_sz; /* total including header and payload */
    1874             : 
    1875             :   /* now we have decrypted packet number */
    1876           0 :   ulong pktnum_comp = fd_quic_pktnum_decode( cur_ptr+pn_offset, pkt_number_sz );
    1877             : 
    1878             :   /* reconstruct packet number */
    1879           0 :   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           0 : # if !FD_QUIC_DISABLE_CRYPTO
    1885             :   /* this decrypts the header and payload */
    1886           0 :   if( FD_UNLIKELY(
    1887           0 :         fd_quic_crypto_decrypt( cur_ptr, tot_sz,
    1888           0 :                                 pn_offset,
    1889           0 :                                 pkt_number,
    1890           0 :                                 &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           0 : # endif /* FD_QUIC_DISABLE_CRYPTO */
    1898             : 
    1899             :   /* set packet number on the context */
    1900           0 :   pkt->pkt_number = pkt_number;
    1901             : 
    1902             :   /* check body size large enough for required elements */
    1903           0 :   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           0 :   ulong         payload_off = pn_offset + pkt_number_sz;
    1909           0 :   uchar const * frame_ptr   = cur_ptr + payload_off;
    1910           0 :   ulong         frame_sz    = body_sz - pkt_number_sz - FD_QUIC_CRYPTO_TAG_SZ; /* total size of all frames in packet */
    1911           0 :   while( frame_sz != 0UL ) {
    1912           0 :     rc = fd_quic_handle_v1_frame( quic,
    1913           0 :                                   conn,
    1914           0 :                                   pkt,
    1915           0 :                                   FD_QUIC_PKT_TYPE_HANDSHAKE,
    1916           0 :                                   frame_ptr,
    1917           0 :                                   frame_sz );
    1918           0 :     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           0 :     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           0 :     frame_ptr += rc;
    1931           0 :     frame_sz  -= rc;
    1932           0 :   }
    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           0 :   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           0 :   conn->last_activity = fd_quic_get_state( quic )->now;
    1944           0 :   conn->flags &= ~( FD_QUIC_CONN_FLAGS_PING_SENT | FD_QUIC_CONN_FLAGS_PING );
    1945             : 
    1946             :   /* update expected packet number */
    1947           0 :   conn->exp_pkt_number[1] = fd_ulong_max( conn->exp_pkt_number[1], pkt_number+1UL );
    1948             : 
    1949             :   /* return number of bytes consumed */
    1950           0 :   return tot_sz;
    1951           0 : }
    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           0 : ) {
    1961           0 :   (void)pkt;
    1962           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
    1963             : 
    1964           0 :   if( FD_UNLIKELY( quic->config.role == FD_QUIC_ROLE_SERVER ) ) {
    1965           0 :     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           0 :     return FD_QUIC_PARSE_FAIL;
    1969           0 :   }
    1970             : 
    1971           0 :   if( FD_UNLIKELY( !conn ) ) {
    1972           0 :     FD_DTRACE_PROBE_2( fd_quic_handle_v1_retry_no_conn , state->now, pkt->pkt_number );
    1973           0 :     quic->metrics.pkt_no_conn_cnt[1]++;
    1974           0 :     return FD_QUIC_PARSE_FAIL;
    1975           0 :   }
    1976             : 
    1977           0 :   fd_quic_conn_id_t const * orig_dst_conn_id = &conn->peer_cids[0];
    1978           0 :   uchar const *             retry_token      = NULL;
    1979           0 :   ulong                     retry_token_sz   = 0UL;
    1980             : 
    1981           0 :   int rc = fd_quic_retry_client_verify(
    1982           0 :       cur_ptr, cur_sz,
    1983           0 :       orig_dst_conn_id,
    1984           0 :       &conn->retry_src_conn_id,
    1985           0 :       &retry_token, &retry_token_sz
    1986           0 :   );
    1987           0 :   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           0 :   conn->peer_cids[0] = conn->retry_src_conn_id;
    1994             : 
    1995             :   /* Re-send the ClientHello */
    1996           0 :   conn->hs_sent_bytes[fd_quic_enc_level_initial_id] = 0;
    1997             : 
    1998             :   /* Need to regenerate keys using the retry source connection id */
    1999           0 :   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           0 :   conn->token_len = retry_token_sz;
    2003           0 :   fd_memcpy( &conn->token, retry_token, conn->token_len );
    2004             : 
    2005             :   /* have to rewind the handshake data */
    2006           0 :   uint enc_level                 = fd_quic_enc_level_initial_id;
    2007           0 :   conn->hs_sent_bytes[enc_level] = 0;
    2008             : 
    2009             :   /* send the INITIAL */
    2010           0 :   conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
    2011             : 
    2012           0 :   fd_quic_svc_prep_schedule_now( conn );
    2013             : 
    2014           0 :   return cur_sz;
    2015           0 : }
    2016             : 
    2017             : ulong
    2018           0 : 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           0 :   (void)pkt;
    2020           0 :   (void)quic;
    2021           0 :   (void)cur_ptr;
    2022           0 :   (void)cur_sz;
    2023             :   /* since we do not support zero-rtt, simply fail the packet */
    2024           0 :   if( conn ) {
    2025           0 :     fd_quic_conn_error( conn, FD_QUIC_CONN_REASON_INTERNAL_ERROR, __LINE__ );
    2026           0 :   }
    2027           0 :   return FD_QUIC_PARSE_FAIL;
    2028           0 : }
    2029             : 
    2030             : int
    2031             : fd_quic_lazy_ack_pkt( fd_quic_t *           quic,
    2032             :                       fd_quic_conn_t *      conn,
    2033           0 :                       fd_quic_pkt_t const * pkt ) {
    2034           0 :   if( pkt->ack_flag & ACK_FLAG_CANCEL ) {
    2035           0 :     return FD_QUIC_ACK_TX_CANCEL;
    2036           0 :   }
    2037             : 
    2038           0 :   fd_quic_state_t   * state   = fd_quic_get_state( quic );
    2039           0 :   fd_quic_ack_gen_t * ack_gen = conn->ack_gen;
    2040           0 :   int res = fd_quic_ack_pkt( conn->ack_gen, pkt->pkt_number, pkt->enc_level, state->now );
    2041           0 :   conn->ack_gen->is_elicited |= fd_uchar_if( pkt->ack_flag & ACK_FLAG_RQD, 1, 0 );
    2042             : 
    2043             :   /* Trigger immediate ACK send? */
    2044           0 :   int ack_sz_threshold_hit = conn->unacked_sz > quic->config.ack_threshold;
    2045           0 :   int force_instant_ack =
    2046           0 :     ( !!(pkt->ack_flag & ACK_FLAG_RQD) ) &
    2047           0 :     ( ( pkt->enc_level == fd_quic_enc_level_initial_id   ) |
    2048           0 :       ( pkt->enc_level == fd_quic_enc_level_handshake_id ) );
    2049           0 :   if( ack_sz_threshold_hit | force_instant_ack ) {
    2050           0 :     conn->unacked_sz = 0UL;
    2051           0 :     fd_quic_svc_prep_schedule( conn, state->now );
    2052           0 :   } else if( ack_gen->is_elicited ) {
    2053           0 :     fd_quic_svc_prep_schedule( conn, state->now + quic->config.ack_delay );
    2054           0 :   }
    2055             : 
    2056           0 :   return res;
    2057           0 : }
    2058             : 
    2059             : /* This thunk works around a compiler bug (bogus stringop-overflow warning) in GCC 11 */
    2060             : __attribute__((noinline)) static void
    2061           0 : fd_quic_key_update_derive1( fd_quic_conn_t * conn ) {
    2062           0 :   fd_quic_key_update_derive( &conn->secrets, conn->new_keys );
    2063           0 : }
    2064             : 
    2065             : static void
    2066           0 : fd_quic_key_update_complete( fd_quic_conn_t * conn ) {
    2067             :   /* Key updates are only possible for 1-RTT packets, which are appdata */
    2068           0 :   ulong const enc_level = fd_quic_enc_level_appdata_id;
    2069             : 
    2070             :   /* Update payload keys */
    2071           0 :   memcpy( conn->keys[enc_level][0].pkt_key, conn->new_keys[0].pkt_key, FD_AES_128_KEY_SZ );
    2072           0 :   memcpy( conn->keys[enc_level][0].iv,      conn->new_keys[0].iv,      FD_AES_GCM_IV_SZ  );
    2073           0 :   memcpy( conn->keys[enc_level][1].pkt_key, conn->new_keys[1].pkt_key, FD_AES_128_KEY_SZ );
    2074           0 :   memcpy( conn->keys[enc_level][1].iv,      conn->new_keys[1].iv,      FD_AES_GCM_IV_SZ  );
    2075             : 
    2076             :   /* Update IVs */
    2077           0 :   memcpy( conn->secrets.secret[enc_level][0], conn->secrets.new_secret[0], FD_QUIC_SECRET_SZ );
    2078           0 :   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           0 :   conn->key_phase  = !conn->key_phase;
    2084           0 :   conn->key_update = 0;
    2085           0 :   fd_quic_key_update_derive1( conn );
    2086             : 
    2087           0 :   FD_DEBUG( FD_LOG_DEBUG(( "key update completed" )); )
    2088           0 : }
    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           0 :                            ulong      const tot_sz ) {
    2096           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
    2097             : 
    2098           0 :   if( !conn ) {
    2099           0 :     quic->metrics.pkt_no_conn_cnt[ fd_quic_enc_level_appdata_id ]++;
    2100           0 :     FD_DTRACE_PROBE_2( fd_quic_handle_v1_one_rtt_no_conn , state->now, pkt->pkt_number );
    2101           0 :     FD_DEBUG( FD_LOG_DEBUG(( "one_rtt failed: no connection found" )) );
    2102           0 :     return FD_QUIC_PARSE_FAIL;
    2103           0 :   }
    2104             : 
    2105           0 :   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           0 :   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           0 :   ulong pn_offset = 1UL + FD_QUIC_CONN_ID_SZ;
    2118             : 
    2119           0 :   pkt->enc_level = fd_quic_enc_level_appdata_id;
    2120             : 
    2121           0 : # if !FD_QUIC_DISABLE_CRYPTO
    2122           0 :   if( FD_UNLIKELY(
    2123           0 :         fd_quic_crypto_decrypt_hdr( cur_ptr, tot_sz,
    2124           0 :                                     pn_offset,
    2125           0 :                                     &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           0 : # endif /* !FD_QUIC_DISABLE_CRYPTO */
    2131             : 
    2132           0 :   uint pkt_number_sz = fd_quic_h0_pkt_num_len( cur_ptr[0] ) + 1u;
    2133           0 :   uint key_phase     = fd_quic_one_rtt_key_phase( cur_ptr[0] );
    2134             : 
    2135             :   /* reconstruct packet number */
    2136           0 :   ulong pktnum_comp = fd_quic_pktnum_decode( cur_ptr+pn_offset, pkt_number_sz );
    2137           0 :   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           0 :   int current_key_phase = conn->key_phase == key_phase;
    2144             : 
    2145           0 : # 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           0 :   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           0 :   if( FD_UNLIKELY(
    2152           0 :         fd_quic_crypto_decrypt( cur_ptr, tot_sz,
    2153           0 :                                 pn_offset,
    2154           0 :                                 pkt_number,
    2155           0 :                                 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           0 : # endif /* !FD_QUIC_DISABLE_CRYPTO */
    2162             : 
    2163             :   /* set packet number on the context */
    2164           0 :   pkt->pkt_number = pkt_number;
    2165             : 
    2166           0 :   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           0 :     fd_quic_key_update_complete( conn );
    2171           0 :   }
    2172             : 
    2173             :   /* handle frames */
    2174           0 :   ulong         payload_off = pn_offset + pkt_number_sz;
    2175           0 :   uchar const * frame_ptr   = cur_ptr + payload_off;
    2176           0 :   ulong         payload_sz  = tot_sz - pn_offset - pkt_number_sz; /* includes auth tag */
    2177           0 :   if( FD_UNLIKELY( payload_sz<FD_QUIC_CRYPTO_TAG_SZ ) ) return FD_QUIC_PARSE_FAIL;
    2178           0 :   ulong         frame_sz    = payload_sz - FD_QUIC_CRYPTO_TAG_SZ; /* total size of all frames in packet */
    2179           0 :   while( frame_sz != 0UL ) {
    2180           0 :     ulong rc = fd_quic_handle_v1_frame(
    2181           0 :         quic, conn, pkt, FD_QUIC_PKT_TYPE_ONE_RTT,
    2182           0 :         frame_ptr, frame_sz );
    2183           0 :     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           0 :     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           0 :     frame_ptr += rc;
    2197           0 :     frame_sz  -= rc;
    2198           0 :   }
    2199             : 
    2200             :   /* update last activity */
    2201           0 :   conn->last_activity = state->now;
    2202             : 
    2203             :   /* update expected packet number */
    2204           0 :   conn->exp_pkt_number[2] = fd_ulong_max( conn->exp_pkt_number[2], pkt_number+1UL );
    2205             : 
    2206           0 :   return tot_sz;
    2207           0 : }
    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           0 :                                 ulong           cur_sz ) {
    2217             : 
    2218             :   /* bounds check packet size */
    2219           0 :   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           0 :   if( FD_UNLIKELY( cur_sz > 1500 ) ) {
    2224           0 :     quic->metrics.pkt_oversz_cnt++;
    2225           0 :     return FD_QUIC_PARSE_FAIL;
    2226           0 :   }
    2227             : 
    2228           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
    2229           0 :   fd_quic_conn_t *  conn  = NULL;
    2230             : 
    2231             : 
    2232             :   /* keep end */
    2233           0 :   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           0 :   uchar hdr_form = fd_quic_h0_hdr_form( *cur_ptr );
    2240           0 :   ulong rc;
    2241             : 
    2242           0 :   if( hdr_form ) { /* long header */
    2243           0 :     fd_quic_long_hdr_t long_hdr[1];
    2244           0 :     rc = fd_quic_decode_long_hdr( long_hdr, cur_ptr+1, cur_sz-1 );
    2245           0 :     if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
    2246           0 :       FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_decode_long_hdr failed" )); )
    2247           0 :       quic->metrics.pkt_quic_hdr_err_cnt++;
    2248           0 :       return FD_QUIC_PARSE_FAIL;
    2249           0 :     }
    2250             : 
    2251           0 :     fd_quic_conn_id_t dcid = fd_quic_conn_id_new( long_hdr->dst_conn_id, long_hdr->dst_conn_id_len );
    2252           0 :     if( dcid.sz == FD_QUIC_CONN_ID_SZ ) {
    2253           0 :       conn = fd_quic_conn_query( state->conn_map, fd_ulong_load_8( dcid.conn_id ) );
    2254           0 :     }
    2255           0 :     fd_quic_conn_id_t scid = fd_quic_conn_id_new( long_hdr->src_conn_id, long_hdr->src_conn_id_len );
    2256             : 
    2257           0 :     uchar long_packet_type = fd_quic_h0_long_packet_type( *cur_ptr );
    2258             : 
    2259             :     /* encryption level matches that of TLS */
    2260           0 :     pkt->enc_level = long_packet_type; /* V2 uses an indirect mapping */
    2261             : 
    2262             :     /* initialize packet number to unused value */
    2263           0 :     pkt->pkt_number = FD_QUIC_PKT_NUM_UNUSED;
    2264             : 
    2265           0 :     switch( long_packet_type ) {
    2266           0 :       case FD_QUIC_PKT_TYPE_INITIAL:
    2267           0 :         rc = fd_quic_handle_v1_initial( quic, &conn, pkt, &dcid, &scid, cur_ptr, cur_sz );
    2268           0 :         if( FD_UNLIKELY( !conn ) ) {
    2269             :           /* FIXME not really a fail - Could be a retry */
    2270           0 :           return FD_QUIC_PARSE_FAIL;
    2271           0 :         }
    2272           0 :         break;
    2273           0 :       case FD_QUIC_PKT_TYPE_HANDSHAKE:
    2274           0 :         rc = fd_quic_handle_v1_handshake( quic, conn, pkt, cur_ptr, cur_sz );
    2275           0 :         break;
    2276           0 :       case FD_QUIC_PKT_TYPE_RETRY:
    2277           0 :         rc = fd_quic_handle_v1_retry( quic, conn, pkt, cur_ptr, cur_sz );
    2278           0 :         break;
    2279           0 :       case FD_QUIC_PKT_TYPE_ZERO_RTT:
    2280           0 :         rc = fd_quic_handle_v1_zero_rtt( quic, conn, pkt, cur_ptr, cur_sz );
    2281           0 :         break;
    2282           0 :     }
    2283             : 
    2284           0 :     fd_quic_svc_timers_schedule( state->svc_timers, conn, state->now );
    2285             : 
    2286           0 :     if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
    2287           0 :       FD_DEBUG( FD_LOG_DEBUG(( "Rejected packet (type=%d)", long_packet_type )); )
    2288           0 :       return FD_QUIC_PARSE_FAIL;
    2289           0 :     }
    2290             : 
    2291           0 :   } else { /* short header */
    2292             :     /* encryption level of short header packets is fd_quic_enc_level_appdata_id */
    2293           0 :     pkt->enc_level = fd_quic_enc_level_appdata_id;
    2294             : 
    2295             :     /* initialize packet number to unused value */
    2296           0 :     pkt->pkt_number = FD_QUIC_PKT_NUM_UNUSED;
    2297             : 
    2298             :     /* find connection id */
    2299           0 :     ulong dst_conn_id = fd_ulong_load_8( cur_ptr+1 );
    2300           0 :     conn = fd_quic_conn_query( state->conn_map, dst_conn_id );
    2301           0 :     rc = fd_quic_handle_v1_one_rtt( quic, conn, pkt, cur_ptr, cur_sz );
    2302             : 
    2303           0 :     fd_quic_svc_timers_schedule( state->svc_timers, conn, state->now );
    2304             : 
    2305           0 :     if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
    2306           0 :       return FD_QUIC_PARSE_FAIL;
    2307           0 :     }
    2308           0 :   }
    2309             : 
    2310           0 :   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           0 :   cur_ptr += rc;
    2315             : 
    2316             :   /* if we get here we parsed all the frames, so ack the packet */
    2317           0 :   int ack_type = fd_quic_lazy_ack_pkt( quic, conn, pkt );
    2318           0 :   quic->metrics.ack_tx[ ack_type ]++;
    2319             : 
    2320             :   /* fd_quic_lazy_ack_pkt may have prepped schedule */
    2321           0 :   fd_quic_svc_timers_schedule( state->svc_timers, conn, state->now );
    2322             : 
    2323           0 :   if( pkt->rtt_ack_time ) {
    2324           0 :     fd_quic_sample_rtt( conn, (long)pkt->rtt_ack_time, (long)pkt->rtt_ack_delay );
    2325           0 :   }
    2326             : 
    2327             :   /* return bytes consumed */
    2328           0 :   return (ulong)( cur_ptr - orig_ptr );
    2329           0 : }
    2330             : 
    2331             : 
    2332             : /* version negotiation packet has version 0 */
    2333             : static inline int
    2334           0 : is_version_invalid( fd_quic_t * quic, uint version ) {
    2335           0 :   if( version == 0 ) {
    2336             :     /* TODO implement version negotiation */
    2337           0 :     quic->metrics.pkt_verneg_cnt++;
    2338           0 :     FD_DEBUG( FD_LOG_DEBUG(( "Got version negotiation packet" )) );
    2339           0 :     return 1;
    2340           0 :   }
    2341             : 
    2342             :   /* 0x?a?a?a?au is intended to force version negotiation
    2343             :       TODO implement */
    2344           0 :   if( ( version & 0x0a0a0a0au ) == 0x0a0a0a0au ) {
    2345             :     /* at present, ignore */
    2346           0 :     quic->metrics.pkt_verneg_cnt++;
    2347           0 :     FD_DEBUG( FD_LOG_DEBUG(( "Got version negotiation packet (forced)" )) );
    2348           0 :     return 1;
    2349           0 :   }
    2350             : 
    2351           0 :   if( version != 1 ) {
    2352             :     /* cannot interpret length, so discard entire packet */
    2353             :     /* TODO send version negotiation */
    2354           0 :     quic->metrics.pkt_verneg_cnt++;
    2355           0 :     FD_DEBUG( FD_LOG_DEBUG(( "Got unknown version QUIC packet" )) );
    2356           0 :     return 1;
    2357           0 :   }
    2358           0 :   return 0;
    2359           0 : }
    2360             : 
    2361             : static inline void
    2362             : fd_quic_process_packet_impl( fd_quic_t * quic,
    2363             :                              uchar *     data,
    2364             :                              ulong       data_sz,
    2365           0 :                              long        now ) {
    2366           0 :   fd_quic_get_state( quic )->now = now;
    2367           0 :   quic->metrics.net_rx_byte_cnt += data_sz;
    2368           0 :   quic->metrics.net_rx_pkt_cnt++;
    2369             : 
    2370           0 :   ulong rc = 0;
    2371             : 
    2372             :   /* holds the remainder of the packet*/
    2373           0 :   uchar * cur_ptr = data;
    2374           0 :   ulong   cur_sz  = data_sz;
    2375             : 
    2376           0 :   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           0 :   fd_quic_pkt_t pkt = { .datagram_sz = (uint)data_sz };
    2383             : 
    2384           0 :   pkt.rcv_time       = now;
    2385           0 :   pkt.rtt_pkt_number = 0;
    2386           0 :   pkt.rtt_ack_time   = 0;
    2387             : 
    2388             :   /* parse ip, udp */
    2389             : 
    2390           0 :   rc = fd_quic_decode_ip4( pkt.ip4, cur_ptr, cur_sz );
    2391           0 :   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           0 :   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           0 :   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           0 :   cur_ptr += rc;
    2418           0 :   cur_sz  -= rc;
    2419             : 
    2420           0 :   rc = fd_quic_decode_udp( pkt.udp, cur_ptr, cur_sz );
    2421           0 :   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           0 :   if( FD_UNLIKELY( pkt.udp->net_len < sizeof(fd_udp_hdr_t) ||
    2431           0 :                    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           0 :   cur_ptr += rc;
    2440           0 :   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           0 :   if( FD_UNLIKELY( cur_sz < FD_QUIC_SHORTEST_PKT ) ) {
    2453           0 :     FD_DTRACE_PROBE( quic_err_rx_net_hdr );
    2454           0 :     quic->metrics.pkt_net_hdr_err_cnt++;
    2455           0 :     FD_DEBUG( FD_LOG_DEBUG(( "Undersize QUIC packet" )) );
    2456           0 :     return;
    2457           0 :   }
    2458             : 
    2459           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
    2460             : 
    2461             :   /* short packets don't have version */
    2462           0 :   int long_pkt = !!( (uint)cur_ptr[0] & 0x80u );
    2463             : 
    2464           0 :   if( long_pkt ) {
    2465             :     /* version at offset 1..4 */
    2466           0 :     uint version = fd_uint_bswap( FD_LOAD( uint, cur_ptr + 1 ) );
    2467             :     /* we only support version 1 */
    2468           0 :     if( FD_UNLIKELY( is_version_invalid( quic, version ) ) ) {
    2469           0 :       return;
    2470           0 :     }
    2471             : 
    2472             :     /* multiple QUIC packets in a UDP packet */
    2473             :     /* shortest valid quic payload? */
    2474           0 :     ulong pkt_idx;
    2475           0 :     for( pkt_idx=0UL; pkt_idx<FD_QUIC_PKT_COALESCE_LIMIT; pkt_idx++ ) {
    2476             :       /* Are we done? Omit short packet handling that follows */
    2477           0 :       if( FD_UNLIKELY( cur_sz < FD_QUIC_SHORTEST_PKT ) ) return;
    2478             : 
    2479             :       /* short packet requires different handling */
    2480           0 :       int short_pkt = !( (uint)cur_ptr[0] & 0x80u );
    2481             : 
    2482           0 :       if( FD_UNLIKELY( short_pkt ) ) break;
    2483             : 
    2484             :       /* check version */
    2485           0 :       uint cur_version = fd_uint_bswap( FD_LOAD( uint, cur_ptr + 1 ) );
    2486             : 
    2487           0 :       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           0 :       rc = fd_quic_process_quic_packet_v1( quic, &pkt, cur_ptr, cur_sz );
    2502           0 :       svc_cnt_eq_alloc_conn( state->svc_timers, quic );
    2503             : 
    2504             :       /* 0UL means no progress, so fail */
    2505           0 :       if( FD_UNLIKELY( ( rc == FD_QUIC_PARSE_FAIL ) |
    2506           0 :                        ( rc == 0UL ) ) ) {
    2507           0 :         FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_process_quic_packet_v1 failed (stuck=%d)", rc==0UL )) );
    2508           0 :         return;
    2509           0 :       }
    2510             : 
    2511           0 :       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           0 :       cur_sz  -= rc;
    2518           0 :       cur_ptr += rc;
    2519           0 :     }
    2520           0 :     if( pkt_idx==FD_QUIC_PKT_COALESCE_LIMIT ) {
    2521             :       /* too many packets in a single udp datagram */
    2522           0 :       return;
    2523           0 :     }
    2524           0 :   }
    2525             : 
    2526             :   /* above can drop out of loop if a short packet is detected */
    2527           0 :   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           0 :   fd_quic_process_quic_packet_v1( quic, &pkt, cur_ptr, cur_sz );
    2532           0 :   svc_cnt_eq_alloc_conn( state->svc_timers, quic );
    2533           0 : }
    2534             : 
    2535             : void
    2536             : fd_quic_process_packet( fd_quic_t  *  quic,
    2537             :                         uchar      *  data,
    2538             :                         ulong         data_sz,
    2539           0 :                         long          now ) {
    2540           0 :   long now_ticks = fd_tickcount();
    2541           0 :   fd_quic_process_packet_impl( quic, data, data_sz, now );
    2542           0 :   long delta_ticks = fd_tickcount() - now_ticks;
    2543           0 :   fd_histf_sample( quic->metrics.receive_duration, (ulong)delta_ticks );
    2544           0 : }
    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           0 :                         int                       flush ) {
    2553           0 :   (void)flush;
    2554             : 
    2555           0 :   fd_quic_t * quic = context;
    2556           0 :   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           0 :   for( ulong j = 0; j < batch_cnt; ++j ) {
    2562           0 :     fd_quic_process_packet( quic, batch[ j ].buf, batch[ j ].buf_sz, now );
    2563           0 :   }
    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           0 :   if( FD_LIKELY( opt_batch_idx ) ) {
    2569           0 :     *opt_batch_idx = batch_cnt;
    2570           0 :   }
    2571             : 
    2572           0 :   return FD_AIO_SUCCESS;
    2573           0 : }
    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           0 :                        fd_quic_tls_secret_t const * secret ) {
    2593             : 
    2594           0 :   fd_quic_conn_t *  conn   = (fd_quic_conn_t*)context;
    2595           0 :   fd_quic_t *       quic   = conn->quic;
    2596             : 
    2597             :   /* look up suite */
    2598             :   /* set secrets */
    2599           0 :   FD_TEST( secret->enc_level < FD_QUIC_NUM_ENC_LEVELS );
    2600             : 
    2601           0 :   uint enc_level = secret->enc_level;
    2602             : 
    2603           0 :   fd_quic_crypto_secrets_t * crypto_secret = &conn->secrets;
    2604             : 
    2605           0 :   memcpy( crypto_secret->secret[enc_level][0], secret->read_secret,  FD_QUIC_SECRET_SZ );
    2606           0 :   memcpy( crypto_secret->secret[enc_level][1], secret->write_secret, FD_QUIC_SECRET_SZ );
    2607             : 
    2608           0 :   conn->keys_avail = fd_uint_set_bit( conn->keys_avail, (int)enc_level );
    2609             : 
    2610             :   /* gen local keys */
    2611           0 :   fd_quic_gen_keys(
    2612           0 :       &conn->keys[enc_level][0],
    2613           0 :       conn->secrets.secret[enc_level][0] );
    2614             : 
    2615             :   /* gen peer keys */
    2616           0 :   fd_quic_gen_keys(
    2617           0 :       &conn->keys[enc_level][1],
    2618           0 :       conn->secrets.secret[enc_level][1] );
    2619             : 
    2620           0 :   if( enc_level==fd_quic_enc_level_appdata_id ) {
    2621           0 :     fd_quic_key_update_derive( &conn->secrets, conn->new_keys );
    2622           0 :   }
    2623             : 
    2624             :   /* Key logging */
    2625             : 
    2626           0 :   void *                  keylog_ctx = quic->cb.quic_ctx;
    2627           0 :   fd_quic_cb_tls_keylog_t keylog_fn  = quic->cb.tls_keylog;
    2628           0 :   if( FD_UNLIKELY( keylog_fn ) ) {
    2629             :     /* Ignore stdout, stderr, stdin */
    2630             : 
    2631           0 :     uchar const * recv_secret = secret->read_secret;
    2632           0 :     uchar const * send_secret = secret->write_secret;
    2633             : 
    2634           0 :     uchar const * client_secret = hs->is_server ? recv_secret : send_secret;
    2635           0 :     uchar const * server_secret = hs->is_server ? send_secret : recv_secret;
    2636             : 
    2637           0 :     char buf[256];
    2638           0 :     char * s;
    2639           0 :     switch( enc_level ) {
    2640           0 :     case FD_TLS_LEVEL_HANDSHAKE:
    2641           0 :       /*     0 chars */ s = fd_cstr_init( buf );
    2642           0 :       /*  0+32 chars */ s = fd_cstr_append_cstr( s, "CLIENT_HANDSHAKE_TRAFFIC_SECRET " );
    2643           0 :       /* 32+64 chars */ s = fd_hex_encode( s, hs->hs.base.client_random, 32UL );
    2644           0 :       /* 96+ 1 chars */ s = fd_cstr_append_char( s, ' ' );
    2645           0 :       /* 97+64 chars */ s = fd_hex_encode( s, client_secret, 32UL );
    2646           0 :       /*   161 chars */     fd_cstr_fini( s );
    2647           0 :       keylog_fn( keylog_ctx, buf );
    2648           0 :       /*     0 chars */ s = fd_cstr_init( buf );
    2649           0 :       /*  0+32 chars */ s = fd_cstr_append_cstr( s, "SERVER_HANDSHAKE_TRAFFIC_SECRET " );
    2650           0 :       /* 32+64 chars */ s = fd_hex_encode( s, hs->hs.base.client_random, 32UL );
    2651           0 :       /* 96+ 1 chars */ s = fd_cstr_append_char( s, ' ' );
    2652           0 :       /* 97+64 chars */ s = fd_hex_encode( s, server_secret, 32UL );
    2653           0 :       /*   161 chars */     fd_cstr_fini( s );
    2654           0 :       keylog_fn( keylog_ctx, buf );
    2655           0 :       break;
    2656           0 :     case FD_TLS_LEVEL_APPLICATION:
    2657           0 :       /*     0 chars */ s = fd_cstr_init( buf );
    2658           0 :       /*  0+24 chars */ s = fd_cstr_append_cstr( s, "CLIENT_TRAFFIC_SECRET_0 " );
    2659           0 :       /* 24+64 chars */ s = fd_hex_encode( s, hs->hs.base.client_random, 32UL );
    2660           0 :       /* 88+ 1 chars */ s = fd_cstr_append_char( s, ' ' );
    2661           0 :       /* 89+64 chars */ s = fd_hex_encode( s, client_secret, 32UL );
    2662           0 :       /*   153 chars */     fd_cstr_fini( s );
    2663           0 :       keylog_fn( keylog_ctx, buf );
    2664           0 :       /*     0 chars */ s = fd_cstr_init( buf );
    2665           0 :       /*  0+24 chars */ s = fd_cstr_append_cstr( s, "SERVER_TRAFFIC_SECRET_0 " );
    2666           0 :       /* 24+64 chars */ s = fd_hex_encode( s, hs->hs.base.client_random, 32UL );
    2667           0 :       /* 88+ 1 chars */ s = fd_cstr_append_char( s, ' ' );
    2668           0 :       /* 89+64 chars */ s = fd_hex_encode( s, server_secret, 32UL );
    2669           0 :       /*   153 chars */     fd_cstr_fini( s );
    2670           0 :       keylog_fn( keylog_ctx, buf );
    2671           0 :       break;
    2672           0 :     }
    2673           0 :   }
    2674             : 
    2675           0 : }
    2676             : 
    2677             : void
    2678             : fd_quic_apply_peer_params( fd_quic_conn_t *                   conn,
    2679           0 :                            fd_quic_transport_params_t const * peer_tp ) {
    2680             :   /* flow control parameters */
    2681           0 :   conn->tx_max_data                   = peer_tp->initial_max_data;
    2682           0 :   conn->tx_initial_max_stream_data_uni= peer_tp->initial_max_stream_data_uni;
    2683             : 
    2684           0 :   if( !conn->server ) {
    2685             :     /* verify retry_src_conn_id */
    2686           0 :     uint retry_src_conn_id_sz = conn->retry_src_conn_id.sz;
    2687           0 :     if( retry_src_conn_id_sz ) {
    2688           0 :       if( FD_UNLIKELY( !peer_tp->retry_source_connection_id_present
    2689           0 :                         || peer_tp->retry_source_connection_id_len != retry_src_conn_id_sz
    2690           0 :                         || 0 != memcmp( peer_tp->retry_source_connection_id,
    2691           0 :                                         conn->retry_src_conn_id.conn_id,
    2692           0 :                                         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           0 :     } else {
    2697           0 :       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           0 :     }
    2702           0 :   }
    2703             : 
    2704             :   /* max datagram size */
    2705           0 :   ulong tx_max_datagram_sz = peer_tp->max_udp_payload_size;
    2706           0 :   if( tx_max_datagram_sz < FD_QUIC_INITIAL_PAYLOAD_SZ_MAX ) {
    2707           0 :     tx_max_datagram_sz = FD_QUIC_INITIAL_PAYLOAD_SZ_MAX;
    2708           0 :   }
    2709           0 :   if( tx_max_datagram_sz > FD_QUIC_INITIAL_PAYLOAD_SZ_MAX ) {
    2710           0 :     tx_max_datagram_sz = FD_QUIC_INITIAL_PAYLOAD_SZ_MAX;
    2711           0 :   }
    2712           0 :   conn->tx_max_datagram_sz = (uint)tx_max_datagram_sz;
    2713             : 
    2714             :   /* initial max_streams */
    2715             : 
    2716           0 :   if( conn->server ) {
    2717           0 :     conn->tx_sup_stream_id = ( (ulong)peer_tp->initial_max_streams_uni << 2UL ) + FD_QUIC_STREAM_TYPE_UNI_SERVER;
    2718           0 :   } else {
    2719           0 :     conn->tx_sup_stream_id = ( (ulong)peer_tp->initial_max_streams_uni << 2UL ) + FD_QUIC_STREAM_TYPE_UNI_CLIENT;
    2720           0 :   }
    2721             : 
    2722             :   /* set the max_idle_timeout to the min of our and peer max_idle_timeout */
    2723           0 :   if( peer_tp->max_idle_timeout_ms ) {
    2724           0 :     long peer_max_idle_timeout_ns = fd_long_sat_mul( (long)peer_tp->max_idle_timeout_ms, (long)1e6);
    2725           0 :     conn->idle_timeout_ns         = fd_long_min( peer_max_idle_timeout_ns, conn->idle_timeout_ns );
    2726           0 :   }
    2727             : 
    2728             :   /* set ack_delay_exponent so we can properly interpret peer's ack_delays
    2729             :      if unspecified, the value is 3 */
    2730           0 :   ulong peer_ack_delay_exponent = fd_ulong_if(
    2731           0 :                                     peer_tp->ack_delay_exponent_present,
    2732           0 :                                     peer_tp->ack_delay_exponent,
    2733           0 :                                     3UL );
    2734             : 
    2735           0 :   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           0 :   float peer_max_ack_delay_us = (float)fd_ulong_if(
    2740           0 :                                     peer_tp->max_ack_delay_present,
    2741           0 :                                     peer_tp->max_ack_delay * 1000UL,
    2742           0 :                                     25000UL );
    2743           0 :   conn->peer_max_ack_delay_ns = peer_max_ack_delay_us * 1e3f;
    2744             : 
    2745           0 :   conn->transport_params_set = 1;
    2746           0 : }
    2747             : 
    2748             : void
    2749             : fd_quic_tls_cb_peer_params( void *        context,
    2750             :                             uchar const * peer_tp_enc,
    2751           0 :                             ulong         peer_tp_enc_sz ) {
    2752           0 :   fd_quic_conn_t * conn = (fd_quic_conn_t*)context;
    2753             : 
    2754             :   /* decode peer transport parameters */
    2755           0 :   fd_quic_transport_params_t peer_tp[1] = {0};
    2756           0 :   int rc = fd_quic_decode_transport_params( peer_tp, peer_tp_enc, peer_tp_enc_sz );
    2757           0 :   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           0 :   fd_quic_apply_peer_params( conn, peer_tp );
    2765           0 : }
    2766             : 
    2767             : void
    2768             : fd_quic_tls_cb_handshake_complete( fd_quic_tls_hs_t * hs,
    2769           0 :                                    void *             context ) {
    2770           0 :   (void)hs;
    2771           0 :   fd_quic_conn_t * conn = (fd_quic_conn_t *)context;
    2772             : 
    2773             :   /* need to send quic handshake completion */
    2774           0 :   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           0 :     case FD_QUIC_CONN_STATE_HANDSHAKE:
    2782           0 :       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           0 :       conn->handshake_complete = 1;
    2788           0 :       fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_HANDSHAKE_COMPLETE );
    2789           0 :       return;
    2790             : 
    2791           0 :     default:
    2792           0 :       FD_LOG_WARNING(( "handshake in unexpected state: %u", conn->state ));
    2793           0 :   }
    2794           0 : }
    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           0 :                              ulong                    p_sz ) {
    2801             :   /* determine whether any of the data was already provided */
    2802           0 :   fd_quic_conn_t *   conn      = context->conn;
    2803           0 :   fd_quic_tls_hs_t * tls_hs    = conn->tls_hs;
    2804           0 :   uint               enc_level = context->pkt->enc_level;
    2805             : 
    2806             :   /* offset expected */
    2807           0 :   ulong rcv_off = crypto->offset;    /* in [0,2^62-1] */
    2808           0 :   ulong rcv_sz  = crypto->length;    /* in [0,2^62-1] */
    2809           0 :   ulong rcv_hi  = rcv_off + rcv_sz;  /* in [0,2^63-1] */
    2810             : 
    2811           0 :   if( FD_UNLIKELY( rcv_sz > p_sz ) ) {
    2812           0 :     fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
    2813           0 :     return FD_QUIC_PARSE_FAIL;
    2814           0 :   }
    2815             : 
    2816           0 :   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           0 :   if( enc_level < tls_hs->rx_enc_level ) {
    2823           0 :     return rcv_sz;
    2824           0 :   }
    2825             : 
    2826           0 :   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           0 :     tls_hs->rx_enc_level = (uchar)enc_level;
    2830           0 :     tls_hs->rx_off       = 0;
    2831           0 :     tls_hs->rx_sz        = 0;
    2832           0 :   }
    2833             : 
    2834           0 :   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           0 :   if( rcv_hi < tls_hs->rx_off ) {
    2840           0 :     return rcv_sz;
    2841           0 :   }
    2842             : 
    2843           0 :   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           0 :   tls_hs->rx_sz = (ushort)rcv_hi;
    2849           0 :   fd_memcpy( tls_hs->rx_hs_buf + rcv_off, p, rcv_sz );
    2850             : 
    2851           0 :   int provide_rc = fd_quic_tls_process( conn->tls_hs );
    2852           0 :   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           0 :     uint alert  = conn->tls_hs->alert;
    2859           0 :     uint reason = conn->tls_hs->hs.base.reason;
    2860           0 :     FD_DTRACE_PROBE_3( quic_handle_crypto_frame, conn->our_conn_id, alert, reason );
    2861           0 :     if( alert == 0u ) {
    2862           0 :       fd_quic_frame_error( context, FD_QUIC_CONN_REASON_INTERNAL_ERROR, __LINE__ );
    2863           0 :     } else {
    2864           0 :       FD_DEBUG(
    2865           0 :         FD_LOG_DEBUG(( "QUIC TLS handshake failed (alert %u-%s; reason %u-%s)",
    2866           0 :                        alert,  fd_tls_alert_cstr( alert ),
    2867           0 :                        reason, fd_tls_reason_cstr( reason ) ));
    2868           0 :       )
    2869           0 :       fd_quic_frame_error( context, FD_QUIC_CONN_REASON_CRYPTO_BASE + alert, __LINE__ );
    2870           0 :     }
    2871           0 :     return FD_QUIC_PARSE_FAIL;
    2872           0 :   }
    2873             : 
    2874           0 :   return rcv_sz;
    2875           0 : }
    2876             : 
    2877             : static int
    2878             : fd_quic_svc_poll( fd_quic_t *      quic,
    2879             :                   fd_quic_conn_t * conn,
    2880           0 :                   long             now ) {
    2881           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
    2882           0 :   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           0 :   if( FD_UNLIKELY( now >= conn->last_activity + ( conn->idle_timeout_ns / 2 ) ) ) {
    2890           0 :     if( FD_UNLIKELY( now >= conn->last_activity + conn->idle_timeout_ns ) ) {
    2891           0 :       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           0 :         FD_DEBUG( FD_LOG_WARNING(("%s  conn %p  conn_idx: %u  closing due to idle timeout=%gms last_activity=%ld now=%ld",
    2897           0 :             conn->server?"SERVER":"CLIENT",
    2898           0 :             (void *)conn, conn->conn_idx,
    2899           0 :             (double)conn->idle_timeout_ns / 1e6,
    2900           0 :             conn->last_activity,
    2901           0 :             now
    2902           0 :         )); )
    2903             : 
    2904           0 :         fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_DEAD );
    2905           0 :         quic->metrics.conn_timeout_cnt++;
    2906           0 :       }
    2907           0 :     } else if( quic->config.keep_alive & !!(conn->let_die_time_ns > now) ) {
    2908             :       /* send PING */
    2909           0 :       if( !( conn->flags & ( FD_QUIC_CONN_FLAGS_PING | FD_QUIC_CONN_FLAGS_PING_SENT ) ) ) {
    2910           0 :         conn->flags         |= FD_QUIC_CONN_FLAGS_PING;
    2911           0 :         conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;     /* update to be sent in next packet */
    2912           0 :       }
    2913           0 :     }
    2914           0 :   }
    2915             : 
    2916           0 :   if( FD_UNLIKELY( conn->state == FD_QUIC_CONN_STATE_DEAD ) ) {
    2917           0 :     fd_quic_cb_conn_final( quic, conn ); /* inform user before freeing */
    2918           0 :     fd_quic_conn_free( quic, conn );
    2919           0 :     return 1; /* do NOT reschedule freed connection */
    2920           0 :   }
    2921             : 
    2922             :   /* state cannot be DEAD here */
    2923           0 :   fd_quic_conn_service( quic, conn, now );
    2924             : 
    2925             :   /* dead? don't reinsert, just clean up */
    2926           0 :   switch( conn->state ) {
    2927           0 :   case FD_QUIC_CONN_STATE_INVALID:
    2928             :     /* skip entirely */
    2929           0 :     break;
    2930           0 :   case FD_QUIC_CONN_STATE_DEAD:
    2931           0 :     fd_quic_cb_conn_final( quic, conn ); /* inform user before freeing */
    2932           0 :     fd_quic_conn_free( quic, conn );
    2933           0 :     break;
    2934           0 :   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           0 :     long const timeout_ns    = conn->idle_timeout_ns;
    2941           0 :     long const last_activity = conn->last_activity;
    2942           0 :     int const  keep_alive    = quic->config.keep_alive & (now < last_activity+timeout_ns/2L);
    2943           0 :     fd_quic_svc_prep_schedule( conn, last_activity + (timeout_ns>>keep_alive) );
    2944           0 :     fd_quic_svc_timers_schedule( state->svc_timers, conn, state->now );
    2945           0 :     break;
    2946           0 :   }
    2947           0 :   }
    2948             : 
    2949           0 :   return 1;
    2950           0 : }
    2951             : 
    2952             : int
    2953             : fd_quic_service( fd_quic_t * quic,
    2954           0 :                  long        now ) {
    2955           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
    2956             : 
    2957           0 :   state->now = now;
    2958           0 :   long now_ticks = fd_tickcount();
    2959             : 
    2960           0 :   fd_quic_svc_timers_t * timers = state->svc_timers;
    2961           0 :   svc_cnt_eq_alloc_conn( timers, quic );
    2962           0 :   fd_quic_svc_event_t    next   = fd_quic_svc_timers_next( timers, now, 1 /* pop */);
    2963           0 :   if( FD_UNLIKELY( next.conn == NULL ) ) {
    2964           0 :     return 0;
    2965           0 :   }
    2966             : 
    2967           0 :   int cnt = fd_quic_svc_poll( quic, next.conn, now );
    2968             : 
    2969           0 :   long delta_ticks = fd_tickcount() - now_ticks;
    2970             : 
    2971           0 :   fd_histf_sample( quic->metrics.service_duration, (ulong)delta_ticks );
    2972             : 
    2973           0 :   return cnt;
    2974           0 : }
    2975             : 
    2976             : static inline ulong FD_FN_UNUSED
    2977           0 : fd_quic_conn_tx_buf_remaining( fd_quic_conn_t * conn ) {
    2978           0 :   return (ulong)( sizeof( conn->tx_buf_conn ) - (ulong)( conn->tx_ptr - conn->tx_buf_conn ) );
    2979           0 : }
    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           0 : ) {
    2999             : 
    3000             :   /* TODO leave space at front of tx_buf for header
    3001             :           then encode directly into it to avoid 1 copy */
    3002           0 :   uchar *tx_ptr = *tx_ptr_ptr;
    3003           0 :   long payload_sz = tx_ptr - tx_buf;
    3004             : 
    3005             :   /* nothing to do */
    3006           0 :   if( FD_UNLIKELY( payload_sz<=0L ) ) {
    3007           0 :     return 0u;
    3008           0 :   }
    3009             : 
    3010           0 :   fd_quic_config_t * config = &quic->config;
    3011           0 :   fd_quic_state_t *  state  = fd_quic_get_state( quic );
    3012             : 
    3013           0 :   uchar * const crypt_scratch = state->crypt_scratch;
    3014             : 
    3015           0 :   uchar * cur_ptr = state->crypt_scratch;
    3016           0 :   ulong   cur_sz  = sizeof( state->crypt_scratch );
    3017             : 
    3018             :   /* TODO much of this may be prepared ahead of time */
    3019           0 :   fd_quic_pkt_t pkt;
    3020             : 
    3021           0 :   pkt.ip4->verihl       = FD_IP4_VERIHL(4,5);
    3022           0 :   pkt.ip4->tos          = (uchar)(config->net.dscp << 2); /* could make this per-connection or per-stream */
    3023           0 :   pkt.ip4->net_tot_len  = (ushort)( 20 + 8 + payload_sz );
    3024           0 :   pkt.ip4->net_id       = *ipv4_id;
    3025           0 :   pkt.ip4->net_frag_off = 0x4000u; /* don't fragment */
    3026           0 :   pkt.ip4->ttl          = 64; /* TODO make configurable */
    3027           0 :   pkt.ip4->protocol     = FD_IP4_HDR_PROTOCOL_UDP;
    3028           0 :   pkt.ip4->check        = 0;
    3029           0 :   pkt.ip4->saddr        = src_ipv4_addr;
    3030           0 :   pkt.ip4->daddr        = dst_ipv4_addr;
    3031           0 :   pkt.udp->net_sport    = src_udp_port;
    3032           0 :   pkt.udp->net_dport    = dst_udp_port;
    3033           0 :   pkt.udp->net_len      = (ushort)( 8 + payload_sz );
    3034           0 :   pkt.udp->check        = 0x0000;
    3035           0 :   *ipv4_id = (ushort)( *ipv4_id + 1 );
    3036             : 
    3037           0 :   ulong rc = fd_quic_encode_ip4( cur_ptr, cur_sz, pkt.ip4 );
    3038           0 :   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           0 :   fd_ip4_hdr_t * ip4_encoded = (fd_ip4_hdr_t *)fd_type_pun( cur_ptr );
    3044           0 :   ip4_encoded->check = (ushort)fd_ip4_hdr_check_fast( ip4_encoded );
    3045             : 
    3046           0 :   cur_ptr += rc;
    3047           0 :   cur_sz  -= rc;
    3048             : 
    3049           0 :   rc = fd_quic_encode_udp( cur_ptr, cur_sz, pkt.udp );
    3050           0 :   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           0 :   cur_ptr += rc;
    3055           0 :   cur_sz  -= rc;
    3056             : 
    3057             :   /* need enough space for payload */
    3058           0 :   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           0 :   fd_memcpy( cur_ptr, tx_buf, (ulong)payload_sz );
    3066             : 
    3067           0 :   cur_ptr += (ulong)payload_sz;
    3068           0 :   cur_sz  -= (ulong)payload_sz;
    3069             : 
    3070           0 :   fd_aio_pkt_info_t aio_buf = { .buf = crypt_scratch, .buf_sz = (ushort)( cur_ptr - crypt_scratch ) };
    3071           0 :   int aio_rc = fd_aio_send( &quic->aio_tx, &aio_buf, 1, NULL, 1 );
    3072           0 :   if( aio_rc == FD_AIO_ERR_AGAIN ) {
    3073             :     /* transient condition - try later */
    3074           0 :     return FD_QUIC_FAILED;
    3075           0 :   } 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           0 :   *tx_ptr_ptr = tx_buf;
    3082             : 
    3083           0 :   quic->metrics.net_tx_pkt_cnt += aio_rc==FD_AIO_SUCCESS;
    3084           0 :   if( FD_LIKELY( aio_rc==FD_AIO_SUCCESS ) ) {
    3085           0 :     quic->metrics.net_tx_byte_cnt += aio_buf.buf_sz;
    3086           0 :   }
    3087             : 
    3088           0 :   return FD_QUIC_SUCCESS; /* success */
    3089           0 : }
    3090             : 
    3091             : uint
    3092             : fd_quic_tx_buffered( fd_quic_t *      quic,
    3093           0 :                      fd_quic_conn_t * conn ) {
    3094           0 :   fd_quic_net_endpoint_t const * endpoint = conn->peer;
    3095           0 :   return fd_quic_tx_buffered_raw(
    3096           0 :       quic,
    3097           0 :       &conn->tx_ptr,
    3098           0 :       conn->tx_buf_conn,
    3099           0 :       &conn->ipv4_id,
    3100           0 :       endpoint->ip_addr,
    3101           0 :       endpoint->udp_port,
    3102           0 :       conn->host.ip_addr,
    3103           0 :       conn->host.udp_port);
    3104           0 : }
    3105             : 
    3106             : static inline int
    3107             : fd_quic_conn_can_acquire_pkt_meta( fd_quic_conn_t             * conn,
    3108           0 :                                    fd_quic_pkt_meta_tracker_t * tracker ) {
    3109           0 :   fd_quic_state_t * state = fd_quic_get_state( conn->quic );
    3110           0 :   fd_quic_metrics_t * metrics = &conn->quic->metrics;
    3111             : 
    3112           0 :   ulong pool_free = fd_quic_pkt_meta_pool_free( tracker->pool );
    3113           0 :   if( !pool_free || conn->used_pkt_meta >= state->max_inflight_frame_cnt_conn ) {
    3114           0 :     if( !pool_free ) {
    3115           0 :       metrics->frame_tx_alloc_cnt[FD_METRICS_ENUM_FRAME_TX_ALLOC_RESULT_V_FAIL_EMPTY_POOL_IDX]++;
    3116           0 :     } else {
    3117           0 :       metrics->frame_tx_alloc_cnt[FD_METRICS_ENUM_FRAME_TX_ALLOC_RESULT_V_FAIL_CONN_MAX_IDX]++;
    3118           0 :     }
    3119           0 :     return 0;
    3120           0 :   }
    3121           0 :   metrics->frame_tx_alloc_cnt[FD_METRICS_ENUM_FRAME_TX_ALLOC_RESULT_V_SUCCESS_IDX]++;
    3122             : 
    3123           0 :   return 1;
    3124           0 : }
    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           0 :                                   fd_quic_conn_t             * conn ) {
    3137           0 :   if( !fd_quic_conn_can_acquire_pkt_meta( conn, tracker ) ) return 0;
    3138             : 
    3139           0 :   conn->used_pkt_meta++;
    3140           0 :   fd_quic_pkt_meta_t * pkt_meta = fd_quic_pkt_meta_pool_ele_acquire( tracker->pool );
    3141           0 :   *pkt_meta = *pkt_meta_tmpl;
    3142           0 :   FD_QUIC_PKT_META_SET_TYPE( pkt_meta, type );
    3143           0 :   pkt_meta->val = value;
    3144           0 :   fd_quic_pkt_meta_insert( &tracker->sent_pkt_metas[pkt_meta->enc_level], pkt_meta, tracker->pool );
    3145           0 :   return 1;
    3146           0 : }
    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           0 :                          fd_quic_pkt_meta_tracker_t * tracker ) {
    3154             : 
    3155           0 :   if( conn->flags & FD_QUIC_CONN_FLAGS_CLOSE_SENT ) return 0UL;
    3156           0 :   conn->flags |= FD_QUIC_CONN_FLAGS_CLOSE_SENT;
    3157             : 
    3158           0 :   ulong frame_sz;
    3159           0 :   if( conn->reason != 0u || conn->state == FD_QUIC_CONN_STATE_PEER_CLOSE ) {
    3160           0 :     fd_quic_conn_close_0_frame_t frame = {
    3161           0 :       .error_code           = conn->reason,
    3162           0 :       .frame_type           = 0u, /* we do not know the frame in question */
    3163           0 :       .reason_phrase_length = 0u  /* no reason phrase */
    3164           0 :     };
    3165           0 :     frame_sz = fd_quic_encode_conn_close_0_frame( payload_ptr,
    3166           0 :                                                   (ulong)( payload_end - payload_ptr ),
    3167           0 :                                                   &frame );
    3168           0 :   } else {
    3169           0 :     fd_quic_conn_close_1_frame_t frame = {
    3170           0 :       .error_code           = conn->app_reason,
    3171           0 :       .reason_phrase_length = 0u /* no reason phrase */
    3172           0 :     };
    3173           0 :     frame_sz = fd_quic_encode_conn_close_1_frame( payload_ptr,
    3174           0 :                                                   (ulong)( payload_end - payload_ptr ),
    3175           0 :                                                   &frame );
    3176           0 :   }
    3177             : 
    3178           0 :   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           0 :   if( !fd_quic_gen_frame_store_pkt_meta( pkt_meta_tmpl,
    3185           0 :                                          FD_QUIC_PKT_META_TYPE_CLOSE,
    3186           0 :                                          (fd_quic_pkt_meta_value_t){0}, /* value doesn't matter */
    3187           0 :                                          tracker,
    3188           0 :                                          conn )) return 0UL;
    3189             : 
    3190           0 :   return frame_sz;
    3191           0 : }
    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           0 :                               fd_quic_pkt_meta_tracker_t * tracker ) {
    3199           0 :   uint enc_level = pkt_meta_tmpl->enc_level;
    3200           0 :   fd_quic_tls_hs_data_t * hs_data = fd_quic_tls_get_hs_data( conn->tls_hs, enc_level );
    3201           0 :   if( !hs_data ) return payload_ptr;
    3202             : 
    3203             :   /* confirm we have pkt_meta space */
    3204           0 :   if( !fd_quic_conn_can_acquire_pkt_meta( conn, tracker ) ) return payload_ptr;
    3205             : 
    3206           0 :   ulong hs_offset   = 0; /* offset within the current hs_data */
    3207           0 :   ulong sent_offset = conn->hs_sent_bytes[enc_level];
    3208           0 :   ulong ackd_offset = conn->hs_ackd_bytes[enc_level];
    3209             :   /* offset within stream */
    3210           0 :   ulong offset = fd_ulong_max( sent_offset, ackd_offset );
    3211             : 
    3212             :   /* track pkt_meta values */
    3213           0 :   ulong offset_lo = offset;
    3214           0 :   ulong offset_hi = offset;
    3215             : 
    3216           0 :   while( hs_data ) {
    3217             :     /* skip data we've sent */
    3218           0 :     if( hs_data->offset + hs_data->data_sz <= offset ) {
    3219           0 :       hs_data = fd_quic_tls_get_next_hs_data( conn->tls_hs, hs_data );
    3220           0 :       continue;
    3221           0 :     }
    3222             : 
    3223           0 :     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           0 :     hs_offset = offset - hs_data->offset;
    3232             : 
    3233             :     /* handshake data to send */
    3234           0 :     uchar const * cur_data    = hs_data->data    + hs_offset;
    3235           0 :     ulong         cur_data_sz = hs_data->data_sz - hs_offset;
    3236             : 
    3237             :     /* 9 bytes header + cur_data_sz */
    3238           0 :     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           0 :     payload_ptr[0] = 0x06; /* CRYPTO frame */
    3243           0 :     uint offset_varint = 0x80U | ( fd_uint_bswap( (uint)offset      & 0x3fffffffU ) );
    3244           0 :     uint length_varint = 0x80U | ( fd_uint_bswap( (uint)cur_data_sz & 0x3fffffffU ) );
    3245           0 :     FD_STORE( uint, payload_ptr+1, offset_varint );
    3246           0 :     FD_STORE( uint, payload_ptr+5, length_varint );
    3247           0 :     payload_ptr += 9;
    3248             : 
    3249           0 :     fd_memcpy( payload_ptr, cur_data, cur_data_sz );
    3250           0 :     payload_ptr += cur_data_sz;
    3251             : 
    3252             :     /* update pkt_meta values */
    3253           0 :     offset_hi += cur_data_sz;
    3254             : 
    3255             :     /* move to next hs_data */
    3256           0 :     offset     += cur_data_sz;
    3257           0 :     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           0 :   }
    3262             : 
    3263             :   /* update packet meta */
    3264           0 :   if( offset_hi > offset_lo ) {
    3265           0 :     fd_quic_gen_frame_store_pkt_meta( pkt_meta_tmpl,
    3266           0 :                                       FD_QUIC_PKT_META_TYPE_HS_DATA,
    3267           0 :                                       (fd_quic_pkt_meta_value_t){
    3268           0 :                                         .range = {
    3269           0 :                                           .offset_lo = offset_lo,
    3270           0 :                                           .offset_hi = offset_hi
    3271           0 :                                         }
    3272           0 :                                       },
    3273           0 :                                       tracker,
    3274           0 :                                       conn );
    3275           0 :   }
    3276             : 
    3277           0 :   return payload_ptr;
    3278           0 : }
    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           0 :                                   fd_quic_pkt_meta_tracker_t * tracker ) {
    3286           0 :   FD_DTRACE_PROBE_1( quic_gen_handshake_done_frame, conn->our_conn_id );
    3287           0 :   if( conn->handshake_done_send==0 ) return 0UL;
    3288           0 :   conn->handshake_done_send = 0;
    3289           0 :   if( FD_UNLIKELY( conn->handshake_done_ackd  ) ) return 0UL;
    3290           0 :   if( FD_UNLIKELY( payload_ptr >= payload_end ) ) return 0UL;
    3291             :   /* send handshake done frame */
    3292           0 :   payload_ptr[0] = 0x1E;
    3293             : 
    3294             :   /* record the send for retx */
    3295           0 :   if( !fd_quic_gen_frame_store_pkt_meta( pkt_meta_tmpl,
    3296           0 :                                          FD_QUIC_PKT_META_TYPE_HS_DONE,
    3297           0 :                                          (fd_quic_pkt_meta_value_t){0}, /* value doesn't matter */
    3298           0 :                                          tracker,
    3299           0 :                                          conn) ) return 0UL;
    3300             : 
    3301           0 :   return 1UL;
    3302           0 : }
    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           0 :                             fd_quic_pkt_meta_tracker_t * tracker ) {
    3310           0 :   fd_quic_conn_stream_rx_t * srx = conn->srx;
    3311             : 
    3312           0 :   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           0 :                                fd_quic_pkt_meta_tracker_t * tracker ) {
    3343           0 :   fd_quic_conn_stream_rx_t * srx = conn->srx;
    3344             : 
    3345             :   /* 0x02 Client-Initiated, Unidirectional
    3346             :      0x03 Server-Initiated, Unidirectional */
    3347           0 :   ulong max_streams_unidir = srx->rx_sup_stream_id >> 2;
    3348             : 
    3349           0 :   uint flags = conn->flags;
    3350           0 :   if( !FD_QUIC_MAX_STREAMS_ALWAYS_UNLESS_ACKED ) {
    3351           0 :     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           0 :                         fd_quic_pkt_meta_tracker_t * tracker ) {
    3381             : 
    3382           0 :   if( ~conn->flags & FD_QUIC_CONN_FLAGS_PING       ) return 0UL;
    3383           0 :   if(  conn->flags & FD_QUIC_CONN_FLAGS_PING_SENT  ) return 0UL;
    3384             : 
    3385           0 :   fd_quic_ping_frame_t ping = {0};
    3386           0 :   ulong frame_sz = fd_quic_encode_ping_frame( payload_ptr,
    3387           0 :       (ulong)( payload_end - payload_ptr ),
    3388           0 :       &ping );
    3389           0 :   if( FD_UNLIKELY( frame_sz==FD_QUIC_ENCODE_FAIL ) ) return 0UL;
    3390           0 :   conn->flags |= FD_QUIC_CONN_FLAGS_PING_SENT;
    3391           0 :   conn->flags &= ~FD_QUIC_CONN_FLAGS_PING;
    3392             : 
    3393           0 :   conn->upd_pkt_number = pkt_meta_tmpl->key.pkt_num;
    3394             :   /* record the send for retx, 0 if fail */
    3395           0 :   if( !fd_quic_gen_frame_store_pkt_meta( pkt_meta_tmpl,
    3396           0 :                                          FD_QUIC_PKT_META_TYPE_PING,
    3397           0 :                                          (fd_quic_pkt_meta_value_t){0}, /* value doesn't matter */
    3398           0 :                                          tracker,
    3399           0 :                                          conn ) ) return 0UL;
    3400             : 
    3401           0 :   return frame_sz;
    3402           0 : }
    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           0 :                            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           0 :   fd_quic_stream_t * sentinel   = conn->send_streams;
    3415           0 :   fd_quic_stream_t * cur_stream = sentinel->next;
    3416           0 :   ulong pkt_num = pkt_meta_tmpl->key.pkt_num;
    3417           0 :   while( !cur_stream->sentinel ) {
    3418             :     /* required, since cur_stream may get removed from list */
    3419           0 :     fd_quic_stream_t * nxt_stream = cur_stream->next;
    3420           0 :     _Bool sent_all_data = 1u;
    3421             : 
    3422           0 :     if( cur_stream->upd_pkt_number >= pkt_num ) {
    3423             : 
    3424             :       /* any stream data? */
    3425           0 :       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           0 :         ulong const data_avail = cur_stream->tx_buf.head - cur_stream->tx_sent;
    3430           0 :         int   const fin_flag_set  = !!(cur_stream->state & FD_QUIC_STREAM_STATE_TX_FIN);
    3431           0 :         ulong const stream_id  = cur_stream->stream_id;
    3432           0 :         ulong const stream_off = cur_stream->tx_sent;
    3433             : 
    3434             :         /* No information to send? */
    3435           0 :         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           0 :         if( payload_ptr+FD_QUIC_MAX_FOOTPRINT( stream_e_frame )+1 > payload_end ) break;
    3440             : 
    3441             :         /* check pkt_meta availability */
    3442           0 :         if( !fd_quic_conn_can_acquire_pkt_meta( conn, tracker ) ) break;
    3443             : 
    3444             :         /* Leave placeholder for frame/stream type */
    3445           0 :         uchar * const frame_type_p = payload_ptr++;
    3446           0 :         uint          frame_type   = 0x0a; /* stream frame with length */
    3447             : 
    3448             :         /* Encode stream ID */
    3449           0 :         payload_ptr += fd_quic_varint_encode( payload_ptr, stream_id );
    3450             : 
    3451             :         /* Optionally encode offset */
    3452           0 :         if( stream_off>0 ) {
    3453           0 :           frame_type |= 0x04; /* with offset field */
    3454           0 :           payload_ptr += fd_quic_varint_encode( payload_ptr, stream_off );
    3455           0 :         }
    3456             : 
    3457             :         /* Leave placeholder for length length */
    3458           0 :         uchar * data_sz_p = payload_ptr;
    3459           0 :         payload_ptr += 2;
    3460             : 
    3461             :         /* Stream metadata */
    3462           0 :         ulong  data_max      = (ulong)payload_end - (ulong)payload_ptr;  /* assume no underflow */
    3463           0 :         ulong  data_sz       = fd_ulong_min( data_avail, data_max );
    3464           0 :         /* */  data_sz       = fd_ulong_min( data_sz, 0x3fffUL );       /* max 2 byte varint */
    3465           0 :         /* */  sent_all_data = data_sz == data_avail;
    3466           0 :         _Bool  fin           = fin_flag_set && sent_all_data;
    3467             : 
    3468             :         /* Finish encoding stream header */
    3469           0 :         ushort data_sz_varint = fd_ushort_bswap( (ushort)( 0x4000u | (uint)data_sz ) );
    3470           0 :         FD_STORE( ushort, data_sz_p, data_sz_varint );
    3471           0 :         frame_type |= fin;
    3472           0 :         *frame_type_p = (uchar)frame_type;
    3473             : 
    3474             :         /* Write stream payload */
    3475           0 :         fd_quic_buffer_t * tx_buf = &cur_stream->tx_buf;
    3476           0 :         fd_quic_buffer_load( tx_buf, stream_off, payload_ptr, data_sz );
    3477           0 :         payload_ptr += data_sz;
    3478             : 
    3479             :         /* Update stream metadata */
    3480           0 :         cur_stream->tx_sent += data_sz;
    3481           0 :         cur_stream->upd_pkt_number = fd_ulong_if( fin, pkt_num, FD_QUIC_PKT_NUM_PENDING );
    3482           0 :         cur_stream->stream_flags &= fd_uint_if( fin, ~FD_QUIC_STREAM_FLAGS_ACTION, UINT_MAX );
    3483             : 
    3484             :         /* Packet metadata for potential retransmits */
    3485           0 :         pkt_meta_tmpl->key.stream_id = cur_stream->stream_id;
    3486           0 :         fd_quic_gen_frame_store_pkt_meta( pkt_meta_tmpl,
    3487           0 :                                           FD_QUIC_PKT_META_TYPE_STREAM,
    3488           0 :                                           (fd_quic_pkt_meta_value_t){
    3489           0 :                                             .range = {
    3490           0 :                                               .offset_lo = stream_off,
    3491           0 :                                               .offset_hi = stream_off + data_sz
    3492           0 :                                             }
    3493           0 :                                           },
    3494           0 :                                           tracker,
    3495           0 :                                           conn );
    3496           0 :       }
    3497           0 :     }
    3498             : 
    3499           0 :     if( sent_all_data ) {
    3500           0 :       cur_stream->stream_flags &= ~FD_QUIC_STREAM_FLAGS_ACTION;
    3501           0 :       FD_QUIC_STREAM_LIST_REMOVE( cur_stream );
    3502           0 :       FD_QUIC_STREAM_LIST_INSERT_BEFORE( conn->used_streams, cur_stream );
    3503           0 :     }
    3504             : 
    3505           0 :     cur_stream = nxt_stream;
    3506           0 :   }
    3507             : 
    3508           0 :   return payload_ptr;
    3509           0 : }
    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           0 :                     long                       now ) {
    3517             : 
    3518           0 :   uint closing = 0U;
    3519           0 :   switch( conn->state ) {
    3520           0 :   case FD_QUIC_CONN_STATE_PEER_CLOSE:
    3521           0 :   case FD_QUIC_CONN_STATE_ABORT:
    3522           0 :   case FD_QUIC_CONN_STATE_CLOSE_PENDING:
    3523           0 :     closing = 1u;
    3524           0 :   }
    3525             : 
    3526           0 :   fd_quic_pkt_meta_tracker_t * tracker = &conn->pkt_meta_tracker;
    3527             : 
    3528           0 :   payload_ptr = fd_quic_gen_ack_frames( conn->ack_gen, payload_ptr, payload_end, pkt_meta_tmpl->enc_level, now );
    3529           0 :   if( conn->ack_gen->head == conn->ack_gen->tail ) conn->unacked_sz = 0UL;
    3530             : 
    3531           0 :   if( FD_UNLIKELY( closing ) ) {
    3532           0 :     payload_ptr += fd_quic_gen_close_frame( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
    3533           0 :   } else {
    3534           0 :     payload_ptr = fd_quic_gen_handshake_frames( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
    3535           0 :     if( pkt_meta_tmpl->enc_level == fd_quic_enc_level_appdata_id ) {
    3536           0 :       payload_ptr += fd_quic_gen_handshake_done_frame( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
    3537           0 :       if( conn->upd_pkt_number >= pkt_meta_tmpl->key.pkt_num ) {
    3538           0 :         payload_ptr += fd_quic_gen_max_data_frame   ( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
    3539           0 :         payload_ptr += fd_quic_gen_max_streams_frame( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
    3540           0 :         payload_ptr += fd_quic_gen_ping_frame       ( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
    3541           0 :       }
    3542           0 :       if( FD_LIKELY( !conn->tls_hs ) ) {
    3543           0 :         payload_ptr = fd_quic_gen_stream_frames( conn, payload_ptr, payload_end, pkt_meta_tmpl, tracker );
    3544           0 :       }
    3545           0 :     }
    3546           0 :   }
    3547             : 
    3548           0 :   fd_quic_svc_prep_schedule( conn, pkt_meta_tmpl->expiry );
    3549             : 
    3550           0 :   return payload_ptr;
    3551           0 : }
    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           0 :                  fd_quic_conn_t * conn ) {
    3564             : 
    3565           0 :   if( FD_UNLIKELY( conn->state == FD_QUIC_CONN_STATE_DEAD ) ) return;
    3566             : 
    3567           0 :   fd_quic_state_t            * state   = fd_quic_get_state( quic );
    3568             : 
    3569             :   /* used for encoding frames into before encrypting */
    3570           0 :   uchar *  crypt_scratch    = state->crypt_scratch;
    3571           0 :   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           0 :   ulong tx_max_datagram_sz = conn->tx_max_datagram_sz;
    3576             : 
    3577           0 :   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           0 :   uint enc_level = fd_quic_tx_enc_level( conn, 1 /* acks */ );
    3595             : 
    3596             :   /* nothing to send / bad state? */
    3597           0 :   if( enc_level == ~0u ) return;
    3598             : 
    3599           0 :   int key_phase_upd = (int)conn->key_update;
    3600           0 :   uint key_phase    = conn->key_phase;
    3601           0 :   int key_phase_tx  = (int)key_phase ^ key_phase_upd;
    3602             : 
    3603             :   /* get time */
    3604           0 :   long now = state->now;
    3605             : 
    3606             :   /* initialize expiry and tx_time */
    3607           0 :   long expiry = now + fd_quic_calc_expiry_duration( conn, 0 /* use PTO */, conn->server );
    3608           0 :   fd_quic_pkt_meta_t pkt_meta_tmpl[1] = {{.expiry = expiry, .tx_time = now}};
    3609             : 
    3610           0 :   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           0 :     if( FD_UNLIKELY( (quic->config.role==FD_QUIC_ROLE_CLIENT) & (enc_level==fd_quic_enc_level_handshake_id) ) ) {
    3618           0 :       fd_quic_abandon_enc_level( conn, fd_quic_enc_level_initial_id );
    3619           0 :     }
    3620             : 
    3621           0 :     uint initial_pkt = 0;    /* is this the first initial packet? */
    3622             : 
    3623             :     /* remaining in datagram */
    3624             :     /* invariant: tx_ptr >= tx_buf */
    3625           0 :     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           0 :     uchar * cur_ptr = crypt_scratch;
    3634           0 :     ulong   cur_sz  = crypt_scratch_sz;
    3635             : 
    3636             :     /* TODO determine actual datagrams size to use */
    3637           0 :     cur_sz = fd_ulong_min( cur_sz, datagram_rem );
    3638             : 
    3639             :     /* determine pn_space */
    3640           0 :     uint pn_space             = fd_quic_enc_level_to_pn_space( enc_level );
    3641           0 :     pkt_meta_tmpl->pn_space   = (uchar)pn_space;
    3642           0 :     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           0 :     ulong pkt_number = conn->pkt_number[pn_space];
    3648           0 :     FD_QUIC_PKT_META_SET_PKT_NUM( pkt_meta_tmpl, pkt_number );
    3649             : 
    3650             :     /* are we the client initial packet? */
    3651           0 :     ulong hs_data_offset = conn->hs_sent_bytes[enc_level];
    3652           0 :     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           0 :     fd_quic_conn_id_t const * peer_conn_id = &conn->peer_cids[0];
    3656             : 
    3657             :     /* our current conn_id */
    3658           0 :     ulong conn_id = conn->our_conn_id;
    3659           0 :     uint const pkt_num_len = 4u; /* 4-byte packet number */
    3660           0 :     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           0 :     uchar * hdr_ptr = cur_ptr;
    3667           0 :     ulong   hdr_sz = 0UL;
    3668           0 :     uchar   _hdr_len_field[2]; /* if no len field exists, catch the write here */
    3669           0 :     uchar * hdr_len_field = _hdr_len_field;
    3670           0 :     switch( enc_level ) {
    3671           0 :       case fd_quic_enc_level_initial_id: {
    3672           0 :         fd_quic_initial_t initial = {0};
    3673           0 :         initial.h0               = fd_quic_initial_h0( pkt_num_len_enc );
    3674           0 :         initial.version          = 1;
    3675           0 :         initial.dst_conn_id_len  = peer_conn_id->sz;
    3676             :         // .dst_conn_id
    3677           0 :         initial.src_conn_id_len  = FD_QUIC_CONN_ID_SZ;
    3678             :         // .src_conn_id
    3679             :         // .token - below
    3680           0 :         initial.len              = 0x3fff; /* use 2 byte varint encoding */
    3681           0 :         initial.pkt_num          = pkt_number;
    3682             : 
    3683           0 :         fd_memcpy( initial.dst_conn_id, peer_conn_id->conn_id, peer_conn_id->sz   );
    3684           0 :         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           0 :         initial.token = conn->token;
    3688           0 :         if( conn->quic->config.role == FD_QUIC_ROLE_CLIENT && conn->token_len ) {
    3689           0 :           initial.token_len = conn->token_len;
    3690           0 :         } else {
    3691           0 :           initial.token_len = 0;
    3692           0 :         }
    3693             : 
    3694           0 :         hdr_sz = fd_quic_encode_initial( cur_ptr, cur_sz, &initial );
    3695           0 :         hdr_len_field = cur_ptr + hdr_sz - 6; /* 2 byte len, 4 byte packet number */
    3696           0 :         FD_DTRACE_PROBE_2( quic_encode_initial, initial.src_conn_id, initial.dst_conn_id );
    3697           0 :         break;
    3698           0 :       }
    3699             : 
    3700           0 :       case fd_quic_enc_level_handshake_id: {
    3701           0 :         fd_quic_handshake_t handshake = {0};
    3702           0 :         handshake.h0      = fd_quic_handshake_h0( pkt_num_len_enc );
    3703           0 :         handshake.version = 1;
    3704             : 
    3705             :         /* destination */
    3706           0 :         fd_memcpy( handshake.dst_conn_id, peer_conn_id->conn_id, peer_conn_id->sz );
    3707           0 :         handshake.dst_conn_id_len = peer_conn_id->sz;
    3708             : 
    3709             :         /* source */
    3710           0 :         FD_STORE( ulong, handshake.src_conn_id, conn_id );
    3711           0 :         handshake.src_conn_id_len = sizeof(ulong);
    3712             : 
    3713           0 :         handshake.len             = 0x3fff; /* use 2 byte varint encoding */
    3714           0 :         handshake.pkt_num         = pkt_number;
    3715             : 
    3716           0 :         hdr_sz = fd_quic_encode_handshake( cur_ptr, cur_sz, &handshake );
    3717           0 :         hdr_len_field = cur_ptr + hdr_sz - 6; /* 2 byte len, 4 byte packet number */
    3718           0 :         FD_DTRACE_PROBE_2( quic_encode_handshake, handshake.src_conn_id, handshake.dst_conn_id );
    3719           0 :         break;
    3720           0 :       }
    3721             : 
    3722           0 :       case fd_quic_enc_level_appdata_id:
    3723           0 :       {
    3724           0 :         fd_quic_one_rtt_t one_rtt = {0};
    3725           0 :         one_rtt.h0 = fd_quic_one_rtt_h0( /* spin */ 0, !!key_phase_tx, pkt_num_len_enc );
    3726             : 
    3727             :         /* destination */
    3728           0 :         fd_memcpy( one_rtt.dst_conn_id, peer_conn_id->conn_id, peer_conn_id->sz );
    3729           0 :         one_rtt.dst_conn_id_len  = peer_conn_id->sz;
    3730             : 
    3731           0 :         one_rtt.pkt_num          = pkt_number;
    3732             : 
    3733           0 :         hdr_sz = fd_quic_encode_one_rtt( cur_ptr, cur_sz, &one_rtt );
    3734           0 :         FD_DTRACE_PROBE_2( quic_encode_one_rtt, one_rtt.dst_conn_id, one_rtt.pkt_num );
    3735           0 :         break;
    3736           0 :       }
    3737             : 
    3738           0 :       default:
    3739           0 :         FD_LOG_ERR(( "%s - logic error: unexpected enc_level", __func__ ));
    3740           0 :     }
    3741             : 
    3742             :     /* if we don't have reasonable amt of space for a new packet, tx to free space */
    3743           0 :     const ulong min_rqd = 64;
    3744           0 :     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           0 :     cur_ptr += hdr_sz;
    3762           0 :     cur_sz  -= hdr_sz;
    3763             : 
    3764             :     /* start writing payload, leaving room for header and expansion
    3765             :        due to varint coding */
    3766             : 
    3767           0 :     uchar * payload_ptr = cur_ptr;
    3768           0 :     ulong   payload_sz  = cur_sz;
    3769             :     /* payload_end leaves room for TAG */
    3770           0 :     uchar * payload_end = payload_ptr + payload_sz - FD_QUIC_CRYPTO_TAG_SZ;
    3771             : 
    3772           0 :     uchar * const frame_start = payload_ptr;
    3773           0 :     payload_ptr = fd_quic_gen_frames( conn, frame_start, payload_end, pkt_meta_tmpl, now );
    3774           0 :     if( FD_UNLIKELY( payload_ptr < frame_start ) ) FD_LOG_CRIT(( "fd_quic_gen_frames failed" ));
    3775             : 
    3776             :     /* did we add any frames? */
    3777             : 
    3778           0 :     if( payload_ptr==frame_start ) {
    3779             :       /* we have data to add, but none was added, presumably due
    3780             :          so space in the datagram */
    3781           0 :       ulong free_bytes = (ulong)( payload_end - payload_ptr );
    3782             :       /* sanity check */
    3783           0 :       if( free_bytes > 64 ) {
    3784             :         /* we should have been able to fit data into 64 bytes
    3785             :            so stop trying here */
    3786           0 :         break;
    3787           0 :       }
    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           0 :     uint tot_frame_sz = (uint)( payload_ptr - frame_start );
    3802           0 :     uint base_pkt_len = (uint)tot_frame_sz + pkt_num_len + FD_QUIC_CRYPTO_TAG_SZ;
    3803           0 :     uint padding      = ( initial_pkt && (base_pkt_len < FD_QUIC_INITIAL_PAYLOAD_SZ_MIN) )
    3804           0 :                             ? FD_QUIC_INITIAL_PAYLOAD_SZ_MIN - base_pkt_len : 0u;
    3805             : 
    3806           0 :     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           0 :     uint quic_pkt_len = base_pkt_len + padding;
    3813             : 
    3814             :     /* set the length on the packet header */
    3815           0 :     uint quic_pkt_len_varint = 0x4000u | fd_uint_min( quic_pkt_len, 0x3fff );
    3816           0 :     FD_STORE( ushort, hdr_len_field, fd_ushort_bswap( (ushort)quic_pkt_len_varint ) );
    3817             : 
    3818             :     /* add padding */
    3819           0 :     if( padding ) {
    3820           0 :       fd_memset( payload_ptr, 0, padding );
    3821           0 :       payload_ptr += padding;
    3822           0 :     }
    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           0 :     ulong   cipher_text_sz = fd_quic_conn_tx_buf_remaining( conn );
    3837           0 :     ulong   frames_sz      = (ulong)( payload_ptr - frame_start ); /* including padding */
    3838             : 
    3839           0 :     fd_quic_crypto_keys_t * hp_keys  = &conn->keys[enc_level][1];
    3840           0 :     fd_quic_crypto_keys_t * pkt_keys = key_phase_upd ? &conn->new_keys[1] : &conn->keys[enc_level][1];
    3841             : 
    3842           0 :     if( FD_UNLIKELY( fd_quic_crypto_encrypt( conn->tx_ptr, &cipher_text_sz, hdr_ptr, hdr_sz,
    3843           0 :           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           0 :     conn->tx_ptr += cipher_text_sz;
    3854           0 : #endif
    3855             : 
    3856             :     /* we have committed the packet into the buffer, so inc pkt_number */
    3857           0 :     conn->pkt_number[pn_space]++;
    3858             : 
    3859           0 :     if( enc_level == fd_quic_enc_level_appdata_id ) {
    3860             :       /* short header must be last in datagram
    3861             :          so send in packet immediately */
    3862           0 :       fd_quic_tx_buffered( quic, conn );
    3863             : 
    3864           0 :       if( conn->tx_ptr == conn->tx_buf_conn ) {
    3865           0 :         enc_level = fd_quic_tx_enc_level( conn, 0 /* acks */ );
    3866           0 :         continue;
    3867           0 :       }
    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           0 :     }
    3879             : 
    3880             :     /* Refresh enc_level in case we can coalesce another packet */
    3881           0 :     enc_level = fd_quic_tx_enc_level( conn, 0 /* acks */ );
    3882           0 :     FD_DEBUG( if( enc_level!=~0u) FD_LOG_DEBUG(( "Attempting to append enc_level=%u packet", enc_level )); )
    3883           0 :   }
    3884             : 
    3885             :   /* try to send? */
    3886           0 :   fd_quic_tx_buffered( quic, conn );
    3887           0 : }
    3888             : 
    3889             : void
    3890           0 : fd_quic_conn_service( fd_quic_t * quic, fd_quic_conn_t * conn, long now ) {
    3891             : 
    3892             :   /* Send new rtt measurement probe? */
    3893           0 :   if( FD_UNLIKELY( now > conn->last_ack + (long)conn->rtt_period_ns ) ) {
    3894             :     /* send PING */
    3895           0 :     if( !( conn->flags & ( FD_QUIC_CONN_FLAGS_PING | FD_QUIC_CONN_FLAGS_PING_SENT ) ) ) {
    3896           0 :       conn->flags         |= FD_QUIC_CONN_FLAGS_PING;
    3897           0 :       conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;     /* update to be sent in next packet */
    3898           0 :     }
    3899           0 :   }
    3900             : 
    3901             :   /* handle expiry on pkt_meta */
    3902           0 :   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           0 :   switch( conn->state ) {
    3912           0 :     case FD_QUIC_CONN_STATE_HANDSHAKE:
    3913           0 :     case FD_QUIC_CONN_STATE_HANDSHAKE_COMPLETE:
    3914           0 :       {
    3915           0 :         if( conn->tls_hs ) {
    3916             :           /* if we're the server, we send "handshake-done" frame */
    3917           0 :           if( conn->state == FD_QUIC_CONN_STATE_HANDSHAKE_COMPLETE && conn->server ) {
    3918           0 :             conn->handshake_done_send = 1;
    3919             : 
    3920             :             /* move straight to ACTIVE */
    3921           0 :             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           0 :             fd_quic_abandon_enc_level( conn, fd_quic_enc_level_handshake_id );
    3930             : 
    3931             :             /* user callback */
    3932           0 :             fd_quic_cb_conn_new( quic, conn );
    3933             : 
    3934             :             /* clear out hs_data here, as we don't need it anymore */
    3935           0 :             fd_quic_tls_clear_hs_data( conn->tls_hs, fd_quic_enc_level_appdata_id );
    3936           0 :           }
    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           0 :         }
    3942             : 
    3943             :         /* do we have data to transmit? */
    3944           0 :         fd_quic_conn_tx( quic, conn );
    3945             : 
    3946           0 :         break;
    3947           0 :       }
    3948             : 
    3949           0 :     case FD_QUIC_CONN_STATE_CLOSE_PENDING:
    3950           0 :     case FD_QUIC_CONN_STATE_PEER_CLOSE:
    3951             :         /* user requested close, and may have set a reason code */
    3952             :         /* transmit the failure reason */
    3953           0 :         fd_quic_conn_tx( quic, conn );
    3954             : 
    3955             :         /* schedule another fd_quic_conn_service to free the conn */
    3956           0 :         fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_DEAD ); /* TODO need draining state wait for 3 * TPO */
    3957           0 :         quic->metrics.conn_closed_cnt++;
    3958             : 
    3959           0 :         break;
    3960             : 
    3961           0 :     case FD_QUIC_CONN_STATE_ABORT:
    3962             :         /* transmit the failure reason */
    3963           0 :         fd_quic_conn_tx( quic, conn );
    3964             : 
    3965             :         /* schedule another fd_quic_conn_service to free the conn */
    3966           0 :         fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_DEAD );
    3967           0 :         quic->metrics.conn_aborted_cnt++;
    3968             : 
    3969           0 :         break;
    3970             : 
    3971           0 :     case FD_QUIC_CONN_STATE_ACTIVE:
    3972             :         /* do we have data to transmit? */
    3973           0 :         fd_quic_conn_tx( quic, conn );
    3974             : 
    3975           0 :         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           0 :   }
    3984             : 
    3985             :   /* check routing and arp for this connection */
    3986             : 
    3987           0 : }
    3988             : 
    3989             : void
    3990             : fd_quic_conn_free( fd_quic_t *      quic,
    3991           0 :                    fd_quic_conn_t * conn ) {
    3992           0 :   if( FD_UNLIKELY( !conn ) ) {
    3993           0 :     FD_LOG_WARNING(( "NULL conn" ));
    3994           0 :     return;
    3995           0 :   }
    3996           0 :   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           0 :   FD_COMPILER_MFENCE();
    4002           0 :   fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_INVALID );
    4003           0 :   FD_COMPILER_MFENCE();
    4004             : 
    4005           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
    4006             : 
    4007             :   /* remove connection id from conn_map */
    4008             : 
    4009           0 :   fd_quic_conn_map_t * entry = fd_quic_conn_map_query( state->conn_map, conn->our_conn_id, NULL );
    4010           0 :   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           0 :   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           0 :   fd_quic_stream_t * used_sentinel = conn->used_streams;
    4025           0 :   while( 1 ) {
    4026           0 :     fd_quic_stream_t * stream = used_sentinel->next;
    4027             : 
    4028           0 :     if( FD_UNLIKELY( stream == used_sentinel ) ) break;
    4029             : 
    4030           0 :     fd_quic_tx_stream_free( quic, conn, stream, FD_QUIC_STREAM_NOTIFY_CONN );
    4031           0 :   }
    4032             : 
    4033             :   /* remove send streams */
    4034           0 :   fd_quic_stream_t * send_sentinel = conn->send_streams;
    4035           0 :   while( 1 ) {
    4036           0 :     fd_quic_stream_t * stream = send_sentinel->next;
    4037             : 
    4038           0 :     if( FD_UNLIKELY( stream == send_sentinel ) ) break;
    4039             : 
    4040           0 :     fd_quic_tx_stream_free( quic, conn, stream, FD_QUIC_STREAM_NOTIFY_CONN );
    4041           0 :   }
    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           0 :   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           0 :   if( conn->tls_hs ) {
    4068             :     /* free tls-hs */
    4069           0 :     fd_quic_tls_hs_delete( conn->tls_hs );
    4070             : 
    4071             :     /* Remove the handshake from the cache before releasing it */
    4072           0 :     fd_quic_tls_hs_cache_ele_remove( &state->hs_cache, conn->tls_hs, state->hs_pool);
    4073           0 :     fd_quic_tls_hs_pool_ele_release( state->hs_pool, conn->tls_hs );
    4074           0 :   }
    4075           0 :   conn->tls_hs = NULL;
    4076             : 
    4077             :   /* remove from service queue */
    4078           0 :   fd_quic_svc_timers_cancel( state->svc_timers, conn );
    4079             : 
    4080             :   /* put connection back in free list */
    4081           0 :   conn->free_conn_next  = state->free_conn_list;
    4082           0 :   state->free_conn_list = conn->conn_idx;
    4083             : 
    4084           0 :   quic->metrics.conn_alloc_cnt--;
    4085             : 
    4086             :   /* clear keys */
    4087           0 :   memset( &conn->secrets, 0, sizeof(fd_quic_crypto_secrets_t) );
    4088           0 :   memset( conn->keys,     0, sizeof( conn->keys ) );
    4089           0 :   memset( conn->new_keys, 0, sizeof( conn->new_keys ) );
    4090           0 : }
    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           0 :                  long        now ) {
    4099           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
    4100           0 :   state->now              = now;
    4101             : 
    4102           0 :   if( FD_UNLIKELY( !fd_quic_tls_hs_pool_free( state->hs_pool ) ) ) {
    4103             :     /* try evicting, 0 if oldest is too young so fail */
    4104           0 :     if( !fd_quic_tls_hs_cache_evict( quic, state ) ) {
    4105           0 :       return NULL;
    4106           0 :     }
    4107           0 :   }
    4108             : 
    4109           0 :   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           0 :   ulong our_conn_id_u64 = fd_rng_ulong( rng );
    4114           0 :   fd_quic_conn_id_t peer_conn_id;  fd_quic_conn_id_rand( &peer_conn_id, rng );
    4115             : 
    4116           0 :   fd_quic_conn_t * conn = fd_quic_conn_create(
    4117           0 :       quic,
    4118           0 :       our_conn_id_u64,
    4119           0 :       &peer_conn_id,
    4120           0 :       dst_ip_addr,
    4121           0 :       dst_udp_port,
    4122           0 :       src_ip_addr,
    4123           0 :       src_udp_port,
    4124           0 :       0 /* client */ );
    4125             : 
    4126           0 :   if( FD_UNLIKELY( !conn ) ) {
    4127           0 :     FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_conn_create failed" )) );
    4128           0 :     return NULL;
    4129           0 :   }
    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           0 :   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           0 :   tp->original_destination_connection_id_present = 0;
    4142           0 :   tp->original_destination_connection_id_len     = 0;
    4143             : 
    4144             :   /* Similarly, explicitly zero out retry fields. */
    4145           0 :   tp->retry_source_connection_id_present     = 0;
    4146           0 :   tp->retry_source_connection_id_len     = 0;
    4147             : 
    4148             :   /* Repeat source conn ID -- rationale see fd_quic_handle_v1_initial */
    4149             : 
    4150           0 :   FD_STORE( ulong, tp->initial_source_connection_id, conn->initial_source_conn_id );
    4151           0 :   tp->initial_source_connection_id_present = 1;
    4152           0 :   tp->initial_source_connection_id_len     = FD_QUIC_CONN_ID_SZ;
    4153             : 
    4154             :   /* Create a TLS handshake (free>0 validated above) */
    4155             : 
    4156           0 :   fd_quic_tls_hs_t * tls_hs = fd_quic_tls_hs_new(
    4157           0 :       fd_quic_tls_hs_pool_ele_acquire( state->hs_pool ),
    4158           0 :       state->tls,
    4159           0 :       (void*)conn,
    4160           0 :       0 /*is_server*/,
    4161           0 :       tp,
    4162           0 :       now );
    4163           0 :   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           0 :   fd_quic_tls_hs_cache_ele_push_tail( &state->hs_cache, tls_hs, state->hs_pool );
    4172             : 
    4173           0 :   quic->metrics.hs_created_cnt++;
    4174           0 :   conn->tls_hs = tls_hs;
    4175             : 
    4176           0 :   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           0 :   conn->called_conn_new = 1;
    4181             : 
    4182           0 :   fd_quic_svc_prep_schedule( conn, now );
    4183           0 :   fd_quic_svc_timers_schedule( state->svc_timers, conn, now );
    4184             : 
    4185             :   /* everything initialized */
    4186           0 :   return conn;
    4187             : 
    4188           0 : }
    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           0 :                      int                       server ) {
    4199           0 :   if( FD_UNLIKELY( !our_conn_id ) ) return NULL;
    4200             : 
    4201           0 :   fd_quic_config_t * config = &quic->config;
    4202           0 :   fd_quic_state_t *  state  = fd_quic_get_state( quic );
    4203             : 
    4204             :   /* fetch top of connection free list */
    4205           0 :   uint conn_idx = state->free_conn_list;
    4206           0 :   if( FD_UNLIKELY( conn_idx==UINT_MAX ) ) {
    4207           0 :     FD_DEBUG( FD_LOG_DEBUG(( "fd_quic_conn_create failed: no free conn slots" )) );
    4208           0 :     quic->metrics.conn_err_no_slots_cnt++;
    4209           0 :     return NULL;
    4210           0 :   }
    4211           0 :   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           0 :   fd_quic_conn_t * conn = fd_quic_conn_at_idx( state, conn_idx );
    4216           0 :   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           0 :   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           0 :   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           0 :   insert_entry->conn = conn;
    4235             : 
    4236             :   /* remove from free list */
    4237           0 :   state->free_conn_list = conn->free_conn_next;
    4238           0 :   conn->free_conn_next  = UINT_MAX;
    4239             : 
    4240             :   /* if conn not marked free, skip */
    4241           0 :   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           0 :   fd_quic_conn_clear( conn );
    4248             : 
    4249           0 :   conn->server              = !!server;
    4250           0 :   conn->our_conn_id         = our_conn_id;
    4251           0 :   conn->host                = (fd_quic_net_endpoint_t){
    4252           0 :     .ip_addr  = self_ip_addr, /* may be 0, if outgoing */
    4253           0 :     .udp_port = self_udp_port,
    4254           0 :   };
    4255           0 :   conn->conn_gen++;
    4256             : 
    4257             : 
    4258             :   /* pkt_meta */
    4259           0 :   fd_quic_pkt_meta_tracker_init( &conn->pkt_meta_tracker,
    4260           0 :                                  quic->limits.inflight_frame_cnt,
    4261           0 :                                  state->pkt_meta_pool );
    4262             : 
    4263             :   /* Initialize streams */
    4264           0 :   FD_QUIC_STREAM_LIST_SENTINEL( conn->send_streams );
    4265           0 :   FD_QUIC_STREAM_LIST_SENTINEL( conn->used_streams );
    4266             : 
    4267             :   /* initialize stream_id members */
    4268           0 :   fd_quic_conn_stream_rx_t * srx = conn->srx;
    4269           0 :   fd_quic_transport_params_t * our_tp = &state->transport_params;
    4270           0 :   srx->rx_hi_stream_id    = server ? FD_QUIC_STREAM_TYPE_UNI_CLIENT : FD_QUIC_STREAM_TYPE_UNI_SERVER;
    4271           0 :   srx->rx_sup_stream_id   = server ? FD_QUIC_STREAM_TYPE_UNI_CLIENT : FD_QUIC_STREAM_TYPE_UNI_SERVER;
    4272           0 :   conn->tx_next_stream_id = server ? FD_QUIC_STREAM_TYPE_UNI_SERVER : FD_QUIC_STREAM_TYPE_UNI_CLIENT;
    4273           0 :   conn->tx_sup_stream_id  = server ? FD_QUIC_STREAM_TYPE_UNI_SERVER : FD_QUIC_STREAM_TYPE_UNI_CLIENT;
    4274             : 
    4275           0 :   srx->rx_max_data       = our_tp->initial_max_data;
    4276             : 
    4277           0 :   if( state->transport_params.initial_max_streams_uni_present ) {
    4278           0 :     srx->rx_sup_stream_id = (state->transport_params.initial_max_streams_uni<<2) + FD_QUIC_STREAM_TYPE_UNI_CLIENT;
    4279           0 :   }
    4280           0 :   if( state->transport_params.initial_max_data ) {
    4281           0 :     srx->rx_max_data = state->transport_params.initial_max_data;
    4282           0 :   }
    4283             : 
    4284             :   /* points to free tx space */
    4285           0 :   conn->tx_ptr = conn->tx_buf_conn;
    4286             : 
    4287           0 :   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           0 :   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           0 :   conn->tx_max_datagram_sz = FD_QUIC_INITIAL_PAYLOAD_SZ_MAX;
    4302             : 
    4303             :   /* initial source connection id */
    4304           0 :   conn->initial_source_conn_id = our_conn_id;
    4305             : 
    4306             :   /* peer connection id */
    4307           0 :   conn->peer_cids[0]     = *peer_conn_id;
    4308           0 :   conn->peer[0].ip_addr  = peer_ip_addr;
    4309           0 :   conn->peer[0].udp_port = peer_udp_port;
    4310             : 
    4311           0 :   fd_quic_ack_gen_init( conn->ack_gen );
    4312             : 
    4313             :   /* initial rtt */
    4314             :   /* overridden when acks start returning */
    4315           0 :   fd_rtt_estimate_t * rtt = conn->rtt;
    4316             : 
    4317           0 :   ulong peer_ack_delay_exponent  = 3UL; /* by spec, default is 3 */
    4318           0 :   conn->peer_ack_delay_scale     = (float)( 1UL << peer_ack_delay_exponent ) * 1e3f;
    4319           0 :   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           0 :   rtt->smoothed_rtt              = FD_QUIC_INITIAL_RTT_US * 1e3f;
    4323           0 :   rtt->latest_rtt                = FD_QUIC_INITIAL_RTT_US * 1e3f;
    4324           0 :   rtt->min_rtt                   = FD_QUIC_INITIAL_RTT_US * 1e3f;
    4325           0 :   rtt->var_rtt                   = FD_QUIC_INITIAL_RTT_US * 1e3f * 0.5f;
    4326           0 :   conn->rtt_period_ns            = FD_QUIC_RTT_PERIOD_US  * 1e3f;
    4327             : 
    4328             :   /* idle timeout */
    4329           0 :   conn->idle_timeout_ns      = config->idle_timeout;
    4330           0 :   conn->last_activity        = state->now;
    4331           0 :   if( !conn->last_activity )   FD_LOG_CRIT(( "last activity: %ld", conn->last_activity ));
    4332           0 :   conn->let_die_time_ns      = LONG_MAX;
    4333             : 
    4334             :   /* update metrics */
    4335           0 :   quic->metrics.conn_alloc_cnt++;
    4336           0 :   quic->metrics.conn_created_cnt++;
    4337             : 
    4338           0 :   fd_quic_svc_timers_init_conn( conn );
    4339             : 
    4340             :   /* prep idle timeout or keep alive at idle timeout/2 */
    4341           0 :   long delay = quic->config.idle_timeout>>(quic->config.keep_alive);
    4342           0 :   fd_quic_svc_prep_schedule( conn, state->now+delay );
    4343             : 
    4344             :   /* return connection */
    4345           0 :   return conn;
    4346           0 : }
    4347             : 
    4348             : long
    4349           0 : fd_quic_get_next_wakeup( fd_quic_t * quic ) {
    4350           0 :   fd_quic_state_t *   state = fd_quic_get_state( quic );
    4351           0 :   long                now   = state->now;
    4352           0 :   fd_quic_svc_event_t next  = fd_quic_svc_timers_next( state->svc_timers, now, 0 );
    4353           0 :   return next.timeout;
    4354           0 : }
    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           0 :     ulong                     p_sz ) {
    4363           0 :   uchar const *       p     = p0;
    4364           0 :   uchar const * const p_end = p + p_sz;
    4365           0 :   while( p<p_end && p[0]==0 ) p++;
    4366           0 :   return (ulong)( p - p0 );
    4367           0 : }
    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           0 :     ulong                  p_sz ) {
    4375           0 :   FD_DTRACE_PROBE_1( quic_handle_ping_frame, ctx->conn->our_conn_id );
    4376             :   /* skip pings and pads */
    4377           0 :   uchar const *       p     = p0;
    4378           0 :   uchar const * const p_end = p + p_sz;
    4379           0 :   while( p < p_end && ((uint)p[0] & 0xfeu) == 0 ) p++;
    4380           0 :   return (ulong)( p - p0 );
    4381           0 : }
    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           0 :                         uint              arg_enc_level  ) {
    4397           0 :   fd_quic_conn_stream_rx_t * srx = conn->srx;
    4398             : 
    4399           0 :   long now = fd_quic_get_state( quic )->now;
    4400             : 
    4401           0 :   fd_quic_pkt_meta_tracker_t * tracker = &conn->pkt_meta_tracker;
    4402           0 :   fd_quic_pkt_meta_t         * pool    = tracker->pool;
    4403             : 
    4404             :   /* used for metric tracking */
    4405           0 :   ulong prev_retx_pkt_num[FD_QUIC_NUM_ENC_LEVELS] = { ~0ul, ~0ul, ~0ul, ~0ul };
    4406             : 
    4407           0 :   long const pto_duration  = fd_quic_calc_expiry_duration( conn, 0, conn->server );
    4408           0 :   long const loss_duration = fd_quic_calc_expiry_duration( conn, 1, conn->server );
    4409             : 
    4410           0 :   while(1) {
    4411             :     /* find earliest expiring pkt_meta, over smallest pkt number at each enc_level */
    4412           0 :     fd_quic_pkt_meta_t * pkt_meta = NULL;
    4413           0 :     long                 expiry   = LONG_MAX;
    4414           0 :     for( uint j=0u; j<4u; ++j ) {
    4415             :       /* if arg_enc_level set, only consider that enc_level */
    4416           0 :       if( !(arg_enc_level==~0u) & !(j==arg_enc_level) ) continue;
    4417             : 
    4418           0 :       fd_quic_pkt_meta_t * pkt_meta_cand = fd_quic_pkt_meta_min( &tracker->sent_pkt_metas[j], pool );
    4419           0 :       if( !pkt_meta_cand ) continue;
    4420             : 
    4421           0 :       uint  const pn_space      = fd_quic_enc_level_to_pn_space( j );
    4422           0 :       ulong const highest_acked = conn->highest_acked[pn_space];
    4423           0 :       long  const cand_duration = fd_long_if( pkt_meta_cand->key.pkt_num < highest_acked, loss_duration, pto_duration );
    4424             : 
    4425           0 :       pkt_meta_cand->expiry = fd_long_min( pkt_meta_cand->tx_time + cand_duration, pkt_meta_cand->expiry );
    4426             : 
    4427           0 :       if( !pkt_meta || pkt_meta_cand->expiry < expiry ) {
    4428           0 :         pkt_meta = pkt_meta_cand;
    4429           0 :         expiry   = pkt_meta_cand->expiry;
    4430           0 :       }
    4431           0 :     }
    4432             : 
    4433           0 :     if( !pkt_meta ) return;
    4434             : 
    4435           0 :     uint  const enc_level = pkt_meta->enc_level;
    4436           0 :     ulong const pkt_num   = pkt_meta->key.pkt_num;
    4437             : 
    4438             :     /* Continue until nothing expired nor to be skipped */
    4439           0 :     if( !!(pkt_num >= force_below_pkt_num) & !!(expiry > now) ) {
    4440             :       /* safe even when expiry is LONG_MAX, because prep_schedule takes min */
    4441           0 :       fd_quic_svc_prep_schedule( conn, expiry );
    4442           0 :       return;
    4443           0 :     };
    4444             : 
    4445           0 :     quic->metrics.pkt_retransmissions_cnt[enc_level] += !(pkt_meta->key.pkt_num == prev_retx_pkt_num[enc_level]);
    4446           0 :     prev_retx_pkt_num[enc_level] = pkt_num;
    4447             : 
    4448           0 :     uint type = pkt_meta->key.type;
    4449           0 :     FD_DTRACE_PROBE_4( quic_pkt_meta_retry, conn->our_conn_id, pkt_num, expiry, type);
    4450             :     /* set the data to retry */
    4451           0 :     switch( type ) {
    4452           0 :       case FD_QUIC_PKT_META_TYPE_HS_DATA:
    4453           0 :         do {
    4454           0 :           ulong offset = fd_ulong_max( conn->hs_ackd_bytes[enc_level], pkt_meta->val.range.offset_lo );
    4455           0 :           if( offset < conn->hs_sent_bytes[enc_level] ) {
    4456           0 :             conn->hs_sent_bytes[enc_level] = offset;
    4457           0 :             conn->upd_pkt_number           = FD_QUIC_PKT_NUM_PENDING;
    4458           0 :           }
    4459           0 :         } while(0);
    4460           0 :         break;
    4461             : 
    4462           0 :       case FD_QUIC_PKT_META_TYPE_STREAM:
    4463           0 :         do {
    4464           0 :           ulong stream_id = pkt_meta->key.stream_id;
    4465             : 
    4466             :           /* find the stream */
    4467           0 :           fd_quic_stream_t *     stream       = NULL;
    4468           0 :           fd_quic_stream_map_t * stream_entry = fd_quic_stream_map_query( conn->stream_map, stream_id, NULL );
    4469           0 :           if( FD_LIKELY( stream_entry && stream_entry->stream &&
    4470           0 :                 ( stream_entry->stream->stream_flags & FD_QUIC_STREAM_FLAGS_DEAD ) == 0 ) ) {
    4471           0 :             stream = stream_entry->stream;
    4472             : 
    4473             :             /* do not try sending data that has been acked */
    4474           0 :             ulong offset = fd_ulong_max( pkt_meta->val.range.offset_lo, stream->unacked_low );
    4475             : 
    4476             :             /* This pkt_meta may be stale: when ACK-driven loss detection
    4477             :                force-retries an earlier pkt_meta for the same stream, the
    4478             :                retransmitted data can be ACKed (advancing unacked_low)
    4479             :                before this pkt_meta expires. Skip the retry if the
    4480             :                stream has nothing left to send. */
    4481           0 :             if( FD_UNLIKELY( offset>=stream->tx_buf.head &&
    4482           0 :                   !( stream->state & FD_QUIC_STREAM_STATE_TX_FIN ) ) ) {
    4483           0 :               break;
    4484           0 :             }
    4485             : 
    4486             :             /* any data left to retry? */
    4487           0 :             stream->tx_sent = fd_ulong_min( stream->tx_sent, offset );
    4488             : 
    4489             :             /* We must have something to send if the stream was found */
    4490           0 :             if( !( (stream->tx_sent < stream->tx_buf.head) | (stream->state & FD_QUIC_STREAM_STATE_TX_FIN) ) ) {
    4491           0 :               FD_LOG_CRIT(( "unexpected retry for completed stream %lu", stream_id ));
    4492           0 :             }
    4493             : 
    4494             :             /* insert into send list */
    4495           0 :             FD_QUIC_STREAM_LIST_REMOVE( stream );
    4496           0 :             FD_QUIC_STREAM_LIST_INSERT_BEFORE( conn->send_streams, stream );
    4497             : 
    4498             :             /* set the data to go out on the next packet */
    4499           0 :             stream->stream_flags   |= FD_QUIC_STREAM_FLAGS_UNSENT; /* we have unsent data */
    4500           0 :             stream->upd_pkt_number  = FD_QUIC_PKT_NUM_PENDING;
    4501           0 :           }
    4502           0 :         } while(0);
    4503           0 :         break;
    4504             : 
    4505           0 :       case FD_QUIC_PKT_META_TYPE_HS_DONE:
    4506           0 :         if( FD_LIKELY( !conn->handshake_done_ackd ) ) {
    4507           0 :           conn->handshake_done_send = 1;
    4508           0 :           conn->upd_pkt_number      = FD_QUIC_PKT_NUM_PENDING;
    4509           0 :         }
    4510           0 :         break;
    4511             : 
    4512           0 :       case FD_QUIC_PKT_META_TYPE_MAX_DATA:
    4513           0 :         if( srx->rx_max_data_ackd < srx->rx_max_data ) {
    4514           0 :           conn->flags         |= FD_QUIC_CONN_FLAGS_MAX_DATA;
    4515           0 :           conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
    4516           0 :         }
    4517           0 :         break;
    4518             : 
    4519           0 :       case FD_QUIC_PKT_META_TYPE_MAX_STREAMS_UNIDIR:
    4520           0 :         do {
    4521             :           /* do we still need to send? */
    4522             :           /* get required value */
    4523           0 :           ulong max_streams_unidir = srx->rx_sup_stream_id >> 2;
    4524             : 
    4525           0 :           if( max_streams_unidir > srx->rx_max_streams_unidir_ackd ) {
    4526             :             /* set the data to go out on the next packet */
    4527           0 :             conn->flags          |= FD_QUIC_CONN_FLAGS_MAX_STREAMS_UNIDIR;
    4528           0 :             conn->upd_pkt_number  = FD_QUIC_PKT_NUM_PENDING;
    4529           0 :           }
    4530           0 :         } while(0);
    4531           0 :         break;
    4532             : 
    4533           0 :       case FD_QUIC_PKT_META_TYPE_CLOSE:
    4534           0 :         conn->flags &= ~FD_QUIC_CONN_FLAGS_CLOSE_SENT;
    4535           0 :         conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
    4536           0 :         break;
    4537             : 
    4538           0 :       case FD_QUIC_PKT_META_TYPE_PING:
    4539           0 :         conn->flags = ( conn->flags & ~FD_QUIC_CONN_FLAGS_PING_SENT )
    4540           0 :                       | FD_QUIC_CONN_FLAGS_PING;
    4541           0 :         conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
    4542           0 :         break;
    4543           0 :     }
    4544             : 
    4545             :     /* reschedule to ensure the data gets processed */
    4546           0 :     fd_quic_svc_prep_schedule_now( conn );
    4547             : 
    4548           0 :     fd_quic_pkt_meta_remove( &tracker->sent_pkt_metas[enc_level], pool, pkt_meta );
    4549           0 :     conn->used_pkt_meta--;
    4550           0 :   }
    4551           0 : }
    4552             : 
    4553             : /* reclaim resources associated with packet metadata
    4554             :    this is called in response to received acks */
    4555             : void
    4556             : fd_quic_reclaim_pkt_meta( fd_quic_conn_t *     conn,
    4557             :                           fd_quic_pkt_meta_t * pkt_meta,
    4558           0 :                           uint                 enc_level ) {
    4559           0 :   fd_quic_conn_stream_rx_t * srx = conn->srx;
    4560             : 
    4561           0 :   uint            type  = pkt_meta->key.type;
    4562           0 :   fd_quic_range_t range = pkt_meta->val.range;
    4563             : 
    4564           0 :   switch( type ) {
    4565             : 
    4566           0 :     case FD_QUIC_PKT_META_TYPE_PING:
    4567           0 :       do {
    4568           0 :         conn->flags &= ~( FD_QUIC_CONN_FLAGS_PING | FD_QUIC_CONN_FLAGS_PING_SENT );
    4569           0 :       } while(0);
    4570           0 :       break;
    4571             : 
    4572           0 :     case FD_QUIC_PKT_META_TYPE_HS_DATA:
    4573           0 :       do {
    4574             :         /* Note that tls_hs could already be freed */
    4575             :         /* is this ack'ing the next consecutive bytes?
    4576             :           if so, we can increase the ack'd bytes
    4577             :           if not, we retransmit the bytes expected to be ack'd
    4578             :             we assume a gap means a dropped packet, and
    4579             :             this policy allows us to free up the pkt_meta here */
    4580           0 :         ulong hs_ackd_bytes = conn->hs_ackd_bytes[enc_level];
    4581           0 :         if( range.offset_lo <= hs_ackd_bytes ) {
    4582           0 :           hs_ackd_bytes = conn->hs_ackd_bytes[enc_level]
    4583           0 :                         = fd_ulong_max( hs_ackd_bytes, range.offset_hi );
    4584             : 
    4585             :           /* remove any unused hs_data */
    4586           0 :           fd_quic_tls_hs_data_t * hs_data = NULL;
    4587             : 
    4588           0 :           hs_data = fd_quic_tls_get_hs_data( conn->tls_hs, enc_level );
    4589           0 :           while( hs_data && hs_data->offset + hs_data->data_sz <= hs_ackd_bytes ) {
    4590           0 :             fd_quic_tls_pop_hs_data( conn->tls_hs, enc_level );
    4591           0 :             hs_data = fd_quic_tls_get_hs_data( conn->tls_hs, enc_level );
    4592           0 :           }
    4593           0 :         } else {
    4594           0 :           conn->hs_sent_bytes[enc_level] =
    4595           0 :               fd_ulong_min( conn->hs_sent_bytes[enc_level], hs_ackd_bytes );
    4596           0 :           conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
    4597           0 :         }
    4598           0 :       } while(0);
    4599           0 :       break;
    4600             : 
    4601           0 :     case FD_QUIC_PKT_META_TYPE_HS_DONE:
    4602           0 :       do {
    4603           0 :         conn->handshake_done_ackd = 1;
    4604           0 :         conn->handshake_done_send = 0;
    4605           0 :         if( FD_LIKELY( conn->tls_hs ) ) {
    4606           0 :           fd_quic_state_t * state = fd_quic_get_state( conn->quic );
    4607           0 :           fd_quic_tls_hs_delete( conn->tls_hs );
    4608           0 :           fd_quic_tls_hs_cache_ele_remove( &state->hs_cache, conn->tls_hs, state->hs_pool );
    4609           0 :           fd_quic_tls_hs_pool_ele_release( state->hs_pool, conn->tls_hs );
    4610           0 :           conn->tls_hs = NULL;
    4611           0 :         }
    4612           0 :       } while(0);
    4613           0 :       break;
    4614             : 
    4615           0 :     case FD_QUIC_PKT_META_TYPE_MAX_DATA:
    4616           0 :       do {
    4617           0 :         ulong max_data_ackd = pkt_meta->val.scalar;
    4618             : 
    4619             :         /* ack can only increase max_data_ackd */
    4620           0 :         max_data_ackd = fd_ulong_max( max_data_ackd, srx->rx_max_data_ackd );
    4621             : 
    4622             :         /* max_data_ackd > rx_max_data is a protocol violation */
    4623           0 :         if( FD_UNLIKELY( max_data_ackd > srx->rx_max_data ) ) {
    4624             :           /* this is a protocol violation, so inform the peer */
    4625           0 :           fd_quic_conn_error( conn, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
    4626           0 :           return;
    4627           0 :         }
    4628             : 
    4629             :         /* clear flag only if acked value == current value */
    4630           0 :         if( FD_LIKELY( max_data_ackd == srx->rx_max_data ) ) {
    4631           0 :           conn->flags &= ~FD_QUIC_CONN_FLAGS_MAX_DATA;
    4632           0 :         }
    4633             : 
    4634             :         /* set the ackd value */
    4635           0 :         srx->rx_max_data_ackd = max_data_ackd;
    4636           0 :       } while(0);
    4637           0 :       break;
    4638             : 
    4639           0 :     case FD_QUIC_PKT_META_TYPE_MAX_STREAMS_UNIDIR:
    4640           0 :       do {
    4641           0 :         ulong max_streams_unidir_ackd = pkt_meta->val.scalar;
    4642             : 
    4643             :         /* ack can only increase max_streams_unidir_ackd */
    4644           0 :         max_streams_unidir_ackd = fd_ulong_max( max_streams_unidir_ackd, srx->rx_max_streams_unidir_ackd );
    4645             : 
    4646             :         /* get required value */
    4647           0 :         ulong max_streams_unidir = srx->rx_sup_stream_id >> 2;
    4648             : 
    4649             :         /* clear flag only if acked value == current value */
    4650           0 :         if( FD_LIKELY( max_streams_unidir_ackd == max_streams_unidir ) ) {
    4651           0 :           conn->flags &= ~FD_QUIC_CONN_FLAGS_MAX_STREAMS_UNIDIR;
    4652           0 :         }
    4653             : 
    4654             :         /* set the ackd value */
    4655           0 :         srx->rx_max_streams_unidir_ackd = max_streams_unidir_ackd;
    4656           0 :       } while(0);
    4657           0 :       break;
    4658             : 
    4659           0 :     case FD_QUIC_PKT_META_TYPE_STREAM:
    4660           0 :       do {
    4661           0 :         ulong stream_id = pkt_meta->key.stream_id;
    4662           0 :         fd_quic_range_t range = pkt_meta->val.range;
    4663             : 
    4664             :         /* find the stream */
    4665           0 :         fd_quic_stream_t *     stream       = NULL;
    4666           0 :         fd_quic_stream_map_t * stream_entry = fd_quic_stream_map_query( conn->stream_map, stream_id, NULL );
    4667           0 :         if( FD_LIKELY( stream_entry && stream_entry->stream &&
    4668           0 :               ( stream_entry->stream->stream_flags & FD_QUIC_STREAM_FLAGS_DEAD ) == 0 ) ) {
    4669           0 :           stream = stream_entry->stream;
    4670             : 
    4671           0 :           ulong tx_tail = stream->unacked_low;
    4672           0 :           ulong tx_sent = stream->tx_sent;
    4673             : 
    4674             :           /* ignore bytes which were already acked */
    4675           0 :           range.offset_lo = fd_ulong_max( range.offset_lo, tx_tail );
    4676             : 
    4677             :           /* verify offset_hi */
    4678           0 :           if( FD_UNLIKELY( range.offset_hi > stream->tx_buf.head ) ) {
    4679             :             /* offset_hi in the pkt_meta (the highest byte offset in the packet */
    4680             :             /* should never exceed tx_buf.head - the highest byte offset in the */
    4681             :             /* stream */
    4682           0 :             fd_quic_conn_error( conn, FD_QUIC_CONN_REASON_INTERNAL_ERROR, __LINE__ );
    4683           0 :             return;
    4684           0 :           }
    4685             : 
    4686           0 :           uchar * tx_ack = stream->tx_ack;
    4687             :           /* did they ack the first unacked byte? */
    4688           0 :           if( FD_LIKELY( range.offset_lo == tx_tail ) ) {
    4689             :             /* move tail to first unacked byte */
    4690           0 :             tx_tail = range.offset_hi;
    4691           0 :             while( tx_tail < tx_sent ) {
    4692             :               /* TODO - optimize this for larger strides */
    4693             :               /* can we skip a whole byte? */
    4694           0 :               if( ( tx_tail & 7ul ) == 0ul && tx_tail + 8ul <= tx_sent && tx_ack[tx_tail>>3ul] == 0xffu ) {
    4695           0 :                 tx_tail += 8ul;
    4696           0 :               } else {
    4697           0 :                 if( tx_ack[tx_tail>>3ul] & ( 1u << ( tx_tail & 7u ) ) ) {
    4698           0 :                   tx_tail++;
    4699           0 :                 } else {
    4700           0 :                   break;
    4701           0 :                 }
    4702           0 :               }
    4703           0 :             }
    4704           0 :             stream->unacked_low = tx_tail;
    4705           0 :           } else {
    4706             :             /* mark this range as acked in tx_ack, so we can skip it later */
    4707             :             /* TODO optimize this for larger strides */
    4708           0 :             for( ulong k = range.offset_lo; k < range.offset_hi; ) {
    4709           0 :               if( ( k & 7ul ) == 0ul && k + 8ul <= range.offset_hi ) {
    4710             :                 /* set whole byte */
    4711           0 :                 tx_ack[k>>3ul] = 0xffu;
    4712           0 :                 k += 8ul;
    4713           0 :               } else {
    4714             :                 /* compiler is not smart enough to know ( 1u << ( k & 7u ) ) fits in a uchar */
    4715           0 :                 tx_ack[k>>3ul] |= (uchar)( 1ul << ( k & 7ul ) );
    4716           0 :                 k++;
    4717           0 :               }
    4718           0 :             }
    4719           0 :           }
    4720             : 
    4721             :           /* For convenience */
    4722           0 :           uint fin_state_mask = FD_QUIC_STREAM_STATE_TX_FIN | FD_QUIC_STREAM_STATE_RX_FIN;
    4723             : 
    4724             :           /* Free stream if it's done:
    4725             :               1. peer has acked every data byte user has tried to send
    4726             :               2. peer has acked the fin --> user has fin'd */
    4727           0 :           if( tx_tail == stream->tx_buf.head &&
    4728           0 :               ( stream->state & fin_state_mask ) == fin_state_mask ) {
    4729             :             /* fd_quic_tx_stream_free also notifies the user */
    4730           0 :             fd_quic_tx_stream_free( conn->quic, conn, stream, FD_QUIC_STREAM_NOTIFY_END );
    4731           0 :           }
    4732           0 :         }
    4733           0 :       } while(0);
    4734           0 :       break;
    4735           0 :   }
    4736           0 : }
    4737             : 
    4738             : /* process ack range
    4739             :    applies to pkt_number in [largest_ack - ack_range, largest_ack] */
    4740             : void
    4741             : fd_quic_process_ack_range( fd_quic_conn_t      * conn,
    4742             :                            fd_quic_frame_ctx_t * context,
    4743             :                            uint                  enc_level,
    4744             :                            ulong                 largest_ack,
    4745             :                            ulong                 ack_range,
    4746             :                            int                   is_largest,
    4747             :                            long                  now,
    4748           0 :                            ulong                 ack_delay ) {
    4749             :   /* FIXME: Close connection if peer ACKed a higher packet number than we sent */
    4750             : 
    4751           0 :   fd_quic_pkt_t * pkt = context->pkt;
    4752             : 
    4753             :   /* inclusive range */
    4754           0 :   ulong hi = largest_ack;
    4755           0 :   ulong lo = largest_ack - ack_range;
    4756           0 :   FD_DTRACE_PROBE_4( quic_process_ack_range, conn->our_conn_id, enc_level, lo, hi );
    4757             : 
    4758           0 :   fd_quic_pkt_meta_tracker_t * tracker  =  &conn->pkt_meta_tracker;
    4759           0 :   fd_quic_pkt_meta_t         * pool     =  tracker->pool;
    4760           0 :   fd_quic_pkt_meta_ds_t      * sent     =  &tracker->sent_pkt_metas[enc_level];
    4761             : 
    4762             :   /* start at oldest sent */
    4763           0 :   for( fd_quic_pkt_meta_ds_fwd_iter_t iter = fd_quic_pkt_meta_ds_idx_ge( sent, lo, pool );
    4764           0 :                                              !fd_quic_pkt_meta_ds_fwd_iter_done( iter );
    4765           0 :                                              iter = fd_quic_pkt_meta_ds_fwd_iter_next( iter, pool ) ) {
    4766           0 :     fd_quic_pkt_meta_t * e = fd_quic_pkt_meta_ds_fwd_iter_ele( iter, pool );
    4767           0 :     if( FD_UNLIKELY( e->key.pkt_num > hi ) ) break;
    4768           0 :     if( is_largest && e->key.pkt_num == hi && hi >= pkt->rtt_pkt_number ) {
    4769           0 :       pkt->rtt_pkt_number = hi;
    4770           0 :       pkt->rtt_ack_time   = now - e->tx_time; /* in ns         */
    4771           0 :       pkt->rtt_ack_delay  = ack_delay;        /* in peer units */
    4772           0 :     }
    4773           0 :     fd_quic_reclaim_pkt_meta( conn, e, enc_level );
    4774           0 :   }
    4775             : 
    4776           0 :   conn->used_pkt_meta -= fd_quic_pkt_meta_remove_range( sent, pool, lo, hi );
    4777           0 : }
    4778             : 
    4779             : static ulong
    4780             : fd_quic_handle_ack_frame( fd_quic_frame_ctx_t * context,
    4781             :                           fd_quic_ack_frame_t * data,
    4782             :                           uchar const         * p,
    4783           0 :                           ulong                 p_sz ) {
    4784           0 :   fd_quic_conn_t *  conn        = context->conn;
    4785           0 :   uint              enc_level   = context->pkt->enc_level;
    4786           0 :   uint              pn_space    = fd_quic_enc_level_to_pn_space( enc_level );
    4787           0 :   ulong const       largest_ack = data->largest_ack;
    4788             : 
    4789           0 :   if( FD_UNLIKELY( data->first_ack_range > largest_ack ) ) {
    4790             :     /* this is a protocol violation, so inform the peer */
    4791           0 :     fd_quic_frame_error( context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
    4792           0 :     return FD_QUIC_PARSE_FAIL;
    4793           0 :   }
    4794             : 
    4795             :   /* update highest_acked */
    4796           0 :   conn->highest_acked[pn_space] = fd_ulong_max( conn->highest_acked[pn_space], largest_ack );
    4797             : 
    4798           0 :   fd_quic_state_t * state           = fd_quic_get_state( conn->quic );
    4799           0 :   long const        now             = state->now;
    4800           0 :   /******/          conn->last_ack  = now;
    4801             : 
    4802             :   /* RFC 9002, Section 6.1: We declare a packet p lost if either:
    4803             :      1. It was 'skipped': at least three packets were sent after p but before
    4804             :        the highest ack'ed packet in this ack frame, e.g. (p x y z highest_acked).
    4805             :      2. It 'expired': p was sent at least time-threshold time ago.
    4806             :        Time-threshold is computed in calc_expiry, and typically differs from
    4807             :        pkt_meta->expiry.
    4808             : 
    4809             :      Let skip_ceil be the smallest pkt_num such that any unacked pkt_meta
    4810             :      with pkt_num < skip_ceil is 'skipped' as defined above. We compute this
    4811             :      before removing acked packets from the tracker.
    4812             : 
    4813             :      We unfortunately can't just use 'largest_ack-3' because 1) largest_ack'd
    4814             :      may have been previously acknowledged and 2) we may have skipped pkt_nums.
    4815             :    */
    4816           0 :   ulong skip_ceil = 0UL;
    4817           0 :   if( FD_LIKELY( largest_ack > 0UL ) ) {
    4818           0 :     #define FD_QUIC_K_PACKET_THRESHOLD 3
    4819           0 :     fd_quic_pkt_meta_tracker_t * tracker  = &conn->pkt_meta_tracker;
    4820           0 :     fd_quic_pkt_meta_t         * pool     = tracker->pool;
    4821           0 :     fd_quic_pkt_meta_ds_t      * sent     = &tracker->sent_pkt_metas[enc_level];
    4822             : 
    4823           0 :     uint  pkt_num_changes = 0;
    4824           0 :     ulong prev_pkt_num    = ~0UL;
    4825           0 :     fd_quic_pkt_meta_ds_fwd_iter_t start = fd_quic_pkt_meta_ds_idx_le( sent, pool, largest_ack-1 );
    4826           0 :     for( fd_quic_pkt_meta_ds_rev_iter_t iter = start; /* rev<>fwd iter */
    4827           0 :          !!(pkt_num_changes<FD_QUIC_K_PACKET_THRESHOLD) & !fd_quic_pkt_meta_ds_rev_iter_done(iter);
    4828           0 :          iter=fd_quic_pkt_meta_ds_rev_iter_next( iter, pool ) ) {
    4829           0 :       fd_quic_pkt_meta_t * e  = fd_quic_pkt_meta_ds_rev_iter_ele( iter, pool );
    4830           0 :       pkt_num_changes        += !(e->key.pkt_num==prev_pkt_num);
    4831           0 :       prev_pkt_num            = e->key.pkt_num;
    4832           0 :     }
    4833           0 :     skip_ceil = fd_ulong_if( pkt_num_changes==FD_QUIC_K_PACKET_THRESHOLD, prev_pkt_num, 0UL );
    4834           0 :   }
    4835             : 
    4836             :   /* track lowest packet acked */
    4837           0 :   ulong low_ack_pkt_number = largest_ack - data->first_ack_range;
    4838             : 
    4839             :   /* process ack range
    4840             :      applies to pkt_number in [largest_ack - first_ack_range, largest_ack] */
    4841           0 :   fd_quic_process_ack_range( conn,
    4842           0 :                              context,
    4843           0 :                              enc_level,
    4844           0 :                              largest_ack,
    4845           0 :                              data->first_ack_range,
    4846           0 :                              1 /* is_largest */,
    4847           0 :                              now,
    4848           0 :                              data->ack_delay );
    4849             : 
    4850           0 :   uchar const * p_str = p;
    4851           0 :   uchar const * p_end = p + p_sz;
    4852             : 
    4853           0 :   ulong ack_range_count = data->ack_range_count;
    4854             : 
    4855             :   /* cur_pkt_number holds the packet number of the lowest processed
    4856             :      and acknowledged packet
    4857             :      This should always be a valid packet number >= 0 */
    4858           0 :   ulong cur_pkt_number = largest_ack - data->first_ack_range;
    4859             : 
    4860             :   /* walk thru ack ranges */
    4861           0 :   for( ulong j = 0UL; j < ack_range_count; ++j ) {
    4862           0 :     if( FD_UNLIKELY( p_end <= p ) ) {
    4863           0 :       fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
    4864           0 :       return FD_QUIC_PARSE_FAIL;
    4865           0 :     }
    4866             : 
    4867           0 :     fd_quic_ack_range_frag_t ack_range[1];
    4868           0 :     ulong rc = fd_quic_decode_ack_range_frag( ack_range, p, (ulong)( p_end - p ) );
    4869           0 :     if( FD_UNLIKELY( rc == FD_QUIC_PARSE_FAIL ) ) {
    4870           0 :       fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
    4871           0 :       return FD_QUIC_PARSE_FAIL;
    4872           0 :     }
    4873             : 
    4874             :     /* ensure we have ulong local vars, regardless of ack_range definition */
    4875           0 :     ulong gap    = (ulong)ack_range->gap;
    4876           0 :     ulong length = (ulong)ack_range->length;
    4877             : 
    4878             :     /* sanity check before unsigned arithmetic */
    4879           0 :     if( FD_UNLIKELY( ( gap    > ( ~0x3UL ) ) |
    4880           0 :                      ( length > ( ~0x3UL ) ) ) ) {
    4881             :       /* This is an unreasonably large value, so fail with protocol violation
    4882             :          It's also likely impossible due to the encoding method */
    4883           0 :       fd_quic_frame_error( context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
    4884           0 :       return FD_QUIC_PARSE_FAIL;
    4885           0 :     }
    4886             : 
    4887             :     /* The number of packet numbers to skip (they are not being acked) is
    4888             :        ack_range->gap + 2
    4889             :        This is +1 to get from the lowest acked packet to the highest unacked packet
    4890             :        and +1 because the count of packets in the gap is (ack_range->gap+1) */
    4891           0 :     ulong skip = gap + 2UL;
    4892             : 
    4893             :     /* verify the skip and length values are valid */
    4894           0 :     if( FD_UNLIKELY( skip + length > cur_pkt_number ) ) {
    4895             :       /* this is a protocol violation, so inform the peer */
    4896           0 :       fd_quic_frame_error( context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
    4897           0 :       return FD_QUIC_PARSE_FAIL;
    4898           0 :     }
    4899             : 
    4900             :     /* track lowest */
    4901           0 :     ulong lo_pkt_number = cur_pkt_number - skip - length;
    4902           0 :     low_ack_pkt_number = fd_ulong_min( low_ack_pkt_number, lo_pkt_number );
    4903             : 
    4904             :     /* process ack range */
    4905           0 :     fd_quic_process_ack_range( conn,
    4906           0 :                                context,
    4907           0 :                                enc_level,
    4908           0 :                                cur_pkt_number - skip,
    4909           0 :                                length,
    4910           0 :                                0 /* is_largest */,
    4911           0 :                                now,
    4912           0 :                                0 /* ack_delay not used here */ );
    4913             : 
    4914             :     /* Find the next lowest processed and acknowledged packet number
    4915             :        This should get us to the next lowest processed and acknowledged packet
    4916             :        number */
    4917           0 :     cur_pkt_number -= skip + length;
    4918             : 
    4919           0 :     p += rc;
    4920           0 :   }
    4921             : 
    4922             :   /* Process packets declared lost for either:
    4923             :   1. 'skipped': see skip_ceil computation above
    4924             :   2. 'expired': checked inside pkt_meta_retry  */
    4925           0 :   fd_quic_pkt_meta_retry( conn->quic, conn, skip_ceil, enc_level );
    4926             : 
    4927             :   /* ECN counts
    4928             :      we currently ignore them, but we must process them to get to the following bytes */
    4929           0 :   if( data->type & 1U ) {
    4930           0 :     if( FD_UNLIKELY( p_end <= p ) ) {
    4931           0 :       fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
    4932           0 :       return FD_QUIC_PARSE_FAIL;
    4933           0 :     }
    4934             : 
    4935           0 :     fd_quic_ecn_counts_frag_t ecn_counts[1];
    4936           0 :     ulong rc = fd_quic_decode_ecn_counts_frag( ecn_counts, p, (ulong)( p_end - p ) );
    4937           0 :     if( rc == FD_QUIC_PARSE_FAIL ) {
    4938           0 :       fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
    4939           0 :       return FD_QUIC_PARSE_FAIL;
    4940           0 :     }
    4941             : 
    4942           0 :     p += rc;
    4943           0 :   }
    4944             : 
    4945           0 :   return (ulong)( p - p_str );
    4946           0 : }
    4947             : 
    4948             : static ulong
    4949             : fd_quic_handle_reset_stream_frame(
    4950             :     fd_quic_frame_ctx_t *          context,
    4951             :     fd_quic_reset_stream_frame_t * data,
    4952             :     uchar const *                  p    FD_PARAM_UNUSED,
    4953           0 :     ulong                          p_sz FD_PARAM_UNUSED ) {
    4954             :   /* TODO implement */
    4955           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 );
    4956           0 :   return 0UL;
    4957           0 : }
    4958             : 
    4959             : static ulong
    4960             : fd_quic_handle_stop_sending_frame(
    4961             :     fd_quic_frame_ctx_t *          context,
    4962             :     fd_quic_stop_sending_frame_t * data,
    4963             :     uchar const *                  p    FD_PARAM_UNUSED,
    4964           0 :     ulong                          p_sz FD_PARAM_UNUSED ) {
    4965           0 :   FD_DTRACE_PROBE_3( quic_handle_stop_sending_frame, context->conn->our_conn_id, data->stream_id, data->app_proto_err_code );
    4966           0 :   return 0UL;
    4967           0 : }
    4968             : 
    4969             : static ulong
    4970             : fd_quic_handle_new_token_frame(
    4971             :     fd_quic_frame_ctx_t *       context,
    4972             :     fd_quic_new_token_frame_t * data,
    4973             :     uchar const *               p    FD_PARAM_UNUSED,
    4974           0 :     ulong                       p_sz FD_PARAM_UNUSED ) {
    4975             :   /* FIXME A server MUST treat receipt of a NEW_TOKEN frame as a connection error of type PROTOCOL_VIOLATION. */
    4976           0 :   (void)data;
    4977           0 :   FD_DTRACE_PROBE_1( quic_handle_new_token_frame, context->conn->our_conn_id );
    4978           0 :   return 0UL;
    4979           0 : }
    4980             : 
    4981             : void
    4982             : fd_quic_tx_stream_free( fd_quic_t *        quic,
    4983             :                         fd_quic_conn_t *   conn,
    4984             :                         fd_quic_stream_t * stream,
    4985           0 :                         int                code ) {
    4986             : 
    4987             :   /* TODO rename FD_QUIC_NOTIFY_END to FD_QUIC_STREAM_NOTIFY_END et al */
    4988           0 :   if( FD_LIKELY( stream->state != FD_QUIC_STREAM_STATE_DEAD ) ) {
    4989           0 :     fd_quic_cb_stream_notify( quic, stream, stream->context, code );
    4990           0 :     stream->state = FD_QUIC_STREAM_STATE_DEAD;
    4991           0 :   }
    4992             : 
    4993           0 :   ulong stream_id = stream->stream_id;
    4994             : 
    4995             :   /* remove from stream map */
    4996           0 :   fd_quic_stream_map_t * stream_map   = conn->stream_map;
    4997           0 :   fd_quic_stream_map_t * stream_entry = fd_quic_stream_map_query( stream_map, stream_id, NULL );
    4998           0 :   if( FD_LIKELY( stream_entry ) ) {
    4999           0 :     if( FD_LIKELY( stream_entry->stream ) ) {
    5000           0 :       stream_entry->stream->stream_flags = FD_QUIC_STREAM_FLAGS_DEAD;
    5001           0 :     }
    5002           0 :     fd_quic_stream_map_remove( stream_map, stream_entry );
    5003           0 :   }
    5004             : 
    5005             :   /* remove from list - idempotent */
    5006           0 :   FD_QUIC_STREAM_LIST_REMOVE( stream );
    5007           0 :   stream->stream_flags = FD_QUIC_STREAM_FLAGS_DEAD;
    5008           0 :   stream->stream_id    = ~0UL;
    5009             : 
    5010             :   /* add to stream_pool */
    5011           0 :   fd_quic_state_t * state = fd_quic_get_state( quic );
    5012           0 :   fd_quic_stream_pool_free( state->stream_pool, stream );
    5013             : 
    5014           0 : }
    5015             : 
    5016             : 
    5017             : static inline __attribute__((always_inline)) ulong
    5018             : fd_quic_handle_stream_frame(
    5019             :     fd_quic_frame_ctx_t * context,
    5020             :     uchar const *         p,
    5021             :     ulong                 p_sz,
    5022             :     ulong                 stream_id,
    5023             :     ulong                 offset,
    5024             :     ulong                 data_sz,
    5025           0 :     int                   fin ) {
    5026           0 :   fd_quic_t *      quic = context->quic;
    5027           0 :   fd_quic_conn_t * conn = context->conn;
    5028           0 :   fd_quic_pkt_t *  pkt  = context->pkt;
    5029             : 
    5030           0 :   FD_DTRACE_PROBE_5( quic_handle_stream_frame, conn->our_conn_id, stream_id, offset, data_sz, fin );
    5031             : 
    5032             :   /* stream_id type check */
    5033           0 :   ulong stream_type = stream_id & 3UL;
    5034           0 :   if( FD_UNLIKELY( stream_type != ( conn->server ? FD_QUIC_STREAM_TYPE_UNI_CLIENT : FD_QUIC_STREAM_TYPE_UNI_SERVER ) ) ) {
    5035           0 :     FD_DEBUG( FD_LOG_DEBUG(( "Received forbidden stream type" )); )
    5036             :     /* Technically should switch between STREAM_LIMIT_ERROR and STREAM_STATE_ERROR here */
    5037           0 :     fd_quic_frame_error( context, FD_QUIC_CONN_REASON_STREAM_LIMIT_ERROR, __LINE__ );
    5038           0 :     return FD_QUIC_PARSE_FAIL;
    5039           0 :   }
    5040             : 
    5041             :   /* length check */
    5042           0 :   if( FD_UNLIKELY( data_sz > p_sz ) ) {
    5043           0 :     FD_DEBUG( FD_LOG_DEBUG(( "Stream header indicates %lu bytes length, but only have %lu", data_sz, p_sz )); )
    5044           0 :     fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
    5045           0 :     return FD_QUIC_PARSE_FAIL;
    5046           0 :   }
    5047             : 
    5048           0 :   conn->unacked_sz += data_sz;
    5049             : 
    5050             :   /* stream_id outside allowed range - protocol error */
    5051           0 :   if( FD_UNLIKELY( stream_id >= conn->srx->rx_sup_stream_id ) ) {
    5052           0 :     FD_DEBUG( FD_LOG_DEBUG(( "Stream ID violation detected" )); )
    5053           0 :     fd_quic_frame_error( context, FD_QUIC_CONN_REASON_STREAM_LIMIT_ERROR, __LINE__ );
    5054           0 :     return FD_QUIC_PARSE_FAIL;
    5055           0 :   }
    5056             : 
    5057             :   /* A receiver MUST close the connection with an error of type FLOW_CONTROL_ERROR if the sender
    5058             :      violates the advertised connection or stream data limits */
    5059           0 :   if( FD_UNLIKELY( quic->config.initial_rx_max_stream_data < offset + data_sz ) ) {
    5060           0 :     FD_DEBUG( FD_LOG_DEBUG(( "Stream data limit exceeded" )); )
    5061           0 :     fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FLOW_CONTROL_ERROR, __LINE__ );
    5062           0 :     return FD_QUIC_PARSE_FAIL;
    5063           0 :   }
    5064             : 
    5065           0 :   int rx_res = fd_quic_cb_stream_rx( quic, conn, stream_id, offset, p, data_sz, fin );
    5066           0 :   pkt->ack_flag |= fd_uint_if( rx_res==FD_QUIC_SUCCESS, 0U, ACK_FLAG_CANCEL );
    5067             : 
    5068             :   /* packet bytes consumed */
    5069           0 :   return data_sz;
    5070           0 : }
    5071             : 
    5072             : static ulong
    5073             : fd_quic_handle_stream_8_frame(
    5074             :     fd_quic_frame_ctx_t *      context,
    5075             :     fd_quic_stream_8_frame_t * data,
    5076             :     uchar const *              p,
    5077           0 :     ulong                      p_sz ) {
    5078           0 :   return fd_quic_handle_stream_frame( context, p, p_sz, data->stream_id, 0UL, p_sz, data->type&1 );
    5079           0 : }
    5080             : 
    5081             : static ulong
    5082             : fd_quic_handle_stream_a_frame(
    5083             :     fd_quic_frame_ctx_t *      context,
    5084             :     fd_quic_stream_a_frame_t * data,
    5085             :     uchar const *              p,
    5086           0 :     ulong                      p_sz ) {
    5087           0 :   return fd_quic_handle_stream_frame( context, p, p_sz, data->stream_id, 0UL, data->length, data->type&1 );
    5088           0 : }
    5089             : 
    5090             : static ulong
    5091             : fd_quic_handle_stream_c_frame(
    5092             :     fd_quic_frame_ctx_t *      context,
    5093             :     fd_quic_stream_c_frame_t * data,
    5094             :     uchar const *              p,
    5095           0 :     ulong                      p_sz ) {
    5096           0 :   return fd_quic_handle_stream_frame( context, p, p_sz, data->stream_id, data->offset, p_sz, data->type&1 );
    5097           0 : }
    5098             : 
    5099             : static ulong
    5100             : fd_quic_handle_stream_e_frame(
    5101             :     fd_quic_frame_ctx_t *      context,
    5102             :     fd_quic_stream_e_frame_t * data,
    5103             :     uchar const *              p,
    5104           0 :     ulong                      p_sz ) {
    5105           0 :   return fd_quic_handle_stream_frame( context, p, p_sz, data->stream_id, data->offset, data->length, data->type&1 );
    5106           0 : }
    5107             : 
    5108             : static ulong
    5109             : fd_quic_handle_max_data_frame(
    5110             :     fd_quic_frame_ctx_t *      context,
    5111             :     fd_quic_max_data_frame_t * data,
    5112             :     uchar const *              p    FD_PARAM_UNUSED,
    5113           0 :     ulong                      p_sz FD_PARAM_UNUSED ) {
    5114           0 :   fd_quic_conn_t * conn = context->conn;
    5115             : 
    5116           0 :   ulong max_data_old = conn->tx_max_data;
    5117           0 :   ulong max_data_new = data->max_data;
    5118           0 :   FD_DTRACE_PROBE_3( quic_handle_max_data_frame, conn->our_conn_id, max_data_new, max_data_old );
    5119             : 
    5120             :   /* max data is only allowed to increase the limit. Transgressing frames
    5121             :      are silently ignored */
    5122           0 :   conn->tx_max_data = fd_ulong_max( max_data_old, max_data_new );
    5123           0 :   return 0; /* no additional bytes consumed from buffer */
    5124           0 : }
    5125             : 
    5126             : static ulong
    5127             : fd_quic_handle_max_stream_data_frame(
    5128             :     fd_quic_frame_ctx_t *             context,
    5129             :     fd_quic_max_stream_data_frame_t * data,
    5130             :     uchar const *                     p    FD_PARAM_UNUSED,
    5131           0 :     ulong                             p_sz FD_PARAM_UNUSED ) {
    5132             :   /* FIXME unsupported for now */
    5133           0 :   FD_DTRACE_PROBE_3( quic_handle_max_stream_data_frame, context->conn->our_conn_id, data->stream_id, data->max_stream_data );
    5134           0 :   return 0;
    5135           0 : }
    5136             : 
    5137             : static ulong
    5138             : fd_quic_handle_max_streams_frame(
    5139             :     fd_quic_frame_ctx_t *         context,
    5140             :     fd_quic_max_streams_frame_t * data,
    5141             :     uchar const *                 p    FD_PARAM_UNUSED,
    5142           0 :     ulong                         p_sz FD_PARAM_UNUSED ) {
    5143           0 :   fd_quic_conn_t * conn = context->conn;
    5144           0 :   FD_DTRACE_PROBE_3( quic_handle_max_streams_frame, conn->our_conn_id, data->type, data->max_streams );
    5145             : 
    5146           0 :   if( data->type == 0x13 ) {
    5147             :     /* Only handle unidirectional streams */
    5148           0 :     ulong type               = (ulong)conn->server | 2UL;
    5149             :     /* Receipt of a frame that permits opening of a stream larger than this limit (2^60)
    5150             :        MUST be treated as a connection error of type FRAME_ENCODING_ERROR. */
    5151           0 :     if( FD_UNLIKELY( data->max_streams > FD_QUIC_STREAM_COUNT_MAX ) ) {
    5152           0 :       fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
    5153           0 :       return FD_QUIC_PARSE_FAIL;
    5154           0 :     }
    5155           0 :     ulong peer_sup_stream_id = data->max_streams * 4UL + type;
    5156           0 :     conn->tx_sup_stream_id = fd_ulong_max( peer_sup_stream_id, conn->tx_sup_stream_id );
    5157           0 :   }
    5158             : 
    5159           0 :   return 0;
    5160           0 : }
    5161             : 
    5162             : static ulong
    5163             : fd_quic_handle_data_blocked_frame(
    5164             :     fd_quic_frame_ctx_t *          context,
    5165             :     fd_quic_data_blocked_frame_t * data,
    5166             :     uchar const *                  p    FD_PARAM_UNUSED,
    5167           0 :     ulong                          p_sz FD_PARAM_UNUSED ) {
    5168           0 :   FD_DTRACE_PROBE_2( quic_handle_data_blocked, context->conn->our_conn_id, data->max_data );
    5169             : 
    5170             :   /* Since we do not do runtime allocations, we will not attempt
    5171             :      to find more memory in the case of DATA_BLOCKED. */
    5172           0 :   return 0;
    5173           0 : }
    5174             : 
    5175             : static ulong
    5176             : fd_quic_handle_stream_data_blocked_frame(
    5177             :     fd_quic_frame_ctx_t *                 context,
    5178             :     fd_quic_stream_data_blocked_frame_t * data,
    5179             :     uchar const *                         p    FD_PARAM_UNUSED,
    5180           0 :     ulong                                 p_sz FD_PARAM_UNUSED ) {
    5181           0 :   FD_DTRACE_PROBE_3( quic_handle_stream_data_blocked, context->conn->our_conn_id, data->stream_id, data->max_stream_data );
    5182             : 
    5183             :   /* Since we do not do runtime allocations, we will not attempt
    5184             :      to find more memory in the case of STREAM_DATA_BLOCKED.*/
    5185           0 :   (void)data;
    5186           0 :   return 0;
    5187           0 : }
    5188             : 
    5189             : static ulong
    5190             : fd_quic_handle_streams_blocked_frame(
    5191             :     fd_quic_frame_ctx_t *             context,
    5192             :     fd_quic_streams_blocked_frame_t * data,
    5193             :     uchar const *                     p    FD_PARAM_UNUSED,
    5194           0 :     ulong                             p_sz FD_PARAM_UNUSED ) {
    5195           0 :   FD_DTRACE_PROBE_2( quic_handle_streams_blocked_frame, context->conn->our_conn_id, data->max_streams );
    5196             : 
    5197             :   /* STREAMS_BLOCKED should be sent by client when it wants
    5198             :      to use a new stream, but is unable to due to the max_streams
    5199             :      value
    5200             :      We can support this in the future, but as of 2024-Dec, the
    5201             :      Agave TPU client does not currently use it */
    5202           0 :   return 0;
    5203           0 : }
    5204             : 
    5205             : static ulong
    5206             : fd_quic_handle_new_conn_id_frame(
    5207             :     fd_quic_frame_ctx_t *         context,
    5208             :     fd_quic_new_conn_id_frame_t * data,
    5209             :     uchar const *                 p    FD_PARAM_UNUSED,
    5210           0 :     ulong                         p_sz FD_PARAM_UNUSED ) {
    5211             :   /* FIXME This is a mandatory feature but we don't support it yet */
    5212           0 :   FD_DTRACE_PROBE_1( quic_handle_new_conn_id_frame, context->conn->our_conn_id );
    5213           0 :   (void)data;
    5214           0 :   return 0;
    5215           0 : }
    5216             : 
    5217             : static ulong
    5218             : fd_quic_handle_retire_conn_id_frame(
    5219             :     fd_quic_frame_ctx_t *            context,
    5220             :     fd_quic_retire_conn_id_frame_t * data,
    5221             :     uchar const *                    p    FD_PARAM_UNUSED,
    5222           0 :     ulong                            p_sz FD_PARAM_UNUSED ) {
    5223             :   /* FIXME This is a mandatory feature but we don't support it yet */
    5224           0 :   FD_DTRACE_PROBE_1( quic_handle_retire_conn_id_frame, context->conn->our_conn_id );
    5225           0 :   (void)data;
    5226           0 :   FD_DEBUG( FD_LOG_DEBUG(( "retire_conn_id requested" )); )
    5227           0 :   return 0;
    5228           0 : }
    5229             : 
    5230             : static ulong
    5231             : fd_quic_handle_path_challenge_frame(
    5232             :     fd_quic_frame_ctx_t *            context,
    5233             :     fd_quic_path_challenge_frame_t * data,
    5234             :     uchar const *                    p    FD_PARAM_UNUSED,
    5235           0 :     ulong                            p_sz FD_PARAM_UNUSED ) {
    5236             :   /* FIXME The recipient of this frame MUST generate a PATH_RESPONSE frame (Section 19.18) containing the same Data value. */
    5237           0 :   FD_DTRACE_PROBE_1( quic_handle_path_challenge_frame, context->conn->our_conn_id );
    5238           0 :   (void)data;
    5239           0 :   return 0UL;
    5240           0 : }
    5241             : 
    5242             : static ulong
    5243             : fd_quic_handle_path_response_frame(
    5244             :     fd_quic_frame_ctx_t *           context,
    5245             :     fd_quic_path_response_frame_t * data,
    5246             :     uchar const *                   p    FD_PARAM_UNUSED,
    5247           0 :     ulong                           p_sz FD_PARAM_UNUSED ) {
    5248             :   /* We don't generate PATH_CHALLENGE frames, so this frame should never arrive */
    5249           0 :   FD_DTRACE_PROBE_1( quic_handle_path_response_frame, context->conn->our_conn_id );
    5250           0 :   (void)data;
    5251           0 :   return 0UL;
    5252           0 : }
    5253             : 
    5254             : static void
    5255           0 : fd_quic_handle_conn_close_frame( fd_quic_conn_t * conn ) {
    5256             :   /* frame type 0x1c means no error, or only error at quic level
    5257             :      frame type 0x1d means error at application layer
    5258             :      TODO provide APP with this info */
    5259           0 :   FD_DEBUG( FD_LOG_DEBUG(( "peer requested close" )) );
    5260             : 
    5261           0 :   switch( conn->state ) {
    5262           0 :     case FD_QUIC_CONN_STATE_PEER_CLOSE:
    5263           0 :     case FD_QUIC_CONN_STATE_ABORT:
    5264           0 :     case FD_QUIC_CONN_STATE_CLOSE_PENDING:
    5265           0 :       return;
    5266             : 
    5267           0 :     default:
    5268           0 :       fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_PEER_CLOSE );
    5269           0 :   }
    5270             : 
    5271           0 :   conn->upd_pkt_number = FD_QUIC_PKT_NUM_PENDING;
    5272           0 :   fd_quic_svc_prep_schedule_now( conn );
    5273           0 : }
    5274             : 
    5275             : static ulong
    5276             : fd_quic_handle_conn_close_0_frame(
    5277             :     fd_quic_frame_ctx_t *          context,
    5278             :     fd_quic_conn_close_0_frame_t * data,
    5279             :     uchar const *                  p,
    5280           0 :     ulong                          p_sz ) {
    5281           0 :   (void)p;
    5282             : 
    5283           0 :   ulong reason_phrase_length = data->reason_phrase_length;
    5284           0 :   if( FD_UNLIKELY( reason_phrase_length > p_sz ) ) {
    5285           0 :     fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
    5286           0 :     return FD_QUIC_PARSE_FAIL;
    5287           0 :   }
    5288             : 
    5289             :   /* the information here can be invaluable for debugging */
    5290           0 :   FD_DEBUG(
    5291           0 :     char reason_buf[256] = {0};
    5292           0 :     ulong reason_len = fd_ulong_min( sizeof(reason_buf)-1, reason_phrase_length );
    5293           0 :     memcpy( reason_buf, p, reason_len );
    5294             : 
    5295           0 :     FD_LOG_WARNING(( "fd_quic_handle_conn_close_frame - "
    5296           0 :         "error_code: %lu  "
    5297           0 :         "frame_type: %lx  "
    5298           0 :         "reason: %s "
    5299           0 :         "peer " FD_IP4_ADDR_FMT ":%u "
    5300           0 :         "conn_id %lu",
    5301           0 :         data->error_code,
    5302           0 :         data->frame_type,
    5303           0 :         reason_buf,
    5304           0 :         FD_IP4_ADDR_FMT_ARGS(context->conn->peer->ip_addr),
    5305           0 :         context->conn->peer->udp_port,
    5306           0 :         context->conn->our_conn_id ));
    5307           0 :   );
    5308             : 
    5309           0 :   fd_quic_handle_conn_close_frame( context->conn );
    5310             : 
    5311           0 :   return reason_phrase_length;
    5312           0 : }
    5313             : 
    5314             : static ulong
    5315             : fd_quic_handle_conn_close_1_frame(
    5316             :     fd_quic_frame_ctx_t *          context,
    5317             :     fd_quic_conn_close_1_frame_t * data,
    5318             :     uchar const *                  p,
    5319           0 :     ulong                          p_sz ) {
    5320           0 :   (void)p;
    5321             : 
    5322           0 :   ulong reason_phrase_length = data->reason_phrase_length;
    5323           0 :   if( FD_UNLIKELY( reason_phrase_length > p_sz ) ) {
    5324           0 :     fd_quic_frame_error( context, FD_QUIC_CONN_REASON_FRAME_ENCODING_ERROR, __LINE__ );
    5325           0 :     return FD_QUIC_PARSE_FAIL;
    5326           0 :   }
    5327             : 
    5328             :   /* the information here can be invaluable for debugging */
    5329           0 :   FD_DEBUG(
    5330           0 :     char reason_buf[256] = {0};
    5331           0 :     ulong reason_len = fd_ulong_min( sizeof(reason_buf)-1, reason_phrase_length );
    5332           0 :     memcpy( reason_buf, p, reason_len );
    5333             : 
    5334           0 :     FD_LOG_WARNING(( "fd_quic_handle_conn_close_frame - "
    5335           0 :         "error_code: %lu  "
    5336           0 :         "reason: %s "
    5337           0 :         "peer " FD_IP4_ADDR_FMT ":%u "
    5338           0 :         "conn_id %lu",
    5339           0 :         data->error_code,
    5340           0 :         reason_buf,
    5341           0 :         FD_IP4_ADDR_FMT_ARGS(context->conn->peer->ip_addr),
    5342           0 :         context->conn->peer->udp_port,
    5343           0 :         context->conn->our_conn_id ));
    5344           0 :   );
    5345             : 
    5346           0 :   fd_quic_handle_conn_close_frame( context->conn );
    5347             : 
    5348           0 :   return reason_phrase_length;
    5349           0 : }
    5350             : 
    5351             : static ulong
    5352             : fd_quic_handle_handshake_done_frame(
    5353             :     fd_quic_frame_ctx_t *            context,
    5354             :     fd_quic_handshake_done_frame_t * data,
    5355             :     uchar const *                    p    FD_PARAM_UNUSED,
    5356           0 :     ulong                            p_sz FD_PARAM_UNUSED ) {
    5357           0 :   fd_quic_conn_t * conn = context->conn;
    5358           0 :   (void)data;
    5359             : 
    5360             :   /* servers must treat receipt of HANDSHAKE_DONE as a protocol violation */
    5361           0 :   if( FD_UNLIKELY( conn->server ) ) {
    5362           0 :     fd_quic_frame_error( context, FD_QUIC_CONN_REASON_PROTOCOL_VIOLATION, __LINE__ );
    5363           0 :     return FD_QUIC_PARSE_FAIL;
    5364           0 :   }
    5365             : 
    5366           0 :   if( conn->state == FD_QUIC_CONN_STATE_HANDSHAKE ) {
    5367             :     /* still handshaking... assume packet was reordered */
    5368           0 :     context->pkt->ack_flag |= ACK_FLAG_CANCEL;
    5369           0 :     return 0UL;
    5370           0 :   } else if( conn->state != FD_QUIC_CONN_STATE_HANDSHAKE_COMPLETE ) {
    5371             :     /* duplicate frame or conn closing? */
    5372           0 :     return 0UL;
    5373           0 :   }
    5374             : 
    5375             :   /* Instantly acknowledge the first HANDSHAKE_DONE frame */
    5376           0 :   fd_quic_svc_prep_schedule_now( conn );
    5377             : 
    5378             :   /* RFC 9001 4.9.2. Discarding Handshake Keys
    5379             :      > An endpoint MUST discard its Handshake keys when the
    5380             :      > TLS handshake is confirmed
    5381             :      RFC 9001 4.1.2. Handshake Confirmed
    5382             :      > At the client, the handshake is considered confirmed when a
    5383             :      > HANDSHAKE_DONE frame is received. */
    5384           0 :   fd_quic_abandon_enc_level( conn, fd_quic_enc_level_handshake_id );
    5385             : 
    5386           0 :   if( FD_UNLIKELY( !conn->tls_hs ) ) {
    5387             :     /* sanity check */
    5388           0 :     return 0;
    5389           0 :   }
    5390             : 
    5391             :   /* eliminate any remaining hs_data at application level */
    5392           0 :   fd_quic_tls_clear_hs_data( conn->tls_hs, fd_quic_enc_level_appdata_id );
    5393             : 
    5394             :   /* we shouldn't be receiving this unless handshake is complete */
    5395           0 :   fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_ACTIVE );
    5396             : 
    5397             :   /* user callback */
    5398           0 :   fd_quic_cb_conn_hs_complete( conn->quic, conn );
    5399             : 
    5400             :   /* Deallocate tls_hs once completed */
    5401           0 :   if( FD_LIKELY( conn->tls_hs ) ) {
    5402           0 :     fd_quic_state_t * state = fd_quic_get_state( conn->quic );
    5403           0 :     fd_quic_tls_hs_delete( conn->tls_hs );
    5404           0 :     fd_quic_tls_hs_cache_ele_remove( &state->hs_cache, conn->tls_hs, state->hs_pool );
    5405           0 :     fd_quic_tls_hs_pool_ele_release( state->hs_pool, conn->tls_hs );
    5406           0 :     conn->tls_hs = NULL;
    5407           0 :   }
    5408             : 
    5409           0 :   return 0;
    5410           0 : }
    5411             : 
    5412             : /* initiate the shutdown of a connection
    5413             :    may select a reason code */
    5414             : void
    5415             : fd_quic_conn_close( fd_quic_conn_t * conn,
    5416           0 :                     uint             app_reason ) {
    5417           0 :   if( FD_UNLIKELY( !conn ) ) return;
    5418             : 
    5419           0 :   switch( conn->state ) {
    5420           0 :     case FD_QUIC_CONN_STATE_INVALID:
    5421           0 :     case FD_QUIC_CONN_STATE_DEAD:
    5422           0 :     case FD_QUIC_CONN_STATE_ABORT:
    5423           0 :       return; /* close has no effect in these states */
    5424             : 
    5425           0 :     default:
    5426           0 :       {
    5427           0 :         fd_quic_set_conn_state( conn, FD_QUIC_CONN_STATE_CLOSE_PENDING );
    5428           0 :         conn->app_reason = app_reason;
    5429           0 :       }
    5430           0 :   }
    5431             : 
    5432             :   /* set connection to be serviced ASAP */
    5433           0 :   fd_quic_svc_prep_schedule_now( conn );
    5434           0 :   fd_quic_svc_schedule1( conn );
    5435           0 : }
    5436             : 
    5437             : void
    5438             : fd_quic_conn_let_die( fd_quic_conn_t * conn,
    5439             :                       long             keep_alive_duration,
    5440           0 :                       long             now ) {
    5441           0 :   fd_quic_get_state( conn->quic )->now = now;
    5442           0 :   conn->let_die_time_ns = fd_long_sat_add( now, keep_alive_duration );
    5443             :   /* If we've missed the keep-alive time, schedule for immediate servicing */
    5444           0 :   if( FD_UNLIKELY( conn->last_activity+conn->idle_timeout_ns/2L < now ) ) {
    5445           0 :     fd_quic_svc_prep_schedule( conn, now );
    5446           0 :     fd_quic_svc_schedule1( conn );
    5447           0 :   }
    5448           0 : }

Generated by: LCOV version 1.14