deps: update ngtcp2 to 1.22.0

PR-URL: https://github.com/nodejs/node/pull/62595
Backport-PR-URL: https://github.com/nodejs/node/pull/64675
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com>
This commit is contained in:
Node.js GitHub Bot authored and Antoine du Hamel committed 2026-08-06 11:32:47 +02:00
1 parent 4309e7c82f
commit 080c4d7cda
114 files changed
+5238 -4361

No files matched your search

+27 -3
View File
@@ -402,7 +402,7 @@ int ngtcp2_crypto_decrypt(uint8_t *dest, const ngtcp2_crypto_aead *aead,
int ngtcp2_crypto_hp_mask(uint8_t *dest, const ngtcp2_crypto_cipher *hp,
const ngtcp2_crypto_cipher_ctx *hp_ctx,
const uint8_t *sample) {
static const uint8_t PLAINTEXT[] = "\x00\x00\x00\x00\x00";
static const uint8_t PLAINTEXT[16] = {0};
ngtcp2_crypto_boringssl_cipher_ctx *ctx = hp_ctx->native_handle;
uint32_t counter;
@@ -420,7 +420,7 @@ int ngtcp2_crypto_hp_mask(uint8_t *dest, const ngtcp2_crypto_cipher *hp,
#else /* !defined(WORDS_BIGENDIAN) */
memcpy(&counter, sample, sizeof(counter));
#endif /* !defined(WORDS_BIGENDIAN) */
CRYPTO_chacha_20(dest, PLAINTEXT, ngtcp2_strlen_lit(PLAINTEXT), ctx->key,
CRYPTO_chacha_20(dest, PLAINTEXT, sizeof(PLAINTEXT), ctx->key,
sample + sizeof(counter), counter);
return 0;
default:
@@ -436,7 +436,8 @@ int ngtcp2_crypto_read_write_crypto_data(
int rv;
int err;
if (SSL_provide_quic_data(
if (datalen &&
SSL_provide_quic_data(
ssl,
ngtcp2_crypto_boringssl_from_ngtcp2_encryption_level(encryption_level),
data, datalen) != 1) {
@@ -465,6 +466,16 @@ int ngtcp2_crypto_read_write_crypto_data(
}
goto retry;
case SSL_ERROR_WANT_X509_LOOKUP:
case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
case SSL_ERROR_WANT_CERTIFICATE_VERIFY:
/* It might be better to return this error, but ngtcp2 does
not need to know whether handshake has been interrupted or
not. We expect that necessary plumbing should be done by
application when handshake is interrupted (e.g., via
SSL_PRIVATE_KEY_METHOD). If it does not work, we will
reconsider this. */
return 0;
default:
return -1;
}
@@ -568,6 +579,19 @@ int ngtcp2_crypto_get_path_challenge_data_cb(ngtcp2_conn *conn, uint8_t *data,
return 0;
}
int ngtcp2_crypto_get_path_challenge_data2_cb(ngtcp2_conn *conn,
ngtcp2_path_challenge_data *data,
void *user_data) {
(void)conn;
(void)user_data;
if (RAND_bytes(data->data, NGTCP2_PATH_CHALLENGE_DATALEN) != 1) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
return 0;
}
int ngtcp2_crypto_random(uint8_t *data, size_t datalen) {
if (RAND_bytes(data, datalen) != 1) {
return -1;
+39 -7
View File
@@ -524,11 +524,14 @@ NGTCP2_EXTERN int ngtcp2_crypto_recv_client_initial_cb(ngtcp2_conn *conn,
* completes. It is allowed to call this function with |datalen| ==
* 0. In this case, no additional read operation is done.
*
* This function is implemented per TLS backend. See
* :ref:`tls-integration` for more details.
*
* This function returns 0 if it succeeds, or a negative error code.
* The generic error code is -1 if a specific error code is not
* suitable. The error codes less than -10000 are specific to
* underlying TLS implementation. For quictls, the error codes are
* defined in *ngtcp2_crypto_quictls.h*.
* underlying TLS implementation. Refer to the implementation
* specific header files for error codes.
*/
NGTCP2_EXTERN int
ngtcp2_crypto_read_write_crypto_data(ngtcp2_conn *conn,
@@ -542,11 +545,22 @@ ngtcp2_crypto_read_write_crypto_data(ngtcp2_conn *conn,
* `ngtcp2_crypto_read_write_crypto_data`. It can be directly passed
* to :member:`ngtcp2_callbacks.recv_crypto_data` field.
*
* For quictls and OpenSSL, the following error codes are treated as
* success:
*
* - -10001 (e.g., :macro:`NGTCP2_CRYPTO_QUICTLS_ERR_TLS_WANT_X509_LOOKUP`)
* - -10002 (e.g., :macro:`NGTCP2_CRYPTO_QUICTLS_ERR_TLS_WANT_CLIENT_HELLO_CB`)
*
* To continue the interrupted handshake, call
* `ngtcp2_conn_continue_handshake`.
*
* See :ref:`tls-integration` for more details.
*
* If this function is used, the TLS implementation specific error
* codes described in `ngtcp2_crypto_read_write_crypto_data` are
* treated as if it returns -1. Do not use this function if an
* application wishes to use the TLS implementation specific error
* codes.
* treated as if it returns -1 except for those that are listed above.
* Do not use this function if an application wishes to use the TLS
* implementation specific error codes.
*/
NGTCP2_EXTERN int ngtcp2_crypto_recv_crypto_data_cb(
ngtcp2_conn *conn, ngtcp2_encryption_level encryption_level, uint64_t offset,
@@ -583,7 +597,7 @@ NGTCP2_EXTERN int ngtcp2_crypto_generate_stateless_reset_token(
* :macro:`NGTCP2_CRYPTO_TOKEN_MAGIC_RETRY` is the magic byte for
* Retry token generated by `ngtcp2_crypto_generate_retry_token`.
*/
#define NGTCP2_CRYPTO_TOKEN_MAGIC_RETRY 0xb6
#define NGTCP2_CRYPTO_TOKEN_MAGIC_RETRY 0xB6
/**
* @macro
@@ -591,7 +605,7 @@ NGTCP2_EXTERN int ngtcp2_crypto_generate_stateless_reset_token(
* :macro:`NGTCP2_CRYPTO_TOKEN_MAGIC_RETRY2` is the magic byte for
* Retry token generated by `ngtcp2_crypto_generate_retry_token2`.
*/
#define NGTCP2_CRYPTO_TOKEN_MAGIC_RETRY2 0xb7
#define NGTCP2_CRYPTO_TOKEN_MAGIC_RETRY2 0xB7
/**
* @macro
@@ -978,11 +992,29 @@ NGTCP2_EXTERN void ngtcp2_crypto_delete_crypto_cipher_ctx_cb(
*
* This function can be directly passed to
* :member:`ngtcp2_callbacks.get_path_challenge_data` field.
*
* Deprecated since v1.22.0. Use
* `ngtcp2_crypto_get_path_challenge_data2_cb` instead.
*/
NGTCP2_EXTERN int ngtcp2_crypto_get_path_challenge_data_cb(ngtcp2_conn *conn,
uint8_t *data,
void *user_data);
/**
* @function
*
* `ngtcp2_crypto_get_path_challenge_data2_cb` writes unpredictable
* sequence of :macro:`NGTCP2_PATH_CHALLENGE_DATALEN` bytes to |data|
* which is sent with PATH_CHALLENGE frame.
*
* This function can be directly passed to
* :member:`ngtcp2_callbacks.get_path_challenge_data2` field.
*
* This function has been available since v1.22.0.
*/
NGTCP2_EXTERN int ngtcp2_crypto_get_path_challenge_data2_cb(
ngtcp2_conn *conn, ngtcp2_path_challenge_data *data, void *user_data);
/**
* @function
*
+48 -21
View File
@@ -49,8 +49,8 @@
static EVP_CIPHER *crypto_aes_128_gcm;
static EVP_CIPHER *crypto_aes_256_gcm;
static EVP_CIPHER *crypto_aes_128_ccm;
static EVP_CIPHER *crypto_aes_128_ctr;
static EVP_CIPHER *crypto_aes_256_ctr;
static EVP_CIPHER *crypto_aes_128_ecb;
static EVP_CIPHER *crypto_aes_256_ecb;
#ifndef NGTCP2_NO_CHACHA_POLY1305
static EVP_CIPHER *crypto_chacha20_poly1305;
static EVP_CIPHER *crypto_chacha20;
@@ -66,8 +66,8 @@ int ngtcp2_crypto_ossl_init(void) {
crypto_aes_128_gcm = EVP_CIPHER_fetch(NULL, "AES-128-GCM", NULL);
crypto_aes_256_gcm = EVP_CIPHER_fetch(NULL, "AES-256-GCM", NULL);
crypto_aes_128_ccm = EVP_CIPHER_fetch(NULL, "AES-128-CCM", NULL);
crypto_aes_128_ctr = EVP_CIPHER_fetch(NULL, "AES-128-CTR", NULL);
crypto_aes_256_ctr = EVP_CIPHER_fetch(NULL, "AES-256-CTR", NULL);
crypto_aes_128_ecb = EVP_CIPHER_fetch(NULL, "AES-128-ECB", NULL);
crypto_aes_256_ecb = EVP_CIPHER_fetch(NULL, "AES-256-ECB", NULL);
#ifndef NGTCP2_NO_CHACHA_POLY1305
crypto_chacha20_poly1305 = EVP_CIPHER_fetch(NULL, "ChaCha20-Poly1305", NULL);
crypto_chacha20 = EVP_CIPHER_fetch(NULL, "ChaCha20", NULL);
@@ -113,20 +113,20 @@ static const EVP_CIPHER *crypto_aead_aes_128_ccm(void) {
return EVP_aes_128_ccm();
}
static const EVP_CIPHER *crypto_cipher_aes_128_ctr(void) {
if (crypto_aes_128_ctr) {
return crypto_aes_128_ctr;
static const EVP_CIPHER *crypto_cipher_aes_128_ecb(void) {
if (crypto_aes_128_ecb) {
return crypto_aes_128_ecb;
}
return EVP_aes_128_ctr();
return EVP_aes_128_ecb();
}
static const EVP_CIPHER *crypto_cipher_aes_256_ctr(void) {
if (crypto_aes_256_ctr) {
return crypto_aes_256_ctr;
static const EVP_CIPHER *crypto_cipher_aes_256_ecb(void) {
if (crypto_aes_256_ecb) {
return crypto_aes_256_ecb;
}
return EVP_aes_256_ctr();
return EVP_aes_256_ecb();
}
#ifndef NGTCP2_NO_CHACHA_POLY1305
@@ -198,7 +198,7 @@ ngtcp2_crypto_md *ngtcp2_crypto_md_sha256(ngtcp2_crypto_md *md) {
ngtcp2_crypto_ctx *ngtcp2_crypto_ctx_initial(ngtcp2_crypto_ctx *ctx) {
ngtcp2_crypto_aead_init(&ctx->aead, (void *)crypto_aead_aes_128_gcm());
ctx->md.native_handle = (void *)crypto_md_sha256();
ctx->hp.native_handle = (void *)crypto_cipher_aes_128_ctr();
ctx->hp.native_handle = (void *)crypto_cipher_aes_128_ecb();
ctx->max_encryption = 0;
ctx->max_decryption_failure = 0;
return ctx;
@@ -269,9 +269,9 @@ static const EVP_CIPHER *crypto_cipher_id_get_hp(uint32_t cipher_id) {
switch (cipher_id) {
case TLS1_3_CK_AES_128_GCM_SHA256:
case TLS1_3_CK_AES_128_CCM_SHA256:
return crypto_cipher_aes_128_ctr();
return crypto_cipher_aes_128_ecb();
case TLS1_3_CK_AES_256_GCM_SHA384:
return crypto_cipher_aes_256_ctr();
return crypto_cipher_aes_256_ecb();
#ifndef NGTCP2_NO_CHACHA_POLY1305
case TLS1_3_CK_CHACHA20_POLY1305_SHA256:
return crypto_cipher_chacha20();
@@ -838,17 +838,31 @@ int ngtcp2_crypto_decrypt(uint8_t *dest, const ngtcp2_crypto_aead *aead,
int ngtcp2_crypto_hp_mask(uint8_t *dest, const ngtcp2_crypto_cipher *hp,
const ngtcp2_crypto_cipher_ctx *hp_ctx,
const uint8_t *sample) {
static const uint8_t PLAINTEXT[] = "\x00\x00\x00\x00\x00";
static const uint8_t PLAINTEXT[16] = {0};
EVP_CIPHER_CTX *actx = hp_ctx->native_handle;
int len;
(void)hp;
if (!EVP_EncryptInit_ex(actx, NULL, NULL, NULL, sample) ||
!EVP_EncryptUpdate(actx, dest, &len, PLAINTEXT,
ngtcp2_strlen_lit(PLAINTEXT)) ||
!EVP_EncryptFinal_ex(actx, dest + ngtcp2_strlen_lit(PLAINTEXT), &len)) {
return -1;
switch (EVP_CIPHER_CTX_nid(actx)) {
case NID_aes_128_ecb:
case NID_aes_256_ecb:
if (!EVP_EncryptUpdate(actx, dest, &len, sample, NGTCP2_HP_SAMPLELEN)) {
return -1;
}
break;
case NID_chacha20:
if (!EVP_EncryptInit_ex(actx, NULL, NULL, NULL, sample) ||
!EVP_EncryptUpdate(actx, dest, &len, PLAINTEXT, sizeof(PLAINTEXT)) ||
!EVP_EncryptFinal_ex(actx, dest + sizeof(PLAINTEXT), &len)) {
return -1;
}
break;
default:
assert(0);
abort();
}
return 0;
@@ -983,6 +997,19 @@ int ngtcp2_crypto_get_path_challenge_data_cb(ngtcp2_conn *conn, uint8_t *data,
return 0;
}
int ngtcp2_crypto_get_path_challenge_data2_cb(ngtcp2_conn *conn,
ngtcp2_path_challenge_data *data,
void *user_data) {
(void)conn;
(void)user_data;
if (RAND_bytes(data->data, NGTCP2_PATH_CHALLENGE_DATALEN) != 1) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
return 0;
}
int ngtcp2_crypto_random(uint8_t *data, size_t datalen) {
if (RAND_bytes(data, (int)datalen) != 1) {
return -1;
+30 -8
View File
@@ -50,7 +50,7 @@ ngtcp2_crypto_md *ngtcp2_crypto_md_sha256(ngtcp2_crypto_md *md) {
ngtcp2_crypto_ctx *ngtcp2_crypto_ctx_initial(ngtcp2_crypto_ctx *ctx) {
ngtcp2_crypto_aead_init(&ctx->aead, (void *)&ptls_openssl_aes128gcm);
ctx->md.native_handle = (void *)&ptls_openssl_sha256;
ctx->hp.native_handle = (void *)&ptls_openssl_aes128ctr;
ctx->hp.native_handle = (void *)&ptls_openssl_aes128ecb;
ctx->max_encryption = 0;
ctx->max_decryption_failure = 0;
return ctx;
@@ -104,11 +104,11 @@ crypto_cipher_suite_get_aead_max_decryption_failure(ptls_cipher_suite_t *cs) {
static const ptls_cipher_algorithm_t *
crypto_cipher_suite_get_hp(ptls_cipher_suite_t *cs) {
if (cs->aead == &ptls_openssl_aes128gcm) {
return &ptls_openssl_aes128ctr;
return &ptls_openssl_aes128ecb;
}
if (cs->aead == &ptls_openssl_aes256gcm) {
return &ptls_openssl_aes256ctr;
return &ptls_openssl_aes256ecb;
}
#ifdef PTLS_OPENSSL_HAVE_CHACHA20_POLY1305
@@ -238,6 +238,11 @@ int ngtcp2_crypto_cipher_ctx_encrypt_init(ngtcp2_crypto_cipher_ctx *cipher_ctx,
return -1;
}
if (cipher->native_handle == &ptls_openssl_aes128ecb ||
cipher->native_handle == &ptls_openssl_aes256ecb) {
ptls_cipher_init(actx, NULL);
}
cipher_ctx->native_handle = actx;
return 0;
@@ -352,13 +357,20 @@ int ngtcp2_crypto_decrypt(uint8_t *dest, const ngtcp2_crypto_aead *aead,
int ngtcp2_crypto_hp_mask(uint8_t *dest, const ngtcp2_crypto_cipher *hp,
const ngtcp2_crypto_cipher_ctx *hp_ctx,
const uint8_t *sample) {
static const uint8_t PLAINTEXT[16] = {0};
ptls_cipher_context_t *actx = hp_ctx->native_handle;
static const uint8_t PLAINTEXT[] = "\x00\x00\x00\x00\x00";
(void)hp;
if (hp->native_handle == &ptls_openssl_aes128ecb ||
hp->native_handle == &ptls_openssl_aes256ecb) {
ptls_cipher_encrypt(actx, dest, sample, NGTCP2_HP_SAMPLELEN);
return 0;
}
ptls_cipher_init(actx, sample);
ptls_cipher_encrypt(actx, dest, PLAINTEXT, ngtcp2_strlen_lit(PLAINTEXT));
ptls_cipher_encrypt(actx, dest, PLAINTEXT, sizeof(PLAINTEXT));
return 0;
}
@@ -377,7 +389,7 @@ int ngtcp2_crypto_read_write_crypto_data(
ptls_buffer_init(&sendbuf, (void *)"", 0);
assert(epoch == ptls_get_read_epoch(cptls->ptls));
assert(datalen == 0 || epoch == ptls_get_read_epoch(cptls->ptls));
rv = ptls_handle_message(cptls->ptls, &sendbuf, epoch_offsets, epoch, data,
datalen, &cptls->handshake_properties);
@@ -493,6 +505,17 @@ int ngtcp2_crypto_get_path_challenge_data_cb(ngtcp2_conn *conn, uint8_t *data,
return 0;
}
int ngtcp2_crypto_get_path_challenge_data2_cb(ngtcp2_conn *conn,
ngtcp2_path_challenge_data *data,
void *user_data) {
(void)conn;
(void)user_data;
ptls_openssl_random_bytes(data->data, NGTCP2_PATH_CHALLENGE_DATALEN);
return 0;
}
int ngtcp2_crypto_random(uint8_t *data, size_t datalen) {
ptls_openssl_random_bytes(data, datalen);
@@ -500,8 +523,7 @@ int ngtcp2_crypto_random(uint8_t *data, size_t datalen) {
}
void ngtcp2_crypto_picotls_ctx_init(ngtcp2_crypto_picotls_ctx *cptls) {
cptls->ptls = NULL;
memset(&cptls->handshake_properties, 0, sizeof(cptls->handshake_properties));
*cptls = (ngtcp2_crypto_picotls_ctx){0};
}
static int set_additional_extensions(ptls_handshake_properties_t *hsprops,
+54 -26
View File
@@ -49,8 +49,8 @@ static EVP_CIPHER *crypto_aes_128_gcm;
static EVP_CIPHER *crypto_aes_256_gcm;
static EVP_CIPHER *crypto_chacha20_poly1305;
static EVP_CIPHER *crypto_aes_128_ccm;
static EVP_CIPHER *crypto_aes_128_ctr;
static EVP_CIPHER *crypto_aes_256_ctr;
static EVP_CIPHER *crypto_aes_128_ecb;
static EVP_CIPHER *crypto_aes_256_ecb;
static EVP_CIPHER *crypto_chacha20;
static EVP_MD *crypto_sha256;
static EVP_MD *crypto_sha384;
@@ -77,13 +77,13 @@ int ngtcp2_crypto_quictls_init(void) {
return -1;
}
crypto_aes_128_ctr = EVP_CIPHER_fetch(NULL, "AES-128-CTR", NULL);
if (crypto_aes_128_ctr == NULL) {
crypto_aes_128_ecb = EVP_CIPHER_fetch(NULL, "AES-128-ECB", NULL);
if (crypto_aes_128_ecb == NULL) {
return -1;
}
crypto_aes_256_ctr = EVP_CIPHER_fetch(NULL, "AES-256-CTR", NULL);
if (crypto_aes_256_ctr == NULL) {
crypto_aes_256_ecb = EVP_CIPHER_fetch(NULL, "AES-256-ECB", NULL);
if (crypto_aes_256_ecb == NULL) {
return -1;
}
@@ -144,20 +144,20 @@ static const EVP_CIPHER *crypto_aead_aes_128_ccm(void) {
return EVP_aes_128_ccm();
}
static const EVP_CIPHER *crypto_cipher_aes_128_ctr(void) {
if (crypto_aes_128_ctr) {
return crypto_aes_128_ctr;
static const EVP_CIPHER *crypto_cipher_aes_128_ecb(void) {
if (crypto_aes_128_ecb) {
return crypto_aes_128_ecb;
}
return EVP_aes_128_ctr();
return EVP_aes_128_ecb();
}
static const EVP_CIPHER *crypto_cipher_aes_256_ctr(void) {
if (crypto_aes_256_ctr) {
return crypto_aes_256_ctr;
static const EVP_CIPHER *crypto_cipher_aes_256_ecb(void) {
if (crypto_aes_256_ecb) {
return crypto_aes_256_ecb;
}
return EVP_aes_256_ctr();
return EVP_aes_256_ecb();
}
static const EVP_CIPHER *crypto_cipher_chacha20(void) {
@@ -196,8 +196,8 @@ static EVP_KDF *crypto_kdf_hkdf(void) {
# define crypto_aead_aes_256_gcm EVP_aes_256_gcm
# define crypto_aead_chacha20_poly1305 EVP_chacha20_poly1305
# define crypto_aead_aes_128_ccm EVP_aes_128_ccm
# define crypto_cipher_aes_128_ctr EVP_aes_128_ctr
# define crypto_cipher_aes_256_ctr EVP_aes_256_ctr
# define crypto_cipher_aes_128_ecb EVP_aes_128_ecb
# define crypto_cipher_aes_256_ecb EVP_aes_256_ecb
# define crypto_cipher_chacha20 EVP_chacha20
# define crypto_md_sha256 EVP_sha256
# define crypto_md_sha384 EVP_sha384
@@ -232,7 +232,7 @@ ngtcp2_crypto_md *ngtcp2_crypto_md_sha256(ngtcp2_crypto_md *md) {
ngtcp2_crypto_ctx *ngtcp2_crypto_ctx_initial(ngtcp2_crypto_ctx *ctx) {
ngtcp2_crypto_aead_init(&ctx->aead, (void *)crypto_aead_aes_128_gcm());
ctx->md.native_handle = (void *)crypto_md_sha256();
ctx->hp.native_handle = (void *)crypto_cipher_aes_128_ctr();
ctx->hp.native_handle = (void *)crypto_cipher_aes_128_ecb();
ctx->max_encryption = 0;
ctx->max_decryption_failure = 0;
return ctx;
@@ -297,9 +297,9 @@ static const EVP_CIPHER *crypto_cipher_id_get_hp(uint32_t cipher_id) {
switch (cipher_id) {
case TLS1_3_CK_AES_128_GCM_SHA256:
case TLS1_3_CK_AES_128_CCM_SHA256:
return crypto_cipher_aes_128_ctr();
return crypto_cipher_aes_128_ecb();
case TLS1_3_CK_AES_256_GCM_SHA384:
return crypto_cipher_aes_256_ctr();
return crypto_cipher_aes_256_ecb();
case TLS1_3_CK_CHACHA20_POLY1305_SHA256:
return crypto_cipher_chacha20();
default:
@@ -779,17 +779,31 @@ int ngtcp2_crypto_decrypt(uint8_t *dest, const ngtcp2_crypto_aead *aead,
int ngtcp2_crypto_hp_mask(uint8_t *dest, const ngtcp2_crypto_cipher *hp,
const ngtcp2_crypto_cipher_ctx *hp_ctx,
const uint8_t *sample) {
static const uint8_t PLAINTEXT[] = "\x00\x00\x00\x00\x00";
static const uint8_t PLAINTEXT[16] = {0};
EVP_CIPHER_CTX *actx = hp_ctx->native_handle;
int len;
(void)hp;
if (!EVP_EncryptInit_ex(actx, NULL, NULL, NULL, sample) ||
!EVP_EncryptUpdate(actx, dest, &len, PLAINTEXT,
ngtcp2_strlen_lit(PLAINTEXT)) ||
!EVP_EncryptFinal_ex(actx, dest + ngtcp2_strlen_lit(PLAINTEXT), &len)) {
return -1;
switch (EVP_CIPHER_CTX_nid(actx)) {
case NID_aes_128_ecb:
case NID_aes_256_ecb:
if (!EVP_EncryptUpdate(actx, dest, &len, sample, NGTCP2_HP_SAMPLELEN)) {
return -1;
}
break;
case NID_chacha20:
if (!EVP_EncryptInit_ex(actx, NULL, NULL, NULL, sample) ||
!EVP_EncryptUpdate(actx, dest, &len, PLAINTEXT, sizeof(PLAINTEXT)) ||
!EVP_EncryptFinal_ex(actx, dest + sizeof(PLAINTEXT), &len)) {
return -1;
}
break;
default:
assert(0);
abort();
}
return 0;
@@ -802,7 +816,8 @@ int ngtcp2_crypto_read_write_crypto_data(
int rv;
int err;
if (SSL_provide_quic_data(
if (datalen &&
SSL_provide_quic_data(
ssl,
ngtcp2_crypto_quictls_from_ngtcp2_encryption_level(encryption_level),
data, datalen) != 1) {
@@ -922,6 +937,19 @@ int ngtcp2_crypto_get_path_challenge_data_cb(ngtcp2_conn *conn, uint8_t *data,
return 0;
}
int ngtcp2_crypto_get_path_challenge_data2_cb(ngtcp2_conn *conn,
ngtcp2_path_challenge_data *data,
void *user_data) {
(void)conn;
(void)user_data;
if (RAND_bytes(data->data, NGTCP2_PATH_CHALLENGE_DATALEN) != 1) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
return 0;
}
int ngtcp2_crypto_random(uint8_t *data, size_t datalen) {
if (RAND_bytes(data, (int)datalen) != 1) {
return -1;
+38 -13
View File
@@ -37,6 +37,22 @@
#include "ngtcp2_macro.h"
#include "ngtcp2_net.h"
/*
* NGTCP2_INITIAL_SALT_V1 is a salt value which is used to derive
* initial secret. It is used for QUIC v1.
*/
static const uint8_t NGTCP2_INITIAL_SALT_V1[] = {
0x38, 0x76, 0x2C, 0xF7, 0xF5, 0x59, 0x34, 0xB3, 0x4D, 0x17,
0x9A, 0xE6, 0xA4, 0xC8, 0x0C, 0xAD, 0xCC, 0xBB, 0x7F, 0x0A};
/*
* NGTCP2_INITIAL_SALT_V2 is a salt value which is used to derive
* initial secret. It is used for QUIC v2.
*/
static const uint8_t NGTCP2_INITIAL_SALT_V2[] = {
0x0D, 0xED, 0xE3, 0xDE, 0xF7, 0x00, 0xA6, 0xDB, 0x81, 0x93,
0x81, 0xBE, 0x6E, 0x26, 0x9D, 0xCB, 0xF9, 0xBD, 0x2E, 0xD9};
ngtcp2_crypto_md *ngtcp2_crypto_md_init(ngtcp2_crypto_md *md,
void *md_native_handle) {
md->native_handle = md_native_handle;
@@ -87,12 +103,12 @@ int ngtcp2_crypto_derive_initial_secrets(uint8_t *rx_secret, uint8_t *tx_secret,
switch (version) {
case NGTCP2_PROTO_VER_V1:
default:
salt = (const uint8_t *)NGTCP2_INITIAL_SALT_V1;
saltlen = ngtcp2_strlen_lit(NGTCP2_INITIAL_SALT_V1);
salt = NGTCP2_INITIAL_SALT_V1;
saltlen = sizeof(NGTCP2_INITIAL_SALT_V1);
break;
case NGTCP2_PROTO_VER_V2:
salt = (const uint8_t *)NGTCP2_INITIAL_SALT_V2;
saltlen = ngtcp2_strlen_lit(NGTCP2_INITIAL_SALT_V2);
salt = NGTCP2_INITIAL_SALT_V2;
saltlen = sizeof(NGTCP2_INITIAL_SALT_V2);
break;
}
@@ -922,8 +938,8 @@ ngtcp2_ssize ngtcp2_crypto_generate_retry_token(
uint8_t *token, const uint8_t *secret, size_t secretlen, uint32_t version,
const ngtcp2_sockaddr *remote_addr, ngtcp2_socklen remote_addrlen,
const ngtcp2_cid *retry_scid, const ngtcp2_cid *odcid, ngtcp2_tstamp ts) {
uint8_t
plaintext[/* cid len = */ 1 + NGTCP2_MAX_CIDLEN + sizeof(ngtcp2_tstamp)];
uint8_t plaintext[/* cid len = */ 1 + NGTCP2_MAX_CIDLEN +
sizeof(ngtcp2_tstamp)] = {0};
uint8_t rand_data[NGTCP2_CRYPTO_TOKEN_RAND_DATALEN];
uint8_t key[16];
uint8_t iv[12];
@@ -942,8 +958,6 @@ ngtcp2_ssize ngtcp2_crypto_generate_retry_token(
assert((size_t)remote_addrlen <= sizeof(ngtcp2_sockaddr_union));
memset(plaintext, 0, sizeof(plaintext));
*p++ = (uint8_t)odcid->datalen;
memcpy(p, odcid->data, odcid->datalen);
p += NGTCP2_MAX_CIDLEN;
@@ -1104,7 +1118,7 @@ ngtcp2_ssize ngtcp2_crypto_generate_retry_token2(
const ngtcp2_sockaddr *remote_addr, ngtcp2_socklen remote_addrlen,
const ngtcp2_cid *retry_scid, const ngtcp2_cid *odcid, ngtcp2_tstamp ts) {
uint8_t plaintext[sizeof(ngtcp2_sockaddr_union) + /* cid len = */ 1 +
NGTCP2_MAX_CIDLEN + sizeof(ngtcp2_tstamp)];
NGTCP2_MAX_CIDLEN + sizeof(ngtcp2_tstamp)] = {0};
uint8_t rand_data[NGTCP2_CRYPTO_TOKEN_RAND_DATALEN];
uint8_t key[16];
uint8_t iv[12];
@@ -1121,8 +1135,6 @@ ngtcp2_ssize ngtcp2_crypto_generate_retry_token2(
assert((size_t)remote_addrlen <= sizeof(ngtcp2_sockaddr_union));
memset(plaintext, 0, sizeof(plaintext));
memcpy(p, remote_addr, (size_t)remote_addrlen);
p += sizeof(ngtcp2_sockaddr_union);
*p++ = (uint8_t)odcid->datalen;
@@ -1717,8 +1729,21 @@ int ngtcp2_crypto_recv_crypto_data_cb(ngtcp2_conn *conn,
(void)offset;
(void)user_data;
if (ngtcp2_crypto_read_write_crypto_data(conn, encryption_level, data,
datalen) != 0) {
rv =
ngtcp2_crypto_read_write_crypto_data(conn, encryption_level, data, datalen);
if (rv != 0) {
switch (rv) {
case /* NGTCP2_CRYPTO_QUICTLS_ERR_TLS_WANT_CLIENT_HELLO_CB */ -10001:
case /* NGTCP2_CRYPTO_QUICTLS_ERR_TLS_WANT_X509_LOOKUP */ -10002:
/* These errors are not unrecoverable error, and they just
indicate that handshake has been interrupted. ngtcp2 does
not mind whether handshake is interrupted or not. Just
return 0 in this case. There are OSSL version and they have
the same enum value, therefore we cannot enumerate them
here. */
return 0;
}
rv = ngtcp2_conn_get_tls_error(conn);
if (rv) {
return rv;
-20
View File
@@ -31,26 +31,6 @@
#include <ngtcp2/ngtcp2_crypto.h>
/**
* @macro
*
* :macro:`NGTCP2_INITIAL_SALT_V1` is a salt value which is used to
* derive initial secret. It is used for QUIC v1.
*/
#define NGTCP2_INITIAL_SALT_V1 \
"\x38\x76\x2c\xf7\xf5\x59\x34\xb3\x4d\x17\x9a\xe6\xa4\xc8\x0c\xad\xcc\xbb" \
"\x7f\x0a"
/**
* @macro
*
* :macro:`NGTCP2_INITIAL_SALT_V2` is a salt value which is used to
* derive initial secret. It is used for QUIC v2.
*/
#define NGTCP2_INITIAL_SALT_V2 \
"\x0d\xed\xe3\xde\xf7\x00\xa6\xdb\x81\x93\x81\xbe\x6e\x26\x9d\xcb\xf9\xbd" \
"\x2e\xd9"
/* Maximum key usage (encryption) limits */
#define NGTCP2_CRYPTO_MAX_ENCRYPTION_AES_GCM (1ULL << 23)
#define NGTCP2_CRYPTO_MAX_ENCRYPTION_CHACHA20_POLY1305 (1ULL << 62)
+52 -12
View File
@@ -56,7 +56,7 @@ ngtcp2_crypto_md *ngtcp2_crypto_md_sha256(ngtcp2_crypto_md *md) {
ngtcp2_crypto_ctx *ngtcp2_crypto_ctx_initial(ngtcp2_crypto_ctx *ctx) {
ngtcp2_crypto_aead_init(&ctx->aead, (void *)wolfSSL_EVP_aes_128_gcm());
ctx->md.native_handle = (void *)wolfSSL_EVP_sha256();
ctx->hp.native_handle = (void *)wolfSSL_EVP_aes_128_ctr();
ctx->hp.native_handle = (void *)wolfSSL_EVP_aes_128_ecb();
ctx->max_encryption = 0;
ctx->max_decryption_failure = 0;
return ctx;
@@ -107,6 +107,21 @@ static int supported_aead(const WOLFSSL_EVP_CIPHER *aead) {
wolfSSL_quic_aead_is_chacha20(aead) || wolfSSL_quic_aead_is_ccm(aead);
}
static const WOLFSSL_EVP_CIPHER *
crypto_aead_get_hp(const WOLFSSL_EVP_CIPHER *aead) {
switch (wolfSSL_EVP_CIPHER_nid(aead)) {
case NID_aes_128_gcm:
case NID_aes_128_ccm:
return wolfSSL_EVP_aes_128_ecb();
case NID_aes_256_gcm:
return wolfSSL_EVP_aes_256_ecb();
case NID_chacha20_poly1305:
return wolfSSL_EVP_chacha20();
default:
return NULL;
}
}
ngtcp2_crypto_ctx *ngtcp2_crypto_ctx_tls(ngtcp2_crypto_ctx *ctx,
void *tls_native_handle) {
WOLFSSL *ssl = tls_native_handle;
@@ -122,7 +137,7 @@ ngtcp2_crypto_ctx *ngtcp2_crypto_ctx_tls(ngtcp2_crypto_ctx *ctx,
ngtcp2_crypto_aead_init(&ctx->aead, (void *)aead);
ctx->md.native_handle = (void *)wolfSSL_quic_get_md(ssl);
ctx->hp.native_handle = (void *)wolfSSL_quic_get_hp(ssl);
ctx->hp.native_handle = (void *)crypto_aead_get_hp(aead);
ctx->max_encryption = crypto_aead_get_aead_max_encryption(aead);
ctx->max_decryption_failure =
crypto_aead_get_aead_max_decryption_failure(aead);
@@ -289,21 +304,33 @@ int ngtcp2_crypto_decrypt(uint8_t *dest, const ngtcp2_crypto_aead *aead,
int ngtcp2_crypto_hp_mask(uint8_t *dest, const ngtcp2_crypto_cipher *hp,
const ngtcp2_crypto_cipher_ctx *hp_ctx,
const uint8_t *sample) {
static const uint8_t PLAINTEXT[] = "\x00\x00\x00\x00\x00";
static const uint8_t PLAINTEXT[16] = {0};
WOLFSSL_EVP_CIPHER_CTX *actx = hp_ctx->native_handle;
int len;
(void)hp;
if (wolfSSL_EVP_EncryptInit_ex(actx, NULL, NULL, NULL, sample) !=
WOLFSSL_SUCCESS ||
wolfSSL_EVP_CipherUpdate(actx, dest, &len, PLAINTEXT,
ngtcp2_strlen_lit(PLAINTEXT)) !=
WOLFSSL_SUCCESS ||
wolfSSL_EVP_EncryptFinal_ex(actx, dest + ngtcp2_strlen_lit(PLAINTEXT),
&len) != WOLFSSL_SUCCESS) {
DEBUG_MSG("WOLFSSL: hp_mask FAILED\n");
return -1;
switch (wolfSSL_EVP_CIPHER_CTX_nid(actx)) {
case NID_aes_128_ecb:
case NID_aes_256_ecb:
if (!wolfSSL_EVP_CipherUpdate(actx, dest, &len, sample,
NGTCP2_HP_SAMPLELEN)) {
return -1;
}
break;
case NID_chacha20:
if (wolfSSL_EVP_EncryptInit_ex(actx, NULL, NULL, NULL, sample) !=
WOLFSSL_SUCCESS ||
wolfSSL_EVP_CipherUpdate(actx, dest, &len, PLAINTEXT,
sizeof(PLAINTEXT)) != WOLFSSL_SUCCESS ||
wolfSSL_EVP_EncryptFinal_ex(actx, dest + sizeof(PLAINTEXT), &len) !=
WOLFSSL_SUCCESS) {
DEBUG_MSG("WOLFSSL: hp_mask FAILED\n");
return -1;
}
break;
}
return 0;
@@ -444,6 +471,19 @@ int ngtcp2_crypto_get_path_challenge_data_cb(ngtcp2_conn *conn, uint8_t *data,
return 0;
}
int ngtcp2_crypto_get_path_challenge_data2_cb(ngtcp2_conn *conn,
ngtcp2_path_challenge_data *data,
void *user_data) {
(void)conn;
(void)user_data;
DEBUG_MSG("WOLFSSL: get path challenge data\n");
if (wolfSSL_RAND_bytes(data->data, NGTCP2_PATH_CHALLENGE_DATALEN) != 1) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
return 0;
}
int ngtcp2_crypto_random(uint8_t *data, size_t datalen) {
DEBUG_MSG("WOLFSSL: get random\n");
if (wolfSSL_RAND_bytes(data, (int)datalen) != 1) {
+496 -476
View File
File diff suppressed because it is too large. Load diff
+54 -41
View File
@@ -55,7 +55,7 @@ struct Stream {
Stream(const Request &req, int64_t stream_id);
~Stream();
int open_file(const std::string_view &path);
std::expected<void, Error> open_file(std::string_view path);
Request req;
int64_t stream_id;
@@ -77,68 +77,81 @@ public:
uint32_t original_version);
~Client();
int init(int fd, const Address &local_addr, const Address &remote_addr,
const char *addr, const char *port, TLSClientContext &tls_ctx);
std::expected<void, Error> init(int fd, const Address &local_addr,
const Address &remote_addr, const char *addr,
const char *port, TLSClientContext &tls_ctx);
void disconnect();
int on_read(const Endpoint &ep);
int on_write();
int write_streams();
int feed_data(const Endpoint &ep, const sockaddr *sa, socklen_t salen,
const ngtcp2_pkt_info *pi, std::span<const uint8_t> data);
int handle_expiry();
std::expected<void, Error> on_read(const Endpoint &ep);
std::expected<void, Error> on_write();
std::expected<void, Error> write_streams();
std::expected<void, Error> feed_data(const Endpoint &ep, const sockaddr *sa,
socklen_t salen,
const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
std::expected<void, Error> handle_expiry();
void update_timer();
int handshake_completed();
int handshake_confirmed();
std::expected<void, Error> handshake_completed();
void handshake_confirmed();
void recv_version_negotiation(const uint32_t *sv, size_t nsv);
int send_packet(const Endpoint &ep, const ngtcp2_addr &remote_addr,
unsigned int ecn, std::span<const uint8_t> data);
std::pair<std::span<const uint8_t>, int>
std::expected<void, Error> send_packet(const Endpoint &ep,
const ngtcp2_addr &remote_addr,
unsigned int ecn,
std::span<const uint8_t> data);
std::span<const uint8_t>
send_packet(const Endpoint &ep, const ngtcp2_addr &remote_addr,
unsigned int ecn, std::span<const uint8_t> data, size_t gso_size);
int send_packet_or_blocked(const ngtcp2_path &path, unsigned int ecn,
std::span<const uint8_t> data, size_t gso_size);
int on_stream_close(int64_t stream_id, uint64_t app_error_code);
int on_extend_max_streams();
int handle_error();
int make_stream_early();
int change_local_addr();
std::expected<void, Error>
send_packet_or_blocked(const ngtcp2_path &path, unsigned int ecn,
std::span<const uint8_t> data, size_t gso_size);
std::expected<void, Error> on_stream_close(int64_t stream_id,
uint64_t app_error_code);
void on_extend_max_streams();
std::expected<void, Error> handle_error();
std::expected<void, Error> make_stream_early();
std::expected<void, Error> change_local_addr();
void start_change_local_addr_timer();
int update_key(uint8_t *rx_secret, uint8_t *tx_secret,
ngtcp2_crypto_aead_ctx *rx_aead_ctx, uint8_t *rx_iv,
ngtcp2_crypto_aead_ctx *tx_aead_ctx, uint8_t *tx_iv,
const uint8_t *current_rx_secret,
const uint8_t *current_tx_secret, size_t secretlen);
int initiate_key_update();
std::expected<void, Error>
update_key(uint8_t *rx_secret, uint8_t *tx_secret,
ngtcp2_crypto_aead_ctx *rx_aead_ctx, uint8_t *rx_iv,
ngtcp2_crypto_aead_ctx *tx_aead_ctx, uint8_t *tx_iv,
const uint8_t *current_rx_secret, const uint8_t *current_tx_secret,
size_t secretlen);
std::expected<void, Error> initiate_key_update();
void start_key_update_timer();
void start_delay_stream_timer();
int select_preferred_address(Address &selected_addr,
const ngtcp2_preferred_addr *paddr);
std::expected<void, Error>
select_preferred_address(Address &selected_addr,
const ngtcp2_preferred_addr *paddr);
std::optional<Endpoint *> endpoint_for(const Address &remote_addr);
std::expected<Endpoint *, Error> endpoint_for(const Address &remote_addr);
void set_remote_addr(const ngtcp2_addr &remote_addr);
int setup_httpconn();
int submit_http_request(const Stream *stream);
int recv_stream_data(uint32_t flags, int64_t stream_id,
std::span<const uint8_t> data);
int acked_stream_data_offset(int64_t stream_id, uint64_t datalen);
std::expected<void, Error> setup_httpconn();
std::expected<void, Error> submit_http_request(const Stream *stream);
std::expected<void, Error> recv_stream_data(uint32_t flags, int64_t stream_id,
std::span<const uint8_t> data);
std::expected<void, Error> acked_stream_data_offset(int64_t stream_id,
uint64_t datalen);
void http_consume(int64_t stream_id, size_t nconsumed);
void http_write_data(int64_t stream_id, std::span<const uint8_t> data);
int on_stream_reset(int64_t stream_id);
int on_stream_stop_sending(int64_t stream_id);
int extend_max_stream_data(int64_t stream_id, uint64_t max_data);
int stop_sending(int64_t stream_id, uint64_t app_error_code);
int reset_stream(int64_t stream_id, uint64_t app_error_code);
std::expected<void, Error> on_stream_reset(int64_t stream_id);
std::expected<void, Error> on_stream_stop_sending(int64_t stream_id);
std::expected<void, Error> extend_max_stream_data(int64_t stream_id,
uint64_t max_data);
std::expected<void, Error> stop_sending(int64_t stream_id,
uint64_t app_error_code);
std::expected<void, Error> reset_stream(int64_t stream_id,
uint64_t app_error_code);
void http_stream_close(int64_t stream_id, uint64_t app_error_code);
void on_send_blocked(const ngtcp2_path &path, unsigned int ecn,
std::span<const uint8_t> data, size_t gso_size);
void start_wev_endpoint(const Endpoint &ep);
int send_blocked_packet();
void send_blocked_packet();
ngtcp2_ssize write_pkt(ngtcp2_path *path, ngtcp2_pkt_info *pi, uint8_t *dest,
size_t destlen, ngtcp2_tstamp ts);
-128
View File
@@ -61,134 +61,6 @@ ClientBase::~ClientBase() {
}
}
int ClientBase::write_transport_params(const char *path,
const ngtcp2_transport_params *params) {
auto f = std::ofstream(path);
if (!f) {
return -1;
}
f << "initial_max_streams_bidi=" << params->initial_max_streams_bidi << '\n'
<< "initial_max_streams_uni=" << params->initial_max_streams_uni << '\n'
<< "initial_max_stream_data_bidi_local="
<< params->initial_max_stream_data_bidi_local << '\n'
<< "initial_max_stream_data_bidi_remote="
<< params->initial_max_stream_data_bidi_remote << '\n'
<< "initial_max_stream_data_uni=" << params->initial_max_stream_data_uni
<< '\n'
<< "initial_max_data=" << params->initial_max_data << '\n'
<< "active_connection_id_limit=" << params->active_connection_id_limit
<< '\n'
<< "max_datagram_frame_size=" << params->max_datagram_frame_size << '\n';
f.close();
if (!f) {
return -1;
}
return 0;
}
int ClientBase::read_transport_params(const char *path,
ngtcp2_transport_params *params) {
auto f = std::ifstream(path);
if (!f) {
return -1;
}
for (std::string line; std::getline(f, line);) {
if (util::istarts_with(line, "initial_max_streams_bidi="sv)) {
if (auto n = util::parse_uint(line.c_str() +
"initial_max_streams_bidi="sv.size());
!n) {
return -1;
} else {
params->initial_max_streams_bidi = *n;
}
continue;
}
if (util::istarts_with(line, "initial_max_streams_uni="sv)) {
if (auto n = util::parse_uint(line.c_str() +
"initial_max_streams_uni="sv.size());
!n) {
return -1;
} else {
params->initial_max_streams_uni = *n;
}
continue;
}
if (util::istarts_with(line, "initial_max_stream_data_bidi_local="sv)) {
if (auto n = util::parse_uint(
line.c_str() + "initial_max_stream_data_bidi_local="sv.size());
!n) {
return -1;
} else {
params->initial_max_stream_data_bidi_local = *n;
}
continue;
}
if (util::istarts_with(line, "initial_max_stream_data_bidi_remote="sv)) {
if (auto n = util::parse_uint(
line.c_str() + "initial_max_stream_data_bidi_remote="sv.size());
!n) {
return -1;
} else {
params->initial_max_stream_data_bidi_remote = *n;
}
continue;
}
if (util::istarts_with(line, "initial_max_stream_data_uni="sv)) {
if (auto n = util::parse_uint(line.c_str() +
"initial_max_stream_data_uni="sv.size());
!n) {
return -1;
} else {
params->initial_max_stream_data_uni = *n;
}
continue;
}
if (util::istarts_with(line, "initial_max_data="sv)) {
if (auto n =
util::parse_uint(line.c_str() + "initial_max_data="sv.size());
!n) {
return -1;
} else {
params->initial_max_data = *n;
}
continue;
}
if (util::istarts_with(line, "active_connection_id_limit="sv)) {
if (auto n = util::parse_uint(line.c_str() +
"active_connection_id_limit="sv.size());
!n) {
return -1;
} else {
params->active_connection_id_limit = *n;
}
continue;
}
if (util::istarts_with(line, "max_datagram_frame_size="sv)) {
if (auto n = util::parse_uint(line.c_str() +
"max_datagram_frame_size="sv.size());
!n) {
return -1;
} else {
params->max_datagram_frame_size = *n;
}
continue;
}
}
return 0;
}
ngtcp2_conn *ClientBase::conn() const { return conn_; }
void qlog_write_cb(void *user_data, uint32_t flags, const void *data,
-4
View File
@@ -214,10 +214,6 @@ public:
ngtcp2_conn *conn() const;
int write_transport_params(const char *path,
const ngtcp2_transport_params *params);
int read_transport_params(const char *path, ngtcp2_transport_params *params);
void write_qlog(const void *data, size_t datalen);
ngtcp2_crypto_conn_ref *conn_ref();
+89 -83
View File
@@ -48,12 +48,12 @@ auto *outfile = stderr;
} // namespace
int handshake_completed(ngtcp2_conn *conn, void *user_data) {
fprintf(outfile, "QUIC handshake has completed\n");
std::println(outfile, "QUIC handshake has completed");
return 0;
}
int handshake_confirmed(ngtcp2_conn *conn, void *user_data) {
fprintf(outfile, "QUIC handshake has been confirmed\n");
std::println(outfile, "QUIC handshake has been confirmed");
return 0;
}
@@ -79,96 +79,100 @@ void print_crypto_data(ngtcp2_encryption_level encryption_level,
assert(0);
abort();
}
fprintf(outfile, "Ordered CRYPTO data in %s crypto level\n",
encryption_level_str);
util::hexdump(outfile, data.data(), data.size());
std::println(outfile, "Ordered CRYPTO data in {} crypto level",
encryption_level_str);
util::hexdump(outfile, data);
}
void print_stream_data(int64_t stream_id, std::span<const uint8_t> data) {
fprintf(outfile, "Ordered STREAM data stream_id=0x%" PRIx64 "\n", stream_id);
util::hexdump(outfile, data.data(), data.size());
std::println(outfile, "Ordered STREAM data stream_id={:#x}", stream_id);
util::hexdump(outfile, data);
}
void print_initial_secret(std::span<const uint8_t> data) {
fprintf(outfile, "initial_secret=%s\n", util::format_hex(data).c_str());
std::println(outfile, "initial_secret={}", util::format_hex(data));
}
void print_client_in_secret(std::span<const uint8_t> data) {
fprintf(outfile, "client_in_secret=%s\n", util::format_hex(data).c_str());
std::println(outfile, "client_in_secret={}", util::format_hex(data));
}
void print_server_in_secret(std::span<const uint8_t> data) {
fprintf(outfile, "server_in_secret=%s\n", util::format_hex(data).c_str());
std::println(outfile, "server_in_secret={}", util::format_hex(data));
}
void print_handshake_secret(std::span<const uint8_t> data) {
fprintf(outfile, "handshake_secret=%s\n", util::format_hex(data).c_str());
std::println(outfile, "handshake_secret={}", util::format_hex(data));
}
void print_client_hs_secret(std::span<const uint8_t> data) {
fprintf(outfile, "client_hs_secret=%s\n", util::format_hex(data).c_str());
std::println(outfile, "client_hs_secret={}", util::format_hex(data));
}
void print_server_hs_secret(std::span<const uint8_t> data) {
fprintf(outfile, "server_hs_secret=%s\n", util::format_hex(data).c_str());
std::println(outfile, "server_hs_secret={}", util::format_hex(data));
}
void print_client_0rtt_secret(std::span<const uint8_t> data) {
fprintf(outfile, "client_0rtt_secret=%s\n", util::format_hex(data).c_str());
std::println(outfile, "client_0rtt_secret={}", util::format_hex(data));
}
void print_client_1rtt_secret(std::span<const uint8_t> data) {
fprintf(outfile, "client_1rtt_secret=%s\n", util::format_hex(data).c_str());
std::println(outfile, "client_1rtt_secret={}", util::format_hex(data));
}
void print_server_1rtt_secret(std::span<const uint8_t> data) {
fprintf(outfile, "server_1rtt_secret=%s\n", util::format_hex(data).c_str());
std::println(outfile, "server_1rtt_secret={}", util::format_hex(data));
}
void print_client_pp_key(std::span<const uint8_t> data) {
fprintf(outfile, "+ client_pp_key=%s\n", util::format_hex(data).c_str());
std::println(outfile, "+ client_pp_key={}", util::format_hex(data));
}
void print_server_pp_key(std::span<const uint8_t> data) {
fprintf(outfile, "+ server_pp_key=%s\n", util::format_hex(data).c_str());
std::println(outfile, "+ server_pp_key={}", util::format_hex(data));
}
void print_client_pp_iv(std::span<const uint8_t> data) {
fprintf(outfile, "+ client_pp_iv=%s\n", util::format_hex(data).c_str());
std::println(outfile, "+ client_pp_iv={}", util::format_hex(data));
}
void print_server_pp_iv(std::span<const uint8_t> data) {
fprintf(outfile, "+ server_pp_iv=%s\n", util::format_hex(data).c_str());
std::println(outfile, "+ server_pp_iv={}", util::format_hex(data));
}
void print_client_pp_hp(std::span<const uint8_t> data) {
fprintf(outfile, "+ client_pp_hp=%s\n", util::format_hex(data).c_str());
std::println(outfile, "+ client_pp_hp={}", util::format_hex(data));
}
void print_server_pp_hp(std::span<const uint8_t> data) {
fprintf(outfile, "+ server_pp_hp=%s\n", util::format_hex(data).c_str());
std::println(outfile, "+ server_pp_hp={}", util::format_hex(data));
}
void print_secrets(std::span<const uint8_t> secret,
std::span<const uint8_t> key, std::span<const uint8_t> iv,
std::span<const uint8_t> hp) {
std::cerr << "+ secret=" << util::format_hex(secret) << "\n"
<< "+ key=" << util::format_hex(key) << "\n"
<< "+ iv=" << util::format_hex(iv) << "\n"
<< "+ hp=" << util::format_hex(hp) << std::endl;
std::println(stderr, R"(+ secret={}
+ key={}
+ iv={}
+ hp={})",
util::format_hex(secret), util::format_hex(key),
util::format_hex(iv), util::format_hex(hp));
}
void print_secrets(std::span<const uint8_t> secret,
std::span<const uint8_t> key, std::span<const uint8_t> iv) {
std::cerr << "+ secret=" << util::format_hex(secret) << "\n"
<< "+ key=" << util::format_hex(key) << "\n"
<< "+ iv=" << util::format_hex(iv) << std::endl;
std::println(stderr, R"(+ secret={}
+ key={}
+ iv={})",
util::format_hex(secret), util::format_hex(key),
util::format_hex(iv));
}
void print_hp_mask(std::span<const uint8_t> mask,
std::span<const uint8_t> sample) {
fprintf(outfile, "mask=%s sample=%s\n", util::format_hex(mask).c_str(),
util::format_hex(sample).c_str());
std::println(outfile, "mask={} sample={}", util::format_hex(mask),
util::format_hex(sample));
}
void log_printf(void *user_data, const char *fmt, ...) {
@@ -197,29 +201,28 @@ void path_validation(const ngtcp2_path *path,
auto remote_addr = util::straddr(
reinterpret_cast<sockaddr *>(path->remote.addr), path->remote.addrlen);
std::cerr << "Path validation against path {local:" << local_addr
<< ", remote:" << remote_addr << "} "
<< (res == NGTCP2_PATH_VALIDATION_RESULT_SUCCESS ? "succeeded"
: "failed")
<< std::endl;
std::println(
stderr, "Path validation against path {{local:{}, remote:{}}} {}",
local_addr, remote_addr,
res == NGTCP2_PATH_VALIDATION_RESULT_SUCCESS ? "succeeded" : "failed");
}
void print_http_begin_request_headers(int64_t stream_id) {
fprintf(outfile, "http: stream 0x%" PRIx64 " request headers started\n",
stream_id);
std::println(outfile, "http: stream {:#x} request headers started",
stream_id);
}
void print_http_begin_response_headers(int64_t stream_id) {
fprintf(outfile, "http: stream 0x%" PRIx64 " response headers started\n",
stream_id);
std::println(outfile, "http: stream {:#x} response headers started",
stream_id);
}
namespace {
void print_header(std::span<const uint8_t> name, std::span<const uint8_t> value,
uint8_t flags) {
fprintf(outfile, "[%.*s: %.*s]%s\n", static_cast<int>(name.size()),
name.data(), static_cast<int>(value.size()), value.data(),
(flags & NGHTTP3_NV_FLAG_NEVER_INDEX) ? "(sensitive)" : "");
std::println(outfile, "[{}: {}]{}", as_string_view(name),
as_string_view(value),
(flags & NGHTTP3_NV_FLAG_NEVER_INDEX) ? "(sensitive)" : "");
}
} // namespace
@@ -241,32 +244,31 @@ void print_header(const nghttp3_nv &nv) {
void print_http_header(int64_t stream_id, const nghttp3_rcbuf *name,
const nghttp3_rcbuf *value, uint8_t flags) {
fprintf(outfile, "http: stream 0x%" PRIx64 " ", stream_id);
std::print(outfile, "http: stream {:#x} ", stream_id);
print_header(name, value, flags);
}
void print_http_end_headers(int64_t stream_id) {
fprintf(outfile, "http: stream 0x%" PRIx64 " headers ended\n", stream_id);
std::println(outfile, "http: stream {:#x} headers ended", stream_id);
}
void print_http_data(int64_t stream_id, std::span<const uint8_t> data) {
fprintf(outfile, "http: stream 0x%" PRIx64 " body %zu bytes\n", stream_id,
data.size());
util::hexdump(outfile, data.data(), data.size());
std::println(outfile, "http: stream {:#x} body {} bytes", stream_id,
data.size());
util::hexdump(outfile, data);
}
void print_http_begin_trailers(int64_t stream_id) {
fprintf(outfile, "http: stream 0x%" PRIx64 " trailers started\n", stream_id);
std::println(outfile, "http: stream {:#x} trailers started", stream_id);
}
void print_http_end_trailers(int64_t stream_id) {
fprintf(outfile, "http: stream 0x%" PRIx64 " trailers ended\n", stream_id);
std::println(outfile, "http: stream {:#x} trailers ended", stream_id);
}
void print_http_request_headers(int64_t stream_id, const nghttp3_nv *nva,
size_t nvlen) {
fprintf(outfile, "http: stream 0x%" PRIx64 " submit request headers\n",
stream_id);
std::println(outfile, "http: stream {:#x} submit request headers", stream_id);
for (size_t i = 0; i < nvlen; ++i) {
auto &nv = nva[i];
print_header(nv);
@@ -275,8 +277,8 @@ void print_http_request_headers(int64_t stream_id, const nghttp3_nv *nva,
void print_http_response_headers(int64_t stream_id, const nghttp3_nv *nva,
size_t nvlen) {
fprintf(outfile, "http: stream 0x%" PRIx64 " submit response headers\n",
stream_id);
std::println(outfile, "http: stream {:#x} submit response headers",
stream_id);
for (size_t i = 0; i < nvlen; ++i) {
auto &nv = nva[i];
print_header(nv);
@@ -284,24 +286,24 @@ void print_http_response_headers(int64_t stream_id, const nghttp3_nv *nva,
}
void print_http_settings(const nghttp3_proto_settings *settings) {
fprintf(outfile,
"http: remote settings\n"
"http: SETTINGS_MAX_FIELD_SECTION_SIZE=%" PRIu64 "\n"
"http: SETTINGS_QPACK_MAX_TABLE_CAPACITY=%zu\n"
"http: SETTINGS_QPACK_BLOCKED_STREAMS=%zu\n"
"http: SETTINGS_ENABLE_CONNECT_PROTOCOL=%d\n"
"http: SETTINGS_H3_DATAGRAM=%d\n",
settings->max_field_section_size, settings->qpack_max_dtable_capacity,
settings->qpack_blocked_streams, settings->enable_connect_protocol,
settings->h3_datagram);
std::println(outfile, R"(http: remote settings
http: SETTINGS_MAX_FIELD_SECTION_SIZE={}
http: SETTINGS_QPACK_MAX_TABLE_CAPACITY={}
http: SETTINGS_QPACK_BLOCKED_STREAMS={}
http: SETTINGS_ENABLE_CONNECT_PROTOCOL={}
http: SETTINGS_H3_DATAGRAM={})",
settings->max_field_section_size,
settings->qpack_max_dtable_capacity,
settings->qpack_blocked_streams,
settings->enable_connect_protocol, settings->h3_datagram);
}
void print_http_origin(const uint8_t *origin, size_t originlen) {
fprintf(outfile, "http: origin [%.*s]\n", static_cast<int>(originlen),
origin);
std::println(outfile, "http: origin [{}]",
as_string_view(std::span{origin, originlen}));
}
void print_http_end_origin() { fprintf(outfile, "http: origin ended\n"); }
void print_http_end_origin() { std::println(outfile, "http: origin ended"); }
std::string_view secret_title(ngtcp2_encryption_level level) {
switch (level) {
@@ -322,22 +324,26 @@ void print_conn_info(ngtcp2_conn *conn) {
ngtcp2_conn_get_conn_info(conn, &cinfo);
std::cout << "# Connection Statistics (see ngtcp2_conn_info for details)\n"
"min_rtt="
<< util::format_durationf(cinfo.min_rtt) << '\n'
<< "smoothed_rtt=" << util::format_durationf(cinfo.smoothed_rtt)
<< '\n'
<< "rttvar=" << util::format_durationf(cinfo.rttvar) << '\n'
<< "cwnd=" << cinfo.cwnd << '\n'
<< "ssthresh=" << cinfo.ssthresh << '\n'
<< "pkt_sent=" << cinfo.pkt_sent << '\n'
<< "bytes_sent=" << cinfo.bytes_sent << '\n'
<< "pkt_recv=" << cinfo.pkt_recv << '\n'
<< "bytes_recv=" << cinfo.bytes_recv << '\n'
<< "pkt_lost=" << cinfo.pkt_lost << '\n'
<< "bytes_lost=" << cinfo.bytes_lost << '\n'
<< "ping_recv=" << cinfo.ping_recv << '\n'
<< "pkt_discarded=" << cinfo.pkt_discarded << std::endl;
std::println(
R"(# Connection Statistics (see ngtcp2_conn_info for details)
min_rtt={}
smoothed_rtt={}
rttvar={}
cwnd={}
ssthresh={}
pkt_sent={}
bytes_sent={}
pkt_recv={}
bytes_recv={}
pkt_lost={}
bytes_lost={}
ping_recv={}
pkt_discarded={})",
util::format_durationf(cinfo.min_rtt),
util::format_durationf(cinfo.smoothed_rtt),
util::format_durationf(cinfo.rttvar), cinfo.cwnd, cinfo.ssthresh,
cinfo.pkt_sent, cinfo.bytes_sent, cinfo.pkt_recv, cinfo.bytes_recv,
cinfo.pkt_lost, cinfo.bytes_lost, cinfo.ping_recv, cinfo.pkt_discarded);
}
} // namespace debug
+6 -7
View File
@@ -244,8 +244,8 @@ static void rand_cb(uint8_t *dest, size_t destlen,
}
static int get_new_connection_id_cb(ngtcp2_conn *conn, ngtcp2_cid *cid,
uint8_t *token, size_t cidlen,
void *user_data) {
ngtcp2_stateless_reset_token *token,
size_t cidlen, void *user_data) {
(void)conn;
(void)user_data;
@@ -255,8 +255,7 @@ static int get_new_connection_id_cb(ngtcp2_conn *conn, ngtcp2_cid *cid,
cid->datalen = cidlen;
if (gnutls_rnd(GNUTLS_RND_RANDOM, token, NGTCP2_STATELESS_RESET_TOKENLEN) !=
0) {
if (gnutls_rnd(GNUTLS_RND_RANDOM, token->data, sizeof(token->data)) != 0) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
@@ -332,12 +331,12 @@ static int client_quic_init(struct client *c,
.recv_retry = ngtcp2_crypto_recv_retry_cb,
.extend_max_local_streams_bidi = extend_max_local_streams_bidi,
.rand = rand_cb,
.get_new_connection_id = get_new_connection_id_cb,
.update_key = ngtcp2_crypto_update_key_cb,
.delete_crypto_aead_ctx = ngtcp2_crypto_delete_crypto_aead_ctx_cb,
.delete_crypto_cipher_ctx = ngtcp2_crypto_delete_crypto_cipher_ctx_cb,
.get_path_challenge_data = ngtcp2_crypto_get_path_challenge_data_cb,
.version_negotiation = ngtcp2_crypto_version_negotiation_cb,
.get_new_connection_id2 = get_new_connection_id_cb,
.get_path_challenge_data2 = ngtcp2_crypto_get_path_challenge_data2_cb,
};
ngtcp2_cid dcid, scid;
ngtcp2_settings settings;
@@ -632,7 +631,7 @@ static int client_init(struct client *c) {
struct sockaddr_storage remote_addr, local_addr;
socklen_t remote_addrlen, local_addrlen = sizeof(local_addr);
memset(c, 0, sizeof(*c));
*c = (struct client){0};
ngtcp2_ccerr_default(&c->last_error);
+417 -412
View File
File diff suppressed because it is too large. Load diff
+45 -37
View File
@@ -57,7 +57,7 @@ struct Stream {
Stream(const Request &req, int64_t stream_id);
~Stream();
int open_file(const std::string_view &path);
std::expected<void, Error> open_file(std::string_view path);
Request req;
int64_t stream_id;
@@ -87,63 +87,71 @@ public:
uint32_t original_version);
~Client();
int init(int fd, const Address &local_addr, const Address &remote_addr,
const char *addr, const char *port, TLSClientContext &tls_ctx);
std::expected<void, Error> init(int fd, const Address &local_addr,
const Address &remote_addr, const char *addr,
const char *port, TLSClientContext &tls_ctx);
void disconnect();
int on_read(const Endpoint &ep);
int on_write();
int write_streams();
int feed_data(const Endpoint &ep, const sockaddr *sa, socklen_t salen,
const ngtcp2_pkt_info *pi, std::span<const uint8_t> data);
int handle_expiry();
std::expected<void, Error> on_read(const Endpoint &ep);
std::expected<void, Error> on_write();
std::expected<void, Error> write_streams();
std::expected<void, Error> feed_data(const Endpoint &ep, const sockaddr *sa,
socklen_t salen,
const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
std::expected<void, Error> handle_expiry();
void update_timer();
int handshake_completed();
int handshake_confirmed();
std::expected<void, Error> handshake_completed();
void handshake_confirmed();
void recv_version_negotiation(const uint32_t *sv, size_t nsv);
int send_packet(const Endpoint &ep, const ngtcp2_addr &remote_addr,
unsigned int ecn, std::span<const uint8_t> data);
std::pair<std::span<const uint8_t>, int>
std::expected<void, Error> send_packet(const Endpoint &ep,
const ngtcp2_addr &remote_addr,
unsigned int ecn,
std::span<const uint8_t> data);
std::span<const uint8_t>
send_packet(const Endpoint &ep, const ngtcp2_addr &remote_addr,
unsigned int ecn, std::span<const uint8_t> data, size_t gso_size);
int send_packet_or_blocked(const ngtcp2_path &path, unsigned int ecn,
std::span<const uint8_t> data, size_t gso_size);
int on_stream_close(int64_t stream_id, uint64_t app_error_code);
int on_extend_max_streams();
int handle_error();
int make_stream_early();
int change_local_addr();
std::expected<void, Error>
send_packet_or_blocked(const ngtcp2_path &path, unsigned int ecn,
std::span<const uint8_t> data, size_t gso_size);
void on_stream_close(int64_t stream_id, uint64_t app_error_code);
void on_extend_max_streams();
std::expected<void, Error> handle_error();
void make_stream_early();
std::expected<void, Error> change_local_addr();
void start_change_local_addr_timer();
int update_key(uint8_t *rx_secret, uint8_t *tx_secret,
ngtcp2_crypto_aead_ctx *rx_aead_ctx, uint8_t *rx_iv,
ngtcp2_crypto_aead_ctx *tx_aead_ctx, uint8_t *tx_iv,
const uint8_t *current_rx_secret,
const uint8_t *current_tx_secret, size_t secretlen);
int initiate_key_update();
std::expected<void, Error>
update_key(uint8_t *rx_secret, uint8_t *tx_secret,
ngtcp2_crypto_aead_ctx *rx_aead_ctx, uint8_t *rx_iv,
ngtcp2_crypto_aead_ctx *tx_aead_ctx, uint8_t *tx_iv,
const uint8_t *current_rx_secret, const uint8_t *current_tx_secret,
size_t secretlen);
std::expected<void, Error> initiate_key_update();
void start_key_update_timer();
void start_delay_stream_timer();
int select_preferred_address(Address &selected_addr,
const ngtcp2_preferred_addr *paddr);
std::expected<void, Error>
select_preferred_address(Address &selected_addr,
const ngtcp2_preferred_addr *paddr);
std::optional<Endpoint *> endpoint_for(const Address &remote_addr);
std::expected<Endpoint *, Error> endpoint_for(const Address &remote_addr);
void set_remote_addr(const ngtcp2_addr &remote_addr);
int submit_http_request(Stream *stream);
int recv_stream_data(uint32_t flags, int64_t stream_id,
std::span<const uint8_t> data);
int acked_stream_data_offset(int64_t stream_id, uint64_t offset,
uint64_t datalen);
int extend_max_stream_data(int64_t stream_id, uint64_t max_data);
void submit_http_request(Stream *stream);
void recv_stream_data(uint32_t flags, int64_t stream_id,
std::span<const uint8_t> data);
void acked_stream_data_offset(int64_t stream_id, uint64_t offset,
uint64_t datalen);
void extend_max_stream_data(int64_t stream_id, uint64_t max_data);
void write_qlog(const void *data, size_t datalen);
void on_send_blocked(const ngtcp2_path &path, unsigned int ecn,
std::span<const uint8_t> data, size_t gso_size);
void start_wev_endpoint(const Endpoint &ep);
int send_blocked_packet();
void send_blocked_packet();
ngtcp2_ssize write_pkt(ngtcp2_path *path, ngtcp2_pkt_info *pi, uint8_t *dest,
size_t destlen, ngtcp2_tstamp ts);
+546 -540
View File
File diff suppressed because it is too large. Load diff
+79 -60
View File
@@ -58,10 +58,10 @@ struct FileEntry;
struct Stream {
Stream(int64_t stream_id, Handler *handler);
int start_response();
std::pair<FileEntry, int> open_file(const std::string &path);
void start_response();
std::expected<FileEntry, Error> open_file(const std::string &path);
void map_file(const FileEntry &fe);
int send_status_response(unsigned int status_code);
void send_status_response(unsigned int status_code);
int64_t stream_id;
Handler *handler;
@@ -95,49 +95,57 @@ public:
Handler(struct ev_loop *loop, Server *server);
~Handler();
int init(const Endpoint &ep, const Address &local_addr,
const Address &remote_addr, const ngtcp2_cid *dcid,
const ngtcp2_cid *scid, const ngtcp2_cid *ocid,
std::span<const uint8_t> token, ngtcp2_token_type token_type,
uint32_t version, TLSServerContext &tls_ctx);
std::expected<void, Error>
init(const Endpoint &ep, const Address &local_addr,
const Address &remote_addr, const ngtcp2_cid *dcid,
const ngtcp2_cid *scid, const ngtcp2_cid *ocid,
std::span<const uint8_t> token, ngtcp2_token_type token_type,
uint32_t version, TLSServerContext &tls_ctx);
int on_read(const Endpoint &ep, const Address &local_addr,
const Address &remote_addr, const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
int on_write();
int write_streams();
int feed_data(const Endpoint &ep, const Address &local_addr,
const Address &remote_addr, const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
std::expected<void, Error> on_read(const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr,
const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
std::expected<void, Error> on_write();
std::expected<void, Error> write_streams();
std::expected<void, Error> feed_data(const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr,
const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
void update_timer();
int handle_expiry();
std::expected<void, Error> handle_expiry();
void signal_write();
int handshake_completed();
std::expected<void, Error> handshake_completed();
Server *server() const;
int recv_stream_data(uint32_t flags, int64_t stream_id,
std::span<const uint8_t> data);
int acked_stream_data_offset(int64_t stream_id, uint64_t offset,
uint64_t datalen);
std::expected<void, Error> recv_stream_data(uint32_t flags, int64_t stream_id,
std::span<const uint8_t> data);
void acked_stream_data_offset(int64_t stream_id, uint64_t offset,
uint64_t datalen);
uint32_t version() const;
void on_stream_open(int64_t stream_id);
int on_stream_close(int64_t stream_id, uint64_t app_error_code);
void on_stream_close(int64_t stream_id, uint64_t app_error_code);
void start_draining_period();
int start_closing_period();
int handle_error();
int send_conn_close();
int send_conn_close(const Endpoint &ep, const Address &local_addr,
const Address &remote_addr, const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
std::expected<void, Error> start_closing_period();
std::expected<void, Error> handle_error();
std::expected<void, Error> send_conn_close();
std::expected<void, Error> send_conn_close(const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr,
const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
int update_key(uint8_t *rx_secret, uint8_t *tx_secret,
ngtcp2_crypto_aead_ctx *rx_aead_ctx, uint8_t *rx_iv,
ngtcp2_crypto_aead_ctx *tx_aead_ctx, uint8_t *tx_iv,
const uint8_t *current_rx_secret,
const uint8_t *current_tx_secret, size_t secretlen);
std::expected<void, Error>
update_key(uint8_t *rx_secret, uint8_t *tx_secret,
ngtcp2_crypto_aead_ctx *rx_aead_ctx, uint8_t *rx_iv,
ngtcp2_crypto_aead_ctx *tx_aead_ctx, uint8_t *tx_iv,
const uint8_t *current_rx_secret, const uint8_t *current_tx_secret,
size_t secretlen);
Stream *find_stream(int64_t stream_id);
int extend_max_stream_data(int64_t stream_id, uint64_t max_data);
void extend_max_stream_data(int64_t stream_id, uint64_t max_data);
void shutdown_read(int64_t stream_id, uint64_t app_error_code);
void write_qlog(const void *data, size_t datalen);
@@ -146,9 +154,11 @@ public:
void on_send_blocked(const ngtcp2_path &path, unsigned int ecn,
std::span<const uint8_t> data, size_t gso_size);
void start_wev_endpoint(const Endpoint &ep);
int send_packet(const ngtcp2_path &path, unsigned int ecn,
std::span<const uint8_t> data, size_t gso_size);
int send_blocked_packet();
std::expected<void, Error> send_packet(const ngtcp2_path &path,
unsigned int ecn,
std::span<const uint8_t> data,
size_t gso_size);
void send_blocked_packet();
ngtcp2_ssize write_pkt(ngtcp2_path *path, ngtcp2_pkt_info *pi, uint8_t *dest,
size_t destlen, ngtcp2_tstamp ts);
@@ -196,35 +206,44 @@ public:
Server(struct ev_loop *loop, TLSServerContext &tls_ctx);
~Server();
int init(const char *addr, const char *port);
std::expected<void, Error> init(const char *addr, const char *port);
void disconnect();
void close();
int on_read(const Endpoint &ep);
void on_read(const Endpoint &ep);
void read_pkt(const Endpoint &ep, const Address &local_addr,
const Address &remote_addr, const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
int send_version_negotiation(uint32_t version, std::span<const uint8_t> dcid,
std::span<const uint8_t> scid,
const Endpoint &ep, const Address &local_addr,
const Address &remote_addr);
int send_retry(const ngtcp2_pkt_hd *chd, const Endpoint &ep,
const Address &local_addr, const Address &remote_addr,
size_t max_pktlen);
int send_stateless_connection_close(const ngtcp2_pkt_hd *chd,
const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr);
int send_stateless_reset(size_t pktlen, std::span<const uint8_t> dcid,
const Endpoint &ep, const Address &local_addr,
std::expected<void, Error>
send_version_negotiation(uint32_t version, std::span<const uint8_t> dcid,
std::span<const uint8_t> scid, const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr);
int verify_retry_token(ngtcp2_cid *ocid, const ngtcp2_pkt_hd *hd,
const Address &remote_addr);
int verify_token(const ngtcp2_pkt_hd *hd, const Address &remote_addr);
int send_packet(const Endpoint &ep, const ngtcp2_addr &local_addr,
const ngtcp2_addr &remote_addr, unsigned int ecn,
std::span<const uint8_t> data);
std::pair<std::span<const uint8_t>, int>
std::expected<void, Error> send_retry(const ngtcp2_pkt_hd *chd,
const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr,
size_t max_pktlen);
std::expected<void, Error>
send_stateless_connection_close(const ngtcp2_pkt_hd *chd, const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr);
std::expected<void, Error> send_stateless_reset(size_t pktlen,
std::span<const uint8_t> dcid,
const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr);
std::expected<void, Error> verify_retry_token(ngtcp2_cid *ocid,
const ngtcp2_pkt_hd *hd,
const Address &remote_addr);
std::expected<void, Error> verify_token(const ngtcp2_pkt_hd *hd,
const Address &remote_addr);
std::expected<void, Error> send_packet(const Endpoint &ep,
const ngtcp2_addr &local_addr,
const ngtcp2_addr &remote_addr,
unsigned int ecn,
std::span<const uint8_t> data);
std::span<const uint8_t>
send_packet(const Endpoint &ep, bool &no_gso, const ngtcp2_addr &local_addr,
const ngtcp2_addr &remote_addr, unsigned int ecn,
std::span<const uint8_t> data, size_t gso_size);
+670 -652
View File
File diff suppressed because it is too large. Load diff
+97 -71
View File
@@ -57,14 +57,16 @@ struct FileEntry;
struct Stream {
Stream(int64_t stream_id, Handler *handler);
int start_response(nghttp3_conn *conn);
std::pair<FileEntry, int> open_file(const std::string &path);
std::expected<void, Error> start_response(nghttp3_conn *conn);
std::expected<FileEntry, Error> open_file(const std::string &path);
void map_file(const FileEntry &fe);
int send_status_response(nghttp3_conn *conn, unsigned int status_code,
const std::vector<HTTPHeader> &extra_headers = {});
int send_redirect_response(nghttp3_conn *conn, unsigned int status_code,
const std::string_view &path);
int64_t find_dyn_length(const std::string_view &path);
std::expected<void, Error>
send_status_response(nghttp3_conn *conn, unsigned int status_code,
const std::vector<HTTPHeader> &extra_headers = {});
std::expected<void, Error> send_redirect_response(nghttp3_conn *conn,
unsigned int status_code,
std::string_view path);
std::expected<uint64_t, Error> find_dyn_length(std::string_view path);
void http_acked_stream_data(uint64_t datalen);
int64_t stream_id;
@@ -101,73 +103,88 @@ public:
Handler(struct ev_loop *loop, Server *server);
~Handler();
int init(const Endpoint &ep, const Address &local_addr,
const Address &remote_addr, const ngtcp2_cid *dcid,
const ngtcp2_cid *scid, const ngtcp2_cid *ocid,
std::span<const uint8_t> token, ngtcp2_token_type token_type,
uint32_t version, TLSServerContext &tls_ctx);
std::expected<void, Error>
init(const Endpoint &ep, const Address &local_addr,
const Address &remote_addr, const ngtcp2_cid *dcid,
const ngtcp2_cid *scid, const ngtcp2_cid *ocid,
std::span<const uint8_t> token, ngtcp2_token_type token_type,
uint32_t version, TLSServerContext &tls_ctx);
int on_read(const Endpoint &ep, const Address &local_addr,
const Address &remote_addr, const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
int on_write();
int write_streams();
int feed_data(const Endpoint &ep, const Address &local_addr,
const Address &remote_addr, const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
std::expected<void, Error> on_read(const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr,
const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
std::expected<void, Error> on_write();
std::expected<void, Error> write_streams();
std::expected<void, Error> feed_data(const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr,
const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
void update_timer();
int handle_expiry();
std::expected<void, Error> handle_expiry();
void signal_write();
int handshake_completed();
std::expected<void, Error> handshake_completed();
Server *server() const;
int recv_stream_data(uint32_t flags, int64_t stream_id,
std::span<const uint8_t> data);
int acked_stream_data_offset(int64_t stream_id, uint64_t datalen);
std::expected<void, Error> recv_stream_data(uint32_t flags, int64_t stream_id,
std::span<const uint8_t> data);
std::expected<void, Error> acked_stream_data_offset(int64_t stream_id,
uint64_t datalen);
uint32_t version() const;
void on_stream_open(int64_t stream_id);
int on_stream_close(int64_t stream_id, uint64_t app_error_code);
std::expected<void, Error> on_stream_close(int64_t stream_id,
uint64_t app_error_code);
void start_draining_period();
int start_closing_period();
int handle_error();
int send_conn_close();
int send_conn_close(const Endpoint &ep, const Address &local_addr,
const Address &remote_addr, const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
std::expected<void, Error> start_closing_period();
std::expected<void, Error> handle_error();
std::expected<void, Error> send_conn_close();
std::expected<void, Error> send_conn_close(const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr,
const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
int update_key(uint8_t *rx_secret, uint8_t *tx_secret,
ngtcp2_crypto_aead_ctx *rx_aead_ctx, uint8_t *rx_iv,
ngtcp2_crypto_aead_ctx *tx_aead_ctx, uint8_t *tx_iv,
const uint8_t *current_rx_secret,
const uint8_t *current_tx_secret, size_t secretlen);
std::expected<void, Error>
update_key(uint8_t *rx_secret, uint8_t *tx_secret,
ngtcp2_crypto_aead_ctx *rx_aead_ctx, uint8_t *rx_iv,
ngtcp2_crypto_aead_ctx *tx_aead_ctx, uint8_t *tx_iv,
const uint8_t *current_rx_secret, const uint8_t *current_tx_secret,
size_t secretlen);
int setup_httpconn();
std::expected<void, Error> setup_httpconn();
void http_consume(int64_t stream_id, size_t nconsumed);
void extend_max_remote_streams_bidi(uint64_t max_streams);
Stream *find_stream(int64_t stream_id);
void http_begin_request_headers(int64_t stream_id);
void http_recv_request_header(Stream *stream, int32_t token,
nghttp3_rcbuf *name, nghttp3_rcbuf *value);
int http_end_request_headers(Stream *stream);
int http_end_stream(Stream *stream);
int start_response(Stream *stream);
int on_stream_reset(int64_t stream_id);
int on_stream_stop_sending(int64_t stream_id);
int extend_max_stream_data(int64_t stream_id, uint64_t max_data);
std::expected<void, Error> http_end_request_headers(Stream *stream);
std::expected<void, Error> http_end_stream(Stream *stream);
std::expected<void, Error> start_response(Stream *stream);
std::expected<void, Error> on_stream_reset(int64_t stream_id);
std::expected<void, Error> on_stream_stop_sending(int64_t stream_id);
std::expected<void, Error> extend_max_stream_data(int64_t stream_id,
uint64_t max_data);
void shutdown_read(int64_t stream_id, uint64_t app_error_code);
void http_acked_stream_data(Stream *stream, uint64_t datalen);
void http_stream_close(int64_t stream_id, uint64_t app_error_code);
int http_stop_sending(int64_t stream_id, uint64_t app_error_code);
int http_reset_stream(int64_t stream_id, uint64_t app_error_code);
std::expected<void, Error> http_stop_sending(int64_t stream_id,
uint64_t app_error_code);
std::expected<void, Error> http_reset_stream(int64_t stream_id,
uint64_t app_error_code);
void write_qlog(const void *data, size_t datalen);
void on_send_blocked(const ngtcp2_path &path, unsigned int ecn,
std::span<const uint8_t> data, size_t gso_size);
void start_wev_endpoint(const Endpoint &ep);
int send_packet(const ngtcp2_path &path, unsigned int ecn,
std::span<const uint8_t> data, size_t gso_size);
int send_blocked_packet();
std::expected<void, Error> send_packet(const ngtcp2_path &path,
unsigned int ecn,
std::span<const uint8_t> data,
size_t gso_size);
void send_blocked_packet();
ngtcp2_ssize write_pkt(ngtcp2_path *path, ngtcp2_pkt_info *pi, uint8_t *dest,
size_t destlen, ngtcp2_tstamp ts);
@@ -215,35 +232,44 @@ public:
Server(struct ev_loop *loop, TLSServerContext &tls_ctx);
~Server();
int init(const char *addr, const char *port);
std::expected<void, Error> init(const char *addr, const char *port);
void disconnect();
void close();
int on_read(const Endpoint &ep);
void on_read(const Endpoint &ep);
void read_pkt(const Endpoint &ep, const Address &local_addr,
const Address &remote_addr, const ngtcp2_pkt_info *pi,
std::span<const uint8_t> data);
int send_version_negotiation(uint32_t version, std::span<const uint8_t> dcid,
std::span<const uint8_t> scid,
const Endpoint &ep, const Address &local_addr,
const Address &remote_addr);
int send_retry(const ngtcp2_pkt_hd *chd, const Endpoint &ep,
const Address &local_addr, const Address &remote_addr,
size_t max_pktlen);
int send_stateless_connection_close(const ngtcp2_pkt_hd *chd,
const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr);
int send_stateless_reset(size_t pktlen, std::span<const uint8_t> dcid,
const Endpoint &ep, const Address &local_addr,
std::expected<void, Error>
send_version_negotiation(uint32_t version, std::span<const uint8_t> dcid,
std::span<const uint8_t> scid, const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr);
int verify_retry_token(ngtcp2_cid *ocid, const ngtcp2_pkt_hd *hd,
const Address &remote_addr);
int verify_token(const ngtcp2_pkt_hd *hd, const Address &remote_addr);
int send_packet(const Endpoint &ep, const ngtcp2_addr &local_addr,
const ngtcp2_addr &remote_addr, unsigned int ecn,
std::span<const uint8_t> data);
std::pair<std::span<const uint8_t>, int>
std::expected<void, Error> send_retry(const ngtcp2_pkt_hd *chd,
const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr,
size_t max_pktlen);
std::expected<void, Error>
send_stateless_connection_close(const ngtcp2_pkt_hd *chd, const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr);
std::expected<void, Error> send_stateless_reset(size_t pktlen,
std::span<const uint8_t> dcid,
const Endpoint &ep,
const Address &local_addr,
const Address &remote_addr);
std::expected<void, Error> verify_retry_token(ngtcp2_cid *ocid,
const ngtcp2_pkt_hd *hd,
const Address &remote_addr);
std::expected<void, Error> verify_token(const ngtcp2_pkt_hd *hd,
const Address &remote_addr);
std::expected<void, Error> send_packet(const Endpoint &ep,
const ngtcp2_addr &local_addr,
const ngtcp2_addr &remote_addr,
unsigned int ecn,
std::span<const uint8_t> data);
std::span<const uint8_t>
send_packet(const Endpoint &ep, bool &no_gso, const ngtcp2_addr &local_addr,
const ngtcp2_addr &remote_addr, unsigned int ecn,
std::span<const uint8_t> data, size_t gso_size);
+1 -1
View File
@@ -171,7 +171,7 @@ struct Config {
};
struct HTTPHeader {
HTTPHeader(const std::string_view &name, const std::string_view &value)
HTTPHeader(std::string_view name, std::string_view value)
: name{name}, value{value} {}
std::string_view name;
+62 -61
View File
@@ -92,13 +92,13 @@ void fd_set_recv_ecn(int fd, int family) {
case AF_INET:
if (setsockopt(fd, IPPROTO_IP, IP_RECVTOS, &tos,
static_cast<socklen_t>(sizeof(tos))) == -1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
std::println(stderr, "setsockopt: {}", strerror(errno));
}
break;
case AF_INET6:
if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVTCLASS, &tos,
static_cast<socklen_t>(sizeof(tos))) == -1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
std::println(stderr, "setsockopt: {}", strerror(errno));
}
break;
}
@@ -113,16 +113,15 @@ void fd_set_ip_mtu_discover(int fd, int family) {
val = IP_PMTUDISC_PROBE;
if (setsockopt(fd, IPPROTO_IP, IP_MTU_DISCOVER, &val,
static_cast<socklen_t>(sizeof(val))) == -1) {
std::cerr << "setsockopt: IP_MTU_DISCOVER: " << strerror(errno)
<< std::endl;
std::println(stderr, "setsockopt: IP_MTU_DISCOVER: {}", strerror(errno));
}
break;
case AF_INET6:
val = IPV6_PMTUDISC_PROBE;
if (setsockopt(fd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &val,
static_cast<socklen_t>(sizeof(val))) == -1) {
std::cerr << "setsockopt: IPV6_MTU_DISCOVER: " << strerror(errno)
<< std::endl;
std::println(stderr, "setsockopt: IPV6_MTU_DISCOVER: {}",
strerror(errno));
}
break;
}
@@ -137,14 +136,13 @@ void fd_set_ip_dontfrag(int fd, int family) {
case AF_INET:
if (setsockopt(fd, IPPROTO_IP, IP_DONTFRAG, &val,
static_cast<socklen_t>(sizeof(val))) == -1) {
std::cerr << "setsockopt: IP_DONTFRAG: " << strerror(errno) << std::endl;
std::println(stderr, "setsockopt: IP_DONTFRAG: {}", strerror(errno));
}
break;
case AF_INET6:
if (setsockopt(fd, IPPROTO_IPV6, IPV6_DONTFRAG, &val,
static_cast<socklen_t>(sizeof(val))) == -1) {
std::cerr << "setsockopt: IPV6_DONTFRAG: " << strerror(errno)
<< std::endl;
std::println(stderr, "setsockopt: IPV6_DONTFRAG: {}", strerror(errno));
}
break;
}
@@ -157,12 +155,12 @@ void fd_set_udp_gro(int fd) {
if (setsockopt(fd, IPPROTO_UDP, UDP_GRO, &val,
static_cast<socklen_t>(sizeof(val))) == -1) {
std::cerr << "setsockopt: UDP_GRO: " << strerror(errno) << std::endl;
std::println(stderr, "setsockopt: UDP_GRO: {}", strerror(errno));
}
#endif // defined(UDP_GRO)
}
std::optional<Address> msghdr_get_local_addr(msghdr *msg, int family) {
std::expected<Address, Error> msghdr_get_local_addr(msghdr *msg, int family) {
switch (family) {
case AF_INET:
for (auto cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
@@ -178,7 +176,7 @@ std::optional<Address> msghdr_get_local_addr(msghdr *msg, int family) {
return res;
}
}
return {};
return std::unexpected{Error::NOT_FOUND};
case AF_INET6:
for (auto cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO) {
@@ -193,9 +191,9 @@ std::optional<Address> msghdr_get_local_addr(msghdr *msg, int family) {
return res;
}
}
return {};
return std::unexpected{Error::NOT_FOUND};
}
return {};
return std::unexpected{Error::INVALID_ARGUMENT};
}
size_t msghdr_get_udp_gro(msghdr *msg) {
@@ -224,7 +222,8 @@ struct nlmsg {
};
namespace {
int send_netlink_msg(int fd, const Address &remote_addr, uint32_t seq) {
std::expected<void, Error> send_netlink_msg(int fd, const Address &remote_addr,
uint32_t seq) {
nlmsg nlmsg{
.hdr{
.nlmsg_type = RTM_GETROUTE,
@@ -285,17 +284,17 @@ int send_netlink_msg(int fd, const Address &remote_addr, uint32_t seq) {
} while (nwrite == -1 && errno == EINTR);
if (nwrite == -1) {
std::cerr << "sendmsg: Could not write netlink message: " << strerror(errno)
<< std::endl;
return -1;
std::println(stderr, "sendmsg: Could not write netlink message: {}",
strerror(errno));
return std::unexpected{Error::SYSCALL};
}
return 0;
return {};
}
} // namespace
namespace {
int recv_netlink_msg(InAddr &ia, int fd, uint32_t seq) {
std::expected<InAddr, Error> recv_netlink_msg(int fd, uint32_t seq) {
std::array<uint8_t, 8192> buf;
iovec iov = {
.iov_base = buf.data(),
@@ -309,41 +308,42 @@ int recv_netlink_msg(InAddr &ia, int fd, uint32_t seq) {
.msg_iovlen = 1,
};
ssize_t nread;
InAddr ia;
do {
nread = recvmsg(fd, &msg, 0);
} while (nread == -1 && errno == EINTR);
if (nread == -1) {
std::cerr << "recvmsg: Could not receive netlink message: "
<< strerror(errno) << std::endl;
return -1;
std::println(stderr, "recvmsg: Could not receive netlink message: {}",
strerror(errno));
return std::unexpected{Error::SYSCALL};
}
for (auto hdr = reinterpret_cast<nlmsghdr *>(buf.data());
NLMSG_OK(hdr, nread); hdr = NLMSG_NEXT(hdr, nread)) {
if (seq != hdr->nlmsg_seq) {
std::cerr << "netlink: unexpected sequence number " << hdr->nlmsg_seq
<< " while expecting " << seq << std::endl;
return -1;
std::println(stderr,
"netlink: unexpected sequence number {} while expecting {}",
hdr->nlmsg_seq, seq);
return std::unexpected{Error::INTERNAL};
}
if (hdr->nlmsg_flags & NLM_F_MULTI) {
std::cerr << "netlink: unexpected NLM_F_MULTI flag set" << std::endl;
return -1;
std::println(stderr, "netlink: unexpected NLM_F_MULTI flag set");
return std::unexpected{Error::INTERNAL};
}
switch (hdr->nlmsg_type) {
case NLMSG_DONE:
std::cerr << "netlink: unexpected NLMSG_DONE" << std::endl;
return -1;
std::println(stderr, "netlink: unexpected NLMSG_DONE");
return std::unexpected{Error::INTERNAL};
case NLMSG_NOOP:
continue;
case NLMSG_ERROR:
std::cerr << "netlink: "
<< strerror(-static_cast<nlmsgerr *>(NLMSG_DATA(hdr))->error)
<< std::endl;
return -1;
std::println(stderr, "netlink: {}",
strerror(-static_cast<nlmsgerr *>(NLMSG_DATA(hdr))->error));
return std::unexpected{Error::INTERNAL};
}
auto attrlen = hdr->nlmsg_len - NLMSG_SPACE(sizeof(rtmsg));
@@ -359,7 +359,7 @@ int recv_netlink_msg(InAddr &ia, int fd, uint32_t seq) {
case AF_INET: {
constexpr auto in_addrlen = sizeof(in_addr);
if (RTA_LENGTH(in_addrlen) != rta->rta_len) {
return -1;
return std::unexpected{Error::INTERNAL};
}
in_addr addr;
@@ -372,7 +372,7 @@ int recv_netlink_msg(InAddr &ia, int fd, uint32_t seq) {
case AF_INET6: {
constexpr auto in_addrlen = sizeof(in6_addr);
if (RTA_LENGTH(in_addrlen) != rta->rta_len) {
return -1;
return std::unexpected{Error::INTERNAL};
}
in6_addr addr;
@@ -392,7 +392,7 @@ int recv_netlink_msg(InAddr &ia, int fd, uint32_t seq) {
}
if (in_addr_empty(ia)) {
return -1;
return std::unexpected{Error::NOT_FOUND};
}
// Read ACK
@@ -411,9 +411,9 @@ int recv_netlink_msg(InAddr &ia, int fd, uint32_t seq) {
} while (nread == -1 && errno == EINTR);
if (nread == -1) {
std::cerr << "recvmsg: Could not receive netlink message: "
<< strerror(errno) << std::endl;
return -1;
std::println(stderr, "recvmsg: Could not receive netlink message: {}",
strerror(errno));
return std::unexpected{Error::SYSCALL};
}
error = -1;
@@ -421,20 +421,21 @@ int recv_netlink_msg(InAddr &ia, int fd, uint32_t seq) {
for (auto hdr = reinterpret_cast<nlmsghdr *>(buf.data());
NLMSG_OK(hdr, nread); hdr = NLMSG_NEXT(hdr, nread)) {
if (seq != hdr->nlmsg_seq) {
std::cerr << "netlink: unexpected sequence number " << hdr->nlmsg_seq
<< " while expecting " << seq << std::endl;
return -1;
std::println(stderr,
"netlink: unexpected sequence number {} while expecting {}",
hdr->nlmsg_seq, seq);
return std::unexpected{Error::INTERNAL};
}
if (hdr->nlmsg_flags & NLM_F_MULTI) {
std::cerr << "netlink: unexpected NLM_F_MULTI flag set" << std::endl;
return -1;
std::println(stderr, "netlink: unexpected NLM_F_MULTI flag set");
return std::unexpected{Error::INTERNAL};
}
switch (hdr->nlmsg_type) {
case NLMSG_DONE:
std::cerr << "netlink: unexpected NLMSG_DONE" << std::endl;
return -1;
std::println(stderr, "netlink: unexpected NLMSG_DONE");
return std::unexpected{Error::INTERNAL};
case NLMSG_NOOP:
continue;
case NLMSG_ERROR:
@@ -443,47 +444,47 @@ int recv_netlink_msg(InAddr &ia, int fd, uint32_t seq) {
break;
}
std::cerr << "netlink: " << strerror(error) << std::endl;
std::println(stderr, "netlink: {}", strerror(error));
return -1;
return std::unexpected{Error::INTERNAL};
}
}
if (error != 0) {
return -1;
return std::unexpected{Error::INTERNAL};
}
return 0;
return ia;
}
} // namespace
int get_local_addr(InAddr &ia, const Address &remote_addr) {
std::expected<InAddr, Error> get_local_addr(const Address &remote_addr) {
sockaddr_nl sa{
.nl_family = AF_NETLINK,
};
auto fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (fd == -1) {
std::cerr << "socket: Could not create netlink socket: " << strerror(errno)
<< std::endl;
return -1;
std::println(stderr, "socket: Could not create netlink socket: {}",
strerror(errno));
return std::unexpected{Error::SYSCALL};
}
auto fd_d = defer([fd] { close(fd); });
if (bind(fd, reinterpret_cast<sockaddr *>(&sa), sizeof(sa)) == -1) {
std::cerr << "bind: Could not bind netlink socket: " << strerror(errno)
<< std::endl;
return -1;
std::println(stderr, "bind: Could not bind netlink socket: {}",
strerror(errno));
return std::unexpected{Error::SYSCALL};
}
uint32_t seq = 1;
if (send_netlink_msg(fd, remote_addr, seq) != 0) {
return -1;
if (auto rv = send_netlink_msg(fd, remote_addr, seq); !rv) {
return std::unexpected{rv.error()};
}
return recv_netlink_msg(ia, fd, seq);
return recv_netlink_msg(fd, seq);
}
#endif // defined(HAVE_LINUX_NETLINK_H)
+113 -10
View File
@@ -32,6 +32,8 @@
#include <optional>
#include <string_view>
#include <span>
#include <print>
#include <expected>
#include <ngtcp2/ngtcp2.h>
@@ -41,23 +43,61 @@ using namespace std::literals;
namespace ngtcp2 {
enum class Error {
// the generic errors that are not covered by more specific error
// codes.
INTERNAL,
// function arguments are invalid
INVALID_ARGUMENT,
// integer overflow error
INTEGER_OVERFLOW,
// file I/O error
IO,
// function is not implemented yet
NOT_IMPLEMENTED,
// the operation is not supported
UNSUPPORTED,
// entity is not found (e.g., file not found)
NOT_FOUND,
// crypto related error (e.g., error from TLS stack)
CRYPTO,
// system call error
SYSCALL,
// C library error (e.g., error from getaddrinfo)
LIBC,
// HTTP3 library error (e.g., error from nghttp3 API)
HTTP3,
// QUIC library error (e.g., error from ngtcp2 API)
QUIC,
// sending packet is blocked by kernel
SEND_BLOCKED,
// QUIC connection is in close-wait.
CLOSE_WAIT,
// QUIC connection should be retried.
RETRY_CONN,
// QUIC connection should be dropped.
DROP_CONN,
// Retry token is unreadable, and should be ignored.
UNREADABLE_TOKEN,
};
enum class AppProtocol {
H3,
HQ,
};
template <size_t N>
consteval std::span<const uint8_t> as_uint8_span(const uint8_t (&s)[N]) {
consteval std::span<const uint8_t> span_from_lit(const uint8_t (&s)[N]) {
return {s, N - 1};
}
inline constexpr uint8_t RAW_HQ_ALPN[] = "\xahq-interop";
inline constexpr auto HQ_ALPN = as_uint8_span(RAW_HQ_ALPN);
inline constexpr auto HQ_ALPN_V1 = as_uint8_span(RAW_HQ_ALPN);
inline constexpr uint8_t RAW_HQ_ALPN[] = "\xAhq-interop";
inline constexpr auto HQ_ALPN = span_from_lit(RAW_HQ_ALPN);
inline constexpr auto HQ_ALPN_V1 = span_from_lit(RAW_HQ_ALPN);
inline constexpr uint8_t RAW_H3_ALPN[] = "\x2h3";
inline constexpr auto H3_ALPN = as_uint8_span(RAW_H3_ALPN);
inline constexpr auto H3_ALPN_V1 = as_uint8_span(RAW_H3_ALPN);
inline constexpr auto H3_ALPN = span_from_lit(RAW_H3_ALPN);
inline constexpr auto H3_ALPN_V1 = span_from_lit(RAW_H3_ALPN);
inline constexpr uint32_t TLS_ALERT_ECH_REQUIRED = 121;
@@ -81,15 +121,15 @@ void fd_set_ip_dontfrag(int fd, int family);
// fd_set_udp_gro sets UDP_GRO socket option to |fd|.
void fd_set_udp_gro(int fd);
std::optional<Address> msghdr_get_local_addr(msghdr *msg, int family);
std::expected<Address, Error> msghdr_get_local_addr(msghdr *msg, int family);
// msghdr_get_udp_gro returns UDP_GRO value from |msg|. If UDP_GRO is
// not found, or UDP_GRO is not supported, this function returns 0.
size_t msghdr_get_udp_gro(msghdr *msg);
// get_local_addr stores preferred local address (interface address)
// in |ia| for a given destination address |remote_addr|.
int get_local_addr(InAddr &ia, const Address &remote_addr);
// get_local_addr returns the preferred local address (interface
// address) for a given destination address |remote_addr|.
std::expected<InAddr, Error> get_local_addr(const Address &remote_addr);
// addreq returns true if |addr| and |ia| contain the same address.
bool addreq(const Address &addr, const InAddr &ia);
@@ -145,4 +185,67 @@ void sockaddr_set(Sockaddr &skaddr, const sockaddr *sa);
} // namespace ngtcp2
template <>
struct std::formatter<ngtcp2::Error> : public std::formatter<std::string_view> {
auto format(ngtcp2::Error e, format_context &ctx) const {
auto s = "unknown"sv;
switch (e) {
case ngtcp2::Error::INTERNAL:
s = "internal"sv;
break;
case ngtcp2::Error::INVALID_ARGUMENT:
s = "invalid argument"sv;
break;
case ngtcp2::Error::INTEGER_OVERFLOW:
s = "integer overflow"sv;
break;
case ngtcp2::Error::IO:
s = "I/O"sv;
break;
case ngtcp2::Error::NOT_IMPLEMENTED:
s = "not implemented"sv;
break;
case ngtcp2::Error::UNSUPPORTED:
s = "unsupported"sv;
break;
case ngtcp2::Error::NOT_FOUND:
s = "not found"sv;
break;
case ngtcp2::Error::CRYPTO:
s = "crypto"sv;
break;
case ngtcp2::Error::SYSCALL:
s = "syscall"sv;
break;
case ngtcp2::Error::LIBC:
s = "libc"sv;
break;
case ngtcp2::Error::HTTP3:
s = "HTTP3"sv;
break;
case ngtcp2::Error::QUIC:
s = "QUIC"sv;
break;
case ngtcp2::Error::SEND_BLOCKED:
s = "send blocked"sv;
break;
case ngtcp2::Error::CLOSE_WAIT:
s = "close wait"sv;
break;
case ngtcp2::Error::RETRY_CONN:
s = "retry connection"sv;
break;
case ngtcp2::Error::DROP_CONN:
s = "drop connection"sv;
break;
case ngtcp2::Error::UNREADABLE_TOKEN:
s = "unreadable token"sv;
break;
}
return std::formatter<std::string_view>::format(s, ctx);
}
};
#endif // !defined(SHARED_H)
+106 -93
View File
@@ -36,7 +36,6 @@
#include "ngtcp2/ngtcp2_crypto_wolfssl.h"
#include "util.h"
#include "shared.h"
#include "debug.h"
using namespace std::literals;
@@ -48,30 +47,31 @@ constexpr auto ALPN_LIST = "ngtcp2-sim"sv;
constexpr size_t CIDLEN = 10;
constexpr uint8_t SERVER_SECRET[] = "server_secret";
int generate_secure_random(std::span<uint8_t> data) {
std::expected<void, Error> generate_secure_random(std::span<uint8_t> data) {
if (wolfSSL_RAND_bytes(data.data(), static_cast<int>(data.size())) != 1) {
return -1;
return std::unexpected{Error::CRYPTO};
}
return 0;
return {};
}
void rand_bytes(uint8_t *dest, size_t destlen,
const ngtcp2_rand_ctx *rand_ctx) {
auto rv = generate_secure_random({dest, destlen});
(void)rv;
assert(0 == rv);
assert(rv);
}
int get_new_connection_id(ngtcp2_conn *conn, ngtcp2_cid *cid, uint8_t *token,
size_t cidlen, void *user_data) {
if (generate_secure_random({cid->data, cidlen}) != 0) {
int get_new_connection_id(ngtcp2_conn *conn, ngtcp2_cid *cid,
ngtcp2_stateless_reset_token *token, size_t cidlen,
void *user_data) {
if (!generate_secure_random({cid->data, cidlen})) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
cid->datalen = cidlen;
if (ngtcp2_crypto_generate_stateless_reset_token(
token, SERVER_SECRET, sizeof(SERVER_SECRET) - 1, cid) != 0) {
token->data, SERVER_SECRET, sizeof(SERVER_SECRET) - 1, cid) != 0) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
@@ -124,12 +124,12 @@ ngtcp2_callbacks default_client_callbacks() {
.recv_stream_data = recv_stream_data,
.recv_retry = ngtcp2_crypto_recv_retry_cb,
.rand = rand_bytes,
.get_new_connection_id = get_new_connection_id,
.update_key = ngtcp2_crypto_update_key_cb,
.delete_crypto_aead_ctx = ngtcp2_crypto_delete_crypto_aead_ctx_cb,
.delete_crypto_cipher_ctx = ngtcp2_crypto_delete_crypto_cipher_ctx_cb,
.get_path_challenge_data = ngtcp2_crypto_get_path_challenge_data_cb,
.version_negotiation = ngtcp2_crypto_version_negotiation_cb,
.get_new_connection_id2 = get_new_connection_id,
.get_path_challenge_data2 = ngtcp2_crypto_get_path_challenge_data2_cb,
};
}
@@ -142,12 +142,12 @@ ngtcp2_callbacks default_server_callbacks() {
.hp_mask = ngtcp2_crypto_hp_mask_cb,
.recv_stream_data = recv_stream_data,
.rand = rand_bytes,
.get_new_connection_id = get_new_connection_id,
.update_key = ngtcp2_crypto_update_key_cb,
.delete_crypto_aead_ctx = ngtcp2_crypto_delete_crypto_aead_ctx_cb,
.delete_crypto_cipher_ctx = ngtcp2_crypto_delete_crypto_cipher_ctx_cb,
.get_path_challenge_data = ngtcp2_crypto_get_path_challenge_data_cb,
.version_negotiation = ngtcp2_crypto_version_negotiation_cb,
.get_new_connection_id2 = get_new_connection_id,
.get_path_challenge_data2 = ngtcp2_crypto_get_path_challenge_data2_cb,
};
}
@@ -325,17 +325,16 @@ SJ9Gq0lvEXEcAiBwWBNUASBqLaje3hmtgwxcF7EIqqiGo5j8f9Ufgu6SRg==
)"sv;
} // namespace
int Endpoint::setup_server(std::span<const uint8_t> original_dcid,
std::span<const uint8_t> client_scid,
uint32_t version, const ngtcp2_addr *remote_addr) {
int rv;
std::expected<void, Error>
Endpoint::setup_server(std::span<const uint8_t> original_dcid,
std::span<const uint8_t> client_scid, uint32_t version,
const ngtcp2_addr *remote_addr) {
ngtcp2_cid scid{
.datalen = CIDLEN,
};
if (generate_secure_random({scid.data, scid.datalen}) != 0) {
return -1;
if (auto rv = generate_secure_random({scid.data, scid.datalen}); !rv) {
return rv;
}
ngtcp2_cid dcid;
@@ -348,8 +347,8 @@ int Endpoint::setup_server(std::span<const uint8_t> original_dcid,
if (ngtcp2_crypto_generate_stateless_reset_token(
params.stateless_reset_token, SERVER_SECRET, sizeof(SERVER_SECRET) - 1,
&scid)) {
return -1;
&scid) != 0) {
return std::unexpected{Error::QUIC};
}
auto path = ngtcp2_path{
@@ -357,43 +356,42 @@ int Endpoint::setup_server(std::span<const uint8_t> original_dcid,
.remote = *remote_addr,
};
rv = ngtcp2_conn_server_new(&conn_, &dcid, &scid, &path, version,
&config_.callbacks, &config_.settings, &params,
nullptr, config_.user_data);
if (rv != 0) {
return -1;
if (ngtcp2_conn_server_new(&conn_, &dcid, &scid, &path, version,
&config_.callbacks, &config_.settings, &params,
nullptr, config_.user_data) != 0) {
return std::unexpected{Error::QUIC};
}
ssl_ctx_ = wolfSSL_CTX_new(wolfTLSv1_3_server_method());
if (!ssl_ctx_) {
return -1;
return std::unexpected{Error::CRYPTO};
}
if (ngtcp2_crypto_wolfssl_configure_server_context(ssl_ctx_) != 0) {
return -1;
return std::unexpected{Error::CRYPTO};
}
if (wolfSSL_CTX_use_certificate_buffer(
ssl_ctx_, reinterpret_cast<const uint8_t *>(tls_crt.data()),
static_cast<long>(tls_crt.size()), SSL_FILETYPE_PEM) != SSL_SUCCESS) {
return -1;
return std::unexpected{Error::CRYPTO};
}
if (wolfSSL_CTX_use_PrivateKey_buffer(
ssl_ctx_, reinterpret_cast<const uint8_t *>(tls_key.data()),
static_cast<long>(tls_key.size()), SSL_FILETYPE_PEM) != SSL_SUCCESS) {
return -1;
return std::unexpected{Error::CRYPTO};
}
ssl_ = wolfSSL_new(ssl_ctx_);
if (!ssl_) {
return -1;
return std::unexpected{Error::CRYPTO};
}
if (wolfSSL_UseALPN(ssl_, const_cast<char *>(ALPN_LIST.data()),
ALPN_LIST.size(),
WOLFSSL_ALPN_FAILED_ON_MISMATCH) != WOLFSSL_SUCCESS) {
return -1;
return std::unexpected{Error::CRYPTO};
}
wolfSSL_set_app_data(ssl_, &conn_ref_);
@@ -404,12 +402,11 @@ int Endpoint::setup_server(std::span<const uint8_t> original_dcid,
initialized_ = true;
return 0;
return {};
}
int Endpoint::setup_client(const ngtcp2_addr *remote_addr) {
int rv;
std::expected<void, Error>
Endpoint::setup_client(const ngtcp2_addr *remote_addr) {
ngtcp2_cid dcid{
.datalen = CIDLEN,
};
@@ -417,10 +414,12 @@ int Endpoint::setup_client(const ngtcp2_addr *remote_addr) {
.datalen = CIDLEN,
};
if (generate_secure_random({dcid.data, dcid.datalen}) != 0 ||
generate_secure_random({scid.data, scid.datalen}) != 0) {
assert(0);
return -1;
if (auto rv = generate_secure_random({dcid.data, dcid.datalen}); !rv) {
return rv;
}
if (auto rv = generate_secure_random({scid.data, scid.datalen}); !rv) {
return rv;
}
auto path = ngtcp2_path{
@@ -428,31 +427,30 @@ int Endpoint::setup_client(const ngtcp2_addr *remote_addr) {
.remote = *remote_addr,
};
rv = ngtcp2_conn_client_new(&conn_, &dcid, &scid, &path, NGTCP2_PROTO_VER_V1,
&config_.callbacks, &config_.settings,
&config_.params, nullptr, config_.user_data);
if (rv != 0) {
return -1;
if (ngtcp2_conn_client_new(
&conn_, &dcid, &scid, &path, NGTCP2_PROTO_VER_V1, &config_.callbacks,
&config_.settings, &config_.params, nullptr, config_.user_data) != 0) {
return std::unexpected{Error::QUIC};
}
ssl_ctx_ = wolfSSL_CTX_new(wolfTLSv1_3_client_method());
if (!ssl_ctx_) {
return -1;
return std::unexpected{Error::CRYPTO};
}
if (ngtcp2_crypto_wolfssl_configure_client_context(ssl_ctx_) != 0) {
return -1;
return std::unexpected{Error::CRYPTO};
}
ssl_ = wolfSSL_new(ssl_ctx_);
if (!ssl_) {
return -1;
return std::unexpected{Error::CRYPTO};
}
if (wolfSSL_UseALPN(ssl_, const_cast<char *>(ALPN_LIST.data()),
ALPN_LIST.size(),
WOLFSSL_ALPN_FAILED_ON_MISMATCH) != WOLFSSL_SUCCESS) {
return -1;
return std::unexpected{Error::CRYPTO};
}
wolfSSL_set_app_data(ssl_, &conn_ref_);
@@ -463,11 +461,12 @@ int Endpoint::setup_client(const ngtcp2_addr *remote_addr) {
initialized_ = true;
return 0;
return {};
}
int Endpoint::on_read(const NetworkPath &path, std::span<const uint8_t> pkt,
const Context &ctx) {
std::expected<void, Error> Endpoint::on_read(const NetworkPath &path,
std::span<const uint8_t> pkt,
const Context &ctx) {
auto ts = to_ngtcp2_tstamp(ctx.ts);
auto cpath = to_ngtcp2_path(path);
@@ -475,35 +474,35 @@ int Endpoint::on_read(const NetworkPath &path, std::span<const uint8_t> pkt,
ngtcp2_conn_read_pkt(conn_, &cpath, nullptr, pkt.data(), pkt.size(), ts);
if (rv != 0) {
std::cerr << "ngtcp2_conn_read_pkt: " << ngtcp2_strerror(rv) << std::endl;
return -1;
return std::unexpected{Error::QUIC};
}
ctx.endpoint->get_channel().schedule_timeout(ctx.ts);
return 0;
return {};
}
int Endpoint::on_write(const Context &ctx) {
if (config_.on_write(conn_, ctx) != 0) {
return -1;
std::expected<void, Error> Endpoint::on_write(const Context &ctx) {
if (auto rv = config_.on_write(conn_, ctx); !rv) {
return rv;
}
auto next_expiry_ts = ngtcp2_conn_get_expiry(conn_);
if (next_expiry_ts == UINT64_MAX) {
return 0;
return {};
}
ctx.endpoint->get_channel().schedule_timeout(to_timestamp(next_expiry_ts));
return 0;
return {};
}
int Endpoint::on_timeout(const Context &ctx) {
std::expected<void, Error> Endpoint::on_timeout(const Context &ctx) {
auto rv = ngtcp2_conn_handle_expiry(conn_, to_ngtcp2_tstamp(ctx.ts));
if (rv != 0) {
std::cerr << "ngtcp2_conn_handle_expiry: " << ngtcp2_strerror(rv)
<< std::endl;
return -1;
return std::unexpected{Error::QUIC};
}
return on_write(ctx);
@@ -701,10 +700,14 @@ std::optional<std::tuple<Event, Endpoint &>> Simulator::get_next_event() {
return {{std::move(ev), server_}};
}
int Simulator::run() {
if (client_.get_initialized() ||
client_.setup_client(&server_.get_endpoint_config().local_addr) != 0) {
return -1;
std::expected<void, Error> Simulator::run() {
if (client_.get_initialized()) {
return std::unexpected{Error::INTERNAL};
}
if (auto rv = client_.setup_client(&server_.get_endpoint_config().local_addr);
!rv) {
return rv;
}
auto ts = Timestamp{};
@@ -744,15 +747,15 @@ int Simulator::run() {
.endpoint = &ep,
};
if (ep.on_timeout(ctx) != 0) {
return -1;
if (auto rv = ep.on_timeout(ctx); !rv) {
return rv;
}
break;
}
case EVENT_TYPE_PKT:
if (deliver_pkt(ep, event.path.invert(), event.pkt, ts) != 0) {
return -1;
if (auto rv = deliver_pkt(ep, event.path.invert(), event.pkt, ts); !rv) {
return rv;
}
break;
@@ -760,18 +763,20 @@ int Simulator::run() {
}
if (k == max_events_) {
return -1;
return std::unexpected{Error::INTERNAL};
}
return 0;
return {};
}
Endpoint &Simulator::get_opposite_endpoint(const Endpoint &ep) {
return &ep == &client_ ? server_ : client_;
}
int Simulator::deliver_pkt(Endpoint &remote_ep, const NetworkPath &path,
std::span<const uint8_t> pkt, Timestamp ts) {
std::expected<void, Error> Simulator::deliver_pkt(Endpoint &remote_ep,
const NetworkPath &path,
std::span<const uint8_t> pkt,
Timestamp ts) {
auto &local_ep = get_opposite_endpoint(remote_ep);
if (!local_ep.get_initialized() && local_ep.get_endpoint_config().server) {
@@ -780,19 +785,20 @@ int Simulator::deliver_pkt(Endpoint &remote_ep, const NetworkPath &path,
auto rv =
ngtcp2_pkt_decode_version_cid(&vcid, pkt.data(), pkt.size(), CIDLEN);
if (rv != 0) {
return 0;
return std::unexpected{Error::QUIC};
}
ngtcp2_pkt_hd hd;
if (ngtcp2_accept(&hd, pkt.data(), pkt.size()) != 0) {
return 0;
return {};
}
if (local_ep.setup_server(
if (auto rv = local_ep.setup_server(
{vcid.dcid, vcid.dcidlen}, {vcid.scid, vcid.scidlen}, vcid.version,
&remote_ep.get_endpoint_config().local_addr) != 0) {
return -1;
&remote_ep.get_endpoint_config().local_addr);
!rv) {
return rv;
}
}
@@ -820,7 +826,8 @@ void HandshakeApp::configure(EndpointConfig &config) {
config.callbacks.handshake_confirmed = handshake_confirmed;
}
config.on_write = [](ngtcp2_conn *conn, const Context &ctx) {
config.on_write = [](ngtcp2_conn *conn,
const Context &ctx) -> std::expected<void, Error> {
std::array<uint8_t, MAX_UDP_PAYLOAD_SIZE> buf;
auto ts = to_ngtcp2_tstamp(ctx.ts);
@@ -833,11 +840,11 @@ void HandshakeApp::configure(EndpointConfig &config) {
if (nwrite < 0) {
std::cerr << "ngtcp2_conn_write_pkt: "
<< ngtcp2_strerror(static_cast<int>(nwrite)) << std::endl;
return -1;
return std::unexpected{Error::QUIC};
}
if (nwrite == 0) {
return 0;
return {};
}
ngtcp2_conn_update_pkt_tx_time(conn, ts);
@@ -845,7 +852,7 @@ void HandshakeApp::configure(EndpointConfig &config) {
ctx.endpoint->get_channel().send_pkt(
to_network_path(&ps.path), {buf.data(), static_cast<size_t>(nwrite)});
return 0;
return {};
};
config.user_data = this;
@@ -872,7 +879,11 @@ void UniStreamApp::configure(EndpointConfig &config) {
[](ngtcp2_conn *conn, uint64_t max_streams, void *user_data) {
auto app = static_cast<UniStreamApp *>(user_data);
return app->extend_max_local_streams_uni(conn);
if (!app->extend_max_local_streams_uni(conn)) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
return 0;
};
config.on_write = [this](ngtcp2_conn *conn, const Context &ctx) {
@@ -903,9 +914,10 @@ void UniStreamApp::stream_close(ngtcp2_conn *conn, int64_t stream_id) {
}
}
int UniStreamApp::extend_max_local_streams_uni(ngtcp2_conn *conn) {
std::expected<void, Error>
UniStreamApp::extend_max_local_streams_uni(ngtcp2_conn *conn) {
if (stream_id_ != -1) {
return 0;
return {};
}
int64_t stream_id;
@@ -914,16 +926,17 @@ int UniStreamApp::extend_max_local_streams_uni(ngtcp2_conn *conn) {
if (rv != 0) {
std::cerr << "ngtcp2_conn_open_uni_stream: " << ngtcp2_strerror(rv)
<< std::endl;
return NGTCP2_ERR_CALLBACK_FAILURE;
return std::unexpected{Error::QUIC};
}
stream_id_ = stream_id;
start_ts_ = to_timestamp(ngtcp2_conn_get_timestamp(conn));
return 0;
return {};
}
int UniStreamApp::on_write(ngtcp2_conn *conn, const Context &ctx) {
std::expected<void, Error> UniStreamApp::on_write(ngtcp2_conn *conn,
const Context &ctx) {
std::array<uint8_t, MAX_UDP_PAYLOAD_SIZE> buf;
int64_t stream_id;
@@ -958,17 +971,17 @@ int UniStreamApp::on_write(ngtcp2_conn *conn, const Context &ctx) {
&ndatalen, flags, stream_id, &vec, veccnt, ts);
if (nwrite < 0) {
if (nwrite == NGTCP2_ERR_STREAM_DATA_BLOCKED) {
return 0;
return {};
}
std::cerr << "ngtcp2_conn_writev_stream: "
<< ngtcp2_strerror(static_cast<int>(nwrite)) << std::endl;
return -1;
return std::unexpected{Error::QUIC};
}
if (nwrite == 0) {
return 0;
return {};
}
if (ndatalen > 0) {
@@ -980,7 +993,7 @@ int UniStreamApp::on_write(ngtcp2_conn *conn, const Context &ctx) {
ctx.endpoint->get_channel().send_pkt(
to_network_path(&ps.path), {buf.data(), static_cast<size_t>(nwrite)});
return 0;
return {};
}
} // namespace ngtcp2
+20 -14
View File
@@ -42,6 +42,7 @@
#include <wolfssl/ssl.h>
#include "network.h"
#include "shared.h"
namespace ngtcp2 {
inline constexpr size_t MAX_UDP_PAYLOAD_SIZE = 1500;
@@ -106,7 +107,8 @@ struct EndpointConfig {
void *user_data{};
LinkConfig link;
std::function<int(ngtcp2_conn *, const Context &)> on_write;
std::function<std::expected<void, Error>(ngtcp2_conn *, const Context &)>
on_write;
};
ngtcp2_callbacks default_client_callbacks();
@@ -206,17 +208,19 @@ public:
Endpoint &operator=(const Endpoint &) = delete;
Endpoint &operator=(Endpoint &&) noexcept;
int setup_client(const ngtcp2_addr *remote_addr);
int setup_server(std::span<const uint8_t> original_dcid,
std::span<const uint8_t> client_scid, uint32_t version,
const ngtcp2_addr *remote_addr);
std::expected<void, Error> setup_client(const ngtcp2_addr *remote_addr);
std::expected<void, Error>
setup_server(std::span<const uint8_t> original_dcid,
std::span<const uint8_t> client_scid, uint32_t version,
const ngtcp2_addr *remote_addr);
ngtcp2_conn *get_conn() const { return conn_; }
bool get_initialized() const { return initialized_; }
const EndpointConfig &get_endpoint_config() const { return config_; }
int on_read(const NetworkPath &path, std::span<const uint8_t> pkt,
const Context &ctx);
int on_write(const Context &ctx);
int on_timeout(const Context &ctx);
std::expected<void, Error> on_read(const NetworkPath &path,
std::span<const uint8_t> pkt,
const Context &ctx);
std::expected<void, Error> on_write(const Context &ctx);
std::expected<void, Error> on_timeout(const Context &ctx);
Channel &get_channel() { return channel_; }
private:
@@ -238,14 +242,16 @@ public:
Simulator &operator=(const Simulator &) = delete;
Simulator &operator=(Simulator &&) noexcept;
int run();
std::expected<void, Error> run();
void set_max_events(size_t n) { max_events_ = n; }
private:
Endpoint &get_opposite_endpoint(const Endpoint &ep);
std::optional<std::tuple<Event, Endpoint &>> get_next_event();
int deliver_pkt(Endpoint &remote_ep, const NetworkPath &path,
std::span<const uint8_t> pkt, Timestamp ts);
std::expected<void, Error> deliver_pkt(Endpoint &remote_ep,
const NetworkPath &path,
std::span<const uint8_t> pkt,
Timestamp ts);
Endpoint client_;
Endpoint server_;
@@ -279,8 +285,8 @@ public:
private:
void stream_close(ngtcp2_conn *conn, int64_t stream_id);
int extend_max_local_streams_uni(ngtcp2_conn *conn);
int on_write(ngtcp2_conn *conn, const Context &ctx);
std::expected<void, Error> extend_max_local_streams_uni(ngtcp2_conn *conn);
std::expected<void, Error> on_write(ngtcp2_conn *conn, const Context &ctx);
int64_t stream_id_{-1};
uint64_t max_bytes_{};
+4 -12
View File
@@ -80,13 +80,9 @@ void test_sim_handshake(void) {
svapp.configure(sv);
sv.link = link;
int rv;
auto rv = Simulator{Endpoint(cl), Endpoint(sv)}.run();
{
rv = Simulator{Endpoint(cl), Endpoint(sv)}.run();
}
assert_int(0, ==, rv);
assert_true(rv.has_value());
assert_true(clapp.get_handshake_confirmed());
assert_true(svapp.get_handshake_confirmed());
}
@@ -132,13 +128,9 @@ void test_sim_unistream(void) {
svapp.configure(sv);
sv.link = link;
int rv;
auto rv = Simulator{Endpoint(cl), Endpoint(sv)}.run();
{
rv = Simulator{Endpoint(cl), Endpoint(sv)}.run();
}
assert_int(0, ==, rv);
assert_true(rv.has_value());
assert_true(svapp.is_all_bytes_sent());
assert_uint64(link.compute_expected_goodput(link.delay * 2), <=,
svapp.compute_goodput());
+7 -7
View File
@@ -48,7 +48,7 @@
#define REMOTE_HOST "127.0.0.1"
#define REMOTE_PORT "4433"
#define ALPN "\xahq-interop"
#define ALPN "\xAhq-interop"
#define MESSAGE "GET /\r\n"
/*
@@ -206,8 +206,8 @@ static void rand_cb(uint8_t *dest, size_t destlen,
}
static int get_new_connection_id_cb(ngtcp2_conn *conn, ngtcp2_cid *cid,
uint8_t *token, size_t cidlen,
void *user_data) {
ngtcp2_stateless_reset_token *token,
size_t cidlen, void *user_data) {
(void)conn;
(void)user_data;
@@ -217,7 +217,7 @@ static int get_new_connection_id_cb(ngtcp2_conn *conn, ngtcp2_cid *cid,
cid->datalen = cidlen;
if (RAND_bytes(token, NGTCP2_STATELESS_RESET_TOKENLEN) != 1) {
if (RAND_bytes(token->data, sizeof(token->data)) != 1) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
@@ -293,12 +293,12 @@ static int client_quic_init(struct client *c,
.recv_retry = ngtcp2_crypto_recv_retry_cb,
.extend_max_local_streams_bidi = extend_max_local_streams_bidi,
.rand = rand_cb,
.get_new_connection_id = get_new_connection_id_cb,
.update_key = ngtcp2_crypto_update_key_cb,
.delete_crypto_aead_ctx = ngtcp2_crypto_delete_crypto_aead_ctx_cb,
.delete_crypto_cipher_ctx = ngtcp2_crypto_delete_crypto_cipher_ctx_cb,
.get_path_challenge_data = ngtcp2_crypto_get_path_challenge_data_cb,
.version_negotiation = ngtcp2_crypto_version_negotiation_cb,
.get_new_connection_id2 = get_new_connection_id_cb,
.get_path_challenge_data2 = ngtcp2_crypto_get_path_challenge_data2_cb,
};
ngtcp2_cid dcid, scid;
ngtcp2_settings settings;
@@ -593,7 +593,7 @@ static int client_init(struct client *c) {
struct sockaddr_storage remote_addr, local_addr;
socklen_t remote_addrlen, local_addrlen = sizeof(local_addr);
memset(c, 0, sizeof(*c));
*c = (struct client){0};
ngtcp2_ccerr_default(&c->last_error);
+5 -5
View File
@@ -79,9 +79,9 @@ uint64_t siphash24(std::span<const uint64_t, 2> key,
std::span<const uint8_t> input) {
const auto orig_input_len = input.size();
uint64_t v[]{
key[0] ^ UINT64_C(0x736f6d6570736575),
key[1] ^ UINT64_C(0x646f72616e646f6d),
key[0] ^ UINT64_C(0x6c7967656e657261),
key[0] ^ UINT64_C(0x736F6D6570736575),
key[1] ^ UINT64_C(0x646F72616E646F6D),
key[0] ^ UINT64_C(0x6C7967656E657261),
key[1] ^ UINT64_C(0x7465646279746573),
};
@@ -97,7 +97,7 @@ uint64_t siphash24(std::span<const uint64_t, 2> key,
std::array<uint8_t, sizeof(uint64_t)> last_block{};
std::ranges::copy(input, std::ranges::begin(last_block));
last_block.back() = orig_input_len & 0xff;
last_block.back() = orig_input_len & 0xFF;
auto last_block_word = CRYPTO_load_u64_le(last_block);
v[3] ^= last_block_word;
@@ -105,7 +105,7 @@ uint64_t siphash24(std::span<const uint64_t, 2> key,
siphash_round(v);
v[0] ^= last_block_word;
v[2] ^= 0xff;
v[2] ^= 0xFF;
siphash_round(v);
siphash_round(v);
siphash_round(v);
+1 -1
View File
@@ -62,7 +62,7 @@ void test_siphash(void) {
std::array<uint8_t, 15> input;
std::iota(std::ranges::begin(input), std::ranges::end(input), 0);
assert_uint64(0xa129ca6149be45e5ull, ==, siphash24(key, input));
assert_uint64(0xA129CA6149BE45E5ULL, ==, siphash24(key, input));
}
void test_siphash_vector(void) {
+319 -319
View File
@@ -4,293 +4,293 @@
const uint8_t vectors_sip64[64][8] = {
{
0x31,
0x0e,
0x0e,
0xdd,
0x0E,
0x0E,
0xDD,
0x47,
0xdb,
0x6f,
0xDB,
0x6F,
0x72,
},
{
0xfd,
0xFD,
0x67,
0xdc,
0xDC,
0x93,
0xc5,
0xC5,
0x39,
0xf8,
0xF8,
0x74,
},
{
0x5a,
0x4f,
0xa9,
0xd9,
0x5A,
0x4F,
0xA9,
0xD9,
0x09,
0x80,
0x6c,
0x0d,
0x6C,
0x0D,
},
{
0x2d,
0x7e,
0xfb,
0xd7,
0x2D,
0x7E,
0xFB,
0xD7,
0x96,
0x66,
0x67,
0x85,
},
{
0xb7,
0xB7,
0x87,
0x71,
0x27,
0xe0,
0xE0,
0x94,
0x27,
0xcf,
0xCF,
},
{
0x8d,
0xa6,
0x8D,
0xA6,
0x99,
0xcd,
0xCD,
0x64,
0x55,
0x76,
0x18,
},
{
0xce,
0xe3,
0xfe,
0xCE,
0xE3,
0xFE,
0x58,
0x6e,
0x6E,
0x46,
0xc9,
0xcb,
0xC9,
0xCB,
},
{
0x37,
0xd1,
0xD1,
0x01,
0x8b,
0xf5,
0x8B,
0xF5,
0x00,
0x02,
0xab,
0xAB,
},
{
0x62,
0x24,
0x93,
0x9a,
0x9A,
0x79,
0xf5,
0xf5,
0xF5,
0xF5,
0x93,
},
{
0xb0,
0xe4,
0xa9,
0x0b,
0xdf,
0xB0,
0xE4,
0xA9,
0x0B,
0xDF,
0x82,
0x00,
0x9e,
0x9E,
},
{
0xf3,
0xb9,
0xdd,
0xF3,
0xB9,
0xDD,
0x94,
0xc5,
0xbb,
0x5d,
0x7a,
0xC5,
0xBB,
0x5D,
0x7A,
},
{
0xa7,
0xad,
0x6b,
0xA7,
0xAD,
0x6B,
0x22,
0x46,
0x2f,
0xb3,
0xf4,
0x2F,
0xB3,
0xF4,
},
{
0xfb,
0xe5,
0x0e,
0xFB,
0xE5,
0x0E,
0x86,
0xbc,
0x8f,
0x1e,
0xBC,
0x8F,
0x1E,
0x75,
},
{
0x90,
0x3d,
0x3D,
0x84,
0xc0,
0xC0,
0x27,
0x56,
0xea,
0xEA,
0x14,
},
{
0xee,
0xf2,
0x7a,
0x8e,
0xEE,
0xF2,
0x7A,
0x8E,
0x90,
0xca,
0xCA,
0x23,
0xf7,
0xF7,
},
{
0xe5,
0xE5,
0x45,
0xbe,
0xBE,
0x49,
0x61,
0xca,
0xCA,
0x29,
0xa1,
0xA1,
},
{
0xdb,
0x9b,
0xc2,
0xDB,
0x9B,
0xC2,
0x57,
0x7f,
0xcc,
0x2a,
0x3f,
0x7F,
0xCC,
0x2A,
0x3F,
},
{
0x94,
0x47,
0xbe,
0x2c,
0xf5,
0xe9,
0x9a,
0xBE,
0x2C,
0xF5,
0xE9,
0x9A,
0x69,
},
{
0x9c,
0xd3,
0x8d,
0x9C,
0xD3,
0x8D,
0x96,
0xf0,
0xb3,
0xc1,
0x4b,
0xF0,
0xB3,
0xC1,
0x4B,
},
{
0xbd,
0xBD,
0x61,
0x79,
0xa7,
0x1d,
0xc9,
0x6d,
0xbb,
0xA7,
0x1D,
0xC9,
0x6D,
0xBB,
},
{
0x98,
0xee,
0xa2,
0x1a,
0xf2,
0x5c,
0xd6,
0xbe,
0xEE,
0xA2,
0x1A,
0xF2,
0x5C,
0xD6,
0xBE,
},
{
0xc7,
0xC7,
0x67,
0x3b,
0x2e,
0xb0,
0xcb,
0xf2,
0xd0,
0x3B,
0x2E,
0xB0,
0xCB,
0xF2,
0xD0,
},
{
0x88,
0x3e,
0xa3,
0xe3,
0x3E,
0xA3,
0xE3,
0x95,
0x67,
0x53,
0x93,
},
{
0xc8,
0xce,
0x5c,
0xcd,
0x8c,
0xC8,
0xCE,
0x5C,
0xCD,
0x8C,
0x03,
0x0c,
0xa8,
0x0C,
0xA8,
},
{
0x94,
0xaf,
0xAF,
0x49,
0xf6,
0xc6,
0xF6,
0xC6,
0x50,
0xad,
0xb8,
0xAD,
0xB8,
},
{
0xea,
0xb8,
0xEA,
0xB8,
0x85,
0x8a,
0xde,
0x8A,
0xDE,
0x92,
0xe1,
0xbc,
0xE1,
0xBC,
},
{
0xf3,
0xF3,
0x15,
0xbb,
0x5b,
0xb8,
0xBB,
0x5B,
0xB8,
0x35,
0xd8,
0xD8,
0x17,
},
{
0xad,
0xcf,
0x6b,
0xAD,
0xCF,
0x6B,
0x07,
0x63,
0x61,
0x2e,
0x2f,
0x2E,
0x2F,
},
{
0xa5,
0xc9,
0x1d,
0xa7,
0xac,
0xaa,
0x4d,
0xde,
0xA5,
0xC9,
0x1D,
0xA7,
0xAC,
0xAA,
0x4D,
0xDE,
},
{
0x71,
@@ -299,77 +299,77 @@ const uint8_t vectors_sip64[64][8] = {
0x87,
0x66,
0x50,
0xa2,
0xa6,
0xA2,
0xA6,
},
{
0x28,
0xef,
0xEF,
0x49,
0x5c,
0x5C,
0x53,
0xa3,
0xA3,
0x87,
0xad,
0xAD,
},
{
0x42,
0xc3,
0xC3,
0x41,
0xd8,
0xfa,
0xD8,
0xFA,
0x92,
0xd8,
0xD8,
0x32,
},
{
0xce,
0x7c,
0xf2,
0xCE,
0x7C,
0xF2,
0x72,
0x2f,
0x2F,
0x51,
0x27,
0x71,
},
{
0xe3,
0xE3,
0x78,
0x59,
0xf9,
0xF9,
0x46,
0x23,
0xf3,
0xa7,
0xF3,
0xA7,
},
{
0x38,
0x12,
0x05,
0xbb,
0x1a,
0xb0,
0xe0,
0xBB,
0x1A,
0xB0,
0xE0,
0x12,
},
{
0xae,
0xAE,
0x97,
0xa1,
0x0f,
0xd4,
0xA1,
0x0F,
0xD4,
0x34,
0xe0,
0xE0,
0x15,
},
{
0xb4,
0xa3,
0xB4,
0xA3,
0x15,
0x08,
0xbe,
0xff,
0x4d,
0xBE,
0xFF,
0x4D,
0x31,
},
{
@@ -377,80 +377,80 @@ const uint8_t vectors_sip64[64][8] = {
0x39,
0x62,
0x29,
0xf0,
0xF0,
0x90,
0x79,
0x02,
},
{
0x4d,
0x0c,
0xf4,
0x9e,
0xe5,
0xd4,
0xdc,
0xca,
0x4D,
0x0C,
0xF4,
0x9E,
0xE5,
0xD4,
0xDC,
0xCA,
},
{
0x5c,
0x5C,
0x73,
0x33,
0x6a,
0x6A,
0x76,
0xd8,
0xbf,
0x9a,
0xD8,
0xBF,
0x9A,
},
{
0xd0,
0xa7,
0xD0,
0xA7,
0x04,
0x53,
0x6b,
0xa9,
0x3e,
0x0e,
0x6B,
0xA9,
0x3E,
0x0E,
},
{
0x92,
0x59,
0x58,
0xfc,
0xd6,
0xFC,
0xD6,
0x42,
0x0c,
0xad,
0x0C,
0xAD,
},
{
0xa9,
0xA9,
0x15,
0xc2,
0x9b,
0xc8,
0xC2,
0x9B,
0xC8,
0x06,
0x73,
0x18,
},
{
0x95,
0x2b,
0x2B,
0x79,
0xf3,
0xbc,
0x0a,
0xa6,
0xd4,
0xF3,
0xBC,
0x0A,
0xA6,
0xD4,
},
{
0xf2,
0x1d,
0xf2,
0xe4,
0x1d,
0xF2,
0x1D,
0xF2,
0xE4,
0x1D,
0x45,
0x35,
0xf9,
0xF9,
},
{
0x87,
@@ -458,188 +458,188 @@ const uint8_t vectors_sip64[64][8] = {
0x75,
0x19,
0x04,
0x8f,
0x8F,
0x53,
0xa9,
0xA9,
},
{
0x10,
0xa5,
0x6c,
0xf5,
0xdf,
0xcd,
0x9a,
0xdb,
0xA5,
0x6C,
0xF5,
0xDF,
0xCD,
0x9A,
0xDB,
},
{
0xeb,
0xEB,
0x75,
0x09,
0x5c,
0xcd,
0x5C,
0xCD,
0x98,
0x6c,
0xd0,
0x6C,
0xD0,
},
{
0x51,
0xa9,
0xcb,
0x9e,
0xcb,
0xa3,
0xA9,
0xCB,
0x9E,
0xCB,
0xA3,
0x12,
0xe6,
0xE6,
},
{
0x96,
0xaf,
0xad,
0xfc,
0x2c,
0xe6,
0xAF,
0xAD,
0xFC,
0x2C,
0xE6,
0x66,
0xc7,
0xC7,
},
{
0x72,
0xfe,
0xFE,
0x52,
0x97,
0x5a,
0x5A,
0x43,
0x64,
0xee,
0xEE,
},
{
0x5a,
0x5A,
0x16,
0x45,
0xb2,
0xB2,
0x76,
0xd5,
0xD5,
0x92,
0xa1,
0xA1,
},
{
0xb2,
0xB2,
0x74,
0xcb,
0x8e,
0xbf,
0xCB,
0x8E,
0xBF,
0x87,
0x87,
0x0a,
0x0A,
},
{
0x6f,
0x9b,
0xb4,
0x6F,
0x9B,
0xB4,
0x20,
0x3d,
0xe7,
0xb3,
0x3D,
0xE7,
0xB3,
0x81,
},
{
0xea,
0xec,
0xb2,
0xa3,
0x0b,
0xEA,
0xEC,
0xB2,
0xA3,
0x0B,
0x22,
0xa8,
0x7f,
0xA8,
0x7F,
},
{
0x99,
0x24,
0xa4,
0x3c,
0xc1,
0xA4,
0x3C,
0xC1,
0x31,
0x57,
0x24,
},
{
0xbd,
0xBD,
0x83,
0x8d,
0x3a,
0xaf,
0xbf,
0x8d,
0xb7,
0x8D,
0x3A,
0xAF,
0xBF,
0x8D,
0xB7,
},
{
0x0b,
0x1a,
0x2a,
0x0B,
0x1A,
0x2A,
0x32,
0x65,
0xd5,
0x1a,
0xea,
0xD5,
0x1A,
0xEA,
},
{
0x13,
0x50,
0x79,
0xa3,
0xA3,
0x23,
0x1c,
0xe6,
0x1C,
0xE6,
0x60,
},
{
0x93,
0x2b,
0x2B,
0x28,
0x46,
0xe4,
0xd7,
0xE4,
0xD7,
0x06,
0x66,
},
{
0xe1,
0xE1,
0x91,
0x5f,
0x5c,
0xb1,
0xec,
0xa4,
0x6c,
0x5F,
0x5C,
0xB1,
0xEC,
0xA4,
0x6C,
},
{
0xf3,
0xF3,
0x25,
0x96,
0x5c,
0xa1,
0x6d,
0x5C,
0xA1,
0x6D,
0x62,
0x9f,
0x9F,
},
{
0x57,
0x5f,
0xf2,
0x8e,
0x5F,
0xF2,
0x8E,
0x60,
0x38,
0x1b,
0xe5,
0x1B,
0xE5,
},
{
0x72,
0x45,
0x06,
0xeb,
0x4c,
0xEB,
0x4C,
0x32,
0x8a,
0x8A,
0x95,
},
};
+19
View File
@@ -41,6 +41,13 @@ template <std::unsigned_integral T>
return static_cast<std::make_signed_t<T>>(n);
}
template <typename T, std::size_t N>
[[nodiscard]] auto as_uint8_span(std::span<T, N> s) noexcept {
return std::span<const uint8_t, N == std::dynamic_extent ? std::dynamic_extent
: N * sizeof(T)>{
reinterpret_cast<const uint8_t *>(s.data()), s.size_bytes()};
}
template <typename F> struct Defer {
explicit Defer(F &&f) noexcept(std::is_nothrow_constructible_v<F, F &&>)
: f(std::forward<F>(f)) {}
@@ -89,4 +96,16 @@ as_writable_uint8_span(std::span<T, N> s) noexcept {
reinterpret_cast<uint8_t *>(s.data()), s.size_bytes()};
}
template <typename R>
requires(std::ranges::contiguous_range<R> && std::ranges::sized_range<R> &&
std::ranges::borrowed_range<R> &&
!std::is_array_v<std::remove_cvref_t<R>> &&
sizeof(std::ranges::range_value_t<R>) ==
sizeof(std::string_view::value_type))
[[nodiscard]] std::string_view as_string_view(R &&r) {
return std::string_view{
reinterpret_cast<std::string_view::const_pointer>(std::ranges::data(r)),
std::ranges::size(r)};
}
#endif // !defined(TEMPLATE_H)
+22 -22
View File
@@ -55,13 +55,13 @@ int new_session_cb(SSL *ssl, SSL_SESSION *session) {
auto f = BIO_new_file(config.session_file, "w");
if (f == nullptr) {
std::cerr << "Could not write TLS session in " << config.session_file
<< std::endl;
std::println(stderr, "Could not write TLS session in {}",
config.session_file);
return 0;
}
if (!PEM_write_bio_SSL_SESSION(f, session)) {
std::cerr << "Unable to write TLS session to file" << std::endl;
std::println(stderr, "Unable to write TLS session to file");
}
BIO_free(f);
@@ -70,40 +70,40 @@ int new_session_cb(SSL *ssl, SSL_SESSION *session) {
}
} // namespace
int TLSClientContext::init(const char *private_key_file,
const char *cert_file) {
std::expected<void, Error> TLSClientContext::init(const char *private_key_file,
const char *cert_file) {
ssl_ctx_ = SSL_CTX_new(TLS_client_method());
if (!ssl_ctx_) {
std::cerr << "SSL_CTX_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "SSL_CTX_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (ngtcp2_crypto_boringssl_configure_client_context(ssl_ctx_) != 0) {
std::cerr << "ngtcp2_crypto_boringssl_configure_client_context failed"
<< std::endl;
return -1;
std::println(stderr,
"ngtcp2_crypto_boringssl_configure_client_context failed");
return std::unexpected{Error::CRYPTO};
}
SSL_CTX_set_default_verify_paths(ssl_ctx_);
if (SSL_CTX_set1_groups_list(ssl_ctx_, config.groups) != 1) {
std::cerr << "SSL_CTX_set1_groups_list failed" << std::endl;
return -1;
std::println(stderr, "SSL_CTX_set1_groups_list failed");
return std::unexpected{Error::CRYPTO};
}
if (private_key_file && cert_file) {
if (SSL_CTX_use_PrivateKey_file(ssl_ctx_, private_key_file,
SSL_FILETYPE_PEM) != 1) {
std::cerr << "SSL_CTX_use_PrivateKey_file: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_use_PrivateKey_file: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_use_certificate_chain_file(ssl_ctx_, cert_file) != 1) {
std::cerr << "SSL_CTX_use_certificate_chain_file: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_use_certificate_chain_file: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
}
@@ -117,12 +117,12 @@ int TLSClientContext::init(const char *private_key_file,
if (!SSL_CTX_add_cert_compression_alg(
ssl_ctx_, ngtcp2::tls::CERTIFICATE_COMPRESSION_ALGO_BROTLI,
ngtcp2::tls::cert_compress, ngtcp2::tls::cert_decompress)) {
std::cerr << "SSL_CTX_add_cert_compression_alg failed" << std::endl;
return -1;
std::println(stderr, "SSL_CTX_add_cert_compression_alg failed");
return std::unexpected{Error::CRYPTO};
}
#endif // defined(HAVE_LIBBROTLI)
return 0;
return {};
}
extern std::ofstream keylog_file;
+6 -1
View File
@@ -31,12 +31,17 @@
#include <openssl/ssl.h>
#include "shared.h"
using namespace ngtcp2;
class TLSClientContext {
public:
TLSClientContext() = default;
~TLSClientContext();
int init(const char *private_key_file, const char *cert_file);
std::expected<void, Error> init(const char *private_key_file,
const char *cert_file);
SSL_CTX *get_native_handle() const;
+21 -21
View File
@@ -67,17 +67,17 @@ int new_session_cb(SSL *ssl, SSL_SESSION *session) {
if (SSL_SESSION_get_max_early_data(session) !=
std::numeric_limits<uint32_t>::max()) {
std::cerr << "max_early_data_size is not 0xffffffff" << std::endl;
std::println(stderr, "max_early_data_size is not 0xffffffff");
}
auto f = BIO_new_file(config.session_file, "w");
if (f == nullptr) {
std::cerr << "Could not write TLS session in " << config.session_file
<< std::endl;
std::println(stderr, "Could not write TLS session in {}",
config.session_file);
return 0;
}
if (!PEM_write_bio_SSL_SESSION(f, session)) {
std::cerr << "Unable to write TLS session to file" << std::endl;
std::println(stderr, "Unable to write TLS session to file");
}
BIO_free(f);
@@ -86,40 +86,40 @@ int new_session_cb(SSL *ssl, SSL_SESSION *session) {
}
} // namespace
int TLSClientContext::init(const char *private_key_file,
const char *cert_file) {
std::expected<void, Error> TLSClientContext::init(const char *private_key_file,
const char *cert_file) {
ssl_ctx_ = SSL_CTX_new(TLS_client_method());
if (!ssl_ctx_) {
std::cerr << "SSL_CTX_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "SSL_CTX_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
SSL_CTX_set_default_verify_paths(ssl_ctx_);
if (SSL_CTX_set_ciphersuites(ssl_ctx_, config.ciphers) != 1) {
std::cerr << "SSL_CTX_set_ciphersuites: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_set_ciphersuites: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_set1_groups_list(ssl_ctx_, config.groups) != 1) {
std::cerr << "SSL_CTX_set1_groups_list failed" << std::endl;
return -1;
std::println(stderr, "SSL_CTX_set1_groups_list failed");
return std::unexpected{Error::CRYPTO};
}
if (private_key_file && cert_file) {
if (SSL_CTX_use_PrivateKey_file(ssl_ctx_, private_key_file,
SSL_FILETYPE_PEM) != 1) {
std::cerr << "SSL_CTX_use_PrivateKey_file: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_use_PrivateKey_file: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_use_certificate_chain_file(ssl_ctx_, cert_file) != 1) {
std::cerr << "SSL_CTX_use_certificate_chain_file: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_use_certificate_chain_file: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
}
@@ -129,7 +129,7 @@ int TLSClientContext::init(const char *private_key_file,
SSL_CTX_sess_set_new_cb(ssl_ctx_, new_session_cb);
}
return 0;
return {};
}
extern std::ofstream keylog_file;
+6 -1
View File
@@ -31,12 +31,17 @@
#include <openssl/ssl.h>
#include "shared.h"
using namespace ngtcp2;
class TLSClientContext {
public:
TLSClientContext() = default;
~TLSClientContext();
int init(const char *private_key_file, const char *cert_file);
std::expected<void, Error> init(const char *private_key_file,
const char *cert_file);
SSL_CTX *get_native_handle() const;
+24 -23
View File
@@ -47,14 +47,14 @@ int save_ticket_cb(ptls_save_ticket_t *self, ptls_t *ptls, ptls_iovec_t input) {
auto f = BIO_new_file(config.session_file, "w");
if (f == nullptr) {
std::cerr << "Could not write TLS session in " << config.session_file
<< std::endl;
std::println(stderr, "Could not write TLS session in {}",
config.session_file);
return 0;
}
if (!PEM_write_bio(f, "PICOTLS SESSION PARAMETERS", "", input.base,
static_cast<long>(input.len))) {
std::cerr << "Unable to write TLS session to file" << std::endl;
std::println(stderr, "Unable to write TLS session to file");
}
BIO_free(f);
@@ -113,12 +113,12 @@ TLSClientContext::~TLSClientContext() {
ptls_context_t *TLSClientContext::get_native_handle() { return &ctx_; }
int TLSClientContext::init(const char *private_key_file,
const char *cert_file) {
std::expected<void, Error> TLSClientContext::init(const char *private_key_file,
const char *cert_file) {
if (ngtcp2_crypto_picotls_configure_client_context(&ctx_) != 0) {
std::cerr << "ngtcp2_crypto_picotls_configure_client_context failed"
<< std::endl;
return -1;
std::println(stderr,
"ngtcp2_crypto_picotls_configure_client_context failed");
return std::unexpected{Error::CRYPTO};
}
if (config.session_file) {
@@ -127,45 +127,46 @@ int TLSClientContext::init(const char *private_key_file,
if (private_key_file && cert_file) {
if (ptls_load_certificates(&ctx_, cert_file) != 0) {
std::cerr << "ptls_load_certificates failed" << std::endl;
return -1;
std::println(stderr, "ptls_load_certificates failed");
return std::unexpected{Error::CRYPTO};
}
if (load_private_key(private_key_file) != 0) {
return -1;
if (auto rv = load_private_key(private_key_file); !rv) {
return rv;
}
}
return 0;
return {};
}
int TLSClientContext::load_private_key(const char *private_key_file) {
std::expected<void, Error>
TLSClientContext::load_private_key(const char *private_key_file) {
auto fp = fopen(private_key_file, "rb");
if (fp == nullptr) {
std::cerr << "Could not open private key file " << private_key_file << ": "
<< strerror(errno) << std::endl;
return -1;
std::println(stderr, "Could not open private key file {}: {}",
private_key_file, strerror(errno));
return std::unexpected{Error::IO};
}
auto fp_d = defer([fp] { fclose(fp); });
auto pkey = PEM_read_PrivateKey(fp, nullptr, nullptr, nullptr);
if (pkey == nullptr) {
std::cerr << "Could not read private key file " << private_key_file
<< std::endl;
return -1;
std::println(stderr, "Could not read private key file {}",
private_key_file);
return std::unexpected{Error::IO};
}
auto pkey_d = defer([pkey] { EVP_PKEY_free(pkey); });
if (ptls_openssl_init_sign_certificate(&sign_cert_, pkey) != 0) {
std::cerr << "ptls_openssl_init_sign_certificate failed" << std::endl;
return -1;
std::println(stderr, "ptls_openssl_init_sign_certificate failed");
return std::unexpected{Error::CRYPTO};
}
ctx_.sign_certificate = &sign_cert_.super;
return 0;
return {};
}
void TLSClientContext::enable_keylog() { ctx_.log_event = &log_event; }
+7 -2
View File
@@ -32,19 +32,24 @@
#include <picotls.h>
#include <picotls/openssl.h>
#include "shared.h"
using namespace ngtcp2;
class TLSClientContext {
public:
TLSClientContext();
~TLSClientContext();
int init(const char *private_key_file, const char *cert_file);
std::expected<void, Error> init(const char *private_key_file,
const char *cert_file);
ptls_context_t *get_native_handle();
void enable_keylog();
private:
int load_private_key(const char *private_key_file);
std::expected<void, Error> load_private_key(const char *private_key_file);
ptls_context_t ctx_;
ptls_openssl_sign_certificate_t sign_cert_{};
+24 -24
View File
@@ -67,17 +67,17 @@ int new_session_cb(SSL *ssl, SSL_SESSION *session) {
if (SSL_SESSION_get_max_early_data(session) !=
std::numeric_limits<uint32_t>::max()) {
std::cerr << "max_early_data_size is not 0xffffffff" << std::endl;
std::println(stderr, "max_early_data_size is not 0xffffffff");
}
auto f = BIO_new_file(config.session_file, "w");
if (f == nullptr) {
std::cerr << "Could not write TLS session in " << config.session_file
<< std::endl;
std::println(stderr, "Could not write TLS session in {}",
config.session_file);
return 0;
}
if (!PEM_write_bio_SSL_SESSION(f, session)) {
std::cerr << "Unable to write TLS session to file" << std::endl;
std::println(stderr, "Unable to write TLS session to file");
}
BIO_free(f);
@@ -86,46 +86,46 @@ int new_session_cb(SSL *ssl, SSL_SESSION *session) {
}
} // namespace
int TLSClientContext::init(const char *private_key_file,
const char *cert_file) {
std::expected<void, Error> TLSClientContext::init(const char *private_key_file,
const char *cert_file) {
ssl_ctx_ = SSL_CTX_new(TLS_client_method());
if (!ssl_ctx_) {
std::cerr << "SSL_CTX_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "SSL_CTX_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (ngtcp2_crypto_quictls_configure_client_context(ssl_ctx_) != 0) {
std::cerr << "ngtcp2_crypto_quictls_configure_client_context failed"
<< std::endl;
return -1;
std::println(stderr,
"ngtcp2_crypto_quictls_configure_client_context failed");
return std::unexpected{Error::CRYPTO};
}
SSL_CTX_set_default_verify_paths(ssl_ctx_);
if (SSL_CTX_set_ciphersuites(ssl_ctx_, config.ciphers) != 1) {
std::cerr << "SSL_CTX_set_ciphersuites: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_set_ciphersuites: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_set1_groups_list(ssl_ctx_, config.groups) != 1) {
std::cerr << "SSL_CTX_set1_groups_list failed" << std::endl;
return -1;
std::println(stderr, "SSL_CTX_set1_groups_list failed");
return std::unexpected{Error::CRYPTO};
}
if (private_key_file && cert_file) {
if (SSL_CTX_use_PrivateKey_file(ssl_ctx_, private_key_file,
SSL_FILETYPE_PEM) != 1) {
std::cerr << "SSL_CTX_use_PrivateKey_file: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_use_PrivateKey_file: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_use_certificate_chain_file(ssl_ctx_, cert_file) != 1) {
std::cerr << "SSL_CTX_use_certificate_chain_file: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_use_certificate_chain_file: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
}
@@ -135,7 +135,7 @@ int TLSClientContext::init(const char *private_key_file,
SSL_CTX_sess_set_new_cb(ssl_ctx_, new_session_cb);
}
return 0;
return {};
}
extern std::ofstream keylog_file;
+6 -1
View File
@@ -31,12 +31,17 @@
#include <openssl/ssl.h>
#include "shared.h"
using namespace ngtcp2;
class TLSClientContext {
public:
TLSClientContext() = default;
~TLSClientContext();
int init(const char *private_key_file, const char *cert_file);
std::expected<void, Error> init(const char *private_key_file,
const char *cert_file);
SSL_CTX *get_native_handle() const;
+29 -37
View File
@@ -49,8 +49,6 @@ WOLFSSL_CTX *TLSClientContext::get_native_handle() const { return ssl_ctx_; }
namespace {
int new_session_cb(WOLFSSL *ssl, WOLFSSL_SESSION *session) {
std::cerr << "new_session_cb called" << std::endl;
auto conn_ref =
static_cast<ngtcp2_crypto_conn_ref *>(wolfSSL_get_app_data(ssl));
auto c = static_cast<ClientBase *>(conn_ref->user_data);
@@ -60,18 +58,18 @@ int new_session_cb(WOLFSSL *ssl, WOLFSSL_SESSION *session) {
#ifdef HAVE_SESSION_TICKET
if (wolfSSL_SESSION_get_max_early_data(session) !=
std::numeric_limits<uint32_t>::max()) {
std::cerr << "max_early_data_size is not 0xffffffff" << std::endl;
std::println(stderr, "max_early_data_size is not 0xffffffff");
}
unsigned char sbuffer[16 * 1024], *data;
auto sz = wolfSSL_i2d_SSL_SESSION(session, nullptr);
if (sz <= 0) {
std::cerr << "Could not export TLS session in " << config.session_file
<< std::endl;
std::println(stderr, "Could not export TLS session in {}",
config.session_file);
return 0;
}
if (static_cast<size_t>(sz) > sizeof(sbuffer)) {
std::cerr << "Exported TLS session too large" << std::endl;
std::println(stderr, "Exported TLS session too large");
return 0;
}
data = sbuffer;
@@ -79,8 +77,8 @@ int new_session_cb(WOLFSSL *ssl, WOLFSSL_SESSION *session) {
auto f = wolfSSL_BIO_new_file(config.session_file, "w");
if (f == nullptr) {
std::cerr << "Could not write TLS session in " << config.session_file
<< std::endl;
std::println(stderr, "Could not write TLS session in {}",
config.session_file);
return 0;
}
@@ -88,32 +86,29 @@ int new_session_cb(WOLFSSL *ssl, WOLFSSL_SESSION *session) {
if (!wolfSSL_PEM_write_bio(f, "WOLFSSL SESSION PARAMETERS", "", sbuffer,
sz)) {
std::cerr << "Unable to write TLS session to file" << std::endl;
std::println(stderr, "Unable to write TLS session to file");
return 0;
}
std::cerr << "new_session_cb: wrote " << sz << " of session data"
<< std::endl;
#else // !defined(HAVE_SESSION_TICKET)
std::cerr << "TLS session tickets not enabled in wolfSSL " << std::endl;
std::println(stderr, "TLS session tickets not enabled in wolfSSL");
#endif // !defined(HAVE_SESSION_TICKET)
return 0;
}
} // namespace
int TLSClientContext::init(const char *private_key_file,
const char *cert_file) {
std::expected<void, Error> TLSClientContext::init(const char *private_key_file,
const char *cert_file) {
ssl_ctx_ = wolfSSL_CTX_new(wolfTLSv1_3_client_method());
if (!ssl_ctx_) {
std::cerr << "wolfSSL_CTX_new: "
<< wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "wolfSSL_CTX_new: {}",
wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (ngtcp2_crypto_wolfssl_configure_client_context(ssl_ctx_) != 0) {
std::cerr << "ngtcp2_crypto_wolfssl_configure_client_context failed"
<< std::endl;
return -1;
std::println(stderr,
"ngtcp2_crypto_wolfssl_configure_client_context failed");
return std::unexpected{Error::CRYPTO};
}
if (wolfSSL_CTX_set_default_verify_paths(ssl_ctx_) ==
@@ -124,34 +119,31 @@ int TLSClientContext::init(const char *private_key_file,
if (wolfSSL_CTX_set_cipher_list(ssl_ctx_, config.ciphers) !=
WOLFSSL_SUCCESS) {
std::cerr << "wolfSSL_CTX_set_cipher_list: "
<< wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "wolfSSL_CTX_set_cipher_list: {}",
wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (wolfSSL_CTX_set1_groups_list(
ssl_ctx_, const_cast<char *>(config.groups)) != WOLFSSL_SUCCESS) {
std::cerr << "wolfSSL_CTX_set1_groups_list(" << config.groups << ") failed"
<< std::endl;
return -1;
std::println(stderr, "wolfSSL_CTX_set1_groups_list({}) failed",
config.groups);
return std::unexpected{Error::CRYPTO};
}
if (private_key_file && cert_file) {
if (wolfSSL_CTX_use_PrivateKey_file(ssl_ctx_, private_key_file,
SSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) {
std::cerr << "wolfSSL_CTX_use_PrivateKey_file: "
<< wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "wolfSSL_CTX_use_PrivateKey_file: {}",
wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (wolfSSL_CTX_use_certificate_chain_file(ssl_ctx_, cert_file) !=
WOLFSSL_SUCCESS) {
std::cerr << "wolfSSL_CTX_use_certificate_chain_file: "
<< wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "wolfSSL_CTX_use_certificate_chain_file: {}",
wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
}
@@ -160,7 +152,7 @@ int TLSClientContext::init(const char *private_key_file,
wolfSSL_CTX_sess_set_new_cb(ssl_ctx_, new_session_cb);
}
return 0;
return {};
}
extern std::ofstream keylog_file;
+6 -1
View File
@@ -33,12 +33,17 @@
#include <wolfssl/ssl.h>
#include <wolfssl/quic.h>
#include "shared.h"
using namespace ngtcp2;
class TLSClientContext {
public:
TLSClientContext() = default;
~TLSClientContext();
int init(const char *private_key_file, const char *cert_file);
std::expected<void, Error> init(const char *private_key_file,
const char *cert_file);
WOLFSSL_CTX *get_native_handle() const;
+24 -22
View File
@@ -35,19 +35,20 @@
extern Config config;
int TLSClientSession::init(bool &early_data_enabled,
const TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client,
uint32_t quic_version, AppProtocol app_proto) {
std::expected<void, Error>
TLSClientSession::init(bool &early_data_enabled,
const TLSClientContext &tls_ctx, const char *remote_addr,
ClientBase *client, uint32_t quic_version,
AppProtocol app_proto) {
early_data_enabled = false;
auto ssl_ctx = tls_ctx.get_native_handle();
ssl_ = SSL_new(ssl_ctx);
if (!ssl_) {
std::cerr << "SSL_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "SSL_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
SSL_set_app_data(ssl_, client->conn_ref());
@@ -75,17 +76,17 @@ int TLSClientSession::init(bool &early_data_enabled,
if (config.session_file) {
auto f = BIO_new_file(config.session_file, "r");
if (f == nullptr) {
std::cerr << "Could not read TLS session file " << config.session_file
<< std::endl;
std::println(stderr, "Could not read TLS session file {}",
config.session_file);
} else {
auto session = PEM_read_bio_SSL_SESSION(f, nullptr, 0, nullptr);
BIO_free(f);
if (session == nullptr) {
std::cerr << "Could not read TLS session file " << config.session_file
<< std::endl;
std::println(stderr, "Could not read TLS session file {}",
config.session_file);
} else {
if (!SSL_set_session(ssl_, session)) {
std::cerr << "Could not set session" << std::endl;
std::println(stderr, "Could not set session");
} else if (!config.disable_early_data &&
SSL_SESSION_early_data_capable(session)) {
early_data_enabled = true;
@@ -99,12 +100,12 @@ int TLSClientSession::init(bool &early_data_enabled,
if (!config.ech_config_list.empty() &&
SSL_set1_ech_config_list(ssl_, config.ech_config_list.data(),
config.ech_config_list.size()) != 1) {
std::cerr << "Could not set ECHConfigList: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "Could not set ECHConfigList: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
return 0;
return {};
}
bool TLSClientSession::get_early_data_accepted() const {
@@ -115,20 +116,21 @@ bool TLSClientSession::get_ech_accepted() const {
return SSL_ech_accepted(ssl_);
}
int TLSClientSession::write_ech_config_list(const char *path) const {
std::expected<void, Error>
TLSClientSession::write_ech_config_list(const char *path) const {
const uint8_t *retry_configs;
size_t retry_configslen;
SSL_get0_ech_retry_configs(ssl_, &retry_configs, &retry_configslen);
if (retry_configslen == 0) {
std::cerr << "No ECH retry configs found" << std::endl;
return -1;
std::println(stderr, "No ECH retry configs found");
return std::unexpected{Error::CRYPTO};
}
auto f = std::ofstream(path);
if (!f) {
return -1;
return std::unexpected{Error::IO};
}
f.write(reinterpret_cast<const char *>(retry_configs),
@@ -136,8 +138,8 @@ int TLSClientSession::write_ech_config_list(const char *path) const {
f.close();
if (!f) {
return -1;
return std::unexpected{Error::IO};
}
return 0;
return {};
}
+5 -4
View File
@@ -41,13 +41,14 @@ class TLSClientSession : public TLSSessionBase {
public:
TLSClientSession() = default;
int init(bool &early_data_enabled, const TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client, uint32_t quic_version,
AppProtocol app_proto);
std::expected<void, Error> init(bool &early_data_enabled,
const TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client,
uint32_t quic_version, AppProtocol app_proto);
bool get_early_data_accepted() const;
bool get_ech_accepted() const;
int write_ech_config_list(const char *path) const;
std::expected<void, Error> write_ech_config_list(const char *path) const;
};
#endif // !defined(TLS_CLIENT_SESSION_BORINGSSL_H)
+16 -16
View File
@@ -36,27 +36,27 @@
extern Config config;
int TLSClientSession::init(bool &early_data_enabled,
const TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client,
uint32_t quic_version, AppProtocol app_proto) {
std::expected<void, Error>
TLSClientSession::init(bool &early_data_enabled,
const TLSClientContext &tls_ctx, const char *remote_addr,
ClientBase *client, uint32_t quic_version,
AppProtocol app_proto) {
early_data_enabled = false;
auto ssl_ctx = tls_ctx.get_native_handle();
auto ssl = SSL_new(ssl_ctx);
if (!ssl) {
std::cerr << "SSL_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "SSL_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
ngtcp2_crypto_ossl_ctx_set_ssl(ossl_ctx_, ssl);
if (ngtcp2_crypto_ossl_configure_client_session(ssl) != 0) {
std::cerr << "ngtcp2_crypto_ossl_configure_client_session failed"
<< std::endl;
return -1;
std::println(stderr, "ngtcp2_crypto_ossl_configure_client_session failed");
return std::unexpected{Error::CRYPTO};
}
SSL_set_app_data(ssl, client->conn_ref());
@@ -84,17 +84,17 @@ int TLSClientSession::init(bool &early_data_enabled,
if (config.session_file) {
auto f = BIO_new_file(config.session_file, "r");
if (f == nullptr) {
std::cerr << "Could not read TLS session file " << config.session_file
<< std::endl;
std::println(stderr, "Could not read TLS session file {}",
config.session_file);
} else {
auto session = PEM_read_bio_SSL_SESSION(f, nullptr, 0, nullptr);
BIO_free(f);
if (session == nullptr) {
std::cerr << "Could not read TLS session file " << config.session_file
<< std::endl;
std::println(stderr, "Could not read TLS session file {}",
config.session_file);
} else {
if (!SSL_set_session(ssl, session)) {
std::cerr << "Could not set session" << std::endl;
std::println(stderr, "Could not set session");
} else if (!config.disable_early_data &&
SSL_SESSION_get_max_early_data(session)) {
early_data_enabled = true;
@@ -106,7 +106,7 @@ int TLSClientSession::init(bool &early_data_enabled,
}
}
return 0;
return {};
}
bool TLSClientSession::get_early_data_accepted() const {
+7 -4
View File
@@ -41,13 +41,16 @@ class TLSClientSession : public TLSSessionBase {
public:
TLSClientSession() = default;
int init(bool &early_data_enabled, const TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client, uint32_t quic_version,
AppProtocol app_proto);
std::expected<void, Error> init(bool &early_data_enabled,
const TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client,
uint32_t quic_version, AppProtocol app_proto);
bool get_early_data_accepted() const;
bool get_ech_accepted() const { return false; }
int write_ech_config_list(const char *path) const { return 0; }
std::expected<void, Error> write_ech_config_list(const char *path) const {
return {};
}
};
#endif // !defined(TLS_CLIENT_SESSION_OSSL_H)
+16 -15
View File
@@ -68,13 +68,14 @@ auto negotiated_protocols_hq = std::to_array<ptls_iovec_t>({
});
} // namespace
int TLSClientSession::init(bool &early_data_enabled, TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client,
uint32_t quic_version, AppProtocol app_proto) {
std::expected<void, Error>
TLSClientSession::init(bool &early_data_enabled, TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client,
uint32_t quic_version, AppProtocol app_proto) {
cptls_.ptls = ptls_client_new(tls_ctx.get_native_handle());
if (!cptls_.ptls) {
std::cerr << "ptls_client_new failed" << std::endl;
return -1;
std::println(stderr, "ptls_client_new failed");
return std::unexpected{Error::CRYPTO};
}
*ptls_get_data_ptr(cptls_.ptls) = client->conn_ref();
@@ -92,9 +93,9 @@ int TLSClientSession::init(bool &early_data_enabled, TLSClientContext &tls_ctx,
};
if (ngtcp2_crypto_picotls_configure_client_session(&cptls_, conn) != 0) {
std::cerr << "ngtcp2_crypto_picotls_configure_client_session failed"
<< std::endl;
return -1;
std::println(stderr,
"ngtcp2_crypto_picotls_configure_client_session failed");
return std::unexpected{Error::CRYPTO};
}
switch (app_proto) {
@@ -121,8 +122,8 @@ int TLSClientSession::init(bool &early_data_enabled, TLSClientContext &tls_ctx,
if (config.session_file) {
auto f = BIO_new_file(config.session_file, "r");
if (f == nullptr) {
std::cerr << "Could not read TLS session file " << config.session_file
<< std::endl;
std::println(stderr, "Could not read TLS session file {}",
config.session_file);
} else {
auto f_d = defer([f] { BIO_free(f); });
@@ -131,12 +132,12 @@ int TLSClientSession::init(bool &early_data_enabled, TLSClientContext &tls_ctx,
long datalen;
if (PEM_read_bio(f, &name, &header, &data, &datalen) != 1) {
std::cerr << "Could not read TLS session file " << config.session_file
<< std::endl;
std::println(stderr, "Could not read TLS session file {}",
config.session_file);
} else {
if ("PICOTLS SESSION PARAMETERS"sv != name) {
std::cerr << "TLS session file contains unexpected name: " << name
<< std::endl;
std::println(stderr, "TLS session file contains unexpected name: {}",
name);
} else {
hsprops.client.session_ticket.base =
new uint8_t[static_cast<size_t>(datalen)];
@@ -158,7 +159,7 @@ int TLSClientSession::init(bool &early_data_enabled, TLSClientContext &tls_ctx,
}
}
return 0;
return {};
}
bool TLSClientSession::get_early_data_accepted() const {
+7 -4
View File
@@ -42,13 +42,16 @@ public:
TLSClientSession() = default;
~TLSClientSession();
int init(bool &early_data_enabled, TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client, uint32_t quic_version,
AppProtocol app_proto);
std::expected<void, Error> init(bool &early_data_enabled,
TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client,
uint32_t quic_version, AppProtocol app_proto);
bool get_early_data_accepted() const;
bool get_ech_accepted() const { return false; }
int write_ech_config_list(const char *path) const { return 0; }
std::expected<void, Error> write_ech_config_list(const char *path) const {
return {};
}
};
#endif // !defined(TLS_CLIENT_SESSION_PICOTLS_H)
+14 -13
View File
@@ -36,19 +36,20 @@
extern Config config;
int TLSClientSession::init(bool &early_data_enabled,
const TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client,
uint32_t quic_version, AppProtocol app_proto) {
std::expected<void, Error>
TLSClientSession::init(bool &early_data_enabled,
const TLSClientContext &tls_ctx, const char *remote_addr,
ClientBase *client, uint32_t quic_version,
AppProtocol app_proto) {
early_data_enabled = false;
auto ssl_ctx = tls_ctx.get_native_handle();
ssl_ = SSL_new(ssl_ctx);
if (!ssl_) {
std::cerr << "SSL_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "SSL_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
SSL_set_app_data(ssl_, client->conn_ref());
@@ -76,17 +77,17 @@ int TLSClientSession::init(bool &early_data_enabled,
if (config.session_file) {
auto f = BIO_new_file(config.session_file, "r");
if (f == nullptr) {
std::cerr << "Could not read TLS session file " << config.session_file
<< std::endl;
std::println(stderr, "Could not read TLS session file {}",
config.session_file);
} else {
auto session = PEM_read_bio_SSL_SESSION(f, nullptr, 0, nullptr);
BIO_free(f);
if (session == nullptr) {
std::cerr << "Could not read TLS session file " << config.session_file
<< std::endl;
std::println(stderr, "Could not read TLS session file {}",
config.session_file);
} else {
if (!SSL_set_session(ssl_, session)) {
std::cerr << "Could not set session" << std::endl;
std::println(stderr, "Could not set session");
}
#ifndef LIBRESSL_VERSION_NUMBER
else if (!config.disable_early_data &&
@@ -100,7 +101,7 @@ int TLSClientSession::init(bool &early_data_enabled,
}
}
return 0;
return {};
}
bool TLSClientSession::get_early_data_accepted() const {
+7 -4
View File
@@ -41,13 +41,16 @@ class TLSClientSession : public TLSSessionBase {
public:
TLSClientSession() = default;
int init(bool &early_data_enabled, const TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client, uint32_t quic_version,
AppProtocol app_proto);
std::expected<void, Error> init(bool &early_data_enabled,
const TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client,
uint32_t quic_version, AppProtocol app_proto);
bool get_early_data_accepted() const;
bool get_ech_accepted() const { return false; }
int write_ech_config_list(const char *path) const { return 0; }
std::expected<void, Error> write_ech_config_list(const char *path) const {
return {};
}
};
#endif // !defined(TLS_CLIENT_SESSION_QUICTLS_H)
+20 -28
View File
@@ -37,27 +37,20 @@ using namespace std::literals;
extern Config config;
namespace {
int wolfssl_session_ticket_cb(WOLFSSL *ssl, const unsigned char *ticket,
int ticketSz, void *cb_ctx) {
std::cerr << "session ticket callback invoked" << std::endl;
return 0;
}
} // namespace
int TLSClientSession::init(bool &early_data_enabled,
const TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client,
uint32_t quic_version, AppProtocol app_proto) {
std::expected<void, Error>
TLSClientSession::init(bool &early_data_enabled,
const TLSClientContext &tls_ctx, const char *remote_addr,
ClientBase *client, uint32_t quic_version,
AppProtocol app_proto) {
early_data_enabled = false;
auto ssl_ctx = tls_ctx.get_native_handle();
ssl_ = wolfSSL_new(ssl_ctx);
if (!ssl_) {
std::cerr << "wolfSSL_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "wolfSSL_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
wolfSSL_set_app_data(ssl_, client->conn_ref());
@@ -92,8 +85,8 @@ int TLSClientSession::init(bool &early_data_enabled,
#ifdef HAVE_SESSION_TICKET
auto f = wolfSSL_BIO_new_file(config.session_file, "r");
if (f == nullptr) {
std::cerr << "Could not open TLS session file " << config.session_file
<< std::endl;
std::println(stderr, "Could not open TLS session file {}",
config.session_file);
} else {
char *name, *header;
unsigned char *data;
@@ -102,23 +95,23 @@ int TLSClientSession::init(bool &early_data_enabled,
WOLFSSL_SESSION *session;
if (wolfSSL_PEM_read_bio(f, &name, &header, &data, &datalen) != 1) {
std::cerr << "Could not read TLS session file " << config.session_file
<< std::endl;
std::println(stderr, "Could not read TLS session file {}",
config.session_file);
} else {
if ("WOLFSSL SESSION PARAMETERS"sv != name) {
std::cerr << "TLS session file contains unexpected name: " << name
<< std::endl;
std::println(stderr, "TLS session file contains unexpected name: {}",
name);
} else {
pdata = data;
session = wolfSSL_d2i_SSL_SESSION(nullptr, &pdata, datalen);
if (session == nullptr) {
std::cerr << "Could not parse TLS session from file "
<< config.session_file << std::endl;
std::println(stderr, "Could not parse TLS session from file {}",
config.session_file);
} else {
auto ret = wolfSSL_set_session(ssl_, session);
if (ret != WOLFSSL_SUCCESS) {
std::cerr << "Could not install TLS session from file "
<< config.session_file << std::endl;
std::println(stderr, "Could not install TLS session from file {}",
config.session_file);
} else {
if (!config.disable_early_data &&
wolfSSL_SESSION_get_max_early_data(session)) {
@@ -137,13 +130,12 @@ int TLSClientSession::init(bool &early_data_enabled,
wolfSSL_BIO_free(f);
}
wolfSSL_UseSessionTicket(ssl_);
wolfSSL_set_SessionTicket_cb(ssl_, wolfssl_session_ticket_cb, nullptr);
#else // !defined(HAVE_SESSION_TICKET)
std::cerr << "TLS session im-/export not enabled in wolfSSL" << std::endl;
std::println(stderr, "TLS session im-/export not enabled in wolfSSL");
#endif // !defined(HAVE_SESSION_TICKET)
}
return 0;
return {};
}
bool TLSClientSession::get_early_data_accepted() const {
+7 -4
View File
@@ -41,13 +41,16 @@ class TLSClientSession : public TLSSessionBase {
public:
TLSClientSession() = default;
int init(bool &early_data_enabled, const TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client, uint32_t quic_version,
AppProtocol app_proto);
std::expected<void, Error> init(bool &early_data_enabled,
const TLSClientContext &tls_ctx,
const char *remote_addr, ClientBase *client,
uint32_t quic_version, AppProtocol app_proto);
bool get_early_data_accepted() const;
bool get_ech_accepted() const { return false; }
int write_ech_config_list(const char *path) const { return 0; }
std::expected<void, Error> write_ech_config_list(const char *path) const {
return {};
}
};
#endif // !defined(TLS_CLIENT_SESSION_WOLFSSL_H)
+38 -37
View File
@@ -64,8 +64,7 @@ int alpn_select_proto_h3_cb(SSL *ssl, const unsigned char **out,
break;
default:
if (!config.quiet) {
std::cerr << "Unexpected quic protocol version: " << std::hex << "0x"
<< version << std::dec << std::endl;
std::println(stderr, "Unexpected quic protocol version: {:#x}", version);
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
@@ -80,7 +79,8 @@ int alpn_select_proto_h3_cb(SSL *ssl, const unsigned char **out,
}
if (!config.quiet) {
std::cerr << "Client did not present ALPN " << &H3_ALPN_V1[1] << std::endl;
std::println(stderr, "Client did not present ALPN {}",
as_string_view(H3_ALPN_V1.subspan(1)));
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
@@ -103,8 +103,7 @@ int alpn_select_proto_hq_cb(SSL *ssl, const unsigned char **out,
break;
default:
if (!config.quiet) {
std::cerr << "Unexpected quic protocol version: " << std::hex << "0x"
<< version << std::dec << std::endl;
std::println(stderr, "Unexpected quic protocol version: {:#x}", version);
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
@@ -119,7 +118,8 @@ int alpn_select_proto_hq_cb(SSL *ssl, const unsigned char **out,
}
if (!config.quiet) {
std::cerr << "Client did not present ALPN " << &HQ_ALPN_V1[1] << std::endl;
std::println(stderr, "Client did not present ALPN {}",
as_string_view(HQ_ALPN_V1.subspan(1)));
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
@@ -134,15 +134,16 @@ int verify_cb(int preverify_ok, X509_STORE_CTX *ctx) {
}
} // namespace
int TLSServerContext::init(const char *private_key_file, const char *cert_file,
AppProtocol app_proto) {
std::expected<void, Error> TLSServerContext::init(const char *private_key_file,
const char *cert_file,
AppProtocol app_proto) {
constexpr static unsigned char sid_ctx[] = "ngtcp2 server";
ssl_ctx_ = SSL_CTX_new(TLS_server_method());
if (!ssl_ctx_) {
std::cerr << "SSL_CTX_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "SSL_CTX_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
constexpr auto ssl_opts = (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
@@ -152,16 +153,16 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
SSL_CTX_set_options(ssl_ctx_, ssl_opts);
if (SSL_CTX_set1_groups_list(ssl_ctx_, config.groups) != 1) {
std::cerr << "SSL_CTX_set1_groups_list failed" << std::endl;
return -1;
std::println(stderr, "SSL_CTX_set1_groups_list failed");
return std::unexpected{Error::CRYPTO};
}
SSL_CTX_set_mode(ssl_ctx_, SSL_MODE_RELEASE_BUFFERS);
if (ngtcp2_crypto_boringssl_configure_server_context(ssl_ctx_) != 0) {
std::cerr << "ngtcp2_crypto_boringssl_configure_server_context failed"
<< std::endl;
return -1;
std::println(stderr,
"ngtcp2_crypto_boringssl_configure_server_context failed");
return std::unexpected{Error::CRYPTO};
}
switch (app_proto) {
@@ -177,21 +178,21 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
if (SSL_CTX_use_PrivateKey_file(ssl_ctx_, private_key_file,
SSL_FILETYPE_PEM) != 1) {
std::cerr << "SSL_CTX_use_PrivateKey_file: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_use_PrivateKey_file: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_use_certificate_chain_file(ssl_ctx_, cert_file) != 1) {
std::cerr << "SSL_CTX_use_certificate_chain_file: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_use_certificate_chain_file: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_check_private_key(ssl_ctx_) != 1) {
std::cerr << "SSL_CTX_check_private_key: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_check_private_key: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
SSL_CTX_set_session_id_context(ssl_ctx_, sid_ctx, sizeof(sid_ctx) - 1);
@@ -207,8 +208,8 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
if (!SSL_CTX_add_cert_compression_alg(
ssl_ctx_, ngtcp2::tls::CERTIFICATE_COMPRESSION_ALGO_BROTLI,
ngtcp2::tls::cert_compress, ngtcp2::tls::cert_decompress)) {
std::cerr << "SSL_CTX_add_cert_compression_alg failed" << std::endl;
return -1;
std::println(stderr, "SSL_CTX_add_cert_compression_alg failed");
return std::unexpected{Error::CRYPTO};
}
#endif // defined(HAVE_LIBBROTLI)
@@ -220,10 +221,10 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
if (EVP_HPKE_KEY_init(pkey, EVP_hpke_x25519_hkdf_sha256(),
echconf.private_key.bytes.data(),
echconf.private_key.bytes.size()) != 1) {
std::cerr << "EVP_HPKE_KEY_init failed: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
std::println(stderr, "EVP_HPKE_KEY_init failed: {}",
ERR_error_string(ERR_get_error(), nullptr));
return -1;
return std::unexpected{Error::CRYPTO};
}
auto pkey_d = defer([pkey] { EVP_HPKE_KEY_free(pkey); });
@@ -233,19 +234,19 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
if (SSL_ECH_KEYS_add(keys, 1, echconf.ech_config.data(),
echconf.ech_config.size(), pkey) != 1) {
std::cerr << "SSL_ECH_KEYS_add failed: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_ECH_KEYS_add failed: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_set1_ech_keys(ssl_ctx_, keys) != 1) {
std::cerr << "SSL_CTX_set1_ech_keys failed: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_set1_ech_keys failed: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
}
return 0;
return {};
}
extern std::ofstream keylog_file;
+2 -2
View File
@@ -40,8 +40,8 @@ public:
TLSServerContext() = default;
~TLSServerContext();
int init(const char *private_key_file, const char *cert_file,
AppProtocol app_proto);
std::expected<void, Error> init(const char *private_key_file,
const char *cert_file, AppProtocol app_proto);
SSL_CTX *get_native_handle() const;
+27 -26
View File
@@ -75,8 +75,7 @@ int alpn_select_proto_h3_cb(SSL *ssl, const unsigned char **out,
break;
default:
if (!config.quiet) {
std::cerr << "Unexpected quic protocol version: " << std::hex << "0x"
<< version << std::dec << std::endl;
std::println(stderr, "Unexpected quic protocol version: {:#x}", version);
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
@@ -91,7 +90,8 @@ int alpn_select_proto_h3_cb(SSL *ssl, const unsigned char **out,
}
if (!config.quiet) {
std::cerr << "Client did not present ALPN " << &H3_ALPN_V1[1] << std::endl;
std::println(stderr, "Client did not present ALPN {}",
as_string_view(H3_ALPN_V1.subspan(1)));
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
@@ -114,8 +114,7 @@ int alpn_select_proto_hq_cb(SSL *ssl, const unsigned char **out,
break;
default:
if (!config.quiet) {
std::cerr << "Unexpected quic protocol version: " << std::hex << "0x"
<< version << std::dec << std::endl;
std::println(stderr, "Unexpected quic protocol version: {:#x}", version);
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
@@ -130,7 +129,8 @@ int alpn_select_proto_hq_cb(SSL *ssl, const unsigned char **out,
}
if (!config.quiet) {
std::cerr << "Client did not present ALPN " << &HQ_ALPN_V1[1] << std::endl;
std::println(stderr, "Client did not present ALPN {}",
as_string_view(HQ_ALPN_V1.subspan(1)));
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
@@ -212,15 +212,16 @@ SSL_TICKET_RETURN decrypt_ticket_cb(SSL *ssl, SSL_SESSION *session,
}
} // namespace
int TLSServerContext::init(const char *private_key_file, const char *cert_file,
AppProtocol app_proto) {
std::expected<void, Error> TLSServerContext::init(const char *private_key_file,
const char *cert_file,
AppProtocol app_proto) {
constexpr static unsigned char sid_ctx[] = "ngtcp2 server";
ssl_ctx_ = SSL_CTX_new(TLS_server_method());
if (!ssl_ctx_) {
std::cerr << "SSL_CTX_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "SSL_CTX_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
SSL_CTX_set_max_early_data(ssl_ctx_, UINT32_MAX);
@@ -233,14 +234,14 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
SSL_CTX_set_options(ssl_ctx_, ssl_opts);
if (SSL_CTX_set_ciphersuites(ssl_ctx_, config.ciphers) != 1) {
std::cerr << "SSL_CTX_set_ciphersuites: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_set_ciphersuites: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_set1_groups_list(ssl_ctx_, config.groups) != 1) {
std::cerr << "SSL_CTX_set1_groups_list failed" << std::endl;
return -1;
std::println(stderr, "SSL_CTX_set1_groups_list failed");
return std::unexpected{Error::CRYPTO};
}
SSL_CTX_set_mode(ssl_ctx_, SSL_MODE_RELEASE_BUFFERS);
@@ -258,21 +259,21 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
if (SSL_CTX_use_PrivateKey_file(ssl_ctx_, private_key_file,
SSL_FILETYPE_PEM) != 1) {
std::cerr << "SSL_CTX_use_PrivateKey_file: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_use_PrivateKey_file: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_use_certificate_chain_file(ssl_ctx_, cert_file) != 1) {
std::cerr << "SSL_CTX_use_certificate_chain_file: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_use_certificate_chain_file: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_check_private_key(ssl_ctx_) != 1) {
std::cerr << "SSL_CTX_check_private_key: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_check_private_key: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
SSL_CTX_set_session_id_context(ssl_ctx_, sid_ctx, sizeof(sid_ctx) - 1);
@@ -287,7 +288,7 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
SSL_CTX_set_session_ticket_cb(ssl_ctx_, gen_ticket_cb, decrypt_ticket_cb,
nullptr);
return 0;
return {};
}
extern std::ofstream keylog_file;
+2 -2
View File
@@ -40,8 +40,8 @@ public:
TLSServerContext() = default;
~TLSServerContext();
int init(const char *private_key_file, const char *cert_file,
AppProtocol app_proto);
std::expected<void, Error> init(const char *private_key_file,
const char *cert_file, AppProtocol app_proto);
SSL_CTX *get_native_handle() const;
+22 -20
View File
@@ -308,8 +308,9 @@ TLSServerContext::~TLSServerContext() {
ptls_context_t *TLSServerContext::get_native_handle() { return &ctx_; }
int TLSServerContext::init(const char *private_key_file, const char *cert_file,
AppProtocol app_proto) {
std::expected<void, Error> TLSServerContext::init(const char *private_key_file,
const char *cert_file,
AppProtocol app_proto) {
switch (app_proto) {
case AppProtocol::H3:
ctx_.on_client_hello = &on_client_hello_h3;
@@ -322,54 +323,55 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
}
if (ngtcp2_crypto_picotls_configure_server_context(&ctx_) != 0) {
std::cerr << "ngtcp2_crypto_picotls_configure_server_context failed"
<< std::endl;
return -1;
std::println(stderr,
"ngtcp2_crypto_picotls_configure_server_context failed");
return std::unexpected{Error::CRYPTO};
}
if (ptls_load_certificates(&ctx_, cert_file) != 0) {
std::cerr << "ptls_load_certificates failed" << std::endl;
return -1;
std::println(stderr, "ptls_load_certificates failed");
return std::unexpected{Error::CRYPTO};
}
if (load_private_key(private_key_file) != 0) {
return -1;
if (auto rv = load_private_key(private_key_file); !rv) {
return rv;
}
if (config.verify_client) {
ctx_.require_client_authentication = 1;
}
return 0;
return {};
}
int TLSServerContext::load_private_key(const char *private_key_file) {
std::expected<void, Error>
TLSServerContext::load_private_key(const char *private_key_file) {
auto fp = fopen(private_key_file, "rb");
if (fp == nullptr) {
std::cerr << "Could not open private key file " << private_key_file << ": "
<< strerror(errno) << std::endl;
return -1;
std::println(stderr, "Could not open private key file {}: {}",
private_key_file, strerror(errno));
return std::unexpected{Error::IO};
}
auto fp_d = defer([fp] { fclose(fp); });
auto pkey = PEM_read_PrivateKey(fp, nullptr, nullptr, nullptr);
if (pkey == nullptr) {
std::cerr << "Could not read private key file " << private_key_file
<< std::endl;
return -1;
std::println(stderr, "Could not read private key file {}",
private_key_file);
return std::unexpected{Error::IO};
}
auto pkey_d = defer([pkey] { EVP_PKEY_free(pkey); });
if (ptls_openssl_init_sign_certificate(&sign_cert_, pkey) != 0) {
std::cerr << "ptls_openssl_init_sign_certificate failed" << std::endl;
return -1;
std::println(stderr, "ptls_openssl_init_sign_certificate failed");
return std::unexpected{Error::CRYPTO};
}
ctx_.sign_certificate = &sign_cert_.super;
return 0;
return {};
}
void TLSServerContext::enable_keylog() { ctx_.log_event = &log_event; }
+3 -3
View File
@@ -41,15 +41,15 @@ public:
TLSServerContext();
~TLSServerContext();
int init(const char *private_key_file, const char *cert_file,
AppProtocol app_proto);
std::expected<void, Error> init(const char *private_key_file,
const char *cert_file, AppProtocol app_proto);
ptls_context_t *get_native_handle();
void enable_keylog();
private:
int load_private_key(const char *private_key_file);
std::expected<void, Error> load_private_key(const char *private_key_file);
ptls_context_t ctx_;
ptls_openssl_sign_certificate_t sign_cert_{};
+30 -29
View File
@@ -75,8 +75,7 @@ int alpn_select_proto_h3_cb(SSL *ssl, const unsigned char **out,
break;
default:
if (!config.quiet) {
std::cerr << "Unexpected quic protocol version: " << std::hex << "0x"
<< version << std::dec << std::endl;
std::println(stderr, "Unexpected quic protocol version: {:#x}", version);
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
@@ -91,7 +90,8 @@ int alpn_select_proto_h3_cb(SSL *ssl, const unsigned char **out,
}
if (!config.quiet) {
std::cerr << "Client did not present ALPN " << &H3_ALPN_V1[1] << std::endl;
std::println(stderr, "Client did not present ALPN {}",
as_string_view(H3_ALPN_V1.subspan(1)));
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
@@ -114,8 +114,7 @@ int alpn_select_proto_hq_cb(SSL *ssl, const unsigned char **out,
break;
default:
if (!config.quiet) {
std::cerr << "Unexpected quic protocol version: " << std::hex << "0x"
<< version << std::dec << std::endl;
std::println(stderr, "Unexpected quic protocol version: {:#x}", version);
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
@@ -130,7 +129,8 @@ int alpn_select_proto_hq_cb(SSL *ssl, const unsigned char **out,
}
if (!config.quiet) {
std::cerr << "Client did not present ALPN " << &HQ_ALPN_V1[1] << std::endl;
std::println(stderr, "Client did not present ALPN {}",
as_string_view(HQ_ALPN_V1.subspan(1)));
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
@@ -214,21 +214,22 @@ SSL_TICKET_RETURN decrypt_ticket_cb(SSL *ssl, SSL_SESSION *session,
} // namespace
#endif // !defined(LIBRESSL_VERSION_NUMBER)
int TLSServerContext::init(const char *private_key_file, const char *cert_file,
AppProtocol app_proto) {
std::expected<void, Error> TLSServerContext::init(const char *private_key_file,
const char *cert_file,
AppProtocol app_proto) {
constexpr static unsigned char sid_ctx[] = "ngtcp2 server";
ssl_ctx_ = SSL_CTX_new(TLS_server_method());
if (!ssl_ctx_) {
std::cerr << "SSL_CTX_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "SSL_CTX_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (ngtcp2_crypto_quictls_configure_server_context(ssl_ctx_) != 0) {
std::cerr << "ngtcp2_crypto_quictls_configure_server_context failed"
<< std::endl;
return -1;
std::println(stderr,
"ngtcp2_crypto_quictls_configure_server_context failed");
return std::unexpected{Error::CRYPTO};
}
SSL_CTX_set_max_early_data(ssl_ctx_, UINT32_MAX);
@@ -244,14 +245,14 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
SSL_CTX_set_options(ssl_ctx_, ssl_opts);
if (SSL_CTX_set_ciphersuites(ssl_ctx_, config.ciphers) != 1) {
std::cerr << "SSL_CTX_set_ciphersuites: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_set_ciphersuites: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_set1_groups_list(ssl_ctx_, config.groups) != 1) {
std::cerr << "SSL_CTX_set1_groups_list failed" << std::endl;
return -1;
std::println(stderr, "SSL_CTX_set1_groups_list failed");
return std::unexpected{Error::CRYPTO};
}
SSL_CTX_set_mode(ssl_ctx_, SSL_MODE_RELEASE_BUFFERS);
@@ -269,21 +270,21 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
if (SSL_CTX_use_PrivateKey_file(ssl_ctx_, private_key_file,
SSL_FILETYPE_PEM) != 1) {
std::cerr << "SSL_CTX_use_PrivateKey_file: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_use_PrivateKey_file: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_use_certificate_chain_file(ssl_ctx_, cert_file) != 1) {
std::cerr << "SSL_CTX_use_certificate_chain_file: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_use_certificate_chain_file: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (SSL_CTX_check_private_key(ssl_ctx_) != 1) {
std::cerr << "SSL_CTX_check_private_key: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "SSL_CTX_check_private_key: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
SSL_CTX_set_session_id_context(ssl_ctx_, sid_ctx, sizeof(sid_ctx) - 1);
@@ -300,7 +301,7 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
nullptr);
#endif // !defined(LIBRESSL_VERSION_NUMBER)
return 0;
return {};
}
extern std::ofstream keylog_file;
+2 -2
View File
@@ -40,8 +40,8 @@ public:
TLSServerContext() = default;
~TLSServerContext();
int init(const char *private_key_file, const char *cert_file,
AppProtocol app_proto);
std::expected<void, Error> init(const char *private_key_file,
const char *cert_file, AppProtocol app_proto);
SSL_CTX *get_native_handle() const;
+31 -34
View File
@@ -62,8 +62,7 @@ int alpn_select_proto_h3_cb(WOLFSSL *ssl, const unsigned char **out,
break;
default:
if (!config.quiet) {
std::cerr << "Unexpected quic protocol version: " << std::hex << "0x"
<< version << std::dec << std::endl;
std::println(stderr, "Unexpected quic protocol version: {:#x}", version);
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
@@ -78,7 +77,8 @@ int alpn_select_proto_h3_cb(WOLFSSL *ssl, const unsigned char **out,
}
if (!config.quiet) {
std::cerr << "Client did not present ALPN " << &H3_ALPN_V1[1] << std::endl;
std::println(stderr, "Client did not present ALPN {}",
as_string_view(H3_ALPN_V1.subspan(1)));
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
@@ -102,8 +102,7 @@ int alpn_select_proto_hq_cb(WOLFSSL *ssl, const unsigned char **out,
break;
default:
if (!config.quiet) {
std::cerr << "Unexpected quic protocol version: " << std::hex << "0x"
<< version << std::dec << std::endl;
std::println(stderr, "Unexpected quic protocol version: {:#x}", version);
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
@@ -118,7 +117,8 @@ int alpn_select_proto_hq_cb(WOLFSSL *ssl, const unsigned char **out,
}
if (!config.quiet) {
std::cerr << "Client did not present ALPN " << &HQ_ALPN_V1[1] << std::endl;
std::println(stderr, "Client did not present ALPN {}",
as_string_view(HQ_ALPN_V1.subspan(1)));
}
return SSL_TLSEXT_ERR_ALERT_FATAL;
@@ -133,8 +133,9 @@ int verify_cb(int preverify_ok, X509_STORE_CTX *ctx) {
}
} // namespace
int TLSServerContext::init(const char *private_key_file, const char *cert_file,
AppProtocol app_proto) {
std::expected<void, Error> TLSServerContext::init(const char *private_key_file,
const char *cert_file,
AppProtocol app_proto) {
constexpr static unsigned char sid_ctx[] = "ngtcp2 server";
#ifdef DEBUG_WOLFSSL
@@ -145,16 +146,15 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
ssl_ctx_ = wolfSSL_CTX_new(wolfTLSv1_3_server_method());
if (!ssl_ctx_) {
std::cerr << "wolfSSL_CTX_new: "
<< wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "wolfSSL_CTX_new: {}",
wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (ngtcp2_crypto_wolfssl_configure_server_context(ssl_ctx_) != 0) {
std::cerr << "ngtcp2_crypto_wolfssl_configure_server_context failed"
<< std::endl;
return -1;
std::println(stderr,
"ngtcp2_crypto_wolfssl_configure_server_context failed");
return std::unexpected{Error::CRYPTO};
}
#ifdef WOLFSSL_EARLY_DATA
@@ -168,16 +168,16 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
wolfSSL_CTX_set_options(ssl_ctx_, ssl_opts);
if (wolfSSL_CTX_set_cipher_list(ssl_ctx_, config.ciphers) != 1) {
std::cerr << "wolfSSL_CTX_set_cipher_list: "
<< ERR_error_string(ERR_get_error(), nullptr) << std::endl;
return -1;
std::println(stderr, "wolfSSL_CTX_set_cipher_list: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (wolfSSL_CTX_set1_groups_list(ssl_ctx_,
const_cast<char *>(config.groups)) != 1) {
std::cerr << "wolfSSL_CTX_set1_groups_list(" << config.groups << ") failed"
<< std::endl;
return -1;
std::println(stderr, "wolfSSL_CTX_set1_groups_list({}) failed",
config.groups);
return std::unexpected{Error::CRYPTO};
}
wolfSSL_CTX_set_mode(ssl_ctx_, SSL_MODE_RELEASE_BUFFERS);
@@ -195,24 +195,21 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
if (wolfSSL_CTX_use_PrivateKey_file(ssl_ctx_, private_key_file,
SSL_FILETYPE_PEM) != 1) {
std::cerr << "wolfSSL_CTX_use_PrivateKey_file: "
<< wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "wolfSSL_CTX_use_PrivateKey_file: {}",
wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (wolfSSL_CTX_use_certificate_chain_file(ssl_ctx_, cert_file) != 1) {
std::cerr << "wolfSSL_CTX_use_certificate_chain_file: "
<< wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "wolfSSL_CTX_use_certificate_chain_file: {}",
wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
if (wolfSSL_CTX_check_private_key(ssl_ctx_) != 1) {
std::cerr << "wolfSSL_CTX_check_private_key: "
<< wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "wolfSSL_CTX_check_private_key: {}",
wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
wolfSSL_CTX_set_session_id_context(ssl_ctx_, sid_ctx, sizeof(sid_ctx) - 1);
@@ -224,7 +221,7 @@ int TLSServerContext::init(const char *private_key_file, const char *cert_file,
verify_cb);
}
return 0;
return {};
}
extern std::ofstream keylog_file;
+2 -2
View File
@@ -41,8 +41,8 @@ public:
TLSServerContext() = default;
~TLSServerContext();
int init(const char *private_key_file, const char *cert_file,
AppProtocol app_proto);
std::expected<void, Error> init(const char *private_key_file,
const char *cert_file, AppProtocol app_proto);
WOLFSSL_CTX *get_native_handle() const;
+11 -12
View File
@@ -34,15 +34,15 @@
extern Config config;
int TLSServerSession::init(const TLSServerContext &tls_ctx,
HandlerBase *handler) {
std::expected<void, Error>
TLSServerSession::init(const TLSServerContext &tls_ctx, HandlerBase *handler) {
auto ssl_ctx = tls_ctx.get_native_handle();
ssl_ = SSL_new(ssl_ctx);
if (!ssl_) {
std::cerr << "SSL_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "SSL_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
SSL_set_app_data(ssl_, handler->conn_ref());
@@ -63,18 +63,17 @@ int TLSServerSession::init(const TLSServerContext &tls_ctx,
auto quic_early_data_ctxlen = ngtcp2_transport_params_encode(
quic_early_data_ctx.data(), quic_early_data_ctx.size(), &params);
if (quic_early_data_ctxlen < 0) {
std::cerr << "ngtcp2_transport_params_encode: "
<< ngtcp2_strerror(static_cast<int>(quic_early_data_ctxlen))
<< std::endl;
return -1;
std::println(stderr, "ngtcp2_transport_params_encode: {}",
ngtcp2_strerror(static_cast<int>(quic_early_data_ctxlen)));
return std::unexpected{Error::CRYPTO};
}
if (SSL_set_quic_early_data_context(ssl_, quic_early_data_ctx.data(),
as_unsigned(quic_early_data_ctxlen)) !=
1) {
std::cerr << "SSL_set_quic_early_data_context failed" << std::endl;
return -1;
std::println(stderr, "SSL_set_quic_early_data_context failed");
return std::unexpected{Error::CRYPTO};
}
return 0;
return {};
}
+6 -2
View File
@@ -30,6 +30,9 @@
#endif // defined(HAVE_CONFIG_H)
#include "tls_session_base_quictls.h"
#include "shared.h"
using namespace ngtcp2;
class TLSServerContext;
class HandlerBase;
@@ -38,9 +41,10 @@ class TLSServerSession : public TLSSessionBase {
public:
TLSServerSession() = default;
int init(const TLSServerContext &tls_ctx, HandlerBase *handler);
std::expected<void, Error> init(const TLSServerContext &tls_ctx,
HandlerBase *handler);
// ticket is sent automatically.
int send_session_ticket() { return 0; }
std::expected<void, Error> send_session_ticket() { return {}; }
};
#endif // !defined(TLS_SERVER_SESSION_BORINGSSL_H)
+8 -9
View File
@@ -31,28 +31,27 @@
#include "tls_server_context_ossl.h"
#include "server_base.h"
int TLSServerSession::init(const TLSServerContext &tls_ctx,
HandlerBase *handler) {
std::expected<void, Error>
TLSServerSession::init(const TLSServerContext &tls_ctx, HandlerBase *handler) {
auto ssl_ctx = tls_ctx.get_native_handle();
auto ssl = SSL_new(ssl_ctx);
if (!ssl) {
std::cerr << "SSL_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "SSL_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
ngtcp2_crypto_ossl_ctx_set_ssl(ossl_ctx_, ssl);
if (ngtcp2_crypto_ossl_configure_server_session(ssl) != 0) {
std::cerr << "ngtcp2_crypto_ossl_configure_server_session failed"
<< std::endl;
return -1;
std::println(stderr, "ngtcp2_crypto_ossl_configure_server_session failed");
return std::unexpected{Error::CRYPTO};
}
SSL_set_app_data(ssl, handler->conn_ref());
SSL_set_accept_state(ssl);
SSL_set_quic_tls_early_data_enabled(ssl, 1);
return 0;
return {};
}
+6 -2
View File
@@ -30,6 +30,9 @@
#endif // defined(HAVE_CONFIG_H)
#include "tls_session_base_ossl.h"
#include "shared.h"
using namespace ngtcp2;
class TLSServerContext;
class HandlerBase;
@@ -38,9 +41,10 @@ class TLSServerSession : public TLSSessionBase {
public:
TLSServerSession() = default;
int init(const TLSServerContext &tls_ctx, HandlerBase *handler);
std::expected<void, Error> init(const TLSServerContext &tls_ctx,
HandlerBase *handler);
// ticket is sent automatically.
int send_session_ticket() { return 0; }
std::expected<void, Error> send_session_ticket() { return {}; }
};
#endif // !defined(TLS_SERVER_SESSION_OSSL_H)
+8 -7
View File
@@ -37,11 +37,12 @@ using namespace ngtcp2;
extern Config config;
int TLSServerSession::init(TLSServerContext &tls_ctx, HandlerBase *handler) {
std::expected<void, Error> TLSServerSession::init(TLSServerContext &tls_ctx,
HandlerBase *handler) {
cptls_.ptls = ptls_server_new(tls_ctx.get_native_handle());
if (!cptls_.ptls) {
std::cerr << "ptls_server_new failed" << std::endl;
return -1;
std::println(stderr, "ptls_server_new failed");
return std::unexpected{Error::CRYPTO};
}
*ptls_get_data_ptr(cptls_.ptls) = handler->conn_ref();
@@ -57,10 +58,10 @@ int TLSServerSession::init(TLSServerContext &tls_ctx, HandlerBase *handler) {
};
if (ngtcp2_crypto_picotls_configure_server_session(&cptls_) != 0) {
std::cerr << "ngtcp2_crypto_picotls_configure_server_session failed"
<< std::endl;
return -1;
std::println(stderr,
"ngtcp2_crypto_picotls_configure_server_session failed");
return std::unexpected{Error::CRYPTO};
}
return 0;
return {};
}
+6 -2
View File
@@ -30,6 +30,9 @@
#endif // defined(HAVE_CONFIG_H)
#include "tls_session_base_picotls.h"
#include "shared.h"
using namespace ngtcp2;
class TLSServerContext;
class HandlerBase;
@@ -38,9 +41,10 @@ class TLSServerSession : public TLSSessionBase {
public:
TLSServerSession() = default;
int init(TLSServerContext &tls_ctx, HandlerBase *handler);
std::expected<void, Error> init(TLSServerContext &tls_ctx,
HandlerBase *handler);
// ticket is sent automatically.
int send_session_ticket() { return 0; }
std::expected<void, Error> send_session_ticket() { return {}; }
};
#endif // !defined(TLS_SERVER_SESSION_PICOTLS_H)
+6 -6
View File
@@ -31,15 +31,15 @@
#include "tls_server_context_quictls.h"
#include "server_base.h"
int TLSServerSession::init(const TLSServerContext &tls_ctx,
HandlerBase *handler) {
std::expected<void, Error>
TLSServerSession::init(const TLSServerContext &tls_ctx, HandlerBase *handler) {
auto ssl_ctx = tls_ctx.get_native_handle();
ssl_ = SSL_new(ssl_ctx);
if (!ssl_) {
std::cerr << "SSL_new: " << ERR_error_string(ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "SSL_new: {}",
ERR_error_string(ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
SSL_set_app_data(ssl_, handler->conn_ref());
@@ -48,5 +48,5 @@ int TLSServerSession::init(const TLSServerContext &tls_ctx,
SSL_set_quic_early_data_enabled(ssl_, 1);
#endif // !defined(LIBRESSL_VERSION_NUMBER)
return 0;
return {};
}
+6 -2
View File
@@ -30,6 +30,9 @@
#endif // defined(HAVE_CONFIG_H)
#include "tls_session_base_quictls.h"
#include "shared.h"
using namespace ngtcp2;
class TLSServerContext;
class HandlerBase;
@@ -38,9 +41,10 @@ class TLSServerSession : public TLSSessionBase {
public:
TLSServerSession() = default;
int init(const TLSServerContext &tls_ctx, HandlerBase *handler);
std::expected<void, Error> init(const TLSServerContext &tls_ctx,
HandlerBase *handler);
// ticket is sent automatically.
int send_session_ticket() { return 0; }
std::expected<void, Error> send_session_ticket() { return {}; }
};
#endif // !defined(TLS_SERVER_SESSION_QUICTLS_H)
+6 -7
View File
@@ -29,16 +29,15 @@
#include "tls_server_context_wolfssl.h"
#include "server_base.h"
int TLSServerSession::init(const TLSServerContext &tls_ctx,
HandlerBase *handler) {
std::expected<void, Error>
TLSServerSession::init(const TLSServerContext &tls_ctx, HandlerBase *handler) {
auto ssl_ctx = tls_ctx.get_native_handle();
ssl_ = wolfSSL_new(ssl_ctx);
if (!ssl_) {
std::cerr << "wolfSSL_new: "
<< wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr)
<< std::endl;
return -1;
std::println(stderr, "wolfSSL_new: {}",
wolfSSL_ERR_error_string(wolfSSL_ERR_get_error(), nullptr));
return std::unexpected{Error::CRYPTO};
}
wolfSSL_set_app_data(ssl_, handler->conn_ref());
@@ -49,5 +48,5 @@ int TLSServerSession::init(const TLSServerContext &tls_ctx,
// Just use QUIC v1
wolfSSL_set_quic_transport_version(ssl_, 0x39);
return 0;
return {};
}
+6 -2
View File
@@ -30,6 +30,9 @@
#endif // defined(HAVE_CONFIG_H)
#include "tls_session_base_wolfssl.h"
#include "shared.h"
using namespace ngtcp2;
class TLSServerContext;
class HandlerBase;
@@ -38,9 +41,10 @@ class TLSServerSession : public TLSSessionBase {
public:
TLSServerSession() = default;
int init(const TLSServerContext &tls_ctx, HandlerBase *handler);
std::expected<void, Error> init(const TLSServerContext &tls_ctx,
HandlerBase *handler);
// ticket is sent automatically.
int send_session_ticket() { return 0; }
std::expected<void, Error> send_session_ticket() { return {}; }
};
#endif // !defined(TLS_SERVER_SESSION_WOLFSSL_H)
+11
View File
@@ -42,6 +42,17 @@ std::string TLSSessionBase::get_cipher_name() const {
return wolfSSL_get_cipher_name(ssl_);
}
std::string_view TLSSessionBase::get_negotiated_group() const {
using namespace std::literals;
auto name = wolfSSL_get_curve_name(ssl_);
if (!name) {
return ""sv;
}
return name;
}
std::string TLSSessionBase::get_selected_alpn() const {
char *alpn = nullptr;
unsigned short alpnlen;
+1 -5
View File
@@ -44,11 +44,7 @@ public:
WOLFSSL *get_native_handle() const;
std::string get_cipher_name() const;
std::string_view get_negotiated_group() const {
using namespace std::literals;
return ""sv;
}
std::string_view get_negotiated_group() const;
std::string get_selected_alpn() const;
// Keylog is enabled per SSL_CTX.
void enable_keylog() {}
+109 -92
View File
@@ -57,17 +57,19 @@ namespace ngtcp2 {
namespace util {
std::optional<HPKEPrivateKey>
read_hpke_private_key_pem(const std::string_view &filename);
std::expected<HPKEPrivateKey, Error>
read_hpke_private_key_pem(std::string_view filename);
std::optional<std::vector<uint8_t>> read_pem(const std::string_view &filename,
const std::string_view &name,
const std::string_view &type);
std::expected<std::vector<uint8_t>, Error> read_pem(std::string_view filename,
std::string_view name,
std::string_view type);
int write_pem(const std::string_view &filename, const std::string_view &name,
const std::string_view &type, std::span<const uint8_t> data);
std::expected<void, Error> write_pem(std::string_view filename,
std::string_view name,
std::string_view type,
std::span<const uint8_t> data);
std::string decode_hex(const std::string_view &s) {
std::string decode_hex(std::string_view s) {
assert(s.size() % 2 == 0);
std::string res(s.size() / 2, '0');
auto p = std::ranges::begin(res);
@@ -182,7 +184,7 @@ uint8_t *hexdump_ascii(uint8_t *dest, std::span<const uint8_t> data) {
*dest++ = '|';
for (auto c : data) {
if (0x20 <= c && c <= 0x7e) {
if (0x20 <= c && c <= 0x7E) {
*dest++ = c;
} else {
*dest++ = '.';
@@ -244,23 +246,24 @@ uint8_t *hexdump_line(uint8_t *dest, std::span<const uint8_t> data,
} // namespace
namespace {
int hexdump_write(int fd, std::span<const uint8_t> data) {
std::expected<void, Error> hexdump_write(int fd,
std::span<const uint8_t> data) {
ssize_t nwrite;
for (;
(nwrite = write(fd, data.data(), data.size())) == -1 && errno == EINTR;)
;
if (nwrite == -1) {
return -1;
return std::unexpected{Error::IO};
}
return 0;
return {};
}
} // namespace
int hexdump(FILE *out, const void *data, size_t datalen) {
if (datalen == 0) {
return 0;
std::expected<void, Error> hexdump(FILE *out, std::span<const uint8_t> data) {
if (data.empty()) {
return {};
}
// min_space is the additional minimum space that the buffer must
@@ -271,7 +274,7 @@ int hexdump(FILE *out, const void *data, size_t datalen) {
auto fd = fileno(out);
std::array<uint8_t, 4096> buf;
auto input = std::span{reinterpret_cast<const uint8_t *>(data), datalen};
auto input = data;
auto last = buf.data();
auto repeated = false;
std::span<const uint8_t> s, last_s{};
@@ -298,22 +301,21 @@ int hexdump(FILE *out, const void *data, size_t datalen) {
repeated = false;
}
last = hexdump_line(
last, s, as_unsigned(s.data() - reinterpret_cast<const uint8_t *>(data)));
last = hexdump_line(last, s, as_unsigned(s.data() - data.data()));
*last++ = '\n';
last_s = s;
auto len = static_cast<size_t>(last - buf.data());
if (len + min_space > buf.size()) {
if (hexdump_write(fd, {buf.data(), len}) != 0) {
return -1;
if (auto rv = hexdump_write(fd, {buf.data(), len}); !rv) {
return rv;
}
last = buf.data();
}
}
last = hexdump_addr(last, datalen);
last = hexdump_addr(last, data.size());
*last++ = '\n';
auto len = static_cast<size_t>(last - buf.data());
@@ -321,7 +323,7 @@ int hexdump(FILE *out, const void *data, size_t datalen) {
return hexdump_write(fd, {buf.data(), len});
}
return 0;
return {};
}
ngtcp2_cid make_cid_key(std::span<const uint8_t> cid) {
@@ -342,7 +344,7 @@ std::string straddr(const sockaddr *sa, socklen_t salen) {
auto rv = getnameinfo(sa, salen, host.data(), host.size(), port.data(),
port.size(), NI_NUMERICHOST | NI_NUMERICSERV);
if (rv != 0) {
std::cerr << "getnameinfo: " << gai_strerror(rv) << std::endl;
std::println(stderr, "getnameinfo: {}", gai_strerror(rv));
return "";
}
std::string res = "[";
@@ -387,11 +389,11 @@ namespace {
constexpr bool rws(char c) { return c == '\t' || c == ' '; }
} // namespace
std::optional<std::unordered_map<std::string, std::string>>
read_mime_types(const std::string_view &filename) {
std::expected<std::unordered_map<std::string, std::string>, Error>
read_mime_types(std::string_view filename) {
std::ifstream f(filename.data());
if (!f) {
return {};
return std::unexpected{Error::IO};
}
std::unordered_map<std::string, std::string> dest;
@@ -442,12 +444,12 @@ std::string format_duration(ngtcp2_duration n) {
}
namespace {
std::optional<std::pair<uint64_t, size_t>>
parse_uint_internal(const std::string_view &s) {
std::expected<std::pair<uint64_t, size_t>, Error>
parse_uint_internal(std::string_view s) {
uint64_t res = 0;
if (s.empty()) {
return {};
return std::unexpected{Error::INVALID_ARGUMENT};
}
for (size_t i = 0; i < s.size(); ++i) {
@@ -458,7 +460,7 @@ parse_uint_internal(const std::string_view &s) {
auto d = static_cast<uint64_t>(c - '0');
if (res > (std::numeric_limits<uint64_t>::max() - d) / 10) {
return {};
return std::unexpected{Error::INTEGER_OVERFLOW};
}
res *= 10;
@@ -469,29 +471,29 @@ parse_uint_internal(const std::string_view &s) {
}
} // namespace
std::optional<uint64_t> parse_uint(const std::string_view &s) {
std::expected<uint64_t, Error> parse_uint(std::string_view s) {
auto o = parse_uint_internal(s);
if (!o) {
return {};
return std::unexpected{o.error()};
}
auto [res, idx] = *o;
if (idx != s.size()) {
return {};
return std::unexpected{Error::INVALID_ARGUMENT};
}
return res;
}
std::optional<uint64_t> parse_uint_iec(const std::string_view &s) {
std::expected<uint64_t, Error> parse_uint_iec(std::string_view s) {
auto o = parse_uint_internal(s);
if (!o) {
return {};
return std::unexpected{o.error()};
}
auto [res, idx] = *o;
if (idx == s.size()) {
return res;
}
if (idx + 1 != s.size()) {
return {};
return std::unexpected{Error::INVALID_ARGUMENT};
}
uint64_t m;
@@ -509,20 +511,20 @@ std::optional<uint64_t> parse_uint_iec(const std::string_view &s) {
m = 1 << 10;
break;
default:
return {};
return std::unexpected{Error::INVALID_ARGUMENT};
}
if (res > std::numeric_limits<uint64_t>::max() / m) {
return {};
return std::unexpected{Error::INTEGER_OVERFLOW};
}
return res * m;
}
std::optional<uint64_t> parse_duration(const std::string_view &s) {
std::expected<uint64_t, Error> parse_duration(std::string_view s) {
auto o = parse_uint_internal(s);
if (!o) {
return {};
return std::unexpected{o.error()};
}
auto [res, idx] = *o;
if (idx == s.size()) {
@@ -545,7 +547,7 @@ std::optional<uint64_t> parse_duration(const std::string_view &s) {
m = NGTCP2_SECONDS;
break;
default:
return {};
return std::unexpected{Error::INVALID_ARGUMENT};
}
} else if (idx + 2 == s.size() && (s[idx + 1] == 's' || s[idx + 1] == 'S')) {
switch (s[idx]) {
@@ -561,14 +563,14 @@ std::optional<uint64_t> parse_duration(const std::string_view &s) {
case 'n':
return res;
default:
return {};
return std::unexpected{Error::INVALID_ARGUMENT};
}
} else {
return {};
return std::unexpected{Error::INVALID_ARGUMENT};
}
if (res > std::numeric_limits<uint64_t>::max() / m) {
return {};
return std::unexpected{Error::INTEGER_OVERFLOW};
}
return res * m;
@@ -611,12 +613,17 @@ template <typename InputIt> InputIt eat_dir(InputIt first, InputIt last) {
}
} // namespace
std::string normalize_path(const std::string_view &path) {
assert(path.size() <= 1024);
std::expected<std::string, Error> normalize_path(std::string_view path) {
constexpr size_t max_path = 1024;
if (path.size() > max_path) {
return std::unexpected{Error::INVALID_ARGUMENT};
}
assert(path.size() > 0);
assert(path[0] == '/');
std::array<char, 1024> res;
std::array<char, max_path> res;
auto p = res.data();
auto first = std::ranges::begin(path);
@@ -664,32 +671,37 @@ std::string normalize_path(const std::string_view &path) {
return std::string{res.data(), p};
}
int make_socket_nonblocking(int fd) {
std::expected<void, Error> make_socket_nonblocking(int fd) {
int rv;
int flags;
while ((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR)
;
if (flags == -1) {
return -1;
return std::unexpected{Error::SYSCALL};
}
while ((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR)
;
return rv;
if (rv == -1) {
return std::unexpected{Error::SYSCALL};
}
return {};
}
int create_nonblock_socket(int domain, int type, int protocol) {
std::expected<int, Error> create_nonblock_socket(int domain, int type,
int protocol) {
#ifdef SOCK_NONBLOCK
auto fd = socket(domain, type | SOCK_NONBLOCK, protocol);
if (fd == -1) {
return -1;
return std::unexpected{Error::SYSCALL};
}
#else // !defined(SOCK_NONBLOCK)
auto fd = socket(domain, type, protocol);
if (fd == -1) {
return -1;
return std::unexpected{Error::SYSCALL};
}
make_socket_nonblocking(fd);
@@ -698,7 +710,7 @@ int create_nonblock_socket(int domain, int type, int protocol) {
return fd;
}
std::vector<std::string_view> split_str(const std::string_view &s, char delim) {
std::vector<std::string_view> split_str(std::string_view s, char delim) {
size_t len = 1;
auto last = std::ranges::end(s);
std::string_view::const_iterator d;
@@ -722,85 +734,91 @@ std::vector<std::string_view> split_str(const std::string_view &s, char delim) {
return list;
}
std::optional<uint32_t> parse_version(const std::string_view &s) {
std::expected<uint32_t, Error> parse_version(std::string_view s) {
if (!util::istarts_with(s, "0x"sv)) {
return {};
return std::unexpected{Error::INVALID_ARGUMENT};
}
auto k = s.substr(2);
auto k_last = k.data() + k.size();
uint32_t v;
auto rv = std::from_chars(k.data(), k_last, v, 16);
if (rv.ptr != k_last || rv.ec != std::errc{}) {
return {};
return std::unexpected{Error::INVALID_ARGUMENT};
}
return v;
}
std::optional<std::vector<uint8_t>>
read_token(const std::string_view &filename) {
std::expected<std::vector<uint8_t>, Error>
read_token(std::string_view filename) {
return read_pem(filename, "token"sv, "QUIC TOKEN"sv);
}
int write_token(const std::string_view &filename,
std::span<const uint8_t> token) {
std::expected<void, Error> write_token(std::string_view filename,
std::span<const uint8_t> token) {
return write_pem(filename, "token"sv, "QUIC TOKEN"sv, token);
}
std::optional<std::vector<uint8_t>>
read_transport_params(const std::string_view &filename) {
std::expected<std::vector<uint8_t>, Error>
read_transport_params(std::string_view filename) {
return read_pem(filename, "transport parameters"sv,
"QUIC TRANSPORT PARAMETERS"sv);
}
int write_transport_params(const std::string_view &filename,
std::span<const uint8_t> data) {
std::expected<void, Error>
write_transport_params(std::string_view filename,
std::span<const uint8_t> data) {
return write_pem(filename, "transport parameters"sv,
"QUIC TRANSPORT PARAMETERS"sv, data);
}
std::string percent_decode(const std::string_view &s) {
std::string percent_decode(std::string_view s) {
std::string result;
result.resize(s.size());
auto p = std::ranges::begin(result);
for (auto first = std::ranges::begin(s), last = std::ranges::end(s);
first != last; ++first) {
if (*first != '%') {
result.resize_and_overwrite(s.size(), [s](auto p, auto len) {
auto head = p;
for (auto first = std::ranges::begin(s), last = std::ranges::end(s);
first != last; ++first) {
if (*first != '%') {
*p++ = *first;
continue;
}
if (first + 1 != last && first + 2 != last &&
is_hex_digit(*(first + 1)) && is_hex_digit(*(first + 2))) {
*p++ = static_cast<char>((hex_to_uint(*(first + 1)) << 4) +
hex_to_uint(*(first + 2)));
first += 2;
continue;
}
*p++ = *first;
continue;
}
if (first + 1 != last && first + 2 != last && is_hex_digit(*(first + 1)) &&
is_hex_digit(*(first + 2))) {
*p++ = static_cast<char>((hex_to_uint(*(first + 1)) << 4) +
hex_to_uint(*(first + 2)));
first += 2;
continue;
}
return p - head;
});
*p++ = *first;
}
result.resize(as_unsigned(p - std::ranges::begin(result)));
return result;
}
std::optional<std::vector<uint8_t>> read_file(const std::string_view &path) {
std::expected<std::vector<uint8_t>, Error> read_file(std::string_view path) {
auto fd = open(path.data(), O_RDONLY);
if (fd == -1) {
return {};
return std::unexpected{Error::IO};
}
auto fd_d = defer([fd] { close(fd); });
auto size = lseek(fd, 0, SEEK_END);
if (size == static_cast<off_t>(-1)) {
return {};
return std::unexpected{Error::IO};
}
auto addr =
mmap(nullptr, static_cast<size_t>(size), PROT_READ, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
return {};
return std::unexpected{Error::IO};
}
auto addr_d =
@@ -825,16 +843,16 @@ bool recv_pkt_time_threshold_exceeded(bool time_sensitive, ngtcp2_tstamp start,
util::timestamp() - start >= NGTCP2_MILLISECONDS;
}
std::optional<ECHServerConfig>
read_ech_server_config(const std::string_view &path) {
std::expected<ECHServerConfig, Error>
read_ech_server_config(std::string_view path) {
auto pkey = read_hpke_private_key_pem(path);
if (!pkey) {
return {};
return std::unexpected{pkey.error()};
}
auto ech_config = read_pem(path, "ECH config"sv, "ECHCONFIG"sv);
if (!ech_config) {
return {};
return std::unexpected{ech_config.error()};
}
return ECHServerConfig{
@@ -847,8 +865,7 @@ std::span<uint64_t, 2> generate_siphash_key() {
static auto key = [] {
std::array<uint64_t, 2> key;
auto rv = generate_secure_random(as_writable_uint8_span(std::span{key}));
if (rv != 0) {
if (!generate_secure_random(as_writable_uint8_span(std::span{key}))) {
assert(0);
abort();
}
+80 -58
View File
@@ -33,12 +33,12 @@
#include <sys/socket.h>
#include <cassert>
#include <optional>
#include <string>
#include <random>
#include <unordered_map>
#include <string_view>
#include <span>
#include <expected>
#include <ngtcp2/ngtcp2.h>
#include <nghttp3/nghttp3.h>
@@ -48,13 +48,14 @@
#include "network.h"
#include "siphash.h"
#include "template.h"
#include "shared.h"
namespace ngtcp2 {
namespace util {
inline nghttp3_nv make_nv(const std::string_view &name,
const std::string_view &value, uint8_t flags) {
inline nghttp3_nv make_nv(std::string_view name, std::string_view value,
uint8_t flags) {
return nghttp3_nv{
reinterpret_cast<uint8_t *>(const_cast<char *>(std::ranges::data(name))),
reinterpret_cast<uint8_t *>(const_cast<char *>(std::ranges::data(value))),
@@ -64,18 +65,15 @@ inline nghttp3_nv make_nv(const std::string_view &name,
};
}
inline nghttp3_nv make_nv_cc(const std::string_view &name,
const std::string_view &value) {
inline nghttp3_nv make_nv_cc(std::string_view name, std::string_view value) {
return make_nv(name, value, NGHTTP3_NV_FLAG_NONE);
}
inline nghttp3_nv make_nv_nc(const std::string_view &name,
const std::string_view &value) {
inline nghttp3_nv make_nv_nc(std::string_view name, std::string_view value) {
return make_nv(name, value, NGHTTP3_NV_FLAG_NO_COPY_NAME);
}
inline nghttp3_nv make_nv_nn(const std::string_view &name,
const std::string_view &value) {
inline nghttp3_nv make_nv_nn(std::string_view name, std::string_view value) {
return make_nv(name, value,
NGHTTP3_NV_FLAG_NO_COPY_NAME | NGHTTP3_NV_FLAG_NO_COPY_VALUE);
}
@@ -90,7 +88,7 @@ constexpr O format_hex_uint8(uint8_t b, O result) {
# pragma GCC diagnostic ignored "-Wsign-conversion"
#endif // __GNUC__
*result++ = LOWER_XDIGITS[b >> 4];
*result++ = LOWER_XDIGITS[b & 0xf];
*result++ = LOWER_XDIGITS[b & 0xF];
#ifdef __GNUC__
# pragma GCC diagnostic pop
#endif // __GNUC__
@@ -135,9 +133,12 @@ constexpr std::string format_hex(I first, std::iter_difference_t<I> n) {
std::string res;
res.resize(as_unsigned(n * 2));
res.resize_and_overwrite(as_unsigned(n * 2), [first = std::move(first),
n](auto p, auto len) mutable {
format_hex(std::move(first), n, p);
format_hex(std::move(first), std::move(n), std::ranges::begin(res));
return len;
});
return res;
}
@@ -155,15 +156,18 @@ constexpr O format_hex(R &&r, O result) {
}
// format_hex converts |R| in hex format, and returns the result.
template <std::ranges::input_range R>
template <std::ranges::forward_range R>
requires(!std::is_array_v<std::remove_cvref_t<R>> &&
sizeof(std::ranges::range_value_t<R>) == sizeof(uint8_t))
constexpr std::string format_hex(R &&r) {
std::string res;
res.resize(as_unsigned(std::ranges::distance(r) * 2));
res.resize_and_overwrite(as_unsigned(std::ranges::distance(r) * 2),
[&r](auto p, auto len) {
format_hex(r, p);
format_hex(std::forward<R>(r), std::ranges::begin(res));
return len;
});
return res;
}
@@ -201,14 +205,16 @@ constexpr O format_hex(T n, O result) {
template <std::unsigned_integral T> constexpr std::string format_hex(T n) {
std::string res;
res.resize(sizeof(n) * 2);
res.resize_and_overwrite(sizeof(n) * 2, [n](auto p, auto len) {
format_hex(n, p);
format_hex(std::move(n), std::ranges::begin(res));
return len;
});
return res;
}
std::string decode_hex(const std::string_view &s);
std::string decode_hex(std::string_view s);
// format_durationf formats |ns| in human readable manner. |ns| must
// be nanoseconds resolution. This function uses the largest unit so
@@ -228,10 +234,14 @@ bool numeric_host(const char *hostname);
bool numeric_host(const char *hostname, int family);
// hexdump dumps |data| of length |datalen| in the format similar to
// hexdump(1) with -C option. This function returns 0 if it succeeds,
// or -1.
int hexdump(FILE *out, const void *data, size_t datalen);
// hexdump dumps |data| in the format similar to hexdump(1) with -C
// option.
std::expected<void, Error> hexdump(FILE *out, std::span<const uint8_t> data);
template <typename T, size_t N>
std::expected<void, Error> hexdump(FILE *out, std::span<T, N> data) {
return hexdump(out, as_uint8_span(data));
}
inline constexpr auto lowcase_tbl = [] {
std::array<char, 256> tbl;
@@ -259,8 +269,7 @@ struct CaseCmp {
// istarts_with returns true if |s| starts with |prefix|. Comparison
// is performed in case-insensitive manner.
constexpr bool istarts_with(const std::string_view &s,
const std::string_view &prefix) {
constexpr bool istarts_with(std::string_view s, std::string_view prefix) {
return s.size() >= prefix.size() &&
std::ranges::equal(s.substr(0, prefix.size()), prefix, CaseCmp());
}
@@ -285,8 +294,8 @@ std::string_view strccalgo(ngtcp2_cc_algo cc_algo);
// read_mime_types reads "MIME media types and the extensions" file
// denoted by |filename| and returns the mapping of extension to MIME
// media type.
std::optional<std::unordered_map<std::string, std::string>>
read_mime_types(const std::string_view &filename);
std::expected<std::unordered_map<std::string, std::string>, Error>
read_mime_types(std::string_view filename);
inline constexpr auto count_digit_tbl = [] {
std::array<uint64_t, std::numeric_limits<uint64_t>::digits10> tbl;
@@ -379,9 +388,11 @@ template <std::unsigned_integral T> constexpr std::string format_uint(T n) {
std::string res;
res.resize(count_digit(n));
res.resize_and_overwrite(count_digit(n), [n](auto p, auto len) {
utos(n, p);
utos(n, std::ranges::begin(res));
return len;
});
return res;
}
@@ -411,31 +422,27 @@ std::string format_duration(ngtcp2_duration n);
// parse_uint parses |s| as 64-bit unsigned integer. If it cannot
// parse |s|, the return value does not contain a value.
std::optional<uint64_t> parse_uint(const std::string_view &s);
std::expected<uint64_t, Error> parse_uint(std::string_view s);
// parse_uint_iec parses |s| as 64-bit unsigned integer. It accepts
// IEC unit letter (either "G", "M", or "K") in |s|. If it cannot
// parse |s|, the return value does not contain a value.
std::optional<uint64_t> parse_uint_iec(const std::string_view &s);
std::expected<uint64_t, Error> parse_uint_iec(std::string_view s);
// parse_duration parses |s| as 64-bit unsigned integer. It accepts a
// unit (either "h", "m", "s", "ms", "us", or "ns") in |s|. If no
// unit is present, the unit "s" is assumed. If it cannot parse |s|,
// the return value does not contain a value.
std::optional<uint64_t> parse_duration(const std::string_view &s);
std::expected<uint64_t, Error> parse_duration(std::string_view s);
// generate_secure_random generates a cryptographically secure pseudo
// random data of |data|.
int generate_secure_random(std::span<uint8_t> data);
// generate_secret generates secret and writes it to |secret|.
// Currently, |secret| must be 32 bytes long.
int generate_secret(std::span<uint8_t> secret);
std::expected<void, Error> generate_secure_random(std::span<uint8_t> data);
// normalize_path removes ".." by consuming a previous path component.
// It also removes ".". It assumes that |path| starts with "/". If
// it cannot consume a previous path component, it just removes "..".
std::string normalize_path(const std::string_view &path);
std::expected<std::string, Error> normalize_path(std::string_view path);
template <std::predicate<size_t> Pred>
consteval auto pred_tbl_gen256(Pred pred) {
@@ -469,7 +476,7 @@ constexpr bool is_hex_digit(char c) noexcept {
// is_hex_string returns true if the length of |s| is even, and |s|
// does not contain a character other than [0-9A-Fa-f]. It returns
// false otherwise.
template <std::ranges::input_range R>
template <std::ranges::sized_range R>
requires(!std::is_array_v<std::remove_cvref_t<R>>)
constexpr bool is_hex_string(R &&r) {
return !(std::ranges::size(r) & 1) && std::ranges::all_of(r, is_hex_digit);
@@ -501,21 +508,23 @@ constexpr uint32_t hex_to_uint(char c) noexcept {
return hex_to_uint_tbl[static_cast<uint8_t>(c)];
}
std::string percent_decode(const std::string_view &s);
std::string percent_decode(std::string_view s);
int make_socket_nonblocking(int fd);
std::expected<void, Error> make_socket_nonblocking(int fd);
int create_nonblock_socket(int domain, int type, int protocol);
std::expected<int, Error> create_nonblock_socket(int domain, int type,
int protocol);
std::optional<std::vector<uint8_t>>
read_token(const std::string_view &filename);
int write_token(const std::string_view &filename,
std::span<const uint8_t> token);
std::expected<std::vector<uint8_t>, Error>
read_token(std::string_view filename);
std::expected<void, Error> write_token(std::string_view filename,
std::span<const uint8_t> token);
std::optional<std::vector<uint8_t>>
read_transport_params(const std::string_view &filename);
int write_transport_params(const std::string_view &filename,
std::span<const uint8_t> data);
std::expected<std::vector<uint8_t>, Error>
read_transport_params(std::string_view filename);
std::expected<void, Error>
write_transport_params(std::string_view filename,
std::span<const uint8_t> data);
const char *crypto_default_ciphers();
@@ -524,15 +533,14 @@ const char *crypto_default_groups();
// split_str parses delimited strings in |s| and returns substrings
// delimited by |delim|. The any white spaces around substring are
// treated as a part of substring.
std::vector<std::string_view> split_str(const std::string_view &s,
char delim = ',');
std::vector<std::string_view> split_str(std::string_view s, char delim = ',');
// parse_version parses |s| to get 4 byte QUIC version. |s| must be a
// hex string and must start with "0x" (e.g., 0x00000001).
std::optional<uint32_t> parse_version(const std::string_view &s);
std::expected<uint32_t, Error> parse_version(std::string_view s);
// read_file reads a file denoted by |path| and returns its content.
std::optional<std::vector<uint8_t>> read_file(const std::string_view &path);
std::expected<std::vector<uint8_t>, Error> read_file(std::string_view path);
size_t clamp_buffer_size(ngtcp2_conn *conn, size_t buflen, size_t gso_burst);
@@ -562,16 +570,15 @@ struct ECHServerConfig {
// read_ech_server_config reads server-side ECH configuration from a
// file denoted by |path|.
std::optional<ECHServerConfig>
read_ech_server_config(const std::string_view &path);
std::expected<ECHServerConfig, Error>
read_ech_server_config(std::string_view path);
std::span<uint64_t, 2> generate_siphash_key();
// get_string returns a URL component specified by |f| of |uri|. This
// function assumes that u.field_set & (1 << f) is nonzero.
constexpr std::string_view get_string(const std::string_view &uri,
const urlparse_url &u,
urlparse_url_fields f) {
constexpr std::string_view
get_string(std::string_view uri, const urlparse_url &u, urlparse_url_fields f) {
assert(u.field_set & (1 << f));
auto p = &u.field_data[f];
@@ -606,4 +613,19 @@ inline bool operator==(const ngtcp2_cid &lhs, const ngtcp2_cid &rhs) {
return ngtcp2_cid_eq(&lhs, &rhs);
}
template <>
struct std::formatter<ngtcp2_cid> : public std::formatter<std::string_view> {
auto format(ngtcp2_cid cid, format_context &ctx) const {
std::array<char, NGTCP2_MAX_CIDLEN * 2 + 2> buf;
buf[0] = '0';
buf[1] = 'x';
auto end = ngtcp2::util::format_hex(std::span{cid.data, cid.datalen},
std::ranges::begin(buf) + 2);
return std::formatter<std::string_view>::format(
{std::ranges::begin(buf), end}, ctx);
}
};
#endif // !defined(UTIL_H)
+24 -53
View File
@@ -28,6 +28,7 @@
#include <iostream>
#include <array>
#include <algorithm>
#include <expected>
#include <ngtcp2/ngtcp2_crypto.h>
@@ -42,7 +43,7 @@ namespace ngtcp2 {
namespace util {
int generate_secure_random(std::span<uint8_t> data) {
std::expected<void, Error> generate_secure_random(std::span<uint8_t> data) {
#ifdef WITH_EXAMPLE_BORINGSSL
using size_type = size_t;
#else // !defined(WITH_EXAMPLE_BORINGSSL)
@@ -50,49 +51,18 @@ int generate_secure_random(std::span<uint8_t> data) {
#endif // !defined(WITH_EXAMPLE_BORINGSSL)
if (RAND_bytes(data.data(), static_cast<size_type>(data.size())) != 1) {
return -1;
return std::unexpected{Error::CRYPTO};
}
return 0;
return {};
}
int generate_secret(std::span<uint8_t> secret) {
std::array<uint8_t, 16> rand;
if (generate_secure_random(rand) != 0) {
return -1;
}
auto ctx = EVP_MD_CTX_new();
if (ctx == nullptr) {
return -1;
}
auto ctx_deleter = defer([ctx] { EVP_MD_CTX_free(ctx); });
static const auto sha256 =
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
EVP_MD_fetch(nullptr, "sha256", nullptr);
#else // OPENSSL_VERSION_NUMBER < 0x30000000L
EVP_sha256();
#endif // OPENSSL_VERSION_NUMBER < 0x30000000L
auto mdlen = static_cast<unsigned int>(secret.size());
if (!EVP_DigestInit_ex(ctx, sha256, nullptr) ||
!EVP_DigestUpdate(ctx, rand.data(), rand.size()) ||
!EVP_DigestFinal_ex(ctx, secret.data(), &mdlen)) {
return -1;
}
return 0;
}
std::optional<HPKEPrivateKey>
read_hpke_private_key_pem(const std::string_view &filename) {
std::expected<HPKEPrivateKey, Error>
read_hpke_private_key_pem(std::string_view filename) {
auto f = BIO_new_file(filename.data(), "r");
if (f == nullptr) {
std::cerr << "Could not open file " << filename << std::endl;
return {};
std::println(stderr, "Could not open file {}", filename);
return std::unexpected{Error::IO};
}
auto f_d = defer([f] { BIO_free(f); });
@@ -100,7 +70,7 @@ read_hpke_private_key_pem(const std::string_view &filename) {
EVP_PKEY *pkey;
if (PEM_read_bio_PrivateKey(f, &pkey, nullptr, nullptr) == nullptr) {
return {};
return std::unexpected{Error::IO};
}
auto pkey_d = defer([pkey] { EVP_PKEY_free(pkey); });
@@ -122,19 +92,19 @@ read_hpke_private_key_pem(const std::string_view &filename) {
break;
}
default:
return {};
return std::unexpected{Error::UNSUPPORTED};
}
return res;
}
std::optional<std::vector<uint8_t>> read_pem(const std::string_view &filename,
const std::string_view &name,
const std::string_view &type) {
std::expected<std::vector<uint8_t>, Error> read_pem(std::string_view filename,
std::string_view name,
std::string_view type) {
auto f = BIO_new_file(filename.data(), "r");
if (f == nullptr) {
std::cerr << "Could not open " << name << " file " << filename << std::endl;
return {};
std::println(stderr, "Could not open {} file {}", name, filename);
return std::unexpected{Error::IO};
}
auto f_d = defer([f] { BIO_free(f); });
@@ -145,9 +115,8 @@ std::optional<std::vector<uint8_t>> read_pem(const std::string_view &filename,
long datalen;
if (PEM_read_bio(f, &pem_type, &header, &data, &datalen) != 1) {
std::cerr << "Could not read " << name << " file " << filename
<< std::endl;
return {};
std::println(stderr, "Could not read {} file {}", name, filename);
return std::unexpected{Error::IO};
}
auto pem_d = defer([pem_type, header, data] {
@@ -164,19 +133,21 @@ std::optional<std::vector<uint8_t>> read_pem(const std::string_view &filename,
}
}
int write_pem(const std::string_view &filename, const std::string_view &name,
const std::string_view &type, std::span<const uint8_t> data) {
std::expected<void, Error> write_pem(std::string_view filename,
std::string_view name,
std::string_view type,
std::span<const uint8_t> data) {
auto f = BIO_new_file(filename.data(), "w");
if (f == nullptr) {
std::cerr << "Could not write " << name << " in " << filename << std::endl;
return -1;
std::println(stderr, "Could not write {} in {}", name, filename);
return std::unexpected{Error::IO};
}
PEM_write_bio(f, type.data(), "", data.data(),
static_cast<long>(data.size()));
BIO_free(f);
return 0;
return {};
}
const char *crypto_default_ciphers() {
+145 -49
View File
@@ -26,6 +26,8 @@
#include <limits>
#include <array>
#include <iterator>
#include <expected>
#include "util.h"
@@ -57,29 +59,33 @@ const MunitSuite util_suite{
};
namespace util {
std::optional<HPKEPrivateKey>
read_hpke_private_key_pem(const std::string_view &filename) {
return {};
std::expected<HPKEPrivateKey, Error>
read_hpke_private_key_pem(std::string_view filename) {
return std::unexpected{Error::NOT_IMPLEMENTED};
}
} // namespace util
namespace util {
std::optional<std::vector<uint8_t>> read_pem(const std::string_view &filename,
const std::string_view &name,
const std::string_view &type) {
return {};
std::expected<std::vector<uint8_t>, Error> read_pem(std::string_view filename,
std::string_view name,
std::string_view type) {
return std::unexpected{Error::NOT_IMPLEMENTED};
}
} // namespace util
namespace util {
int write_pem(const std::string_view &filename, const std::string_view &name,
const std::string_view &type, std::span<const uint8_t> data) {
return -1;
std::expected<void, Error> write_pem(std::string_view filename,
std::string_view name,
std::string_view type,
std::span<const uint8_t> data) {
return std::unexpected{Error::NOT_IMPLEMENTED};
}
} // namespace util
namespace util {
int generate_secure_random(std::span<uint8_t> data) { return -1; }
std::expected<void, Error> generate_secure_random(std::span<uint8_t> data) {
return std::unexpected{Error::NOT_IMPLEMENTED};
}
} // namespace util
void test_util_format_durationf() {
@@ -92,26 +98,26 @@ void test_util_format_durationf() {
assert_stdstring_equal("2.00us", util::format_durationf(1999));
assert_stdstring_equal("1.00ms", util::format_durationf(999999));
assert_stdstring_equal("3.50ms", util::format_durationf(3500111));
assert_stdstring_equal("9999.99s", util::format_durationf(9999990000000llu));
assert_stdstring_equal("9999.99s", util::format_durationf(9999990000000ULL));
}
void test_util_format_uint() {
assert_stdstring_equal("0"s, util::format_uint(0u));
assert_stdstring_equal("0"s, util::format_uint(0U));
assert_stdstring_equal("18446744073709551615"s,
util::format_uint(18446744073709551615ull));
util::format_uint(18446744073709551615ULL));
}
void test_util_format_uint_iec() {
assert_stdstring_equal("0"s, util::format_uint_iec(0u));
assert_stdstring_equal("1023"s, util::format_uint_iec((1u << 10) - 1));
assert_stdstring_equal("1K"s, util::format_uint_iec(1u << 10));
assert_stdstring_equal("1M"s, util::format_uint_iec(1u << 20));
assert_stdstring_equal("1G"s, util::format_uint_iec(1u << 30));
assert_stdstring_equal("0"s, util::format_uint_iec(0U));
assert_stdstring_equal("1023"s, util::format_uint_iec((1U << 10) - 1));
assert_stdstring_equal("1K"s, util::format_uint_iec(1U << 10));
assert_stdstring_equal("1M"s, util::format_uint_iec(1U << 20));
assert_stdstring_equal("1G"s, util::format_uint_iec(1U << 30));
assert_stdstring_equal(
"18446744073709551615"s,
util::format_uint_iec(std::numeric_limits<uint64_t>::max()));
assert_stdstring_equal("1025K"s,
util::format_uint_iec((1u << 20) + (1u << 10)));
util::format_uint_iec((1U << 20) + (1U << 10)));
}
void test_util_format_duration() {
@@ -120,12 +126,12 @@ void test_util_format_duration() {
assert_stdstring_equal("1us", util::format_duration(1000));
assert_stdstring_equal("1ms", util::format_duration(1000000));
assert_stdstring_equal("1s", util::format_duration(1000000000));
assert_stdstring_equal("1m", util::format_duration(60000000000ull));
assert_stdstring_equal("1h", util::format_duration(3600000000000ull));
assert_stdstring_equal("1m", util::format_duration(60000000000ULL));
assert_stdstring_equal("1h", util::format_duration(3600000000000ULL));
assert_stdstring_equal(
"18446744073709551615ns",
util::format_duration(std::numeric_limits<uint64_t>::max()));
assert_stdstring_equal("61s", util::format_duration(61000000000ull));
assert_stdstring_equal("61s", util::format_duration(61000000000ULL));
}
void test_util_parse_uint() {
@@ -142,7 +148,7 @@ void test_util_parse_uint() {
{
auto res = util::parse_uint("18446744073709551615");
assert_true(res.has_value());
assert_uint64(18446744073709551615ull, ==, *res);
assert_uint64(18446744073709551615ULL, ==, *res);
}
{
auto res = util::parse_uint("18446744073709551616");
@@ -187,7 +193,7 @@ void test_util_parse_uint_iec() {
{
auto res = util::parse_uint_iec("11G");
assert_true(res.has_value());
assert_uint64((1ull << 30) * 11, ==, *res);
assert_uint64((1ULL << 30) * 11, ==, *res);
}
{
auto res = util::parse_uint_iec("18446744073709551616");
@@ -273,19 +279,109 @@ void test_util_parse_duration() {
}
void test_util_normalize_path() {
assert_stdstring_equal("/", util::normalize_path("/"));
assert_stdstring_equal("/", util::normalize_path("//"));
assert_stdstring_equal("/foo", util::normalize_path("/foo"));
assert_stdstring_equal("/foo/bar/", util::normalize_path("/foo/bar/"));
assert_stdstring_equal("/foo/bar/", util::normalize_path("/foo/abc/../bar/"));
assert_stdstring_equal("/foo/bar/",
util::normalize_path("/../foo/abc/../bar/"));
assert_stdstring_equal("/foo/bar/",
util::normalize_path("/./foo/././abc///.././bar/./"));
assert_stdstring_equal("/foo/", util::normalize_path("/foo/."));
assert_stdstring_equal("/foo/bar", util::normalize_path("/foo/./bar"));
assert_stdstring_equal("/bar", util::normalize_path("/foo/./../bar"));
assert_stdstring_equal("/bar", util::normalize_path("/../../bar"));
{
auto rv = util::normalize_path("/");
assert_true(rv.has_value());
assert_stdstring_equal("/", rv.value());
}
{
auto rv = util::normalize_path("//");
assert_true(rv.has_value());
assert_stdstring_equal("/", rv.value());
}
{
auto rv = util::normalize_path("/foo");
assert_true(rv.has_value());
assert_stdstring_equal("/foo", rv.value());
}
{
auto rv = util::normalize_path("/foo/bar/");
assert_true(rv.has_value());
assert_stdstring_equal("/foo/bar/", rv.value());
}
{
auto rv = util::normalize_path("/foo/abc/../bar/");
assert_true(rv.has_value());
assert_stdstring_equal("/foo/bar/", rv.value());
}
{
auto rv = util::normalize_path("/../foo/abc/../bar/");
assert_true(rv.has_value());
assert_stdstring_equal("/foo/bar/", rv.value());
}
{
auto rv = util::normalize_path("/./foo/././abc///.././bar/./");
assert_true(rv.has_value());
assert_stdstring_equal("/foo/bar/", rv.value());
}
{
auto rv = util::normalize_path("/foo/.");
assert_true(rv.has_value());
assert_stdstring_equal("/foo/", rv.value());
}
{
auto rv = util::normalize_path("/foo/./bar");
assert_true(rv.has_value());
assert_stdstring_equal("/foo/bar", rv.value());
}
{
auto rv = util::normalize_path("/foo/./../bar");
assert_true(rv.has_value());
assert_stdstring_equal("/bar", rv.value());
}
{
auto rv = util::normalize_path("/../../bar");
assert_true(rv.has_value());
assert_stdstring_equal("/bar", rv.value());
}
{
auto rv = util::normalize_path(std::string(1024, '/'));
assert_true(rv.has_value());
assert_stdstring_equal("/", rv.value());
}
{
auto rv = util::normalize_path(std::string(1025, '/'));
assert_false(rv);
}
{
auto rv = util::normalize_path("/..");
assert_true(rv.has_value());
assert_stdstring_equal("/", rv.value());
}
{
auto rv = util::normalize_path("/../../index.html");
assert_true(rv.has_value());
assert_stdstring_equal("/index.html", rv.value());
}
}
void test_util_hexdump() {
@@ -349,7 +445,7 @@ void test_util_hexdump() {
},
{
.title = "Non-printables",
.data = "\0\a\b\t\n\v\f\r\x7f"sv,
.data = "\0\a\b\t\n\v\f\r\x7F"sv,
.dump = "00000000 00 07 08 09 0a 0b 0c 0d 7f "
"|.........|\n"
"00000009\n"sv,
@@ -399,9 +495,9 @@ void test_util_hexdump() {
munit_log(MUNIT_LOG_INFO, t.title);
auto f = tmpfile();
auto rv = util::hexdump(f, t.data.data(), t.data.size());
auto rv = util::hexdump(f, std::span{t.data});
assert_int(0, ==, rv);
assert_true(rv.has_value());
fseek(f, 0, SEEK_SET);
auto nread = fread(buf, 1, sizeof(buf), f);
@@ -414,35 +510,35 @@ void test_util_hexdump() {
}
void test_util_format_hex() {
auto a = std::to_array<uint8_t>({0xde, 0xad, 0xbe, 0xef});
auto a = std::to_array<uint8_t>({0xDE, 0xAD, 0xBE, 0xEF});
assert_stdstring_equal("deadbeef"s, util::format_hex(a));
assert_stdstring_equal("deadbeef"s, util::format_hex(0xdeadbeef));
assert_stdstring_equal("deadbeef"s, util::format_hex(0xDEADBEEF));
assert_stdstring_equal("beef"s, util::format_hex(a.data() + 2, 2));
std::array<char, 64> buf;
assert_stdsv_equal(
"00"sv, (std::string_view{std::ranges::begin(buf),
util::format_hex(static_cast<uint8_t>(0u),
util::format_hex(static_cast<uint8_t>(0U),
std::ranges::begin(buf))}));
assert_stdsv_equal(
"ec"sv, (std::string_view{std::ranges::begin(buf),
util::format_hex(static_cast<uint8_t>(0xecu),
util::format_hex(static_cast<uint8_t>(0xECU),
std::ranges::begin(buf))}));
assert_stdsv_equal(
"00000000"sv,
(std::string_view{std::ranges::begin(buf),
util::format_hex(0u, std::ranges::begin(buf))}));
util::format_hex(0U, std::ranges::begin(buf))}));
assert_stdsv_equal(
"0000ab01"sv,
(std::string_view{std::ranges::begin(buf),
util::format_hex(0xab01u, std::ranges::begin(buf))}));
util::format_hex(0xAB01U, std::ranges::begin(buf))}));
assert_stdsv_equal(
"deadbeefbaadf00d"sv,
(std::string_view{
std::ranges::begin(buf),
util::format_hex(0xdeadbeefbaadf00du, std::ranges::begin(buf))}));
util::format_hex(0xDEADBEEFBAADF00DU, std::ranges::begin(buf))}));
assert_stdsv_equal(
"ffffffffffffffff"sv,
(std::string_view{std::ranges::begin(buf),
@@ -466,7 +562,7 @@ void test_util_format_hex() {
}
void test_util_decode_hex() {
assert_stdstring_equal("\xde\xad\xbe\xef"s, util::decode_hex("deadbeef"sv));
assert_stdstring_equal("\xDE\xAD\xBE\xEF"s, util::decode_hex("deadbeef"sv));
assert_stdstring_equal(""s, util::decode_hex(""sv));
}
+22 -44
View File
@@ -28,6 +28,7 @@
#include <iostream>
#include <array>
#include <algorithm>
#include <expected>
#include <ngtcp2/ngtcp2_crypto.h>
@@ -41,50 +42,26 @@ namespace ngtcp2 {
namespace util {
int generate_secure_random(std::span<uint8_t> data) {
std::expected<void, Error> generate_secure_random(std::span<uint8_t> data) {
if (wolfSSL_RAND_bytes(data.data(), static_cast<int>(data.size())) != 1) {
return -1;
return std::unexpected{Error::CRYPTO};
}
return 0;
}
std::optional<HPKEPrivateKey>
read_hpke_private_key_pem(const std::string_view &filename) {
return {};
}
int generate_secret(std::span<uint8_t> secret) {
std::array<uint8_t, 16> rand;
if (generate_secure_random(rand) != 0) {
return -1;
}
auto ctx = wolfSSL_EVP_MD_CTX_new();
if (ctx == nullptr) {
return -1;
}
auto mdlen = static_cast<unsigned int>(secret.size());
if (!wolfSSL_EVP_DigestInit_ex(ctx, EVP_sha256(), nullptr) ||
!wolfSSL_EVP_DigestUpdate(ctx, rand.data(), rand.size()) ||
!wolfSSL_EVP_DigestFinal_ex(ctx, secret.data(), &mdlen)) {
wolfSSL_EVP_MD_CTX_free(ctx);
return -1;
}
wolfSSL_EVP_MD_CTX_free(ctx);
return 0;
std::expected<HPKEPrivateKey, Error>
read_hpke_private_key_pem(std::string_view filename) {
return std::unexpected{Error::NOT_IMPLEMENTED};
}
std::optional<std::vector<uint8_t>> read_pem(const std::string_view &filename,
const std::string_view &name,
const std::string_view &type) {
std::expected<std::vector<uint8_t>, Error> read_pem(std::string_view filename,
std::string_view name,
std::string_view type) {
auto f = wolfSSL_BIO_new_file(filename.data(), "r");
if (f == nullptr) {
std::cerr << "Could not open " << name << " file " << filename << std::endl;
return {};
std::println(stderr, "Could not open {} file {}", name, filename);
return std::unexpected{Error::IO};
}
auto f_d = defer([f] { wolfSSL_BIO_free(f); });
@@ -94,8 +71,8 @@ std::optional<std::vector<uint8_t>> read_pem(const std::string_view &filename,
long datalen;
if (wolfSSL_PEM_read_bio(f, &pem_type, &header, &data, &datalen) != 1) {
std::cerr << "Could not read " << name << " file " << filename << std::endl;
return {};
std::println(stderr, "Could not read {} file {}", name, filename);
return std::unexpected{Error::IO};
}
auto pem_d = defer([pem_type, header, data] {
@@ -105,27 +82,28 @@ std::optional<std::vector<uint8_t>> read_pem(const std::string_view &filename,
});
if (type != pem_type) {
std::cerr << name << " file " << filename << " contains unexpected type"
<< std::endl;
return {};
std::println(stderr, "{} file {} contains unexpected type", name, filename);
return std::unexpected{Error::IO};
}
return {{data, data + datalen}};
}
int write_pem(const std::string_view &filename, const std::string_view &name,
const std::string_view &type, std::span<const uint8_t> data) {
std::expected<void, Error> write_pem(std::string_view filename,
std::string_view name,
std::string_view type,
std::span<const uint8_t> data) {
auto f = wolfSSL_BIO_new_file(filename.data(), "w");
if (f == nullptr) {
std::cerr << "Could not write " << name << " in " << filename << std::endl;
return -1;
std::println(stderr, "Could not write {} to {}", name, filename);
return std::unexpected{Error::IO};
}
wolfSSL_PEM_write_bio(f, type.data(), "", data.data(),
static_cast<long>(data.size()));
wolfSSL_BIO_free(f);
return 0;
return {};
}
const char *crypto_default_ciphers() {
+344 -55
View File
@@ -262,7 +262,7 @@ typedef struct ngtcp2_mem {
*
* :macro:`NGTCP2_PROTO_VER_V1` is the QUIC version 1.
*/
#define NGTCP2_PROTO_VER_V1 ((uint32_t)0x00000001u)
#define NGTCP2_PROTO_VER_V1 ((uint32_t)0x00000001U)
/**
* @macro
@@ -270,7 +270,7 @@ typedef struct ngtcp2_mem {
* :macro:`NGTCP2_PROTO_VER_V2` is the QUIC version 2. See
* :rfc:`9369`.
*/
#define NGTCP2_PROTO_VER_V2 ((uint32_t)0x6b3343cfu)
#define NGTCP2_PROTO_VER_V2 ((uint32_t)0x6B3343CFU)
/**
* @macro
@@ -294,7 +294,7 @@ typedef struct ngtcp2_mem {
* :macro:`NGTCP2_RESERVED_VERSION_MASK` is the bit mask of reserved
* version.
*/
#define NGTCP2_RESERVED_VERSION_MASK 0x0a0a0a0au
#define NGTCP2_RESERVED_VERSION_MASK 0x0A0A0A0AU
/**
* @macrosection
@@ -377,7 +377,7 @@ typedef struct ngtcp2_mem {
* integrity tag of Retry packet. It is used for QUIC v1.
*/
#define NGTCP2_RETRY_KEY_V1 \
"\xbe\x0c\x69\x0b\x9f\x66\x57\x5a\x1d\x76\x6b\x54\xe3\x68\xc8\x4e"
"\xBE\x0C\x69\x0B\x9F\x66\x57\x5A\x1D\x76\x6B\x54\xE3\x68\xC8\x4E"
/**
* @macro
@@ -385,7 +385,7 @@ typedef struct ngtcp2_mem {
* :macro:`NGTCP2_RETRY_NONCE_V1` is nonce used when generating
* integrity tag of Retry packet. It is used for QUIC v1.
*/
#define NGTCP2_RETRY_NONCE_V1 "\x46\x15\x99\xd3\x5d\x63\x2b\xf2\x23\x98\x25\xbb"
#define NGTCP2_RETRY_NONCE_V1 "\x46\x15\x99\xD3\x5D\x63\x2B\xF2\x23\x98\x25\xBB"
/**
* @macro
@@ -395,7 +395,7 @@ typedef struct ngtcp2_mem {
* :rfc:`9369`.
*/
#define NGTCP2_RETRY_KEY_V2 \
"\x8f\xb4\xb0\x1b\x56\xac\x48\xe2\x60\xfb\xcb\xce\xad\x7c\xcc\x92"
"\x8F\xB4\xB0\x1B\x56\xAC\x48\xE2\x60\xFB\xCB\xCE\xAD\x7C\xCC\x92"
/**
* @macro
@@ -404,7 +404,7 @@ typedef struct ngtcp2_mem {
* integrity tag of Retry packet. It is used for QUIC v2. See
* :rfc:`9369`.
*/
#define NGTCP2_RETRY_NONCE_V2 "\xd8\x69\x69\xbc\x2d\x7c\x6d\x99\x90\xef\xb0\x4a"
#define NGTCP2_RETRY_NONCE_V2 "\xD8\x69\x69\xBC\x2D\x7C\x6D\x99\x90\xEF\xB0\x4A"
/**
* @macro
@@ -812,7 +812,7 @@ typedef struct NGTCP2_ALIGN(8) ngtcp2_pkt_info {
*
* :macro:`NGTCP2_PKT_FLAG_NONE` indicates no flag set.
*/
#define NGTCP2_PKT_FLAG_NONE 0x00u
#define NGTCP2_PKT_FLAG_NONE 0x00U
/**
* @macro
@@ -820,7 +820,7 @@ typedef struct NGTCP2_ALIGN(8) ngtcp2_pkt_info {
* :macro:`NGTCP2_PKT_FLAG_LONG_FORM` indicates the Long header packet
* header.
*/
#define NGTCP2_PKT_FLAG_LONG_FORM 0x01u
#define NGTCP2_PKT_FLAG_LONG_FORM 0x01U
/**
* @macro
@@ -828,14 +828,14 @@ typedef struct NGTCP2_ALIGN(8) ngtcp2_pkt_info {
* :macro:`NGTCP2_PKT_FLAG_FIXED_BIT_CLEAR` indicates that Fixed Bit
* (aka QUIC bit) is not set.
*/
#define NGTCP2_PKT_FLAG_FIXED_BIT_CLEAR 0x02u
#define NGTCP2_PKT_FLAG_FIXED_BIT_CLEAR 0x02U
/**
* @macro
*
* :macro:`NGTCP2_PKT_FLAG_KEY_PHASE` indicates Key Phase bit set.
*/
#define NGTCP2_PKT_FLAG_KEY_PHASE 0x04u
#define NGTCP2_PKT_FLAG_KEY_PHASE 0x04U
/**
* @enum
@@ -887,7 +887,7 @@ typedef enum ngtcp2_pkt_type {
*
* :macro:`NGTCP2_NO_ERROR` is QUIC transport error code ``NO_ERROR``.
*/
#define NGTCP2_NO_ERROR 0x0u
#define NGTCP2_NO_ERROR 0x0U
/**
* @macro
@@ -895,7 +895,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_INTERNAL_ERROR` is QUIC transport error code
* ``INTERNAL_ERROR``.
*/
#define NGTCP2_INTERNAL_ERROR 0x1u
#define NGTCP2_INTERNAL_ERROR 0x1U
/**
* @macro
@@ -903,7 +903,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_CONNECTION_REFUSED` is QUIC transport error code
* ``CONNECTION_REFUSED``.
*/
#define NGTCP2_CONNECTION_REFUSED 0x2u
#define NGTCP2_CONNECTION_REFUSED 0x2U
/**
* @macro
@@ -911,7 +911,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_FLOW_CONTROL_ERROR` is QUIC transport error code
* ``FLOW_CONTROL_ERROR``.
*/
#define NGTCP2_FLOW_CONTROL_ERROR 0x3u
#define NGTCP2_FLOW_CONTROL_ERROR 0x3U
/**
* @macro
@@ -919,7 +919,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_STREAM_LIMIT_ERROR` is QUIC transport error code
* ``STREAM_LIMIT_ERROR``.
*/
#define NGTCP2_STREAM_LIMIT_ERROR 0x4u
#define NGTCP2_STREAM_LIMIT_ERROR 0x4U
/**
* @macro
@@ -927,7 +927,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_STREAM_STATE_ERROR` is QUIC transport error code
* ``STREAM_STATE_ERROR``.
*/
#define NGTCP2_STREAM_STATE_ERROR 0x5u
#define NGTCP2_STREAM_STATE_ERROR 0x5U
/**
* @macro
@@ -935,7 +935,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_FINAL_SIZE_ERROR` is QUIC transport error code
* ``FINAL_SIZE_ERROR``.
*/
#define NGTCP2_FINAL_SIZE_ERROR 0x6u
#define NGTCP2_FINAL_SIZE_ERROR 0x6U
/**
* @macro
@@ -943,7 +943,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_FRAME_ENCODING_ERROR` is QUIC transport error code
* ``FRAME_ENCODING_ERROR``.
*/
#define NGTCP2_FRAME_ENCODING_ERROR 0x7u
#define NGTCP2_FRAME_ENCODING_ERROR 0x7U
/**
* @macro
@@ -951,7 +951,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_TRANSPORT_PARAMETER_ERROR` is QUIC transport error
* code ``TRANSPORT_PARAMETER_ERROR``.
*/
#define NGTCP2_TRANSPORT_PARAMETER_ERROR 0x8u
#define NGTCP2_TRANSPORT_PARAMETER_ERROR 0x8U
/**
* @macro
@@ -959,7 +959,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_CONNECTION_ID_LIMIT_ERROR` is QUIC transport error
* code ``CONNECTION_ID_LIMIT_ERROR``.
*/
#define NGTCP2_CONNECTION_ID_LIMIT_ERROR 0x9u
#define NGTCP2_CONNECTION_ID_LIMIT_ERROR 0x9U
/**
* @macro
@@ -967,7 +967,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_PROTOCOL_VIOLATION` is QUIC transport error code
* ``PROTOCOL_VIOLATION``.
*/
#define NGTCP2_PROTOCOL_VIOLATION 0xau
#define NGTCP2_PROTOCOL_VIOLATION 0xAU
/**
* @macro
@@ -975,7 +975,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_INVALID_TOKEN` is QUIC transport error code
* ``INVALID_TOKEN``.
*/
#define NGTCP2_INVALID_TOKEN 0xbu
#define NGTCP2_INVALID_TOKEN 0xBU
/**
* @macro
@@ -983,7 +983,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_APPLICATION_ERROR` is QUIC transport error code
* ``APPLICATION_ERROR``.
*/
#define NGTCP2_APPLICATION_ERROR 0xcu
#define NGTCP2_APPLICATION_ERROR 0xCU
/**
* @macro
@@ -991,7 +991,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_CRYPTO_BUFFER_EXCEEDED` is QUIC transport error code
* ``CRYPTO_BUFFER_EXCEEDED``.
*/
#define NGTCP2_CRYPTO_BUFFER_EXCEEDED 0xdu
#define NGTCP2_CRYPTO_BUFFER_EXCEEDED 0xDU
/**
* @macro
@@ -999,7 +999,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_KEY_UPDATE_ERROR` is QUIC transport error code
* ``KEY_UPDATE_ERROR``.
*/
#define NGTCP2_KEY_UPDATE_ERROR 0xeu
#define NGTCP2_KEY_UPDATE_ERROR 0xEU
/**
* @macro
@@ -1007,7 +1007,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_AEAD_LIMIT_REACHED` is QUIC transport error code
* ``AEAD_LIMIT_REACHED``.
*/
#define NGTCP2_AEAD_LIMIT_REACHED 0xfu
#define NGTCP2_AEAD_LIMIT_REACHED 0xFU
/**
* @macro
@@ -1015,7 +1015,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_NO_VIABLE_PATH` is QUIC transport error code
* ``NO_VIABLE_PATH``.
*/
#define NGTCP2_NO_VIABLE_PATH 0x10u
#define NGTCP2_NO_VIABLE_PATH 0x10U
/**
* @macro
@@ -1023,7 +1023,7 @@ typedef enum ngtcp2_pkt_type {
* :macro:`NGTCP2_CRYPTO_ERROR` is QUIC transport error code
* ``CRYPTO_ERROR``.
*/
#define NGTCP2_CRYPTO_ERROR 0x100u
#define NGTCP2_CRYPTO_ERROR 0x100U
/**
* @macro
@@ -1187,6 +1187,9 @@ typedef struct ngtcp2_pkt_hd {
* @struct
*
* :type:`ngtcp2_pkt_stateless_reset` represents Stateless Reset.
*
* Deprecated since v1.22.0. Use :type:`ngtcp2_pkt_stateless_reset2`
* instead.
*/
typedef struct ngtcp2_pkt_stateless_reset {
/**
@@ -1204,6 +1207,40 @@ typedef struct ngtcp2_pkt_stateless_reset {
size_t randlen;
} ngtcp2_pkt_stateless_reset;
/**
* @struct
*
* :type:`ngtcp2_stateless_reset_token` stores stateless reset token.
*
* This struct has been available since v1.22.0.
*/
typedef struct ngtcp2_stateless_reset_token {
uint8_t data[NGTCP2_STATELESS_RESET_TOKENLEN];
} ngtcp2_stateless_reset_token;
/**
* @struct
*
* :type:`ngtcp2_pkt_stateless_reset2` represents Stateless Reset.
*
* This struct has been available since v1.22.0.
*/
typedef struct ngtcp2_pkt_stateless_reset2 {
/**
* :member:`token` contains stateless reset token.
*/
ngtcp2_stateless_reset_token token;
/**
* :member:`rand` points a buffer which contains random bytes
* section.
*/
const uint8_t *rand;
/**
* :member:`randlen` is the number of random bytes.
*/
size_t randlen;
} ngtcp2_pkt_stateless_reset2;
/**
* @macrosection
*
@@ -1250,7 +1287,7 @@ typedef struct ngtcp2_pkt_stateless_reset {
* :macro:`NGTCP2_TLSEXT_QUIC_TRANSPORT_PARAMETERS_V1` is TLS
* extension type of quic_transport_parameters.
*/
#define NGTCP2_TLSEXT_QUIC_TRANSPORT_PARAMETERS_V1 0x39u
#define NGTCP2_TLSEXT_QUIC_TRANSPORT_PARAMETERS_V1 0x39U
#ifdef NGTCP2_USE_GENERIC_SOCKADDR
# ifndef NGTCP2_AF_INET
@@ -1703,14 +1740,14 @@ typedef void (*ngtcp2_printf)(void *user_data, const char *format, ...);
*
* :macro:`NGTCP2_QLOG_WRITE_FLAG_NONE` indicates no flag set.
*/
#define NGTCP2_QLOG_WRITE_FLAG_NONE 0x00u
#define NGTCP2_QLOG_WRITE_FLAG_NONE 0x00U
/**
* @macro
*
* :macro:`NGTCP2_QLOG_WRITE_FLAG_FIN` indicates that this is the
* final call to :type:`ngtcp2_qlog_write` in the current connection.
*/
#define NGTCP2_QLOG_WRITE_FLAG_FIN 0x01u
#define NGTCP2_QLOG_WRITE_FLAG_FIN 0x01U
/**
* @struct
@@ -2444,11 +2481,42 @@ NGTCP2_EXTERN ngtcp2_ssize ngtcp2_pkt_decode_hd_short(ngtcp2_pkt_hd *dest,
* :macro:`NGTCP2_ERR_INVALID_ARGUMENT`
* |randlen| is strictly less than
* :macro:`NGTCP2_MIN_STATELESS_RESET_RANDLEN`.
*
* Deprecated since v1.22.0. Use `ngtcp2_pkt_write_stateless_reset2`
* instead.
*/
NGTCP2_EXTERN ngtcp2_ssize ngtcp2_pkt_write_stateless_reset(
uint8_t *dest, size_t destlen, const uint8_t *stateless_reset_token,
const uint8_t *rand, size_t randlen);
/**
* @function
*
* `ngtcp2_pkt_write_stateless_reset2` writes Stateless Reset packet
* in the buffer pointed by |dest| whose length is |destlen|. |token|
* must store the Stateless Reset Token. |rand| specifies the random
* octets preceding Stateless Reset Token. The length of |rand| is
* specified by |randlen| which must be at least
* :macro:`NGTCP2_MIN_STATELESS_RESET_RANDLEN` bytes long.
*
* If |randlen| is too long to write them all in the buffer, |rand| is
* written to the buffer as much as possible, and is truncated.
*
* This function returns the number of bytes written to the buffer, or
* one of the following negative error codes:
*
* :macro:`NGTCP2_ERR_NOBUF`
* Buffer is too small.
* :macro:`NGTCP2_ERR_INVALID_ARGUMENT`
* |randlen| is strictly less than
* :macro:`NGTCP2_MIN_STATELESS_RESET_RANDLEN`.
*
* This function has been available since v1.22.0.
*/
NGTCP2_EXTERN ngtcp2_ssize ngtcp2_pkt_write_stateless_reset2(
uint8_t *dest, size_t destlen, const ngtcp2_stateless_reset_token *token,
const uint8_t *rand, size_t randlen);
/**
* @function
*
@@ -2744,7 +2812,7 @@ typedef int (*ngtcp2_hp_mask)(uint8_t *dest, const ngtcp2_crypto_cipher *hp,
*
* :macro:`NGTCP2_STREAM_DATA_FLAG_NONE` indicates no flag set.
*/
#define NGTCP2_STREAM_DATA_FLAG_NONE 0x00u
#define NGTCP2_STREAM_DATA_FLAG_NONE 0x00U
/**
* @macro
@@ -2752,7 +2820,7 @@ typedef int (*ngtcp2_hp_mask)(uint8_t *dest, const ngtcp2_crypto_cipher *hp,
* :macro:`NGTCP2_STREAM_DATA_FLAG_FIN` indicates that this chunk of
* data is final piece of an incoming stream.
*/
#define NGTCP2_STREAM_DATA_FLAG_FIN 0x01u
#define NGTCP2_STREAM_DATA_FLAG_FIN 0x01U
/**
* @macro
@@ -2761,7 +2829,7 @@ typedef int (*ngtcp2_hp_mask)(uint8_t *dest, const ngtcp2_crypto_cipher *hp,
* data contains data received in 0-RTT packet, and the handshake has
* not completed yet, which means that the data might be replayed.
*/
#define NGTCP2_STREAM_DATA_FLAG_0RTT 0x02u
#define NGTCP2_STREAM_DATA_FLAG_0RTT 0x02U
/**
* @functypedef
@@ -2816,7 +2884,7 @@ typedef int (*ngtcp2_stream_open)(ngtcp2_conn *conn, int64_t stream_id,
*
* :macro:`NGTCP2_STREAM_CLOSE_FLAG_NONE` indicates no flag set.
*/
#define NGTCP2_STREAM_CLOSE_FLAG_NONE 0x00u
#define NGTCP2_STREAM_CLOSE_FLAG_NONE 0x00U
/**
* @macro
@@ -2824,7 +2892,7 @@ typedef int (*ngtcp2_stream_open)(ngtcp2_conn *conn, int64_t stream_id,
* :macro:`NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET` indicates that
* app_error_code parameter is set.
*/
#define NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET 0x01u
#define NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET 0x01U
/**
* @functypedef
@@ -2905,6 +2973,9 @@ typedef int (*ngtcp2_acked_stream_data_offset)(
* The implementation of this callback should return 0 if it succeeds.
* Returning :macro:`NGTCP2_ERR_CALLBACK_FAILURE` makes the library
* call return immediately.
*
* Deprecated since v1.22.0. Use :type:`ngtcp2_recv_stateless_reset2`
* instead.
*/
typedef int (*ngtcp2_recv_stateless_reset)(ngtcp2_conn *conn,
const ngtcp2_pkt_stateless_reset *sr,
@@ -2969,6 +3040,9 @@ typedef void (*ngtcp2_rand)(uint8_t *dest, size_t destlen,
* The callback function must return 0 if it succeeds. Returning
* :macro:`NGTCP2_ERR_CALLBACK_FAILURE` makes the library call return
* immediately.
*
* Deprecated since v1.22.0. Use
* :type:`ngtcp2_get_new_connection_id2` instead.
*/
typedef int (*ngtcp2_get_new_connection_id)(ngtcp2_conn *conn, ngtcp2_cid *cid,
uint8_t *token, size_t cidlen,
@@ -3033,7 +3107,7 @@ typedef int (*ngtcp2_update_key)(
*
* :macro:`NGTCP2_PATH_VALIDATION_FLAG_NONE` indicates no flag set.
*/
#define NGTCP2_PATH_VALIDATION_FLAG_NONE 0x00u
#define NGTCP2_PATH_VALIDATION_FLAG_NONE 0x00U
/**
* @macro
@@ -3042,7 +3116,7 @@ typedef int (*ngtcp2_update_key)(
* validation involving server preferred address. This flag is only
* set for client.
*/
#define NGTCP2_PATH_VALIDATION_FLAG_PREFERRED_ADDR 0x01u
#define NGTCP2_PATH_VALIDATION_FLAG_PREFERRED_ADDR 0x01U
/**
* @macro
@@ -3051,7 +3125,7 @@ typedef int (*ngtcp2_update_key)(
* server should send NEW_TOKEN frame for the new remote address.
* This flag is only set for server.
*/
#define NGTCP2_PATH_VALIDATION_FLAG_NEW_TOKEN 0x02u
#define NGTCP2_PATH_VALIDATION_FLAG_NEW_TOKEN 0x02U
/**
* @functypedef
@@ -3166,6 +3240,9 @@ typedef enum ngtcp2_connection_id_status_type {
* The callback function must return 0 if it succeeds. Returning
* :macro:`NGTCP2_ERR_CALLBACK_FAILURE` makes the library call return
* immediately.
*
* Deprecated since v1.22.0. Use :type:`ngtcp2_connection_id_status2`
* instead.
*/
typedef int (*ngtcp2_connection_id_status)(
ngtcp2_conn *conn, ngtcp2_connection_id_status_type type, uint64_t seq,
@@ -3221,7 +3298,7 @@ typedef void (*ngtcp2_delete_crypto_cipher_ctx)(
*
* :macro:`NGTCP2_DATAGRAM_FLAG_NONE` indicates no flag set.
*/
#define NGTCP2_DATAGRAM_FLAG_NONE 0x00u
#define NGTCP2_DATAGRAM_FLAG_NONE 0x00U
/**
* @macro
@@ -3230,7 +3307,7 @@ typedef void (*ngtcp2_delete_crypto_cipher_ctx)(
* received in 0-RTT packet, and the handshake has not completed yet,
* which means that the data might be replayed.
*/
#define NGTCP2_DATAGRAM_FLAG_0RTT 0x01u
#define NGTCP2_DATAGRAM_FLAG_0RTT 0x01U
/**
* @functypedef
@@ -3293,6 +3370,9 @@ typedef int (*ngtcp2_lost_datagram)(ngtcp2_conn *conn, uint64_t dgram_id,
* The callback function must return 0 if it succeeds. Returning
* :macro:`NGTCP2_ERR_CALLBACK_FAILURE` makes the library call return
* immediately.
*
* Deprecated since v1.22.0. Use
* :type:`ngtcp2_get_path_challenge_data2` instead.
*/
typedef int (*ngtcp2_get_path_challenge_data)(ngtcp2_conn *conn, uint8_t *data,
void *user_data);
@@ -3364,9 +3444,99 @@ typedef int (*ngtcp2_recv_key)(ngtcp2_conn *conn, ngtcp2_encryption_level level,
typedef int (*ngtcp2_tls_early_data_rejected)(ngtcp2_conn *conn,
void *user_data);
/**
* @functypedef
*
* :type:`ngtcp2_recv_stateless_reset2` is a callback function which
* is called when Stateless Reset packet is received. The stateless
* reset details are given in |sr|.
*
* The implementation of this callback should return 0 if it succeeds.
* Returning :macro:`NGTCP2_ERR_CALLBACK_FAILURE` makes the library
* call return immediately.
*
* This type has been available since v1.22.0
*/
typedef int (*ngtcp2_recv_stateless_reset2)(
ngtcp2_conn *conn, const ngtcp2_pkt_stateless_reset2 *sr, void *user_data);
/**
* @functypedef
*
* :type:`ngtcp2_get_new_connection_id2` is a callback function to ask
* an application for new connection ID. Application must generate
* new unused connection ID with the exact |cidlen| bytes, and store
* it in |cid|. It also has to generate a stateless reset token, and
* store it in |token|.
*
* The callback function must return 0 if it succeeds. Returning
* :macro:`NGTCP2_ERR_CALLBACK_FAILURE` makes the library call return
* immediately.
*
* This type has been available since v1.22.0
*/
typedef int (*ngtcp2_get_new_connection_id2)(
ngtcp2_conn *conn, ngtcp2_cid *cid, ngtcp2_stateless_reset_token *token,
size_t cidlen, void *user_data);
/**
* @functypedef
*
* :type:`ngtcp2_connection_id_status2` is a callback function which
* is called when the status of Destination Connection ID changes.
*
* |token| is the associated stateless reset token, and it is ``NULL``
* if no token is present.
*
* |type| is the one of the value defined in
* :type:`ngtcp2_connection_id_status_type`. The new value might be
* added in the future release.
*
* The callback function must return 0 if it succeeds. Returning
* :macro:`NGTCP2_ERR_CALLBACK_FAILURE` makes the library call return
* immediately.
*
* This type has been available since v1.22.0
*/
typedef int (*ngtcp2_connection_id_status2)(
ngtcp2_conn *conn, ngtcp2_connection_id_status_type type, uint64_t seq,
const ngtcp2_cid *cid, const ngtcp2_stateless_reset_token *token,
void *user_data);
/**
* @struct
*
* :type:`ngtcp2_path_challenge_data` stores path challenge data.
*
* This type has been available since v1.22.0.
*/
typedef struct ngtcp2_path_challenge_data {
uint8_t data[NGTCP2_PATH_CHALLENGE_DATALEN];
} ngtcp2_path_challenge_data;
/**
* @functypedef
*
* :type:`ngtcp2_get_path_challenge_data2` is a callback function to
* ask an application for new data that is sent in PATH_CHALLENGE
* frame. Application must generate new unpredictable, exactly
* :macro:`NGTCP2_PATH_CHALLENGE_DATALEN` bytes of random data, and
* store them into |data|.
*
* The callback function must return 0 if it succeeds. Returning
* :macro:`NGTCP2_ERR_CALLBACK_FAILURE` makes the library call return
* immediately.
*
* This type has been available since v1.22.0.
*/
typedef int (*ngtcp2_get_path_challenge_data2)(ngtcp2_conn *conn,
ngtcp2_path_challenge_data *data,
void *user_data);
#define NGTCP2_CALLBACKS_V1 1
#define NGTCP2_CALLBACKS_V2 2
#define NGTCP2_CALLBACKS_VERSION NGTCP2_CALLBACKS_V2
#define NGTCP2_CALLBACKS_V3 3
#define NGTCP2_CALLBACKS_VERSION NGTCP2_CALLBACKS_V3
/**
* @struct
@@ -3453,6 +3623,11 @@ typedef struct ngtcp2_callbacks {
* :member:`recv_stateless_reset` is a callback function which is
* invoked when Stateless Reset packet is received. This callback
* function is optional.
*
* Deprecated since v1.22.0. Use :member:`recv_stateless_reset2`
* instead. If both :member:`recv_stateless_reset` and
* :member:`recv_stateless_reset2` are set, the latter has the
* precedence.
*/
ngtcp2_recv_stateless_reset recv_stateless_reset;
/**
@@ -3483,8 +3658,14 @@ typedef struct ngtcp2_callbacks {
ngtcp2_rand rand;
/**
* :member:`get_new_connection_id` is a callback function which is
* invoked when the library needs new connection ID. This callback
* function must be specified.
* invoked when the library needs new connection ID. Either this
* callback function or :member:`get_new_connection_id2` must be
* specified.
*
* Deprecated since v1.22.0. Use :member:`get_new_connection_id2`
* instead. If both :member:`get_new_connection_id` and
* :member:`get_new_connection_id2` are set, the latter has the
* precedence.
*/
ngtcp2_get_new_connection_id get_new_connection_id;
/**
@@ -3545,6 +3726,10 @@ typedef struct ngtcp2_callbacks {
* when the new Destination Connection ID is activated, or the
* activated Destination Connection ID is now deactivated. This
* callback function is optional.
*
* Deprecated since v1.22.0. Use :member:`dcid_status2` instead.
* If both :member:`dcid_status` and :member:`dcid_status2` are set,
* the latter has the precedence.
*/
ngtcp2_connection_id_status dcid_status;
/**
@@ -3595,6 +3780,9 @@ typedef struct ngtcp2_callbacks {
* :member:`get_path_challenge_data` is a callback function which is
* invoked when the library needs new data sent along with
* PATH_CHALLENGE frame. This callback must be specified.
*
* Deprecated since v1.22.0. Use :member:`get_path_challenge_data2`
* instead.
*/
ngtcp2_get_path_challenge_data get_path_challenge_data;
/**
@@ -3638,6 +3826,35 @@ typedef struct ngtcp2_callbacks {
* available since v1.14.0.
*/
ngtcp2_begin_path_validation begin_path_validation;
/* The following fields have been added since NGTCP2_CALLBACKS_V3. */
/**
* :member:`recv_stateless_reset2` is a callback function which is
* invoked when Stateless Reset packet is received. This callback
* function is optional. This field is available since v1.22.0.
*/
ngtcp2_recv_stateless_reset2 recv_stateless_reset2;
/**
* :member:`get_new_connection_id2` is a callback function which is
* invoked when the library needs new connection ID. This callback
* function must be specified. This field is available since
* v1.22.0.
*/
ngtcp2_get_new_connection_id2 get_new_connection_id2;
/**
* :member:`dcid_status2` is a callback function which is invoked
* when the new Destination Connection ID is activated, or the
* activated Destination Connection ID is now deactivated. This
* callback function is optional. This field is available since
* v1.22.0.
*/
ngtcp2_connection_id_status2 dcid_status2;
/**
* :member:`get_path_challenge_data2` is a callback function which
* is invoked when the library needs new data sent along with
* PATH_CHALLENGE frame. This callback must be specified. This
* field is available since v1.22.0.
*/
ngtcp2_get_path_challenge_data2 get_path_challenge_data2;
} ngtcp2_callbacks;
/**
@@ -3853,6 +4070,21 @@ NGTCP2_EXTERN ngtcp2_ssize ngtcp2_conn_write_pkt_versioned(
ngtcp2_conn *conn, ngtcp2_path *path, int pkt_info_version,
ngtcp2_pkt_info *pi, uint8_t *dest, size_t destlen, ngtcp2_tstamp ts);
/**
* @function
*
* `ngtcp2_conn_continue_handshake` resumes handshake interrupted by
* TLS stack routine (e.g., private key operation offloading,
* certificate lookup, etc).
*
* This function returns 0 if it succeeds. In general, this function
* returns the same set of error codes from `ngtcp2_conn_read_pkt`.
*
* This function has been available since v1.22.0.
*/
NGTCP2_EXTERN int ngtcp2_conn_continue_handshake(ngtcp2_conn *conn,
ngtcp2_tstamp ts);
/**
* @function
*
@@ -4512,7 +4744,7 @@ NGTCP2_EXTERN int ngtcp2_conn_shutdown_stream_read(ngtcp2_conn *conn,
*
* :macro:`NGTCP2_WRITE_STREAM_FLAG_NONE` indicates no flag set.
*/
#define NGTCP2_WRITE_STREAM_FLAG_NONE 0x00u
#define NGTCP2_WRITE_STREAM_FLAG_NONE 0x00U
/**
* @macro
@@ -4520,7 +4752,7 @@ NGTCP2_EXTERN int ngtcp2_conn_shutdown_stream_read(ngtcp2_conn *conn,
* :macro:`NGTCP2_WRITE_STREAM_FLAG_MORE` indicates that more data may
* come, and should be coalesced into the same packet if possible.
*/
#define NGTCP2_WRITE_STREAM_FLAG_MORE 0x01u
#define NGTCP2_WRITE_STREAM_FLAG_MORE 0x01U
/**
* @macro
@@ -4528,7 +4760,7 @@ NGTCP2_EXTERN int ngtcp2_conn_shutdown_stream_read(ngtcp2_conn *conn,
* :macro:`NGTCP2_WRITE_STREAM_FLAG_FIN` indicates that a passed data
* is the final part of a stream.
*/
#define NGTCP2_WRITE_STREAM_FLAG_FIN 0x02u
#define NGTCP2_WRITE_STREAM_FLAG_FIN 0x02U
/**
* @macro
@@ -4539,7 +4771,7 @@ NGTCP2_EXTERN int ngtcp2_conn_shutdown_stream_read(ngtcp2_conn *conn,
* finalizing it. PATH_CHALLENGE, PATH_RESPONSE, CONNECTION_CLOSE
* only packets and PMTUD packets are excluded.
*/
#define NGTCP2_WRITE_STREAM_FLAG_PADDING 0x04u
#define NGTCP2_WRITE_STREAM_FLAG_PADDING 0x04U
/**
* @function
@@ -4724,7 +4956,7 @@ NGTCP2_EXTERN ngtcp2_ssize ngtcp2_conn_writev_stream_versioned(
*
* :macro:`NGTCP2_WRITE_DATAGRAM_FLAG_NONE` indicates no flag set.
*/
#define NGTCP2_WRITE_DATAGRAM_FLAG_NONE 0x00u
#define NGTCP2_WRITE_DATAGRAM_FLAG_NONE 0x00U
/**
* @macro
@@ -4732,7 +4964,7 @@ NGTCP2_EXTERN ngtcp2_ssize ngtcp2_conn_writev_stream_versioned(
* :macro:`NGTCP2_WRITE_DATAGRAM_FLAG_MORE` indicates that more data
* may come, and should be coalesced into the same packet if possible.
*/
#define NGTCP2_WRITE_DATAGRAM_FLAG_MORE 0x01u
#define NGTCP2_WRITE_DATAGRAM_FLAG_MORE 0x01U
/**
* @macro
@@ -4743,7 +4975,7 @@ NGTCP2_EXTERN ngtcp2_ssize ngtcp2_conn_writev_stream_versioned(
* finalizing it. PATH_CHALLENGE, PATH_RESPONSE, CONNECTION_CLOSE
* only packets and PMTUD packets are excluded.
*/
#define NGTCP2_WRITE_DATAGRAM_FLAG_PADDING 0x02u
#define NGTCP2_WRITE_DATAGRAM_FLAG_PADDING 0x02U
/**
* @function
@@ -4980,6 +5212,8 @@ NGTCP2_EXTERN size_t ngtcp2_conn_get_scid(ngtcp2_conn *conn, ngtcp2_cid *dest);
*
* :type:`ngtcp2_cid_token` is the convenient struct to store
* Connection ID, its associated path, and stateless reset token.
*
* Deprecated since v1.22.0. Use :type:`ngtcp2_cid_token2` instead.
*/
typedef struct ngtcp2_cid_token {
/**
@@ -5019,10 +5253,65 @@ typedef struct ngtcp2_cid_token {
* sizeof(:type:`ngtcp2_cid_token`) * n bytes available, where n is
* the return value of `ngtcp2_conn_get_active_dcid` with |dest| ==
* NULL.
*
* Deprecated since v1.22.0. Use `ngtcp2_conn_get_active_dcid2`
* instead.
*/
NGTCP2_EXTERN size_t ngtcp2_conn_get_active_dcid(ngtcp2_conn *conn,
ngtcp2_cid_token *dest);
/**
* @struct
*
* :type:`ngtcp2_cid_token2` is the convenient struct to store
* Connection ID, its associated path, and stateless reset token.
*
* This type has been available since v1.22.0.
*/
typedef struct ngtcp2_cid_token2 {
/**
* :member:`seq` is the sequence number of this Connection ID.
*/
uint64_t seq;
/**
* :member:`cid` is Connection ID.
*/
ngtcp2_cid cid;
/**
* :member:`ps` is the path which this Connection ID is associated
* with.
*/
ngtcp2_path_storage ps;
/**
* :member:`token` is the stateless reset token for this Connection
* ID.
*/
ngtcp2_stateless_reset_token token;
/**
* :member:`token_present` is nonzero if token contains stateless
* reset token.
*/
uint8_t token_present;
} ngtcp2_cid_token2;
/**
* @function
*
* `ngtcp2_conn_get_active_dcid2` writes the all active Destination
* Connection IDs and their tokens to |dest|. Before handshake
* completes, this function returns 0. If |dest| is NULL, this
* function does not write anything, and returns the number of
* Destination Connection IDs that would otherwise be written to the
* provided buffer. The buffer pointed by |dest| must have
* sizeof(:type:`ngtcp2_cid_token2`) * n bytes available, where n is
* the return value of `ngtcp2_conn_get_active_dcid2` with |dest| ==
* NULL.
*
* This function has been available since v1.22.0.
*/
NGTCP2_EXTERN size_t ngtcp2_conn_get_active_dcid2(ngtcp2_conn *conn,
ngtcp2_cid_token2 *dest);
/**
* @function
*
@@ -5553,7 +5842,7 @@ NGTCP2_EXTERN void ngtcp2_ccerr_set_application_error(ngtcp2_ccerr *ccerr,
* @function
*
* `ngtcp2_conn_write_connection_close` writes a packet which contains
* CONNECTION_CLOSE frame(s) (type 0x1c or 0x1d) in the buffer pointed
* CONNECTION_CLOSE frame(s) (type 0x1C or 0x1D) in the buffer pointed
* by |dest| whose capacity is |destlen|.
*
* For client, |destlen| should be at least
@@ -5570,10 +5859,10 @@ NGTCP2_EXTERN void ngtcp2_ccerr_set_application_error(ngtcp2_ccerr *ccerr,
*
* If :member:`ccerr->type <ngtcp2_ccerr.type>` ==
* :enum:`ngtcp2_ccerr_type.NGTCP2_CCERR_TYPE_TRANSPORT`, this
* function sends CONNECTION_CLOSE (type 0x1c) frame. If
* function sends CONNECTION_CLOSE (type 0x1C) frame. If
* :member:`ccerr->type <ngtcp2_ccerr.type>` ==
* :enum:`ngtcp2_ccerr_type.NGTCP2_CCERR_TYPE_APPLICATION`, it sends
* CONNECTION_CLOSE (type 0x1d) frame. Otherwise, it does not produce
* CONNECTION_CLOSE (type 0x1D) frame. Otherwise, it does not produce
* any data, and returns 0.
*
* |destlen| could be shorten by some factors (e.g., server side
+2 -2
View File
@@ -36,7 +36,7 @@
*
* Version number of the ngtcp2 library release.
*/
#define NGTCP2_VERSION "1.21.0"
#define NGTCP2_VERSION "1.22.0"
/**
* @macro
@@ -46,6 +46,6 @@
* number, 8 bits for minor and 8 bits for patch. Version 1.2.3
* becomes 0x010203.
*/
#define NGTCP2_VERSION_NUM 0x011500
#define NGTCP2_VERSION_NUM 0x011600
#endif /* !defined(NGTCP2_VERSION_H) */
+4 -4
View File
@@ -97,16 +97,16 @@ typedef struct ngtcp2_acktr_ack_entry {
} ngtcp2_acktr_ack_entry;
/* NGTCP2_ACKTR_FLAG_NONE indicates that no flag set. */
#define NGTCP2_ACKTR_FLAG_NONE 0x00u
#define NGTCP2_ACKTR_FLAG_NONE 0x00U
/* NGTCP2_ACKTR_FLAG_IMMEDIATE_ACK indicates that immediate
acknowledgement is required. */
#define NGTCP2_ACKTR_FLAG_IMMEDIATE_ACK 0x01u
#define NGTCP2_ACKTR_FLAG_IMMEDIATE_ACK 0x01U
/* NGTCP2_ACKTR_FLAG_ACTIVE_ACK indicates that there are pending
protected packet to be acknowledged. */
#define NGTCP2_ACKTR_FLAG_ACTIVE_ACK 0x02u
#define NGTCP2_ACKTR_FLAG_ACTIVE_ACK 0x02U
/* NGTCP2_ACKTR_FLAG_CANCEL_TIMER is set when ACK delay timer is
expired and canceled. */
#define NGTCP2_ACKTR_FLAG_CANCEL_TIMER 0x0100u
#define NGTCP2_ACKTR_FLAG_CANCEL_TIMER 0x0100U
ngtcp2_static_ringbuf_def(acks, 32, sizeof(ngtcp2_acktr_ack_entry))
+4 -4
View File
@@ -46,14 +46,14 @@ void ngtcp2_addr_copy(ngtcp2_addr *dest, const ngtcp2_addr *src);
int ngtcp2_addr_eq(const ngtcp2_addr *a, const ngtcp2_addr *b);
/* NGTCP2_ADDR_CMP_FLAG_NONE indicates that no flag set. */
#define NGTCP2_ADDR_CMP_FLAG_NONE 0x0u
#define NGTCP2_ADDR_CMP_FLAG_NONE 0x0U
/* NGTCP2_ADDR_CMP_FLAG_ADDR indicates IP addresses do not match. */
#define NGTCP2_ADDR_CMP_FLAG_ADDR 0x1u
#define NGTCP2_ADDR_CMP_FLAG_ADDR 0x1U
/* NGTCP2_ADDR_CMP_FLAG_PORT indicates ports do not match. */
#define NGTCP2_ADDR_CMP_FLAG_PORT 0x2u
#define NGTCP2_ADDR_CMP_FLAG_PORT 0x2U
/* NGTCP2_ADDR_CMP_FLAG_FAMILY indicates address families do not
match. */
#define NGTCP2_ADDR_CMP_FLAG_FAMILY 0x4u
#define NGTCP2_ADDR_CMP_FLAG_FAMILY 0x4U
/*
* ngtcp2_addr_cmp compares address and port between |a| and |b|, and
+6 -6
View File
@@ -30,7 +30,7 @@
void ngtcp2_balloc_init(ngtcp2_balloc *balloc, size_t blklen,
const ngtcp2_mem *mem) {
assert((blklen & 0xfu) == 0);
assert((blklen & 0xFU) == 0);
balloc->mem = mem;
balloc->blklen = blklen;
@@ -66,7 +66,7 @@ int ngtcp2_balloc_get(ngtcp2_balloc *balloc, void **pbuf, size_t n) {
if (ngtcp2_buf_left(&balloc->buf) < n) {
p = ngtcp2_mem_malloc(balloc->mem,
sizeof(ngtcp2_memblock_hd) + 0x8u + balloc->blklen);
sizeof(ngtcp2_memblock_hd) + 0x8U + balloc->blklen);
if (p == NULL) {
return NGTCP2_ERR_NOMEM;
}
@@ -76,15 +76,15 @@ int ngtcp2_balloc_get(ngtcp2_balloc *balloc, void **pbuf, size_t n) {
balloc->head = hd;
ngtcp2_buf_init(
&balloc->buf,
(uint8_t *)(((uintptr_t)p + sizeof(ngtcp2_memblock_hd) + 0xfu) &
~(uintptr_t)0xfu),
(uint8_t *)(((uintptr_t)p + sizeof(ngtcp2_memblock_hd) + 0xFU) &
~(uintptr_t)0xFU),
balloc->blklen);
}
assert(((uintptr_t)balloc->buf.last & 0xfu) == 0);
assert(((uintptr_t)balloc->buf.last & 0xFU) == 0);
*pbuf = balloc->buf.last;
balloc->buf.last += (n + 0xfu) & ~(uintptr_t)0xfu;
balloc->buf.last += (n + 0xFU) & ~(uintptr_t)0xFU;
return 0;
}
+4 -1
View File
@@ -42,7 +42,7 @@ const ngtcp2_callbacks *ngtcp2_callbacks_convert_to_latest(
return src;
}
memset(dest, 0, sizeof(*dest));
*dest = (ngtcp2_callbacks){0};
callbacks_copy(dest, src, callbacks_version);
@@ -63,6 +63,9 @@ size_t ngtcp2_callbackslen_version(int callbacks_version) {
switch (callbacks_version) {
case NGTCP2_CALLBACKS_VERSION:
return sizeof(callbacks);
case NGTCP2_CALLBACKS_V2:
return offsetof(ngtcp2_callbacks, begin_path_validation) +
sizeof(callbacks.begin_path_validation);
case NGTCP2_CALLBACKS_V1:
return offsetof(ngtcp2_callbacks, tls_early_data_rejected) +
sizeof(callbacks.tls_early_data_rejected);
+16 -13
View File
@@ -29,8 +29,9 @@
#include "ngtcp2_path.h"
#include "ngtcp2_str.h"
#include "ngtcp2_pkt.h"
void ngtcp2_cid_zero(ngtcp2_cid *cid) { memset(cid, 0, sizeof(*cid)); }
void ngtcp2_cid_zero(ngtcp2_cid *cid) { *cid = (ngtcp2_cid){0}; }
void ngtcp2_cid_init(ngtcp2_cid *cid, const uint8_t *data, size_t datalen) {
assert(datalen <= NGTCP2_MAX_CIDLEN);
@@ -74,12 +75,12 @@ void ngtcp2_scid_copy(ngtcp2_scid *dest, const ngtcp2_scid *src) {
}
void ngtcp2_dcid_init(ngtcp2_dcid *dcid, uint64_t seq, const ngtcp2_cid *cid,
const uint8_t *token) {
const ngtcp2_stateless_reset_token *token) {
dcid->seq = seq;
dcid->cid = *cid;
if (token) {
memcpy(dcid->token, token, NGTCP2_STATELESS_RESET_TOKENLEN);
dcid->token = *token;
dcid->flags = NGTCP2_DCID_FLAG_TOKEN_PRESENT;
} else {
dcid->flags = NGTCP2_DCID_FLAG_NONE;
@@ -93,11 +94,12 @@ void ngtcp2_dcid_init(ngtcp2_dcid *dcid, uint64_t seq, const ngtcp2_cid *cid,
dcid->max_udp_payload_size = NGTCP2_MAX_UDP_PAYLOAD_SIZE;
}
void ngtcp2_dcid_set_token(ngtcp2_dcid *dcid, const uint8_t *token) {
void ngtcp2_dcid_set_token(ngtcp2_dcid *dcid,
const ngtcp2_stateless_reset_token *token) {
assert(token);
dcid->flags |= NGTCP2_DCID_FLAG_TOKEN_PRESENT;
memcpy(dcid->token, token, NGTCP2_STATELESS_RESET_TOKENLEN);
dcid->token = *token;
}
void ngtcp2_dcid_set_path(ngtcp2_dcid *dcid, const ngtcp2_path *path) {
@@ -106,7 +108,7 @@ void ngtcp2_dcid_set_path(ngtcp2_dcid *dcid, const ngtcp2_path *path) {
void ngtcp2_dcid_copy(ngtcp2_dcid *dest, const ngtcp2_dcid *src) {
ngtcp2_dcid_init(dest, src->seq, &src->cid,
(src->flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT) ? src->token
(src->flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT) ? &src->token
: NULL);
ngtcp2_path_copy(&dest->ps.path, &src->ps.path);
dest->retired_ts = src->retired_ts;
@@ -123,18 +125,19 @@ void ngtcp2_dcid_copy_cid_token(ngtcp2_dcid *dest, const ngtcp2_dcid *src) {
if (src->flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT) {
dest->flags |= NGTCP2_DCID_FLAG_TOKEN_PRESENT;
memcpy(dest->token, src->token, NGTCP2_STATELESS_RESET_TOKENLEN);
dest->token = src->token;
} else if (dest->flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT) {
dest->flags &= (uint8_t)~NGTCP2_DCID_FLAG_TOKEN_PRESENT;
}
}
int ngtcp2_dcid_verify_uniqueness(const ngtcp2_dcid *dcid, uint64_t seq,
const ngtcp2_cid *cid, const uint8_t *token) {
const ngtcp2_cid *cid,
const ngtcp2_stateless_reset_token *token) {
if (dcid->seq == seq) {
return ngtcp2_cid_eq(&dcid->cid, cid) &&
(dcid->flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT) &&
memcmp(dcid->token, token, NGTCP2_STATELESS_RESET_TOKENLEN) == 0
ngtcp2_stateless_reset_token_eq(&dcid->token, token)
? 0
: NGTCP2_ERR_PROTO;
}
@@ -142,12 +145,12 @@ int ngtcp2_dcid_verify_uniqueness(const ngtcp2_dcid *dcid, uint64_t seq,
return !ngtcp2_cid_eq(&dcid->cid, cid) ? 0 : NGTCP2_ERR_PROTO;
}
int ngtcp2_dcid_verify_stateless_reset_token(const ngtcp2_dcid *dcid,
const ngtcp2_path *path,
const uint8_t *token) {
int ngtcp2_dcid_verify_stateless_reset_token(
const ngtcp2_dcid *dcid, const ngtcp2_path *path,
const ngtcp2_stateless_reset_token *token) {
return ngtcp2_path_eq(&dcid->ps.path, path) &&
(dcid->flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT) &&
ngtcp2_cmemeq(dcid->token, token, NGTCP2_STATELESS_RESET_TOKENLEN)
ngtcp2_cmemeq(dcid->token.data, token->data, sizeof(token->data))
? 0
: NGTCP2_ERR_INVALID_ARGUMENT;
}
+18 -16
View File
@@ -35,13 +35,13 @@
#include "ngtcp2_path.h"
/* NGTCP2_SCID_FLAG_NONE indicates that no flag is set. */
#define NGTCP2_SCID_FLAG_NONE 0x00u
#define NGTCP2_SCID_FLAG_NONE 0x00U
/* NGTCP2_SCID_FLAG_USED indicates that a local endpoint observed that
a remote endpoint uses this particular Connection ID. */
#define NGTCP2_SCID_FLAG_USED 0x01u
#define NGTCP2_SCID_FLAG_USED 0x01U
/* NGTCP2_SCID_FLAG_RETIRED indicates that this particular Connection
ID is retired. */
#define NGTCP2_SCID_FLAG_RETIRED 0x02u
#define NGTCP2_SCID_FLAG_RETIRED 0x02U
typedef struct ngtcp2_scid {
ngtcp2_pq_entry pe;
@@ -57,13 +57,13 @@ typedef struct ngtcp2_scid {
} ngtcp2_scid;
/* NGTCP2_DCID_FLAG_NONE indicates that no flag is set. */
#define NGTCP2_DCID_FLAG_NONE 0x00u
#define NGTCP2_DCID_FLAG_NONE 0x00U
/* NGTCP2_DCID_FLAG_PATH_VALIDATED indicates that an associated path
has been validated. */
#define NGTCP2_DCID_FLAG_PATH_VALIDATED 0x01u
#define NGTCP2_DCID_FLAG_PATH_VALIDATED 0x01U
/* NGTCP2_DCID_FLAG_TOKEN_PRESENT indicates that a stateless reset
token is set in token field. */
#define NGTCP2_DCID_FLAG_TOKEN_PRESENT 0x02u
#define NGTCP2_DCID_FLAG_TOKEN_PRESENT 0x02U
typedef struct ngtcp2_dcid {
/* seq is the sequence number associated to the Connection ID. */
@@ -93,7 +93,7 @@ typedef struct ngtcp2_dcid {
/* token is a stateless reset token received along with this
Connection ID. The stateless reset token is tied to the
connection, not to the particular Connection ID. */
uint8_t token[NGTCP2_STATELESS_RESET_TOKENLEN];
ngtcp2_stateless_reset_token token;
} ngtcp2_dcid;
/* ngtcp2_cid_zero makes |cid| zero-length. */
@@ -123,17 +123,18 @@ void ngtcp2_scid_copy(ngtcp2_scid *dest, const ngtcp2_scid *src);
/*
* ngtcp2_dcid_init initializes |dcid| with the given parameters. If
* |token| is NULL, the function fills dcid->token with 0. |token|
* must be NGTCP2_STATELESS_RESET_TOKENLEN bytes long.
* |token| is not NULL, the function sets
* NGTCP2_DCID_FLAG_TOKEN_PRESENT flag.
*/
void ngtcp2_dcid_init(ngtcp2_dcid *dcid, uint64_t seq, const ngtcp2_cid *cid,
const uint8_t *token);
const ngtcp2_stateless_reset_token *token);
/*
* ngtcp2_dcid_set_token sets |token| to |dcid|. |token| must not be
* NULL, and must be NGTCP2_STATELESS_RESET_TOKENLEN bytes long.
* NULL.
*/
void ngtcp2_dcid_set_token(ngtcp2_dcid *dcid, const uint8_t *token);
void ngtcp2_dcid_set_token(ngtcp2_dcid *dcid,
const ngtcp2_stateless_reset_token *token);
/*
* ngtcp2_dcid_set_path sets |path| to |dcid|. It sets
@@ -160,7 +161,8 @@ void ngtcp2_dcid_copy_cid_token(ngtcp2_dcid *dest, const ngtcp2_dcid *src);
* |token|) tuple against |dcid|.
*/
int ngtcp2_dcid_verify_uniqueness(const ngtcp2_dcid *dcid, uint64_t seq,
const ngtcp2_cid *cid, const uint8_t *token);
const ngtcp2_cid *cid,
const ngtcp2_stateless_reset_token *token);
/*
* ngtcp2_dcid_verify_stateless_reset_token verifies stateless reset
@@ -172,9 +174,9 @@ int ngtcp2_dcid_verify_uniqueness(const ngtcp2_dcid *dcid, uint64_t seq,
* NGTCP2_ERR_INVALID_ARGUMENT
* Tokens do not match; or |dcid| does not contain a token.
*/
int ngtcp2_dcid_verify_stateless_reset_token(const ngtcp2_dcid *dcid,
const ngtcp2_path *path,
const uint8_t *token);
int ngtcp2_dcid_verify_stateless_reset_token(
const ngtcp2_dcid *dcid, const ngtcp2_path *path,
const ngtcp2_stateless_reset_token *token);
/* TODO It might be performance win if we store congestion state in
this entry, and restore it when migrate back to this path. */
+247 -133
View File
@@ -255,13 +255,20 @@ static int conn_call_extend_max_local_streams_uni(ngtcp2_conn *conn,
}
static int conn_call_get_new_connection_id(ngtcp2_conn *conn, ngtcp2_cid *cid,
uint8_t *token, size_t cidlen) {
ngtcp2_stateless_reset_token *token,
size_t cidlen) {
int rv;
assert(conn->callbacks.get_new_connection_id);
if (conn->callbacks.get_new_connection_id2) {
rv = conn->callbacks.get_new_connection_id2(conn, cid, token, cidlen,
conn->user_data);
} else {
assert(conn->callbacks.get_new_connection_id);
rv = conn->callbacks.get_new_connection_id(conn, cid, token->data, cidlen,
conn->user_data);
}
rv = conn->callbacks.get_new_connection_id(conn, cid, token, cidlen,
conn->user_data);
if (rv != 0) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
@@ -424,14 +431,20 @@ static int conn_call_dcid_status(ngtcp2_conn *conn,
const ngtcp2_dcid *dcid) {
int rv;
if (!conn->callbacks.dcid_status) {
if (conn->callbacks.dcid_status2) {
rv = conn->callbacks.dcid_status2(
conn, type, dcid->seq, &dcid->cid,
(dcid->flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT) ? &dcid->token : NULL,
conn->user_data);
} else if (conn->callbacks.dcid_status) {
rv = conn->callbacks.dcid_status(
conn, type, dcid->seq, &dcid->cid,
(dcid->flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT) ? dcid->token.data : NULL,
conn->user_data);
} else {
return 0;
}
rv = conn->callbacks.dcid_status(
conn, type, dcid->seq, &dcid->cid,
(dcid->flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT) ? dcid->token : NULL,
conn->user_data);
if (rv != 0) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
@@ -504,12 +517,19 @@ static int conn_call_client_initial(ngtcp2_conn *conn) {
return 0;
}
static int conn_call_get_path_challenge_data(ngtcp2_conn *conn, uint8_t *data) {
static int conn_call_get_path_challenge_data(ngtcp2_conn *conn,
ngtcp2_path_challenge_data *data) {
int rv;
assert(conn->callbacks.get_path_challenge_data);
if (conn->callbacks.get_path_challenge_data2) {
rv = conn->callbacks.get_path_challenge_data2(conn, data, conn->user_data);
} else {
assert(conn->callbacks.get_path_challenge_data);
rv = conn->callbacks.get_path_challenge_data(conn, data->data,
conn->user_data);
}
rv = conn->callbacks.get_path_challenge_data(conn, data, conn->user_data);
if (rv != 0) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
@@ -550,14 +570,24 @@ static int conn_call_recv_retry(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd) {
static int
conn_call_recv_stateless_reset(ngtcp2_conn *conn,
const ngtcp2_pkt_stateless_reset *sr) {
const ngtcp2_pkt_stateless_reset2 *sr) {
int rv;
ngtcp2_pkt_stateless_reset legacy_sr;
if (!conn->callbacks.recv_stateless_reset) {
if (conn->callbacks.recv_stateless_reset2) {
rv = conn->callbacks.recv_stateless_reset2(conn, sr, conn->user_data);
} else if (conn->callbacks.recv_stateless_reset) {
memcpy(legacy_sr.stateless_reset_token, sr->token.data,
sizeof(legacy_sr.stateless_reset_token));
legacy_sr.rand = sr->rand;
legacy_sr.randlen = sr->randlen;
rv =
conn->callbacks.recv_stateless_reset(conn, &legacy_sr, conn->user_data);
} else {
return 0;
}
rv = conn->callbacks.recv_stateless_reset(conn, sr, conn->user_data);
if (rv != 0) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
@@ -840,8 +870,8 @@ static void conn_reset_conn_stat_cc(ngtcp2_conn *conn,
*/
static void reset_conn_stat_recovery(ngtcp2_conn_stat *cstat) {
/* Initializes them with UINT64_MAX. */
memset(cstat->loss_time, 0xff, sizeof(cstat->loss_time));
memset(cstat->last_tx_pkt_ts, 0xff, sizeof(cstat->last_tx_pkt_ts));
memset(cstat->loss_time, 0xFF, sizeof(cstat->loss_time));
memset(cstat->last_tx_pkt_ts, 0xFF, sizeof(cstat->last_tx_pkt_ts));
}
/*
@@ -1072,13 +1102,13 @@ static void conn_update_skip_pkt(ngtcp2_conn *conn, ngtcp2_pktns *pktns) {
conn->callbacks.rand(&r, 1, &conn->local.settings.rand_ctx);
if (1ll << pktns->tx.skip_pkt.exponent >
if (1LL << pktns->tx.skip_pkt.exponent >
(NGTCP2_MAX_PKT_NUM - min_gap) / ((int64_t)r + 1)) {
pktns->tx.skip_pkt.next_pkt_num = INT64_MAX;
return;
}
gap = ((int64_t)r + 1) * (1ll << pktns->tx.skip_pkt.exponent++) + min_gap;
gap = ((int64_t)r + 1) * (1LL << pktns->tx.skip_pkt.exponent++) + min_gap;
if (pktns->tx.last_pkt_num > NGTCP2_MAX_PKT_NUM - gap) {
pktns->tx.skip_pkt.next_pkt_num = INT64_MAX;
@@ -1196,11 +1226,12 @@ static int conn_new(ngtcp2_conn **pconn, const ngtcp2_cid *dcid,
assert(callbacks->hp_mask);
assert(server || callbacks->recv_retry);
assert(callbacks->rand);
assert(callbacks->get_new_connection_id);
assert(callbacks->get_new_connection_id2 || callbacks->get_new_connection_id);
assert(callbacks->update_key);
assert(callbacks->delete_crypto_aead_ctx);
assert(callbacks->delete_crypto_cipher_ctx);
assert(callbacks->get_path_challenge_data);
assert(callbacks->get_path_challenge_data2 ||
callbacks->get_path_challenge_data);
assert(!server || !ngtcp2_is_reserved_version(client_chosen_version));
for (i = 0; i < settings->pmtud_probeslen; ++i) {
@@ -1860,13 +1891,13 @@ static size_t pktns_select_pkt_numlen(ngtcp2_pktns *pktns) {
n = n * 2 - 1;
if (n > 0xffffff) {
if (n > 0xFFFFFF) {
return 4;
}
if (n > 0xffff) {
if (n > 0xFFFF) {
return 3;
}
if (n > 0xff) {
if (n > 0xFF) {
return 2;
}
return 1;
@@ -1974,6 +2005,16 @@ static int conn_verify_dcid(ngtcp2_conn *conn, int *pnew_cid_used,
return 0;
}
static int conn_can_send_next_pkt(ngtcp2_conn *conn, size_t left,
uint64_t min_payloadlen) {
/* TODO the next packet type should be taken into account */
return left >=
/* TODO Assuming that pkt_num is encoded in 1 byte. */
NGTCP2_MIN_LONG_HEADERLEN + conn->dcid.current.cid.datalen +
conn->oscid.datalen + NGTCP2_PKT_LENGTHLEN - 1 + min_payloadlen +
NGTCP2_MAX_AEAD_OVERHEAD;
}
/*
* conn_should_pad_pkt returns nonzero if the packet should be padded.
* |type| is the type of packet. |left| is the space left in packet
@@ -2020,32 +2061,30 @@ static int conn_should_pad_pkt(ngtcp2_conn *conn, uint8_t type, size_t left,
return 1;
}
}
} else {
assert(type == NGTCP2_PKT_HANDSHAKE);
if (!require_padding) {
return 0;
}
if (!conn->pktns.crypto.tx.ckm) {
return 1;
}
/* We might send Handshake packet even if exceeding CWND. In that
case, we do not write non-probe 1RTT packet. */
if (conn_cwnd_is_zero(conn) && conn->pktns.rtb.probe_pkt_left == 0) {
return 1;
}
min_payloadlen = NGTCP2_MIN_COALESCED_PAYLOADLEN;
return !conn_can_send_next_pkt(conn, left, min_payloadlen);
}
/* TODO the next packet type should be taken into account */
return left <
/* TODO Assuming that pkt_num is encoded in 1 byte. */
NGTCP2_MIN_LONG_HEADERLEN + conn->dcid.current.cid.datalen +
conn->oscid.datalen + NGTCP2_PKT_LENGTHLEN - 1 + min_payloadlen +
NGTCP2_MAX_AEAD_OVERHEAD;
assert(type == NGTCP2_PKT_HANDSHAKE);
if (!require_padding) {
/* If we have 1RTT key, pad this Handshake packet so that the next
1RTT packet can be squeezed into the same GSO buffer. */
return conn->pktns.crypto.tx.ckm &&
!conn_can_send_next_pkt(conn, left, NGTCP2_MIN_COALESCED_PAYLOADLEN);
}
if (!conn->pktns.crypto.tx.ckm) {
return 1;
}
/* We might send Handshake packet even if exceeding CWND. In that
case, we do not write non-probe 1RTT packet. */
if (conn_cwnd_is_zero(conn) && conn->pktns.rtb.probe_pkt_left == 0) {
return 1;
}
return !conn_can_send_next_pkt(conn, left, NGTCP2_MIN_COALESCED_PAYLOADLEN);
}
static void conn_restart_timer_on_write(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
@@ -2888,7 +2927,7 @@ static void conn_discard_early_key(ngtcp2_conn *conn) {
conn_call_delete_crypto_aead_ctx(conn, &conn->early.ckm->aead_ctx);
conn_call_delete_crypto_cipher_ctx(conn, &conn->early.hp_ctx);
memset(&conn->early.hp_ctx, 0, sizeof(conn->early.hp_ctx));
conn->early.hp_ctx = (ngtcp2_crypto_cipher_ctx){0};
ngtcp2_crypto_km_del(conn->early.ckm, conn->mem);
conn->early.ckm = NULL;
@@ -3205,58 +3244,59 @@ static size_t conn_required_num_new_connection_id(ngtcp2_conn *conn) {
static int conn_enqueue_new_connection_id(ngtcp2_conn *conn) {
size_t i, need = conn_required_num_new_connection_id(conn);
size_t cidlen = conn->oscid.datalen;
ngtcp2_cid cid;
uint64_t seq;
int rv;
uint8_t token[NGTCP2_STATELESS_RESET_TOKENLEN];
ngtcp2_frame_chain *nfrc;
ngtcp2_pktns *pktns = &conn->pktns;
ngtcp2_scid *scid;
ngtcp2_ksl_it it;
for (i = 0; i < need; ++i) {
rv = conn_call_get_new_connection_id(conn, &cid, token, cidlen);
if (rv != 0) {
return rv;
}
if (cid.datalen != cidlen) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
/* Assert uniqueness */
it = ngtcp2_ksl_lower_bound(&conn->scid.set, &cid);
if (!ngtcp2_ksl_it_end(&it) &&
ngtcp2_cid_eq(ngtcp2_ksl_it_key(&it), &cid)) {
return NGTCP2_ERR_CALLBACK_FAILURE;
}
seq = ++conn->scid.last_seq;
scid = ngtcp2_mem_malloc(conn->mem, sizeof(*scid));
if (scid == NULL) {
return NGTCP2_ERR_NOMEM;
}
ngtcp2_scid_init(scid, seq, &cid);
rv = ngtcp2_ksl_insert(&conn->scid.set, NULL, &scid->cid, scid);
if (rv != 0) {
ngtcp2_mem_free(conn->mem, scid);
return rv;
}
rv = ngtcp2_frame_chain_objalloc_new(&nfrc, &conn->frc_objalloc);
if (rv != 0) {
return rv;
}
nfrc->fr.new_connection_id.type = NGTCP2_FRAME_NEW_CONNECTION_ID;
nfrc->fr.new_connection_id.seq = seq;
nfrc->fr.new_connection_id.seq = ++conn->scid.last_seq;
nfrc->fr.new_connection_id.retire_prior_to = 0;
nfrc->fr.new_connection_id.cid = cid;
memcpy(nfrc->fr.new_connection_id.stateless_reset_token, token,
sizeof(token));
rv = conn_call_get_new_connection_id(conn, &nfrc->fr.new_connection_id.cid,
&nfrc->fr.new_connection_id.token,
cidlen);
if (rv != 0) {
goto fail;
}
if (nfrc->fr.new_connection_id.cid.datalen != cidlen) {
rv = NGTCP2_ERR_CALLBACK_FAILURE;
goto fail;
}
/* Assert uniqueness */
it =
ngtcp2_ksl_lower_bound(&conn->scid.set, &nfrc->fr.new_connection_id.cid);
if (!ngtcp2_ksl_it_end(&it) &&
ngtcp2_cid_eq(ngtcp2_ksl_it_key(&it),
&nfrc->fr.new_connection_id.cid)) {
rv = NGTCP2_ERR_CALLBACK_FAILURE;
goto fail;
}
scid = ngtcp2_mem_malloc(conn->mem, sizeof(*scid));
if (scid == NULL) {
rv = NGTCP2_ERR_NOMEM;
goto fail;
}
ngtcp2_scid_init(scid, nfrc->fr.new_connection_id.seq,
&nfrc->fr.new_connection_id.cid);
rv = ngtcp2_ksl_insert(&conn->scid.set, NULL, &scid->cid, scid);
if (rv != 0) {
ngtcp2_mem_free(conn->mem, scid);
goto fail;
}
nfrc->next = pktns->tx.frq;
pktns->tx.frq = nfrc;
@@ -3266,6 +3306,11 @@ static int conn_enqueue_new_connection_id(ngtcp2_conn *conn) {
}
return 0;
fail:
ngtcp2_frame_chain_objalloc_del(nfrc, &conn->frc_objalloc, conn->mem);
return rv;
}
static int dcidtr_on_deactivate(const ngtcp2_dcid *dcid, void *user_data) {
@@ -3605,9 +3650,10 @@ static ngtcp2_ssize conn_write_pkt(ngtcp2_conn *conn, ngtcp2_pkt_info *pi,
/* PATH_RESPONSE is bound to the path that the corresponding
PATH_CHALLENGE is received. */
if (ngtcp2_path_eq(&conn->dcid.current.ps.path, &pcent->ps.path)) {
lfr.path_response.type = NGTCP2_FRAME_PATH_RESPONSE;
memcpy(lfr.path_response.data, pcent->data,
sizeof(lfr.path_response.data));
lfr.path_response = (ngtcp2_path_response){
.type = NGTCP2_FRAME_PATH_RESPONSE,
.data = pcent->data,
};
rv = conn_ppe_write_frame_hd_log(conn, ppe, &hd_logged, hd, &lfr);
if (rv != 0) {
@@ -5121,7 +5167,7 @@ static ngtcp2_ssize conn_write_path_challenge(ngtcp2_conn *conn,
return 0;
}
rv = conn_call_get_path_challenge_data(conn, lfr.path_challenge.data);
rv = conn_call_get_path_challenge_data(conn, &lfr.path_challenge.data);
if (rv != 0) {
return rv;
}
@@ -5153,7 +5199,7 @@ static ngtcp2_ssize conn_write_path_challenge(ngtcp2_conn *conn,
flags = NGTCP2_PV_ENTRY_FLAG_NONE;
}
ngtcp2_pv_add_entry(pv, lfr.path_challenge.data, expiry, flags, ts);
ngtcp2_pv_add_entry(pv, &lfr.path_challenge.data, expiry, flags, ts);
nwrite = ngtcp2_conn_write_single_frame_pkt(
conn, pi, dest, destlen, NGTCP2_PKT_1RTT, NGTCP2_WRITE_PKT_FLAG_NONE,
@@ -5259,8 +5305,10 @@ static ngtcp2_ssize conn_write_path_response(ngtcp2_conn *conn,
}
}
lfr.path_response.type = NGTCP2_FRAME_PATH_RESPONSE;
memcpy(lfr.path_response.data, pcent->data, sizeof(lfr.path_response.data));
lfr.path_response = (ngtcp2_path_response){
.type = NGTCP2_FRAME_PATH_RESPONSE,
.data = pcent->data,
};
nwrite = ngtcp2_conn_write_single_frame_pkt(
conn, pi, dest, destlen, NGTCP2_PKT_1RTT, NGTCP2_WRITE_PKT_FLAG_NONE,
@@ -5877,9 +5925,9 @@ decrypt_hp(ngtcp2_pkt_hd *hd, uint8_t *dest, const ngtcp2_crypto_cipher *hp,
}
if (hd->flags & NGTCP2_PKT_FLAG_LONG_FORM) {
dest[0] = (uint8_t)(dest[0] ^ (mask[0] & 0x0f));
dest[0] = (uint8_t)(dest[0] ^ (mask[0] & 0x0F));
} else {
dest[0] = (uint8_t)(dest[0] ^ (mask[0] & 0x1f));
dest[0] = (uint8_t)(dest[0] ^ (mask[0] & 0x1F));
if (dest[0] & NGTCP2_SHORT_KEY_PHASE_BIT) {
hd->flags |= NGTCP2_PKT_FLAG_KEY_PHASE;
}
@@ -5994,7 +6042,7 @@ static void conn_recv_path_challenge(ngtcp2_conn *conn, const ngtcp2_path *path,
}
ent = ngtcp2_ringbuf_push_front(&conn->rx.path_challenge.rb);
ngtcp2_path_challenge_entry_init(ent, path, fr->data);
ngtcp2_path_challenge_entry_init(ent, path, &fr->data);
}
/*
@@ -6064,7 +6112,7 @@ static int conn_recv_path_response(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
return 0;
}
rv = ngtcp2_pv_validate(pv, &ent_flags, fr->data);
rv = ngtcp2_pv_validate(pv, &ent_flags, &fr->data);
if (rv != 0) {
assert(!ngtcp2_err_is_fatal(rv));
@@ -6947,6 +6995,10 @@ static ngtcp2_ssize conn_recv_handshake_cpkt(ngtcp2_conn *conn,
const uint8_t *origpkt = pkt;
uint32_t version;
if (pktlen == 0) {
return 0;
}
if (ngtcp2_path_eq(&conn->dcid.current.ps.path, path)) {
conn->dcid.current.bytes_recv += dgramlen;
}
@@ -7882,9 +7934,8 @@ static int conn_recv_stop_sending(ngtcp2_conn *conn,
*/
static int check_stateless_reset(const ngtcp2_dcid *dcid,
const ngtcp2_path *path,
const ngtcp2_pkt_stateless_reset *sr) {
return ngtcp2_dcid_verify_stateless_reset_token(
dcid, path, sr->stateless_reset_token) == 0;
const ngtcp2_pkt_stateless_reset2 *sr) {
return ngtcp2_dcid_verify_stateless_reset_token(dcid, path, &sr->token) == 0;
}
/*
@@ -7908,7 +7959,7 @@ static int conn_on_stateless_reset(ngtcp2_conn *conn, const ngtcp2_path *path,
const uint8_t *payload, size_t payloadlen) {
int rv;
ngtcp2_pv *pv = conn->pv;
ngtcp2_pkt_stateless_reset sr;
ngtcp2_pkt_stateless_reset2 sr;
rv = ngtcp2_pkt_decode_stateless_reset(&sr, payload, payloadlen);
if (rv != 0) {
@@ -7919,8 +7970,7 @@ static int conn_on_stateless_reset(ngtcp2_conn *conn, const ngtcp2_path *path,
(!pv || (!check_stateless_reset(&pv->dcid, path, &sr) &&
(!(pv->flags & NGTCP2_PV_FLAG_FALLBACK_PRESENT) ||
!check_stateless_reset(&pv->fallback_dcid, path, &sr))))) {
rv = ngtcp2_dcidtr_verify_stateless_reset(&conn->dcid.dtr, path,
sr.stateless_reset_token);
rv = ngtcp2_dcidtr_verify_stateless_reset(&conn->dcid.dtr, path, &sr.token);
if (rv != 0) {
return rv;
}
@@ -8000,7 +8050,7 @@ static int conn_recv_new_connection_id(ngtcp2_conn *conn,
}
rv = ngtcp2_dcid_verify_uniqueness(&conn->dcid.current, fr->seq, &fr->cid,
fr->stateless_reset_token);
&fr->token);
if (rv != 0) {
return rv;
}
@@ -8009,8 +8059,8 @@ static int conn_recv_new_connection_id(ngtcp2_conn *conn,
}
if (pv) {
rv = ngtcp2_dcid_verify_uniqueness(&pv->dcid, fr->seq, &fr->cid,
fr->stateless_reset_token);
rv =
ngtcp2_dcid_verify_uniqueness(&pv->dcid, fr->seq, &fr->cid, &fr->token);
if (rv != 0) {
return rv;
}
@@ -8019,8 +8069,8 @@ static int conn_recv_new_connection_id(ngtcp2_conn *conn,
}
}
rv = ngtcp2_dcidtr_verify_token_uniqueness(
&conn->dcid.dtr, &found, fr->seq, &fr->cid, fr->stateless_reset_token);
rv = ngtcp2_dcidtr_verify_token_uniqueness(&conn->dcid.dtr, &found, fr->seq,
&fr->cid, &fr->token);
if (rv != 0) {
return rv;
}
@@ -8098,8 +8148,7 @@ static int conn_recv_new_connection_id(ngtcp2_conn *conn,
return 0;
}
ngtcp2_dcidtr_push_unused(&conn->dcid.dtr, fr->seq, &fr->cid,
fr->stateless_reset_token);
ngtcp2_dcidtr_push_unused(&conn->dcid.dtr, fr->seq, &fr->cid, &fr->token);
return 0;
}
@@ -10305,6 +10354,49 @@ int ngtcp2_conn_read_pkt_versioned(ngtcp2_conn *conn, const ngtcp2_path *path,
return conn_recv_cpkt(conn, path, pi, pkt, pktlen, ts);
}
int ngtcp2_conn_continue_handshake(ngtcp2_conn *conn, ngtcp2_tstamp ts) {
int rv;
ngtcp2_encryption_level encryption_level;
uint64_t offset;
conn_update_timestamp(conn, ts);
switch (conn->state) {
case NGTCP2_CS_CLIENT_INITIAL:
case NGTCP2_CS_CLIENT_WAIT_HANDSHAKE:
case NGTCP2_CS_SERVER_INITIAL:
case NGTCP2_CS_SERVER_WAIT_HANDSHAKE:
/* Most of the handshake interruption happens in Initial
encryption level, but this might not be the case depending on
the TLS stack and its functionality and where interruption
occurs. After all, we do not need to support all kinds of
interruptions. */
if (conn->in_pktns) {
encryption_level = NGTCP2_ENCRYPTION_LEVEL_INITIAL;
offset = ngtcp2_strm_rx_offset(&conn->in_pktns->crypto.strm);
} else if (conn->hs_pktns) {
encryption_level = NGTCP2_ENCRYPTION_LEVEL_HANDSHAKE;
offset = ngtcp2_strm_rx_offset(&conn->hs_pktns->crypto.strm);
} else {
return 0;
}
rv = conn_call_recv_crypto_data(conn, encryption_level, offset, NULL, 0);
if (rv != 0) {
return rv;
}
return (int)conn_read_handshake(conn, /* path = */ NULL, /* pi = */ NULL,
/* pkt = */ NULL, 0, ts);
case NGTCP2_CS_CLOSING:
return NGTCP2_ERR_CLOSING;
case NGTCP2_CS_DRAINING:
return NGTCP2_ERR_DRAINING;
default:
return 0;
}
}
/*
* conn_check_pkt_num_exhausted returns nonzero if packet number is
* exhausted in at least one of packet number space.
@@ -10406,6 +10498,7 @@ static ngtcp2_ssize conn_write_handshake(ngtcp2_conn *conn, ngtcp2_pkt_info *pi,
size_t origlen = destlen;
uint64_t pending_early_datalen;
ngtcp2_preferred_addr *paddr;
ngtcp2_stateless_reset_token token;
switch (conn->state) {
case NGTCP2_CS_CLIENT_INITIAL:
@@ -10533,8 +10626,8 @@ static ngtcp2_ssize conn_write_handshake(ngtcp2_conn *conn, ngtcp2_pkt_info *pi,
assert(!ngtcp2_dcidtr_unused_full(&conn->dcid.dtr));
paddr = &conn->remote.transport_params->preferred_addr;
ngtcp2_dcidtr_push_unused(&conn->dcid.dtr, 1, &paddr->cid,
paddr->stateless_reset_token);
memcpy(token.data, paddr->stateless_reset_token, sizeof(token.data));
ngtcp2_dcidtr_push_unused(&conn->dcid.dtr, 1, &paddr->cid, &token);
rv = ngtcp2_gaptr_push(&conn->dcid.seqgap, 1, 1);
if (rv != 0) {
@@ -10542,12 +10635,12 @@ static ngtcp2_ssize conn_write_handshake(ngtcp2_conn *conn, ngtcp2_pkt_info *pi,
}
}
if (conn->remote.transport_params->stateless_reset_token_present) {
assert(conn->dcid.current.seq == 0);
if (conn->remote.transport_params->stateless_reset_token_present &&
conn->dcid.current.seq == 0) {
assert(!(conn->dcid.current.flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT));
ngtcp2_dcid_set_token(
&conn->dcid.current,
conn->remote.transport_params->stateless_reset_token);
memcpy(token.data, conn->remote.transport_params->stateless_reset_token,
sizeof(token.data));
ngtcp2_dcid_set_token(&conn->dcid.current, &token);
}
rv = conn_call_activate_dcid(conn, &conn->dcid.current);
@@ -10923,8 +11016,7 @@ int ngtcp2_conn_install_rx_handshake_key(
if (rv != 0) {
ngtcp2_crypto_km_del(pktns->crypto.rx.ckm, conn->mem);
pktns->crypto.rx.ckm = NULL;
memset(&pktns->crypto.rx.hp_ctx, 0, sizeof(pktns->crypto.rx.hp_ctx));
pktns->crypto.rx.hp_ctx = (ngtcp2_crypto_cipher_ctx){0};
return rv;
}
@@ -10971,8 +11063,7 @@ fail:
to them. */
ngtcp2_crypto_km_del(pktns->crypto.tx.ckm, conn->mem);
pktns->crypto.tx.ckm = NULL;
memset(&pktns->crypto.tx.hp_ctx, 0, sizeof(pktns->crypto.tx.hp_ctx));
pktns->crypto.tx.hp_ctx = (ngtcp2_crypto_cipher_ctx){0};
return rv;
}
@@ -11005,8 +11096,7 @@ int ngtcp2_conn_install_0rtt_key(ngtcp2_conn *conn,
if (rv != 0) {
ngtcp2_crypto_km_del(conn->early.ckm, conn->mem);
conn->early.ckm = NULL;
memset(&conn->early.hp_ctx, 0, sizeof(conn->early.hp_ctx));
conn->early.hp_ctx = (ngtcp2_crypto_cipher_ctx){0};
return rv;
}
@@ -11053,8 +11143,7 @@ int ngtcp2_conn_install_rx_key(ngtcp2_conn *conn, const uint8_t *secret,
if (rv != 0) {
ngtcp2_crypto_km_del(pktns->crypto.rx.ckm, conn->mem);
pktns->crypto.rx.ckm = NULL;
memset(&pktns->crypto.rx.hp_ctx, 0, sizeof(pktns->crypto.rx.hp_ctx));
pktns->crypto.rx.hp_ctx = (ngtcp2_crypto_cipher_ctx){0};
return rv;
}
@@ -11099,8 +11188,7 @@ int ngtcp2_conn_install_tx_key(ngtcp2_conn *conn, const uint8_t *secret,
if (rv != 0) {
ngtcp2_crypto_km_del(pktns->crypto.tx.ckm, conn->mem);
pktns->crypto.tx.ckm = NULL;
memset(&pktns->crypto.tx.hp_ctx, 0, sizeof(pktns->crypto.tx.hp_ctx));
pktns->crypto.tx.hp_ctx = (ngtcp2_crypto_cipher_ctx){0};
return rv;
}
@@ -13485,20 +13573,46 @@ static size_t conn_get_num_active_dcid(ngtcp2_conn *conn) {
return n;
}
static void copy_dcid_to_cid_token(ngtcp2_cid_token *dest,
size_t ngtcp2_conn_get_active_dcid(ngtcp2_conn *conn, ngtcp2_cid_token *dest) {
ngtcp2_cid_token2 cid_tokens[/* current */ 1 + /* pv */ 2 +
NGTCP2_DCIDTR_MAX_RETIRED_DCID_SIZE];
size_t n, i;
if (!dest) {
return ngtcp2_conn_get_active_dcid2(conn, NULL);
}
n = ngtcp2_conn_get_active_dcid2(conn, cid_tokens);
for (i = 0; i < n; ++i) {
dest[i].seq = cid_tokens[i].seq;
dest[i].cid = cid_tokens[i].cid;
ngtcp2_path_storage_init2(&dest[i].ps, &cid_tokens[i].ps.path);
dest[i].token_present = cid_tokens[i].token_present;
if (dest[i].token_present) {
memcpy(dest[i].token, cid_tokens[i].token.data, sizeof(dest[i].token));
}
}
return n;
}
static void copy_dcid_to_cid_token(ngtcp2_cid_token2 *dest,
const ngtcp2_dcid *src) {
dest->seq = src->seq;
dest->cid = src->cid;
ngtcp2_path_storage_init2(&dest->ps, &src->ps.path);
if ((dest->token_present =
(src->flags & NGTCP2_DCID_FLAG_TOKEN_PRESENT) != 0)) {
memcpy(dest->token, src->token, NGTCP2_STATELESS_RESET_TOKENLEN);
dest->token = src->token;
}
}
size_t ngtcp2_conn_get_active_dcid(ngtcp2_conn *conn, ngtcp2_cid_token *dest) {
size_t ngtcp2_conn_get_active_dcid2(ngtcp2_conn *conn,
ngtcp2_cid_token2 *dest) {
ngtcp2_pv *pv = conn->pv;
ngtcp2_cid_token *orig = dest;
ngtcp2_cid_token2 *orig = dest;
ngtcp2_dcid *dcid;
size_t len, i;
@@ -14068,9 +14182,9 @@ ngtcp2_conn_find_path_history(ngtcp2_conn *conn, const ngtcp2_path *path,
void ngtcp2_path_challenge_entry_init(ngtcp2_path_challenge_entry *pcent,
const ngtcp2_path *path,
const uint8_t *data) {
const ngtcp2_path_challenge_data *data) {
ngtcp2_path_storage_init2(&pcent->ps, path);
memcpy(pcent->data, data, sizeof(pcent->data));
pcent->data = *data;
}
/* The functions prefixed with ngtcp2_pkt_ are usually put inside
+30 -30
View File
@@ -94,35 +94,35 @@ typedef enum {
#define NGTCP2_CCERR_MAX_REASONLEN 1024
/* NGTCP2_WRITE_PKT_FLAG_NONE indicates that no flag is set. */
#define NGTCP2_WRITE_PKT_FLAG_NONE 0x00u
#define NGTCP2_WRITE_PKT_FLAG_NONE 0x00U
/* NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING indicates that packet other
than Initial packet should be padded so that UDP datagram payload
is at least NGTCP2_MAX_UDP_PAYLOAD_SIZE bytes. Initial packet
might be padded based on QUIC requirement regardless of this
flag. */
#define NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING 0x01u
#define NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING 0x01U
/* NGTCP2_WRITE_PKT_FLAG_MORE indicates that more frames might come
and it should be encoded into the current packet. */
#define NGTCP2_WRITE_PKT_FLAG_MORE 0x02u
#define NGTCP2_WRITE_PKT_FLAG_MORE 0x02U
/* NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING_FULL is just like
NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING, but it requests to add
padding to the full UDP datagram payload size. */
#define NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING_FULL 0x04u
#define NGTCP2_WRITE_PKT_FLAG_REQUIRE_PADDING_FULL 0x04U
/* NGTCP2_WRITE_PKT_FLAG_PADDING_IF_NOT_EMPTY adds padding to the QUIC
packet as much as possible if the packet is not empty. */
#define NGTCP2_WRITE_PKT_FLAG_PADDING_IF_NOT_EMPTY 0x08u
#define NGTCP2_WRITE_PKT_FLAG_PADDING_IF_NOT_EMPTY 0x08U
typedef struct ngtcp2_path_challenge_entry {
ngtcp2_path_storage ps;
uint8_t data[NGTCP2_PATH_CHALLENGE_DATALEN];
ngtcp2_path_challenge_data data;
} ngtcp2_path_challenge_entry;
void ngtcp2_path_challenge_entry_init(ngtcp2_path_challenge_entry *pcent,
const ngtcp2_path *path,
const uint8_t *data);
const ngtcp2_path_challenge_data *data);
/* NGTCP2_CONN_FLAG_NONE indicates that no flag is set. */
#define NGTCP2_CONN_FLAG_NONE 0x00u
#define NGTCP2_CONN_FLAG_NONE 0x00U
/* NGTCP2_CONN_FLAG_TLS_HANDSHAKE_COMPLETED is set when TLS stack
declares that TLS handshake has completed. The condition of this
declaration varies between TLS implementations and this flag does
@@ -130,69 +130,69 @@ void ngtcp2_path_challenge_entry_init(ngtcp2_path_challenge_entry *pcent,
implementations declare TLS handshake completion as server when
they write off Server Finished and before deriving application rx
secret. */
#define NGTCP2_CONN_FLAG_TLS_HANDSHAKE_COMPLETED 0x01u
#define NGTCP2_CONN_FLAG_TLS_HANDSHAKE_COMPLETED 0x01U
/* NGTCP2_CONN_FLAG_INITIAL_PKT_PROCESSED is set when the first
Initial packet has successfully been processed. */
#define NGTCP2_CONN_FLAG_INITIAL_PKT_PROCESSED 0x02u
#define NGTCP2_CONN_FLAG_INITIAL_PKT_PROCESSED 0x02U
/* NGTCP2_CONN_FLAG_TRANSPORT_PARAM_RECVED is set if transport
parameters are received. */
#define NGTCP2_CONN_FLAG_TRANSPORT_PARAM_RECVED 0x04u
#define NGTCP2_CONN_FLAG_TRANSPORT_PARAM_RECVED 0x04U
/* NGTCP2_CONN_FLAG_LOCAL_TRANSPORT_PARAMS_COMMITTED is set when a
local transport parameters are applied. */
#define NGTCP2_CONN_FLAG_LOCAL_TRANSPORT_PARAMS_COMMITTED 0x08u
#define NGTCP2_CONN_FLAG_LOCAL_TRANSPORT_PARAMS_COMMITTED 0x08U
/* NGTCP2_CONN_FLAG_RECV_RETRY is set when a client receives Retry
packet. */
#define NGTCP2_CONN_FLAG_RECV_RETRY 0x10u
#define NGTCP2_CONN_FLAG_RECV_RETRY 0x10U
/* NGTCP2_CONN_FLAG_EARLY_DATA_REJECTED is set when 0-RTT packet is
rejected by a peer. */
#define NGTCP2_CONN_FLAG_EARLY_DATA_REJECTED 0x20u
#define NGTCP2_CONN_FLAG_EARLY_DATA_REJECTED 0x20U
/* NGTCP2_CONN_FLAG_KEEP_ALIVE_CANCELLED is set when the expired
keep-alive timer has been cancelled. */
#define NGTCP2_CONN_FLAG_KEEP_ALIVE_CANCELLED 0x40u
#define NGTCP2_CONN_FLAG_KEEP_ALIVE_CANCELLED 0x40U
/* NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED is set when an endpoint
confirmed completion of handshake. */
#define NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED 0x80u
#define NGTCP2_CONN_FLAG_HANDSHAKE_CONFIRMED 0x80U
/* NGTCP2_CONN_FLAG_HANDSHAKE_COMPLETED is set when the library
transitions its state to "post handshake". */
#define NGTCP2_CONN_FLAG_HANDSHAKE_COMPLETED 0x0100u
#define NGTCP2_CONN_FLAG_HANDSHAKE_COMPLETED 0x0100U
/* NGTCP2_CONN_FLAG_HANDSHAKE_EARLY_RETRANSMIT is set when the early
handshake retransmission has done when server receives overlapping
Initial crypto data. */
#define NGTCP2_CONN_FLAG_HANDSHAKE_EARLY_RETRANSMIT 0x0200u
#define NGTCP2_CONN_FLAG_HANDSHAKE_EARLY_RETRANSMIT 0x0200U
/* NGTCP2_CONN_FLAG_CLEAR_FIXED_BIT indicates that the local endpoint
sends a QUIC packet without Fixed Bit set if a remote endpoint
supports Greasing QUIC Bit extension. */
#define NGTCP2_CONN_FLAG_CLEAR_FIXED_BIT 0x0400u
#define NGTCP2_CONN_FLAG_CLEAR_FIXED_BIT 0x0400U
/* NGTCP2_CONN_FLAG_KEY_UPDATE_NOT_CONFIRMED is set when key update is
not confirmed by the local endpoint. That is, it has not received
ACK frame which acknowledges packet which is encrypted with new
key. */
#define NGTCP2_CONN_FLAG_KEY_UPDATE_NOT_CONFIRMED 0x0800u
#define NGTCP2_CONN_FLAG_KEY_UPDATE_NOT_CONFIRMED 0x0800U
/* NGTCP2_CONN_FLAG_PPE_PENDING is set when
NGTCP2_WRITE_STREAM_FLAG_MORE is used and the intermediate state of
ngtcp2_ppe is stored in pkt struct of ngtcp2_conn. */
#define NGTCP2_CONN_FLAG_PPE_PENDING 0x1000u
#define NGTCP2_CONN_FLAG_PPE_PENDING 0x1000U
/* NGTCP2_CONN_FLAG_RESTART_IDLE_TIMER_ON_WRITE is set when idle timer
should be restarted on next write. */
#define NGTCP2_CONN_FLAG_RESTART_IDLE_TIMER_ON_WRITE 0x2000u
#define NGTCP2_CONN_FLAG_RESTART_IDLE_TIMER_ON_WRITE 0x2000U
/* NGTCP2_CONN_FLAG_SERVER_ADDR_VERIFIED indicates that server as peer
verified client address. This flag is only used by client. */
#define NGTCP2_CONN_FLAG_SERVER_ADDR_VERIFIED 0x4000u
#define NGTCP2_CONN_FLAG_SERVER_ADDR_VERIFIED 0x4000U
/* NGTCP2_CONN_FLAG_EARLY_KEY_INSTALLED indicates that an early key is
installed. conn->early.ckm cannot be used for this purpose because
it might be discarded when a certain condition is met. */
#define NGTCP2_CONN_FLAG_EARLY_KEY_INSTALLED 0x8000u
#define NGTCP2_CONN_FLAG_EARLY_KEY_INSTALLED 0x8000U
/* NGTCP2_CONN_FLAG_KEY_UPDATE_INITIATOR is set when the local
endpoint has initiated key update. */
#define NGTCP2_CONN_FLAG_KEY_UPDATE_INITIATOR 0x10000u
#define NGTCP2_CONN_FLAG_KEY_UPDATE_INITIATOR 0x10000U
/* NGTCP2_CONN_FLAG_AGGREGATE_PKTS is set when
ngtcp2_conn_writev_stream is called inside the callback invoked by
ngtcp2_conn_write_aggregate_pkt. */
#define NGTCP2_CONN_FLAG_AGGREGATE_PKTS 0x20000u
#define NGTCP2_CONN_FLAG_AGGREGATE_PKTS 0x20000U
/* NGTCP2_CONN_FLAG_CRUMBLE_INITIAL_CRYPTO, if set, crumbles an
Initial CRYPTO frame into pieces as a countermeasure against Deep
Packet Inspection. */
#define NGTCP2_CONN_FLAG_CRUMBLE_INITIAL_CRYPTO 0x40000u
#define NGTCP2_CONN_FLAG_CRUMBLE_INITIAL_CRYPTO 0x40000U
typedef struct ngtcp2_pktns {
struct {
@@ -943,7 +943,7 @@ ngtcp2_conn_server_negotiate_version(ngtcp2_conn *conn,
* @function
*
* `ngtcp2_conn_write_connection_close_pkt` writes a packet which
* contains a CONNECTION_CLOSE frame (type 0x1c) in the buffer pointed
* contains a CONNECTION_CLOSE frame (type 0x1C) in the buffer pointed
* by |dest| whose capacity is |datalen|.
*
* If |path| is not ``NULL``, this function stores the network path
@@ -985,7 +985,7 @@ ngtcp2_ssize ngtcp2_conn_write_connection_close_pkt(
* @function
*
* `ngtcp2_conn_write_application_close_pkt` writes a packet which
* contains a CONNECTION_CLOSE frame (type 0x1d) in the buffer pointed
* contains a CONNECTION_CLOSE frame (type 0x1D) in the buffer pointed
* by |dest| whose capacity is |datalen|.
*
* If |path| is not ``NULL``, this function stores the network path
@@ -998,7 +998,7 @@ ngtcp2_ssize ngtcp2_conn_write_connection_close_pkt(
* if it succeeds. The metadata includes ECN markings.
*
* If handshake has not been confirmed yet, CONNECTION_CLOSE (type
* 0x1c) with error code :macro:`NGTCP2_APPLICATION_ERROR` is written
* 0x1C) with error code :macro:`NGTCP2_APPLICATION_ERROR` is written
* instead.
*
* This function must not be called from inside the callback
+5 -5
View File
@@ -74,21 +74,21 @@ static const uint8_t *get_uvarint(uint64_t *dest, const uint8_t *p) {
case 1:
memcpy(&n16, p, 2);
n16 = ngtcp2_ntohs(n16);
n16 &= 0x3fff;
n16 &= 0x3FFF;
*dest = n16;
return p + 2;
case 2:
memcpy(&n32, p, 4);
n32 = ngtcp2_ntohl(n32);
n32 &= 0x3fffffff;
n32 &= 0x3FFFFFFF;
*dest = n32;
return p + 4;
case 3:
memcpy(&n64, p, 8);
n64 = ngtcp2_ntohl64(n64);
n64 &= 0x3fffffffffffffff;
n64 &= 0x3FFFFFFFFFFFFFFF;
*dest = n64;
return p + 8;
@@ -168,7 +168,7 @@ uint8_t *ngtcp2_put_uvarint(uint8_t *p, uint64_t n) {
}
assert(n < 4611686018427387904ULL);
rv = ngtcp2_put_uint64be(p, n);
*p |= 0xc0;
*p |= 0xC0;
return rv;
}
@@ -200,7 +200,7 @@ uint8_t *ngtcp2_put_pkt_num(uint8_t *p, int64_t pkt_num, size_t len) {
}
size_t ngtcp2_get_uvarintlen(const uint8_t *p) {
return (size_t)(1u << (*p >> 6));
return (size_t)(1U << (*p >> 6));
}
size_t ngtcp2_put_uvarintlen(uint64_t n) {
+2 -2
View File
@@ -42,10 +42,10 @@
#define NGTCP2_MAX_AEAD_OVERHEAD 16
/* NGTCP2_CRYPTO_KM_FLAG_NONE indicates that no flag is set. */
#define NGTCP2_CRYPTO_KM_FLAG_NONE 0x00u
#define NGTCP2_CRYPTO_KM_FLAG_NONE 0x00U
/* NGTCP2_CRYPTO_KM_FLAG_KEY_PHASE_ONE is set if key phase bit is
set. */
#define NGTCP2_CRYPTO_KM_FLAG_KEY_PHASE_ONE 0x01u
#define NGTCP2_CRYPTO_KM_FLAG_KEY_PHASE_ONE 0x01U
typedef struct ngtcp2_crypto_km {
ngtcp2_vec secret;
+9 -8
View File
@@ -157,9 +157,9 @@ int ngtcp2_dcidtr_bind_dcid(ngtcp2_dcidtr *dtr, ngtcp2_dcid **pdest,
return 0;
}
int ngtcp2_dcidtr_verify_stateless_reset(const ngtcp2_dcidtr *dtr,
const ngtcp2_path *path,
const uint8_t *token) {
int ngtcp2_dcidtr_verify_stateless_reset(
const ngtcp2_dcidtr *dtr, const ngtcp2_path *path,
const ngtcp2_stateless_reset_token *token) {
const ngtcp2_dcid *dcid;
const ngtcp2_ringbuf *rb = &dtr->bound.rb;
size_t i, len = ngtcp2_ringbuf_len(rb);
@@ -176,7 +176,7 @@ int ngtcp2_dcidtr_verify_stateless_reset(const ngtcp2_dcidtr *dtr,
static int verify_token_uniqueness(const ngtcp2_ringbuf *rb, int *pfound,
uint64_t seq, const ngtcp2_cid *cid,
const uint8_t *token) {
const ngtcp2_stateless_reset_token *token) {
const ngtcp2_dcid *dcid;
size_t i, len = ngtcp2_ringbuf_len(rb);
int rv;
@@ -196,9 +196,9 @@ static int verify_token_uniqueness(const ngtcp2_ringbuf *rb, int *pfound,
return 0;
}
int ngtcp2_dcidtr_verify_token_uniqueness(const ngtcp2_dcidtr *dtr, int *pfound,
uint64_t seq, const ngtcp2_cid *cid,
const uint8_t *token) {
int ngtcp2_dcidtr_verify_token_uniqueness(
const ngtcp2_dcidtr *dtr, int *pfound, uint64_t seq, const ngtcp2_cid *cid,
const ngtcp2_stateless_reset_token *token) {
int rv;
rv = verify_token_uniqueness(&dtr->bound.rb, pfound, seq, cid, token);
@@ -406,7 +406,8 @@ ngtcp2_tstamp ngtcp2_dcidtr_earliest_retired_ts(const ngtcp2_dcidtr *dtr) {
}
void ngtcp2_dcidtr_push_unused(ngtcp2_dcidtr *dtr, uint64_t seq,
const ngtcp2_cid *cid, const uint8_t *token) {
const ngtcp2_cid *cid,
const ngtcp2_stateless_reset_token *token) {
ngtcp2_dcid *dcid = ngtcp2_ringbuf_push_back(&dtr->unused.rb);
ngtcp2_dcid_init(dcid, seq, cid, token);
+8 -7
View File
@@ -154,9 +154,9 @@ int ngtcp2_dcidtr_bind_dcid(ngtcp2_dcidtr *dtr, ngtcp2_dcid **pdest,
* There is no Destination Connection ID that matches the given
* |path| and |token|.
*/
int ngtcp2_dcidtr_verify_stateless_reset(const ngtcp2_dcidtr *dtr,
const ngtcp2_path *path,
const uint8_t *token);
int ngtcp2_dcidtr_verify_stateless_reset(
const ngtcp2_dcidtr *dtr, const ngtcp2_path *path,
const ngtcp2_stateless_reset_token *token);
/*
* ngtcp2_dcidtr_verify_token_uniqueness verifies that the uniqueness
@@ -180,9 +180,9 @@ int ngtcp2_dcidtr_verify_stateless_reset(const ngtcp2_dcidtr *dtr,
* The given combination of values does not satisfy the above
* conditions.
*/
int ngtcp2_dcidtr_verify_token_uniqueness(const ngtcp2_dcidtr *dtr, int *pfound,
uint64_t seq, const ngtcp2_cid *cid,
const uint8_t *token);
int ngtcp2_dcidtr_verify_token_uniqueness(
const ngtcp2_dcidtr *dtr, int *pfound, uint64_t seq, const ngtcp2_cid *cid,
const ngtcp2_stateless_reset_token *token);
/*
* ngtcp2_dcidtr_retire_inactive_dcid_prior_to retires inactive
@@ -273,7 +273,8 @@ ngtcp2_tstamp ngtcp2_dcidtr_earliest_retired_ts(const ngtcp2_dcidtr *dtr);
* buffer space is full, the earliest ngtcp2_dcid is removed.
*/
void ngtcp2_dcidtr_push_unused(ngtcp2_dcidtr *dtr, uint64_t seq,
const ngtcp2_cid *cid, const uint8_t *token);
const ngtcp2_cid *cid,
const ngtcp2_stateless_reset_token *token);
/*
* ngtcp2_dcidtr_pop_unused_cid_token removes an unused Destination
+2 -2
View File
@@ -36,10 +36,10 @@
/* NGTCP2_FRAME_CHAIN_BINDER_FLAG_NONE indicates that no flag is
set. */
#define NGTCP2_FRAME_CHAIN_BINDER_FLAG_NONE 0x00u
#define NGTCP2_FRAME_CHAIN_BINDER_FLAG_NONE 0x00U
/* NGTCP2_FRAME_CHAIN_BINDER_FLAG_ACK indicates that an information
which a frame carries has been acknowledged. */
#define NGTCP2_FRAME_CHAIN_BINDER_FLAG_ACK 0x01u
#define NGTCP2_FRAME_CHAIN_BINDER_FLAG_ACK 0x01U
/*
* ngtcp2_frame_chain_binder binds 2 or more of ngtcp2_frame_chain to
+2 -2
View File
@@ -55,12 +55,12 @@ void ngtcp2_ksl_init(ngtcp2_ksl *ksl, ngtcp2_ksl_compar compar,
assert(keylen >= sizeof(uint64_t));
aligned_keylen = (keylen + 0x7u) & ~0x7u;
aligned_keylen = (keylen + 0x7U) & ~0x7U;
assert(aligned_keylen <= UINT16_MAX);
ngtcp2_objalloc_init(&ksl->blkalloc,
(ksl_blklen(aligned_keylen) + 0xfu) & ~(uintptr_t)0xfu,
(ksl_blklen(aligned_keylen) + 0xFU) & ~(uintptr_t)0xFU,
mem);
ksl->root = NULL;
+20 -22
View File
@@ -47,7 +47,7 @@ void ngtcp2_log_init(ngtcp2_log *log, const ngtcp2_cid *scid,
log->scid[0] = '\0';
}
log->log_printf = log_printf;
log->events = 0xff;
log->events = 0xFF;
log->ts = log->last_ts = ts;
log->user_data = user_data;
}
@@ -134,7 +134,7 @@ static const char *strerrorcode(uint64_t error_code) {
case NGTCP2_VERSION_NEGOTIATION_ERROR:
return "VERSION_NEGOTIATION_ERROR";
default:
if (0x100u <= error_code && error_code <= 0x1ffu) {
if (0x100U <= error_code && error_code <= 0x1FFU) {
return "CRYPTO_ERROR";
}
return "(unknown)";
@@ -328,7 +328,7 @@ static void log_fr_streams_blocked(ngtcp2_log *log, const ngtcp2_pkt_hd *hd,
static void log_fr_new_connection_id(ngtcp2_log *log, const ngtcp2_pkt_hd *hd,
const ngtcp2_new_connection_id *fr,
const char *dir) {
char buf[sizeof(fr->stateless_reset_token) * 2 + 1];
char buf[sizeof(fr->token.data) * 2 + 1];
char cid[sizeof(fr->cid.data) * 2 + 1];
ngtcp2_log_infof_raw(
@@ -339,8 +339,7 @@ static void log_fr_new_connection_id(ngtcp2_log *log, const ngtcp2_pkt_hd *hd,
NGTCP2_LOG_PKT_HD_FIELDS(dir), fr->type, fr->seq,
ngtcp2_encode_hex_cstr(cid, fr->cid.data, fr->cid.datalen),
fr->retire_prior_to,
ngtcp2_encode_hex_cstr(buf, fr->stateless_reset_token,
sizeof(fr->stateless_reset_token)));
ngtcp2_encode_hex_cstr(buf, fr->token.data, sizeof(fr->token.data)));
}
static void log_fr_stop_sending(ngtcp2_log *log, const ngtcp2_pkt_hd *hd,
@@ -357,25 +356,25 @@ static void log_fr_stop_sending(ngtcp2_log *log, const ngtcp2_pkt_hd *hd,
static void log_fr_path_challenge(ngtcp2_log *log, const ngtcp2_pkt_hd *hd,
const ngtcp2_path_challenge *fr,
const char *dir) {
char buf[sizeof(fr->data) * 2 + 1];
char buf[sizeof(fr->data.data) * 2 + 1];
ngtcp2_log_infof_raw(log, NGTCP2_LOG_EVENT_FRM,
NGTCP2_LOG_PKT " PATH_CHALLENGE(0x%02" PRIx64
") data=0x%s",
NGTCP2_LOG_PKT_HD_FIELDS(dir), fr->type,
ngtcp2_encode_hex_cstr(buf, fr->data, sizeof(fr->data)));
ngtcp2_log_infof_raw(
log, NGTCP2_LOG_EVENT_FRM,
NGTCP2_LOG_PKT " PATH_CHALLENGE(0x%02" PRIx64 ") data=0x%s",
NGTCP2_LOG_PKT_HD_FIELDS(dir), fr->type,
ngtcp2_encode_hex_cstr(buf, fr->data.data, sizeof(fr->data.data)));
}
static void log_fr_path_response(ngtcp2_log *log, const ngtcp2_pkt_hd *hd,
const ngtcp2_path_response *fr,
const char *dir) {
char buf[sizeof(fr->data) * 2 + 1];
char buf[sizeof(fr->data.data) * 2 + 1];
ngtcp2_log_infof_raw(log, NGTCP2_LOG_EVENT_FRM,
NGTCP2_LOG_PKT " PATH_RESPONSE(0x%02" PRIx64
") data=0x%s",
NGTCP2_LOG_PKT_HD_FIELDS(dir), fr->type,
ngtcp2_encode_hex_cstr(buf, fr->data, sizeof(fr->data)));
ngtcp2_log_infof_raw(
log, NGTCP2_LOG_EVENT_FRM,
NGTCP2_LOG_PKT " PATH_RESPONSE(0x%02" PRIx64 ") data=0x%s",
NGTCP2_LOG_PKT_HD_FIELDS(dir), fr->type,
ngtcp2_encode_hex_cstr(buf, fr->data.data, sizeof(fr->data.data)));
}
static void log_fr_crypto(ngtcp2_log *log, const ngtcp2_pkt_hd *hd,
@@ -542,8 +541,8 @@ void ngtcp2_log_rx_vn(ngtcp2_log *log, const ngtcp2_pkt_hd *hd,
}
}
void ngtcp2_log_rx_sr(ngtcp2_log *log, const ngtcp2_pkt_stateless_reset *sr) {
char buf[sizeof(sr->stateless_reset_token) * 2 + 1];
void ngtcp2_log_rx_sr(ngtcp2_log *log, const ngtcp2_pkt_stateless_reset2 *sr) {
char buf[sizeof(sr->token.data) * 2 + 1];
ngtcp2_pkt_hd shd;
ngtcp2_pkt_hd *hd = &shd;
@@ -558,14 +557,13 @@ void ngtcp2_log_rx_sr(ngtcp2_log *log, const ngtcp2_pkt_stateless_reset *sr) {
ngtcp2_log_infof_raw(
log, NGTCP2_LOG_EVENT_PKT, NGTCP2_LOG_PKT " token=0x%s randlen=%zu",
NGTCP2_LOG_PKT_HD_FIELDS("rx"),
ngtcp2_encode_hex_cstr(buf, sr->stateless_reset_token,
sizeof(sr->stateless_reset_token)),
ngtcp2_encode_hex_cstr(buf, sr->token.data, sizeof(sr->token.data)),
sr->randlen);
}
void ngtcp2_log_remote_tp(ngtcp2_log *log,
const ngtcp2_transport_params *params) {
char token[NGTCP2_STATELESS_RESET_TOKENLEN * 2 + 1];
char token[sizeof(params->stateless_reset_token) * 2 + 1];
char addr[16 * 2 + 7 + 1];
char cid[NGTCP2_MAX_CIDLEN * 2 + 1];
size_t i;
+1 -1
View File
@@ -107,7 +107,7 @@ void ngtcp2_log_tx_fr(ngtcp2_log *log, const ngtcp2_pkt_hd *hd,
void ngtcp2_log_rx_vn(ngtcp2_log *log, const ngtcp2_pkt_hd *hd,
const uint32_t *sv, size_t nsv);
void ngtcp2_log_rx_sr(ngtcp2_log *log, const ngtcp2_pkt_stateless_reset *sr);
void ngtcp2_log_rx_sr(ngtcp2_log *log, const ngtcp2_pkt_stateless_reset2 *sr);
void ngtcp2_log_remote_tp(ngtcp2_log *log,
const ngtcp2_transport_params *params);
+2 -2
View File
@@ -77,10 +77,10 @@ int ngtcp2_map_each(const ngtcp2_map *map, int (*func)(void *data, void *ptr),
/* Hasher from
https://github.com/rust-lang/rustc-hash/blob/dc5c33f1283de2da64d8d7a06401d91aded03ad4/src/lib.rs
to maximize the output's sensitivity to all input bits. */
#define NGTCP2_MAP_HASHER 0xf1357aea2e62a9c5ull
#define NGTCP2_MAP_HASHER 0xF1357AEA2E62A9C5ULL
/* 64-bit Fibonacci hashing constant, Golden Ratio constant, to get
the high bits with the good distribution. */
#define NGTCP2_MAP_FIBO 0x9e3779b97f4a7c15ull
#define NGTCP2_MAP_FIBO 0x9E3779B97F4A7C15ULL
static size_t map_index(const ngtcp2_map *map, ngtcp2_map_key_type key) {
key += map->seed;
+4 -4
View File
@@ -97,9 +97,9 @@ STIN uint32_t ngtcp2_htonl(uint32_t hostlong) {
uint32_t res;
unsigned char *p = (unsigned char *)&res;
*p++ = (unsigned char)(hostlong >> 24);
*p++ = (hostlong >> 16) & 0xffu;
*p++ = (hostlong >> 8) & 0xffu;
*p = hostlong & 0xffu;
*p++ = (hostlong >> 16) & 0xFFU;
*p++ = (hostlong >> 8) & 0xFFU;
*p = hostlong & 0xFFU;
return res;
}
@@ -107,7 +107,7 @@ STIN uint16_t ngtcp2_htons(uint16_t hostshort) {
uint16_t res;
unsigned char *p = (unsigned char *)&res;
*p++ = (unsigned char)(hostshort >> 8);
*p = hostshort & 0xffu;
*p = hostshort & 0xFFU;
return res;
}
+2 -2
View File
@@ -69,7 +69,7 @@ void ngtcp2_objalloc_clear(ngtcp2_objalloc *objalloc);
inline static void ngtcp2_objalloc_##NAME##_init( \
ngtcp2_objalloc *objalloc, size_t nmemb, const ngtcp2_mem *mem) { \
ngtcp2_objalloc_init( \
objalloc, ((sizeof(TYPE) + 0xfu) & ~(uintptr_t)0xfu) * nmemb, mem); \
objalloc, ((sizeof(TYPE) + 0xFU) & ~(uintptr_t)0xFU) * nmemb, mem); \
} \
\
TYPE *ngtcp2_objalloc_##NAME##_get(ngtcp2_objalloc *objalloc); \
@@ -123,7 +123,7 @@ void ngtcp2_objalloc_clear(ngtcp2_objalloc *objalloc);
inline static void ngtcp2_objalloc_##NAME##_init( \
ngtcp2_objalloc *objalloc, size_t nmemb, const ngtcp2_mem *mem) { \
ngtcp2_objalloc_init( \
objalloc, ((sizeof(TYPE) + 0xfu) & ~(uintptr_t)0xfu) * nmemb, mem); \
objalloc, ((sizeof(TYPE) + 0xFU) & ~(uintptr_t)0xFU) * nmemb, mem); \
} \
\
inline static TYPE *ngtcp2_objalloc_##NAME##_get( \
+2 -2
View File
@@ -70,8 +70,8 @@ static uint32_t pcg_rotr_32(uint32_t value, unsigned int rot) {
}
static uint32_t pcg_output_xsh_rr_64_32(uint64_t state) {
return pcg_rotr_32((uint32_t)(((state >> 18u) ^ state) >> 27u),
(unsigned int)(state >> 59u));
return pcg_rotr_32((uint32_t)(((state >> 18U) ^ state) >> 27U),
(unsigned int)(state >> 59U));
}
uint32_t ngtcp2_pcg32_rand(ngtcp2_pcg32 *pcg) {
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more