mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-11-18 19:40:57 +00:00
Let ClientImpl::stop() end a connection being opened (#2668)
* Let ClientImpl::stop() end a connect or a TLS handshake stop() took socket_mutex_, which send_() and open_stream() hold while they open the connection, so a stop() made during a connect, a TLS handshake or the CONNECT of a proxy tunnel waited for the connection to open or to time out, 300 seconds by default, for a server that never answers. stop() no longer waits for the mutex while a connection opens: it cancels the connection phase by a compare-exchange from Connecting, and the end of the phase reads the cancel in the same exchange that takes the state back to Idle, so a cancel stop() accepts is never lost. stop() also sets stop_requested_: the wait of the connect and the waits of the handshake, in every TLS backend, poll it in slices of 100 ms, as do the reads of the CONNECT of a proxy tunnel. A request or a stream canceled there reports Error::Canceled, before it sends anything or takes the socket. A request opened after stop() clears the flag as before, and a stream now does too. A negative connection timeout still waits without end in the interruptible connect wait. * Add ClientImpl::set_interrupt(), a stop the caller holds stop() ends what is in flight, and a request or a stream opened after it clears the flag, so a stop() made just before a request goes out is lost. set_interrupt() gives the client a predicate its caller owns, polled wherever stop_requested_ is: the connect, the TLS handshake, the CONNECT of a proxy tunnel and the reads of a request, and the head of a stream too. The client of a cross-host redirect keeps it. A request or a stream refuses to go out once it holds, so a stop the caller holds is never lost, whenever it comes. A call blocked in the system, a send() of a large body or a TLS read inside a record, still ends through stop() alone, which shuts the socket down. A timeout past what the clock reaches now waits without end instead of expiring at once, so such a wait still ends on the interrupt. * test: create the backlog sockets with SOCK_NONBLOCK detail::set_nonblocking lives in httplib.cc in the split build, so test_split did not compile. The test only runs on Linux, where SOCK_NONBLOCK makes the socket nonblocking at creation. * Open the connection without socket_mutex_ instead Rework the change so that send_() and open_stream_() open the connection without holding socket_mutex_, as requests are already serialized by request_mutex_. stop() then never waits for a connection being opened: it always sets stop_requested_, which the connect wait, the TLS handshake, the CONNECT and the wait for the head of a stream poll, and the call ends with Error::Canceled before it sends anything. This replaces the connection state machine and the try_lock loop in stop(). The flag is cleared once, as a send() or an open_stream() starts, so a retry inside the call no longer drops a stop() it already got. Drop set_interrupt() for now: a predicate held per client cannot be shared, e.g. by an SSEClient that borrows the caller's Client. Also drop StopEndsATlsReadInsideARecord, which checked existing behavior that does not hold on Windows, and share the listener setup of the tests. Keep the deadline_after() fix: a timeout past what the clock reaches waits forever instead of overflowing into an immediate timeout. --------- Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
This commit is contained in:
1 parent
cd446a4e01
commit
5a956da084
2 files changed
+377
-122
No files matched your search
@@ -3023,8 +3023,8 @@ protected:
|
|||||||
// shutdown_socket
|
// shutdown_socket
|
||||||
// close_socket
|
// close_socket
|
||||||
// disconnect
|
// disconnect
|
||||||
// should ONLY be called when socket_mutex_ is locked, and only when
|
// should ONLY be called on socket_ with socket_mutex_ locked, or on a
|
||||||
// no other thread is using the socket.
|
// connection being opened, and only when no other thread is using it.
|
||||||
virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
|
virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
|
||||||
void shutdown_socket(Socket &socket) const;
|
void shutdown_socket(Socket &socket) const;
|
||||||
void close_socket(Socket &socket);
|
void close_socket(Socket &socket);
|
||||||
@@ -3035,6 +3035,13 @@ protected:
|
|||||||
// changed since, is closed instead.
|
// changed since, is closed instead.
|
||||||
bool socket_reusable();
|
bool socket_reusable();
|
||||||
|
|
||||||
|
// Makes socket_ ready for a request, with socket_mutex_ held by guard. A new
|
||||||
|
// connection is opened without the lock, so that stop() can end it.
|
||||||
|
bool
|
||||||
|
prepare_socket(std::unique_lock<std::mutex> &guard,
|
||||||
|
std::chrono::time_point<std::chrono::steady_clock> start_time,
|
||||||
|
Response &res, bool &success, Error &error);
|
||||||
|
|
||||||
// TLS settings apply as a connection is set up, so a change makes the
|
// TLS settings apply as a connection is set up, so a change makes the
|
||||||
// connection kept alive unfit for the next request.
|
// connection kept alive unfit for the next request.
|
||||||
void tls_settings_changed() { tls_settings_version_++; }
|
void tls_settings_changed() { tls_settings_version_++; }
|
||||||
@@ -3060,16 +3067,21 @@ protected:
|
|||||||
// How many send() calls are running on this client, guarded by
|
// How many send() calls are running on this client, guarded by
|
||||||
// request_mutex_
|
// request_mutex_
|
||||||
size_t send_depth_ = 0;
|
size_t send_depth_ = 0;
|
||||||
|
// Also guarded by request_mutex_
|
||||||
|
size_t socket_tls_settings_version_ = 0;
|
||||||
|
|
||||||
// These are all protected under socket_mutex
|
// These are all protected under socket_mutex
|
||||||
size_t socket_requests_in_flight_ = 0;
|
size_t socket_requests_in_flight_ = 0;
|
||||||
std::thread::id socket_requests_are_from_thread_ = std::thread::id();
|
std::thread::id socket_requests_are_from_thread_ = std::thread::id();
|
||||||
bool socket_should_be_closed_when_request_is_done_ = false;
|
bool socket_should_be_closed_when_request_is_done_ = false;
|
||||||
size_t socket_tls_settings_version_ = 0;
|
|
||||||
|
|
||||||
// Set by stop() while a request is in flight. The request's reads poll it,
|
// Set by stop(), cleared as a send() or an open_stream() starts. Its waits
|
||||||
// because shutting the socket down does not wake a read on Windows.
|
// poll it: shutdown() does not reach a connection being opened, nor wake a
|
||||||
|
// read on Windows.
|
||||||
std::atomic<bool> stop_requested_{false};
|
std::atomic<bool> stop_requested_{false};
|
||||||
|
std::function<bool()> stop_interrupt() const {
|
||||||
|
return [this] { return stop_requested_.load(); };
|
||||||
|
}
|
||||||
|
|
||||||
std::atomic<size_t> tls_settings_version_{0};
|
std::atomic<size_t> tls_settings_version_{0};
|
||||||
|
|
||||||
@@ -3866,15 +3878,14 @@ bool process_client_socket(
|
|||||||
std::chrono::time_point<std::chrono::steady_clock> start_time,
|
std::chrono::time_point<std::chrono::steady_clock> start_time,
|
||||||
std::function<bool(Stream &)> callback);
|
std::function<bool(Stream &)> callback);
|
||||||
|
|
||||||
socket_t create_client_socket(const std::string &host, const std::string &ip,
|
socket_t create_client_socket(
|
||||||
int port, int address_family, bool tcp_nodelay,
|
const std::string &host, const std::string &ip, int port,
|
||||||
bool ipv6_v6only, SocketOptions socket_options,
|
int address_family, bool tcp_nodelay, bool ipv6_v6only,
|
||||||
time_t connection_timeout_sec,
|
SocketOptions socket_options, time_t connection_timeout_sec,
|
||||||
time_t connection_timeout_usec,
|
time_t connection_timeout_usec, time_t read_timeout_sec,
|
||||||
time_t read_timeout_sec, time_t read_timeout_usec,
|
time_t read_timeout_usec, time_t write_timeout_sec,
|
||||||
time_t write_timeout_sec,
|
time_t write_timeout_usec, const std::string &intf, Error &error,
|
||||||
time_t write_timeout_usec,
|
const std::function<bool()> &interrupted = nullptr);
|
||||||
const std::string &intf, Error &error);
|
|
||||||
|
|
||||||
const char *get_header_value(const Headers &headers, const std::string &key,
|
const char *get_header_value(const Headers &headers, const std::string &key,
|
||||||
const char *def, size_t id);
|
const char *def, size_t id);
|
||||||
@@ -5407,9 +5418,10 @@ bool set_sni(session_t session, const char *hostname, bool verify_hostname);
|
|||||||
TlsError connect(session_t session);
|
TlsError connect(session_t session);
|
||||||
TlsError accept(session_t session);
|
TlsError accept(session_t session);
|
||||||
|
|
||||||
// Handshake with timeout (blocking until timeout)
|
// Handshake with timeout (blocking until timeout, or until interrupted)
|
||||||
bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
|
bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
|
||||||
time_t timeout_usec, TlsError *err);
|
time_t timeout_usec, TlsError *err,
|
||||||
|
const std::function<bool()> &interrupted = nullptr);
|
||||||
bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
|
bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
|
||||||
time_t timeout_usec, TlsError *err);
|
time_t timeout_usec, TlsError *err);
|
||||||
|
|
||||||
@@ -6872,39 +6884,41 @@ inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
|
|||||||
return select_impl(sock, POLLOUT, sec, usec);
|
return select_impl(sock, POLLOUT, sec, usec);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The point sec and usec from now, for select_until(). A negative sec never
|
// The point sec and usec from now, for select_until(). A negative sec, or one
|
||||||
// comes, as a negative timeout waits forever in select_impl().
|
// past what the clock reaches, never comes.
|
||||||
inline std::chrono::steady_clock::time_point deadline_after(time_t sec,
|
inline std::chrono::steady_clock::time_point deadline_after(time_t sec,
|
||||||
time_t usec) {
|
time_t usec) {
|
||||||
if (sec < 0) { return (std::chrono::steady_clock::time_point::max)(); }
|
auto now = std::chrono::steady_clock::now();
|
||||||
return std::chrono::steady_clock::now() + std::chrono::seconds(sec) +
|
auto never = (std::chrono::steady_clock::time_point::max)();
|
||||||
std::chrono::microseconds(usec);
|
if (sec < 0 ||
|
||||||
|
sec >= std::chrono::duration_cast<std::chrono::seconds>(never - now)
|
||||||
|
.count()) {
|
||||||
|
return never;
|
||||||
|
}
|
||||||
|
return now + std::chrono::seconds(sec) + std::chrono::microseconds(usec);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Waits only for the time left until deadline, so that all the waits of one
|
// Waits only for the time left until deadline, so that all the waits of one
|
||||||
// TLS handshake come out of a single timeout.
|
// TLS handshake come out of a single timeout. With interrupted, it waits in
|
||||||
inline ssize_t select_until(socket_t sock, short events,
|
// slices and gives up once interrupted() returns true, as a local shutdown()
|
||||||
std::chrono::steady_clock::time_point deadline) {
|
// would not wake the wait on Windows.
|
||||||
if (deadline == (std::chrono::steady_clock::time_point::max)()) {
|
|
||||||
return select_impl(sock, events, -1, 0);
|
|
||||||
}
|
|
||||||
auto left = std::chrono::duration_cast<std::chrono::microseconds>(
|
|
||||||
deadline - std::chrono::steady_clock::now())
|
|
||||||
.count();
|
|
||||||
if (left <= 0) { return 0; }
|
|
||||||
return select_impl(sock, events, static_cast<time_t>(left / 1000000),
|
|
||||||
static_cast<time_t>(left % 1000000));
|
|
||||||
}
|
|
||||||
|
|
||||||
// select_read(), but waits in slices and gives up once interrupted() returns
|
|
||||||
// true. A local shutdown() would not wake the wait on Windows.
|
|
||||||
inline ssize_t
|
inline ssize_t
|
||||||
select_read_interruptible(socket_t sock, time_t sec, time_t usec,
|
select_until(socket_t sock, short events,
|
||||||
const std::function<bool()> &interrupted) {
|
std::chrono::steady_clock::time_point deadline,
|
||||||
if (!interrupted) { return select_read(sock, sec, usec); }
|
const std::function<bool()> &interrupted = nullptr) {
|
||||||
|
if (!interrupted) {
|
||||||
|
if (deadline == (std::chrono::steady_clock::time_point::max)()) {
|
||||||
|
return select_impl(sock, events, -1, 0);
|
||||||
|
}
|
||||||
|
auto left = std::chrono::duration_cast<std::chrono::microseconds>(
|
||||||
|
deadline - std::chrono::steady_clock::now())
|
||||||
|
.count();
|
||||||
|
if (left <= 0) { return 0; }
|
||||||
|
return select_impl(sock, events, static_cast<time_t>(left / 1000000),
|
||||||
|
static_cast<time_t>(left % 1000000));
|
||||||
|
}
|
||||||
|
|
||||||
const auto slice = std::chrono::microseconds(100000);
|
const auto slice = std::chrono::microseconds(100000);
|
||||||
auto deadline = deadline_after(sec, usec);
|
|
||||||
while (!interrupted()) {
|
while (!interrupted()) {
|
||||||
auto left = std::chrono::duration_cast<std::chrono::microseconds>(
|
auto left = std::chrono::duration_cast<std::chrono::microseconds>(
|
||||||
deadline - std::chrono::steady_clock::now());
|
deadline - std::chrono::steady_clock::now());
|
||||||
@@ -6914,36 +6928,46 @@ select_read_interruptible(socket_t sock, time_t sec, time_t usec,
|
|||||||
auto wait_usec = last ? (std::max)((left.count() + 999) / 1000 * 1000,
|
auto wait_usec = last ? (std::max)((left.count() + 999) / 1000 * 1000,
|
||||||
static_cast<decltype(left.count())>(0))
|
static_cast<decltype(left.count())>(0))
|
||||||
: slice.count();
|
: slice.count();
|
||||||
auto ret = select_impl(sock, POLLIN, 0, static_cast<time_t>(wait_usec));
|
auto ret = select_impl(sock, events, 0, static_cast<time_t>(wait_usec));
|
||||||
if (ret != 0 || last) { return ret; }
|
if (ret != 0 || last) { return ret; }
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
|
// select_impl(), but waits in slices and gives up once interrupted() returns
|
||||||
time_t usec) {
|
// true
|
||||||
struct pollfd pfd_read;
|
inline ssize_t select_interruptible(socket_t sock, short events, time_t sec,
|
||||||
pfd_read.fd = sock;
|
time_t usec,
|
||||||
pfd_read.events = POLLIN | POLLOUT;
|
const std::function<bool()> &interrupted) {
|
||||||
pfd_read.revents = 0;
|
if (!interrupted) { return select_impl(sock, events, sec, usec); }
|
||||||
|
return select_until(sock, events, deadline_after(sec, usec), interrupted);
|
||||||
|
}
|
||||||
|
|
||||||
auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
|
inline ssize_t
|
||||||
|
select_read_interruptible(socket_t sock, time_t sec, time_t usec,
|
||||||
|
const std::function<bool()> &interrupted) {
|
||||||
|
return select_interruptible(sock, POLLIN, sec, usec, interrupted);
|
||||||
|
}
|
||||||
|
|
||||||
auto poll_res =
|
// Waits for a connect in progress, which ends as Error::Canceled once
|
||||||
handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
|
// interrupted() returns true
|
||||||
|
inline Error
|
||||||
if (poll_res == 0) { return Error::ConnectionTimeout; }
|
wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec,
|
||||||
|
const std::function<bool()> &interrupted = nullptr) {
|
||||||
if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
|
auto ret =
|
||||||
auto error = 0;
|
select_interruptible(sock, POLLIN | POLLOUT, sec, usec, interrupted);
|
||||||
socklen_t len = sizeof(error);
|
if (ret == 0) {
|
||||||
auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
|
return interrupted && interrupted() ? Error::Canceled
|
||||||
reinterpret_cast<char *>(&error), &len);
|
: Error::ConnectionTimeout;
|
||||||
auto successful = res >= 0 && !error;
|
|
||||||
return successful ? Error::Success : Error::Connection;
|
|
||||||
}
|
}
|
||||||
|
if (ret < 0) { return Error::Connection; }
|
||||||
|
|
||||||
return Error::Connection;
|
// A failed connect reports its error here, whatever events poll() returned
|
||||||
|
auto error = 0;
|
||||||
|
socklen_t len = sizeof(error);
|
||||||
|
auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
|
||||||
|
reinterpret_cast<char *>(&error), &len);
|
||||||
|
return res >= 0 && !error ? Error::Success : Error::Connection;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool is_socket_alive(socket_t sock) {
|
inline bool is_socket_alive(socket_t sock) {
|
||||||
@@ -7760,13 +7784,15 @@ inline std::string if2ip(int address_family, const std::string &ifn) {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
inline socket_t create_client_socket(
|
inline socket_t
|
||||||
const std::string &host, const std::string &ip, int port,
|
create_client_socket(const std::string &host, const std::string &ip, int port,
|
||||||
int address_family, bool tcp_nodelay, bool ipv6_v6only,
|
int address_family, bool tcp_nodelay, bool ipv6_v6only,
|
||||||
SocketOptions socket_options, time_t connection_timeout_sec,
|
SocketOptions socket_options,
|
||||||
time_t connection_timeout_usec, time_t read_timeout_sec,
|
time_t connection_timeout_sec,
|
||||||
time_t read_timeout_usec, time_t write_timeout_sec,
|
time_t connection_timeout_usec, time_t read_timeout_sec,
|
||||||
time_t write_timeout_usec, const std::string &intf, Error &error) {
|
time_t read_timeout_usec, time_t write_timeout_sec,
|
||||||
|
time_t write_timeout_usec, const std::string &intf,
|
||||||
|
Error &error, const std::function<bool()> &interrupted) {
|
||||||
auto sock = create_socket(
|
auto sock = create_socket(
|
||||||
host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
|
host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
|
||||||
std::move(socket_options),
|
std::move(socket_options),
|
||||||
@@ -7792,10 +7818,13 @@ inline socket_t create_client_socket(
|
|||||||
error = Error::Connection;
|
error = Error::Connection;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
|
error =
|
||||||
connection_timeout_usec);
|
wait_until_socket_is_ready(sock2, connection_timeout_sec,
|
||||||
|
connection_timeout_usec, interrupted);
|
||||||
if (error != Error::Success) {
|
if (error != Error::Success) {
|
||||||
if (error == Error::ConnectionTimeout) { quit = true; }
|
if (error == Error::ConnectionTimeout || error == Error::Canceled) {
|
||||||
|
quit = true;
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11465,6 +11494,8 @@ struct ClientTlsSessionOptions {
|
|||||||
// certificate verification.
|
// certificate verification.
|
||||||
bool server_hostname_verification = true;
|
bool server_hostname_verification = true;
|
||||||
std::function<SSLVerifierResponse(tls::session_t)> session_verifier;
|
std::function<SSLVerifierResponse(tls::session_t)> session_verifier;
|
||||||
|
// When set, ends the handshake as a timeout does once it returns true
|
||||||
|
std::function<bool()> interrupted;
|
||||||
// When non-null, guards session creation against concurrent use of the
|
// When non-null, guards session creation against concurrent use of the
|
||||||
// context. A WebSocketClient is not safe to use from several threads to
|
// context. A WebSocketClient is not safe to use from several threads to
|
||||||
// begin with, so it passes nothing.
|
// begin with, so it passes nothing.
|
||||||
@@ -11564,8 +11595,8 @@ inline bool setup_client_tls_session(
|
|||||||
}
|
}
|
||||||
|
|
||||||
TlsError tls_err;
|
TlsError tls_err;
|
||||||
if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec,
|
if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, &tls_err,
|
||||||
&tls_err)) {
|
options.interrupted)) {
|
||||||
return fail_tls(tls_err.code, tls_err.backend_code);
|
return fail_tls(tls_err.code, tls_err.backend_code);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -15743,7 +15774,8 @@ inline socket_t ClientImpl::create_client_socket(Error &error) const {
|
|||||||
proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
|
proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
|
||||||
ipv6_v6only_, socket_options_, connection_timeout_sec_,
|
ipv6_v6only_, socket_options_, connection_timeout_sec_,
|
||||||
connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
|
connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
|
||||||
write_timeout_sec_, write_timeout_usec_, interface_, error);
|
write_timeout_sec_, write_timeout_usec_, interface_, error,
|
||||||
|
stop_interrupt());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check is custom IP or hostname specified for host_
|
// Check is custom IP or hostname specified for host_
|
||||||
@@ -15755,7 +15787,7 @@ inline socket_t ClientImpl::create_client_socket(Error &error) const {
|
|||||||
connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
|
connect_host, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
|
||||||
socket_options_, connection_timeout_sec_, connection_timeout_usec_,
|
socket_options_, connection_timeout_sec_, connection_timeout_usec_,
|
||||||
read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
|
read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
|
||||||
write_timeout_usec_, interface_, error);
|
write_timeout_usec_, interface_, error, stop_interrupt());
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool ClientImpl::create_and_connect_socket(Socket &socket,
|
inline bool ClientImpl::create_and_connect_socket(Socket &socket,
|
||||||
@@ -15833,6 +15865,33 @@ inline bool ClientImpl::socket_reusable() {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline bool ClientImpl::prepare_socket(
|
||||||
|
std::unique_lock<std::mutex> &guard,
|
||||||
|
std::chrono::time_point<std::chrono::steady_clock> start_time,
|
||||||
|
Response &res, bool &success, Error &error) {
|
||||||
|
auto opened = true;
|
||||||
|
if (!socket_reusable()) {
|
||||||
|
Socket socket;
|
||||||
|
guard.unlock();
|
||||||
|
opened = ensure_socket_connection(socket, error);
|
||||||
|
if (opened) {
|
||||||
|
opened = setup_proxy_connection(socket, start_time, res, success, error);
|
||||||
|
} else {
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
guard.lock();
|
||||||
|
socket_ = socket;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stop_requested_) {
|
||||||
|
disconnect(/*gracefully=*/false);
|
||||||
|
error = Error::Canceled;
|
||||||
|
success = false;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return opened;
|
||||||
|
}
|
||||||
|
|
||||||
inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
|
inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
|
||||||
Response &res,
|
Response &res,
|
||||||
bool skip_100_continue) const {
|
bool skip_100_continue) const {
|
||||||
@@ -15877,7 +15936,10 @@ inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
|
|||||||
// the call the caller made reports a failure, once, with its request.
|
// the call the caller made reports a failure, once, with its request.
|
||||||
auto outermost = send_depth_++ == 0;
|
auto outermost = send_depth_++ == 0;
|
||||||
auto se = detail::scope_exit([&] { send_depth_--; });
|
auto se = detail::scope_exit([&] { send_depth_--; });
|
||||||
if (outermost) { error = Error::Success; }
|
if (outermost) {
|
||||||
|
error = Error::Success;
|
||||||
|
stop_requested_ = false;
|
||||||
|
}
|
||||||
|
|
||||||
auto ret = send_(req, res, error);
|
auto ret = send_(req, res, error);
|
||||||
if (error == Error::SSLPeerCouldBeClosed_) {
|
if (error == Error::SSLPeerCouldBeClosed_) {
|
||||||
@@ -15903,26 +15965,16 @@ inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> guard(socket_mutex_);
|
std::unique_lock<std::mutex> guard(socket_mutex_);
|
||||||
|
|
||||||
// Set this to false immediately - if it ever gets set to true by the end
|
// Set this to false immediately - if it ever gets set to true by the end
|
||||||
// of the request, we know another thread instructed us to close the
|
// of the request, we know another thread instructed us to close the
|
||||||
// socket.
|
// socket.
|
||||||
socket_should_be_closed_when_request_is_done_ = false;
|
socket_should_be_closed_when_request_is_done_ = false;
|
||||||
|
|
||||||
// A redirect or a retry sent inside a request keeps its stop()
|
auto success = true;
|
||||||
if (socket_requests_in_flight_ == 0) { stop_requested_ = false; }
|
if (!prepare_socket(guard, req.start_time_, res, success, error)) {
|
||||||
|
return success;
|
||||||
if (!socket_reusable()) {
|
|
||||||
if (!ensure_socket_connection(socket_, error)) { return false; }
|
|
||||||
|
|
||||||
{
|
|
||||||
auto success = true;
|
|
||||||
if (!setup_proxy_connection(socket_, req.start_time_, res, success,
|
|
||||||
error)) {
|
|
||||||
return success;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mark the current socket as being in use so that it cannot be closed by
|
// Mark the current socket as being in use so that it cannot be closed by
|
||||||
@@ -15960,7 +16012,7 @@ inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
|
ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
|
||||||
strm.set_read_interrupt([this] { return stop_requested_.load(); });
|
strm.set_read_interrupt(stop_interrupt());
|
||||||
return handle_request(strm, req, res, close_connection, error);
|
return handle_request(strm, req, res, close_connection, error);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -16077,23 +16129,14 @@ inline ClientImpl::StreamHandle ClientImpl::open_stream_(Request &req) {
|
|||||||
{
|
{
|
||||||
// A request in flight uses socket_ without holding socket_mutex_
|
// A request in flight uses socket_ without holding socket_mutex_
|
||||||
std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
|
std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
|
||||||
std::lock_guard<std::mutex> guard(socket_mutex_);
|
if (send_depth_ == 0) { stop_requested_ = false; }
|
||||||
|
std::unique_lock<std::mutex> guard(socket_mutex_);
|
||||||
|
|
||||||
if (!socket_reusable()) {
|
auto success = true;
|
||||||
if (!ensure_socket_connection(socket_, handle.error)) {
|
if (!prepare_socket(guard, std::chrono::steady_clock::now(),
|
||||||
handle.response.reset();
|
*handle.response, success, handle.error)) {
|
||||||
return handle;
|
if (!success) { handle.response.reset(); }
|
||||||
}
|
return handle;
|
||||||
|
|
||||||
{
|
|
||||||
auto success = true;
|
|
||||||
auto start_time = std::chrono::steady_clock::now();
|
|
||||||
if (!setup_proxy_connection(socket_, start_time, *handle.response,
|
|
||||||
success, handle.error)) {
|
|
||||||
if (!success) { handle.response.reset(); }
|
|
||||||
return handle;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
transfer_socket_ownership_to_handle(handle);
|
transfer_socket_ownership_to_handle(handle);
|
||||||
@@ -16119,6 +16162,11 @@ inline ClientImpl::StreamHandle ClientImpl::open_stream_(Request &req) {
|
|||||||
|
|
||||||
auto &strm = *handle.stream_;
|
auto &strm = *handle.stream_;
|
||||||
|
|
||||||
|
// Only for the head, as the handle may outlive this client
|
||||||
|
strm.set_read_interrupt(stop_interrupt());
|
||||||
|
auto release_interrupt =
|
||||||
|
detail::scope_exit([&] { strm.set_read_interrupt(nullptr); });
|
||||||
|
|
||||||
// After connecting, as for a buffered request
|
// After connecting, as for a buffered request
|
||||||
add_credential_headers(req);
|
add_credential_headers(req);
|
||||||
|
|
||||||
@@ -18193,6 +18241,8 @@ inline Result ClientImpl::Options(const std::string &path,
|
|||||||
inline void ClientImpl::stop() {
|
inline void ClientImpl::stop() {
|
||||||
std::lock_guard<std::mutex> guard(socket_mutex_);
|
std::lock_guard<std::mutex> guard(socket_mutex_);
|
||||||
|
|
||||||
|
stop_requested_ = true;
|
||||||
|
|
||||||
// If there is anything ongoing right now, the ONLY thread-safe thing we can
|
// If there is anything ongoing right now, the ONLY thread-safe thing we can
|
||||||
// do is to shutdown_socket, so that threads using this socket suddenly
|
// do is to shutdown_socket, so that threads using this socket suddenly
|
||||||
// discover they can't read/write any more and error out. Everything else
|
// discover they can't read/write any more and error out. Everything else
|
||||||
@@ -18200,9 +18250,6 @@ inline void ClientImpl::stop() {
|
|||||||
// are not thread-safe.
|
// are not thread-safe.
|
||||||
if (socket_requests_in_flight_ > 0) {
|
if (socket_requests_in_flight_ > 0) {
|
||||||
shutdown_socket(socket_);
|
shutdown_socket(socket_);
|
||||||
// shutdown() does not wake a read waiting in WSAPoll on Windows, so the
|
|
||||||
// request's reads also give up once they see this flag.
|
|
||||||
stop_requested_ = true;
|
|
||||||
|
|
||||||
// Aside from that, we set a flag for the socket to be closed when we're
|
// Aside from that, we set a flag for the socket to be closed when we're
|
||||||
// done.
|
// done.
|
||||||
@@ -19359,8 +19406,7 @@ inline bool SSLClient::setup_proxy_connection(
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Assumes that socket_mutex_ is locked and that there are no requests in
|
// Assumes that socket is a connection being opened, which no other thread uses
|
||||||
// flight
|
|
||||||
inline bool SSLClient::connect_with_proxy(
|
inline bool SSLClient::connect_with_proxy(
|
||||||
Socket &socket,
|
Socket &socket,
|
||||||
std::chrono::time_point<std::chrono::steady_clock> start_time,
|
std::chrono::time_point<std::chrono::steady_clock> start_time,
|
||||||
@@ -19375,6 +19421,7 @@ inline bool SSLClient::connect_with_proxy(
|
|||||||
socket.sock, read_timeout_sec_, read_timeout_usec_,
|
socket.sock, read_timeout_sec_, read_timeout_usec_,
|
||||||
write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
|
write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
|
||||||
start_time, [&](Stream &strm) {
|
start_time, [&](Stream &strm) {
|
||||||
|
strm.set_read_interrupt(stop_interrupt());
|
||||||
Request req2;
|
Request req2;
|
||||||
req2.method = "CONNECT";
|
req2.method = "CONNECT";
|
||||||
req2.path = connect_target;
|
req2.path = connect_target;
|
||||||
@@ -19415,6 +19462,7 @@ inline bool SSLClient::connect_with_proxy(
|
|||||||
socket.sock, read_timeout_sec_, read_timeout_usec_,
|
socket.sock, read_timeout_sec_, read_timeout_usec_,
|
||||||
write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
|
write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
|
||||||
start_time, [&](Stream &strm) {
|
start_time, [&](Stream &strm) {
|
||||||
|
strm.set_read_interrupt(stop_interrupt());
|
||||||
Request req3;
|
Request req3;
|
||||||
req3.method = "CONNECT";
|
req3.method = "CONNECT";
|
||||||
req3.path = connect_target;
|
req3.path = connect_target;
|
||||||
@@ -19609,6 +19657,7 @@ inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
|
|||||||
detail::ClientTlsSessionOptions options;
|
detail::ClientTlsSessionOptions options;
|
||||||
options.server_hostname_verification = server_hostname_verification_;
|
options.server_hostname_verification = server_hostname_verification_;
|
||||||
options.session_verifier = session_verifier_;
|
options.session_verifier = session_verifier_;
|
||||||
|
options.interrupted = stop_interrupt();
|
||||||
options.ctx_mutex = &ctx_mutex_;
|
options.ctx_mutex = &ctx_mutex_;
|
||||||
#ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
|
#ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
|
||||||
// Skip Schannel when a custom CA cert is specified, as the Windows
|
// Skip Schannel when a custom CA cert is specified, as the Windows
|
||||||
@@ -20555,7 +20604,8 @@ inline TlsError accept(session_t session) {
|
|||||||
|
|
||||||
inline bool connect_nonblocking(session_t session, socket_t sock,
|
inline bool connect_nonblocking(session_t session, socket_t sock,
|
||||||
time_t timeout_sec, time_t timeout_usec,
|
time_t timeout_sec, time_t timeout_usec,
|
||||||
TlsError *err) {
|
TlsError *err,
|
||||||
|
const std::function<bool()> &interrupted) {
|
||||||
if (!session) {
|
if (!session) {
|
||||||
if (err) { err->code = ErrorCode::Fatal; }
|
if (err) { err->code = ErrorCode::Fatal; }
|
||||||
return false;
|
return false;
|
||||||
@@ -20580,10 +20630,14 @@ inline bool connect_nonblocking(session_t session, socket_t sock,
|
|||||||
auto ssl_err = SSL_get_error(ssl, res);
|
auto ssl_err = SSL_get_error(ssl, res);
|
||||||
switch (ssl_err) {
|
switch (ssl_err) {
|
||||||
case SSL_ERROR_WANT_READ:
|
case SSL_ERROR_WANT_READ:
|
||||||
if (detail::select_until(sock, POLLIN, deadline) > 0) { continue; }
|
if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
case SSL_ERROR_WANT_WRITE:
|
case SSL_ERROR_WANT_WRITE:
|
||||||
if (detail::select_until(sock, POLLOUT, deadline) > 0) { continue; }
|
if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
default: break;
|
default: break;
|
||||||
}
|
}
|
||||||
@@ -21910,7 +21964,8 @@ inline TlsError accept(session_t session) {
|
|||||||
|
|
||||||
inline bool connect_nonblocking(session_t session, socket_t sock,
|
inline bool connect_nonblocking(session_t session, socket_t sock,
|
||||||
time_t timeout_sec, time_t timeout_usec,
|
time_t timeout_sec, time_t timeout_usec,
|
||||||
TlsError *err) {
|
TlsError *err,
|
||||||
|
const std::function<bool()> &interrupted) {
|
||||||
if (!session) {
|
if (!session) {
|
||||||
if (err) { err->code = ErrorCode::Fatal; }
|
if (err) { err->code = ErrorCode::Fatal; }
|
||||||
return false;
|
return false;
|
||||||
@@ -21929,9 +21984,13 @@ inline bool connect_nonblocking(session_t session, socket_t sock,
|
|||||||
// Non-fatal TLS 1.3 ticket; retry immediately.
|
// Non-fatal TLS 1.3 ticket; retry immediately.
|
||||||
if (impl::mbedtls_is_session_ticket(ret)) { continue; }
|
if (impl::mbedtls_is_session_ticket(ret)) { continue; }
|
||||||
if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
|
if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
|
||||||
if (detail::select_until(sock, POLLIN, deadline) > 0) { continue; }
|
if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
} else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
|
} else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
|
||||||
if (detail::select_until(sock, POLLOUT, deadline) > 0) { continue; }
|
if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TlsError or timeout
|
// TlsError or timeout
|
||||||
@@ -23083,7 +23142,8 @@ inline TlsError accept(session_t session) {
|
|||||||
|
|
||||||
inline bool connect_nonblocking(session_t session, socket_t sock,
|
inline bool connect_nonblocking(session_t session, socket_t sock,
|
||||||
time_t timeout_sec, time_t timeout_usec,
|
time_t timeout_sec, time_t timeout_usec,
|
||||||
TlsError *err) {
|
TlsError *err,
|
||||||
|
const std::function<bool()> &interrupted) {
|
||||||
if (!session) {
|
if (!session) {
|
||||||
if (err) { err->code = ErrorCode::Fatal; }
|
if (err) { err->code = ErrorCode::Fatal; }
|
||||||
return false;
|
return false;
|
||||||
@@ -23101,9 +23161,13 @@ inline bool connect_nonblocking(session_t session, socket_t sock,
|
|||||||
while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
|
while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
|
||||||
int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
|
int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
|
||||||
if (ssl_error == SSL_ERROR_WANT_READ) {
|
if (ssl_error == SSL_ERROR_WANT_READ) {
|
||||||
if (detail::select_until(sock, POLLIN, deadline) > 0) { continue; }
|
if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
} else if (ssl_error == SSL_ERROR_WANT_WRITE) {
|
} else if (ssl_error == SSL_ERROR_WANT_WRITE) {
|
||||||
if (detail::select_until(sock, POLLOUT, deadline) > 0) { continue; }
|
if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Error or timeout
|
// Error or timeout
|
||||||
|
|||||||
+191
@@ -3600,6 +3600,197 @@ TEST(ClientStopTest, StopEndsWaitForResponse) {
|
|||||||
EXPECT_EQ(Error::Read, res.error());
|
EXPECT_EQ(Error::Read, res.error());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A listener whose backlog completes the TCP connections of clients, and that
|
||||||
|
// never answers them
|
||||||
|
struct SilentListener {
|
||||||
|
socket_t sock = INVALID_SOCKET;
|
||||||
|
sockaddr_in addr{};
|
||||||
|
int port = 0;
|
||||||
|
|
||||||
|
explicit SilentListener(int backlog = 1) {
|
||||||
|
sock = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
addr.sin_family = AF_INET;
|
||||||
|
::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
|
||||||
|
socklen_t len = sizeof(addr);
|
||||||
|
if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
|
||||||
|
::listen(sock, backlog) != 0 ||
|
||||||
|
::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
|
||||||
|
detail::close_socket(sock);
|
||||||
|
sock = INVALID_SOCKET;
|
||||||
|
}
|
||||||
|
port = ntohs(addr.sin_port);
|
||||||
|
}
|
||||||
|
~SilentListener() { detail::close_socket(sock); }
|
||||||
|
|
||||||
|
// The next connection, whose reads give up after 5 seconds
|
||||||
|
socket_t accept() const {
|
||||||
|
auto peer = ::accept(sock, nullptr, nullptr);
|
||||||
|
if (peer != INVALID_SOCKET) {
|
||||||
|
detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
|
||||||
|
}
|
||||||
|
return peer;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
static bool receives_a_byte(socket_t peer) {
|
||||||
|
char c = 0;
|
||||||
|
return detail::read_socket(peer, &c, 1, 0) == 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Runs op, stops cli once the listener receives the first byte op sends, and
|
||||||
|
// expects op to end with error soon after
|
||||||
|
template <typename ClientType, typename Op>
|
||||||
|
static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
|
||||||
|
Op op, Error error = Error::Canceled) {
|
||||||
|
auto ended = std::async(std::launch::async, op);
|
||||||
|
auto peer = listener.accept();
|
||||||
|
auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
|
||||||
|
ASSERT_NE(INVALID_SOCKET, peer);
|
||||||
|
ASSERT_TRUE(receives_a_byte(peer));
|
||||||
|
|
||||||
|
cli.stop();
|
||||||
|
EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
|
||||||
|
EXPECT_EQ(error, ended.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stops itself from another thread as the connection opens, the last moment a
|
||||||
|
// stop() cancels it. It waits for stop() at most a second, so a stop() that
|
||||||
|
// waits for the connection fails the test instead of hanging it.
|
||||||
|
class StoppedAsConnectedClient : public ClientImpl {
|
||||||
|
public:
|
||||||
|
using ClientImpl::ClientImpl;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
bool ensure_socket_connection(Socket &socket, Error &error) override {
|
||||||
|
if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
|
||||||
|
stopper_ = std::async(std::launch::async, [this] { stop(); });
|
||||||
|
stopper_.wait_for(std::chrono::seconds(1));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::future<void> stopper_;
|
||||||
|
};
|
||||||
|
|
||||||
|
TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
|
||||||
|
SilentListener listener;
|
||||||
|
ASSERT_NE(INVALID_SOCKET, listener.sock);
|
||||||
|
|
||||||
|
StoppedAsConnectedClient cli("127.0.0.1", listener.port);
|
||||||
|
cli.set_read_timeout(std::chrono::seconds(3));
|
||||||
|
EXPECT_EQ(Error::Canceled, cli.Get("/").error());
|
||||||
|
auto peer = listener.accept();
|
||||||
|
EXPECT_FALSE(receives_a_byte(peer));
|
||||||
|
detail::close_socket(peer);
|
||||||
|
|
||||||
|
auto handle = cli.open_stream("GET", "/");
|
||||||
|
EXPECT_FALSE(handle.is_valid());
|
||||||
|
EXPECT_EQ(Error::Canceled, handle.error);
|
||||||
|
peer = listener.accept();
|
||||||
|
EXPECT_FALSE(receives_a_byte(peer));
|
||||||
|
detail::close_socket(peer);
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef __linux__
|
||||||
|
// A connect that a listener with a full backlog never completes
|
||||||
|
TEST(ClientStopTest, StopEndsAConnect) {
|
||||||
|
SilentListener listener(0);
|
||||||
|
ASSERT_NE(INVALID_SOCKET, listener.sock);
|
||||||
|
std::vector<socket_t> backlog;
|
||||||
|
auto close_backlog = detail::scope_exit([&] {
|
||||||
|
for (auto sock : backlog) {
|
||||||
|
detail::close_socket(sock);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
for (int i = 0; i < 8; i++) {
|
||||||
|
auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
|
||||||
|
::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
|
||||||
|
sizeof(listener.addr));
|
||||||
|
backlog.push_back(sock);
|
||||||
|
}
|
||||||
|
|
||||||
|
Client cli("127.0.0.1", listener.port);
|
||||||
|
cli.set_connection_timeout(std::chrono::seconds(3));
|
||||||
|
auto ended =
|
||||||
|
std::async(std::launch::async, [&] { return cli.Get("/").error(); });
|
||||||
|
|
||||||
|
// A stop() before the request starts does not apply to it, so it repeats
|
||||||
|
auto status = std::future_status::timeout;
|
||||||
|
for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
|
||||||
|
cli.stop();
|
||||||
|
status = ended.wait_for(std::chrono::milliseconds(10));
|
||||||
|
}
|
||||||
|
EXPECT_EQ(std::future_status::ready, status);
|
||||||
|
EXPECT_EQ(Error::Canceled, ended.get());
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// The stream holds the socket while it waits for the head, out of the reach
|
||||||
|
// of shutdown()
|
||||||
|
TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
|
||||||
|
SilentListener listener;
|
||||||
|
ASSERT_NE(INVALID_SOCKET, listener.sock);
|
||||||
|
|
||||||
|
Client cli("127.0.0.1", listener.port);
|
||||||
|
cli.set_read_timeout(std::chrono::seconds(3));
|
||||||
|
expect_stop_ends(
|
||||||
|
cli, listener, [&] { return cli.open_stream("GET", "/").error; },
|
||||||
|
Error::Read);
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||||
|
// A server that never answers the ClientHello
|
||||||
|
TEST(ClientStopTest, StopEndsATlsHandshake) {
|
||||||
|
SilentListener listener;
|
||||||
|
ASSERT_NE(INVALID_SOCKET, listener.sock);
|
||||||
|
|
||||||
|
SSLClient cli("127.0.0.1", listener.port);
|
||||||
|
cli.enable_server_certificate_verification(false);
|
||||||
|
cli.set_connection_timeout(std::chrono::seconds(3));
|
||||||
|
expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
|
||||||
|
expect_stop_ends(cli, listener,
|
||||||
|
[&] { return cli.open_stream("GET", "/").error; });
|
||||||
|
}
|
||||||
|
|
||||||
|
// A proxy that takes the CONNECT and never answers it
|
||||||
|
TEST(ClientStopTest, StopEndsAProxyTunnel) {
|
||||||
|
SilentListener listener;
|
||||||
|
ASSERT_NE(INVALID_SOCKET, listener.sock);
|
||||||
|
|
||||||
|
SSLClient cli("example.com", 443);
|
||||||
|
cli.set_proxy("127.0.0.1", listener.port);
|
||||||
|
cli.set_read_timeout(std::chrono::seconds(3));
|
||||||
|
expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// A read timeout past what the clock reaches waits for the response
|
||||||
|
TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
|
||||||
|
SilentListener listener;
|
||||||
|
ASSERT_NE(INVALID_SOCKET, listener.sock);
|
||||||
|
|
||||||
|
Client cli("127.0.0.1", listener.port);
|
||||||
|
cli.set_read_timeout(
|
||||||
|
static_cast<time_t>((std::min)(static_cast<long long>(
|
||||||
|
(std::numeric_limits<time_t>::max)()),
|
||||||
|
10000000000LL)),
|
||||||
|
0);
|
||||||
|
auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
|
||||||
|
|
||||||
|
auto peer = listener.accept();
|
||||||
|
auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
|
||||||
|
ASSERT_NE(INVALID_SOCKET, peer);
|
||||||
|
ASSERT_TRUE(receives_a_byte(peer));
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
||||||
|
std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
|
||||||
|
"Connection: close\r\n\r\nok";
|
||||||
|
detail::send_socket(peer, answer.data(), answer.size(), 0);
|
||||||
|
|
||||||
|
auto result = res.get();
|
||||||
|
ASSERT_TRUE(result);
|
||||||
|
EXPECT_EQ("ok", result->body);
|
||||||
|
}
|
||||||
|
|
||||||
static std::string remove_whitespace(const std::string &input) {
|
static std::string remove_whitespace(const std::string &input) {
|
||||||
std::string output;
|
std::string output;
|
||||||
output.reserve(input.size());
|
output.reserve(input.size());
|
||||||
|
|||||||
Reference in new issue
Block a user