-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathearly_413.cpp
More file actions
74 lines (61 loc) · 2.63 KB
/
Copy pathearly_413.cpp
File metadata and controls
74 lines (61 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
This file is part of libhttpserver
Copyright (C) 2011-2026 Sebastiano Merlino
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
// Demonstrates the solution to issue #273: short-circuit large uploads
// with a 413 BEFORE any body bytes are consumed.
//
// Register a `request_received` hook that inspects Content-Length; if
// it exceeds the configured cap, return a respond_with(413) action.
// libhttpserver aborts the upload -- the resource handler is not
// invoked and the body bytes never cross the daemon's I/O boundary.
#include <cstddef>
#include <functional>
#include <memory>
#include <string>
#include <httpserver.hpp>
namespace hs = httpserver;
namespace {
constexpr std::size_t kMaxUploadBytes = 1 * 1024 * 1024; // 1 MB
} // namespace
class upload_resource : public hs::http_resource {
public:
hs::http_response render_post(const hs::http_request&) override {
return hs::http_response::string("UPLOAD OK");
}
};
int main() {
hs::webserver ws{hs::create_webserver(8080)};
auto h = ws.add_hook(hs::hook_phase::request_received,
std::function<hs::hook_action(hs::request_received_ctx&)>(
[](hs::request_received_ctx& ctx) {
std::string cl{ctx.request->get_header("Content-Length")};
if (cl.empty()) return hs::hook_action::pass();
try {
if (std::stoull(cl) > kMaxUploadBytes) {
return hs::hook_action::respond_with(
hs::http_response::empty().with_status(413));
}
} catch (...) {
// Malformed Content-Length: let the normal pipeline
// produce a 400 elsewhere.
}
return hs::hook_action::pass();
}));
auto resource = std::make_shared<upload_resource>();
ws.register_path("/upload", resource);
ws.start(true); // blocking
return 0;
}