Commit cbb7652cd for llama.cpp

commit cbb7652cd34841b04e1f2cbce5d04d888f70b1d4
Author: Alessandro de Oliveira Faria (A.K.A.CABELO) <cabelo@opensuse.org>
Date:   Sat Nov 28 18:28:39 2026 -0300

    vendor : update cpp-httplib-0.68.0 (#33259)

    [no ci]

diff --git a/scripts/sync_vendor.py b/scripts/sync_vendor.py
index 3f706df7f..6344f2ad2 100755
--- a/scripts/sync_vendor.py
+++ b/scripts/sync_vendor.py
@@ -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)
diff --git a/vendor/cpp-httplib/httplib.cpp b/vendor/cpp-httplib/httplib.cpp
index 094154eb9..74df8eec1 100644
--- a/vendor/cpp-httplib/httplib.cpp
+++ b/vendor/cpp-httplib/httplib.cpp
@@ -445,7 +445,8 @@ bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
                          time_t timeout_usec, TlsError *err,
                          const std::function<bool()> &interrupted = nullptr);
 bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
-                        time_t timeout_usec, TlsError *err);
+                        time_t timeout_usec, TlsError *err,
+                        const std::function<bool()> &interrupted = nullptr);

 // I/O (non-blocking capable)
 ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
@@ -924,67 +925,59 @@ void fill_random_bytes(unsigned char *out, size_t n) {
 bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
                                   const char *data, size_t len, bool fin,
                                   bool mask) {
-  // First byte: FIN + opcode
-  uint8_t header[2];
-  header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
-                                   (static_cast<uint8_t>(opcode) & 0x0F));
-
-  // Second byte: MASK + payload length
+  // The header (FIN + opcode, MASK + length, the extended length, the mask
+  // key: 14 bytes at most) goes out in one write with the payload's first
+  // chunk, so that under TCP_NODELAY a small frame is one segment, not three.
+  uint8_t header[14];
+  size_t header_len = 0;
+  header[header_len++] = static_cast<uint8_t>(
+      (fin ? 0x80 : 0x00) | (static_cast<uint8_t>(opcode) & 0x0F));
+  uint8_t mask_bit = mask ? 0x80 : 0x00;
   if (len < 126) {
-    header[1] = static_cast<uint8_t>(len);
-    if (mask) { header[1] |= 0x80; }
-    if (!write_data(strm, reinterpret_cast<char *>(header), 2)) {
-      return false;
-    }
+    header[header_len++] = static_cast<uint8_t>(len) | mask_bit;
   } else if (len <= 0xFFFF) {
-    header[1] = 126;
-    if (mask) { header[1] |= 0x80; }
-    if (!write_data(strm, reinterpret_cast<char *>(header), 2)) {
-      return false;
-    }
-    uint8_t ext[2];
-    ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
-    ext[1] = static_cast<uint8_t>(len & 0xFF);
-    if (!write_data(strm, reinterpret_cast<char *>(ext), 2)) { return false; }
+    header[header_len++] = 126 | mask_bit;
+    header[header_len++] = static_cast<uint8_t>((len >> 8) & 0xFF);
+    header[header_len++] = static_cast<uint8_t>(len & 0xFF);
   } else {
-    header[1] = 127;
-    if (mask) { header[1] |= 0x80; }
-    if (!write_data(strm, reinterpret_cast<char *>(header), 2)) {
-      return false;
-    }
-    uint8_t ext[8];
+    header[header_len++] = 127 | mask_bit;
     for (int i = 7; i >= 0; i--) {
-      ext[7 - i] =
+      header[header_len++] =
           static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
     }
-    if (!write_data(strm, reinterpret_cast<char *>(ext), 8)) { return false; }
   }
-
+  uint8_t mask_key[4] = {0};
   if (mask) {
-    // Generate random mask key
-    uint8_t mask_key[4];
     fill_random_bytes(mask_key, sizeof(mask_key));
-    if (!write_data(strm, reinterpret_cast<char *>(mask_key), 4)) {
-      return false;
-    }
+    std::copy(mask_key, mask_key + 4, header + header_len);
+    header_len += 4;
+  }

-    // Write masked payload in chunks
-    const size_t chunk_size = 4096;
-    std::vector<char> buf((std::min)(len, chunk_size));
-    for (size_t offset = 0; offset < len; offset += chunk_size) {
-      size_t n = (std::min)(chunk_size, len - offset);
-      for (size_t i = 0; i < n; i++) {
-        buf[i] =
-            data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
-      }
-      if (!write_data(strm, buf.data(), n)) { return false; }
-    }
-  } else {
-    if (len > 0) {
-      if (!write_data(strm, data, len)) { return false; }
+  // `n` bytes of the payload from `offset`, masked if they are to be, at `out`
+  auto put = [&](char *out, size_t offset, size_t n) {
+    for (size_t i = 0; i < n; i++) {
+      out[i] = mask ? data[offset + i] ^
+                          static_cast<char>(mask_key[(offset + i) % 4])
+                    : data[offset + i];
     }
-  }
+  };
+
+  const size_t chunk_size = 4096;
+  size_t first = (std::min)(len, chunk_size);
+  std::vector<char> buf(header_len + first);
+  std::copy(header, header + header_len, buf.begin());
+  put(buf.data() + header_len, 0, first);
+  if (!write_data(strm, buf.data(), buf.size())) { return false; }

+  // The rest, masked a chunk at a time, or else as it is
+  if (!mask) {
+    return first == len || write_data(strm, data + first, len - first);
+  }
+  for (size_t offset = first; offset < len; offset += chunk_size) {
+    size_t n = (std::min)(chunk_size, len - offset);
+    put(buf.data(), offset, n);
+    if (!write_data(strm, buf.data(), n)) { return false; }
+  }
   return true;
 }

@@ -993,124 +986,143 @@ bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
 namespace ws {
 namespace impl {

-// Read exactly `size` bytes. Stream::read may return less than asked for -- it
-// hands back whatever its buffer already holds -- so every multi-byte field has
-// to loop. Reading a 2-byte header with a single read() fails whenever the
-// header straddles the read buffer's boundary.
-//
-// Timeout is reported only when nothing at all was consumed. Once a byte has
-// been taken the stream sits mid-field and cannot be resumed, so a timeout
-// there is a failure like any other. (When read() fails it always records why,
-// so the error belongs to this call and not to an earlier one.)
-FrameRead read_exact(Stream &strm, void *buf, size_t size) {
-  auto p = static_cast<char *>(buf);
-  size_t total = 0;
-  while (total < size) {
-    auto n = strm.read(p + total, size - total);
-    if (n <= 0) {
-      auto timed_out = total == 0 && strm.get_error() == Error::Timeout;
-      return timed_out ? FrameRead::Timeout : FrameRead::Fail;
-    }
-    total += static_cast<size_t>(n);
-  }
-  return FrameRead::Ok;
+void FrameReader::reset() {
+  have_ = 0;
+  need_ = 2;
+  sized_ = false;
+  len_ = 0;
+  payload_.clear();
 }

-FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
-                                      std::string &payload, bool &fin,
-                                      bool expect_masked, size_t max_len) {
-  // Read first 2 bytes. This is the only read that may report a timeout: it
-  // sits on a frame boundary, where nothing has been consumed yet.
-  uint8_t header[2];
-  FrameRead first = read_exact(strm, header, 2);
-  if (first != FrameRead::Ok) { return first; }
-
-  fin = (header[0] & 0x80) != 0;
-
-  // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
-  if (header[0] & 0x70) { return FrameRead::Fail; }
-
-  opcode = static_cast<Opcode>(header[0] & 0x0F);
-  bool masked = (header[1] & 0x80) != 0;
-  uint64_t payload_len = header[1] & 0x7F;
-
-  // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
-  // MUST have a payload length of 125 bytes or less
-  bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
-  if (is_control) {
-    if (!fin) { return FrameRead::Fail; }
-    if (payload_len > 125) { return FrameRead::Fail; }
-  }
-
-  if (masked != expect_masked) { return FrameRead::Fail; }
-
-  // Extended payload length
-  if (payload_len == 126) {
-    uint8_t ext[2];
-    if (read_exact(strm, ext, 2) != FrameRead::Ok) { return FrameRead::Fail; }
-    payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
-  } else if (payload_len == 127) {
-    uint8_t ext[8];
-    if (read_exact(strm, ext, 8) != FrameRead::Ok) { return FrameRead::Fail; }
-    // RFC 6455 Section 5.2: the most significant bit MUST be 0
-    if (ext[0] & 0x80) { return FrameRead::Fail; }
-    payload_len = 0;
-    for (int i = 0; i < 8; i++) {
-      payload_len = (payload_len << 8) | ext[i];
-    }
-  }
-
-  // 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 && payload_len > max_len) ||
-      !detail::fits_in_size_t(payload_len)) {
+// Stream::read may return less than asked for -- it hands back whatever its
+// buffer already holds -- so each part of the frame is read in a loop, a byte
+// at a time if that is how it comes. (When read() fails it always records why,
+// so the error belongs to this call and not to an earlier one.)
+FrameRead FrameReader::read(Stream &strm, Opcode &opcode,
+                                   std::string &payload, bool &fin,
+                                   bool expect_masked, size_t max_len) {
+  // A timeout keeps what was read; anything else ends the frame
+  auto stopped = [&]() {
+    if (strm.get_error() == Error::Timeout) { return FrameRead::Timeout; }
+    reset();
     return FrameRead::Fail;
-  }
+  };
+  auto reject = [&](FrameRead r) {
+    reset();
+    return r;
+  };

-  // Read mask key if present
-  uint8_t mask_key[4] = {0};
-  if (masked) {
-    if (read_exact(strm, mask_key, 4) != FrameRead::Ok) {
-      return FrameRead::Fail;
+  while (have_ < need_) {
+    auto n = strm.read(reinterpret_cast<char *>(head_) + have_, need_ - have_);
+    if (n <= 0) { return stopped(); }
+    have_ += static_cast<size_t>(n);
+    if (have_ < 2 || need_ > 2) { continue; }
+
+    // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
+    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 reject(FrameRead::ProtocolError);
+    }
+    auto masked = (head_[1] & 0x80) != 0;
+    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);
+  }
+
+  if (!sized_) {
+    uint64_t len = head_[1] & 0x7F;
+    if (len == 126) {
+      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 reject(FrameRead::ProtocolError); }
+      len = 0;
+      for (size_t i = 2; i < 10; i++) {
+        len = (len << 8) | head_[i];
+      }
+    }
+    // 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 reject(FrameRead::TooBig);
     }
+    len_ = static_cast<size_t>(len);
+    sized_ = true;
   }

   // Grow the payload only as it arrives, since a header alone can announce
   // max_len bytes that never come.
-  payload.clear();
-  auto len = static_cast<size_t>(payload_len);
-  while (payload.size() < len) {
-    auto offset = payload.size();
-    auto n = (std::min)(len - offset, CPPHTTPLIB_RECV_BUFSIZ);
-    payload.resize(offset + n);
-    if (read_exact(strm, &payload[offset], n) != FrameRead::Ok) {
-      return FrameRead::Fail;
+  while (payload_.size() < len_) {
+    auto offset = payload_.size();
+    auto n = (std::min)(len_ - offset, CPPHTTPLIB_RECV_BUFSIZ);
+    payload_.resize(offset + n);
+    auto got = strm.read(&payload_[offset], n);
+    if (got <= 0) {
+      payload_.resize(offset);
+      return stopped();
     }
+    payload_.resize(offset + static_cast<size_t>(got));
   }

-  // Unmask if needed
-  if (masked) {
-    for (size_t i = 0; i < payload.size(); i++) {
-      payload[i] ^= static_cast<char>(mask_key[i % 4]);
+  if (head_[1] & 0x80) {
+    const auto *mask_key = head_ + need_ - 4;
+    for (size_t i = 0; i < payload_.size(); i++) {
+      payload_[i] ^= static_cast<char>(mask_key[i % 4]);
     }
   }
-
+  fin = (head_[0] & 0x80) != 0;
+  opcode = static_cast<Opcode>(head_[0] & 0x0F);
+  payload = std::move(payload_);
+  reset();
   return FrameRead::Ok;
 }

+FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
+                                      std::string &payload, bool &fin,
+                                      bool expect_masked, size_t max_len) {
+  FrameReader reader;
+  auto r = reader.read(strm, opcode, payload, fin, expect_masked, max_len);
+  return r == FrameRead::Timeout && reader.begun() ? FrameRead::Fail : r;
+}
+
 // 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
+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]));
+}
+
 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.
