/
filesystem.c++
1595 lines (1412 loc) · 50.5 KB
/
filesystem.c++
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) 2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "filesystem.h"
#include "vector.h"
#include "debug.h"
#include "one-of.h"
#include <map>
namespace kj {
Path::Path(StringPtr name): Path(heapString(name)) {}
Path::Path(String&& name): parts(heapArray<String>(1)) {
parts[0] = kj::mv(name);
validatePart(parts[0]);
}
Path::Path(ArrayPtr<const StringPtr> parts)
: Path(KJ_MAP(p, parts) { return heapString(p); }) {}
Path::Path(Array<String> partsParam)
: Path(kj::mv(partsParam), ALREADY_CHECKED) {
for (auto& p: parts) {
validatePart(p);
}
}
Path PathPtr::clone() {
return Path(KJ_MAP(p, parts) { return heapString(p); }, Path::ALREADY_CHECKED);
}
Path Path::parse(StringPtr path) {
KJ_REQUIRE(!path.startsWith("/"), "expected a relative path, got absolute", path) {
// When exceptions are disabled, go on -- the leading '/' will end up ignored.
break;
}
return evalImpl(Vector<String>(countParts(path)), path);
}
Path PathPtr::append(Path suffix) const {
auto newParts = kj::heapArrayBuilder<String>(parts.size() + suffix.parts.size());
for (auto& p: parts) newParts.add(heapString(p));
for (auto& p: suffix.parts) newParts.add(kj::mv(p));
return Path(newParts.finish(), Path::ALREADY_CHECKED);
}
Path Path::append(Path suffix) && {
auto newParts = kj::heapArrayBuilder<String>(parts.size() + suffix.parts.size());
for (auto& p: parts) newParts.add(kj::mv(p));
for (auto& p: suffix.parts) newParts.add(kj::mv(p));
return Path(newParts.finish(), ALREADY_CHECKED);
}
Path PathPtr::append(PathPtr suffix) const {
auto newParts = kj::heapArrayBuilder<String>(parts.size() + suffix.parts.size());
for (auto& p: parts) newParts.add(heapString(p));
for (auto& p: suffix.parts) newParts.add(heapString(p));
return Path(newParts.finish(), Path::ALREADY_CHECKED);
}
Path Path::append(PathPtr suffix) && {
auto newParts = kj::heapArrayBuilder<String>(parts.size() + suffix.parts.size());
for (auto& p: parts) newParts.add(kj::mv(p));
for (auto& p: suffix.parts) newParts.add(heapString(p));
return Path(newParts.finish(), ALREADY_CHECKED);
}
Path PathPtr::eval(StringPtr pathText) const {
if (pathText.startsWith("/")) {
// Optimization: avoid copying parts that will just be dropped.
return Path::evalImpl(Vector<String>(Path::countParts(pathText)), pathText);
} else {
Vector<String> newParts(parts.size() + Path::countParts(pathText));
for (auto& p: parts) newParts.add(heapString(p));
return Path::evalImpl(kj::mv(newParts), pathText);
}
}
Path Path::eval(StringPtr pathText) && {
if (pathText.startsWith("/")) {
// Optimization: avoid copying parts that will just be dropped.
return evalImpl(Vector<String>(countParts(pathText)), pathText);
} else {
Vector<String> newParts(parts.size() + countParts(pathText));
for (auto& p: parts) newParts.add(kj::mv(p));
return evalImpl(kj::mv(newParts), pathText);
}
}
PathPtr PathPtr::basename() const {
KJ_REQUIRE(parts.size() > 0, "root path has no basename");
return PathPtr(parts.slice(parts.size() - 1, parts.size()));
}
Path Path::basename() && {
KJ_REQUIRE(parts.size() > 0, "root path has no basename");
auto newParts = kj::heapArrayBuilder<String>(1);
newParts.add(kj::mv(parts[parts.size() - 1]));
return Path(newParts.finish(), ALREADY_CHECKED);
}
PathPtr PathPtr::parent() const {
KJ_REQUIRE(parts.size() > 0, "root path has no parent");
return PathPtr(parts.slice(0, parts.size() - 1));
}
Path Path::parent() && {
KJ_REQUIRE(parts.size() > 0, "root path has no parent");
return Path(KJ_MAP(p, parts.slice(0, parts.size() - 1)) { return kj::mv(p); }, ALREADY_CHECKED);
}
String PathPtr::toString(bool absolute) const {
if (parts.size() == 0) {
// Special-case empty path.
return absolute ? kj::str("/") : kj::str(".");
}
size_t size = absolute + (parts.size() - 1);
for (auto& p: parts) size += p.size();
String result = kj::heapString(size);
char* ptr = result.begin();
bool leadingSlash = absolute;
for (auto& p: parts) {
if (leadingSlash) *ptr++ = '/';
leadingSlash = true;
memcpy(ptr, p.begin(), p.size());
ptr += p.size();
}
KJ_ASSERT(ptr == result.end());
return result;
}
Path Path::slice(size_t start, size_t end) && {
return Path(KJ_MAP(p, parts.slice(start, end)) { return kj::mv(p); });
}
Path PathPtr::evalWin32(StringPtr pathText) const {
Vector<String> newParts(parts.size() + Path::countPartsWin32(pathText));
for (auto& p: parts) newParts.add(heapString(p));
return Path::evalWin32Impl(kj::mv(newParts), pathText);
}
Path Path::evalWin32(StringPtr pathText) && {
Vector<String> newParts(parts.size() + countPartsWin32(pathText));
for (auto& p: parts) newParts.add(kj::mv(p));
return evalWin32Impl(kj::mv(newParts), pathText);
}
String PathPtr::toWin32String(bool absolute) const {
if (parts.size() == 0) {
// Special-case empty path.
KJ_REQUIRE(!absolute, "absolute path is missing disk designator") {
break;
}
return absolute ? kj::str("\\\\") : kj::str(".");
}
bool isUncPath = false;
if (absolute) {
if (Path::isWin32Drive(parts[0])) {
// It's a win32 drive
} else if (Path::isNetbiosName(parts[0])) {
isUncPath = true;
} else {
KJ_FAIL_REQUIRE("absolute win32 path must start with drive letter or netbios host name",
parts[0]);
}
}
size_t size = (isUncPath ? 2 : 0) + (parts.size() - 1);
for (auto& p: parts) size += p.size();
String result = heapString(size);
char* ptr = result.begin();
if (isUncPath) {
*ptr++ = '\\';
*ptr++ = '\\';
}
bool leadingSlash = false;
for (auto& p: parts) {
if (leadingSlash) *ptr++ = '\\';
leadingSlash = true;
KJ_REQUIRE(!Path::isWin32Special(p), "path cannot contain DOS reserved name", p) {
// Recover by blotting out the name with invalid characters which Win32 syscalls will reject.
for (size_t i = 0; i < p.size(); i++) {
*ptr++ = '|';
}
continue;
}
memcpy(ptr, p.begin(), p.size());
ptr += p.size();
}
KJ_ASSERT(ptr == result.end());
// Check for colons (other than in drive letter), which on NTFS would be interpreted as an
// "alternate data stream", which can lead to surprising results. If we want to support ADS, we
// should do so using an explicit API. Note that this check also prevents a relative path from
// appearing to start with a drive letter.
for (size_t i: kj::indices(result)) {
if (result[i] == ':') {
if (absolute && i == 1) {
// False alarm: this is the drive letter.
} else {
KJ_FAIL_REQUIRE(
"colons are prohibited in win32 paths to avoid triggering alterante data streams",
result) {
// Recover by using a different character which we know Win32 syscalls will reject.
result[i] = '|';
}
}
}
}
return result;
}
// -----------------------------------------------------------------------------
String Path::stripNul(String input) {
kj::Vector<char> output(input.size());
for (char c: input) {
if (c != '\0') output.add(c);
}
output.add('\0');
return String(output.releaseAsArray());
}
void Path::validatePart(StringPtr part) {
KJ_REQUIRE(part != "" && part != "." && part != "..", "invalid path component", part);
KJ_REQUIRE(strlen(part.begin()) == part.size(), "NUL character in path component", part);
KJ_REQUIRE(part.findFirst('/') == nullptr,
"'/' character in path component; did you mean to use Path::parse()?", part);
}
void Path::evalPart(Vector<String>& parts, ArrayPtr<const char> part) {
if (part.size() == 0) {
// Ignore consecutive or trailing '/'s.
} else if (part.size() == 1 && part[0] == '.') {
// Refers to current directory; ignore.
} else if (part.size() == 2 && part[0] == '.' && part [1] == '.') {
KJ_REQUIRE(parts.size() > 0, "can't use \"..\" to break out of starting directory") {
// When exceptions are disabled, ignore.
return;
}
parts.removeLast();
} else {
auto str = heapString(part);
KJ_REQUIRE(strlen(str.begin()) == str.size(), "NUL character in path component", str) {
// When exceptions are disabled, strip out '\0' chars.
str = stripNul(kj::mv(str));
break;
}
parts.add(kj::mv(str));
}
}
Path Path::evalImpl(Vector<String>&& parts, StringPtr path) {
if (path.startsWith("/")) {
parts.clear();
}
size_t partStart = 0;
for (auto i: kj::indices(path)) {
if (path[i] == '/') {
evalPart(parts, path.slice(partStart, i));
partStart = i + 1;
}
}
evalPart(parts, path.slice(partStart));
return Path(parts.releaseAsArray(), Path::ALREADY_CHECKED);
}
Path Path::evalWin32Impl(Vector<String>&& parts, StringPtr path) {
// Convert all forward slashes to backslashes.
String ownPath;
if (path.findFirst('/') != nullptr) {
ownPath = heapString(path);
for (char& c: ownPath) {
if (c == '/') c = '\\';
}
path = ownPath;
}
// Interpret various forms of absolute paths.
if (path.startsWith("\\\\")) {
// UNC path.
path = path.slice(2);
// This path is absolute. The first component is a server name.
parts.clear();
} else if (path.startsWith("\\")) {
// Path is relative to the current drive / network share.
if (parts.size() >= 1 && isWin32Drive(parts[0])) {
// Leading \ interpreted as root of current drive.
parts.truncate(1);
} else if (parts.size() >= 2) {
// Leading \ interpreted as root of current network share (which is indicated by the first
// *two* components of the path).
parts.truncate(2);
} else {
KJ_FAIL_REQUIRE("must specify drive letter", path) {
// Recover by assuming C drive.
parts.clear();
parts.add(kj::str("c:"));
break;
}
}
} else if ((path.size() == 2 || (path.size() > 2 && path[2] == '\\')) &&
isWin32Drive(path.slice(0, 2))) {
// Starts with a drive letter.
parts.clear();
}
size_t partStart = 0;
for (auto i: kj::indices(path)) {
if (path[i] == '\\') {
evalPart(parts, path.slice(partStart, i));
partStart = i + 1;
}
}
evalPart(parts, path.slice(partStart));
return Path(parts.releaseAsArray(), Path::ALREADY_CHECKED);
}
size_t Path::countParts(StringPtr path) {
size_t result = 1;
for (char c: path) {
result += (c == '/');
}
return result;
}
size_t Path::countPartsWin32(StringPtr path) {
size_t result = 1;
for (char c: path) {
result += (c == '/' || c == '\\');
}
return result;
}
bool Path::isWin32Drive(ArrayPtr<const char> part) {
return part.size() == 2 && part[1] == ':' &&
(('a' <= part[0] && part[0] <= 'z') || ('A' <= part[0] && part[0] <= 'Z'));
}
bool Path::isNetbiosName(ArrayPtr<const char> part) {
// Characters must be alphanumeric or '.' or '-'.
for (char c: part) {
if (c != '.' && c != '-' &&
(c < 'a' || 'z' < c) &&
(c < 'A' || 'Z' < c) &&
(c < '0' || '9' < c)) {
return false;
}
}
// Can't be empty nor start or end with a '.' or a '-'.
return part.size() > 0 &&
part[0] != '.' && part[0] != '-' &&
part[part.size() - 1] != '.' && part[part.size() - 1] != '-';
}
bool Path::isWin32Special(StringPtr part) {
bool isNumbered;
if (part.size() == 3 || (part.size() > 3 && part[3] == '.')) {
// Filename is three characters or three characters followed by an extension.
isNumbered = false;
} else if ((part.size() == 4 || (part.size() > 4 && part[4] == '.')) &&
'1' <= part[3] && part[3] <= '9') {
// Filename is four characters or four characters followed by an extension, and the fourth
// character is a nonzero digit.
isNumbered = true;
} else {
return false;
}
// OK, this could be a Win32 special filename. We need to match the first three letters against
// the list of specials, case-insensitively.
char tmp[4];
memcpy(tmp, part.begin(), 3);
tmp[3] = '\0';
for (char& c: tmp) {
if ('A' <= c && c <= 'Z') {
c += 'a' - 'A';
}
}
StringPtr str(tmp, 3);
if (isNumbered) {
// Specials that are followed by a digit.
return str == "com" || str == "lpt";
} else {
// Specials that are not followed by a digit.
return str == "con" || str == "prn" || str == "aux" || str == "nul";
}
}
// =======================================================================================
String ReadableFile::readAllText() {
String result = heapString(stat().size);
size_t n = read(0, result.asBytes());
if (n < result.size()) {
// Apparently file was truncated concurrently. Reduce to new size to match.
result = heapString(result.slice(0, n));
}
return result;
}
Array<byte> ReadableFile::readAllBytes() {
Array<byte> result = heapArray<byte>(stat().size);
size_t n = read(0, result.asBytes());
if (n < result.size()) {
// Apparently file was truncated concurrently. Reduce to new size to match.
result = heapArray(result.slice(0, n));
}
return result;
}
void File::writeAll(ArrayPtr<const byte> bytes) {
truncate(0);
write(0, bytes);
}
void File::writeAll(StringPtr text) {
writeAll(text.asBytes());
}
size_t File::copy(uint64_t offset, ReadableFile& from, uint64_t fromOffset, uint64_t size) {
byte buffer[8192];
size_t result = 0;
while (size > 0) {
size_t n = from.read(fromOffset, kj::arrayPtr(buffer, kj::min(sizeof(buffer), size)));
write(offset, arrayPtr(buffer, n));
result += n;
if (n < sizeof(buffer)) {
// Either we copied the amount requested or we hit EOF.
break;
}
fromOffset += n;
offset += n;
size -= n;
}
return result;
}
FsNode::Metadata ReadableDirectory::lstat(PathPtr path) {
KJ_IF_MAYBE(meta, tryLstat(path)) {
return *meta;
} else {
KJ_FAIL_REQUIRE("no such file", path) { break; }
return FsNode::Metadata();
}
}
Own<ReadableFile> ReadableDirectory::openFile(PathPtr path) {
KJ_IF_MAYBE(file, tryOpenFile(path)) {
return kj::mv(*file);
} else {
KJ_FAIL_REQUIRE("no such directory", path) { break; }
return newInMemoryFile(nullClock());
}
}
Own<ReadableDirectory> ReadableDirectory::openSubdir(PathPtr path) {
KJ_IF_MAYBE(dir, tryOpenSubdir(path)) {
return kj::mv(*dir);
} else {
KJ_FAIL_REQUIRE("no such file or directory", path) { break; }
return newInMemoryDirectory(nullClock());
}
}
String ReadableDirectory::readlink(PathPtr path) {
KJ_IF_MAYBE(p, tryReadlink(path)) {
return kj::mv(*p);
} else {
KJ_FAIL_REQUIRE("not a symlink", path) { break; }
return kj::str(".");
}
}
Own<File> Directory::openFile(PathPtr path, WriteMode mode) {
KJ_IF_MAYBE(f, tryOpenFile(path, mode)) {
return kj::mv(*f);
} else if (has(mode, WriteMode::CREATE) && !has(mode, WriteMode::MODIFY)) {
KJ_FAIL_REQUIRE("file already exists", path) { break; }
} else if (has(mode, WriteMode::MODIFY) && !has(mode, WriteMode::CREATE)) {
KJ_FAIL_REQUIRE("file does not exist", path) { break; }
} else if (!has(mode, WriteMode::MODIFY) && !has(mode, WriteMode::CREATE)) {
KJ_FAIL_ASSERT("neither WriteMode::CREATE nor WriteMode::MODIFY was given", path) { break; }
} else {
// Shouldn't happen.
KJ_FAIL_ASSERT("tryOpenFile() returned null despite no preconditions", path) { break; }
}
return newInMemoryFile(nullClock());
}
Own<AppendableFile> Directory::appendFile(PathPtr path, WriteMode mode) {
KJ_IF_MAYBE(f, tryAppendFile(path, mode)) {
return kj::mv(*f);
} else if (has(mode, WriteMode::CREATE) && !has(mode, WriteMode::MODIFY)) {
KJ_FAIL_REQUIRE("file already exists", path) { break; }
} else if (has(mode, WriteMode::MODIFY) && !has(mode, WriteMode::CREATE)) {
KJ_FAIL_REQUIRE("file does not exist", path) { break; }
} else if (!has(mode, WriteMode::MODIFY) && !has(mode, WriteMode::CREATE)) {
KJ_FAIL_ASSERT("neither WriteMode::CREATE nor WriteMode::MODIFY was given", path) { break; }
} else {
// Shouldn't happen.
KJ_FAIL_ASSERT("tryAppendFile() returned null despite no preconditions", path) { break; }
}
return newFileAppender(newInMemoryFile(nullClock()));
}
Own<Directory> Directory::openSubdir(PathPtr path, WriteMode mode) {
KJ_IF_MAYBE(f, tryOpenSubdir(path, mode)) {
return kj::mv(*f);
} else if (has(mode, WriteMode::CREATE) && !has(mode, WriteMode::MODIFY)) {
KJ_FAIL_REQUIRE("directory already exists", path) { break; }
} else if (has(mode, WriteMode::MODIFY) && !has(mode, WriteMode::CREATE)) {
KJ_FAIL_REQUIRE("directory does not exist", path) { break; }
} else if (!has(mode, WriteMode::MODIFY) && !has(mode, WriteMode::CREATE)) {
KJ_FAIL_ASSERT("neither WriteMode::CREATE nor WriteMode::MODIFY was given", path) { break; }
} else {
// Shouldn't happen.
KJ_FAIL_ASSERT("tryOpenSubdir() returned null despite no preconditions", path) { break; }
}
return newInMemoryDirectory(nullClock());
}
void Directory::symlink(PathPtr linkpath, StringPtr content, WriteMode mode) {
if (!trySymlink(linkpath, content, mode)) {
if (has(mode, WriteMode::CREATE)) {
KJ_FAIL_REQUIRE("path already exsits", linkpath) { break; }
} else {
// Shouldn't happen.
KJ_FAIL_ASSERT("symlink() returned null despite no preconditions", linkpath) { break; }
}
}
}
void Directory::transfer(PathPtr toPath, WriteMode toMode,
Directory& fromDirectory, PathPtr fromPath,
TransferMode mode) {
if (!tryTransfer(toPath, toMode, fromDirectory, fromPath, mode)) {
if (has(toMode, WriteMode::CREATE)) {
KJ_FAIL_REQUIRE("toPath already exists or fromPath doesn't exist", toPath, fromPath) {
break;
}
} else {
KJ_FAIL_ASSERT("fromPath doesn't exist", fromPath) { break; }
}
}
}
static void copyContents(Directory& to, ReadableDirectory& from);
static bool tryCopyDirectoryEntry(Directory& to, PathPtr toPath, WriteMode toMode,
ReadableDirectory& from, PathPtr fromPath,
FsNode::Type type, bool atomic) {
// TODO(cleanup): Make this reusable?
switch (type) {
case FsNode::Type::FILE: {
KJ_IF_MAYBE(fromFile, from.tryOpenFile(fromPath)) {
if (atomic) {
auto replacer = to.replaceFile(toPath, toMode);
replacer->get().copy(0, **fromFile, 0, kj::maxValue);
return replacer->tryCommit();
} else KJ_IF_MAYBE(toFile, to.tryOpenFile(toPath, toMode)) {
toFile->get()->copy(0, **fromFile, 0, kj::maxValue);
return true;
} else {
return false;
}
} else {
// Apparently disappeared. Treat as source-doesn't-exist.
return false;
}
}
case FsNode::Type::DIRECTORY:
KJ_IF_MAYBE(fromSubdir, from.tryOpenSubdir(fromPath)) {
if (atomic) {
auto replacer = to.replaceSubdir(toPath, toMode);
copyContents(replacer->get(), **fromSubdir);
return replacer->tryCommit();
} else KJ_IF_MAYBE(toSubdir, to.tryOpenSubdir(toPath, toMode)) {
copyContents(**toSubdir, **fromSubdir);
return true;
} else {
return false;
}
} else {
// Apparently disappeared. Treat as source-doesn't-exist.
return false;
}
case FsNode::Type::SYMLINK:
KJ_IF_MAYBE(content, from.tryReadlink(fromPath)) {
return to.trySymlink(toPath, *content, toMode);
} else {
// Apparently disappeared. Treat as source-doesn't-exist.
return false;
}
break;
default:
// Note: Unclear whether it's better to throw an error here or just ignore it / log a
// warning. Can reconsider when we see an actual use case.
KJ_FAIL_REQUIRE("can only copy files, directories, and symlinks", fromPath) {
return false;
}
}
}
static void copyContents(Directory& to, ReadableDirectory& from) {
for (auto& entry: from.listEntries()) {
Path subPath(kj::mv(entry.name));
tryCopyDirectoryEntry(to, subPath, WriteMode::CREATE, from, subPath, entry.type, false);
}
}
bool Directory::tryTransfer(PathPtr toPath, WriteMode toMode,
Directory& fromDirectory, PathPtr fromPath,
TransferMode mode) {
KJ_REQUIRE(toPath.size() > 0, "can't replace self") { return false; }
// First try reversing.
KJ_IF_MAYBE(result, fromDirectory.tryTransferTo(*this, toPath, toMode, fromPath, mode)) {
return *result;
}
switch (mode) {
case TransferMode::COPY:
KJ_IF_MAYBE(meta, fromDirectory.tryLstat(fromPath)) {
return tryCopyDirectoryEntry(*this, toPath, toMode, fromDirectory,
fromPath, meta->type, true);
} else {
// Source doesn't exist.
return false;
}
case TransferMode::MOVE:
// Implement move as copy-then-delete.
if (!tryTransfer(toPath, toMode, fromDirectory, fromPath, TransferMode::COPY)) {
return false;
}
fromDirectory.remove(fromPath);
return true;
case TransferMode::LINK:
KJ_FAIL_REQUIRE("can't link across different Directory implementations") { return false; }
}
}
Maybe<bool> Directory::tryTransferTo(Directory& toDirectory, PathPtr toPath, WriteMode toMode,
PathPtr fromPath, TransferMode mode) {
return nullptr;
}
void Directory::remove(PathPtr path) {
if (!tryRemove(path)) {
KJ_FAIL_REQUIRE("path to remove doesn't exist", path) { break; }
}
}
void Directory::commitFailed(WriteMode mode) {
if (has(mode, WriteMode::CREATE) && !has(mode, WriteMode::MODIFY)) {
KJ_FAIL_REQUIRE("replace target already exists") { break; }
} else if (has(mode, WriteMode::MODIFY) && !has(mode, WriteMode::CREATE)) {
KJ_FAIL_REQUIRE("replace target does not exist") { break; }
} else if (!has(mode, WriteMode::MODIFY) && !has(mode, WriteMode::CREATE)) {
KJ_FAIL_ASSERT("neither WriteMode::CREATE nor WriteMode::MODIFY was given") { break; }
} else {
KJ_FAIL_ASSERT("tryCommit() returned null despite no preconditions") { break; }
}
}
// =======================================================================================
namespace {
class InMemoryFile final: public File, public Refcounted {
public:
InMemoryFile(Clock& clock): clock(clock), lastModified(clock.now()) {}
Own<FsNode> cloneFsNode() override {
return addRef(*this);
}
Maybe<int> getFd() override {
return nullptr;
}
Metadata stat() override {
return Metadata { Type::FILE, size, size, lastModified, 1 };
}
void sync() override {}
void datasync() override {}
// no-ops
size_t read(uint64_t offset, ArrayPtr<byte> buffer) override {
if (offset >= size) {
// Entirely out-of-range.
return 0;
}
size_t readSize = kj::min(buffer.size(), size - offset);
memcpy(buffer.begin(), bytes.begin() + offset, readSize);
return readSize;
}
Array<const byte> mmap(uint64_t offset, uint64_t size) override {
KJ_REQUIRE(offset + size >= offset, "mmap() request overflows uint64");
ensureCapacity(offset + size);
ArrayDisposer* disposer = new MmapDisposer(addRef(*this));
return Array<const byte>(bytes.begin() + offset, size, *disposer);
}
Array<byte> mmapPrivate(uint64_t offset, uint64_t size) override {
// Return a copy.
// Allocate exactly the size requested.
auto result = heapArray<byte>(size);
// Use read() to fill it.
size_t actual = read(offset, result);
// Ignore the rest.
if (actual < size) {
memset(result.begin() + actual, 0, size - actual);
}
return result;
}
void write(uint64_t offset, ArrayPtr<const byte> data) override {
if (data.size() == 0) return;
modified();
uint64_t end = offset + data.size();
KJ_REQUIRE(end >= offset, "write() request overflows uint64");
ensureCapacity(end);
size = kj::max(size, end);
memcpy(bytes.begin() + offset, data.begin(), data.size());
}
void zero(uint64_t offset, uint64_t zeroSize) override {
if (zeroSize == 0) return;
modified();
uint64_t end = offset + zeroSize;
KJ_REQUIRE(end >= offset, "zero() request overflows uint64");
ensureCapacity(end);
size = kj::max(size, end);
memset(bytes.begin() + offset, 0, zeroSize);
}
void truncate(uint64_t newSize) override {
if (newSize < size) {
modified();
memset(bytes.begin() + newSize, 0, size - newSize);
size = newSize;
} else if (newSize > size) {
modified();
ensureCapacity(newSize);
size = newSize;
}
}
Own<WritableFileMapping> mmapWritable(uint64_t offset, uint64_t size) override {
uint64_t end = offset + size;
KJ_REQUIRE(end >= offset, "mmapWritable() request overflows uint64");
ensureCapacity(end);
return heap<WritableFileMappingImpl>(addRef(*this), bytes.slice(offset, end));
}
size_t copy(uint64_t offset, ReadableFile& from,
uint64_t fromOffset, uint64_t copySize) override {
size_t fromFileSize = from.stat().size;
if (fromFileSize <= fromOffset) return 0;
// Clamp size to EOF.
copySize = kj::min(copySize, fromFileSize - fromOffset);
if (copySize == 0) return 0;
// Allocate space for the copy.
uint64_t end = offset + copySize;
ensureCapacity(end);
// Read directly into our backing store.
size_t n = from.read(fromOffset, bytes.slice(offset, end));
size = kj::max(size, offset + n);
modified();
return n;
}
private:
Clock& clock;
Array<byte> bytes;
size_t size = 0; // bytes may be larger than this to accommodate mmaps
Date lastModified;
uint mmapCount = 0; // number of mappings outstanding
void ensureCapacity(size_t capacity) {
if (bytes.size() < capacity) {
KJ_ASSERT(mmapCount == 0,
"InMemoryFile cannot resize the file backing store while memory mappings exist.");
auto newBytes = heapArray<byte>(kj::max(capacity, bytes.size() * 2));
memcpy(newBytes.begin(), bytes.begin(), size);
memset(newBytes.begin() + size, 0, newBytes.size() - size);
bytes = kj::mv(newBytes);
}
}
void modified() {
lastModified = clock.now();
}
class MmapDisposer final: public ArrayDisposer {
public:
MmapDisposer(Own<InMemoryFile>&& refParam): ref(kj::mv(refParam)) {
++ref->mmapCount;
}
~MmapDisposer() noexcept(false) {
--ref->mmapCount;
}
void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount,
size_t capacity, void (*destroyElement)(void*)) const override {
delete this;
}
private:
Own<InMemoryFile> ref;
};
class WritableFileMappingImpl final: public WritableFileMapping {
public:
WritableFileMappingImpl(Own<InMemoryFile>&& refParam, ArrayPtr<byte> range)
: ref(kj::mv(refParam)), range(range) {
++ref->mmapCount;
}
~WritableFileMappingImpl() noexcept(false) {
--ref->mmapCount;
}
ArrayPtr<byte> get() override {
return range;
}
void changed(ArrayPtr<byte> slice) override {
ref->modified();
}
void sync(ArrayPtr<byte> slice) override {
ref->modified();
}
private:
Own<InMemoryFile> ref;
ArrayPtr<byte> range;
};
};
// -----------------------------------------------------------------------------
class InMemoryDirectory final: public Directory, public Refcounted {
public:
InMemoryDirectory(Clock& clock)
: clock(clock), lastModified(clock.now()) {}
Own<FsNode> cloneFsNode() override {
return addRef(*this);
}
Maybe<int> getFd() override {
return nullptr;
}
Metadata stat() override {
return Metadata { Type::DIRECTORY, 0, 0, lastModified, 1 };
}
void sync() override {}
void datasync() override {}
// no-ops
Array<String> listNames() override {
return KJ_MAP(e, entries) { return heapString(e.first); };
}
Array<Entry> listEntries() override {
return KJ_MAP(e, entries) {
FsNode::Type type;
if (e.second.node.is<SymlinkNode>()) {
type = FsNode::Type::SYMLINK;
} else if (e.second.node.is<FileNode>()) {
type = FsNode::Type::FILE;
} else {
KJ_ASSERT(e.second.node.is<DirectoryNode>());
type = FsNode::Type::DIRECTORY;
}
return Entry { type, heapString(e.first) };
};
}
bool exists(PathPtr path) override {
if (path.size() == 0) {
return true;
} else if (path.size() == 1) {
KJ_IF_MAYBE(entry, tryGetEntry(path[0])) {
return exists(*entry);
} else {
return false;
}
} else {
KJ_IF_MAYBE(subdir, tryGetParent(path[0])) {
return subdir->get()->exists(path.slice(1, path.size()));
} else {
return false;
}
}
}
Maybe<FsNode::Metadata> tryLstat(PathPtr path) override {
if (path.size() == 0) {
return stat();
} else if (path.size() == 1) {
KJ_IF_MAYBE(entry, tryGetEntry(path[0])) {
if (entry->node.is<FileNode>()) {
return entry->node.get<FileNode>().file->stat();
} else if (entry->node.is<DirectoryNode>()) {
return entry->node.get<DirectoryNode>().directory->stat();
} else if (entry->node.is<SymlinkNode>()) {
auto& link = entry->node.get<SymlinkNode>();
return FsNode::Metadata { FsNode::Type::SYMLINK, 0, 0, link.lastModified, 1 };
} else {
KJ_FAIL_ASSERT("unknown node type") { return nullptr; }
}
} else {
return nullptr;
}
} else {
KJ_IF_MAYBE(subdir, tryGetParent(path[0])) {
return subdir->get()->tryLstat(path.slice(1, path.size()));
} else {
return nullptr;
}
}
}
Maybe<Own<ReadableFile>> tryOpenFile(PathPtr path) override {
if (path.size() == 0) {
KJ_FAIL_REQUIRE("not a file") { return nullptr; }
} else if (path.size() == 1) {
KJ_IF_MAYBE(entry, tryGetEntry(path[0])) {
return asFile(*entry);
} else {
return nullptr;
}
} else {
KJ_IF_MAYBE(subdir, tryGetParent(path[0])) {
return subdir->get()->tryOpenFile(path.slice(1, path.size()));
} else {
return nullptr;
}
}
}
Maybe<Own<ReadableDirectory>> tryOpenSubdir(PathPtr path) override {
if (path.size() == 0) {
return clone();
} else if (path.size() == 1) {
KJ_IF_MAYBE(entry, tryGetEntry(path[0])) {
return asDirectory(*entry);
} else {