This repository was archived by the owner on Jul 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathnsLocalFileWin.cpp
More file actions
3782 lines (3197 loc) · 97.3 KB
/
Copy pathnsLocalFileWin.cpp
File metadata and controls
3782 lines (3197 loc) · 97.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- 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/UniquePtrExtensions.h"
#include "nsCOMPtr.h"
#include "nsAutoPtr.h"
#include "nsMemory.h"
#include "GeckoProfiler.h"
#include "nsLocalFile.h"
#include "nsIDirectoryEnumerator.h"
#include "nsNativeCharsetUtils.h"
#include "nsISimpleEnumerator.h"
#include "nsIComponentManager.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 <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/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/WidgetUtils.h"
using namespace mozilla;
#define CHECK_mWorkingPath() \
do { \
if (mWorkingPath.IsEmpty()) \
return NS_ERROR_NOT_INITIALIZED; \
} while(0)
// CopyFileEx only supports unbuffered I/O in Windows Vista and above
#ifndef COPY_FILE_NO_BUFFERING
#define COPY_FILE_NO_BUFFERING 0x00001000
#endif
#ifndef FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
#define FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 0x00002000
#endif
#ifndef DRIVE_REMOTE
#define DRIVE_REMOTE 4
#endif
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));
}
/**
* A runnable to dispatch back to the main thread when
* AsyncRevealOperation completes.
*/
class AsyncLocalFileWinDone : public Runnable
{
public:
AsyncLocalFileWinDone() :
Runnable("AsyncLocalFileWinDone"),
mWorkerThread(do_GetCurrentThread())
{
// Objects of this type must only be created on worker threads
MOZ_ASSERT(!NS_IsMainThread());
}
NS_IMETHOD Run() override
{
// This event shuts down the worker thread and so must be main thread.
MOZ_ASSERT(NS_IsMainThread());
// If we don't destroy the thread when we're done with it, it will hang
// around forever... and that is bad!
mWorkerThread->Shutdown();
return NS_OK;
}
private:
nsCOMPtr<nsIThread> mWorkerThread;
};
/**
* A runnable to dispatch from the main thread when an async operation should
* be performed.
*/
class AsyncRevealOperation : public Runnable
{
public:
explicit AsyncRevealOperation(const nsAString& aResolvedPath)
: Runnable("AsyncRevealOperation"),
mResolvedPath(aResolvedPath)
{
}
NS_IMETHOD Run() override
{
MOZ_ASSERT(!NS_IsMainThread(),
"AsyncRevealOperation should not be run on the main thread!");
bool doCoUninitialize = SUCCEEDED(
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE));
Reveal();
if (doCoUninitialize) {
CoUninitialize();
}
// Send the result back to the main thread so that this thread can be
// cleanly shut down
nsCOMPtr<nsIRunnable> resultrunnable = new AsyncLocalFileWinDone();
NS_DispatchToMainThread(resultrunnable);
return NS_OK;
}
private:
// Reveals the path in explorer.
nsresult Reveal()
{
DWORD attributes = GetFileAttributesW(mResolvedPath.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(mResolvedPath.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 = mResolvedPath.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, mResolvedPath.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(mResolvedPath.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;
}
// Stores the path to perform the operation on
nsString mResolvedPath;
};
class nsDriveEnumerator : public nsISimpleEnumerator
{
public:
nsDriveEnumerator();
NS_DECL_ISUPPORTS
NS_DECL_NSISIMPLEENUMERATOR
nsresult Init();
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;
};
//----------------------------------------------------------------------------
// short cut resolver
//----------------------------------------------------------------------------
class ShortcutResolver
{
public:
ShortcutResolver();
// nonvirtual since we're not subclassed
~ShortcutResolver();
nsresult Init();
nsresult Resolve(const WCHAR* aIn, WCHAR* aOut);
nsresult SetShortcut(bool aUpdateExisting,
const WCHAR* aShortcutPath,
const WCHAR* aTargetPath,
const WCHAR* aWorkingDir,
const WCHAR* aArgs,
const WCHAR* aDescription,
const WCHAR* aIconFile,
int32_t aIconIndex);
private:
Mutex mLock;
RefPtr<IPersistFile> mPersistFile;
RefPtr<IShellLinkW> mShellLink;
};
ShortcutResolver::ShortcutResolver() :
mLock("ShortcutResolver.mLock")
{
CoInitialize(nullptr);
}
ShortcutResolver::~ShortcutResolver()
{
CoUninitialize();
}
nsresult
ShortcutResolver::Init()
{
// Get a pointer to the IPersistFile interface.
if (FAILED(CoCreateInstance(CLSID_ShellLink,
nullptr,
CLSCTX_INPROC_SERVER,
IID_IShellLinkW,
getter_AddRefs(mShellLink))) ||
FAILED(mShellLink->QueryInterface(IID_IPersistFile,
getter_AddRefs(mPersistFile)))) {
mShellLink = nullptr;
return NS_ERROR_FAILURE;
}
return NS_OK;
}
// |out| must be an allocated buffer of size MAX_PATH
nsresult
ShortcutResolver::Resolve(const WCHAR* aIn, WCHAR* aOut)
{
if (!mShellLink) {
return NS_ERROR_FAILURE;
}
MutexAutoLock lock(mLock);
if (FAILED(mPersistFile->Load(aIn, STGM_READ)) ||
FAILED(mShellLink->Resolve(nullptr, SLR_NO_UI)) ||
FAILED(mShellLink->GetPath(aOut, MAX_PATH, nullptr, SLGP_UNCPRIORITY))) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
nsresult
ShortcutResolver::SetShortcut(bool aUpdateExisting,
const WCHAR* aShortcutPath,
const WCHAR* aTargetPath,
const WCHAR* aWorkingDir,
const WCHAR* aArgs,
const WCHAR* aDescription,
const WCHAR* aIconPath,
int32_t aIconIndex)
{
if (!mShellLink) {
return NS_ERROR_FAILURE;
}
if (!aShortcutPath) {
return NS_ERROR_FAILURE;
}
MutexAutoLock lock(mLock);
if (aUpdateExisting) {
if (FAILED(mPersistFile->Load(aShortcutPath, STGM_READWRITE))) {
return NS_ERROR_FAILURE;
}
} else {
if (!aTargetPath) {
return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST;
}
// Since we reuse our IPersistFile, we have to clear out any values that
// may be left over from previous calls to SetShortcut.
if (FAILED(mShellLink->SetWorkingDirectory(L"")) ||
FAILED(mShellLink->SetArguments(L"")) ||
FAILED(mShellLink->SetDescription(L"")) ||
FAILED(mShellLink->SetIconLocation(L"", 0))) {
return NS_ERROR_FAILURE;
}
}
if (aTargetPath && FAILED(mShellLink->SetPath(aTargetPath))) {
return NS_ERROR_FAILURE;
}
if (aWorkingDir && FAILED(mShellLink->SetWorkingDirectory(aWorkingDir))) {
return NS_ERROR_FAILURE;
}
if (aArgs && FAILED(mShellLink->SetArguments(aArgs))) {
return NS_ERROR_FAILURE;
}
if (aDescription && FAILED(mShellLink->SetDescription(aDescription))) {
return NS_ERROR_FAILURE;
}
if (aIconPath && FAILED(mShellLink->SetIconLocation(aIconPath, aIconIndex))) {
return NS_ERROR_FAILURE;
}
if (FAILED(mPersistFile->Save(aShortcutPath,
TRUE))) {
// Second argument indicates whether the file path specified in the
// first argument should become the "current working file" for this
// IPersistFile
return NS_ERROR_FAILURE;
}
return NS_OK;
}
static ShortcutResolver* gResolver = nullptr;
static nsresult
NS_CreateShortcutResolver()
{
gResolver = new ShortcutResolver();
return gResolver->Init();
}
static void
NS_DestroyShortcutResolver()
{
delete gResolver;
gResolver = nullptr;
}
//-----------------------------------------------------------------------------
// static helper functions
//-----------------------------------------------------------------------------
// certainly not all the error that can be
// encountered, but many of them common ones
static nsresult
ConvertWinError(DWORD aWinErr)
{
nsresult rv;
switch (aWinErr) {
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
case ERROR_INVALID_DRIVE:
case ERROR_NOT_READY:
rv = NS_ERROR_FILE_NOT_FOUND;
break;
case ERROR_ACCESS_DENIED:
case ERROR_NOT_SAME_DEVICE:
rv = NS_ERROR_FILE_ACCESS_DENIED;
break;
case ERROR_SHARING_VIOLATION: // CreateFile without sharing flags
case ERROR_LOCK_VIOLATION: // LockFile, LockFileEx
rv = NS_ERROR_FILE_IS_LOCKED;
break;
case ERROR_NOT_ENOUGH_MEMORY:
case ERROR_INVALID_BLOCK:
case ERROR_INVALID_HANDLE:
case ERROR_ARENA_TRASHED:
rv = NS_ERROR_OUT_OF_MEMORY;
break;
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:
rv = NS_ERROR_FILE_TOO_BIG;
break;
case ERROR_FILE_EXISTS:
case ERROR_ALREADY_EXISTS:
case ERROR_CANNOT_MAKE:
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 0:
rv = NS_OK;
break;
default:
rv = NS_ERROR_FAILURE;
break;
}
return rv;
}
// as suggested in the MSDN documentation on SetFilePointer
static __int64
MyFileSeek64(HANDLE aHandle, __int64 aDistance, DWORD aMoveMethod)
{
LARGE_INTEGER li;
li.QuadPart = aDistance;
li.LowPart = SetFilePointer(aHandle, li.LowPart, &li.HighPart, aMoveMethod);
if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
li.QuadPart = -1;
}
return li.QuadPart;
}
static bool
IsShortcutPath(const nsAString& aPath)
{
// Under Windows, the shortcuts are just files with a ".lnk" extension.
// Note also that we don't resolve links in the middle of paths.
// i.e. "c:\foo.lnk\bar.txt" is invalid.
MOZ_ASSERT(!aPath.IsEmpty(), "don't pass an empty string");
int32_t len = aPath.Length();
return len >= 4 && (StringTail(aPath, 4).LowerCaseEqualsASCII(".lnk"));
}
//-----------------------------------------------------------------------------
// 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, PRFileInfo64* aInfo)
{
WIN32_FILE_ATTRIBUTE_DATA fileData;
if (aName.IsEmpty() || aName.FindCharInSet(u"?*") != kNotFound) {
return NS_ERROR_INVALID_ARG;
}
if (!::GetFileAttributesExW(aName.get(), GetFileExInfoStandard, &fileData)) {
return ConvertWinError(GetLastError());
}
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;
FileTimeToPRTime(&fileData.ftLastWriteTime, &aInfo->modifyTime);
if (0 == fileData.ftCreationTime.dwLowDateTime &&
0 == fileData.ftCreationTime.dwHighDateTime) {
aInfo->creationTime = aInfo->modifyTime;
} else {
FileTimeToPRTime(&fileData.ftCreationTime, &aInfo->creationTime);
}
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;
if (aName.Length() + 3 >= MAX_PATH) {
return NS_ERROR_FILE_NAME_TOO_LONG;
}
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 nsISimpleEnumerator
, public nsIDirectoryEnumerator
{
private:
~nsDirEnumerator()
{
Close();
}
public:
NS_DECL_ISUPPORTS
nsDirEnumerator() : mDir(nullptr)
{
}
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)
{
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
if (NS_FAILED(CloseDir(mDir))) {
return NS_ERROR_FAILURE;
}
*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 = do_QueryInterface(file);
}
*aResult = mNext != nullptr;
if (!*aResult) {
Close();
}
return NS_OK;
}
NS_IMETHOD GetNext(nsISupports** aResult)
{
nsresult rv;
bool hasMore;
rv = HasMoreElements(&hasMore);
if (NS_FAILED(rv)) {
return rv;
}
*aResult = mNext; // might return nullptr
NS_IF_ADDREF(*aResult);
mNext = nullptr;
return NS_OK;
}
NS_IMETHOD GetNextFile(nsIFile** aResult)
{
*aResult = nullptr;
bool hasMore = false;
nsresult rv = HasMoreElements(&hasMore);
if (NS_FAILED(rv) || !hasMore) {
return rv;
}
*aResult = mNext;
NS_IF_ADDREF(*aResult);
mNext = nullptr;
return NS_OK;
}
NS_IMETHOD Close()
{
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(nsDirEnumerator, nsISimpleEnumerator, nsIDirectoryEnumerator)
//-----------------------------------------------------------------------------
// nsLocalFile <public>
//-----------------------------------------------------------------------------
nsLocalFile::nsLocalFile()
: mDirty(true)
, mResolveDirty(true)
, mFollowSymlinks(false)
{
}
nsresult
nsLocalFile::nsLocalFileConstructor(nsISupports* aOuter, const nsIID& aIID,
void** aInstancePtr)
{
if (NS_WARN_IF(!aInstancePtr)) {
return NS_ERROR_INVALID_ARG;
}
if (NS_WARN_IF(aOuter)) {
return NS_ERROR_NO_AGGREGATION;
}
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,
nsIHashable)
//-----------------------------------------------------------------------------
// nsLocalFile <private>
//-----------------------------------------------------------------------------
nsLocalFile::nsLocalFile(const nsLocalFile& aOther)
: mDirty(true)
, mResolveDirty(true)
, mFollowSymlinks(aOther.mFollowSymlinks)
, mWorkingPath(aOther.mWorkingPath)
{
}
// Resolve the shortcut file from mWorkingPath and write the path
// it points to into mResolvedPath.
nsresult
nsLocalFile::ResolveShortcut()
{
// we can't do anything without the resolver
if (!gResolver) {
return NS_ERROR_FAILURE;
}
mResolvedPath.SetLength(MAX_PATH);
if (mResolvedPath.Length() != MAX_PATH) {
return NS_ERROR_OUT_OF_MEMORY;
}
wchar_t* resolvedPath = mResolvedPath.get();
// resolve this shortcut
nsresult rv = gResolver->Resolve(mWorkingPath.get(), resolvedPath);