Compare commits

...
Author SHA1 Message Date
yhirose 90bd0f7daf Merge remote-tracking branch 'origin/master' into unify-serving-paths 2026-11-26 19:26:20 -05:00
Eminy d5befb4326 Match Content-Disposition parameter names case-insensitively (#2698)
parse_disposition_params stored parameter names as they arrived, while FormDataParser looks up "name", "filename" and "filename*" in lower case. A part with NAME= was rejected with 400, and one with FILENAME*= was silently treated as a plain field. Parameter names are case-insensitive (RFC 2045 section 5.1), so the names are now lowercased when stored, as extract_media_type already does for Content-Type. Values keep their case.
2026-11-26 19:02:31 -05:00
bb00fece7c Send a Close frame when a WebSocket read fails on the peer's error (#2694)
* Send a Close frame when a WebSocket read fails on the peer's error

WebSocket::read() answered a malformed Close with 1002 and invalid UTF-8
with 1007, but every other protocol error, and a message over
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, only marked the connection
closed, so the peer saw the TCP connection drop without a reason. That
covers set RSV bits, a mask bit the wrong way, a fragmented or oversized
control frame, a 64-bit length with its top bit set, a reserved opcode,
a continuation without a message to continue or a new message inside a
fragmented one, and a frame or message over the limit. RFC 6455 Section
7.1.7 says an endpoint that fails the connection should send a Close
frame with the status first.

FrameReader::read() now tells these apart from a failed read, with
FrameRead::ProtocolError and FrameRead::TooBig, and read() answers them,
and the opcode and fragmentation errors it finds itself, with a Close
frame of 1002 or 1009. As for the malformed Close, it does not wait for
the peer's reply: the stream may be in the middle of the bad frame, and
Section 7.1.7 says to read nothing more. A read that fails or times out
still closes without a frame. This applies to Server's WebSocket
handlers and to WebSocketClient alike.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Send every Close frame through one helper

WebSocket::close(), the Close echo and the new failure path each encoded
a status and wrote a Close frame under write_mutex_. They now share
send_close() and ws::impl::close_payload(), so every path that ends the
connection also wakes the heartbeat thread. The tests share a helper for
the raw-socket exchange and decode the client's Close with
read_websocket_frame().

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-11-26 17:55:50 -05:00
yhirose 9af51b109f Tell service failures from client failures in the online tests (#2699)
The no-exceptions CI job runs the *_Online tests, and over its last 40
runs 27 failed, each time on tests that never reached what they check:

- google.com answered CI runners with 302 or 429 instead of the 301 or
  200 the certificate verification tests asserted. Those tests only need
  a response, which proves the handshake and the verification passed, as
  UniversalClientRedirectTest.EnableSystemCaCarriesOver_Online already
  does. Issue2004_Online is a regression test for a crash, so a response
  is enough there too.
- badssl.com drops connections from CI runners before it sends its
  certificate, so the hostname and self-signed checks never ran. From
  elsewhere, the same OpenSSL 3.0.13 gets the certificate and the
  expected verification error.

Generalize retry_gateway_errors() to retry_service_failures(), which also
treats a handshake that failed before any verdict on the certificate as
the service's failure, and use it for the two badssl.com tests. Such a
handshake failure in the client itself is caught by the TLS tests that
run against local servers.
2026-11-26 17:37:46 -05:00
yhirose f181182a9d Leave include_httplib.cc out of the compiled CMake test build
include_httplib.cc now instantiates detail::process_server_socket(),
which the split header does not declare, so the compiled CMake build
failed to compile it. The file only means something for the header-only
build anyway, and the Makefile's split targets already leave it out.
2026-11-26 08:13:35 -05:00
yhirose bba6042bba Decide the graceful close in close_served() itself
Both callers of close_served() worked out from the same connection
whether to close gracefully, so pass what resume() returned and let the
connection check turn.websocket_upgraded once.

Also wait for the keep-alive timeout in both modes at once, which halves
the test to about a second, and describe include_httplib.cc for what it
now does.
2026-11-25 23:39:27 -05:00
yhirose 8037789492 Let ab.sh measure without keep-alive
--no-keep-alive sends "Connection: close" so that every request opens a
new connection, which measures the cost of accepting and setting one up.
bombardier's default fasthttp client ignores its own -a flag, so the
header is the way to do it.

On macOS, keep runs short (--duration 1s): at about 20k connections per
second, closed connections pile up in TIME_WAIT and a 5-second run
starts failing, on any ref.
2026-11-25 23:15:41 -05:00
yhirose eea8ce9798 Describe KeepAliveConnection as the one serving path
The comments said these connections belong to keep-alive parking, which is no longer true now that every accepted socket is served through one.
2026-11-25 23:00:11 -05:00
yhirose 84acde731b Serve SSLServer without parking through TlsConnection too
SSLServer::process_and_close_socket() repeated the handshake, the
stream and the cleanup that TlsConnection already has. With the base
implementation now creating its connection through
new_keep_alive_connection(), the override is no longer needed: the base
gets a TlsConnection and serves it the same way.

The handshake now runs inside serve_guarded(), so an exception from it
is caught like one from a handler, and it is not started once the server
is stopping.
2026-11-25 22:59:41 -05:00
yhirose daf46bd502 Serve connections without parking through KeepAliveConnection
Server::process_and_close_socket() repeated what KeepAliveConnection
already does for keep-alive parking: make the stream, look up the
addresses, run process_server_socket_core(), and close. Make it create
the connection with new_keep_alive_connection() and resume() it once,
with a flag that waits for the next request on the worker through
keep_alive(), as before. The flag is checked first, ahead of the stop
check, since keep_alive() serves a request that is already on the socket
even when the server is stopping.

detail::process_server_socket() and process_server_socket_ssl() are no
longer called by the library, but overrides of process_and_close_socket()
call them. Instantiate them in include_httplib.cc, which only the header
build compiles, so that a change to process_server_socket_core() cannot
break them unnoticed.
2026-11-25 22:56:54 -05:00
yhirose 084b30055e Test what both serving paths must keep in common
Before the legacy path and keep-alive parking share one serving path,
pin down what the legacy path does that the existing tests cannot tell
apart:

- A connection that sends nothing is closed at the keep-alive timeout,
  not the read timeout. Both default to 5 seconds, so a wrong wait went
  unnoticed.
- Without parking, a request that arrived before stop() is still served
  when its worker gets to it.
- A failed TLS handshake closes the connection and sets
  ssl_last_error(), now checked with parking off as well.
2026-11-25 22:53:06 -05:00
5 changed files with 415 additions and 243 deletions

No files matched your search

+12 -2
View File
@@ -4,7 +4,7 @@
# #
# Usage: ./ab.sh [--base REF] [--head REF] [--rounds N] [--duration S] # Usage: ./ab.sh [--base REF] [--head REF] [--rounds N] [--duration S]
# [--connections N] [--threads N] [--path PATH] [--tls] # [--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: # --path selects the workload. The harness serves:
# / small body via set_content(); the response line, the # / small body via set_content(); the response line, the
@@ -20,6 +20,9 @@
# --tls runs the same workload over HTTPS, which writes through # --tls runs the same workload over HTTPS, which writes through
# SSLSocketStream instead of SocketStream. # 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 # --timeout is bombardier's per-request timeout. Its 2s default aborts large
# TLS responses, and the run then fails on the non-2xx check. # TLS responses, and the run then fails on the non-2xx check.
# #
@@ -43,6 +46,7 @@ REQ_PATH="/"
TLS=0 TLS=0
LARGE_MIB=1 LARGE_MIB=1
TIMEOUT="30s" TIMEOUT="30s"
NO_KEEP_ALIVE=0
while [ $# -gt 0 ]; do while [ $# -gt 0 ]; do
case "$1" in case "$1" in
@@ -56,10 +60,16 @@ while [ $# -gt 0 ]; do
--large-mib) LARGE_MIB="$2"; shift 2 ;; --large-mib) LARGE_MIB="$2"; shift 2 ;;
--timeout) TIMEOUT="$2"; shift 2 ;; --timeout) TIMEOUT="$2"; shift 2 ;;
--tls) TLS=1; shift ;; --tls) TLS=1; shift ;;
--no-keep-alive) NO_KEEP_ALIVE=1; shift ;;
*) echo "Unknown option: $1" >&2; exit 1 ;; *) echo "Unknown option: $1" >&2; exit 1 ;;
esac esac
done 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 bombardier >/dev/null || { echo "Error: bombardier not found" >&2; exit 1; }
command -v python3 >/dev/null || { echo "Error: python3 not found" >&2; exit 1; } command -v python3 >/dev/null || { echo "Error: python3 not found" >&2; exit 1; }
@@ -162,7 +172,7 @@ measure() {
done done
set +e 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) "$SCHEME://127.0.0.1:$PORT$REQ_PATH" 2>/dev/null)
rc=$? rc=$?
set -e set -e
+87 -126
View File
@@ -2589,7 +2589,7 @@ private:
ContentReceiver multipart_receiver) const; ContentReceiver multipart_receiver) const;
virtual bool process_and_close_socket(socket_t sock); 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> virtual std::shared_ptr<KeepAliveConnection>
new_keep_alive_connection(socket_t sock); new_keep_alive_connection(socket_t sock);
@@ -3551,7 +3551,6 @@ public:
int ssl_last_error() const { return last_ssl_error_; } int ssl_last_error() const { return last_ssl_error_; }
private: private:
bool process_and_close_socket(socket_t sock) override;
std::shared_ptr<KeepAliveConnection> std::shared_ptr<KeepAliveConnection>
new_keep_alive_connection(socket_t sock) override; new_keep_alive_connection(socket_t sock) override;
struct TlsConnection; struct TlsConnection;
@@ -4871,9 +4870,10 @@ namespace impl {
bool is_valid_utf8(const std::string &s); bool is_valid_utf8(const std::string &s);
// Three states: a frame, a failure (the connection cannot be read on), or a // A frame, a failure (the connection cannot be read on), a timeout with the
// timeout with the stream still usable. // stream still usable, or a frame the peer should not have sent: one that
enum class FrameRead { Ok, Fail, Timeout }; // breaks the protocol, or one longer than the limit.
enum class FrameRead { Ok, Fail, Timeout, ProtocolError, TooBig };
// A frame read in as many calls as it takes. A timeout leaves what was read // A frame read in as many calls as it takes. A timeout leaves what was read
// so far in place, and the next read() goes on from there, so the stream is // so far in place, and the next read() goes on from there, so the stream is
@@ -4968,6 +4968,7 @@ private:
} }
void start_heartbeat(); void start_heartbeat();
bool send_frame(Opcode op, const char *data, size_t len, bool fin = true); bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
bool send_close(const std::string &payload);
Stream &strm_; Stream &strm_;
std::unique_ptr<Stream> owned_strm_; std::unique_ptr<Stream> owned_strm_;
@@ -6209,9 +6210,9 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
reset(); reset();
return FrameRead::Fail; return FrameRead::Fail;
}; };
auto fail = [&]() { auto reject = [&](FrameRead r) {
reset(); reset();
return FrameRead::Fail; return r;
}; };
while (have_ < need_) { while (have_ < need_) {
@@ -6221,15 +6222,15 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
if (have_ < 2 || need_ > 2) { continue; } if (have_ < 2 || need_ > 2) { continue; }
// RSV1, RSV2, RSV3 must be 0 when no extension is negotiated // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
if (head_[0] & 0x70) { return fail(); } if (head_[0] & 0x70) { return reject(FrameRead::ProtocolError); }
// RFC 6455 Section 5.5: control frames MUST NOT be fragmented and // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
// MUST have a payload length of 125 bytes or less // MUST have a payload length of 125 bytes or less
auto len7 = head_[1] & 0x7F; auto len7 = head_[1] & 0x7F;
if ((head_[0] & 0x08) && (!(head_[0] & 0x80) || len7 > 125)) { if ((head_[0] & 0x08) && (!(head_[0] & 0x80) || len7 > 125)) {
return fail(); return reject(FrameRead::ProtocolError);
} }
auto masked = (head_[1] & 0x80) != 0; auto masked = (head_[1] & 0x80) != 0;
if (masked != expect_masked) { return fail(); } if (masked != expect_masked) { return reject(FrameRead::ProtocolError); }
// The extended length and the mask key follow // The extended length and the mask key follow
need_ = 2 + (len7 == 126 ? 2 : len7 == 127 ? 8 : 0) + (masked ? 4 : 0); need_ = 2 + (len7 == 126 ? 2 : len7 == 127 ? 8 : 0) + (masked ? 4 : 0);
} }
@@ -6240,7 +6241,7 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
len = (static_cast<uint64_t>(head_[2]) << 8) | head_[3]; len = (static_cast<uint64_t>(head_[2]) << 8) | head_[3];
} else if (len == 127) { } else if (len == 127) {
// RFC 6455 Section 5.2: the most significant bit MUST be 0 // RFC 6455 Section 5.2: the most significant bit MUST be 0
if (head_[2] & 0x80) { return fail(); } if (head_[2] & 0x80) { return reject(FrameRead::ProtocolError); }
len = 0; len = 0;
for (size_t i = 2; i < 10; i++) { for (size_t i = 2; i < 10; i++) {
len = (len << 8) | head_[i]; len = (len << 8) | head_[i];
@@ -6249,7 +6250,7 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
// A max_len of 0 means no limit, as payload_max_length does, and a length // A max_len of 0 means no limit, as payload_max_length does, and a length
// size_t cannot hold (32-bit builds) is refused either way. // size_t cannot hold (32-bit builds) is refused either way.
if ((max_len > 0 && len > max_len) || !detail::fits_in_size_t(len)) { if ((max_len > 0 && len > max_len) || !detail::fits_in_size_t(len)) {
return fail(); return reject(FrameRead::TooBig);
} }
len_ = static_cast<size_t>(len); len_ = static_cast<size_t>(len);
sized_ = true; sized_ = true;
@@ -6303,6 +6304,23 @@ inline bool is_valid_close_payload(const std::string &payload) {
return may_be_sent && is_valid_utf8(payload.substr(2)); return may_be_sent && is_valid_utf8(payload.substr(2));
} }
// The payload of a Close with this status and reason. The reason is cut to fit
// a control frame (RFC 6455 Section 5.5), back to a whole UTF-8 character, and
// a code that may not be sent, such as NoStatus, goes without a payload.
inline std::string close_payload(CloseStatus status,
const std::string &reason = std::string()) {
auto code = static_cast<uint16_t>(status);
std::string payload{static_cast<char>(code >> 8),
static_cast<char>(code & 0xff)};
auto short_reason = reason.substr(0, 123);
while (!short_reason.empty() && !is_valid_utf8(short_reason)) {
short_reason.pop_back();
}
payload += short_reason;
if (!is_valid_close_payload(payload)) { payload.clear(); }
return payload;
}
} // namespace impl } // namespace impl
} // namespace ws } // namespace ws
@@ -10161,8 +10179,10 @@ inline void parse_disposition_params(const std::string &s, Params &params) {
std::string val; std::string val;
divide_param_pair(b, e, key, val); divide_param_pair(b, e, key, val);
// Parameter names are case-insensitive (RFC 2045 §5.1)
if (!key.empty()) { if (!key.empty()) {
params.emplace(trim_double_quotes_copy(key), unquote_param(val)); params.emplace(case_ignore::to_lower(trim_double_quotes_copy(key)),
unquote_param(val));
} }
}); });
} }
@@ -14327,9 +14347,9 @@ WebSocketSSLStream::set_read_interrupt(std::function<bool()> interrupted) {
* Group 4: Server implementation * Group 4: Server implementation
*/ */
// A kept-alive connection that the event loop of set_keep_alive_parking() // A connection served across its requests. With set_keep_alive_parking(), the
// owns while it is idle, and a worker owns while it serves a request. A // event loop owns it while it is idle, and a worker while it serves a request.
// derived class adds the transport: the stream, and for TLS the session. // A derived class adds the transport: the stream, and for TLS the session.
struct Server::KeepAliveConnection { struct Server::KeepAliveConnection {
KeepAliveConnection(socket_t s, Server &server) : svr(server), sock(s) {} KeepAliveConnection(socket_t s, Server &server) : svr(server), sock(s) {}
// Every owner closes it before letting go, which the transport hooks need; // Every owner closes it before letting go, which the transport hooks need;
@@ -14349,8 +14369,8 @@ struct Server::KeepAliveConnection {
// close_notify. // close_notify.
virtual void shut_down(bool /*graceful*/) {} virtual void shut_down(bool /*graceful*/) {}
// On a worker, once the event loop has seen the socket readable. Afterwards // On a worker, with parking once the event loop has seen the socket
// turn.park tells whether it may be parked again. // readable. Afterwards turn.park tells whether it may be parked again.
bool resume() { bool resume() {
turn = Turn(); turn = Turn();
return svr.serve_guarded([this]() { return svr.serve_guarded([this]() {
@@ -14375,11 +14395,11 @@ struct Server::KeepAliveConnection {
sock = INVALID_SOCKET; sock = INVALID_SOCKET;
} }
// From the worker that served it. // From the worker that served it, with what resume() returned.
void close_served(bool graceful) { void close_served(bool ok) {
assert(sock != INVALID_SOCKET); assert(sock != INVALID_SOCKET);
if (opened) { if (opened) {
shut_down(graceful); shut_down(ok && !turn.websocket_upgraded);
detail::drain_and_close_socket(sock); detail::drain_and_close_socket(sock);
} else { } else {
// It never got as far as a request, e.g. a failed TLS handshake. // It never got as far as a request, e.g. a failed TLS handshake.
@@ -14404,6 +14424,10 @@ struct Server::KeepAliveConnection {
} }
bool wait_for_next_request() { 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. // The event loop saw the socket readable just before this ran.
if (turn.woken) { if (turn.woken) {
turn.woken = false; turn.woken = false;
@@ -14427,6 +14451,8 @@ struct Server::KeepAliveConnection {
int remote_port = 0; int remote_port = 0;
int local_port = 0; int local_port = 0;
bool opened = false; // by resume(), once open() has succeeded 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; Turn turn;
size_t served = 0; size_t served = 0;
std::string remote_addr; std::string remote_addr;
@@ -16463,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::is_valid() const { return !has_invalid_registration_; }
inline bool Server::process_and_close_socket(socket_t sock) { inline bool Server::process_and_close_socket(socket_t sock) {
std::string remote_addr; auto conn = new_keep_alive_connection(sock);
int remote_port = 0; conn->wait_in_place = true;
detail::get_remote_ip_and_port(sock, remote_addr, remote_port); auto ret = conn->resume();
conn->close_served(ret);
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);
return ret; return ret;
} }
@@ -16670,7 +16677,7 @@ Server::resume_connection(std::shared_ptr<KeepAliveConnection> conn) {
c.release_buffers(); // it may stay idle for long c.release_buffers(); // it may stay idle for long
if (st.give_back(conn)) { return; } 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 { inline void Server::output_log(const Request &req, const Response &res) const {
@@ -20201,9 +20208,9 @@ inline bool ssl_free_buffers_is_safe(unsigned long version) {
} // namespace detail } // namespace detail
#endif #endif
// A connection that keep-alive parking keeps for SSLServer. The worker that // The connection of SSLServer. The worker that first resumes it runs the
// first resumes it runs the handshake, so one that has not sent its // handshake, so with parking one that has not sent its ClientHello yet waits
// ClientHello yet waits in the event loop like an idle connection. // in the event loop like an idle connection.
struct SSLServer::TlsConnection final : Server::KeepAliveConnection { struct SSLServer::TlsConnection final : Server::KeepAliveConnection {
TlsConnection(socket_t s, SSLServer &server) TlsConnection(socket_t s, SSLServer &server)
: KeepAliveConnection(s, server), ssl_svr(server) {} : KeepAliveConnection(s, server), ssl_svr(server) {}
@@ -20301,47 +20308,6 @@ inline tls::session_t SSLServer::start_session(socket_t sock) {
return session; 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, inline bool SSLServer::update_certs_pem(const char *cert_pem,
const char *key_pem, const char *key_pem,
const char *client_ca_pem, const char *client_ca_pem,
@@ -24860,7 +24826,25 @@ inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
return true; return true;
} }
// Sends this side's one Close frame and marks the connection closed. Returns
// false when it already was.
inline bool WebSocket::send_close(const std::string &payload) {
if (closed_.exchange(true)) { return false; }
ping_cv_.notify_all();
std::lock_guard<std::mutex> lock(write_mutex_);
detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
payload.size(), true, !is_server_);
return true;
}
inline ReadResult WebSocket::read(std::string &msg) { inline ReadResult WebSocket::read(std::string &msg) {
// RFC 6455 Section 7.1.7: a connection failed on the peer's error is told
// why with a Close frame, and nothing more is read from it.
auto fail_with = [&](CloseStatus status) {
send_close(impl::close_payload(status));
return Fail;
};
// Answers a control frame; any other opcode here is a protocol error. // Answers a control frame; any other opcode here is a protocol error.
// Returns false when the connection is done. // Returns false when the connection is done.
auto handle_control = [&](Opcode op, const std::string &payload) -> bool { auto handle_control = [&](Opcode op, const std::string &payload) -> bool {
@@ -24872,21 +24856,14 @@ inline ReadResult WebSocket::read(std::string &msg) {
unacked_pings_ = 0; unacked_pings_ = 0;
return true; return true;
} }
case Opcode::Close: { case Opcode::Close:
// RFC 6455 §5.5.1: a Close is echoed back, unless its payload is // RFC 6455 §5.5.1: a Close is echoed back, unless its payload is
// malformed, which is answered with a protocol error instead. // malformed, which is answered with a protocol error instead.
if (closed_.exchange(true)) { return false; } send_close(impl::is_valid_close_payload(payload)
auto reply = payload; ? payload
if (!impl::is_valid_close_payload(payload)) { : impl::close_payload(CloseStatus::ProtocolError));
auto code = static_cast<uint16_t>(CloseStatus::ProtocolError);
reply = {static_cast<char>(code >> 8), static_cast<char>(code & 0xff)};
}
std::lock_guard<std::mutex> lock(write_mutex_);
detail::write_websocket_frame(strm_, Opcode::Close, reply.data(),
reply.size(), true, !is_server_);
return false; return false;
} default: fail_with(CloseStatus::ProtocolError); return false;
default: closed_ = true; return false;
} }
}; };
@@ -24923,6 +24900,12 @@ inline ReadResult WebSocket::read(std::string &msg) {
if (r == impl::FrameRead::Timeout && read_timeout_set_ && !closed_) { if (r == impl::FrameRead::Timeout && read_timeout_set_ && !closed_) {
return Timeout; return Timeout;
} }
if (r == impl::FrameRead::ProtocolError) {
return fail_with(CloseStatus::ProtocolError);
}
if (r == impl::FrameRead::TooBig) {
return fail_with(CloseStatus::MessageTooBig);
}
if (r != impl::FrameRead::Ok) { if (r != impl::FrameRead::Ok) {
closed_ = true; closed_ = true;
return Fail; return Fail;
@@ -24936,8 +24919,7 @@ inline ReadResult WebSocket::read(std::string &msg) {
// RFC 6455 5.4: a message is a Text or Binary frame and the continuation // RFC 6455 5.4: a message is a Text or Binary frame and the continuation
// frames after it, with only control frames between them. // frames after it, with only control frames between them.
if (continues == (message_kind_ == Fail)) { if (continues == (message_kind_ == Fail)) {
closed_ = true; return fail_with(CloseStatus::ProtocolError);
return Fail;
} }
if (continues) { if (continues) {
message_ += payload; message_ += payload;
@@ -24947,8 +24929,7 @@ inline ReadResult WebSocket::read(std::string &msg) {
} }
if (CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH > 0 && if (CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH > 0 &&
message_.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) { message_.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
closed_ = true; return fail_with(CloseStatus::MessageTooBig);
return Fail;
} }
if (!fin) { continue; } if (!fin) { continue; }
@@ -24978,27 +24959,7 @@ inline bool WebSocket::send(const char *data, size_t len) {
} }
inline void WebSocket::close(CloseStatus status, const std::string &reason) { inline void WebSocket::close(CloseStatus status, const std::string &reason) {
if (closed_.exchange(true)) { return; } if (!send_close(impl::close_payload(status, reason))) { return; }
ping_cv_.notify_all();
std::string payload;
auto code = static_cast<uint16_t>(status);
payload.push_back(static_cast<char>((code >> 8) & 0xFF));
payload.push_back(static_cast<char>(code & 0xFF));
// RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
// Close frame has 2-byte status code, so reason is limited to 123 bytes,
// cut back to a whole UTF-8 character
auto short_reason = reason.substr(0, 123);
while (!short_reason.empty() && !impl::is_valid_utf8(short_reason)) {
short_reason.pop_back();
}
payload += short_reason;
// A code that may not be sent, such as NoStatus, goes without a payload
if (!impl::is_valid_close_payload(payload)) { payload.clear(); }
{
std::lock_guard<std::mutex> lock(write_mutex_);
detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
payload.size(), true, !is_server_);
}
// RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
// Close response before closing the TCP connection. // Close response before closing the TCP connection.
+5 -1
View File
@@ -26,7 +26,11 @@ endif()
find_package(CURL REQUIRED) 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_compile_options(httplib-test PRIVATE "$<$<CXX_COMPILER_ID:MSVC>:/utf-8;/bigobj>")
target_link_libraries(httplib-test PRIVATE httplib GTest::gtest_main CURL::libcurl) target_link_libraries(httplib-test PRIVATE httplib GTest::gtest_main CURL::libcurl)
gtest_discover_tests(httplib-test) gtest_discover_tests(httplib-test)
+16 -3
View File
@@ -1,5 +1,18 @@
// The sole purpose of this file is to include httplib.h in a separate // Includes httplib.h in a separate compilation unit, thus verifying that
// compilation unit, thus verifying that inline keywords have not been forgotten // inline keywords have not been forgotten when linked together with test.cc.
// when linked together with test.cc.
#include <httplib.h> #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
+295 -111
View File
@@ -157,28 +157,38 @@ static void read_file(const std::string &path, std::string &out) {
fs.read(&out[0], static_cast<std::streamsize>(size)); fs.read(&out[0], static_cast<std::streamsize>(size));
} }
// httpbingo.org intermittently answers with gateway errors unrelated to the // Failures of the services that the *_Online tests reach, unrelated to the
// client under test. // client under test: httpbingo.org intermittently answers with gateway errors,
static bool is_gateway_error(const Result &res) { // and badssl.com drops connections from CI runners before it sends its
return res && (res->status == StatusCode::BadGateway_502 || // certificate. A handshake that fails before any verdict on the certificate is
// left to the tests against local servers.
static bool is_service_failure(const Result &res) {
if (res) {
return res->status == StatusCode::BadGateway_502 ||
res->status == StatusCode::ServiceUnavailable_503 || res->status == StatusCode::ServiceUnavailable_503 ||
res->status == StatusCode::GatewayTimeout_504); res->status == StatusCode::GatewayTimeout_504;
}
return res.error() == Error::SSLConnection;
} }
template <typename F> static Result retry_gateway_errors(F &&send) { template <typename F> static Result retry_service_failures(F &&send) {
auto res = send(); auto res = send();
for (auto wait : {1, 2}) { for (auto wait : {1, 2}) {
if (!is_gateway_error(res)) { break; } if (!is_service_failure(res)) { break; }
std::this_thread::sleep_for(std::chrono::seconds(wait)); std::this_thread::sleep_for(std::chrono::seconds(wait));
res = send(); res = send();
} }
return res; return res;
} }
#define SKIP_ON_GATEWAY_ERROR(res) \ #define SKIP_ON_SERVICE_FAILURE(res) \
do { \ do { \
if (is_gateway_error(res)) { \ if (is_service_failure(res)) { \
GTEST_SKIP() << "gateway error " << (res)->status; \ if (res) { \
GTEST_SKIP() << "service failure: status " << (res)->status; \
} else { \
GTEST_SKIP() << "service failure: " << to_string((res).error()); \
} \
} \ } \
} while (0) } while (0)
@@ -2083,6 +2093,9 @@ TEST(ParseDispositionParamsTest, QuotedValues) {
} cases[] = { } cases[] = {
{"name=\"file1\"; filename=\"a.txt\"", {"name=\"file1\"; filename=\"a.txt\"",
{{"name", "file1"}, {"filename", "a.txt"}}}, {{"name", "file1"}, {"filename", "a.txt"}}},
// MIME parameter names are case-insensitive, but their values are not.
{"NaMe=\"Upload\"; FiLeNaMe=\"Report.TXT\"",
{{"name", "Upload"}, {"filename", "Report.TXT"}}},
// Whitespace around '=' and ';' is still trimmed // Whitespace around '=' and ';' is still trimmed
{"name=\"file2\" ;filename = \"a.html\"", {"name=\"file2\" ;filename = \"a.html\"",
{{"name", "file2"}, {"filename", "a.html"}}}, {{"name", "file2"}, {"filename", "a.html"}}},
@@ -2853,8 +2866,8 @@ TEST(RangeTest, FromHTTPBin_Online) {
cli.set_connection_timeout(5); cli.set_connection_timeout(5);
{ {
auto res = retry_gateway_errors([&] { return cli.Get(path); }); auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body); EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
@@ -2862,8 +2875,8 @@ TEST(RangeTest, FromHTTPBin_Online) {
{ {
Headers headers = {make_range_header({{1, -1}})}; Headers headers = {make_range_header({{1, -1}})};
auto res = retry_gateway_errors([&] { return cli.Get(path, headers); }); auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body); EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_EQ(StatusCode::PartialContent_206, res->status); EXPECT_EQ(StatusCode::PartialContent_206, res->status);
@@ -2871,8 +2884,8 @@ TEST(RangeTest, FromHTTPBin_Online) {
{ {
Headers headers = {make_range_header({{1, 10}})}; Headers headers = {make_range_header({{1, 10}})};
auto res = retry_gateway_errors([&] { return cli.Get(path, headers); }); auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("bcdefghijk", res->body); EXPECT_EQ("bcdefghijk", res->body);
EXPECT_EQ(StatusCode::PartialContent_206, res->status); EXPECT_EQ(StatusCode::PartialContent_206, res->status);
@@ -2883,8 +2896,8 @@ TEST(RangeTest, FromHTTPBin_Online) {
// acceptable per RFC 9110 §15.3.7, so we accept either status code. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
{ {
Headers headers = {make_range_header({{0, 31}})}; Headers headers = {make_range_header({{0, 31}})};
auto res = retry_gateway_errors([&] { return cli.Get(path, headers); }); auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body); EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_TRUE(res->status == StatusCode::OK_200 || EXPECT_TRUE(res->status == StatusCode::OK_200 ||
@@ -2893,8 +2906,8 @@ TEST(RangeTest, FromHTTPBin_Online) {
{ {
Headers headers = {make_range_header({{0, -1}})}; Headers headers = {make_range_header({{0, -1}})};
auto res = retry_gateway_errors([&] { return cli.Get(path, headers); }); auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body); EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_TRUE(res->status == StatusCode::OK_200 || EXPECT_TRUE(res->status == StatusCode::OK_200 ||
@@ -2906,8 +2919,8 @@ TEST(RangeTest, FromHTTPBin_Online) {
// in real servers, so we only verify the request succeeds. // in real servers, so we only verify the request succeeds.
{ {
Headers headers = {make_range_header({{0, 32}})}; Headers headers = {make_range_header({{0, 32}})};
auto res = retry_gateway_errors([&] { return cli.Get(path, headers); }); auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
} }
} }
@@ -3222,9 +3235,9 @@ TEST(CancelTest, NoCancel_Online) {
#endif #endif
cli.set_connection_timeout(std::chrono::seconds(5)); cli.set_connection_timeout(std::chrono::seconds(5));
auto res = retry_gateway_errors( auto res = retry_service_failures(
[&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); }); [&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body); EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
@@ -3245,9 +3258,9 @@ TEST(CancelTest, WithCancelSmallPayload_Online) {
Client cli(host, port); Client cli(host, port);
#endif #endif
auto res = retry_gateway_errors( auto res = retry_service_failures(
[&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); }); [&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
cli.set_connection_timeout(std::chrono::seconds(5)); cli.set_connection_timeout(std::chrono::seconds(5));
ASSERT_TRUE(!res); ASSERT_TRUE(!res);
EXPECT_EQ(Error::Canceled, res.error()); EXPECT_EQ(Error::Canceled, res.error());
@@ -3266,12 +3279,12 @@ TEST(CancelTest, WithCancelLargePayload_Online) {
#endif #endif
cli.set_connection_timeout(std::chrono::seconds(5)); cli.set_connection_timeout(std::chrono::seconds(5));
auto res = retry_gateway_errors([&] { auto res = retry_service_failures([&] {
auto count = 0; auto count = 0;
return cli.Get(path, return cli.Get(path,
[&count](uint64_t, uint64_t) { return (count++ == 0); }); [&count](uint64_t, uint64_t) { return (count++ == 0); });
}); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(!res); ASSERT_TRUE(!res);
EXPECT_EQ(Error::Canceled, res.error()); EXPECT_EQ(Error::Canceled, res.error());
} }
@@ -3861,18 +3874,18 @@ TEST(BaseAuthTest, FromHTTPWatch_Online) {
#endif #endif
{ {
auto res = retry_gateway_errors([&] { return cli.Get(path); }); auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status); EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
} }
{ {
auto res = retry_gateway_errors([&] { auto res = retry_service_failures([&] {
return cli.Get( return cli.Get(
path, Headers{make_basic_authentication_header("hello", "world")}); path, Headers{make_basic_authentication_header("hello", "world")});
}); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
auto body = remove_whitespace(res->body); auto body = remove_whitespace(res->body);
EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos); EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
@@ -3882,8 +3895,8 @@ TEST(BaseAuthTest, FromHTTPWatch_Online) {
{ {
cli.set_basic_auth("hello", "world"); cli.set_basic_auth("hello", "world");
auto res = retry_gateway_errors([&] { return cli.Get(path); }); auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
auto body = remove_whitespace(res->body); auto body = remove_whitespace(res->body);
EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos); EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
@@ -3893,16 +3906,16 @@ TEST(BaseAuthTest, FromHTTPWatch_Online) {
{ {
cli.set_basic_auth("hello", "bad"); cli.set_basic_auth("hello", "bad");
auto res = retry_gateway_errors([&] { return cli.Get(path); }); auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status); EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
} }
{ {
cli.set_basic_auth("bad", "world"); cli.set_basic_auth("bad", "world");
auto res = retry_gateway_errors([&] { return cli.Get(path); }); auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status); EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
} }
@@ -3921,8 +3934,8 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
SSLClient cli(host, port); SSLClient cli(host, port);
{ {
auto res = retry_gateway_errors([&] { return cli.Get(unauth_path); }); auto res = retry_service_failures([&] { return cli.Get(unauth_path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status); EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
} }
@@ -3931,8 +3944,8 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
cli.set_digest_auth("hello", "world"); cli.set_digest_auth("hello", "world");
for (const auto &path : paths) { for (const auto &path : paths) {
auto res = retry_gateway_errors([&] { return cli.Get(path.c_str()); }); auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
auto body = remove_whitespace(res->body); auto body = remove_whitespace(res->body);
EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos); EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
@@ -3942,8 +3955,8 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
cli.set_digest_auth("hello", "bad"); cli.set_digest_auth("hello", "bad");
for (const auto &path : paths) { for (const auto &path : paths) {
auto res = retry_gateway_errors([&] { return cli.Get(path.c_str()); }); auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status); EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
} }
@@ -4155,8 +4168,8 @@ TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
cli.set_direct_hostname_addr_map({{another_host, wrong_ip}}); cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
auto res = cli.Get("/"); auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
} }
TEST(SpecifyServerIPAddressTest, RealHostname_Online) { TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
@@ -4341,8 +4354,8 @@ TEST(AbsoluteRedirectTest, Redirect_Online) {
#endif #endif
cli.set_follow_location(true); cli.set_follow_location(true);
auto res = retry_gateway_errors([&] { return cli.Get(path); }); auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
} }
@@ -4358,8 +4371,8 @@ TEST(RedirectTest, Redirect_Online) {
#endif #endif
cli.set_follow_location(true); cli.set_follow_location(true);
auto res = retry_gateway_errors([&] { return cli.Get(path); }); auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
} }
@@ -4375,8 +4388,8 @@ TEST(RelativeRedirectTest, Redirect_Online) {
#endif #endif
cli.set_follow_location(true); cli.set_follow_location(true);
auto res = retry_gateway_errors([&] { return cli.Get(path); }); auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
} }
@@ -4392,8 +4405,8 @@ TEST(TooManyRedirectTest, Redirect_Online) {
#endif #endif
cli.set_follow_location(true); cli.set_follow_location(true);
auto res = retry_gateway_errors([&] { return cli.Get(path); }); auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(!res); ASSERT_TRUE(!res);
EXPECT_EQ(Error::ExceedRedirectCount, res.error()); EXPECT_EQ(Error::ExceedRedirectCount, res.error());
} }
@@ -4420,10 +4433,10 @@ TEST(YahooRedirectTest, Redirect_Online) {
TEST(HttpsToHttpRedirectTest, Redirect_Online) { TEST(HttpsToHttpRedirectTest, Redirect_Online) {
SSLClient cli(REDIR_HOST); SSLClient cli(REDIR_HOST);
cli.set_follow_location(true); cli.set_follow_location(true);
auto res = retry_gateway_errors([&] { auto res = retry_service_failures([&] {
return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302"); return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
}); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
} }
@@ -4436,9 +4449,9 @@ TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
params.emplace("url", "http://example.com"); params.emplace("url", "http://example.com");
params.emplace("status_code", "302"); params.emplace("status_code", "302");
auto res = retry_gateway_errors( auto res = retry_service_failures(
[&] { return cli.Get(REDIR_PATH, params, Headers{}); }); [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
} }
@@ -4450,10 +4463,10 @@ TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
Params params; Params params;
params.emplace("url", "http://example.com"); params.emplace("url", "http://example.com");
auto res = retry_gateway_errors([&] { auto res = retry_service_failures([&] {
return cli.Get(REDIR_PATH "?status_code=302", params, Headers{}); return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
}); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
} }
@@ -6442,8 +6455,8 @@ TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
#ifdef CPPHTTPLIB_SSL_ENABLED #ifdef CPPHTTPLIB_SSL_ENABLED
TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) { TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
// SSLServer::process_and_close_socket() is a separate overload with its own // SSLServer serves through its own connection type, so it is exercised on
// guard, so it is exercised on its own. // its own.
SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE); SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
ASSERT_TRUE(svr.is_valid()); ASSERT_TRUE(svr.is_valid());
svr.new_task_queue = [] { return new ThreadPool(1); }; svr.new_task_queue = [] { return new ThreadPool(1); };
@@ -15125,16 +15138,16 @@ TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
cli.set_connection_timeout(5); cli.set_connection_timeout(5);
{ {
auto res = retry_gateway_errors([&] { return cli.Get(path); }); auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("bcdefghijk", res->body); EXPECT_EQ("bcdefghijk", res->body);
EXPECT_EQ(StatusCode::PartialContent_206, res->status); EXPECT_EQ(StatusCode::PartialContent_206, res->status);
} }
{ {
auto res = retry_gateway_errors([&] { return cli.Get(path); }); auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("bcdefghijk", res->body); EXPECT_EQ("bcdefghijk", res->body);
EXPECT_EQ(StatusCode::PartialContent_206, res->status); EXPECT_EQ(StatusCode::PartialContent_206, res->status);
@@ -16818,10 +16831,8 @@ TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
// Verify client is still valid and can make connections // Verify client is still valid and can make connections
httplib_client.enable_server_certificate_verification(true); httplib_client.enable_server_certificate_verification(true);
auto res = httplib_client.Get("/"); auto res = httplib_client.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
// Google may return 200 or 301 depending on various factors
EXPECT_TRUE(res->status == StatusCode::OK_200 ||
res->status == StatusCode::MovedPermanently_301);
} }
TEST(SSLClientTest, ServerNameIndication_Online) { TEST(SSLClientTest, ServerNameIndication_Online) {
@@ -16829,8 +16840,8 @@ TEST(SSLClientTest, ServerNameIndication_Online) {
auto path = std::string{"/get"}; auto path = std::string{"/get"};
SSLClient cli(host, 443); SSLClient cli(host, 443);
auto res = retry_gateway_errors([&] { return cli.Get(path); }); auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status); ASSERT_EQ(StatusCode::OK_200, res->status);
} }
@@ -16839,7 +16850,8 @@ TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
// Use a site that will cause SSL verification failure due to self-signed cert // Use a site that will cause SSL verification failure due to self-signed cert
SSLClient cli("self-signed.badssl.com", 443); SSLClient cli("self-signed.badssl.com", 443);
cli.enable_server_certificate_verification(true); cli.enable_server_certificate_verification(true);
auto res = cli.Get("/"); auto res = retry_service_failures([&] { return cli.Get("/"); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(!res); ASSERT_TRUE(!res);
EXPECT_EQ(Error::SSLServerVerification, res.error()); EXPECT_EQ(Error::SSLServerVerification, res.error());
@@ -16869,7 +16881,8 @@ TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
cli.enable_server_certificate_verification(true); cli.enable_server_certificate_verification(true);
cli.enable_server_hostname_verification(true); cli.enable_server_hostname_verification(true);
auto res = cli.Get("/"); auto res = retry_service_failures([&] { return cli.Get("/"); });
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(!res); ASSERT_TRUE(!res);
EXPECT_EQ(Error::SSLServerHostnameVerification, res.error()); EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
@@ -16977,16 +16990,16 @@ TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
TEST(SSLClientTest, ServerCertificateVerification1_Online) { TEST(SSLClientTest, ServerCertificateVerification1_Online) {
Client cli("https://google.com"); Client cli("https://google.com");
auto res = cli.Get("/"); auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
} }
TEST(SSLClientTest, ServerCertificateVerification2_Online) { TEST(SSLClientTest, ServerCertificateVerification2_Online) {
SSLClient cli("google.com"); SSLClient cli("google.com");
cli.set_ca_cert_path(CA_CERT_FILE); cli.set_ca_cert_path(CA_CERT_FILE);
auto res = cli.Get("/"); auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
} }
TEST(SSLClientTest, ServerCertificateVerification3_Online) { TEST(SSLClientTest, ServerCertificateVerification3_Online) {
@@ -17051,8 +17064,8 @@ TEST(SSLClientTest, ServerCertificateVerification5_Online) {
SSLClient cli("google.com"); SSLClient cli("google.com");
cli.load_ca_cert_store(cert.data(), cert.size()); cli.load_ca_cert_store(cert.data(), cert.size());
const auto res = cli.Get("/"); const auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
} }
TEST(SSLClientTest, ServerCertificateVerification6_Online) { TEST(SSLClientTest, ServerCertificateVerification6_Online) {
@@ -17083,8 +17096,8 @@ TEST(SSLClientTest, ServerCertificateVerification6_Online) {
SSLClient cli("google.com"); SSLClient cli("google.com");
cli.load_ca_cert_store(cert, sizeof(cert)); cli.load_ca_cert_store(cert, sizeof(cert));
const auto res = cli.Get("/"); const auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
} }
TEST(SSLClientTest, WildcardHostNameMatch_Online) { TEST(SSLClientTest, WildcardHostNameMatch_Online) {
@@ -17095,8 +17108,8 @@ TEST(SSLClientTest, WildcardHostNameMatch_Online) {
cli.set_follow_location(true); cli.set_follow_location(true);
auto res = cli.Get("/"); auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
} }
TEST(SSLClientTest, WildcardHostNameMatchCase_Online) { TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
@@ -17108,8 +17121,8 @@ TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
cli.set_follow_location(true); cli.set_follow_location(true);
auto res = cli.Get("/"); auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
} }
TEST(SSLClientTest, HostNameMatchCase_Online) { TEST(SSLClientTest, HostNameMatchCase_Online) {
@@ -17120,8 +17133,8 @@ TEST(SSLClientTest, HostNameMatchCase_Online) {
cli.set_follow_location(true); cli.set_follow_location(true);
auto res = cli.Get("/"); auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
} }
TEST(SSLClientTest, Issue2004_Online) { TEST(SSLClientTest, Issue2004_Online) {
@@ -17129,11 +17142,8 @@ TEST(SSLClientTest, Issue2004_Online) {
client.set_follow_location(true); client.set_follow_location(true);
auto res = client.Get("/"); auto res = client.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
auto body = res->body;
EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
} }
TEST(SSLClientTest, ErrorReportingWhenInvalid) { TEST(SSLClientTest, ErrorReportingWhenInvalid) {
@@ -18877,10 +18887,10 @@ TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) { TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
Client cli(REDIR_HOST); Client cli(REDIR_HOST);
cli.set_follow_location(true); cli.set_follow_location(true);
auto res = retry_gateway_errors([&] { auto res = retry_service_failures([&] {
return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302"); return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
}); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
@@ -18894,9 +18904,9 @@ TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
params.emplace("url", "http://example.com"); params.emplace("url", "http://example.com");
params.emplace("status_code", "302"); params.emplace("status_code", "302");
auto res = retry_gateway_errors( auto res = retry_service_failures(
[&] { return cli.Get(REDIR_PATH, params, Headers{}); }); [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
} }
@@ -18908,10 +18918,10 @@ TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
Params params; Params params;
params.emplace("url", "http://example.com"); params.emplace("url", "http://example.com");
auto res = retry_gateway_errors([&] { auto res = retry_service_failures([&] {
return cli.Get(REDIR_PATH "?status_code=302", params, Headers{}); return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
}); });
SKIP_ON_GATEWAY_ERROR(res); SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status); EXPECT_EQ(StatusCode::OK_200, res->status);
} }
@@ -19287,8 +19297,8 @@ TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
cli.enable_server_certificate_verification(true); cli.enable_server_certificate_verification(true);
auto res = cli.Get("/"); auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
} }
// The custom CA remains effective when combined with the system CA // The custom CA remains effective when combined with the system CA
@@ -19591,8 +19601,8 @@ TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
cli.enable_server_certificate_verification(true); cli.enable_server_certificate_verification(true);
auto res = cli.Get("/"); auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error()); ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
} }
// The system CA policy must carry over to the client created internally for // The system CA policy must carry over to the client created internally for
@@ -28695,7 +28705,7 @@ TEST(WebSocketTest, RSVBitsMustBeZero) {
bool fin; bool fin;
EXPECT_EQ( EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024), ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail); ws::impl::FrameRead::ProtocolError);
} }
// RSV2 set (0x20) // RSV2 set (0x20)
@@ -28707,7 +28717,7 @@ TEST(WebSocketTest, RSVBitsMustBeZero) {
bool fin; bool fin;
EXPECT_EQ( EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024), ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail); ws::impl::FrameRead::ProtocolError);
} }
// RSV3 set (0x10) // RSV3 set (0x10)
@@ -28719,7 +28729,7 @@ TEST(WebSocketTest, RSVBitsMustBeZero) {
bool fin; bool fin;
EXPECT_EQ( EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024), ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail); ws::impl::FrameRead::ProtocolError);
} }
// No RSV bits set - should succeed // No RSV bits set - should succeed
@@ -28754,7 +28764,7 @@ TEST(WebSocketTest, ControlFrameValidation) {
bool fin; bool fin;
EXPECT_EQ( EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024), ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail); ws::impl::FrameRead::ProtocolError);
} }
// Close with FIN=0 - must be rejected // Close with FIN=0 - must be rejected
@@ -28769,7 +28779,7 @@ TEST(WebSocketTest, ControlFrameValidation) {
bool fin; bool fin;
EXPECT_EQ( EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024), ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail); ws::impl::FrameRead::ProtocolError);
} }
// Ping with payload_len=126 (extended length) - must be rejected // Ping with payload_len=126 (extended length) - must be rejected
@@ -28787,7 +28797,7 @@ TEST(WebSocketTest, ControlFrameValidation) {
bool fin; bool fin;
EXPECT_EQ( EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024), ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail); ws::impl::FrameRead::ProtocolError);
} }
// Ping with FIN=1 and payload_len=125 - should succeed // Ping with FIN=1 and payload_len=125 - should succeed
@@ -28828,7 +28838,7 @@ TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
bool fin; bool fin;
EXPECT_EQ( EXPECT_EQ(
ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024), ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
ws::impl::FrameRead::Fail); ws::impl::FrameRead::ProtocolError);
} }
// MSB clear - should pass length parsing (will be rejected by max_len, // MSB clear - should pass length parsing (will be rejected by max_len,
@@ -30963,6 +30973,24 @@ static std::string masked_frame(uint8_t first_byte,
return f + payload; return f + payload;
} }
// Sends frames on a new raw connection to /ws and returns the first n bytes the
// server sends back, or what came before it closed.
static std::string raw_websocket_reply(int port, const std::string &frames,
size_t n) {
auto sock = connect_raw_websocket(port, "/ws");
if (sock == INVALID_SOCKET) { return std::string(); }
detail::send_socket(sock, frames.data(), frames.size(), 0);
std::string reply;
char buf[256];
while (reply.size() < n) {
auto got = ::recv(sock, buf, sizeof(buf), 0);
if (got <= 0) { break; }
reply.append(buf, static_cast<size_t>(got));
}
detail::close_socket(sock);
return reply;
}
TEST(WebSocketTest, AssemblesFragmentsAroundAPing) { TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
std::atomic<bool> done{false}; std::atomic<bool> done{false};
std::string received; std::string received;
@@ -31360,24 +31388,119 @@ TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
// Also between the fragments of a message. // Also between the fragments of a message.
for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) { for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
for (const auto &c : cases) { for (const auto &c : cases) {
auto sock = connect_raw_websocket(port, "/ws"); EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
ASSERT_NE(INVALID_SOCKET, sock); c.second,
auto frames = prefix + masked_frame(0x88, c.first); raw_websocket_reply(port, prefix + masked_frame(0x88, c.first),
detail::send_socket(sock, frames.data(), frames.size(), 0); 2 + c.second.size()));
}
}
}
TEST(WebSocketTest, FailsABadFrameWithACloseStatus) {
Server svr;
svr.set_websocket_ping_interval(0);
svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
std::string msg;
while (ws.read(msg)) {}
});
auto port = svr.bind_to_any_port("127.0.0.1");
std::thread t([&]() { svr.listen_after_bind(); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
});
svr.wait_until_ready();
// A header that announces one byte over the limit, and none of its payload
std::string too_big = "\x82\xff";
uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1;
for (int shift = 56; shift >= 0; shift -= 8) {
too_big += static_cast<char>((len >> shift) & 0xff);
}
too_big.append(4, '\0');
const std::string protocol_error("\x03\xea"); // 1002
const std::string too_big_error("\x03\xf1"); // 1009
// What the client sends and the status the server closes with
std::vector<std::pair<std::string, std::string>> cases = {
{masked_frame(0xc1, "a"), protocol_error}, // RSV1
{std::string("\x81\x01") + "a", protocol_error}, // not masked
{masked_frame(0x09, ""), protocol_error}, // fragmented Ping
{masked_frame(0x83, ""), protocol_error}, // reserved opcode
{masked_frame(0x8b, ""), protocol_error}, // reserved control opcode
{masked_frame(0x80, "a"), protocol_error}, // continuation, no start
{masked_frame(0x01, "a") + masked_frame(0x81, "b"),
protocol_error}, // a new message inside a fragmented one
{std::string("\x81\xff\x80", 3) + std::string(11, '\0'),
protocol_error}, // 64-bit length with its top bit set
{too_big, too_big_error},
};
for (const auto &c : cases) {
EXPECT_EQ(std::string("\x88\x02") + c.second,
raw_websocket_reply(port, c.first, 4));
}
}
TEST(WebSocketTest, ClientFailsAMaskedFrameWithProtocolError) {
SilentListener listener;
ASSERT_NE(INVALID_SOCKET, listener.sock);
// A peer that completes the handshake, then sends a masked frame, which a
// server must never do, and keeps what the client sends back.
std::string reply; std::string reply;
std::thread peer([&]() {
auto sock = listener.accept();
if (sock == INVALID_SOCKET) { return; }
std::string req;
char c;
while (req.find("\r\n\r\n") == std::string::npos &&
::recv(sock, &c, 1, 0) == 1) {
req += c;
}
const std::string field = "Sec-WebSocket-Key: ";
auto pos = req.find(field);
if (pos != std::string::npos) {
pos += field.size();
auto key = req.substr(pos, req.find("\r\n", pos) - pos);
auto res = "HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: " +
detail::websocket_accept_key(key) + "\r\n\r\n" +
masked_frame(0x81, "a");
detail::send_socket(sock, res.data(), res.size(), 0);
// FIN + Close, masked with a length of 2, the mask key, the code
char buf[256]; char buf[256];
while (reply.size() < 2 + c.second.size()) { while (reply.size() < 8) {
auto n = ::recv(sock, buf, sizeof(buf), 0); auto n = ::recv(sock, buf, sizeof(buf), 0);
if (n <= 0) { break; } if (n <= 0) { break; }
reply.append(buf, static_cast<size_t>(n)); reply.append(buf, static_cast<size_t>(n));
} }
}
detail::close_socket(sock); detail::close_socket(sock);
EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) + });
c.second,
reply); ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(listener.port) +
} "/ws");
} auto connected = static_cast<bool>(client.connect());
std::string msg;
auto r = connected ? client.read(msg) : ws::Fail;
peer.join();
ASSERT_TRUE(connected);
EXPECT_EQ(ws::Fail, r);
detail::BufferStream strm;
strm.write(reply.data(), reply.size());
ws::Opcode opcode;
std::string payload;
bool fin;
ASSERT_EQ(
ws::impl::FrameRead::Ok,
ws::impl::read_websocket_frame(strm, opcode, payload, fin, true, 125));
EXPECT_EQ(ws::Opcode::Close, opcode);
EXPECT_EQ(std::string("\x03\xea"), payload);
} }
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
@@ -34425,9 +34548,10 @@ bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
return true; 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.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) { svr.Get("/", [](const Request &, Response &res) {
res.set_content("ok", "text/plain"); res.set_content("ok", "text/plain");
}); });
@@ -34491,6 +34615,63 @@ private:
} // namespace parking_test } // 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) { TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
using namespace parking_test; using namespace parking_test;
Server svr; Server svr;
@@ -34745,9 +34926,11 @@ TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) { TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
using namespace parking_test; using namespace parking_test;
for (auto parking : {true, false}) {
SCOPED_TRACE(parking ? "parking" : "no parking");
SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE); SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
ASSERT_TRUE(svr.is_valid()); ASSERT_TRUE(svr.is_valid());
serve_ok(svr, threads(1)); serve_ok(svr, threads(1), parking);
RunningServer running(svr); RunningServer running(svr);
Sockets socks; Sockets socks;
@@ -34756,6 +34939,7 @@ TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
EXPECT_TRUE(sees_eof(plain, in_ms(1000))); EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
EXPECT_NE(0, svr.ssl_last_error()); EXPECT_NE(0, svr.ssl_last_error());
} }
}
TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) { TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
using namespace parking_test; using namespace parking_test;