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