lsquic_mini_conn_ietf.c revision 7d09751d
1/* Copyright (c) 2017 - 2020 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                                                    size_t udp_payload_size)
396{
397    if (udp_payload_size < IQUIC_MIN_INIT_PACKET_SZ)
398    {
399        /* [draft-ietf-quic-transport-24] Section 14 */
400        LSQ_LOG1(LSQ_LOG_DEBUG, "incoming UDP payload too small: %zu bytes",
401                                                            udp_payload_size);
402        return 0;
403    }
404    /* TODO: Move decryption of the first packet into this function? */
405    return 1;   /* TODO */
406}
407
408
409struct lsquic_conn *
410lsquic_mini_conn_ietf_new (struct lsquic_engine_public *enpub,
411               const struct lsquic_packet_in *packet_in,
412           enum lsquic_version version, int is_ipv4, const lsquic_cid_t *odcid,
413           size_t udp_payload_size)
414{
415    struct ietf_mini_conn *conn;
416    enc_session_t *enc_sess;
417    enum enc_level i;
418    const struct enc_session_funcs_iquic *esfi;
419
420    if (!is_first_packet_ok(packet_in, udp_payload_size))
421        return NULL;
422
423    conn = lsquic_malo_get(enpub->enp_mm.malo.mini_conn_ietf);
424    if (!conn)
425    {
426        LSQ_LOG1(LSQ_LOG_WARN, "cannot allocate mini connection: %s",
427                                                            strerror(errno));
428        return NULL;
429    }
430    memset(conn, 0, sizeof(*conn));
431    conn->imc_conn.cn_if = &mini_conn_ietf_iface;
432    conn->imc_conn.cn_cces = conn->imc_cces;
433    conn->imc_conn.cn_n_cces = sizeof(conn->imc_cces)
434                                                / sizeof(conn->imc_cces[0]);
435    conn->imc_cces[0].cce_cid = packet_in->pi_dcid;
436    conn->imc_cces[0].cce_flags = CCE_USED;
437    conn->imc_conn.cn_cces_mask = 1;
438    lsquic_scid_from_packet_in(packet_in, &conn->imc_path.np_dcid);
439    LSQ_DEBUGC("recv SCID from client %"CID_FMT, CID_BITS(&conn->imc_cces[0].cce_cid));
440    LSQ_DEBUGC("recv DCID from client %"CID_FMT, CID_BITS(&conn->imc_path.np_dcid));
441
442    /* Generate new SCID. Since is not the original SCID, it is given
443     * a sequence number (0) and therefore can be retired by the client.
444     */
445    lsquic_generate_cid(&conn->imc_conn.cn_cces[1].cce_cid,
446                                        enpub->enp_settings.es_scid_len);
447    LSQ_DEBUGC("generated SCID %"CID_FMT" at index %u, switching to it",
448                CID_BITS(&conn->imc_conn.cn_cces[1].cce_cid), 1);
449    conn->imc_conn.cn_cces[1].cce_flags = CCE_SEQNO | CCE_USED;
450    conn->imc_conn.cn_cces_mask |= 1u << 1;
451    conn->imc_conn.cn_cur_cce_idx = 1;
452
453    conn->imc_conn.cn_flags = LSCONN_MINI|LSCONN_IETF|LSCONN_SERVER;
454
455    for (i = 0; i < N_ENC_LEVS; ++i)
456    {
457        conn->imc_streams[i].mcs_enc_level = i;
458        conn->imc_stream_ps[i] = &conn->imc_streams[i];
459    }
460
461    esfi = select_esf_iquic_by_ver(version);
462    enc_sess = esfi->esfi_create_server(enpub, &conn->imc_conn,
463                &packet_in->pi_dcid, conn->imc_stream_ps, &crypto_stream_if,
464                odcid);
465    if (!enc_sess)
466    {
467        lsquic_malo_put(conn);
468        return NULL;
469    }
470
471    conn->imc_enpub = enpub;
472    conn->imc_created = packet_in->pi_received;
473    conn->imc_path.np_pack_size = is_ipv4 ? IQUIC_MAX_IPv4_PACKET_SZ
474                                                    : IQUIC_MAX_IPv6_PACKET_SZ;
475#ifndef NDEBUG
476    if (getenv("LSQUIC_CN_PACK_SIZE"))
477        conn->imc_path.np_pack_size = atoi(getenv("LSQUIC_CN_PACK_SIZE"));
478#endif
479    conn->imc_conn.cn_version = version;
480    conn->imc_conn.cn_pf = select_pf_by_ver(version);
481    conn->imc_conn.cn_esf.i = esfi;
482    conn->imc_conn.cn_enc_session = enc_sess;
483    conn->imc_conn.cn_esf_c = select_esf_common_by_ver(version);
484    TAILQ_INIT(&conn->imc_packets_out);
485    TAILQ_INIT(&conn->imc_app_packets);
486    TAILQ_INIT(&conn->imc_crypto_frames);
487    if (odcid)
488        conn->imc_flags |= IMC_ADDR_VALIDATED;
489
490    LSQ_DEBUG("created mini connection object %p; max packet size=%hu",
491                                                conn, conn->imc_path.np_pack_size);
492    return &conn->imc_conn;
493}
494
495
496static void
497ietf_mini_conn_ci_client_call_on_new (struct lsquic_conn *lconn)
498{
499    assert(0);
500}
501
502
503static void
504ietf_mini_conn_ci_destroy (struct lsquic_conn *lconn)
505{
506    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
507    struct lsquic_packet_out *packet_out;
508    struct lsquic_packet_in *packet_in;
509    struct stream_frame *frame;
510
511    while ((packet_out = TAILQ_FIRST(&conn->imc_packets_out)))
512    {
513        TAILQ_REMOVE(&conn->imc_packets_out, packet_out, po_next);
514        imico_destroy_packet(conn, packet_out);
515    }
516    while ((packet_in = TAILQ_FIRST(&conn->imc_app_packets)))
517    {
518        TAILQ_REMOVE(&conn->imc_app_packets, packet_in, pi_next);
519        lsquic_packet_in_put(&conn->imc_enpub->enp_mm, packet_in);
520    }
521    while ((frame = TAILQ_FIRST(&conn->imc_crypto_frames)))
522    {
523        TAILQ_REMOVE(&conn->imc_crypto_frames, frame, next_frame);
524        lsquic_packet_in_put(&conn->imc_enpub->enp_mm, frame->packet_in);
525        lsquic_malo_put(frame);
526    }
527    if (lconn->cn_enc_session)
528        lconn->cn_esf.i->esfi_destroy(lconn->cn_enc_session);
529    LSQ_DEBUG("ietf_mini_conn_ci_destroyed");
530    lsquic_malo_put(conn);
531}
532
533
534static struct lsquic_engine *
535ietf_mini_conn_ci_get_engine (struct lsquic_conn *lconn)
536{
537    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
538    return conn->imc_enpub->enp_engine;
539}
540
541
542static void
543ietf_mini_conn_ci_hsk_done (struct lsquic_conn *lconn,
544                                                enum lsquic_hsk_status status)
545{
546    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
547
548    switch (status)
549    {
550    case LSQ_HSK_OK:
551    case LSQ_HSK_0RTT_OK:
552        conn->imc_flags |= IMC_HSK_OK;
553        conn->imc_conn.cn_flags |= LSCONN_HANDSHAKE_DONE;
554        LSQ_DEBUG("handshake OK");
555        break;
556    default:
557        assert(0);
558        /* fall-through */
559    case LSQ_HSK_FAIL:
560        conn->imc_flags |= IMC_HSK_FAILED|IMC_ERROR;
561        LSQ_INFO("handshake failed");
562        break;
563    }
564}
565
566
567static void
568ietf_mini_conn_ci_tls_alert (struct lsquic_conn *lconn, uint8_t alert)
569{
570    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
571    LSQ_DEBUG("got TLS alert %"PRIu8, alert);
572    conn->imc_flags |= IMC_ERROR|IMC_TLS_ALERT;
573    conn->imc_tls_alert = alert;
574}
575
576
577static int
578ietf_mini_conn_ci_is_tickable (struct lsquic_conn *lconn)
579{
580    /* A mini connection is never tickable:  Either there are incoming
581     * packets, in which case, the connection is going to be ticked, or
582     * there is an alarm pending, in which case it will be handled via
583     * the attq.
584     */
585    return 0;
586}
587
588
589static int
590imico_can_send (const struct ietf_mini_conn *conn, size_t size)
591{
592    return (conn->imc_flags & IMC_ADDR_VALIDATED)
593        || conn->imc_bytes_in * 3 >= conn->imc_bytes_out + size
594        ;
595}
596
597
598static struct lsquic_packet_out *
599ietf_mini_conn_ci_next_packet_to_send (struct lsquic_conn *lconn, size_t size)
600{
601    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
602    struct lsquic_packet_out *packet_out;
603    size_t packet_size;
604
605    TAILQ_FOREACH(packet_out, &conn->imc_packets_out, po_next)
606    {
607        if (packet_out->po_flags & PO_SENT)
608            continue;
609        packet_size = lsquic_packet_out_total_sz(lconn, packet_out);
610        if (size == 0 || packet_size + size <= conn->imc_path.np_pack_size)
611        {
612            if (!imico_can_send(conn, packet_size + IQUIC_TAG_LEN))
613            {
614                LSQ_DEBUG("cannot send packet %"PRIu64" of size %zu: client "
615                    "address has not been validated", packet_out->po_packno,
616                    packet_size + IQUIC_TAG_LEN);
617                return NULL;
618            }
619            packet_out->po_flags |= PO_SENT;
620            conn->imc_bytes_out += packet_size + IQUIC_TAG_LEN;
621            if (size == 0)
622                LSQ_DEBUG("packet_to_send: %"PRIu64, packet_out->po_packno);
623            else
624                LSQ_DEBUG("packet_to_send: %"PRIu64" (coalesced)",
625                                                    packet_out->po_packno);
626            return packet_out;
627        }
628        else
629            return NULL;
630    }
631
632    return NULL;
633}
634
635
636static int
637imico_calc_retx_timeout (const struct ietf_mini_conn *conn)
638{
639    lsquic_time_t to;
640    to = lsquic_rtt_stats_get_srtt(&conn->imc_rtt_stats);
641    if (to)
642    {
643        to += to / 2;
644        if (to < 10000)
645            to = 10000;
646    }
647    else
648        to = 300000;
649    return to << conn->imc_hsk_count;
650}
651
652
653static lsquic_time_t
654ietf_mini_conn_ci_next_tick_time (struct lsquic_conn *lconn, unsigned *why)
655{
656    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
657    const struct lsquic_packet_out *packet_out;
658    lsquic_time_t exp_time, retx_time;
659
660    exp_time = conn->imc_created +
661                        conn->imc_enpub->enp_settings.es_handshake_to;
662
663    TAILQ_FOREACH(packet_out, &conn->imc_packets_out, po_next)
664        if (packet_out->po_flags & PO_SENT)
665        {
666            retx_time = packet_out->po_sent + imico_calc_retx_timeout(conn);
667            if (retx_time < exp_time)
668            {
669                *why = N_AEWS + AL_RETX_HSK;
670                return retx_time;
671            }
672            else
673            {
674                *why = AEW_MINI_EXPIRE;
675                return exp_time;
676            }
677        }
678
679    *why = AEW_MINI_EXPIRE;
680    return exp_time;
681}
682
683
684#define IMICO_PROC_FRAME_ARGS                                           \
685    struct ietf_mini_conn *conn, struct lsquic_packet_in *packet_in,    \
686    const unsigned char *p, size_t len
687
688
689static void
690imico_dispatch_stream_events (struct ietf_mini_conn *conn)
691{
692    enum enc_level i;
693
694    for (i = 0; i < N_ENC_LEVS; ++i)
695        if ((conn->imc_streams[i].mcs_flags & (MCS_CREATED|MCS_WANTREAD))
696                                                == (MCS_CREATED|MCS_WANTREAD))
697        {
698            LSQ_DEBUG("dispatch read events on level #%u", i);
699            lsquic_mini_cry_sm_if.on_read((void *) &conn->imc_streams[i],
700                                            conn->imc_conn.cn_enc_session);
701        }
702
703    for (i = 0; i < N_ENC_LEVS; ++i)
704        if ((conn->imc_streams[i].mcs_flags & (MCS_CREATED|MCS_WANTWRITE))
705                                                == (MCS_CREATED|MCS_WANTWRITE))
706        {
707            LSQ_DEBUG("dispatch write events on level #%u", i);
708            lsquic_mini_cry_sm_if.on_write((void *) &conn->imc_streams[i],
709                                            conn->imc_conn.cn_enc_session);
710        }
711}
712
713
714static int
715imico_stash_stream_frame (struct ietf_mini_conn *conn,
716        enum enc_level enc_level, struct lsquic_packet_in *packet_in,
717        const struct stream_frame *frame)
718{
719    struct stream_frame *copy;
720
721    if (conn->imc_n_crypto_frames >= IMICO_MAX_STASHED_FRAMES)
722    {
723        LSQ_INFO("cannot stash more CRYPTO frames, at %hhu already, while max "
724            "is %u", conn->imc_n_crypto_frames, IMICO_MAX_STASHED_FRAMES);
725        return -1;
726    }
727
728    if (conn->imc_crypto_frames_sz + DF_SIZE(frame) > IMICO_MAX_BUFFERED_CRYPTO)
729    {
730        LSQ_INFO("cannot stash more than %u bytes of CRYPTO frames",
731            IMICO_MAX_BUFFERED_CRYPTO);
732        return -1;
733    }
734
735    copy = lsquic_malo_get(conn->imc_enpub->enp_mm.malo.stream_frame);
736    if (!copy)
737    {
738        LSQ_INFO("could not allocate stream frame for stashing");
739        return -1;
740    }
741
742    *copy = *frame;
743    copy->packet_in = lsquic_packet_in_get(packet_in);
744    copy->stream_id = enc_level;
745    TAILQ_INSERT_TAIL(&conn->imc_crypto_frames, copy, next_frame);
746    ++conn->imc_n_crypto_frames;
747    conn->imc_crypto_frames_sz += DF_SIZE(frame);
748    return 0;
749}
750
751
752static unsigned
753imico_process_crypto_frame (IMICO_PROC_FRAME_ARGS)
754{
755    int parsed_len;
756    enum enc_level enc_level, i;
757    struct stream_frame stream_frame;
758    const struct transport_params *params;
759
760    parsed_len = conn->imc_conn.cn_pf->pf_parse_crypto_frame(p, len,
761                                                                &stream_frame);
762    if (parsed_len < 0)
763        return 0;
764
765    enc_level = lsquic_packet_in_enc_level(packet_in);
766    EV_LOG_CRYPTO_FRAME_IN(LSQUIC_LOG_CONN_ID, &stream_frame, enc_level);
767
768    if (conn->imc_streams[enc_level].mcs_read_off >= DF_OFF(&stream_frame)
769        && conn->imc_streams[enc_level].mcs_read_off < DF_END(&stream_frame))
770        LSQ_DEBUG("Got CRYPTO frame for enc level #%u", enc_level);
771    else if (conn->imc_streams[enc_level].mcs_read_off < DF_OFF(&stream_frame))
772    {
773        LSQ_DEBUG("Can't read CRYPTO frame on enc level #%u at offset %"PRIu64
774            " yet -- stash", enc_level, DF_OFF(&stream_frame));
775        if (0 == imico_stash_stream_frame(conn, enc_level, packet_in,
776                                                                &stream_frame))
777            return parsed_len;
778        else
779            return 0;
780    }
781    else
782    {
783        LSQ_DEBUG("Got duplicate CRYPTO frame for enc level #%u -- ignore",
784                                                                    enc_level);
785        return parsed_len;
786    }
787
788    if (!(conn->imc_flags & IMC_ENC_SESS_INITED))
789    {
790        if (0 != conn->imc_conn.cn_esf.i->esfi_init_server(
791                                            conn->imc_conn.cn_enc_session))
792            return -1;
793        conn->imc_flags |= IMC_ENC_SESS_INITED;
794    }
795
796    if (!(conn->imc_streams[enc_level].mcs_flags & MCS_CREATED))
797    {
798        LSQ_DEBUG("creating stream on level #%u", enc_level);
799        conn->imc_streams[enc_level].mcs_flags |= MCS_CREATED;
800        lsquic_mini_cry_sm_if.on_new_stream(conn->imc_conn.cn_enc_session,
801                                    (void *) &conn->imc_streams[enc_level]);
802    }
803
804    /* Assume that receiving a CRYPTO frame at a higher level means that we
805     * no longer want to read from a lower level.
806     */
807    for (i = 0; i < enc_level; ++i)
808        conn->imc_streams[i].mcs_flags &= ~MCS_WANTREAD;
809
810    conn->imc_last_in.frame = &stream_frame;
811    conn->imc_last_in.enc_level = enc_level;
812    imico_dispatch_stream_events(conn);
813    conn->imc_last_in.frame = NULL;
814
815    if (DF_ROFF(&stream_frame) < DF_END(&stream_frame))
816    {
817        /* This is an odd condition, but let's handle it just in case */
818        LSQ_DEBUG("New CRYPTO frame on enc level #%u not fully read -- stash",
819            enc_level);
820        if (0 != imico_stash_stream_frame(conn, enc_level, packet_in,
821                                                                &stream_frame))
822            return 0;
823    }
824
825
826    if (enc_level == ENC_LEV_CLEAR
827        && imico_chlo_has_been_consumed(conn)
828        && (conn->imc_flags & (IMC_ENC_SESS_INITED|IMC_HAVE_TP))
829                                                    == IMC_ENC_SESS_INITED)
830    {
831        params = conn->imc_conn.cn_esf.i->esfi_get_peer_transport_params(
832                                                conn->imc_conn.cn_enc_session);
833        if (params)
834        {
835            conn->imc_flags |= IMC_HAVE_TP;
836            conn->imc_ack_exp = params->tp_ack_delay_exponent;
837        }
838        else
839        {
840            conn->imc_flags |= IMC_BAD_TRANS_PARAMS;
841            return 0;
842        }
843    }
844
845    return parsed_len;
846}
847
848
849static ptrdiff_t
850imico_count_zero_bytes (const unsigned char *p, size_t len)
851{
852    const unsigned char *const end = p + len;
853    while (p < end && 0 == *p)
854        ++p;
855    return len - (end - p);
856}
857
858
859static unsigned
860imico_process_padding_frame (IMICO_PROC_FRAME_ARGS)
861{
862    len = (size_t) imico_count_zero_bytes(p, len);
863    EV_LOG_PADDING_FRAME_IN(LSQUIC_LOG_CONN_ID, len);
864    return len;
865}
866
867
868static void
869imico_take_rtt_sample (struct ietf_mini_conn *conn,
870                            const struct lsquic_packet_out *packet_out,
871                            lsquic_time_t now, lsquic_time_t lack_delta)
872{
873    assert(packet_out->po_sent);
874    lsquic_time_t measured_rtt = now - packet_out->po_sent;
875    if (lack_delta < measured_rtt)
876    {
877        lsquic_rtt_stats_update(&conn->imc_rtt_stats, measured_rtt, lack_delta);
878        LSQ_DEBUG("srtt: %"PRIu64" usec, var: %"PRIu64,
879                        lsquic_rtt_stats_get_srtt(&conn->imc_rtt_stats),
880                        lsquic_rtt_stats_get_rttvar(&conn->imc_rtt_stats));
881    }
882}
883
884
885static unsigned
886imico_process_ack_frame (IMICO_PROC_FRAME_ARGS)
887{
888    int parsed_len;
889    unsigned n;
890    lsquic_packet_out_t *packet_out, *next;
891    struct ack_info *acki;
892    lsquic_packno_t packno;
893    lsquic_time_t warn_time;
894    packno_set_t acked;
895    enum packnum_space pns;
896    uint8_t ack_exp;
897
898    if (conn->imc_flags & IMC_HAVE_TP)
899        ack_exp = conn->imc_ack_exp;
900    else
901        ack_exp = TP_DEF_ACK_DELAY_EXP; /* Odd: no transport params yet? */
902    acki = conn->imc_enpub->enp_mm.acki;
903    parsed_len = conn->imc_conn.cn_pf->pf_parse_ack_frame(p, len, acki,
904                                                                    ack_exp);
905    if (parsed_len < 0)
906        return 0;
907
908    pns = lsquic_hety2pns[ packet_in->pi_header_type ];
909    acked = 0;
910
911    for (n = 0; n < acki->n_ranges; ++n)
912    {
913        if (acki->ranges[n].high <= MAX_PACKETS)
914        {
915            acked |= (1ULL << acki->ranges[n].high)
916                                        | ((1ULL << acki->ranges[n].high) - 1);
917            acked &= ~((1ULL << acki->ranges[n].low) - 1);
918        }
919        else
920        {
921            packno = acki->ranges[n].high;
922            goto err_never_sent;
923        }
924    }
925    if (acked & ~conn->imc_sent_packnos)
926    {
927        packno = highest_bit_set(acked & ~conn->imc_sent_packnos);
928        goto err_never_sent;
929    }
930
931    EV_LOG_ACK_FRAME_IN(LSQUIC_LOG_CONN_ID, acki);
932    for (packet_out = TAILQ_FIRST(&conn->imc_packets_out); packet_out;
933                                                            packet_out = next)
934    {
935        next = TAILQ_NEXT(packet_out, po_next);
936        if ((1ULL << packet_out->po_packno) & acked)
937        {
938            assert(lsquic_packet_out_pns(packet_out) == pns);
939            LSQ_DEBUG("Got ACK for packet %"PRIu64, packet_out->po_packno);
940            if (packet_out->po_packno == largest_acked(acki))
941                imico_take_rtt_sample(conn, packet_out,
942                                    packet_in->pi_received, acki->lack_delta);
943            TAILQ_REMOVE(&conn->imc_packets_out, packet_out, po_next);
944            imico_destroy_packet(conn, packet_out);
945        }
946    }
947
948    if (conn->imc_sent_packnos & ~conn->imc_acked_packnos[pns] & acked)
949    {
950        LSQ_DEBUG("Newly acked packets, reset handshake count");
951        conn->imc_hsk_count = 0;
952    }
953
954    conn->imc_acked_packnos[pns] |= acked;
955
956    return parsed_len;
957
958  err_never_sent:
959    warn_time = lsquic_time_now();
960    if (0 == conn->imc_enpub->enp_last_warning[WT_ACKPARSE_MINI]
961        || conn->imc_enpub->enp_last_warning[WT_ACKPARSE_MINI]
962                + WARNING_INTERVAL < warn_time)
963    {
964        conn->imc_enpub->enp_last_warning[WT_ACKPARSE_MINI] = warn_time;
965        LSQ_WARN("packet %"PRIu64" (pns: %u) was never sent", packno, pns);
966    }
967    else
968        LSQ_DEBUG("packet %"PRIu64" (pns: %u) was never sent", packno, pns);
969    return 0;
970}
971
972
973static unsigned
974imico_process_ping_frame (IMICO_PROC_FRAME_ARGS)
975{
976    LSQ_DEBUG("got a PING frame, do nothing");
977    return 1;
978}
979
980
981static unsigned
982imico_process_connection_close_frame (IMICO_PROC_FRAME_ARGS)
983{
984    struct lsquic_packet_out *packet_out;
985    uint64_t error_code;
986    uint16_t reason_len;
987    uint8_t reason_off;
988    int parsed_len, app_error;
989
990    while ((packet_out = TAILQ_FIRST(&conn->imc_packets_out)))
991    {
992        TAILQ_REMOVE(&conn->imc_packets_out, packet_out, po_next);
993        imico_destroy_packet(conn, packet_out);
994    }
995    conn->imc_flags |= IMC_CLOSE_RECVD;
996    parsed_len = conn->imc_conn.cn_pf->pf_parse_connect_close_frame(p, len,
997                            &app_error, &error_code, &reason_len, &reason_off);
998    if (parsed_len < 0)
999        return 0;
1000    EV_LOG_CONNECTION_CLOSE_FRAME_IN(LSQUIC_LOG_CONN_ID, error_code,
1001                            (int) reason_len, (const char *) p + reason_off);
1002    LSQ_INFO("Received CONNECTION_CLOSE frame (%s-level code: %"PRIu64"; "
1003            "reason: %.*s)", app_error ? "application" : "transport",
1004                error_code, (int) reason_len, (const char *) p + reason_off);
1005    return 0;   /* This shuts down the connection */
1006}
1007
1008
1009static unsigned
1010imico_process_invalid_frame (IMICO_PROC_FRAME_ARGS)
1011{
1012    LSQ_DEBUG("invalid frame %u (%s)", p[0],
1013        frame_type_2_str[ conn->imc_conn.cn_pf->pf_parse_frame_type(p[0]) ]);
1014    return 0;
1015}
1016
1017
1018static unsigned (*const imico_process_frames[N_QUIC_FRAMES])
1019                                                (IMICO_PROC_FRAME_ARGS) =
1020{
1021    [QUIC_FRAME_PADDING]            =  imico_process_padding_frame,
1022    [QUIC_FRAME_CRYPTO]             =  imico_process_crypto_frame,
1023    [QUIC_FRAME_ACK]                =  imico_process_ack_frame,
1024    [QUIC_FRAME_PING]               =  imico_process_ping_frame,
1025    [QUIC_FRAME_CONNECTION_CLOSE]   =  imico_process_connection_close_frame,
1026    /* Some of them are invalid, while others are unexpected.  We treat
1027     * them the same: handshake cannot proceed.
1028     */
1029    [QUIC_FRAME_RST_STREAM]         =  imico_process_invalid_frame,
1030    [QUIC_FRAME_MAX_DATA]           =  imico_process_invalid_frame,
1031    [QUIC_FRAME_MAX_STREAM_DATA]    =  imico_process_invalid_frame,
1032    [QUIC_FRAME_MAX_STREAMS]        =  imico_process_invalid_frame,
1033    [QUIC_FRAME_BLOCKED]            =  imico_process_invalid_frame,
1034    [QUIC_FRAME_STREAM_BLOCKED]     =  imico_process_invalid_frame,
1035    [QUIC_FRAME_STREAMS_BLOCKED]    =  imico_process_invalid_frame,
1036    [QUIC_FRAME_NEW_CONNECTION_ID]  =  imico_process_invalid_frame,
1037    [QUIC_FRAME_STOP_SENDING]       =  imico_process_invalid_frame,
1038    [QUIC_FRAME_PATH_CHALLENGE]     =  imico_process_invalid_frame,
1039    [QUIC_FRAME_PATH_RESPONSE]      =  imico_process_invalid_frame,
1040    /* STREAM frame can only come in the App PNS and we delay those packets: */
1041    [QUIC_FRAME_STREAM]             =  imico_process_invalid_frame,
1042};
1043
1044
1045static unsigned
1046imico_process_packet_frame (struct ietf_mini_conn *conn,
1047        struct lsquic_packet_in *packet_in, const unsigned char *p, size_t len)
1048{
1049    enum enc_level enc_level = lsquic_packet_in_enc_level(packet_in);
1050    enum quic_frame_type type = conn->imc_conn.cn_pf->pf_parse_frame_type(p[0]);
1051    if (lsquic_legal_frames_by_level[enc_level] & (1 << type))
1052    {
1053        packet_in->pi_frame_types |= 1 << type;
1054        return imico_process_frames[type](conn, packet_in, p, len);
1055    }
1056    else
1057    {
1058        LSQ_DEBUG("invalid frame %u at encryption level %s", type,
1059                                                lsquic_enclev2str[enc_level]);
1060        return 0;
1061    }
1062}
1063
1064
1065static int
1066imico_parse_regular_packet (struct ietf_mini_conn *conn,
1067                                        struct lsquic_packet_in *packet_in)
1068{
1069    const unsigned char *p, *pend;
1070    unsigned len;
1071
1072    p = packet_in->pi_data + packet_in->pi_header_sz;
1073    pend = packet_in->pi_data + packet_in->pi_data_sz;
1074
1075    while (p < pend)
1076    {
1077        len = imico_process_packet_frame(conn, packet_in, p, pend - p);
1078        if (len > 0)
1079            p += len;
1080        else
1081            return -1;
1082    }
1083
1084    return 0;
1085}
1086
1087
1088static unsigned
1089highest_bit_set (unsigned long long sz)
1090{
1091#if __GNUC__
1092    unsigned clz = __builtin_clzll(sz);
1093    return 63 - clz;
1094#else
1095    unsigned long y;
1096    unsigned n;
1097    n = 64;
1098    y = sz >> 32;     if (y) { n -= 32; sz = y; }
1099    y = sz >> 16;     if (y) { n -= 16; sz = y; }
1100    y = sz >>  8;     if (y) { n -=  8; sz = y; }
1101    y = sz >>  4;     if (y) { n -=  4; sz = y; }
1102    y = sz >>  2;     if (y) { n -=  2; sz = y; }
1103    y = sz >>  1;     if (y) return 63 - n + 2;
1104    return 63 - n + sz;
1105#endif
1106}
1107
1108
1109static void
1110ignore_init (struct ietf_mini_conn *conn)
1111{
1112    struct lsquic_packet_out *packet_out, *next;
1113    unsigned count;
1114
1115    conn->imc_flags |= IMC_IGNORE_INIT;
1116    conn->imc_flags &= ~(IMC_QUEUED_ACK_INIT << PNS_INIT);
1117
1118    count = 0;
1119    for (packet_out = TAILQ_FIRST(&conn->imc_packets_out); packet_out;
1120                                                            packet_out = next)
1121    {
1122        next = TAILQ_NEXT(packet_out, po_next);
1123        if (PNS_INIT == lsquic_packet_out_pns(packet_out))
1124        {
1125            TAILQ_REMOVE(&conn->imc_packets_out, packet_out, po_next);
1126            imico_destroy_packet(conn, packet_out);
1127            ++count;
1128        }
1129    }
1130
1131    LSQ_DEBUG("henceforth, no Initial packets shall be sent or received; "
1132        "destroyed %u packet%.*s", count, count != 1, "s");
1133}
1134
1135
1136/* Only a single packet is supported */
1137static void
1138ietf_mini_conn_ci_packet_in (struct lsquic_conn *lconn,
1139                        struct lsquic_packet_in *packet_in)
1140{
1141    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1142    enum dec_packin dec_packin;
1143    enum packnum_space pns;
1144
1145    if (conn->imc_flags & IMC_ERROR)
1146    {
1147        LSQ_DEBUG("ignore incoming packet: connection is in error state");
1148        return;
1149    }
1150
1151    pns = lsquic_hety2pns[ packet_in->pi_header_type ];
1152    if (pns == PNS_INIT && (conn->imc_flags & IMC_IGNORE_INIT))
1153    {
1154        LSQ_DEBUG("ignore init packet");    /* Don't bother decrypting */
1155        return;
1156    }
1157
1158    dec_packin = lconn->cn_esf_c->esf_decrypt_packet(lconn->cn_enc_session,
1159                                conn->imc_enpub, &conn->imc_conn, packet_in);
1160    if (dec_packin != DECPI_OK)
1161    {
1162        /* TODO: handle reordering perhaps? */
1163        LSQ_DEBUG("could not decrypt packet");
1164        return;
1165    }
1166
1167    EV_LOG_PACKET_IN(LSQUIC_LOG_CONN_ID, packet_in);
1168    conn->imc_bytes_in += packet_in->pi_data_sz + IQUIC_TAG_LEN;
1169
1170    if (pns == PNS_APP)
1171    {
1172        lsquic_packet_in_upref(packet_in);
1173        TAILQ_INSERT_TAIL(&conn->imc_app_packets, packet_in, pi_next);
1174        LSQ_DEBUG("delay processing of packet %"PRIu64" in pns %u",
1175            packet_in->pi_packno, pns);
1176        return;
1177    }
1178    else if (pns == PNS_HSK)
1179        conn->imc_flags |= IMC_ADDR_VALIDATED;
1180
1181    if (((conn->imc_flags >> IMCBIT_PNS_BIT_SHIFT) & 3) < pns)
1182    {
1183        conn->imc_flags &= ~(3 << IMCBIT_PNS_BIT_SHIFT);
1184        conn->imc_flags |= pns << IMCBIT_PNS_BIT_SHIFT;
1185    }
1186
1187    if (pns == PNS_HSK && !(conn->imc_flags & IMC_IGNORE_INIT))
1188        ignore_init(conn);
1189
1190    if (conn->imc_recvd_packnos[pns] & (1ULL << packet_in->pi_packno))
1191    {
1192        LSQ_DEBUG("duplicate packet %"PRIu64, packet_in->pi_packno);
1193        return;
1194    }
1195
1196    /* Update receive history before processing the packet: if there is an
1197     * error, the connection is terminated and recording this packet number
1198     * is helpful when it is printed along with other diagnostics in dtor.
1199     */
1200    if (0 == conn->imc_recvd_packnos[pns] ||
1201            packet_in->pi_packno > highest_bit_set(conn->imc_recvd_packnos[pns]))
1202        conn->imc_largest_recvd[pns] = packet_in->pi_received;
1203    conn->imc_recvd_packnos[pns] |= 1ULL << packet_in->pi_packno;
1204
1205    if (0 != imico_parse_regular_packet(conn, packet_in))
1206    {
1207        LSQ_DEBUG("connection is now in error state");
1208        conn->imc_flags |= IMC_ERROR;
1209        return;
1210    }
1211
1212    conn->imc_flags |= IMC_QUEUED_ACK_INIT << pns;
1213    ++conn->imc_ecn_counts_in[pns][ lsquic_packet_in_ecn(packet_in) ];
1214    conn->imc_incoming_ecn <<= 1;
1215    conn->imc_incoming_ecn |= lsquic_packet_in_ecn(packet_in) != ECN_NOT_ECT;
1216}
1217
1218
1219static void
1220ietf_mini_conn_ci_packet_sent (struct lsquic_conn *lconn,
1221                              struct lsquic_packet_out *packet_out)
1222{
1223    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1224    conn->imc_sent_packnos |= 1ULL << packet_out->po_packno;
1225    conn->imc_ecn_packnos |= !!lsquic_packet_out_ecn(packet_out)
1226                                                    << packet_out->po_packno;
1227#if 0
1228    if (packet_out->po_frame_types & (1 << QUIC_FRAME_ACK))
1229    {
1230        assert(mc->mc_flags & MC_UNSENT_ACK);
1231        mc->mc_flags &= ~MC_UNSENT_ACK;
1232    }
1233#endif
1234    ++conn->imc_ecn_counts_out[ lsquic_packet_out_pns(packet_out) ]
1235                              [ lsquic_packet_out_ecn(packet_out) ];
1236    if (packet_out->po_header_type == HETY_HANDSHAKE)
1237        conn->imc_flags |= IMC_HSK_PACKET_SENT;
1238    LSQ_DEBUG("%s: packet %"PRIu64" sent", __func__, packet_out->po_packno);
1239}
1240
1241
1242static void
1243ietf_mini_conn_ci_packet_not_sent (struct lsquic_conn *lconn,
1244                              struct lsquic_packet_out *packet_out)
1245{
1246    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1247    size_t packet_size;
1248
1249    packet_out->po_flags &= ~PO_SENT;
1250    packet_size = lsquic_packet_out_total_sz(lconn, packet_out);
1251    conn->imc_bytes_out -= packet_size + IQUIC_TAG_LEN;
1252    LSQ_DEBUG("%s: packet %"PRIu64" not sent", __func__, packet_out->po_packno);
1253}
1254
1255
1256static void
1257imico_return_enc_data (struct ietf_mini_conn *conn,
1258                                        struct lsquic_packet_out *packet_out)
1259{
1260    conn->imc_enpub->enp_pmi->pmi_return(conn->imc_enpub->enp_pmi_ctx,
1261        conn->imc_path.np_peer_ctx, packet_out->po_enc_data,
1262        lsquic_packet_out_ipv6(packet_out));
1263    packet_out->po_flags &= ~PO_ENCRYPTED;
1264    packet_out->po_enc_data = NULL;
1265}
1266
1267
1268static int
1269imico_repackage_packet (struct ietf_mini_conn *conn,
1270                                        struct lsquic_packet_out *packet_out)
1271{
1272    const lsquic_packno_t oldno = packet_out->po_packno;
1273    const lsquic_packno_t packno = conn->imc_next_packno++;
1274    if (packno > MAX_PACKETS)
1275        return -1;
1276
1277    LSQ_DEBUG("Packet %"PRIu64" repackaged for resending as packet %"PRIu64,
1278                                                        oldno, packno);
1279    EV_LOG_CONN_EVENT(LSQUIC_LOG_CONN_ID, "packet %"PRIu64" repackaged for "
1280        "resending as packet %"PRIu64, oldno, packno);
1281    packet_out->po_packno = packno;
1282    packet_out->po_flags &= ~PO_SENT;
1283    lsquic_packet_out_set_ecn(packet_out, imico_get_ecn(conn));
1284    if (packet_out->po_flags & PO_ENCRYPTED)
1285        imico_return_enc_data(conn, packet_out);
1286    TAILQ_INSERT_TAIL(&conn->imc_packets_out, packet_out, po_next);
1287    return 0;
1288}
1289
1290
1291static int
1292imico_handle_losses_and_have_unsent (struct ietf_mini_conn *conn,
1293                                                            lsquic_time_t now)
1294{
1295    TAILQ_HEAD(, lsquic_packet_out) lost_packets =
1296                                    TAILQ_HEAD_INITIALIZER(lost_packets);
1297    lsquic_packet_out_t *packet_out, *next;
1298    lsquic_time_t retx_to = 0;
1299    unsigned n_to_send = 0;
1300
1301    for (packet_out = TAILQ_FIRST(&conn->imc_packets_out); packet_out;
1302                                                        packet_out = next)
1303    {
1304        next = TAILQ_NEXT(packet_out, po_next);
1305        if (packet_out->po_flags & PO_SENT)
1306        {
1307            if (0 == retx_to)
1308                retx_to = imico_calc_retx_timeout(conn);
1309            if (packet_out->po_sent + retx_to < now)
1310            {
1311                LSQ_DEBUG("packet %"PRIu64" has been lost (rto: %"PRIu64")",
1312                                                packet_out->po_packno, retx_to);
1313                TAILQ_REMOVE(&conn->imc_packets_out, packet_out, po_next);
1314                TAILQ_INSERT_TAIL(&lost_packets, packet_out, po_next);
1315            }
1316        }
1317        else
1318            ++n_to_send;
1319    }
1320
1321    conn->imc_hsk_count += !TAILQ_EMPTY(&lost_packets);
1322
1323    while ((packet_out = TAILQ_FIRST(&lost_packets)))
1324    {
1325        TAILQ_REMOVE(&lost_packets, packet_out, po_next);
1326        if ((packet_out->po_frame_types & IQUIC_FRAME_RETX_MASK)
1327                            && 0 == imico_repackage_packet(conn, packet_out))
1328            ++n_to_send;
1329        else
1330            imico_destroy_packet(conn, packet_out);
1331    }
1332
1333    return n_to_send > 0;
1334}
1335
1336
1337static int
1338imico_have_packets_to_send (struct ietf_mini_conn *conn, lsquic_time_t now)
1339{
1340    return imico_handle_losses_and_have_unsent(conn, now);
1341}
1342
1343
1344struct ietf_mini_rechist
1345{
1346    const struct ietf_mini_conn *conn;
1347    packno_set_t                 cur_set;
1348    struct lsquic_packno_range   range;   /* We return a pointer to this */
1349    int                          cur_idx;
1350    enum packnum_space           pns;
1351};
1352
1353
1354static void
1355imico_rechist_init (struct ietf_mini_rechist *rechist,
1356                    const struct ietf_mini_conn *conn, enum packnum_space pns)
1357{
1358    rechist->conn    = conn;
1359    rechist->pns     = pns;
1360    rechist->cur_set = 0;
1361    rechist->cur_idx = 0;
1362}
1363
1364
1365static lsquic_time_t
1366imico_rechist_largest_recv (void *rechist_ctx)
1367{
1368    struct ietf_mini_rechist *rechist = rechist_ctx;
1369    return rechist->conn->imc_largest_recvd[ rechist->pns ];
1370}
1371
1372
1373static const struct lsquic_packno_range *
1374imico_rechist_next (void *rechist_ctx)
1375{
1376    struct ietf_mini_rechist *rechist = rechist_ctx;
1377    const struct ietf_mini_conn *conn = rechist->conn;
1378    packno_set_t packnos;
1379    int i;
1380
1381    packnos = rechist->cur_set;
1382    if (0 == packnos)
1383        return NULL;
1384
1385    /* There may be a faster way to do this, but for now, we just want
1386     * correctness.
1387     */
1388    for (i = rechist->cur_idx; i >= 0; --i)
1389        if (packnos & (1ULL << i))
1390        {
1391            rechist->range.low  = i;
1392            rechist->range.high = i;
1393            break;
1394        }
1395    assert(i >= 0); /* We must have hit at least one bit */
1396    --i;
1397    for ( ; i >= 0 && (packnos & (1ULL << i)); --i)
1398        rechist->range.low = i;
1399    if (i >= 0)
1400    {
1401        rechist->cur_set = packnos & ((1ULL << i) - 1);
1402        rechist->cur_idx = i;
1403    }
1404    else
1405        rechist->cur_set = 0;
1406    LSQ_DEBUG("%s: return [%"PRIu64", %"PRIu64"]", __func__,
1407                                rechist->range.low, rechist->range.high);
1408    return &rechist->range;
1409}
1410
1411
1412static const struct lsquic_packno_range *
1413imico_rechist_first (void *rechist_ctx)
1414{
1415    struct ietf_mini_rechist *rechist = rechist_ctx;
1416    rechist->cur_set = rechist->conn->imc_recvd_packnos[ rechist->pns ];
1417    rechist->cur_idx = highest_bit_set(rechist->cur_set);
1418    return imico_rechist_next(rechist_ctx);
1419}
1420
1421
1422static const enum header_type pns2hety[] =
1423{
1424    [PNS_INIT]  = HETY_INITIAL,
1425    [PNS_HSK]   = HETY_HANDSHAKE,
1426    [PNS_APP]   = HETY_NOT_SET,
1427};
1428
1429
1430static int
1431imico_generate_ack (struct ietf_mini_conn *conn, enum packnum_space pns,
1432                                                            lsquic_time_t now)
1433{
1434    struct lsquic_packet_out *packet_out;
1435    enum header_type header_type;
1436    struct ietf_mini_rechist rechist;
1437    int not_used_has_missing, len;
1438    uint64_t ecn_counts_buf[4];
1439    const uint64_t *ecn_counts;
1440
1441    header_type = pns2hety[pns];
1442
1443    if (conn->imc_incoming_ecn)
1444    {
1445        ecn_counts_buf[0]   = conn->imc_ecn_counts_in[pns][0];
1446        ecn_counts_buf[1]   = conn->imc_ecn_counts_in[pns][1];
1447        ecn_counts_buf[2]   = conn->imc_ecn_counts_in[pns][2];
1448        ecn_counts_buf[3]   = conn->imc_ecn_counts_in[pns][3];
1449        ecn_counts = ecn_counts_buf;
1450    }
1451    else
1452        ecn_counts = NULL;
1453
1454    packet_out = imico_get_packet_out(conn, header_type, 0);
1455    if (!packet_out)
1456        return -1;
1457
1458    /* Generate ACK frame */
1459    imico_rechist_init(&rechist, conn, pns);
1460    len = conn->imc_conn.cn_pf->pf_gen_ack_frame(
1461                packet_out->po_data + packet_out->po_data_sz,
1462                lsquic_packet_out_avail(packet_out), imico_rechist_first,
1463                imico_rechist_next, imico_rechist_largest_recv, &rechist,
1464                now, &not_used_has_missing, &packet_out->po_ack2ed, ecn_counts);
1465    if (len < 0)
1466    {
1467        LSQ_WARN("could not generate ACK frame");
1468        return -1;
1469    }
1470    EV_LOG_GENERATED_ACK_FRAME(LSQUIC_LOG_CONN_ID, conn->imc_conn.cn_pf,
1471                        packet_out->po_data + packet_out->po_data_sz, len);
1472    packet_out->po_frame_types |= 1 << QUIC_FRAME_ACK;
1473    packet_out->po_data_sz += len;
1474    packet_out->po_regen_sz += len;
1475    conn->imc_flags &= ~(IMC_QUEUED_ACK_INIT << pns);
1476    LSQ_DEBUG("wrote ACK frame of size %d", len);
1477    return 0;
1478}
1479
1480
1481static int
1482imico_generate_acks (struct ietf_mini_conn *conn, lsquic_time_t now)
1483{
1484    enum packnum_space pns;
1485
1486    for (pns = PNS_INIT; pns < N_PNS; ++pns)
1487        if (conn->imc_flags & (IMC_QUEUED_ACK_INIT << pns)
1488                && !(pns == PNS_INIT && (conn->imc_flags & IMC_IGNORE_INIT)))
1489            if (0 != imico_generate_ack(conn, pns, now))
1490                return -1;
1491
1492    return 0;
1493}
1494
1495
1496static void
1497imico_generate_conn_close (struct ietf_mini_conn *conn)
1498{
1499    struct lsquic_packet_out *packet_out;
1500    enum header_type header_type;
1501    enum packnum_space pns, pns_max;
1502    unsigned error_code;
1503    const char *reason;
1504    size_t need;
1505    int sz, rlen, is_app;
1506    char reason_buf[0x20];
1507
1508    if (conn->imc_flags & IMC_ABORT_ERROR)
1509    {
1510        is_app = !!(conn->imc_flags & IMC_ABORT_ISAPP);
1511        error_code = conn->imc_error_code;
1512        reason = NULL;
1513        rlen = 0;
1514    }
1515    else if (conn->imc_flags & IMC_TLS_ALERT)
1516    {
1517        is_app = 0;
1518        error_code = 0x100 + conn->imc_tls_alert;
1519        if (ALERT_NO_APPLICATION_PROTOCOL == conn->imc_tls_alert)
1520            reason = "no suitable application protocol";
1521        else
1522        {
1523            snprintf(reason_buf, sizeof(reason_buf), "TLS alert %"PRIu8,
1524                                                        conn->imc_tls_alert);
1525            reason = reason_buf;
1526        }
1527        rlen = strlen(reason);
1528    }
1529    else if (conn->imc_flags & IMC_BAD_TRANS_PARAMS)
1530    {
1531        is_app = 0;
1532        error_code = TEC_NO_ERROR;
1533        reason = "bad transport parameters";
1534        rlen = 24;
1535    }
1536    else if (conn->imc_flags & IMC_HSK_FAILED)
1537    {
1538        is_app = 0;
1539        error_code = TEC_NO_ERROR;
1540        reason = "handshake failed";
1541        rlen = 16;
1542    }
1543    else
1544    {
1545        is_app = 0;
1546        error_code = TEC_INTERNAL_ERROR;
1547        reason = NULL;
1548        rlen = 0;
1549    }
1550
1551
1552/* [draft-ietf-quic-transport-23] Section 12.2:
1553 *
1554 " A client will always know whether the server has Handshake keys (see
1555 " Section 17.2.2.1), but it is possible that a server does not know
1556 " whether the client has Handshake keys.  Under these circumstances, a
1557 " server SHOULD send a CONNECTION_CLOSE frame in both Handshake and
1558 " Initial packets to ensure that at least one of them is processable by
1559 " the client.
1560 */
1561
1562    pns = (conn->imc_flags >> IMCBIT_PNS_BIT_SHIFT) & 3;
1563    switch ((!!(conn->imc_flags & IMC_HSK_PACKET_SENT) << 1)
1564                | (pns == PNS_HSK) /* Handshake packet received */)
1565    {
1566    case (0 << 1) | 0:
1567        pns = PNS_INIT;
1568        pns_max = PNS_INIT;
1569        break;
1570    case (1 << 1) | 0:
1571        pns = PNS_INIT;
1572        pns_max = PNS_HSK;
1573        break;
1574    default:
1575        pns = PNS_HSK;
1576        pns_max = PNS_HSK;
1577        break;
1578    }
1579
1580    need = conn->imc_conn.cn_pf->pf_connect_close_frame_size(is_app,
1581                                                        error_code, 0, rlen);
1582    LSQ_DEBUG("will generate %u CONNECTION_CLOSE frame%.*s",
1583        pns_max - pns + 1, pns_max > pns, "s");
1584    do
1585    {
1586        header_type = pns2hety[pns];
1587        packet_out = imico_get_packet_out(conn, header_type, need);
1588        if (!packet_out)
1589            return;
1590        sz = conn->imc_conn.cn_pf->pf_gen_connect_close_frame(
1591                 packet_out->po_data + packet_out->po_data_sz,
1592                 lsquic_packet_out_avail(packet_out), is_app, error_code, reason,
1593                 rlen);
1594        if (sz >= 0)
1595        {
1596            packet_out->po_frame_types |= 1 << QUIC_FRAME_CONNECTION_CLOSE;
1597            packet_out->po_data_sz += sz;
1598            LSQ_DEBUG("generated CONNECTION_CLOSE frame");
1599        }
1600        else
1601            LSQ_WARN("could not generate CONNECTION_CLOSE frame");
1602        ++pns;
1603    }
1604    while (pns <= pns_max);
1605}
1606
1607
1608static enum tick_st
1609ietf_mini_conn_ci_tick (struct lsquic_conn *lconn, lsquic_time_t now)
1610{
1611    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1612    enum tick_st tick;
1613
1614    if (conn->imc_created + conn->imc_enpub->enp_settings.es_handshake_to < now)
1615    {
1616        LSQ_DEBUG("connection expired: closing");
1617        return TICK_CLOSE;
1618    }
1619
1620
1621    if (conn->imc_flags &
1622            (IMC_QUEUED_ACK_INIT|IMC_QUEUED_ACK_HSK|IMC_QUEUED_ACK_APP))
1623    {
1624        if (0 != imico_generate_acks(conn, now))
1625        {
1626            conn->imc_flags |= IMC_ERROR;
1627            return TICK_CLOSE;
1628        }
1629    }
1630
1631
1632    tick = 0;
1633
1634    if (conn->imc_flags & IMC_ERROR)
1635    {
1636        if (!(conn->imc_flags & IMC_CLOSE_RECVD))
1637            imico_generate_conn_close(conn);
1638        tick |= TICK_CLOSE;
1639    }
1640    else if (conn->imc_flags & IMC_HSK_OK)
1641        tick |= TICK_PROMOTE;
1642
1643    if (imico_have_packets_to_send(conn, now))
1644        tick |= TICK_SEND;
1645    else
1646        tick |= TICK_QUIET;
1647
1648    LSQ_DEBUG("Return TICK %d", tick);
1649    return tick;
1650}
1651
1652
1653static void
1654ietf_mini_conn_ci_internal_error (struct lsquic_conn *lconn,
1655                                                    const char *format, ...)
1656{
1657    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1658    LSQ_INFO("internal error reported");
1659    conn->imc_flags |= IMC_ERROR;
1660}
1661
1662
1663static void
1664ietf_mini_conn_ci_abort_error (struct lsquic_conn *lconn, int is_app,
1665                                unsigned error_code, const char *fmt, ...)
1666{
1667    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1668    va_list ap;
1669    const char *err_str, *percent;
1670    char err_buf[0x100];
1671
1672    percent = strchr(fmt, '%');
1673    if (percent)
1674    {
1675        va_start(ap, fmt);
1676        vsnprintf(err_buf, sizeof(err_buf), fmt, ap);
1677        va_end(ap);
1678        err_str = err_buf;
1679    }
1680    else
1681        err_str = fmt;
1682    LSQ_INFO("abort error: is_app: %d; error code: %u; error str: %s",
1683        is_app, error_code, err_str);
1684    conn->imc_flags |= IMC_ERROR|IMC_ABORT_ERROR;
1685    if (is_app)
1686        conn->imc_flags |= IMC_ABORT_ISAPP;
1687    conn->imc_error_code = error_code;
1688}
1689
1690
1691static struct network_path *
1692ietf_mini_conn_ci_get_path (struct lsquic_conn *lconn,
1693                                                    const struct sockaddr *sa)
1694{
1695    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1696
1697    return &conn->imc_path;
1698}
1699
1700
1701static const lsquic_cid_t *
1702ietf_mini_conn_ci_get_log_cid (const struct lsquic_conn *lconn)
1703{
1704    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1705
1706    if (conn->imc_path.np_dcid.len)
1707        return &conn->imc_path.np_dcid;
1708    else
1709        return CN_SCID(lconn);
1710}
1711
1712
1713static unsigned char
1714ietf_mini_conn_ci_record_addrs (struct lsquic_conn *lconn, void *peer_ctx,
1715            const struct sockaddr *local_sa, const struct sockaddr *peer_sa)
1716{
1717    struct ietf_mini_conn *conn = (struct ietf_mini_conn *) lconn;
1718    struct lsquic_packet_out *packet_out;
1719    size_t len;
1720
1721    if (NP_IS_IPv6(&conn->imc_path) != (AF_INET6 == peer_sa->sa_family))
1722        TAILQ_FOREACH(packet_out, &conn->imc_packets_out, po_next)
1723            if ((packet_out->po_flags & (PO_SENT|PO_ENCRYPTED)) == PO_ENCRYPTED)
1724                imico_return_enc_data(conn, packet_out);
1725
1726    len = local_sa->sa_family == AF_INET ? sizeof(struct sockaddr_in)
1727                                                : sizeof(struct sockaddr_in6);
1728
1729    memcpy(conn->imc_path.np_peer_addr, peer_sa, len);
1730    memcpy(conn->imc_path.np_local_addr, local_sa, len);
1731    conn->imc_path.np_peer_ctx = peer_ctx;
1732    return 0;
1733}
1734
1735
1736static const struct conn_iface mini_conn_ietf_iface = {
1737    .ci_abort_error          =  ietf_mini_conn_ci_abort_error,
1738    .ci_client_call_on_new   =  ietf_mini_conn_ci_client_call_on_new,
1739    .ci_destroy              =  ietf_mini_conn_ci_destroy,
1740    .ci_get_engine           =  ietf_mini_conn_ci_get_engine,
1741    .ci_get_log_cid          =  ietf_mini_conn_ci_get_log_cid,
1742    .ci_get_path             =  ietf_mini_conn_ci_get_path,
1743    .ci_hsk_done             =  ietf_mini_conn_ci_hsk_done,
1744    .ci_internal_error       =  ietf_mini_conn_ci_internal_error,
1745    .ci_is_tickable          =  ietf_mini_conn_ci_is_tickable,
1746    .ci_next_packet_to_send  =  ietf_mini_conn_ci_next_packet_to_send,
1747    .ci_next_tick_time       =  ietf_mini_conn_ci_next_tick_time,
1748    .ci_packet_in            =  ietf_mini_conn_ci_packet_in,
1749    .ci_packet_not_sent      =  ietf_mini_conn_ci_packet_not_sent,
1750    .ci_packet_sent          =  ietf_mini_conn_ci_packet_sent,
1751    .ci_record_addrs         =  ietf_mini_conn_ci_record_addrs,
1752    .ci_tick                 =  ietf_mini_conn_ci_tick,
1753    .ci_tls_alert            =  ietf_mini_conn_ci_tls_alert,
1754};
1755