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.
RFC 9110 allows 1*SP between the auth scheme and what follows it in both
challenges and credentials. parse_www_authenticate() took the scheme up
to the last whitespace before "=", so "Digest realm=..." was not
recognized as Digest and the 401 was returned without a retry, and
get_bearer_token_auth() returned the token of "Bearer abc" with a
leading space.
The scheme is now the text up to the first whitespace, with the key
after it trimmed, and get_bearer_token_auth() skips the extra spaces.
When a server offered both qop=auth and qop=auth-int, the client chose
auth-int, which hashes req.body. That is empty when a content provider
streams the body, so the response was wrong and the request failed. A
challenge whose qop offered neither option (e.g. only auth-conf) was
answered without qop, although RFC 7616 makes qop mandatory and has the
client use the first challenge it supports.
select_digest_qop() now picks auth over auth-int, as curl does, and
parse_www_authenticate() treats a challenge whose qop offers neither as
unanswerable, so a later challenge is used or the 401 is returned. A
challenge without qop is still answered in the RFC 2069 form.
The Digest client compared the algorithm and qop values of a challenge
case-sensitively, so algorithm=sha-256 was answered with an MD5 hash and
qop="AUTH" without qop. A challenge whose algorithm it doesn't implement
(SHA-512-256, the -sess variants, or a value that isn't a token) was
answered with an MD5 hash under the server's algorithm name, and only the
first Digest challenge was ever looked at.
- Match algorithm and qop options case-insensitively. qop is split into
tokens instead of searched as a substring, and sent as auth/auth-int.
- Collect params per Digest challenge and use the first one the client
can answer (RFC 7616 Sections 3.3 and 3.7): realm and nonce present and
an algorithm it implements. If there is none, the 401 is returned
without a retry.
- digest_hash() is the single list of supported algorithms, used by both
parse_www_authenticate() and make_digest_authentication_header(). The
algorithm is sent back as the server wrote it (RFC 7616 Section 3.4).
parse_www_authenticate() moves into the SSL block, next to the hash
functions and its callers.
There was no way to refuse a connection before the server read a
request from it, or before the TLS handshake on SSLServer. The earliest
hook was the pre-routing handler, after the request head had been read.
set_accept_handler() takes a callback that gets each accepted socket
and returns whether to serve it. Both accept paths, with and without
keep-alive parking, go through one function, admit_accepted_socket(),
which sets the socket timeouts first, so that a handler reading from
the socket cannot block forever. A refused or throwing handler closes
the socket; an exception is reported as Error::UserCallbackException.
Fix#2700
* Only treat :// as a scheme separator before the path
parse_url looked for :// anywhere, so a redirect to a path whose query
held a URL, such as /login?next=https://example.com/, was split at the
query and rejected because the scheme was not letters only.
* Check the path-with-query case in ParseUrlTest
The redirect test resolves its relative case to the same input shape, and
the case with a leading slash did not fit the test's name.
---------
Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
The WebSocket constructors took the ping interval, the missed-pong limit
and the message limit as adjacent positional arguments of types that
convert into each other, so swapping two still compiled, and every new
setting grew both constructors and all three call sites. They now take a
ws::impl::Options whose fields the Server and WebSocketClient set by
name. The members of Server, WebSocketClient and WebSocket do not
change.
MaxPayloadExceeded and MaxPayloadAtLimit pushed messages at the default
limit through the echo route. A message over the limit is refused in
ServerMaxMessageLength and FailsABadFrameWithACloseStatus, one at the
limit is accepted in ServerMaxMessageLength, and LargeMessage covers a
payload read in many pieces, so the pair only cost time (about 230 ms
locally).
check_bounded_read_resumes() sent each piece 200 ms after the last and
required every read() to return within 150 ms, which a stalled macOS
runner missed (167 ms, 174 ms). The sender now waits, after each piece
is sent, until read() has timed out twice, so a read() that waits for
the rest of the message still fails the test and a slow machine only
waits longer. TCP_NODELAY keeps Nagle's algorithm from holding a piece
back until the next, and the two tests drop from about 1.4 s to 70 ms.
* Add set_websocket_max_message_length() to Server and WebSocketClient
The largest WebSocket frame and message read() accepts was fixed at
compile time by CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, so a program
running several servers, or one build of httplib.h shared by many
applications, could not pick a limit per server. Checking the size
after read() does not help, since by then the message has already been
assembled in memory.
Add set_websocket_max_message_length() to Server and WebSocketClient,
next to the heartbeat setters. It defaults to the macro, is handed to
ws::WebSocket like the ping settings, and replaces the macro in both
checks in read(): the declared frame length and the size of a message
assembled from fragments. 0 still means no limit, and a message over
the limit still makes read() fail and close the connection. On the
client, the value applies from the next connect().
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Keep control frames out of the message limit and trim the limit tests
With a limit under 125 bytes, a frame read between messages was held to
the limit itself, so a Ping or a Close with a reason was answered with
1009. The frame limit is now what is left of the message limit, but
never less than 125, so control frames always fit; a small data frame
over the limit is still refused by the message check.
The test that sent two 16 MiB messages is replaced by cheap checks in
the remaining tests: a header that announces more than the limit is
refused before its payload, a Ping over the limit is answered, and 0
lifts the limit on the client.
* Fold the server limit tests and drop unused constructor defaults
The two server-side tests become one on an echo server, checked with
raw_websocket_reply(): a Ping over the limit is answered, a message at
the limit is echoed, one over it gets 1009, and so does a header that
announces more than the limit. Every caller of the WebSocket
constructors passes the settings, so their defaults are dropped.
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
* Expose the WebSocket close status and reason
When the peer closed a WebSocket, read() returned Fail and the code and
reason of its Close frame were dropped after the reply, so a handler or
a WebSocketClient user could not tell a normal close from going away, an
application code, or a connection that ended without a Close at all.
Add close_status() and close_reason() to ws::WebSocket and
WebSocketClient. Once read() has returned Fail they report the code and
reason of the peer's Close (RFC 6455 7.1.5 and 7.1.6), NoStatus (1005)
when it carried no code, ProtocolError when it was malformed, and
Abnormal (1006) when none came. After a close() of our own they report
the peer's reply. Application codes (3000-4999) come back as a
CloseStatus too, as close() already takes them.
The status is set once, under the read mutex, with the reason written
before it, so the accessors may be called from any thread.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Return close_reason() by value and fold the handler-side close tests
WebSocketClient::close_reason() returned a reference into the connection
that connect() replaces, so a reference kept across a reconnect dangled.
Both close_reason() accessors now return a copy of the reason, which is
at most 123 bytes.
The six handler-side tests become one table-driven test on one server,
and the client test checks the reason still reads after a reconnect.
* Decode the close code in one place and fold the client close tests
is_valid_close_payload() and set_close_status() each decoded the code by
hand; they now share impl::close_code(). The client-side checks move
into the existing CloseHandshake, CloseWithStatus and
ClientCloseWithStatus tests, which already reach those states, and the
reconnect check becomes a static_assert on close_reason()'s type.
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
parse_disposition_params stored parameter names as they arrived, while FormDataParser looks up "name", "filename" and "filename*" in lower case. A part with NAME= was rejected with 400, and one with FILENAME*= was silently treated as a plain field. Parameter names are case-insensitive (RFC 2045 section 5.1), so the names are now lowercased when stored, as extract_media_type already does for Content-Type. Values keep their case.
* Send a Close frame when a WebSocket read fails on the peer's error
WebSocket::read() answered a malformed Close with 1002 and invalid UTF-8
with 1007, but every other protocol error, and a message over
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, only marked the connection
closed, so the peer saw the TCP connection drop without a reason. That
covers set RSV bits, a mask bit the wrong way, a fragmented or oversized
control frame, a 64-bit length with its top bit set, a reserved opcode,
a continuation without a message to continue or a new message inside a
fragmented one, and a frame or message over the limit. RFC 6455 Section
7.1.7 says an endpoint that fails the connection should send a Close
frame with the status first.
FrameReader::read() now tells these apart from a failed read, with
FrameRead::ProtocolError and FrameRead::TooBig, and read() answers them,
and the opcode and fragmentation errors it finds itself, with a Close
frame of 1002 or 1009. As for the malformed Close, it does not wait for
the peer's reply: the stream may be in the middle of the bad frame, and
Section 7.1.7 says to read nothing more. A read that fails or times out
still closes without a frame. This applies to Server's WebSocket
handlers and to WebSocketClient alike.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Send every Close frame through one helper
WebSocket::close(), the Close echo and the new failure path each encoded
a status and wrote a Close frame under write_mutex_. They now share
send_close() and ws::impl::close_payload(), so every path that ends the
connection also wakes the heartbeat thread. The tests share a helper for
the raw-socket exchange and decode the client's Close with
read_websocket_frame().
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
The no-exceptions CI job runs the *_Online tests, and over its last 40
runs 27 failed, each time on tests that never reached what they check:
- google.com answered CI runners with 302 or 429 instead of the 301 or
200 the certificate verification tests asserted. Those tests only need
a response, which proves the handshake and the verification passed, as
UniversalClientRedirectTest.EnableSystemCaCarriesOver_Online already
does. Issue2004_Online is a regression test for a crash, so a response
is enough there too.
- badssl.com drops connections from CI runners before it sends its
certificate, so the hostname and self-signed checks never ran. From
elsewhere, the same OpenSSL 3.0.13 gets the certificate and the
expected verification error.
Generalize retry_gateway_errors() to retry_service_failures(), which also
treats a handshake that failed before any verdict on the certificate as
the service's failure, and use it for the two badssl.com tests. Such a
handshake failure in the client itself is caught by the TLS tests that
run against local servers.
SSLServer::process_and_close_socket() waits for the handshake of an
accepted connection for up to the read timeout, and that wait ignored
stop(). A client that connects and never sends a ClientHello kept
listen() from returning for the full timeout (4.7 seconds with the
default 5-second read timeout).
Give tls::accept_nonblocking() the same `interrupted` parameter that
connect_nonblocking() already has, and pass `is_stopping()` from
start_session(). Keep-alive parking was not affected, since it waits for
the ClientHello in its event loop, which stop() wakes.
send_frame now marks the connection closed whenever it returns false,
so the heartbeat no longer needs to. The second send() in the test
fails before the fix too, since the client is not reading, so it does
not check anything; large_sent becomes an ASSERT as the precondition.
WebSocket::send_frame returned false when write_websocket_frame failed
but left the connection open, and the Pong reply in read() ignored a
failed write. A write that fails partway (the write timeout expiring
while the peer is not reading) has already sent a frame header that
announces the whole payload, so anything written after it is read by
the peer as the rest of that frame, and a later payload's bytes as a
frame of their own. Mark the connection closed on a failed write, as
the heartbeat already does for its Ping, and send the Pong through
send_frame.
httpbingo.org intermittently answers with 502/503/504, which made the
*_Online tests that depend on it fail for reasons unrelated to the
client. Retry such responses twice with a short backoff, and skip the
test if the service keeps failing. Connection errors and other statuses
are still reported as failures.
2026-11-24 11:10:31 -05:00
11 changed files with 1271 additions and 450 deletions
| `CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND` | `300` | Server read timeout (seconds) |
| `CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND` | `5` | Timeout for waiting peer's Close response (seconds) |
@@ -550,6 +570,18 @@ With the default ping interval of 30 seconds, `max_missed_pongs = 2` detects a d
**The default is `0`**, which means "never close the connection because of missing pongs." Pings are still sent on the heartbeat interval, but their responses are not checked. On the server side a dead connection still does not linger: while a handler is inside `read()`, `CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND` (default **300 seconds = 5 minutes**) acts as a backstop. A client has no such backstop — it waits forever unless you set a read timeout — so there `max_missed_pongs` is what notices an unresponsive peer at all. On either side it is also the knob for noticing one *faster* than the 5-minute fallback.
### Maximum Message Length
`read()` refuses a message larger than `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` (16MB by default): it returns `Fail` and closes the connection with `MessageTooBig` (1009). A frame that announces a larger length is refused before its payload is read, and a fragmented message is refused as soon as its fragments add up to more, so the limit bounds the memory a peer can make `read()` hold. You can set it per server or per client at runtime instead of changing the compile-time macro. `0` means no limit.
WebSocket connections share the same thread pool as HTTP requests. Each WebSocket connection occupies one thread for its entire lifetime, so a client opening many of them can leave none for HTTP requests. Reject the upgrades you do not want in `set_pre_request_handler()`, before the connection takes a thread for good.
| 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.
> Because the body has not been read yet, `req.body` and form fields parsed from the body are not available in the pre-request handler. Inspect headers, the path, query parameters, or `req.matched_route` instead.
### Accept handler
The accept handler runs for each accepted connection before anything is read from it, and before the TLS handshake on `SSLServer`. Return `false` to close the connection.
```cpp
svr.set_accept_handler([](socket_t sock) {
sockaddr_storage addr;
socklen_t len = sizeof(addr);
if (getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
return false;
}
return is_allowed(addr); // Your own check
});
```
> [!NOTE]
> The handler runs on the thread that accepts connections, so a slow handler delays every new connection. With `set_keep_alive_parking(true)`, that thread also hands out the next requests on kept-alive connections, so those wait too. The server owns `sock` and closes it after a refusal, so the handler must not close it. If the handler throws, the connection is closed and the error logger receives `Error::UserCallbackException`.
### Handler execution order
`set_start_handler` runs once when the server starts. For each request, handlers run in the following order:
`set_start_handler` runs once when the server starts, and `set_accept_handler` once for each connection, before any request on it. For each request, handlers run in the following order:
@@ -51,4 +51,21 @@ If auth fails, return `Handled` to respond with 401 immediately. If it passes, r
If you want different auth rules per route rather than a single global check, `set_pre_request_handler()` is a better fit. See [S11. Authenticate per route with a pre-request handler](../s11-pre-request).
## Refuse at the connection
If all you need is to filter by the peer address, you can refuse the connection before any request is read. `set_accept_handler()` runs right after a connection is accepted, before the request is read (and before the TLS handshake on `SSLServer`). Return `false`, and the connection is closed without reading from it.
The handler runs on the thread that accepts connections, so a slow handler holds up every new connection. The server closes the socket, so don't close it in the handler.
> **Note:** If all you want is to modify the response, `set_post_routing_handler()` is the right tool. See [S10. Add response headers with a post-routing handler](../s10-post-routing).
On the client,`read()`just returns`Fail`; the status and reason it received aren't exposed. If the client needs to tell a restart from other closures, send it a message first (say, `ws.send("restarting")`), then call `close()`.
Once`read()`has returned`Fail`, `close_status()` and `close_reason()` tell you why: the status and reason of the peer's Close, `NoStatus` (1005) if it sent no status, or `Abnormal` (1006) if the connection ended without a Close. This works the same on the server and the client.
@@ -85,4 +85,4 @@ if (cli.read(buf) == httplib::ws::ReadResult::Binary) {
You can mix text and binary in the same connection. A common pattern: JSON for control messages, binary for the actual data — you get efficient handling of metadata and payload both.
> **Note:** An incoming message can be at most `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` (16MB by default, 0 for no limit). A larger one makes `read()` return `Fail` and ends the connection. Within that limit, a message is held in memory whole, so for very large data, chunk it in your application code.
> **Note:** An incoming message can be at most `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` (16MB by default, 0 for no limit), or what `set_websocket_max_message_length()` on `Server` or `WebSocketClient` sets at runtime. A larger one makes `read()` return `Fail` and ends the connection. Within that limit, a message is held in memory whole, so for very large data, chunk it in your application code.
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.