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