From b64d4c5222c89d50673f3323b349b701383ba9e3 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:23:14 +0100 Subject: [PATCH 1/5] Serve files and dynamic routes by byte ranges (#455) Unencoded files of known size answer a single Range with 206 and Content-Range, or 416 past the end, and read only the selected bytes. If-Range compares a strong ETag derived from a native file's size and modification time. Several ranges and malformed ranges are answered in full; encoded responses say Accept-Ranges: none. fs::File gains seek and entityTag, and routes serve files by ranges with http::fileReply. --- docs/CHANGELOG.md | 11 +- docs/HTTP_ASSETS.md | 32 +- ...DR-002-systemes-de-fichiers-composables.md | 1 + docs/adr/ADR-020-services-systeme.md | 3 + docs/adr/README.md | 4 +- include/webfront/http/HTTPServer.hpp | 100 +++- include/webfront/http/Ranges.hpp | 113 +++++ include/webfront/system/DefaultFS.hpp | 5 +- include/webfront/system/FileSystem.hpp | 37 +- include/webfront/system/NativeFS.hpp | 5 +- test/unit/CMakeLists.txt | 2 +- test/unit/HTTPRangeTests.cpp | 461 ++++++++++++++++++ test/web/JasmineTest.cpp | 40 +- test/web/suite/specs/webfront-specs.mjs | 82 ++++ 14 files changed, 879 insertions(+), 17 deletions(-) create mode 100644 include/webfront/http/Ranges.hpp create mode 100644 test/unit/HTTPRangeTests.cpp diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 3d237d5a..9f618d25 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -24,7 +24,16 @@ prefixes are refused at registration; other methods get 405. Headers that could split the response, or that the server owns (`Content-Length`, `Connection`, `Transfer-Encoding`), turn into a 500. Unencoded files of known size (`fs::File::knownSize()`) are streamed the same way, so serving a large file no longer loads it into memory; encoded - files are still read whole. `Range` (#455) and the binding to a connection (#469) follow. + files are still read whole. The binding to a connection (#469) follows; `Range` is described below (#455). + +- HTTP server: byte ranges (#455, ADR-020 prerequisite). Unencoded files of known size are served by `Range` (`bytes=a-b`, + `a-`, `-n`): `206` with `Content-Range` and only the selected bytes read, `416` with `bytes */size` for a range that + starts past the end, and `Accept-Ranges: bytes`; `HEAD` announces the same headers. Several ranges, a unit other than + `bytes` and malformed ranges are ignored (`200`, whole file); encoded or decoded responses say `Accept-Ranges: none`. + `If-Range` compares the strong `ETag` that `fs::File` now derives from a native file's size and modification time + (`File(ifstream, path)`, used by `NativeDebugFS` and the development root); a changed file is sent in full. `fs::File` + gains `seek` and `entityTag`. Dynamic routes serve a file by ranges with `http::fileReply`, or `http::range::select`. The binding + to a connection (#469) follows. - Embedded frontends: `alert`, `confirm`, `prompt` and `beforeunload` (`beforeunload` is not handled under WKWebView, see `docs/FRONTENDS.md`; #452, ADR-020 rule 6). WKWebView implements the three `WKUIDelegate` panel methods (an `NSAlert` sheet of the window; without them these calls did nothing); WebKitGTK, CEF and diff --git a/docs/HTTP_ASSETS.md b/docs/HTTP_ASSETS.md index 6815a478..514b618c 100644 --- a/docs/HTTP_ASSETS.md +++ b/docs/HTTP_ASSETS.md @@ -45,8 +45,36 @@ connection closes) and a `body` callback filling the next chunk (0 ends it). The thread, so a slow disk does not delay other connections. Route work runs on its own pool of 4 threads and the files of the providers on another of 2: a handler that blocks for seconds delays at most the routes queued behind four such handlers, never `WebFront.js` or a page. A route precedes the file providers, never masks the embedded `WebFront.js`, and overlapping prefixes are refused when registered. Other methods get 405; a handler that throws, or sets a header that could split the response or that the server owns (`Content-Length`, `Connection`, `Transfer-Encoding`), gets -500. The registration handle removes the route when destroyed; a request already running keeps its handler. `Range` -requests (#455) and the binding of a request to a connection (#469) are not part of this mechanism yet. +500. The registration handle removes the route when destroyed; a request already running keeps its handler. The +binding of a request to a connection (#469) is not part of this mechanism yet. + +## Byte ranges (#455) + +An unencoded file of known size, from any provider, is served by ranges (RFC 9110 §14) and says so with +`Accept-Ranges: bytes`. A single `Range: bytes=a-b`, `a-` or `-n` answers `206 Partial Content` with `Content-Range` +and the length of that part; only those bytes are read, on the worker, in chunks of `emissionBufferSize` (the file +positions itself with `fs::File::seek`). A range that starts at or past the end, an empty suffix (`-0`), or any range of an +empty file answers `416` with `Content-Range: bytes */size`; a last byte past the end is clamped, and a suffix longer than +the file selects all of it. `HEAD` answers like `GET` without a body, so it announces the 206 and its length. + +What the server may ignore, it ignores, and the answer is a normal `200` with the whole file: several ranges (in one +field or several), a unit other than `bytes`, a malformed or inverted range (`5-2`), and a `Range` on a response that +cannot be ranged. Multipart answers (`multipart/byteranges`) are not produced. The responses of encoded files (served as +stored with `Content-Encoding`, or decoded by the gzip fallback) carry `Accept-Ranges: none` and are never partial, like +files whose size is unknown. + +`If-Range` conditions a range on a validator. Only a strong entity tag is compared: a native file (`NativeDebugFS`, the +development document root, or any provider building `fs::File(ifstream, path)`) has the tag `"-"`, +sent as `ETag` on its 200 and 206 responses. If the tag in `If-Range` is not the file's current one, the file changed +between the two requests, so the current file is sent in full with its new tag. Embedded data and providers that +do not give a path have no tag, and a conditioned range is answered in full. The server sends no `Last-Modified`, so a date +in `If-Range` never matches (and a browser applies no heuristic freshness to development files). + +A dynamic route that serves a file, such as the services built on #454, calls `http::fileReply(request, file, contentType)`: +it applies the same rules to the route's `RouteRequest::request` and returns the `RouteReply` (200, 206 or 416) that the +handler completes with its own headers (`Cache-Control`, `Content-Disposition`...). A handler with its own storage +can use `http::range::select(request, size, entityTag)` directly. The read-only reply is repeatable: successive range +requests on one URL each open the file again. ## Validated representation cache diff --git a/docs/adr/ADR-002-systemes-de-fichiers-composables.md b/docs/adr/ADR-002-systemes-de-fichiers-composables.md index 02206ae9..8fe0728c 100644 --- a/docs/adr/ADR-002-systemes-de-fichiers-composables.md +++ b/docs/adr/ADR-002-systemes-de-fichiers-composables.md @@ -15,6 +15,7 @@ | 2.3 | 2026-10-14 | Acceptée | Ambroise Leclerc | Composition facultative des ressources des composants avec DefaultFSWith. | [40f5621](https://github.com/ambroise-leclerc/WebFront/commit/40f5621928fdd188f230bf08ff062f9557619046) | | 2.4 | 2026-10-14 | Acceptée | Ambroise Leclerc | Fournisseur PackageFS et stockage transactionnel des outils installés. | [4bcfc28](https://github.com/ambroise-leclerc/WebFront/commit/4bcfc28c7b78672603a2114a72d9decf25d36387) | | 2.5 | 2026-11-03 | Acceptée | Ambroise Leclerc | `fs::File::knownSize()` : taille connue avant lecture (données embarquées, fichier natif sur flux positionnable), pour annoncer `Content-Length` et envoyer le fichier en flux (#454). Les routes dynamiques passent après le `WebFront.js` protégé et ne peuvent pas le masquer. | Branche `454-dynamic-routes` | +| 2.6 | 2026-11-04 | Acceptée | Ambroise Leclerc | `fs::File::seek` et `entityTag()` : positionnement dans un fichier de taille connue et validateur fort (taille et date) d'un fichier natif construit avec son chemin, pour les requêtes `Range` et `If-Range` (#455). Le serveur traite les plages ; `fs::Provider` ne voit toujours pas la requête. | Branche `455-range-requests` | ## État et chronologie diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index af906c76..e7cb2b61 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -8,6 +8,7 @@ | 1.1 | 2026-11-02 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison partielle de l'étape 1 pour #451 (sélecteur de fichiers et téléchargements sous WebKitGTK, CEF, WKWebView et WebView2) ; #452 reste à faire. La section « État de l'étape 1 » distingue les preuves de validation par moteur et par révision ; `docs/FRONTENDS.md` précise les limites de couverture. | Branche `451-file-chooser-downloads` (PR #484), implémentation initiale `91049ab`, stockage privé WKWebView `52d8c68` | | 1.2 | 2026-11-03 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de #452 (`alert`, `confirm`, `prompt` partout ; `beforeunload` sauf sous WKWebView, qui n'a pas de délégué public pour lui) : l'étape 1 n'est complète qu'avec cette limite. `docs/FRONTENDS.md` précise la couverture par moteur (WKWebView et WebView2 non exécutés localement ; `beforeunload` non exercé de bout en bout et jamais demandé à la fermeture de la fenêtre). | Branche `452-script-dialogs` | | 1.3 | 2026-11-03 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de #454 (étape 2) : routes HTTP dynamiques (`addRoute`, désinscription par handle, priorité après `WebFront.js` et avant les fournisseurs, collision de préfixes refusée), envoi en flux par morceaux bornés d'une réponse produite à l'exécution et des fichiers non encodés de taille connue (`fs::File::knownSize`), gestionnaire et lectures sur un thread de travail du serveur. Les plages `Range` (#455) et la liaison à la connexion (#469) restent à faire ; elles s'appuient sur ces routes. | Branche `454-dynamic-routes` | +| 1.4 | 2026-11-04 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de #455 (étape 2) : requêtes partielles `Range` (206, 416, `Accept-Ranges`) pour les fichiers non encodés de taille connue et pour les routes dynamiques (`http::fileReply`, `http::range::select`), `If-Range` sur un `ETag` fort tiré de la taille et de la date d'un fichier natif, plages multiples servies en entier. La liaison à la connexion (#469) reste à faire. | Branche `455-range-requests` | ## État et chronologie @@ -374,6 +375,8 @@ limites par moteur. #452 est livré dans la version 1.2 (`beforeunload` n'est pa #454 est livré dans la version 1.3 : `addRoute(préfixe, gestionnaire)` répond aux `GET` et `HEAD` sous un préfixe absolu terminé par `/`, par une réponse (`http::RouteReply`) dont le corps est lu morceau par morceau sur un thread de travail du serveur, sans mémoire proportionnelle à sa taille (mesure : 128 Mio envoyés sans croissance du pic mémoire). Les fichiers non encodés des fournisseurs dont la taille est connue sont envoyés de la même façon ; les fichiers encodés restent lus en entier pour la négociation de codage (ADR-009). Le gestionnaire ne reçoit ni jeton ni identité de connexion : ils viennent de #469. +#455 est livré dans la version 1.4 : un fichier non encodé de taille connue est servi par plages (`Range: bytes=a-b`, `a-`, `-n` sur une seule plage : `206` avec `Content-Range`, `416` pour une plage qui commence après la fin, `Accept-Ranges: bytes`), en ne lisant que la plage demandée. Les plages multiples sont servies en entier (`200`) ; il n'y a pas de réponse `multipart/byteranges`. Les réponses encodées ou décodées par le repli annoncent `Accept-Ranges: none`. `If-Range` n'accepte qu'un `ETag` fort (taille et date d'un fichier natif) ; sans validateur (données embarquées), la plage conditionnée est servie en entier. Une route dynamique sert un fichier par plages avec `http::fileReply`. Le jeton de lecture reste donc réutilisable pour plusieurs requêtes `Range` ; leur liaison à la connexion propriétaire vient de #469. + Après l'étape 4, le premier service (sélecteur HTML, poignées, import et export côté client) fera l'objet de sa propre épique ; les dialogues natifs suivront l'étape 5. `PUT`/`POST` ne sont pas des préalables : les écritures passent par des tableaux typés en morceaux ; leur ajout au serveur, utile aux très gros envois en flux et aux formulaires sans diff --git a/docs/adr/README.md b/docs/adr/README.md index 3d40d78e..69852495 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -42,7 +42,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | ADR | Decision | Status | Initial creation | Current version | | --- | --- | --- | --- | --- | | [ADR-001](ADR-001-coeur-cpp23-header-only.md) | A header-only C++23 core embedded in the application | Accepted | 2020-04-19 | 1.5 — 2026-10-13 | -| [ADR-002](ADR-002-systemes-de-fichiers-composables.md) | An abstract, composable filesystem as the foundation for portability | Accepted | 2023-03-16 | 2.5 — 2026-11-03 | +| [ADR-002](ADR-002-systemes-de-fichiers-composables.md) | An abstract, composable filesystem as the foundation for portability | Accepted | 2023-03-16 | 2.6 — 2026-11-04 | | [ADR-003](ADR-003-protocole-binaire-et-bornes.md) | A shared, typed and bounded binary protocol | Accepted through 1.13; 1.14 and 1.15 proposed | 2022-02-06 | 1.15 — 2026-11-04 | | [ADR-004](ADR-004-appels-asynchrones-et-erreurs.md) | Asynchronous calls with deliberately asymmetric contracts | Accepted | 2022-02-06 | 2.4 — 2026-10-18 | | [ADR-005](ADR-005-evolution-reseau-asio-stdnet.md) | From standalone ASIO to stdnet: anticipating standard networking without blocking progress | Accepted through 3.1; 3.2 proposed | 2022-01-21 | 3.2 — 2026-10-26 | @@ -60,7 +60,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-017](ADR-017-acces-direct-aux-frontends.md) | Direct access to embedded frontends, with HTML kept normative | Proposed | 2026-10-24 | 1.1 — 2026-10-25 | | [ADR-018](ADR-018-acces-au-dom.md) | DOM access from C++ through a bounded mutation stream, without contesting the DOM of UI libraries | Proposed, partially superseded, partially delivered | 2026-10-26 | 1.5 — 2026-10-30 | | [ADR-019](ADR-019-developpement-automatisable-et-agents.md) | Automating the developer environment through shared operations and an optional local MCP adapter | Accepted | 2026-10-28 | 1.2 — 2026-10-29 | -| [ADR-020](ADR-020-services-systeme.md) | System services (files, clipboard, shell, notifications…) through optional C++ portals with per-connection backends, granting handles rather than paths | Proposed | 2026-10-31 | 1.3 — 2026-11-03 | +| [ADR-020](ADR-020-services-systeme.md) | System services (files, clipboard, shell, notifications…) through optional C++ portals with per-connection backends, granting handles rather than paths | Proposed | 2026-10-31 | 1.4 — 2026-11-04 | | [ADR-021](ADR-021-publication-de-l-environnement-developpeur.md) | Simplifying the publication of the developer environment: automate the release, keep pinned hashes, no dedicated server | Accepted (domain delivered; phase 1 to implement) | 2026-11-02 | 1.0 — 2026-11-02 | Numbering follows the reading topics; milestones and individual file histories provide diff --git a/include/webfront/http/HTTPServer.hpp b/include/webfront/http/HTTPServer.hpp index 88f2463c..619134bb 100644 --- a/include/webfront/http/HTTPServer.hpp +++ b/include/webfront/http/HTTPServer.hpp @@ -16,6 +16,7 @@ #include "GzipCache.hpp" #include "GzipExecutor.hpp" #include "MimeType.hpp" +#include "Ranges.hpp" #include "WebSocket.hpp" #include @@ -221,11 +222,13 @@ struct Response : Headers { enum StatusCode : uint16_t { switchingProtocols = 101, ok = 200, + partialContent = 206, badRequest = 400, forbidden = 403, notFound = 404, methodNotAllowed = 405, notAcceptable = 406, + rangeNotSatisfiable = 416, internalServerError = 500, notImplemented = 501, serviceUnavailable = 503, @@ -274,14 +277,16 @@ struct Response : Headers { mutable std::string httpStatus; [[nodiscard]] static std::string toString(StatusCode code) { - static constexpr std::array, 11> names{ + static constexpr std::array, 13> names{ {{switchingProtocols, "Switching Protocols"}, {ok, "OK"}, + {partialContent, "Partial Content"}, {badRequest, "Bad Request"}, {forbidden, "Forbidden"}, {notFound, "Not Found"}, {methodNotAllowed, "Method Not Allowed"}, {notAcceptable, "Not Acceptable"}, + {rangeNotSatisfiable, "Range Not Satisfiable"}, {internalServerError, "Internal Server Error"}, {notImplemented, "Not Implemented"}, {serviceUnavailable, "Service Unavailable"}, @@ -460,6 +465,53 @@ inline void validateReply(const RouteReply& reply) { } // namespace routing +/// The reply of a route that serves `file` as `contentType`, with the byte ranges of RFC 9110 §14: `Range` selects +/// one part (206 with `Content-Range`, 416 when it starts past the end), `If-Range` conditions it on the file's +/// entity tag, several ranges are answered in full, and only the selected bytes are read, in chunks, by the server. +/// A file that is encoded or has no known size is answered in full with `Accept-Ranges: none`. +/// The handler adds what it alone knows (`Cache-Control`, `Content-Disposition`...). +[[nodiscard]] inline RouteReply fileReply(const Request& request, fs::File file, std::string contentType) { + RouteReply reply; + reply.headers.emplace_back("Content-Type", std::move(contentType)); + const auto size = file.knownSize(); + if (file.isEncoded() || !size) { + reply.headers.emplace_back("Accept-Ranges", "none"); + reply.body = [file = std::make_shared(std::move(file))](std::span out) { return file->read(out); }; + reply.contentLength = size; + return reply; + } + reply.headers.emplace_back("Accept-Ranges", "bytes"); + if (file.entityTag()) reply.headers.emplace_back("ETag", *file.entityTag()); + const auto selection = range::select(request, *size, file.entityTag()); + if (selection.outcome == range::Outcome::unsatisfiable) { + reply.status = Response::rangeNotSatisfiable; + reply.headers.emplace_back("Content-Range", range::unsatisfiedContentRange(*size)); + reply.contentLength = 0; + return reply; + } + std::uint64_t first = 0; + std::uint64_t length = *size; + if (selection.outcome == range::Outcome::partial) { + reply.status = Response::partialContent; + reply.headers.emplace_back("Content-Range", range::contentRange(selection, *size)); + first = selection.first; + length = selection.length; + } + reply.contentLength = length; + reply.body = [file = std::make_shared(std::move(file)), first, remaining = length, positioned = first == 0](std::span out) mutable { + if (!positioned) { + if (!file->seek(first)) throw std::runtime_error("The file cannot seek"); + positioned = true; + } + const auto count = static_cast(std::min(out.size(), remaining)); + if (count == 0) return std::size_t{0}; + const auto read = file->read(out.first(count)); + remaining -= read; + return read; + }; + return reply; +} + template class RequestHandler { public: @@ -481,6 +533,10 @@ class RequestHandler { bool identityFallback = false; /// An unencoded file of known size, left unread to be streamed (asynchronous requests only). std::unique_ptr file{}; + /// The part of `file` a `Range` request selected: its first byte, and how many bytes follow (206). + bool partial = false; + std::uint64_t offset = 0; + std::uint64_t length = 0; std::size_t limit = maxDecodedAssetSize(); }; @@ -520,13 +576,15 @@ class RequestHandler { result.needsDecode = false; return result; } - response.statusCode = Response::ok; + response.statusCode = result.partial ? Response::partialContent : Response::ok; response.headers.emplace_back("Content-Type", MimeType(requestPath->extension().string()).toString()); if (!result.needsDecode) { if (!response.getHeaderValue("Content-Length")) response.headers.emplace_back("Content-Length", std::to_string(response.content.size())); if (result.head) response.content.clear(); } + // Only an unencoded file of known size is served by ranges, and it announced them when it was opened. + if (!response.getHeaderValue("Accept-Ranges")) response.headers.emplace_back("Accept-Ranges", "none"); return result; } @@ -586,7 +644,23 @@ class RequestHandler { prepared.identityFallback = fallback; if (asynchronous && !file->isEncoded()) { if (const auto size = file->knownSize()) { - response.headers.emplace_back("Content-Length", std::to_string(*size)); + response.headers.emplace_back("Accept-Ranges", "bytes"); + if (file->entityTag()) response.headers.emplace_back("ETag", *file->entityTag()); + const auto selection = range::select(request, *size, file->entityTag()); + if (selection.outcome == range::Outcome::unsatisfiable) { + auto unsatisfiable = Response::getStatusResponse(Response::rangeNotSatisfiable); + unsatisfiable.headers.emplace_back("Content-Range", range::unsatisfiedContentRange(*size)); + unsatisfiable.headers.emplace_back("Accept-Ranges", "bytes"); + return unsatisfiable; + } + prepared.length = *size; + if (selection.outcome == range::Outcome::partial) { + prepared.partial = true; + prepared.offset = selection.first; + prepared.length = selection.length; + response.headers.emplace_back("Content-Range", range::contentRange(selection, *size)); + } + response.headers.emplace_back("Content-Length", std::to_string(prepared.length)); if (prepared.head) return {}; prepared.file = std::make_unique(std::move(*file)); return {}; @@ -872,6 +946,7 @@ class Server { Request request; std::optional::Lease> lease; std::unique_ptr streamed; + std::uint64_t streamOffset = 0, streamLength = 0; bool head = false; Response response; try { @@ -900,7 +975,11 @@ class Server { prepared.response.headers.emplace_back("Vary", "Accept-Encoding"); } } - if (prepared.response.statusCode == Response::ok) streamed = std::move(prepared.file); + if (prepared.response.statusCode == Response::ok || prepared.response.statusCode == Response::partialContent) { + streamOffset = prepared.offset; + streamLength = prepared.length; + streamed = std::move(prepared.file); + } response = std::move(prepared.response); } log::info(" responding http {}", static_cast(response.statusCode)); @@ -923,7 +1002,18 @@ class Server { if (head) response.content.clear(); // an error page keeps its Content-Length; HEAD never has a body co_await Net::Send(socket, response.toBuffers()); if (streamed) - co_await streamBody(fileWorker, socket, [&file = *streamed](std::span out) { return file.read(out); }, streamed->knownSize(), "File response"); + co_await streamBody(fileWorker, socket, [&file = *streamed, offset = streamOffset, remaining = streamLength, + positioned = streamOffset == 0](std::span out) mutable { + if (!positioned) { + if (!file.seek(offset)) throw std::runtime_error("The file cannot seek"); + positioned = true; + } + const auto count = static_cast(std::min(out.size(), remaining)); + if (count == 0) return std::size_t{0}; + const auto read = file.read(out.first(count)); + remaining -= read; + return read; + }, streamLength, "File response"); if (response.statusCode != Response::switchingProtocols || tasks.stopRequested()) socket.shutdown(Net::Socket::shutdown_both); // a stopped server hands nothing over: its drain would never end else if (upgradeHandler) diff --git a/include/webfront/http/Ranges.hpp b/include/webfront/http/Ranges.hpp new file mode 100644 index 00000000..4f6c546a --- /dev/null +++ b/include/webfront/http/Ranges.hpp @@ -0,0 +1,113 @@ +/// @brief Byte range requests (RFC 9110 §14): which part of a representation a `Range` header selects. +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace webfront::http::range { + +enum class Outcome { + whole, ///< No usable range: answer 200 with the entire representation. + partial, ///< Answer 206 with `[first, first + length)`. + unsatisfiable ///< Answer 416. +}; + +struct Selection { + Outcome outcome = Outcome::whole; + std::uint64_t first = 0; + std::uint64_t length = 0; +}; + +namespace detail { + +inline std::string_view trim(std::string_view text) { + while (!text.empty() && (text.front() == ' ' || text.front() == '\t')) text.remove_prefix(1); + while (!text.empty() && (text.back() == ' ' || text.back() == '\t')) text.remove_suffix(1); + return text; +} + +/// Digits only; a number too large for 64 bits saturates, which every comparison below treats as "past the end". +inline std::optional number(std::string_view digits) { + if (digits.empty()) return {}; + std::uint64_t value = 0; + for (const char c : digits) { + if (c < '0' || c > '9') return {}; + const auto digit = static_cast(c - '0'); + value = value > (std::numeric_limits::max() - digit) / 10 ? std::numeric_limits::max() : value * 10 + digit; + } + return value; +} + +inline bool startsWithBytes(std::string_view spec) { + constexpr std::string_view unit = "bytes="; + return spec.size() >= unit.size() && std::equal(unit.begin(), unit.end(), spec.begin(), [](char expected, char c) { + return expected == (c >= 'A' && c <= 'Z' ? static_cast(c - 'A' + 'a') : c); + }); +} + +} // namespace detail + +/// The part of a representation of `size` bytes that the request asks for. +/// +/// Anything the server may ignore is ignored, and the whole representation is answered: a unit other than `bytes`, a +/// malformed or inverted range, several ranges (in one field or several fields), and a range conditioned by an +/// `If-Range` that the representation's validator does not strictly match. Only a single, well-formed range that +/// starts past the end (or an empty suffix) is unsatisfiable. +/// @tparam Fields a type with `getHeadersValues(name)`, such as `http::Request` +/// @param entityTag the strong entity tag of the representation, quoted, when it has one +template +[[nodiscard]] Selection select(const Fields& request, std::uint64_t size, const std::optional& entityTag) { + const auto ranges = request.getHeadersValues("Range"); + if (ranges.size() != 1) return {}; + + const auto conditions = request.getHeadersValues("If-Range"); + if (conditions.size() > 1) return {}; + if (!conditions.empty()) { + // A date cannot match: the representation has no Last-Modified. A weak tag never matches (strong comparison). + const auto condition = detail::trim(conditions.front()); + if (!entityTag || condition != *entityTag) return {}; + } + + auto spec = detail::trim(ranges.front()); + if (!detail::startsWithBytes(spec)) return {}; + spec.remove_prefix(6); + if (spec.find(',') != std::string_view::npos) return {}; + const auto dash = spec.find('-'); + if (dash == std::string_view::npos) return {}; + const auto firstText = spec.substr(0, dash); + const auto lastText = spec.substr(dash + 1); + + if (firstText.empty()) { // "-n": the last n bytes + const auto suffix = detail::number(lastText); + if (!suffix) return {}; + if (*suffix == 0 || size == 0) return {Outcome::unsatisfiable}; + const auto length = std::min(*suffix, size); + return {Outcome::partial, size - length, length}; + } + const auto first = detail::number(firstText); + if (!first) return {}; + std::optional last; + if (!lastText.empty()) { + last = detail::number(lastText); + if (!last || *last < *first) return {}; + } + if (*first >= size) return {Outcome::unsatisfiable}; + const auto end = last ? std::min(*last, size - 1) : size - 1; + return {Outcome::partial, *first, end - *first + 1}; +} + +/// The `Content-Range` of a 206: `bytes first-last/size`. +[[nodiscard]] inline std::string contentRange(const Selection& selection, std::uint64_t size) { + return "bytes " + std::to_string(selection.first) + "-" + std::to_string(selection.first + selection.length - 1) + "/" + std::to_string(size); +} + +/// The `Content-Range` of a 416: `bytes */size`. +[[nodiscard]] inline std::string unsatisfiedContentRange(std::uint64_t size) { + return "bytes */" + std::to_string(size); +} + +} // namespace webfront::http::range diff --git a/include/webfront/system/DefaultFS.hpp b/include/webfront/system/DefaultFS.hpp index 553ad89e..2121479d 100644 --- a/include/webfront/system/DefaultFS.hpp +++ b/include/webfront/system/DefaultFS.hpp @@ -33,8 +33,9 @@ class OptionalDevRootFS { std::optional open(std::filesystem::path file) const { if (root.empty()) return {}; - std::ifstream stream(root / file, std::ios::binary); - if (stream.is_open()) return File{std::move(stream)}; + const auto full = root / file; + std::ifstream stream(full, std::ios::binary); + if (stream.is_open()) return File{std::move(stream), full}; return {}; } diff --git a/include/webfront/system/FileSystem.hpp b/include/webfront/system/FileSystem.hpp index 0656d989..d3d3f1d0 100644 --- a/include/webfront/system/FileSystem.hpp +++ b/include/webfront/system/FileSystem.hpp @@ -14,7 +14,9 @@ #include #include #include +#include #include +#include namespace webfront::fs { @@ -41,6 +43,12 @@ class File { File(std::span input, size_t fileSize, std::string_view contentEncoding = "") : fileType{FileType::staticData}, data(input), size(fileSize), eofBit(fileSize==0), encoding(contentEncoding) {} File(std::ifstream ifstream) : fileType{FileType::nativeFStream}, fstream{std::move(ifstream)} { measureStream(); } + /// A native file, with the validator its path provides (see entityTag()). + File(std::ifstream ifstream, const std::filesystem::path& source) : File(std::move(ifstream)) { + std::error_code error; + const auto modified = std::filesystem::last_write_time(source, error); + if (!error && streamSize) entityTagValue = "\"" + std::to_string(*streamSize) + "-" + std::to_string(static_cast(modified.time_since_epoch().count())) + "\""; + } [[nodiscard]] bool isEncoded() const { return !encoding.empty(); } [[nodiscard]] std::string_view getEncoding() const { return encoding; } @@ -50,6 +58,28 @@ class File { /// native file whose stream can seek). A server uses it to announce a length and stream the file in chunks. [[nodiscard]] std::optional knownSize() const { return fileType == FileType::staticData ? std::optional{size} : streamSize; } + /// A strong entity tag (RFC 9110 §8.8.3), when the file can tell its version: a native file's size and + /// modification time. Embedded data and providers that do not know their version have none, and a range + /// request conditioned by `If-Range` is then answered in full. + [[nodiscard]] const std::optional& entityTag() const { return entityTagValue; } + + /// Positions the next read at `offset` bytes from the start of the content (the position the file had when it + /// was built), when knownSize() is set. An offset past the end positions at the end. + /// @return false when the file cannot seek, or the stream failed; the position is then unspecified. + [[nodiscard]] bool seek(std::uint64_t offset) { + if (fileType == FileType::staticData) { + readIndex = static_cast(std::min(offset, size)); + eofBit = readIndex == size; + return true; + } + if (!streamSize || !fstream.is_open()) return false; + const auto target = std::min(offset, *streamSize); + fstream.clear(); + fstream.seekg(streamOrigin + static_cast(target)); + eofBit = false; + return static_cast(fstream); + } + // Extracts characters from file into given buffer until buffer size or end of file is reached. // @param buffer buffer which will receive extracted data // @return bytes read @@ -63,6 +93,8 @@ class File { std::span data; size_t readIndex{}, size{}; std::optional streamSize; + std::streamoff streamOrigin{}; + std::optional entityTagValue; bool eofBit{false}; const std::string encoding{}; std::ifstream fstream; @@ -88,7 +120,10 @@ class File { fstream.seekg(0, std::ios::end); const auto end = fstream.tellg(); fstream.seekg(start); - if (start >= 0 && end >= start && fstream) streamSize = static_cast(end - start); + if (start >= 0 && end >= start && fstream) { + streamSize = static_cast(end - start); + streamOrigin = static_cast(start); + } else fstream.clear(); } diff --git a/include/webfront/system/NativeFS.hpp b/include/webfront/system/NativeFS.hpp index a6c12072..d5fecabd 100644 --- a/include/webfront/system/NativeFS.hpp +++ b/include/webfront/system/NativeFS.hpp @@ -14,8 +14,9 @@ class NativeRawFS { public: std::optional open(std::filesystem::path path) { std::ifstream file; - file.open(rootPath / path, std::ios::binary); - if (file.is_open()) return File{std::move(file)}; + const auto full = rootPath / path; + file.open(full, std::ios::binary); + if (file.is_open()) return File{std::move(file), full}; return {}; } protected: diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index c946a392..bbe5eaa4 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -24,7 +24,7 @@ if(WEBFRONT_TEST_DOXYGEN) endif() set(TESTS_LIST) -list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServerTests.cpp HTTPEncodingTests.cpp GzipExecutorTests.cpp AcceptEncodingTests.cpp GzipTests.cpp ModuleHTTPServerTests.cpp HTTPRoutesTests.cpp EncodingsTests.cpp WebSocketTests.cpp LoggerTests.cpp MimeTypeTests.cpp) +list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServerTests.cpp HTTPEncodingTests.cpp GzipExecutorTests.cpp AcceptEncodingTests.cpp GzipTests.cpp ModuleHTTPServerTests.cpp HTTPRoutesTests.cpp HTTPRangeTests.cpp EncodingsTests.cpp WebSocketTests.cpp LoggerTests.cpp MimeTypeTests.cpp) list(APPEND TESTS_LIST FormsTests.cpp ReactStoreTests.cpp DomDocumentTests.cpp DomBatchTests.cpp JSFunctionTests.cpp TypeErasedFunctionTests.cpp MessagesTests.cpp IndexFSTests.cpp) list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp SafePathTests.cpp UISubscribersTests.cpp) diff --git a/test/unit/HTTPRangeTests.cpp b/test/unit/HTTPRangeTests.cpp new file mode 100644 index 00000000..93740c16 --- /dev/null +++ b/test/unit/HTTPRangeTests.cpp @@ -0,0 +1,461 @@ +/// Byte range requests (#455): the selection of a range, and its use by files and by dynamic routes. +#include "GzipFixtures.hpp" +#include "InjectableNetworking.hpp" +#include "Mocks.hpp" +#include "TemporaryDirectory.hpp" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace webfront; +using namespace webfront::http; +using namespace std::chrono_literals; +using webfront::testing::InjectableSocket; + +namespace { + +/// The header fields of a request, as `range::select` reads them. +struct Fields { + std::vector> fields; + std::list getHeadersValues(std::string_view name) const { + std::list values; + for (const auto& [key, value] : fields) + if (key == name) values.push_back(value); + return values; + } +}; + +Fields withRange(std::string value) { return {{{"Range", std::move(value)}}}; } + +using range::Outcome; + +struct Expected { + Outcome outcome; + std::uint64_t first = 0; + std::uint64_t length = 0; +}; + +void expectSelection(const Fields& request, std::uint64_t size, Expected expected, const std::optional& tag = {}) { + const auto selection = range::select(request, size, tag); + REQUIRE(selection.outcome == expected.outcome); + if (expected.outcome == Outcome::partial) { + REQUIRE(selection.first == expected.first); + REQUIRE(selection.length == expected.length); + } +} + +struct RangeNet : webfront::testing::InjectableNetworking { + static inline std::atomic accepts{0}; + static auto Accept(auto&) { + return networking::ex::then(networking::ex::just(), []() -> Socket { + if (accepts++ != 0) throw std::system_error(std::make_error_code(std::errc::operation_canceled)); + return Socket{}; + }); + } +}; + +bool waitFor(auto condition) { + for (auto waited = 0ms; waited < 10s; waited += 1ms) { + if (condition()) return true; + std::this_thread::sleep_for(1ms); + } + return false; +} + +/// What the provider below serves, whatever the path asked. +struct Served { + static inline std::string content; + static inline std::vector words; + static inline std::filesystem::path native; ///< a native file when set, embedded data otherwise + static inline std::string_view encoding; +}; + +struct ServedFS { + explicit ServedFS(std::filesystem::path) {} + std::optional open(std::filesystem::path) { + if (!Served::native.empty()) return fs::File(std::ifstream(Served::native, std::ios::binary), Served::native); + auto& words = Served::words; + words.assign((Served::content.size() + 7) / 8, 0); + for (std::size_t index = 0; index < Served::content.size(); ++index) + words[index / 8] |= static_cast(static_cast(Served::content[index])) << ((7 - index % 8) * 8); + return fs::File(words, Served::content.size(), Served::encoding); + } +}; + +std::string pattern(std::size_t size) { + std::string text; + for (std::size_t index = 0; index < size; ++index) text.push_back(static_cast('a' + (index * 7 + index / 13) % 26)); + return text; +} + +std::string request(std::string_view method, std::string_view headers) { + return std::string(method) + " /media.bin HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: gzip\r\n" + std::string(headers) + "\r\n"; +} + +/// Serves one request on a new server and returns everything it wrote. +std::string fetch(const std::string& text) { + InjectableSocket::reset(); + RangeNet::accepts = 0; + http::Server server("127.0.0.1", "0"); + std::vector bytes; + for (const char c : text) bytes.push_back(static_cast(c)); + InjectableSocket::receive(bytes); + REQUIRE(waitFor([] { return InjectableSocket::shutdownCount() > 0; })); + auto written = InjectableSocket::writtenText(); + InjectableSocket::reset(); + return written; +} + +bool contains(const std::string& haystack, std::string_view needle) { return haystack.find(needle) != std::string::npos; } + +std::string body(const std::string& response) { + const auto end = response.find("\r\n\r\n"); + return end == std::string::npos ? std::string{} : response.substr(end + 4); +} + +std::string header(const std::string& response, std::string_view name) { + const auto head = response.substr(0, response.find("\r\n\r\n")); + const auto start = head.find("\r\n" + std::string(name) + ": "); + if (start == std::string::npos) return {}; + const auto from = start + 4 + name.size(); + return head.substr(from, head.find("\r\n", from) - from); +} + +void serveEmbedded(std::string content, std::string_view encoding = {}) { + Served::content = std::move(content); + Served::encoding = encoding; + Served::native.clear(); +} + +} // namespace + +SCENARIO("A Range header selects one part of a representation") { + constexpr std::uint64_t size = 1000; + GIVEN("well-formed single ranges") { + THEN("first-last selects the bytes, last being clamped to the end") { + expectSelection(withRange("bytes=0-0"), size, {Outcome::partial, 0, 1}); + expectSelection(withRange("bytes=10-19"), size, {Outcome::partial, 10, 10}); + expectSelection(withRange("bytes=990-5000"), size, {Outcome::partial, 990, 10}); + expectSelection(withRange("bytes=0-999"), size, {Outcome::partial, 0, 1000}); + expectSelection(withRange("bytes=999-999"), size, {Outcome::partial, 999, 1}); + } + THEN("first- selects up to the end") { + expectSelection(withRange("bytes=0-"), size, {Outcome::partial, 0, 1000}); + expectSelection(withRange("bytes=900-"), size, {Outcome::partial, 900, 100}); + expectSelection(withRange("bytes=999-"), size, {Outcome::partial, 999, 1}); + } + THEN("-n selects the last n bytes, the whole when n exceeds the size") { + expectSelection(withRange("bytes=-1"), size, {Outcome::partial, 999, 1}); + expectSelection(withRange("bytes=-100"), size, {Outcome::partial, 900, 100}); + expectSelection(withRange("bytes=-1000"), size, {Outcome::partial, 0, 1000}); + expectSelection(withRange("bytes=-5000"), size, {Outcome::partial, 0, 1000}); + } + THEN("the unit is case-insensitive and surrounding blanks are ignored") { + expectSelection(withRange("Bytes=5-6"), size, {Outcome::partial, 5, 2}); + expectSelection(withRange(" bytes=5-6 \t"), size, {Outcome::partial, 5, 2}); + } + } + GIVEN("ranges nothing can satisfy") { + THEN("a first byte at or past the end is unsatisfiable") { + expectSelection(withRange("bytes=1000-"), size, {Outcome::unsatisfiable}); + expectSelection(withRange("bytes=1000-1001"), size, {Outcome::unsatisfiable}); + expectSelection(withRange("bytes=99999999999999999999999-"), size, {Outcome::unsatisfiable}); + } + THEN("an empty suffix is unsatisfiable") { expectSelection(withRange("bytes=-0"), size, {Outcome::unsatisfiable}); } + THEN("any range of an empty representation is unsatisfiable") { + expectSelection(withRange("bytes=0-0"), 0, {Outcome::unsatisfiable}); + expectSelection(withRange("bytes=0-"), 0, {Outcome::unsatisfiable}); + expectSelection(withRange("bytes=-5"), 0, {Outcome::unsatisfiable}); + } + } + GIVEN("headers the server ignores") { + THEN("the whole representation is answered") { + expectSelection({}, size, {Outcome::whole}); + expectSelection(withRange("items=0-5"), size, {Outcome::whole}); + expectSelection(withRange("bytes"), size, {Outcome::whole}); + expectSelection(withRange("bytes="), size, {Outcome::whole}); + expectSelection(withRange("bytes=-"), size, {Outcome::whole}); + expectSelection(withRange("bytes=5-2"), size, {Outcome::whole}); + expectSelection(withRange("bytes=a-b"), size, {Outcome::whole}); + expectSelection(withRange("bytes=+1-2"), size, {Outcome::whole}); + expectSelection(withRange("bytes=1 -2"), size, {Outcome::whole}); + expectSelection(withRange("bytes=0-1,5-6"), size, {Outcome::whole}); + expectSelection(withRange("bytes=0-1,"), size, {Outcome::whole}); + expectSelection({{{"Range", "bytes=0-1"}, {"Range", "bytes=5-6"}}}, size, {Outcome::whole}); + } + } + GIVEN("a number beyond 64 bits") { + THEN("it saturates instead of wrapping") { + expectSelection(withRange("bytes=0-99999999999999999999999"), size, {Outcome::partial, 0, 1000}); + expectSelection(withRange("bytes=-99999999999999999999999"), size, {Outcome::partial, 0, 1000}); + } + } + GIVEN("an If-Range condition") { + const std::optional tag{"\"1000-42\""}; + auto conditioned = [](std::string condition) { + return Fields{{{"Range", "bytes=10-19"}, {"If-Range", std::move(condition)}}}; + }; + THEN("the range applies when it is the strong tag of the representation") { + expectSelection(conditioned("\"1000-42\""), size, {Outcome::partial, 10, 10}, tag); + } + THEN("the whole representation is answered when the tag differs, is weak, is a date or cannot be compared") { + expectSelection(conditioned("\"1000-43\""), size, {Outcome::whole}, tag); + expectSelection(conditioned("W/\"1000-42\""), size, {Outcome::whole}, tag); + expectSelection(conditioned("Sun, 06 Nov 1994 08:49:37 GMT"), size, {Outcome::whole}, tag); + expectSelection(conditioned("\"1000-42\""), size, {Outcome::whole}); + expectSelection({{{"Range", "bytes=10-19"}, {"If-Range", "\"1000-42\""}, {"If-Range", "\"1000-42\""}}}, size, {Outcome::whole}, tag); + } + THEN("an If-Range without Range does nothing") { + expectSelection({{{"If-Range", "\"1000-42\""}}}, size, {Outcome::whole}, tag); + } + } + THEN("the Content-Range headers spell the bounds and the size") { + REQUIRE(range::contentRange({Outcome::partial, 10, 10}, 1000) == "bytes 10-19/1000"); + REQUIRE(range::unsatisfiedContentRange(1000) == "bytes */1000"); + } +} + +SCENARIO("A file is served by ranges") { + const auto chunk = DefaultBuffersPolicy::emissionBufferSize; + for (const bool native : {false, true}) { + GIVEN(std::string(native ? "a native file" : "an embedded file") << " of several chunks") { + webfront::test::TemporaryDirectory directory; + const auto content = pattern(3 * chunk + 11); + serveEmbedded(content); + if (native) { + Served::native = directory.path() / "media.bin"; + std::ofstream(Served::native, std::ios::binary) << content; + } + WHEN("the whole file is requested") { + const auto response = fetch(request("GET", "")); + THEN("200 announces the ranges") { + REQUIRE(response.starts_with("HTTP/1.1 200 OK\r\n")); + REQUIRE(header(response, "Accept-Ranges") == "bytes"); + REQUIRE(body(response) == content); + } + THEN("a native file has an entity tag, embedded data none") { + REQUIRE(header(response, "ETag").empty() != native); + } + } + WHEN("a range crosses the emission chunks") { + const auto first = chunk - 5; + const auto response = fetch(request("GET", "Range: bytes=" + std::to_string(first) + "-" + std::to_string(2 * chunk + 4) + "\r\n")); + THEN("206 sends exactly those bytes") { + REQUIRE(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); + REQUIRE(header(response, "Content-Range") == "bytes " + std::to_string(first) + "-" + std::to_string(2 * chunk + 4) + "/" + std::to_string(content.size())); + REQUIRE(header(response, "Content-Length") == std::to_string(chunk + 10)); + REQUIRE(body(response) == content.substr(first, chunk + 10)); + } + } + WHEN("the end of the file is requested") { + THEN("an open range reads to the end") { + const auto response = fetch(request("GET", "Range: bytes=" + std::to_string(content.size() - 7) + "-\r\n")); + REQUIRE(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); + REQUIRE(body(response) == content.substr(content.size() - 7)); + } + THEN("a suffix reads the last bytes") { + const auto response = fetch(request("GET", "Range: bytes=-7\r\n")); + REQUIRE(body(response) == content.substr(content.size() - 7)); + REQUIRE(header(response, "Content-Range") == "bytes " + std::to_string(content.size() - 7) + "-" + std::to_string(content.size() - 1) + "/" + std::to_string(content.size())); + } + THEN("a last byte past the end is clamped") { + const auto response = fetch(request("GET", "Range: bytes=" + std::to_string(content.size() - 3) + "-99999999\r\n")); + REQUIRE(body(response) == content.substr(content.size() - 3)); + } + } + WHEN("the range starts at the first byte") { + const auto response = fetch(request("GET", "Range: bytes=0-0\r\n")); + THEN("206 sends it without seeking") { REQUIRE(body(response) == content.substr(0, 1)); } + } + WHEN("the range starts past the end") { + const auto response = fetch(request("GET", "Range: bytes=" + std::to_string(content.size()) + "-\r\n")); + THEN("416 tells the size and sends no content") { + REQUIRE(response.starts_with("HTTP/1.1 416 Range Not Satisfiable\r\n")); + REQUIRE(header(response, "Content-Range") == "bytes */" + std::to_string(content.size())); + REQUIRE_FALSE(contains(response, content.substr(0, 40))); + } + } + WHEN("several ranges are requested") { + const auto response = fetch(request("GET", "Range: bytes=0-1,5-6\r\n")); + THEN("the whole file is answered") { + REQUIRE(response.starts_with("HTTP/1.1 200 OK\r\n")); + REQUIRE(body(response) == content); + } + } + WHEN("HEAD carries a range") { + const auto response = fetch(request("HEAD", "Range: bytes=10-29\r\n")); + THEN("it announces the 206 and sends no body") { + REQUIRE(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); + REQUIRE(header(response, "Content-Length") == "20"); + REQUIRE(header(response, "Content-Range") == "bytes 10-29/" + std::to_string(content.size())); + REQUIRE(body(response).empty()); + } + } + } + } +} + +SCENARIO("A range survives a file changed between two requests only when its validator still matches") { + webfront::test::TemporaryDirectory directory; + Served::native = directory.path() / "media.bin"; + Served::encoding = {}; + const auto original = pattern(5000); + std::ofstream(Served::native, std::ios::binary) << original; + const auto tag = header(fetch(request("GET", "")), "ETag"); + REQUIRE_FALSE(tag.empty()); + const std::string conditional = "Range: bytes=100-199\r\nIf-Range: " + tag + "\r\n"; + + GIVEN("the file did not change") { + const auto response = fetch(request("GET", conditional)); + THEN("the range is served") { + REQUIRE(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); + REQUIRE(body(response) == original.substr(100, 100)); + } + } + GIVEN("the file grew") { + const auto replaced = pattern(5001); + std::ofstream(Served::native, std::ios::binary | std::ios::trunc) << replaced; + const auto response = fetch(request("GET", conditional)); + THEN("the current file is sent in full, with its new tag") { + REQUIRE(response.starts_with("HTTP/1.1 200 OK\r\n")); + REQUIRE(body(response) == replaced); + REQUIRE(header(response, "ETag") != tag); + } + } + GIVEN("the file was rewritten with the same size, later") { + const auto before = std::filesystem::last_write_time(Served::native); + std::string replaced = original; + std::reverse(replaced.begin(), replaced.end()); + std::ofstream(Served::native, std::ios::binary | std::ios::trunc) << replaced; + std::filesystem::last_write_time(Served::native, before + 1h); + const auto response = fetch(request("GET", conditional)); + THEN("the current file is sent in full") { + REQUIRE(response.starts_with("HTTP/1.1 200 OK\r\n")); + REQUIRE(body(response) == replaced); + } + } + GIVEN("the file shrank without the validator being checked") { + std::ofstream(Served::native, std::ios::binary | std::ios::trunc) << pattern(150); + const auto response = fetch(request("GET", "Range: bytes=100-199\r\n")); + THEN("the range is clamped to the current file") { + REQUIRE(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); + REQUIRE(body(response) == pattern(150).substr(100)); + } + } + GIVEN("embedded data, which has no validator") { + serveEmbedded(original); + const auto response = fetch(request("GET", "Range: bytes=100-199\r\nIf-Range: \"anything\"\r\n")); + THEN("a conditioned range is answered in full") { + REQUIRE(response.starts_with("HTTP/1.1 200 OK\r\n")); + REQUIRE(body(response) == original); + } + } +} + +SCENARIO("A stored or decoded representation is not served by ranges") { + const auto content = pattern(300); + GIVEN("a gzip file the client accepts") { + serveEmbedded(content, "gzip"); + const auto response = fetch(request("GET", "Range: bytes=10-19\r\n")); + THEN("it is sent in full, as stored, and says it has no ranges") { + REQUIRE(response.starts_with("HTTP/1.1 200 OK\r\n")); + REQUIRE(header(response, "Accept-Ranges") == "none"); + REQUIRE(header(response, "Content-Encoding") == "gzip"); + } + } + GIVEN("a gzip file the client does not accept, which the server decodes") { + serveEmbedded(std::string(gzipfixtures::fixed), "gzip"); + const auto response = fetch("GET /media.bin HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: identity\r\nRange: bytes=10-19\r\n\r\n"); + THEN("the answer is never a 206 and says it has no ranges") { + REQUIRE(response.starts_with("HTTP/1.1 200 OK\r\n")); + REQUIRE(body(response).starts_with("WebFront gzip fallback")); + REQUIRE(header(response, "Accept-Ranges") == "none"); + } + } +} + +SCENARIO("A dynamic route serves a file by ranges") { + for (const bool native : {false, true}) { + GIVEN(std::string(native ? "a native file" : "an embedded file") << " behind a route") { + webfront::test::TemporaryDirectory directory; + const auto content = pattern(2 * DefaultBuffersPolicy::emissionBufferSize + 3); + serveEmbedded(content); + Served::native.clear(); + const auto path = directory.path() / "granted.bin"; + if (native) std::ofstream(path, std::ios::binary) << content; + const auto open = [&] { + if (native) return fs::File(std::ifstream(path, std::ios::binary), path); + static std::vector words; + words.assign((content.size() + 7) / 8, 0); + for (std::size_t index = 0; index < content.size(); ++index) + words[index / 8] |= static_cast(static_cast(content[index])) << ((7 - index % 8) * 8); + return fs::File(words, content.size()); + }; + const auto answer = [&](const std::string& text) { + InjectableSocket::reset(); + RangeNet::accepts = 0; + http::Server server("127.0.0.1", "0"); + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest& routed) { + auto reply = fileReply(routed.request, open(), "video/mp4"); + reply.headers.emplace_back("Cache-Control", "no-store"); + return reply; + }); + std::vector bytes; + for (const char c : text) bytes.push_back(static_cast(c)); + InjectableSocket::receive(bytes); + REQUIRE(waitFor([] { return InjectableSocket::shutdownCount() > 0; })); + auto written = InjectableSocket::writtenText(); + InjectableSocket::reset(); + return written; + }; + const auto get = [](std::string_view method, std::string_view headers) { + return std::string(method) + " /webfront/services/files/token HTTP/1.1\r\nHost: localhost\r\n" + std::string(headers) + "\r\n"; + }; + WHEN("the file is requested in full, then twice by range on the same URL") { + const auto whole = answer(get("GET", "")); + const auto middle = answer(get("GET", "Range: bytes=1000-1999\r\n")); + const auto resumed = answer(get("GET", "Range: bytes=2000-\r\n")); + THEN("every request succeeds with its own bytes") { + REQUIRE(whole.starts_with("HTTP/1.1 200 OK\r\n")); + REQUIRE(header(whole, "Accept-Ranges") == "bytes"); + REQUIRE(header(whole, "Content-Type") == "video/mp4"); + REQUIRE(header(whole, "Cache-Control") == "no-store"); + REQUIRE(body(whole) == content); + REQUIRE(middle.starts_with("HTTP/1.1 206 Partial Content\r\n")); + REQUIRE(header(middle, "Content-Range") == "bytes 1000-1999/" + std::to_string(content.size())); + REQUIRE(body(middle) == content.substr(1000, 1000)); + REQUIRE(resumed.starts_with("HTTP/1.1 206 Partial Content\r\n")); + REQUIRE(body(resumed) == content.substr(2000)); + } + } + WHEN("the range is unsatisfiable") { + const auto response = answer(get("GET", "Range: bytes=" + std::to_string(content.size()) + "-\r\n")); + THEN("416 tells the size") { + REQUIRE(response.starts_with("HTTP/1.1 416 Range Not Satisfiable\r\n")); + REQUIRE(header(response, "Content-Range") == "bytes */" + std::to_string(content.size())); + REQUIRE(header(response, "Content-Length") == "0"); + } + } + WHEN("HEAD carries a range") { + const auto response = answer(get("HEAD", "Range: bytes=5-14\r\n")); + THEN("it announces the part and sends no body") { + REQUIRE(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); + REQUIRE(header(response, "Content-Length") == "10"); + REQUIRE(body(response).empty()); + } + } + } + } +} diff --git a/test/web/JasmineTest.cpp b/test/web/JasmineTest.cpp index 9b05aba6..f4c8704d 100644 --- a/test/web/JasmineTest.cpp +++ b/test/web/JasmineTest.cpp @@ -23,7 +23,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -93,6 +95,8 @@ class BrowserIntegrationTest { ~BrowserIntegrationTest() { joinBitsetFutureChecks(); + error_code ignored; + if (!mediaFile.empty()) filesystem::remove(mediaFile, ignored); } /// Registers the callbacks of the specs before the page opens; the rejecting WebSocket server starts after the CEF @@ -104,6 +108,7 @@ class BrowserIntegrationTest { registerCallbacks(); registerBitsetCallbacks(); lifeReactSubscription = demo::installLifeReact(app); + registerMediaRoute(app); streamRoute = app.addRoute("/webfront/services/test-stream/", [](const http::RouteRequest& request) { if (request.query.find("fail=1") != std::string_view::npos) throw std::runtime_error("route failure requested by the spec"); std::uint64_t size = 0; @@ -174,7 +179,10 @@ class BrowserIntegrationTest { optional connectedUI; UISubscription uiSubscription; UISubscription lifeReactSubscription; - http::RouteTable::Registration streamRoute; + http::RouteTable::Registration streamRoute, mediaRoute; + filesystem::path mediaFile; + mutex mediaMutex; + vector mediaRanges; std::map>> reactStores; UISubscription closedDomSubscription; std::map closedDocumentRejected; @@ -381,6 +389,36 @@ class BrowserIntegrationTest { } } + /// A 20 second PCM sound in a native file, served by ranges (#455): a