Coverage Report

Created: 2026-12-01 06:56

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/h2o/lib/http3/common.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2018 Fastly, Kazuho Oku
3
 *
4
 * Permission is hereby granted, free of charge, to any person obtaining a copy
5
 * of this software and associated documentation files (the "Software"), to
6
 * deal in the Software without restriction, including without limitation the
7
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8
 * sell copies of the Software, and to permit persons to whom the Software is
9
 * furnished to do so, subject to the following conditions:
10
 *
11
 * The above copyright notice and this permission notice shall be included in
12
 * all copies or substantial portions of the Software.
13
 *
14
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20
 * IN THE SOFTWARE.
21
 */
22
#ifdef __APPLE__
23
#define __APPLE_USE_RFC_3542 /* to use IPV6_PKTINFO */
24
#endif
25
#include <errno.h>
26
#include <sys/types.h>
27
#include <netinet/in.h>
28
#include <netinet/ip.h>
29
#include <netinet/udp.h>
30
#include <pthread.h>
31
#include <stdio.h>
32
#include <sys/socket.h>
33
#include <unistd.h>
34
#include "picotls/openssl.h"
35
#include "h2o.h"
36
#include "h2o/string_.h"
37
#include "h2o/http3_common.h"
38
#include "h2o/http3_internal.h"
39
#include "h2o/multithread.h"
40
#include "../probes_.h"
41
42
h2o_quic_conn_t h2o_quic_accept_conn_decryption_failed;
43
h2o_http3_conn_t h2o_http3_accept_conn_closed;
44
45
struct st_h2o_http3_ingress_unistream_t {
46
    /**
47
     * back pointer
48
     */
49
    quicly_stream_t *quic;
50
    /**
51
     *
52
     */
53
    h2o_buffer_t *recvbuf;
54
    /**
55
     * Points to the counter that records the number of bytes received on a control or QPACK stream; remains NULL until such a
56
     * stream type is identified.
57
     */
58
    uint64_t *bytes_received;
59
    /**
60
     * A callback that passes unparsed input to be handled. `src` is set to NULL when receiving a reset.
61
     */
62
    void (*handle_input)(h2o_http3_conn_t *conn, struct st_h2o_http3_ingress_unistream_t *stream, const uint8_t **src,
63
                         const uint8_t *src_end, int is_eos);
64
};
65
66
const char h2o_http3_err_frame_too_large[] = "HTTP/3 frame is too large";
67
68
const ptls_iovec_t h2o_http3_alpn[3] = {{(void *)H2O_STRLIT("h3")}, {(void *)H2O_STRLIT("h3-29")}, {(void *)H2O_STRLIT("h3-27")}};
69
70
static void report_sendmsg_errors(h2o_error_reporter_t *reporter, uint64_t total_successes, uint64_t cur_successes)
71
0
{
72
0
    char errstr[256];
73
0
    fprintf(stderr, "sendmsg failed %" PRIu64 " time%s, succeeded: %" PRIu64 " time%s, over the last minute: %s\n",
74
0
            reporter->cur_errors, reporter->cur_errors > 1 ? "s" : "", cur_successes, cur_successes > 1 ? "s" : "",
75
0
            h2o_strerror_r((int)reporter->data, errstr, sizeof(errstr)));
76
0
}
77
78
static h2o_error_reporter_t track_sendmsg = H2O_ERROR_REPORTER_INITIALIZER(report_sendmsg_errors);
79
80
#if !H2O_USE_LIBUV
81
h2o_socket_t *h2o_quic_create_client_socket(h2o_loop_t *loop, int family)
82
0
{
83
0
    int fd, on = 1;
84
0
    quicly_address_t addr = {.sa.sa_family = family};
85
0
    socklen_t addrlen;
86
87
0
    if ((fd = socket(family, SOCK_DGRAM, 0)) == -1)
88
0
        return NULL;
89
90
0
    switch (family) {
91
0
    case AF_INET:
92
0
#ifdef IP_RECVTOS
93
0
        setsockopt(fd, IPPROTO_IP, IP_RECVTOS, &on, sizeof(on));
94
0
#endif
95
0
        addrlen = sizeof(addr.sin);
96
0
        break;
97
0
    case AF_INET6:
98
0
#ifdef IPV6_V6ONLY
99
0
        if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) != 0)
100
0
            goto Error;
101
0
#endif
102
0
#ifdef IPV6_RECVTCLASS
103
0
        setsockopt(fd, IPPROTO_IPV6, IPV6_RECVTCLASS, &on, sizeof(on));
104
0
#endif
105
0
        addrlen = sizeof(addr.sin6);
106
0
        break;
107
0
    default:
108
0
        assert(!"unexpected address family");
109
0
        goto Error;
110
0
    }
111
112
0
    if (bind(fd, &addr.sa, addrlen) != 0)
113
0
        goto Error;
114
115
0
    return h2o_evloop_socket_create(loop, fd, H2O_SOCKET_FLAG_DONT_READ);
116
117
0
Error: {
118
0
    int saved_errno = errno;
119
0
    close(fd);
120
0
    errno = saved_errno;
121
0
}
122
0
    return NULL;
123
0
}
124
#endif
125
126
int h2o_quic_send_datagrams(h2o_quic_ctx_t *ctx, quicly_address_t *dest, quicly_address_t *src, struct iovec *datagrams,
127
                            size_t num_datagrams, uint8_t ecn)
128
0
{
129
0
    union {
130
0
        struct cmsghdr hdr;
131
0
        char buf[
132
0
#ifdef IPV6_PKTINFO
133
0
            CMSG_SPACE(sizeof(struct in6_pktinfo))
134
#elif defined(IP_PKTINFO)
135
            CMSG_SPACE(sizeof(struct in_pktinfo))
136
#elif defined(IP_SENDSRCADDR)
137
            CMSG_SPACE(sizeof(struct in_addr))
138
#else
139
            CMSG_SPACE(1)
140
#endif
141
0
#ifdef UDP_SEGMENT
142
0
            + CMSG_SPACE(sizeof(uint16_t))
143
0
#endif
144
            + CMSG_SPACE(sizeof(int)) /* IP_TOS or IPV6_TCLASS */
145
            + CMSG_SPACE(1)           /* sentry */
146
0
        ];
147
0
    } cmsgbuf = {.buf = {} /* zero-cleared so that CMSG_NXTHDR can be used for locating the *next* cmsghdr */};
148
0
    struct msghdr mess = {
149
0
        .msg_name = &dest->sa,
150
0
        .msg_namelen = quicly_get_socklen(&dest->sa),
151
0
        .msg_control = cmsgbuf.buf,
152
0
        .msg_controllen = sizeof(cmsgbuf.buf),
153
0
    };
154
0
    struct cmsghdr *cmsg = CMSG_FIRSTHDR(&mess);
155
0
    h2o_quic_socket_t *sock;
156
0
    int ret;
157
158
0
#define PUSH_CMSG(level, type, value)                                                                                              \
159
0
    do {                                                                                                                           \
160
0
        cmsg->cmsg_level = (level);                                                                                                \
161
0
        cmsg->cmsg_type = (type);                                                                                                  \
162
0
        cmsg->cmsg_len = CMSG_LEN(sizeof(value));                                                                                  \
163
0
        memcpy(CMSG_DATA(cmsg), &value, sizeof(value));                                                                            \
164
0
        cmsg = CMSG_NXTHDR(&mess, cmsg);                                                                                           \
165
0
    } while (0)
166
167
0
    if (ctx->sock.addr.ss_family == dest->sa.sa_family) {
168
0
        sock = &ctx->sock;
169
0
    } else if (ctx->sock_alt_family.sock != NULL && ctx->sock_alt_family.addr.ss_family == dest->sa.sa_family) {
170
0
        sock = &ctx->sock_alt_family;
171
0
    } else {
172
0
        return 0;
173
0
    }
174
175
    /* first CMSG is the source address */
176
0
    if (src->sa.sa_family != AF_UNSPEC) {
177
0
        switch (src->sa.sa_family) {
178
0
        case AF_INET: {
179
0
#if defined(IP_PKTINFO)
180
0
            if (*sock->port != src->sin.sin_port)
181
0
                return 0;
182
0
            struct in_pktinfo info = {.ipi_spec_dst = src->sin.sin_addr};
183
0
            PUSH_CMSG(IPPROTO_IP, IP_PKTINFO, info);
184
#elif defined(IP_SENDSRCADDR)
185
            if (*sock->port != src->sin.sin_port)
186
                return 0;
187
            struct sockaddr_in *fdaddr = (struct sockaddr_in *)&sock->addr;
188
            assert(fdaddr->sin_family == AF_INET);
189
            if (fdaddr->sin_addr.s_addr == INADDR_ANY)
190
                PUSH_CMSG(IPPROTO_IP, IP_SENDSRCADDR, src->sin.sin_addr);
191
#else
192
            h2o_fatal("IP_PKTINFO not available");
193
#endif
194
0
        } break;
195
0
        case AF_INET6:
196
0
#ifdef IPV6_PKTINFO
197
0
            if (*sock->port != src->sin6.sin6_port)
198
0
                return 0;
199
0
            struct in6_pktinfo info = {.ipi6_addr = src->sin6.sin6_addr};
200
0
            PUSH_CMSG(IPPROTO_IPV6, IPV6_PKTINFO, info);
201
#else
202
            h2o_fatal("IPV6_PKTINFO not available");
203
#endif
204
0
            break;
205
0
        default:
206
0
            h2o_fatal("unexpected address family");
207
0
            break;
208
0
        }
209
0
    }
210
211
    /* next CMSG is UDP_SEGMENT size (for GSO); assert that the input follows the expected pattern (see the doc-comment of
212
     * `quicly_send`), then set the CMSG and convert `datagrams` into one. */
213
0
    for (size_t i = 1; i < num_datagrams; ++i) {
214
0
        assert(datagrams[i - 1].iov_base + datagrams[i - 1].iov_len == datagrams[i].iov_base);
215
0
        assert(i == num_datagrams - 1 || datagrams[i].iov_len == datagrams[0].iov_len);
216
0
    }
217
0
#ifdef UDP_SEGMENT
218
0
    struct iovec gso_iovec;
219
0
    if (num_datagrams > 1 && ctx->use_gso) {
220
0
        uint16_t segsize = (uint16_t)datagrams[0].iov_len;
221
0
        PUSH_CMSG(SOL_UDP, UDP_SEGMENT, segsize);
222
0
        gso_iovec = (struct iovec){
223
0
            .iov_base = datagrams[0].iov_base,
224
0
            .iov_len = datagrams[num_datagrams - 1].iov_base + datagrams[num_datagrams - 1].iov_len - datagrams[0].iov_base,
225
0
        };
226
0
        datagrams = &gso_iovec;
227
0
        num_datagrams = 1;
228
0
    }
229
0
#endif
230
231
0
    if (ecn != 0) {
232
0
        int tos = ecn; /* IPV6_TCLASS uses int, and draft-ietf-tsvwg-udp-ecn-05 says IP_TOS assumes int too, on all platforms */
233
0
        switch (dest->sa.sa_family) {
234
0
        case AF_INET:
235
0
            PUSH_CMSG(IPPROTO_IP, IP_TOS, tos);
236
0
            break;
237
0
        case AF_INET6:
238
0
#ifdef IPV6_TCLASS
239
0
            PUSH_CMSG(IPPROTO_IPV6, IPV6_TCLASS, tos);
240
0
#endif
241
0
            break;
242
0
        default:
243
0
            break;
244
0
        }
245
0
    }
246
247
    /* commit CMSG length */
248
0
    if ((mess.msg_controllen = (socklen_t)((char *)cmsg - (char *)cmsgbuf.buf)) == 0)
249
0
        mess.msg_control = NULL;
250
251
    /* send datagrams */
252
0
    for (size_t i = 0; i < num_datagrams; ++i) {
253
0
        mess.msg_iov = datagrams + i;
254
0
        mess.msg_iovlen = 1;
255
0
        while ((ret = (int)sendmsg(h2o_socket_get_fd(sock->sock), &mess, 0)) == -1 && errno == EINTR)
256
0
            ;
257
0
        if (ret == -1)
258
0
            goto SendmsgError;
259
0
    }
260
261
0
    h2o_error_reporter_record_success(&track_sendmsg);
262
263
0
    return 1;
264
265
0
SendmsgError:
266
    /* The UDP stack returns EINVAL (linux) or EADDRNOTAVAIL (darwin, and presumably other BSD) when it was unable to use the
267
     * designated source address.  We communicate that back to the caller so that the connection can be closed immediately. */
268
0
    if (src->sa.sa_family != AF_UNSPEC && (errno == EINVAL || errno == EADDRNOTAVAIL))
269
0
        return 0;
270
271
    /* Temporary failure to send a packet is not a permanent error fo the connection. (TODO do we want do something more
272
     * specific?) */
273
274
    /* Log the number of failed invocations once per minute, if there has been such a failure. */
275
0
    h2o_error_reporter_record_error(ctx->loop, &track_sendmsg, 60000, errno);
276
277
0
    return 1;
278
279
0
#undef PUSH_CMSG
280
0
}
281
282
static inline const h2o_http3_conn_callbacks_t *get_callbacks(h2o_http3_conn_t *conn)
283
0
{
284
0
    return (const h2o_http3_conn_callbacks_t *)conn->super.callbacks;
285
0
}
286
287
static void ingress_unistream_on_destroy(quicly_stream_t *qs, quicly_error_t err)
288
0
{
289
0
    struct st_h2o_http3_ingress_unistream_t *stream = qs->data;
290
0
    h2o_buffer_dispose(&stream->recvbuf);
291
0
    free(stream);
292
0
}
293
294
static void ingress_unistream_on_receive(quicly_stream_t *qs, size_t off, const void *input, size_t len)
295
0
{
296
0
    h2o_http3_conn_t *conn = *quicly_get_data(qs->conn);
297
0
    struct st_h2o_http3_ingress_unistream_t *stream = qs->data;
298
299
    /* save received data */
300
0
    h2o_http3_update_recvbuf(&stream->recvbuf, off, input, len);
301
302
    /* determine bytes that can be handled */
303
0
    size_t bytes_available = quicly_recvstate_bytes_available(&stream->quic->recvstate);
304
0
    const uint8_t *src = (const uint8_t *)stream->recvbuf->bytes;
305
0
    if (bytes_available == 0 && !quicly_recvstate_transfer_complete(&stream->quic->recvstate))
306
0
        return;
307
0
    uint64_t bytes_received = stream->quic->recvstate.data_off + bytes_available;
308
309
    /* handle the bytes */
310
0
    stream->handle_input(conn, stream, &src, src + bytes_available, quicly_recvstate_transfer_complete(&stream->quic->recvstate));
311
0
    if (stream->bytes_received != NULL && *stream->bytes_received < bytes_received)
312
0
        *stream->bytes_received = bytes_received;
313
0
    if (quicly_get_state(conn->super.quic) >= QUICLY_STATE_CLOSING)
314
0
        return;
315
316
    /* remove bytes that have been consumed */
317
0
    size_t bytes_consumed = src - (const uint8_t *)stream->recvbuf->bytes;
318
0
    if (bytes_consumed != 0) {
319
0
        h2o_buffer_consume(&stream->recvbuf, bytes_consumed);
320
0
        quicly_stream_sync_recvbuf(stream->quic, bytes_consumed);
321
0
    }
322
0
}
323
324
static void ingress_unistream_on_receive_reset(quicly_stream_t *qs, quicly_error_t err)
325
0
{
326
0
    h2o_http3_conn_t *conn = *quicly_get_data(qs->conn);
327
0
    struct st_h2o_http3_ingress_unistream_t *stream = qs->data;
328
329
0
    stream->handle_input(conn, stream, NULL, NULL, 1);
330
0
}
331
332
static void qpack_encoder_stream_handle_input(h2o_http3_conn_t *conn, struct st_h2o_http3_ingress_unistream_t *stream,
333
                                              const uint8_t **src, const uint8_t *src_end, int is_eos)
