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