forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsOfflineCacheUpdate.cpp
2066 lines (1678 loc) · 60.7 KB
/
nsOfflineCacheUpdate.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 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation
* Portions created by the Initial Developer are Copyright (C) 2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Dave Camp <dcamp@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsOfflineCacheUpdate.h"
#include "nsCPrefetchService.h"
#include "nsCURILoader.h"
#include "nsIApplicationCacheContainer.h"
#include "nsIApplicationCacheChannel.h"
#include "nsIApplicationCacheService.h"
#include "nsICache.h"
#include "nsICacheService.h"
#include "nsICacheSession.h"
#include "nsICachingChannel.h"
#include "nsIContent.h"
#include "mozilla/dom/Element.h"
#include "nsIDocumentLoader.h"
#include "nsIDOMElement.h"
#include "nsIDOMWindow.h"
#include "nsIDOMOfflineResourceList.h"
#include "nsIDocument.h"
#include "nsIObserverService.h"
#include "nsIURL.h"
#include "nsIWebProgress.h"
#include "nsICryptoHash.h"
#include "nsICacheEntryDescriptor.h"
#include "nsIPermissionManager.h"
#include "nsIPrincipal.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsServiceManagerUtils.h"
#include "nsStreamUtils.h"
#include "nsThreadUtils.h"
#include "nsProxyRelease.h"
#include "prlog.h"
#include "nsIAsyncVerifyRedirectCallback.h"
#include "nsXULAppAPI.h"
static const PRUint32 kRescheduleLimit = 3;
#if defined(PR_LOGGING)
//
// To enable logging (see prlog.h for full details):
//
// set NSPR_LOG_MODULES=nsOfflineCacheUpdate:5
// set NSPR_LOG_FILE=offlineupdate.log
//
// this enables PR_LOG_ALWAYS level information and places all output in
// the file offlineupdate.log
//
extern PRLogModuleInfo *gOfflineCacheUpdateLog;
#endif
#define LOG(args) PR_LOG(gOfflineCacheUpdateLog, 4, args)
#define LOG_ENABLED() PR_LOG_TEST(gOfflineCacheUpdateLog, 4)
class AutoFreeArray {
public:
AutoFreeArray(PRUint32 count, char **values)
: mCount(count), mValues(values) {};
~AutoFreeArray() { NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mCount, mValues); }
private:
PRUint32 mCount;
char **mValues;
};
static nsresult
DropReferenceFromURL(nsIURI * aURI)
{
nsCOMPtr<nsIURL> url = do_QueryInterface(aURI);
if (url) {
nsresult rv = url->SetRef(EmptyCString());
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsManifestCheck
//-----------------------------------------------------------------------------
class nsManifestCheck : public nsIStreamListener
, public nsIChannelEventSink
, public nsIInterfaceRequestor
{
public:
nsManifestCheck(nsOfflineCacheUpdate *aUpdate,
nsIURI *aURI,
nsIURI *aReferrerURI)
: mUpdate(aUpdate)
, mURI(aURI)
, mReferrerURI(aReferrerURI)
{}
NS_DECL_ISUPPORTS
NS_DECL_NSIREQUESTOBSERVER
NS_DECL_NSISTREAMLISTENER
NS_DECL_NSICHANNELEVENTSINK
NS_DECL_NSIINTERFACEREQUESTOR
nsresult Begin();
private:
static NS_METHOD ReadManifest(nsIInputStream *aInputStream,
void *aClosure,
const char *aFromSegment,
PRUint32 aOffset,
PRUint32 aCount,
PRUint32 *aBytesConsumed);
nsRefPtr<nsOfflineCacheUpdate> mUpdate;
nsCOMPtr<nsIURI> mURI;
nsCOMPtr<nsIURI> mReferrerURI;
nsCOMPtr<nsICryptoHash> mManifestHash;
nsCOMPtr<nsIChannel> mChannel;
};
//-----------------------------------------------------------------------------
// nsManifestCheck::nsISupports
//-----------------------------------------------------------------------------
NS_IMPL_ISUPPORTS4(nsManifestCheck,
nsIRequestObserver,
nsIStreamListener,
nsIChannelEventSink,
nsIInterfaceRequestor)
//-----------------------------------------------------------------------------
// nsManifestCheck <public>
//-----------------------------------------------------------------------------
nsresult
nsManifestCheck::Begin()
{
nsresult rv;
mManifestHash = do_CreateInstance("@mozilla.org/security/hash;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = mManifestHash->Init(nsICryptoHash::MD5);
NS_ENSURE_SUCCESS(rv, rv);
rv = NS_NewChannel(getter_AddRefs(mChannel),
mURI,
nsnull, nsnull, nsnull,
nsIRequest::LOAD_BYPASS_CACHE);
NS_ENSURE_SUCCESS(rv, rv);
// configure HTTP specific stuff
nsCOMPtr<nsIHttpChannel> httpChannel =
do_QueryInterface(mChannel);
if (httpChannel) {
httpChannel->SetReferrer(mReferrerURI);
httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("X-Moz"),
NS_LITERAL_CSTRING("offline-resource"),
PR_FALSE);
}
rv = mChannel->AsyncOpen(this, nsnull);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsManifestCheck <public>
//-----------------------------------------------------------------------------
/* static */
NS_METHOD
nsManifestCheck::ReadManifest(nsIInputStream *aInputStream,
void *aClosure,
const char *aFromSegment,
PRUint32 aOffset,
PRUint32 aCount,
PRUint32 *aBytesConsumed)
{
nsManifestCheck *manifestCheck =
static_cast<nsManifestCheck*>(aClosure);
nsresult rv;
*aBytesConsumed = aCount;
rv = manifestCheck->mManifestHash->Update(
reinterpret_cast<const PRUint8 *>(aFromSegment), aCount);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsManifestCheck::nsIStreamListener
//-----------------------------------------------------------------------------
NS_IMETHODIMP
nsManifestCheck::OnStartRequest(nsIRequest *aRequest,
nsISupports *aContext)
{
return NS_OK;
}
NS_IMETHODIMP
nsManifestCheck::OnDataAvailable(nsIRequest *aRequest,
nsISupports *aContext,
nsIInputStream *aStream,
PRUint32 aOffset,
PRUint32 aCount)
{
PRUint32 bytesRead;
aStream->ReadSegments(ReadManifest, this, aCount, &bytesRead);
return NS_OK;
}
NS_IMETHODIMP
nsManifestCheck::OnStopRequest(nsIRequest *aRequest,
nsISupports *aContext,
nsresult aStatus)
{
nsCAutoString manifestHash;
if (NS_SUCCEEDED(aStatus)) {
mManifestHash->Finish(PR_TRUE, manifestHash);
}
mUpdate->ManifestCheckCompleted(aStatus, manifestHash);
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsManifestCheck::nsIInterfaceRequestor
//-----------------------------------------------------------------------------
NS_IMETHODIMP
nsManifestCheck::GetInterface(const nsIID &aIID, void **aResult)
{
if (aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
NS_ADDREF_THIS();
*aResult = static_cast<nsIChannelEventSink *>(this);
return NS_OK;
}
return NS_ERROR_NO_INTERFACE;
}
//-----------------------------------------------------------------------------
// nsManifestCheck::nsIChannelEventSink
//-----------------------------------------------------------------------------
NS_IMETHODIMP
nsManifestCheck::AsyncOnChannelRedirect(nsIChannel *aOldChannel,
nsIChannel *aNewChannel,
PRUint32 aFlags,
nsIAsyncVerifyRedirectCallback *callback)
{
// Redirects should cause the load (and therefore the update) to fail.
if (aFlags & nsIChannelEventSink::REDIRECT_INTERNAL) {
callback->OnRedirectVerifyCallback(NS_OK);
return NS_OK;
}
aOldChannel->Cancel(NS_ERROR_ABORT);
return NS_ERROR_ABORT;
}
//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateItem::nsISupports
//-----------------------------------------------------------------------------
NS_IMPL_ISUPPORTS6(nsOfflineCacheUpdateItem,
nsIDOMLoadStatus,
nsIRequestObserver,
nsIStreamListener,
nsIRunnable,
nsIInterfaceRequestor,
nsIChannelEventSink)
//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateItem <public>
//-----------------------------------------------------------------------------
nsOfflineCacheUpdateItem::nsOfflineCacheUpdateItem(nsOfflineCacheUpdate *aUpdate,
nsIURI *aURI,
nsIURI *aReferrerURI,
nsIApplicationCache *aPreviousApplicationCache,
const nsACString &aClientID,
PRUint32 type)
: mURI(aURI)
, mReferrerURI(aReferrerURI)
, mPreviousApplicationCache(aPreviousApplicationCache)
, mClientID(aClientID)
, mItemType(type)
, mUpdate(aUpdate)
, mChannel(nsnull)
, mState(nsIDOMLoadStatus::UNINITIALIZED)
, mBytesRead(0)
{
}
nsOfflineCacheUpdateItem::~nsOfflineCacheUpdateItem()
{
}
nsresult
nsOfflineCacheUpdateItem::OpenChannel()
{
#if defined(PR_LOGGING)
if (LOG_ENABLED()) {
nsCAutoString spec;
mURI->GetSpec(spec);
LOG(("%p: Opening channel for %s", this, spec.get()));
}
#endif
nsresult rv = nsOfflineCacheUpdate::GetCacheKey(mURI, mCacheKey);
NS_ENSURE_SUCCESS(rv, rv);
rv = NS_NewChannel(getter_AddRefs(mChannel),
mURI,
nsnull, nsnull, this,
nsIRequest::LOAD_BACKGROUND |
nsICachingChannel::LOAD_ONLY_IF_MODIFIED |
nsICachingChannel::LOAD_CHECK_OFFLINE_CACHE);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIApplicationCacheChannel> appCacheChannel =
do_QueryInterface(mChannel, &rv);
// Support for nsIApplicationCacheChannel is required.
NS_ENSURE_SUCCESS(rv, rv);
// Use the existing application cache as the cache to check.
rv = appCacheChannel->SetApplicationCache(mPreviousApplicationCache);
NS_ENSURE_SUCCESS(rv, rv);
// configure HTTP specific stuff
nsCOMPtr<nsIHttpChannel> httpChannel =
do_QueryInterface(mChannel);
if (httpChannel) {
httpChannel->SetReferrer(mReferrerURI);
httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("X-Moz"),
NS_LITERAL_CSTRING("offline-resource"),
PR_FALSE);
}
nsCOMPtr<nsICachingChannel> cachingChannel =
do_QueryInterface(mChannel);
if (cachingChannel) {
rv = cachingChannel->SetCacheForOfflineUse(PR_TRUE);
NS_ENSURE_SUCCESS(rv, rv);
if (!mClientID.IsEmpty()) {
rv = cachingChannel->SetOfflineCacheClientID(mClientID);
NS_ENSURE_SUCCESS(rv, rv);
}
}
rv = mChannel->AsyncOpen(this, nsnull);
NS_ENSURE_SUCCESS(rv, rv);
mState = nsIDOMLoadStatus::REQUESTED;
return NS_OK;
}
nsresult
nsOfflineCacheUpdateItem::Cancel()
{
if (mChannel) {
mChannel->Cancel(NS_ERROR_ABORT);
mChannel = nsnull;
}
mState = nsIDOMLoadStatus::UNINITIALIZED;
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateItem::nsIStreamListener
//-----------------------------------------------------------------------------
NS_IMETHODIMP
nsOfflineCacheUpdateItem::OnStartRequest(nsIRequest *aRequest,
nsISupports *aContext)
{
mState = nsIDOMLoadStatus::RECEIVING;
return NS_OK;
}
NS_IMETHODIMP
nsOfflineCacheUpdateItem::OnDataAvailable(nsIRequest *aRequest,
nsISupports *aContext,
nsIInputStream *aStream,
PRUint32 aOffset,
PRUint32 aCount)
{
PRUint32 bytesRead = 0;
aStream->ReadSegments(NS_DiscardSegment, nsnull, aCount, &bytesRead);
mBytesRead += bytesRead;
LOG(("loaded %u bytes into offline cache [offset=%u]\n",
bytesRead, aOffset));
return NS_OK;
}
NS_IMETHODIMP
nsOfflineCacheUpdateItem::OnStopRequest(nsIRequest *aRequest,
nsISupports *aContext,
nsresult aStatus)
{
LOG(("done fetching offline item [status=%x]\n", aStatus));
mState = nsIDOMLoadStatus::LOADED;
if (mBytesRead == 0 && aStatus == NS_OK) {
// we didn't need to read (because LOAD_ONLY_IF_MODIFIED was
// specified), but the object should report loadedSize as if it
// did.
mChannel->GetContentLength(&mBytesRead);
}
// We need to notify the update that the load is complete, but we
// want to give the channel a chance to close the cache entries.
NS_DispatchToCurrentThread(this);
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateItem::nsIRunnable
//-----------------------------------------------------------------------------
NS_IMETHODIMP
nsOfflineCacheUpdateItem::Run()
{
mUpdate->LoadCompleted();
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateItem::nsIInterfaceRequestor
//-----------------------------------------------------------------------------
NS_IMETHODIMP
nsOfflineCacheUpdateItem::GetInterface(const nsIID &aIID, void **aResult)
{
if (aIID.Equals(NS_GET_IID(nsIChannelEventSink))) {
NS_ADDREF_THIS();
*aResult = static_cast<nsIChannelEventSink *>(this);
return NS_OK;
}
return NS_ERROR_NO_INTERFACE;
}
//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateItem::nsIChannelEventSink
//-----------------------------------------------------------------------------
NS_IMETHODIMP
nsOfflineCacheUpdateItem::AsyncOnChannelRedirect(nsIChannel *aOldChannel,
nsIChannel *aNewChannel,
PRUint32 aFlags,
nsIAsyncVerifyRedirectCallback *cb)
{
if (!(aFlags & nsIChannelEventSink::REDIRECT_INTERNAL)) {
// Don't allow redirect in case of non-internal redirect and cancel
// the channel to clean the cache entry.
aOldChannel->Cancel(NS_ERROR_ABORT);
return NS_ERROR_ABORT;
}
nsCOMPtr<nsIURI> newURI;
nsresult rv = aNewChannel->GetURI(getter_AddRefs(newURI));
if (NS_FAILED(rv))
return rv;
nsCOMPtr<nsICachingChannel> oldCachingChannel =
do_QueryInterface(aOldChannel);
nsCOMPtr<nsICachingChannel> newCachingChannel =
do_QueryInterface(aNewChannel);
if (newCachingChannel) {
rv = newCachingChannel->SetCacheForOfflineUse(PR_TRUE);
NS_ENSURE_SUCCESS(rv, rv);
if (!mClientID.IsEmpty()) {
rv = newCachingChannel->SetOfflineCacheClientID(mClientID);
NS_ENSURE_SUCCESS(rv, rv);
}
}
nsCAutoString oldScheme;
mURI->GetScheme(oldScheme);
PRBool match;
if (NS_FAILED(newURI->SchemeIs(oldScheme.get(), &match)) || !match) {
LOG(("rejected: redirected to a different scheme\n"));
return NS_ERROR_ABORT;
}
// HTTP request headers are not automatically forwarded to the new channel.
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aNewChannel);
NS_ENSURE_STATE(httpChannel);
httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("X-Moz"),
NS_LITERAL_CSTRING("offline-resource"),
PR_FALSE);
mChannel = aNewChannel;
cb->OnRedirectVerifyCallback(NS_OK);
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsOfflineCacheUpdateItem::nsIDOMLoadStatus
//-----------------------------------------------------------------------------
NS_IMETHODIMP
nsOfflineCacheUpdateItem::GetSource(nsIDOMNode **aSource)
{
*aSource = nsnull;
return NS_OK;
}
NS_IMETHODIMP
nsOfflineCacheUpdateItem::GetUri(nsAString &aURI)
{
nsCAutoString spec;
nsresult rv = mURI->GetSpec(spec);
NS_ENSURE_SUCCESS(rv, rv);
CopyUTF8toUTF16(spec, aURI);
return NS_OK;
}
NS_IMETHODIMP
nsOfflineCacheUpdateItem::GetTotalSize(PRInt32 *aTotalSize)
{
if (mChannel) {
return mChannel->GetContentLength(aTotalSize);
}
*aTotalSize = -1;
return NS_OK;
}
NS_IMETHODIMP
nsOfflineCacheUpdateItem::GetLoadedSize(PRInt32 *aLoadedSize)
{
*aLoadedSize = mBytesRead;
return NS_OK;
}
NS_IMETHODIMP
nsOfflineCacheUpdateItem::GetReadyState(PRUint16 *aReadyState)
{
*aReadyState = mState;
return NS_OK;
}
nsresult
nsOfflineCacheUpdateItem::GetRequestSucceeded(PRBool * succeeded)
{
*succeeded = PR_FALSE;
if (!mChannel)
return NS_OK;
nsresult rv;
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(mChannel, &rv);
NS_ENSURE_SUCCESS(rv, rv);
PRBool reqSucceeded;
rv = httpChannel->GetRequestSucceeded(&reqSucceeded);
if (NS_ERROR_NOT_AVAILABLE == rv)
return NS_OK;
NS_ENSURE_SUCCESS(rv, rv);
if (!reqSucceeded) {
LOG(("Request failed"));
return NS_OK;
}
nsresult channelStatus;
rv = httpChannel->GetStatus(&channelStatus);
NS_ENSURE_SUCCESS(rv, rv);
if (NS_FAILED(channelStatus)) {
LOG(("Channel status=0x%08x", channelStatus));
return NS_OK;
}
*succeeded = PR_TRUE;
return NS_OK;
}
NS_IMETHODIMP
nsOfflineCacheUpdateItem::GetStatus(PRUint16 *aStatus)
{
if (!mChannel) {
*aStatus = 0;
return NS_OK;
}
nsresult rv;
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(mChannel, &rv);
NS_ENSURE_SUCCESS(rv, rv);
PRUint32 httpStatus;
rv = httpChannel->GetResponseStatus(&httpStatus);
if (rv == NS_ERROR_NOT_AVAILABLE) {
*aStatus = 0;
return NS_OK;
}
NS_ENSURE_SUCCESS(rv, rv);
*aStatus = PRUint16(httpStatus);
return NS_OK;
}
//-----------------------------------------------------------------------------
// nsOfflineManifestItem
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// nsOfflineManifestItem <public>
//-----------------------------------------------------------------------------
nsOfflineManifestItem::nsOfflineManifestItem(nsOfflineCacheUpdate *aUpdate,
nsIURI *aURI,
nsIURI *aReferrerURI,
nsIApplicationCache *aPreviousApplicationCache,
const nsACString &aClientID)
: nsOfflineCacheUpdateItem(aUpdate, aURI, aReferrerURI,
aPreviousApplicationCache, aClientID,
nsIApplicationCache::ITEM_MANIFEST)
, mParserState(PARSE_INIT)
, mNeedsUpdate(PR_TRUE)
, mManifestHashInitialized(PR_FALSE)
{
ReadStrictFileOriginPolicyPref();
}
nsOfflineManifestItem::~nsOfflineManifestItem()
{
}
//-----------------------------------------------------------------------------
// nsOfflineManifestItem <private>
//-----------------------------------------------------------------------------
/* static */
NS_METHOD
nsOfflineManifestItem::ReadManifest(nsIInputStream *aInputStream,
void *aClosure,
const char *aFromSegment,
PRUint32 aOffset,
PRUint32 aCount,
PRUint32 *aBytesConsumed)
{
nsOfflineManifestItem *manifest =
static_cast<nsOfflineManifestItem*>(aClosure);
nsresult rv;
*aBytesConsumed = aCount;
if (manifest->mParserState == PARSE_ERROR) {
// parse already failed, ignore this
return NS_OK;
}
if (!manifest->mManifestHashInitialized) {
// Avoid re-creation of crypto hash when it fails from some reason the first time
manifest->mManifestHashInitialized = PR_TRUE;
manifest->mManifestHash = do_CreateInstance("@mozilla.org/security/hash;1", &rv);
if (NS_SUCCEEDED(rv)) {
rv = manifest->mManifestHash->Init(nsICryptoHash::MD5);
if (NS_FAILED(rv)) {
manifest->mManifestHash = nsnull;
LOG(("Could not initialize manifest hash for byte-to-byte check, rv=%08x", rv));
}
}
}
if (manifest->mManifestHash) {
rv = manifest->mManifestHash->Update(reinterpret_cast<const PRUint8 *>(aFromSegment), aCount);
if (NS_FAILED(rv)) {
manifest->mManifestHash = nsnull;
LOG(("Could not update manifest hash, rv=%08x", rv));
}
}
manifest->mReadBuf.Append(aFromSegment, aCount);
nsCString::const_iterator begin, iter, end;
manifest->mReadBuf.BeginReading(begin);
manifest->mReadBuf.EndReading(end);
for (iter = begin; iter != end; iter++) {
if (*iter == '\r' || *iter == '\n') {
nsresult rv = manifest->HandleManifestLine(begin, iter);
if (NS_FAILED(rv)) {
LOG(("HandleManifestLine failed with 0x%08x", rv));
return NS_ERROR_ABORT;
}
begin = iter;
begin++;
}
}
// any leftovers are saved for next time
manifest->mReadBuf = Substring(begin, end);
return NS_OK;
}
nsresult
nsOfflineManifestItem::AddNamespace(PRUint32 namespaceType,
const nsCString &namespaceSpec,
const nsCString &data)
{
nsresult rv;
if (!mNamespaces) {
mNamespaces = do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
}
nsCOMPtr<nsIApplicationCacheNamespace> ns =
do_CreateInstance(NS_APPLICATIONCACHENAMESPACE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = ns->Init(namespaceType, namespaceSpec, data);
NS_ENSURE_SUCCESS(rv, rv);
rv = mNamespaces->AppendElement(ns, PR_FALSE);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
nsresult
nsOfflineManifestItem::HandleManifestLine(const nsCString::const_iterator &aBegin,
const nsCString::const_iterator &aEnd)
{
nsCString::const_iterator begin = aBegin;
nsCString::const_iterator end = aEnd;
// all lines ignore trailing spaces and tabs
nsCString::const_iterator last = end;
--last;
while (end != begin && (*last == ' ' || *last == '\t')) {
--end;
--last;
}
if (mParserState == PARSE_INIT) {
// Allow a UTF-8 BOM
if (begin != end && static_cast<unsigned char>(*begin) == 0xef) {
if (++begin == end || static_cast<unsigned char>(*begin) != 0xbb ||
++begin == end || static_cast<unsigned char>(*begin) != 0xbf) {
mParserState = PARSE_ERROR;
return NS_OK;
}
++begin;
}
const nsCSubstring &magic = Substring(begin, end);
if (!magic.EqualsLiteral("CACHE MANIFEST")) {
mParserState = PARSE_ERROR;
return NS_OK;
}
mParserState = PARSE_CACHE_ENTRIES;
return NS_OK;
}
// lines other than the first ignore leading spaces and tabs
while (begin != end && (*begin == ' ' || *begin == '\t'))
begin++;
// ignore blank lines and comments
if (begin == end || *begin == '#')
return NS_OK;
const nsCSubstring &line = Substring(begin, end);
if (line.EqualsLiteral("CACHE:")) {
mParserState = PARSE_CACHE_ENTRIES;
return NS_OK;
}
if (line.EqualsLiteral("FALLBACK:")) {
mParserState = PARSE_FALLBACK_ENTRIES;
return NS_OK;
}
if (line.EqualsLiteral("NETWORK:")) {
mParserState = PARSE_BYPASS_ENTRIES;
return NS_OK;
}
nsresult rv;
switch(mParserState) {
case PARSE_INIT:
case PARSE_ERROR: {
// this should have been dealt with earlier
return NS_ERROR_FAILURE;
}
case PARSE_CACHE_ENTRIES: {
nsCOMPtr<nsIURI> uri;
rv = NS_NewURI(getter_AddRefs(uri), line, nsnull, mURI);
if (NS_FAILED(rv))
break;
if (NS_FAILED(DropReferenceFromURL(uri)))
break;
nsCAutoString scheme;
uri->GetScheme(scheme);
// Manifest URIs must have the same scheme as the manifest.
PRBool match;
if (NS_FAILED(mURI->SchemeIs(scheme.get(), &match)) || !match)
break;
mExplicitURIs.AppendObject(uri);
break;
}
case PARSE_FALLBACK_ENTRIES: {
PRInt32 separator = line.FindChar(' ');
if (separator == kNotFound) {
separator = line.FindChar('\t');
if (separator == kNotFound)
break;
}
nsCString namespaceSpec(Substring(line, 0, separator));
nsCString fallbackSpec(Substring(line, separator + 1));
namespaceSpec.CompressWhitespace();
fallbackSpec.CompressWhitespace();
nsCOMPtr<nsIURI> namespaceURI;
rv = NS_NewURI(getter_AddRefs(namespaceURI), namespaceSpec, nsnull, mURI);
if (NS_FAILED(rv))
break;
if (NS_FAILED(DropReferenceFromURL(namespaceURI)))
break;
rv = namespaceURI->GetAsciiSpec(namespaceSpec);
if (NS_FAILED(rv))
break;
nsCOMPtr<nsIURI> fallbackURI;
rv = NS_NewURI(getter_AddRefs(fallbackURI), fallbackSpec, nsnull, mURI);
if (NS_FAILED(rv))
break;
if (NS_FAILED(DropReferenceFromURL(fallbackURI)))
break;
rv = fallbackURI->GetAsciiSpec(fallbackSpec);
if (NS_FAILED(rv))
break;
// Manifest and namespace must be same origin
if (!NS_SecurityCompareURIs(mURI, namespaceURI,
mStrictFileOriginPolicy))
break;
// Fallback and namespace must be same origin
if (!NS_SecurityCompareURIs(namespaceURI, fallbackURI,
mStrictFileOriginPolicy))
break;
mFallbackURIs.AppendObject(fallbackURI);
AddNamespace(nsIApplicationCacheNamespace::NAMESPACE_FALLBACK,
namespaceSpec, fallbackSpec);
break;
}
case PARSE_BYPASS_ENTRIES: {
if (line[0] == '*' && (line.Length() == 1 || line[1] == ' ' || line[1] == '\t'))
{
// '*' indicates to make the online whitelist wildcard flag open,
// i.e. do allow load of resources not present in the offline cache
// or not conforming any namespace.
// We achive that simply by adding an 'empty' - i.e. universal
// namespace of BYPASS type into the cache.
AddNamespace(nsIApplicationCacheNamespace::NAMESPACE_BYPASS,
EmptyCString(), EmptyCString());
break;
}
nsCOMPtr<nsIURI> bypassURI;
rv = NS_NewURI(getter_AddRefs(bypassURI), line, nsnull, mURI);
if (NS_FAILED(rv))
break;
nsCAutoString scheme;
bypassURI->GetScheme(scheme);
PRBool equals;
if (NS_FAILED(mURI->SchemeIs(scheme.get(), &equals)) || !equals)
break;
if (NS_FAILED(DropReferenceFromURL(bypassURI)))
break;
nsCString spec;
if (NS_FAILED(bypassURI->GetAsciiSpec(spec)))
break;
AddNamespace(nsIApplicationCacheNamespace::NAMESPACE_BYPASS,
spec, EmptyCString());
break;
}
}
return NS_OK;
}
nsresult
nsOfflineManifestItem::GetOldManifestContentHash(nsIRequest *aRequest)
{
nsresult rv;
nsCOMPtr<nsICachingChannel> cachingChannel = do_QueryInterface(aRequest, &rv);
NS_ENSURE_SUCCESS(rv, rv);
// load the main cache token that is actually the old offline cache token and
// read previous manifest content hash value
nsCOMPtr<nsISupports> cacheToken;
cachingChannel->GetCacheToken(getter_AddRefs(cacheToken));
if (cacheToken) {
nsCOMPtr<nsICacheEntryDescriptor> cacheDescriptor(do_QueryInterface(cacheToken, &rv));
NS_ENSURE_SUCCESS(rv, rv);
rv = cacheDescriptor->GetMetaDataElement("offline-manifest-hash", getter_Copies(mOldManifestHashValue));
if (NS_FAILED(rv))
mOldManifestHashValue.Truncate();
}
return NS_OK;
}
nsresult
nsOfflineManifestItem::CheckNewManifestContentHash(nsIRequest *aRequest)
{
nsresult rv;
if (!mManifestHash) {
// Nothing to compare against...
return NS_OK;
}
nsCString newManifestHashValue;
rv = mManifestHash->Finish(PR_TRUE, mManifestHashValue);
mManifestHash = nsnull;