2 * nghttp2 - HTTP/2 C Library
4 * Copyright (c) 2019 nghttp2 contributors
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 #include "h2load_quic.h"
27 #include <netinet/udp.h>
31 #ifdef HAVE_LIBNGTCP2_CRYPTO_OPENSSL
32 # include <ngtcp2/ngtcp2_crypto_openssl.h>
33 #endif // HAVE_LIBNGTCP2_CRYPTO_OPENSSL
34 #ifdef HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
35 # include <ngtcp2/ngtcp2_crypto_boringssl.h>
36 #endif // HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
38 #include <openssl/err.h>
40 #include "h2load_http3_session.h"
45 auto randgen = util::make_mt19937();
49 int handshake_completed(ngtcp2_conn *conn, void *user_data) {
50 auto c = static_cast<Client *>(user_data);
52 if (c->quic_handshake_completed() != 0) {
53 return NGTCP2_ERR_CALLBACK_FAILURE;
60 int Client::quic_handshake_completed() { return connection_made(); }
63 int recv_stream_data(ngtcp2_conn *conn, uint32_t flags, int64_t stream_id,
64 uint64_t offset, const uint8_t *data, size_t datalen,
65 void *user_data, void *stream_user_data) {
66 auto c = static_cast<Client *>(user_data);
67 if (c->quic_recv_stream_data(flags, stream_id, data, datalen) != 0) {
68 // TODO Better to do this gracefully rather than
69 // NGTCP2_ERR_CALLBACK_FAILURE. Perhaps, call
70 // ngtcp2_conn_write_application_close() ?
71 return NGTCP2_ERR_CALLBACK_FAILURE;
77 int Client::quic_recv_stream_data(uint32_t flags, int64_t stream_id,
78 const uint8_t *data, size_t datalen) {
79 if (worker->current_phase == Phase::MAIN_DURATION) {
80 worker->stats.bytes_total += datalen;
83 auto s = static_cast<Http3Session *>(session.get());
84 auto nconsumed = s->read_stream(flags, stream_id, data, datalen);
85 if (nconsumed == -1) {
89 ngtcp2_conn_extend_max_stream_offset(quic.conn, stream_id, nconsumed);
90 ngtcp2_conn_extend_max_offset(quic.conn, nconsumed);
96 int acked_stream_data_offset(ngtcp2_conn *conn, int64_t stream_id,
97 uint64_t offset, uint64_t datalen, void *user_data,
98 void *stream_user_data) {
99 auto c = static_cast<Client *>(user_data);
100 if (c->quic_acked_stream_data_offset(stream_id, datalen) != 0) {
101 return NGTCP2_ERR_CALLBACK_FAILURE;
107 int Client::quic_acked_stream_data_offset(int64_t stream_id, size_t datalen) {
108 auto s = static_cast<Http3Session *>(session.get());
109 if (s->add_ack_offset(stream_id, datalen) != 0) {
116 int stream_close(ngtcp2_conn *conn, uint32_t flags, int64_t stream_id,
117 uint64_t app_error_code, void *user_data,
118 void *stream_user_data) {
119 auto c = static_cast<Client *>(user_data);
121 if (!(flags & NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET)) {
122 app_error_code = NGHTTP3_H3_NO_ERROR;
125 if (c->quic_stream_close(stream_id, app_error_code) != 0) {
132 int Client::quic_stream_close(int64_t stream_id, uint64_t app_error_code) {
133 auto s = static_cast<Http3Session *>(session.get());
134 if (s->close_stream(stream_id, app_error_code) != 0) {
141 int stream_reset(ngtcp2_conn *conn, int64_t stream_id, uint64_t final_size,
142 uint64_t app_error_code, void *user_data,
143 void *stream_user_data) {
144 auto c = static_cast<Client *>(user_data);
145 if (c->quic_stream_reset(stream_id, app_error_code) != 0) {
152 int Client::quic_stream_reset(int64_t stream_id, uint64_t app_error_code) {
153 auto s = static_cast<Http3Session *>(session.get());
154 if (s->shutdown_stream_read(stream_id) != 0) {
161 int stream_stop_sending(ngtcp2_conn *conn, int64_t stream_id,
162 uint64_t app_error_code, void *user_data,
163 void *stream_user_data) {
164 auto c = static_cast<Client *>(user_data);
165 if (c->quic_stream_stop_sending(stream_id, app_error_code) != 0) {
172 int Client::quic_stream_stop_sending(int64_t stream_id,
173 uint64_t app_error_code) {
174 auto s = static_cast<Http3Session *>(session.get());
175 if (s->shutdown_stream_read(stream_id) != 0) {
182 int extend_max_local_streams_bidi(ngtcp2_conn *conn, uint64_t max_streams,
184 auto c = static_cast<Client *>(user_data);
186 if (c->quic_extend_max_local_streams() != 0) {
187 return NGTCP2_ERR_CALLBACK_FAILURE;
194 int Client::quic_extend_max_local_streams() {
195 auto s = static_cast<Http3Session *>(session.get());
196 if (s->extend_max_local_streams() != 0) {
197 return NGTCP2_ERR_CALLBACK_FAILURE;
203 int get_new_connection_id(ngtcp2_conn *conn, ngtcp2_cid *cid, uint8_t *token,
204 size_t cidlen, void *user_data) {
205 auto dis = std::uniform_int_distribution<uint8_t>(
206 0, std::numeric_limits<uint8_t>::max());
207 auto f = [&dis]() { return dis(randgen); };
209 std::generate_n(cid->data, cidlen, f);
210 cid->datalen = cidlen;
211 std::generate_n(token, NGTCP2_STATELESS_RESET_TOKENLEN, f);
218 void debug_log_printf(void *user_data, const char *fmt, ...) {
222 vfprintf(stderr, fmt, ap);
225 fprintf(stderr, "\n");
230 void generate_cid(ngtcp2_cid &dest) {
231 auto dis = std::uniform_int_distribution<uint8_t>(
232 0, std::numeric_limits<uint8_t>::max());
234 std::generate_n(dest.data, dest.datalen, [&dis]() { return dis(randgen); });
239 ngtcp2_tstamp timestamp(struct ev_loop *loop) {
240 return ev_now(loop) * NGTCP2_SECONDS;
244 #ifdef HAVE_LIBNGTCP2_CRYPTO_OPENSSL
246 int set_encryption_secrets(SSL *ssl, OSSL_ENCRYPTION_LEVEL ossl_level,
247 const uint8_t *rx_secret, const uint8_t *tx_secret,
249 auto c = static_cast<Client *>(SSL_get_app_data(ssl));
250 auto level = ngtcp2_crypto_openssl_from_ossl_encryption_level(ossl_level);
252 if (c->quic_on_rx_secret(level, rx_secret, secret_len) != 0) {
256 if (c->quic_on_tx_secret(level, tx_secret, secret_len) != 0) {
265 int add_handshake_data(SSL *ssl, OSSL_ENCRYPTION_LEVEL ossl_level,
266 const uint8_t *data, size_t len) {
267 auto c = static_cast<Client *>(SSL_get_app_data(ssl));
268 c->quic_write_client_handshake(
269 ngtcp2_crypto_openssl_from_ossl_encryption_level(ossl_level), data, len);
275 int flush_flight(SSL *ssl) { return 1; }
279 int send_alert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert) {
280 auto c = static_cast<Client *>(SSL_get_app_data(ssl));
281 c->quic_set_tls_alert(alert);
287 auto quic_method = SSL_QUIC_METHOD{
288 set_encryption_secrets,
294 #endif // HAVE_LIBNGTCP2_CRYPTO_OPENSSL
296 #ifdef HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
298 int set_read_secret(SSL *ssl, ssl_encryption_level_t ssl_level,
299 const SSL_CIPHER *cipher, const uint8_t *secret,
301 auto c = static_cast<Client *>(SSL_get_app_data(ssl));
303 if (c->quic_on_rx_secret(
304 ngtcp2_crypto_boringssl_from_ssl_encryption_level(ssl_level), secret,
314 int set_write_secret(SSL *ssl, ssl_encryption_level_t ssl_level,
315 const SSL_CIPHER *cipher, const uint8_t *secret,
317 auto c = static_cast<Client *>(SSL_get_app_data(ssl));
319 if (c->quic_on_tx_secret(
320 ngtcp2_crypto_boringssl_from_ssl_encryption_level(ssl_level), secret,
330 int add_handshake_data(SSL *ssl, ssl_encryption_level_t ssl_level,
331 const uint8_t *data, size_t len) {
332 auto c = static_cast<Client *>(SSL_get_app_data(ssl));
333 c->quic_write_client_handshake(
334 ngtcp2_crypto_boringssl_from_ssl_encryption_level(ssl_level), data, len);
340 int flush_flight(SSL *ssl) { return 1; }
344 int send_alert(SSL *ssl, ssl_encryption_level_t level, uint8_t alert) {
345 auto c = static_cast<Client *>(SSL_get_app_data(ssl));
346 c->quic_set_tls_alert(alert);
352 auto quic_method = SSL_QUIC_METHOD{
353 set_read_secret, set_write_secret, add_handshake_data,
354 flush_flight, send_alert,
357 #endif // HAVE_LIBNGTCP2_CRYPTO_BORINGSSL
359 // qlog write callback -- excerpted from ngtcp2/examples/client_base.cc
361 void qlog_write_cb(void *user_data, uint32_t flags, const void *data,
363 auto c = static_cast<Client *>(user_data);
364 c->quic_write_qlog(data, datalen);
368 void Client::quic_write_qlog(const void *data, size_t datalen) {
369 assert(quic.qlog_file != nullptr);
370 fwrite(data, 1, datalen, quic.qlog_file);
373 int Client::quic_init(const sockaddr *local_addr, socklen_t local_addrlen,
374 const sockaddr *remote_addr, socklen_t remote_addrlen) {
378 ssl = SSL_new(worker->ssl_ctx);
380 SSL_set_app_data(ssl, this);
381 SSL_set_connect_state(ssl);
382 SSL_set_quic_method(ssl, &quic_method);
383 SSL_set_quic_use_legacy_codepoint(ssl, 0);
386 auto callbacks = ngtcp2_callbacks{
387 ngtcp2_crypto_client_initial_cb,
388 nullptr, // recv_client_initial
389 ngtcp2_crypto_recv_crypto_data_cb,
390 h2load::handshake_completed,
391 nullptr, // recv_version_negotiation
392 ngtcp2_crypto_encrypt_cb,
393 ngtcp2_crypto_decrypt_cb,
394 ngtcp2_crypto_hp_mask_cb,
395 h2load::recv_stream_data,
396 h2load::acked_stream_data_offset,
397 nullptr, // stream_open
398 h2load::stream_close,
399 nullptr, // recv_stateless_reset
400 ngtcp2_crypto_recv_retry_cb,
401 h2load::extend_max_local_streams_bidi,
402 nullptr, // extend_max_local_streams_uni
404 get_new_connection_id,
405 nullptr, // remove_connection_id
406 ngtcp2_crypto_update_key_cb,
407 nullptr, // path_validation
408 nullptr, // select_preferred_addr
409 h2load::stream_reset,
410 nullptr, // extend_max_remote_streams_bidi
411 nullptr, // extend_max_remote_streams_uni
412 nullptr, // extend_max_stream_data
413 nullptr, // dcid_status
414 nullptr, // handshake_confirmed
415 nullptr, // recv_new_token
416 ngtcp2_crypto_delete_crypto_aead_ctx_cb,
417 ngtcp2_crypto_delete_crypto_cipher_ctx_cb,
418 nullptr, // recv_datagram
419 nullptr, // ack_datagram
420 nullptr, // lost_datagram
421 nullptr, // get_path_challenge_data
422 h2load::stream_stop_sending,
425 ngtcp2_cid scid, dcid;
429 auto config = worker->config;
431 ngtcp2_settings settings;
432 ngtcp2_settings_default(&settings);
433 if (config->verbose) {
434 settings.log_printf = debug_log_printf;
436 settings.initial_ts = timestamp(worker->loop);
437 if (!config->qlog_file_base.empty()) {
438 assert(quic.qlog_file == nullptr);
439 auto path = config->qlog_file_base;
441 path += util::utos(worker->id);
443 path += util::utos(id);
445 quic.qlog_file = fopen(path.c_str(), "w");
446 if (quic.qlog_file == nullptr) {
447 std::cerr << "Failed to open a qlog file: " << path << std::endl;
450 settings.qlog.write = qlog_write_cb;
452 if (config->max_udp_payload_size) {
453 settings.max_udp_payload_size = config->max_udp_payload_size;
454 settings.no_udp_payload_size_shaping = 1;
457 ngtcp2_transport_params params;
458 ngtcp2_transport_params_default(¶ms);
459 auto max_stream_data =
460 std::min((1 << 26) - 1, (1 << config->window_bits) - 1);
461 params.initial_max_stream_data_bidi_local = max_stream_data;
462 params.initial_max_stream_data_uni = max_stream_data;
463 params.initial_max_data = (1 << config->connection_window_bits) - 1;
464 params.initial_max_streams_bidi = 0;
465 params.initial_max_streams_uni = 100;
466 params.max_idle_timeout = 30 * NGTCP2_SECONDS;
468 auto path = ngtcp2_path{
469 {local_addrlen, const_cast<sockaddr *>(local_addr)},
470 {remote_addrlen, const_cast<sockaddr *>(remote_addr)},
473 assert(config->npn_list.size());
475 uint32_t quic_version;
477 if (config->npn_list[0] == NGHTTP3_ALPN_H3) {
478 quic_version = NGTCP2_PROTO_VER_V1;
480 quic_version = NGTCP2_PROTO_VER_MIN;
483 rv = ngtcp2_conn_client_new(&quic.conn, &dcid, &scid, &path, quic_version,
484 &callbacks, &settings, ¶ms, nullptr, this);
489 ngtcp2_conn_set_tls_native_handle(quic.conn, ssl);
494 void Client::quic_free() {
495 ngtcp2_conn_del(quic.conn);
496 if (quic.qlog_file != nullptr) {
497 fclose(quic.qlog_file);
498 quic.qlog_file = nullptr;
502 void Client::quic_close_connection() {
507 std::array<uint8_t, NGTCP2_MAX_UDP_PAYLOAD_SIZE> buf;
509 ngtcp2_path_storage ps;
510 ngtcp2_path_storage_zero(&ps);
512 switch (quic.last_error.type) {
513 case quic::ErrorType::TransportVersionNegotiation:
515 case quic::ErrorType::Transport:
516 nwrite = ngtcp2_conn_write_connection_close(
517 quic.conn, &ps.path, nullptr, buf.data(), buf.size(),
518 quic.last_error.code, timestamp(worker->loop));
520 case quic::ErrorType::Application:
521 nwrite = ngtcp2_conn_write_application_close(
522 quic.conn, &ps.path, nullptr, buf.data(), buf.size(),
523 quic.last_error.code, timestamp(worker->loop));
534 write_udp(reinterpret_cast<sockaddr *>(ps.path.remote.addr),
535 ps.path.remote.addrlen, buf.data(), nwrite, 0);
538 int Client::quic_on_rx_secret(ngtcp2_crypto_level level, const uint8_t *secret,
540 if (ngtcp2_crypto_derive_and_install_rx_key(quic.conn, nullptr, nullptr,
541 nullptr, level, secret,
543 std::cerr << "ngtcp2_crypto_derive_and_install_rx_key() failed"
548 if (level == NGTCP2_CRYPTO_LEVEL_APPLICATION) {
549 auto s = std::make_unique<Http3Session>(this);
550 if (s->init_conn() == -1) {
553 session = std::move(s);
559 int Client::quic_on_tx_secret(ngtcp2_crypto_level level, const uint8_t *secret,
561 if (ngtcp2_crypto_derive_and_install_tx_key(quic.conn, nullptr, nullptr,
562 nullptr, level, secret,
564 std::cerr << "ngtcp2_crypto_derive_and_install_tx_key() failed"
572 void Client::quic_set_tls_alert(uint8_t alert) {
573 quic.last_error = quic::err_transport_tls(alert);
576 void Client::quic_write_client_handshake(ngtcp2_crypto_level level,
577 const uint8_t *data, size_t datalen) {
580 ngtcp2_conn_submit_crypto_data(quic.conn, level, data, datalen);
583 void quic_pkt_timeout_cb(struct ev_loop *loop, ev_timer *w, int revents) {
584 auto c = static_cast<Client *>(w->data);
586 if (c->quic_pkt_timeout() != 0) {
588 c->worker->free_client(c);
594 int Client::quic_pkt_timeout() {
596 auto now = timestamp(worker->loop);
598 rv = ngtcp2_conn_handle_expiry(quic.conn, now);
600 quic.last_error = quic::err_transport(NGTCP2_ERR_INTERNAL);
607 void Client::quic_restart_pkt_timer() {
608 auto expiry = ngtcp2_conn_get_expiry(quic.conn);
609 auto now = timestamp(worker->loop);
610 auto t = expiry > now ? static_cast<ev_tstamp>(expiry - now) / NGTCP2_SECONDS
612 quic.pkt_timer.repeat = t;
613 ev_timer_again(worker->loop, &quic.pkt_timer);
616 int Client::read_quic() {
617 std::array<uint8_t, 65536> buf;
619 socklen_t addrlen = sizeof(su);
622 ngtcp2_pkt_info pi{};
626 recvfrom(fd, buf.data(), buf.size(), MSG_DONTWAIT, &su.sa, &addrlen);
633 ++worker->stats.udp_dgram_recv;
635 auto path = ngtcp2_path{
636 {local_addr.len, &local_addr.su.sa},
640 rv = ngtcp2_conn_read_pkt(quic.conn, &path, &pi, buf.data(), nread,
641 timestamp(worker->loop));
643 std::cerr << "ngtcp2_conn_read_pkt: " << ngtcp2_strerror(rv) << std::endl;
647 if (++pktcnt == 100) {
655 int Client::write_quic() {
656 ev_io_stop(worker->loop, &wev);
658 if (quic.close_requested) {
662 std::array<nghttp3_vec, 16> vec;
664 auto max_udp_payload_size =
665 ngtcp2_conn_get_path_max_udp_payload_size(quic.conn);
668 worker->config->no_udp_gso
670 : std::min(static_cast<size_t>(10),
671 static_cast<size_t>(64_k / max_udp_payload_size));
672 #else // !UDP_SEGMENT
674 #endif // !UDP_SEGMENT
675 std::array<uint8_t, 64_k> buf;
676 uint8_t *bufpos = buf.data();
677 ngtcp2_path_storage ps;
679 ngtcp2_path_storage_zero(&ps);
681 auto s = static_cast<Http3Session *>(session.get());
684 int64_t stream_id = -1;
688 if (session && ngtcp2_conn_get_max_data_left(quic.conn)) {
689 sveccnt = s->write_stream(stream_id, fin, vec.data(), vec.size());
695 ngtcp2_ssize ndatalen;
697 auto vcnt = static_cast<size_t>(sveccnt);
699 uint32_t flags = NGTCP2_WRITE_STREAM_FLAG_MORE;
701 flags |= NGTCP2_WRITE_STREAM_FLAG_FIN;
704 auto nwrite = ngtcp2_conn_writev_stream(
705 quic.conn, &ps.path, nullptr, bufpos, max_udp_payload_size, &ndatalen,
706 flags, stream_id, reinterpret_cast<const ngtcp2_vec *>(v), vcnt,
707 timestamp(worker->loop));
710 case NGTCP2_ERR_STREAM_DATA_BLOCKED:
711 assert(ndatalen == -1);
712 if (s->block_stream(stream_id) != 0) {
716 case NGTCP2_ERR_STREAM_SHUT_WR:
717 assert(ndatalen == -1);
718 if (s->shutdown_stream_write(stream_id) != 0) {
722 case NGTCP2_ERR_WRITE_MORE:
723 assert(ndatalen >= 0);
724 if (s->add_write_offset(stream_id, ndatalen) != 0) {
730 quic.last_error = quic::err_transport(nwrite);
732 } else if (ndatalen >= 0 && s->add_write_offset(stream_id, ndatalen) != 0) {
736 quic_restart_pkt_timer();
739 if (bufpos - buf.data()) {
740 write_udp(ps.path.remote.addr, ps.path.remote.addrlen, buf.data(),
741 bufpos - buf.data(), max_udp_payload_size);
748 // Assume that the path does not change.
749 if (++pktcnt == max_pktcnt ||
750 static_cast<size_t>(nwrite) < max_udp_payload_size) {
751 write_udp(ps.path.remote.addr, ps.path.remote.addrlen, buf.data(),
752 bufpos - buf.data(), max_udp_payload_size);
759 } // namespace h2load