// SPDX-FileCopyrightText: 2026 James Chapman // SPDX-License-Identifier: GPL-3.0-or-later #include "merovingian/homeserver/HttpServer.hpp" #include "merovingian/config/Config.hpp" #include "merovingian/config/HttpTransportConfig.hpp" #include "merovingian/core/CurrentException.hpp" #include "merovingian/core/Error.hpp" #include "merovingian/core/QueryParams.hpp" #include "merovingian/core/SocketHandle.hpp" #include "merovingian/database/PersistentStore.hpp" #include "merovingian/homeserver/ConnectionAdmission.hpp" #include "merovingian/homeserver/ConnectionContext.hpp" #include "merovingian/homeserver/FederationProxy.hpp" #include "merovingian/homeserver/FederationRequestRouting.hpp" #include "merovingian/homeserver/HttpConnection.hpp" #include "merovingian/homeserver/HttpConnectionDispatcher.hpp" #include "merovingian/homeserver/HttpServeStats.hpp" #include "merovingian/homeserver/HttpServeTuning.hpp" #include "merovingian/homeserver/HttpServerInternal.hpp" #include "merovingian/homeserver/LocalHttpRequest.hpp" #include "merovingian/homeserver/LocalHttpResponse.hpp" #include "merovingian/homeserver/LocalHttpRouter.hpp" #include "merovingian/homeserver/MediaFetchAdmissionCaps.hpp" #include "merovingian/homeserver/ParkingReservation.hpp" #include "merovingian/homeserver/RemoteMediaFetchMode.hpp" #include "merovingian/homeserver/RoundOutcome.hpp" #include "merovingian/homeserver/StreamedBody.hpp" #include "merovingian/homeserver/StreamedBodyResult.hpp" #include "merovingian/homeserver/SyncAdmissionCaps.hpp" #include "merovingian/homeserver/Tls.hpp" #include "merovingian/homeserver/TlsConnection.hpp" #include "merovingian/homeserver/TlsServerContext.hpp" #include "merovingian/http/ClientAddress.hpp" #include "merovingian/http/ConnectionLimiter.hpp" #include "merovingian/http/ConnectionPreference.hpp" #include "merovingian/http/HttpVersion.hpp" #include "merovingian/http/KeepAlive.hpp" #include "merovingian/http/KeepAlivePolicy.hpp" #include "merovingian/http/Request.hpp" #include "merovingian/http/RequestErrorCode.hpp" #include "merovingian/http/RequestHead.hpp" #include "merovingian/http/RequestLimits.hpp" #include "merovingian/http/ResponseHead.hpp" #include "merovingian/net/ConnectionParker.hpp" #include "merovingian/observability/LogEventSeverity.hpp" #include "merovingian/observability/Observability.hpp" #include "merovingian/observability/SingleLog.hpp" #include "merovingian/observability/StructuredLogField.hpp" #include "merovingian/sync/ParkedPoll.hpp" #include "merovingian/sync/ParkedPollLimits.hpp" #include "merovingian/sync/WakeReason.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace merovingian::homeserver { namespace { using detail::resume_parked_poll; using detail::serve_request_round; auto log_diagnostic(std::string_view event, std::vector fields, observability::LogEventSeverity severity = observability::LogEventSeverity::debug) -> void { observability::log_diagnostic("http_server", event, fields, severity); } // Waits for one readiness event on `fd`, bounded by `timeout_ms`. Returns // false on timeout or error so the caller fails the I/O rather than // retrying forever. [[nodiscard]] auto poll_for_plain_io(int fd, short events, int timeout_ms) noexcept -> bool { auto entry = pollfd{}; entry.fd = fd; entry.events = events; auto const poll_result = ::poll(&entry, 1U, timeout_ms); return poll_result > 0 && (entry.revents & events) != 0; } // Convert the peer sockaddr captured at accept() time to a dotted-decimal // (IPv4) or colon-separated (IPv6) string. Returns an empty string when // the address family is unknown rather than crashing — the rate limiter // treats empty as "unknown" and falls back to the synthetic global bucket. [[nodiscard]] auto peer_addr_to_string(sockaddr_storage const& sa) noexcept -> std::string { char buf[INET6_ADDRSTRLEN] = {}; if (sa.ss_family == AF_INET) { auto const* in4 = reinterpret_cast(&sa); if (::inet_ntop(AF_INET, &in4->sin_addr, buf, sizeof(buf)) == nullptr) { return {}; } } else if (sa.ss_family == AF_INET6) { auto const* in6 = reinterpret_cast(&sa); if (::inet_ntop(AF_INET6, &in6->sin6_addr, buf, sizeof(buf)) == nullptr) { return {}; } } return {buf}; } // C2: the three swallowed-exception sites in this file (sync wait, sync // pool dispatch, dispatch_local_http_request) previously logged only // {"reason":"exception"}. Capture the mangled type // (core::current_exception_type_name) and the std::exception message so a // postmortem can identify the throwing site. using core::current_exception_type_name; [[nodiscard]] auto current_exception_message() noexcept -> std::string { try { std::rethrow_exception(std::current_exception()); } catch (std::exception const& ex) { return std::string{ex.what()}; } catch (...) { return {}; } } auto log_swallowed_exception(std::string_view site) -> void { auto fields = std::vector{ observability::StructuredLogField{"site", std::string{site}, false}, observability::StructuredLogField{"type", std::string{current_exception_type_name()}, false}, observability::StructuredLogField{"what", current_exception_message(), false} }; log_diagnostic("sync.exception", std::move(fields)); } using detail::receive_timeout_milliseconds; // B3: slowloris hardening for the request HEAD, which a worker reads once // the connection is readable (ADR-0077: the first byte is waited for by // the dispatcher, never by a worker): // - overall request-head deadline (30 s): a slow client can dribble a // head indefinitely without ever filling the head buffer. // - per-byte inter-byte cap (5 s) between bytes of the head. // A client that dribbles heads holds at most its own share of the workers // (max(1, pool / 4)) for at most 30 s each. constexpr auto request_head_deadline = std::chrono::seconds{30}; constexpr auto inter_byte_timeout = std::chrono::seconds{5}; constexpr auto header_terminator = std::string_view{"\r\n\r\n"}; class ConnectionStream { public: ConnectionStream() = default; virtual ~ConnectionStream() = default; ConnectionStream(ConnectionStream const&) = delete; auto operator=(ConnectionStream const&) -> ConnectionStream& = delete; ConnectionStream(ConnectionStream&&) = delete; auto operator=(ConnectionStream&&) -> ConnectionStream& = delete; [[nodiscard]] virtual auto fd() const noexcept -> int = 0; // Input already held above the socket, which poll() cannot see. [[nodiscard]] virtual auto has_buffered_input() const noexcept -> bool { return false; } [[nodiscard]] virtual auto read(char* buffer, std::size_t capacity) noexcept -> std::ptrdiff_t = 0; [[nodiscard]] virtual auto write(std::string_view data) noexcept -> std::ptrdiff_t = 0; }; // A plain-HTTP connection. The descriptor is non-blocking for the life of // the connection (see make_connection_stream), so both directions retry // against a deadline here rather than parking a worker in the kernel. // // ADR-0054 made TLS sockets non-blocking for life and stated the rule this // class now also obeys: no code below the HTTP layer may perform a blocking // I/O call on a connection descriptor, because every timeout above is // expressed as poll() on that descriptor and that is only a timeout if the // call beneath it cannot block. Reads here were already guarded by the HTTP // layer's poll(POLLIN); writes were not, so a peer that accepted a // connection and then stopped reading held a worker inside ::send() for as // long as it liked. class PlainConnectionStream final : public ConnectionStream { public: PlainConnectionStream(int file_descriptor, int io_timeout_milliseconds) noexcept : m_fd{file_descriptor} , m_io_timeout_ms{io_timeout_milliseconds} { } [[nodiscard]] auto fd() const noexcept -> int override { return m_fd; } [[nodiscard]] auto read(char* buffer, std::size_t capacity) noexcept -> std::ptrdiff_t override { while (true) { auto const received = ::recv(m_fd, buffer, capacity, 0); if (received >= 0) { return received; } if (errno == EINTR) { continue; } // Callers poll POLLIN before reading, so EAGAIN here is a // spurious readiness (a discarded packet, a checksum failure). // Wait for real data rather than reporting a dead connection. if (errno != EAGAIN && errno != EWOULDBLOCK) { return -1; } if (!poll_for_plain_io(m_fd, POLLIN, m_io_timeout_ms)) { return -1; } } } [[nodiscard]] auto write(std::string_view data) noexcept -> std::ptrdiff_t override { while (true) { // MSG_NOSIGNAL avoids SIGPIPE on early client close (POSIX 2008). auto const sent = ::send(m_fd, data.data(), data.size(), MSG_NOSIGNAL); if (sent >= 0) { return sent; } if (errno == EINTR) { continue; } if (errno != EAGAIN && errno != EWOULDBLOCK) { return -1; } // The peer's receive window is full. Wait for it to drain, but // only for as long as the deadline allows: a client that never // reads must cost one bounded timeout, not a parked worker. if (!poll_for_plain_io(m_fd, POLLOUT, m_io_timeout_ms)) { return -1; } } } private: int m_fd; int m_io_timeout_ms; }; // A TLS connection, borrowed from the HttpConnection that owns it for the // length of one request round (or one sync-pool response). class TlsConnectionStream final : public ConnectionStream { public: explicit TlsConnectionStream(TlsConnection& connection) noexcept : m_connection{connection} { } [[nodiscard]] auto fd() const noexcept -> int override { return m_connection.fd(); } [[nodiscard]] auto has_buffered_input() const noexcept -> bool override { return m_connection.has_pending_input(); } [[nodiscard]] auto read(char* buffer, std::size_t capacity) noexcept -> std::ptrdiff_t override { return m_connection.read(buffer, capacity); } [[nodiscard]] auto write(std::string_view data) noexcept -> std::ptrdiff_t override { return m_connection.write(data); } private: TlsConnection& m_connection; }; // --------------------------------------------------------------------- // Connections and the dispatcher (ADR-0077) // // Matrix v1.19 is served over HTTP/1.1, where persistent connections are // the default (RFC 9112 §9.3). A connection is served one request round at // a time: read one request, drain its body exactly, write one response. // Between rounds, and before the first one, the connection is held by the // dispatcher (net::ConnectionParker), NOT by a worker thread; a worker gets // it back only once it is readable. Pipelining (more than one outstanding // request) is NOT supported: pipelined bytes are buffered and served in // order, one response at a time. // // Ownership: every connection is an HttpConnection behind a // std::unique_ptr, owned by exactly one of the parker, one pool task, or // one sync-pool task at any moment. Destroying it closes the socket and // releases everything it holds (per-IP slot, parking reservation). // --------------------------------------------------------------------- // ADR-0072: decided at accept time, before a byte is read. A connection // from an address in server.trusted_proxies is exempt, because a reverse // proxy carries many clients over its own address; per-client limiting // then relies on the proxy and on the per-IP rate limiter, which sees the // forwarded address. Everything else is counted under its // client_address_key and refused once that key holds // server.http.max_connections_per_ip connections. The same key (and the // same exemption) is the connection's per-client worker share (ADR-0077). [[nodiscard]] auto admit_connection(ClientServerRuntime& runtime, std::string const& peer_addr) -> ConnectionAdmission { auto const& server = runtime.homeserver.config.server(); if (std::ranges::find(server.trusted_proxies, peer_addr) != server.trusted_proxies.end()) { return {true, std::nullopt, {}}; } if (!runtime.connection_limiter) { return {false, std::nullopt, {}}; } auto key = http::client_address_key(peer_addr, server.http.ipv6_client_prefix_length); if (key.empty()) { // Fail closed: an address we could not render still shares one // budget rather than escaping the per-client caps. key = "unknown"; } auto slot = runtime.connection_limiter->try_acquire(key, server.http.max_connections_per_ip); if (!slot.has_value()) { return {false, std::nullopt, {}}; } auto admission = ConnectionAdmission{}; admission.admitted = true; admission.slot.emplace(std::move(*slot)); admission.client_key = std::move(key); return admission; } // The effective keep-alive policy for one connection. Keep-alive is off // when there is no dispatcher to park the connection on: direct // serve_one_http_connection callers keep the one-request-per-call // contract. [[nodiscard]] auto keep_alive_policy_for(ConnectionContext const& ctx) noexcept -> http::KeepAlivePolicy { auto const& http_config = ctx.runtime.homeserver.config.server().http; auto const enabled = http_config.keep_alive && ctx.dispatcher != nullptr; return {enabled, http_config.keep_alive_idle_seconds, http_config.keep_alive_max_connections}; } [[nodiscard]] auto set_socket_nonblocking(int fd) noexcept -> bool { auto const flags = ::fcntl(fd, F_GETFL, 0); if (flags < 0) { return false; } return ::fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0; } // Returns nullptr when the plain socket cannot be put into non-blocking // mode; the caller closes the connection. Failing closed matters: a socket // left blocking silently reinstates the unbounded ::send() this was written // to remove, and nothing above would notice. [[nodiscard]] auto make_connection_stream(HttpConnection& connection) -> std::unique_ptr { if (connection.tls.has_value()) { // accept_tls_connection already left this descriptor non-blocking // and deliberately never restores it (ADR-0054). return std::make_unique(*connection.tls); } auto const fd = connection.fd(); if (!set_socket_nonblocking(fd)) { log_diagnostic("connection.nonblocking_failed", { {"fd", std::to_string(fd), false}, {"errno", std::to_string(errno), false} }); return nullptr; } return std::make_unique(fd, receive_timeout_milliseconds); } [[nodiscard]] auto header_size_cap(http::RequestLimits const& limits) noexcept -> std::size_t { auto const headers = static_cast(limits.max_header_bytes); auto const start = static_cast(limits.max_start_line_bytes); // Allow for the start line, the header block, and a trailing CRLFCRLF. return start + headers + header_terminator.size(); } [[nodiscard]] auto body_size_cap(http::RequestLimits const& limits) noexcept -> std::size_t { return static_cast(limits.max_body_bytes); } // Returned by recv_with_timeout when the poll budget expired with no data, // as distinct from -1 for a peer close or socket error. The caller loops on // it so the slowloris caps below are re-evaluated and the specific one that // expired is the thing that ends the request (and gets logged). constexpr auto recv_budget_expired = std::ptrdiff_t{-2}; // `budget_ms` bounds this single poll. It must be the SMALLEST of the // per-read timeout and the time left on any slowloris cap the caller is // enforcing: the caps are only checked between reads, so a poll allowed to // outlast one makes that cap unenforceable. That was a real defect — with a // fixed 15s poll and a 5s inter-byte cap, a peer that stopped mid-body held // the worker for the full 15s and the inter-byte cap never once fired. [[nodiscard]] auto recv_with_timeout(ConnectionStream& stream, char* buffer, std::size_t capacity, int budget_ms) noexcept -> std::ptrdiff_t { // Input OpenSSL already holds is invisible to poll(): read it now, or // the wait below runs out on bytes that have already arrived. if (stream.has_buffered_input()) { return stream.read(buffer, capacity); } auto entry = pollfd{}; entry.fd = stream.fd(); entry.events = POLLIN; auto const poll_result = ::poll(&entry, 1U, budget_ms); if (poll_result == 0) { return recv_budget_expired; } if (poll_result < 0) { return -1; } if ((entry.revents & POLLIN) == 0) { return -1; } return stream.read(buffer, capacity); } // The poll budget for one read: whichever of the per-read timeout, the // overall deadline, and the inter-byte cap runs out first. Never negative — // an already-expired cap yields a zero-length poll and the caller's loop-top // check then ends the request. [[nodiscard]] auto recv_budget_ms(std::chrono::steady_clock::time_point now, std::chrono::steady_clock::time_point deadline, std::chrono::steady_clock::time_point last_byte) noexcept -> int { auto const to_deadline = std::chrono::duration_cast(deadline - now).count(); auto const to_inter_byte = std::chrono::duration_cast((last_byte + inter_byte_timeout) - now).count(); auto const smallest = std::min({static_cast(receive_timeout_milliseconds), static_cast(to_deadline), static_cast(to_inter_byte)}); return smallest <= 0 ? 0 : static_cast(smallest); } // Reads one full request head. `buffered` carries bytes read past the // previous request (pipelined next request) so request boundaries are // never lost across keep-alive rounds; a complete head already in it is // returned without touching the socket. The slowloris clocks restart per // call, i.e. per request — a keep-alive connection parked between // requests is not charged for its idle time. [[nodiscard]] auto read_request_head(ConnectionStream& stream, std::string buffered, std::size_t cap) -> std::pair { auto buffer = std::move(buffered); // Pipelined head already fully buffered: no recv needed. This check // must precede the deadline logic so an idle park followed by a // buffered head is not misread as a slow client. if (auto const buffered_terminator = buffer.find(header_terminator); buffered_terminator != std::string::npos) { return {std::move(buffer), buffered_terminator + header_terminator.size()}; } auto chunk = std::array{}; auto const start = std::chrono::steady_clock::now(); auto last_byte = start; while (true) { // B3 slowloris: enforce an overall deadline and an inter-byte cap // in addition to the per-byte recv poll timeout. The deadline // bounds the worst-case worker hold time regardless of how // cleverly the client dribbles bytes. auto const now = std::chrono::steady_clock::now(); if (now - start >= request_head_deadline) { log_diagnostic( "request.head_slowloris", { {"reason", "overall_deadline", false}, {"elapsed_ms", std::to_string(std::chrono::duration_cast(now - start).count()), false }, {"bytes_received", std::to_string(buffer.size()), false} }); return {std::move(buffer), std::string::npos}; } if (now - last_byte >= inter_byte_timeout) { log_diagnostic( "request.head_slowloris", { {"reason", "inter_byte_timeout", false}, {"elapsed_ms", std::to_string(std::chrono::duration_cast(now - last_byte).count()), false }, {"bytes_received", std::to_string(buffer.size()), false} }); return {std::move(buffer), std::string::npos}; } if (buffer.size() >= cap) { return {std::move(buffer), std::string::npos}; } auto const remaining_capacity = cap - buffer.size(); auto const wanted = remaining_capacity < chunk.size() ? remaining_capacity : chunk.size(); // Bound the poll by whichever cap expires first, so neither the // overall deadline nor the inter-byte cap can be outlived by a // single read. On expiry, loop so the check above names the cap. auto const received = recv_with_timeout(stream, chunk.data(), wanted, recv_budget_ms(now, start + request_head_deadline, last_byte)); if (received == recv_budget_expired) { continue; } if (received <= 0) { return {std::move(buffer), std::string::npos}; } buffer.append(chunk.data(), static_cast(received)); last_byte = std::chrono::steady_clock::now(); auto const terminator = buffer.find(header_terminator); if (terminator != std::string::npos) { return {std::move(buffer), terminator + header_terminator.size()}; } } } // Body-read outcome. `leftover` holds any bytes past the request's // Content-Length that already arrived (a pipelined next request); they // are preserved so the keep-alive loop never loses a request boundary. struct BodyReadResult final { std::string body{}; std::string leftover{}; bool complete{false}; }; // Reads exactly `expected` body bytes (never more than `cap`) under the // minimum body rate (HTTP-1, ADR-0077): once `grace` has passed since the // body read started, the bytes received so far must be at least // `min_bytes_per_second` x (elapsed - grace). The rule is continuous: the // moment the count falls behind the line the read ends and the caller // answers 408. It replaced a whole-body deadline (30 s + length / 16 KiB) // with a 5 s inter-byte gap, which let a client that sent one byte every // 4.9 s hold a worker for most of an hour on a large upload. // // Bytes that arrived with the head count as received. A legitimate client // at or above the floor never trips the rule however large the body; // with the production values (10 s, 16 KiB/s) a 1 MiB body may take up to // 74 s. [[nodiscard]] auto read_remaining_body(ConnectionStream& stream, std::string head_tail, std::size_t expected, std::size_t cap, HttpServeTuning const& tuning) -> BodyReadResult { if (expected > cap) { return {}; } auto body = std::move(head_tail); if (body.size() >= expected) { auto leftover = body.substr(expected); body.resize(expected); return {std::move(body), std::move(leftover), true}; } auto chunk = std::array{}; auto const rate = std::max(1U, tuning.body_min_bytes_per_second); auto const start = std::chrono::steady_clock::now(); while (body.size() < expected) { auto const now = std::chrono::steady_clock::now(); // The instant the bytes held so far stop satisfying the rule: // grace plus the time the floor rate needs to deliver them. auto const earned = std::chrono::milliseconds{ static_cast((static_cast(body.size()) * 1000U) / rate)}; auto const trips_at = start + tuning.body_rate_grace + earned; if (now >= trips_at) { log_diagnostic( "request.body_slowloris", { {"reason", "minimum_body_rate", false}, {"elapsed_ms", std::to_string(std::chrono::duration_cast(now - start).count()), false }, {"bytes_received", std::to_string(body.size()), false}, {"bytes_expected", std::to_string(expected), false} }); return {}; } auto const remaining = expected - body.size(); auto const wanted = remaining < chunk.size() ? remaining : chunk.size(); // Never wait past the moment the rule would trip: the rule is only // checked between reads, so a longer poll would make it // unenforceable. auto const to_trip = std::chrono::duration_cast(trips_at - now).count(); auto const budget = std::max( 1, std::min(static_cast(receive_timeout_milliseconds), to_trip)); auto const received = recv_with_timeout(stream, chunk.data(), wanted, static_cast(budget)); if (received == recv_budget_expired) { continue; } if (received <= 0) { return {}; } body.append(chunk.data(), static_cast(received)); } return {std::move(body), {}, true}; } // A formatted head (or whole response), or the fixed 500 that replaces it when http::format_response_head refused // the handler's status or headers (ADR-0767). `refused` tells the writer to close the connection afterwards. struct FormattedResponse final { std::string text{}; bool refused{false}; }; // The fixed answer to a refused head: no handler header and Connection: close. Its own inputs are constant, so // the formatter cannot refuse them; the literal below is a last resort that is never expected to be used. [[nodiscard]] auto refused_response(std::string_view reason) -> FormattedResponse { log_diagnostic("response.head_refused", { {"reason", std::string{reason}, false} }, observability::LogEventSeverity::error); auto formatted = http::format_response(500U, R"({"errcode":"M_UNKNOWN","error":"internal server error"})", {}, http::ConnectionPreference::close, 0U); if (auto* text = std::get_if(&formatted)) { return {std::move(*text), true}; } return {"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", true}; } // Formats a full HTTP/1.1 response (http/ResponseHead.hpp). `connection` selects the framing declaration: // keep_alive announces a persistent connection and adds the Keep-Alive timeout hint; error responses and every // path that keeps one request per connection use the default `close`. [[nodiscard]] auto format_for_wire(std::uint16_t status, std::string_view body, std::vector> const& headers = {}, http::ConnectionPreference connection = http::ConnectionPreference::close, std::uint32_t keep_alive_timeout_seconds = 0U) -> FormattedResponse { auto formatted = http::format_response(status, body, headers, connection, keep_alive_timeout_seconds); if (auto* text = std::get_if(&formatted)) { return {std::move(*text), false}; } return refused_response(std::get(formatted).message()); } // The head alone, for a body of `body_length` bytes that is not in memory (ADR-0574). [[nodiscard]] auto format_head_for_wire(std::uint16_t status, std::uint64_t body_length, std::vector> const& headers, http::ConnectionPreference connection, std::uint32_t keep_alive_timeout_seconds) -> FormattedResponse { auto formatted = http::format_response_head(status, body_length, headers, connection, keep_alive_timeout_seconds); if (auto* text = std::get_if(&formatted)) { return {std::move(*text), false}; } return refused_response(std::get(formatted).message()); } auto send_all(ConnectionStream& stream, std::string_view data) noexcept -> bool { auto remaining = data; while (!remaining.empty()) { auto const sent = stream.write(remaining); if (sent <= 0) { return false; } remaining.remove_prefix(static_cast(sent)); } return true; } // The size the "response_bytes" log field reports: a streamed body is not in `body`. [[nodiscard]] auto response_body_bytes(LocalHttpResponse const& response) -> std::uint64_t { return response.body_stream.has_value() ? response.body_stream->size_bytes : response.body.size(); } // Writes one response. A body held in memory goes out with its head in one buffer. A streamed body (ADR-0574) // goes out as the head, then chunks read from the database one at a time with no runtime lock held: each read // is on a connection closed before the chunk is written, so a client that stops reading holds no database // connection. The stream's write timeouts apply to each chunk. The status line is already sent when a read // fails, so the only answer left is to report false and let the caller close the connection. [[nodiscard]] auto write_response(ConnectionStream& stream, LocalHttpResponse const& response, http::ConnectionPreference connection, std::uint32_t keep_alive_timeout_seconds) -> bool { if (!response.body_stream.has_value()) { auto const formatted = format_for_wire(response.status, response.body, response.headers, connection, keep_alive_timeout_seconds); // A refused head was answered with a 500 that says Connection: close, so the connection is not kept. return send_all(stream, formatted.text) && !formatted.refused; } auto const& source = *response.body_stream; auto const head = format_head_for_wire(response.status, source.size_bytes, response.headers, connection, keep_alive_timeout_seconds); if (!send_all(stream, head.text) || head.refused) { // Refused: the 500 went out instead of the head, and the streamed body is not sent. return false; } auto const result = write_streamed_body( source.size_bytes, database::media_blob_chunk_bytes, [&source](std::uint64_t offset, std::size_t length) { return database::read_media_blob_chunk(source.blob, source.size_bytes, offset, length); }, [&stream](std::string_view chunk) { return send_all(stream, chunk); }); if (result == StreamedBodyResult::read_failed) { log_diagnostic("response.stream_read_failed", { {"storage_id", source.blob.storage_id, false}, {"size_bytes", std::to_string(source.size_bytes), false} }, observability::LogEventSeverity::error); } return result == StreamedBodyResult::complete; } [[nodiscard]] auto find_header_value(http::RequestHead const& head, std::string_view name) -> std::string { for (auto const& header : head.headers) { if (header.name.size() != name.size()) { continue; } auto match = true; for (auto index = std::size_t{0U}; index < name.size(); ++index) { auto const left = header.name[index]; auto const right = name[index]; auto const left_lower = (left >= 'A' && left <= 'Z') ? static_cast(left - 'A' + 'a') : left; auto const right_lower = (right >= 'A' && right <= 'Z') ? static_cast(right - 'A' + 'a') : right; if (left_lower != right_lower) { match = false; break; } } if (match) { return header.value; } } return {}; } [[nodiscard]] auto extract_bearer_token(std::string_view authorization) -> std::string { auto constexpr prefix = std::string_view{"Bearer "}; if (authorization.size() <= prefix.size()) { return std::string{authorization}; } // Compare case-insensitively only on the scheme name. for (auto index = std::size_t{0U}; index < prefix.size(); ++index) { auto const candidate = authorization[index]; auto const expected = prefix[index]; auto const candidate_lower = (candidate >= 'A' && candidate <= 'Z') ? static_cast(candidate - 'A' + 'a') : candidate; auto const expected_lower = (expected >= 'A' && expected <= 'Z') ? static_cast(expected - 'A' + 'a') : expected; if (candidate_lower != expected_lower) { return std::string{authorization}; } } return std::string{authorization.substr(prefix.size())}; } // The routes on which an `access_token` query parameter is a client // credential: the client-server API and the media repository. Federation // requests are authenticated by X-Matrix and never read it here (the // federation OpenID userinfo route reads its own parameter). [[nodiscard]] auto carries_query_access_token(std::string_view target) noexcept -> bool { return target.starts_with("/_matrix/client/") || target.starts_with("/_matrix/media/"); } // The percent-decoded value of the first `access_token` query parameter, // or empty when there is none. [[nodiscard]] auto query_access_token(std::string_view target) -> std::string { auto const query_pos = target.find('?'); if (query_pos == std::string_view::npos) { return {}; } auto query = target.substr(query_pos + 1U); while (!query.empty()) { auto const amp = query.find('&'); auto const pair = query.substr(0U, amp); auto const equals = pair.find('='); if (equals != std::string_view::npos && core::percent_decode(pair.substr(0U, equals)) == "access_token") { return core::percent_decode(pair.substr(equals + 1U)); } if (amp == std::string_view::npos) { break; } query.remove_prefix(amp + 1U); } return {}; } // `target` with every `access_token` query parameter removed, and the `?` too when nothing is // left after it (ADR-0295). Handlers match exact paths such as `/_matrix/client/v3/createRoom`, // and a credential has no business in the target routing, rate-limit keys and logs see. [[nodiscard]] auto without_query_access_token(std::string_view target) -> std::string { auto const query_pos = target.find('?'); if (query_pos == std::string_view::npos) { return std::string{target}; } auto result = std::string{target.substr(0U, query_pos)}; auto kept = std::string{}; auto query = target.substr(query_pos + 1U); while (true) { auto const amp = query.find('&'); auto const pair = query.substr(0U, amp); auto const name = pair.substr(0U, pair.find('=')); if (!pair.empty() && core::percent_decode(name) != "access_token") { if (!kept.empty()) { kept.push_back('&'); } kept.append(pair); } if (amp == std::string_view::npos) { break; } query.remove_prefix(amp + 1U); } if (!kept.empty()) { result.push_back('?'); result.append(kept); } return result; } [[nodiscard]] auto build_local_request(http::RequestHead const& head, std::string body, std::string_view peer_addr) -> LocalHttpRequest { auto request = LocalHttpRequest{}; request.method = head.method; request.target = head.target; request.body = std::move(body); // Copy all request headers so downstream code (CORS, trusted-proxy // X-Forwarded-For resolution) has the full wire header set. request.headers = head.headers; auto const authorization = find_header_value(head, "authorization"); if (!authorization.empty()) { request.access_token = extract_bearer_token(authorization); } else if (carries_query_access_token(request.target)) { // Spec v1.19 client-server-api.md "Using access tokens": "Clients may // alternatively provide the access token via a query string parameter: // `access_token=TheTokenHere`. [...] Homeservers MUST support both // methods." Complement's blueprint runner sends every token this way. request.access_token = query_access_token(request.target); } if (carries_query_access_token(request.target)) { // Read (or overridden by the header) either way: the parameter leaves the target. request.target = without_query_access_token(request.target); } request.remote_addr = std::string{peer_addr}; return request; } // Reads the `Origin` header straight out of the raw head bytes. The // transport-layer error paths need it before (or instead of) a successful // parse — a head that was too large, timed out, or failed to parse still // has to answer a browser with CORS headers, and by then there is no // http::RequestHead to consult. [[nodiscard]] auto origin_from_raw_head(std::string_view raw) -> std::string { auto constexpr name = std::string_view{"origin"}; auto rest = raw; // Skip the request line; header fields start after the first CRLF. auto const first_break = rest.find("\r\n"); if (first_break == std::string_view::npos) { return {}; } rest.remove_prefix(first_break + 2U); while (!rest.empty()) { auto const line_end = rest.find("\r\n"); auto const line = rest.substr(0U, line_end == std::string_view::npos ? rest.size() : line_end); if (line.empty()) { return {}; } auto const colon = line.find(':'); if (colon != std::string_view::npos && colon == name.size()) { auto matches = true; for (auto index = std::size_t{0U}; index < name.size(); ++index) { auto const c = line[index]; auto const lower = (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; if (lower != name[index]) { matches = false; break; } } if (matches) { auto value = line.substr(colon + 1U); while (!value.empty() && (value.front() == ' ' || value.front() == '\t')) { value.remove_prefix(1U); } while (!value.empty() && (value.back() == ' ' || value.back() == '\t')) { value.remove_suffix(1U); } return std::string{value}; } } if (line_end == std::string_view::npos) { return {}; } rest.remove_prefix(line_end + 2U); } return {}; } // Spec v1.19 §10.5: the client-server API MUST "supply Cross-Origin // Resource Sharing (CORS) headers on all requests". "All" includes the // errors this transport layer answers before routing — a 400, 408 or 413 // without Access-Control-Allow-Origin reaches the browser as a CORS // failure, hiding the real status from the client entirely. // // Access-Control-Allow-Credentials is deliberately never emitted here: // these responses are not preflights, and pairing it with a wildcard origin // is a CORS-spec violation (see resolve_allow_origin in ClientServerRuntime.cpp). [[nodiscard]] auto transport_cors_headers(ConnectionContext const& ctx, std::string_view origin) -> std::vector> { auto headers = std::vector>{}; if (ctx.dispatch_mode != HttpDispatchMode::client_server || ctx.runtime.cors.allowed_origins.empty() || origin.empty()) { return headers; } for (auto const& allowed : ctx.runtime.cors.allowed_origins) { if (allowed == "*" || allowed == origin) { headers.emplace_back("Access-Control-Allow-Origin", allowed == "*" ? std::string{"*"} : std::string{origin}); // Vary: Origin so an intermediate cache cannot serve one // origin's response to another. headers.emplace_back("Vary", "Origin"); break; } } return headers; } auto write_error_response(ConnectionStream& stream, std::uint16_t status, std::string_view body, std::vector> const& cors_headers) noexcept -> void { auto const response = format_for_wire(status, body, cors_headers); std::ignore = send_all(stream, response.text); } // `GET /_merovingian/health` (ADR-0479). Matched on the path alone, so a probe that adds a query string is // still a probe; any other method is not. [[nodiscard]] auto is_health_probe(LocalHttpRequest const& request) noexcept -> bool { return request.method == "GET" && std::string_view{request.target}.substr(0U, request.target.find('?')) == "/_merovingian/health"; } // Routes a request without ever blocking. The caller is responsible for // handling DispatchResult::Status::needs_wait (long-poll sync) and, when it // passes RemoteMediaFetchMode::defer, needs_media_fetch (ADR-0121). [[nodiscard]] auto route_request(ClientServerRuntime& runtime, LocalHttpRequest const& request, HttpDispatchMode mode, RemoteMediaFetchMode remote_media = RemoteMediaFetchMode::inline_fetch) -> DispatchResult { // Fast path: the key-server endpoint is served from a lock-free atomic // cache so concurrent federation makes-join cannot delay it. if (mode == HttpDispatchMode::federation && request.method == "GET" && is_federation_key_server_endpoint(request.target)) { auto& cache = runtime.homeserver.database.key_server_cache; if (cache) { auto const now_ms = static_cast(std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()) .count()); // A stale document falls through to the slow path, which re-publishes // it with a fresh valid_until_ts before serving. if (auto cached = cache->load(now_ms)) { return { DispatchResult::Status::complete, {200U, *cached}, {} }; } } } auto result = DispatchResult{}; switch (mode) { case HttpDispatchMode::client_server: result = handle_client_server_request(runtime, request, ClientServerDispatchOptions{.remote_media = remote_media}); break; case HttpDispatchMode::federation: if (runtime.homeserver.federation_proxy != nullptr) { result.response = runtime.homeserver.federation_proxy->handle(request); } else { result.response = handle_federation_http_request(runtime.homeserver, request); } break; case HttpDispatchMode::local_router: result.response = handle_local_http_request(runtime.homeserver, request); break; } return result; } } // namespace auto health_probe_response(bool serving) -> LocalHttpResponse { return LocalHttpResponse{ serving ? std::uint16_t{200U} : std::uint16_t{503U}, serving ? "ok" : "unavailable", {{"Content-Type", "text/plain; charset=utf-8"}, {"Cache-Control", "no-store"}} }; } auto sync_admission_caps(config::HttpTransportConfig const& settings, std::size_t pool_worker_count) noexcept -> SyncAdmissionCaps { auto const configured_pool_size = pool_worker_count == 0U ? static_cast(settings.sync_threads) : pool_worker_count; auto const pool_cap = static_cast(std::min( configured_pool_size, static_cast(std::numeric_limits::max()))); // A parked wait holds no thread (ADR-0569), so with a sync pool the cap is not the pool size (ADR-0570). auto const global = pool_worker_count == 0U ? std::min(settings.sync_max_in_flight, pool_cap) : settings.sync_max_in_flight; return SyncAdmissionCaps{ .global = global, .per_user = std::min(settings.sync_max_per_user, global), .per_device = std::min(settings.sync_max_per_device, global), }; } auto media_fetch_admission_caps(config::HttpTransportConfig const& settings) noexcept -> MediaFetchAdmissionCaps { return MediaFetchAdmissionCaps{ .global = settings.media_fetch_max_in_flight, .per_client = std::min(settings.media_fetch_max_per_client, settings.media_fetch_max_in_flight), }; } auto http_request_limits_for(ClientServerRuntime const& runtime, HttpDispatchMode dispatch_mode, std::string_view method, std::string_view target) -> http::RequestLimits { auto limits = http::RequestLimits{}; auto const& runtime_config = runtime.homeserver.config; auto const& http_config = runtime_config.server().http; auto const body_limit = config::parse_size_limit(http_config.max_body_size); if (!body_limit.valid) { return limits; } limits.max_start_line_bytes = http_config.max_start_line_bytes; limits.max_header_bytes = http_config.max_header_bytes; limits.max_header_count = http_config.max_header_count; limits.max_body_bytes = body_limit.bytes; if (!http::request_limits_are_valid(limits)) { return http::RequestLimits{}; } constexpr auto send_prefix = std::string_view{"/_matrix/federation/v1/send/"}; if (dispatch_mode == HttpDispatchMode::federation && method == "PUT" && target.starts_with(send_prefix)) { auto const transaction_limit = config::parse_size_limit(runtime_config.security().federation.max_transaction_size); if (transaction_limit.valid && transaction_limit.bytes <= 64U * 1024U * 1024U) { limits.max_body_bytes = transaction_limit.bytes; } } return limits; } namespace { [[nodiscard]] auto is_media_upload_target(std::string_view method, std::string_view target) noexcept -> bool { if (method == "PUT") { // ADR-0212: content for an mxc:// URI reserved by POST /create. return target.starts_with("/_matrix/media/v3/upload/"); } return method == "POST" && (target == "/_matrix/media/v3/upload" || target.starts_with("/_matrix/media/v3/upload?") || target == "/_matrix/client/v1/media/upload" || target.starts_with("/_matrix/client/v1/media/upload?")); } [[nodiscard]] auto max_upload_bytes(ClientServerRuntime const& runtime) -> std::size_t { auto const parsed = config::parse_size_limit(runtime.homeserver.config.security().media.max_upload_size); auto const raw = parsed.valid ? parsed.bytes : std::uint64_t{104857600U}; return raw > std::numeric_limits::max() ? std::numeric_limits::max() : static_cast(raw); } // Connection framing for one response (RFC 9112 §9.3), decided when the // response is about to be written: the client's Connection header and // the keep-alive policy, then the per-connection caps (HTTP-8), then a // slot in the parked-connection budget. A kept-alive response holds that // slot (in the connection) until the connection is next dispatched, so // the Keep-Alive header is never a promise the dispatcher cannot keep. [[nodiscard]] auto decide_connection(ConnectionContext const& ctx, HttpConnection& connection, http::HttpVersion version, std::string_view connection_header) -> http::ConnectionPreference { ++connection.requests_served; auto const policy = keep_alive_policy_for(ctx); auto const parked = ctx.dispatcher != nullptr ? ctx.dispatcher->parked_keep_alive() : 0U; auto const preference = http::connection_preference_for_response(version, connection_header, policy, parked); if (preference != http::ConnectionPreference::keep_alive || ctx.dispatcher == nullptr) { return http::ConnectionPreference::close; } if (connection.requests_served >= ctx.tuning.max_requests_per_connection) { log_diagnostic("connection.request_cap_reached", { {"requests", std::to_string(connection.requests_served), false} }); return http::ConnectionPreference::close; } if (std::chrono::steady_clock::now() - connection.opened_at >= ctx.tuning.max_connection_lifetime) { log_diagnostic( "connection.lifetime_cap_reached", { {"lifetime_seconds", std::to_string(ctx.tuning.max_connection_lifetime.count()), false} }); return http::ConnectionPreference::close; } if (!ctx.dispatcher->reserve_keep_alive(connection, policy.max_connections)) { log_diagnostic("connection.keep_alive_cap_reached", { {"limit", std::to_string(policy.max_connections), false} }); return http::ConnectionPreference::close; } return http::ConnectionPreference::keep_alive; } // Runs a waiting /sync again, after a wake-up or once its timeout expires. // Its first run was counted by the rate limiter: a request only answers // needs_wait after allow() admitted it. Counting every re-run as well // refused a client allowed one more request with 429 at the moment its // waiting sync was answered. [[nodiscard]] auto rerun_waiting_sync(ClientServerRuntime& runtime, LocalHttpRequest const& request, bool can_wait) -> DispatchResult { return handle_client_server_request( runtime, request, ClientServerDispatchOptions{.can_wait = can_wait, .rate_limit_admitted = true}); } // The long-poll of the transports with no sync pool: one wait for the whole timeout, no peer peek. True when // a rerun completed and left its answer in `result`. [[nodiscard]] auto wait_for_sync(sync::SyncNotifier& notifier, ClientServerRuntime& runtime, LocalHttpRequest const& request, SyncWaitParams const& wait, DispatchResult& result) -> bool { auto const outcome = sync::long_poll_wait( notifier, wait.user_id, wait.since_stream_ordering, wait.since_sync_stream_id, std::chrono::steady_clock::now() + wait.timeout, std::chrono::milliseconds{wait.timeout}, [] { return true; }, [&] { auto interim = rerun_waiting_sync(runtime, request, true); if (interim.status == DispatchResult::Status::complete) { result = std::move(interim); return sync::LongPollStep{true, 0U, 0U}; } return sync::LongPollStep{false, interim.wait.since_stream_ordering, interim.wait.since_sync_stream_id}; }, [] { return true; }); return outcome.dispatched; } // A long-poll handed to the sync pool. It owns the connection from the // moment it is submitted; everything it needs is held by value, since the // round that created it may be gone by the time it runs. struct SyncHandoff final { ConnectionOwner connection; ConnectionContext ctx; LocalHttpRequest request; SyncWaitParams wait; sync::SyncNotifier& notifier; http::HttpVersion version; std::string connection_header; http::InFlightBudget::Slot user_slot; http::InFlightBudget::Slot device_slot; // Set when the first pass starts: the wait's timeout runs from there, not from the queueing. std::chrono::steady_clock::time_point deadline{}; // True until the first pass has run; the first pass checks the positions as well (ADR-0437). bool first_pass{true}; }; // A long-poll the notifier's registry can hold (ADR-0569). Destroying it closes the connection and releases // the admission slots, so a poll the registry drops at shutdown cleans up after itself. struct ParkedSyncPoll final : sync::ParkedPoll { explicit ParkedSyncPoll(SyncHandoff handoff_value) : handoff{std::move(handoff_value)} { } SyncHandoff handoff; }; // True when a non-blocking peek shows the peer closed (FIN or RST) rather than sent data or nothing. [[nodiscard]] auto peer_has_closed(int fd) -> bool { auto peek_buf = std::array{}; auto const n = ::recv(fd, peek_buf.data(), 1U, MSG_PEEK | MSG_DONTWAIT); return n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR); } enum class PollStep : std::uint8_t { // Respond now: with the answered result, or with a final rerun that does not wait. answer, client_gone, // The poll was moved into the registry and must not be touched again. parked, }; // One pass of a long-poll on a sync-pool thread (ADR-0569): take the cursor BEFORE the rerun, rerun, and if // there is still nothing, park with that cursor. A woken poll is rerun from the start; the registry never // answers. `poll` is null on return exactly when the result is `parked` (or a throw lost it). [[nodiscard]] auto advance_sync_poll(std::unique_ptr& poll, sync::WakeReason reason, std::optional& answered) -> PollStep { auto& handoff = poll->handoff; auto& runtime = handoff.ctx.runtime; auto* const sync_pool = handoff.ctx.sync_pool; auto& notifier = handoff.notifier; auto const fd = http_connection(handoff.connection).fd(); if (peer_has_closed(fd)) { return PollStep::client_gone; } if (handoff.deadline == std::chrono::steady_clock::time_point{}) { handoff.deadline = std::chrono::steady_clock::now() + handoff.wait.timeout; } if (reason == sync::WakeReason::deadline || !sync_pool->running()) { return PollStep::answer; } // (a) the cursor, then (b) the rerun whose snapshot is after it. auto cursor = notifier.observe(handoff.wait.user_id); auto const first = std::exchange(handoff.first_pass, false); if (!first || notifier.wait_for_change(handoff.wait.since_stream_ordering, handoff.wait.since_sync_stream_id, std::chrono::milliseconds{0})) { auto interim = rerun_waiting_sync(runtime, handoff.request, true); if (interim.status == DispatchResult::Status::complete) { answered = std::move(interim); return PollStep::answer; } handoff.wait.since_stream_ordering = interim.wait.since_stream_ordering; handoff.wait.since_sync_stream_id = interim.wait.since_sync_stream_id; } if (std::chrono::steady_clock::now() >= handoff.deadline) { return PollStep::answer; } // (c) park. Once parked the poll may be resumed on another thread at any moment: copy what is needed first. auto const deadline = handoff.deadline; auto* const dispatcher = handoff.ctx.dispatcher.get(); if (dispatcher != nullptr && dispatcher->parks_polls()) { auto base = std::unique_ptr{std::move(poll)}; if (notifier.park(cursor, deadline, base).parked) { return PollStep::parked; } // Refused (full, or stopping): keep the thread and wait as before, from the cursor already held. poll.reset(static_cast(base.release())); } auto& held = poll->handoff; constexpr auto poll_interval = std::chrono::milliseconds{1000U}; auto const outcome = sync::long_poll_wait( held.notifier, held.wait.user_id, held.wait.since_stream_ordering, held.wait.since_sync_stream_id, deadline, poll_interval, [sync_pool] { return sync_pool->running(); }, [&] { auto interim = rerun_waiting_sync(runtime, held.request, true); if (interim.status == DispatchResult::Status::complete) { answered = std::move(interim); return sync::LongPollStep{true, 0U, 0U}; } return sync::LongPollStep{false, interim.wait.since_stream_ordering, interim.wait.since_sync_stream_id}; }, [fd] { // Quiet slice: a peer that closed ends the wait at once, which keeps a client that reconnects in a // loop from exhausting the pool. return !peer_has_closed(fd); }, std::move(cursor)); return outcome.client_gone ? PollStep::client_gone : PollStep::answer; } // Writes the answer and hands a kept-alive connection back to the dispatcher. auto finish_sync_handoff(SyncHandoff& handoff, DispatchResult const& final_result) -> void { auto& stats = handoff.ctx.stats; auto& connection = http_connection(handoff.connection); ++stats.completed_requests; log_diagnostic("request.completed", { {"method", handoff.request.method, false}, {"target", observability::sanitized_http_target(handoff.request.target), false}, {"status", std::to_string(final_result.response.status), false}, {"response_bytes", std::to_string(response_body_bytes(final_result.response)), false} }); auto const decision = decide_connection(handoff.ctx, connection, handoff.version, handoff.connection_header); auto stream = make_connection_stream(connection); auto const written = stream != nullptr && write_response(*stream, final_result.response, decision, keep_alive_policy_for(handoff.ctx).idle_timeout_seconds); stream.reset(); if (written && decision == http::ConnectionPreference::keep_alive && handoff.ctx.dispatcher != nullptr) { // Back to the dispatcher for the next request: the next round runs // on a main-pool worker (pool separation preserved). handoff.ctx.dispatcher->park_for_next_request(std::move(handoff.connection)); return; } handoff.connection.reset(); } // A sync-pool task: the first pass of a new long-poll, or the resumption of a woken or expired parked one. auto run_sync_poll(std::unique_ptr poll, sync::WakeReason reason) -> void { auto answered = std::optional{}; auto step = PollStep::answer; try { step = advance_sync_poll(poll, reason, answered); } catch (...) { log_swallowed_exception("sync_pool_dispatch"); } if (poll == nullptr || step == PollStep::parked) { return; } if (step == PollStep::client_gone) { // Closed before we could respond: close without logging a completed request. return; } auto& handoff = poll->handoff; auto const final_result = answered.has_value() ? std::move(*answered) : rerun_waiting_sync(handoff.ctx.runtime, handoff.request, false); finish_sync_handoff(handoff, final_result); } } // namespace namespace detail { // The registry's resume callback: runs on the registry thread, so it only hands the poll to the sync pool. A // pool that is stopping or full drops it, which closes the connection. auto resume_parked_poll(net::ThreadPool& pool, std::unique_ptr base, sync::WakeReason reason) -> void { auto typed = std::unique_ptr{static_cast(base.release())}; // Pool tasks are copyable; the holder carries the unique pointer to exactly one run (ADR-0077 rule 7). auto holder = std::make_shared>( // SHARED_PTR: reviewed — copyable pool task std::move(typed)); if (!pool.submit([holder, reason] { run_sync_poll(std::move(*holder), reason); })) { log_diagnostic("sync.resume_refused", {}); } } } // namespace detail namespace { // A remote media request handed to the media fetch pool (ADR-0121). It owns // the connection from the moment it is submitted, and its admission slot // until it ends; everything it needs is held by value, since the round that // created it may be gone by the time it runs. struct MediaFetchHandoff final { ConnectionOwner connection; ConnectionContext ctx; LocalHttpRequest request; http::HttpVersion version; std::string connection_header; std::string origin; http::InFlightBudget::Slot slot; }; auto run_media_fetch_handoff(MediaFetchHandoff& handoff) -> void { auto& connection = http_connection(handoff.connection); auto* const media_fetch_pool = handoff.ctx.media_fetch_pool; auto result = DispatchResult{}; if (media_fetch_pool == nullptr || !media_fetch_pool->running()) { // A stopping pool still runs what is queued. Starting a fetch now // would hold shutdown for the fetch's whole deadline. result.response = LocalHttpResponse{503U, matrix_error("M_UNKNOWN", "server is shutting down"), transport_cors_headers(handoff.ctx, handoff.origin)}; } else { // The client may have gone while the request was queued; then there // is nobody to fetch for. recv returns 0 or an error other than // EAGAIN for a closed peer, and data or EAGAIN for a live one. auto peek_buf = std::array{}; auto const peeked = ::recv(connection.fd(), peek_buf.data(), 1U, MSG_PEEK | MSG_DONTWAIT); if (peeked == 0 || (peeked < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) { log_diagnostic("media_fetch.client_gone", { {"target", observability::sanitized_http_target(handoff.request.target), false} }); handoff.connection.reset(); return; } auto threw = false; try { // Run again in admitted mode: the fetch skips the main-pool // budget, which this handoff's slot replaces, and the request // was already counted by the rate limiter. result = handle_client_server_request( handoff.ctx.runtime, handoff.request, ClientServerDispatchOptions{.can_wait = false, .remote_media = RemoteMediaFetchMode::admitted, .rate_limit_admitted = true}); } catch (...) { log_swallowed_exception("media_fetch_dispatch"); threw = true; } if (threw || result.status != DispatchResult::Status::complete) { result.response = LocalHttpResponse{500U, matrix_error("M_UNKNOWN", "remote media fetch failed"), transport_cors_headers(handoff.ctx, handoff.origin)}; } } ++handoff.ctx.stats.completed_requests; log_diagnostic("request.completed", { {"method", handoff.request.method, false}, {"target", observability::sanitized_http_target(handoff.request.target), false}, {"status", std::to_string(result.response.status), false}, {"response_bytes", std::to_string(response_body_bytes(result.response)), false} }); auto const decision = decide_connection(handoff.ctx, connection, handoff.version, handoff.connection_header); auto stream = make_connection_stream(connection); auto const written = stream != nullptr && write_response(*stream, result.response, decision, keep_alive_policy_for(handoff.ctx).idle_timeout_seconds); stream.reset(); if (written && decision == http::ConnectionPreference::keep_alive && handoff.ctx.dispatcher != nullptr) { // Back to the dispatcher: the next request runs on a main-pool // worker, as after a sync handoff. handoff.ctx.dispatcher->park_for_next_request(std::move(handoff.connection)); return; } handoff.connection.reset(); } } // namespace namespace detail { // Serves exactly one request round on `connection`: read the head, drain // the body exactly, route, write one response. Pipelined bytes past this // request's body stay in connection.leftover for the next round. The // connection's first round that gets zero bytes is a 408; a later one is a // client closing an idle kept-alive connection and is closed silently. // // Returns close_connection / continue_keep_alive, or transferred when a // long-poll was handed to the sync pool, which then owns the connection // (`owner` is empty on return). [[nodiscard]] auto serve_request_round(ConnectionContext& ctx, HttpConnection& connection, ConnectionOwner& owner) -> RoundOutcome { auto stream = make_connection_stream(connection); if (stream == nullptr) { return RoundOutcome::close_connection; } auto const head_limits = http_request_limits_for(ctx.runtime, ctx.dispatch_mode, {}, {}); auto const head_cap = header_size_cap(head_limits); auto const first_request = std::exchange(connection.first_request, false); auto [buffer, head_end] = read_request_head(*stream, std::move(connection.leftover), head_cap); // std::move leaves it valid-but-unspecified; reset it. It is re-assigned // below with this round's surplus bytes on keep-alive paths. connection.leftover.clear(); if (head_end == std::string::npos) { if (!first_request && buffer.empty()) { // Client closed an idle kept-alive connection. The previous // response was fully written, so nothing is lost; close // quietly instead of emitting 408 noise. return RoundOutcome::close_connection; } ++ctx.stats.rejected_requests; if (buffer.size() >= head_cap) { log_diagnostic("request.rejected", { {"status", "413", false}, {"received_bytes", std::to_string(buffer.size()), false}, {"limit_bytes", std::to_string(head_cap), false}, {"reason", "request head too large", false} }); write_error_response(*stream, 413U, "request head too large", transport_cors_headers(ctx, origin_from_raw_head(buffer))); } else { log_diagnostic("request.rejected", { {"status", "408", false}, {"received_bytes", std::to_string(buffer.size()), false}, {"reason", "request head incomplete or timed out", false} }); write_error_response(*stream, 408U, "request head incomplete or timed out", transport_cors_headers(ctx, origin_from_raw_head(buffer))); } return RoundOutcome::close_connection; } auto const parse = http::parse_request_head(std::string_view{buffer.data(), head_end}, head_limits); if (parse.error != http::RequestErrorCode::none) { ++ctx.stats.rejected_requests; auto reason = std::string{"request rejected: "}; reason.append(http::request_error_name(parse.error)); log_diagnostic("request.rejected", { {"status", std::to_string(http::request_error_status(parse.error)), false}, {"reason", http::request_error_name(parse.error), false} }); write_error_response( *stream, http::request_error_status(parse.error), reason, transport_cors_headers(ctx, origin_from_raw_head(std::string_view{buffer.data(), head_end}))); return RoundOutcome::close_connection; } auto const connection_header = find_header_value(parse.request, "connection"); auto const request_limits = http_request_limits_for(ctx.runtime, ctx.dispatch_mode, parse.request.method, parse.request.target); auto body_tail = std::string{buffer.substr(head_end)}; auto body = std::string{}; if (parse.request.has_content_length && parse.request.content_length > 0U) { auto const expected_body_bytes = parse.request.content_length; auto effective_cap = body_size_cap(request_limits); // HTTP-1 / HTTP-6: the media upload routes may carry up to // max_upload_size, but only for a request whose head already // authenticates. Anything else is answered from the head alone, // before a byte of a large body is read, and the connection closed // (its unread body cannot be skipped). if (ctx.dispatch_mode == HttpDispatchMode::client_server && is_media_upload_target(parse.request.method, parse.request.target) && expected_body_bytes > effective_cap) { auto const head_only = build_local_request(parse.request, {}, ctx.peer_addr); if (auto const refusal = media_upload_authentication_refusal(ctx.runtime, head_only); refusal.has_value()) { ++ctx.stats.rejected_requests; log_diagnostic("request.rejected", { {"method", parse.request.method, false}, {"target", observability::sanitized_http_target(parse.request.target), false}, {"status", std::to_string(refusal->status), false}, {"expected_body_bytes", std::to_string(expected_body_bytes), false}, {"reason", "upload body refused before authentication", false} }); std::ignore = send_all(*stream, format_for_wire(refusal->status, refusal->body, refusal->headers).text); return RoundOutcome::close_connection; } effective_cap = max_upload_bytes(ctx.runtime); } if (expected_body_bytes > effective_cap) { ++ctx.stats.rejected_requests; log_diagnostic("request.rejected", { {"method", parse.request.method, false}, {"target", observability::sanitized_http_target(parse.request.target), false}, {"status", "413", false}, {"expected_body_bytes", std::to_string(expected_body_bytes), false}, {"limit_bytes", std::to_string(effective_cap), false}, {"reason", "request body too large", false} }); // Matrix spec §10.5: every response MUST carry CORS headers or // browsers surface the 413 as a CORS error instead of the real one. auto const cors_hdrs = transport_cors_headers(ctx, find_header_value(parse.request, "origin")); auto const rejection = format_for_wire(413U, R"({"errcode":"M_TOO_LARGE","error":"request body too large"})", cors_hdrs); std::ignore = send_all(*stream, rejection.text); return RoundOutcome::close_connection; } // Drain the body exactly: read precisely Content-Length bytes and // keep any surplus (a pipelined next request) for the next round. auto const expected = static_cast(expected_body_bytes); auto body_result = read_remaining_body(*stream, std::move(body_tail), expected, effective_cap, ctx.tuning); if (!body_result.complete) { ++ctx.stats.rejected_requests; log_diagnostic("request.rejected", { {"method", parse.request.method, false}, {"target", observability::sanitized_http_target(parse.request.target), false}, {"status", "408", false}, {"expected_body_bytes", std::to_string(expected), false}, {"received_body_bytes", std::to_string(body_result.body.size()), false}, {"reason", "request body incomplete or timed out", false} }); write_error_response(*stream, 408U, "request body incomplete or timed out", transport_cors_headers(ctx, find_header_value(parse.request, "origin"))); return RoundOutcome::close_connection; } body = std::move(body_result.body); connection.leftover = std::move(body_result.leftover); } else { // No body declared. Chunked transfer coding is rejected by the // parser, so a body can only arrive via Content-Length; every // byte past the head therefore belongs to the next request. connection.leftover = std::move(body_tail); } auto const local_request = build_local_request(parse.request, std::move(body), ctx.peer_addr); log_diagnostic("request.dispatch", { {"method", local_request.method, false}, {"target", observability::sanitized_http_target(local_request.target), false}, {"body_bytes", std::to_string(local_request.body.size()), false}, {"has_access_token", local_request.access_token.empty() ? "false" : "true", false} }); // The health probe is answered here, before the dispatcher (ADR-0479): it reads one atomic flag (is the // dispatcher still running) and takes neither runtime.mutex nor any other lock, so a request that holds // the runtime lock for a long time cannot make a probe wait. It is not rate-limited and needs no token. auto result = is_health_probe(local_request) ? DispatchResult{DispatchResult::Status::complete, // A connection served without a dispatcher (serve_one_http_connection) has none to // ask, and is by definition being served. health_probe_response(ctx.dispatcher == nullptr || ctx.dispatcher->running()), {}} : route_request(ctx.runtime, local_request, ctx.dispatch_mode, ctx.media_fetch_pool != nullptr ? RemoteMediaFetchMode::defer : RemoteMediaFetchMode::inline_fetch); if (result.status == DispatchResult::Status::needs_media_fetch) { // ADR-0121: the request needs a fetch from a remote server. Hand it // to the media fetch pool so no main-pool worker waits on that // server. Admit before submitting: queued fetches count too, and one // client must not occupy the pool. auto const origin = find_header_value(parse.request, "origin"); auto const& server_settings = ctx.runtime.homeserver.config.server(); auto const caps = media_fetch_admission_caps(server_settings.http); auto slot = ctx.runtime.media_fetch_budget->try_acquire( rate_limit_client_key(local_request, server_settings), caps.global, caps.per_client); if (!slot.has_value()) { log_diagnostic("media_fetch.over_budget", { {"target", observability::sanitized_http_target(local_request.target), false} }); write_error_response( *stream, 429U, matrix_error("M_LIMIT_EXCEEDED", "too many concurrent remote media fetches", 1000U), transport_cors_headers(ctx, origin)); return RoundOutcome::close_connection; } auto handoff = std::make_shared( MediaFetchHandoff{// SHARED_PTR: reviewed — copyable pool task std::move(owner), ctx, local_request, parse.request.version, connection_header, std::string{origin}, std::move(*slot)}); if (ctx.media_fetch_pool != nullptr && ctx.media_fetch_pool->submit([handoff] { run_media_fetch_handoff(*handoff); })) { return RoundOutcome::transferred; } // A refused handoff is backpressure, never a reason to fetch on a // main-pool worker. Take ownership back before answering; the slot // is released with the handoff. owner = std::move(handoff->connection); handoff.reset(); write_error_response(*stream, 429U, matrix_error("M_LIMIT_EXCEEDED", "media fetch pool unavailable", 1000U), transport_cors_headers(ctx, origin)); return RoundOutcome::close_connection; } if (result.status == DispatchResult::Status::needs_wait) { auto* const notifier = ctx.runtime.sync_notifier.get(); if (notifier == nullptr) { write_error_response(*stream, 503U, matrix_error("M_UNKNOWN", "sync notifier unavailable"), transport_cors_headers(ctx, find_header_value(parse.request, "origin"))); return RoundOutcome::close_connection; } // Admit before submitting: queued waits count too. One account must // not occupy the sync pool, even across tokens, devices and protocols. auto const& sync_settings = ctx.runtime.homeserver.config.server().http; auto const sync_caps = sync_admission_caps( sync_settings, ctx.sync_pool == nullptr ? std::size_t{0U} : ctx.sync_pool->worker_count()); auto user_slot = ctx.runtime.sync_user_budget->try_acquire(result.wait.user_id, sync_caps.global, sync_caps.per_user); auto const device_key = std::to_string(result.wait.user_id.size()) + ":" + result.wait.user_id + result.wait.device_id; auto device_slot = user_slot.has_value() ? ctx.runtime.sync_device_budget->try_acquire(device_key, sync_caps.global, sync_caps.per_device) : std::nullopt; if (result.wait.user_id.empty() || !user_slot.has_value() || !device_slot.has_value()) { write_error_response(*stream, 429U, matrix_error("M_LIMIT_EXCEEDED", "too many concurrent sync waits", 1000U), transport_cors_headers(ctx, find_header_value(parse.request, "origin"))); return RoundOutcome::close_connection; } if (ctx.sync_pool != nullptr) { // Hand off to the dedicated sync pool: this main-pool worker is // freed at once, and the sync task owns the connection from // here (answering it and closing it or handing it back to the // dispatcher, or parking it in the notifier's registry, ADR-0569). auto poll = std::make_shared>( // SHARED_PTR: reviewed — copyable pool task std::make_unique(SyncHandoff{ std::move(owner), ctx, local_request, result.wait, *notifier, parse.request.version, connection_header, std::move(*user_slot), std::move(*device_slot)})); if (ctx.sync_pool->submit([poll] { run_sync_poll(std::move(*poll), sync::WakeReason::published); })) { return RoundOutcome::transferred; } // A refused handoff is backpressure, never a reason to wait on // a main request worker. Take ownership back before answering. owner = std::move((*poll)->handoff.connection); write_error_response(*stream, 429U, matrix_error("M_LIMIT_EXCEEDED", "sync pool unavailable", 1000U), transport_cors_headers(ctx, find_header_value(parse.request, "origin"))); return RoundOutcome::close_connection; } // No sync pool (embedded callers and tests): wait until new // events arrive or the timeout expires. The re-wait loop mirrors // the sync-pool path. { auto const wait = result.wait; auto dispatched = false; try { dispatched = wait_for_sync(*notifier, ctx.runtime, local_request, wait, result); } catch (...) { log_swallowed_exception("serve_request_round_sync_wait"); } if (!dispatched) { result = rerun_waiting_sync(ctx.runtime, local_request, false); } } } ++ctx.stats.completed_requests; log_diagnostic("request.completed", { {"method", local_request.method, false}, {"target", observability::sanitized_http_target(local_request.target), false}, {"status", std::to_string(result.response.status), false}, {"response_bytes", std::to_string(response_body_bytes(result.response)), false} }); auto const decision = decide_connection(ctx, connection, parse.request.version, connection_header); if (!write_response(*stream, result.response, decision, keep_alive_policy_for(ctx).idle_timeout_seconds)) { return RoundOutcome::close_connection; } return decision == http::ConnectionPreference::keep_alive ? RoundOutcome::continue_keep_alive : RoundOutcome::close_connection; } } // namespace detail auto dispatch_local_http_request(ClientServerRuntime& runtime, LocalHttpRequest const& request, HttpDispatchMode mode) -> LocalHttpResponse { // This public API preserves its original blocking behaviour for backward // compatibility (tests, one-off callers). The server's hot path uses // route_request() + serve_connection() with a dedicated sync_pool instead. auto result = route_request(runtime, request, mode); if (result.status == DispatchResult::Status::needs_wait) { auto* notifier = runtime.sync_notifier.get(); if (notifier == nullptr) { return {503U, matrix_error("M_UNKNOWN", "sync notifier unavailable")}; } // Re-wait loop: after each notifier fire, call the handler with can_wait=true // so sliding_sync_json can return needs_wait again when the wakeup was caused // by an event not relevant to this connection (e.g. another user uploading // device keys). The handler advances wait.since_sync_stream_id past the // irrelevant bump, preventing an immediate re-fire. auto const wait = result.wait; auto dispatched = false; try { dispatched = wait_for_sync(*notifier, runtime, request, wait, result); } catch (...) { log_swallowed_exception("dispatch_local_http_request"); } if (!dispatched) { result = rerun_waiting_sync(runtime, request, false); } } return result.response; } auto serve_one_http_connection(int client_fd, ClientServerRuntime& runtime, HttpServeStats& stats, HttpDispatchMode dispatch_mode, net::ThreadPool* sync_pool, std::string_view peer_addr, net::ThreadPool* media_fetch_pool) -> bool { // Direct callers (tests, one-off embeds) keep the historical one-request- // per-call contract: with no dispatcher there is nowhere to park the // connection, so keep-alive is off (see keep_alive_policy_for) and this // serves a single round. The caller owns the descriptor unless it was // transferred to the sync or media fetch pool, which then closes it. auto owner = ConnectionOwner{std::make_unique(core::SocketHandle{client_fd}, dispatch_mode, std::string{peer_addr}, std::string{})}; auto& connection = http_connection(owner); auto ctx = ConnectionContext{ runtime, stats, sync_pool, media_fetch_pool, nullptr, HttpServeTuning{}, dispatch_mode, std::string{peer_addr}}; if (serve_request_round(ctx, connection, owner) == RoundOutcome::transferred) { return true; } // Not ours to close: give the descriptor back to the caller untouched. std::ignore = connection.socket.release(); return false; } namespace { // Accepts connections until `shutdown` fires, the acceptor fails, or the // dispatcher stops, and parks each admitted one on the dispatcher. No // worker is involved: a connection reaches the pool only once it is // readable. auto accept_until_shutdown(net::TcpAcceptor& acceptor, HttpConnectionDispatcher::Impl& dispatcher, net::ShutdownSignal& shutdown, HttpDispatchMode dispatch_mode, std::optional> tls_context) -> void { auto const event_prefix = std::string{tls_context.has_value() ? "tls.connection." : "connection."}; while (!shutdown.fired() && acceptor.valid() && dispatcher.running()) { auto entries = std::array{}; entries[0].fd = acceptor.fd(); entries[0].events = POLLIN; entries[1].fd = shutdown.read_fd(); entries[1].events = POLLIN; auto const poll_result = ::poll(entries.data(), entries.size(), -1); if (poll_result < 0) { if (errno == EINTR) { continue; } return; } if ((entries[1].revents & POLLIN) != 0 || shutdown.fired()) { return; } if ((entries[0].revents & POLLIN) == 0) { continue; } sockaddr_storage peer_sa{}; socklen_t peer_len = sizeof(peer_sa); // SOCK_CLOEXEC: accepted client sockets must not leak into worker // subprocesses spawned via posix_spawn/fork() (federation workers, // thumbnail worker) while a connection is still open. Matches the // SOCK_CLOEXEC listening-socket pattern in net/TcpAcceptor.cpp. // // SOCK_NONBLOCK: the socket is non-blocking from the instant it // exists, as ADR-0054 requires for the life of the connection; the // TLS handshake keeps it that way. auto raw_client = ::accept4(acceptor.fd(), reinterpret_cast(&peer_sa), &peer_len, SOCK_CLOEXEC | SOCK_NONBLOCK); if (raw_client < 0) { if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) { continue; } // Transient resource exhaustion — retry after a brief pause // rather than permanently killing the listener thread. if (errno == EMFILE || errno == ENFILE || errno == ENOBUFS || errno == ENOMEM) { log_diagnostic(event_prefix + "accept_retry", { {"errno", std::to_string(errno), false} }); ::usleep(100000); continue; } log_diagnostic(event_prefix + "accept_failed", { {"errno", std::to_string(errno), false} }); return; } auto client = core::SocketHandle{raw_client}; auto peer_addr = peer_addr_to_string(peer_sa); // ADR-0072: refuse before reading a byte (or starting a TLS // handshake) once this client holds its share of connections; // ~SocketHandle closes the refused descriptor. auto admission = admit_connection(dispatcher.runtime, peer_addr); if (!admission.admitted) { log_diagnostic( event_prefix + "per_ip_cap_reached", { {"cap", std::to_string(dispatcher.runtime.homeserver.config.server().http.max_connections_per_ip), false} }); continue; } dispatcher.accept(std::move(client), std::move(peer_addr), dispatch_mode, std::move(admission), tls_context); } } } // namespace auto serve_http(net::TcpAcceptor& acceptor, HttpConnectionDispatcher& dispatcher, net::ShutdownSignal& shutdown, HttpDispatchMode dispatch_mode) -> void { accept_until_shutdown(acceptor, dispatcher.impl(), shutdown, dispatch_mode, std::nullopt); } auto serve_tls_http(TlsServerContext& tls_context, net::TcpAcceptor& acceptor, HttpConnectionDispatcher& dispatcher, net::ShutdownSignal& shutdown, HttpDispatchMode dispatch_mode) -> void { accept_until_shutdown(acceptor, dispatcher.impl(), shutdown, dispatch_mode, std::ref(tls_context)); } auto serve_http(net::TcpAcceptor& acceptor, ClientServerRuntime& runtime, net::ShutdownSignal& shutdown, HttpServeStats& stats, HttpDispatchMode dispatch_mode, net::ThreadPool& pool, net::ThreadPool* sync_pool, HttpServeTuning tuning) -> void { auto dispatcher = HttpConnectionDispatcher{runtime, stats, pool, sync_pool, tuning}; if (!dispatcher.start()) { log_diagnostic("dispatcher.start_failed", {}, observability::LogEventSeverity::error); return; } serve_http(acceptor, dispatcher, shutdown, dispatch_mode); dispatcher.request_stop(); } auto serve_tls_http(TlsServerContext& tls_context, net::TcpAcceptor& acceptor, ClientServerRuntime& runtime, net::ShutdownSignal& shutdown, HttpServeStats& stats, HttpDispatchMode dispatch_mode, net::ThreadPool& pool, net::ThreadPool* sync_pool, HttpServeTuning tuning) -> void { auto dispatcher = HttpConnectionDispatcher{runtime, stats, pool, sync_pool, tuning}; if (!dispatcher.start()) { log_diagnostic("dispatcher.start_failed", {}, observability::LogEventSeverity::error); return; } serve_tls_http(tls_context, acceptor, dispatcher, shutdown, dispatch_mode); dispatcher.request_stop(); } } // namespace merovingian::homeserver