forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnsLocalFileUnix.cpp
2932 lines (2481 loc) · 74.3 KB
/
nsLocalFileUnix.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/. */
/**
* Implementation of nsIFile for "unixy" systems.
*/
#include "nsLocalFile.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Sprintf.h"
#include "mozilla/FilePreferences.h"
#include "prtime.h"
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#if defined(XP_MACOSX)
# include <sys/xattr.h>
#endif
#if defined(USE_LINUX_QUOTACTL)
# include <sys/mount.h>
# include <sys/quota.h>
# include <sys/sysmacros.h>
# ifndef BLOCK_SIZE
# define BLOCK_SIZE 1024 /* kernel block size */
# endif
#endif
#include "nsDirectoryServiceDefs.h"
#include "nsCOMPtr.h"
#include "nsIFile.h"
#include "nsString.h"
#include "nsIDirectoryEnumerator.h"
#include "nsSimpleEnumerator.h"
#include "private/pprio.h"
#include "prlink.h"
#ifdef MOZ_WIDGET_GTK
# include "nsIGIOService.h"
#endif
#ifdef MOZ_WIDGET_COCOA
# include <Carbon/Carbon.h>
# include "CocoaFileUtils.h"
# include "prmem.h"
# include "plbase64.h"
static nsresult MacErrorMapper(OSErr inErr);
#endif
#ifdef MOZ_WIDGET_ANDROID
# include "mozilla/java/GeckoAppShellWrappers.h"
# include "nsIMIMEService.h"
# include <linux/magic.h>
#endif
#include "nsNativeCharsetUtils.h"
#include "nsTraceRefcnt.h"
/**
* we need these for statfs()
*/
#ifdef HAVE_SYS_STATVFS_H
# if defined(__osf__) && defined(__DECCXX)
extern "C" int statvfs(const char*, struct statvfs*);
# endif
# include <sys/statvfs.h>
#endif
#ifdef HAVE_SYS_STATFS_H
# include <sys/statfs.h>
#endif
#ifdef HAVE_SYS_VFS_H
# include <sys/vfs.h>
#endif
#if defined(HAVE_STATVFS64) && (!defined(LINUX) && !defined(__osf__))
# define STATFS statvfs64
# define F_BSIZE f_frsize
#elif defined(HAVE_STATVFS) && (!defined(LINUX) && !defined(__osf__))
# define STATFS statvfs
# define F_BSIZE f_frsize
#elif defined(HAVE_STATFS64)
# define STATFS statfs64
# define F_BSIZE f_bsize
#elif defined(HAVE_STATFS)
# define STATFS statfs
# define F_BSIZE f_bsize
#endif
using namespace mozilla;
#define ENSURE_STAT_CACHE() \
do { \
if (!FillStatCache()) return NSRESULT_FOR_ERRNO(); \
} while (0)
#define CHECK_mPath() \
do { \
if (mPath.IsEmpty()) return NS_ERROR_NOT_INITIALIZED; \
if (!FilePreferences::IsAllowedPath(mPath)) \
return NS_ERROR_FILE_ACCESS_DENIED; \
} while (0)
static PRTime TimespecToMillis(const struct timespec& aTimeSpec) {
return PRTime(aTimeSpec.tv_sec) * PR_MSEC_PER_SEC +
PRTime(aTimeSpec.tv_nsec) / PR_NSEC_PER_MSEC;
}
/* directory enumerator */
class nsDirEnumeratorUnix final : public nsSimpleEnumerator,
public nsIDirectoryEnumerator {
public:
nsDirEnumeratorUnix();
// nsISupports interface
NS_DECL_ISUPPORTS_INHERITED
// nsISimpleEnumerator interface
NS_DECL_NSISIMPLEENUMERATOR
// nsIDirectoryEnumerator interface
NS_DECL_NSIDIRECTORYENUMERATOR
NS_IMETHOD Init(nsLocalFile* aParent, bool aIgnored);
NS_FORWARD_NSISIMPLEENUMERATORBASE(nsSimpleEnumerator::)
const nsID& DefaultInterface() override { return NS_GET_IID(nsIFile); }
private:
~nsDirEnumeratorUnix() override;
protected:
NS_IMETHOD GetNextEntry();
DIR* mDir;
struct dirent* mEntry;
nsCString mParentPath;
};
nsDirEnumeratorUnix::nsDirEnumeratorUnix() : mDir(nullptr), mEntry(nullptr) {}
nsDirEnumeratorUnix::~nsDirEnumeratorUnix() { Close(); }
NS_IMPL_ISUPPORTS_INHERITED(nsDirEnumeratorUnix, nsSimpleEnumerator,
nsIDirectoryEnumerator)
NS_IMETHODIMP
nsDirEnumeratorUnix::Init(nsLocalFile* aParent,
bool aResolveSymlinks /*ignored*/) {
nsAutoCString dirPath;
if (NS_FAILED(aParent->GetNativePath(dirPath)) || dirPath.IsEmpty()) {
return NS_ERROR_FILE_INVALID_PATH;
}
// When enumerating the directory, the paths must have a slash at the end.
nsAutoCString dirPathWithSlash(dirPath);
dirPathWithSlash.Append('/');
if (!FilePreferences::IsAllowedPath(dirPathWithSlash)) {
return NS_ERROR_FILE_ACCESS_DENIED;
}
if (NS_FAILED(aParent->GetNativePath(mParentPath))) {
return NS_ERROR_FAILURE;
}
mDir = opendir(dirPath.get());
if (!mDir) {
return NSRESULT_FOR_ERRNO();
}
return GetNextEntry();
}
NS_IMETHODIMP
nsDirEnumeratorUnix::HasMoreElements(bool* aResult) {
*aResult = mDir && mEntry;
if (!*aResult) {
Close();
}
return NS_OK;
}
NS_IMETHODIMP
nsDirEnumeratorUnix::GetNext(nsISupports** aResult) {
nsCOMPtr<nsIFile> file;
nsresult rv = GetNextFile(getter_AddRefs(file));
if (NS_FAILED(rv)) {
return rv;
}
if (!file) {
return NS_ERROR_FAILURE;
}
file.forget(aResult);
return NS_OK;
}
NS_IMETHODIMP
nsDirEnumeratorUnix::GetNextEntry() {
do {
errno = 0;
mEntry = readdir(mDir);
// end of dir or error
if (!mEntry) {
return NSRESULT_FOR_ERRNO();
}
// keep going past "." and ".."
} while (mEntry->d_name[0] == '.' &&
(mEntry->d_name[1] == '\0' || // .\0
(mEntry->d_name[1] == '.' && mEntry->d_name[2] == '\0'))); // ..\0
return NS_OK;
}
NS_IMETHODIMP
nsDirEnumeratorUnix::GetNextFile(nsIFile** aResult) {
nsresult rv;
if (!mDir || !mEntry) {
*aResult = nullptr;
return NS_OK;
}
nsCOMPtr<nsIFile> file = new nsLocalFile();
if (NS_FAILED(rv = file->InitWithNativePath(mParentPath)) ||
NS_FAILED(rv = file->AppendNative(nsDependentCString(mEntry->d_name)))) {
return rv;
}
file.forget(aResult);
return GetNextEntry();
}
NS_IMETHODIMP
nsDirEnumeratorUnix::Close() {
if (mDir) {
closedir(mDir);
mDir = nullptr;
}
return NS_OK;
}
nsLocalFile::nsLocalFile() : mCachedStat() {}
nsLocalFile::nsLocalFile(const nsACString& aFilePath) : mCachedStat() {
InitWithNativePath(aFilePath);
}
nsLocalFile::nsLocalFile(const nsLocalFile& aOther) : mPath(aOther.mPath) {}
#ifdef MOZ_WIDGET_COCOA
NS_IMPL_ISUPPORTS(nsLocalFile, nsILocalFileMac, nsIFile)
#else
NS_IMPL_ISUPPORTS(nsLocalFile, nsIFile)
#endif
nsresult nsLocalFile::nsLocalFileConstructor(const nsIID& aIID,
void** aInstancePtr) {
if (NS_WARN_IF(!aInstancePtr)) {
return NS_ERROR_INVALID_ARG;
}
*aInstancePtr = nullptr;
nsCOMPtr<nsIFile> inst = new nsLocalFile();
return inst->QueryInterface(aIID, aInstancePtr);
}
bool nsLocalFile::FillStatCache() {
if (!FilePreferences::IsAllowedPath(mPath)) {
errno = EACCES;
return false;
}
if (STAT(mPath.get(), &mCachedStat) == -1) {
// try lstat it may be a symlink
if (LSTAT(mPath.get(), &mCachedStat) == -1) {
return false;
}
}
return true;
}
NS_IMETHODIMP
nsLocalFile::Clone(nsIFile** aFile) {
// Just copy-construct ourselves
RefPtr<nsLocalFile> copy = new nsLocalFile(*this);
copy.forget(aFile);
return NS_OK;
}
NS_IMETHODIMP
nsLocalFile::InitWithNativePath(const nsACString& aFilePath) {
if (!aFilePath.IsEmpty() && aFilePath.First() == '~') {
if (aFilePath.Length() == 1 || aFilePath.CharAt(1) == '/') {
// Home dir for the current user
nsCOMPtr<nsIFile> homeDir;
nsAutoCString homePath;
if (NS_FAILED(NS_GetSpecialDirectory(NS_OS_HOME_DIR,
getter_AddRefs(homeDir))) ||
NS_FAILED(homeDir->GetNativePath(homePath))) {
return NS_ERROR_FAILURE;
}
mPath = homePath;
if (aFilePath.Length() > 2) {
mPath.Append(Substring(aFilePath, 1));
}
} else {
// Home dir for an arbitrary user e.g. `~foo/bar` -> `/home/foo/bar`
// (`/Users/foo/bar` on Mac). The accurate way to get this directory
// is with `getpwnam`, but we would like to avoid doing blocking
// filesystem I/O while creating an `nsIFile`.
mPath =
#ifdef XP_MACOSX
"/Users/"_ns
#else
"/home/"_ns
#endif
+ Substring(aFilePath, 1);
}
} else {
if (aFilePath.IsEmpty() || aFilePath.First() != '/') {
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
}
mPath = aFilePath;
}
if (!FilePreferences::IsAllowedPath(mPath)) {
mPath.Truncate();
return NS_ERROR_FILE_ACCESS_DENIED;
}
// trim off trailing slashes
ssize_t len = mPath.Length();
while ((len > 1) && (mPath[len - 1] == '/')) {
--len;
}
mPath.SetLength(len);
return NS_OK;
}
NS_IMETHODIMP
nsLocalFile::CreateAllAncestors(uint32_t aPermissions) {
if (!FilePreferences::IsAllowedPath(mPath)) {
return NS_ERROR_FILE_ACCESS_DENIED;
}
// <jband> I promise to play nice
char* buffer = mPath.BeginWriting();
char* slashp = buffer;
int mkdir_result = 0;
int mkdir_errno;
#ifdef DEBUG_NSIFILE
fprintf(stderr, "nsIFile: before: %s\n", buffer);
#endif
while ((slashp = strchr(slashp + 1, '/'))) {
/*
* Sequences of '/' are equivalent to a single '/'.
*/
if (slashp[1] == '/') {
continue;
}
/*
* If the path has a trailing slash, don't make the last component,
* because we'll get EEXIST in Create when we try to build the final
* component again, and it's easier to condition the logic here than
* there.
*/
if (slashp[1] == '\0') {
break;
}
/* Temporarily NUL-terminate here */
*slashp = '\0';
#ifdef DEBUG_NSIFILE
fprintf(stderr, "nsIFile: mkdir(\"%s\")\n", buffer);
#endif
mkdir_result = mkdir(buffer, aPermissions);
if (mkdir_result == -1) {
mkdir_errno = errno;
/*
* Always set |errno| to EEXIST if the dir already exists
* (we have to do this here since the errno value is not consistent
* in all cases - various reasons like different platform,
* automounter-controlled dir, etc. can affect it (see bug 125489
* for details)).
*/
if (mkdir_errno != EEXIST && access(buffer, F_OK) == 0) {
mkdir_errno = EEXIST;
}
#ifdef DEBUG_NSIFILE
fprintf(stderr, "nsIFile: errno: %d\n", mkdir_errno);
#endif
}
/* Put the / back */
*slashp = '/';
}
/*
* We could get EEXIST for an existing file -- not directory --
* but that's OK: we'll get ENOTDIR when we try to make the final
* component of the path back in Create and error out appropriately.
*/
if (mkdir_result == -1 && mkdir_errno != EEXIST) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
NS_IMETHODIMP
nsLocalFile::OpenNSPRFileDesc(int32_t aFlags, int32_t aMode,
PRFileDesc** aResult) {
if (!FilePreferences::IsAllowedPath(mPath)) {
return NS_ERROR_FILE_ACCESS_DENIED;
}
*aResult = PR_Open(mPath.get(), aFlags, aMode);
if (!*aResult) {
return NS_ErrorAccordingToNSPR();
}
if (aFlags & DELETE_ON_CLOSE) {
PR_Delete(mPath.get());
}
#if defined(HAVE_POSIX_FADVISE)
if (aFlags & OS_READAHEAD) {
posix_fadvise(PR_FileDesc2NativeHandle(*aResult), 0, 0,
POSIX_FADV_SEQUENTIAL);
}
#endif
return NS_OK;
}
NS_IMETHODIMP
nsLocalFile::OpenANSIFileDesc(const char* aMode, FILE** aResult) {
if (!FilePreferences::IsAllowedPath(mPath)) {
return NS_ERROR_FILE_ACCESS_DENIED;
}
*aResult = fopen(mPath.get(), aMode);
if (!*aResult) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
static int do_create(const char* aPath, int aFlags, mode_t aMode,
PRFileDesc** aResult) {
*aResult = PR_Open(aPath, aFlags, aMode);
return *aResult ? 0 : -1;
}
static int do_mkdir(const char* aPath, int aFlags, mode_t aMode,
PRFileDesc** aResult) {
*aResult = nullptr;
return mkdir(aPath, aMode);
}
nsresult nsLocalFile::CreateAndKeepOpen(uint32_t aType, int aFlags,
uint32_t aPermissions,
bool aSkipAncestors,
PRFileDesc** aResult) {
if (!FilePreferences::IsAllowedPath(mPath)) {
return NS_ERROR_FILE_ACCESS_DENIED;
}
if (aType != NORMAL_FILE_TYPE && aType != DIRECTORY_TYPE) {
return NS_ERROR_FILE_UNKNOWN_TYPE;
}
int (*createFunc)(const char*, int, mode_t, PRFileDesc**) =
(aType == NORMAL_FILE_TYPE) ? do_create : do_mkdir;
int result = createFunc(mPath.get(), aFlags, aPermissions, aResult);
if (result == -1 && errno == ENOENT && !aSkipAncestors) {
/*
* If we failed because of missing ancestor components, try to create
* them and then retry the original creation.
*
* Ancestor directories get the same permissions as the file we're
* creating, with the X bit set for each of (user,group,other) with
* an R bit in the original permissions. If you want to do anything
* fancy like setgid or sticky bits, do it by hand.
*/
int dirperm = aPermissions;
if (aPermissions & S_IRUSR) {
dirperm |= S_IXUSR;
}
if (aPermissions & S_IRGRP) {
dirperm |= S_IXGRP;
}
if (aPermissions & S_IROTH) {
dirperm |= S_IXOTH;
}
#ifdef DEBUG_NSIFILE
fprintf(stderr, "nsIFile: perm = %o, dirperm = %o\n", aPermissions,
dirperm);
#endif
if (NS_FAILED(CreateAllAncestors(dirperm))) {
return NS_ERROR_FAILURE;
}
#ifdef DEBUG_NSIFILE
fprintf(stderr, "nsIFile: Create(\"%s\") again\n", mPath.get());
#endif
result = createFunc(mPath.get(), aFlags, aPermissions, aResult);
}
return NSRESULT_FOR_RETURN(result);
}
NS_IMETHODIMP
nsLocalFile::Create(uint32_t aType, uint32_t aPermissions,
bool aSkipAncestors) {
if (!FilePreferences::IsAllowedPath(mPath)) {
return NS_ERROR_FILE_ACCESS_DENIED;
}
PRFileDesc* junk = nullptr;
nsresult rv = CreateAndKeepOpen(
aType, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE | PR_EXCL, aPermissions,
aSkipAncestors, &junk);
if (junk) {
PR_Close(junk);
}
return rv;
}
NS_IMETHODIMP
nsLocalFile::AppendNative(const nsACString& aFragment) {
if (aFragment.IsEmpty()) {
return NS_OK;
}
// only one component of path can be appended and cannot append ".."
nsACString::const_iterator begin, end;
if (aFragment.EqualsASCII("..") ||
FindCharInReadable('/', aFragment.BeginReading(begin),
aFragment.EndReading(end))) {
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
}
return AppendRelativeNativePath(aFragment);
}
NS_IMETHODIMP
nsLocalFile::AppendRelativeNativePath(const nsACString& aFragment) {
if (aFragment.IsEmpty()) {
return NS_OK;
}
// No leading '/' and cannot be ".."
if (aFragment.First() == '/' || aFragment.EqualsASCII("..")) {
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
}
if (aFragment.Contains('/')) {
// can't contain .. as a path component. Ensure that the valid components
// "foo..foo", "..foo", and "foo.." are not falsely detected,
// but the invalid paths "../", "foo/..", "foo/../foo",
// "../foo", etc are.
constexpr auto doubleDot = "/.."_ns;
nsACString::const_iterator start, end, offset;
aFragment.BeginReading(start);
aFragment.EndReading(end);
offset = end;
while (FindInReadable(doubleDot, start, offset)) {
if (offset == end || *offset == '/') {
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
}
start = offset;
offset = end;
}
// catches the remaining cases of prefixes
if (StringBeginsWith(aFragment, "../"_ns)) {
return NS_ERROR_FILE_UNRECOGNIZED_PATH;
}
}
if (!mPath.EqualsLiteral("/")) {
mPath.Append('/');
}
mPath.Append(aFragment);
return NS_OK;
}
NS_IMETHODIMP
nsLocalFile::Normalize() {
char resolved_path[PATH_MAX] = "";
char* resolved_path_ptr = nullptr;
if (!FilePreferences::IsAllowedPath(mPath)) {
return NS_ERROR_FILE_ACCESS_DENIED;
}
resolved_path_ptr = realpath(mPath.get(), resolved_path);
// if there is an error, the return is null.
if (!resolved_path_ptr) {
return NSRESULT_FOR_ERRNO();
}
mPath = resolved_path;
return NS_OK;
}
void nsLocalFile::LocateNativeLeafName(nsACString::const_iterator& aBegin,
nsACString::const_iterator& aEnd) {
// XXX perhaps we should cache this??
mPath.BeginReading(aBegin);
mPath.EndReading(aEnd);
nsACString::const_iterator it = aEnd;
nsACString::const_iterator stop = aBegin;
--stop;
while (--it != stop) {
if (*it == '/') {
aBegin = ++it;
return;
}
}
// else, the entire path is the leaf name (which means this
// isn't an absolute path... unexpected??)
}
NS_IMETHODIMP
nsLocalFile::GetNativeLeafName(nsACString& aLeafName) {
nsACString::const_iterator begin, end;
LocateNativeLeafName(begin, end);
aLeafName = Substring(begin, end);
return NS_OK;
}
NS_IMETHODIMP
nsLocalFile::SetNativeLeafName(const nsACString& aLeafName) {
nsACString::const_iterator begin, end;
LocateNativeLeafName(begin, end);
mPath.Replace(begin.get() - mPath.get(), Distance(begin, end), aLeafName);
return NS_OK;
}
NS_IMETHODIMP
nsLocalFile::GetDisplayName(nsAString& aLeafName) {
return GetLeafName(aLeafName);
}
nsCString nsLocalFile::NativePath() { return mPath; }
nsresult nsIFile::GetNativePath(nsACString& aResult) {
aResult = NativePath();
return NS_OK;
}
nsCString nsIFile::HumanReadablePath() {
nsCString path;
DebugOnly<nsresult> rv = GetNativePath(path);
MOZ_ASSERT(NS_SUCCEEDED(rv));
return path;
}
nsresult nsLocalFile::GetNativeTargetPathName(nsIFile* aNewParent,
const nsACString& aNewName,
nsACString& aResult) {
nsresult rv;
nsCOMPtr<nsIFile> oldParent;
if (!aNewParent) {
if (NS_FAILED(rv = GetParent(getter_AddRefs(oldParent)))) {
return rv;
}
aNewParent = oldParent.get();
} else {
// check to see if our target directory exists
bool targetExists;
if (NS_FAILED(rv = aNewParent->Exists(&targetExists))) {
return rv;
}
if (!targetExists) {
// XXX create the new directory with some permissions
rv = aNewParent->Create(DIRECTORY_TYPE, 0755);
if (NS_FAILED(rv)) {
return rv;
}
} else {
// make sure that the target is actually a directory
bool targetIsDirectory;
if (NS_FAILED(rv = aNewParent->IsDirectory(&targetIsDirectory))) {
return rv;
}
if (!targetIsDirectory) {
return NS_ERROR_FILE_DESTINATION_NOT_DIR;
}
}
}
nsACString::const_iterator nameBegin, nameEnd;
if (!aNewName.IsEmpty()) {
aNewName.BeginReading(nameBegin);
aNewName.EndReading(nameEnd);
} else {
LocateNativeLeafName(nameBegin, nameEnd);
}
nsAutoCString dirName;
if (NS_FAILED(rv = aNewParent->GetNativePath(dirName))) {
return rv;
}
aResult = dirName + "/"_ns + Substring(nameBegin, nameEnd);
return NS_OK;
}
nsresult nsLocalFile::CopyDirectoryTo(nsIFile* aNewParent) {
nsresult rv;
/*
* dirCheck is used for various boolean test results such as from Equals,
* Exists, isDir, etc.
*/
bool dirCheck, isSymlink;
uint32_t oldPerms;
if (NS_FAILED(rv = IsDirectory(&dirCheck))) {
return rv;
}
if (!dirCheck) {
return CopyToNative(aNewParent, ""_ns);
}
if (NS_FAILED(rv = Equals(aNewParent, &dirCheck))) {
return rv;
}
if (dirCheck) {
// can't copy dir to itself
return NS_ERROR_INVALID_ARG;
}
if (NS_FAILED(rv = aNewParent->Exists(&dirCheck))) {
return rv;
}
// get the dirs old permissions
if (NS_FAILED(rv = GetPermissions(&oldPerms))) {
return rv;
}
if (!dirCheck) {
if (NS_FAILED(rv = aNewParent->Create(DIRECTORY_TYPE, oldPerms))) {
return rv;
}
} else { // dir exists lets try to use leaf
nsAutoCString leafName;
if (NS_FAILED(rv = GetNativeLeafName(leafName))) {
return rv;
}
if (NS_FAILED(rv = aNewParent->AppendNative(leafName))) {
return rv;
}
if (NS_FAILED(rv = aNewParent->Exists(&dirCheck))) {
return rv;
}
if (dirCheck) {
return NS_ERROR_FILE_ALREADY_EXISTS; // dest exists
}
if (NS_FAILED(rv = aNewParent->Create(DIRECTORY_TYPE, oldPerms))) {
return rv;
}
}
nsCOMPtr<nsIDirectoryEnumerator> dirIterator;
if (NS_FAILED(rv = GetDirectoryEntries(getter_AddRefs(dirIterator)))) {
return rv;
}
nsCOMPtr<nsIFile> entry;
while (NS_SUCCEEDED(dirIterator->GetNextFile(getter_AddRefs(entry))) &&
entry) {
if (NS_FAILED(rv = entry->IsSymlink(&isSymlink))) {
return rv;
}
if (NS_FAILED(rv = entry->IsDirectory(&dirCheck))) {
return rv;
}
if (dirCheck && !isSymlink) {
nsCOMPtr<nsIFile> destClone;
rv = aNewParent->Clone(getter_AddRefs(destClone));
if (NS_SUCCEEDED(rv)) {
if (NS_FAILED(rv = entry->CopyToNative(destClone, ""_ns))) {
#ifdef DEBUG
nsresult rv2;
nsAutoCString pathName;
if (NS_FAILED(rv2 = entry->GetNativePath(pathName))) {
return rv2;
}
printf("Operation not supported: %s\n", pathName.get());
#endif
if (rv == NS_ERROR_OUT_OF_MEMORY) {
return rv;
}
continue;
}
}
} else {
if (NS_FAILED(rv = entry->CopyToNative(aNewParent, ""_ns))) {
#ifdef DEBUG
nsresult rv2;
nsAutoCString pathName;
if (NS_FAILED(rv2 = entry->GetNativePath(pathName))) {
return rv2;
}
printf("Operation not supported: %s\n", pathName.get());
#endif
if (rv == NS_ERROR_OUT_OF_MEMORY) {
return rv;
}
continue;
}
}
}
return NS_OK;
}
NS_IMETHODIMP
nsLocalFile::CopyToNative(nsIFile* aNewParent, const nsACString& aNewName) {
nsresult rv;
// check to make sure that this has been initialized properly
CHECK_mPath();
// we copy the parent here so 'aNewParent' remains immutable
nsCOMPtr<nsIFile> workParent;
if (aNewParent) {
if (NS_FAILED(rv = aNewParent->Clone(getter_AddRefs(workParent)))) {
return rv;
}
} else {
if (NS_FAILED(rv = GetParent(getter_AddRefs(workParent)))) {
return rv;
}
}
// check to see if we are a directory or if we are a file
bool isDirectory;
if (NS_FAILED(rv = IsDirectory(&isDirectory))) {
return rv;
}
nsAutoCString newPathName;
if (isDirectory) {
if (!aNewName.IsEmpty()) {
if (NS_FAILED(rv = workParent->AppendNative(aNewName))) {
return rv;
}
} else {
if (NS_FAILED(rv = GetNativeLeafName(newPathName))) {
return rv;
}
if (NS_FAILED(rv = workParent->AppendNative(newPathName))) {
return rv;
}
}
if (NS_FAILED(rv = CopyDirectoryTo(workParent))) {
return rv;
}
} else {
rv = GetNativeTargetPathName(workParent, aNewName, newPathName);
if (NS_FAILED(rv)) {
return rv;
}
#ifdef DEBUG_blizzard
printf("nsLocalFile::CopyTo() %s -> %s\n", mPath.get(), newPathName.get());
#endif
// actually create the file.
auto* newFile = new nsLocalFile();
nsCOMPtr<nsIFile> fileRef(newFile); // release on exit
rv = newFile->InitWithNativePath(newPathName);
if (NS_FAILED(rv)) {
return rv;
}
// get the old permissions
uint32_t myPerms = 0;
rv = GetPermissions(&myPerms);
if (NS_FAILED(rv)) {
return rv;
}
// Create the new file with the old file's permissions, even if write
// permission is missing. We can't create with write permission and
// then change back to myPerm on all filesystems (FAT on Linux, e.g.).
// But we can write to a read-only file on all Unix filesystems if we
// open it successfully for writing.
PRFileDesc* newFD;
rv = newFile->CreateAndKeepOpen(
NORMAL_FILE_TYPE, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, myPerms,
/* aSkipAncestors = */ false, &newFD);
if (NS_FAILED(rv)) {
return rv;
}
// open the old file, too
bool specialFile;
if (NS_FAILED(rv = IsSpecial(&specialFile))) {
PR_Close(newFD);
return rv;
}
if (specialFile) {
#ifdef DEBUG
printf("Operation not supported: %s\n", mPath.get());
#endif
// make sure to clean up properly
PR_Close(newFD);
return NS_OK;
}
#if defined(XP_MACOSX)
bool quarantined = true;
(void)HasXAttr("com.apple.quarantine"_ns, &quarantined);
#endif
PRFileDesc* oldFD;
rv = OpenNSPRFileDesc(PR_RDONLY, myPerms, &oldFD);
if (NS_FAILED(rv)) {
// make sure to clean up properly
PR_Close(newFD);
return rv;
}
#ifdef DEBUG_blizzard
int32_t totalRead = 0;
int32_t totalWritten = 0;
#endif
char buf[BUFSIZ];
int32_t bytesRead;
// record PR_Write() error for better error message later.
nsresult saved_write_error = NS_OK;
nsresult saved_read_error = NS_OK;
nsresult saved_read_close_error = NS_OK;
nsresult saved_write_close_error = NS_OK;
// DONE: Does PR_Read() return bytesRead < 0 for error?
// Yes., The errors from PR_Read are not so common and
// the value may not have correspondence in NS_ERROR_*, but
// we do catch it still, immediately after while() loop.
// We can differentiate errors pf PR_Read and PR_Write by
// looking at saved_write_error value. If PR_Write error occurs (and not
// PR_Read() error), save_write_error is not NS_OK.
while ((bytesRead = PR_Read(oldFD, buf, BUFSIZ)) > 0) {
#ifdef DEBUG_blizzard
totalRead += bytesRead;
#endif
// PR_Write promises never to do a short write
int32_t bytesWritten = PR_Write(newFD, buf, bytesRead);
if (bytesWritten < 0) {
saved_write_error = NSRESULT_FOR_ERRNO();
bytesRead = -1;
break;
}
NS_ASSERTION(bytesWritten == bytesRead, "short PR_Write?");
#ifdef DEBUG_blizzard
totalWritten += bytesWritten;
#endif
}
// TODO/FIXME: If CIFS (and NFS?) may force read/write to return EINTR,
// we are better off to prepare for retrying. But we need confirmation if