Commit Graph
785 Commits
Author SHA1 Message Date
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
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
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
yhirose f361a08f67 Add certificate and session verifiers to WebSocketClient
A wss client could set its CAs but had no way to pin a certificate. Add
set_server_certificate_verifier() and set_session_verifier(), as
SSLClient has.
2026-10-16 16:39:00 -04:00
yhirose 7c44a7a5e1 Compare extensions, header names and media types without case
INDEX.HTML got the default type, a REMOTE_ADDR spelled in lower case got
past the guard on prohibited header names, and Multipart/Form-Data was
not taken for multipart, though RFC 9110 makes field names and media
types case-insensitive and web servers match extensions so.
2026-10-16 16:39:00 -04:00
yhirose fcf7568230 Complete server certificate updates on every backend
OpenSSL allowed client-initiated renegotiation, which runs a handshake
update_certs_pem() does not wait for, and kept sessions and ticket keys
across a change of client CAs, so a client verified under the old ones
could resume. wolfSSL added new client CAs to the old instead of
replacing them, and a bad certificate or key left Mbed TLS and wolfSSL
half updated.

Turn renegotiation off, forget the sessions and ticket keys on a client
CA change, replace wolfSSL's CAs, and check new material before swapping
it in. Note that the update must not be called from a TLS callback.
2026-10-16 16:39:00 -04:00
yhirose 314e5577b8 Match certificate names as X509_check_host does
The Mbed TLS and wolfSSL backends matched *.com, a bare *, vic*.test and
names with empty labels, which OpenSSL rejects. Require two labels after
a wildcard, none in an IDNA label and no empty label, and ignore a
trailing dot on the host, so every backend accepts the same names.
2026-10-16 16:39:00 -04:00
yhirose 7ce6c6438a Validate a WebSocket Close before echoing it
Any Close payload was echoed back, a 1-byte one, a code that may not be
sent and a reason that is not UTF-8 included. Echo a valid one and
answer the others with 1002, from one place for both read loops.
2026-10-16 16:39:00 -04:00
yhirose 162b87f325 Fail a refused CONNECT instead of returning the proxy's answer
A non-200 answer to CONNECT was returned as the response, so a proxy, or
anyone on the plain leg to it, could answer an HTTPS request as if the
origin had. Fail the request with Error::ProxyConnection for anything
but a 4xx or 5xx refusal.
2026-10-16 16:39:00 -04:00
yhirose ce7ecb633b Skip every interim response, with its header fields
Only 100 Continue was skipped, and only without header fields, so a 103
Early Hints was taken for the final response and a 100 with fields threw
the parsing off. Skip every 1xx but 101, along with its header fields.
2026-10-16 16:39:00 -04:00
yhirose 5d10305218 Close the connection after an early answer to Expect: 100-continue
When the final response came before 100 Continue, the body was never
sent but the connection was kept, so the server could read the next
request as that body. Close it after the response.
2026-10-16 16:39:00 -04:00
yhirose aaccde2122 Reject userinfo and backslashes in a URL authority
parse_url took http://user@evil.com/ for the host "user@evil.com", where
parsers that honour userinfo, or read a backslash as '/', see evil.com.
userinfo is not supported, so reject both.
2026-10-16 16:39:00 -04:00
yhirose eeaae4bc3c Serve no file whose path cannot be resolved
When the real path of a file under a mount point could not be resolved,
the check that it stays inside the mount point was skipped and the file
was served. Do not serve it from there, and refuse a mount point whose
directory cannot be resolved.
2026-10-16 16:39:00 -04:00
yhirose 455166314b Keep a %u escape that is not a character
decode_path_component dropped a %u escape of a surrogate, joining what
was on either side of it, so /ad%uD800min became /admin after a filter
had seen something else. Keep such an escape as it is.
2026-10-16 16:39:00 -04:00
yhirose 3420ba8fca Read the request line strictly
Any run of spaces or tabs separated the parts of the request line, a
fragment in the target was stripped, and an HTTP/1.1 request without
Host was served, so a server or a cache in front that follows RFC 9112
could see another request. Require a single SP between the parts, and
answer a target with '#' and an HTTP/1.1 request without Host with 400.
The client no longer sends the fragment of a URL.
2026-10-16 16:39:00 -04:00
yhirose 58957ae4da Close the connection after an ambiguous Transfer-Encoding
RFC 9112 6.1 has a server close the connection after answering a
request with both Transfer-Encoding and Content-Length, or with
Transfer-Encoding in HTTP/1.0. Close it, and send Connection: close
whenever the connection closes after a response.
2026-10-16 16:39:00 -04:00
yhirose 64bebd3b2b Honor quoted-pairs in parameter values
split_unquoted ended a quoted-string at an escaped quote, so
name="a\"; filename=evil.php" came apart into a name and a filename that
a parser in front following RFC 9110 would not see. Skip quoted-pairs
when splitting, and unescape \" and \\ in Content-Disposition values,
leaving other backslashes, such as those of a Windows path, as they are.
2026-10-16 16:39:00 -04:00
yhirose d5851d7e89 Resume the multipart header search where it stopped
A part header arriving a few bytes at a time was searched for its CRLF
from the start on every read, which made parsing it quadratic. Remember
how far the search got.
2026-10-16 16:39:00 -04:00
yhirose cadcc425b8 Bound the size of an SSE event
The SSE client buffered a line, or the data of an event, with no limit
of its own, and with payload_max_length(0) with none at all. Add
CPPHTTPLIB_SSE_MAX_EVENT_LENGTH (16MB) and end the connection with
ExceedMaxPayloadSize past it.
2026-10-16 16:39:00 -04:00
yhirose f5e11024da Bound each WebSocket fragment by what is left of the limit
Every continuation frame could be as long as the whole message limit,
and the total was checked only after appending it, so a fragmented
message could take about twice the limit. Read each fragment against
what is left, with room for a control frame between them.
2026-10-16 16:39:00 -04:00
yhirose 672255619b Do not reserve a response body by its claimed length
The client reserved what Content-Length claimed, up to
payload_max_length, before any of the body arrived, and without a limit
nothing bounded it. Reserve at most 1 MiB up front and let a longer body
grow as it is read.
2026-10-16 16:39:00 -04:00
yhirose b270564c18 Keep a Client usable when its URL cannot be used
An unsupported scheme without exceptions, or a port out of range, left
Client with no implementation, so the first request after it went
through a null pointer. Put a client in its place that reports itself
invalid and fails every request with Error::Connection.
2026-10-16 16:39:00 -04:00
yhirose 0116be0a2b Treat a zero WebSocket payload limit as none
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH = 0 rejected every frame with a
payload, while 0 means no limit for payload_max_length. Make it mean the
same here, and refuse a length that size_t cannot hold.
2026-10-16 16:39:00 -04:00
yhirose 194f392417 Treat a zero payload limit as none when decompressing a stream
set_payload_max_length(0) means no limit, but StreamHandle compared the
decompressed size against 0, so every compressed response read through
the streaming API failed.
2026-10-16 16:39:00 -04:00
yhirose 82e28aa4f3 Hash case-insensitive keys in a loop
case_ignore::hash recursed once per character of the key, and trailer
field names from the wire reach it, so a long one could overflow the
stack of a build that keeps the recursion (-O0). Hash in a loop instead,
which gives the same values.
2026-10-16 16:39:00 -04:00
yhirose 6acdc6255d Compare names as strings instead of by hash
find_content_type(), can_compress_content_type() and
is_prohibited_header_name() switched on a 26-bit hash of the name and
never compared the name itself, so any name that hashed alike was taken
for a known one. An uploaded file with an unknown extension could be
served as text/html, for one.