334
0
{
335
0
    if (src == NULL || is_eos) {
336
0
        h2o_quic_close_connection(&conn->super, H2O_HTTP3_ERROR_CLOSED_CRITICAL_STREAM, NULL);
337
0
        return;
338
0
    }
339
340
0
    uint64_t insert_count;
341
0
    int ret;
342
0
    const char *err_desc = NULL;
343
0
    if ((ret = h2o_qpack_decoder_handle_input(conn->qpack.dec, &insert_count, src, src_end, &err_desc)) != 0) {
344
0
        h2o_quic_close_connection(&conn->super, ret, err_desc);
345
0
        return;
346
0
    }
347
0
    if (insert_count != 0)
348
0
        get_callbacks(conn)->qpack_unblock_streams(conn, insert_count);
349
0
}
350
351
static void qpack_decoder_stream_handle_input(h2o_http3_conn_t *conn, struct st_h2o_http3_ingress_unistream_t *stream,
352
                                              const uint8_t **src, const uint8_t *src_end, int is_eos)
353
0
{
354
0
    if (src == NULL || is_eos) {
355
0
        h2o_quic_close_connection(&conn->super, H2O_HTTP3_ERROR_CLOSED_CRITICAL_STREAM, NULL);
356
0
        return;
357
0
    }
358
359
0
    int ret;
360
0
    const char *err_desc = NULL;
361
0
    if ((ret = h2o_qpack_encoder_handle_input(conn->qpack.enc, src, src_end, &err_desc)) != 0)
362
0
        h2o_quic_close_connection(&conn->super, ret, err_desc);
363
0
}
364
365
static void control_stream_handle_input(h2o_http3_conn_t *conn, struct st_h2o_http3_ingress_unistream_t *stream,
366
                                        const uint8_t **src, const uint8_t *src_end, int is_eos)
367
0
{
368
0
    if (src == NULL || is_eos) {
369
0
        h2o_quic_close_connection(&conn->super, H2O_HTTP3_ERROR_CLOSED_CRITICAL_STREAM, NULL);
370
0
        return;
371
0
    }
372
373
0
    do {
374
0
        h2o_http3_read_frame_t frame;
375
0
        quicly_error_t ret;
376
0
        const char *err_desc = NULL;
377
378
0
        if ((ret = h2o_http3_read_frame(&frame, quicly_is_client(conn->super.quic), H2O_HTTP3_STREAM_TYPE_CONTROL,
379
0
                                        conn->max_frame_payload_size, src, src_end, &err_desc)) != 0) {
380
0
            if (ret != H2O_HTTP3_ERROR_INCOMPLETE)
381
0
                h2o_quic_close_connection(&conn->super, ret, err_desc);
382
0
            break;
383
0
        }
384
0
        if (h2o_http3_has_received_settings(conn) == (frame.type == H2O_HTTP3_FRAME_TYPE_SETTINGS) ||
385
0
            frame.type == H2O_HTTP3_FRAME_TYPE_DATA) {
386
0
            h2o_quic_close_connection(&conn->super, H2O_HTTP3_ERROR_FRAME_UNEXPECTED, NULL);
387
0
            break;
388
0
        }
389
0
        get_callbacks(conn)->handle_control_stream_frame(conn, frame.type, frame.payload, frame.length);
390
0
        if (quicly_get_state(conn->super.quic) >= QUICLY_STATE_CLOSING)
391
0
            break;
392
0
    } while (*src != src_end);
393
0
}
394
395
static void discard_handle_input(h2o_http3_conn_t *conn, struct st_h2o_http3_ingress_unistream_t *stream, const uint8_t **src,
396
                                 const uint8_t *src_end, int is_eos)
397
0
{
398
0
    if (src == NULL)
399
0
        return;
400
0
    *src = src_end;
401
0
}
402
403
static void unknown_type_handle_input(h2o_http3_conn_t *conn, struct st_h2o_http3_ingress_unistream_t *stream, const uint8_t **src,
404
                                      const uint8_t *src_end, int is_eos)
