Repository navigation
Expand file tree
/
Copy pathFileManager.cpp
More file actions
1562 lines (1422 loc) · 63.3 KB
/
Copy pathFileManager.cpp
File metadata and controls
1562 lines (1422 loc) · 63.3 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
// FileManager.cpp
// Full file (original + diagnosticListAll + rmdir & raw-entry fallbacks + remount fallback)
#include "FileManager.hpp"
#include "WebServerManager.hpp" // for extern WebServer* server and LittleFS availability
#include <LittleFS.h>
#include <ArduinoJson.h>
#include <WebServer.h>
#include <FS.h>
#include "PsramUtils.hpp" // Include for PsramVector instead of std::vector
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include "MultiLogger.hpp"
// Helper: sanitize and normalize an incoming path parameter.
// Ensures:
// - path starts with '/'
// - no '/../' sequences
// - no duplicate slashes
static String sanitizePathParam(const String& raw) {
if (raw.length() == 0) return "/";
String p = raw;
if (p.charAt(0) != '/') p = "/" + p;
// Remove any ../ sequences
while (p.indexOf("..") != -1) p.replace("..", "");
// Normalize duplicate slashes
while (p.indexOf("//") != -1) p.replace("//", "/");
// Trim trailing spaces and control chars
while (p.endsWith(" ") || p.endsWith("\n") || p.endsWith("\r")) p.remove(p.length()-1);
if (p.length() == 0) return "/";
return p;
}
// Helper: compute parent path, e.g. "/a/b/c" -> "/a/b", "/a" -> "/", "/" -> "/"
static String parentPath(const String& path) {
if (path == "/" || path.length() == 0) return "/";
String p = path;
if (p.endsWith("/") && p.length() > 1) p.remove(p.length()-1);
int idx = p.lastIndexOf('/');
if (idx <= 0) return "/";
return p.substring(0, idx);
}
// Guess common content types
static const char* guessContentType(const String& path) {
String p = path;
p.toLowerCase();
if (p.endsWith(".htm") || p.endsWith(".html")) return "text/html";
if (p.endsWith(".css")) return "text/css";
if (p.endsWith(".js")) return "application/javascript";
if (p.endsWith(".png")) return "image/png";
if (p.endsWith(".jpg") || p.endsWith(".jpeg")) return "image/jpeg";
if (p.endsWith(".gif")) return "image/gif";
if (p.endsWith(".svg")) return "image/svg+xml";
if (p.endsWith(".json")) return "application/json";
if (p.endsWith(".txt")) return "text/plain";
return "application/octet-stream";
}
// Format size into user-friendly string
static String humanReadableSize(uint64_t bytes) {
char buf[32];
if (bytes < 1024) {
snprintf(buf, sizeof(buf), "%llu B", (unsigned long long)bytes);
} else if (bytes < 1024ULL * 1024ULL) {
double kb = bytes / 1024.0;
snprintf(buf, sizeof(buf), "%.1f KB", kb);
} else if (bytes < 1024ULL * 1024ULL * 1024ULL) {
double mb = bytes / (1024.0 * 1024.0);
snprintf(buf, sizeof(buf), "%.2f MB", mb);
} else {
double gb = bytes / (1024.0 * 1024.0 * 1024.0);
snprintf(buf, sizeof(buf), "%.2f GB", gb);
}
return String(buf);
}
// Ensure parent directories exist for a given full file path (creates recursively)
static void ensureParentDirs(const String& fullpath) {
int lastSlash = fullpath.lastIndexOf('/');
if (lastSlash <= 0) return; // root or no parent
String dir = fullpath.substring(0, lastSlash);
if (dir.length() == 0 || dir == "/") return;
if (!dir.startsWith("/")) dir = "/" + dir;
String accum = "";
int pos = 1; // skip initial '/'
while (pos <= dir.length()) {
int next = dir.indexOf('/', pos);
String token;
if (next == -1) {
token = dir.substring(pos);
pos = dir.length() + 1;
} else {
token = dir.substring(pos, next);
pos = next + 1;
}
if (token.length() == 0) continue;
accum += "/" + token;
if (!LittleFS.exists(accum)) {
LittleFS.mkdir(accum);
}
}
}
// Recursively copy a file from srcPath to dstPath. Returns true on success.
static bool copyFile(const String& srcPath, const String& dstPath) {
File src = LittleFS.open(srcPath, "r");
if (!src) return false;
File dst = LittleFS.open(dstPath, "w");
if (!dst) { src.close(); return false; }
uint8_t buf[1024];
while (src.available()) {
size_t r = src.readBytes((char*)buf, sizeof(buf));
dst.write(buf, r);
}
dst.close();
src.close();
return true;
}
// --------- URL-decode and parsing helpers for fallback parsing ----------
static String urlDecode(const String& in) {
String out;
out.reserve(in.length());
for (size_t i = 0; i < in.length(); ++i) {
char c = in[i];
if (c == '+') {
out += ' ';
} else if (c == '%' && i + 2 < in.length()) {
auto hexVal = [](char h) -> int {
if (h >= '0' && h <= '9') return h - '0';
if (h >= 'A' && h <= 'F') return 10 + (h - 'A');
if (h >= 'a' && h <= 'f') return 10 + (h - 'a');
return 0;
};
char hi = in[i+1];
char lo = in[i+2];
char decoded = (char)((hexVal(hi) << 4) | hexVal(lo));
out += decoded;
i += 2;
} else {
out += c;
}
}
return out;
}
// parse urlencoded body like "src=/a/b&dest=foo.pem&cwd=/a"
static void parseUrlEncodedBody(const String& body, String& srcOut, String& destOut, String& cwdOut) {
size_t pos = 0;
while (pos < body.length()) {
size_t amp = body.indexOf('&', pos);
String pair = (amp == -1) ? body.substring(pos) : body.substring(pos, amp);
int eq = pair.indexOf('=');
if (eq != -1) {
String name = pair.substring(0, eq);
String val = pair.substring(eq + 1);
name = urlDecode(name);
val = urlDecode(val);
if (name == "src") srcOut = val;
else if (name == "dest") destOut = val;
else if (name == "cwd") cwdOut = val;
}
if (amp == -1) break;
pos = amp + 1;
}
}
// Iterative move directory implementation with logging and defensive handling
static bool moveDirectoryRecursive(const String& srcDir, const String& dstDir) {
// Normalize
String ssrc = sanitizePathParam(srcDir);
String sdst = sanitizePathParam(dstDir);
if (!ssrc.endsWith("/")) ssrc += "/";
if (!sdst.endsWith("/")) sdst += "/";
Log.printf("[WebFS] moveDirectoryRecursive START: '%s' -> '%s'\n", ssrc.c_str(), sdst.c_str());
// Ensure destination directory exists (create parents)
ensureParentDirs(sdst + "dummy");
if (!LittleFS.exists(sdst)) {
if (!LittleFS.mkdir(sdst)) {
Log.printf("[WebFS] moveDirectoryRecursive: failed to create dest dir %s\n", sdst.c_str());
return false;
}
}
struct Pair { String src; String dst; };
PsramVector<Pair> stack;
stack.push_back({ssrc, sdst});
while (!stack.empty()) {
Pair p = stack.back();
stack.pop_back();
String curSrc = p.src;
String curDst = p.dst;
Log.printf("[WebFS] moving dir: '%s' -> '%s'\n", curSrc.c_str(), curDst.c_str());
File dir = LittleFS.open(curSrc);
if (!dir) {
Log.printf("[WebFS] moveDirectoryRecursive: cannot open src dir %s\n", curSrc.c_str());
return false;
}
File file = dir.openNextFile();
while (file) {
String child = file.name();
bool isDir = file.isDirectory();
// Normalize child to absolute path
String absChild;
if (child.startsWith("/")) absChild = child;
else {
if (curSrc == "/") absChild = String("/") + child;
else absChild = curSrc + child;
}
if (isDir) {
String rel = absChild;
if (rel.startsWith(curSrc)) rel = rel.substring(curSrc.length());
if (rel.startsWith("/")) rel = rel.substring(1);
String dstSub = curDst;
if (!dstSub.endsWith("/")) dstSub += "/";
dstSub += rel;
Log.printf("[WebFS] found dir: '%s' -> create '%s'\n", absChild.c_str(), dstSub.c_str());
ensureParentDirs(dstSub + "dummy");
if (!LittleFS.exists(dstSub)) {
if (!LittleFS.mkdir(dstSub)) {
Log.printf("[WebFS] failed to create dst subdir %s\n", dstSub.c_str());
file.close();
dir.close();
return false;
}
}
file.close();
stack.push_back({absChild, dstSub});
} else {
String rel = absChild;
if (rel.startsWith(curSrc)) rel = rel.substring(curSrc.length());
if (rel.startsWith("/")) rel = rel.substring(1);
String dstPath = curDst;
if (!dstPath.endsWith("/")) dstPath += "/";
dstPath += rel;
Log.printf("[WebFS] copy file: '%s' -> '%s'\n", absChild.c_str(), dstPath.c_str());
file.close();
ensureParentDirs(dstPath);
bool ok = copyFile(absChild, dstPath);
if (!ok) {
Log.printf("[WebFS] failed to copy %s -> %s\n", absChild.c_str(), dstPath.c_str());
dir.close();
return false;
}
if (!LittleFS.remove(absChild)) {
Log.printf("[WebFS] WARNING: failed to remove source file %s (continuing)\n", absChild.c_str());
} else {
Log.printf("[WebFS] removed source file %s\n", absChild.c_str());
}
}
file = dir.openNextFile();
}
dir.close();
if (!LittleFS.remove(curSrc)) {
Log.printf("[WebFS] could not remove source dir %s (may not be empty)\n", curSrc.c_str());
} else {
Log.printf("[WebFS] removed source dir %s\n", curSrc.c_str());
}
}
Log.printf("[WebFS] moveDirectoryRecursive DONE: '%s' -> '%s'\n", ssrc.c_str(), sdst.c_str());
return true;
}
// Recursively list all entries under LittleFS root (diagnostic)
static void diagnosticListAll() {
Log.println("[WebFS DIAG] Listing all filesystem entries (recursive):");
File root = LittleFS.open("/");
if (!root) {
Log.println("[WebFS DIAG] Failed to open root");
return;
}
PsramVector<String> stack;
stack.push_back("/");
while (!stack.empty()) {
String cur = stack.back();
stack.pop_back();
File dir = LittleFS.open(cur);
if (!dir) {
Log.printf("[WebFS DIAG] Cannot open dir '%s'\n", cur.c_str());
continue;
}
File f = dir.openNextFile();
while (f) {
String name = f.name();
bool isDir = f.isDirectory();
String full;
if (name.startsWith("/")) full = name;
else {
if (cur == "/") full = "/" + name;
else {
full = cur;
if (!full.endsWith("/")) full += "/";
full += name;
}
}
Log.printf("[WebFS DIAG] %s %s\n", isDir ? "DIR " : "FILE", full.c_str());
if (isDir) stack.push_back(full);
f.close();
f = dir.openNextFile();
}
dir.close();
}
}
// Serve a tiny file manager HTML page on GET /fs
static void handleFsUi() {
String html;
html.reserve(11000);
html += R"rawliteral(<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale:1"/>
<title>Panelclock - File Manager</title>
<style>
body{font-family:Arial,Helvetica,sans-serif;margin:12px;color:#eee;background:#111}
h1{font-size:18px;margin-bottom:8px}
.fsinfo{font-size:13px;color:#ccc;margin-bottom:8px;}
.table{width:100%;border-collapse:collapse;margin-bottom:8px}
.table th,.table td{padding:6px 8px;border-bottom:1px solid #333;text-align:left}
.btn{display:inline-block;padding:6px 10px;background:#2b7;color:#051;border-radius:4px;text-decoration:none;margin-right:6px}
.btn-danger{background:#d44;color:#fff}
.small{font-size:12px;color:#ccc}
.input{padding:6px;border:1px solid #333;background:#111;color:#eee;border-radius:4px}
.entry-file { color: #ffffff; } /* files: white */
.entry-dir { color: #ffd600; } /* directories: yellow */
.path-breadcrumb { color:#ccc; font-size:13px; margin-bottom:8px; display:block; }
.controls { margin:8px 0 12px 0; }
.create-input { width:220px; margin-left:8px; }
</style>
</head>
<body>
<h1>Dateimanager (LittleFS)</h1>
<div class="fsinfo" id="fs_info">Lade Speicherinfo...</div>
<span id="cwd" class="path-breadcrumb">/</span>
<div class="controls">
<a href="/" class="btn" style="background:#555">← Zurück zum Hauptmenü</a>
<button id="refresh" class="btn">Refresh</button>
<button id="downloadAll" class="btn" style="background:#2196F3">Download All (Current Dir)</button>
<form id="uploadForm" style="display:inline-block;margin-left:8px">
<input id="fileInput" class="input" type="file" name="file" />
<input id="destInput" class="input" type="text" placeholder="/path/optional-name" style="width:260px;margin-left:6px"/>
<label class="small" style="margin-left:6px"><input id="overwrite" type="checkbox"/> overwrite</label>
<button type="submit" class="btn">Upload</button>
</form>
<!-- create dir -->
<input id="newDirName" class="input create-input" type="text" placeholder="Neues Verzeichnisname" />
<button id="mkdirBtn" class="btn" style="background:#ffb400;color:#000;margin-left:6px;">Verzeichnis erstellen</button>
</div>
<div id="msg" class="small"></div>
<table class="table" id="listing">
<thead><tr><th>Name</th><th>Size</th><th>Modified</th><th>Actions</th></tr></thead>
<tbody></tbody>
</table>
<script>
window.currentFsPath = '/';
async function refreshInfo() {
try {
const rsp = await fetch('/fs/info');
if (!rsp.ok) { document.getElementById('fs_info').innerText = 'Speicherinfo: Fehler'; return; }
const info = await rsp.json();
document.getElementById('fs_info').innerText = `Speicher: ${info.used_readable} belegt / ${info.total_readable} gesamt (frei: ${info.free_readable})`;
} catch (e) {
document.getElementById('fs_info').innerText = 'Speicherinfo: Fehler';
}
}
async function list(path='/') {
window.currentFsPath = path;
document.getElementById('cwd').innerText = 'Pfad: ' + path;
refreshInfo();
const rsp = await fetch('/fs/list?path=' + encodeURIComponent(path));
if (!rsp.ok) { document.getElementById('msg').innerText = 'List failed: ' + rsp.status; return; }
const j = await rsp.json();
const tbody = document.querySelector('#listing tbody');
tbody.innerHTML = '';
if (!j.entries) return;
if (j.path && j.path !== '/') {
const parent = (function(p){ if (p.endsWith('/') && p.length>1) p = p.slice(0,-1); var idx = p.lastIndexOf('/'); if (idx<=0) return '/'; return p.substring(0, idx); })(j.path);
const tr = document.createElement('tr');
const nameTd = document.createElement('td');
const link = document.createElement('a');
link.href = '#';
link.innerText = '..';
link.className = 'entry-dir';
link.onclick = ()=>{ list(parent); return false; };
nameTd.appendChild(link);
tr.appendChild(nameTd);
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
const actionsTd = document.createElement('td');
const upBtn = document.createElement('a');
upBtn.href = '#';
upBtn.className = 'btn';
upBtn.innerText = 'Open';
upBtn.onclick = ()=>{ list(parent); return false; };
actionsTd.appendChild(upBtn);
tr.appendChild(actionsTd);
tbody.appendChild(tr);
}
j.entries.forEach(e => {
const tr = document.createElement('tr');
const name = document.createElement('td');
const link = document.createElement('a');
link.href = '#';
link.innerText = e.name;
link.className = e.isDir ? 'entry-dir' : 'entry-file';
link.onclick = ()=>{ if(e.isDir) list(e.path); else window.open('/fs/download?path=' + encodeURIComponent(e.path)); return false; };
name.appendChild(link);
tr.appendChild(name);
const size = document.createElement('td'); size.innerText = e.isDir ? '-' : (e.size_readable || e.size_bytes || '-'); tr.appendChild(size);
const mod = document.createElement('td'); mod.innerText = e.modified || ''; tr.appendChild(mod);
const actions = document.createElement('td');
if (!e.isDir) {
const dl = document.createElement('a'); dl.href='/fs/download?path=' + encodeURIComponent(e.path); dl.className='btn'; dl.innerText='Download'; actions.appendChild(dl);
const del = document.createElement('a'); del.href='#'; del.className='btn btn-danger'; del.innerText='Delete'; del.onclick = async ()=>{
if (!confirm('Delete ' + e.path + '?')) return false;
const r = await fetch('/fs/delete?path=' + encodeURIComponent(e.path), { method:'DELETE' });
if (r.ok) { list(window.currentFsPath); document.getElementById('msg').innerText = 'Deleted'; refreshInfo(); } else { const txt = await r.text(); document.getElementById('msg').innerText = 'Delete failed: ' + r.status + ' ' + txt; }
return false;
}; actions.appendChild(del);
const ren = document.createElement('a'); ren.href='#'; ren.className='btn'; ren.innerText='Rename/Move'; ren.onclick = async ()=>{
const current = e.path;
const base = current.substring(current.lastIndexOf('/')+1);
const input = prompt('Neuer Name oder Zielpfad (z.B. newname.txt oder /dir/newname.txt):', base);
if (input === null) return false;
const params = new URLSearchParams();
params.append('src', current);
params.append('dest', input);
params.append('cwd', window.currentFsPath);
const url = '/fs/rename?' + params.toString();
const r = await fetch(url); // GET by default
if (r.ok) { document.getElementById('msg').innerText = 'Renamed/Moved'; list(window.currentFsPath); refreshInfo(); return false; }
else {
const txt = await r.text();
alert('Fehler: ' + r.status + ' - ' + txt);
return false;
}
}; actions.appendChild(ren);
} else {
const open = document.createElement('a'); open.href='#'; open.className='btn'; open.innerText='Open'; open.onclick = ()=>{ list(e.path); return false; }; actions.appendChild(open);
const delDir = document.createElement('a'); delDir.href='#'; delDir.className='btn btn-danger'; delDir.innerText='Delete'; delDir.onclick = async ()=>{
if (!confirm('Delete directory ' + e.path + '? (only empty directories can be deleted)')) return false;
const r = await fetch('/fs/delete?path=' + encodeURIComponent(e.path), { method:'DELETE' });
if (r.ok) { list(window.currentFsPath); document.getElementById('msg').innerText = 'Directory deleted'; refreshInfo(); } else { const txt = await r.text(); alert('Fehler: ' + r.status + ' - ' + txt); }
return false;
}; actions.appendChild(delDir);
const renDir = document.createElement('a'); renDir.href='#'; renDir.className='btn'; renDir.innerText='Rename/Move'; renDir.onclick = async ()=>{
const current = e.path;
const base = current.substring(current.lastIndexOf('/')+1);
const input = prompt('Neuer Verzeichnisname oder Zielpfad (z.B. newdir oder /otherdir/newdir):', base);
if (input === null) return false;
const params = new URLSearchParams();
params.append('src', current);
params.append('dest', input);
params.append('cwd', window.currentFsPath);
const url = '/fs/rename?' + params.toString();
const r = await fetch(url); // GET
if (r.ok) { document.getElementById('msg').innerText = 'Renamed/Moved'; list(window.currentFsPath); refreshInfo(); return false; }
else {
const txt = await r.text();
alert('Fehler: ' + r.status + ' - ' + txt);
return false;
}
}; actions.appendChild(renDir);
}
tr.appendChild(actions);
tbody.appendChild(tr);
});
}
document.getElementById('refresh').onclick = ()=>list(window.currentFsPath);
// Download All button: creates a tar archive of the current directory
document.getElementById('downloadAll').onclick = async function() {
const currentPath = window.currentFsPath || '/';
document.getElementById('msg').innerText = 'Erstelle Archiv...';
const r = await fetch('/fs/downloadall?path=' + encodeURIComponent(currentPath));
if (r.ok) {
const blob = await r.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
// Extract directory name for filename
let dirName = currentPath === '/' ? 'root' : currentPath.substring(currentPath.lastIndexOf('/') + 1);
if (!dirName) dirName = 'root';
a.download = dirName + '.tar';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
document.getElementById('msg').innerText = 'Archiv heruntergeladen';
} else {
const txt = await r.text();
document.getElementById('msg').innerText = 'Download-Fehler: ' + r.status + ' - ' + txt;
}
};
// ---------- Upload form: send dest/cwd/overwrite in URL query so server->arg() sees them reliably ----------
document.getElementById('uploadForm').onsubmit = async function(ev){
ev.preventDefault();
const fileInput = document.getElementById('fileInput');
if (!fileInput.files.length) { document.getElementById('msg').innerText='No file selected'; return; }
const fd = new FormData();
fd.append('file', fileInput.files[0]);
const destInput = document.getElementById('destInput').value;
const cwd = window.currentFsPath || '/';
const overwrite = document.getElementById('overwrite').checked ? '1' : '0';
// Build query params so server receives dest/cwd/overwrite reliably (multipart fields are unreliable across server impls)
const params = new URLSearchParams();
if (destInput && destInput.length > 0) params.append('dest', destInput);
else params.append('dest', cwd);
params.append('cwd', cwd);
params.append('overwrite', overwrite);
document.getElementById('msg').innerText='Uploading...';
// send file as multipart body, but metadata in URL query
const resp = await fetch('/fs/upload?' + params.toString(), { method:'POST', body: fd });
if (resp.ok) {
document.getElementById('msg').innerText = 'Upload done';
list(window.currentFsPath);
refreshInfo();
} else {
document.getElementById('msg').innerText = 'Upload failed: ' + resp.status;
}
};
// ---------- Make mkdir use GET with query params so server->arg() reliably sees name/path ----------
document.getElementById('mkdirBtn').onclick = async function() {
const name = document.getElementById('newDirName').value.trim();
if (!name) { document.getElementById('msg').innerText = 'Bitte Verzeichnisnamen eingeben'; return; }
if (name.indexOf('/') !== -1 || name.indexOf('..') !== -1) { document.getElementById('msg').innerText = 'Ungültiger Name'; return; }
const params = new URLSearchParams();
params.append('path', window.currentFsPath);
params.append('name', name);
const url = '/fs/mkdir?' + params.toString();
const r = await fetch(url); // GET
if (r.ok) {
document.getElementById('msg').innerText = 'Verzeichnis erstellt';
document.getElementById('newDirName').value = '';
list(window.currentFsPath);
refreshInfo();
} else {
const txt = await r.text();
document.getElementById('msg').innerText = 'Fehler: ' + r.status + ' ' + txt;
}
};
list('/');
refreshInfo();
</script>
</body>
</html>)rawliteral";
server->send(200, "text/html", html);
}
// GET /fs/info -> returns storage info { total, used, free, total_readable, used_readable, free_readable }
static void handleFsInfo() {
// Use PSRAM allocator for JSON
struct SpiRamAllocator : ArduinoJson::Allocator {
void* allocate(size_t size) override { return ps_malloc(size); }
void deallocate(void* pointer) override { free(pointer); }
void* reallocate(void* ptr, size_t new_size) override { return ps_realloc(ptr, new_size); }
};
SpiRamAllocator allocator;
JsonDocument doc(&allocator);
uint64_t total = (uint64_t)LittleFS.totalBytes();
uint64_t used = (uint64_t)LittleFS.usedBytes();
uint64_t free = (total >= used) ? (total - used) : 0;
doc["total"] = total;
doc["used"] = used;
doc["free"] = free;
// humanReadableSize returns String, but we'll use it briefly
String total_str = humanReadableSize(total);
String used_str = humanReadableSize(used);
String free_str = humanReadableSize(free);
doc["total_readable"] = total_str;
doc["used_readable"] = used_str;
doc["free_readable"] = free_str;
String out;
serializeJson(doc, out);
server->send(200, "application/json", out);
}
// GET /fs/list?path=...
static void handleFsList() {
String raw = server->hasArg("path") ? server->arg("path") : "/";
String path = sanitizePathParam(raw);
// Use PSRAM allocator for large JSON document
struct SpiRamAllocator : ArduinoJson::Allocator {
void* allocate(size_t size) override { return ps_malloc(size); }
void deallocate(void* pointer) override { free(pointer); }
void* reallocate(void* ptr, size_t new_size) override { return ps_realloc(ptr, new_size); }
};
SpiRamAllocator allocator;
JsonDocument doc(&allocator);
doc["path"] = path;
JsonArray arr = doc.createNestedArray("entries");
File dir = LittleFS.open(path);
if (!dir) {
server->send(400, "application/json", "{\"error\":\"invalid_path\"}");
return;
}
File file = dir.openNextFile();
while (file) {
JsonObject e = arr.createNestedObject();
String rawName = file.name(); // may be "darts.pem" or "certs/darts.pem" or "/certs/darts.pem"
bool isdir = file.isDirectory();
// compute normalized fullPath
String fullPath;
if (rawName.startsWith("/")) {
fullPath = rawName;
} else if (rawName.indexOf('/') != -1) {
// contains a directory component, make absolute
fullPath = "/" + rawName;
} else {
// only a filename returned by openNextFile() - combine with requested directory 'path'
if (path == "/") fullPath = "/" + rawName;
else {
fullPath = path;
if (!fullPath.endsWith("/")) fullPath += "/";
fullPath += rawName;
}
}
// compute displayName as basename
String displayName = fullPath;
int idx = displayName.lastIndexOf('/');
if (idx != -1) displayName = displayName.substring(idx + 1);
if (displayName.startsWith("/")) displayName = displayName.substring(1);
e["name"] = displayName;
e["path"] = fullPath; // normalized absolute path (starts with '/')
e["isDir"] = isdir;
if (!isdir) {
uint64_t sz = (uint64_t)file.size();
e["size_bytes"] = sz;
String sz_str = humanReadableSize(sz);
e["size_readable"] = sz_str;
}
e["modified"] = 0;
file = dir.openNextFile();
}
String out;
serializeJson(doc, out);
server->send(200, "application/json", out);
}
// GET /fs/download?path=...
static void handleFsDownload() {
if (!server->hasArg("path")) {
server->send(400, "text/plain", "missing path");
return;
}
String raw = server->arg("path");
String path = sanitizePathParam(raw);
// Try normalized path first; if not found, try variants (without leading slash, with leading slash)
if (!LittleFS.exists(path)) {
String alt = path;
if (alt.startsWith("/")) alt = alt.substring(1);
if (LittleFS.exists(alt)) {
path = alt;
} else {
alt = path;
if (!alt.startsWith("/")) alt = "/" + alt;
if (LittleFS.exists(alt)) {
path = alt;
} else {
server->send(404, "text/plain", "not found");
return;
}
}
}
File f = LittleFS.open(path, "r");
if (!f) {
server->send(500, "text/plain", "open failed");
return;
}
String ct = guessContentType(path);
server->sendHeader("Content-Disposition", String("attachment; filename=\"") + path.substring(path.lastIndexOf('/')+1) + "\"");
server->streamFile(f, ct);
f.close();
}
// DELETE /fs/delete?path=...
static void handleFsDelete() {
if (!server) return;
if (!server->hasArg("path")) {
server->send(400, "application/json", "{\"error\":\"missing_path\"}");
return;
}
String raw = server->arg("path");
String path = sanitizePathParam(raw);
Log.printf("[WebFS] handleFsDelete requested path='%s'\n", path.c_str());
// Build candidate path variants to try (prefer normalized absolute path first) using PSRAM
PsramVector<String> variants;
// normalized absolute
if (!path.startsWith("/")) path = "/" + path;
// push canonical, canonical without leading slash, without trailing slash, with trailing slash
variants.push_back(path);
if (path.endsWith("/") && path.length() > 1) variants.push_back(path.substring(0, path.length()-1));
if (!path.endsWith("/")) variants.push_back(path + "/");
// without leading slash
String noLead = path;
if (noLead.startsWith("/")) noLead = noLead.substring(1);
variants.push_back(noLead);
// ensure uniqueness
for (size_t i = 0; i < variants.size(); ++i) {
for (size_t j = i + 1; j < variants.size();) {
if (variants[i] == variants[j]) variants.erase(variants.begin() + j);
else ++j;
}
}
// Try to find an existing variant
String found = "";
for (const auto &v : variants) {
if (LittleFS.exists(v)) {
found = v;
break;
}
}
if (found.length() == 0) {
Log.printf("[WebFS] handleFsDelete: path not found (checked variants)\n");
server->send(404, "application/json", "{\"error\":\"not_found\"}");
return;
}
Log.printf("[WebFS] handleFsDelete: using variant '%s'\n", found.c_str());
// Open and check if directory or file
File f = LittleFS.open(found);
if (f) {
if (f.isDirectory()) {
// Check if directory is empty: iterate openNextFile() and count children
int childCount = 0;
PsramVector<String> childNames;
File child = f.openNextFile();
while (child) {
++childCount;
childNames.push_back(String(child.name()));
child.close();
child = f.openNextFile();
}
f.close();
if (childCount > 0) {
Log.printf("[WebFS] delete directory failed (not empty): %s entries=%d\n", found.c_str(), childCount);
// include the first few child names in the response for debugging
String payload = "{\"error\":\"directory_not_empty\",\"entries\":[";
for (size_t i = 0; i < childNames.size(); ++i) {
payload += "\"" + childNames[i] + "\"";
if (i + 1 < childNames.size()) payload += ",";
}
payload += "]}";
server->send(409, "application/json", payload);
return;
}
// Directory seems empty — attempt removal, but try sensible variants as fallback
bool removed = false;
String triedList = "";
for (const auto &v : variants) {
triedList += "\"" + v + "\" ";
if (!LittleFS.exists(v)) continue;
Log.printf("[WebFS] attempt LittleFS.remove('%s')\n", v.c_str());
if (LittleFS.remove(v)) {
Log.printf("[WebFS] directory removed: %s\n", v.c_str());
removed = true;
break;
} else {
Log.printf("[WebFS] LittleFS.remove failed for '%s'\n", v.c_str());
// Try rmdir() on VFS as fallback (may succeed where LittleFS.remove fails)
errno = 0;
int rr = rmdir(v.c_str());
if (rr == 0) {
Log.printf("[WebFS] rmdir('%s') succeeded\n", v.c_str());
removed = true;
break;
} else {
Log.printf("[WebFS] rmdir('%s') failed: errno=%d (%s)\n", v.c_str(), errno, strerror(errno));
}
}
}
// Additional fallback: attempt removal using raw entry names returned by parent directory listing.
if (!removed) {
String base = found;
if (base.endsWith("/")) base = base.substring(0, base.length()-1);
int slash = base.lastIndexOf('/');
String baseName = (slash >= 0) ? base.substring(slash + 1) : base;
String parent = parentPath(found);
Log.printf("[WebFS] fallback: trying removal using parent listing - parent='%s' basename='%s'\n", parent.c_str(), baseName.c_str());
File pd = LittleFS.open(parent);
if (pd) {
File ef = pd.openNextFile();
while (ef) {
String entryName = ef.name(); // may be returned with or without leading slash
Log.printf("[WebFS] parent entry raw name: '%s'\n", entryName.c_str());
// Try removing the raw name as-is
if (LittleFS.exists(entryName)) {
Log.printf("[WebFS] attempt LittleFS.remove(raw='%s')\n", entryName.c_str());
if (LittleFS.remove(entryName)) {
Log.printf("[WebFS] removed via raw entry name '%s'\n", entryName.c_str());
removed = true;
ef.close();
break;
} else {
Log.printf("[WebFS] LittleFS.remove failed for raw name '%s'\n", entryName.c_str());
}
}
// Try removing with parent/entryName variants
String cand = entryName;
if (!cand.startsWith("/")) {
// try absolute form
String absCand = parent;
if (!absCand.endsWith("/")) absCand += "/";
absCand += cand;
Log.printf("[WebFS] attempt LittleFS.remove(abs='%s')\n", absCand.c_str());
if (LittleFS.exists(absCand) && LittleFS.remove(absCand)) {
Log.printf("[WebFS] removed via abs entry name '%s'\n", absCand.c_str());
removed = true;
ef.close();
break;
}
} else {
// entryName already absolute - try stripping leading slash
String stripped = cand.substring(1);
Log.printf("[WebFS] attempt LittleFS.remove(stripped='%s')\n", stripped.c_str());
if (LittleFS.exists(stripped) && LittleFS.remove(stripped)) {
Log.printf("[WebFS] removed via stripped entry name '%s'\n", stripped.c_str());
removed = true;
ef.close();
break;
}
}
// Try matching by basename
String candidateBasename = entryName;
int idx = candidateBasename.lastIndexOf('/');
if (idx != -1) candidateBasename = candidateBasename.substring(idx + 1);
if (candidateBasename == baseName) {
// try removing candidate forms
Log.printf("[WebFS] basename match - trying various removes for '%s'\n", candidateBasename.c_str());
if (LittleFS.exists(candidateBasename) && LittleFS.remove(candidateBasename)) { removed = true; ef.close(); break; }
String abs2 = parent;
if (!abs2.endsWith("/")) abs2 += "/";
abs2 += candidateBasename;
if (LittleFS.exists(abs2) && LittleFS.remove(abs2)) { removed = true; ef.close(); break; }
String abs3 = String("/") + candidateBasename;
if (LittleFS.exists(abs3) && LittleFS.remove(abs3)) { removed = true; ef.close(); break; }
}
ef.close();
ef = pd.openNextFile();
}
pd.close();
} else {
Log.printf("[WebFS] fallback: could not open parent '%s' for listing\n", parent.c_str());
}
// final attempt: try LittleFS.remove on basename variants directly
if (!removed) {
Log.printf("[WebFS] fallback final attempts on basename variants\n");
if (LittleFS.exists(baseName) && LittleFS.remove(baseName)) removed = true;
else {
String abs1 = parent;
if (!abs1.endsWith("/")) abs1 += "/";
abs1 += baseName;
if (LittleFS.exists(abs1) && LittleFS.remove(abs1)) removed = true;
else {
String abs2 = String("/") + baseName;
if (LittleFS.exists(abs2) && LittleFS.remove(abs2)) removed = true;
}
}
}
// If any of these removals succeeded, try rmdir as well (cleanup)
if (removed) {
Log.printf("[WebFS] fallback removal succeeded for '%s' (or equivalent)\n", found.c_str());
} else {
Log.printf("[WebFS] fallback removal attempts did not succeed for '%s'\n", found.c_str());
}
}
// REMOUNT FALLBACK:
// If we still didn't remove the directory, it is very likely another open FD holds some resource.
// Unmounting and remounting LittleFS will close internal file descriptors and can allow removal.
if (!removed) {
Log.println("[WebFS] remove failed - attempting LittleFS end()/begin() remount fallback");
// try to unmount and remount filesystem (may close stray FDs)
LittleFS.end();
delay(60);
bool began = LittleFS.begin();
Log.printf("[WebFS] LittleFS.begin() after end() -> %d\n", (int)began);
if (began) {
// try the variants again after remount
for (const auto &v : variants) {
if (!LittleFS.exists(v)) continue;
Log.printf("[WebFS] remount: attempt LittleFS.remove('%s')\n", v.c_str());
if (LittleFS.remove(v)) {
Log.printf("[WebFS] remount: directory removed: %s\n", v.c_str());
removed = true;
break;
} else {
Log.printf("[WebFS] remount: LittleFS.remove failed for '%s'\n", v.c_str());
}
}
} else {
Log.println("[WebFS] remount failed - cannot retry remove");
}
}
if (removed) {
server->send(200, "application/json", "{\"success\":true}");
return;
} else {
Log.printf("[WebFS] delete directory failed remove(): %s (tried: %s)\n", found.c_str(), triedList.c_str());
// Additional diagnostic: list full filesystem so we can see hidden/other entries
diagnosticListAll();
// return 500 with diagnostic info
String out = "{\"error\":\"remove_failed\",\"tried\": [";
for (size_t i = 0; i < variants.size(); ++i) {
out += "\"" + variants[i] + "\"";
if (i + 1 < variants.size()) out += ",";
}
out += "], \"note\": \"see serial logs for full FS listing\"}";
server->send(500, "application/json", out);
return;
}
} else {
// it's a file
f.close();
if (LittleFS.remove(found)) {
Log.printf("[WebFS] file removed: %s\n", found.c_str());
server->send(200, "application/json", "{\"success\":true}");
return;
} else {
Log.printf("[WebFS] file remove failed: %s\n", found.c_str());
server->send(500, "application/json", "{\"error\":\"remove_failed\"}");
return;
}
}
} else {
// Could not open (strange) — try remove anyway on variants
Log.printf("[WebFS] open() returned false for '%s' — trying remove on candidates\n", found.c_str());
bool removed = false;
for (const auto &v : variants) {
if (!LittleFS.exists(v)) continue;
Log.printf("[WebFS] attempt LittleFS.remove('%s')\n", v.c_str());
if (LittleFS.remove(v)) { removed = true; break; }
errno = 0;
int rr = rmdir(v.c_str());
if (rr == 0) { Log.printf("[WebFS] rmdir('%s') succeeded\n", v.c_str()); removed = true; break; }
else Log.printf("[WebFS] rmdir('%s') failed: errno=%d (%s)\n", v.c_str(), errno, strerror(errno));
}
if (!removed) {
Log.println("[WebFS] remove attempts failed — doing full diagnostic listing");
diagnosticListAll();
// Try remount fallback as last resort