Commit Graph
824 Commits
Author SHA1 Message Date
yhirose 2e3cb0f985 Parse chunked trailers when the stream API decompresses
StreamHandle::read() parsed the trailers only on the path without a
decompressor, so response->trailers stayed empty for a compressed
chunked response. Parse them in one place for both paths, and only
after the last chunk: after a failed read it waited another read
timeout for a trailer line, and parse_trailers_if_needed() called
before the end read body bytes as trailers.
2026-10-18 12:41:23 -04:00
yhirose 07edfb86b4 Do not report a body that ends with the connection as an error
A response with neither Content-Length nor chunked encoding ends when
the connection closes (RFC 9112 6.3), but the stream API set
read_error() to ConnectionClosed on reaching that end, and SSEClient
passed it on to on_error. Only a body shorter than its Content-Length
is cut short there.
2026-10-18 12:41:23 -04:00
yhirose 106edcf606 Return a 3xx without a Location instead of failing the redirect
With follow_location on, every 3xx was taken for a redirect, so a 304
Not Modified, or any 3xx without a Location, failed with Error::Unknown.
Follow a 3xx only when it has a Location, as curl does, and return the
others as the response, as curl, Go, requests and urllib3 do. Response
handlers and content receivers now get such a response too.
2026-10-18 12:41:23 -04:00
yhirose 906a7bf04e Keep an accepting verifier from overriding Mbed TLS verification
With built-in verification on, a server certificate verifier returning
true made Mbed TLS accept a certificate its own check had rejected,
such as a self-signed one, while OpenSSL and wolfSSL still failed with
SSLServerVerification. On a client, keep the flags of Mbed TLS's own
verification, so the verifier is an additional check as on the other
backends. With verification off, the verifier is still the only check.

A server still clears them: there all three backends let an accepting
callback admit a client certificate.
2026-10-18 12:41:23 -04:00
yhirose 3744227de2 Let SSEClient::stop() interrupt a blocked read
The event loop reads through open_stream(), which takes the socket out
of the Client, so the client_.stop() in stop() could not reach it.
stop(), and the destructor with it, waited until the server sent
something or the read timeout passed, 300 seconds by default.

The loop now hands the stream's socket to stop() while it reads, and
withdraws it under the same lock before the socket is closed. stop()
shuts down the read side only: a TLS backend answers the EOF with an
alert, and writing it to a socket closed for writing raises SIGPIPE.
2026-10-18 12:41:23 -04:00
yhirose 30879bb48b Honor the PEM lengths in PemMemory
SSLServer, SSLClient and WebSocketClient take a PemMemory with
cert_pem_len and key_pem_len, but the lengths were never read: every
backend read the PEM up to a NUL, so a buffer holding exactly the PEM,
such as a std::vector<char> read from a file, was read past its end.
Hand on a NUL-terminated copy of the given number of bytes instead.