Compare the names themselves, and drop the hash and its literal
operator, which nothing else uses.
2026-10-16 14:57:01 -04:00
yhirose 9c51a0effa Wait for handshakes before replacing a server's certificates
update_certs_pem() replaced the certificate, key and client CAs inside
the TLS context while handshakes on other threads were still reading
them, and only the creation of a session was serialized with it. A
server rotating its certificates under load could crash.

Count the handshakes in progress, make an update wait until there are
none, and hold off new handshakes while an update is pending so that a
steady stream of them cannot keep it waiting. The wait is bounded by
the handshake timeout.
2026-10-16 12:49:22 -04:00
yhirose 41fada8c6e Bound a TLS handshake by its timeout as a whole
The handshake loops gave every wait for the socket the full timeout
again, so a peer that sent a byte now and then kept a handshake going,
and the worker serving it, for as long as it liked. Work out the
deadline once and wait only for what is left of it, on both sides and in
every backend.
2026-10-16 12:49:22 -04:00
yhirose 2b66aa65e1 Keep a client's limits and TLS checks across redirects
A cross-host redirect is followed by a new client, which did not get the
payload limit, the max timeout, the connection timeout's microseconds or
the hostname address map. Over HTTPS it also lost the session verifier,
the server certificate verifier and a store given to set_ca_cert_store(),
and fell back to the default CAs. Copy them over. The store belongs to
the original TLS context, so pass on the CA certificates it holds as PEM.

