Compare commits

..
Author SHA1 Message Date
yhirose 3d85cf56d6 Tidy two spots left from the keep-alive parking review
drain_and_close_socket() checks the size bound before it reads the clock,
which saves a clock read on a drain that stops at 1 MB, and the comment
on PollPoller::fds_ fits on one line. Nothing else changes.
2026-11-21 23:22:06 -05:00
yhirose 0fe58217ea Let the parking loop wait without a cap when nothing is due
parking_loop capped every Poller::wait() at one minute only to keep the
millisecond timeout within an int, so an idle server woke once a minute
for nothing.

detail::poll_timeout_until() turns a deadline into the timeout instead:
-1 when there is none, which Poller::wait() already defines as waiting
until a descriptor is ready or wake() is called, otherwise whole
milliseconds, rounded up and capped at INT_MAX. The rounding is now
exact: adding 999 us turned a deadline 1 ns away into a timeout of 0.

The loop relies on a negative timeout for the first time, so the Poller
contract tests now check it on every backend.
2026-11-21 23:22:06 -05:00
3 changed files with 132 additions and 271 deletions

No files matched your search

+1 -2
View File
@@ -129,8 +129,7 @@ Passed to the handler registered with `Server::WebSocket()`. The handler runs in
// Read next message (blocks until received, returns Fail/Text/Binary/Timeout)
ReadResult read(std::string &msg);
// Send messages. A send that fails (e.g. the write timeout elapsed) closes the
// connection, since part of the frame may already have gone out.
// Send messages
bool send(const std::string &data); // Text
bool send(const char *data, size_t len); // Binary
+47 -48
View File
@@ -4034,8 +4034,7 @@ private:
PollerWaker waker_;
// fds_[0] is the waker's, which is always armed; tokens_[i] belongs to
// fds_[i].
// fds_[0] is the waker's, always armed; tokens_[i] belongs to fds_[i].
std::vector<struct pollfd> fds_;
std::vector<Token> tokens_;
std::unordered_map<socket_t, size_t> index_;
@@ -4088,6 +4087,11 @@ private:
// The best poller for this platform, or nullptr when it cannot be created.
std::unique_ptr<Poller> make_poller();
// The Poller::wait() timeout until `deadline`: -1 for time_point::max(),
// otherwise whole milliseconds, rounded up and capped at INT_MAX.
int poll_timeout_until(std::chrono::steady_clock::time_point deadline,
std::chrono::steady_clock::time_point now);
class BufferStream final : public Stream {
public:
BufferStream() = default;
@@ -5647,8 +5651,7 @@ bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
time_t timeout_usec, TlsError *err,
const std::function<bool()> &interrupted = nullptr);
bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
time_t timeout_usec, TlsError *err,
const std::function<bool()> &interrupted = nullptr);
time_t timeout_usec, TlsError *err);
// I/O (non-blocking capable)
ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
@@ -7380,7 +7383,7 @@ inline void drain_and_close_socket(socket_t sock,
const auto n = read_socket(sock, buf, sizeof(buf), CPPHTTPLIB_RECV_FLAGS);
if (n <= 0) { break; }
total += static_cast<size_t>(n);
} while (usec_left() > 0 && total < size_t(1024u * 1024u)); // bound #2
} while (total < size_t(1024u * 1024u) && usec_left() > 0); // bound #2
shutdown_socket(sock);
close_socket(sock);
@@ -8263,6 +8266,18 @@ inline std::unique_ptr<Poller> make_poller() {
return PollPoller::create();
}
inline int poll_timeout_until(std::chrono::steady_clock::time_point deadline,
std::chrono::steady_clock::time_point now) {
using namespace std::chrono;
if (deadline == (steady_clock::time_point::max)()) { return -1; }
if (deadline <= now) { return 0; }
const auto left = deadline - now;
auto msec = duration_cast<milliseconds>(left);
if (msec < left) { msec += milliseconds(1); }
const auto cap = milliseconds((std::numeric_limits<int>::max)());
return static_cast<int>((std::min)(msec, cap).count());
}
inline bool bind_ip_address(socket_t sock, const std::string &host) {
struct addrinfo hints;
struct addrinfo *result;
@@ -16577,16 +16592,10 @@ inline bool Server::parking_loop(TaskQueue &task_queue) {
poller.arm(listen_sock, listen_token) ? never : now + check_interval;
}
// At most a minute, which keeps the timeout below within an int.
auto until = (std::min)({st.next_deadline(), listen_rearm_at, next_idle,
st.backlog.empty() ? never : now + check_interval,
now + std::chrono::seconds(60)});
// Rounded up, so that the wait does not end just short of the deadline.
auto timeout = std::chrono::duration_cast<std::chrono::milliseconds>(
until - now + std::chrono::microseconds(999));
poller.wait(static_cast<int>((std::max)(timeout.count(),
std::chrono::milliseconds::rep(0))),
ready);
auto until =
(std::min)({st.next_deadline(), listen_rearm_at, next_idle,
st.backlog.empty() ? never : now + check_interval});
poller.wait(detail::poll_timeout_until(until, now), ready);
if (svr_sock_ != listen_sock) { break; }
now = Clock::now();
@@ -20279,9 +20288,8 @@ inline tls::session_t SSLServer::start_session(socket_t sock) {
std::lock_guard<std::mutex> guard(ctx_mutex_);
if (--handshakes_in_progress_ == 0) { ctx_cv_.notify_all(); }
});
accepted =
accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
&tls_err, [this]() { return is_stopping(); });
accepted = accept_nonblocking(session, sock, read_timeout_sec_,
read_timeout_usec_, &tls_err);
}
if (!accepted) {
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
@@ -21696,8 +21704,7 @@ inline bool connect_nonblocking(session_t session, socket_t sock,
inline bool accept_nonblocking(session_t session, socket_t sock,
time_t timeout_sec, time_t timeout_usec,
TlsError *err,
const std::function<bool()> &interrupted) {
TlsError *err) {
if (!session) {
if (err) { err->code = ErrorCode::Fatal; }
return false;
@@ -21722,14 +21729,10 @@ inline bool accept_nonblocking(session_t session, socket_t sock,
auto ssl_err = SSL_get_error(ssl, res);
switch (ssl_err) {
case SSL_ERROR_WANT_READ:
if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
continue;
}
if (detail::select_until(sock, POLLIN, deadline) > 0) { continue; }
break;
case SSL_ERROR_WANT_WRITE:
if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
continue;
}
if (detail::select_until(sock, POLLOUT, deadline) > 0) { continue; }
break;
default: break;
}
@@ -23056,14 +23059,13 @@ inline bool connect_nonblocking(session_t session, socket_t sock,
inline bool accept_nonblocking(session_t session, socket_t sock,
time_t timeout_sec, time_t timeout_usec,
TlsError *err,
const std::function<bool()> &interrupted) {
TlsError *err) {
// A failed handshake leaves its SNI behind, so start without it
impl::mbedpending_sni().clear();
// Same implementation as connect for Mbed TLS
bool result = connect_nonblocking(session, sock, timeout_sec, timeout_usec,
err, interrupted);
bool result =
connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
// After successful handshake, capture SNI from thread-local storage
if (result && session) {
@@ -24238,8 +24240,7 @@ inline bool connect_nonblocking(session_t session, socket_t sock,
inline bool accept_nonblocking(session_t session, socket_t sock,
time_t timeout_sec, time_t timeout_usec,
TlsError *err,
const std::function<bool()> &interrupted) {
TlsError *err) {
if (!session) {
if (err) { err->code = ErrorCode::Fatal; }
return false;
@@ -24257,13 +24258,9 @@ inline bool accept_nonblocking(session_t session, socket_t sock,
while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
if (ssl_error == SSL_ERROR_WANT_READ) {
if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
continue;
}
if (detail::select_until(sock, POLLIN, deadline) > 0) { continue; }
} else if (ssl_error == SSL_ERROR_WANT_WRITE) {
if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
continue;
}
if (detail::select_until(sock, POLLOUT, deadline) > 0) { continue; }
}
// Error or timeout
@@ -24851,13 +24848,7 @@ inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
bool fin) {
std::lock_guard<std::mutex> lock(write_mutex_);
if (closed_) { return false; }
// A failed write may have sent part of the frame, whose header announces the
// whole length, so the peer would read the next frames as the rest of it.
if (!detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_)) {
closed_ = true;
return false;
}
return true;
return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
}
inline ReadResult WebSocket::read(std::string &msg) {
@@ -24865,8 +24856,12 @@ inline ReadResult WebSocket::read(std::string &msg) {
// Returns false when the connection is done.
auto handle_control = [&](Opcode op, const std::string &payload) -> bool {
switch (op) {
case Opcode::Ping:
return send_frame(Opcode::Pong, payload.data(), payload.size());
case Opcode::Ping: {
std::lock_guard<std::mutex> lock(write_mutex_);
detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
payload.size(), true, !is_server_);
return true;
}
case Opcode::Pong: {
std::lock_guard<std::mutex> lock(ping_mutex_);
unacked_pings_ = 0;
@@ -25065,7 +25060,11 @@ inline void WebSocket::start_heartbeat() {
return;
}
lock.unlock();
if (!send_frame(Opcode::Ping, nullptr, 0)) { return; }
if (!send_frame(Opcode::Ping, nullptr, 0)) {
lock.lock();
closed_ = true;
break;
}
lock.lock();
unacked_pings_++;
}
+84 -221
View File
@@ -84,8 +84,7 @@ bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
time_t timeout_usec, TlsError *err,
const std::function<bool()> &interrupted);
bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
time_t timeout_usec, TlsError *err,
const std::function<bool()> &interrupted);
time_t timeout_usec, TlsError *err);
ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
void shutdown(session_t session, bool graceful);
@@ -157,41 +156,6 @@ static void read_file(const std::string &path, std::string &out) {
fs.read(&out[0], static_cast<std::streamsize>(size));
}
// Failures of the services that the *_Online tests reach, unrelated to the
// client under test: httpbingo.org intermittently answers with gateway errors,
// and badssl.com drops connections from CI runners before it sends its
// certificate. A handshake that fails before any verdict on the certificate is
// left to the tests against local servers.
static bool is_service_failure(const Result &res) {
if (res) {
return res->status == StatusCode::BadGateway_502 ||
res->status == StatusCode::ServiceUnavailable_503 ||
res->status == StatusCode::GatewayTimeout_504;
}
return res.error() == Error::SSLConnection;
}
template <typename F> static Result retry_service_failures(F &&send) {
auto res = send();
for (auto wait : {1, 2}) {
if (!is_service_failure(res)) { break; }
std::this_thread::sleep_for(std::chrono::seconds(wait));
res = send();
}
return res;
}
#define SKIP_ON_SERVICE_FAILURE(res) \
do { \
if (is_service_failure(res)) { \
if (res) { \
GTEST_SKIP() << "service failure: status " << (res)->status; \
} else { \
GTEST_SKIP() << "service failure: " << to_string((res).error()); \
} \
} \
} while (0)
class UnixSocketTest : public ::testing::Test {
protected:
void TearDown() override { std::remove(pathname_.c_str()); }
@@ -2863,8 +2827,7 @@ TEST(RangeTest, FromHTTPBin_Online) {
cli.set_connection_timeout(5);
{
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_EQ(StatusCode::OK_200, res->status);
@@ -2872,8 +2835,7 @@ TEST(RangeTest, FromHTTPBin_Online) {
{
Headers headers = {make_range_header({{1, -1}})};
auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path, headers);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_EQ(StatusCode::PartialContent_206, res->status);
@@ -2881,8 +2843,7 @@ TEST(RangeTest, FromHTTPBin_Online) {
{
Headers headers = {make_range_header({{1, 10}})};
auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path, headers);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("bcdefghijk", res->body);
EXPECT_EQ(StatusCode::PartialContent_206, res->status);
@@ -2893,8 +2854,7 @@ TEST(RangeTest, FromHTTPBin_Online) {
// acceptable per RFC 9110 §15.3.7, so we accept either status code.
{
Headers headers = {make_range_header({{0, 31}})};
auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path, headers);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_TRUE(res->status == StatusCode::OK_200 ||
@@ -2903,8 +2863,7 @@ TEST(RangeTest, FromHTTPBin_Online) {
{
Headers headers = {make_range_header({{0, -1}})};
auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path, headers);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_TRUE(res->status == StatusCode::OK_200 ||
@@ -2916,8 +2875,7 @@ TEST(RangeTest, FromHTTPBin_Online) {
// in real servers, so we only verify the request succeeds.
{
Headers headers = {make_range_header({{0, 32}})};
auto res = retry_service_failures([&] { return cli.Get(path, headers); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path, headers);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
}
}
@@ -3232,9 +3190,7 @@ TEST(CancelTest, NoCancel_Online) {
#endif
cli.set_connection_timeout(std::chrono::seconds(5));
auto res = retry_service_failures(
[&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
EXPECT_EQ(StatusCode::OK_200, res->status);
@@ -3255,9 +3211,7 @@ TEST(CancelTest, WithCancelSmallPayload_Online) {
Client cli(host, port);
#endif
auto res = retry_service_failures(
[&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
cli.set_connection_timeout(std::chrono::seconds(5));
ASSERT_TRUE(!res);
EXPECT_EQ(Error::Canceled, res.error());
@@ -3276,12 +3230,9 @@ TEST(CancelTest, WithCancelLargePayload_Online) {
#endif
cli.set_connection_timeout(std::chrono::seconds(5));
auto res = retry_service_failures([&] {
auto count = 0;
return cli.Get(path,
[&count](uint64_t, uint64_t) { return (count++ == 0); });
});
SKIP_ON_SERVICE_FAILURE(res);
uint32_t count = 0;
auto res =
cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
ASSERT_TRUE(!res);
EXPECT_EQ(Error::Canceled, res.error());
}
@@ -3871,18 +3822,14 @@ TEST(BaseAuthTest, FromHTTPWatch_Online) {
#endif
{
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
}
{
auto res = retry_service_failures([&] {
return cli.Get(
auto res = cli.Get(
path, Headers{make_basic_authentication_header("hello", "world")});
});
SKIP_ON_SERVICE_FAILURE(res);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
auto body = remove_whitespace(res->body);
EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
@@ -3892,8 +3839,7 @@ TEST(BaseAuthTest, FromHTTPWatch_Online) {
{
cli.set_basic_auth("hello", "world");
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
auto body = remove_whitespace(res->body);
EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
@@ -3903,16 +3849,14 @@ TEST(BaseAuthTest, FromHTTPWatch_Online) {
{
cli.set_basic_auth("hello", "bad");
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
}
{
cli.set_basic_auth("bad", "world");
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
}
@@ -3931,8 +3875,7 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
SSLClient cli(host, port);
{
auto res = retry_service_failures([&] { return cli.Get(unauth_path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(unauth_path);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
}
@@ -3941,8 +3884,7 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
cli.set_digest_auth("hello", "world");
for (const auto &path : paths) {
auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path.c_str());
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
auto body = remove_whitespace(res->body);
EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
@@ -3952,8 +3894,7 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
cli.set_digest_auth("hello", "bad");
for (const auto &path : paths) {
auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path.c_str());
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
}
@@ -4165,8 +4106,8 @@ TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
@@ -4351,8 +4292,7 @@ TEST(AbsoluteRedirectTest, Redirect_Online) {
#endif
cli.set_follow_location(true);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -4368,8 +4308,7 @@ TEST(RedirectTest, Redirect_Online) {
#endif
cli.set_follow_location(true);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -4385,8 +4324,7 @@ TEST(RelativeRedirectTest, Redirect_Online) {
#endif
cli.set_follow_location(true);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -4402,8 +4340,7 @@ TEST(TooManyRedirectTest, Redirect_Online) {
#endif
cli.set_follow_location(true);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path);
ASSERT_TRUE(!res);
EXPECT_EQ(Error::ExceedRedirectCount, res.error());
}
@@ -4430,10 +4367,8 @@ TEST(YahooRedirectTest, Redirect_Online) {
TEST(HttpsToHttpRedirectTest, Redirect_Online) {
SSLClient cli(REDIR_HOST);
cli.set_follow_location(true);
auto res = retry_service_failures([&] {
return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
});
SKIP_ON_SERVICE_FAILURE(res);
auto res =
cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -4446,9 +4381,7 @@ TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
params.emplace("url", "http://example.com");
params.emplace("status_code", "302");
auto res = retry_service_failures(
[&] { return cli.Get(REDIR_PATH, params, Headers{}); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(REDIR_PATH, params, Headers{});
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -4460,10 +4393,7 @@ TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
Params params;
params.emplace("url", "http://example.com");
auto res = retry_service_failures([&] {
return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
});
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -5979,40 +5909,6 @@ TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
TEST(SSLClientServerTest, StopDoesNotWaitForHandshakeInProgress) {
SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
ASSERT_TRUE(svr.is_valid());
// Keep-alive parking would wait for the ClientHello without a handshake.
svr.set_keep_alive_parking(false);
svr.set_read_timeout(10, 0);
thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
auto se = detail::scope_exit([&] {
svr.stop();
if (t.joinable()) { t.join(); }
});
svr.wait_until_ready();
// A connection that sends no ClientHello keeps its handshake in progress,
// once the server has had a moment to start it.
auto error = Error::Success;
auto sock = detail::create_client_socket(
HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
/*connection_timeout_sec=*/5, 0,
/*read_timeout_sec=*/5, 0,
/*write_timeout_sec=*/5, 0, std::string(), error);
ASSERT_NE(INVALID_SOCKET, sock);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
auto start = std::chrono::steady_clock::now();
svr.stop();
t.join();
auto elapsed = std::chrono::steady_clock::now() - start;
detail::close_socket(sock);
EXPECT_LT(elapsed, std::chrono::seconds(3));
}
#endif
TEST(ErrorHandlerTest, ContentLength) {
@@ -13847,8 +13743,7 @@ static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
if (use_tls) {
peer.session = tls::create_session(ctx, peer.sock);
tls::TlsError err;
if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err,
nullptr)) {
if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err)) {
close_peer(peer);
return Peer();
}
@@ -15135,16 +15030,14 @@ TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
cli.set_connection_timeout(5);
{
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("bcdefghijk", res->body);
EXPECT_EQ(StatusCode::PartialContent_206, res->status);
}
{
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ("bcdefghijk", res->body);
EXPECT_EQ(StatusCode::PartialContent_206, res->status);
@@ -16828,8 +16721,10 @@ TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
// Verify client is still valid and can make connections
httplib_client.enable_server_certificate_verification(true);
auto res = httplib_client.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
// Google may return 200 or 301 depending on various factors
EXPECT_TRUE(res->status == StatusCode::OK_200 ||
res->status == StatusCode::MovedPermanently_301);
}
TEST(SSLClientTest, ServerNameIndication_Online) {
@@ -16837,8 +16732,7 @@ TEST(SSLClientTest, ServerNameIndication_Online) {
auto path = std::string{"/get"};
SSLClient cli(host, 443);
auto res = retry_service_failures([&] { return cli.Get(path); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(path);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
}
@@ -16847,8 +16741,7 @@ TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
// Use a site that will cause SSL verification failure due to self-signed cert
SSLClient cli("self-signed.badssl.com", 443);
cli.enable_server_certificate_verification(true);
auto res = retry_service_failures([&] { return cli.Get("/"); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get("/");
ASSERT_TRUE(!res);
EXPECT_EQ(Error::SSLServerVerification, res.error());
@@ -16878,8 +16771,7 @@ TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
cli.enable_server_certificate_verification(true);
cli.enable_server_hostname_verification(true);
auto res = retry_service_failures([&] { return cli.Get("/"); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get("/");
ASSERT_TRUE(!res);
EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
@@ -16987,16 +16879,16 @@ TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
TEST(SSLClientTest, ServerCertificateVerification1_Online) {
Client cli("https://google.com");
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
TEST(SSLClientTest, ServerCertificateVerification2_Online) {
SSLClient cli("google.com");
cli.set_ca_cert_path(CA_CERT_FILE);
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
TEST(SSLClientTest, ServerCertificateVerification3_Online) {
@@ -17061,8 +16953,8 @@ TEST(SSLClientTest, ServerCertificateVerification5_Online) {
SSLClient cli("google.com");
cli.load_ca_cert_store(cert.data(), cert.size());
const auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
TEST(SSLClientTest, ServerCertificateVerification6_Online) {
@@ -17093,8 +16985,8 @@ TEST(SSLClientTest, ServerCertificateVerification6_Online) {
SSLClient cli("google.com");
cli.load_ca_cert_store(cert, sizeof(cert));
const auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
TEST(SSLClientTest, WildcardHostNameMatch_Online) {
@@ -17105,8 +16997,8 @@ TEST(SSLClientTest, WildcardHostNameMatch_Online) {
cli.set_follow_location(true);
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
}
TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
@@ -17118,8 +17010,8 @@ TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
cli.set_follow_location(true);
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
}
TEST(SSLClientTest, HostNameMatchCase_Online) {
@@ -17130,8 +17022,8 @@ TEST(SSLClientTest, HostNameMatchCase_Online) {
cli.set_follow_location(true);
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
}
TEST(SSLClientTest, Issue2004_Online) {
@@ -17139,8 +17031,11 @@ TEST(SSLClientTest, Issue2004_Online) {
client.set_follow_location(true);
auto res = client.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::OK_200, res->status);
auto body = res->body;
EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
}
TEST(SSLClientTest, ErrorReportingWhenInvalid) {
@@ -18884,10 +18779,8 @@ TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
Client cli(REDIR_HOST);
cli.set_follow_location(true);
auto res = retry_service_failures([&] {
return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
});
SKIP_ON_SERVICE_FAILURE(res);
auto res =
cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
@@ -18901,9 +18794,7 @@ TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
params.emplace("url", "http://example.com");
params.emplace("status_code", "302");
auto res = retry_service_failures(
[&] { return cli.Get(REDIR_PATH, params, Headers{}); });
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(REDIR_PATH, params, Headers{});
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -18915,10 +18806,7 @@ TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
Params params;
params.emplace("url", "http://example.com");
auto res = retry_service_failures([&] {
return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
});
SKIP_ON_SERVICE_FAILURE(res);
auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
}
@@ -19294,8 +19182,8 @@ TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
cli.enable_server_certificate_verification(true);
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
// The custom CA remains effective when combined with the system CA
@@ -19598,8 +19486,8 @@ TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
cli.enable_server_certificate_verification(true);
auto res = cli.Get("/");
// Any status: Google may redirect or rate-limit CI runners.
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
}
// The system CA policy must carry over to the client created internally for
@@ -25225,7 +25113,7 @@ static void with_single_tls_response(const std::string &response,
nullptr);
auto session = tls::create_session(ctx, cli);
tls::TlsError err;
if (tls::accept_nonblocking(session, cli, 5, 0, &err, nullptr)) {
if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
// The request head first, so that closing the socket sends a FIN
// rather than an RST for the unread bytes.
std::string req;
@@ -29658,59 +29546,6 @@ TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
client.close();
}
// A send() that fails partway leaves a frame on the wire whose header announces
// more than was sent. Nothing may follow it, or the peer reads the next frames
// as the rest of it and a later payload's bytes as a frame of their own.
TEST(WebSocketPartialWriteTest, FailedWriteClosesConnection) {
signal(SIGPIPE, SIG_IGN);
const std::string large(4 * 1024 * 1024, 'A');
std::atomic<bool> large_sent{true};
std::atomic<bool> open_after_failure{true};
std::atomic<bool> handler_done{false};
Server svr;
svr.set_write_timeout(0, 200000);
svr.set_socket_options([](socket_t sock) {
int size = 8192;
setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
reinterpret_cast<const char *>(&size), sizeof(size));
});
svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
large_sent = ws.send(large.data(), large.size());
open_after_failure = ws.is_open();
handler_done = true;
});
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://" + std::string(HOST) + ":" +
std::to_string(port) + "/ws");
client.set_socket_options([](socket_t sock) {
int size = 8192;
setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
reinterpret_cast<const char *>(&size), sizeof(size));
});
ASSERT_TRUE(client.connect());
// Read nothing, so the server's write times out partway through the frame.
for (int i = 0; i < 100 && !handler_done; i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
ASSERT_TRUE(handler_done);
ASSERT_FALSE(large_sent);
EXPECT_FALSE(open_after_failure);
client.close();
}
#endif
TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
@@ -34214,6 +34049,20 @@ TEST_P(PollerTest, WaitHonoursItsTimeout) {
EXPECT_LT(elapsed, std::chrono::seconds(1));
}
TEST_P(PollerTest, NegativeTimeoutWaitsUntilReady) {
TestSocketPair sp;
ASSERT_TRUE(sp.ok());
ASSERT_TRUE(poller_->arm(sp.reader(), 3));
std::thread writer([&] {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
sp.make_readable();
});
auto ready = wait_for(-1);
writer.join();
EXPECT_EQ(Tokens{3}, ready);
}
TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
std::vector<std::unique_ptr<TestSocketPair>> sps;
for (detail::Poller::Token i = 0; i < 8; i++) {
@@ -34332,6 +34181,20 @@ TEST(PollerFactoryTest, MakePollerWorks) {
EXPECT_TRUE(poller->wait(1000, ready));
}
TEST(PollTimeoutTest, LastsUntilTheDeadline) {
using namespace std::chrono;
const auto now = steady_clock::now();
auto timeout = [&](steady_clock::time_point deadline) {
return detail::poll_timeout_until(deadline, now);
};
EXPECT_EQ(-1, timeout((steady_clock::time_point::max)()));
EXPECT_EQ(0, timeout(now - milliseconds(5)));
EXPECT_EQ(1, timeout(now + nanoseconds(1)));
EXPECT_EQ(1, timeout(now + milliseconds(1)));
EXPECT_EQ(2, timeout(now + microseconds(1001)));
EXPECT_EQ((std::numeric_limits<int>::max)(), timeout(now + hours(1000)));
}
// ---------------------------------------------------------------------------
// Keep-alive parking
// ---------------------------------------------------------------------------