Repository navigation
Expand file tree
/
Copy pathPoggetHistoryFileSystem.hpp
More file actions
1638 lines (1511 loc) · 70.7 KB
/
Copy pathPoggetHistoryFileSystem.hpp
File metadata and controls
1638 lines (1511 loc) · 70.7 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
#pragma once
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cwctype>
#include <filesystem>
#include <fstream>
#include <functional>
#include <limits>
#include <string>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "PoggetLogs.hpp"
#ifdef _WIN32
#include <windows.h>
#include <shellapi.h>
#undef min
#undef max
#endif
namespace PoggetCore::HistoryFileSystem {
inline constexpr std::uintmax_t FullContentVerificationLimit = 64ULL * 1024ULL * 1024ULL;
inline constexpr std::uintmax_t SampleVerificationBlockSize = 1ULL * 1024ULL * 1024ULL;
inline constexpr size_t SampleVerificationBlockCount = 8;
inline constexpr size_t DeleteUndoPromptItemThreshold = 128;
inline constexpr std::uintmax_t DeleteUndoPromptByteThreshold =
1ULL * 1024ULL * 1024ULL * 1024ULL;
inline constexpr wchar_t OperationStorageDirectoryName[] = L".pogget_operations";
inline constexpr wchar_t LegacyUndoStorageDirectoryName[] = L".pogget_undo";
struct Result {
bool success = false;
std::error_code error;
std::wstring context;
// The requested move published a verified destination, but the source
// could not be removed. Callers must treat the result as a copy for
// history/UI purposes and may ask the user to delete the source.
bool sourceRetained = false;
// A shared-profile destination rejected creation/write access. UI
// callers may offer a writable per-user desktop destination instead.
bool protectedDestinationDenied = false;
explicit operator bool() const noexcept { return success; }
};
struct MoveStep {
std::filesystem::path source;
std::filesystem::path destination;
};
struct DestructiveRequest {
std::filesystem::path source;
// When supplied, the source must be an immediate child of this directory.
// UI surfaces use this as a final scope boundary for delete/recycle actions.
std::filesystem::path requiredParent;
};
enum class PathPresence {
Missing,
Present,
Inaccessible
};
struct PathInspection {
PathPresence presence = PathPresence::Missing;
std::filesystem::file_status status{};
std::error_code error;
};
struct DeleteUndoRiskPolicy {
size_t itemCountThreshold = DeleteUndoPromptItemThreshold;
std::uintmax_t knownBytesThreshold = DeleteUndoPromptByteThreshold;
};
struct DeleteUndoRiskAssessment {
bool promptRecommended = false;
bool itemCountThresholdReached = false;
bool containsDirectory = false;
bool metadataUnavailable = false;
size_t itemCount = 0;
size_t inspectedItemCount = 0;
std::uintmax_t knownBytes = 0;
};
struct RestoreRequest {
std::filesystem::path source;
std::filesystem::path preferredDestination;
};
struct RestoreItemResult {
std::filesystem::path source;
std::filesystem::path preferredDestination;
std::filesystem::path finalDestination;
Result result;
bool rolledBack = false;
};
struct RestoreBatchResult {
bool success = false;
bool fullyRolledBack = true;
std::wstring context;
std::vector<RestoreItemResult> items;
explicit operator bool() const noexcept { return success; }
};
enum class RestoreFailurePolicy {
RollBackCommittedItems,
KeepCommittedItems
};
inline Result AuditedResult(
FileOperationType operation,
const std::filesystem::path& source,
const std::filesystem::path& destination,
Result result) noexcept {
PoggetLogger::AuditFileOperation(
operation, source, destination, result.success, result.error, result.context);
if (operation == FileOperationType::Delete || operation == FileOperationType::Recycle) {
try {
const std::wstring action = operation == FileOperationType::Recycle
? L"Recycle"
: L"Permanent delete";
PoggetLogger::Log(
L"FileOperation",
result.success ? L"SUCCESS" : L"FAILURE",
action + (result.success ? L" succeeded" : L" failed") +
L": source=\"" + source.wstring() +
L"\" destination=\"" + destination.wstring() +
L"\" error=" + std::to_wstring(result.error.value()) +
L" context=\"" + result.context + L"\"");
}
catch (...) {
// Result logging must never alter the file-operation outcome.
}
}
return result;
}
inline std::wstring ComparablePath(const std::filesystem::path& path) {
if (path.empty()) return {};
std::error_code ec;
auto normalized = std::filesystem::absolute(path, ec).lexically_normal().wstring();
if (ec) normalized = path.lexically_normal().wstring();
#ifdef _WIN32
std::transform(normalized.begin(), normalized.end(), normalized.begin(), ::towlower);
#endif
return normalized;
}
inline std::filesystem::path FileSystemAccessPath(
const std::filesystem::path& path) {
#ifdef _WIN32
if (path.empty()) return path;
const auto original = path.wstring();
if (original.starts_with(L"\\\\?\\")) return path;
std::error_code ec;
auto value = std::filesystem::absolute(path, ec).lexically_normal().wstring();
if (ec) value = path.lexically_normal().wstring();
const std::filesystem::path normalized(value);
if (normalized == normalized.root_path()) return normalized;
if (value.starts_with(L"\\\\")) {
return std::filesystem::path(L"\\\\?\\UNC\\" + value.substr(2));
}
return std::filesystem::path(L"\\\\?\\" + value);
#else
return path;
#endif
}
inline PathInspection InspectPath(const std::filesystem::path& path) noexcept {
if (path.empty()) {
return { PathPresence::Missing, {},
std::make_error_code(std::errc::invalid_argument) };
}
std::error_code ec;
const auto status = std::filesystem::symlink_status(
FileSystemAccessPath(path), ec);
if (!ec) {
return {
status.type() == std::filesystem::file_type::not_found
? PathPresence::Missing
: PathPresence::Present,
status,
{}
};
}
if (ec == std::errc::no_such_file_or_directory ||
ec == std::errc::not_a_directory) {
return { PathPresence::Missing, {}, {} };
}
return { PathPresence::Inaccessible, {}, ec };
}
inline bool Exists(const std::filesystem::path& path) noexcept {
return InspectPath(path).presence == PathPresence::Present;
}
/*
* Deletion prompts must never recursively enumerate a directory on the UI
* thread. Large batches are classified by count alone. Small batches only
* inspect top-level metadata and stop as soon as a warning condition is met.
*/
inline DeleteUndoRiskAssessment AssessDeleteUndoRisk(
const std::vector<std::filesystem::path>& paths,
const DeleteUndoRiskPolicy& policy = {}) noexcept {
DeleteUndoRiskAssessment assessment;
assessment.itemCount = paths.size();
if (policy.itemCountThreshold > 0 &&
paths.size() >= policy.itemCountThreshold) {
assessment.promptRecommended = true;
assessment.itemCountThresholdReached = true;
return assessment;
}
for (const auto& path : paths) {
++assessment.inspectedItemCount;
const auto inspection = InspectPath(path);
if (inspection.presence != PathPresence::Present) {
assessment.promptRecommended = true;
assessment.metadataUnavailable = true;
return assessment;
}
if (std::filesystem::is_directory(inspection.status)) {
assessment.promptRecommended = true;
assessment.containsDirectory = true;
return assessment;
}
if (!std::filesystem::is_regular_file(inspection.status)) {
assessment.promptRecommended = true;
assessment.metadataUnavailable = true;
return assessment;
}
std::error_code sizeError;
const auto size = std::filesystem::file_size(
FileSystemAccessPath(path), sizeError);
if (sizeError) {
assessment.promptRecommended = true;
assessment.metadataUnavailable = true;
return assessment;
}
if (policy.knownBytesThreshold > 0 &&
(size >= policy.knownBytesThreshold ||
assessment.knownBytes >= policy.knownBytesThreshold - size)) {
assessment.knownBytes = policy.knownBytesThreshold;
assessment.promptRecommended = true;
return assessment;
}
assessment.knownBytes += size;
}
return assessment;
}
inline Result EnsureDirectoryExists(const std::filesystem::path& path) noexcept {
if (path.empty()) {
return { false, std::make_error_code(std::errc::invalid_argument),
L"empty directory path" };
}
const auto inspection = InspectPath(path);
if (inspection.presence == PathPresence::Inaccessible) {
return { false, inspection.error, L"checking directory" };
}
if (inspection.presence == PathPresence::Present) {
std::error_code ec;
const bool isDirectory = std::filesystem::is_directory(
FileSystemAccessPath(path), ec);
if (ec) return { false, ec, L"checking directory type" };
if (!isDirectory) {
return { false, std::make_error_code(std::errc::not_a_directory),
L"path exists but is not a directory" };
}
return { true, {}, L"" };
}
std::error_code ec;
std::filesystem::create_directories(FileSystemAccessPath(path), ec);
if (ec) return { false, ec, L"creating directory" };
return { true, {}, L"" };
}
inline bool IsPathInside(
const std::filesystem::path& candidate,
const std::filesystem::path& parent) {
auto candidateKey = ComparablePath(candidate);
auto parentKey = ComparablePath(parent);
if (candidateKey.empty() || parentKey.empty() || candidateKey == parentKey) return false;
if (parentKey.back() != L'\\' && parentKey.back() != L'/') {
parentKey.push_back(std::filesystem::path::preferred_separator);
}
return candidateKey.starts_with(parentKey);
}
inline bool IsWindowsSharedProfilePath(
const std::filesystem::path& path) noexcept {
#ifdef _WIN32
if (path.empty()) return false;
std::error_code ec;
auto absolute = std::filesystem::absolute(path, ec).lexically_normal();
if (ec) absolute = path.lexically_normal();
std::wstring previous;
for (const auto& component : absolute) {
std::wstring current = component.wstring();
std::transform(current.begin(), current.end(), current.begin(), ::towlower);
if (previous == L"users" &&
(current == L"public" || current == L"default")) {
return true;
}
previous = std::move(current);
}
#else
(void)path;
#endif
return false;
}
inline Result ValidateDestructiveBatch(
const std::vector<DestructiveRequest>& requests) {
if (requests.empty()) return { true, {}, L"nothing to remove" };
std::unordered_set<std::wstring> sourceKeys;
std::vector<std::filesystem::path> sources;
sources.reserve(requests.size());
for (const auto& request : requests) {
if (request.source.empty()) {
return { false, std::make_error_code(std::errc::invalid_argument),
L"destructive batch contains an empty source path" };
}
std::error_code ec;
const auto source = std::filesystem::absolute(request.source, ec).lexically_normal();
if (ec) return { false, ec, L"resolving destructive source path" };
if (source == source.root_path()) {
return { false, std::make_error_code(std::errc::operation_not_permitted),
L"refusing to remove a file-system root" };
}
const auto inspection = InspectPath(source);
if (inspection.presence == PathPresence::Inaccessible) {
return { false, inspection.error, L"checking destructive source: " + source.wstring() };
}
if (inspection.presence == PathPresence::Missing) {
return { false, std::make_error_code(std::errc::no_such_file_or_directory),
L"destructive source does not exist: " + source.wstring() };
}
if (!request.requiredParent.empty()) {
const auto requiredParent =
std::filesystem::absolute(request.requiredParent, ec).lexically_normal();
if (ec) return { false, ec, L"resolving destructive scope directory" };
if (ComparablePath(source.parent_path()) != ComparablePath(requiredParent)) {
return { false, std::make_error_code(std::errc::operation_not_permitted),
L"destructive source is outside its required parent: " + source.wstring() };
}
const auto parentInspection = InspectPath(requiredParent);
if (parentInspection.presence != PathPresence::Present ||
!std::filesystem::is_directory(parentInspection.status)) {
return { false,
parentInspection.presence == PathPresence::Inaccessible
? parentInspection.error
: std::make_error_code(std::errc::not_a_directory),
L"destructive scope directory is unavailable: " +
requiredParent.wstring() };
}
}
const auto key = ComparablePath(source);
if (!sourceKeys.insert(key).second) {
return { false, std::make_error_code(std::errc::invalid_argument),
L"destructive batch contains the same source more than once: " +
source.wstring() };
}
sources.push_back(source);
}
for (std::size_t left = 0; left < sources.size(); ++left) {
for (std::size_t right = left + 1; right < sources.size(); ++right) {
if (IsPathInside(sources[left], sources[right]) ||
IsPathInside(sources[right], sources[left])) {
return { false, std::make_error_code(std::errc::invalid_argument),
L"destructive batch contains overlapping parent and child sources" };
}
}
}
return { true, {}, L"" };
}
inline bool IsHistoryStorageRootName(std::wstring name) {
#ifdef _WIN32
std::transform(name.begin(), name.end(), name.begin(), ::towlower);
#endif
return name == OperationStorageDirectoryName ||
name == LegacyUndoStorageDirectoryName;
}
inline bool IsManagedHistoryPath(const std::filesystem::path& path) {
if (path.empty()) return false;
std::vector<std::wstring> components;
for (const auto& component : path.lexically_normal()) {
auto value = component.wstring();
#ifdef _WIN32
std::transform(value.begin(), value.end(), value.begin(), ::towlower);
#endif
components.push_back(std::move(value));
}
for (size_t index = 0; index < components.size(); ++index) {
if (IsHistoryStorageRootName(components[index]) ||
components[index] == L"poggetundo") {
return true;
}
if (index >= 2 &&
(components[index] == L"operations" || components[index] == L"undo") &&
components[index - 1] == L".temp" &&
components[index - 2] == L".data") {
return true;
}
}
return false;
}
inline bool IsManagedHistoryPayloadPath(const std::filesystem::path& path) {
if (path.empty()) return false;
std::vector<std::wstring> components;
for (const auto& component : path.lexically_normal()) {
auto value = component.wstring();
#ifdef _WIN32
std::transform(value.begin(), value.end(), value.begin(), ::towlower);
#endif
components.push_back(std::move(value));
}
for (size_t index = 0; index < components.size(); ++index) {
const bool namedRoot = IsHistoryStorageRootName(components[index]) ||
components[index] == L"poggetundo";
const bool fallbackRoot = index >= 2 &&
(components[index] == L"operations" || components[index] == L"undo") &&
components[index - 1] == L".temp" &&
components[index - 2] == L".data";
if ((namedRoot || fallbackRoot) && index + 2 < components.size()) {
return true; // storage root / process session / payload
}
}
return false;
}
inline bool EquivalentFileContents(
const std::filesystem::path& left,
const std::filesystem::path& right,
bool verifyContent = false) {
std::error_code ec;
const auto leftAccess = FileSystemAccessPath(left);
const auto rightAccess = FileSystemAccessPath(right);
const auto leftSize = std::filesystem::file_size(leftAccess, ec);
if (ec) return false;
const auto rightSize = std::filesystem::file_size(rightAccess, ec);
if (ec || leftSize != rightSize) return false;
if (!verifyContent) return true;
std::ifstream leftStream(leftAccess, std::ios::binary);
std::ifstream rightStream(rightAccess, std::ios::binary);
if (!leftStream.is_open() || !rightStream.is_open()) return false;
std::vector<char> leftBuffer(1024 * 1024);
std::vector<char> rightBuffer(1024 * 1024);
auto compareRange = [&](std::uintmax_t offset, std::uintmax_t length) {
if (offset > static_cast<std::uintmax_t>(std::numeric_limits<std::streamoff>::max())) {
return false;
}
leftStream.clear();
rightStream.clear();
leftStream.seekg(static_cast<std::streamoff>(offset));
rightStream.seekg(static_cast<std::streamoff>(offset));
if (!leftStream.good() || !rightStream.good()) return false;
while (length > 0) {
const auto chunk = static_cast<std::streamsize>(
std::min<std::uintmax_t>(length, leftBuffer.size()));
leftStream.read(leftBuffer.data(), chunk);
rightStream.read(rightBuffer.data(), chunk);
if (leftStream.gcount() != chunk || rightStream.gcount() != chunk ||
!std::equal(leftBuffer.begin(), leftBuffer.begin() + chunk, rightBuffer.begin())) {
return false;
}
length -= static_cast<std::uintmax_t>(chunk);
}
return true;
};
if (leftSize <= FullContentVerificationLimit) {
return compareRange(0, leftSize);
}
// Large files are sampled after the operating-system copy has completed
// successfully. This keeps verification bounded while still checking the
// beginning, end, and evenly distributed regions of the copied payload.
const auto blockSize = (std::min)(leftSize, SampleVerificationBlockSize);
const auto maxOffset = leftSize - blockSize;
const auto intervals = static_cast<std::uintmax_t>(SampleVerificationBlockCount - 1);
const auto quotient = maxOffset / intervals;
const auto remainder = maxOffset % intervals;
for (std::uintmax_t index = 0; index < SampleVerificationBlockCount; ++index) {
const auto offset = quotient * index + (remainder * index) / intervals;
if (!compareRange(offset, blockSize)) return false;
}
return true;
}
inline bool EquivalentSingleEntry(
const std::filesystem::path& left,
const std::filesystem::path& right,
bool verifyContent = false) {
std::error_code ec;
const auto leftAccess = FileSystemAccessPath(left);
const auto rightAccess = FileSystemAccessPath(right);
const auto leftStatus = std::filesystem::symlink_status(leftAccess, ec);
if (ec) return false;
const auto rightStatus = std::filesystem::symlink_status(rightAccess, ec);
if (ec || leftStatus.type() != rightStatus.type()) return false;
if (std::filesystem::is_regular_file(leftStatus)) {
return EquivalentFileContents(left, right, verifyContent);
}
if (std::filesystem::is_symlink(leftStatus)) {
const auto leftTarget = std::filesystem::read_symlink(leftAccess, ec);
if (ec) return false;
const auto rightTarget = std::filesystem::read_symlink(rightAccess, ec);
return !ec && leftTarget == rightTarget;
}
return std::filesystem::is_directory(leftStatus);
}
inline bool EquivalentPathContents(
const std::filesystem::path& left,
const std::filesystem::path& right,
bool verifyContent = false) {
const auto leftAccess = FileSystemAccessPath(left);
const auto rightAccess = FileSystemAccessPath(right);
if (!EquivalentSingleEntry(leftAccess, rightAccess, verifyContent)) return false;
std::error_code ec;
const auto leftStatus = std::filesystem::symlink_status(leftAccess, ec);
if (ec || !std::filesystem::is_directory(leftStatus)) return !ec;
size_t leftCount = 0;
for (std::filesystem::recursive_directory_iterator it(leftAccess, ec), end;
!ec && it != end; it.increment(ec)) {
++leftCount;
const auto relative = it->path().lexically_relative(leftAccess);
if (relative.empty() ||
!EquivalentSingleEntry(it->path(), rightAccess / relative, verifyContent)) return false;
}
if (ec) return false;
size_t rightCount = 0;
for (std::filesystem::recursive_directory_iterator it(rightAccess, ec), end;
!ec && it != end; it.increment(ec)) {
++rightCount;
}
return !ec && leftCount == rightCount;
}
/*
Validate an entire move transaction against a simulated file-system state.
This prevents a late deterministic conflict from exposing a partially applied
batch and then forcing visible rollback moves.
*/
inline Result ValidateMoveSequence(const std::vector<MoveStep>& steps) {
std::unordered_map<std::wstring, bool> simulated;
auto existsInSimulation = [&](const std::filesystem::path& path) {
const auto key = ComparablePath(path);
auto it = simulated.find(key);
if (it != simulated.end()) return it->second;
const bool exists = Exists(path);
simulated.emplace(key, exists);
return exists;
};
for (const auto& step : steps) {
if (step.source.empty() || step.destination.empty()) {
return { false, {}, L"history transaction contains an empty path" };
}
const auto sourceKey = ComparablePath(step.source);
const auto destinationKey = ComparablePath(step.destination);
if (sourceKey == destinationKey) continue;
if (!existsInSimulation(step.source)) {
return { false, {}, L"history source is missing: " + step.source.wstring() };
}
if (existsInSimulation(step.destination)) {
return { false, {}, L"history destination is occupied: " + step.destination.wstring() };
}
simulated[sourceKey] = false;
simulated[destinationKey] = true;
}
return { true, {}, L"" };
}
inline std::filesystem::path MakeUniquePath(
const std::filesystem::path& root,
const std::filesystem::path& source,
const wchar_t* purpose = L"payload",
bool preserveExtension = false) {
if (root.empty()) return {};
if (!EnsureDirectoryExists(root)) return {};
static std::atomic<unsigned long long> sequence{ 0 };
const auto ticks = static_cast<unsigned long long>(
std::chrono::steady_clock::now().time_since_epoch().count());
const auto sourceName = source.filename();
const std::wstring baseName = sourceName.empty()
? L"item"
: sourceName.wstring();
const std::wstring extension = preserveExtension
? sourceName.extension().wstring()
: L"";
const std::wstring nameWithoutExtension = preserveExtension && !extension.empty()
? sourceName.stem().wstring()
: baseName;
for (int attempt = 0; attempt < 128; ++attempt) {
const auto id = ++sequence;
auto candidate = root /
(nameWithoutExtension + L"." + purpose + L"." + std::to_wstring(ticks) +
L"." + std::to_wstring(id) + extension);
const auto inspection = InspectPath(candidate);
if (inspection.presence == PathPresence::Missing) return candidate;
if (inspection.presence == PathPresence::Inaccessible) return {};
}
return {};
}
inline Result RemovePath(const std::filesystem::path& path) {
const std::filesystem::path deletedDestination(L"<permanently-deleted>");
if (path.empty()) {
return AuditedResult(FileOperationType::Delete, path, deletedDestination,
{ false, {}, L"empty path" });
}
std::error_code ec;
const auto absolutePath = std::filesystem::absolute(path, ec).lexically_normal();
if (ec) {
return AuditedResult(FileOperationType::Delete, path, deletedDestination,
{ false, ec, L"resolving removal path" });
}
if (absolutePath == absolutePath.root_path()) {
return AuditedResult(FileOperationType::Delete, absolutePath, deletedDestination,
{ false, std::make_error_code(std::errc::operation_not_permitted),
L"refusing to remove a file-system root" });
}
const auto inspection = InspectPath(absolutePath);
if (inspection.presence == PathPresence::Inaccessible) {
return AuditedResult(FileOperationType::Delete, absolutePath, deletedDestination,
{ false, inspection.error, L"checking path" });
}
if (inspection.presence == PathPresence::Missing) {
return AuditedResult(FileOperationType::Delete, absolutePath, deletedDestination,
{ true, {}, L"already absent" });
}
ec.clear();
if (std::filesystem::is_directory(inspection.status)) {
std::filesystem::remove_all(FileSystemAccessPath(absolutePath), ec);
}
else {
std::filesystem::remove(FileSystemAccessPath(absolutePath), ec);
}
return AuditedResult(FileOperationType::Delete, absolutePath, deletedDestination,
{ !ec, ec, ec ? L"removing path" : L"" });
}
inline Result RemovePathWithRetries(
const std::filesystem::path& path,
unsigned int maxAttempts = 3,
std::chrono::milliseconds retryDelay = std::chrono::milliseconds(100)) {
if (maxAttempts == 0) maxAttempts = 1;
#ifdef _WIN32
auto clearReadOnlyAttribute = [](const std::filesystem::path& candidate) noexcept {
const auto attributes = GetFileAttributesW(candidate.c_str());
if (attributes == INVALID_FILE_ATTRIBUTES ||
(attributes & FILE_ATTRIBUTE_READONLY) == 0) {
return;
}
SetFileAttributesW(candidate.c_str(), attributes & ~FILE_ATTRIBUTE_READONLY);
};
const auto inspection = InspectPath(path);
if (inspection.presence == PathPresence::Present) {
clearReadOnlyAttribute(path);
if (std::filesystem::is_directory(inspection.status)) {
std::error_code iteratorError;
const auto options = std::filesystem::directory_options::skip_permission_denied;
for (std::filesystem::recursive_directory_iterator iterator(
path, options, iteratorError), end;
iterator != end;
iterator.increment(iteratorError)) {
if (iteratorError) {
iteratorError.clear();
continue;
}
clearReadOnlyAttribute(iterator->path());
}
}
}
#endif
Result lastResult;
for (unsigned int attempt = 0; attempt < maxAttempts; ++attempt) {
lastResult = RemovePath(path);
if (lastResult) return lastResult;
if (attempt + 1 < maxAttempts) std::this_thread::sleep_for(retryDelay);
}
if (!lastResult.context.empty()) {
lastResult.context += L" after " + std::to_wstring(maxAttempts) + L" attempts";
}
return lastResult;
}
inline Result RecyclePath(const std::filesystem::path& path) {
if (path.empty()) {
return AuditedResult(FileOperationType::Recycle, path, L"<recycle-bin>",
{ false, {}, L"empty path" });
}
std::error_code ec;
const auto absolutePath = std::filesystem::absolute(path, ec).lexically_normal();
if (ec) {
return AuditedResult(FileOperationType::Recycle, path, L"<recycle-bin>",
{ false, ec, L"resolving recycle path" });
}
if (absolutePath == absolutePath.root_path()) {
return AuditedResult(FileOperationType::Recycle, absolutePath, L"<recycle-bin>",
{ false, std::make_error_code(std::errc::operation_not_permitted),
L"refusing to recycle a file-system root" });
}
const auto sourceInspection = InspectPath(absolutePath);
if (sourceInspection.presence == PathPresence::Inaccessible) {
return AuditedResult(FileOperationType::Recycle, absolutePath, L"<recycle-bin>",
{ false, sourceInspection.error, L"checking recycle source" });
}
if (sourceInspection.presence == PathPresence::Missing) {
return AuditedResult(FileOperationType::Recycle, absolutePath, L"<recycle-bin>",
{ false, std::make_error_code(std::errc::no_such_file_or_directory),
L"source does not exist" });
}
#ifdef _WIN32
std::wstring doubleNullPath = absolutePath.wstring();
doubleNullPath.push_back(L'\0');
doubleNullPath.push_back(L'\0');
SHFILEOPSTRUCTW operation{};
operation.wFunc = FO_DELETE;
operation.pFrom = doubleNullPath.c_str();
operation.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI;
const int result = SHFileOperationW(&operation);
const auto finalInspection = InspectPath(absolutePath);
const bool success = result == 0 && !operation.fAnyOperationsAborted &&
finalInspection.presence == PathPresence::Missing;
const auto error = result != 0
? std::error_code(result, std::system_category())
: (finalInspection.presence == PathPresence::Inaccessible
? finalInspection.error
: std::error_code{});
return AuditedResult(FileOperationType::Recycle, absolutePath, L"<recycle-bin>",
{ success, error,
operation.fAnyOperationsAborted ? L"recycle operation was aborted"
: (success ? L"" : L"recycle operation failed") });
#else
return AuditedResult(FileOperationType::Recycle, absolutePath, L"<recycle-bin>",
{ false, std::make_error_code(std::errc::operation_not_supported),
L"recycle bin is only implemented on Windows" });
#endif
}
inline bool IsCrossVolumeMoveError(const std::error_code& error) noexcept {
if (!error) return false;
#ifdef _WIN32
if (error.category() == std::system_category() &&
error.value() == ERROR_NOT_SAME_DEVICE) return true;
#endif
return error == std::errc::cross_device_link;
}
inline bool IsTransientRenameError(const std::error_code& error) noexcept {
#ifdef _WIN32
if (error.category() != std::system_category()) return false;
switch (error.value()) {
case ERROR_ACCESS_DENIED:
case ERROR_SHARING_VIOLATION:
case ERROR_LOCK_VIOLATION:
case ERROR_BUSY:
case ERROR_USER_MAPPED_FILE:
return true;
default:
return false;
}
#else
return error == std::errc::device_or_resource_busy ||
error == std::errc::resource_unavailable_try_again;
#endif
}
enum class VolumeRelation {
Unknown,
Same,
Different
};
#ifdef _WIN32
struct PathVolumeIdentity {
bool available = false;
ULONGLONG serialNumber = 0;
std::error_code error;
};
inline PathVolumeIdentity QueryPathVolumeIdentity(
const std::filesystem::path& existingPath) noexcept {
const auto accessPath = FileSystemAccessPath(existingPath).wstring();
HANDLE handle = ::CreateFileW(
accessPath.c_str(), FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr);
if (handle == INVALID_HANDLE_VALUE) {
return { false, 0,
std::error_code(static_cast<int>(::GetLastError()),
std::system_category()) };
}
FILE_ID_INFO information{};
const BOOL succeeded = ::GetFileInformationByHandleEx(
handle, FileIdInfo, &information, sizeof(information));
const DWORD error = succeeded ? ERROR_SUCCESS : ::GetLastError();
::CloseHandle(handle);
if (!succeeded) {
return { false, 0,
std::error_code(static_cast<int>(error), std::system_category()) };
}
return { true, information.VolumeSerialNumber, {} };
}
inline std::filesystem::path ResolveExistingParent(
const std::filesystem::path& path) noexcept {
auto parent = path.parent_path();
if (!parent.empty()) return parent;
std::error_code error;
parent = std::filesystem::current_path(error);
return error ? std::filesystem::path{} : parent;
}
inline VolumeRelation ComparePathVolumes(
const std::filesystem::path& source,
const std::filesystem::path& destination,
ULONGLONG* sourceSerial = nullptr,
ULONGLONG* destinationSerial = nullptr) noexcept {
const auto sourceIdentity = QueryPathVolumeIdentity(
ResolveExistingParent(source));
const auto destinationIdentity = QueryPathVolumeIdentity(
ResolveExistingParent(destination));
if (!sourceIdentity.available || !destinationIdentity.available) {
return VolumeRelation::Unknown;
}
if (sourceSerial) *sourceSerial = sourceIdentity.serialNumber;
if (destinationSerial) *destinationSerial = destinationIdentity.serialNumber;
return sourceIdentity.serialNumber == destinationIdentity.serialNumber
? VolumeRelation::Same : VolumeRelation::Different;
}
inline std::error_code RenamePathByHandle(
const std::filesystem::path& source,
const std::filesystem::path& destination) noexcept {
const auto sourceAccess = FileSystemAccessPath(source).wstring();
const auto destinationParent = ResolveExistingParent(destination);
if (destinationParent.empty() || destination.filename().empty()) {
return std::make_error_code(std::errc::invalid_argument);
}
HANDLE sourceHandle = ::CreateFileW(
sourceAccess.c_str(), DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr);
if (sourceHandle == INVALID_HANDLE_VALUE) {
return std::error_code(static_cast<int>(::GetLastError()),
std::system_category());
}
// FILE_RENAME_INFO is a variable-length structure. Keep the trailing
// NUL even though FileNameLength excludes it: several redirector and
// cloud-file providers read the terminator while validating the rename
// payload and otherwise return ERROR_INVALID_PARAMETER.
const auto destinationAccess = FileSystemAccessPath(destination).wstring();
const size_t fileNameBytes = destinationAccess.size() * sizeof(wchar_t);
const size_t bufferSize = offsetof(FILE_RENAME_INFO, FileName) +
fileNameBytes + sizeof(wchar_t);
if (bufferSize > static_cast<size_t>((std::numeric_limits<DWORD>::max)())) {
::CloseHandle(sourceHandle);
return std::make_error_code(std::errc::filename_too_long);
}
std::vector<unsigned char> buffer(bufferSize, 0);
auto* information = reinterpret_cast<FILE_RENAME_INFO*>(buffer.data());
information->ReplaceIfExists = FALSE;
information->RootDirectory = nullptr;
information->FileNameLength = static_cast<DWORD>(fileNameBytes);
std::copy(destinationAccess.begin(), destinationAccess.end(), information->FileName);
information->FileName[destinationAccess.size()] = L'\0';
const BOOL succeeded = ::SetFileInformationByHandle(
sourceHandle, FileRenameInfo, information,
static_cast<DWORD>(buffer.size()));
const DWORD error = succeeded ? ERROR_SUCCESS : ::GetLastError();
::CloseHandle(sourceHandle);
return succeeded ? std::error_code{} :
std::error_code(static_cast<int>(error), std::system_category());
}
#else
inline VolumeRelation ComparePathVolumes(
const std::filesystem::path&,
const std::filesystem::path&) noexcept {
return VolumeRelation::Unknown;
}
#endif
inline std::error_code RenamePathWithoutCopy(
const std::filesystem::path& source,
const std::filesystem::path& destination) noexcept {
constexpr unsigned int maxAttempts = 4;
std::error_code error;
for (unsigned int attempt = 0; attempt < maxAttempts; ++attempt) {
#ifdef _WIN32
const auto sourceAccess = FileSystemAccessPath(source).wstring();
const auto destinationAccess = FileSystemAccessPath(destination).wstring();
if (::MoveFileExW(sourceAccess.c_str(), destinationAccess.c_str(), 0)) {
return {};
}
error = std::error_code(static_cast<int>(::GetLastError()),
std::system_category());
#else
std::filesystem::rename(
FileSystemAccessPath(source), FileSystemAccessPath(destination), error);
if (!error) return {};
#endif
if (!IsTransientRenameError(error) || attempt + 1 >= maxAttempts) break;
std::this_thread::sleep_for(
std::chrono::milliseconds(25U * (attempt + 1U)));
}
return error;
}
inline Result CopyToStaging(
const std::filesystem::path& source,
const std::filesystem::path& destination,
std::filesystem::path& staging,
bool verifyContent = false) {
staging.clear();
const auto parent = destination.parent_path();
if (!parent.empty()) {
auto parentResult = EnsureDirectoryExists(parent);
if (!parentResult) {
parentResult.context = L"creating destination parent: " + parentResult.context;
return parentResult;
}
}
auto stagingRoot = parent;
std::error_code ec;
if (stagingRoot.empty()) {
stagingRoot = std::filesystem::current_path(ec);
if (ec) return { false, ec, L"resolving staging directory" };
}
staging = MakeUniquePath(stagingRoot, destination, L"staging");
if (staging.empty()) {
return { false, {}, L"creating staging path in: " + stagingRoot.wstring() };
}
const auto stagingPathForDiagnostics = staging;
const auto sourceAccess = FileSystemAccessPath(source);
const auto stagingAccess = FileSystemAccessPath(staging);
const auto sourceStatus = std::filesystem::symlink_status(sourceAccess, ec);
if (ec) return { false, ec, L"reading source status" };
if (std::filesystem::is_symlink(sourceStatus)) {
std::filesystem::copy_symlink(sourceAccess, stagingAccess, ec);
}
else if (std::filesystem::is_directory(sourceStatus)) {
std::filesystem::copy(
sourceAccess,
stagingAccess,
std::filesystem::copy_options::recursive |
std::filesystem::copy_options::copy_symlinks,
ec);
}
else if (std::filesystem::is_regular_file(sourceStatus)) {
std::filesystem::copy_file(sourceAccess, stagingAccess, ec);
}
else {
return { false, std::make_error_code(std::errc::operation_not_supported),