/
farwinapi.cpp
2180 lines (1864 loc) · 62.5 KB
/
farwinapi.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
/*
farwinapi.cpp
Враперы вокруг некоторых WinAPI функций
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 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.
*/
#include "headers.hpp"
#pragma hdrstop
#include "flink.hpp"
#include "imports.hpp"
#include "pathmix.hpp"
#include "ctrlobj.hpp"
#include "elevation.hpp"
#include "plugins.hpp"
#include "datetime.hpp"
#include "strmix.hpp"
#include "lasterror.hpp"
#include "string_utils.hpp"
#include "cvtname.hpp"
#include "farexcpt.hpp"
#include "drivemix.hpp"
namespace os
{
template<typename T>
bool ApiDynamicStringReceiver(string& Destination, const T& Callable)
{
wchar_t Buffer[MAX_PATH];
auto Size = Callable(Buffer, std::size(Buffer));
if (!Size)
return false;
if (Size < std::size(Buffer))
{
Destination.assign(Buffer, Size);
return true;
}
for (;;)
{
wchar_t_ptr vBuffer(Size);
Size = Callable(vBuffer.get(), vBuffer.size());
if (!Size)
return false;
if (Size < vBuffer.size())
{
Destination.assign(vBuffer.get(), Size);
return true;
}
}
}
template<typename T>
bool ApiDynamicErrorBasedStringReceiver(DWORD ExpectedErrorCode, string& Destination, const T& Callable)
{
wchar_t Buffer[MAX_PATH];
if (const auto Size = Callable(Buffer, std::size(Buffer)))
{
Destination.assign(Buffer, Size);
return true;
}
auto BufferSize = std::size(Buffer);
while (GetLastError() == ExpectedErrorCode)
{
wchar_t_ptr vBuffer(BufferSize *= 2);
if (const auto Size = Callable(vBuffer.get(), vBuffer.size()))
{
Destination.assign(vBuffer.get(), Size);
return true;
}
}
return false;
}
namespace detail
{
class i_find_handle_impl
{
public:
virtual ~i_find_handle_impl() = 0;
};
i_find_handle_impl::~i_find_handle_impl() = default;
void handle_closer::operator()(HANDLE Handle) const { CloseHandle(Handle); }
void find_handle_closer::operator()(HANDLE Handle) const { FindClose(Handle); }
void find_file_handle_closer::operator()(HANDLE Handle) const { delete static_cast<i_find_handle_impl*>(Handle); }
void find_volume_handle_closer::operator()(HANDLE Handle) const { FindVolumeClose(Handle); }
void find_notification_handle_closer::operator()(HANDLE Handle) const { FindCloseChangeNotification(Handle); }
void printer_handle_closer::operator()(HANDLE Handle) const { ClosePrinter(Handle); }
class far_find_handle_impl: public i_find_handle_impl
{
public:
fs::file Object;
block_ptr<BYTE> BufferBase;
block_ptr<BYTE> Buffer2;
ULONG NextOffset {};
bool Extended {};
bool ReadDone {};
};
class os_find_handle_impl: public i_find_handle_impl, public handle_t<find_handle_closer>
{
using handle_t<find_handle_closer>::handle_t;
};
}
static void DirectoryInfoToFindData(const FILE_ID_BOTH_DIR_INFORMATION& DirectoryInfo, FAR_FIND_DATA& FindData, bool IsExtended)
{
FindData.dwFileAttributes = DirectoryInfo.FileAttributes;
FindData.ftCreationTime = UI64ToFileTime(DirectoryInfo.CreationTime);
FindData.ftLastAccessTime = UI64ToFileTime(DirectoryInfo.LastAccessTime);
FindData.ftLastWriteTime = UI64ToFileTime(DirectoryInfo.LastWriteTime);
FindData.ftChangeTime = UI64ToFileTime(DirectoryInfo.ChangeTime);
FindData.nFileSize = DirectoryInfo.EndOfFile.QuadPart;
FindData.nAllocationSize = DirectoryInfo.AllocationSize.QuadPart;
FindData.dwReserved0 = FindData.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT? DirectoryInfo.EaSize : 0;
const auto& CopyNames = [&FindData](const auto& DirInfo)
{
FindData.strFileName.assign(DirInfo.FileName, DirInfo.FileNameLength / sizeof(wchar_t));
FindData.strAlternateFileName.assign(DirInfo.ShortName, DirInfo.ShortNameLength / sizeof(wchar_t));
};
if (IsExtended)
{
FindData.FileId = DirectoryInfo.FileId.QuadPart;
CopyNames(DirectoryInfo);
}
else
{
FindData.FileId = 0;
CopyNames(reinterpret_cast<const FILE_BOTH_DIR_INFORMATION&>(DirectoryInfo));
}
const auto& RemoveTrailingZeros = [](string& Where)
{
const auto Pos = Where.find_last_not_of(L'\0');
Pos != string::npos? Where.resize(Pos + 1) : Where.clear();
};
// 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 the applications use FindFirstFile API, which copies this string
// to the 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.
RemoveTrailingZeros(FindData.strFileName);
RemoveTrailingZeros(FindData.strAlternateFileName);
// Some other buggy implementations just set the first char of AlternateFileName to '\0' to make it "empty", leaving rubbish in others. Double facepalm.
if (!FindData.strAlternateFileName.empty() && FindData.strAlternateFileName.front() == L'\0')
FindData.strAlternateFileName.clear();
}
static find_file_handle FindFirstFileInternal(const string& Name, FAR_FIND_DATA& FindData)
{
if (Name.empty() || IsSlash(Name.back()))
return nullptr;
auto Handle = std::make_unique<detail::far_find_handle_impl>();
auto strDirectory(Name);
CutToSlash(strDirectory);
const auto& OpenDirectory = [&] { return Handle->Object.Open(strDirectory, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING); };
if (!OpenDirectory())
{
// fix error code if we are looking for FILE(S) in non-existent directory, not directory itself
if (GetLastError() == ERROR_FILE_NOT_FOUND && *PointToName(Name))
{
SetLastError(ERROR_PATH_NOT_FOUND);
}
return nullptr;
}
// for network paths buffer size must be <= 64k
Handle->BufferBase.reset(0x10000);
const auto NamePtr = PointToName(Name);
Handle->Extended = true;
bool QueryResult = Handle->Object.NtQueryDirectoryFile(Handle->BufferBase.get(), Handle->BufferBase.size(), FileIdBothDirectoryInformation, false, NamePtr, true);
if (QueryResult) // try next read immediately to avoid M#2128 bug
{
block_ptr<BYTE> Buffer2(Handle->BufferBase.size());
if (Handle->Object.NtQueryDirectoryFile(Buffer2.get(), Buffer2.size(), FileIdBothDirectoryInformation, false, NamePtr, false))
{
Handle->Buffer2 = std::move(Buffer2);
}
else
{
if (GetLastError() != ERROR_INVALID_LEVEL)
Handle->ReadDone = true;
else
QueryResult = false;
}
}
if (!QueryResult)
{
Handle->Extended = false;
// re-create handle to avoid weird bugs with some network emulators
Handle->Object.Close();
if (OpenDirectory())
{
QueryResult = Handle->Object.NtQueryDirectoryFile(Handle->BufferBase.get(), Handle->BufferBase.size(), FileBothDirectoryInformation, false, NamePtr, true);
}
}
if (!QueryResult)
return nullptr;
const auto DirectoryInfo = reinterpret_cast<const FILE_ID_BOTH_DIR_INFORMATION*>(Handle->BufferBase.get());
DirectoryInfoToFindData(*DirectoryInfo, FindData, Handle->Extended);
Handle->NextOffset = DirectoryInfo->NextEntryOffset;
return find_file_handle(Handle.release());
}
static bool FindNextFileInternal(const find_file_handle& Find, FAR_FIND_DATA& FindData)
{
bool Result = false;
const auto Handle = static_cast<detail::far_find_handle_impl*>(Find.native_handle());
bool Status = true, set_errcode = true;
auto DirectoryInfo = reinterpret_cast<const FILE_ID_BOTH_DIR_INFORMATION*>(Handle->BufferBase.get());
if(Handle->NextOffset)
{
DirectoryInfo = reinterpret_cast<const FILE_ID_BOTH_DIR_INFORMATION*>(reinterpret_cast<const char*>(DirectoryInfo)+Handle->NextOffset);
}
else
{
if (Handle->ReadDone)
{
Status = false;
}
else
{
if (Handle->Buffer2)
{
Handle->BufferBase.reset();
using std::swap;
swap(Handle->BufferBase, Handle->Buffer2);
DirectoryInfo = reinterpret_cast<const FILE_ID_BOTH_DIR_INFORMATION*>(Handle->BufferBase.get());
}
else
{
Status = Handle->Object.NtQueryDirectoryFile(Handle->BufferBase.get(), Handle->BufferBase.size(), Handle->Extended ? FileIdBothDirectoryInformation : FileBothDirectoryInformation, false, nullptr, false);
set_errcode = false;
}
}
}
if(Status)
{
DirectoryInfoToFindData(*DirectoryInfo, FindData, Handle->Extended);
Handle->NextOffset = DirectoryInfo->NextEntryOffset? Handle->NextOffset + DirectoryInfo->NextEntryOffset : 0;
Result = true;
}
if (set_errcode)
SetLastError(Result ? ERROR_SUCCESS : ERROR_NO_MORE_FILES);
return Result;
}
//-------------------------------------------------------------------------
namespace fs
{
file_status::file_status():
m_Data(INVALID_FILE_ATTRIBUTES)
{
}
file_status::file_status(const string& Object) :
file_status(Object.data())
{
}
file_status::file_status(const wchar_t* Object):
m_Data(os::GetFileAttributes(Object))
{
}
bool file_status::check(DWORD Data) const
{
return m_Data != INVALID_FILE_ATTRIBUTES && m_Data & Data;
}
bool exists(file_status Status)
{
return Status.check(~0);
}
bool is_file(file_status Status)
{
return exists(Status) && !is_directory(Status);
}
bool is_directory(file_status Status)
{
return Status.check(FILE_ATTRIBUTE_DIRECTORY);
}
bool is_not_empty_directory(const string& Object)
{
const auto Pattern = Object + L"\\*";
const auto Find = enum_files(Pattern);
return Find.begin() != Find.end();
}
bool is_standard_drive_letter(wchar_t Letter)
{
return InRange(L'A', upper(Letter), L'Z');
}
int get_drive_number(wchar_t Letter)
{
return upper(Letter) - L'A';
}
string get_drive(wchar_t Letter)
{
return { Letter, L':' };
}
string get_root_directory(wchar_t Letter)
{
return{ Letter, L':', L'\\' };
}
//-------------------------------------------------------------------------
string detail::enum_files_prepare(const string& Object)
{
auto PreparedObject = NTPath(Object);
auto Root = false;
const auto Type = ParsePath(PreparedObject, nullptr, &Root);
if (Root && (Type == PATH_DRIVELETTER || Type == PATH_DRIVELETTERUNC || Type == PATH_VOLUMEGUID))
{
AddEndSlash(PreparedObject);
}
else
{
DeleteEndSlash(PreparedObject);
}
return PreparedObject;
}
bool detail::get_file_impl(find_file_handle& Handle, const string& Object, size_t index, FAR_FIND_DATA& FindData, bool ScanSymLink)
{
auto Result = false;
if (!index)
{
// temporary disable elevation to try "real" name first
{
SCOPED_ACTION(elevation::suppress);
Handle = FindFirstFileInternal(Object, FindData);
}
if (!Handle && GetLastError() == ERROR_ACCESS_DENIED)
{
if (ScanSymLink)
{
auto strReal = Object;
// only links in path should be processed, not the object name itself
CutToSlash(strReal);
strReal = ConvertNameToReal(strReal);
AddEndSlash(strReal);
strReal += PointToName(Object);
strReal = NTPath(strReal);
Handle = FindFirstFileInternal(strReal, FindData);
}
if (!Handle && ElevationRequired(ELEVATION_READ_REQUEST))
{
Handle = FindFirstFileInternal(Object, FindData);
}
}
Result = Handle != nullptr;
}
else
{
if (Handle)
{
Result = FindNextFileInternal(Handle, FindData);
}
}
// skip ".." & "."
if(Result && FindData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY && FindData.strFileName[0] == L'.' &&
((FindData.strFileName.size() == 2 && FindData.strFileName[1] == L'.') || FindData.strFileName.size() == 1) &&
// хитрый способ - у виртуальных папок не бывает SFN, в отличие от. (UPD: или бывает, но такое же)
(FindData.strAlternateFileName.empty() || FindData.strAlternateFileName == FindData.strFileName))
{
// index not important here, anything but 0 is fine
Result = get_file_impl(Handle, Object, 1, FindData, ScanSymLink);
}
return Result;
}
//-------------------------------------------------------------------------
bool detail::get_name_impl(find_handle& Handle, const string& Object, size_t Index, string& Value)
{
if (!Index)
{
Handle = FindFirstFileName(Object, 0, Value);
return Handle != nullptr;
}
return FindNextFileName(Handle, Value);
}
//-------------------------------------------------------------------------
bool detail::get_stream_impl(find_file_handle& Handle, const string& Object, size_t Index, WIN32_FIND_STREAM_DATA& Value)
{
if (!Index)
{
Handle = os::FindFirstStream(Object, FindStreamInfoStandard, &Value);
return Handle != nullptr;
}
return FindNextStream(Handle, &Value);
}
//-------------------------------------------------------------------------
bool detail::get_volume_impl(find_volume_handle& Handle, size_t Index, string& Value)
{
wchar_t VolumeName[50];
if (!Index)
{
Handle.reset(FindFirstVolume(VolumeName, static_cast<DWORD>(std::size(VolumeName))));
if (!Handle)
{
return false;
}
}
else
{
if (!FindNextVolume(Handle.native_handle(), VolumeName, static_cast<DWORD>(std::size(VolumeName))))
{
return false;
}
}
Value = VolumeName;
return true;
}
//-------------------------------------------------------------------------
bool file::Open(const string& Object, DWORD DesiredAccess, DWORD ShareMode, LPSECURITY_ATTRIBUTES SecurityAttributes, DWORD CreationDistribution, DWORD FlagsAndAttributes, const file* TemplateFile, bool ForceElevation)
{
assert(!m_Handle);
m_Pointer = 0;
m_NeedSyncPointer = false;
const auto TemplateFileHandle = TemplateFile? TemplateFile->m_Handle.native_handle() : nullptr;
m_Handle = CreateFile(Object, DesiredAccess, ShareMode, SecurityAttributes, CreationDistribution, FlagsAndAttributes, TemplateFileHandle, ForceElevation);
if (m_Handle)
{
m_Name = Object;
m_ShareMode = ShareMode;
}
else
{
m_Name.clear();
m_ShareMode = 0;
}
return m_Handle? true : false;
}
void file::SyncPointer() const
{
if(m_NeedSyncPointer)
{
LARGE_INTEGER Distance, NewPointer;
Distance.QuadPart = m_Pointer;
if (SetFilePointerEx(m_Handle.native_handle(), Distance, &NewPointer, FILE_BEGIN))
{
m_Pointer = NewPointer.QuadPart;
m_NeedSyncPointer = false;
}
}
}
bool file::Read(LPVOID Buffer, size_t NumberOfBytesToRead, size_t& NumberOfBytesRead, LPOVERLAPPED Overlapped) const
{
assert(NumberOfBytesToRead <= std::numeric_limits<DWORD>::max());
SyncPointer();
DWORD BytesRead = 0;
bool Result = ReadFile(m_Handle.native_handle(), Buffer, static_cast<DWORD>(NumberOfBytesToRead), &BytesRead, Overlapped) != FALSE;
NumberOfBytesRead = BytesRead;
if(Result)
{
m_Pointer += NumberOfBytesRead;
}
return Result;
}
bool file::Write(LPCVOID Buffer, size_t NumberOfBytesToWrite, size_t& NumberOfBytesWritten, LPOVERLAPPED Overlapped) const
{
assert(NumberOfBytesToWrite <= std::numeric_limits<DWORD>::max());
SyncPointer();
DWORD BytesWritten = 0;
bool Result = WriteFile(m_Handle.native_handle(), Buffer, static_cast<DWORD>(NumberOfBytesToWrite), &BytesWritten, Overlapped) != FALSE;
NumberOfBytesWritten = BytesWritten;
if(Result)
{
m_Pointer += NumberOfBytesWritten;
}
return Result;
}
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;
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();
bool ok = SetEndOfFile(m_Handle.native_handle()) != FALSE;
if (!ok && !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();
ok = SetEndOfFile(m_Handle.native_handle()) != FALSE;
}
}
return ok;
}
bool file::GetTime(LPFILETIME CreationTime, LPFILETIME LastAccessTime, LPFILETIME LastWriteTime, LPFILETIME ChangeTime) const
{
FILE_BASIC_INFORMATION fbi;
if (!NtQueryInformationFile(&fbi, sizeof fbi, FileBasicInformation))
return false;
if (CreationTime)
{
*CreationTime = UI64ToFileTime(fbi.CreationTime);
}
if (LastAccessTime)
{
*LastAccessTime = UI64ToFileTime(fbi.LastAccessTime);
}
if (LastWriteTime)
{
*LastWriteTime = UI64ToFileTime(fbi.LastWriteTime);
}
if (ChangeTime)
{
*ChangeTime = UI64ToFileTime(fbi.ChangeTime);
}
return true;
}
bool file::SetTime(const FILETIME* CreationTime, const FILETIME* LastAccessTime, const FILETIME* LastWriteTime, const FILETIME* ChangeTime) const
{
FILE_BASIC_INFORMATION fbi{};
if (CreationTime)
{
fbi.CreationTime.QuadPart = FileTimeToUI64(*CreationTime);
}
if (LastAccessTime)
{
fbi.LastAccessTime.QuadPart = FileTimeToUI64(*LastAccessTime);
}
if (LastWriteTime)
{
fbi.LastWriteTime.QuadPart = FileTimeToUI64(*LastWriteTime);
}
if (ChangeTime)
{
fbi.ChangeTime.QuadPart = FileTimeToUI64(*ChangeTime);
}
IO_STATUS_BLOCK IoStatusBlock;
const auto Status = Imports().NtSetInformationFile(m_Handle.native_handle(), &IoStatusBlock, &fbi, sizeof fbi, FileBasicInformation);
::SetLastError(Imports().RtlNtStatusToDosError(Status));
return Status == STATUS_SUCCESS;
}
bool file::GetSize(unsigned long long& Size) const
{
return GetFileSizeEx(m_Handle.native_handle(), Size);
}
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, LPVOID InBuffer, DWORD InBufferSize, LPVOID OutBuffer, DWORD OutBufferSize, LPDWORD BytesReturned, LPOVERLAPPED Overlapped) const
{
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
{
DWORD Result = Imports().GetStorageDependencyInformation(m_Handle.native_handle(), Flags, StorageDependencyInfoSize, StorageDependencyInfo, SizeUsed);
SetLastError(Result);
return Result == ERROR_SUCCESS;
}
bool file::NtQueryDirectoryFile(PVOID FileInformation, size_t Length, FILE_INFORMATION_CLASS FileInformationClass, bool ReturnSingleEntry, LPCWSTR FileName, bool RestartScan, NTSTATUS* Status) const
{
IO_STATUS_BLOCK IoStatusBlock;
PUNICODE_STRING pNameString = nullptr;
UNICODE_STRING NameString;
if(FileName && *FileName)
{
NameString.Buffer = const_cast<LPWSTR>(FileName);
NameString.Length = static_cast<USHORT>(wcslen(FileName)*sizeof(WCHAR));
NameString.MaximumLength = NameString.Length;
pNameString = &NameString;
}
const auto di = reinterpret_cast<FILE_ID_BOTH_DIR_INFORMATION*>(FileInformation);
di->NextEntryOffset = 0xffffffffUL;
NTSTATUS Result = Imports().NtQueryDirectoryFile(m_Handle.native_handle(), nullptr, nullptr, nullptr, &IoStatusBlock, FileInformation, static_cast<ULONG>(Length), FileInformationClass, ReturnSingleEntry, pNameString, RestartScan);
SetLastError(Imports().RtlNtStatusToDosError(Result));
if(Status)
{
*Status = Result;
}
return (Result == STATUS_SUCCESS) && (di->NextEntryOffset != 0xffffffffUL);
}
bool file::NtQueryInformationFile(PVOID FileInformation, size_t Length, FILE_INFORMATION_CLASS FileInformationClass, NTSTATUS* Status) const
{
IO_STATUS_BLOCK IoStatusBlock;
NTSTATUS Result = Imports().NtQueryInformationFile(m_Handle.native_handle(), &IoStatusBlock, FileInformation, static_cast<ULONG>(Length), FileInformationClass);
SetLastError(Imports().RtlNtStatusToDosError(Result));
if(Status)
{
*Status = Result;
}
return Result == STATUS_SUCCESS;
}
void file::Close()
{
m_Handle.close();
}
bool file::Eof() const
{
const auto Ptr = GetPointer();
unsigned long long Size=0;
GetSize(Size);
return Ptr >= Size;
}
//-------------------------------------------------------------------------
struct file_walker::Chunk
{
unsigned long long Offset;
DWORD Size;
Chunk(unsigned long long Offset, DWORD Size): Offset(Offset), Size(Size) {}
};
file_walker::file_walker():
m_FileSize(0),
m_AllocSize(0),
m_ProcessedSize(0),
m_CurrentChunk(m_ChunkList.begin()),
m_ChunkSize(0),
m_IsSparse(false)
{
}
file_walker::~file_walker() = default;
bool file_walker::InitWalk(size_t BlockSize)
{
bool Result = false;
m_ChunkSize = static_cast<DWORD>(BlockSize);
if(GetSize(m_FileSize) && m_FileSize)
{
BY_HANDLE_FILE_INFORMATION bhfi;
m_IsSparse = GetInformation(bhfi) && bhfi.dwFileAttributes&FILE_ATTRIBUTE_SPARSE_FILE;
if(m_IsSparse)
{
FILE_ALLOCATED_RANGE_BUFFER QueryRange = {};
QueryRange.Length.QuadPart = m_FileSize;
FILE_ALLOCATED_RANGE_BUFFER Ranges[1024];
DWORD BytesReturned;
for(;;)
{
const bool QueryResult = IoControl(FSCTL_QUERY_ALLOCATED_RANGES, &QueryRange, sizeof(QueryRange), Ranges, sizeof(Ranges), &BytesReturned);
if((QueryResult || GetLastError() == ERROR_MORE_DATA) && BytesReturned)
{
for (const auto& i: make_range(Ranges, BytesReturned / sizeof(*Ranges)))
{
m_AllocSize += i.Length.QuadPart;
const unsigned long long RangeEndOffset = i.FileOffset.QuadPart + i.Length.QuadPart;
for(auto j = static_cast<unsigned long long>(i.FileOffset.QuadPart); j < RangeEndOffset; j+=m_ChunkSize)
{
m_ChunkList.emplace_back(j, static_cast<DWORD>(std::min(RangeEndOffset - j, static_cast<unsigned long long>(m_ChunkSize))));
}
}
QueryRange.FileOffset.QuadPart = m_ChunkList.back().Offset+m_ChunkList.back().Size;
QueryRange.Length.QuadPart = m_FileSize - QueryRange.FileOffset.QuadPart;
}
else
{
break;
}
}
Result = !m_ChunkList.empty();
}
else
{
m_AllocSize = m_FileSize;
m_ChunkList.emplace_back(0, static_cast<DWORD>(std::min(static_cast<unsigned long long>(BlockSize), m_FileSize)));
Result = true;
}
m_CurrentChunk = m_ChunkList.begin();
}
return Result;
}
bool file_walker::Step()
{
bool Result = false;
if(m_IsSparse)
{
++m_CurrentChunk;
if(m_CurrentChunk != m_ChunkList.end())
{
SetPointer(m_CurrentChunk->Offset, nullptr, FILE_BEGIN);
m_ProcessedSize += m_CurrentChunk->Size;
Result = true;
}
}
else
{
const auto NewOffset = (!m_CurrentChunk->Size)? 0 : m_CurrentChunk->Offset + m_ChunkSize;
if(NewOffset < m_FileSize)
{
m_CurrentChunk->Offset = NewOffset;
const auto rest = m_FileSize - NewOffset;
m_CurrentChunk->Size = (rest>=m_ChunkSize)?m_ChunkSize:rest;
m_ProcessedSize += m_CurrentChunk->Size;
Result = true;
}
}
return Result;
}
unsigned long long file_walker::GetChunkOffset() const
{
return m_CurrentChunk->Offset;
}
DWORD file_walker::GetChunkSize() const
{
return m_CurrentChunk->Size;
}
int file_walker::GetPercent() const
{
return m_AllocSize? (m_ProcessedSize) * 100 / m_AllocSize : 0;
}
} // fs
//-------------------------------------------------------------------------
NTSTATUS GetLastNtStatus()
{
return Imports().RtlGetLastNtStatus? Imports().RtlGetLastNtStatus() : STATUS_SUCCESS;
}
bool DeleteFile(const string& FileName)
{
NTPath strNtName(FileName);
if (::DeleteFile(strNtName.data()))
return true;
const auto IsElevationRequired = ElevationRequired(ELEVATION_MODIFY_REQUEST);
if (!os::fs::exists(strNtName))
{
// Someone deleted it already,
// but job is done, no need to report error.
return true;
}
if(IsElevationRequired)
return elevation::instance().fDeleteFile(strNtName);
return false;
}
bool RemoveDirectory(const string& DirName)
{
NTPath strNtName(DirName);
if (::RemoveDirectory(strNtName.data()))
return true;
const auto IsElevationRequired = ElevationRequired(ELEVATION_MODIFY_REQUEST);
if (!os::fs::exists(strNtName))
{
// Someone deleted it already,
// but job is done, no need to report error.
return true;
}
if(IsElevationRequired)
return elevation::instance().fRemoveDirectory(strNtName);
return false;
}
handle CreateFile(const string& Object, DWORD DesiredAccess, DWORD ShareMode, LPSECURITY_ATTRIBUTES SecurityAttributes, DWORD CreationDistribution, DWORD FlagsAndAttributes, HANDLE TemplateFile, bool ForceElevation)
{
NTPath strObject(Object);
FlagsAndAttributes |= FILE_FLAG_BACKUP_SEMANTICS;
if (CreationDistribution == OPEN_EXISTING || CreationDistribution == TRUNCATE_EXISTING)
{
FlagsAndAttributes |= FILE_FLAG_POSIX_SEMANTICS;
}
if (auto Handle = handle(::CreateFile(strObject.data(), DesiredAccess, ShareMode, SecurityAttributes, CreationDistribution, FlagsAndAttributes, TemplateFile)))
return Handle;
const auto LastError = GetLastError();
if (STATUS_STOPPED_ON_SYMLINK == GetLastNtStatus() && ERROR_STOPPED_ON_SYMLINK != LastError)
{
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return nullptr;
}
if (LastError == ERROR_FILE_NOT_FOUND || LastError == ERROR_PATH_NOT_FOUND)
{
FlagsAndAttributes &= ~FILE_FLAG_POSIX_SEMANTICS;
if (auto Handle = handle(::CreateFile(strObject.data(), DesiredAccess, ShareMode, SecurityAttributes, CreationDistribution, FlagsAndAttributes, TemplateFile)))
return Handle;
}
if (ElevationRequired(DesiredAccess & (GENERIC_ALL | GENERIC_WRITE | WRITE_OWNER | WRITE_DAC | DELETE | FILE_WRITE_DATA | FILE_ADD_FILE | FILE_APPEND_DATA | FILE_ADD_SUBDIRECTORY | FILE_CREATE_PIPE_INSTANCE | FILE_WRITE_EA | FILE_DELETE_CHILD | FILE_WRITE_ATTRIBUTES)? ELEVATION_MODIFY_REQUEST : ELEVATION_READ_REQUEST) || ForceElevation)
return handle(elevation::instance().fCreateFile(strObject, DesiredAccess, ShareMode, SecurityAttributes, CreationDistribution, FlagsAndAttributes, TemplateFile));
return nullptr;
}
bool CopyFileEx(
const string& ExistingFileName,
const string& NewFileName,
LPPROGRESS_ROUTINE lpProgressRoutine,
LPVOID lpData,
LPBOOL pbCancel,
DWORD dwCopyFlags
)
{
NTPath strFrom(ExistingFileName), strTo(NewFileName);
if(IsSlash(strTo.back()))
{
strTo += PointToName(strFrom);
}
if (::CopyFileEx(strFrom.data(), strTo.data(), lpProgressRoutine, lpData, pbCancel, dwCopyFlags))
return true;
if (STATUS_STOPPED_ON_SYMLINK == GetLastNtStatus() && ERROR_STOPPED_ON_SYMLINK != GetLastError())
{
::SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return false;
}
if (STATUS_FILE_IS_A_DIRECTORY == GetLastNtStatus())
{
::SetLastError(ERROR_FILE_EXISTS);
return false;
}
if (ElevationRequired(ELEVATION_MODIFY_REQUEST)) //BUGBUG, really unknown
return elevation::instance().fCopyFileEx(strFrom, strTo, lpProgressRoutine, lpData, pbCancel, dwCopyFlags);
return false;
}
bool MoveFile(
const string& ExistingFileName, // address of name of the existing file
const string& NewFileName // address of new name for the file
)
{
NTPath strFrom(ExistingFileName), strTo(NewFileName);
if(IsSlash(strTo.back()))
{
strTo += PointToName(strFrom);
}
if (::MoveFile(strFrom.data(), strTo.data()))
return true;
if (STATUS_STOPPED_ON_SYMLINK == GetLastNtStatus() && ERROR_STOPPED_ON_SYMLINK != GetLastError())
{
::SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return false;
}
if (ElevationRequired(ELEVATION_MODIFY_REQUEST)) //BUGBUG, really unknown
return elevation::instance().fMoveFileEx(strFrom, strTo, 0);
return false;
}
bool MoveFileEx(
const string& ExistingFileName, // address of name of the existing file
const string& NewFileName, // address of new name for the file
DWORD dwFlags // flag to determine how to move file
)
{
NTPath strFrom(ExistingFileName), strTo(NewFileName);
if(IsSlash(strTo.back()))
{