+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

@@ -2033,6 +2045,10 @@ public:
   // question that was answered a moment ago. Consumed by that read.
   void set_readable_hint() { readable_hint_ = true; }

+  // Frees the read buffer of an idle stream until its next read. Nothing may
+  // be buffered.
+  void release_buffer();
+
 private:
   bool ensure_readable();

@@ -2089,30 +2105,27 @@ bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
   return false;
 }

-// `has_buffered_request` reports whether the connection's stream already holds
-// bytes of the next request. A client may pipeline its requests (RFC 9112
-// 9.3.2), so reading one request can pull the start of the next one into the
-// stream's buffer; that request must be served without waiting for the socket
-// to become readable again, since its bytes are no longer on the socket.
-// `callback` is told whether keep_alive() has just seen the socket go readable.
-template <typename P, typename T>
-bool process_server_socket_core(const std::atomic<socket_t> &svr_sock,
-                                       socket_t sock,
+// Serves the requests of one connection while they come. A client may
+// pipeline its requests (RFC 9112 9.3.2), so reading one request can pull the
+// start of the next one into the stream's buffer; that request must be served
+// without waiting for the socket to become readable again, since its bytes are
+// no longer on the socket. Otherwise `wait_for_next_request` waits for the
+// socket, and returning false ends the loop. `served` counts the requests
+// served on this connection so far.
+template <typename S, typename W, typename T>
+bool process_server_socket_core(S &strm, size_t &served,
                                        size_t keep_alive_max_count,
-                                       time_t keep_alive_timeout_sec,
-                                       P has_buffered_request, T callback) {
+                                       W wait_for_next_request, T callback) {
   auto ret = false;
   // A keep_alive_max_count of 0 sets no limit.
-  for (size_t served = 0;
-       keep_alive_max_count == 0 || served < keep_alive_max_count; served++) {
-    auto socket_readable = false;
-    if (!has_buffered_request()) {
-      if (!keep_alive(svr_sock, sock, keep_alive_timeout_sec)) { break; }
-      socket_readable = true;
+  for (; keep_alive_max_count == 0 || served < keep_alive_max_count; served++) {
+    if (!strm.is_readable()) {
+      if (!wait_for_next_request()) { break; }
+      strm.set_readable_hint();
     }
     auto close_connection = served + 1 == keep_alive_max_count;
     auto connection_closed = false;
-    ret = callback(socket_readable, close_connection, connection_closed);
+    ret = callback(strm, close_connection, connection_closed);
     if (!ret || connection_closed) { break; }
   }
   return ret;
@@ -2129,14 +2142,11 @@ process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
   // the next, pipelined request.
   SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
                     write_timeout_sec, write_timeout_usec);
+  size_t served = 0;
   return process_server_socket_core(
-      svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
-      [&]() { return strm.is_readable(); },
-      [&](bool socket_readable, bool close_connection,
-          bool &connection_closed) {
-        if (socket_readable) { strm.set_readable_hint(); }
-        return callback(strm, close_connection, connection_closed);
-      });
+      strm, served, keep_alive_max_count,
+      [&]() { return keep_alive(svr_sock, sock, keep_alive_timeout_sec); },
+      callback);
 }

 bool process_client_socket(
@@ -2163,8 +2173,10 @@ int shutdown_socket(socket_t sock) noexcept {
 // the final shutdown+close. Closing with unread data in the receive queue
 // (or bytes arriving after the receive side is closed) makes the stack send
 // an abortive RST instead of a graceful FIN, which can make the peer see the
-// response as a failed read even though it was fully written.
-void drain_and_close_socket(socket_t sock) noexcept {
+// response as a failed read even though it was fully written. With a
+// `wait_msec` of 0, it reads once, without waiting.
+void drain_and_close_socket(socket_t sock,
+                                   time_t wait_msec = 100) noexcept {
 #ifdef _WIN32
   shutdown(sock, SD_SEND);
 #else
@@ -2174,19 +2186,21 @@ void drain_and_close_socket(socket_t sock) noexcept {
   char buf[CPPHTTPLIB_RECV_BUFSIZ];
   size_t total = 0;
   const auto deadline = std::chrono::steady_clock::now() +
-                        std::chrono::milliseconds(100); // bound #1
-
-  while (total < size_t(1024u * 1024u)) { // bound #2
-    const auto remaining =
-        std::chrono::duration_cast<std::chrono::microseconds>(
-            deadline - std::chrono::steady_clock::now())
-            .count();
-    if (remaining <= 0) { break; }
-    if (select_read(sock, 0, static_cast<time_t>(remaining)) <= 0) { break; }
+                        std::chrono::milliseconds(wait_msec); // bound #1
+  auto usec_left = [&]() {
+    const auto left = std::chrono::duration_cast<std::chrono::microseconds>(
+                          deadline - std::chrono::steady_clock::now())
+                          .count();
+    return static_cast<time_t>(
+        (std::max)(left, std::chrono::microseconds::rep(0)));
+  };
+
+  do {
+    if (select_read(sock, 0, usec_left()) <= 0) { break; }
     const auto n = read_socket(sock, buf, sizeof(buf), CPPHTTPLIB_RECV_FLAGS);
     if (n <= 0) { break; }
     total += static_cast<size_t>(n);
-  }
+  } while (usec_left() > 0 && total < size_t(1024u * 1024u)); // bound #2

   shutdown_socket(sock);
   close_socket(sock);
@@ -2737,6 +2751,338 @@ bool is_accept_transient_error() {
 #endif
 }

+socket_t accept_socket(socket_t svr_sock) {
+#if defined _WIN32
+  // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
+  // OVERLAPPED
+  return WSAAccept(svr_sock, nullptr, nullptr, nullptr, 0);
+#elif defined SOCK_CLOEXEC
+  return accept4(svr_sock, nullptr, nullptr, SOCK_CLOEXEC);
+#else
+  return accept(svr_sock, nullptr, nullptr);
+#endif
+}
+
+bool is_would_block_error() {
+#ifdef _WIN32
+  return WSAGetLastError() == WSAEWOULDBLOCK;
+#else
+  return errno == EAGAIN || errno == EWOULDBLOCK;
+#endif
+}
+
+bool create_socket_pair(socket_t sv[2]) {
+#ifdef _WIN32
+  auto listener = create_socket(
+      std::string(), "127.0.0.1", 0, AF_INET, 0, false, false, nullptr,
+      [](socket_t sock, struct addrinfo &ai, bool &) {
+        return ::bind(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen)) == 0 &&
+               ::listen(sock, 1) == 0;
+      });
+  if (listener == INVALID_SOCKET) { return false; }
+
+  socket_t a = INVALID_SOCKET;
+  socket_t b = INVALID_SOCKET;
+  sockaddr_in addr{};
+  auto addr_len = static_cast<int>(sizeof(addr));
+  if (::getsockname(listener, reinterpret_cast<sockaddr *>(&addr), &addr_len) ==
+      0) {
+    a = create_socket(std::string(), "127.0.0.1", ntohs(addr.sin_port), AF_INET,
+                      0, true, false, nullptr,
+                      [](socket_t sock, struct addrinfo &ai, bool &) {
+                        return ::connect(sock, ai.ai_addr,
+                                         static_cast<int>(ai.ai_addrlen)) == 0;
+                      });
+    // Unlike accept(), this keeps the listener's no-inherit flag.
+    if (a != INVALID_SOCKET) {
+      b = WSAAccept(listener, nullptr, nullptr, nullptr, 0);
+    }
+  }
+  close_socket(listener);
+
+  // Any local process could connect while the listener was open, so make sure
+  // that the connection we accepted is the one we made.
+  if (b != INVALID_SOCKET) {
+    sockaddr_in local{}, peer{};
+    auto local_len = static_cast<int>(sizeof(local));
+    auto peer_len = static_cast<int>(sizeof(peer));
+    if (::getsockname(a, reinterpret_cast<sockaddr *>(&local), &local_len) !=
+            0 ||
+        ::getpeername(b, reinterpret_cast<sockaddr *>(&peer), &peer_len) != 0 ||
+        local.sin_port != peer.sin_port ||
+        local.sin_addr.s_addr != peer.sin_addr.s_addr) {
+      close_socket(b);
+      b = INVALID_SOCKET;
+    }
+  }
+
+  if (b == INVALID_SOCKET) {
+    if (a != INVALID_SOCKET) { close_socket(a); }
+    return false;
+  }
+  sv[0] = a;
+  sv[1] = b;
+  return true;
+#else
+#ifdef SOCK_CLOEXEC
+  return ::socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) == 0;
+#else
+  if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) { return false; }
+  fcntl(sv[0], F_SETFD, FD_CLOEXEC);
+  fcntl(sv[1], F_SETFD, FD_CLOEXEC);
+  return true;
+#endif
+#endif
+}
+
+PollerWaker::~PollerWaker() {
+  if (pair_fd_ != INVALID_SOCKET) { close_socket(pair_fd_); }
+  if (fd_ != INVALID_SOCKET) { close_socket(fd_); }
+}
+
+bool PollerWaker::open() {
+  // wake() must not block its caller, and drain() must not block the poller.
+#ifdef __linux__
+  fd_ = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
+  return fd_ != INVALID_SOCKET;
+#else
+  socket_t sv[2];
+  if (!create_socket_pair(sv)) { return false; }
+  fd_ = sv[0];
+  pair_fd_ = sv[1];
+  set_nonblocking(fd_, true);
+  set_nonblocking(pair_fd_, true);
+  return true;
+#endif
+}
+
+void PollerWaker::wake() noexcept {
+  if (pending_.exchange(true)) { return; }
+#ifdef __linux__
+  const uint64_t one = 1;
+  auto r = write(fd_, &one, sizeof(one));
+  (void)r;
+#else
+  const char c = 1;
+  send_socket(pair_fd_, &c, 1, CPPHTTPLIB_SEND_FLAGS);
+#endif
+}
+
+void PollerWaker::drain() noexcept {
+  // While pending_ is set, at most one wake is unread, and one read takes it.
+#ifdef __linux__
+  uint64_t count;
+  auto r = read(fd_, &count, sizeof(count));
+  (void)r;
+#else
+  char buf[64];
+  read_socket(fd_, buf, sizeof(buf), CPPHTTPLIB_RECV_FLAGS);
+#endif
+  // Only after the read: cleared before it, a wake() in between would be read
+  // here and leave pending_ set with nothing to read. One skipped during the
+  // read is fine, as the caller checks what it was woken for afterwards.
+  pending_ = false;
+}
+
+std::unique_ptr<Poller> PollPoller::create() {
+  std::unique_ptr<PollPoller> poller(new PollPoller());
+  if (!poller->waker_.open()) { return nullptr; }
+
+  struct pollfd pfd;
+  pfd.fd = poller->waker_.fd();
+  pfd.events = POLLIN;
+  pfd.revents = 0;
+  poller->fds_.push_back(pfd);
+  poller->tokens_.push_back(0);
+  return std::unique_ptr<Poller>(poller.release());
+}
+
+bool PollPoller::arm(socket_t fd, Token token) {
+  assert(index_.find(fd) == index_.end());
+
+  struct pollfd pfd;
+  pfd.fd = fd;
+  pfd.events = POLLIN;
+  pfd.revents = 0;
+  index_[fd] = fds_.size();
+  fds_.push_back(pfd);
+  tokens_.push_back(token);
+  return true;
+}
+
+void PollPoller::disarm(socket_t fd) {
+  auto it = index_.find(fd);
+  if (it != index_.end()) { remove_at(it->second); }
+}
+
+// Fills the hole with the last entry, so that arm() and disarm() are O(1).
+void PollPoller::remove_at(size_t index) {
+  assert(index > 0 && index < fds_.size());
+  auto last = fds_.size() - 1;
+  index_.erase(fds_[index].fd);
+  if (index != last) {
+    fds_[index] = fds_[last];
+    tokens_[index] = tokens_[last];
+    index_[fds_[index].fd] = index;
+  }
+  fds_.pop_back();
+  tokens_.pop_back();
+}
+
+bool PollPoller::wait(int timeout_ms, std::vector<Token> &ready) {
+  ready.clear();
+
+  auto n = handle_EINTR([&]() {
+    return poll_wrapper(fds_.data(), static_cast<nfds_t>(fds_.size()),
+                        timeout_ms);
+  });
+  if (n <= 0) { return false; }
+
+  auto woken = fds_[0].revents != 0;
+  if (woken) {
+    n--;
+    waker_.drain();
+  }
+
+  // Walk backwards: remove_at() moves the last entry, already seen, into the
+  // freed slot.
+  for (auto i = fds_.size(); n > 0 && i-- > 1;) {
+    auto revents = fds_[i].revents;
+    if (revents == 0) { continue; }
+    n--;
+    assert(!(revents & POLLNVAL)); // closed while armed
+    if (!(revents & POLLNVAL)) { ready.push_back(tokens_[i]); }
+    remove_at(i);
+  }
+  return woken;
+}
+
+#ifdef __linux__
+std::unique_ptr<Poller> EpollPoller::create() {
+  std::unique_ptr<EpollPoller> poller(new EpollPoller());
+  poller->epfd_ = epoll_create1(EPOLL_CLOEXEC);
+  if (poller->epfd_ < 0 || !poller->waker_.open()) { return nullptr; }
+
+  epoll_event ev{};
+  ev.events = EPOLLIN; // level-triggered: it stays readable until drained
+  ev.data.u64 = poller->waker_.token();
+  if (epoll_ctl(poller->epfd_, EPOLL_CTL_ADD, poller->waker_.fd(), &ev) != 0) {
+    return nullptr;
+  }
+  poller->events_.resize(256);
+  return std::unique_ptr<Poller>(poller.release());
+}
+
+EpollPoller::~EpollPoller() {
+  if (epfd_ >= 0) { close(epfd_); }
+}
+
+bool EpollPoller::arm(socket_t fd, Token token) {
+  epoll_event ev{};
+  ev.events = EPOLLIN | EPOLLONESHOT;
+  ev.data.u64 = token;
+  // A delivered descriptor stays registered, only disabled, so modify it.
+  // One that was closed in between, or never armed, has to be added.
+  return epoll_ctl(epfd_, EPOLL_CTL_MOD, fd, &ev) == 0 ||
+         (errno == ENOENT && epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &ev) == 0);
+}
+
+void EpollPoller::disarm(socket_t fd) {
+  epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, nullptr);
+}
+
+bool EpollPoller::wait(int timeout_ms, std::vector<Token> &ready) {
+  ready.clear();
+  auto n = handle_EINTR([&]() {
+    return epoll_wait(epfd_, events_.data(), static_cast<int>(events_.size()),
+                      timeout_ms);
+  });
+
+  auto woken = false;
+  for (auto i = 0; i < n; i++) {
+    auto token = static_cast<Token>(events_[static_cast<size_t>(i)].data.u64);
+    if (token == waker_.token()) {
+      woken = true;
+      waker_.drain();
+    } else {
+      ready.push_back(token);
+    }
+  }
+  return woken;
+}
+#endif
+
+#ifdef CPPHTTPLIB_KQUEUE_POLLER
+std::unique_ptr<Poller> KqueuePoller::create() {
+  std::unique_ptr<KqueuePoller> poller(new KqueuePoller());
+  poller->kq_ = kqueue();
+  if (poller->kq_ < 0) { return nullptr; }
+  fcntl(poller->kq_, F_SETFD, FD_CLOEXEC);
+  if (!poller->waker_.open()) { return nullptr; }
+
+  // Level-triggered: it stays readable until drained.
+  struct kevent ev;
+  EV_SET(&ev, poller->waker_.fd(), EVFILT_READ, EV_ADD, 0, 0,
+         reinterpret_cast<void *>(poller->waker_.token()));
+  if (kevent(poller->kq_, &ev, 1, nullptr, 0, nullptr) != 0) { return nullptr; }
+  poller->events_.resize(256);
+  return std::unique_ptr<Poller>(poller.release());
+}
+
+KqueuePoller::~KqueuePoller() {
+  if (kq_ >= 0) { close(kq_); }
+}
+
+bool KqueuePoller::arm(socket_t fd, Token token) {
+  // EV_ONESHOT deletes the event once it is delivered.
+  struct kevent ev;
+  EV_SET(&ev, fd, EVFILT_READ, EV_ADD | EV_ONESHOT, 0, 0,
+         reinterpret_cast<void *>(token));
+  return kevent(kq_, &ev, 1, nullptr, 0, nullptr) == 0;
+}
+
+void KqueuePoller::disarm(socket_t fd) {
+  struct kevent ev;
+  EV_SET(&ev, fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr);
+  kevent(kq_, &ev, 1, nullptr, 0, nullptr);
+}
+
+bool KqueuePoller::wait(int timeout_ms, std::vector<Token> &ready) {
+  ready.clear();
+  struct timespec ts;
+  ts.tv_sec = timeout_ms / 1000;
+  ts.tv_nsec = static_cast<long>(timeout_ms % 1000) * 1000000;
+  auto n = handle_EINTR([&]() {
+    return kevent(kq_, nullptr, 0, events_.data(),
+                  static_cast<int>(events_.size()),
+                  timeout_ms < 0 ? nullptr : &ts);
+  });
+
+  auto woken = false;
+  for (auto i = 0; i < n; i++) {
+    auto token = reinterpret_cast<Token>(events_[static_cast<size_t>(i)].udata);
+    if (token == waker_.token()) {
+      woken = true;
+      waker_.drain();
+    } else {
+      ready.push_back(token);
+    }
+  }
+  return woken;
+}
+#endif
+
+std::unique_ptr<Poller> make_poller() {
+#if defined(__linux__)
+  auto poller = EpollPoller::create();
+  if (poller) { return poller; }
+#elif defined(CPPHTTPLIB_KQUEUE_POLLER)
+  auto poller = KqueuePoller::create();
+  if (poller) { return poller; }
+#endif
+  return PollPoller::create();
+}
+
 bool bind_ip_address(socket_t sock, const std::string &host) {
   struct addrinfo hints;
   struct addrinfo *result;
@@ -4635,8 +4981,10 @@ void parse_disposition_params(const std::string &s, Params &params) {
         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));
         }
       });
 }
