-
-
Notifications
You must be signed in to change notification settings - Fork 556
Add a request body sink, with FileBodySink as a file-backed wrapper #1235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
anton-n-petrov
wants to merge
15
commits into
CrowCpp:master
Choose a base branch
from
anton-n-petrov:feature/request-body-sink
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
fa21b7f
Add a request body size limit that closes over-limit connections
anton-n-petrov 87adfe6
Add a request body sink, with body_file() as a file-backed wrapper
anton-n-petrov 225034f
Don't allocate from untrusted Content-Length when body size is unlimited
anton-n-petrov 71c9f86
Merge feature/max-body-size into request-body-sink
anton-n-petrov 7767c4c
Make body_file/body_sink last-call-wins and cover sink failure paths
anton-n-petrov cffeec8
Rework the request body sink per review: shared handle, opt-in file h…
anton-n-petrov 0b3a6dc
Address code review: portable file sink, drain doc, comments
anton-n-petrov a0e6733
Drop the Content-Length reserve() unconditionally, clear req.body on …
anton-n-petrov 7dca1ef
Keep file_body_sink.h out of the amalgamated crow_all.h
anton-n-petrov ec10ad8
Fix stale mkostemp reference in body-file guide
anton-n-petrov 2779929
Fix CIFuzz build: DummyHandler out of sync with HTTPParser handler in…
anton-n-petrov 300378a
Address PR review: scope drain wording, make send_file test cwd-indep…
anton-n-petrov e4e4a26
Explicit skip_body on body_error_status_ responses, matching max-body…
anton-n-petrov 16fa250
Address PR review: fix inaccurate drain wording, init rule_index
anton-n-petrov 99d7368
Address PR review: linger-drain on body errors, dedupe test helpers
anton-n-petrov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| <span class="tag">[:octicons-feed-tag-16: master](https://github.com/CrowCpp/Crow)</span> | ||
|
|
||
| By default Crow stores a request body in `req.body` (`std::string`). That is | ||
| the right default for JSON and form fields, but a large upload then occupies | ||
| the same amount of RAM as the file. | ||
|
|
||
| A route can divert body bytes **while they arrive** to a sink instead, via | ||
| `#!cpp .body_sink(factory)`. The built-in sink is a unique file | ||
| (`crow::FileBodySink`, an opt-in header — see below); you can also supply | ||
| your own (flash, SD, a bounded buffer) when there is no writable filesystem. | ||
|
|
||
| The handler still runs only after the full body has been received. Writes run | ||
| synchronously on the connection's io thread, before the `Host` header check, | ||
| before middleware, and before `100 Continue`. A sink that throws, or returns | ||
| `false` from `write()`/`finish()`, ends the request as a 500 with the | ||
| connection closed; the route handler never runs. | ||
|
|
||
| This is the request-side counterpart of returning a file with | ||
| `response.set_static_file_info()`: the payload is never held as one string. | ||
|
|
||
| Size limits are `app.max_body_size()` / `.max_body_size()` — see | ||
| [Request body size](app.md#request-body-size). Over-limit requests are 413 | ||
| and the connection closes; nothing the sink wrote is kept. | ||
|
|
||
| ## File convenience | ||
|
|
||
| ```cpp | ||
| #include "crow.h" | ||
| #include "crow/file_body_sink.h" // opt-in: not pulled in by crow.h | ||
|
|
||
| crow::SimpleApp app; | ||
| app.max_body_size(64ull * 1024 * 1024); | ||
|
|
||
| CROW_ROUTE(app, "/upload") | ||
| .methods(crow::HTTPMethod::Put, crow::HTTPMethod::Post) | ||
| .body_sink(crow::FileBodySink::factory("uploads")) // empty: system temp directory | ||
| ([](const crow::request& req) { | ||
| auto* file = crow::FileBodySink::from(req); | ||
| if (!file) | ||
| return crow::response(200); // e.g. an empty PUT: see "Empty bodies" below | ||
| // req.body is empty; the bytes are in file->path() | ||
| std::ifstream in(file->path(), std::ios::binary); | ||
| // ... | ||
| return crow::response(200); | ||
| }); | ||
| ``` | ||
|
|
||
| `crow::FileBodySink::factory(directory)` resolves `directory` to an absolute | ||
| path once, at the point you call it, and throws | ||
| `std::filesystem::filesystem_error` if it does not already exist — Crow does | ||
| not create it for you, and does not fail silently. Crow always generates a | ||
| unique file name (POSIX: a retried `open(O_CREAT | O_EXCL)`; Windows: a | ||
| retried `CREATE_NEW`), so concurrent requests never share a path. The | ||
| descriptor is kept open until the body is complete; the handler then reads | ||
| `file->path()`. | ||
|
|
||
| The file is deleted when the last `crow::request` copy that reached the | ||
| handler is destroyed — normally right after the response has been fully | ||
| sent. Call `file->keep()` if the application will use the file after that | ||
| (for example after renaming it into place); the destructor then only closes | ||
| the descriptor. | ||
|
|
||
| A client that disconnects before the body is complete never reaches the | ||
| handler; the partial file is removed. Bodyless GET/HEAD (and | ||
| `Content-Length: 0`) do not create a file — `crow::FileBodySink::from(req)` | ||
| returns `nullptr` in that case, same as for any route where the body didn't | ||
| go to this sink. | ||
|
|
||
| `crow::FileBodySink::from()` uses `dynamic_cast` and so needs RTTI; that is | ||
| why this header is opt-in and never pulled in by `crow.h` or | ||
| `crow/parser.h`. A build with `-fno-rtti` (or asio's `-DASIO_NO_TYPEID`) can | ||
| use `crow::BodySink` directly and simply not include | ||
| `crow/file_body_sink.h`. | ||
|
|
||
| ## Custom sink | ||
|
|
||
| ```cpp | ||
| struct FlashSink : crow::BodySink { | ||
| bool write(const char* data, std::size_t length) override; | ||
| bool finish() override; | ||
| }; | ||
|
|
||
| CROW_ROUTE(app, "/upload") | ||
| .methods(crow::HTTPMethod::Post) | ||
| .body_sink([](const crow::request& req) -> std::unique_ptr<crow::BodySink> { | ||
| return std::make_unique<FlashSink>(req); | ||
| }) | ||
| ([](const crow::request&) { | ||
| return crow::response(200); | ||
| }); | ||
| ``` | ||
|
|
||
| The factory runs once per request, after headers and before the body; `req` | ||
| carries the method, url, headers and `remote_ip_address` (already set, so a | ||
| factory can apply a per-peer policy), but not `body` or `body_sink` yet. | ||
| Returning `nullptr` from the factory means "no sink for this request" — the | ||
| body goes to `req.body` as usual, it is not an error. Throwing from the | ||
| factory, or from `write()`/`finish()`, is a 500. | ||
|
|
||
| Calling `.body_sink(...)` again on the same route replaces the factory | ||
| (last-call-wins). | ||
|
|
||
| ## Empty bodies | ||
|
|
||
| A `.body_sink(...)` route only opens a sink when a body is actually coming | ||
| (`Content-Length` > 0, or chunked framing); a bodyless request never calls | ||
| the factory, so `req.body_sink` (and `crow::FileBodySink::from(req)`) is | ||
| `nullptr`. Handle that case explicitly — see the example above. Note that an | ||
| empty **chunked** body (`0\r\n\r\n`) still counts as "a body is coming" and | ||
| does open the sink (into an empty file, for the built-in one), unlike | ||
| `Content-Length: 0`. | ||
|
|
||
| ## What this is not | ||
|
|
||
| `.body_sink(...)` stores the **raw** request body. `multipart/form-data` is | ||
| parsed from `req.body` by `crow::multipart::message`; a route with a sink | ||
| diverts every body regardless of `Content-Type`, so `req.body` is empty and | ||
| `crow::multipart::message` cannot be used on it. Saving individual multipart | ||
| parts as they arrive is a separate feature. | ||
|
|
||
| The route handler is not invoked per chunk. Incremental processing belongs in | ||
| `BodySink::write`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| #include "crow.h" | ||
| #include "crow/file_body_sink.h" | ||
|
|
||
| #include <fstream> | ||
| #include <iterator> | ||
| #include <string> | ||
|
|
||
| int main() | ||
| { | ||
| crow::SimpleApp app; | ||
| app.max_body_size(64ull * 1024 * 1024); | ||
|
|
||
| // PUT or POST the raw body; Crow writes it to disk as the bytes arrive. | ||
| CROW_ROUTE(app, "/upload") | ||
| .methods(crow::HTTPMethod::Put, crow::HTTPMethod::Post) | ||
| .body_sink(crow::FileBodySink::factory("uploads")) // requires ./uploads to exist | ||
| ([](const crow::request& req) { | ||
| auto* file = crow::FileBodySink::from(req); | ||
| if (!file) | ||
| { | ||
| // No incoming body (e.g. an empty PUT): the sink never opened. | ||
| crow::json::wvalue reply; | ||
| reply["bytes"] = 0; | ||
| reply["preview"] = ""; | ||
| return crow::response(reply); | ||
| } | ||
|
|
||
| std::ifstream in(file->path(), std::ios::binary); | ||
| const std::string contents((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); | ||
|
|
||
| crow::json::wvalue reply; | ||
| reply["bytes"] = contents.size(); | ||
| reply["preview"] = contents.substr(0, 32); | ||
| return crow::response(reply); | ||
| }); | ||
|
|
||
| app.port(18080).multithreaded().run(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| #pragma once | ||
|
|
||
| #include <cstddef> | ||
| #include <functional> | ||
| #include <memory> | ||
|
|
||
| namespace crow | ||
| { | ||
| struct request; | ||
|
|
||
| /// Destination for request body bytes as they arrive from the parser. | ||
| /// | ||
| /// `write()`/`finish()` run on the connection's io thread, at headers-complete, | ||
| /// before the `Host` check, before middleware, and before `100 Continue`. A | ||
| /// thrown exception or a `false` return is a 500 with the connection closed; | ||
| /// the route handler never runs. If `finish()` was never called, the body did | ||
| /// not arrive in full (client disconnect, over-limit body, or a write failure). | ||
| struct BodySink | ||
| { | ||
| virtual ~BodySink() = default; | ||
| virtual bool write(const char* data, std::size_t length) = 0; | ||
| virtual bool finish() = 0; | ||
| }; | ||
|
|
||
| /// `req` carries method, url, headers and `remote_ip_address` (set before the | ||
| /// factory runs); `req.body` and `req.body_sink` are not yet populated. | ||
| /// Returning `nullptr` keeps the body in `req.body` instead of diverting it. | ||
| using BodySinkFactory = std::function<std::unique_ptr<BodySink>(const request&)>; | ||
| } // namespace crow | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P2] The timing contract is incorrect. Only the factory runs at headers-complete before
100 Continue;write()runs after the body starts arriving, so anExpect: 100-continuerequest receives the interim 100 before a laterwrite()failure can produce 500, andfinish()runs at message-complete. Please distinguish factory timing fromwrite()/finish()here and indocs/guides/body-file.md.