Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
58 changes: 58 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
35 changes: 29 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<thread>`
and then `import std;` fails to link `std::stop_source::request_stop()` (an
Expand All @@ -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 |
Expand All @@ -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
Expand Down Expand Up @@ -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"
```

### 构建
Expand Down
2 changes: 1 addition & 1 deletion mcpp.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
128 changes: 115 additions & 13 deletions src/http.cppm
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::int64_t(std::int64_t offset, std::span<char> 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<BodySource> 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<std::ifstream>(path, std::ios::binary);
if (!*stream) return std::nullopt;
BodySource source;
source.size = static_cast<std::int64_t>(size);
source.read = [stream](std::int64_t offset, std::span<char> out) -> std::int64_t {
stream->clear();
stream->seekg(offset);
if (!*stream) return -1;
stream->read(out.data(), static_cast<std::streamsize>(out.size()));
const auto got = stream->gcount();
return got > 0 ? static_cast<std::int64_t>(got) : -1;
};
return source;
}
};

export struct HttpRequest {
Method method { Method::GET };
std::string url;
std::map<std::string, std::string> headers;
std::string body;
// A body streamed from a source instead of `body`, which must then be empty.
std::optional<BodySource> bodySource;

static HttpRequest post(std::string_view url, std::string_view body) {
return { Method::POST, std::string(url),
Expand Down Expand Up @@ -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;

Expand All @@ -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,
Expand All @@ -470,10 +513,34 @@ static bool write_all(TlsSocket& sock, const std::string& data, int timeoutMs) {
continue;
}
total += static_cast<std::size_t>(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<char> slice(64 * 1024);
std::int64_t offset = 0;
while (offset < source.size) {
const auto want = static_cast<std::size_t>(
source.size - offset < static_cast<std::int64_t>(slice.size())
? source.size - offset : static_cast<std::int64_t>(slice.size()));
const auto got = source.read ? source.read(offset, std::span<char>(slice.data(), want)) : -1;
if (got <= 0 || got > static_cast<std::int64_t>(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<std::size_t>(got)), timeoutMs)) {
return "Write failed";
}
offset += got;
}
return {};
}

// ─────────────────────────────────────────────────────────────────────────────
// One reader, used by all three entry points.
//
Expand Down Expand Up @@ -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);
}

Expand All @@ -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);
Expand All @@ -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;
Expand Down Expand Up @@ -1000,6 +1072,15 @@ private:
bool cancelled { false };
};

static std::optional<HttpResponse> 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";
Expand All @@ -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";
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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;

Expand All @@ -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), {} };
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading