diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index d3b8f3d667..035785fecf 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -245,7 +245,9 @@ jobs: uses: actions/checkout@v7 if: inputs.run-tests with: - repository: 'PokemonAutomation/CommandLineTests' + # The fork's fixtures: upstream's plus the SystemKeyboardDetector screenshots. + repository: 'dayfine/CommandLineTests' + ref: '5de4ff774f9141d904c4b5c557fa7b9dc85eaef1' path: 'CommandLineTests' # The unit tests assume the downloadable resources they need are already downloaded diff --git a/.github/workflows/lab-instance-tools.yml b/.github/workflows/lab-instance-tools.yml index ebf48e6600..55e47d1eb4 100644 --- a/.github/workflows/lab-instance-tools.yml +++ b/.github/workflows/lab-instance-tools.yml @@ -19,3 +19,4 @@ jobs: with: python-version: '3.12' - run: python3 -m unittest discover -s devtools/lab -p 'test_lab_instance.py' -v + - run: python3 -m unittest discover -s devtools/lab -p 'test_cfr_steps_to_story.py' -v diff --git a/Common/Cpp/HttpServer/HttpServer.cpp b/Common/Cpp/HttpServer/HttpServer.cpp new file mode 100644 index 0000000000..b4c97cbab1 --- /dev/null +++ b/Common/Cpp/HttpServer/HttpServer.cpp @@ -0,0 +1,821 @@ +/* HTTP Server + * + * From: https://github.com/PokemonAutomation/ + * + * Implementation notes: + * - The socket's receive/disconnect callbacks only append data to the + * per-connection buffer and flip flags. One "connection task" per + * connection (from the thread pool) does all parsing and writing, so + * the handler may run for a long time without stalling the socket's + * receive loop. + * - Every write goes through "AbstractServerSocket::send()" with the + * connection's socket id (captured at accept time), so a response + * that outlives its connection - the peer disconnected and the next + * client was accepted in the meantime - is refused by the socket + * instead of reaching the new client's stream. + * - "Expect: 100-continue" is answered as soon as the headers are + * validated, while the body is still pending (a waiting client is + * blocked on that interim response). + * - Task handles live in "m_tasks" under a dedicated "m_task_lock" + * (the socket library's "m_task_lock" pattern): destroying an + * "AsyncTask" handle blocks until that task finishes, and the task's + * final cleanup takes "m_lock", so a handle must never be destroyed + * while holding "m_lock". "on_connect()" may therefore find the + * previous connection's task still finishing (for example, still in a + * long handler call); its handle is kept and reaped later. + * - "stop()" marks the active connection dead before it waits for the + * in-flight task: the socket suppresses its disconnect callback for a + * close_connection() close, so without the mark a handler polling + * "connection_alive()" would never see the shutdown. "stop()" then + * moves the socket out under "m_lock" and destroys it after releasing + * the lock: "~ServerSocket" joins the socket's worker threads, and + * their callbacks take "m_lock". + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/ThreadPool.h" +#include "Common/Cpp/HttpServer/HttpServer.h" +#include "Common/Cpp/Sockets/ServerSocket.h" + +namespace PokemonAutomation{ + +namespace{ + + +constexpr size_t MAX_REQUEST_LINE_BYTES = 8192; +constexpr size_t MAX_HEADER_SECTION_BYTES = 65536; +constexpr size_t MAX_HEADER_COUNT = 100; +constexpr size_t MAX_BODY_BYTES = 1u << 20; // 1 MiB +// The total per-connection receive buffer; enforced when data is +// appended, not at parse time. +constexpr size_t MAX_BUFFER_BYTES = 2u << 20; + +// A stalled peer is declared dead after this; loopback writes of a few MB +// finish in milliseconds, so this is very generous. +constexpr std::chrono::milliseconds WRITE_TIMEOUT{30000}; + + +bool is_token_char(char c){ + return std::isalnum((unsigned char)c) != 0 + || std::strchr("-!#$%&'*+.^_`|~", c) != nullptr; +} + + +std::string to_lower(std::string value){ + std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c){ + return (char)std::tolower(c); + }); + return value; +} + + +// Strips the leading and trailing spaces and tabs (OWS). +std::string trim_ows(std::string value){ + static const char OWS[] = " \t"; + const auto begin = value.find_first_not_of(OWS); + if (begin == std::string::npos){ + return ""; + } + const auto end = value.find_last_not_of(OWS); + return value.substr(begin, end - begin + 1); +} + + +// The concrete HandlerContext: "connection_alive()" is simply the +// connection's dead flag. +struct HandlerContextImpl : AbstractHttpServer::HandlerContext{ + explicit HandlerContextImpl(const std::atomic& dead) + : m_dead(dead) + {} + + virtual bool connection_alive() const override{ + return !m_dead.load(std::memory_order_acquire); + } + +private: + const std::atomic& m_dead; +}; + + + +} // anonymous namespace + + + +const char* HttpServer::status_reason(int status){ + switch (status){ + 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 411: + return "Length Required"; + case 413: + return "Payload Too Large"; + case 426: + return "Upgrade Required"; + case 500: + return "Internal Server Error"; + case 501: + return "Not Implemented"; + case 503: + return "Service Unavailable"; + case 505: + return "Version Not Supported"; + default: + return "Unknown Status"; + } +} + + +std::string HttpServer::format_response(const Response& response, bool keep_alive){ + std::string out; + out += "HTTP/1.1 "; + out += std::to_string(response.status); + out += " "; + const char* reason = response.reason.empty() ? status_reason(response.status) : response.reason.c_str(); + out += reason; + out += "\r\n"; + + for (const auto& header : response.headers){ + // The server sets both of these below. + if (to_lower(header.first) == "content-length" || + to_lower(header.first) == "connection" + ){ + continue; + } + out += header.first; + out += ": "; + out += header.second; + out += "\r\n"; + } + + out += "Content-Length: "; + out += std::to_string(response.body.size()); + out += "\r\n"; + out += "Connection: "; + out += keep_alive ? "keep-alive" : "close"; + out += "\r\n\r\n"; + out += response.body; + + return out; +} + + + +HttpServer::HttpServer(ThreadPool& thread_pool) + : m_thread_pool(thread_pool) +{} + + +HttpServer::~HttpServer(){ + stop(); +} + + +void HttpServer::start(const std::string& address, uint16_t port, Handler handler){ + AbstractServerSocket* socket = nullptr; + { + std::lock_guard lg(m_lock); + if (m_socket != nullptr){ + return; + } + m_handler = std::move(handler); + m_stop_requested.store(false, std::memory_order_release); + m_socket = std::make_unique(m_thread_pool); + // Register before start(): the accept thread is dispatched by + // start() and may report on_listen_finished() as soon as it runs. + m_socket->add_listener(*this); + socket = m_socket.get(); + } + + // Asynchronous: on_listen_finished() fires on a thread from the pool. + socket->start(address, port); +} + + +void HttpServer::stop(){ + m_stop_requested.store(true, std::memory_order_release); + + AbstractServerSocket* socket = nullptr; + { + std::lock_guard lg(m_lock); + socket = m_socket.get(); + } + if (socket == nullptr){ + return; + } + + // Mark the active connection dead: the socket suppresses its + // disconnect callback for a close_connection() close, so without + // this a handler polling connection_alive() would never see the + // shutdown, and the wait for it below would never end. + { + std::lock_guard lg(m_lock); + if (m_connection != nullptr){ + m_connection->dead.store(true, std::memory_order_release); + m_connection->cv.notify_all(); + } + } + + // Kill the active connection, if any: it cancels in-flight writes and + // makes the socket's connection thread exit. The socket keeps + // listening until it is destroyed below, so it may accept a few more + // clients in the meantime; on_connect() sees m_stop_requested and + // closes them without dispatching a connection task. + socket->close_connection(); + + // Wait for the in-flight connection tasks. The handles are moved out + // under m_task_lock (never destroyed while holding m_lock: a task's + // final cleanup takes m_lock, and destroying a handle blocks until + // the task finishes). Loop, because a task may have been dispatched + // between the previous ones being joined and the socket being + // destroyed. + while (true){ + std::vector tasks; + { + std::lock_guard lg(m_task_lock); + tasks.swap(m_tasks); + } + if (tasks.empty()){ + break; + } + for (auto& task : tasks){ + task.wait_and_ignore_exceptions(); + } + } + + // Take the socket out under m_lock and destroy it after releasing + // the lock: "~ServerSocket" joins the socket's worker threads, and + // their callbacks (on_connect and friends) take m_lock. + std::unique_ptr owned; + { + std::lock_guard lg(m_lock); + owned = std::move(m_socket); + m_connection = nullptr; + m_handler = Handler(); + } +} + + +bool HttpServer::is_running() const{ + std::lock_guard lg(m_lock); + return (m_socket != nullptr); +} + + + +void HttpServer::on_listen_finished(const std::string& error_message){ + m_listeners.run_method(&Listener::on_listen_finished, error_message); +} + + +void HttpServer::on_connect(){ + AbstractServerSocket* socket = nullptr; + std::shared_ptr conn; + { + std::lock_guard lg(m_lock); + socket = m_socket.get(); + if (socket != nullptr && + !m_stop_requested.load(std::memory_order_acquire) + ){ + conn = std::make_shared(); + // The previous socket connection is over (the socket only + // accepts a new client once the previous one is gone), but + // its task may still be finishing (for example, still inside + // a long handler call), and the socket's on_disconnect + // callback for it may not have run yet: it runs after the + // socket has already moved back to listening. Mark it dead + // now, before the new connection takes over the socket's + // active fd, so the old task discards its response instead + // of delivering it to the new client. + if (m_connection != nullptr){ + m_connection->dead.store(true, std::memory_order_release); + m_connection->cv.notify_all(); + } + m_connection = conn; + // The token of the connection this one will serve; send() + // refuses to write through a socket that has moved on. + conn->socket_id = socket->connection_id(); + } + } + if (conn == nullptr){ + // Stopping (or the socket is gone): close the connection without + // a connection task. + if (socket != nullptr){ + socket->close_connection(); + } + }else{ + // Dispatch outside m_lock: the task's final cleanup takes + // m_lock, and so does stop(). The task handles live in m_tasks + // under a dedicated m_task_lock (the socket library's + // m_task_lock pattern): destroying an AsyncTask handle blocks + // until its task finishes, so a handle must never be destroyed + // while holding m_lock. + try{ + AsyncTask task = m_thread_pool.dispatch( + [this, conn, socket]{ + connection_task(conn, socket); + } + ); + std::lock_guard lg(m_task_lock); + // Reap finished handles (destroying one that is already + // finished is a no-op). Keep unfinished ones: the + // previous connection's task may still be finishing up + // (for example, still inside a long handler call) by the + // time this connection is accepted; it holds only its + // own (dead) connection. + m_tasks.erase( + std::remove_if(m_tasks.begin(), m_tasks.end(), [](const AsyncTask& task){ + return task.is_finished(); + }), + m_tasks.end() + ); + m_tasks.push_back(std::move(task)); + }catch (...){ + // The task could not be started: drop the connection and + // keep listening. + { + std::lock_guard lg(m_lock); + if (m_connection.get() == conn.get()){ + m_connection = nullptr; + } + } + socket->close_connection(); + } + } + m_listeners.run_method(&Listener::on_connect); +} + + +void HttpServer::on_connect_rejected(){ + m_listeners.run_method(&Listener::on_connect_rejected); +} + + +void HttpServer::on_receive_data(const void* data, size_t bytes){ + std::shared_ptr conn; + AbstractServerSocket* socket = nullptr; + { + std::lock_guard lg(m_lock); + conn = m_connection; + socket = m_socket.get(); + } + if (conn == nullptr){ + return; + } + bool exceeded = false; + { + std::lock_guard lg(conn->lock); + exceeded = conn->buffer.size() + bytes > MAX_BUFFER_BYTES; + if (!exceeded){ + const char* ptr = (const char*)data; + conn->buffer.append(ptr, bytes); + } + } + conn->cv.notify_all(); + if (exceeded && socket != nullptr){ + // The stream is longer than we are willing to buffer. It is + // likely in the middle of a request, so there is no reliable + // response left to send: just end the connection. ("socket" can + // be null only while stop() is tearing the socket down, in which + // case there is no connection task left to wake up.) + end_connection(conn, socket); + } +} + + +void HttpServer::on_disconnect(const std::string& error_message){ + std::shared_ptr conn; + { + std::lock_guard lg(m_lock); + // The socket may already be serving the next client by the time + // this callback runs: the socket's connection thread sets the + // state back to LISTENING before it reports the disconnect, so a + // fast reconnect can be accepted in between. In that case this + // disconnect is about the previous connection, which on_connect() + // has already marked dead; the current one belongs to the new + // client and must not be killed. + if (m_socket == nullptr || + m_socket->state() != AbstractServerSocket::State::CONNECTED + ){ + conn = m_connection; + } + } + if (conn != nullptr){ + conn->dead.store(true, std::memory_order_release); + conn->cv.notify_all(); + } + m_listeners.run_method(&Listener::on_disconnect, error_message); +} + + + +void HttpServer::connection_task( + const std::shared_ptr& conn, + AbstractServerSocket* socket +){ + // The handler may be replaced or cleared by start()/stop() while this + // task is waiting; a copy taken under m_lock is stable for the task's + // whole lifetime, because stop() waits for the task before clearing it. + Handler handler; + { + std::lock_guard lg(m_lock); + handler = m_handler; + } + + // "Expect: 100-continue" is answered at most once, and only while + // the body is still pending. + bool sent_continue = false; + + while (true){ + if (m_stop_requested.load(std::memory_order_acquire) || + conn->dead.load(std::memory_order_acquire) + ){ + break; + } + + ParsedRequest parsed; + size_t buffer_size; + { + std::lock_guard lg(conn->lock); + parsed = try_parse(conn->buffer); + buffer_size = conn->buffer.size(); + } + + if (parsed.state == ParseState::NEED_BODY){ + // The headers are complete and valid, but the body has not + // fully arrived. A client that sent "Expect: 100-continue" is + // still waiting for this before sending the body: answer it + // now, not after the (still missing) body arrives. (If the + // whole request was already buffered, the state is READY and + // the final response alone moves the client on; RFC 9110). + if (parsed.expect_continue && !sent_continue){ + static const char CONTINUE_RESPONSE[] = "HTTP/1.1 100 Continue\r\n\r\n"; + if (!write_raw(conn, socket, CONTINUE_RESPONSE)){ + break; + } + sent_continue = true; + } + } + + if (parsed.state == ParseState::NEED_MORE || + parsed.state == ParseState::NEED_BODY + ){ + // Wait for the rest of this request, a disconnect, or a + // stop. The predicate requires the buffer to have grown past + // what the parse just saw: with a partial request, + // "!buffer.empty()" alone is permanently true and would spin + // this loop at 100% CPU until the request completes. + std::unique_lock lg(conn->lock); + conn->cv.wait_for(lg, std::chrono::milliseconds(10), [this, &conn, buffer_size]{ + return conn->buffer.size() != buffer_size + || conn->dead.load(std::memory_order_relaxed) + || m_stop_requested.load(std::memory_order_relaxed); + }); + continue; + } + + if (parsed.state == ParseState::ERROR_RESPONSE){ + Response response; + response.status = parsed.error_status; + response.headers = std::move(parsed.error_headers); + response.body = parsed.error_reason + "\n"; + write_response(conn, socket, response, false); + end_connection(conn, socket); + break; + } + + // A complete request is ready to be handled. + Response response; + { + HandlerContextImpl context(conn->dead); + try{ + if (handler){ + handler(parsed.request, response, context); + }else{ + response.status = 500; + response.body = "No handler is registered.\n"; + response.connection_close = true; + } + }catch (...){ + response = Response(); + response.status = 500; + response.body = "The handler threw an exception.\n"; + response.connection_close = true; + } + } + + // The connection may have closed or been replaced by a new + // client while the handler was running; discard the response in + // that case. + if (conn->dead.load(std::memory_order_acquire) || + m_stop_requested.load(std::memory_order_acquire) + ){ + break; + } + + const bool keep_alive = parsed.http_1_1 + && !parsed.connection_close_requested + && !response.connection_close; + if (!write_response(conn, socket, response, keep_alive)){ + break; + } + if (!keep_alive){ + end_connection(conn, socket); + break; + } + // Keep-alive: the next request (possibly already buffered) is + // picked up at the top of the loop. + } + + conn->dead.store(true, std::memory_order_release); + { + std::lock_guard lg(m_lock); + if (m_connection.get() == conn.get()){ + m_connection = nullptr; + } + } +} + + +HttpServer::ParsedRequest HttpServer::try_parse(std::string& buffer){ + ParsedRequest result; + + auto error = [&result](int status, const char* reason, std::vector> headers = {}){ + result.state = ParseState::ERROR_RESPONSE; + result.error_status = status; + result.error_reason = reason; + result.error_headers = std::move(headers); + }; + + // The header section ends at the blank line. "header_end" points at + // the "\r\n" that terminates the last header (or the request line + // when there are no headers). + const size_t header_end = buffer.find("\r\n\r\n"); + if (header_end == std::string::npos){ + if (buffer.size() > MAX_HEADER_SECTION_BYTES){ + error(400, "Malformed request."); + } + return result; // NEED_MORE: the headers have not fully arrived yet. + } + // The same limit applies to a complete header section: the + // in-progress check above only fires while the terminator is still + // missing, so a large section that arrives in one piece would + // otherwise sail through. + if (header_end + 4 > MAX_HEADER_SECTION_BYTES){ + error(400, "Malformed request."); + return result; + } + + const size_t line_end = buffer.find("\r\n"); + if (line_end == std::string::npos){ + error(400, "Malformed request."); + return result; + } + if (line_end > MAX_REQUEST_LINE_BYTES){ + error(400, "Request line too long."); + return result; + } + + // "METHOD SP TARGET SP VERSION" + const std::string line = buffer.substr(0, line_end); + const size_t sp1 = line.find(' '); + if (sp1 == std::string::npos || sp1 == 0){ + error(400, "Malformed request."); + return result; + } + std::string method = line.substr(0, sp1); + for (char c : method){ + if (c < 'A' || c > 'Z'){ + error(400, "Malformed request."); + return result; + } + } + const size_t sp2 = line.find(' ', sp1 + 1); + if (sp2 == std::string::npos){ + error(400, "Malformed request."); + return result; + } + std::string target = line.substr(sp1 + 1, sp2 - sp1 - 1); + if (target.empty()){ + error(400, "Malformed request."); + return result; + } + for (char c : target){ + if (c == ' ' || c == '\r' || c == '\n' || c == '\0'){ + error(400, "Malformed request."); + return result; + } + } + const std::string version = line.substr(sp2 + 1); + const bool http_1_1 = (version == "HTTP/1.1"); + const bool http_1_0 = (version == "HTTP/1.0"); + if (!http_1_1 && !http_1_0){ + error(505, "HTTP version not supported."); + return result; + } + + // Headers: [line_end + 2, header_end) + const size_t section_begin = line_end + 2; + std::string section; + if (header_end >= section_begin){ + section = buffer.substr(section_begin, header_end - section_begin); + } + size_t header_count = 0; + size_t pos = 0; + while (pos < section.size()){ + const size_t eol = section.find("\r\n", pos); + const size_t length = (eol == std::string::npos) ? section.size() - pos : eol - pos; + const std::string header_line = section.substr(pos, length); + + if (header_line.empty() || ++header_count > MAX_HEADER_COUNT){ + error(400, "Malformed request."); + return result; + } + + const size_t colon = header_line.find(':'); + if (colon == std::string::npos || colon == 0){ + error(400, "Malformed request."); + return result; + } + std::string name = header_line.substr(0, colon); + for (char c : name){ + if (!is_token_char(c)){ + error(400, "Malformed request."); + return result; + } + } + std::string value = trim_ows(header_line.substr(colon + 1)); + for (char c : value){ + if ((unsigned char)c < 0x20 || (unsigned char)c == 0x7F){ + error(400, "Malformed request."); + return result; + } + } + name = to_lower(std::move(name)); + if (name == "content-length" && result.request.headers.count("content-length") != 0){ + error(400, "Duplicate content-length."); + return result; + } + result.request.headers[std::move(name)] = std::move(value); + + if (eol == std::string::npos){ + break; + } + pos = eol + 2; + } + + // Special headers. + if (result.request.headers.count("transfer-encoding") != 0){ + // "Not Implemented" rather than "Length Required": chunked + // encoding is a (unsupported) representation of the body, not a + // missing length (RFC 9112). + error(501, "Chunked transfer encoding is not supported."); + return result; + } + + uint64_t content_length = 0; + { + const auto content_length_it = result.request.headers.find("content-length"); + if (content_length_it != result.request.headers.end()){ + const std::string& value = content_length_it->second; + if (value.empty() || value.size() > 10){ + error(400, "Malformed content-length."); + return result; + } + for (char c : value){ + if (c < '0' || c > '9'){ + error(400, "Malformed content-length."); + return result; + } + } + content_length = std::stoull(value); + if (content_length > MAX_BODY_BYTES){ + error(413, "Request body too large."); + return result; + } + } + } + + const auto connection_it = result.request.headers.find("connection"); + if (connection_it != result.request.headers.end() && + to_lower(connection_it->second).find("close") != std::string::npos + ){ + result.connection_close_requested = true; + } + + const auto expect_it = result.request.headers.find("expect"); + if (expect_it != result.request.headers.end() && + to_lower(expect_it->second).find("100-continue") != std::string::npos + ){ + result.expect_continue = true; + } + + const size_t consumed = header_end + 4 + (size_t)content_length; + if (buffer.size() < consumed){ + // NEED_BODY: the headers are complete and valid, the body has + // not fully arrived yet. In this state the buffer holds nothing + // but the bytes of this one request ("consumed" is at most a + // header section plus the body cap), so the buffer cannot exceed + // MAX_BUFFER_BYTES here; the overall cap is enforced when data + // is appended instead. + result.state = ParseState::NEED_BODY; + return result; + } + + result.state = ParseState::READY; + result.request.method = std::move(method); + const size_t query = target.find('?'); + result.request.path = target.substr(0, query); + if (query != std::string::npos){ + result.request.query = target.substr(query + 1); + } + result.request.body = buffer.substr(header_end + 4, content_length); + buffer.erase(0, consumed); + result.http_1_1 = http_1_1; + return result; +} + + +void HttpServer::end_connection( + const std::shared_ptr& conn, + AbstractServerSocket* socket +){ + conn->dead.store(true, std::memory_order_release); + conn->cv.notify_all(); + // Close the socket's connection only while it still belongs to this + // connection: by the time a task notices its own connection died, + // the socket may already be serving the next client, and closing + // unconditionally would kill that client's connection instead. + { + std::lock_guard lg(m_lock); + if (m_connection.get() != conn.get()){ + return; + } + } + socket->close_connection(); +} + + +bool HttpServer::write_raw( + const std::shared_ptr& conn, + AbstractServerSocket* socket, + const std::string& bytes +){ + // "conn->socket_id" is the socket's connection token when this + // connection was accepted: if the socket has moved on to the next + // client since then, the send is refused instead of being delivered + // into the new client's socket. + const size_t sent = socket->send(bytes.data(), bytes.size(), WRITE_TIMEOUT, conn->socket_id); + if (sent != bytes.size()){ + // The peer went away, or the write stalled: the connection is + // unusable either way. + end_connection(conn, socket); + return false; + } + return true; +} + + +bool HttpServer::write_response( + const std::shared_ptr& conn, + AbstractServerSocket* socket, + const Response& response, + bool keep_alive +){ + return write_raw(conn, socket, format_response(response, keep_alive)); +} + + + +} diff --git a/Common/Cpp/HttpServer/HttpServer.h b/Common/Cpp/HttpServer/HttpServer.h new file mode 100644 index 0000000000..a770ea88fb --- /dev/null +++ b/Common/Cpp/HttpServer/HttpServer.h @@ -0,0 +1,169 @@ +/* HTTP Server + * + * From: https://github.com/PokemonAutomation/ + * + * The "AbstractServerSocket" implementation of "AbstractHttpServer": a + * minimal HTTP/1.1 server on the platform's default server socket, for a + * single local client that issues one request at a time. The request/ + * response types, the handler contract, and the threading rules are in + * "AbstractHttpServer.h"; this file documents the implementation. + * + */ + +#ifndef PokemonAutomation_HttpServer_H +#define PokemonAutomation_HttpServer_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/AsyncTask.h" +#include "Common/Cpp/Concurrency/ConditionVariable.h" +#include "Common/Cpp/Concurrency/Mutex.h" +#include "Common/Cpp/HttpServer/AbstractHttpServer.h" +#include "Common/Cpp/Sockets/AbstractServerSocket.h" + +namespace PokemonAutomation{ + +class ThreadPool; + + + +class HttpServer : public AbstractHttpServer, private AbstractServerSocket::Listener{ +public: + // The interface's types, re-exported under this class's name. + using AbstractHttpServer::Request; + using AbstractHttpServer::Response; + using AbstractHttpServer::HandlerContext; + using AbstractHttpServer::Handler; + using AbstractHttpServer::Listener; + + +public: + explicit HttpServer(ThreadPool& thread_pool); + ~HttpServer(); + + virtual void start(const std::string& address, uint16_t port, Handler handler) override; + virtual void stop() override; + virtual bool is_running() const override; + + +private: + // AbstractServerSocket::Listener. + virtual void on_listen_finished(const std::string& error_message) override; + virtual void on_connect() override; + virtual void on_connect_rejected() override; + virtual void on_receive_data(const void* data, size_t bytes) override; + virtual void on_disconnect(const std::string& error_message) override; + + +private: + // One request that is waiting to be parsed out of the buffer. + enum class ParseState{ + NEED_MORE, + NEED_BODY, + READY, + // Named "ERROR_RESPONSE" rather than "ERROR" because "ERROR" is + // a macro on Windows (winerror.h). + ERROR_RESPONSE, + }; + + struct ParsedRequest{ + ParseState state = ParseState::NEED_MORE; + + // ERROR_RESPONSE + int error_status = 400; + std::string error_reason; + std::vector> error_headers; + + // READY / NEED_BODY + Request request; + bool http_1_1 = true; + bool connection_close_requested = false; + bool expect_continue = false; + }; + + // Per-connection state. The connection task is the only thread that + // parses or writes; "on_receive_data"/"on_disconnect" only append + // data and flip flags. + struct Connection{ + Mutex lock; + ConditionVariable cv; + std::string buffer; + std::atomic dead{false}; + + // The server socket's connection_id() when this connection was + // accepted. Passed to every send(), so a write that outlives the + // connection is refused instead of reaching the next client. + uint64_t socket_id = 0; + }; + + // Runs on a thread from the thread pool, one instance per + // connection. + void connection_task( + const std::shared_ptr& conn, + AbstractServerSocket* socket + ); + + // Parses one complete request out of "buffer", removing it on + // success. Must be called with "conn->lock" held. + static ParsedRequest try_parse(std::string& buffer); + + // Marks the connection dead and closes it at the socket level. No-op + // if the socket is no longer connected to this client. + void end_connection( + const std::shared_ptr& conn, + AbstractServerSocket* socket + ); + + // Writes "bytes" to the connection completely; returns false (and + // ends the connection) if the peer went away or the write stalled. + bool write_raw( + const std::shared_ptr& conn, + AbstractServerSocket* socket, + const std::string& bytes + ); + + // Formats and writes the final response. + bool write_response( + const std::shared_ptr& conn, + AbstractServerSocket* socket, + const Response& response, + bool keep_alive + ); + + // The standard reason phrase for "status", or "Unknown Status". + static const char* status_reason(int status); + + // Builds the wire format of a response. + static std::string format_response(const Response& response, bool keep_alive); + + +private: + ThreadPool& m_thread_pool; + + // Guards m_socket, m_connection, and m_handler. Never held across a + // blocking wait, a task destruction, or a socket destruction. + mutable Mutex m_lock; + std::unique_ptr m_socket; + std::shared_ptr m_connection; + Handler m_handler; + + // Guards m_tasks. Never held while an AsyncTask destructor runs: + // the destructor blocks until the task finishes, and the task's + // final cleanup takes m_lock. + Mutex m_task_lock; + std::vector m_tasks; + + // Set by "stop()"; checked by the connection tasks between requests + // and by "HandlerContext". + std::atomic m_stop_requested{false}; +}; + + + +} +#endif diff --git a/Common/Cpp/HttpServer/HttpServer_Tests.cpp b/Common/Cpp/HttpServer/HttpServer_Tests.cpp new file mode 100644 index 0000000000..65b4ca31f9 --- /dev/null +++ b/Common/Cpp/HttpServer/HttpServer_Tests.cpp @@ -0,0 +1,1372 @@ +/* HTTP Server Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Loopback tests that run a real "HttpServer" (the platform's default + * server socket backend) on 127.0.0.1 and drive it with raw + * "ClientSocket" clients. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/AsyncTask.h" +#include "Common/Cpp/Concurrency/ConditionVariable.h" +#include "Common/Cpp/Concurrency/Mutex.h" +#include "Common/Cpp/Concurrency/ThreadPool.h" +#include "Common/Cpp/HttpServer/HttpServer.h" +#include "Common/Cpp/Sockets/ClientSocket.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "HttpServer_Tests.h" + +namespace PokemonAutomation{ + +namespace{ + + +struct Waiter{ + Mutex lock; + ConditionVariable cv; + + bool wait_for(std::chrono::milliseconds timeout, const std::function& pred){ + std::unique_lock lg(lock); + return cv.wait_for(lg, timeout, pred); + } + + void notify(){ + std::lock_guard lg(lock); + cv.notify_all(); + } +}; + + +// Long enough that a moderately loaded machine can make it, short enough +// that a real regression is still reported within the CI timeouts. +constexpr std::chrono::seconds HTTP_TEST_WAIT{60}; + + +// A handler gate: handlers notify "started" when they begin, and block on +// "wait_for_release()" until the test releases them. +struct HandlerGate{ + Waiter started; + + Mutex lock; + ConditionVariable cv; + std::atomic released{false}; + + void wait_for_release(std::chrono::milliseconds timeout){ + std::unique_lock lg(lock); + cv.wait_for(lg, timeout, [this]{ + return released.load(std::memory_order_relaxed); + }); + } + + void release(){ + released.store(true, std::memory_order_release); + std::lock_guard lg(lock); + cv.notify_all(); + } +}; + + +// A raw TCP client that accumulates everything it receives. +// "received" and the error strings are protected by "waiter.lock": the +// socket's receive thread writes them, the test thread reads them. +struct TestClient{ + Waiter waiter; + std::string received; + std::atomic connected{0}; + std::atomic disconnected{0}; + std::string connect_error; + std::string disconnect_error; + + struct Listener : AbstractClientSocket::Listener{ + TestClient* client; + + virtual void on_connect_finished(const std::string& error_message) override{ + { + std::lock_guard lg(client->waiter.lock); + client->connect_error = error_message; + } + client->connected++; + client->waiter.notify(); + } + + virtual void on_receive_data(const void* data, size_t bytes) override{ + { + std::lock_guard lg(client->waiter.lock); + client->received.append((const char*)data, bytes); + } + client->waiter.notify(); + } + + virtual void on_disconnect(const std::string& error_message) override{ + { + std::lock_guard lg(client->waiter.lock); + client->disconnect_error = error_message; + } + client->disconnected++; + client->waiter.notify(); + } + } listener_impl; + + ClientSocket socket; + + explicit TestClient(ThreadPool& thread_pool) + : socket(thread_pool) + { + listener_impl.client = this; + socket.add_listener(listener_impl); + } + + bool connect(uint16_t port){ + socket.connect("127.0.0.1", port); + return waiter.wait_for( + HTTP_TEST_WAIT, + [this]{ return connected.load() >= 1; } + ); + } + + bool send_all(const std::string& bytes){ + size_t total = 0; + while (total < bytes.size()){ + const size_t sent = socket.send(bytes.data() + total, bytes.size() - total); + if (sent == 0){ + return false; + } + total += sent; + } + return true; + } + + bool wait_for_bytes(size_t n){ + // The predicate runs with "waiter.lock" held, so it may read + // "received" directly. + return waiter.wait_for( + HTTP_TEST_WAIT, + [this, n]{ return received.size() >= n; } + ); + } + + // A consistent copy of everything received so far, for assertions. + std::string received_snapshot(){ + std::lock_guard lg(waiter.lock); + return received; + } +}; + + +struct TestServerListener : HttpServer::Listener{ + Waiter waiter; + std::atomic listen_finished{0}; + // Protected by "waiter.lock" (written by the socket's thread). + std::string last_listen_error; + std::atomic connected{0}; + std::atomic rejected{0}; + std::atomic disconnected{0}; + + virtual void on_listen_finished(const std::string& error_message) override{ + { + std::lock_guard lg(waiter.lock); + last_listen_error = error_message; + } + listen_finished++; + waiter.notify(); + } + + std::string last_listen_error_snapshot(){ + std::lock_guard lg(waiter.lock); + return last_listen_error; + } + + virtual void on_connect() override{ + connected++; + waiter.notify(); + } + + virtual void on_connect_rejected() override{ + rejected++; + waiter.notify(); + } + + virtual void on_disconnect(const std::string& error_message) override{ + disconnected++; + waiter.notify(); + } +}; + + +class TestHttpServer : public UnitTest{ +public: + TestHttpServer(ThreadPool& thread_pool, std::string name) + : UnitTest(std::move(name)) + , m_thread_pool(thread_pool) + { + m_threads = 2; + } + + +protected: + // Starts the server with "handler" on a free loopback port, waiting + // for the listen to finish. "handler" is copied on each attempt. + bool start_server(HttpServer& server, TestServerListener& listener, HttpServer::Handler handler, uint16_t& port) const{ + for (int attempt = 0; attempt < 8; attempt++){ + uint16_t candidate; + { + std::lock_guard lg(m_rng_lock); + candidate = (uint16_t)(40000 + m_rng() % 20000); + } + const int finished_before = listener.listen_finished.load(); + server.start("127.0.0.1", candidate, handler); + if (!listener.waiter.wait_for( + HTTP_TEST_WAIT, + [finished_before, &listener]{ + return listener.listen_finished.load() > finished_before; + } + )){ + server.stop(); + continue; + } + if (listener.last_listen_error_snapshot().empty()){ + port = candidate; + return true; + } + // A failed listen leaves the server "started but not + // listening"; stop() cleans that up before the next attempt. + server.stop(); + } + return false; + } + +protected: + ThreadPool& m_thread_pool; + +private: + mutable Mutex m_rng_lock; + mutable std::mt19937 m_rng{std::random_device{}()}; +}; + + +// A POST request is parsed (method, path, query, headers, body) and the +// response carries the extra headers and the exact body; the connection +// stays keep-alive. +class Test_Http_PostEcho : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + auto handler = [](const HttpServer::Request& request, HttpServer::Response& response, HttpServer::HandlerContext&){ + response.status = 200; + response.headers.push_back({"X-Test", "yes"}); + response.body = request.path + "|" + request.query + "|" + request.header("X-Client") + "|" + request.body; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + std::string error; + { + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect"; + }else if (!server_listener.waiter.wait_for( + HTTP_TEST_WAIT, + [&server_listener]{ return server_listener.connected.load() >= 1; } + )){ + error = "The server did not call on_connect"; + }else if (!client.send_all( + "POST /mcp?session=abc HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "X-Client: unit-test\r\n" + "Content-Length: 5\r\n" + "\r\n" + "hello" + )){ + error = "The client did not send the request"; + }else{ + const std::string expected = + "HTTP/1.1 200 OK\r\n" + "X-Test: yes\r\n" + "Content-Length: 32\r\n" + "Connection: keep-alive\r\n" + "\r\n" + "/mcp|session=abc|unit-test|hello"; + if (!client.wait_for_bytes(expected.size())){ + error = "The client did not receive the full response"; + }else if (client.received_snapshot() != expected){ + error = "Bad response:\n" + client.received_snapshot(); + } + } + // The client goes out of scope here and closes the socket. + } + + if (error.empty() && + !server_listener.waiter.wait_for( + HTTP_TEST_WAIT, + [&server_listener]{ return server_listener.disconnected.load() >= 1; } + ) + ){ + error = "The server did not call on_disconnect"; + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + +// Two requests sent back to back on one connection (the second is already +// buffered while the first is being answered): both must be answered, in +// order. +class Test_Http_PipelinedKeepAlive : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + auto handler = [](const HttpServer::Request& request, HttpServer::Response& response, HttpServer::HandlerContext&){ + response.status = 200; + response.body = "r" + request.body; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + std::string error; + { + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect"; + }else if (!client.send_all( + "POST /a HTTP/1.1\r\n" + "Content-Length: 3\r\n" + "\r\n" + "one" + "POST /b HTTP/1.1\r\n" + "Content-Length: 3\r\n" + "\r\n" + "two" + )){ + error = "The client did not send the requests"; + }else{ + const std::string expected = + "HTTP/1.1 200 OK\r\n" + "Content-Length: 4\r\n" + "Connection: keep-alive\r\n" + "\r\n" + "rone" + "HTTP/1.1 200 OK\r\n" + "Content-Length: 4\r\n" + "Connection: keep-alive\r\n" + "\r\n" + "rtwo"; + if (!client.wait_for_bytes(expected.size())){ + error = "The client did not receive both responses (got " + std::to_string(client.received_snapshot().size()) + " of " + std::to_string(expected.size()) + " bytes)"; + }else if (client.received_snapshot() != expected){ + error = "Bad response:\n" + client.received_snapshot(); + } + } + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + +// "Connection: close" in the request: the response says so, the server +// closes the connection, and it keeps serving new clients. +class Test_Http_ConnectionClose : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + auto handler = [](const HttpServer::Request&, HttpServer::Response& response, HttpServer::HandlerContext&){ + response.status = 200; + response.body = "done"; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + std::string error; + { + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect"; + }else if (!client.send_all( + "POST / HTTP/1.1\r\n" + "Content-Length: 1\r\n" + "Connection: close\r\n" + "\r\n" + "x" + )){ + error = "The client did not send the request"; + }else{ + const std::string expected = + "HTTP/1.1 200 OK\r\n" + "Content-Length: 4\r\n" + "Connection: close\r\n" + "\r\n" + "done"; + if (!client.wait_for_bytes(expected.size())){ + error = "The client did not receive the full response"; + }else if (client.received_snapshot() != expected){ + error = "Bad response:\n" + client.received_snapshot(); + }else if (!client.waiter.wait_for( + HTTP_TEST_WAIT, + [&client]{ return client.disconnected.load() >= 1; } + )){ + error = "The server did not close the connection"; + } + } + } + + if (error.empty()){ + // The server must keep listening for a new client. + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not reconnect"; + }else if (!client.send_all( + "POST / HTTP/1.1\r\n" + "Content-Length: 1\r\n" + "\r\n" + "y" + )){ + error = "The client did not send the request"; + }else{ + const std::string expected = + "HTTP/1.1 200 OK\r\n" + "Content-Length: 4\r\n" + "Connection: keep-alive\r\n" + "\r\n" + "done"; + if (!client.wait_for_bytes(expected.size()) || client.received_snapshot() != expected){ + error = "The reconnected client did not get a good response:\n" + client.received_snapshot(); + } + } + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + +// A request line that is not "METHOD SP TARGET SP VERSION" gets a 400 and +// a closed connection; the server recovers and serves a new client. +class Test_Http_BadRequest : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + auto handler = [](const HttpServer::Request&, HttpServer::Response& response, HttpServer::HandlerContext&){ + response.status = 200; + response.body = "ok"; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + std::string error; + { + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect"; + }else if (!client.send_all("GARBAGE\r\n\r\n")){ + error = "The client did not send the request"; + }else{ + const std::string expected = + "HTTP/1.1 400 Bad Request\r\n" + "Content-Length: 19\r\n" + "Connection: close\r\n" + "\r\n" + "Malformed request.\n"; + if (!client.wait_for_bytes(expected.size()) || client.received_snapshot() != expected){ + error = "Bad error response:\n" + client.received_snapshot(); + } + } + } + + if (error.empty()){ + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not reconnect"; + }else if (!client.send_all( + "POST / HTTP/1.1\r\n" + "Content-Length: 0\r\n" + "\r\n" + )){ + error = "The client did not send the request"; + }else{ + const std::string expected = + "HTTP/1.1 200 OK\r\n" + "Content-Length: 2\r\n" + "Connection: keep-alive\r\n" + "\r\n" + "ok"; + if (!client.wait_for_bytes(expected.size()) || client.received_snapshot() != expected){ + error = "The server did not recover:\n" + client.received_snapshot(); + } + } + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + +// Chunked request bodies are not supported: 501 and a closed connection, +// and the handler is never called. +class Test_Http_ChunkedRejected : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + std::atomic handler_called{false}; + auto handler = [&handler_called](const HttpServer::Request&, HttpServer::Response& response, HttpServer::HandlerContext&){ + handler_called = true; + response.status = 200; + response.body = "ok"; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + std::string error; + { + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect"; + }else if (!client.send_all( + "POST / HTTP/1.1\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + )){ + error = "The client did not send the request"; + }else{ + const std::string expected = + "HTTP/1.1 501 Not Implemented\r\n" + "Content-Length: 44\r\n" + "Connection: close\r\n" + "\r\n" + "Chunked transfer encoding is not supported.\n"; + if (!client.wait_for_bytes(expected.size()) || client.received_snapshot() != expected){ + error = "Bad error response:\n" + client.received_snapshot(); + } + } + } + + if (error.empty() && handler_called.load()){ + error = "The handler was called for a rejected request"; + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + +// A content-length above the body limit is rejected with 413 before the +// (never sent) body arrives, and the handler is never called. +class Test_Http_BodyTooLarge : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + std::atomic handler_called{false}; + auto handler = [&handler_called](const HttpServer::Request&, HttpServer::Response& response, HttpServer::HandlerContext&){ + handler_called = true; + response.status = 200; + response.body = "ok"; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + std::string error; + { + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect"; + }else if (!client.send_all( + "POST / HTTP/1.1\r\n" + "Content-Length: 2097152\r\n" + "\r\n" + )){ + error = "The client did not send the request"; + }else{ + const std::string expected = + "HTTP/1.1 413 Payload Too Large\r\n" + "Content-Length: 24\r\n" + "Connection: close\r\n" + "\r\n" + "Request body too large.\n"; + if (!client.wait_for_bytes(expected.size()) || client.received_snapshot() != expected){ + error = "Bad error response:\n" + client.received_snapshot(); + } + } + } + + if (error.empty() && handler_called.load()){ + error = "The handler was called for a rejected request"; + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + +// A complete header section over the size limit is rejected with 400, +// even though it arrives in one piece (the in-progress limit check only +// fires while the terminator is still missing). +class Test_Http_HeadersTooLarge : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + std::atomic handler_called{false}; + auto handler = [&handler_called](const HttpServer::Request&, HttpServer::Response& response, HttpServer::HandlerContext&){ + handler_called = true; + response.status = 200; + response.body = "ok"; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + // 50 headers of about 1.5 KiB each: about 75 KiB of headers - + // under the 100-header count limit, over the 64 KiB size limit. + std::string request = "POST / HTTP/1.1\r\n"; + for (int i = 0; i < 50; i++){ + request += "X-Filler-"; + request += std::to_string(i); + request += ": "; + request += std::string(1490, 'a'); + request += "\r\n"; + } + request += "\r\n"; + + std::string error; + { + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect"; + }else if (!client.send_all(request)){ + error = "The client did not send the request"; + }else{ + const std::string expected = + "HTTP/1.1 400 Bad Request\r\n" + "Content-Length: 19\r\n" + "Connection: close\r\n" + "\r\n" + "Malformed request.\n"; + if (!client.wait_for_bytes(expected.size()) || client.received_snapshot() != expected){ + error = "Bad error response:\n" + client.received_snapshot(); + } + } + } + + if (error.empty() && handler_called.load()){ + error = "The handler was called for a rejected request"; + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + +// A connection that sends more data than the receive buffer cap (about +// 2 MiB) is closed without a response, and the server keeps listening. +class Test_Http_BufferCap : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + std::atomic handler_calls{0}; + auto handler = [&handler_calls](const HttpServer::Request&, HttpServer::Response& response, HttpServer::HandlerContext&){ + handler_calls++; + response.status = 200; + response.body = "ok"; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + std::string error; + { + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect"; + }else{ + // A never-completing request far larger than the buffer + // cap: the server closes the connection without a + // response. (The send may fail partway through once the + // server has hung up; that is expected.) + const std::string flood(3u << 20, 'A'); + client.send_all(flood); + if (!client.waiter.wait_for( + HTTP_TEST_WAIT, + [&client]{ return client.disconnected.load() >= 1; } + )){ + error = "The server did not close the over-cap connection"; + } + } + } + + if (error.empty() && handler_calls.load() != 0){ + error = "The handler was called for a capped connection"; + } + + if (error.empty()){ + // The server must still be listening afterwards. + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect after the cap test"; + }else if (!client.send_all( + "POST / HTTP/1.1\r\n" + "Content-Length: 0\r\n" + "\r\n" + )){ + error = "The client did not send the request"; + }else{ + const std::string expected = + "HTTP/1.1 200 OK\r\n" + "Content-Length: 2\r\n" + "Connection: keep-alive\r\n" + "\r\n" + "ok"; + if (!client.wait_for_bytes(expected.size()) || client.received_snapshot() != expected){ + error = "The server did not answer after the cap test:\n" + client.received_snapshot(); + } + } + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + +// "Expect: 100-continue" is answered with "100 Continue" as soon as the +// headers are validated - before the body arrives, which is what a +// client waiting for the interim response is waiting for - and the +// final response carries the body. +class Test_Http_ExpectContinue : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + auto handler = [](const HttpServer::Request& request, HttpServer::Response& response, HttpServer::HandlerContext&){ + response.status = 200; + response.body = request.body; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + std::string error; + { + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect"; + }else if (!client.send_all( + "POST / HTTP/1.1\r\n" + "Content-Length: 5\r\n" + "Expect: 100-continue\r\n" + "\r\n" + )){ + error = "The client did not send the headers"; + }else{ + const std::string continue_response = "HTTP/1.1 100 Continue\r\n\r\n"; + if (!client.wait_for_bytes(continue_response.size()) + || client.received_snapshot().compare(0, continue_response.size(), continue_response) != 0 + ){ + error = "The server did not answer the interim response:\n" + client.received_snapshot(); + }else if (!client.send_all("hello")){ + error = "The client did not send the body"; + }else{ + const std::string expected = + "HTTP/1.1 100 Continue\r\n\r\n" + "HTTP/1.1 200 OK\r\n" + "Content-Length: 5\r\n" + "Connection: keep-alive\r\n" + "\r\n" + "hello"; + if (!client.wait_for_bytes(expected.size()) || client.received_snapshot() != expected){ + error = "Bad response:\n" + client.received_snapshot(); + } + } + } + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + +// The client disconnects while the handler is still running: the handler +// sees it via "HandlerContext::connection_alive()", its response is +// discarded, and the server keeps serving new clients. +class Test_Http_DisconnectDuringHandler : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + HandlerGate gate; + std::atomic call_count{0}; + std::atomic first_call_alive{false}; + std::atomic first_call_saw_disconnect{false}; + + auto handler = [&gate, &call_count, &first_call_alive, &first_call_saw_disconnect]( + const HttpServer::Request&, + HttpServer::Response& response, + HttpServer::HandlerContext& context + ){ + const int call = call_count.fetch_add(1) + 1; + if (call == 1){ + first_call_alive = context.connection_alive(); + gate.started.notify(); + gate.wait_for_release(HTTP_TEST_WAIT); + first_call_saw_disconnect = !context.connection_alive(); + } + response.status = 200; + response.body = "ok"; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + std::string error; + { + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect"; + }else if (!client.send_all( + "POST / HTTP/1.1\r\n" + "Content-Length: 1\r\n" + "\r\n" + "x" + )){ + error = "The client did not send the request"; + }else if (!gate.started.wait_for( + HTTP_TEST_WAIT, + [&first_call_alive]{ return first_call_alive.load(); } + )){ + error = "The handler did not start"; + } + // The client goes out of scope here and closes the socket, + // while the handler is still blocked on the gate. + } + + if (error.empty() && + !server_listener.waiter.wait_for( + HTTP_TEST_WAIT, + [&server_listener]{ return server_listener.disconnected.load() >= 1; } + ) + ){ + error = "The server did not call on_disconnect"; + } + + if (error.empty()){ + gate.release(); + } + + if (error.empty()){ + // The server must keep serving new clients. + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not reconnect"; + }else if (!client.send_all( + "POST / HTTP/1.1\r\n" + "Content-Length: 1\r\n" + "\r\n" + "y" + )){ + error = "The client did not send the request"; + }else{ + const std::string expected = + "HTTP/1.1 200 OK\r\n" + "Content-Length: 2\r\n" + "Connection: keep-alive\r\n" + "\r\n" + "ok"; + if (!client.wait_for_bytes(expected.size()) || client.received_snapshot() != expected){ + error = "The server did not recover:\n" + client.received_snapshot(); + } + } + } + + if (error.empty()){ + // Wait for the first handler to have recorded its observation. + if (!gate.started.wait_for( + HTTP_TEST_WAIT, + [&first_call_saw_disconnect, &call_count]{ + return call_count.load() >= 1 && first_call_saw_disconnect.load(); + } + )){ + error = "The handler did not record the disconnect"; + } + } + + if (error.empty()){ + if (!first_call_alive.load()){ + error = "The handler did not see the connection as alive on entry"; + }else if (!first_call_saw_disconnect.load()){ + error = "The handler did not see the disconnect via connection_alive()"; + } + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + +// The client disconnects while the handler is still running, and a new +// client connects before the handler returns: the old task must discard +// its response instead of writing it into the new client's socket. +class Test_Http_ReconnectWhileHandlerRunning : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + HandlerGate gate; + std::atomic first_call_alive{false}; + + auto handler = [&gate, &first_call_alive]( + const HttpServer::Request& request, + HttpServer::Response& response, + HttpServer::HandlerContext& context + ){ + if (request.path == "/a"){ + first_call_alive = context.connection_alive(); + gate.started.notify(); + gate.wait_for_release(HTTP_TEST_WAIT); + } + response.status = 200; + response.body = (request.path == "/a") ? "A" : "ok"; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + std::string error; + TestClient client_a(m_thread_pool); + TestClient client_b(m_thread_pool); + { + if (!client_a.connect(port)){ + error = "The first client did not connect"; + }else if (!client_a.send_all( + "POST /a HTTP/1.1\r\n" + "Content-Length: 1\r\n" + "\r\n" + "x" + )){ + error = "The first client did not send the request"; + }else if (!gate.started.wait_for( + HTTP_TEST_WAIT, + [&first_call_alive]{ return first_call_alive.load(); } + )){ + error = "The handler did not start"; + } + } + + if (error.empty()){ + // Disconnect the first client (closing its socket while it is + // still in scope, so its connection task keeps running) and + // wait for the server to report the disconnect. + client_a.socket.close(); + if (!server_listener.waiter.wait_for( + HTTP_TEST_WAIT, + [&server_listener]{ return server_listener.disconnected.load() >= 1; } + )){ + error = "The server did not report the first client's disconnect"; + } + } + + if (error.empty()){ + // Connect the second client while the first connection's + // handler is still blocked on the gate. Waiting for the + // second on_connect guarantees the second connection has + // replaced the first one in the server by the time the gate + // is released. + if (!client_b.connect(port)){ + error = "The second client did not connect"; + }else if (!server_listener.waiter.wait_for( + HTTP_TEST_WAIT, + [&server_listener]{ return server_listener.connected.load() >= 2; } + )){ + error = "The server did not accept the second client"; + } + } + + if (error.empty()){ + gate.release(); + } + + if (error.empty()){ + // The second client's first bytes must be its own response: + // the first client's late response was discarded, not + // written into this socket. + if (!client_b.send_all( + "POST /b HTTP/1.1\r\n" + "Content-Length: 1\r\n" + "\r\n" + "y" + )){ + error = "The second client did not send the request"; + }else{ + const std::string expected = + "HTTP/1.1 200 OK\r\n" + "Content-Length: 2\r\n" + "Connection: keep-alive\r\n" + "\r\n" + "ok"; + if (!client_b.wait_for_bytes(expected.size()) || client_b.received_snapshot() != expected){ + error = "The second client received a stray response:\n" + client_b.received_snapshot(); + } + } + } + + if (error.empty() && !first_call_alive.load()){ + error = "The handler did not see the connection as alive on entry"; + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + +// "stop()" while the handler is still running blocks until the handler +// returns, and "start()" works afterwards. +class Test_Http_StopDuringHandler : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + HandlerGate gate; + std::atomic handler_started{false}; + std::atomic saw_disconnect_on_stop{false}; + + auto handler = [&gate, &handler_started, &saw_disconnect_on_stop]( + const HttpServer::Request&, + HttpServer::Response& response, + HttpServer::HandlerContext& context + ){ + handler_started = true; + gate.started.notify(); + gate.wait_for_release(HTTP_TEST_WAIT); + // Then stay alive while the connection is alive: the pattern + // a long-running tool call uses. stop() marks the connection + // dead before it waits for this handler (the socket's + // close_connection() close suppresses the disconnect + // callback), so the loop must terminate - without that mark + // this would spin forever and stop() would hang. + while (context.connection_alive()){ + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + saw_disconnect_on_stop = !context.connection_alive(); + response.status = 200; + response.body = "late"; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + std::string error; + { + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect"; + }else if (!client.send_all( + "POST / HTTP/1.1\r\n" + "Content-Length: 1\r\n" + "\r\n" + "x" + )){ + error = "The client did not send the request"; + }else if (!gate.started.wait_for( + HTTP_TEST_WAIT, + [&handler_started]{ return handler_started.load(); } + )){ + error = "The handler did not start"; + } + } + + if (error.empty()){ + // stop() blocks until the in-flight handler returns. Release + // the handler from a pool thread so this thread can call it. + // The handle is kept (dispatch is [[nodiscard]]); its + // destructor waits for the trivial release task to finish. + AsyncTask releaser_task = m_thread_pool.dispatch([&gate]{ + gate.release(); + }); + server.stop(); + if (server.is_running()){ + error = "The server is still running after stop()"; + } + } + + if (error.empty() && !saw_disconnect_on_stop.load()){ + error = "The handler did not see the connection as gone after stop()"; + } + + if (error.empty()){ + // Start again (on a fresh port) and serve a fresh request. + auto simple_handler = [](const HttpServer::Request&, HttpServer::Response& response, HttpServer::HandlerContext&){ + response.status = 200; + response.body = "ok"; + }; + if (!start_server(server, server_listener, simple_handler, port)){ + error = "Failed to restart the server"; + }else{ + TestClient client(m_thread_pool); + if (!client.connect(port)){ + error = "The client did not connect to the restarted server"; + }else if (!client.send_all( + "POST / HTTP/1.1\r\n" + "Content-Length: 0\r\n" + "\r\n" + )){ + error = "The client did not send the request"; + }else{ + const std::string expected = + "HTTP/1.1 200 OK\r\n" + "Content-Length: 2\r\n" + "Connection: keep-alive\r\n" + "\r\n" + "ok"; + if (!client.wait_for_bytes(expected.size()) || client.received_snapshot() != expected){ + error = "The restarted server did not answer:\n" + client.received_snapshot(); + } + } + } + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + +// While one client is connected, a second one is rejected. +class Test_Http_RejectSecondClient : public TestHttpServer{ +public: + using TestHttpServer::TestHttpServer; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + TestServerListener server_listener; + HttpServer server(m_thread_pool); + server.add_listener(server_listener); + + auto handler = [](const HttpServer::Request&, HttpServer::Response& response, HttpServer::HandlerContext&){ + response.status = 200; + response.body = "ok"; + }; + + uint16_t port; + if (!start_server(server, server_listener, handler, port)){ + return "Failed to start the server"; + } + + std::string error; + { + TestClient first(m_thread_pool); + if (!first.connect(port)){ + error = "The first client did not connect"; + }else if (!server_listener.waiter.wait_for( + HTTP_TEST_WAIT, + [&server_listener]{ return server_listener.connected.load() >= 1; } + )){ + error = "The server did not call on_connect"; + }else{ + TestClient second(m_thread_pool); + second.connect(port); // May complete at the TCP level; the server closes it. + if (!server_listener.waiter.wait_for( + HTTP_TEST_WAIT, + [&server_listener]{ return server_listener.rejected.load() >= 1; } + )){ + error = "The server did not call on_connect_rejected"; + } + } + } + + server.stop(); + if (!error.empty()){ + return error; + } + return true; + } +}; + + + +} // anonymous namespace + + +void add_tests_HttpServer(UnitTestDatabase& database, ThreadPool& thread_pool){ + database.add( + thread_pool, "HttpServer - POST request/response with headers, query and body" + ); + database.add( + thread_pool, "HttpServer - Two pipelined requests on one keep-alive connection" + ); + database.add( + thread_pool, "HttpServer - Connection: close and reconnection" + ); + database.add( + thread_pool, "HttpServer - Malformed request line" + ); + database.add( + thread_pool, "HttpServer - Chunked request bodies are rejected" + ); + database.add( + thread_pool, "HttpServer - Oversized content-length is rejected" + ); + database.add( + thread_pool, "HttpServer - An oversized header section is rejected" + ); + database.add( + thread_pool, "HttpServer - A connection over the buffer cap is closed" + ); + database.add( + thread_pool, "HttpServer - Expect: 100-continue" + ); + database.add( + thread_pool, "HttpServer - Disconnect while the handler is running" + ); + database.add( + thread_pool, "HttpServer - Reconnect while the previous handler is still running" + ); + database.add( + thread_pool, "HttpServer - stop() while the handler is running" + ); + database.add( + thread_pool, "HttpServer - A second client is rejected" + ); +} + + + +} diff --git a/Common/Cpp/HttpServer/HttpServer_Tests.h b/Common/Cpp/HttpServer/HttpServer_Tests.h new file mode 100644 index 0000000000..6fe6c25cb1 --- /dev/null +++ b/Common/Cpp/HttpServer/HttpServer_Tests.h @@ -0,0 +1,28 @@ +/* HTTP Server Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_HttpServer_Tests_H +#define PokemonAutomation_HttpServer_Tests_H + +namespace PokemonAutomation{ + +class ThreadPool; +class UnitTestDatabase; + + +// Loopback tests that run a real "HttpServer" (the platform's default +// server socket backend) on 127.0.0.1 and drive it with raw "ClientSocket" +// clients: request/response parsing, keep-alive, pipelining, +// "Connection: close", "Expect: 100-continue", error responses, and the +// lifecycle (disconnect during a handler, "stop()" during a handler, +// restart, second-client rejection). `thread_pool` runs the server and +// the test workers; it must be a long-lived pool (e.g. +// `GlobalThreadPools::unlimited_normal()`). +void add_tests_HttpServer(UnitTestDatabase& database, ThreadPool& thread_pool); + + +} +#endif diff --git a/Common/Cpp/Sockets/AbstractServerSocket.h b/Common/Cpp/Sockets/AbstractServerSocket.h index 4139a0f120..1c2da259ef 100644 --- a/Common/Cpp/Sockets/AbstractServerSocket.h +++ b/Common/Cpp/Sockets/AbstractServerSocket.h @@ -13,6 +13,7 @@ #define PokemonAutomation_Sockets_AbstractServerSocket_H #include +#include #include #include "Common/Cpp/ListenerSet.h" @@ -58,6 +59,18 @@ class AbstractServerSocket{ return m_state.load(std::memory_order_relaxed); } + // A token identifying the connection the socket is currently + // serving. It changes every time a new client is accepted, and it + // is 0 when no connection is active. Capture it when a write + // starts and pass it to "send()", so that a write that outlives its + // connection (the peer disconnected and a new client was accepted + // in the meantime) refuses to reach the new client's socket. + // Implementations keep the underlying counter monotonic (never + // reset it when a connection closes, or a queued write for the old + // connection could match the next connection's id); 0 is only the + // "no connection is active" report, never a counter value. + virtual uint64_t connection_id() = 0; + // Binds to "address" and listens on "port". // Use "0.0.0.0" to accept connections on all interfaces. virtual void start(const std::string& address, uint16_t port) = 0; @@ -69,7 +82,10 @@ class AbstractServerSocket{ virtual size_t send( const void* data, size_t bytes, - std::chrono::milliseconds timeout = std::chrono::milliseconds::max() + std::chrono::milliseconds timeout = std::chrono::milliseconds::max(), + // The connection_id() captured when this write started. 0 skips + // the check: the call applies to whatever connection is active. + uint64_t connection = 0 ) = 0; diff --git a/Common/Cpp/Sockets/ServerSocket_POSIX.cpp b/Common/Cpp/Sockets/ServerSocket_POSIX.cpp index 75b2a14ead..ad38549eb6 100644 --- a/Common/Cpp/Sockets/ServerSocket_POSIX.cpp +++ b/Common/Cpp/Sockets/ServerSocket_POSIX.cpp @@ -83,6 +83,14 @@ void ServerSocket_POSIX::start(const std::string& address, uint16_t port){ } } +uint64_t ServerSocket_POSIX::connection_id(){ + std::lock_guard lg(m_lock); + return m_state.load(std::memory_order_relaxed) == State::CONNECTED + ? m_connection_id + : 0; +} + + void ServerSocket_POSIX::close_connection(){ int socket; { @@ -159,16 +167,16 @@ void ServerSocket_POSIX::close_and_wait() noexcept{ } } -size_t ServerSocket_POSIX::send(const void* data, size_t bytes, std::chrono::milliseconds timeout){ +size_t ServerSocket_POSIX::send(const void* data, size_t bytes, std::chrono::milliseconds timeout, uint64_t connection){ int socket; { std::lock_guard lg(m_lock); - socket = m_state.load(std::memory_order_relaxed) == State::CONNECTED - ? m_client - : -1; - } - if (socket == -1){ - return 0; + if (m_state.load(std::memory_order_relaxed) != State::CONNECTED + || (connection != 0 && m_connection_id != connection) + ){ + return 0; + } + socket = m_client; } const char* ptr = (const char*)data; @@ -184,7 +192,12 @@ size_t ServerSocket_POSIX::send(const void* data, size_t bytes, std::chrono::mil while (bytes > 0){ { std::lock_guard lg(m_lock); - if (m_state.load(std::memory_order_relaxed) != State::CONNECTED){ + // The connection may have been replaced (or closed) since the + // last iteration: in that case this write must stop rather + // than reach the new client's socket. + if (m_state.load(std::memory_order_relaxed) != State::CONNECTED + || (connection != 0 && m_connection_id != connection) + ){ return sent; } } @@ -359,6 +372,7 @@ void ServerSocket_POSIX::accept_thread_loop(std::string address, uint16_t port, fcntl(client_socket, F_SETFL, O_NONBLOCK); m_client = client_socket; m_close_requested = false; + m_connection_id++; m_state.store(State::CONNECTED, std::memory_order_release); accepted = true; } diff --git a/Common/Cpp/Sockets/ServerSocket_POSIX.h b/Common/Cpp/Sockets/ServerSocket_POSIX.h index 6786a631fc..f08b83ca68 100644 --- a/Common/Cpp/Sockets/ServerSocket_POSIX.h +++ b/Common/Cpp/Sockets/ServerSocket_POSIX.h @@ -42,9 +42,15 @@ class ServerSocket_POSIX final : public AbstractServerSocket{ virtual size_t send( const void* data, size_t bytes, - std::chrono::milliseconds timeout = std::chrono::milliseconds::max() + std::chrono::milliseconds timeout = std::chrono::milliseconds::max(), + uint64_t connection = 0 ) override; + // A token identifying the connection the socket is currently + // serving. It changes every time a new client is accepted, and it + // is 0 when no connection is active. + virtual uint64_t connection_id() override; + private: @@ -87,6 +93,12 @@ class ServerSocket_POSIX final : public AbstractServerSocket{ int m_client = -1; bool m_close_requested = false; + // A connection token, incremented (under m_lock) on every accept. + // send() compares it against the token the caller captured, so a + // write that outlived its connection cannot reach the client that + // replaced it. 0 means no connection is active. + uint64_t m_connection_id = 0; + // One task per start() call. start() must never destroy the previous // task's AsyncTask here: its destructor blocks until the task has // finished, and a task from an earlier attempt may still be running diff --git a/Common/Cpp/Sockets/ServerSocket_Qt.cpp b/Common/Cpp/Sockets/ServerSocket_Qt.cpp index fd48c72001..359a45b1f1 100644 --- a/Common/Cpp/Sockets/ServerSocket_Qt.cpp +++ b/Common/Cpp/Sockets/ServerSocket_Qt.cpp @@ -174,13 +174,16 @@ void ServerSocket_Qt::close_and_wait() noexcept{ m_close_requested = false; } -size_t ServerSocket_Qt::send(const void* data, size_t bytes, std::chrono::milliseconds timeout){ +size_t ServerSocket_Qt::send(const void* data, size_t bytes, std::chrono::milliseconds timeout, uint64_t connection){ QTcpSocket* socket; { std::lock_guard lg(m_lock); - socket = m_state.load(std::memory_order_relaxed) == State::CONNECTED - ? m_socket - : nullptr; + if (m_state.load(std::memory_order_relaxed) != State::CONNECTED + || (connection != 0 && m_connection_id != connection) + ){ + return 0; + } + socket = m_socket; } if (socket == nullptr){ return 0; @@ -188,6 +191,7 @@ size_t ServerSocket_Qt::send(const void* data, size_t bytes, std::chrono::millis QSharedPointer send_data = QSharedPointer::create(); send_data->packet.assign((const char*)data, bytes); + send_data->connection = connection; // "time_point::max()" (the infinite default) is never reached; using // it also avoids overflowing "now() + timeout". send_data->deadline = @@ -213,7 +217,8 @@ size_t ServerSocket_Qt::send(const void* data, size_t bytes, std::chrono::millis std::lock_guard lg(m_lock); registered = m_state.load(std::memory_order_relaxed) == State::CONNECTED - && m_socket != nullptr; + && m_socket != nullptr + && (connection == 0 || m_connection_id == connection); if (registered){ m_inflight_sends.push_back(send_data); } @@ -310,6 +315,7 @@ void ServerSocket_Qt::on_new_connection(){ }else{ m_socket = sock; m_close_requested = false; + m_connection_id++; m_state.store(State::CONNECTED, std::memory_order_release); accepted = true; rejected = false; @@ -434,11 +440,28 @@ void ServerSocket_Qt::on_close_connection(QSharedPointer comple completion->cv.notify_all(); } +uint64_t ServerSocket_Qt::connection_id(){ + std::lock_guard lg(m_lock); + return m_state.load(std::memory_order_relaxed) == State::CONNECTED + ? m_connection_id + : 0; +} + + void ServerSocket_Qt::on_send(QSharedPointer send_data){ QTcpSocket* sock; { std::lock_guard lg(m_lock); - sock = m_socket; + if (send_data->connection != 0 + && m_connection_id != send_data->connection + ){ + // The connection this send was queued for was replaced (or + // torn down) while it was waiting in the queue: the write + // loop must not reach into the new connection's socket. + sock = nullptr; + }else{ + sock = m_socket; + } } { diff --git a/Common/Cpp/Sockets/ServerSocket_Qt.h b/Common/Cpp/Sockets/ServerSocket_Qt.h index 0bcf70c0a6..370152e98c 100644 --- a/Common/Cpp/Sockets/ServerSocket_Qt.h +++ b/Common/Cpp/Sockets/ServerSocket_Qt.h @@ -54,6 +54,12 @@ class ServerSocket_Qt final : public QObject, public AbstractServerSocket{ // "close_and_wait()"/"close_connection()" cancel the send. bool done = false; + // The connection_id() the send was queued for; 0 skips the + // check. "on_send" refuses to write if the connection was + // replaced while the send was queued, so it cannot reach the + // new client's socket. + uint64_t connection = 0; + Mutex lock; ConditionVariable cv; }; @@ -86,9 +92,15 @@ class ServerSocket_Qt final : public QObject, public AbstractServerSocket{ virtual size_t send( const void* data, size_t bytes, - std::chrono::milliseconds timeout = std::chrono::milliseconds::max() + std::chrono::milliseconds timeout = std::chrono::milliseconds::max(), + uint64_t connection = 0 ) override; + // A token identifying the connection the socket is currently + // serving. It changes every time a new client is accepted, and it + // is 0 when no connection is active. + virtual uint64_t connection_id() override; + signals: void internal_send(QSharedPointer send_data); @@ -142,6 +154,12 @@ class ServerSocket_Qt final : public QObject, public AbstractServerSocket{ bool m_close_requested = false; bool m_starting = false; + // A connection token, incremented (under m_lock) on every accept. + // "send()" compares it against the token the caller captured, so a + // write that outlived its connection cannot reach the client that + // replaced it. 0 means no connection is active. + uint64_t m_connection_id = 0; + // The "send()" calls that are queued on the event thread but not // finished yet, so that "close_and_wait()"/"close_connection()" can // cancel diff --git a/Common/Cpp/Sockets/ServerSocket_WinSocket.cpp b/Common/Cpp/Sockets/ServerSocket_WinSocket.cpp index 55889f4b38..066a76ab24 100644 --- a/Common/Cpp/Sockets/ServerSocket_WinSocket.cpp +++ b/Common/Cpp/Sockets/ServerSocket_WinSocket.cpp @@ -94,6 +94,14 @@ void ServerSocket_WinSocket::start(const std::string& address, uint16_t port){ } } +uint64_t ServerSocket_WinSocket::connection_id(){ + std::lock_guard lg(m_lock); + return m_state.load(std::memory_order_relaxed) == State::CONNECTED + ? m_connection_id + : 0; +} + + void ServerSocket_WinSocket::close_connection(){ SOCKET socket; { @@ -170,13 +178,16 @@ void ServerSocket_WinSocket::close_and_wait() noexcept{ } } -size_t ServerSocket_WinSocket::send(const void* data, size_t bytes, std::chrono::milliseconds timeout){ +size_t ServerSocket_WinSocket::send(const void* data, size_t bytes, std::chrono::milliseconds timeout, uint64_t connection){ SOCKET socket; { std::lock_guard lg(m_lock); - socket = m_state.load(std::memory_order_relaxed) == State::CONNECTED - ? m_client - : INVALID_SOCKET; + if (m_state.load(std::memory_order_relaxed) != State::CONNECTED + || (connection != 0 && m_connection_id != connection) + ){ + return 0; + } + socket = m_client; } if (socket == INVALID_SOCKET){ return 0; @@ -195,7 +206,12 @@ size_t ServerSocket_WinSocket::send(const void* data, size_t bytes, std::chrono: while (bytes > 0){ { std::lock_guard lg(m_lock); - if (m_state.load(std::memory_order_relaxed) != State::CONNECTED){ + // The connection may have been replaced (or closed) since the + // last iteration: in that case this write must stop rather + // than reach the new client's socket. + if (m_state.load(std::memory_order_relaxed) != State::CONNECTED + || (connection != 0 && m_connection_id != connection) + ){ return sent; } } @@ -379,6 +395,7 @@ void ServerSocket_WinSocket::accept_thread_loop(std::string address, uint16_t po ioctlsocket(client_socket, FIONBIO, &client_non_blocking); m_client = client_socket; m_close_requested = false; + m_connection_id++; m_state.store(State::CONNECTED, std::memory_order_release); accepted = true; } diff --git a/Common/Cpp/Sockets/ServerSocket_WinSocket.h b/Common/Cpp/Sockets/ServerSocket_WinSocket.h index 6b68519ab8..f478e69b46 100644 --- a/Common/Cpp/Sockets/ServerSocket_WinSocket.h +++ b/Common/Cpp/Sockets/ServerSocket_WinSocket.h @@ -45,9 +45,15 @@ class ServerSocket_WinSocket final : public AbstractServerSocket{ virtual size_t send( const void* data, size_t bytes, - std::chrono::milliseconds timeout = std::chrono::milliseconds::max() + std::chrono::milliseconds timeout = std::chrono::milliseconds::max(), + uint64_t connection = 0 ) override; + // A token identifying the connection the socket is currently + // serving. It changes every time a new client is accepted, and it + // is 0 when no connection is active. + virtual uint64_t connection_id() override; + private: // Winsock has to be started before any of its functions can be used, and @@ -96,6 +102,12 @@ class ServerSocket_WinSocket final : public AbstractServerSocket{ SOCKET m_client = INVALID_SOCKET; bool m_close_requested = false; + // A connection token, incremented (under m_lock) on every accept. + // send() compares it against the token the caller captured, so a + // write that outlived its connection cannot reach the client that + // replaced it. 0 means no connection is active. + uint64_t m_connection_id = 0; + // One task per start() call. start() must never destroy the previous // task's AsyncTask here: its destructor blocks until the task has // finished, and a task from an earlier attempt may still be running diff --git a/Common/Cpp/Sockets/Sockets_Tests.cpp b/Common/Cpp/Sockets/Sockets_Tests.cpp index 7864a7d34a..3fe3bd915d 100644 --- a/Common/Cpp/Sockets/Sockets_Tests.cpp +++ b/Common/Cpp/Sockets/Sockets_Tests.cpp @@ -822,6 +822,117 @@ class Test_Sockets_RejectSecondClient : public TestSockets +class Test_Sockets_StaleSend : public TestSockets{ +public: + using TestSockets::TestSockets; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + ServerListener server_listener; + ServerSocketType server(this->m_thread_pool); + server.add_listener(server_listener); + + uint16_t port; + if (!this->start_server(server, server_listener, port)){ + return "Failed to start the server"; + } + + std::string error; + if (server.connection_id() != 0){ + error = "connection_id() was not 0 before any connection"; + } + + uint64_t first_id = 0; + { + ClientListener client_listener; + ClientSocketType client(this->m_thread_pool); + client.add_listener(client_listener); + + if (!this->connect_client(client, client_listener, port, 1)){ + error = "The first client did not finish connecting"; + }else if (!server_listener.waiter.wait_for( + SOCKET_TEST_WAIT, + [&server_listener]{ return server_listener.connected.load() >= 1; } + )){ + error = "The server did not call on_connect"; + }else{ + first_id = server.connection_id(); + if (first_id == 0){ + error = "The server did not assign a connection id"; + } + client.close(); + } + } + + if (error.empty() && !server_listener.waiter.wait_for( + SOCKET_TEST_WAIT, + [&server_listener]{ return server_listener.disconnected.load() >= 1; } + )){ + error = "The server did not call on_disconnect"; + } + + // The counter is monotonic and not reset, but with no active + // connection the id must report 0. + if (error.empty() && server.connection_id() != 0){ + error = "connection_id() was not 0 while no connection was active"; + } + + uint64_t second_id = 0; + { + ClientListener client_listener; + ClientSocketType client(this->m_thread_pool); + client.add_listener(client_listener); + + if (!this->connect_client(client, client_listener, port, 1)){ + error = "The second client did not finish connecting"; + }else if (!server_listener.waiter.wait_for( + SOCKET_TEST_WAIT, + [&server_listener]{ return server_listener.connected.load() >= 2; } + )){ + error = "The server did not call on_connect for the second client"; + }else{ + second_id = server.connection_id(); + if (second_id == first_id){ + error = "The connection id did not change after reconnect"; + } + // A send for the replaced connection must be refused, + // not delivered into the new client's socket. + if (error.empty() && + server.send("stale", 5, std::chrono::milliseconds::max(), first_id) != 0 + ){ + error = "A send for a replaced connection was not refused"; + } + // A send for the current connection still goes through. + if (error.empty() && + server.send("hello", 5, std::chrono::milliseconds::max(), second_id) != 5 + ){ + error = "The send for the current connection was not delivered"; + } + if (error.empty() && !client_listener.waiter.wait_for( + SOCKET_TEST_WAIT, + [&client_listener]{ return client_listener.received.size() >= 5; } + )){ + error = "The second client did not receive the data"; + }else if (error.empty() && + std::memcmp(client_listener.received.data(), "hello", 5) != 0 + ){ + error = "The second client received the wrong data"; + } + client.close(); + } + } + + if (!error.empty()){ + return error; + } + return true; + } +}; + + // Starting a second server on an already-bound port must fail through // on_listen_finished and leave the server not running. template @@ -2676,6 +2787,9 @@ void add_socket_tests(UnitTestDatabase& database, ThreadPool& thread_pool, const database.add>( thread_pool, prefix + "Reject a second client" ); + database.add>( + thread_pool, prefix + "A send for a replaced connection is refused" + ); database.add>( thread_pool, prefix + "Port in use" ); diff --git a/SerialPrograms/Source/CommonFramework/Windows/Lab.md b/SerialPrograms/Source/CommonFramework/Windows/Lab.md index 37ccad0e5e..fcfb9dfa23 100644 --- a/SerialPrograms/Source/CommonFramework/Windows/Lab.md +++ b/SerialPrograms/Source/CommonFramework/Windows/Lab.md @@ -27,6 +27,7 @@ takes effect at the next launch. | `Lab/done/.txt` | app moves | The request, moved here when it starts. | | `Lab/outbox/.out` | app writes | The request's journal (below). It appears only once the request has finished; `.tmp` shows the progress so far. | | `Lab/outbox/_