forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnsWebBrowserPersist.cpp
2717 lines (2344 loc) · 89.1 KB
/
nsWebBrowserPersist.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: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* 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/TextUtils.h"
#include "nspr.h"
#include "nsIFileStreams.h" // New Necko file streams
#include <algorithm>
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsIClassOfService.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsILoadContext.h"
#include "nsIPrivateBrowsingChannel.h"
#include "nsComponentManagerUtils.h"
#include "nsIStorageStream.h"
#include "nsISeekableStream.h"
#include "nsIHttpChannel.h"
#include "nsIEncodedChannel.h"
#include "nsIUploadChannel.h"
#include "nsICacheInfoChannel.h"
#include "nsIFileChannel.h"
#include "nsEscape.h"
#include "nsUnicharUtils.h"
#include "nsIStringEnumerator.h"
#include "nsContentCID.h"
#include "nsStreamUtils.h"
#include "nsCExternalHandlerService.h"
#include "nsIURL.h"
#include "nsIFileURL.h"
#include "nsIWebProgressListener.h"
#include "nsIAuthPrompt.h"
#include "nsIPrompt.h"
#include "nsIFormControl.h"
#include "nsIThreadRetargetableRequest.h"
#include "nsContentUtils.h"
#include "nsIStringBundle.h"
#include "nsIProtocolHandler.h"
#include "nsWebBrowserPersist.h"
#include "WebBrowserPersistLocalDocument.h"
#include "nsIContent.h"
#include "nsIMIMEInfo.h"
#include "mozilla/dom/HTMLInputElement.h"
#include "mozilla/dom/HTMLSharedElement.h"
#include "mozilla/net/CookieJarSettings.h"
#include "mozilla/Mutex.h"
#include "mozilla/Printf.h"
#include "ReferrerInfo.h"
#include "nsIURIMutator.h"
#include "mozilla/WebBrowserPersistDocumentParent.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/WindowGlobalParent.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/PContentParent.h"
#include "mozilla/dom/BrowserParent.h"
#include "nsIDocumentEncoder.h"
using namespace mozilla;
using namespace mozilla::dom;
// Buffer file writes in 32kb chunks
#define BUFFERED_OUTPUT_SIZE (1024 * 32)
struct nsWebBrowserPersist::WalkData {
nsCOMPtr<nsIWebBrowserPersistDocument> mDocument;
nsCOMPtr<nsIURI> mFile;
nsCOMPtr<nsIURI> mDataPath;
};
// Information about a DOM document
struct nsWebBrowserPersist::DocData {
nsCOMPtr<nsIURI> mBaseURI;
nsCOMPtr<nsIWebBrowserPersistDocument> mDocument;
nsCOMPtr<nsIURI> mFile;
nsCString mCharset;
};
// Information about a URI
struct nsWebBrowserPersist::URIData {
bool mNeedsPersisting;
bool mSaved;
bool mIsSubFrame;
bool mDataPathIsRelative;
bool mNeedsFixup;
nsString mFilename;
nsString mSubFrameExt;
nsCOMPtr<nsIURI> mFile;
nsCOMPtr<nsIURI> mDataPath;
nsCOMPtr<nsIURI> mRelativeDocumentURI;
nsCOMPtr<nsIPrincipal> mTriggeringPrincipal;
nsCOMPtr<nsICookieJarSettings> mCookieJarSettings;
nsContentPolicyType mContentPolicyType;
nsCString mRelativePathToData;
nsCString mCharset;
nsresult GetLocalURI(nsIURI* targetBaseURI, nsCString& aSpecOut);
};
// Information about the output stream
// Note that this data structure (and the map that nsWebBrowserPersist keeps,
// where these are values) is used from two threads: the main thread,
// and the background task thread.
// The background thread only writes to mStream (from OnDataAvailable), and
// this access is guarded using mStreamMutex. It reads the mFile member, which
// is only written to on the main thread when the object is constructed and
// from OnStartRequest (if mCalcFileExt), both guaranteed to happen before
// OnDataAvailable is fired.
// The main thread gets OnStartRequest, OnStopRequest, and progress sink events,
// and accesses the other members.
struct nsWebBrowserPersist::OutputData {
nsCOMPtr<nsIURI> mFile;
nsCOMPtr<nsIURI> mOriginalLocation;
nsCOMPtr<nsIOutputStream> mStream;
Mutex mStreamMutex MOZ_UNANNOTATED;
int64_t mSelfProgress;
int64_t mSelfProgressMax;
bool mCalcFileExt;
OutputData(nsIURI* aFile, nsIURI* aOriginalLocation, bool aCalcFileExt)
: mFile(aFile),
mOriginalLocation(aOriginalLocation),
mStreamMutex("nsWebBrowserPersist::OutputData::mStreamMutex"),
mSelfProgress(0),
mSelfProgressMax(10000),
mCalcFileExt(aCalcFileExt) {}
~OutputData() {
// Gaining this lock in the destructor is pretty icky. It should be OK
// because the only other place we lock the mutex is in OnDataAvailable,
// which will never itself cause the OutputData instance to be
// destroyed.
MutexAutoLock lock(mStreamMutex);
if (mStream) {
mStream->Close();
}
}
};
struct nsWebBrowserPersist::UploadData {
nsCOMPtr<nsIURI> mFile;
int64_t mSelfProgress;
int64_t mSelfProgressMax;
explicit UploadData(nsIURI* aFile)
: mFile(aFile), mSelfProgress(0), mSelfProgressMax(10000) {}
};
struct nsWebBrowserPersist::CleanupData {
nsCOMPtr<nsIFile> mFile;
// Snapshot of what the file actually is at the time of creation so that if
// it transmutes into something else later on it can be ignored. For example,
// catch files that turn into dirs or vice versa.
bool mIsDirectory;
};
class nsWebBrowserPersist::OnWalk final
: public nsIWebBrowserPersistResourceVisitor {
public:
OnWalk(nsWebBrowserPersist* aParent, nsIURI* aFile, nsIFile* aDataPath)
: mParent(aParent),
mFile(aFile),
mDataPath(aDataPath),
mPendingDocuments(1),
mStatus(NS_OK) {}
NS_DECL_NSIWEBBROWSERPERSISTRESOURCEVISITOR
NS_DECL_ISUPPORTS
private:
RefPtr<nsWebBrowserPersist> mParent;
nsCOMPtr<nsIURI> mFile;
nsCOMPtr<nsIFile> mDataPath;
uint32_t mPendingDocuments;
nsresult mStatus;
virtual ~OnWalk() = default;
};
NS_IMPL_ISUPPORTS(nsWebBrowserPersist::OnWalk,
nsIWebBrowserPersistResourceVisitor)
class nsWebBrowserPersist::OnRemoteWalk final
: public nsIWebBrowserPersistDocumentReceiver {
public:
OnRemoteWalk(nsIWebBrowserPersistResourceVisitor* aVisitor,
nsIWebBrowserPersistDocument* aDocument)
: mVisitor(aVisitor), mDocument(aDocument) {}
NS_DECL_NSIWEBBROWSERPERSISTDOCUMENTRECEIVER
NS_DECL_ISUPPORTS
private:
nsCOMPtr<nsIWebBrowserPersistResourceVisitor> mVisitor;
nsCOMPtr<nsIWebBrowserPersistDocument> mDocument;
virtual ~OnRemoteWalk() = default;
};
NS_IMPL_ISUPPORTS(nsWebBrowserPersist::OnRemoteWalk,
nsIWebBrowserPersistDocumentReceiver)
class nsWebBrowserPersist::OnWrite final
: public nsIWebBrowserPersistWriteCompletion {
public:
OnWrite(nsWebBrowserPersist* aParent, nsIURI* aFile, nsIFile* aLocalFile)
: mParent(aParent), mFile(aFile), mLocalFile(aLocalFile) {}
NS_DECL_NSIWEBBROWSERPERSISTWRITECOMPLETION
NS_DECL_ISUPPORTS
private:
RefPtr<nsWebBrowserPersist> mParent;
nsCOMPtr<nsIURI> mFile;
nsCOMPtr<nsIFile> mLocalFile;
virtual ~OnWrite() = default;
};
NS_IMPL_ISUPPORTS(nsWebBrowserPersist::OnWrite,
nsIWebBrowserPersistWriteCompletion)
class nsWebBrowserPersist::FlatURIMap final
: public nsIWebBrowserPersistURIMap {
public:
explicit FlatURIMap(const nsACString& aTargetBase)
: mTargetBase(aTargetBase) {}
void Add(const nsACString& aMapFrom, const nsACString& aMapTo) {
mMapFrom.AppendElement(aMapFrom);
mMapTo.AppendElement(aMapTo);
}
NS_DECL_NSIWEBBROWSERPERSISTURIMAP
NS_DECL_ISUPPORTS
private:
nsTArray<nsCString> mMapFrom;
nsTArray<nsCString> mMapTo;
nsCString mTargetBase;
virtual ~FlatURIMap() = default;
};
NS_IMPL_ISUPPORTS(nsWebBrowserPersist::FlatURIMap, nsIWebBrowserPersistURIMap)
NS_IMETHODIMP
nsWebBrowserPersist::FlatURIMap::GetNumMappedURIs(uint32_t* aNum) {
MOZ_ASSERT(mMapFrom.Length() == mMapTo.Length());
*aNum = mMapTo.Length();
return NS_OK;
}
NS_IMETHODIMP
nsWebBrowserPersist::FlatURIMap::GetTargetBaseURI(nsACString& aTargetBase) {
aTargetBase = mTargetBase;
return NS_OK;
}
NS_IMETHODIMP
nsWebBrowserPersist::FlatURIMap::GetURIMapping(uint32_t aIndex,
nsACString& aMapFrom,
nsACString& aMapTo) {
MOZ_ASSERT(mMapFrom.Length() == mMapTo.Length());
if (aIndex >= mMapTo.Length()) {
return NS_ERROR_INVALID_ARG;
}
aMapFrom = mMapFrom[aIndex];
aMapTo = mMapTo[aIndex];
return NS_OK;
}
// Maximum file length constant. The max file name length is
// volume / server dependent but it is difficult to obtain
// that information. Instead this constant is a reasonable value that
// modern systems should able to cope with.
const uint32_t kDefaultMaxFilenameLength = 64;
// Default flags for persistence
const uint32_t kDefaultPersistFlags =
nsIWebBrowserPersist::PERSIST_FLAGS_NO_CONVERSION |
nsIWebBrowserPersist::PERSIST_FLAGS_REPLACE_EXISTING_FILES;
// String bundle where error messages come from
const char* kWebBrowserPersistStringBundle =
"chrome://global/locale/nsWebBrowserPersist.properties";
nsWebBrowserPersist::nsWebBrowserPersist()
: mCurrentDataPathIsRelative(false),
mCurrentThingsToPersist(0),
mOutputMapMutex("nsWebBrowserPersist::mOutputMapMutex"),
mFirstAndOnlyUse(true),
mSavingDocument(false),
mCancel(false),
mEndCalled(false),
mCompleted(false),
mStartSaving(false),
mReplaceExisting(true),
mSerializingOutput(false),
mIsPrivate(false),
mPersistFlags(kDefaultPersistFlags),
mPersistResult(NS_OK),
mTotalCurrentProgress(0),
mTotalMaxProgress(0),
mWrapColumn(72),
mEncodingFlags(0) {}
nsWebBrowserPersist::~nsWebBrowserPersist() { Cleanup(); }
//*****************************************************************************
// nsWebBrowserPersist::nsISupports
//*****************************************************************************
NS_IMPL_ADDREF(nsWebBrowserPersist)
NS_IMPL_RELEASE(nsWebBrowserPersist)
NS_INTERFACE_MAP_BEGIN(nsWebBrowserPersist)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIWebBrowserPersist)
NS_INTERFACE_MAP_ENTRY(nsIWebBrowserPersist)
NS_INTERFACE_MAP_ENTRY(nsICancelable)
NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
NS_INTERFACE_MAP_ENTRY(nsIThreadRetargetableStreamListener)
NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
NS_INTERFACE_MAP_ENTRY(nsIProgressEventSink)
NS_INTERFACE_MAP_END
//*****************************************************************************
// nsWebBrowserPersist::nsIInterfaceRequestor
//*****************************************************************************
NS_IMETHODIMP nsWebBrowserPersist::GetInterface(const nsIID& aIID,
void** aIFace) {
NS_ENSURE_ARG_POINTER(aIFace);
*aIFace = nullptr;
nsresult rv = QueryInterface(aIID, aIFace);
if (NS_SUCCEEDED(rv)) {
return rv;
}
if (mProgressListener && (aIID.Equals(NS_GET_IID(nsIAuthPrompt)) ||
aIID.Equals(NS_GET_IID(nsIPrompt)))) {
mProgressListener->QueryInterface(aIID, aIFace);
if (*aIFace) return NS_OK;
}
nsCOMPtr<nsIInterfaceRequestor> req = do_QueryInterface(mProgressListener);
if (req) {
return req->GetInterface(aIID, aIFace);
}
return NS_ERROR_NO_INTERFACE;
}
//*****************************************************************************
// nsWebBrowserPersist::nsIWebBrowserPersist
//*****************************************************************************
NS_IMETHODIMP nsWebBrowserPersist::GetPersistFlags(uint32_t* aPersistFlags) {
NS_ENSURE_ARG_POINTER(aPersistFlags);
*aPersistFlags = mPersistFlags;
return NS_OK;
}
NS_IMETHODIMP nsWebBrowserPersist::SetPersistFlags(uint32_t aPersistFlags) {
mPersistFlags = aPersistFlags;
mReplaceExisting = (mPersistFlags & PERSIST_FLAGS_REPLACE_EXISTING_FILES);
mSerializingOutput = (mPersistFlags & PERSIST_FLAGS_SERIALIZE_OUTPUT);
return NS_OK;
}
NS_IMETHODIMP nsWebBrowserPersist::GetCurrentState(uint32_t* aCurrentState) {
NS_ENSURE_ARG_POINTER(aCurrentState);
if (mCompleted) {
*aCurrentState = PERSIST_STATE_FINISHED;
} else if (mFirstAndOnlyUse) {
*aCurrentState = PERSIST_STATE_SAVING;
} else {
*aCurrentState = PERSIST_STATE_READY;
}
return NS_OK;
}
NS_IMETHODIMP nsWebBrowserPersist::GetResult(nsresult* aResult) {
NS_ENSURE_ARG_POINTER(aResult);
*aResult = mPersistResult;
return NS_OK;
}
NS_IMETHODIMP nsWebBrowserPersist::GetProgressListener(
nsIWebProgressListener** aProgressListener) {
NS_ENSURE_ARG_POINTER(aProgressListener);
*aProgressListener = mProgressListener;
NS_IF_ADDREF(*aProgressListener);
return NS_OK;
}
NS_IMETHODIMP nsWebBrowserPersist::SetProgressListener(
nsIWebProgressListener* aProgressListener) {
mProgressListener = aProgressListener;
mProgressListener2 = do_QueryInterface(aProgressListener);
mEventSink = do_GetInterface(aProgressListener);
return NS_OK;
}
NS_IMETHODIMP nsWebBrowserPersist::SaveURI(
nsIURI* aURI, nsIPrincipal* aPrincipal, uint32_t aCacheKey,
nsIReferrerInfo* aReferrerInfo, nsICookieJarSettings* aCookieJarSettings,
nsIInputStream* aPostData, const char* aExtraHeaders, nsISupports* aFile,
nsContentPolicyType aContentPolicyType, nsILoadContext* aPrivacyContext) {
bool isPrivate = aPrivacyContext && aPrivacyContext->UsePrivateBrowsing();
return SavePrivacyAwareURI(aURI, aPrincipal, aCacheKey, aReferrerInfo,
aCookieJarSettings, aPostData, aExtraHeaders,
aFile, aContentPolicyType, isPrivate);
}
NS_IMETHODIMP nsWebBrowserPersist::SavePrivacyAwareURI(
nsIURI* aURI, nsIPrincipal* aPrincipal, uint32_t aCacheKey,
nsIReferrerInfo* aReferrerInfo, nsICookieJarSettings* aCookieJarSettings,
nsIInputStream* aPostData, const char* aExtraHeaders, nsISupports* aFile,
nsContentPolicyType aContentPolicy, bool aIsPrivate) {
NS_ENSURE_TRUE(mFirstAndOnlyUse, NS_ERROR_FAILURE);
mFirstAndOnlyUse = false; // Stop people from reusing this object!
nsCOMPtr<nsIURI> fileAsURI;
nsresult rv;
rv = GetValidURIFromObject(aFile, getter_AddRefs(fileAsURI));
NS_ENSURE_SUCCESS(rv, NS_ERROR_INVALID_ARG);
// SaveURI doesn't like broken uris.
mPersistFlags |= PERSIST_FLAGS_FAIL_ON_BROKEN_LINKS;
rv = SaveURIInternal(aURI, aPrincipal, aContentPolicy, aCacheKey,
aReferrerInfo, aCookieJarSettings, aPostData,
aExtraHeaders, fileAsURI, false, aIsPrivate);
return NS_FAILED(rv) ? rv : NS_OK;
}
NS_IMETHODIMP nsWebBrowserPersist::SaveChannel(nsIChannel* aChannel,
nsISupports* aFile) {
NS_ENSURE_TRUE(mFirstAndOnlyUse, NS_ERROR_FAILURE);
mFirstAndOnlyUse = false; // Stop people from reusing this object!
nsCOMPtr<nsIURI> fileAsURI;
nsresult rv;
rv = GetValidURIFromObject(aFile, getter_AddRefs(fileAsURI));
NS_ENSURE_SUCCESS(rv, NS_ERROR_INVALID_ARG);
rv = aChannel->GetURI(getter_AddRefs(mURI));
NS_ENSURE_SUCCESS(rv, rv);
// SaveURI doesn't like broken uris.
mPersistFlags |= PERSIST_FLAGS_FAIL_ON_BROKEN_LINKS;
rv = SaveChannelInternal(aChannel, fileAsURI, false);
return NS_FAILED(rv) ? rv : NS_OK;
}
NS_IMETHODIMP nsWebBrowserPersist::SaveDocument(nsISupports* aDocument,
nsISupports* aFile,
nsISupports* aDataPath,
const char* aOutputContentType,
uint32_t aEncodingFlags,
uint32_t aWrapColumn) {
NS_ENSURE_TRUE(mFirstAndOnlyUse, NS_ERROR_FAILURE);
mFirstAndOnlyUse = false; // Stop people from reusing this object!
// We need a STATE_IS_NETWORK start/stop pair to bracket the
// notification callbacks. For a whole document we generate those
// here and in EndDownload(), but for the single-request methods
// that's done in On{Start,Stop}Request instead.
mSavingDocument = true;
NS_ENSURE_ARG_POINTER(aDocument);
NS_ENSURE_ARG_POINTER(aFile);
nsCOMPtr<nsIURI> fileAsURI;
nsCOMPtr<nsIURI> datapathAsURI;
nsresult rv;
rv = GetValidURIFromObject(aFile, getter_AddRefs(fileAsURI));
NS_ENSURE_SUCCESS(rv, NS_ERROR_INVALID_ARG);
if (aDataPath) {
rv = GetValidURIFromObject(aDataPath, getter_AddRefs(datapathAsURI));
NS_ENSURE_SUCCESS(rv, NS_ERROR_INVALID_ARG);
}
mWrapColumn = aWrapColumn;
mEncodingFlags = aEncodingFlags;
if (aOutputContentType) {
mContentType.AssignASCII(aOutputContentType);
}
// State start notification
if (mProgressListener) {
mProgressListener->OnStateChange(
nullptr, nullptr,
nsIWebProgressListener::STATE_START |
nsIWebProgressListener::STATE_IS_NETWORK,
NS_OK);
}
nsCOMPtr<nsIWebBrowserPersistDocument> doc = do_QueryInterface(aDocument);
if (!doc) {
nsCOMPtr<Document> localDoc = do_QueryInterface(aDocument);
if (localDoc) {
doc = new mozilla::WebBrowserPersistLocalDocument(localDoc);
} else {
rv = NS_ERROR_NO_INTERFACE;
}
}
bool closed = false;
if (doc && NS_SUCCEEDED(doc->GetIsClosed(&closed)) && !closed) {
rv = SaveDocumentInternal(doc, fileAsURI, datapathAsURI);
}
if (NS_FAILED(rv) || closed) {
SendErrorStatusChange(true, rv, nullptr, mURI);
EndDownload(rv);
}
return rv;
}
NS_IMETHODIMP nsWebBrowserPersist::Cancel(nsresult aReason) {
// No point cancelling if we're already complete.
if (mEndCalled) {
return NS_OK;
}
mCancel = true;
EndDownload(aReason);
return NS_OK;
}
NS_IMETHODIMP nsWebBrowserPersist::CancelSave() {
return Cancel(NS_BINDING_ABORTED);
}
nsresult nsWebBrowserPersist::StartUpload(nsIStorageStream* storStream,
nsIURI* aDestinationURI,
const nsACString& aContentType) {
// setup the upload channel if the destination is not local
nsCOMPtr<nsIInputStream> inputstream;
nsresult rv = storStream->NewInputStream(0, getter_AddRefs(inputstream));
NS_ENSURE_TRUE(inputstream, NS_ERROR_FAILURE);
NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
return StartUpload(inputstream, aDestinationURI, aContentType);
}
nsresult nsWebBrowserPersist::StartUpload(nsIInputStream* aInputStream,
nsIURI* aDestinationURI,
const nsACString& aContentType) {
nsCOMPtr<nsIChannel> destChannel;
CreateChannelFromURI(aDestinationURI, getter_AddRefs(destChannel));
nsCOMPtr<nsIUploadChannel> uploadChannel(do_QueryInterface(destChannel));
NS_ENSURE_TRUE(uploadChannel, NS_ERROR_FAILURE);
// Set the upload stream
// NOTE: ALL data must be available in "inputstream"
nsresult rv = uploadChannel->SetUploadStream(aInputStream, aContentType, -1);
NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
rv = destChannel->AsyncOpen(this);
NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
// add this to the upload list
nsCOMPtr<nsISupports> keyPtr = do_QueryInterface(destChannel);
mUploadList.InsertOrUpdate(keyPtr, MakeUnique<UploadData>(aDestinationURI));
return NS_OK;
}
void nsWebBrowserPersist::SerializeNextFile() {
nsresult rv = NS_OK;
MOZ_ASSERT(mWalkStack.Length() == 0);
// First, handle gathered URIs.
// This is potentially O(n^2), when taking into account the
// number of times this method is called. If it becomes a
// bottleneck, the count of not-yet-persisted URIs could be
// maintained separately, and we can skip iterating mURIMap if there are none.
// Persist each file in the uri map. The document(s)
// will be saved after the last one of these is saved.
for (const auto& entry : mURIMap) {
URIData* data = entry.GetWeak();
if (!data->mNeedsPersisting || data->mSaved) {
continue;
}
// Create a URI from the key.
nsCOMPtr<nsIURI> uri;
rv = NS_NewURI(getter_AddRefs(uri), entry.GetKey(), data->mCharset.get());
if (NS_WARN_IF(NS_FAILED(rv))) {
break;
}
// Make a URI to save the data to.
nsCOMPtr<nsIURI> fileAsURI = data->mDataPath;
rv = AppendPathToURI(fileAsURI, data->mFilename, fileAsURI);
if (NS_WARN_IF(NS_FAILED(rv))) {
break;
}
rv = SaveURIInternal(uri, data->mTriggeringPrincipal,
data->mContentPolicyType, 0, nullptr,
data->mCookieJarSettings, nullptr, nullptr, fileAsURI,
true, mIsPrivate);
// If SaveURIInternal fails, then it will have called EndDownload,
// which means that |data| is no longer valid memory. We MUST bail.
if (NS_WARN_IF(NS_FAILED(rv))) {
break;
}
if (rv == NS_OK) {
// URIData.mFile will be updated to point to the correct
// URI object when it is fixed up with the right file extension
// in OnStartRequest
data->mFile = fileAsURI;
data->mSaved = true;
} else {
data->mNeedsFixup = false;
}
if (mSerializingOutput) {
break;
}
}
// If there are downloads happening, wait until they're done; the
// OnStopRequest handler will call this method again.
if (mOutputMap.Count() > 0) {
return;
}
// If serializing, also wait until last upload is done.
if (mSerializingOutput && mUploadList.Count() > 0) {
return;
}
// If there are also no more documents, then we're done.
if (mDocList.Length() == 0) {
// ...or not quite done, if there are still uploads.
if (mUploadList.Count() > 0) {
return;
}
// Finish and clean things up. Defer this because the caller
// may have been expecting to use the listeners that that
// method will clear.
NS_DispatchToCurrentThread(
NewRunnableMethod("nsWebBrowserPersist::FinishDownload", this,
&nsWebBrowserPersist::FinishDownload));
return;
}
// There are no URIs to save, so just save the next document.
mStartSaving = true;
mozilla::UniquePtr<DocData> docData(mDocList.ElementAt(0));
mDocList.RemoveElementAt(0); // O(n^2) but probably doesn't matter.
MOZ_ASSERT(docData);
if (!docData) {
EndDownload(NS_ERROR_FAILURE);
return;
}
mCurrentBaseURI = docData->mBaseURI;
mCurrentCharset = docData->mCharset;
mTargetBaseURI = docData->mFile;
// Save the document, fixing it up with the new URIs as we do
nsAutoCString targetBaseSpec;
if (mTargetBaseURI) {
rv = mTargetBaseURI->GetSpec(targetBaseSpec);
if (NS_FAILED(rv)) {
SendErrorStatusChange(true, rv, nullptr, nullptr);
EndDownload(rv);
return;
}
}
// mFlatURIMap must be rebuilt each time through SerializeNextFile, as
// mTargetBaseURI is used to create the relative URLs and will be different
// with each serialized document.
RefPtr<FlatURIMap> flatMap = new FlatURIMap(targetBaseSpec);
for (const auto& uriEntry : mURIMap) {
nsAutoCString mapTo;
nsresult rv = uriEntry.GetWeak()->GetLocalURI(mTargetBaseURI, mapTo);
if (NS_SUCCEEDED(rv) || !mapTo.IsVoid()) {
flatMap->Add(uriEntry.GetKey(), mapTo);
}
}
mFlatURIMap = std::move(flatMap);
nsCOMPtr<nsIFile> localFile;
GetLocalFileFromURI(docData->mFile, getter_AddRefs(localFile));
if (localFile) {
// if we're not replacing an existing file but the file
// exists, something is wrong
bool fileExists = false;
rv = localFile->Exists(&fileExists);
if (NS_SUCCEEDED(rv) && !mReplaceExisting && fileExists) {
rv = NS_ERROR_FILE_ALREADY_EXISTS;
}
if (NS_FAILED(rv)) {
SendErrorStatusChange(false, rv, nullptr, docData->mFile);
EndDownload(rv);
return;
}
}
nsCOMPtr<nsIOutputStream> outputStream;
rv = MakeOutputStream(docData->mFile, getter_AddRefs(outputStream));
if (NS_SUCCEEDED(rv) && !outputStream) {
rv = NS_ERROR_FAILURE;
}
if (NS_FAILED(rv)) {
SendErrorStatusChange(false, rv, nullptr, docData->mFile);
EndDownload(rv);
return;
}
RefPtr<OnWrite> finish = new OnWrite(this, docData->mFile, localFile);
rv = docData->mDocument->WriteContent(outputStream, mFlatURIMap,
NS_ConvertUTF16toUTF8(mContentType),
mEncodingFlags, mWrapColumn, finish);
if (NS_FAILED(rv)) {
SendErrorStatusChange(false, rv, nullptr, docData->mFile);
EndDownload(rv);
}
}
NS_IMETHODIMP
nsWebBrowserPersist::OnWrite::OnFinish(nsIWebBrowserPersistDocument* aDoc,
nsIOutputStream* aStream,
const nsACString& aContentType,
nsresult aStatus) {
nsresult rv = aStatus;
if (NS_FAILED(rv)) {
mParent->SendErrorStatusChange(false, rv, nullptr, mFile);
mParent->EndDownload(rv);
return NS_OK;
}
if (!mLocalFile) {
nsCOMPtr<nsIStorageStream> storStream(do_QueryInterface(aStream));
if (storStream) {
aStream->Close();
rv = mParent->StartUpload(storStream, mFile, aContentType);
if (NS_FAILED(rv)) {
mParent->SendErrorStatusChange(false, rv, nullptr, mFile);
mParent->EndDownload(rv);
}
// Either we failed and we're done, or we're uploading and
// the OnStopRequest callback is responsible for the next
// SerializeNextFile().
return NS_OK;
}
}
NS_DispatchToCurrentThread(
NewRunnableMethod("nsWebBrowserPersist::SerializeNextFile", mParent,
&nsWebBrowserPersist::SerializeNextFile));
return NS_OK;
}
//*****************************************************************************
// nsWebBrowserPersist::nsIRequestObserver
//*****************************************************************************
NS_IMETHODIMP nsWebBrowserPersist::OnStartRequest(nsIRequest* request) {
if (mProgressListener) {
uint32_t stateFlags = nsIWebProgressListener::STATE_START |
nsIWebProgressListener::STATE_IS_REQUEST;
if (!mSavingDocument) {
stateFlags |= nsIWebProgressListener::STATE_IS_NETWORK;
}
mProgressListener->OnStateChange(nullptr, request, stateFlags, NS_OK);
}
nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
NS_ENSURE_TRUE(channel, NS_ERROR_FAILURE);
nsCOMPtr<nsISupports> keyPtr = do_QueryInterface(request);
OutputData* data = mOutputMap.Get(keyPtr);
// NOTE: This code uses the channel as a hash key so it will not
// recognize redirected channels because the key is not the same.
// When that happens we remove and add the data entry to use the
// new channel as the hash key.
if (!data) {
UploadData* upData = mUploadList.Get(keyPtr);
if (!upData) {
// Redirect? Try and fixup the output table
nsresult rv = FixRedirectedChannelEntry(channel);
NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
// Should be able to find the data after fixup unless redirects
// are disabled.
data = mOutputMap.Get(keyPtr);
if (!data) {
return NS_ERROR_FAILURE;
}
}
}
if (data && data->mFile) {
nsCOMPtr<nsIThreadRetargetableRequest> r = do_QueryInterface(request);
// Determine if we're uploading. Only use OMT onDataAvailable if not.
nsCOMPtr<nsIFile> localFile;
GetLocalFileFromURI(data->mFile, getter_AddRefs(localFile));
if (r && localFile) {
if (!mBackgroundQueue) {
NS_CreateBackgroundTaskQueue("WebBrowserPersist",
getter_AddRefs(mBackgroundQueue));
}
if (mBackgroundQueue) {
r->RetargetDeliveryTo(mBackgroundQueue);
}
}
// If PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION is set in mPersistFlags,
// try to determine whether this channel needs to apply Content-Encoding
// conversions.
NS_ASSERTION(
!((mPersistFlags & PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION) &&
(mPersistFlags & PERSIST_FLAGS_NO_CONVERSION)),
"Conflict in persist flags: both AUTODETECT and NO_CONVERSION set");
if (mPersistFlags & PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION)
SetApplyConversionIfNeeded(channel);
if (data->mCalcFileExt &&
!(mPersistFlags & PERSIST_FLAGS_DONT_CHANGE_FILENAMES)) {
nsCOMPtr<nsIURI> uriWithExt;
// this is the first point at which the server can tell us the mimetype
nsresult rv = CalculateAndAppendFileExt(
data->mFile, channel, data->mOriginalLocation, uriWithExt);
if (NS_SUCCEEDED(rv)) {
data->mFile = uriWithExt;
}
// now make filename conformant and unique
nsCOMPtr<nsIURI> uniqueFilenameURI;
rv = CalculateUniqueFilename(data->mFile, uniqueFilenameURI);
if (NS_SUCCEEDED(rv)) {
data->mFile = uniqueFilenameURI;
}
// The URIData entry is pointing to the old unfixed URI, so we need
// to update it.
nsCOMPtr<nsIURI> chanURI;
rv = channel->GetOriginalURI(getter_AddRefs(chanURI));
if (NS_SUCCEEDED(rv)) {
nsAutoCString spec;
chanURI->GetSpec(spec);
URIData* uridata;
if (mURIMap.Get(spec, &uridata)) {
uridata->mFile = data->mFile;
}
}
}
// compare uris and bail before we add to output map if they are equal
bool isEqual = false;
if (NS_SUCCEEDED(data->mFile->Equals(data->mOriginalLocation, &isEqual)) &&
isEqual) {
{
MutexAutoLock lock(mOutputMapMutex);
// remove from output map
mOutputMap.Remove(keyPtr);
}
// cancel; we don't need to know any more
// stop request will get called
request->Cancel(NS_BINDING_ABORTED);
}
}
return NS_OK;
}
NS_IMETHODIMP nsWebBrowserPersist::OnStopRequest(nsIRequest* request,
nsresult status) {
nsCOMPtr<nsISupports> keyPtr = do_QueryInterface(request);
OutputData* data = mOutputMap.Get(keyPtr);
if (data) {
if (NS_SUCCEEDED(mPersistResult) && NS_FAILED(status)) {
SendErrorStatusChange(true, status, request, data->mFile);
}
// If there is a stream ref and we weren't canceled,
// close it away from the main thread.
// We don't do this when there's an error/cancelation,
// because our consumer may try to delete the file, which will error
// if we're still holding on to it, so we have to close it pronto.
{
MutexAutoLock lock(data->mStreamMutex);
if (data->mStream && NS_SUCCEEDED(status) && !mCancel) {
if (!mBackgroundQueue) {
nsresult rv = NS_CreateBackgroundTaskQueue(
"WebBrowserPersist", getter_AddRefs(mBackgroundQueue));
if (NS_FAILED(rv)) {
return rv;
}
}
// Now steal the stream ref and close it away from the main thread,
// keeping the promise around so we don't finish before all files
// are flushed and closed.
mFileClosePromises.AppendElement(InvokeAsync(
mBackgroundQueue, __func__, [stream = std::move(data->mStream)]() {
nsresult rv = stream->Close();
// We don't care if closing failed; we don't care in the
// destructor either...
return ClosePromise::CreateAndResolve(rv, __func__);
}));
}
}
MutexAutoLock lock(mOutputMapMutex);
mOutputMap.Remove(keyPtr);
} else {
// if we didn't find the data in mOutputMap, try mUploadList
UploadData* upData = mUploadList.Get(keyPtr);
if (upData) {
mUploadList.Remove(keyPtr);
}
}
// Do more work.
SerializeNextFile();
if (mProgressListener) {
uint32_t stateFlags = nsIWebProgressListener::STATE_STOP |
nsIWebProgressListener::STATE_IS_REQUEST;
if (!mSavingDocument) {
stateFlags |= nsIWebProgressListener::STATE_IS_NETWORK;
}
mProgressListener->OnStateChange(nullptr, request, stateFlags, status);
}
return NS_OK;
}
//*****************************************************************************
// nsWebBrowserPersist::nsIStreamListener
//*****************************************************************************
// Note: this is supposed to (but not guaranteed to) fire on a background
// thread when used to save to local disk (channels not using local files will
// use the main thread).
// (Read) Access to mOutputMap is guarded via mOutputMapMutex.
// Access to individual OutputData::mStream is guarded via its mStreamMutex.
// mCancel is atomic, as is mPersistFlags (accessed via MakeOutputStream).
// If you end up touching this method and needing other member access, bear
// this in mind.
NS_IMETHODIMP
nsWebBrowserPersist::OnDataAvailable(nsIRequest* request,
nsIInputStream* aIStream, uint64_t aOffset,
uint32_t aLength) {
// MOZ_ASSERT(!NS_IsMainThread()); // no guarantees, but it's likely.
bool cancel = mCancel;
if (!cancel) {
nsresult rv = NS_OK;
uint32_t bytesRemaining = aLength;
nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
NS_ENSURE_TRUE(channel, NS_ERROR_FAILURE);
MutexAutoLock lock(mOutputMapMutex);
nsCOMPtr<nsISupports> keyPtr = do_QueryInterface(request);
OutputData* data = mOutputMap.Get(keyPtr);
if (!data) {
// might be uploadData; consume necko's buffer and bail...
uint32_t n;
return aIStream->ReadSegments(NS_DiscardSegment, nullptr, aLength, &n);
}
bool readError = true;
MutexAutoLock streamLock(data->mStreamMutex);
// Make the output stream
if (!data->mStream) {
rv = MakeOutputStream(data->mFile, getter_AddRefs(data->mStream));
if (NS_FAILED(rv)) {
readError = false;
cancel = true;
}
}
// Read data from the input and write to the output
char buffer[8192];
uint32_t bytesRead;
while (!cancel && bytesRemaining) {
readError = true;
rv = aIStream->Read(buffer,