-
-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathhook_dispatcher.cpp
More file actions
323 lines (281 loc) · 12.9 KB
/
Copy pathhook_dispatcher.cpp
File metadata and controls
323 lines (281 loc) · 12.9 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/*
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
*/
// hook_dispatcher behavior service (DR-014 §4.11). Logic moved verbatim
// out of the former hook_phase_dispatch.cpp (the eleven forwarders) and
// webserver_hook_firing.cpp (the four gated helpers). Those TUs now hold
// only the thin webserver_impl forwarders during the migration. The one
// behavioral change is that the per-call error logger now routes through
// the detail::log_dispatch_error free function (config bag) instead of the
// webserver_impl member.
#include "httpserver/detail/hook_dispatcher.hpp"
#include <microhttpd.h>
#include <chrono>
#include <cstddef>
#include <memory>
#include <optional>
#include <string_view>
#include <utility>
#include "httpserver/hook_action.hpp"
#include "httpserver/hook_context.hpp"
#include "httpserver/hook_phase.hpp"
#include "httpserver/http_request.hpp"
#include "httpserver/http_resource.hpp"
#include "httpserver/http_response.hpp"
#include "httpserver/detail/response_body.hpp"
#include "httpserver/detail/dispatch_util.hpp"
#include "httpserver/detail/hook_bus.hpp"
#include "httpserver/detail/connection_context.hpp"
#include "httpserver/detail/resource_hook_table.hpp"
namespace httpserver {
namespace detail {
bool hook_dispatcher::has_hooks_for(hook_phase p) const noexcept {
return hooks_.has_hooks_for(p);
}
bool hook_dispatcher::has_handler_exception_alias() const noexcept {
return hooks_.has_handler_exception_alias();
}
namespace {
// Fetch the per-route hook table (if any) from the request's
// resource_weak_ slot, keeping the shared_ptr alive in res_out so the
// caller can hold the table pointer valid. Returns nullptr when no
// per-route table exists. Uses a direct lock() (atomic) rather than
// expired()+lock() to avoid a TOCTOU window.
resource_hook_table* per_route_table(detail::connection_context* conn,
std::shared_ptr<http_resource>& res_out) {
res_out = conn->resource_weak_.lock();
if (!res_out) return nullptr;
return res_out->hook_table_raw_();
}
} // namespace
// ---- eleven per-phase forwarders -----------------------------------------
void hook_dispatcher::fire_connection_opened(
const connection_open_ctx& ctx) noexcept {
hooks_.fire_connection_opened(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
void hook_dispatcher::fire_accept_decision(const accept_ctx& ctx) noexcept {
hooks_.fire_accept_decision(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
void hook_dispatcher::fire_connection_closed(
const connection_close_ctx& ctx) noexcept {
hooks_.fire_connection_closed(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
std::optional<http_response> hook_dispatcher::fire_request_received(
request_received_ctx& ctx) noexcept {
return hooks_.fire_request_received(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
std::optional<http_response> hook_dispatcher::fire_body_chunk(
body_chunk_ctx& ctx) noexcept {
return hooks_.fire_body_chunk(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
void hook_dispatcher::fire_route_resolved(
const route_resolved_ctx& ctx) noexcept {
hooks_.fire_route_resolved(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
std::optional<http_response> hook_dispatcher::fire_before_handler(
before_handler_ctx& ctx) noexcept {
return hooks_.fire_before_handler(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
std::optional<http_response> hook_dispatcher::fire_handler_exception(
const handler_exception_ctx& ctx) noexcept {
return hooks_.fire_handler_exception(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
std::optional<http_response> hook_dispatcher::fire_after_handler(
after_handler_ctx& ctx) noexcept {
return hooks_.fire_after_handler(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
void hook_dispatcher::fire_response_sent(
const response_sent_ctx& ctx) noexcept {
hooks_.fire_response_sent(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
void hook_dispatcher::fire_request_completed(
const request_completed_ctx& ctx) noexcept {
hooks_.fire_request_completed(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
// ---- gated: before_handler (server-wide + per-route, short-circuiting) ---
bool hook_dispatcher::fire_before_handler_gated(
detail::connection_context* conn,
const std::shared_ptr<http_resource>& hrm) {
const bool server_gate = hooks_.has_hooks_for(hook_phase::before_handler);
// rtable comes from hrm directly (already resolved under the route
// table lock); hrm keeps the resource alive for this function. The
// acquire barrier from that shared_lock lets hook_table_raw_() observe
// any prior add_hook() store.
auto* rtable = hrm->hook_table_raw_();
const bool per_route_gate = rtable != nullptr &&
rtable->any_hooks(hook_phase::before_handler);
if (!server_gate && !per_route_gate) return false;
std::optional<route_descriptor> desc;
if (!conn->matched_path_template.empty()) {
desc = route_descriptor{
/*path_template=*/std::string_view{conn->matched_path_template},
/*methods=*/hrm->get_allowed_methods(),
/*is_prefix=*/conn->matched_is_prefix};
}
before_handler_ctx ctx{
/*request=*/conn->request.get(),
/*matched=*/std::move(desc),
/*method=*/conn->method_enum,
/*resource=*/hrm.get()};
if (server_gate) {
if (auto sc = fire_before_handler(ctx)) {
conn->response.emplace(std::move(*sc));
return true;
}
}
if (per_route_gate) {
if (auto sc = rtable->fire_before_handler(ctx,
[this](std::string_view m) {
log_dispatch_error(config_, m);
})) {
conn->response.emplace(std::move(*sc));
return true;
}
}
return false;
}
// ---- gated: after_handler (server-wide + per-route, replace-response) ----
void hook_dispatcher::fire_after_handler_gated(detail::connection_context* conn,
http_resource* resource) {
const bool server_gate = hooks_.has_hooks_for(hook_phase::after_handler);
// resource is borrowed from finalize_answer's live shared_ptr; no
// weak_ptr lock() needed. nullptr on the 404 path -- no per-route table.
auto* rtable = resource != nullptr ? resource->hook_table_raw_() : nullptr;
const bool route_gate = rtable != nullptr &&
rtable->any_hooks(hook_phase::after_handler);
if (!server_gate && !route_gate) return;
if (!conn->response) return; // defensive: never fire without a response
after_handler_ctx ctx{conn->request.get(), &*conn->response};
if (server_gate) {
if (auto sc = fire_after_handler(ctx)) {
// Short-circuit: REPLACE conn->response (emplace destroys the old
// response, releasing deferred captures now). The per-route
// chain ALSO sees the replaced response, so refresh ctx.
conn->response.emplace(std::move(*sc));
ctx.response = &*conn->response;
}
}
if (route_gate) {
if (auto sc = rtable->fire_after_handler(ctx,
[this](std::string_view m) {
log_dispatch_error(config_, m);
})) {
conn->response.emplace(std::move(*sc));
}
}
}
// ---- gated: response_sent (observation, server-wide + per-route) ---------
void hook_dispatcher::fire_response_sent_gated(detail::connection_context* conn,
http_resource* resource) {
const bool server_gate = hooks_.has_hooks_for(hook_phase::response_sent);
// resource is borrowed from finalize_answer's live shared_ptr, so read
// the per-route table directly instead of locking the weak_ptr. nullptr
// on the skip_handler / 404 paths.
auto* rtable = resource != nullptr ? resource->hook_table_raw_() : nullptr;
const bool route_gate = rtable != nullptr &&
rtable->any_hooks(hook_phase::response_sent);
// Whether any user hook (server-wide or per-route) will observe this
// firing. Distinct from the log_access alias slot, which fires
// regardless but never reads ctx.elapsed (see the elapsed gate below).
const bool user_gate = server_gate || route_gate;
if (!user_gate && !hooks_.has_log_access_alias()) return;
// conn->response is null only if materialize_and_queue_response's
// belt-and-suspenders fallback also failed; fire nothing rather than crash.
if (!conn->response) return;
// 0 for deferred/pipe bodies -- see response_sent_ctx docs.
const std::size_t bytes_queued = (conn->response->body_ != nullptr)
? conn->response->body_->size() : 0;
// elapsed is consumed by user hooks, not by the log_access alias.
// Skip the steady_clock::now() syscall when only the alias slot fires.
// NOTE: the alias body MUST NOT read ctx.elapsed; any future change that
// needs elapsed in the alias must also remove this optimisation.
const auto elapsed = user_gate
? std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now() - conn->start_time)
: std::chrono::nanoseconds::zero();
response_sent_ctx ctx{conn->request.get(), &*conn->response,
conn->response->get_status(), bytes_queued, elapsed};
fire_response_sent(ctx);
// Per-route chain AFTER server-wide + its alias slot.
// response_sent is observation-only; no short-circuit logic.
if (route_gate) {
rtable->fire_response_sent(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
}
// ---- gated: request_completed (fires from MHD completion callback) -------
void hook_dispatcher::fire_request_completed_gated(
detail::connection_context* conn,
enum MHD_RequestTerminationCode toe) {
const bool server_gate =
hooks_.has_hooks_for(hook_phase::request_completed);
// Per-route gate. This fires from the MHD completion callback --
// finalize_answer's owning shared_ptr is gone -- so lock() the weak_ptr
// to keep the resource alive while rtable is in use. Skip the lock()
// entirely on the common path: route_has_hook_table_ is a snapshot of
// whether the resource carried any per-route hook table; when it's false
// and no server-wide hook is registered, no control-block atomics are
// touched.
std::shared_ptr<http_resource> res;
resource_hook_table* rtable = nullptr;
if (server_gate || conn->route_has_hook_table_) {
rtable = per_route_table(conn, res);
}
const bool per_route_present = rtable != nullptr &&
rtable->any_hooks(hook_phase::request_completed);
if (!server_gate && !per_route_present) {
return;
}
const http_response* resp_ptr =
conn->response ? &*conn->response : nullptr;
// conn->start_time may be epoch if answer_to_connection never ran (e.g. a
// port scan: uri_log created conn but MHD closed before dispatch). Emit
// nanoseconds{-1} as a sentinel so hook authors can distinguish the
// degenerate case from a real (but very slow) request.
const auto raw_duration =
std::chrono::steady_clock::now() - conn->start_time;
const auto duration =
(conn->start_time == std::chrono::steady_clock::time_point{})
? std::chrono::nanoseconds{-1}
: std::chrono::duration_cast<std::chrono::nanoseconds>(
raw_duration);
request_completed_ctx ctx{
/*request=*/conn->request.get(),
/*resp=*/resp_ptr,
/*succeeded=*/(toe == MHD_REQUEST_TERMINATED_COMPLETED_OK),
/*duration=*/duration,
};
if (server_gate) {
fire_request_completed(ctx);
}
if (per_route_present) {
rtable->fire_request_completed(ctx,
[this](std::string_view m) { log_dispatch_error(config_, m); });
}
}
} // namespace detail
} // namespace httpserver