lsquic_parse_ietf_v1.c revision de46bf2f
1/* Copyright (c) 2017 - 2019 LiteSpeed Technologies Inc.  See LICENSE. */
2/*
3 * lsquic_parse_ietf_v1.c -- Parsing functions specific to IETF QUIC v1
4 */
5
6#include <assert.h>
7#include <inttypes.h>
8#include <errno.h>
9#include <stddef.h>
10#include <string.h>
11#include <sys/queue.h>
12#ifndef WIN32
13#include <sys/types.h>
14#else
15#include <vc_compat.h>
16#endif
17
18#include "lsquic_types.h"
19#include "lsquic_int_types.h"
20#include "lsquic_sizes.h"
21#include "lsquic_packet_common.h"
22#include "lsquic_packet_ietf.h"
23#include "lsquic_packet_in.h"
24#include "lsquic_packet_out.h"
25#include "lsquic_parse.h"
26#include "lsquic_parse_common.h"
27#include "lsquic_sfcw.h"
28#include "lsquic_varint.h"
29#include "lsquic_hq.h"
30#include "lsquic_hash.h"
31#include "lsquic_stream.h"
32#include "lsquic_mm.h"
33#include "lsquic_malo.h"
34#include "lsquic_version.h"
35#include "lsquic.h"
36#include "lsquic_byteswap.h"
37#include "lsquic_varint.h"
38#include "lsquic_conn.h"
39#include "lsquic_enc_sess.h"
40#include "lsquic_trans_params.h"
41#include "lsquic_parse_ietf.h"
42#include "lsquic_qtags.h"
43
44#define LSQUIC_LOGGER_MODULE LSQLM_PARSE
45#include "lsquic_logger.h"
46
47#define CHECK_SPACE(need, pstart, pend)  \
48    do { if ((intptr_t) (need) > ((pend) - (pstart))) { return -1; } } while (0)
49
50static int
51ietf_v1_gen_one_varint (unsigned char *, size_t, unsigned char, uint64_t);
52
53static int
54ietf_v1_gen_two_varints (unsigned char *, size_t, unsigned char, uint64_t[2]);
55
56static void
57ietf_v1_parse_packet_in_finish (lsquic_packet_in_t *packet_in,
58                                            struct packin_parse_state *state)
59{
60    /* Packet number is set to an invalid value.  The packet number must
61     * be decrypted, which happens later.
62     */
63    packet_in->pi_packno        = 1ULL << 62;
64}
65
66
67/* Note: token size is not accounted for */
68static size_t
69ietf_v1_packout_header_size_long_by_flags (const struct lsquic_conn *lconn,
70                enum header_type header_type, enum packet_out_flags flags,
71                size_t dcid_len)
72{
73    size_t sz;
74    enum packno_bits packno_bits;
75
76    packno_bits = (flags >> POBIT_SHIFT) & 0x3;
77
78    sz = 1 /* Type */
79       + 4 /* Version */
80       + 1 /* DCIL */
81       + dcid_len
82       + 1 /* SCIL */
83       + CN_SCID(lconn)->len
84       + (header_type == HETY_INITIAL)  /* Token length */
85       + 2 /* Always use two bytes to encode payload length */
86       + iquic_packno_bits2len(packno_bits)
87       ;
88
89    return sz;
90}
91
92
93static size_t
94ietf_v1_packout_header_size_long_by_packet (const struct lsquic_conn *lconn,
95                                const struct lsquic_packet_out *packet_out)
96{
97    size_t sz;
98    unsigned token_len; /* Need intermediate value to quiet compiler warning */
99    enum packno_bits packno_bits;
100
101    packno_bits = lsquic_packet_out_packno_bits(packet_out);
102
103    sz = 1 /* Type */
104       + 4 /* Version */
105       + 1 /* DCIL */
106       + packet_out->po_path->np_dcid.len
107       + 1 /* SCIL */
108       + CN_SCID(lconn)->len
109       + (packet_out->po_header_type == HETY_INITIAL ?
110            (token_len = packet_out->po_token_len,
111                (1 << vint_val2bits(token_len)) + token_len) : 0)
112       + 2 /* Always use two bytes to encode payload length */
113       + iquic_packno_bits2len(packno_bits)
114       ;
115
116    return sz;
117}
118
119
120static size_t
121ietf_v1_packout_header_size_short (const struct lsquic_conn *lconn,
122                                enum packet_out_flags flags, size_t dcid_len)
123{
124    enum packno_bits bits;
125    size_t sz;
126
127    bits = (flags >> POBIT_SHIFT) & 0x3;
128    sz = 1 /* Type */
129       + (flags & PO_CONN_ID ? dcid_len : 0)
130       + iquic_packno_bits2len(bits)
131       ;
132
133    return sz;
134}
135
136
137static size_t
138ietf_v1_packout_max_header_size (const struct lsquic_conn *lconn,
139                                enum packet_out_flags flags, size_t dcid_len)
140{
141    if (lconn->cn_flags & LSCONN_HANDSHAKE_DONE)
142        return ietf_v1_packout_header_size_short(lconn, flags, dcid_len);
143    else if (lconn->cn_flags & LSCONN_SERVER)
144        /* Server does not set the token in its Initial packet header: set
145         * the packet type to something else in order not to overestimate
146         * header size.
147         */
148        return ietf_v1_packout_header_size_long_by_flags(lconn, HETY_HANDSHAKE,
149                                                            flags, dcid_len);
150    else
151        return ietf_v1_packout_header_size_long_by_flags(lconn, HETY_INITIAL,
152                                                            flags, dcid_len);
153}
154
155
156/* [draft-ietf-quic-transport-17] Section-17.2 */
157static const unsigned char header_type_to_bin[] = {
158    [HETY_INITIAL]      = 0x0,
159    [HETY_0RTT]         = 0x1,
160    [HETY_HANDSHAKE]    = 0x2,
161    [HETY_RETRY]        = 0x3,
162};
163
164
165static unsigned
166write_packno (unsigned char *p, lsquic_packno_t packno,
167                                                enum packno_bits bits)
168{
169    unsigned char *const begin = p;
170
171    switch (bits)
172    {
173    case IQUIC_PACKNO_LEN_4:
174        *p++ = packno >> 24;
175    case IQUIC_PACKNO_LEN_3:
176        *p++ = packno >> 16;
177    case IQUIC_PACKNO_LEN_2:
178        *p++ = packno >> 8;
179    default:
180        *p++ = packno;
181    }
182
183    return p - begin;
184}
185
186
187static int
188gen_long_pkt_header (const struct lsquic_conn *lconn,
189            const struct lsquic_packet_out *packet_out, unsigned char *buf,
190                                                                size_t bufsz)
191{
192    unsigned payload_len, bits;
193    enum packno_bits packno_bits;
194    lsquic_ver_tag_t ver_tag;
195    unsigned char *p;
196    unsigned token_len;
197    size_t need;
198
199    need = ietf_v1_packout_header_size_long_by_packet(lconn, packet_out);
200    if (need > bufsz)
201    {
202        errno = EINVAL;
203        return -1;
204    }
205
206    packno_bits = lsquic_packet_out_packno_bits(packet_out);
207    p = buf;
208    *p++ = 0xC0
209         | ( header_type_to_bin[ packet_out->po_header_type ] << 4)
210         | packno_bits
211         ;
212    ver_tag = lsquic_ver2tag(lconn->cn_version);
213    memcpy(p, &ver_tag, sizeof(ver_tag));
214    p += sizeof(ver_tag);
215
216    *p++ = packet_out->po_path->np_dcid.len;
217    memcpy(p, packet_out->po_path->np_dcid.idbuf, packet_out->po_path->np_dcid.len);
218    p += packet_out->po_path->np_dcid.len;
219    *p++ = CN_SCID(lconn)->len;
220    memcpy(p, CN_SCID(lconn)->idbuf, CN_SCID(lconn)->len);
221    p +=  CN_SCID(lconn)->len;
222
223    if (HETY_INITIAL == packet_out->po_header_type)
224    {
225        token_len = packet_out->po_token_len;
226        bits = vint_val2bits(token_len);
227        vint_write(p, token_len, bits, 1 << bits);
228        p += 1 << bits;
229        memcpy(p, packet_out->po_token, token_len);
230        p += token_len;
231    }
232
233    payload_len = packet_out->po_data_sz
234                + lconn->cn_esf_c->esf_tag_len
235                + iquic_packno_bits2len(packno_bits);
236    bits = 1;   /* Always use two bytes to encode payload length */
237    vint_write(p, payload_len, bits, 1 << bits);
238    p += 1 << bits;
239
240    p += write_packno(p, packet_out->po_packno, packno_bits);
241
242    return p - buf;
243}
244
245
246static int
247gen_short_pkt_header (const struct lsquic_conn *lconn,
248            const struct lsquic_packet_out *packet_out, unsigned char *buf,
249                                                                size_t bufsz)
250{
251    unsigned packno_len, cid_len, need;
252    enum packno_bits packno_bits;
253
254    packno_bits = lsquic_packet_out_packno_bits(packet_out);
255    packno_len = iquic_packno_bits2len(packno_bits);
256    cid_len = packet_out->po_flags & PO_CONN_ID ? packet_out->po_path->np_dcid.len : 0;
257
258    need = 1 + cid_len + packno_len;
259    if (need > bufsz)
260        return -1;
261
262    buf[0] = 0x40
263           | (lsquic_packet_out_spin_bit(packet_out) << 5)
264           | (lsquic_packet_out_square_bit(packet_out) << 4)
265           | (lsquic_packet_out_loss_bit(packet_out) << 3)
266           | (lsquic_packet_out_key_phase(packet_out) << 2)
267           | packno_bits
268           ;
269
270    if (cid_len)
271        memcpy(buf + 1, packet_out->po_path->np_dcid.idbuf, cid_len);
272
273    (void) write_packno(buf + 1 + cid_len, packet_out->po_packno, packno_bits);
274
275    return need;
276}
277
278
279static int
280ietf_v1_gen_reg_pkt_header (const struct lsquic_conn *lconn,
281            const struct lsquic_packet_out *packet_out, unsigned char *buf,
282                                                                size_t bufsz)
283{
284    if (packet_out->po_header_type == HETY_NOT_SET)
285        return gen_short_pkt_header(lconn, packet_out, buf, bufsz);
286    else
287        return gen_long_pkt_header(lconn, packet_out, buf, bufsz);
288}
289
290
291static void
292ietf_v1_packno_info (const struct lsquic_conn *lconn,
293        const struct lsquic_packet_out *packet_out, unsigned *packno_off,
294        unsigned *packno_len)
295{
296    unsigned token_len; /* Need intermediate value to quiet compiler warning */
297
298    if (packet_out->po_header_type == HETY_NOT_SET)
299        *packno_off = 1 +
300            (packet_out->po_flags & PO_CONN_ID ? packet_out->po_path->np_dcid.len : 0);
301    else
302        *packno_off = 1
303                    + 4
304                    + 1
305                    + packet_out->po_path->np_dcid.len
306                    + 1
307                    + CN_SCID(lconn)->len
308                    + (packet_out->po_header_type == HETY_INITIAL ?
309                        (token_len = packet_out->po_token_len,
310                            (1 << vint_val2bits(token_len)) + token_len) : 0)
311                    + 2;
312    *packno_len = iquic_packno_bits2len(
313        lsquic_packet_out_packno_bits(packet_out));
314}
315
316
317static size_t
318ietf_v1_packout_size (const struct lsquic_conn *lconn,
319                                const struct lsquic_packet_out *packet_out)
320{
321    size_t sz;
322
323    if ((lconn->cn_flags & LSCONN_HANDSHAKE_DONE)
324                                && packet_out->po_header_type == HETY_NOT_SET)
325        sz = ietf_v1_packout_header_size_short(lconn, packet_out->po_flags,
326                                            packet_out->po_path->np_dcid.len);
327    else
328        sz = ietf_v1_packout_header_size_long_by_packet(lconn, packet_out);
329
330    sz += packet_out->po_data_sz;
331    sz += lconn->cn_esf_c->esf_tag_len;
332
333    return sz;
334}
335
336
337static int
338ietf_v1_gen_stream_frame (unsigned char *buf, size_t buf_len,
339        lsquic_stream_id_t stream_id, uint64_t offset, int fin, size_t size,
340        gsf_read_f gsf_read, void *stream)
341{
342    /* 0b00001XXX
343     *  0x4     OFF
344     *  0x2     LEN
345     *  0x1     FIN
346     */
347    unsigned sbits, obits, dbits;
348    unsigned slen, olen, dlen;
349    unsigned char *p = buf + 1;
350
351    assert(!!fin ^ !!size);
352
353    /* We do not check that stream_id, offset, and size are smaller
354     * than 2^62: this is not necessary, as this code will never generate
355     * this many stream IDs, nor will it even transfer this much data.
356     * The size is limited by our own code.
357     */
358
359    sbits = vint_val2bits(stream_id);
360    slen = 1 << sbits;
361    if (offset)
362    {
363        obits = vint_val2bits(offset);
364        olen = 1 << obits;
365    }
366    else
367        olen = 0;
368
369    if (!fin)
370    {
371        unsigned n_avail;
372        size_t nr;
373
374        n_avail = buf_len - (p + slen + olen - buf);
375
376        /* If we cannot fill remaining buffer, we need to include data
377         * length.
378         */
379        if (size < n_avail)
380        {
381            dbits = vint_val2bits(size);
382            dlen = 1 << dbits;
383            n_avail -= dlen;
384            if (size > n_avail)
385                size = n_avail;
386        }
387        else
388        {
389            dlen = 0;
390            size = n_avail;
391        }
392
393        CHECK_STREAM_SPACE(1 + olen + slen + dlen +
394            + 1 /* We need to write at least 1 byte */, buf, buf + buf_len);
395
396        vint_write(p, stream_id, sbits, slen);
397        p += slen;
398
399        if (olen)
400            vint_write(p, offset, obits, olen);
401        p += olen;
402
403        /* Read as much as we can */
404        nr = gsf_read(stream, p + dlen, size, &fin);
405        assert(nr != 0);
406        assert(nr <= size);
407
408        if (dlen)
409            vint_write(p, nr, dbits, dlen);
410
411        p += dlen + nr;
412    }
413    else
414    {
415        dlen = 1 + slen + olen < buf_len;
416        CHECK_STREAM_SPACE(1 + slen + olen + dlen, buf, buf + buf_len);
417        vint_write(p, stream_id, sbits, slen);
418        p += slen;
419        if (olen)
420            vint_write(p, offset, obits, olen);
421        p += olen;
422        if (dlen)
423            *p++ = 0;
424    }
425
426    buf[0] = 0x08
427           | (!!olen << 2)
428           | (!!dlen << 1)
429           | (!!fin  << 0)
430           ;
431    return p - buf;
432}
433
434
435int
436lsquic_ietf_v1_gen_crypto_frame (unsigned char *buf, unsigned char first_byte,
437            size_t buf_len, uint64_t offset, size_t size, gcf_read_f gcf_read,
438            void *stream)
439{
440    unsigned char *const end = buf + buf_len;
441    unsigned char *p;
442    unsigned obits, dbits;
443    unsigned olen, dlen;
444    size_t nr, n_avail;
445
446    obits = vint_val2bits(offset);
447    olen = 1 << obits;
448    dbits = vint_val2bits(size);
449    dlen = 1 << dbits;
450
451    CHECK_SPACE(1 + olen + dlen
452        + (dlen > 0) /* We need to write at least 1 byte */, buf, end);
453
454    n_avail = end - buf - 1 - olen - dlen;
455    if (n_avail < size)
456        size = n_avail;
457
458    p = buf;
459    *p++ = first_byte;
460
461    vint_write(p, offset, obits, olen);
462    p += olen;
463
464    nr = gcf_read(stream, p + dlen, size);
465    assert(nr != 0);    /* This indicates error in the caller */
466    assert(nr <= size); /* This also indicates an error in the caller */
467
468    vint_write(p, nr, dbits, dlen);
469    p += dlen + nr;
470
471    return p - buf;
472}
473
474
475static int
476ietf_v1_gen_crypto_frame (unsigned char *buf, size_t buf_len,
477        uint64_t offset, size_t size, gcf_read_f gcf_read, void *stream)
478{
479    return lsquic_ietf_v1_gen_crypto_frame(buf, 0x6, buf_len, offset,
480                                                size, gcf_read, stream);
481}
482
483
484/* return parsed (used) buffer length */
485static int
486ietf_v1_parse_stream_frame (const unsigned char *buf, size_t rem_packet_sz,
487                                        struct stream_frame *stream_frame)
488{
489    /* 0b00001XXX
490     *  0x4     OFF
491     *  0x2     LEN
492     *  0x1     FIN
493     */
494    const unsigned char *const pend = buf + rem_packet_sz;
495    const unsigned char *p = buf;
496    lsquic_stream_id_t stream_id;
497    uint64_t offset, data_sz;
498    int r;
499
500    CHECK_SPACE(1, p, pend);
501    const char type = *p++;
502
503    r = vint_read(p, pend, &stream_id);
504    if (r < 0)
505        return -1;
506    p += r;
507
508    if (type & 0x4)
509    {
510        r = vint_read(p, pend, &offset);
511        if (r < 0)
512            return -1;
513        p += r;
514    }
515    else
516        offset = 0;
517
518    if (type & 0x2)
519    {
520        r = vint_read(p, pend, &data_sz);
521        if (r < 0)
522            return -1;
523        p += r;
524        CHECK_SPACE(data_sz, p, pend);
525    }
526    else
527        data_sz = pend - p;
528
529    stream_frame->stream_id             = stream_id;
530    stream_frame->data_frame.df_fin     = type & 0x1;
531    stream_frame->data_frame.df_offset  = offset;
532    stream_frame->data_frame.df_size    = data_sz;
533    stream_frame->data_frame.df_data    = p;
534    stream_frame->data_frame.df_read_off= 0;
535    stream_frame->packet_in             = NULL;
536
537    assert(p <= pend);
538
539    return p + data_sz - (unsigned char *) buf;
540}
541
542
543int
544lsquic_ietf_v1_parse_crypto_frame (const unsigned char *buf,
545                    size_t rem_packet_sz, struct stream_frame *stream_frame)
546{
547    const unsigned char *const pend = buf + rem_packet_sz;
548    const unsigned char *p = buf;
549    uint64_t offset, data_sz;
550    int r;
551
552    CHECK_SPACE(1, p, pend);
553
554    ++p;
555
556    r = vint_read(p, pend, &offset);
557    if (r < 0)
558        return -1;
559    p += r;
560
561    r = vint_read(p, pend, &data_sz);
562    if (r < 0)
563        return -1;
564    p += r;
565    CHECK_SPACE(data_sz, p, pend);
566
567    stream_frame->stream_id             = ~0ULL;    /* Unset */
568    stream_frame->data_frame.df_fin     = 0;
569    stream_frame->data_frame.df_offset  = offset;
570    stream_frame->data_frame.df_size    = data_sz;
571    stream_frame->data_frame.df_data    = p;
572    stream_frame->data_frame.df_read_off= 0;
573    stream_frame->packet_in             = NULL;
574
575    assert(p <= pend);
576
577    return p + data_sz - (unsigned char *) buf;
578}
579
580
581static int
582ietf_v1_parse_crypto_frame (const unsigned char *buf, size_t rem_packet_sz,
583                                        struct stream_frame *stream_frame)
584{
585    if (rem_packet_sz > 0)
586    {
587        assert(0x06 == buf[0]);
588        return lsquic_ietf_v1_parse_crypto_frame(buf, rem_packet_sz,
589                                                            stream_frame);
590    }
591    else
592        return -1;
593}
594
595
596#if __GNUC__
597#   define UNLIKELY(cond) __builtin_expect(cond, 0)
598#else
599#   define UNLIKELY(cond) cond
600#endif
601
602
603/* Bits 10 (2) is ECT(0); * bits 01 (1) is ECT(1). */
604static const int ecnmap[4] = { 0, 2, 1, 3, };
605
606
607static int
608ietf_v1_parse_ack_frame (const unsigned char *const buf, size_t buf_len,
609                                            struct ack_info *ack, uint8_t exp)
610{
611    const unsigned char *p = buf;
612    const unsigned char *const end = buf + buf_len;
613    uint64_t block_count, gap, block;
614    enum ecn ecn;
615    unsigned i;
616    int r;
617
618    ++p;
619    r = vint_read(p, end, &ack->ranges[0].high);
620    if (UNLIKELY(r < 0))
621        return -1;
622    p += r;
623    r = vint_read(p, end, &ack->lack_delta);
624    if (UNLIKELY(r < 0))
625        return -1;
626    p += r;
627    ack->lack_delta <<= exp;
628    r = vint_read(p, end, &block_count);
629    if (UNLIKELY(r < 0))
630        return -1;
631    p += r;
632    r = vint_read(p, end, &block);
633    if (UNLIKELY(r < 0))
634        return -1;
635    ack->ranges[0].low = ack->ranges[0].high - block;
636    if (UNLIKELY(ack->ranges[0].high < ack->ranges[0].low))
637        return -1;
638    p += r;
639
640    for (i = 1; i <= block_count; ++i)
641    {
642        r = vint_read(p, end, &gap);
643        if (UNLIKELY(r < 0))
644            return -1;
645        p += r;
646        r = vint_read(p, end, &block);
647        if (UNLIKELY(r < 0))
648            return -1;
649        p += r;
650        if (i < sizeof(ack->ranges) / sizeof(ack->ranges[0]))
651        {
652            ack->ranges[i].high = ack->ranges[i - 1].low - gap - 2;
653            ack->ranges[i].low  = ack->ranges[i].high - block;
654            if (UNLIKELY(ack->ranges[i].high >= ack->ranges[i - 1].low
655                         || ack->ranges[i].high < ack->ranges[i].low))
656                return -1;
657        }
658    }
659
660    if (i < sizeof(ack->ranges) / sizeof(ack->ranges[0]))
661    {
662        ack->flags = 0;
663        ack->n_ranges = block_count + 1;
664    }
665    else
666    {
667        ack->flags = AI_TRUNCATED;
668        ack->n_ranges = sizeof(ack->ranges) / sizeof(ack->ranges[0]);
669    }
670
671
672    if (0x03 == buf[0])
673    {
674        for (ecn = 1; ecn <= 3; ++ecn)
675        {
676            r = vint_read(p, end, &ack->ecn_counts[ecnmap[ecn]]);
677            if (UNLIKELY(r < 0))
678                return -1;
679            p += r;
680        }
681        ack->flags |= AI_ECN;
682    }
683
684    return p - buf;
685}
686
687
688static unsigned
689ietf_v1_rst_frame_size (lsquic_stream_id_t stream_id, uint64_t error_code,
690                                                            uint64_t final_size)
691{
692    return 1                        /* Type */
693         + vint_size(stream_id)   /* Stream ID (i) */
694         + vint_size(error_code)  /* Application Error Code (i) */
695         + vint_size(final_size); /* Final Size (i) */
696}
697
698
699static int
700ietf_v1_gen_rst_frame (unsigned char *buf, size_t buf_len,
701        lsquic_stream_id_t stream_id, uint64_t error_code, uint64_t final_size)
702{
703    unsigned vbits;
704    unsigned char *p;
705
706    if (buf_len < ietf_v1_rst_frame_size(stream_id, error_code, final_size))
707        return -1;
708    p = buf;
709
710    *p++ = 0x04;
711    /* Stream ID (i) */
712    vbits = vint_val2bits(stream_id);
713    vint_write(p, stream_id, vbits, 1 << vbits);
714    p += 1 << vbits;
715
716    /* Application Error Code (i) */
717    vbits = vint_val2bits(error_code);
718    vint_write(p, error_code, vbits, 1 << vbits);
719    p += 1 << vbits;
720
721    /* Final Size (i) */
722    vbits = vint_val2bits(final_size);
723    vint_write(p, final_size, vbits, 1 << vbits);
724    p += 1 << vbits;
725
726    return p - buf;
727}
728
729
730static int
731ietf_v1_parse_rst_frame (const unsigned char *buf, size_t buf_len,
732    lsquic_stream_id_t *stream_id_p, uint64_t *final_size_p, uint64_t *error_code_p)
733{
734    const unsigned char *p = buf + 1;
735    const unsigned char *const end = buf + buf_len;
736    uint64_t stream_id, final_size, error_code;
737    int r;
738
739    /* Stream ID (i) */
740    r = vint_read(p, end, &stream_id);
741    if (r < 0)
742        return r;
743    p += r;
744
745    /* Application Error Code (i) */
746    r = vint_read(p, end, &error_code);
747    if (r < 0)
748        return r;
749    p += r;
750
751    /* Final Size (i) */
752    r = vint_read(p, end, &final_size);
753    if (r < 0)
754        return r;
755    p += r;
756
757    *stream_id_p = stream_id;
758    *final_size_p = final_size;
759    *error_code_p = error_code;
760
761    return p - buf;
762}
763
764
765static int
766ietf_v1_parse_stop_sending_frame (const unsigned char *buf, size_t buf_len,
767                        lsquic_stream_id_t *stream_id, uint64_t *error_code)
768{
769    const unsigned char *p = buf + 1;
770    const unsigned char *const end = buf + buf_len;
771    int r;
772
773    r = vint_read(p, end, stream_id);
774    if (r < 0)
775        return r;
776    p += r;
777
778    r = vint_read(p, end, error_code);
779    if (r < 0)
780        return r;
781    p += r;
782
783    return p - buf;
784}
785
786
787static int
788ietf_v1_gen_stop_sending_frame (unsigned char *buf, size_t len,
789                            lsquic_stream_id_t stream_id, uint64_t error_code)
790{
791    return ietf_v1_gen_two_varints(buf, len, 0x05, (uint64_t[]){ stream_id,
792                                                                error_code, });
793}
794
795
796static unsigned
797ietf_v1_stop_sending_frame_size (lsquic_stream_id_t val, uint64_t error_code)
798{
799    return 1 + vint_size(val) + vint_size(error_code);
800}
801
802
803static int
804ietf_v1_parse_new_token_frame (const unsigned char *buf, size_t buf_len,
805                            const unsigned char **token, size_t *token_size_p)
806{
807    uint64_t token_size;
808    const unsigned char *p = buf + 1;
809    const unsigned char *const end = buf + buf_len;
810    int r;
811
812    r = vint_read(p, end, &token_size);
813    if (r < 0)
814        return r;
815    p += r;
816
817    if (p + token_size > end)
818        return -1;
819    *token = p;
820    p += token_size;
821    *token_size_p = token_size;
822
823    return p - buf;
824}
825
826
827static int
828ietf_v1_gen_ping_frame (unsigned char *buf, int buf_len)
829{
830    if (buf_len > 0)
831    {
832        buf[0] = 0x01;
833        return 1;
834    }
835    else
836        return -1;
837}
838
839
840static int
841ietf_v1_gen_connect_close_frame (unsigned char *buf, size_t buf_len,
842    int app_error, unsigned error_code, const char *reason, int reason_len)
843{
844    size_t needed;
845    unsigned bits_error, bits_reason;
846    unsigned char *p;
847
848    assert(!!reason == !!reason_len);
849
850    bits_reason = vint_val2bits(reason_len);
851    bits_error = vint_val2bits(error_code);
852    needed = 1 /* Type */ + (1 << bits_error)
853           + (app_error ? 0 : 1) /* Frame type */
854        /* TODO: frame type instead of just zero */
855           + (1 << bits_reason) + reason_len;
856
857    if (buf_len < needed)
858        return -1;
859
860    p = buf;
861    *p = 0x1C + !!app_error;
862    ++p;
863    vint_write(p, error_code, bits_error, 1 << bits_error);
864    p += 1 << bits_error;
865    if (!app_error)
866        *p++ = 0;   /* Frame type */ /* TODO */
867    vint_write(p, reason_len, bits_reason, 1 << bits_reason);
868    p += 1 << bits_reason;
869    if (reason_len)
870    {
871        memcpy(p, reason, reason_len);
872        p += reason_len;
873    }
874
875    assert((unsigned) (p - buf) == needed);
876    return p - buf;
877}
878
879
880static int
881ietf_v1_parse_connect_close_frame (const unsigned char *buf, size_t buf_len,
882        int *app_error_p, uint64_t *error_code, uint16_t *reason_len,
883        uint8_t *reason_offset)
884{
885    const unsigned char *const pend = buf + buf_len;
886    const unsigned char *p = buf + 1;
887    uint64_t len;
888    ptrdiff_t off;
889    int app_error, r;
890
891    r = vint_read(p, pend, error_code);
892    if (r < 0)
893        return -1;
894    p += r;
895
896    app_error = buf[0] == 0x1D;
897    if (!app_error)
898    {
899        r = vint_read(p, pend, &len);
900        if (r < 0)
901            return -1;
902        p += r;
903    }
904
905    r = vint_read(p, pend, &len);
906    if (r < 0)
907        return -1;
908    if (len > UINT16_MAX)
909        return -1;
910    p += r;
911
912    off = p - buf;
913    if (buf_len < off + len)
914        return -2;
915
916    *app_error_p = app_error;
917    *reason_len = len;
918    *reason_offset = off;
919    return off + len;
920}
921
922
923/* Returns number of bytes written or -1 on failure */
924/* This function makes an assumption that there is at least one range */
925static int
926ietf_v1_gen_ack_frame (unsigned char *outbuf, size_t outbuf_sz,
927        gaf_rechist_first_f rechist_first, gaf_rechist_next_f rechist_next,
928        gaf_rechist_largest_recv_f rechist_largest_recv,
929        void *rechist, lsquic_time_t now, int *has_missing,
930        lsquic_packno_t *largest_received, const uint64_t *ecn_counts)
931{
932    unsigned char *block_count_p, *p = outbuf;
933    unsigned char *const end = p + outbuf_sz;
934    lsquic_time_t time_diff;
935    lsquic_packno_t packno_diff, gap, prev_low, maxno, rsize;
936    size_t sz;
937    const struct lsquic_packno_range *range;
938    unsigned a, b, c, addl_ack_blocks, ecn_needs;
939    unsigned bits[4];
940    enum ecn ecn;
941
942#define AVAIL() (end - p)
943
944#define CHECKOUT(sz) do {                                               \
945    if ((intptr_t) (sz) > AVAIL()) {                                    \
946        errno = ENOBUFS;                                                \
947        return -1;                                                      \
948    }                                                                   \
949} while (0)
950
951    range = rechist_first(rechist);
952    if (!range)
953    {
954        errno = EINVAL;
955        return -1;
956    }
957    // LSQ_DEBUG("range [%"PRIu64" - %"PRIu64"]", range->high, range->low);
958
959    time_diff = now - rechist_largest_recv(rechist);
960    time_diff >>= TP_DEF_ACK_DELAY_EXP;
961
962    maxno = range->high;
963    packno_diff = maxno - range->low;
964
965    a = vint_val2bits(maxno);
966    b = vint_val2bits(time_diff);
967    c = vint_val2bits(packno_diff);
968    sz = 1          /* Type */
969       + (1 << a)   /* Largest Acknowledged */
970       + (1 << b)   /* ACK Delay */
971       + 1          /* ACK Block Count */
972       + (1 << c)   /* ACK Blocks */
973       ;
974
975    CHECKOUT(sz);
976
977    if (ecn_counts)
978    {
979        for (ecn = 1; ecn <= 3; ++ecn)
980            bits[ecn] = vint_val2bits(ecn_counts[ecn]);
981        ecn_needs = (1 << bits[1]) + (1 << bits[2]) + (1 << bits[3]);
982    }
983    else
984        ecn_needs = 0;
985
986    *p = 0x02 + !!ecn_counts;
987    ++p;
988
989    vint_write(p, maxno, a, 1 << a);
990    p += 1 << a;
991    vint_write(p, time_diff, b, 1 << b);
992    p += 1 << b;
993    block_count_p = p;
994    p += 1; /* Initial guess that we have fewer than 64 additional ACK Blocks */
995    vint_write(p, packno_diff, c, 1 << c);
996    p += 1 << c;
997
998    prev_low = range->low;
999    addl_ack_blocks = 0;
1000    while ((range = rechist_next(rechist)))
1001    {
1002        // LSQ_DEBUG("range [%"PRIu64" - %"PRIu64"]", range->high, range->low);
1003        gap = prev_low - range->high - 1;
1004        rsize = range->high - range->low;
1005        a = vint_val2bits(gap - 1);
1006        b = vint_val2bits(rsize);
1007        if (ecn_needs + (1 << a) + (1 << b) > AVAIL())
1008            break;
1009        if (addl_ack_blocks == VINT_MAX_ONE_BYTE)
1010        {
1011            memmove(block_count_p + 2, block_count_p + 1,
1012                                                p - block_count_p - 1);
1013            ++p;
1014        }
1015        vint_write(p, gap - 1, a, 1 << a);
1016        p += 1 << a;
1017        vint_write(p, rsize, b, 1 << b);
1018        p += 1 << b;
1019        ++addl_ack_blocks;
1020        prev_low = range->low;
1021    }
1022
1023    /* Here we assume that addl_ack_blocks < (1 << 14), which is a safe
1024     * assumption to make.
1025     */
1026    vint_write(block_count_p, addl_ack_blocks,
1027                        addl_ack_blocks > VINT_MAX_ONE_BYTE,
1028                        1 + (addl_ack_blocks > VINT_MAX_ONE_BYTE));
1029
1030    if (ecn_counts)
1031    {
1032        assert(ecn_needs <= AVAIL());
1033        for (ecn = 1; ecn <= 3; ++ecn)
1034        {
1035            vint_write(p, ecn_counts[ecnmap[ecn]], bits[ecnmap[ecn]], 1 << bits[ecnmap[ecn]]);
1036            p += 1 << bits[ecnmap[ecn]];
1037        }
1038    }
1039
1040    *has_missing = addl_ack_blocks > 0;
1041    *largest_received = maxno;
1042    return p - (unsigned char *) outbuf;
1043
1044#undef CHECKOUT
1045#undef AVAIL
1046}
1047
1048
1049static size_t
1050ietf_v1_calc_stream_frame_header_sz (lsquic_stream_id_t stream_id,
1051                                            uint64_t offset, unsigned data_sz)
1052{
1053    if (offset)
1054        return 1
1055            + (1 << vint_val2bits(stream_id))
1056            + (1 << vint_val2bits(data_sz))
1057            + (1 << vint_val2bits(offset));
1058    else
1059        return 1
1060            + (1 << vint_val2bits(data_sz))
1061            + (1 << vint_val2bits(stream_id));
1062}
1063
1064
1065/* [draft-ietf-quic-transport-24] Section 19.6 */
1066static size_t
1067ietf_v1_calc_crypto_frame_header_sz (uint64_t offset, unsigned data_sz)
1068{
1069    return 1    /* Frame type */
1070         + (1 << vint_val2bits(offset))
1071         + (1 << vint_val2bits(data_sz))
1072         ;
1073}
1074
1075
1076static enum quic_frame_type
1077ietf_v1_parse_frame_type (unsigned char byte)
1078{
1079    return lsquic_iquic_byte2type[byte];
1080}
1081
1082
1083static unsigned
1084ietf_v1_path_chal_frame_size (void)
1085{
1086    return 1 + sizeof(uint64_t);
1087}
1088
1089
1090static int
1091ietf_v1_gen_path_chal_frame (unsigned char *buf, size_t len, uint64_t chal)
1092{
1093    if (len >= 1 + sizeof(chal))
1094    {
1095        *buf = 0x1A;
1096        memcpy(buf + 1, &chal, sizeof(chal));
1097        return 1 + sizeof(chal);
1098    }
1099    else
1100        return -1;
1101}
1102
1103
1104static int
1105ietf_v1_parse_path_chal_frame (const unsigned char *buf, size_t len,
1106                                                            uint64_t *chal)
1107{
1108    if (len >= 9)
1109    {
1110        memcpy(chal, buf + 1, 8);
1111        return 9;
1112    }
1113    else
1114        return -1;
1115}
1116
1117
1118static unsigned
1119ietf_v1_path_resp_frame_size (void)
1120{
1121    return 1 + sizeof(uint64_t);
1122}
1123
1124
1125static int
1126ietf_v1_gen_path_resp_frame (unsigned char *buf, size_t len, uint64_t resp)
1127{
1128    if (len >= 1 + sizeof(resp))
1129    {
1130        *buf = 0x1B;
1131        memcpy(buf + 1, &resp, sizeof(resp));
1132        return 1 + sizeof(resp);
1133    }
1134    else
1135        return -1;
1136}
1137
1138
1139static int
1140ietf_v1_parse_path_resp_frame (const unsigned char *buf, size_t len,
1141                                                            uint64_t *resp)
1142{
1143    return ietf_v1_parse_path_chal_frame(buf, len, resp);
1144}
1145
1146
1147void
1148ietf_v1_turn_on_fin (unsigned char *stream_frame_header)
1149{
1150    *stream_frame_header |= 1;
1151}
1152
1153
1154static unsigned
1155ietf_v1_packno_bits2len (enum packno_bits bits)
1156{
1157    return iquic_packno_bits2len(bits);
1158}
1159
1160
1161static enum packno_bits
1162ietf_v1_calc_packno_bits (lsquic_packno_t packno,
1163                    lsquic_packno_t least_unacked, uint64_t n_in_flight)
1164{
1165    uint64_t delta;
1166    unsigned bits;
1167
1168    delta = packno - least_unacked;
1169    if (n_in_flight > delta)
1170        delta = n_in_flight;
1171
1172    delta *= 4;
1173    bits = (delta >= (1ULL <<  8))
1174         + (delta >= (1ULL << 16))
1175         + (delta >= (1ULL << 24))
1176         ;
1177
1178    return bits;
1179}
1180
1181
1182static int
1183ietf_v1_parse_one_varint (const unsigned char *buf, size_t len, uint64_t *val)
1184{
1185    int s;
1186
1187    s = vint_read(buf + 1, buf + len, val);
1188    if (s >= 0)
1189        return 1 + s;
1190    else
1191        return s;
1192}
1193
1194
1195static int
1196ietf_v1_gen_one_varint (unsigned char *buf, size_t len,
1197                                        unsigned char type, uint64_t val)
1198{
1199    unsigned vbits;
1200    unsigned char *p;
1201
1202    vbits = vint_val2bits(val);
1203
1204    if (1u + (1u << vbits) > len)
1205        return -1;
1206
1207    p = buf;
1208    *p++ = type;
1209    vint_write(p, val, vbits, 1 << vbits);
1210    p += 1 << vbits;
1211
1212    return p - buf;
1213}
1214
1215
1216static int
1217ietf_v1_gen_blocked_frame (unsigned char *buf, size_t buf_len, uint64_t off)
1218{
1219    return ietf_v1_gen_one_varint(buf, buf_len, 0x14, off);
1220}
1221
1222
1223static int
1224ietf_v1_parse_blocked_frame (const unsigned char *buf, size_t sz, uint64_t *off)
1225{
1226    return ietf_v1_parse_one_varint(buf, sz, off);
1227}
1228
1229
1230static unsigned
1231ietf_v1_blocked_frame_size (uint64_t off)
1232{
1233    return 1 + vint_size(off);
1234}
1235
1236
1237static int
1238ietf_v1_parse_max_data (const unsigned char *buf, size_t len, uint64_t *val)
1239{
1240    return ietf_v1_parse_one_varint(buf, len, val);
1241}
1242
1243
1244static int
1245ietf_v1_gen_max_data_frame (unsigned char *buf, size_t len, uint64_t val)
1246{
1247    return ietf_v1_gen_one_varint(buf, len, 0x10, val);
1248}
1249
1250
1251static unsigned
1252ietf_v1_max_data_frame_size (uint64_t val)
1253{
1254    return 1 + vint_size(val);
1255}
1256
1257
1258static int
1259ietf_v1_parse_retire_cid_frame (const unsigned char *buf, size_t len,
1260                                                                uint64_t *val)
1261{
1262    return ietf_v1_parse_one_varint(buf, len, val);
1263}
1264
1265
1266static int
1267ietf_v1_gen_retire_cid_frame (unsigned char *buf, size_t len, uint64_t val)
1268{
1269    return ietf_v1_gen_one_varint(buf, len, 0x19, val);
1270}
1271
1272
1273static size_t
1274ietf_v1_retire_cid_frame_size (uint64_t val)
1275{
1276    return 1 + vint_size(val);
1277}
1278
1279
1280static int
1281ietf_v1_parse_new_conn_id (const unsigned char *buf, size_t len,
1282                        uint64_t *seqno, uint64_t *retire_prior_to,
1283                        lsquic_cid_t *cid, const unsigned char **reset_token)
1284{
1285    const unsigned char *p = buf + 1;
1286    const unsigned char *const end = buf + len;
1287    unsigned char cid_len;
1288    int s;
1289
1290    s = vint_read(p, end, seqno);
1291    if (s < 0)
1292        return s;
1293    p += s;
1294
1295    s = vint_read(p, end, retire_prior_to);
1296    if (s < 0)
1297        return s;
1298    p += s;
1299
1300    if (p >= end)
1301        return -1;
1302
1303    cid_len = *p++;
1304    if (cid_len == 0 || cid_len > MAX_CID_LEN)
1305        return -2;
1306
1307    if ((unsigned) (end - p) < cid_len + IQUIC_SRESET_TOKEN_SZ)
1308        return -1;
1309    cid->len = cid_len;
1310    memcpy(cid->idbuf, p, cid_len);
1311    p += cid_len;
1312    if (reset_token)
1313        *reset_token = p;
1314    p += IQUIC_SRESET_TOKEN_SZ;
1315
1316    return p - buf;
1317}
1318
1319
1320/* Size of a frame that contains two varints */
1321static unsigned
1322ietf_v1_two_varints_size (uint64_t vals[2])
1323{
1324    unsigned vbits[2];
1325
1326    vbits[0] = vint_val2bits(vals[0]);
1327    vbits[1] = vint_val2bits(vals[1]);
1328    return 1u + (1u << vbits[0]) + (1u << vbits[1]);
1329}
1330
1331
1332static int
1333ietf_v1_gen_two_varints (unsigned char *buf, size_t len,
1334                                    unsigned char type, uint64_t vals[2])
1335{
1336    unsigned vbits[2];
1337    unsigned char *p;
1338
1339    vbits[0] = vint_val2bits(vals[0]);
1340    vbits[1] = vint_val2bits(vals[1]);
1341
1342    if (1u + (1u << vbits[0]) + (1u << vbits[1]) > len)
1343        return -1;
1344
1345    p = buf;
1346    *p++ = type;
1347    vint_write(p, vals[0], vbits[0], 1 << vbits[0]);
1348    p += 1 << vbits[0];
1349    vint_write(p, vals[1], vbits[1], 1 << vbits[1]);
1350    p += 1 << vbits[1];
1351
1352    return p - buf;
1353}
1354
1355
1356static int
1357ietf_v1_parse_two_varints (const unsigned char *buf, size_t len, uint64_t *vals[2])
1358{
1359    const unsigned char *p = buf;
1360    const unsigned char *const end = p + len;
1361    int s;
1362
1363    if (len < 2)
1364        return -1;
1365
1366    ++p;    /* Type */
1367
1368    s = vint_read(p, end, vals[0]);
1369    if (s < 0)
1370        return s;
1371    p += s;
1372
1373    s = vint_read(p, end, vals[1]);
1374    if (s < 0)
1375        return s;
1376    p += s;
1377
1378    return p - buf;
1379}
1380
1381
1382static int
1383ietf_v1_parse_stream_blocked_frame (const unsigned char *buf, size_t len,
1384                            lsquic_stream_id_t *stream_id, uint64_t *offset)
1385{
1386    return ietf_v1_parse_two_varints(buf, len,
1387                                       (uint64_t *[]) { stream_id, offset, });
1388}
1389
1390
1391static unsigned
1392ietf_v1_stream_blocked_frame_size (lsquic_stream_id_t stream_id, uint64_t off)
1393{
1394    return ietf_v1_two_varints_size((uint64_t []) { stream_id, off, });
1395}
1396
1397
1398static int
1399ietf_v1_gen_streams_blocked_frame (unsigned char *buf, size_t len,
1400                                    enum stream_dir sd, uint64_t limit)
1401{
1402    return ietf_v1_gen_one_varint(buf, len, 0x16 + (sd == SD_UNI), limit);
1403}
1404
1405
1406static int
1407ietf_v1_parse_streams_blocked_frame (const unsigned char *buf, size_t len,
1408                                    enum stream_dir *sd, uint64_t *limit)
1409{
1410    int s;
1411
1412    s = ietf_v1_parse_one_varint(buf, len, limit);
1413    if (s > 0)
1414    {
1415        if (buf[0] == 0x16)
1416            *sd = SD_BIDI;
1417        else
1418            *sd = SD_UNI;
1419    }
1420    return s;
1421}
1422
1423
1424static unsigned
1425ietf_v1_streams_blocked_frame_size (uint64_t limit)
1426{
1427    return 1 + vint_size(limit);
1428}
1429
1430
1431static int
1432ietf_v1_gen_stream_blocked_frame (unsigned char *buf, size_t len,
1433                                    lsquic_stream_id_t stream_id, uint64_t off)
1434{
1435    return ietf_v1_gen_two_varints(buf, len, 0x15, (uint64_t[]){ stream_id, off, });
1436}
1437
1438
1439static int
1440ietf_v1_gen_max_stream_data_frame (unsigned char *buf, size_t len,
1441                                    lsquic_stream_id_t stream_id, uint64_t off)
1442{
1443    return ietf_v1_gen_two_varints(buf, len, 0x11, (uint64_t[]){ stream_id, off, });
1444}
1445
1446
1447static unsigned
1448ietf_v1_max_stream_data_frame_size (lsquic_stream_id_t stream_id, uint64_t off)
1449{
1450    return ietf_v1_two_varints_size((uint64_t []) { stream_id, off, });
1451}
1452
1453
1454
1455static int
1456ietf_v1_parse_max_stream_data_frame (const unsigned char *buf, size_t len,
1457                                lsquic_stream_id_t *stream_id, uint64_t *off)
1458{
1459    return ietf_v1_parse_two_varints(buf, len, (uint64_t *[]){ stream_id, off, });
1460}
1461
1462
1463static int
1464ietf_v1_parse_max_streams_frame (const unsigned char *buf, size_t len,
1465                                    enum stream_dir *sd, uint64_t *max_streams)
1466{
1467    int s;
1468
1469    s = ietf_v1_parse_one_varint(buf, len, max_streams);
1470    if (s > 0)
1471        *sd = buf[0] == 0x12 ? SD_BIDI : SD_UNI;
1472    return s;
1473}
1474
1475
1476static int
1477ietf_v1_gen_max_streams_frame (unsigned char *buf, size_t len,
1478                                    enum stream_dir sd, uint64_t limit)
1479{
1480    return ietf_v1_gen_one_varint(buf, len, 0x12 + (sd == SD_UNI), limit);
1481}
1482
1483
1484static unsigned
1485ietf_v1_max_streams_frame_size (uint64_t limit)
1486{
1487    return 1 + vint_size(limit);
1488}
1489
1490
1491static size_t
1492ietf_v1_new_token_frame_size (size_t token_sz)
1493{
1494    unsigned bits;
1495
1496    bits = vint_val2bits(token_sz);
1497    return 1 + (1 << bits) + token_sz;
1498}
1499
1500
1501int
1502ietf_v1_gen_new_token_frame (unsigned char *buf, size_t buf_sz,
1503                                const unsigned char *token, size_t token_sz)
1504{
1505    unsigned char *p;
1506    unsigned bits;
1507
1508    bits = vint_val2bits(token_sz);
1509    if (buf_sz < 1 + (1 << bits) + token_sz)
1510    {
1511        errno = ENOBUFS;
1512        return -1;
1513    }
1514
1515    p = buf;
1516    *p++ = 0x07;
1517    vint_write(p, token_sz, bits, 1 << bits);
1518    p += 1 << bits;
1519    memcpy(p, token, token_sz);
1520    p += token_sz;
1521
1522    return p - buf;
1523}
1524
1525
1526static size_t
1527ietf_v1_new_connection_id_frame_size (unsigned seqno, unsigned scid_len)
1528{
1529    unsigned bits;
1530
1531    bits = vint_val2bits(seqno);
1532    return 1                /* Frame Type */
1533         + (1 << bits)      /* Sequence Number */
1534         + 1                /* Retire Prior To (we always set it to zero */
1535         + 1                /* CID length */
1536         + scid_len
1537         + IQUIC_SRESET_TOKEN_SZ;
1538}
1539
1540
1541int
1542ietf_v1_gen_new_connection_id_frame (unsigned char *buf, size_t buf_sz,
1543            unsigned seqno, const struct lsquic_cid *cid,
1544            const unsigned char *token, size_t token_sz)
1545{
1546    unsigned char *p;
1547    unsigned bits;
1548
1549    if (buf_sz < ietf_v1_new_connection_id_frame_size(seqno, cid->len))
1550        return -1;
1551
1552    p = buf;
1553    *p++ = 0x18;
1554    bits = vint_val2bits(seqno);
1555    vint_write(p, seqno, bits, 1 << bits);
1556    p += 1 << bits;
1557    *p++ = 0;   /* Retire Prior To */
1558    *p++ = cid->len;
1559    memcpy(p, cid->idbuf, cid->len);
1560    p += cid->len;
1561    memcpy(p, token, token_sz);
1562    p += token_sz;
1563
1564    return p - buf;
1565}
1566
1567
1568/* [draft-ietf-quic-transport-17] Section-17.2 */
1569static const enum header_type bits2ht[4] =
1570{
1571    [0] = HETY_INITIAL,
1572    [1] = HETY_0RTT,
1573    [2] = HETY_HANDSHAKE,
1574    [3] = HETY_RETRY,
1575};
1576
1577
1578int
1579lsquic_ietf_v1_parse_packet_in_long_begin (struct lsquic_packet_in *packet_in,
1580                size_t length, int is_server, unsigned cid_len,
1581                struct packin_parse_state *state)
1582{
1583    const unsigned char *p = packet_in->pi_data;
1584    const unsigned char *const end = p + length;
1585    lsquic_ver_tag_t tag;
1586    enum header_type header_type;
1587    unsigned dcil, scil, odcil;
1588    int verneg, r;
1589    unsigned char first_byte;
1590    uint64_t payload_len, token_len;
1591
1592    if (length < 6)
1593        return -1;
1594    first_byte = *p++;
1595
1596    memcpy(&tag, p, 4);
1597    p += 4;
1598    verneg = 0 == tag;
1599    if (!verneg)
1600        header_type = bits2ht[ (first_byte >> 4) & 3 ];
1601    else
1602        header_type = HETY_VERNEG;
1603
1604    packet_in->pi_header_type = header_type;
1605
1606    dcil = *p++;
1607    if (p + dcil >= end || dcil > MAX_CID_LEN)
1608        return -1;
1609    if (dcil)
1610    {
1611        memcpy(packet_in->pi_dcid.idbuf, p, dcil);
1612        packet_in->pi_flags |= PI_CONN_ID;
1613        p += dcil;
1614    }
1615    packet_in->pi_dcid.len = dcil;
1616
1617    scil = *p++;
1618    if (p + scil > end || scil > MAX_CID_LEN)
1619        return -1;
1620    if (scil)
1621    {
1622        packet_in->pi_scid_off = p - packet_in->pi_data;
1623        p += scil;
1624    }
1625    packet_in->pi_scid_len = scil;
1626
1627    switch (header_type)
1628    {
1629    case HETY_INITIAL:
1630        if (dcil < MIN_INITIAL_DCID_LEN)
1631            return -1;
1632        r = vint_read(p, end, &token_len);
1633        if (r < 0)
1634            return -1;
1635        if (token_len && !is_server)
1636        {
1637            /* From [draft-ietf-quic-transport-14]:
1638             *
1639             *  Token Length:  A variable-length integer specifying the
1640             *  length of the Token field, in bytes.  This value is zero
1641             *  if no token is present.  Initial packets sent by the
1642             *  server MUST set the Token Length field to zero; clients
1643             *  that receive an Initial packet with a non-zero Token
1644             *  Length field MUST either discard the packet or generate
1645             *  a connection error of type PROTOCOL_VIOLATION.
1646             */
1647            return -1;
1648        }
1649        p += r;
1650        if (token_len)
1651        {
1652            if (token_len >=
1653                        1ull << (sizeof(packet_in->pi_token_size) * 8))
1654                return -1;
1655            if (p + token_len > end)
1656                return -1;
1657            packet_in->pi_token = p - packet_in->pi_data;
1658            packet_in->pi_token_size = token_len;
1659            p += token_len;
1660        }
1661        /* fall-through */
1662    case HETY_HANDSHAKE:
1663    case HETY_0RTT:
1664        if (p >= end)
1665            return -1;
1666        r = vint_read(p, end, &payload_len);
1667        if (r < 0)
1668            return -1;
1669        p += r;
1670        if (p - packet_in->pi_data + payload_len > length)
1671            return -1;
1672        length = p - packet_in->pi_data + payload_len;
1673        if (end - p < 4)
1674            return -1;
1675        state->pps_p      = p - r;
1676        state->pps_nbytes = r;
1677        packet_in->pi_quic_ver = 1;
1678        break;
1679    case HETY_RETRY:
1680        if (p >= end)
1681            return -1;
1682        odcil = *p++;
1683        if (p + odcil > end || odcil > MAX_CID_LEN)
1684            return -1;
1685        packet_in->pi_odcid_len = odcil;
1686        packet_in->pi_odcid = p - packet_in->pi_data;
1687        p += odcil;
1688        packet_in->pi_token = p - packet_in->pi_data;
1689        packet_in->pi_token_size = end - p;
1690        p = end;
1691        length = end - packet_in->pi_data;
1692        state->pps_p      = NULL;
1693        state->pps_nbytes = 0;
1694        packet_in->pi_quic_ver = 1;
1695        break;
1696    default:
1697        assert(header_type == HETY_VERNEG);
1698        if (p >= end || (3 & (uintptr_t) (end - p)))
1699            return -1;
1700        packet_in->pi_quic_ver = p - packet_in->pi_data;
1701        p = end;
1702        state->pps_p      = NULL;
1703        state->pps_nbytes = 0;
1704        break;
1705    }
1706
1707    packet_in->pi_header_sz     = p - packet_in->pi_data;
1708    packet_in->pi_data_sz       = length;
1709    packet_in->pi_nonce         = 0;
1710    packet_in->pi_refcnt        = 0;
1711    packet_in->pi_frame_types   = 0;
1712    memset(&packet_in->pi_next, 0, sizeof(packet_in->pi_next));
1713    packet_in->pi_refcnt        = 0;
1714    packet_in->pi_received      = 0;
1715
1716    /* Packet number is set to an invalid value.  The packet number must
1717     * be decrypted, which happens later.
1718     */
1719    packet_in->pi_packno        = 1ULL << 62;
1720
1721    return 0;
1722}
1723
1724
1725/* Is this a valid Initial packet?  We take the perspective of the server. */
1726int
1727lsquic_is_valid_ietf_v1_or_Q046plus_hs_packet (const unsigned char *buf,
1728                                        size_t length, lsquic_ver_tag_t *tagp)
1729{
1730    const unsigned char *p = buf;
1731    const unsigned char *const end = p + length;
1732    lsquic_ver_tag_t tag;
1733    enum header_type header_type;
1734    unsigned dcil, scil;
1735    int r;
1736    unsigned char first_byte;
1737    uint64_t payload_len, token_len, packet_len;
1738
1739    if (length < 6)
1740        return 0;
1741    first_byte = *p++;
1742
1743    header_type = bits2ht[ (first_byte >> 4) & 3 ];
1744    if (header_type != HETY_INITIAL)
1745        return 0;
1746
1747    memcpy(&tag, p, 4);
1748    p += 4;
1749    switch (tag)
1750    {
1751    case 0:
1752        return 0;       /* Client never sends version negotiation packets */
1753    case TAG('Q', '0', '4', '6'):
1754        dcil = p[0] >> 4;
1755        if (dcil)
1756            dcil += 3;
1757        scil = p[0] & 0xF;
1758        if (scil)
1759            scil += 3;
1760        ++p;
1761
1762        if (!(dcil == GQUIC_CID_LEN && scil == 0))
1763            return 0;
1764
1765        packet_len = first_byte & 3;
1766
1767        if (end - p < (ptrdiff_t) (dcil + scil + packet_len))
1768            return 0;
1769        break;
1770    case TAG('Q', '0', '5', '0'):
1771        dcil = *p++;
1772        if (dcil != 8)
1773            return 0;
1774        if (p + dcil + 1 >= end)
1775            return 0;
1776        p += dcil;
1777        scil = *p++;
1778        if (scil != 0)
1779            return 0;
1780        goto read_token;
1781    default:
1782        dcil = *p++;
1783        if (dcil < MIN_INITIAL_DCID_LEN || dcil > MAX_CID_LEN)
1784            return 0;
1785        if (p + dcil >= end)
1786            return 0;
1787        p += dcil;
1788        scil = *p++;
1789        if (p + scil > end || scil > MAX_CID_LEN)
1790            return 0;
1791        p += scil;
1792  read_token:
1793        r = vint_read(p, end, &token_len);
1794        if (r < 0)
1795            return 0;
1796        p += r;
1797        p += token_len;
1798        if (p >= end)
1799            return 0;
1800        r = vint_read(p, end, &payload_len);
1801        if (r < 0)
1802            return 0;
1803        p += r;
1804        if (p - buf + payload_len > length)
1805            return 0;
1806        if (end - p < 4)
1807            return 0;
1808    }
1809
1810    *tagp = tag;
1811    return 1;
1812}
1813
1814
1815int
1816lsquic_ietf_v1_parse_packet_in_short_begin (struct lsquic_packet_in *packet_in,
1817                size_t length, int is_server, unsigned cid_len,
1818                struct packin_parse_state *state)
1819{
1820    unsigned char byte;
1821    unsigned header_sz;
1822
1823    /* By the time this function has been called, we know length is non-zero */
1824    byte = packet_in->pi_data[0];
1825
1826    /* [draft-ietf-quic-transport-17] Section 17.3 */
1827    /* 01SRRKPP */
1828
1829    if (cid_len)
1830    {
1831        header_sz = 1 + cid_len;
1832        if (length < header_sz)
1833            return -1;
1834        memcpy(packet_in->pi_dcid.idbuf, packet_in->pi_data + 1, cid_len);
1835        packet_in->pi_dcid.len = cid_len;
1836        packet_in->pi_flags |= PI_CONN_ID;
1837    }
1838    else
1839        header_sz = 1;
1840
1841    packet_in->pi_flags |= ((byte & 0x20) > 0) << PIBIT_SPIN_SHIFT;
1842    packet_in->pi_flags |= (byte & 3) << PIBIT_BITS_SHIFT;
1843
1844    packet_in->pi_header_sz     = header_sz;
1845    packet_in->pi_data_sz       = length;
1846    packet_in->pi_quic_ver      = 0;
1847    packet_in->pi_nonce         = 0;
1848    packet_in->pi_refcnt        = 0;
1849    packet_in->pi_frame_types   = 0;
1850    memset(&packet_in->pi_next, 0, sizeof(packet_in->pi_next));
1851    packet_in->pi_refcnt        = 0;
1852    packet_in->pi_received      = 0;
1853
1854    /* This is so that Q046 works, ID-18 code does not use it */
1855    state->pps_p                = packet_in->pi_data + header_sz;
1856    state->pps_nbytes           = 1 + (byte & 3);
1857
1858    return 0;
1859}
1860
1861
1862#if __GNUC__
1863#   define popcount __builtin_popcount
1864#else
1865static int
1866popcount (unsigned v)
1867{
1868    int count, i;
1869    for (i = 0, count = 0; i < sizeof(v) * 8; ++i)
1870        if (v & (1 << i))
1871            ++count;
1872    return count;
1873}
1874#endif
1875
1876
1877int
1878lsquic_ietf_v1_gen_ver_nego_pkt (unsigned char *buf, size_t bufsz,
1879         const lsquic_cid_t *scid, const lsquic_cid_t *dcid, unsigned versions,
1880         uint8_t rand)
1881{
1882    size_t need;
1883    int r;
1884
1885    need = 1 /* Type */ + 4 /* Version */ + 1 /* DCIL */
1886                + dcid->len + 1 /* SCIL */ + scid->len + popcount(versions) * 4;
1887
1888    if (need > bufsz)
1889        return -1;
1890
1891    *buf++ = 0x80 | 0x40 | rand;
1892    memset(buf, 0, 4);
1893    buf += 4;
1894
1895    /* From [draft-ietf-quic-transport-22], Section 17.2.1:
1896     *
1897     *  The server MUST include the value from the Source Connection ID field
1898     *  of the packet it receives in the Destination Connection ID field.
1899     *  The value for Source Connection ID MUST be copied from the
1900     *  Destination Connection ID of the received packet, which is initially
1901     *  randomly selected by a client.  Echoing both connection IDs gives
1902     *  clients some assurance that the server received the packet and that
1903     *  the Version Negotiation packet was not generated by an off-path
1904     *  attacker.
1905     */
1906
1907    *buf++ = dcid->len;
1908    memcpy(buf, dcid->idbuf, dcid->len);
1909    buf += dcid->len;
1910    *buf++ = scid->len;
1911    memcpy(buf, scid->idbuf, scid->len);
1912    buf += scid->len;
1913
1914    r = lsquic_gen_ver_tags(buf, bufsz - 1 - 4 - 2 - dcid->len - scid->len,
1915                                                                    versions);
1916    if (r < 0)
1917        return -1;
1918    assert((unsigned) r == popcount(versions) * 4u);
1919
1920    return need;
1921}
1922
1923
1924
1925
1926const struct parse_funcs lsquic_parse_funcs_ietf_v1 =
1927{
1928    .pf_gen_reg_pkt_header            =  ietf_v1_gen_reg_pkt_header,
1929    .pf_parse_packet_in_finish        =  ietf_v1_parse_packet_in_finish,
1930    .pf_gen_stream_frame              =  ietf_v1_gen_stream_frame,
1931    .pf_calc_stream_frame_header_sz   =  ietf_v1_calc_stream_frame_header_sz,
1932    .pf_parse_stream_frame            =  ietf_v1_parse_stream_frame,
1933    .pf_parse_ack_frame               =  ietf_v1_parse_ack_frame,
1934    .pf_gen_ack_frame                 =  ietf_v1_gen_ack_frame,
1935    .pf_gen_blocked_frame             =  ietf_v1_gen_blocked_frame,
1936    .pf_parse_blocked_frame           =  ietf_v1_parse_blocked_frame,
1937    .pf_blocked_frame_size            =  ietf_v1_blocked_frame_size,
1938    .pf_rst_frame_size                =  ietf_v1_rst_frame_size,
1939    .pf_gen_rst_frame                 =  ietf_v1_gen_rst_frame,
1940    .pf_parse_rst_frame               =  ietf_v1_parse_rst_frame,
1941    .pf_gen_connect_close_frame       =  ietf_v1_gen_connect_close_frame,
1942    .pf_parse_connect_close_frame     =  ietf_v1_parse_connect_close_frame,
1943    .pf_gen_ping_frame                =  ietf_v1_gen_ping_frame,
1944    .pf_parse_frame_type              =  ietf_v1_parse_frame_type,
1945    .pf_turn_on_fin                   =  ietf_v1_turn_on_fin,
1946    .pf_packout_size                  =  ietf_v1_packout_size,
1947    .pf_packout_max_header_size       =  ietf_v1_packout_max_header_size,
1948    .pf_path_chal_frame_size          =  ietf_v1_path_chal_frame_size,
1949    .pf_parse_path_chal_frame         =  ietf_v1_parse_path_chal_frame,
1950    .pf_gen_path_chal_frame           =  ietf_v1_gen_path_chal_frame,
1951    .pf_path_resp_frame_size          =  ietf_v1_path_resp_frame_size,
1952    .pf_gen_path_resp_frame           =  ietf_v1_gen_path_resp_frame,
1953    .pf_parse_path_resp_frame         =  ietf_v1_parse_path_resp_frame,
1954    .pf_calc_packno_bits              =  ietf_v1_calc_packno_bits,
1955    .pf_packno_bits2len               =  ietf_v1_packno_bits2len,
1956    .pf_packno_info                   =  ietf_v1_packno_info,
1957    .pf_gen_crypto_frame              =  ietf_v1_gen_crypto_frame,
1958    .pf_parse_crypto_frame            =  ietf_v1_parse_crypto_frame,
1959    .pf_calc_crypto_frame_header_sz   =  ietf_v1_calc_crypto_frame_header_sz,
1960    .pf_parse_max_data                =  ietf_v1_parse_max_data,
1961    .pf_gen_max_data_frame            =  ietf_v1_gen_max_data_frame,
1962    .pf_max_data_frame_size           =  ietf_v1_max_data_frame_size,
1963    .pf_parse_new_conn_id             =  ietf_v1_parse_new_conn_id,
1964    .pf_gen_stream_blocked_frame      =  ietf_v1_gen_stream_blocked_frame,
1965    .pf_parse_stream_blocked_frame    =  ietf_v1_parse_stream_blocked_frame,
1966    .pf_stream_blocked_frame_size     =  ietf_v1_stream_blocked_frame_size,
1967    .pf_gen_max_stream_data_frame     =  ietf_v1_gen_max_stream_data_frame,
1968    .pf_parse_max_stream_data_frame   =  ietf_v1_parse_max_stream_data_frame,
1969    .pf_max_stream_data_frame_size    =  ietf_v1_max_stream_data_frame_size,
1970    .pf_parse_stop_sending_frame      =  ietf_v1_parse_stop_sending_frame,
1971    .pf_gen_stop_sending_frame        =  ietf_v1_gen_stop_sending_frame,
1972    .pf_stop_sending_frame_size       =  ietf_v1_stop_sending_frame_size,
1973    .pf_parse_new_token_frame         =  ietf_v1_parse_new_token_frame,
1974    .pf_new_connection_id_frame_size  =  ietf_v1_new_connection_id_frame_size,
1975    .pf_gen_new_connection_id_frame   =  ietf_v1_gen_new_connection_id_frame,
1976    .pf_new_token_frame_size          =  ietf_v1_new_token_frame_size,
1977    .pf_gen_new_token_frame           =  ietf_v1_gen_new_token_frame,
1978    .pf_parse_retire_cid_frame        =  ietf_v1_parse_retire_cid_frame,
1979    .pf_gen_retire_cid_frame          =  ietf_v1_gen_retire_cid_frame,
1980    .pf_retire_cid_frame_size         =  ietf_v1_retire_cid_frame_size,
1981    .pf_gen_streams_blocked_frame     =  ietf_v1_gen_streams_blocked_frame,
1982    .pf_parse_streams_blocked_frame   =  ietf_v1_parse_streams_blocked_frame,
1983    .pf_streams_blocked_frame_size    =  ietf_v1_streams_blocked_frame_size,
1984    .pf_gen_max_streams_frame         =  ietf_v1_gen_max_streams_frame,
1985    .pf_parse_max_streams_frame       =  ietf_v1_parse_max_streams_frame,
1986    .pf_max_streams_frame_size        =  ietf_v1_max_streams_frame_size,
1987};
1988