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