diff --git a/README-websocket.md b/README-websocket.md index f6b029f3..e13fcc49 100644 --- a/README-websocket.md +++ b/README-websocket.md @@ -242,6 +242,9 @@ void set_connection_timeout(const std::chrono::duration &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); @@ -525,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) | @@ -567,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. diff --git a/docs-src/pages/en/cookbook/w04-websocket-binary.md b/docs-src/pages/en/cookbook/w04-websocket-binary.md index 63d64485..4c844c5f 100644 --- a/docs-src/pages/en/cookbook/w04-websocket-binary.md +++ b/docs-src/pages/en/cookbook/w04-websocket-binary.md @@ -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. diff --git a/docs-src/pages/ja/cookbook/w04-websocket-binary.md b/docs-src/pages/ja/cookbook/w04-websocket-binary.md index 5cab5aac..c7abfe02 100644 --- a/docs-src/pages/ja/cookbook/w04-websocket-binary.md +++ b/docs-src/pages/ja/cookbook/w04-websocket-binary.md @@ -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`を返し、接続は終了します。上限以内でもメッセージはまるごとメモリに載るので、巨大なデータを送るときは、アプリケーション側で分割して送るのが安全です。 diff --git a/httplib.h b/httplib.h index f25780ef..53d050f8 100644 --- a/httplib.h +++ b/httplib.h @@ -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 = @@ -4944,27 +4948,27 @@ 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, - std::function server_stopping = nullptr) + WebSocket(Stream &strm, const Request &req, bool is_server, + time_t ping_interval_sec, int max_missed_pongs, + size_t max_message_length, + std::function server_stopping = nullptr) : strm_(strm), req_(req), is_server_(is_server), ping_interval_sec_(ping_interval_sec), max_missed_pongs_(max_missed_pongs), + max_message_length_(max_message_length), server_stopping_(std::move(server_stopping)) { interrupt_reads(); start_heartbeat(); } - WebSocket( - std::unique_ptr &&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, - std::function server_stopping = nullptr) + WebSocket(std::unique_ptr &&owned_strm, const Request &req, + bool is_server, time_t ping_interval_sec, int max_missed_pongs, + size_t max_message_length, + std::function 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), + max_message_length_(max_message_length), server_stopping_(std::move(server_stopping)) { interrupt_reads(); start_heartbeat(); @@ -4985,6 +4989,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 closed_{false}; // Set when the peer stopped answering pings, to end a read() waiting on it @@ -5047,6 +5053,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); @@ -5129,6 +5136,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; @@ -14981,6 +14990,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; @@ -16403,7 +16417,8 @@ Server::process_request(Stream &strm, const std::string &remote_addr, write_timeout_sec_, write_timeout_usec_)); ws::WebSocket ws(std::move(ws_strm), req, true, websocket_ping_interval_sec_, - websocket_max_missed_pongs_, stopping); + websocket_max_missed_pongs_, + websocket_max_message_length_, stopping); ws_route->handler(req, ws); return true; } @@ -16411,7 +16426,8 @@ Server::process_request(Stream &strm, const std::string &remote_addr, // 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); + websocket_max_missed_pongs_, + websocket_max_message_length_, stopping); ws_route->handler(req, ws); return true; } @@ -24957,13 +24973,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 @@ -25003,8 +25018,7 @@ 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) { + if (max_message_length_ > 0 && message_.size() > max_message_length_) { return fail_with(CloseStatus::MessageTooBig); } if (!fin) { continue; } @@ -25377,9 +25391,9 @@ inline Result WebSocketClient::connect() { } subprotocol_ = std::move(upgrade.selected_subprotocol); - ws_ = std::unique_ptr(new WebSocket(std::move(strm), req, false, - websocket_ping_interval_sec_, - websocket_max_missed_pongs_)); + ws_ = std::unique_ptr(new WebSocket( + std::move(strm), req, false, websocket_ping_interval_sec_, + websocket_max_missed_pongs_, websocket_max_message_length_)); // 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_; @@ -25442,6 +25456,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) { diff --git a/test/test.cc b/test/test.cc index a2145404..afff7252 100644 --- a/test/test.cc +++ b/test/test.cc @@ -31096,6 +31096,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);