405
0
{
406
0
    uint64_t type;
407
408
    /* resets are allowed at least until the type is being determined */
409
0
    if (src == NULL)
410
0
        return;
411
412
    /* read the type, or just return if incomplete */
413
0
    const uint8_t *p = *src;
414
0
    if ((type = quicly_decodev(&p, src_end)) == UINT64_MAX)
415
0
        return;
416
0
    *src = p;
417
418
0
    switch (type) {
419
0
    case H2O_HTTP3_STREAM_TYPE_CONTROL:
420
0
        if (conn->_control_streams.ingress.control != NULL)
421
0
            goto Duplicate;
422
0
        conn->_control_streams.ingress.control = stream;
423
0
        stream->bytes_received = &conn->stats.bytes_received.control_stream;
424
0
        stream->handle_input = control_stream_handle_input;
425
0
        break;
426
0
    case H2O_HTTP3_STREAM_TYPE_QPACK_ENCODER:
427
0
        if (conn->_control_streams.ingress.qpack_encoder != NULL)
428
0
            goto Duplicate;
429
0
        conn->_control_streams.ingress.qpack_encoder = stream;
430
0
        stream->bytes_received = &conn->stats.bytes_received.qpack_encoder;
431
0
        stream->handle_input = qpack_encoder_stream_handle_input;
432
0
        break;
433
0
    case H2O_HTTP3_STREAM_TYPE_QPACK_DECODER:
434
0
        if (conn->_control_streams.ingress.qpack_decoder != NULL)
435
0
            goto Duplicate;
436
0
        conn->_control_streams.ingress.qpack_decoder = stream;
437
0
        stream->bytes_received = &conn->stats.bytes_received.qpack_decoder;
438
0
        stream->handle_input = qpack_decoder_stream_handle_input;
439
0
        break;
440
0
    default:
441
0
        quicly_request_stop(stream->quic, H2O_HTTP3_ERROR_STREAM_CREATION);
442
0
        stream->handle_input = discard_handle_input;
443
0
        break;
444
0
    }
445
446
0
    return stream->handle_input(conn, stream, src, src_end, is_eos);
447
448
0
Duplicate:
449
    /* permit only one control, encoder, and decoder stream per peer (RFC 9114 Section 6.2.1, RFC 9204 Section 4.2) */
450
0
    h2o_quic_close_connection(&conn->super, H2O_HTTP3_ERROR_STREAM_CREATION, "duplicate critical stream");
451
0
    stream->handle_input = discard_handle_input;
452
0
}
453
454
static void egress_unistream_on_destroy(quicly_stream_t *qs, quicly_error_t err)
455
20.3k
{
456
20.3k
    struct st_h2o_http3_egress_unistream_t *stream = qs->data;
457
20.3k
    h2o_buffer_dispose(&stream->sendbuf);
458
20.3k
    free(stream);
459
20.3k
}
460
461
static void egress_unistream_on_send_shift(quicly_stream_t *qs, size_t delta)
462
0
{
463
0
    struct st_h2o_http3_egress_unistream_t *stream = qs->data;
464
0
    h2o_buffer_consume(&stream->sendbuf, delta);
465
0
}
466
467
static void egress_unistream_on_send_emit(quicly_stream_t *qs, size_t off, void *dst, size_t *len, int *wrote_all)
468
21.8k
{
469
21.8k
    struct st_h2o_http3_egress_unistream_t *stream = qs->data;
470
471
21.8k
    if (*len >= stream->sendbuf->size - off) {
472
21.8k
        *len = stream->sendbuf->size - off;
473
21.8k
        *wrote_all = 1;
474
21.8k
    } else {
475
0
        *wrote_all = 0;
476
0
    }
477
21.8k
    memcpy(dst, stream->sendbuf->bytes + off, *len);
478
21.8k
    uint64_t bytes_sent = off + *len;
479
21.8k
    if (stream->bytes_sent != NULL && *stream->bytes_sent < bytes_sent)
480
21.8k
        *stream->bytes_sent = bytes_sent;
481
21.8k
}
482
483
static void egress_unistream_on_send_stop(quicly_stream_t *qs, quicly_error_t err)
484
0
{
485
0
    struct st_h2o_http3_conn_t *conn = *quicly_get_data(qs->conn);
486
0
    h2o_quic_close_connection(&conn->super, H2O_HTTP3_ERROR_CLOSED_CRITICAL_STREAM, NULL);
487
0
}
488
489
void h2o_http3_on_create_unidirectional_stream(quicly_stream_t *qs)
490
20.3k
{
491
20.3k
    if (quicly_stream_is_self_initiated(qs)) {
492
        /* create egress unistream */
493
20.3k
        static const quicly_stream_callbacks_t callbacks = {egress_unistream_on_destroy, egress_unistream_on_send_shift,
494
20.3k
                                                            egress_unistream_on_send_emit, egress_unistream_on_send_stop};
495
20.3k
        struct st_h2o_http3_egress_unistream_t *stream = h2o_mem_alloc(sizeof(*stream));
496
20.3k
        qs->data = stream;
497
20.3k
        qs->callbacks = &callbacks;
498
20.3k
        stream->quic = qs;
499
20.3k
        stream->bytes_sent = NULL;
500
20.3k
        h2o_buffer_init(&stream->sendbuf, &h2o_socket_buffer_prototype);
501
20.3k
    } else {
502
        /* create ingress unistream */
503
0
        static const quicly_stream_callbacks_t callbacks = {
504
0
            ingress_unistream_on_destroy, NULL, NULL, NULL, ingress_unistream_on_receive, ingress_unistream_on_receive_reset};
505
0
        struct st_h2o_http3_ingress_unistream_t *stream = h2o_mem_alloc(sizeof(*stream));
506
0
        qs->data = stream;
507
0
        qs->callbacks = &callbacks;
508
0
        stream->quic = qs;
509
0
        h2o_buffer_init(&stream->recvbuf, &h2o_socket_buffer_prototype);
510
0
        stream->bytes_received = NULL;
511
0
        stream->handle_input = unknown_type_handle_input;
512
0
    }
513
20.3k
}
514
515
static quicly_error_t open_egress_unistream(h2o_http3_conn_t *conn, struct st_h2o_http3_egress_unistream_t **stream,
516
                                            uint64_t *bytes_sent, h2o_iovec_t initial_bytes)
517
20.3k
{
518
20.3k
    quicly_stream_t *qs;
519
20.3k
    quicly_error_t ret;
520
521
20.3k
    if ((ret = quicly_open_stream(conn->super.quic, &qs, 1)) != 0)
522
0
        return ret;
523
20.3k
    *stream = qs->data;
524
20.3k
    assert((*stream)->quic == qs);
525
20.3k
    (*stream)->bytes_sent = bytes_sent;
526
527
20.3k
    h2o_buffer_append(&(*stream)->sendbuf, initial_bytes.base, initial_bytes.len);
528
20.3k
    return quicly_stream_sync_sendbuf((*stream)->quic, 1);
529
20.3k
}
530
531
static uint8_t *accept_hashkey_flatten_address(uint8_t *p, quicly_address_t *addr)
532
0
{
533
0
    switch (addr->sa.sa_family) {
534
0
    case AF_INET:
535
0
        *p++ = 4;
536
0
        memcpy(p, &addr->sin.sin_addr.s_addr, 4);
537
0
        p += 4;
538
0
        memcpy(p, &addr->sin.sin_port, 2);
539
0
        p += 2;
540
0
        break;
541
0
    case AF_INET6:
542
0
        *p++ = 6;
543
0
        memcpy(p, addr->sin6.sin6_addr.s6_addr, 16);
544
0
        p += 16;
545
0
        memcpy(p, &addr->sin6.sin6_port, 2);
546
0
        p += 2;
547
0
        break;
548
0
    case AF_UNSPEC:
549
0
        *p++ = 0;
550
0
        break;
551
0
    default:
552
0
        h2o_fatal("unknown protocol family");
553
0
        break;
554
0
    }
555
0
    return p;
556
0
}
557
558
static uint64_t calc_accept_hashkey(quicly_address_t *destaddr, quicly_address_t *srcaddr, ptls_iovec_t src_cid)
559
0
{
560
    /* prepare key */
561
0
    static __thread EVP_CIPHER_CTX *cipher = NULL;
562
0
    if (cipher == NULL) {
563
0
        static uint8_t key[PTLS_AES128_KEY_SIZE];
564
0
        H2O_MULTITHREAD_ONCE({ ptls_openssl_random_bytes(key, sizeof(key)); });
565
0
        if ((cipher = EVP_CIPHER_CTX_new()) == NULL || !EVP_EncryptInit_ex(cipher, EVP_aes_128_cbc(), NULL, key, NULL))
566
0
            h2o_fatal("failed to setup the cipher for calculating the accept hash key");
567
0
    }
568
569
0
    uint8_t buf[(1 + 16 + 2) * 2 + QUICLY_MAX_CID_LEN_V1 + PTLS_AES_BLOCK_SIZE] = {0};
570
0
    uint8_t *p = buf;
571
572
    /* build plaintext to encrypt */
573
0
    p = accept_hashkey_flatten_address(p, destaddr);
574
0
    p = accept_hashkey_flatten_address(p, srcaddr);
575
0
    memcpy(p, src_cid.base, src_cid.len);
576
0
    p += src_cid.len;
577
0
    assert(p <= buf + sizeof(buf));
578
0
    size_t bytes_to_encrypt = ((p - buf) + PTLS_AES_BLOCK_SIZE - 1) / PTLS_AES_BLOCK_SIZE * PTLS_AES_BLOCK_SIZE;
579
0
    assert(bytes_to_encrypt <= sizeof(buf));
580
581
0
    { /* encrypt (IV is given explicitly, as OpenSSL 3 does not reset the IV of a reused CBC context when NULL is given) */
582
0
        static const uint8_t iv[PTLS_AES_BLOCK_SIZE] = {0};
583
0
        EVP_EncryptInit_ex(cipher, NULL, NULL, NULL, iv);
584
0
        int bytes_encrypted = 0, ret = EVP_EncryptUpdate(cipher, buf, &bytes_encrypted, buf, (int)bytes_to_encrypt);
585
0
        assert(ret);
586
0
        assert(bytes_encrypted == bytes_to_encrypt);
587
0
    }
588
589
    /* use the last `size_t` bytes of the CBC output as the result */
590
0
    uint64_t result;
591
0
    memcpy(&result, buf + bytes_to_encrypt - sizeof(result), sizeof(result));
592
    /* avoid 0 (used as nonexist) */
593
0
    if (result == 0)
594
0
        result = 1;
595
0
    return result;
596
0
}
597
598
static void drop_from_acceptmap(h2o_quic_ctx_t *ctx, h2o_quic_conn_t *conn)
599
6.78k
{
600
6.78k
    if (conn->_accept_hashkey != 0) {
601
0
        khint_t iter;
602
0
        if ((iter = kh_get_h2o_quic_acceptmap(ctx->conns_accepting, conn->_accept_hashkey)) != kh_end(ctx->conns_accepting))
603
0
            kh_del_h2o_quic_acceptmap(ctx->conns_accepting, iter);
604
0
        conn->_accept_hashkey = 0;
605
0
    }
606
6.78k
}
607
608
static void send_version_negotiation(h2o_quic_ctx_t *ctx, quicly_address_t *destaddr, ptls_iovec_t dest_cid,
609
                                     quicly_address_t *srcaddr, ptls_iovec_t src_cid, const uint32_t *versions)
610
0
{
611
0
    uint8_t payload[QUICLY_MIN_CLIENT_INITIAL_SIZE];
612
0
    size_t payload_size = quicly_send_version_negotiation(ctx->quic, dest_cid, src_cid, versions, payload);
613
0
    assert(payload_size != SIZE_MAX);
614
0
    struct iovec vec = {.iov_base = payload, .iov_len = payload_size};
615
0
    h2o_quic_send_datagrams(ctx, destaddr, srcaddr, &vec, 1, 0);
616
0
    return;
617
0
}
618
619
static void process_packets(h2o_quic_ctx_t *ctx, quicly_address_t *destaddr, quicly_address_t *srcaddr, uint8_t ttl,
620
                            quicly_decoded_packet_t *packets, size_t num_packets)
621
0
{
622
0
    h2o_quic_conn_t *conn = NULL;
623
0
    size_t accepted_packet_index = SIZE_MAX;
624
625
0
    assert(num_packets != 0);
626
627
0
    if (ctx->quic_stats != NULL) {
628
0
        ctx->quic_stats->packet_received += num_packets;
629
0
    }
630
631
#if H2O_USE_DTRACE
632
    if (PTLS_UNLIKELY(H2O_H3_PACKET_RECEIVE_ENABLED())) {
633
        for (size_t i = 0; i != num_packets; ++i)
634
            H2O_H3_PACKET_RECEIVE(&destaddr->sa, &srcaddr->sa, packets[i].octets.base, packets[i].octets.len);
635
    }
636
#endif
637
638
0
    if (packets[0].cid.src.len > QUICLY_MAX_CID_LEN_V1)
639
0
        return;
640
641
    /* find the matching connection, by first looking at the CID (all packets as client, or Handshake, 1-RTT packets as server) */
642
0
    if (packets[0].cid.dest.plaintext.node_id == ctx->next_cid->node_id &&
643
0
        packets[0].cid.dest.plaintext.thread_id == ctx->next_cid->thread_id) {
644
0
        khiter_t iter = kh_get_h2o_quic_idmap(ctx->conns_by_id, packets[0].cid.dest.plaintext.master_id);
645
0
        if (iter != kh_end(ctx->conns_by_id)) {
646
0
            conn = kh_val(ctx->conns_by_id, iter);
647
            /* drop long header packets with different 4-tuple than the original, or if the incoming packet might be the first-
648
             * flight from the client, advance to state lookup using `cons_accepting` */
649
0
            if (!quicly_is_destination(conn->quic, &destaddr->sa, &srcaddr->sa, packets)) {
650
0
                if (!packets[0].cid.dest.might_be_client_generated)
651
0
                    return;
652
0
                conn = NULL;
653
0
            }
654
0
        } else if (!packets[0].cid.dest.might_be_client_generated) {
655
            /* send stateless reset when we could not find a matching connection for a 1 RTT packet */
656
0
            if (packets[0].octets.len >= QUICLY_STATELESS_RESET_PACKET_MIN_LEN) {
657
0
                uint8_t payload[QUICLY_MIN_CLIENT_INITIAL_SIZE];
658
0
                size_t payload_size = quicly_send_stateless_reset(ctx->quic, packets[0].cid.dest.encrypted.base, payload);
659
0
                if (payload_size != SIZE_MAX) {
660
0
                    struct iovec vec = {.iov_base = payload, .iov_len = payload_size};
661
0
                    h2o_quic_send_datagrams(ctx, srcaddr, destaddr, &vec, 1, 0);
662
0
                }
663
0
            }
664
0
            return;
665
0
        }
666
0
    } else if (!packets[0].cid.dest.might_be_client_generated) {
667
        /* forward 1-RTT packets belonging to different nodes, threads */
668
0
        uint64_t offending_node_id = packets[0].cid.dest.plaintext.node_id;
669
0
        if (ctx->forward_packets != NULL && ctx->forward_packets(ctx, &offending_node_id, packets[0].cid.dest.plaintext.thread_id,
670
0
                                                                 destaddr, srcaddr, ttl, packets, num_packets))
671
0
            return;
672
        /* non-authenticating 1-RTT packets are potentially stateless resets (FIXME handle them, note that we need to use a hashdos-
673
         * resistant hash map that also meets constant-time comparison requirements) */
674
0
        return;
675
0
    }
676
677
0
    if (conn == NULL) {
678
        /* Initial or 0-RTT packet, use 4-tuple to match the thread and the connection */
679
0
        assert(packets[0].cid.dest.might_be_client_generated);
680
0
        uint64_t accept_hashkey = calc_accept_hashkey(destaddr, srcaddr, packets[0].cid.src);
681
0
        if (ctx->accept_thread_divisor != 0) {
682
0
            uint32_t offending_thread = accept_hashkey % ctx->accept_thread_divisor;
683
0
            if (offending_thread != ctx->next_cid->thread_id) {
684
0
                if (ctx->forward_packets != NULL)
685
0
                    ctx->forward_packets(ctx, NULL, offending_thread, destaddr, srcaddr, ttl, packets, num_packets);
686
0
                return;
687
0
            }
688
0
        }
689
0
        khiter_t iter = kh_get_h2o_quic_acceptmap(ctx->conns_accepting, accept_hashkey);
690
0
        if (iter == kh_end(ctx->conns_accepting)) {
691
            /* a new connection for this thread (at least on this process); accept or delegate to newer process */
692
0
            if (ctx->acceptor != NULL) {
693
0
                if (packets[0].version != 0 && !quicly_is_supported_version(packets[0].version)) {
694
0
                    send_version_negotiation(ctx, srcaddr, packets[0].cid.src, destaddr, packets[0].cid.dest.encrypted,
695
0
                                             quicly_supported_versions);
696
0
                    return;
697
0
                }
698
0
            } else {
699
                /* This is the offending thread but it is not accepting, which means that the process (or the thread) is not acting
700
                 * as a server (likely gracefully shutting down). Let the application process forward the packet to the next
701
                 * generation. */
702
0
                if (ctx->forward_packets != NULL &&
703
0
                    ctx->forward_packets(ctx, NULL, ctx->next_cid->thread_id, destaddr, srcaddr, ttl, packets, num_packets))
704
0
                    return;
705
                /* If not forwarded, send rejection to the peer. A Version Negotiation packet that carries only a greasing version
706
                 * number is used for the purpose, hoping that that signal will trigger immediate downgrade to HTTP/2, across the
707
                 * broad spectrum of the client implementations than if CONNECTION_REFUSED is being used. */
708
0
                if (packets[0].version != 0) {
709
0
                    static const uint32_t no_versions[] = {0};
710
0
                    send_version_negotiation(ctx, srcaddr, packets[0].cid.src, destaddr, packets[0].cid.dest.encrypted,
711
0
                                             no_versions);
712
0
                }
713
0
                return;
714
0
            }
715
            /* try to accept any of the Initial packets being received */
716
0
            size_t i;
717
0
            for (i = 0; i != num_packets; ++i) {
718
0
                if ((packets[i].octets.base[0] & QUICLY_PACKET_TYPE_BITMASK) == QUICLY_PACKET_TYPE_INITIAL &&
719
0
                    (conn = ctx->acceptor(ctx, destaddr, srcaddr, packets + i)) != NULL) {
720
                    /* non-null generally means success, except for H2O_QUIC_ACCEPT_CONN_DECRYPTION_FAILED */
721
0
                    if (conn == &h2o_quic_accept_conn_decryption_failed) {
722
                        /* failed to decrypt Initial packet <=> it could belong to a connection on a different node; forward it to
723
                         * the destination being claimed by the DCID */
724
0
                        uint64_t offending_node_id = packets[i].cid.dest.plaintext.node_id;
725
0
                        uint32_t offending_thread_id = packets[i].cid.dest.plaintext.thread_id;
726
0
                        if (ctx->forward_packets != NULL &&
727
0
                            (offending_node_id != ctx->next_cid->node_id || offending_thread_id != ctx->next_cid->thread_id))
728
0
                            ctx->forward_packets(ctx, &offending_node_id, offending_thread_id, destaddr, srcaddr, ttl, packets,
729
0
                                                 num_packets);
730
0
                        return;
731
0
                    }
732
0
                    break;
733
0
                }
734
0
            }
735
0
            if (conn == NULL)
736
0
                return;
737
0
            accepted_packet_index = i;
738
0
            conn->_accept_hashkey = accept_hashkey;
739
0
            int r;
740
0
            iter = kh_put_h2o_quic_acceptmap(conn->ctx->conns_accepting, accept_hashkey, &r);
741
0
            assert(iter != kh_end(conn->ctx->conns_accepting));
742
0
            kh_val(conn->ctx->conns_accepting, iter) = conn;
743
0
        } else {
744
            /* likely have found a connection in `conns_accepting` */
745
0
            conn = kh_val(ctx->conns_accepting, iter);
746
0
            assert(conn != NULL);
747
0
            assert(!quicly_is_client(conn->quic));
748
0
            if (!quicly_is_destination(conn->quic, &destaddr->sa, &srcaddr->sa, packets)) {
749
0
                uint64_t offending_node_id = packets[0].cid.dest.plaintext.node_id;
750
0
                uint32_t offending_thread_id = packets[0].cid.dest.plaintext.thread_id;
751
0
                if (offending_node_id != ctx->next_cid->node_id || offending_thread_id != ctx->next_cid->thread_id) {
752
                    /* accept key matches to a connection being established, but DCID doesn't -- likely a second (or later) Initial
753
                     * that is supposed to be handled by another node. forward it. */
754
0
                    if (ctx->forward_packets != NULL)
755
0
                        ctx->forward_packets(ctx, &offending_node_id, offending_thread_id, destaddr, srcaddr, ttl, packets,
756
0
                                             num_packets);
757
0
                }
758
                /* regardless of forwarding outcome, we need to drop this packet as it is not for us */
759
0
                return;
760
0
            }
761
0
        }
762
0
    }
763
764
    /* receive packets to the found connection */
765
0
    for (size_t i = 0; i != num_packets; ++i) {
766
0
        if (i != accepted_packet_index) {
767
0
            quicly_error_t ret = quicly_receive(conn->quic, &destaddr->sa, &srcaddr->sa, packets + i);
768
0
            switch (ret) {
769
0
            case 0:
770
0
                if (ctx->quic_stats != NULL)
771
0
                    ++ctx->quic_stats->packet_processed;
772
0
                break;
773
0
            case QUICLY_ERROR_PACKET_IGNORED:
774
0
                break;
775
0
            default:
776
0
                fprintf(stderr, "%s: `quicly_receive()` returned ret:%" PRId64 "\n", __func__, ret);
777
0
                conn->callbacks->destroy_connection(conn);
778
0
                return;
779
0
            }
780
0
        }
781
0
    }
782
783
0
    h2o_quic_schedule_timer(conn);
784
0
    if (ctx->notify_conn_update != NULL)
785
0
        ctx->notify_conn_update(ctx, conn);
786
0
}
787
788
void h2o_quic_read_socket(h2o_quic_ctx_t *ctx, h2o_socket_t *sock)
789
0
{
790
0
    struct {
791
0
        quicly_address_t destaddr, srcaddr;
792
0
        struct iovec vec;
793
0
        uint8_t ttl;
794
0
        uint8_t ecn;
795
0
        union {
796
0
            struct cmsghdr _align; /* natrually align the contents of controlbuf (which are of type cmsghdr) */
797
0
            char controlbuf[
798
0
#ifdef IPV6_PKTINFO
799
0
                CMSG_SPACE(sizeof(struct in6_pktinfo))
800
#elif defined(IP_PKTINFO)
801
                CMSG_SPACE(sizeof(struct in_pktinfo))
802
#elif defined(IP_RECVDSTADDR)
803
                CMSG_SPACE(sizeof(struct in_addr))
804
#else
805
                CMSG_SPACE(1)
806
#endif
807
0
#if defined(IPV6_TCLASS) || defined(IP_TOS) || defined(IP_RECVTOS)
808
                + CMSG_SPACE(sizeof(int)) /* IPv6 uses int, which is bigger than uint8_t used by IPv4 */
809
0
#endif
810
0
            ];
811
0
        };
812
0
        uint8_t buf[1600];
813
0
    } dgrams[10];
814
0
#ifdef __linux__
815
0
    struct mmsghdr mess[PTLS_ELEMENTSOF(dgrams)];
816
#else
817
    struct {
818
        struct msghdr msg_hdr;
819
    } mess[PTLS_ELEMENTSOF(dgrams)];
820
#endif
821
822
0
#define INIT_DGRAMS(i)                                                                                                             \
823
0
    do {                                                                                                                           \
824
0
        mess[i].msg_hdr = (struct msghdr){                                                                                         \
825
0
            .msg_name = &dgrams[i].srcaddr,                                                                                        \
826
0
            .msg_namelen = sizeof(dgrams[i].srcaddr),                                                                              \
827
0
            .msg_iov = &dgrams[i].vec,                                                                                             \
828
0
            .msg_iovlen = 1,                                                                                                       \
829
0
            .msg_control = &dgrams[i].controlbuf,                                                                                  \
830
0
            .msg_controllen = sizeof(dgrams[i].controlbuf),                                                                        \
831
0
        };                                                                                                                         \
832
0
        memset(&dgrams[i].destaddr, 0, sizeof(dgrams[i].destaddr));                                                                \
833
0
        dgrams[i].vec.iov_base = dgrams[i].buf;                                                                                    \
834
0
        dgrams[i].vec.iov_len = sizeof(dgrams[i].buf);                                                                             \
835
0
    } while (0)
836
837
    /* If the socket is either ctx->sock or ctx->sock_alt_family, the destination port is that of the socket. Otherwise, the
838
     * preprocess_packet callback takes care, therefore the value can be bogus. */
839
0
    in_port_t dst_port = ctx->sock_alt_family.sock == sock ? *ctx->sock_alt_family.port : *ctx->sock.port;
840
841
0
    int fd = h2o_socket_get_fd(sock);
842
0
    size_t dgram_index, num_dgrams;
843
844
    /* Read datagrams. Sender should be provided an ACK every fraction of RTT, otherwise its behavior becomes bursty (assuming that
845
     * pacing is not used), rather than packets being spread across entire round-trip. To minimize the chance of us entering such
846
     * situation, number of datagrams being read at once is limited to `PTLS_ELEMENTSOF(dgrams)`. In other words, one ack is
847
     * generated for no more than every 10 ack-eliciting packets being received, unless the ack-frequency extension is used. */
848
0
#ifdef __linux__
849
0
    {
850
0
        int rret;
851
0
        do {
852
0
            for (dgram_index = 0; dgram_index < PTLS_ELEMENTSOF(dgrams); ++dgram_index)
853
0
                INIT_DGRAMS(dgram_index);
854
0
        } while ((rret = recvmmsg(fd, mess, PTLS_ELEMENTSOF(mess), 0, NULL)) < 0 && errno == EINTR);
855
0
        if (rret <= 0)
856
0
            goto Exit;
857
0
        num_dgrams = (size_t)rret;
858
0
        for (dgram_index = 0; dgram_index < num_dgrams; ++dgram_index)
859
0
            dgrams[dgram_index].vec.iov_len = (size_t)mess[dgram_index].msg_len;
860
0
    }
861
#else
862
    for (dgram_index = 0; dgram_index < PTLS_ELEMENTSOF(dgrams); ++dgram_index) {
863
        ssize_t rret;
864
        do {
865
            INIT_DGRAMS(dgram_index);
866
        } while ((rret = recvmsg(fd, &mess[dgram_index].msg_hdr, 0)) < 0 && errno == EINTR);
867
        if (rret < 0)
868
            break;
869
        dgrams[dgram_index].vec.iov_len = rret;
870
    }
871
    num_dgrams = dgram_index;
872
    if (num_dgrams == 0)
873
        goto Exit;
874
#endif
875
876
    /* normalize and store the obtained data into `dgrams` */
877
0
    for (dgram_index = 0; dgram_index < num_dgrams; ++dgram_index) {
878
0
        dgrams[dgram_index].ecn = 0;
879
0
        dgrams[dgram_index].destaddr.sa.sa_family = AF_UNSPEC;
880
0
        { /* fetch destination address */
881
0
            struct cmsghdr *cmsg;
882
0
            for (cmsg = CMSG_FIRSTHDR(&mess[dgram_index].msg_hdr); cmsg != NULL;
883
0
                 cmsg = CMSG_NXTHDR(&mess[dgram_index].msg_hdr, cmsg)) {
884
0
                switch (cmsg->cmsg_level) {
885
0
                case IPPROTO_IP:
886
0
                    switch (cmsg->cmsg_type) {
887
0
#ifdef IP_PKTINFO
888
0
                    case IP_PKTINFO:
889
0
                        dgrams[dgram_index].destaddr.sin.sin_family = AF_INET;
890
0
                        memcpy(&dgrams[dgram_index].destaddr.sin.sin_addr, CMSG_DATA(cmsg) + offsetof(struct in_pktinfo, ipi_addr),
891
0
                               sizeof(struct in_addr));
892
0
                        dgrams[dgram_index].destaddr.sin.sin_port = dst_port;
893
0
                        break;
894
0
#endif
895
#ifdef IP_RECVDSTADDR
896
                    case IP_RECVDSTADDR:
897
                        dgrams[dgram_index].destaddr.sin.sin_family = AF_INET;
898
                        memcpy(&dgrams[dgram_index].destaddr.sin.sin_addr, CMSG_DATA(cmsg), sizeof(struct in_addr));
899
                        dgrams[dgram_index].destaddr.sin.sin_port = dst_port;
900
                        break;
901
#endif
902
0
#ifdef IP_RECVTOS
903
#ifdef __APPLE__
904
                    case IP_RECVTOS:
905
#else
906
0
                    case IP_TOS:
907
0
#endif
908
                        /* draft-ietf-tsvwg-udp-ecn-05 recommends using a byte on all platforms */
909
0
                        dgrams[dgram_index].ecn = *(uint8_t *)CMSG_DATA(cmsg) & IPTOS_ECN_MASK;
910
0
                        break;
911
0
#endif
912
0
                    default:
913
0
                        break;
914
0
                    }
915
0
                    break;
916
0
                case IPPROTO_IPV6:
917
0
                    switch (cmsg->cmsg_type) {
918
0
#ifdef IPV6_PKTINFO
919
0
                    case IPV6_PKTINFO:
920
0
                        dgrams[dgram_index].destaddr.sin6.sin6_family = AF_INET6;
921
0
                        memcpy(&dgrams[dgram_index].destaddr.sin6.sin6_addr,
922
0
                               CMSG_DATA(cmsg) + offsetof(struct in6_pktinfo, ipi6_addr), sizeof(struct in6_addr));
923
0
                        dgrams[dgram_index].destaddr.sin6.sin6_port = dst_port;
924
0
                        break;
925
0
#endif
926
0
#ifdef IPV6_TCLASS
927
0
                    case IPV6_TCLASS: {
928
0
                        int optval;
929
0
                        memcpy(&optval, CMSG_DATA(cmsg), sizeof(optval));
930
0
                        dgrams[dgram_index].ecn = optval & IPTOS_ECN_MASK;
931
0
                    } break;
932
0
#endif
933
0
                    default:
934
0
                        break;
935
0
                    }
936
0
                    break;
937
0
                }
938
0
            }
939
0
        }
940
0
        dgrams[dgram_index].ttl = ctx->default_ttl;
941
        /* preprocess (and drop the packet if it failed) */
942
0
        if (ctx->preprocess_packet != NULL &&
943
0
            !ctx->preprocess_packet(ctx, &mess[dgram_index].msg_hdr, &dgrams[dgram_index].destaddr, &dgrams[dgram_index].srcaddr,
944
0
                                    &dgrams[dgram_index].ttl)) {
945
0
            dgrams[dgram_index].vec.iov_len = 0; /* mark as unused */
946
0
        } else {
947
0
            assert(dgrams[dgram_index].srcaddr.sa.sa_family == AF_INET || dgrams[dgram_index].srcaddr.sa.sa_family == AF_INET6);
948
0
        }
949
0
    }
950
951
    /* convert dgrams to decoded packets and process them in group of (4-tuple, dcid) */
952
0
    quicly_decoded_packet_t packets[64];
953
0
    size_t packet_index = 0;
954
0
    dgram_index = 0;
955
0
    while (dgram_index < num_dgrams) {
956
0
        int has_decoded = 0; /* indicates if a decoded packet belonging to a different connection is stored at
957
                              * `packets[packet_index]` */
958
        /* skip zero-sized datagrams (or the ones for which preprocessing failed) */
959
0
        if (dgrams[dgram_index].vec.iov_len == 0) {
960
0
            ++dgram_index;
961
0
            continue;
962
0
        }
963
        /* dispatch packets in `packets`, if the datagram at dgram_index is from a different path */
964
0
        if (packet_index != 0) {
965
0
            assert(dgram_index != 0);
966
            /* check source address */
967
0
            if (h2o_socket_compare_address(&dgrams[dgram_index - 1].srcaddr.sa, &dgrams[dgram_index].srcaddr.sa, 1) != 0)
968
0
                goto ProcessPackets;
969
            /* check destination address, if available */
970
0
            if (dgrams[dgram_index - 1].destaddr.sa.sa_family == AF_UNSPEC &&
971
0
                dgrams[dgram_index].destaddr.sa.sa_family == AF_UNSPEC) {
972
                /* ok */
973
0
            } else if (h2o_socket_compare_address(&dgrams[dgram_index - 1].destaddr.sa, &dgrams[dgram_index].destaddr.sa, 1) == 0) {
974
                /* ok */
975
0
            } else {
976
0
                goto ProcessPackets;
977
0
            }
978
            /* TTL should be same for dispatched packets */
979
0
            if (dgrams[dgram_index - 1].ttl != dgrams[dgram_index].ttl)
980
0
                goto ProcessPackets;
981
0
        }
982
        /* decode the first packet */
983
0
        size_t payload_off = 0;
984
0
        if (quicly_decode_packet(ctx->quic, packets + packet_index, dgrams[dgram_index].vec.iov_base,
985
0
                                 dgrams[dgram_index].vec.iov_len, &payload_off) == SIZE_MAX) {
986
0
            ++dgram_index;
987
0
            goto ProcessPackets;
988
0
        }
989
0
        packets[packet_index].ecn = dgrams[dgram_index].ecn;
990
        /* dispatch packets in `packets` if the DCID is different, setting the `has_decoded` flag */
991
0
        if (packet_index != 0) {
992
0
            const ptls_iovec_t *prev_dcid = &packets[packet_index - 1].cid.dest.encrypted,
993
0
                               *cur_dcid = &packets[packet_index].cid.dest.encrypted;
994
0
            if (!(prev_dcid->len == cur_dcid->len && memcmp(prev_dcid->base, cur_dcid->base, prev_dcid->len) == 0)) {
995
0
                has_decoded = 1;
996
0
                ++dgram_index;
997
0
                goto ProcessPackets;
998
0
            }
999
0
        }
1000
0
        ++packet_index;
1001
        /* add rest of the packets */
1002
0
        while (payload_off < dgrams[dgram_index].vec.iov_len && packet_index < PTLS_ELEMENTSOF(packets)) {
1003
0
            if (quicly_decode_packet(ctx->quic, packets + packet_index, dgrams[dgram_index].vec.iov_base,
1004
0
                                     dgrams[dgram_index].vec.iov_len, &payload_off) == SIZE_MAX)
1005
0
                break;
1006
0
            packets[packet_index].ecn = dgrams[dgram_index].ecn;
1007
0
            ++packet_index;
1008
0
        }
1009
0
        ++dgram_index;
1010
        /* if we have enough room for the next datagram, that is, the expected worst case of 4 packets in a coalesced datagram,
1011
         * continue */
1012
0
        if (packet_index + 4 < PTLS_ELEMENTSOF(packets))
1013
0
            continue;
1014
1015
0
    ProcessPackets:
1016
0
        if (packet_index != 0) {
1017
0
            process_packets(ctx, &dgrams[dgram_index - 1].destaddr, &dgrams[dgram_index - 1].srcaddr, dgrams[dgram_index - 1].ttl,
1018
0
                            packets, packet_index);
1019
0
            if (has_decoded) {
1020
0
                packets[0] = packets[packet_index];
1021
0
                packet_index = 1;
1022
0
            } else {
1023
0
                packet_index = 0;
1024
0
            }
1025
0
        }
1026
0
    }
1027
0
    if (packet_index != 0)
1028
0
        process_packets(ctx, &dgrams[dgram_index - 1].destaddr, &dgrams[dgram_index - 1].srcaddr, dgrams[dgram_index - 1].ttl,
1029
0
                        packets, packet_index);
1030
1031
0
Exit:;
1032
1033
0
#undef INIT_DGRAMS
1034
0
}
1035
1036
static void on_read(h2o_socket_t *sock, const char *err)
1037
0
{
1038
0
    h2o_quic_ctx_t *ctx = sock->data;
1039
0
    h2o_quic_read_socket(ctx, sock);
1040
0
}
1041
1042
static void setup_quic_socket(h2o_quic_ctx_t *ctx, h2o_quic_socket_t *qsock, h2o_socket_t *sock)
1043
0
{
1044
0
    *qsock = (h2o_quic_socket_t){.sock = sock};
1045
0
    h2o_socket_getsockname(qsock->sock, (void *)&qsock->addr);
1046
0
    switch (qsock->addr.ss_family) {
1047
0
    case AF_INET:
1048
0
        qsock->port = &((struct sockaddr_in *)&qsock->addr)->sin_port;
1049
0
        break;
1050
0
    case AF_INET6:
1051
0
        qsock->port = &((struct sockaddr_in6 *)&qsock->addr)->sin6_port;
1052
0
        break;
1053
0
    default:
1054
0
        assert(!"unexpected address family");
1055
0
        break;
1056
0
    }
1057
0
    qsock->sock->data = ctx;
1058
0
    h2o_socket_read_start(qsock->sock, on_read);
1059
0
}
1060
1061
static void on_timeout(h2o_timer_t *timeout)
1062
23.1k
{
1063
23.1k
    h2o_quic_conn_t *conn = H2O_STRUCT_FROM_MEMBER(h2o_quic_conn_t, _timeout, timeout);
1064
23.1k
    h2o_quic_send(conn);
1065
23.1k
}
1066
1067
int h2o_http3_read_frame(h2o_http3_read_frame_t *frame, int is_client, uint64_t stream_type, size_t max_frame_payload_size,
1068
                         const uint8_t **_src, const uint8_t *src_end, const char **err_desc)
