Compare commits

...
25 Commits
Author SHA1 Message Date
yhirose 197d1247bd Release v0.68.0 2026-11-28 09:33:10 -05:00
yhirose 7bd99c5ddf Add Server::set_accept_handler() to refuse connections before reading
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
2026-11-27 19:42:04 -05:00
Eminyandyhirose 74180f0512 Only treat :// as a scheme separator before the path (#2701)
* 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>
2026-11-27 18:46:30 -05:00
yhirose ba9447efc4 Pass WebSocket settings to each connection as one struct
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.
2026-11-26 23:44:00 -05:00
yhirose c10c3c82cc Drop the 16 MiB WebSocket payload tests that other tests cover
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).
2026-11-26 21:52:24 -05:00
yhirose fe4cf49fcd Check bounded WebSocket reads by their timeouts, not by wall time
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.
2026-11-26 20:46:17 -05:00
0bdc860f2c Add set_websocket_max_message_length() to Server and WebSocketClient (#2696)
* 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>
2026-11-26 19:31:41 -05:00
f57e25ec92 Expose the WebSocket close status and reason (#2695)
* 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>
2026-11-26 19:31:11 -05:00
Eminy d5befb4326 Match Content-Disposition parameter names case-insensitively (#2698)
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.
2026-11-26 19:02:31 -05:00
bb00fece7c Send a Close frame when a WebSocket read fails on the peer's error (#2694)
* 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>
2026-11-26 17:55:50 -05:00
yhirose 9af51b109f Tell service failures from client failures in the online tests (#2699)
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.
2026-11-26 17:37:46 -05:00
yhirose 4995333ef2 Stop waiting for a TLS handshake once the server is stopping
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.
2026-11-24 23:58:31 -05:00
yhirose baf27c5993 Drop the heartbeat's own closed_ update and the vacuous test check
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.
2026-11-24 11:25:15 -05:00
Sayed Kaif 77b035c892 mark a websocket closed when a frame write fails
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.
2026-11-24 11:25:15 -05:00
yhirose 277b1d62a4 Retry gateway errors from httpbingo.org in online tests
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
yhirose 51b186974b Run the test suite with keep-alive parking on in CI, and mark it experimental
CPPHTTPLIB_KEEPALIVE_PARKING makes every Server start with parking on.
The OpenSSL jobs on Ubuntu (epoll) and macOS (kqueue) now also run the
whole suite built with it, which used to be done only locally. The two
tests that check the blocking path turn parking off explicitly. README
and the cookbook call the feature experimental and say that a server
whose event loop cannot be set up serves as it does without it.
2026-11-21 21:23:22 -05:00
yhirose f09081e320 Describe keep-alive parking in the Keep-Alive cookbook page 2026-11-21 21:23:22 -05:00
yhirose b2a81c0019 Add keep-alive parking (Server::set_keep_alive_parking())
A kept-alive connection holds a worker thread while it waits for its
next request, so connections beyond the thread count wait for one to be
closed, and some clients get nothing until another connection ends.

With keep-alive parking, listen() runs an event loop on the
detail::Poller instead of the blocking accept loop. A connection waiting
for its next request is parked there and goes back to a worker through
the TaskQueue when the request arrives. The handlers, content providers
and WebSocket keep their blocking API and still hold a thread while they
run. SSLServer supports it too: a worker runs the TLS handshake once the
client starts it, and the session stays with the parked connection.

It is opt-in and off by default. With it on:
- consecutive requests on a connection may run on different threads;
- when the queue is full, a connection that has not been served (or has
  not finished its TLS handshake) is closed as before, while an
  established one waits in a backlog instead of losing its request;
- a parked connection frees its read buffer, and with OpenSSL 3.0.14,
  3.1.6, 3.2.2, 3.3.1 or later also its TLS record buffers;
- handing a connection over adds roughly 10-20 us to a request;
- a subclass that overrides the private process_and_close_socket() is
  bypassed.

On two CPUs with two workers, 50 keep-alive clients of a 2.7 ms handler
were all served evenly (the slowest response took about 70 ms instead of
5 s, with 10 clients getting nothing), light requests from 50 clients
went from 79k to about 240k per second, and with 10000 idle connections
parked, 10 active clients got 95k requests per second where the old loop
served none. An idle connection costs under 1 KB, or about 15 KB with
TLS.

The old accept loop moved unchanged into accept_loop(). KeepAliveConnection
holds a parked connection, PlainConnection and SSLServer::TlsConnection
add the transport, and SSLServer::start_session() holds the session setup
and handshake that both paths use.
2026-11-21 21:23:22 -05:00
yhirose d8da76a4a5 Pass the keep-alive wait and the served count into the server loop
process_server_socket_core() now takes the function that waits for the
next request and the number of requests served so far, instead of
calling keep_alive() and counting on its own stack. Both callers pass
keep_alive() and a fresh counter, so nothing changes yet; this lets a
caller stop waiting and resume the same connection later without losing
track of keep_alive_max_count.
2026-11-21 21:23:22 -05:00
yhirose 581a615f7c Add a one-shot Poller with poll, epoll and kqueue backends
Groundwork for keep-alive parking, an opt-in event loop that parks idle
keep-alive connections instead of blocking a worker thread on each.

detail::Poller delivers readiness once per arm(), so a descriptor is
either armed (owned by the poller) or owned by whoever got the event.
wake() ends a wait() from any thread, and an armed descriptor must be
disarmed before it is closed.

- PollPoller (poll() / WSAPoll()) works everywhere.
- EpollPoller (Linux) uses EPOLLONESHOT.
- KqueuePoller (macOS, FreeBSD) uses EV_ONESHOT.
- PollerWaker carries wake() for all three: an eventfd on Linux, a socket
  pair elsewhere. detail::create_socket_pair() emulates socketpair() on
  Windows with sockets that child processes do not inherit.

make_poller() picks the best one and falls back to poll(). The contract
tests run on every backend that builds. Nothing uses the poller yet.
2026-11-21 21:23:22 -05:00
yhirose 726e4583ef Accept an uppercase URL scheme
parse_url rejected any scheme containing an uppercase letter, so
Client("HTTPS://..."), WebSocketClient("WSS://...") and a redirect to
"Location: HTTPS://..." failed, although the scheme is case-insensitive
(RFC 3986 3.1). Lowercase the scheme in parse_url so that every caller
compares one canonical form and selects TLS for it.
2026-11-20 17:47:57 -05:00
yhirose a6ab971a3f Verify WebSocketClient certificates with CryptoAPI on Windows
SSLClient verifies the server certificate chain with CryptoAPI on
Windows by default, while WebSocketClient always left it to the TLS
backend, whose snapshot of the Windows store lacks the roots Windows
fetches on demand. A wss:// connection could fail against a host that
SSLClient connects to.

WebSocketClient now makes the same decision through a shared helper,
and gets enable_windows_certificate_verification() to turn it off.

Fix #2685
2026-11-20 12:36:14 -05:00
yhirose 9458c27c7c WebSocket: a read timeout can land inside a message; TCP_NODELAY by default
A read timeout set with set_read_timeout() was reported only on a frame
boundary. One that elapsed inside a frame, or between the fragments of a
message, failed the read and closed the connection, as what had been read
could not be resumed. A small frame written in pieces often arrives in
pieces on Linux, so a server polling with a short timeout lost the
connection on its first message.

A frame is now read by ws::impl::FrameReader, which keeps what it has read
across a timeout, and WebSocket keeps the message being assembled, so
read() returns Timeout wherever the timeout lands and goes on from there at
the next call. close() waits for the peer's Close through the same reader.
read_websocket_frame() keeps its one-shot meaning.

write_websocket_frame() writes the header with the payload's first chunk
in one write, and WebSocket connections set TCP_NODELAY unless
CPPHTTPLIB_WEBSOCKET_TCP_NODELAY is false: on Linux, small messages each
way otherwise waited on Nagle's algorithm for the peer's delayed ACK, a
few in fifty around 30-40 ms late.
2026-11-20 08:18:40 -05:00
metsw24-max e7a004f509 Refuse a bare host:port Location in ClientImpl::redirect (#2684)
ClientImpl::redirect() resolved a Location with resolve_relative_location(), which hands a value with a ':' in its first segment back unchanged as having a scheme, and then parsed it with parse_url(), which also accepts a bare host[:port] so that Client("localhost:8080") works. A Location such as "internal:8080" or "127.0.0.1:6379" therefore came out with an empty scheme and a host, slipped past the http/https check, and was followed as a cross-host redirect to that host and port. A value such as "localhost:8080/x" was sent to the same host as a path without a leading '/'.

Follow only http/https URLs and references starting with '/', and refuse anything else, as an unsupported scheme already was. Network-path references such as "//host:port/x" are still followed.
2026-11-19 16:32:58 -05:00
yhirose 3544f47edd Shorten the comment on the close() check in WebSocket::read() 2026-11-18 12:39:02 -05:00
18 changed files with 3489 additions and 558 deletions

No files matched your search

+10
View File
@@ -109,6 +109,11 @@ jobs:
run: cd test && make test_split && make test_openssl_parallel run: cd test && make test_split && make test_openssl_parallel
env: env:
LSAN_OPTIONS: suppressions=lsan_suppressions.txt LSAN_OPTIONS: suppressions=lsan_suppressions.txt
- name: build and run tests with keep-alive parking on (OpenSSL)
if: matrix.tls_backend == 'openssl'
run: cd test && make test_parking_parallel
env:
LSAN_OPTIONS: suppressions=lsan_suppressions.txt
- name: build and run tests (Mbed TLS) - name: build and run tests (Mbed TLS)
if: matrix.tls_backend == 'mbedtls' if: matrix.tls_backend == 'mbedtls'
run: cd test && make test_split_mbedtls && make test_mbedtls_parallel run: cd test && make test_split_mbedtls && make test_mbedtls_parallel
@@ -417,6 +422,11 @@ jobs:
run: cd test && make test_split && make test_openssl_parallel run: cd test && make test_split && make test_openssl_parallel
env: env:
LSAN_OPTIONS: suppressions=lsan_suppressions.txt LSAN_OPTIONS: suppressions=lsan_suppressions.txt
- name: build and run tests with keep-alive parking on (OpenSSL)
if: matrix.tls_backend == 'openssl'
run: cd test && make test_parking_parallel
env:
LSAN_OPTIONS: suppressions=lsan_suppressions.txt
- name: build and run tests (Mbed TLS) - name: build and run tests (Mbed TLS)
if: matrix.tls_backend == 'mbedtls' if: matrix.tls_backend == 'mbedtls'
run: cd test && make test_split_mbedtls && make test_mbedtls_parallel run: cd test && make test_split_mbedtls && make test_mbedtls_parallel
+1
View File
@@ -43,6 +43,7 @@ test/test
test/test_mbedtls test/test_mbedtls
test/test_wolfssl test/test_wolfssl
test/test_no_tls test/test_no_tls
test/test_parking
test/server_fuzzer test/server_fuzzer
test/client_fuzzer test/client_fuzzer
test/header_parser_fuzzer test/header_parser_fuzzer
+40 -4
View File
@@ -66,7 +66,7 @@ enum ReadResult : int {
Returned by `read()`. Since `Fail` is `0`, the result works naturally in boolean contexts — `while (ws.read(msg))` continues until the connection closes. When you need to distinguish text from binary, check the return value directly. Returned by `read()`. Since `Fail` is `0`, the result works naturally in boolean contexts — `while (ws.read(msg))` continues until the connection closes. When you need to distinguish text from binary, check the return value directly.
`Timeout` is only returned for a read timeout you set yourself with `set_read_timeout()`. It means the timeout elapsed on a message boundary: nothing was consumed and the connection is still open, so you can send on it and read again. The compile-time defaults (`CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND`, 300 seconds on the server; a client waits forever) are a backstop against a peer that has gone quiet, not a request for control: when one of them elapses, `read()` returns `Fail` and closes the connection, so code that never calls `set_read_timeout()` can keep using `while (ws.read(msg))`. `Timeout` is only returned for a read timeout you set yourself with `set_read_timeout()`. It means the timeout elapsed and the connection is still open, so you can send on it and read again. It can land anywhere, inside a message too: what was read of the message is kept, and the next `read()` goes on from there. The compile-time defaults (`CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND`, 300 seconds on the server; a client waits forever) are a backstop against a peer that has gone quiet, not a request for control: when one of them elapses, `read()` returns `Fail` and closes the connection, so code that never calls `set_read_timeout()` can keep using `while (ws.read(msg))`.
**`msg` is left untouched on `Timeout`.** Because `Timeout` is non-zero, `while (ws.read(msg))` keeps looping — with the *previous* message still in `msg`. Once you set a read timeout, test the result instead: **`msg` is left untouched on `Timeout`.** Because `Timeout` is non-zero, `while (ws.read(msg))` keeps looping — with the *previous* message still in `msg`. Once you set a read timeout, test the result instead:
@@ -129,7 +129,8 @@ Passed to the handler registered with `Server::WebSocket()`. The handler runs in
// Read next message (blocks until received, returns Fail/Text/Binary/Timeout) // Read next message (blocks until received, returns Fail/Text/Binary/Timeout)
ReadResult read(std::string &msg); ReadResult read(std::string &msg);
// Send messages // Send messages. A send that fails (e.g. the write timeout elapsed) closes the
// connection, since part of the frame may already have gone out.
bool send(const std::string &data); // Text bool send(const std::string &data); // Text
bool send(const char *data, size_t len); // Binary bool send(const char *data, size_t len); // Binary
@@ -143,6 +144,14 @@ const Request &request() const;
// Check if the connection is still open // Check if the connection is still open
bool is_open() const; bool is_open() const;
// Why the connection ended, once read() has returned Fail: the code and reason
// of the peer's Close frame (any code, including 3000-4999, which are not
// named in CloseStatus), NoStatus (1005) for a Close without a code,
// ProtocolError (1002) for a malformed one, and Abnormal (1006) when the
// connection ended without one. After your own close(), the peer's reply.
CloseStatus close_status() const;
std::string close_reason() const;
// Bound how long read() waits before returning Timeout (0 waits forever). // Bound how long read() waits before returning Timeout (0 waits forever).
// Safe to call while another thread is in read(). // Safe to call while another thread is in read().
void set_read_timeout(time_t sec, time_t usec = 0); void set_read_timeout(time_t sec, time_t usec = 0);
@@ -199,6 +208,8 @@ bool send(const char *data, size_t len);
void close(CloseStatus status = CloseStatus::Normal, void close(CloseStatus status = CloseStatus::Normal,
const std::string &reason = ""); const std::string &reason = "");
bool is_open() const; bool is_open() const;
CloseStatus close_status() const;
std::string close_reason() const;
// Authentication - the same setters Client has (Basic wins over Bearer). // Authentication - the same setters Client has (Basic wins over Bearer).
void set_basic_auth(const std::string &username, const std::string &password); void set_basic_auth(const std::string &username, const std::string &password);
@@ -231,7 +242,10 @@ void set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
void set_websocket_ping_interval(time_t sec); void set_websocket_ping_interval(time_t sec);
void set_websocket_max_missed_pongs(int count); void set_websocket_max_missed_pongs(int count);
// Socket - the same setters Client has // Largest message read() accepts (see Maximum Message Length below)
void set_websocket_max_message_length(size_t length);
// Socket - the same setters Client has (TCP_NODELAY is on by default here)
void set_tcp_nodelay(bool on); void set_tcp_nodelay(bool on);
void set_address_family(int family); void set_address_family(int family);
void set_ipv6_v6only(bool on); void set_ipv6_v6only(bool on);
@@ -252,6 +266,9 @@ void enable_system_ca(bool enabled);
void set_server_certificate_verifier(tls::VerifyCallback verifier); void set_server_certificate_verifier(tls::VerifyCallback verifier);
void set_session_verifier( void set_session_verifier(
std::function<SSLVerifierResponse(tls::session_t)> verifier); std::function<SSLVerifierResponse(tls::session_t)> verifier);
// Windows only, as on SSLClient (see "Platform-specific Certificate Handling"
// in README.md)
void enable_windows_certificate_verification(bool enabled);
``` ```
## Examples ## Examples
@@ -374,6 +391,12 @@ ws.close(httplib::ws::CloseStatus::GoingAway, "shutting down");
// Server-side: close with a policy violation status // Server-side: close with a policy violation status
ws.close(httplib::ws::CloseStatus::PolicyViolation, "forbidden"); ws.close(httplib::ws::CloseStatus::PolicyViolation, "forbidden");
// Either side: why the peer closed, once read() has returned Fail
std::string msg;
while (ws.read(msg)) {}
auto code = static_cast<uint16_t>(ws.close_status()); // e.g. 1000, 1001, 4001
auto reason = ws.close_reason();
``` ```
### Accessing the Upgrade Request ### Accessing the Upgrade Request
@@ -505,12 +528,13 @@ if (ws.connect()) {
| Macro | Default | Description | | Macro | Default | Description |
|---------------------------------------------|-------------------|----------------------------------------------------------| |---------------------------------------------|-------------------|----------------------------------------------------------|
| `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` | `16777216` (16MB) | Maximum payload size per message (`0` means no limit) | | `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` | `16777216` (16MB) | Default maximum message size (`0` means no limit) |
| `CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND` | `0` | Client read timeout (seconds); `0` waits forever | | `CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND` | `0` | Client read timeout (seconds); `0` waits forever |
| `CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND` | `300` | Server read timeout (seconds) | | `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) | | `CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND` | `5` | Timeout for waiting peer's Close response (seconds) |
| `CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND` | `30` | Automatic Ping interval for heartbeat (seconds) | | `CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND` | `30` | Automatic Ping interval for heartbeat (seconds) |
| `CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS` | `0` (disabled) | Close the connection after N consecutive unacked pings | | `CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS` | `0` (disabled) | Close the connection after N consecutive unacked pings |
| `CPPHTTPLIB_WEBSOCKET_TCP_NODELAY` | `true` | Set TCP_NODELAY on WebSocket connections, so small messages do not wait on Nagle's algorithm |
### Runtime Ping Interval ### Runtime Ping Interval
@@ -546,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. **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.
```cpp
// Server side
svr.set_websocket_max_message_length(64 * 1024); // 64KB
// Client side, applied by the next connect()
ws.set_websocket_max_message_length(64 * 1024);
```
## Threading Model ## Threading Model
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. 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.
+43 -3
View File
@@ -252,7 +252,7 @@ On Windows, the CryptoAPI check can also be turned off at runtime. The TLS backe
cli.enable_windows_certificate_verification(false); cli.enable_windows_certificate_verification(false);
``` ```
`WebSocketClient` does not use CryptoAPI; the TLS backend always verifies its chain. `WebSocketClient` verifies the same way and has the same `enable_windows_certificate_verification()`.
> [!NOTE] > [!NOTE]
> When using SSL, it seems impossible to avoid SIGPIPE in all cases, since on some operating systems, SIGPIPE can only be suppressed on a per-message basis, but there is no way to make the OpenSSL library do so for its internal communications. If your program needs to avoid being terminated on SIGPIPE, the only fully general way might be to set up a signal handler for SIGPIPE to handle or ignore it yourself. > When using SSL, it seems impossible to avoid SIGPIPE in all cases, since on some operating systems, SIGPIPE can only be suppressed on a per-message basis, but there is no way to make the OpenSSL library do so for its internal communications. If your program needs to avoid being terminated on SIGPIPE, the only fully general way might be to set up a signal handler for SIGPIPE to handle or ignore it yourself.
@@ -587,9 +587,27 @@ svr.set_pre_request_handler([](const auto& req, auto& res) {
> [!NOTE] > [!NOTE]
> 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. > 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 ### 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:
``` ```
Request received Request received
@@ -919,6 +937,28 @@ svr.set_keep_alive_max_count(2); // Default is 100, 0 for no limit
svr.set_keep_alive_timeout(10); // Default is 5 svr.set_keep_alive_timeout(10); // Default is 5
``` ```
#### Keep-alive parking
> [!NOTE]
> Keep-alive parking is experimental. Its behavior may change in a future release.
```cpp
svr.set_keep_alive_parking(true); // Call it before listen()
```
Defining `CPPHTTPLIB_KEEPALIVE_PARKING` as `true` turns it on for every `Server` from the start. If the event loop cannot be set up, the server serves as it does without it.
By default, a kept-alive connection holds a worker thread while it waits for its next request, so connections beyond the thread count wait for one to be closed. With keep-alive parking, a connection waiting for its next request is handed to an event loop instead, and goes back to a worker when the request arrives. An idle connection then costs a socket and a few kilobytes instead of a thread, and connections that outnumber the threads take turns.
With it:
- Consecutive requests on a connection may run on different threads.
- When the [max queued requests](#max-queued-requests) limit is reached, only a connection that has not been served yet (or, with `SSLServer`, has not finished its TLS handshake) is closed. An established one waits for room.
- Handing the connection over to a worker adds roughly 10-20 µs to each request. It only shows when the client is as near as loopback and the handlers are very light: in our measurements, 2 connections on 2 threads served about a third fewer requests per second over loopback, but only a few percent fewer with a 250 µs round trip.
- A handler, a content provider and a WebSocket still hold their thread while they run.
- A subclass that overrides the private `process_and_close_socket()` is bypassed.
- `SSLServer` runs the TLS handshake on a worker when the client starts it. Until then the connection waits in the event loop and is closed at the keep-alive timeout, not the read timeout, and `ssl_last_error()` is not set for it.
### Client address behind a reverse proxy ### Client address behind a reverse proxy
```cpp ```cpp
@@ -962,7 +1002,7 @@ Please see [Server example](https://github.com/yhirose/cpp-httplib/blob/master/e
When a new task arrives and the queued tasks outnumber the idle threads, a temporary thread is spawned (up to the maximum). A dynamic thread exits automatically once it has waited for the idle timeout without receiving a task. The idle timeout defaults to 3 seconds, configurable via `CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT`. When a new task arrives and the queued tasks outnumber the idle threads, a temporary thread is spawned (up to the maximum). A dynamic thread exits automatically once it has waited for the idle timeout without receiving a task. The idle timeout defaults to 3 seconds, configurable via `CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT`.
A connection holds its thread while it is served: between requests up to the keep-alive timeout, through a request body sent slowly but within the read timeout, and for the whole life of a WebSocket. Enough of them leave no thread for anyone else, so in front of untrusted clients, put a reverse proxy that limits connections per client, and reject unwanted WebSocket upgrades in the pre-request handler. A connection holds its thread while it is served: between requests up to the keep-alive timeout (unless [keep-alive parking](#keep-alive-parking) is on), through a request body sent slowly but within the read timeout, and for the whole life of a WebSocket. Enough of them leave no thread for anyone else, so in front of untrusted clients, put a reverse proxy that limits connections per client, and reject unwanted WebSocket upgrades in the pre-request handler.
If you want to set the thread counts at runtime: If you want to set the thread counts at runtime:
+1 -1
View File
@@ -4,7 +4,7 @@ langs = ["en", "ja"]
[site] [site]
title = "cpp-httplib" title = "cpp-httplib"
version = "0.67.0" version = "0.68.0"
hostname = "https://yhirose.github.io" hostname = "https://yhirose.github.io"
base_path = "/cpp-httplib" base_path = "/cpp-httplib"
footer_message = "© 2026 Yuji Hirose. All rights reserved." footer_message = "© 2026 Yuji Hirose. All rights reserved."
@@ -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). 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.
```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
});
```
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). > **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).
+20 -2
View File
@@ -34,7 +34,7 @@ svr.set_keep_alive_timeout(10s);
## Tuning ideas ## Tuning ideas
**Too many idle connections eating resources** **Too many idle connections eating resources**
Shorten the timeout so idle connections drop and release their worker threads. Shorten the timeout so idle connections drop and release their worker threads. If you want to keep them open, turn on keep-alive parking instead (see below).
```cpp ```cpp
svr.set_keep_alive_timeout(2s); svr.set_keep_alive_timeout(2s);
@@ -52,6 +52,24 @@ Set `set_keep_alive_max_count(1)` and every request gets its own connection. Mos
## Relationship with the thread pool ## Relationship with the thread pool
A Keep-Alive connection holds a worker thread for its entire lifetime. The pool adds threads under load, up to its maximum thread count (4× the base count by default). If open connections outnumber that maximum, new connections wait in the queue until one closes. For thread counts, see [S21. Configure the thread pool](../s21-thread-pool). By default, a Keep-Alive connection holds a worker thread for its entire lifetime. The pool adds threads under load, up to its maximum thread count (4× the base count by default). If open connections outnumber that maximum, new connections wait in the queue until one closes. For thread counts, see [S21. Configure the thread pool](../s21-thread-pool).
## Keep idle connections off the threads
> **Note:** Keep-alive parking is experimental. Its behavior may change in a future release.
```cpp
svr.set_keep_alive_parking(true); // call it before listen()
```
With keep-alive parking, a connection waiting for its next request is handed to an event loop instead of keeping its worker thread, and goes back to a worker when the request arrives. An idle connection then costs a socket and some memory (a few kilobytes, more with TLS) instead of a thread, and connections that outnumber the threads take turns instead of waiting for one to close. `SSLServer` supports it too. Defining `CPPHTTPLIB_KEEPALIVE_PARKING` as `true` turns it on for every server.
What changes with it:
- Consecutive requests on one connection may run on different threads, so don't keep per-connection state in `thread_local` variables.
- Handing the connection over to a worker adds roughly 10-20 µs to each request. It only shows with very light handlers and a client as near as loopback.
- A handler, a content provider and a WebSocket still hold their thread while they run.
The full list is in the [README](https://github.com/yhirose/cpp-httplib/blob/master/README.md#keep-alive-parking).
> **Note:** For the client side, see [C14. Understand connection reuse and Keep-Alive behavior](../c14-keep-alive). Even when the server closes the connection on timeout, the client reconnects automatically. > **Note:** For the client side, see [C14. Understand connection reuse and Keep-Alive behavior](../c14-keep-alive). Even when the server closes the connection on timeout, the client reconnects automatically.
@@ -67,7 +67,15 @@ To notify in-flight clients that the server is going down, use `GoingAway`.
ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting"); ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting");
``` ```
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.
```cpp
std::string msg;
while (cli.read(msg)) {}
if (cli.close_status() == httplib::ws::CloseStatus::GoingAway) {
// the server is restarting: reconnect later
}
```
## Example: a tiny chat with quit ## Example: a tiny chat with quit
@@ -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. 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.
@@ -42,7 +42,7 @@ ws.set_write_timeout(10s);
## What the read timeout means ## What the read timeout means
`set_read_timeout()` applies to a single `read()` call. If no message arrives within that time, `read()` returns `ReadResult::Timeout`: **the connection is still open** and nothing was consumed, so you can send on it and read again. That is what separates it from `ReadResult::Fail`, which means the connection is gone. `set_read_timeout()` applies to a single `read()` call. If no whole message arrives within that time, `read()` returns `ReadResult::Timeout`: **the connection is still open**, and what was read of a message is kept for the next `read()`, so you can send on it and read again. That is what separates it from `ReadResult::Fail`, which means the connection is gone.
This is what lets one thread own a connection in both directions: This is what lets one thread own a connection in both directions:
@@ -67,7 +67,7 @@ Without a read timeout, `read()` blocks until a message arrives, so the thread h
Two things to know about `Timeout`: Two things to know about `Timeout`:
- It leaves `msg` untouched, and it is non-zero. So `while (ws.read(msg))` is not usable once a read timeout is set — the loop would keep running with the *previous* message still in `msg`. - It leaves `msg` untouched, and it is non-zero. So `while (ws.read(msg))` is not usable once a read timeout is set — the loop would keep running with the *previous* message still in `msg`.
- It is only reported on a message boundary. If the timeout elapses partway through a fragmented message, that message cannot be resumed and `read()` returns `Fail`. - It can land anywhere, partway through a message too. What was read of the message is kept, and the next `read()` goes on from there, so a message that arrives slowly or in fragments still comes out whole.
For connections where long idle periods are normal — waiting on notifications, for example — either leave the read timeout unset, or treat `Timeout` as the no-op it is and keep looping. For connections where long idle periods are normal — waiting on notifications, for example — either leave the read timeout unset, or treat `Timeout` as the no-op it is and keep looping.
@@ -51,4 +51,21 @@ svr.set_pre_routing_handler(
全ルート共通ではなく、ルート単位で認証を分けたいときは、[S11. Pre-request handlerでルート単位の認証を行う](../s11-pre-request)のほうが適しています。 全ルート共通ではなく、ルート単位で認証を分けたいときは、[S11. Pre-request handlerでルート単位の認証を行う](../s11-pre-request)のほうが適しています。
## 接続の段階で断る
接続元のアドレスで絞り込むだけなら、リクエストを読む前に断れます。`set_accept_handler()`は、接続を受け付けた直後、リクエストを読む前(`SSLServer`ならTLSハンドシェイクの前)に呼ばれます。`false`を返すと、その接続は何も読まずに閉じられます。
```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); // 自前の判定
});
```
このハンドラは接続を受け付けるスレッドで動くので、時間のかかる処理を入れると新しい接続がすべて待たされます。また、ソケットはサーバーが閉じるので、ハンドラの中では閉じないでください。
> **Note:** レスポンスを加工したいだけなら、`set_post_routing_handler()`のほうが適切です。[S10. Post-routing handlerでレスポンスヘッダーを追加する](../s10-post-routing)を参照してください。 > **Note:** レスポンスを加工したいだけなら、`set_post_routing_handler()`のほうが適切です。[S10. Post-routing handlerでレスポンスヘッダーを追加する](../s10-post-routing)を参照してください。
+20 -2
View File
@@ -34,7 +34,7 @@ svr.set_keep_alive_timeout(10s);
## チューニングの目安 ## チューニングの目安
**アイドル接続が多くてリソースを食う** **アイドル接続が多くてリソースを食う**
タイムアウトを短めに設定すると、遊んでいる接続がすぐに切れてスレッドが解放されます。 タイムアウトを短めに設定すると、遊んでいる接続がすぐに切れてスレッドが解放されます。接続は残したままにしたい場合は、代わりにKeep-Aliveのパーキング(後述)を有効にします。
```cpp ```cpp
svr.set_keep_alive_timeout(2s); svr.set_keep_alive_timeout(2s);
@@ -52,6 +52,24 @@ svr.set_keep_alive_max_count(1000);
## スレッドプールとの関係 ## スレッドプールとの関係
Keep-Aliveでつながりっぱなしの接続は、その間ずっとワーカースレッドを1つ占有します。スレッドプールは負荷に応じて最大スレッド数(デフォルトはベースの4倍)までスレッドを増やしますが、開いている接続数がそれを超えると、新しい接続はどれかが閉じるまでキューで待たされます。スレッド数の調整は[S21. マルチスレッド数を設定する](../s21-thread-pool)を参照してください。 デフォルトでは、Keep-Aliveでつながりっぱなしの接続は、その間ずっとワーカースレッドを1つ占有します。スレッドプールは負荷に応じて最大スレッド数(デフォルトはベースの4倍)までスレッドを増やしますが、開いている接続数がそれを超えると、新しい接続はどれかが閉じるまでキューで待たされます。スレッド数の調整は[S21. マルチスレッド数を設定する](../s21-thread-pool)を参照してください。
## アイドル接続にスレッドを持たせない
> **Note:** Keep-Aliveのパーキングは実験的な機能です。今後のリリースで挙動が変わることがあります。
```cpp
svr.set_keep_alive_parking(true); // listen()の前に呼ぶ
```
Keep-Aliveのパーキングを有効にすると、次のリクエストを待っている接続はワーカースレッドを手放してイベントループに預けられ、リクエストが届くとまたワーカーに戻ります。アイドル接続のコストはスレッド1つではなく、ソケットと少しのメモリ(数KB、TLSではもう少し多い)になり、スレッド数より多い接続も、どれかが閉じるのを待たずに順番に処理されます。`SSLServer`でも使えます。`CPPHTTPLIB_KEEPALIVE_PARKING`を`true`と定義すると、すべてのサーバーで最初から有効になります。
有効にすると変わること:
- 同じ接続の連続するリクエストが、別々のスレッドで処理されることがあります。接続ごとの状態を`thread_local`変数に持たせないでください。
- ワーカーへの接続の受け渡しで、1リクエストあたり10〜20µsほど時間が増えます。目立つのは、ハンドラがとても軽く、クライアントがループバック並みに近いときだけです。
- ハンドラ、コンテンツプロバイダ、WebSocketは、実行中は今までどおりスレッドを占有します。
すべての変更点は[README](https://github.com/yhirose/cpp-httplib/blob/master/README.md#keep-alive-parking)にあります。
> **Note:** クライアント側の挙動は[C14. 接続の再利用とKeep-Aliveの挙動を理解する](../c14-keep-alive)を参照してください。サーバーがタイムアウトで接続を切っても、クライアントは自動で再接続します。 > **Note:** クライアント側の挙動は[C14. 接続の再利用とKeep-Aliveの挙動を理解する](../c14-keep-alive)を参照してください。サーバーがタイムアウトで接続を切っても、クライアントは自動で再接続します。
@@ -67,7 +67,15 @@ cli.close(httplib::ws::CloseStatus::Normal);
ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting"); ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting");
``` ```
クライアント側の`read()`は`Fail`を返すだけで、受け取ったステータスや理由は取り出せません。再起動による切断をほかの切断と見分けたい場合は、先にメッセージ(`ws.send("restarting")`など)を送ってから`close()`を呼びましょう。 `read()`が`Fail`を返したあとは、`close_status()`と`close_reason()`で切断の理由を取り出せます。相手のCloseフレームのステータスと理由、ステータスがなければ`NoStatus` (1005)、Closeフレームなしで切れた場合は`Abnormal` (1006)です。サーバー側でもクライアント側でも同じです。
```cpp
std::string msg;
while (cli.read(msg)) {}
if (cli.close_status() == httplib::ws::CloseStatus::GoingAway) {
// サーバーが再起動中: あとで再接続する
}
```
## サンプル: 簡単なチャット終了 ## サンプル: 簡単なチャット終了
@@ -85,4 +85,4 @@ if (cli.read(buf) == httplib::ws::ReadResult::Binary) {
テキストとバイナリを混ぜて送ることもできます。たとえば「制御メッセージはJSON、データ本体はバイナリ」といったプロトコルを組み立てると、メタデータと生データを効率よく扱えます。 テキストとバイナリを混ぜて送ることもできます。たとえば「制御メッセージはJSON、データ本体はバイナリ」といったプロトコルを組み立てると、メタデータと生データを効率よく扱えます。
> **Note:** 受信できるメッセージの大きさは`CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH`(デフォルトは16MB、0なら無制限)までです。これを超えると`read()`は`Fail`を返し、接続は終了します。上限以内でもメッセージはまるごとメモリに載るので、巨大なデータを送るときは、アプリケーション側で分割して送るのが安全です。 > **Note:** 受信できるメッセージの大きさは`CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH`(デフォルトは16MB、0なら無制限)、または`Server`や`WebSocketClient`の`set_websocket_max_message_length()`で設定した値までです。これを超えると`read()`は`Fail`を返し、接続は終了します。上限以内でもメッセージはまるごとメモリに載るので、巨大なデータを送るときは、アプリケーション側で分割して送るのが安全です。
@@ -42,7 +42,7 @@ ws.set_write_timeout(10s);
## 読み取りタイムアウトの意味 ## 読み取りタイムアウトの意味
`set_read_timeout()`は「1回の`read()`呼び出し」に対するタイムアウトです。メッセージが届かないまま指定時間が経過すると`read()`は`ReadResult::Timeout`を返します。このとき**接続は開いたまま**で、1バイトも読み進めていないので、そのまま送信して読み直せます。接続が失われたことを意味する`ReadResult::Fail`とはここが違います。 `set_read_timeout()`は「1回の`read()`呼び出し」に対するタイムアウトです。メッセージがそろわないまま指定時間が経過すると`read()`は`ReadResult::Timeout`を返します。このとき**接続は開いたまま**で、途中まで読んだ分は次の`read()`に引き継がれるので、そのまま送信して読み直せます。接続が失われたことを意味する`ReadResult::Fail`とはここが違います。
1本の接続を1つのスレッドで双方向に扱えるのはこのためです。 1本の接続を1つのスレッドで双方向に扱えるのはこのためです。
@@ -67,7 +67,7 @@ while (ws.is_open()) {
`Timeout`について2点あります。 `Timeout`について2点あります。
- `msg`は書き換えられません。値も0以外なので、読み取りタイムアウトを設定した状態で`while (ws.read(msg))`と書くと、**前回のメッセージ**が`msg`に残ったままループが回り続けます。 - `msg`は書き換えられません。値も0以外なので、読み取りタイムアウトを設定した状態で`while (ws.read(msg))`と書くと、**前回のメッセージ**が`msg`に残ったままループが回り続けます。
- 報告されるのはメッセージの境界だけです。分割されたメッセージの途中でタイムアウトした場合、そのメッセージは再開できないので`read()`は`Fail`を返します。 - メッセージの途中でも報告されます。それまでに読んだ分は残り、次の`read()`はその続きから読むので、ゆっくり届くメッセージや分割されたメッセージも、そろった形で受け取れます。
通知の待受のように長時間メッセージが来ないことが正常な接続では、読み取りタイムアウトを設定しないままにするか、`Timeout`を「まだ何も来ていない」印として扱ってループを続けてください。 通知の待受のように長時間メッセージが来ないことが正常な接続では、読み取りタイムアウトを設定しないままにするか、`Timeout`を「まだ何も来ていない」印として扱ってループを続けてください。
+1576 -424
View File
File diff suppressed because it is too large. Load diff
+10 -2
View File
@@ -100,7 +100,7 @@ define run_parallel
echo "All shards passed." echo "All shards passed."
endef endef
.PHONY: test_openssl_parallel test_mbedtls_parallel test_wolfssl_parallel test_no_tls_parallel .PHONY: test_openssl_parallel test_mbedtls_parallel test_wolfssl_parallel test_no_tls_parallel test_parking_parallel
test_openssl_parallel : test test_openssl_parallel : test
$(call run_parallel,test) $(call run_parallel,test)
@@ -114,6 +114,9 @@ test_wolfssl_parallel : test_wolfssl
test_no_tls_parallel : test_no_tls test_no_tls_parallel : test_no_tls
$(call run_parallel,test_no_tls) $(call run_parallel,test_no_tls)
test_parking_parallel : test_parking
$(call run_parallel,test_parking)
proxy : test_proxy proxy : test_proxy
@echo "Starting proxy server..." @echo "Starting proxy server..."
cd proxy && \ cd proxy && \
@@ -201,6 +204,11 @@ test_no_tls : test.cc include_httplib.cc ../httplib.h Makefile
$(CXX) -o $@ -I.. $(CXXFLAGS) test.cc include_httplib.cc $(TEST_ARGS_NO_TLS) $(CXX) -o $@ -I.. $(CXXFLAGS) test.cc include_httplib.cc $(TEST_ARGS_NO_TLS)
@file $@ @file $@
# The whole suite with keep-alive parking on by default
test_parking : test.cc include_httplib.cc ../httplib.h Makefile cert.pem
$(CXX) -o $@ -I.. $(CXXFLAGS) -DCPPHTTPLIB_KEEPALIVE_PARKING=true test.cc include_httplib.cc $(TEST_ARGS)
@file $@
test_split_no_tls : test.cc ../httplib.h httplib.cc Makefile test_split_no_tls : test.cc ../httplib.h httplib.cc Makefile
$(CXX) -o $@ $(CXXFLAGS) test.cc httplib.cc $(TEST_ARGS_NO_TLS) $(CXX) -o $@ $(CXXFLAGS) test.cc httplib.cc $(TEST_ARGS_NO_TLS)
@@ -321,5 +329,5 @@ cert.pem:
./gen-certs.sh ./gen-certs.sh
clean: clean:
rm -rf test test_split test_mbedtls test_split_mbedtls test_wolfssl test_split_wolfssl test_no_tls, test_split_no_tls test_proxy test_proxy_mbedtls test_proxy_wolfssl test_benchmark server_fuzzer client_fuzzer header_parser_fuzzer url_parser_fuzzer *.pem *.0 *.o *.1 *.srl httplib.h httplib.cc _build* *.dSYM *_shard_*.log cpp-httplib rm -rf test test_split test_parking test_mbedtls test_split_mbedtls test_wolfssl test_split_wolfssl test_no_tls, test_split_no_tls test_proxy test_proxy_mbedtls test_proxy_wolfssl test_benchmark server_fuzzer client_fuzzer header_parser_fuzzer url_parser_fuzzer *.pem *.0 *.o *.1 *.srl httplib.h httplib.cc _build* *.dSYM *_shard_*.log cpp-httplib
+1710 -112
View File
File diff suppressed because it is too large. Load diff