Compare commits

...
23 Commits
Author SHA1 Message Date
yhirose c419c904da Release v0.61.0 2026-10-13 22:56:02 -04:00
yhirose 878ba41099 Wait for the reconnect in the SSE retry test instead of sleeping
SSEIntegrationTest.DigitRetryFieldApplied slept for 500ms and then
expected a second connection. The first connection, the 100ms wait and
the reconnect do not always fit in that window: the macOS Mbed TLS job
saw only one connection.

Wait until the second connection arrives, and check that it came at
least 100ms after the first one rather than counting connections. The
test no longer depends on how fast the runner is, and takes about 150ms
instead of 500ms.
2026-10-13 09:07:56 -04:00
yhirose 941745c33d Send proxy Basic authentication when one credential is empty
Proxy-Authorization was added only when both the proxy username and the
proxy password were set, and a cross-host redirect carried the proxy
credentials over only when the username was set. Authorization has been
sent when either one is set since #958; do the same for the proxy.

A client that has both a proxy Basic credential with one empty field
and a proxy bearer token now sends Basic rather than Bearer, the order
Authorization already follows.
2026-10-12 22:59:55 -04:00
yhirose 11daa99c86 Stop at the last match when getting a value by index
get_header_value(), get_header_value_u64(), get_multimap_value() and
MultipartFormData::get_field() advanced an equal_range() iterator by
the caller's index after casting it to ssize_t. An index that is
negative as a signed value stepped back onto an entry of another key,
and a huge positive one kept looping after the last match.

Advance with bounded_next(), which stops at the end of the range.
2026-10-12 22:59:55 -04:00
yhirose cbaf751da1 Ignore quoted-strings when parsing an Accept header
parse_accept_header() split on every ',' and then on every ';', with no
idea that a parameter value can be a quoted-string (RFC 9110 §5.6.6). A
value such as text/html;profile="a,b" was cut in the middle, and the
request was answered with 400.

The parser never looks at a parameter value, so remove each
quoted-string (§5.6.4) before parsing rather than teach every split
about quotes. A header without a '"' takes the same path as before.

A quoted-string is removed wherever it appears, so a malformed value
can now be read without it instead of being rejected, and an
unterminated quote hides the rest of the value.
2026-10-12 22:59:47 -04:00
yhirose 33d84a12b6 Compare the Range unit case-insensitively
RFC 9110 §14.1 makes range unit names case-insensitive, but
parse_range_header() matched "bytes=" exactly, so a request with
Range: Bytes=1-3 was answered with 416.
2026-10-12 19:37:07 -04:00
yhirose 5107381963 Fix the RFC reference in the Host validation test
The rule that a client sends an empty Host value when the target URI
has no authority is in RFC 9112 §3.2, not RFC 9110 §7.2.
2026-10-11 23:44:07 -04:00
yhirose 0acbee16dc Reject an ambiguous or invalid Host in a request
A request with more than one Host field line, or with a Host value
holding a byte that cannot appear in uri-host [ ":" port ], is now
answered with 400 (RFC 9112 §3.2). The handler sees only the first
Host line, so such a request could reach it with an authority that
differs from the one an intermediary acted on.

Only the byte set is checked, not the full grammar. An empty value
stays valid, and a request without a Host line is still accepted.

Close #2623
2026-10-11 23:39:50 -04:00
yhirose 1f12bbaabb Treat a bare CR as an SSE line ending
The SSE spec ends a line with CRLF, LF or CR, but SSEClient split only
on LF, so a stream that uses CR alone never produced an event. The LF
of a CRLF is skipped even when it arrives in a later chunk than its CR.

Search for a line ending only in the newly received data. What is left
in the buffer has none, and scanning it again for every chunk made a
long line quadratic.
2026-10-11 23:05:46 -04:00
yhirose 5189edc52e Ignore an SSE id that cannot be sent as Last-Event-ID
SSEClient stored any id it received, but the client rejects a request
whose header value is invalid. An id with a NUL, a control character or
surrounding whitespace therefore made every reconnect fail with
Error::InvalidHeaders before reaching the server, and the id could
never be replaced.

Accept an id only if it is a valid header value, so that the previous
id stays in effect. The SSE spec asks for this for NUL only; the rest
follows from what this client can send.
2026-10-11 23:05:38 -04:00
yhirose fee592c2c2 Ignore a leading UTF-8 BOM in an SSE stream
The SSE spec strips one BOM at the start of the stream, but
SSEClient kept it as part of the first field name, so the
first event was silently dropped.
2026-10-08 21:07:40 -04:00
yhirose 885ed54b10 Unify spacing and wording in the Japanese docs pages
Drop the spaces between Japanese text and inline code or alphanumerics
in the tour and the few other pages that still had them, and reword
sentences that read awkwardly. The client compression page now lists
Zstd alongside zlib and Brotli.
2026-10-08 20:39:13 -04:00
yhirose c95d799180 Polish the wording of the updated docs pages
Reword the Japanese sentences so they read naturally, and correct the
size of the llama.cpp server sources in the code reading chapter.
2026-10-08 20:39:13 -04:00
yhirose bef278e0d2 Fix docs pages that no longer match the code
Samples that did not compile or run as shown:
- res.user_data.get<T>() inside a generic lambda needs the `template`
  keyword; use explicit parameter types (tour 09, cookbook s15).
- listen() on a Unix domain socket fails with port 0 (tour 09, s22).
- "*.dev.local" is not a NO_PROXY pattern (c16).
- ssl_backend_error() holds a verify result, not an ERR_get_error()
  value, after a verification failure; decode each with the matching
  OpenSSL function (c18).
- The content provider's `length` is everything that remains, so the
  sample read the whole file in one call (s05).

Statements corrected:
- Client keep-alive is off by default; c14 is rewritten around
  set_keep_alive(true).
- Mounted files are looked up before GET handlers (tour 04, s04).
- Params keep insertion order, and to_string(Error::Connection) reads
  "Could not establish connection" (tour 02).
- A chunked provider ends with sink.done(), and post_routing_handler
  runs before the response is sent (tour 09).
- Timeouts surface as Error::Read; Error::Timeout comes from the stream
  API (c17). The max timeout cuts off the wait for the response only
  (c13). The progress callback needs Content-Length (c11).
- Encoding selection follows q-values, then Brotli, gzip, Zstd (s08),
  and the client compresses with the first of those it was built with
  (c15).
- stop() cuts a provider-driven response short (s19); a rejected
  content_reader already gets 400 or 413 (s07); user_data values must be
  copyable (s12); Client accepts a client certificate too (t04);
  on_message() is the fallback for every unhandled event and 204/403/404
  end reconnection (e04); the pong timeout takes two to three intervals
  and ends a waiting read() (w02).

In the LLM app tutorial, an uncaught exception does not crash the
server, so say what it does instead. Drop the server and client timeout
settings whose stated purpose, covering inference and download time,
they do not serve: those timeouts bound a single socket wait. Update
the llama.cpp server layout in chapter 7.
2026-10-08 20:39:13 -04:00
yhirose 05f7478523 Fix README samples and statements that no longer match the code
Samples that did not compile or did not do what they showed:
- SSLServer has no default constructor, and SSLClient("host:port") does
  not parse the port.
- res.user_data.get<T>() inside a generic lambda needs the `template`
  keyword; use explicit parameter types instead.
- get_header_value() takes the default value before the index.
- Server has no socket(); show set_socket_opt inside set_socket_options.
- The content provider sample used a local without capturing it.
- "*.dev.local" is not a NO_PROXY pattern; ".dev.local" is.
- The reverse proxy example in README-stream.md called open_stream()
  without a method and moved a StreamHandle into a std::function. Keep
  the client and the handle in one shared object.
- open_stream() does not follow redirects, so drop set_follow_location()
  from the Stream API samples.

Statements corrected:
- ssl_error() returns a tls::ErrorCode, not SSL_ERROR_*.
- An exception escaping the exception handler no longer crashes the
  server; the connection is dropped and the error logger is told.
- post_routing_handler runs before every response, including those the
  earlier hooks short-circuit; file_request_handler runs for GET only.
- Only wolfSSL cannot enumerate CAs loaded from a path or the system.
- Digest authentication and the WebSocket TLS setters need any TLS
  backend, not OpenSSL specifically.
- A dynamic pool thread exits on the idle timeout only.
- The stream connection closes when the Result is destroyed.
- The pong timeout takes two to three ping intervals to fire.
- Regex routes skip paths over CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH.

Also list the Error values and compressible MIME types that were
missing, note that a content receiver lifts the default client payload
limit, and update the docker server's startup output.
2026-10-08 20:39:13 -04:00
yhirose f6aee694e2 Log the response length for static files in the docker server
The access log took $body_bytes_sent from res.body, which stays empty
for a static file because it is sent by a content provider. Every file
was logged as 0 bytes. Use the Content-Length of the response instead,
and 0 for HEAD.
2026-10-08 20:39:13 -04:00
yhirose 8aa547e4a1 Wake a blocked WebSocket read when the pong timeout fires
When max_missed_pongs was exceeded, the heartbeat thread called close(),
which returns without touching the socket while another thread is in
read(). That read() then stayed blocked until its read timeout: forever
by default on a client, 300 seconds on a server. A plain read loop never
noticed the unresponsive peer the heartbeat had just detected.

Shut down the read side of the socket after close() so the pending
read() returns Fail. Only the read side: a TLS backend answers the EOF
with an alert, and writing it to a socket closed for writing raises
SIGPIPE in a process that has not ignored it.

ClientDetectsNonResponsivePeer now waits in read() instead of polling
is_open(), which covers both.
2026-10-08 20:39:13 -04:00
yhirose 84ff13ec47 Treat a payload max length of 0 as unlimited on every read path
set_payload_max_length(0) is documented to disable the limit, but the
readers for a chunked body and for a body delimited by the connection
closing compared the size against the limit without checking for 0.
A server configured that way answered a chunked request with 413, and
a client failed to read a chunked or unframed response. A body with
Content-Length was already unlimited.

