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