Files
Library/src/Net/HttpServer.cpp
T

2931 lines
84 KiB
C++

#include <Void/Net/HttpServer.hpp>
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <poll.h>
#include <sys/eventfd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <cctype>
#include <cerrno>
#include <charconv>
#include <chrono>
#include <condition_variable>
#include <cstring>
#include <format>
#include <limits>
#include <map>
#include <mutex>
#include <optional>
#include <set>
#include <shared_mutex>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
namespace Void::Net
{
namespace
{
std::atomic<std::uint64_t> g_temp_upload_seq{0};
[[nodiscard]] bool
equal_ascii_ci(std::string_view a, std::string_view b) noexcept
{
return a.size() == b.size() &&
std::ranges::equal(a, b, [](char x, char y) {
return std::tolower(static_cast<unsigned char>(x)) ==
std::tolower(static_cast<unsigned char>(y));
});
}
[[nodiscard]] bool
contains_ascii_ci(std::string_view haystack,
std::string_view needle) noexcept
{
if (needle.empty() || needle.size() > haystack.size()) {
return false;
}
for (std::size_t i = 0; i + needle.size() <= haystack.size(); ++i) {
if (equal_ascii_ci(haystack.substr(i, needle.size()), needle)) {
return true;
}
}
return false;
}
[[nodiscard]] std::string_view trim_ows(std::string_view s) noexcept
{
while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) {
s.remove_prefix(1);
}
while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) {
s.remove_suffix(1);
}
return s;
}
[[nodiscard]] std::optional<Method>
parse_method(std::string_view token) noexcept
{
if (token == "GET") return Method::Get;
if (token == "HEAD") return Method::Head;
if (token == "POST") return Method::Post;
if (token == "PUT") return Method::Put;
if (token == "DELETE") return Method::Delete;
if (token == "PATCH") return Method::Patch;
if (token == "OPTIONS") return Method::Options;
return std::nullopt;
}
[[nodiscard]] std::string_view method_string(Method m) noexcept
{
switch (m) {
case Method::Get: return "GET";
case Method::Head: return "HEAD";
case Method::Post: return "POST";
case Method::Put: return "PUT";
case Method::Delete: return "DELETE";
case Method::Patch: return "PATCH";
case Method::Options: return "OPTIONS";
}
return "GET";
}
[[nodiscard]] std::string_view reason_phrase(std::uint16_t code) noexcept
{
switch (code) {
case 100: return "Continue";
case 200: return "OK";
case 201: return "Created";
case 204: return "No Content";
case 301: return "Moved Permanently";
case 302: return "Found";
case 304: return "Not Modified";
case 400: return "Bad Request";
case 401: return "Unauthorized";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 408: return "Request Timeout";
case 413: return "Payload Too Large";
case 415: return "Unsupported Media Type";
case 431: return "Request Header Fields Too Large";
case 500: return "Internal Server Error";
case 501: return "Not Implemented";
case 503: return "Service Unavailable";
default: return "OK";
}
}
[[nodiscard]] bool has_crlf_or_nul(std::string_view s) noexcept
{
for (const unsigned char ch : s) {
if (ch == '\r' || ch == '\n' || ch == '\0') {
return true;
}
}
return false;
}
[[nodiscard]] bool is_valid_token(std::string_view s) noexcept
{
if (s.empty()) {
return false;
}
for (const unsigned char ch : s) {
if (ch <= 0x20 || ch >= 0x7F || ch == ':' || ch == '(' ||
ch == ')' || ch == '<' || ch == '>' || ch == '@' ||
ch == ',' || ch == ';' || ch == '\\' || ch == '"' ||
ch == '/' || ch == '[' || ch == ']' || ch == '?' ||
ch == '=' || ch == '{' || ch == '}') {
return false;
}
}
return true;
}
[[nodiscard]] bool parse_u64_decimal(std::string_view s,
std::uint64_t& out) noexcept
{
if (s.empty()) {
return false;
}
for (const unsigned char ch : s) {
if (ch < '0' || ch > '9') {
return false;
}
}
const auto res = std::from_chars(s.data(), s.data() + s.size(), out);
return res.ec == std::errc{} && res.ptr == s.data() + s.size();
}
[[nodiscard]] std::vector<std::string> split_path(std::string_view path)
{
std::vector<std::string> segments;
std::size_t begin = path.starts_with('/') ? 1 : 0;
while (begin < path.size()) {
const auto end = path.find('/', begin);
const auto segment = path.substr(begin, end - begin);
if (!segment.empty()) {
segments.emplace_back(segment);
}
if (end == std::string_view::npos) {
break;
}
begin = end + 1;
}
return segments;
}
[[nodiscard]] bool valid_param_name(std::string_view name) noexcept
{
return !name.empty() && std::ranges::all_of(name, [](char v) {
const auto c = static_cast<unsigned char>(v);
return std::isalnum(c) != 0 || v == '_';
});
}
[[nodiscard]] Void::Result::Result<std::vector<std::string>>
compile_route_pattern(std::string_view pattern)
{
if (pattern.empty() || !pattern.starts_with('/') ||
pattern.find_first_of("?#") != std::string_view::npos) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer: route patterns must be absolute paths")};
}
auto segments = split_path(pattern);
std::set<std::string, std::less<>> names;
for (std::size_t i = 0; i < segments.size(); ++i) {
const auto& seg = segments[i];
if (!seg.starts_with(':') && !seg.starts_with('*')) {
continue;
}
const auto name = std::string_view{seg}.substr(1);
if (!valid_param_name(name) || !names.emplace(name).second ||
(seg.starts_with('*') && i + 1 != segments.size())) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer: invalid streaming route pattern")};
}
}
return segments;
}
[[nodiscard]] std::optional<RouteParameters>
match_segments(const std::vector<std::string>& pattern,
const std::vector<std::string>& path)
{
RouteParameters params;
std::size_t pi = 0;
for (const auto& seg : pattern) {
if (seg.starts_with('*')) {
std::string val;
for (; pi < path.size(); ++pi) {
if (!val.empty()) {
val.push_back('/');
}
val += path[pi];
}
params.emplace(seg.substr(1), std::move(val));
return params;
}
if (pi >= path.size()) {
return std::nullopt;
}
if (seg.starts_with(':')) {
params.emplace(seg.substr(1), path[pi]);
} else if (seg != path[pi]) {
return std::nullopt;
}
++pi;
}
if (pi != path.size()) {
return std::nullopt;
}
return params;
}
[[nodiscard]] int segment_rank(std::string_view s) noexcept
{
if (s.starts_with('*')) return 0;
if (s.starts_with(':')) return 1;
return 2;
}
[[nodiscard]] bool
more_specific_route(const std::vector<std::string>& cand,
const std::vector<std::string>& cur) noexcept
{
const std::size_t n = std::min(cand.size(), cur.size());
for (std::size_t i = 0; i < n; ++i) {
const int cr = segment_rank(cand[i]);
const int br = segment_rank(cur[i]);
if (cr != br) {
return cr > br;
}
}
return cand.size() > cur.size();
}
[[nodiscard]] bool
same_route_shape(const std::vector<std::string>& lhs,
const std::vector<std::string>& rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
for (std::size_t i = 0; i < lhs.size(); ++i) {
const int lr = segment_rank(lhs[i]);
const int rr = segment_rank(rhs[i]);
if (lr != rr || (lr == 2 && lhs[i] != rhs[i])) {
return false;
}
}
return true;
}
class OwnedFd
{
public:
explicit OwnedFd(int fd = -1) noexcept : m_fd(fd) {}
~OwnedFd() noexcept { reset(); }
OwnedFd(OwnedFd&& other) noexcept
: m_fd(std::exchange(other.m_fd, -1))
{
}
OwnedFd& operator=(OwnedFd&& other) noexcept
{
if (this != &other) {
reset(std::exchange(other.m_fd, -1));
}
return *this;
}
OwnedFd(const OwnedFd&) = delete;
OwnedFd& operator=(const OwnedFd&) = delete;
[[nodiscard]] int get() const noexcept { return m_fd; }
[[nodiscard]] explicit operator bool() const noexcept
{
return m_fd >= 0;
}
[[nodiscard]] int release() noexcept
{
return std::exchange(m_fd, -1);
}
void reset(int fd = -1) noexcept
{
if (m_fd >= 0) {
(void)::close(m_fd);
}
m_fd = fd;
}
private:
int m_fd{-1};
};
[[nodiscard]] Void::Result::Result<std::size_t>
recv_slice(int fd, std::span<char> dst,
const std::atomic<bool>& stopping,
std::chrono::milliseconds timeout)
{
const auto deadline = std::chrono::steady_clock::now() + timeout;
for (;;) {
if (stopping.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::HttpServer: server shutting down")};
}
const auto now = std::chrono::steady_clock::now();
if (timeout > std::chrono::milliseconds::zero() &&
now >= deadline) {
return std::unexpected{make_net_error(
NetErrorCode::timeout, "Net::HttpServer: read timeout")};
}
int wait_ms = 50;
if (timeout > std::chrono::milliseconds::zero()) {
const auto rem = std::chrono::duration_cast<
std::chrono::milliseconds>(deadline - now)
.count();
wait_ms = static_cast<int>(std::clamp<long long>(rem, 1, 50));
}
struct pollfd pfd{};
pfd.fd = fd;
pfd.events = POLLIN;
const int pr = ::poll(&pfd, 1, wait_ms);
if (pr < 0) {
if (errno == EINTR) {
continue;
}
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::HttpServer: poll failed: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()})};
}
if (pr == 0) {
continue;
}
const ssize_t n = ::recv(fd, dst.data(), dst.size(), 0);
if (n < 0) {
if (errno == EINTR || errno == EAGAIN ||
errno == EWOULDBLOCK) {
continue;
}
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::HttpServer: recv failed: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()})};
}
return static_cast<std::size_t>(n);
}
}
[[nodiscard]] Void::Result::Result<void>
send_all(int fd, std::span<const std::byte> data,
std::chrono::milliseconds timeout)
{
std::size_t off = 0;
const auto deadline = std::chrono::steady_clock::now() + timeout;
while (off < data.size()) {
const auto now = std::chrono::steady_clock::now();
if (timeout > std::chrono::milliseconds::zero() &&
now >= deadline) {
return std::unexpected{make_net_error(
NetErrorCode::timeout,
"Net::HttpServer: write timeout")};
}
int wait_ms = 100;
if (timeout > std::chrono::milliseconds::zero()) {
const auto rem = std::chrono::duration_cast<
std::chrono::milliseconds>(deadline - now)
.count();
wait_ms =
static_cast<int>(std::clamp<long long>(rem, 1, 100));
}
struct pollfd pfd{};
pfd.fd = fd;
pfd.events = POLLOUT;
const int pr = ::poll(&pfd, 1, wait_ms);
if (pr < 0) {
if (errno == EINTR) {
continue;
}
return std::unexpected{make_net_error(
NetErrorCode::io_error, "Net::HttpServer: send poll failed")};
}
if (pr == 0) {
continue;
}
const ssize_t n = ::send(
fd,
reinterpret_cast<const char*>(data.data()) + off,
data.size() - off, MSG_NOSIGNAL);
if (n < 0) {
if (errno == EINTR || errno == EAGAIN ||
errno == EWOULDBLOCK) {
continue;
}
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::HttpServer: send failed: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()})};
}
if (n == 0) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
"Net::HttpServer: peer closed socket on send")};
}
off += static_cast<std::size_t>(n);
}
return {};
}
[[nodiscard]] Void::Result::Result<void>
send_str(int fd, std::string_view s,
std::chrono::milliseconds timeout)
{
return send_all(fd,
std::as_bytes(std::span{s.data(), s.size()}),
timeout);
}
} // namespace
struct BodyReader::State {
int fd{-1};
const std::atomic<bool>* stopping{nullptr};
std::chrono::milliseconds read_timeout{};
std::uint64_t default_max_bytes{0};
std::string* rx_buf{nullptr};
std::size_t* rx_off{nullptr};
bool chunked{false};
std::optional<std::uint64_t> declared_length{};
std::uint64_t total_read{0};
std::uint64_t remaining_fixed{0};
bool eof{false};
enum class ChunkPhase {
Header,
Data,
AfterDataCrlf,
Trailers,
Done
};
ChunkPhase chunk_phase{ChunkPhase::Header};
std::uint64_t chunk_remaining{0};
void consume_rx(std::size_t n) noexcept
{
*rx_off += n;
if (*rx_off >= rx_buf->size()) {
rx_buf->clear();
*rx_off = 0;
} else if (*rx_off > 64ULL * 1024U) {
rx_buf->erase(0, *rx_off);
*rx_off = 0;
}
}
[[nodiscard]] Void::Result::Result<bool> fill_rx()
{
if (*rx_off < rx_buf->size()) {
return true;
}
rx_buf->clear();
*rx_off = 0;
std::array<char, 16 * 1024> tmp{};
auto n = recv_slice(fd, tmp, *stopping, read_timeout);
if (!n.has_value()) {
return std::unexpected{std::move(n.error())};
}
if (*n == 0) {
return false;
}
rx_buf->append(tmp.data(), *n);
return true;
}
[[nodiscard]] Void::Result::Result<std::string> read_line_crlf(
std::size_t max_len = 8192)
{
for (;;) {
const std::size_t pos = rx_buf->find("\r\n", *rx_off);
if (pos != std::string::npos) {
const std::size_t line_len = pos - *rx_off;
if (line_len > max_len) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"Net::HttpServer: chunk header line too long")};
}
std::string line = rx_buf->substr(*rx_off, line_len);
consume_rx(line_len + 2U);
return line;
}
if (rx_buf->size() - *rx_off > max_len) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"Net::HttpServer: chunk line exceeds limit")};
}
rx_buf->erase(0, *rx_off);
*rx_off = 0;
std::array<char, 4096> tmp{};
auto n = recv_slice(fd, tmp, *stopping, read_timeout);
if (!n.has_value()) {
return std::unexpected{std::move(n.error())};
}
if (*n == 0) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"Net::HttpServer: unexpected EOF in chunked body")};
}
rx_buf->append(tmp.data(), *n);
}
}
};
std::optional<std::uint64_t> BodyReader::content_length() const noexcept
{
return m_state ? m_state->declared_length : std::nullopt;
}
bool BodyReader::is_chunked() const noexcept
{
return m_state != nullptr && m_state->chunked;
}
std::uint64_t BodyReader::bytes_read() const noexcept
{
return m_state ? m_state->total_read : 0;
}
Void::Result::Result<std::size_t>
BodyReader::read_some(std::span<std::byte> dst)
{
if (m_state == nullptr || m_state->eof) {
return std::size_t{0};
}
if (dst.empty()) {
return std::size_t{0};
}
if (!m_state->chunked) {
if (m_state->remaining_fixed == 0) {
m_state->eof = true;
return std::size_t{0};
}
const std::size_t avail =
m_state->rx_buf->size() - *m_state->rx_off;
if (avail > 0) {
const std::size_t take = static_cast<std::size_t>(
std::min<std::uint64_t>(
std::min(dst.size(), avail), m_state->remaining_fixed));
std::memcpy(dst.data(),
m_state->rx_buf->data() + *m_state->rx_off, take);
m_state->consume_rx(take);
m_state->remaining_fixed -= take;
m_state->total_read += take;
if (m_state->remaining_fixed == 0) {
m_state->eof = true;
}
return take;
}
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(dst.size(), m_state->remaining_fixed));
auto r = recv_slice(
m_state->fd,
std::span<char>{reinterpret_cast<char*>(dst.data()), want},
*m_state->stopping, m_state->read_timeout);
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
if (*r == 0) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"Net::HttpServer: unexpected EOF before Content-Length")};
}
m_state->remaining_fixed -= *r;
m_state->total_read += *r;
if (m_state->remaining_fixed == 0) {
m_state->eof = true;
}
return *r;
}
for (;;) {
switch (m_state->chunk_phase) {
case State::ChunkPhase::Header: {
auto line = m_state->read_line_crlf();
if (!line.has_value()) {
return std::unexpected{std::move(line.error())};
}
const std::size_t semi = line->find(';');
std::string_view hex_part =
semi == std::string::npos
? std::string_view{*line}
: std::string_view{*line}.substr(0, semi);
hex_part = trim_ows(hex_part);
if (hex_part.empty()) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"Net::HttpServer: empty chunk size")};
}
std::uint64_t csize = 0;
const auto res = std::from_chars(
hex_part.data(), hex_part.data() + hex_part.size(),
csize, 16);
if (res.ec != std::errc{} ||
res.ptr != hex_part.data() + hex_part.size()) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"Net::HttpServer: invalid chunk size")};
}
m_state->chunk_remaining = csize;
if (csize == 0) {
m_state->chunk_phase = State::ChunkPhase::Trailers;
} else {
m_state->chunk_phase = State::ChunkPhase::Data;
}
break;
}
case State::ChunkPhase::Data: {
const std::size_t avail =
m_state->rx_buf->size() - *m_state->rx_off;
std::size_t got = 0;
if (avail > 0) {
got = static_cast<std::size_t>(std::min<std::uint64_t>(
std::min(dst.size(), avail),
m_state->chunk_remaining));
std::memcpy(dst.data(),
m_state->rx_buf->data() + *m_state->rx_off,
got);
m_state->consume_rx(got);
} else {
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(dst.size(),
m_state->chunk_remaining));
auto r = recv_slice(
m_state->fd,
std::span<char>{
reinterpret_cast<char*>(dst.data()), want},
*m_state->stopping, m_state->read_timeout);
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
if (*r == 0) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"Net::HttpServer: unexpected EOF in chunk data")};
}
got = *r;
}
m_state->chunk_remaining -= got;
m_state->total_read += got;
if (m_state->chunk_remaining == 0) {
m_state->chunk_phase = State::ChunkPhase::AfterDataCrlf;
}
return got;
}
case State::ChunkPhase::AfterDataCrlf: {
auto line = m_state->read_line_crlf(16);
if (!line.has_value()) {
return std::unexpected{std::move(line.error())};
}
if (!line->empty()) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"Net::HttpServer: expected CRLF after chunk")};
}
m_state->chunk_phase = State::ChunkPhase::Header;
break;
}
case State::ChunkPhase::Trailers: {
for (;;) {
auto line = m_state->read_line_crlf();
if (!line.has_value()) {
return std::unexpected{std::move(line.error())};
}
if (line->empty()) {
m_state->chunk_phase = State::ChunkPhase::Done;
m_state->eof = true;
return std::size_t{0};
}
}
}
case State::ChunkPhase::Done:
m_state->eof = true;
return std::size_t{0};
}
}
}
Void::Result::Result<std::uint64_t>
BodyReader::read_to_file(const std::filesystem::path& destination,
std::uint64_t max_bytes)
{
if (m_state == nullptr) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::BodyReader::read_to_file: invalid reader state")};
}
std::uint64_t effective_limit = max_bytes;
if (effective_limit == 0) {
effective_limit = m_state->default_max_bytes;
} else if (m_state->default_max_bytes > 0) {
effective_limit =
std::min(effective_limit, m_state->default_max_bytes);
}
if (effective_limit > 0 && m_state->declared_length.has_value() &&
*m_state->declared_length > effective_limit) {
return std::unexpected{make_net_error(
NetErrorCode::payload_too_large,
"Net::BodyReader::read_to_file: declared body exceeds limit")};
}
std::filesystem::path parent = destination.parent_path();
if (parent.empty()) {
parent = ".";
}
std::error_code ec;
std::filesystem::create_directories(parent, ec);
if (ec) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::BodyReader: create_directories failed: {}",
ec.message()),
ec)};
}
const std::filesystem::path tmp_path =
parent / std::format(".void-upload-{}-{}",
static_cast<long long>(::getpid()),
g_temp_upload_seq.fetch_add(
1, std::memory_order_relaxed));
OwnedFd out_fd{::open(tmp_path.c_str(),
O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC |
O_NOFOLLOW,
0644)};
if (!out_fd) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::BodyReader: cannot create temp file: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()})};
}
auto fail_cleanup = [&](Void::Result::Error err)
-> Void::Result::Result<std::uint64_t> {
out_fd.reset();
std::error_code rm_ec;
std::filesystem::remove(tmp_path, rm_ec);
return std::unexpected{std::move(err)};
};
std::array<std::byte, 64 * 1024> buf{};
std::uint64_t written_total = 0;
for (;;) {
auto n = read_some(buf);
if (!n.has_value()) {
return fail_cleanup(std::move(n.error()));
}
if (*n == 0) {
break;
}
const auto amt = static_cast<std::uint64_t>(*n);
if (effective_limit > 0 && amt > effective_limit - written_total) {
return fail_cleanup(make_net_error(
NetErrorCode::payload_too_large,
"Net::BodyReader::read_to_file: streaming body exceeds "
"limit"));
}
std::size_t off = 0;
while (off < *n) {
const ssize_t w = ::write(
out_fd.get(),
reinterpret_cast<const char*>(buf.data()) + off,
*n - off);
if (w < 0 && errno == EINTR) {
continue;
}
if (w <= 0) {
return fail_cleanup(make_net_error(
NetErrorCode::io_error,
std::format("Net::BodyReader: write temp file failed: "
"{}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()}));
}
off += static_cast<std::size_t>(w);
}
written_total += amt;
}
if (::fsync(out_fd.get()) != 0) {
return fail_cleanup(make_net_error(
NetErrorCode::io_error,
std::format("Net::BodyReader: fsync failed: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()}));
}
const int raw = out_fd.release();
if (::close(raw) != 0) {
return fail_cleanup(make_net_error(
NetErrorCode::io_error,
std::format("Net::BodyReader: close failed: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()}));
}
std::filesystem::rename(tmp_path, destination, ec);
if (ec) {
std::error_code rm_ec;
std::filesystem::remove(tmp_path, rm_ec);
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::BodyReader: rename failed: {}", ec.message()),
ec)};
}
return written_total;
}
struct ResponseWriter::State {
int fd{-1};
const std::atomic<bool>* stopping{nullptr};
std::atomic<bool> cancel_requested{false};
std::atomic<bool> head_attempted{false};
std::atomic<bool> begun{false};
std::atomic<bool> finished{false};
std::atomic<bool> invalid{false};
std::atomic<bool> chunked{false};
std::atomic<bool> bodyless{false};
std::atomic<bool> fixed_length{false};
std::atomic<bool> close_delimited{false};
std::atomic<bool> has_content_length{false};
std::atomic<bool> keep_alive{true};
std::atomic<std::uint64_t> content_length{0};
std::atomic<std::uint64_t> accepted{0};
std::atomic<std::uint64_t> sent{0};
std::atomic<std::size_t> pending_bytes{0};
std::atomic<std::chrono::milliseconds::rep> write_timeout_ms{
std::chrono::seconds{30}.count()};
std::mutex io_mutex{};
std::string pending{};
std::size_t max_pending{64ULL * 1024};
bool head_request{false};
bool http10{false};
std::stop_source stop_source{};
[[nodiscard]] bool stopped() const noexcept
{
return cancel_requested.load(std::memory_order_acquire) ||
(stopping != nullptr &&
stopping->load(std::memory_order_acquire));
}
void request_stop() noexcept
{
(void)stop_source.request_stop();
}
};
namespace
{
[[nodiscard]] Void::Result::Result<void>
writer_send_all(ResponseWriter::State& state,
std::span<const std::byte> data)
{
const auto timeout = std::chrono::milliseconds{
state.write_timeout_ms.load(std::memory_order_acquire)};
const auto deadline = std::chrono::steady_clock::now() + timeout;
std::size_t off = 0;
while (off < data.size()) {
if (state.stopped()) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ResponseWriter: exchange cancelled")};
}
const auto now = std::chrono::steady_clock::now();
if (timeout > std::chrono::milliseconds::zero() &&
now >= deadline) {
return std::unexpected{make_net_error(
NetErrorCode::timeout,
"Net::ResponseWriter: write timeout")};
}
int wait_ms = 100;
if (timeout > std::chrono::milliseconds::zero()) {
const auto rem = std::chrono::duration_cast<
std::chrono::milliseconds>(deadline - now)
.count();
wait_ms = static_cast<int>(std::clamp<long long>(rem, 1, 100));
}
struct pollfd pfd{};
pfd.fd = state.fd;
pfd.events = POLLOUT;
const int pr = ::poll(&pfd, 1, wait_ms);
if (pr < 0) {
if (errno == EINTR) {
continue;
}
return std::unexpected{make_net_error(
NetErrorCode::io_error,
"Net::ResponseWriter: poll failed")};
}
if (pr == 0) {
continue;
}
const ssize_t n = ::send(
state.fd,
reinterpret_cast<const char*>(data.data()) + off,
data.size() - off, MSG_NOSIGNAL);
if (n < 0) {
if (errno == EINTR || errno == EAGAIN ||
errno == EWOULDBLOCK) {
continue;
}
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::ResponseWriter: send failed: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()})};
}
if (n == 0) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::io_error,
"Net::ResponseWriter: peer closed connection")};
}
off += static_cast<std::size_t>(n);
}
return {};
}
[[nodiscard]] Void::Result::Result<void>
writer_flush(ResponseWriter::State& state)
{
if (state.pending.empty()) {
return {};
}
auto res = writer_send_all(
state, std::as_bytes(std::span{state.pending.data(),
state.pending.size()}));
if (!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
state.pending.clear();
state.pending_bytes.store(0, std::memory_order_release);
state.sent.store(state.accepted.load(std::memory_order_acquire),
std::memory_order_release);
return {};
}
[[nodiscard]] Void::Result::Result<void>
writer_require_active(const std::shared_ptr<ResponseWriter::State>& s)
{
if (!s || s->invalid.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: exchange is no longer active")};
}
return {};
}
} // namespace
bool ResponseWriter::valid() const noexcept
{
return m_state != nullptr &&
!m_state->invalid.load(std::memory_order_acquire);
}
bool ResponseWriter::begun() const noexcept
{
return m_state != nullptr &&
m_state->begun.load(std::memory_order_acquire);
}
bool ResponseWriter::finished() const noexcept
{
return m_state != nullptr &&
m_state->finished.load(std::memory_order_acquire);
}
bool ResponseWriter::cancelled() const noexcept
{
return m_state == nullptr ||
m_state->cancel_requested.load(std::memory_order_acquire) ||
(m_state->stopping != nullptr &&
m_state->stopping->load(std::memory_order_acquire));
}
bool ResponseWriter::chunked() const noexcept
{
return m_state != nullptr &&
m_state->chunked.load(std::memory_order_acquire);
}
std::optional<std::uint64_t> ResponseWriter::content_length() const noexcept
{
if (m_state == nullptr ||
!m_state->has_content_length.load(std::memory_order_acquire)) {
return std::nullopt;
}
return m_state->content_length.load(std::memory_order_acquire);
}
std::uint64_t ResponseWriter::bytes_accepted() const noexcept
{
return m_state != nullptr
? m_state->accepted.load(std::memory_order_acquire)
: 0;
}
std::uint64_t ResponseWriter::bytes_sent() const noexcept
{
return m_state != nullptr
? m_state->sent.load(std::memory_order_acquire)
: 0;
}
std::size_t ResponseWriter::buffered_bytes() const noexcept
{
return m_state != nullptr
? m_state->pending_bytes.load(std::memory_order_acquire)
: 0;
}
std::stop_token ResponseWriter::stop_token() const noexcept
{
return m_state != nullptr ? m_state->stop_source.get_token()
: std::stop_token{};
}
void ResponseWriter::cancel() noexcept
{
if (m_state) {
m_state->cancel_requested.store(true, std::memory_order_release);
m_state->request_stop();
}
}
void ResponseWriter::set_write_timeout(
std::chrono::milliseconds timeout) noexcept
{
if (m_state) {
m_state->write_timeout_ms.store(timeout.count(),
std::memory_order_release);
}
}
std::chrono::milliseconds ResponseWriter::write_timeout() const noexcept
{
return std::chrono::milliseconds{
m_state != nullptr
? m_state->write_timeout_ms.load(std::memory_order_acquire)
: std::chrono::seconds{30}.count()};
}
Void::Result::Result<void>
ResponseWriter::begin(std::uint16_t status, std::vector<Header> headers)
{
auto active = writer_require_active(m_state);
if (!active.has_value()) {
return active;
}
State& state = *m_state;
std::unique_lock lock{state.io_mutex, std::try_to_lock};
if (!lock.owns_lock()) {
return Void::Result::fail(
Void::Result::ErrorKind::overloaded,
"Net::ResponseWriter: concurrent writer");
}
if (state.invalid.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: exchange is no longer active")};
}
if (state.begun.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response already started")};
}
if (state.stopped()) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ResponseWriter: exchange cancelled")};
}
if (status < 100 || status > 599) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: invalid status code")};
}
const bool bodyless = state.head_request ||
(status >= 100 && status < 200) || status == 204 ||
status == 304;
std::optional<std::uint64_t> content_length;
std::optional<std::string> transfer_encoding;
bool connection_close = false;
std::string extra_headers;
for (const auto& header : headers) {
if (!is_valid_token(header.name) ||
has_crlf_or_nul(header.name) ||
has_crlf_or_nul(header.value)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: invalid response header")};
}
if (equal_ascii_ci(header.name, "Content-Length")) {
std::uint64_t parsed = 0;
if (!parse_u64_decimal(trim_ows(header.value), parsed)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: invalid Content-Length")};
}
if (content_length.has_value() &&
*content_length != parsed) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: conflicting Content-Length")};
}
content_length = parsed;
continue;
}
if (equal_ascii_ci(header.name, "Transfer-Encoding")) {
if (transfer_encoding.has_value()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: duplicate Transfer-Encoding")};
}
transfer_encoding = header.value;
continue;
}
if (equal_ascii_ci(header.name, "Connection")) {
if (contains_ascii_ci(header.value, "close")) {
connection_close = true;
}
continue;
}
extra_headers += header.name;
extra_headers += ": ";
extra_headers += header.value;
extra_headers += "\r\n";
}
if (transfer_encoding.has_value() &&
!equal_ascii_ci(trim_ows(*transfer_encoding), "chunked")) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: unsupported Transfer-Encoding")};
}
if (transfer_encoding.has_value() && content_length.has_value()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: ambiguous response framing")};
}
if (bodyless && transfer_encoding.has_value()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: bodyless response with "
"Transfer-Encoding")};
}
if (bodyless && content_length.has_value() && !state.head_request &&
status != 304) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: bodyless response with "
"Content-Length")};
}
bool chunked = false;
bool fixed = false;
bool close_delimited = false;
if (!bodyless) {
if (transfer_encoding.has_value()) {
chunked = true;
} else if (content_length.has_value()) {
fixed = true;
} else if (state.http10) {
close_delimited = true;
} else {
chunked = true;
}
}
bool keep = state.keep_alive.load(std::memory_order_acquire) &&
!close_delimited;
if (connection_close) {
keep = false;
}
std::string head =
std::format("HTTP/1.1 {} {}\r\n", status, reason_phrase(status));
head += extra_headers;
if (bodyless) {
if (content_length.has_value()) {
head += std::format("Content-Length: {}\r\n",
*content_length);
}
} else if (fixed) {
head += std::format("Content-Length: {}\r\n", *content_length);
} else if (chunked) {
head += "Transfer-Encoding: chunked\r\n";
}
head += std::format("Connection: {}\r\n\r\n",
keep ? "keep-alive" : "close");
state.head_attempted.store(true, std::memory_order_release);
auto sent_head = writer_send_all(
state, std::as_bytes(std::span{head.data(), head.size()}));
if (!sent_head.has_value()) {
return std::unexpected{std::move(sent_head.error())};
}
state.bodyless.store(bodyless, std::memory_order_release);
state.chunked.store(chunked, std::memory_order_release);
state.fixed_length.store(fixed, std::memory_order_release);
state.close_delimited.store(close_delimited,
std::memory_order_release);
state.keep_alive.store(keep, std::memory_order_release);
if (content_length.has_value()) {
state.content_length.store(*content_length,
std::memory_order_release);
state.has_content_length.store(true,
std::memory_order_release);
}
state.begun.store(true, std::memory_order_release);
return {};
}
Void::Result::Result<std::size_t>
ResponseWriter::write_some(std::span<const std::byte> bytes)
{
auto active = writer_require_active(m_state);
if (!active.has_value()) {
return std::unexpected{std::move(active.error())};
}
State& state = *m_state;
std::unique_lock lock{state.io_mutex, std::try_to_lock};
if (!lock.owns_lock()) {
return Void::Result::fail(
Void::Result::ErrorKind::overloaded,
"Net::ResponseWriter: concurrent writer");
}
if (state.invalid.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: exchange is no longer active")};
}
if (!state.begun.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response not started")};
}
if (state.finished.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response already finished")};
}
if (state.stopped()) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ResponseWriter: exchange cancelled")};
}
if (bytes.empty()) {
return std::size_t{0};
}
if (state.bodyless.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: bodyless response cannot carry a body")};
}
auto flushed = writer_flush(state);
if (!flushed.has_value()) {
return std::unexpected{std::move(flushed.error())};
}
const std::size_t max_pending = state.max_pending;
std::size_t capacity = max_pending;
if (state.chunked.load(std::memory_order_acquire)) {
// Leave room for the chunk size line and trailing CRLF.
capacity = max_pending > 32 ? max_pending - 32 : 1;
}
std::size_t accepted = std::min(bytes.size(), capacity);
if (accepted == 0) {
return std::size_t{0};
}
if (state.fixed_length.load(std::memory_order_acquire)) {
const std::uint64_t total =
state.content_length.load(std::memory_order_acquire);
const std::uint64_t written =
state.accepted.load(std::memory_order_acquire);
const std::uint64_t remaining =
total > written ? total - written : 0;
if (accepted > remaining) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: fixed-length body overflow")};
}
}
if (state.chunked.load(std::memory_order_acquire)) {
state.pending += std::format("{:x}\r\n", accepted);
state.pending.append(
reinterpret_cast<const char*>(bytes.data()), accepted);
state.pending += "\r\n";
} else {
state.pending.append(
reinterpret_cast<const char*>(bytes.data()), accepted);
}
state.pending_bytes.store(state.pending.size(),
std::memory_order_release);
state.accepted.fetch_add(accepted, std::memory_order_acq_rel);
auto after = writer_flush(state);
if (!after.has_value()) {
return std::unexpected{std::move(after.error())};
}
return accepted;
}
Void::Result::Result<void> ResponseWriter::finish()
{
auto active = writer_require_active(m_state);
if (!active.has_value()) {
return active;
}
State& state = *m_state;
std::unique_lock lock{state.io_mutex, std::try_to_lock};
if (!lock.owns_lock()) {
return Void::Result::fail(
Void::Result::ErrorKind::overloaded,
"Net::ResponseWriter: concurrent writer");
}
if (state.invalid.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: exchange is no longer active")};
}
if (!state.begun.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response not started")};
}
if (state.finished.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ResponseWriter: response already finished")};
}
if (state.stopped()) {
state.request_stop();
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ResponseWriter: exchange cancelled")};
}
auto flushed = writer_flush(state);
if (!flushed.has_value()) {
return std::unexpected{std::move(flushed.error())};
}
if (state.chunked.load(std::memory_order_acquire)) {
const std::string_view terminal = "0\r\n\r\n";
auto res = writer_send_all(
state, std::as_bytes(std::span{terminal.data(),
terminal.size()}));
if (!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
} else if (state.fixed_length.load(std::memory_order_acquire)) {
const std::uint64_t total =
state.content_length.load(std::memory_order_acquire);
const std::uint64_t written =
state.accepted.load(std::memory_order_acquire);
if (written != total) {
return std::unexpected{make_net_error(
NetErrorCode::protocol_error,
"Net::ResponseWriter: fixed-length body incomplete")};
}
}
state.finished.store(true, std::memory_order_release);
state.request_stop();
return {};
}
struct ResponseWriterAccess {
static ResponseWriter
make(std::shared_ptr<ResponseWriter::State> state)
{
return ResponseWriter{std::move(state)};
}
};
namespace
{
struct StreamingRoute {
Method method;
std::string pattern;
std::vector<std::string> segments;
StreamingRouteHandler handler;
};
struct DuplexRoute {
Method method;
std::string pattern;
std::vector<std::string> segments;
DuplexRouteHandler handler;
};
struct WorkerEntry {
std::uint64_t id{0};
std::atomic<int> client_fd{-1};
std::atomic<bool> finished{false};
std::thread thread{};
};
struct WebSocketRoute {
std::string pattern;
std::vector<std::string> segments;
WebSocketSessions* sessions{nullptr};
WebSocketUpgradeOptions options{};
};
class TcpWebSocketConnection final : public WebSocketConnection
{
public:
TcpWebSocketConnection(WebSocketConnectionId id, int fd,
WebSocketLimits limits) noexcept
: m_id(id), m_fd(fd), m_limits(limits)
{
}
[[nodiscard]] WebSocketConnectionId id() const noexcept override
{
return m_id;
}
[[nodiscard]] Void::Result::Result<void>
send_text(std::string_view message) override
{
if (!is_valid_utf8(message)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::WebSocket: invalid UTF-8 in server text")};
}
if (message.size() > m_limits.max_message_bytes) {
return std::unexpected{make_net_error(
NetErrorCode::payload_too_large,
"Net::WebSocket: message exceeds max_message_bytes")};
}
WebSocketFrame f;
f.fin = true;
f.opcode = WebSocketOpcode::Text;
f.masked = false;
f.payload.resize(message.size());
if (!message.empty()) {
std::memcpy(f.payload.data(), message.data(),
message.size());
}
return send_frame(f);
}
[[nodiscard]] Void::Result::Result<void>
send_binary(std::span<const std::byte> message) override
{
if (message.size() > m_limits.max_message_bytes) {
return std::unexpected{make_net_error(
NetErrorCode::payload_too_large,
"Net::WebSocket: binary message exceeds limit")};
}
WebSocketFrame f;
f.fin = true;
f.opcode = WebSocketOpcode::Binary;
f.masked = false;
f.payload.assign(message.begin(), message.end());
return send_frame(f);
}
[[nodiscard]] Void::Result::Result<void>
send_pong(std::span<const std::byte> payload)
{
WebSocketFrame f;
f.fin = true;
f.opcode = WebSocketOpcode::Pong;
f.masked = false;
f.payload.assign(payload.begin(), payload.end());
return send_frame(f);
}
void close(const WebSocketClose& close_info) noexcept override
{
std::lock_guard lock{m_io_mutex};
if (m_closed || m_fd < 0) {
m_closed = true;
return;
}
m_closed = true;
if (!m_close_sent) {
m_close_sent = true;
auto cf = encode_websocket_close_frame(close_info, false);
if (cf.has_value()) {
(void)send_all(m_fd, *cf,
std::chrono::milliseconds{500});
}
}
(void)::shutdown(m_fd, SHUT_RDWR);
}
void detach_fd() noexcept
{
std::lock_guard lock{m_io_mutex};
m_closed = true;
m_fd = -1;
}
[[nodiscard]] bool is_closed() const noexcept
{
std::lock_guard lock{m_io_mutex};
return m_closed || m_fd < 0;
}
private:
[[nodiscard]] Void::Result::Result<void>
send_frame(const WebSocketFrame& frame)
{
auto encoded = encode_websocket_frame(frame);
if (!encoded.has_value()) {
return std::unexpected{std::move(encoded.error())};
}
std::lock_guard lock{m_io_mutex};
if (m_closed || m_fd < 0) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
"Net::WebSocket: connection closed")};
}
return send_all(m_fd, *encoded, m_limits.io_timeout);
}
WebSocketConnectionId m_id{};
mutable std::mutex m_io_mutex{};
int m_fd{-1};
bool m_closed{false};
bool m_close_sent{false};
WebSocketLimits m_limits{};
};
} // namespace
struct HttpServer::Impl {
HttpServerOptions options{};
std::optional<Router> owned_router{};
Router* router{nullptr};
mutable std::shared_mutex stream_mutex{};
std::vector<StreamingRoute> streaming_routes{};
std::vector<DuplexRoute> duplex_routes{};
std::vector<WebSocketRoute> ws_routes{};
std::atomic<std::uint64_t> next_ws_id{1};
std::atomic<bool> running{false};
std::atomic<bool> stopping{false};
int listen_fd{-1};
int wake_fd{-1};
std::uint16_t bound_port{0};
std::string bind_addr_str{};
std::thread accept_thread{};
std::mutex workers_mutex{};
std::condition_variable workers_cv{};
std::uint64_t next_worker_id{0};
std::map<std::uint64_t, std::unique_ptr<WorkerEntry>> workers{};
~Impl() noexcept { shutdown(std::chrono::seconds{5}); }
void reap_finished_workers()
{
std::vector<std::thread> to_join;
{
std::lock_guard lock{workers_mutex};
for (auto it = workers.begin(); it != workers.end();) {
if (it->second->finished.load(
std::memory_order_acquire)) {
if (it->second->thread.joinable()) {
to_join.push_back(std::move(it->second->thread));
}
it = workers.erase(it);
} else {
++it;
}
}
}
for (auto& t : to_join) {
t.join();
}
}
[[nodiscard]] std::optional<
std::pair<StreamingRouteHandler, RouteParameters>>
match_streaming(Method m, std::string_view path_view) const
{
const auto segments = split_path(path_view);
std::shared_lock lock{stream_mutex};
const StreamingRoute* best = nullptr;
RouteParameters best_params;
for (const auto& r : streaming_routes) {
if (r.method != m) {
continue;
}
auto matched = match_segments(r.segments, segments);
if (!matched.has_value()) {
continue;
}
if (best == nullptr ||
more_specific_route(r.segments, best->segments)) {
best = &r;
best_params = std::move(*matched);
}
}
if (best == nullptr) {
return std::nullopt;
}
return std::pair<StreamingRouteHandler, RouteParameters>{
best->handler, std::move(best_params)};
}
[[nodiscard]] std::optional<
std::pair<DuplexRouteHandler, RouteParameters>>
match_duplex(Method m, std::string_view path_view) const
{
const auto segments = split_path(path_view);
std::shared_lock lock{stream_mutex};
const DuplexRoute* best = nullptr;
RouteParameters best_params;
for (const auto& r : duplex_routes) {
if (r.method != m) {
continue;
}
auto matched = match_segments(r.segments, segments);
if (!matched.has_value()) {
continue;
}
if (best == nullptr ||
more_specific_route(r.segments, best->segments)) {
best = &r;
best_params = std::move(*matched);
}
}
if (best == nullptr) {
return std::nullopt;
}
return std::pair<DuplexRouteHandler, RouteParameters>{
best->handler, std::move(best_params)};
}
[[nodiscard]] std::optional<WebSocketRoute>
match_websocket(std::string_view path_view) const
{
const auto segments = split_path(path_view);
std::shared_lock lock{stream_mutex};
const WebSocketRoute* best = nullptr;
for (const auto& r : ws_routes) {
if (!match_segments(r.segments, segments).has_value()) {
continue;
}
if (best == nullptr ||
more_specific_route(r.segments, best->segments)) {
best = &r;
}
}
if (best == nullptr) {
return std::nullopt;
}
return *best;
}
void run_websocket_session(int fd, const WebSocketRoute& route,
const WebSocketUpgradeHandshake& hs,
std::string& rx_buf,
std::size_t& rx_off)
{
std::string resp = std::format(
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: {}\r\n",
hs.accept_key);
if (hs.selected_subprotocol.has_value()) {
resp += std::format("Sec-WebSocket-Protocol: {}\r\n",
*hs.selected_subprotocol);
}
resp += "\r\n";
if (!send_str(fd, resp, options.write_timeout).has_value()) {
return;
}
const WebSocketConnectionId cid{
next_ws_id.fetch_add(1, std::memory_order_relaxed)};
auto conn = std::make_shared<TcpWebSocketConnection>(
cid, fd, route.options.limits);
auto opened = route.sessions->open(conn);
if (!opened.has_value() || !(*opened)) {
conn->close({1001, "session rejected"});
conn->detach_fd();
return;
}
WebSocketDecoder decoder{true, route.options.limits};
WebSocketClose final_close{1000, ""};
bool protocol_failed = false;
auto process_messages =
[&](const std::vector<WebSocketMessage>& messages) -> bool {
for (const auto& msg : messages) {
switch (msg.opcode) {
case WebSocketOpcode::Text:
(void)route.sessions->receive_text(
cid, msg.text_view());
break;
case WebSocketOpcode::Binary:
(void)route.sessions->receive_binary(
cid, msg.payload);
break;
case WebSocketOpcode::Ping:
if (!conn->send_pong(msg.payload).has_value()) {
return false;
}
break;
case WebSocketOpcode::Pong:
break;
case WebSocketOpcode::Close:
final_close = msg.close_info.value_or(
WebSocketClose{1000, ""});
conn->close(final_close);
return false;
case WebSocketOpcode::Continuation:
break;
}
}
return !conn->is_closed();
};
bool active = true;
if (rx_off < rx_buf.size()) {
const auto tail = std::span<const std::byte>{
reinterpret_cast<const std::byte*>(rx_buf.data()) +
rx_off,
rx_buf.size() - rx_off};
std::vector<WebSocketMessage> msgs;
auto dr = decoder.feed(tail, msgs);
rx_buf.clear();
rx_off = 0;
if (!dr.has_value()) {
protocol_failed = true;
(void)route.sessions->fail(cid, dr.error());
final_close = {1002, "protocol error"};
conn->close(final_close);
active = false;
} else {
active = process_messages(msgs);
}
}
std::array<char, 8192> buf{};
while (active && !stopping.load(std::memory_order_acquire) &&
!conn->is_closed()) {
auto nr = recv_slice(fd, buf, stopping,
route.options.limits.io_timeout);
if (!nr.has_value()) {
if (stopping.load(std::memory_order_acquire)) {
final_close = {1001, "server shutdown"};
conn->close(final_close);
} else if (nr.error().kind() !=
Void::Result::ErrorKind::cancelled) {
(void)route.sessions->fail(cid, nr.error());
final_close = {1006, "transport error"};
}
break;
}
if (*nr == 0) {
if (!decoder.close_received()) {
final_close = {1006, "peer closed"};
}
break;
}
std::vector<WebSocketMessage> msgs;
auto dr = decoder.feed(
std::span<const std::byte>{
reinterpret_cast<const std::byte*>(buf.data()),
*nr},
msgs);
if (!dr.has_value()) {
protocol_failed = true;
(void)route.sessions->fail(cid, dr.error());
final_close = {1002, "protocol error"};
conn->close(final_close);
break;
}
active = process_messages(msgs);
}
(void)protocol_failed;
conn->detach_fd();
(void)route.sessions->disconnect(cid, final_close);
}
[[nodiscard]] std::vector<Method>
collect_allowed_methods(std::string_view path_view) const
{
std::vector<Method> methods = router->allowed_methods(path_view);
const auto segments = split_path(path_view);
{
std::shared_lock lock{stream_mutex};
for (const auto& r : streaming_routes) {
if (match_segments(r.segments, segments).has_value() &&
std::ranges::find(methods, r.method) ==
methods.end()) {
methods.push_back(r.method);
}
}
for (const auto& r : duplex_routes) {
if (match_segments(r.segments, segments).has_value() &&
std::ranges::find(methods, r.method) ==
methods.end()) {
methods.push_back(r.method);
}
}
}
return methods;
}
void send_response(int fd, Method req_method, ServerResponse resp,
bool keep_alive)
{
std::string file_path_err;
OwnedFd file_fd;
std::uint64_t body_len = resp.body.size();
std::string content_type_default;
if (resp.file_body.has_value()) {
OwnedFd f{::open(resp.file_body->c_str(),
O_RDONLY | O_CLOEXEC | O_NOFOLLOW)};
if (!f) {
const std::uint16_t err_status =
errno == ENOENT ? 404 : 500;
resp.file_body.reset();
resp.status = err_status;
resp.headers.clear();
resp.body = err_status == 404 ? "Not Found"
: "Internal Server Error";
body_len = resp.body.size();
} else {
struct stat st{};
if (::fstat(f.get(), &st) != 0 ||
!S_ISREG(st.st_mode)) {
resp.file_body.reset();
resp.status = 500;
resp.headers.clear();
resp.body = "Internal Server Error";
body_len = resp.body.size();
} else {
file_fd = std::move(f);
body_len = static_cast<std::uint64_t>(st.st_size);
content_type_default =
std::string{content_type_for(*resp.file_body)};
}
}
}
std::string head = std::format(
"HTTP/1.1 {} {}\r\nContent-Length: {}\r\nConnection: "
"{}\r\n",
resp.status, reason_phrase(resp.status), body_len,
keep_alive ? "keep-alive" : "close");
bool has_ct = false;
for (const auto& h : resp.headers) {
if (has_crlf_or_nul(h.name) || has_crlf_or_nul(h.value) ||
!is_valid_token(h.name)) {
continue;
}
if (equal_ascii_ci(h.name, "Content-Length") ||
equal_ascii_ci(h.name, "Connection") ||
equal_ascii_ci(h.name, "Transfer-Encoding")) {
continue;
}
if (equal_ascii_ci(h.name, "Content-Type")) {
has_ct = true;
}
head += h.name;
head += ": ";
head += h.value;
head += "\r\n";
}
if (!has_ct && !content_type_default.empty()) {
head += "Content-Type: ";
head += content_type_default;
head += "\r\n";
}
head += "\r\n";
if (!send_str(fd, head, options.write_timeout).has_value()) {
return;
}
if (req_method == Method::Head) {
return;
}
if (file_fd) {
std::array<std::byte, 64 * 1024> buf{};
std::uint64_t remaining = body_len;
while (remaining > 0) {
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(remaining, buf.size()));
const ssize_t r = ::read(file_fd.get(), buf.data(), want);
if (r < 0 && errno == EINTR) {
continue;
}
if (r <= 0) {
return;
}
if (!send_all(fd,
std::span<const std::byte>{
buf.data(),
static_cast<std::size_t>(r)},
options.write_timeout)
.has_value()) {
return;
}
remaining -= static_cast<std::uint64_t>(r);
}
return;
}
if (!resp.body.empty()) {
(void)send_str(fd, resp.body, options.write_timeout);
}
}
void send_error_close(int fd, std::uint16_t status,
std::string_view msg,
std::vector<Header> extra = {})
{
ServerResponse r;
r.status = status;
r.headers = std::move(extra);
r.body = std::string{msg};
send_response(fd, Method::Get, std::move(r), false);
(void)::shutdown(fd, SHUT_WR);
}
void serve_connection(int raw_fd, WorkerEntry& entry)
{
OwnedFd fd_guard{raw_fd};
std::string rx_buf;
std::size_t rx_off = 0;
while (!stopping.load(std::memory_order_acquire)) {
// 1. Read request headers up to \r\n\r\n.
std::size_t hdr_end = std::string::npos;
bool peer_eof = false;
bool hdr_too_large = false;
while (true) {
const std::size_t found = rx_buf.find("\r\n\r\n", rx_off);
if (found != std::string::npos) {
if (found - rx_off > options.max_header_bytes) {
hdr_too_large = true;
}
hdr_end = found;
break;
}
if (rx_buf.size() - rx_off > options.max_header_bytes) {
hdr_too_large = true;
break;
}
if (rx_off > 0 && rx_buf.size() == rx_off) {
rx_buf.clear();
rx_off = 0;
}
std::array<char, 8192> chunk{};
auto nr = recv_slice(fd_guard.get(), chunk, stopping,
options.read_timeout);
if (!nr.has_value()) {
peer_eof = true;
break;
}
if (*nr == 0) {
peer_eof = true;
break;
}
rx_buf.append(chunk.data(), *nr);
}
if (hdr_too_large) {
send_error_close(fd_guard.get(), 431,
"Request Header Fields Too Large");
break;
}
if (peer_eof || hdr_end == std::string::npos) {
break;
}
const std::string_view header_block{
rx_buf.data() + rx_off, hdr_end - rx_off};
rx_off = hdr_end + 4U;
// 2. Parse request line.
const std::size_t first_eol = header_block.find("\r\n");
const std::string_view req_line =
first_eol == std::string_view::npos
? header_block
: header_block.substr(0, first_eol);
const std::size_t sp1 = req_line.find(' ');
const std::size_t sp2 =
sp1 == std::string_view::npos
? std::string_view::npos
: req_line.find(' ', sp1 + 1U);
if (sp1 == std::string_view::npos ||
sp2 == std::string_view::npos ||
req_line.find(' ', sp2 + 1U) != std::string_view::npos) {
send_error_close(fd_guard.get(), 400, "Bad Request");
break;
}
const auto method_opt =
parse_method(req_line.substr(0, sp1));
if (!method_opt.has_value()) {
send_error_close(fd_guard.get(), 501,
"Not Implemented");
break;
}
const std::string_view target =
req_line.substr(sp1 + 1U, sp2 - sp1 - 1U);
const std::string_view version = req_line.substr(sp2 + 1U);
if ((version != "HTTP/1.1" && version != "HTTP/1.0") ||
target.empty() || target.front() != '/' ||
has_crlf_or_nul(target)) {
send_error_close(fd_guard.get(), 400, "Bad Request");
break;
}
std::string_view raw_path = target;
std::string_view raw_query{};
if (const std::size_t qpos = target.find('?');
qpos != std::string_view::npos) {
raw_path = target.substr(0, qpos);
raw_query = target.substr(qpos + 1U);
}
if (const std::size_t hpos = raw_query.find('#');
hpos != std::string_view::npos) {
raw_query = raw_query.substr(0, hpos);
}
// 3. Parse & validate headers (RFC 9112 smuggling rules).
std::vector<Header> headers;
bool has_te = false;
bool chunked = false;
bool bad_headers = false;
bool too_many_headers = false;
bool expect_continue = false;
std::optional<std::uint64_t> content_length;
std::optional<bool> conn_keep_alive;
std::size_t hpos =
first_eol == std::string_view::npos
? header_block.size()
: first_eol + 2U;
while (hpos < header_block.size()) {
const std::size_t eol = header_block.find("\r\n", hpos);
const std::string_view line =
eol == std::string_view::npos
? header_block.substr(hpos)
: header_block.substr(hpos, eol - hpos);
hpos = (eol == std::string_view::npos)
? header_block.size()
: (eol + 2U);
const std::size_t colon = line.find(':');
if (colon == std::string_view::npos) {
bad_headers = true;
break;
}
const std::string_view hname = line.substr(0, colon);
const std::string_view hval =
trim_ows(line.substr(colon + 1U));
if (!is_valid_token(hname) || has_crlf_or_nul(hval)) {
bad_headers = true;
break;
}
if (headers.size() >= options.max_headers) {
too_many_headers = true;
break;
}
if (equal_ascii_ci(hname, "Content-Length")) {
std::uint64_t cl = 0;
if (!parse_u64_decimal(hval, cl)) {
bad_headers = true;
break;
}
if (content_length.has_value() &&
*content_length != cl) {
bad_headers = true;
break;
}
content_length = cl;
} else if (equal_ascii_ci(hname, "Transfer-Encoding")) {
has_te = true;
if (contains_ascii_ci(hval, "chunked")) {
chunked = true;
}
} else if (equal_ascii_ci(hname, "Connection")) {
if (contains_ascii_ci(hval, "close")) {
conn_keep_alive = false;
} else if (contains_ascii_ci(hval, "keep-alive")) {
conn_keep_alive = true;
}
} else if (equal_ascii_ci(hname, "Expect")) {
if (equal_ascii_ci(hval, "100-continue")) {
expect_continue = true;
}
}
headers.push_back(
Header{std::string{hname}, std::string{hval}});
}
if (too_many_headers) {
send_error_close(fd_guard.get(), 431,
"Request Header Fields Too Large");
break;
}
if (bad_headers || (has_te && content_length.has_value())) {
send_error_close(fd_guard.get(), 400, "Bad Request");
break;
}
if (has_te && !chunked) {
send_error_close(fd_guard.get(), 501,
"Not Implemented");
break;
}
bool keep_alive =
conn_keep_alive.has_value()
? *conn_keep_alive
: (version == "HTTP/1.1");
if (stopping.load(std::memory_order_acquire)) {
keep_alive = false;
}
// 3b. Check RFC 6455 WebSocket upgrade route.
if (auto ws_match = match_websocket(raw_path);
ws_match.has_value()) {
ServerRequest ws_req;
ws_req.method = *method_opt;
ws_req.path = std::string{raw_path};
ws_req.headers = std::move(headers);
ws_req.query = std::string{raw_query};
auto hs = validate_websocket_upgrade_request(
ws_req, ws_match->options);
if (!hs.has_value()) {
send_error_close(fd_guard.get(), 400,
"Bad Request");
break;
}
run_websocket_session(fd_guard.get(), *ws_match, *hs,
rx_buf, rx_off);
break;
}
// 4. Check duplex/streaming routes vs buffered Router.
auto duplex_match = match_duplex(*method_opt, raw_path);
auto streaming_match =
match_streaming(*method_opt, raw_path);
const bool live_route = duplex_match.has_value() ||
streaming_match.has_value();
if (!live_route) {
// Enforce buffered max_body_bytes before reading body.
if (!chunked && content_length.has_value() &&
*content_length > options.max_body_bytes) {
send_error_close(fd_guard.get(), 413,
"Payload Too Large");
break;
}
} else {
if (!chunked && content_length.has_value() &&
options.max_streaming_body_bytes > 0 &&
*content_length >
options.max_streaming_body_bytes) {
send_error_close(fd_guard.get(), 413,
"Payload Too Large");
break;
}
}
BodyReader::State reader_state;
reader_state.fd = fd_guard.get();
reader_state.stopping = &stopping;
reader_state.read_timeout = options.read_timeout;
reader_state.default_max_bytes =
streaming_match.has_value()
? options.max_streaming_body_bytes
: options.max_body_bytes;
reader_state.rx_buf = &rx_buf;
reader_state.rx_off = &rx_off;
reader_state.chunked = chunked;
reader_state.declared_length = content_length;
reader_state.remaining_fixed =
content_length.value_or(0ULL);
reader_state.eof =
(!chunked && reader_state.remaining_fixed == 0);
BodyReader body_reader{reader_state};
if (expect_continue &&
(chunked || reader_state.remaining_fixed > 0)) {
if (!send_str(fd_guard.get(),
"HTTP/1.1 100 Continue\r\n\r\n",
options.write_timeout)
.has_value()) {
break;
}
}
if (duplex_match.has_value()) {
ServerRequest req;
req.method = *method_opt;
req.path = std::string{raw_path};
req.headers = std::move(headers);
req.parameters = std::move(duplex_match->second);
req.query = std::string{raw_query};
auto writer_state =
std::make_shared<ResponseWriter::State>();
writer_state->fd = fd_guard.get();
writer_state->stopping = &stopping;
writer_state->write_timeout_ms.store(
options.write_timeout.count(),
std::memory_order_release);
writer_state->max_pending =
options.duplex_write_buffer_bytes;
writer_state->head_request =
(*method_opt == Method::Head);
writer_state->http10 = (version == "HTTP/1.0");
writer_state->keep_alive.store(
keep_alive, std::memory_order_release);
ResponseWriter writer =
ResponseWriterAccess::make(writer_state);
auto route_res = duplex_match->first(
req, body_reader, writer);
const bool committed = writer_state->begun.load(
std::memory_order_acquire);
const bool head_attempted =
writer_state->head_attempted.load(
std::memory_order_acquire);
if (!route_res.has_value()) {
if (!committed && !head_attempted &&
!stopping.load(std::memory_order_acquire)) {
if (route_res.error().kind() ==
Void::Result::ErrorKind::exhausted) {
send_error_close(fd_guard.get(), 413,
"Payload Too Large");
} else if (
route_res.error().kind() ==
Void::Result::ErrorKind::timeout ||
route_res.error().kind() ==
Void::Result::ErrorKind::cancelled) {
send_error_close(fd_guard.get(), 408,
"Request Timeout");
} else {
send_error_close(
fd_guard.get(), 500,
"Internal Server Error");
}
}
// After headers the stream is simply terminated
// without a successful terminal chunk.
} else if (!committed) {
if (!head_attempted) {
send_error_close(fd_guard.get(), 500,
"Internal Server Error");
}
} else if (!writer_state->finished.load(
std::memory_order_acquire)) {
auto fin = writer.finish();
if (!fin.has_value()) {
// Framing could not be completed; close.
}
}
const bool completed = writer_state->finished.load(
std::memory_order_acquire);
const bool exchange_keep_alive =
keep_alive &&
writer_state->keep_alive.load(
std::memory_order_acquire) &&
reader_state.eof;
{
// Wait for any writer still inside an
// operation, then permanently invalidate the
// shared state. Retained writers stay memory-safe
// but can no longer touch this connection.
std::lock_guard lock{writer_state->io_mutex};
writer_state->invalid.store(
true, std::memory_order_release);
writer_state->fd = -1;
writer_state->stopping = nullptr;
}
writer_state->request_stop();
if (!exchange_keep_alive || !completed) {
break;
}
continue;
}
if (streaming_match.has_value()) {
ServerRequest req;
req.method = *method_opt;
req.path = std::string{raw_path};
req.headers = std::move(headers);
req.parameters = std::move(streaming_match->second);
req.query = std::string{raw_query};
auto route_res =
streaming_match->first(req, body_reader);
if (!route_res.has_value()) {
if (route_res.error().kind() ==
Void::Result::ErrorKind::exhausted) {
send_error_close(fd_guard.get(), 413,
"Payload Too Large");
} else {
send_error_close(fd_guard.get(), 500,
"Internal Server Error");
}
break;
}
if (!reader_state.eof) {
keep_alive = false;
}
send_response(fd_guard.get(), *method_opt,
std::move(*route_res), keep_alive);
if (!keep_alive) {
break;
}
continue;
}
// Buffered body read (respecting max_body_bytes on both
// Content-Length and chunked transfer encoding).
std::string body_str;
bool payload_too_large = false;
bool body_io_err = false;
if (chunked || reader_state.remaining_fixed > 0) {
if (!chunked) {
body_str.reserve(static_cast<std::size_t>(
reader_state.remaining_fixed));
}
std::array<std::byte, 32 * 1024> tmp{};
for (;;) {
auto nr = body_reader.read_some(tmp);
if (!nr.has_value()) {
body_io_err = true;
break;
}
if (*nr == 0) {
break;
}
if (body_str.size() + *nr >
options.max_body_bytes) {
payload_too_large = true;
break;
}
body_str.append(
reinterpret_cast<const char*>(tmp.data()), *nr);
}
}
if (payload_too_large) {
send_error_close(fd_guard.get(), 413,
"Payload Too Large");
break;
}
if (body_io_err) {
break;
}
Method dispatch_method = *method_opt;
ServerRequest req;
req.method = dispatch_method;
req.path = std::string{raw_path};
req.headers = std::move(headers);
req.body = std::move(body_str);
req.query = std::string{raw_query};
auto dispatched = router->dispatch(req);
if (!dispatched.has_value()) {
send_error_close(fd_guard.get(), 500,
"Internal Server Error");
break;
}
if (!dispatched->has_value() &&
dispatch_method == Method::Head) {
req.method = Method::Get;
dispatched = router->dispatch(req);
if (!dispatched.has_value()) {
send_error_close(fd_guard.get(), 500,
"Internal Server Error");
break;
}
}
if (!dispatched->has_value()) {
const auto allowed = collect_allowed_methods(raw_path);
if (!allowed.empty()) {
std::string allow_hdr;
for (std::size_t i = 0; i < allowed.size(); ++i) {
if (i > 0) allow_hdr += ", ";
allow_hdr += method_string(allowed[i]);
}
send_response(
fd_guard.get(), *method_opt,
ServerResponse{
.status = 405,
.headers = {Header{"Allow",
std::move(allow_hdr)}},
.body = "Method Not Allowed"},
keep_alive);
} else {
send_response(
fd_guard.get(), *method_opt,
ServerResponse{.status = 404,
.body = "Not Found"},
keep_alive);
}
if (!keep_alive) {
break;
}
continue;
}
send_response(fd_guard.get(), *method_opt,
std::move(**dispatched), keep_alive);
if (!keep_alive) {
break;
}
}
entry.client_fd.store(-1, std::memory_order_release);
fd_guard.reset();
}
void accept_loop()
{
while (!stopping.load(std::memory_order_acquire)) {
std::array<struct pollfd, 2> pfds{{
{.fd = listen_fd, .events = POLLIN, .revents = 0},
{.fd = wake_fd, .events = POLLIN, .revents = 0},
}};
const int pr = ::poll(pfds.data(), pfds.size(), 100);
if (pr < 0) {
if (errno == EINTR) {
continue;
}
break;
}
if ((pfds[1].revents & POLLIN) != 0) {
std::uint64_t val = 0;
// Best effort: the eventfd is only a wakeup hint and the
// stopping flag is authoritative, but consume the result so
// fortified headers do not raise -Wunused-result.
[[maybe_unused]] const ssize_t drained =
::read(wake_fd, &val, sizeof(val));
}
if (stopping.load(std::memory_order_acquire)) {
break;
}
if ((pfds[0].revents & POLLIN) == 0) {
reap_finished_workers();
continue;
}
for (;;) {
#ifdef SOCK_CLOEXEC
int client_fd = ::accept4(listen_fd, nullptr, nullptr,
SOCK_CLOEXEC);
#else
int client_fd = ::accept(listen_fd, nullptr, nullptr);
if (client_fd >= 0) {
(void)::fcntl(client_fd, F_SETFD, FD_CLOEXEC);
}
#endif
if (client_fd < 0) {
if (errno == EINTR) {
continue;
}
break;
}
reap_finished_workers();
std::lock_guard lock{workers_mutex};
if (stopping.load(std::memory_order_acquire) ||
workers.size() >=
options.max_concurrent_connections) {
// Unlock or immediately decline without unbounded
// thread creation.
const std::string_view busy =
"HTTP/1.1 503 Service Unavailable\r\n"
"Content-Length: 19\r\n"
"Connection: close\r\n\r\n"
"Service Unavailable";
// The connection is closed regardless of whether the
// 503 could be delivered; consume the result explicitly.
[[maybe_unused]] const ssize_t sent =
::send(client_fd, busy.data(), busy.size(),
MSG_NOSIGNAL);
(void)::close(client_fd);
continue;
}
const std::uint64_t id = ++next_worker_id;
auto entry = std::make_unique<WorkerEntry>();
entry->id = id;
entry->client_fd.store(client_fd,
std::memory_order_release);
WorkerEntry* raw_entry = entry.get();
entry->thread =
std::thread([this, raw_entry, client_fd]() {
serve_connection(client_fd, *raw_entry);
raw_entry->finished.store(
true, std::memory_order_release);
std::lock_guard lk{workers_mutex};
workers_cv.notify_all();
});
workers.emplace(id, std::move(entry));
}
}
}
void shutdown(std::chrono::milliseconds drain_timeout) noexcept
{
const bool was_running =
running.load(std::memory_order_acquire);
if (!was_running && listen_fd < 0 &&
!accept_thread.joinable()) {
return;
}
stopping.store(true, std::memory_order_release);
if (wake_fd >= 0) {
const std::uint64_t one = 1;
// Best effort wakeup: the accept loop also polls with a
// timeout, so a full eventfd cannot delay shutdown.
[[maybe_unused]] const ssize_t signalled =
::write(wake_fd, &one, sizeof(one));
}
if (accept_thread.joinable()) {
accept_thread.join();
}
if (listen_fd >= 0) {
(void)::close(listen_fd);
listen_fd = -1;
}
if (wake_fd >= 0) {
(void)::close(wake_fd);
wake_fd = -1;
}
std::vector<std::thread> to_join;
{
std::unique_lock lock{workers_mutex};
const auto all_finished = [this]() {
for (const auto& [id, w] : workers) {
(void)id;
if (!w->finished.load(std::memory_order_acquire)) {
return false;
}
}
return true;
};
if (drain_timeout > std::chrono::milliseconds::zero()) {
(void)workers_cv.wait_for(lock, drain_timeout,
all_finished);
}
for (const auto& [id, w] : workers) {
(void)id;
const int cfd = w->client_fd.exchange(
-1, std::memory_order_acq_rel);
if (cfd >= 0) {
(void)::shutdown(cfd, SHUT_RDWR);
}
}
for (auto& [id, w] : workers) {
(void)id;
if (w->thread.joinable()) {
to_join.push_back(std::move(w->thread));
}
}
}
for (auto& t : to_join) {
t.join();
}
{
std::lock_guard lock{workers_mutex};
workers.clear();
}
bound_port = 0;
bind_addr_str.clear();
running.store(false, std::memory_order_release);
stopping.store(false, std::memory_order_release);
}
};
HttpServer::HttpServer(HttpServerOptions options)
: m_impl(std::make_unique<Impl>())
{
m_impl->options = std::move(options);
m_impl->owned_router.emplace();
m_impl->router = &(*m_impl->owned_router);
}
HttpServer::HttpServer(Router& external_router, HttpServerOptions options)
: m_impl(std::make_unique<Impl>())
{
m_impl->options = std::move(options);
m_impl->router = &external_router;
}
HttpServer::~HttpServer() noexcept = default;
HttpServer::HttpServer(HttpServer&&) noexcept = default;
HttpServer& HttpServer::operator=(HttpServer&&) noexcept = default;
Router& HttpServer::router() noexcept { return *m_impl->router; }
Void::Result::Result<void>
HttpServer::add_route(Method method, std::string pattern,
RouteHandler handler)
{
return m_impl->router->add(method, std::move(pattern),
std::move(handler));
}
Void::Result::Result<void>
HttpServer::add_streaming_route(Method method, std::string pattern,
StreamingRouteHandler handler)
{
if (!handler) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer: streaming route handler is empty")};
}
auto compiled = compile_route_pattern(pattern);
if (!compiled.has_value()) {
return std::unexpected{std::move(compiled.error())};
}
std::unique_lock lock{m_impl->stream_mutex};
const auto dup = std::ranges::find_if(
m_impl->streaming_routes, [&](const StreamingRoute& r) {
return r.method == method &&
same_route_shape(r.segments, *compiled);
});
if (dup != m_impl->streaming_routes.end()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer: duplicate streaming route")};
}
m_impl->streaming_routes.push_back(StreamingRoute{
method, std::move(pattern), std::move(*compiled),
std::move(handler)});
return {};
}
Void::Result::Result<void>
HttpServer::add_duplex_route(Method method, std::string pattern,
DuplexRouteHandler handler)
{
if (!handler) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer: duplex route handler is empty")};
}
auto compiled = compile_route_pattern(pattern);
if (!compiled.has_value()) {
return std::unexpected{std::move(compiled.error())};
}
std::unique_lock lock{m_impl->stream_mutex};
const auto dup = std::ranges::find_if(
m_impl->duplex_routes, [&](const DuplexRoute& r) {
return r.method == method &&
same_route_shape(r.segments, *compiled);
});
if (dup != m_impl->duplex_routes.end()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer: duplicate duplex route")};
}
m_impl->duplex_routes.push_back(DuplexRoute{
method, std::move(pattern), std::move(*compiled),
std::move(handler)});
return {};
}
Void::Result::Result<void>
HttpServer::add_websocket_route(std::string pattern,
WebSocketSessions& sessions,
WebSocketUpgradeOptions options)
{
auto compiled = compile_route_pattern(pattern);
if (!compiled.has_value()) {
return std::unexpected{std::move(compiled.error())};
}
std::unique_lock lock{m_impl->stream_mutex};
const auto dup = std::ranges::find_if(
m_impl->ws_routes, [&](const WebSocketRoute& r) {
return same_route_shape(r.segments, *compiled);
});
if (dup != m_impl->ws_routes.end()) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer: duplicate WebSocket route")};
}
m_impl->ws_routes.push_back(WebSocketRoute{
std::move(pattern), std::move(*compiled), &sessions,
std::move(options)});
return {};
}
Void::Result::Result<void> HttpServer::start()
{
if (m_impl->running.load(std::memory_order_acquire)) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer::start: server is already running")};
}
if (m_impl->options.max_concurrent_connections == 0 ||
m_impl->options.max_header_bytes == 0 ||
m_impl->options.max_headers == 0 ||
m_impl->options.duplex_write_buffer_bytes == 0) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::HttpServer::start: limits must be positive")};
}
const std::string host = m_impl->options.bind_host.empty()
? std::string{"127.0.0.1"}
: m_impl->options.bind_host;
const std::string port_str = std::to_string(m_impl->options.port);
struct addrinfo hints{};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
struct addrinfo* res = nullptr;
const int gai = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &res);
if (gai != 0 || res == nullptr) {
return std::unexpected{make_net_error(
NetErrorCode::connect_failed,
std::format("Net::HttpServer::start: getaddrinfo '{}' failed: "
"{}",
host, ::gai_strerror(gai)))};
}
OwnedFd listen_guard;
int last_errno = 0;
for (struct addrinfo* p = res; p != nullptr; p = p->ai_next) {
#ifdef SOCK_CLOEXEC
int fd = ::socket(p->ai_family, p->ai_socktype | SOCK_CLOEXEC,
p->ai_protocol);
#else
int fd = ::socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (fd >= 0) {
(void)::fcntl(fd, F_SETFD, FD_CLOEXEC);
}
#endif
if (fd < 0) {
last_errno = errno;
continue;
}
OwnedFd cand{fd};
int yes = 1;
(void)::setsockopt(cand.get(), SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(yes));
if (::bind(cand.get(), p->ai_addr, p->ai_addrlen) == 0 &&
::listen(cand.get(), m_impl->options.listen_backlog) == 0) {
listen_guard = std::move(cand);
break;
}
last_errno = errno;
}
::freeaddrinfo(res);
if (!listen_guard) {
return std::unexpected{make_net_error(
NetErrorCode::connect_failed,
std::format("Net::HttpServer::start: bind/listen on {}:{} "
"failed: {}",
host, m_impl->options.port,
std::strerror(last_errno)),
std::error_code{last_errno, std::generic_category()})};
}
(void)::fcntl(listen_guard.get(), F_SETFL,
::fcntl(listen_guard.get(), F_GETFL, 0) | O_NONBLOCK);
struct sockaddr_storage ss{};
socklen_t slen = sizeof(ss);
if (::getsockname(listen_guard.get(), reinterpret_cast<sockaddr*>(&ss),
&slen) != 0) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::HttpServer::start: getsockname failed: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()})};
}
std::array<char, INET6_ADDRSTRLEN> ip_buf{};
std::uint16_t actual_port = 0;
if (ss.ss_family == AF_INET) {
const auto* s4 = reinterpret_cast<const sockaddr_in*>(&ss);
actual_port = ntohs(s4->sin_port);
(void)::inet_ntop(AF_INET, &s4->sin_addr, ip_buf.data(),
ip_buf.size());
m_impl->bind_addr_str = ip_buf.data();
} else if (ss.ss_family == AF_INET6) {
const auto* s6 = reinterpret_cast<const sockaddr_in6*>(&ss);
actual_port = ntohs(s6->sin6_port);
(void)::inet_ntop(AF_INET6, &s6->sin6_addr, ip_buf.data(),
ip_buf.size());
m_impl->bind_addr_str = std::format("[{}]", ip_buf.data());
}
int efd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (efd < 0) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::HttpServer::start: eventfd failed: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()})};
}
m_impl->listen_fd = listen_guard.release();
m_impl->wake_fd = efd;
m_impl->bound_port = actual_port;
m_impl->stopping.store(false, std::memory_order_release);
m_impl->running.store(true, std::memory_order_release);
m_impl->accept_thread =
std::thread([impl = m_impl.get()]() { impl->accept_loop(); });
return {};
}
void HttpServer::shutdown(std::chrono::milliseconds drain_timeout) noexcept
{
if (m_impl) {
m_impl->shutdown(drain_timeout);
}
}
bool HttpServer::running() const noexcept
{
return m_impl && m_impl->running.load(std::memory_order_acquire);
}
std::uint16_t HttpServer::bound_port() const noexcept
{
return m_impl ? m_impl->bound_port : 0;
}
std::string HttpServer::bind_address() const
{
return m_impl ? m_impl->bind_addr_str : std::string{};
}
std::string HttpServer::base_url() const
{
if (!m_impl || m_impl->bound_port == 0) {
return {};
}
return std::format("http://{}:{}", m_impl->bind_addr_str,
m_impl->bound_port);
}
} // namespace Void::Net