1069
13.4k
{
1070
13.4k
    const uint8_t *src = *_src;
1071
1072
13.4k
    if ((frame->type = quicly_decodev(&src, src_end)) == UINT64_MAX)
1073
34
        return H2O_HTTP3_ERROR_INCOMPLETE;
1074
13.3k
    if ((frame->length = quicly_decodev(&src, src_end)) == UINT64_MAX)
1075
107
        return H2O_HTTP3_ERROR_INCOMPLETE;
1076
13.2k
    frame->_header_size = (uint8_t)(src - *_src);
1077
1078
    /* read the content of the frame (unless it's a DATA frame) */
1079
13.2k
    frame->payload = NULL;
1080
13.2k
    if (frame->type != H2O_HTTP3_FRAME_TYPE_DATA) {
1081
8.04k
        if (frame->length > max_frame_payload_size) {
1082
165
            H2O_PROBE(H3_FRAME_RECEIVE, frame->type, NULL, frame->length);
1083
165
            PTLS_LOG(h2o, h3_frame_receive, {
1084
165
                PTLS_LOG_ELEMENT_NUMBER(frame_type, frame->type);
1085
165
                PTLS_LOG_ELEMENT_NUMBER(payload_len, frame->length);
1086
165
            });
1087
165
            *err_desc = h2o_http3_err_frame_too_large;
1088
165
            return H2O_HTTP3_ERROR_GENERAL_PROTOCOL; /* FIXME is this the correct code? */
1089
165
        }
1090
7.88k
        if (src_end - src < frame->length)
1091
44
            return H2O_HTTP3_ERROR_INCOMPLETE;
1092
7.83k
        frame->payload = src;
1093
7.83k
        src += frame->length;
1094
7.83k
    }
1095
1096
13.0k
    H2O_PROBE(H3_FRAME_RECEIVE, frame->type, frame->payload, frame->length);
1097
13.0k
    PTLS_LOG(h2o, h3_frame_receive, {
1098
13.0k
        PTLS_LOG_ELEMENT_NUMBER(frame_type, frame->type);
1099
13.0k
        if (frame->payload != NULL) {
1100
13.0k
            PTLS_LOG_APPDATA_ELEMENT_HEXDUMP(payload, frame->payload, frame->length);
1101
13.0k
        } else {
1102
13.0k
            PTLS_LOG_ELEMENT_NUMBER(payload_len, frame->length);
1103
13.0k
        }
1104
13.0k
    });
1105
1106
    /* validate frame type */
1107
13.0k
    switch (frame->type) {
1108
0
#define FRAME(id, req_clnt, req_srvr, ctl_clnt, ctl_srvr)                                                                          \
1109
11.5k
    case H2O_HTTP3_FRAME_TYPE_##id:                                                                                                \
1110
11.5k
        switch (stream_type) {                                                                                                     \
1111
11.5k
        case H2O_HTTP3_STREAM_TYPE_REQUEST:                                                                                        \
1112
11.5k
            if (req_clnt && !is_client)                                                                                            \
1113
11.5k
                goto Validation_Success;                                                                                           \
1114
11.5k
            if (req_srvr && is_client)                                                                                             \
1115
19
                goto Validation_Success;                                                                                           \
1116
19
            break;                                                                                                                 \
1117
19
        case H2O_HTTP3_STREAM_TYPE_CONTROL:                                                                                        \
1118
0
            if (ctl_clnt && !is_client)                                                                                            \
1119
0
                goto Validation_Success;                                                                                           \
1120
0
            if (ctl_srvr && is_client)                                                                                             \
1121
0
                goto Validation_Success;                                                                                           \
1122
0
            break;                                                                                                                 \
1123
0
        default:                                                                                                                   \
1124
0
            h2o_fatal("unexpected stream type");                                                                                   \
1125
0
            break;                                                                                                                 \
1126
11.5k
        }                                                                                                                          \
1127
11.5k
        break
1128
        /* clang-format off */
1129
        /*   +-------------------------+-------------+-------------+
1130
         *   |                         | req-stream  | ctrl-stream |
1131
         *   |          frame          +------+------+------+------+
1132
         *   |                         |client|server|client|server|
1133
         *   +-------------------------+------+------+------+------+ */
1134
5.23k
        FRAME( DATA                    ,    1 ,    1 ,    0 ,    0 );
1135
6.33k
        FRAME( HEADERS                 ,    1 ,    1 ,    0 ,    0 );
1136
2
        FRAME( CANCEL_PUSH             ,    0 ,    0 ,    1 ,    1 );
1137
4
        FRAME( SETTINGS                ,    0 ,    0 ,    1 ,    1 );
1138
4
        FRAME( PUSH_PROMISE            ,    0 ,    1 ,    0 ,    0 );
1139
2
        FRAME( GOAWAY                  ,    0 ,    0 ,    1 ,    1 );
1140
2
        FRAME( MAX_PUSH_ID             ,    0 ,    0 ,    1 ,    0 );
1141
1
        FRAME( PRIORITY_UPDATE_REQUEST ,    0 ,    0 ,    1 ,    0 );
1142
1
        FRAME( PRIORITY_UPDATE_PUSH    ,    0 ,    0 ,    1 ,    0 );
1143
2
        FRAME( HTTP2_PRIORITY          ,    0 ,    0 ,    0 ,    0 );
1144
2
        FRAME( HTTP2_PING              ,    0 ,    0 ,    0 ,    0 );
1145
2
        FRAME( HTTP2_WINDOW_UPDATE     ,    0 ,    0 ,    0 ,    0 );
1146
2
        FRAME( HTTP2_CONTINUATION      ,    0 ,    0 ,    0 ,    0 );
1147
        /*   +-------------------------+------+------+------+------+ */
1148
        /* clang-format on */
1149
1
#undef FRAME
1150
1.48k
    default:
1151
        /* ignore extension frames that we do not handle */
1152
1.48k
        goto Validation_Success;
1153
13.0k
    }
1154
19
    return H2O_HTTP3_ERROR_FRAME_UNEXPECTED;
1155
13.0k
Validation_Success:;
1156
1157
13.0k
    *_src = src;
1158
13.0k
    return 0;
1159
13.0k
}
1160
1161
void h2o_quic_init_context(h2o_quic_ctx_t *ctx, h2o_loop_t *loop, h2o_socket_t *sock, h2o_socket_t *sock_alt_family,
1162
                           quicly_context_t *quic, quicly_cid_plaintext_t *next_cid, h2o_quic_accept_cb acceptor,
1163
                           h2o_quic_notify_connection_update_cb notify_conn_update, uint8_t use_gso, h2o_quic_stats_t *quic_stats)
