From 30d5f21b43bb39ac55d83070cdbd666b8540d1e2 Mon Sep 17 00:00:00 2001 From: yhirose Date: Sun, 29 Nov 2026 10:14:56 -0500 Subject: [PATCH] Require Mbed TLS built with MBEDTLS_THREADING_C SSLServer runs TLS handshakes on several pool threads, and SSLClients may be used from several threads. Mbed TLS is thread-safe only when it is built with MBEDTLS_THREADING_C, which its default configuration leaves off. Without it, concurrent handshakes race on the PSA key store and the shared CTR-DRBG and corrupt memory. Stop the build with an #error when the option is missing, and document the requirement in the README. Define CPPHTTPLIB_MBEDTLS_SINGLE_THREADED to build anyway when Mbed TLS is only ever used from one thread. Distribution packages (Debian, Ubuntu, Homebrew) already enable the option, so builds against them are unaffected. --- README.md | 3 +++ httplib.h | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/README.md b/README.md index 600f0558..0e6b5984 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,9 @@ cpp-httplib supports multiple TLS backends through an abstraction layer: | Mbed TLS | `CPPHTTPLIB_MBEDTLS_SUPPORT` | `libmbedtls`, `libmbedx509`, `libmbedcrypto` | 2.x, 3.x, and 4.x supported (auto-detected); 4.x renames `libmbedcrypto` to `libtfpsacrypto` | | wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` | 5.x supported; must build with `--enable-opensslall` | +> [!NOTE] +> **Mbed TLS threading:** Mbed TLS must be built with `MBEDTLS_THREADING_C`, because `SSLServer` handles connections on several threads and Mbed TLS is not thread-safe without it. Its default configuration leaves this option off, while distribution packages such as Debian, Ubuntu and Homebrew turn it on. Building against Mbed TLS without it stops with an `#error`. If Mbed TLS is only ever used from one thread, define `CPPHTTPLIB_MBEDTLS_SINGLE_THREADED` to build anyway. + > [!NOTE] > **wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()` or `set_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable. > diff --git a/httplib.h b/httplib.h index 3c58ef04..0950008f 100644 --- a/httplib.h +++ b/httplib.h @@ -565,6 +565,13 @@ using socket_t = int; #define CPPHTTPLIB_MBEDTLS_V3 #endif +// SSLServer (and SSLClients on several threads) use Mbed TLS concurrently. +#if !defined(MBEDTLS_THREADING_C) && \ + !defined(CPPHTTPLIB_MBEDTLS_SINGLE_THREADED) +#error \ + "Mbed TLS must be built with MBEDTLS_THREADING_C. Define CPPHTTPLIB_MBEDTLS_SINGLE_THREADED if it is only ever used from one thread." +#endif + #endif // CPPHTTPLIB_MBEDTLS_SUPPORT #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT