forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnsLocalFileWin.cpp
3697 lines (3106 loc) · 104 KB
/
nsLocalFileWin.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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/ArrayUtils.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/TextUtils.h"
#include "mozilla/UniquePtrExtensions.h"
#include "mozilla/Utf8.h"
#include "mozilla/WinHeaderOnlyUtils.h"
#include "nsCOMPtr.h"
#include "nsLocalFile.h"
#include "nsLocalFileCommon.h"
#include "nsIDirectoryEnumerator.h"
#include "nsNativeCharsetUtils.h"
#include "nsSimpleEnumerator.h"
#include "prio.h"
#include "private/pprio.h" // To get PR_ImportFile
#include "nsHashKeys.h"
#include "nsString.h"
#include "nsReadableUtils.h"
#include <direct.h>
#include <fileapi.h>
#include <windows.h>
#include <shlwapi.h>
#include <aclapi.h>
#include "shellapi.h"
#include "shlguid.h"
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <mbstring.h>
#include "prproces.h"
#include "prlink.h"
#include "mozilla/FilePreferences.h"
#include "mozilla/Mutex.h"
#include "SpecialSystemDirectory.h"
#include "nsTraceRefcnt.h"
#include "nsXPCOMCIDInternal.h"
#include "nsThreadUtils.h"
#include "nsXULAppAPI.h"
#include "nsIWindowMediator.h"
#include "mozIDOMWindow.h"
#include "nsPIDOMWindow.h"
#include "nsIWidget.h"
#include "mozilla/ShellHeaderOnlyUtils.h"
#include "mozilla/WidgetUtils.h"
#include "WinUtils.h"
using namespace mozilla;
using mozilla::FilePreferences::kDevicePathSpecifier;
using mozilla::FilePreferences::kPathSeparator;
#define CHECK_mWorkingPath() \
do { \
if (mWorkingPath.IsEmpty()) return NS_ERROR_NOT_INITIALIZED; \
} while (0)
#ifndef FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
# define FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 0x00002000
#endif
#ifndef DRIVE_REMOTE
# define DRIVE_REMOTE 4
#endif
namespace {
nsresult NewLocalFile(const nsAString& aPath, bool aUseDOSDevicePathSyntax,
nsIFile** aResult) {
RefPtr<nsLocalFile> file = new nsLocalFile();
file->SetUseDOSDevicePathSyntax(aUseDOSDevicePathSyntax);
if (!aPath.IsEmpty()) {
nsresult rv = file->InitWithPath(aPath);
if (NS_FAILED(rv)) {
return rv;
}
}
file.forget(aResult);
return NS_OK;
}
} // anonymous namespace
static HWND GetMostRecentNavigatorHWND() {
nsresult rv;
nsCOMPtr<nsIWindowMediator> winMediator(
do_GetService(NS_WINDOWMEDIATOR_CONTRACTID, &rv));
if (NS_FAILED(rv)) {
return nullptr;
}
nsCOMPtr<mozIDOMWindowProxy> navWin;
rv = winMediator->GetMostRecentWindow(u"navigator:browser",
getter_AddRefs(navWin));
if (NS_FAILED(rv) || !navWin) {
return nullptr;
}
nsPIDOMWindowOuter* win = nsPIDOMWindowOuter::From(navWin);
nsCOMPtr<nsIWidget> widget = widget::WidgetUtils::DOMWindowToWidget(win);
if (!widget) {
return nullptr;
}
return reinterpret_cast<HWND>(widget->GetNativeData(NS_NATIVE_WINDOW));
}
nsresult nsLocalFile::RevealFile(const nsString& aResolvedPath) {
MOZ_ASSERT(!NS_IsMainThread(), "Don't run on the main thread");
DWORD attributes = GetFileAttributesW(aResolvedPath.get());
if (INVALID_FILE_ATTRIBUTES == attributes) {
return NS_ERROR_FILE_INVALID_PATH;
}
HRESULT hr;
if (attributes & FILE_ATTRIBUTE_DIRECTORY) {
// We have a directory so we should open the directory itself.
LPITEMIDLIST dir = ILCreateFromPathW(aResolvedPath.get());
if (!dir) {
return NS_ERROR_FAILURE;
}
LPCITEMIDLIST selection[] = {dir};
UINT count = ArrayLength(selection);
// Perform the open of the directory.
hr = SHOpenFolderAndSelectItems(dir, count, selection, 0);
CoTaskMemFree(dir);
} else {
int32_t len = aResolvedPath.Length();
// We don't currently handle UNC long paths of the form \\?\ anywhere so
// this should be fine.
if (len > MAX_PATH) {
return NS_ERROR_FILE_INVALID_PATH;
}
WCHAR parentDirectoryPath[MAX_PATH + 1] = {0};
wcsncpy(parentDirectoryPath, aResolvedPath.get(), MAX_PATH);
PathRemoveFileSpecW(parentDirectoryPath);
// We have a file so we should open the parent directory.
LPITEMIDLIST dir = ILCreateFromPathW(parentDirectoryPath);
if (!dir) {
return NS_ERROR_FAILURE;
}
// Set the item in the directory to select to the file we want to reveal.
LPITEMIDLIST item = ILCreateFromPathW(aResolvedPath.get());
if (!item) {
CoTaskMemFree(dir);
return NS_ERROR_FAILURE;
}
LPCITEMIDLIST selection[] = {item};
UINT count = ArrayLength(selection);
// Perform the selection of the file.
hr = SHOpenFolderAndSelectItems(dir, count, selection, 0);
CoTaskMemFree(dir);
CoTaskMemFree(item);
}
return SUCCEEDED(hr) ? NS_OK : NS_ERROR_FAILURE;
}
// static
bool nsLocalFile::CheckForReservedFileName(const nsString& aFileName) {
static const nsLiteralString forbiddenNames[] = {
u"COM1"_ns, u"COM2"_ns, u"COM3"_ns, u"COM4"_ns, u"COM5"_ns, u"COM6"_ns,
u"COM7"_ns, u"COM8"_ns, u"COM9"_ns, u"LPT1"_ns, u"LPT2"_ns, u"LPT3"_ns,
u"LPT4"_ns, u"LPT5"_ns, u"LPT6"_ns, u"LPT7"_ns, u"LPT8"_ns, u"LPT9"_ns,
u"CON"_ns, u"PRN"_ns, u"AUX"_ns, u"NUL"_ns, u"CLOCK$"_ns};
for (const nsLiteralString& forbiddenName : forbiddenNames) {
if (StringBeginsWith(aFileName, forbiddenName,
nsASCIICaseInsensitiveStringComparator)) {
// invalid name is either the entire string, or a prefix with a period
if (aFileName.Length() == forbiddenName.Length() ||
aFileName.CharAt(forbiddenName.Length()) == char16_t('.')) {
return true;
}
}
}
return false;
}
class nsDriveEnumerator : public nsSimpleEnumerator,
public nsIDirectoryEnumerator {
public:
explicit nsDriveEnumerator(bool aUseDOSDevicePathSyntax);
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_NSISIMPLEENUMERATOR
NS_FORWARD_NSISIMPLEENUMERATORBASE(nsSimpleEnumerator::)
nsresult Init();
const nsID& DefaultInterface() override { return NS_GET_IID(nsIFile); }
NS_IMETHOD GetNextFile(nsIFile** aResult) override {
bool hasMore = false;
nsresult rv = HasMoreElements(&hasMore);
if (NS_FAILED(rv) || !hasMore) {
return rv;
}
nsCOMPtr<nsISupports> next;
rv = GetNext(getter_AddRefs(next));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIFile> result = do_QueryInterface(next);
result.forget(aResult);
return NS_OK;
}
NS_IMETHOD Close() override { return NS_OK; }
private:
virtual ~nsDriveEnumerator();
/* mDrives stores the null-separated drive names.
* Init sets them.
* HasMoreElements checks mStartOfCurrentDrive.
* GetNext advances mStartOfCurrentDrive.
*/
nsString mDrives;
nsAString::const_iterator mStartOfCurrentDrive;
nsAString::const_iterator mEndOfDrivesString;
const bool mUseDOSDevicePathSyntax;
};
//-----------------------------------------------------------------------------
// static helper functions
//-----------------------------------------------------------------------------
/**
* While not comprehensive, this will map many common Windows error codes to a
* corresponding nsresult. If an unmapped error is encountered, the hex error
* code will be logged to stderr. Error codes, names, and descriptions can be
* found at the following MSDN page:
* https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes
*
* \note When adding more mappings here, it must be checked if there's code that
* depends on the current generic NS_ERROR_MODULE_WIN32 mapping for such error
* codes.
*/
static nsresult ConvertWinError(DWORD aWinErr) {
nsresult rv;
switch (aWinErr) {
case ERROR_FILE_NOT_FOUND:
[[fallthrough]]; // to NS_ERROR_FILE_NOT_FOUND
case ERROR_PATH_NOT_FOUND:
[[fallthrough]]; // to NS_ERROR_FILE_NOT_FOUND
case ERROR_INVALID_DRIVE:
rv = NS_ERROR_FILE_NOT_FOUND;
break;
case ERROR_ACCESS_DENIED:
[[fallthrough]]; // to NS_ERROR_FILE_ACCESS_DENIED
case ERROR_NOT_SAME_DEVICE:
[[fallthrough]]; // to NS_ERROR_FILE_ACCESS_DENIED
case ERROR_CANNOT_MAKE:
[[fallthrough]]; // to NS_ERROR_FILE_ACCESS_DENIED
case ERROR_CONTENT_BLOCKED:
rv = NS_ERROR_FILE_ACCESS_DENIED;
break;
case ERROR_SHARING_VIOLATION: // CreateFile without sharing flags
[[fallthrough]]; // to NS_ERROR_FILE_IS_LOCKED
case ERROR_LOCK_VIOLATION: // LockFile, LockFileEx
rv = NS_ERROR_FILE_IS_LOCKED;
break;
case ERROR_NOT_ENOUGH_MEMORY:
[[fallthrough]]; // to NS_ERROR_OUT_OF_MEMORY
case ERROR_NO_SYSTEM_RESOURCES:
rv = NS_ERROR_OUT_OF_MEMORY;
break;
case ERROR_DIR_NOT_EMPTY:
[[fallthrough]]; // to NS_ERROR_FILE_DIR_NOT_EMPTY
case ERROR_CURRENT_DIRECTORY:
rv = NS_ERROR_FILE_DIR_NOT_EMPTY;
break;
case ERROR_WRITE_PROTECT:
rv = NS_ERROR_FILE_READ_ONLY;
break;
case ERROR_HANDLE_DISK_FULL:
[[fallthrough]]; // to NS_ERROR_FILE_NO_DEVICE_SPACE
case ERROR_DISK_FULL:
rv = NS_ERROR_FILE_NO_DEVICE_SPACE;
break;
case ERROR_FILE_EXISTS:
[[fallthrough]]; // to NS_ERROR_FILE_ALREADY_EXISTS
case ERROR_ALREADY_EXISTS:
rv = NS_ERROR_FILE_ALREADY_EXISTS;
break;
case ERROR_FILENAME_EXCED_RANGE:
rv = NS_ERROR_FILE_NAME_TOO_LONG;
break;
case ERROR_DIRECTORY:
rv = NS_ERROR_FILE_NOT_DIRECTORY;
break;
case ERROR_FILE_CORRUPT:
[[fallthrough]]; // to NS_ERROR_FILE_FS_CORRUPTED
case ERROR_DISK_CORRUPT:
rv = NS_ERROR_FILE_FS_CORRUPTED;
break;
case ERROR_DEVICE_HARDWARE_ERROR:
[[fallthrough]]; // to NS_ERROR_FILE_DEVICE_FAILURE
case ERROR_DEVICE_NOT_CONNECTED:
[[fallthrough]]; // to NS_ERROR_FILE_DEVICE_FAILURE
case ERROR_DEV_NOT_EXIST:
[[fallthrough]]; // to NS_ERROR_FILE_DEVICE_FAILURE
case ERROR_IO_DEVICE:
rv = NS_ERROR_FILE_DEVICE_FAILURE;
break;
case ERROR_NOT_READY:
rv = NS_ERROR_FILE_DEVICE_TEMPORARY_FAILURE;
break;
case ERROR_INVALID_NAME:
rv = NS_ERROR_FILE_INVALID_PATH;
break;
case ERROR_INVALID_BLOCK:
[[fallthrough]]; // to NS_ERROR_FILE_INVALID_HANDLE
case ERROR_INVALID_HANDLE:
[[fallthrough]]; // to NS_ERROR_FILE_INVALID_HANDLE
case ERROR_ARENA_TRASHED:
rv = NS_ERROR_FILE_INVALID_HANDLE;
break;
case 0:
rv = NS_OK;
break;
default:
printf_stderr(
"ConvertWinError received an unrecognized WinError: 0x%" PRIx32 "\n",
static_cast<uint32_t>(aWinErr));
MOZ_ASSERT((aWinErr & 0xFFFF) == aWinErr);
rv = NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_WIN32, aWinErr & 0xFFFF);
break;
}
return rv;
}
// Check whether a path is a volume root. Expects paths to be \-terminated.
static bool IsRootPath(const nsAString& aPath) {
// Easy cases first:
if (aPath.Last() != L'\\') {
return false;
}
if (StringEndsWith(aPath, u":\\"_ns)) {
return true;
}
nsAString::const_iterator begin, end;
aPath.BeginReading(begin);
aPath.EndReading(end);
// We know we've got a trailing slash, skip that:
end--;
// Find the next last slash:
if (RFindInReadable(u"\\"_ns, begin, end)) {
// Reset iterator:
aPath.EndReading(end);
end--;
auto lastSegment = Substring(++begin, end);
if (lastSegment.IsEmpty()) {
return false;
}
// Check if we end with e.g. "c$", a drive letter in UNC or network shares
if (lastSegment.Last() == L'$' && lastSegment.Length() == 2 &&
IsAsciiAlpha(lastSegment.First())) {
return true;
}
// Volume GUID paths:
if (StringBeginsWith(lastSegment, u"Volume{"_ns) &&
lastSegment.Last() == L'}') {
return true;
}
}
return false;
}
static auto kSpecialNTFSFilesInRoot = {
u"$MFT"_ns, u"$MFTMirr"_ns, u"$LogFile"_ns, u"$Volume"_ns,
u"$AttrDef"_ns, u"$Bitmap"_ns, u"$Boot"_ns, u"$BadClus"_ns,
u"$Secure"_ns, u"$UpCase"_ns, u"$Extend"_ns};
static bool IsSpecialNTFSPath(const nsAString& aFilePath) {
nsAString::const_iterator begin, end;
aFilePath.BeginReading(begin);
aFilePath.EndReading(end);
auto iter = begin;
// Early exit if there's no '$' (common case)
if (!FindCharInReadable(L'$', iter, end)) {
return false;
}
iter = begin;
// Any use of ':$' is illegal in filenames anyway; while we support some
// ADS stuff (ie ":Zone.Identifier"), none of them use the ':$' syntax:
if (FindInReadable(u":$"_ns, iter, end)) {
return true;
}
auto normalized = mozilla::MakeUniqueFallible<wchar_t[]>(MAX_PATH);
if (!normalized) {
return true;
}
auto flatPath = PromiseFlatString(aFilePath);
auto fullPathRV =
GetFullPathNameW(flatPath.get(), MAX_PATH - 1, normalized.get(), nullptr);
if (fullPathRV == 0 || fullPathRV > MAX_PATH - 1) {
return false;
}
nsString normalizedPath(normalized.get());
normalizedPath.BeginReading(begin);
normalizedPath.EndReading(end);
iter = begin;
auto kDelimiters = u"\\:"_ns;
while (iter != end && FindCharInReadable(L'$', iter, end)) {
for (auto str : kSpecialNTFSFilesInRoot) {
if (StringBeginsWith(Substring(iter, end), str,
nsCaseInsensitiveStringComparator)) {
// If we're enclosed by separators or the beginning/end of the string,
// this is one of the special files. Check if we're on a volume root.
auto iterCopy = iter;
iterCopy.advance(str.Length());
// We check for both \ and : here because the filename could be
// followd by a colon and a stream name/type, which shouldn't affect
// our check:
if (iterCopy == end || kDelimiters.Contains(*iterCopy)) {
iterCopy = iter;
// At the start of this path component, we don't need to care about
// colons: we would have caught those in the check for `:$` above.
if (iterCopy == begin || *(--iterCopy) == L'\\') {
return IsRootPath(Substring(begin, iter));
}
}
}
}
iter++;
}
return false;
}
//-----------------------------------------------------------------------------
// We need the following three definitions to make |OpenFile| convert a file
// handle to an NSPR file descriptor correctly when |O_APPEND| flag is
// specified. It is defined in a private header of NSPR (primpl.h) we can't
// include. As a temporary workaround until we decide how to extend
// |PR_ImportFile|, we define it here. Currently, |_PR_HAVE_PEEK_BUFFER|
// and |PR_STRICT_ADDR_LEN| are not defined for the 'w95'-dependent portion
// of NSPR so that fields of |PRFilePrivate| #ifdef'd by them are not copied.
// Similarly, |_MDFileDesc| is taken from nsprpub/pr/include/md/_win95.h.
// In an unlikely case we switch to 'NT'-dependent NSPR AND this temporary
// workaround last beyond the switch, |PRFilePrivate| and |_MDFileDesc|
// need to be changed to match the definitions for WinNT.
//-----------------------------------------------------------------------------
typedef enum {
_PR_TRI_TRUE = 1,
_PR_TRI_FALSE = 0,
_PR_TRI_UNKNOWN = -1
} _PRTriStateBool;
struct _MDFileDesc {
PROsfd osfd;
};
struct PRFilePrivate {
int32_t state;
bool nonblocking;
_PRTriStateBool inheritable;
PRFileDesc* next;
int lockCount; /* 0: not locked
* -1: a native lockfile call is in progress
* > 0: # times the file is locked */
bool appendMode;
_MDFileDesc md;
};
//-----------------------------------------------------------------------------
// Six static methods defined below (OpenFile, FileTimeToPRTime, GetFileInfo,
// OpenDir, CloseDir, ReadDir) should go away once the corresponding
// UTF-16 APIs are implemented on all the supported platforms (or at least
// Windows 9x/ME) in NSPR. Currently, they're only implemented on
// Windows NT4 or later. (bug 330665)
//-----------------------------------------------------------------------------
// copied from nsprpub/pr/src/{io/prfile.c | md/windows/w95io.c} :
// PR_Open and _PR_MD_OPEN
nsresult OpenFile(const nsString& aName, int aOsflags, int aMode,
bool aShareDelete, PRFileDesc** aFd) {
int32_t access = 0;
int32_t shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
int32_t disposition = 0;
int32_t attributes = 0;
if (aShareDelete) {
shareMode |= FILE_SHARE_DELETE;
}
if (aOsflags & PR_SYNC) {
attributes = FILE_FLAG_WRITE_THROUGH;
}
if (aOsflags & PR_RDONLY || aOsflags & PR_RDWR) {
access |= GENERIC_READ;
}
if (aOsflags & PR_WRONLY || aOsflags & PR_RDWR) {
access |= GENERIC_WRITE;
}
if (aOsflags & PR_CREATE_FILE && aOsflags & PR_EXCL) {
disposition = CREATE_NEW;
} else if (aOsflags & PR_CREATE_FILE) {
if (aOsflags & PR_TRUNCATE) {
disposition = CREATE_ALWAYS;
} else {
disposition = OPEN_ALWAYS;
}
} else {
if (aOsflags & PR_TRUNCATE) {
disposition = TRUNCATE_EXISTING;
} else {
disposition = OPEN_EXISTING;
}
}
if (aOsflags & nsIFile::DELETE_ON_CLOSE) {
attributes |= FILE_FLAG_DELETE_ON_CLOSE;
}
if (aOsflags & nsIFile::OS_READAHEAD) {
attributes |= FILE_FLAG_SEQUENTIAL_SCAN;
}
// If no write permissions are requested, and if we are possibly creating
// the file, then set the new file as read only.
// The flag has no effect if we happen to open the file.
if (!(aMode & (PR_IWUSR | PR_IWGRP | PR_IWOTH)) &&
disposition != OPEN_EXISTING) {
attributes |= FILE_ATTRIBUTE_READONLY;
}
HANDLE file = ::CreateFileW(aName.get(), access, shareMode, nullptr,
disposition, attributes, nullptr);
if (file == INVALID_HANDLE_VALUE) {
*aFd = nullptr;
return ConvertWinError(GetLastError());
}
*aFd = PR_ImportFile((PROsfd)file);
if (*aFd) {
// On Windows, _PR_HAVE_O_APPEND is not defined so that we have to
// add it manually. (see |PR_Open| in nsprpub/pr/src/io/prfile.c)
(*aFd)->secret->appendMode = (PR_APPEND & aOsflags) ? true : false;
return NS_OK;
}
nsresult rv = NS_ErrorAccordingToNSPR();
CloseHandle(file);
return rv;
}
// copied from nsprpub/pr/src/{io/prfile.c | md/windows/w95io.c} :
// PR_FileTimeToPRTime and _PR_FileTimeToPRTime
static void FileTimeToPRTime(const FILETIME* aFiletime, PRTime* aPrtm) {
#ifdef __GNUC__
const PRTime _pr_filetime_offset = 116444736000000000LL;
#else
const PRTime _pr_filetime_offset = 116444736000000000i64;
#endif
MOZ_ASSERT(sizeof(FILETIME) == sizeof(PRTime));
::CopyMemory(aPrtm, aFiletime, sizeof(PRTime));
#ifdef __GNUC__
*aPrtm = (*aPrtm - _pr_filetime_offset) / 10LL;
#else
*aPrtm = (*aPrtm - _pr_filetime_offset) / 10i64;
#endif
}
// copied from nsprpub/pr/src/{io/prfile.c | md/windows/w95io.c} with some
// changes : PR_GetFileInfo64, _PR_MD_GETFILEINFO64
static nsresult GetFileInfo(const nsString& aName,
nsLocalFile::FileInfo* aInfo) {
if (aName.IsEmpty()) {
return NS_ERROR_INVALID_ARG;
}
// Checking u"?*" for the file path excluding the kDevicePathSpecifier.
// ToDo: Check if checking "?" for the file path is still needed.
const int32_t offset = StringBeginsWith(aName, kDevicePathSpecifier)
? kDevicePathSpecifier.Length()
: 0;
if (aName.FindCharInSet(u"?*", offset) != kNotFound) {
return NS_ERROR_INVALID_ARG;
}
WIN32_FILE_ATTRIBUTE_DATA fileData;
if (!::GetFileAttributesExW(aName.get(), GetFileExInfoStandard, &fileData)) {
return ConvertWinError(GetLastError());
}
if (fileData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
aInfo->type = PR_FILE_OTHER;
} else if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
aInfo->type = PR_FILE_DIRECTORY;
} else {
aInfo->type = PR_FILE_FILE;
}
aInfo->size = fileData.nFileSizeHigh;
aInfo->size = (aInfo->size << 32) + fileData.nFileSizeLow;
if (0 == fileData.ftCreationTime.dwLowDateTime &&
0 == fileData.ftCreationTime.dwHighDateTime) {
aInfo->creationTime = aInfo->modifyTime;
} else {
FileTimeToPRTime(&fileData.ftCreationTime, &aInfo->creationTime);
}
FileTimeToPRTime(&fileData.ftLastAccessTime, &aInfo->accessTime);
FileTimeToPRTime(&fileData.ftLastWriteTime, &aInfo->modifyTime);
return NS_OK;
}
struct nsDir {
HANDLE handle;
WIN32_FIND_DATAW data;
bool firstEntry;
};
static nsresult OpenDir(const nsString& aName, nsDir** aDir) {
if (NS_WARN_IF(!aDir)) {
return NS_ERROR_INVALID_ARG;
}
*aDir = nullptr;
nsDir* d = new nsDir();
nsAutoString filename(aName);
// If |aName| ends in a slash or backslash, do not append another backslash.
if (filename.Last() == L'/' || filename.Last() == L'\\') {
filename.Append('*');
} else {
filename.AppendLiteral("\\*");
}
filename.ReplaceChar(L'/', L'\\');
// FindFirstFileW Will have a last error of ERROR_DIRECTORY if
// <file_path>\* is passed in. If <unknown_path>\* is passed in then
// ERROR_PATH_NOT_FOUND will be the last error.
d->handle = ::FindFirstFileW(filename.get(), &(d->data));
if (d->handle == INVALID_HANDLE_VALUE) {
delete d;
return ConvertWinError(GetLastError());
}
d->firstEntry = true;
*aDir = d;
return NS_OK;
}
static nsresult ReadDir(nsDir* aDir, PRDirFlags aFlags, nsString& aName) {
aName.Truncate();
if (NS_WARN_IF(!aDir)) {
return NS_ERROR_INVALID_ARG;
}
while (1) {
BOOL rv;
if (aDir->firstEntry) {
aDir->firstEntry = false;
rv = 1;
} else {
rv = ::FindNextFileW(aDir->handle, &(aDir->data));
}
if (rv == 0) {
break;
}
const wchar_t* fileName;
fileName = (aDir)->data.cFileName;
if ((aFlags & PR_SKIP_DOT) && (fileName[0] == L'.') &&
(fileName[1] == L'\0')) {
continue;
}
if ((aFlags & PR_SKIP_DOT_DOT) && (fileName[0] == L'.') &&
(fileName[1] == L'.') && (fileName[2] == L'\0')) {
continue;
}
DWORD attrib = aDir->data.dwFileAttributes;
if ((aFlags & PR_SKIP_HIDDEN) && (attrib & FILE_ATTRIBUTE_HIDDEN)) {
continue;
}
aName = fileName;
return NS_OK;
}
DWORD err = GetLastError();
return err == ERROR_NO_MORE_FILES ? NS_OK : ConvertWinError(err);
}
static nsresult CloseDir(nsDir*& aDir) {
if (NS_WARN_IF(!aDir)) {
return NS_ERROR_INVALID_ARG;
}
BOOL isOk = FindClose(aDir->handle);
delete aDir;
aDir = nullptr;
return isOk ? NS_OK : ConvertWinError(GetLastError());
}
//-----------------------------------------------------------------------------
// nsDirEnumerator
//-----------------------------------------------------------------------------
class nsDirEnumerator final : public nsSimpleEnumerator,
public nsIDirectoryEnumerator {
private:
~nsDirEnumerator() { Close(); }
public:
NS_DECL_ISUPPORTS_INHERITED
NS_FORWARD_NSISIMPLEENUMERATORBASE(nsSimpleEnumerator::)
nsDirEnumerator() : mDir(nullptr) {}
const nsID& DefaultInterface() override { return NS_GET_IID(nsIFile); }
nsresult Init(nsIFile* aParent) {
nsAutoString filepath;
aParent->GetTarget(filepath);
if (filepath.IsEmpty()) {
aParent->GetPath(filepath);
}
if (filepath.IsEmpty()) {
return NS_ERROR_UNEXPECTED;
}
// IsDirectory is not needed here because OpenDir will return
// NS_ERROR_FILE_NOT_DIRECTORY if the passed in path is a file.
nsresult rv = OpenDir(filepath, &mDir);
if (NS_FAILED(rv)) {
return rv;
}
mParent = aParent;
return NS_OK;
}
NS_IMETHOD HasMoreElements(bool* aResult) override {
nsresult rv;
if (!mNext && mDir) {
nsString name;
rv = ReadDir(mDir, PR_SKIP_BOTH, name);
if (NS_FAILED(rv)) {
return rv;
}
if (name.IsEmpty()) {
// end of dir entries
rv = CloseDir(mDir);
if (NS_FAILED(rv)) {
return rv;
}
*aResult = false;
return NS_OK;
}
nsCOMPtr<nsIFile> file;
rv = mParent->Clone(getter_AddRefs(file));
if (NS_FAILED(rv)) {
return rv;
}
rv = file->Append(name);
if (NS_FAILED(rv)) {
return rv;
}
mNext = file.forget();
}
*aResult = mNext != nullptr;
if (!*aResult) {
Close();
}
return NS_OK;
}
NS_IMETHOD GetNext(nsISupports** aResult) override {
nsresult rv;
bool hasMore;
rv = HasMoreElements(&hasMore);
if (NS_FAILED(rv)) {
return rv;
}
if (!hasMore) {
return NS_ERROR_FAILURE;
}
mNext.forget(aResult);
return NS_OK;
}
NS_IMETHOD GetNextFile(nsIFile** aResult) override {
*aResult = nullptr;
bool hasMore = false;
nsresult rv = HasMoreElements(&hasMore);
if (NS_FAILED(rv) || !hasMore) {
return rv;
}
mNext.forget(aResult);
return NS_OK;
}
NS_IMETHOD Close() override {
if (mDir) {
nsresult rv = CloseDir(mDir);
NS_ASSERTION(NS_SUCCEEDED(rv), "close failed");
if (NS_FAILED(rv)) {
return NS_ERROR_FAILURE;
}
}
return NS_OK;
}
protected:
nsDir* mDir;
nsCOMPtr<nsIFile> mParent;
nsCOMPtr<nsIFile> mNext;
};
NS_IMPL_ISUPPORTS_INHERITED(nsDirEnumerator, nsSimpleEnumerator,
nsIDirectoryEnumerator)
//-----------------------------------------------------------------------------
// nsLocalFile <public>
//-----------------------------------------------------------------------------
nsLocalFile::nsLocalFile()
: mDirty(true), mResolveDirty(true), mUseDOSDevicePathSyntax(false) {}
nsLocalFile::nsLocalFile(const nsAString& aFilePath)
: mUseDOSDevicePathSyntax(false) {
InitWithPath(aFilePath);
}
nsresult nsLocalFile::nsLocalFileConstructor(const nsIID& aIID,
void** aInstancePtr) {
if (NS_WARN_IF(!aInstancePtr)) {
return NS_ERROR_INVALID_ARG;
}
nsLocalFile* inst = new nsLocalFile();
nsresult rv = inst->QueryInterface(aIID, aInstancePtr);
if (NS_FAILED(rv)) {
delete inst;
return rv;
}
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsLocalFile::nsISupports
//-----------------------------------------------------------------------------
NS_IMPL_ISUPPORTS(nsLocalFile, nsIFile, nsILocalFileWin)
//-----------------------------------------------------------------------------
// nsLocalFile <private>
//-----------------------------------------------------------------------------
nsLocalFile::nsLocalFile(const nsLocalFile& aOther)
: mDirty(true),
mResolveDirty(true),
mUseDOSDevicePathSyntax(aOther.mUseDOSDevicePathSyntax),
mWorkingPath(aOther.mWorkingPath) {}
nsresult nsLocalFile::ResolveSymlink() {
std::wstring workingPath(mWorkingPath.Data());
if (!widget::WinUtils::ResolveJunctionPointsAndSymLinks(workingPath)) {
return NS_ERROR_FAILURE;
}
mResolvedPath.Assign(workingPath.c_str(), workingPath.length());
return NS_OK;
}
// Resolve any shortcuts and stat the resolved path. After a successful return
// the path is guaranteed valid and the members of mFileInfo can be used.
nsresult nsLocalFile::ResolveAndStat() {
// if we aren't dirty then we are already done
if (!mDirty) {
return NS_OK;
}
AUTO_PROFILER_LABEL("nsLocalFile::ResolveAndStat", OTHER);
// we can't resolve/stat anything that isn't a valid NSPR addressable path
if (mWorkingPath.IsEmpty()) {
return NS_ERROR_FILE_INVALID_PATH;
}
// this is usually correct
mResolvedPath.Assign(mWorkingPath);
// Make sure root paths have a trailing slash.
nsAutoString nsprPath(mWorkingPath);
if (mWorkingPath.Length() == 2 && mWorkingPath.CharAt(1) == u':') {
nsprPath.Append('\\');
}
// first we will see if the working path exists. If it doesn't then
// there is nothing more that can be done
nsresult rv = GetFileInfo(nsprPath, &mFileInfo);
if (NS_FAILED(rv)) {
return rv;
}
if (mFileInfo.type != PR_FILE_OTHER) {
mResolveDirty = false;
mDirty = false;
return NS_OK;
}
// OTHER from GetFileInfo currently means a symlink
rv = ResolveSymlink();
// Even if it fails we need to have the resolved path equal to working path
// for those functions that always use the resolved path.
if (NS_FAILED(rv)) {
mResolvedPath.Assign(mWorkingPath);
return rv;
}
mResolveDirty = false;
// get the details of the resolved path
rv = GetFileInfo(mResolvedPath, &mFileInfo);
if (NS_FAILED(rv)) {
return rv;
}
mDirty = false;
return NS_OK;
}
/**
* Fills the mResolvedPath member variable with the file or symlink target
* if follow symlinks is on. This is a copy of the Resolve parts from
* ResolveAndStat. ResolveAndStat is much slower though because of the stat.
*
* @return NS_OK on success.
*/
nsresult nsLocalFile::Resolve() {
// if we aren't dirty then we are already done
if (!mResolveDirty) {
return NS_OK;
}
// we can't resolve/stat anything that isn't a valid NSPR addressable path
if (mWorkingPath.IsEmpty()) {
return NS_ERROR_FILE_INVALID_PATH;
}
// this is usually correct
mResolvedPath.Assign(mWorkingPath);
// TODO: Implement symlink support