1164
0
{
1165
0
    assert(quic->stream_open != NULL);
1166
1167
0
    *ctx = (h2o_quic_ctx_t){
1168
0
        .loop = loop,
1169
0
        .quic = quic,
1170
0
        .next_cid = next_cid,
1171
0
        .conns_by_id = kh_init_h2o_quic_idmap(),
1172
0
        .conns_accepting = kh_init_h2o_quic_acceptmap(),
1173
0
        .notify_conn_update = notify_conn_update,
1174
0
        .acceptor = acceptor,
1175
0
        .use_gso = use_gso,
1176
0
        .quic_stats = quic_stats,
1177
0
    };
1178
0
    setup_quic_socket(ctx, &ctx->sock, sock);
1179
0
    if (sock_alt_family != NULL) {
1180
0
        setup_quic_socket(ctx, &ctx->sock_alt_family, sock_alt_family);
1181
0
    }
1182
0
}
1183
1184
void h2o_quic_dispose_context(h2o_quic_ctx_t *ctx)
1185
0
{
1186
0
    assert(kh_size(ctx->conns_by_id) == 0);
1187
0
    assert(kh_size(ctx->conns_accepting) == 0);
1188
1189
0
    h2o_socket_close(ctx->sock.sock);
1190
0
    if (ctx->sock_alt_family.sock != NULL)
1191
0
        h2o_socket_close(ctx->sock_alt_family.sock);
1192
0
    kh_destroy_h2o_quic_idmap(ctx->conns_by_id);
1193
0
    kh_destroy_h2o_quic_acceptmap(ctx->conns_accepting);
1194
0
}
1195
1196
void h2o_quic_set_forwarding_context(h2o_quic_ctx_t *ctx, uint32_t accept_thread_divisor, uint8_t ttl,
1197
                                     h2o_quic_forward_packets_cb forward_cb, h2o_quic_preprocess_packet_cb preprocess_cb)
