This repository has been archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnsWebBrowserPersist.cpp
2823 lines (2453 loc) · 89.3 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: 4 -*-
* 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 "nspr.h"
#include "nsIFileStreams.h" // New Necko file streams
#include <algorithm>
#include "nsAutoPtr.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsILoadContext.h"
#include "nsIPrivateBrowsingChannel.h"
#include "nsComponentManagerUtils.h"
#include "nsIComponentRegistrar.h"
#include "nsIStorageStream.h"
#include "nsISeekableStream.h"
#include "nsIHttpChannel.h"
#include "nsIHttpChannelInternal.h"
#include "nsIEncodedChannel.h"
#include "nsIUploadChannel.h"
#include "nsICacheInfoChannel.h"
#include "nsIFileChannel.h"
#include "nsEscape.h"
#include "nsUnicharUtils.h"
#include "nsIStringEnumerator.h"
#include "nsCRT.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 "nsISHEntry.h"
#include "nsIWebPageDescriptor.h"
#include "nsIFormControl.h"
#include "nsContentUtils.h"
#include "nsIImageLoadingContent.h"
#include "ftpCore.h"
#include "nsITransport.h"
#include "nsISocketTransport.h"
#include "nsIStringBundle.h"
#include "nsIProtocolHandler.h"
#include "nsIWebBrowserPersistable.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/dom/HTMLSharedObjectElement.h"
#include "mozilla/Printf.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;
nsCString mRelativePathToData;
nsCString mCharset;
nsresult GetLocalURI(nsIURI *targetBaseURI, nsCString& aSpecOut);
};
// Information about the output stream
struct nsWebBrowserPersist::OutputData
{
nsCOMPtr<nsIURI> mFile;
nsCOMPtr<nsIURI> mOriginalLocation;
nsCOMPtr<nsIOutputStream> mStream;
int64_t mSelfProgress;
int64_t mSelfProgressMax;
bool mCalcFileExt;
OutputData(nsIURI *aFile, nsIURI *aOriginalLocation, bool aCalcFileExt) :
mFile(aFile),
mOriginalLocation(aOriginalLocation),
mSelfProgress(0),
mSelfProgressMax(10000),
mCalcFileExt(aCalcFileExt)
{
}
~OutputData()
{
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)
{ }
NS_DECL_NSIWEBBROWSERPERSISTRESOURCEVISITOR
NS_DECL_ISUPPORTS
private:
RefPtr<nsWebBrowserPersist> mParent;
nsCOMPtr<nsIURI> mFile;
nsCOMPtr<nsIFile> mDataPath;
virtual ~OnWalk() = default;
};
NS_IMPL_ISUPPORTS(nsWebBrowserPersist::OnWalk,
nsIWebBrowserPersistResourceVisitor)
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),
mFirstAndOnlyUse(true),
mSavingDocument(false),
mCancel(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(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) ? true : false;
mSerializingOutput = (mPersistFlags & PERSIST_FLAGS_SERIALIZE_OUTPUT) ? true : false;
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, nsISupports *aCacheKey,
nsIURI *aReferrer, uint32_t aReferrerPolicy,
nsIInputStream *aPostData, const char *aExtraHeaders,
nsISupports *aFile, nsILoadContext* aPrivacyContext)
{
return SavePrivacyAwareURI(aURI, aCacheKey, aReferrer, aReferrerPolicy,
aPostData, aExtraHeaders, aFile,
aPrivacyContext && aPrivacyContext->UsePrivateBrowsing());
}
NS_IMETHODIMP nsWebBrowserPersist::SavePrivacyAwareURI(
nsIURI *aURI, nsISupports *aCacheKey,
nsIURI *aReferrer, uint32_t aReferrerPolicy,
nsIInputStream *aPostData, const char *aExtraHeaders,
nsISupports *aFile, 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, aCacheKey, aReferrer, aReferrerPolicy,
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<nsIDocument> localDoc = do_QueryInterface(aDocument);
if (localDoc) {
doc = new mozilla::WebBrowserPersistLocalDocument(localDoc);
} else {
rv = NS_ERROR_NO_INTERFACE;
}
}
if (doc) {
rv = SaveDocumentInternal(doc, fileAsURI, datapathAsURI);
}
if (NS_FAILED(rv)) {
SendErrorStatusChange(true, rv, nullptr, mURI);
EndDownload(rv);
}
return rv;
}
NS_IMETHODIMP nsWebBrowserPersist::Cancel(nsresult aReason)
{
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->AsyncOpen2(this);
NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
// add this to the upload list
nsCOMPtr<nsISupports> keyPtr = do_QueryInterface(destChannel);
mUploadList.Put(keyPtr, new UploadData(aDestinationURI));
return NS_OK;
}
void
nsWebBrowserPersist::SerializeNextFile()
{
nsresult rv = NS_OK;
MOZ_ASSERT(mWalkStack.Length() == 0);
// First, handle gathered URIs.
// Count how many URIs in the URI map require persisting
uint32_t urisToPersist = 0;
if (mURIMap.Count() > 0) {
// 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.
for (auto iter = mURIMap.Iter(); !iter.Done(); iter.Next()) {
URIData *data = iter.UserData();
if (data->mNeedsPersisting && !data->mSaved) {
urisToPersist++;
}
}
}
if (urisToPersist > 0) {
// Persist each file in the uri map. The document(s)
// will be saved after the last one of these is saved.
for (auto iter = mURIMap.Iter(); !iter.Done(); iter.Next()) {
URIData *data = iter.UserData();
if (!data->mNeedsPersisting || data->mSaved) {
continue;
}
nsresult rv;
// Create a URI from the key.
nsCOMPtr<nsIURI> uri;
rv = NS_NewURI(getter_AddRefs(uri), iter.Key(),
data->mCharset.get());
if (NS_WARN_IF(NS_FAILED(rv))) {
break;
}
// Make a URI to save the data to.
nsCOMPtr<nsIURI> fileAsURI;
rv = data->mDataPath->Clone(getter_AddRefs(fileAsURI));
if (NS_WARN_IF(NS_FAILED(rv))) {
break;
}
rv = AppendPathToURI(fileAsURI, data->mFilename);
if (NS_WARN_IF(NS_FAILED(rv))) {
break;
}
// The Referrer Policy doesn't matter here since the referrer is
// nullptr.
rv = SaveURIInternal(uri, nullptr, nullptr,
mozilla::net::RP_Unset, 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) {
// Store the actual object because once it's persisted this
// will be fixed up with the right file extension.
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 (auto iter = mURIMap.Iter(); !iter.Done(); iter.Next()) {
nsAutoCString mapTo;
nsresult rv = iter.UserData()->GetLocalURI(mTargetBaseURI, mapTo);
if (NS_SUCCEEDED(rv) || !mapTo.IsVoid()) {
flatMap->Add(iter.Key(), mapTo);
}
}
mFlatURIMap = flatMap.forget();
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, nsISupports *ctxt)
{
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)
{
// 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))
{
// this is the first point at which the server can tell us the mimetype
CalculateAndAppendFileExt(data->mFile, channel, data->mOriginalLocation);
// now make filename conformant and unique
CalculateUniqueFilename(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)
{
// 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, nsISupports *ctxt, 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);
}
// This will automatically close the output stream
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
//*****************************************************************************
NS_IMETHODIMP
nsWebBrowserPersist::OnDataAvailable(
nsIRequest* request, nsISupports *aContext, nsIInputStream *aIStream,
uint64_t aOffset, uint32_t aLength)
{
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);
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;
// 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,
std::min(uint32_t(sizeof(buffer)), bytesRemaining),
&bytesRead);
if (NS_SUCCEEDED(rv))
{
readError = false;
// Write out the data until something goes wrong, or, it is
// all written. We loop because for some errors (e.g., disk
// full), we get NS_OK with some bytes written, then an error.
// So, we want to write again in that case to get the actual
// error code.
const char *bufPtr = buffer; // Where to write from.
while (NS_SUCCEEDED(rv) && bytesRead)
{
uint32_t bytesWritten = 0;
rv = data->mStream->Write(bufPtr, bytesRead, &bytesWritten);
if (NS_SUCCEEDED(rv))
{
bytesRead -= bytesWritten;
bufPtr += bytesWritten;
bytesRemaining -= bytesWritten;
// Force an error if (for some reason) we get NS_OK but
// no bytes written.
if (!bytesWritten)
{
rv = NS_ERROR_FAILURE;
cancel = true;
}
}
else
{
// Disaster - can't write out the bytes - disk full / permission?
cancel = true;
}
}
}
else
{
// Disaster - can't read the bytes - broken link / file error?