mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-11-28 21:08:28 +00:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
197d1247bd | ||
|
|
7bd99c5ddf | ||
|
|
74180f0512 | ||
|
|
ba9447efc4 | ||
|
|
c10c3c82cc | ||
|
|
fe4cf49fcd | ||
|
|
0bdc860f2c | ||
|
|
f57e25ec92 | ||
|
|
d5befb4326 | ||
|
|
bb00fece7c | ||
|
|
9af51b109f | ||
|
|
4995333ef2 | ||
|
|
baf27c5993 | ||
|
|
77b035c892 | ||
|
|
277b1d62a4 |
No files matched your search
+34
-2
@@ -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,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_ping_interval(time_t sec);
|
||||||
void set_websocket_max_missed_pongs(int count);
|
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)
|
// 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);
|
||||||
@@ -377,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
|
||||||
@@ -508,7 +528,7 @@ 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) |
|
||||||
@@ -550,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.
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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).
|
||||||
@@ -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.
|
||||||
@@ -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)を参照してください。
|
||||||
@@ -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`を返し、接続は終了します。上限以内でもメッセージはまるごとメモリに載るので、巨大なデータを送るときは、アプリケーション側で分割して送るのが安全です。
|
||||||
@@ -8,8 +8,8 @@
|
|||||||
#ifndef CPPHTTPLIB_HTTPLIB_H
|
#ifndef CPPHTTPLIB_HTTPLIB_H
|
||||||
#define CPPHTTPLIB_HTTPLIB_H
|
#define CPPHTTPLIB_HTTPLIB_H
|
||||||
|
|
||||||
#define CPPHTTPLIB_VERSION "0.67.0"
|
#define CPPHTTPLIB_VERSION "0.68.0"
|
||||||
#define CPPHTTPLIB_VERSION_NUM "0x004300"
|
#define CPPHTTPLIB_VERSION_NUM "0x004400"
|
||||||
|
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
|
#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
|
||||||
@@ -925,7 +925,7 @@ inline bool parse_url(const std::string &url, UrlComponents &uc) {
|
|||||||
size_t pos = 0;
|
size_t pos = 0;
|
||||||
|
|
||||||
auto sep = url.find("://");
|
auto sep = url.find("://");
|
||||||
if (sep != std::string::npos) {
|
if (sep < url.find_first_of("/?#")) {
|
||||||
// Schemes are case-insensitive (RFC 3986 3.1)
|
// Schemes are case-insensitive (RFC 3986 3.1)
|
||||||
uc.scheme = case_ignore::to_lower(url.substr(0, sep));
|
uc.scheme = case_ignore::to_lower(url.substr(0, sep));
|
||||||
|
|
||||||
@@ -2298,6 +2298,8 @@ public:
|
|||||||
|
|
||||||
using StartHandler = std::function<void()>;
|
using StartHandler = std::function<void()>;
|
||||||
|
|
||||||
|
using AcceptHandler = std::function<bool(socket_t sock)>;
|
||||||
|
|
||||||
using WebSocketHandler =
|
using WebSocketHandler =
|
||||||
std::function<void(const Request &, ws::WebSocket &)>;
|
std::function<void(const Request &, ws::WebSocket &)>;
|
||||||
using SubProtocolSelector =
|
using SubProtocolSelector =
|
||||||
@@ -2363,6 +2365,8 @@ public:
|
|||||||
|
|
||||||
Server &set_start_handler(StartHandler handler);
|
Server &set_start_handler(StartHandler handler);
|
||||||
|
|
||||||
|
Server &set_accept_handler(AcceptHandler handler);
|
||||||
|
|
||||||
Server &set_logger(Logger logger);
|
Server &set_logger(Logger logger);
|
||||||
Server &set_pre_compression_logger(Logger logger);
|
Server &set_pre_compression_logger(Logger logger);
|
||||||
Server &set_error_logger(ErrorLogger error_logger);
|
Server &set_error_logger(ErrorLogger error_logger);
|
||||||
@@ -2415,6 +2419,8 @@ public:
|
|||||||
|
|
||||||
Server &set_websocket_max_missed_pongs(int count);
|
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);
|
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);
|
int bind_to_any_port(const std::string &host, int socket_flags = 0);
|
||||||
bool listen_after_bind();
|
bool listen_after_bind();
|
||||||
@@ -2436,8 +2442,9 @@ protected:
|
|||||||
const std::function<void(Request &)> &setup_request,
|
const std::function<void(Request &)> &setup_request,
|
||||||
bool *websocket_upgraded = nullptr);
|
bool *websocket_upgraded = nullptr);
|
||||||
|
|
||||||
// Runs the per-connection serving loop and stops an exception thrown by a
|
// Runs a user callback, or the per-connection serving loop that calls user
|
||||||
// user callback from escaping the worker thread.
|
// callbacks, and stops an exception thrown by one from escaping the
|
||||||
|
// server's threads.
|
||||||
//
|
//
|
||||||
// process_request() wraps only routing() and the hooks before a WebSocket
|
// process_request() wraps only routing() and the hooks before a WebSocket
|
||||||
// upgrade in a try/catch. Content providers, the post-routing, error,
|
// upgrade in a try/catch. Content providers, the post-routing, error,
|
||||||
@@ -2497,6 +2504,8 @@ protected:
|
|||||||
time_t websocket_ping_interval_sec_ =
|
time_t websocket_ping_interval_sec_ =
|
||||||
CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
|
CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
|
||||||
int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
|
int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
|
||||||
|
size_t websocket_max_message_length_ =
|
||||||
|
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
using Handlers =
|
using Handlers =
|
||||||
@@ -2538,7 +2547,7 @@ private:
|
|||||||
bool listen_internal();
|
bool listen_internal();
|
||||||
bool accept_loop(TaskQueue &task_queue);
|
bool accept_loop(TaskQueue &task_queue);
|
||||||
bool parking_loop(TaskQueue &task_queue);
|
bool parking_loop(TaskQueue &task_queue);
|
||||||
void prepare_accepted_socket(socket_t sock) const;
|
bool admit_accepted_socket(socket_t sock) const;
|
||||||
struct PlainConnection;
|
struct PlainConnection;
|
||||||
void resume_connection(std::shared_ptr<KeepAliveConnection> conn);
|
void resume_connection(std::shared_ptr<KeepAliveConnection> conn);
|
||||||
bool abandon_listen_socket();
|
bool abandon_listen_socket();
|
||||||
@@ -2643,6 +2652,7 @@ private:
|
|||||||
HandlerWithResponse pre_request_handler_;
|
HandlerWithResponse pre_request_handler_;
|
||||||
Expect100ContinueHandler expect_100_continue_handler_;
|
Expect100ContinueHandler expect_100_continue_handler_;
|
||||||
StartHandler start_handler_;
|
StartHandler start_handler_;
|
||||||
|
AcceptHandler accept_handler_;
|
||||||
|
|
||||||
mutable std::mutex logger_mutex_;
|
mutable std::mutex logger_mutex_;
|
||||||
Logger logger_;
|
Logger logger_;
|
||||||
@@ -4871,9 +4881,17 @@ namespace impl {
|
|||||||
|
|
||||||
bool is_valid_utf8(const std::string &s);
|
bool is_valid_utf8(const std::string &s);
|
||||||
|
|
||||||
// Three states: a frame, a failure (the connection cannot be read on), or a
|
// A frame, a failure (the connection cannot be read on), a timeout with the
|
||||||
// timeout with the stream still usable.
|
// stream still usable, or a frame the peer should not have sent: one that
|
||||||
enum class FrameRead { Ok, Fail, Timeout };
|
// 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
|
// 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
|
// so far in place, and the next read() goes on from there, so the stream is
|
||||||
@@ -4918,6 +4936,13 @@ public:
|
|||||||
const Request &request() const;
|
const Request &request() const;
|
||||||
bool is_open() 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.
|
// 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
|
// 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().
|
// through WebSocketClient. Safe to call while another thread is in read().
|
||||||
@@ -4936,27 +4961,25 @@ private:
|
|||||||
friend class httplib::Server;
|
friend class httplib::Server;
|
||||||
friend class httplib::ws::WebSocketClient;
|
friend class httplib::ws::WebSocketClient;
|
||||||
|
|
||||||
WebSocket(
|
WebSocket(Stream &strm, const Request &req, bool is_server,
|
||||||
Stream &strm, const Request &req, bool is_server,
|
const impl::Options &options,
|
||||||
time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
|
std::function<bool()> server_stopping = nullptr)
|
||||||
int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS,
|
|
||||||
std::function<bool()> server_stopping = nullptr)
|
|
||||||
: strm_(strm), req_(req), is_server_(is_server),
|
: strm_(strm), req_(req), is_server_(is_server),
|
||||||
ping_interval_sec_(ping_interval_sec),
|
ping_interval_sec_(options.ping_interval_sec),
|
||||||
max_missed_pongs_(max_missed_pongs),
|
max_missed_pongs_(options.max_missed_pongs),
|
||||||
|
max_message_length_(options.max_message_length),
|
||||||
server_stopping_(std::move(server_stopping)) {
|
server_stopping_(std::move(server_stopping)) {
|
||||||
interrupt_reads();
|
interrupt_reads();
|
||||||
start_heartbeat();
|
start_heartbeat();
|
||||||
}
|
}
|
||||||
|
|
||||||
WebSocket(
|
WebSocket(std::unique_ptr<Stream> &&owned_strm, const Request &req,
|
||||||
std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
|
bool is_server, const impl::Options &options,
|
||||||
time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
|
std::function<bool()> server_stopping = nullptr)
|
||||||
int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS,
|
|
||||||
std::function<bool()> server_stopping = nullptr)
|
|
||||||
: strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
|
: strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
|
||||||
is_server_(is_server), ping_interval_sec_(ping_interval_sec),
|
is_server_(is_server), ping_interval_sec_(options.ping_interval_sec),
|
||||||
max_missed_pongs_(max_missed_pongs),
|
max_missed_pongs_(options.max_missed_pongs),
|
||||||
|
max_message_length_(options.max_message_length),
|
||||||
server_stopping_(std::move(server_stopping)) {
|
server_stopping_(std::move(server_stopping)) {
|
||||||
interrupt_reads();
|
interrupt_reads();
|
||||||
start_heartbeat();
|
start_heartbeat();
|
||||||
@@ -4968,6 +4991,8 @@ private:
|
|||||||
}
|
}
|
||||||
void start_heartbeat();
|
void start_heartbeat();
|
||||||
bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
|
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_;
|
Stream &strm_;
|
||||||
std::unique_ptr<Stream> owned_strm_;
|
std::unique_ptr<Stream> owned_strm_;
|
||||||
@@ -4975,6 +5000,8 @@ private:
|
|||||||
bool is_server_;
|
bool is_server_;
|
||||||
time_t ping_interval_sec_;
|
time_t ping_interval_sec_;
|
||||||
int max_missed_pongs_;
|
int max_missed_pongs_;
|
||||||
|
// The largest frame or message read() accepts; 0 means no limit
|
||||||
|
size_t max_message_length_;
|
||||||
int unacked_pings_ = 0;
|
int unacked_pings_ = 0;
|
||||||
std::atomic<bool> closed_{false};
|
std::atomic<bool> closed_{false};
|
||||||
// Set when the peer stopped answering pings, to end a read() waiting on it
|
// Set when the peer stopped answering pings, to end a read() waiting on it
|
||||||
@@ -4997,6 +5024,10 @@ private:
|
|||||||
impl::FrameReader frames_;
|
impl::FrameReader frames_;
|
||||||
std::string message_;
|
std::string message_;
|
||||||
ReadResult message_kind_ = Fail; // Text or Binary while one is assembled
|
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::thread ping_thread_;
|
||||||
std::mutex ping_mutex_;
|
std::mutex ping_mutex_;
|
||||||
std::condition_variable ping_cv_;
|
std::condition_variable ping_cv_;
|
||||||
@@ -5020,6 +5051,8 @@ public:
|
|||||||
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;
|
||||||
const std::string &subprotocol() const;
|
const std::string &subprotocol() const;
|
||||||
void set_read_timeout(time_t sec, time_t usec = 0);
|
void set_read_timeout(time_t sec, time_t usec = 0);
|
||||||
template <class Rep, class Period>
|
template <class Rep, class Period>
|
||||||
@@ -5031,6 +5064,7 @@ public:
|
|||||||
|
|
||||||
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);
|
||||||
|
void set_websocket_max_message_length(size_t length);
|
||||||
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);
|
||||||
@@ -5113,6 +5147,8 @@ private:
|
|||||||
time_t websocket_ping_interval_sec_ =
|
time_t websocket_ping_interval_sec_ =
|
||||||
CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
|
CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
|
||||||
int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
|
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;
|
int address_family_ = AF_UNSPEC;
|
||||||
bool tcp_nodelay_ = CPPHTTPLIB_WEBSOCKET_TCP_NODELAY;
|
bool tcp_nodelay_ = CPPHTTPLIB_WEBSOCKET_TCP_NODELAY;
|
||||||
bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
|
bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
|
||||||
@@ -5647,7 +5683,8 @@ bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
|
|||||||
time_t timeout_usec, TlsError *err,
|
time_t timeout_usec, TlsError *err,
|
||||||
const std::function<bool()> &interrupted = nullptr);
|
const std::function<bool()> &interrupted = nullptr);
|
||||||
bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
|
bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
|
||||||
time_t timeout_usec, TlsError *err);
|
time_t timeout_usec, TlsError *err,
|
||||||
|
const std::function<bool()> &interrupted = nullptr);
|
||||||
|
|
||||||
// I/O (non-blocking capable)
|
// I/O (non-blocking capable)
|
||||||
ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
|
ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
|
||||||
@@ -6208,9 +6245,9 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
|
|||||||
reset();
|
reset();
|
||||||
return FrameRead::Fail;
|
return FrameRead::Fail;
|
||||||
};
|
};
|
||||||
auto fail = [&]() {
|
auto reject = [&](FrameRead r) {
|
||||||
reset();
|
reset();
|
||||||
return FrameRead::Fail;
|
return r;
|
||||||
};
|
};
|
||||||
|
|
||||||
while (have_ < need_) {
|
while (have_ < need_) {
|
||||||
@@ -6220,15 +6257,15 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
|
|||||||
if (have_ < 2 || need_ > 2) { continue; }
|
if (have_ < 2 || need_ > 2) { continue; }
|
||||||
|
|
||||||
// RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
|
// 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
|
// RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
|
||||||
// MUST have a payload length of 125 bytes or less
|
// MUST have a payload length of 125 bytes or less
|
||||||
auto len7 = head_[1] & 0x7F;
|
auto len7 = head_[1] & 0x7F;
|
||||||
if ((head_[0] & 0x08) && (!(head_[0] & 0x80) || len7 > 125)) {
|
if ((head_[0] & 0x08) && (!(head_[0] & 0x80) || len7 > 125)) {
|
||||||
return fail();
|
return reject(FrameRead::ProtocolError);
|
||||||
}
|
}
|
||||||
auto masked = (head_[1] & 0x80) != 0;
|
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
|
// The extended length and the mask key follow
|
||||||
need_ = 2 + (len7 == 126 ? 2 : len7 == 127 ? 8 : 0) + (masked ? 4 : 0);
|
need_ = 2 + (len7 == 126 ? 2 : len7 == 127 ? 8 : 0) + (masked ? 4 : 0);
|
||||||
}
|
}
|
||||||
@@ -6239,7 +6276,7 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
|
|||||||
len = (static_cast<uint64_t>(head_[2]) << 8) | head_[3];
|
len = (static_cast<uint64_t>(head_[2]) << 8) | head_[3];
|
||||||
} else if (len == 127) {
|
} else if (len == 127) {
|
||||||
// RFC 6455 Section 5.2: the most significant bit MUST be 0
|
// 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;
|
len = 0;
|
||||||
for (size_t i = 2; i < 10; i++) {
|
for (size_t i = 2; i < 10; i++) {
|
||||||
len = (len << 8) | head_[i];
|
len = (len << 8) | head_[i];
|
||||||
@@ -6248,7 +6285,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
|
// 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.
|
// size_t cannot hold (32-bit builds) is refused either way.
|
||||||
if ((max_len > 0 && len > max_len) || !detail::fits_in_size_t(len)) {
|
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);
|
len_ = static_cast<size_t>(len);
|
||||||
sized_ = true;
|
sized_ = true;
|
||||||
@@ -6291,17 +6328,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
|
// 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.
|
// 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) {
|
inline bool is_valid_close_payload(const std::string &payload) {
|
||||||
if (payload.empty()) { return true; }
|
if (payload.empty()) { return true; }
|
||||||
if (payload.size() < 2) { return false; }
|
if (payload.size() < 2) { return false; }
|
||||||
auto code = (static_cast<uint8_t>(payload[0]) << 8) |
|
auto code = close_code(payload);
|
||||||
static_cast<uint8_t>(payload[1]);
|
|
||||||
auto may_be_sent = (1000 <= code && code <= 1003) ||
|
auto may_be_sent = (1000 <= code && code <= 1003) ||
|
||||||
(1007 <= code && code <= 1014) ||
|
(1007 <= code && code <= 1014) ||
|
||||||
(3000 <= code && code <= 4999);
|
(3000 <= code && code <= 4999);
|
||||||
return may_be_sent && is_valid_utf8(payload.substr(2));
|
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 impl
|
||||||
} // namespace ws
|
} // namespace ws
|
||||||
|
|
||||||
@@ -10160,8 +10219,10 @@ inline void parse_disposition_params(const std::string &s, Params ¶ms) {
|
|||||||
std::string val;
|
std::string val;
|
||||||
divide_param_pair(b, e, key, val);
|
divide_param_pair(b, e, key, val);
|
||||||
|
|
||||||
|
// Parameter names are case-insensitive (RFC 2045 §5.1)
|
||||||
if (!key.empty()) {
|
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));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -14818,6 +14879,11 @@ inline Server &Server::set_start_handler(StartHandler handler) {
|
|||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline Server &Server::set_accept_handler(AcceptHandler handler) {
|
||||||
|
accept_handler_ = std::move(handler);
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
inline Server &Server::set_address_family(int family) {
|
inline Server &Server::set_address_family(int family) {
|
||||||
address_family_ = family;
|
address_family_ = family;
|
||||||
return *this;
|
return *this;
|
||||||
@@ -14940,6 +15006,11 @@ inline Server &Server::set_websocket_max_missed_pongs(int count) {
|
|||||||
return *this;
|
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) {
|
inline Server &Server::set_websocket_ping_interval(time_t sec) {
|
||||||
websocket_ping_interval_sec_ = sec;
|
websocket_ping_interval_sec_ = sec;
|
||||||
return *this;
|
return *this;
|
||||||
@@ -15618,12 +15689,22 @@ inline bool Server::listen_internal() {
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void Server::prepare_accepted_socket(socket_t sock) const {
|
// Closes the socket and returns false when the accept handler refuses it.
|
||||||
|
inline bool Server::admit_accepted_socket(socket_t sock) const {
|
||||||
detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec_,
|
detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec_,
|
||||||
read_timeout_usec_);
|
read_timeout_usec_);
|
||||||
detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec_,
|
detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec_,
|
||||||
write_timeout_usec_);
|
write_timeout_usec_);
|
||||||
if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
|
if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
|
||||||
|
|
||||||
|
// After the timeouts, so that a handler reading from the socket returns.
|
||||||
|
if (accept_handler_ &&
|
||||||
|
!serve_guarded([&]() { return accept_handler_(sock); })) {
|
||||||
|
detail::shutdown_socket(sock);
|
||||||
|
detail::close_socket(sock);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Serves each connection on one worker thread for its whole life.
|
// Serves each connection on one worker thread for its whole life.
|
||||||
@@ -15662,7 +15743,7 @@ inline bool Server::accept_loop(TaskQueue &task_queue) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
prepare_accepted_socket(sock);
|
if (!admit_accepted_socket(sock)) { continue; }
|
||||||
|
|
||||||
if (!task_queue.enqueue(
|
if (!task_queue.enqueue(
|
||||||
[this, sock]() { process_and_close_socket(sock); })) {
|
[this, sock]() { process_and_close_socket(sock); })) {
|
||||||
@@ -16346,6 +16427,10 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
|
|||||||
connection_closed = true;
|
connection_closed = true;
|
||||||
if (websocket_upgraded) { *websocket_upgraded = true; }
|
if (websocket_upgraded) { *websocket_upgraded = true; }
|
||||||
auto stopping = [this] { return is_stopping(); };
|
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) {
|
if (CPPHTTPLIB_WEBSOCKET_TCP_NODELAY) {
|
||||||
set_socket_opt(strm.socket(), IPPROTO_TCP, TCP_NODELAY, 1);
|
set_socket_opt(strm.socket(), IPPROTO_TCP, TCP_NODELAY, 1);
|
||||||
}
|
}
|
||||||
@@ -16360,17 +16445,14 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
|
|||||||
strm.socket(), const_cast<tls::session_t>(req.ssl),
|
strm.socket(), const_cast<tls::session_t>(req.ssl),
|
||||||
CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0,
|
CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0,
|
||||||
write_timeout_sec_, write_timeout_usec_));
|
write_timeout_sec_, write_timeout_usec_));
|
||||||
ws::WebSocket ws(std::move(ws_strm), req, true,
|
ws::WebSocket ws(std::move(ws_strm), req, true, options, stopping);
|
||||||
websocket_ping_interval_sec_,
|
|
||||||
websocket_max_missed_pongs_, stopping);
|
|
||||||
ws_route->handler(req, ws);
|
ws_route->handler(req, ws);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
// Use WebSocket-specific read timeout instead of HTTP timeout
|
// Use WebSocket-specific read timeout instead of HTTP timeout
|
||||||
strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0);
|
strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0);
|
||||||
ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
|
ws::WebSocket ws(strm, req, true, options, stopping);
|
||||||
websocket_max_missed_pongs_, stopping);
|
|
||||||
ws_route->handler(req, ws);
|
ws_route->handler(req, ws);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -16623,7 +16705,7 @@ inline bool Server::parking_loop(TaskQueue &task_queue) {
|
|||||||
}
|
}
|
||||||
// Some platforms make it non-blocking like the listening socket.
|
// Some platforms make it non-blocking like the listening socket.
|
||||||
detail::set_nonblocking(sock, false);
|
detail::set_nonblocking(sock, false);
|
||||||
prepare_accepted_socket(sock);
|
if (!admit_accepted_socket(sock)) { continue; }
|
||||||
park(new_keep_alive_connection(sock), now);
|
park(new_keep_alive_connection(sock), now);
|
||||||
if (idle.count() > 0) { next_idle = now + idle; }
|
if (idle.count() > 0) { next_idle = now + idle; }
|
||||||
}
|
}
|
||||||
@@ -20278,8 +20360,9 @@ inline tls::session_t SSLServer::start_session(socket_t sock) {
|
|||||||
std::lock_guard<std::mutex> guard(ctx_mutex_);
|
std::lock_guard<std::mutex> guard(ctx_mutex_);
|
||||||
if (--handshakes_in_progress_ == 0) { ctx_cv_.notify_all(); }
|
if (--handshakes_in_progress_ == 0) { ctx_cv_.notify_all(); }
|
||||||
});
|
});
|
||||||
accepted = accept_nonblocking(session, sock, read_timeout_sec_,
|
accepted =
|
||||||
read_timeout_usec_, &tls_err);
|
accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
|
||||||
|
&tls_err, [this]() { return is_stopping(); });
|
||||||
}
|
}
|
||||||
if (!accepted) {
|
if (!accepted) {
|
||||||
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
|
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
|
||||||
@@ -21694,7 +21777,8 @@ inline bool connect_nonblocking(session_t session, socket_t sock,
|
|||||||
|
|
||||||
inline bool accept_nonblocking(session_t session, socket_t sock,
|
inline bool accept_nonblocking(session_t session, socket_t sock,
|
||||||
time_t timeout_sec, time_t timeout_usec,
|
time_t timeout_sec, time_t timeout_usec,
|
||||||
TlsError *err) {
|
TlsError *err,
|
||||||
|
const std::function<bool()> &interrupted) {
|
||||||
if (!session) {
|
if (!session) {
|
||||||
if (err) { err->code = ErrorCode::Fatal; }
|
if (err) { err->code = ErrorCode::Fatal; }
|
||||||
return false;
|
return false;
|
||||||
@@ -21719,10 +21803,14 @@ inline bool accept_nonblocking(session_t session, socket_t sock,
|
|||||||
auto ssl_err = SSL_get_error(ssl, res);
|
auto ssl_err = SSL_get_error(ssl, res);
|
||||||
switch (ssl_err) {
|
switch (ssl_err) {
|
||||||
case SSL_ERROR_WANT_READ:
|
case SSL_ERROR_WANT_READ:
|
||||||
if (detail::select_until(sock, POLLIN, deadline) > 0) { continue; }
|
if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
case SSL_ERROR_WANT_WRITE:
|
case SSL_ERROR_WANT_WRITE:
|
||||||
if (detail::select_until(sock, POLLOUT, deadline) > 0) { continue; }
|
if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
default: break;
|
default: break;
|
||||||
}
|
}
|
||||||
@@ -23049,13 +23137,14 @@ inline bool connect_nonblocking(session_t session, socket_t sock,
|
|||||||
|
|
||||||
inline bool accept_nonblocking(session_t session, socket_t sock,
|
inline bool accept_nonblocking(session_t session, socket_t sock,
|
||||||
time_t timeout_sec, time_t timeout_usec,
|
time_t timeout_sec, time_t timeout_usec,
|
||||||
TlsError *err) {
|
TlsError *err,
|
||||||
|
const std::function<bool()> &interrupted) {
|
||||||
// A failed handshake leaves its SNI behind, so start without it
|
// A failed handshake leaves its SNI behind, so start without it
|
||||||
impl::mbedpending_sni().clear();
|
impl::mbedpending_sni().clear();
|
||||||
|
|
||||||
// Same implementation as connect for Mbed TLS
|
// Same implementation as connect for Mbed TLS
|
||||||
bool result =
|
bool result = connect_nonblocking(session, sock, timeout_sec, timeout_usec,
|
||||||
connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
|
err, interrupted);
|
||||||
|
|
||||||
// After successful handshake, capture SNI from thread-local storage
|
// After successful handshake, capture SNI from thread-local storage
|
||||||
if (result && session) {
|
if (result && session) {
|
||||||
@@ -24230,7 +24319,8 @@ inline bool connect_nonblocking(session_t session, socket_t sock,
|
|||||||
|
|
||||||
inline bool accept_nonblocking(session_t session, socket_t sock,
|
inline bool accept_nonblocking(session_t session, socket_t sock,
|
||||||
time_t timeout_sec, time_t timeout_usec,
|
time_t timeout_sec, time_t timeout_usec,
|
||||||
TlsError *err) {
|
TlsError *err,
|
||||||
|
const std::function<bool()> &interrupted) {
|
||||||
if (!session) {
|
if (!session) {
|
||||||
if (err) { err->code = ErrorCode::Fatal; }
|
if (err) { err->code = ErrorCode::Fatal; }
|
||||||
return false;
|
return false;
|
||||||
@@ -24248,9 +24338,13 @@ inline bool accept_nonblocking(session_t session, socket_t sock,
|
|||||||
while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
|
while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
|
||||||
int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
|
int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
|
||||||
if (ssl_error == SSL_ERROR_WANT_READ) {
|
if (ssl_error == SSL_ERROR_WANT_READ) {
|
||||||
if (detail::select_until(sock, POLLIN, deadline) > 0) { continue; }
|
if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
} else if (ssl_error == SSL_ERROR_WANT_WRITE) {
|
} else if (ssl_error == SSL_ERROR_WANT_WRITE) {
|
||||||
if (detail::select_until(sock, POLLOUT, deadline) > 0) { continue; }
|
if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Error or timeout
|
// Error or timeout
|
||||||
@@ -24838,40 +24932,55 @@ inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
|
|||||||
bool fin) {
|
bool fin) {
|
||||||
std::lock_guard<std::mutex> lock(write_mutex_);
|
std::lock_guard<std::mutex> lock(write_mutex_);
|
||||||
if (closed_) { return false; }
|
if (closed_) { return false; }
|
||||||
return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
|
// A failed write may have sent part of the frame, whose header announces the
|
||||||
|
// whole length, so the peer would read the next frames as the rest of it.
|
||||||
|
if (!detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_)) {
|
||||||
|
closed_ = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
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) {
|
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.
|
// Answers a control frame; any other opcode here is a protocol error.
|
||||||
// Returns false when the connection is done.
|
// Returns false when the connection is done.
|
||||||
auto handle_control = [&](Opcode op, const std::string &payload) -> bool {
|
auto handle_control = [&](Opcode op, const std::string &payload) -> bool {
|
||||||
switch (op) {
|
switch (op) {
|
||||||
case Opcode::Ping: {
|
case Opcode::Ping:
|
||||||
std::lock_guard<std::mutex> lock(write_mutex_);
|
return send_frame(Opcode::Pong, payload.data(), payload.size());
|
||||||
detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
|
|
||||||
payload.size(), true, !is_server_);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
case Opcode::Pong: {
|
case Opcode::Pong: {
|
||||||
std::lock_guard<std::mutex> lock(ping_mutex_);
|
std::lock_guard<std::mutex> lock(ping_mutex_);
|
||||||
unacked_pings_ = 0;
|
unacked_pings_ = 0;
|
||||||
return true;
|
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
|
// RFC 6455 §5.5.1: a Close is echoed back, unless its payload is
|
||||||
// malformed, which is answered with a protocol error instead.
|
// malformed, which is answered with a protocol error instead.
|
||||||
if (closed_.exchange(true)) { return false; }
|
send_close(impl::is_valid_close_payload(payload)
|
||||||
auto reply = payload;
|
? payload
|
||||||
if (!impl::is_valid_close_payload(payload)) {
|
: impl::close_payload(CloseStatus::ProtocolError));
|
||||||
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_);
|
|
||||||
return false;
|
return false;
|
||||||
}
|
default: fail_with(CloseStatus::ProtocolError); return false;
|
||||||
default: closed_ = true; return false;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -24889,13 +24998,12 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|||||||
std::string payload;
|
std::string payload;
|
||||||
bool fin;
|
bool fin;
|
||||||
|
|
||||||
// While a message is assembled, only what is left of the limit, but room
|
// What is left of the limit (all of it between messages), but always room
|
||||||
// for a control frame, which may come between its fragments.
|
// for a control frame, which the limit does not cover.
|
||||||
auto max_len =
|
auto max_len =
|
||||||
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH == 0 || message_kind_ == Fail
|
max_message_length_ == 0
|
||||||
? size_t(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)
|
? size_t(0)
|
||||||
: (std::max)(size_t(125), CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH -
|
: (std::max)(size_t(125), max_message_length_ - message_.size());
|
||||||
message_.size());
|
|
||||||
auto r = frames_.read(strm_, opcode, payload, fin, is_server_, max_len);
|
auto r = frames_.read(strm_, opcode, payload, fin, is_server_, max_len);
|
||||||
if (r != impl::FrameRead::Ok && server_stopping()) { return going_away(); }
|
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
|
// A timeout leaves what was read of the frame and of the message for the
|
||||||
@@ -24908,6 +25016,12 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|||||||
if (r == impl::FrameRead::Timeout && read_timeout_set_ && !closed_) {
|
if (r == impl::FrameRead::Timeout && read_timeout_set_ && !closed_) {
|
||||||
return Timeout;
|
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) {
|
if (r != impl::FrameRead::Ok) {
|
||||||
closed_ = true;
|
closed_ = true;
|
||||||
return Fail;
|
return Fail;
|
||||||
@@ -24921,8 +25035,7 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|||||||
// RFC 6455 5.4: a message is a Text or Binary frame and the continuation
|
// RFC 6455 5.4: a message is a Text or Binary frame and the continuation
|
||||||
// frames after it, with only control frames between them.
|
// frames after it, with only control frames between them.
|
||||||
if (continues == (message_kind_ == Fail)) {
|
if (continues == (message_kind_ == Fail)) {
|
||||||
closed_ = true;
|
return fail_with(CloseStatus::ProtocolError);
|
||||||
return Fail;
|
|
||||||
}
|
}
|
||||||
if (continues) {
|
if (continues) {
|
||||||
message_ += payload;
|
message_ += payload;
|
||||||
@@ -24930,10 +25043,8 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|||||||
message_ = std::move(payload);
|
message_ = std::move(payload);
|
||||||
message_kind_ = opcode == Opcode::Text ? Text : Binary;
|
message_kind_ = opcode == Opcode::Text ? Text : Binary;
|
||||||
}
|
}
|
||||||
if (CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH > 0 &&
|
if (max_message_length_ > 0 && message_.size() > max_message_length_) {
|
||||||
message_.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
|
return fail_with(CloseStatus::MessageTooBig);
|
||||||
closed_ = true;
|
|
||||||
return Fail;
|
|
||||||
}
|
}
|
||||||
if (!fin) { continue; }
|
if (!fin) { continue; }
|
||||||
|
|
||||||
@@ -24963,27 +25074,7 @@ inline bool WebSocket::send(const char *data, size_t len) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
inline void WebSocket::close(CloseStatus status, const std::string &reason) {
|
inline void WebSocket::close(CloseStatus status, const std::string &reason) {
|
||||||
if (closed_.exchange(true)) { return; }
|
if (!send_close(impl::close_payload(status, reason))) { 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_);
|
|
||||||
}
|
|
||||||
|
|
||||||
// RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
|
// RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
|
||||||
// Close response before closing the TCP connection.
|
// Close response before closing the TCP connection.
|
||||||
@@ -25009,7 +25100,10 @@ inline void WebSocket::close(CloseStatus status, const std::string &reason) {
|
|||||||
while (std::chrono::steady_clock::now() < deadline &&
|
while (std::chrono::steady_clock::now() < deadline &&
|
||||||
frames_.read(strm_, op, resp, fin, is_server_, 125) ==
|
frames_.read(strm_, op, resp, fin, is_server_, 125) ==
|
||||||
impl::FrameRead::Ok) {
|
impl::FrameRead::Ok) {
|
||||||
if (op == Opcode::Close) { break; }
|
if (op == Opcode::Close) {
|
||||||
|
set_close_status(resp);
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25050,11 +25144,7 @@ inline void WebSocket::start_heartbeat() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
if (!send_frame(Opcode::Ping, nullptr, 0)) {
|
if (!send_frame(Opcode::Ping, nullptr, 0)) { return; }
|
||||||
lock.lock();
|
|
||||||
closed_ = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
lock.lock();
|
lock.lock();
|
||||||
unacked_pings_++;
|
unacked_pings_++;
|
||||||
}
|
}
|
||||||
@@ -25065,6 +25155,25 @@ inline const Request &WebSocket::request() const { return req_; }
|
|||||||
|
|
||||||
inline bool WebSocket::is_open() const { return !closed_; }
|
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) {
|
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
|
// 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
|
// poll(), where 0 would instead mean "return immediately", so hand it the
|
||||||
@@ -25307,9 +25416,12 @@ inline Result WebSocketClient::connect() {
|
|||||||
}
|
}
|
||||||
subprotocol_ = std::move(upgrade.selected_subprotocol);
|
subprotocol_ = std::move(upgrade.selected_subprotocol);
|
||||||
|
|
||||||
ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
|
impl::Options options;
|
||||||
websocket_ping_interval_sec_,
|
options.ping_interval_sec = websocket_ping_interval_sec_;
|
||||||
websocket_max_missed_pongs_));
|
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
|
// 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.
|
// whether it came from the caller, so read() knows to report it as Timeout.
|
||||||
ws_->read_timeout_set_ = read_timeout_set_;
|
ws_->read_timeout_set_ = read_timeout_set_;
|
||||||
@@ -25338,6 +25450,14 @@ inline void WebSocketClient::close(CloseStatus status,
|
|||||||
|
|
||||||
inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
|
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 {
|
inline const std::string &WebSocketClient::subprotocol() const {
|
||||||
return subprotocol_;
|
return subprotocol_;
|
||||||
}
|
}
|
||||||
@@ -25364,6 +25484,10 @@ inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
|
|||||||
websocket_max_missed_pongs_ = 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_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
|
||||||
|
|
||||||
inline void WebSocketClient::set_address_family(int family) {
|
inline void WebSocketClient::set_address_family(int family) {
|
||||||
|
|||||||
+647
-124
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user