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