Give both readers the same `payload_max_length > 0` guard the other
payload checks use.
2026-10-08 20:39:13 -04:00
metsw24-maxandyhirose 8f094fe292 match a wildcard only in the leftmost label in match_hostname (#2619)
* match a wildcard only in the leftmost label in match_hostname

* Shorten the wildcard comment in match_hostname

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-10-08 12:47:24 -04:00
yhirose 00afaaed6a Release v0.60.1 2026-10-07 23:40:36 -04:00
yhirose e803f5e413 Let the SSL chain policy alone judge the Windows chain (#2618)
verify_cert_with_windows_schannel() rejected a chain whenever
TrustStatus.dwErrorStatus was non-zero, before
CertVerifyCertificateChainPolicy() ran. The
CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS flag passed to that
policy check was therefore dead code: a certificate without revocation
information, or one whose CRL could not be fetched, failed with
CERT_TRUST_REVOCATION_STATUS_UNKNOWN.

Drop the pre-check so the SSL chain policy is the only judge.
Revocation checking becomes best-effort: a revoked certificate and
every other chain error are still rejected, while an undetermined
revocation status is accepted.

On a rejected chain, ssl_backend_error() now holds the policy status,
such as CERT_E_UNTRUSTEDROOT, instead of the trust status bit mask.
2026-10-07 23:19:36 -04:00
Michael Weitzel 57b8aca6da Avoid name clash with class WebSocketClient by explicit qualification (#2616)
Adds an explicit namespace qualification and a forward declaration for
class WebSocketClient. This change avoids a name clash on code bases
containing unrelated WebSocketClient classes.
2026-10-07 22:38:50 -04:00
KBSandyoudie006 213029685a Serve the whole body for a suffix range longer than it (#2615)
RFC 9110 14.1.2: if the representation is shorter than the suffix-length,
the entire representation is used. range_error computed a negative first
byte position for bytes=-8 on a 7-byte body and answered 416. Clamp it
at 0, as #711 did before the range handling was reworked.

Co-authored-by: youdie006 <youdie006@users.noreply.github.com>
2026-10-07 22:20:53 -04:00
76 changed files with 829 additions and 404 deletions

No files matched your search

+16 -11
View File
@@ -4,7 +4,7 @@ This document describes the streaming extensions for cpp-httplib, providing an i
> **Important Notes**:
>
> - **No Keep-Alive**: Each `stream::Get()` call uses a dedicated connection that is closed after the response is fully read. For connection reuse, use `Client::Get()`.
> - **No Keep-Alive**: Each `stream::Get()` call uses a dedicated connection that is closed when the returned `stream::Result` is destroyed. For connection reuse, use `Client::Get()`.
> - **Single iteration only**: The `next()` method can only iterate through the body once.
> - **Result is not thread-safe**: While `stream::Get()` can be called from multiple threads simultaneously, the returned `stream::Result` must be used from a single thread only.
@@ -114,7 +114,6 @@ The `httplib.h` header provides a more ergonomic iterator-style API.
#include "httplib.h"
httplib::Client cli("http://localhost:8080");
cli.set_follow_location(true);
...
// Simple GET
@@ -243,23 +242,29 @@ int main() {
```cpp
#include "httplib.h"
// Keeps the client and its stream alive until the response has been sent.
struct Upstream {
httplib::Client cli{"http://backend:8080"};
httplib::ClientImpl::StreamHandle handle;
};
httplib::Server svr;
svr.Get("/proxy/(.*)", [](const httplib::Request& req, httplib::Response& res) {
httplib::Client upstream("http://backend:8080");
auto handle = upstream.open_stream("/" + req.matches[1].str());
if (!handle.is_valid()) {
auto upstream = std::make_shared<Upstream>();
upstream->handle = upstream->cli.open_stream("GET", "/" + req.matches[1].str());
if (!upstream->handle.is_valid()) {
res.status = 502;
return;
}
res.status = handle.response->status;
res.status = upstream->handle.response->status;
res.set_chunked_content_provider(
handle.response->get_header_value("Content-Type"),
[handle = std::move(handle)](size_t, httplib::DataSink& sink) mutable {
upstream->handle.response->get_header_value("Content-Type"),
[upstream](size_t, httplib::DataSink& sink) {
char buf[8192];
auto n = handle.read(buf, sizeof(buf));
auto n = upstream->handle.read(buf, sizeof(buf));
if (n > 0) {
sink.write(buf, static_cast<size_t>(n));
return true;
+4 -5
View File
@@ -151,9 +151,8 @@ bool is_open() const;
explicit WebSocketClient(const std::string &scheme_host_port_path,
const Headers &headers = {});
// Constructor with a client certificate for mutual TLS (wss:// only,
// requires CPPHTTPLIB_OPENSSL_SUPPORT). The certificate is ignored for
// ws:// URLs.
// Constructor with a client certificate for mutual TLS (wss:// only, SSL
// builds only). The certificate is ignored for ws:// URLs.
struct PemMemory {
const char *cert_pem;
size_t cert_pem_len;
@@ -199,7 +198,7 @@ void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
template <class Rep, class Period>
void set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
// SSL configuration (wss:// only, requires CPPHTTPLIB_OPENSSL_SUPPORT)
// SSL configuration (wss:// only, SSL builds only)
void set_ca_cert_path(const std::string &ca_cert_file_path,
const std::string &ca_cert_dir_path = std::string());
void set_ca_cert_store(tls::ca_store_t store);
@@ -473,7 +472,7 @@ ws.set_websocket_max_missed_pongs(2); // close after 2 consecutive unacked pings
The server side has the same `set_websocket_max_missed_pongs()`.
With the default ping interval of 30 seconds, `max_missed_pongs = 2` detects a dead peer within ~60 seconds. The counter is reset every time a Pong frame is received, so the mechanism only works when your code is actively calling `read()` — exactly the pattern a normal WebSocket client already uses.
With the default ping interval of 30 seconds, `max_missed_pongs = 2` detects a dead peer 60 to 90 seconds after it stops answering: the count is checked once per interval, just before the next ping goes out. A `read()` waiting on the peer at that moment returns `Fail`. The counter is reset every time a Pong frame is received, so the mechanism only works when your code is actively calling `read()`, which is exactly the pattern a normal WebSocket client already uses.
**The default is `0`**, which means "never close the connection because of missing pongs." Pings are still sent on the heartbeat interval, but their responses are not checked. On the server side a dead connection still does not linger: while a handler is inside `read()`, `CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND` (default **300 seconds = 5 minutes**) acts as a backstop. A client has no such backstop — it waits forever unless you set a read timeout — so there `max_missed_pongs` is what notices an unresponsive peer at all. On either side it is also the knob for noticing one *faster* than the 5-minute fallback.
+47 -41
View File
@@ -33,7 +33,7 @@ Learn more in the [official documentation](https://yhirose.github.io/cpp-httplib
httplib::Server svr;
// HTTPS
httplib::SSLServer svr;
httplib::SSLServer svr("./cert.pem", "./key.pem");
svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
res.set_content("Hello World!", "text/plain");
@@ -71,7 +71,7 @@ cpp-httplib supports multiple TLS backends through an abstraction layer:
| wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` | 5.x supported; must build with `--enable-opensslall` |
> [!NOTE]
> **Mbed TLS / wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable.
> **wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable.
> [!NOTE]
> **BoringSSL (best-effort):** BoringSSL builds under `CPPHTTPLIB_OPENSSL_SUPPORT` and is exercised by CI against current upstream. Because BoringSSL does not guarantee API stability, support is best-effort — breakage may occasionally land. Two known behavioral differences vs OpenSSL: (1) BoringSSL's public headers require C++14 or later, so consumers must compile accordingly; (2) hostname verification is SAN-only per RFC 6125 §6.4.4 (no CN fallback).
@@ -86,7 +86,7 @@ httplib::SSLServer svr("./cert.pem", "./key.pem");
// Client
httplib::Client cli("https://localhost:1234"); // scheme + host
httplib::SSLClient cli("localhost:1234"); // host
httplib::SSLClient cli("localhost"); // host (port 443)
httplib::SSLClient cli("localhost", 1234); // host, port
// Use your CA bundle
@@ -103,8 +103,8 @@ cli.enable_server_hostname_verification(false);
When SSL operations fail, cpp-httplib provides detailed error information through `ssl_error()` and `ssl_backend_error()`:
- `ssl_error()` - Returns the TLS-level error code (e.g., `SSL_ERROR_SSL` for OpenSSL)
- `ssl_backend_error()` - Returns the backend-specific error code (e.g., `ERR_get_error()` for OpenSSL/wolfSSL, return value for Mbed TLS)
- `ssl_error()` - Returns the TLS-level error as a backend-independent `httplib::tls::ErrorCode` value (e.g., `Fatal`, `CertVerifyFailed`), cast to `int`
- `ssl_backend_error()` - Returns the backend-specific error code (e.g., `ERR_get_error()` for OpenSSL/wolfSSL, return value for Mbed TLS). With OpenSSL, a certificate verification failure reports the verify result (`X509_V_ERR_*`) here instead
```c++
#define CPPHTTPLIB_OPENSSL_SUPPORT // or CPPHTTPLIB_MBEDTLS_SUPPORT or CPPHTTPLIB_WOLFSSL_SUPPORT
@@ -230,7 +230,7 @@ cpp-httplib automatically integrates with the OS certificate store on macOS and
| Platform | Behavior | Disable (compile time) |
| :------- | :------- | :--------------------- |
| macOS | Loads system certs from Keychain (link `CoreFoundation` and `Security` with `-framework`). Requires Apple Clang; GCC is not supported for this feature. | `CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES` |
| Windows | Verifies the certificate chain with CryptoAPI (`CertGetCertificateChain` / `CertVerifyCertificateChainPolicy`) instead of the TLS backend, with revocation checking. Windows fetches missing roots and intermediates on demand. With a custom CA, the TLS backend verifies the chain instead; with `set_server_certificate_verifier()`, both do. | `CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE` |
| Windows | Verifies the certificate chain with CryptoAPI (`CertGetCertificateChain` / `CertVerifyCertificateChainPolicy`) instead of the TLS backend. Revocation checking is best-effort: a revoked server certificate is rejected, while one whose revocation status cannot be determined is accepted. Windows fetches missing roots and intermediates on demand. With a custom CA, the TLS backend verifies the chain instead; with `set_server_certificate_verifier()`, both do. | `CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE` |
On Windows, verification can also be disabled at runtime:
@@ -337,7 +337,7 @@ Note the following:
* The method name must be a valid HTTP method token (RFC 9110) and must be registered before `listen()` is called.
* `GET`, `HEAD`, `POST`, `PUT`, `DELETE`, `CONNECT`, `OPTIONS`, `TRACE`, `PATCH` and `PRI` cannot be registered this way. Use the dedicated methods above instead.
* A rejected registration makes `is_valid()` return `false`, and `listen()` then fails rather than starting a server with a route that would never fire.
* Static file serving and WebSocket upgrades remain `GET`/`HEAD` only.
* Static file serving remains `GET`/`HEAD` only, and WebSocket upgrades `GET` only.
* `Allow` and the WebDAV `DAV:` header are not generated automatically. Register an `Options` handler if clients need them.
### Bind a socket to multiple interfaces and any available port
@@ -518,7 +518,7 @@ svr.set_exception_handler([](const auto& req, auto& res, std::exception_ptr ep)
```
> [!CAUTION]
> if you don't provide the `catch (...)` block for a rethrown exception pointer, an uncaught exception will end up causing the server crash. Be careful!
> If you don't provide the `catch (...)` block for a rethrown exception pointer, an exception that is not a `std::exception` escapes the handler. The server keeps running, but that connection is dropped without a response, and the error logger receives `Error::UserCallbackException`.
### Pre routing handler
@@ -569,21 +569,21 @@ svr.set_pre_request_handler([](const auto& req, auto& res) {
Request received
│
├─ expect_100_continue_handler (when the request has "Expect: 100-continue")
│ └─ returns a status other than 100 → stop here
│ └─ returns a status other than 100 → go straight to post_routing_handler
│
├─ pre_routing_handler route not matched yet, body not read
│ └─ returns Handled → stop here
│ └─ returns Handled → go straight to post_routing_handler
│
├─ file_request_handler (GET/HEAD, static file serving)
├─ file_request_handler when a static file is served (GET only)
│
├─ route matching → req.matched_route is set
│
├─ pre_request_handler route matched, body NOT read yet
│ └─ returns Handled → stop here (route handler is skipped)
│ └─ returns Handled → go straight to post_routing_handler
│
├─ route handler Get/Post/...; the request body is read first
│
└─ post_routing_handler after routing completes
└─ post_routing_handler just before the response is written
On a thrown exception → exception_handler
On an error status (4xx/5xx) → error_handler
@@ -611,7 +611,7 @@ svr.set_pre_routing_handler([](const auto& req, auto& res) {
return Server::HandlerResponse::Unhandled;
});
svr.Get("/me", [](const auto& /*req*/, auto& res) {
svr.Get("/me", [](const Request& /*req*/, Response& res) {
auto* ctx = res.user_data.get<AuthContext>("auth");
if (!ctx) {
res.status = StatusCode::Unauthorized_401;
@@ -908,7 +908,7 @@ Please see [Server example](https://github.com/yhirose/cpp-httplib/blob/master/e
`ThreadPool` is used as the **default** task queue, with dynamic scaling support. By default, it maintains a base thread count of 8 or `std::thread::hardware_concurrency() - 1` (whichever is greater), and can scale up to 4x that count under load. You can change these with `CPPHTTPLIB_THREAD_POOL_COUNT` and `CPPHTTPLIB_THREAD_POOL_MAX_COUNT`.
When all threads are busy and a new task arrives, a temporary thread is spawned (up to the maximum). When a dynamic thread finishes its task and the queue is empty, or after an idle timeout, it exits automatically. The idle timeout defaults to 3 seconds, configurable via `CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT`.
When all threads are busy and a new task arrives, a temporary thread is spawned (up to the maximum). A dynamic thread exits automatically once it has waited for the idle timeout without receiving a task. The idle timeout defaults to 3 seconds, configurable via `CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT`.
If you want to set the thread counts at runtime:
@@ -1042,6 +1042,8 @@ enum class Error {
HTTPParsing,
InvalidRangeHeader,
UnsupportedContentEncoding,
WebSocketHandshake,
UserCallbackException,
};
```
@@ -1257,7 +1259,7 @@ std::string body = ...;
auto res = cli.Post(
"/stream", body.size(),
[](size_t offset, size_t length, DataSink &sink) {
[&](size_t offset, size_t length, DataSink &sink) {
sink.write(body.data() + offset, length);
return true; // return 'false' if you want to cancel the request.
},
@@ -1310,7 +1312,7 @@ cli.set_bearer_token_auth("token");
```
> [!NOTE]
> OpenSSL is required for Digest Authentication.
> A TLS backend (OpenSSL, Mbed TLS, or wolfSSL) is required for Digest Authentication.
### Proxy server support
@@ -1328,12 +1330,12 @@ cli.set_proxy_bearer_token_auth("pass");
```
> [!NOTE]
> OpenSSL is required for Digest Authentication.
> A TLS backend (OpenSSL, Mbed TLS, or wolfSSL) is required for Digest Authentication.
#### Bypass the proxy for specific hosts (`NO_PROXY`)
```cpp
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", "*.dev.local"});
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", ".dev.local"});
```
Each pattern is `*`, a hostname suffix, an IP literal, or a CIDR block.
@@ -1478,8 +1480,8 @@ for (auto it = req.headers.equal_range("Accept-Encoding").first;
std::cout << it->second << std::endl;
}
// get_header_value(key, id) reaches a specific one directly.
auto second = req.get_header_value("Accept-Encoding", 1); // "br"
// get_header_value(key, def, id) reaches a specific one directly.
auto second = req.get_header_value("Accept-Encoding", "", 1); // "br"
```
`Headers` matches field names case-insensitively, as before. `Params`, `FormFields`, and `FormFiles` are case-sensitive.
@@ -1489,7 +1491,7 @@ auto second = req.get_header_value("Accept-Encoding", 1); // "br"
## Payload Limit
The maximum payload body size is limited to 100MB by default for both server and client. You can change it with `set_payload_max_length()` or by defining `CPPHTTPLIB_PAYLOAD_MAX_LENGTH` at compile time. Setting it to `0` disables the limit entirely.
The maximum payload body size is limited to 100MB by default for both server and client. You can change it with `set_payload_max_length()` or by defining `CPPHTTPLIB_PAYLOAD_MAX_LENGTH` at compile time. Setting it to `0` disables the limit entirely. On the client, a request made with a content receiver is not limited unless you call `set_payload_max_length()` yourself, so that a large download can be streamed without raising the limit first.
## Compression
@@ -1498,10 +1500,15 @@ The server can apply compression to the following MIME type contents:
- all text types except text/event-stream
- image/svg+xml
- application/javascript
- application/x-javascript
- application/json
- application/ld+json
- application/xml
- application/protobuf
- application/xhtml+xml
- application/rss+xml
- application/atom+xml
- application/xslt+xml
- application/protobuf
A response that already carries `Content-Encoding` is sent as it is. A handler serving content it encoded itself, an asset compressed at build time for instance, keeps its own coding and its own bytes:
@@ -1638,7 +1645,6 @@ Process large responses without loading everything into memory.
```c++
httplib::Client cli("localhost", 8080);
cli.set_follow_location(true);
...
auto result = httplib::stream::Get(cli, "/large-file");
@@ -1718,7 +1724,7 @@ SSL is also supported via `wss://` scheme (e.g. `WebSocketClient("wss://example.
> **WebSocket extensions are not supported.** `permessage-deflate` and other RFC 6455 extensions are not implemented. If a client proposes them via `Sec-WebSocket-Extensions`, the server silently declines them in its handshake response.
> **Unresponsive-peer detection.** Heartbeat pings also serve as a liveness probe when `set_websocket_max_missed_pongs(n)` is set: if the client sends `n` consecutive pings without receiving a pong, it will close the connection. Disabled by default (`0`).
> **Unresponsive-peer detection.** Heartbeat pings also serve as a liveness probe when `set_websocket_max_missed_pongs(n)` is set: once `n` consecutive pings have gone unanswered, the connection is closed and a `read()` waiting on it fails. Both `WebSocketClient` and `Server` have the setter. Disabled by default (`0`).
See [README-websocket.md](README-websocket.md) for more details.
@@ -1727,12 +1733,14 @@ See [README-websocket.md](README-websocket.md) for more details.
`set_socket_opt` is a convenience wrapper around `setsockopt` for setting integer socket options:
```cpp
auto sock = svr.socket();
httplib::set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1);
svr.set_socket_options([](socket_t sock) {
httplib::default_socket_options(sock);
httplib::set_socket_opt(sock, SOL_SOCKET, SO_KEEPALIVE, 1);
});
```
> [!TIP]
> For most use cases, prefer `set_tcp_nodelay(true)` or `set_socket_options(callback)` on the Server/Client instead of calling `set_socket_opt` directly.
> `set_socket_options` replaces the default socket options, so call `default_socket_options()` in the callback to keep them. For `TCP_NODELAY`, `set_tcp_nodelay(true)` is simpler.
## Split httplib.h into .h and .cc
@@ -1761,7 +1769,9 @@ Dockerfile for static HTTP server is available. Port number of this HTTP server
...
> docker run --rm -it -p 8080:80 -v ./docker/html:/html cpp-httplib-server
Serving HTTP on 0.0.0.0 port 80 ...
Serving HTTP on 0.0.0.0:80
Mount point: / -> ./html
Press Ctrl+C to shutdown gracefully...
192.168.65.1 - - [31/Aug/2024:21:33:56 +0000] "GET / HTTP/1.1" 200 599 "-" "curl/8.7.1"
192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET / HTTP/1.1" 200 599 "-" "Mozilla/5.0 ..."
192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
@@ -1771,7 +1781,9 @@ From Docker Hub
```bash
> docker run --rm -it -p 8080:80 -v ./docker/html:/html yhirose4dockerhub/cpp-httplib-server
Serving HTTP on 0.0.0.0 port 80 ...
Serving HTTP on 0.0.0.0:80
Mount point: / -> ./html
Press Ctrl+C to shutdown gracefully...
192.168.65.1 - - [31/Aug/2024:21:33:56 +0000] "GET / HTTP/1.1" 200 599 "-" "curl/8.7.1"
192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET / HTTP/1.1" 200 599 "-" "Mozilla/5.0 ..."
192.168.65.1 - - [31/Aug/2024:21:34:26 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
@@ -1783,19 +1795,13 @@ NOTE
### Regular Expression Stack Overflow
> [!CAUTION]
> When using complex regex patterns in route handlers, be aware that certain patterns may cause stack overflow during pattern matching. This is a known issue with `std::regex` implementations and affects the `dispatch_request()` method.
>
> `std::regex` implementations can overflow the stack while matching a long input, even with a pattern as simple as `.*`. To keep a request from triggering this, a regex route is never applied to a path longer than `CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH` (256 by default); such a path does not match the route. Raising the limit brings the risk back with it.
>
> Path parameters are matched without `std::regex` and have no such limit, so prefer them where they fit:
>
> ```cpp
> // This pattern can cause stack overflow with large input
> svr.Get(".*", handler);
> ```
>
> Consider using simpler patterns or path parameters to avoid this issue:
>
> ```cpp
> // Safer alternatives
> svr.Get("/users/:id", handler); // Path parameters
> svr.Get(R"(/api/v\d+/.*)", handler); // More specific patterns
> svr.Get(R"(/api/v\d+/.*)", handler); // Regex route, limited to short paths
> ```
### g++
+3 -1
View File
@@ -76,7 +76,9 @@ void nginx_access_logger(const Request &req, const Response &res) {
// the percent-decoded req.path.
auto request = std::format("{} {} {}", req.method, req.target, req.version);
auto status = res.status;
auto body_bytes_sent = res.body.size();
// A static file is sent by a content provider, which leaves res.body empty.
auto body_bytes_sent =
req.method == "HEAD" ? 0 : res.get_header_value_u64("Content-Length");
auto http_referer = req.get_header_value("Referer");
if (http_referer.empty()) http_referer = "-";
auto http_user_agent = req.get_header_value("User-Agent");
+1 -1
View File
@@ -4,7 +4,7 @@ langs = ["en", "ja"]
[site]
title = "cpp-httplib"
version = "0.60.0"
version = "0.61.0"
hostname = "https://yhirose.github.io"
base_path = "/cpp-httplib"
footer_message = "© 2026 Yuji Hirose. All rights reserved."
+1 -1
View File
@@ -17,7 +17,7 @@ auto res = cli.Post("/api/users", j.dump(), "application/json");
Pass the JSON string as the second argument to `Post()` and the Content-Type as the third. The same pattern works with `Put()` and `Patch()`.
> **Warning:** If you omit the Content-Type (the third argument), the server may not recognize the body as JSON. Always specify `"application/json"`.
> **Warning:** If the Content-Type (the third argument) is anything other than `"application/json"`, the server may not recognize the body as JSON. Always specify `"application/json"`.
## Receive a JSON response
@@ -21,7 +21,7 @@ auto res = cli.Get("/large-file",
std::cout << std::endl;
```
The callback fires each time data arrives. `total` comes from the Content-Length header — if the server doesn't send one, it may be `0`. In that case, you can't compute a percentage, so just display bytes received.
The callback fires each time data arrives. `total` comes from the Content-Length header. For a response without one (chunked transfer, for example), the progress callback is not called at all.
## Upload progress
@@ -54,6 +54,8 @@ auto res = cli.Get("/large-file",
});
```
> **Note:** A response without Content-Length never calls the progress callback, so it cannot be cancelled this way. Return `false` from a `ContentReceiver` instead.
> **Note:** `ContentReceiver` and the progress callback can be used together. When you want to stream to a file and show progress at the same time, pass both.
> For a concrete example of saving to a file, see [C01. Get the response body / save to a file](../c01-get-response-body).
@@ -16,7 +16,7 @@ cli.set_max_timeout(5000); // 5 seconds (in milliseconds)
auto res = cli.Get("/slow-endpoint");
```
The value is in milliseconds. Connection, send, and receive together — the whole request is aborted if it exceeds the limit.
The value is in milliseconds. Once that much time has passed since the request started, waiting for the response is cut off. The limit does not shorten the connection and write waits themselves, so bound those with `set_connection_timeout` and `set_write_timeout`.
## Use `std::chrono`
+9 -8
View File
@@ -4,30 +4,29 @@ order: 14
status: "draft"
---
When you send multiple requests through the same `httplib::Client` instance, the TCP connection is reused automatically. HTTP/1.1 Keep-Alive does the work for you — you don't pay the TCP and TLS handshake cost on every call.
By default, `httplib::Client` closes the connection after every request (it sends `Connection: close`). Call `set_keep_alive(true)` and the requests you send through the same instance share one TCP connection, so you don't pay the TCP and TLS handshake cost on every call.
## Connections are reused automatically
## Enable Keep-Alive
```cpp
httplib::Client cli("https://api.example.com");
cli.set_keep_alive(true);
auto res1 = cli.Get("/users/1");
auto res2 = cli.Get("/users/2"); // reuses the same connection
auto res3 = cli.Get("/users/3"); // reuses the same connection
```
No special config required. Just hold on to `cli` — internally, the socket stays open across calls. The effect is especially noticeable over HTTPS, where the TLS handshake is expensive.
After that, just hold on to `cli`. Internally, the socket stays open across calls. The effect is especially noticeable over HTTPS, where the TLS handshake is expensive.
## Disable Keep-Alive explicitly
## Turn Keep-Alive back off
To force a fresh connection every time, call `set_keep_alive(false)`. Mostly useful for testing.
To go back to a fresh connection every time, call `set_keep_alive(false)`. This is the default behavior.
```cpp
cli.set_keep_alive(false);
```
For normal use, leave it on (the default).
## Don't create a `Client` per request
If you create a `Client` inside a loop and let it fall out of scope each iteration, you lose the reuse benefit. Create the instance outside the loop.
@@ -36,11 +35,13 @@ If you create a `Client` inside a loop and let it fall out of scope each iterati
// Bad: a new connection every iteration
for (auto id : ids) {
httplib::Client cli("https://api.example.com");
cli.set_keep_alive(true);
cli.Get("/users/" + id);
}
// Good: the connection is reused
httplib::Client cli("https://api.example.com");
cli.set_keep_alive(true);
for (auto id : ids) {
cli.Get("/users/" + id);
}
@@ -50,4 +51,4 @@ for (auto id : ids) {
If you want to send requests in parallel from multiple threads, give each thread its own `Client` instance. A single `Client` uses a single TCP connection, so firing concurrent requests at the same instance ends up serializing them anyway.
> **Note:** If the server closes the connection after its Keep-Alive timeout, cpp-httplib reconnects and retries transparently. You don't need to handle this in application code.
> **Note:** If the server closes the connection after its Keep-Alive timeout, cpp-httplib notices before it sends the next request and reconnects. You don't need to handle this in application code.
@@ -4,7 +4,7 @@ order: 15
status: "draft"
---
cpp-httplib supports compression when sending and decompression when receiving. You just need to build it with zlib or Brotli enabled.
cpp-httplib supports compression when sending and decompression when receiving. You just need to build it with zlib, Brotli, or Zstd enabled.
## Build-time setup
@@ -13,10 +13,11 @@ To use compression, define these macros before including `httplib.h`:
```cpp
#define CPPHTTPLIB_ZLIB_SUPPORT // gzip / deflate
#define CPPHTTPLIB_BROTLI_SUPPORT // brotli
#define CPPHTTPLIB_ZSTD_SUPPORT // zstd
#include <httplib.h>
```
You'll also need to link against `zlib` or `brotli`.
You'll also need to link against `zlib`, `brotli`, or `zstd`, whichever you enabled.
## Compress the request body
@@ -28,7 +29,7 @@ std::string big_payload = build_payload();
auto res = cli.Post("/api/data", big_payload, "application/json");
```
With `set_compress(true)`, the body of POST or PUT requests gets gzipped before sending. The server needs to handle compressed bodies too.
With `set_compress(true)`, the body of POST or PUT requests is compressed before sending. The encoding is the first one enabled in your build, in the order Brotli, gzip, Zstd. The server needs to handle compressed bodies too.
## Decompress the response
@@ -44,4 +45,4 @@ With `set_decompress(true)`, the client automatically decompresses responses tha
It's on by default, so normally you don't need to do anything. Set it to `false` only if you want the raw compressed bytes.
> **Warning:** If you build without `CPPHTTPLIB_ZLIB_SUPPORT`, calling `set_compress()` or `set_decompress()` does nothing. If compression isn't working, check the macro definition first.
> **Warning:** If you build without any compression library, `set_compress(true)` leaves the request uncompressed. And a response compressed with an encoding your build lacks makes the request fail with `Error::UnsupportedContentEncoding`. If compression isn't working, check the macro definitions first.
+1 -1
View File
@@ -55,7 +55,7 @@ You often want internal endpoints to skip the proxy. Configure a bypass list wit
```cpp
cli.set_proxy("proxy.internal", 8080);
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", "*.dev.local"});
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", ".dev.local"});
```
Each entry is one of:
@@ -29,8 +29,8 @@ Use `if (res)` to check success. On failure, `res.error()` returns a `httplib::E
| --- | --- |
| `Error::Connection` | Couldn't connect to the server |
| `Error::ConnectionTimeout` | Connection timeout (`set_connection_timeout`) |
| `Error::Read` / `Error::Write` | Error during send or receive |
| `Error::Timeout` | Overall timeout set via `set_max_timeout` |
| `Error::Read` / `Error::Write` | Error during send or receive. A timeout from `set_read_timeout` or `set_max_timeout` is also reported as `Error::Read` |
| `Error::Timeout` | A body read timed out in `stream::Get()` or `SSEClient` |
| `Error::ExceedRedirectCount` | Too many redirects |
| `Error::SSLConnection` | TLS handshake failed |
| `Error::SSLServerVerification` | Server certificate verification failed |
+8 -3
View File
@@ -24,19 +24,24 @@ if (!res) {
}
```
`ssl_error()` returns the error code from the SSL library (e.g., OpenSSL's `SSL_get_error()`). `ssl_backend_error()` gives you the backend's more detailed error value — for OpenSSL, that's `ERR_get_error()`.
`ssl_error()` is a backend-independent TLS error category: an `httplib::tls::ErrorCode` cast to `int`. `ssl_backend_error()` gives you the backend's own error value. With OpenSSL that is `ERR_get_error()` when the handshake failed, and the verify result (`X509_V_ERR_*`) when certificate verification failed.
## Format OpenSSL errors as strings
When you have a value from `ssl_backend_error()`, pass it to OpenSSL's `ERR_error_string()` to get a readable message.
When you have a value from `ssl_backend_error()`, pass it to the OpenSSL function that matches the kind of failure to get a readable message.
```cpp
#include <openssl/err.h>
#include <openssl/x509.h>
if (res.ssl_backend_error() != 0) {
if (res.error() == httplib::Error::SSLConnection) {
char buf[256];
ERR_error_string_n(res.ssl_backend_error(), buf, sizeof(buf));
std::cerr << "openssl: " << buf << std::endl;
} else if (res.error() == httplib::Error::SSLServerVerification ||
res.error() == httplib::Error::SSLServerHostnameVerification) {
auto code = static_cast<long>(res.ssl_backend_error());
std::cerr << "openssl: " << X509_verify_cert_error_string(code) << std::endl;
}
```
+2 -2
View File
@@ -41,7 +41,7 @@ sse.on_event("leave", [](const auto &msg) {
});
```
`on_message()` serves as a generic fallback for unnamed events (the default `message` type).
`on_message()` is the generic fallback: it receives every event that has no handler registered through `on_event()`. With `on_event("message", ...)` registered as above, `message` events go there instead.
## Connection lifecycle and errors
@@ -55,7 +55,7 @@ sse.on_error([](httplib::Error err) {
});
```
Hook into connection open and error events. Even when the error handler fires, `SSEClient` keeps trying to reconnect in the background.
Hook into connection open and error events. Even when the error handler fires, `SSEClient` keeps trying to reconnect in the background. The exceptions are a 204, 403, or 404 response, after which it stops.
## Run asynchronously
@@ -30,7 +30,7 @@ You can even mount multiple directories at the same path — they're searched in
## Combine with API handlers
Static files and API handlers coexist happily. Handlers registered with `Get()` and friends take priority; the mount points are searched only when nothing matches.
Static files and API handlers coexist happily. For GET and HEAD, the mount points are searched first; handlers registered with `Get()` and friends run only when no file is found.
```cpp
svr.Get("/api/users", [](const auto &req, auto &res) {
@@ -15,14 +15,15 @@ svr.Get("/download", [](const httplib::Request &req, httplib::Response &res) {
res.set_content_provider(
total_size, "application/octet-stream",
[](size_t offset, size_t length, httplib::DataSink &sink) {
auto data = read_range_from_file("large.bin", offset, length);
auto n = std::min(length, size_t(64 * 1024));
auto data = read_range_from_file("large.bin", offset, n);
sink.write(data.data(), data.size());
return true;
});
});
```
The lambda is called repeatedly with `offset` and `length`. Read just that range and write it to `sink`. Only a small chunk sits in memory at any given time.
The lambda is called repeatedly with `offset`, the position sent so far, and `length`, the number of bytes still to send. Cap how much you read per call and write it to `sink`, and only a small chunk sits in memory at any given time.
## Just send a file
@@ -96,7 +96,7 @@ svr.Post("/upload",
});
```
When `content_reader` returns `false`, set the response status yourself. The rest of the body is left unread and the connection is closed, so a client that is still sending sees the connection drop.
When `content_reader` returns `false`, the response status becomes 400 (413 if the body exceeded the size limit). Set it yourself if you want a different one. The rest of the body is left unread and the connection is closed, so a client that is still sending sees the connection drop.
> **Warning:** When you use `HandlerWithContentReader`, `req.body` stays **empty**. Handle the body yourself inside the callbacks.
@@ -32,7 +32,7 @@ That's it. If the client sent `Accept-Encoding: gzip`, cpp-httplib compresses th
## Encoding priority
When the client accepts multiple encodings, cpp-httplib picks in this order (among those enabled at build time): Brotli → Zstd → gzip. Your code doesn't need to care — you always get the most efficient option available.
When the client accepts multiple encodings, cpp-httplib picks the one with the highest q-value in `Accept-Encoding`. On a tie the order is Brotli → gzip → Zstd (among those enabled at build time).
## Streaming responses are compressed too
+1 -1
View File
@@ -37,7 +37,7 @@ svr.Get("/me", [](const httplib::Request &req, httplib::Response &res) {
## Typical value types
Strings, numbers, structs, `std::shared_ptr` — anything copyable or movable works.
Strings, numbers, structs, `std::shared_ptr`: anything copyable works.
```cpp
res.user_data.set("user_id", std::string{"42"});
@@ -48,7 +48,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
return httplib::Server::HandlerResponse::Unhandled;
});
svr.set_logger([](const auto &req, const auto &res) {
svr.set_logger([](const httplib::Request &req, const httplib::Response &res) {
auto *start = res.user_data.get<std::chrono::steady_clock::time_point>("start");
auto elapsed = start
? std::chrono::duration_cast<std::chrono::milliseconds>(
@@ -52,6 +52,6 @@ int main() {
## What happens to in-flight requests
When you call `stop()`, new connections are refused, but requests already being processed are **allowed to finish**. Once all workers drain, `listen()` returns. That's what makes it graceful.
When you call `stop()`, new connections are refused, but handlers that are already running are **allowed to finish**. A response still being sent by a content provider (a streaming response, for example) is cut short, though. Once all workers drain, `listen()` returns. That's what makes it graceful.
> **Warning:** There's a wait between calling `stop()` and `listen()` returning — it's the time in-flight requests take to finish. To enforce a timeout, you'll need to add your own shutdown timer in application code.
@@ -19,7 +19,7 @@ svr.Get("/", [](const auto &, auto &res) {
svr.listen("/tmp/httplib.sock", 80);
```
Call `set_address_family(AF_UNIX)` first, then pass the socket file path as the first argument to `listen()`. The port number is unused but required by the signature — pass any value.
Call `set_address_family(AF_UNIX)` first, then pass the socket file path as the first argument to `listen()`. The port number is unused but required by the signature. Pass any value other than `0`, which makes `listen()` fail.
## Client side
+1 -1
View File
@@ -55,7 +55,7 @@ httplib::SSLClient cli("api.example.com", 443,
auto res = cli.Get("/");
```
Note you're using `SSLClient` directly, not `Client`. If the private key has a password, pass it as the fifth argument.
If the certificate and key paths are all you need, `Client` takes them too: `httplib::Client cli("https://api.example.com", "client-cert.pem", "client-key.pem")`. When the private key has a password, use `SSLClient` and pass it as the fifth argument.
The client side has the same `PemMemory` struct too, letting you set the client certificate from PEM in memory.
@@ -67,7 +67,7 @@ cli.set_websocket_max_missed_pongs(2); // close after 2 consecutive unacked ping
The server side has the same `set_websocket_max_missed_pongs()`.
With a 30-second ping interval and `max_missed_pongs = 2`, a dead peer is detected within roughly 60 seconds and the connection is closed with `CloseStatus::GoingAway` and the reason `"pong timeout"`.
With a 30-second ping interval and `max_missed_pongs = 2`, a dead peer is detected 60 to 90 seconds after it stops answering, and the connection is closed with `CloseStatus::GoingAway` and the reason `"pong timeout"`. A `read()` waiting on the peer at that moment returns `Fail`.
The counter is reset whenever `read()` consumes an incoming Pong frame, so this only works if your code is actively calling `read()` in a loop — which is what a normal WebSocket client does anyway.
+1 -9
View File
@@ -18,10 +18,6 @@ Simply pass the path to a model file to `llamalib::Llama`, and model loading, co
int main() {
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
// LLM inference takes time, so set a longer timeout (default is 5 seconds)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
// ... Build and start the HTTP server ...
}
```
@@ -78,7 +74,7 @@ svr.Post("/translate",
});
```
`llm.chat()` can throw exceptions during inference (for example, when the context length is exceeded). By catching them with `try/catch` and returning the error as JSON, we prevent the server from crashing.
`llm.chat()` can throw exceptions during inference (for example, when the context length is exceeded). We catch them with `try/catch` and return the error as JSON. Left uncaught, cpp-httplib would still answer with a 500, but the client would not learn the cause.
## 2.3 Complete Code
@@ -111,10 +107,6 @@ int main() {
// Load the model downloaded in Chapter 1
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
// LLM inference takes time, so set a longer timeout (default is 5 seconds)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
// Log requests and responses
svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status
@@ -73,7 +73,7 @@ A few key points:
- After writing to `sink.os`, you can check whether the client is still connected with `sink.os.good()`. If the client has disconnected, it returns `false` to stop inference
- Each token is escaped as a JSON string using `json(token).dump()` before sending. This is safe even for tokens containing newlines or quotes
- The first three arguments of `dump(-1, ' ', false, ...)` are the defaults. What matters is the fourth argument, `json::error_handler_t::replace`. Since the LLM returns tokens at the subword level, multi-byte characters (such as Japanese) can be split mid-character across tokens. Passing an incomplete UTF-8 byte sequence directly to `dump()` would throw an exception, so `replace` safely substitutes them. The browser reassembles the bytes on its end, so everything displays correctly
- The entire lambda is wrapped in `try/catch`. `llm.chat()` can throw exceptions for reasons such as exceeding the context window. If an exception goes uncaught inside the lambda, the server will crash, so we return the error as an SSE event instead
- The entire lambda is wrapped in `try/catch`. `llm.chat()` can throw exceptions for reasons such as exceeding the context window. If an exception goes uncaught inside the lambda, cpp-httplib just drops the connection and the client never learns the cause, so we return the error as an SSE event instead
- `data: [DONE]` follows the OpenAI API convention to signal the end of the stream to the client
## 3.4 Complete Code
@@ -107,10 +107,6 @@ int main() {
// Load the GGUF model
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
// LLM inference takes time, so set a longer timeout (default is 5 seconds)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
// Log requests and responses
svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status
@@ -219,7 +219,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true);
cli.set_read_timeout(std::chrono::hours(1));
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename;
@@ -469,7 +468,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); // Hugging Face redirects to a CDN
cli.set_read_timeout(std::chrono::hours(1)); // Set a long timeout for large models
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename;
@@ -539,10 +537,6 @@ int main() {
auto llm = llamalib::Llama{path};
std::mutex llm_mutex; // Protect access during model switching
// Set a long timeout since LLM inference takes time (default is 5 seconds)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status
<< std::endl;
-5
View File
@@ -939,7 +939,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); // Hugging Face redirects to CDN
cli.set_read_timeout(std::chrono::hours(1)); // Long timeout for large models
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename;
@@ -1008,10 +1007,6 @@ int main() {
}
auto llm = llamalib::Llama{path};
// LLM inference takes time, so set a longer timeout (default is 5 seconds)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status
<< std::endl;
@@ -407,7 +407,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); // Hugging Face redirects to a CDN
cli.set_read_timeout(std::chrono::hours(1)); // Long timeout for large models
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename;
@@ -469,10 +468,6 @@ int main() {
auto llm = llamalib::Llama{path};
std::mutex llm_mutex; // Protect access during model switching
// Set a long timeout since LLM inference takes time (default is 5 seconds)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status
<< std::endl;
+10 -6
View File
@@ -11,13 +11,17 @@ Over the course of six chapters, we built a translation desktop app from scratch
## 7.1 Source Code Location
```ascii
llama.cpp/tools/server/
├── server.cpp # Main server implementation
├── httplib.h # cpp-httplib (bundled version)
└── ...
llama.cpp/
├── tools/server/
│ ├── server.cpp # Entry point
│ ├── server-http.cpp # HTTP server (the layer that uses cpp-httplib)
│ ├── server-context.cpp # Inference and slot management
│ └── ...
└── vendor/cpp-httplib/
└── httplib.h # cpp-httplib (bundled version)
```
The code is contained in a single `server.cpp`. It runs to several thousand lines, but once you understand the structure, you can narrow down the parts worth reading.
The implementation is split across several files by role. Together they run to more than 20,000 lines, but once you understand the structure, you can narrow down the parts worth reading.
## 7.2 OpenAI-Compatible API
@@ -141,7 +145,7 @@ Let's organize the differences we've covered.
| SSE format | Tokens only | OpenAI-compatible JSON |
| KV cache | Cleared each time | Prefix reuse |
| Structured output | None | JSON Schema / grammar constraints |
| Code size | ~200 lines | Several thousand lines |
| Code size | ~200 lines | Over 20,000 lines |
Our code is simple because of the assumption that "one person uses it as a desktop app." If you're building a server for multiple users or one that integrates with the existing ecosystem, `llama-server`'s design serves as a valuable reference.
+2 -2
View File
@@ -200,8 +200,8 @@ auto res = cli.Post("/submit", httplib::Params{
});
if (res) {
std::cout << res->body << std::endl;
// age = 30
// name = Alice
// age = 30
}
```
@@ -241,7 +241,7 @@ auto res = cli.Get("/hi");
if (!res) {
// Connection error
std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
// Error: Connection
// Error: Could not establish connection
return 1;
}
@@ -95,7 +95,7 @@ svr.set_mount_point("/", "./public");
svr.listen("0.0.0.0", 8080);
```
Handlers take priority. The handler responds to `/api/hello`. For every other path, the server looks for a file in `./public`.
The server looks for a file in `./public` first and calls the handler when there is none. So the handler responds to `/api/hello` unless you put a file at `./public/api/hello`.
## Adding response headers
+4 -4
View File
@@ -50,7 +50,7 @@ svr.Get("/stream", [](const auto &, auto &res) {
res.set_chunked_content_provider("text/plain",
[](size_t offset, httplib::DataSink &sink) {
sink.write("chunk\n", 6);
return true; // Return false to finish
return true; // Call sink.done() to finish
});
});
```
@@ -155,7 +155,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
});
svr.set_post_routing_handler([](const auto &req, auto &res) {
// Runs after the response is sent
// Runs just before the response is sent
res.set_header("X-Server", "cpp-httplib");
});
```
@@ -168,7 +168,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
return httplib::Server::HandlerResponse::Unhandled;
});
svr.Get("/me", [](const auto &req, auto &res) {
svr.Get("/me", [](const httplib::Request &req, httplib::Response &res) {
auto *user = res.user_data.get<std::string>("auth_user");
res.set_content("Hello, " + *user, "text/plain");
});
@@ -205,7 +205,7 @@ In addition to TCP, we support Unix Domain Sockets. You can use them for inter-p
// Server
httplib::Server svr;
svr.set_address_family(AF_UNIX);
svr.listen("/tmp/httplib.sock", 0);
svr.listen("/tmp/httplib.sock", 80); // The port is unused, but must not be 0
```
```cpp
+1 -1
View File
@@ -17,7 +17,7 @@ auto res = cli.Post("/api/users", j.dump(), "application/json");
`Post()`の第2引数にJSON文字列、第3引数にContent-Typeを渡します。`Put()`や`Patch()`でも同じ形です。
> **Warning:** 第3引数のContent-Typeを省略すると、サーバー側でJSONとして認識されないことがあります。`"application/json"`を必ず指定しましょう。
> **Warning:** 第3引数のContent-Typeが`"application/json"`でないと、サーバー側でJSONとして扱われないことがあります。忘れずに指定しましょう。
## JSONレスポンスを受け取る
@@ -21,7 +21,7 @@ auto res = cli.Get("/large-file",
std::cout << std::endl;
```
コールバックはデータを受信するたびに呼ばれます。`total`はContent-Lengthから取得した値で、サーバーが送ってこない場合は`0`になることがあります。その場合は進捗率が計算できないので、受信済みバイト数だけを表示するのが無難です。
コールバックはデータを受信するたびに呼ばれます。`total`はContent-Lengthの値です。chunked転送のようにContent-Lengthのないレスポンスでは、進捗コールバックは一度も呼ばれません。
## アップロードの進捗
@@ -54,6 +54,8 @@ auto res = cli.Get("/large-file",
});
```
> **Note:** Content-Lengthのないレスポンスでは進捗コールバックが呼ばれないため、この方法は使えません。代わりに`ContentReceiver`から`false`を返して中断します。
> **Note:** `ContentReceiver`と進捗コールバックは同時に使えます。ファイルに書き出しながら進捗を表示したいときは、両方を渡しましょう。
> ファイル保存と組み合わせる具体例は[C01. レスポンスボディを取得する / ファイルに保存する](../c01-get-response-body)も参照してください。
@@ -16,11 +16,11 @@ cli.set_max_timeout(5000); // 5秒(ミリ秒単位)
auto res = cli.Get("/slow-endpoint");
```
ミリ秒単位で指定します。接続、送信、受信をすべて含めて、リクエスト全体が指定時間を超えたら打ち切られます。
ミリ秒単位で指定します。リクエストを始めてからこの時間が過ぎると、レスポンスを待っている途中でも打ち切られます。ただし、接続や送信で待たされる時間まで短くなるわけではありません。そちらは`set_connection_timeout`と`set_write_timeout`で調整します。
## `std::chrono`で指定する
こちらも`std::chrono`の期間を受け取るオーバーロードがあります。
こちらにも、`std::chrono`の期間を受け取るオーバーロードがあります。
```cpp
using namespace std::chrono_literals;
+10 -9
View File
@@ -4,43 +4,44 @@ order: 14
status: "draft"
---
`httplib::Client`は同じインスタンスで複数回リクエストを送ると、TCP接続を自動的に再利用します。HTTP/1.1のKeep-Aliveが有効に働くので、TCPハンドシェイクやTLSハンドシェイクのオーバーヘッドを毎回払わずに済みます。
`httplib::Client`は、デフォルトではリクエストのたびに接続を閉じます(`Connection: close`を送ります)。`set_keep_alive(true)`を呼んでおくと、同じインスタンスから送るリクエストは1本のTCP接続を使い回します。TCPやTLSのハンドシェイクを毎回やり直さずに済みます。
## 接続は自動で使い回される
## Keep-Aliveを有効にする
```cpp
httplib::Client cli("https://api.example.com");
cli.set_keep_alive(true);
auto res1 = cli.Get("/users/1");
auto res2 = cli.Get("/users/2"); // 同じ接続を再利用
auto res3 = cli.Get("/users/3"); // 同じ接続を再利用
```
特別な設定は要りません。`cli`を使い回すだけで、内部的には同じソケットで通信が続きます。とくにHTTPSでは、TLSハンドシェイクのコストが大きいので効果が顕著です。
あとは`cli`を使い回すだけで、内部的には同じソケットで通信が続きます。とくにHTTPSでは、TLSハンドシェイクのコストが大きいので効果が顕著です。
## Keep-Aliveを明示的にオフにする
## Keep-Aliveをオフに戻す
毎回新しい接続を張り直したい場合は、`set_keep_alive(false)`を呼びます。テスト目的などで使うことがあります。
リクエストのたびに接続を張り直す動作(デフォルト)に戻すには、`set_keep_alive(false)`を呼びます。
```cpp
cli.set_keep_alive(false);
```
ただし、普段はオン(デフォルト)のままで問題ありません。
## リクエストごとに`Client`を作らない
1回のリクエストのたびに`Client`をスコープから抜けて破棄すると、接続の再利用は効きません。ループの外でインスタンスを作り、中で使い回しましょう。
リクエストのたびに`Client`を作っては破棄していると、接続は再利用されません。インスタンスはループの外で作り、中で使い回しましょう。
```cpp
// NG: 毎回接続が切れる
for (auto id : ids) {
httplib::Client cli("https://api.example.com");
cli.set_keep_alive(true);
cli.Get("/users/" + id);
}
// OK: 接続が再利用される
httplib::Client cli("https://api.example.com");
cli.set_keep_alive(true);
for (auto id : ids) {
cli.Get("/users/" + id);
}
@@ -50,4 +51,4 @@ for (auto id : ids) {
複数のスレッドから並行にリクエストを送りたいときは、スレッドごとに別々の`Client`インスタンスを持つのが無難です。1つの`Client`は1本のTCP接続を使い回すので、同じインスタンスに複数スレッドから同時にリクエストを投げると、結局どこかで直列化されます。
> **Note:** サーバー側のKeep-Aliveタイムアウトを超えると、サーバーが接続を切ります。その場合cpp-httplibは自動で再接続して再試行するので、アプリケーションコードで気にする必要はありません。
> **Note:** サーバー側のKeep-Aliveタイムアウトを超えると、サーバーが接続を切ります。cpp-httplibは次のリクエストを送る前にそれに気付いて接続し直すので、アプリケーション側で気にする必要はありません。
@@ -4,7 +4,7 @@ order: 15
status: "draft"
---
cpp-httplibは送信時の圧縮と受信時の解凍をサポートしています。ただし、zlibまたはBrotliを有効にしてビルドしておく必要があります。
cpp-httplibは送信時の圧縮と受信時の解凍をサポートしています。ただし、zlib、Brotli、Zstdのいずれかを有効にしてビルドしておく必要があります。
## ビルド時の準備
@@ -13,10 +13,11 @@ cpp-httplibは送信時の圧縮と受信時の解凍をサポートしていま
```cpp
#define CPPHTTPLIB_ZLIB_SUPPORT // gzip / deflate
#define CPPHTTPLIB_BROTLI_SUPPORT // brotli
#define CPPHTTPLIB_ZSTD_SUPPORT // zstd
#include <httplib.h>
```
リンク時に`zlib`や`brotli`のライブラリも必要です。
有効にした方式に応じて、`zlib`、`brotli`、`zstd`のライブラリもリンクします。
## リクエストボディを圧縮して送る
@@ -28,7 +29,7 @@ std::string big_payload = build_payload();
auto res = cli.Post("/api/data", big_payload, "application/json");
```
`set_compress(true)`を呼んでおくと、POSTやPUTのリクエストボディがgzipで圧縮されて送信されます。サーバー側が対応している必要があります。
`set_compress(true)`を呼んでおくと、POSTやPUTのリクエストボディが圧縮されて送信されます。圧縮方式は、ビルドで有効にしたもののうち、Brotli、gzip、Zstdの順で最初に当てはまるものです。サーバー側もその方式に対応している必要があります。
## レスポンスを解凍する
@@ -44,4 +45,4 @@ std::cout << res->body << std::endl;
デフォルトで有効なので、通常は何もしなくても解凍されます。あえて生の圧縮データを触りたいときだけ`set_decompress(false)`にしましょう。
> **Warning:** `CPPHTTPLIB_ZLIB_SUPPORT`を定義せずにビルドすると、`set_compress()`や`set_decompress()`を呼んでも何も起こりません。マクロの定義を忘れていないか、最初に確認しましょう。
> **Warning:** 圧縮ライブラリを1つも有効にしていないビルドでは、`set_compress(true)`を呼んでもリクエストは圧縮されません。また、ビルドで有効にしていない方式で圧縮されたレスポンスが返ってくると、リクエストは`Error::UnsupportedContentEncoding`で失敗します。うまく動かないときは、まずマクロの定義を確認しましょう。
+1 -1
View File
@@ -55,7 +55,7 @@ cli.set_bearer_token_auth("api-token"); // エンドサーバー向け
```cpp
cli.set_proxy("proxy.internal", 8080);
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", "*.dev.local"});
cli.set_no_proxy({"internal.corp", "10.0.0.0/8", ".dev.local"});
```
エントリは次のいずれかです。
@@ -29,8 +29,8 @@ if (res) {
| --- | --- |
| `Error::Connection` | サーバーに接続できなかった |
| `Error::ConnectionTimeout` | 接続タイムアウト(`set_connection_timeout`) |
| `Error::Read` / `Error::Write` | 送受信中のエラー |
| `Error::Timeout` | `set_max_timeout`で設定した全体タイムアウト |
| `Error::Read` / `Error::Write` | 送受信中のエラー。`set_read_timeout`や`set_max_timeout`によるタイムアウトも`Error::Read`になる |
| `Error::Timeout` | `stream::Get()`や`SSEClient`で、ボディの読み取りがタイムアウトした |
| `Error::ExceedRedirectCount` | リダイレクト回数が上限を超えた |
| `Error::SSLConnection` | TLSハンドシェイクに失敗 |
| `Error::SSLServerVerification` | サーバー証明書の検証に失敗 |
@@ -38,7 +38,7 @@ if (res) {
## ステータスコードとの使い分け
`res`が truthy でも、HTTPステータスコードが4xxや5xxのこともあります。この2つは別物です。
`res`がtruthyでも、HTTPステータスコードが4xxや5xxのこともあります。この2つは別物です。
```cpp
auto res = cli.Get("/api/data");
+8 -3
View File
@@ -24,19 +24,24 @@ if (!res) {
}
```
`ssl_error()`はSSLライブラリが返したエラーコード(OpenSSLの`SSL_get_error()`の値など)、`ssl_backend_error()`はバックエンドがさらに詳しく提供するエラー値です。OpenSSLなら`ERR_get_error()`の値が入ります。
`ssl_error()`は、どのTLSバックエンドでも共通のエラー種別(`httplib::tls::ErrorCode`)を`int`で返します。`ssl_backend_error()`は、バックエンドが返したエラー値そのものです。OpenSSLなら、ハンドシェイクの失敗では`ERR_get_error()`の値が、証明書検証の失敗では検証結果のコード(`X509_V_ERR_*`)が入ります。
## OpenSSLのエラーを文字列化する
`ssl_backend_error()`で取得した値を、OpenSSLの`ERR_error_string()`で文字列にするとデバッグに便利です。
`ssl_backend_error()`の値は、OpenSSLの関数で文字列にしておくとデバッグに便利です。使う関数は失敗の種類によって変わります。
```cpp
#include <openssl/err.h>
#include <openssl/x509.h>
if (res.ssl_backend_error() != 0) {
if (res.error() == httplib::Error::SSLConnection) {
char buf[256];
ERR_error_string_n(res.ssl_backend_error(), buf, sizeof(buf));
std::cerr << "openssl: " << buf << std::endl;
} else if (res.error() == httplib::Error::SSLServerVerification ||
res.error() == httplib::Error::SSLServerHostnameVerification) {
auto code = static_cast<long>(res.ssl_backend_error());
std::cerr << "openssl: " << X509_verify_cert_error_string(code) << std::endl;
}
```
+3 -3
View File
@@ -25,7 +25,7 @@ sse.start(); // ブロッキング
## イベント名で分岐する
サーバー側で`event:`を付けて送られてくる場合は、`on_event()`で名前ごとにハンドラを登録できます。
サーバーが`event:`を付けてイベントを送ってくる場合は、`on_event()`で名前ごとにハンドラを登録できます。
```cpp
sse.on_event("message", [](const auto &msg) {
@@ -41,7 +41,7 @@ sse.on_event("leave", [](const auto &msg) {
});
```
`on_message()`は、名前なし(デフォルトの`message`イベント)を受け取る汎用ハンドラとして使えます。
`on_message()`は、`on_event()`で登録していない名前のイベントをまとめて受け取る汎用ハンドラです。上の例のように`on_event("message", ...)`を登録した場合、`message`イベントは`on_message()`ではなくそちらに届きます。
## 接続イベントとエラーハンドリング
@@ -55,7 +55,7 @@ sse.on_error([](httplib::Error err) {
});
```
接続確立時やエラー発生時にもフックを挟めます。エラーハンドラが呼ばれても、`SSEClient`は内部で再接続を試みます。
接続確立時やエラー発生時にもフックを挟めます。エラーハンドラが呼ばれても、`SSEClient`は内部で再接続を試みます。ただし、サーバーが204、403、404のいずれかを返したときは再接続しません。
## 非同期で動かす
@@ -14,7 +14,7 @@ svr.set_mount_point("/", "./public");
svr.listen("0.0.0.0", 8080);
```
`./public/index.html`が`http://localhost:8080/index.html`で、`./public/css/style.css`が`http://localhost:8080/css/style.css`でアクセスできます。ディレクトリ構造がそのままURLに反映されます。
`./public/index.html`には`http://localhost:8080/index.html`で、`./public/css/style.css`には`http://localhost:8080/css/style.css`でアクセスできます。ディレクトリ構造がそのままURLに反映されます。
## 複数のマウントポイント
@@ -26,11 +26,11 @@ svr.set_mount_point("/assets", "./dist/assets");
svr.set_mount_point("/uploads", "./var/uploads");
```
同じパスに複数のマウントを登録することもできます。その場合は登録順に探されて、見つかった最初のものが返ります。
同じパスに複数のマウントを登録することもできます。その場合は登録した順に探し、最初に見つかったファイルを返します。
## APIハンドラと組み合わせる
静的ファイルとAPIハンドラは共存できます。`Get()`などで登録したハンドラが優先され、マッチしなかったときにマウントポイントが探されます。
静的ファイルとAPIハンドラは共存できます。GETとHEADのリクエストでは、まずマウントポイントからファイルを探し、見つからなければ`Get()`などで登録したハンドラを呼びます。
```cpp
svr.Get("/api/users", [](const auto &req, auto &res) {
@@ -44,7 +44,7 @@ svr.set_mount_point("/", "./public");
## MIMEタイプを追加する
拡張子からContent-Typeを決めるマッピングは組み込みですが、カスタムの拡張子を追加できます。
拡張子からContent-Typeを決める対応表は組み込まれていますが、独自の拡張子を追加することもできます。
```cpp
svr.set_file_extension_and_mimetype_mapping("wasm", "application/wasm");
@@ -15,14 +15,15 @@ svr.Get("/download", [](const httplib::Request &req, httplib::Response &res) {
res.set_content_provider(
total_size, "application/octet-stream",
[](size_t offset, size_t length, httplib::DataSink &sink) {
auto data = read_range_from_file("large.bin", offset, length);
auto n = std::min(length, size_t(64 * 1024));
auto data = read_range_from_file("large.bin", offset, n);
sink.write(data.data(), data.size());
return true;
});
});
```
ラムダが呼ばれるたびに`offset`と`length`が渡されるので、その範囲だけ読み込んで`sink.write()`で送ります。メモリには常に少量のチャンクしか載りません。
ラムダは繰り返し呼ばれ、そのたびに`offset`(ここまでに送った位置)と`length`(残りのバイト数)が渡されます。`length`は残り全部を指すので、上の例のように1回に読む量を自分で区切って`sink.write()`で送ります。こうすれば、メモリに載るのは常に小さなチャンクだけです。
## ファイルをそのまま返す
@@ -96,7 +96,7 @@ svr.Post("/upload",
});
```
`content_reader`が`false`を返したら、レスポンスのステータスは自分でセットしてください。ボディの残りは読まずに接続を閉じるので、送信中のクライアントには接続が切れたように見えます。
`content_reader`が`false`を返した場合、何もしなければステータスは400になります(ボディがサイズ上限を超えていたときは413)。ほかのステータスを返したいときは自分でセットしてください。ボディの残りは読まずに接続を閉じるので、送信中のクライアントには接続が切れたように見えます。
> **Warning:** `HandlerWithContentReader`を使うと、`req.body`は**空のまま**です。ボディはコールバック内で自分で処理してください。
@@ -32,7 +32,7 @@ svr.Get("/api/data", [](const httplib::Request &req, httplib::Response &res) {
## 圧縮の優先順位
クライアントが複数の方式を受け入れる場合、Brotli → Zstd → gzipの順に選ばれます(ビルドで有効になっている中から)。クライアント側では気にせず、一番効率の良い方式で圧縮されます。
クライアントが複数の方式を受け入れる場合は、`Accept-Encoding`のq値がいちばん高い方式で圧縮します。q値が同じときは、ビルドで有効な方式の中からBrotli → gzip → Zstdの順に選びます。
## ストリーミングレスポンスも圧縮される
@@ -69,7 +69,7 @@ svr.set_static_file_compression_max_length(1024 * 1024);
どちらの境界も`0`で無効にできます。コンパイル時のデフォルトは`CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH`と`CPPHTTPLIB_STATIC_FILE_COMPRESSION_MAX_LENGTH`で決まります。
圧縮しても`Content-Length`は付いたままなので、`HEAD`は`GET`と同じサイズを返します。細かい挙動として、Rangeリクエストは非圧縮の表現から切り出して返し、`ETag`には`W/"...-gzip"`のように使われた圧縮方式が入ります。
圧縮しても`Content-Length`は付いたままなので、`HEAD`は`GET`と同じサイズを返します。細かい点が2つあります。Rangeリクエストには圧縮前のデータから該当範囲を切り出して返します。また、`ETag`には`W/"...-gzip"`のように、使った圧縮方式が入ります。
なお`set_content_provider()`で登録したコンテンツプロバイダは対象外です。圧縮器を通すと、内部バッファが埋まるまで書き込みが送出されず、ボディを少しずつ生成するプロバイダが止まってしまうためです。生成したボディを圧縮したい場合は`set_chunked_content_provider()`を使ってください。
+2 -2
View File
@@ -37,7 +37,7 @@ svr.Get("/me", [](const httplib::Request &req, httplib::Response &res) {
## よくある型
`std::string`、数値、構造体、`std::shared_ptr`など、コピーかムーブできる値なら何でも入れられます。
`std::string`、数値、構造体、`std::shared_ptr`など、コピーできる値なら何でも入れられます。
```cpp
res.user_data.set("user_id", std::string{"42"});
@@ -51,6 +51,6 @@ res.user_data.set("started_at", std::chrono::steady_clock::now());
## 注意点
`user_data`は`Response`に乗っています(`req.user_data`ではありません)。これは、ハンドラには`Response&`として可変参照が渡されるためです。一見不思議ですが、「ハンドラ間で共有する可変コンテキスト」として覚えておくと素直です。
`user_data`は`Response`に乗っています(`req.user_data`ではありません)。これは、ハンドラには`Response&`として可変参照が渡されるためです。一見不思議ですが、「ハンドラ間で共有する可変コンテキスト」だと考えると納得がいきます。
> **Warning:** `user_data.get<T>()`は型が一致しないと`nullptr`を返します。保存時と取得時で同じ型を指定してください。`AuthUser`で入れて`const AuthUser`で取ろうとすると失敗します。
@@ -48,7 +48,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
return httplib::Server::HandlerResponse::Unhandled;
});
svr.set_logger([](const auto &req, const auto &res) {
svr.set_logger([](const httplib::Request &req, const httplib::Response &res) {
auto *start = res.user_data.get<std::chrono::steady_clock::time_point>("start");
auto elapsed = start
? std::chrono::duration_cast<std::chrono::milliseconds>(
@@ -52,6 +52,6 @@ int main() {
## 処理中のリクエストの扱い
`stop()`を呼ぶと、新しい接続は受け付けなくなりますが、すでに処理中のリクエストは**最後まで実行**されます。その後、スレッドプールのワーカーが順次終了し、`listen()`から戻ってきます。これがグレースフルシャットダウンと呼ばれる理由です。
`stop()`を呼ぶと、新しい接続は受け付けなくなりますが、すでに動いているハンドラは**最後まで実行**されます。ただし、ストリーミングのようにコンテンツプロバイダで送っている途中のレスポンスは、その場で打ち切られます。その後、スレッドプールのワーカーが順次終了し、`listen()`から戻ってきます。これがグレースフルシャットダウンと呼ばれる理由です。
> **Warning:** `stop()`を呼んでから`listen()`が戻るまでには、処理中のリクエストが終わるのを待つ時間がかかります。タイムアウトを強制したい場合は、シャットダウン用のタイマーを別途用意するなど、アプリケーション側の工夫が必要です。
@@ -19,7 +19,7 @@ svr.Get("/", [](const auto &, auto &res) {
svr.listen("/tmp/httplib.sock", 80);
```
`set_address_family(AF_UNIX)`を呼んでから、`listen()`の第1引数にソケットファイルのパスを渡します。第2引数のポート番号は使われませんが、シグネチャの都合で何か渡す必要があります。
`set_address_family(AF_UNIX)`を呼んでから、`listen()`の第1引数にソケットファイルのパスを渡します。第2引数のポート番号は使われませんが、省略はできません。`0`を渡すと`listen()`が失敗するので、`0`以外の適当な値を渡してください。
## クライアント側
+1 -1
View File
@@ -55,7 +55,7 @@ httplib::SSLClient cli("api.example.com", 443,
auto res = cli.Get("/");
```
`Client`ではなく`SSLClient`を直接使う点に注意してください。秘密鍵にパスワードがある場合は第5引数で渡せます。
証明書と鍵のファイルを渡すだけなら、`httplib::Client cli("https://api.example.com", "client-cert.pem", "client-key.pem")`のように`Client`でも書けます。秘密鍵にパスワードがかかっている場合は`SSLClient`を使い、第5引数にパスワードを渡します。
クライアント側にも同じ`PemMemory`構造体があり、メモリ上のPEMからクライアント証明書を設定できます。
@@ -41,7 +41,7 @@ cli.connect();
デフォルトのPing間隔は、ビルド時のマクロ`CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND`で決まります。通常はそのままで問題ありませんが、特別なプロキシ環境に合わせて短くしたい場合は調整してください。
## PongはどうやってpIngに応答するか
## Pingへの応答(Pong)
WebSocketプロトコルでは、PingフレームにはPongフレームで応答することが決まっています。cpp-httplibは受信したPingに自動でPongを返すので、アプリケーションコード側で気にする必要はありません。
@@ -55,7 +55,7 @@ WebSocketプロトコルでは、PingフレームにはPongフレームで応答
短すぎると無駄なトラフィックになり、長すぎると接続が切れます。だいたい**接続が切れる時間の半分**くらいが目安です。
> **Warning:** Ping間隔を極端に短くすると、WebSocket接続ごとにバックグラウンドでスレッドが走るので、CPU負荷が上がります。接続数が多いサーバーでは控えめな値に設定しましょう。
> **Warning:** WebSocket接続ごとにバックグラウンドでスレッドが走るので、Ping間隔を極端に短くするとCPU負荷が上がります。接続数が多いサーバーでは控えめな値に設定しましょう。
## 無応答のピアを検出する
@@ -67,14 +67,14 @@ cli.set_websocket_max_missed_pongs(2); // 2回連続でPongが返ってこなけ
サーバー側にも同じ`set_websocket_max_missed_pongs()`があります。
たとえばPing間隔が30秒で`max_missed_pongs = 2`なら、無応答のピアは約60秒で検出され、`CloseStatus::GoingAway`(理由は`"pong timeout"`)で接続が閉じられます。
たとえばPing間隔が30秒で`max_missed_pongs = 2`なら、相手が応答しなくなってから60〜90秒で検出され、`CloseStatus::GoingAway`(理由は`"pong timeout"`)で接続が閉じられます。このとき`read()`で受信を待っていた場合は、`Fail`が返ります。
この仕組みは`read()`を呼んでPongフレームを消費したタイミングでカウンタがリセットされます。つまり通常のWebSocketクライアントのように`read()`をループで回していれば、特に意識することなく動きます。
カウンタは、`read()`がPongフレームを受け取ったタイミングでリセットされます。つまり、通常のWebSocketクライアントのように`read()`をループで回していれば、特に意識しなくても動きます。
### デフォルトは無効
`max_missed_pongs`のデフォルトは`0`で、これは「Pongが何回返ってこなくてもこの仕組みでは切断しない」という意味です。Ping自体は送られ続けますが、応答の有無はチェックされません。無応答ピアを検出したい場合は明示的に`1`以上を設定してください。
サーバ側は`0`のままでも接続が残り続けることはありません。ハンドラが`read()`を呼んでいる間は`CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND`(デフォルト**300秒 = 5分**)が保険として働きます。一方クライアント側にはこの保険がなく、読み取りタイムアウトを設定しない限り無期限に待つので、無応答ピアを検出する手段は`max_missed_pongs`だけです。どちらの側でも「**もっと速く**検出したい」ときに使うオプションでもあります。
サーバー側は`0`のままでも接続が残り続けることはありません。ハンドラが`read()`を呼んでいる間は`CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND`(デフォルト**300秒 = 5分**)が保険として働きます。一方クライアント側にはこの保険がなく、読み取りタイムアウトを設定しない限り無期限に待つので、無応答ピアを検出する手段は`max_missed_pongs`だけです。どちらの側でも「**もっと速く**検出したい」ときに使うオプションでもあります。
> 接続が閉じたときの処理は[W03. 接続クローズをハンドリングする](../w03-websocket-close)を参照してください。
+1 -1
View File
@@ -3,7 +3,7 @@ title: "cpp-httplib"
order: 0
---
[cpp-httplib](https://github.com/yhirose/cpp-httplib)は、C++用のHTTP/HTTPSライブラリです。[`httplib.h`](https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h) というヘッダーファイルを1枚コピーするだけで使えます。
[cpp-httplib](https://github.com/yhirose/cpp-httplib)は、C++用のHTTP/HTTPSライブラリです。[`httplib.h`](https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h)というヘッダーファイルを1枚コピーするだけで使えます。
C++でちょっとしたHTTPサーバーやクライアントが必要になったとき、すぐに動くものが欲しいですよね。cpp-httplibはまさにそのために作られました。サーバーもクライアントも、数行のコードで書き始められます。
+1 -9
View File
@@ -18,10 +18,6 @@ llama.cppのAPIを直接扱うとコードが長くなるので、薄いラッ
int main() {
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
// ... HTTPサーバーの構築・起動 ...
}
```
@@ -78,7 +74,7 @@ svr.Post("/translate",
});
```
`llm.chat()`は推論中に例外を投げることがあります(コンテキスト長の超過など)。`try/catch`で捕捉してエラーをJSONで返すことで、サーバーがクラッシュするのを防ぎます。
`llm.chat()`は推論中に例外を投げることがあります(コンテキスト長の超過など)。`try/catch`で捕捉して、エラーの内容をJSONで返します。捕捉しなくてもcpp-httplibが500を返してくれますが、何が起きたのかはクライアントに伝わりません。
## 2.3 全体のコード
@@ -111,10 +107,6 @@ int main() {
// 1章でダウンロードしたモデルをロード
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
// リクエストとレスポンスをログに記録
svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status
@@ -73,7 +73,7 @@ svr.Post("/translate/stream",
- `sink.os`に書き込んだ後、`sink.os.good()`でクライアントがまだ接続しているかを確認できます。切断されていたら`false`を返して推論を止めます
- 各トークンは`json(token).dump()`でJSON文字列としてエスケープしてから送ります。改行やクォートを含むトークンでも安全です
- `dump(-1, ' ', false, ...)`の最初の3つの引数はデフォルトと同じです。重要なのは第4引数の`json::error_handler_t::replace`です。LLMはトークンをサブワード単位で返すため、マルチバイト文字(日本語など)の途中でトークンが切れることがあります。不完全なUTF-8バイト列をそのまま`dump()`に渡すと例外が飛ぶので、`replace`で安全に置換します。ブラウザ側で結合されるため、表示上の問題はありません
- `try/catch`でラムダ全体を囲んでいます。`llm.chat()`はコンテキストウィンドウの超過などで例外を投げることがあります。ラムダ内で例外が未捕捉だとサーバーがクラッシュするので、エラーをSSEイベントとして返します
- `try/catch`でラムダ全体を囲んでいます。`llm.chat()`はコンテキストウィンドウの超過などで例外を投げることがあります。ラムダの中で例外を捕捉しないと、cpp-httplibは接続を切るだけなので、何が起きたのかクライアントにはわかりません。そこで、エラーをSSEイベントとして返します
- `data: [DONE]`はOpenAI APIと同じ慣習で、ストリームの終了をクライアントに伝えます
## 3.4 全体のコード
@@ -107,10 +107,6 @@ int main() {
// GGUFモデルをロード
auto llm = llamalib::Llama{"models/gemma-2-2b-it-Q4_K_M.gguf"};
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
// リクエストとレスポンスをログに記録
svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status
@@ -219,7 +219,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true);
cli.set_read_timeout(std::chrono::hours(1));
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename;
@@ -469,7 +468,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); // Hugging FaceはCDNにリダイレクトする
cli.set_read_timeout(std::chrono::hours(1)); // 大きなモデルに備えて長めに
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename;
@@ -539,10 +537,6 @@ int main() {
auto llm = llamalib::Llama{path};
std::mutex llm_mutex; // モデル切り替え中のアクセスを保護する
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status
<< std::endl;
-5
View File
@@ -939,7 +939,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); // Hugging FaceはCDNにリダイレクトする
cli.set_read_timeout(std::chrono::hours(1)); // 大きなモデルに備えて長めに
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename;
@@ -1008,10 +1007,6 @@ int main() {
}
auto llm = llamalib::Llama{path};
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status
<< std::endl;
@@ -17,7 +17,7 @@ order: 6
モデルは初回起動時に自動ダウンロードされるので、ユーザーに渡すのはバイナリ1つだけです。
## 6.1 webview/webview を導入する
## 6.1 webview/webviewを導入する
[webview/webview](https://github.com/webview/webview)は、OS標準のWebViewコンポーネント(macOSならWKWebView、LinuxならWebKitGTK、WindowsならWebView2)をC/C++から使えるようにするライブラリです。Electronのように独自ブラウザを同梱するわけではないので、バイナリサイズへの影響はほぼありません。
@@ -78,7 +78,7 @@ int main() {
5章の`signal_handler`は不要になります。デスクトップアプリではウインドウを閉じることがアプリの終了を意味するからです。
## 6.3 cpp-embedlib で静的ファイルを埋め込む
## 6.3 cpp-embedlibで静的ファイルを埋め込む
5章では`public/`ディレクトリからファイルを配信していました。これだと配布時に`public/`も一緒に渡す必要があります。[cpp-embedlib](https://github.com/yhirose/cpp-embedlib)を使うと、HTML・CSS・JavaScriptをバイナリに埋め込んで、配布物をバイナリ1つにまとめられます。
@@ -108,7 +108,7 @@ target_link_libraries(translate-app PRIVATE
`cpp_embedlib_add`は、`public/`配下のファイルをコンパイル時にバイナリに変換し、`WebAssets`という静的ライブラリを作ります。リンクすると`Web::FS`というオブジェクトから埋め込みファイルにアクセスできます。`cpp-embedlib-httplib`は`httplib::mount()`関数を提供するヘルパーライブラリです。
### set_mount_point を httplib::mount に置き換える
### set_mount_pointをhttplib::mountに置き換える
5章の`set_mount_point`をcpp-embedlibの`httplib::mount`に置き換えるだけです。
@@ -407,7 +407,6 @@ bool download_model(const ModelInfo &model,
std::function<bool(int)> progress_cb) {
httplib::Client cli("https://huggingface.co");
cli.set_follow_location(true); // Hugging FaceはCDNにリダイレクトする
cli.set_read_timeout(std::chrono::hours(1)); // 大きなモデルに備えて長めに
auto url = "/" + model.repo + "/resolve/main/" + model.filename;
auto path = get_models_dir() / model.filename;
@@ -469,10 +468,6 @@ int main() {
auto llm = llamalib::Llama{path};
std::mutex llm_mutex; // モデル切り替え中のアクセスを保護する
// LLM推論は時間がかかるのでタイムアウトを長めに設定(デフォルトは5秒)
svr.set_read_timeout(300);
svr.set_write_timeout(300);
svr.set_logger([](const auto &req, const auto &res) {
std::cout << req.method << " " << req.path << " -> " << res.status
<< std::endl;
+10 -6
View File
@@ -11,13 +11,17 @@ order: 7
## 7.1 ソースコードの場所
```ascii
llama.cpp/tools/server/
├── server.cpp # メインのサーバー実装
├── httplib.h # cpp-httplib(同梱版)
└── ...
llama.cpp/
├── tools/server/
│ ├── server.cpp # エントリポイント
│ ├── server-http.cpp # HTTPサーバー(cpp-httplibを使う層)
│ ├── server-context.cpp # 推論とスロットの管理
│ └── ...
└── vendor/cpp-httplib/
└── httplib.h # cpp-httplib(同梱版)
```
ファイルは1つの`server.cpp`にまとまっています。数千行ありますが、構造を知っていれば読むべき箇所は絞れます。
実装は役割ごとにファイルが分かれています。全体では2万行を超えますが、構造を知っていれば読むべき箇所は絞れます。
## 7.2 OpenAI互換API
@@ -141,7 +145,7 @@ LLMをアプリに組み込むとき、出力を確実にパースできるか
| SSEフォーマット | トークンのみ | OpenAI互換JSON |
| KVキャッシュ | 毎回クリア | prefixを再利用 |
| 構造化出力 | なし | JSON Schema/文法制約 |
| コード量 | 約200行 | 数千行 |
| コード量 | 約200行 | 2万行以上 |
私たちのコードがシンプルなのは、「デスクトップアプリで1人が使う」という前提があるからです。複数人に提供するサーバーや、既存のエコシステムと連携するサーバーを作るなら、`llama-server`の設計が参考になります。
@@ -113,7 +113,7 @@ CI(GitHub Actionsなど)でクロスプラットフォームビルドを自
- **クライアント**: HTTPS接続、リダイレクト追従、コンテンツレシーバーによる大容量ダウンロード、進捗コールバック
- **WebView連携**: `bind_to_any_port` + `listen_after_bind`でバックグラウンドスレッド化
cpp-httplibにはこの他にも、マルチパートによるファイルアップロード、認証、タイムアウト制御、圧縮、レンジリクエストなど便利な機能があります。詳しくは [A Tour of cpp-httplib](../../tour/) をご覧ください。
cpp-httplibにはこの他にも、マルチパートによるファイルアップロード、認証、タイムアウト制御、圧縮、レンジリクエストなど便利な機能があります。詳しくは[A Tour of cpp-httplib](../../tour/)をご覧ください。
これらのパターンは翻訳アプリに限りません。自分のC++ライブラリにWeb APIを付けたい、ブラウザUIで操作できるようにしたい、配布しやすいデスクトップアプリにしたい―そんなときに、この本がリファレンスになれば嬉しいです。
+9 -9
View File
@@ -5,7 +5,7 @@ order: 1
cpp-httplibを始めるのに必要なのは、`httplib.h`とC++コンパイラーだけです。ファイルをダウンロードして、Hello Worldサーバーを動かすところまでやってみましょう。
## httplib.h の入手
## httplib.hの入手
GitHubから直接ダウンロードできます。常に最新版を使ってください。
@@ -13,19 +13,19 @@ GitHubから直接ダウンロードできます。常に最新版を使って
curl -LO https://github.com/yhirose/cpp-httplib/raw/refs/tags/latest/httplib.h
```
ダウンロードした `httplib.h` をプロジェクトのディレクトリに置けば、準備完了です。
ダウンロードした`httplib.h`をプロジェクトのディレクトリに置けば、準備完了です。
## コンパイラーの準備
| OS | 開発環境 | セットアップ |
| -- | -------- | ------------ |
| macOS | Apple Clang | Xcode Command Line Tools (`xcode-select --install`) |
| Ubuntu | clang++ または g++ | `apt install clang` または `apt install g++` |
| Windows | MSVC | Visual Studio 2022 以降(C++ コンポーネントを含めてインストール) |
| Ubuntu | clang++またはg++ | `apt install clang`または`apt install g++` |
| Windows | MSVC | Visual Studio 2022以降(C++コンポーネントを含めてインストール) |
## Hello World サーバー
## Hello Worldサーバー
次のコードを `server.cpp` として保存しましょう。
次のコードを`server.cpp`として保存しましょう。
```cpp
#include "httplib.h"
@@ -70,16 +70,16 @@ cl /EHsc /std:c++17 server.cpp
server.exe
```
ブラウザで `http://localhost:8080` を開いてください。"Hello, World!" と表示されれば成功です。
ブラウザで`http://localhost:8080`を開いてください。"Hello, World!"と表示されれば成功です。
`curl` でも確認できます。
`curl`でも確認できます。
```sh
curl http://localhost:8080/
# Hello, World!
```
サーバーを停止するには、ターミナルで `Ctrl+C` を押します。
サーバーを停止するには、ターミナルで`Ctrl+C`を押します。
## 次のステップ
+21 -21
View File
@@ -3,7 +3,7 @@ title: "Basic Client"
order: 2
---
cpp-httplibはサーバーだけでなく、HTTPクライアント機能も備えています。`httplib::Client` を使って、GETやPOSTリクエストを送ってみましょう。
cpp-httplibはサーバーだけでなく、HTTPクライアント機能も備えています。`httplib::Client`を使って、GETやPOSTリクエストを送ってみましょう。
## テスト用サーバーの準備
@@ -77,9 +77,9 @@ int main() {
}
```
`httplib::Client` のコンストラクターにサーバーのアドレスを渡し、`Get()` でリクエストを送ります。戻り値の `res` からステータスコードやボディを取得できます。
`httplib::Client`のコンストラクターにサーバーのアドレスを渡し、`Get()`でリクエストを送ります。戻り値の`res`からステータスコードやボディを取得できます。
対応する `curl` コマンドはこうなります。
対応する`curl`コマンドはこうなります。
```sh
curl http://localhost:8080/hi
@@ -104,11 +104,11 @@ if (res) {
}
```
`res->body` は `std::string` なので、JSON レスポンスをパースしたい場合は [nlohmann/json](https://github.com/nlohmann/json) などの JSON ライブラリにそのまま渡せます。
`res->body`は`std::string`なので、JSONレスポンスをパースしたい場合は[nlohmann/json](https://github.com/nlohmann/json)などのJSONライブラリにそのまま渡せます。
## クエリパラメーター
GETリクエストにクエリパラメーターを付けるには、URLに直接書くか、`httplib::Params` を使います。
GETリクエストにクエリパラメーターを付けるには、URLに直接書くか、`httplib::Params`を使います。
```cpp
auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
@@ -117,7 +117,7 @@ if (res) {
}
```
`httplib::Params` を使うと、特殊文字のURLエンコードを自動で行ってくれます。
`httplib::Params`を使うと、特殊文字のURLエンコードを自動で行ってくれます。
```sh
curl "http://localhost:8080/search?q=cpp-httplib"
@@ -126,7 +126,7 @@ curl "http://localhost:8080/search?q=cpp-httplib"
## パスパラメーター
URLのパスに値を直接埋め込む場合も、クライアント側は特別なAPIは不要です。パスをそのまま `Get()` に渡すだけです。
URLのパスに値を直接埋め込む場合も、クライアント側は特別なAPIは不要です。パスをそのまま`Get()`に渡すだけです。
```cpp
auto res = cli.Get("/users/42");
@@ -140,7 +140,7 @@ curl http://localhost:8080/users/42
# User ID: 42
```
テスト用サーバーには、正規表現でIDを数字のみに絞った `/files/(\d+)` もあります。
テスト用サーバーには、正規表現でIDを数字のみに絞った`/files/(\d+)`もあります。
```cpp
auto res = cli.Get("/files/42");
@@ -154,11 +154,11 @@ curl http://localhost:8080/files/42
# File ID: 42
```
`/files/abc` のように数字以外を渡すと404が返ります。仕組みは次章で解説します。
`/files/abc`のように数字以外を渡すと404が返ります。仕組みは次章で解説します。
## リクエストヘッダー
カスタムHTTPヘッダーを付けるには、`httplib::Headers` を渡します。`Get()` や `Post()` のどちらでも使えます。
カスタムHTTPヘッダーを付けるには、`httplib::Headers`を渡します。`Get()`や`Post()`のどちらでも使えます。
```cpp
auto res = cli.Get("/hi", httplib::Headers{
@@ -172,7 +172,7 @@ curl -H "Authorization: Bearer my-token" http://localhost:8080/hi
## POSTリクエスト
テキストデータをPOSTしてみましょう。`Post()` の第2引数にボディ、第3引数にContent-Typeを指定します。
テキストデータをPOSTしてみましょう。`Post()`の第2引数にボディ、第3引数にContent-Typeを指定します。
```cpp
auto res = cli.Post("/post", "Hello, Server!", "text/plain");
@@ -182,7 +182,7 @@ if (res) {
}
```
テスト用サーバーの `/post` はボディをそのまま返すので、送った文字列がそのまま返ってきます。
テスト用サーバーの`/post`はボディをそのまま返すので、送った文字列がそのまま返ってきます。
```sh
curl -X POST -H "Content-Type: text/plain" -d "Hello, Server!" http://localhost:8080/post
@@ -191,7 +191,7 @@ curl -X POST -H "Content-Type: text/plain" -d "Hello, Server!" http://localhost:
## フォームデータの送信
HTMLフォームのように、キーと値のペアを送ることもできます。`httplib::Params` を使います。
HTMLフォームのように、キーと値のペアを送ることもできます。`httplib::Params`を使います。
```cpp
auto res = cli.Post("/submit", httplib::Params{
@@ -200,12 +200,12 @@ auto res = cli.Post("/submit", httplib::Params{
});
if (res) {
std::cout << res->body << std::endl;
// age = 30
// name = Alice
// age = 30
}
```
これは `application/x-www-form-urlencoded` 形式で送信されます。
これは`application/x-www-form-urlencoded`形式で送信されます。
```sh
curl -X POST -d "name=Alice&age=30" http://localhost:8080/submit
@@ -213,7 +213,7 @@ curl -X POST -d "name=Alice&age=30" http://localhost:8080/submit
## ファイルのPOST
ファイルをアップロードするには、`httplib::UploadFormDataItems` を使ってマルチパートフォームデータとして送信します。
ファイルをアップロードするには、`httplib::UploadFormDataItems`を使ってマルチパートフォームデータとして送信します。
```cpp
auto res = cli.Post("/upload", httplib::UploadFormDataItems{
@@ -224,7 +224,7 @@ if (res) {
}
```
`UploadFormDataItems` の各要素は `{name, content, filename, content_type}` の4つのフィールドで構成されます。
`UploadFormDataItems`の各要素は`{name, content, filename, content_type}`の4つのフィールドで構成されます。
```sh
curl -F "file=Hello, File!;filename=hello.txt;type=text/plain" http://localhost:8080/upload
@@ -232,7 +232,7 @@ curl -F "file=Hello, File!;filename=hello.txt;type=text/plain" http://localhost:
## エラーハンドリング
ネットワーク通信では、サーバーに接続できない場合があります。`res` が有効かどうかを必ず確認しましょう。
ネットワーク通信では、サーバーに接続できない場合があります。`res`が有効かどうかを必ず確認しましょう。
```cpp
httplib::Client cli("http://localhost:9999"); // 存在しないポート
@@ -241,7 +241,7 @@ auto res = cli.Get("/hi");
if (!res) {
// 接続エラー
std::cout << "Error: " << httplib::to_string(res.error()) << std::endl;
// Error: Connection
// Error: Could not establish connection
return 1;
}
@@ -256,8 +256,8 @@ std::cout << res->body << std::endl;
エラーには2つのレベルがあります。
- **接続エラー**: サーバーに到達できなかった場合。`res` が偽になり、`res.error()` でエラーの種類を取得できます
- **HTTPエラー**: サーバーからエラーステータス(404、500など)が返ってきた場合。`res` は真ですが、`res->status` を確認する必要があります
- **接続エラー**: サーバーに到達できなかった場合。`res`が偽になり、`res.error()`でエラーの種類を取得できます
- **HTTPエラー**: サーバーからエラーステータス(404、500など)が返ってきた場合。`res`は真ですが、`res->status`を確認する必要があります
## 次のステップ
+28 -28
View File
@@ -7,15 +7,15 @@ order: 3
## サーバーの起動
ルーティングを登録したら、最後に `svr.listen()` を呼んでサーバーを起動します。
ルーティングを登録したら、最後に`svr.listen()`を呼んでサーバーを起動します。
```cpp
svr.listen("0.0.0.0", 8080);
```
第1引数はホスト、第2引数はポート番号です。`"0.0.0.0"` を指定すると、すべてのネットワークインターフェースでリクエストを受け付けます。自分のマシンからのアクセスだけに限定したいときは `"127.0.0.1"` を使います。
第1引数はホスト、第2引数はポート番号です。`"0.0.0.0"`を指定すると、すべてのネットワークインターフェースでリクエストを受け付けます。自分のマシンからのアクセスだけに限定したいときは`"127.0.0.1"`を使います。
`listen()` はブロッキング呼び出しです。サーバーが停止するまで、この行から先には進みません。ターミナルで `Ctrl+C` を押すか、別スレッドから `svr.stop()` を呼ぶまでサーバーは動き続けます。
`listen()`はブロッキング呼び出しです。サーバーが停止するまで、この行から先には進みません。ターミナルで`Ctrl+C`を押すか、別スレッドから`svr.stop()`を呼ぶまでサーバーは動き続けます。
## ルーティング
@@ -29,7 +29,7 @@ svr.Get("/hi", [](const httplib::Request &req, httplib::Response &res) {
});
```
`svr.Get()` は、GETリクエストに対するハンドラーを登録します。第1引数がパス、第2引数がハンドラー関数です。`/hi` にGETリクエストが来たら、このラムダが呼ばれます。
`svr.Get()`は、GETリクエストに対するハンドラーを登録します。第1引数がパス、第2引数がハンドラー関数です。`/hi`にGETリクエストが来たら、このラムダが呼ばれます。
HTTPメソッドごとにメソッドが用意されています。
@@ -40,7 +40,7 @@ svr.Put("/path", handler); // PUT
svr.Delete("/path", handler); // DELETE
```
ハンドラーのシグネチャは `(const httplib::Request &req, httplib::Response &res)` です。`auto` を使って短く書くこともできます。
ハンドラーのシグネチャは`(const httplib::Request &req, httplib::Response &res)`です。`auto`を使って短く書くこともできます。
```cpp
svr.Get("/hi", [](const auto &req, auto &res) {
@@ -52,11 +52,11 @@ svr.Get("/hi", [](const auto &req, auto &res) {
## リクエストオブジェクト
ハンドラーの第1引数 `req` から、クライアントが送ってきた情報を読み取れます。
ハンドラーの第1引数`req`から、クライアントが送ってきた情報を読み取れます。
### ボディ
`req.body` でリクエストボディを取得できます。型は `std::string` です。
`req.body`でリクエストボディを取得できます。型は`std::string`です。
```cpp
svr.Post("/post", [](const auto &req, auto &res) {
@@ -67,7 +67,7 @@ svr.Post("/post", [](const auto &req, auto &res) {
### ヘッダー
`req.get_header_value()` でリクエストヘッダーの値を取得できます。
`req.get_header_value()`でリクエストヘッダーの値を取得できます。
```cpp
svr.Get("/check", [](const auto &req, auto &res) {
@@ -78,7 +78,7 @@ svr.Get("/check", [](const auto &req, auto &res) {
### クエリパラメーターとフォームデータ
`req.get_param_value()` でパラメーターを取得できます。GETのクエリパラメーターと、POSTのフォームデータの両方に使えます。
`req.get_param_value()`でパラメーターを取得できます。GETのクエリパラメーターと、POSTのフォームデータの両方に使えます。
```cpp
svr.Get("/search", [](const auto &req, auto &res) {
@@ -87,9 +87,9 @@ svr.Get("/search", [](const auto &req, auto &res) {
});
```
`/search?q=cpp-httplib` にアクセスすると、`q` の値は `"cpp-httplib"` になります。
`/search?q=cpp-httplib`にアクセスすると、`q`の値は`"cpp-httplib"`になります。
すべてのパラメーターをループで処理したいときは、`req.params` を使います。
すべてのパラメーターをループで処理したいときは、`req.params`を使います。
```cpp
svr.Post("/submit", [](const auto &req, auto &res) {
@@ -103,7 +103,7 @@ svr.Post("/submit", [](const auto &req, auto &res) {
### ファイルアップロード
マルチパートフォームでアップロードされたファイルは、`req.form.get_file()` で取得します。
マルチパートフォームでアップロードされたファイルは、`req.form.get_file()`で取得します。
```cpp
svr.Post("/upload", [](const auto &req, auto &res) {
@@ -113,11 +113,11 @@ svr.Post("/upload", [](const auto &req, auto &res) {
});
```
`f.filename` でファイル名、`f.content` でファイルの中身にアクセスできます。
`f.filename`でファイル名、`f.content`でファイルの中身にアクセスできます。
## パスパラメーター
URLの一部を変数として受け取りたいことがあります。たとえば `/users/42` の `42` を取得したい場合です。`:param` 記法を使うと、URLの一部をキャプチャできます。
URLの一部を変数として受け取りたいことがあります。たとえば`/users/42`の`42`を取得したい場合です。`:param`記法を使うと、URLの一部をキャプチャできます。
```cpp
svr.Get("/users/:id", [](const auto &req, auto &res) {
@@ -126,7 +126,7 @@ svr.Get("/users/:id", [](const auto &req, auto &res) {
});
```
`/users/42` にアクセスすると、`req.path_params.at("id")` は `"42"` を返します。`/users/100` なら `"100"` です。
`/users/42`にアクセスすると、`req.path_params.at("id")`は`"42"`を返します。`/users/100`なら`"100"`です。
複数のパスパラメーターも使えます。
@@ -140,7 +140,7 @@ svr.Get("/users/:user_id/posts/:post_id", [](const auto &req, auto &res) {
### 正規表現パターン
`:param` の代わりに正規表現をパスに書くこともできます。キャプチャグループの値は `req.matches` で取得します。型は `std::smatch` です。
`:param`の代わりに正規表現をパスに書くこともできます。キャプチャグループの値は`req.matches`で取得します。型は`std::smatch`です。
```cpp
// 数字のみのIDを受け付ける
@@ -150,15 +150,15 @@ svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
});
```
`/files/42` にはマッチしますが、`/files/abc` にはマッチしません。入力値を絞り込みたいときに便利です。
`/files/42`にはマッチしますが、`/files/abc`にはマッチしません。入力値を絞り込みたいときに便利です。
## レスポンスの組み立て
ハンドラーの第2引数 `res` を使って、クライアントに返すレスポンスを組み立てます。
ハンドラーの第2引数`res`を使って、クライアントに返すレスポンスを組み立てます。
### ボディとContent-Type
`res.set_content()` でボディとContent-Typeを設定します。これだけでステータスコード200のレスポンスが返ります。
`res.set_content()`でボディとContent-Typeを設定します。これだけでステータスコード200のレスポンスが返ります。
```cpp
svr.Get("/hi", [](const auto &req, auto &res) {
@@ -168,7 +168,7 @@ svr.Get("/hi", [](const auto &req, auto &res) {
### ステータスコード
ステータスコードを変えたいときは、`res.status` に代入します。
ステータスコードを変えたいときは、`res.status`に代入します。
```cpp
svr.Get("/not-found", [](const auto &req, auto &res) {
@@ -179,7 +179,7 @@ svr.Get("/not-found", [](const auto &req, auto &res) {
### レスポンスヘッダー
`res.set_header()` でレスポンスヘッダーを追加できます。
`res.set_header()`でレスポンスヘッダーを追加できます。
```cpp
svr.Get("/with-header", [](const auto &req, auto &res) {
@@ -200,7 +200,7 @@ svr.Get("/hi", [](const auto &, auto &res) {
});
```
最もシンプルなハンドラーです。リクエストの情報は使わないので、`req` の変数名を省略しています。`"Hello!"` というテキストをそのまま返します。
最もシンプルなハンドラーです。リクエストの情報は使わないので、`req`の変数名を省略しています。`"Hello!"`というテキストをそのまま返します。
### GET /search
@@ -211,7 +211,7 @@ svr.Get("/search", [](const auto &req, auto &res) {
});
```
`req.get_param_value("q")` でクエリパラメーター `q` の値を取り出します。`/search?q=cpp-httplib` なら、レスポンスは `"Query: cpp-httplib"` になります。
`req.get_param_value("q")`でクエリパラメーター`q`の値を取り出します。`/search?q=cpp-httplib`なら、レスポンスは`"Query: cpp-httplib"`になります。
### POST /post
@@ -221,7 +221,7 @@ svr.Post("/post", [](const auto &req, auto &res) {
});
```
クライアントが送ったリクエストボディを、そのままレスポンスとして返すエコーサーバーです。`req.body` にボディが丸ごと入っています。
クライアントが送ったリクエストボディを、そのままレスポンスとして返すエコーサーバーです。`req.body`にボディが丸ごと入っています。
### POST /submit
@@ -235,7 +235,7 @@ svr.Post("/submit", [](const auto &req, auto &res) {
});
```
フォームデータとして送られたキーと値のペアを、`req.params` でループ処理しています。構造化束縛 `auto &[key, val]` を使って、各ペアを取り出しています。
フォームデータとして送られたキーと値のペアを、`req.params`でループ処理しています。構造化束縛`auto &[key, val]`を使って、各ペアを取り出しています。
### POST /upload
@@ -247,7 +247,7 @@ svr.Post("/upload", [](const auto &req, auto &res) {
});
```
マルチパートフォームで送られたファイルを受け取ります。`req.form.get_file("file")` で `"file"` という名前のフィールドを取得し、`f.filename` と `f.content.size()` でファイル名とサイズを返しています。
マルチパートフォームで送られたファイルを受け取ります。`req.form.get_file("file")`で`"file"`という名前のフィールドを取得し、`f.filename`と`f.content.size()`でファイル名とサイズを返しています。
### GET /users/:id
@@ -258,7 +258,7 @@ svr.Get("/users/:id", [](const auto &req, auto &res) {
});
```
`:id` の部分がパスパラメーターです。`req.path_params.at("id")` で値を取り出しています。`/users/42` なら `"42"`、`/users/alice` なら `"alice"` が得られます。
`:id`の部分がパスパラメーターです。`req.path_params.at("id")`で値を取り出しています。`/users/42`なら`"42"`、`/users/alice`なら`"alice"`が得られます。
### GET /files/(\d+)
@@ -269,7 +269,7 @@ svr.Get(R"(/files/(\d+))", [](const auto &req, auto &res) {
});
```
正規表現 `(\d+)` で数字だけのIDにマッチします。`/files/42` にはマッチしますが、`/files/abc` は404になります。`req.matches[1]` で最初のキャプチャグループの値を取得しています。
正規表現`(\d+)`で数字だけのIDにマッチします。`/files/42`にはマッチしますが、`/files/abc`は404になります。`req.matches[1]`で最初のキャプチャグループの値を取得しています。
## 次のステップ
+13 -13
View File
@@ -3,11 +3,11 @@ title: "Static File Server"
order: 4
---
cpp-httplibは、HTMLやCSS、画像ファイルなどの静的ファイルも配信できます。面倒な設定は要りません。`set_mount_point()` を1行呼ぶだけです。
cpp-httplibは、HTMLやCSS、画像ファイルなどの静的ファイルも配信できます。面倒な設定は要りません。`set_mount_point()`を1行呼ぶだけです。
## set_mount_point の基本
## set_mount_pointの基本
さっそくやってみましょう。`set_mount_point()` は、URLのパスとローカルディレクトリを紐づけます。
さっそくやってみましょう。`set_mount_point()`は、URLのパスとローカルディレクトリを紐づけます。
```cpp
#include "httplib.h"
@@ -23,9 +23,9 @@ int main() {
}
```
第1引数がURLのマウントポイント、第2引数がローカルのディレクトリパスです。この例だと、`/` へのリクエストを `./html` ディレクトリから配信します。
第1引数がURLのマウントポイント、第2引数がローカルのディレクトリパスです。この例だと、`/`へのリクエストを`./html`ディレクトリから配信します。
試してみましょう。まず `html` ディレクトリを作って、`index.html` を置きます。
試してみましょう。まず`html`ディレクトリを作って、`index.html`を置きます。
```sh
mkdir html
@@ -49,9 +49,9 @@ g++ -std=c++17 -o server server.cpp -pthread
./server
```
ブラウザで `http://localhost:8080` を開いてみてください。`html/index.html` の内容が表示されるはずです。`http://localhost:8080/index.html` でも同じページが返ります。
ブラウザで`http://localhost:8080`を開いてみてください。`html/index.html`の内容が表示されるはずです。`http://localhost:8080/index.html`でも同じページが返ります。
もちろん、前章のクライアントコードや `curl` でもアクセスできますよ。
もちろん、前章のクライアントコードや`curl`でもアクセスできますよ。
```cpp
httplib::Client cli("http://localhost:8080");
@@ -67,7 +67,7 @@ curl http://localhost:8080
## 複数のマウントポイント
`set_mount_point()` は何回でも呼べます。URLのパスごとに、別々のディレクトリを割り当てられます。
`set_mount_point()`は何回でも呼べます。URLのパスごとに、別々のディレクトリを割り当てられます。
```cpp
svr.set_mount_point("/", "./public");
@@ -75,7 +75,7 @@ svr.set_mount_point("/assets", "./static/assets");
svr.set_mount_point("/docs", "./documentation");
```
`/assets/style.css` なら `./static/assets/style.css` を、`/docs/guide.html` なら `./documentation/guide.html` を配信します。
`/assets/style.css`なら`./static/assets/style.css`を、`/docs/guide.html`なら`./documentation/guide.html`を配信します。
## ハンドラーとの組み合わせ
@@ -95,11 +95,11 @@ svr.set_mount_point("/", "./public");
svr.listen("0.0.0.0", 8080);
```
ハンドラーが先に評価されます。`/api/hello` にはハンドラーが応答し、それ以外のパスは `./public` ディレクトリからファイルを探します。
リクエストが来ると、まず`./public`ディレクトリからファイルを探し、見つからなければハンドラーを呼びます。`./public/api/hello`というファイルを置かない限り、`/api/hello`にはハンドラーが応答します。
## レスポンスヘッダーの追加
`set_mount_point()` の第3引数にヘッダーを渡すと、静的ファイルのレスポンスにカスタムヘッダーを付けられます。キャッシュ制御に便利です。
`set_mount_point()`の第3引数にヘッダーを渡すと、静的ファイルのレスポンスにカスタムヘッダーを付けられます。キャッシュ制御に便利です。
```cpp
svr.set_mount_point("/", "./public", {
@@ -111,7 +111,7 @@ svr.set_mount_point("/", "./public", {
## 静的ファイルサーバー用のDockerファイル
cpp-httplibのリポジトリには、静的ファイルサーバー用の `Dockerfile` が含まれています。Docker Hubにビルド済みイメージも公開しているので、1コマンドで起動できます。
cpp-httplibのリポジトリには、静的ファイルサーバー用の`Dockerfile`が含まれています。Docker Hubにビルド済みイメージも公開しているので、1コマンドで起動できます。
```sh
> docker run -p 8080:80 -v ./my-site:/html yhirose4dockerhub/cpp-httplib-server
@@ -123,7 +123,7 @@ Press Ctrl+C to shutdown gracefully...
192.168.65.1 - - [22/Feb/2026:12:00:01 +0000] "GET /favicon.ico HTTP/1.1" 404 152 "-" "Mozilla/5.0 ..."
```
`./my-site` ディレクトリの中身が、そのままポート8080で配信されます。NGINXと同じログ形式で、アクセスの様子を確認できますよ。
`./my-site`ディレクトリの中身が、そのままポート8080で配信されます。NGINXと同じログ形式で、アクセスの様子を確認できますよ。
## 次のステップ
+3 -3
View File
@@ -19,7 +19,7 @@ order: 5
## コンパイルオプション
TLS機能を有効にするには、`CPPHTTPLIB_OPENSSL_SUPPORT` マクロを定義してコンパイルします。前章までのコンパイルコマンドに、いくつかオプションが増えます。
TLS機能を有効にするには、`CPPHTTPLIB_OPENSSL_SUPPORT`マクロを定義してコンパイルします。前章までのコンパイルコマンドに、いくつかオプションが増えます。
```sh
# macOS (Homebrew)
@@ -48,7 +48,7 @@ cl /EHsc /std:c++17 /DCPPHTTPLIB_OPENSSL_SUPPORT server.cpp libssl.lib libcrypto
## 動作確認
ちゃんと動くか確認してみましょう。`httplib::Client` にHTTPSのURLを渡してアクセスするだけのプログラムです。
ちゃんと動くか確認してみましょう。`httplib::Client`にHTTPSのURLを渡してアクセスするだけのプログラムです。
```cpp
#define CPPHTTPLIB_OPENSSL_SUPPORT
@@ -67,7 +67,7 @@ int main() {
}
```
コンパイルして実行してみてください。`Status: 200` と表示されれば、セットアップ完了です。
コンパイルして実行してみてください。`Status: 200`と表示されれば、セットアップ完了です。
## 他のTLSバックエンド
+7 -7
View File
@@ -3,7 +3,7 @@ title: "HTTPS Client"
order: 6
---
前章でOpenSSLのセットアップが済んだので、さっそくHTTPSクライアントを使ってみましょう。2章で使った `httplib::Client` がそのまま使えます。コンストラクタに `https://` 付きのURLを渡すだけです。
前章でOpenSSLのセットアップが済んだので、さっそくHTTPSクライアントを使ってみましょう。2章で使った`httplib::Client`がそのまま使えます。コンストラクタに`https://`付きのURLを渡すだけです。
## GETリクエスト
@@ -27,7 +27,7 @@ int main() {
}
```
2章では `httplib::Client cli("http://localhost:8080")` と書きましたよね。スキームを `https://` に変えるだけです。`Get()` や `Post()` など、2章で学んだAPIはすべてそのまま使えます。
2章では`httplib::Client cli("http://localhost:8080")`と書きましたよね。スキームを`https://`に変えるだけです。`Get()`や`Post()`など、2章で学んだAPIはすべてそのまま使えます。
```sh
curl https://nghttp2.org/
@@ -43,13 +43,13 @@ httplib::Client cli("https://localhost:8443");
## CA証明書の検証
`httplib::Client` はHTTPS接続時、デフォルトでサーバー証明書を検証します。信頼できるCA(認証局)が発行した証明書を持つサーバーにしか接続しません。
`httplib::Client`はHTTPS接続時、デフォルトでサーバー証明書を検証します。信頼できるCA(認証局)が発行した証明書を持つサーバーにしか接続しません。
CA証明書は、macOSならKeychain、LinuxならシステムのCA証明書ストア、WindowsならWindowsの証明書ストアから自動で読み込みます。ほとんどの場合、追加の設定は要りません。
### CA証明書ファイルの指定
環境によってはシステムのCA証明書が見つからないこともあります。そのときは `set_ca_cert_path()` でパスを直接指定してください。
環境によってはシステムのCA証明書が見つからないこともあります。そのときは`set_ca_cert_path()`でパスを直接指定してください。
```cpp
httplib::Client cli("https://nghttp2.org");
@@ -81,9 +81,9 @@ curl -k https://localhost:8443/
## リダイレクトの追跡
HTTPSサイトへのアクセスでは、リダイレクトに遭遇することがよくあります。たとえば `http://` から `https://` へ、あるいは `www` なしから `www` ありへ転送されるケースです。
HTTPSサイトへのアクセスでは、リダイレクトに遭遇することがよくあります。たとえば`http://`から`https://`へ、あるいは`www`なしから`www`ありへ転送されるケースです。
デフォルトではリダイレクトを追跡しません。リダイレクト先は `Location` ヘッダーで確認できます。
デフォルトではリダイレクトを追跡しません。リダイレクト先は`Location`ヘッダーで確認できます。
```cpp
httplib::Client cli("https://nghttp2.org");
@@ -99,7 +99,7 @@ if (res) {
curl https://nghttp2.org/httpbin/redirect/3
```
`set_follow_location(true)` を設定すると、リダイレクトを自動で追跡して、最終的なレスポンスを返してくれます。
`set_follow_location(true)`を設定すると、リダイレクトを自動で追跡して、最終的なレスポンスを返してくれます。
```cpp
httplib::Client cli("https://nghttp2.org");
+8 -8
View File
@@ -3,7 +3,7 @@ title: "HTTPS Server"
order: 7
---
前章ではHTTPSクライアントを使いました。今度は自分でHTTPSサーバーを立ててみましょう。3章の `httplib::Server` を `httplib::SSLServer` に置き換えるだけです。
前章ではHTTPSクライアントを使いました。今度は自分でHTTPSサーバーを立ててみましょう。3章の`httplib::Server`を`httplib::SSLServer`に置き換えるだけです。
ただし、TLSサーバーにはサーバー証明書と秘密鍵が必要です。まずはそこから準備しましょう。
@@ -41,24 +41,24 @@ int main() {
}
```
`httplib::SSLServer` のコンストラクタに証明書と秘密鍵のパスを渡すだけです。ルーティングの書き方は3章の `httplib::Server` とまったく同じですよ。
`httplib::SSLServer`のコンストラクタに証明書と秘密鍵のパスを渡すだけです。ルーティングの書き方は3章の`httplib::Server`とまったく同じですよ。
コンパイルして起動しましょう。
## 動作確認
サーバーが起動したら、`curl` でアクセスしてみましょう。自己署名証明書なので、`-k` オプションで証明書検証をスキップします。
サーバーが起動したら、`curl`でアクセスしてみましょう。自己署名証明書なので、`-k`オプションで証明書検証をスキップします。
```sh
curl -k https://localhost:8443/
# Hello, HTTPS!
```
ブラウザで `https://localhost:8443` を開くと、「この接続は安全ではありません」と警告が出ます。自己署名証明書なので正常です。気にせず進めてください。
ブラウザで`https://localhost:8443`を開くと、「この接続は安全ではありません」と警告が出ます。自己署名証明書なので正常です。気にせず進めてください。
## クライアントからの接続
前章の `httplib::Client` で接続してみましょう。自己署名証明書のサーバーに接続するには、2つの方法があります。
前章の`httplib::Client`で接続してみましょう。自己署名証明書のサーバーに接続するには、2つの方法があります。
### 方法1: 証明書検証を無効にする
@@ -82,7 +82,7 @@ int main() {
### 方法2: 自己署名証明書をCA証明書として指定する
こちらのほうが安全です。`cert.pem` をCA証明書として信頼するよう指定します。
こちらのほうが安全です。`cert.pem`をCA証明書として信頼するよう指定します。
```cpp
#define CPPHTTPLIB_OPENSSL_SUPPORT
@@ -102,9 +102,9 @@ int main() {
この方法なら、指定した証明書のサーバーにだけ接続を許可して、なりすましを防げます。テスト環境でもなるべくこちらを使いましょう。
## Server と SSLServer の比較
## ServerとSSLServerの比較
3章で学んだ `httplib::Server` のAPIは、`httplib::SSLServer` でもそのまま使えます。違いはコンストラクタだけです。
3章で学んだ`httplib::Server`のAPIは、`httplib::SSLServer`でもそのまま使えます。違いはコンストラクタだけです。
| | `httplib::Server` | `httplib::SSLServer` |
| -- | ------------------ | -------------------- |
+9 -9
View File
@@ -30,13 +30,13 @@ int main() {
}
```
`svr.WebSocket()` でWebSocketハンドラーを登録します。3章の `svr.Get()` や `svr.Post()` と同じ感覚ですね。
`svr.WebSocket()`でWebSocketハンドラーを登録します。3章の`svr.Get()`や`svr.Post()`と同じ感覚ですね。
ハンドラーの中では、`ws.read(msg)` でメッセージを待ちます。接続が閉じられると `read()` が `false` を返すので、ループを抜けます。`ws.send(msg)` でメッセージを送り返します。
ハンドラーの中では、`ws.read(msg)`でメッセージを待ちます。接続が閉じられると`read()`が`false`を返すので、ループを抜けます。`ws.send(msg)`でメッセージを送り返します。
## クライアントからの接続
`httplib::ws::WebSocketClient` を使ってサーバーに接続してみましょう。
`httplib::ws::WebSocketClient`を使ってサーバーに接続してみましょう。
```cpp
#include "httplib.h"
@@ -63,11 +63,11 @@ int main() {
}
```
コンストラクタには `ws://host:port/path` 形式のURLを渡します。`connect()` で接続を開始し、`send()` と `read()` でメッセージをやり取りします。
コンストラクタには`ws://host:port/path`形式のURLを渡します。`connect()`で接続を開始し、`send()`と`read()`でメッセージをやり取りします。
## テキストとバイナリ
WebSocketにはテキストとバイナリの2種類のメッセージがあります。`read()` の戻り値で区別できます。
WebSocketにはテキストとバイナリの2種類のメッセージがあります。`read()`の戻り値で区別できます。
```cpp
svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
@@ -90,7 +90,7 @@ svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
## リクエスト情報へのアクセス
ハンドラーの第1引数 `req` から、ハンドシェイク時のHTTPリクエスト情報を読み取れます。認証トークンの確認などに便利です。
ハンドラーの第1引数`req`から、ハンドシェイク時のHTTPリクエスト情報を読み取れます。認証トークンの確認などに便利です。
```cpp
svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws) {
@@ -111,7 +111,7 @@ svr.WebSocket("/ws", [](const httplib::Request &req, httplib::ws::WebSocket &ws)
## WSSで使う
HTTPS上のWebSocket(WSS)にも対応しています。サーバー側は `httplib::SSLServer` にWebSocketハンドラーを登録するだけです。
HTTPS上のWebSocket(WSS)にも対応しています。サーバー側は`httplib::SSLServer`にWebSocketハンドラーを登録するだけです。
```cpp
httplib::SSLServer svr("cert.pem", "key.pem");
@@ -126,7 +126,7 @@ svr.WebSocket("/ws", [](const httplib::Request &, httplib::ws::WebSocket &ws) {
svr.listen("0.0.0.0", 8443);
```
クライアント側は `wss://` スキームを使います。
クライアント側は`wss://`スキームを使います。
```cpp
httplib::ws::WebSocketClient client("wss://localhost:8443/ws");
@@ -134,7 +134,7 @@ httplib::ws::WebSocketClient client("wss://localhost:8443/ws");
## 次のステップ
WebSocketの基本がわかりましたね。ここまでで Tourは終わりです。
WebSocketの基本がわかりましたね。ここまででTourは終わりです。
次のページでは、Tourで取り上げなかった機能をまとめて紹介します。
+10 -10
View File
@@ -7,7 +7,7 @@ Tourお疲れさまでした! cpp-httplibの基本はひと通り押さえま
## Streaming API
LLMのストリーミング応答や大きなファイルのダウンロードでは、レスポンス全体をメモリに載せたくないですよね。`stream::Get()` を使えば、データをチャンクごとに処理できます。
LLMのストリーミング応答や大きなファイルのダウンロードでは、レスポンス全体をメモリに載せたくないですよね。`stream::Get()`を使えば、データをチャンクごとに処理できます。
```cpp
httplib::Client cli("http://localhost:11434");
@@ -21,7 +21,7 @@ if (result) {
}
```
`Get()` に `content_receiver` コールバックを渡す方法もあります。こちらはKeep-Aliveと併用できます。
`Get()`に`content_receiver`コールバックを渡す方法もあります。こちらはKeep-Aliveと併用できます。
```cpp
httplib::Client cli("http://localhost:8080");
@@ -32,7 +32,7 @@ cli.Get("/stream", [](const char *data, size_t len) {
});
```
サーバー側には `set_content_provider()` と `set_chunked_content_provider()` があります。サイズがわかっているなら前者、不明なら後者を使ってください。
サーバー側には`set_content_provider()`と`set_chunked_content_provider()`があります。サイズがわかっているなら前者、不明なら後者を使ってください。
```cpp
// サイズ指定あり(Content-Length が設定される)
@@ -50,12 +50,12 @@ svr.Get("/stream", [](const auto &, auto &res) {
res.set_chunked_content_provider("text/plain",
[](size_t offset, httplib::DataSink &sink) {
sink.write("chunk\n", 6);
return true; // falseを返すと終了
return true; // 終了するときはsink.done()を呼ぶ
});
});
```
大きなファイルのアップロードには `make_file_provider()` が便利です。ファイルを全部メモリに読み込まず、ストリーミングで送れます。
大きなファイルのアップロードには`make_file_provider()`が便利です。ファイルを全部メモリに読み込まず、ストリーミングで送れます。
```cpp
httplib::Client cli("http://localhost:8080");
@@ -67,7 +67,7 @@ auto res = cli.Post("/upload", {}, {}, {
## Server-Sent Events (SSE)
SSEクライアントも用意しています。自動再接続や `Last-Event-ID` による再開にも対応しています。
SSEクライアントも用意しています。自動再接続や`Last-Event-ID`による再開にも対応しています。
```cpp
httplib::Client cli("http://localhost:8080");
@@ -155,12 +155,12 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
});
svr.set_post_routing_handler([](const auto &req, auto &res) {
// レスポンスが返された後に実行される
// レスポンスを送信する直前に実行される
res.set_header("X-Server", "cpp-httplib");
});
```
`res.user_data` を使うと、ミドルウェアからハンドラーにデータを渡せます。認証トークンのデコード結果を共有するときに便利です。
`res.user_data`を使うと、ミドルウェアからハンドラーにデータを渡せます。認証トークンのデコード結果を共有するときに便利です。
```cpp
svr.set_pre_routing_handler([](const auto &req, auto &res) {
@@ -168,7 +168,7 @@ svr.set_pre_routing_handler([](const auto &req, auto &res) {
return httplib::Server::HandlerResponse::Unhandled;
});
svr.Get("/me", [](const auto &req, auto &res) {
svr.Get("/me", [](const httplib::Request &req, httplib::Response &res) {
auto *user = res.user_data.get<std::string>("auth_user");
res.set_content("Hello, " + *user, "text/plain");
});
@@ -205,7 +205,7 @@ TCP以外に、Unix Domain Socketでの通信にも対応しています。同
// サーバー
httplib::Server svr;
svr.set_address_family(AF_UNIX);
svr.listen("/tmp/httplib.sock", 0);
svr.listen("/tmp/httplib.sock", 80); // ポート番号は使われない(0以外を渡す)
```
```cpp
+2 -2
View File
@@ -5,11 +5,11 @@ order: 0
cpp-httplibの基本を、順番に学んでいくチュートリアルです。各章は前の章の内容を踏まえて進む構成なので、1章から順に読んでください。
1. [Getting Started](01-getting-started) — httplib.h の入手とHello Worldサーバー
1. [Getting Started](01-getting-started) — httplib.hの入手とHello Worldサーバー
2. [Basic Client](02-basic-client) — GET/POST・パスパラメーターのリクエスト送信
3. [Basic Server](03-basic-server) — ルーティング、パスパラメーター、レスポンスの組み立て
4. [Static File Server](04-static-file-server) — 静的ファイルの配信
5. [TLS Setup](05-tls-setup) — OpenSSL / mbedTLS のセットアップ
5. [TLS Setup](05-tls-setup) — OpenSSL / mbedTLSのセットアップ
6. [HTTPS Client](06-https-client) — HTTPSサイトへのリクエスト
7. [HTTPS Server](07-https-server) — HTTPSサーバーの構築
8. [WebSocket](08-websocket) — WebSocket通信の基本
+116 -41
View File
@@ -8,8 +8,8 @@
#ifndef CPPHTTPLIB_HTTPLIB_H
#define CPPHTTPLIB_HTTPLIB_H
#define CPPHTTPLIB_VERSION "0.60.0"
#define CPPHTTPLIB_VERSION_NUM "0x003c00"
#define CPPHTTPLIB_VERSION "0.61.0"
#define CPPHTTPLIB_VERSION_NUM "0x003d00"
#ifdef _WIN32
#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
@@ -1141,8 +1141,7 @@ private:
pointer operator->() const { return data_ + idx_; }
iterator_t &operator++() {
// Saturating, so that advancing past the last entry of a key (which
// get_multimap_value() does when asked for an out-of-range id) stays at
// Saturating, so that advancing past the last entry of a key stays at
// end() instead of running off the container.
if (idx_ >= size_) { return *this; }
++idx_;
@@ -3477,13 +3476,20 @@ inline bool is_numeric(const std::string &str) {
return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
}
// std::ranges::next(first, n, last) for C++11
template <typename It> inline It bounded_next(It first, size_t n, It last) {
for (; n > 0 && first != last; --n) {
++first;
}
return first;
}
inline size_t get_header_value_u64(const Headers &headers,
const std::string &key, size_t def,
size_t id, bool &is_invalid_value) {
is_invalid_value = false;
auto rng = headers.equal_range(key);
auto it = rng.first;
std::advance(it, static_cast<ssize_t>(id));
auto it = bounded_next(rng.first, id, rng.second);
if (it != rng.second) {
if (is_numeric(it->second)) {
// Parse at size_t width so an out-of-range Content-Length is reported
@@ -3968,6 +3974,7 @@ bool is_field_content(const std::string &s);
bool is_field_value(const std::string &s);
bool is_field_valid(const std::string &name, const std::string &value);
bool is_request_target(const std::string &s);
bool is_host(const std::string &s);
} // namespace fields
} // namespace detail
@@ -4412,6 +4419,8 @@ private:
namespace ws {
class WebSocketClient;
enum class Opcode : uint8_t {
Continuation = 0x0,
Text = 0x1,
@@ -4513,7 +4522,7 @@ public:
private:
friend class httplib::Server;
friend class WebSocketClient;
friend class httplib::ws::WebSocketClient;
WebSocket(
Stream &strm, const Request &req, bool is_server,
@@ -4916,9 +4925,12 @@ inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
msg.data += value;
has_data = true;
} else if (field == "id") {
// Empty id is valid (clears the last event ID)
msg.id = value;
has_id = true;
// An id that cannot be sent back as Last-Event-ID is ignored. Empty id is
// valid (clears the last event ID)
if (detail::fields::is_field_value(value)) {
msg.id = value;
has_id = true;
}
} else if (field == "retry") {
// Parse retry interval in milliseconds
// Per the SSE spec, a value that is not all ASCII digits is ignored.
@@ -4991,22 +5003,36 @@ inline void SSEClient::run_event_loop() {
SSEMessage current_msg;
auto has_data = false;
auto has_id = false;
auto first_line = true;
auto after_cr = false;
while (running_.load() && result.next()) {
// What is left in the buffer has no line ending
auto search_pos = buffer.size();
buffer.append(result.data(), result.size());
// Process complete lines in the buffer
// Process complete lines in the buffer. A line ends with \r\n, \n or \r
// per the SSE spec
size_t line_start = 0;
size_t newline_pos;
size_t eol_pos;
while ((newline_pos = buffer.find('\n', line_start)) !=
while ((eol_pos = buffer.find_first_of("\r\n", search_pos)) !=
std::string::npos) {
auto line = buffer.substr(line_start, newline_pos - line_start);
line_start = newline_pos + 1;
auto line = buffer.substr(line_start, eol_pos - line_start);
line_start = eol_pos + 1;
search_pos = line_start;
// Strip the \r of a CRLF line ending so that every field, including
// one without a colon, sees the same line
if (!line.empty() && line.back() == '\r') { line.pop_back(); }
// The \n of a \r\n may arrive in a later chunk than its \r
auto is_lf_of_crlf =
after_cr && line.empty() && buffer[eol_pos] == '\n';
after_cr = buffer[eol_pos] == '\r';
if (is_lf_of_crlf) { continue; }
// A UTF-8 BOM at the start of the stream is ignored per the SSE spec
if (first_line) {
first_line = false;
if (line.compare(0, 3, "\xEF\xBB\xBF") == 0) { line.erase(0, 3); }
}
// Parse the line and check if event is complete
auto event_complete = parse_sse_line(
@@ -8126,8 +8152,7 @@ inline const char *get_header_value(const Headers &headers,
}
auto rng = headers.equal_range(key);
auto it = rng.first;
std::advance(it, static_cast<ssize_t>(id));
auto it = bounded_next(rng.first, id, rng.second);
if (it != rng.second) { return it->second.c_str(); }
return def;
}
@@ -8180,8 +8205,7 @@ template <typename Map>
inline typename Map::mapped_type
get_multimap_value(const Map &m, const std::string &key, size_t id) {
auto rng = m.equal_range(key);
auto it = rng.first;
std::advance(it, static_cast<ssize_t>(id));
auto it = bounded_next(rng.first, id, rng.second);
if (it != rng.second) { return it->second; }
return typename Map::mapped_type();
}
@@ -8410,8 +8434,9 @@ read_content_without_length(Stream &strm, size_t payload_max_length,
if (n < 0) { return ReadContentResult::Error; }
// Check if adding this data would exceed the payload limit
if (r > payload_max_length ||
payload_max_length - r < static_cast<size_t>(n)) {
if (payload_max_length > 0 &&
(r > payload_max_length ||
payload_max_length - r < static_cast<size_t>(n))) {
return ReadContentResult::PayloadTooLarge;
}
@@ -8446,8 +8471,9 @@ inline ReadContentResult read_content_chunked(Stream &strm, T &x,
return ReadContentResult::Success;
}
if (total_len > payload_max_length ||
payload_max_length - total_len < static_cast<size_t>(n)) {
if (payload_max_length > 0 &&
(total_len > payload_max_length ||
payload_max_length - total_len < static_cast<size_t>(n))) {
return ReadContentResult::PayloadTooLarge;
}
@@ -9167,7 +9193,7 @@ inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
};
if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
if (s.size() > 7 && case_ignore::equal(s.substr(0, 6), "bytes=")) {
const auto pos = static_cast<size_t>(6);
const auto len = static_cast<size_t>(s.size() - 6);
auto all_valid_ranges = true;
@@ -9225,8 +9251,30 @@ inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
} catch (...) { return false; }
#endif
// Removes each quoted-string, honoring a quoted-pair (RFC 9110 Section 5.6.4)
inline std::string remove_quoted_strings(const std::string &s) {
std::string out;
auto in_quotes = false;
for (size_t i = 0; i < s.size(); i++) {
if (s[i] == '"') {
in_quotes = !in_quotes;
} else if (!in_quotes) {
out += s[i];
} else if (s[i] == '\\') {
i++;
}
}
return out;
}
inline bool parse_accept_header(const std::string &s,
std::vector<std::string> &content_types) {
// Parameter values are not used here, so a quoted-string is dropped rather
// than parsed: a ',' or ';' inside one must not be read as a delimiter.
if (s.find('"') != std::string::npos) {
return parse_accept_header(remove_quoted_strings(s), content_types);
}
content_types.clear();
// Empty string is considered valid (no preference)
@@ -9910,8 +9958,10 @@ inline bool range_error(Request &req, Response &res) {
last_pos = content_len;
}
// RFC 9110 14.1.2: a suffix-length longer than the representation
// selects the entire representation.
if (first_pos == -1) {
first_pos = content_len - last_pos;
first_pos = (std::max)(static_cast<ssize_t>(0), content_len - last_pos);
last_pos = content_len - 1;
}
@@ -10299,6 +10349,17 @@ inline bool is_request_target(const std::string &s) {
return std::all_of(s.begin(), s.end(), is_field_vchar);
}
// RFC 9110 §7.2: the bytes of uri-host [ ":" port ], i.e. unreserved,
// sub-delims, "%", ":" and the IP-literal brackets. An empty value is valid.
inline bool is_host(const std::string &s) {
return std::all_of(s.begin(), s.end(), [](char c) {
return is_ascii_alnum(c) || c == '-' || c == '.' || c == '_' || c == '~' ||
c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
c == '=' || c == '%' || c == ':' || c == '[' || c == ']';
});
}
} // namespace fields
inline bool perform_websocket_handshake(Stream &strm, Request &req,
@@ -10755,12 +10816,14 @@ inline bool match_hostname(const std::string &pattern,
// Compare each component with wildcard support
// Supports: "*" (full wildcard), "prefix*" (partial wildcard)
// https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
// Only the leftmost label may carry a wildcard (RFC 6125 6.4.3)
auto itr = pattern_components.begin();
for (const auto &h : host_components) {
auto &p = *itr;
if (!detail::case_ignore::equal(p, h) && p != "*") {
auto is_leftmost = itr == pattern_components.begin();
if (!detail::case_ignore::equal(p, h) && !(is_leftmost && p == "*")) {
bool partial_match = false;
if (!p.empty() && p[p.size() - 1] == '*') {
if (is_leftmost && !p.empty() && p[p.size() - 1] == '*') {
const auto prefix_length = p.size() - 1;
if (prefix_length == 0) {
partial_match = true;
@@ -10854,12 +10917,6 @@ inline bool verify_cert_with_windows_schannel(
auto chain_guard =
scope_exit([&] { CertFreeCertificateChain(chain_context); });
// Check if chain has errors
if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
out_error = chain_context->TrustStatus.dwErrorStatus;
return false;
}
// Verify SSL policy
SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
extra_policy_para.cbSize = sizeof(extra_policy_para);
@@ -11675,8 +11732,7 @@ inline bool Request::is_multipart_form_data() const {
inline std::string MultipartFormData::get_field(const std::string &key,
size_t id) const {
auto rng = fields.equal_range(key);
auto it = rng.first;
std::advance(it, static_cast<ssize_t>(id));
auto it = detail::bounded_next(rng.first, id, rng.second);
if (it != rng.second) { return it->second.content; }
return std::string();
}
@@ -14561,6 +14617,16 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
return write_response(strm, close_connection, req, res);
}
// RFC 9112 §3.2: Reject more than one Host field line or an invalid Host
// value, so that every recipient of the request sees the same authority.
if (req.get_header_value_count("Host") > 1 ||
!detail::fields::is_host(req.get_header_value("Host"))) {
connection_closed = true;
res.status = StatusCode::BadRequest_400;
output_error_log(Error::InvalidHeaders, &req);
return write_response(strm, close_connection, req, res);
}
// Check if the request URI doesn't exceed the limit
if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
connection_closed = true;
@@ -15878,7 +15944,8 @@ inline void ClientImpl::setup_redirect_client(ClientType &client) {
if (!proxy_host_.empty() && proxy_port_ != -1) {
client.set_proxy(proxy_host_, proxy_port_);
if (!proxy_basic_auth_username_.empty()) {
if (!proxy_basic_auth_username_.empty() ||
!proxy_basic_auth_password_.empty()) {
client.set_proxy_basic_auth(proxy_basic_auth_username_,
proxy_basic_auth_password_);
}
@@ -15981,8 +16048,8 @@ inline bool ClientImpl::write_request(Stream &strm, Request &req,
// otherwise NO_PROXY-matched requests, and requests inside a TLS tunnel,
// would leak proxy credentials to the destination server.
if (is_proxy_enabled_for_host(host_) && (!is_ssl() || is_connect)) {
if (!proxy_basic_auth_username_.empty() &&
!proxy_basic_auth_password_.empty() &&
if ((!proxy_basic_auth_username_.empty() ||
!proxy_basic_auth_password_.empty()) &&
!req.has_header("Proxy-Authorization")) {
req.headers.insert(make_basic_authentication_header(
proxy_basic_auth_username_, proxy_basic_auth_password_, true));
@@ -22841,6 +22908,14 @@ inline void WebSocket::start_heartbeat() {
if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
lock.unlock();
close(CloseStatus::GoingAway, "pong timeout");
// Wake a read() blocked on the unresponsive peer. Only the read side
// is shut down: a TLS backend answers the EOF with an alert, and
// writing it to a socket closed for writing raises SIGPIPE.
#ifdef _WIN32
shutdown(strm_.socket(), SD_RECEIVE);
#else
shutdown(strm_.socket(), SHUT_RD);
#endif
return;
}
lock.unlock();
+9
View File
@@ -153,6 +153,15 @@ if(HTTPLIB_IS_USING_OPENSSL)
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMAND_ERROR_IS_FATAL ANY
)
# cert_wildcard_san.pem: a leftmost wildcard next to one that is not
# leftmost. "*.leftmost.example.test" matches a single
# label; the wildcard in "www.*.example.test" must not be
# honoured.
execute_process(
COMMAND ${OPENSSL_COMMAND} req -x509 -key key.pem -sha256 -days 3650 -nodes -subj /CN=wildcard-san -addext subjectAltName=DNS:*.leftmost.example.test,DNS:www.*.example.test -out cert_wildcard_san.pem
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMAND_ERROR_IS_FATAL ANY
)
endif()
add_subdirectory(fuzzing)
+5
View File
@@ -37,3 +37,8 @@ openssl req -x509 -key key.pem -sha256 -days 3650 -nodes -subj "/CN=::1" -addext
# cert_san_types.pem: the bytes of each SAN read as the other type:
# DNS:a.zz is 97.46.122.122, IP:42.46.122.122 is "*.zz".
openssl req -x509 -key key.pem -sha256 -days 3650 -nodes -subj "/CN=san-types" -addext "subjectAltName=DNS:a.zz,IP:42.46.122.122" -out cert_san_types.pem
# cert_wildcard_san.pem: a leftmost wildcard next to one that is not leftmost.
# "*.leftmost.example.test" matches a single label; the
# wildcard in "www.*.example.test" must not be honoured.
openssl req -x509 -key key.pem -sha256 -days 3650 -nodes -subj "/CN=wildcard-san" -addext "subjectAltName=DNS:*.leftmost.example.test,DNS:www.*.example.test" -out cert_wildcard_san.pem
+12 -1
View File
@@ -146,6 +146,16 @@ cert_san_types_pem = custom_target(
command: [openssl, 'req', '-x509', '-key', '@INPUT@', '-sha256', '-days', '3650', '-nodes', '-subj', '/CN=san-types', '-addext', 'subjectAltName=DNS:a.zz,IP:42.46.122.122', '-out', '@OUTPUT@']
)
# cert_wildcard_san.pem: a leftmost wildcard next to one that is not leftmost.
# "*.leftmost.example.test" matches a single label; the wildcard in
# "www.*.example.test" must not be honoured.
cert_wildcard_san_pem = custom_target(
'cert_wildcard_san_pem',
input: key_pem,
output: 'cert_wildcard_san.pem',
command: [openssl, 'req', '-x509', '-key', '@INPUT@', '-sha256', '-days', '3650', '-nodes', '-subj', '/CN=wildcard-san', '-addext', 'subjectAltName=DNS:*.leftmost.example.test,DNS:www.*.example.test', '-out', '@OUTPUT@']
)
# Copy test files to the build directory
configure_file(input: 'ca-bundle.crt', output: 'ca-bundle.crt', copy: true)
configure_file(input: 'image.jpg', output: 'image.jpg', copy: true)
@@ -188,7 +198,8 @@ test(
client_encrypted_cert_pem,
cert_ip_cn_pem,
cert_ipv6_pem,
cert_san_types_pem
cert_san_types_pem,
cert_wildcard_san_pem
],
workdir: meson.current_build_dir(),
timeout: 300
+361 -22
View File
@@ -43,6 +43,7 @@ inline std::string u8_to_string(const char8_t *s) {
#define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
#define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
#define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
#define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
#define SERVER_PRIVATE_KEY_FILE "./key.pem"
#define CA_CERT_FILE "./ca-bundle.crt"
#define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
@@ -1118,6 +1119,39 @@ TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
}
// RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
// or ';' inside one does not end the list element or the parameter. Section
// 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
struct {
const char *value;
std::vector<std::string> expected;
} cases[] = {
{"text/html;profile=\"a,b\",application/json",
{"text/html", "application/json"}},
// A "q=" inside a quoted value is not the weight
{"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
{"text/html", "application/json"}},
// The weight after a quoted value still applies
{"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
{"application/json", "text/html"}},
{"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
{"application/json", "text/html"}},
{"text/html;profile=\"a\\\"b\",application/json",
{"text/html", "application/json"}},
// An escaped backslash does not escape the '"' after it
{"text/html;profile=\"a\\\\\",application/json",
{"text/html", "application/json"}},
};
for (const auto &c : cases) {
std::vector<std::string> result;
EXPECT_TRUE(detail::parse_accept_header(c.value, result))
<< "value: " << c.value;
EXPECT_EQ(c.expected, result) << "value: " << c.value;
}
}
TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
Server svr;
@@ -1889,6 +1923,28 @@ TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
}
TEST(HeadersOrderTest, HugeIdYieldsDefault) {
Request req;
req.set_header("X-First", "1");
req.set_header("X-Test", "2");
req.params.emplace("first", "1");
req.params.emplace("test", "2");
req.form.fields.emplace("first", FormField{"first", "1", {}});
req.form.fields.emplace("test", FormField{"test", "2", {}});
req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
// The second one is negative when read as a signed value
const auto max_id = (std::numeric_limits<size_t>::max)();
for (auto id : {max_id / 2, max_id}) {
EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
EXPECT_EQ("", req.get_param_value("test", id));
EXPECT_EQ("", req.form.get_field("test", id));
EXPECT_EQ("", req.form.get_file("test", id).content);
}
}
TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
Headers headers;
headers.emplace("Host", "example.com");
@@ -2032,6 +2088,13 @@ TEST(ParseHeaderValueTest, Range) {
EXPECT_EQ(0, ranges[0].first);
EXPECT_EQ(-1, ranges[0].second);
}
// RFC 9110 14.1: range unit names are case-insensitive.
for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
Ranges ranges;
EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
}
}
TEST(ParseAcceptEncoding1, AcceptEncoding) {
@@ -7242,8 +7305,21 @@ TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
}
TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
// RFC 9110 14.1.2: a suffix-length longer than the representation selects
// the entire representation.
for (auto range : {"bytes=-8", "bytes=-9999"}) {
auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
EXPECT_EQ(std::string("abcdefg"), res->body) << range;
}
}
TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
auto res =
cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
EXPECT_EQ("0", res->get_header_value("Content-Length"));
@@ -14176,9 +14252,8 @@ TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
<< " ssl_backend_error=" << res.ssl_backend_error();
}
// Windows, not the backend, decides on the chain: the error carries a
// CryptoAPI trust status, which no backend error for a self-signed
// certificate has.
// Windows, not the backend, decides on the chain: the error is a CryptoAPI
// policy status, which no backend reports for a self-signed certificate.
TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
ASSERT_TRUE(svr.is_valid());
@@ -14198,8 +14273,7 @@ TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
auto res = cli.Get("/");
ASSERT_FALSE(res);
EXPECT_EQ(Error::SSLServerVerification, res.error());
EXPECT_NE(0u, res.ssl_backend_error() & CERT_TRUST_IS_UNTRUSTED_ROOT)
<< "ssl_backend_error=" << res.ssl_backend_error();
EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
}
#endif
@@ -14929,6 +15003,61 @@ TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
<< "A DNS host must not be authenticated via an iPAddress SAN";
}
// RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
// "www.*.example.test" names one host and not every host under example.test.
TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
using namespace httplib::tls;
// SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
ASSERT_TRUE(svr.is_valid());
svr.Get("/test", [](const Request &, Response &res) {
res.set_content("ok", "text/plain");
});
auto port = svr.bind_to_any_port(HOST);
thread t([&]() { svr.listen_after_bind(); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
});
svr.wait_until_ready();
bool verify_callback_called = false;
bool leftmost_wildcard_matched = false;
bool wildcard_spanned_labels = true;
bool inner_wildcard_matched = true;
SSLClient cli(HOST, port);
cli.enable_server_certificate_verification(true);
cli.set_ca_cert_path(CA_CERT_FILE);
cli.set_connection_timeout(5);
cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
verify_callback_called = true;
if (!ctx.cert) return false;
leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
return true; // Accept for the purpose of this test
});
cli.Get("/test");
ASSERT_TRUE(verify_callback_called)
<< "Verify callback should have been called";
EXPECT_TRUE(leftmost_wildcard_matched)
<< "A leftmost wildcard should match a single label";
EXPECT_FALSE(wildcard_spanned_labels)
<< "A wildcard label must not match more than one label";
EXPECT_FALSE(inner_wildcard_matched)
<< "A wildcard outside the leftmost label must not be honoured";
}
// sans() must report each SAN entry under its own type.
TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
using namespace httplib::tls;
@@ -19619,6 +19748,58 @@ TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
}
TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
Server svr;
svr.Get("/test", [](const Request &, Response &res) {
res.set_content("ok", "text/plain");
});
auto port = svr.bind_to_any_port(HOST);
thread t = thread([&] { svr.listen_after_bind(); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
ASSERT_FALSE(svr.is_running());
});
svr.wait_until_ready();
auto status_line = [&](const std::string &host_lines) {
std::string res;
send_request(
5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
&res, port);
return res.substr(0, res.find("\r\n"));
};
const char *accepted[] = {
"Host: localhost\r\n",
"Host: a.example:8080\r\n",
"Host: my_service\r\n",
"Host: [::1]:8080\r\n",
"Host: [fe80::1%25eth0]\r\n",
"Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
};
for (auto host_lines : accepted) {
EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
}
const char *rejected[] = {
"Host: a.example\r\nHost: b.example\r\n",
"Host: a.example\r\nHost: a.example\r\n",
"Host: a@b.example\r\n",
"Host: a.example/b\r\n",
"Host: a.example\\b\r\n",
"Host: a.example?b\r\n",
"Host: a.example#b\r\n",
"Host: a.example b.example\r\n",
};
for (auto host_lines : rejected) {
EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
<< host_lines;
}
}
TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
Server svr;
@@ -21124,6 +21305,55 @@ TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
}
}
// A payload max length of 0 means no limit, however the body is framed.
TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
for (const char *response : {"HTTP/1.1 200 OK\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"5\r\nhello\r\n0\r\n\r\n",
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\n"
"\r\n"
"hello"}) {
with_single_response(response, [&](Client &cli) {
cli.set_payload_max_length(0);
auto res = cli.Get("/");
ASSERT_TRUE(res) << response;
EXPECT_EQ("hello", res->body) << response;
});
}
}
TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
Server svr;
svr.set_payload_max_length(0);
svr.Post("/echo", [](const Request &req, Response &res) {
res.set_content(req.body, "text/plain");
});
auto port = svr.bind_to_any_port(HOST);
thread t = thread([&] { svr.listen_after_bind(); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
ASSERT_FALSE(svr.is_running());
});
svr.wait_until_ready();
Client cli(HOST, port);
auto res = cli.Post(
"/echo",
[](size_t /*offset*/, DataSink &sink) {
sink.write("hello", 5);
sink.done();
return true;
},
"text/plain");
ASSERT_TRUE(res);
EXPECT_EQ(StatusCode::OK_200, res->status);
EXPECT_EQ("hello", res->body);
}
#ifdef CPPHTTPLIB_ZLIB_SUPPORT
TEST_F(OpenStreamTest, Gzip) {
Client cli("127.0.0.1", port_);
@@ -22677,6 +22907,47 @@ TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
EXPECT_EQ(msgs[0].data, "");
}
TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
auto msgs = parse("event: update\rdata: hello\r\r");
ASSERT_EQ(msgs.size(), 1u);
EXPECT_EQ(msgs[0].event, "update");
EXPECT_EQ(msgs[0].data, "hello");
}
TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
// Chunk boundaries fall inside every \r\n and right before the first one
std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
"\n\r", "\nevent: end\ndata: end\n\n"};
server_->Get("/split", [chunks](const Request &, Response &res) {
auto i = std::make_shared<size_t>(0);
res.set_chunked_content_provider(
"text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
if (*i == chunks.size()) {
sink.done();
} else {
sink.write(chunks[*i].data(), chunks[*i].size());
(*i)++;
}
return true;
});
});
auto msgs = collect("/split");
ASSERT_EQ(msgs.size(), 1u);
EXPECT_EQ(msgs[0].event, "update");
EXPECT_EQ(msgs[0].data, "hello");
}
TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
// Only a BOM at the start of the stream is ignored
auto msgs = parse("\xEF\xBB\xBF"
"data: first\n\n"
"\xEF\xBB\xBF"
"data: second\n\n");
ASSERT_EQ(msgs.size(), 1u);
EXPECT_EQ(msgs[0].data, "first");
}
TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
auto msgs = parse("unknown: value\ndata: hello\n\n");
ASSERT_EQ(msgs.size(), 1u);
@@ -22743,6 +23014,28 @@ TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
EXPECT_EQ(msgs[2].data, "not sent");
}
TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
// The first connection sets an id and then sends ids that cannot be carried
// in a header; the second echoes back the Last-Event-ID it was reconnected
// with
std::atomic<int> connection_count{0};
server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
if (connection_count++ == 0) {
res.set_content(std::string("id: 42\n\nid: a") + '\0' +
"b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
"text/event-stream");
} else {
res.set_content("data: " + req.get_header_value("Last-Event-ID") +
"\n\nevent: end\ndata: end\n\n",
"text/event-stream");
}
});
auto msgs = collect("/id-unsendable");
ASSERT_EQ(msgs.size(), 1u);
EXPECT_EQ(msgs[0].data, "42");
}
TEST_F(SSEParsingTest, CompleteEventParsing) {
auto msgs = parse("event: notification\nid: evt-42\n"
"data: {\"type\":\"alert\"}\nretry: 1000\n\n");
@@ -23194,20 +23487,25 @@ TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
// Test: A retry field of all ASCII digits sets the reconnection time
TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
std::atomic<int> connection_count{0};
std::mutex mutex;
std::condition_variable cv;
std::vector<std::chrono::steady_clock::time_point> connected_at;
server_->Get("/zero-retry",
[&connection_count](const Request &, Response &res) {
connection_count.fetch_add(1);
res.set_chunked_content_provider(
"text/event-stream", [](size_t offset, DataSink &sink) {
if (offset == 0) {
std::string event = "retry: 0\ndata: hello\n\n";
sink.write(event.data(), event.size());
}
return false;
});
});
server_->Get("/zero-retry", [&](const Request &, Response &res) {
{
std::lock_guard<std::mutex> lock(mutex);
connected_at.push_back(std::chrono::steady_clock::now());
cv.notify_all();
}
res.set_chunked_content_provider(
"text/event-stream", [](size_t offset, DataSink &sink) {
if (offset == 0) {
std::string event = "retry: 0\ndata: hello\n\n";
sink.write(event.data(), event.size());
}
return false;
});
});
Client client("localhost", get_port());
sse::SSEClient sse(client, "/zero-retry");
@@ -23215,13 +23513,21 @@ TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
sse.set_reconnect_interval(10000);
sse.start_async();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
{
std::unique_lock<std::mutex> lock(mutex);
cv.wait_for(lock, std::chrono::seconds(5),
[&] { return connected_at.size() >= 2; });
}
sse.stop();
// The server-supplied interval is applied, but never below 100ms, so
// "retry: 0" does not cause a busy reconnect loop
EXPECT_GE(connection_count.load(), 2);
EXPECT_LE(connection_count.load(), 10);
std::lock_guard<std::mutex> lock(mutex);
ASSERT_GE(connected_at.size(), 2u);
auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
connected_at[1] - connected_at[0])
.count();
EXPECT_GE(interval_ms, 100);
}
// Test: Last-Event-ID sent on reconnect
@@ -26669,6 +26975,39 @@ TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
EXPECT_TRUE(s.last_had_proxy_authz());
}
TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
std::atomic<int> hits{0};
std::atomic<int> hits_with_authz{0};
no_proxy_test::ScopedServer proxy_mock;
proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
hits++;
if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
if (req.target.find("/redir") != std::string::npos) {
res.set_redirect("http://other.example/landed");
} else {
res.set_content("via-proxy", "text/plain");
}
});
proxy_mock.listen();
for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
hits = 0;
hits_with_authz = 0;
Client cli("public.example", 80);
cli.set_proxy("127.0.0.1", proxy_mock.port());
cli.set_proxy_basic_auth(c.first, c.second);
cli.set_follow_location(true);
// The redirect to another host goes through the proxy as well
auto res = cli.Get("/redir");
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(2, hits.load());
EXPECT_EQ(2, hits_with_authz.load());
}
}
TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
ProxyAndTargetServers s;
auto cli = make_client("anything.test", s);
+8 -6
View File
@@ -179,18 +179,20 @@ protected:
TEST_F(WebSocketPongTimeoutTest, ClientDetectsNonResponsivePeer) {
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
client.set_websocket_max_missed_pongs(2);
// A read timeout asked for at runtime is reported as Timeout, so it cannot
// be mistaken for the Fail a pong timeout produces.
client.set_read_timeout(10);
ASSERT_TRUE(client.connect());
ASSERT_TRUE(client.is_open());
// Client pings every 1s (compile-time default in this test file).
// With max_missed_pongs = 2, the heartbeat thread should self-close within
// roughly 3s. Poll is_open() up to 6s.
// roughly 3s, and that has to end a read() already waiting on the peer.
auto start = std::chrono::steady_clock::now();
while (client.is_open() &&
std::chrono::steady_clock::now() - start < std::chrono::seconds(6)) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::string msg;
EXPECT_EQ(client.read(msg), ws::Fail);
EXPECT_TRUE(std::chrono::steady_clock::now() - start <
std::chrono::seconds(6));
EXPECT_FALSE(client.is_open());
}