A length of 0 still means a NUL-terminated string, which is what
callers got before. The client CA already honored its length.
2026-10-18 12:41:23 -04:00
Kim, Hyuk 94cf1b5c9a Support HTTP proxies in WebSocketClient (#2635)
WebSocketClient gets the proxy setters Client has: set_proxy(),
set_proxy_basic_auth(), set_proxy_bearer_token_auth(), set_no_proxy()
and, in SSL builds, set_proxy_digest_auth(). connect() opens a CONNECT
tunnel for ws:// as well as wss:// (RFC 6455 4.1) and sends the proxy
credentials on the CONNECT request only. A proxy that does not answer
200 is reported as Error::ProxyConnection, with its status and headers
in Result.
2026-10-18 09:24:59 -04:00
yhirose 7220bdb8b2 Pass the read state to curl by address in the Expect test
CURLOPT_READDATA takes a pointer, but ServerClosesConnection passed
the read_data struct itself through curl_easy_setopt()'s varargs, so
the read callback never got its state and never produced a body.
2026-10-18 07:44:30 -04:00
yhirose 7234944098 Fix the warnings left in the 32-bit, BoringSSL and MSVC builds
time_t is 32 bits wide on 32-bit builds, so the millisecond counts in
set_max_timeout() and the streams' duration() narrowed into it
implicitly. Cast them as duration_to_sec_and_usec() already does. In
the tests, six content receivers took a uint64_t length where
ContentReceiver passes size_t, the Expect: 100-continue test kept
10 GiB in a size_t, and the Range checks compared ssize_t fields with
unsigned literals, so they now compare whole Ranges.
DoesNotReserveTheClaimedLength shifted a size_t by 41. It now claims
std::string().max_size(), the most the client accepts, and still
fails if the reserve cap is removed.

BoringSSL counts stacks in size_t, and takes the protocol version as
uint16_t and the error code as uint32_t. Walk the certificate stacks
with the decltype(count) loop used elsewhere, pass the version as
uint16_t, and cast the error code to what ERR_get_error() returns.

MSVC takes the send() length as int, so the raw send() calls left in
the tests go through detail::send_socket().
2026-10-18 00:36:18 -04:00
yhirose e97165b5dc Spawn a dynamic thread when queued jobs outnumber idle threads
ThreadPool::enqueue only spawned a dynamic thread when no thread was
idle. Threads already notified for an earlier job still counted as
idle until they took it, so a burst of connections could leave jobs
queued with no thread while the pool was below max_threads. With
keep-alive, such a connection waited until another connection closed.

Fix #2633
2026-10-17 23:55:12 -04:00
yhirose 062666f3a1 Fix the warnings clang gives when building the tests
from_chars() mixed its int digit and base into the arithmetic of an
unsigned T, a sign conversion since Content-Length is parsed as size_t.
Convert both to T first.

Comparing a uint64_t with SIZE_MAX is always false on 64-bit builds,
so the WebSocket frame length and mmap size checks tripped
-Wtautological-type-limit-compare. fits_in_size_t() checks with a
round trip instead, and the Windows branch of mmap::open() uses it too.

The raw ::send() calls in the WebSocket tests passed an int length,
which POSIX takes as size_t. Use detail::send_socket(), which handles
both.
2026-10-17 23:21:28 -04:00
yhirose e4b3865387 Revert "Encode the characters RFC 3986 doesn't allow in a client path"
This reverts commit 28f3922. Keep the path encoding settled in #2082
(#2170) and #2608 until a concrete report needs more: user input
belongs in encode_path_component(), and an embedded NUL is invalid
input.
2026-10-17 09:00:41 -04:00
yhirose 28f39225fc Encode the characters RFC 3986 doesn't allow in a client path
encode_path() sent '"', '<', '>', '\', '^', '`', '{', '|', '}', '['
and ']' raw, although RFC 3986 §3.3 doesn't allow them in a path.
Tomcat, Jetty and Undertow answer each of them with 400 by default, but
accept the percent-encoded form. It also stopped at an embedded NUL, so
"/a\0b" went out as "/a". Encode every byte outside pchar, keeping '/'
and '%' so that escapes pass through, and still encode '+', ',', ';'
and '\'' as before.

encode_request_target() now passes only the path to encode_path(). The
"http://host" of a target sent to a proxy and a CONNECT "host:port" are
sent as they are, so the brackets of an IPv6 host stay.
2026-10-17 07:36:51 -04:00
Claude 87940631e2 Check the client certificate in the PEM memory test and skip the CA dir
PemMemoryClientCertPresent now checks that the server saw the client's
certificate, as ClientCertPresent does. Before, it also passed when the
server built from PemMemory did not ask for a certificate at all.

The ClientCertPresent and ClientCertMissing helpers no longer pass
CLIENT_CA_CERT_DIR, which is "." and makes Mbed TLS parse every file in
the test directory, test binaries included, on each server they build.
The CA file is all they need. That makes TrustDirOptional, which built
the same server and client, a duplicate, so it goes. The tests that
still pass the directory keep the constructor taking one covered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGAYpQgXt95LdDQcJYgjB8
2026-10-17 05:00:23 +00:00
Claude 4836eb0fa5 Check both outcomes in the update_certs_pem client cert test
Make ClientCertStillRequired take the setup to apply, so the
update_certs_pem test runs the same pair as the verify callback tests:
a client without a certificate is rejected and one with a certificate
is still accepted. Rejection alone would also pass if the update broke
the server for every client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGAYpQgXt95LdDQcJYgjB8
2026-10-17 04:41:00 +00:00
Claude d00af3f4e6 Test client cert rejection for PEM memory servers and update_certs_pem
Split the rejection scenario out of ClientCertMissing so it can run
against any server, then use it to check that a server built from
PemMemory with a client CA, and a server whose certificates were
replaced with update_certs_pem, both reject a client without a
certificate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGAYpQgXt95LdDQcJYgjB8
2026-10-17 04:41:00 +00:00
yhirose 958f9aa82b Take resumable test sessions from the new-session callback
On BoringSSL, SSL_get1_session() after a TLS 1.3 handshake gives a
session that cannot be resumed; the tickets come only through the
new-session callback, which its documentation recommends. Store the
session from that callback, so the resumption tests resume there too.
2026-10-17 00:32:39 -04:00
yhirose f1c5068ee8 Build the tests that throw only with exceptions
ThrowingVerifyCallbackRejectsTheCertificate and
ErrorAndExceptionHandlersReplaceProvider throw from a callback, which
does not compile with CPPHTTPLIB_NO_EXCEPTIONS and -fno-exceptions.
2026-10-17 00:32:39 -04:00
yhirose 2594f17983 Drop tests the merge duplicated
Both sides of the merge tested the same behavior. Keep one test of
each: ClientCertStillRequired* for a server keeping client certificates
required, which covers a cleared callback too, VerifierStaysWithItsClient
for per-client verifiers across threads, and the Keep* redirect tests,
which share one helper. KeepSessionVerifier now also checks the error,
as the dropped SessionVerifier did.
2026-10-17 00:21:49 -04:00
yhirose 0b382e353e Merge origin/master
Both sides keep TLS verify callbacks per context. Keep this side's
storage, which lets a handshake keep the callback it is running and
takes an exception from it as a rejection, and take the other side's
apply_verify_mode(), which works out the verify mode in one place on
every backend, with Mbed TLS and wolfSSL client contexts verifying by
default. Mbed TLS installs its verify callback on every session, and
each session runs its own copy of the user's callback. The redirect
client setup that both sides added is kept once.
2026-10-17 00:08:39 -04:00
yhirose a09e00b03d Do not resume sessions on an OpenSSL context with a verify callback
A resumed handshake does not show the client certificate again, so since
OpenSSL mTLS servers resume sessions, a verify callback, such as one
checking a deny list, was skipped for as long as the ticket was good
(7200 s by default). Turn off session tickets, TLS 1.3 ones included,
and the session cache on a context with a callback, as on wolfSSL.
2026-10-16 23:52:15 -04:00
yhirose 8ca46a4db5 Bound the number of interim responses a client skips
A server sending "102 Processing" without end kept the client reading
them unless max_timeout was set. Skip at most
CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT (100) and fail with Error::Read
past it.
2026-10-16 23:52:15 -04:00
yhirose 560126bffc Accept a Unix socket path with "//" in it
Client took any string with "//" in it that it could not use as a URL
for a bad URL, so a Unix socket path such as /run/app//api.sock gave an
invalid client. Only a string that starts with a scheme and "://", or
with "//", is taken for a URL now.
2026-10-16 23:52:15 -04:00
yhirose be5043a240 Replace the Content-Type along with the content
set_content_provider() and file content added their Content-Type next to
the one an earlier set_content() had set, so the response went out with
two, and clients took the first. Each content setter now replaces it. A
Content-Type set after set_file_content() is used for the file.
2026-10-16 23:52:15 -04:00
yhirose 7bf66db6ca Close the connection after a response body with no length
A content provider without a length or chunked coding sends a body that
only the end of the connection delimits (RFC 9112 6.3), yet the response
offered keep-alive, so a keep-alive client waited for the server's idle
timeout. Send Connection: close and close after it, as Go's net/http
does. A Content-Length set by the handler is still dropped; the
overload that takes a length frames such a body.
2026-10-16 23:52:15 -04:00
yhirose 645bdab90e Reject a certificate whose verify callback throws
An exception from a verify callback unwound through the TLS library,
which is C: OpenSSL leaked the objects of the handshake, and a server
worker thread ended the process. It also left the handshake count that
update_certs_pem() waits on raised, so with a task queue that caught the
exception, every later update waited forever. Take the exception as a
rejection, and lower the count on every way out of the handshake.
2026-10-16 23:52:15 -04:00
yhirose 567e099361 Keep a verify callback alive while a handshake runs it
Replacing a verify callback, as set_server_certificate_verifier() does,
deleted the one that a handshake on another thread could be running, on
OpenSSL and wolfSSL. Handshakes now share the callback and take their
reference under a lock, and SSLClient replaces it under the lock that
guards creating a session from its context.
2026-10-16 23:52:15 -04:00
yhirose c52881cb1f Keep client certificates required after setting a verify callback
tls::set_verify_callback() set the verify mode anew, so on a server that
required client certificates it made them optional: OpenSSL and wolfSSL
dropped SSL_VERIFY_FAIL_IF_NO_PEER_CERT, and Mbed TLS went from REQUIRED
to OPTIONAL. A client without a certificate got through. Keep what the
server requires.
2026-10-16 23:52:15 -04:00
Claude 28741cb9d1 Keep the TLS error behind a failed read or write in the client's Result
A request that fails after the TLS handshake reports Error::Read or
Error::Write, and SSLSocketStream dropped the TLS error behind it. On
TLS 1.3, where a server rejects a client without a certificate only
after the handshake, ssl_error() and ssl_backend_error() were 0 instead
of showing, for example, OpenSSL's "tlsv13 alert certificate required".

SSLSocketStream now keeps the error from its last failed TLS read or
write, and SSLClient copies it into the values Result reports. Error
itself stays Read or Write.

Those values are also reset at the start of each request, so a later
successful request no longer reports the TLS error of an earlier one. A
client whose TLS context failed to set up keeps reporting that error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGAYpQgXt95LdDQcJYgjB8
2026-10-17 01:54:23 +00:00
yhirose 9a08b01ed7 Turn off session resumption on wolfSSL servers verifying clients
wolfSSL shares its session cache between contexts, so a session resumed
on a server that checks client certificates could carry a certificate
checked against another server's CA, or against a client CA replaced
since. Such a server no longer resumes sessions.
2026-10-16 21:38:40 -04:00
yhirose a7fce92ed0 Let a client resume its session with an OpenSSL mTLS server
Without a session id context, OpenSSL answers a client resuming its
session with a fatal alert once client certificates are verified, which
curl and browsers run into on their second connection. Set one on every
server context. A changed client CA still stops resumption, as fcf7568
flushes the cache and rotates the ticket keys.
2026-10-16 21:38:40 -04:00
yhirose 489fe8e504 Give a redirect client the CAs its client trusts
With set_ca_cert_store() after load_ca_cert_store(), the redirect client
trusted the earlier PEM too, though the store had replaced it, and of
several load_ca_cert_store() calls it kept only the last. Take the CAs
from the context when a store was set, and from every PEM loaded
otherwise.
2026-10-16 21:38:40 -04:00
yhirose 9724ea6b2e Skip the CN next to a DNS SAN on Mbed TLS and wolfSSL
Hostname verification on these backends fell back to the subject CN
even when the certificate had a DNS SAN, unlike X509_check_host and
RFC 6125 6.4.4. It does so only without one now. Mbed TLS also reads
the CN by its OID instead of searching the formatted DN for "CN=", and
no longer stops at an empty SAN.
2026-10-16 21:38:40 -04:00
yhirose bf08ec763c Sign the request-target sent in a Digest uri
The Digest uri and A2 took the raw path, while the request line carried
it encoded, with the params and without the fragment, so a server
comparing the two rejected the credentials. Build the target in one
place for both.
2026-10-16 21:38:40 -04:00
yhirose f29721c7d8 Treat 0 as no limit for the remaining limits
set_keep_alive_max_count(0) tripped an assert, a negative WebSocket ping
interval sent pings in a tight loop, and the form length, multipart file
count and range count macros rejected every request at 0. Make 0 mean
no limit for those, and a ping interval of 0 or less turn pings off. The
URI, header and line bounds cannot be lifted, so a static_assert keeps
them positive.
2026-10-16 21:38:40 -04:00
yhirose ad6c851d19 Bound an SSE stream by event only
An event stream has no end, but the client's payload_max_length, 100MB
by default, cut it and made the client reconnect. SSEClient lifts that
limit for its stream; each event stays bounded by
CPPHTTPLIB_SSE_MAX_EVENT_LENGTH.
2026-10-16 21:38:40 -04:00
yhirose 35342285a0 Serve files without mapping them on POSIX
Files have been read with pread() since 44658e6, so the mapping went
unused. Keep only the descriptor, open it close-on-exec and without
waiting on a FIFO, and accept only a regular file, so that a device is
no longer served as an empty body.
2026-10-16 21:38:40 -04:00
yhirose a10338a6ee Unescape quoted Content-Type parameters and escape backslashes
A quoted boundary kept its quoted-pairs, as only the quotes were taken
off, and the multipart writer sent a backslash as it was, so a name
ending in one escaped the closing quote for this library's own parser.
Unescape \" and \\ in media type parameters as in Content-Disposition,
and write a backslash as \\.
2026-10-16 21:38:40 -04:00
yhirose aa0a588ed5 Answer WebSocket control frames from one place
The read loop and the loop over the fragments of a message each answered
Ping, Pong and Close the same way. Both go through one handler now.
2026-10-16 21:38:40 -04:00
yhirose 079f2176af Put Params before the fragment of a client path
append_query_params() added the parameters after a '#', where the
fragment, which is not sent, took them along, and write_request() read a
query that came after one. Insert them before the fragment, and leave
the fragment out of the query.
2026-10-16 21:38:40 -04:00
yhirose f18f0b7576 Close the client connection after faulty response framing
A response framed by Transfer-Encoding next to a Content-Length, or an
HTTP/1.0 response with Transfer-Encoding, left the connection open for
the next request, though RFC 9112 6.1 has such framing treated as faulty
and the connection closed after it. Close it, with the check the server
makes for requests now shared.
2026-10-16 21:38:40 -04:00
Claude b4ef313cc7 Accept a write error for a client rejected after the TLS 1.3 handshake
On TLS 1.3 the server rejects a client without a certificate only after
the client has finished its side of the handshake, so the client notices
either when it writes the request or when it reads the response. CI saw
the write fail on Windows (OpenSSL) and once on macOS (Mbed TLS), which
ClientCertMissing did not accept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGAYpQgXt95LdDQcJYgjB8
2026-10-17 01:04:13 +00:00
Claude 6529de1a91 Declare tls::set_verify_callback() for the split test build
The ClientCertStillRequired tests call tls::set_verify_callback(), whose
declaration lives below the split border, so test_split failed to compile.
Declare it next to create_ca_store(), which the split build needs for the
same reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGAYpQgXt95LdDQcJYgjB8
2026-10-16 23:29:35 +00:00
yhirose 43c9c6ddf3 Frame response bodies in one place
A content provider that wrote past the length it was given put the
extra bytes after the framed body, where a keep-alive peer read them as
the next message. Write only what fits and fail the write, on both the
server and the client.

Content-Length and Transfer-Encoding a handler set were sent next to
the ones the library worked out, for ranges and compression, and a
post-routing handler could change the body after Content-Length was
set. Work both out in one place, from the body about to be written,
again after the post-routing handler; a HEAD response keeps the length
its handler gave it. A 1xx, 204 or 304 response sends no body and,
following RFC 9110 8.6, no Content-Length.

The client still sends a Content-Length or Transfer-Encoding its caller
passes, as curl and urllib3 do, and the README says these have to match
the body.
2026-10-16 19:13:12 -04:00
yhirose bc837b87fc Bound the request head by the read timeout as a whole
The read timeout applied to each read of the request line and headers,
so a client that sent them a byte now and then held a worker for as
long as it liked, and enough such clients left no worker for anyone
else. Bound the whole head by the read timeout, as the TLS handshake
already is, through a new Stream::set_max_timeout() that the socket
streams implement with their existing max timeout.

A request body is still bounded per read, and a WebSocket holds its
worker for its whole life. The README says so, and points to a
reverse proxy and the pre-request handler for untrusted clients.
2026-10-16 19:13:03 -04:00
Claude 8f21292d16 Tidy the client certificate test helpers
Use ASSERT_FALSE and FAIL() instead of their hand-written forms, drop an
unused using-directive and a comment that restated the code, and fix the
section comment that still referred to get_peer_cert().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGAYpQgXt95LdDQcJYgjB8
2026-10-16 23:02:50 +00:00
Claude 589b028022 Build the client-cert-still-required tests on the existing helpers
ClientCertPresent() and ClientCertMissing() now take a setup step for the
server, bind to any port instead of the legacy PORT, and the two new tests
are just calls to them.

ClientCertMissing also no longer checks the server certificate: with it
checked, the request failed because cert.pem is not trusted, whether or not
the server asked for a client certificate, so the test never exercised the
client certificate requirement. A rejected client is reported as
SSLConnection, or as Read on TLS 1.3, where the client only notices on its
first read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGAYpQgXt95LdDQcJYgjB8
2026-10-16 22:48:39 +00:00
Claude 300c084d6f Derive the TLS verify mode from one place per backend
set_verify_client() and set_verify_callback() each set the verify mode on
their own, and set_verify_callback() ignored whether the peer's certificate
was required. A server that required client certificates therefore stopped
requiring them as soon as a verify callback was set on its context (OpenSSL,
Mbed TLS, wolfSSL) or set and then cleared again (OpenSSL, Mbed TLS).

Compute the mode from "peer certificate required" and "callback set" in one
helper per backend and call it from set_verify_client(),
set_verify_callback() and the context constructors. The context now records
that a client verifies the server by default, so clearing a callback on a
client context restores that default.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGAYpQgXt95LdDQcJYgjB8
2026-10-16 21:12:47 +00:00
yhirose ae169c6253 Address review of the audit fixes
A retry or redirect after an early answer to Expect: 100-continue now
opens a new connection, interim responses are also skipped while
waiting for 100 Continue, and a URL Client cannot use, such as one with
userinfo, gives an invalid client. Only a 407 is passed on from a
refused CONNECT, WebSocket::close() sends only a valid payload, and the
SSE client stops on an oversized event rather than reconnect to it.

Media type parameter names and user extension mappings are matched
without case, file content is read in larger chunks from a buffer of
its own, the streaming decompression limit reports
ExceedMaxPayloadSize, and the tests use the existing single-response
server helpers. Comments and the README are brought in line.
2026-10-16 16:39:08 -04:00
yhirose 44658e660b Read served files with pread
Over TLS a file is copied out of its mapping in this process, so one
truncated while it was being served raised SIGBUS and took the whole
server down. Read it with pread, which comes up short instead.
2026-10-16 16:39:00 -04:00