After the redirect, the original client also answered a 401 or 407 from
the new host with its own digest credentials and sent that to its own
host, with the new host's path. Return the redirected response as it is,
since the client that followed it has already answered what it could.
2026-10-16 12:02:26 -04:00
yhirose 344311c1c3 Grow a WebSocket payload only as it arrives
read_websocket_frame() resized the payload to the length a frame header
declared before reading any of it, so a 14-byte header made the peer
allocate and zero-fill up to CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH and
hold it until the read timed out. 70 such headers took a server to over
1 GB, and a client reading from a hostile server was exposed the same way.

Read the payload in CPPHTTPLIB_RECV_BUFSIZ chunks and grow it by each one,
so memory follows the bytes that actually came in.
2026-10-16 10:30:34 -04:00
yhirose 2e278fd6e9 Parse status lines without std::regex
std::regex_match recursed once per character of a status line's reason
phrase, so a server that sent one as long as a whole line overflowed the
client's stack. file_extension() and append_query_params() ran the same
kind of regex over a request path and a caller's path.

Parse all three by hand, with the same results, except that a path that
starts with '?' now gets its parameters joined with '&'. Serving a static
file no longer defers the content type lookup to keep a regex off the 304
path, so it looks the type up once.
2026-10-16 09:56:31 -04:00
yhirose b917676861 Declare set_file_content_provider for the split build
FileContentProviderStaysWithinFile, added in e374966, calls
detail::set_file_content_provider, which split.py moves into httplib.cc,
so test_split did not compile. Declare it in the test, as the other tests
that call into detail:: already do.
2026-10-16 09:56:19 -04:00
yhirose fc0e8230ba Close the connection after a partly read request body
When a content receiver returned false, or threw, partway through a body,
the drain after the response read a whole Content-Length again from where
it stopped. It swallowed the start of the next request, so the rest was
parsed as a request of its own once the handler answered below 400. A
handler that called the content reader a second time read into the next
request the same way.

Mark the body once reading starts, and if it does not finish, answer with
Connection: close and never drain it from the middle. Let each request's
body be read only once.
2026-10-16 05:32:29 -04:00
yhirose c11d95b26b Pass the session handle to wolfSSL verify callbacks
The wolfSSL verify callback set VerifyContext::session to the raw WOLFSSL
pointer, while every other tls:: function takes the WolfSSLSession that
wraps it, so passing ctx.session on from a verifier read the wrong type.
Point each WOLFSSL back to its WolfSSLSession and hand that out instead,
as the OpenSSL and Mbed TLS backends already do with their own handles.
2026-10-16 04:55:45 -04:00
yhirose 6fc677444f Keep TLS verify callbacks per context
tls::set_verify_callback(), which set_server_certificate_verifier() uses,
stored the callback in a single thread_local slot shared by every context.
A verifier was skipped when the handshake ran on another thread, ran for
other clients on the thread that set it, and could run after its client
was destroyed.

Store it with the context instead: in SSL_CTX ex_data for OpenSSL, and in
MbedTlsContext and WolfSSLContext for Mbed TLS and wolfSSL.
2026-10-16 04:55:45 -04:00
yhirose e3749669bc Keep a single content source in a Response
set_content() did not drop a content provider installed earlier, and
apply_ranges() then took the body's size as the Content-Length while the
provider was still the one written. The provider was asked for more bytes
than it had: a file under a mount point went out under the error status a
file request handler set to hide it, its mapping was read past the end,
and a user provider read past its own data.

Make every content setter clear the other sources so the last one wins,
let a body assigned directly after a provider or a file win as well, and
never read past the mapping in the file content provider.
2026-10-16 03:58:42 -04:00
yhirose 2c918f27ee Redirect a directory request with a relative Location (#2630)
* Redirect a directory request with a relative Location

The trailing-slash redirect used the request path as-is, so a path
starting with "//" produced a Location that clients read as a
network-path reference to another host. Name only the last segment,
percent-encoded and prefixed with "./", so the target always resolves
against the request URL, whatever the mount point or any prefix a
proxy put in front of it.

* Shorten the relative redirect comment
2026-10-14 16:00:03 -04:00
mervindejong 924b5cecf0 Fix redirect for mounted folders (#2628)
A directory request without a trailing slash was redirected to the path
relative to the mount point, so /mount/dir under a mount at /mount sent
Location: //dir/ instead of /mount/dir/. Redirect to the request path
with the slash appended.
2026-10-14 15:35:27 -04:00