Source code

Revision control

Other Tools

1
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* This Source Code Form is subject to the terms of the Mozilla Public
3
* License, v. 2.0. If a copy of the MPL was not distributed with this
4
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6
#include "ipc/IPCMessageUtils.h"
7
8
#if defined(XP_UNIX) || defined(XP_BEOS)
9
# include <unistd.h>
10
#elif defined(XP_WIN)
11
# include <windows.h>
12
# include "nsILocalFileWin.h"
13
#else
14
// XXX add necessary include file for ftruncate (or equivalent)
15
#endif
16
17
#include "private/pprio.h"
18
#include "prerror.h"
19
20
#include "IOActivityMonitor.h"
21
#include "nsFileStreams.h"
22
#include "nsIFile.h"
23
#include "nsReadLine.h"
24
#include "nsIClassInfoImpl.h"
25
#include "nsLiteralString.h"
26
#include "nsSocketTransport2.h" // for ErrorAccordingToNSPR()
27
#include "mozilla/ipc/InputStreamUtils.h"
28
#include "mozilla/Unused.h"
29
#include "mozilla/FileUtils.h"
30
#include "nsNetCID.h"
31
#include "nsXULAppAPI.h"
32
33
typedef mozilla::ipc::FileDescriptor::PlatformHandleType FileHandleType;
34
35
using namespace mozilla::ipc;
36
using namespace mozilla::net;
37
38
using mozilla::DebugOnly;
39
using mozilla::Maybe;
40
using mozilla::Nothing;
41
using mozilla::Some;
42
43
////////////////////////////////////////////////////////////////////////////////
44
// nsFileStreamBase
45
46
nsFileStreamBase::nsFileStreamBase()
47
: mFD(nullptr),
48
mBehaviorFlags(0),
49
mState(eUnitialized),
50
mErrorValue(NS_ERROR_FAILURE) {}
51
52
nsFileStreamBase::~nsFileStreamBase() {
53
// We don't want to try to rewrind the stream when shutting down.
54
mBehaviorFlags &= ~nsIFileInputStream::REOPEN_ON_REWIND;
55
56
Close();
57
}
58
59
NS_IMPL_ISUPPORTS(nsFileStreamBase, nsISeekableStream, nsITellableStream,
60
nsIFileMetadata)
61
62
NS_IMETHODIMP
63
nsFileStreamBase::Seek(int32_t whence, int64_t offset) {
64
nsresult rv = DoPendingOpen();
65
NS_ENSURE_SUCCESS(rv, rv);
66
67
int64_t cnt = PR_Seek64(mFD, offset, (PRSeekWhence)whence);
68
if (cnt == int64_t(-1)) {
69
return NS_ErrorAccordingToNSPR();
70
}
71
return NS_OK;
72
}
73
74
NS_IMETHODIMP
75
nsFileStreamBase::Tell(int64_t* result) {
76
nsresult rv = DoPendingOpen();
77
NS_ENSURE_SUCCESS(rv, rv);
78
79
int64_t cnt = PR_Seek64(mFD, 0, PR_SEEK_CUR);
80
if (cnt == int64_t(-1)) {
81
return NS_ErrorAccordingToNSPR();
82
}
83
*result = cnt;
84
return NS_OK;
85
}
86
87
NS_IMETHODIMP
88
nsFileStreamBase::SetEOF() {
89
nsresult rv = DoPendingOpen();
90
NS_ENSURE_SUCCESS(rv, rv);
91
92
#if defined(XP_UNIX) || defined(XP_BEOS)
93
// Some system calls require an EOF offset.
94
int64_t offset;
95
rv = Tell(&offset);
96
if (NS_FAILED(rv)) return rv;
97
#endif
98
99
#if defined(XP_UNIX) || defined(XP_BEOS)
100
if (ftruncate(PR_FileDesc2NativeHandle(mFD), offset) != 0) {
101
NS_ERROR("ftruncate failed");
102
return NS_ERROR_FAILURE;
103
}
104
#elif defined(XP_WIN)
105
if (!SetEndOfFile((HANDLE)PR_FileDesc2NativeHandle(mFD))) {
106
NS_ERROR("SetEndOfFile failed");
107
return NS_ERROR_FAILURE;
108
}
109
#else
110
// XXX not implemented
111
#endif
112
113
return NS_OK;
114
}
115
116
NS_IMETHODIMP
117
nsFileStreamBase::GetSize(int64_t* _retval) {
118
nsresult rv = DoPendingOpen();
119
NS_ENSURE_SUCCESS(rv, rv);
120
121
PRFileInfo64 info;
122
if (PR_GetOpenFileInfo64(mFD, &info) == PR_FAILURE) {
123
return NS_BASE_STREAM_OSERROR;
124
}
125
126
*_retval = int64_t(info.size);
127
128
return NS_OK;
129
}
130
131
NS_IMETHODIMP
132
nsFileStreamBase::GetLastModified(int64_t* _retval) {
133
nsresult rv = DoPendingOpen();
134
NS_ENSURE_SUCCESS(rv, rv);
135
136
PRFileInfo64 info;
137
if (PR_GetOpenFileInfo64(mFD, &info) == PR_FAILURE) {
138
return NS_BASE_STREAM_OSERROR;
139
}
140
141
int64_t modTime = int64_t(info.modifyTime);
142
if (modTime == 0) {
143
*_retval = 0;
144
} else {
145
*_retval = modTime / int64_t(PR_USEC_PER_MSEC);
146
}
147
148
return NS_OK;
149
}
150
151
NS_IMETHODIMP
152
nsFileStreamBase::GetFileDescriptor(PRFileDesc** _retval) {
153
nsresult rv = DoPendingOpen();
154
NS_ENSURE_SUCCESS(rv, rv);
155
156
*_retval = mFD;
157
return NS_OK;
158
}
159
160
nsresult nsFileStreamBase::Close() {
161
CleanUpOpen();
162
163
nsresult rv = NS_OK;
164
if (mFD) {
165
if (PR_Close(mFD) == PR_FAILURE) rv = NS_BASE_STREAM_OSERROR;
166
mFD = nullptr;
167
mState = eClosed;
168
}
169
return rv;
170
}
171
172
nsresult nsFileStreamBase::Available(uint64_t* aResult) {
173
nsresult rv = DoPendingOpen();
174
NS_ENSURE_SUCCESS(rv, rv);
175
176
// PR_Available with files over 4GB returns an error, so we have to
177
// use the 64-bit version of PR_Available.
178
int64_t avail = PR_Available64(mFD);
179
if (avail == -1) {
180
return NS_ErrorAccordingToNSPR();
181
}
182
183
// If available is greater than 4GB, return 4GB
184
*aResult = (uint64_t)avail;
185
return NS_OK;
186
}
187
188
nsresult nsFileStreamBase::Read(char* aBuf, uint32_t aCount,
189
uint32_t* aResult) {
190
nsresult rv = DoPendingOpen();
191
if (rv == NS_BASE_STREAM_CLOSED) {
192
*aResult = 0;
193
return NS_OK;
194
}
195
196
if (NS_FAILED(rv)) {
197
return rv;
198
}
199
200
int32_t bytesRead = PR_Read(mFD, aBuf, aCount);
201
if (bytesRead == -1) {
202
return NS_ErrorAccordingToNSPR();
203
}
204
205
*aResult = bytesRead;
206
return NS_OK;
207
}
208
209
nsresult nsFileStreamBase::ReadSegments(nsWriteSegmentFun aWriter,
210
void* aClosure, uint32_t aCount,
211
uint32_t* aResult) {
212
// ReadSegments is not implemented because it would be inefficient when
213
// the writer does not consume all data. If you want to call ReadSegments,
214
// wrap a BufferedInputStream around the file stream. That will call
215
// Read().
216
217
return NS_ERROR_NOT_IMPLEMENTED;
218
}
219
220
nsresult nsFileStreamBase::IsNonBlocking(bool* aNonBlocking) {
221
*aNonBlocking = false;
222
return NS_OK;
223
}
224
225
nsresult nsFileStreamBase::Flush(void) {
226
nsresult rv = DoPendingOpen();
227
NS_ENSURE_SUCCESS(rv, rv);
228
229
int32_t cnt = PR_Sync(mFD);
230
if (cnt == -1) {
231
return NS_ErrorAccordingToNSPR();
232
}
233
return NS_OK;
234
}
235
236
nsresult nsFileStreamBase::Write(const char* buf, uint32_t count,
237
uint32_t* result) {
238
nsresult rv = DoPendingOpen();
239
NS_ENSURE_SUCCESS(rv, rv);
240
241
int32_t cnt = PR_Write(mFD, buf, count);
242
if (cnt == -1) {
243
return NS_ErrorAccordingToNSPR();
244
}
245
*result = cnt;
246
return NS_OK;
247
}
248
249
nsresult nsFileStreamBase::WriteFrom(nsIInputStream* inStr, uint32_t count,
250
uint32_t* _retval) {
251
MOZ_ASSERT_UNREACHABLE("WriteFrom (see source comment)");
252
return NS_ERROR_NOT_IMPLEMENTED;
253
// File streams intentionally do not support this method.
254
// If you need something like this, then you should wrap
255
// the file stream using nsIBufferedOutputStream
256
}
257
258
nsresult nsFileStreamBase::WriteSegments(nsReadSegmentFun reader, void* closure,
259
uint32_t count, uint32_t* _retval) {
260
return NS_ERROR_NOT_IMPLEMENTED;
261
// File streams intentionally do not support this method.
262
// If you need something like this, then you should wrap
263
// the file stream using nsIBufferedOutputStream
264
}
265
266
nsresult nsFileStreamBase::MaybeOpen(nsIFile* aFile, int32_t aIoFlags,
267
int32_t aPerm, bool aDeferred) {
268
NS_ENSURE_STATE(aFile);
269
270
mOpenParams.ioFlags = aIoFlags;
271
mOpenParams.perm = aPerm;
272
273
if (aDeferred) {
274
// Clone the file, as it may change between now and the deferred open
275
nsCOMPtr<nsIFile> file;
276
nsresult rv = aFile->Clone(getter_AddRefs(file));
277
NS_ENSURE_SUCCESS(rv, rv);
278
279
mOpenParams.localFile = file.forget();
280
NS_ENSURE_TRUE(mOpenParams.localFile, NS_ERROR_UNEXPECTED);
281
282
mState = eDeferredOpen;
283
return NS_OK;
284
}
285
286
mOpenParams.localFile = aFile;
287
288
// Following call open() at main thread.
289
// Main thread might be blocked, while open a remote file.
290
return DoOpen();
291
}
292
293
void nsFileStreamBase::CleanUpOpen() { mOpenParams.localFile = nullptr; }
294
295
nsresult nsFileStreamBase::DoOpen() {
296
MOZ_ASSERT(mState == eDeferredOpen || mState == eUnitialized ||
297
mState == eClosed);
298
NS_ASSERTION(!mFD, "Already have a file descriptor!");
299
NS_ASSERTION(mOpenParams.localFile, "Must have a file to open");
300
301
PRFileDesc* fd;
302
nsresult rv;
303
304
if (mOpenParams.ioFlags & PR_CREATE_FILE) {
305
nsCOMPtr<nsIFile> parent;
306
mOpenParams.localFile->GetParent(getter_AddRefs(parent));
307
308
// Result doesn't need to be checked. If the file's parent path does not
309
// exist, make it. If it does exist, do nothing.
310
if (parent) {
311
Unused << parent->Create(nsIFile::DIRECTORY_TYPE, 0755);
312
}
313
}
314
315
#ifdef XP_WIN
316
if (mBehaviorFlags & nsIFileInputStream::SHARE_DELETE) {
317
nsCOMPtr<nsILocalFileWin> file = do_QueryInterface(mOpenParams.localFile);
318
MOZ_ASSERT(file);
319
320
rv = file->OpenNSPRFileDescShareDelete(mOpenParams.ioFlags,
321
mOpenParams.perm, &fd);
322
} else
323
#endif // XP_WIN
324
{
325
rv = mOpenParams.localFile->OpenNSPRFileDesc(mOpenParams.ioFlags,
326
mOpenParams.perm, &fd);
327
}
328
329
if (rv == NS_OK && IOActivityMonitor::IsActive()) {
330
auto nativePath = mOpenParams.localFile->NativePath();
331
if (!nativePath.IsEmpty()) {
332
// registering the file to the activity monitor
333
#ifdef XP_WIN
334
// 16 bits unicode
335
IOActivityMonitor::MonitorFile(
336
fd, NS_ConvertUTF16toUTF8(nativePath.get()).get());
337
#else
338
// 8 bit unicode
339
IOActivityMonitor::MonitorFile(fd, nativePath.get());
340
#endif
341
}
342
}
343
344
CleanUpOpen();
345
346
if (NS_FAILED(rv)) {
347
mState = eError;
348
mErrorValue = rv;
349
return rv;
350
}
351
352
mFD = fd;
353
mState = eOpened;
354
355
return NS_OK;
356
}
357
358
nsresult nsFileStreamBase::DoPendingOpen() {
359
switch (mState) {
360
case eUnitialized:
361
MOZ_CRASH("This should not happen.");
362
return NS_ERROR_FAILURE;
363
364
case eDeferredOpen:
365
return DoOpen();
366
367
case eOpened:
368
MOZ_ASSERT(mFD);
369
if (NS_WARN_IF(!mFD)) {
370
return NS_ERROR_FAILURE;
371
}
372
return NS_OK;
373
374
case eClosed:
375
MOZ_ASSERT(!mFD);
376
return NS_BASE_STREAM_CLOSED;
377
378
case eError:
379
return mErrorValue;
380
}
381
382
MOZ_CRASH("Invalid mState value.");
383
return NS_ERROR_FAILURE;
384
}
385
386
////////////////////////////////////////////////////////////////////////////////
387
// nsFileInputStream
388
389
NS_IMPL_ADDREF_INHERITED(nsFileInputStream, nsFileStreamBase)
390
NS_IMPL_RELEASE_INHERITED(nsFileInputStream, nsFileStreamBase)
391
392
NS_IMPL_CLASSINFO(nsFileInputStream, nullptr, nsIClassInfo::THREADSAFE,
393
NS_LOCALFILEINPUTSTREAM_CID)
394
395
NS_INTERFACE_MAP_BEGIN(nsFileInputStream)
396
NS_INTERFACE_MAP_ENTRY(nsIInputStream)
397
NS_INTERFACE_MAP_ENTRY(nsIFileInputStream)
398
NS_INTERFACE_MAP_ENTRY(nsILineInputStream)
399
NS_INTERFACE_MAP_ENTRY(nsIIPCSerializableInputStream)
400
NS_IMPL_QUERY_CLASSINFO(nsFileInputStream)
401
NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsICloneableInputStream, IsCloneable())
402
NS_INTERFACE_MAP_END_INHERITING(nsFileStreamBase)
403
404
NS_IMPL_CI_INTERFACE_GETTER(nsFileInputStream, nsIInputStream,
405
nsIFileInputStream, nsISeekableStream,
406
nsITellableStream, nsILineInputStream)
407
408
nsresult nsFileInputStream::Create(nsISupports* aOuter, REFNSIID aIID,
409
void** aResult) {
410
NS_ENSURE_NO_AGGREGATION(aOuter);
411
412
RefPtr<nsFileInputStream> stream = new nsFileInputStream();
413
return stream->QueryInterface(aIID, aResult);
414
}
415
416
nsresult nsFileInputStream::Open(nsIFile* aFile, int32_t aIOFlags,
417
int32_t aPerm) {
418
nsresult rv = NS_OK;
419
420
// If the previous file is open, close it
421
if (mFD) {
422
rv = Close();
423
if (NS_FAILED(rv)) return rv;
424
}
425
426
// Open the file
427
if (aIOFlags == -1) aIOFlags = PR_RDONLY;
428
if (aPerm == -1) aPerm = 0;
429
430
return MaybeOpen(aFile, aIOFlags, aPerm,
431
mBehaviorFlags & nsIFileInputStream::DEFER_OPEN);
432
}
433
434
NS_IMETHODIMP
435
nsFileInputStream::Init(nsIFile* aFile, int32_t aIOFlags, int32_t aPerm,
436
int32_t aBehaviorFlags) {
437
NS_ENSURE_TRUE(!mFD, NS_ERROR_ALREADY_INITIALIZED);
438
NS_ENSURE_TRUE(mState == eUnitialized || mState == eClosed,
439
NS_ERROR_ALREADY_INITIALIZED);
440
441
mBehaviorFlags = aBehaviorFlags;
442
mState = eUnitialized;
443
444
mFile = aFile;
445
mIOFlags = aIOFlags;
446
mPerm = aPerm;
447
448
return Open(aFile, aIOFlags, aPerm);
449
}
450
451
NS_IMETHODIMP
452
nsFileInputStream::Close() {
453
// Get the cache position at the time the file was close. This allows
454
// NS_SEEK_CUR on a closed file that has been opened with
455
// REOPEN_ON_REWIND.
456
if (mBehaviorFlags & REOPEN_ON_REWIND) {
457
// Get actual position. Not one modified by subclasses
458
nsFileStreamBase::Tell(&mCachedPosition);
459
}
460
461
// null out mLineBuffer in case Close() is called again after failing
462
mLineBuffer = nullptr;
463
return nsFileStreamBase::Close();
464
}
465
466
NS_IMETHODIMP
467
nsFileInputStream::Read(char* aBuf, uint32_t aCount, uint32_t* _retval) {
468
nsresult rv = nsFileStreamBase::Read(aBuf, aCount, _retval);
469
if (rv == NS_ERROR_FILE_NOT_FOUND) {
470
// Don't warn if this is a deffered file not found.
471
return rv;
472
}
473
474
NS_ENSURE_SUCCESS(rv, rv);
475
476
// Check if we're at the end of file and need to close
477
if (mBehaviorFlags & CLOSE_ON_EOF && *_retval == 0) {
478
Close();
479
}
480
481
return NS_OK;
482
}
483
484
NS_IMETHODIMP
485
nsFileInputStream::ReadLine(nsACString& aLine, bool* aResult) {
486
if (!mLineBuffer) {
487
mLineBuffer = new nsLineBuffer<char>;
488
}
489
return NS_ReadLine(this, mLineBuffer.get(), aLine, aResult);
490
}
491
492
NS_IMETHODIMP
493
nsFileInputStream::Seek(int32_t aWhence, int64_t aOffset) {
494
return SeekInternal(aWhence, aOffset);
495
}
496
497
nsresult nsFileInputStream::SeekInternal(int32_t aWhence, int64_t aOffset,
498
bool aClearBuf) {
499
nsresult rv = DoPendingOpen();
500
if (rv != NS_OK && rv != NS_BASE_STREAM_CLOSED) {
501
return rv;
502
}
503
504
if (aClearBuf) {
505
mLineBuffer = nullptr;
506
}
507
508
if (rv == NS_BASE_STREAM_CLOSED) {
509
if (mBehaviorFlags & REOPEN_ON_REWIND) {
510
rv = Open(mFile, mIOFlags, mPerm);
511
NS_ENSURE_SUCCESS(rv, rv);
512
513
// If the file was closed, and we do a relative seek, use the
514
// position we cached when we closed the file to seek to the right
515
// location.
516
if (aWhence == NS_SEEK_CUR) {
517
aWhence = NS_SEEK_SET;
518
aOffset += mCachedPosition;
519
}
520
} else {
521
return NS_BASE_STREAM_CLOSED;
522
}
523
}
524
525
return nsFileStreamBase::Seek(aWhence, aOffset);
526
}
527
528
NS_IMETHODIMP
529
nsFileInputStream::Tell(int64_t* aResult) {
530
return nsFileStreamBase::Tell(aResult);
531
}
532
533
NS_IMETHODIMP
534
nsFileInputStream::Available(uint64_t* aResult) {
535
return nsFileStreamBase::Available(aResult);
536
}
537
538
void nsFileInputStream::Serialize(InputStreamParams& aParams,
539
FileDescriptorArray& aFileDescriptors,
540
bool aDelayedStart, uint32_t aMaxSize,
541
uint32_t* aSizeUsed,
542
mozilla::dom::ContentChild* aManager) {
543
MOZ_ASSERT(aSizeUsed);
544
*aSizeUsed = 0;
545
546
SerializeInternal(aParams, aFileDescriptors);
547
}
548
549
void nsFileInputStream::Serialize(InputStreamParams& aParams,
550
FileDescriptorArray& aFileDescriptors,
551
bool aDelayedStart, uint32_t aMaxSize,
552
uint32_t* aSizeUsed,
553
PBackgroundChild* aManager) {
554
MOZ_ASSERT(aSizeUsed);
555
*aSizeUsed = 0;
556
557
SerializeInternal(aParams, aFileDescriptors);
558
}
559
560
void nsFileInputStream::Serialize(InputStreamParams& aParams,
561
FileDescriptorArray& aFileDescriptors,
562
bool aDelayedStart, uint32_t aMaxSize,
563
uint32_t* aSizeUsed,
564
mozilla::dom::ContentParent* aManager) {
565
MOZ_ASSERT(aSizeUsed);
566
*aSizeUsed = 0;
567
568
SerializeInternal(aParams, aFileDescriptors);
569
}
570
571
void nsFileInputStream::Serialize(InputStreamParams& aParams,
572
FileDescriptorArray& aFileDescriptors,
573
bool aDelayedStart, uint32_t aMaxSize,
574
uint32_t* aSizeUsed,
575
PBackgroundParent* aManager) {
576
MOZ_ASSERT(aSizeUsed);
577
*aSizeUsed = 0;
578
579
SerializeInternal(aParams, aFileDescriptors);
580
}
581
582
void nsFileInputStream::SerializeInternal(
583
InputStreamParams& aParams, FileDescriptorArray& aFileDescriptors) {
584
FileInputStreamParams params;
585
586
if (NS_SUCCEEDED(DoPendingOpen())) {
587
MOZ_ASSERT(mFD);
588
FileHandleType fd = FileHandleType(PR_FileDesc2NativeHandle(mFD));
589
NS_ASSERTION(fd, "This should never be null!");
590
591
DebugOnly<FileDescriptor*> dbgFD = aFileDescriptors.AppendElement(fd);
592
NS_ASSERTION(dbgFD->IsValid(), "Sending an invalid file descriptor!");
593
594
params.fileDescriptorIndex() = aFileDescriptors.Length() - 1;
595
596
Close();
597
} else {
598
NS_WARNING(
599
"This file has not been opened (or could not be opened). "
600
"Sending an invalid file descriptor to the other process!");
601
602
params.fileDescriptorIndex() = UINT32_MAX;
603
}
604
605
int32_t behaviorFlags = mBehaviorFlags;
606
607
// The receiving process (or thread) is going to have an open file
608
// descriptor automatically so transferring this flag is meaningless.
609
behaviorFlags &= ~nsIFileInputStream::DEFER_OPEN;
610
611
params.behaviorFlags() = behaviorFlags;
612
params.ioFlags() = mIOFlags;
613
614
aParams = params;
615
}
616
617
bool nsFileInputStream::Deserialize(
618
const InputStreamParams& aParams,
619
const FileDescriptorArray& aFileDescriptors) {
620
NS_ASSERTION(!mFD, "Already have a file descriptor?!");
621
NS_ASSERTION(mState == nsFileStreamBase::eUnitialized, "Deferring open?!");
622
NS_ASSERTION(!mFile, "Should never have a file here!");
623
NS_ASSERTION(!mPerm, "This should always be 0!");
624
625
if (aParams.type() != InputStreamParams::TFileInputStreamParams) {
626
NS_WARNING("Received unknown parameters from the other process!");
627
return false;
628
}
629
630
const FileInputStreamParams& params = aParams.get_FileInputStreamParams();
631
632
uint32_t fileDescriptorIndex = params.fileDescriptorIndex();
633
634
FileDescriptor fd;
635
if (fileDescriptorIndex < aFileDescriptors.Length()) {
636
fd = aFileDescriptors[fileDescriptorIndex];
637
NS_WARNING_ASSERTION(fd.IsValid(), "Received an invalid file descriptor!");
638
} else {
639
NS_WARNING("Received a bad file descriptor index!");
640
}
641
642
if (fd.IsValid()) {
643
auto rawFD = fd.ClonePlatformHandle();
644
PRFileDesc* fileDesc = PR_ImportFile(PROsfd(rawFD.release()));
645
if (!fileDesc) {
646
NS_WARNING("Failed to import file handle!");
647
return false;
648
}
649
mFD = fileDesc;
650
mState = eOpened;
651
} else {
652
mState = eError;
653
mErrorValue = NS_ERROR_FILE_NOT_FOUND;
654
}
655
656
mBehaviorFlags = params.behaviorFlags();
657
658
if (!XRE_IsParentProcess()) {
659
// A child process shouldn't close when it reads the end because it will
660
// not be able to reopen the file later.
661
mBehaviorFlags &= ~nsIFileInputStream::CLOSE_ON_EOF;
662
663
// A child process will not be able to reopen the file so this flag is
664
// meaningless.
665
mBehaviorFlags &= ~nsIFileInputStream::REOPEN_ON_REWIND;
666
}
667
668
mIOFlags = params.ioFlags();
669
670
return true;
671
}
672
673
bool nsFileInputStream::IsCloneable() const {
674
// This inputStream is cloneable only if has been created using Init() and
675
// it owns a nsIFile. This is not true when it is deserialized from IPC.
676
return XRE_IsParentProcess() && mFile;
677
}
678
679
NS_IMETHODIMP
680
nsFileInputStream::GetCloneable(bool* aCloneable) {
681
*aCloneable = IsCloneable();
682
return NS_OK;
683
}
684
685
NS_IMETHODIMP
686
nsFileInputStream::Clone(nsIInputStream** aResult) {
687
MOZ_ASSERT(IsCloneable());
688
return NS_NewLocalFileInputStream(aResult, mFile, mIOFlags, mPerm,
689
mBehaviorFlags);
690
}
691
692
////////////////////////////////////////////////////////////////////////////////
693
// nsFileOutputStream
694
695
NS_IMPL_ISUPPORTS_INHERITED(nsFileOutputStream, nsFileStreamBase,
696
nsIOutputStream, nsIFileOutputStream)
697
698
nsresult nsFileOutputStream::Create(nsISupports* aOuter, REFNSIID aIID,
699
void** aResult) {
700
NS_ENSURE_NO_AGGREGATION(aOuter);
701
702
RefPtr<nsFileOutputStream> stream = new nsFileOutputStream();
703
return stream->QueryInterface(aIID, aResult);
704
}
705
706
NS_IMETHODIMP
707
nsFileOutputStream::Init(nsIFile* file, int32_t ioFlags, int32_t perm,
708
int32_t behaviorFlags) {
709
NS_ENSURE_TRUE(mFD == nullptr, NS_ERROR_ALREADY_INITIALIZED);
710
NS_ENSURE_TRUE(mState == eUnitialized || mState == eClosed,
711
NS_ERROR_ALREADY_INITIALIZED);
712
713
mBehaviorFlags = behaviorFlags;
714
mState = eUnitialized;
715
716
if (ioFlags == -1) ioFlags = PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE;
717
if (perm <= 0) perm = 0664;
718
719
return MaybeOpen(file, ioFlags, perm,
720
mBehaviorFlags & nsIFileOutputStream::DEFER_OPEN);
721
}
722
723
NS_IMETHODIMP
724
nsFileOutputStream::Preallocate(int64_t aLength) {
725
if (!mFD) {
726
return NS_ERROR_NOT_INITIALIZED;
727
}
728
729
if (!mozilla::fallocate(mFD, aLength)) {
730
return NS_ERROR_FAILURE;
731
}
732
733
return NS_OK;
734
}
735
736
////////////////////////////////////////////////////////////////////////////////
737
// nsAtomicFileOutputStream
738
739
NS_IMPL_ISUPPORTS_INHERITED(nsAtomicFileOutputStream, nsFileOutputStream,
740
nsISafeOutputStream, nsIOutputStream,
741
nsIFileOutputStream)
742
743
NS_IMETHODIMP
744
nsAtomicFileOutputStream::Init(nsIFile* file, int32_t ioFlags, int32_t perm,
745
int32_t behaviorFlags) {
746
// While `PR_APPEND` is not supported, `-1` is used as `ioFlags` parameter
747
// in some places, and `PR_APPEND | PR_TRUNCATE` does not require appending
748
// to existing file. So, throw an exception only if `PR_APPEND` is
749
// explicitly specified without `PR_TRUNCATE`.
750
if ((ioFlags & PR_APPEND) && !(ioFlags & PR_TRUNCATE)) {
751
return NS_ERROR_INVALID_ARG;
752
}
753
return nsFileOutputStream::Init(file, ioFlags, perm, behaviorFlags);
754
}
755
756
nsresult nsAtomicFileOutputStream::DoOpen() {
757
// Make sure mOpenParams.localFile will be empty if we bail somewhere in
758
// this function
759
nsCOMPtr<nsIFile> file;
760
file.swap(mOpenParams.localFile);
761
762
if (!file) {
763
return NS_ERROR_NOT_INITIALIZED;
764
}
765
nsresult rv = file->Exists(&mTargetFileExists);
766
if (NS_FAILED(rv)) {
767
NS_ERROR("Can't tell if target file exists");
768
mTargetFileExists =
769
true; // Safer to assume it exists - we just do more work.
770
}
771
772
// follow symlinks, for two reasons:
773
// 1) if a user has deliberately set up a profile file as a symlink, we
774
// honor it
775
// 2) to make the MoveToNative() in Finish() an atomic operation (which may
776
// not be the case if moving across directories on different
777
// filesystems).
778
nsCOMPtr<nsIFile> tempResult;
779
rv = file->Clone(getter_AddRefs(tempResult));
780
if (NS_SUCCEEDED(rv)) {
781
tempResult->SetFollowLinks(true);
782
783
// XP_UNIX ignores SetFollowLinks(), so we have to normalize.
784
if (mTargetFileExists) {
785
tempResult->Normalize();
786
}
787
}
788
789
if (NS_SUCCEEDED(rv) && mTargetFileExists) {
790
// Abort if |file| is not writable; it won't work as an output stream.
791
bool isWritable;
792
if (NS_SUCCEEDED(file->IsWritable(&isWritable)) && !isWritable) {
793
return NS_ERROR_FILE_ACCESS_DENIED;
794
}
795
796
uint32_t origPerm;
797
if (NS_FAILED(file->GetPermissions(&origPerm))) {
798
NS_ERROR("Can't get permissions of target file");
799
origPerm = mOpenParams.perm;
800
}
801
802
// XXX What if |perm| is more restrictive then |origPerm|?
803
// This leaves the user supplied permissions as they were.
804
rv = tempResult->CreateUnique(nsIFile::NORMAL_FILE_TYPE, origPerm);
805
}
806
if (NS_SUCCEEDED(rv)) {
807
// nsFileOutputStream::DoOpen will work on the temporary file, so we
808
// prepare it and place it in mOpenParams.localFile.
809
mOpenParams.localFile = tempResult;
810
mTempFile = tempResult;
811
mTargetFile = file;
812
rv = nsFileOutputStream::DoOpen();
813
}
814
return rv;
815
}
816
817
NS_IMETHODIMP
818
nsAtomicFileOutputStream::Close() {
819
nsresult rv = nsFileOutputStream::Close();
820
821
// the consumer doesn't want the original file overwritten -
822
// so clean up by removing the temp file.
823
if (mTempFile) {
824
mTempFile->Remove(false);
825
mTempFile = nullptr;
826
}
827
828
return rv;
829
}
830
831
NS_IMETHODIMP
832
nsAtomicFileOutputStream::Finish() {
833
nsresult rv = nsFileOutputStream::Close();
834
835
// if there is no temp file, don't try to move it over the original target.
836
// It would destroy the targetfile if close() is called twice.
837
if (!mTempFile) return rv;
838
839
// Only overwrite if everything was ok, and the temp file could be closed.
840
if (NS_SUCCEEDED(mWriteResult) && NS_SUCCEEDED(rv)) {
841
NS_ENSURE_STATE(mTargetFile);
842
843
if (!mTargetFileExists) {
844
// If the target file did not exist when we were initialized, then the
845
// temp file we gave out was actually a reference to the target file.
846
// since we succeeded in writing to the temp file (and hence succeeded
847
// in writing to the target file), there is nothing more to do.
848
#ifdef DEBUG
849
bool equal;
850
if (NS_FAILED(mTargetFile->Equals(mTempFile, &equal)) || !equal)
851
NS_WARNING("mTempFile not equal to mTargetFile");
852
#endif
853
} else {
854
nsAutoString targetFilename;
855
rv = mTargetFile->GetLeafName(targetFilename);
856
if (NS_SUCCEEDED(rv)) {
857
// This will replace target.
858
rv = mTempFile->MoveTo(nullptr, targetFilename);
859
if (NS_FAILED(rv)) mTempFile->Remove(false);
860
}
861
}
862
} else {
863
mTempFile->Remove(false);
864
865
// if writing failed, propagate the failure code to the caller.
866
if (NS_FAILED(mWriteResult)) rv = mWriteResult;
867
}
868
mTempFile = nullptr;
869
return rv;
870
}
871
872
NS_IMETHODIMP
873
nsAtomicFileOutputStream::Write(const char* buf, uint32_t count,
874
uint32_t* result) {
875
nsresult rv = nsFileOutputStream::Write(buf, count, result);
876
if (NS_SUCCEEDED(mWriteResult)) {
877
if (NS_FAILED(rv))
878
mWriteResult = rv;
879
else if (count != *result)
880
mWriteResult = NS_ERROR_LOSS_OF_SIGNIFICANT_DATA;
881
882
if (NS_FAILED(mWriteResult) && count > 0)
883
NS_WARNING("writing to output stream failed! data may be lost");
884
}
885
return rv;
886
}
887
888
////////////////////////////////////////////////////////////////////////////////
889
// nsSafeFileOutputStream
890
891
NS_IMETHODIMP
892
nsSafeFileOutputStream::Finish() {
893
(void)Flush();
894
return nsAtomicFileOutputStream::Finish();
895
}
896
897
////////////////////////////////////////////////////////////////////////////////
898
// nsFileStream
899
900
NS_IMPL_ISUPPORTS_INHERITED(nsFileStream, nsFileStreamBase, nsIInputStream,
901
nsIOutputStream, nsIFileStream)
902
903
NS_IMETHODIMP
904
nsFileStream::Init(nsIFile* file, int32_t ioFlags, int32_t perm,
905
int32_t behaviorFlags) {
906
NS_ENSURE_TRUE(mFD == nullptr, NS_ERROR_ALREADY_INITIALIZED);
907
NS_ENSURE_TRUE(mState == eUnitialized || mState == eClosed,
908
NS_ERROR_ALREADY_INITIALIZED);
909
910
mBehaviorFlags = behaviorFlags;
911
mState = eUnitialized;
912
913
if (ioFlags == -1) ioFlags = PR_RDWR;
914
if (perm <= 0) perm = 0;
915
916
return MaybeOpen(file, ioFlags, perm,
917
mBehaviorFlags & nsIFileStream::DEFER_OPEN);
918
}
919
920
////////////////////////////////////////////////////////////////////////////////