1198
0
{
1199
0
    ctx->accept_thread_divisor = accept_thread_divisor;
1200
0
    ctx->forward_packets = forward_cb;
1201
0
    ctx->default_ttl = ttl;
1202
0
    ctx->preprocess_packet = preprocess_cb;
1203
0
}
1204
1205
void h2o_quic_close_connection(h2o_quic_conn_t *conn, quicly_error_t err, const char *reason_phrase)
1206
4.31k
{
1207
4.31k
    switch (quicly_get_state(conn->quic)) {
1208
0
    case QUICLY_STATE_FIRSTFLIGHT: /* FIXME why is this separate? */
1209
0
        conn->callbacks->destroy_connection(conn);
1210
0
        break;
1211
4.31k
    case QUICLY_STATE_CONNECTED:
1212
4.31k
        quicly_close(conn->quic, err, reason_phrase);
1213
4.31k
        h2o_quic_schedule_timer(conn);
1214
4.31k
        break;
1215
0
    default:
1216
        /* only need to wait for the socket close */
1217
0
        break;
1218
4.31k
    }
1219
4.31k
}
1220
1221
void h2o_quic_close_all_connections(h2o_quic_ctx_t *ctx)
1222
0
{
1223
0
    h2o_quic_conn_t *conn;
1224
1225
0
    kh_foreach_value(ctx->conns_by_id, conn, { h2o_quic_close_connection(conn, 0, NULL); });
1226
    /* closing a connection should also remove an entry from conns_accepting */
1227
0
    assert(kh_size(ctx->conns_accepting) == 0);
1228
0
}
1229
1230
size_t h2o_quic_num_connections(h2o_quic_ctx_t *ctx)
1231
0
{
1232
    /* throughout its lifetime, a connection is always registered to both conns_by_id and conns_accepting,
1233
       thus counting conns_by_id is enough */
1234
0
    return kh_size(ctx->conns_by_id);
1235
0
}
1236
1237
void h2o_quic_init_conn(h2o_quic_conn_t *conn, h2o_quic_ctx_t *ctx, const h2o_quic_conn_callbacks_t *callbacks)
1238
6.78k
{
1239
6.78k
    *conn = (h2o_quic_conn_t){ctx, NULL, callbacks};
1240
6.78k
    h2o_timer_init(&conn->_timeout, on_timeout);
1241
6.78k
}
1242
1243
void h2o_quic_dispose_conn(h2o_quic_conn_t *conn)
1244
6.78k
{
1245
6.78k
    if (conn->quic != NULL) {
1246
6.78k
        khiter_t iter;
1247
        /* unregister from maps */
1248
6.78k
        if ((iter = kh_get_h2o_quic_idmap(conn->ctx->conns_by_id, quicly_get_master_id(conn->quic)->master_id)) !=
1249
6.78k
            kh_end(conn->ctx->conns_by_id))
1250
6.78k
            kh_del_h2o_quic_idmap(conn->ctx->conns_by_id, iter);
1251
6.78k
        drop_from_acceptmap(conn->ctx, conn);
1252
6.78k
        quicly_free(conn->quic);
1253
6.78k
    }
1254
6.78k
    h2o_timer_unlink(&conn->_timeout);
1255
6.78k
}
1256
1257
void h2o_quic_setup(h2o_quic_conn_t *conn, quicly_conn_t *quic)
1258
6.78k
{
1259
    /* Setup relation between `h2o_quic_conn_t` and `quicly_conn_t`. At this point, `conn` will not have `quic` associated, though
1260
     * the back pointer might have alreday been set up (see how we call `quicly_accept`). */
1261
6.78k
    assert(conn->quic == NULL);
1262
6.78k
    void **backptr = quicly_get_data(quic);
1263
6.78k
    if (*backptr == NULL) {
1264
6.78k
        *backptr = conn;
1265
6.78k
    } else {
1266
0
        assert(*backptr == conn);
1267
0
    }
1268
6.78k
    conn->quic = quic;
1269
1270
    /* register to the idmap */
1271
6.78k
    int r;
1272
6.78k
    khiter_t iter = kh_put_h2o_quic_idmap(conn->ctx->conns_by_id, quicly_get_master_id(conn->quic)->master_id, &r);
1273
6.78k
    assert(iter != kh_end(conn->ctx->conns_by_id));
1274
6.78k
    kh_val(conn->ctx->conns_by_id, iter) = conn;
1275
6.78k
}
1276
1277
void h2o_http3_init_conn(h2o_http3_conn_t *conn, h2o_quic_ctx_t *ctx, const h2o_http3_conn_callbacks_t *callbacks,
1278
                         const h2o_http3_qpack_context_t *qpack_ctx, size_t max_frame_payload_size)
