GCC Code Coverage Report


Directory: ./
File: fpphttp.h
Date: 2026-10-29 08:11:58
Exec Total Coverage
Lines: 72 76 94.7%
Functions: 12 13 92.3%
Branches: 73 132 55.3%

Line Branch Exec Source
1 #pragma once
2 /*
3 * This file is part of the Falcon Player (FPP) and is Copyright (C)
4 * 2013-2022 by the Falcon Player Developers.
5 *
6 * The Falcon Player (FPP) is free software, and is covered under
7 * multiple Open Source licenses. Please see the included 'LICENSES'
8 * file for descriptions of what files are covered by each license.
9 *
10 * This source file is covered under the LGPL v2.1 as described in the
11 * included LICENSE.LGPL file.
12 */
13
14 // HTTP helpers for FPP and for plugins, on top of Drogon.
15 // Only include the minimal drogon headers to avoid DrObject auto-registration
16 // in translation units that don't need the full framework.
17
18 // HttpRequestPtr/HttpResponsePtr/HttpCallback aliases live there so that
19 // declaration-only headers can use them without the heavy drogon include below.
20 // See fpphttp_types.h.
21 #include "fpphttp_types.h"
22
23 #include <drogon/HttpRequest.h>
24 #include <drogon/HttpResponse.h>
25
26 // Trantor (drogon dependency) defines these as macros which conflict
27 // with FPP's LogLevel enum values in log.h. Undefine them here.
28 #ifdef LOG_WARN
29 #undef LOG_WARN
30 #endif
31 #ifdef LOG_INFO
32 #undef LOG_INFO
33 #endif
34 #ifdef LOG_DEBUG
35 #undef LOG_DEBUG
36 #endif
37
38 #include <cstdint>
39 #include <cstdio>
40 #include <ctime>
41 #include <functional>
42 #include <memory>
43 #include <string>
44 #include <unistd.h>
45 #include <utility>
46 #include <vector>
47
48 // HttpRequestPtr / HttpResponsePtr / HttpCallback are defined in fpphttp_types.h
49 // (included above), so they are also available to lightweight headers.
50
51 // Helper to split a URL path into pieces (equivalent to libhttpserver's get_path_pieces())
52 886380 inline std::vector<std::string> getPathPieces(const std::string& path) {
53 886380 std::vector<std::string> pieces;
54 886380 std::string piece;
55
2/2
✓ Branch 0 taken 16491215 times.
✓ Branch 1 taken 886380 times.
17377595 for (size_t i = 0; i < path.size(); ++i) {
56
2/2
✓ Branch 0 taken 2208020 times.
✓ Branch 1 taken 14283195 times.
16491215 if (path[i] == '/') {
57
2/2
✓ Branch 0 taken 1321515 times.
✓ Branch 1 taken 886505 times.
2208020 if (!piece.empty()) {
58
1/2
✓ Branch 0 taken 1321515 times.
✗ Branch 1 not taken.
1321515 pieces.push_back(piece);
59 1321515 piece.clear();
60 }
61 } else {
62
1/2
✓ Branch 0 taken 14283195 times.
✗ Branch 1 not taken.
14283195 piece += path[i];
63 }
64 }
65
2/2
✓ Branch 0 taken 886259 times.
✓ Branch 1 taken 121 times.
886380 if (!piece.empty()) {
66
1/2
✓ Branch 0 taken 886259 times.
✗ Branch 1 not taken.
886259 pieces.push_back(piece);
67 }
68 886380 return pieces;
69 886380 }
70
71 // Helper to create a string response (equivalent to httpserver::string_response)
72 1111332 inline HttpResponsePtr makeStringResponse(const std::string& body, int statusCode = 200,
73 const std::string& contentType = "text/plain") {
74 1111332 auto resp = drogon::HttpResponse::newHttpResponse();
75
1/2
✓ Branch 0 taken 1111332 times.
✗ Branch 1 not taken.
1111332 resp->setStatusCode(static_cast<drogon::HttpStatusCode>(statusCode));
76
1/2
✓ Branch 0 taken 1111332 times.
✗ Branch 1 not taken.
1111332 resp->setBody(body);
77
3/4
✓ Branch 0 taken 1111332 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 632977 times.
✓ Branch 3 taken 478355 times.
1111332 if (contentType == "application/json") {
78
1/2
✓ Branch 0 taken 632977 times.
✗ Branch 1 not taken.
632977 resp->setContentTypeCode(drogon::CT_APPLICATION_JSON);
79 } else {
80
1/2
✓ Branch 0 taken 478355 times.
✗ Branch 1 not taken.
478355 resp->setContentTypeCodeAndCustomString(drogon::CT_CUSTOM, contentType);
81 }
82 1111332 return resp;
83 ✗ }
84
85 // ---- ETags -----------------------------------------------------------------
86 //
87 // FNV-1a, used to turn either a response body or a caller-supplied version
88 // string into a compact validator. This is a validator rather than a digest --
89 // it only has to change when the content does, and nothing depends on it being
90 // hard to forge.
91 28689 inline uint64_t fppETagHash(const std::string& s, uint64_t h = 0xcbf29ce484222325ULL) {
92
2/2
✓ Branch 0 taken 205617064 times.
✓ Branch 1 taken 28689 times.
205645753 for (unsigned char c : s) {
93 205617064 h ^= c;
94 205617064 h *= 0x100000001b3ULL;
95 }
96 28689 return h;
97 }
98
99 // True when the client's If-None-Match carries `bare`.
100 //
101 // If-None-Match may hold a list, and a cache that compressed the response on
102 // the way past can append a suffix to the tag it echoes back (`"...-gzip"`), so
103 // match on the bare tag appearing anywhere rather than on string equality.
104 13181 inline bool fppETagPresent(const HttpRequestPtr& req, const std::string& bare) {
105
3/6
✓ Branch 0 taken 13181 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 13181 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 13181 times.
✗ Branch 5 not taken.
26362 std::string inm = req->getHeader("if-none-match");
106
4/4
✓ Branch 0 taken 21 times.
✓ Branch 1 taken 13160 times.
✓ Branch 2 taken 7 times.
✓ Branch 3 taken 14 times.
26362 return !inm.empty() && inm.find(bare) != std::string::npos;
107 13181 }
108
109 7 inline HttpResponsePtr makeNotModifiedResponse(const std::string& bare) {
110 7 auto resp = drogon::HttpResponse::newHttpResponse();
111
1/2
✓ Branch 0 taken 7 times.
✗ Branch 1 not taken.
7 resp->setStatusCode(drogon::k304NotModified);
112
4/8
✓ Branch 0 taken 7 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 7 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 7 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 7 times.
✗ Branch 7 not taken.
21 resp->addHeader("ETag", "\"" + bare + "\"");
113 7 return resp;
114 ✗ }
115
116 // Build a response that carries a content-derived ETag, answering 304 when the
117 // client already holds this version.
118 //
119 // For a large, rarely-changing API result this is the difference between
120 // sending the body on every page load and sending nothing at all: the overlay
121 // effect list alone is ~350KB, and a client that goes through FPPMon's MQTT
122 // proxy pays for those bytes over someone's internet connection.
123 //
124 // This form still builds the body before it can hash it, so it saves transfer
125 // and compression but not generation. When the handler can name what it is
126 // about to serialize more cheaply than serializing it, prefer the versioned
127 // form below.
128 5510 inline HttpResponsePtr makeETagResponse(const HttpRequestPtr& req, const std::string& body,
129 const std::string& contentType = "application/json") {
130 char buf[64];
131 5511 snprintf(buf, sizeof(buf), "%llx-%llx", (unsigned long long)body.size(),
132 5510 (unsigned long long)fppETagHash(body));
133
1/2
✓ Branch 0 taken 5510 times.
✗ Branch 1 not taken.
5510 std::string bare(buf);
134
135
2/4
✓ Branch 0 taken 5510 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 5510 times.
5510 if (fppETagPresent(req, bare)) {
136 ✗ return makeNotModifiedResponse(bare);
137 }
138
1/2
✓ Branch 0 taken 5510 times.
✗ Branch 1 not taken.
5510 auto resp = makeStringResponse(body, 200, contentType);
139
4/8
✓ Branch 0 taken 5510 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 5510 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 5510 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 5510 times.
✗ Branch 7 not taken.
16529 resp->addHeader("ETag", "\"" + bare + "\"");
140 5510 return resp;
141 5510 }
142
143 // ---- Versioned ETags -------------------------------------------------------
144 //
145 // The content hash above cannot answer a conditional request without first
146 // building the answer, and on the slow boards building is the expensive half:
147 // /api/overlays/effects?full=true takes 0.9-3.4s of a PocketBeagle2 to
148 // serialize but only ~10KB to send once gzipped. A handler that can name its
149 // own version -- a counter bumped when the underlying data changes, a file
150 // mtime -- can answer 304 without doing that work at all.
151 //
152 // `version` need only distinguish one state of the data from the next; it is
153 // never parsed by the client. Two things are folded in for you:
154 //
155 // - the request path and query string, so a handler whose output varies on
156 // parameters (?simple=true, ?full=true) cannot serve one variant's body
157 // under another variant's tag by using a single counter for all of them;
158 // - a per-process salt, because an in-memory counter restarts at zero. Without
159 // it a client holding a tag from before an fppd restart would be told 304
160 // against a *different* command or model set that happens to be at the same
161 // count. The cost is that a restart invalidates these tags, which is the
162 // right way round: a false 304 serves stale content, a false 200 only costs
163 // bytes.
164 7677 inline std::string makeETagToken(const HttpRequestPtr& req, const std::string& version) {
165
7/14
✓ Branch 0 taken 148 times.
✓ Branch 1 taken 7529 times.
✓ Branch 2 taken 148 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 148 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 148 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 148 times.
✗ Branch 9 not taken.
✓ Branch 10 taken 148 times.
✗ Branch 11 not taken.
✗ Branch 12 not taken.
✗ Branch 13 not taken.
7677 static const uint64_t salt = fppETagHash(std::to_string((unsigned long long)::time(nullptr)) + "-" + std::to_string((long)::getpid()));
166
167 7677 uint64_t h = fppETagHash(version, salt);
168
1/2
✓ Branch 0 taken 7677 times.
✗ Branch 1 not taken.
7677 h = fppETagHash(req->path(), h);
169
1/2
✓ Branch 0 taken 7677 times.
✗ Branch 1 not taken.
7677 h = fppETagHash(req->query(), h);
170 char buf[64];
171 7677 snprintf(buf, sizeof(buf), "v%llx", (unsigned long long)h);
172
1/2
✓ Branch 0 taken 7677 times.
✗ Branch 1 not taken.
15354 return std::string(buf);
173 }
174
175 // True when the client already holds this version of this route, and the
176 // handler can skip building the body entirely. Pair it with
177 // makeVersionedETagResponse() below so the 200 goes back carrying the same tag:
178 //
179 // std::string ver = std::to_string(generation);
180 // if (etagMatches(req, ver)) {
181 // return makeNotModifiedResponse(makeETagToken(req, ver));
182 // }
183 // ... build body ...
184 // return makeVersionedETagResponse(req, ver, body);
185 //
186 // The callable overload does both halves in one step and is harder to get
187 // wrong -- forgetting the tag on the 200 leaves a client that can never
188 // revalidate, which fails silently as "the ETag does nothing".
189 3808 inline bool etagMatches(const HttpRequestPtr& req, const std::string& version) {
190
2/4
✓ Branch 0 taken 3808 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 3808 times.
✗ Branch 3 not taken.
3808 return fppETagPresent(req, makeETagToken(req, version));
191 }
192
193 // Body already in hand.
194 3802 inline HttpResponsePtr makeVersionedETagResponse(const HttpRequestPtr& req, const std::string& version,
195 const std::string& body,
196 const std::string& contentType = "application/json") {
197
1/2
✓ Branch 0 taken 3802 times.
✗ Branch 1 not taken.
3802 std::string bare = makeETagToken(req, version);
198
2/4
✓ Branch 0 taken 3802 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 3802 times.
3802 if (fppETagPresent(req, bare)) {
199 ✗ return makeNotModifiedResponse(bare);
200 }
201
1/2
✓ Branch 0 taken 3802 times.
✗ Branch 1 not taken.
3802 auto resp = makeStringResponse(body, 200, contentType);
202
4/8
✓ Branch 0 taken 3802 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 3802 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 3802 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 3802 times.
✗ Branch 7 not taken.
11406 resp->addHeader("ETag", "\"" + bare + "\"");
203 3802 return resp;
204 3802 }
205
206 // Preferred form: `bodyFn` runs only on a miss, so a 304 costs a hash and
207 // nothing else. SFINAE on callability keeps this from competing with the
208 // std::string overload above.
209 template <typename BodyFn, typename = decltype(std::declval<BodyFn&>()())>
210 61 inline HttpResponsePtr makeVersionedETagResponse(const HttpRequestPtr& req, const std::string& version,
211 BodyFn&& bodyFn,
212 const std::string& contentType = "application/json") {
213
1/2
✓ Branch 0 taken 61 times.
✗ Branch 1 not taken.
61 std::string bare = makeETagToken(req, version);
214
3/4
✓ Branch 0 taken 61 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 60 times.
61 if (fppETagPresent(req, bare)) {
215
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 return makeNotModifiedResponse(bare);
216 }
217
2/4
✓ Branch 0 taken 60 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 60 times.
✗ Branch 3 not taken.
60 auto resp = makeStringResponse(bodyFn(), 200, contentType);
218
4/8
✓ Branch 0 taken 60 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 60 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 60 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 60 times.
✗ Branch 7 not taken.
180 resp->addHeader("ETag", "\"" + bare + "\"");
219 60 return resp;
220 61 }
221
222 // Helper to get a request parameter (query string or form parameter)
223 // Equivalent to libhttpserver's req.get_arg("key")
224 522223 inline std::string getRequestArg(const HttpRequestPtr& req, const std::string& key) {
225 522223 return req->getParameter(key);
226 }
227
228 // Helper to get request body as string
229 // Equivalent to libhttpserver's req.get_content()
230 418127 inline std::string getRequestContent(const HttpRequestPtr& req) {
231
2/4
✓ Branch 0 taken 418127 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 418127 times.
✗ Branch 3 not taken.
421473 return std::string(req->body());
232 }
233
234 // Helper to get query string
235 // Equivalent to libhttpserver's req.get_querystring()
236 inline std::string getQueryString(const HttpRequestPtr& req) {
237 return req->query();
238 }
239
240 // ---- Plugin HTTP API registration -----------------------------------------
241 //
242 // Plugins must register their HTTP routes through these rather than calling
243 // drogon::app().registerHandler() directly, because drogon has no route removal
244 // API. A handler registered straight with drogon is a function pointer into the
245 // plugin's .so that can never be withdrawn, which makes the plugin impossible to
246 // unload -- and impossible to upgrade in place, since a newly loaded build
247 // cannot take over a path the retired one still owns.
248 //
249 // What FPP does instead: the drogon route is registered once, ever, per path,
250 // and belongs to FPP. It dispatches through a slot that lives here in libfpp,
251 // not in any plugin. registerPluginApi() arms that slot; unregisterPluginApi()
252 // disarms it and requests to the path answer 410 Gone. A later
253 // registerPluginApi() for the same path re-arms the same slot, so a replacement
254 // build of the plugin picks the route straight back up.
255 //
256 // unregisterPluginApi() does not return until no request is executing inside the
257 // handler AND the handler object itself has been destroyed -- the plugin's own
258 // callable, whose code and captured state live in the .so. That is the ordering
259 // that makes a subsequent dlclose() safe: destroy while still mapped, then
260 // unmap. (A handler that unregistered its own path from inside itself would
261 // deadlock. Nothing should do that.)
262 //
263 // This covers inbound HTTP only. A handler that hands work to another thread is
264 // responsible for that thread itself, in FPPPlugins::Plugin::shutdown().
265 namespace FPPPlugins {
266
267 // Same shape drogon's registerHandler() takes.
268 using PluginApiHandler = std::function<void(const HttpRequestPtr&, HttpCallback&&)>;
269
270 // Registers (or re-arms) 'path'. With family=true, subpaths of 'path' route to
271 // the same handler as well.
272 void registerPluginApi(const std::string& path, PluginApiHandler handler,
273 const std::vector<drogon::HttpMethod>& methods = { drogon::Get, drogon::Post, drogon::Put,
274 drogon::Delete, drogon::Head },
275 bool family = false);
276
277 // Disarms 'path' (and its family subpaths, if any were registered) and destroys
278 // the handler before returning. Safe to call for a path that was never
279 // registered, and safe to call twice.
280 void unregisterPluginApi(const std::string& path);
281
282 // FPP-internal. installPluginApiRouter() hooks the registry into drogon; fppd
283 // calls it once, before app().run(). listPluginApiRoutes() returns the armed
284 // paths, a family registration listed as "<path>/.*".
285 void installPluginApiRouter();
286 std::vector<std::pair<std::string, drogon::HttpMethod>> listPluginApiRoutes();
287
288 } // namespace FPPPlugins
289
290