forked from ardyesp/ESPWebDAV
-
Notifications
You must be signed in to change notification settings - Fork 9
/
ESPWebDAV.cpp
1789 lines (1521 loc) · 51.1 KB
/
ESPWebDAV.cpp
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
/*
Copyright (c) 2018 Gurpreet Bal https://github.com/ardyesp/ESPWebDAV
Copyright (c) 2020 David Gauchard https://github.com/d-a-v/ESPWebDAV
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/
#include "strutils.h"
#include <FS.h>
#if defined(ARDUINO_ARCH_ESP8266) || defined(CORE_MOCK)
#include <ESP8266WiFi.h>
#include <coredecls.h> // crc32()
#include <PolledTimeout.h>
#define FILENAME(f) f.fileName().c_str()
#define FILEFULLNAME(f) f.fullName()
#define FILESIZE(f) f.fileSize()
#define FILETIME(f) f.fileTime()
#define GETCREATIONTIME(f) f.getCreationTime()
#define FILECREATIONTIME(f) f.fileCreationTime()
#define ISFILE(f) f.isFile()
#endif //ARDUINO_ARCH_ESP8266
#if defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#include "PolledTimeout_esp32.h"
#include <rom/miniz.h>
const char * FileName(const char * path)
{
String name = path;
if (name == "/")return path;
//path should not end by / if yes need to add a sanity check
int p = name.lastIndexOf("/");
if (p == -1) return path;
return &path[p + 1];
}
#undef crc32
#define crc32(a, len) mz_crc32( 0xffffffff,(const unsigned char *)a, len)
#define FILENAME(f) FileName(f.name())
#define FILEFULLNAME(f) f.name()
#define FILESIZE(f) f.size()
#define FILETIME(f) f.getLastWrite()
#define GETCREATIONTIME(f) f.getLastWrite()
#define FILECREATIONTIME(f) f.getLastWrite()
#define ISFILE(f) !f.isDirectory()
//in esp32 totalbytes and usedbytes are not part of FS class
//so need to call an helper to address directly SPIFFS/LITTLEFS/SD/etc...
//but due to https://support.microsoft.com/en-us/topic/webdav-mapped-drive-reports-incorrect-drive-capacity-fa101657-7448-1ce6-5999-5bcc59d6a8bd
//this is not used / working
//so let just send 0 but keep helper as comment if in futur it is working
//extern uint64_t TotalBytes();
//extern uint64_t UsedBytes();
#define TotalBytes() 0
#define UsedBytes() 0
#endif //ARDUINO_ARCH_ESP32
#include <time.h>
#include <ESPWebDAV.h>
#define ALLOW "PROPPATCH,PROPFIND,OPTIONS,DELETE" SCUNLOCK ",COPY" SCLOCK ",MOVE,HEAD,POST,PUT,GET"
#if WEBDAV_LOCK_SUPPORT
#define SLOCK "LOCK"
#define SCLOCK ",LOCK"
#define SUNLOCK "UNLOCK"
#define SCUNLOCK ",UNLOCK"
#else
#define SLOCK ""
#define SCLOCK ""
#define SUNLOCK ""
#define SCUNLOCK ""
#endif
#define DEBUG_LEN 160
#define PROC "proc" // simple virtual file. TODO XXX real virtual fs with user callbacks
#if STREAMSEND_API
static const __FlashStringHelper* streamError (Stream::Report r)
{
switch (r) {
case Stream::Report::TimedOut: return F("Stream::send: timeout");
case Stream::Report::ReadError: return F("Stream::send: read error");
case Stream::Report::WriteError: return F("Stream::send: write error");
case Stream::Report::ShortOperation: return F("Stream::send: short transfer");
default: return F("");
}
}
#endif // STREAMSEND_API
#if defined(ARDUINO_ARCH_ESP32)
// transfer buffer
#define BUF_ALLOC(bufSize, error...) \
constexpr size_t bufSize = 3 * TCP_MSS; \
char* buf = (char*)malloc(bufSize); \
if (!buf) do { error; } while (0);
#define BUF_FREE() free(buf);
#else
// transfer buffer for small stack / heap
// (esp8266 arduino core v3 should use Stream::send API for data transfer)
#define BUF_ALLOC(bufSize, error...) \
constexpr size_t bufSize = 128; \
char buf[bufSize];
#define BUF_FREE() do { (void)0; } while (0)
#endif
#if WEBDAV_LOCK_SUPPORT
void ESPWebDAVCore::makeToken(String& ret, uint32_t pash, uint32_t ownash)
{
char lock_token[17];
snprintf(lock_token, sizeof(lock_token), "%08x%08x", pash, ownash);
ret = lock_token;
}
int ESPWebDAVCore::extractLockToken(const String& someHeader, const char* start, const char* end, uint32_t& pash, uint32_t& ownash)
{
// If: (<46dd353d7e585af1>)
// =>
// IfToken: path:0x46dd353d / owner:0x7e585af1
pash = 0;
ownash = 0;
DBG_PRINT("extracting lockToken from '%s'", someHeader.c_str());
// extract "... <:[lock >
int startIdx = someHeader.indexOf(start);
if (startIdx < 0)
{
DBG_PRINT("lock: can't find '%s'", start);
return 412; // fail with precondition failed
}
startIdx += strlen(start);
int endIdx = someHeader.indexOf(end, startIdx);
if (endIdx < 0)
{
DBG_PRINT("lock: can't find '%s'", end);
return 412; // fail with precondition fail
}
DBG_PRINT("found in [%d..%d[ (%d)", startIdx, endIdx, endIdx - startIdx);
int len = endIdx - startIdx;
if (len < 1 || len > 16)
{
DBG_PRINT("lock: format error (1-16 hex chars)");
return 423; // fail with lock
}
char cp [len + 1];
memcpy(cp, &(someHeader.c_str()[startIdx]), len);
cp[len] = 0;
DBG_PRINT("IfToken: '%s'", cp);
int ownIdx = std::max(len - 8, 0);
ownash = strtoul(&cp[ownIdx], nullptr, 16);
cp[ownIdx] = 0;
pash = strtoul(cp, nullptr, 16);
DBG_PRINT("IfToken: path:0x%08x / owner:0x%08x", pash, ownash);
return 200;
}
#endif // WEBDAV_LOCK_SUPPORT
int ESPWebDAVCore::allowed(const String& uri, uint32_t ownash)
{
#if WEBDAV_LOCK_SUPPORT > 1
String test = uri;
while (test.length())
{
stripSlashes(test);
DBG_PRINT("lock: testing '%s'", test.c_str());
uint32_t hash = crc32(test.c_str(), test.length());
const auto& lock = _locks.find(hash);
if (lock != _locks.end())
{
DBG_PRINT("lock: found lock, %sowner!", lock->second == ownash ? "" : "not");
return lock->second == ownash ? 200 : 423;
}
int s = test.lastIndexOf('/');
if (s < 0)
break;
test.remove(s);
}
DBG_PRINT("lock: none found");
return 200;
#else
(void)uri;
(void)ownash;
return 200;
#endif
}
int ESPWebDAVCore::allowed(const String& uri, const String& xml /* = emptyString */)
{
uint32_t hpash, anyownash;
if (ifHeader.length())
{
int code = extractLockToken(ifHeader, "(<", ">", hpash, anyownash);
if (code != 200)
return code;
if (anyownash == 0)
// malformed
return 412; // PUT failed with 423 not 412
}
else
{
int startIdx = xml.indexOf("<owner>");
int endIdx = xml.indexOf("</owner>");
anyownash = startIdx > 0 && endIdx > 0 ? crc32(&(xml.c_str()[startIdx + 7]), endIdx - startIdx - 7) : 0;
}
return allowed(uri, anyownash);
}
void ESPWebDAVCore::stripName(String& name)
{
if (name.length() > (size_t)_maxPathLength)
{
int dot = name.lastIndexOf('.');
int newDot = _maxPathLength - (name.length() - dot);
if (dot <= 0 || newDot < 0)
name.remove(_maxPathLength);
else
name.remove(newDot, dot - newDot);
}
}
void ESPWebDAVCore::stripHost(String& name)
{
int remove = name.indexOf(hostHeader);
if (remove >= 0)
name.remove(0, remove + hostHeader.length());
}
void ESPWebDAVCore::dir(const String& path, Print* out)
{
dirAction(path, true, [out](int depth, const String & parent, Dir & entry)->bool
{
(void)parent;
for (int i = 0; i < depth; i++)
out->print(" ");
if (entry.isDirectory())
out->printf("[%s]\n", FILENAME(entry));
else
out->printf("%-40s%4dMiB %6dKiB %d\n",
FILENAME(entry),
((int)FILESIZE(entry) + (1 << 19)) >> 20,
((int)FILESIZE(entry) + (1 << 9)) >> 10,
(int)FILESIZE(entry));
return true;
}, /*false=subdir first*/false);
}
size_t ESPWebDAVCore::makeVirtual(virt_e v, String& internal)
{
if (v == VIRT_PROC)
{
#if defined(ARDUINO_ARCH_ESP8266) || defined(CORE_MOCK)
internal = ESP.getFullVersion();
#endif //ARDUINO_ARCH_ESP8266
#if defined(ARDUINO_ARCH_ESP32)
internal = "SDK:";
internal += ESP.getSdkVersion();
#endif //ARDUINO_ARCH_ESP32
internal += '\n';
}
return internal.length();
}
ESPWebDAVCore::virt_e ESPWebDAVCore::isVirtual(const String& uri)
{
const char* n = &(uri.c_str()[0]);
while (*n && *n == '/')
n++;
if (strcmp(n, PROC) == 0)
return VIRT_PROC;
return VIRT_NONE;
}
bool ESPWebDAVCore::getPayload(StreamString& payload)
{
DBG_PRINT("content length=%d", (int)contentLengthHeader);
payload.clear();
if (contentLengthHeader > 0)
{
payload.reserve(contentLengthHeader);
#if defined(ARDUINO_ARCH_ESP8266) || defined(CORE_MOCK)
esp8266::polledTimeout::oneShotFastMs timeout(HTTP_MAX_POST_WAIT);
#endif //ARDUINO_ARCH_ESP8266
#if defined(ARDUINO_ARCH_ESP32)
PolledTimeout timeout(HTTP_MAX_POST_WAIT);
#endif //ARDUINO_ARCH_ESP32
while (payload.length() < (size_t)contentLengthHeader)
{
uint8_t buf[16];
auto n = client->read(buf, std::min((size_t)client->available(), sizeof(buf)));
if (n <= 0 && timeout)
{
DBG_PRINT("get content: short read (%d < %d)",
(int)payload.length(), (int)contentLengthHeader);
return false;
}
if (n > 0)
{
payload.write(buf, n);
timeout.reset();
}
}
DBG_PRINT(">>>>>>>>>>> CONTENT:");
DBG_PRINTSHORT("%s", payload.c_str());
DBG_PRINTSHORT("\n");
DBG_PRINT("<<<<<<<<<<< CONTENT");
}
return true;
}
bool ESPWebDAVCore::dirAction(const String& path,
bool recursive,
const std::function<bool(int depth, const String& parent, Dir& entry)>& cb,
bool callAfter,
int depth)
{
DBG_PRINT("diraction: scanning dir '%s'", path.c_str());
#if defined(ARDUINO_ARCH_ESP8266) || defined(CORE_MOCK)
Dir entry = gfs->openDir(path);
while (entry.next())
#endif //ARDUINO_ARCH_ESP8266
#if defined(ARDUINO_ARCH_ESP32)
File root = gfs->open(path);
File entry = root.openNextFile();
while (entry)
#endif //ARDUINO_ARCH_ESP32
{
if (!entry.isDirectory())
{
DBG_PRINT("diraction: %s/%s (%d B): ", path.c_str(), FILENAME(entry), (int)FILESIZE(entry));
if (cb(depth, path, entry))
{
DBG_PRINT("(file-OK)");
}
else
{
DBG_PRINT("(file-abort)");
return false;
}
}
#if defined(ARDUINO_ARCH_ESP32)
entry = root.openNextFile();
#endif //ARDUINO_ARCH_ESP32
}
if (recursive)
{
#if defined(ARDUINO_ARCH_ESP32)
root = gfs->open(path);
entry = root.openNextFile();
while (entry)
#endif //ARDUINO_ARCH_ESP32
#if defined(ARDUINO_ARCH_ESP8266) || defined(CORE_MOCK)
entry = gfs->openDir(path);
while (entry.next())
#endif //ARDUINO_ARCH_ESP8266
{
if (entry.isDirectory())
{
DBG_PRINT("diraction: -------- %s/%s/", path.c_str(), FILENAME(entry));
if ((callAfter || cb(depth, path, entry))
&& dirAction(path + '/' + FILENAME(entry), recursive, cb, callAfter, depth + 1)
&& (!callAfter || cb(depth, path, entry)))
{
DBG_PRINT("(dir-OK)");
}
else
{
DBG_PRINT("(dir-abort)");
return false;
}
}
#if defined(ARDUINO_ARCH_ESP32)
entry = root.openNextFile();
#endif //ARDUINO_ARCH_ESP32
}
}
return true;
}
void ESPWebDAVCore::handleIssue(int code, const char* text)
{
String message;
message.reserve(strlen(text) + uri.length() + method.length() + 32);
message += text;
message += "\nURI: ";
message += uri;
message += " Method: ";
message += method;
message += "\n";
String err;
err.reserve(strlen(text) + 32);
err += code;
err += ' ';
err += text;
DBG_PRINT("Issue:\ntext='%s'", text);
DBG_PRINT("message='%s'", message.c_str());
DBG_PRINT("err='%s'", err.c_str());
send(err, "text/plain", message);
}
void ESPWebDAVCore::handleRequest()
{
payload.clear();
replaceFront(uri, _davRoot, _fsRoot);
ResourceType resource = RESOURCE_NONE;
// check depth header
depth = DEPTH_NONE;
if (depthHeader.length())
{
if (depthHeader.equals("1"))
depth = DEPTH_CHILD;
else if (depthHeader.equals("infinity"))
depth = DEPTH_ALL;
DBG_PRINT("Depth: %d", depth);
}
File file;
if (uri != "/" && !gfs->exists(uri) && (method.equals("GET") || method.equals("HEAD")))
uri += ".gz";
if (uri == "/" || gfs->exists(uri))
{
// does uri refer to a file or directory or a null?
file = gfs->open(uri, "r");
if (file)
{
resource = file.isDirectory() ? RESOURCE_DIR : RESOURCE_FILE;
DBG_PRINT("resource: '%s' is %s", uri.c_str(), resource == RESOURCE_DIR ? "dir" : "file");
}
else
DBG_PRINT("resource: '%s': no file nor dir", uri.c_str());
}
else
{
DBG_PRINT("resource: '%s': not exists", uri.c_str());
}
DBG_PRINT("m: %s", method.c_str());
DBG_PRINT(" r: %d", resource);
DBG_PRINT(" u: %s", uri.c_str());
// add header that gets sent everytime
#if WEBDAV_LOCK_SUPPORT
sendHeader("DAV", "1, 2");
#else
sendHeader("DAV", "1");
#endif
sendHeader("Accept-Ranges", "bytes");
sendHeader("Allow", ALLOW);
// handle file create/uploads
if (method.equals("PUT"))
// payload is managed
return handlePut(resource);
// swallow content
if (!getPayload(payload))
{
handleIssue(408, "Request Time-out");
client->stop();
return;
}
// handle properties
if (method.equals("PROPFIND"))
return handleProp(resource, file);
if (method.equals("GET"))
return handleGet(resource, file, true);
if (method.equals("HEAD"))
return handleGet(resource, file, false);
// handle options
if (method.equals("OPTIONS"))
return handleOptions(resource);
#if WEBDAV_LOCK_SUPPORT
// handle file locks
if (method.equals("LOCK"))
return handleLock(resource);
if (method.equals("UNLOCK"))
return handleUnlock(resource);
#endif
if (method.equals("PROPPATCH"))
return handlePropPatch(resource, file);
// directory creation
if (method.equals("MKCOL"))
return handleDirectoryCreate(resource);
// move a file or directory
if (method.equals("MOVE"))
return handleMove(resource, file);
// delete a file or directory
if (method.equals("DELETE"))
return handleDelete(resource);
// delete a file or directory
if (method.equals("COPY"))
return handleCopy(resource, file);
// if reached here, means its a unhandled
handleIssue(404, "Not found");
//return false;
}
void ESPWebDAVCore::handleOptions(ResourceType resource)
{
(void)resource;
DBG_PRINT("Processing OPTION");
send("200 OK", NULL, "");
}
#if WEBDAV_LOCK_SUPPORT
void ESPWebDAVCore::handleLock(ResourceType resource)
{
DBG_PRINT("Processing LOCK");
// does URI refer to an existing resource
(void)resource;
DBG_PRINT("r=%d/%d", resource, RESOURCE_NONE);
#if WEBDAV_LOCK_SUPPORT > 1
// lock owner
uint32_t hpash, ownash;
if (ifHeader.length())
{
int code;
if ((code = extractLockToken(ifHeader, "(<", ">", hpash, ownash)) != 200)
return handleIssue(code, "Lock error");
}
else
{
int startIdx, endIdx;
startIdx = payload.indexOf("<owner>");
endIdx = payload.indexOf("</owner>");
ownash = startIdx > 0 && endIdx > 0 ? crc32(&payload[startIdx + 7], endIdx - startIdx - 7) : 0;
}
if (!ownash)
{
/* XXXFIXME xml extraction should be improved (on macOS)
0:10:08.058253: <D:owner>
0:10:08.058391: <D:href>http://www.apple.com/webdav_fs/</D:href>
0:10:08.058898: </D:owner>
*/
ownash = 0xdeadbeef;
}
uint32_t pash = crc32(uri.c_str(), uri.length());
const auto& lock = _locks.find(pash);
if (lock == _locks.end())
{
_locks[pash] = ownash;
}
else
{
if (lock->second != ownash)
{
DBG_PRINT("cannot relock '%s' (owner is 0x%08x)", uri.c_str(), lock->second);
return handleIssue(423, "Locked");
}
DBG_PRINT("owner has relocked");
}
#else
const char* lock_token = "0";
#endif
String lock_token;
makeToken(lock_token, pash, ownash);
sendHeader("Lock-Token", lock_token);
#if 1
String resp;
resp.reserve(500 + uri.length());
resp += F("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<D:prop xmlns:D=\"DAV:\">"
"<D:lockdiscovery>"
"<D:activelock>"
"<D:locktoken>"
"<D:href>");
resp += lock_token;
resp += F("</D:href>"
"</D:locktoken>"
#if 0
"<D:locktype>"
"<write/>"
"</D:locktype>"
"<D:lockscope>"
"<exclusive/>"
"</D:lockscope>"
"<D:lockroot>"
"<D:href>");
resp += uri;
resp += F("</D:href>"
"</D:lockroot>"
"<D:depth>"
"infinity"
"</D:depth>");
#if 0
if (href.length())
{
resp += F("<D:owner>"
"<a:href xmlns:a=\"DAV:\">");
resp += href;
resp += F("</a:href>"
"</D:owner>");
}
#endif
resp += F("<D:timeout>"
"Second-3600"
"</D:timeout>"
#endif
"</D:activelock>"
"</D:lockdiscovery>"
"</D:prop>");
send("200 OK", "application/xml;charset=utf-8", resp);
#else
send("200 OK", "application/xml;charset=utf-8", "");
#endif
}
void ESPWebDAVCore::handleUnlock(ResourceType resource)
{
#if WEBDAV_LOCK_SUPPORT > 1
uint32_t pash = crc32(uri.c_str(), uri.length());
uint32_t hpash, hownash;
(void)extractLockToken(lockTokenHeader, "<", ">", hpash, hownash);
auto lock = _locks.find(pash);
if (lock == _locks.end())
{
DBG_PRINT("wasn't locked: '%s'", uri.c_str());
return handleIssue(423, "Locked");
}
if (lock->second != hownash)
{
DBG_PRINT("lock found, bad owner 0x%08x != 0x%08x", hownash, lock->second);
return handleIssue(423, "Locked");
}
_locks.erase(lock);
#endif
(void)resource;
DBG_PRINT("Processing UNLOCK");
send("204 No Content", NULL, "");
}
#endif // WEBDAV_LOCK_SUPPORT
void ESPWebDAVCore::handlePropPatch(ResourceType resource, File& file)
{
DBG_PRINT("PROPPATCH forwarding to PROPFIND");
handleProp(resource, file);
}
void ESPWebDAVCore::handleProp(ResourceType resource, File& file)
{
DBG_PRINT("Processing PROPFIND");
auto v = isVirtual(uri);
if (v)
resource = RESOURCE_FILE;
// does URI refer to an existing resource
else if (resource == RESOURCE_NONE)
return handleIssue(404, "Not found");
int code;
if (payload.indexOf("lockdiscovery") < 0 && (code = allowed(uri)) != 200)
return handleIssue(code, "Locked");
setContentLength(CONTENT_LENGTH_UNKNOWN);
send("207 Multi-Status", "application/xml;charset=utf-8", "");
sendContent(F("<?xml version=\"1.0\" encoding=\"utf-8\"?>"));
sendContent(F("<D:multistatus xmlns:D=\"DAV:\">"));
if (v)
{
// virtual file
sendPropResponse(false, uri.c_str(), 1024, time(nullptr), 0);
}
else if (ISFILE(file) || depth == DEPTH_NONE)
{
DBG_PRINT("----- PROP FILE '%s':", uri.c_str());
sendPropResponse(file.isDirectory(), uri.c_str(), file.size(), file.getLastWrite(), GETCREATIONTIME(file));
}
else
{
DBG_PRINT("----- PROP DIR '%s':", uri.c_str());
sendPropResponse(true, uri, 0, time(nullptr), 0);
#if defined(ARDUINO_ARCH_ESP32)
File root = gfs->open(uri);
File entry = root.openNextFile();
while (entry)
#endif //ARDUINO_ARCH_ESP32
#if defined(ARDUINO_ARCH_ESP8266) || defined(CORE_MOCK)
Dir entry = gfs->openDir(uri);
while (entry.next())
#endif //ARDUINO_ARCH_ESP8266
{
yield();
String path;
path.reserve(uri.length() + 1 + strlen(FILENAME(entry)));
path += uri;
path += '/';
path += FILENAME(entry);
stripSlashes(path);
DBG_PRINT("Path: %s", path.c_str());
sendPropResponse(entry.isDirectory(), path.c_str(), FILESIZE(entry), FILETIME(entry), FILECREATIONTIME(entry));
#if defined(ARDUINO_ARCH_ESP32)
entry = root.openNextFile();
#endif //ARDUINO_ARCH_ESP32
}
}
if (payload.indexOf(F("quota-available-bytes")) >= 0 ||
payload.indexOf(F("quota-used-bytes")) >= 0)
{
#if defined(ARDUINO_ARCH_ESP8266) || defined(CORE_MOCK)
fs::FSInfo64 info;
if (gfs->info64(info))
{
sendContentProp(F("quota-available-bytes"), String(1.0 * (info.totalBytes - info.usedBytes), 0));
sendContentProp(F("quota-used-bytes"), String(1.0 * info.usedBytes, 0));
}
#endif //ARDUINO_ARCH_ESP8266
#if defined(ARDUINO_ARCH_ESP32)
//NEED TO BE not related to SPIFFS
//use external functions
//but SPIFFS/FAT size_t because in MB
//and SD uint64_t because in GB
//so use uint64_t
sendContentProp(F("quota-available-bytes"), String(1.0 * (TotalBytes() - UsedBytes()), 0));
sendContentProp(F("quota-used-bytes"), String(1.0 * UsedBytes(), 0));
#endif //ARDUINO_ARCH_ESP32
}
sendContent(F("</D:multistatus>"));
}
void ESPWebDAVCore::sendContentProp(const String& what, const String& response)
{
String one;
one.reserve(100 + 2 * what.length() + response.length());
one += F("<esp:");
one += what;
one += F(">");
one += response;
one += F("</esp:");
one += what;
one += F(">");
sendContent(one);
}
void ESPWebDAVCore::sendPropResponse(bool isDir, const String& fullResPathFS, size_t size, time_t lastWrite, time_t creationDate)
{
String fullResPath = fullResPathFS;
replaceFront(fullResPath, _fsRoot, _davRoot);
fullResPath = c2enc(fullResPath);
String blah;
blah.reserve(100);
blah += F("<D:response xmlns:esp=\"DAV:\"><D:href>");
blah += fullResPath;
blah += F("</D:href><D:propstat><D:status>HTTP/1.1 200 OK</D:status><D:prop>");
sendContent(blah);
sendContentProp(F("getlastmodified"), date2date(lastWrite));
sendContentProp(F("creationdate"), date2date(creationDate));
DBG_PRINT("-----\nentry: '%s'(dir:%d)\n-----",
fullResPath.c_str(), isDir);
if (isDir)
{
sendContentProp(F("resourcetype"), F("<D:collection/>"));
}
else
{
sendContentProp(F("getcontentlength"), String(size));
sendContentProp(F("getcontenttype"), contentTypeFn(fullResPath));
sendContent("<resourcetype/>");
char entityTag [uri.length() + 32];
sprintf(entityTag, "%s%lu", uri.c_str(), (unsigned long)lastWrite);
uint32_t crc = crc32(entityTag, strlen(entityTag));
sprintf(entityTag, "\"%08x\"", crc);
sendContentProp(F("getetag"), entityTag);
}
sendContentProp(F("displayname"), fullResPath);
sendContent(F("</D:prop></D:propstat></D:response>"));
}
void ESPWebDAVCore::handleGet(ResourceType resource, File& file, bool isGet)
{
DBG_PRINT("Processing GET (ressource=%d)", (int)resource);
// does URI refer to an existing file resource
auto v = isVirtual(uri);
if (!v)
{
if (resource == RESOURCE_DIR)
return handleIssue(200, "GET/HEAD on dir");
if (resource != RESOURCE_FILE)
return handleIssue(404, "Not found");
}
// no lock on GET
#if DBG_WEBDAV
long tStart = millis();
#endif
size_t fileSize = file.size();
String contentType = contentTypeFn(uri);
if (uri.endsWith(".gz")) //&& contentType != "application/x-gzip" && contentType != "application/octet-stream")
sendHeader("Content-Encoding", "gzip");
String internal = emptyString;
if (v)
{
fileSize = makeVirtual(v, internal);
}
else if (!fileSize)
{
setContentLength(0);
send("200 OK", contentType.c_str(), "");
DBG_PRINT("send empty file");
return;
}
BUF_ALLOC(bufSize, return send("500 Memory full", contentType.c_str(), ""));
// Content-Range: bytes 0-1023/146515
// Content-Length: 1024
int remaining;
if (_rangeStart == 0 && (_rangeEnd < 0 || _rangeEnd == (int)fileSize - 1))
{
_rangeEnd = fileSize - 1;
remaining = fileSize;
setContentLength(remaining);
send("200 OK", contentType.c_str(), "");
}
else
{
if (_rangeEnd == -1 || _rangeEnd >= (int)fileSize)
{
_rangeEnd = _rangeStart + (2 * TCP_MSS - 100);
if (_rangeEnd >= (int)fileSize)
_rangeEnd = fileSize - 1;
}
snprintf(buf, bufSize, "bytes %d-%d/%d", _rangeStart, _rangeEnd, (int)fileSize);
sendHeader("Content-Range", buf);
remaining = _rangeEnd - _rangeStart + 1;
setContentLength(remaining);
send("206 Partial Content", contentType.c_str(), "");
}
if (isGet && (internal.length() || file.seek(_rangeStart, SeekSet)))
{
DBG_PRINT("GET: (%d bytes, remain=%d)", remaining, remaining);
if (internal.length())
{
// send virtual content
if (transferStatusFn)
transferStatusFn(file.name(), (100 * _rangeStart) / fileSize, false);
if (client->write(&internal.c_str()[_rangeStart], remaining) != (size_t)remaining)
{
DBG_PRINT("file->net short transfer");
}
else if (transferStatusFn)
transferStatusFn(file.name(), (100 * (_rangeStart + remaining)) / fileSize, false);
}
else
{
if (transferStatusFn)
transferStatusFn(file.name(), 0, false);
int percent = 0;
while (remaining > 0 && file.available())
{
#if STREAMSEND_API
size_t numRead = file.sendSize(client, 2 * TCP_MSS);
if (file.getLastSendReport() != Stream::Report::Success)
{
String error;
error.reserve(64);
error += F("Write data failed: ");
error += streamError(file.getLastSendReport());
DBG_PRINT("WebDav: Get: file('%s') error: %s\n", file.name(), error.c_str());
break; // abort transfer
}
#else // !STREAMSEND_API
#if defined(ARDUINO_ARCH_ESP8266) || defined(CORE_MOCK)
#warning NOT using Stream::sendSize
#endif
size_t toRead = (size_t)remaining > bufSize ? bufSize : remaining;
size_t numRead = file.read((uint8_t*)buf, toRead);
DBG_PRINT("read %d bytes from file", (int)numRead);
if (client->write(buf, numRead) != numRead)
{
DBG_PRINT("file->net short transfer");
break; // abort transfer
}
#endif // !STREAMSEND_API
#if 0 && DBG_WEBDAV
for (size_t i = 0; i < 80 && i < numRead; i++)
DBG_PRINTSHORT("%c", buf[i] < 32 || buf[i] > 127 ? '.' : buf[i]);
#endif
remaining -= numRead;
if (transferStatusFn)
{
int p = (100 * (file.size() - remaining)) / file.size();
if (p != percent)
{
transferStatusFn(file.name(), percent = p, false);
}
}
DBG_PRINT("wrote %d bytes to http client", (int)numRead);
}
}
}
BUF_FREE();
DBG_PRINT("File %zu bytes sent in: %ld sec", fileSize, (millis() - tStart) / 1000);
}