-
Notifications
You must be signed in to change notification settings - Fork 194
/
platform.fs.cpp
2503 lines (2030 loc) · 76.4 KB
/
platform.fs.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
/*
platform.fs.cpp
*/
/*
Copyright © 2017 Far Group
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 authors 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.
*/
// BUGBUG
#include "platform.headers.hpp"
// Self:
#include "platform.fs.hpp"
// Internal:
#include "cvtname.hpp"
#include "drivemix.hpp"
#include "elevation.hpp"
#include "flink.hpp"
#include "imports.hpp"
#include "pathmix.hpp"
#include "string_utils.hpp"
#include "strmix.hpp"
#include "exception.hpp"
#include "exception_handler.hpp"
#include "mix.hpp"
#include "log.hpp"
// Platform:
#include "platform.hpp"
#include "platform.reg.hpp"
#include "platform.version.hpp"
// Common:
#include "common.hpp"
#include "common/algorithm.hpp"
#include "common/scope_exit.hpp"
// External:
//----------------------------------------------------------------------------
namespace
{
class i_find_file_handle_impl
{
public:
virtual ~i_find_file_handle_impl() = 0;
};
i_find_file_handle_impl::~i_find_file_handle_impl() = default;
class far_find_file_handle_impl final: public i_find_file_handle_impl
{
public:
os::fs::file Object;
block_ptr<BYTE> BufferBase;
block_ptr<BYTE> Buffer2;
ULONG NextOffset{};
bool Extended{};
bool ReadDone{};
};
class os_find_file_handle_impl final: public i_find_file_handle_impl, public os::fs::find_handle
{
using os::fs::find_handle::find_handle;
};
DWORD SHErrorToWinError(DWORD const SHError)
{
switch (SHError)
{
// https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shfileoperationw
// To examine the nonzero values for troubleshooting purposes, they largely map to those defined in Winerror.h.
// However, several of its possible return values are based on pre-Win32 error codes, which in some cases
// overlap the later Winerror.h values without matching their meaning. Those particular values are detailed here,
// and for these specific values only these meanings should be accepted over the Winerror.h codes.
case 0x71: return ERROR_ALREADY_EXISTS; // DE_SAMEFILE The source and destination files are the same file.
case 0x72: return ERROR_INVALID_PARAMETER; // DE_MANYSRC1DEST Multiple file paths were specified in the source buffer, but only one destination file path.
case 0x73: return ERROR_NOT_SAME_DEVICE; // DE_DIFFDIR Rename operation was specified but the destination path is a different directory. Use the move operation instead.
case 0x74: return ERROR_INVALID_PARAMETER; // DE_ROOTDIR The source is a root directory, which cannot be moved or renamed.
case 0x75: return ERROR_CANCELLED; // DE_OPCANCELLED The operation was canceled by the user, or silently canceled if the appropriate flags were supplied to SHFileOperation.
case 0x76: return ERROR_BAD_PATHNAME; // DE_DESTSUBTREE The destination is a subtree of the source.
case 0x78: return ERROR_ACCESS_DENIED; // DE_ACCESSDENIEDSRC Security settings denied access to the source.
case 0x79: return ERROR_BUFFER_OVERFLOW; // DE_PATHTOODEEP The source or destination path exceeded or would exceed MAX_PATH.
case 0x7A: return ERROR_INVALID_PARAMETER; // DE_MANYDEST The operation involved multiple destination paths, which can fail in the case of a move operation.
case 0x7C: return ERROR_BAD_PATHNAME; // DE_INVALIDFILES The path in the source or destination or both was invalid.
case 0x7D: return ERROR_INVALID_PARAMETER; // DE_DESTSAMETREE The source and destination have the same parent folder.
case 0x7E: return ERROR_ALREADY_EXISTS; // DE_FLDDESTISFILE The destination path is an existing file.
case 0x80: return ERROR_ALREADY_EXISTS; // DE_FILEDESTISFLD The destination path is an existing folder.
case 0x81: return ERROR_BUFFER_OVERFLOW; // DE_FILENAMETOOLONG The name of the file exceeds MAX_PATH.
case 0x82: return ERROR_WRITE_FAULT; // DE_DEST_IS_CDROM The destination is a read-only CD-ROM, possibly unformatted.
case 0x83: return ERROR_WRITE_FAULT; // DE_DEST_IS_DVD The destination is a read-only DVD, possibly unformatted.
case 0x84: return ERROR_WRITE_FAULT; // DE_DEST_IS_CDRECORD The destination is a writable CD-ROM, possibly unformatted.
case 0x85: return ERROR_DISK_FULL; // DE_FILE_TOO_LARGE The file involved in the operation is too large for the destination media or file system.
case 0x86: return ERROR_READ_FAULT; // DE_SRC_IS_CDROM The source is a read-only CD-ROM, possibly unformatted.
case 0x87: return ERROR_READ_FAULT; // DE_SRC_IS_DVD The source is a read-only DVD, possibly unformatted.
case 0x88: return ERROR_READ_FAULT; // DE_SRC_IS_CDRECORD The source is a writable CD-ROM, possibly unformatted.
case 0xB7: return ERROR_BUFFER_OVERFLOW; // DE_ERROR_MAX MAX_PATH was exceeded during the operation.
case 0x402: return ERROR_PATH_NOT_FOUND; // An unknown error occurred. This is typically due to an invalid path in the source or destination. This error does not occur on Windows Vista and later.
case 0x10000: return ERROR_GEN_FAILURE; // ERRORONDEST An unspecified error occurred on the destination.
case 0x10074: return ERROR_INVALID_PARAMETER; // DE_ROOTDIR|ERRORONDEST Destination is a root directory and cannot be renamed.
default: return SHError;
}
}
}
namespace os::fs
{
namespace detail
{
void find_handle_closer::operator()(HANDLE Handle) const noexcept
{
if (!FindClose(Handle))
LOGWARNING(L"FindClose(): {}"sv, last_error());
}
void find_file_handle_closer::operator()(HANDLE Handle) const noexcept
{
delete static_cast<i_find_file_handle_impl*>(Handle);
}
void find_volume_handle_closer::operator()(HANDLE Handle) const noexcept
{
if (!FindVolumeClose(Handle))
LOGWARNING(L"FindVolumeClose(): {}"sv, last_error());
}
void find_nt_handle_closer::operator()(HANDLE const Handle) const noexcept
{
if (const auto Status = imports.NtClose(Handle); !NT_SUCCESS(Status))
LOGWARNING(L"NtClose(): {}"sv, Status);
}
}
namespace state
{
static std::atomic_bool current_directory_syncronisation = false;
void set_current_directory_syncronisation(bool const Value)
{
current_directory_syncronisation = Value;
}
}
const string& find_data::AlternateFileName() const
{
return HasAlternateFileName()? AlternateFileNameData : FileName;
}
void find_data::SetAlternateFileName(string_view Name)
{
AlternateFileNameData = Name;
}
bool find_data::HasAlternateFileName() const
{
return !AlternateFileNameData.empty();
}
namespace drive
{
bool is_standard_letter(wchar_t Letter)
{
return in_closed_range(L'A', upper(Letter), L'Z');
}
size_t get_number(wchar_t Letter)
{
assert(is_standard_letter(Letter));
return upper(Letter) - L'A';
}
wchar_t get_letter(size_t Number)
{
assert(Number < 26);
return static_cast<wchar_t>(L'A' + Number);
}
string get_device_path(wchar_t Letter)
{
return { Letter, L':' };
}
string get_device_path(size_t const Number)
{
return { get_letter(Number), L':' };
}
string get_win32nt_device_path(wchar_t Letter)
{
return { L'\\', L'\\', L'?', L'\\', Letter, L':' };
}
string get_root_directory(wchar_t Letter)
{
return { Letter, L':', L'\\' };
}
string get_win32nt_root_directory(wchar_t Letter)
{
return { L'\\', L'\\', L'?', L'\\', Letter, L':', L'\\' };
}
unsigned get_type(string_view const Path)
{
bool IsRoot = false;
if (const auto PathType = ParsePath(Path, {}, &IsRoot); IsRoot && (PathType == root_type::drive_letter || PathType == root_type::win32nt_drive_letter))
{
// It seems that Windows caches this information for drive letters, but not for other paths.
// We want to utilise it, if possible, to avoid delays with network drives.
return GetDriveType(get_root_directory(PathType == root_type::drive_letter? Path[0] : Path[4]).c_str());
}
auto NtPath = nt_path(Path.empty()? os::fs::get_current_directory() : Path);
AddEndSlash(NtPath);
return GetDriveType(NtPath.c_str());
}
}
//-------------------------------------------------------------------------
enum_drives::enum_drives(drives_set Drives):
m_Drives(Drives)
{
}
bool enum_drives::get(bool Reset, wchar_t& Value) const
{
if (Reset)
m_CurrentIndex = 0;
while (m_CurrentIndex != m_Drives.size() && !m_Drives[m_CurrentIndex])
++m_CurrentIndex;
if (m_CurrentIndex == m_Drives.size())
return false;
Value = drive::get_letter(m_CurrentIndex);
++m_CurrentIndex;
return true;
}
//-------------------------------------------------------------------------
static string enum_files_prepare(const string_view Object)
{
string PreparedObject = nt_path(Object);
auto Root = false;
ParsePath(PreparedObject, nullptr, &Root);
if (Root)
{
AddEndSlash(PreparedObject);
}
else
{
DeleteEndSlash(PreparedObject);
}
return PreparedObject;
}
enum_files::enum_files(const string_view Object, const bool ScanSymlink):
m_Object(enum_files_prepare(Object)),
m_ScanSymlink(ScanSymlink)
{
}
// MSDN verse 2.4.17:
// "When working with this field, use FileNameLength to determine the length of the file name
// rather than assuming the presence of a trailing null delimiter."
// Some buggy implementations (e. g. ms sharepoint, rdesktop) set the length incorrectly
// (e. g. including the terminating \0 or as ((number of bytes in the source string) * 2) when source is in UTF-8),
// so instead of, say, "name" (4) they return "name\0\0\0\0" (8).
// Generally speaking, it's their own problems and we shall use it as is, as per the verse above.
// However, most of applications use FindFirstFile API, which copies this string
// to a fixed-size buffer, WIN32_FIND_DATA.cFileName, leaving the burden of finding its length
// to the application itself, which, by coincidence, does it correctly, effectively masking the initial error.
// So people come to us and claim that Far isn't working properly while other programs are fine.
static auto trim_trailing_zeros(string_view const Str)
{
const auto Pos = Str.find_last_not_of(L'\0');
return Pos != string::npos? Str.substr(0, Pos + 1) : string_view{};
}
// Some other buggy implementations just set the first char of AlternateFileName to '\0' to make it "empty", leaving rubbish in others. Double facepalm.
static auto empty_if_zero(string_view const Str)
{
return Str.starts_with(L'\0')? string_view{} : Str;
}
static void DirectoryInfoToFindData(const FILE_ID_BOTH_DIR_INFORMATION& DirectoryInfo, find_data& FindData, bool IsExtended)
{
FindData.Attributes = DirectoryInfo.FileAttributes;
FindData.CreationTime = os::chrono::nt_clock::from_hectonanoseconds(DirectoryInfo.CreationTime.QuadPart);
FindData.LastAccessTime = os::chrono::nt_clock::from_hectonanoseconds(DirectoryInfo.LastAccessTime.QuadPart);
FindData.LastWriteTime = os::chrono::nt_clock::from_hectonanoseconds(DirectoryInfo.LastWriteTime.QuadPart);
FindData.ChangeTime = os::chrono::nt_clock::from_hectonanoseconds(DirectoryInfo.ChangeTime.QuadPart);
FindData.FileSize = DirectoryInfo.EndOfFile.QuadPart;
FindData.AllocationSize = DirectoryInfo.AllocationSize.QuadPart;
FindData.ReparseTag = FindData.Attributes&FILE_ATTRIBUTE_REPARSE_POINT? DirectoryInfo.EaSize : 0;
const auto CopyNames = [&FindData](const auto& DirInfo)
{
FindData.FileName = trim_trailing_zeros({ DirInfo.FileName, DirInfo.FileNameLength / sizeof(wchar_t) });
FindData.SetAlternateFileName(trim_trailing_zeros(empty_if_zero({ DirInfo.ShortName, DirInfo.ShortNameLength / sizeof(wchar_t) })));
};
if (IsExtended)
{
FindData.FileId = DirectoryInfo.FileId.QuadPart;
CopyNames(DirectoryInfo);
}
else
{
FindData.FileId = 0;
CopyNames(view_as<FILE_BOTH_DIR_INFORMATION>(&DirectoryInfo));
}
}
// gh-425 Incorrect file sizes shown/calculated for files compressed with LZX
// WOF-based compression doesn't set FILE_ATTRIBUTE_COMPRESSED and doesn't fill AllocationSize
static void fill_allocation_size_alternative(find_data& FindData, string_view Directory)
{
if (FindData.AllocationSize)
return;
if (!FindData.FileSize)
return;
if (flags::check_any(FindData.Attributes, FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT))
return;
static const auto IsWeirdCompressionAvailable = IsWindows10OrGreater();
if (!IsWeirdCompressionAvailable && !flags::check_any(FindData.Attributes, FILE_ATTRIBUTE_COMPRESSED | FILE_ATTRIBUTE_SPARSE_FILE))
return;
// TODO: It's a separate call so we might need an elevation for it
ULARGE_INTEGER Size;
Size.LowPart = GetCompressedFileSize(nt_path(path::join(Directory, FindData.FileName)).c_str(), &Size.HighPart);
if (Size.LowPart == INVALID_FILE_SIZE && GetLastError() != NO_ERROR)
return;
FindData.AllocationSize = Size.QuadPart;
}
static find_file_handle FindFirstFileInternal(string_view const Name, find_data& FindData)
{
if (Name.empty() || path::get_is_separator(Name)(Name.back()))
return nullptr;
auto Handle = std::make_unique<far_find_file_handle_impl>();
string_view NamePart;
auto Directory = Name;
if (CutToSlash(Directory))
{
NamePart = Name.substr(Directory.size());
}
const auto OpenDirectory = [&]
{
return Handle->Object.Open(Directory, FILE_LIST_DIRECTORY, file_share_all, nullptr, OPEN_EXISTING);
};
if (!OpenDirectory())
{
// fix error code if we are looking for FILE(S) in a non-existent directory, not for a directory itself
if (GetLastError() == ERROR_FILE_NOT_FOUND && !NamePart.empty())
{
SetLastError(ERROR_PATH_NOT_FOUND);
}
return nullptr;
}
// for network paths buffer size must be <= 64k
Handle->BufferBase.reset(65536);
Handle->Extended = true;
bool QueryResult = Handle->Object.NtQueryDirectoryFile(Handle->BufferBase.data(), Handle->BufferBase.size(), FileIdBothDirectoryInformation, false, NamePart, true);
if (QueryResult) // try next read immediately to avoid M#2128 bug
{
block_ptr<BYTE> Buffer2(Handle->BufferBase.size());
if (Handle->Object.NtQueryDirectoryFile(Buffer2.data(), Buffer2.size(), FileIdBothDirectoryInformation, false, NamePart, false))
{
Handle->Buffer2 = std::move(Buffer2);
}
else
{
if (GetLastError() != ERROR_INVALID_LEVEL)
Handle->ReadDone = true;
else
QueryResult = false;
}
}
if (!QueryResult)
{
Handle->Extended = false;
// recreate the handle to avoid weird bugs with some network emulators
Handle->Object.Close();
if (OpenDirectory())
{
QueryResult = Handle->Object.NtQueryDirectoryFile(Handle->BufferBase.data(), Handle->BufferBase.size(), FileBothDirectoryInformation, false, NamePart, true);
}
}
if (!QueryResult)
return nullptr;
const auto& DirectoryInfo = view_as<FILE_ID_BOTH_DIR_INFORMATION>(Handle->BufferBase.data());
DirectoryInfoToFindData(DirectoryInfo, FindData, Handle->Extended);
fill_allocation_size_alternative(FindData, Directory);
Handle->NextOffset = DirectoryInfo.NextEntryOffset;
return find_file_handle(Handle.release());
}
static bool FindNextFileInternal(const find_file_handle& Find, find_data& FindData)
{
bool Result = false;
auto& Handle = *static_cast<far_find_file_handle_impl*>(Find.native_handle());
bool Status = true, set_errcode = true;
auto DirectoryInfo = std::bit_cast<const FILE_ID_BOTH_DIR_INFORMATION*>(Handle.BufferBase.data());
if (Handle.NextOffset)
{
DirectoryInfo = view_as<const FILE_ID_BOTH_DIR_INFORMATION*>(DirectoryInfo, Handle.NextOffset);
}
else
{
if (Handle.ReadDone)
{
Status = false;
}
else
{
if (Handle.Buffer2)
{
Handle.BufferBase = std::move(Handle.Buffer2);
DirectoryInfo = view_as<const FILE_ID_BOTH_DIR_INFORMATION*>(Handle.BufferBase.data());
}
else
{
Status = Handle.Object.NtQueryDirectoryFile(Handle.BufferBase.data(), Handle.BufferBase.size(), Handle.Extended? FileIdBothDirectoryInformation : FileBothDirectoryInformation, false, {}, false);
set_errcode = false;
}
}
}
if (Status)
{
DirectoryInfoToFindData(*DirectoryInfo, FindData, Handle.Extended);
fill_allocation_size_alternative(FindData, Handle.Object.GetName());
Handle.NextOffset = DirectoryInfo->NextEntryOffset? Handle.NextOffset + DirectoryInfo->NextEntryOffset : 0;
Result = true;
}
if (set_errcode)
SetLastError(Result? ERROR_SUCCESS : ERROR_NO_MORE_FILES);
return Result;
}
bool enum_files::get(bool Reset, find_data& Value) const
{
if (Reset)
{
// temporarily disable elevation to try the requested name first
{
SCOPED_ACTION(auto)(elevation::suppress(true));
m_Handle = FindFirstFileInternal(m_Object, Value);
}
if (!m_Handle && GetLastError() == ERROR_ACCESS_DENIED)
{
if (m_ScanSymlink)
{
string_view Str = m_Object;
// only links in the path should be processed, not the object name itself
CutToSlash(Str);
m_Handle = FindFirstFileInternal(nt_path(path::join(ConvertNameToReal(Str), PointToName(m_Object))), Value);
}
if (!m_Handle && ElevationRequired(ELEVATION_READ_REQUEST))
{
m_Handle = FindFirstFileInternal(m_Object, Value);
}
}
if (!m_Handle)
return false;
}
else
{
if (!FindNextFileInternal(m_Handle, Value))
return false;
}
// skip ".." & "."
if (Value.Attributes & FILE_ATTRIBUTE_DIRECTORY &&
Value.FileName[0] == L'.' && ((Value.FileName.size() == 2 && Value.FileName[1] == L'.') || Value.FileName.size() == 1) &&
// These "virtual" folders either don't have an SFN at all or it's the same as LFN:
(!Value.HasAlternateFileName() || Value.AlternateFileName() == Value.FileName))
{
return get(false, Value);
}
return true;
}
//-------------------------------------------------------------------------
static find_handle FindFirstFileName(const string_view FileName, const DWORD Flags, string& LinkName)
{
if (!imports.FindFirstFileNameW)
return {};
const auto NtFileName = nt_path(FileName);
find_handle Handle;
// BUGBUG check result
(void)os::detail::ApiDynamicStringReceiver(LinkName, [&](std::span<wchar_t> Buffer)
{
auto BufferSize = static_cast<DWORD>(Buffer.size());
Handle.reset(imports.FindFirstFileNameW(NtFileName.c_str(), Flags, &BufferSize, Buffer.data()));
if (Handle)
// FindFirstFileNameW always includes terminating \0 in the returned size
return BufferSize - 1;
return GetLastError() == ERROR_MORE_DATA? BufferSize : 0;
});
return Handle;
}
static bool FindNextFileName(const find_handle& hFindStream, string& LinkName)
{
if (!imports.FindNextFileNameW)
return false;
return os::detail::ApiDynamicStringReceiver(LinkName, [&](std::span<wchar_t> Buffer)
{
auto BufferSize = static_cast<DWORD>(Buffer.size());
if (imports.FindNextFileNameW(hFindStream.native_handle(), &BufferSize, Buffer.data()))
// FindNextFileNameW always includes terminating \0 in the returned size
return BufferSize - 1;
return GetLastError() == ERROR_MORE_DATA? BufferSize : 0;
});
}
enum_names::enum_names(const string_view Object):
m_Object(Object)
{
}
bool enum_names::get(bool Reset, string& Value) const
{
if (Reset)
{
m_Handle = FindFirstFileName(m_Object, 0, Value);
return m_Handle != nullptr;
}
return FindNextFileName(m_Handle, Value);
}
//-------------------------------------------------------------------------
static bool FileStreamInformationToFindStreamData(const FILE_STREAM_INFORMATION& StreamInfo, WIN32_FIND_STREAM_DATA& StreamData)
{
const auto Length = StreamInfo.StreamNameLength / sizeof(wchar_t);
if (!Length || Length >= std::size(StreamData.cStreamName))
return false;
*std::copy_n(std::cbegin(StreamInfo.StreamName), Length, StreamData.cStreamName) = {};
StreamData.StreamSize = StreamInfo.StreamSize;
return true;
}
static find_file_handle FindFirstStream(const string_view FileName, const STREAM_INFO_LEVELS InfoLevel, void* const FindStreamData, const DWORD Flags)
{
if (imports.FindFirstStreamW && imports.FindNextStreamW)
{
os_find_file_handle_impl Handle(imports.FindFirstStreamW(nt_path(FileName).c_str(), InfoLevel, FindStreamData, Flags));
return find_file_handle(Handle? std::make_unique<os_find_file_handle_impl>(Handle.release()).release() : nullptr);
}
if (InfoLevel != FindStreamInfoStandard)
return nullptr;
auto Handle = std::make_unique<far_find_file_handle_impl>();
if (!Handle->Object.Open(FileName, 0, file_share_all, nullptr, OPEN_EXISTING))
return nullptr;
// for network paths buffer size must be <= 64k
// we double it in a first loop, so starting value is 32k
size_t BufferSize = 32768;
auto Result = STATUS_UNSUCCESSFUL;
do
{
BufferSize *= 2;
Handle->BufferBase.reset(BufferSize);
// sometimes for directories NtQueryInformationFile returns STATUS_SUCCESS but doesn't fill the buffer
auto& StreamInfo = edit_as<FILE_STREAM_INFORMATION>(Handle->BufferBase.data());
StreamInfo.StreamNameLength = 0;
// BUGBUG check result
(void)Handle->Object.NtQueryInformationFile(Handle->BufferBase.data(), Handle->BufferBase.size(), FileStreamInformation, &Result);
}
while (any_of(Result, STATUS_INFO_LENGTH_MISMATCH, STATUS_BUFFER_OVERFLOW, STATUS_BUFFER_TOO_SMALL));
if (!NT_SUCCESS(Result))
return nullptr;
const auto& StreamInfo = view_as<FILE_STREAM_INFORMATION>(Handle->BufferBase.data());
Handle->NextOffset = StreamInfo.NextEntryOffset;
const auto StreamData = static_cast<WIN32_FIND_STREAM_DATA*>(FindStreamData);
if (!FileStreamInformationToFindStreamData(StreamInfo, *StreamData))
return nullptr;
return find_file_handle(Handle.release());
}
static bool FindNextStream(const find_file_handle& hFindStream, void* FindStreamData)
{
if (imports.FindFirstStreamW && imports.FindNextStreamW)
{
return imports.FindNextStreamW(static_cast<os_find_file_handle_impl*>(hFindStream.native_handle())->native_handle(), FindStreamData) != FALSE;
}
const auto Handle = static_cast<far_find_file_handle_impl*>(hFindStream.native_handle());
if (!Handle->NextOffset)
return false;
const auto& StreamInfo = view_as<FILE_STREAM_INFORMATION>(Handle->BufferBase.data() + Handle->NextOffset);
Handle->NextOffset = StreamInfo.NextEntryOffset? Handle->NextOffset + StreamInfo.NextEntryOffset : 0;
const auto StreamData = static_cast<WIN32_FIND_STREAM_DATA*>(FindStreamData);
return FileStreamInformationToFindStreamData(StreamInfo, *StreamData);
}
enum_streams::enum_streams(const string_view Object):
m_Object(Object)
{
}
bool enum_streams::get(bool Reset, WIN32_FIND_STREAM_DATA& Value) const
{
if (Reset)
{
m_Handle = FindFirstStream(m_Object, FindStreamInfoStandard, &Value, 0);
return m_Handle != nullptr;
}
return FindNextStream(m_Handle, &Value);
}
//-------------------------------------------------------------------------
enum_volumes::enum_volumes() = default;
bool enum_volumes::get(bool Reset, string& Value) const
{
// A reasonable size for the buffer to accommodate the largest possible volume UUID path is 50 characters.
wchar_t VolumeName[50];
if (Reset)
{
m_Handle.reset(FindFirstVolume(VolumeName, static_cast<DWORD>(std::size(VolumeName))));
if (!m_Handle)
{
return false;
}
}
else
{
if (!FindNextVolume(m_Handle.native_handle(), VolumeName, static_cast<DWORD>(std::size(VolumeName))))
{
return false;
}
}
Value = VolumeName;
return true;
}
//-------------------------------------------------------------------------
enum_devices::enum_devices(string_view const Object)
{
m_Object.Buffer = const_cast<wchar_t*>(Object.data());
m_Object.Length = m_Object.MaximumLength = static_cast<USHORT>(Object.size() * sizeof(wchar_t));
OBJECT_ATTRIBUTES Attributes;
InitializeObjectAttributes(&Attributes, &m_Object, 0, nullptr, nullptr)
if (!NT_SUCCESS(imports.NtOpenDirectoryObject(&ptr_setter(m_Handle), GENERIC_READ, &Attributes)))
return;
m_Buffer.reset(32 * 1024);
}
bool enum_devices::get(bool Reset, string_view& Value) const
{
if (!m_Handle)
return false;
if (Reset)
m_Index.reset();
auto RestartScan = Reset;
const auto fill = [&]
{
ULONG Size;
if (!NT_SUCCESS(imports.NtQueryDirectoryObject(m_Handle.native_handle(), m_Buffer.data(), static_cast<ULONG>(m_Buffer.size()), false, RestartScan, &m_Context, &Size)))
return false;
RestartScan = false;
m_Index = 0;
return true;
};
if (!m_Index)
{
if (!fill())
return false;
}
const auto Entries = std::bit_cast<OBJECT_DIRECTORY_INFORMATION const*>(m_Buffer.data());
if (!Entries[*m_Index].Name.Length)
{
m_Index.reset();
if (!fill())
return false;
}
Value = { Entries[*m_Index].Name.Buffer, Entries[*m_Index].Name.Length / sizeof(wchar_t) };
++*m_Index;
return true;
}
//-------------------------------------------------------------------------
file::file():
m_Pointer(),
m_NeedSyncPointer(),
m_ShareMode()
{
}
file::file(handle&& Handle):
m_Handle(std::move(Handle)),
m_Pointer(),
m_NeedSyncPointer(),
m_ShareMode()
{
LARGE_INTEGER NewPointer;
SetFilePointerEx(m_Handle.native_handle(), {}, &NewPointer, FILE_CURRENT);
m_Pointer = NewPointer.QuadPart;
}
file::operator bool() const noexcept
{
return m_Handle.operator bool();
}
bool file::Open(const string_view Object, const DWORD DesiredAccess, const DWORD ShareMode, SECURITY_ATTRIBUTES* SecurityAttributes, const DWORD CreationDistribution, const DWORD FlagsAndAttributes, const file* TemplateFile, const bool ForceElevation)
{
assert(!m_Handle);
m_Pointer = 0;
m_NeedSyncPointer = false;
const auto TemplateFileHandle = TemplateFile? TemplateFile->m_Handle.native_handle() : nullptr;
m_Handle = create_file(Object, DesiredAccess, ShareMode, SecurityAttributes, CreationDistribution, FlagsAndAttributes, TemplateFileHandle, ForceElevation);
if (!m_Handle)
{
m_Name.clear();
m_ShareMode = 0;
return false;
}
m_Name = Object;
m_ShareMode = ShareMode;
return true;
}
bool file::Read(void* Buffer, size_t NumberOfBytesToRead, size_t& NumberOfBytesRead) const
{
assert(NumberOfBytesToRead <= std::numeric_limits<DWORD>::max());
SyncPointer();
NumberOfBytesRead = 0;
DWORD BytesRead = 0;
if (!ReadFile(m_Handle.native_handle(), Buffer, static_cast<DWORD>(NumberOfBytesToRead), &BytesRead, nullptr))
return false;
NumberOfBytesRead = BytesRead;
m_Pointer += NumberOfBytesRead;
return true;
}
bool file::Write(const void* Buffer, size_t NumberOfBytesToWrite) const
{
assert(NumberOfBytesToWrite <= std::numeric_limits<DWORD>::max());
SyncPointer();
DWORD BytesWritten = 0;
if (!WriteFile(m_Handle.native_handle(), Buffer, static_cast<DWORD>(NumberOfBytesToWrite), &BytesWritten, nullptr))
return false;
m_Pointer += BytesWritten;
return true;
}
unsigned long long file::GetPointer() const
{
return m_Pointer;
}
bool file::SetPointer(long long DistanceToMove, unsigned long long* NewFilePointer, DWORD MoveMethod) const
{
const auto OldPointer = m_Pointer;
switch (MoveMethod)
{
case FILE_BEGIN:
m_Pointer = DistanceToMove;
break;
case FILE_CURRENT:
m_Pointer += DistanceToMove;
break;
case FILE_END:
{
unsigned long long Size = 0;
// BUGBUG check result
(void)GetSize(Size);
m_Pointer = Size + DistanceToMove;
}
break;
}
if (OldPointer != m_Pointer)
{
m_NeedSyncPointer = true;
}
if (NewFilePointer)
{
*NewFilePointer = m_Pointer;
}
return true;
}
bool file::SetEnd()
{
SyncPointer();
if (SetEndOfFile(m_Handle.native_handle()))
return true;
if (!m_Name.empty() && GetLastError() == ERROR_INVALID_PARAMETER) // OSX buggy SMB workaround
{
const auto fsize = GetPointer();
Close();
if (Open(m_Name, GENERIC_WRITE, m_ShareMode, nullptr, OPEN_EXISTING, 0))
{
SetPointer(fsize, nullptr, FILE_BEGIN);
SyncPointer();
return SetEndOfFile(m_Handle.native_handle()) != FALSE;
}
}
return false;
}
bool file::GetTime(os::chrono::time_point* CreationTime, os::chrono::time_point* LastAccessTime, os::chrono::time_point* LastWriteTime, os::chrono::time_point* ChangeTime) const
{
const auto convert_time = [](LARGE_INTEGER const& From, os::chrono::time_point* const To)
{
if (To)
*To = os::chrono::nt_clock::from_hectonanoseconds(From.QuadPart);
};
FILE_BASIC_INFORMATION fbi;
if (!NtQueryInformationFile(&fbi, sizeof fbi, FileBasicInformation))
return false;
convert_time(fbi.CreationTime, CreationTime);
convert_time(fbi.LastAccessTime, LastAccessTime);
convert_time(fbi.LastWriteTime, LastWriteTime);
convert_time(fbi.ChangeTime, ChangeTime);
return true;
}
bool file::SetTime(const os::chrono::time_point* CreationTime, const os::chrono::time_point* LastAccessTime, const os::chrono::time_point* LastWriteTime, const os::chrono::time_point* ChangeTime) const
{
const auto convert_time = [](os::chrono::time_point const* const From, LARGE_INTEGER& To)
{
if (From)
To.QuadPart = os::chrono::nt_clock::to_hectonanoseconds(*From);
};
FILE_BASIC_INFORMATION fbi{};
convert_time(CreationTime, fbi.CreationTime);
convert_time(LastAccessTime, fbi.LastAccessTime);
convert_time(LastWriteTime, fbi.LastWriteTime);
convert_time(ChangeTime, fbi.ChangeTime);
IO_STATUS_BLOCK IoStatusBlock;
const auto Status = imports.NtSetInformationFile(m_Handle.native_handle(), &IoStatusBlock, &fbi, sizeof fbi, FileBasicInformation);
set_last_error_from_ntstatus(Status);
return NT_SUCCESS(Status);
}
bool file::GetSize(unsigned long long& Size) const
{
GET_LENGTH_INFORMATION gli;
if (!GetFileSizeEx(m_Handle.native_handle(), &gli.Length) && !IoControl(IOCTL_DISK_GET_LENGTH_INFO, nullptr, 0, &gli, sizeof(gli)))
return false;
Size = gli.Length.QuadPart;
return true;
}
bool file::FlushBuffers() const
{
return FlushFileBuffers(m_Handle.native_handle()) != FALSE;
}
bool file::GetInformation(BY_HANDLE_FILE_INFORMATION& info) const
{
return GetFileInformationByHandle(m_Handle.native_handle(), &info) != FALSE;
}
bool file::IoControl(DWORD IoControlCode, void* InBuffer, DWORD InBufferSize, void* OutBuffer, DWORD OutBufferSize, DWORD* BytesReturned, OVERLAPPED* Overlapped) const
{
DWORD BytesReturnedFallback = 0;
if (!BytesReturned)
BytesReturned = &BytesReturnedFallback;
return DeviceIoControl(m_Handle.native_handle(), IoControlCode, InBuffer, InBufferSize, OutBuffer, OutBufferSize, BytesReturned, Overlapped) != FALSE;
}
bool file::GetStorageDependencyInformation(GET_STORAGE_DEPENDENCY_FLAG Flags, ULONG StorageDependencyInfoSize, PSTORAGE_DEPENDENCY_INFO StorageDependencyInfo, PULONG SizeUsed) const
{
if (!imports.GetStorageDependencyInformation)
return false;
const auto Result = imports.GetStorageDependencyInformation(m_Handle.native_handle(), Flags, StorageDependencyInfoSize, StorageDependencyInfo, SizeUsed);
SetLastError(Result);
return Result == ERROR_SUCCESS;
}
bool file::NtQueryDirectoryFile(void* FileInformation, size_t Length, FILE_INFORMATION_CLASS FileInformationClass, bool ReturnSingleEntry, string_view const FileName, bool RestartScan, NTSTATUS* Status) const
{
IO_STATUS_BLOCK IoStatusBlock;
PUNICODE_STRING pNameString = nullptr;
UNICODE_STRING NameString;
if (!FileName.empty())