1279
6.78k
{
1280
6.78k
    h2o_quic_init_conn(&conn->super, ctx, &callbacks->super);
1281
6.78k
    memset((char *)conn + sizeof(conn->super), 0, sizeof(*conn) - sizeof(conn->super));
1282
6.78k
    conn->qpack.ctx = qpack_ctx;
1283
6.78k
    conn->max_frame_payload_size = max_frame_payload_size;
1284
6.78k
}
1285
1286
void h2o_http3_dispose_conn(h2o_http3_conn_t *conn)
1287
6.78k
{
1288
6.78k
    if (conn->qpack.dec != NULL)
1289
6.78k
        h2o_qpack_destroy_decoder(conn->qpack.dec);
1290
6.78k
    if (conn->qpack.enc != NULL)
1291
0
        h2o_qpack_destroy_encoder(conn->qpack.enc);
1292
6.78k
    h2o_quic_dispose_conn(&conn->super);
1293
6.78k
}
1294
1295
static uint64_t calc_max_blocked_streams(h2o_http3_conn_t *conn)
1296
13.5k
{
1297
13.5k
    if (conn->qpack.ctx->decoder_table_capacity == 0)
1298
13.5k
        return 0;
1299
0
    uint64_t max_blocked = quicly_get_context(conn->super.quic)->transport_params.max_streams_bidi;
1300
0
    assert(max_blocked == 0 || get_callbacks(conn)->qpack_unblock_streams != NULL ||
1301
0
           !"connection enables QPACK blocked-stream support but provides no qpack_unblock_streams callback");
1302
0
    return max_blocked;
1303
0
}
1304
1305
static size_t build_firstflight(h2o_http3_conn_t *conn, uint8_t *bytebuf, size_t capacity)
1306
6.78k
{
1307
6.78k
    ptls_buffer_t buf;
1308
6.78k
    int ret = 0;
1309
6.78k
    uint64_t max_blocked_streams = calc_max_blocked_streams(conn);
1310
1311
6.78k
    ptls_buffer_init(&buf, bytebuf, capacity);
1312
1313
    /* push stream type */
1314
6.78k
    ptls_buffer_push_quicint(&buf, H2O_HTTP3_STREAM_TYPE_CONTROL);
1315
1316
    /* push SETTINGS frame */
1317
6.78k
    ptls_buffer_push_quicint(&buf, H2O_HTTP3_FRAME_TYPE_SETTINGS);
1318
6.78k
    ptls_buffer_push_block(&buf, -1, {
1319
6.78k
        quicly_context_t *qctx = quicly_get_context(conn->super.quic);
1320
6.78k
        if (qctx->transport_params.max_datagram_frame_size != 0) {
1321
            // advertise that we are prepared to receive both RFC and draft-03 datagram formats
1322
6.78k
            ptls_buffer_push_quicint(&buf, H2O_HTTP3_SETTINGS_H3_DATAGRAM);
1323
6.78k
            ptls_buffer_push_quicint(&buf, 1);
1324
6.78k
            ptls_buffer_push_quicint(&buf, H2O_HTTP3_SETTINGS_H3_DATAGRAM_DRAFT03);
1325
6.78k
            ptls_buffer_push_quicint(&buf, 1);
1326
6.78k
        };
1327
6.78k
        if (conn->qpack.ctx->decoder_table_capacity != 0) {
1328
6.78k
            ptls_buffer_push_quicint(&buf, H2O_HTTP3_SETTINGS_QPACK_MAX_TABLE_CAPACITY);
1329
6.78k
            ptls_buffer_push_quicint(&buf, conn->qpack.ctx->decoder_table_capacity);
1330
6.78k
        }
1331
6.78k
        if (max_blocked_streams != 0) {
1332
6.78k
            ptls_buffer_push_quicint(&buf, H2O_HTTP3_SETTINGS_QPACK_BLOCKED_STREAMS);
1333
6.78k
            ptls_buffer_push_quicint(&buf, max_blocked_streams);
1334
6.78k
        }
1335
6.78k
        ptls_buffer_push_quicint(&buf, H2O_HTTP3_SETTINGS_ENABLE_CONNECT_PROTOCOL);
1336
6.78k
        ptls_buffer_push_quicint(&buf, 1);
1337
6.78k
    });
1338
1339
6.78k
    assert(!buf.is_allocated);
1340
6.78k
    return buf.off;
1341
1342
0
Exit:
1343
0
    h2o_fatal("unreachable");
1344
6.78k
}
1345
1346
quicly_error_t h2o_http3_setup(h2o_http3_conn_t *conn, quicly_conn_t *quic)
1347
6.78k
{
1348
6.78k
    quicly_error_t ret;
1349
1350
6.78k
    h2o_quic_setup(&conn->super, quic);
1351
6.78k
    conn->state = H2O_HTTP3_CONN_STATE_OPEN;
1352
1353
    /* setup h3 objects, only when the connection state has been created */
1354
6.78k
    if (quicly_get_state(quic) > QUICLY_STATE_CONNECTED)
1355
0
        goto Exit;
1356
1357
6.78k
    conn->qpack.dec = h2o_qpack_create_decoder(conn->qpack.ctx->decoder_table_capacity, calc_max_blocked_streams(conn));
1358
1359
6.78k
    { /* open control streams, send SETTINGS */
1360
6.78k
        uint8_t firstflight[32];
1361
6.78k
        size_t firstflight_len = build_firstflight(conn, firstflight, sizeof(firstflight));
1362
6.78k
        if ((ret = open_egress_unistream(conn, &conn->_control_streams.egress.control, &conn->stats.bytes_sent.control_stream,
1363
6.78k
                                         h2o_iovec_init(firstflight, firstflight_len))) != 0)
1364
0
            return ret;
1365
6.78k
    }
1366
1367
6.78k
    { /* open QPACK encoder & decoder streams */
1368
6.78k
        static const uint8_t encoder_first_flight[] = {H2O_HTTP3_STREAM_TYPE_QPACK_ENCODER};
1369
6.78k
        static const uint8_t decoder_first_flight[] = {H2O_HTTP3_STREAM_TYPE_QPACK_DECODER};
1370
6.78k
        if ((ret = open_egress_unistream(conn, &conn->_control_streams.egress.qpack_encoder, &conn->stats.bytes_sent.qpack_encoder,
1371
6.78k
                                         h2o_iovec_init(encoder_first_flight, sizeof(encoder_first_flight)))) != 0 ||
1372
6.78k
            (ret = open_egress_unistream(conn, &conn->_control_streams.egress.qpack_decoder, &conn->stats.bytes_sent.qpack_decoder,
1373
6.78k
                                         h2o_iovec_init(decoder_first_flight, sizeof(decoder_first_flight)))) != 0)
1374
0
            return ret;
1375
6.78k
    }
1376
1377
6.78k
Exit:
1378
6.78k
    h2o_quic_schedule_timer(&conn->super);
1379
6.78k
    return 0;
1380
6.78k
}
1381
1382
quicly_error_t h2o_quic_send(h2o_quic_conn_t *conn)
1383
29.8k
{
1384
29.8k
    quicly_address_t dest, src;
1385
29.8k
    struct iovec datagrams[10];
1386
29.8k
    size_t num_datagrams = PTLS_ELEMENTSOF(datagrams);
1387
29.8k
    uint8_t datagram_buf[1500 * PTLS_ELEMENTSOF(datagrams)];
1388
1389
29.8k
    quicly_error_t ret = quicly_send(conn->quic, &dest, &src, datagrams, &num_datagrams, datagram_buf, sizeof(datagram_buf));
1390
29.8k
    switch (ret) {
1391
23.1k
    case 0:
1392
23.1k
        if (num_datagrams != 0 &&
1393
0
            !h2o_quic_send_datagrams(conn->ctx, &dest, &src, datagrams, num_datagrams, quicly_send_get_ecn_bits(conn->quic))) {
1394
            /* FIXME close the connection immediately */
1395
0
            break;
1396
0
        }
1397
23.1k
        break;
1398
23.1k
    default:
1399
0
        fprintf(stderr, "%s: `quicly_send()` returned ret:%" PRId64 "\n", __func__, ret);
1400
        /* fall through */
1401
0
    case QUICLY_ERROR_STATE_EXHAUSTION:
1402
6.78k
    case QUICLY_ERROR_FREE_CONNECTION:
1403
6.78k
        conn->callbacks->destroy_connection(conn);
1404
6.78k
        return 0;
1405
29.8k
    }
1406
1407
23.1k
    h2o_quic_schedule_timer(conn);
1408
1409
23.1k
    return 1;
1410
29.8k
}
1411
1412
void h2o_http3_update_recvbuf(h2o_buffer_t **buf, size_t off, const void *src, size_t len)
1413
6.78k
{
1414
6.78k
    size_t new_size = off + len;
1415
1416
6.78k
    if ((*buf)->size < new_size) {
1417
6.78k
        h2o_buffer_reserve(buf, new_size - (*buf)->size);
1418
6.78k
        (*buf)->size = new_size;
1419
6.78k
    }
1420
6.78k
    memcpy((*buf)->bytes + off, src, len);
1421
6.78k
}
1422
1423
void h2o_quic_schedule_timer(h2o_quic_conn_t *conn)
1424
39.0k
{
1425
39.0k
    int64_t timeout = quicly_get_first_timeout(conn->quic);
1426
39.0k
    if (h2o_timer_is_linked(&conn->_timeout)) {
1427
#if !H2O_USE_LIBUV /* optimization to skip registering a timer specifying the same time */
1428
15.9k
        if (timeout == conn->_timeout.expire_at)
1429
15.8k
            return;
1430
91
#endif
1431
91
        h2o_timer_unlink(&conn->_timeout);
1432
91
    }
1433
23.2k
    uint64_t now = h2o_now(conn->ctx->loop), delay = now < timeout ? timeout - now : 0;
1434
23.2k
    h2o_timer_link(conn->ctx->loop, delay, &conn->_timeout);
1435
23.2k
}
1436
1437
int h2o_http3_handle_settings_frame(h2o_http3_conn_t *conn, const uint8_t *payload, size_t length, const char **err_desc)
1438
0
{
1439
0
    const uint8_t *src = payload, *src_end = src + length;
1440
0
    uint32_t header_table_size = 0;
1441
0
    uint64_t blocked_streams = 0;
1442
1443
0
    assert(!h2o_http3_has_received_settings(conn));
1444
1445
0
    while (src != src_end) {
1446
0
        uint64_t id;
1447
0
        uint64_t value;
1448
0
        if ((id = quicly_decodev(&src, src_end)) == UINT64_MAX)
1449
0
            goto Malformed;
1450
0
        if ((value = quicly_decodev(&src, src_end)) == UINT64_MAX)
1451
0
            goto Malformed;
1452
0
        switch (id) {
1453
0
        case H2O_HTTP3_SETTINGS_MAX_FIELD_SECTION_SIZE:
1454
0
            conn->peer_settings.max_field_section_size = value;
1455
0
            break;
1456
0
        case H2O_HTTP3_SETTINGS_QPACK_MAX_TABLE_CAPACITY:
1457
0
            header_table_size =
1458
0
                value < conn->qpack.ctx->encoder_table_capacity ? (uint32_t)value : conn->qpack.ctx->encoder_table_capacity;
1459
0
            break;
1460
0
        case H2O_HTTP3_SETTINGS_QPACK_BLOCKED_STREAMS:
1461
0
            blocked_streams = value;
1462
0
            break;
1463
0
        case H2O_HTTP3_SETTINGS_H3_DATAGRAM:
1464
0
        case H2O_HTTP3_SETTINGS_H3_DATAGRAM_DRAFT03:
1465
0
            switch (value) {
1466
0
            case 0:
1467
0
                break;
1468
0
            case 1: {
1469
0
                const quicly_transport_parameters_t *remote_tp = quicly_get_remote_transport_parameters(conn->super.quic);
1470
0
                if (remote_tp->max_datagram_frame_size == 0)
1471
0
                    goto Malformed;
1472
0
                conn->peer_settings.h3_datagram = 1;
1473
0
            } break;
1474
0
            default:
1475
0
                goto Malformed;
1476
0
            }
1477
0
            break;
1478
0
        default:
1479
0
            break;
1480
0
        }
1481
0
    }
1482
1483
0
    conn->qpack.enc = h2o_qpack_create_encoder(header_table_size, blocked_streams);
1484
0
    return 0;
1485
0
Malformed:
1486
0
    *err_desc = "malformed SETTINGS frame";
1487
0
    return H2O_HTTP3_ERROR_FRAME;
1488
0
}
1489
1490
void h2o_http3_qpack_cancel_stream(h2o_http3_conn_t *conn, quicly_stream_id_t stream_id)
1491
2.46k
{
1492
2.46k
    struct st_h2o_http3_egress_unistream_t *stream = conn->_control_streams.egress.qpack_decoder;
1493
1494
    /* allocate and write */
1495
2.46k
    h2o_iovec_t buf = h2o_buffer_reserve(&stream->sendbuf, stream->sendbuf->size + H2O_HPACK_ENCODE_INT_MAX_LENGTH);
1496
2.46k
    assert(buf.base != NULL);
1497
2.46k
    stream->sendbuf->size += h2o_qpack_decoder_send_stream_cancel(conn->qpack.dec, (uint8_t *)buf.base, stream_id);
1498
1499
    /* notify the transport */
1500
2.46k
    H2O_HTTP3_CHECK_SUCCESS(quicly_stream_sync_sendbuf(stream->quic, 1) == 0);
1501
2.46k
}
1502
1503
void h2o_http3_send_qpack_header_ack(h2o_http3_conn_t *conn, const void *bytes, size_t len)
1504
0
{
1505
0
    struct st_h2o_http3_egress_unistream_t *stream = conn->_control_streams.egress.qpack_decoder;
1506
1507
0
    assert(stream != NULL);
1508
0
    h2o_buffer_append(&stream->sendbuf, bytes, len);
1509
0
    H2O_HTTP3_CHECK_SUCCESS(quicly_stream_sync_sendbuf(stream->quic, 1) == 0);
1510
0
}
1511
1512
void h2o_http3_send_shutdown_goaway_frame(h2o_http3_conn_t *conn)
1513
0
{
1514
    /* There is a moment where the transport-level close has been initiated while st_h2o_http3_server_conn_t remains.
1515
     * Check QUIC connection state to skip sending GOAWAY in such a case. */
1516
0
    if (conn->state < H2O_HTTP3_CONN_STATE_HALF_CLOSED && quicly_get_state(conn->super.quic) == QUICLY_STATE_CONNECTED) {
1517
        /* advertise the maximum stream ID to indicate that we will no longer accept new requests.
1518
         * HTTP/3 draft section 5.2.8 --
1519
         * "An endpoint that is attempting to gracefully shut down a connection can send a GOAWAY frame with a value set to the
1520
         * maximum possible value (2^62-4 for servers, 2^62-1 for clients). This ensures that the peer stops creating new
1521
         * requests or pushes." */
1522
0
        h2o_http3_send_goaway_frame(conn, (UINT64_C(1) << 62) - 4);
1523
0
    }
1524
0
}
1525
1526
void h2o_http3_send_goaway_frame(h2o_http3_conn_t *conn, uint64_t stream_or_push_id)
1527
0
{
1528
0
    size_t cap = h2o_http3_goaway_frame_capacity(stream_or_push_id);
1529
0
    h2o_iovec_t alloced = h2o_buffer_reserve(&conn->_control_streams.egress.control->sendbuf, cap);
1530
0
    h2o_http3_encode_goaway_frame((uint8_t *)alloced.base, stream_or_push_id);
1531
0
    conn->_control_streams.egress.control->sendbuf->size += cap;
1532
0
    quicly_stream_sync_sendbuf(conn->_control_streams.egress.control->quic, 1);
1533
0
}
1534
1535
void h2o_http3_send_h3_datagrams(h2o_http3_conn_t *conn, uint64_t flow_id, h2o_iovec_t *datagrams, size_t num_datagrams)
1536
0
{
1537
0
    for (size_t i = 0; i < num_datagrams; ++i) {
1538
0
        h2o_iovec_t *src = datagrams + i;
1539
0
        uint8_t buf[quicly_encodev_capacity(flow_id) + src->len], *p = buf;
1540
0
        p = quicly_encodev(p, flow_id);
1541
0
        memcpy(p, src->base, src->len);
1542
0
        p += src->len;
1543
0
        ptls_iovec_t payload = ptls_iovec_init(buf, p - buf);
1544
0
        quicly_send_datagram_frames(conn->super.quic, &payload, 1);
1545
0
    }
1546
1547
0
    h2o_quic_schedule_timer(&conn->super);
1548
0
}
1549
1550
uint64_t h2o_http3_decode_h3_datagram(h2o_iovec_t *payload, const void *_src, size_t len)
1551
0
{
1552
0
    const uint8_t *src = _src, *end = src + len;
1553
0
    uint64_t flow_id;
1554
1555
0
    if ((flow_id = ptls_decode_quicint(&src, end)) != UINT64_MAX)
1556
0
        *payload = h2o_iovec_init(src, end - src);
1557
0
    return flow_id;
1558
0
}