mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-11-29 21:18:29 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90bd0f7daf | ||
|
|
f181182a9d | ||
|
|
bba6042bba | ||
|
|
8037789492 | ||
|
|
eea8ce9798 | ||
|
|
84acde731b | ||
|
|
daf46bd502 | ||
|
|
084b30055e |
No files matched your search
+1
-32
@@ -144,14 +144,6 @@ 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);
|
||||
@@ -208,8 +200,6 @@ 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);
|
||||
@@ -242,9 +232,6 @@ 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);
|
||||
@@ -391,12 +378,6 @@ 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
|
||||
@@ -528,7 +509,7 @@ if (ws.connect()) {
|
||||
|
||||
| Macro | Default | Description |
|
||||
|---------------------------------------------|-------------------|----------------------------------------------------------|
|
||||
| `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` | `16777216` (16MB) | Default maximum message size (`0` means no limit) |
|
||||
| `CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH` | `16777216` (16MB) | Maximum payload size per message (`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) |
|
||||
@@ -570,18 +551,6 @@ 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.
|
||||
|
||||
@@ -70,9 +70,6 @@ cpp-httplib supports multiple TLS backends through an abstraction layer:
|
||||
| Mbed TLS | `CPPHTTPLIB_MBEDTLS_SUPPORT` | `libmbedtls`, `libmbedx509`, `libmbedcrypto` | 2.x, 3.x, and 4.x supported (auto-detected); 4.x renames `libmbedcrypto` to `libtfpsacrypto` |
|
||||
| wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` | 5.x supported; must build with `--enable-opensslall` |
|
||||
|
||||
> [!NOTE]
|
||||
> **Mbed TLS threading:** Mbed TLS must be built with `MBEDTLS_THREADING_C`, because `SSLServer` handles connections on several threads and Mbed TLS is not thread-safe without it. Its default configuration leaves this option off, while distribution packages such as Debian, Ubuntu and Homebrew turn it on. Building against Mbed TLS without it stops with an `#error`. If Mbed TLS is only ever used from one thread, define `CPPHTTPLIB_MBEDTLS_SINGLE_THREADED` to build anyway.
|
||||
|
||||
> [!NOTE]
|
||||
> **wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()` or `set_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable.
|
||||
>
|
||||
@@ -590,27 +587,9 @@ svr.set_pre_request_handler([](const auto& req, auto& res) {
|
||||
> [!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.
|
||||
|
||||
### 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
|
||||
|
||||
`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:
|
||||
`set_start_handler` runs once when the server starts. For each request, handlers run in the following order:
|
||||
|
||||
```
|
||||
Request received
|
||||
|
||||
+12
-2
@@ -4,7 +4,7 @@
|
||||
#
|
||||
# Usage: ./ab.sh [--base REF] [--head REF] [--rounds N] [--duration S]
|
||||
# [--connections N] [--threads N] [--path PATH] [--tls]
|
||||
# [--large-mib N] [--timeout S]
|
||||
# [--large-mib N] [--timeout S] [--no-keep-alive]
|
||||
#
|
||||
# --path selects the workload. The harness serves:
|
||||
# / small body via set_content(); the response line, the
|
||||
@@ -20,6 +20,9 @@
|
||||
# --tls runs the same workload over HTTPS, which writes through
|
||||
# SSLSocketStream instead of SocketStream.
|
||||
#
|
||||
# --no-keep-alive opens a new connection for every request, which measures
|
||||
# the cost of accepting and setting up a connection.
|
||||
#
|
||||
# --timeout is bombardier's per-request timeout. Its 2s default aborts large
|
||||
# TLS responses, and the run then fails on the non-2xx check.
|
||||
#
|
||||
@@ -43,6 +46,7 @@ REQ_PATH="/"
|
||||
TLS=0
|
||||
LARGE_MIB=1
|
||||
TIMEOUT="30s"
|
||||
NO_KEEP_ALIVE=0
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
@@ -56,10 +60,16 @@ while [ $# -gt 0 ]; do
|
||||
--large-mib) LARGE_MIB="$2"; shift 2 ;;
|
||||
--timeout) TIMEOUT="$2"; shift 2 ;;
|
||||
--tls) TLS=1; shift ;;
|
||||
--no-keep-alive) NO_KEEP_ALIVE=1; shift ;;
|
||||
*) echo "Unknown option: $1" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# bombardier's default fasthttp client ignores -a, so close each connection
|
||||
# with the request header instead.
|
||||
CLOSE_HEADER=()
|
||||
if [ "$NO_KEEP_ALIVE" -eq 1 ]; then CLOSE_HEADER=(-H "Connection: close"); fi
|
||||
|
||||
command -v bombardier >/dev/null || { echo "Error: bombardier not found" >&2; exit 1; }
|
||||
command -v python3 >/dev/null || { echo "Error: python3 not found" >&2; exit 1; }
|
||||
|
||||
@@ -162,7 +172,7 @@ measure() {
|
||||
done
|
||||
|
||||
set +e
|
||||
json=$(bombardier -c "$CONNECTIONS" -d "$DURATION" -t "$TIMEOUT" -o json -p r $INSECURE \
|
||||
json=$(bombardier -c "$CONNECTIONS" -d "$DURATION" -t "$TIMEOUT" -o json -p r $INSECURE ${CLOSE_HEADER[@]+"${CLOSE_HEADER[@]}"} \
|
||||
"$SCHEME://127.0.0.1:$PORT$REQ_PATH" 2>/dev/null)
|
||||
rc=$?
|
||||
set -e
|
||||
|
||||
@@ -4,7 +4,7 @@ langs = ["en", "ja"]
|
||||
|
||||
[site]
|
||||
title = "cpp-httplib"
|
||||
version = "0.69.0"
|
||||
version = "0.67.0"
|
||||
hostname = "https://yhirose.github.io"
|
||||
base_path = "/cpp-httplib"
|
||||
footer_message = "© 2026 Yuji Hirose. All rights reserved."
|
||||
|
||||
@@ -51,21 +51,4 @@ 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).
|
||||
|
||||
## 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).
|
||||
@@ -67,15 +67,7 @@ To notify in-flight clients that the server is going down, use `GoingAway`.
|
||||
ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting");
|
||||
```
|
||||
|
||||
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
|
||||
}
|
||||
```
|
||||
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()`.
|
||||
|
||||
## 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), 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.
|
||||
> **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.
|
||||
@@ -51,21 +51,4 @@ svr.set_pre_routing_handler(
|
||||
|
||||
全ルート共通ではなく、ルート単位で認証を分けたいときは、[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)を参照してください。
|
||||
@@ -67,15 +67,7 @@ cli.close(httplib::ws::CloseStatus::Normal);
|
||||
ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting");
|
||||
```
|
||||
|
||||
`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) {
|
||||
// サーバーが再起動中: あとで再接続する
|
||||
}
|
||||
```
|
||||
クライアント側の`read()`は`Fail`を返すだけで、受け取ったステータスや理由は取り出せません。再起動による切断をほかの切断と見分けたい場合は、先にメッセージ(`ws.send("restarting")`など)を送ってから`close()`を呼びましょう。
|
||||
|
||||
## サンプル: 簡単なチャット終了
|
||||
|
||||
|
||||
@@ -85,4 +85,4 @@ if (cli.read(buf) == httplib::ws::ReadResult::Binary) {
|
||||
|
||||
テキストとバイナリを混ぜて送ることもできます。たとえば「制御メッセージはJSON、データ本体はバイナリ」といったプロトコルを組み立てると、メタデータと生データを効率よく扱えます。
|
||||
|
||||
> **Note:** 受信できるメッセージの大きさは`CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH`(デフォルトは16MB、0なら無制限)、または`Server`や`WebSocketClient`の`set_websocket_max_message_length()`で設定した値までです。これを超えると`read()`は`Fail`を返し、接続は終了します。上限以内でもメッセージはまるごとメモリに載るので、巨大なデータを送るときは、アプリケーション側で分割して送るのが安全です。
|
||||
> **Note:** 受信できるメッセージの大きさは`CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH`(デフォルトは16MB、0なら無制限)までです。これを超えると`read()`は`Fail`を返し、接続は終了します。上限以内でもメッセージはまるごとメモリに載るので、巨大なデータを送るときは、アプリケーション側で分割して送るのが安全です。
|
||||
@@ -8,8 +8,8 @@
|
||||
#ifndef CPPHTTPLIB_HTTPLIB_H
|
||||
#define CPPHTTPLIB_HTTPLIB_H
|
||||
|
||||
#define CPPHTTPLIB_VERSION "0.69.0"
|
||||
#define CPPHTTPLIB_VERSION_NUM "0x004500"
|
||||
#define CPPHTTPLIB_VERSION "0.67.0"
|
||||
#define CPPHTTPLIB_VERSION_NUM "0x004300"
|
||||
|
||||
#ifdef _WIN32
|
||||
#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
|
||||
@@ -565,13 +565,6 @@ using socket_t = int;
|
||||
#define CPPHTTPLIB_MBEDTLS_V3
|
||||
#endif
|
||||
|
||||
// SSLServer (and SSLClients on several threads) use Mbed TLS concurrently.
|
||||
#if !defined(MBEDTLS_THREADING_C) && \
|
||||
!defined(CPPHTTPLIB_MBEDTLS_SINGLE_THREADED)
|
||||
#error \
|
||||
"Mbed TLS must be built with MBEDTLS_THREADING_C. Define CPPHTTPLIB_MBEDTLS_SINGLE_THREADED if it is only ever used from one thread."
|
||||
#endif
|
||||
|
||||
#endif // CPPHTTPLIB_MBEDTLS_SUPPORT
|
||||
|
||||
#ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
|
||||
@@ -932,7 +925,7 @@ inline bool parse_url(const std::string &url, UrlComponents &uc) {
|
||||
size_t pos = 0;
|
||||
|
||||
auto sep = url.find("://");
|
||||
if (sep < url.find_first_of("/?#")) {
|
||||
if (sep != std::string::npos) {
|
||||
// Schemes are case-insensitive (RFC 3986 3.1)
|
||||
uc.scheme = case_ignore::to_lower(url.substr(0, sep));
|
||||
|
||||
@@ -2305,8 +2298,6 @@ public:
|
||||
|
||||
using StartHandler = std::function<void()>;
|
||||
|
||||
using AcceptHandler = std::function<bool(socket_t sock)>;
|
||||
|
||||
using WebSocketHandler =
|
||||
std::function<void(const Request &, ws::WebSocket &)>;
|
||||
using SubProtocolSelector =
|
||||
@@ -2372,8 +2363,6 @@ public:
|
||||
|
||||
Server &set_start_handler(StartHandler handler);
|
||||
|
||||
Server &set_accept_handler(AcceptHandler handler);
|
||||
|
||||
Server &set_logger(Logger logger);
|
||||
Server &set_pre_compression_logger(Logger logger);
|
||||
Server &set_error_logger(ErrorLogger error_logger);
|
||||
@@ -2426,8 +2415,6 @@ 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();
|
||||
@@ -2449,9 +2436,8 @@ protected:
|
||||
const std::function<void(Request &)> &setup_request,
|
||||
bool *websocket_upgraded = nullptr);
|
||||
|
||||
// Runs a user callback, or the per-connection serving loop that calls user
|
||||
// callbacks, and stops an exception thrown by one from escaping the
|
||||
// server's threads.
|
||||
// Runs the per-connection serving loop and stops an exception thrown by a
|
||||
// user callback from escaping the worker thread.
|
||||
//
|
||||
// process_request() wraps only routing() and the hooks before a WebSocket
|
||||
// upgrade in a try/catch. Content providers, the post-routing, error,
|
||||
@@ -2511,8 +2497,6 @@ 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 =
|
||||
@@ -2554,7 +2538,7 @@ private:
|
||||
bool listen_internal();
|
||||
bool accept_loop(TaskQueue &task_queue);
|
||||
bool parking_loop(TaskQueue &task_queue);
|
||||
bool admit_accepted_socket(socket_t sock) const;
|
||||
void prepare_accepted_socket(socket_t sock) const;
|
||||
struct PlainConnection;
|
||||
void resume_connection(std::shared_ptr<KeepAliveConnection> conn);
|
||||
bool abandon_listen_socket();
|
||||
@@ -2605,7 +2589,7 @@ private:
|
||||
ContentReceiver multipart_receiver) const;
|
||||
|
||||
virtual bool process_and_close_socket(socket_t sock);
|
||||
// The connection that parking_loop() keeps for a socket it has accepted.
|
||||
// The connection that serves an accepted socket, with or without parking.
|
||||
virtual std::shared_ptr<KeepAliveConnection>
|
||||
new_keep_alive_connection(socket_t sock);
|
||||
|
||||
@@ -2659,7 +2643,6 @@ private:
|
||||
HandlerWithResponse pre_request_handler_;
|
||||
Expect100ContinueHandler expect_100_continue_handler_;
|
||||
StartHandler start_handler_;
|
||||
AcceptHandler accept_handler_;
|
||||
|
||||
mutable std::mutex logger_mutex_;
|
||||
Logger logger_;
|
||||
@@ -3568,7 +3551,6 @@ public:
|
||||
int ssl_last_error() const { return last_ssl_error_; }
|
||||
|
||||
private:
|
||||
bool process_and_close_socket(socket_t sock) override;
|
||||
std::shared_ptr<KeepAliveConnection>
|
||||
new_keep_alive_connection(socket_t sock) override;
|
||||
struct TlsConnection;
|
||||
@@ -4893,13 +4875,6 @@ bool is_valid_utf8(const std::string &s);
|
||||
// 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
|
||||
// usable after a timeout wherever in a frame it lands.
|
||||
@@ -4943,13 +4918,6 @@ 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().
|
||||
@@ -4968,25 +4936,27 @@ private:
|
||||
friend class httplib::Server;
|
||||
friend class httplib::ws::WebSocketClient;
|
||||
|
||||
WebSocket(Stream &strm, const Request &req, bool is_server,
|
||||
const impl::Options &options,
|
||||
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<bool()> server_stopping = nullptr)
|
||||
: strm_(strm), req_(req), 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),
|
||||
ping_interval_sec_(ping_interval_sec),
|
||||
max_missed_pongs_(max_missed_pongs),
|
||||
server_stopping_(std::move(server_stopping)) {
|
||||
interrupt_reads();
|
||||
start_heartbeat();
|
||||
}
|
||||
|
||||
WebSocket(std::unique_ptr<Stream> &&owned_strm, const Request &req,
|
||||
bool is_server, const impl::Options &options,
|
||||
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,
|
||||
std::function<bool()> server_stopping = nullptr)
|
||||
: strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
|
||||
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),
|
||||
is_server_(is_server), ping_interval_sec_(ping_interval_sec),
|
||||
max_missed_pongs_(max_missed_pongs),
|
||||
server_stopping_(std::move(server_stopping)) {
|
||||
interrupt_reads();
|
||||
start_heartbeat();
|
||||
@@ -4999,7 +4969,6 @@ 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_;
|
||||
@@ -5007,8 +4976,6 @@ 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
|
||||
@@ -5031,10 +4998,6 @@ 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_;
|
||||
@@ -5058,8 +5021,6 @@ 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>
|
||||
@@ -5071,7 +5032,6 @@ 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);
|
||||
@@ -5154,8 +5114,6 @@ 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;
|
||||
@@ -6335,16 +6293,11 @@ 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 = close_code(payload);
|
||||
auto code = (static_cast<uint8_t>(payload[0]) << 8) |
|
||||
static_cast<uint8_t>(payload[1]);
|
||||
auto may_be_sent = (1000 <= code && code <= 1003) ||
|
||||
(1007 <= code && code <= 1014) ||
|
||||
(3000 <= code && code <= 4999);
|
||||
@@ -11231,6 +11184,75 @@ inline std::string escape_quoted_pairs(const std::string &s) {
|
||||
return out;
|
||||
}
|
||||
|
||||
// RFC 9110 Section 11.6.1 defines a challenge list as
|
||||
// WWW-Authenticate = #challenge
|
||||
// challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
|
||||
// auth-param = token BWS "=" BWS ( token / quoted-string )
|
||||
// so a server may offer several schemes, each with its own comma-separated
|
||||
// auth-param list, in either order and either as separate field lines or
|
||||
// packed into one. Splitting on every comma would break apart a challenge's
|
||||
// own param list; splitting only on the first space would miss a Digest
|
||||
// challenge that isn't first. Split on commas that aren't inside a
|
||||
// quoted-string instead (split_unquoted), then track which scheme each
|
||||
// resulting segment belongs to: a segment whose text before "=" contains
|
||||
// whitespace (or that has no "=" at all) starts a new challenge named by its
|
||||
// leading token.
|
||||
inline bool parse_www_authenticate(const Response &res,
|
||||
std::map<std::string, std::string> &auth,
|
||||
bool is_proxy) {
|
||||
auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
|
||||
auto combined = get_combined_header_value(res.headers, auth_key);
|
||||
if (combined.empty()) { return false; }
|
||||
|
||||
auto found_digest = false;
|
||||
auto in_digest_challenge = false;
|
||||
split_unquoted(
|
||||
combined.data(), combined.data() + combined.size(), ',',
|
||||
[&](const char *b, const char *e) {
|
||||
std::string segment(b, e);
|
||||
auto eq_pos = segment.find('=');
|
||||
// BWS is allowed on both sides of "=", so the text naming the key (or,
|
||||
// for the first segment of a challenge, "<scheme> <key>") must be
|
||||
// trimmed before its boundaries are inspected.
|
||||
auto key_part = trim_copy(
|
||||
eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
|
||||
auto space_pos = key_part.find_last_of(" \t");
|
||||
if (space_pos != std::string::npos || eq_pos == std::string::npos) {
|
||||
// "<scheme>[ <key>]" starts a new challenge.
|
||||
auto scheme_end =
|
||||
space_pos == std::string::npos ? key_part.size() : space_pos;
|
||||
// RFC 7616 Section 3.7: a server may offer more than one Digest
|
||||
// challenge (e.g. SHA-256 and MD5); keep only the first so a nonce
|
||||
// from one challenge is never paired with another's algorithm.
|
||||
in_digest_challenge =
|
||||
!found_digest &&
|
||||
case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
|
||||
if (in_digest_challenge) { found_digest = true; }
|
||||
if (space_pos == std::string::npos) {
|
||||
// Bare scheme (or a token68), no auth-param on this segment.
|
||||
return;
|
||||
}
|
||||
key_part = key_part.substr(space_pos + 1);
|
||||
}
|
||||
|
||||
if (!in_digest_challenge) { return; }
|
||||
|
||||
auto val = trim_copy(segment.substr(eq_pos + 1));
|
||||
auto unquoted = trim_double_quotes_copy(val);
|
||||
if (unquoted.size() != val.size()) {
|
||||
unquoted = unescape_quoted_pairs(unquoted);
|
||||
}
|
||||
auth[std::move(key_part)] = std::move(unquoted);
|
||||
});
|
||||
|
||||
// RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge;
|
||||
// make_digest_authentication_header() dereferences both unconditionally, so
|
||||
// a challenge missing either can't produce a usable Authorization header.
|
||||
// Treat it the same as no Digest challenge at all.
|
||||
return found_digest && auth.find("realm") != auth.end() &&
|
||||
auth.find("nonce") != auth.end();
|
||||
}
|
||||
|
||||
class ContentProviderAdapter {
|
||||
public:
|
||||
explicit ContentProviderAdapter(
|
||||
@@ -11699,121 +11721,6 @@ inline bool process_client_socket_ssl(
|
||||
return callback(strm);
|
||||
}
|
||||
|
||||
using DigestHash = std::string (*)(const std::string &);
|
||||
|
||||
// The Digest algorithms the client implements, matched case-insensitively;
|
||||
// nullptr for any other.
|
||||
inline DigestHash digest_hash(const std::string &algorithm) {
|
||||
if (case_ignore::equal(algorithm, "MD5")) { return detail::MD5; }
|
||||
if (case_ignore::equal(algorithm, "SHA-256")) { return detail::SHA_256; }
|
||||
if (case_ignore::equal(algorithm, "SHA-512")) { return detail::SHA_512; }
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Picks auth over auth-int from the qop options a server offers, as curl does:
|
||||
// auth-int hashes req.body, which is empty when a content provider streams the
|
||||
// body. Empty when it offers neither.
|
||||
inline std::string select_digest_qop(const std::string &options) {
|
||||
std::string qop;
|
||||
split(options.data(), options.data() + options.size(), ',',
|
||||
[&](const char *b, const char *e) {
|
||||
std::string option(b, e);
|
||||
if (case_ignore::equal(option, "auth")) {
|
||||
qop = "auth";
|
||||
} else if (qop.empty() && case_ignore::equal(option, "auth-int")) {
|
||||
qop = "auth-int";
|
||||
}
|
||||
});
|
||||
return qop;
|
||||
}
|
||||
|
||||
// RFC 9110 Section 11.6.1 defines a challenge list as
|
||||
// WWW-Authenticate = #challenge
|
||||
// challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
|
||||
// auth-param = token BWS "=" BWS ( token / quoted-string )
|
||||
// so a server may offer several schemes, each with its own comma-separated
|
||||
// auth-param list, in either order and either as separate field lines or
|
||||
// packed into one. Splitting on every comma would break apart a challenge's
|
||||
// own param list; splitting only on the first space would miss a Digest
|
||||
// challenge that isn't first. Split on commas that aren't inside a
|
||||
// quoted-string instead (split_unquoted), then track which scheme each
|
||||
// resulting segment belongs to: a segment whose text before "=" contains
|
||||
// whitespace (or that has no "=" at all) starts a new challenge named by its
|
||||
// leading token.
|
||||
inline bool parse_www_authenticate(const Response &res,
|
||||
std::map<std::string, std::string> &auth,
|
||||
bool is_proxy) {
|
||||
auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
|
||||
auto combined = get_combined_header_value(res.headers, auth_key);
|
||||
if (combined.empty()) { return false; }
|
||||
|
||||
// RFC 7616 Section 3.7: a server may offer more than one Digest challenge
|
||||
// (e.g. SHA-256 and MD5), and the client uses the first one it supports.
|
||||
// A challenge whose algorithm the client doesn't implement is ignored
|
||||
// (Section 3.3), as is one whose qop offers neither auth nor auth-int, and
|
||||
// one without realm and nonce can't be answered. Params are collected per
|
||||
// challenge, so a nonce from one is never paired with another's algorithm.
|
||||
auto answerable = [](const std::map<std::string, std::string> &c) {
|
||||
if (c.find("realm") == c.end() || c.find("nonce") == c.end()) {
|
||||
return false;
|
||||
}
|
||||
auto algo_it = c.find("algorithm");
|
||||
if (algo_it != c.end() && !digest_hash(algo_it->second)) { return false; }
|
||||
auto qop_it = c.find("qop");
|
||||
return qop_it == c.end() || !select_digest_qop(qop_it->second).empty();
|
||||
};
|
||||
|
||||
auto found = false;
|
||||
auto in_digest_challenge = false;
|
||||
std::map<std::string, std::string> challenge;
|
||||
auto take_challenge_if_answerable = [&] {
|
||||
if (!found && in_digest_challenge && answerable(challenge)) {
|
||||
auth = std::move(challenge);
|
||||
found = true;
|
||||
}
|
||||
challenge.clear();
|
||||
};
|
||||
|
||||
split_unquoted(
|
||||
combined.data(), combined.data() + combined.size(), ',',
|
||||
[&](const char *b, const char *e) {
|
||||
std::string segment(b, e);
|
||||
auto eq_pos = segment.find('=');
|
||||
// BWS is allowed on both sides of "=", so the text naming the key (or,
|
||||
// for the first segment of a challenge, "<scheme> <key>") must be
|
||||
// trimmed before its boundaries are inspected.
|
||||
auto key_part = trim_copy(
|
||||
eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
|
||||
auto space_pos = key_part.find_first_of(" \t");
|
||||
if (space_pos != std::string::npos || eq_pos == std::string::npos) {
|
||||
// "<scheme>[ <key>]" starts a new challenge.
|
||||
take_challenge_if_answerable();
|
||||
auto scheme_end =
|
||||
space_pos == std::string::npos ? key_part.size() : space_pos;
|
||||
in_digest_challenge =
|
||||
case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
|
||||
if (space_pos == std::string::npos) {
|
||||
// Bare scheme (or a token68), no auth-param on this segment.
|
||||
return;
|
||||
}
|
||||
key_part = trim_copy(key_part.substr(space_pos + 1));
|
||||
}
|
||||
|
||||
if (!in_digest_challenge) { return; }
|
||||
|
||||
auto val = trim_copy(segment.substr(eq_pos + 1));
|
||||
auto unquoted = trim_double_quotes_copy(val);
|
||||
if (unquoted.size() != val.size()) {
|
||||
unquoted = unescape_quoted_pairs(unquoted);
|
||||
}
|
||||
// auth-param names are case-insensitive (RFC 9110 Section 11.2)
|
||||
challenge[case_ignore::to_lower(key_part)] = std::move(unquoted);
|
||||
});
|
||||
take_challenge_if_answerable();
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
// `uri` is req's request-target in origin form, as curl sends it, also when
|
||||
// the request line carries the absolute form for a proxy.
|
||||
inline std::pair<std::string, std::string> make_digest_authentication_header(
|
||||
@@ -11828,21 +11735,33 @@ inline std::pair<std::string, std::string> make_digest_authentication_header(
|
||||
nc = ss.str();
|
||||
}
|
||||
|
||||
// Without qop, the RFC 2069 form is used.
|
||||
auto qop_it = auth.find("qop");
|
||||
auto qop =
|
||||
qop_it == auth.end() ? std::string() : select_digest_qop(qop_it->second);
|
||||
assert(qop_it == auth.end() || !qop.empty());
|
||||
std::string qop;
|
||||
if (auth.find("qop") != auth.end()) {
|
||||
qop = auth.at("qop");
|
||||
if (qop.find("auth-int") != std::string::npos) {
|
||||
qop = "auth-int";
|
||||
} else if (qop.find("auth") != std::string::npos) {
|
||||
qop = "auth";
|
||||
} else {
|
||||
qop.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// Sent back as the server wrote it (RFC 7616 Section 3.4).
|
||||
// parse_www_authenticate() accepts only one digest_hash() knows.
|
||||
auto algo_it = auth.find("algorithm");
|
||||
auto algo = algo_it == auth.end() ? std::string("MD5") : algo_it->second;
|
||||
auto H = digest_hash(algo);
|
||||
assert(H);
|
||||
std::string algo = "MD5";
|
||||
if (auth.find("algorithm") != auth.end()) {
|
||||
// algorithm is an unquoted token (RFC 7616 §3.4). A server value that is
|
||||
// not a token would otherwise be emitted verbatim and could carry commas
|
||||
// or quotes that inject further auth-params into the header below.
|
||||
const auto &a = auth.at("algorithm");
|
||||
if (fields::is_token(a)) { algo = a; }
|
||||
}
|
||||
|
||||
std::string response;
|
||||
{
|
||||
auto H = algo == "SHA-256" ? detail::SHA_256
|
||||
: algo == "SHA-512" ? detail::SHA_512
|
||||
: detail::MD5;
|
||||
|
||||
auto A1 = username + ":" + auth.at("realm") + ":" + password;
|
||||
|
||||
auto A2 = req.method + ":" + uri;
|
||||
@@ -12337,16 +12256,15 @@ inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
|
||||
}
|
||||
|
||||
inline std::string get_bearer_token_auth(const Request &req) {
|
||||
// The auth scheme is case-insensitive (RFC 9110 11.1) and followed by 1*SP,
|
||||
// and a value shorter than the prefix carries no token.
|
||||
// The auth scheme is case-insensitive (RFC 9110 11.1), and a value shorter
|
||||
// than the prefix carries no token.
|
||||
constexpr const char bearer_prefix[] = "Bearer ";
|
||||
constexpr auto bearer_prefix_len = detail::str_len(bearer_prefix);
|
||||
auto value = req.get_header_value("Authorization");
|
||||
if (value.size() >= bearer_prefix_len &&
|
||||
detail::case_ignore::equal(value.substr(0, bearer_prefix_len),
|
||||
bearer_prefix)) {
|
||||
auto pos = value.find_first_not_of(' ', bearer_prefix_len);
|
||||
if (pos != std::string::npos) { return value.substr(pos); }
|
||||
return value.substr(bearer_prefix_len);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
@@ -14429,9 +14347,9 @@ WebSocketSSLStream::set_read_interrupt(std::function<bool()> interrupted) {
|
||||
* Group 4: Server implementation
|
||||
*/
|
||||
|
||||
// A kept-alive connection that the event loop of set_keep_alive_parking()
|
||||
// owns while it is idle, and a worker owns while it serves a request. A
|
||||
// derived class adds the transport: the stream, and for TLS the session.
|
||||
// A connection served across its requests. With set_keep_alive_parking(), the
|
||||
// event loop owns it while it is idle, and a worker while it serves a request.
|
||||
// A derived class adds the transport: the stream, and for TLS the session.
|
||||
struct Server::KeepAliveConnection {
|
||||
KeepAliveConnection(socket_t s, Server &server) : svr(server), sock(s) {}
|
||||
// Every owner closes it before letting go, which the transport hooks need;
|
||||
@@ -14451,8 +14369,8 @@ struct Server::KeepAliveConnection {
|
||||
// close_notify.
|
||||
virtual void shut_down(bool /*graceful*/) {}
|
||||
|
||||
// On a worker, once the event loop has seen the socket readable. Afterwards
|
||||
// turn.park tells whether it may be parked again.
|
||||
// On a worker, with parking once the event loop has seen the socket
|
||||
// readable. Afterwards turn.park tells whether it may be parked again.
|
||||
bool resume() {
|
||||
turn = Turn();
|
||||
return svr.serve_guarded([this]() {
|
||||
@@ -14477,11 +14395,11 @@ struct Server::KeepAliveConnection {
|
||||
sock = INVALID_SOCKET;
|
||||
}
|
||||
|
||||
// From the worker that served it.
|
||||
void close_served(bool graceful) {
|
||||
// From the worker that served it, with what resume() returned.
|
||||
void close_served(bool ok) {
|
||||
assert(sock != INVALID_SOCKET);
|
||||
if (opened) {
|
||||
shut_down(graceful);
|
||||
shut_down(ok && !turn.websocket_upgraded);
|
||||
detail::drain_and_close_socket(sock);
|
||||
} else {
|
||||
// It never got as far as a request, e.g. a failed TLS handshake.
|
||||
@@ -14506,6 +14424,10 @@ struct Server::KeepAliveConnection {
|
||||
}
|
||||
|
||||
bool wait_for_next_request() {
|
||||
if (wait_in_place) {
|
||||
return detail::keep_alive(svr.svr_sock_, sock,
|
||||
svr.keep_alive_timeout_sec_);
|
||||
}
|
||||
// The event loop saw the socket readable just before this ran.
|
||||
if (turn.woken) {
|
||||
turn.woken = false;
|
||||
@@ -14529,6 +14451,8 @@ struct Server::KeepAliveConnection {
|
||||
int remote_port = 0;
|
||||
int local_port = 0;
|
||||
bool opened = false; // by resume(), once open() has succeeded
|
||||
// Waits for the next request on the worker, as without parking.
|
||||
bool wait_in_place = false;
|
||||
Turn turn;
|
||||
size_t served = 0;
|
||||
std::string remote_addr;
|
||||
@@ -14921,11 +14845,6 @@ inline Server &Server::set_start_handler(StartHandler handler) {
|
||||
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) {
|
||||
address_family_ = family;
|
||||
return *this;
|
||||
@@ -15048,11 +14967,6 @@ 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;
|
||||
@@ -15731,22 +15645,12 @@ inline bool Server::listen_internal() {
|
||||
return ret;
|
||||
}
|
||||
|
||||
// Closes the socket and returns false when the accept handler refuses it.
|
||||
inline bool Server::admit_accepted_socket(socket_t sock) const {
|
||||
inline void Server::prepare_accepted_socket(socket_t sock) const {
|
||||
detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec_,
|
||||
read_timeout_usec_);
|
||||
detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec_,
|
||||
write_timeout_usec_);
|
||||
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.
|
||||
@@ -15785,7 +15689,7 @@ inline bool Server::accept_loop(TaskQueue &task_queue) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (!admit_accepted_socket(sock)) { continue; }
|
||||
prepare_accepted_socket(sock);
|
||||
|
||||
if (!task_queue.enqueue(
|
||||
[this, sock]() { process_and_close_socket(sock); })) {
|
||||
@@ -16469,10 +16373,6 @@ 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);
|
||||
}
|
||||
@@ -16487,14 +16387,17 @@ 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, options, stopping);
|
||||
ws::WebSocket ws(std::move(ws_strm), req, true,
|
||||
websocket_ping_interval_sec_,
|
||||
websocket_max_missed_pongs_, 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, options, stopping);
|
||||
ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
|
||||
websocket_max_missed_pongs_, stopping);
|
||||
ws_route->handler(req, ws);
|
||||
return true;
|
||||
}
|
||||
@@ -16586,29 +16489,10 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
|
||||
inline bool Server::is_valid() const { return !has_invalid_registration_; }
|
||||
|
||||
inline bool Server::process_and_close_socket(socket_t sock) {
|
||||
std::string remote_addr;
|
||||
int remote_port = 0;
|
||||
detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
|
||||
|
||||
std::string local_addr;
|
||||
int local_port = 0;
|
||||
detail::get_local_ip_and_port(sock, local_addr, local_port);
|
||||
|
||||
bool websocket_upgraded = false;
|
||||
auto ret = serve_guarded([&]() {
|
||||
return detail::process_server_socket(
|
||||
svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
|
||||
read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
|
||||
write_timeout_usec_,
|
||||
[&](Stream &strm, bool close_connection, bool &connection_closed) {
|
||||
return process_request(strm, remote_addr, remote_port, local_addr,
|
||||
local_port, close_connection,
|
||||
connection_closed, nullptr,
|
||||
&websocket_upgraded);
|
||||
});
|
||||
});
|
||||
|
||||
detail::drain_and_close_socket(sock);
|
||||
auto conn = new_keep_alive_connection(sock);
|
||||
conn->wait_in_place = true;
|
||||
auto ret = conn->resume();
|
||||
conn->close_served(ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -16747,7 +16631,7 @@ inline bool Server::parking_loop(TaskQueue &task_queue) {
|
||||
}
|
||||
// Some platforms make it non-blocking like the listening socket.
|
||||
detail::set_nonblocking(sock, false);
|
||||
if (!admit_accepted_socket(sock)) { continue; }
|
||||
prepare_accepted_socket(sock);
|
||||
park(new_keep_alive_connection(sock), now);
|
||||
if (idle.count() > 0) { next_idle = now + idle; }
|
||||
}
|
||||
@@ -16793,7 +16677,7 @@ Server::resume_connection(std::shared_ptr<KeepAliveConnection> conn) {
|
||||
c.release_buffers(); // it may stay idle for long
|
||||
if (st.give_back(conn)) { return; }
|
||||
}
|
||||
c.close_served(!c.turn.websocket_upgraded && ret);
|
||||
c.close_served(ret);
|
||||
}
|
||||
|
||||
inline void Server::output_log(const Request &req, const Response &res) const {
|
||||
@@ -20324,9 +20208,9 @@ inline bool ssl_free_buffers_is_safe(unsigned long version) {
|
||||
} // namespace detail
|
||||
#endif
|
||||
|
||||
// A connection that keep-alive parking keeps for SSLServer. The worker that
|
||||
// first resumes it runs the handshake, so one that has not sent its
|
||||
// ClientHello yet waits in the event loop like an idle connection.
|
||||
// The connection of SSLServer. The worker that first resumes it runs the
|
||||
// handshake, so with parking one that has not sent its ClientHello yet waits
|
||||
// in the event loop like an idle connection.
|
||||
struct SSLServer::TlsConnection final : Server::KeepAliveConnection {
|
||||
TlsConnection(socket_t s, SSLServer &server)
|
||||
: KeepAliveConnection(s, server), ssl_svr(server) {}
|
||||
@@ -20424,47 +20308,6 @@ inline tls::session_t SSLServer::start_session(socket_t sock) {
|
||||
return session;
|
||||
}
|
||||
|
||||
inline bool SSLServer::process_and_close_socket(socket_t sock) {
|
||||
auto session = start_session(sock);
|
||||
if (!session) {
|
||||
detail::shutdown_socket(sock);
|
||||
detail::close_socket(sock);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Use scope_exit to ensure cleanup on all paths (including exceptions)
|
||||
bool ret = false;
|
||||
bool websocket_upgraded = false;
|
||||
auto cleanup = detail::scope_exit([&] {
|
||||
tls::shutdown(session, !websocket_upgraded && ret);
|
||||
tls::free_session(session);
|
||||
detail::drain_and_close_socket(sock);
|
||||
});
|
||||
|
||||
std::string remote_addr;
|
||||
int remote_port = 0;
|
||||
detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
|
||||
|
||||
std::string local_addr;
|
||||
int local_port = 0;
|
||||
detail::get_local_ip_and_port(sock, local_addr, local_port);
|
||||
|
||||
ret = serve_guarded([&]() {
|
||||
return detail::process_server_socket_ssl(
|
||||
svr_sock_, session, sock, keep_alive_max_count_,
|
||||
keep_alive_timeout_sec_, read_timeout_sec_, read_timeout_usec_,
|
||||
write_timeout_sec_, write_timeout_usec_,
|
||||
[&](Stream &strm, bool close_connection, bool &connection_closed) {
|
||||
return process_request(
|
||||
strm, remote_addr, remote_port, local_addr, local_port,
|
||||
close_connection, connection_closed,
|
||||
[&](Request &req) { req.ssl = session; }, &websocket_upgraded);
|
||||
});
|
||||
});
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
inline bool SSLServer::update_certs_pem(const char *cert_pem,
|
||||
const char *key_pem,
|
||||
const char *client_ca_pem,
|
||||
@@ -25014,8 +24857,6 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
||||
return true;
|
||||
}
|
||||
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.
|
||||
send_close(impl::is_valid_close_payload(payload)
|
||||
@@ -25040,12 +24881,13 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
||||
std::string payload;
|
||||
bool fin;
|
||||
|
||||
// What is left of the limit (all of it between messages), but always room
|
||||
// for a control frame, which the limit does not cover.
|
||||
// While a message is assembled, only what is left of the limit, but room
|
||||
// for a control frame, which may come between its fragments.
|
||||
auto max_len =
|
||||
max_message_length_ == 0
|
||||
? size_t(0)
|
||||
: (std::max)(size_t(125), max_message_length_ - message_.size());
|
||||
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());
|
||||
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
|
||||
@@ -25085,7 +24927,8 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
||||
message_ = std::move(payload);
|
||||
message_kind_ = opcode == Opcode::Text ? Text : Binary;
|
||||
}
|
||||
if (max_message_length_ > 0 && message_.size() > max_message_length_) {
|
||||
if (CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH > 0 &&
|
||||
message_.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
|
||||
return fail_with(CloseStatus::MessageTooBig);
|
||||
}
|
||||
if (!fin) { continue; }
|
||||
@@ -25142,10 +24985,7 @@ 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) {
|
||||
set_close_status(resp);
|
||||
break;
|
||||
}
|
||||
if (op == Opcode::Close) { break; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25197,25 +25037,6 @@ 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
|
||||
@@ -25458,12 +25279,9 @@ inline Result WebSocketClient::connect() {
|
||||
}
|
||||
subprotocol_ = std::move(upgrade.selected_subprotocol);
|
||||
|
||||
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));
|
||||
ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
|
||||
websocket_ping_interval_sec_,
|
||||
websocket_max_missed_pongs_));
|
||||
// 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_;
|
||||
@@ -25492,14 +25310,6 @@ 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_;
|
||||
}
|
||||
@@ -25526,10 +25336,6 @@ 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) {
|
||||
|
||||
+5
-1
@@ -26,7 +26,11 @@ endif()
|
||||
|
||||
find_package(CURL REQUIRED)
|
||||
|
||||
add_executable(httplib-test test.cc include_httplib.cc $<$<BOOL:${WIN32}>:include_windows_h.cc>)
|
||||
# include_httplib.cc checks the header-only build, as the Makefile's split
|
||||
# targets leave it out too.
|
||||
add_executable(httplib-test test.cc
|
||||
$<$<NOT:$<BOOL:${HTTPLIB_IS_COMPILED}>>:include_httplib.cc>
|
||||
$<$<BOOL:${WIN32}>:include_windows_h.cc>)
|
||||
target_compile_options(httplib-test PRIVATE "$<$<CXX_COMPILER_ID:MSVC>:/utf-8;/bigobj>")
|
||||
target_link_libraries(httplib-test PRIVATE httplib GTest::gtest_main CURL::libcurl)
|
||||
gtest_discover_tests(httplib-test)
|
||||
|
||||
+16
-3
@@ -1,5 +1,18 @@
|
||||
// The sole purpose of this file is to include httplib.h in a separate
|
||||
// compilation unit, thus verifying that inline keywords have not been forgotten
|
||||
// when linked together with test.cc.
|
||||
// Includes httplib.h in a separate compilation unit, thus verifying that
|
||||
// inline keywords have not been forgotten when linked together with test.cc.
|
||||
|
||||
#include <httplib.h>
|
||||
|
||||
// Nothing in the library calls these, but subclasses that override
|
||||
// process_and_close_socket() do. Instantiating them here, where the split build
|
||||
// does not reach, keeps a change to process_server_socket_core() from breaking
|
||||
// them unnoticed.
|
||||
struct IncludeHttplibServeNothing {
|
||||
bool operator()(httplib::Stream &, bool, bool &) const { return false; }
|
||||
};
|
||||
auto include_httplib_process_server_socket =
|
||||
&httplib::detail::process_server_socket<IncludeHttplibServeNothing>;
|
||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||
auto include_httplib_process_server_socket_ssl =
|
||||
&httplib::detail::process_server_socket_ssl<IncludeHttplibServeNothing>;
|
||||
#endif
|
||||
+180
-428
@@ -2341,7 +2341,6 @@ TEST(BearerTokenAuthTest, SchemeValidation) {
|
||||
{"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
|
||||
{"Bearer abc123", "abc123"},
|
||||
{"bearer abc123", "abc123"}, // scheme match is case-insensitive
|
||||
{"Bearer abc123", "abc123"}, // 1*SP after the scheme
|
||||
};
|
||||
|
||||
for (const auto &c : cases) {
|
||||
@@ -3964,13 +3963,17 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
|
||||
}
|
||||
}
|
||||
|
||||
// Runs one 401 -> Digest-retry round trip with the given WWW-Authenticate
|
||||
// field lines (get_combined_header_value() joins them in receipt order) and
|
||||
// returns the Authorization header of the retry.
|
||||
static std::string
|
||||
get_digest_retry_authorization(const std::vector<std::string> &challenges) {
|
||||
// RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
|
||||
// comma-separated list of challenges, and each challenge may itself carry a
|
||||
// comma-separated auth-param list, so a server can legally offer Basic
|
||||
// before Digest, either as two field lines or packed into one. Runs one 401
|
||||
// -> Digest-retry round trip with the given field lines (get_combined_header_
|
||||
// value() joins them in receipt order) and checks that the retry carries a
|
||||
// well-formed Digest Authorization header naming expected_realm.
|
||||
static void
|
||||
run_digest_challenge_list_test(const std::vector<std::string> &challenges,
|
||||
const std::string &expected_realm) {
|
||||
std::atomic<int> hits{0};
|
||||
std::string authorization;
|
||||
|
||||
Server svr;
|
||||
svr.Get("/x", [&](const Request &req, Response &res) {
|
||||
@@ -3980,7 +3983,11 @@ get_digest_retry_authorization(const std::vector<std::string> &challenges) {
|
||||
res.set_header("WWW-Authenticate", challenge);
|
||||
}
|
||||
} else {
|
||||
authorization = req.get_header_value("Authorization");
|
||||
auto authorization = req.get_header_value("Authorization");
|
||||
EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
|
||||
EXPECT_NE(std::string::npos,
|
||||
authorization.find("realm=\"" + expected_realm + "\""));
|
||||
EXPECT_EQ(std::string::npos, authorization.find("Basic"));
|
||||
res.set_content("ok", "text/plain");
|
||||
}
|
||||
});
|
||||
@@ -3996,25 +4003,9 @@ get_digest_retry_authorization(const std::vector<std::string> &challenges) {
|
||||
Client cli(HOST, port);
|
||||
cli.set_digest_auth("hello", "world");
|
||||
auto res = cli.Get("/x");
|
||||
EXPECT_TRUE(res) << "Error: " << to_string(res.error());
|
||||
EXPECT_EQ(2, hits.load());
|
||||
return authorization;
|
||||
}
|
||||
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
|
||||
|
||||
// RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
|
||||
// comma-separated list of challenges, and each challenge may itself carry a
|
||||
// comma-separated auth-param list, so a server can legally offer Basic
|
||||
// before Digest, either as two field lines or packed into one. Checks that
|
||||
// the retry carries a well-formed Digest Authorization header naming
|
||||
// expected_realm.
|
||||
static void
|
||||
run_digest_challenge_list_test(const std::vector<std::string> &challenges,
|
||||
const std::string &expected_realm) {
|
||||
auto authorization = get_digest_retry_authorization(challenges);
|
||||
EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
|
||||
EXPECT_NE(std::string::npos,
|
||||
authorization.find("realm=\"" + expected_realm + "\""));
|
||||
EXPECT_EQ(std::string::npos, authorization.find("Basic"));
|
||||
EXPECT_EQ(2, hits.load());
|
||||
}
|
||||
|
||||
static const char *kBasicChallenge = "Basic realm=\"decoy\"";
|
||||
@@ -4043,70 +4034,6 @@ TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
|
||||
"test,realm");
|
||||
}
|
||||
|
||||
// RFC 9110 11.6.1: 1*SP separates the scheme from its first auth-param.
|
||||
TEST(DigestAuthTest, SeveralSpacesAfterScheme) {
|
||||
auto authorization =
|
||||
get_digest_retry_authorization({"Digest realm=\"r\", nonce=\"n\""});
|
||||
EXPECT_NE(std::string::npos, authorization.find("nonce=\"n\""));
|
||||
}
|
||||
|
||||
// RFC 9110 11.2: auth-param names are matched case-insensitively.
|
||||
TEST(DigestAuthTest, ParamNamesAreCaseInsensitive) {
|
||||
auto authorization = get_digest_retry_authorization(
|
||||
{"Digest Realm=\"testrealm\", QOP=\"auth\", Nonce=\"abc123\", "
|
||||
"Algorithm=SHA-256, OPAQUE=\"op\""});
|
||||
EXPECT_NE(std::string::npos, authorization.find("realm=\"testrealm\""));
|
||||
EXPECT_NE(std::string::npos, authorization.find("nonce=\"abc123\""));
|
||||
EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
|
||||
EXPECT_NE(std::string::npos, authorization.find("qop=auth"));
|
||||
EXPECT_NE(std::string::npos, authorization.find("opaque=\"op\""));
|
||||
}
|
||||
|
||||
// The algorithm is matched case-insensitively and sent back as the server
|
||||
// wrote it (RFC 7616 3.4).
|
||||
TEST(DigestAuthTest, AlgorithmValueIsCaseInsensitive) {
|
||||
auto authorization = get_digest_retry_authorization(
|
||||
{"Digest realm=\"r\", nonce=\"n\", qop=\"auth\", algorithm=sha-256"});
|
||||
EXPECT_NE(std::string::npos, authorization.find("algorithm=sha-256"));
|
||||
const std::string prefix = "response=\"";
|
||||
auto b = authorization.find(prefix);
|
||||
ASSERT_NE(std::string::npos, b);
|
||||
b += prefix.size();
|
||||
EXPECT_EQ(64u, authorization.find('"', b) - b); // SHA-256, not MD5
|
||||
}
|
||||
|
||||
// qop options are matched case-insensitively.
|
||||
TEST(DigestAuthTest, QopValueIsCaseInsensitive) {
|
||||
auto authorization = get_digest_retry_authorization(
|
||||
{"Digest realm=\"r\", nonce=\"n\", qop=\"AUTH\""});
|
||||
EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
|
||||
}
|
||||
|
||||
// auth-int hashes req.body, which is empty when a content provider streams the
|
||||
// body, so it is chosen only when the server offers no auth.
|
||||
TEST(DigestAuthTest, PrefersQopAuthOverAuthInt) {
|
||||
auto authorization = get_digest_retry_authorization(
|
||||
{"Digest realm=\"r\", nonce=\"n\", qop=\"auth-int, auth\""});
|
||||
EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
|
||||
|
||||
authorization = get_digest_retry_authorization(
|
||||
{"Digest realm=\"r\", nonce=\"n\", qop=\"Auth-Int\""});
|
||||
EXPECT_NE(std::string::npos, authorization.find("qop=auth-int,"));
|
||||
}
|
||||
|
||||
// RFC 7616 3.7: the client uses the first Digest challenge it can answer.
|
||||
TEST(DigestAuthTest, SkipsUnanswerableDigestChallenges) {
|
||||
auto authorization = get_digest_retry_authorization(
|
||||
{"Digest realm=\"r\", nonce=\"n1\", algorithm=SHA-512-256, "
|
||||
"Digest realm=\"r\", nonce=\"n2\", algorithm=SHA-256"});
|
||||
EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
|
||||
EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
|
||||
|
||||
authorization = get_digest_retry_authorization(
|
||||
{"Digest realm=\"r\", qop=\"auth\", Digest realm=\"r\", nonce=\"n2\""});
|
||||
EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
|
||||
}
|
||||
|
||||
// RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
|
||||
// the params and leaves out the fragment.
|
||||
TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
|
||||
@@ -4141,16 +4068,13 @@ TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
|
||||
EXPECT_EQ(target, uri);
|
||||
}
|
||||
|
||||
// A Digest challenge the client can't answer (realm or nonce missing, or no
|
||||
// algorithm or qop option it implements) must leave the 401 as it is, without
|
||||
// a retry.
|
||||
static void
|
||||
run_unanswerable_digest_challenge_test(const std::string &challenge) {
|
||||
std::atomic<int> hits{0};
|
||||
|
||||
// RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
|
||||
// make_digest_authentication_header() dereferences both unconditionally, so
|
||||
// a server sending a challenge missing either one must not be treated as
|
||||
// usable -- doing so used to crash the client with std::out_of_range.
|
||||
static void run_digest_challenge_missing_field_test(const char *challenge) {
|
||||
Server svr;
|
||||
svr.Get("/x", [&](const Request & /*req*/, Response &res) {
|
||||
++hits;
|
||||
res.status = StatusCode::Unauthorized_401;
|
||||
res.set_header("WWW-Authenticate", challenge);
|
||||
});
|
||||
@@ -4168,56 +4092,65 @@ run_unanswerable_digest_challenge_test(const std::string &challenge) {
|
||||
auto res = cli.Get("/x");
|
||||
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
|
||||
EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
|
||||
EXPECT_EQ(1, hits.load());
|
||||
}
|
||||
|
||||
TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
|
||||
run_unanswerable_digest_challenge_test("Digest qop=\"auth\"");
|
||||
run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
|
||||
}
|
||||
|
||||
TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
|
||||
run_unanswerable_digest_challenge_test("Digest realm=\"r\", qop=\"auth\"");
|
||||
run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
|
||||
}
|
||||
|
||||
TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
|
||||
run_unanswerable_digest_challenge_test("Digest nonce=\"n\", qop=\"auth\"");
|
||||
run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
|
||||
}
|
||||
|
||||
// RFC 7616 3.3: a challenge with an algorithm the client doesn't implement is
|
||||
// ignored. The last value isn't a token and would otherwise inject auth-params
|
||||
// into the Authorization header.
|
||||
TEST(DigestAuthTest, UnsupportedAlgorithmIsIgnored) {
|
||||
for (auto algorithm :
|
||||
{"SHA-512-256", "MD5-sess", "\"MD5, injected=\\\"y\\\"\""}) {
|
||||
SCOPED_TRACE(algorithm);
|
||||
run_unanswerable_digest_challenge_test(
|
||||
std::string("Digest realm=\"r\", nonce=\"n\", qop=\"auth\", "
|
||||
"algorithm=") +
|
||||
algorithm);
|
||||
}
|
||||
}
|
||||
|
||||
// RFC 7616 3.3: qop options the client doesn't implement are ignored, and a
|
||||
// challenge that offers no other can't be answered.
|
||||
TEST(DigestAuthTest, UnsupportedQopIsIgnored) {
|
||||
run_unanswerable_digest_challenge_test(
|
||||
"Digest realm=\"r\", nonce=\"n\", qop=\"auth-conf\"");
|
||||
}
|
||||
|
||||
// A hostile server can put a '"' in realm/nonce/opaque in its challenge.
|
||||
// parse_www_authenticate() de-escapes quoted-pairs when storing the values, so
|
||||
// the header builder has to re-escape them; otherwise the value breaks out of
|
||||
// its quoted-string and injects extra auth-params into the Authorization.
|
||||
// A hostile server can put a '"' in realm/nonce/opaque, or a non-token
|
||||
// algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
|
||||
// when storing the values, so the header builder has to re-escape them (and
|
||||
// keep algorithm a bare token); otherwise the value breaks out of its
|
||||
// quoted-string and injects extra auth-params into the client's Authorization.
|
||||
TEST(DigestAuthTest, EscapesInjectedAuthParams) {
|
||||
// On the wire the quotes embedded in the value are backslash-escaped.
|
||||
auto authorization = get_digest_retry_authorization(
|
||||
{"Digest realm=\"testrealm\", nonce=\"n\\\"; injected=\\\"x\", "
|
||||
"qop=\"auth\""});
|
||||
std::atomic<int> hits{0};
|
||||
std::string authorization;
|
||||
|
||||
Server svr;
|
||||
svr.Get("/x", [&](const Request &req, Response &res) {
|
||||
if (++hits == 1) {
|
||||
res.status = StatusCode::Unauthorized_401;
|
||||
// On the wire the quotes embedded in the values are backslash-escaped.
|
||||
res.set_header("WWW-Authenticate",
|
||||
"Digest realm=\"testrealm\", "
|
||||
"nonce=\"n\\\"; injected=\\\"x\", "
|
||||
"algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
|
||||
} else {
|
||||
authorization = req.get_header_value("Authorization");
|
||||
res.set_content("ok", "text/plain");
|
||||
}
|
||||
});
|
||||
|
||||
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();
|
||||
|
||||
Client cli(HOST, port);
|
||||
cli.set_digest_auth("hello", "world");
|
||||
auto res = cli.Get("/x");
|
||||
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
|
||||
EXPECT_EQ(2, hits.load());
|
||||
|
||||
EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
|
||||
// The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
|
||||
// inside its quoted-string rather than starting an "injected" auth-param.
|
||||
EXPECT_NE(std::string::npos,
|
||||
authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
|
||||
// A non-token algorithm falls back to a bare MD5 token, dropping the payload.
|
||||
EXPECT_EQ(std::string::npos, authorization.find("injected2"));
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -6522,8 +6455,8 @@ TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
|
||||
|
||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||
TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
|
||||
// SSLServer::process_and_close_socket() is a separate overload with its own
|
||||
// guard, so it is exercised on its own.
|
||||
// SSLServer serves through its own connection type, so it is exercised on
|
||||
// its own.
|
||||
SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
|
||||
ASSERT_TRUE(svr.is_valid());
|
||||
svr.new_task_queue = [] { return new ThreadPool(1); };
|
||||
@@ -21748,8 +21681,6 @@ TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
|
||||
const std::vector<std::pair<std::string, std::string>> cases = {
|
||||
{"next", "/dir/next"},
|
||||
{"./next?x=1", "/dir/next?x=1"},
|
||||
{"next?source=https://example.com/catalog",
|
||||
"/dir/next?source=https://example.com/catalog"},
|
||||
{"../other", "/other"},
|
||||
};
|
||||
for (const auto &c : cases) {
|
||||
@@ -22466,14 +22397,6 @@ TEST(ParseUrlTest, SchemeEdgeCases) {
|
||||
ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
|
||||
EXPECT_EQ("https", uc.scheme);
|
||||
}
|
||||
{
|
||||
detail::UrlComponents uc;
|
||||
ASSERT_TRUE(detail::parse_url("/path?next=https://example.com/", uc));
|
||||
EXPECT_TRUE(uc.scheme.empty());
|
||||
EXPECT_TRUE(uc.host.empty());
|
||||
EXPECT_EQ("/path", uc.path);
|
||||
EXPECT_EQ("?next=https://example.com/", uc.query);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ParseUrlTest, PortEdgeCases) {
|
||||
@@ -29342,8 +29265,6 @@ 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) {
|
||||
@@ -29475,6 +29396,41 @@ 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");
|
||||
@@ -29532,24 +29488,15 @@ 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) {
|
||||
@@ -31138,86 +31085,6 @@ 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);
|
||||
@@ -31432,13 +31299,12 @@ 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 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.
|
||||
// sent a while after the one before, much longer than the handler's timeout.
|
||||
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);
|
||||
@@ -31446,9 +31312,11 @@ static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
|
||||
ws.set_read_timeout(0, 10000);
|
||||
std::string msg;
|
||||
ws::ReadResult r;
|
||||
while ((r = ws.read(msg)) == ws::Timeout) {
|
||||
timeouts++;
|
||||
}
|
||||
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);
|
||||
if (r == ws::Text) { received = msg; }
|
||||
done = true;
|
||||
});
|
||||
@@ -31464,24 +31332,19 @@ 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); });
|
||||
// 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 (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));
|
||||
}
|
||||
|
||||
for (int i = 0; i < 5000 && !done; i++) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
for (int i = 0; i < 500 && !done; i++) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
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) {
|
||||
@@ -31640,73 +31503,6 @@ TEST(WebSocketTest, ClientFailsAMaskedFrameWithProtocolError) {
|
||||
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
|
||||
class WebSocketSSLIntegrationTest : public ::testing::Test {
|
||||
protected:
|
||||
@@ -34743,11 +34539,6 @@ bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
|
||||
detail::read_socket(sock, &c, 1, 0) <= 0;
|
||||
}
|
||||
|
||||
// Whether the server closes `sock` without answering a request.
|
||||
bool get_refused(socket_t sock, int timeout_ms) {
|
||||
return send_get(sock) && sees_eof(sock, in_ms(timeout_ms));
|
||||
}
|
||||
|
||||
bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
|
||||
auto deadline = in_ms(timeout_ms);
|
||||
while (!cond()) {
|
||||
@@ -34757,9 +34548,10 @@ bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
|
||||
return true;
|
||||
}
|
||||
|
||||
void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
|
||||
void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue,
|
||||
bool parking = true) {
|
||||
svr.new_task_queue = std::move(new_task_queue);
|
||||
svr.set_keep_alive_parking(true);
|
||||
svr.set_keep_alive_parking(parking);
|
||||
svr.Get("/", [](const Request &, Response &res) {
|
||||
res.set_content("ok", "text/plain");
|
||||
});
|
||||
@@ -34823,6 +34615,63 @@ private:
|
||||
|
||||
} // namespace parking_test
|
||||
|
||||
// A connection that sends nothing is closed at the keep-alive timeout, not the
|
||||
// read timeout, whether or not it is parked.
|
||||
TEST(KeepAliveParkingTest, FirstRequestWaitsForTheKeepAliveTimeout) {
|
||||
using namespace parking_test;
|
||||
// Both modes at once, since each waits a whole second.
|
||||
Server svrs[2];
|
||||
std::unique_ptr<RunningServer> running[2];
|
||||
Sockets socks; // after `running`, so that the sockets close first
|
||||
for (auto i = 0; i < 2; i++) {
|
||||
serve_ok(svrs[i], threads(1), /*parking=*/i == 0);
|
||||
svrs[i].set_read_timeout(10, 0);
|
||||
svrs[i].set_keep_alive_timeout(1);
|
||||
running[i].reset(new RunningServer(svrs[i]));
|
||||
ASSERT_NE(INVALID_SOCKET, socks.connect(running[i]->port));
|
||||
}
|
||||
|
||||
auto early = in_ms(500);
|
||||
for (size_t i = 0; i < 2; i++) {
|
||||
SCOPED_TRACE(i == 0 ? "parking" : "no parking");
|
||||
EXPECT_FALSE(sees_eof(socks.socks[i], early));
|
||||
}
|
||||
auto late = in_ms(2500);
|
||||
for (size_t i = 0; i < 2; i++) {
|
||||
SCOPED_TRACE(i == 0 ? "parking" : "no parking");
|
||||
EXPECT_TRUE(sees_eof(socks.socks[i], late));
|
||||
}
|
||||
}
|
||||
|
||||
// Without parking, a request that arrived before stop() is still served when
|
||||
// its worker gets to it.
|
||||
TEST(KeepAliveParkingTest, RequestBeforeStopIsServedWithoutParking) {
|
||||
using namespace parking_test;
|
||||
std::atomic<int> ok{0}, full{0};
|
||||
Server svr;
|
||||
serve_ok(svr, [&] { return new CountingTaskQueue(1, 0, ok, full); }, false);
|
||||
Gate gate;
|
||||
svr.Get("/gate", [&](const Request &, Response &res) {
|
||||
gate.wait();
|
||||
res.set_content("ok", "text/plain");
|
||||
});
|
||||
RunningServer running(svr);
|
||||
Sockets socks;
|
||||
|
||||
// Hold the only worker, and queue a connection whose request has arrived.
|
||||
auto held = socks.connect(running.port);
|
||||
ASSERT_TRUE(send_get(held, "/gate"));
|
||||
ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
|
||||
auto waiting = socks.connect(running.port);
|
||||
ASSERT_TRUE(send_get(waiting));
|
||||
ASSERT_TRUE(wait_until([&] { return ok == 2; }, 2000));
|
||||
|
||||
svr.stop();
|
||||
gate.open();
|
||||
EXPECT_TRUE(receives_ok(held, 2000));
|
||||
EXPECT_TRUE(receives_ok(waiting, 2000));
|
||||
}
|
||||
|
||||
TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
|
||||
using namespace parking_test;
|
||||
Server svr;
|
||||
@@ -35077,9 +34926,11 @@ TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
|
||||
|
||||
TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
|
||||
using namespace parking_test;
|
||||
for (auto parking : {true, false}) {
|
||||
SCOPED_TRACE(parking ? "parking" : "no parking");
|
||||
SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
|
||||
ASSERT_TRUE(svr.is_valid());
|
||||
serve_ok(svr, threads(1));
|
||||
serve_ok(svr, threads(1), parking);
|
||||
RunningServer running(svr);
|
||||
Sockets socks;
|
||||
|
||||
@@ -35088,6 +34939,7 @@ TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
|
||||
EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
|
||||
EXPECT_NE(0, svr.ssl_last_error());
|
||||
}
|
||||
}
|
||||
|
||||
TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
|
||||
using namespace parking_test;
|
||||
@@ -35109,103 +34961,3 @@ TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
|
||||
std::chrono::milliseconds(500));
|
||||
}
|
||||
#endif
|
||||
|
||||
TEST(AcceptHandlerTest, RefusedConnectionIsClosedUnread) {
|
||||
using namespace parking_test;
|
||||
for (auto parking : {false, true}) {
|
||||
SCOPED_TRACE(parking);
|
||||
Server svr;
|
||||
serve_ok(svr, threads(2));
|
||||
svr.set_keep_alive_parking(parking);
|
||||
std::atomic<int> served{0};
|
||||
svr.set_pre_routing_handler([&](const Request &, Response &) {
|
||||
served++;
|
||||
return Server::HandlerResponse::Unhandled;
|
||||
});
|
||||
std::atomic<bool> allow{false};
|
||||
std::atomic<bool> peer_seen{false};
|
||||
svr.set_accept_handler([&](socket_t sock) {
|
||||
sockaddr_in addr{};
|
||||
socklen_t len = sizeof(addr);
|
||||
peer_seen =
|
||||
getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) == 0 &&
|
||||
addr.sin_family == AF_INET &&
|
||||
ntohl(addr.sin_addr.s_addr) == INADDR_LOOPBACK;
|
||||
return allow.load();
|
||||
});
|
||||
RunningServer running(svr);
|
||||
Sockets socks;
|
||||
|
||||
EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
|
||||
EXPECT_TRUE(peer_seen);
|
||||
EXPECT_EQ(0, served);
|
||||
|
||||
allow = true;
|
||||
EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
|
||||
EXPECT_EQ(1, served);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(AcceptHandlerTest, HandlerSeesTheReadTimeout) {
|
||||
using namespace parking_test;
|
||||
Server svr;
|
||||
serve_ok(svr, threads(1));
|
||||
svr.set_read_timeout(std::chrono::milliseconds(50));
|
||||
std::atomic<bool> timed_out{false};
|
||||
svr.set_accept_handler([&](socket_t sock) {
|
||||
char c;
|
||||
timed_out = detail::read_socket(sock, &c, 1, 0) < 0;
|
||||
return true;
|
||||
});
|
||||
RunningServer running(svr);
|
||||
Sockets socks;
|
||||
|
||||
auto sock = socks.connect(running.port);
|
||||
EXPECT_TRUE(wait_until([&] { return timed_out.load(); }, 1000));
|
||||
EXPECT_TRUE(get_ok(sock, 1000));
|
||||
}
|
||||
|
||||
#ifndef CPPHTTPLIB_NO_EXCEPTIONS
|
||||
TEST(AcceptHandlerTest, ThrowingHandlerRefusesTheConnection) {
|
||||
using namespace parking_test;
|
||||
Server svr;
|
||||
serve_ok(svr, threads(1));
|
||||
std::atomic<bool> throws{true};
|
||||
svr.set_accept_handler([&](socket_t) -> bool {
|
||||
if (throws) { throw std::runtime_error("refused"); }
|
||||
return true;
|
||||
});
|
||||
std::atomic<int> logged{0};
|
||||
svr.set_error_logger([&](const Error &err, const Request *) {
|
||||
if (err == Error::UserCallbackException) { logged++; }
|
||||
});
|
||||
RunningServer running(svr);
|
||||
Sockets socks;
|
||||
|
||||
EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
|
||||
EXPECT_EQ(1, logged);
|
||||
|
||||
throws = false;
|
||||
EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||
TEST(AcceptHandlerTest, RefusedTlsConnectionSkipsTheHandshake) {
|
||||
using namespace parking_test;
|
||||
for (auto parking : {false, true}) {
|
||||
SCOPED_TRACE(parking);
|
||||
SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
|
||||
ASSERT_TRUE(svr.is_valid());
|
||||
serve_ok(svr, threads(1));
|
||||
svr.set_keep_alive_parking(parking);
|
||||
svr.set_accept_handler([](socket_t) { return false; });
|
||||
RunningServer running(svr);
|
||||
Sockets socks;
|
||||
|
||||
// A handshake on a plain request would fail and set ssl_last_error().
|
||||
EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
|
||||
EXPECT_EQ(0, svr.ssl_last_error());
|
||||
}
|
||||
}
|
||||
#endif
|
||||
Reference in new issue
Block a user