diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1da4c4c..779744b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -368,7 +368,7 @@ jobs: - name: The hermetic tests run: | set -o pipefail - for t in test_framing test_tls_verify test_pool test_proxy test_cancel test_handshake_timeout test_extra_ca; do + for t in test_framing test_tls_verify test_pool test_proxy test_cancel test_handshake_timeout test_extra_ca test_idle_timeout test_body_source; do mcpp test "$t" 2>&1 | tee "$t.log" grep -q "^$t \.\.\. ok" "$t.log" done diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a6300a..402fbb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,63 @@ # Changelog +## 0.3.7 + +A connection that stops moving no longer holds a request, wherever it stops, and +a request body can be streamed from a file or any other source of known length. +It is a patch release, so a dependency written as a caret range, +`tinyhttps = "^0.3.1"`, resolves to it. Everything is added; the one change in +behaviour, a stall inside a TLS record now failing after `readTimeoutMs`, is the +end of a hang rather than a new failure mode. + +### `readTimeoutMs` bounds every `recv` and `send` + +[#28](https://github.com/mcpplibs/tinyhttps/issues/28). The wait before a read +was bounded; the read mbedtls makes to complete a TLS record once its first +bytes have arrived was not. A peer that stopped inside a record, with the +connection open, held `send`, `send_stream` and `download_to_file` for good: with +`readTimeoutMs = 5000` a request was still waiting after 40 s. A write to a peer +that stopped reading did the same. + +* `Socket::set_idle_timeout` bounds each wait before a `recv` or `send` of the + connection; `bio_recv` and `bio_send` wait against it. The client sets it to + `readTimeoutMs` for every exchange, after the connection is open, so inside an + `https://` proxy's tunnel it is the socket at the bottom that carries it. + `TlsSocket` gains `set_idle_timeout` and `idle_timeout_hit`; `Socket` gains + `wait_before_send`, `idle_timeout_hit` and `set_send_timeout`. +* The kernel's send timeout (`SO_SNDTIMEO`) is set to the same value, for the + send that the poll found room for and that then wants more room than was free. +* `write_all` bounds the time without progress instead of the whole write, so a + large body on a slow link is not cut while it is moving. +* A stop token now also ends a write blocked on a peer that is not reading. +* The errors are the existing ones: `Read timed out before the declared length`, + `No response`, `Write failed`. +* `tests/test_idle_timeout.cpp`: a peer that stops inside a record (the head, + the body, a stream, a download), a peer that stops reading, and an upload and + a download that keep moving for several times the bound. Without the bound + the first five wait the full 20 s the peer holds on for. + +### Streaming a request body + +A body had to be a `std::string`, so uploading a file meant holding it in +memory. + +* `BodySource` is a size and a function that reads the bytes at an offset; + `HttpRequest::bodySource` sends it with `Content-Length`, in 64 KiB slices. + `BodySource::file(path)` reads a file. +* The source is read again from offset 0 when the request is sent once more, on + a stale pooled connection or a 307/308 redirect; a 301, 302 or 303 drops it + with the method. +* A source that fails ends the request with `statusCode` 0 and + `Request body source failed at byte N of M`; the server, still owed bytes, has + not acted on it. A request with both `body` and `bodySource` is refused before + anything is sent. +* `tests/test_body_source.cpp` compares the bytes the server received. + +### CI + +* The Windows job runs `test_idle_timeout` and `test_body_source` with the other + hermetic tests. + ## 0.3.6 On Windows every request works again. It is a patch release, so a dependency diff --git a/README.md b/README.md index ad576f0..3ace17b 100644 --- a/README.md +++ b/README.md @@ -66,9 +66,9 @@ is not retried and its redirect is not followed. `download_to_file` reports the same in `DownloadToFileResult::cancelled` and `error`, whether the token or its `isCancelled` callback asked. -It covers connecting, a proxy's handshake, the TLS handshake, waiting for the -response and reading it. Name resolution and a write blocked on a server that is -not reading cannot be interrupted. Without a token nothing changes. +It covers connecting, a proxy's handshake, the TLS handshake, sending the +request, waiting for the response and reading it. Name resolution cannot be +interrupted. Without a token nothing changes. With libc++ 20 or 22, a file that includes a standard header such as `` and then `import std;` fails to link `std::stop_source::request_stop()` (an @@ -80,7 +80,7 @@ includes in that file, or use libc++ 23 or libstdc++. | field | default | what it decides | | --- | --- | --- | | `connectTimeoutMs` | 10000 | setting up the connection: the TCP connect, each wait for a proxy's reply, and the TLS handshake, with the proxy and with the target (the handshake as a whole, not each read in it) | -| `readTimeoutMs` | 60000 | any single read, and the total wait on a blocked write | +| `readTimeoutMs` | 60000 | the time without progress: each `recv` and `send` of a connection, including one inside a TLS record, waits at most this long; a transfer that keeps moving is not cut, however long it takes | | `verifySsl` | true | verify the server certificate against the CA bundle (`SSL_CERT_FILE`, else the Windows `ROOT` certificate store in Windows Sockets builds, else a system location); the connection fails if the certificate is not trusted, has expired or is for another host, or if no bundle is found | | `keepAlive` | true | reuse connections between requests | | `maxRedirects` | 10 | 0 disables redirect following | @@ -89,6 +89,29 @@ includes in that file, or use libc++ 23 or libstdc++. | `extraCaFile` | empty | path of a PEM file of CA certificates to trust in addition to the default store, see below | | `proxy` | none | proxy URL, see below | +### Streaming a request body + +A body that should not be held in memory, such as a file being uploaded, is +given as a `BodySource`: its size, and a function that reads the bytes at an +offset. The request is sent with `Content-Length` and the bytes are read as they +are written. + +```cpp +HttpRequest req; +req.method = Method::POST; +req.url = "https://uploads.example.com/assets?name=big.tar.gz"; +req.headers["Content-Type"] = "application/octet-stream"; +req.bodySource = BodySource::file("dist/big.tar.gz"); // empty if unreadable +auto resp = client.send(req); +``` + +`read(offset, out)` returns how many bytes it put in `out`, or -1. It may be +called again from offset 0 when the request is sent once more, on a stale pooled +connection or a 307/308 redirect. A source that fails ends the request with +`statusCode` 0 and `statusText` `Request body source failed at byte N of M`; the +server, still owed bytes, has not acted on it. A request that sets both `body` +and `bodySource` is refused before anything is sent. + ### Extra CA certificates A private CA, or a proxy that re-signs TLS, is not in the default store, and @@ -214,14 +237,14 @@ Windows). Locally, ### 添加依赖 ```bash -mcpp add tinyhttps@0.3.6 +mcpp add tinyhttps@0.3.7 ``` 或在 `mcpp.toml` 中手动添加: ```toml [dependencies] -tinyhttps = "0.3.6" +tinyhttps = "0.3.7" ``` ### 构建 diff --git a/mcpp.toml b/mcpp.toml index 68a00c2..2160ef4 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -1,7 +1,7 @@ [package] namespace = "mcpplibs" name = "tinyhttps" -version = "0.3.6" +version = "0.3.7" description = "Minimal C++23 HTTP/HTTPS client with SSE streaming support" license = "Apache-2.0" repo = "https://github.com/mcpplibs/tinyhttps" diff --git a/src/http.cppm b/src/http.cppm index 5cbdc73..d8d6293 100644 --- a/src/http.cppm +++ b/src/http.cppm @@ -16,11 +16,49 @@ namespace mcpplibs::tinyhttps { export enum class Method { GET, POST, PUT, DELETE_, PATCH, HEAD }; +// A request body read in pieces rather than held in memory, for an upload of a +// file or of anything else whose length is known before the first byte is sent. +// +// `read` fills `out` with the bytes that start at `offset` and returns how many +// it wrote: more than zero until `size` bytes have been read, and -1 when the +// source cannot be read. It is called with increasing offsets from 0, and again +// from 0 when the request is sent once more (a stale pooled connection, a 307 or +// 308 redirect), which is why it takes an offset instead of keeping a position. +// The body is sent with `Content-Length: size`, never chunked: the platforms +// this library talks to refuse a chunked upload. +export struct BodySource { + std::int64_t size { 0 }; + std::function out)> read; + + // The bytes of a file, read as they are sent. Empty when the file cannot + // be opened; the size is the file's when this is called. + static std::optional file(const std::filesystem::path& path) { + std::error_code ec; + const auto size = std::filesystem::file_size(path, ec); + if (ec) return std::nullopt; + auto stream = std::make_shared(path, std::ios::binary); + if (!*stream) return std::nullopt; + BodySource source; + source.size = static_cast(size); + source.read = [stream](std::int64_t offset, std::span out) -> std::int64_t { + stream->clear(); + stream->seekg(offset); + if (!*stream) return -1; + stream->read(out.data(), static_cast(out.size())); + const auto got = stream->gcount(); + return got > 0 ? static_cast(got) : -1; + }; + return source; + } +}; + export struct HttpRequest { Method method { Method::GET }; std::string url; std::map headers; std::string body; + // A body streamed from a source instead of `body`, which must then be empty. + std::optional bodySource; static HttpRequest post(std::string_view url, std::string_view body) { return { Method::POST, std::string(url), @@ -429,7 +467,8 @@ read_complete_line(TlsSocket& sock, int timeoutMs, bool* sawBytes = nullptr) { return std::unexpected("connection closed before CRLF"); } if (r.status != ReadStatus::Data) { - return std::unexpected("read error before CRLF"); + return std::unexpected(sock.idle_timeout_hit() ? "timed out before CRLF" + : "read error before CRLF"); } if (sawBytes) *sawBytes = true; @@ -452,11 +491,15 @@ read_complete_line(TlsSocket& sock, int timeoutMs, bool* sawBytes = nullptr) { // `TlsSocket::write` reports back-pressure as 0. This used to answer that by // retrying immediately once and giving up if the second attempt also returned 0 // — so a slow peer reached the caller as an unexplained "Write failed". Waiting -// on the socket is what the 0 was asking for; the total wait is bounded by -// `timeoutMs` so a peer that never drains cannot stall the call. -static bool write_all(TlsSocket& sock, const std::string& data, int timeoutMs) { - const auto deadline = std::chrono::steady_clock::now() - + std::chrono::milliseconds(timeoutMs); +// on the socket is what the 0 was asking for. +// +// The bound is on the time without progress, not on the whole write: until 0.3.6 +// `timeoutMs` bounded the whole buffer, so a body that needed longer than that to +// cross a slow link failed while it was still moving (#28). A peer that never +// drains is still bounded, here and by the idle bound on each `send`. +static bool write_all(TlsSocket& sock, std::string_view data, int timeoutMs) { + auto deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(timeoutMs); std::size_t total = 0; while (total < data.size()) { int ret = sock.write(data.data() + total, @@ -470,10 +513,34 @@ static bool write_all(TlsSocket& sock, const std::string& data, int timeoutMs) { continue; } total += static_cast(ret); + deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); } return true; } +// Sends a streamed body in slices. Empty on success, else why it stopped: the +// source failed or ended early (then nothing more is written, and the server, +// still owed bytes, cannot act on the request), or the write failed. +static std::string write_source(TlsSocket& sock, const BodySource& source, int timeoutMs) { + std::vector slice(64 * 1024); + std::int64_t offset = 0; + while (offset < source.size) { + const auto want = static_cast( + source.size - offset < static_cast(slice.size()) + ? source.size - offset : static_cast(slice.size())); + const auto got = source.read ? source.read(offset, std::span(slice.data(), want)) : -1; + if (got <= 0 || got > static_cast(want)) { + return "Request body source failed at byte " + std::to_string(offset) + + " of " + std::to_string(source.size); + } + if (!write_all(sock, std::string_view(slice.data(), static_cast(got)), timeoutMs)) { + return "Write failed"; + } + offset += got; + } + return {}; +} + // ───────────────────────────────────────────────────────────────────────────── // One reader, used by all three entry points. // @@ -909,9 +976,12 @@ public: // `stop` can be stopped from another thread to abandon the request: the // call returns within about 50 ms with `cancelled` set, and the connection - // is closed rather than pooled. It cannot interrupt name resolution or a - // write blocked because the server is not reading. + // is closed rather than pooled. It cannot interrupt name resolution. + // + // A request with both `body` and `bodySource` is refused before anything + // is sent: `statusCode` 0 and a `statusText` that says so. HttpResponse send(const HttpRequest& request, std::stop_token stop = {}) { + if (auto refused = refuse_two_bodies(request)) return *refused; return send_impl(request, 0, stop); } @@ -922,6 +992,7 @@ public: HttpResponse send_stream(const HttpRequest& request, SseCallbackFn callback, std::stop_token stop = {}) { if (stop.stop_requested()) return cancelled_response(); + if (auto refused = refuse_two_bodies(request)) return *refused; HttpResponse response; auto parsed = parse_url(request.url); @@ -935,7 +1006,8 @@ public: PooledConnection guard(pool_, poolKey); auto exchange = perform_exchange(parsed, poolKey, - build_request(request, parsed), guard, stop); + build_request(request, parsed), guard, stop, + request.bodySource ? &*request.bodySource : nullptr); if (!exchange.error.empty()) { response.statusCode = 0; response.statusText = exchange.error; @@ -1000,6 +1072,15 @@ private: bool cancelled { false }; }; + static std::optional refuse_two_bodies(const HttpRequest& request) { + if (!request.bodySource || request.body.empty()) return std::nullopt; + HttpResponse response; + response.statusText = "A request has a body or a body source, not both"; + response.bodyComplete = false; + response.bodyError = response.statusText; + return response; + } + static HttpResponse cancelled_response() { HttpResponse response; response.statusText = "Cancelled"; @@ -1025,7 +1106,11 @@ private: } reqStr += "\r\n"; } - if (!request.body.empty() && !has_header(request.headers, "Content-Length")) { + if (request.bodySource && !has_header(request.headers, "Content-Length")) { + reqStr += "Content-Length: "; + reqStr += std::to_string(request.bodySource->size); + reqStr += "\r\n"; + } else if (!request.body.empty() && !has_header(request.headers, "Content-Length")) { reqStr += "Content-Length: "; reqStr += std::to_string(request.body.size()); reqStr += "\r\n"; @@ -1080,7 +1165,8 @@ private: // only when no response byte has arrived. See `retryOnStaleConnection`. Exchange perform_exchange(const ParsedUrl& parsed, const std::string& poolKey, const std::string& reqStr, PooledConnection& guard, - std::stop_token stop = {}) { + std::stop_token stop = {}, + const BodySource* source = nullptr) { // Drops the connection; a stop request outranks whatever went wrong. auto fail = [&](std::string message) -> Exchange { guard.drop(); @@ -1115,6 +1201,11 @@ private: } } + // Every recv and send of this exchange waits at most this long for + // progress (#28). Set after the connection is open: inside an + // https:// proxy's tunnel the socket at the bottom exists only then. + sock->set_idle_timeout(config_.readTimeoutMs); + const bool mayRetry = reused && attempt == 0 && config_.retryOnStaleConnection; @@ -1129,6 +1220,14 @@ private: if (mayRetry) { guard.reset(); continue; } return fail("Write failed"); } + // A streamed body follows its head. A source that fails is not + // retried: it would fail the same way, and the server, owed bytes, + // has acted on nothing. + if (source != nullptr) { + auto why = write_source(*sock, *source, config_.readTimeoutMs); + if (why == "Write failed" && mayRetry) { guard.reset(); continue; } + if (!why.empty()) return fail(std::move(why)); + } auto head = read_response_head(*sock, config_.readTimeoutMs); if (head) return { sock, std::move(*head), {} }; @@ -1197,7 +1296,8 @@ private: PooledConnection guard(pool_, poolKey); auto exchange = perform_exchange(parsed, poolKey, - build_request(request, parsed), guard, stop); + build_request(request, parsed), guard, stop, + request.bodySource ? &*request.bodySource : nullptr); if (!exchange.error.empty()) { response.statusCode = 0; response.statusText = exchange.error; @@ -1246,6 +1346,7 @@ private: if (response.statusCode != 307 && response.statusCode != 308) { redirectReq.method = Method::GET; redirectReq.body.clear(); + redirectReq.bodySource.reset(); } // Settle before recursing: the inner call may put its own // connection into the pool under this same key, and a guard @@ -1288,7 +1389,8 @@ private: request.headers = { {"User-Agent", "tinyhttps/1.0"}, {"Accept", "*/*"} }; auto exchange = perform_exchange(parsed, poolKey, - build_request(request, parsed), guard, stop); + build_request(request, parsed), guard, stop, + request.bodySource ? &*request.bodySource : nullptr); if (!exchange.error.empty()) { result.error = exchange.error; result.cancelled = exchange.cancelled; diff --git a/src/socket.cppm b/src/socket.cppm index 18264b9..1ac516c 100644 --- a/src/socket.cppm +++ b/src/socket.cppm @@ -15,6 +15,7 @@ module; #pragma comment(lib, "ws2_32.lib") #else #include +#include #include #include #include @@ -55,7 +56,8 @@ public: // Move constructor Socket(Socket&& other) noexcept : fd_(other.fd_), stop_(std::move(other.stop_)), deadline_(other.deadline_) - , deadline_hit_(other.deadline_hit_) { + , deadline_hit_(other.deadline_hit_), idleTimeoutMs_(other.idleTimeoutMs_) + , idle_hit_(other.idle_hit_) { other.fd_ = INVALID_SOCKET_FD; } @@ -67,6 +69,8 @@ public: stop_ = std::move(other.stop_); deadline_ = other.deadline_; deadline_hit_ = other.deadline_hit_; + idleTimeoutMs_ = other.idleTimeoutMs_; + idle_hit_ = other.idle_hit_; other.fd_ = INVALID_SOCKET_FD; } return *this; @@ -82,42 +86,50 @@ public: [[nodiscard]] bool stop_possible() const { return stop_.stop_possible(); } - // Bounds the TLS handshake: until it is cleared, `wait_before_recv` gives up - // once this time has passed. Cleared once the handshake is over. + // Bounds the TLS handshake: until it is cleared, `wait_before_recv` and + // `wait_before_send` give up once this time has passed. Cleared once the + // handshake is over. void set_deadline(std::optional deadline) { deadline_ = deadline; deadline_hit_ = false; } - // True once `wait_before_recv` gave up because of the deadline. + // True once a wait gave up because of the deadline. [[nodiscard]] bool deadline_hit() const { return deadline_hit_; } - // What `bio_recv` calls ahead of a `recv` that would otherwise block. True - // when a `recv` now will not block. With neither a token nor a deadline it - // answers true without waiting, so the plain `recv` is as it was. + // Bounds every `recv` and `send` of the connection: each waits at most + // `timeoutMs` for the socket to become ready, and gives up after that. A + // negative value waits without limit, as before 0.3.7. // - // A wait that ends before the deadline is waited again for what is left: a - // signal ends `poll` with EINTR even under SA_RESTART, which the blocking - // `recv` this wait stands in front of would have restarted. The deadline is - // hit only when the clock says so. - bool wait_before_recv() { - if (!stop_.stop_possible() && !deadline_) return true; - for (;;) { - int wait = -1; - if (deadline_) { - const auto left = std::chrono::ceil( - *deadline_ - std::chrono::steady_clock::now()).count(); - wait = left > 0 ? static_cast(left) : 0; - } - if (wait_readable(wait)) return true; - if (stop_.stop_requested() || !deadline_) return false; - if (std::chrono::steady_clock::now() >= *deadline_) { - deadline_hit_ = true; - return false; - } - } + // WHY EVERY CALL AND NOT ONLY THE WAIT BEFORE A READ. The HTTP reader waits + // with `readTimeoutMs` before it reads, but once the first bytes of a TLS + // record have arrived that wait answers true, and mbedtls completes the + // record through `bio_recv`. A peer that stopped inside the record held that + // `recv` for good (issue #28): with `readTimeoutMs = 5000` a request was still + // waiting after 40 s. A write to a peer that stopped reading held `send` the + // same way. The bound is on each call, so a transfer that keeps moving is + // never cut, however long it takes in total. + void set_idle_timeout(int timeoutMs) { + idleTimeoutMs_ = timeoutMs; + idle_hit_ = false; + set_send_timeout(timeoutMs); } + // True once a wait gave up because the idle bound passed. + [[nodiscard]] bool idle_timeout_hit() const { return idle_hit_; } + + // What `bio_recv` and `bio_send` call ahead of a `recv` or `send` that would + // otherwise block. True when the call now will not block. With no token, no + // deadline and no idle bound they answer true without waiting, so the plain + // call is as it was. + // + // A wait that ends before its end is waited again for what is left: a + // signal ends `poll` with EINTR even under SA_RESTART, which the blocking + // call this wait stands in front of would have restarted. A bound is hit + // only when the clock says so. + bool wait_before_recv() { return wait_before_io(true); } + bool wait_before_send() { return wait_before_io(false); } + bool connect(const char* host, int port, int timeoutMs) { // Winsock first: a socket or getaddrinfo before WSAStartup fails with // WSANOTINITIALISED, which reaches the caller as a bare "Connection failed". @@ -404,6 +416,59 @@ private: std::stop_token stop_; std::optional deadline_; bool deadline_hit_ = false; + int idleTimeoutMs_ = -1; + bool idle_hit_ = false; + + // A send the poll found room for can still block, when the peer stops + // reading part-way through it and the call wants more room than was free: + // poll reports a socket writable once some room is free, not all that a + // record needs. The kernel's own send timeout bounds that one call. A + // runtime that ignores the option leaves the poll as the only bound. + void set_send_timeout(int timeoutMs) { + if (!is_valid()) return; +#ifdef TINYHTTPS_WINSOCK + DWORD ms = timeoutMs > 0 ? static_cast(timeoutMs) : 0; + ::setsockopt(fd_, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast(&ms), sizeof ms); +#else + struct timeval tv {}; + if (timeoutMs > 0) { + tv.tv_sec = timeoutMs / 1000; + tv.tv_usec = (timeoutMs % 1000) * 1000; + } + ::setsockopt(fd_, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv); +#endif + } + + // The wait behind `wait_before_recv` and `wait_before_send`: until the + // socket is ready, a stop is requested, or the nearer of the deadline and + // the idle bound passes. The idle bound starts at the call. + bool wait_before_io(bool forRead) { + using Clock = std::chrono::steady_clock; + if (!stop_.stop_possible() && !deadline_ && idleTimeoutMs_ < 0) return true; + std::optional idleEnd; + if (idleTimeoutMs_ >= 0) idleEnd = Clock::now() + std::chrono::milliseconds(idleTimeoutMs_); + for (;;) { + std::optional end = deadline_; + bool idleIsNearer = false; + if (idleEnd && (!end || *idleEnd < *end)) { + end = idleEnd; + idleIsNearer = true; + } + int wait = -1; + if (end) { + const auto left = std::chrono::ceil( + *end - Clock::now()).count(); + wait = left > 0 ? static_cast(left) : 0; + } + if (wait_fd(fd_, wait, forRead)) return true; + if (stop_.stop_requested() || !end) return false; + if (Clock::now() >= *end) { + if (idleIsNearer) idle_hit_ = true; + else deadline_hit_ = true; + return false; + } + } + } // poll_fd in slices while a token is attached. A negative timeout waits // without limit. Not std::min: defines a `min` macro. diff --git a/src/tls.cppm b/src/tls.cppm index 112e633..6bd0b1d 100644 --- a/src/tls.cppm +++ b/src/tls.cppm @@ -68,6 +68,12 @@ struct TlsState { // BIO callbacks for mbedtls — forward to Socket read/write static int bio_send(void* ctx, const unsigned char* buf, size_t len) { auto* sock = static_cast(ctx); + // With a stop token, a handshake deadline or an idle bound, wait here so + // the send below cannot block past any of them: a peer that stopped reading + // fills the send buffer, and a blocking send then waits for good (#28). + if (!sock->wait_before_send()) { + return MBEDTLS_ERR_NET_SEND_FAILED; + } int ret = sock->write(reinterpret_cast(buf), static_cast(len)); if (ret <= 0) { return MBEDTLS_ERR_NET_SEND_FAILED; @@ -94,8 +100,10 @@ static int bio_send(void* ctx, const unsigned char* buf, size_t len) { // complete and correct. static int bio_recv(void* ctx, unsigned char* buf, size_t len) { auto* sock = static_cast(ctx); - // With a stop token or a handshake deadline, wait here so the recv below - // cannot block past a stop or the deadline. + // With a stop token, a handshake deadline or an idle bound, wait here so + // the recv below cannot block past any of them. This is the read that + // completes a TLS record once its first bytes have arrived, which no wait + // above mbedtls can bound (#28). if (!sock->wait_before_recv()) { return MBEDTLS_ERR_NET_RECV_FAILED; } @@ -209,6 +217,19 @@ public: socket_.set_stop(std::move(stop)); } + // Each `recv` and `send` of the connection waits at most `timeoutMs` for + // progress; negative waits without limit. Like the token, the bound belongs + // to the socket at the bottom, which inside a tunnel is beneath `lower_`. + void set_idle_timeout(int timeoutMs) { + if (lower_) lower_->set_idle_timeout(timeoutMs); + socket_.set_idle_timeout(timeoutMs); + } + + // True once a `recv` or `send` gave up because the idle bound passed. + [[nodiscard]] bool idle_timeout_hit() const { + return lower_ ? lower_->idle_timeout_hit() : socket_.idle_timeout_hit(); + } + // A PEM file of roots to trust in addition to the default store. Call before // connect(); setup fails if the file cannot be read or holds no certificate. void set_extra_ca_file(std::string path) { extraCaFile_ = std::move(path); } diff --git a/tests/test_body_source.cpp b/tests/test_body_source.cpp new file mode 100644 index 0000000..54d800f --- /dev/null +++ b/tests/test_body_source.cpp @@ -0,0 +1,185 @@ +// A request body streamed from a `BodySource` instead of held in `body`. +// +// The server here keeps what it received, so each case compares bytes rather +// than trusting a status: the length the head declared, and the body itself. +#include +#include "tls_test_server.hpp" + +import mcpplibs.tinyhttps; +import std; + +namespace https = mcpplibs::tinyhttps; + +namespace { + +https::HttpClientConfig test_config() { + https::HttpClientConfig cfg; + cfg.verifySsl = false; // the test certificate authenticates nothing + cfg.connectTimeoutMs = 4000; + cfg.readTimeoutMs = 5000; + return cfg; +} + +char byte_at(std::int64_t offset) { return static_cast((offset * 31 + 7) % 251); } + +std::string expected_bytes(std::int64_t size) { + std::string out(static_cast(size), '\0'); + for (std::int64_t i = 0; i < size; ++i) out[static_cast(i)] = byte_at(i); + return out; +} + +// Generated bytes; `failAt` makes every read at or past that offset fail. +https::BodySource generated(std::int64_t size, std::int64_t failAt = -1, + std::atomic* readsFromZero = nullptr) { + https::BodySource source; + source.size = size; + source.read = [failAt, readsFromZero](std::int64_t offset, std::span out) -> std::int64_t { + if (failAt >= 0 && offset >= failAt) return -1; + if (offset == 0 && readsFromZero) ++*readsFromZero; + for (std::size_t i = 0; i < out.size(); ++i) out[i] = byte_at(offset + static_cast(i)); + return static_cast(out.size()); + }; + return source; +} + +https::HttpRequest put(const std::string& url) { + https::HttpRequest req; + req.method = https::Method::PUT; + req.url = url; + req.headers["Content-Type"] = "application/octet-stream"; + return req; +} + +// Answers with the number of body bytes it read and keeps them. +struct Keeper { + std::mutex mutex; + std::vector heads; + std::vector bodies; + + tls_test::Server::Handler handler(bool keepAlive = true) { + return [this, keepAlive](tls_test::Conn& conn, int) { + { + std::lock_guard lock(mutex); + heads.push_back(conn.request()); + bodies.push_back(conn.body()); + } + conn.write(tls_test::ok_response(std::to_string(conn.body().size()))); + return keepAlive; + }; + } +}; + +class BodySourceTest : public ::testing::Test { +protected: + void SetUp() override { https::Socket::platform_init(); } +}; + +} // namespace + +TEST_F(BodySourceTest, AStreamedBodyArrivesWholeWithItsLength) { + constexpr std::int64_t kSize = 5ll * 1024 * 1024 + 3; + Keeper keeper; + tls_test::Server server(keeper.handler()); + ASSERT_FALSE(server.failed()); + + auto req = put(server.url("/upload")); + req.bodySource = generated(kSize); + https::HttpClient client(test_config()); + auto res = client.send(req); + + ASSERT_EQ(res.statusCode, 200) << res.statusText; + EXPECT_EQ(res.body, std::to_string(kSize)); + ASSERT_EQ(keeper.bodies.size(), 1u); + EXPECT_NE(keeper.heads[0].find("Content-Length: " + std::to_string(kSize)), std::string::npos); + EXPECT_TRUE(keeper.bodies[0] == expected_bytes(kSize)) << "the bytes that arrived differ"; +} + +TEST_F(BodySourceTest, AFileIsSentAsItIsRead) { + const auto path = std::filesystem::temp_directory_path() / "tinyhttps-body-source.bin"; + const std::string content = expected_bytes(1024 * 1024 + 17); + { + std::ofstream out(path, std::ios::binary | std::ios::trunc); + out.write(content.data(), static_cast(content.size())); + } + Keeper keeper; + tls_test::Server server(keeper.handler()); + ASSERT_FALSE(server.failed()); + + { + auto source = https::BodySource::file(path); + ASSERT_TRUE(source.has_value()); + EXPECT_EQ(source->size, static_cast(content.size())); + auto req = put(server.url("/upload")); + req.bodySource = std::move(source); + https::HttpClient client(test_config()); + auto res = client.send(req); + + ASSERT_EQ(res.statusCode, 200) << res.statusText; + ASSERT_EQ(keeper.bodies.size(), 1u); + EXPECT_TRUE(keeper.bodies[0] == content) << "the bytes that arrived differ"; + } // the source holds the file open; Windows removes no open file + std::error_code ec; + std::filesystem::remove(path, ec); + EXPECT_FALSE(https::BodySource::file(path.string() + ".missing").has_value()); +} + +// The server is owed bytes when the source fails, so it acts on nothing; the +// client says where the source failed. +TEST_F(BodySourceTest, AFailingSourceEndsTheRequestBeforeTheServerActs) { + constexpr std::int64_t kSize = 4ll * 1024 * 1024; + Keeper keeper; + tls_test::Server server(keeper.handler()); + ASSERT_FALSE(server.failed()); + + auto req = put(server.url("/upload")); + req.bodySource = generated(kSize, 1024 * 1024); + https::HttpClient client(test_config()); + auto res = client.send(req); + + EXPECT_EQ(res.statusCode, 0); + EXPECT_EQ(res.statusText, "Request body source failed at byte 1048576 of 4194304"); + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + EXPECT_EQ(server.requests(), 0); +} + +TEST_F(BodySourceTest, ABodyAndABodySourceTogetherAreRefusedBeforeAnythingIsSent) { + Keeper keeper; + tls_test::Server server(keeper.handler()); + ASSERT_FALSE(server.failed()); + + auto req = put(server.url("/upload")); + req.body = "inline"; + req.bodySource = generated(10); + https::HttpClient client(test_config()); + auto res = client.send(req); + + EXPECT_EQ(res.statusCode, 0); + EXPECT_EQ(res.statusText, "A request has a body or a body source, not both"); + EXPECT_EQ(server.accepts(), 0); +} + +// The first request leaves its connection in the pool and the server closes it +// while idle. The second, a streamed body, is sent again on a fresh connection, +// and the source is read again from the start. +TEST_F(BodySourceTest, AStaleConnectionSendsTheSourceAgainFromTheStart) { + constexpr std::int64_t kSize = 2ll * 1024 * 1024; + Keeper keeper; + tls_test::Server server(keeper.handler(/*keepAlive=*/false)); + ASSERT_FALSE(server.failed()); + + https::HttpClient client(test_config()); + auto first = client.send(put(server.url("/first"))); + ASSERT_EQ(first.statusCode, 200) << first.statusText; + std::this_thread::sleep_for(std::chrono::milliseconds(250)); + + std::atomic readsFromZero { 0 }; + auto req = put(server.url("/second")); + req.bodySource = generated(kSize, -1, &readsFromZero); + auto second = client.send(req); + + ASSERT_EQ(second.statusCode, 200) << second.statusText; + EXPECT_EQ(server.accepts(), 2); + ASSERT_EQ(keeper.bodies.size(), 2u); + EXPECT_TRUE(keeper.bodies[1] == expected_bytes(kSize)) << "the bytes that arrived differ"; + EXPECT_GE(readsFromZero.load(), 1); +} diff --git a/tests/test_idle_timeout.cpp b/tests/test_idle_timeout.cpp new file mode 100644 index 0000000..453c539 --- /dev/null +++ b/tests/test_idle_timeout.cpp @@ -0,0 +1,227 @@ +// `readTimeoutMs` bounds every recv and send of a connection (#28). +// +// The wait before a read was always bounded. What was not is the read mbedtls +// makes to complete a TLS record once its first bytes have arrived, and the +// write to a peer that stopped reading: both went straight to a blocking call. +// Each case below gives the client such a peer, with no stop token, and a +// `readTimeoutMs` of 500 ms; the peer holds the connection open for up to 20 s, +// so a call that is not bounded fails the case by the time it took instead of +// hanging the suite. Before 0.3.7 the first case was still waiting after 40 s +// with a 5 s timeout. +// +// The last two cases are the other half: the bound is on the time without +// progress, so a transfer that keeps moving for longer than `readTimeoutMs` in +// total is not cut. +#include +#include "tls_test_server.hpp" + +import mcpplibs.tinyhttps; +import std; + +namespace https = mcpplibs::tinyhttps; + +namespace { + +using Clock = std::chrono::steady_clock; + +constexpr int kReadTimeoutMs = 500; +// Far above the 500 ms bound, far below the 20 s the peers hold on for. +constexpr long long kPromptMs = 3000; + +https::HttpClientConfig test_config(int readTimeoutMs = kReadTimeoutMs) { + https::HttpClientConfig cfg; + cfg.verifySsl = false; // the test certificate authenticates nothing + cfg.connectTimeoutMs = 4000; + cfg.readTimeoutMs = readTimeoutMs; + return cfg; +} + +https::HttpRequest get(const std::string& url) { + https::HttpRequest req; + req.method = https::Method::GET; + req.url = url; + return req; +} + +long long since_ms(Clock::time_point start) { + return std::chrono::duration_cast(Clock::now() - start).count(); +} + +// The head and the first 4 KiB of a 64 KiB body in whole records, then 100 +// bytes of the next record, and nothing more: the client is inside a record. +bool answer_then_stop_inside_a_record(tls_test::Conn& conn, std::string_view extraHeaders = {}) { + const std::string body(64 * 1024, 'x'); + std::string head = "HTTP/1.1 200 OK\r\nContent-Length: " + std::to_string(body.size()) + "\r\n"; + head += extraHeaders; + head += "\r\n"; + if (!conn.write(head + body.substr(0, 4096))) return false; + if (!conn.write_cut(body.substr(4096, 8192), 100)) return false; + conn.park(); + return false; +} + +// A body read in 64 KiB slices from nowhere: no memory held, any size. +https::BodySource generated(std::int64_t size) { + https::BodySource source; + source.size = size; + source.read = [](std::int64_t offset, std::span out) -> std::int64_t { + for (std::size_t i = 0; i < out.size(); ++i) out[i] = static_cast((offset + static_cast(i)) % 251); + return static_cast(out.size()); + }; + return source; +} + +class IdleTimeoutTest : public ::testing::Test { +protected: + void SetUp() override { https::Socket::platform_init(); } +}; + +} // namespace + +TEST_F(IdleTimeoutTest, SendGivesUpOnAPeerThatStopsInsideABodyRecord) { + tls_test::Server server([](tls_test::Conn& conn, int) { return answer_then_stop_inside_a_record(conn); }); + ASSERT_FALSE(server.failed()); + + https::HttpClient client(test_config()); + const auto start = Clock::now(); + auto res = client.send(get(server.url("/"))); + + EXPECT_EQ(res.statusCode, 200); + EXPECT_FALSE(res.bodyComplete); + EXPECT_EQ(res.bodyError, "Read timed out before the declared length"); + EXPECT_EQ(res.body.size(), 4096u); + EXPECT_LT(since_ms(start), kPromptMs); +} + +TEST_F(IdleTimeoutTest, SendGivesUpOnAPeerThatStopsInsideTheHead) { + tls_test::Server server([](tls_test::Conn& conn, int) { + conn.write_cut(tls_test::ok_response("never complete"), 30); + conn.park(); + return false; + }); + ASSERT_FALSE(server.failed()); + + https::HttpClient client(test_config()); + const auto start = Clock::now(); + auto res = client.send(get(server.url("/"))); + + // What a response that never began has always said, timeout or not. + EXPECT_EQ(res.statusCode, 0); + EXPECT_EQ(res.statusText, "No response"); + EXPECT_LT(since_ms(start), kPromptMs); +} + +TEST_F(IdleTimeoutTest, SendStreamGivesUpOnAPeerThatStopsInsideARecord) { + tls_test::Server server([](tls_test::Conn& conn, int) { + return answer_then_stop_inside_a_record(conn, "Content-Type: text/event-stream\r\n"); + }); + ASSERT_FALSE(server.failed()); + + https::HttpClient client(test_config()); + const auto start = Clock::now(); + auto res = client.send_stream(get(server.url("/")), [](const https::SseEvent&) { return true; }); + + EXPECT_EQ(res.statusCode, 200); + EXPECT_FALSE(res.bodyComplete); + EXPECT_LT(since_ms(start), kPromptMs); +} + +TEST_F(IdleTimeoutTest, DownloadGivesUpOnAPeerThatStopsInsideARecord) { + tls_test::Server server([](tls_test::Conn& conn, int) { return answer_then_stop_inside_a_record(conn); }); + ASSERT_FALSE(server.failed()); + + const auto dest = std::filesystem::temp_directory_path() + / ("tinyhttps-idle-" + std::to_string(server.port()) + ".bin"); + https::HttpClient client(test_config()); + const auto start = Clock::now(); + auto result = client.download_to_file(server.url("/file"), dest); + + EXPECT_FALSE(result.ok()); + EXPECT_FALSE(result.error.empty()); + EXPECT_LT(since_ms(start), kPromptMs); + std::error_code ec; + std::filesystem::remove(dest, ec); +} + +// The peer completes the handshake and never reads: the send buffers fill and +// the next send has nowhere to go. +TEST_F(IdleTimeoutTest, AWriteGivesUpOnAPeerThatStopsReading) { + tls_test::Server server([](tls_test::Conn&, int) { return false; }, + [](tls_test::Conn& conn) { + conn.park(); + return false; + }); + ASSERT_FALSE(server.failed()); + + https::HttpRequest req; + req.method = https::Method::PUT; + req.url = server.url("/upload"); + req.bodySource = generated(256ll * 1024 * 1024); + + https::HttpClient client(test_config()); + const auto start = Clock::now(); + auto res = client.send(req); + + EXPECT_EQ(res.statusCode, 0); + EXPECT_EQ(res.statusText, "Write failed"); + EXPECT_LT(since_ms(start), kPromptMs); +} + +// The other half: the bound is on the time without progress, so a transfer that +// keeps moving for several times the bound in total is not cut. The pace is set +// by sleeps of 10 and 20 ms, which every system honours to within its timer's +// tick (about 16 ms on Windows), far inside the 500 ms bound. + +// An upload whose source yields 64 KiB every 10 ms or more, to a peer that reads +// as fast as it can: 8 MiB take more than 1.2 s. +TEST_F(IdleTimeoutTest, AnUploadThatKeepsMovingIsNotCut) { + constexpr std::int64_t kBody = 8ll * 1024 * 1024; + tls_test::Server server([](tls_test::Conn& conn, int) { + conn.write(tls_test::ok_response(std::to_string(conn.body().size()))); + return false; + }); + ASSERT_FALSE(server.failed()); + + https::HttpRequest req; + req.method = https::Method::PUT; + req.url = server.url("/upload"); + auto source = generated(kBody); + req.bodySource = https::BodySource{source.size, [read = source.read](std::int64_t offset, std::span out) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + return read(offset, out); + }}; + + https::HttpClient client(test_config()); + const auto start = Clock::now(); + auto res = client.send(req); + + EXPECT_EQ(res.statusCode, 200) << res.statusText; + EXPECT_EQ(res.body, std::to_string(kBody)); + EXPECT_GT(since_ms(start), 2 * kReadTimeoutMs); +} + +// A response whose 2 MiB body arrives 32 KiB every 20 ms or more: 1.28 s at +// least, every wait far inside the bound. +TEST_F(IdleTimeoutTest, ADownloadThatKeepsMovingIsNotCut) { + constexpr std::size_t kSlice = 32 * 1024; + constexpr std::size_t kSlices = 64; + tls_test::Server server([](tls_test::Conn& conn, int) { + const std::string slice(kSlice, 'y'); + if (!conn.write("HTTP/1.1 200 OK\r\nContent-Length: " + std::to_string(kSlice * kSlices) + "\r\n\r\n")) return false; + for (std::size_t i = 0; i < kSlices; ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + if (!conn.write(slice)) return false; + } + return false; + }); + ASSERT_FALSE(server.failed()); + + https::HttpClient client(test_config()); + const auto start = Clock::now(); + auto res = client.send(get(server.url("/"))); + + EXPECT_EQ(res.statusCode, 200) << res.statusText; + EXPECT_TRUE(res.bodyComplete) << res.bodyError; + EXPECT_EQ(res.body.size(), kSlice * kSlices); + EXPECT_GT(since_ms(start), 2 * kReadTimeoutMs); +} diff --git a/tests/tls_test_server.hpp b/tests/tls_test_server.hpp index 8017262..8aa9879 100644 --- a/tests/tls_test_server.hpp +++ b/tests/tls_test_server.hpp @@ -212,6 +212,44 @@ class Conn { // answer differently per path. const std::string& request() const { return request_; } + // The body of that request, as many bytes as its Content-Length declared. + const std::string& body() const { return body_; } + + // Encrypts `data` and sends only the first `keep` bytes of what it became, + // so the client holds part of a TLS record and waits for the rest — a peer + // that stopped inside a record, with the connection still open (#28). The + // session cannot be used for anything else afterwards: park or close it. + bool write_cut(std::string_view data, std::size_t keep) { + std::string sealed; + mbedtls_ssl_set_bio(&ssl_, &sealed, +[](void* ctx, const unsigned char* buf, size_t len) -> int { + static_cast(ctx)->append(reinterpret_cast(buf), len); + return static_cast(len); + }, mbedtls_net_recv, nullptr); + const bool sealedAll = write(data); + mbedtls_ssl_set_bio(&ssl_, &net_, mbedtls_net_send, mbedtls_net_recv, nullptr); + if (!sealedAll) return false; + if (keep > sealed.size()) keep = sealed.size(); + std::size_t sent = 0; + while (sent < keep) { + int ret = mbedtls_net_send(&net_, reinterpret_cast(sealed.data() + sent), + keep - sent); + if (ret <= 0) return false; + sent += static_cast(ret); + } + return true; + } + + // Reads up to `len` decrypted bytes of what the client sends; 0 at its end + // or when the server is stopped. For a hook that reads a request its own way. + int read_some(char* buf, std::size_t len) { + for (;;) { + if (!wait_readable()) return 0; + int ret = mbedtls_ssl_read(&ssl_, reinterpret_cast(buf), len); + if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) continue; + return ret > 0 ? ret : 0; + } + } + // Splices what this connection decrypts to 127.0.0.1:`port`, and what comes // back from there into it, until either side ends. This is what makes the // server a proxy for the proxy tests: after it answers a CONNECT, the @@ -251,7 +289,8 @@ class Conn { if (request_.size() > 65536) return false; } std::size_t bodyLen = declared_body_length(request_); - std::string sink; + std::string& sink = body_; + sink.clear(); while (sink.size() < bodyLen) { if (!wait_readable()) return false; unsigned char buf[4096]; @@ -286,6 +325,7 @@ class Conn { mbedtls_net_context net_ {}; mbedtls_ssl_context ssl_ {}; std::string request_; + std::string body_; bool closed_ { false }; }; @@ -296,10 +336,21 @@ class Server { // Return true to serve another request on the same connection. using Handler = std::function; + // Runs once per connection, after the handshake and before the first + // request is read, for a test that reads the request its own way or not at + // all. Return true to go on to `Handler`, false to end the connection. + using AfterHandshake = std::function; + + // Serves `certPem`/`keyPem`, the default pair unless a test needs another. explicit Server(Handler handler, const char* certPem = kCertPem, const char* keyPem = kKeyPem) - : handler_(std::move(handler)), certPem_(certPem), keyPem_(keyPem) { + : Server(std::move(handler), AfterHandshake{}, certPem, keyPem) {} + + Server(Handler handler, AfterHandshake afterHandshake, + const char* certPem = kCertPem, const char* keyPem = kKeyPem) + : handler_(std::move(handler)), afterHandshake_(std::move(afterHandshake)), + certPem_(certPem), keyPem_(keyPem) { mbedtls_net_init(&listener_); // Port 0: the OS picks a free one, which is what lets tests run // concurrently and on a machine where anything might already be bound. @@ -434,6 +485,11 @@ class Server { } } + if (afterHandshake_ && !afterHandshake_(conn)) { + conn.shutdown(); + cleanup(); + return; + } while (!stopping_.load()) { if (!conn.read_request()) break; const int index = requests_.fetch_add(1); @@ -444,6 +500,7 @@ class Server { } Handler handler_; + AfterHandshake afterHandshake_; const char* certPem_; const char* keyPem_; mbedtls_net_context listener_ {};