Compare commits

...
Author SHA1 Message Date
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
7 changed files with 627 additions and 238 deletions

No files matched your search

+32 -1
View File
@@ -144,6 +144,14 @@ const Request &request() const;
// Check if the connection is still open
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).
// Safe to call while another thread is in read().
void set_read_timeout(time_t sec, time_t usec = 0);
@@ -200,6 +208,8 @@ bool send(const char *data, size_t len);
void close(CloseStatus status = CloseStatus::Normal,
const std::string &reason = "");
bool is_open() const;
CloseStatus close_status() const;
std::string close_reason() const;
// Authentication - the same setters Client has (Basic wins over Bearer).
void set_basic_auth(const std::string &username, const std::string &password);
@@ -232,6 +242,9 @@ void set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
void set_websocket_ping_interval(time_t sec);
void set_websocket_max_missed_pongs(int count);
// 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_address_family(int family);
@@ -378,6 +391,12 @@ ws.close(httplib::ws::CloseStatus::GoingAway, "shutting down");
// Server-side: close with a policy violation status
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
@@ -509,7 +528,7 @@ if (ws.connect()) {
| 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_SERVER_READ_TIMEOUT_SECOND` | `300` | Server read timeout (seconds) |
| `CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND` | `5` | Timeout for waiting peer's Close response (seconds) |
@@ -551,6 +570,18 @@ With the default ping interval of 30 seconds, `max_missed_pongs = 2` detects a d
**The default is `0`**, which means "never close the connection because of missing pongs." Pings are still sent on the heartbeat interval, but their responses are not checked. On the server side a dead connection still does not linger: while a handler is inside `read()`, `CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND` (default **300 seconds = 5 minutes**) acts as a backstop. A client has no such backstop — it waits forever unless you set a read timeout — so there `max_missed_pongs` is what notices an unresponsive peer at all. On either side it is also the knob for noticing one *faster* than the 5-minute fallback.
### Maximum Message Length
`read()` refuses a message larger than `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` (16MB by default): it returns `Fail` and closes the connection with `MessageTooBig` (1009). A frame that announces a larger length is refused before its payload is read, and a fragmented message is refused as soon as its fragments add up to more, so the limit bounds the memory a peer can make `read()` hold. You can set it per server or per client at runtime instead of changing the compile-time macro. `0` means no limit.
```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
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.
@@ -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");
```
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
@@ -85,4 +85,4 @@ if (cli.read(buf) == httplib::ws::ReadResult::Binary) {
You can mix text and binary in the same connection. A common pattern: JSON for control messages, binary for the actual data — you get efficient handling of metadata and payload both.
> **Note:** An incoming message can be at most `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` (16MB by default, 0 for no limit). A larger one makes `read()` return `Fail` and ends the connection. Within that limit, a message is held in memory whole, so for very large data, chunk it in your application code.
> **Note:** An incoming message can be at most `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` (16MB by default, 0 for no limit), or what `set_websocket_max_message_length()` on `Server` or `WebSocketClient` sets at runtime. A larger one makes `read()` return `Fail` and ends the connection. Within that limit, a message is held in memory whole, so for very large data, chunk it in your application code.
@@ -67,7 +67,15 @@ cli.close(httplib::ws::CloseStatus::Normal);
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、データ本体はバイナリ」といったプロトコルを組み立てると、メタデータと生データを効率よく扱えます。
> **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`を返し、接続は終了します。上限以内でもメッセージはまるごとメモリに載るので、巨大なデータを送るときは、アプリケーション側で分割して送るのが安全です。
+171 -79
View File
@@ -2415,6 +2415,8 @@ public:
Server &set_websocket_max_missed_pongs(int count);
Server &set_websocket_max_message_length(size_t length);
bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
int bind_to_any_port(const std::string &host, int socket_flags = 0);
bool listen_after_bind();
@@ -2497,6 +2499,8 @@ protected:
time_t websocket_ping_interval_sec_ =
CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
size_t websocket_max_message_length_ =
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
private:
using Handlers =
@@ -4871,9 +4875,17 @@ namespace impl {
bool is_valid_utf8(const std::string &s);
// Three states: a frame, a failure (the connection cannot be read on), or a
// timeout with the stream still usable.
enum class FrameRead { Ok, Fail, Timeout };
// A frame, a failure (the connection cannot be read on), a timeout with the
// stream still usable, or a frame the peer should not have sent: one that
// breaks the protocol, or one longer than the limit.
enum class FrameRead { Ok, Fail, Timeout, ProtocolError, TooBig };
// The settings a Server or WebSocketClient gives each WebSocket it creates
struct Options {
time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
size_t max_message_length = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
};
// A frame read in as many calls as it takes. A timeout leaves what was read
// so far in place, and the next read() goes on from there, so the stream is
@@ -4918,6 +4930,13 @@ public:
const Request &request() const;
bool is_open() const;
// Why the connection ended, once read() has returned Fail (RFC 6455 7.1.5,
// 7.1.6): the code and reason of the peer's Close, NoStatus when it had no
// code, ProtocolError when it was malformed, and Abnormal when none came.
// After a close() of our own, the peer's reply is what is reported.
CloseStatus close_status() const;
std::string close_reason() const;
// Bound how long read() waits before returning Timeout. 0 waits forever.
// A server handler owns its connection's timeout this way; a client sets it
// through WebSocketClient. Safe to call while another thread is in read().
@@ -4936,27 +4955,25 @@ private:
friend class httplib::Server;
friend class httplib::ws::WebSocketClient;
WebSocket(
Stream &strm, const Request &req, bool is_server,
time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS,
WebSocket(Stream &strm, const Request &req, bool is_server,
const impl::Options &options,
std::function<bool()> server_stopping = nullptr)
: strm_(strm), req_(req), is_server_(is_server),
ping_interval_sec_(ping_interval_sec),
max_missed_pongs_(max_missed_pongs),
ping_interval_sec_(options.ping_interval_sec),
max_missed_pongs_(options.max_missed_pongs),
max_message_length_(options.max_message_length),
server_stopping_(std::move(server_stopping)) {
interrupt_reads();
start_heartbeat();
}
WebSocket(
std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS,
WebSocket(std::unique_ptr<Stream> &&owned_strm, const Request &req,
bool is_server, const impl::Options &options,
std::function<bool()> server_stopping = nullptr)
: strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
is_server_(is_server), ping_interval_sec_(ping_interval_sec),
max_missed_pongs_(max_missed_pongs),
is_server_(is_server), ping_interval_sec_(options.ping_interval_sec),
max_missed_pongs_(options.max_missed_pongs),
max_message_length_(options.max_message_length),
server_stopping_(std::move(server_stopping)) {
interrupt_reads();
start_heartbeat();
@@ -4968,6 +4985,8 @@ private:
}
void start_heartbeat();
bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
bool send_close(const std::string &payload);
void set_close_status(const std::string &payload);
Stream &strm_;
std::unique_ptr<Stream> owned_strm_;
@@ -4975,6 +4994,8 @@ private:
bool is_server_;
time_t ping_interval_sec_;
int max_missed_pongs_;
// The largest frame or message read() accepts; 0 means no limit
size_t max_message_length_;
int unacked_pings_ = 0;
std::atomic<bool> closed_{false};
// Set when the peer stopped answering pings, to end a read() waiting on it
@@ -4997,6 +5018,10 @@ private:
impl::FrameReader frames_;
std::string message_;
ReadResult message_kind_ = Fail; // Text or Binary while one is assembled
// The peer's Close, set once under read_mutex_. close_reason_ is written
// before close_status_ leaves Abnormal and is not changed after.
std::atomic<CloseStatus> close_status_{CloseStatus::Abnormal};
std::string close_reason_;
std::thread ping_thread_;
std::mutex ping_mutex_;
std::condition_variable ping_cv_;
@@ -5020,6 +5045,8 @@ public:
void close(CloseStatus status = CloseStatus::Normal,
const std::string &reason = "");
bool is_open() const;
CloseStatus close_status() const;
std::string close_reason() const;
const std::string &subprotocol() const;
void set_read_timeout(time_t sec, time_t usec = 0);
template <class Rep, class Period>
@@ -5031,6 +5058,7 @@ public:
void set_websocket_ping_interval(time_t sec);
void set_websocket_max_missed_pongs(int count);
void set_websocket_max_message_length(size_t length);
void set_tcp_nodelay(bool on);
void set_address_family(int family);
void set_ipv6_v6only(bool on);
@@ -5113,6 +5141,8 @@ private:
time_t websocket_ping_interval_sec_ =
CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
size_t websocket_max_message_length_ =
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
int address_family_ = AF_UNSPEC;
bool tcp_nodelay_ = CPPHTTPLIB_WEBSOCKET_TCP_NODELAY;
bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
@@ -6209,9 +6239,9 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
reset();
return FrameRead::Fail;
};
auto fail = [&]() {
auto reject = [&](FrameRead r) {
reset();
return FrameRead::Fail;
return r;
};
while (have_ < need_) {
@@ -6221,15 +6251,15 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
if (have_ < 2 || need_ > 2) { continue; }
// RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
if (head_[0] & 0x70) { return fail(); }
if (head_[0] & 0x70) { return reject(FrameRead::ProtocolError); }
// RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
// MUST have a payload length of 125 bytes or less
auto len7 = head_[1] & 0x7F;
if ((head_[0] & 0x08) && (!(head_[0] & 0x80) || len7 > 125)) {
return fail();
return reject(FrameRead::ProtocolError);
}
auto masked = (head_[1] & 0x80) != 0;
if (masked != expect_masked) { return fail(); }
if (masked != expect_masked) { return reject(FrameRead::ProtocolError); }
// The extended length and the mask key follow
need_ = 2 + (len7 == 126 ? 2 : len7 == 127 ? 8 : 0) + (masked ? 4 : 0);
}
@@ -6240,7 +6270,7 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
len = (static_cast<uint64_t>(head_[2]) << 8) | head_[3];
} else if (len == 127) {
// RFC 6455 Section 5.2: the most significant bit MUST be 0
if (head_[2] & 0x80) { return fail(); }
if (head_[2] & 0x80) { return reject(FrameRead::ProtocolError); }
len = 0;
for (size_t i = 2; i < 10; i++) {
len = (len << 8) | head_[i];
@@ -6249,7 +6279,7 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
// A max_len of 0 means no limit, as payload_max_length does, and a length
// size_t cannot hold (32-bit builds) is refused either way.
if ((max_len > 0 && len > max_len) || !detail::fits_in_size_t(len)) {
return fail();
return reject(FrameRead::TooBig);
}
len_ = static_cast<size_t>(len);
sized_ = true;
@@ -6292,17 +6322,39 @@ inline FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
// RFC 6455 §5.5.1, §7.4: a Close payload is empty, or a status code that may
// be sent followed by a UTF-8 reason.
// The status code a Close payload of at least 2 bytes starts with
inline uint16_t close_code(const std::string &payload) {
return static_cast<uint16_t>((static_cast<uint8_t>(payload[0]) << 8) |
static_cast<uint8_t>(payload[1]));
}
inline bool is_valid_close_payload(const std::string &payload) {
if (payload.empty()) { return true; }
if (payload.size() < 2) { return false; }
auto code = (static_cast<uint8_t>(payload[0]) << 8) |
static_cast<uint8_t>(payload[1]);
auto code = close_code(payload);
auto may_be_sent = (1000 <= code && code <= 1003) ||
(1007 <= code && code <= 1014) ||
(3000 <= code && code <= 4999);
return may_be_sent && is_valid_utf8(payload.substr(2));
}
// The payload of a Close with this status and reason. The reason is cut to fit
// a control frame (RFC 6455 Section 5.5), back to a whole UTF-8 character, and
// a code that may not be sent, such as NoStatus, goes without a payload.
inline std::string close_payload(CloseStatus status,
const std::string &reason = std::string()) {
auto code = static_cast<uint16_t>(status);
std::string payload{static_cast<char>(code >> 8),
static_cast<char>(code & 0xff)};
auto short_reason = reason.substr(0, 123);
while (!short_reason.empty() && !is_valid_utf8(short_reason)) {
short_reason.pop_back();
}
payload += short_reason;
if (!is_valid_close_payload(payload)) { payload.clear(); }
return payload;
}
} // namespace impl
} // namespace ws
@@ -10161,8 +10213,10 @@ inline void parse_disposition_params(const std::string &s, Params &params) {
std::string val;
divide_param_pair(b, e, key, val);
// Parameter names are case-insensitive (RFC 2045 §5.1)
if (!key.empty()) {
params.emplace(trim_double_quotes_copy(key), unquote_param(val));
params.emplace(case_ignore::to_lower(trim_double_quotes_copy(key)),
unquote_param(val));
}
});
}
@@ -14941,6 +14995,11 @@ inline Server &Server::set_websocket_max_missed_pongs(int count) {
return *this;
}
inline Server &Server::set_websocket_max_message_length(size_t length) {
websocket_max_message_length_ = length;
return *this;
}
inline Server &Server::set_websocket_ping_interval(time_t sec) {
websocket_ping_interval_sec_ = sec;
return *this;
@@ -16347,6 +16406,10 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
connection_closed = true;
if (websocket_upgraded) { *websocket_upgraded = true; }
auto stopping = [this] { return is_stopping(); };
ws::impl::Options options;
options.ping_interval_sec = websocket_ping_interval_sec_;
options.max_missed_pongs = websocket_max_missed_pongs_;
options.max_message_length = websocket_max_message_length_;
if (CPPHTTPLIB_WEBSOCKET_TCP_NODELAY) {
set_socket_opt(strm.socket(), IPPROTO_TCP, TCP_NODELAY, 1);
}
@@ -16361,17 +16424,14 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
strm.socket(), const_cast<tls::session_t>(req.ssl),
CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0,
write_timeout_sec_, write_timeout_usec_));
ws::WebSocket ws(std::move(ws_strm), req, true,
websocket_ping_interval_sec_,
websocket_max_missed_pongs_, stopping);
ws::WebSocket ws(std::move(ws_strm), req, true, options, stopping);
ws_route->handler(req, ws);
return true;
}
#endif
// Use WebSocket-specific read timeout instead of HTTP timeout
strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0);
ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
websocket_max_missed_pongs_, stopping);
ws::WebSocket ws(strm, req, true, options, stopping);
ws_route->handler(req, ws);
return true;
}
@@ -24860,7 +24920,25 @@ inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
return true;
}
// Sends this side's one Close frame and marks the connection closed. Returns
// false when it already was.
inline bool WebSocket::send_close(const std::string &payload) {
if (closed_.exchange(true)) { return false; }
ping_cv_.notify_all();
std::lock_guard<std::mutex> lock(write_mutex_);
detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
payload.size(), true, !is_server_);
return true;
}
inline ReadResult WebSocket::read(std::string &msg) {
// RFC 6455 Section 7.1.7: a connection failed on the peer's error is told
// why with a Close frame, and nothing more is read from it.
auto fail_with = [&](CloseStatus status) {
send_close(impl::close_payload(status));
return Fail;
};
// Answers a control frame; any other opcode here is a protocol error.
// Returns false when the connection is done.
auto handle_control = [&](Opcode op, const std::string &payload) -> bool {
@@ -24872,21 +24950,16 @@ inline ReadResult WebSocket::read(std::string &msg) {
unacked_pings_ = 0;
return true;
}
case Opcode::Close: {
case Opcode::Close:
// The reply to a close() of our own, too
set_close_status(payload);
// RFC 6455 §5.5.1: a Close is echoed back, unless its payload is
// malformed, which is answered with a protocol error instead.
if (closed_.exchange(true)) { return false; }
auto reply = payload;
if (!impl::is_valid_close_payload(payload)) {
auto code = static_cast<uint16_t>(CloseStatus::ProtocolError);
reply = {static_cast<char>(code >> 8), static_cast<char>(code & 0xff)};
}
std::lock_guard<std::mutex> lock(write_mutex_);
detail::write_websocket_frame(strm_, Opcode::Close, reply.data(),
reply.size(), true, !is_server_);
send_close(impl::is_valid_close_payload(payload)
? payload
: impl::close_payload(CloseStatus::ProtocolError));
return false;
}
default: closed_ = true; return false;
default: fail_with(CloseStatus::ProtocolError); return false;
}
};
@@ -24904,13 +24977,12 @@ inline ReadResult WebSocket::read(std::string &msg) {
std::string payload;
bool fin;
// While a message is assembled, only what is left of the limit, but room
// for a control frame, which may come between its fragments.
// What is left of the limit (all of it between messages), but always room
// for a control frame, which the limit does not cover.
auto max_len =
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH == 0 || message_kind_ == Fail
? size_t(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)
: (std::max)(size_t(125), CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH -
message_.size());
max_message_length_ == 0
? size_t(0)
: (std::max)(size_t(125), max_message_length_ - message_.size());
auto r = frames_.read(strm_, opcode, payload, fin, is_server_, max_len);
if (r != impl::FrameRead::Ok && server_stopping()) { return going_away(); }
// A timeout leaves what was read of the frame and of the message for the
@@ -24923,6 +24995,12 @@ inline ReadResult WebSocket::read(std::string &msg) {
if (r == impl::FrameRead::Timeout && read_timeout_set_ && !closed_) {
return Timeout;
}
if (r == impl::FrameRead::ProtocolError) {
return fail_with(CloseStatus::ProtocolError);
}
if (r == impl::FrameRead::TooBig) {
return fail_with(CloseStatus::MessageTooBig);
}
if (r != impl::FrameRead::Ok) {
closed_ = true;
return Fail;
@@ -24936,8 +25014,7 @@ inline ReadResult WebSocket::read(std::string &msg) {
// RFC 6455 5.4: a message is a Text or Binary frame and the continuation
// frames after it, with only control frames between them.
if (continues == (message_kind_ == Fail)) {
closed_ = true;
return Fail;
return fail_with(CloseStatus::ProtocolError);
}
if (continues) {
message_ += payload;
@@ -24945,10 +25022,8 @@ inline ReadResult WebSocket::read(std::string &msg) {
message_ = std::move(payload);
message_kind_ = opcode == Opcode::Text ? Text : Binary;
}
if (CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH > 0 &&
message_.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
closed_ = true;
return Fail;
if (max_message_length_ > 0 && message_.size() > max_message_length_) {
return fail_with(CloseStatus::MessageTooBig);
}
if (!fin) { continue; }
@@ -24978,27 +25053,7 @@ inline bool WebSocket::send(const char *data, size_t len) {
}
inline void WebSocket::close(CloseStatus status, const std::string &reason) {
if (closed_.exchange(true)) { return; }
ping_cv_.notify_all();
std::string payload;
auto code = static_cast<uint16_t>(status);
payload.push_back(static_cast<char>((code >> 8) & 0xFF));
payload.push_back(static_cast<char>(code & 0xFF));
// RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
// Close frame has 2-byte status code, so reason is limited to 123 bytes,
// cut back to a whole UTF-8 character
auto short_reason = reason.substr(0, 123);
while (!short_reason.empty() && !impl::is_valid_utf8(short_reason)) {
short_reason.pop_back();
}
payload += short_reason;
// A code that may not be sent, such as NoStatus, goes without a payload
if (!impl::is_valid_close_payload(payload)) { payload.clear(); }
{
std::lock_guard<std::mutex> lock(write_mutex_);
detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
payload.size(), true, !is_server_);
}
if (!send_close(impl::close_payload(status, reason))) { return; }
// RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
// Close response before closing the TCP connection.
@@ -25024,7 +25079,10 @@ inline void WebSocket::close(CloseStatus status, const std::string &reason) {
while (std::chrono::steady_clock::now() < deadline &&
frames_.read(strm_, op, resp, fin, is_server_, 125) ==
impl::FrameRead::Ok) {
if (op == Opcode::Close) { break; }
if (op == Opcode::Close) {
set_close_status(resp);
break;
}
}
}
@@ -25076,6 +25134,25 @@ inline const Request &WebSocket::request() const { return req_; }
inline bool WebSocket::is_open() const { return !closed_; }
inline CloseStatus WebSocket::close_status() const { return close_status_; }
inline std::string WebSocket::close_reason() const {
return close_status_ == CloseStatus::Abnormal ? std::string() : close_reason_;
}
// Called with read_mutex_ held. Only the first Close counts.
inline void WebSocket::set_close_status(const std::string &payload) {
if (close_status_ != CloseStatus::Abnormal) { return; }
if (payload.empty()) {
close_status_ = CloseStatus::NoStatus;
} else if (impl::is_valid_close_payload(payload)) {
close_reason_ = payload.substr(2);
close_status_ = static_cast<CloseStatus>(impl::close_code(payload));
} else {
close_status_ = CloseStatus::ProtocolError;
}
}
inline void WebSocket::set_read_timeout(time_t sec, time_t usec) {
// 0 waits forever here, as it does for SO_RCVTIMEO. The stream waits with
// poll(), where 0 would instead mean "return immediately", so hand it the
@@ -25318,9 +25395,12 @@ inline Result WebSocketClient::connect() {
}
subprotocol_ = std::move(upgrade.selected_subprotocol);
ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
websocket_ping_interval_sec_,
websocket_max_missed_pongs_));
impl::Options options;
options.ping_interval_sec = websocket_ping_interval_sec_;
options.max_missed_pongs = websocket_max_missed_pongs_;
options.max_message_length = websocket_max_message_length_;
ws_ = std::unique_ptr<WebSocket>(
new WebSocket(std::move(strm), req, false, options));
// The stream was created with the timeout already; tell the WebSocket
// whether it came from the caller, so read() knows to report it as Timeout.
ws_->read_timeout_set_ = read_timeout_set_;
@@ -25349,6 +25429,14 @@ inline void WebSocketClient::close(CloseStatus status,
inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
inline CloseStatus WebSocketClient::close_status() const {
return ws_ ? ws_->close_status() : CloseStatus::Abnormal;
}
inline std::string WebSocketClient::close_reason() const {
return ws_ ? ws_->close_reason() : std::string();
}
inline const std::string &WebSocketClient::subprotocol() const {
return subprotocol_;
}
@@ -25375,6 +25463,10 @@ inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
websocket_max_missed_pongs_ = count;
}
inline void WebSocketClient::set_websocket_max_message_length(size_t length) {
websocket_max_message_length_ = length;
}
inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
inline void WebSocketClient::set_address_family(int family) {
+404 -154
View File
@@ -157,28 +157,38 @@ static void read_file(const std::string &path, std::string &out) {
fs.read(&out[0], static_cast<std::streamsize>(size));
}
// httpbingo.org intermittently answers with gateway errors unrelated to the
// client under test.
static bool is_gateway_error(const Result &res) {
return res && (res->status == StatusCode::BadGateway_502 ||
// Failures of the services that the *_Online tests reach, unrelated to the
// client under test: httpbingo.org intermittently answers with gateway errors,
// and badssl.com drops connections from CI runners before it sends its
// certificate. A handshake that fails before any verdict on the certificate is
// left to the tests against local servers.
static bool is_service_failure(const Result &res) {
if (res) {
return res->status == StatusCode::BadGateway_502 ||
res->status == StatusCode::ServiceUnavailable_503 ||
res->status == StatusCode::GatewayTimeout_504);
res->status == StatusCode::GatewayTimeout_504;
}
return res.error() == Error::SSLConnection;
}
template <typename F> static Result retry_gateway_errors(F &&send) {
template <typename F> static Result retry_service_failures(F &&send) {
auto res = send();
for (auto wait : {1, 2}) {
if (!is_gateway_error(res)) { break; }
if (!is_service_failure(res)) { break; }
std::this_thread::sleep_for(std::chrono::seconds(wait));
res = send();
}
return res;
}
#define SKIP_ON_GATEWAY_ERROR(res) \
#define SKIP_ON_SERVICE_FAILURE(res) \
do { \
if (is_gateway_error(res)) { \
GTEST_SKIP() << "gateway error " << (res)->status; \
if (is_service_failure(res)) { \
if (res) { \
GTEST_SKIP() << "service failure: status " << (res)->status; \
} else { \
GTEST_SKIP() << "service failure: " << to_string((res).error()); \
} \
} \
} while (0)
@@ -2083,6 +2093,9 @@ TEST(ParseDispositionParamsTest, QuotedValues) {
} cases[] = {
{"name=\"file1\"; filename=\"a.txt\"",
{{"name", "file1"}, {"filename", "a.txt"}}},
// MIME parameter names are case-insensitive, but their values are not.
{"NaMe=\"Upload\"; FiLeNaMe=\"Report.TXT\"",
{{"name", "Upload"}, {"filename", "Report.TXT"}}},
// Whitespace around '=' and ';' is still trimmed
{"name=\"file2\" ;filename = \"a.html\"",
{{"name", "file2"}, {"filename", "a.html"}}},
@@ -2853,8 +2866,8 @@ TEST(RangeTest, FromHTTPBin_Online) {
cli.set_connection_timeout(5);
{
auto res = retry_gateway_errors([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_EQ(StatusCode::OK_200, res->status);
@@ -2862,8 +2875,8 @@ TEST(RangeTest, FromHTTPBin_Online) {
{
Headers headers = {make_range_header({{1, -1}})};
auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_EQ(StatusCode::PartialContent_206, res->status);
@@ -2871,8 +2884,8 @@ TEST(RangeTest, FromHTTPBin_Online) {
{
Headers headers = {make_range_header({{1, 10}})};
auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("bcdefghijk", res->body);
EXPECT_EQ(StatusCode::PartialContent_206, res->status);
@@ -2883,8 +2896,8 @@ TEST(RangeTest, FromHTTPBin_Online) {
// acceptable per RFC 9110 §15.3.7, so we accept either status code.
{
Headers headers = {make_range_header({{0, 31}})};
auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_TRUE(res->status == StatusCode::OK_200 ||
@@ -2893,8 +2906,8 @@ TEST(RangeTest, FromHTTPBin_Online) {
{
Headers headers = {make_range_header({{0, -1}})};
auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_TRUE(res->status == StatusCode::OK_200 ||
@@ -2906,8 +2919,8 @@ TEST(RangeTest, FromHTTPBin_Online) {
// in real servers, so we only verify the request succeeds.
{
Headers headers = {make_range_header({{0, 32}})};
auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
}
}
@@ -3222,9 +3235,9 @@ TEST(CancelTest, NoCancel_Online) {
#endif
cli.set_connection_timeout(std::chrono::seconds(5));
auto res = retry_gateway_errors(
auto res = retry_service_failures(
[&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
SKIP_ON_GATEWAY_ERROR(res);
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_EQ(StatusCode::OK_200, res->status);
@@ -3245,9 +3258,9 @@ TEST(CancelTest, WithCancelSmallPayload_Online) {
Client cli(host, port);
#endif
auto res = retry_gateway_errors(
auto res = retry_service_failures(
[&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
SKIP_ON_GATEWAY_ERROR(res);
SKIP_ON_SERVICE_FAILURE(res);
cli.set_connection_timeout(std::chrono::seconds(5));
ASSERT_TRUE(!res);
EXPECT_EQ(Error::Canceled, res.error());
@@ -3266,12 +3279,12 @@ TEST(CancelTest, WithCancelLargePayload_Online) {
#endif
cli.set_connection_timeout(std::chrono::seconds(5));
auto res = retry_gateway_errors([&] {
auto res = retry_service_failures([&] {
auto count = 0;
return cli.Get(path,
[&count](uint64_t, uint64_t) { return (count++ == 0); });
});
SKIP_ON_GATEWAY_ERROR(res);
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(!res);
EXPECT_EQ(Error::Canceled, res.error());
}
@@ -3861,18 +3874,18 @@ TEST(BaseAuthTest, FromHTTPWatch_Online) {
#endif
{
auto res = retry_gateway_errors([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
}
{
auto res = retry_gateway_errors([&] {
auto res = retry_service_failures([&] {
return cli.Get(
path, Headers{make_basic_authentication_header("hello", "world")});
});
SKIP_ON_GATEWAY_ERROR(res);
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
auto body = remove_whitespace(res->body);
EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
@@ -3882,8 +3895,8 @@ TEST(BaseAuthTest, FromHTTPWatch_Online) {
{
cli.set_basic_auth("hello", "world");
auto res = retry_gateway_errors([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
auto body = remove_whitespace(res->body);
EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
@@ -3893,16 +3906,16 @@ TEST(BaseAuthTest, FromHTTPWatch_Online) {
{
cli.set_basic_auth("hello", "bad");
auto res = retry_gateway_errors([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
}
{
cli.set_basic_auth("bad", "world");
auto res = retry_gateway_errors([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
}
@@ -3921,8 +3934,8 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
SSLClient cli(host, port);
{
auto res = retry_gateway_errors([&] { return cli.Get(unauth_path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(unauth_path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
}
@@ -3931,8 +3944,8 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
cli.set_digest_auth("hello", "world");
for (const auto &path : paths) {
auto res = retry_gateway_errors([&] { return cli.Get(path.c_str()); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
auto body = remove_whitespace(res->body);
EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
@@ -3942,8 +3955,8 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
cli.set_digest_auth("hello", "bad");
for (const auto &path : paths) {
auto res = retry_gateway_errors([&] { return cli.Get(path.c_str()); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
}
@@ -4155,8 +4168,8 @@ TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
@@ -4341,8 +4354,8 @@ TEST(AbsoluteRedirectTest, Redirect_Online) {
#endif
cli.set_follow_location(true);
auto res = retry_gateway_errors([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -4358,8 +4371,8 @@ TEST(RedirectTest, Redirect_Online) {
#endif
cli.set_follow_location(true);
auto res = retry_gateway_errors([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -4375,8 +4388,8 @@ TEST(RelativeRedirectTest, Redirect_Online) {
#endif
cli.set_follow_location(true);
auto res = retry_gateway_errors([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -4392,8 +4405,8 @@ TEST(TooManyRedirectTest, Redirect_Online) {
#endif
cli.set_follow_location(true);
auto res = retry_gateway_errors([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(!res);
EXPECT_EQ(Error::ExceedRedirectCount, res.error());
}
@@ -4420,10 +4433,10 @@ TEST(YahooRedirectTest, Redirect_Online) {
TEST(HttpsToHttpRedirectTest, Redirect_Online) {
SSLClient cli(REDIR_HOST);
cli.set_follow_location(true);
auto res = retry_gateway_errors([&] {
auto res = retry_service_failures([&] {
return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
});
SKIP_ON_GATEWAY_ERROR(res);
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -4436,9 +4449,9 @@ TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
params.emplace("url", "http://example.com");
params.emplace("status_code", "302");
auto res = retry_gateway_errors(
auto res = retry_service_failures(
[&] { return cli.Get(REDIR_PATH, params, Headers{}); });
SKIP_ON_GATEWAY_ERROR(res);
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -4450,10 +4463,10 @@ TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
Params params;
params.emplace("url", "http://example.com");
auto res = retry_gateway_errors([&] {
auto res = retry_service_failures([&] {
return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
});
SKIP_ON_GATEWAY_ERROR(res);
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -15125,16 +15138,16 @@ TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
cli.set_connection_timeout(5);
{
auto res = retry_gateway_errors([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("bcdefghijk", res->body);
EXPECT_EQ(StatusCode::PartialContent_206, res->status);
}
{
auto res = retry_gateway_errors([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("bcdefghijk", res->body);
EXPECT_EQ(StatusCode::PartialContent_206, res->status);
@@ -16818,10 +16831,8 @@ TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
// Verify client is still valid and can make connections
httplib_client.enable_server_certificate_verification(true);
auto res = httplib_client.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
// Google may return 200 or 301 depending on various factors
EXPECT_TRUE(res->status == StatusCode::OK_200 ||
res->status == StatusCode::MovedPermanently_301);
}
TEST(SSLClientTest, ServerNameIndication_Online) {
@@ -16829,8 +16840,8 @@ TEST(SSLClientTest, ServerNameIndication_Online) {
auto path = std::string{"/get"};
SSLClient cli(host, 443);
auto res = retry_gateway_errors([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
}
@@ -16839,7 +16850,8 @@ TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
// Use a site that will cause SSL verification failure due to self-signed cert
SSLClient cli("self-signed.badssl.com", 443);
cli.enable_server_certificate_verification(true);
auto res = cli.Get("/");
auto res = retry_service_failures([&] { return cli.Get("/"); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(!res);
EXPECT_EQ(Error::SSLServerVerification, res.error());
@@ -16869,7 +16881,8 @@ TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
cli.enable_server_certificate_verification(true);
cli.enable_server_hostname_verification(true);
auto res = cli.Get("/");
auto res = retry_service_failures([&] { return cli.Get("/"); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(!res);
EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
@@ -16977,16 +16990,16 @@ TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
TEST(SSLClientTest, ServerCertificateVerification1_Online) {
Client cli("https://google.com");
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
TEST(SSLClientTest, ServerCertificateVerification2_Online) {
SSLClient cli("google.com");
cli.set_ca_cert_path(CA_CERT_FILE);
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
TEST(SSLClientTest, ServerCertificateVerification3_Online) {
@@ -17051,8 +17064,8 @@ TEST(SSLClientTest, ServerCertificateVerification5_Online) {
SSLClient cli("google.com");
cli.load_ca_cert_store(cert.data(), cert.size());
const auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
TEST(SSLClientTest, ServerCertificateVerification6_Online) {
@@ -17083,8 +17096,8 @@ TEST(SSLClientTest, ServerCertificateVerification6_Online) {
SSLClient cli("google.com");
cli.load_ca_cert_store(cert, sizeof(cert));
const auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
TEST(SSLClientTest, WildcardHostNameMatch_Online) {
@@ -17095,8 +17108,8 @@ TEST(SSLClientTest, WildcardHostNameMatch_Online) {
cli.set_follow_location(true);
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
}
TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
@@ -17108,8 +17121,8 @@ TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
cli.set_follow_location(true);
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
}
TEST(SSLClientTest, HostNameMatchCase_Online) {
@@ -17120,8 +17133,8 @@ TEST(SSLClientTest, HostNameMatchCase_Online) {
cli.set_follow_location(true);
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
}
TEST(SSLClientTest, Issue2004_Online) {
@@ -17129,11 +17142,8 @@ TEST(SSLClientTest, Issue2004_Online) {
client.set_follow_location(true);
auto res = client.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
auto body = res->body;
EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
}
TEST(SSLClientTest, ErrorReportingWhenInvalid) {
@@ -18877,10 +18887,10 @@ TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
Client cli(REDIR_HOST);
cli.set_follow_location(true);
auto res = retry_gateway_errors([&] {
auto res = retry_service_failures([&] {
return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
});
SKIP_ON_GATEWAY_ERROR(res);
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
@@ -18894,9 +18904,9 @@ TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
params.emplace("url", "http://example.com");
params.emplace("status_code", "302");
auto res = retry_gateway_errors(
auto res = retry_service_failures(
[&] { return cli.Get(REDIR_PATH, params, Headers{}); });
SKIP_ON_GATEWAY_ERROR(res);
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -18908,10 +18918,10 @@ TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
Params params;
params.emplace("url", "http://example.com");
auto res = retry_gateway_errors([&] {
auto res = retry_service_failures([&] {
return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
});
SKIP_ON_GATEWAY_ERROR(res);
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -19287,8 +19297,8 @@ TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
cli.enable_server_certificate_verification(true);
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
// The custom CA remains effective when combined with the system CA
@@ -19591,8 +19601,8 @@ TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
cli.enable_server_certificate_verification(true);
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
// The system CA policy must carry over to the client created internally for
@@ -28695,7 +28705,7 @@ TEST(WebSocketTest, RSVBitsMustBeZero) {
bool fin;
EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail);
ws::impl::FrameRead::ProtocolError);
}
// RSV2 set (0x20)
@@ -28707,7 +28717,7 @@ TEST(WebSocketTest, RSVBitsMustBeZero) {
bool fin;
EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail);
ws::impl::FrameRead::ProtocolError);
}
// RSV3 set (0x10)
@@ -28719,7 +28729,7 @@ TEST(WebSocketTest, RSVBitsMustBeZero) {
bool fin;
EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail);
ws::impl::FrameRead::ProtocolError);
}
// No RSV bits set - should succeed
@@ -28754,7 +28764,7 @@ TEST(WebSocketTest, ControlFrameValidation) {
bool fin;
EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail);
ws::impl::FrameRead::ProtocolError);
}
// Close with FIN=0 - must be rejected
@@ -28769,7 +28779,7 @@ TEST(WebSocketTest, ControlFrameValidation) {
bool fin;
EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail);
ws::impl::FrameRead::ProtocolError);
}
// Ping with payload_len=126 (extended length) - must be rejected
@@ -28787,7 +28797,7 @@ TEST(WebSocketTest, ControlFrameValidation) {
bool fin;
EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail);
ws::impl::FrameRead::ProtocolError);
}
// Ping with FIN=1 and payload_len=125 - should succeed
@@ -28828,7 +28838,7 @@ TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
bool fin;
EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail);
ws::impl::FrameRead::ProtocolError);
}
// MSB clear - should pass length parsing (will be rejected by max_len,
@@ -29255,6 +29265,8 @@ TEST_F(WebSocketIntegrationTest, CloseHandshake) {
std::string msg;
EXPECT_FALSE(client.read(msg));
EXPECT_FALSE(client.is_open());
EXPECT_EQ(ws::CloseStatus::Normal, client.close_status());
EXPECT_EQ("", client.close_reason());
}
TEST_F(WebSocketIntegrationTest, LargeMessage) {
@@ -29386,41 +29398,6 @@ TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
EXPECT_TRUE(client.is_open());
}
TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
"/ws-echo");
client.set_read_timeout(5, 0);
ASSERT_TRUE(client.connect());
// Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
// The server should reject it and close the connection.
std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
client.send(oversized);
// The server's read() should have failed due to payload limit,
// so our read() should return false (connection closed).
std::string msg;
EXPECT_FALSE(client.read(msg));
}
TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
"/ws-echo");
client.set_read_timeout(10, 0);
ASSERT_TRUE(client.connect());
// Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
// This should succeed.
std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
ASSERT_TRUE(client.send(at_limit));
std::string msg;
ASSERT_TRUE(client.read(msg));
EXPECT_EQ(at_limit.size(), msg.size());
client.close();
}
TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
"/nonexistent");
@@ -29478,15 +29455,24 @@ TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
std::string msg;
EXPECT_FALSE(client.read(msg));
EXPECT_FALSE(client.is_open());
EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
EXPECT_EQ("shutting down", client.close_reason());
// A copy, so it outlives a reconnect that replaces the connection
static_assert(
std::is_same<decltype(client.close_reason()), std::string>::value, "");
}
TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
"/ws-echo");
EXPECT_EQ(ws::CloseStatus::Abnormal, client.close_status());
ASSERT_TRUE(client.connect());
client.close(ws::CloseStatus::GoingAway, "client leaving");
EXPECT_FALSE(client.is_open());
// The server echoes the Close it receives
EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
EXPECT_EQ("client leaving", client.close_reason());
}
TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
@@ -30963,6 +30949,24 @@ static std::string masked_frame(uint8_t first_byte,
return f + payload;
}
// Sends frames on a new raw connection to /ws and returns the first n bytes the
// server sends back, or what came before it closed.
static std::string raw_websocket_reply(int port, const std::string &frames,
size_t n) {
auto sock = connect_raw_websocket(port, "/ws");
if (sock == INVALID_SOCKET) { return std::string(); }
detail::send_socket(sock, frames.data(), frames.size(), 0);
std::string reply;
char buf[256];
while (reply.size() < n) {
auto got = ::recv(sock, buf, sizeof(buf), 0);
if (got <= 0) { break; }
reply.append(buf, static_cast<size_t>(got));
}
detail::close_socket(sock);
return reply;
}
TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
std::atomic<bool> done{false};
std::string received;
@@ -31057,6 +31061,86 @@ TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
EXPECT_TRUE(read_ended);
}
TEST(WebSocketTest, ServerMaxMessageLength) {
Server svr;
svr.set_websocket_ping_interval(0);
svr.set_websocket_max_message_length(100);
svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
std::string msg;
while (ws.read(msg)) {
ws.send(msg);
}
});
auto port = svr.bind_to_any_port("127.0.0.1");
std::thread t([&]() { svr.listen_after_bind(); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
});
svr.wait_until_ready();
const std::string ping(110, 'p');
const std::string half(50, 'a');
const std::string over(60, 'b');
const std::string too_big("\x88\x02\x03\xf1"); // Close 1009
// A Ping longer than the limit is answered, since the limit is for
// messages. A message at the limit is echoed, and one over it is refused
// although each of its frames is within it.
EXPECT_EQ(std::string("\x8a\x6e") + ping + "\x81\x64" + half + half + too_big,
raw_websocket_reply(
port,
masked_frame(0x89, ping) + masked_frame(0x01, half) +
masked_frame(0x80, half) + masked_frame(0x01, over) +
masked_frame(0x80, over),
2 + ping.size() + 2 + 2 * half.size() + too_big.size()));
// A header that announces more than the limit is refused before its payload
EXPECT_EQ(too_big, raw_websocket_reply(port,
std::string("\x82\xfe\x03\xe8", 4) +
std::string(4, '\0'),
too_big.size()));
}
TEST(WebSocketTest, ClientMaxMessageLength) {
Server svr;
svr.set_websocket_ping_interval(0);
svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
ws.send(std::string(1024, 'a'));
ws.send(std::string(2048, 'b'));
std::string msg;
while (ws.read(msg)) {}
});
auto port = svr.bind_to_any_port(HOST);
std::thread t([&]() { svr.listen_after_bind(); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
});
svr.wait_until_ready();
ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
client.set_read_timeout(5, 0);
client.set_websocket_max_message_length(1024);
ASSERT_TRUE(client.connect());
std::string msg;
ASSERT_EQ(ws::Text, client.read(msg));
EXPECT_EQ(1024u, msg.size());
EXPECT_EQ(ws::Fail, client.read(msg));
EXPECT_FALSE(client.is_open());
// 0 lifts the limit
client.set_websocket_max_message_length(0);
ASSERT_TRUE(client.connect());
EXPECT_EQ(ws::Text, client.read(msg));
EXPECT_EQ(ws::Text, client.read(msg));
EXPECT_EQ(2048u, msg.size());
}
TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
Server svr;
svr.set_websocket_ping_interval(-1);
@@ -31271,12 +31355,13 @@ TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
// A handler that bounds its reads gets control back within its timeout even
// while a message arrives in pieces, and the message whole once the last has
// come: what was read of it is kept across the timeouts. Each of `pieces` is
// sent a while after the one before, much longer than the handler's timeout.
// sent once read() has timed out twice since the one before was sent, so the
// second timeout came from a read() that had that piece to take.
static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
const std::string &expected) {
std::atomic<bool> done{false};
std::atomic<int> timeouts{0};
std::string received;
std::chrono::steady_clock::duration longest{};
Server svr;
svr.set_websocket_ping_interval(0);
@@ -31284,11 +31369,9 @@ static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
ws.set_read_timeout(0, 10000);
std::string msg;
ws::ReadResult r;
do {
auto began = std::chrono::steady_clock::now();
r = ws.read(msg);
longest = (std::max)(longest, std::chrono::steady_clock::now() - began);
} while (r == ws::Timeout);
while ((r = ws.read(msg)) == ws::Timeout) {
timeouts++;
}
if (r == ws::Text) { received = msg; }
done = true;
});
@@ -31304,19 +31387,24 @@ static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
auto sock = connect_raw_websocket(port, "/ws");
ASSERT_NE(INVALID_SOCKET, sock);
auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
for (const auto &piece : pieces) {
ASSERT_EQ(static_cast<ssize_t>(piece.size()),
detail::send_socket(sock, piece.data(), piece.size(), 0));
std::this_thread::sleep_for(std::chrono::milliseconds(200));
// Each piece goes out at once, not held back by Nagle's algorithm
ASSERT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
for (size_t i = 0; i < pieces.size(); i++) {
ASSERT_EQ(static_cast<ssize_t>(pieces[i].size()),
detail::send_socket(sock, pieces[i].data(), pieces[i].size(), 0));
if (i + 1 == pieces.size()) { break; }
auto before = timeouts.load();
for (int j = 0; j < 5000 && timeouts < before + 2; j++) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
ASSERT_GE(timeouts.load(), before + 2) << "piece " << i;
}
for (int i = 0; i < 500 && !done; i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
for (int i = 0; i < 5000 && !done; i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
ASSERT_TRUE(done);
EXPECT_EQ(expected, received);
// Far under the 200 ms between the pieces, however loaded the machine
EXPECT_LT(longest, std::chrono::milliseconds(150));
}
TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
@@ -31360,24 +31448,186 @@ TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
// Also between the fragments of a message.
for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
for (const auto &c : cases) {
auto sock = connect_raw_websocket(port, "/ws");
ASSERT_NE(INVALID_SOCKET, sock);
auto frames = prefix + masked_frame(0x88, c.first);
detail::send_socket(sock, frames.data(), frames.size(), 0);
EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
c.second,
raw_websocket_reply(port, prefix + masked_frame(0x88, c.first),
2 + c.second.size()));
}
}
}
TEST(WebSocketTest, FailsABadFrameWithACloseStatus) {
Server svr;
svr.set_websocket_ping_interval(0);
svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
std::string msg;
while (ws.read(msg)) {}
});
auto port = svr.bind_to_any_port("127.0.0.1");
std::thread t([&]() { svr.listen_after_bind(); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
});
svr.wait_until_ready();
// A header that announces one byte over the limit, and none of its payload
std::string too_big = "\x82\xff";
uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1;
for (int shift = 56; shift >= 0; shift -= 8) {
too_big += static_cast<char>((len >> shift) & 0xff);
}
too_big.append(4, '\0');
const std::string protocol_error("\x03\xea"); // 1002
const std::string too_big_error("\x03\xf1"); // 1009
// What the client sends and the status the server closes with
std::vector<std::pair<std::string, std::string>> cases = {
{masked_frame(0xc1, "a"), protocol_error}, // RSV1
{std::string("\x81\x01") + "a", protocol_error}, // not masked
{masked_frame(0x09, ""), protocol_error}, // fragmented Ping
{masked_frame(0x83, ""), protocol_error}, // reserved opcode
{masked_frame(0x8b, ""), protocol_error}, // reserved control opcode
{masked_frame(0x80, "a"), protocol_error}, // continuation, no start
{masked_frame(0x01, "a") + masked_frame(0x81, "b"),
protocol_error}, // a new message inside a fragmented one
{std::string("\x81\xff\x80", 3) + std::string(11, '\0'),
protocol_error}, // 64-bit length with its top bit set
{too_big, too_big_error},
};
for (const auto &c : cases) {
EXPECT_EQ(std::string("\x88\x02") + c.second,
raw_websocket_reply(port, c.first, 4));
}
}
TEST(WebSocketTest, ClientFailsAMaskedFrameWithProtocolError) {
SilentListener listener;
ASSERT_NE(INVALID_SOCKET, listener.sock);
// A peer that completes the handshake, then sends a masked frame, which a
// server must never do, and keeps what the client sends back.
std::string reply;
std::thread peer([&]() {
auto sock = listener.accept();
if (sock == INVALID_SOCKET) { return; }
std::string req;
char c;
while (req.find("\r\n\r\n") == std::string::npos &&
::recv(sock, &c, 1, 0) == 1) {
req += c;
}
const std::string field = "Sec-WebSocket-Key: ";
auto pos = req.find(field);
if (pos != std::string::npos) {
pos += field.size();
auto key = req.substr(pos, req.find("\r\n", pos) - pos);
auto res = "HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: " +
detail::websocket_accept_key(key) + "\r\n\r\n" +
masked_frame(0x81, "a");
detail::send_socket(sock, res.data(), res.size(), 0);
// FIN + Close, masked with a length of 2, the mask key, the code
char buf[256];
while (reply.size() < 2 + c.second.size()) {
while (reply.size() < 8) {
auto n = ::recv(sock, buf, sizeof(buf), 0);
if (n <= 0) { break; }
reply.append(buf, static_cast<size_t>(n));
}
}
detail::close_socket(sock);
EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
c.second,
reply);
});
ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(listener.port) +
"/ws");
auto connected = static_cast<bool>(client.connect());
std::string msg;
auto r = connected ? client.read(msg) : ws::Fail;
peer.join();
ASSERT_TRUE(connected);
EXPECT_EQ(ws::Fail, r);
detail::BufferStream strm;
strm.write(reply.data(), reply.size());
ws::Opcode opcode;
std::string payload;
bool fin;
ASSERT_EQ(
ws::impl::FrameRead::Ok,
ws::impl::read_websocket_frame(strm, opcode, payload, fin, true, 125));
EXPECT_EQ(ws::Opcode::Close, opcode);
EXPECT_EQ(std::string("\x03\xea"), payload);
}
// What a handler sees of the peer's close once read() has failed
TEST(WebSocketTest, HandlerSeesThePeersClose) {
std::mutex m;
std::condition_variable cv;
size_t handled = 0;
uint16_t seen_status = 0;
std::string seen_reason;
Server svr;
svr.set_websocket_ping_interval(0);
svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
std::string msg;
while (ws.read(msg)) {}
std::lock_guard<std::mutex> lock(m);
seen_status = static_cast<uint16_t>(ws.close_status());
seen_reason = ws.close_reason();
handled++;
cv.notify_one();
});
auto port = svr.bind_to_any_port("127.0.0.1");
std::thread t([&]() { svr.listen_after_bind(); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
});
svr.wait_until_ready();
auto expect_seen = [&](size_t n, uint16_t status, const std::string &reason,
const char *label) {
std::unique_lock<std::mutex> lock(m);
ASSERT_TRUE(cv.wait_for(lock, std::chrono::seconds(5), [&] {
return handled == n;
})) << label;
EXPECT_EQ(status, seen_status) << label;
EXPECT_EQ(reason, seen_reason) << label;
};
// What a raw client sends before it drops the connection
struct Case {
const char *label;
std::string sent;
uint16_t status;
std::string reason;
};
std::vector<Case> cases = {
{"application code", masked_frame(0x88, "\x0f\xa1logout"), 4001,
"logout"},
{"normal", masked_frame(0x88, "\x03\xe8"), 1000, ""},
{"no status", masked_frame(0x88, ""), 1005, ""},
{"malformed", masked_frame(0x88, "\x03"), 1002, ""},
{"no Close", masked_frame(0x81, "hi"), 1006, ""},
};
for (size_t i = 0; i < cases.size(); i++) {
auto sock = connect_raw_websocket(port, "/ws");
ASSERT_NE(INVALID_SOCKET, sock);
detail::send_socket(sock, cases[i].sent.data(), cases[i].sent.size(), 0);
detail::close_socket(sock);
expect_seen(i + 1, cases[i].status, cases[i].reason, cases[i].label);
}
ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws");
ASSERT_TRUE(client.connect());
client.close(static_cast<ws::CloseStatus>(4001), "logout");
expect_seen(cases.size() + 1, 4001, "logout", "WebSocketClient");
}
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT