This repository was archived by the owner on Jul 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathCacheStorageService.cpp
More file actions
2274 lines (1803 loc) · 68.4 KB
/
Copy pathCacheStorageService.cpp
File metadata and controls
2274 lines (1803 loc) · 68.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "CacheLog.h"
#include "CacheStorageService.h"
#include "CacheFileIOManager.h"
#include "CacheObserver.h"
#include "CacheIndex.h"
#include "CacheIndexIterator.h"
#include "CacheStorage.h"
#include "AppCacheStorage.h"
#include "CacheEntry.h"
#include "CacheFileUtils.h"
#include "OldWrappers.h"
#include "nsCacheService.h"
#include "nsDeleteDir.h"
#include "nsICacheStorageVisitor.h"
#include "nsIObserverService.h"
#include "nsIFile.h"
#include "nsIURI.h"
#include "nsCOMPtr.h"
#include "nsContentUtils.h"
#include "nsAutoPtr.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsServiceManagerUtils.h"
#include "nsXULAppAPI.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Services.h"
#include "mozilla/IntegerPrintfMacros.h"
namespace mozilla {
namespace net {
namespace {
void AppendMemoryStorageTag(nsAutoCString& key) {
// Using DEL as the very last ascii-7 character we can use in the list of
// attributes
key.Append('\x7f');
key.Append(',');
}
} // namespace
// Not defining as static or class member of CacheStorageService since
// it would otherwise need to include CacheEntry.h and that then would
// need to be exported to make nsNetModule.cpp compilable.
typedef nsClassHashtable<nsCStringHashKey, CacheEntryTable> GlobalEntryTables;
/**
* Keeps tables of entries. There is one entries table for each distinct load
* context type. The distinction is based on following load context info
* states: <isPrivate|isAnon|inIsolatedMozBrowser> which builds a mapping
* key.
*
* Thread-safe to access, protected by the service mutex.
*/
static GlobalEntryTables* sGlobalEntryTables;
CacheMemoryConsumer::CacheMemoryConsumer(uint32_t aFlags)
: mReportedMemoryConsumption(0), mFlags(aFlags) {}
void CacheMemoryConsumer::DoMemoryReport(uint32_t aCurrentSize) {
if (!(mFlags & DONT_REPORT) && CacheStorageService::Self()) {
CacheStorageService::Self()->OnMemoryConsumptionChange(this, aCurrentSize);
}
}
CacheStorageService::MemoryPool::MemoryPool(EType aType)
: mType(aType), mMemorySize(0) {}
CacheStorageService::MemoryPool::~MemoryPool() {
if (mMemorySize != 0) {
NS_ERROR(
"Network cache reported memory consumption is not at 0, probably "
"leaking?");
}
}
uint32_t CacheStorageService::MemoryPool::Limit() const {
uint32_t limit = 0;
switch (mType) {
case DISK:
limit = CacheObserver::MetadataMemoryLimit();
break;
case MEMORY:
limit = CacheObserver::MemoryCacheCapacity();
break;
default:
MOZ_CRASH("Bad pool type");
}
static const uint32_t kMaxLimit = 0x3FFFFF;
if (limit > kMaxLimit) {
LOG((" a memory limit (%u) is unexpectedly high, clipping to %u", limit,
kMaxLimit));
limit = kMaxLimit;
}
return limit << 10;
}
NS_IMPL_ISUPPORTS(CacheStorageService, nsICacheStorageService,
nsIMemoryReporter, nsITimerCallback, nsICacheTesting,
nsINamed)
CacheStorageService* CacheStorageService::sSelf = nullptr;
CacheStorageService::CacheStorageService()
: mLock("CacheStorageService.mLock"),
mForcedValidEntriesLock("CacheStorageService.mForcedValidEntriesLock"),
mShutdown(false),
mDiskPool(MemoryPool::DISK),
mMemoryPool(MemoryPool::MEMORY) {
CacheFileIOManager::Init();
MOZ_ASSERT(XRE_IsParentProcess());
MOZ_ASSERT(!sSelf);
sSelf = this;
sGlobalEntryTables = new GlobalEntryTables();
RegisterStrongMemoryReporter(this);
}
CacheStorageService::~CacheStorageService() {
LOG(("CacheStorageService::~CacheStorageService"));
sSelf = nullptr;
}
void CacheStorageService::Shutdown() {
mozilla::MutexAutoLock lock(mLock);
if (mShutdown) return;
LOG(("CacheStorageService::Shutdown - start"));
mShutdown = true;
nsCOMPtr<nsIRunnable> event =
NewRunnableMethod("net::CacheStorageService::ShutdownBackground", this,
&CacheStorageService::ShutdownBackground);
Dispatch(event);
#ifdef NS_FREE_PERMANENT_DATA
sGlobalEntryTables->Clear();
delete sGlobalEntryTables;
#endif
sGlobalEntryTables = nullptr;
LOG(("CacheStorageService::Shutdown - done"));
}
void CacheStorageService::ShutdownBackground() {
LOG(("CacheStorageService::ShutdownBackground - start"));
MOZ_ASSERT(IsOnManagementThread());
{
mozilla::MutexAutoLock lock(mLock);
// Cancel purge timer to avoid leaking.
if (mPurgeTimer) {
LOG((" freeing the timer"));
mPurgeTimer->Cancel();
}
}
#ifdef NS_FREE_PERMANENT_DATA
Pool(false).mFrecencyArray.Clear();
Pool(false).mExpirationArray.Clear();
Pool(true).mFrecencyArray.Clear();
Pool(true).mExpirationArray.Clear();
#endif
LOG(("CacheStorageService::ShutdownBackground - done"));
}
// Internal management methods
namespace {
// WalkCacheRunnable
// Base class for particular storage entries visiting
class WalkCacheRunnable : public Runnable,
public CacheStorageService::EntryInfoCallback {
protected:
WalkCacheRunnable(nsICacheStorageVisitor* aVisitor, bool aVisitEntries)
: Runnable("net::WalkCacheRunnable"),
mService(CacheStorageService::Self()),
mCallback(aVisitor),
mSize(0),
mNotifyStorage(true),
mVisitEntries(aVisitEntries),
mCancel(false) {
MOZ_ASSERT(NS_IsMainThread());
}
virtual ~WalkCacheRunnable() {
if (mCallback) {
ProxyReleaseMainThread("WalkCacheRunnable::mCallback", mCallback);
}
}
RefPtr<CacheStorageService> mService;
nsCOMPtr<nsICacheStorageVisitor> mCallback;
uint64_t mSize;
bool mNotifyStorage : 1;
bool mVisitEntries : 1;
Atomic<bool> mCancel;
};
// WalkMemoryCacheRunnable
// Responsible to visit memory storage and walk
// all entries on it asynchronously.
class WalkMemoryCacheRunnable : public WalkCacheRunnable {
public:
WalkMemoryCacheRunnable(nsILoadContextInfo* aLoadInfo, bool aVisitEntries,
nsICacheStorageVisitor* aVisitor)
: WalkCacheRunnable(aVisitor, aVisitEntries) {
CacheFileUtils::AppendKeyPrefix(aLoadInfo, mContextKey);
MOZ_ASSERT(NS_IsMainThread());
}
nsresult Walk() { return mService->Dispatch(this); }
private:
NS_IMETHOD Run() override {
if (CacheStorageService::IsOnManagementThread()) {
LOG(("WalkMemoryCacheRunnable::Run - collecting [this=%p]", this));
// First, walk, count and grab all entries from the storage
mozilla::MutexAutoLock lock(CacheStorageService::Self()->Lock());
if (!CacheStorageService::IsRunning()) return NS_ERROR_NOT_INITIALIZED;
CacheEntryTable* entries;
if (sGlobalEntryTables->Get(mContextKey, &entries)) {
for (auto iter = entries->Iter(); !iter.Done(); iter.Next()) {
CacheEntry* entry = iter.UserData();
// Ignore disk entries
if (entry->IsUsingDisk()) {
continue;
}
mSize += entry->GetMetadataMemoryConsumption();
int64_t size;
if (NS_SUCCEEDED(entry->GetDataSize(&size))) {
mSize += size;
}
mEntryArray.AppendElement(entry);
}
}
// Next, we dispatch to the main thread
} else if (NS_IsMainThread()) {
LOG(("WalkMemoryCacheRunnable::Run - notifying [this=%p]", this));
if (mNotifyStorage) {
LOG((" storage"));
uint64_t capacity = CacheObserver::MemoryCacheCapacity();
capacity <<= 10; // kilobytes to bytes
// Second, notify overall storage info
mCallback->OnCacheStorageInfo(mEntryArray.Length(), mSize, capacity,
nullptr);
if (!mVisitEntries) return NS_OK; // done
mNotifyStorage = false;
} else {
LOG((" entry [left=%zu, canceled=%d]", mEntryArray.Length(),
(bool)mCancel));
// Third, notify each entry until depleted or canceled
if (!mEntryArray.Length() || mCancel) {
mCallback->OnCacheEntryVisitCompleted();
return NS_OK; // done
}
// Grab the next entry
RefPtr<CacheEntry> entry = mEntryArray[0];
mEntryArray.RemoveElementAt(0);
// Invokes this->OnEntryInfo, that calls the callback with all
// information of the entry.
CacheStorageService::GetCacheEntryInfo(entry, this);
}
} else {
MOZ_CRASH("Bad thread");
return NS_ERROR_FAILURE;
}
NS_DispatchToMainThread(this);
return NS_OK;
}
virtual ~WalkMemoryCacheRunnable() {
if (mCallback)
ProxyReleaseMainThread("WalkMemoryCacheRunnable::mCallback", mCallback);
}
virtual void OnEntryInfo(const nsACString& aURISpec,
const nsACString& aIdEnhance, int64_t aDataSize,
int32_t aFetchCount, uint32_t aLastModifiedTime,
uint32_t aExpirationTime, bool aPinned,
nsILoadContextInfo* aInfo) override {
nsresult rv;
nsCOMPtr<nsIURI> uri;
rv = NS_NewURI(getter_AddRefs(uri), aURISpec);
if (NS_FAILED(rv)) {
return;
}
rv = mCallback->OnCacheEntryInfo(uri, aIdEnhance, aDataSize, aFetchCount,
aLastModifiedTime, aExpirationTime,
aPinned, aInfo);
if (NS_FAILED(rv)) {
LOG((" callback failed, canceling the walk"));
mCancel = true;
}
}
private:
nsCString mContextKey;
nsTArray<RefPtr<CacheEntry>> mEntryArray;
};
// WalkDiskCacheRunnable
// Using the cache index information to get the list of files per context.
class WalkDiskCacheRunnable : public WalkCacheRunnable {
public:
WalkDiskCacheRunnable(nsILoadContextInfo* aLoadInfo, bool aVisitEntries,
nsICacheStorageVisitor* aVisitor)
: WalkCacheRunnable(aVisitor, aVisitEntries),
mLoadInfo(aLoadInfo),
mPass(COLLECT_STATS),
mCount(0) {}
nsresult Walk() {
// TODO, bug 998693
// Initial index build should be forced here so that about:cache soon
// after startup gives some meaningfull results.
// Dispatch to the INDEX level in hope that very recent cache entries
// information gets to the index list before we grab the index iterator
// for the first time. This tries to avoid miss of entries that has
// been created right before the visit is required.
RefPtr<CacheIOThread> thread = CacheFileIOManager::IOThread();
NS_ENSURE_TRUE(thread, NS_ERROR_NOT_INITIALIZED);
return thread->Dispatch(this, CacheIOThread::INDEX);
}
private:
// Invokes OnCacheEntryInfo callback for each single found entry.
// There is one instance of this class per one entry.
class OnCacheEntryInfoRunnable : public Runnable {
public:
explicit OnCacheEntryInfoRunnable(WalkDiskCacheRunnable* aWalker)
: Runnable("net::WalkDiskCacheRunnable::OnCacheEntryInfoRunnable"),
mWalker(aWalker),
mDataSize(0),
mFetchCount(0),
mLastModifiedTime(0),
mExpirationTime(0),
mPinned(false) {}
NS_IMETHOD Run() override {
MOZ_ASSERT(NS_IsMainThread());
nsresult rv;
nsCOMPtr<nsIURI> uri;
rv = NS_NewURI(getter_AddRefs(uri), mURISpec);
if (NS_FAILED(rv)) {
return NS_OK;
}
rv = mWalker->mCallback->OnCacheEntryInfo(
uri, mIdEnhance, mDataSize, mFetchCount, mLastModifiedTime,
mExpirationTime, mPinned, mInfo);
if (NS_FAILED(rv)) {
mWalker->mCancel = true;
}
return NS_OK;
}
RefPtr<WalkDiskCacheRunnable> mWalker;
nsCString mURISpec;
nsCString mIdEnhance;
int64_t mDataSize;
int32_t mFetchCount;
uint32_t mLastModifiedTime;
uint32_t mExpirationTime;
bool mPinned;
nsCOMPtr<nsILoadContextInfo> mInfo;
};
NS_IMETHOD Run() override {
// The main loop
nsresult rv;
if (CacheStorageService::IsOnManagementThread()) {
switch (mPass) {
case COLLECT_STATS:
// Get quickly the cache stats.
uint32_t size;
rv = CacheIndex::GetCacheStats(mLoadInfo, &size, &mCount);
if (NS_FAILED(rv)) {
if (mVisitEntries) {
// both onStorageInfo and onCompleted are expected
NS_DispatchToMainThread(this);
}
return NS_DispatchToMainThread(this);
}
mSize = static_cast<uint64_t>(size) << 10;
// Invoke onCacheStorageInfo with valid information.
NS_DispatchToMainThread(this);
if (!mVisitEntries) {
return NS_OK; // done
}
mPass = ITERATE_METADATA;
MOZ_FALLTHROUGH;
case ITERATE_METADATA:
// Now grab the context iterator.
if (!mIter) {
rv =
CacheIndex::GetIterator(mLoadInfo, true, getter_AddRefs(mIter));
if (NS_FAILED(rv)) {
// Invoke onCacheEntryVisitCompleted now
return NS_DispatchToMainThread(this);
}
}
while (!mCancel && !CacheObserver::ShuttingDown()) {
if (CacheIOThread::YieldAndRerun()) return NS_OK;
SHA1Sum::Hash hash;
rv = mIter->GetNextHash(&hash);
if (NS_FAILED(rv)) break; // done (or error?)
// This synchronously invokes OnEntryInfo on this class where we
// redispatch to the main thread for the consumer callback.
CacheFileIOManager::GetEntryInfo(&hash, this);
}
// Invoke onCacheEntryVisitCompleted on the main thread
NS_DispatchToMainThread(this);
}
} else if (NS_IsMainThread()) {
if (mNotifyStorage) {
nsCOMPtr<nsIFile> dir;
CacheFileIOManager::GetCacheDirectory(getter_AddRefs(dir));
uint64_t capacity = CacheObserver::DiskCacheCapacity();
capacity <<= 10; // kilobytes to bytes
mCallback->OnCacheStorageInfo(mCount, mSize, capacity, dir);
mNotifyStorage = false;
} else {
mCallback->OnCacheEntryVisitCompleted();
}
} else {
MOZ_CRASH("Bad thread");
return NS_ERROR_FAILURE;
}
return NS_OK;
}
virtual void OnEntryInfo(const nsACString& aURISpec,
const nsACString& aIdEnhance, int64_t aDataSize,
int32_t aFetchCount, uint32_t aLastModifiedTime,
uint32_t aExpirationTime, bool aPinned,
nsILoadContextInfo* aInfo) override {
// Called directly from CacheFileIOManager::GetEntryInfo.
// Invoke onCacheEntryInfo on the main thread for this entry.
RefPtr<OnCacheEntryInfoRunnable> info = new OnCacheEntryInfoRunnable(this);
info->mURISpec = aURISpec;
info->mIdEnhance = aIdEnhance;
info->mDataSize = aDataSize;
info->mFetchCount = aFetchCount;
info->mLastModifiedTime = aLastModifiedTime;
info->mExpirationTime = aExpirationTime;
info->mPinned = aPinned;
info->mInfo = aInfo;
NS_DispatchToMainThread(info);
}
RefPtr<nsILoadContextInfo> mLoadInfo;
enum {
// First, we collect stats for the load context.
COLLECT_STATS,
// Second, if demanded, we iterate over the entries gethered
// from the iterator and call CacheFileIOManager::GetEntryInfo
// for each found entry.
ITERATE_METADATA,
} mPass;
RefPtr<CacheIndexIterator> mIter;
uint32_t mCount;
};
} // namespace
void CacheStorageService::DropPrivateBrowsingEntries() {
mozilla::MutexAutoLock lock(mLock);
if (mShutdown) return;
nsTArray<nsCString> keys;
for (auto iter = sGlobalEntryTables->Iter(); !iter.Done(); iter.Next()) {
const nsACString& key = iter.Key();
nsCOMPtr<nsILoadContextInfo> info = CacheFileUtils::ParseKey(key);
if (info && info->IsPrivate()) {
keys.AppendElement(key);
}
}
for (uint32_t i = 0; i < keys.Length(); ++i) {
DoomStorageEntries(keys[i], nullptr, true, false, nullptr);
}
}
namespace {
class CleaupCacheDirectoriesRunnable : public Runnable {
public:
NS_DECL_NSIRUNNABLE
static bool Post();
private:
CleaupCacheDirectoriesRunnable()
: Runnable("net::CleaupCacheDirectoriesRunnable") {
nsCacheService::GetDiskCacheDirectory(getter_AddRefs(mCache1Dir));
CacheFileIOManager::GetCacheDirectory(getter_AddRefs(mCache2Dir));
#if defined(MOZ_WIDGET_ANDROID)
CacheFileIOManager::GetProfilelessCacheDirectory(
getter_AddRefs(mCache2Profileless));
#endif
}
virtual ~CleaupCacheDirectoriesRunnable() = default;
nsCOMPtr<nsIFile> mCache1Dir, mCache2Dir;
#if defined(MOZ_WIDGET_ANDROID)
nsCOMPtr<nsIFile> mCache2Profileless;
#endif
};
// static
bool CleaupCacheDirectoriesRunnable::Post() {
// To obtain the cache1 directory we must unfortunately instantiate the old
// cache service despite it may not be used at all... This also initializes
// nsDeleteDir.
nsCOMPtr<nsICacheService> service = do_GetService(NS_CACHESERVICE_CONTRACTID);
if (!service) return false;
nsCOMPtr<nsIEventTarget> thread;
service->GetCacheIOTarget(getter_AddRefs(thread));
if (!thread) return false;
RefPtr<CleaupCacheDirectoriesRunnable> r =
new CleaupCacheDirectoriesRunnable();
thread->Dispatch(r, NS_DISPATCH_NORMAL);
return true;
}
NS_IMETHODIMP CleaupCacheDirectoriesRunnable::Run() {
MOZ_ASSERT(!NS_IsMainThread());
if (mCache1Dir) {
nsDeleteDir::RemoveOldTrashes(mCache1Dir);
}
if (mCache2Dir) {
nsDeleteDir::RemoveOldTrashes(mCache2Dir);
}
#if defined(MOZ_WIDGET_ANDROID)
if (mCache2Profileless) {
nsDeleteDir::RemoveOldTrashes(mCache2Profileless);
// Always delete the profileless cache on Android
nsDeleteDir::DeleteDir(mCache2Profileless, true, 30000);
}
#endif
if (mCache1Dir) {
nsDeleteDir::DeleteDir(mCache1Dir, true, 30000);
}
return NS_OK;
}
} // namespace
// static
void CacheStorageService::CleaupCacheDirectories() {
// Make sure we schedule just once in case CleaupCacheDirectories gets called
// multiple times from some reason.
static bool runOnce = CleaupCacheDirectoriesRunnable::Post();
if (!runOnce) {
NS_WARNING("Could not start cache trashes cleanup");
}
}
// Helper methods
// static
bool CacheStorageService::IsOnManagementThread() {
RefPtr<CacheStorageService> service = Self();
if (!service) return false;
nsCOMPtr<nsIEventTarget> target = service->Thread();
if (!target) return false;
bool currentThread;
nsresult rv = target->IsOnCurrentThread(¤tThread);
return NS_SUCCEEDED(rv) && currentThread;
}
already_AddRefed<nsIEventTarget> CacheStorageService::Thread() const {
return CacheFileIOManager::IOTarget();
}
nsresult CacheStorageService::Dispatch(nsIRunnable* aEvent) {
RefPtr<CacheIOThread> cacheIOThread = CacheFileIOManager::IOThread();
if (!cacheIOThread) return NS_ERROR_NOT_AVAILABLE;
return cacheIOThread->Dispatch(aEvent, CacheIOThread::MANAGEMENT);
}
// nsICacheStorageService
NS_IMETHODIMP CacheStorageService::MemoryCacheStorage(
nsILoadContextInfo* aLoadContextInfo, nsICacheStorage** _retval) {
NS_ENSURE_ARG(aLoadContextInfo);
NS_ENSURE_ARG(_retval);
nsCOMPtr<nsICacheStorage> storage =
new CacheStorage(aLoadContextInfo, false, false, false, false);
storage.forget(_retval);
return NS_OK;
}
NS_IMETHODIMP CacheStorageService::DiskCacheStorage(
nsILoadContextInfo* aLoadContextInfo, bool aLookupAppCache,
nsICacheStorage** _retval) {
NS_ENSURE_ARG(aLoadContextInfo);
NS_ENSURE_ARG(_retval);
// TODO save some heap granularity - cache commonly used storages.
// When disk cache is disabled, still provide a storage, but just keep stuff
// in memory.
bool useDisk = CacheObserver::UseDiskCache();
nsCOMPtr<nsICacheStorage> storage =
new CacheStorage(aLoadContextInfo, useDisk, aLookupAppCache,
false /* size limit */, false /* don't pin */);
storage.forget(_retval);
return NS_OK;
}
NS_IMETHODIMP CacheStorageService::PinningCacheStorage(
nsILoadContextInfo* aLoadContextInfo, nsICacheStorage** _retval) {
NS_ENSURE_ARG(aLoadContextInfo);
NS_ENSURE_ARG(_retval);
// When disk cache is disabled don't pretend we cache.
if (!CacheObserver::UseDiskCache()) {
return NS_ERROR_NOT_AVAILABLE;
}
nsCOMPtr<nsICacheStorage> storage = new CacheStorage(
aLoadContextInfo, true /* use disk */, false /* no appcache */,
true /* ignore size checks */, true /* pin */);
storage.forget(_retval);
return NS_OK;
}
NS_IMETHODIMP CacheStorageService::AppCacheStorage(
nsILoadContextInfo* aLoadContextInfo,
nsIApplicationCache* aApplicationCache, nsICacheStorage** _retval) {
NS_ENSURE_ARG(aLoadContextInfo);
NS_ENSURE_ARG(_retval);
nsCOMPtr<nsICacheStorage> storage;
// Using classification since cl believes we want to instantiate this method
// having the same name as the desired class...
storage =
new mozilla::net::AppCacheStorage(aLoadContextInfo, aApplicationCache);
storage.forget(_retval);
return NS_OK;
}
NS_IMETHODIMP CacheStorageService::SynthesizedCacheStorage(
nsILoadContextInfo* aLoadContextInfo, nsICacheStorage** _retval) {
NS_ENSURE_ARG(aLoadContextInfo);
NS_ENSURE_ARG(_retval);
nsCOMPtr<nsICacheStorage> storage =
new CacheStorage(aLoadContextInfo, false, false,
true /* skip size checks for synthesized cache */,
false /* no pinning */);
storage.forget(_retval);
return NS_OK;
}
NS_IMETHODIMP CacheStorageService::Clear() {
nsresult rv;
// Tell the index to block notification to AsyncGetDiskConsumption.
// Will be allowed again from CacheFileContextEvictor::EvictEntries()
// when all the context have been removed from disk.
CacheIndex::OnAsyncEviction(true);
mozilla::MutexAutoLock lock(mLock);
{
mozilla::MutexAutoLock forcedValidEntriesLock(mForcedValidEntriesLock);
mForcedValidEntries.Clear();
}
NS_ENSURE_TRUE(!mShutdown, NS_ERROR_NOT_INITIALIZED);
nsTArray<nsCString> keys;
for (auto iter = sGlobalEntryTables->Iter(); !iter.Done(); iter.Next()) {
keys.AppendElement(iter.Key());
}
for (uint32_t i = 0; i < keys.Length(); ++i) {
DoomStorageEntries(keys[i], nullptr, true, false, nullptr);
}
// Passing null as a load info means to evict all contexts.
// EvictByContext() respects the entry pinning. EvictAll() does not.
rv = CacheFileIOManager::EvictByContext(nullptr, false, EmptyString());
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
NS_IMETHODIMP CacheStorageService::ClearOrigin(nsIPrincipal* aPrincipal) {
nsresult rv;
if (NS_WARN_IF(!aPrincipal)) {
return NS_ERROR_FAILURE;
}
nsAutoString origin;
rv = nsContentUtils::GetUTFOrigin(aPrincipal, origin);
NS_ENSURE_SUCCESS(rv, rv);
rv = ClearOriginInternal(origin, aPrincipal->OriginAttributesRef(), true);
NS_ENSURE_SUCCESS(rv, rv);
rv = ClearOriginInternal(origin, aPrincipal->OriginAttributesRef(), false);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
static bool RemoveExactEntry(CacheEntryTable* aEntries, nsACString const& aKey,
CacheEntry* aEntry, bool aOverwrite) {
RefPtr<CacheEntry> existingEntry;
if (!aEntries->Get(aKey, getter_AddRefs(existingEntry))) {
LOG(("RemoveExactEntry [entry=%p already gone]", aEntry));
return false; // Already removed...
}
if (!aOverwrite && existingEntry != aEntry) {
LOG(("RemoveExactEntry [entry=%p already replaced]", aEntry));
return false; // Already replaced...
}
LOG(("RemoveExactEntry [entry=%p removed]", aEntry));
aEntries->Remove(aKey);
return true;
}
nsresult CacheStorageService::ClearOriginInternal(
const nsAString& aOrigin, const OriginAttributes& aOriginAttributes,
bool aAnonymous) {
nsresult rv;
RefPtr<LoadContextInfo> info =
GetLoadContextInfo(aAnonymous, aOriginAttributes);
if (NS_WARN_IF(!info)) {
return NS_ERROR_FAILURE;
}
mozilla::MutexAutoLock lock(mLock);
if (sGlobalEntryTables) {
for (auto iter = sGlobalEntryTables->Iter(); !iter.Done(); iter.Next()) {
bool matches = false;
rv =
CacheFileUtils::KeyMatchesLoadContextInfo(iter.Key(), info, &matches);
NS_ENSURE_SUCCESS(rv, rv);
if (!matches) {
continue;
}
CacheEntryTable* table = iter.UserData();
MOZ_ASSERT(table);
nsTArray<RefPtr<CacheEntry>> entriesToDelete;
for (auto entryIter = table->Iter(); !entryIter.Done();
entryIter.Next()) {
CacheEntry* entry = entryIter.UserData();
nsCOMPtr<nsIURI> uri;
rv = NS_NewURI(getter_AddRefs(uri), entry->GetURI());
NS_ENSURE_SUCCESS(rv, rv);
nsAutoString origin;
rv = nsContentUtils::GetUTFOrigin(uri, origin);
NS_ENSURE_SUCCESS(rv, rv);
if (origin != aOrigin) {
continue;
}
entriesToDelete.AppendElement(entry);
}
for (RefPtr<CacheEntry>& entry : entriesToDelete) {
nsAutoCString entryKey;
rv = entry->HashingKey(entryKey);
if (NS_FAILED(rv)) {
NS_ERROR("aEntry->HashingKey() failed?");
return rv;
}
RemoveExactEntry(table, entryKey, entry, false /* don't overwrite */);
}
}
}
rv = CacheFileIOManager::EvictByContext(info, false /* pinned */, aOrigin);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
NS_IMETHODIMP CacheStorageService::PurgeFromMemory(uint32_t aWhat) {
uint32_t what;
switch (aWhat) {
case PURGE_DISK_DATA_ONLY:
what = CacheEntry::PURGE_DATA_ONLY_DISK_BACKED;
break;
case PURGE_DISK_ALL:
what = CacheEntry::PURGE_WHOLE_ONLY_DISK_BACKED;
break;
case PURGE_EVERYTHING:
what = CacheEntry::PURGE_WHOLE;
break;
default:
return NS_ERROR_INVALID_ARG;
}
nsCOMPtr<nsIRunnable> event = new PurgeFromMemoryRunnable(this, what);
return Dispatch(event);
}
NS_IMETHODIMP CacheStorageService::PurgeFromMemoryRunnable::Run() {
if (NS_IsMainThread()) {
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (observerService) {
observerService->NotifyObservers(
nullptr, "cacheservice:purge-memory-pools", nullptr);
}
return NS_OK;
}
if (mService) {
// TODO not all flags apply to both pools
mService->Pool(true).PurgeAll(mWhat);
mService->Pool(false).PurgeAll(mWhat);
mService = nullptr;
}
NS_DispatchToMainThread(this);
return NS_OK;
}
NS_IMETHODIMP CacheStorageService::AsyncGetDiskConsumption(
nsICacheStorageConsumptionObserver* aObserver) {
NS_ENSURE_ARG(aObserver);
nsresult rv;
rv = CacheIndex::AsyncGetDiskConsumption(aObserver);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
NS_IMETHODIMP CacheStorageService::GetIoTarget(nsIEventTarget** aEventTarget) {
NS_ENSURE_ARG(aEventTarget);
nsCOMPtr<nsIEventTarget> ioTarget = CacheFileIOManager::IOTarget();
ioTarget.forget(aEventTarget);
return NS_OK;
}
NS_IMETHODIMP CacheStorageService::AsyncVisitAllStorages(
nsICacheStorageVisitor* aVisitor, bool aVisitEntries) {
LOG(("CacheStorageService::AsyncVisitAllStorages [cb=%p]", aVisitor));
NS_ENSURE_FALSE(mShutdown, NS_ERROR_NOT_INITIALIZED);
// Walking the disk cache also walks the memory cache.
RefPtr<WalkDiskCacheRunnable> event =
new WalkDiskCacheRunnable(nullptr, aVisitEntries, aVisitor);
return event->Walk();
return NS_OK;
}
// Methods used by CacheEntry for management of in-memory structures.
namespace {
class FrecencyComparator {
public:
bool Equals(CacheEntry* a, CacheEntry* b) const {
return a->GetFrecency() == b->GetFrecency();
}
bool LessThan(CacheEntry* a, CacheEntry* b) const {
return a->GetFrecency() < b->GetFrecency();
}
};
class ExpirationComparator {
public:
bool Equals(CacheEntry* a, CacheEntry* b) const {
return a->GetExpirationTime() == b->GetExpirationTime();
}
bool LessThan(CacheEntry* a, CacheEntry* b) const {
return a->GetExpirationTime() < b->GetExpirationTime();
}
};
} // namespace
void CacheStorageService::RegisterEntry(CacheEntry* aEntry) {
MOZ_ASSERT(IsOnManagementThread());
if (mShutdown || !aEntry->CanRegister()) return;
TelemetryRecordEntryCreation(aEntry);
LOG(("CacheStorageService::RegisterEntry [entry=%p]", aEntry));
MemoryPool& pool = Pool(aEntry->IsUsingDisk());
pool.mFrecencyArray.AppendElement(aEntry);
pool.mExpirationArray.AppendElement(aEntry);
aEntry->SetRegistered(true);
}
void CacheStorageService::UnregisterEntry(CacheEntry* aEntry) {
MOZ_ASSERT(IsOnManagementThread());
if (!aEntry->IsRegistered()) return;
TelemetryRecordEntryRemoval(aEntry);