@@ -6156,14 +6504,11 @@ bool process_server_socket_ssl(
   // of a pipelined request, which keep_alive() cannot see on the socket.
   SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
                        write_timeout_sec, write_timeout_usec);
+  size_t served = 0;
   return process_server_socket_core(
-      svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
-      [&]() { return strm.is_readable(); },
-      [&](bool socket_readable, bool close_connection,
-          bool &connection_closed) {
-        if (socket_readable) { strm.set_readable_hint(); }
-        return callback(strm, close_connection, connection_closed);
-      });
+      strm, served, keep_alive_max_count,
+      [&]() { return keep_alive(svr_sock, sock, keep_alive_timeout_sec); },
+      callback);
 }

 template <typename T>
@@ -6478,6 +6823,21 @@ bool load_client_ca_config(tls::ctx_t ctx,
   return ret;
 }

+#ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
+// Schannel is skipped when a custom CA is specified, as the Windows
+// certificate store would not know about it, and when system CA trust is
+// explicitly disabled.
+bool use_windows_cert_verification(bool enabled,
+                                          const std::string &ca_cert_file_path,
+                                          const std::string &ca_cert_dir_path,
+                                          bool has_custom_store,
+                                          SystemCAMode mode) {
+  return enabled && mode != SystemCAMode::Disabled &&
+         ca_cert_file_path.empty() && ca_cert_dir_path.empty() &&
+         !has_custom_store;
+}
+#endif
+
 // Serializes the CA certificates installed in ctx as PEM, so they can be
 // loaded into another context.
 std::string ca_certs_to_pem(tls::ctx_t ctx) {
@@ -6523,8 +6883,7 @@ struct ClientTlsSessionOptions {
   // begin with, so it passes nothing.
   std::mutex *ctx_mutex = nullptr;
 #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
-  // The caller decides whether Schannel has anything to say about this
-  // connection; see SSLClient::initialize_ssl().
+  // See use_windows_cert_verification().
   bool windows_cert_verification = false;
   // A server certificate verifier works on the backend's chain verification,
   // so the backend keeps deciding and Schannel only adds its own check.
@@ -7879,8 +8238,7 @@ SocketStream::SocketStream(
       read_timeout_usec_(read_timeout_usec),
       write_timeout_sec_(write_timeout_sec),
       write_timeout_usec_(write_timeout_usec),
-      max_timeout_msec_(max_timeout_msec), start_time_(start_time),
-      read_buff_(read_buff_size_, 0) {}
+      max_timeout_msec_(max_timeout_msec), start_time_(start_time) {}

 SocketStream::~SocketStream() = default;

@@ -7920,6 +8278,11 @@ const char *SocketStream::buffered_data(size_t &size) const {
   return size ? read_buff_.data() + read_buff_off_ : nullptr;
 }

+void SocketStream::release_buffer() {
+  assert(read_buff_off_ == read_buff_content_size_);
+  std::vector<char>().swap(read_buff_);
+}
+
 void SocketStream::consume_buffered(size_t size) {
   assert(size <= read_buff_content_size_ - read_buff_off_);
   read_buff_off_ += size;
@@ -7960,6 +8323,8 @@ ssize_t SocketStream::read(char *ptr, size_t size) {
   read_buff_content_size_ = 0;

   if (size < read_buff_size_) {
+    // Allocated on the first use, which an idle connection may never make.
+    if (read_buff_.empty()) { read_buff_.resize(read_buff_size_); }
     auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
                          CPPHTTPLIB_RECV_FLAGS);
     if (n <= 0) {
@@ -8784,6 +9149,228 @@ WebSocketSSLStream::set_read_interrupt(std::function<bool()> interrupted) {
  * Group 4: Server implementation
  */

+// A kept-alive connection that the event loop of set_keep_alive_parking()
+// owns while it is idle, and a worker owns while it serves a request. A
+// derived class adds the transport: the stream, and for TLS the session.
+struct Server::KeepAliveConnection {
+  KeepAliveConnection(socket_t s, Server &server) : svr(server), sock(s) {}
+  // Every owner closes it before letting go, which the transport hooks need;
+  // this is only a net, which cannot reach them any more.
+  virtual ~KeepAliveConnection() {
+    if (sock != INVALID_SOCKET) { detail::drain_and_close_socket(sock, 0); }
+  }
+
+  // On a worker before the first request, e.g. for a TLS handshake. False
+  // closes the connection. One that reads from the socket clears turn.woken.
+  virtual bool open() { return true; }
+  // Serves requests while they come: serve_on() with the transport's stream.
+  virtual bool serve() = 0;
+  // Before it is parked. Nothing is buffered then.
+  virtual void release_buffers() {}
+  // Before the socket of an open connection is closed, e.g. to send TLS
+  // close_notify.
+  virtual void shut_down(bool /*graceful*/) {}
+
+  // On a worker, once the event loop has seen the socket readable. Afterwards
+  // turn.park tells whether it may be parked again.
+  bool resume() {
+    turn = Turn();
+    return svr.serve_guarded([this]() {
+      if (!opened) {
+        detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
+        detail::get_local_ip_and_port(sock, local_addr, local_port);
+        if (!open()) { return false; }
+        opened = true;
+      }
+      return serve();
+    });
+  }
+
+  // From the event loop, which must not wait for the peer.
+  void close_idle() {
+    assert(sock != INVALID_SOCKET);
+    if (opened) {
+      detail::set_nonblocking(sock, true);
+      shut_down(true);
+    }
+    detail::drain_and_close_socket(sock, 0);
+    sock = INVALID_SOCKET;
+  }
+
+  // From the worker that served it.
+  void close_served(bool graceful) {
+    assert(sock != INVALID_SOCKET);
+    if (opened) {
+      shut_down(graceful);
+      detail::drain_and_close_socket(sock);
+    } else {
+      // It never got as far as a request, e.g. a failed TLS handshake.
+      detail::shutdown_socket(sock);
+      detail::close_socket(sock);
+    }
+    sock = INVALID_SOCKET;
+  }
+
+  template <typename S>
+  bool serve_on(S &strm,
+                const std::function<void(Request &)> &setup_request = nullptr) {
+    return detail::process_server_socket_core(
+        strm, served, svr.keep_alive_max_count_,
+        [this]() { return wait_for_next_request(); },
+        [&](Stream &s, bool close_connection, bool &connection_closed) {
+          return svr.process_request(s, remote_addr, remote_port, local_addr,
+                                     local_port, close_connection,
+                                     connection_closed, setup_request,
+                                     &turn.websocket_upgraded);
+        });
+  }
+
+  bool wait_for_next_request() {
+    // The event loop saw the socket readable just before this ran.
+    if (turn.woken) {
+      turn.woken = false;
+      return true;
+    }
+    if (svr.is_stopping()) { return false; }
+    // Waiting here for a slow client would keep the worker from others.
+    turn.park = detail::select_read(sock, 0, 0) <= 0;
+    return !turn.park;
+  }
+
+  // A worker's time with it, from resume() until it is parked or closed.
+  struct Turn {
+    bool woken = true;
+    bool park = false;
+    bool websocket_upgraded = false;
+  };
+
+  Server &svr;
+  socket_t sock;
+  int remote_port = 0;
+  int local_port = 0;
+  bool opened = false; // by resume(), once open() has succeeded
+  Turn turn;
+  size_t served = 0;
+  std::string remote_addr;
+  std::string local_addr;
+
+  // While parked
+  std::list<std::shared_ptr<KeepAliveConnection>>::iterator parked_at;
+  std::chrono::steady_clock::time_point deadline;
+};
+
+struct Server::PlainConnection final : Server::KeepAliveConnection {
+  PlainConnection(socket_t s, Server &server)
+      : KeepAliveConnection(s, server),
+        strm(s, server.read_timeout_sec_, server.read_timeout_usec_,
+             server.write_timeout_sec_, server.write_timeout_usec_) {}
+
+  bool serve() override { return serve_on(strm); }
+  void release_buffers() override { strm.release_buffer(); }
+
+  // Kept across requests: it may hold the start of a pipelined request.
+  detail::SocketStream strm;
+};
+
+struct Server::ParkingState {
+  using Clock = std::chrono::steady_clock;
+  using Token = detail::Poller::Token;
+  using Connection = std::shared_ptr<KeepAliveConnection>;
+
+  // Kept for the Server's life, so that stop() can wake() it without a lock.
+  std::unique_ptr<detail::Poller> poller;
+
+  // The listening socket while parking_loop() watches it. Whichever of stop()
+  // and parking_loop() takes it out of here decides who closes it, so that it
+  // is never closed while the poller still watches it.
+  std::atomic<socket_t> listen_sock{INVALID_SOCKET};
+
+  // From stop(): whether parking_loop() takes over closing `sock`.
+  bool release_listen(socket_t sock) {
+    if (!listen_sock.compare_exchange_strong(sock, INVALID_SOCKET)) {
+      return false;
+    }
+    poller->wake();
+    return true;
+  }
+
+  // From a worker: hands an idle connection back, unless the loop has ended.
+  bool give_back(Connection conn) {
+    {
+      std::lock_guard<std::mutex> guard(mutex);
+      if (closed) { return false; }
+      returned.push_back(std::move(conn));
+    }
+    poller->wake();
+    return true;
+  }
+
+  // The rest belongs to parking_loop(). A parked connection's token is its
+  // address, and `parked` lists them in the order they expire.
+
+  // Closes it and returns false when the poller cannot watch it: unwatched,
+  // it would only wait for its deadline.
+  bool park(Connection conn, Clock::time_point deadline) {
+    auto &c = *conn;
+    c.deadline = deadline;
+    c.parked_at = parked.insert(parked.end(), std::move(conn));
+    if (poller->arm(c.sock, reinterpret_cast<Token>(&c))) { return true; }
+    unpark(reinterpret_cast<Token>(&c))->close_idle();
+    return false;
+  }
+
+  Connection unpark(Token token) {
+    auto &c = *reinterpret_cast<KeepAliveConnection *>(token);
+    auto conn = std::move(*c.parked_at);
+    parked.erase(c.parked_at);
+    return conn;
+  }
+
+  Clock::time_point next_deadline() const {
+    return parked.empty() ? (Clock::time_point::max)()
+                          : parked.front()->deadline;
+  }
+
+  void expire(Clock::time_point now) {
+    while (!parked.empty() && parked.front()->deadline <= now) {
+      poller->disarm(parked.front()->sock);
+      parked.front()->close_idle();
+      parked.pop_front();
+    }
+  }
+
+  // Closes them here rather than wherever the last reference goes, which may
+  // be a worker that has just given one back, or the destructor, which cannot
+  // reach the transport.
+  void close_all() {
+    std::vector<Connection> left;
+    {
+      std::lock_guard<std::mutex> guard(mutex);
+      closed = true;
+      left.swap(returned);
+    }
+    for (auto &conn : parked) {
+      poller->disarm(conn->sock);
+      conn->close_idle();
+    }
+    for (auto &conn : left) {
+      conn->close_idle();
+    }
+    for (auto &conn : backlog) {
+      conn->close_idle();
+    }
+    parked.clear();
+    backlog.clear();
+  }
+
+  std::mutex mutex;
+  std::vector<Connection> returned;
+  bool closed = false;
+
+  std::list<Connection> parked;
+  std::list<Connection> backlog;
+};
+
 // HTTP server implementation
 Server::Server()
     : new_task_queue([] {
@@ -8793,6 +9380,7 @@ Server::Server()
 #ifndef _WIN32
   signal(SIGPIPE, SIG_IGN);
 #endif
+  set_keep_alive_parking(CPPHTTPLIB_KEEPALIVE_PARKING);
 }

 Server::~Server() = default;
@@ -9053,6 +9641,11 @@ Server &Server::set_start_handler(StartHandler handler) {
   return *this;
 }

+Server &Server::set_accept_handler(AcceptHandler handler) {
+  accept_handler_ = std::move(handler);
+  return *this;
+}
+
 Server &Server::set_address_family(int family) {
   address_family_ = family;
   return *this;
@@ -9128,6 +9721,20 @@ Server &Server::set_write_timeout(time_t sec, time_t usec) {
 Server &Server::set_idle_interval(time_t sec, time_t usec) {
   idle_interval_sec_ = sec;
   idle_interval_usec_ = usec;
+  idle_interval_set_ = true;
+  return *this;
+}
+
+Server &Server::set_keep_alive_parking(bool on) {
+  // Never destroyed once made: stop() may use it from another thread.
+  if (on && !parking_) {
+    auto poller = detail::make_poller();
+    if (poller) {
+      parking_.reset(new ParkingState());
+      parking_->poller = std::move(poller);
+    }
+  }
+  keep_alive_parking_ = on;
   return *this;
 }

@@ -9161,6 +9768,11 @@ Server &Server::set_websocket_max_missed_pongs(int count) {
   return *this;
 }

+Server &Server::set_websocket_max_message_length(size_t length) {
+  websocket_max_message_length_ = length;
+  return *this;
+}
+
 Server &Server::set_websocket_ping_interval(time_t sec) {
   websocket_ping_interval_sec_ = sec;
   return *this;
@@ -9207,7 +9819,7 @@ void Server::stop() noexcept {
   // bind_to_port() without listen_after_bind() still owns the descriptor. The
   // exchange is what makes this safe to call concurrently with the accept loop.
   socket_t sock = svr_sock_.exchange(INVALID_SOCKET);
-  if (sock != INVALID_SOCKET) {
+  if (sock != INVALID_SOCKET && !(parking_ && parking_->release_listen(sock))) {
     detail::shutdown_socket(sock);
     detail::close_socket(sock);
   }
@@ -9829,78 +10441,79 @@ bool Server::listen_internal() {
   {
     std::unique_ptr<TaskQueue> task_queue(new_task_queue());

-    while (svr_sock_ != INVALID_SOCKET) {
+    ret = keep_alive_parking_ && parking_ ? parking_loop(*task_queue)
+                                          : accept_loop(*task_queue);
+
+    task_queue->shutdown();
+  }
+
+  is_decommissioned = !ret;
+  return ret;
+}
+
+// Closes the socket and returns false when the accept handler refuses it.
+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.
+bool Server::accept_loop(TaskQueue &task_queue) {
+  auto ret = true;
+  while (svr_sock_ != INVALID_SOCKET) {
 #ifndef _WIN32
-      if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
+    if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
 #endif
-        auto val = detail::select_read(svr_sock_, idle_interval_sec_,
-                                       idle_interval_usec_);
-        if (val == 0) { // Timeout
-          task_queue->on_idle();
-          continue;
-        }
-#ifndef _WIN32
+      auto val = detail::select_read(svr_sock_, idle_interval_sec_,
+                                     idle_interval_usec_);
+      if (val == 0) { // Timeout
+        task_queue.on_idle();
+        continue;
       }
+#ifndef _WIN32
+    }
 #endif

-#if defined _WIN32
-      // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
-      // OVERLAPPED
-      socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
-#elif defined SOCK_CLOEXEC
-      socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
-#else
-      socket_t sock = accept(svr_sock_, nullptr, nullptr);
-#endif
+    auto sock = detail::accept_socket(svr_sock_);

-      if (sock == INVALID_SOCKET) {
-        // NOTE: Winsock reports failures through WSAGetLastError() and never
-        // touches the CRT errno, so the two have to be asked platform by
-        // platform rather than by testing errno here.
-        if (detail::is_accept_resource_error()) {
-          // The per-process descriptor limit or the network stack's buffer
-          // space has been reached. Try to accept new connections after a
-          // short sleep.
-          std::this_thread::sleep_for(std::chrono::microseconds{1});
-          continue;
-        } else if (detail::is_accept_transient_error()) {
-          continue;
-        }
-        // Take the descriptor out of svr_sock_ before closing it: a later
-        // stop() would otherwise shutdown()/close() a value the OS may have
-        // reused, and keep_alive() watches svr_sock_ to notice the server is
-        // gone. The exchange also settles the race with a concurrent stop(),
-        // since whichever side takes the descriptor closes it exactly once.
-        auto listen_sock = svr_sock_.exchange(INVALID_SOCKET);
-        if (listen_sock != INVALID_SOCKET) {
-          detail::close_socket(listen_sock);
-          ret = false;
-          output_error_log(Error::Connection, nullptr);
-        } else {
-          ; // The server socket was closed by user.
-        }
-        break;
+    if (sock == INVALID_SOCKET) {
+      // NOTE: Winsock reports failures through WSAGetLastError() and never
+      // touches the CRT errno, so the two have to be asked platform by
+      // platform rather than by testing errno here.
+      if (detail::is_accept_resource_error()) {
+        // The per-process descriptor limit or the network stack's buffer
+        // space has been reached. Try to accept new connections after a
+        // short sleep.
+        std::this_thread::sleep_for(std::chrono::microseconds{1});
+        continue;
+      } else if (detail::is_accept_transient_error()) {
+        continue;
       }
+      if (abandon_listen_socket()) { ret = false; }
+      break;
+    }

-      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); }
+    if (!admit_accepted_socket(sock)) { continue; }

-      if (!task_queue->enqueue(
-              [this, sock]() { process_and_close_socket(sock); })) {
-        output_error_log(Error::ResourceExhaustion, nullptr);
-        detail::shutdown_socket(sock);
-        detail::close_socket(sock);
-      }
+    if (!task_queue.enqueue(
+            [this, sock]() { process_and_close_socket(sock); })) {
+      output_error_log(Error::ResourceExhaustion, nullptr);
+      detail::shutdown_socket(sock);
+      detail::close_socket(sock);
     }
-
-    task_queue->shutdown();
   }
-
-  is_decommissioned = !ret;
   return ret;
 }

@@ -10576,6 +11189,13 @@ 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);
+      }

 #ifdef CPPHTTPLIB_SSL_ENABLED
       if (req.ssl) {
@@ -10587,17 +11207,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;
     }
@@ -10715,6 +11332,190 @@ bool Server::process_and_close_socket(socket_t sock) {
   return ret;
 }

+// After accept() failed for good. Takes the descriptor out of svr_sock_
+// before closing it: a later stop() would otherwise shutdown()/close() a value
+// the OS may have reused, and keep_alive() watches svr_sock_ to notice the
+// server is gone. The exchange also settles the race with a concurrent stop(),
+// since whichever side takes the descriptor closes it exactly once. Returns
+// false when stop() took it first.
+bool Server::abandon_listen_socket() {
+  auto sock = svr_sock_.exchange(INVALID_SOCKET);
+  if (sock == INVALID_SOCKET) { return false; }
+  detail::close_socket(sock);
+  output_error_log(Error::Connection, nullptr);
+  return true;
+}
+
+// Like accept_loop(), but a connection waiting for its next request sits in
+// the poller instead of keeping a worker. A worker serves a connection while it
+// has requests to read, then gives it back to this loop.
+bool Server::parking_loop(TaskQueue &task_queue) {
+  using Clock = ParkingState::Clock;
+  using Connection = ParkingState::Connection;
+  const ParkingState::Token listen_token = 0;
+  const auto never = (Clock::time_point::max)();
+
+  auto &st = *parking_;
+  auto &poller = *st.poller;
+
+  std::vector<ParkingState::Token> ready;
+  poller.wait(0, ready); // drops a wake() left from an earlier stop()
+  {
+    std::lock_guard<std::mutex> guard(st.mutex);
+    st.closed = false;
+  }
+
+  // Publish the listening socket before checking that stop() has not taken it,
+  // so that a stop() from now on leaves closing it to this loop.
+  auto listen_sock = svr_sock_.load();
+  st.listen_sock = listen_sock;
+  auto listening = listen_sock != INVALID_SOCKET && svr_sock_ == listen_sock;
+  if (listening) { detail::set_nonblocking(listen_sock, true); }
+  auto listen_rearm_at = Clock::now(); // `never` while it is armed
+  auto fatal = false;
+
+  const auto check_interval =
+      std::chrono::duration_cast<Clock::duration>(std::chrono::microseconds(
+          CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND));
+  // Never shorter than the interval keep_alive() first waits, so that a
+  // request sent right after connecting is served even with a timeout of 0.
+  const auto keep_alive =
+      (std::max)(Clock::duration(std::chrono::seconds(keep_alive_timeout_sec_)),
+                 check_interval);
+  // Only an interval the user asked for: Windows' default exists for the sake
+  // of stop(), which wake() already serves here.
+  const auto idle = std::chrono::microseconds(
+      idle_interval_set_ ? idle_interval_sec_ * 1000000 + idle_interval_usec_
+                         : 0);
+  auto next_idle = idle.count() > 0 ? Clock::now() + idle : never;
+
+  auto park = [&](Connection conn, Clock::time_point now) {
+    if (!st.park(std::move(conn), now + keep_alive)) {
+      output_error_log(Error::ResourceExhaustion, nullptr);
+    }
+  };
+  auto dispatch = [&](const Connection &conn) {
+    return task_queue.enqueue([this, conn]() { resume_connection(conn); });
+  };
+  // The only way into the queue besides the backlog, which nothing overtakes.
+  // When the queue is full, a new connection is turned away, as accept_loop()
+  // does, and an established one waits in the backlog, since closing it would
+  // lose its request. A TaskQueue gives no sign when it has room again, so the
+  // backlog is retried every check_interval.
+  auto submit = [&](Connection conn) {
+    if (st.backlog.empty() && dispatch(conn)) { return; }
+    if (conn->opened) {
+      st.backlog.push_back(std::move(conn));
+      return;
+    }
+    conn->close_idle();
+    output_error_log(Error::ResourceExhaustion, nullptr);
+  };
+
+  std::vector<Connection> returned;
+  while (listening && svr_sock_ == listen_sock) {
+    auto now = Clock::now();
+    if (now >= listen_rearm_at) {
+      listen_rearm_at =
+          poller.arm(listen_sock, listen_token) ? never : now + check_interval;
+    }
+
+    // At most a minute, which keeps the timeout below within an int.
+    auto until = (std::min)({st.next_deadline(), listen_rearm_at, next_idle,
+                             st.backlog.empty() ? never : now + check_interval,
+                             now + std::chrono::seconds(60)});
+    // Rounded up, so that the wait does not end just short of the deadline.
+    auto timeout = std::chrono::duration_cast<std::chrono::milliseconds>(
+        until - now + std::chrono::microseconds(999));
+    poller.wait(static_cast<int>((std::max)(timeout.count(),
+                                            std::chrono::milliseconds::rep(0))),
+                ready);
+    if (svr_sock_ != listen_sock) { break; }
+    now = Clock::now();
+
+    {
+      std::lock_guard<std::mutex> guard(st.mutex);
+      returned.swap(st.returned);
+    }
+    for (auto &conn : returned) {
+      park(std::move(conn), now);
+    }
+    returned.clear();
+
+    // Connections that found the queue full go first, in their order.
+    while (!st.backlog.empty() && dispatch(st.backlog.front())) {
+      st.backlog.pop_front();
+    }
+
+    for (auto token : ready) {
+      if (token == listen_token) {
+        listen_rearm_at = now;
+        // A batch per round, so that a burst of new connections does not
+        // hold up the ones that are ready.
+        for (auto i = 0; i < 64; i++) {
+          auto sock = detail::accept_socket(listen_sock);
+          if (sock == INVALID_SOCKET) {
+            if (detail::is_would_block_error()) { break; }
+            if (detail::is_accept_resource_error()) {
+              // Out of descriptors: let the deadlines free some first.
+              listen_rearm_at = now + check_interval;
+              break;
+            }
+            if (detail::is_accept_transient_error()) { continue; }
+            fatal = true;
+            break;
+          }
+          // Some platforms make it non-blocking like the listening socket.
+          detail::set_nonblocking(sock, false);
+          if (!admit_accepted_socket(sock)) { continue; }
+          park(new_keep_alive_connection(sock), now);
+          if (idle.count() > 0) { next_idle = now + idle; }
+        }
+        continue;
+      }
+
+      submit(st.unpark(token));
+    }
+    if (fatal) { break; }
+
+    st.expire(now);
+    if (now >= next_idle) {
+      task_queue.on_idle();
+      next_idle = now + idle;
+    }
+  }
+
+  // A worker still serving a request closes its connection itself.
+  st.close_all();
+  poller.disarm(listen_sock);
+
+  // See ParkingState::listen_sock.
+  if (st.listen_sock.exchange(INVALID_SOCKET) == INVALID_SOCKET) {
+    // stop() handed it over.
+    detail::shutdown_socket(listen_sock);
+    detail::close_socket(listen_sock);
+    return true;
+  }
+  return !(fatal && abandon_listen_socket());
+}
+
+std::shared_ptr<Server::KeepAliveConnection>
+Server::new_keep_alive_connection(socket_t sock) {
+  return std::make_shared<PlainConnection>(sock, *this);
+}
+
+void
+Server::resume_connection(std::shared_ptr<KeepAliveConnection> conn) {
+  auto &st = *parking_;
+  auto &c = *conn;
+  auto ret = c.resume();
+  if (c.turn.park) {
+    c.release_buffers(); // it may stay idle for long
+    if (st.give_back(conn)) { return; }
+  }
+  c.close_served(!c.turn.websocket_upgraded && ret);
+}
+
 void Server::output_log(const Request &req, const Response &res) const {
   if (logger_) {
     std::lock_guard<std::mutex> guard(logger_mutex_);
@@ -11609,14 +12410,13 @@ bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
   auto location = res.get_header_value("location");
   if (location.empty()) { return false; }

+  auto next_url = detail::resolve_relative_location(location, req.path);
+
   detail::UrlComponents uc;
-  if (!detail::parse_url(detail::resolve_relative_location(location, req.path),
-                         uc)) {
-    return false;
-  }
+  if (!detail::parse_url(next_url, uc)) { return false; }

-  // Only follow http/https redirects
-  if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
+  // Follow only http/https URLs and references starting with '/'
+  if (next_url[0] != '/' && uc.scheme != "http" && uc.scheme != "https") {
     return false;
   }

@@ -14227,7 +15027,73 @@ bool SSLServer::is_valid() const {
   return ctx_ != nullptr && Server::is_valid();
 }

-bool SSLServer::process_and_close_socket(socket_t sock) {
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+namespace detail {
+
+// Before these, SSL_free_buffers() could free a buffer that a record whose
+// body has not arrived yet still uses (CVE-2024-4741). `version` is
+// OpenSSL_version_num().
+bool ssl_free_buffers_is_safe(unsigned long version) {
+  if (version >= 0x30400000UL) { return true; }
+  if (version >= 0x30300000UL) { return version >= 0x30300010UL; } // 3.3.1
+  if (version >= 0x30200000UL) { return version >= 0x30200020UL; } // 3.2.2
+  if (version >= 0x30100000UL) { return version >= 0x30100060UL; } // 3.1.6
+  return version >= 0x300000e0UL;                                  // 3.0.14
+}
+
+} // namespace detail
+#endif
+
+// A connection that keep-alive parking keeps for SSLServer. The worker that
+// first resumes it runs the handshake, so one that has not sent its
+// ClientHello yet waits in the event loop like an idle connection.
+struct SSLServer::TlsConnection final : Server::KeepAliveConnection {
+  TlsConnection(socket_t s, SSLServer &server)
+      : KeepAliveConnection(s, server), ssl_svr(server) {}
+  ~TlsConnection() override { tls::free_session(session); }
+
+  bool open() override {
+    // A handshake would hold up the stop() that is under way.
+    if (ssl_svr.is_stopping()) { return false; }
+    session = ssl_svr.start_session(sock);
+    if (!session) { return false; }
+    // The handshake has read what the event loop saw, so a client that sends
+    // nothing after it is parked instead of being waited for.
+    turn.woken = false;
+    return true;
+  }
+
+  // The session, not the stream, holds what a pipelined request has left.
+  bool serve() override {
+    detail::SSLSocketStream strm(
+        sock, session, ssl_svr.read_timeout_sec_, ssl_svr.read_timeout_usec_,
+        ssl_svr.write_timeout_sec_, ssl_svr.write_timeout_usec_);
+    return serve_on(strm, [this](Request &req) { req.ssl = session; });
+  }
+
+  void release_buffers() override {
+#if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) &&   \
+    !defined(LIBRESSL_VERSION_NUMBER)
+    // The record buffers are most of an idle session's memory, and the next
+    // read makes new ones. The library that runs decides whether that is safe.
+    static const auto safe =
+        detail::ssl_free_buffers_is_safe(OpenSSL_version_num());
+    if (safe) { SSL_free_buffers(static_cast<SSL *>(session)); }
+#endif
+  }
+
+  void shut_down(bool graceful) override { tls::shutdown(session, graceful); }
+
+  SSLServer &ssl_svr;
+  tls::session_t session = nullptr;
+};
+
+std::shared_ptr<Server::KeepAliveConnection>
+SSLServer::new_keep_alive_connection(socket_t sock) {
+  return std::make_shared<TlsConnection>(sock, *this);
+}
+
+tls::session_t SSLServer::start_session(socket_t sock) {
   using namespace tls;

   session_t session = nullptr;
@@ -14240,36 +15106,25 @@ bool SSLServer::process_and_close_socket(socket_t sock) {

   if (!session) {
     last_ssl_error_ = static_cast<int>(get_error());
-    detail::shutdown_socket(sock);
-    detail::close_socket(sock);
-    return false;
+    return nullptr;
   }

-  // Use scope_exit to ensure cleanup on all paths (including exceptions)
-  bool handshake_done = false;
-  bool ret = false;
-  bool websocket_upgraded = false;
+  // Frees the session on all paths but success (including exceptions)
+  auto accepted = false;
   auto cleanup = detail::scope_exit([&] {
-    if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
-    free_session(session);
-    if (handshake_done) {
-      detail::drain_and_close_socket(sock);
-    } else {
-      detail::shutdown_socket(sock);
-      detail::close_socket(sock);
-    }
+    if (!accepted) { free_session(session); }
   });

   // Perform TLS accept handshake with timeout
   TlsError tls_err;
-  auto accepted = false;
   {
     auto handshake_left = detail::scope_exit([&] {
       std::lock_guard<std::mutex> guard(ctx_mutex_);
       if (--handshakes_in_progress_ == 0) { ctx_cv_.notify_all(); }
     });
-    accepted = accept_nonblocking(session, sock, read_timeout_sec_,
-                                  read_timeout_usec_, &tls_err);
+    accepted =
+        accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
+                           &tls_err, [this]() { return is_stopping(); });
   }
   if (!accepted) {
 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
@@ -14284,10 +15139,27 @@ bool SSLServer::process_and_close_socket(socket_t sock) {
 #else
     last_ssl_error_ = static_cast<int>(get_error());
 #endif
+    return nullptr;
+  }
+  return session;
+}
+
+bool SSLServer::process_and_close_socket(socket_t sock) {
+  auto session = start_session(sock);
+  if (!session) {
+    detail::shutdown_socket(sock);
+    detail::close_socket(sock);
     return false;
   }

-  handshake_done = true;
+  // Use scope_exit to ensure cleanup on all paths (including exceptions)
+  bool ret = false;
+  bool websocket_upgraded = false;
+  auto cleanup = detail::scope_exit([&] {
+    tls::shutdown(session, !websocket_upgraded && ret);
+    tls::free_session(session);
+    detail::drain_and_close_socket(sock);
+  });

   std::string remote_addr;
   int remote_port = 0;
@@ -14681,13 +15553,9 @@ bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
   options.interrupted = stop_interrupt();
   options.ctx_mutex = &ctx_mutex_;
 #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
-  // Skip Schannel when a custom CA cert is specified, as the Windows
-  // certificate store would not know about user-provided CA certificates.
-  // Also skip when system CA trust is explicitly disabled.
-  options.windows_cert_verification =
-      enable_windows_cert_verification_ &&
-      system_ca_mode_ != SystemCAMode::Disabled && ca_cert_file_path_.empty() &&
-      ca_cert_dir_path_.empty() && !custom_ca_loaded_;
+  options.windows_cert_verification = detail::use_windows_cert_verification(
+      enable_windows_cert_verification_, ca_cert_file_path_, ca_cert_dir_path_,
+      custom_ca_loaded_, system_ca_mode_);
   // Only a verifier set through set_server_certificate_verifier() is seen
   // here, not one installed with tls::set_verify_callback() directly.
   options.server_certificate_verifier_set =
@@ -15671,7 +16539,8 @@ bool connect_nonblocking(session_t session, socket_t sock,

 bool accept_nonblocking(session_t session, socket_t sock,
                                time_t timeout_sec, time_t timeout_usec,
-                               TlsError *err) {
+                               TlsError *err,
+                               const std::function<bool()> &interrupted) {
   if (!session) {
     if (err) { err->code = ErrorCode::Fatal; }
     return false;
@@ -15696,10 +16565,14 @@ bool accept_nonblocking(session_t session, socket_t sock,
     auto ssl_err = SSL_get_error(ssl, res);
     switch (ssl_err) {
     case SSL_ERROR_WANT_READ:
-      if (detail::select_until(sock, POLLIN, deadline) > 0) { continue; }
+      if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
+        continue;
+      }
       break;
     case SSL_ERROR_WANT_WRITE:
-      if (detail::select_until(sock, POLLOUT, deadline) > 0) { continue; }
+      if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
+        continue;
+      }
       break;
     default: break;
     }
@@ -17026,13 +17899,14 @@ bool connect_nonblocking(session_t session, socket_t sock,

 bool accept_nonblocking(session_t session, socket_t sock,
                                time_t timeout_sec, time_t timeout_usec,
-                               TlsError *err) {
+                               TlsError *err,
+                               const std::function<bool()> &interrupted) {
   // A failed handshake leaves its SNI behind, so start without it
   impl::mbedpending_sni().clear();

   // Same implementation as connect for Mbed TLS
-  bool result =
-      connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
+  bool result = connect_nonblocking(session, sock, timeout_sec, timeout_usec,
+                                    err, interrupted);

   // After successful handshake, capture SNI from thread-local storage
   if (result && session) {
@@ -18207,7 +19081,8 @@ bool connect_nonblocking(session_t session, socket_t sock,

 bool accept_nonblocking(session_t session, socket_t sock,
                                time_t timeout_sec, time_t timeout_usec,
-                               TlsError *err) {
+                               TlsError *err,
+                               const std::function<bool()> &interrupted) {
   if (!session) {
     if (err) { err->code = ErrorCode::Fatal; }
     return false;
@@ -18225,9 +19100,13 @@ bool accept_nonblocking(session_t session, socket_t sock,
   while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
     int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
     if (ssl_error == SSL_ERROR_WANT_READ) {
-      if (detail::select_until(sock, POLLIN, deadline) > 0) { continue; }
+      if (detail::select_until(sock, POLLIN, deadline, interrupted) > 0) {
+        continue;
+      }
     } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
-      if (detail::select_until(sock, POLLOUT, deadline) > 0) { continue; }
+      if (detail::select_until(sock, POLLOUT, deadline, interrupted) > 0) {
+        continue;
+      }
     }

     // Error or timeout
@@ -18815,40 +19694,55 @@ bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
                                   bool fin) {
   std::lock_guard<std::mutex> lock(write_mutex_);
   if (closed_) { return false; }
-  return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
+  // A failed write may have sent part of the frame, whose header announces the
+  // whole length, so the peer would read the next frames as the rest of it.
+  if (!detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_)) {
+    closed_ = true;
+    return false;
+  }
+  return true;
+}
+
+// Sends this side's one Close frame and marks the connection closed. Returns
+// false when it already was.
+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;
 }

 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 {
     switch (op) {
-    case Opcode::Ping: {
-      std::lock_guard<std::mutex> lock(write_mutex_);
-      detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
-                                    payload.size(), true, !is_server_);
-      return true;
-    }
+    case Opcode::Ping:
+      return send_frame(Opcode::Pong, payload.data(), payload.size());
     case Opcode::Pong: {
       std::lock_guard<std::mutex> lock(ping_mutex_);
       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;
     }
   };

@@ -18860,93 +19754,75 @@ ReadResult WebSocket::read(std::string &msg) {
     close(CloseStatus::GoingAway, "server stopping");
     return Fail;
   };
+  // close() ends the read, even while the peer keeps sending fragments
   while (!closed_) {
     Opcode opcode;
     std::string payload;
     bool fin;

-    impl::FrameRead r =
-        impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
-                                   CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH);
+    // 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 =
+        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 landed on a frame boundary of an open connection: it is
-    // untouched and still usable, so hand control back without closing it.
-    // That is only useful to a caller who asked for the timeout; the
-    // compile-time default is a backstop against a peer gone quiet, and
-    // elapsing it closes the connection so a plain `while (ws.read(msg))` loop
-    // ends. A wait that a pong timeout cut short finds the connection closed.
+    // A timeout leaves what was read of the frame and of the message for the
+    // next read(), so the connection is still usable wherever it landed: hand
+    // control back without closing it. That is only useful to a caller who
+    // asked for the timeout; the compile-time default is a backstop against a
+    // peer gone quiet, and elapsing it closes the connection so a plain
+    // `while (ws.read(msg))` loop ends. A wait that a pong timeout cut short
+    // finds the connection closed.
     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;
     }

-    switch (opcode) {
-    case Opcode::Text:
-    case Opcode::Binary: {
-      auto result = opcode == Opcode::Text ? Text : Binary;
-      msg = std::move(payload);
-
-      // Handle fragmentation
-      if (!fin) {
-        while (true) {
-          // A close() from another thread ends the message being assembled,
-          // as it ends the loop over frames above: a peer that keeps sending
-          // fragments never lets a read reach a wait
-          if (closed_) { return Fail; }
-          Opcode cont_opcode;
-          std::string cont_payload;
-          bool cont_fin;
-          // Only what is left of the limit, but room for a control frame,
-          // which may come between the fragments.
-          auto max_len =
-              CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH == 0
-                  ? size_t(0)
-                  : (std::max)(size_t(125),
-                               CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH -
-                                   msg.size());
-          // A timeout is not reportable here: half of a fragmented message is
-          // already in `msg` and read() has no way to resume it, so it is a
-          // failure like any other. Timeouts are only ever seen on a message
-          // boundary.
-          if (impl::read_websocket_frame(strm_, cont_opcode, cont_payload,
-                                         cont_fin, is_server_,
-                                         max_len) != impl::FrameRead::Ok) {
-            if (server_stopping()) { return going_away(); }
-            closed_ = true;
-            return Fail;
-          }
-          // RFC 6455 5.4: the fragments are continuation frames, with only
-          // control frames between them.
-          if (cont_opcode != Opcode::Continuation) {
-            if (handle_control(cont_opcode, cont_payload)) { continue; }
-            return Fail;
-          }
-          msg += cont_payload;
-          if (CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH > 0 &&
-              msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
-            closed_ = true;
-            return Fail;
-          }
-          if (cont_fin) { break; }
-        }
-      }
-      // RFC 6455 Section 5.6: text frames must contain valid UTF-8
-      if (result == Text && !impl::is_valid_utf8(msg)) {
-        // close() takes the read lock to wait for the peer's Close reply, so
-        // it must not run while this thread still holds it.
-        read_lock.unlock();
-        close(CloseStatus::InvalidPayload, "invalid UTF-8");
-        return Fail;
-      }
-      return result;
-    }
-    default:
+    auto continues = opcode == Opcode::Continuation;
+    if (opcode != Opcode::Text && opcode != Opcode::Binary && !continues) {
       if (handle_control(opcode, payload)) { continue; }
       return Fail;
     }
+    // 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)) {
+      return fail_with(CloseStatus::ProtocolError);
+    }
+    if (continues) {
+      message_ += payload;
+    } else {
+      message_ = std::move(payload);
+      message_kind_ = opcode == Opcode::Text ? Text : Binary;
+    }
+    if (max_message_length_ > 0 && message_.size() > max_message_length_) {
+      return fail_with(CloseStatus::MessageTooBig);
+    }
+    if (!fin) { continue; }
+
+    auto result = message_kind_;
+    msg = std::move(message_);
+    message_.clear();
+    message_kind_ = Fail;
+    // RFC 6455 Section 5.6: text frames must contain valid UTF-8
+    if (result == Text && !impl::is_valid_utf8(msg)) {
+      // close() takes the read lock to wait for the peer's Close reply, so
+      // it must not run while this thread still holds it.
+      read_lock.unlock();
+      close(CloseStatus::InvalidPayload, "invalid UTF-8");
+      return Fail;
+    }
+    return result;
   }
   return Fail;
 }
@@ -18960,27 +19836,7 @@ bool WebSocket::send(const char *data, size_t len) {
 }

 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.
@@ -18999,13 +19855,17 @@ void WebSocket::close(CloseStatus status, const std::string &reason) {
   auto deadline =
       detail::deadline_after(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);

+  // From where the last read() left the stream, inside a frame as it may be
   Opcode op;
   std::string resp;
   bool fin;
   while (std::chrono::steady_clock::now() < deadline &&
-         impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125) ==
+         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;
+    }
   }
 }

@@ -19046,11 +19906,7 @@ void WebSocket::start_heartbeat() {
         return;
       }
       lock.unlock();
-      if (!send_frame(Opcode::Ping, nullptr, 0)) {
-        lock.lock();
-        closed_ = true;
-        break;
-      }
+      if (!send_frame(Opcode::Ping, nullptr, 0)) { return; }
       lock.lock();
       unacked_pings_++;
     }
@@ -19061,6 +19917,25 @@ const Request &WebSocket::request() const { return req_; }

 bool WebSocket::is_open() const { return !closed_; }

+CloseStatus WebSocket::close_status() const { return close_status_; }
+
+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.
+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;
+  }
+}
+
 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
@@ -19207,6 +20082,12 @@ bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm,
     detail::ClientTlsSessionOptions options;
     options.server_hostname_verification = server_hostname_verification_;
     options.session_verifier = session_verifier_;
+#ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
+    options.windows_cert_verification = detail::use_windows_cert_verification(
+        enable_windows_cert_verification_, ca_cert_file_path_,
+        ca_cert_dir_path_, custom_ca_loaded_, system_ca_mode_);
+    options.server_certificate_verifier_set = server_certificate_verifier_set_;
+#endif

     auto timeout = handshake_timeout();
     detail::ClientTlsSessionError tls_error;
@@ -19297,9 +20178,12 @@ 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_;
@@ -19328,6 +20212,14 @@ void WebSocketClient::close(CloseStatus status,

 bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }

+CloseStatus WebSocketClient::close_status() const {
+  return ws_ ? ws_->close_status() : CloseStatus::Abnormal;
+}
+
+std::string WebSocketClient::close_reason() const {
+  return ws_ ? ws_->close_reason() : std::string();
+}
+
 const std::string &WebSocketClient::subprotocol() const {
   return subprotocol_;
 }
@@ -19354,6 +20246,10 @@ void WebSocketClient::set_websocket_max_missed_pongs(int count) {
   websocket_max_missed_pongs_ = count;
 }

+void WebSocketClient::set_websocket_max_message_length(size_t length) {
+  websocket_max_message_length_ = length;
+}
+
 void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }

 void WebSocketClient::set_address_family(int family) {
@@ -19516,6 +20412,9 @@ WebSocketClient::set_ca_cert_path(const std::string &ca_cert_file_path,

 void
 WebSocketClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
+#ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
+  server_certificate_verifier_set_ = static_cast<bool>(verifier);
+#endif
   if (tls_ctx_) { tls::set_verify_callback(tls_ctx_, std::move(verifier)); }
 }

@@ -19555,6 +20454,13 @@ void WebSocketClient::enable_system_ca(bool enabled) {
   system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
 }

+#ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
+void
+WebSocketClient::enable_windows_certificate_verification(bool enabled) {
+  enable_windows_cert_verification_ = enabled;
+}
+#endif
+
 void
 WebSocketClient::set_proxy_digest_auth(const std::string &username,
                                        const std::string &password) {
diff --git a/vendor/cpp-httplib/httplib.h b/vendor/cpp-httplib/httplib.h
index fc9d004be..6e0202731 100644
--- a/vendor/cpp-httplib/httplib.h
+++ b/vendor/cpp-httplib/httplib.h
@@ -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,22 +5228,14 @@ 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 };
+} // namespace ws

-FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
-                               std::string &payload, bool &fin,
-                               bool expect_masked, size_t max_len);
+namespace detail {

-} // namespace impl
+bool write_websocket_frame(Stream &strm, ws::Opcode opcode, const char *data,
+                           size_t len, bool fin, bool mask);

-} // namespace ws
+} // namespace detail


 } // namespace httplib