|
|
@@ -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.69.0"
|
|
|
+#define CPPHTTPLIB_VERSION_NUM "0x004500"
|
|
|
|
|
|
#ifdef _WIN32
|
|
|
#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
|
|
|
@@ -565,6 +565,13 @@ using socket_t = int;
|
|
|
#define CPPHTTPLIB_MBEDTLS_V3
|
|
|
#endif
|
|
|
|
|
|
+// SSLServer (and SSLClients on several threads) use Mbed TLS concurrently.
|
|
|
+#if !defined(MBEDTLS_THREADING_C) && \
|
|
|
+ !defined(CPPHTTPLIB_MBEDTLS_SINGLE_THREADED)
|
|
|
+#error \
|
|
|
+ "Mbed TLS must be built with MBEDTLS_THREADING_C. Define CPPHTTPLIB_MBEDTLS_SINGLE_THREADED if it is only ever used from one thread."
|
|
|
+#endif
|
|
|
+
|
|
|
#endif // CPPHTTPLIB_MBEDTLS_SUPPORT
|
|
|
|
|
|
#ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
|
|
|
@@ -925,7 +932,7 @@ inline bool parse_url(const std::string &url, UrlComponents &uc) {
|
|
|
size_t pos = 0;
|
|
|
|
|
|
auto sep = url.find("://");
|
|
|
- if (sep != std::string::npos) {
|
|
|
+ if (sep < url.find_first_of("/?#")) {
|
|
|
// Schemes are case-insensitive (RFC 3986 3.1)
|
|
|
uc.scheme = case_ignore::to_lower(url.substr(0, sep));
|
|
|
|
|
|
@@ -2298,6 +2305,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 =
|
|
|
@@ -2363,6 +2372,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);
|
|
|
@@ -2415,6 +2426,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();
|
|
|
@@ -2436,8 +2449,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,
|
|
|
@@ -2497,6 +2511,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 =
|
|
|
@@ -2538,7 +2554,7 @@ private:
|
|
|
bool listen_internal();
|
|
|
bool accept_loop(TaskQueue &task_queue);
|
|
|
bool parking_loop(TaskQueue &task_queue);
|
|
|
- void prepare_accepted_socket(socket_t sock) const;
|
|
|
+ bool admit_accepted_socket(socket_t sock) const;
|
|
|
struct PlainConnection;
|
|
|
void resume_connection(std::shared_ptr<KeepAliveConnection> conn);
|
|
|
bool abandon_listen_socket();
|
|
|
@@ -2643,6 +2659,7 @@ private:
|
|
|
HandlerWithResponse pre_request_handler_;
|
|
|
Expect100ContinueHandler expect_100_continue_handler_;
|
|
|
StartHandler start_handler_;
|
|
|
+ AcceptHandler accept_handler_;
|
|
|
|
|
|
mutable std::mutex logger_mutex_;
|
|
|
Logger logger_;
|
|
|
@@ -4871,9 +4888,17 @@ namespace impl {
|
|
|
|
|
|
bool is_valid_utf8(const std::string &s);
|
|
|
|
|
|
-// Three states: a frame, a failure (the connection cannot be read on), or a
|
|
|
-// timeout with the stream still usable.
|
|
|
-enum class FrameRead { Ok, Fail, Timeout };
|
|
|
+// 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
|
|
|
@@ -4918,6 +4943,13 @@ 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().
|
|
|
@@ -4936,27 +4968,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();
|
|
|
@@ -4968,6 +4998,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_;
|
|
|
@@ -4975,6 +5007,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
|
|
|
@@ -4997,6 +5031,10 @@ private:
|
|
|
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_;
|
|
|
@@ -5020,6 +5058,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>
|
|
|
@@ -5031,6 +5071,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);
|
|
|
@@ -5113,6 +5154,8 @@ 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_WEBSOCKET_TCP_NODELAY;
|
|
|
bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
|
|
|
@@ -6209,9 +6252,9 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
|
|
|
reset();
|
|
|
return FrameRead::Fail;
|
|
|
};
|
|
|
- auto fail = [&]() {
|
|
|
+ auto reject = [&](FrameRead r) {
|
|
|
reset();
|
|
|
- return FrameRead::Fail;
|
|
|
+ return r;
|
|
|
};
|
|
|
|
|
|
while (have_ < need_) {
|
|
|
@@ -6221,15 +6264,15 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
|
|
|
if (have_ < 2 || need_ > 2) { continue; }
|
|
|
|
|
|
// RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
|
|
|
- if (head_[0] & 0x70) { return fail(); }
|
|
|
+ if (head_[0] & 0x70) { return reject(FrameRead::ProtocolError); }
|
|
|
// RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
|
|
|
// MUST have a payload length of 125 bytes or less
|
|
|
auto len7 = head_[1] & 0x7F;
|
|
|
if ((head_[0] & 0x08) && (!(head_[0] & 0x80) || len7 > 125)) {
|
|
|
- return fail();
|
|
|
+ return reject(FrameRead::ProtocolError);
|
|
|
}
|
|
|
auto masked = (head_[1] & 0x80) != 0;
|
|
|
- if (masked != expect_masked) { return fail(); }
|
|
|
+ if (masked != expect_masked) { return reject(FrameRead::ProtocolError); }
|
|
|
// The extended length and the mask key follow
|
|
|
need_ = 2 + (len7 == 126 ? 2 : len7 == 127 ? 8 : 0) + (masked ? 4 : 0);
|
|
|
}
|
|
|
@@ -6240,7 +6283,7 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
|
|
|
len = (static_cast<uint64_t>(head_[2]) << 8) | head_[3];
|
|
|
} else if (len == 127) {
|
|
|
// RFC 6455 Section 5.2: the most significant bit MUST be 0
|
|
|
- if (head_[2] & 0x80) { return fail(); }
|
|
|
+ if (head_[2] & 0x80) { return reject(FrameRead::ProtocolError); }
|
|
|
len = 0;
|
|
|
for (size_t i = 2; i < 10; i++) {
|
|
|
len = (len << 8) | head_[i];
|
|
|
@@ -6249,7 +6292,7 @@ inline FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
|
|
|
// A max_len of 0 means no limit, as payload_max_length does, and a length
|
|
|
// size_t cannot hold (32-bit builds) is refused either way.
|
|
|
if ((max_len > 0 && len > max_len) || !detail::fits_in_size_t(len)) {
|
|
|
- return fail();
|
|
|
+ return reject(FrameRead::TooBig);
|
|
|
}
|
|
|
len_ = static_cast<size_t>(len);
|
|
|
sized_ = true;
|
|
|
@@ -6292,17 +6335,39 @@ inline FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
|
|
|
|
|
|
// RFC 6455 §5.5.1, §7.4: a Close payload is empty, or a status code that may
|
|
|
// be sent followed by a UTF-8 reason.
|
|
|
+// The status code a Close payload of at least 2 bytes starts with
|
|
|
+inline uint16_t close_code(const std::string &payload) {
|
|
|
+ return static_cast<uint16_t>((static_cast<uint8_t>(payload[0]) << 8) |
|
|
|
+ static_cast<uint8_t>(payload[1]));
|
|
|
+}
|
|
|
+
|
|
|
inline bool is_valid_close_payload(const std::string &payload) {
|
|
|
if (payload.empty()) { return true; }
|
|
|
if (payload.size() < 2) { return false; }
|
|
|
- auto code = (static_cast<uint8_t>(payload[0]) << 8) |
|
|
|
- static_cast<uint8_t>(payload[1]);
|
|
|
+ auto code = close_code(payload);
|
|
|
auto may_be_sent = (1000 <= code && code <= 1003) ||
|
|
|
(1007 <= code && code <= 1014) ||
|
|
|
(3000 <= code && code <= 4999);
|
|
|
return may_be_sent && is_valid_utf8(payload.substr(2));
|
|
|
}
|
|
|
|
|
|
+// The payload of a Close with this status and reason. The reason is cut to fit
|
|
|
+// a control frame (RFC 6455 Section 5.5), back to a whole UTF-8 character, and
|
|
|
+// a code that may not be sent, such as NoStatus, goes without a payload.
|
|
|
+inline std::string close_payload(CloseStatus status,
|
|
|
+ const std::string &reason = std::string()) {
|
|
|
+ auto code = static_cast<uint16_t>(status);
|
|
|
+ std::string payload{static_cast<char>(code >> 8),
|
|
|
+ static_cast<char>(code & 0xff)};
|
|
|
+ auto short_reason = reason.substr(0, 123);
|
|
|
+ while (!short_reason.empty() && !is_valid_utf8(short_reason)) {
|
|
|
+ short_reason.pop_back();
|
|
|
+ }
|
|
|
+ payload += short_reason;
|
|
|
+ if (!is_valid_close_payload(payload)) { payload.clear(); }
|
|
|
+ return payload;
|
|
|
+}
|
|
|
+
|
|
|
} // namespace impl
|
|
|
} // namespace ws
|
|
|
|
|
|
@@ -10161,8 +10226,10 @@ inline void parse_disposition_params(const std::string &s, Params ¶ms) {
|
|
|
std::string val;
|
|
|
divide_param_pair(b, e, key, val);
|
|
|
|
|
|
+ // Parameter names are case-insensitive (RFC 2045 §5.1)
|
|
|
if (!key.empty()) {
|
|
|
- params.emplace(trim_double_quotes_copy(key), unquote_param(val));
|
|
|
+ params.emplace(case_ignore::to_lower(trim_double_quotes_copy(key)),
|
|
|
+ unquote_param(val));
|
|
|
}
|
|
|
});
|
|
|
}
|
|
|
@@ -10927,7 +10994,7 @@ inline bool range_error(Request &req, Response &res) {
|
|
|
ssize_t content_len = static_cast<ssize_t>(
|
|
|
res.content_length_ ? res.content_length_ : res.body.size());
|
|
|
|
|
|
- std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
|
|
|
+ Ranges satisfiable_ranges;
|
|
|
size_t overwrapping_count = 0;
|
|
|
|
|
|
// NOTE: The following Range check is based on '14.2. Range' in RFC 9110
|
|
|
@@ -10940,7 +11007,9 @@ inline bool range_error(Request &req, Response &res) {
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
- for (auto &r : req.ranges) {
|
|
|
+ satisfiable_ranges.reserve(req.ranges.size());
|
|
|
+
|
|
|
+ for (auto r : req.ranges) {
|
|
|
auto &first_pos = r.first;
|
|
|
auto &last_pos = r.second;
|
|
|
|
|
|
@@ -10969,25 +11038,28 @@ inline bool range_error(Request &req, Response &res) {
|
|
|
last_pos = content_len - 1;
|
|
|
}
|
|
|
|
|
|
- // Range must be within content length
|
|
|
+ // Skip an unsatisfiable range (RFC 9110 14.1.1)
|
|
|
if (!(0 <= first_pos && first_pos <= last_pos &&
|
|
|
last_pos <= content_len - 1)) {
|
|
|
- return true;
|
|
|
+ continue;
|
|
|
}
|
|
|
|
|
|
// Request must not have more than two overlapping ranges
|
|
|
- for (const auto &processed_range : processed_ranges) {
|
|
|
- if (!(last_pos < processed_range.first ||
|
|
|
- first_pos > processed_range.second)) {
|
|
|
+ for (const auto &prev : satisfiable_ranges) {
|
|
|
+ if (!(last_pos < prev.first || first_pos > prev.second)) {
|
|
|
overwrapping_count++;
|
|
|
if (overwrapping_count > 2) { return true; }
|
|
|
break; // Only count once per range
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- processed_ranges.emplace_back(first_pos, last_pos);
|
|
|
+ satisfiable_ranges.push_back(r);
|
|
|
}
|
|
|
|
|
|
+ // 416 only when no range is satisfiable (RFC 9110 15.5.17)
|
|
|
+ if (satisfiable_ranges.empty()) { return true; }
|
|
|
+ req.ranges = std::move(satisfiable_ranges);
|
|
|
+
|
|
|
// After validation, coalesce overlapping ranges as per RFC 9110
|
|
|
coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
|
|
|
}
|
|
|
@@ -11164,75 +11236,6 @@ inline std::string escape_quoted_pairs(const std::string &s) {
|
|
|
return out;
|
|
|
}
|
|
|
|
|
|
-// RFC 9110 Section 11.6.1 defines a challenge list as
|
|
|
-// WWW-Authenticate = #challenge
|
|
|
-// challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
|
|
|
-// auth-param = token BWS "=" BWS ( token / quoted-string )
|
|
|
-// so a server may offer several schemes, each with its own comma-separated
|
|
|
-// auth-param list, in either order and either as separate field lines or
|
|
|
-// packed into one. Splitting on every comma would break apart a challenge's
|
|
|
-// own param list; splitting only on the first space would miss a Digest
|
|
|
-// challenge that isn't first. Split on commas that aren't inside a
|
|
|
-// quoted-string instead (split_unquoted), then track which scheme each
|
|
|
-// resulting segment belongs to: a segment whose text before "=" contains
|
|
|
-// whitespace (or that has no "=" at all) starts a new challenge named by its
|
|
|
-// leading token.
|
|
|
-inline bool parse_www_authenticate(const Response &res,
|
|
|
- std::map<std::string, std::string> &auth,
|
|
|
- bool is_proxy) {
|
|
|
- auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
|
|
|
- auto combined = get_combined_header_value(res.headers, auth_key);
|
|
|
- if (combined.empty()) { return false; }
|
|
|
-
|
|
|
- auto found_digest = false;
|
|
|
- auto in_digest_challenge = false;
|
|
|
- split_unquoted(
|
|
|
- combined.data(), combined.data() + combined.size(), ',',
|
|
|
- [&](const char *b, const char *e) {
|
|
|
- std::string segment(b, e);
|
|
|
- auto eq_pos = segment.find('=');
|
|
|
- // BWS is allowed on both sides of "=", so the text naming the key (or,
|
|
|
- // for the first segment of a challenge, "<scheme> <key>") must be
|
|
|
- // trimmed before its boundaries are inspected.
|
|
|
- auto key_part = trim_copy(
|
|
|
- eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
|
|
|
- auto space_pos = key_part.find_last_of(" \t");
|
|
|
- if (space_pos != std::string::npos || eq_pos == std::string::npos) {
|
|
|
- // "<scheme>[ <key>]" starts a new challenge.
|
|
|
- auto scheme_end =
|
|
|
- space_pos == std::string::npos ? key_part.size() : space_pos;
|
|
|
- // RFC 7616 Section 3.7: a server may offer more than one Digest
|
|
|
- // challenge (e.g. SHA-256 and MD5); keep only the first so a nonce
|
|
|
- // from one challenge is never paired with another's algorithm.
|
|
|
- in_digest_challenge =
|
|
|
- !found_digest &&
|
|
|
- case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
|
|
|
- if (in_digest_challenge) { found_digest = true; }
|
|
|
- if (space_pos == std::string::npos) {
|
|
|
- // Bare scheme (or a token68), no auth-param on this segment.
|
|
|
- return;
|
|
|
- }
|
|
|
- key_part = key_part.substr(space_pos + 1);
|
|
|
- }
|
|
|
-
|
|
|
- if (!in_digest_challenge) { return; }
|
|
|
-
|
|
|
- auto val = trim_copy(segment.substr(eq_pos + 1));
|
|
|
- auto unquoted = trim_double_quotes_copy(val);
|
|
|
- if (unquoted.size() != val.size()) {
|
|
|
- unquoted = unescape_quoted_pairs(unquoted);
|
|
|
- }
|
|
|
- auth[std::move(key_part)] = std::move(unquoted);
|
|
|
- });
|
|
|
-
|
|
|
- // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge;
|
|
|
- // make_digest_authentication_header() dereferences both unconditionally, so
|
|
|
- // a challenge missing either can't produce a usable Authorization header.
|
|
|
- // Treat it the same as no Digest challenge at all.
|
|
|
- return found_digest && auth.find("realm") != auth.end() &&
|
|
|
- auth.find("nonce") != auth.end();
|
|
|
-}
|
|
|
-
|
|
|
class ContentProviderAdapter {
|
|
|
public:
|
|
|
explicit ContentProviderAdapter(
|
|
|
@@ -11701,6 +11704,121 @@ inline bool process_client_socket_ssl(
|
|
|
return callback(strm);
|
|
|
}
|
|
|
|
|
|
+using DigestHash = std::string (*)(const std::string &);
|
|
|
+
|
|
|
+// The Digest algorithms the client implements, matched case-insensitively;
|
|
|
+// nullptr for any other.
|
|
|
+inline DigestHash digest_hash(const std::string &algorithm) {
|
|
|
+ if (case_ignore::equal(algorithm, "MD5")) { return detail::MD5; }
|
|
|
+ if (case_ignore::equal(algorithm, "SHA-256")) { return detail::SHA_256; }
|
|
|
+ if (case_ignore::equal(algorithm, "SHA-512")) { return detail::SHA_512; }
|
|
|
+ return nullptr;
|
|
|
+}
|
|
|
+
|
|
|
+// Picks auth over auth-int from the qop options a server offers, as curl does:
|
|
|
+// auth-int hashes req.body, which is empty when a content provider streams the
|
|
|
+// body. Empty when it offers neither.
|
|
|
+inline std::string select_digest_qop(const std::string &options) {
|
|
|
+ std::string qop;
|
|
|
+ split(options.data(), options.data() + options.size(), ',',
|
|
|
+ [&](const char *b, const char *e) {
|
|
|
+ std::string option(b, e);
|
|
|
+ if (case_ignore::equal(option, "auth")) {
|
|
|
+ qop = "auth";
|
|
|
+ } else if (qop.empty() && case_ignore::equal(option, "auth-int")) {
|
|
|
+ qop = "auth-int";
|
|
|
+ }
|
|
|
+ });
|
|
|
+ return qop;
|
|
|
+}
|
|
|
+
|
|
|
+// RFC 9110 Section 11.6.1 defines a challenge list as
|
|
|
+// WWW-Authenticate = #challenge
|
|
|
+// challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
|
|
|
+// auth-param = token BWS "=" BWS ( token / quoted-string )
|
|
|
+// so a server may offer several schemes, each with its own comma-separated
|
|
|
+// auth-param list, in either order and either as separate field lines or
|
|
|
+// packed into one. Splitting on every comma would break apart a challenge's
|
|
|
+// own param list; splitting only on the first space would miss a Digest
|
|
|
+// challenge that isn't first. Split on commas that aren't inside a
|
|
|
+// quoted-string instead (split_unquoted), then track which scheme each
|
|
|
+// resulting segment belongs to: a segment whose text before "=" contains
|
|
|
+// whitespace (or that has no "=" at all) starts a new challenge named by its
|
|
|
+// leading token.
|
|
|
+inline bool parse_www_authenticate(const Response &res,
|
|
|
+ std::map<std::string, std::string> &auth,
|
|
|
+ bool is_proxy) {
|
|
|
+ auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
|
|
|
+ auto combined = get_combined_header_value(res.headers, auth_key);
|
|
|
+ if (combined.empty()) { return false; }
|
|
|
+
|
|
|
+ // RFC 7616 Section 3.7: a server may offer more than one Digest challenge
|
|
|
+ // (e.g. SHA-256 and MD5), and the client uses the first one it supports.
|
|
|
+ // A challenge whose algorithm the client doesn't implement is ignored
|
|
|
+ // (Section 3.3), as is one whose qop offers neither auth nor auth-int, and
|
|
|
+ // one without realm and nonce can't be answered. Params are collected per
|
|
|
+ // challenge, so a nonce from one is never paired with another's algorithm.
|
|
|
+ auto answerable = [](const std::map<std::string, std::string> &c) {
|
|
|
+ if (c.find("realm") == c.end() || c.find("nonce") == c.end()) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ auto algo_it = c.find("algorithm");
|
|
|
+ if (algo_it != c.end() && !digest_hash(algo_it->second)) { return false; }
|
|
|
+ auto qop_it = c.find("qop");
|
|
|
+ return qop_it == c.end() || !select_digest_qop(qop_it->second).empty();
|
|
|
+ };
|
|
|
+
|
|
|
+ auto found = false;
|
|
|
+ auto in_digest_challenge = false;
|
|
|
+ std::map<std::string, std::string> challenge;
|
|
|
+ auto take_challenge_if_answerable = [&] {
|
|
|
+ if (!found && in_digest_challenge && answerable(challenge)) {
|
|
|
+ auth = std::move(challenge);
|
|
|
+ found = true;
|
|
|
+ }
|
|
|
+ challenge.clear();
|
|
|
+ };
|
|
|
+
|
|
|
+ split_unquoted(
|
|
|
+ combined.data(), combined.data() + combined.size(), ',',
|
|
|
+ [&](const char *b, const char *e) {
|
|
|
+ std::string segment(b, e);
|
|
|
+ auto eq_pos = segment.find('=');
|
|
|
+ // BWS is allowed on both sides of "=", so the text naming the key (or,
|
|
|
+ // for the first segment of a challenge, "<scheme> <key>") must be
|
|
|
+ // trimmed before its boundaries are inspected.
|
|
|
+ auto key_part = trim_copy(
|
|
|
+ eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
|
|
|
+ auto space_pos = key_part.find_first_of(" \t");
|
|
|
+ if (space_pos != std::string::npos || eq_pos == std::string::npos) {
|
|
|
+ // "<scheme>[ <key>]" starts a new challenge.
|
|
|
+ take_challenge_if_answerable();
|
|
|
+ auto scheme_end =
|
|
|
+ space_pos == std::string::npos ? key_part.size() : space_pos;
|
|
|
+ in_digest_challenge =
|
|
|
+ case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
|
|
|
+ if (space_pos == std::string::npos) {
|
|
|
+ // Bare scheme (or a token68), no auth-param on this segment.
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ key_part = trim_copy(key_part.substr(space_pos + 1));
|
|
|
+ }
|
|
|
+
|
|
|
+ if (!in_digest_challenge) { return; }
|
|
|
+
|
|
|
+ auto val = trim_copy(segment.substr(eq_pos + 1));
|
|
|
+ auto unquoted = trim_double_quotes_copy(val);
|
|
|
+ if (unquoted.size() != val.size()) {
|
|
|
+ unquoted = unescape_quoted_pairs(unquoted);
|
|
|
+ }
|
|
|
+ // auth-param names are case-insensitive (RFC 9110 Section 11.2)
|
|
|
+ challenge[case_ignore::to_lower(key_part)] = std::move(unquoted);
|
|
|
+ });
|
|
|
+ take_challenge_if_answerable();
|
|
|
+
|
|
|
+ return found;
|
|
|
+}
|
|
|
+
|
|
|
// `uri` is req's request-target in origin form, as curl sends it, also when
|
|
|
// the request line carries the absolute form for a proxy.
|
|
|
inline std::pair<std::string, std::string> make_digest_authentication_header(
|
|
|
@@ -11715,33 +11833,21 @@ inline std::pair<std::string, std::string> make_digest_authentication_header(
|
|
|
nc = ss.str();
|
|
|
}
|
|
|
|
|
|
- std::string qop;
|
|
|
- if (auth.find("qop") != auth.end()) {
|
|
|
- qop = auth.at("qop");
|
|
|
- if (qop.find("auth-int") != std::string::npos) {
|
|
|
- qop = "auth-int";
|
|
|
- } else if (qop.find("auth") != std::string::npos) {
|
|
|
- qop = "auth";
|
|
|
- } else {
|
|
|
- qop.clear();
|
|
|
- }
|
|
|
- }
|
|
|
+ // Without qop, the RFC 2069 form is used.
|
|
|
+ auto qop_it = auth.find("qop");
|
|
|
+ auto qop =
|
|
|
+ qop_it == auth.end() ? std::string() : select_digest_qop(qop_it->second);
|
|
|
+ assert(qop_it == auth.end() || !qop.empty());
|
|
|
|
|
|
- std::string algo = "MD5";
|
|
|
- if (auth.find("algorithm") != auth.end()) {
|
|
|
- // algorithm is an unquoted token (RFC 7616 §3.4). A server value that is
|
|
|
- // not a token would otherwise be emitted verbatim and could carry commas
|
|
|
- // or quotes that inject further auth-params into the header below.
|
|
|
- const auto &a = auth.at("algorithm");
|
|
|
- if (fields::is_token(a)) { algo = a; }
|
|
|
- }
|
|
|
+ // Sent back as the server wrote it (RFC 7616 Section 3.4).
|
|
|
+ // parse_www_authenticate() accepts only one digest_hash() knows.
|
|
|
+ auto algo_it = auth.find("algorithm");
|
|
|
+ auto algo = algo_it == auth.end() ? std::string("MD5") : algo_it->second;
|
|
|
+ auto H = digest_hash(algo);
|
|
|
+ assert(H);
|
|
|
|
|
|
std::string response;
|
|
|
{
|
|
|
- auto H = algo == "SHA-256" ? detail::SHA_256
|
|
|
- : algo == "SHA-512" ? detail::SHA_512
|
|
|
- : detail::MD5;
|
|
|
-
|
|
|
auto A1 = username + ":" + auth.at("realm") + ":" + password;
|
|
|
|
|
|
auto A2 = req.method + ":" + uri;
|
|
|
@@ -12236,15 +12342,16 @@ inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
|
|
|
}
|
|
|
|
|
|
inline std::string get_bearer_token_auth(const Request &req) {
|
|
|
- // The auth scheme is case-insensitive (RFC 9110 11.1), and a value shorter
|
|
|
- // than the prefix carries no token.
|
|
|
+ // The auth scheme is case-insensitive (RFC 9110 11.1) and followed by 1*SP,
|
|
|
+ // and a value shorter than the prefix carries no token.
|
|
|
constexpr const char bearer_prefix[] = "Bearer ";
|
|
|
constexpr auto bearer_prefix_len = detail::str_len(bearer_prefix);
|
|
|
auto value = req.get_header_value("Authorization");
|
|
|
if (value.size() >= bearer_prefix_len &&
|
|
|
detail::case_ignore::equal(value.substr(0, bearer_prefix_len),
|
|
|
bearer_prefix)) {
|
|
|
- return value.substr(bearer_prefix_len);
|
|
|
+ auto pos = value.find_first_not_of(' ', bearer_prefix_len);
|
|
|
+ if (pos != std::string::npos) { return value.substr(pos); }
|
|
|
}
|
|
|
return "";
|
|
|
}
|
|
|
@@ -14819,6 +14926,11 @@ inline Server &Server::set_start_handler(StartHandler handler) {
|
|
|
return *this;
|
|
|
}
|
|
|
|
|
|
+inline Server &Server::set_accept_handler(AcceptHandler handler) {
|
|
|
+ accept_handler_ = std::move(handler);
|
|
|
+ return *this;
|
|
|
+}
|
|
|
+
|
|
|
inline Server &Server::set_address_family(int family) {
|
|
|
address_family_ = family;
|
|
|
return *this;
|
|
|
@@ -14941,6 +15053,11 @@ inline Server &Server::set_websocket_max_missed_pongs(int count) {
|
|
|
return *this;
|
|
|
}
|
|
|
|
|
|
+inline Server &Server::set_websocket_max_message_length(size_t length) {
|
|
|
+ websocket_max_message_length_ = length;
|
|
|
+ return *this;
|
|
|
+}
|
|
|
+
|
|
|
inline Server &Server::set_websocket_ping_interval(time_t sec) {
|
|
|
websocket_ping_interval_sec_ = sec;
|
|
|
return *this;
|
|
|
@@ -15619,12 +15736,22 @@ inline bool Server::listen_internal() {
|
|
|
return ret;
|
|
|
}
|
|
|
|
|
|
-inline void Server::prepare_accepted_socket(socket_t sock) const {
|
|
|
+// Closes the socket and returns false when the accept handler refuses it.
|
|
|
+inline bool Server::admit_accepted_socket(socket_t sock) const {
|
|
|
detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec_,
|
|
|
read_timeout_usec_);
|
|
|
detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec_,
|
|
|
write_timeout_usec_);
|
|
|
if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
|
|
|
+
|
|
|
+ // After the timeouts, so that a handler reading from the socket returns.
|
|
|
+ if (accept_handler_ &&
|
|
|
+ !serve_guarded([&]() { return accept_handler_(sock); })) {
|
|
|
+ detail::shutdown_socket(sock);
|
|
|
+ detail::close_socket(sock);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ return true;
|
|
|
}
|
|
|
|
|
|
// Serves each connection on one worker thread for its whole life.
|
|
|
@@ -15663,7 +15790,7 @@ inline bool Server::accept_loop(TaskQueue &task_queue) {
|
|
|
break;
|
|
|
}
|
|
|
|
|
|
- prepare_accepted_socket(sock);
|
|
|
+ if (!admit_accepted_socket(sock)) { continue; }
|
|
|
|
|
|
if (!task_queue.enqueue(
|
|
|
[this, sock]() { process_and_close_socket(sock); })) {
|
|
|
@@ -16347,6 +16474,10 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
|
|
|
connection_closed = true;
|
|
|
if (websocket_upgraded) { *websocket_upgraded = true; }
|
|
|
auto stopping = [this] { return is_stopping(); };
|
|
|
+ ws::impl::Options options;
|
|
|
+ options.ping_interval_sec = websocket_ping_interval_sec_;
|
|
|
+ options.max_missed_pongs = websocket_max_missed_pongs_;
|
|
|
+ options.max_message_length = websocket_max_message_length_;
|
|
|
if (CPPHTTPLIB_WEBSOCKET_TCP_NODELAY) {
|
|
|
set_socket_opt(strm.socket(), IPPROTO_TCP, TCP_NODELAY, 1);
|
|
|
}
|
|
|
@@ -16361,17 +16492,14 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
|
|
|
strm.socket(), const_cast<tls::session_t>(req.ssl),
|
|
|
CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0,
|
|
|
write_timeout_sec_, write_timeout_usec_));
|
|
|
- ws::WebSocket ws(std::move(ws_strm), req, true,
|
|
|
- websocket_ping_interval_sec_,
|
|
|
- websocket_max_missed_pongs_, stopping);
|
|
|
+ ws::WebSocket ws(std::move(ws_strm), req, true, options, stopping);
|
|
|
ws_route->handler(req, ws);
|
|
|
return true;
|
|
|
}
|
|
|
#endif
|
|
|
// Use WebSocket-specific read timeout instead of HTTP timeout
|
|
|
strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0);
|
|
|
- ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
|
|
|
- websocket_max_missed_pongs_, stopping);
|
|
|
+ ws::WebSocket ws(strm, req, true, options, stopping);
|
|
|
ws_route->handler(req, ws);
|
|
|
return true;
|
|
|
}
|
|
|
@@ -16624,7 +16752,7 @@ inline bool Server::parking_loop(TaskQueue &task_queue) {
|
|
|
}
|
|
|
// Some platforms make it non-blocking like the listening socket.
|
|
|
detail::set_nonblocking(sock, false);
|
|
|
- prepare_accepted_socket(sock);
|
|
|
+ if (!admit_accepted_socket(sock)) { continue; }
|
|
|
park(new_keep_alive_connection(sock), now);
|
|
|
if (idle.count() > 0) { next_idle = now + idle; }
|
|
|
}
|
|
|
@@ -24860,7 +24988,25 @@ inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
+// Sends this side's one Close frame and marks the connection closed. Returns
|
|
|
+// false when it already was.
|
|
|
+inline bool WebSocket::send_close(const std::string &payload) {
|
|
|
+ if (closed_.exchange(true)) { return false; }
|
|
|
+ ping_cv_.notify_all();
|
|
|
+ std::lock_guard<std::mutex> lock(write_mutex_);
|
|
|
+ detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
|
|
|
+ payload.size(), true, !is_server_);
|
|
|
+ return true;
|
|
|
+}
|
|
|
+
|
|
|
inline ReadResult WebSocket::read(std::string &msg) {
|
|
|
+ // RFC 6455 Section 7.1.7: a connection failed on the peer's error is told
|
|
|
+ // why with a Close frame, and nothing more is read from it.
|
|
|
+ auto fail_with = [&](CloseStatus status) {
|
|
|
+ send_close(impl::close_payload(status));
|
|
|
+ return Fail;
|
|
|
+ };
|
|
|
+
|
|
|
// Answers a control frame; any other opcode here is a protocol error.
|
|
|
// Returns false when the connection is done.
|
|
|
auto handle_control = [&](Opcode op, const std::string &payload) -> bool {
|
|
|
@@ -24872,21 +25018,16 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|
|
unacked_pings_ = 0;
|
|
|
return true;
|
|
|
}
|
|
|
- case Opcode::Close: {
|
|
|
+ case Opcode::Close:
|
|
|
+ // The reply to a close() of our own, too
|
|
|
+ set_close_status(payload);
|
|
|
// RFC 6455 §5.5.1: a Close is echoed back, unless its payload is
|
|
|
// malformed, which is answered with a protocol error instead.
|
|
|
- if (closed_.exchange(true)) { return false; }
|
|
|
- auto reply = payload;
|
|
|
- if (!impl::is_valid_close_payload(payload)) {
|
|
|
- auto code = static_cast<uint16_t>(CloseStatus::ProtocolError);
|
|
|
- reply = {static_cast<char>(code >> 8), static_cast<char>(code & 0xff)};
|
|
|
- }
|
|
|
- std::lock_guard<std::mutex> lock(write_mutex_);
|
|
|
- detail::write_websocket_frame(strm_, Opcode::Close, reply.data(),
|
|
|
- reply.size(), true, !is_server_);
|
|
|
+ send_close(impl::is_valid_close_payload(payload)
|
|
|
+ ? payload
|
|
|
+ : impl::close_payload(CloseStatus::ProtocolError));
|
|
|
return false;
|
|
|
- }
|
|
|
- default: closed_ = true; return false;
|
|
|
+ default: fail_with(CloseStatus::ProtocolError); return false;
|
|
|
}
|
|
|
};
|
|
|
|
|
|
@@ -24904,13 +25045,12 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|
|
std::string payload;
|
|
|
bool fin;
|
|
|
|
|
|
- // While a message is assembled, only what is left of the limit, but room
|
|
|
- // for a control frame, which may come between its fragments.
|
|
|
+ // What is left of the limit (all of it between messages), but always room
|
|
|
+ // for a control frame, which the limit does not cover.
|
|
|
auto max_len =
|
|
|
- CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH == 0 || message_kind_ == Fail
|
|
|
- ? size_t(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)
|
|
|
- : (std::max)(size_t(125), CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH -
|
|
|
- message_.size());
|
|
|
+ max_message_length_ == 0
|
|
|
+ ? size_t(0)
|
|
|
+ : (std::max)(size_t(125), max_message_length_ - message_.size());
|
|
|
auto r = frames_.read(strm_, opcode, payload, fin, is_server_, max_len);
|
|
|
if (r != impl::FrameRead::Ok && server_stopping()) { return going_away(); }
|
|
|
// A timeout leaves what was read of the frame and of the message for the
|
|
|
@@ -24923,6 +25063,12 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|
|
if (r == impl::FrameRead::Timeout && read_timeout_set_ && !closed_) {
|
|
|
return Timeout;
|
|
|
}
|
|
|
+ if (r == impl::FrameRead::ProtocolError) {
|
|
|
+ return fail_with(CloseStatus::ProtocolError);
|
|
|
+ }
|
|
|
+ if (r == impl::FrameRead::TooBig) {
|
|
|
+ return fail_with(CloseStatus::MessageTooBig);
|
|
|
+ }
|
|
|
if (r != impl::FrameRead::Ok) {
|
|
|
closed_ = true;
|
|
|
return Fail;
|
|
|
@@ -24936,8 +25082,7 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|
|
// RFC 6455 5.4: a message is a Text or Binary frame and the continuation
|
|
|
// frames after it, with only control frames between them.
|
|
|
if (continues == (message_kind_ == Fail)) {
|
|
|
- closed_ = true;
|
|
|
- return Fail;
|
|
|
+ return fail_with(CloseStatus::ProtocolError);
|
|
|
}
|
|
|
if (continues) {
|
|
|
message_ += payload;
|
|
|
@@ -24945,10 +25090,8 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|
|
message_ = std::move(payload);
|
|
|
message_kind_ = opcode == Opcode::Text ? Text : Binary;
|
|
|
}
|
|
|
- if (CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH > 0 &&
|
|
|
- message_.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
|
|
|
- closed_ = true;
|
|
|
- return Fail;
|
|
|
+ if (max_message_length_ > 0 && message_.size() > max_message_length_) {
|
|
|
+ return fail_with(CloseStatus::MessageTooBig);
|
|
|
}
|
|
|
if (!fin) { continue; }
|
|
|
|
|
|
@@ -24978,27 +25121,7 @@ inline bool WebSocket::send(const char *data, size_t len) {
|
|
|
}
|
|
|
|
|
|
inline void WebSocket::close(CloseStatus status, const std::string &reason) {
|
|
|
- if (closed_.exchange(true)) { return; }
|
|
|
- ping_cv_.notify_all();
|
|
|
- std::string payload;
|
|
|
- auto code = static_cast<uint16_t>(status);
|
|
|
- payload.push_back(static_cast<char>((code >> 8) & 0xFF));
|
|
|
- payload.push_back(static_cast<char>(code & 0xFF));
|
|
|
- // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
|
|
|
- // Close frame has 2-byte status code, so reason is limited to 123 bytes,
|
|
|
- // cut back to a whole UTF-8 character
|
|
|
- auto short_reason = reason.substr(0, 123);
|
|
|
- while (!short_reason.empty() && !impl::is_valid_utf8(short_reason)) {
|
|
|
- short_reason.pop_back();
|
|
|
- }
|
|
|
- payload += short_reason;
|
|
|
- // A code that may not be sent, such as NoStatus, goes without a payload
|
|
|
- if (!impl::is_valid_close_payload(payload)) { payload.clear(); }
|
|
|
- {
|
|
|
- std::lock_guard<std::mutex> lock(write_mutex_);
|
|
|
- detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
|
|
|
- payload.size(), true, !is_server_);
|
|
|
- }
|
|
|
+ if (!send_close(impl::close_payload(status, reason))) { return; }
|
|
|
|
|
|
// RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
|
|
|
// Close response before closing the TCP connection.
|
|
|
@@ -25024,7 +25147,10 @@ inline void WebSocket::close(CloseStatus status, const std::string &reason) {
|
|
|
while (std::chrono::steady_clock::now() < deadline &&
|
|
|
frames_.read(strm_, op, resp, fin, is_server_, 125) ==
|
|
|
impl::FrameRead::Ok) {
|
|
|
- if (op == Opcode::Close) { break; }
|
|
|
+ if (op == Opcode::Close) {
|
|
|
+ set_close_status(resp);
|
|
|
+ break;
|
|
|
+ }
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -25076,6 +25202,25 @@ inline const Request &WebSocket::request() const { return req_; }
|
|
|
|
|
|
inline bool WebSocket::is_open() const { return !closed_; }
|
|
|
|
|
|
+inline CloseStatus WebSocket::close_status() const { return close_status_; }
|
|
|
+
|
|
|
+inline std::string WebSocket::close_reason() const {
|
|
|
+ return close_status_ == CloseStatus::Abnormal ? std::string() : close_reason_;
|
|
|
+}
|
|
|
+
|
|
|
+// Called with read_mutex_ held. Only the first Close counts.
|
|
|
+inline void WebSocket::set_close_status(const std::string &payload) {
|
|
|
+ if (close_status_ != CloseStatus::Abnormal) { return; }
|
|
|
+ if (payload.empty()) {
|
|
|
+ close_status_ = CloseStatus::NoStatus;
|
|
|
+ } else if (impl::is_valid_close_payload(payload)) {
|
|
|
+ close_reason_ = payload.substr(2);
|
|
|
+ close_status_ = static_cast<CloseStatus>(impl::close_code(payload));
|
|
|
+ } else {
|
|
|
+ close_status_ = CloseStatus::ProtocolError;
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
inline void WebSocket::set_read_timeout(time_t sec, time_t usec) {
|
|
|
// 0 waits forever here, as it does for SO_RCVTIMEO. The stream waits with
|
|
|
// poll(), where 0 would instead mean "return immediately", so hand it the
|
|
|
@@ -25318,9 +25463,12 @@ inline Result WebSocketClient::connect() {
|
|
|
}
|
|
|
subprotocol_ = std::move(upgrade.selected_subprotocol);
|
|
|
|
|
|
- ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
|
|
|
- websocket_ping_interval_sec_,
|
|
|
- websocket_max_missed_pongs_));
|
|
|
+ impl::Options options;
|
|
|
+ options.ping_interval_sec = websocket_ping_interval_sec_;
|
|
|
+ options.max_missed_pongs = websocket_max_missed_pongs_;
|
|
|
+ options.max_message_length = websocket_max_message_length_;
|
|
|
+ ws_ = std::unique_ptr<WebSocket>(
|
|
|
+ new WebSocket(std::move(strm), req, false, options));
|
|
|
// The stream was created with the timeout already; tell the WebSocket
|
|
|
// whether it came from the caller, so read() knows to report it as Timeout.
|
|
|
ws_->read_timeout_set_ = read_timeout_set_;
|
|
|
@@ -25349,6 +25497,14 @@ inline void WebSocketClient::close(CloseStatus status,
|
|
|
|
|
|
inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
|
|
|
|
|
|
+inline CloseStatus WebSocketClient::close_status() const {
|
|
|
+ return ws_ ? ws_->close_status() : CloseStatus::Abnormal;
|
|
|
+}
|
|
|
+
|
|
|
+inline std::string WebSocketClient::close_reason() const {
|
|
|
+ return ws_ ? ws_->close_reason() : std::string();
|
|
|
+}
|
|
|
+
|
|
|
inline const std::string &WebSocketClient::subprotocol() const {
|
|
|
return subprotocol_;
|
|
|
}
|
|
|
@@ -25375,6 +25531,10 @@ inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
|
|
|
websocket_max_missed_pongs_ = count;
|
|
|
}
|
|
|
|
|
|
+inline void WebSocketClient::set_websocket_max_message_length(size_t length) {
|
|
|
+ websocket_max_message_length_ = length;
|
|
|
+}
|
|
|
+
|
|
|
inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
|
|
|
|
|
|
inline void WebSocketClient::set_address_family(int family) {
|