lsquic_mini_conn_ietf.c revision de46bf2f
1/* Copyright (c) 2017 - 2019 LiteSpeed Technologies Inc.  See LICENSE. */
2/*
3 * lsquic_mini_conn_ietf.c -- Mini connection used by the IETF QUIC
4 */
5
6#include <assert.h>
7#include <errno.h>
8#include <inttypes.h>
9#include <stddef.h>
10#include <stdint.h>
11#include <string.h>
12#include <sys/queue.h>
13#include <stdlib.h>
14
15#include "lsquic.h"
16#include "lsquic_int_types.h"
17#include "lsquic_sizes.h"
18#include "lsquic_hash.h"
19#include "lsquic_conn.h"
20#include "lsquic_mm.h"
21#include "lsquic_malo.h"
22#include "lsquic_engine_public.h"
23#include "lsquic_packet_common.h"
24#include "lsquic_packet_in.h"
25#include "lsquic_packet_out.h"
26#include "lsquic_parse.h"
27#include "lsquic_rtt.h"
28#include "lsquic_util.h"
29#include "lsquic_enc_sess.h"
30#include "lsquic_mini_conn_ietf.h"
31#include "lsquic_ev_log.h"
32#include "lsquic_trans_params.h"
33#include "lsquic_ietf.h"
34#include "lsquic_packet_ietf.h"
35#include "lsquic_attq.h"
36#include "lsquic_alarmset.h"
37
38#define LSQUIC_LOGGER_MODULE LSQLM_MINI_CONN
39#define LSQUIC_LOG_CONN_ID lsquic_conn_log_cid(&conn->imc_conn)
40#include "lsquic_logger.h"
41
42#define MIN(a, b) ((a) < (b) ? (a) : (b))
43#define MAX(a, b) ((a) > (b) ? (a) : (b))
44
45static const struct conn_iface mini_conn_ietf_iface;
46
47static unsigned highest_bit_set (unsigned long long);
48
49
50static const enum header_type el2hety[] =
51{
52    [ENC_LEV_INIT]  = HETY_HANDSHAKE,
53    [ENC_LEV_CLEAR] = HETY_INITIAL,
54    [ENC_LEV_FORW]  = HETY_NOT_SET,
55    [ENC_LEV_EARLY] = 0,    /* Invalid */
56};
57
58
59static void
60imico_destroy_packet (struct ietf_mini_conn *conn,
61                                        struct lsquic_packet_out *packet_out)
62{
63    lsquic_packet_out_destroy(packet_out, conn->imc_enpub,
64                                                conn->imc_path.np_peer_ctx);
65}
66
67
68int
69lsquic_mini_conn_ietf_ecn_ok (const struct ietf_mini_conn *conn)
70{
71    packno_set_t acked;
72
73    /* First flight has only Initial and Handshake packets */
74    acked = conn->imc_acked_packnos[PNS_INIT]
75          | conn->imc_acked_packnos[PNS_HSK]
76          ;
77    return 0 != (conn->imc_ecn_packnos & acked);
78}
79
80
81#define imico_ecn_ok lsquic_mini_conn_ietf_ecn_ok
82
83
84static enum ecn
85imico_get_ecn (struct ietf_mini_conn *conn)
86{
87    if (!conn->imc_enpub->enp_settings.es_ecn)
88        return ECN_NOT_ECT;
89    else if (!conn->imc_sent_packnos /* We set ECT0 in first flight */
90                                                    || imico_ecn_ok(conn))
91        return ECN_ECT0;
92    else
93        return ECN_NOT_ECT;
94}
95
96
97static struct lsquic_packet_out *
98imico_get_packet_out (struct ietf_mini_conn *conn,
99                                    enum header_type header_type, size_t need)
100{
101    struct lsquic_packet_out *packet_out;
102    enum ecn ecn;
103
104    if (need)
105        TAILQ_FOREACH(packet_out, &conn->imc_packets_out, po_next)
106            if (!(packet_out->po_flags & PO_SENT)
107                    && packet_out->po_header_type == header_type
108                    && lsquic_packet_out_avail(packet_out) >= need)
109                return packet_out;
110
111    if (conn->imc_next_packno >= MAX_PACKETS)
112    {
113        LSQ_DEBUG("ran out of outgoing packet numbers, won't allocate packet");
114        return NULL;
115    }
116
117    packet_out = lsquic_packet_out_new(&conn->imc_enpub->enp_mm, NULL, 1,
118            &conn->imc_conn, IQUIC_PACKNO_LEN_1, NULL, NULL, &conn->imc_path);
119    if (!packet_out)
120    {
121        LSQ_WARN("could not allocate packet: %s", strerror(errno));
122        return NULL;
123    }
124
125    packet_out->po_header_type = header_type;
126    packet_out->po_packno = conn->imc_next_packno++;
127    packet_out->po_flags |= PO_MINI;
128    lsquic_packet_out_set_pns(packet_out, lsquic_hety2pns[header_type]);
129    ecn = imico_get_ecn(conn);
130    packet_out->po_lflags |= ecn << POECN_SHIFT;
131    TAILQ_INSERT_TAIL(&conn->imc_packets_out, packet_out, po_next);
132    packet_out->po_loss_chain = packet_out;
133    return packet_out;
134}
135
136
137static struct ietf_mini_conn *
138cryst_get_conn (const struct mini_crypto_stream *cryst)
139{
140    return (void *)
141        ((unsigned char *) (cryst - cryst->mcs_enc_level)
142                        - offsetof(struct ietf_mini_conn, imc_streams));
143}
144
145
146struct msg_ctx
147{
148    const unsigned char       *buf;
149    const unsigned char *const end;
150};
151
152
153static size_t
154read_from_msg_ctx (void *ctx, void *buf, size_t len)
155{
156    struct msg_ctx *msg_ctx = ctx;
157    if (len > (uintptr_t) (msg_ctx->end - msg_ctx->buf))
158        len = msg_ctx->end - msg_ctx->buf;
159    memcpy(buf, msg_ctx->buf, len);
160    msg_ctx->buf += len;
161    return len;
162}
163
164
165static ssize_t
166imico_stream_write (void *stream, const void *bufp, size_t bufsz)
167{
168    struct mini_crypto_stream *const cryst = stream;
169    struct ietf_mini_conn *const conn = cryst_get_conn(cryst);
170    struct lsquic_conn *const lconn = &conn->imc_conn;
171    const struct parse_funcs *const pf = lconn->cn_pf;
172    struct msg_ctx msg_ctx = { bufp, (unsigned char *) bufp + bufsz, };
173    struct lsquic_packet_out *packet_out;
174    size_t header_sz, need;
175    const unsigned char *p;
176    int len;
177
178    if (PNS_INIT == lsquic_enclev2pns[ cryst->mcs_enc_level ]
179                                        && (conn->imc_flags & IMC_IGNORE_INIT))
180    {
181        LSQ_WARN("trying to write at the ignored Initial level");
182        return bufsz;
183    }
184
185    while (msg_ctx.buf < msg_ctx.end)
186    {
187        header_sz = lconn->cn_pf->pf_calc_crypto_frame_header_sz(
188                            cryst->mcs_write_off, msg_ctx.end - msg_ctx.buf);
189        need = header_sz + 1;
190        packet_out = imico_get_packet_out(conn,
191                                        el2hety[ cryst->mcs_enc_level ], need);
192        if (!packet_out)
193            return -1;
194
195        p = msg_ctx.buf;
196        len = pf->pf_gen_crypto_frame(packet_out->po_data + packet_out->po_data_sz,
197                    lsquic_packet_out_avail(packet_out), cryst->mcs_write_off,
198                    msg_ctx.end - msg_ctx.buf, read_from_msg_ctx, &msg_ctx);
199        if (len < 0)
200            return len;
201        EV_LOG_GENERATED_CRYPTO_FRAME(LSQUIC_LOG_CONN_ID, pf,
202                                packet_out->po_data + packet_out->po_data_sz, len);
203        packet_out->po_data_sz += len;
204        packet_out->po_frame_types |= 1 << QUIC_FRAME_CRYPTO;
205        packet_out->po_flags |= PO_HELLO;
206        cryst->mcs_write_off += msg_ctx.buf - p;
207    }
208
209    assert(msg_ctx.buf == msg_ctx.end);
210    return bufsz;
211}
212
213
214static int
215imico_stream_flush (void *stream)
216{
217    return 0;
218}
219
220
221static struct stream_frame *
222imico_find_stream_frame (const struct ietf_mini_conn *conn,
223                                enum enc_level enc_level, unsigned read_off)
224{
225    struct stream_frame *frame;
226
227    if (conn->imc_last_in.frame && enc_level == conn->imc_last_in.enc_level
228            && read_off == DF_ROFF(conn->imc_last_in.frame))
229        return conn->imc_last_in.frame;
230
231    TAILQ_FOREACH(frame, &conn->imc_crypto_frames, next_frame)
232        if (enc_level == frame->stream_id && read_off == DF_ROFF(frame))
233            return frame;
234
235    return NULL;
236}
237
238
239static void
240imico_read_chlo_size (struct ietf_mini_conn *conn, const unsigned char *buf,
241                                                                    size_t sz)
242{
243    const unsigned char *const end = buf + sz;
244
245    assert(conn->imc_streams[ENC_LEV_CLEAR].mcs_read_off < 4);
246    switch (conn->imc_streams[ENC_LEV_CLEAR].mcs_read_off)
247    {
248    case 0:
249        if (buf == end)
250            return;
251        if (*buf != 1)
252        {
253            LSQ_DEBUG("Does not begin with ClientHello");
254            conn->imc_flags |= IMC_ERROR;
255            return;
256        }
257        ++buf;
258        /* fall-through */
259    case 1:
260        if (buf == end)
261            return;
262        if (*buf != 0)
263        {
264            LSQ_DEBUG("ClientHello larger than 16K");
265            conn->imc_flags |= IMC_ERROR;
266            return;
267        }
268        ++buf;
269        /* fall-through */
270    case 2:
271        if (buf == end)
272            return;
273        conn->imc_ch_len = *buf << 8;
274        ++buf;
275        /* fall-through */
276    default:
277        if (buf == end)
278            return;
279        conn->imc_ch_len |= *buf;
280    }
281}
282
283
284static int
285imico_chlo_has_been_consumed (const struct ietf_mini_conn *conn)
286{
287    return conn->imc_streams[ENC_LEV_CLEAR].mcs_read_off > 3
288        && conn->imc_streams[ENC_LEV_CLEAR].mcs_read_off >= conn->imc_ch_len;
289}
290
291
292static ssize_t
293imico_stream_readf (void *stream,
294        size_t (*readf)(void *, const unsigned char *, size_t, int), void *ctx)
295{
296    struct mini_crypto_stream *const cryst = stream;
297    struct ietf_mini_conn *const conn = cryst_get_conn(cryst);
298    struct stream_frame *frame;
299    const unsigned char *buf;
300    size_t nread, total_read;
301    unsigned avail;
302
303    total_read = 0;
304    while ((frame = imico_find_stream_frame(conn, cryst->mcs_enc_level,
305                                                        cryst->mcs_read_off)))
306    {
307        avail = DF_SIZE(frame) - frame->data_frame.df_read_off;
308        buf = frame->data_frame.df_data + frame->data_frame.df_read_off;
309        nread = readf(ctx, buf, avail, DF_FIN(frame));
310        if (cryst->mcs_enc_level == ENC_LEV_CLEAR && cryst->mcs_read_off < 4)
311            imico_read_chlo_size(conn, buf, nread);
312        total_read += nread;
313        cryst->mcs_read_off += nread;
314        frame->data_frame.df_read_off += nread;
315        LSQ_DEBUG("read %zu bytes at offset %"PRIu64" on enc level %u", nread,
316            DF_ROFF(frame), cryst->mcs_enc_level);
317        if (DF_END(frame) == DF_ROFF(frame))
318        {
319            if (frame == conn->imc_last_in.frame)
320                conn->imc_last_in.frame = NULL;
321            else
322            {
323                TAILQ_REMOVE(&conn->imc_crypto_frames, frame, next_frame);
324                --conn->imc_n_crypto_frames;
325                conn->imc_crypto_frames_sz -= DF_SIZE(frame);
326                lsquic_packet_in_put(&conn->imc_enpub->enp_mm,
327                                                            frame->packet_in);
328                lsquic_malo_put(frame);
329            }
330        }
331        if (nread < avail)
332            break;
333    }
334
335    if (total_read > 0)
336        return total_read;
337    else
338    {
339        /* CRYPTO streams never end, so zero bytes read always means
340         * EWOULDBLOCK
341         */
342        errno = EWOULDBLOCK;
343        return -1;
344    }
345}
346
347
348static int
349imico_stream_wantX (struct mini_crypto_stream *cryst, int bit, int is_want)
350{
351    int old;
352
353    old = (cryst->mcs_flags & (1 << bit)) > 0;
354    cryst->mcs_flags &= ~(1 << bit);
355    cryst->mcs_flags |= !!is_want << bit;
356    return old;
357}
358
359
360static int
361imico_stream_wantwrite (void *stream, int is_want)
362{
363    return imico_stream_wantX(stream, MCSBIT_WANTWRITE, is_want);
364}
365
366
367static int
368imico_stream_wantread (void *stream, int is_want)
369{
370    return imico_stream_wantX(stream, MCSBIT_WANTREAD, is_want);
371}
372
373
374static enum enc_level
375imico_stream_enc_level (void *stream)
376{
377    struct mini_crypto_stream *const cryst = stream;
378    return cryst->mcs_enc_level;
379}
380
381
382static const struct crypto_stream_if crypto_stream_if =
383{
384    .csi_write      = imico_stream_write,
385    .csi_flush      = imico_stream_flush,
386    .csi_readf      = imico_stream_readf,
387    .csi_wantwrite  = imico_stream_wantwrite,
388    .csi_wantread   = imico_stream_wantread,
389    .csi_enc_level  = imico_stream_enc_level,
390};
391
392
393static int
394is_first_packet_ok (const struct lsquic_packet_in *packet_in)
395{
396    if (packet_in->pi_data_sz < IQUIC_MIN_INIT_PACKET_SZ)
397    {
398        /* [draft-ietf-quic-transport-24] Section 14 */
399        LSQ_LOG1(LSQ_LOG_DEBUG, "incoming packet too small: %hu bytes",
400                                                    packet_in->pi_data_sz);
401        return 0;
402    }
403    /* TODO: Move decryption of the first packet into this function? */
404    return 1;   /* TODO */
405}
406
407
408struct lsquic_conn *
409lsquic_mini_conn_ietf_new (struct lsquic_engine_public *enpub,
410               const struct lsquic_packet_in *packet_in,
411           enum lsquic_version version, int is_ipv4, const lsquic_cid_t *odcid)
412{
413    struct ietf_mini_conn *conn;
414    enc_session_t *enc_sess;
415    enum enc_level i;
416    const struct enc_session_funcs_iquic *esfi;
417
418    if (!is_first_packet_ok(packet_in))
419        return NULL;
420
421    conn = lsquic_malo_get(enpub->enp_mm.malo.mini_conn_ietf);
422    if (!conn)
423    {
424        LSQ_LOG1(LSQ_LOG_WARN, "cannot allocate mini connection: %s",
425                                                            strerror(errno));
426        return NULL;
427    }
428    memset(conn, 0, sizeof(*conn));
429    conn->imc_conn.cn_if = &mini_conn_ietf_iface;
430    conn->imc_conn.cn_cces = conn->imc_cces;
431    conn->imc_conn.cn_n_cces = sizeof(conn->imc_cces)
432                                                / sizeof(conn->imc_cces[0]);
433    conn->imc_cces[0].cce_cid = packet_in->pi_dcid;
434    conn->imc_cces[0].cce_flags = CCE_USED;
435    conn->imc_conn.cn_cces_mask = 1;
436    lsquic_scid_from_packet_in(packet_in, &conn->imc_path.np_dcid);
437    LSQ_DEBUGC("recv SCID from client %"CID_FMT, CID_BITS(&conn->imc_cces[0].cce_cid));
438    LSQ_DEBUGC("recv DCID from client %"CID_FMT, CID_BITS(&conn->imc_path.np_dcid));
439
440    /* Generate new SCID. Since is not the original SCID, it is given
441     * a sequence number (0) and therefore can be retired by the client.
442     */
443    lsquic_generate_cid(&conn->imc_conn.cn_cces[1].cce_cid,
444                                        enpub->enp_settings.es_scid_len);
445    LSQ_DEBUGC("generated SCID %"CID_FMT" at index %u, switching to it",
446                CID_BITS(&conn->imc_conn.cn_cces[1].cce_cid), 1);
447    conn->imc_conn.cn_cces[1].cce_flags = CCE_SEQNO | CCE_USED;
448    conn->imc_conn.cn_cces_mask |= 1u << 1;
449    conn->imc_conn.cn_cur_cce_idx = 1;
450
451    conn->imc_conn.cn_flags = LSCONN_MINI|LSCONN_IETF|LSCONN_SERVER;
452
453    for (i = 0; i < N_ENC_LEVS; ++i)
454    {
455        conn->imc_streams[i].mcs_enc_level = i;
456        conn->imc_stream_ps[i] = &conn->imc_streams[i];
457    }
458
459    esfi = select_esf_iquic_by_ver(version);
460    enc_sess = esfi->esfi_create_server(enpub, &conn->imc_conn,
461                &packet_in->pi_dcid, conn->imc_stream_ps, &crypto_stream_if,
462                odcid);
463    if (!enc_sess)
464    {
465        lsquic_malo_put(conn);
466        return NULL;
467    }
468
469    conn->imc_enpub = enpub;
470    conn->imc_created = packet_in->pi_received;
471    conn->imc_path.np_pack_size = is_ipv4 ? IQUIC_MAX_IPv4_PACKET_SZ
472                                                    : IQUIC_MAX_IPv6_PACKET_SZ;
473#ifndef NDEBUG
474    if (getenv("LSQUIC_CN_PACK_SIZE"))
475        conn->imc_path.np_pack_size = atoi(getenv("LSQUIC_CN_PACK_SIZE"));
476#endif
477    conn->imc_conn.cn_version = version;
478    conn->imc_conn.cn_pf = select_pf_by_ver(version);
479    conn->imc_conn.cn_esf.i = esfi;
480    conn->imc_conn.cn_enc_session = enc_sess;
481    conn->imc_conn.cn_esf_c = select_esf_common_by_ver(version);
482    TAILQ_INIT(&conn->imc_packets_out);
483    TAILQ_INIT(&conn->imc_app_packets);
484    TAILQ_INIT(&conn->imc_crypto_frames);
485    if (odcid)
486        conn->imc_flags |= IMC_ADDR_VALIDATED;
487
488    LSQ_DEBUG("created mini connection object %p; max packet size=%hu",
489                                                conn, conn->imc_path.np_pack_size);
490    return &conn->imc_conn;
491}
492
493
494static void
495ietf_mini_conn_ci_client_call_on_new (struct lsquic_conn *lconn)
496{
497    assert(0);
498}
499
500
501static void
502ietf_mini_conn_ci_destroy (struct lsquic_conn *lconn)
503{
504    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
505    struct lsquic_packet_out *packet_out;
506    struct lsquic_packet_in *packet_in;
507    struct stream_frame *frame;
508
509    while ((packet_out = TAILQ_FIRST(&conn->imc_packets_out)))
510    {
511        TAILQ_REMOVE(&conn->imc_packets_out, packet_out, po_next);
512        imico_destroy_packet(conn, packet_out);
513    }
514    while ((packet_in = TAILQ_FIRST(&conn->imc_app_packets)))
515    {
516        TAILQ_REMOVE(&conn->imc_app_packets, packet_in, pi_next);
517        lsquic_packet_in_put(&conn->imc_enpub->enp_mm, packet_in);
518    }
519    while ((frame = TAILQ_FIRST(&conn->imc_crypto_frames)))
520    {
521        TAILQ_REMOVE(&conn->imc_crypto_frames, frame, next_frame);
522        lsquic_packet_in_put(&conn->imc_enpub->enp_mm, frame->packet_in);
523        lsquic_malo_put(frame);
524    }
525    if (lconn->cn_enc_session)
526        lconn->cn_esf.i->esfi_destroy(lconn->cn_enc_session);
527    LSQ_DEBUG("ietf_mini_conn_ci_destroyed");
528    lsquic_malo_put(conn);
529}
530
531
532static struct lsquic_engine *
533ietf_mini_conn_ci_get_engine (struct lsquic_conn *lconn)
534{
535    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
536    return conn->imc_enpub->enp_engine;
537}
538
539
540static void
541ietf_mini_conn_ci_hsk_done (struct lsquic_conn *lconn,
542                                                enum lsquic_hsk_status status)
543{
544    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
545
546    switch (status)
547    {
548    case LSQ_HSK_OK:
549    case LSQ_HSK_0RTT_OK:
550        conn->imc_flags |= IMC_HSK_OK;
551        conn->imc_conn.cn_flags |= LSCONN_HANDSHAKE_DONE;
552        LSQ_DEBUG("handshake OK");
553        break;
554    default:
555        assert(0);
556        /* fall-through */
557    case LSQ_HSK_FAIL:
558        conn->imc_flags |= IMC_HSK_FAILED|IMC_ERROR;
559        LSQ_INFO("handshake failed");
560        break;
561    }
562}
563
564
565static void
566ietf_mini_conn_ci_tls_alert (struct lsquic_conn *lconn, uint8_t alert)
567{
568    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
569    LSQ_DEBUG("got TLS alert %"PRIu8, alert);
570    conn->imc_flags |= IMC_ERROR|IMC_TLS_ALERT;
571    conn->imc_tls_alert = alert;
572}
573
574
575static int
576ietf_mini_conn_ci_is_tickable (struct lsquic_conn *lconn)
577{
578    /* A mini connection is never tickable:  Either there are incoming
579     * packets, in which case, the connection is going to be ticked, or
580     * there is an alarm pending, in which case it will be handled via
581     * the attq.
582     */
583    return 0;
584}
585
586
587static int
588imico_can_send (const struct ietf_mini_conn *conn, size_t size)
589{
590    return (conn->imc_flags & IMC_ADDR_VALIDATED)
591        || conn->imc_bytes_in * 3 >= conn->imc_bytes_out + size
592        ;
593}
594
595
596static struct lsquic_packet_out *
597ietf_mini_conn_ci_next_packet_to_send (struct lsquic_conn *lconn, size_t size)
598{
599    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
600    struct lsquic_packet_out *packet_out;
601    size_t packet_size;
602
603    TAILQ_FOREACH(packet_out, &conn->imc_packets_out, po_next)
604    {
605        if (packet_out->po_flags & PO_SENT)
606            continue;
607        packet_size = lsquic_packet_out_total_sz(lconn, packet_out);
608        if (size == 0 || packet_size + size <= conn->imc_path.np_pack_size)
609        {
610            if (!imico_can_send(conn, packet_size + IQUIC_TAG_LEN))
611            {
612                LSQ_DEBUG("cannot send packet %"PRIu64" of size %zu: client "
613                    "address has not been validated", packet_out->po_packno,
614                    packet_size + IQUIC_TAG_LEN);
615                return NULL;
616            }
617            packet_out->po_flags |= PO_SENT;
618            conn->imc_bytes_out += packet_size + IQUIC_TAG_LEN;
619            if (size == 0)
620                LSQ_DEBUG("packet_to_send: %"PRIu64, packet_out->po_packno);
621            else
622                LSQ_DEBUG("packet_to_send: %"PRIu64" (coalesced)",
623                                                    packet_out->po_packno);
624            return packet_out;
625        }
626        else
627            return NULL;
628    }
629
630    return NULL;
631}
632
633
634static int
635imico_calc_retx_timeout (const struct ietf_mini_conn *conn)
636{
637    lsquic_time_t to;
638    to = lsquic_rtt_stats_get_srtt(&conn->imc_rtt_stats);
639    if (to)
640    {
641        to += to / 2;
642        if (to < 10000)
643            to = 10000;
644    }
645    else
646        to = 300000;
647    return to << conn->imc_hsk_count;
648}
649
650
651static lsquic_time_t
652ietf_mini_conn_ci_next_tick_time (struct lsquic_conn *lconn, unsigned *why)
653{
654    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
655    const struct lsquic_packet_out *packet_out;
656    lsquic_time_t exp_time, retx_time;
657
658    exp_time = conn->imc_created +
659                        conn->imc_enpub->enp_settings.es_handshake_to;
660
661    TAILQ_FOREACH(packet_out, &conn->imc_packets_out, po_next)
662        if (packet_out->po_flags & PO_SENT)
663        {
664            retx_time = packet_out->po_sent + imico_calc_retx_timeout(conn);
665            if (retx_time < exp_time)
666            {
667                *why = N_AEWS + AL_RETX_HSK;
668                return retx_time;
669            }
670            else
671            {
672                *why = AEW_MINI_EXPIRE;
673                return exp_time;
674            }
675        }
676
677    *why = AEW_MINI_EXPIRE;
678    return exp_time;
679}
680
681
682#define IMICO_PROC_FRAME_ARGS                                           \
683    struct ietf_mini_conn *conn, struct lsquic_packet_in *packet_in,    \
684    const unsigned char *p, size_t len
685
686
687static void
688imico_dispatch_stream_events (struct ietf_mini_conn *conn)
689{
690    enum enc_level i;
691
692    for (i = 0; i < N_ENC_LEVS; ++i)
693        if ((conn->imc_streams[i].mcs_flags & (MCS_CREATED|MCS_WANTREAD))
694                                                == (MCS_CREATED|MCS_WANTREAD))
695        {
696            LSQ_DEBUG("dispatch read events on level #%u", i);
697            lsquic_mini_cry_sm_if.on_read((void *) &conn->imc_streams[i],
698                                            conn->imc_conn.cn_enc_session);
699        }
700
701    for (i = 0; i < N_ENC_LEVS; ++i)
702        if ((conn->imc_streams[i].mcs_flags & (MCS_CREATED|MCS_WANTWRITE))
703                                                == (MCS_CREATED|MCS_WANTWRITE))
704        {
705            LSQ_DEBUG("dispatch write events on level #%u", i);
706            lsquic_mini_cry_sm_if.on_write((void *) &conn->imc_streams[i],
707                                            conn->imc_conn.cn_enc_session);
708        }
709}
710
711
712static unsigned
713imico_process_stream_frame (IMICO_PROC_FRAME_ARGS)
714{
715    LSQ_WARN("%s: TODO", __func__);
716    return 0;
717}
718
719
720static int
721imico_stash_stream_frame (struct ietf_mini_conn *conn,
722        enum enc_level enc_level, struct lsquic_packet_in *packet_in,
723        const struct stream_frame *frame)
724{
725    struct stream_frame *copy;
726
727    if (conn->imc_n_crypto_frames >= IMICO_MAX_STASHED_FRAMES)
728    {
729        LSQ_INFO("cannot stash more CRYPTO frames, at %hhu already, while max "
730            "is %u", conn->imc_n_crypto_frames, IMICO_MAX_STASHED_FRAMES);
731        return -1;
732    }
733
734    if (conn->imc_crypto_frames_sz + DF_SIZE(frame) > IMICO_MAX_BUFFERED_CRYPTO)
735    {
736        LSQ_INFO("cannot stash more than %u bytes of CRYPTO frames",
737            IMICO_MAX_BUFFERED_CRYPTO);
738        return -1;
739    }
740
741    copy = lsquic_malo_get(conn->imc_enpub->enp_mm.malo.stream_frame);
742    if (!copy)
743    {
744        LSQ_INFO("could not allocate stream frame for stashing");
745        return -1;
746    }
747
748    *copy = *frame;
749    copy->packet_in = lsquic_packet_in_get(packet_in);
750    copy->stream_id = enc_level;
751    TAILQ_INSERT_TAIL(&conn->imc_crypto_frames, copy, next_frame);
752    ++conn->imc_n_crypto_frames;
753    conn->imc_crypto_frames_sz += DF_SIZE(frame);
754    return 0;
755}
756
757
758static unsigned
759imico_process_crypto_frame (IMICO_PROC_FRAME_ARGS)
760{
761    int parsed_len;
762    enum enc_level enc_level, i;
763    struct stream_frame stream_frame;
764    const struct transport_params *params;
765
766    parsed_len = conn->imc_conn.cn_pf->pf_parse_crypto_frame(p, len,
767                                                                &stream_frame);
768    if (parsed_len < 0)
769        return 0;
770
771    enc_level = lsquic_packet_in_enc_level(packet_in);
772    EV_LOG_CRYPTO_FRAME_IN(LSQUIC_LOG_CONN_ID, &stream_frame, enc_level);
773
774    if (conn->imc_streams[enc_level].mcs_read_off >= DF_OFF(&stream_frame)
775        && conn->imc_streams[enc_level].mcs_read_off < DF_END(&stream_frame))
776        LSQ_DEBUG("Got CRYPTO frame for enc level #%u", enc_level);
777    else if (conn->imc_streams[enc_level].mcs_read_off < DF_OFF(&stream_frame))
778    {
779        LSQ_DEBUG("Can't read CRYPTO frame on enc level #%u at offset %"PRIu64
780            " yet -- stash", enc_level, DF_OFF(&stream_frame));
781        if (0 == imico_stash_stream_frame(conn, enc_level, packet_in,
782                                                                &stream_frame))
783            return parsed_len;
784        else
785            return 0;
786    }
787    else
788    {
789        LSQ_DEBUG("Got duplicate CRYPTO frame for enc level #%u -- ignore",
790                                                                    enc_level);
791        return parsed_len;
792    }
793
794    if (!(conn->imc_flags & IMC_ENC_SESS_INITED))
795    {
796        if (0 != conn->imc_conn.cn_esf.i->esfi_init_server(
797                                            conn->imc_conn.cn_enc_session))
798            return -1;
799        conn->imc_flags |= IMC_ENC_SESS_INITED;
800    }
801
802    if (!(conn->imc_streams[enc_level].mcs_flags & MCS_CREATED))
803    {
804        LSQ_DEBUG("creating stream on level #%u", enc_level);
805        conn->imc_streams[enc_level].mcs_flags |= MCS_CREATED;
806        lsquic_mini_cry_sm_if.on_new_stream(conn->imc_conn.cn_enc_session,
807                                    (void *) &conn->imc_streams[enc_level]);
808    }
809
810    /* Assume that receiving a CRYPTO frame at a higher level means that we
811     * no longer want to read from a lower level.
812     */
813    for (i = 0; i < enc_level; ++i)
814        conn->imc_streams[i].mcs_flags &= ~MCS_WANTREAD;
815
816    conn->imc_last_in.frame = &stream_frame;
817    conn->imc_last_in.enc_level = enc_level;
818    imico_dispatch_stream_events(conn);
819    conn->imc_last_in.frame = NULL;
820
821    if (DF_ROFF(&stream_frame) < DF_END(&stream_frame))
822    {
823        /* This is an odd condition, but let's handle it just in case */
824        LSQ_DEBUG("New CRYPTO frame on enc level #%u not fully read -- stash",
825            enc_level);
826        if (0 != imico_stash_stream_frame(conn, enc_level, packet_in,
827                                                                &stream_frame))
828            return 0;
829    }
830
831
832    if (enc_level == ENC_LEV_CLEAR
833        && imico_chlo_has_been_consumed(conn)
834        && (conn->imc_flags & (IMC_ENC_SESS_INITED|IMC_HAVE_TP))
835                                                    == IMC_ENC_SESS_INITED)
836    {
837        params = conn->imc_conn.cn_esf.i->esfi_get_peer_transport_params(
838                                                conn->imc_conn.cn_enc_session);
839        if (params)
840        {
841            conn->imc_flags |= IMC_HAVE_TP;
842            conn->imc_ack_exp = params->tp_ack_delay_exponent;
843        }
844        else
845        {
846            conn->imc_flags |= IMC_BAD_TRANS_PARAMS;
847            return 0;
848        }
849    }
850
851    return parsed_len;
852}
853
854
855static ptrdiff_t
856imico_count_zero_bytes (const unsigned char *p, size_t len)
857{
858    const unsigned char *const end = p + len;
859    while (p < end && 0 == *p)
860        ++p;
861    return len - (end - p);
862}
863
864
865static unsigned
866imico_process_padding_frame (IMICO_PROC_FRAME_ARGS)
867{
868    len = (size_t) imico_count_zero_bytes(p, len);
869    EV_LOG_PADDING_FRAME_IN(LSQUIC_LOG_CONN_ID, len);
870    return len;
871}
872
873
874static void
875imico_take_rtt_sample (struct ietf_mini_conn *conn,
876                            const struct lsquic_packet_out *packet_out,
877                            lsquic_time_t now, lsquic_time_t lack_delta)
878{
879    assert(packet_out->po_sent);
880    lsquic_time_t measured_rtt = now - packet_out->po_sent;
881    if (lack_delta < measured_rtt)
882    {
883        lsquic_rtt_stats_update(&conn->imc_rtt_stats, measured_rtt, lack_delta);
884        LSQ_DEBUG("srtt: %"PRIu64" usec, var: %"PRIu64,
885                        lsquic_rtt_stats_get_srtt(&conn->imc_rtt_stats),
886                        lsquic_rtt_stats_get_rttvar(&conn->imc_rtt_stats));
887    }
888}
889
890
891static unsigned
892imico_process_ack_frame (IMICO_PROC_FRAME_ARGS)
893{
894    int parsed_len;
895    unsigned n;
896    lsquic_packet_out_t *packet_out, *next;
897    struct ack_info *acki;
898    lsquic_packno_t packno;
899    lsquic_time_t warn_time;
900    packno_set_t acked;
901    enum packnum_space pns;
902    uint8_t ack_exp;
903
904    if (conn->imc_flags & IMC_HAVE_TP)
905        ack_exp = conn->imc_ack_exp;
906    else
907        ack_exp = TP_DEF_ACK_DELAY_EXP; /* Odd: no transport params yet? */
908    acki = conn->imc_enpub->enp_mm.acki;
909    parsed_len = conn->imc_conn.cn_pf->pf_parse_ack_frame(p, len, acki,
910                                                                    ack_exp);
911    if (parsed_len < 0)
912        return 0;
913
914    pns = lsquic_hety2pns[ packet_in->pi_header_type ];
915    acked = 0;
916
917    for (n = 0; n < acki->n_ranges; ++n)
918    {
919        if (acki->ranges[n].high <= MAX_PACKETS)
920        {
921            acked |= (1ULL << acki->ranges[n].high)
922                                        | ((1ULL << acki->ranges[n].high) - 1);
923            acked &= ~((1ULL << acki->ranges[n].low) - 1);
924        }
925        else
926        {
927            packno = acki->ranges[n].high;
928            goto err_never_sent;
929        }
930    }
931    if (acked & ~conn->imc_sent_packnos)
932    {
933        packno = highest_bit_set(acked & ~conn->imc_sent_packnos);
934        goto err_never_sent;
935    }
936
937    EV_LOG_ACK_FRAME_IN(LSQUIC_LOG_CONN_ID, acki);
938    for (packet_out = TAILQ_FIRST(&conn->imc_packets_out); packet_out;
939                                                            packet_out = next)
940    {
941        next = TAILQ_NEXT(packet_out, po_next);
942        if ((1ULL << packet_out->po_packno) & acked)
943        {
944            assert(lsquic_packet_out_pns(packet_out) == pns);
945            LSQ_DEBUG("Got ACK for packet %"PRIu64, packet_out->po_packno);
946            if (packet_out->po_packno == largest_acked(acki))
947                imico_take_rtt_sample(conn, packet_out,
948                                    packet_in->pi_received, acki->lack_delta);
949            TAILQ_REMOVE(&conn->imc_packets_out, packet_out, po_next);
950            imico_destroy_packet(conn, packet_out);
951        }
952    }
953
954    if (conn->imc_sent_packnos & ~conn->imc_acked_packnos[pns] & acked)
955    {
956        LSQ_DEBUG("Newly acked packets, reset handshake count");
957        conn->imc_hsk_count = 0;
958    }
959
960    conn->imc_acked_packnos[pns] |= acked;
961
962    return parsed_len;
963
964  err_never_sent:
965    warn_time = lsquic_time_now();
966    if (0 == conn->imc_enpub->enp_last_warning[WT_ACKPARSE_MINI]
967        || conn->imc_enpub->enp_last_warning[WT_ACKPARSE_MINI]
968                + WARNING_INTERVAL < warn_time)
969    {
970        conn->imc_enpub->enp_last_warning[WT_ACKPARSE_MINI] = warn_time;
971        LSQ_WARN("packet %"PRIu64" (pns: %u) was never sent", packno, pns);
972    }
973    else
974        LSQ_DEBUG("packet %"PRIu64" (pns: %u) was never sent", packno, pns);
975    return 0;
976}
977
978
979static unsigned
980imico_process_ping_frame (IMICO_PROC_FRAME_ARGS)
981{
982    LSQ_DEBUG("got a PING frame, do nothing");
983    return 1;
984}
985
986
987static unsigned
988imico_process_connection_close_frame (IMICO_PROC_FRAME_ARGS)
989{
990    struct lsquic_packet_out *packet_out;
991    uint64_t error_code;
992    uint16_t reason_len;
993    uint8_t reason_off;
994    int parsed_len, app_error;
995
996    while ((packet_out = TAILQ_FIRST(&conn->imc_packets_out)))
997    {
998        TAILQ_REMOVE(&conn->imc_packets_out, packet_out, po_next);
999        imico_destroy_packet(conn, packet_out);
1000    }
1001    conn->imc_flags |= IMC_CLOSE_RECVD;
1002    parsed_len = conn->imc_conn.cn_pf->pf_parse_connect_close_frame(p, len,
1003                            &app_error, &error_code, &reason_len, &reason_off);
1004    if (parsed_len < 0)
1005        return 0;
1006    EV_LOG_CONNECTION_CLOSE_FRAME_IN(LSQUIC_LOG_CONN_ID, error_code,
1007                            (int) reason_len, (const char *) p + reason_off);
1008    LSQ_INFO("Received CONNECTION_CLOSE frame (%s-level code: %"PRIu64"; "
1009            "reason: %.*s)", app_error ? "application" : "transport",
1010                error_code, (int) reason_len, (const char *) p + reason_off);
1011    return 0;   /* This shuts down the connection */
1012}
1013
1014
1015static unsigned
1016imico_process_invalid_frame (IMICO_PROC_FRAME_ARGS)
1017{
1018    LSQ_DEBUG("invalid frame %u (%s)", p[0],
1019        frame_type_2_str[ conn->imc_conn.cn_pf->pf_parse_frame_type(p[0]) ]);
1020    return 0;
1021}
1022
1023
1024static unsigned (*const imico_process_frames[N_QUIC_FRAMES])
1025                                                (IMICO_PROC_FRAME_ARGS) =
1026{
1027    [QUIC_FRAME_PADDING]            =  imico_process_padding_frame,
1028    [QUIC_FRAME_STREAM]             =  imico_process_stream_frame,
1029    [QUIC_FRAME_CRYPTO]             =  imico_process_crypto_frame,
1030    [QUIC_FRAME_ACK]                =  imico_process_ack_frame,
1031    [QUIC_FRAME_PING]               =  imico_process_ping_frame,
1032    [QUIC_FRAME_CONNECTION_CLOSE]   =  imico_process_connection_close_frame,
1033    /* XXX: Some of them are invalid, while others are unexpected.  We treat
1034     * them the same: handshake cannot proceed.
1035     */
1036    [QUIC_FRAME_RST_STREAM]         =  imico_process_invalid_frame,
1037    [QUIC_FRAME_MAX_DATA]           =  imico_process_invalid_frame,
1038    [QUIC_FRAME_MAX_STREAM_DATA]    =  imico_process_invalid_frame,
1039    [QUIC_FRAME_MAX_STREAMS]        =  imico_process_invalid_frame,
1040    [QUIC_FRAME_BLOCKED]            =  imico_process_invalid_frame,
1041    [QUIC_FRAME_STREAM_BLOCKED]     =  imico_process_invalid_frame,
1042    [QUIC_FRAME_STREAMS_BLOCKED]    =  imico_process_invalid_frame,
1043    [QUIC_FRAME_NEW_CONNECTION_ID]  =  imico_process_invalid_frame,
1044    [QUIC_FRAME_STOP_SENDING]       =  imico_process_invalid_frame,
1045    [QUIC_FRAME_PATH_CHALLENGE]     =  imico_process_invalid_frame,
1046    [QUIC_FRAME_PATH_RESPONSE]      =  imico_process_invalid_frame,
1047};
1048
1049
1050static unsigned
1051imico_process_packet_frame (struct ietf_mini_conn *conn,
1052        struct lsquic_packet_in *packet_in, const unsigned char *p, size_t len)
1053{
1054    enum enc_level enc_level = lsquic_packet_in_enc_level(packet_in);
1055    enum quic_frame_type type = conn->imc_conn.cn_pf->pf_parse_frame_type(p[0]);
1056    if (lsquic_legal_frames_by_level[enc_level] & (1 << type))
1057    {
1058        packet_in->pi_frame_types |= 1 << type;
1059        return imico_process_frames[type](conn, packet_in, p, len);
1060    }
1061    else
1062    {
1063        LSQ_DEBUG("invalid frame %u at encryption level %s", type,
1064                                                lsquic_enclev2str[enc_level]);
1065        return 0;
1066    }
1067}
1068
1069
1070static int
1071imico_parse_regular_packet (struct ietf_mini_conn *conn,
1072                                        struct lsquic_packet_in *packet_in)
1073{
1074    const unsigned char *p, *pend;
1075    unsigned len;
1076
1077    p = packet_in->pi_data + packet_in->pi_header_sz;
1078    pend = packet_in->pi_data + packet_in->pi_data_sz;
1079
1080    while (p < pend)
1081    {
1082        len = imico_process_packet_frame(conn, packet_in, p, pend - p);
1083        if (len > 0)
1084            p += len;
1085        else
1086            return -1;
1087    }
1088
1089    return 0;
1090}
1091
1092
1093static unsigned
1094highest_bit_set (unsigned long long sz)
1095{
1096#if __GNUC__
1097    unsigned clz = __builtin_clzll(sz);
1098    return 63 - clz;
1099#else
1100    unsigned long y;
1101    unsigned n;
1102    n = 64;
1103    y = sz >> 32;     if (y) { n -= 32; sz = y; }
1104    y = sz >> 16;     if (y) { n -= 16; sz = y; }
1105    y = sz >>  8;     if (y) { n -=  8; sz = y; }
1106    y = sz >>  4;     if (y) { n -=  4; sz = y; }
1107    y = sz >>  2;     if (y) { n -=  2; sz = y; }
1108    y = sz >>  1;     if (y) return 63 - n + 2;
1109    return 63 - n + sz;
1110#endif
1111}
1112
1113
1114static void
1115ignore_init (struct ietf_mini_conn *conn)
1116{
1117    struct lsquic_packet_out *packet_out, *next;
1118    unsigned count;
1119
1120    conn->imc_flags |= IMC_IGNORE_INIT;
1121    conn->imc_flags &= ~(IMC_QUEUED_ACK_INIT << PNS_INIT);
1122
1123    count = 0;
1124    for (packet_out = TAILQ_FIRST(&conn->imc_packets_out); packet_out;
1125                                                            packet_out = next)
1126    {
1127        next = TAILQ_NEXT(packet_out, po_next);
1128        if (PNS_INIT == lsquic_packet_out_pns(packet_out))
1129        {
1130            TAILQ_REMOVE(&conn->imc_packets_out, packet_out, po_next);
1131            imico_destroy_packet(conn, packet_out);
1132            ++count;
1133        }
1134    }
1135
1136    LSQ_DEBUG("henceforth, no Initial packets shall be sent or received; "
1137        "destroyed %u packet%.*s", count, count != 1, "s");
1138}
1139
1140
1141/* Only a single packet is supported */
1142static void
1143ietf_mini_conn_ci_packet_in (struct lsquic_conn *lconn,
1144                        struct lsquic_packet_in *packet_in)
1145{
1146    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1147    enum dec_packin dec_packin;
1148    enum packnum_space pns;
1149
1150    if (conn->imc_flags & IMC_ERROR)
1151    {
1152        LSQ_DEBUG("ignore incoming packet: connection is in error state");
1153        return;
1154    }
1155
1156    pns = lsquic_hety2pns[ packet_in->pi_header_type ];
1157    if (pns == PNS_INIT && (conn->imc_flags & IMC_IGNORE_INIT))
1158    {
1159        LSQ_DEBUG("ignore init packet");    /* Don't bother decrypting */
1160        return;
1161    }
1162
1163    dec_packin = lconn->cn_esf_c->esf_decrypt_packet(lconn->cn_enc_session,
1164                                conn->imc_enpub, &conn->imc_conn, packet_in);
1165    if (dec_packin != DECPI_OK)
1166    {
1167        /* TODO: handle reordering perhaps? */
1168        LSQ_DEBUG("could not decrypt packet");
1169        return;
1170    }
1171
1172    EV_LOG_PACKET_IN(LSQUIC_LOG_CONN_ID, packet_in);
1173    conn->imc_bytes_in += packet_in->pi_data_sz + IQUIC_TAG_LEN;
1174
1175    if (pns == PNS_APP)
1176    {
1177        lsquic_packet_in_upref(packet_in);
1178        TAILQ_INSERT_TAIL(&conn->imc_app_packets, packet_in, pi_next);
1179        LSQ_DEBUG("delay processing of packet %"PRIu64" in pns %u",
1180            packet_in->pi_packno, pns);
1181        return;
1182    }
1183    else if (pns == PNS_HSK)
1184        conn->imc_flags |= IMC_ADDR_VALIDATED;
1185
1186    if (((conn->imc_flags >> IMCBIT_PNS_BIT_SHIFT) & 3) < pns)
1187    {
1188        conn->imc_flags &= ~(3 << IMCBIT_PNS_BIT_SHIFT);
1189        conn->imc_flags |= pns << IMCBIT_PNS_BIT_SHIFT;
1190    }
1191
1192    if (pns == PNS_HSK && !(conn->imc_flags & IMC_IGNORE_INIT))
1193        ignore_init(conn);
1194
1195    if (conn->imc_recvd_packnos[pns] & (1ULL << packet_in->pi_packno))
1196    {
1197        LSQ_DEBUG("duplicate packet %"PRIu64, packet_in->pi_packno);
1198        return;
1199    }
1200
1201    /* Update receive history before processing the packet: if there is an
1202     * error, the connection is terminated and recording this packet number
1203     * is helpful when it is printed along with other diagnostics in dtor.
1204     */
1205    if (0 == conn->imc_recvd_packnos[pns] ||
1206            packet_in->pi_packno > highest_bit_set(conn->imc_recvd_packnos[pns]))
1207        conn->imc_largest_recvd[pns] = packet_in->pi_received;
1208    conn->imc_recvd_packnos[pns] |= 1ULL << packet_in->pi_packno;
1209
1210    if (0 != imico_parse_regular_packet(conn, packet_in))
1211    {
1212        LSQ_DEBUG("connection is now in error state");
1213        conn->imc_flags |= IMC_ERROR;
1214        return;
1215    }
1216
1217    conn->imc_flags |= IMC_QUEUED_ACK_INIT << pns;
1218    ++conn->imc_ecn_counts_in[pns][ lsquic_packet_in_ecn(packet_in) ];
1219    conn->imc_incoming_ecn <<= 1;
1220    conn->imc_incoming_ecn |= lsquic_packet_in_ecn(packet_in) != ECN_NOT_ECT;
1221}
1222
1223
1224static void
1225ietf_mini_conn_ci_packet_sent (struct lsquic_conn *lconn,
1226                              struct lsquic_packet_out *packet_out)
1227{
1228    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1229    conn->imc_sent_packnos |= 1ULL << packet_out->po_packno;
1230    conn->imc_ecn_packnos |= !!lsquic_packet_out_ecn(packet_out)
1231                                                    << packet_out->po_packno;
1232#if 0
1233    if (packet_out->po_frame_types & (1 << QUIC_FRAME_ACK))
1234    {
1235        assert(mc->mc_flags & MC_UNSENT_ACK);
1236        mc->mc_flags &= ~MC_UNSENT_ACK;
1237    }
1238#endif
1239    ++conn->imc_ecn_counts_out[ lsquic_packet_out_pns(packet_out) ]
1240                              [ lsquic_packet_out_ecn(packet_out) ];
1241    if (packet_out->po_header_type == HETY_HANDSHAKE)
1242        conn->imc_flags |= IMC_HSK_PACKET_SENT;
1243    LSQ_DEBUG("%s: packet %"PRIu64" sent", __func__, packet_out->po_packno);
1244}
1245
1246
1247static void
1248ietf_mini_conn_ci_packet_not_sent (struct lsquic_conn *lconn,
1249                              struct lsquic_packet_out *packet_out)
1250{
1251    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1252    size_t packet_size;
1253
1254    packet_out->po_flags &= ~PO_SENT;
1255    packet_size = lsquic_packet_out_total_sz(lconn, packet_out);
1256    conn->imc_bytes_out -= packet_size + IQUIC_TAG_LEN;
1257    LSQ_DEBUG("%s: packet %"PRIu64" not sent", __func__, packet_out->po_packno);
1258}
1259
1260
1261static void
1262imico_return_enc_data (struct ietf_mini_conn *conn,
1263                                        struct lsquic_packet_out *packet_out)
1264{
1265    conn->imc_enpub->enp_pmi->pmi_return(conn->imc_enpub->enp_pmi_ctx,
1266        conn->imc_path.np_peer_ctx, packet_out->po_enc_data,
1267        lsquic_packet_out_ipv6(packet_out));
1268    packet_out->po_flags &= ~PO_ENCRYPTED;
1269    packet_out->po_enc_data = NULL;
1270}
1271
1272
1273static int
1274imico_repackage_packet (struct ietf_mini_conn *conn,
1275                                        struct lsquic_packet_out *packet_out)
1276{
1277    const lsquic_packno_t oldno = packet_out->po_packno;
1278    const lsquic_packno_t packno = conn->imc_next_packno++;
1279    if (packno > MAX_PACKETS)
1280        return -1;
1281
1282    LSQ_DEBUG("Packet %"PRIu64" repackaged for resending as packet %"PRIu64,
1283                                                        oldno, packno);
1284    EV_LOG_CONN_EVENT(LSQUIC_LOG_CONN_ID, "packet %"PRIu64" repackaged for "
1285        "resending as packet %"PRIu64, oldno, packno);
1286    packet_out->po_packno = packno;
1287    packet_out->po_flags &= ~PO_SENT;
1288    lsquic_packet_out_set_ecn(packet_out, imico_get_ecn(conn));
1289    if (packet_out->po_flags & PO_ENCRYPTED)
1290        imico_return_enc_data(conn, packet_out);
1291    TAILQ_INSERT_TAIL(&conn->imc_packets_out, packet_out, po_next);
1292    return 0;
1293}
1294
1295
1296static int
1297imico_handle_losses_and_have_unsent (struct ietf_mini_conn *conn,
1298                                                            lsquic_time_t now)
1299{
1300    TAILQ_HEAD(, lsquic_packet_out) lost_packets =
1301                                    TAILQ_HEAD_INITIALIZER(lost_packets);
1302    lsquic_packet_out_t *packet_out, *next;
1303    lsquic_time_t retx_to = 0;
1304    unsigned n_to_send = 0;
1305
1306    for (packet_out = TAILQ_FIRST(&conn->imc_packets_out); packet_out;
1307                                                        packet_out = next)
1308    {
1309        next = TAILQ_NEXT(packet_out, po_next);
1310        if (packet_out->po_flags & PO_SENT)
1311        {
1312            if (0 == retx_to)
1313                retx_to = imico_calc_retx_timeout(conn);
1314            if (packet_out->po_sent + retx_to < now)
1315            {
1316                LSQ_DEBUG("packet %"PRIu64" has been lost (rto: %"PRIu64")",
1317                                                packet_out->po_packno, retx_to);
1318                TAILQ_REMOVE(&conn->imc_packets_out, packet_out, po_next);
1319                TAILQ_INSERT_TAIL(&lost_packets, packet_out, po_next);
1320            }
1321        }
1322        else
1323            ++n_to_send;
1324    }
1325
1326    conn->imc_hsk_count += !TAILQ_EMPTY(&lost_packets);
1327
1328    while ((packet_out = TAILQ_FIRST(&lost_packets)))
1329    {
1330        TAILQ_REMOVE(&lost_packets, packet_out, po_next);
1331        if ((packet_out->po_frame_types & IQUIC_FRAME_RETX_MASK)
1332                            && 0 == imico_repackage_packet(conn, packet_out))
1333            ++n_to_send;
1334        else
1335            imico_destroy_packet(conn, packet_out);
1336    }
1337
1338    return n_to_send > 0;
1339}
1340
1341
1342static int
1343imico_have_packets_to_send (struct ietf_mini_conn *conn, lsquic_time_t now)
1344{
1345    return imico_handle_losses_and_have_unsent(conn, now);
1346}
1347
1348
1349struct ietf_mini_rechist
1350{
1351    const struct ietf_mini_conn *conn;
1352    packno_set_t                 cur_set;
1353    struct lsquic_packno_range   range;   /* We return a pointer to this */
1354    int                          cur_idx;
1355    enum packnum_space           pns;
1356};
1357
1358
1359static void
1360imico_rechist_init (struct ietf_mini_rechist *rechist,
1361                    const struct ietf_mini_conn *conn, enum packnum_space pns)
1362{
1363    rechist->conn    = conn;
1364    rechist->pns     = pns;
1365    rechist->cur_set = 0;
1366    rechist->cur_idx = 0;
1367}
1368
1369
1370static lsquic_time_t
1371imico_rechist_largest_recv (void *rechist_ctx)
1372{
1373    struct ietf_mini_rechist *rechist = rechist_ctx;
1374    return rechist->conn->imc_largest_recvd[ rechist->pns ];
1375}
1376
1377
1378static const struct lsquic_packno_range *
1379imico_rechist_next (void *rechist_ctx)
1380{
1381    struct ietf_mini_rechist *rechist = rechist_ctx;
1382    const struct ietf_mini_conn *conn = rechist->conn;
1383    packno_set_t packnos;
1384    int i;
1385
1386    packnos = rechist->cur_set;
1387    if (0 == packnos)
1388        return NULL;
1389
1390    /* There may be a faster way to do this, but for now, we just want
1391     * correctness.
1392     */
1393    for (i = rechist->cur_idx; i >= 0; --i)
1394        if (packnos & (1ULL << i))
1395        {
1396            rechist->range.low  = i;
1397            rechist->range.high = i;
1398            break;
1399        }
1400    assert(i >= 0); /* We must have hit at least one bit */
1401    --i;
1402    for ( ; i >= 0 && (packnos & (1ULL << i)); --i)
1403        rechist->range.low = i;
1404    if (i >= 0)
1405    {
1406        rechist->cur_set = packnos & ((1ULL << i) - 1);
1407        rechist->cur_idx = i;
1408    }
1409    else
1410        rechist->cur_set = 0;
1411    LSQ_DEBUG("%s: return [%"PRIu64", %"PRIu64"]", __func__,
1412                                rechist->range.low, rechist->range.high);
1413    return &rechist->range;
1414}
1415
1416
1417static const struct lsquic_packno_range *
1418imico_rechist_first (void *rechist_ctx)
1419{
1420    struct ietf_mini_rechist *rechist = rechist_ctx;
1421    rechist->cur_set = rechist->conn->imc_recvd_packnos[ rechist->pns ];
1422    rechist->cur_idx = highest_bit_set(rechist->cur_set);
1423    return imico_rechist_next(rechist_ctx);
1424}
1425
1426
1427static const enum header_type pns2hety[] =
1428{
1429    [PNS_INIT]  = HETY_INITIAL,
1430    [PNS_HSK]   = HETY_HANDSHAKE,
1431    [PNS_APP]   = HETY_NOT_SET,
1432};
1433
1434
1435static int
1436imico_generate_ack (struct ietf_mini_conn *conn, enum packnum_space pns,
1437                                                            lsquic_time_t now)
1438{
1439    struct lsquic_packet_out *packet_out;
1440    enum header_type header_type;
1441    struct ietf_mini_rechist rechist;
1442    int not_used_has_missing, len;
1443    uint64_t ecn_counts_buf[4];
1444    const uint64_t *ecn_counts;
1445
1446    header_type = pns2hety[pns];
1447
1448    if (conn->imc_incoming_ecn)
1449    {
1450        ecn_counts_buf[0]   = conn->imc_ecn_counts_in[pns][0];
1451        ecn_counts_buf[1]   = conn->imc_ecn_counts_in[pns][1];
1452        ecn_counts_buf[2]   = conn->imc_ecn_counts_in[pns][2];
1453        ecn_counts_buf[3]   = conn->imc_ecn_counts_in[pns][3];
1454        ecn_counts = ecn_counts_buf;
1455    }
1456    else
1457        ecn_counts = NULL;
1458
1459    packet_out = imico_get_packet_out(conn, header_type, 0);
1460    if (!packet_out)
1461        return -1;
1462
1463    /* Generate ACK frame */
1464    imico_rechist_init(&rechist, conn, pns);
1465    len = conn->imc_conn.cn_pf->pf_gen_ack_frame(
1466                packet_out->po_data + packet_out->po_data_sz,
1467                lsquic_packet_out_avail(packet_out), imico_rechist_first,
1468                imico_rechist_next, imico_rechist_largest_recv, &rechist,
1469                now, &not_used_has_missing, &packet_out->po_ack2ed, ecn_counts);
1470    if (len < 0)
1471    {
1472        LSQ_WARN("could not generate ACK frame");
1473        return -1;
1474    }
1475    EV_LOG_GENERATED_ACK_FRAME(LSQUIC_LOG_CONN_ID, conn->imc_conn.cn_pf,
1476                        packet_out->po_data + packet_out->po_data_sz, len);
1477    packet_out->po_frame_types |= 1 << QUIC_FRAME_ACK;
1478    packet_out->po_data_sz += len;
1479    packet_out->po_regen_sz += len;
1480    conn->imc_flags &= ~(IMC_QUEUED_ACK_INIT << pns);
1481    LSQ_DEBUG("wrote ACK frame of size %d", len);
1482    return 0;
1483}
1484
1485
1486static int
1487imico_generate_acks (struct ietf_mini_conn *conn, lsquic_time_t now)
1488{
1489    enum packnum_space pns;
1490
1491    for (pns = PNS_INIT; pns < N_PNS; ++pns)
1492        if (conn->imc_flags & (IMC_QUEUED_ACK_INIT << pns)
1493                && !(pns == PNS_INIT && (conn->imc_flags & IMC_IGNORE_INIT)))
1494            if (0 != imico_generate_ack(conn, pns, now))
1495                return -1;
1496
1497    return 0;
1498}
1499
1500
1501static void
1502imico_generate_conn_close (struct ietf_mini_conn *conn)
1503{
1504    struct lsquic_packet_out *packet_out;
1505    enum header_type header_type;
1506    enum packnum_space pns, pns_max;
1507    unsigned error_code;
1508    const char *reason;
1509    size_t need;
1510    int sz, rlen, is_app;
1511    char reason_buf[0x20];
1512
1513    if (conn->imc_flags & IMC_ABORT_ERROR)
1514    {
1515        is_app = !!(conn->imc_flags & IMC_ABORT_ISAPP);
1516        error_code = conn->imc_error_code;
1517        reason = NULL;
1518        rlen = 0;
1519    }
1520    else if (conn->imc_flags & IMC_TLS_ALERT)
1521    {
1522        is_app = 0;
1523        error_code = 0x100 + conn->imc_tls_alert;
1524        if (ALERT_NO_APPLICATION_PROTOCOL == conn->imc_tls_alert)
1525            reason = "no suitable application protocol";
1526        else
1527        {
1528            snprintf(reason_buf, sizeof(reason_buf), "TLS alert %"PRIu8,
1529                                                        conn->imc_tls_alert);
1530            reason = reason_buf;
1531        }
1532        rlen = strlen(reason);
1533    }
1534    else if (conn->imc_flags & IMC_BAD_TRANS_PARAMS)
1535    {
1536        is_app = 0;
1537        error_code = TEC_NO_ERROR;
1538        reason = "bad transport parameters";
1539        rlen = 24;
1540    }
1541    else if (conn->imc_flags & IMC_HSK_FAILED)
1542    {
1543        is_app = 0;
1544        error_code = TEC_NO_ERROR;
1545        reason = "handshake failed";
1546        rlen = 16;
1547    }
1548    else
1549    {
1550        is_app = 0;
1551        error_code = TEC_INTERNAL_ERROR;
1552        reason = NULL;
1553        rlen = 0;
1554    }
1555
1556
1557/* [draft-ietf-quic-transport-23] Section 12.2:
1558 *
1559 " A client will always know whether the server has Handshake keys (see
1560 " Section 17.2.2.1), but it is possible that a server does not know
1561 " whether the client has Handshake keys.  Under these circumstances, a
1562 " server SHOULD send a CONNECTION_CLOSE frame in both Handshake and
1563 " Initial packets to ensure that at least one of them is processable by
1564 " the client.
1565 */
1566
1567    pns = (conn->imc_flags >> IMCBIT_PNS_BIT_SHIFT) & 3;
1568    switch ((!!(conn->imc_flags & IMC_HSK_PACKET_SENT) << 1)
1569                | (pns == PNS_HSK) /* Handshake packet received */)
1570    {
1571    case (0 << 1) | 0:
1572        pns = PNS_INIT;
1573        pns_max = PNS_INIT;
1574        break;
1575    case (1 << 1) | 0:
1576        pns = PNS_INIT;
1577        pns_max = PNS_HSK;
1578        break;
1579    default:
1580        pns = PNS_HSK;
1581        pns_max = PNS_HSK;
1582        break;
1583    }
1584
1585    LSQ_DEBUG("will generate %u CONNECTION_CLOSE frame%.*s",
1586        pns_max - pns + 1, pns_max > pns, "s");
1587    do
1588    {
1589        header_type = pns2hety[pns];
1590        need = 30;  /* Guess */ /* TODO: calculate, don't guess */
1591        packet_out = imico_get_packet_out(conn, header_type, need);
1592        if (!packet_out)
1593            return;
1594        sz = conn->imc_conn.cn_pf->pf_gen_connect_close_frame(
1595                 packet_out->po_data + packet_out->po_data_sz,
1596                 lsquic_packet_out_avail(packet_out), is_app, error_code, reason,
1597                 rlen);
1598        if (sz >= 0)
1599        {
1600            packet_out->po_frame_types |= 1 << QUIC_FRAME_CONNECTION_CLOSE;
1601            packet_out->po_data_sz += sz;
1602            LSQ_DEBUG("generated CONNECTION_CLOSE frame");
1603        }
1604        else
1605            LSQ_WARN("could not generate CONNECTION_CLOSE frame");
1606        ++pns;
1607    }
1608    while (pns <= pns_max);
1609}
1610
1611
1612static enum tick_st
1613ietf_mini_conn_ci_tick (struct lsquic_conn *lconn, lsquic_time_t now)
1614{
1615    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1616    enum tick_st tick;
1617
1618    if (conn->imc_created + conn->imc_enpub->enp_settings.es_handshake_to < now)
1619    {
1620        LSQ_DEBUG("connection expired: closing");
1621        return TICK_CLOSE;
1622    }
1623
1624
1625    if (conn->imc_flags &
1626            (IMC_QUEUED_ACK_INIT|IMC_QUEUED_ACK_HSK|IMC_QUEUED_ACK_APP))
1627    {
1628        if (0 != imico_generate_acks(conn, now))
1629        {
1630            conn->imc_flags |= IMC_ERROR;
1631            return TICK_CLOSE;
1632        }
1633    }
1634
1635
1636    tick = 0;
1637
1638    if (conn->imc_flags & IMC_ERROR)
1639    {
1640        if (!(conn->imc_flags & IMC_CLOSE_RECVD))
1641            imico_generate_conn_close(conn);
1642        tick |= TICK_CLOSE;
1643    }
1644    else if (conn->imc_flags & IMC_HSK_OK)
1645        tick |= TICK_PROMOTE;
1646
1647    if (imico_have_packets_to_send(conn, now))
1648        tick |= TICK_SEND;
1649    else
1650        tick |= TICK_QUIET;
1651
1652    LSQ_DEBUG("Return TICK %d", tick);
1653    return tick;
1654}
1655
1656
1657static void
1658ietf_mini_conn_ci_internal_error (struct lsquic_conn *lconn,
1659                                                    const char *format, ...)
1660{
1661    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1662    LSQ_INFO("internal error reported");
1663    conn->imc_flags |= IMC_ERROR;
1664}
1665
1666
1667static void
1668ietf_mini_conn_ci_abort_error (struct lsquic_conn *lconn, int is_app,
1669                                unsigned error_code, const char *fmt, ...)
1670{
1671    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1672    va_list ap;
1673    const char *err_str, *percent;
1674    char err_buf[0x100];
1675
1676    percent = strchr(fmt, '%');
1677    if (percent)
1678    {
1679        va_start(ap, fmt);
1680        vsnprintf(err_buf, sizeof(err_buf), fmt, ap);
1681        va_end(ap);
1682        err_str = err_buf;
1683    }
1684    else
1685        err_str = fmt;
1686    LSQ_INFO("abort error: is_app: %d; error code: %u; error str: %s",
1687        is_app, error_code, err_str);
1688    conn->imc_flags |= IMC_ERROR|IMC_ABORT_ERROR;
1689    if (is_app)
1690        conn->imc_flags |= IMC_ABORT_ISAPP;
1691    conn->imc_error_code = error_code;
1692}
1693
1694
1695static struct network_path *
1696ietf_mini_conn_ci_get_path (struct lsquic_conn *lconn,
1697                                                    const struct sockaddr *sa)
1698{
1699    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1700
1701    return &conn->imc_path;
1702}
1703
1704
1705static const lsquic_cid_t *
1706ietf_mini_conn_ci_get_log_cid (const struct lsquic_conn *lconn)
1707{
1708    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1709
1710    if (conn->imc_path.np_dcid.len)
1711        return &conn->imc_path.np_dcid;
1712    else
1713        return CN_SCID(lconn);
1714}
1715
1716
1717static unsigned char
1718ietf_mini_conn_ci_record_addrs (struct lsquic_conn *lconn, void *peer_ctx,
1719            const struct sockaddr *local_sa, const struct sockaddr *peer_sa)
1720{
1721    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1722    struct lsquic_packet_out *packet_out;
1723    size_t len;
1724
1725    if (NP_IS_IPv6(&conn->imc_path) != (AF_INET6 == peer_sa->sa_family))
1726        TAILQ_FOREACH(packet_out, &conn->imc_packets_out, po_next)
1727            if ((packet_out->po_flags & (PO_SENT|PO_ENCRYPTED)) == PO_ENCRYPTED)
1728                imico_return_enc_data(conn, packet_out);
1729
1730    len = local_sa->sa_family == AF_INET ? sizeof(struct sockaddr_in)
1731                                                : sizeof(struct sockaddr_in6);
1732
1733    memcpy(conn->imc_path.np_peer_addr, peer_sa, len);
1734    memcpy(conn->imc_path.np_local_addr, local_sa, len);
1735    conn->imc_path.np_peer_ctx = peer_ctx;
1736    return 0;
1737}
1738
1739
1740static const struct conn_iface mini_conn_ietf_iface = {
1741    .ci_abort_error          =  ietf_mini_conn_ci_abort_error,
1742    .ci_client_call_on_new   =  ietf_mini_conn_ci_client_call_on_new,
1743    .ci_destroy              =  ietf_mini_conn_ci_destroy,
1744    .ci_get_engine           =  ietf_mini_conn_ci_get_engine,
1745    .ci_get_log_cid          =  ietf_mini_conn_ci_get_log_cid,
1746    .ci_get_path             =  ietf_mini_conn_ci_get_path,
1747    .ci_hsk_done             =  ietf_mini_conn_ci_hsk_done,
1748    .ci_internal_error       =  ietf_mini_conn_ci_internal_error,
1749    .ci_is_tickable          =  ietf_mini_conn_ci_is_tickable,
1750    .ci_next_packet_to_send  =  ietf_mini_conn_ci_next_packet_to_send,
1751    .ci_next_tick_time       =  ietf_mini_conn_ci_next_tick_time,
1752    .ci_packet_in            =  ietf_mini_conn_ci_packet_in,
1753    .ci_packet_not_sent      =  ietf_mini_conn_ci_packet_not_sent,
1754    .ci_packet_sent          =  ietf_mini_conn_ci_packet_sent,
1755    .ci_record_addrs         =  ietf_mini_conn_ci_record_addrs,
1756    .ci_tick                 =  ietf_mini_conn_ci_tick,
1757    .ci_tls_alert            =  ietf_mini_conn_ci_tls_alert,
1758};
1759