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