Compare commits

..
3 Commits
Author SHA1 Message Date
Ed Addario 918fe468db Honor --chunks when using llama-perplexity with --kl-divergence (#32257)
* Honour --chunks when using --kl-divergence
* Fix formatting
2026-11-28 23:03:31 +01:00
IsNot a43d06ef90 unicode : speed up tokenization (#33164)
* unicode : speed up tokenization

* unicode : remove always-true asserts, pass byte_encode explicitly in test

* unicode : remove always-true asserts, pass byte_encode explicitly in test
2026-11-28 22:28:55 +01:00
Alessandro de Oliveira Faria (A.K.A.CABELO) cbb7652cd3 vendor : update cpp-httplib-0.68.0 (#33259)
[no ci]
2026-11-28 22:28:39 +01:00
7 changed files with 1687 additions and 522 deletions
+1 -1
View File
@@ -5,7 +5,7 @@ import os
import sys
import subprocess
HTTPLIB_VERSION = "refs/tags/v0.67.0"
HTTPLIB_VERSION = "refs/tags/v0.68.0"
JSON_VERSION = "v3.12.0"
# stb has no release tag, so we pin a commit (stb_image v2.32)
+35 -48
View File
@@ -2,6 +2,7 @@
#include "unicode-data.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <cstddef>
#include <cstdint>
@@ -159,23 +160,20 @@ static std::vector<unicode_cpt_flags> unicode_cpt_flags_array() {
return cpt_flags;
}
static std::unordered_map<uint8_t, std::string> unicode_byte_to_utf8_map() {
std::unordered_map<uint8_t, std::string> map;
static std::array<std::string, 256> unicode_byte_to_utf8_map() {
std::array<std::string, 256> map;
for (int ch = 0x21; ch <= 0x7E; ++ch) { // u'!' to u'~'
assert(0 <= ch && ch < 256);
map[ch] = unicode_cpt_to_utf8(ch);
}
for (int ch = 0xA1; ch <= 0xAC; ++ch) { // u'¡' to u'¬'
assert(0 <= ch && ch < 256);
map[ch] = unicode_cpt_to_utf8(ch);
}
for (int ch = 0xAE; ch <= 0xFF; ++ch) { // u'®' to u'ÿ'
assert(0 <= ch && ch < 256);
map[ch] = unicode_cpt_to_utf8(ch);
}
auto n = 0;
for (int ch = 0; ch < 256; ++ch) {
if (map.find(ch) == map.end()) {
if (map[ch].empty()) {
map[ch] = unicode_cpt_to_utf8(256 + n);
++n;
}
@@ -186,15 +184,12 @@ static std::unordered_map<uint8_t, std::string> unicode_byte_to_utf8_map() {
static std::unordered_map<std::string, uint8_t> unicode_utf8_to_byte_map() {
std::unordered_map<std::string, uint8_t> map;
for (int ch = 0x21; ch <= 0x7E; ++ch) { // u'!' to u'~'
assert(0 <= ch && ch < 256);
map[unicode_cpt_to_utf8(ch)] = ch;
}
for (int ch = 0xA1; ch <= 0xAC; ++ch) { // u'¡' to u'¬'
assert(0 <= ch && ch < 256);
map[unicode_cpt_to_utf8(ch)] = ch;
}
for (int ch = 0xAE; ch <= 0xFF; ++ch) { // u'®' to u'ÿ'
assert(0 <= ch && ch < 256);
map[unicode_cpt_to_utf8(ch)] = ch;
}
auto n = 0;
@@ -222,18 +217,13 @@ static std::vector<int> unicode_cpt_to_byte_map() {
static std::vector<std::string> unicode_byte_encoding_process(const std::vector<std::string> & bpe_words) {
std::vector<std::string> bpe_encoded_words;
bpe_encoded_words.reserve(bpe_words.size());
for (const auto & word : bpe_words) {
std::string text_utf;
auto utf_word = unicode_cpts_from_utf8(word);
for (size_t i = 0; i < utf_word.size(); ++i) {
text_utf += unicode_cpt_to_utf8(utf_word[i]);
}
std::string encoded_token;
for (char & c : text_utf) {
auto & encoded_token = bpe_encoded_words.emplace_back();
encoded_token.reserve(word.size() * 2);
for (const char & c : word) {
encoded_token += unicode_byte_to_utf8(c);
}
bpe_encoded_words.emplace_back(encoded_token);
}
return bpe_encoded_words;
}
@@ -1439,33 +1429,30 @@ static std::vector<size_t> unicode_regex_split_custom(const std::string & text,
// interface
//
static void unicode_cpt_to_utf8(uint32_t cpt, std::string & out) {
if (/* 0x00 <= cpt && */ cpt <= 0x7f) {
out.push_back(cpt);
} else if (cpt <= 0x7ff) {
out.push_back(0xc0 | ((cpt >> 6) & 0x1f));
out.push_back(0x80 | (cpt & 0x3f));
} else if (cpt <= 0xffff) {
out.push_back(0xe0 | ((cpt >> 12) & 0x0f));
out.push_back(0x80 | ((cpt >> 6) & 0x3f));
out.push_back(0x80 | (cpt & 0x3f));
} else if (cpt <= 0x10ffff) {
out.push_back(0xf0 | ((cpt >> 18) & 0x07));
out.push_back(0x80 | ((cpt >> 12) & 0x3f));
out.push_back(0x80 | ((cpt >> 6) & 0x3f));
out.push_back(0x80 | (cpt & 0x3f));
} else {
throw std::invalid_argument("invalid codepoint");
}
}
std::string unicode_cpt_to_utf8(uint32_t cpt) {
std::string result;
if (/* 0x00 <= cpt && */ cpt <= 0x7f) {
result.push_back(cpt);
return result;
}
if (0x80 <= cpt && cpt <= 0x7ff) {
result.push_back(0xc0 | ((cpt >> 6) & 0x1f));
result.push_back(0x80 | (cpt & 0x3f));
return result;
}
if (0x800 <= cpt && cpt <= 0xffff) {
result.push_back(0xe0 | ((cpt >> 12) & 0x0f));
result.push_back(0x80 | ((cpt >> 6) & 0x3f));
result.push_back(0x80 | (cpt & 0x3f));
return result;
}
if (0x10000 <= cpt && cpt <= 0x10ffff) {
result.push_back(0xf0 | ((cpt >> 18) & 0x07));
result.push_back(0x80 | ((cpt >> 12) & 0x3f));
result.push_back(0x80 | ((cpt >> 6) & 0x3f));
result.push_back(0x80 | (cpt & 0x3f));
return result;
}
throw std::invalid_argument("invalid codepoint");
unicode_cpt_to_utf8(cpt, result);
return result;
}
std::vector<uint32_t> unicode_cpts_normalize_nfd(const std::vector<uint32_t> & cpts) {
@@ -1599,9 +1586,9 @@ unicode_cpt_flags unicode_cpt_flags_from_utf8(const std::string & utf8) {
return unicode_cpt_flags_from_cpt(unicode_cpt_from_utf8(utf8, offset));
}
std::string unicode_byte_to_utf8(uint8_t byte) {
static std::unordered_map<uint8_t, std::string> map = unicode_byte_to_utf8_map();
return map.at(byte);
const std::string & unicode_byte_to_utf8(uint8_t byte) {
static const std::array<std::string, 256> map = unicode_byte_to_utf8_map();
return map[byte];
}
uint8_t unicode_utf8_to_byte(const std::string & utf8) {
@@ -1845,9 +1832,9 @@ std::vector<std::string> unicode_regex_split(const std::string & text, const std
size_t start = 0;
for (size_t & offset : bpe_offsets) {
bpe_words.emplace_back();
auto & word = bpe_words.emplace_back();
for (size_t i = start; i < start + offset; ++i) {
bpe_words.back() += unicode_cpt_to_utf8(cpts[i]);
unicode_cpt_to_utf8(cpts[i], word);
}
start += offset;
}
+3 -3
View File
@@ -102,9 +102,9 @@ std::vector<uint32_t> unicode_cpts_normalize_nfc(const std::vector<uint32_t> & c
unicode_cpt_flags unicode_cpt_flags_from_cpt (uint32_t cpt);
unicode_cpt_flags unicode_cpt_flags_from_utf8(const std::string & utf8);
std::string unicode_byte_to_utf8(uint8_t byte);
uint8_t unicode_utf8_to_byte(const std::string & utf8);
uint8_t unicode_cpt_to_byte (uint32_t cpt);
const std::string & unicode_byte_to_utf8(uint8_t byte);
uint8_t unicode_utf8_to_byte(const std::string & utf8);
uint8_t unicode_cpt_to_byte (uint32_t cpt);
uint32_t unicode_tolower(uint32_t cpt);
+22
View File
@@ -82,5 +82,27 @@ int main() {
success = false;
}
const std::vector<std::string> regex_exprs_bytes = { "\\p{L}+", "\\p{N}+", "\\s+" };
const std::string byte_encode_text = "\xc4\x80\xc4\xb1\xe0\xa4\x95\xf0\x9f\x98\x80";
const auto actual_byte_encode = unicode_regex_split(byte_encode_text, regex_exprs_bytes, true);
// GPT-2 byte-level encoding of byte_encode_text, independent of unicode_byte_to_utf8().
const std::vector<std::string> expected_byte_encode = {
"\xc3\x84\xc4\xa2\xc3\x84\xc2\xb1\xc3\xa0\xc2\xa4\xc4\xb7",
"\xc3\xb0\xc5\x81\xc4\xba\xc4\xa2",
};
if (actual_byte_encode != expected_byte_encode) {
fprintf(stderr, "unexpected byte-encoded split:");
for (const auto & piece : actual_byte_encode) {
fprintf(stderr, " [");
for (const unsigned char byte : piece) {
fprintf(stderr, "%02x", byte);
}
fprintf(stderr, "]");
}
fprintf(stderr, "\n");
success = false;
}
return success ? 0 : 1;
}
+4
View File
@@ -1719,6 +1719,10 @@ static void kl_divergence(llama_context * ctx, const common_params & params) {
return;
}
if (params.n_chunks >= 0) {
n_chunk = std::min(n_chunk, params.n_chunks);
}
const int n_batch = params.n_batch;
const int num_batches = (static_cast<int>(n_ctx) + n_batch - 1) / n_batch;
// Calculate n_seq based on the logits file's n_ctx, but cap it at what the context supports
+1337 -431
View File
File diff suppressed because it is too large Load Diff
+285 -39
View File
@@ -8,8 +8,8 @@
#ifndef CPPHTTPLIB_HTTPLIB_H
#define CPPHTTPLIB_HTTPLIB_H
#define CPPHTTPLIB_VERSION "0.67.0"
#define CPPHTTPLIB_VERSION_NUM "0x004300"
#define CPPHTTPLIB_VERSION "0.68.0"
#define CPPHTTPLIB_VERSION_NUM "0x004400"
#ifdef _WIN32
#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
@@ -34,6 +34,11 @@
#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
#endif
// Whether a Server starts with set_keep_alive_parking(true).
#ifndef CPPHTTPLIB_KEEPALIVE_PARKING
#define CPPHTTPLIB_KEEPALIVE_PARKING false
#endif
#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
#endif
@@ -291,6 +296,13 @@ static_assert(CPPHTTPLIB_MAX_LINE_LENGTH > 0,
#define CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS 0
#endif
// A WebSocket connection carries small messages each way, which Nagle's
// algorithm would hold back for the peer's delayed ACK (tens of milliseconds
// on Linux), so it sets TCP_NODELAY unless this is false.
#ifndef CPPHTTPLIB_WEBSOCKET_TCP_NODELAY
#define CPPHTTPLIB_WEBSOCKET_TCP_NODELAY true
#endif
/*
* Headers
*/
@@ -367,6 +379,8 @@ using socklen_t = int;
#ifdef __linux__
#include <resolv.h>
#undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
#include <sys/epoll.h>
#include <sys/eventfd.h>
#endif
#include <csignal>
#include <netinet/tcp.h>
@@ -386,6 +400,11 @@ using socket_t = int;
#include <TargetConditionals.h>
#endif
#if defined(__APPLE__) || defined(__FreeBSD__)
#define CPPHTTPLIB_KQUEUE_POLLER
#include <sys/event.h>
#endif
#include <algorithm>
#include <array>
#include <atomic>
@@ -906,8 +925,9 @@ inline bool parse_url(const std::string &url, UrlComponents &uc) {
size_t pos = 0;
auto sep = url.find("://");
if (sep != std::string::npos) {
uc.scheme = url.substr(0, sep);
if (sep < url.find_first_of("/?#")) {
// Schemes are case-insensitive (RFC 3986 3.1)
uc.scheme = case_ignore::to_lower(url.substr(0, sep));
// Scheme must be [a-z]+ only
if (uc.scheme.empty()) { return false; }
@@ -2278,6 +2298,8 @@ public:
using StartHandler = std::function<void()>;
using AcceptHandler = std::function<bool(socket_t sock)>;
using WebSocketHandler =
std::function<void(const Request &, ws::WebSocket &)>;
using SubProtocolSelector =
@@ -2343,6 +2365,8 @@ public:
Server &set_start_handler(StartHandler handler);
Server &set_accept_handler(AcceptHandler handler);
Server &set_logger(Logger logger);
Server &set_pre_compression_logger(Logger logger);
Server &set_error_logger(ErrorLogger error_logger);
@@ -2376,6 +2400,10 @@ public:
template <class Rep, class Period>
Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
// Keeps idle keep-alive connections in an event loop instead of a worker
// thread each. Call it before listen(). See README for what changes.
Server &set_keep_alive_parking(bool on);
Server &set_payload_max_length(size_t length);
Server &set_compress(bool on);
@@ -2391,6 +2419,8 @@ public:
Server &set_websocket_max_missed_pongs(int count);
Server &set_websocket_max_message_length(size_t length);
bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
int bind_to_any_port(const std::string &host, int socket_flags = 0);
bool listen_after_bind();
@@ -2412,8 +2442,9 @@ protected:
const std::function<void(Request &)> &setup_request,
bool *websocket_upgraded = nullptr);
// Runs the per-connection serving loop and stops an exception thrown by a
// user callback from escaping the worker thread.
// Runs a user callback, or the per-connection serving loop that calls user
// callbacks, and stops an exception thrown by one from escaping the
// server's threads.
//
// process_request() wraps only routing() and the hooks before a WebSocket
// upgrade in a try/catch. Content providers, the post-routing, error,
@@ -2446,6 +2477,13 @@ protected:
// stop() takes the listening socket away; listen() then waits for handlers
bool is_stopping() const { return svr_sock_ == INVALID_SOCKET; }
// See set_keep_alive_parking(). Defined in the implementation part.
struct KeepAliveConnection;
struct ParkingState;
std::unique_ptr<ParkingState> parking_;
bool keep_alive_parking_ = false;
bool idle_interval_set_ = false;
std::vector<std::string> trusted_proxies_;
size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
@@ -2466,6 +2504,8 @@ protected:
time_t websocket_ping_interval_sec_ =
CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
size_t websocket_max_message_length_ =
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
private:
using Handlers =
@@ -2505,6 +2545,12 @@ private:
SocketOptions socket_options) const;
int bind_internal(const std::string &host, int port, int socket_flags);
bool listen_internal();
bool accept_loop(TaskQueue &task_queue);
bool parking_loop(TaskQueue &task_queue);
bool admit_accepted_socket(socket_t sock) const;
struct PlainConnection;
void resume_connection(std::shared_ptr<KeepAliveConnection> conn);
bool abandon_listen_socket();
bool routing(Request &req, Response &res, Stream &strm,
bool skip_pre_routing);
@@ -2552,6 +2598,9 @@ private:
ContentReceiver multipart_receiver) const;
virtual bool process_and_close_socket(socket_t sock);
// The connection that parking_loop() keeps for a socket it has accepted.
virtual std::shared_ptr<KeepAliveConnection>
new_keep_alive_connection(socket_t sock);
void output_log(const Request &req, const Response &res) const;
void output_pre_compression_log(const Request &req,
@@ -2603,6 +2652,7 @@ private:
HandlerWithResponse pre_request_handler_;
Expect100ContinueHandler expect_100_continue_handler_;
StartHandler start_handler_;
AcceptHandler accept_handler_;
mutable std::mutex logger_mutex_;
Logger logger_;
@@ -3512,6 +3562,12 @@ public:
private:
bool process_and_close_socket(socket_t sock) override;
std::shared_ptr<KeepAliveConnection>
new_keep_alive_connection(socket_t sock) override;
struct TlsConnection;
// Creates a session and runs the handshake. Null on failure, which sets
// last_ssl_error_.
tls::session_t start_session(socket_t sock);
tls::ctx_t ctx_ = nullptr;
// update_certs_pem() replaces the certificates and CAs that handshakes read
@@ -3922,6 +3978,126 @@ EncodingType encoding_type(const Request &req, const Response &res,
EncodingType encoding_type(const Request &req, const Response &res);
// Creates a connected pair of stream sockets that child processes do not
// inherit. Windows has no socketpair(), so it is emulated there.
bool create_socket_pair(socket_t sv[2]);
// Ends a Poller's wait() from another thread. The poller watches fd() for
// readability, level-triggered, and calls drain() when it is reported.
class PollerWaker {
public:
~PollerWaker();
// An eventfd on Linux, a socket pair elsewhere.
bool open();
socket_t fd() const { return fd_; }
// An address inside the poller, which no caller's token can be.
uintptr_t token() const { return reinterpret_cast<uintptr_t>(this); }
// From any thread. While one is pending, later calls make no syscall.
void wake() noexcept;
void drain() noexcept;
private:
socket_t fd_ = INVALID_SOCKET;
socket_t pair_fd_ = INVALID_SOCKET; // the end wake() writes; none on Linux
std::atomic<bool> pending_{false};
};
// One-shot readiness notification for a reactor:
// - A delivered event disarms the descriptor; arm() it again to wait again.
// - A hang-up or an error counts as readable.
// - Only an unarmed descriptor may be armed, and an armed one must be
// disarmed before it is closed.
// - wake() may be called from any thread; the rest belongs to one thread.
class Poller {
public:
using Token = uintptr_t;
virtual ~Poller() = default;
virtual bool arm(socket_t fd, Token token) = 0;
virtual void disarm(socket_t fd) = 0;
// Fills `ready` in no particular order and returns whether wake() was
// called. A negative timeout waits until either happens.
virtual bool wait(int timeout_ms, std::vector<Token> &ready) = 0;
virtual void wake() noexcept = 0;
};
// poll() on POSIX, WSAPoll() on Windows. Works everywhere.
class PollPoller final : public Poller {
public:
// nullptr when the descriptors cannot be created.
static std::unique_ptr<Poller> create();
bool arm(socket_t fd, Token token) override;
void disarm(socket_t fd) override;
bool wait(int timeout_ms, std::vector<Token> &ready) override;
void wake() noexcept override { waker_.wake(); }
private:
PollPoller() = default;
void remove_at(size_t index);
PollerWaker waker_;
// fds_[0] is the waker's, which is always armed; tokens_[i] belongs to
// fds_[i].
std::vector<struct pollfd> fds_;
std::vector<Token> tokens_;
std::unordered_map<socket_t, size_t> index_;
};
#ifdef __linux__
// epoll with EPOLLONESHOT. Waits in O(ready) instead of O(armed).
class EpollPoller final : public Poller {
public:
// nullptr when the descriptors cannot be created.
static std::unique_ptr<Poller> create();
~EpollPoller() override;
bool arm(socket_t fd, Token token) override;
void disarm(socket_t fd) override;
bool wait(int timeout_ms, std::vector<Token> &ready) override;
void wake() noexcept override { waker_.wake(); }
private:
EpollPoller() = default;
int epfd_ = -1;
PollerWaker waker_; // always armed
std::vector<struct epoll_event> events_;
};
#endif
#ifdef CPPHTTPLIB_KQUEUE_POLLER
// kqueue with EV_ONESHOT. Waits in O(ready) instead of O(armed).
class KqueuePoller final : public Poller {
public:
// nullptr when the descriptors cannot be created.
static std::unique_ptr<Poller> create();
~KqueuePoller() override;
bool arm(socket_t fd, Token token) override;
void disarm(socket_t fd) override;
bool wait(int timeout_ms, std::vector<Token> &ready) override;
void wake() noexcept override { waker_.wake(); }
private:
KqueuePoller() = default;
int kq_ = -1;
PollerWaker waker_; // always armed
std::vector<struct kevent> events_;
};
#endif
// The best poller for this platform, or nullptr when it cannot be created.
std::unique_ptr<Poller> make_poller();
class BufferStream final : public Stream {
public:
BufferStream() = default;
@@ -4701,6 +4877,51 @@ private:
#endif
};
namespace impl {
bool is_valid_utf8(const std::string &s);
// A frame, a failure (the connection cannot be read on), a timeout with the
// stream still usable, or a frame the peer should not have sent: one that
// breaks the protocol, or one longer than the limit.
enum class FrameRead { Ok, Fail, Timeout, ProtocolError, TooBig };
// The settings a Server or WebSocketClient gives each WebSocket it creates
struct Options {
time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
size_t max_message_length = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
};
// A frame read in as many calls as it takes. A timeout leaves what was read
// so far in place, and the next read() goes on from there, so the stream is
// usable after a timeout wherever in a frame it lands.
class FrameReader {
public:
FrameRead read(Stream &strm, Opcode &opcode, std::string &payload, bool &fin,
bool expect_masked, size_t max_len);
// Whether part of a frame has been read and the rest is still to come
bool begun() const { return have_ > 0; }
private:
void reset();
uint8_t head_[14] = {0}; // FIN + opcode, MASK + length, its extension, key
size_t have_ = 0; // bytes of the header read so far
size_t need_ = 2; // bytes of the header, once the second is read
bool sized_ = false; // the header is whole and its length checked
size_t len_ = 0; // the payload's length, once sized_
std::string payload_;
};
// A whole frame read in one go: a timeout before any of it came is reported,
// and one that cuts it short is a failure.
FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
std::string &payload, bool &fin,
bool expect_masked, size_t max_len);
} // namespace impl
class WebSocket {
public:
WebSocket(const WebSocket &) = delete;
@@ -4715,9 +4936,18 @@ public:
const Request &request() const;
bool is_open() const;
// Why the connection ended, once read() has returned Fail (RFC 6455 7.1.5,
// 7.1.6): the code and reason of the peer's Close, NoStatus when it had no
// code, ProtocolError when it was malformed, and Abnormal when none came.
// After a close() of our own, the peer's reply is what is reported.
CloseStatus close_status() const;
std::string close_reason() const;
// Bound how long read() waits before returning Timeout. 0 waits forever.
// A server handler owns its connection's timeout this way; a client sets it
// through WebSocketClient. Safe to call while another thread is in read().
// It lands anywhere, inside a message too: what was read of it is kept,
// and the next read() goes on from there.
//
// Only a timeout set here is reported as Timeout. The compile-time default
// (CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND) is a backstop rather
@@ -4731,27 +4961,25 @@ private:
friend class httplib::Server;
friend class httplib::ws::WebSocketClient;
WebSocket(
Stream &strm, const Request &req, bool is_server,
time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS,
std::function<bool()> server_stopping = nullptr)
WebSocket(Stream &strm, const Request &req, bool is_server,
const impl::Options &options,
std::function<bool()> server_stopping = nullptr)
: strm_(strm), req_(req), is_server_(is_server),
ping_interval_sec_(ping_interval_sec),
max_missed_pongs_(max_missed_pongs),
ping_interval_sec_(options.ping_interval_sec),
max_missed_pongs_(options.max_missed_pongs),
max_message_length_(options.max_message_length),
server_stopping_(std::move(server_stopping)) {
interrupt_reads();
start_heartbeat();
}
WebSocket(
std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS,
std::function<bool()> server_stopping = nullptr)
WebSocket(std::unique_ptr<Stream> &&owned_strm, const Request &req,
bool is_server, const impl::Options &options,
std::function<bool()> server_stopping = nullptr)
: strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
is_server_(is_server), ping_interval_sec_(ping_interval_sec),
max_missed_pongs_(max_missed_pongs),
is_server_(is_server), ping_interval_sec_(options.ping_interval_sec),
max_missed_pongs_(options.max_missed_pongs),
max_message_length_(options.max_message_length),
server_stopping_(std::move(server_stopping)) {
interrupt_reads();
start_heartbeat();
@@ -4763,6 +4991,8 @@ private:
}
void start_heartbeat();
bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
bool send_close(const std::string &payload);
void set_close_status(const std::string &payload);
Stream &strm_;
std::unique_ptr<Stream> owned_strm_;
@@ -4770,6 +5000,8 @@ private:
bool is_server_;
time_t ping_interval_sec_;
int max_missed_pongs_;
// The largest frame or message read() accepts; 0 means no limit
size_t max_message_length_;
int unacked_pings_ = 0;
std::atomic<bool> closed_{false};
// Set when the peer stopped answering pings, to end a read() waiting on it
@@ -4782,10 +5014,20 @@ private:
std::atomic<bool> read_timeout_set_{false};
std::mutex write_mutex_;
// Owned by whichever thread is parsing frames off strm_. Only one thread
// may do so: read_websocket_frame() reads a payload until it has the whole
// declared length, so a second parser stealing bytes silently corrupts the
// message the first one is assembling.
// may do so: a frame is read until it has the whole declared length,
// across several read() calls when a timeout lands inside it (frames_
// below), so a second parser stealing bytes silently corrupts the message
// the first one is assembling.
std::mutex read_mutex_;
// What read() has of the frame and the message it has not finished, kept
// across a timeout. Guarded by read_mutex_.
impl::FrameReader frames_;
std::string message_;
ReadResult message_kind_ = Fail; // Text or Binary while one is assembled
// The peer's Close, set once under read_mutex_. close_reason_ is written
// before close_status_ leaves Abnormal and is not changed after.
std::atomic<CloseStatus> close_status_{CloseStatus::Abnormal};
std::string close_reason_;
std::thread ping_thread_;
std::mutex ping_mutex_;
std::condition_variable ping_cv_;
@@ -4809,6 +5051,8 @@ public:
void close(CloseStatus status = CloseStatus::Normal,
const std::string &reason = "");
bool is_open() const;
CloseStatus close_status() const;
std::string close_reason() const;
const std::string &subprotocol() const;
void set_read_timeout(time_t sec, time_t usec = 0);
template <class Rep, class Period>
@@ -4820,6 +5064,7 @@ public:
void set_websocket_ping_interval(time_t sec);
void set_websocket_max_missed_pongs(int count);
void set_websocket_max_message_length(size_t length);
void set_tcp_nodelay(bool on);
void set_address_family(int family);
void set_ipv6_v6only(bool on);
@@ -4870,6 +5115,9 @@ public:
std::function<SSLVerifierResponse(tls::session_t)> verifier);
void set_proxy_digest_auth(const std::string &username,
const std::string &password);
#ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
void enable_windows_certificate_verification(bool enabled);
#endif
#endif
private:
@@ -4899,8 +5147,10 @@ private:
time_t websocket_ping_interval_sec_ =
CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
size_t websocket_max_message_length_ =
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
int address_family_ = AF_UNSPEC;
bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
bool tcp_nodelay_ = CPPHTTPLIB_WEBSOCKET_TCP_NODELAY;
bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
SocketOptions socket_options_ = nullptr;
time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
@@ -4942,6 +5192,10 @@ private:
std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
std::string proxy_digest_auth_username_;
std::string proxy_digest_auth_password_;
#ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
bool enable_windows_cert_verification_ = true;
bool server_certificate_verifier_set_ = false;
#endif
#endif
};
@@ -4974,23 +5228,15 @@ inline void WebSocketClient::set_connection_timeout(
});
}
namespace impl {
bool is_valid_utf8(const std::string &s);
// Three states, because a failure that consumed bytes and one that consumed
// none are not the same thing: the first has left the stream in the middle of
// a frame and the connection cannot be reused, the second can just be retried.
enum class FrameRead { Ok, Fail, Timeout };
FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
std::string &payload, bool &fin,
bool expect_masked, size_t max_len);
} // namespace impl
} // namespace ws
namespace detail {
bool write_websocket_frame(Stream &strm, ws::Opcode opcode, const char *data,
size_t len, bool fin, bool mask);
} // namespace detail
} // namespace httplib