-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHttpServerModule.cpp
More file actions
1871 lines (1735 loc) · 92.5 KB
/
Copy pathHttpServerModule.cpp
File metadata and controls
1871 lines (1735 loc) · 92.5 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// HttpServerModule implementation. Public surface and class layout live in
// HttpServerModule.h. Per the project policy in CLAUDE.md, core service modules
// that bridge to the platform (HTTP server, WebSocket framing, JSON state push)
// split into .h + .cpp so implementation edits don't cascade-recompile every TU
// that includes the header.
#include "core/HttpServerModule.h"
#include "core/Scheduler.h"
#include "core/ModuleFactory.h"
#include "core/JsonUtil.h"
#include "core/JsonSink.h"
#include "core/Sha1.h"
#include "core/Base64.h"
#include "core/FilesystemModule.h"
#include "core/FirmwareUpdateModule.h"
#include "core/SystemModule.h" // deviceName() for the WLED /json/info shim
#include "platform/platform.h"
#include "ui/ui_embedded.h"
#include <climits>
#include <cstdarg>
#include <cstdio>
#include <cstdlib> // strtol — bounded Content-Length parse
#include <cerrno> // errno / ERANGE — Content-Length overflow check
#include <cstring>
#include <cstdint>
namespace mm {
void HttpServerModule::onBuildControls() {
controls_.addUint16("port", port);
}
void HttpServerModule::setup() {
if (!server_.open(port)) {
std::printf("HTTP server failed to open port %u\n", port);
}
}
void HttpServerModule::teardown() {
previewSend_.active = false; // drop any in-flight send before the clients go (body is borrowed)
for (auto& ws : wsClients_) ws.close();
server_.close();
}
void HttpServerModule::loop20ms() {
// Drain the in-flight resumable preview frame on the TRANSPORT-poll cadence (20 ms), NOT the
// per-render-tick loop(): pushing frame bytes to the socket must not be charged to the LED
// render hot path. The render tick stays free of preview work; the preview frame rate is
// bounded by this 20 ms drain cadence (a few fps at large full-res frames) — an acceptable
// trade, since the preview is a *view* and the LEDs are not. This drain is the consumer-side
// transport step, kept as a standalone call so it sits cleanly on the render/transport seam
// (architecture.md § Parallelism). Drain BEFORE accept so a connection burst can't starve an
// active send. No-op when nothing is in flight.
drainPreviewSend();
// Read any inbound WS frames: the native WLED app SETS state (its on/off + brightness
// slider) by SENDING a {on,bri} text frame over /ws, not by HTTP POST — so we must read
// the socket, not only push to it. Cheap (non-blocking, usually nothing pending).
pollWledStateFromWebSockets();
// Accept one HTTP connection per tick.
auto conn = server_.accept();
if (conn.valid()) handleConnection(conn);
}
void HttpServerModule::loop1s() {
pushStateToWebSockets();
}
void HttpServerModule::handleConnection(platform::TcpConnection& conn) {
uint8_t buf[2048];
int totalRead = 0;
// Read the request. read() is non-blocking (-1 = nothing pending yet), so the render
// loop is never stalled waiting for bytes (a blocking socket timeout used to freeze the
// whole loop). A just-accepted connection's request normally lands in the same read; if
// not, allow a SHORT bounded wait (≤ ~5 ms total) for it, then bail — an idle/half-open
// connection costs at most that, and the steady-state (nothing pending) costs ~0.
for (int empties = 0; totalRead < static_cast<int>(sizeof(buf) - 1);) {
int n = conn.read(buf + totalRead, sizeof(buf) - 1 - totalRead);
if (n > 0) {
totalRead += n;
buf[totalRead] = 0;
if (std::strstr(reinterpret_cast<char*>(buf), "\r\n\r\n")) break;
empties = 0; // got data — reset the patience counter
} else if (n == 0) {
return; // peer closed
} else { // -1 = nothing pending yet
if (totalRead > 0) break; // had a partial then nothing more — process it
if (++empties > 5) break; // fresh conn, no bytes after ~5 ms — give up
platform::delayMs(1);
}
}
if (totalRead == 0) { conn.close(); return; }
buf[totalRead] = 0;
auto* req = reinterpret_cast<char*>(buf);
// If headers arrived but the body is still in flight, read the rest. read() is
// non-blocking (-1 = nothing pending yet), so the body can land a TCP segment after the
// headers — wait briefly between empty reads (the same bounded retry as the header
// phase) instead of breaking on the first -1, which would route a TRUNCATED body into
// the permissive JSON helpers (a silent partial control write). If the full declared
// body still hasn't arrived within the budget, reject with 400 rather than process it.
auto* headerEnd = std::strstr(req, "\r\n\r\n");
int contentLen = 0; // declared body length (0 if no Content-Length); used by the streaming route
if (headerEnd) {
auto* clh = std::strstr(req, "Content-Length:");
if (clh) {
// Bounded parse (not atoi): a malformed/negative/overflowing Content-Length must not
// flow downstream, where it's cast to size_t — a negative int would become a huge
// length that UploadSource/handleFirmwareUpload would treat as "gigabytes still to
// come". We reject anything that isn't a clean unsigned integer: strtol with an end
// pointer catches non-numeric, trailing junk ("123abc"), and ERANGE overflow; then we
// reject negative and clamp to a firmware-sized ceiling (8 MB > any image we flash),
// returning 400 rather than acting on it. The value ends at CR/LF/space or the string end.
constexpr long kContentLenMax = 8L * 1024 * 1024;
const char* valStart = clh + 15;
while (*valStart == ' ' || *valStart == '\t') valStart++; // skip OWS after the colon
char* valEnd = nullptr;
errno = 0;
const long parsed = std::strtol(valStart, &valEnd, 10);
const bool consumedDigits = valEnd != valStart;
const bool endsCleanly = *valEnd == '\r' || *valEnd == '\n' || *valEnd == ' ' ||
*valEnd == '\t' || *valEnd == '\0';
if (!consumedDigits || !endsCleanly || errno == ERANGE ||
parsed < 0 || parsed > kContentLenMax) {
sendResponse(conn, 400, "application/json",
"{\"error\":\"invalid content-length\"}");
return;
}
contentLen = static_cast<int>(parsed);
int headerSize = static_cast<int>(headerEnd + 4 - req);
int bodyNeeded = headerSize + contentLen;
// Only the STREAMING routes (/api/file, /api/firmware/upload) may carry a body larger than
// buf — they take the buffered prefix and pull the remainder straight off the socket. For
// every OTHER route the body is parsed whole from buf, so a body over the buffer must be
// REJECTED (413), not truncated: a capped read would parse a JSON prefix as if complete
// (its own bodyNeeded check wouldn't fire, since the cap makes the short read "enough").
// The request line sits at the start of req; a substring match on the path is sufficient.
const bool isStreamingRoute =
std::strncmp(req, "POST /api/file", 14) == 0 ||
std::strncmp(req, "POST /api/firmware/upload", 25) == 0;
if (bodyNeeded > static_cast<int>(sizeof(buf) - 1)) {
if (!isStreamingRoute) {
sendResponse(conn, 413, "application/json",
"{\"error\":\"request body too large\"}");
return;
}
bodyNeeded = static_cast<int>(sizeof(buf) - 1); // streaming: buffer the prefix only
}
for (int empties = 0; totalRead < bodyNeeded;) {
int n = conn.read(buf + totalRead, sizeof(buf) - 1 - totalRead);
if (n > 0) { totalRead += n; empties = 0; }
else if (n == 0) break; // peer closed
else { if (++empties > 50) break; platform::delayMs(1); } // ~50 ms for the body
}
buf[totalRead] = 0;
if (totalRead < bodyNeeded) { // body never fully arrived
sendResponse(conn, 400, "application/json",
"{\"error\":\"incomplete request body\"}");
return;
}
}
}
// Parse method and path
char method[8] = {};
char path[128] = {};
std::sscanf(req, "%7s %127s", method, path);
// Strip any query string before route matching — every strcmp() below
// expects a bare path. RFC 3986 §3.4: the query starts at the first '?'
// and is not part of the path. Browsers send `/?foo=bar` for query-on-
// root; without this split the GET / route falls through to 404. The web
// installer's Inject button hits us as `/?deviceModel=<name>` to hand off the
// deviceModels.json entry — see docs/moonmodules/core/moxygen/SystemModule.md.
char* queryStart = std::strchr(path, '?');
if (queryStart) *queryStart = 0;
// Check for WebSocket upgrade (case-insensitive header check)
if (std::strcmp(method, "GET") == 0 && std::strcmp(path, "/ws") == 0 &&
(std::strstr(req, "Upgrade: websocket") || std::strstr(req, "upgrade: websocket") ||
std::strstr(req, "Upgrade: WebSocket"))) {
handleWebSocketUpgrade(conn, req);
return; // don't close — connection is now a WebSocket
}
// Read POST body if present
// Body pointer (headerEnd already found above)
char* body = headerEnd ? const_cast<char*>(headerEnd) + 4 : nullptr;
// Route
if (std::strcmp(method, "GET") == 0) {
if (std::strcmp(path, "/") == 0) serveFile(conn, "index.html", "text/html");
else if (std::strcmp(path, "/app.js") == 0) serveFile(conn, "app.js", "application/javascript");
else if (std::strcmp(path, "/install-picker.js") == 0) serveFile(conn, "install-picker.js", "application/javascript");
else if (std::strcmp(path, "/semver.js") == 0) serveFile(conn, "semver.js", "application/javascript");
else if (std::strcmp(path, "/preview3d.js") == 0) serveFile(conn, "preview3d.js", "application/javascript");
else if (std::strcmp(path, "/style.css") == 0) serveFile(conn, "style.css", "text/css");
else if (std::strcmp(path, "/moonlight-logo.png") == 0) serveFile(conn, "moonlight-logo.png", "image/png");
else if (std::strcmp(path, "/api/state") == 0) serveState(conn);
else if (std::strcmp(path, "/api/system") == 0) serveSystem(conn);
else if (std::strcmp(path, "/api/types") == 0) serveTypes(conn);
// File Manager: GET /api/dir?path=<rel>[&hidden=1] → one directory's children as JSON
// [{name,isDir,size}] (the lazy tree loads a node's children on expand).
else if (std::strcmp(path, "/api/dir") == 0) serveDirListing(conn, queryStart ? queryStart + 1 : "");
// File Manager: GET /api/file?path=<rel> → the file's contents (text, size-capped).
else if (std::strcmp(path, "/api/file") == 0) serveFileContents(conn, queryStart ? queryStart + 1 : "");
// WLED-compatibility shim: the native WLED apps (and Home Assistant's WLED
// integration) discover a device via mDNS `_wled._tcp` then VALIDATE it by
// GETting /json/info and checking it's WLED-shaped. Serving a minimal
// WLED-compatible info makes a projectMM device appear in those apps — and is a
// useful independent cross-check that our mDNS advertise resolves.
else if (std::strcmp(path, "/json/info") == 0) serveWledInfo(conn);
// WLED state + the combined state+info (`/json/si`) the app reads for its device
// card: on/off, brightness, and the segment's primary colour (which the app uses
// as the card tint). serveWledState reads live brightness from the Drivers module.
else if (std::strcmp(path, "/json/state") == 0) serveWledState(conn);
else if (std::strcmp(path, "/json/si") == 0) serveWledStateInfo(conn);
else sendResponse(conn, 404, "text/plain", "Not found");
} else if (std::strcmp(method, "POST") == 0) {
// POST /api/modules/<name>/move with body {"to":N}.
// Strict-suffix check: path must end with "/move" exactly (rejects "/movex").
const size_t pathLen = std::strlen(path);
const bool isMoveRoute =
std::strncmp(path, "/api/modules/", 13) == 0 &&
pathLen > 18 &&
std::strcmp(path + pathLen - 5, "/move") == 0;
// POST /api/modules/<name>/replace with body {"type":"<TypeName>"}.
// Strict-suffix check, same as the move route.
const bool isReplaceRoute =
std::strncmp(path, "/api/modules/", 13) == 0 &&
pathLen > 21 &&
std::strcmp(path + pathLen - 8, "/replace") == 0;
if (std::strcmp(path, "/api/control") == 0 && body) {
handleSetControl(conn, body);
} else if (std::strcmp(path, "/api/file") == 0 && body) {
// File Manager: POST /api/file?path=<rel>, the body → streamed atomic write. `body`
// points at the bytes already buffered (initialLen); the full length is Content-Length,
// and handleWriteFile pulls any remainder straight off the socket — so an upload of any
// size streams to the file without a whole-request buffer or a strlen (binary-safe).
const size_t initialLen = static_cast<size_t>(totalRead) - static_cast<size_t>(body - req);
handleWriteFile(conn, queryStart ? queryStart + 1 : "", body, initialLen,
static_cast<size_t>(contentLen));
} else if (std::strcmp(path, "/api/dir") == 0) {
// File Manager: POST /api/dir?path=<rel> → mkdir. The path is the whole operation (a
// create is a filesystem action, not a stored control), so it rides the request query
// — same path-as-query shape as /api/file, no persisted control holds it.
handleMakeDir(conn, queryStart ? queryStart + 1 : "");
} else if (std::strcmp(path, "/api/modules") == 0 && body) {
handleAddModule(conn, body);
} else if (isMoveRoute && body) {
char nameBuf[32] = {};
size_t nameLen = pathLen - 13 - 5; // strip "/api/modules/" prefix and "/move" suffix
// Reject rather than truncate — a truncated name could match a
// different module than the client intended.
if (nameLen >= sizeof(nameBuf)) {
sendResponse(conn, 400, "application/json", "{\"error\":\"module name too long\"}");
} else {
std::memcpy(nameBuf, path + 13, nameLen);
nameBuf[nameLen] = 0;
handleMoveModule(conn, nameBuf, body);
}
} else if (isReplaceRoute && body) {
char nameBuf[32] = {};
size_t nameLen = pathLen - 13 - 8; // strip "/api/modules/" prefix and "/replace" suffix
if (nameLen >= sizeof(nameBuf)) {
sendResponse(conn, 400, "application/json", "{\"error\":\"module name too long\"}");
} else {
std::memcpy(nameBuf, path + 13, nameLen);
nameBuf[nameLen] = 0;
handleReplaceModule(conn, nameBuf, body);
}
} else if (std::strcmp(path, "/json/state") == 0 && body) {
// WLED-compatibility: the native WLED app POSTs {on,bri,…} here to control the
// device. We map it onto the Drivers brightness control so the app's on/off +
// brightness slider drive the real output.
handleWledState(conn, body);
} else if (std::strcmp(path, "/api/reboot") == 0) {
handleReboot(conn);
} else if (std::strcmp(path, "/api/firmware/url") == 0 && body) {
handleFirmwareUrl(conn, body);
} else if (std::strcmp(path, "/api/firmware/upload") == 0 && body) {
// OTA from an uploaded .bin body (no URL, no host to serve it) — the browser POSTs the
// firmware image straight to the device, which streams it into the OTA partition. Same
// streamed-body handling as /api/file (initial buffered bytes + socket remainder).
const size_t initialLen = static_cast<size_t>(totalRead) - static_cast<size_t>(body - req);
handleFirmwareUpload(conn, body, initialLen, static_cast<size_t>(contentLen));
} else {
sendResponse(conn, 404, "text/plain", "Not found");
}
} else if (std::strcmp(method, "DELETE") == 0) {
// DELETE /api/modules/ModuleName
if (std::strncmp(path, "/api/modules/", 13) == 0) {
handleDeleteModule(conn, path + 13);
} else if (std::strcmp(path, "/api/dir") == 0) {
// File Manager: DELETE /api/dir?path=<rel> → remove a file or empty dir.
handleRemoveEntry(conn, queryStart ? queryStart + 1 : "");
} else {
sendResponse(conn, 404, "text/plain", "Not found");
}
} else if (std::strcmp(method, "OPTIONS") == 0) {
// CORS preflight. The browser sends OPTIONS before any cross-origin
// POST with a non-simple Content-Type (e.g. application/json), which
// covers every /api/control and /api/modules write the web installer
// makes from preview / localhost. Without this branch the dispatcher
// fell through to 405 Method Not Allowed and the browser silently
// blocked the subsequent POST. The response carries the same
// Access-Control-Allow-Origin: * the actual response already does,
// plus the methods + headers we accept on the API surface. 204 (no
// body) is the conventional preflight reply.
//
// Path-agnostic: we return 204 for OPTIONS to ANY path, even ones
// that would 404 on a real GET/POST. Most public servers narrow
// preflight to known API routes; we don't bother because the
// device's HTTP surface is tiny and lives behind the user's LAN.
// A scanner hitting OPTIONS /random gets a CORS-OK 204 rather
// than a 404 — informational only, no behaviour change.
sendPreflightResponse(conn);
} else {
sendResponse(conn, 405, "text/plain", "Method not allowed");
}
conn.close();
}
void HttpServerModule::sendPreflightResponse(platform::TcpConnection& conn) {
// 204 No Content is the standard preflight success reply. The
// Access-Control-Allow-* headers tell the browser what cross-origin
// requests we accept on the API. Max-Age caches the preflight for an
// hour so subsequent same-session POSTs go straight through.
const char* response =
"HTTP/1.1 204 No Content\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS\r\n"
"Access-Control-Allow-Headers: Content-Type\r\n"
"Access-Control-Max-Age: 3600\r\n"
"Connection: close\r\n"
"\r\n";
conn.write(reinterpret_cast<const uint8_t*>(response), std::strlen(response));
}
void HttpServerModule::sendResponse(platform::TcpConnection& conn, int status, const char* contentType, const char* body) {
const char* statusText =
status == 200 ? "OK" :
status == 202 ? "Accepted" :
status == 400 ? "Bad Request" :
status == 404 ? "Not Found" :
status == 405 ? "Method Not Allowed" :
status == 409 ? "Conflict" :
status == 500 ? "Internal Server Error" :
status == 501 ? "Not Implemented" :
"Error";
char header[256];
int bodyLen = static_cast<int>(std::strlen(body));
int headerLen = std::snprintf(header, sizeof(header),
"HTTP/1.1 %d %s\r\n"
"Content-Type: %s\r\n"
"Content-Length: %d\r\n"
"Connection: close\r\n"
"Access-Control-Allow-Origin: *\r\n"
"\r\n",
status, statusText, contentType, bodyLen);
conn.write(reinterpret_cast<const uint8_t*>(header), headerLen);
conn.write(reinterpret_cast<const uint8_t*>(body), bodyLen);
}
// --- File Manager file read/write (the /api/file endpoints) ---
//
// A file body isn't a control value, so these are their own small endpoints (not /api/control).
// The path comes as a query param `path=<rel>`; parseFilePath vets it (reject "..", root at the
// mount) — the single traversal guard shared by every filesystem HTTP entry (read, write, dir
// listing, mkdir, delete).
//
// Read + write both stream: the write pulls the request body chunk-by-chunk straight to the file
// (fsWriteStream), the read pulls the file into a size-fit buffer — so a file of any size up- and
// downloads intact without a fixed cap. kUploadMax is a per-request sanity ceiling; a legit upload
// is additionally rejected up front if it wouldn't fit the free filesystem space.
static constexpr size_t kUploadMax = 256 * 1024; // 256 KB — sanity bound on one upload
// Copy the `path=` query value into `out` (decoding %XX and '+' minimally), rooted at the mount.
// Returns false on a missing/empty path or a ".." traversal attempt.
//
// Deliberately NOT a `.config`/dotfile denylist (PO decision): the File Manager is a device-admin
// tool on a trusted LAN, and reading the persisted `.config/*.json` is a feature (inspect/back up
// the device's own config), not a leak — there are no third-party secrets on the device, and the
// WiFi password is XOR-obfuscated in what it writes. The weak-protection is `show hidden` defaulting
// off (FileManagerModule), so `.config` isn't shown unless the operator asks. Reviewers periodically
// flag this as a secrets-exposure — it's an accepted design, not an oversight; leave it.
bool HttpServerModule::parseFilePath(const char* query, char* out, size_t cap) {
const char* p = query ? std::strstr(query, "path=") : nullptr;
if (!p) return false;
p += 5; // past "path="
size_t i = 0;
// The path may be its own query (stop at '&') and percent-encoded ('/' → %2F, ' ' → %20).
while (*p && *p != '&' && i + 1 < cap) {
char c = *p;
if (c == '%' && p[1] && p[2]) { // %XX → byte
auto hex = [](char h) -> int {
if (h >= '0' && h <= '9') return h - '0';
if (h >= 'a' && h <= 'f') return h - 'a' + 10;
if (h >= 'A' && h <= 'F') return h - 'A' + 10;
return -1;
};
const int hi = hex(p[1]), lo = hex(p[2]);
if (hi >= 0 && lo >= 0) { c = static_cast<char>((hi << 4) | lo); p += 2; }
} else if (c == '+') {
c = ' ';
}
out[i++] = c;
p++;
}
// Reject an overlong path outright rather than routing on a truncated prefix: if the loop stopped
// because the buffer filled (still more path bytes to come, i.e. not at '\0' or the '&' delimiter),
// the decoded value is incomplete and must not be treated as a valid path.
if (*p && *p != '&') return false;
out[i] = 0;
if (i == 0 || std::strstr(out, "..")) return false; // empty or traversal → reject
if (out[0] != '/') { // relative → root at the mount
char rooted[160];
const int n = std::snprintf(rooted, sizeof(rooted), "/%s", out);
if (n <= 0 || static_cast<size_t>(n) >= cap) return false;
std::strncpy(out, rooted, cap - 1); out[cap - 1] = 0;
}
return true;
}
// --- File Manager directory listing (the /api/dir endpoint) ---
//
// One directory's children as a JSON array, the source the lazy tree loads a node's children from.
// Single-level only (platform::fsList) — the recursion is the UI's job, one fetch per expanded node,
// the standard file-tree shape. The `hidden` query flag (hidden=1) includes dot-prefixed entries.
// The listing streams straight to the socket (as serveState does) — no whole-listing buffer. The
// fsList C callback carries the streaming sink + the hidden filter + a first-row flag via `user`.
namespace {
struct DirListState {
JsonSink* sink;
bool showHidden;
bool first = true;
};
void dirListTrampoline(const char* name, bool isDir, uint32_t size, void* user) {
auto* st = static_cast<DirListState*>(user);
if (!st->showHidden && name[0] == '.') return; // dotfile convention
if (!st->first) st->sink->append(",");
st->first = false;
st->sink->append("{\"name\":");
st->sink->writeJsonString(name);
st->sink->appendf(",\"isDir\":%s,\"size\":%lu}",
isDir ? "true" : "false", static_cast<unsigned long>(size));
}
} // namespace
void HttpServerModule::serveDirListing(platform::TcpConnection& conn, const char* query) {
char path[160];
if (!parseFilePath(query, path, sizeof(path))) {
sendResponse(conn, 400, "application/json", "{\"error\":\"bad path\"}");
return;
}
const char* header =
"HTTP/1.1 200 OK\r\n"
"Content-Type: application/json\r\n"
"Connection: close\r\n"
"Access-Control-Allow-Origin: *\r\n"
"\r\n";
conn.write(reinterpret_cast<const uint8_t*>(header), std::strlen(header));
JsonSink sink(conn);
DirListState st{&sink, query && std::strstr(query, "hidden=1") != nullptr, true};
sink.append("[");
platform::fsList(path, &dirListTrampoline, &st);
sink.append("]");
sink.flush();
}
// POST /api/dir?path=<rel> → mkdir. The path rides the query and is vetted by parseFilePath (the
// same `..`-reject + root-at-mount guard /api/file and /api/dir GET use). A create is a filesystem
// action, not a stored control — no persisted `path` control holds it, so no flash write.
void HttpServerModule::handleMakeDir(platform::TcpConnection& conn, const char* query) {
char path[160];
if (!parseFilePath(query, path, sizeof(path))) {
sendResponse(conn, 400, "application/json", "{\"error\":\"bad path\"}");
return;
}
if (platform::fsMkdir(path)) sendResponse(conn, 200, "application/json", "{\"ok\":true}");
else sendResponse(conn, 500, "application/json", "{\"error\":\"mkdir failed\"}");
}
// DELETE /api/dir?path=<rel> → remove a file or EMPTY dir (fsRemove fails cleanly on a non-empty
// dir). Same path guard as handleMakeDir.
void HttpServerModule::handleRemoveEntry(platform::TcpConnection& conn, const char* query) {
char path[160];
if (!parseFilePath(query, path, sizeof(path))) {
sendResponse(conn, 400, "application/json", "{\"error\":\"bad path\"}");
return;
}
if (platform::fsRemove(path)) sendResponse(conn, 200, "application/json", "{\"ok\":true}");
else sendResponse(conn, 500, "application/json", "{\"error\":\"delete failed (folder not empty?)\"}");
}
void HttpServerModule::serveFileContents(platform::TcpConnection& conn, const char* query) {
char path[160];
if (!parseFilePath(query, path, sizeof(path))) {
sendResponse(conn, 400, "application/json", "{\"error\":\"bad path\"}");
return;
}
// Stream the file straight to the socket in fixed 1 KB chunks (fsReadAt) with an explicit
// Content-Length header — no whole-file buffer, and NUL-safe (sendResponse strlen()s its body, so
// it can't carry binary). Symmetric with the streamed upload: a file of any size downloads whole.
const long size = platform::fsSize(path);
if (size < 0) { sendResponse(conn, 404, "application/json", "{\"error\":\"not found\"}"); return; }
char header[160];
const int hn = std::snprintf(header, sizeof(header),
"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %ld\r\n"
"Connection: close\r\nAccess-Control-Allow-Origin: *\r\n\r\n", size);
conn.write(reinterpret_cast<const uint8_t*>(header), static_cast<size_t>(hn));
char chunk[1024];
for (long offset = 0; offset < size;) {
const size_t want = static_cast<size_t>(size - offset) < sizeof(chunk)
? static_cast<size_t>(size - offset) : sizeof(chunk);
const int got = platform::fsReadAt(path, offset, chunk, want);
if (got <= 0) break; // read error / early EOF — the client sees a short (truncated) body
conn.write(reinterpret_cast<const uint8_t*>(chunk), static_cast<size_t>(got));
offset += got;
}
}
// Source state for the streamed upload: yields the body bytes already sitting in the request buffer,
// then reads the remainder straight off the socket — feeding fsWriteStream in fixed chunks so the
// device never holds the whole upload in RAM.
namespace {
// This drain runs SYNCHRONOUSLY on the loop20ms() tick, which is inside Scheduler::tick — so it
// blocks rendering for the duration of the transfer (LEDs freeze until the upload completes or a
// bound trips). Accepted trade-off: an upload is user-initiated and transient (and a firmware upload
// reboots the device anyway), so a brief freeze is fine where a persistent one wouldn't be. The two
// bounds cap how long that freeze can last, because neither alone is enough:
// - kUploadIdleMs: max wait for the NEXT byte, reset on every successful read. Scales to
// any size the endpoint accepts — a big but steady upload (256 KB over slow LittleFS +
// weak WiFi) never trips it, because progress keeps resetting the clock. But idle-only
// lets a slowloris trickle one byte just under the idle limit forever, freezing rendering
// (and the HTTP server) for as long as it keeps dribbling.
// - kUploadHardMs: an absolute whole-request ceiling that closes that hole. Sized well
// above a legit worst case (256 KB / ~50 KB/s ≈ 5 s, plus wide margin) so a real slow
// upload finishes, but far below the days a byte-per-idle-window trickler would need.
// A single budget can't do both jobs; the pair does (idle scales, hard caps the total). The
// zero-freeze fix (drain a chunk per tick, like drainPreviewSend) is backlogged; the bounded
// synchronous drain is the accepted interim.
constexpr uint32_t kUploadIdleMs = 5000; // max gap between successful reads before abort
constexpr uint32_t kUploadHardMs = 60000; // absolute whole-request ceiling (anti-slowloris)
struct UploadSource {
platform::TcpConnection* conn;
const char* initial; // body bytes already read into the request buffer
size_t initialLeft; // how many of those remain to hand out
size_t remaining; // total body bytes still to deliver (Content-Length − delivered)
uint32_t hardDeadline; // absolute millis by which the whole body must arrive
};
size_t uploadPull(char* out, size_t cap, void* user, bool* abort) {
auto* s = static_cast<UploadSource*>(user);
if (s->remaining == 0) return 0; // all body delivered → clean EOF
// Whole-request ceiling, checked on EVERY pull (not only while the socket is dry): a paced
// trickler that always keeps one byte ready makes each read return > 0 immediately, so a cap
// tested only in the wait loop would never fire. Enforcing it here makes it truly absolute.
if (static_cast<int32_t>(platform::millis() - s->hardDeadline) >= 0) { *abort = true; return 0; }
// Drain the already-buffered prefix first.
if (s->initialLeft) {
const size_t n = s->initialLeft < cap ? s->initialLeft : cap;
std::memcpy(out, s->initial, n);
s->initial += n; s->initialLeft -= n; s->remaining -= n;
return n;
}
// Then pull the rest off the socket, bounded by BOTH the per-pull idle deadline (recomputed
// here, only advances while we wait — bounds a stall) and the request-lifetime hardDeadline
// (set once at construction — bounds the total). If the body is still incomplete when the
// socket closes early or either deadline lapses, signal *abort — fsWriteStream then discards
// the temp file rather than committing a truncated upload (a 0 here is NOT a clean end). Both
// compares are subtraction-based, wraparound-safe across the ~49.7-day millis() rollover.
const size_t want = s->remaining < cap ? s->remaining : cap;
const uint32_t deadline = platform::millis() + kUploadIdleMs;
for (;;) {
const int r = s->conn->read(reinterpret_cast<uint8_t*>(out), want);
if (r > 0) { s->remaining -= static_cast<size_t>(r); return static_cast<size_t>(r); }
if (r == 0) { *abort = true; return 0; } // peer closed with body remaining
// Idle timeout (the hard whole-request cap is enforced at the top of uploadPull, so it
// covers the pacing case this wait loop can't). Both compares are wraparound-safe.
if (static_cast<int32_t>(platform::millis() - deadline) >= 0) { *abort = true; return 0; }
platform::delayMs(1);
}
}
} // namespace
void HttpServerModule::handleWriteFile(platform::TcpConnection& conn, const char* query,
const char* initialBody, size_t initialLen, size_t contentLen) {
char path[160];
if (!parseFilePath(query, path, sizeof(path))) {
sendResponse(conn, 400, "application/json", "{\"error\":\"bad path\"}");
return;
}
if (contentLen > kUploadMax) {
sendResponse(conn, 413, "application/json", "{\"error\":\"file too large\"}");
return;
}
// Reject up front if it wouldn't fit the free filesystem space (friendlier than filling the FS
// and failing mid-write — fsWriteStream also fails cleanly + discards the temp if it does fill).
// total − used = free. An overwrite would reclaim the old file's space, but treat free
// conservatively (don't credit the overwrite) so the check never over-promises.
const size_t total = platform::filesystemTotal();
const size_t used = platform::filesystemUsed();
const size_t freeBytes = total > used ? total - used : 0;
if (total > 0 && contentLen > freeBytes) {
char msg[96];
std::snprintf(msg, sizeof(msg), "{\"error\":\"not enough space (%lu free)\"}",
static_cast<unsigned long>(freeBytes));
sendResponse(conn, 507, "application/json", msg); // 507 Insufficient Storage
return;
}
// Never hand the source more than Content-Length of the already-buffered bytes: a buffer can hold
// bytes past the body (a pipelined next request), which must not be written into the file.
const size_t initial = initialLen < contentLen ? initialLen : contentLen;
UploadSource src{&conn, initialBody, initial, contentLen,
platform::millis() + kUploadHardMs};
if (platform::fsWriteStream(path, &uploadPull, &src)) {
sendResponse(conn, 200, "application/json", "{\"ok\":true}");
} else {
sendResponse(conn, 500, "application/json", "{\"error\":\"write failed\"}");
}
}
// OTA from an uploaded .bin body: stream the request body straight into the OTA partition
// (platform::otaWriteStream), reusing the exact uploadPull the file-upload path uses — the only
// difference is the sink (OTA partition vs a file). On success the device reboots into the new
// image; the 200 goes out first (otaWriteStream's ~600 ms pre-reboot delay covers the round-trip).
void HttpServerModule::handleFirmwareUpload(platform::TcpConnection& conn, const char* initialBody,
size_t initialLen, size_t contentLen) {
if constexpr (!platform::hasOta) {
sendResponse(conn, 501, "application/json", "{\"error\":\"OTA not supported on this platform\"}");
return;
}
// Same 409 concurrency guard as handleFirmwareUrl: one OTA at a time (both write g_ota* state).
if (otaInFlight()) {
sendResponse(conn, 409, "application/json", "{\"error\":\"ota already in progress\"}");
return;
}
const size_t initial = initialLen < contentLen ? initialLen : contentLen;
UploadSource src{&conn, initialBody, initial, contentLen, platform::millis() + kUploadHardMs};
g_otaBytesTotal = static_cast<uint32_t>(contentLen); // the UI's "Y KB" (Content-Length up front)
g_otaBytesRead = 0; // clear any stale count from a prior OTA
// Stream the body into the OTA partition. otaWriteStream commits the image + flips the boot
// pointer but does NOT reboot — it returns so we can send a 200 first, then reboot the same
// way /api/reboot does (response, close, brief drain, platform::reboot). That gives the browser
// a clean "flashed" response instead of an aborted socket it can't tell from a real failure.
const bool ok = platform::otaWriteStream(&uploadPull, &src, contentLen,
g_otaStatus, sizeof(g_otaStatus), &g_otaBytesRead);
if (!ok) {
char msg[96];
std::snprintf(msg, sizeof(msg), "{\"error\":\"ota failed: %.60s\"}", g_otaStatus);
sendResponse(conn, 500, "application/json", msg);
return;
}
FilesystemModule::flushPending();
sendResponse(conn, 200, "application/json", "{\"ok\":true}");
conn.close();
platform::delayMs(200);
platform::reboot(); // noreturn — boots the flashed image
}
void HttpServerModule::serveFile(platform::TcpConnection& conn, const char* filename, const char* contentType) {
// Try disk first (desktop development — live editing without rebuild)
char filepath[256];
std::snprintf(filepath, sizeof(filepath), "%s/%s", uiPath_, filename);
FILE* f = std::fopen(filepath, "rb");
if (f) {
std::fseek(f, 0, SEEK_END);
long size = std::ftell(f);
std::fseek(f, 0, SEEK_SET);
char header[256];
int headerLen = std::snprintf(header, sizeof(header),
"HTTP/1.1 200 OK\r\n"
"Content-Type: %s\r\n"
"Content-Length: %ld\r\n"
"Connection: close\r\n"
"Cache-Control: no-cache\r\n"
"\r\n",
contentType, size);
conn.write(reinterpret_cast<const uint8_t*>(header), headerLen);
uint8_t chunk[1024];
while (size > 0) {
size_t toRead = size > static_cast<long>(sizeof(chunk)) ? sizeof(chunk) : static_cast<size_t>(size);
size_t bytesRead = std::fread(chunk, 1, toRead, f);
if (bytesRead == 0) break;
conn.write(chunk, bytesRead);
size -= static_cast<long>(bytesRead);
}
std::fclose(f);
return;
}
// Fall back to embedded data (ESP32 or when disk files not found). The text
// assets are embedded gzipped (see embed_ui.cmake) and served with
// Content-Encoding: gzip — the browser inflates them. gzipped is false only
// for already-compressed binaries (the PNG), which are embedded raw.
const uint8_t* data = nullptr;
size_t dataLen = 0;
bool gzipped = false;
if (std::strcmp(filename, "index.html") == 0) { data = ui::indexHtml; dataLen = ui::indexHtmlLen; gzipped = true; }
else if (std::strcmp(filename, "app.js") == 0) { data = ui::appJs; dataLen = ui::appJsLen; gzipped = true; }
else if (std::strcmp(filename, "install-picker.js") == 0) { data = ui::installPickerJs; dataLen = ui::installPickerJsLen; gzipped = true; }
else if (std::strcmp(filename, "semver.js") == 0) { data = ui::semverJs; dataLen = ui::semverJsLen; gzipped = true; }
else if (std::strcmp(filename, "preview3d.js") == 0) { data = ui::preview3dJs; dataLen = ui::preview3dJsLen; gzipped = true; }
else if (std::strcmp(filename, "style.css") == 0) { data = ui::styleCss; dataLen = ui::styleCssLen; gzipped = true; }
else if (std::strcmp(filename, "moonlight-logo.png") == 0) { data = ui::logoPng; dataLen = ui::logoPngLen; }
if (!data) {
sendResponse(conn, 404, "text/plain", "File not found");
return;
}
char header[256];
int headerLen = std::snprintf(header, sizeof(header),
"HTTP/1.1 200 OK\r\n"
"Content-Type: %s\r\n"
"Content-Length: %zu\r\n"
"%s"
"Connection: close\r\n"
"Cache-Control: no-cache\r\n"
"\r\n",
contentType, dataLen,
gzipped ? "Content-Encoding: gzip\r\n" : "");
conn.write(reinterpret_cast<const uint8_t*>(header), headerLen);
conn.write(data, dataLen);
}
void HttpServerModule::serveState(platform::TcpConnection& conn) {
const char* header =
"HTTP/1.1 200 OK\r\n"
"Content-Type: application/json\r\n"
"Connection: close\r\n"
"Access-Control-Allow-Origin: *\r\n"
"\r\n";
conn.write(reinterpret_cast<const uint8_t*>(header), std::strlen(header));
JsonSink sink(conn);
buildStateJson(sink);
sink.flush();
}
void HttpServerModule::buildStateJson(JsonSink& sink) {
sink.append("{\"modules\":[");
if (scheduler_) {
bool first = true;
for (uint8_t m = 0; m < scheduler_->moduleCount(); m++) {
auto* mod = scheduler_->module(m);
// Skip modules that opt out of the UI via appearsInUi() — the one mechanism for
// "not a card in /api/state": HttpServerModule (the server itself) and FilesystemModule
// (a pure persistence engine, no controls) both return false.
if (!mod || !mod->appearsInUi()) continue;
if (!first) sink.append(",");
first = false;
writeModuleJson(sink, mod);
}
}
sink.append("]}");
}
void HttpServerModule::writeModuleJson(JsonSink& sink, MoonModule* mod) {
// Per-module header: name, role, enabled, loopTimeUs (fps/ms display),
// classSize (static C++ object bytes) + dynamicBytes (heap), controls
const char* roleStr = roleName(mod->role());
const char* type = mod->typeName();
if (!type) type = "";
sink.appendf(
"{\"name\":\"%s\",\"type\":\"%s\",\"role\":\"%s\",\"enabled\":%s,"
"\"loopTimeUs\":%u,\"classSize\":%u,\"dynamicBytes\":%u",
mod->name() ? mod->name() : "",
type,
roleStr,
mod->enabled() ? "true" : "false",
static_cast<unsigned>(mod->loopTimeUs()),
static_cast<unsigned>(mod->classSize()),
static_cast<unsigned>(mod->dynamicBytes()));
writeStatus(sink, mod);
// userEditable: omit when true (the common case) to save bytes — the UI
// treats absent as editable, same convention as the control hidden/readonly
// flags. Emitted only for modules that opt out (e.g. PreviewDriver), so the
// UI hides their delete/replace affordance.
if (!mod->userEditable()) sink.append(",\"userEditable\":false");
sink.append(",\"controls\":[");
writeControls(sink, mod);
sink.append("]");
// Children
uint8_t cc = mod->childCount();
if (cc > 0) {
sink.append(",\"children\":[");
for (uint8_t i = 0; i < cc; i++) {
if (i > 0) sink.append(",");
writeModuleJson(sink, mod->child(i));
}
sink.append("]");
}
sink.append("}");
}
void HttpServerModule::writeStatus(JsonSink& sink, MoonModule* mod) {
// Only emit when the module has a status — keeps the common case lean.
// Severity strings are stable wire format: "status", "warning", "error"
// (matches the C++ enum names lowercased; documented in HttpServerModule.md).
const char* s = mod->status();
if (!s) return;
static const char* sevStr[] = {"status", "warning", "error"};
sink.appendf(",\"status\":\"%s\",\"severity\":\"%s\"",
s, sevStr[static_cast<int>(mod->severity())]);
}
void HttpServerModule::writeControls(JsonSink& sink, MoonModule* mod) {
auto& ctrls = mod->controls();
for (uint8_t i = 0; i < ctrls.count(); i++) {
if (i > 0) sink.append(",");
auto& c = ctrls[i];
// Common wrapper for every control: {"name":...,"type":...,"value":VALUE,EXTRAS,"hidden":?}
// Per-type VALUE + EXTRAS rendering lives in Control.cpp so the
// wire format isn't duplicated across HttpServer/FS/scenario.
// Password is the one exception — its API serialization XOR-obfuscates +
// base64-encodes (writeControlValue emits plaintext, which is what
// FilesystemModule's writeValue wants); handle it here in-line so
// writeControlValue stays sink-neutral.
sink.appendf("{\"name\":\"%s\",\"type\":\"%s\",\"value\":",
c.name, controlTypeName(c.type));
if (c.type == ControlType::Password) {
// The password is sent XOR-obfuscated + base64-encoded, NOT
// in plaintext. This is deliberate obfuscation, not security:
// the XOR key is a fixed shared constant (also in app.js), so
// anyone can reverse it. It is a first line of defence — the
// value is not readable at a glance in `curl /api/state` — and
// it lets the UI's hold-to-peek reveal the stored password.
const char* pw = static_cast<char*>(c.ptr);
uint8_t scrambled[64];
size_t pwLen = std::strlen(pw);
if (pwLen > sizeof(scrambled)) pwLen = sizeof(scrambled);
for (size_t k = 0; k < pwLen; k++) {
scrambled[k] = static_cast<uint8_t>(pw[k]) ^ PASSWORD_XOR_KEY;
}
char encoded[96];
base64Encode(std::span(scrambled).first(pwLen), std::span(encoded));
sink.appendf("\"%s\"", encoded);
} else {
writeControlValue(sink, c);
}
writeControlMetadata(sink, c);
// Emit optional flags only when set (common case is false; omit to save bytes).
if (c.readonly) sink.append(",\"readonly\":true");
sink.append(c.hidden ? ",\"hidden\":true}" : "}");
}
}
// Apply-core: set one control's value. `valueJson` is a small JSON object holding
// the value under the "value" key ({"value":8}) — the same body the HTTP handler
// receives, so applyControlValue (which reads by key) is reused verbatim. Transport-
// free: no TcpConnection, returns an OpResult the caller maps to its own reporting.
HttpServerModule::OpResult HttpServerModule::applySetControl(
const char* moduleName, const char* controlName, const char* valueJson) {
// The generic control-set is a Scheduler primitive (it owns the tree + persistence hook),
// shared with every other control writer — Improv, the WLED bridge, IrModule. This wrapper
// only maps its result onto the HTTP OpResult so the response carries the right status code.
if (!scheduler_) return OpResult::ModuleNotFound;
switch (scheduler_->setControl(moduleName, controlName, valueJson)) {
case Scheduler::SetControlResult::Ok: return OpResult::Ok;
case Scheduler::SetControlResult::ModuleNotFound: return OpResult::ModuleNotFound;
case Scheduler::SetControlResult::ControlNotFound: return OpResult::ControlNotFound;
case Scheduler::SetControlResult::OutOfRange: return OpResult::OutOfRange;
case Scheduler::SetControlResult::Malformed: return OpResult::Malformed;
case Scheduler::SetControlResult::ReadOnly: return OpResult::ReadOnly;
}
return OpResult::ModuleNotFound; // unreachable; keeps -Wreturn-type happy
}
void HttpServerModule::handleSetControl(platform::TcpConnection& conn, const char* body) {
// Parse: {"module":"Noise","control":"scale","value":8} — the apply-core reads
// the value out of `body` itself (so it sees the exact same JSON the API got).
char moduleName[32] = {};
char controlName[32] = {};
mm::json::parseString(body, "module", moduleName, sizeof(moduleName));
mm::json::parseString(body, "control", controlName, sizeof(controlName));
switch (applySetControl(moduleName, controlName, body)) {
case OpResult::Ok:
sendResponse(conn, 200, "application/json", "{\"ok\":true}");
return;
case OpResult::ModuleNotFound:
sendResponse(conn, 404, "application/json", "{\"error\":\"module not found\"}");
return;
case OpResult::ControlNotFound:
sendResponse(conn, 404, "application/json", "{\"error\":\"control not found\"}");
return;
case OpResult::OutOfRange:
sendResponse(conn, 400, "application/json", "{\"error\":\"value out of range\"}");
return;
case OpResult::Malformed:
sendResponse(conn, 400, "application/json", "{\"error\":\"value malformed\"}");
return;
case OpResult::ReadOnly:
sendResponse(conn, 400, "application/json", "{\"error\":\"control is read-only\"}");
return;
default:
sendResponse(conn, 400, "application/json", "{\"error\":\"bad request\"}");
return;
}
}
// The Scheduler owns the module tree, so the tree-walk-by-name lives there (firstByName);
// this only adds the scheduler_ null-guard the request handlers rely on (scheduler_ is unset
// until setScheduler() runs), then delegates — one recursive lookup, not two.
MoonModule* HttpServerModule::findModuleByName(const char* name) {
return scheduler_ ? scheduler_->firstByName(name) : nullptr;
}
void HttpServerModule::serveSystem(platform::TcpConnection& conn) {
const char* header =
"HTTP/1.1 200 OK\r\n"
"Content-Type: application/json\r\n"
"Connection: close\r\n"
"Access-Control-Allow-Origin: *\r\n"
"\r\n";
conn.write(reinterpret_cast<const uint8_t*>(header), std::strlen(header));
JsonSink sink(conn);
// maxBlock = internal-only (maxInternalAllocBlock) — the all-memory
// variant reports ~8 MB on PSRAM boards and is meaningless as a
// pressure signal. Same rationale as main.cpp's tick log line.
sink.appendf(
"{\"fps\":%u,\"tickTimeUs\":%u,\"freeHeap\":%u,\"freeInternal\":%u,\"maxBlock\":%u,\"uptime\":%u,\"modules\":[",
static_cast<unsigned>(scheduler_ ? scheduler_->fps() : 0),
static_cast<unsigned>(scheduler_ ? scheduler_->tickTimeUs() : 0),
static_cast<unsigned>(platform::freeHeap()),
static_cast<unsigned>(platform::freeInternalHeap()),
static_cast<unsigned>(platform::maxInternalAllocBlock()),
static_cast<unsigned>(scheduler_ ? scheduler_->elapsed() / 1000 : 0));
// Per-module timing (walk tree recursively)
if (scheduler_) {
bool first = true;
for (uint8_t i = 0; i < scheduler_->moduleCount(); i++) {
writeModuleMetricsJson(sink, scheduler_->module(i), first);
}
}
sink.append("]}");
sink.flush();
}
// WLED-compatibility `/json/info` — the subset of WLED's info object the native WLED
// apps + Home Assistant validate when they probe a device they discovered via
// `_wled._tcp`. The clients gate on a WLED-shaped identity: `brand:"WLED"`, a real
// `vid` (build id; they reject 0), a WLED-major `ver`, and `leds.count`. We declare
// `brand:"WLED"` because the apps key on it — the same thing WLED-MM (the MoonModules
// WLED fork) does — while `product:"MoonModules"` says what this actually is. We speak
// WLED's info shape to interoperate, not to impersonate. Built fresh against WLED's
// public JSON, not copied. (Reference real WLED carries far more; this is the trimmed,
// known-sufficient field set — see docs/moonmodules/core/moxygen/HttpServerModule.md.)
void HttpServerModule::serveWledInfo(platform::TcpConnection& conn) {
const char* header =
"HTTP/1.1 200 OK\r\n"
"Content-Type: application/json\r\n"
"Connection: close\r\n"
"Access-Control-Allow-Origin: *\r\n"
"\r\n";
conn.write(reinterpret_cast<const uint8_t*>(header), std::strlen(header));
// Identity: the deviceName (from SystemModule), the live IP, the MAC.
const char* name = "projectMM";
if (MoonModule* sys = findModuleByName("System")) {
const char* dn = static_cast<SystemModule*>(sys)->deviceName();
if (dn && dn[0]) name = dn;
}
uint8_t ip[4] = {};
platform::ethGetIPv4(ip);
if (!ip[0] && !ip[1] && !ip[2] && !ip[3]) platform::wifiStaGetIPv4(ip);
uint8_t mac[6] = {};
platform::getMacAddress(mac);
// Field set reverse-engineered from the WLED-Android app's `Info` Moshi model
// (model/wledapi/Info.kt): the ONLY non-nullable fields it requires are `name`, `leds`
// (object), and `wifi` (object) — a missing one fails the JSON parse and the device is
// silently dropped. `DeviceFirstContactService.kt` additionally rejects a device whose
// body `mac` is empty. Every other field in the model is nullable. So this is the
// minimal object the native app accepts: name + leds{} + wifi{} + a non-empty mac. The
// inner Leds/Wifi fields are themselves all nullable, so empty `{}` objects parse — we
// send a real `mac` and otherwise the smallest shapes that satisfy the parser. `brand`/
// `product` identify us as the MoonModules WLED-compatible product (interoperate, not
// impersonate). Confirmed on the bench: projectMM devices list in the WLED native app.
JsonSink sink(conn);
writeWledInfoBody(sink, name, mac);
sink.flush();
}
// The WLED info object, written into an open sink (no HTTP header). Shared by