Play your Steam library's Windows games on a jailbroken PS5.
C++
Serve web requests on several workers
Leonardo Lobatoc22b5fe76cb0
diff --git a/src/web/http.cpp b/src/web/http.cppindex 80e2104..02e3fee 100644--- a/src/web/http.cpp+++ b/src/web/http.cpp@@ -62,7 +62,13 @@ std::optional<std::string> QueryValue(std::string_view query, std::string_view kreturn std::nullopt;}-ParseResult ParseRequestHead(std::string_view bytes, Request* out) {+std::optional<std::string> HeaderValue(const Request& request, std::string_view name) {+ for (const auto& [key, value] : request.headers)+ if (key == name) return value;+ return std::nullopt;+}++ParseResult ParseRequestHead(std::string_view bytes, Request* out, std::size_t* head_size) {std::size_t end = bytes.find("\r\n\r\n");std::size_t terminator = 4;if (const auto bare = bytes.find("\n\n"); bare != std::string_view::npos && (end == std::string_view::npos || bare < end)) {@@ -114,9 +120,20 @@ ParseResult ParseRequestHead(std::string_view bytes, Request* out) {}const auto value = TrimSpaces(header.substr(colon + 1));for (const unsigned char c : value) if ((c < 0x20 && c != '\t') || c == 0x7f) return ParseResult::kBadRequest;+ if (name == "transfer-encoding") return ParseResult::kBadRequest; // no chunked uploads+ if (name == "content-length") {+ if (request.content_length || value.empty() || value.size() > 19) return ParseResult::kBadRequest;+ std::uint64_t length = 0;+ for (const char c : value) {+ if (c < '0' || c > '9') return ParseResult::kBadRequest;+ length = length * 10 + static_cast<std::uint64_t>(c - '0');+ }+ request.content_length = length;+ }request.headers.emplace_back(std::move(name), std::string(value));}*out = std::move(request);+ if (head_size) *head_size = end + terminator;return ParseResult::kOk;}@@ -125,13 +142,19 @@ const char* StatusText(int status) {case 200: return "OK";case 202: return "Accepted";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 409: return "Conflict";+ case 411: return "Length Required";+ case 413: return "Content Too Large";+ case 429: return "Too Many Requests";case 431: return "Request Header Fields Too Large";case 500: return "Internal Server Error";case 503: return "Service Unavailable";+ case 507: return "Insufficient Storage";default: return "Unknown";}}@@ -156,9 +179,36 @@ bool Response::Start(int status, std::string_view content_type, std::optional<streturn !failed_;}+bool Response::StartChunked(int status, std::string_view content_type,+ const std::vector<std::pair<std::string, std::string>>& extra) {+ auto headers = extra;+ if (!head_only_) headers.emplace_back("Transfer-Encoding", "chunked");+ const bool started = Start(status, content_type, std::nullopt, headers);+ chunked_ = !head_only_;+ return started;+}++bool Response::FinishChunks() {+ if (!started_ || failed_) return false;+ if (!chunked_) return true;+ static constexpr char kLast[] = "0\r\n\r\n";+ if (!write_(kLast, sizeof kLast - 1)) failed_ = true;+ return !failed_;+}+bool Response::Body(const char* data, std::size_t size) {if (!started_ || failed_) return false;if (head_only_ || size == 0) return true;+ if (chunked_) {+ char line[32];+ const int length = std::snprintf(line, sizeof line, "%zx\r\n", size);+ if (!write_(line, static_cast<std::size_t>(length)) || !write_(data, size) || !write_("\r\n", 2)) {+ failed_ = true;+ return false;+ }+ body_bytes_ += size;+ return true;+ }if (!write_(data, size)) {failed_ = true;return false;diff --git a/src/web/http.h b/src/web/http.hindex df1fd76..db70b8b 100644--- a/src/web/http.h+++ b/src/web/http.h@@ -23,13 +23,22 @@ struct Request {std::string path; // percent-decoded, without the querystd::string query; // raw, after '?'std::vector<std::pair<std::string, std::string>> headers; // names lower-cased+ // The body's declared length; nothing without a Content-Length header.+ std::optional<std::uint64_t> content_length;+ // Reads up to size body bytes: the count, 0 at the end of the declared length, -1 when the client went away or+ // went quiet. Empty when there is no connection (tests that route a request directly).+ std::function<std::ptrdiff_t(char* data, std::size_t size)> read_body;};+// A header's value (names are lower-case), or nothing.+std::optional<std::string> HeaderValue(const Request& request, std::string_view name);+enum class ParseResult { kIncomplete, kOk, kBadRequest, kTooLarge };// Parses an HTTP/1.x request head from the bytes received so far. kIncomplete: no blank line yet-// and still under kMaxRequestHead. The body, if any, is ignored.-ParseResult ParseRequestHead(std::string_view bytes, Request* out);+// and still under kMaxRequestHead. *head_size is set to the head's size with its blank line, so what follows+// is the start of the body. A chunked or repeated body length, or one that isn't a number, is kBadRequest.+ParseResult ParseRequestHead(std::string_view bytes, Request* out, std::size_t* head_size = nullptr);// The percent-decoded value of key in a query string ("title=FAKE78012&x=1"), or nothing.std::optional<std::string> QueryValue(std::string_view query, std::string_view key);@@ -49,6 +58,11 @@ class Response {// the connection closes (a streamed zip).bool Start(int status, std::string_view content_type, std::optional<std::uint64_t> length,const std::vector<std::pair<std::string, std::string>>& extra = {});+ // Sends the status line and headers of a chunked body. The client sees the download as complete only after+ // FinishChunks: a body cut before it (the connection closed on a failure) shows as a failed download.+ bool StartChunked(int status, std::string_view content_type,+ const std::vector<std::pair<std::string, std::string>>& extra = {});+ bool FinishChunks();bool Body(const char* data, std::size_t size);bool Body(std::string_view text) { return Body(text.data(), text.size()); }// A complete small response: Start with the body's length, then the body.@@ -65,6 +79,7 @@ class Response {bool head_only_ = false;bool started_ = false;bool failed_ = false;+ bool chunked_ = false;int status_ = 0;std::uint64_t body_bytes_ = 0;};diff --git a/src/web/server.cpp b/src/web/server.cppindex 498f5ce..7e2069b 100644--- a/src/web/server.cpp+++ b/src/web/server.cpp@@ -4,6 +4,7 @@#include "web/router.h"#include <arpa/inet.h>+#include <algorithm>#include <cerrno>#include <chrono>#include <cstring>@@ -108,24 +109,45 @@ bool Server::Start(const ServerOptions& options, Handler handler, std::string* esocklen_t size = sizeof bound;if (::getsockname(listener_, reinterpret_cast<sockaddr*>(&bound), &size) != 0) return fail("getsockname: " + ErrorText(errno));port_ = ntohs(bound.sin_port);- worker_ = std::thread([this] { Run(); });+ idle_ = 0;+ for (int i = 0; i < std::max(options.workers, 1); ++i) workers_.emplace_back([this] { Work(); });+ acceptor_ = std::thread([this] { Run(); });return true;}void Server::Stop() {stop_.store(true);{- // Wakes a send or recv blocked on the client; the worker still owns and closes the descriptor.- std::lock_guard<std::mutex> lock(client_mutex_);- if (client_ >= 0) ::shutdown(client_, SHUT_RDWR);+ // Wakes every send or recv blocked on a client; the worker still owns and closes the descriptor.+ std::lock_guard<std::mutex> lock(mutex_);+ for (const int client : clients_) ::shutdown(client, SHUT_RDWR);}- if (worker_.joinable()) worker_.join();+ changed_.notify_all();+ if (acceptor_.joinable()) acceptor_.join();+ for (auto& worker : workers_)+ if (worker.joinable()) worker.join();+ workers_.clear();+ // Accepted, but no worker took them before the stop.+ for (const auto& accepted : waiting_) {+ ::shutdown(accepted.fd, SHUT_RDWR);+ ::close(accepted.fd);+ }+ waiting_.clear();+ clients_.clear();if (listener_ >= 0) ::close(listener_);listener_ = -1;}void Server::Run() {while (!stop_.load()) {+ // Accept only for a free worker: the others wait in the backlog, not in a queue of ours.+ {+ std::unique_lock<std::mutex> lock(mutex_);+ changed_.wait_for(lock, std::chrono::milliseconds(options_.poll_interval_ms),+ [this] { return stop_.load() || idle_ > static_cast<int>(waiting_.size()); });+ if (stop_.load()) break;+ if (idle_ <= static_cast<int>(waiting_.size())) continue;+ }pollfd waiting{};waiting.fd = listener_;waiting.events = POLLIN;@@ -148,19 +170,36 @@ void Server::Run() {Log("accept fd=" + std::to_string(client) + (client < 0 ? " " + ErrorText(accept_error) : std::string(" client=") + ip));if (client < 0) continue;NoSigpipe(client);- SetTimeout(client, SO_RCVTIMEO, options_.read_timeout_ms);SetTimeout(client, SO_SNDTIMEO, options_.write_timeout_ms);{- std::lock_guard<std::mutex> lock(client_mutex_);- client_ = client;+ std::lock_guard<std::mutex> lock(mutex_);+ waiting_.push_back({client, ip});+ clients_.push_back(client);}- if (!stop_.load()) Serve(client, ip);+ changed_.notify_all();+ }+}++void Server::Work() {+ while (true) {+ Accepted accepted;+ {+ std::unique_lock<std::mutex> lock(mutex_);+ ++idle_;+ changed_.notify_all();+ changed_.wait(lock, [this] { return stop_.load() || !waiting_.empty(); });+ --idle_;+ if (stop_.load()) return;+ accepted = std::move(waiting_.front());+ waiting_.erase(waiting_.begin());+ }+ Serve(accepted.fd, accepted.ip);{- std::lock_guard<std::mutex> lock(client_mutex_);- client_ = -1;+ std::lock_guard<std::mutex> lock(mutex_);+ clients_.erase(std::remove(clients_.begin(), clients_.end(), accepted.fd), clients_.end());}- ::shutdown(client, SHUT_RDWR);- ::close(client);+ ::shutdown(accepted.fd, SHUT_RDWR);+ ::close(accepted.fd);}}@@ -181,20 +220,61 @@ void Server::Serve(int client, const std::string& client_ip) {std::vector<char> buffer(2048);Request request;ParseResult parsed = ParseResult::kIncomplete;+ std::size_t head_size = 0;+ SetTimeout(client, SO_RCVTIMEO, std::min(options_.silent_timeout_ms, options_.read_timeout_ms));while (parsed == ParseResult::kIncomplete) {if (std::chrono::steady_clock::now() > deadline || stop_.load()) break;const auto count = ::recv(client, buffer.data(), buffer.size(), 0);if (count < 0 && errno == EINTR) continue;if (count <= 0) break;+ if (received.empty()) SetTimeout(client, SO_RCVTIMEO, options_.read_timeout_ms);received.append(buffer.data(), static_cast<std::size_t>(count));- parsed = ParseRequestHead(received, &request);+ parsed = ParseRequestHead(received, &request, &head_size);}Response response(write, request.method == Method::kHead);std::string target = "-";if (parsed == ParseResult::kOk) {target = LoggedTarget(request);+ // Body bytes that came with the head go first; the handler decides whether to read the rest.+ received.erase(0, head_size);+ std::uint64_t body_left = request.content_length.value_or(0);+ std::size_t leftover = 0;+ SetTimeout(client, SO_RCVTIMEO, options_.body_timeout_ms);+ request.read_body = [&, client](char* data, std::size_t size) -> std::ptrdiff_t {+ if (body_left == 0 || size == 0) return 0;+ if (size > body_left) size = static_cast<std::size_t>(body_left);+ if (leftover < received.size()) {+ const auto count = std::min(size, received.size() - leftover);+ std::memcpy(data, received.data() + leftover, count);+ leftover += count;+ body_left -= count;+ return static_cast<std::ptrdiff_t>(count);+ }+ while (!stop_.load()) {+ const auto count = ::recv(client, data, size, 0);+ if (count < 0 && errno == EINTR) continue;+ if (count <= 0) return -1;+ body_left -= static_cast<std::uint64_t>(count);+ return count;+ }+ return -1;+ };handler_(request, response);if (!response.started()) SendError(response, 500, "No answer.");+ // An answer sent before the whole body was read (a refused upload): closing now could reset the connection+ // and lose the answer, so read a bounded amount more while the client finishes its side.+ if (body_left > 0 && !stop_.load()) {+ ::shutdown(client, SHUT_WR);+ SetTimeout(client, SO_RCVTIMEO, 500);+ const auto until = std::chrono::steady_clock::now() + std::chrono::seconds(2);+ std::uint64_t drained = 0;+ while (body_left > 0 && drained < 16 * 1024 * 1024 && !stop_.load() && std::chrono::steady_clock::now() < until) {+ const auto count = ::recv(client, buffer.data(), buffer.size(), 0);+ if (count <= 0) break;+ drained += static_cast<std::uint64_t>(count);+ body_left -= std::min<std::uint64_t>(body_left, static_cast<std::uint64_t>(count));+ }+ }} else if (parsed == ParseResult::kTooLarge) {SendError(response, 431, "The request is too large.");} else if (parsed == ParseResult::kBadRequest) {diff --git a/src/web/server.h b/src/web/server.hindex eaa1786..2708a69 100644--- a/src/web/server.h+++ b/src/web/server.h@@ -4,11 +4,13 @@#include "web/http.h"#include <atomic>+#include <condition_variable>#include <cstdint>#include <functional>#include <mutex>#include <string>#include <thread>+#include <vector>namespace playden::web {@@ -17,9 +19,14 @@ struct ServerOptions {std::uint16_t first_port = 7031;std::uint16_t last_port = 7039;bool loopback_only = false; // 127.0.0.1 instead of every address (tests)- int backlog = 4; // connections waiting while one is served+ int backlog = 8; // connections waiting while every worker is busy+ int workers = 6; // connections served at onceint read_timeout_ms = 10'000;int write_timeout_ms = 10'000;+ // A connection that has sent nothing gives up after this (a browser's spare connection), so it doesn't hold a worker.+ int silent_timeout_ms = 2'000;+ // A request body may go quiet for this long.+ int body_timeout_ms = 30'000;// How often the accept wait looks at Stop. Closing a listening socket does not reliably wake a// blocked accept, so the worker never blocks longer than this.int poll_interval_ms = 250;@@ -29,8 +36,9 @@ struct ServerOptions {std::function<void(const std::string&)> log;};-// A small HTTP/1.1 server: one worker accepts and serves one connection at a time, reading the-// request, routing it and writing the answer, then closing. No keep-alive.+// A small HTTP/1.1 server: one thread accepts, and a fixed pool of workers each serves one connection at a+// time, reading the request, routing it and writing the answer, then closing. No keep-alive. Handlers run on the+// workers, at the same time. Every worker busy: new connections wait in the listen backlog.class Server {public:using Handler = std::function<void(const Request& request, Response& response)>;@@ -44,11 +52,16 @@ class Server {bool Start(const ServerOptions& options, Handler handler, std::string* error);// Stops accepting, cuts the connection being served (a slow download included), and closes the socket.void Stop();- bool running() const { return worker_.joinable(); }+ bool running() const { return acceptor_.joinable(); }std::uint16_t port() const { return port_; }private:+ struct Accepted {+ int fd = -1;+ std::string ip;+ };void Run();+ void Work();void Serve(int client, const std::string& client_ip);void Log(const std::string& line) const;ServerOptions options_;@@ -56,9 +69,13 @@ class Server {int listener_ = -1;std::uint16_t port_ = 0;std::atomic<bool> stop_{false};- std::mutex client_mutex_;- int client_ = -1; // the connection being served, so Stop can cut it- std::thread worker_;+ std::mutex mutex_;+ std::condition_variable changed_;+ std::vector<Accepted> waiting_; // accepted, for the next free worker+ int idle_ = 0; // workers waiting for a connection+ std::vector<int> clients_; // every open connection, so Stop can cut them+ std::thread acceptor_;+ std::vector<std::thread> workers_;};} // namespace playden::webdiff --git a/src/web/service.cpp b/src/web/service.cppindex 07f5848..571e2fc 100644--- a/src/web/service.cpp+++ b/src/web/service.cpp@@ -7,6 +7,37 @@namespace playden::web {namespace {const std::vector<std::pair<std::string, std::string>> kNoStore = {{"Cache-Control", "no-store"}};++// The host part of a Host or Origin authority: an IPv4 literal or localhost. A DNS rebinding site reaches this+// server under its own domain name, and is same-site with itself, so a name is refused on every route. A request+// with no Host at all isn't from a browser.+bool LocalAuthority(std::string_view authority) {+ const auto colon = authority.find(':');+ const auto host = authority.substr(0, colon);+ if (host == "localhost") return true;+ int parts = 0, digits = 0, value = 0;+ for (const char c : host) {+ if (c == '.') {+ if (digits == 0) return false;+ ++parts;+ digits = value = 0;+ } else if (c >= '0' && c <= '9') {+ value = value * 10 + (c - '0');+ if (++digits > 3 || value > 255) return false;+ } else {+ return false;+ }+ }+ return parts == 3 && digits > 0;+}++// An Origin, when sent, must be this server's own: the page's address, as Host names it.+bool SameOrigin(const Request& request) {+ const auto origin = HeaderValue(request, "origin");+ if (!origin) return true;+ const auto host = HeaderValue(request, "host");+ return host && (*origin == "http://" + *host);+}} // namespaceService::Service(ServiceConfig config) : config_(std::move(config)), logs_(config_.paths) {@@ -124,7 +155,13 @@ void Service::Shutdown() {if (worker_.joinable()) worker_.join();}-void Service::Handle(const Request& request, Response& response) { router_.Handle(request, response); }+void Service::Handle(const Request& request, Response& response) {+ if (const auto host = HeaderValue(request, "host"); host && !LocalAuthority(*host))+ return SendError(response, 403, "Open this page by the PS5's IP address.");+ if (request.method == Method::kPost && !SameOrigin(request))+ return SendError(response, 403, "This request came from another site.");+ router_.Handle(request, response);+}void Service::Run() {using Clock = std::chrono::steady_clock;diff --git a/src/web/service.h b/src/web/service.hindex f3c02d7..ee67eef 100644--- a/src/web/service.h+++ b/src/web/service.h@@ -55,7 +55,7 @@ class Service {// Stops the server and the worker. Safe to call twice.void Shutdown();- // Routes one request, as the server's worker does (tests call it directly).+ // Routes one request, as the server's workers do, at the same time (tests call it directly).void Handle(const Request& request, Response& response);private:diff --git a/tests/web_request_test.cpp b/tests/web_request_test.cppindex cf779b2..27bad7a 100644--- a/tests/web_request_test.cpp+++ b/tests/web_request_test.cpp@@ -79,5 +79,39 @@ int main() {// A client gone mid-answer: the response says so and writes nothing more.Response gone([](const char*, std::size_t) { return false; }, false);CHECK(!gone.Start(200, "text/plain", std::nullopt) && gone.failed() && !gone.Body("x"));+ // The body's length, and where the body starts.+ {+ Request request;+ std::size_t head = 0;+ const std::string text = "POST /u HTTP/1.1\r\nContent-Length: 12\r\n\r\nbody";+ CHECK(ParseRequestHead(text, &request, &head) == ParseResult::kOk);+ CHECK(request.content_length == std::uint64_t{12} && text.substr(head) == "body");+ CHECK(HeaderValue(request, "content-length") == std::string("12") && !HeaderValue(request, "origin"));+ Request none;+ CHECK(ParseRequestHead("GET / HTTP/1.1\r\n\r\n", &none) == ParseResult::kOk && !none.content_length);+ for (const char* bad : {"POST / HTTP/1.1\r\nContent-Length: 1\r\nContent-Length: 2\r\n\r\n",+ "POST / HTTP/1.1\r\nContent-Length: x\r\n\r\n", "POST / HTTP/1.1\r\nContent-Length: -1\r\n\r\n",+ "POST / HTTP/1.1\r\nContent-Length: 12345678901234567890\r\n\r\n",+ "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"}) {+ Request refused;+ CHECK(ParseRequestHead(bad, &refused) == ParseResult::kBadRequest);+ }+ }+ // A chunked answer: each piece framed, the end only after FinishChunks; HEAD sends neither.+ {+ std::string out;+ Response response([&out](const char* data, std::size_t size) { out.append(data, size); return true; }, false);+ CHECK(response.StartChunked(200, "application/zip"));+ CHECK(response.Body("hello"));+ CHECK(out.find("Transfer-Encoding: chunked\r\n") != std::string::npos);+ CHECK(out.size() > 10 && out.compare(out.size() - 10, 10, "5\r\nhello\r\n") == 0);+ CHECK(response.FinishChunks());+ CHECK(out.compare(out.size() - 5, 5, "0\r\n\r\n") == 0);+ CHECK(response.body_bytes() == 5);+ std::string head;+ Response head_only([&head](const char* data, std::size_t size) { head.append(data, size); return true; }, true);+ CHECK(head_only.StartChunked(200, "application/zip") && head_only.Body("hello") && head_only.FinishChunks());+ CHECK(head.find("hello") == std::string::npos && head.find("chunked") == std::string::npos);+ }std::puts("web_request: ok");}diff --git a/tests/web_server_test.cpp b/tests/web_server_test.cppindex 22837e5..bd88512 100644--- a/tests/web_server_test.cpp+++ b/tests/web_server_test.cpp@@ -186,6 +186,127 @@ int main() {::close(fd);}+ // Several connections at once: a client that stalls doesn't hold up the next.+ {+ ServerOptions pool = options;+ pool.first_port = pool.last_port = 0;+ pool.workers = 3;+ pool.read_timeout_ms = 30'000;+ pool.silent_timeout_ms = 30'000;+ Server busy;+ CHECK(busy.Start(pool, [](const Request&, Response& response) { response.Send(200, "text/plain", "x"); }, &error));+ const int stalled = Connect(busy.port());+ CHECK(::send(stalled, "GET / HTTP/1.1\r\n", 16, 0) == 16);+ const int silent = Connect(busy.port());+ std::this_thread::sleep_for(std::chrono::milliseconds(150));+ const auto started = std::chrono::steady_clock::now();+ CHECK(Exchange(busy.port(), "GET / HTTP/1.1\r\n\r\n").rfind("HTTP/1.1 200", 0) == 0);+ CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(1));+ // Every worker taken: the next waits in the backlog, and Stop still returns promptly.+ const int second = Connect(busy.port());+ CHECK(::send(second, "GET / HTTP/1.1\r\n", 16, 0) == 16);+ const int queued = Connect(busy.port());+ std::this_thread::sleep_for(std::chrono::milliseconds(150));+ const auto cut = std::chrono::steady_clock::now();+ busy.Stop();+ CHECK(std::chrono::steady_clock::now() - cut < std::chrono::seconds(2));+ for (const int fd : {stalled, silent, second, queued}) ::close(fd);+ }+ // A connection that sends nothing gives its worker back after the silent time.+ {+ ServerOptions quiet = options;+ quiet.first_port = quiet.last_port = 0;+ quiet.workers = 1;+ quiet.read_timeout_ms = 30'000;+ quiet.silent_timeout_ms = 200;+ Server one;+ CHECK(one.Start(quiet, [](const Request&, Response& response) { response.Send(200, "text/plain", "x"); }, &error));+ const int silent = Connect(one.port());+ std::this_thread::sleep_for(std::chrono::milliseconds(50));+ const auto started = std::chrono::steady_clock::now();+ CHECK(Exchange(one.port(), "GET / HTTP/1.1\r\n\r\n").rfind("HTTP/1.1 200", 0) == 0);+ CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(2));+ ::close(silent);+ one.Stop();+ }+ // The body: what came with the head first, split anywhere, at most the declared length.+ {+ ServerOptions bodies = options;+ bodies.first_port = bodies.last_port = 0;+ bodies.body_timeout_ms = 300;+ std::mutex read_mutex;+ std::string read_text;+ std::ptrdiff_t last = 99;+ Server reading;+ CHECK(reading.Start(bodies, [&](const Request& request, Response& response) {+ std::string text;+ char buffer[7];+ std::ptrdiff_t count;+ while ((count = request.read_body(buffer, sizeof buffer)) > 0) text.append(buffer, static_cast<std::size_t>(count));+ {+ std::lock_guard<std::mutex> lock(read_mutex);+ read_text = text;+ last = count;+ }+ response.Send(200, "text/plain", "read");+ }, &error));+ const std::string payload = "0123456789abcdefghij";+ const std::string head = "POST /u HTTP/1.1\r\nContent-Length: " + std::to_string(payload.size()) + "\r\n\r\n";+ const std::string whole = head + payload + "EXTRA";+ for (const std::size_t split : {std::size_t{5}, head.size() - 1, head.size(), head.size() + 3, head.size() + 19}) {+ const int fd = Connect(reading.port());+ CHECK(::send(fd, whole.data(), split, 0) == static_cast<ssize_t>(split));+ std::this_thread::sleep_for(std::chrono::milliseconds(30));+ CHECK(::send(fd, whole.data() + split, whole.size() - split, 0) == static_cast<ssize_t>(whole.size() - split));+ std::string answer;+ char buffer[256];+ ssize_t count;+ while ((count = ::recv(fd, buffer, sizeof buffer, 0)) > 0) answer.append(buffer, static_cast<std::size_t>(count));+ ::close(fd);+ CHECK(answer.rfind("HTTP/1.1 200", 0) == 0);+ std::lock_guard<std::mutex> lock(read_mutex);+ CHECK(read_text == payload && last == 0);+ }+ // A short body: the read fails once the client goes quiet, instead of waiting for ever.+ {+ const int fd = Connect(reading.port());+ const std::string shorter = head + "012";+ CHECK(::send(fd, shorter.data(), shorter.size(), 0) == static_cast<ssize_t>(shorter.size()));+ std::string answer;+ char buffer[256];+ ssize_t count;+ while ((count = ::recv(fd, buffer, sizeof buffer, 0)) > 0) answer.append(buffer, static_cast<std::size_t>(count));+ ::close(fd);+ std::lock_guard<std::mutex> lock(read_mutex);+ CHECK(read_text == "012" && last == -1);+ }+ reading.Stop();+ }+ // An answer before the body: the client still gets it, after sending all it had.+ {+ ServerOptions refuse = options;+ refuse.first_port = refuse.last_port = 0;+ Server refusing;+ CHECK(refusing.Start(refuse, [](const Request&, Response& response) { response.Send(409, "text/plain", "no\n"); }, &error));+ const int fd = Connect(refusing.port());+ const std::string payload(256 * 1024, 'p');+ const std::string head = "POST /u HTTP/1.1\r\nContent-Length: " + std::to_string(payload.size()) + "\r\n\r\n";+ CHECK(::send(fd, head.data(), head.size(), 0) == static_cast<ssize_t>(head.size()));+ std::size_t sent = 0;+ while (sent < payload.size()) {+ const auto count = ::send(fd, payload.data() + sent, payload.size() - sent, 0);+ if (count <= 0) break;+ sent += static_cast<std::size_t>(count);+ }+ std::string answer;+ char buffer[256];+ ssize_t count;+ while ((count = ::recv(fd, buffer, sizeof buffer, 0)) > 0) answer.append(buffer, static_cast<std::size_t>(count));+ ::close(fd);+ CHECK(answer.rfind("HTTP/1.1 409", 0) == 0);+ refusing.Stop();+ }+// Started again after a stop.options.first_port = options.last_port = 0;CHECK(server.Start(options, [&router](const Request& request, Response& response) { router.Handle(request, response); }, &error));diff --git a/tests/web_service_test.cpp b/tests/web_service_test.cppindex cb48413..cb77c6e 100644--- a/tests/web_service_test.cpp+++ b/tests/web_service_test.cpp@@ -36,7 +36,7 @@ std::string Get(std::uint16_t port, const std::string& head) {if (fd >= 0) ::close(fd);return {};}- const std::string request = head + " HTTP/1.1\r\nHost: x\r\n\r\n";+ const std::string request = head + " HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";CHECK(::send(fd, request.data(), request.size(), 0) == static_cast<ssize_t>(request.size()));std::string answer;char buffer[8192];@@ -146,6 +146,35 @@ int main() {}// Quit: POST with the header only; the caller takes the request once.+ // A name in Host (a DNS rebinding site reaching this server) is refused on every route; addresses are not.+ {+ const auto raw = [&](const std::string& text) {+ const int fd = ::socket(AF_INET, SOCK_STREAM, 0);+ sockaddr_in address{};+ address.sin_family = AF_INET;+ address.sin_port = htons(on.port);+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ CHECK(fd >= 0 && ::connect(fd, reinterpret_cast<sockaddr*>(&address), sizeof address) == 0);+ CHECK(::send(fd, text.data(), text.size(), 0) == static_cast<ssize_t>(text.size()));+ std::string answer;+ char buffer[1024];+ ssize_t count;+ while ((count = ::recv(fd, buffer, sizeof buffer, 0)) > 0) answer.append(buffer, static_cast<std::size_t>(count));+ ::close(fd);+ return answer;+ };+ for (const char* host : {"evil.example", "evil.example:7031", "1.2.3", "1.2.3.4.5", "1.2.3.999", "1.2.3.x", "ps5.local"})+ CHECK(raw(std::string("GET /api/status HTTP/1.1\r\nHost: ") + host + "\r\n\r\n").rfind("HTTP/1.1 403", 0) == 0);+ for (const char* host : {"192.168.1.40", "192.168.1.40:7031", "localhost", "localhost:7031"})+ CHECK(raw(std::string("GET /api/status HTTP/1.1\r\nHost: ") + host + "\r\n\r\n").rfind("HTTP/1.1 200", 0) == 0);+ CHECK(raw("GET /api/status HTTP/1.1\r\n\r\n").rfind("HTTP/1.1 200", 0) == 0);+ // A POST from another origin is refused before it reaches its route.+ const std::string quit = "POST /api/quit HTTP/1.1\r\nHost: 10.0.0.2:7031\r\nX-Playden-Action: quit\r\nContent-Length: 0\r\n";+ CHECK(raw(quit + "Origin: http://evil.example\r\n\r\n").rfind("HTTP/1.1 403", 0) == 0);+ CHECK(!service.TakeQuitRequest());+ CHECK(raw(quit + "Origin: http://10.0.0.2:7031\r\n\r\n").rfind("HTTP/1.1 202", 0) == 0);+ CHECK(service.TakeQuitRequest());+ }CHECK(Get(on.port, "GET /api/quit").rfind("HTTP/1.1 405", 0) == 0);CHECK(Get(on.port, "POST /api/quit").rfind("HTTP/1.1 403", 0) == 0 && !service.TakeQuitRequest());{