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