lsquic_parse_ietf_v1.c revision 03e6b668
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;
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    *p = 0x02 + !!ecn_counts;
958    ++p;
959
960    vint_write(p, maxno, a, 1 << a);
961    p += 1 << a;
962    vint_write(p, time_diff, b, 1 << b);
963    p += 1 << b;
964    block_count_p = p;
965    p += 1; /* Initial guess that we have fewer than 64 additional ACK Blocks */
966    vint_write(p, packno_diff, c, 1 << c);
967    p += 1 << c;
968
969    prev_low = range->low;
970    addl_ack_blocks = 0;
971    while ((range = rechist_next(rechist)))
972    {
973        // LSQ_DEBUG("range [%"PRIu64" - %"PRIu64"]", range->high, range->low);
974        gap = prev_low - range->high - 1;
975        rsize = range->high - range->low;
976        a = vint_val2bits(gap - 1);
977        b = vint_val2bits(rsize);
978        if (addl_ack_blocks == VINT_MAX_ONE_BYTE)
979        {
980            memmove(block_count_p + 2, block_count_p + 1,
981                                                p - block_count_p - 1);
982            ++p;
983        }
984        CHECKOUT((1 << a) + (1 << b));
985        vint_write(p, gap - 1, a, 1 << a);
986        p += 1 << a;
987        vint_write(p, rsize, b, 1 << b);
988        p += 1 << b;
989        ++addl_ack_blocks;
990        prev_low = range->low;
991    }
992
993    /* Here we assume that addl_ack_blocks < (1 << 14), which is a safe
994     * assumption to make.
995     */
996    vint_write(block_count_p, addl_ack_blocks,
997                        addl_ack_blocks > VINT_MAX_ONE_BYTE,
998                        1 + (addl_ack_blocks > VINT_MAX_ONE_BYTE));
999
1000    if (ecn_counts)
1001    {
1002        for (ecn = 1; ecn <= 3; ++ecn)
1003            bits[ecn] = vint_val2bits(ecn_counts[ecn]);
1004        CHECKOUT((1 << bits[1]) + (1 << bits[2]) + (1 << bits[3]));
1005        for (ecn = 1; ecn <= 3; ++ecn)
1006        {
1007            vint_write(p, ecn_counts[ecnmap[ecn]], bits[ecnmap[ecn]], 1 << bits[ecnmap[ecn]]);
1008            p += 1 << bits[ecnmap[ecn]];
1009        }
1010    }
1011
1012    *has_missing = addl_ack_blocks > 0;
1013    *largest_received = maxno;
1014    return p - (unsigned char *) outbuf;
1015
1016#undef CHECKOUT
1017#undef AVAIL
1018}
1019
1020
1021static size_t
1022ietf_v1_calc_stream_frame_header_sz (lsquic_stream_id_t stream_id,
1023                                            uint64_t offset, unsigned data_sz)
1024{
1025    if (offset)
1026        return 1
1027            + (1 << vint_val2bits(stream_id))
1028            + (1 << vint_val2bits(data_sz))
1029            + (1 << vint_val2bits(offset));
1030    else
1031        return 1
1032            + (1 << vint_val2bits(data_sz))
1033            + (1 << vint_val2bits(stream_id));
1034}
1035
1036
1037static size_t
1038ietf_v1_calc_crypto_frame_header_sz (uint64_t offset)
1039{
1040    return 1    /* Frame type */
1041         + (1 << vint_val2bits(offset))
1042         + 1    /* Data len */
1043         ;
1044}
1045
1046
1047static enum quic_frame_type
1048ietf_v1_parse_frame_type (unsigned char byte)
1049{
1050    return lsquic_iquic_byte2type[byte];
1051}
1052
1053
1054static unsigned
1055ietf_v1_path_chal_frame_size (void)
1056{
1057    return 1 + sizeof(uint64_t);
1058}
1059
1060
1061static int
1062ietf_v1_gen_path_chal_frame (unsigned char *buf, size_t len, uint64_t chal)
1063{
1064    if (len >= 1 + sizeof(chal))
1065    {
1066        *buf = 0x1A;
1067        memcpy(buf + 1, &chal, sizeof(chal));
1068        return 1 + sizeof(chal);
1069    }
1070    else
1071        return -1;
1072}
1073
1074
1075static int
1076ietf_v1_parse_path_chal_frame (const unsigned char *buf, size_t len,
1077                                                            uint64_t *chal)
1078{
1079    if (len >= 9)
1080    {
1081        memcpy(chal, buf + 1, 8);
1082        return 9;
1083    }
1084    else
1085        return -1;
1086}
1087
1088
1089static unsigned
1090ietf_v1_path_resp_frame_size (void)
1091{
1092    return 1 + sizeof(uint64_t);
1093}
1094
1095
1096static int
1097ietf_v1_gen_path_resp_frame (unsigned char *buf, size_t len, uint64_t resp)
1098{
1099    if (len >= 1 + sizeof(resp))
1100    {
1101        *buf = 0x1B;
1102        memcpy(buf + 1, &resp, sizeof(resp));
1103        return 1 + sizeof(resp);
1104    }
1105    else
1106        return -1;
1107}
1108
1109
1110static int
1111ietf_v1_parse_path_resp_frame (const unsigned char *buf, size_t len,
1112                                                            uint64_t *resp)
1113{
1114    return ietf_v1_parse_path_chal_frame(buf, len, resp);
1115}
1116
1117
1118void
1119ietf_v1_turn_on_fin (unsigned char *stream_frame_header)
1120{
1121    *stream_frame_header |= 1;
1122}
1123
1124
1125static unsigned
1126ietf_v1_packno_bits2len (enum packno_bits bits)
1127{
1128    return iquic_packno_bits2len(bits);
1129}
1130
1131
1132static enum packno_bits
1133ietf_v1_calc_packno_bits (lsquic_packno_t packno,
1134                    lsquic_packno_t least_unacked, uint64_t n_in_flight)
1135{
1136    uint64_t delta;
1137    unsigned bits;
1138
1139    delta = packno - least_unacked;
1140    if (n_in_flight > delta)
1141        delta = n_in_flight;
1142
1143    delta *= 4;
1144    bits = (delta >= (1ULL <<  8))
1145         + (delta >= (1ULL << 16))
1146         + (delta >= (1ULL << 24))
1147         ;
1148
1149    return bits;
1150}
1151
1152
1153static int
1154ietf_v1_parse_one_varint (const unsigned char *buf, size_t len, uint64_t *val)
1155{
1156    int s;
1157
1158    s = vint_read(buf + 1, buf + len, val);
1159    if (s >= 0)
1160        return 1 + s;
1161    else
1162        return s;
1163}
1164
1165
1166static int
1167ietf_v1_gen_one_varint (unsigned char *buf, size_t len,
1168                                        unsigned char type, uint64_t val)
1169{
1170    unsigned vbits;
1171    unsigned char *p;
1172
1173    vbits = vint_val2bits(val);
1174
1175    if (1u + (1u << vbits) > len)
1176        return -1;
1177
1178    p = buf;
1179    *p++ = type;
1180    vint_write(p, val, vbits, 1 << vbits);
1181    p += 1 << vbits;
1182
1183    return p - buf;
1184}
1185
1186
1187static int
1188ietf_v1_gen_blocked_frame (unsigned char *buf, size_t buf_len, uint64_t off)
1189{
1190    return ietf_v1_gen_one_varint(buf, buf_len, 0x14, off);
1191}
1192
1193
1194static int
1195ietf_v1_parse_blocked_frame (const unsigned char *buf, size_t sz, uint64_t *off)
1196{
1197    return ietf_v1_parse_one_varint(buf, sz, off);
1198}
1199
1200
1201static unsigned
1202ietf_v1_blocked_frame_size (uint64_t off)
1203{
1204    return 1 + vint_size(off);
1205}
1206
1207
1208static int
1209ietf_v1_parse_max_data (const unsigned char *buf, size_t len, uint64_t *val)
1210{
1211    return ietf_v1_parse_one_varint(buf, len, val);
1212}
1213
1214
1215static int
1216ietf_v1_gen_max_data_frame (unsigned char *buf, size_t len, uint64_t val)
1217{
1218    return ietf_v1_gen_one_varint(buf, len, 0x10, val);
1219}
1220
1221
1222static unsigned
1223ietf_v1_max_data_frame_size (uint64_t val)
1224{
1225    return 1 + vint_size(val);
1226}
1227
1228
1229static int
1230ietf_v1_parse_retire_cid_frame (const unsigned char *buf, size_t len,
1231                                                                uint64_t *val)
1232{
1233    return ietf_v1_parse_one_varint(buf, len, val);
1234}
1235
1236
1237static int
1238ietf_v1_gen_retire_cid_frame (unsigned char *buf, size_t len, uint64_t val)
1239{
1240    return ietf_v1_gen_one_varint(buf, len, 0x19, val);
1241}
1242
1243
1244static size_t
1245ietf_v1_retire_cid_frame_size (uint64_t val)
1246{
1247    return 1 + vint_size(val);
1248}
1249
1250
1251static int
1252ietf_v1_parse_new_conn_id (const unsigned char *buf, size_t len,
1253                        uint64_t *seqno, uint64_t *retire_prior_to,
1254                        lsquic_cid_t *cid, const unsigned char **reset_token)
1255{
1256    const unsigned char *p = buf + 1;
1257    const unsigned char *const end = buf + len;
1258    unsigned char cid_len;
1259    int s;
1260
1261    s = vint_read(p, end, seqno);
1262    if (s < 0)
1263        return s;
1264    p += s;
1265
1266    s = vint_read(p, end, retire_prior_to);
1267    if (s < 0)
1268        return s;
1269    p += s;
1270
1271    if (p >= end)
1272        return -1;
1273
1274    cid_len = *p++;
1275    if (cid_len == 0 || cid_len > MAX_CID_LEN)
1276        return -2;
1277
1278    if ((unsigned) (end - p) < cid_len + IQUIC_SRESET_TOKEN_SZ)
1279        return -1;
1280    cid->len = cid_len;
1281    memcpy(cid->idbuf, p, cid_len);
1282    p += cid_len;
1283    if (reset_token)
1284        *reset_token = p;
1285    p += IQUIC_SRESET_TOKEN_SZ;
1286
1287    return p - buf;
1288}
1289
1290
1291/* Size of a frame that contains two varints */
1292static unsigned
1293ietf_v1_two_varints_size (uint64_t vals[2])
1294{
1295    unsigned vbits[2];
1296
1297    vbits[0] = vint_val2bits(vals[0]);
1298    vbits[1] = vint_val2bits(vals[1]);
1299    return 1u + (1u << vbits[0]) + (1u << vbits[1]);
1300}
1301
1302
1303static int
1304ietf_v1_gen_two_varints (unsigned char *buf, size_t len,
1305                                    unsigned char type, uint64_t vals[2])
1306{
1307    unsigned vbits[2];
1308    unsigned char *p;
1309
1310    vbits[0] = vint_val2bits(vals[0]);
1311    vbits[1] = vint_val2bits(vals[1]);
1312
1313    if (1u + (1u << vbits[0]) + (1u << vbits[1]) > len)
1314        return -1;
1315
1316    p = buf;
1317    *p++ = type;
1318    vint_write(p, vals[0], vbits[0], 1 << vbits[0]);
1319    p += 1 << vbits[0];
1320    vint_write(p, vals[1], vbits[1], 1 << vbits[1]);
1321    p += 1 << vbits[1];
1322
1323    return p - buf;
1324}
1325
1326
1327static int
1328ietf_v1_parse_two_varints (const unsigned char *buf, size_t len, uint64_t *vals[2])
1329{
1330    const unsigned char *p = buf;
1331    const unsigned char *const end = p + len;
1332    int s;
1333
1334    if (len < 2)
1335        return -1;
1336
1337    ++p;    /* Type */
1338
1339    s = vint_read(p, end, vals[0]);
1340    if (s < 0)
1341        return s;
1342    p += s;
1343
1344    s = vint_read(p, end, vals[1]);
1345    if (s < 0)
1346        return s;
1347    p += s;
1348
1349    return p - buf;
1350}
1351
1352
1353static int
1354ietf_v1_parse_stream_blocked_frame (const unsigned char *buf, size_t len,
1355                            lsquic_stream_id_t *stream_id, uint64_t *offset)
1356{
1357    return ietf_v1_parse_two_varints(buf, len,
1358                                       (uint64_t *[]) { stream_id, offset, });
1359}
1360
1361
1362static unsigned
1363ietf_v1_stream_blocked_frame_size (lsquic_stream_id_t stream_id, uint64_t off)
1364{
1365    return ietf_v1_two_varints_size((uint64_t []) { stream_id, off, });
1366}
1367
1368
1369static int
1370ietf_v1_gen_streams_blocked_frame (unsigned char *buf, size_t len,
1371                                    enum stream_dir sd, uint64_t limit)
1372{
1373    return ietf_v1_gen_one_varint(buf, len, 0x16 + (sd == SD_UNI), limit);
1374}
1375
1376
1377static int
1378ietf_v1_parse_streams_blocked_frame (const unsigned char *buf, size_t len,
1379                                    enum stream_dir *sd, uint64_t *limit)
1380{
1381    int s;
1382
1383    s = ietf_v1_parse_one_varint(buf, len, limit);
1384    if (s > 0)
1385    {
1386        if (buf[0] == 0x16)
1387            *sd = SD_BIDI;
1388        else
1389            *sd = SD_UNI;
1390    }
1391    return s;
1392}
1393
1394
1395static unsigned
1396ietf_v1_streams_blocked_frame_size (uint64_t limit)
1397{
1398    return 1 + vint_size(limit);
1399}
1400
1401
1402static int
1403ietf_v1_gen_stream_blocked_frame (unsigned char *buf, size_t len,
1404                                    lsquic_stream_id_t stream_id, uint64_t off)
1405{
1406    return ietf_v1_gen_two_varints(buf, len, 0x15, (uint64_t[]){ stream_id, off, });
1407}
1408
1409
1410static int
1411ietf_v1_gen_max_stream_data_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, 0x11, (uint64_t[]){ stream_id, off, });
1415}
1416
1417
1418static unsigned
1419ietf_v1_max_stream_data_frame_size (lsquic_stream_id_t stream_id, uint64_t off)
1420{
1421    return ietf_v1_two_varints_size((uint64_t []) { stream_id, off, });
1422}
1423
1424
1425
1426static int
1427ietf_v1_parse_max_stream_data_frame (const unsigned char *buf, size_t len,
1428                                lsquic_stream_id_t *stream_id, uint64_t *off)
1429{
1430    return ietf_v1_parse_two_varints(buf, len, (uint64_t *[]){ stream_id, off, });
1431}
1432
1433
1434static int
1435ietf_v1_parse_max_streams_frame (const unsigned char *buf, size_t len,
1436                                    enum stream_dir *sd, uint64_t *max_streams)
1437{
1438    int s;
1439
1440    s = ietf_v1_parse_one_varint(buf, len, max_streams);
1441    if (s > 0)
1442        *sd = buf[0] == 0x12 ? SD_BIDI : SD_UNI;
1443    return s;
1444}
1445
1446
1447static int
1448ietf_v1_gen_max_streams_frame (unsigned char *buf, size_t len,
1449                                    enum stream_dir sd, uint64_t limit)
1450{
1451    return ietf_v1_gen_one_varint(buf, len, 0x12 + (sd == SD_UNI), limit);
1452}
1453
1454
1455static unsigned
1456ietf_v1_max_streams_frame_size (uint64_t limit)
1457{
1458    return 1 + vint_size(limit);
1459}
1460
1461
1462static size_t
1463ietf_v1_new_token_frame_size (size_t token_sz)
1464{
1465    unsigned bits;
1466
1467    bits = vint_val2bits(token_sz);
1468    return 1 + (1 << bits) + token_sz;
1469}
1470
1471
1472int
1473ietf_v1_gen_new_token_frame (unsigned char *buf, size_t buf_sz,
1474                                const unsigned char *token, size_t token_sz)
1475{
1476    unsigned char *p;
1477    unsigned bits;
1478
1479    bits = vint_val2bits(token_sz);
1480    if (buf_sz < 1 + (1 << bits) + token_sz)
1481    {
1482        errno = ENOBUFS;
1483        return -1;
1484    }
1485
1486    p = buf;
1487    *p++ = 0x07;
1488    vint_write(p, token_sz, bits, 1 << bits);
1489    p += 1 << bits;
1490    memcpy(p, token, token_sz);
1491    p += token_sz;
1492
1493    return p - buf;
1494}
1495
1496
1497static size_t
1498ietf_v1_new_connection_id_frame_size (unsigned seqno, unsigned scid_len)
1499{
1500    unsigned bits;
1501
1502    bits = vint_val2bits(seqno);
1503    return 1                /* Frame Type */
1504         + (1 << bits)      /* Sequence Number */
1505         + 1                /* Retire Prior To (we always set it to zero */
1506         + 1                /* CID length */
1507         + scid_len
1508         + IQUIC_SRESET_TOKEN_SZ;
1509}
1510
1511
1512int
1513ietf_v1_gen_new_connection_id_frame (unsigned char *buf, size_t buf_sz,
1514            unsigned seqno, const struct lsquic_cid *cid,
1515            const unsigned char *token, size_t token_sz)
1516{
1517    unsigned char *p;
1518    unsigned bits;
1519
1520    if (buf_sz < ietf_v1_new_connection_id_frame_size(seqno, cid->len))
1521        return -1;
1522
1523    p = buf;
1524    *p++ = 0x18;
1525    bits = vint_val2bits(seqno);
1526    vint_write(p, seqno, bits, 1 << bits);
1527    p += 1 << bits;
1528    *p++ = 0;   /* Retire Prior To */
1529    *p++ = cid->len;
1530    memcpy(p, cid->idbuf, cid->len);
1531    p += cid->len;
1532    memcpy(p, token, token_sz);
1533    p += token_sz;
1534
1535    return p - buf;
1536}
1537
1538
1539/* [draft-ietf-quic-transport-17] Section-17.2 */
1540static const enum header_type bits2ht[4] =
1541{
1542    [0] = HETY_INITIAL,
1543    [1] = HETY_0RTT,
1544    [2] = HETY_HANDSHAKE,
1545    [3] = HETY_RETRY,
1546};
1547
1548
1549int
1550lsquic_ietf_v1_parse_packet_in_long_begin (struct lsquic_packet_in *packet_in,
1551                size_t length, int is_server, unsigned cid_len,
1552                struct packin_parse_state *state)
1553{
1554    const unsigned char *p = packet_in->pi_data;
1555    const unsigned char *const end = p + length;
1556    lsquic_ver_tag_t tag;
1557    enum header_type header_type;
1558    unsigned dcil, scil, odcil;
1559    int verneg, r;
1560    unsigned char first_byte;
1561    uint64_t payload_len, token_len;
1562
1563    if (length < 6)
1564        return -1;
1565    first_byte = *p++;
1566
1567    memcpy(&tag, p, 4);
1568    p += 4;
1569    verneg = 0 == tag;
1570    if (!verneg)
1571        header_type = bits2ht[ (first_byte >> 4) & 3 ];
1572    else
1573        header_type = HETY_VERNEG;
1574
1575    packet_in->pi_header_type = header_type;
1576
1577    dcil = *p++;
1578    if (p + dcil >= end || dcil > MAX_CID_LEN)
1579        return -1;
1580    if (dcil)
1581    {
1582        memcpy(packet_in->pi_dcid.idbuf, p, dcil);
1583        packet_in->pi_flags |= PI_CONN_ID;
1584        p += dcil;
1585    }
1586    packet_in->pi_dcid.len = dcil;
1587
1588    scil = *p++;
1589    if (p + scil > end || scil > MAX_CID_LEN)
1590        return -1;
1591    if (scil)
1592    {
1593        packet_in->pi_scid_off = p - packet_in->pi_data;
1594        p += scil;
1595    }
1596    packet_in->pi_scid_len = scil;
1597
1598    switch (header_type)
1599    {
1600    case HETY_INITIAL:
1601        if (dcil < MIN_INITIAL_DCID_LEN)
1602            return -1;
1603        r = vint_read(p, end, &token_len);
1604        if (r < 0)
1605            return -1;
1606        if (token_len && !is_server)
1607        {
1608            /* From [draft-ietf-quic-transport-14]:
1609             *
1610             *  Token Length:  A variable-length integer specifying the
1611             *  length of the Token field, in bytes.  This value is zero
1612             *  if no token is present.  Initial packets sent by the
1613             *  server MUST set the Token Length field to zero; clients
1614             *  that receive an Initial packet with a non-zero Token
1615             *  Length field MUST either discard the packet or generate
1616             *  a connection error of type PROTOCOL_VIOLATION.
1617             */
1618            return -1;
1619        }
1620        p += r;
1621        if (token_len)
1622        {
1623            if (token_len >=
1624                        1ull << (sizeof(packet_in->pi_token_size) * 8))
1625                return -1;
1626            if (p + token_len > end)
1627                return -1;
1628            packet_in->pi_token = p - packet_in->pi_data;
1629            packet_in->pi_token_size = token_len;
1630            p += token_len;
1631        }
1632        /* fall-through */
1633    case HETY_HANDSHAKE:
1634    case HETY_0RTT:
1635        if (p >= end)
1636            return -1;
1637        r = vint_read(p, end, &payload_len);
1638        if (r < 0)
1639            return -1;
1640        p += r;
1641        if (p - packet_in->pi_data + payload_len > length)
1642            return -1;
1643        length = p - packet_in->pi_data + payload_len;
1644        if (end - p < 4)
1645            return -1;
1646        state->pps_p      = p - r;
1647        state->pps_nbytes = r;
1648        packet_in->pi_quic_ver = 1;
1649        break;
1650    case HETY_RETRY:
1651        if (p >= end)
1652            return -1;
1653        odcil = *p++;
1654        if (p + odcil > end || odcil > MAX_CID_LEN)
1655            return -1;
1656        packet_in->pi_odcid_len = odcil;
1657        packet_in->pi_odcid = p - packet_in->pi_data;
1658        p += odcil;
1659        packet_in->pi_token = p - packet_in->pi_data;
1660        packet_in->pi_token_size = end - p;
1661        p = end;
1662        length = end - packet_in->pi_data;
1663        state->pps_p      = NULL;
1664        state->pps_nbytes = 0;
1665        packet_in->pi_quic_ver = 1;
1666        break;
1667    default:
1668        assert(header_type == HETY_VERNEG);
1669        if (p >= end || (3 & (uintptr_t) (end - p)))
1670            return -1;
1671        packet_in->pi_quic_ver = p - packet_in->pi_data;
1672        p = end;
1673        state->pps_p      = NULL;
1674        state->pps_nbytes = 0;
1675        break;
1676    }
1677
1678    packet_in->pi_header_sz     = p - packet_in->pi_data;
1679    packet_in->pi_data_sz       = length;
1680    packet_in->pi_nonce         = 0;
1681    packet_in->pi_refcnt        = 0;
1682    packet_in->pi_frame_types   = 0;
1683    memset(&packet_in->pi_next, 0, sizeof(packet_in->pi_next));
1684    packet_in->pi_refcnt        = 0;
1685    packet_in->pi_received      = 0;
1686
1687    /* Packet number is set to an invalid value.  The packet number must
1688     * be decrypted, which happens later.
1689     */
1690    packet_in->pi_packno        = 1ULL << 62;
1691
1692    return 0;
1693}
1694
1695
1696/* Is this a valid Initial packet?  We take the perspective of the server. */
1697int
1698lsquic_is_valid_ietf_v1_or_Q046_hs_packet (const unsigned char *buf,
1699                                        size_t length, lsquic_ver_tag_t *tagp)
1700{
1701    const unsigned char *p = buf;
1702    const unsigned char *const end = p + length;
1703    lsquic_ver_tag_t tag;
1704    enum header_type header_type;
1705    unsigned dcil, scil;
1706    int r;
1707    unsigned char first_byte;
1708    uint64_t payload_len, token_len, packet_len;
1709
1710    if (length < 6)
1711        return 0;
1712    first_byte = *p++;
1713
1714    header_type = bits2ht[ (first_byte >> 4) & 3 ];
1715    if (header_type != HETY_INITIAL)
1716        return 0;
1717
1718    memcpy(&tag, p, 4);
1719    p += 4;
1720    if (tag == 0)
1721        return 0;       /* Client never sends version negotiation packets */
1722
1723    if (tag == * (uint32_t *) "Q046")
1724    {
1725        dcil = p[0] >> 4;
1726        if (dcil)
1727            dcil += 3;
1728        scil = p[0] & 0xF;
1729        if (scil)
1730            scil += 3;
1731        ++p;
1732
1733        if (!(dcil == GQUIC_CID_LEN && scil == 0))
1734            return 0;
1735
1736        packet_len = first_byte & 3;
1737
1738        if (end - p < (ptrdiff_t) (dcil + scil + packet_len))
1739            return 0;
1740    }
1741    else
1742    {
1743        dcil = *p++;
1744        if (dcil < MIN_INITIAL_DCID_LEN || dcil > MAX_CID_LEN)
1745            return 0;
1746        if (p + dcil >= end)
1747            return 0;
1748        p += dcil;
1749        scil = *p++;
1750        if (p + scil > end || scil > MAX_CID_LEN)
1751            return 0;
1752        p += scil;
1753        r = vint_read(p, end, &token_len);
1754        if (r < 0)
1755            return 0;
1756        p += r;
1757        p += token_len;
1758        if (p >= end)
1759            return 0;
1760        r = vint_read(p, end, &payload_len);
1761        if (r < 0)
1762            return 0;
1763        p += r;
1764        if (p - buf + payload_len > length)
1765            return 0;
1766        if (end - p < 4)
1767            return 0;
1768    }
1769
1770    *tagp = tag;
1771    return 1;
1772}
1773
1774
1775int
1776lsquic_ietf_v1_parse_packet_in_short_begin (struct lsquic_packet_in *packet_in,
1777                size_t length, int is_server, unsigned cid_len,
1778                struct packin_parse_state *state)
1779{
1780    unsigned char byte;
1781    unsigned header_sz;
1782
1783    /* By the time this function has been called, we know length is non-zero */
1784    byte = packet_in->pi_data[0];
1785
1786    /* [draft-ietf-quic-transport-17] Section 17.3 */
1787    /* 01SRRKPP */
1788
1789    if (cid_len)
1790    {
1791        header_sz = 1 + cid_len;
1792        if (length < header_sz)
1793            return -1;
1794        memcpy(packet_in->pi_dcid.idbuf, packet_in->pi_data + 1, cid_len);
1795        packet_in->pi_dcid.len = cid_len;
1796        packet_in->pi_flags |= PI_CONN_ID;
1797    }
1798    else
1799        header_sz = 1;
1800
1801    packet_in->pi_flags |= ((byte & 0x20) > 0) << PIBIT_SPIN_SHIFT;
1802    packet_in->pi_flags |= (byte & 3) << PIBIT_BITS_SHIFT;
1803
1804    packet_in->pi_header_sz     = header_sz;
1805    packet_in->pi_data_sz       = length;
1806    packet_in->pi_quic_ver      = 0;
1807    packet_in->pi_nonce         = 0;
1808    packet_in->pi_refcnt        = 0;
1809    packet_in->pi_frame_types   = 0;
1810    memset(&packet_in->pi_next, 0, sizeof(packet_in->pi_next));
1811    packet_in->pi_refcnt        = 0;
1812    packet_in->pi_received      = 0;
1813
1814    /* This is so that Q046 works, ID-18 code does not use it */
1815    state->pps_p                = packet_in->pi_data + header_sz;
1816    state->pps_nbytes           = 1 + (byte & 3);
1817
1818    return 0;
1819}
1820
1821
1822#if __GNUC__
1823#   define popcount __builtin_popcount
1824#else
1825static int
1826popcount (unsigned v)
1827{
1828    int count, i;
1829    for (i = 0, count = 0; i < sizeof(v) * 8; ++i)
1830        if (v & (1 << i))
1831            ++count;
1832    return count;
1833}
1834#endif
1835
1836
1837int
1838lsquic_ietf_v1_gen_ver_nego_pkt (unsigned char *buf, size_t bufsz,
1839         const lsquic_cid_t *scid, const lsquic_cid_t *dcid, unsigned versions,
1840         uint8_t rand)
1841{
1842    size_t need;
1843    int r;
1844
1845    need = 1 /* Type */ + 4 /* Version */ + 1 /* DCIL */
1846                + dcid->len + 1 /* SCIL */ + scid->len + popcount(versions) * 4;
1847
1848    if (need > bufsz)
1849        return -1;
1850
1851    *buf++ = 0x80 | 0x40 | rand;
1852    memset(buf, 0, 4);
1853    buf += 4;
1854
1855    /* From [draft-ietf-quic-transport-22], Section 17.2.1:
1856     *
1857     *  The server MUST include the value from the Source Connection ID field
1858     *  of the packet it receives in the Destination Connection ID field.
1859     *  The value for Source Connection ID MUST be copied from the
1860     *  Destination Connection ID of the received packet, which is initially
1861     *  randomly selected by a client.  Echoing both connection IDs gives
1862     *  clients some assurance that the server received the packet and that
1863     *  the Version Negotiation packet was not generated by an off-path
1864     *  attacker.
1865     */
1866
1867    *buf++ = dcid->len;
1868    memcpy(buf, dcid->idbuf, dcid->len);
1869    buf += dcid->len;
1870    *buf++ = scid->len;
1871    memcpy(buf, scid->idbuf, scid->len);
1872    buf += scid->len;
1873
1874    r = lsquic_gen_ver_tags(buf, bufsz - 1 - 4 - 2 - dcid->len - scid->len,
1875                                                                    versions);
1876    if (r < 0)
1877        return -1;
1878    assert((unsigned) r == popcount(versions) * 4u);
1879
1880    return need;
1881}
1882
1883
1884
1885
1886const struct parse_funcs lsquic_parse_funcs_ietf_v1 =
1887{
1888    .pf_gen_reg_pkt_header            =  ietf_v1_gen_reg_pkt_header,
1889    .pf_parse_packet_in_finish        =  ietf_v1_parse_packet_in_finish,
1890    .pf_gen_stream_frame              =  ietf_v1_gen_stream_frame,
1891    .pf_calc_stream_frame_header_sz   =  ietf_v1_calc_stream_frame_header_sz,
1892    .pf_parse_stream_frame            =  ietf_v1_parse_stream_frame,
1893    .pf_parse_ack_frame               =  ietf_v1_parse_ack_frame,
1894    .pf_gen_ack_frame                 =  ietf_v1_gen_ack_frame,
1895    .pf_gen_blocked_frame             =  ietf_v1_gen_blocked_frame,
1896    .pf_parse_blocked_frame           =  ietf_v1_parse_blocked_frame,
1897    .pf_blocked_frame_size            =  ietf_v1_blocked_frame_size,
1898    .pf_rst_frame_size                =  ietf_v1_rst_frame_size,
1899    .pf_gen_rst_frame                 =  ietf_v1_gen_rst_frame,
1900    .pf_parse_rst_frame               =  ietf_v1_parse_rst_frame,
1901    .pf_gen_connect_close_frame       =  ietf_v1_gen_connect_close_frame,
1902    .pf_parse_connect_close_frame     =  ietf_v1_parse_connect_close_frame,
1903    .pf_gen_ping_frame                =  ietf_v1_gen_ping_frame,
1904    .pf_parse_frame_type              =  ietf_v1_parse_frame_type,
1905    .pf_turn_on_fin                   =  ietf_v1_turn_on_fin,
1906    .pf_packout_size                  =  ietf_v1_packout_size,
1907    .pf_packout_max_header_size       =  ietf_v1_packout_max_header_size,
1908    .pf_path_chal_frame_size          =  ietf_v1_path_chal_frame_size,
1909    .pf_parse_path_chal_frame         =  ietf_v1_parse_path_chal_frame,
1910    .pf_gen_path_chal_frame           =  ietf_v1_gen_path_chal_frame,
1911    .pf_path_resp_frame_size          =  ietf_v1_path_resp_frame_size,
1912    .pf_gen_path_resp_frame           =  ietf_v1_gen_path_resp_frame,
1913    .pf_parse_path_resp_frame         =  ietf_v1_parse_path_resp_frame,
1914    .pf_calc_packno_bits              =  ietf_v1_calc_packno_bits,
1915    .pf_packno_bits2len               =  ietf_v1_packno_bits2len,
1916    .pf_packno_info                   =  ietf_v1_packno_info,
1917    .pf_gen_crypto_frame              =  ietf_v1_gen_crypto_frame,
1918    .pf_parse_crypto_frame            =  ietf_v1_parse_crypto_frame,
1919    .pf_calc_crypto_frame_header_sz   =  ietf_v1_calc_crypto_frame_header_sz,
1920    .pf_parse_max_data                =  ietf_v1_parse_max_data,
1921    .pf_gen_max_data_frame            =  ietf_v1_gen_max_data_frame,
1922    .pf_max_data_frame_size           =  ietf_v1_max_data_frame_size,
1923    .pf_parse_new_conn_id             =  ietf_v1_parse_new_conn_id,
1924    .pf_gen_stream_blocked_frame      =  ietf_v1_gen_stream_blocked_frame,
1925    .pf_parse_stream_blocked_frame    =  ietf_v1_parse_stream_blocked_frame,
1926    .pf_stream_blocked_frame_size     =  ietf_v1_stream_blocked_frame_size,
1927    .pf_gen_max_stream_data_frame     =  ietf_v1_gen_max_stream_data_frame,
1928    .pf_parse_max_stream_data_frame   =  ietf_v1_parse_max_stream_data_frame,
1929    .pf_max_stream_data_frame_size    =  ietf_v1_max_stream_data_frame_size,
1930    .pf_parse_stop_sending_frame      =  ietf_v1_parse_stop_sending_frame,
1931    .pf_gen_stop_sending_frame        =  ietf_v1_gen_stop_sending_frame,
1932    .pf_stop_sending_frame_size       =  ietf_v1_stop_sending_frame_size,
1933    .pf_parse_new_token_frame         =  ietf_v1_parse_new_token_frame,
1934    .pf_new_connection_id_frame_size  =  ietf_v1_new_connection_id_frame_size,
1935    .pf_gen_new_connection_id_frame   =  ietf_v1_gen_new_connection_id_frame,
1936    .pf_new_token_frame_size          =  ietf_v1_new_token_frame_size,
1937    .pf_gen_new_token_frame           =  ietf_v1_gen_new_token_frame,
1938    .pf_parse_retire_cid_frame        =  ietf_v1_parse_retire_cid_frame,
1939    .pf_gen_retire_cid_frame          =  ietf_v1_gen_retire_cid_frame,
1940    .pf_retire_cid_frame_size         =  ietf_v1_retire_cid_frame_size,
1941    .pf_gen_streams_blocked_frame     =  ietf_v1_gen_streams_blocked_frame,
1942    .pf_parse_streams_blocked_frame   =  ietf_v1_parse_streams_blocked_frame,
1943    .pf_streams_blocked_frame_size    =  ietf_v1_streams_blocked_frame_size,
1944    .pf_gen_max_streams_frame         =  ietf_v1_gen_max_streams_frame,
1945    .pf_parse_max_streams_frame       =  ietf_v1_parse_max_streams_frame,
1946    .pf_max_streams_frame_size        =  ietf_v1_max_streams_frame_size,
1947};
1948