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