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

Generated by: LCOV version 1.14