Repository navigation
Expand file tree
/
Copy pathWebDAVHandler.cpp
More file actions
835 lines (706 loc) · 24.3 KB
/
Copy pathWebDAVHandler.cpp
File metadata and controls
835 lines (706 loc) · 24.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
#include "WebDAVHandler.h"
#include <FsHelpers.h>
#include <HalStorage.h>
#include <Logging.h>
#include "ClippingStore.h"
#include "util/BookCacheUtils.h"
#include "util/TaskWatchdog.h"
namespace {
constexpr const char* HIDDEN_ITEMS[] = {"System Volume Information", "XTCache"};
// RFC 1123 date format helper: "Sun, 06 Nov 1994 08:49:37 GMT"
// ESP32 doesn't have real-time clock set by default, so we use a fixed epoch date
// as a fallback. The date is not critical for WebDAV Class 1 operations.
const char* FIXED_DATE = "Thu, 01 Jan 2024 00:00:00 GMT";
} // namespace
// ── RequestHandler interface ─────────────────────────────────────────────────
bool WebDAVHandler::canHandle(WebServer& server, HTTPMethod method, const String& uri) {
(void)server;
(void)uri;
switch (method) {
case HTTP_OPTIONS:
case HTTP_PROPFIND:
case HTTP_GET:
case HTTP_HEAD:
case HTTP_PUT:
case HTTP_DELETE:
case HTTP_MKCOL:
case HTTP_MOVE:
case HTTP_COPY:
case HTTP_LOCK:
case HTTP_UNLOCK:
return true;
default:
return false;
}
}
bool WebDAVHandler::canRaw(WebServer& server, const String& uri) {
(void)uri;
return server.method() == HTTP_PUT;
}
void WebDAVHandler::raw(WebServer& server, const String& uri, HTTPRaw& raw) {
(void)uri;
if (raw.status == RAW_START) {
_putPath = getRequestPath(server);
if (isProtectedPath(_putPath)) {
_putOk = false;
return;
}
// Ensure parent directory exists
int lastSlash = _putPath.lastIndexOf('/');
if (lastSlash > 0) {
String parentPath = _putPath.substring(0, lastSlash);
if (!Storage.exists(parentPath.c_str())) {
_putOk = false;
return;
}
}
if (_putFile) _putFile.close();
_putExisted = Storage.exists(_putPath.c_str());
if (_putExisted) {
HalFile existing = Storage.open(_putPath.c_str());
if (existing && existing.isDirectory()) {
existing.close();
_putOk = false;
return;
}
if (existing) existing.close();
}
// Write to a temp file to avoid destroying the original on failed upload
String tempPath = _putPath + ".davtmp";
Storage.remove(tempPath.c_str());
_putOk = Storage.openFileForWrite("DAV", tempPath, _putFile);
LOG_DBG("DAV", "PUT START: %s", _putPath.c_str());
} else if (raw.status == RAW_WRITE) {
if (_putFile && _putOk) {
resetTaskWatchdogIfSubscribed();
size_t written = _putFile.write(raw.buf, raw.currentSize);
if (written != raw.currentSize) {
_putOk = false;
}
}
} else if (raw.status == RAW_END) {
if (_putFile) _putFile.close();
if (_putOk) {
String tempPath = _putPath + ".davtmp";
if (_putExisted) Storage.remove(_putPath.c_str());
HalFile tmp = Storage.open(tempPath.c_str());
if (tmp) {
_putOk = tmp.rename(_putPath.c_str());
tmp.close();
} else {
_putOk = false;
}
if (!_putOk) Storage.remove(tempPath.c_str());
}
LOG_DBG("DAV", "PUT END: %u bytes, ok=%d", raw.totalSize, _putOk);
} else if (raw.status == RAW_ABORTED) {
if (_putFile) _putFile.close();
String tempPath = _putPath + ".davtmp";
Storage.remove(tempPath.c_str());
_putOk = false;
}
}
bool WebDAVHandler::handle(WebServer& server, HTTPMethod method, const String& uri) {
(void)uri;
switch (method) {
case HTTP_OPTIONS:
handleOptions(server);
return true;
case HTTP_PROPFIND:
handlePropfind(server);
return true;
case HTTP_GET:
handleGet(server);
return true;
case HTTP_HEAD:
handleHead(server);
return true;
case HTTP_PUT:
handlePut(server);
return true;
case HTTP_DELETE:
handleDelete(server);
return true;
case HTTP_MKCOL:
handleMkcol(server);
return true;
case HTTP_MOVE:
handleMove(server);
return true;
case HTTP_COPY:
handleCopy(server);
return true;
case HTTP_LOCK:
handleLock(server);
return true;
case HTTP_UNLOCK:
handleUnlock(server);
return true;
default:
return false;
}
}
// ── OPTIONS ──────────────────────────────────────────────────────────────────
void WebDAVHandler::handleOptions(WebServer& s) {
s.sendHeader("DAV", "1");
s.sendHeader("Allow",
"OPTIONS, GET, HEAD, PUT, DELETE, "
"PROPFIND, MKCOL, MOVE, COPY, LOCK, UNLOCK");
s.sendHeader("MS-Author-Via", "DAV");
s.send(200);
LOG_DBG("DAV", "OPTIONS %s", s.uri().c_str());
}
// ── PROPFIND ─────────────────────────────────────────────────────────────────
void WebDAVHandler::handlePropfind(WebServer& s) {
String path = getRequestPath(s);
int depth = getDepth(s);
LOG_DBG("DAV", "PROPFIND %s depth=%d", path.c_str(), depth);
// Check if path exists
if (!Storage.exists(path.c_str()) && path != "/") {
s.send(404, "text/plain", "Not Found");
return;
}
HalFile root = Storage.open(path.c_str());
if (!root) {
if (path == "/") {
// Root should always work — send minimal response
s.setContentLength(CONTENT_LENGTH_UNKNOWN);
s.send(207, "application/xml; charset=\"utf-8\"", "");
s.sendContent(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<D:multistatus xmlns:D=\"DAV:\">\n");
sendPropEntry(s, "/", true, 0, FIXED_DATE);
s.sendContent("</D:multistatus>\n");
s.sendContent("");
return;
}
s.send(500, "text/plain", "Failed to open");
return;
}
bool isDir = root.isDirectory();
s.setContentLength(CONTENT_LENGTH_UNKNOWN);
s.send(207, "application/xml; charset=\"utf-8\"", "");
s.sendContent(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<D:multistatus xmlns:D=\"DAV:\">\n");
// Entry for the resource itself
if (isDir) {
sendPropEntry(s, path, true, 0, FIXED_DATE);
} else {
sendPropEntry(s, path, false, root.size(), FIXED_DATE);
root.close();
s.sendContent("</D:multistatus>\n");
s.sendContent("");
return;
}
// If depth > 0 and it's a directory, list children
if (depth > 0) {
HalFile file = root.openNextFile();
char name[500];
while (file) {
file.getName(name, sizeof(name));
String fileName(name);
// Skip hidden/protected items
bool shouldHide = fileName.startsWith(".");
if (!shouldHide) {
for (const auto* item : HIDDEN_ITEMS) {
if (fileName.equals(item)) {
shouldHide = true;
break;
}
}
}
if (!shouldHide) {
String childPath = path;
if (!childPath.endsWith("/")) childPath += "/";
childPath += fileName;
if (file.isDirectory()) {
sendPropEntry(s, childPath, true, 0, FIXED_DATE);
} else {
sendPropEntry(s, childPath, false, file.size(), FIXED_DATE);
}
}
file.close();
yield();
resetTaskWatchdogIfSubscribed();
file = root.openNextFile();
}
}
root.close();
s.sendContent("</D:multistatus>\n");
s.sendContent("");
}
void WebDAVHandler::sendPropEntry(WebServer& s, const String& path, bool isDir, size_t size,
const String& lastModified) const {
String href;
urlEncodePath(path, href);
// Ensure directory hrefs end with /
if (isDir && !href.endsWith("/")) href += "/";
String xml = "<D:response><D:href>";
xml += href;
xml += "</D:href><D:propstat><D:prop>";
if (isDir) {
xml += "<D:resourcetype><D:collection/></D:resourcetype>";
} else {
xml += "<D:resourcetype/>";
xml += "<D:getcontentlength>";
xml += String(size);
xml += "</D:getcontentlength>";
String mime = getMimeType(path);
xml += "<D:getcontenttype>";
xml += mime;
xml += "</D:getcontenttype>";
}
xml += "<D:getlastmodified>";
xml += lastModified;
xml += "</D:getlastmodified>";
xml += "</D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>\n";
s.sendContent(xml);
}
// ── GET ──────────────────────────────────────────────────────────────────────
void WebDAVHandler::handleGet(WebServer& s) {
String path = getRequestPath(s);
LOG_DBG("DAV", "GET %s", path.c_str());
if (isProtectedPath(path)) {
s.send(403, "text/plain", "Forbidden");
return;
}
if (!Storage.exists(path.c_str())) {
s.send(404, "text/plain", "Not Found");
return;
}
HalFile file = Storage.open(path.c_str());
if (!file) {
s.send(500, "text/plain", "Failed to open file");
return;
}
if (file.isDirectory()) {
file.close();
// For directories, return a PROPFIND-like response or redirect
s.send(405, "text/plain", "Method Not Allowed");
return;
}
String contentType = getMimeType(path);
const size_t fileSize = file.size();
file.close();
s.setContentLength(fileSize);
s.send(200, contentType.c_str(), "");
// **This used to be `client.write(file)`, and it sent exactly one byte.**
//
// It worked while `Storage.open()` returned an SdFat `FsFile`, which derives
// from `Stream`: the call matched `NetworkClient::write(Stream&)` and streamed
// the file. `HalFile` derives from `Print`, not `Stream` (lib/hal/HalStorage.h),
// so that overload stopped matching, the compiler took `HalFile::operator bool()`
// instead, promoted the `true` to `uint8_t`, and wrote a single `0x01`. **The
// call site never changed; its meaning did**, and nothing warned because every
// step is a legal conversion.
//
// The reply still carried the real Content-Length, so a client waited for a
// body that never arrived and reported a truncated transfer rather than an
// error, which is why this reads as a flaky network rather than a server bug.
NetworkClient client = s.client();
if (!Storage.readFileToStream(path.c_str(), client)) {
LOG_ERR("DAV", "GET %s: failed to stream file", path.c_str());
}
}
// ── HEAD ─────────────────────────────────────────────────────────────────────
void WebDAVHandler::handleHead(WebServer& s) {
String path = getRequestPath(s);
LOG_DBG("DAV", "HEAD %s", path.c_str());
if (isProtectedPath(path)) {
s.send(403, "text/plain", "");
return;
}
if (!Storage.exists(path.c_str())) {
s.send(404, "text/plain", "");
return;
}
HalFile file = Storage.open(path.c_str());
if (!file) {
s.send(500, "text/plain", "");
return;
}
if (file.isDirectory()) {
file.close();
s.send(200, "text/html", "");
return;
}
String contentType = getMimeType(path);
s.setContentLength(file.size());
s.send(200, contentType.c_str(), "");
file.close();
}
// ── PUT ──────────────────────────────────────────────────────────────────────
void WebDAVHandler::handlePut(WebServer& s) {
// Body was already received via canRaw/raw callbacks
String path = getRequestPath(s);
LOG_DBG("DAV", "PUT %s", path.c_str());
if (isProtectedPath(path)) {
s.send(403, "text/plain", "Forbidden");
return;
}
if (!_putOk) {
String tempPath = path + ".davtmp";
Storage.remove(tempPath.c_str());
s.send(500, "text/plain", "Write failed - incomplete upload or disk full");
return;
}
clearBookCache(path.c_str());
s.send(_putExisted ? 204 : 201);
LOG_DBG("DAV", "PUT complete: %s", path.c_str());
}
// ── DELETE ───────────────────────────────────────────────────────────────────
void WebDAVHandler::handleDelete(WebServer& s) {
String path = getRequestPath(s);
LOG_DBG("DAV", "DELETE %s", path.c_str());
if (path == "/" || path.isEmpty()) {
s.send(403, "text/plain", "Cannot delete root");
return;
}
if (isProtectedPath(path)) {
s.send(403, "text/plain", "Forbidden");
return;
}
if (!Storage.exists(path.c_str())) {
s.send(404, "text/plain", "Not Found");
return;
}
HalFile file = Storage.open(path.c_str());
if (!file) {
s.send(500, "text/plain", "Failed to open");
return;
}
if (file.isDirectory()) {
// Check if directory is empty
HalFile entry = file.openNextFile();
if (entry) {
entry.close();
file.close();
s.send(409, "text/plain", "Directory not empty");
return;
}
file.close();
if (Storage.rmdir(path.c_str())) {
s.send(204);
} else {
s.send(500, "text/plain", "Failed to remove directory");
}
} else {
file.close();
if (removeBookFile(path.c_str())) {
s.send(204);
} else {
s.send(500, "text/plain", "Failed to delete file");
}
}
}
// ── MKCOL ────────────────────────────────────────────────────────────────────
void WebDAVHandler::handleMkcol(WebServer& s) {
String path = getRequestPath(s);
LOG_DBG("DAV", "MKCOL %s", path.c_str());
if (isProtectedPath(path)) {
s.send(403, "text/plain", "Forbidden");
return;
}
// MKCOL must not have a body (RFC 4918)
if (s.clientContentLength() > 0) {
s.send(415, "text/plain", "Unsupported Media Type");
return;
}
if (Storage.exists(path.c_str())) {
s.send(405, "text/plain", "Already exists");
return;
}
// Check parent exists
int lastSlash = path.lastIndexOf('/');
if (lastSlash > 0) {
String parentPath = path.substring(0, lastSlash);
if (!parentPath.isEmpty() && !Storage.exists(parentPath.c_str())) {
s.send(409, "text/plain", "Parent directory does not exist");
return;
}
}
if (Storage.mkdir(path.c_str())) {
s.send(201);
LOG_DBG("DAV", "Created directory: %s", path.c_str());
} else {
s.send(500, "text/plain", "Failed to create directory");
}
}
// ── MOVE ─────────────────────────────────────────────────────────────────────
void WebDAVHandler::handleMove(WebServer& s) {
String srcPath = getRequestPath(s);
String dstPath = getDestinationPath(s);
bool overwrite = getOverwrite(s);
LOG_DBG("DAV", "MOVE %s -> %s (overwrite=%d)", srcPath.c_str(), dstPath.c_str(), overwrite);
if (srcPath == "/" || srcPath.isEmpty()) {
s.send(403, "text/plain", "Cannot move root");
return;
}
if (isProtectedPath(srcPath) || isProtectedPath(dstPath)) {
s.send(403, "text/plain", "Forbidden");
return;
}
if (dstPath.isEmpty()) {
s.send(400, "text/plain", "Missing Destination header");
return;
}
if (srcPath == dstPath) {
s.send(204);
return;
}
if (!Storage.exists(srcPath.c_str())) {
s.send(404, "text/plain", "Source not found");
return;
}
// Check destination parent exists
int lastSlash = dstPath.lastIndexOf('/');
if (lastSlash > 0) {
String parentPath = dstPath.substring(0, lastSlash);
if (!parentPath.isEmpty() && !Storage.exists(parentPath.c_str())) {
s.send(409, "text/plain", "Destination parent does not exist");
return;
}
}
bool dstExists = Storage.exists(dstPath.c_str());
if (dstExists && !overwrite) {
s.send(412, "text/plain", "Destination exists and Overwrite is F");
return;
}
if (dstExists && !removeBookFile(dstPath.c_str())) {
s.send(500, "text/plain", "Failed to remove destination");
return;
}
HalFile file = Storage.open(srcPath.c_str());
if (!file) {
s.send(500, "text/plain", "Failed to open source");
return;
}
clearBookCache(srcPath.c_str());
file.close();
const bool success = ClippingStore::moveBook(srcPath.c_str(), dstPath.c_str());
if (success) {
s.send(dstExists ? 204 : 201);
} else {
s.send(500, "text/plain", "Move failed");
}
}
// ── COPY ─────────────────────────────────────────────────────────────────────
void WebDAVHandler::handleCopy(WebServer& s) {
String srcPath = getRequestPath(s);
String dstPath = getDestinationPath(s);
bool overwrite = getOverwrite(s);
LOG_DBG("DAV", "COPY %s -> %s (overwrite=%d)", srcPath.c_str(), dstPath.c_str(), overwrite);
if (isProtectedPath(srcPath) || isProtectedPath(dstPath)) {
s.send(403, "text/plain", "Forbidden");
return;
}
if (dstPath.isEmpty()) {
s.send(400, "text/plain", "Missing Destination header");
return;
}
if (srcPath == dstPath) {
s.send(204);
return;
}
if (!Storage.exists(srcPath.c_str())) {
s.send(404, "text/plain", "Source not found");
return;
}
HalFile srcFile = Storage.open(srcPath.c_str());
if (!srcFile) {
s.send(500, "text/plain", "Failed to open source");
return;
}
if (srcFile.isDirectory()) {
srcFile.close();
s.send(403, "text/plain", "Cannot copy directories");
return;
}
// Check destination parent exists
int lastSlash = dstPath.lastIndexOf('/');
if (lastSlash > 0) {
String parentPath = dstPath.substring(0, lastSlash);
if (!parentPath.isEmpty() && !Storage.exists(parentPath.c_str())) {
srcFile.close();
s.send(409, "text/plain", "Destination parent does not exist");
return;
}
}
bool dstExists = Storage.exists(dstPath.c_str());
if (dstExists && !overwrite) {
srcFile.close();
s.send(412, "text/plain", "Destination exists and Overwrite is F");
return;
}
if (dstExists) {
Storage.remove(dstPath.c_str());
}
HalFile dstFile;
if (!Storage.openFileForWrite("DAV", dstPath, dstFile)) {
srcFile.close();
s.send(500, "text/plain", "Failed to create destination");
return;
}
// Streaming copy with 4KB buffer on stack
uint8_t buf[4096];
bool copyOk = true;
while (srcFile.available()) {
resetTaskWatchdogIfSubscribed();
int bytesRead = srcFile.read(buf, sizeof(buf));
if (bytesRead <= 0) break;
size_t written = dstFile.write(buf, bytesRead);
if (written != (size_t)bytesRead) {
copyOk = false;
break;
}
}
srcFile.close();
dstFile.close();
if (copyOk) {
s.send(dstExists ? 204 : 201);
} else {
Storage.remove(dstPath.c_str());
s.send(500, "text/plain", "Copy failed - disk full?");
}
}
// ── LOCK / UNLOCK (dummy for client compatibility) ───────────────────────────
void WebDAVHandler::handleLock(WebServer& s) {
String path = getRequestPath(s);
LOG_DBG("DAV", "LOCK %s (dummy)", path.c_str());
// Return a dummy lock token for client compatibility
String xml =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<D:prop xmlns:D=\"DAV:\">\n"
"<D:lockdiscovery><D:activelock>\n"
"<D:locktype><D:write/></D:locktype>\n"
"<D:lockscope><D:exclusive/></D:lockscope>\n"
"<D:depth>infinity</D:depth>\n"
"<D:owner><D:href>crosspoint</D:href></D:owner>\n"
"<D:timeout>Second-3600</D:timeout>\n"
"<D:locktoken><D:href>urn:uuid:dummy-lock-token</D:href></D:locktoken>\n"
"<D:lockroot><D:href>/</D:href></D:lockroot>\n"
"</D:activelock></D:lockdiscovery>\n"
"</D:prop>\n";
s.sendHeader("Lock-Token", "<urn:uuid:dummy-lock-token>");
s.send(200, "application/xml; charset=\"utf-8\"", xml);
}
void WebDAVHandler::handleUnlock(WebServer& s) {
LOG_DBG("DAV", "UNLOCK %s (dummy)", s.uri().c_str());
s.send(204);
}
// ── Utility functions ────────────────────────────────────────────────────────
String WebDAVHandler::getRequestPath(WebServer& s) const {
String uri = s.uri();
String decoded = WebServer::urlDecode(uri);
// Normalize using FsHelpers
std::string normalized = FsHelpers::normalisePath(decoded.c_str());
String result = normalized.c_str();
if (result.isEmpty()) return "/";
if (!result.startsWith("/")) result = "/" + result;
// Remove trailing slash unless root
if (result.length() > 1 && result.endsWith("/")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
String WebDAVHandler::getDestinationPath(WebServer& s) const {
String dest = s.header("Destination");
if (dest.isEmpty()) return "";
// Extract path from full URL: http://host/path -> /path
// Find the third slash (after http://)
int schemeEnd = dest.indexOf("://");
if (schemeEnd >= 0) {
int pathStart = dest.indexOf('/', schemeEnd + 3);
if (pathStart >= 0) {
dest = dest.substring(pathStart);
} else {
dest = "/";
}
}
String decoded = WebServer::urlDecode(dest);
std::string normalized = FsHelpers::normalisePath(decoded.c_str());
String result = normalized.c_str();
if (result.isEmpty()) return "/";
if (!result.startsWith("/")) result = "/" + result;
// Remove trailing slash unless root
if (result.length() > 1 && result.endsWith("/")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
void WebDAVHandler::urlEncodePath(const String& path, String& out) const {
out = "";
for (unsigned int i = 0; i < path.length(); i++) {
char c = path.charAt(i);
if (c == '/') {
out += '/';
} else if (c == ' ') {
out += "%20";
} else if (c == '%') {
out += "%25";
} else if (c == '#') {
out += "%23";
} else if (c == '?') {
out += "%3F";
} else if (c == '&') {
out += "%26";
} else if ((uint8_t)c > 127) {
// Encode non-ASCII bytes
char hex[4];
snprintf(hex, sizeof(hex), "%%%02X", (uint8_t)c);
out += hex;
} else {
out += c;
}
}
}
bool WebDAVHandler::isProtectedPath(const String& path) const {
// Check every segment of the path, not just the last one.
// This prevents access to e.g. /.hidden/somefile or /System Volume Information/foo
int start = 0;
while (start < (int)path.length()) {
if (path.charAt(start) == '/') {
start++;
continue;
}
int end = path.indexOf('/', start);
if (end == -1) end = path.length();
String segment = path.substring(start, end);
if (segment.startsWith(".")) return true;
for (const auto* item : HIDDEN_ITEMS) {
if (segment.equals(item)) return true;
}
start = end + 1;
}
return false;
}
int WebDAVHandler::getDepth(WebServer& s) const {
String depth = s.header("Depth");
if (depth == "0") return 0;
if (depth == "1") return 1;
// "infinity" or missing → treat as 1 (Class 1 servers don't need to support infinity)
return 1;
}
bool WebDAVHandler::getOverwrite(WebServer& s) const {
String ow = s.header("Overwrite");
if (ow == "F" || ow == "f") return false;
return true; // Default is T
}
String WebDAVHandler::getMimeType(const String& path) {
if (FsHelpers::hasEpubExtension(path)) return "application/epub+zip";
if (FsHelpers::checkFileExtension(path, ".pdf")) return "application/pdf";
if (FsHelpers::hasTxtExtension(path)) return "text/plain";
if (FsHelpers::checkFileExtension(path, ".html") || FsHelpers::checkFileExtension(path, ".htm")) return "text/html";
if (FsHelpers::checkFileExtension(path, ".css")) return "text/css";
if (FsHelpers::checkFileExtension(path, ".js")) return "application/javascript";
if (FsHelpers::checkFileExtension(path, ".json")) return "application/json";
if (FsHelpers::checkFileExtension(path, ".xml")) return "application/xml";
if (FsHelpers::hasJpgExtension(path)) return "image/jpeg";
if (FsHelpers::hasPngExtension(path)) return "image/png";
if (FsHelpers::hasGifExtension(path)) return "image/gif";
if (FsHelpers::checkFileExtension(path, ".svg")) return "image/svg+xml";
if (FsHelpers::checkFileExtension(path, ".zip")) return "application/zip";
if (FsHelpers::checkFileExtension(path, ".gz")) return "application/gzip";
return "application/octet-stream";
}