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