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