lsquic_engine.c revision 7f2bd84c
1/* Copyright (c) 2017 - 2018 LiteSpeed Technologies Inc.  See LICENSE. */
2/*
3 * lsquic_engine.c - QUIC engine
4 */
5
6#include <assert.h>
7#include <errno.h>
8#include <inttypes.h>
9#include <stdint.h>
10#include <stdio.h>
11#include <stdlib.h>
12#include <string.h>
13#include <sys/queue.h>
14#include <time.h>
15#ifndef WIN32
16#include <sys/time.h>
17#include <netinet/in.h>
18#include <sys/types.h>
19#include <sys/stat.h>
20#include <fcntl.h>
21#include <unistd.h>
22#include <netdb.h>
23#endif
24
25
26
27#include "lsquic.h"
28#include "lsquic_types.h"
29#include "lsquic_alarmset.h"
30#include "lsquic_parse_common.h"
31#include "lsquic_parse.h"
32#include "lsquic_packet_in.h"
33#include "lsquic_packet_out.h"
34#include "lsquic_senhist.h"
35#include "lsquic_rtt.h"
36#include "lsquic_cubic.h"
37#include "lsquic_pacer.h"
38#include "lsquic_send_ctl.h"
39#include "lsquic_set.h"
40#include "lsquic_conn_flow.h"
41#include "lsquic_sfcw.h"
42#include "lsquic_stream.h"
43#include "lsquic_conn.h"
44#include "lsquic_full_conn.h"
45#include "lsquic_util.h"
46#include "lsquic_qtags.h"
47#include "lsquic_str.h"
48#include "lsquic_handshake.h"
49#include "lsquic_mm.h"
50#include "lsquic_conn_hash.h"
51#include "lsquic_engine_public.h"
52#include "lsquic_eng_hist.h"
53#include "lsquic_ev_log.h"
54#include "lsquic_version.h"
55#include "lsquic_hash.h"
56#include "lsquic_attq.h"
57#include "lsquic_min_heap.h"
58
59#define LSQUIC_LOGGER_MODULE LSQLM_ENGINE
60#include "lsquic_logger.h"
61
62
63/* The batch of outgoing packets grows and shrinks dynamically */
64#define MAX_OUT_BATCH_SIZE 1024
65#define MIN_OUT_BATCH_SIZE 256
66#define INITIAL_OUT_BATCH_SIZE 512
67
68struct out_batch
69{
70    lsquic_conn_t           *conns  [MAX_OUT_BATCH_SIZE];
71    lsquic_packet_out_t     *packets[MAX_OUT_BATCH_SIZE];
72    struct lsquic_out_spec   outs   [MAX_OUT_BATCH_SIZE];
73};
74
75typedef struct lsquic_conn * (*conn_iter_f)(struct lsquic_engine *);
76
77static void
78process_connections (struct lsquic_engine *engine, conn_iter_f iter,
79                     lsquic_time_t now);
80
81static void
82engine_incref_conn (lsquic_conn_t *conn, enum lsquic_conn_flags flag);
83
84static lsquic_conn_t *
85engine_decref_conn (lsquic_engine_t *engine, lsquic_conn_t *conn,
86                                        enum lsquic_conn_flags flag);
87
88static void
89force_close_conn (lsquic_engine_t *engine, lsquic_conn_t *conn);
90
91/* Nested calls to LSQUIC are not supported */
92#define ENGINE_IN(e) do {                               \
93    assert(!((e)->pub.enp_flags & ENPUB_PROC));         \
94    (e)->pub.enp_flags |= ENPUB_PROC;                   \
95} while (0)
96
97#define ENGINE_OUT(e) do {                              \
98    assert((e)->pub.enp_flags & ENPUB_PROC);            \
99    (e)->pub.enp_flags &= ~ENPUB_PROC;                  \
100} while (0)
101
102/* A connection can be referenced from one of six places:
103 *
104 *   1. Connection hash: a connection starts its life in one of those.
105 *
106 *   2. Outgoing queue.
107 *
108 *   3. Tickable queue
109 *
110 *   4. Advisory Tick Time queue.
111 *
112 *   5. Closing connections queue.  This is a transient queue -- it only
113 *      exists for the duration of process_connections() function call.
114 *
115 *   6. Ticked connections queue.  Another transient queue, similar to (5).
116 *
117 * The idea is to destroy the connection when it is no longer referenced.
118 * For example, a connection tick may return TICK_SEND|TICK_CLOSE.  In
119 * that case, the connection is referenced from two places: (2) and (5).
120 * After its packets are sent, it is only referenced in (5), and at the
121 * end of the function call, when it is removed from (5), reference count
122 * goes to zero and the connection is destroyed.  If not all packets can
123 * be sent, at the end of the function call, the connection is referenced
124 * by (2) and will only be removed once all outgoing packets have been
125 * sent.
126 */
127#define CONN_REF_FLAGS  (LSCONN_HASHED          \
128                        |LSCONN_HAS_OUTGOING    \
129                        |LSCONN_TICKABLE        \
130                        |LSCONN_TICKED          \
131                        |LSCONN_CLOSING         \
132                        |LSCONN_ATTQ)
133
134
135
136
137struct lsquic_engine
138{
139    struct lsquic_engine_public        pub;
140    enum {
141        ENG_SERVER      = LSENG_SERVER,
142        ENG_HTTP        = LSENG_HTTP,
143        ENG_COOLDOWN    = (1 <<  7),    /* Cooldown: no new connections */
144        ENG_PAST_DEADLINE
145                        = (1 <<  8),    /* Previous call to a processing
146                                         * function went past time threshold.
147                                         */
148#ifndef NDEBUG
149        ENG_DTOR        = (1 << 26),    /* Engine destructor */
150#endif
151    }                                  flags;
152    const struct lsquic_stream_if     *stream_if;
153    void                              *stream_if_ctx;
154    lsquic_packets_out_f               packets_out;
155    void                              *packets_out_ctx;
156    void                              *bad_handshake_ctx;
157    struct conn_hash                   conns_hash;
158    struct min_heap                    conns_tickable;
159    struct min_heap                    conns_out;
160    struct eng_hist                    history;
161    unsigned                           batch_size;
162    struct attq                       *attq;
163    /* Track time last time a packet was sent to give new connections
164     * priority lower than that of existing connections.
165     */
166    lsquic_time_t                      last_sent;
167    unsigned                           n_conns;
168    lsquic_time_t                      deadline;
169    struct out_batch                   out_batch;
170};
171
172
173void
174lsquic_engine_init_settings (struct lsquic_engine_settings *settings,
175                             unsigned flags)
176{
177    memset(settings, 0, sizeof(*settings));
178    settings->es_versions        = LSQUIC_DF_VERSIONS;
179    if (flags & ENG_SERVER)
180    {
181        settings->es_cfcw        = LSQUIC_DF_CFCW_SERVER;
182        settings->es_sfcw        = LSQUIC_DF_SFCW_SERVER;
183        settings->es_support_srej= LSQUIC_DF_SUPPORT_SREJ_SERVER;
184    }
185    else
186    {
187        settings->es_cfcw        = LSQUIC_DF_CFCW_CLIENT;
188        settings->es_sfcw        = LSQUIC_DF_SFCW_CLIENT;
189        settings->es_support_srej= LSQUIC_DF_SUPPORT_SREJ_CLIENT;
190    }
191    settings->es_max_streams_in  = LSQUIC_DF_MAX_STREAMS_IN;
192    settings->es_idle_conn_to    = LSQUIC_DF_IDLE_CONN_TO;
193    settings->es_handshake_to    = LSQUIC_DF_HANDSHAKE_TO;
194    settings->es_silent_close    = LSQUIC_DF_SILENT_CLOSE;
195    settings->es_max_header_list_size
196                                 = LSQUIC_DF_MAX_HEADER_LIST_SIZE;
197    settings->es_ua              = LSQUIC_DF_UA;
198
199    settings->es_pdmd            = QTAG_X509;
200    settings->es_aead            = QTAG_AESG;
201    settings->es_kexs            = QTAG_C255;
202    settings->es_support_push    = LSQUIC_DF_SUPPORT_PUSH;
203    settings->es_support_tcid0   = LSQUIC_DF_SUPPORT_TCID0;
204    settings->es_support_nstp    = LSQUIC_DF_SUPPORT_NSTP;
205    settings->es_honor_prst      = LSQUIC_DF_HONOR_PRST;
206    settings->es_progress_check  = LSQUIC_DF_PROGRESS_CHECK;
207    settings->es_rw_once         = LSQUIC_DF_RW_ONCE;
208    settings->es_proc_time_thresh= LSQUIC_DF_PROC_TIME_THRESH;
209    settings->es_pace_packets    = LSQUIC_DF_PACE_PACKETS;
210}
211
212
213/* Note: if returning an error, err_buf must be valid if non-NULL */
214int
215lsquic_engine_check_settings (const struct lsquic_engine_settings *settings,
216                              unsigned flags,
217                              char *err_buf, size_t err_buf_sz)
218{
219    if (settings->es_cfcw < LSQUIC_MIN_FCW ||
220        settings->es_sfcw < LSQUIC_MIN_FCW)
221    {
222        if (err_buf)
223            snprintf(err_buf, err_buf_sz, "%s",
224                                            "flow control window set too low");
225        return -1;
226    }
227    if (0 == (settings->es_versions & LSQUIC_SUPPORTED_VERSIONS))
228    {
229        if (err_buf)
230            snprintf(err_buf, err_buf_sz, "%s",
231                        "No supported QUIC versions specified");
232        return -1;
233    }
234    if (settings->es_versions & ~LSQUIC_SUPPORTED_VERSIONS)
235    {
236        if (err_buf)
237            snprintf(err_buf, err_buf_sz, "%s",
238                        "one or more unsupported QUIC version is specified");
239        return -1;
240    }
241    return 0;
242}
243
244
245static void
246free_packet (void *ctx, unsigned char *packet_data)
247{
248    free(packet_data);
249}
250
251
252static void *
253malloc_buf (void *ctx, size_t size)
254{
255    return malloc(size);
256}
257
258
259static const struct lsquic_packout_mem_if stock_pmi =
260{
261    malloc_buf, (void(*)(void *, void *)) free_packet,
262};
263
264
265static int
266hash_conns_by_addr (const struct lsquic_engine *engine)
267{
268    if (engine->pub.enp_settings.es_versions & LSQUIC_FORCED_TCID0_VERSIONS)
269        return 1;
270    if ((engine->pub.enp_settings.es_versions & LSQUIC_GQUIC_HEADER_VERSIONS)
271                                && engine->pub.enp_settings.es_support_tcid0)
272        return 1;
273    return 0;
274}
275
276
277lsquic_engine_t *
278lsquic_engine_new (unsigned flags,
279                   const struct lsquic_engine_api *api)
280{
281    lsquic_engine_t *engine;
282    int tag_buf_len;
283    char err_buf[100];
284
285    if (!api->ea_packets_out)
286    {
287        LSQ_ERROR("packets_out callback is not specified");
288        return NULL;
289    }
290
291    if (api->ea_settings &&
292                0 != lsquic_engine_check_settings(api->ea_settings, flags,
293                                                    err_buf, sizeof(err_buf)))
294    {
295        LSQ_ERROR("cannot create engine: %s", err_buf);
296        return NULL;
297    }
298
299    engine = calloc(1, sizeof(*engine));
300    if (!engine)
301        return NULL;
302    if (0 != lsquic_mm_init(&engine->pub.enp_mm))
303    {
304        free(engine);
305        return NULL;
306    }
307    if (api->ea_settings)
308        engine->pub.enp_settings        = *api->ea_settings;
309    else
310        lsquic_engine_init_settings(&engine->pub.enp_settings, flags);
311    tag_buf_len = lsquic_gen_ver_tags(engine->pub.enp_ver_tags_buf,
312                                    sizeof(engine->pub.enp_ver_tags_buf),
313                                    engine->pub.enp_settings.es_versions);
314    if (tag_buf_len <= 0)
315    {
316        LSQ_ERROR("cannot generate version tags buffer");
317        free(engine);
318        return NULL;
319    }
320    engine->pub.enp_ver_tags_len = tag_buf_len;
321    engine->pub.enp_flags = ENPUB_CAN_SEND;
322
323    engine->flags           = flags;
324    engine->stream_if       = api->ea_stream_if;
325    engine->stream_if_ctx   = api->ea_stream_if_ctx;
326    engine->packets_out     = api->ea_packets_out;
327    engine->packets_out_ctx = api->ea_packets_out_ctx;
328    if (api->ea_pmi)
329    {
330        engine->pub.enp_pmi      = api->ea_pmi;
331        engine->pub.enp_pmi_ctx  = api->ea_pmi_ctx;
332    }
333    else
334    {
335        engine->pub.enp_pmi      = &stock_pmi;
336        engine->pub.enp_pmi_ctx  = NULL;
337    }
338    engine->pub.enp_verify_cert  = api->ea_verify_cert;
339    engine->pub.enp_verify_ctx   = api->ea_verify_ctx;
340    engine->pub.enp_engine = engine;
341    conn_hash_init(&engine->conns_hash,
342                        hash_conns_by_addr(engine) ?  CHF_USE_ADDR : 0);
343    engine->attq = attq_create();
344    eng_hist_init(&engine->history);
345    engine->batch_size = INITIAL_OUT_BATCH_SIZE;
346
347
348    LSQ_INFO("instantiated engine");
349    return engine;
350}
351
352
353static void
354grow_batch_size (struct lsquic_engine *engine)
355{
356    engine->batch_size <<= engine->batch_size < MAX_OUT_BATCH_SIZE;
357}
358
359
360static void
361shrink_batch_size (struct lsquic_engine *engine)
362{
363    engine->batch_size >>= engine->batch_size > MIN_OUT_BATCH_SIZE;
364}
365
366
367/* Wrapper to make sure important things occur before the connection is
368 * really destroyed.
369 */
370static void
371destroy_conn (struct lsquic_engine *engine, lsquic_conn_t *conn)
372{
373    --engine->n_conns;
374    conn->cn_flags |= LSCONN_NEVER_TICKABLE;
375    conn->cn_if->ci_destroy(conn);
376}
377
378
379static int
380maybe_grow_conn_heaps (struct lsquic_engine *engine)
381{
382    struct min_heap_elem *els;
383    unsigned count;
384
385    if (engine->n_conns < lsquic_mh_nalloc(&engine->conns_tickable))
386        return 0;   /* Nothing to do */
387
388    if (lsquic_mh_nalloc(&engine->conns_tickable))
389        count = lsquic_mh_nalloc(&engine->conns_tickable) * 2 * 2;
390    else
391        count = 8;
392
393    els = malloc(sizeof(els[0]) * count);
394    if (!els)
395    {
396        LSQ_ERROR("%s: malloc failed", __func__);
397        return -1;
398    }
399
400    LSQ_DEBUG("grew heaps to %u elements", count / 2);
401    memcpy(&els[0], engine->conns_tickable.mh_elems,
402                sizeof(els[0]) * lsquic_mh_count(&engine->conns_tickable));
403    memcpy(&els[count / 2], engine->conns_out.mh_elems,
404                sizeof(els[0]) * lsquic_mh_count(&engine->conns_out));
405    free(engine->conns_tickable.mh_elems);
406    engine->conns_tickable.mh_elems = els;
407    engine->conns_out.mh_elems = &els[count / 2];
408    engine->conns_tickable.mh_nalloc = count / 2;
409    engine->conns_out.mh_nalloc = count / 2;
410    return 0;
411}
412
413
414static lsquic_conn_t *
415new_full_conn_client (lsquic_engine_t *engine, const char *hostname,
416                      unsigned short max_packet_size)
417{
418    lsquic_conn_t *conn;
419    unsigned flags;
420    if (0 != maybe_grow_conn_heaps(engine))
421        return NULL;
422    flags = engine->flags & (ENG_SERVER|ENG_HTTP);
423    conn = full_conn_client_new(&engine->pub, engine->stream_if,
424                    engine->stream_if_ctx, flags, hostname, max_packet_size);
425    if (!conn)
426        return NULL;
427    ++engine->n_conns;
428    return conn;
429}
430
431
432static lsquic_conn_t *
433find_conn (lsquic_engine_t *engine, lsquic_packet_in_t *packet_in,
434         struct packin_parse_state *ppstate, const struct sockaddr *sa_local)
435{
436    lsquic_conn_t *conn;
437
438    if (conn_hash_using_addr(&engine->conns_hash))
439        conn = conn_hash_find_by_addr(&engine->conns_hash, sa_local);
440    else if (packet_in->pi_flags & PI_CONN_ID)
441        conn = conn_hash_find_by_cid(&engine->conns_hash,
442                                                    packet_in->pi_conn_id);
443    else
444    {
445        LSQ_DEBUG("packet header does not have connection ID: discarding");
446        return NULL;
447    }
448
449    if (!conn)
450        return NULL;
451
452    conn->cn_pf->pf_parse_packet_in_finish(packet_in, ppstate);
453    if ((packet_in->pi_flags & PI_CONN_ID)
454        && conn->cn_cid != packet_in->pi_conn_id)
455    {
456        LSQ_DEBUG("connection IDs do not match");
457        return NULL;
458    }
459
460    return conn;
461}
462
463
464#if !defined(NDEBUG) && __GNUC__
465__attribute__((weak))
466#endif
467void
468lsquic_engine_add_conn_to_tickable (struct lsquic_engine_public *enpub,
469                                    lsquic_conn_t *conn)
470{
471    if (0 == (enpub->enp_flags & ENPUB_PROC) &&
472        0 == (conn->cn_flags & (LSCONN_TICKABLE|LSCONN_NEVER_TICKABLE)))
473    {
474        lsquic_engine_t *engine = (lsquic_engine_t *) enpub;
475        lsquic_mh_insert(&engine->conns_tickable, conn, conn->cn_last_ticked);
476        engine_incref_conn(conn, LSCONN_TICKABLE);
477    }
478}
479
480
481void
482lsquic_engine_add_conn_to_attq (struct lsquic_engine_public *enpub,
483                                lsquic_conn_t *conn, lsquic_time_t tick_time)
484{
485    lsquic_engine_t *const engine = (lsquic_engine_t *) enpub;
486    if (conn->cn_flags & LSCONN_TICKABLE)
487    {
488        /* Optimization: no need to add the connection to the Advisory Tick
489         * Time Queue: it is about to be ticked, after which it its next tick
490         * time may be queried again.
491         */;
492    }
493    else if (conn->cn_flags & LSCONN_ATTQ)
494    {
495        if (lsquic_conn_adv_time(conn) != tick_time)
496        {
497            attq_remove(engine->attq, conn);
498            if (0 != attq_add(engine->attq, conn, tick_time))
499                engine_decref_conn(engine, conn, LSCONN_ATTQ);
500        }
501    }
502    else if (0 == attq_add(engine->attq, conn, tick_time))
503        engine_incref_conn(conn, LSCONN_ATTQ);
504}
505
506
507/* Return 0 if packet is being processed by a connections, otherwise return 1 */
508static int
509process_packet_in (lsquic_engine_t *engine, lsquic_packet_in_t *packet_in,
510       struct packin_parse_state *ppstate, const struct sockaddr *sa_local,
511       const struct sockaddr *sa_peer, void *peer_ctx)
512{
513    lsquic_conn_t *conn;
514
515    if (lsquic_packet_in_is_gquic_prst(packet_in)
516                                && !engine->pub.enp_settings.es_honor_prst)
517    {
518        lsquic_mm_put_packet_in(&engine->pub.enp_mm, packet_in);
519        LSQ_DEBUG("public reset packet: discarding");
520        return 1;
521    }
522
523    conn = find_conn(engine, packet_in, ppstate, sa_local);
524
525    if (!conn)
526    {
527        lsquic_mm_put_packet_in(&engine->pub.enp_mm, packet_in);
528        return 1;
529    }
530
531    if (0 == (conn->cn_flags & LSCONN_TICKABLE))
532    {
533        lsquic_mh_insert(&engine->conns_tickable, conn, conn->cn_last_ticked);
534        engine_incref_conn(conn, LSCONN_TICKABLE);
535    }
536    lsquic_conn_record_sockaddr(conn, sa_local, sa_peer);
537    lsquic_packet_in_upref(packet_in);
538    conn->cn_peer_ctx = peer_ctx;
539    conn->cn_if->ci_packet_in(conn, packet_in);
540    lsquic_packet_in_put(&engine->pub.enp_mm, packet_in);
541    return 0;
542}
543
544
545void
546lsquic_engine_destroy (lsquic_engine_t *engine)
547{
548    lsquic_conn_t *conn;
549
550    LSQ_DEBUG("destroying engine");
551#ifndef NDEBUG
552    engine->flags |= ENG_DTOR;
553#endif
554
555    while ((conn = lsquic_mh_pop(&engine->conns_out)))
556    {
557        assert(conn->cn_flags & LSCONN_HAS_OUTGOING);
558        (void) engine_decref_conn(engine, conn, LSCONN_HAS_OUTGOING);
559    }
560
561    while ((conn = lsquic_mh_pop(&engine->conns_tickable)))
562    {
563        assert(conn->cn_flags & LSCONN_TICKABLE);
564        (void) engine_decref_conn(engine, conn, LSCONN_TICKABLE);
565    }
566
567    for (conn = conn_hash_first(&engine->conns_hash); conn;
568                            conn = conn_hash_next(&engine->conns_hash))
569        force_close_conn(engine, conn);
570    conn_hash_cleanup(&engine->conns_hash);
571
572    assert(0 == engine->n_conns);
573    attq_destroy(engine->attq);
574
575    assert(0 == lsquic_mh_count(&engine->conns_out));
576    assert(0 == lsquic_mh_count(&engine->conns_tickable));
577    free(engine->conns_tickable.mh_elems);
578    free(engine);
579}
580
581
582lsquic_conn_t *
583lsquic_engine_connect (lsquic_engine_t *engine, const struct sockaddr *local_sa,
584                       const struct sockaddr *peer_sa,
585                       void *peer_ctx, lsquic_conn_ctx_t *conn_ctx,
586                       const char *hostname, unsigned short max_packet_size)
587{
588    lsquic_conn_t *conn;
589    ENGINE_IN(engine);
590
591    if (engine->flags & ENG_SERVER)
592    {
593        LSQ_ERROR("`%s' must only be called in client mode", __func__);
594        goto err;
595    }
596
597    if (conn_hash_using_addr(&engine->conns_hash)
598                && conn_hash_find_by_addr(&engine->conns_hash, local_sa))
599    {
600        LSQ_ERROR("cannot have more than one connection on the same port");
601        goto err;
602    }
603
604    if (0 == max_packet_size)
605    {
606        switch (peer_sa->sa_family)
607        {
608        case AF_INET:
609            max_packet_size = QUIC_MAX_IPv4_PACKET_SZ;
610            break;
611        default:
612            max_packet_size = QUIC_MAX_IPv6_PACKET_SZ;
613            break;
614        }
615    }
616
617    conn = new_full_conn_client(engine, hostname, max_packet_size);
618    if (!conn)
619        goto err;
620    lsquic_conn_record_sockaddr(conn, local_sa, peer_sa);
621    if (0 != conn_hash_add(&engine->conns_hash, conn))
622    {
623        LSQ_WARN("cannot add connection %"PRIu64" to hash - destroy",
624            conn->cn_cid);
625        destroy_conn(engine, conn);
626        goto err;
627    }
628    assert(!(conn->cn_flags &
629        (CONN_REF_FLAGS
630         & ~LSCONN_TICKABLE /* This flag may be set as effect of user
631                                 callbacks */
632                             )));
633    conn->cn_flags |= LSCONN_HASHED;
634    lsquic_mh_insert(&engine->conns_tickable, conn, conn->cn_last_ticked);
635    engine_incref_conn(conn, LSCONN_TICKABLE);
636    conn->cn_peer_ctx = peer_ctx;
637    lsquic_conn_set_ctx(conn, conn_ctx);
638    full_conn_client_call_on_new(conn);
639  end:
640    ENGINE_OUT(engine);
641    return conn;
642  err:
643    conn = NULL;
644    goto end;
645}
646
647
648static void
649remove_conn_from_hash (lsquic_engine_t *engine, lsquic_conn_t *conn)
650{
651    conn_hash_remove(&engine->conns_hash, conn);
652    (void) engine_decref_conn(engine, conn, LSCONN_HASHED);
653}
654
655
656static void
657refflags2str (enum lsquic_conn_flags flags, char s[6])
658{
659    *s = 'C'; s += !!(flags & LSCONN_CLOSING);
660    *s = 'H'; s += !!(flags & LSCONN_HASHED);
661    *s = 'O'; s += !!(flags & LSCONN_HAS_OUTGOING);
662    *s = 'T'; s += !!(flags & LSCONN_TICKABLE);
663    *s = 'A'; s += !!(flags & LSCONN_ATTQ);
664    *s = 'K'; s += !!(flags & LSCONN_TICKED);
665    *s = '\0';
666}
667
668
669static void
670engine_incref_conn (lsquic_conn_t *conn, enum lsquic_conn_flags flag)
671{
672    char str[2][7];
673    assert(flag & CONN_REF_FLAGS);
674    assert(!(conn->cn_flags & flag));
675    conn->cn_flags |= flag;
676    LSQ_DEBUG("incref conn %"PRIu64", '%s' -> '%s'", conn->cn_cid,
677                    (refflags2str(conn->cn_flags & ~flag, str[0]), str[0]),
678                    (refflags2str(conn->cn_flags, str[1]), str[1]));
679}
680
681
682static lsquic_conn_t *
683engine_decref_conn (lsquic_engine_t *engine, lsquic_conn_t *conn,
684                                        enum lsquic_conn_flags flags)
685{
686    char str[2][7];
687    assert(flags & CONN_REF_FLAGS);
688    assert(conn->cn_flags & flags);
689#ifndef NDEBUG
690    if (flags & LSCONN_CLOSING)
691        assert(0 == (conn->cn_flags & LSCONN_HASHED));
692#endif
693    conn->cn_flags &= ~flags;
694    LSQ_DEBUG("decref conn %"PRIu64", '%s' -> '%s'", conn->cn_cid,
695                    (refflags2str(conn->cn_flags | flags, str[0]), str[0]),
696                    (refflags2str(conn->cn_flags, str[1]), str[1]));
697    if (0 == (conn->cn_flags & CONN_REF_FLAGS))
698    {
699        eng_hist_inc(&engine->history, 0, sl_del_full_conns);
700        destroy_conn(engine, conn);
701        return NULL;
702    }
703    else
704        return conn;
705}
706
707
708/* This is not a general-purpose function.  Only call from engine dtor. */
709static void
710force_close_conn (lsquic_engine_t *engine, lsquic_conn_t *conn)
711{
712    assert(engine->flags & ENG_DTOR);
713    const enum lsquic_conn_flags flags = conn->cn_flags;
714    assert(conn->cn_flags & CONN_REF_FLAGS);
715    assert(!(flags & LSCONN_HAS_OUTGOING));  /* Should be removed already */
716    assert(!(flags & LSCONN_TICKABLE));    /* Should be removed already */
717    assert(!(flags & LSCONN_CLOSING));  /* It is in transient queue? */
718    if (flags & LSCONN_ATTQ)
719    {
720        attq_remove(engine->attq, conn);
721        (void) engine_decref_conn(engine, conn, LSCONN_ATTQ);
722    }
723    if (flags & LSCONN_HASHED)
724        remove_conn_from_hash(engine, conn);
725}
726
727
728/* Iterator for tickable connections (those on the Tickable Queue).  Before
729 * a connection is returned, it is removed from the Advisory Tick Time queue
730 * if necessary.
731 */
732static lsquic_conn_t *
733conn_iter_next_tickable (struct lsquic_engine *engine)
734{
735    lsquic_conn_t *conn;
736
737    conn = lsquic_mh_pop(&engine->conns_tickable);
738
739    if (conn)
740        conn = engine_decref_conn(engine, conn, LSCONN_TICKABLE);
741    if (conn && (conn->cn_flags & LSCONN_ATTQ))
742    {
743        attq_remove(engine->attq, conn);
744        conn = engine_decref_conn(engine, conn, LSCONN_ATTQ);
745    }
746
747    return conn;
748}
749
750
751void
752lsquic_engine_process_conns (lsquic_engine_t *engine)
753{
754    lsquic_conn_t *conn;
755    lsquic_time_t now;
756
757    ENGINE_IN(engine);
758
759    now = lsquic_time_now();
760    while ((conn = attq_pop(engine->attq, now)))
761    {
762        conn = engine_decref_conn(engine, conn, LSCONN_ATTQ);
763        if (conn && !(conn->cn_flags & LSCONN_TICKABLE))
764        {
765            lsquic_mh_insert(&engine->conns_tickable, conn, conn->cn_last_ticked);
766            engine_incref_conn(conn, LSCONN_TICKABLE);
767        }
768    }
769
770    process_connections(engine, conn_iter_next_tickable, now);
771    ENGINE_OUT(engine);
772}
773
774
775static ssize_t
776really_encrypt_packet (const lsquic_conn_t *conn,
777                       struct lsquic_packet_out *packet_out,
778                       unsigned char *buf, size_t bufsz)
779{
780    int header_sz, is_hello_packet;
781    enum enc_level enc_level;
782    size_t packet_sz;
783    unsigned char header_buf[QUIC_MAX_PUBHDR_SZ];
784
785    header_sz = conn->cn_pf->pf_gen_reg_pkt_header(conn, packet_out,
786                                            header_buf, sizeof(header_buf));
787    if (header_sz < 0)
788        return -1;
789
790    is_hello_packet = !!(packet_out->po_flags & PO_HELLO);
791    enc_level = conn->cn_esf->esf_encrypt(conn->cn_enc_session,
792                conn->cn_version, 0,
793                packet_out->po_packno, header_buf, header_sz,
794                packet_out->po_data, packet_out->po_data_sz,
795                buf, bufsz, &packet_sz, is_hello_packet);
796    if ((int) enc_level >= 0)
797    {
798        lsquic_packet_out_set_enc_level(packet_out, enc_level);
799        LSQ_DEBUG("encrypted packet %"PRIu64"; plaintext is %zu bytes, "
800            "ciphertext is %zd bytes",
801            packet_out->po_packno,
802            conn->cn_pf->pf_packout_header_size(conn, packet_out->po_flags) +
803                                                packet_out->po_data_sz,
804            packet_sz);
805        return packet_sz;
806    }
807    else
808        return -1;
809}
810
811
812static enum { ENCPA_OK, ENCPA_NOMEM, ENCPA_BADCRYPT, }
813encrypt_packet (lsquic_engine_t *engine, const lsquic_conn_t *conn,
814                                            lsquic_packet_out_t *packet_out)
815{
816    ssize_t enc_sz;
817    size_t bufsz;
818    unsigned sent_sz;
819    unsigned char *buf;
820
821    bufsz = conn->cn_pf->pf_packout_header_size(conn, packet_out->po_flags) +
822                                packet_out->po_data_sz + QUIC_PACKET_HASH_SZ;
823    buf = engine->pub.enp_pmi->pmi_allocate(engine->pub.enp_pmi_ctx, bufsz);
824    if (!buf)
825    {
826        LSQ_DEBUG("could not allocate memory for outgoing packet of size %zd",
827                                                                        bufsz);
828        return ENCPA_NOMEM;
829    }
830
831    {
832        enc_sz = really_encrypt_packet(conn, packet_out, buf, bufsz);
833        sent_sz = enc_sz;
834    }
835
836    if (enc_sz < 0)
837    {
838        engine->pub.enp_pmi->pmi_release(engine->pub.enp_pmi_ctx, buf);
839        return ENCPA_BADCRYPT;
840    }
841
842    packet_out->po_enc_data    = buf;
843    packet_out->po_enc_data_sz = enc_sz;
844    packet_out->po_sent_sz     = sent_sz;
845    packet_out->po_flags |= PO_ENCRYPTED|PO_SENT_SZ;
846
847    return ENCPA_OK;
848}
849
850
851STAILQ_HEAD(conns_stailq, lsquic_conn);
852TAILQ_HEAD(conns_tailq, lsquic_conn);
853
854
855struct conns_out_iter
856{
857    struct min_heap            *coi_heap;
858    TAILQ_HEAD(, lsquic_conn)   coi_active_list,
859                                coi_inactive_list;
860    lsquic_conn_t              *coi_next;
861#ifndef NDEBUG
862    lsquic_time_t               coi_last_sent;
863#endif
864};
865
866
867static void
868coi_init (struct conns_out_iter *iter, struct lsquic_engine *engine)
869{
870    iter->coi_heap = &engine->conns_out;
871    iter->coi_next = NULL;
872    TAILQ_INIT(&iter->coi_active_list);
873    TAILQ_INIT(&iter->coi_inactive_list);
874#ifndef NDEBUG
875    iter->coi_last_sent = 0;
876#endif
877}
878
879
880static lsquic_conn_t *
881coi_next (struct conns_out_iter *iter)
882{
883    lsquic_conn_t *conn;
884
885    if (lsquic_mh_count(iter->coi_heap) > 0)
886    {
887        conn = lsquic_mh_pop(iter->coi_heap);
888        TAILQ_INSERT_TAIL(&iter->coi_active_list, conn, cn_next_out);
889        conn->cn_flags |= LSCONN_COI_ACTIVE;
890#ifndef NDEBUG
891        if (iter->coi_last_sent)
892            assert(iter->coi_last_sent <= conn->cn_last_sent);
893        iter->coi_last_sent = conn->cn_last_sent;
894#endif
895        return conn;
896    }
897    else if (!TAILQ_EMPTY(&iter->coi_active_list))
898    {
899        conn = iter->coi_next;
900        if (!conn)
901            conn = TAILQ_FIRST(&iter->coi_active_list);
902        if (conn)
903            iter->coi_next = TAILQ_NEXT(conn, cn_next_out);
904        return conn;
905    }
906    else
907        return NULL;
908}
909
910
911static void
912coi_deactivate (struct conns_out_iter *iter, lsquic_conn_t *conn)
913{
914    if (!(conn->cn_flags & LSCONN_EVANESCENT))
915    {
916        assert(!TAILQ_EMPTY(&iter->coi_active_list));
917        TAILQ_REMOVE(&iter->coi_active_list, conn, cn_next_out);
918        conn->cn_flags &= ~LSCONN_COI_ACTIVE;
919        TAILQ_INSERT_TAIL(&iter->coi_inactive_list, conn, cn_next_out);
920        conn->cn_flags |= LSCONN_COI_INACTIVE;
921    }
922}
923
924
925static void
926coi_reactivate (struct conns_out_iter *iter, lsquic_conn_t *conn)
927{
928    assert(conn->cn_flags & LSCONN_COI_INACTIVE);
929    TAILQ_REMOVE(&iter->coi_inactive_list, conn, cn_next_out);
930    conn->cn_flags &= ~LSCONN_COI_INACTIVE;
931    TAILQ_INSERT_TAIL(&iter->coi_active_list, conn, cn_next_out);
932    conn->cn_flags |= LSCONN_COI_ACTIVE;
933}
934
935
936static void
937coi_reheap (struct conns_out_iter *iter, lsquic_engine_t *engine)
938{
939    lsquic_conn_t *conn;
940    while ((conn = TAILQ_FIRST(&iter->coi_active_list)))
941    {
942        TAILQ_REMOVE(&iter->coi_active_list, conn, cn_next_out);
943        conn->cn_flags &= ~LSCONN_COI_ACTIVE;
944        lsquic_mh_insert(iter->coi_heap, conn, conn->cn_last_sent);
945    }
946    while ((conn = TAILQ_FIRST(&iter->coi_inactive_list)))
947    {
948        TAILQ_REMOVE(&iter->coi_inactive_list, conn, cn_next_out);
949        conn->cn_flags &= ~LSCONN_COI_INACTIVE;
950        (void) engine_decref_conn(engine, conn, LSCONN_HAS_OUTGOING);
951    }
952}
953
954
955static unsigned
956send_batch (lsquic_engine_t *engine, struct conns_out_iter *conns_iter,
957                  struct out_batch *batch, unsigned n_to_send)
958{
959    int n_sent, i;
960    lsquic_time_t now;
961
962    /* Set sent time before the write to avoid underestimating RTT */
963    now = lsquic_time_now();
964    for (i = 0; i < (int) n_to_send; ++i)
965        batch->packets[i]->po_sent = now;
966    n_sent = engine->packets_out(engine->packets_out_ctx, batch->outs,
967                                                                n_to_send);
968    if (n_sent >= 0)
969        LSQ_DEBUG("packets out returned %d (out of %u)", n_sent, n_to_send);
970    else
971    {
972        engine->pub.enp_flags &= ~ENPUB_CAN_SEND;
973        LSQ_DEBUG("packets out returned an error: %s", strerror(errno));
974        EV_LOG_GENERIC_EVENT("cannot send packets");
975        n_sent = 0;
976    }
977    if (n_sent > 0)
978        engine->last_sent = now + n_sent;
979    for (i = 0; i < n_sent; ++i)
980    {
981        eng_hist_inc(&engine->history, now, sl_packets_out);
982        EV_LOG_PACKET_SENT(batch->conns[i]->cn_cid, batch->packets[i]);
983        batch->conns[i]->cn_if->ci_packet_sent(batch->conns[i],
984                                                    batch->packets[i]);
985        /* `i' is added to maintain relative order */
986        batch->conns[i]->cn_last_sent = now + i;
987        /* Release packet out buffer as soon as the packet is sent
988         * successfully.  If not successfully sent, we hold on to
989         * this buffer until the packet sending is attempted again
990         * or until it times out and regenerated.
991         */
992        if (batch->packets[i]->po_flags & PO_ENCRYPTED)
993        {
994            batch->packets[i]->po_flags &= ~PO_ENCRYPTED;
995            engine->pub.enp_pmi->pmi_release(engine->pub.enp_pmi_ctx,
996                                                batch->packets[i]->po_enc_data);
997            batch->packets[i]->po_enc_data = NULL;  /* JIC */
998        }
999    }
1000    if (LSQ_LOG_ENABLED_EXT(LSQ_LOG_DEBUG, LSQLM_EVENT))
1001        for ( ; i < (int) n_to_send; ++i)
1002            EV_LOG_PACKET_NOT_SENT(batch->conns[i]->cn_cid, batch->packets[i]);
1003    /* Return packets to the connection in reverse order so that the packet
1004     * ordering is maintained.
1005     */
1006    for (i = (int) n_to_send - 1; i >= n_sent; --i)
1007    {
1008        batch->conns[i]->cn_if->ci_packet_not_sent(batch->conns[i],
1009                                                    batch->packets[i]);
1010        if (!(batch->conns[i]->cn_flags & (LSCONN_COI_ACTIVE|LSCONN_EVANESCENT)))
1011            coi_reactivate(conns_iter, batch->conns[i]);
1012    }
1013    return n_sent;
1014}
1015
1016
1017/* Return 1 if went past deadline, 0 otherwise */
1018static int
1019check_deadline (lsquic_engine_t *engine)
1020{
1021    if (engine->pub.enp_settings.es_proc_time_thresh &&
1022                                lsquic_time_now() > engine->deadline)
1023    {
1024        LSQ_INFO("went past threshold of %u usec, stop sending",
1025                            engine->pub.enp_settings.es_proc_time_thresh);
1026        engine->flags |= ENG_PAST_DEADLINE;
1027        return 1;
1028    }
1029    else
1030        return 0;
1031}
1032
1033
1034static void
1035send_packets_out (struct lsquic_engine *engine,
1036                  struct conns_tailq *ticked_conns,
1037                  struct conns_stailq *closed_conns)
1038{
1039    unsigned n, w, n_sent, n_batches_sent;
1040    lsquic_packet_out_t *packet_out;
1041    lsquic_conn_t *conn;
1042    struct out_batch *const batch = &engine->out_batch;
1043    struct conns_out_iter conns_iter;
1044    int shrink, deadline_exceeded;
1045
1046    coi_init(&conns_iter, engine);
1047    n_batches_sent = 0;
1048    n_sent = 0, n = 0;
1049    shrink = 0;
1050    deadline_exceeded = 0;
1051
1052    while ((conn = coi_next(&conns_iter)))
1053    {
1054        packet_out = conn->cn_if->ci_next_packet_to_send(conn);
1055        if (!packet_out) {
1056            LSQ_DEBUG("batched all outgoing packets for conn %"PRIu64,
1057                                                            conn->cn_cid);
1058            coi_deactivate(&conns_iter, conn);
1059            continue;
1060        }
1061        if (!(packet_out->po_flags & (PO_ENCRYPTED|PO_NOENCRYPT)))
1062        {
1063            switch (encrypt_packet(engine, conn, packet_out))
1064            {
1065            case ENCPA_NOMEM:
1066                /* Send what we have and wait for a more opportune moment */
1067                conn->cn_if->ci_packet_not_sent(conn, packet_out);
1068                goto end_for;
1069            case ENCPA_BADCRYPT:
1070                /* This is pretty bad: close connection immediately */
1071                conn->cn_if->ci_packet_not_sent(conn, packet_out);
1072                LSQ_INFO("conn %"PRIu64" has unsendable packets", conn->cn_cid);
1073                if (!(conn->cn_flags & LSCONN_EVANESCENT))
1074                {
1075                    if (!(conn->cn_flags & LSCONN_CLOSING))
1076                    {
1077                        STAILQ_INSERT_TAIL(closed_conns, conn, cn_next_closed_conn);
1078                        engine_incref_conn(conn, LSCONN_CLOSING);
1079                        if (conn->cn_flags & LSCONN_HASHED)
1080                            remove_conn_from_hash(engine, conn);
1081                    }
1082                    coi_deactivate(&conns_iter, conn);
1083                    if (conn->cn_flags & LSCONN_TICKED)
1084                    {
1085                        TAILQ_REMOVE(ticked_conns, conn, cn_next_ticked);
1086                        engine_decref_conn(engine, conn, LSCONN_TICKED);
1087                    }
1088                }
1089                continue;
1090            case ENCPA_OK:
1091                break;
1092            }
1093        }
1094        LSQ_DEBUG("batched packet %"PRIu64" for connection %"PRIu64,
1095                                        packet_out->po_packno, conn->cn_cid);
1096        assert(conn->cn_flags & LSCONN_HAS_PEER_SA);
1097        if (packet_out->po_flags & PO_ENCRYPTED)
1098        {
1099            batch->outs[n].buf     = packet_out->po_enc_data;
1100            batch->outs[n].sz      = packet_out->po_enc_data_sz;
1101        }
1102        else
1103        {
1104            batch->outs[n].buf     = packet_out->po_data;
1105            batch->outs[n].sz      = packet_out->po_data_sz;
1106        }
1107        batch->outs   [n].peer_ctx = conn->cn_peer_ctx;
1108        batch->outs   [n].local_sa = (struct sockaddr *) conn->cn_local_addr;
1109        batch->outs   [n].dest_sa  = (struct sockaddr *) conn->cn_peer_addr;
1110        batch->conns  [n]          = conn;
1111        batch->packets[n]          = packet_out;
1112        ++n;
1113        if (n == engine->batch_size)
1114        {
1115            n = 0;
1116            w = send_batch(engine, &conns_iter, batch, engine->batch_size);
1117            ++n_batches_sent;
1118            n_sent += w;
1119            if (w < engine->batch_size)
1120            {
1121                shrink = 1;
1122                break;
1123            }
1124            deadline_exceeded = check_deadline(engine);
1125            if (deadline_exceeded)
1126                break;
1127            grow_batch_size(engine);
1128        }
1129    }
1130  end_for:
1131
1132    if (n > 0) {
1133        w = send_batch(engine, &conns_iter, batch, n);
1134        n_sent += w;
1135        shrink = w < n;
1136        ++n_batches_sent;
1137        deadline_exceeded = check_deadline(engine);
1138    }
1139
1140    if (shrink)
1141        shrink_batch_size(engine);
1142    else if (n_batches_sent > 1 && !deadline_exceeded)
1143        grow_batch_size(engine);
1144
1145    coi_reheap(&conns_iter, engine);
1146
1147    LSQ_DEBUG("%s: sent %u packet%.*s", __func__, n_sent, n_sent != 1, "s");
1148}
1149
1150
1151int
1152lsquic_engine_has_unsent_packets (lsquic_engine_t *engine)
1153{
1154    return lsquic_mh_count(&engine->conns_out) > 0
1155    ;
1156}
1157
1158
1159static void
1160reset_deadline (lsquic_engine_t *engine, lsquic_time_t now)
1161{
1162    engine->deadline = now + engine->pub.enp_settings.es_proc_time_thresh;
1163    engine->flags &= ~ENG_PAST_DEADLINE;
1164}
1165
1166
1167/* TODO: this is a user-facing function, account for load */
1168void
1169lsquic_engine_send_unsent_packets (lsquic_engine_t *engine)
1170{
1171    lsquic_conn_t *conn;
1172    struct conns_stailq closed_conns;
1173    struct conns_tailq ticked_conns = TAILQ_HEAD_INITIALIZER(ticked_conns);
1174
1175    STAILQ_INIT(&closed_conns);
1176    reset_deadline(engine, lsquic_time_now());
1177    if (!(engine->pub.enp_flags & ENPUB_CAN_SEND))
1178    {
1179        LSQ_DEBUG("can send again");
1180        EV_LOG_GENERIC_EVENT("can send again");
1181        engine->pub.enp_flags |= ENPUB_CAN_SEND;
1182    }
1183
1184    send_packets_out(engine, &ticked_conns, &closed_conns);
1185
1186    while ((conn = STAILQ_FIRST(&closed_conns))) {
1187        STAILQ_REMOVE_HEAD(&closed_conns, cn_next_closed_conn);
1188        (void) engine_decref_conn(engine, conn, LSCONN_CLOSING);
1189    }
1190
1191}
1192
1193
1194static void
1195process_connections (lsquic_engine_t *engine, conn_iter_f next_conn,
1196                     lsquic_time_t now)
1197{
1198    lsquic_conn_t *conn;
1199    enum tick_st tick_st;
1200    unsigned i;
1201    lsquic_time_t next_tick_time;
1202    struct conns_stailq closed_conns;
1203    struct conns_tailq ticked_conns;
1204
1205    eng_hist_tick(&engine->history, now);
1206
1207    STAILQ_INIT(&closed_conns);
1208    TAILQ_INIT(&ticked_conns);
1209    reset_deadline(engine, now);
1210
1211    i = 0;
1212    while ((conn = next_conn(engine))
1213          )
1214    {
1215        tick_st = conn->cn_if->ci_tick(conn, now);
1216        conn->cn_last_ticked = now + i /* Maintain relative order */ ++;
1217        if (tick_st & TICK_SEND)
1218        {
1219            if (!(conn->cn_flags & LSCONN_HAS_OUTGOING))
1220            {
1221                lsquic_mh_insert(&engine->conns_out, conn, conn->cn_last_sent);
1222                engine_incref_conn(conn, LSCONN_HAS_OUTGOING);
1223            }
1224        }
1225        if (tick_st & TICK_CLOSE)
1226        {
1227            STAILQ_INSERT_TAIL(&closed_conns, conn, cn_next_closed_conn);
1228            engine_incref_conn(conn, LSCONN_CLOSING);
1229            if (conn->cn_flags & LSCONN_HASHED)
1230                remove_conn_from_hash(engine, conn);
1231        }
1232        else
1233        {
1234            TAILQ_INSERT_TAIL(&ticked_conns, conn, cn_next_ticked);
1235            engine_incref_conn(conn, LSCONN_TICKED);
1236        }
1237    }
1238
1239    if ((engine->pub.enp_flags & ENPUB_CAN_SEND)
1240                        && lsquic_engine_has_unsent_packets(engine))
1241        send_packets_out(engine, &ticked_conns, &closed_conns);
1242
1243    while ((conn = STAILQ_FIRST(&closed_conns))) {
1244        STAILQ_REMOVE_HEAD(&closed_conns, cn_next_closed_conn);
1245        (void) engine_decref_conn(engine, conn, LSCONN_CLOSING);
1246    }
1247
1248    /* TODO Heapification can be optimized by switching to the Floyd method:
1249     * https://en.wikipedia.org/wiki/Binary_heap#Building_a_heap
1250     */
1251    while ((conn = TAILQ_FIRST(&ticked_conns)))
1252    {
1253        TAILQ_REMOVE(&ticked_conns, conn, cn_next_ticked);
1254        engine_decref_conn(engine, conn, LSCONN_TICKED);
1255        if (!(conn->cn_flags & LSCONN_TICKABLE)
1256            && conn->cn_if->ci_is_tickable(conn))
1257        {
1258            lsquic_mh_insert(&engine->conns_tickable, conn, conn->cn_last_ticked);
1259            engine_incref_conn(conn, LSCONN_TICKABLE);
1260        }
1261        else if (!(conn->cn_flags & LSCONN_ATTQ))
1262        {
1263            next_tick_time = conn->cn_if->ci_next_tick_time(conn);
1264            if (next_tick_time)
1265            {
1266                if (0 == attq_add(engine->attq, conn, next_tick_time))
1267                    engine_incref_conn(conn, LSCONN_ATTQ);
1268            }
1269            else
1270                assert(0);
1271        }
1272    }
1273
1274}
1275
1276
1277/* Return 0 if packet is being processed by a real connection, 1 if the
1278 * packet was processed, but not by a connection, and -1 on error.
1279 */
1280int
1281lsquic_engine_packet_in (lsquic_engine_t *engine,
1282    const unsigned char *packet_in_data, size_t packet_in_size,
1283    const struct sockaddr *sa_local, const struct sockaddr *sa_peer,
1284    void *peer_ctx)
1285{
1286    struct packin_parse_state ppstate;
1287    lsquic_packet_in_t *packet_in;
1288    int (*parse_packet_in_begin) (struct lsquic_packet_in *, size_t length,
1289                                int is_server, struct packin_parse_state *);
1290
1291    if (packet_in_size > QUIC_MAX_PACKET_SZ)
1292    {
1293        LSQ_DEBUG("Cannot handle packet_in_size(%zd) > %d packet incoming "
1294            "packet's header", packet_in_size, QUIC_MAX_PACKET_SZ);
1295        errno = E2BIG;
1296        return -1;
1297    }
1298
1299    if (conn_hash_using_addr(&engine->conns_hash))
1300    {
1301        const struct lsquic_conn *conn;
1302        conn = conn_hash_find_by_addr(&engine->conns_hash, sa_local);
1303        if (!conn)
1304            return -1;
1305        if ((1 << conn->cn_version) & LSQUIC_GQUIC_HEADER_VERSIONS)
1306            parse_packet_in_begin = lsquic_gquic_parse_packet_in_begin;
1307        else
1308            parse_packet_in_begin = lsquic_iquic_parse_packet_in_begin;
1309    }
1310    else
1311        parse_packet_in_begin = lsquic_parse_packet_in_begin;
1312
1313    packet_in = lsquic_mm_get_packet_in(&engine->pub.enp_mm);
1314    if (!packet_in)
1315        return -1;
1316
1317    /* Library does not modify packet_in_data, it is not referenced after
1318     * this function returns and subsequent release of pi_data is guarded
1319     * by PI_OWN_DATA flag.
1320     */
1321    packet_in->pi_data = (unsigned char *) packet_in_data;
1322    if (0 != parse_packet_in_begin(packet_in, packet_in_size,
1323                                        engine->flags & ENG_SERVER, &ppstate))
1324    {
1325        LSQ_DEBUG("Cannot parse incoming packet's header");
1326        lsquic_mm_put_packet_in(&engine->pub.enp_mm, packet_in);
1327        errno = EINVAL;
1328        return -1;
1329    }
1330
1331    packet_in->pi_received = lsquic_time_now();
1332    eng_hist_inc(&engine->history, packet_in->pi_received, sl_packets_in);
1333    return process_packet_in(engine, packet_in, &ppstate, sa_local, sa_peer,
1334                                                                    peer_ctx);
1335}
1336
1337
1338#if __GNUC__ && !defined(NDEBUG)
1339__attribute__((weak))
1340#endif
1341unsigned
1342lsquic_engine_quic_versions (const lsquic_engine_t *engine)
1343{
1344    return engine->pub.enp_settings.es_versions;
1345}
1346
1347
1348int
1349lsquic_engine_earliest_adv_tick (lsquic_engine_t *engine, int *diff)
1350{
1351    const lsquic_time_t *next_time;
1352    lsquic_time_t now;
1353
1354    if (((engine->flags & ENG_PAST_DEADLINE)
1355                                    && lsquic_mh_count(&engine->conns_out))
1356        || lsquic_mh_count(&engine->conns_tickable))
1357    {
1358        *diff = 0;
1359        return 1;
1360    }
1361
1362    next_time = attq_next_time(engine->attq);
1363    if (!next_time)
1364        return 0;
1365
1366    now = lsquic_time_now();
1367    *diff = (int) ((int64_t) *next_time - (int64_t) now);
1368    return 1;
1369}
1370
1371
1372unsigned
1373lsquic_engine_count_attq (lsquic_engine_t *engine, int from_now)
1374{
1375    lsquic_time_t now;
1376    now = lsquic_time_now();
1377    if (from_now < 0)
1378        now -= from_now;
1379    else
1380        now += from_now;
1381    return attq_count_before(engine->attq, now);
1382}
1383