diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
commit | 2aa4a82499d4becd2284cdb482213d541b8804dd (patch) | |
tree | b80bf8bf13c3766139fbacc530efd0dd9d54394c /netwerk/cache | |
parent | Initial commit. (diff) | |
download | firefox-upstream.tar.xz firefox-upstream.zip |
Adding upstream version 86.0.1.upstream/86.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'netwerk/cache')
31 files changed, 9625 insertions, 0 deletions
diff --git a/netwerk/cache/moz.build b/netwerk/cache/moz.build new file mode 100644 index 0000000000..62a0c06ebe --- /dev/null +++ b/netwerk/cache/moz.build @@ -0,0 +1,50 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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/. + +with Files("**"): + BUG_COMPONENT = ("Core", "Networking: Cache") + +XPIDL_SOURCES += [ + "nsICache.idl", + "nsICacheEntryDescriptor.idl", + "nsICacheListener.idl", + "nsICacheService.idl", + "nsICacheSession.idl", + "nsICacheVisitor.idl", +] + +XPIDL_MODULE = "necko_cache" + +EXPORTS += [ + "nsApplicationCache.h", + "nsApplicationCacheService.h", + "nsCacheDevice.h", + "nsCacheService.h", + "nsDeleteDir.h", + "nsDiskCacheDeviceSQL.h", +] + +UNIFIED_SOURCES += [ + "nsApplicationCacheService.cpp", + "nsCache.cpp", + "nsCacheEntry.cpp", + "nsCacheEntryDescriptor.cpp", + "nsCacheMetaData.cpp", + "nsCacheService.cpp", + "nsCacheSession.cpp", + "nsCacheUtils.cpp", + "nsDeleteDir.cpp", + "nsDiskCacheDeviceSQL.cpp", +] + +FINAL_LIBRARY = "xul" + +LOCAL_INCLUDES += [ + "/netwerk/base", +] + +if CONFIG["CC_TYPE"] in ("clang", "gcc"): + CXXFLAGS += ["-Wno-error=shadow"] diff --git a/netwerk/cache/nsApplicationCache.h b/netwerk/cache/nsApplicationCache.h new file mode 100644 index 0000000000..37e3bc14e4 --- /dev/null +++ b/netwerk/cache/nsApplicationCache.h @@ -0,0 +1,33 @@ +/* vim:set ts=2 sw=2 sts=2 et cin: */ +/* 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 "nsIApplicationCache.h" +#include "nsWeakReference.h" +#include "mozilla/RefPtr.h" +#include "nsString.h" + +class nsOfflineCacheDevice; + +class nsApplicationCache : public nsIApplicationCache, + public nsSupportsWeakReference { + public: + NS_DECL_ISUPPORTS + NS_DECL_NSIAPPLICATIONCACHE + + nsApplicationCache(nsOfflineCacheDevice* device, const nsACString& group, + const nsACString& clientID); + + nsApplicationCache(); + + void MarkInvalid(); + + private: + virtual ~nsApplicationCache(); + + RefPtr<nsOfflineCacheDevice> mDevice; + nsCString mGroup; + nsCString mClientID; + bool mValid; +}; diff --git a/netwerk/cache/nsApplicationCacheService.cpp b/netwerk/cache/nsApplicationCacheService.cpp new file mode 100644 index 0000000000..af931706a3 --- /dev/null +++ b/netwerk/cache/nsApplicationCacheService.cpp @@ -0,0 +1,192 @@ +/* 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 "nsDiskCache.h" +#include "nsDiskCacheDeviceSQL.h" +#include "nsCacheService.h" +#include "nsApplicationCacheService.h" +#include "nsCRT.h" +#include "nsNetCID.h" +#include "nsNetUtil.h" +#include "nsIObserverService.h" +#include "mozilla/LoadContextInfo.h" + +using namespace mozilla; + +static NS_DEFINE_CID(kCacheServiceCID, NS_CACHESERVICE_CID); + +//----------------------------------------------------------------------------- +// nsApplicationCacheService +//----------------------------------------------------------------------------- + +NS_IMPL_ISUPPORTS(nsApplicationCacheService, nsIApplicationCacheService) + +nsApplicationCacheService::nsApplicationCacheService() { + nsCOMPtr<nsICacheService> serv = do_GetService(kCacheServiceCID); + mCacheService = nsCacheService::GlobalInstance(); +} + +NS_IMETHODIMP +nsApplicationCacheService::BuildGroupIDForInfo( + nsIURI* aManifestURL, nsILoadContextInfo* aLoadContextInfo, + nsACString& _result) { + nsresult rv; + + nsAutoCString originSuffix; + if (aLoadContextInfo) { + aLoadContextInfo->OriginAttributesPtr()->CreateSuffix(originSuffix); + } + + rv = nsOfflineCacheDevice::BuildApplicationCacheGroupID( + aManifestURL, originSuffix, _result); + NS_ENSURE_SUCCESS(rv, rv); + + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCacheService::BuildGroupIDForSuffix( + nsIURI* aManifestURL, nsACString const& aOriginSuffix, + nsACString& _result) { + nsresult rv; + + rv = nsOfflineCacheDevice::BuildApplicationCacheGroupID( + aManifestURL, aOriginSuffix, _result); + NS_ENSURE_SUCCESS(rv, rv); + + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCacheService::CreateApplicationCache(const nsACString& group, + nsIApplicationCache** out) { + if (!mCacheService) return NS_ERROR_UNEXPECTED; + + RefPtr<nsOfflineCacheDevice> device; + nsresult rv = mCacheService->GetOfflineDevice(getter_AddRefs(device)); + NS_ENSURE_SUCCESS(rv, rv); + return device->CreateApplicationCache(group, out); +} + +NS_IMETHODIMP +nsApplicationCacheService::CreateCustomApplicationCache( + const nsACString& group, nsIFile* profileDir, int32_t quota, + nsIApplicationCache** out) { + if (!mCacheService) return NS_ERROR_UNEXPECTED; + + RefPtr<nsOfflineCacheDevice> device; + nsresult rv = mCacheService->GetCustomOfflineDevice(profileDir, quota, + getter_AddRefs(device)); + NS_ENSURE_SUCCESS(rv, rv); + return device->CreateApplicationCache(group, out); +} + +NS_IMETHODIMP +nsApplicationCacheService::GetApplicationCache(const nsACString& clientID, + nsIApplicationCache** out) { + if (!mCacheService) return NS_ERROR_UNEXPECTED; + + RefPtr<nsOfflineCacheDevice> device; + nsresult rv = mCacheService->GetOfflineDevice(getter_AddRefs(device)); + NS_ENSURE_SUCCESS(rv, rv); + return device->GetApplicationCache(clientID, out); +} + +NS_IMETHODIMP +nsApplicationCacheService::GetActiveCache(const nsACString& group, + nsIApplicationCache** out) { + if (!mCacheService) return NS_ERROR_UNEXPECTED; + + RefPtr<nsOfflineCacheDevice> device; + nsresult rv = mCacheService->GetOfflineDevice(getter_AddRefs(device)); + NS_ENSURE_SUCCESS(rv, rv); + return device->GetActiveCache(group, out); +} + +NS_IMETHODIMP +nsApplicationCacheService::DeactivateGroup(const nsACString& group) { + if (!mCacheService) return NS_ERROR_UNEXPECTED; + + RefPtr<nsOfflineCacheDevice> device; + nsresult rv = mCacheService->GetOfflineDevice(getter_AddRefs(device)); + NS_ENSURE_SUCCESS(rv, rv); + return device->DeactivateGroup(group); +} + +NS_IMETHODIMP +nsApplicationCacheService::ChooseApplicationCache( + const nsACString& key, nsILoadContextInfo* aLoadContextInfo, + nsIApplicationCache** out) { + if (!mCacheService) return NS_ERROR_UNEXPECTED; + + RefPtr<nsOfflineCacheDevice> device; + nsresult rv = mCacheService->GetOfflineDevice(getter_AddRefs(device)); + if (NS_FAILED(rv)) { + // Silently fail and provide no appcache to the caller. + return NS_OK; + } + + return device->ChooseApplicationCache(key, aLoadContextInfo, out); +} + +NS_IMETHODIMP +nsApplicationCacheService::CacheOpportunistically(nsIApplicationCache* cache, + const nsACString& key) { + if (!mCacheService) return NS_ERROR_UNEXPECTED; + + RefPtr<nsOfflineCacheDevice> device; + nsresult rv = mCacheService->GetOfflineDevice(getter_AddRefs(device)); + NS_ENSURE_SUCCESS(rv, rv); + return device->CacheOpportunistically(cache, key); +} + +NS_IMETHODIMP +nsApplicationCacheService::Evict(nsILoadContextInfo* aInfo) { + if (!mCacheService) return NS_ERROR_UNEXPECTED; + + RefPtr<nsOfflineCacheDevice> device; + nsresult rv = mCacheService->GetOfflineDevice(getter_AddRefs(device)); + NS_ENSURE_SUCCESS(rv, rv); + return device->Evict(aInfo); +} + +NS_IMETHODIMP +nsApplicationCacheService::EvictMatchingOriginAttributes( + nsAString const& aPattern) { + if (!mCacheService) return NS_ERROR_UNEXPECTED; + + RefPtr<nsOfflineCacheDevice> device; + nsresult rv = mCacheService->GetOfflineDevice(getter_AddRefs(device)); + NS_ENSURE_SUCCESS(rv, rv); + + mozilla::OriginAttributesPattern pattern; + if (!pattern.Init(aPattern)) { + NS_ERROR( + "Could not parse OriginAttributesPattern JSON in " + "clear-origin-attributes-data notification"); + return NS_ERROR_FAILURE; + } + + return device->Evict(pattern); +} + +NS_IMETHODIMP +nsApplicationCacheService::GetGroups(nsTArray<nsCString>& keys) { + if (!mCacheService) return NS_ERROR_UNEXPECTED; + + RefPtr<nsOfflineCacheDevice> device; + nsresult rv = mCacheService->GetOfflineDevice(getter_AddRefs(device)); + NS_ENSURE_SUCCESS(rv, rv); + return device->GetGroups(keys); +} + +NS_IMETHODIMP +nsApplicationCacheService::GetGroupsTimeOrdered(nsTArray<nsCString>& keys) { + if (!mCacheService) return NS_ERROR_UNEXPECTED; + + RefPtr<nsOfflineCacheDevice> device; + nsresult rv = mCacheService->GetOfflineDevice(getter_AddRefs(device)); + NS_ENSURE_SUCCESS(rv, rv); + return device->GetGroupsTimeOrdered(keys); +} diff --git a/netwerk/cache/nsApplicationCacheService.h b/netwerk/cache/nsApplicationCacheService.h new file mode 100644 index 0000000000..d57a913726 --- /dev/null +++ b/netwerk/cache/nsApplicationCacheService.h @@ -0,0 +1,27 @@ +/* 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/. */ + +#ifndef _nsApplicationCacheService_h_ +#define _nsApplicationCacheService_h_ + +#include "nsIApplicationCacheService.h" +#include "mozilla/Attributes.h" + +class nsCacheService; + +class nsApplicationCacheService final : public nsIApplicationCacheService { + public: + nsApplicationCacheService(); + + NS_DECL_ISUPPORTS + NS_DECL_NSIAPPLICATIONCACHESERVICE + + static void AppClearDataObserverInit(); + + private: + ~nsApplicationCacheService() = default; + RefPtr<nsCacheService> mCacheService; +}; + +#endif // _nsApplicationCacheService_h_ diff --git a/netwerk/cache/nsCache.cpp b/netwerk/cache/nsCache.cpp new file mode 100644 index 0000000000..73b98dee1c --- /dev/null +++ b/netwerk/cache/nsCache.cpp @@ -0,0 +1,70 @@ +/* -*- 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 "nsCache.h" +#include "nsReadableUtils.h" +#include "nsDependentSubstring.h" +#include "nsString.h" +#include "mozilla/IntegerPrintfMacros.h" + +/** + * Cache Service Utility Functions + */ + +mozilla::LazyLogModule gCacheLog("cache"); + +void CacheLogPrintPath(mozilla::LogLevel level, const char* format, + nsIFile* item) { + MOZ_LOG(gCacheLog, level, (format, item->HumanReadablePath().get())); +} + +uint32_t SecondsFromPRTime(PRTime prTime) { + int64_t microSecondsPerSecond = PR_USEC_PER_SEC; + return uint32_t(prTime / microSecondsPerSecond); +} + +PRTime PRTimeFromSeconds(uint32_t seconds) { + int64_t intermediateResult = seconds; + PRTime prTime = intermediateResult * PR_USEC_PER_SEC; + return prTime; +} + +nsresult ClientIDFromCacheKey(const nsACString& key, nsACString& result) { + nsReadingIterator<char> colon; + key.BeginReading(colon); + + nsReadingIterator<char> start; + key.BeginReading(start); + + nsReadingIterator<char> end; + key.EndReading(end); + + if (FindCharInReadable(':', colon, end)) { + result.Assign(Substring(start, colon)); + return NS_OK; + } + + NS_ASSERTION(false, "FindCharInRead failed to find ':'"); + return NS_ERROR_UNEXPECTED; +} + +nsresult ClientKeyFromCacheKey(const nsCString& key, nsACString& result) { + nsReadingIterator<char> start; + key.BeginReading(start); + + nsReadingIterator<char> end; + key.EndReading(end); + + if (FindCharInReadable(':', start, end)) { + ++start; // advance past clientID ':' delimiter + result.Assign(Substring(start, end)); + return NS_OK; + } + + NS_ASSERTION(false, "FindCharInRead failed to find ':'"); + result.Truncate(0); + return NS_ERROR_UNEXPECTED; +} diff --git a/netwerk/cache/nsCache.h b/netwerk/cache/nsCache.h new file mode 100644 index 0000000000..859dddb8f2 --- /dev/null +++ b/netwerk/cache/nsCache.h @@ -0,0 +1,39 @@ +/* -*- 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/. */ + +/** + * Cache Service Utility Functions + */ + +#ifndef _nsCache_h_ +#define _nsCache_h_ + +#include "mozilla/Logging.h" +#include "nsISupports.h" +#include "nsIFile.h" +#include "nsAString.h" +#include "prtime.h" +#include "nsError.h" + +// PR_LOG args = "format string", arg, arg, ... +extern mozilla::LazyLogModule gCacheLog; +void CacheLogPrintPath(mozilla::LogLevel level, const char* format, + nsIFile* item); +#define CACHE_LOG_INFO(args) MOZ_LOG(gCacheLog, mozilla::LogLevel::Info, args) +#define CACHE_LOG_ERROR(args) MOZ_LOG(gCacheLog, mozilla::LogLevel::Error, args) +#define CACHE_LOG_WARNING(args) \ + MOZ_LOG(gCacheLog, mozilla::LogLevel::Warning, args) +#define CACHE_LOG_DEBUG(args) MOZ_LOG(gCacheLog, mozilla::LogLevel::Debug, args) +#define CACHE_LOG_PATH(level, format, item) \ + CacheLogPrintPath(level, format, item) + +extern uint32_t SecondsFromPRTime(PRTime prTime); +extern PRTime PRTimeFromSeconds(uint32_t seconds); + +extern nsresult ClientIDFromCacheKey(const nsACString& key, nsACString& result); +extern nsresult ClientKeyFromCacheKey(const nsCString& key, nsACString& result); + +#endif // _nsCache_h diff --git a/netwerk/cache/nsCacheDevice.h b/netwerk/cache/nsCacheDevice.h new file mode 100644 index 0000000000..fc68bcb8a2 --- /dev/null +++ b/netwerk/cache/nsCacheDevice.h @@ -0,0 +1,63 @@ +/* -*- 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/. */ + +#ifndef _nsCacheDevice_h_ +#define _nsCacheDevice_h_ + +#include "nspr.h" +#include "nsError.h" +#include "nsICache.h" +#include "nsStringFwd.h" + +class nsIFile; +class nsCacheEntry; +class nsICacheVisitor; +class nsIInputStream; +class nsIOutputStream; + +/****************************************************************************** + * nsCacheDevice + *******************************************************************************/ +class nsCacheDevice { + public: + MOZ_COUNTED_DEFAULT_CTOR(nsCacheDevice) + MOZ_COUNTED_DTOR_VIRTUAL(nsCacheDevice) + + virtual nsresult Init() = 0; + virtual nsresult Shutdown() = 0; + + virtual const char* GetDeviceID(void) = 0; + virtual nsCacheEntry* FindEntry(nsCString* key, bool* collision) = 0; + + virtual nsresult DeactivateEntry(nsCacheEntry* entry) = 0; + virtual nsresult BindEntry(nsCacheEntry* entry) = 0; + virtual void DoomEntry(nsCacheEntry* entry) = 0; + + virtual nsresult OpenInputStreamForEntry(nsCacheEntry* entry, + nsCacheAccessMode mode, + uint32_t offset, + nsIInputStream** result) = 0; + + virtual nsresult OpenOutputStreamForEntry(nsCacheEntry* entry, + nsCacheAccessMode mode, + uint32_t offset, + nsIOutputStream** result) = 0; + + virtual nsresult GetFileForEntry(nsCacheEntry* entry, nsIFile** result) = 0; + + virtual nsresult OnDataSizeChange(nsCacheEntry* entry, int32_t deltaSize) = 0; + + virtual nsresult Visit(nsICacheVisitor* visitor) = 0; + + /** + * Device must evict entries associated with clientID. If clientID == + * nullptr, all entries must be evicted. Active entries must be doomed, + * rather than evicted. + */ + virtual nsresult EvictEntries(const char* clientID) = 0; +}; + +#endif // _nsCacheDevice_h_ diff --git a/netwerk/cache/nsCacheEntry.cpp b/netwerk/cache/nsCacheEntry.cpp new file mode 100644 index 0000000000..c91748ef72 --- /dev/null +++ b/netwerk/cache/nsCacheEntry.cpp @@ -0,0 +1,415 @@ +/* -*- 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 "nsCache.h" +#include "nspr.h" +#include "nsCacheEntry.h" +#include "nsCacheEntryDescriptor.h" +#include "nsCacheMetaData.h" +#include "nsCacheRequest.h" +#include "nsThreadUtils.h" +#include "nsError.h" +#include "nsCacheService.h" +#include "nsCacheDevice.h" +#include "nsHashKeys.h" + +using namespace mozilla; + +nsCacheEntry::nsCacheEntry(const nsACString& key, bool streamBased, + nsCacheStoragePolicy storagePolicy) + : mKey(key), + mFetchCount(0), + mLastFetched(0), + mLastModified(0), + mLastValidated(0), + mExpirationTime(nsICache::NO_EXPIRATION_TIME), + mFlags(0), + mPredictedDataSize(-1), + mDataSize(0), + mCacheDevice(nullptr), + mCustomDevice(nullptr), + mData(nullptr), + mRequestQ{}, + mDescriptorQ{} { + MOZ_COUNT_CTOR(nsCacheEntry); + PR_INIT_CLIST(this); + PR_INIT_CLIST(&mRequestQ); + PR_INIT_CLIST(&mDescriptorQ); + + if (streamBased) MarkStreamBased(); + SetStoragePolicy(storagePolicy); + + MarkPublic(); +} + +nsCacheEntry::~nsCacheEntry() { + MOZ_COUNT_DTOR(nsCacheEntry); + + if (mData) nsCacheService::ReleaseObject_Locked(mData, mEventTarget); +} + +nsresult nsCacheEntry::Create(const char* key, bool streamBased, + nsCacheStoragePolicy storagePolicy, + nsCacheDevice* device, nsCacheEntry** result) { + nsCacheEntry* entry = + new nsCacheEntry(nsCString(key), streamBased, storagePolicy); + entry->SetCacheDevice(device); + *result = entry; + return NS_OK; +} + +void nsCacheEntry::Fetched() { + mLastFetched = SecondsFromPRTime(PR_Now()); + ++mFetchCount; + MarkEntryDirty(); +} + +const char* nsCacheEntry::GetDeviceID() { + if (mCacheDevice) return mCacheDevice->GetDeviceID(); + return nullptr; +} + +void nsCacheEntry::TouchData() { + mLastModified = SecondsFromPRTime(PR_Now()); + MarkDataDirty(); +} + +void nsCacheEntry::SetData(nsISupports* data) { + if (mData) { + nsCacheService::ReleaseObject_Locked(mData, mEventTarget); + mData = nullptr; + } + + if (data) { + NS_ADDREF(mData = data); + mEventTarget = GetCurrentEventTarget(); + } +} + +void nsCacheEntry::TouchMetaData() { + mLastModified = SecondsFromPRTime(PR_Now()); + MarkMetaDataDirty(); +} + +/** + * cache entry states + * 0 descriptors (new entry) + * 0 descriptors (existing, bound entry) + * n descriptors (existing, bound entry) valid + * n descriptors (existing, bound entry) not valid (wait until valid or + * doomed) + */ + +nsresult nsCacheEntry::RequestAccess(nsCacheRequest* request, + nsCacheAccessMode* accessGranted) { + nsresult rv = NS_OK; + + if (IsDoomed()) return NS_ERROR_CACHE_ENTRY_DOOMED; + + if (!IsInitialized()) { + // brand new, unbound entry + if (request->IsStreamBased()) MarkStreamBased(); + MarkInitialized(); + + *accessGranted = request->AccessRequested() & nsICache::ACCESS_WRITE; + NS_ASSERTION(*accessGranted, "new cache entry for READ-ONLY request"); + PR_APPEND_LINK(request, &mRequestQ); + return rv; + } + + if (IsStreamData() != request->IsStreamBased()) { + *accessGranted = nsICache::ACCESS_NONE; + return request->IsStreamBased() ? NS_ERROR_CACHE_DATA_IS_NOT_STREAM + : NS_ERROR_CACHE_DATA_IS_STREAM; + } + + if (PR_CLIST_IS_EMPTY(&mDescriptorQ)) { + // 1st descriptor for existing bound entry + *accessGranted = request->AccessRequested(); + if (*accessGranted & nsICache::ACCESS_WRITE) { + MarkInvalid(); + } else { + MarkValid(); + } + } else { + // nth request for existing, bound entry + *accessGranted = request->AccessRequested() & ~nsICache::ACCESS_WRITE; + if (!IsValid()) rv = NS_ERROR_CACHE_WAIT_FOR_VALIDATION; + } + PR_APPEND_LINK(request, &mRequestQ); + + return rv; +} + +nsresult nsCacheEntry::CreateDescriptor(nsCacheRequest* request, + nsCacheAccessMode accessGranted, + nsICacheEntryDescriptor** result) { + NS_ENSURE_ARG_POINTER(request && result); + + nsCacheEntryDescriptor* descriptor = + new nsCacheEntryDescriptor(this, accessGranted); + + // XXX check request is on q + PR_REMOVE_AND_INIT_LINK(request); // remove request regardless of success + + if (descriptor == nullptr) return NS_ERROR_OUT_OF_MEMORY; + + PR_APPEND_LINK(descriptor, &mDescriptorQ); + + CACHE_LOG_DEBUG((" descriptor %p created for request %p on entry %p\n", + descriptor, request, this)); + + *result = do_AddRef(descriptor).take(); + return NS_OK; +} + +bool nsCacheEntry::RemoveRequest(nsCacheRequest* request) { + // XXX if debug: verify this request belongs to this entry + PR_REMOVE_AND_INIT_LINK(request); + + // return true if this entry should stay active + return !((PR_CLIST_IS_EMPTY(&mRequestQ)) && + (PR_CLIST_IS_EMPTY(&mDescriptorQ))); +} + +bool nsCacheEntry::RemoveDescriptor(nsCacheEntryDescriptor* descriptor, + bool* doomEntry) { + NS_ASSERTION(descriptor->CacheEntry() == this, "### Wrong cache entry!!"); + + *doomEntry = descriptor->ClearCacheEntry(); + + PR_REMOVE_AND_INIT_LINK(descriptor); + + if (!PR_CLIST_IS_EMPTY(&mDescriptorQ)) + return true; // stay active if we still have open descriptors + + if (PR_CLIST_IS_EMPTY(&mRequestQ)) + return false; // no descriptors or requests, we can deactivate + + return true; // find next best request to give a descriptor to +} + +void nsCacheEntry::DetachDescriptors() { + nsCacheEntryDescriptor* descriptor = + (nsCacheEntryDescriptor*)PR_LIST_HEAD(&mDescriptorQ); + + while (descriptor != &mDescriptorQ) { + nsCacheEntryDescriptor* nextDescriptor = + (nsCacheEntryDescriptor*)PR_NEXT_LINK(descriptor); + + descriptor->ClearCacheEntry(); + PR_REMOVE_AND_INIT_LINK(descriptor); + descriptor = nextDescriptor; + } +} + +void nsCacheEntry::GetDescriptors( + nsTArray<RefPtr<nsCacheEntryDescriptor> >& outDescriptors) { + nsCacheEntryDescriptor* descriptor = + (nsCacheEntryDescriptor*)PR_LIST_HEAD(&mDescriptorQ); + + while (descriptor != &mDescriptorQ) { + nsCacheEntryDescriptor* nextDescriptor = + (nsCacheEntryDescriptor*)PR_NEXT_LINK(descriptor); + + outDescriptors.AppendElement(descriptor); + descriptor = nextDescriptor; + } +} + +/****************************************************************************** + * nsCacheEntryInfo - for implementing about:cache + *****************************************************************************/ + +NS_IMPL_ISUPPORTS(nsCacheEntryInfo, nsICacheEntryInfo) + +NS_IMETHODIMP +nsCacheEntryInfo::GetClientID(nsACString& aClientID) { + if (!mCacheEntry) { + aClientID.Truncate(); + return NS_ERROR_NOT_AVAILABLE; + } + + return ClientIDFromCacheKey(*mCacheEntry->Key(), aClientID); +} + +NS_IMETHODIMP +nsCacheEntryInfo::GetDeviceID(nsACString& aDeviceID) { + if (!mCacheEntry) { + aDeviceID.Truncate(); + return NS_ERROR_NOT_AVAILABLE; + } + + aDeviceID.Assign(mCacheEntry->GetDeviceID()); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryInfo::GetKey(nsACString& key) { + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + return ClientKeyFromCacheKey(*mCacheEntry->Key(), key); +} + +NS_IMETHODIMP +nsCacheEntryInfo::GetFetchCount(int32_t* fetchCount) { + NS_ENSURE_ARG_POINTER(fetchCount); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *fetchCount = mCacheEntry->FetchCount(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryInfo::GetLastFetched(uint32_t* lastFetched) { + NS_ENSURE_ARG_POINTER(lastFetched); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *lastFetched = mCacheEntry->LastFetched(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryInfo::GetLastModified(uint32_t* lastModified) { + NS_ENSURE_ARG_POINTER(lastModified); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *lastModified = mCacheEntry->LastModified(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryInfo::GetExpirationTime(uint32_t* expirationTime) { + NS_ENSURE_ARG_POINTER(expirationTime); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *expirationTime = mCacheEntry->ExpirationTime(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryInfo::GetDataSize(uint32_t* dataSize) { + NS_ENSURE_ARG_POINTER(dataSize); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *dataSize = mCacheEntry->DataSize(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryInfo::IsStreamBased(bool* result) { + NS_ENSURE_ARG_POINTER(result); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *result = mCacheEntry->IsStreamData(); + return NS_OK; +} + +/****************************************************************************** + * nsCacheEntryHashTable + *****************************************************************************/ + +const PLDHashTableOps nsCacheEntryHashTable::ops = {HashKey, MatchEntry, + MoveEntry, ClearEntry}; + +nsCacheEntryHashTable::nsCacheEntryHashTable() + : table(&ops, sizeof(nsCacheEntryHashTableEntry), kInitialTableLength), + initialized(false) { + MOZ_COUNT_CTOR(nsCacheEntryHashTable); +} + +nsCacheEntryHashTable::~nsCacheEntryHashTable() { + MOZ_COUNT_DTOR(nsCacheEntryHashTable); + if (initialized) Shutdown(); +} + +void nsCacheEntryHashTable::Init() { + table.ClearAndPrepareForLength(kInitialTableLength); + initialized = true; +} + +void nsCacheEntryHashTable::Shutdown() { + if (initialized) { + table.ClearAndPrepareForLength(kInitialTableLength); + initialized = false; + } +} + +nsCacheEntry* nsCacheEntryHashTable::GetEntry(const nsCString* key) const { + NS_ASSERTION(initialized, "nsCacheEntryHashTable not initialized"); + if (!initialized) return nullptr; + + PLDHashEntryHdr* hashEntry = table.Search(key); + return hashEntry ? ((nsCacheEntryHashTableEntry*)hashEntry)->cacheEntry + : nullptr; +} + +nsresult nsCacheEntryHashTable::AddEntry(nsCacheEntry* cacheEntry) { + PLDHashEntryHdr* hashEntry; + + NS_ASSERTION(initialized, "nsCacheEntryHashTable not initialized"); + if (!initialized) return NS_ERROR_NOT_INITIALIZED; + if (!cacheEntry) return NS_ERROR_NULL_POINTER; + + hashEntry = table.Add(&(cacheEntry->mKey), fallible); + + if (!hashEntry) return NS_ERROR_FAILURE; + NS_ASSERTION(((nsCacheEntryHashTableEntry*)hashEntry)->cacheEntry == nullptr, + "### nsCacheEntryHashTable::AddEntry - entry already used"); + ((nsCacheEntryHashTableEntry*)hashEntry)->cacheEntry = cacheEntry; + + return NS_OK; +} + +void nsCacheEntryHashTable::RemoveEntry(nsCacheEntry* cacheEntry) { + NS_ASSERTION(initialized, "nsCacheEntryHashTable not initialized"); + NS_ASSERTION(cacheEntry, "### cacheEntry == nullptr"); + + if (!initialized) return; // NS_ERROR_NOT_INITIALIZED + +#if DEBUG + // XXX debug code to make sure we have the entry we're trying to remove + nsCacheEntry* check = GetEntry(&(cacheEntry->mKey)); + NS_ASSERTION(check == cacheEntry, + "### Attempting to remove unknown cache entry!!!"); +#endif + table.Remove(&(cacheEntry->mKey)); +} + +PLDHashTable::Iterator nsCacheEntryHashTable::Iter() { + return PLDHashTable::Iterator(&table); +} + +/** + * hash table operation callback functions + */ + +PLDHashNumber nsCacheEntryHashTable::HashKey(const void* key) { + return HashString(*static_cast<const nsCString*>(key)); +} + +bool nsCacheEntryHashTable::MatchEntry(const PLDHashEntryHdr* hashEntry, + const void* key) { + NS_ASSERTION(key != nullptr, + "### nsCacheEntryHashTable::MatchEntry : null key"); + nsCacheEntry* cacheEntry = + ((nsCacheEntryHashTableEntry*)hashEntry)->cacheEntry; + + return cacheEntry->mKey.Equals(*(nsCString*)key); +} + +void nsCacheEntryHashTable::MoveEntry(PLDHashTable* /* table */, + const PLDHashEntryHdr* from, + PLDHashEntryHdr* to) { + new (KnownNotNull, to) nsCacheEntryHashTableEntry( + std::move(*((nsCacheEntryHashTableEntry*)from))); + // No need to destroy `from`. +} + +void nsCacheEntryHashTable::ClearEntry(PLDHashTable* /* table */, + PLDHashEntryHdr* hashEntry) { + ((nsCacheEntryHashTableEntry*)hashEntry)->cacheEntry = nullptr; +} diff --git a/netwerk/cache/nsCacheEntry.h b/netwerk/cache/nsCacheEntry.h new file mode 100644 index 0000000000..ee2a2af35f --- /dev/null +++ b/netwerk/cache/nsCacheEntry.h @@ -0,0 +1,285 @@ +/* -*- 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/. */ + +#ifndef _nsCacheEntry_h_ +#define _nsCacheEntry_h_ + +#include "nsICache.h" +#include "nsICacheEntryDescriptor.h" +#include "nsCacheMetaData.h" + +#include "nspr.h" +#include "PLDHashTable.h" +#include "nscore.h" +#include "nsCOMPtr.h" +#include "nsString.h" +#include "nsAString.h" + +class nsCacheDevice; +class nsCacheMetaData; +class nsCacheRequest; +class nsCacheEntryDescriptor; +class nsIEventTarget; + +/****************************************************************************** + * nsCacheEntry + *******************************************************************************/ +class nsCacheEntry : public PRCList { + public: + nsCacheEntry(const nsACString& key, bool streamBased, + nsCacheStoragePolicy storagePolicy); + ~nsCacheEntry(); + + static nsresult Create(const char* key, bool streamBased, + nsCacheStoragePolicy storagePolicy, + nsCacheDevice* device, nsCacheEntry** result); + + nsCString* Key() { return &mKey; } + + int32_t FetchCount() { return mFetchCount; } + void SetFetchCount(int32_t count) { mFetchCount = count; } + void Fetched(); + + uint32_t LastFetched() { return mLastFetched; } + void SetLastFetched(uint32_t lastFetched) { mLastFetched = lastFetched; } + + uint32_t LastModified() { return mLastModified; } + void SetLastModified(uint32_t lastModified) { mLastModified = lastModified; } + + uint32_t ExpirationTime() { return mExpirationTime; } + void SetExpirationTime(uint32_t expires) { mExpirationTime = expires; } + + uint32_t Size() { return mDataSize + mMetaData.Size() + mKey.Length(); } + + nsCacheDevice* CacheDevice() { return mCacheDevice; } + void SetCacheDevice(nsCacheDevice* device) { mCacheDevice = device; } + void SetCustomCacheDevice(nsCacheDevice* device) { mCustomDevice = device; } + nsCacheDevice* CustomCacheDevice() { return mCustomDevice; } + const char* GetDeviceID(); + + /** + * Data accessors + */ + nsISupports* Data() { return mData; } + void SetData(nsISupports* data); + + int64_t PredictedDataSize() { return mPredictedDataSize; } + void SetPredictedDataSize(int64_t size) { mPredictedDataSize = size; } + + uint32_t DataSize() { return mDataSize; } + void SetDataSize(uint32_t size) { mDataSize = size; } + + void TouchData(); + + /** + * Meta data accessors + */ + const char* GetMetaDataElement(const char* key) { + return mMetaData.GetElement(key); + } + nsresult SetMetaDataElement(const char* key, const char* value) { + return mMetaData.SetElement(key, value); + } + nsresult VisitMetaDataElements(nsICacheMetaDataVisitor* visitor) { + return mMetaData.VisitElements(visitor); + } + nsresult FlattenMetaData(char* buffer, uint32_t bufSize) { + return mMetaData.FlattenMetaData(buffer, bufSize); + } + nsresult UnflattenMetaData(const char* buffer, uint32_t bufSize) { + return mMetaData.UnflattenMetaData(buffer, bufSize); + } + uint32_t MetaDataSize() { return mMetaData.Size(); } + + void TouchMetaData(); + + /** + * Security Info accessors + */ + nsISupports* SecurityInfo() { return mSecurityInfo; } + void SetSecurityInfo(nsISupports* info) { mSecurityInfo = info; } + + // XXX enumerate MetaData method + + enum CacheEntryFlags { + eStoragePolicyMask = 0x000000FF, + eDoomedMask = 0x00000100, + eEntryDirtyMask = 0x00000200, + eDataDirtyMask = 0x00000400, + eMetaDataDirtyMask = 0x00000800, + eStreamDataMask = 0x00001000, + eActiveMask = 0x00002000, + eInitializedMask = 0x00004000, + eValidMask = 0x00008000, + eBindingMask = 0x00010000, + ePrivateMask = 0x00020000 + }; + + void MarkBinding() { mFlags |= eBindingMask; } + void ClearBinding() { mFlags &= ~eBindingMask; } + bool IsBinding() { return (mFlags & eBindingMask) != 0; } + + void MarkEntryDirty() { mFlags |= eEntryDirtyMask; } + void MarkEntryClean() { mFlags &= ~eEntryDirtyMask; } + void MarkDataDirty() { mFlags |= eDataDirtyMask; } + void MarkDataClean() { mFlags &= ~eDataDirtyMask; } + void MarkMetaDataDirty() { mFlags |= eMetaDataDirtyMask; } + void MarkMetaDataClean() { mFlags &= ~eMetaDataDirtyMask; } + void MarkStreamData() { mFlags |= eStreamDataMask; } + void MarkValid() { mFlags |= eValidMask; } + void MarkInvalid() { mFlags &= ~eValidMask; } + void MarkPrivate() { mFlags |= ePrivateMask; } + void MarkPublic() { mFlags &= ~ePrivateMask; } + // void MarkAllowedInMemory() { mFlags |= eAllowedInMemoryMask; } + // void MarkAllowedOnDisk() { mFlags |= eAllowedOnDiskMask; } + + bool IsDoomed() { return (mFlags & eDoomedMask) != 0; } + bool IsEntryDirty() { return (mFlags & eEntryDirtyMask) != 0; } + bool IsDataDirty() { return (mFlags & eDataDirtyMask) != 0; } + bool IsMetaDataDirty() { return (mFlags & eMetaDataDirtyMask) != 0; } + bool IsStreamData() { return (mFlags & eStreamDataMask) != 0; } + bool IsActive() { return (mFlags & eActiveMask) != 0; } + bool IsInitialized() { return (mFlags & eInitializedMask) != 0; } + bool IsValid() { return (mFlags & eValidMask) != 0; } + bool IsInvalid() { return (mFlags & eValidMask) == 0; } + bool IsInUse() { + return IsBinding() || + !(PR_CLIST_IS_EMPTY(&mRequestQ) && PR_CLIST_IS_EMPTY(&mDescriptorQ)); + } + bool IsNotInUse() { return !IsInUse(); } + bool IsPrivate() { return (mFlags & ePrivateMask) != 0; } + + bool IsAllowedInMemory() { + return (StoragePolicy() == nsICache::STORE_ANYWHERE) || + (StoragePolicy() == nsICache::STORE_IN_MEMORY); + } + + bool IsAllowedOnDisk() { + return !IsPrivate() && ((StoragePolicy() == nsICache::STORE_ANYWHERE) || + (StoragePolicy() == nsICache::STORE_ON_DISK)); + } + + bool IsAllowedOffline() { + return (StoragePolicy() == nsICache::STORE_OFFLINE); + } + + nsCacheStoragePolicy StoragePolicy() { + return (nsCacheStoragePolicy)(mFlags & eStoragePolicyMask); + } + + void SetStoragePolicy(nsCacheStoragePolicy policy) { + NS_ASSERTION(policy <= 0xFF, "too many bits in nsCacheStoragePolicy"); + mFlags &= ~eStoragePolicyMask; // clear storage policy bits + mFlags |= policy; + } + + // methods for nsCacheService + nsresult RequestAccess(nsCacheRequest* request, + nsCacheAccessMode* accessGranted); + nsresult CreateDescriptor(nsCacheRequest* request, + nsCacheAccessMode accessGranted, + nsICacheEntryDescriptor** result); + + bool RemoveRequest(nsCacheRequest* request); + bool RemoveDescriptor(nsCacheEntryDescriptor* descriptor, bool* doomEntry); + + void GetDescriptors( + nsTArray<RefPtr<nsCacheEntryDescriptor> >& outDescriptors); + + private: + friend class nsCacheEntryHashTable; + friend class nsCacheService; + + void DetachDescriptors(); + + // internal methods + void MarkDoomed() { mFlags |= eDoomedMask; } + void MarkStreamBased() { mFlags |= eStreamDataMask; } + void MarkInitialized() { mFlags |= eInitializedMask; } + void MarkActive() { mFlags |= eActiveMask; } + void MarkInactive() { mFlags &= ~eActiveMask; } + + nsCString mKey; + uint32_t mFetchCount; // 4 + uint32_t mLastFetched; // 4 + uint32_t mLastModified; // 4 + uint32_t mLastValidated; // 4 + uint32_t mExpirationTime; // 4 + uint32_t mFlags; // 4 + int64_t mPredictedDataSize; // Size given by ContentLength. + uint32_t mDataSize; // 4 + nsCacheDevice* mCacheDevice; // 4 + nsCacheDevice* mCustomDevice; // 4 + nsCOMPtr<nsISupports> mSecurityInfo; // + nsISupports* mData; // strong ref + nsCOMPtr<nsIEventTarget> mEventTarget; + nsCacheMetaData mMetaData; // 4 + PRCList mRequestQ; // 8 + PRCList mDescriptorQ; // 8 +}; + +/****************************************************************************** + * nsCacheEntryInfo + *******************************************************************************/ +class nsCacheEntryInfo : public nsICacheEntryInfo { + public: + NS_DECL_ISUPPORTS + NS_DECL_NSICACHEENTRYINFO + + explicit nsCacheEntryInfo(nsCacheEntry* entry) : mCacheEntry(entry) {} + + void DetachEntry() { mCacheEntry = nullptr; } + + private: + nsCacheEntry* mCacheEntry; + + virtual ~nsCacheEntryInfo() = default; +}; + +/****************************************************************************** + * nsCacheEntryHashTable + *******************************************************************************/ + +struct nsCacheEntryHashTableEntry : public PLDHashEntryHdr { + nsCacheEntry* cacheEntry; +}; + +class nsCacheEntryHashTable { + public: + nsCacheEntryHashTable(); + ~nsCacheEntryHashTable(); + + void Init(); + void Shutdown(); + + nsCacheEntry* GetEntry(const nsCString* key) const; + nsresult AddEntry(nsCacheEntry* entry); + void RemoveEntry(nsCacheEntry* entry); + + PLDHashTable::Iterator Iter(); + + private: + // PLDHashTable operation callbacks + static PLDHashNumber HashKey(const void* key); + + static bool MatchEntry(const PLDHashEntryHdr* entry, const void* key); + + static void MoveEntry(PLDHashTable* table, const PLDHashEntryHdr* from, + PLDHashEntryHdr* to); + + static void ClearEntry(PLDHashTable* table, PLDHashEntryHdr* entry); + + static void Finalize(PLDHashTable* table); + + // member variables + static const PLDHashTableOps ops; + PLDHashTable table; + bool initialized; + + static const uint32_t kInitialTableLength = 256; +}; + +#endif // _nsCacheEntry_h_ diff --git a/netwerk/cache/nsCacheEntryDescriptor.cpp b/netwerk/cache/nsCacheEntryDescriptor.cpp new file mode 100644 index 0000000000..c879e8b31b --- /dev/null +++ b/netwerk/cache/nsCacheEntryDescriptor.cpp @@ -0,0 +1,1307 @@ +/* -*- 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 "nsICache.h" +#include "nsCache.h" +#include "nsCacheService.h" +#include "nsCacheEntryDescriptor.h" +#include "nsCacheEntry.h" +#include "nsReadableUtils.h" +#include "nsIOutputStream.h" +#include "nsCRT.h" +#include "nsThreadUtils.h" +#include <algorithm> +#include "mozilla/IntegerPrintfMacros.h" + +#define kMinDecompressReadBufLen 1024 +#define kMinCompressWriteBufLen 1024 + +/****************************************************************************** + * nsAsyncDoomEvent + *****************************************************************************/ + +class nsAsyncDoomEvent : public mozilla::Runnable { + public: + nsAsyncDoomEvent(nsCacheEntryDescriptor* descriptor, + nsICacheListener* listener) + : mozilla::Runnable("nsAsyncDoomEvent") { + mDescriptor = descriptor; + mListener = listener; + mEventTarget = GetCurrentEventTarget(); + // We addref the listener here and release it in nsNotifyDoomListener + // on the callers thread. If posting of nsNotifyDoomListener event fails + // we leak the listener which is better than releasing it on a wrong + // thread. + NS_IF_ADDREF(mListener); + } + + NS_IMETHOD Run() override { + nsresult status = NS_OK; + + { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSASYNCDOOMEVENT_RUN)); + + if (mDescriptor->mCacheEntry) { + status = nsCacheService::gService->DoomEntry_Internal( + mDescriptor->mCacheEntry, true); + } else if (!mDescriptor->mDoomedOnClose) { + status = NS_ERROR_NOT_AVAILABLE; + } + } + + if (mListener) { + mEventTarget->Dispatch(new nsNotifyDoomListener(mListener, status), + NS_DISPATCH_NORMAL); + // posted event will release the reference on the correct thread + mListener = nullptr; + } + + return NS_OK; + } + + private: + RefPtr<nsCacheEntryDescriptor> mDescriptor; + nsICacheListener* mListener; + nsCOMPtr<nsIEventTarget> mEventTarget; +}; + +NS_IMPL_ISUPPORTS(nsCacheEntryDescriptor, nsICacheEntryDescriptor, + nsICacheEntryInfo) + +nsCacheEntryDescriptor::nsCacheEntryDescriptor(nsCacheEntry* entry, + nsCacheAccessMode accessGranted) + : mCacheEntry(entry), + mAccessGranted(accessGranted), + mOutputWrapper(nullptr), + mLock("nsCacheEntryDescriptor.mLock"), + mAsyncDoomPending(false), + mDoomedOnClose(false), + mClosingDescriptor(false) { + PR_INIT_CLIST(this); + // We need to make sure the cache service lives for the entire lifetime + // of the descriptor + mCacheService = nsCacheService::GlobalInstance(); +} + +nsCacheEntryDescriptor::~nsCacheEntryDescriptor() { + // No need to close if the cache entry has already been severed. This + // helps avoid a shutdown assertion (bug 285519) that is caused when + // consumers end up holding onto these objects past xpcom-shutdown. It's + // okay for them to do that because the cache service calls our Close + // method during xpcom-shutdown, so we don't need to complain about it. + if (mCacheEntry) Close(); + + NS_ASSERTION(mInputWrappers.IsEmpty(), "We have still some input wrapper!"); + NS_ASSERTION(!mOutputWrapper, "We have still an output wrapper!"); +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetClientID(nsACString& aClientID) { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETCLIENTID)); + if (!mCacheEntry) { + aClientID.Truncate(); + return NS_ERROR_NOT_AVAILABLE; + } + + return ClientIDFromCacheKey(*(mCacheEntry->Key()), aClientID); +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetDeviceID(nsACString& aDeviceID) { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETDEVICEID)); + if (!mCacheEntry) { + aDeviceID.Truncate(); + return NS_ERROR_NOT_AVAILABLE; + } + + aDeviceID.Assign(mCacheEntry->GetDeviceID()); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetKey(nsACString& result) { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETKEY)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + return ClientKeyFromCacheKey(*(mCacheEntry->Key()), result); +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetFetchCount(int32_t* result) { + NS_ENSURE_ARG_POINTER(result); + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETFETCHCOUNT)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *result = mCacheEntry->FetchCount(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetLastFetched(uint32_t* result) { + NS_ENSURE_ARG_POINTER(result); + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETLASTFETCHED)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *result = mCacheEntry->LastFetched(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetLastModified(uint32_t* result) { + NS_ENSURE_ARG_POINTER(result); + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETLASTMODIFIED)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *result = mCacheEntry->LastModified(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetExpirationTime(uint32_t* result) { + NS_ENSURE_ARG_POINTER(result); + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETEXPIRATIONTIME)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *result = mCacheEntry->ExpirationTime(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::SetExpirationTime(uint32_t expirationTime) { + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_SETEXPIRATIONTIME)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + mCacheEntry->SetExpirationTime(expirationTime); + mCacheEntry->MarkEntryDirty(); + return NS_OK; +} + +NS_IMETHODIMP nsCacheEntryDescriptor::IsStreamBased(bool* result) { + NS_ENSURE_ARG_POINTER(result); + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_ISSTREAMBASED)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *result = mCacheEntry->IsStreamData(); + return NS_OK; +} + +NS_IMETHODIMP nsCacheEntryDescriptor::GetPredictedDataSize(int64_t* result) { + NS_ENSURE_ARG_POINTER(result); + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETPREDICTEDDATASIZE)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *result = mCacheEntry->PredictedDataSize(); + return NS_OK; +} + +NS_IMETHODIMP nsCacheEntryDescriptor::SetPredictedDataSize( + int64_t predictedSize) { + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_SETPREDICTEDDATASIZE)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + mCacheEntry->SetPredictedDataSize(predictedSize); + return NS_OK; +} + +NS_IMETHODIMP nsCacheEntryDescriptor::GetDataSize(uint32_t* result) { + NS_ENSURE_ARG_POINTER(result); + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETDATASIZE)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + const char* val = mCacheEntry->GetMetaDataElement("uncompressed-len"); + if (!val) { + *result = mCacheEntry->DataSize(); + } else { + *result = atol(val); + } + + return NS_OK; +} + +NS_IMETHODIMP nsCacheEntryDescriptor::GetStorageDataSize(uint32_t* result) { + NS_ENSURE_ARG_POINTER(result); + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETSTORAGEDATASIZE)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *result = mCacheEntry->DataSize(); + + return NS_OK; +} + +nsresult nsCacheEntryDescriptor::RequestDataSizeChange(int32_t deltaSize) { + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_REQUESTDATASIZECHANGE)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + nsresult rv; + rv = nsCacheService::OnDataSizeChange(mCacheEntry, deltaSize); + if (NS_SUCCEEDED(rv)) { + // XXX review for signed/unsigned math errors + uint32_t newDataSize = mCacheEntry->DataSize() + deltaSize; + mCacheEntry->SetDataSize(newDataSize); + mCacheEntry->TouchData(); + } + return rv; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::SetDataSize(uint32_t dataSize) { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_SETDATASIZE)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + // XXX review for signed/unsigned math errors + int32_t deltaSize = dataSize - mCacheEntry->DataSize(); + + nsresult rv; + rv = nsCacheService::OnDataSizeChange(mCacheEntry, deltaSize); + // this had better be NS_OK, this call instance is advisory for memory cache + // objects + if (NS_SUCCEEDED(rv)) { + // XXX review for signed/unsigned math errors + uint32_t newDataSize = mCacheEntry->DataSize() + deltaSize; + mCacheEntry->SetDataSize(newDataSize); + mCacheEntry->TouchData(); + } else { + NS_WARNING("failed SetDataSize() on memory cache object!"); + } + + return rv; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::OpenInputStream(uint32_t offset, + nsIInputStream** result) { + NS_ENSURE_ARG_POINTER(result); + + RefPtr<nsInputStreamWrapper> cacheInput; + { + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_OPENINPUTSTREAM)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + if (!mCacheEntry->IsStreamData()) return NS_ERROR_CACHE_DATA_IS_NOT_STREAM; + + // Don't open any new stream when closing descriptor or clearing entries + if (mClosingDescriptor || nsCacheService::GetClearingEntries()) + return NS_ERROR_NOT_AVAILABLE; + + // ensure valid permissions + if (!(mAccessGranted & nsICache::ACCESS_READ)) + return NS_ERROR_CACHE_READ_ACCESS_DENIED; + + const char* val; + val = mCacheEntry->GetMetaDataElement("uncompressed-len"); + if (val) { + cacheInput = new nsDecompressInputStreamWrapper(this, offset); + } else { + cacheInput = new nsInputStreamWrapper(this, offset); + } + if (!cacheInput) return NS_ERROR_OUT_OF_MEMORY; + + mInputWrappers.AppendElement(cacheInput); + } + + cacheInput.forget(result); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::OpenOutputStream(uint32_t offset, + nsIOutputStream** result) { + NS_ENSURE_ARG_POINTER(result); + + RefPtr<nsOutputStreamWrapper> cacheOutput; + { + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_OPENOUTPUTSTREAM)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + if (!mCacheEntry->IsStreamData()) return NS_ERROR_CACHE_DATA_IS_NOT_STREAM; + + // Don't open any new stream when closing descriptor or clearing entries + if (mClosingDescriptor || nsCacheService::GetClearingEntries()) + return NS_ERROR_NOT_AVAILABLE; + + // ensure valid permissions + if (!(mAccessGranted & nsICache::ACCESS_WRITE)) + return NS_ERROR_CACHE_WRITE_ACCESS_DENIED; + + int32_t compressionLevel = nsCacheService::CacheCompressionLevel(); + const char* val; + val = mCacheEntry->GetMetaDataElement("uncompressed-len"); + if ((compressionLevel > 0) && val) { + cacheOutput = new nsCompressOutputStreamWrapper(this, offset); + } else { + // clear compression flag when compression disabled - see bug 715198 + if (val) { + mCacheEntry->SetMetaDataElement("uncompressed-len", nullptr); + } + cacheOutput = new nsOutputStreamWrapper(this, offset); + } + if (!cacheOutput) return NS_ERROR_OUT_OF_MEMORY; + + mOutputWrapper = cacheOutput; + } + + cacheOutput.forget(result); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetCacheElement(nsISupports** result) { + NS_ENSURE_ARG_POINTER(result); + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETCACHEELEMENT)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + if (mCacheEntry->IsStreamData()) return NS_ERROR_CACHE_DATA_IS_STREAM; + + NS_IF_ADDREF(*result = mCacheEntry->Data()); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::SetCacheElement(nsISupports* cacheElement) { + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_SETCACHEELEMENT)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + if (mCacheEntry->IsStreamData()) return NS_ERROR_CACHE_DATA_IS_STREAM; + + return nsCacheService::SetCacheElement(mCacheEntry, cacheElement); +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetAccessGranted(nsCacheAccessMode* result) { + NS_ENSURE_ARG_POINTER(result); + *result = mAccessGranted; + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetStoragePolicy(nsCacheStoragePolicy* result) { + NS_ENSURE_ARG_POINTER(result); + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETSTORAGEPOLICY)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *result = mCacheEntry->StoragePolicy(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::SetStoragePolicy(nsCacheStoragePolicy policy) { + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_SETSTORAGEPOLICY)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + // XXX validate policy against session? + + bool storageEnabled = false; + storageEnabled = nsCacheService::IsStorageEnabledForPolicy_Locked(policy); + if (!storageEnabled) return NS_ERROR_FAILURE; + + // Don't change the storage policy of entries we can't write + if (!(mAccessGranted & nsICache::ACCESS_WRITE)) return NS_ERROR_NOT_AVAILABLE; + + // Don't allow a cache entry to move from memory-only to anything else + if (mCacheEntry->StoragePolicy() == nsICache::STORE_IN_MEMORY && + policy != nsICache::STORE_IN_MEMORY) + return NS_ERROR_NOT_AVAILABLE; + + mCacheEntry->SetStoragePolicy(policy); + mCacheEntry->MarkEntryDirty(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetFile(nsIFile** result) { + NS_ENSURE_ARG_POINTER(result); + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETFILE)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + return nsCacheService::GetFileForEntry(mCacheEntry, result); +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetSecurityInfo(nsISupports** result) { + NS_ENSURE_ARG_POINTER(result); + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETSECURITYINFO)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + *result = mCacheEntry->SecurityInfo(); + NS_IF_ADDREF(*result); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::SetSecurityInfo(nsISupports* securityInfo) { + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_SETSECURITYINFO)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + mCacheEntry->SetSecurityInfo(securityInfo); + mCacheEntry->MarkEntryDirty(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::Doom() { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_DOOM)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + return nsCacheService::DoomEntry(mCacheEntry); +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::DoomAndFailPendingRequests(nsresult status) { + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_DOOMANDFAILPENDINGREQUESTS)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + return NS_ERROR_NOT_IMPLEMENTED; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::AsyncDoom(nsICacheListener* listener) { + bool asyncDoomPending; + { + mozilla::MutexAutoLock lock(mLock); + asyncDoomPending = mAsyncDoomPending; + mAsyncDoomPending = true; + } + + if (asyncDoomPending) { + // AsyncDoom was already called. Notify listener if it is non-null, + // otherwise just return success. + if (listener) { + nsresult rv = NS_DispatchToCurrentThread( + new nsNotifyDoomListener(listener, NS_ERROR_NOT_AVAILABLE)); + if (NS_SUCCEEDED(rv)) NS_IF_ADDREF(listener); + return rv; + } + return NS_OK; + } + + nsCOMPtr<nsIRunnable> event = new nsAsyncDoomEvent(this, listener); + return nsCacheService::DispatchToCacheIOThread(event); +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::MarkValid() { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_MARKVALID)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + nsresult rv = nsCacheService::ValidateEntry(mCacheEntry); + return rv; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::Close() { + RefPtr<nsOutputStreamWrapper> outputWrapper; + nsTArray<RefPtr<nsInputStreamWrapper> > inputWrappers; + + { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_CLOSE)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + // Make sure no other stream can be opened + mClosingDescriptor = true; + outputWrapper = mOutputWrapper; + for (size_t i = 0; i < mInputWrappers.Length(); i++) + inputWrappers.AppendElement(mInputWrappers[i]); + } + + // Call Close() on the streams outside the lock since it might need to call + // methods that grab the cache service lock, e.g. compressed output stream + // when it finalizes the entry + if (outputWrapper) { + if (NS_FAILED(outputWrapper->Close())) { + NS_WARNING("Dooming entry because Close() failed!!!"); + Doom(); + } + outputWrapper = nullptr; + } + + for (uint32_t i = 0; i < inputWrappers.Length(); i++) + inputWrappers[i]->Close(); + + inputWrappers.Clear(); + + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_CLOSE)); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + // XXX perhaps closing descriptors should clear/sever transports + + // tell nsCacheService we're going away + nsCacheService::CloseDescriptor(this); + NS_ASSERTION(mCacheEntry == nullptr, "mCacheEntry not null"); + + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::GetMetaDataElement(const char* key, char** result) { + NS_ENSURE_ARG_POINTER(key); + *result = nullptr; + + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_GETMETADATAELEMENT)); + NS_ENSURE_TRUE(mCacheEntry, NS_ERROR_NOT_AVAILABLE); + + const char* value; + + value = mCacheEntry->GetMetaDataElement(key); + if (!value) return NS_ERROR_NOT_AVAILABLE; + + *result = NS_xstrdup(value); + + return NS_OK; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::SetMetaDataElement(const char* key, const char* value) { + NS_ENSURE_ARG_POINTER(key); + + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_SETMETADATAELEMENT)); + NS_ENSURE_TRUE(mCacheEntry, NS_ERROR_NOT_AVAILABLE); + + // XXX allow null value, for clearing key? + + nsresult rv = mCacheEntry->SetMetaDataElement(key, value); + if (NS_SUCCEEDED(rv)) mCacheEntry->TouchMetaData(); + return rv; +} + +NS_IMETHODIMP +nsCacheEntryDescriptor::VisitMetaData(nsICacheMetaDataVisitor* visitor) { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHEENTRYDESCRIPTOR_VISITMETADATA)); + // XXX check callers, we're calling out of module + NS_ENSURE_ARG_POINTER(visitor); + if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE; + + return mCacheEntry->VisitMetaDataElements(visitor); +} + +/****************************************************************************** + * nsCacheInputStream - a wrapper for nsIInputStream keeps the cache entry + * open while referenced. + ******************************************************************************/ + +NS_IMPL_ADDREF(nsCacheEntryDescriptor::nsInputStreamWrapper) +NS_IMETHODIMP_(MozExternalRefCountType) +nsCacheEntryDescriptor::nsInputStreamWrapper::Release() { + // Holding a reference to descriptor ensures that cache service won't go + // away. Do not grab cache service lock if there is no descriptor. + RefPtr<nsCacheEntryDescriptor> desc; + + { + mozilla::MutexAutoLock lock(mLock); + desc = mDescriptor; + } + + if (desc) nsCacheService::Lock(LOCK_TELEM(NSINPUTSTREAMWRAPPER_RELEASE)); + + nsrefcnt count; + MOZ_ASSERT(0 != mRefCnt, "dup release"); + count = --mRefCnt; + NS_LOG_RELEASE(this, count, "nsCacheEntryDescriptor::nsInputStreamWrapper"); + + if (0 == count) { + // don't use desc here since mDescriptor might be already nulled out + if (mDescriptor) { + NS_ASSERTION(mDescriptor->mInputWrappers.Contains(this), + "Wrapper not found in array!"); + mDescriptor->mInputWrappers.RemoveElement(this); + } + + if (desc) nsCacheService::Unlock(); + + mRefCnt = 1; + delete (this); + return 0; + } + + if (desc) nsCacheService::Unlock(); + + return count; +} + +NS_INTERFACE_MAP_BEGIN(nsCacheEntryDescriptor::nsInputStreamWrapper) + NS_INTERFACE_MAP_ENTRY(nsIInputStream) + NS_INTERFACE_MAP_ENTRY(nsISupports) +NS_INTERFACE_MAP_END + +nsresult nsCacheEntryDescriptor::nsInputStreamWrapper::LazyInit() { + // Check if we have the descriptor. If not we can't even grab the cache + // lock since it is not ensured that the cache service still exists. + if (!mDescriptor) return NS_ERROR_NOT_AVAILABLE; + + nsCacheServiceAutoLock lock(LOCK_TELEM(NSINPUTSTREAMWRAPPER_LAZYINIT)); + + nsCacheAccessMode mode; + nsresult rv = mDescriptor->GetAccessGranted(&mode); + if (NS_FAILED(rv)) return rv; + + NS_ENSURE_TRUE(mode & nsICache::ACCESS_READ, NS_ERROR_UNEXPECTED); + + nsCacheEntry* cacheEntry = mDescriptor->CacheEntry(); + if (!cacheEntry) return NS_ERROR_NOT_AVAILABLE; + + rv = nsCacheService::OpenInputStreamForEntry(cacheEntry, mode, mStartOffset, + getter_AddRefs(mInput)); + + CACHE_LOG_DEBUG( + ("nsInputStreamWrapper::LazyInit " + "[entry=%p, wrapper=%p, mInput=%p, rv=%d]", + mDescriptor, this, mInput.get(), int(rv))); + + if (NS_FAILED(rv)) return rv; + + mInitialized = true; + return NS_OK; +} + +nsresult nsCacheEntryDescriptor::nsInputStreamWrapper::EnsureInit() { + if (mInitialized) { + NS_ASSERTION(mDescriptor, "Bad state"); + return NS_OK; + } + + return LazyInit(); +} + +void nsCacheEntryDescriptor::nsInputStreamWrapper::CloseInternal() { + mLock.AssertCurrentThreadOwns(); + if (!mDescriptor) { + NS_ASSERTION(!mInitialized, "Bad state"); + NS_ASSERTION(!mInput, "Bad state"); + return; + } + + nsCacheServiceAutoLock lock(LOCK_TELEM(NSINPUTSTREAMWRAPPER_CLOSEINTERNAL)); + + if (mDescriptor) { + mDescriptor->mInputWrappers.RemoveElement(this); + nsCacheService::ReleaseObject_Locked(mDescriptor); + mDescriptor = nullptr; + } + mInitialized = false; + mInput = nullptr; +} + +nsresult nsCacheEntryDescriptor::nsInputStreamWrapper::Close() { + mozilla::MutexAutoLock lock(mLock); + + return Close_Locked(); +} + +nsresult nsCacheEntryDescriptor::nsInputStreamWrapper::Close_Locked() { + nsresult rv = EnsureInit(); + if (NS_SUCCEEDED(rv)) { + rv = mInput->Close(); + } else { + NS_ASSERTION(!mInput, "Shouldn't have mInput when EnsureInit() failed"); + } + + // Call CloseInternal() even when EnsureInit() failed, e.g. in case we are + // closing streams with nsCacheService::CloseAllStream() + CloseInternal(); + return rv; +} + +nsresult nsCacheEntryDescriptor::nsInputStreamWrapper::Available( + uint64_t* avail) { + mozilla::MutexAutoLock lock(mLock); + + nsresult rv = EnsureInit(); + if (NS_FAILED(rv)) return rv; + + return mInput->Available(avail); +} + +nsresult nsCacheEntryDescriptor::nsInputStreamWrapper::Read( + char* buf, uint32_t count, uint32_t* countRead) { + mozilla::MutexAutoLock lock(mLock); + + return Read_Locked(buf, count, countRead); +} + +nsresult nsCacheEntryDescriptor::nsInputStreamWrapper::Read_Locked( + char* buf, uint32_t count, uint32_t* countRead) { + nsresult rv = EnsureInit(); + if (NS_SUCCEEDED(rv)) rv = mInput->Read(buf, count, countRead); + + CACHE_LOG_DEBUG( + ("nsInputStreamWrapper::Read " + "[entry=%p, wrapper=%p, mInput=%p, rv=%" PRId32 "]", + mDescriptor, this, mInput.get(), static_cast<uint32_t>(rv))); + + return rv; +} + +nsresult nsCacheEntryDescriptor::nsInputStreamWrapper::ReadSegments( + nsWriteSegmentFun writer, void* closure, uint32_t count, + uint32_t* countRead) { + // cache stream not buffered + return NS_ERROR_NOT_IMPLEMENTED; +} + +nsresult nsCacheEntryDescriptor::nsInputStreamWrapper::IsNonBlocking( + bool* result) { + // cache streams will never return NS_BASE_STREAM_WOULD_BLOCK + *result = false; + return NS_OK; +} + +/****************************************************************************** + * nsDecompressInputStreamWrapper - an input stream wrapper that decompresses + ******************************************************************************/ + +NS_IMPL_ADDREF(nsCacheEntryDescriptor::nsDecompressInputStreamWrapper) +NS_IMETHODIMP_(MozExternalRefCountType) +nsCacheEntryDescriptor::nsDecompressInputStreamWrapper::Release() { + // Holding a reference to descriptor ensures that cache service won't go + // away. Do not grab cache service lock if there is no descriptor. + RefPtr<nsCacheEntryDescriptor> desc; + + { + mozilla::MutexAutoLock lock(mLock); + desc = mDescriptor; + } + + if (desc) + nsCacheService::Lock(LOCK_TELEM(NSDECOMPRESSINPUTSTREAMWRAPPER_RELEASE)); + + nsrefcnt count; + MOZ_ASSERT(0 != mRefCnt, "dup release"); + count = --mRefCnt; + NS_LOG_RELEASE(this, count, + "nsCacheEntryDescriptor::nsDecompressInputStreamWrapper"); + + if (0 == count) { + // don't use desc here since mDescriptor might be already nulled out + if (mDescriptor) { + NS_ASSERTION(mDescriptor->mInputWrappers.Contains(this), + "Wrapper not found in array!"); + mDescriptor->mInputWrappers.RemoveElement(this); + } + + if (desc) nsCacheService::Unlock(); + + mRefCnt = 1; + delete (this); + return 0; + } + + if (desc) nsCacheService::Unlock(); + + return count; +} + +NS_INTERFACE_MAP_BEGIN(nsCacheEntryDescriptor::nsDecompressInputStreamWrapper) + NS_INTERFACE_MAP_ENTRY(nsIInputStream) + NS_INTERFACE_MAP_ENTRY(nsISupports) +NS_INTERFACE_MAP_END + +NS_IMETHODIMP nsCacheEntryDescriptor::nsDecompressInputStreamWrapper::Read( + char* buf, uint32_t count, uint32_t* countRead) { + mozilla::MutexAutoLock lock(mLock); + + int zerr = Z_OK; + nsresult rv = NS_OK; + + if (!mStreamInitialized) { + rv = InitZstream(); + if (NS_FAILED(rv)) { + return rv; + } + } + + mZstream.next_out = (Bytef*)buf; + mZstream.avail_out = count; + + if (mReadBufferLen < count) { + // Allocate a buffer for reading from the input stream. This will + // determine the max number of compressed bytes read from the + // input stream at one time. Making the buffer size proportional + // to the request size is not necessary, but helps minimize the + // number of read requests to the input stream. + uint32_t newBufLen = std::max(count, (uint32_t)kMinDecompressReadBufLen); + mReadBuffer = (unsigned char*)moz_xrealloc(mReadBuffer, newBufLen); + mReadBufferLen = newBufLen; + if (!mReadBuffer) { + mReadBufferLen = 0; + return NS_ERROR_OUT_OF_MEMORY; + } + } + + // read and inflate data until the output buffer is full, or + // there is no more data to read + while (NS_SUCCEEDED(rv) && zerr == Z_OK && mZstream.avail_out > 0 && + count > 0) { + if (mZstream.avail_in == 0) { + rv = nsInputStreamWrapper::Read_Locked((char*)mReadBuffer, mReadBufferLen, + &mZstream.avail_in); + if (NS_FAILED(rv) || !mZstream.avail_in) { + break; + } + mZstream.next_in = mReadBuffer; + } + zerr = inflate(&mZstream, Z_NO_FLUSH); + if (zerr == Z_STREAM_END) { + // The compressed data may have been stored in multiple + // chunks/streams. To allow for this case, re-initialize + // the inflate stream and continue decompressing from + // the next byte. + Bytef* saveNextIn = mZstream.next_in; + unsigned int saveAvailIn = mZstream.avail_in; + Bytef* saveNextOut = mZstream.next_out; + unsigned int saveAvailOut = mZstream.avail_out; + inflateReset(&mZstream); + mZstream.next_in = saveNextIn; + mZstream.avail_in = saveAvailIn; + mZstream.next_out = saveNextOut; + mZstream.avail_out = saveAvailOut; + zerr = Z_OK; + } else if (zerr != Z_OK) { + rv = NS_ERROR_INVALID_CONTENT_ENCODING; + } + } + if (NS_SUCCEEDED(rv)) { + *countRead = count - mZstream.avail_out; + } + return rv; +} + +nsresult nsCacheEntryDescriptor::nsDecompressInputStreamWrapper::Close() { + mozilla::MutexAutoLock lock(mLock); + + if (!mDescriptor) return NS_ERROR_NOT_AVAILABLE; + + EndZstream(); + if (mReadBuffer) { + free(mReadBuffer); + mReadBuffer = nullptr; + mReadBufferLen = 0; + } + return nsInputStreamWrapper::Close_Locked(); +} + +nsresult nsCacheEntryDescriptor::nsDecompressInputStreamWrapper::InitZstream() { + if (!mDescriptor) return NS_ERROR_NOT_AVAILABLE; + + if (mStreamEnded) return NS_ERROR_FAILURE; + + // Initialize zlib inflate stream + mZstream.zalloc = Z_NULL; + mZstream.zfree = Z_NULL; + mZstream.opaque = Z_NULL; + mZstream.next_out = Z_NULL; + mZstream.avail_out = 0; + mZstream.next_in = Z_NULL; + mZstream.avail_in = 0; + if (inflateInit(&mZstream) != Z_OK) { + return NS_ERROR_FAILURE; + } + mStreamInitialized = true; + return NS_OK; +} + +nsresult nsCacheEntryDescriptor::nsDecompressInputStreamWrapper::EndZstream() { + if (mStreamInitialized && !mStreamEnded) { + inflateEnd(&mZstream); + mStreamInitialized = false; + mStreamEnded = true; + } + return NS_OK; +} + +/****************************************************************************** + * nsOutputStreamWrapper - a wrapper for nsIOutputstream to track the amount of + * data written to a cache entry. + * - also keeps the cache entry open while referenced. + ******************************************************************************/ + +NS_IMPL_ADDREF(nsCacheEntryDescriptor::nsOutputStreamWrapper) +NS_IMETHODIMP_(MozExternalRefCountType) +nsCacheEntryDescriptor::nsOutputStreamWrapper::Release() { + // Holding a reference to descriptor ensures that cache service won't go + // away. Do not grab cache service lock if there is no descriptor. + RefPtr<nsCacheEntryDescriptor> desc; + + { + mozilla::MutexAutoLock lock(mLock); + desc = mDescriptor; + } + + if (desc) nsCacheService::Lock(LOCK_TELEM(NSOUTPUTSTREAMWRAPPER_RELEASE)); + + nsrefcnt count; + MOZ_ASSERT(0 != mRefCnt, "dup release"); + count = --mRefCnt; + NS_LOG_RELEASE(this, count, "nsCacheEntryDescriptor::nsOutputStreamWrapper"); + + if (0 == count) { + // don't use desc here since mDescriptor might be already nulled out + if (mDescriptor) mDescriptor->mOutputWrapper = nullptr; + + if (desc) nsCacheService::Unlock(); + + mRefCnt = 1; + delete (this); + return 0; + } + + if (desc) nsCacheService::Unlock(); + + return count; +} + +NS_INTERFACE_MAP_BEGIN(nsCacheEntryDescriptor::nsOutputStreamWrapper) + NS_INTERFACE_MAP_ENTRY(nsIOutputStream) + NS_INTERFACE_MAP_ENTRY(nsISupports) +NS_INTERFACE_MAP_END + +nsresult nsCacheEntryDescriptor::nsOutputStreamWrapper::LazyInit() { + // Check if we have the descriptor. If not we can't even grab the cache + // lock since it is not ensured that the cache service still exists. + if (!mDescriptor) return NS_ERROR_NOT_AVAILABLE; + + nsCacheServiceAutoLock lock(LOCK_TELEM(NSOUTPUTSTREAMWRAPPER_LAZYINIT)); + + nsCacheAccessMode mode; + nsresult rv = mDescriptor->GetAccessGranted(&mode); + if (NS_FAILED(rv)) return rv; + + NS_ENSURE_TRUE(mode & nsICache::ACCESS_WRITE, NS_ERROR_UNEXPECTED); + + nsCacheEntry* cacheEntry = mDescriptor->CacheEntry(); + if (!cacheEntry) return NS_ERROR_NOT_AVAILABLE; + + NS_ASSERTION(mOutput == nullptr, "mOutput set in LazyInit"); + + nsCOMPtr<nsIOutputStream> stream; + rv = nsCacheService::OpenOutputStreamForEntry(cacheEntry, mode, mStartOffset, + getter_AddRefs(stream)); + if (NS_FAILED(rv)) return rv; + + nsCacheDevice* device = cacheEntry->CacheDevice(); + if (device) { + // the entry has been truncated to mStartOffset bytes, inform device + int32_t size = cacheEntry->DataSize(); + rv = device->OnDataSizeChange(cacheEntry, mStartOffset - size); + if (NS_SUCCEEDED(rv)) cacheEntry->SetDataSize(mStartOffset); + } else { + rv = NS_ERROR_NOT_AVAILABLE; + } + + // If anything above failed, clean up internal state and get out of here + // (see bug #654926)... + if (NS_FAILED(rv)) { + nsCacheService::ReleaseObject_Locked(stream.forget().take()); + mDescriptor->mOutputWrapper = nullptr; + nsCacheService::ReleaseObject_Locked(mDescriptor); + mDescriptor = nullptr; + mInitialized = false; + return rv; + } + + mOutput = stream; + mInitialized = true; + return NS_OK; +} + +nsresult nsCacheEntryDescriptor::nsOutputStreamWrapper::EnsureInit() { + if (mInitialized) { + NS_ASSERTION(mDescriptor, "Bad state"); + return NS_OK; + } + + return LazyInit(); +} + +nsresult nsCacheEntryDescriptor::nsOutputStreamWrapper::OnWrite( + uint32_t count) { + if (count > INT32_MAX) return NS_ERROR_UNEXPECTED; + return mDescriptor->RequestDataSizeChange((int32_t)count); +} + +void nsCacheEntryDescriptor::nsOutputStreamWrapper::CloseInternal() { + mLock.AssertCurrentThreadOwns(); + if (!mDescriptor) { + NS_ASSERTION(!mInitialized, "Bad state"); + NS_ASSERTION(!mOutput, "Bad state"); + return; + } + + nsCacheServiceAutoLock lock(LOCK_TELEM(NSOUTPUTSTREAMWRAPPER_CLOSEINTERNAL)); + + if (mDescriptor) { + mDescriptor->mOutputWrapper = nullptr; + nsCacheService::ReleaseObject_Locked(mDescriptor); + mDescriptor = nullptr; + } + mInitialized = false; + mOutput = nullptr; +} + +NS_IMETHODIMP nsCacheEntryDescriptor::nsOutputStreamWrapper::Close() { + mozilla::MutexAutoLock lock(mLock); + + return Close_Locked(); +} + +nsresult nsCacheEntryDescriptor::nsOutputStreamWrapper::Close_Locked() { + nsresult rv = EnsureInit(); + if (NS_SUCCEEDED(rv)) { + rv = mOutput->Close(); + } else { + NS_ASSERTION(!mOutput, "Shouldn't have mOutput when EnsureInit() failed"); + } + + // Call CloseInternal() even when EnsureInit() failed, e.g. in case we are + // closing streams with nsCacheService::CloseAllStream() + CloseInternal(); + return rv; +} + +NS_IMETHODIMP nsCacheEntryDescriptor::nsOutputStreamWrapper::Flush() { + mozilla::MutexAutoLock lock(mLock); + + nsresult rv = EnsureInit(); + if (NS_FAILED(rv)) return rv; + + return mOutput->Flush(); +} + +NS_IMETHODIMP nsCacheEntryDescriptor::nsOutputStreamWrapper::Write( + const char* buf, uint32_t count, uint32_t* result) { + mozilla::MutexAutoLock lock(mLock); + return Write_Locked(buf, count, result); +} + +nsresult nsCacheEntryDescriptor::nsOutputStreamWrapper::Write_Locked( + const char* buf, uint32_t count, uint32_t* result) { + nsresult rv = EnsureInit(); + if (NS_FAILED(rv)) return rv; + + rv = OnWrite(count); + if (NS_FAILED(rv)) return rv; + + return mOutput->Write(buf, count, result); +} + +NS_IMETHODIMP nsCacheEntryDescriptor::nsOutputStreamWrapper::WriteFrom( + nsIInputStream* inStr, uint32_t count, uint32_t* result) { + return NS_ERROR_NOT_IMPLEMENTED; +} + +NS_IMETHODIMP nsCacheEntryDescriptor::nsOutputStreamWrapper::WriteSegments( + nsReadSegmentFun reader, void* closure, uint32_t count, uint32_t* result) { + return NS_ERROR_NOT_IMPLEMENTED; +} + +NS_IMETHODIMP nsCacheEntryDescriptor::nsOutputStreamWrapper::IsNonBlocking( + bool* result) { + // cache streams will never return NS_BASE_STREAM_WOULD_BLOCK + *result = false; + return NS_OK; +} + +/****************************************************************************** + * nsCompressOutputStreamWrapper - an output stream wrapper that compresses + * data before it is written + ******************************************************************************/ + +NS_IMPL_ADDREF(nsCacheEntryDescriptor::nsCompressOutputStreamWrapper) +NS_IMETHODIMP_(MozExternalRefCountType) +nsCacheEntryDescriptor::nsCompressOutputStreamWrapper::Release() { + // Holding a reference to descriptor ensures that cache service won't go + // away. Do not grab cache service lock if there is no descriptor. + RefPtr<nsCacheEntryDescriptor> desc; + + { + mozilla::MutexAutoLock lock(mLock); + desc = mDescriptor; + } + + if (desc) + nsCacheService::Lock(LOCK_TELEM(NSCOMPRESSOUTPUTSTREAMWRAPPER_RELEASE)); + + nsrefcnt count; + MOZ_ASSERT(0 != mRefCnt, "dup release"); + count = --mRefCnt; + NS_LOG_RELEASE(this, count, + "nsCacheEntryDescriptor::nsCompressOutputStreamWrapper"); + + if (0 == count) { + // don't use desc here since mDescriptor might be already nulled out + if (mDescriptor) mDescriptor->mOutputWrapper = nullptr; + + if (desc) nsCacheService::Unlock(); + + mRefCnt = 1; + delete (this); + return 0; + } + + if (desc) nsCacheService::Unlock(); + + return count; +} + +NS_INTERFACE_MAP_BEGIN(nsCacheEntryDescriptor::nsCompressOutputStreamWrapper) + NS_INTERFACE_MAP_ENTRY(nsIOutputStream) + NS_INTERFACE_MAP_ENTRY(nsISupports) +NS_INTERFACE_MAP_END + +NS_IMETHODIMP nsCacheEntryDescriptor::nsCompressOutputStreamWrapper::Write( + const char* buf, uint32_t count, uint32_t* result) { + mozilla::MutexAutoLock lock(mLock); + + int zerr = Z_OK; + nsresult rv = NS_OK; + + if (!mStreamInitialized) { + rv = InitZstream(); + if (NS_FAILED(rv)) { + return rv; + } + } + + if (!mWriteBuffer) { + // Once allocated, this buffer is referenced by the zlib stream and + // cannot be grown. We use 2x(initial write request) to approximate + // a stream buffer size proportional to request buffers. + mWriteBufferLen = std::max(count * 2, (uint32_t)kMinCompressWriteBufLen); + mWriteBuffer = (unsigned char*)moz_xmalloc(mWriteBufferLen); + mZstream.next_out = mWriteBuffer; + mZstream.avail_out = mWriteBufferLen; + } + + // Compress (deflate) the requested buffer. Keep going + // until the entire buffer has been deflated. + mZstream.avail_in = count; + mZstream.next_in = (Bytef*)buf; + while (mZstream.avail_in > 0) { + zerr = deflate(&mZstream, Z_NO_FLUSH); + if (zerr == Z_STREAM_ERROR) { + deflateEnd(&mZstream); + mStreamEnded = true; + mStreamInitialized = false; + return NS_ERROR_FAILURE; + } + // Note: Z_BUF_ERROR is non-fatal and sometimes expected here. + + // If the compression stream output buffer is filled, write + // it out to the underlying stream wrapper. + if (mZstream.avail_out == 0) { + rv = WriteBuffer(); + if (NS_FAILED(rv)) { + deflateEnd(&mZstream); + mStreamEnded = true; + mStreamInitialized = false; + return rv; + } + } + } + *result = count; + mUncompressedCount += *result; + return NS_OK; +} + +NS_IMETHODIMP nsCacheEntryDescriptor::nsCompressOutputStreamWrapper::Close() { + mozilla::MutexAutoLock lock(mLock); + + if (!mDescriptor) return NS_ERROR_NOT_AVAILABLE; + + nsresult retval = NS_OK; + nsresult rv; + int zerr = 0; + + if (mStreamInitialized) { + // complete compression of any data remaining in the zlib stream + do { + zerr = deflate(&mZstream, Z_FINISH); + rv = WriteBuffer(); + if (NS_FAILED(rv)) retval = rv; + } while (zerr == Z_OK && rv == NS_OK); + deflateEnd(&mZstream); + mStreamInitialized = false; + } + // Do not allow to initialize stream after calling Close(). + mStreamEnded = true; + + if (mDescriptor->CacheEntry()) { + nsAutoCString uncompressedLenStr; + rv = mDescriptor->GetMetaDataElement("uncompressed-len", + getter_Copies(uncompressedLenStr)); + if (NS_SUCCEEDED(rv)) { + int32_t oldCount = uncompressedLenStr.ToInteger(&rv); + if (NS_SUCCEEDED(rv)) { + mUncompressedCount += oldCount; + } + } + uncompressedLenStr.Adopt(nullptr); + uncompressedLenStr.AppendInt(mUncompressedCount); + rv = mDescriptor->SetMetaDataElement("uncompressed-len", + uncompressedLenStr.get()); + if (NS_FAILED(rv)) retval = rv; + } + + if (mWriteBuffer) { + free(mWriteBuffer); + mWriteBuffer = nullptr; + mWriteBufferLen = 0; + } + + rv = nsOutputStreamWrapper::Close_Locked(); + if (NS_FAILED(rv)) retval = rv; + + return retval; +} + +nsresult nsCacheEntryDescriptor::nsCompressOutputStreamWrapper::InitZstream() { + if (!mDescriptor) return NS_ERROR_NOT_AVAILABLE; + + if (mStreamEnded) return NS_ERROR_FAILURE; + + // Determine compression level: Aggressive compression + // may impact performance on mobile devices, while a + // lower compression level still provides substantial + // space savings for many text streams. + int32_t compressionLevel = nsCacheService::CacheCompressionLevel(); + + // Initialize zlib deflate stream + mZstream.zalloc = Z_NULL; + mZstream.zfree = Z_NULL; + mZstream.opaque = Z_NULL; + if (deflateInit2(&mZstream, compressionLevel, Z_DEFLATED, MAX_WBITS, 8, + Z_DEFAULT_STRATEGY) != Z_OK) { + return NS_ERROR_FAILURE; + } + mZstream.next_in = Z_NULL; + mZstream.avail_in = 0; + + mStreamInitialized = true; + + return NS_OK; +} + +nsresult nsCacheEntryDescriptor::nsCompressOutputStreamWrapper::WriteBuffer() { + uint32_t bytesToWrite = mWriteBufferLen - mZstream.avail_out; + uint32_t result = 0; + nsresult rv = nsCacheEntryDescriptor::nsOutputStreamWrapper::Write_Locked( + (const char*)mWriteBuffer, bytesToWrite, &result); + mZstream.next_out = mWriteBuffer; + mZstream.avail_out = mWriteBufferLen; + return rv; +} diff --git a/netwerk/cache/nsCacheEntryDescriptor.h b/netwerk/cache/nsCacheEntryDescriptor.h new file mode 100644 index 0000000000..2274150cff --- /dev/null +++ b/netwerk/cache/nsCacheEntryDescriptor.h @@ -0,0 +1,220 @@ +/* -*- 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/. */ + +#ifndef _nsCacheEntryDescriptor_h_ +#define _nsCacheEntryDescriptor_h_ + +#include "nsICacheEntryDescriptor.h" +#include "nsCacheEntry.h" +#include "nsIInputStream.h" +#include "nsIOutputStream.h" +#include "nsCacheService.h" +#include "zlib.h" +#include "mozilla/Mutex.h" + +/****************************************************************************** + * nsCacheEntryDescriptor + *******************************************************************************/ +class nsCacheEntryDescriptor final : public PRCList, + public nsICacheEntryDescriptor { + public: + NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_NSICACHEENTRYDESCRIPTOR + NS_DECL_NSICACHEENTRYINFO + + friend class nsAsyncDoomEvent; + friend class nsCacheService; + + nsCacheEntryDescriptor(nsCacheEntry* entry, nsCacheAccessMode mode); + + /** + * utility method to attempt changing data size of associated entry + */ + nsresult RequestDataSizeChange(int32_t deltaSize); + + /** + * methods callbacks for nsCacheService + */ + nsCacheEntry* CacheEntry(void) { return mCacheEntry; } + bool ClearCacheEntry(void) { + NS_ASSERTION(mInputWrappers.IsEmpty(), "Bad state"); + NS_ASSERTION(!mOutputWrapper, "Bad state"); + + bool doomEntry = false; + bool asyncDoomPending; + { + mozilla::MutexAutoLock lock(mLock); + asyncDoomPending = mAsyncDoomPending; + } + + if (asyncDoomPending && mCacheEntry) { + doomEntry = true; + mDoomedOnClose = true; + } + mCacheEntry = nullptr; + + return doomEntry; + } + + private: + virtual ~nsCacheEntryDescriptor(); + + /************************************************************************* + * input stream wrapper class - + * + * The input stream wrapper references the descriptor, but the descriptor + * doesn't need any references to the stream wrapper. + *************************************************************************/ + class nsInputStreamWrapper : public nsIInputStream { + friend class nsCacheEntryDescriptor; + + private: + nsCacheEntryDescriptor* mDescriptor; + nsCOMPtr<nsIInputStream> mInput; + uint32_t mStartOffset; + bool mInitialized; + mozilla::Mutex mLock; + + public: + NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_NSIINPUTSTREAM + + nsInputStreamWrapper(nsCacheEntryDescriptor* desc, uint32_t off) + : mDescriptor(desc), + mStartOffset(off), + mInitialized(false), + mLock("nsInputStreamWrapper.mLock") { + NS_ADDREF(mDescriptor); + } + + private: + virtual ~nsInputStreamWrapper() { NS_IF_RELEASE(mDescriptor); } + + nsresult LazyInit(); + nsresult EnsureInit(); + nsresult Read_Locked(char* buf, uint32_t count, uint32_t* countRead); + nsresult Close_Locked(); + void CloseInternal(); + }; + + class nsDecompressInputStreamWrapper : public nsInputStreamWrapper { + private: + unsigned char* mReadBuffer; + uint32_t mReadBufferLen; + z_stream mZstream; + bool mStreamInitialized; + bool mStreamEnded; + + public: + NS_DECL_ISUPPORTS_INHERITED + + nsDecompressInputStreamWrapper(nsCacheEntryDescriptor* desc, uint32_t off) + : nsInputStreamWrapper(desc, off), + mReadBuffer(nullptr), + mReadBufferLen(0), + mZstream{}, + mStreamInitialized(false), + mStreamEnded(false) {} + NS_IMETHOD Read(char* buf, uint32_t count, uint32_t* result) override; + NS_IMETHOD Close() override; + + private: + virtual ~nsDecompressInputStreamWrapper() { Close(); } + nsresult InitZstream(); + nsresult EndZstream(); + }; + + /************************************************************************* + * output stream wrapper class - + * + * The output stream wrapper references the descriptor, but the descriptor + * doesn't need any references to the stream wrapper. + *************************************************************************/ + class nsOutputStreamWrapper : public nsIOutputStream { + friend class nsCacheEntryDescriptor; + + protected: + nsCacheEntryDescriptor* mDescriptor; + nsCOMPtr<nsIOutputStream> mOutput; + uint32_t mStartOffset; + bool mInitialized; + mozilla::Mutex mLock; + + public: + NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_NSIOUTPUTSTREAM + + nsOutputStreamWrapper(nsCacheEntryDescriptor* desc, uint32_t off) + : mDescriptor(desc), + mStartOffset(off), + mInitialized(false), + mLock("nsOutputStreamWrapper.mLock") { + NS_ADDREF(mDescriptor); // owning ref + } + + private: + virtual ~nsOutputStreamWrapper() { + Close(); + + NS_ASSERTION(!mOutput, "Bad state"); + NS_ASSERTION(!mDescriptor, "Bad state"); + } + + nsresult LazyInit(); + nsresult EnsureInit(); + nsresult OnWrite(uint32_t count); + nsresult Write_Locked(const char* buf, uint32_t count, uint32_t* result); + nsresult Close_Locked(); + void CloseInternal(); + }; + + class nsCompressOutputStreamWrapper : public nsOutputStreamWrapper { + private: + unsigned char* mWriteBuffer; + uint32_t mWriteBufferLen; + z_stream mZstream; + bool mStreamInitialized; + bool mStreamEnded; + uint32_t mUncompressedCount; + + public: + NS_DECL_ISUPPORTS_INHERITED + + nsCompressOutputStreamWrapper(nsCacheEntryDescriptor* desc, uint32_t off) + : nsOutputStreamWrapper(desc, off), + mWriteBuffer(nullptr), + mWriteBufferLen(0), + mZstream{}, + mStreamInitialized(false), + mStreamEnded(false), + mUncompressedCount(0) {} + NS_IMETHOD Write(const char* buf, uint32_t count, + uint32_t* result) override; + NS_IMETHOD Close() override; + + private: + virtual ~nsCompressOutputStreamWrapper() { Close(); } + nsresult InitZstream(); + nsresult WriteBuffer(); + }; + + private: + /** + * nsCacheEntryDescriptor data members + */ + + nsCOMPtr<nsICacheServiceInternal> mCacheService; + nsCacheEntry* mCacheEntry; // we are a child of the entry + nsCacheAccessMode mAccessGranted; + nsTArray<nsInputStreamWrapper*> mInputWrappers; + nsOutputStreamWrapper* mOutputWrapper; + mozilla::Mutex mLock; + bool mAsyncDoomPending; + bool mDoomedOnClose; + bool mClosingDescriptor; +}; + +#endif // _nsCacheEntryDescriptor_h_ diff --git a/netwerk/cache/nsCacheMetaData.cpp b/netwerk/cache/nsCacheMetaData.cpp new file mode 100644 index 0000000000..386b569ea0 --- /dev/null +++ b/netwerk/cache/nsCacheMetaData.cpp @@ -0,0 +1,151 @@ +/* -*- 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 "nsCacheMetaData.h" +#include "nsICacheEntryDescriptor.h" + +const char* nsCacheMetaData::GetElement(const char* key) { + const char* data = mBuffer; + const char* limit = mBuffer + mMetaSize; + + while (data < limit) { + // Point to the value part + const char* value = data + strlen(data) + 1; + MOZ_ASSERT(value < limit, "Cache Metadata corrupted"); + if (strcmp(data, key) == 0) return value; + + // Skip value part + data = value + strlen(value) + 1; + } + MOZ_ASSERT(data == limit, "Metadata corrupted"); + return nullptr; +} + +nsresult nsCacheMetaData::SetElement(const char* key, const char* value) { + const uint32_t keySize = strlen(key) + 1; + char* pos = (char*)GetElement(key); + + if (!value) { + // No value means remove the key/value pair completely, if existing + if (pos) { + uint32_t oldValueSize = strlen(pos) + 1; + uint32_t offset = pos - mBuffer; + uint32_t remainder = mMetaSize - (offset + oldValueSize); + + memmove(pos - keySize, pos + oldValueSize, remainder); + mMetaSize -= keySize + oldValueSize; + } + return NS_OK; + } + + const uint32_t valueSize = strlen(value) + 1; + uint32_t newSize = mMetaSize + valueSize; + if (pos) { + const uint32_t oldValueSize = strlen(pos) + 1; + const uint32_t offset = pos - mBuffer; + const uint32_t remainder = mMetaSize - (offset + oldValueSize); + + // Update the value in place + newSize -= oldValueSize; + nsresult rv = EnsureBuffer(newSize); + NS_ENSURE_SUCCESS(rv, rv); + + // Move the remainder to the right place + pos = mBuffer + offset; + memmove(pos + valueSize, pos + oldValueSize, remainder); + } else { + // allocate new meta data element + newSize += keySize; + nsresult rv = EnsureBuffer(newSize); + NS_ENSURE_SUCCESS(rv, rv); + + // Add after last element + pos = mBuffer + mMetaSize; + memcpy(pos, key, keySize); + pos += keySize; + } + + // Update value + memcpy(pos, value, valueSize); + mMetaSize = newSize; + + return NS_OK; +} + +nsresult nsCacheMetaData::FlattenMetaData(char* buffer, uint32_t bufSize) { + if (mMetaSize > bufSize) { + NS_ERROR("buffer size too small for meta data."); + return NS_ERROR_OUT_OF_MEMORY; + } + + if (!mBuffer) { + MOZ_ASSERT(mMetaSize == 0); + MOZ_ASSERT(bufSize == 0); + return NS_OK; + } + + memcpy(buffer, mBuffer, mMetaSize); + return NS_OK; +} + +nsresult nsCacheMetaData::UnflattenMetaData(const char* data, uint32_t size) { + if (data && size) { + // Check if the metadata ends with a zero byte. + if (data[size - 1] != '\0') { + NS_ERROR("Cache MetaData is not null terminated"); + return NS_ERROR_ILLEGAL_VALUE; + } + // Check that there are an even number of zero bytes + // to match the pattern { key \0 value \0 } + bool odd = false; + for (uint32_t i = 0; i < size; i++) { + if (data[i] == '\0') odd = !odd; + } + if (odd) { + NS_ERROR("Cache MetaData is malformed"); + return NS_ERROR_ILLEGAL_VALUE; + } + + nsresult rv = EnsureBuffer(size); + NS_ENSURE_SUCCESS(rv, rv); + + memcpy(mBuffer, data, size); + mMetaSize = size; + } + return NS_OK; +} + +nsresult nsCacheMetaData::VisitElements(nsICacheMetaDataVisitor* visitor) { + const char* data = mBuffer; + const char* limit = mBuffer + mMetaSize; + + while (data < limit) { + const char* key = data; + // Skip key part + data += strlen(data) + 1; + MOZ_ASSERT(data < limit, "Metadata corrupted"); + bool keepGoing; + nsresult rv = visitor->VisitMetaDataElement(key, data, &keepGoing); + if (NS_FAILED(rv) || !keepGoing) return NS_OK; + + // Skip value part + data += strlen(data) + 1; + } + MOZ_ASSERT(data == limit, "Metadata corrupted"); + return NS_OK; +} + +nsresult nsCacheMetaData::EnsureBuffer(uint32_t bufSize) { + if (mBufferSize < bufSize) { + char* buf = (char*)realloc(mBuffer, bufSize); + if (!buf) { + return NS_ERROR_OUT_OF_MEMORY; + } + mBuffer = buf; + mBufferSize = bufSize; + } + return NS_OK; +} diff --git a/netwerk/cache/nsCacheMetaData.h b/netwerk/cache/nsCacheMetaData.h new file mode 100644 index 0000000000..4cf84ad5fa --- /dev/null +++ b/netwerk/cache/nsCacheMetaData.h @@ -0,0 +1,45 @@ +/* -*- 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/. */ + +#ifndef _nsCacheMetaData_h_ +#define _nsCacheMetaData_h_ + +#include "nspr.h" +#include "nscore.h" + +class nsICacheMetaDataVisitor; + +class nsCacheMetaData { + public: + nsCacheMetaData() : mBuffer(nullptr), mBufferSize(0), mMetaSize(0) {} + + ~nsCacheMetaData() { + mBufferSize = mMetaSize = 0; + free(mBuffer); + mBuffer = nullptr; + } + + const char* GetElement(const char* key); + + nsresult SetElement(const char* key, const char* value); + + uint32_t Size(void) { return mMetaSize; } + + nsresult FlattenMetaData(char* buffer, uint32_t bufSize); + + nsresult UnflattenMetaData(const char* buffer, uint32_t bufSize); + + nsresult VisitElements(nsICacheMetaDataVisitor* visitor); + + private: + nsresult EnsureBuffer(uint32_t size); + + char* mBuffer; + uint32_t mBufferSize; + uint32_t mMetaSize; +}; + +#endif // _nsCacheMetaData_h diff --git a/netwerk/cache/nsCacheRequest.h b/netwerk/cache/nsCacheRequest.h new file mode 100644 index 0000000000..1d5dcd3106 --- /dev/null +++ b/netwerk/cache/nsCacheRequest.h @@ -0,0 +1,146 @@ +/* -*- 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/. */ + +#ifndef _nsCacheRequest_h_ +#define _nsCacheRequest_h_ + +#include "nspr.h" +#include "mozilla/CondVar.h" +#include "mozilla/Mutex.h" +#include "nsCOMPtr.h" +#include "nsICache.h" +#include "nsICacheListener.h" +#include "nsCacheSession.h" +#include "nsCacheService.h" + +class nsCacheRequest : public PRCList { + typedef mozilla::CondVar CondVar; + typedef mozilla::MutexAutoLock MutexAutoLock; + typedef mozilla::Mutex Mutex; + + private: + friend class nsCacheService; + friend class nsCacheEntry; + friend class nsProcessRequestEvent; + + nsCacheRequest(const nsACString& key, nsICacheListener* listener, + nsCacheAccessMode accessRequested, bool blockingMode, + nsCacheSession* session) + : mKey(key), + mInfo(0), + mListener(listener), + mLock("nsCacheRequest.mLock"), + mCondVar(mLock, "nsCacheRequest.mCondVar"), + mProfileDir(session->ProfileDir()) { + MOZ_COUNT_CTOR(nsCacheRequest); + PR_INIT_CLIST(this); + SetAccessRequested(accessRequested); + SetStoragePolicy(session->StoragePolicy()); + if (session->IsStreamBased()) MarkStreamBased(); + if (session->WillDoomEntriesIfExpired()) MarkDoomEntriesIfExpired(); + if (session->IsPrivate()) MarkPrivate(); + if (blockingMode == nsICache::BLOCKING) MarkBlockingMode(); + MarkWaitingForValidation(); + NS_IF_ADDREF(mListener); + } + + ~nsCacheRequest() { + MOZ_COUNT_DTOR(nsCacheRequest); + NS_ASSERTION(PR_CLIST_IS_EMPTY(this), "request still on a list"); + + if (mListener) + nsCacheService::ReleaseObject_Locked(mListener, mEventTarget); + } + + /** + * Simple Accessors + */ + enum CacheRequestInfo { + eStoragePolicyMask = 0x000000FF, + eStreamBasedMask = 0x00000100, + ePrivateMask = 0x00000200, + eDoomEntriesIfExpiredMask = 0x00001000, + eBlockingModeMask = 0x00010000, + eWaitingForValidationMask = 0x00100000, + eAccessRequestedMask = 0xFF000000 + }; + + void SetAccessRequested(nsCacheAccessMode mode) { + NS_ASSERTION(mode <= 0xFF, "too many bits in nsCacheAccessMode"); + mInfo &= ~eAccessRequestedMask; + mInfo |= mode << 24; + } + + nsCacheAccessMode AccessRequested() { + return (nsCacheAccessMode)((mInfo >> 24) & 0xFF); + } + + void MarkStreamBased() { mInfo |= eStreamBasedMask; } + bool IsStreamBased() { return (mInfo & eStreamBasedMask) != 0; } + + void MarkDoomEntriesIfExpired() { mInfo |= eDoomEntriesIfExpiredMask; } + bool WillDoomEntriesIfExpired() { + return (0 != (mInfo & eDoomEntriesIfExpiredMask)); + } + + void MarkBlockingMode() { mInfo |= eBlockingModeMask; } + bool IsBlocking() { return (0 != (mInfo & eBlockingModeMask)); } + bool IsNonBlocking() { return !(mInfo & eBlockingModeMask); } + + void SetStoragePolicy(nsCacheStoragePolicy policy) { + NS_ASSERTION(policy <= 0xFF, "too many bits in nsCacheStoragePolicy"); + mInfo &= ~eStoragePolicyMask; // clear storage policy bits + mInfo |= policy; // or in new bits + } + + nsCacheStoragePolicy StoragePolicy() { + return (nsCacheStoragePolicy)(mInfo & eStoragePolicyMask); + } + + void MarkPrivate() { mInfo |= ePrivateMask; } + void MarkPublic() { mInfo &= ~ePrivateMask; } + bool IsPrivate() { return (mInfo & ePrivateMask) != 0; } + + void MarkWaitingForValidation() { mInfo |= eWaitingForValidationMask; } + void DoneWaitingForValidation() { mInfo &= ~eWaitingForValidationMask; } + bool WaitingForValidation() { + return (mInfo & eWaitingForValidationMask) != 0; + } + + nsresult WaitForValidation(void) { + if (!WaitingForValidation()) { // flag already cleared + MarkWaitingForValidation(); // set up for next time + return NS_OK; // early exit; + } + { + MutexAutoLock lock(mLock); + while (WaitingForValidation()) { + mCondVar.Wait(); + } + MarkWaitingForValidation(); // set up for next time + } + return NS_OK; + } + + void WakeUp(void) { + DoneWaitingForValidation(); + MutexAutoLock lock(mLock); + mCondVar.Notify(); + } + + /** + * Data members + */ + nsCString mKey; + uint32_t mInfo; + nsICacheListener* mListener; // strong ref + nsCOMPtr<nsIEventTarget> mEventTarget; + Mutex mLock; + CondVar mCondVar; + nsCOMPtr<nsIFile> mProfileDir; +}; + +#endif // _nsCacheRequest_h_ diff --git a/netwerk/cache/nsCacheService.cpp b/netwerk/cache/nsCacheService.cpp new file mode 100644 index 0000000000..f7cb31d010 --- /dev/null +++ b/netwerk/cache/nsCacheService.cpp @@ -0,0 +1,1910 @@ +/* -*- 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 "nsCacheService.h" + +#include "mozilla/ArrayUtils.h" +#include "mozilla/Attributes.h" +#include "mozilla/Assertions.h" +#include "mozilla/DebugOnly.h" +#include "mozilla/FileUtils.h" + +#include "nsCache.h" +#include "nsCacheRequest.h" +#include "nsCacheEntry.h" +#include "nsCacheEntryDescriptor.h" +#include "nsCacheDevice.h" +#include "nsICacheVisitor.h" +#include "nsDiskCacheDeviceSQL.h" +#include "nsCacheUtils.h" +#include "../cache2/CacheObserver.h" +#include "nsIObserverService.h" +#include "nsIPrefBranch.h" +#include "nsIFile.h" +#include "nsIOService.h" +#include "nsDirectoryServiceDefs.h" +#include "nsAppDirectoryServiceDefs.h" +#include "nsThreadUtils.h" +#include "nsProxyRelease.h" +#include "nsDeleteDir.h" +#include "nsNetCID.h" +#include <math.h> // for log() +#include "mozilla/Services.h" +#include "mozilla/StaticPrefs_browser.h" + +#include "mozilla/net/NeckoCommon.h" +#include <algorithm> + +using namespace mozilla; +using namespace mozilla::net; + +/****************************************************************************** + * nsCacheProfilePrefObserver + *****************************************************************************/ +#define OFFLINE_CACHE_DIR_PREF "browser.cache.offline.parent_directory" +#define OFFLINE_CACHE_CAPACITY_PREF "browser.cache.offline.capacity" +#define OFFLINE_CACHE_CAPACITY 512000 + +#define CACHE_COMPRESSION_LEVEL 1 + +static const char* observerList[] = { + "profile-before-change", "profile-do-change", + NS_XPCOM_SHUTDOWN_OBSERVER_ID, "last-pb-context-exited", + "suspend_process_notification", "resume_process_notification"}; + +class nsCacheProfilePrefObserver : public nsIObserver { + virtual ~nsCacheProfilePrefObserver() = default; + + public: + NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_NSIOBSERVER + + nsCacheProfilePrefObserver() + : mHaveProfile(false), + mOfflineCacheEnabled(false), + mOfflineStorageCacheEnabled(false), + mOfflineCacheCapacity(0), + mCacheCompressionLevel(CACHE_COMPRESSION_LEVEL), + mSanitizeOnShutdown(false), + mClearCacheOnShutdown(false) {} + + nsresult Install(); + void Remove(); + nsresult ReadPrefs(nsIPrefBranch* branch); + + nsIFile* DiskCacheParentDirectory() { return mDiskCacheParentDirectory; } + + bool OfflineCacheEnabled(); + int32_t OfflineCacheCapacity() { return mOfflineCacheCapacity; } + nsIFile* OfflineCacheParentDirectory() { + return mOfflineCacheParentDirectory; + } + + int32_t CacheCompressionLevel(); + + bool SanitizeAtShutdown() { + return mSanitizeOnShutdown && mClearCacheOnShutdown; + } + + private: + bool mHaveProfile; + + nsCOMPtr<nsIFile> mDiskCacheParentDirectory; + + bool mOfflineCacheEnabled; + bool mOfflineStorageCacheEnabled; + int32_t mOfflineCacheCapacity; // in kilobytes + nsCOMPtr<nsIFile> mOfflineCacheParentDirectory; + + int32_t mCacheCompressionLevel; + + bool mSanitizeOnShutdown; + bool mClearCacheOnShutdown; +}; + +NS_IMPL_ISUPPORTS(nsCacheProfilePrefObserver, nsIObserver) + +class nsBlockOnCacheThreadEvent : public Runnable { + public: + nsBlockOnCacheThreadEvent() + : mozilla::Runnable("nsBlockOnCacheThreadEvent") {} + NS_IMETHOD Run() override { + nsCacheServiceAutoLock autoLock(LOCK_TELEM(NSBLOCKONCACHETHREADEVENT_RUN)); + CACHE_LOG_DEBUG(("nsBlockOnCacheThreadEvent [%p]\n", this)); + nsCacheService::gService->mNotified = true; + nsCacheService::gService->mCondVar.Notify(); + return NS_OK; + } +}; + +nsresult nsCacheProfilePrefObserver::Install() { + // install profile-change observer + nsCOMPtr<nsIObserverService> observerService = + mozilla::services::GetObserverService(); + if (!observerService) return NS_ERROR_FAILURE; + + nsresult rv, rv2 = NS_OK; + for (auto& observer : observerList) { + rv = observerService->AddObserver(this, observer, false); + if (NS_FAILED(rv)) rv2 = rv; + } + + // install preferences observer + nsCOMPtr<nsIPrefBranch> branch = do_GetService(NS_PREFSERVICE_CONTRACTID); + if (!branch) return NS_ERROR_FAILURE; + + // Determine if we have a profile already + // Install() is called *after* the profile-after-change notification + // when there is only a single profile, or it is specified on the + // commandline at startup. + // In that case, we detect the presence of a profile by the existence + // of the NS_APP_USER_PROFILE_50_DIR directory. + + nsCOMPtr<nsIFile> directory; + rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, + getter_AddRefs(directory)); + if (NS_SUCCEEDED(rv)) mHaveProfile = true; + + rv = ReadPrefs(branch); + NS_ENSURE_SUCCESS(rv, rv); + + return rv2; +} + +void nsCacheProfilePrefObserver::Remove() { + // remove Observer Service observers + nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService(); + if (obs) { + for (auto& observer : observerList) { + obs->RemoveObserver(this, observer); + } + } +} + +NS_IMETHODIMP +nsCacheProfilePrefObserver::Observe(nsISupports* subject, const char* topic, + const char16_t* data_unicode) { + NS_ConvertUTF16toUTF8 data(data_unicode); + CACHE_LOG_INFO(("Observe [topic=%s data=%s]\n", topic, data.get())); + + if (!nsCacheService::IsInitialized()) { + if (!strcmp("resume_process_notification", topic)) { + // A suspended process has a closed cache, so re-open it here. + nsCacheService::GlobalInstance()->Init(); + } + return NS_OK; + } + + if (!strcmp(NS_XPCOM_SHUTDOWN_OBSERVER_ID, topic)) { + // xpcom going away, shutdown cache service + nsCacheService::GlobalInstance()->Shutdown(); + } else if (!strcmp("profile-before-change", topic)) { + // profile before change + mHaveProfile = false; + + // XXX shutdown devices + nsCacheService::OnProfileShutdown(); + } else if (!strcmp("suspend_process_notification", topic)) { + // A suspended process may never return, so shutdown the cache to reduce + // cache corruption. + nsCacheService::GlobalInstance()->Shutdown(); + } else if (!strcmp("profile-do-change", topic)) { + // profile after change + mHaveProfile = true; + nsCOMPtr<nsIPrefBranch> branch = do_GetService(NS_PREFSERVICE_CONTRACTID); + if (!branch) { + return NS_ERROR_FAILURE; + } + (void)ReadPrefs(branch); + nsCacheService::OnProfileChanged(); + + } else if (!strcmp("last-pb-context-exited", topic)) { + nsCacheService::LeavePrivateBrowsing(); + } + + return NS_OK; +} + +static already_AddRefed<nsIFile> GetCacheDirectory(const char* aSubdir, + bool aAllowProcDirCache) { + nsCOMPtr<nsIFile> directory; + + // try to get the disk cache parent directory + Unused << NS_GetSpecialDirectory(NS_APP_CACHE_PARENT_DIR, + getter_AddRefs(directory)); + if (!directory) { + // try to get the profile directory (there may not be a profile yet) + nsCOMPtr<nsIFile> profDir; + NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(profDir)); + NS_GetSpecialDirectory(NS_APP_USER_PROFILE_LOCAL_50_DIR, + getter_AddRefs(directory)); + if (!directory) + directory = profDir; + else if (profDir) { + nsCacheService::MoveOrRemoveDiskCache(profDir, directory, aSubdir); + } + } + if (!directory && aAllowProcDirCache) { + Unused << NS_GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR, + getter_AddRefs(directory)); + } + return directory.forget(); +} + +nsresult nsCacheProfilePrefObserver::ReadPrefs(nsIPrefBranch* branch) { + if (!mDiskCacheParentDirectory) { + // use file cache in build tree only if asked, to avoid cache dir litter + bool allowProcDirCache = PR_GetEnv("NECKO_DEV_ENABLE_DISK_CACHE"); + mDiskCacheParentDirectory = GetCacheDirectory("Cache", allowProcDirCache); + } + + // read offline cache device prefs + mOfflineCacheEnabled = StaticPrefs::browser_cache_offline_enable(); + mOfflineStorageCacheEnabled = + StaticPrefs::browser_cache_offline_storage_enable(); + + mOfflineCacheCapacity = OFFLINE_CACHE_CAPACITY; + (void)branch->GetIntPref(OFFLINE_CACHE_CAPACITY_PREF, &mOfflineCacheCapacity); + mOfflineCacheCapacity = std::max(0, mOfflineCacheCapacity); + + (void)branch->GetComplexValue(OFFLINE_CACHE_DIR_PREF, // ignore error + NS_GET_IID(nsIFile), + getter_AddRefs(mOfflineCacheParentDirectory)); + + if (!mOfflineCacheParentDirectory) { +#ifdef DEBUG + bool allowProcDirCache = true; +#else + bool allowProcDirCache = false; +#endif + mOfflineCacheParentDirectory = + GetCacheDirectory("OfflineCache", allowProcDirCache); + } + + if (!mDiskCacheParentDirectory || !mOfflineCacheParentDirectory) { + return NS_ERROR_FAILURE; + } + + if (!mOfflineStorageCacheEnabled) { + // Dispatch cleanup task + nsCOMPtr<nsIRunnable> runnable = + NS_NewRunnableFunction("Delete OfflineCache", []() { + nsCOMPtr<nsIFile> dir; + nsCacheService::GetAppCacheDirectory(getter_AddRefs(dir)); + bool exists = false; + if (dir && NS_SUCCEEDED(dir->Exists(&exists)) && exists) { + // Delay delete by 1 minute to avoid IO thrash on startup. + CACHE_LOG_INFO( + ("Queuing Delete of AppCacheDirectory in 60 seconds")); + nsDeleteDir::DeleteDir(dir, false, 60000); + } + }); + Unused << nsCacheService::DispatchToCacheIOThread(runnable); + } + + return NS_OK; +} + +nsresult nsCacheService::DispatchToCacheIOThread(nsIRunnable* event) { + if (!gService || !gService->mCacheIOThread) return NS_ERROR_NOT_AVAILABLE; + return gService->mCacheIOThread->Dispatch(event, NS_DISPATCH_NORMAL); +} + +nsresult nsCacheService::SyncWithCacheIOThread() { + if (!gService || !gService->mCacheIOThread) return NS_ERROR_NOT_AVAILABLE; + gService->mLock.AssertCurrentThreadOwns(); + + nsCOMPtr<nsIRunnable> event = new nsBlockOnCacheThreadEvent(); + + // dispatch event - it will notify the monitor when it's done + nsresult rv = gService->mCacheIOThread->Dispatch(event, NS_DISPATCH_NORMAL); + if (NS_FAILED(rv)) { + NS_WARNING("Failed dispatching block-event"); + return NS_ERROR_UNEXPECTED; + } + + // wait until notified, then return + gService->mNotified = false; + while (!gService->mNotified) { + gService->mCondVar.Wait(); + } + + return NS_OK; +} + +bool nsCacheProfilePrefObserver::OfflineCacheEnabled() { + if ((mOfflineCacheCapacity == 0) || (!mOfflineCacheParentDirectory)) + return false; + + return mOfflineCacheEnabled && mOfflineStorageCacheEnabled; +} + +int32_t nsCacheProfilePrefObserver::CacheCompressionLevel() { + return mCacheCompressionLevel; +} + +/****************************************************************************** + * nsProcessRequestEvent + *****************************************************************************/ + +class nsProcessRequestEvent : public Runnable { + public: + explicit nsProcessRequestEvent(nsCacheRequest* aRequest) + : mozilla::Runnable("nsProcessRequestEvent") { + mRequest = aRequest; + } + + NS_IMETHOD Run() override { + nsresult rv; + + NS_ASSERTION(mRequest->mListener, + "Sync OpenCacheEntry() posted to background thread!"); + + nsCacheServiceAutoLock lock(LOCK_TELEM(NSPROCESSREQUESTEVENT_RUN)); + rv = nsCacheService::gService->ProcessRequest(mRequest, false, nullptr); + + // Don't delete the request if it was queued + if (!(mRequest->IsBlocking() && rv == NS_ERROR_CACHE_WAIT_FOR_VALIDATION)) + delete mRequest; + + return NS_OK; + } + + protected: + virtual ~nsProcessRequestEvent() = default; + + private: + nsCacheRequest* mRequest; +}; + +/****************************************************************************** + * nsDoomEvent + *****************************************************************************/ + +class nsDoomEvent : public Runnable { + public: + nsDoomEvent(nsCacheSession* session, const nsACString& key, + nsICacheListener* listener) + : mozilla::Runnable("nsDoomEvent") { + mKey = *session->ClientID(); + mKey.Append(':'); + mKey.Append(key); + mStoragePolicy = session->StoragePolicy(); + mListener = listener; + mEventTarget = GetCurrentEventTarget(); + // We addref the listener here and release it in nsNotifyDoomListener + // on the callers thread. If posting of nsNotifyDoomListener event fails + // we leak the listener which is better than releasing it on a wrong + // thread. + NS_IF_ADDREF(mListener); + } + + NS_IMETHOD Run() override { + nsCacheServiceAutoLock lock; + + bool foundActive = true; + nsresult status = NS_ERROR_NOT_AVAILABLE; + nsCacheEntry* entry; + entry = nsCacheService::gService->mActiveEntries.GetEntry(&mKey); + if (!entry) { + bool collision = false; + foundActive = false; + entry = nsCacheService::gService->SearchCacheDevices( + &mKey, mStoragePolicy, &collision); + } + + if (entry) { + status = NS_OK; + nsCacheService::gService->DoomEntry_Internal(entry, foundActive); + } + + if (mListener) { + mEventTarget->Dispatch(new nsNotifyDoomListener(mListener, status), + NS_DISPATCH_NORMAL); + // posted event will release the reference on the correct thread + mListener = nullptr; + } + + return NS_OK; + } + + private: + nsCString mKey; + nsCacheStoragePolicy mStoragePolicy; + nsICacheListener* mListener; + nsCOMPtr<nsIEventTarget> mEventTarget; +}; + +/****************************************************************************** + * nsCacheService + *****************************************************************************/ +nsCacheService* nsCacheService::gService = nullptr; + +NS_IMPL_ISUPPORTS(nsCacheService, nsICacheService, nsICacheServiceInternal) + +nsCacheService::nsCacheService() + : mObserver(nullptr), + mLock("nsCacheService.mLock"), + mCondVar(mLock, "nsCacheService.mCondVar"), + mNotified(false), + mTimeStampLock("nsCacheService.mTimeStampLock"), + mInitialized(false), + mClearingEntries(false), + mEnableOfflineDevice(false), + mOfflineDevice(nullptr), + mDoomedEntries{}, + mTotalEntries(0), + mCacheHits(0), + mCacheMisses(0), + mMaxKeyLength(0), + mMaxDataSize(0), + mMaxMetaSize(0), + mDeactivateFailures(0), + mDeactivatedUnboundEntries(0) { + NS_ASSERTION(gService == nullptr, "multiple nsCacheService instances!"); + gService = this; + + // create list of cache devices + PR_INIT_CLIST(&mDoomedEntries); +} + +nsCacheService::~nsCacheService() { + if (mInitialized) // Shutdown hasn't been called yet. + (void)Shutdown(); + + if (mObserver) { + mObserver->Remove(); + NS_RELEASE(mObserver); + } + + gService = nullptr; +} + +nsresult nsCacheService::Init() { + // Thie method must be called on the main thread because mCacheIOThread must + // only be modified on the main thread. + if (!NS_IsMainThread()) { + NS_ERROR("nsCacheService::Init called off the main thread"); + return NS_ERROR_NOT_SAME_THREAD; + } + + NS_ASSERTION(!mInitialized, "nsCacheService already initialized."); + if (mInitialized) return NS_ERROR_ALREADY_INITIALIZED; + + if (mozilla::net::IsNeckoChild()) { + return NS_ERROR_UNEXPECTED; + } + + nsresult rv; + + mStorageService = do_GetService("@mozilla.org/storage/service;1", &rv); + NS_ENSURE_SUCCESS(rv, rv); + + rv = NS_NewNamedThread("Cache I/O", getter_AddRefs(mCacheIOThread)); + if (NS_FAILED(rv)) { + NS_WARNING("Can't create cache IO thread"); + } + + rv = nsDeleteDir::Init(); + if (NS_FAILED(rv)) { + NS_WARNING("Can't initialize nsDeleteDir"); + } + + // initialize hashtable for active cache entries + mActiveEntries.Init(); + + // create profile/preference observer + if (!mObserver) { + mObserver = new nsCacheProfilePrefObserver(); + NS_ADDREF(mObserver); + mObserver->Install(); + } + + mEnableOfflineDevice = mObserver->OfflineCacheEnabled(); + + mInitialized = true; + return NS_OK; +} + +void nsCacheService::Shutdown() { + // This method must be called on the main thread because mCacheIOThread must + // only be modified on the main thread. + if (!NS_IsMainThread()) { + MOZ_CRASH("nsCacheService::Shutdown called off the main thread"); + } + + nsCOMPtr<nsIThread> cacheIOThread; + Telemetry::AutoTimer<Telemetry::NETWORK_DISK_CACHE_SHUTDOWN> totalTimer; + + bool shouldSanitize = false; + nsCOMPtr<nsIFile> parentDir; + + { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHESERVICE_SHUTDOWN)); + NS_ASSERTION( + mInitialized, + "can't shutdown nsCacheService unless it has been initialized."); + if (!mInitialized) return; + + mClearingEntries = true; + DoomActiveEntries(nullptr); + } + + CloseAllStreams(); + + { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHESERVICE_SHUTDOWN)); + NS_ASSERTION(mInitialized, "Bad state"); + + mInitialized = false; + + // Clear entries + ClearDoomList(); + + // Make sure to wait for any pending cache-operations before + // proceeding with destructive actions (bug #620660) + (void)SyncWithCacheIOThread(); + mActiveEntries.Shutdown(); + + // obtain the disk cache directory in case we need to sanitize it + parentDir = mObserver->DiskCacheParentDirectory(); + shouldSanitize = mObserver->SanitizeAtShutdown(); + + if (mOfflineDevice) mOfflineDevice->Shutdown(); + + NS_IF_RELEASE(mOfflineDevice); + + for (auto iter = mCustomOfflineDevices.Iter(); !iter.Done(); iter.Next()) { + iter.Data()->Shutdown(); + iter.Remove(); + } + + LogCacheStatistics(); + + mClearingEntries = false; + mCacheIOThread.swap(cacheIOThread); + } + + if (cacheIOThread) nsShutdownThread::BlockingShutdown(cacheIOThread); + + if (shouldSanitize) { + nsresult rv = parentDir->AppendNative("Cache"_ns); + if (NS_SUCCEEDED(rv)) { + bool exists; + if (NS_SUCCEEDED(parentDir->Exists(&exists)) && exists) + nsDeleteDir::DeleteDir(parentDir, false); + } + Telemetry::AutoTimer<Telemetry::NETWORK_DISK_CACHE_SHUTDOWN_CLEAR_PRIVATE> + timer; + nsDeleteDir::Shutdown(shouldSanitize); + } else { + Telemetry::AutoTimer<Telemetry::NETWORK_DISK_CACHE_DELETEDIR_SHUTDOWN> + timer; + nsDeleteDir::Shutdown(shouldSanitize); + } +} + +nsresult nsCacheService::Create(nsISupports* aOuter, const nsIID& aIID, + void** aResult) { + nsresult rv; + + if (aOuter != nullptr) return NS_ERROR_NO_AGGREGATION; + + RefPtr<nsCacheService> cacheService = new nsCacheService(); + rv = cacheService->Init(); + if (NS_SUCCEEDED(rv)) { + rv = cacheService->QueryInterface(aIID, aResult); + } + return rv; +} + +NS_IMETHODIMP +nsCacheService::CreateSession(const char* clientID, + nsCacheStoragePolicy storagePolicy, + bool streamBased, nsICacheSession** result) { + *result = nullptr; + + return NS_ERROR_NOT_IMPLEMENTED; +} + +nsresult nsCacheService::CreateSessionInternal( + const char* clientID, nsCacheStoragePolicy storagePolicy, bool streamBased, + nsICacheSession** result) { + RefPtr<nsCacheSession> session = + new nsCacheSession(clientID, storagePolicy, streamBased); + session.forget(result); + + return NS_OK; +} + +nsresult nsCacheService::EvictEntriesForSession(nsCacheSession* session) { + NS_ASSERTION(gService, "nsCacheService::gService is null."); + return gService->EvictEntriesForClient(session->ClientID()->get(), + session->StoragePolicy()); +} + +namespace { + +class EvictionNotifierRunnable : public Runnable { + public: + explicit EvictionNotifierRunnable(nsISupports* aSubject) + : mozilla::Runnable("EvictionNotifierRunnable"), mSubject(aSubject) {} + + NS_DECL_NSIRUNNABLE + + private: + nsCOMPtr<nsISupports> mSubject; +}; + +NS_IMETHODIMP +EvictionNotifierRunnable::Run() { + nsCOMPtr<nsIObserverService> obsSvc = mozilla::services::GetObserverService(); + if (obsSvc) { + obsSvc->NotifyObservers(mSubject, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID, + nullptr); + } + return NS_OK; +} + +} // namespace + +nsresult nsCacheService::EvictEntriesForClient( + const char* clientID, nsCacheStoragePolicy storagePolicy) { + RefPtr<EvictionNotifierRunnable> r = + new EvictionNotifierRunnable(NS_ISUPPORTS_CAST(nsICacheService*, this)); + NS_DispatchToMainThread(r); + + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHESERVICE_EVICTENTRIESFORCLIENT)); + nsresult res = NS_OK; + + // Only clear the offline cache if it has been specifically asked for. + if (storagePolicy == nsICache::STORE_OFFLINE) { + if (mEnableOfflineDevice) { + nsresult rv = NS_OK; + if (!mOfflineDevice) rv = CreateOfflineDevice(); + if (mOfflineDevice) rv = mOfflineDevice->EvictEntries(clientID); + if (NS_FAILED(rv)) res = rv; + } + } + + return res; +} + +nsresult nsCacheService::IsStorageEnabledForPolicy( + nsCacheStoragePolicy storagePolicy, bool* result) { + if (gService == nullptr) return NS_ERROR_NOT_AVAILABLE; + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHESERVICE_ISSTORAGEENABLEDFORPOLICY)); + + *result = nsCacheService::IsStorageEnabledForPolicy_Locked(storagePolicy); + return NS_OK; +} + +nsresult nsCacheService::DoomEntry(nsCacheSession* session, + const nsACString& key, + nsICacheListener* listener) { + CACHE_LOG_DEBUG(("Dooming entry for session %p, key %s\n", session, + PromiseFlatCString(key).get())); + if (!gService || !gService->mInitialized) return NS_ERROR_NOT_INITIALIZED; + + return DispatchToCacheIOThread(new nsDoomEvent(session, key, listener)); +} + +bool nsCacheService::IsStorageEnabledForPolicy_Locked( + nsCacheStoragePolicy storagePolicy) { + if (gService->mEnableOfflineDevice && + storagePolicy == nsICache::STORE_OFFLINE) { + return true; + } + + return false; +} + +NS_IMETHODIMP nsCacheService::VisitEntries(nsICacheVisitor* visitor) { + return NS_ERROR_NOT_IMPLEMENTED; +} + +nsresult nsCacheService::VisitEntriesInternal(nsICacheVisitor* visitor) { + NS_ENSURE_ARG_POINTER(visitor); + + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHESERVICE_VISITENTRIES)); + + if (!mEnableOfflineDevice) return NS_ERROR_NOT_AVAILABLE; + + // XXX record the fact that a visitation is in progress, + // XXX i.e. keep list of visitors in progress. + + nsresult rv = NS_OK; + + if (mEnableOfflineDevice) { + if (!mOfflineDevice) { + rv = CreateOfflineDevice(); + if (NS_FAILED(rv)) return rv; + } + rv = mOfflineDevice->Visit(visitor); + if (NS_FAILED(rv)) return rv; + } + + // XXX notify any shutdown process that visitation is complete for THIS + // visitor. + // XXX keep queue of visitors + + return NS_OK; +} + +void nsCacheService::FireClearNetworkCacheStoredAnywhereNotification() { + MOZ_ASSERT(NS_IsMainThread()); + nsCOMPtr<nsIObserverService> obsvc = mozilla::services::GetObserverService(); + if (obsvc) { + obsvc->NotifyObservers(nullptr, "network-clear-cache-stored-anywhere", + nullptr); + } +} + +NS_IMETHODIMP nsCacheService::EvictEntries(nsCacheStoragePolicy storagePolicy) { + return NS_ERROR_NOT_IMPLEMENTED; +} + +nsresult nsCacheService::EvictEntriesInternal( + nsCacheStoragePolicy storagePolicy) { + if (storagePolicy == nsICache::STORE_ANYWHERE) { + // if not called on main thread, dispatch the notification to the main + // thread to notify observers + if (!NS_IsMainThread()) { + nsCOMPtr<nsIRunnable> event = NewRunnableMethod( + "nsCacheService::FireClearNetworkCacheStoredAnywhereNotification", + this, + &nsCacheService::FireClearNetworkCacheStoredAnywhereNotification); + NS_DispatchToMainThread(event); + } else { + // else you're already on main thread - notify observers + FireClearNetworkCacheStoredAnywhereNotification(); + } + } + return EvictEntriesForClient(nullptr, storagePolicy); +} + +NS_IMETHODIMP nsCacheService::GetCacheIOTarget( + nsIEventTarget** aCacheIOTarget) { + NS_ENSURE_ARG_POINTER(aCacheIOTarget); + + // Because mCacheIOThread can only be changed on the main thread, it can be + // read from the main thread without the lock. This is useful to prevent + // blocking the main thread on other cache operations. + if (!NS_IsMainThread()) { + Lock(LOCK_TELEM(NSCACHESERVICE_GETCACHEIOTARGET)); + } + + nsresult rv; + if (mCacheIOThread) { + *aCacheIOTarget = do_AddRef(mCacheIOThread).take(); + rv = NS_OK; + } else { + *aCacheIOTarget = nullptr; + rv = NS_ERROR_NOT_AVAILABLE; + } + + if (!NS_IsMainThread()) { + Unlock(); + } + + return rv; +} + +NS_IMETHODIMP nsCacheService::GetLockHeldTime(double* aLockHeldTime) { + MutexAutoLock lock(mTimeStampLock); + + if (mLockAcquiredTimeStamp.IsNull()) { + *aLockHeldTime = 0.0; + } else { + *aLockHeldTime = + (TimeStamp::Now() - mLockAcquiredTimeStamp).ToMilliseconds(); + } + + return NS_OK; +} + +/** + * Internal Methods + */ +nsresult nsCacheService::GetOfflineDevice(nsOfflineCacheDevice** aDevice) { + if (!mOfflineDevice) { + nsresult rv = CreateOfflineDevice(); + if (NS_FAILED(rv)) { + return rv; + } + } + + *aDevice = do_AddRef(mOfflineDevice).take(); + return NS_OK; +} + +nsresult nsCacheService::GetCustomOfflineDevice( + nsIFile* aProfileDir, int32_t aQuota, nsOfflineCacheDevice** aDevice) { + nsresult rv; + + nsAutoString profilePath; + rv = aProfileDir->GetPath(profilePath); + NS_ENSURE_SUCCESS(rv, rv); + + if (!mCustomOfflineDevices.Get(profilePath, aDevice)) { + rv = CreateCustomOfflineDevice(aProfileDir, aQuota, aDevice); + if (NS_FAILED(rv)) { + return rv; + } + + (*aDevice)->SetAutoShutdown(); + mCustomOfflineDevices.Put(profilePath, RefPtr{*aDevice}); + } + + return NS_OK; +} + +nsresult nsCacheService::CreateOfflineDevice() { + CACHE_LOG_INFO(("Creating default offline device")); + + if (mOfflineDevice) return NS_OK; + if (!nsCacheService::IsInitialized()) { + return NS_ERROR_NOT_AVAILABLE; + } + + return CreateCustomOfflineDevice(mObserver->OfflineCacheParentDirectory(), + mObserver->OfflineCacheCapacity(), + &mOfflineDevice); +} + +nsresult nsCacheService::CreateCustomOfflineDevice( + nsIFile* aProfileDir, int32_t aQuota, nsOfflineCacheDevice** aDevice) { + NS_ENSURE_ARG(aProfileDir); + + if (MOZ_LOG_TEST(gCacheLog, LogLevel::Info)) { + CACHE_LOG_INFO(("Creating custom offline device, %s, %d", + aProfileDir->HumanReadablePath().get(), aQuota)); + } + + if (!mInitialized) { + NS_WARNING("nsCacheService not initialized"); + return NS_ERROR_NOT_AVAILABLE; + } + + if (!mEnableOfflineDevice) return NS_ERROR_NOT_AVAILABLE; + + RefPtr<nsOfflineCacheDevice> device = new nsOfflineCacheDevice(); + + // set the preferences + device->SetCacheParentDirectory(aProfileDir); + device->SetCapacity(aQuota); + + nsresult rv = device->InitWithSqlite(mStorageService); + if (NS_FAILED(rv)) { + CACHE_LOG_DEBUG(("OfflineDevice->InitWithSqlite() failed (0x%.8" PRIx32 + ")\n", + static_cast<uint32_t>(rv))); + CACHE_LOG_DEBUG((" - disabling offline cache for this session.\n")); + device = nullptr; + } + + device.forget(aDevice); + return rv; +} + +nsresult nsCacheService::RemoveCustomOfflineDevice( + nsOfflineCacheDevice* aDevice) { + nsCOMPtr<nsIFile> profileDir = aDevice->BaseDirectory(); + if (!profileDir) return NS_ERROR_UNEXPECTED; + + nsAutoString profilePath; + nsresult rv = profileDir->GetPath(profilePath); + NS_ENSURE_SUCCESS(rv, rv); + + mCustomOfflineDevices.Remove(profilePath); + return NS_OK; +} + +nsresult nsCacheService::CreateRequest(nsCacheSession* session, + const nsACString& clientKey, + nsCacheAccessMode accessRequested, + bool blockingMode, + nsICacheListener* listener, + nsCacheRequest** request) { + NS_ASSERTION(request, "CreateRequest: request is null"); + + nsAutoCString key(*session->ClientID()); + key.Append(':'); + key.Append(clientKey); + + if (mMaxKeyLength < key.Length()) mMaxKeyLength = key.Length(); + + // create request + *request = + new nsCacheRequest(key, listener, accessRequested, blockingMode, session); + + if (!listener) return NS_OK; // we're sync, we're done. + + // get the request's thread + (*request)->mEventTarget = GetCurrentEventTarget(); + + return NS_OK; +} + +class nsCacheListenerEvent : public Runnable { + public: + nsCacheListenerEvent(nsICacheListener* listener, + nsICacheEntryDescriptor* descriptor, + nsCacheAccessMode accessGranted, nsresult status) + : mozilla::Runnable("nsCacheListenerEvent"), + mListener(listener) // transfers reference + , + mDescriptor(descriptor) // transfers reference (may be null) + , + mAccessGranted(accessGranted), + mStatus(status) {} + + NS_IMETHOD Run() override { + mListener->OnCacheEntryAvailable(mDescriptor, mAccessGranted, mStatus); + + NS_RELEASE(mListener); + NS_IF_RELEASE(mDescriptor); + return NS_OK; + } + + private: + // We explicitly leak mListener or mDescriptor if Run is not called + // because otherwise we cannot guarantee that they are destroyed on + // the right thread. + + nsICacheListener* mListener; + nsICacheEntryDescriptor* mDescriptor; + nsCacheAccessMode mAccessGranted; + nsresult mStatus; +}; + +nsresult nsCacheService::NotifyListener(nsCacheRequest* request, + nsICacheEntryDescriptor* descriptor, + nsCacheAccessMode accessGranted, + nsresult status) { + NS_ASSERTION(request->mEventTarget, "no thread set in async request!"); + + // Swap ownership, and release listener on target thread... + nsICacheListener* listener = request->mListener; + request->mListener = nullptr; + + nsCOMPtr<nsIRunnable> ev = + new nsCacheListenerEvent(listener, descriptor, accessGranted, status); + if (!ev) { + // Better to leak listener and descriptor if we fail because we don't + // want to destroy them inside the cache service lock or on potentially + // the wrong thread. + return NS_ERROR_OUT_OF_MEMORY; + } + + return request->mEventTarget->Dispatch(ev, NS_DISPATCH_NORMAL); +} + +nsresult nsCacheService::ProcessRequest(nsCacheRequest* request, + bool calledFromOpenCacheEntry, + nsICacheEntryDescriptor** result) { + // !!! must be called with mLock held !!! + nsresult rv; + nsCacheEntry* entry = nullptr; + nsCacheEntry* doomedEntry = nullptr; + nsCacheAccessMode accessGranted = nsICache::ACCESS_NONE; + if (result) *result = nullptr; + + while (true) { // Activate entry loop + rv = ActivateEntry(request, &entry, + &doomedEntry); // get the entry for this request + if (NS_FAILED(rv)) break; + + while (true) { // Request Access loop + NS_ASSERTION(entry, "no entry in Request Access loop!"); + // entry->RequestAccess queues request on entry + rv = entry->RequestAccess(request, &accessGranted); + if (rv != NS_ERROR_CACHE_WAIT_FOR_VALIDATION) break; + + if (request->IsBlocking()) { + if (request->mListener) { + // async exits - validate, doom, or close will resume + return rv; + } + + // XXX this is probably wrong... + Unlock(); + rv = request->WaitForValidation(); + Lock(LOCK_TELEM(NSCACHESERVICE_PROCESSREQUEST)); + } + + PR_REMOVE_AND_INIT_LINK(request); + if (NS_FAILED(rv)) + break; // non-blocking mode returns WAIT_FOR_VALIDATION error + // okay, we're ready to process this request, request access again + } + if (rv != NS_ERROR_CACHE_ENTRY_DOOMED) break; + + if (entry->IsNotInUse()) { + // this request was the last one keeping it around, so get rid of it + DeactivateEntry(entry); + } + // loop back around to look for another entry + } + + if (NS_SUCCEEDED(rv) && request->mProfileDir) { + // Custom cache directory has been demanded. Preset the cache device. + if (entry->StoragePolicy() != nsICache::STORE_OFFLINE) { + // Failsafe check: this is implemented only for offline cache atm. + rv = NS_ERROR_FAILURE; + } else { + RefPtr<nsOfflineCacheDevice> customCacheDevice; + rv = GetCustomOfflineDevice(request->mProfileDir, -1, + getter_AddRefs(customCacheDevice)); + if (NS_SUCCEEDED(rv)) entry->SetCustomCacheDevice(customCacheDevice); + } + } + + nsICacheEntryDescriptor* descriptor = nullptr; + + if (NS_SUCCEEDED(rv)) + rv = entry->CreateDescriptor(request, accessGranted, &descriptor); + + // If doomedEntry is set, ActivatEntry() doomed an existing entry and + // created a new one for that cache-key. However, any pending requests + // on the doomed entry were not processed and we need to do that here. + // This must be done after adding the created entry to list of active + // entries (which is done in ActivateEntry()) otherwise the hashkeys crash + // (see bug ##561313). It is also important to do this after creating a + // descriptor for this request, or some other request may end up being + // executed first for the newly created entry. + // Finally, it is worth to emphasize that if doomedEntry is set, + // ActivateEntry() created a new entry for the request, which will be + // initialized by RequestAccess() and they both should have returned NS_OK. + if (doomedEntry) { + (void)ProcessPendingRequests(doomedEntry); + if (doomedEntry->IsNotInUse()) DeactivateEntry(doomedEntry); + doomedEntry = nullptr; + } + + if (request->mListener) { // Asynchronous + + if (NS_FAILED(rv) && calledFromOpenCacheEntry && request->IsBlocking()) + return rv; // skip notifying listener, just return rv to caller + + // call listener to report error or descriptor + nsresult rv2 = NotifyListener(request, descriptor, accessGranted, rv); + if (NS_FAILED(rv2) && NS_SUCCEEDED(rv)) { + rv = rv2; // trigger delete request + } + } else { // Synchronous + *result = descriptor; + } + return rv; +} + +nsresult nsCacheService::OpenCacheEntry(nsCacheSession* session, + const nsACString& key, + nsCacheAccessMode accessRequested, + bool blockingMode, + nsICacheListener* listener, + nsICacheEntryDescriptor** result) { + CACHE_LOG_DEBUG( + ("Opening entry for session %p, key %s, mode %d, blocking %d\n", session, + PromiseFlatCString(key).get(), accessRequested, blockingMode)); + if (result) *result = nullptr; + + if (!gService || !gService->mInitialized) return NS_ERROR_NOT_INITIALIZED; + + nsCacheRequest* request = nullptr; + + nsresult rv = gService->CreateRequest(session, key, accessRequested, + blockingMode, listener, &request); + if (NS_FAILED(rv)) return rv; + + CACHE_LOG_DEBUG(("Created request %p\n", request)); + + // Process the request on the background thread if we are on the main thread + // and the the request is asynchronous + if (NS_IsMainThread() && listener && gService->mCacheIOThread) { + nsCOMPtr<nsIRunnable> ev = new nsProcessRequestEvent(request); + rv = DispatchToCacheIOThread(ev); + + // delete request if we didn't post the event + if (NS_FAILED(rv)) delete request; + } else { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHESERVICE_OPENCACHEENTRY)); + rv = gService->ProcessRequest(request, true, result); + + // delete requests that have completed + if (!(listener && blockingMode && + (rv == NS_ERROR_CACHE_WAIT_FOR_VALIDATION))) + delete request; + } + + return rv; +} + +nsresult nsCacheService::ActivateEntry(nsCacheRequest* request, + nsCacheEntry** result, + nsCacheEntry** doomedEntry) { + CACHE_LOG_DEBUG(("Activate entry for request %p\n", request)); + if (!mInitialized || mClearingEntries) return NS_ERROR_NOT_AVAILABLE; + + nsresult rv = NS_OK; + + NS_ASSERTION(request != nullptr, "ActivateEntry called with no request"); + if (result) *result = nullptr; + if (doomedEntry) *doomedEntry = nullptr; + if ((!request) || (!result) || (!doomedEntry)) return NS_ERROR_NULL_POINTER; + + // check if the request can be satisfied + if (!request->IsStreamBased()) return NS_ERROR_FAILURE; + if (!IsStorageEnabledForPolicy_Locked(request->StoragePolicy())) + return NS_ERROR_FAILURE; + + // search active entries (including those not bound to device) + nsCacheEntry* entry = mActiveEntries.GetEntry(&(request->mKey)); + CACHE_LOG_DEBUG(("Active entry for request %p is %p\n", request, entry)); + + if (!entry) { + // search cache devices for entry + bool collision = false; + entry = SearchCacheDevices(&(request->mKey), request->StoragePolicy(), + &collision); + CACHE_LOG_DEBUG( + ("Device search for request %p returned %p\n", request, entry)); + // When there is a hashkey collision just refuse to cache it... + if (collision) return NS_ERROR_CACHE_IN_USE; + + if (entry) entry->MarkInitialized(); + } else { + NS_ASSERTION(entry->IsActive(), "Inactive entry found in mActiveEntries!"); + } + + if (entry) { + ++mCacheHits; + entry->Fetched(); + } else { + ++mCacheMisses; + } + + if (entry && ((request->AccessRequested() == nsICache::ACCESS_WRITE) || + ((request->StoragePolicy() != nsICache::STORE_OFFLINE) && + (entry->mExpirationTime <= SecondsFromPRTime(PR_Now()) && + request->WillDoomEntriesIfExpired())))) + + { + // this is FORCE-WRITE request or the entry has expired + // we doom entry without processing pending requests, but store it in + // doomedEntry which causes pending requests to be processed below + rv = DoomEntry_Internal(entry, false); + *doomedEntry = entry; + if (NS_FAILED(rv)) { + // XXX what to do? Increment FailedDooms counter? + } + entry = nullptr; + } + + if (!entry) { + if (!(request->AccessRequested() & nsICache::ACCESS_WRITE)) { + // this is a READ-ONLY request + rv = NS_ERROR_CACHE_KEY_NOT_FOUND; + goto error; + } + + entry = new nsCacheEntry(request->mKey, request->IsStreamBased(), + request->StoragePolicy()); + if (!entry) return NS_ERROR_OUT_OF_MEMORY; + + if (request->IsPrivate()) entry->MarkPrivate(); + + entry->Fetched(); + ++mTotalEntries; + + // XXX we could perform an early bind in some cases based on storage policy + } + + if (!entry->IsActive()) { + rv = mActiveEntries.AddEntry(entry); + if (NS_FAILED(rv)) goto error; + CACHE_LOG_DEBUG(("Added entry %p to mActiveEntries\n", entry)); + entry->MarkActive(); // mark entry active, because it's now in + // mActiveEntries + } + *result = entry; + return NS_OK; + +error: + *result = nullptr; + delete entry; + return rv; +} + +nsCacheEntry* nsCacheService::SearchCacheDevices(nsCString* key, + nsCacheStoragePolicy policy, + bool* collision) { + Telemetry::AutoTimer<Telemetry::CACHE_DEVICE_SEARCH_2> timer; + nsCacheEntry* entry = nullptr; + + *collision = false; + if (policy == nsICache::STORE_OFFLINE || + (policy == nsICache::STORE_ANYWHERE && gIOService->IsOffline())) { + if (mEnableOfflineDevice) { + if (!mOfflineDevice) { + nsresult rv = CreateOfflineDevice(); + if (NS_FAILED(rv)) return nullptr; + } + + entry = mOfflineDevice->FindEntry(key, collision); + } + } + + return entry; +} + +nsCacheDevice* nsCacheService::EnsureEntryHasDevice(nsCacheEntry* entry) { + nsCacheDevice* device = entry->CacheDevice(); + // return device if found, possibly null if the entry is doomed i.e prevent + // doomed entries to bind to a device (see e.g. bugs #548406 and #596443) + if (device || entry->IsDoomed()) return device; + + if (!device && entry->IsStreamData() && entry->IsAllowedOffline() && + mEnableOfflineDevice) { + if (!mOfflineDevice) { + (void)CreateOfflineDevice(); // ignore the error (check for + // mOfflineDevice instead) + } + + device = entry->CustomCacheDevice() ? entry->CustomCacheDevice() + : mOfflineDevice; + + if (device) { + entry->MarkBinding(); + nsresult rv = device->BindEntry(entry); + entry->ClearBinding(); + if (NS_FAILED(rv)) device = nullptr; + } + } + + if (device) entry->SetCacheDevice(device); + return device; +} + +nsresult nsCacheService::DoomEntry(nsCacheEntry* entry) { + return gService->DoomEntry_Internal(entry, true); +} + +nsresult nsCacheService::DoomEntry_Internal(nsCacheEntry* entry, + bool doProcessPendingRequests) { + if (entry->IsDoomed()) return NS_OK; + + CACHE_LOG_DEBUG(("Dooming entry %p\n", entry)); + nsresult rv = NS_OK; + entry->MarkDoomed(); + + NS_ASSERTION(!entry->IsBinding(), "Dooming entry while binding device."); + nsCacheDevice* device = entry->CacheDevice(); + if (device) device->DoomEntry(entry); + + if (entry->IsActive()) { + // remove from active entries + mActiveEntries.RemoveEntry(entry); + CACHE_LOG_DEBUG(("Removed entry %p from mActiveEntries\n", entry)); + entry->MarkInactive(); + } + + // put on doom list to wait for descriptors to close + NS_ASSERTION(PR_CLIST_IS_EMPTY(entry), "doomed entry still on device list"); + PR_APPEND_LINK(entry, &mDoomedEntries); + + // handle pending requests only if we're supposed to + if (doProcessPendingRequests) { + // tell pending requests to get on with their lives... + rv = ProcessPendingRequests(entry); + + // All requests have been removed, but there may still be open descriptors + if (entry->IsNotInUse()) { + DeactivateEntry(entry); // tell device to get rid of it + } + } + return rv; +} + +void nsCacheService::OnProfileShutdown() { + if (!gService || !gService->mInitialized) { + // The cache service has been shut down, but someone is still holding + // a reference to it. Ignore this call. + return; + } + + { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHESERVICE_ONPROFILESHUTDOWN)); + gService->mClearingEntries = true; + gService->DoomActiveEntries(nullptr); + } + + gService->CloseAllStreams(); + + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHESERVICE_ONPROFILESHUTDOWN)); + gService->ClearDoomList(); + + // Make sure to wait for any pending cache-operations before + // proceeding with destructive actions (bug #620660) + (void)SyncWithCacheIOThread(); + + if (gService->mOfflineDevice && gService->mEnableOfflineDevice) { + gService->mOfflineDevice->Shutdown(); + } + for (auto iter = gService->mCustomOfflineDevices.Iter(); !iter.Done(); + iter.Next()) { + iter.Data()->Shutdown(); + iter.Remove(); + } + + gService->mEnableOfflineDevice = false; + + gService->mClearingEntries = false; +} + +void nsCacheService::OnProfileChanged() { + if (!gService) return; + + CACHE_LOG_DEBUG(("nsCacheService::OnProfileChanged")); + + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHESERVICE_ONPROFILECHANGED)); + + gService->mEnableOfflineDevice = gService->mObserver->OfflineCacheEnabled(); + + if (gService->mOfflineDevice) { + gService->mOfflineDevice->SetCacheParentDirectory( + gService->mObserver->OfflineCacheParentDirectory()); + gService->mOfflineDevice->SetCapacity( + gService->mObserver->OfflineCacheCapacity()); + + // XXX initialization of mOfflineDevice could be made lazily, if + // mEnableOfflineDevice is false + nsresult rv = + gService->mOfflineDevice->InitWithSqlite(gService->mStorageService); + if (NS_FAILED(rv)) { + NS_ERROR( + "nsCacheService::OnProfileChanged: Re-initializing offline device " + "failed"); + gService->mEnableOfflineDevice = false; + // XXX delete mOfflineDevice? + } + } +} + +void nsCacheService::SetOfflineCacheEnabled(bool enabled) { + if (!gService) return; + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHESERVICE_SETOFFLINECACHEENABLED)); + gService->mEnableOfflineDevice = enabled; +} + +void nsCacheService::SetOfflineCacheCapacity(int32_t capacity) { + if (!gService) return; + nsCacheServiceAutoLock lock( + LOCK_TELEM(NSCACHESERVICE_SETOFFLINECACHECAPACITY)); + + if (gService->mOfflineDevice) { + gService->mOfflineDevice->SetCapacity(capacity); + } + + gService->mEnableOfflineDevice = gService->mObserver->OfflineCacheEnabled(); +} + +/****************************************************************************** + * static methods for nsCacheEntryDescriptor + *****************************************************************************/ +void nsCacheService::CloseDescriptor(nsCacheEntryDescriptor* descriptor) { + // ask entry to remove descriptor + nsCacheEntry* entry = descriptor->CacheEntry(); + bool doomEntry; + bool stillActive = entry->RemoveDescriptor(descriptor, &doomEntry); + + if (!entry->IsValid()) { + gService->ProcessPendingRequests(entry); + } + + if (doomEntry) { + gService->DoomEntry_Internal(entry, true); + return; + } + + if (!stillActive) { + gService->DeactivateEntry(entry); + } +} + +nsresult nsCacheService::GetFileForEntry(nsCacheEntry* entry, + nsIFile** result) { + nsCacheDevice* device = gService->EnsureEntryHasDevice(entry); + if (!device) return NS_ERROR_UNEXPECTED; + + return device->GetFileForEntry(entry, result); +} + +nsresult nsCacheService::OpenInputStreamForEntry(nsCacheEntry* entry, + nsCacheAccessMode mode, + uint32_t offset, + nsIInputStream** result) { + nsCacheDevice* device = gService->EnsureEntryHasDevice(entry); + if (!device) return NS_ERROR_UNEXPECTED; + + return device->OpenInputStreamForEntry(entry, mode, offset, result); +} + +nsresult nsCacheService::OpenOutputStreamForEntry(nsCacheEntry* entry, + nsCacheAccessMode mode, + uint32_t offset, + nsIOutputStream** result) { + nsCacheDevice* device = gService->EnsureEntryHasDevice(entry); + if (!device) return NS_ERROR_UNEXPECTED; + + return device->OpenOutputStreamForEntry(entry, mode, offset, result); +} + +nsresult nsCacheService::OnDataSizeChange(nsCacheEntry* entry, + int32_t deltaSize) { + nsCacheDevice* device = gService->EnsureEntryHasDevice(entry); + if (!device) return NS_ERROR_UNEXPECTED; + + return device->OnDataSizeChange(entry, deltaSize); +} + +void nsCacheService::LockAcquired() { + MutexAutoLock lock(mTimeStampLock); + mLockAcquiredTimeStamp = TimeStamp::Now(); +} + +void nsCacheService::LockReleased() { + MutexAutoLock lock(mTimeStampLock); + mLockAcquiredTimeStamp = TimeStamp(); +} + +void nsCacheService::Lock() { + gService->mLock.Lock(); + gService->LockAcquired(); +} + +void nsCacheService::Lock(mozilla::Telemetry::HistogramID mainThreadLockerID) { + mozilla::Telemetry::HistogramID lockerID; + mozilla::Telemetry::HistogramID generalID; + + if (NS_IsMainThread()) { + lockerID = mainThreadLockerID; + generalID = mozilla::Telemetry::CACHE_SERVICE_LOCK_WAIT_MAINTHREAD_2; + } else { + lockerID = mozilla::Telemetry::HistogramCount; + generalID = mozilla::Telemetry::CACHE_SERVICE_LOCK_WAIT_2; + } + + TimeStamp start(TimeStamp::Now()); + + nsCacheService::Lock(); + + TimeStamp stop(TimeStamp::Now()); + + // Telemetry isn't thread safe on its own, but this is OK because we're + // protecting it with the cache lock. + if (lockerID != mozilla::Telemetry::HistogramCount) { + mozilla::Telemetry::AccumulateTimeDelta(lockerID, start, stop); + } + mozilla::Telemetry::AccumulateTimeDelta(generalID, start, stop); +} + +void nsCacheService::Unlock() { + gService->mLock.AssertCurrentThreadOwns(); + + nsTArray<nsISupports*> doomed = std::move(gService->mDoomedObjects); + + gService->LockReleased(); + gService->mLock.Unlock(); + + for (uint32_t i = 0; i < doomed.Length(); ++i) doomed[i]->Release(); +} + +void nsCacheService::ReleaseObject_Locked(nsISupports* obj, + nsIEventTarget* target) { + gService->mLock.AssertCurrentThreadOwns(); + + bool isCur; + if (!target || (NS_SUCCEEDED(target->IsOnCurrentThread(&isCur)) && isCur)) { + gService->mDoomedObjects.AppendElement(obj); + } else { + NS_ProxyRelease("nsCacheService::ReleaseObject_Locked::obj", target, + dont_AddRef(obj)); + } +} + +nsresult nsCacheService::SetCacheElement(nsCacheEntry* entry, + nsISupports* element) { + entry->SetData(element); + entry->TouchData(); + return NS_OK; +} + +nsresult nsCacheService::ValidateEntry(nsCacheEntry* entry) { + nsCacheDevice* device = gService->EnsureEntryHasDevice(entry); + if (!device) return NS_ERROR_UNEXPECTED; + + entry->MarkValid(); + nsresult rv = gService->ProcessPendingRequests(entry); + NS_ASSERTION(rv == NS_OK, "ProcessPendingRequests failed."); + // XXX what else should be done? + + return rv; +} + +int32_t nsCacheService::CacheCompressionLevel() { + int32_t level = gService->mObserver->CacheCompressionLevel(); + return level; +} + +void nsCacheService::DeactivateEntry(nsCacheEntry* entry) { + CACHE_LOG_DEBUG(("Deactivating entry %p\n", entry)); + nsresult rv = NS_OK; + NS_ASSERTION(entry->IsNotInUse(), "### deactivating an entry while in use!"); + nsCacheDevice* device = nullptr; + + if (mMaxDataSize < entry->DataSize()) mMaxDataSize = entry->DataSize(); + if (mMaxMetaSize < entry->MetaDataSize()) + mMaxMetaSize = entry->MetaDataSize(); + + if (entry->IsDoomed()) { + // remove from Doomed list + PR_REMOVE_AND_INIT_LINK(entry); + } else if (entry->IsActive()) { + // remove from active entries + mActiveEntries.RemoveEntry(entry); + CACHE_LOG_DEBUG( + ("Removed deactivated entry %p from mActiveEntries\n", entry)); + entry->MarkInactive(); + + // bind entry if necessary to store meta-data + device = EnsureEntryHasDevice(entry); + if (!device) { + CACHE_LOG_DEBUG( + ("DeactivateEntry: unable to bind active " + "entry %p\n", + entry)); + NS_WARNING("DeactivateEntry: unable to bind active entry\n"); + return; + } + } else { + // if mInitialized == false, + // then we're shutting down and this state is okay. + NS_ASSERTION(!mInitialized, "DeactivateEntry: bad cache entry state."); + } + + device = entry->CacheDevice(); + if (device) { + rv = device->DeactivateEntry(entry); + if (NS_FAILED(rv)) { + // increment deactivate failure count + ++mDeactivateFailures; + } + } else { + // increment deactivating unbound entry statistic + ++mDeactivatedUnboundEntries; + delete entry; // because no one else will + } +} + +nsresult nsCacheService::ProcessPendingRequests(nsCacheEntry* entry) { + nsresult rv = NS_OK; + nsCacheRequest* request = (nsCacheRequest*)PR_LIST_HEAD(&entry->mRequestQ); + nsCacheRequest* nextRequest; + bool newWriter = false; + + CACHE_LOG_DEBUG(( + "ProcessPendingRequests for %sinitialized %s %salid entry %p\n", + (entry->IsInitialized() ? "" : "Un"), (entry->IsDoomed() ? "DOOMED" : ""), + (entry->IsValid() ? "V" : "Inv"), entry)); + + if (request == &entry->mRequestQ) return NS_OK; // no queued requests + + if (!entry->IsDoomed() && entry->IsInvalid()) { + // 1st descriptor closed w/o MarkValid() + NS_ASSERTION(PR_CLIST_IS_EMPTY(&entry->mDescriptorQ), + "shouldn't be here with open descriptors"); + +#if DEBUG + // verify no ACCESS_WRITE requests(shouldn't have any of these) + while (request != &entry->mRequestQ) { + NS_ASSERTION(request->AccessRequested() != nsICache::ACCESS_WRITE, + "ACCESS_WRITE request should have been given a new entry"); + request = (nsCacheRequest*)PR_NEXT_LINK(request); + } + request = (nsCacheRequest*)PR_LIST_HEAD(&entry->mRequestQ); +#endif + // find first request with ACCESS_READ_WRITE (if any) and promote it to 1st + // writer + while (request != &entry->mRequestQ) { + if (request->AccessRequested() == nsICache::ACCESS_READ_WRITE) { + newWriter = true; + CACHE_LOG_DEBUG((" promoting request %p to 1st writer\n", request)); + break; + } + + request = (nsCacheRequest*)PR_NEXT_LINK(request); + } + + if (request == &entry->mRequestQ) // no requests asked for + // ACCESS_READ_WRITE, back to top + request = (nsCacheRequest*)PR_LIST_HEAD(&entry->mRequestQ); + + // XXX what should we do if there are only READ requests in queue? + // XXX serialize their accesses, give them only read access, but force them + // to check validate flag? + // XXX or do readers simply presume the entry is valid + // See fix for bug #467392 below + } + + nsCacheAccessMode accessGranted = nsICache::ACCESS_NONE; + + while (request != &entry->mRequestQ) { + nextRequest = (nsCacheRequest*)PR_NEXT_LINK(request); + CACHE_LOG_DEBUG((" %sync request %p for %p\n", + (request->mListener ? "As" : "S"), request, entry)); + + if (request->mListener) { + // Async request + PR_REMOVE_AND_INIT_LINK(request); + + if (entry->IsDoomed()) { + rv = ProcessRequest(request, false, nullptr); + if (rv == NS_ERROR_CACHE_WAIT_FOR_VALIDATION) + rv = NS_OK; + else + delete request; + + if (NS_FAILED(rv)) { + // XXX what to do? + } + } else if (entry->IsValid() || newWriter) { + rv = entry->RequestAccess(request, &accessGranted); + NS_ASSERTION(NS_SUCCEEDED(rv), + "if entry is valid, RequestAccess must succeed."); + // XXX if (newWriter) { + // NS_ASSERTION( accessGranted == + // request->AccessRequested(), "why not?"); + // } + + // entry->CreateDescriptor dequeues request, and queues descriptor + nsICacheEntryDescriptor* descriptor = nullptr; + rv = entry->CreateDescriptor(request, accessGranted, &descriptor); + + // post call to listener to report error or descriptor + rv = NotifyListener(request, descriptor, accessGranted, rv); + delete request; + if (NS_FAILED(rv)) { + // XXX what to do? + } + + } else { + // read-only request to an invalid entry - need to wait for + // the entry to become valid so we post an event to process + // the request again later (bug #467392) + nsCOMPtr<nsIRunnable> ev = new nsProcessRequestEvent(request); + rv = DispatchToCacheIOThread(ev); + if (NS_FAILED(rv)) { + delete request; // avoid leak + } + } + } else { + // Synchronous request + request->WakeUp(); + } + if (newWriter) break; // process remaining requests after validation + request = nextRequest; + } + + return NS_OK; +} + +bool nsCacheService::IsDoomListEmpty() { + nsCacheEntry* entry = (nsCacheEntry*)PR_LIST_HEAD(&mDoomedEntries); + return &mDoomedEntries == entry; +} + +void nsCacheService::ClearDoomList() { + nsCacheEntry* entry = (nsCacheEntry*)PR_LIST_HEAD(&mDoomedEntries); + + while (entry != &mDoomedEntries) { + nsCacheEntry* next = (nsCacheEntry*)PR_NEXT_LINK(entry); + + entry->DetachDescriptors(); + DeactivateEntry(entry); + entry = next; + } +} + +void nsCacheService::DoomActiveEntries(DoomCheckFn check) { + AutoTArray<nsCacheEntry*, 8> array; + + for (auto iter = mActiveEntries.Iter(); !iter.Done(); iter.Next()) { + nsCacheEntry* entry = + static_cast<nsCacheEntryHashTableEntry*>(iter.Get())->cacheEntry; + + if (check && !check(entry)) { + continue; + } + + array.AppendElement(entry); + + // entry is being removed from the active entry list + entry->MarkInactive(); + iter.Remove(); + } + + uint32_t count = array.Length(); + for (uint32_t i = 0; i < count; ++i) { + DoomEntry_Internal(array[i], true); + } +} + +void nsCacheService::CloseAllStreams() { + nsTArray<RefPtr<nsCacheEntryDescriptor::nsInputStreamWrapper> > inputs; + nsTArray<RefPtr<nsCacheEntryDescriptor::nsOutputStreamWrapper> > outputs; + + { + nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHESERVICE_CLOSEALLSTREAMS)); + + nsTArray<nsCacheEntry*> entries; + +#if DEBUG + // make sure there is no active entry + for (auto iter = mActiveEntries.Iter(); !iter.Done(); iter.Next()) { + auto entry = static_cast<nsCacheEntryHashTableEntry*>(iter.Get()); + entries.AppendElement(entry->cacheEntry); + } + NS_ASSERTION(entries.IsEmpty(), "Bad state"); +#endif + + // Get doomed entries + nsCacheEntry* entry = (nsCacheEntry*)PR_LIST_HEAD(&mDoomedEntries); + while (entry != &mDoomedEntries) { + nsCacheEntry* next = (nsCacheEntry*)PR_NEXT_LINK(entry); + entries.AppendElement(entry); + entry = next; + } + + // Iterate through all entries and collect input and output streams + for (size_t i = 0; i < entries.Length(); i++) { + entry = entries.ElementAt(i); + + nsTArray<RefPtr<nsCacheEntryDescriptor> > descs; + entry->GetDescriptors(descs); + + for (uint32_t j = 0; j < descs.Length(); j++) { + if (descs[j]->mOutputWrapper) + outputs.AppendElement(descs[j]->mOutputWrapper); + + for (size_t k = 0; k < descs[j]->mInputWrappers.Length(); k++) + inputs.AppendElement(descs[j]->mInputWrappers[k]); + } + } + } + + uint32_t i; + for (i = 0; i < inputs.Length(); i++) inputs[i]->Close(); + + for (i = 0; i < outputs.Length(); i++) outputs[i]->Close(); +} + +bool nsCacheService::GetClearingEntries() { + AssertOwnsLock(); + return gService->mClearingEntries; +} + +// static +void nsCacheService::GetCacheBaseDirectoty(nsIFile** result) { + *result = nullptr; + if (!gService || !gService->mObserver) return; + + nsCOMPtr<nsIFile> directory = gService->mObserver->DiskCacheParentDirectory(); + if (!directory) return; + + directory->Clone(result); +} + +// static +void nsCacheService::GetDiskCacheDirectory(nsIFile** result) { + nsCOMPtr<nsIFile> directory; + GetCacheBaseDirectoty(getter_AddRefs(directory)); + if (!directory) return; + + nsresult rv = directory->AppendNative("Cache"_ns); + if (NS_FAILED(rv)) return; + + directory.forget(result); +} + +// static +void nsCacheService::GetAppCacheDirectory(nsIFile** result) { + nsCOMPtr<nsIFile> directory; + GetCacheBaseDirectoty(getter_AddRefs(directory)); + if (!directory) return; + + nsresult rv = directory->AppendNative("OfflineCache"_ns); + if (NS_FAILED(rv)) return; + + directory.forget(result); +} + +void nsCacheService::LogCacheStatistics() { + uint32_t hitPercentage = 0; + double sum = (double)(mCacheHits + mCacheMisses); + if (sum != 0) { + hitPercentage = (uint32_t)((((double)mCacheHits) / sum) * 100); + } + CACHE_LOG_INFO(("\nCache Service Statistics:\n\n")); + CACHE_LOG_INFO((" TotalEntries = %d\n", mTotalEntries)); + CACHE_LOG_INFO((" Cache Hits = %d\n", mCacheHits)); + CACHE_LOG_INFO((" Cache Misses = %d\n", mCacheMisses)); + CACHE_LOG_INFO((" Cache Hit %% = %d%%\n", hitPercentage)); + CACHE_LOG_INFO((" Max Key Length = %d\n", mMaxKeyLength)); + CACHE_LOG_INFO((" Max Meta Size = %d\n", mMaxMetaSize)); + CACHE_LOG_INFO((" Max Data Size = %d\n", mMaxDataSize)); + CACHE_LOG_INFO(("\n")); + CACHE_LOG_INFO( + (" Deactivate Failures = %d\n", mDeactivateFailures)); + CACHE_LOG_INFO( + (" Deactivated Unbound Entries = %d\n", mDeactivatedUnboundEntries)); +} + +void nsCacheService::MoveOrRemoveDiskCache(nsIFile* aOldCacheDir, + nsIFile* aNewCacheDir, + const char* aCacheSubdir) { + bool same; + if (NS_FAILED(aOldCacheDir->Equals(aNewCacheDir, &same)) || same) return; + + nsCOMPtr<nsIFile> aOldCacheSubdir; + aOldCacheDir->Clone(getter_AddRefs(aOldCacheSubdir)); + + nsresult rv = aOldCacheSubdir->AppendNative(nsDependentCString(aCacheSubdir)); + if (NS_FAILED(rv)) return; + + bool exists; + if (NS_FAILED(aOldCacheSubdir->Exists(&exists)) || !exists) return; + + nsCOMPtr<nsIFile> aNewCacheSubdir; + aNewCacheDir->Clone(getter_AddRefs(aNewCacheSubdir)); + + rv = aNewCacheSubdir->AppendNative(nsDependentCString(aCacheSubdir)); + if (NS_FAILED(rv)) return; + + PathString newPath = aNewCacheSubdir->NativePath(); + + if (NS_SUCCEEDED(aNewCacheSubdir->Exists(&exists)) && !exists) { + // New cache directory does not exist, try to move the old one here + // rename needs an empty target directory + + // Make sure the parent of the target sub-dir exists + rv = aNewCacheDir->Create(nsIFile::DIRECTORY_TYPE, 0777); + if (NS_SUCCEEDED(rv) || NS_ERROR_FILE_ALREADY_EXISTS == rv) { + PathString oldPath = aOldCacheSubdir->NativePath(); +#ifdef XP_WIN + if (MoveFileW(oldPath.get(), newPath.get())) +#else + if (rename(oldPath.get(), newPath.get()) == 0) +#endif + { + return; + } + } + } + + // Delay delete by 1 minute to avoid IO thrash on startup. + nsDeleteDir::DeleteDir(aOldCacheSubdir, false, 60000); +} + +static bool IsEntryPrivate(nsCacheEntry* entry) { return entry->IsPrivate(); } + +void nsCacheService::LeavePrivateBrowsing() { + nsCacheServiceAutoLock lock; + + gService->DoomActiveEntries(IsEntryPrivate); +} diff --git a/netwerk/cache/nsCacheService.h b/netwerk/cache/nsCacheService.h new file mode 100644 index 0000000000..2f9ca28af0 --- /dev/null +++ b/netwerk/cache/nsCacheService.h @@ -0,0 +1,331 @@ +/* -*- 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/. */ + +#ifndef _nsCacheService_h_ +#define _nsCacheService_h_ + +#include "nsICacheService.h" +#include "nsCacheSession.h" +#include "nsCacheDevice.h" +#include "nsCacheEntry.h" +#include "nsThreadUtils.h" +#include "nsICacheListener.h" + +#include "prthread.h" +#include "nsString.h" +#include "nsTArray.h" +#include "nsRefPtrHashtable.h" +#include "mozilla/CondVar.h" +#include "mozilla/Mutex.h" +#include "mozilla/Telemetry.h" + +class nsCacheRequest; +class nsCacheProfilePrefObserver; +class nsOfflineCacheDevice; +class nsCacheServiceAutoLock; +class nsITimer; +class mozIStorageService; + +/****************************************************************************** + * nsNotifyDoomListener + *****************************************************************************/ + +class nsNotifyDoomListener : public mozilla::Runnable { + public: + nsNotifyDoomListener(nsICacheListener* listener, nsresult status) + : mozilla::Runnable("nsNotifyDoomListener"), + mListener(listener) // transfers reference + , + mStatus(status) {} + + NS_IMETHOD Run() override { + mListener->OnCacheEntryDoomed(mStatus); + NS_RELEASE(mListener); + return NS_OK; + } + + private: + nsICacheListener* mListener; + nsresult mStatus; +}; + +/****************************************************************************** + * nsCacheService + ******************************************************************************/ + +class nsCacheService final : public nsICacheServiceInternal { + virtual ~nsCacheService(); + + public: + NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_NSICACHESERVICE + NS_DECL_NSICACHESERVICEINTERNAL + + nsCacheService(); + + // Define a Create method to be used with a factory: + static nsresult Create(nsISupports* outer, const nsIID& iid, void** result); + + /** + * Methods called by nsCacheSession + */ + static nsresult OpenCacheEntry(nsCacheSession* session, const nsACString& key, + nsCacheAccessMode accessRequested, + bool blockingMode, nsICacheListener* listener, + nsICacheEntryDescriptor** result); + + static nsresult EvictEntriesForSession(nsCacheSession* session); + + static nsresult IsStorageEnabledForPolicy(nsCacheStoragePolicy storagePolicy, + bool* result); + + static nsresult DoomEntry(nsCacheSession* session, const nsACString& key, + nsICacheListener* listener); + + /** + * Methods called by nsCacheEntryDescriptor + */ + + static void CloseDescriptor(nsCacheEntryDescriptor* descriptor); + + static nsresult GetFileForEntry(nsCacheEntry* entry, nsIFile** result); + + static nsresult OpenInputStreamForEntry(nsCacheEntry* entry, + nsCacheAccessMode mode, + uint32_t offset, + nsIInputStream** result); + + static nsresult OpenOutputStreamForEntry(nsCacheEntry* entry, + nsCacheAccessMode mode, + uint32_t offset, + nsIOutputStream** result); + + static nsresult OnDataSizeChange(nsCacheEntry* entry, int32_t deltaSize); + + static nsresult SetCacheElement(nsCacheEntry* entry, nsISupports* element); + + static nsresult ValidateEntry(nsCacheEntry* entry); + + static int32_t CacheCompressionLevel(); + + static bool GetClearingEntries(); + + static void GetCacheBaseDirectoty(nsIFile** result); + static void GetDiskCacheDirectory(nsIFile** result); + static void GetAppCacheDirectory(nsIFile** result); + + /** + * Methods called by any cache classes + */ + + static nsCacheService* GlobalInstance() { return gService; } + + static nsresult DoomEntry(nsCacheEntry* entry); + + static bool IsStorageEnabledForPolicy_Locked(nsCacheStoragePolicy policy); + + /** + * Methods called by nsApplicationCacheService + */ + + nsresult GetOfflineDevice(nsOfflineCacheDevice** aDevice); + + /** + * Creates an offline cache device that works over a specific profile + * directory. A tool to preload offline cache for profiles different from the + * current application's profile directory. + */ + nsresult GetCustomOfflineDevice(nsIFile* aProfileDir, int32_t aQuota, + nsOfflineCacheDevice** aDevice); + + // This method may be called to release an object while the cache service + // lock is being held. If a non-null target is specified and the target + // does not correspond to the current thread, then the release will be + // proxied to the specified target. Otherwise, the object will be added to + // the list of objects to be released when the cache service is unlocked. + static void ReleaseObject_Locked(nsISupports* object, + nsIEventTarget* target = nullptr); + + static nsresult DispatchToCacheIOThread(nsIRunnable* event); + + // Calling this method will block the calling thread until all pending + // events on the cache-io thread has finished. The calling thread must + // hold the cache-lock + static nsresult SyncWithCacheIOThread(); + + /** + * Methods called by nsCacheProfilePrefObserver + */ + static void OnProfileShutdown(); + static void OnProfileChanged(); + + static void SetOfflineCacheEnabled(bool enabled); + // Sets the offline cache capacity (in kilobytes) + static void SetOfflineCacheCapacity(int32_t capacity); + + static void MoveOrRemoveDiskCache(nsIFile* aOldCacheDir, + nsIFile* aNewCacheDir, + const char* aCacheSubdir); + + nsresult Init(); + void Shutdown(); + + static bool IsInitialized() { + if (!gService) { + return false; + } + return gService->mInitialized; + } + + static void AssertOwnsLock() { gService->mLock.AssertCurrentThreadOwns(); } + + static void LeavePrivateBrowsing(); + bool IsDoomListEmpty(); + + typedef bool (*DoomCheckFn)(nsCacheEntry* entry); + + // Accessors to the disabled functionality + nsresult CreateSessionInternal(const char* clientID, + nsCacheStoragePolicy storagePolicy, + bool streamBased, nsICacheSession** result); + nsresult VisitEntriesInternal(nsICacheVisitor* visitor); + nsresult EvictEntriesInternal(nsCacheStoragePolicy storagePolicy); + + private: + friend class nsCacheServiceAutoLock; + friend class nsOfflineCacheDevice; + friend class nsProcessRequestEvent; + friend class nsBlockOnCacheThreadEvent; + friend class nsDoomEvent; + friend class nsAsyncDoomEvent; + friend class nsCacheEntryDescriptor; + + /** + * Internal Methods + */ + + static void Lock(); + static void Lock(::mozilla::Telemetry::HistogramID mainThreadLockerID); + static void Unlock(); + void LockAcquired(); + void LockReleased(); + + nsresult CreateDiskDevice(); + nsresult CreateOfflineDevice(); + nsresult CreateCustomOfflineDevice(nsIFile* aProfileDir, int32_t aQuota, + nsOfflineCacheDevice** aDevice); + nsresult CreateMemoryDevice(); + + nsresult RemoveCustomOfflineDevice(nsOfflineCacheDevice* aDevice); + + nsresult CreateRequest(nsCacheSession* session, const nsACString& clientKey, + nsCacheAccessMode accessRequested, bool blockingMode, + nsICacheListener* listener, nsCacheRequest** request); + + nsresult DoomEntry_Internal(nsCacheEntry* entry, + bool doProcessPendingRequests); + + nsresult EvictEntriesForClient(const char* clientID, + nsCacheStoragePolicy storagePolicy); + + // Notifies request listener asynchronously on the request's thread, and + // releases the descriptor on the request's thread. If this method fails, + // the descriptor is not released. + nsresult NotifyListener(nsCacheRequest* request, + nsICacheEntryDescriptor* descriptor, + nsCacheAccessMode accessGranted, nsresult error); + + nsresult ActivateEntry(nsCacheRequest* request, nsCacheEntry** entry, + nsCacheEntry** doomedEntry); + + nsCacheDevice* EnsureEntryHasDevice(nsCacheEntry* entry); + + nsCacheEntry* SearchCacheDevices(nsCString* key, nsCacheStoragePolicy policy, + bool* collision); + + void DeactivateEntry(nsCacheEntry* entry); + + nsresult ProcessRequest(nsCacheRequest* request, + bool calledFromOpenCacheEntry, + nsICacheEntryDescriptor** result); + + nsresult ProcessPendingRequests(nsCacheEntry* entry); + + void ClearDoomList(void); + void DoomActiveEntries(DoomCheckFn check); + void CloseAllStreams(); + void FireClearNetworkCacheStoredAnywhereNotification(); + + void LogCacheStatistics(); + + /** + * Data Members + */ + + static nsCacheService* gService; // there can be only one... + + nsCOMPtr<mozIStorageService> mStorageService; + + nsCacheProfilePrefObserver* mObserver; + + mozilla::Mutex mLock; + mozilla::CondVar mCondVar; + bool mNotified; + + mozilla::Mutex mTimeStampLock; + mozilla::TimeStamp mLockAcquiredTimeStamp; + + nsCOMPtr<nsIThread> mCacheIOThread; + + nsTArray<nsISupports*> mDoomedObjects; + + bool mInitialized; + bool mClearingEntries; + + bool mEnableOfflineDevice; + + nsOfflineCacheDevice* mOfflineDevice; + + nsRefPtrHashtable<nsStringHashKey, nsOfflineCacheDevice> + mCustomOfflineDevices; + + nsCacheEntryHashTable mActiveEntries; + PRCList mDoomedEntries; + + // stats + + uint32_t mTotalEntries; + uint32_t mCacheHits; + uint32_t mCacheMisses; + uint32_t mMaxKeyLength; + uint32_t mMaxDataSize; + uint32_t mMaxMetaSize; + + // Unexpected error totals + uint32_t mDeactivateFailures; + uint32_t mDeactivatedUnboundEntries; +}; + +/****************************************************************************** + * nsCacheServiceAutoLock + ******************************************************************************/ + +#define LOCK_TELEM(x) \ + (::mozilla::Telemetry::CACHE_SERVICE_LOCK_WAIT_MAINTHREAD_##x) + +// Instantiate this class to acquire the cache service lock for a particular +// execution scope. +class nsCacheServiceAutoLock { + public: + nsCacheServiceAutoLock() { nsCacheService::Lock(); } + explicit nsCacheServiceAutoLock( + mozilla::Telemetry::HistogramID mainThreadLockerID) { + nsCacheService::Lock(mainThreadLockerID); + } + ~nsCacheServiceAutoLock() { nsCacheService::Unlock(); } +}; + +#endif // _nsCacheService_h_ diff --git a/netwerk/cache/nsCacheSession.cpp b/netwerk/cache/nsCacheSession.cpp new file mode 100644 index 0000000000..3e4a1f92da --- /dev/null +++ b/netwerk/cache/nsCacheSession.cpp @@ -0,0 +1,121 @@ +/* -*- 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 "nsCacheSession.h" +#include "nsCacheService.h" +#include "nsCRT.h" +#include "nsThreadUtils.h" + +NS_IMPL_ISUPPORTS(nsCacheSession, nsICacheSession) + +nsCacheSession::nsCacheSession(const char* clientID, + nsCacheStoragePolicy storagePolicy, + bool streamBased) + : mClientID(clientID), mInfo(0) { + SetStoragePolicy(storagePolicy); + + if (streamBased) + MarkStreamBased(); + else + SetStoragePolicy(nsICache::STORE_IN_MEMORY); + + MarkPublic(); + + MarkDoomEntriesIfExpired(); +} + +nsCacheSession::~nsCacheSession() { + /* destructor code */ + // notify service we are going away? +} + +NS_IMETHODIMP nsCacheSession::GetDoomEntriesIfExpired(bool* result) { + NS_ENSURE_ARG_POINTER(result); + *result = WillDoomEntriesIfExpired(); + return NS_OK; +} + +NS_IMETHODIMP nsCacheSession::SetProfileDirectory(nsIFile* profileDir) { + if (StoragePolicy() != nsICache::STORE_OFFLINE && profileDir) { + // Profile directory override is currently implemented only for + // offline cache. This is an early failure to prevent the request + // being processed before it would fail later because of inability + // to assign a cache base dir. + return NS_ERROR_UNEXPECTED; + } + + mProfileDir = profileDir; + return NS_OK; +} + +NS_IMETHODIMP nsCacheSession::GetProfileDirectory(nsIFile** profileDir) { + *profileDir = do_AddRef(mProfileDir).take(); + return NS_OK; +} + +NS_IMETHODIMP nsCacheSession::SetDoomEntriesIfExpired( + bool doomEntriesIfExpired) { + if (doomEntriesIfExpired) + MarkDoomEntriesIfExpired(); + else + ClearDoomEntriesIfExpired(); + return NS_OK; +} + +NS_IMETHODIMP +nsCacheSession::OpenCacheEntry(const nsACString& key, + nsCacheAccessMode accessRequested, + bool blockingMode, + nsICacheEntryDescriptor** result) { + nsresult rv; + + if (NS_IsMainThread()) + rv = NS_ERROR_NOT_AVAILABLE; + else + rv = + nsCacheService::OpenCacheEntry(this, key, accessRequested, blockingMode, + nullptr, // no listener + result); + return rv; +} + +NS_IMETHODIMP nsCacheSession::AsyncOpenCacheEntry( + const nsACString& key, nsCacheAccessMode accessRequested, + nsICacheListener* listener, bool noWait) { + nsresult rv; + rv = nsCacheService::OpenCacheEntry(this, key, accessRequested, !noWait, + listener, + nullptr); // no result + + if (rv == NS_ERROR_CACHE_WAIT_FOR_VALIDATION) rv = NS_OK; + return rv; +} + +NS_IMETHODIMP nsCacheSession::EvictEntries() { + return nsCacheService::EvictEntriesForSession(this); +} + +NS_IMETHODIMP nsCacheSession::IsStorageEnabled(bool* result) { + return nsCacheService::IsStorageEnabledForPolicy(StoragePolicy(), result); +} + +NS_IMETHODIMP nsCacheSession::DoomEntry(const nsACString& key, + nsICacheListener* listener) { + return nsCacheService::DoomEntry(this, key, listener); +} + +NS_IMETHODIMP nsCacheSession::GetIsPrivate(bool* aPrivate) { + *aPrivate = IsPrivate(); + return NS_OK; +} + +NS_IMETHODIMP nsCacheSession::SetIsPrivate(bool aPrivate) { + if (aPrivate) + MarkPrivate(); + else + MarkPublic(); + return NS_OK; +} diff --git a/netwerk/cache/nsCacheSession.h b/netwerk/cache/nsCacheSession.h new file mode 100644 index 0000000000..59bb748231 --- /dev/null +++ b/netwerk/cache/nsCacheSession.h @@ -0,0 +1,67 @@ +/* -*- 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/. */ + +#ifndef _nsCacheSession_h_ +#define _nsCacheSession_h_ + +#include "nspr.h" +#include "nsError.h" +#include "nsCOMPtr.h" +#include "nsICacheSession.h" +#include "nsIFile.h" +#include "nsString.h" + +class nsCacheSession : public nsICacheSession { + virtual ~nsCacheSession(); + + public: + NS_DECL_ISUPPORTS + NS_DECL_NSICACHESESSION + + nsCacheSession(const char* clientID, nsCacheStoragePolicy storagePolicy, + bool streamBased); + + nsCString* ClientID() { return &mClientID; } + + enum SessionInfo { + eStoragePolicyMask = 0x000000FF, + eStreamBasedMask = 0x00000100, + eDoomEntriesIfExpiredMask = 0x00001000, + ePrivateMask = 0x00010000 + }; + + void MarkStreamBased() { mInfo |= eStreamBasedMask; } + void ClearStreamBased() { mInfo &= ~eStreamBasedMask; } + bool IsStreamBased() { return (mInfo & eStreamBasedMask) != 0; } + + void MarkDoomEntriesIfExpired() { mInfo |= eDoomEntriesIfExpiredMask; } + void ClearDoomEntriesIfExpired() { mInfo &= ~eDoomEntriesIfExpiredMask; } + bool WillDoomEntriesIfExpired() { + return (0 != (mInfo & eDoomEntriesIfExpiredMask)); + } + + void MarkPrivate() { mInfo |= ePrivateMask; } + void MarkPublic() { mInfo &= ~ePrivateMask; } + bool IsPrivate() { return (mInfo & ePrivateMask) != 0; } + nsCacheStoragePolicy StoragePolicy() { + return (nsCacheStoragePolicy)(mInfo & eStoragePolicyMask); + } + + void SetStoragePolicy(nsCacheStoragePolicy policy) { + NS_ASSERTION(policy <= 0xFF, "too many bits in nsCacheStoragePolicy"); + mInfo &= ~eStoragePolicyMask; // clear storage policy bits + mInfo |= policy; + } + + nsIFile* ProfileDir() { return mProfileDir; } + + private: + nsCString mClientID; + uint32_t mInfo; + nsCOMPtr<nsIFile> mProfileDir; +}; + +#endif // _nsCacheSession_h_ diff --git a/netwerk/cache/nsCacheUtils.cpp b/netwerk/cache/nsCacheUtils.cpp new file mode 100644 index 0000000000..88bcabce12 --- /dev/null +++ b/netwerk/cache/nsCacheUtils.cpp @@ -0,0 +1,78 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et cindent: */ +/* 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 "nsCache.h" +#include "nsCacheUtils.h" +#include "nsThreadUtils.h" + +using namespace mozilla; + +class nsDestroyThreadEvent : public Runnable { + public: + explicit nsDestroyThreadEvent(nsIThread* thread) + : mozilla::Runnable("nsDestroyThreadEvent"), mThread(thread) {} + NS_IMETHOD Run() override { + mThread->Shutdown(); + return NS_OK; + } + + private: + nsCOMPtr<nsIThread> mThread; +}; + +nsShutdownThread::nsShutdownThread(nsIThread* aThread) + : mozilla::Runnable("nsShutdownThread"), + mMonitor("nsShutdownThread.mMonitor"), + mShuttingDown(false), + mThread(aThread) {} + +nsresult nsShutdownThread::Shutdown(nsIThread* aThread) { + nsresult rv; + RefPtr<nsDestroyThreadEvent> ev = new nsDestroyThreadEvent(aThread); + rv = NS_DispatchToMainThread(ev); + if (NS_FAILED(rv)) { + NS_WARNING("Dispatching event in nsShutdownThread::Shutdown failed!"); + } + return rv; +} + +nsresult nsShutdownThread::BlockingShutdown(nsIThread* aThread) { + nsresult rv; + + RefPtr<nsShutdownThread> st = new nsShutdownThread(aThread); + nsCOMPtr<nsIThread> workerThread; + + rv = NS_NewNamedThread("thread shutdown", getter_AddRefs(workerThread)); + if (NS_FAILED(rv)) { + NS_WARNING("Can't create nsShutDownThread worker thread!"); + return rv; + } + + { + MonitorAutoLock mon(st->mMonitor); + rv = workerThread->Dispatch(st, NS_DISPATCH_NORMAL); + if (NS_FAILED(rv)) { + NS_WARNING( + "Dispatching event in nsShutdownThread::BlockingShutdown failed!"); + } else { + st->mShuttingDown = true; + while (st->mShuttingDown) { + mon.Wait(); + } + } + } + + return Shutdown(workerThread); +} + +NS_IMETHODIMP +nsShutdownThread::Run() { + MonitorAutoLock mon(mMonitor); + mThread->Shutdown(); + mShuttingDown = false; + mon.Notify(); + return NS_OK; +} diff --git a/netwerk/cache/nsCacheUtils.h b/netwerk/cache/nsCacheUtils.h new file mode 100644 index 0000000000..71f3056f89 --- /dev/null +++ b/netwerk/cache/nsCacheUtils.h @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set sw=2 ts=8 et 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/. */ + +#ifndef _nsCacheUtils_h_ +#define _nsCacheUtils_h_ + +#include "nsThreadUtils.h" +#include "nsCOMPtr.h" +#include "mozilla/Monitor.h" + +class nsIThread; + +/** + * A class with utility methods for shutting down nsIThreads easily. + */ +class nsShutdownThread : public mozilla::Runnable { + public: + explicit nsShutdownThread(nsIThread* aThread); + ~nsShutdownThread() = default; + + NS_IMETHOD Run() override; + + /** + * Shutdown ensures that aThread->Shutdown() is called on a main thread + */ + static nsresult Shutdown(nsIThread* aThread); + + /** + * BlockingShutdown ensures that by the time it returns, aThread->Shutdown() + * has been called and no pending events have been processed on the current + * thread. + */ + static nsresult BlockingShutdown(nsIThread* aThread); + + private: + mozilla::Monitor mMonitor; + bool mShuttingDown; + nsCOMPtr<nsIThread> mThread; +}; + +#endif diff --git a/netwerk/cache/nsDeleteDir.cpp b/netwerk/cache/nsDeleteDir.cpp new file mode 100644 index 0000000000..f99896b721 --- /dev/null +++ b/netwerk/cache/nsDeleteDir.cpp @@ -0,0 +1,362 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et cindent: */ +/* 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 "nsDeleteDir.h" +#include "nsIFile.h" +#include "nsString.h" +#include "mozilla/Telemetry.h" +#include "nsITimer.h" +#include "nsThreadUtils.h" +#include "nsISupportsPriority.h" +#include "nsCacheUtils.h" +#include "prtime.h" +#include <time.h> + +using namespace mozilla; + +class nsBlockOnBackgroundThreadEvent : public Runnable { + public: + nsBlockOnBackgroundThreadEvent() + : mozilla::Runnable("nsBlockOnBackgroundThreadEvent") {} + NS_IMETHOD Run() override { + MutexAutoLock lock(nsDeleteDir::gInstance->mLock); + nsDeleteDir::gInstance->mNotified = true; + nsDeleteDir::gInstance->mCondVar.Notify(); + return NS_OK; + } +}; + +nsDeleteDir* nsDeleteDir::gInstance = nullptr; + +nsDeleteDir::nsDeleteDir() + : mLock("nsDeleteDir.mLock"), + mCondVar(mLock, "nsDeleteDir.mCondVar"), + mNotified(false), + mShutdownPending(false), + mStopDeleting(false) { + NS_ASSERTION(gInstance == nullptr, "multiple nsCacheService instances!"); +} + +nsDeleteDir::~nsDeleteDir() { gInstance = nullptr; } + +nsresult nsDeleteDir::Init() { + if (gInstance) return NS_ERROR_ALREADY_INITIALIZED; + + gInstance = new nsDeleteDir(); + return NS_OK; +} + +nsresult nsDeleteDir::Shutdown(bool finishDeleting) { + if (!gInstance) return NS_ERROR_NOT_INITIALIZED; + + nsCOMArray<nsIFile> dirsToRemove; + nsCOMPtr<nsISerialEventTarget> eventTarget; + { + MutexAutoLock lock(gInstance->mLock); + NS_ASSERTION(!gInstance->mShutdownPending, + "Unexpected state in nsDeleteDir::Shutdown()"); + gInstance->mShutdownPending = true; + + if (!finishDeleting) gInstance->mStopDeleting = true; + + // remove all pending timers + for (int32_t i = gInstance->mTimers.Count(); i > 0; i--) { + nsCOMPtr<nsITimer> timer = gInstance->mTimers[i - 1]; + gInstance->mTimers.RemoveObjectAt(i - 1); + + nsCOMArray<nsIFile>* arg; + timer->GetClosure((reinterpret_cast<void**>(&arg))); + timer->Cancel(); + + if (finishDeleting) dirsToRemove.AppendObjects(*arg); + + // delete argument passed to the timer + delete arg; + } + + eventTarget.swap(gInstance->mBackgroundET); + if (eventTarget) { + // dispatch event and wait for it to run and notify us, so we know thread + // has completed all work and can be shutdown + nsCOMPtr<nsIRunnable> event = new nsBlockOnBackgroundThreadEvent(); + nsresult rv = eventTarget->Dispatch(event, NS_DISPATCH_EVENT_MAY_BLOCK); + if (NS_FAILED(rv)) { + NS_WARNING("Failed dispatching block-event"); + return NS_ERROR_UNEXPECTED; + } + + gInstance->mNotified = false; + while (!gInstance->mNotified) { + gInstance->mCondVar.Wait(); + } + } + } + + delete gInstance; + + for (int32_t i = 0; i < dirsToRemove.Count(); i++) + dirsToRemove[i]->Remove(true); + + return NS_OK; +} + +nsresult nsDeleteDir::InitThread() { + if (mBackgroundET) return NS_OK; + + nsresult rv = NS_CreateBackgroundTaskQueue("Cache Deleter", + getter_AddRefs(mBackgroundET)); + if (NS_FAILED(rv)) { + NS_WARNING("Can't create background task queue"); + return rv; + } + + return NS_OK; +} + +void nsDeleteDir::DestroyThread() { + if (!mBackgroundET) return; + + if (mTimers.Count()) + // more work to do, so don't delete thread. + return; + + mBackgroundET = nullptr; +} + +void nsDeleteDir::TimerCallback(nsITimer* aTimer, void* arg) { + Telemetry::AutoTimer<Telemetry::NETWORK_DISK_CACHE_DELETEDIR> timer; + { + MutexAutoLock lock(gInstance->mLock); + + int32_t idx = gInstance->mTimers.IndexOf(aTimer); + if (idx == -1) { + // Timer was canceled and removed during shutdown. + return; + } + + gInstance->mTimers.RemoveObjectAt(idx); + } + + UniquePtr<nsCOMArray<nsIFile>> dirList; + dirList.reset(static_cast<nsCOMArray<nsIFile>*>(arg)); + + bool shuttingDown = false; + + // Intentional extra braces to control variable sope. + { + // Low IO priority can only be set when running in the context of the + // current thread. So this shouldn't be moved to where we set the priority + // of the Cache deleter thread using the nsThread's NSPR priority constants. + nsAutoLowPriorityIO autoLowPriority; + for (int32_t i = 0; i < dirList->Count() && !shuttingDown; i++) { + gInstance->RemoveDir((*dirList)[i], &shuttingDown); + } + } + + { + MutexAutoLock lock(gInstance->mLock); + gInstance->DestroyThread(); + } +} + +nsresult nsDeleteDir::DeleteDir(nsIFile* dirIn, bool moveToTrash, + uint32_t delay) { + Telemetry::AutoTimer<Telemetry::NETWORK_DISK_CACHE_TRASHRENAME> timer; + + if (!gInstance) return NS_ERROR_NOT_INITIALIZED; + + nsresult rv; + nsCOMPtr<nsIFile> trash, dir; + + // Need to make a clone of this since we don't want to modify the input + // file object. + rv = dirIn->Clone(getter_AddRefs(dir)); + if (NS_FAILED(rv)) return rv; + + if (moveToTrash) { + rv = GetTrashDir(dir, &trash); + if (NS_FAILED(rv)) return rv; + nsAutoCString origLeaf; + rv = trash->GetNativeLeafName(origLeaf); + if (NS_FAILED(rv)) return rv; + + // Append random number to the trash directory and check if it exists. + srand(static_cast<unsigned>(PR_Now())); + nsAutoCString leaf; + for (int32_t i = 0; i < 10; i++) { + leaf = origLeaf; + leaf.AppendInt(rand()); + rv = trash->SetNativeLeafName(leaf); + if (NS_FAILED(rv)) return rv; + + bool exists; + if (NS_SUCCEEDED(trash->Exists(&exists)) && !exists) { + break; + } + + leaf.Truncate(); + } + + // Fail if we didn't find unused trash directory within the limit + if (!leaf.Length()) return NS_ERROR_FAILURE; + +#if defined(MOZ_WIDGET_ANDROID) + nsCOMPtr<nsIFile> parent; + rv = trash->GetParent(getter_AddRefs(parent)); + if (NS_FAILED(rv)) return rv; + rv = dir->MoveToNative(parent, leaf); +#else + // Important: must rename directory w/o changing parent directory: else on + // NTFS we'll wait (with cache lock) while nsIFile's ACL reset walks file + // tree: was hanging GUI for *minutes* on large cache dirs. + rv = dir->MoveToNative(nullptr, leaf); +#endif + if (NS_FAILED(rv)) return rv; + } else { + // we want to pass a clone of the original off to the worker thread. + trash.swap(dir); + } + + UniquePtr<nsCOMArray<nsIFile>> arg(new nsCOMArray<nsIFile>); + arg->AppendObject(trash); + + rv = gInstance->PostTimer(arg.get(), delay); + if (NS_FAILED(rv)) return rv; + + Unused << arg.release(); + return NS_OK; +} + +nsresult nsDeleteDir::GetTrashDir(nsIFile* target, nsCOMPtr<nsIFile>* result) { + nsresult rv; +#if defined(MOZ_WIDGET_ANDROID) + // Try to use the app cache folder for cache trash on Android + char* cachePath = getenv("CACHE_DIRECTORY"); + if (cachePath) { + rv = NS_NewNativeLocalFile(nsDependentCString(cachePath), true, + getter_AddRefs(*result)); + if (NS_FAILED(rv)) return rv; + + // Add a sub folder with the cache folder name + nsAutoCString leaf; + rv = target->GetNativeLeafName(leaf); + (*result)->AppendNative(leaf); + } else +#endif + { + rv = target->Clone(getter_AddRefs(*result)); + } + if (NS_FAILED(rv)) return rv; + + nsAutoCString leaf; + rv = (*result)->GetNativeLeafName(leaf); + if (NS_FAILED(rv)) return rv; + leaf.AppendLiteral(".Trash"); + + return (*result)->SetNativeLeafName(leaf); +} + +nsresult nsDeleteDir::RemoveOldTrashes(nsIFile* cacheDir) { + if (!gInstance) return NS_ERROR_NOT_INITIALIZED; + + nsresult rv; + + nsCOMPtr<nsIFile> trash; + rv = GetTrashDir(cacheDir, &trash); + if (NS_FAILED(rv)) return rv; + + nsAutoString trashName; + rv = trash->GetLeafName(trashName); + if (NS_FAILED(rv)) return rv; + + nsCOMPtr<nsIFile> parent; +#if defined(MOZ_WIDGET_ANDROID) + rv = trash->GetParent(getter_AddRefs(parent)); +#else + rv = cacheDir->GetParent(getter_AddRefs(parent)); +#endif + if (NS_FAILED(rv)) return rv; + + nsCOMPtr<nsIDirectoryEnumerator> iter; + rv = parent->GetDirectoryEntries(getter_AddRefs(iter)); + if (NS_FAILED(rv)) return rv; + + UniquePtr<nsCOMArray<nsIFile>> dirList; + + nsCOMPtr<nsIFile> file; + while (NS_SUCCEEDED(iter->GetNextFile(getter_AddRefs(file))) && file) { + nsAutoString leafName; + rv = file->GetLeafName(leafName); + if (NS_FAILED(rv)) continue; + + // match all names that begin with the trash name (i.e. "Cache.Trash") + if (Substring(leafName, 0, trashName.Length()).Equals(trashName)) { + if (!dirList) dirList = MakeUnique<nsCOMArray<nsIFile>>(); + dirList->AppendObject(file); + } + } + + if (dirList) { + rv = gInstance->PostTimer(dirList.get(), 90000); + if (NS_FAILED(rv)) return rv; + + Unused << dirList.release(); + } + + return NS_OK; +} + +nsresult nsDeleteDir::PostTimer(void* arg, uint32_t delay) { + nsresult rv; + + MutexAutoLock lock(mLock); + + rv = InitThread(); + if (NS_FAILED(rv)) return rv; + + nsCOMPtr<nsITimer> timer; + rv = NS_NewTimerWithFuncCallback(getter_AddRefs(timer), TimerCallback, arg, + delay, nsITimer::TYPE_ONE_SHOT, + "nsDeleteDir::PostTimer", mBackgroundET); + if (NS_FAILED(rv)) return rv; + + mTimers.AppendObject(timer); + return NS_OK; +} + +nsresult nsDeleteDir::RemoveDir(nsIFile* file, bool* stopDeleting) { + nsresult rv; + bool isLink; + + rv = file->IsSymlink(&isLink); + if (NS_FAILED(rv) || isLink) return NS_ERROR_UNEXPECTED; + + bool isDir; + rv = file->IsDirectory(&isDir); + if (NS_FAILED(rv)) return rv; + + if (isDir) { + nsCOMPtr<nsIDirectoryEnumerator> iter; + rv = file->GetDirectoryEntries(getter_AddRefs(iter)); + if (NS_FAILED(rv)) return rv; + + nsCOMPtr<nsIFile> file2; + while (NS_SUCCEEDED(iter->GetNextFile(getter_AddRefs(file2))) && file2) { + RemoveDir(file2, stopDeleting); + // No check for errors to remove as much as possible + + if (*stopDeleting) return NS_OK; + } + } + + file->Remove(false); + // No check for errors to remove as much as possible + + MutexAutoLock lock(mLock); + if (mStopDeleting) *stopDeleting = true; + + return NS_OK; +} diff --git a/netwerk/cache/nsDeleteDir.h b/netwerk/cache/nsDeleteDir.h new file mode 100644 index 0000000000..cf6de26dde --- /dev/null +++ b/netwerk/cache/nsDeleteDir.h @@ -0,0 +1,79 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et cindent: */ +/* 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/. */ + +#ifndef nsDeleteDir_h__ +#define nsDeleteDir_h__ + +#include "nsCOMPtr.h" +#include "nsCOMArray.h" +#include "mozilla/Mutex.h" +#include "mozilla/CondVar.h" + +class nsIFile; +class nsISerialEventTarget; +class nsITimer; + +class nsDeleteDir { + public: + nsDeleteDir(); + ~nsDeleteDir(); + + static nsresult Init(); + static nsresult Shutdown(bool finishDeleting); + + /** + * This routine attempts to delete a directory that may contain some files + * that are still in use. This latter point is only an issue on Windows and + * a few other systems. + * + * If the moveToTrash parameter is true we first rename the given directory + * "foo.Trash123" (where "foo" is the original directory name, and "123" is + * a random number, in order to support multiple concurrent deletes). The + * directory is then deleted, file-by-file, on a background thread. + * + * If the moveToTrash parameter is false, then the given directory is deleted + * directly. + * + * If 'delay' is non-zero, the directory will not be deleted until the + * specified number of milliseconds have passed. (The directory is still + * renamed immediately if 'moveToTrash' is passed, so upon return it is safe + * to create a directory with the same name). + */ + static nsresult DeleteDir(nsIFile* dir, bool moveToTrash, uint32_t delay = 0); + + /** + * Returns the trash directory corresponding to the given directory. + */ + static nsresult GetTrashDir(nsIFile* dir, nsCOMPtr<nsIFile>* result); + + /** + * Remove all trashes left from previous run. This function does nothing when + * called second and more times. + */ + static nsresult RemoveOldTrashes(nsIFile* cacheDir); + + static void TimerCallback(nsITimer* aTimer, void* arg); + + private: + friend class nsBlockOnBackgroundThreadEvent; + friend class nsDestroyThreadEvent; + + nsresult InitThread(); + void DestroyThread(); + nsresult PostTimer(void* arg, uint32_t delay); + nsresult RemoveDir(nsIFile* file, bool* stopDeleting); + + static nsDeleteDir* gInstance; + mozilla::Mutex mLock; + mozilla::CondVar mCondVar; + bool mNotified; + nsCOMArray<nsITimer> mTimers; + nsCOMPtr<nsISerialEventTarget> mBackgroundET; + bool mShutdownPending; + bool mStopDeleting; +}; + +#endif // nsDeleteDir_h__ diff --git a/netwerk/cache/nsDiskCache.h b/netwerk/cache/nsDiskCache.h new file mode 100644 index 0000000000..e01860b7bf --- /dev/null +++ b/netwerk/cache/nsDiskCache.h @@ -0,0 +1,72 @@ +/* -*- 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/. */ + +#ifndef _nsDiskCache_h_ +#define _nsDiskCache_h_ + +#include "nsCacheEntry.h" + +#ifdef XP_WIN +# include <winsock.h> // for htonl/ntohl +#endif + +class nsDiskCache { + public: + enum { + kCurrentVersion = + 0x00010013 // format = 16 bits major version/16 bits minor version + }; + + enum { kData, kMetaData }; + + // Stores the reason why the cache is corrupt. + // Note: I'm only listing the enum values explicitly for easy mapping when + // looking at telemetry data. + enum CorruptCacheInfo { + kNotCorrupt = 0, + kInvalidArgPointer = 1, + kUnexpectedError = 2, + kOpenCacheMapError = 3, + kBlockFilesShouldNotExist = 4, + kOutOfMemory = 5, + kCreateCacheSubdirectories = 6, + kBlockFilesShouldExist = 7, + kHeaderSizeNotRead = 8, + kHeaderIsDirty = 9, + kVersionMismatch = 10, + kRecordsIncomplete = 11, + kHeaderIncomplete = 12, + kNotEnoughToRead = 13, + kEntryCountIncorrect = 14, + kCouldNotGetBlockFileForIndex = 15, + kCouldNotCreateBlockFile = 16, + kBlockFileSizeError = 17, + kBlockFileBitMapWriteError = 18, + kBlockFileSizeLessThanBitMap = 19, + kBlockFileBitMapReadError = 20, + kBlockFileEstimatedSizeError = 21, + kFlushHeaderError = 22, + kCacheCleanFilePathError = 23, + kCacheCleanOpenFileError = 24, + kCacheCleanTimerError = 25 + }; + + // Parameter initval initializes internal state of hash function. Hash values + // are different for the same text when different initval is used. It can be + // any random number. + // + // It can be used for generating 64-bit hash value: + // (uint64_t(Hash(key, initval1)) << 32) | Hash(key, initval2) + // + // It can be also used to hash multiple strings: + // h = Hash(string1, 0); + // h = Hash(string2, h); + // ... + static PLDHashNumber Hash(const char* key, PLDHashNumber initval = 0); + static nsresult Truncate(PRFileDesc* fd, uint32_t newEOF); +}; + +#endif // _nsDiskCache_h_ diff --git a/netwerk/cache/nsDiskCacheDeviceSQL.cpp b/netwerk/cache/nsDiskCacheDeviceSQL.cpp new file mode 100644 index 0000000000..b2523a4d3f --- /dev/null +++ b/netwerk/cache/nsDiskCacheDeviceSQL.cpp @@ -0,0 +1,2608 @@ +/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim:set ts=2 sw=2 sts=2 et cin: */ +/* 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 <inttypes.h> + +#include "mozilla/ArrayUtils.h" +#include "mozilla/Attributes.h" +#include "mozilla/Sprintf.h" +#include "mozilla/ThreadLocal.h" + +#include "nsCache.h" +#include "nsDiskCache.h" +#include "nsDiskCacheDeviceSQL.h" +#include "nsCacheService.h" +#include "nsApplicationCache.h" +#include "../cache2/CacheHashUtils.h" + +#include "nsNetCID.h" +#include "nsNetUtil.h" +#include "nsIURI.h" +#include "nsEscape.h" +#include "nsIPrefBranch.h" +#include "nsString.h" +#include "nsPrintfCString.h" +#include "nsCRT.h" +#include "nsArrayUtils.h" +#include "nsIArray.h" +#include "nsIVariant.h" +#include "nsILoadContextInfo.h" +#include "nsThreadUtils.h" +#include "nsISerializable.h" +#include "nsIInputStream.h" +#include "nsIOutputStream.h" +#include "nsSerializationHelper.h" +#include "nsMemory.h" + +#include "mozIStorageService.h" +#include "mozIStorageStatement.h" +#include "mozIStorageFunction.h" +#include "mozStorageHelper.h" + +#include "nsICacheVisitor.h" +#include "nsISeekableStream.h" + +#include "mozilla/Telemetry.h" + +#include "mozilla/storage.h" +#include "nsVariant.h" +#include "mozilla/BasePrincipal.h" + +using namespace mozilla; +using namespace mozilla::storage; +using mozilla::OriginAttributes; + +static const char OFFLINE_CACHE_DEVICE_ID[] = {"offline"}; + +#define LOG(args) CACHE_LOG_DEBUG(args) + +static uint32_t gNextTemporaryClientID = 0; + +/***************************************************************************** + * helpers + */ + +static nsresult EnsureDir(nsIFile* dir) { + bool exists; + nsresult rv = dir->Exists(&exists); + if (NS_SUCCEEDED(rv) && !exists) + rv = dir->Create(nsIFile::DIRECTORY_TYPE, 0700); + return rv; +} + +static bool DecomposeCacheEntryKey(const nsCString* fullKey, const char** cid, + const char** key, nsCString& buf) { + buf = *fullKey; + + int32_t colon = buf.FindChar(':'); + if (colon == kNotFound) { + NS_ERROR("Invalid key"); + return false; + } + buf.SetCharAt('\0', colon); + + *cid = buf.get(); + *key = buf.get() + colon + 1; + + return true; +} + +class AutoResetStatement { + public: + explicit AutoResetStatement(mozIStorageStatement* s) : mStatement(s) {} + ~AutoResetStatement() { mStatement->Reset(); } + mozIStorageStatement* operator->() MOZ_NO_ADDREF_RELEASE_ON_RETURN { + return mStatement; + } + + private: + mozIStorageStatement* mStatement; +}; + +class EvictionObserver { + public: + EvictionObserver(mozIStorageConnection* db, + nsOfflineCacheEvictionFunction* evictionFunction) + : mDB(db), mEvictionFunction(evictionFunction) { + mEvictionFunction->Init(); + mDB->ExecuteSimpleSQL( + nsLiteralCString("CREATE TEMP TRIGGER cache_on_delete BEFORE DELETE" + " ON moz_cache FOR EACH ROW BEGIN SELECT" + " cache_eviction_observer(" + " OLD.ClientID, OLD.key, OLD.generation);" + " END;")); + } + + ~EvictionObserver() { + mDB->ExecuteSimpleSQL("DROP TRIGGER cache_on_delete;"_ns); + mEvictionFunction->Reset(); + } + + void Apply() { return mEvictionFunction->Apply(); } + + private: + mozIStorageConnection* mDB; + RefPtr<nsOfflineCacheEvictionFunction> mEvictionFunction; +}; + +#define DCACHE_HASH_MAX INT64_MAX +#define DCACHE_HASH_BITS 64 + +/** + * nsOfflineCache::Hash(const char * key) + * + * This algorithm of this method implies nsOfflineCacheRecords will be stored + * in a certain order on disk. If the algorithm changes, existing cache + * map files may become invalid, and therefore the kCurrentVersion needs + * to be revised. + */ +static uint64_t DCacheHash(const char* key) { + // initval 0x7416f295 was chosen randomly + return (uint64_t(CacheHash::Hash(key, strlen(key), 0)) << 32) | + CacheHash::Hash(key, strlen(key), 0x7416f295); +} + +/****************************************************************************** + * nsOfflineCacheEvictionFunction + */ + +NS_IMPL_ISUPPORTS(nsOfflineCacheEvictionFunction, mozIStorageFunction) + +// helper function for directly exposing the same data file binding +// path algorithm used in nsOfflineCacheBinding::Create +static nsresult GetCacheDataFile(nsIFile* cacheDir, const char* key, + int generation, nsCOMPtr<nsIFile>& file) { + cacheDir->Clone(getter_AddRefs(file)); + if (!file) return NS_ERROR_OUT_OF_MEMORY; + + uint64_t hash = DCacheHash(key); + + uint32_t dir1 = (uint32_t)(hash & 0x0F); + uint32_t dir2 = (uint32_t)((hash & 0xF0) >> 4); + + hash >>= 8; + + file->AppendNative(nsPrintfCString("%X", dir1)); + file->AppendNative(nsPrintfCString("%X", dir2)); + + char leaf[64]; + SprintfLiteral(leaf, "%014" PRIX64 "-%X", hash, generation); + return file->AppendNative(nsDependentCString(leaf)); +} + +namespace appcachedetail { + +typedef nsCOMArray<nsIFile> FileArray; +static MOZ_THREAD_LOCAL(FileArray*) tlsEvictionItems; + +} // namespace appcachedetail + +NS_IMETHODIMP +nsOfflineCacheEvictionFunction::OnFunctionCall(mozIStorageValueArray* values, + nsIVariant** _retval) { + LOG(("nsOfflineCacheEvictionFunction::OnFunctionCall\n")); + + *_retval = nullptr; + + uint32_t numEntries; + nsresult rv = values->GetNumEntries(&numEntries); + NS_ENSURE_SUCCESS(rv, rv); + NS_ASSERTION(numEntries == 3, "unexpected number of arguments"); + + uint32_t valueLen; + const char* clientID = values->AsSharedUTF8String(0, &valueLen); + const char* key = values->AsSharedUTF8String(1, &valueLen); + nsAutoCString fullKey(clientID); + fullKey.Append(':'); + fullKey.Append(key); + int generation = values->AsInt32(2); + + // If the key is currently locked, refuse to delete this row. + if (mDevice->IsLocked(fullKey)) { + // This code thought it was performing the equivalent of invoking the SQL + // "RAISE(IGNORE)" function. It was not. Please see bug 1470961 and any + // follow-ups to understand the plan for correcting this bug. + return NS_OK; + } + + nsCOMPtr<nsIFile> file; + rv = GetCacheDataFile(mDevice->CacheDirectory(), key, generation, file); + if (NS_FAILED(rv)) { + LOG(("GetCacheDataFile [key=%s generation=%d] failed [rv=%" PRIx32 "]!\n", + key, generation, static_cast<uint32_t>(rv))); + return rv; + } + + appcachedetail::FileArray* items = appcachedetail::tlsEvictionItems.get(); + MOZ_ASSERT(items); + if (items) { + items->AppendObject(file); + } + + return NS_OK; +} + +nsOfflineCacheEvictionFunction::nsOfflineCacheEvictionFunction( + nsOfflineCacheDevice* device) + : mDevice(device) { + mTLSInited = appcachedetail::tlsEvictionItems.init(); +} + +void nsOfflineCacheEvictionFunction::Init() { + if (mTLSInited) { + appcachedetail::tlsEvictionItems.set(new appcachedetail::FileArray()); + } +} + +void nsOfflineCacheEvictionFunction::Reset() { + if (!mTLSInited) { + return; + } + + appcachedetail::FileArray* items = appcachedetail::tlsEvictionItems.get(); + if (!items) { + return; + } + + appcachedetail::tlsEvictionItems.set(nullptr); + delete items; +} + +void nsOfflineCacheEvictionFunction::Apply() { + LOG(("nsOfflineCacheEvictionFunction::Apply\n")); + + if (!mTLSInited) { + return; + } + + appcachedetail::FileArray* pitems = appcachedetail::tlsEvictionItems.get(); + if (!pitems) { + return; + } + + appcachedetail::FileArray items = std::move(*pitems); + + for (int32_t i = 0; i < items.Count(); i++) { + if (MOZ_LOG_TEST(gCacheLog, LogLevel::Debug)) { + LOG((" removing %s\n", items[i]->HumanReadablePath().get())); + } + + items[i]->Remove(false); + } +} + +class nsOfflineCacheDiscardCache : public Runnable { + public: + nsOfflineCacheDiscardCache(nsOfflineCacheDevice* device, nsCString& group, + nsCString& clientID) + : mozilla::Runnable("nsOfflineCacheDiscardCache"), + mDevice(device), + mGroup(group), + mClientID(clientID) {} + + NS_IMETHOD Run() override { + if (mDevice->IsActiveCache(mGroup, mClientID)) { + mDevice->DeactivateGroup(mGroup); + } + + return mDevice->EvictEntries(mClientID.get()); + } + + private: + RefPtr<nsOfflineCacheDevice> mDevice; + nsCString mGroup; + nsCString mClientID; +}; + +/****************************************************************************** + * nsOfflineCacheDeviceInfo + */ + +class nsOfflineCacheDeviceInfo final : public nsICacheDeviceInfo { + public: + NS_DECL_ISUPPORTS + NS_DECL_NSICACHEDEVICEINFO + + explicit nsOfflineCacheDeviceInfo(nsOfflineCacheDevice* device) + : mDevice(device) {} + + private: + ~nsOfflineCacheDeviceInfo() = default; + + nsOfflineCacheDevice* mDevice; +}; + +NS_IMPL_ISUPPORTS(nsOfflineCacheDeviceInfo, nsICacheDeviceInfo) + +NS_IMETHODIMP +nsOfflineCacheDeviceInfo::GetDescription(nsACString& aDescription) { + aDescription.AssignLiteral("Offline cache device"); + return NS_OK; +} + +NS_IMETHODIMP +nsOfflineCacheDeviceInfo::GetUsageReport(nsACString& aUsageReport) { + nsAutoCString buffer; + buffer.AssignLiteral( + " <tr>\n" + " <th>Cache Directory:</th>\n" + " <td>"); + nsIFile* cacheDir = mDevice->CacheDirectory(); + if (!cacheDir) return NS_OK; + + nsAutoString path; + nsresult rv = cacheDir->GetPath(path); + if (NS_SUCCEEDED(rv)) + AppendUTF16toUTF8(path, buffer); + else + buffer.AppendLiteral("directory unavailable"); + + buffer.AppendLiteral( + "</td>\n" + " </tr>\n"); + + aUsageReport.Assign(buffer); + return NS_OK; +} + +NS_IMETHODIMP +nsOfflineCacheDeviceInfo::GetEntryCount(uint32_t* aEntryCount) { + *aEntryCount = mDevice->EntryCount(); + return NS_OK; +} + +NS_IMETHODIMP +nsOfflineCacheDeviceInfo::GetTotalSize(uint32_t* aTotalSize) { + *aTotalSize = mDevice->CacheSize(); + return NS_OK; +} + +NS_IMETHODIMP +nsOfflineCacheDeviceInfo::GetMaximumSize(uint32_t* aMaximumSize) { + *aMaximumSize = mDevice->CacheCapacity(); + return NS_OK; +} + +/****************************************************************************** + * nsOfflineCacheBinding + */ + +class nsOfflineCacheBinding final : public nsISupports { + ~nsOfflineCacheBinding() = default; + + public: + NS_DECL_THREADSAFE_ISUPPORTS + + static nsOfflineCacheBinding* Create(nsIFile* cacheDir, const nsCString* key, + int generation); + + enum { FLAG_NEW_ENTRY = 1 }; + + nsCOMPtr<nsIFile> mDataFile; + int mGeneration; + int mFlags; + + bool IsNewEntry() { return mFlags & FLAG_NEW_ENTRY; } + void MarkNewEntry() { mFlags |= FLAG_NEW_ENTRY; } + void ClearNewEntry() { mFlags &= ~FLAG_NEW_ENTRY; } +}; + +NS_IMPL_ISUPPORTS0(nsOfflineCacheBinding) + +nsOfflineCacheBinding* nsOfflineCacheBinding::Create(nsIFile* cacheDir, + const nsCString* fullKey, + int generation) { + nsCOMPtr<nsIFile> file; + cacheDir->Clone(getter_AddRefs(file)); + if (!file) return nullptr; + + nsAutoCString keyBuf; + const char *cid, *key; + if (!DecomposeCacheEntryKey(fullKey, &cid, &key, keyBuf)) return nullptr; + + uint64_t hash = DCacheHash(key); + + uint32_t dir1 = (uint32_t)(hash & 0x0F); + uint32_t dir2 = (uint32_t)((hash & 0xF0) >> 4); + + hash >>= 8; + + // XXX we might want to create these directories up-front + + file->AppendNative(nsPrintfCString("%X", dir1)); + Unused << file->Create(nsIFile::DIRECTORY_TYPE, 00700); + + file->AppendNative(nsPrintfCString("%X", dir2)); + Unused << file->Create(nsIFile::DIRECTORY_TYPE, 00700); + + nsresult rv; + char leaf[64]; + + if (generation == -1) { + file->AppendNative("placeholder"_ns); + + for (generation = 0;; ++generation) { + SprintfLiteral(leaf, "%014" PRIX64 "-%X", hash, generation); + + rv = file->SetNativeLeafName(nsDependentCString(leaf)); + if (NS_FAILED(rv)) return nullptr; + rv = file->Create(nsIFile::NORMAL_FILE_TYPE, 00600); + if (NS_FAILED(rv) && rv != NS_ERROR_FILE_ALREADY_EXISTS) return nullptr; + if (NS_SUCCEEDED(rv)) break; + } + } else { + SprintfLiteral(leaf, "%014" PRIX64 "-%X", hash, generation); + rv = file->AppendNative(nsDependentCString(leaf)); + if (NS_FAILED(rv)) return nullptr; + } + + nsOfflineCacheBinding* binding = new nsOfflineCacheBinding; + if (!binding) return nullptr; + + binding->mDataFile.swap(file); + binding->mGeneration = generation; + binding->mFlags = 0; + return binding; +} + +/****************************************************************************** + * nsOfflineCacheRecord + */ + +struct nsOfflineCacheRecord { + const char* clientID; + const char* key; + const uint8_t* metaData; + uint32_t metaDataLen; + int32_t generation; + int32_t dataSize; + int32_t fetchCount; + int64_t lastFetched; + int64_t lastModified; + int64_t expirationTime; +}; + +static nsCacheEntry* CreateCacheEntry(nsOfflineCacheDevice* device, + const nsCString* fullKey, + const nsOfflineCacheRecord& rec) { + nsCacheEntry* entry; + + if (device->IsLocked(*fullKey)) { + return nullptr; + } + + nsresult rv = nsCacheEntry::Create(fullKey->get(), // XXX enable sharing + nsICache::STREAM_BASED, + nsICache::STORE_OFFLINE, device, &entry); + if (NS_FAILED(rv)) return nullptr; + + entry->SetFetchCount((uint32_t)rec.fetchCount); + entry->SetLastFetched(SecondsFromPRTime(rec.lastFetched)); + entry->SetLastModified(SecondsFromPRTime(rec.lastModified)); + entry->SetExpirationTime(SecondsFromPRTime(rec.expirationTime)); + entry->SetDataSize((uint32_t)rec.dataSize); + + entry->UnflattenMetaData((const char*)rec.metaData, rec.metaDataLen); + + // Restore security info, if present + const char* info = entry->GetMetaDataElement("security-info"); + if (info) { + nsCOMPtr<nsISupports> infoObj; + rv = + NS_DeserializeObject(nsDependentCString(info), getter_AddRefs(infoObj)); + if (NS_FAILED(rv)) { + delete entry; + return nullptr; + } + entry->SetSecurityInfo(infoObj); + } + + // create a binding object for this entry + nsOfflineCacheBinding* binding = nsOfflineCacheBinding::Create( + device->CacheDirectory(), fullKey, rec.generation); + if (!binding) { + delete entry; + return nullptr; + } + entry->SetData(binding); + + return entry; +} + +/****************************************************************************** + * nsOfflineCacheEntryInfo + */ + +class nsOfflineCacheEntryInfo final : public nsICacheEntryInfo { + ~nsOfflineCacheEntryInfo() = default; + + public: + NS_DECL_ISUPPORTS + NS_DECL_NSICACHEENTRYINFO + + nsOfflineCacheRecord* mRec; +}; + +NS_IMPL_ISUPPORTS(nsOfflineCacheEntryInfo, nsICacheEntryInfo) + +NS_IMETHODIMP +nsOfflineCacheEntryInfo::GetClientID(nsACString& aClientID) { + aClientID.Assign(mRec->clientID); + return NS_OK; +} + +NS_IMETHODIMP +nsOfflineCacheEntryInfo::GetDeviceID(nsACString& aDeviceID) { + aDeviceID.Assign(OFFLINE_CACHE_DEVICE_ID); + return NS_OK; +} + +NS_IMETHODIMP +nsOfflineCacheEntryInfo::GetKey(nsACString& clientKey) { + clientKey.Assign(mRec->key); + return NS_OK; +} + +NS_IMETHODIMP +nsOfflineCacheEntryInfo::GetFetchCount(int32_t* aFetchCount) { + *aFetchCount = mRec->fetchCount; + return NS_OK; +} + +NS_IMETHODIMP +nsOfflineCacheEntryInfo::GetLastFetched(uint32_t* aLastFetched) { + *aLastFetched = SecondsFromPRTime(mRec->lastFetched); + return NS_OK; +} + +NS_IMETHODIMP +nsOfflineCacheEntryInfo::GetLastModified(uint32_t* aLastModified) { + *aLastModified = SecondsFromPRTime(mRec->lastModified); + return NS_OK; +} + +NS_IMETHODIMP +nsOfflineCacheEntryInfo::GetExpirationTime(uint32_t* aExpirationTime) { + *aExpirationTime = SecondsFromPRTime(mRec->expirationTime); + return NS_OK; +} + +NS_IMETHODIMP +nsOfflineCacheEntryInfo::IsStreamBased(bool* aStreamBased) { + *aStreamBased = true; + return NS_OK; +} + +NS_IMETHODIMP +nsOfflineCacheEntryInfo::GetDataSize(uint32_t* aDataSize) { + *aDataSize = mRec->dataSize; + return NS_OK; +} + +/****************************************************************************** + * nsApplicationCacheNamespace + */ + +NS_IMPL_ISUPPORTS(nsApplicationCacheNamespace, nsIApplicationCacheNamespace) + +NS_IMETHODIMP +nsApplicationCacheNamespace::Init(uint32_t itemType, + const nsACString& namespaceSpec, + const nsACString& data) { + mItemType = itemType; + mNamespaceSpec = namespaceSpec; + mData = data; + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCacheNamespace::GetItemType(uint32_t* out) { + *out = mItemType; + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCacheNamespace::GetNamespaceSpec(nsACString& out) { + out = mNamespaceSpec; + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCacheNamespace::GetData(nsACString& out) { + out = mData; + return NS_OK; +} + +/****************************************************************************** + * nsApplicationCache + */ + +NS_IMPL_ISUPPORTS(nsApplicationCache, nsIApplicationCache, + nsISupportsWeakReference) + +nsApplicationCache::nsApplicationCache() : mDevice(nullptr), mValid(true) {} + +nsApplicationCache::nsApplicationCache(nsOfflineCacheDevice* device, + const nsACString& group, + const nsACString& clientID) + : mDevice(device), mGroup(group), mClientID(clientID), mValid(true) {} + +nsApplicationCache::~nsApplicationCache() { + if (!mDevice) return; + + { + MutexAutoLock lock(mDevice->mLock); + mDevice->mCaches.Remove(mClientID); + } + + // If this isn't an active cache anymore, it can be destroyed. + if (mValid && !mDevice->IsActiveCache(mGroup, mClientID)) Discard(); +} + +void nsApplicationCache::MarkInvalid() { mValid = false; } + +NS_IMETHODIMP +nsApplicationCache::InitAsHandle(const nsACString& groupId, + const nsACString& clientId) { + NS_ENSURE_FALSE(mDevice, NS_ERROR_ALREADY_INITIALIZED); + NS_ENSURE_TRUE(mGroup.IsEmpty(), NS_ERROR_ALREADY_INITIALIZED); + + mGroup = groupId; + mClientID = clientId; + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCache::GetManifestURI(nsIURI** out) { + nsCOMPtr<nsIURI> uri; + nsresult rv = NS_NewURI(getter_AddRefs(uri), mGroup); + NS_ENSURE_SUCCESS(rv, rv); + + rv = NS_GetURIWithNewRef(uri, ""_ns, out); + NS_ENSURE_SUCCESS(rv, rv); + + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCache::GetGroupID(nsACString& out) { + out = mGroup; + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCache::GetClientID(nsACString& out) { + out = mClientID; + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCache::GetProfileDirectory(nsIFile** out) { + *out = do_AddRef(mDevice->BaseDirectory()).take(); + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCache::GetActive(bool* out) { + NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE); + + *out = mDevice->IsActiveCache(mGroup, mClientID); + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCache::Activate() { + NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE); + NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE); + + mDevice->ActivateCache(mGroup, mClientID); + + if (mDevice->AutoShutdown(this)) mDevice = nullptr; + + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCache::Discard() { + NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE); + NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE); + + mValid = false; + + nsCOMPtr<nsIRunnable> ev = + new nsOfflineCacheDiscardCache(mDevice, mGroup, mClientID); + nsresult rv = nsCacheService::DispatchToCacheIOThread(ev); + return rv; +} + +NS_IMETHODIMP +nsApplicationCache::MarkEntry(const nsACString& key, uint32_t typeBits) { + NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE); + NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE); + + return mDevice->MarkEntry(mClientID, key, typeBits); +} + +NS_IMETHODIMP +nsApplicationCache::UnmarkEntry(const nsACString& key, uint32_t typeBits) { + NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE); + NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE); + + return mDevice->UnmarkEntry(mClientID, key, typeBits); +} + +NS_IMETHODIMP +nsApplicationCache::GetTypes(const nsACString& key, uint32_t* typeBits) { + NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE); + NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE); + + return mDevice->GetTypes(mClientID, key, typeBits); +} + +NS_IMETHODIMP +nsApplicationCache::GatherEntries(uint32_t typeBits, + nsTArray<nsCString>& keys) { + NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE); + NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE); + + return mDevice->GatherEntries(mClientID, typeBits, keys); +} + +NS_IMETHODIMP +nsApplicationCache::AddNamespaces(nsIArray* namespaces) { + NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE); + NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE); + + if (!namespaces) return NS_OK; + + mozStorageTransaction transaction(mDevice->mDB, false); + + uint32_t length; + nsresult rv = namespaces->GetLength(&length); + NS_ENSURE_SUCCESS(rv, rv); + + for (uint32_t i = 0; i < length; i++) { + nsCOMPtr<nsIApplicationCacheNamespace> ns = + do_QueryElementAt(namespaces, i); + if (ns) { + rv = mDevice->AddNamespace(mClientID, ns); + NS_ENSURE_SUCCESS(rv, rv); + } + } + + rv = transaction.Commit(); + NS_ENSURE_SUCCESS(rv, rv); + + return NS_OK; +} + +NS_IMETHODIMP +nsApplicationCache::GetMatchingNamespace(const nsACString& key, + nsIApplicationCacheNamespace** out) + +{ + NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE); + NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE); + + return mDevice->GetMatchingNamespace(mClientID, key, out); +} + +NS_IMETHODIMP +nsApplicationCache::GetUsage(uint32_t* usage) { + NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE); + NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE); + + return mDevice->GetUsage(mClientID, usage); +} + +/****************************************************************************** + * nsCloseDBEvent + *****************************************************************************/ + +class nsCloseDBEvent : public Runnable { + public: + explicit nsCloseDBEvent(mozIStorageConnection* aDB) + : mozilla::Runnable("nsCloseDBEvent") { + mDB = aDB; + } + + NS_IMETHOD Run() override { + mDB->Close(); + return NS_OK; + } + + protected: + virtual ~nsCloseDBEvent() = default; + + private: + nsCOMPtr<mozIStorageConnection> mDB; +}; + +/****************************************************************************** + * nsOfflineCacheDevice + */ + +NS_IMPL_ISUPPORTS0(nsOfflineCacheDevice) + +nsOfflineCacheDevice::nsOfflineCacheDevice() + : mDB(nullptr), + mCacheCapacity(0), + mDeltaCounter(0), + mAutoShutdown(false), + mLock("nsOfflineCacheDevice.lock"), + mActiveCaches(4), + mLockedEntries(32) {} + +/* static */ +bool nsOfflineCacheDevice::GetStrictFileOriginPolicy() { + nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID); + + bool retval; + if (prefs && NS_SUCCEEDED(prefs->GetBoolPref( + "security.fileuri.strict_origin_policy", &retval))) + return retval; + + // As default value use true (be more strict) + return true; +} + +uint32_t nsOfflineCacheDevice::CacheSize() { + NS_ENSURE_TRUE(Initialized(), 0); + + AutoResetStatement statement(mStatement_CacheSize); + + bool hasRows; + nsresult rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_TRUE(NS_SUCCEEDED(rv) && hasRows, 0); + + return (uint32_t)statement->AsInt32(0); +} + +uint32_t nsOfflineCacheDevice::EntryCount() { + NS_ENSURE_TRUE(Initialized(), 0); + + AutoResetStatement statement(mStatement_EntryCount); + + bool hasRows; + nsresult rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_TRUE(NS_SUCCEEDED(rv) && hasRows, 0); + + return (uint32_t)statement->AsInt32(0); +} + +nsresult nsOfflineCacheDevice::UpdateEntry(nsCacheEntry* entry) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + // Decompose the key into "ClientID" and "Key" + nsAutoCString keyBuf; + const char *cid, *key; + + if (!DecomposeCacheEntryKey(entry->Key(), &cid, &key, keyBuf)) + return NS_ERROR_UNEXPECTED; + + // Store security info, if it is serializable + nsCOMPtr<nsISupports> infoObj = entry->SecurityInfo(); + nsCOMPtr<nsISerializable> serializable = do_QueryInterface(infoObj); + if (infoObj && !serializable) return NS_ERROR_UNEXPECTED; + + if (serializable) { + nsCString info; + nsresult rv = NS_SerializeToString(serializable, info); + NS_ENSURE_SUCCESS(rv, rv); + + rv = entry->SetMetaDataElement("security-info", info.get()); + NS_ENSURE_SUCCESS(rv, rv); + } + + nsCString metaDataBuf; + uint32_t mdSize = entry->MetaDataSize(); + if (!metaDataBuf.SetLength(mdSize, fallible)) return NS_ERROR_OUT_OF_MEMORY; + char* md = metaDataBuf.BeginWriting(); + entry->FlattenMetaData(md, mdSize); + + nsOfflineCacheRecord rec; + rec.metaData = (const uint8_t*)md; + rec.metaDataLen = mdSize; + rec.dataSize = entry->DataSize(); + rec.fetchCount = entry->FetchCount(); + rec.lastFetched = PRTimeFromSeconds(entry->LastFetched()); + rec.lastModified = PRTimeFromSeconds(entry->LastModified()); + rec.expirationTime = PRTimeFromSeconds(entry->ExpirationTime()); + + AutoResetStatement statement(mStatement_UpdateEntry); + + nsresult rv; + rv = statement->BindBlobByIndex(0, rec.metaData, rec.metaDataLen); + nsresult tmp = statement->BindInt32ByIndex(1, rec.dataSize); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindInt32ByIndex(2, rec.fetchCount); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindInt64ByIndex(3, rec.lastFetched); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindInt64ByIndex(4, rec.lastModified); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindInt64ByIndex(5, rec.expirationTime); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindUTF8StringByIndex(6, nsDependentCString(cid)); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindUTF8StringByIndex(7, nsDependentCString(key)); + if (NS_FAILED(tmp)) { + rv = tmp; + } + NS_ENSURE_SUCCESS(rv, rv); + + bool hasRows; + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + + NS_ASSERTION(!hasRows, "UPDATE should not result in output"); + return rv; +} + +nsresult nsOfflineCacheDevice::UpdateEntrySize(nsCacheEntry* entry, + uint32_t newSize) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + // Decompose the key into "ClientID" and "Key" + nsAutoCString keyBuf; + const char *cid, *key; + if (!DecomposeCacheEntryKey(entry->Key(), &cid, &key, keyBuf)) + return NS_ERROR_UNEXPECTED; + + AutoResetStatement statement(mStatement_UpdateEntrySize); + + nsresult rv = statement->BindInt32ByIndex(0, newSize); + nsresult tmp = statement->BindUTF8StringByIndex(1, nsDependentCString(cid)); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindUTF8StringByIndex(2, nsDependentCString(key)); + if (NS_FAILED(tmp)) { + rv = tmp; + } + NS_ENSURE_SUCCESS(rv, rv); + + bool hasRows; + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + + NS_ASSERTION(!hasRows, "UPDATE should not result in output"); + return rv; +} + +nsresult nsOfflineCacheDevice::DeleteEntry(nsCacheEntry* entry, + bool deleteData) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + if (deleteData) { + nsresult rv = DeleteData(entry); + if (NS_FAILED(rv)) return rv; + } + + // Decompose the key into "ClientID" and "Key" + nsAutoCString keyBuf; + const char *cid, *key; + if (!DecomposeCacheEntryKey(entry->Key(), &cid, &key, keyBuf)) + return NS_ERROR_UNEXPECTED; + + AutoResetStatement statement(mStatement_DeleteEntry); + + nsresult rv = statement->BindUTF8StringByIndex(0, nsDependentCString(cid)); + nsresult rv2 = statement->BindUTF8StringByIndex(1, nsDependentCString(key)); + NS_ENSURE_SUCCESS(rv, rv); + NS_ENSURE_SUCCESS(rv2, rv2); + + bool hasRows; + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + + NS_ASSERTION(!hasRows, "DELETE should not result in output"); + return rv; +} + +nsresult nsOfflineCacheDevice::DeleteData(nsCacheEntry* entry) { + nsOfflineCacheBinding* binding = (nsOfflineCacheBinding*)entry->Data(); + NS_ENSURE_STATE(binding); + + return binding->mDataFile->Remove(false); +} + +/** + * nsCacheDevice implementation + */ + +// This struct is local to nsOfflineCacheDevice::Init, but ISO C++98 doesn't +// allow a template (mozilla::ArrayLength) to be instantiated based on a local +// type. Boo-urns! +struct StatementSql { + nsCOMPtr<mozIStorageStatement>& statement; + const char* sql; + StatementSql(nsCOMPtr<mozIStorageStatement>& aStatement, const char* aSql) + : statement(aStatement), sql(aSql) {} +}; + +nsresult nsOfflineCacheDevice::Init() { + MOZ_ASSERT(false, "Need to be initialized with sqlite"); + return NS_ERROR_NOT_IMPLEMENTED; +} + +nsresult nsOfflineCacheDevice::InitWithSqlite(mozIStorageService* ss) { + NS_ENSURE_TRUE(!mDB, NS_ERROR_ALREADY_INITIALIZED); + + // SetCacheParentDirectory must have been called + NS_ENSURE_TRUE(mCacheDirectory, NS_ERROR_UNEXPECTED); + + // make sure the cache directory exists + nsresult rv = EnsureDir(mCacheDirectory); + NS_ENSURE_SUCCESS(rv, rv); + + // build path to index file + nsCOMPtr<nsIFile> indexFile; + rv = mCacheDirectory->Clone(getter_AddRefs(indexFile)); + NS_ENSURE_SUCCESS(rv, rv); + rv = indexFile->AppendNative("index.sqlite"_ns); + NS_ENSURE_SUCCESS(rv, rv); + + MOZ_ASSERT(ss, + "nsOfflineCacheDevice::InitWithSqlite called before " + "nsCacheService::Init() ?"); + NS_ENSURE_TRUE(ss, NS_ERROR_UNEXPECTED); + + rv = ss->OpenDatabase(indexFile, getter_AddRefs(mDB)); + NS_ENSURE_SUCCESS(rv, rv); + + mInitEventTarget = GetCurrentEventTarget(); + + mDB->ExecuteSimpleSQL("PRAGMA synchronous = OFF;"_ns); + + // XXX ... other initialization steps + + // XXX in the future we may wish to verify the schema for moz_cache + // perhaps using "PRAGMA table_info" ? + + // build the table + // + // "Generation" is the data file generation number. + // + rv = mDB->ExecuteSimpleSQL( + nsLiteralCString("CREATE TABLE IF NOT EXISTS moz_cache (\n" + " ClientID TEXT,\n" + " Key TEXT,\n" + " MetaData BLOB,\n" + " Generation INTEGER,\n" + " DataSize INTEGER,\n" + " FetchCount INTEGER,\n" + " LastFetched INTEGER,\n" + " LastModified INTEGER,\n" + " ExpirationTime INTEGER,\n" + " ItemType INTEGER DEFAULT 0\n" + ");\n")); + NS_ENSURE_SUCCESS(rv, rv); + + // Databases from 1.9.0 don't have the ItemType column. Add the column + // here, but don't worry about failures (the column probably already exists) + mDB->ExecuteSimpleSQL( + "ALTER TABLE moz_cache ADD ItemType INTEGER DEFAULT 0"_ns); + + // Create the table for storing cache groups. All actions on + // moz_cache_groups use the GroupID, so use it as the primary key. + rv = mDB->ExecuteSimpleSQL( + nsLiteralCString("CREATE TABLE IF NOT EXISTS moz_cache_groups (\n" + " GroupID TEXT PRIMARY KEY,\n" + " ActiveClientID TEXT\n" + ");\n")); + NS_ENSURE_SUCCESS(rv, rv); + + mDB->ExecuteSimpleSQL( + nsLiteralCString("ALTER TABLE moz_cache_groups " + "ADD ActivateTimeStamp INTEGER DEFAULT 0")); + + // ClientID: clientID joining moz_cache and moz_cache_namespaces + // tables. + // Data: Data associated with this namespace (e.g. a fallback URI + // for fallback entries). + // ItemType: the type of namespace. + rv = + mDB->ExecuteSimpleSQL(nsLiteralCString("CREATE TABLE IF NOT EXISTS" + " moz_cache_namespaces (\n" + " ClientID TEXT,\n" + " NameSpace TEXT,\n" + " Data TEXT,\n" + " ItemType INTEGER\n" + ");\n")); + NS_ENSURE_SUCCESS(rv, rv); + + // Databases from 1.9.0 have a moz_cache_index that should be dropped + rv = mDB->ExecuteSimpleSQL("DROP INDEX IF EXISTS moz_cache_index"_ns); + NS_ENSURE_SUCCESS(rv, rv); + + // Key/ClientID pairs should be unique in the database. All queries + // against moz_cache use the Key (which is also the most unique), so + // use it as the primary key for this index. + rv = mDB->ExecuteSimpleSQL( + nsLiteralCString("CREATE UNIQUE INDEX IF NOT EXISTS " + " moz_cache_key_clientid_index" + " ON moz_cache (Key, ClientID);")); + NS_ENSURE_SUCCESS(rv, rv); + + // Used for ClientID lookups and to keep ClientID/NameSpace pairs unique. + rv = mDB->ExecuteSimpleSQL( + nsLiteralCString("CREATE UNIQUE INDEX IF NOT EXISTS" + " moz_cache_namespaces_clientid_index" + " ON moz_cache_namespaces (ClientID, NameSpace);")); + NS_ENSURE_SUCCESS(rv, rv); + + // Used for namespace lookups. + rv = mDB->ExecuteSimpleSQL( + nsLiteralCString("CREATE INDEX IF NOT EXISTS" + " moz_cache_namespaces_namespace_index" + " ON moz_cache_namespaces (NameSpace);")); + NS_ENSURE_SUCCESS(rv, rv); + + mEvictionFunction = new nsOfflineCacheEvictionFunction(this); + if (!mEvictionFunction) return NS_ERROR_OUT_OF_MEMORY; + + rv = mDB->CreateFunction("cache_eviction_observer"_ns, 3, mEvictionFunction); + NS_ENSURE_SUCCESS(rv, rv); + + // create all (most) of our statements up front + StatementSql prepared[] = { + // clang-format off + StatementSql ( mStatement_CacheSize, "SELECT Sum(DataSize) from moz_cache;" ), + StatementSql ( mStatement_ApplicationCacheSize, "SELECT Sum(DataSize) from moz_cache WHERE ClientID = ?;" ), + StatementSql ( mStatement_EntryCount, "SELECT count(*) from moz_cache;" ), + StatementSql ( mStatement_UpdateEntry, "UPDATE moz_cache SET MetaData = ?, DataSize = ?, FetchCount = ?, LastFetched = ?, LastModified = ?, ExpirationTime = ? WHERE ClientID = ? AND Key = ?;" ), + StatementSql ( mStatement_UpdateEntrySize, "UPDATE moz_cache SET DataSize = ? WHERE ClientID = ? AND Key = ?;" ), + StatementSql ( mStatement_DeleteEntry, "DELETE FROM moz_cache WHERE ClientID = ? AND Key = ?;" ), + StatementSql ( mStatement_FindEntry, "SELECT MetaData, Generation, DataSize, FetchCount, LastFetched, LastModified, ExpirationTime, ItemType FROM moz_cache WHERE ClientID = ? AND Key = ?;" ), + StatementSql ( mStatement_BindEntry, "INSERT INTO moz_cache (ClientID, Key, MetaData, Generation, DataSize, FetchCount, LastFetched, LastModified, ExpirationTime) VALUES(?,?,?,?,?,?,?,?,?);" ), + + StatementSql ( mStatement_MarkEntry, "UPDATE moz_cache SET ItemType = (ItemType | ?) WHERE ClientID = ? AND Key = ?;" ), + StatementSql ( mStatement_UnmarkEntry, "UPDATE moz_cache SET ItemType = (ItemType & ~?) WHERE ClientID = ? AND Key = ?;" ), + StatementSql ( mStatement_GetTypes, "SELECT ItemType FROM moz_cache WHERE ClientID = ? AND Key = ?;"), + StatementSql ( mStatement_CleanupUnmarked, "DELETE FROM moz_cache WHERE ClientID = ? AND Key = ? AND ItemType = 0;" ), + StatementSql ( mStatement_GatherEntries, "SELECT Key FROM moz_cache WHERE ClientID = ? AND (ItemType & ?) > 0;" ), + + StatementSql ( mStatement_ActivateClient, "INSERT OR REPLACE INTO moz_cache_groups (GroupID, ActiveClientID, ActivateTimeStamp) VALUES (?, ?, ?);" ), + StatementSql ( mStatement_DeactivateGroup, "DELETE FROM moz_cache_groups WHERE GroupID = ?;" ), + StatementSql ( mStatement_FindClient, "/* do not warn (bug 1293375) */ SELECT ClientID, ItemType FROM moz_cache WHERE Key = ? ORDER BY LastFetched DESC, LastModified DESC;" ), + + // Search for namespaces that match the URI. Use the <= operator + // to ensure that we use the index on moz_cache_namespaces. + StatementSql ( mStatement_FindClientByNamespace, "/* do not warn (bug 1293375) */ SELECT ns.ClientID, ns.ItemType FROM" + " moz_cache_namespaces AS ns JOIN moz_cache_groups AS groups" + " ON ns.ClientID = groups.ActiveClientID" + " WHERE ns.NameSpace <= ?1 AND ?1 GLOB ns.NameSpace || '*'" + " ORDER BY ns.NameSpace DESC, groups.ActivateTimeStamp DESC;"), + StatementSql ( mStatement_FindNamespaceEntry, "SELECT NameSpace, Data, ItemType FROM moz_cache_namespaces" + " WHERE ClientID = ?1" + " AND NameSpace <= ?2 AND ?2 GLOB NameSpace || '*'" + " ORDER BY NameSpace DESC;"), + StatementSql ( mStatement_InsertNamespaceEntry, "INSERT INTO moz_cache_namespaces (ClientID, NameSpace, Data, ItemType) VALUES(?, ?, ?, ?);"), + StatementSql ( mStatement_EnumerateApps, "SELECT GroupID, ActiveClientID FROM moz_cache_groups WHERE GroupID LIKE ?1;"), + StatementSql ( mStatement_EnumerateGroups, "SELECT GroupID, ActiveClientID FROM moz_cache_groups;"), + StatementSql ( mStatement_EnumerateGroupsTimeOrder, "SELECT GroupID, ActiveClientID FROM moz_cache_groups ORDER BY ActivateTimeStamp;") + // clang-format on + }; + for (uint32_t i = 0; NS_SUCCEEDED(rv) && i < ArrayLength(prepared); ++i) { + LOG(("Creating statement: %s\n", prepared[i].sql)); + + rv = mDB->CreateStatement(nsDependentCString(prepared[i].sql), + getter_AddRefs(prepared[i].statement)); + NS_ENSURE_SUCCESS(rv, rv); + } + + rv = InitActiveCaches(); + NS_ENSURE_SUCCESS(rv, rv); + + return NS_OK; +} + +namespace { + +nsresult GetGroupForCache(const nsACString& clientID, nsCString& group) { + group.Assign(clientID); + group.Truncate(group.FindChar('|')); + NS_UnescapeURL(group); + + return NS_OK; +} + +} // namespace + +// static +nsresult nsOfflineCacheDevice::BuildApplicationCacheGroupID( + nsIURI* aManifestURL, nsACString const& aOriginSuffix, + nsACString& _result) { + nsCOMPtr<nsIURI> newURI; + nsresult rv = + NS_GetURIWithNewRef(aManifestURL, ""_ns, getter_AddRefs(newURI)); + NS_ENSURE_SUCCESS(rv, rv); + + nsAutoCString manifestSpec; + rv = newURI->GetAsciiSpec(manifestSpec); + NS_ENSURE_SUCCESS(rv, rv); + + _result.Assign(manifestSpec); + _result.Append('#'); + _result.Append(aOriginSuffix); + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::InitActiveCaches() { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + MutexAutoLock lock(mLock); + + AutoResetStatement statement(mStatement_EnumerateGroups); + + bool hasRows; + nsresult rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + + while (hasRows) { + nsAutoCString group; + statement->GetUTF8String(0, group); + nsCString clientID; + statement->GetUTF8String(1, clientID); + + mActiveCaches.PutEntry(clientID); + mActiveCachesByGroup.Put(group, new nsCString(clientID)); + + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + } + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::Shutdown() { + NS_ENSURE_TRUE(mDB, NS_ERROR_NOT_INITIALIZED); + + { + MutexAutoLock lock(mLock); + for (auto iter = mCaches.Iter(); !iter.Done(); iter.Next()) { + nsCOMPtr<nsIApplicationCache> obj = do_QueryReferent(iter.UserData()); + if (obj) { + auto appCache = static_cast<nsApplicationCache*>(obj.get()); + appCache->MarkInvalid(); + } + } + } + + { + EvictionObserver evictionObserver(mDB, mEvictionFunction); + + // Delete all rows whose clientID is not an active clientID. + nsresult rv = mDB->ExecuteSimpleSQL(nsLiteralCString( + "DELETE FROM moz_cache WHERE rowid IN" + " (SELECT moz_cache.rowid FROM" + " moz_cache LEFT OUTER JOIN moz_cache_groups ON" + " (moz_cache.ClientID = moz_cache_groups.ActiveClientID)" + " WHERE moz_cache_groups.GroupID ISNULL)")); + + if (NS_FAILED(rv)) + NS_WARNING("Failed to clean up unused application caches."); + else + evictionObserver.Apply(); + + // Delete all namespaces whose clientID is not an active clientID. + rv = mDB->ExecuteSimpleSQL(nsLiteralCString( + "DELETE FROM moz_cache_namespaces WHERE rowid IN" + " (SELECT moz_cache_namespaces.rowid FROM" + " moz_cache_namespaces LEFT OUTER JOIN moz_cache_groups ON" + " (moz_cache_namespaces.ClientID = " + "moz_cache_groups.ActiveClientID)" + " WHERE moz_cache_groups.GroupID ISNULL)")); + + if (NS_FAILED(rv)) NS_WARNING("Failed to clean up namespaces."); + + mEvictionFunction = nullptr; + + mStatement_CacheSize = nullptr; + mStatement_ApplicationCacheSize = nullptr; + mStatement_EntryCount = nullptr; + mStatement_UpdateEntry = nullptr; + mStatement_UpdateEntrySize = nullptr; + mStatement_DeleteEntry = nullptr; + mStatement_FindEntry = nullptr; + mStatement_BindEntry = nullptr; + mStatement_ClearDomain = nullptr; + mStatement_MarkEntry = nullptr; + mStatement_UnmarkEntry = nullptr; + mStatement_GetTypes = nullptr; + mStatement_FindNamespaceEntry = nullptr; + mStatement_InsertNamespaceEntry = nullptr; + mStatement_CleanupUnmarked = nullptr; + mStatement_GatherEntries = nullptr; + mStatement_ActivateClient = nullptr; + mStatement_DeactivateGroup = nullptr; + mStatement_FindClient = nullptr; + mStatement_FindClientByNamespace = nullptr; + mStatement_EnumerateApps = nullptr; + mStatement_EnumerateGroups = nullptr; + mStatement_EnumerateGroupsTimeOrder = nullptr; + } + + // Close Database on the correct thread + bool isOnCurrentThread = true; + if (mInitEventTarget) + isOnCurrentThread = mInitEventTarget->IsOnCurrentThread(); + + if (!isOnCurrentThread) { + nsCOMPtr<nsIRunnable> ev = new nsCloseDBEvent(mDB); + + if (ev) { + mInitEventTarget->Dispatch(ev, NS_DISPATCH_NORMAL); + } + } else { + mDB->Close(); + } + + mDB = nullptr; + mInitEventTarget = nullptr; + + return NS_OK; +} + +const char* nsOfflineCacheDevice::GetDeviceID() { + return OFFLINE_CACHE_DEVICE_ID; +} + +nsCacheEntry* nsOfflineCacheDevice::FindEntry(nsCString* fullKey, + bool* collision) { + NS_ENSURE_TRUE(Initialized(), nullptr); + + mozilla::Telemetry::AutoTimer<mozilla::Telemetry::CACHE_OFFLINE_SEARCH_2> + timer; + LOG(("nsOfflineCacheDevice::FindEntry [key=%s]\n", fullKey->get())); + + // SELECT * FROM moz_cache WHERE key = ? + + // Decompose the key into "ClientID" and "Key" + nsAutoCString keyBuf; + const char *cid, *key; + if (!DecomposeCacheEntryKey(fullKey, &cid, &key, keyBuf)) return nullptr; + + AutoResetStatement statement(mStatement_FindEntry); + + nsresult rv = statement->BindUTF8StringByIndex(0, nsDependentCString(cid)); + nsresult rv2 = statement->BindUTF8StringByIndex(1, nsDependentCString(key)); + NS_ENSURE_SUCCESS(rv, nullptr); + NS_ENSURE_SUCCESS(rv2, nullptr); + + bool hasRows; + rv = statement->ExecuteStep(&hasRows); + if (NS_FAILED(rv) || !hasRows) return nullptr; // entry not found + + nsOfflineCacheRecord rec; + statement->GetSharedBlob(0, &rec.metaDataLen, (const uint8_t**)&rec.metaData); + rec.generation = statement->AsInt32(1); + rec.dataSize = statement->AsInt32(2); + rec.fetchCount = statement->AsInt32(3); + rec.lastFetched = statement->AsInt64(4); + rec.lastModified = statement->AsInt64(5); + rec.expirationTime = statement->AsInt64(6); + + LOG(("entry: [%u %d %d %d %" PRId64 " %" PRId64 " %" PRId64 "]\n", + rec.metaDataLen, rec.generation, rec.dataSize, rec.fetchCount, + rec.lastFetched, rec.lastModified, rec.expirationTime)); + + nsCacheEntry* entry = CreateCacheEntry(this, fullKey, rec); + + if (entry) { + // make sure that the data file exists + nsOfflineCacheBinding* binding = (nsOfflineCacheBinding*)entry->Data(); + bool isFile; + rv = binding->mDataFile->IsFile(&isFile); + if (NS_FAILED(rv) || !isFile) { + DeleteEntry(entry, false); + delete entry; + return nullptr; + } + + // lock the entry + Lock(*fullKey); + } + + return entry; +} + +nsresult nsOfflineCacheDevice::DeactivateEntry(nsCacheEntry* entry) { + LOG(("nsOfflineCacheDevice::DeactivateEntry [key=%s]\n", + entry->Key()->get())); + + // This method is called to inform us that the nsCacheEntry object is going + // away. We should persist anything that needs to be persisted, or if the + // entry is doomed, we can go ahead and clear its storage. + + if (entry->IsDoomed()) { + // remove corresponding row and file if they exist + + // the row should have been removed in DoomEntry... we could assert that + // that happened. otherwise, all we have to do here is delete the file + // on disk. + DeleteData(entry); + } else if (((nsOfflineCacheBinding*)entry->Data())->IsNewEntry()) { + // UPDATE the database row + + // Only new entries are updated, since offline cache is updated in + // transactions. New entries are those who is returned from + // BindEntry(). + + LOG(("nsOfflineCacheDevice::DeactivateEntry updating new entry\n")); + UpdateEntry(entry); + } else { + LOG( + ("nsOfflineCacheDevice::DeactivateEntry " + "skipping update since entry is not dirty\n")); + } + + // Unlock the entry + Unlock(*entry->Key()); + + delete entry; + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::BindEntry(nsCacheEntry* entry) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + LOG(("nsOfflineCacheDevice::BindEntry [key=%s]\n", entry->Key()->get())); + + NS_ENSURE_STATE(!entry->Data()); + + // This method is called to inform us that we have a new entry. The entry + // may collide with an existing entry in our DB, but if that happens we can + // assume that the entry is not being used. + + // INSERT the database row + + // XXX Assumption: if the row already exists, then FindEntry would have + // returned it. if that entry was doomed, then DoomEntry would have removed + // it from the table. so, we should always have to insert at this point. + + // Decompose the key into "ClientID" and "Key" + nsAutoCString keyBuf; + const char *cid, *key; + if (!DecomposeCacheEntryKey(entry->Key(), &cid, &key, keyBuf)) + return NS_ERROR_UNEXPECTED; + + // create binding, pick best generation number + RefPtr<nsOfflineCacheBinding> binding = + nsOfflineCacheBinding::Create(mCacheDirectory, entry->Key(), -1); + if (!binding) return NS_ERROR_OUT_OF_MEMORY; + binding->MarkNewEntry(); + + nsOfflineCacheRecord rec; + rec.clientID = cid; + rec.key = key; + rec.metaData = nullptr; // don't write any metadata now. + rec.metaDataLen = 0; + rec.generation = binding->mGeneration; + rec.dataSize = 0; + rec.fetchCount = entry->FetchCount(); + rec.lastFetched = PRTimeFromSeconds(entry->LastFetched()); + rec.lastModified = PRTimeFromSeconds(entry->LastModified()); + rec.expirationTime = PRTimeFromSeconds(entry->ExpirationTime()); + + AutoResetStatement statement(mStatement_BindEntry); + + nsresult rv = + statement->BindUTF8StringByIndex(0, nsDependentCString(rec.clientID)); + nsresult tmp = + statement->BindUTF8StringByIndex(1, nsDependentCString(rec.key)); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindBlobByIndex(2, rec.metaData, rec.metaDataLen); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindInt32ByIndex(3, rec.generation); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindInt32ByIndex(4, rec.dataSize); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindInt32ByIndex(5, rec.fetchCount); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindInt64ByIndex(6, rec.lastFetched); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindInt64ByIndex(7, rec.lastModified); + if (NS_FAILED(tmp)) { + rv = tmp; + } + tmp = statement->BindInt64ByIndex(8, rec.expirationTime); + if (NS_FAILED(tmp)) { + rv = tmp; + } + NS_ENSURE_SUCCESS(rv, rv); + + bool hasRows; + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + NS_ASSERTION(!hasRows, "INSERT should not result in output"); + + entry->SetData(binding); + + // lock the entry + Lock(*entry->Key()); + + return NS_OK; +} + +void nsOfflineCacheDevice::DoomEntry(nsCacheEntry* entry) { + LOG(("nsOfflineCacheDevice::DoomEntry [key=%s]\n", entry->Key()->get())); + + // This method is called to inform us that we should mark the entry to be + // deleted when it is no longer in use. + + // We can go ahead and delete the corresponding row in our table, + // but we must not delete the file on disk until we are deactivated. + // In another word, the file should be deleted if the entry had been + // deactivated. + + DeleteEntry(entry, !entry->IsActive()); +} + +nsresult nsOfflineCacheDevice::OpenInputStreamForEntry( + nsCacheEntry* entry, nsCacheAccessMode mode, uint32_t offset, + nsIInputStream** result) { + LOG(("nsOfflineCacheDevice::OpenInputStreamForEntry [key=%s]\n", + entry->Key()->get())); + + *result = nullptr; + + NS_ENSURE_TRUE(!offset || (offset < entry->DataSize()), NS_ERROR_INVALID_ARG); + + // return an input stream to the entry's data file. the stream + // may be read on a background thread. + + nsOfflineCacheBinding* binding = (nsOfflineCacheBinding*)entry->Data(); + NS_ENSURE_STATE(binding); + + nsCOMPtr<nsIInputStream> in; + NS_NewLocalFileInputStream(getter_AddRefs(in), binding->mDataFile, PR_RDONLY); + if (!in) return NS_ERROR_UNEXPECTED; + + // respect |offset| param + if (offset != 0) { + nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(in); + NS_ENSURE_TRUE(seekable, NS_ERROR_UNEXPECTED); + + seekable->Seek(nsISeekableStream::NS_SEEK_SET, offset); + } + + in.swap(*result); + return NS_OK; +} + +nsresult nsOfflineCacheDevice::OpenOutputStreamForEntry( + nsCacheEntry* entry, nsCacheAccessMode mode, uint32_t offset, + nsIOutputStream** result) { + LOG(("nsOfflineCacheDevice::OpenOutputStreamForEntry [key=%s]\n", + entry->Key()->get())); + + *result = nullptr; + + NS_ENSURE_TRUE(offset <= entry->DataSize(), NS_ERROR_INVALID_ARG); + + // return an output stream to the entry's data file. we can assume + // that the output stream will only be used on the main thread. + + nsOfflineCacheBinding* binding = (nsOfflineCacheBinding*)entry->Data(); + NS_ENSURE_STATE(binding); + + nsCOMPtr<nsIOutputStream> out; + NS_NewLocalFileOutputStream(getter_AddRefs(out), binding->mDataFile, + PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 00600); + if (!out) return NS_ERROR_UNEXPECTED; + + // respect |offset| param + nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(out); + NS_ENSURE_TRUE(seekable, NS_ERROR_UNEXPECTED); + if (offset != 0) seekable->Seek(nsISeekableStream::NS_SEEK_SET, offset); + + // truncate the file at the given offset + seekable->SetEOF(); + + nsCOMPtr<nsIOutputStream> bufferedOut; + nsresult rv = NS_NewBufferedOutputStream(getter_AddRefs(bufferedOut), + out.forget(), 16 * 1024); + NS_ENSURE_SUCCESS(rv, rv); + + bufferedOut.forget(result); + return NS_OK; +} + +nsresult nsOfflineCacheDevice::GetFileForEntry(nsCacheEntry* entry, + nsIFile** result) { + LOG(("nsOfflineCacheDevice::GetFileForEntry [key=%s]\n", + entry->Key()->get())); + + nsOfflineCacheBinding* binding = (nsOfflineCacheBinding*)entry->Data(); + NS_ENSURE_STATE(binding); + + NS_IF_ADDREF(*result = binding->mDataFile); + return NS_OK; +} + +nsresult nsOfflineCacheDevice::OnDataSizeChange(nsCacheEntry* entry, + int32_t deltaSize) { + LOG(("nsOfflineCacheDevice::OnDataSizeChange [key=%s delta=%d]\n", + entry->Key()->get(), deltaSize)); + + const int32_t DELTA_THRESHOLD = 1 << 14; // 16k + + // called to notify us of an impending change in the total size of the + // specified entry. + + uint32_t oldSize = entry->DataSize(); + NS_ASSERTION(deltaSize >= 0 || int32_t(oldSize) + deltaSize >= 0, "oops"); + uint32_t newSize = int32_t(oldSize) + deltaSize; + UpdateEntrySize(entry, newSize); + + mDeltaCounter += deltaSize; // this may go negative + + if (mDeltaCounter >= DELTA_THRESHOLD) { + if (CacheSize() > mCacheCapacity) { + // the entry will overrun the cache capacity, doom the entry + // and abort +#ifdef DEBUG + nsresult rv = +#endif + nsCacheService::DoomEntry(entry); + NS_ASSERTION(NS_SUCCEEDED(rv), "DoomEntry() failed."); + return NS_ERROR_ABORT; + } + + mDeltaCounter = 0; // reset counter + } + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::Visit(nsICacheVisitor* visitor) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + // called to enumerate the offline cache. + + nsCOMPtr<nsICacheDeviceInfo> deviceInfo = new nsOfflineCacheDeviceInfo(this); + + bool keepGoing; + nsresult rv = + visitor->VisitDevice(OFFLINE_CACHE_DEVICE_ID, deviceInfo, &keepGoing); + if (NS_FAILED(rv)) return rv; + + if (!keepGoing) return NS_OK; + + // SELECT * from moz_cache; + + nsOfflineCacheRecord rec; + RefPtr<nsOfflineCacheEntryInfo> info = new nsOfflineCacheEntryInfo; + if (!info) return NS_ERROR_OUT_OF_MEMORY; + info->mRec = &rec; + + // XXX may want to list columns explicitly + nsCOMPtr<mozIStorageStatement> statement; + rv = mDB->CreateStatement("SELECT * FROM moz_cache;"_ns, + getter_AddRefs(statement)); + NS_ENSURE_SUCCESS(rv, rv); + + bool hasRows; + for (;;) { + rv = statement->ExecuteStep(&hasRows); + if (NS_FAILED(rv) || !hasRows) break; + + statement->GetSharedUTF8String(0, nullptr, &rec.clientID); + statement->GetSharedUTF8String(1, nullptr, &rec.key); + statement->GetSharedBlob(2, &rec.metaDataLen, + (const uint8_t**)&rec.metaData); + rec.generation = statement->AsInt32(3); + rec.dataSize = statement->AsInt32(4); + rec.fetchCount = statement->AsInt32(5); + rec.lastFetched = statement->AsInt64(6); + rec.lastModified = statement->AsInt64(7); + rec.expirationTime = statement->AsInt64(8); + + bool keepGoing; + rv = visitor->VisitEntry(OFFLINE_CACHE_DEVICE_ID, info, &keepGoing); + if (NS_FAILED(rv) || !keepGoing) break; + } + + info->mRec = nullptr; + return NS_OK; +} + +nsresult nsOfflineCacheDevice::EvictEntries(const char* clientID) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + LOG(("nsOfflineCacheDevice::EvictEntries [cid=%s]\n", + clientID ? clientID : "")); + + // called to evict all entries matching the given clientID. + + // need trigger to fire user defined function after a row is deleted + // so we can delete the corresponding data file. + EvictionObserver evictionObserver(mDB, mEvictionFunction); + + nsCOMPtr<mozIStorageStatement> statement; + nsresult rv; + if (clientID) { + rv = mDB->CreateStatement("DELETE FROM moz_cache WHERE ClientID=?;"_ns, + getter_AddRefs(statement)); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->BindUTF8StringByIndex(0, nsDependentCString(clientID)); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->Execute(); + NS_ENSURE_SUCCESS(rv, rv); + + rv = mDB->CreateStatement( + nsLiteralCString( + "DELETE FROM moz_cache_groups WHERE ActiveClientID=?;"), + getter_AddRefs(statement)); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->BindUTF8StringByIndex(0, nsDependentCString(clientID)); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->Execute(); + NS_ENSURE_SUCCESS(rv, rv); + + // TODO - Should update internal hashtables. + // Low priority, since this API is not widely used. + } else { + rv = mDB->CreateStatement("DELETE FROM moz_cache;"_ns, + getter_AddRefs(statement)); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->Execute(); + NS_ENSURE_SUCCESS(rv, rv); + + rv = mDB->CreateStatement("DELETE FROM moz_cache_groups;"_ns, + getter_AddRefs(statement)); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->Execute(); + NS_ENSURE_SUCCESS(rv, rv); + + MutexAutoLock lock(mLock); + mCaches.Clear(); + mActiveCaches.Clear(); + mActiveCachesByGroup.Clear(); + } + + evictionObserver.Apply(); + + statement = nullptr; + // Also evict any namespaces associated with this clientID. + if (clientID) { + rv = mDB->CreateStatement( + "DELETE FROM moz_cache_namespaces WHERE ClientID=?"_ns, + getter_AddRefs(statement)); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->BindUTF8StringByIndex(0, nsDependentCString(clientID)); + NS_ENSURE_SUCCESS(rv, rv); + } else { + rv = mDB->CreateStatement("DELETE FROM moz_cache_namespaces;"_ns, + getter_AddRefs(statement)); + NS_ENSURE_SUCCESS(rv, rv); + } + + rv = statement->Execute(); + NS_ENSURE_SUCCESS(rv, rv); + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::MarkEntry(const nsCString& clientID, + const nsACString& key, + uint32_t typeBits) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + LOG(("nsOfflineCacheDevice::MarkEntry [cid=%s, key=%s, typeBits=%d]\n", + clientID.get(), PromiseFlatCString(key).get(), typeBits)); + + AutoResetStatement statement(mStatement_MarkEntry); + nsresult rv = statement->BindInt32ByIndex(0, typeBits); + NS_ENSURE_SUCCESS(rv, rv); + rv = statement->BindUTF8StringByIndex(1, clientID); + NS_ENSURE_SUCCESS(rv, rv); + rv = statement->BindUTF8StringByIndex(2, key); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->Execute(); + NS_ENSURE_SUCCESS(rv, rv); + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::UnmarkEntry(const nsCString& clientID, + const nsACString& key, + uint32_t typeBits) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + LOG(("nsOfflineCacheDevice::UnmarkEntry [cid=%s, key=%s, typeBits=%d]\n", + clientID.get(), PromiseFlatCString(key).get(), typeBits)); + + AutoResetStatement statement(mStatement_UnmarkEntry); + nsresult rv = statement->BindInt32ByIndex(0, typeBits); + NS_ENSURE_SUCCESS(rv, rv); + rv = statement->BindUTF8StringByIndex(1, clientID); + NS_ENSURE_SUCCESS(rv, rv); + rv = statement->BindUTF8StringByIndex(2, key); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->Execute(); + NS_ENSURE_SUCCESS(rv, rv); + + // Remove the entry if it is now empty. + + EvictionObserver evictionObserver(mDB, mEvictionFunction); + + AutoResetStatement cleanupStatement(mStatement_CleanupUnmarked); + rv = cleanupStatement->BindUTF8StringByIndex(0, clientID); + NS_ENSURE_SUCCESS(rv, rv); + rv = cleanupStatement->BindUTF8StringByIndex(1, key); + NS_ENSURE_SUCCESS(rv, rv); + + rv = cleanupStatement->Execute(); + NS_ENSURE_SUCCESS(rv, rv); + + evictionObserver.Apply(); + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::GetMatchingNamespace( + const nsCString& clientID, const nsACString& key, + nsIApplicationCacheNamespace** out) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + LOG(("nsOfflineCacheDevice::GetMatchingNamespace [cid=%s, key=%s]\n", + clientID.get(), PromiseFlatCString(key).get())); + + nsresult rv; + + AutoResetStatement statement(mStatement_FindNamespaceEntry); + + rv = statement->BindUTF8StringByIndex(0, clientID); + NS_ENSURE_SUCCESS(rv, rv); + rv = statement->BindUTF8StringByIndex(1, key); + NS_ENSURE_SUCCESS(rv, rv); + + bool hasRows; + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + + *out = nullptr; + + bool found = false; + nsCString nsSpec; + int32_t nsType = 0; + nsCString nsData; + + while (hasRows) { + int32_t itemType; + rv = statement->GetInt32(2, &itemType); + NS_ENSURE_SUCCESS(rv, rv); + + if (!found || itemType > nsType) { + nsType = itemType; + + rv = statement->GetUTF8String(0, nsSpec); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->GetUTF8String(1, nsData); + NS_ENSURE_SUCCESS(rv, rv); + + found = true; + } + + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + } + + if (found) { + nsCOMPtr<nsIApplicationCacheNamespace> ns = + new nsApplicationCacheNamespace(); + if (!ns) return NS_ERROR_OUT_OF_MEMORY; + rv = ns->Init(nsType, nsSpec, nsData); + NS_ENSURE_SUCCESS(rv, rv); + + ns.swap(*out); + } + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::CacheOpportunistically(const nsCString& clientID, + const nsACString& key) { + // XXX: We should also be propagating this cache entry to other matching + // caches. See bug 444807. + + return MarkEntry(clientID, key, nsIApplicationCache::ITEM_OPPORTUNISTIC); +} + +nsresult nsOfflineCacheDevice::GetTypes(const nsCString& clientID, + const nsACString& key, + uint32_t* typeBits) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + LOG(("nsOfflineCacheDevice::GetTypes [cid=%s, key=%s]\n", clientID.get(), + PromiseFlatCString(key).get())); + + AutoResetStatement statement(mStatement_GetTypes); + nsresult rv = statement->BindUTF8StringByIndex(0, clientID); + NS_ENSURE_SUCCESS(rv, rv); + rv = statement->BindUTF8StringByIndex(1, key); + NS_ENSURE_SUCCESS(rv, rv); + + bool hasRows; + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + + if (!hasRows) return NS_ERROR_CACHE_KEY_NOT_FOUND; + + *typeBits = statement->AsInt32(0); + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::GatherEntries(const nsCString& clientID, + uint32_t typeBits, + nsTArray<nsCString>& keys) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + LOG(("nsOfflineCacheDevice::GatherEntries [cid=%s, typeBits=%X]\n", + clientID.get(), typeBits)); + + AutoResetStatement statement(mStatement_GatherEntries); + nsresult rv = statement->BindUTF8StringByIndex(0, clientID); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->BindInt32ByIndex(1, typeBits); + NS_ENSURE_SUCCESS(rv, rv); + + return RunSimpleQuery(mStatement_GatherEntries, 0, keys); +} + +nsresult nsOfflineCacheDevice::AddNamespace(const nsCString& clientID, + nsIApplicationCacheNamespace* ns) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + nsCString namespaceSpec; + nsresult rv = ns->GetNamespaceSpec(namespaceSpec); + NS_ENSURE_SUCCESS(rv, rv); + + nsCString data; + rv = ns->GetData(data); + NS_ENSURE_SUCCESS(rv, rv); + + uint32_t itemType; + rv = ns->GetItemType(&itemType); + NS_ENSURE_SUCCESS(rv, rv); + + LOG(("nsOfflineCacheDevice::AddNamespace [cid=%s, ns=%s, data=%s, type=%d]", + clientID.get(), namespaceSpec.get(), data.get(), itemType)); + + AutoResetStatement statement(mStatement_InsertNamespaceEntry); + + rv = statement->BindUTF8StringByIndex(0, clientID); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->BindUTF8StringByIndex(1, namespaceSpec); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->BindUTF8StringByIndex(2, data); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->BindInt32ByIndex(3, itemType); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->Execute(); + NS_ENSURE_SUCCESS(rv, rv); + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::GetUsage(const nsACString& clientID, + uint32_t* usage) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + LOG(("nsOfflineCacheDevice::GetUsage [cid=%s]\n", + PromiseFlatCString(clientID).get())); + + *usage = 0; + + AutoResetStatement statement(mStatement_ApplicationCacheSize); + + nsresult rv = statement->BindUTF8StringByIndex(0, clientID); + NS_ENSURE_SUCCESS(rv, rv); + + bool hasRows; + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + + if (!hasRows) return NS_OK; + + *usage = static_cast<uint32_t>(statement->AsInt32(0)); + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::GetGroups(nsTArray<nsCString>& keys) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + LOG(("nsOfflineCacheDevice::GetGroups")); + + return RunSimpleQuery(mStatement_EnumerateGroups, 0, keys); +} + +nsresult nsOfflineCacheDevice::GetGroupsTimeOrdered(nsTArray<nsCString>& keys) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + LOG(("nsOfflineCacheDevice::GetGroupsTimeOrder")); + + return RunSimpleQuery(mStatement_EnumerateGroupsTimeOrder, 0, keys); +} + +bool nsOfflineCacheDevice::IsLocked(const nsACString& key) { + MutexAutoLock lock(mLock); + return mLockedEntries.GetEntry(key); +} + +void nsOfflineCacheDevice::Lock(const nsACString& key) { + MutexAutoLock lock(mLock); + mLockedEntries.PutEntry(key); +} + +void nsOfflineCacheDevice::Unlock(const nsACString& key) { + MutexAutoLock lock(mLock); + mLockedEntries.RemoveEntry(key); +} + +nsresult nsOfflineCacheDevice::RunSimpleQuery(mozIStorageStatement* statement, + uint32_t resultIndex, + nsTArray<nsCString>& values) { + bool hasRows; + nsresult rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + + nsTArray<nsCString> valArray; + while (hasRows) { + uint32_t length; + valArray.AppendElement(nsDependentCString( + statement->AsSharedUTF8String(resultIndex, &length))); + + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + } + + values = std::move(valArray); + return NS_OK; +} + +nsresult nsOfflineCacheDevice::CreateApplicationCache( + const nsACString& group, nsIApplicationCache** out) { + *out = nullptr; + + nsCString clientID; + // Some characters are special in the clientID. Escape the groupID + // before putting it in to the client key. + if (!NS_Escape(nsCString(group), clientID, url_Path)) { + return NS_ERROR_OUT_OF_MEMORY; + } + + PRTime now = PR_Now(); + + // Include the timestamp to guarantee uniqueness across runs, and + // the gNextTemporaryClientID for uniqueness within a second. + clientID.Append(nsPrintfCString("|%016" PRId64 "|%d", now / PR_USEC_PER_SEC, + gNextTemporaryClientID++)); + + nsCOMPtr<nsIApplicationCache> cache = + new nsApplicationCache(this, group, clientID); + if (!cache) return NS_ERROR_OUT_OF_MEMORY; + + nsWeakPtr weak = do_GetWeakReference(cache); + if (!weak) return NS_ERROR_OUT_OF_MEMORY; + + MutexAutoLock lock(mLock); + mCaches.Put(clientID, weak); + + cache.swap(*out); + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::GetApplicationCache(const nsACString& clientID, + nsIApplicationCache** out) { + MutexAutoLock lock(mLock); + return GetApplicationCache_Unlocked(clientID, out); +} + +nsresult nsOfflineCacheDevice::GetApplicationCache_Unlocked( + const nsACString& clientID, nsIApplicationCache** out) { + *out = nullptr; + + nsCOMPtr<nsIApplicationCache> cache; + + nsWeakPtr weak; + if (mCaches.Get(clientID, getter_AddRefs(weak))) + cache = do_QueryReferent(weak); + + if (!cache) { + nsCString group; + nsresult rv = GetGroupForCache(clientID, group); + NS_ENSURE_SUCCESS(rv, rv); + + if (group.IsEmpty()) { + return NS_OK; + } + + cache = new nsApplicationCache(this, group, clientID); + weak = do_GetWeakReference(cache); + if (!weak) return NS_ERROR_OUT_OF_MEMORY; + + mCaches.Put(clientID, weak); + } + + cache.swap(*out); + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::GetActiveCache(const nsACString& group, + nsIApplicationCache** out) { + *out = nullptr; + + MutexAutoLock lock(mLock); + + nsCString* clientID; + if (mActiveCachesByGroup.Get(group, &clientID)) + return GetApplicationCache_Unlocked(*clientID, out); + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::DeactivateGroup(const nsACString& group) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + nsCString* active = nullptr; + + AutoResetStatement statement(mStatement_DeactivateGroup); + nsresult rv = statement->BindUTF8StringByIndex(0, group); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->Execute(); + NS_ENSURE_SUCCESS(rv, rv); + + MutexAutoLock lock(mLock); + + if (mActiveCachesByGroup.Get(group, &active)) { + mActiveCaches.RemoveEntry(*active); + mActiveCachesByGroup.Remove(group); + active = nullptr; + } + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::Evict(nsILoadContextInfo* aInfo) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + NS_ENSURE_ARG(aInfo); + + nsresult rv; + + mozilla::OriginAttributes const* oa = aInfo->OriginAttributesPtr(); + + if (oa->mInIsolatedMozBrowser == false) { + nsCOMPtr<nsICacheService> serv = do_GetService(kCacheServiceCID, &rv); + NS_ENSURE_SUCCESS(rv, rv); + + return nsCacheService::GlobalInstance()->EvictEntriesInternal( + nsICache::STORE_OFFLINE); + } + + nsAutoCString jaridsuffix; + jaridsuffix.Append('%'); + + nsAutoCString suffix; + oa->CreateSuffix(suffix); + jaridsuffix.Append('#'); + jaridsuffix.Append(suffix); + + AutoResetStatement statement(mStatement_EnumerateApps); + rv = statement->BindUTF8StringByIndex(0, jaridsuffix); + NS_ENSURE_SUCCESS(rv, rv); + + bool hasRows; + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + + while (hasRows) { + nsAutoCString group; + rv = statement->GetUTF8String(0, group); + NS_ENSURE_SUCCESS(rv, rv); + + nsCString clientID; + rv = statement->GetUTF8String(1, clientID); + NS_ENSURE_SUCCESS(rv, rv); + + nsCOMPtr<nsIRunnable> ev = + new nsOfflineCacheDiscardCache(this, group, clientID); + + rv = nsCacheService::DispatchToCacheIOThread(ev); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + } + + return NS_OK; +} + +namespace { // anon + +class OriginMatch final : public mozIStorageFunction { + ~OriginMatch() = default; + mozilla::OriginAttributesPattern const mPattern; + + NS_DECL_ISUPPORTS + NS_DECL_MOZISTORAGEFUNCTION + explicit OriginMatch(mozilla::OriginAttributesPattern const& aPattern) + : mPattern(aPattern) {} +}; + +NS_IMPL_ISUPPORTS(OriginMatch, mozIStorageFunction) + +NS_IMETHODIMP +OriginMatch::OnFunctionCall(mozIStorageValueArray* aFunctionArguments, + nsIVariant** aResult) { + nsresult rv; + + nsAutoCString groupId; + rv = aFunctionArguments->GetUTF8String(0, groupId); + NS_ENSURE_SUCCESS(rv, rv); + + int32_t hash = groupId.Find("#"_ns); + if (hash == kNotFound) { + // Just ignore... + return NS_OK; + } + + ++hash; + + nsDependentCSubstring suffix(groupId.BeginReading() + hash, + groupId.Length() - hash); + + mozilla::OriginAttributes oa; + bool ok = oa.PopulateFromSuffix(suffix); + NS_ENSURE_TRUE(ok, NS_ERROR_UNEXPECTED); + + bool match = mPattern.Matches(oa); + + RefPtr<nsVariant> outVar(new nsVariant()); + rv = outVar->SetAsUint32(match ? 1 : 0); + NS_ENSURE_SUCCESS(rv, rv); + + outVar.forget(aResult); + return NS_OK; +} + +} // namespace + +nsresult nsOfflineCacheDevice::Evict( + mozilla::OriginAttributesPattern const& aPattern) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + nsresult rv; + + nsCOMPtr<mozIStorageFunction> function1(new OriginMatch(aPattern)); + rv = mDB->CreateFunction("ORIGIN_MATCH"_ns, 1, function1); + NS_ENSURE_SUCCESS(rv, rv); + + class AutoRemoveFunc { + public: + mozIStorageConnection* mDB; + explicit AutoRemoveFunc(mozIStorageConnection* aDB) : mDB(aDB) {} + ~AutoRemoveFunc() { mDB->RemoveFunction("ORIGIN_MATCH"_ns); } + }; + AutoRemoveFunc autoRemove(mDB); + + nsCOMPtr<mozIStorageStatement> statement; + rv = mDB->CreateStatement( + nsLiteralCString("SELECT GroupID, ActiveClientID FROM moz_cache_groups " + "WHERE ORIGIN_MATCH(GroupID);"), + getter_AddRefs(statement)); + NS_ENSURE_SUCCESS(rv, rv); + + AutoResetStatement statementScope(statement); + + bool hasRows; + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + + while (hasRows) { + nsAutoCString group; + rv = statement->GetUTF8String(0, group); + NS_ENSURE_SUCCESS(rv, rv); + + nsCString clientID; + rv = statement->GetUTF8String(1, clientID); + NS_ENSURE_SUCCESS(rv, rv); + + nsCOMPtr<nsIRunnable> ev = + new nsOfflineCacheDiscardCache(this, group, clientID); + + rv = nsCacheService::DispatchToCacheIOThread(ev); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + } + + return NS_OK; +} + +bool nsOfflineCacheDevice::CanUseCache(nsIURI* keyURI, + const nsACString& clientID, + nsILoadContextInfo* loadContextInfo) { + { + MutexAutoLock lock(mLock); + if (!mActiveCaches.Contains(clientID)) return false; + } + + nsAutoCString groupID; + nsresult rv = GetGroupForCache(clientID, groupID); + NS_ENSURE_SUCCESS(rv, false); + + nsCOMPtr<nsIURI> groupURI; + rv = NS_NewURI(getter_AddRefs(groupURI), groupID); + if (NS_FAILED(rv)) { + return false; + } + + // When we are choosing an initial cache to load the top + // level document from, the URL of that document must have + // the same origin as the manifest, according to the spec. + // The following check is here because explicit, fallback + // and dynamic entries might have origin different from the + // manifest origin. + if (!NS_SecurityCompareURIs(keyURI, groupURI, GetStrictFileOriginPolicy())) { + return false; + } + + // Check the groupID we found is equal to groupID based + // on the load context demanding load from app cache. + // This is check of extended origin. + + nsAutoCString originSuffix; + loadContextInfo->OriginAttributesPtr()->CreateSuffix(originSuffix); + + nsAutoCString demandedGroupID; + rv = BuildApplicationCacheGroupID(groupURI, originSuffix, demandedGroupID); + NS_ENSURE_SUCCESS(rv, false); + + if (groupID != demandedGroupID) { + return false; + } + + return true; +} + +nsresult nsOfflineCacheDevice::ChooseApplicationCache( + const nsACString& key, nsILoadContextInfo* loadContextInfo, + nsIApplicationCache** out) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + NS_ENSURE_ARG(loadContextInfo); + + nsresult rv; + + *out = nullptr; + + nsCOMPtr<nsIURI> keyURI; + rv = NS_NewURI(getter_AddRefs(keyURI), key); + NS_ENSURE_SUCCESS(rv, rv); + + // First try to find a matching cache entry. + AutoResetStatement statement(mStatement_FindClient); + rv = statement->BindUTF8StringByIndex(0, key); + NS_ENSURE_SUCCESS(rv, rv); + + bool hasRows; + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + + while (hasRows) { + int32_t itemType; + rv = statement->GetInt32(1, &itemType); + NS_ENSURE_SUCCESS(rv, rv); + + if (!(itemType & nsIApplicationCache::ITEM_FOREIGN)) { + nsAutoCString clientID; + rv = statement->GetUTF8String(0, clientID); + NS_ENSURE_SUCCESS(rv, rv); + + if (CanUseCache(keyURI, clientID, loadContextInfo)) { + return GetApplicationCache(clientID, out); + } + } + + rv = statement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + } + + // OK, we didn't find an exact match. Search for a client with a + // matching namespace. + + AutoResetStatement nsstatement(mStatement_FindClientByNamespace); + + rv = nsstatement->BindUTF8StringByIndex(0, key); + NS_ENSURE_SUCCESS(rv, rv); + + rv = nsstatement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + + while (hasRows) { + int32_t itemType; + rv = nsstatement->GetInt32(1, &itemType); + NS_ENSURE_SUCCESS(rv, rv); + + // Don't associate with a cache based solely on a whitelist entry + if (!(itemType & nsIApplicationCacheNamespace::NAMESPACE_BYPASS)) { + nsAutoCString clientID; + rv = nsstatement->GetUTF8String(0, clientID); + NS_ENSURE_SUCCESS(rv, rv); + + if (CanUseCache(keyURI, clientID, loadContextInfo)) { + return GetApplicationCache(clientID, out); + } + } + + rv = nsstatement->ExecuteStep(&hasRows); + NS_ENSURE_SUCCESS(rv, rv); + } + + return NS_OK; +} + +nsresult nsOfflineCacheDevice::CacheOpportunistically( + nsIApplicationCache* cache, const nsACString& key) { + NS_ENSURE_ARG_POINTER(cache); + + nsresult rv; + + nsAutoCString clientID; + rv = cache->GetClientID(clientID); + NS_ENSURE_SUCCESS(rv, rv); + + return CacheOpportunistically(clientID, key); +} + +nsresult nsOfflineCacheDevice::ActivateCache(const nsACString& group, + const nsACString& clientID) { + NS_ENSURE_TRUE(Initialized(), NS_ERROR_NOT_INITIALIZED); + + AutoResetStatement statement(mStatement_ActivateClient); + nsresult rv = statement->BindUTF8StringByIndex(0, group); + NS_ENSURE_SUCCESS(rv, rv); + rv = statement->BindUTF8StringByIndex(1, clientID); + NS_ENSURE_SUCCESS(rv, rv); + rv = statement->BindInt32ByIndex(2, SecondsFromPRTime(PR_Now())); + NS_ENSURE_SUCCESS(rv, rv); + + rv = statement->Execute(); + NS_ENSURE_SUCCESS(rv, rv); + + MutexAutoLock lock(mLock); + + nsCString* active; + if (mActiveCachesByGroup.Get(group, &active)) { + mActiveCaches.RemoveEntry(*active); + mActiveCachesByGroup.Remove(group); + active = nullptr; + } + + if (!clientID.IsEmpty()) { + mActiveCaches.PutEntry(clientID); + mActiveCachesByGroup.Put(group, new nsCString(clientID)); + } + + return NS_OK; +} + +bool nsOfflineCacheDevice::IsActiveCache(const nsACString& group, + const nsACString& clientID) { + nsCString* active = nullptr; + MutexAutoLock lock(mLock); + return mActiveCachesByGroup.Get(group, &active) && *active == clientID; +} + +/** + * Preference accessors + */ + +void nsOfflineCacheDevice::SetCacheParentDirectory(nsIFile* parentDir) { + if (Initialized()) { + NS_ERROR("cannot switch cache directory once initialized"); + return; + } + + if (!parentDir) { + mCacheDirectory = nullptr; + return; + } + + // ensure parent directory exists + nsresult rv = EnsureDir(parentDir); + if (NS_FAILED(rv)) { + NS_WARNING("unable to create parent directory"); + return; + } + + mBaseDirectory = parentDir; + + // cache dir may not exist, but that's ok + nsCOMPtr<nsIFile> dir; + rv = parentDir->Clone(getter_AddRefs(dir)); + if (NS_FAILED(rv)) return; + rv = dir->AppendNative("OfflineCache"_ns); + if (NS_FAILED(rv)) return; + + mCacheDirectory = dir; +} + +void nsOfflineCacheDevice::SetCapacity(uint32_t capacity) { + mCacheCapacity = capacity * 1024; +} + +bool nsOfflineCacheDevice::AutoShutdown(nsIApplicationCache* aAppCache) { + if (!mAutoShutdown) return false; + + mAutoShutdown = false; + + Shutdown(); + + nsCOMPtr<nsICacheService> serv = do_GetService(kCacheServiceCID); + RefPtr<nsCacheService> cacheService = nsCacheService::GlobalInstance(); + cacheService->RemoveCustomOfflineDevice(this); + + nsAutoCString clientID; + aAppCache->GetClientID(clientID); + + MutexAutoLock lock(mLock); + mCaches.Remove(clientID); + + return true; +} diff --git a/netwerk/cache/nsDiskCacheDeviceSQL.h b/netwerk/cache/nsDiskCacheDeviceSQL.h new file mode 100644 index 0000000000..772bc21b83 --- /dev/null +++ b/netwerk/cache/nsDiskCacheDeviceSQL.h @@ -0,0 +1,263 @@ +/* vim:set ts=2 sw=2 sts=2 et cin: */ +/* 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/. */ + +#ifndef nsOfflineCacheDevice_h__ +#define nsOfflineCacheDevice_h__ + +#include "nsCacheDevice.h" +#include "nsIApplicationCache.h" +#include "mozIStorageConnection.h" +#include "mozIStorageFunction.h" +#include "nsIFile.h" +#include "nsCOMPtr.h" +#include "nsCOMArray.h" +#include "nsInterfaceHashtable.h" +#include "nsClassHashtable.h" +#include "nsIWeakReference.h" +#include "mozilla/Attributes.h" +#include "mozilla/Mutex.h" + +class nsIURI; +class nsOfflineCacheDevice; +class mozIStorageService; +class nsILoadContextInfo; +namespace mozilla { +class OriginAttributesPattern; +} + +class nsApplicationCacheNamespace final : public nsIApplicationCacheNamespace { + public: + NS_DECL_ISUPPORTS + NS_DECL_NSIAPPLICATIONCACHENAMESPACE + + nsApplicationCacheNamespace() : mItemType(0) {} + + private: + ~nsApplicationCacheNamespace() = default; + + uint32_t mItemType; + nsCString mNamespaceSpec; + nsCString mData; +}; + +class nsOfflineCacheEvictionFunction final : public mozIStorageFunction { + public: + NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_MOZISTORAGEFUNCTION + + explicit nsOfflineCacheEvictionFunction(nsOfflineCacheDevice* device); + + void Init(); + void Reset(); + void Apply(); + + private: + ~nsOfflineCacheEvictionFunction() = default; + + nsOfflineCacheDevice* mDevice; + bool mTLSInited; +}; + +class nsOfflineCacheDevice final : public nsCacheDevice, public nsISupports { + public: + nsOfflineCacheDevice(); + + NS_DECL_THREADSAFE_ISUPPORTS + + /** + * nsCacheDevice methods + */ + + virtual nsresult Init() override; + nsresult InitWithSqlite(mozIStorageService* ss); + virtual nsresult Shutdown() override; + + virtual const char* GetDeviceID(void) override; + virtual nsCacheEntry* FindEntry(nsCString* key, bool* collision) override; + virtual nsresult DeactivateEntry(nsCacheEntry* entry) override; + virtual nsresult BindEntry(nsCacheEntry* entry) override; + virtual void DoomEntry(nsCacheEntry* entry) override; + + virtual nsresult OpenInputStreamForEntry(nsCacheEntry* entry, + nsCacheAccessMode mode, + uint32_t offset, + nsIInputStream** result) override; + + virtual nsresult OpenOutputStreamForEntry(nsCacheEntry* entry, + nsCacheAccessMode mode, + uint32_t offset, + nsIOutputStream** result) override; + + virtual nsresult GetFileForEntry(nsCacheEntry* entry, + nsIFile** result) override; + + virtual nsresult OnDataSizeChange(nsCacheEntry* entry, + int32_t deltaSize) override; + + virtual nsresult Visit(nsICacheVisitor* visitor) override; + + virtual nsresult EvictEntries(const char* clientID) override; + + /* Entry ownership */ + nsresult GetOwnerDomains(const char* clientID, uint32_t* count, + char*** domains); + nsresult GetOwnerURIs(const char* clientID, const nsACString& ownerDomain, + uint32_t* count, char*** uris); + nsresult SetOwnedKeys(const char* clientID, const nsACString& ownerDomain, + const nsACString& ownerUrl, uint32_t count, + const char** keys); + nsresult GetOwnedKeys(const char* clientID, const nsACString& ownerDomain, + const nsACString& ownerUrl, uint32_t* count, + char*** keys); + nsresult AddOwnedKey(const char* clientID, const nsACString& ownerDomain, + const nsACString& ownerURI, const nsACString& key); + nsresult RemoveOwnedKey(const char* clientID, const nsACString& ownerDomain, + const nsACString& ownerURI, const nsACString& key); + nsresult KeyIsOwned(const char* clientID, const nsACString& ownerDomain, + const nsACString& ownerURI, const nsACString& key, + bool* isOwned); + + nsresult ClearKeysOwnedByDomain(const char* clientID, + const nsACString& ownerDomain); + nsresult EvictUnownedEntries(const char* clientID); + + static nsresult BuildApplicationCacheGroupID(nsIURI* aManifestURL, + nsACString const& aOriginSuffix, + nsACString& _result); + + nsresult ActivateCache(const nsACString& group, const nsACString& clientID); + bool IsActiveCache(const nsACString& group, const nsACString& clientID); + nsresult CreateApplicationCache(const nsACString& group, + nsIApplicationCache** out); + + nsresult GetApplicationCache(const nsACString& clientID, + nsIApplicationCache** out); + nsresult GetApplicationCache_Unlocked(const nsACString& clientID, + nsIApplicationCache** out); + + nsresult GetActiveCache(const nsACString& group, nsIApplicationCache** out); + + nsresult DeactivateGroup(const nsACString& group); + + nsresult ChooseApplicationCache(const nsACString& key, + nsILoadContextInfo* loadContext, + nsIApplicationCache** out); + + nsresult CacheOpportunistically(nsIApplicationCache* cache, + const nsACString& key); + + nsresult Evict(nsILoadContextInfo* aInfo); + nsresult Evict(mozilla::OriginAttributesPattern const& aPattern); + + nsresult GetGroups(nsTArray<nsCString>& keys); + + nsresult GetGroupsTimeOrdered(nsTArray<nsCString>& keys); + + bool IsLocked(const nsACString& key); + void Lock(const nsACString& key); + void Unlock(const nsACString& key); + + /** + * Preference accessors + */ + + void SetCacheParentDirectory(nsIFile* parentDir); + void SetCapacity(uint32_t capacity); + void SetAutoShutdown() { mAutoShutdown = true; } + bool AutoShutdown(nsIApplicationCache* aAppCache); + + nsIFile* BaseDirectory() { return mBaseDirectory; } + nsIFile* CacheDirectory() { return mCacheDirectory; } + uint32_t CacheCapacity() { return mCacheCapacity; } + uint32_t CacheSize(); + uint32_t EntryCount(); + + private: + ~nsOfflineCacheDevice() = default; + + friend class nsApplicationCache; + + static bool GetStrictFileOriginPolicy(); + + bool Initialized() { return mDB != nullptr; } + + nsresult InitActiveCaches(); + nsresult UpdateEntry(nsCacheEntry* entry); + nsresult UpdateEntrySize(nsCacheEntry* entry, uint32_t newSize); + nsresult DeleteEntry(nsCacheEntry* entry, bool deleteData); + nsresult DeleteData(nsCacheEntry* entry); + nsresult EnableEvictionObserver(); + nsresult DisableEvictionObserver(); + + bool CanUseCache(nsIURI* keyURI, const nsACString& clientID, + nsILoadContextInfo* loadContext); + + nsresult MarkEntry(const nsCString& clientID, const nsACString& key, + uint32_t typeBits); + nsresult UnmarkEntry(const nsCString& clientID, const nsACString& key, + uint32_t typeBits); + + nsresult CacheOpportunistically(const nsCString& clientID, + const nsACString& key); + nsresult GetTypes(const nsCString& clientID, const nsACString& key, + uint32_t* typeBits); + + nsresult GetMatchingNamespace(const nsCString& clientID, + const nsACString& key, + nsIApplicationCacheNamespace** out); + nsresult GatherEntries(const nsCString& clientID, uint32_t typeBits, + nsTArray<nsCString>& keys); + nsresult AddNamespace(const nsCString& clientID, + nsIApplicationCacheNamespace* ns); + + nsresult GetUsage(const nsACString& clientID, uint32_t* usage); + + nsresult RunSimpleQuery(mozIStorageStatement* statment, uint32_t resultIndex, + nsTArray<nsCString>& values); + + nsCOMPtr<mozIStorageConnection> mDB; + RefPtr<nsOfflineCacheEvictionFunction> mEvictionFunction; + + nsCOMPtr<mozIStorageStatement> mStatement_CacheSize; + nsCOMPtr<mozIStorageStatement> mStatement_ApplicationCacheSize; + nsCOMPtr<mozIStorageStatement> mStatement_EntryCount; + nsCOMPtr<mozIStorageStatement> mStatement_UpdateEntry; + nsCOMPtr<mozIStorageStatement> mStatement_UpdateEntrySize; + nsCOMPtr<mozIStorageStatement> mStatement_DeleteEntry; + nsCOMPtr<mozIStorageStatement> mStatement_FindEntry; + nsCOMPtr<mozIStorageStatement> mStatement_BindEntry; + nsCOMPtr<mozIStorageStatement> mStatement_ClearDomain; + nsCOMPtr<mozIStorageStatement> mStatement_MarkEntry; + nsCOMPtr<mozIStorageStatement> mStatement_UnmarkEntry; + nsCOMPtr<mozIStorageStatement> mStatement_GetTypes; + nsCOMPtr<mozIStorageStatement> mStatement_FindNamespaceEntry; + nsCOMPtr<mozIStorageStatement> mStatement_InsertNamespaceEntry; + nsCOMPtr<mozIStorageStatement> mStatement_CleanupUnmarked; + nsCOMPtr<mozIStorageStatement> mStatement_GatherEntries; + nsCOMPtr<mozIStorageStatement> mStatement_ActivateClient; + nsCOMPtr<mozIStorageStatement> mStatement_DeactivateGroup; + nsCOMPtr<mozIStorageStatement> mStatement_FindClient; + nsCOMPtr<mozIStorageStatement> mStatement_FindClientByNamespace; + nsCOMPtr<mozIStorageStatement> mStatement_EnumerateApps; + nsCOMPtr<mozIStorageStatement> mStatement_EnumerateGroups; + nsCOMPtr<mozIStorageStatement> mStatement_EnumerateGroupsTimeOrder; + + nsCOMPtr<nsIFile> mBaseDirectory; + nsCOMPtr<nsIFile> mCacheDirectory; + uint32_t mCacheCapacity; // in bytes + int32_t mDeltaCounter; + bool mAutoShutdown; + + mozilla::Mutex mLock; + + nsInterfaceHashtable<nsCStringHashKey, nsIWeakReference> mCaches; + nsClassHashtable<nsCStringHashKey, nsCString> mActiveCachesByGroup; + nsTHashtable<nsCStringHashKey> mActiveCaches; + nsTHashtable<nsCStringHashKey> mLockedEntries; + + nsCOMPtr<nsIEventTarget> mInitEventTarget; +}; + +#endif // nsOfflineCacheDevice_h__ diff --git a/netwerk/cache/nsICache.idl b/netwerk/cache/nsICache.idl new file mode 100644 index 0000000000..cd14c98312 --- /dev/null +++ b/netwerk/cache/nsICache.idl @@ -0,0 +1,142 @@ +/* -*- Mode: IDL; 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 "nsISupports.idl" + +typedef long nsCacheStoragePolicy; +typedef long nsCacheAccessMode; + +/** + * nsICache is a namespace for various cache constants. It does not represent + * an actual object. + */ +[builtinclass, uuid(d6c67f38-b39a-4582-8a48-4c4f8a56dfd0)] +interface nsICache : nsISupports +{ + /** + * Access Modes + * + * + * Mode Requested | Not Cached | Cached + * ------------------------------------------------------------------------ + * READ | KEY_NOT_FOUND | NS_OK + * | Mode = NONE | Mode = READ + * | No Descriptor | Descriptor + * ------------------------------------------------------------------------ + * WRITE | NS_OK | NS_OK (Cache service + * | Mode = WRITE | Mode = WRITE dooms existing + * | Descriptor | Descriptor cache entry) + * ------------------------------------------------------------------------ + * READ_WRITE | NS_OK | NS_OK + * (1st req.) | Mode = WRITE | Mode = READ_WRITE + * | Descriptor | Descriptor + * ------------------------------------------------------------------------ + * READ_WRITE | N/A | NS_OK + * (Nth req.) | | Mode = READ + * | | Descriptor + * ------------------------------------------------------------------------ + * + * + * Access Requested: + * + * READ - I only want to READ, if there isn't an entry just fail + * WRITE - I have something new I want to write into the cache, make + * me a new entry and doom the old one, if any. + * READ_WRITE - I want to READ, but I'm willing to update an existing + * entry if necessary, or create a new one if none exists. + * + * + * Access Granted: + * + * NONE - No descriptor is provided. You get zilch. Nada. Nothing. + * READ - You can READ from this descriptor. + * WRITE - You must WRITE to this descriptor because the cache entry + * was just created for you. + * READ_WRITE - You can READ the descriptor to determine if it's valid, + * you may WRITE if it needs updating. + * + * + * Comments: + * + * If you think that you might need to modify cached data or meta data, + * then you must open a cache entry requesting WRITE access. Only one + * cache entry descriptor, per cache entry, will be granted WRITE access. + * + * Usually, you will request READ_WRITE access in order to first test the + * meta data and informational fields to determine if a write (ie. going + * to the net) may actually be necessary. If you determine that it is + * not, then you would mark the cache entry as valid (using MarkValid) and + * then simply read the data from the cache. + * + * A descriptor granted WRITE access has exclusive access to the cache + * entry up to the point at which it marks it as valid. Once the cache + * entry has been "validated", other descriptors with READ access may be + * opened to the cache entry. + * + * If you make a request for READ_WRITE access to a cache entry, the cache + * service will downgrade your access to READ if there is already a + * cache entry descriptor open with WRITE access. + * + * If you make a request for only WRITE access to a cache entry and another + * descriptor with WRITE access is currently open, then the existing cache + * entry will be 'doomed', and you will be given a descriptor (with WRITE + * access only) to a new cache entry. + * + */ + const nsCacheAccessMode ACCESS_NONE = 0; + const nsCacheAccessMode ACCESS_READ = 1; + const nsCacheAccessMode ACCESS_WRITE = 2; + const nsCacheAccessMode ACCESS_READ_WRITE = 3; + + /** + * Storage Policy + * + * The storage policy of a cache entry determines the device(s) to which + * it belongs. See nsICacheSession and nsICacheEntryDescriptor for more + * details. + * + * STORE_ANYWHERE - Allows the cache entry to be stored in any device. + * The cache service decides which cache device to use + * based on "some resource management calculation." + * STORE_IN_MEMORY - Requires the cache entry to reside in non-persistent + * storage (ie. typically in system RAM). + * STORE_ON_DISK - Requires the cache entry to reside in persistent + * storage (ie. typically on a system's hard disk). + * STORE_OFFLINE - Requires the cache entry to reside in persistent, + * reliable storage for offline use. + */ + const nsCacheStoragePolicy STORE_ANYWHERE = 0; + const nsCacheStoragePolicy STORE_IN_MEMORY = 1; + const nsCacheStoragePolicy STORE_ON_DISK = 2; + // value 3 was used by STORE_ON_DISK_AS_FILE which was removed + const nsCacheStoragePolicy STORE_OFFLINE = 4; + + /** + * All entries for a cache session are stored as streams of data or + * as objects. These constant my be used to specify the type of entries + * when calling nsICacheService::CreateSession(). + */ + const long NOT_STREAM_BASED = 0; + const long STREAM_BASED = 1; + + /** + * The synchronous OpenCacheEntry() may be blocking or non-blocking. If a cache entry is + * waiting to be validated by another cache descriptor (so no new cache descriptors for that + * key can be created, OpenCacheEntry() will return NS_ERROR_CACHE_WAIT_FOR_VALIDATION in + * non-blocking mode. In blocking mode, it will wait until the cache entry for the key has + * been validated or doomed. If the cache entry is validated, then a descriptor for that + * entry will be created and returned. If the cache entry was doomed, then a descriptor + * will be created for a new cache entry for the key. + */ + const long NON_BLOCKING = 0; + const long BLOCKING = 1; + + /** + * Constant meaning no expiration time. + */ + const unsigned long NO_EXPIRATION_TIME = 0xFFFFFFFF; +}; + diff --git a/netwerk/cache/nsICacheEntryDescriptor.idl b/netwerk/cache/nsICacheEntryDescriptor.idl new file mode 100644 index 0000000000..085ab388a8 --- /dev/null +++ b/netwerk/cache/nsICacheEntryDescriptor.idl @@ -0,0 +1,164 @@ +/* -*- Mode: IDL; 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 "nsICacheVisitor.idl" +#include "nsICache.idl" + +interface nsISimpleEnumerator; +interface nsICacheListener; +interface nsIInputStream; +interface nsIOutputStream; +interface nsIFile; +interface nsICacheMetaDataVisitor; + + +[scriptable, uuid(90b17d31-46aa-4fb1-a206-473c966cbc18)] +interface nsICacheEntryDescriptor : nsICacheEntryInfo +{ + /** + * Set the time at which the cache entry should be considered invalid (in + * seconds since the Epoch). + */ + void setExpirationTime(in uint32_t expirationTime); + + /** + * Set the cache entry data size. This will fail if the cache entry + * IS stream based. + */ + void setDataSize(in unsigned long size); + + /** + * Open blocking input stream to cache data. This will fail if the cache + * entry IS NOT stream based. Use the stream transport service to + * asynchronously read this stream on a background thread. The returned + * stream MAY implement nsISeekableStream. + * + * @param offset + * read starting from this offset into the cached data. an offset + * beyond the end of the stream has undefined consequences. + * + * @return blocking, unbuffered input stream. + */ + nsIInputStream openInputStream(in unsigned long offset); + + /** + * Open blocking output stream to cache data. This will fail if the cache + * entry IS NOT stream based. Use the stream transport service to + * asynchronously write to this stream on a background thread. The returned + * stream MAY implement nsISeekableStream. + * + * If opening an output stream to existing cached data, the data will be + * truncated to the specified offset. + * + * @param offset + * write starting from this offset into the cached data. an offset + * beyond the end of the stream has undefined consequences. + * + * @return blocking, unbuffered output stream. + */ + nsIOutputStream openOutputStream(in unsigned long offset); + + /** + * Get/set the cache data element. This will fail if the cache entry + * IS stream based. The cache entry holds a strong reference to this + * object. The object will be released when the cache entry is destroyed. + */ + attribute nsISupports cacheElement; + + /** + * Stores the Content-Length specified in the HTTP header for this + * entry. Checked before we write to the cache entry, to prevent ever + * taking up space in the cache for an entry that we know up front + * is going to have to be evicted anyway. See bug 588507. + */ + attribute int64_t predictedDataSize; + + /** + * Get the access granted to this descriptor. See nsICache.idl for the + * definitions of the access modes and a thorough description of their + * corresponding meanings. + */ + readonly attribute nsCacheAccessMode accessGranted; + + /** + * Get/set the storage policy of the cache entry. See nsICache.idl for + * the definitions of the storage policies. + */ + attribute nsCacheStoragePolicy storagePolicy; + + /** + * Get the disk file associated with the cache entry. + */ + readonly attribute nsIFile file; + + /** + * Get/set security info on the cache entry for this descriptor. This fails + * if the storage policy is not STORE_IN_MEMORY. + */ + attribute nsISupports securityInfo; + + /** + * Get the size of the cache entry data, as stored. This may differ + * from the entry's dataSize, if the entry is compressed. + */ + readonly attribute unsigned long storageDataSize; + + /** + * Doom the cache entry this descriptor references in order to slate it for + * removal. Once doomed a cache entry cannot be undoomed. + * + * A descriptor with WRITE access can doom the cache entry and choose to + * fail pending requests. This means that pending requests will not get + * a cache descriptor. This is meant as a tool for clients that wish to + * instruct pending requests to skip the cache. + */ + void doom(); + void doomAndFailPendingRequests(in nsresult status); + + /** + * Asynchronously doom an entry. Listener will be notified about the status + * of the operation. Null may be passed if caller doesn't care about the + * result. + */ + void asyncDoom(in nsICacheListener listener); + + /** + * A writer must validate this cache object before any readers are given + * a descriptor to the object. + */ + void markValid(); + + /** + * Explicitly close the descriptor (optional). + */ + + void close(); + + /** + * Methods for accessing meta data. Meta data is a table of key/value + * string pairs. The strings do not have to conform to any particular + * charset, but they must be null terminated. + */ + string getMetaDataElement(in string key); + void setMetaDataElement(in string key, in string value); + + /** + * Visitor will be called with key/value pair for each meta data element. + */ + void visitMetaData(in nsICacheMetaDataVisitor visitor); +}; + + + +[scriptable, uuid(22f9a49c-3cf8-4c23-8006-54efb11ac562)] +interface nsICacheMetaDataVisitor : nsISupports +{ + /** + * Called for each key/value pair in the meta data for a cache entry + */ + boolean visitMetaDataElement(in string key, + in string value); +}; diff --git a/netwerk/cache/nsICacheListener.idl b/netwerk/cache/nsICacheListener.idl new file mode 100644 index 0000000000..cfb2dd4708 --- /dev/null +++ b/netwerk/cache/nsICacheListener.idl @@ -0,0 +1,32 @@ +/* -*- Mode: IDL; 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 "nsISupports.idl" +#include "nsICache.idl" + + +interface nsICacheEntryDescriptor; + +[scriptable, uuid(8eadf2ed-8cac-4961-8025-6da6d5827e74)] +interface nsICacheListener : nsISupports +{ + /** + * Called when the requested access (or appropriate subset) is + * acquired. The status parameter equals NS_OK on success. + * See nsICacheService.idl for accessGranted values. + */ + void onCacheEntryAvailable(in nsICacheEntryDescriptor descriptor, + in nsCacheAccessMode accessGranted, + in nsresult status); + + /** + * Called when nsCacheSession::DoomEntry() is completed. The status + * parameter is NS_OK when the entry was doomed, or NS_ERROR_NOT_AVAILABLE + * when there is no such entry. + */ + void onCacheEntryDoomed(in nsresult status); +}; diff --git a/netwerk/cache/nsICacheService.idl b/netwerk/cache/nsICacheService.idl new file mode 100644 index 0000000000..c062a7910f --- /dev/null +++ b/netwerk/cache/nsICacheService.idl @@ -0,0 +1,98 @@ +/* -*- Mode: IDL; 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 "nsISupports.idl" +#include "nsICache.idl" + +interface nsISimpleEnumerator; +interface nsICacheListener; +interface nsICacheSession; +interface nsICacheVisitor; +interface nsIEventTarget; + +/** + * @deprecated + * + * IMPORTANT NOTE: THIS INTERFACE IS NO LONGER SUPPORTED AND PLANNED TO BE + * REMOVED SOON. WE STRONGLY ENCORAGE TO MIGRATE THE EXISTING CODE AND FOR + * THE NEW CODE USE ONLY THE NEW HTTP CACHE API IN netwerk/cache2/. + */ +[scriptable, uuid(14dbe1e9-f3bc-45af-92f4-2c574fcd4e39)] +interface nsICacheService : nsISupports +{ + /** + * @throws NS_ERROR_NOT_IMPLEMENTED when the cache v2 is prefered to use. + * + * Create a cache session + * + * A cache session represents a client's access into the cache. The cache + * session is not "owned" by the cache service. Hence, it is possible to + * create duplicate cache sessions. Entries created by a cache session + * are invisible to other cache sessions, unless the cache sessions are + * equivalent. + * + * @param clientID - Specifies the name of the client using the cache. + * @param storagePolicy - Limits the storage policy for all entries + * accessed via the returned session. As a result, devices excluded + * by the storage policy will not be searched when opening entries + * from the returned session. + * @param streamBased - Indicates whether or not the data being cached + * can be represented as a stream. The storagePolicy must be + * consistent with the value of this field. For example, a non-stream- + * based cache entry can only have a storage policy of STORE_IN_MEMORY. + * @return new cache session. + */ + nsICacheSession createSession(in string clientID, + in nsCacheStoragePolicy storagePolicy, + in boolean streamBased); + + /** + * @throws NS_ERROR_NOT_IMPLEMENTED when the cache v2 is prefered to use. + * + * Visit entries stored in the cache. Used to implement about:cache. + */ + void visitEntries(in nsICacheVisitor visitor); + + /** + * @throws NS_ERROR_NOT_IMPLEMENTED when the cache v2 is prefered to use. + * + * Evicts all entries in all devices implied by the storage policy. + * + * @note This function may evict some items but will throw if it fails to evict + * everything. + */ + void evictEntries(in nsCacheStoragePolicy storagePolicy); + + /** + * Event target which is used for I/O operations + */ + readonly attribute nsIEventTarget cacheIOTarget; +}; + +%{C++ +/** + * Observer service notification that is sent when + * nsICacheService::evictEntries() or nsICacheSession::evictEntries() + * is called. + */ +#define NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID "cacheservice:empty-cache" +%} + +[scriptable, builtinclass, uuid(d0fc8d38-db80-4928-bf1c-b0085ddfa9dc)] +interface nsICacheServiceInternal : nsICacheService +{ + /** + * This is an internal interface. It changes so frequently that it probably + * went away while you were reading this. + */ + + /** + * Milliseconds for which the service lock has been held. 0 if unlocked. + */ + readonly attribute double lockHeldTime; +}; + + diff --git a/netwerk/cache/nsICacheSession.idl b/netwerk/cache/nsICacheSession.idl new file mode 100644 index 0000000000..cb8871c28d --- /dev/null +++ b/netwerk/cache/nsICacheSession.idl @@ -0,0 +1,88 @@ +/* -*- Mode: IDL; 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 "nsISupports.idl" +#include "nsICache.idl" + +interface nsICacheEntryDescriptor; +interface nsICacheListener; +interface nsIFile; + +[scriptable, uuid(1dd7708c-de48-4ffe-b5aa-cd218c762887)] +interface nsICacheSession : nsISupports +{ + /** + * Expired entries will be doomed or evicted if this attribute is set to + * true. If false, expired entries will be returned (useful for offline- + * mode and clients, such as HTTP, that can update the valid lifetime of + * cached content). This attribute defaults to true. + */ + attribute boolean doomEntriesIfExpired; + + /** + * When set, entries created with this session will be placed to a cache + * based at this directory. Use when storing entries to a different + * profile than the active profile of the the current running application + * process. + */ + attribute nsIFile profileDirectory; + + /** + * A cache session can only give out one descriptor with WRITE access + * to a given cache entry at a time. Until the client calls MarkValid on + * its descriptor, other attempts to open the same cache entry will block. + */ + + /** + * Synchronous cache access. This method fails if it is called on the main + * thread. Use asyncOpenCacheEntry() instead. This returns a unique + * descriptor each time it is called, even if the same key is specified. + * When called by multiple threads for write access, only one writable + * descriptor will be granted. If 'blockingMode' is set to false, it will + * return NS_ERROR_CACHE_WAIT_FOR_VALIDATION rather than block when another + * descriptor has been given WRITE access but hasn't validated the entry yet. + */ + nsICacheEntryDescriptor openCacheEntry(in ACString key, + in nsCacheAccessMode accessRequested, + in boolean blockingMode); + + /** + * Asynchronous cache access. Does not block the calling thread. Instead, + * the listener will be notified when the descriptor is available. If + * 'noWait' is set to true, the listener will be notified immediately with + * status NS_ERROR_CACHE_WAIT_FOR_VALIDATION rather than queuing the request + * when another descriptor has been given WRITE access but hasn't validated + * the entry yet. + */ + void asyncOpenCacheEntry(in ACString key, + in nsCacheAccessMode accessRequested, + in nsICacheListener listener, + [optional] in boolean noWait); + + /** + * Evict all entries for this session's clientID according to its storagePolicy. + */ + void evictEntries(); + + /** + * Return whether any of the cache devices implied by the session storage policy + * are currently enabled for instantiation if they don't already exist. + */ + boolean isStorageEnabled(); + + /** + * Asynchronously doom an entry specified by the key. Listener will be + * notified about the status of the operation. Null may be passed if caller + * doesn't care about the result. + */ + void doomEntry(in ACString key, in nsICacheListener listener); + + /** + * Private entries will be doomed when the last private browsing session + * finishes. + */ + attribute boolean isPrivate; +}; diff --git a/netwerk/cache/nsICacheVisitor.idl b/netwerk/cache/nsICacheVisitor.idl new file mode 100644 index 0000000000..56b503d430 --- /dev/null +++ b/netwerk/cache/nsICacheVisitor.idl @@ -0,0 +1,123 @@ +/* -*- Mode: IDL; 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 "nsISupports.idl" + +/* XXX we should define device and entry info as well (stats, etc) */ + +interface nsICacheDeviceInfo; +interface nsICacheEntryInfo; + + +[scriptable, uuid(f8c08c4b-d778-49d1-a59b-866fdc500d95)] +interface nsICacheVisitor : nsISupports +{ + /** + * Called to provide information about a cache device. + * + * @param deviceID - specifies the device being visited. + * @param deviceInfo - specifies information about this device. + * + * @return true to start visiting all entries for this device. + * @return false to advance to the next device. + */ + boolean visitDevice(in string deviceID, + in nsICacheDeviceInfo deviceInfo); + + /** + * Called to provide information about a cache entry. + * + * @param deviceID - specifies the device being visited. + * @param entryInfo - specifies information about this entry. + * + * @return true to visit the next entry on the current device, or if the + * end of the device has been reached, advance to the next device. + * @return false to advance to the next device. + */ + boolean visitEntry(in string deviceID, + in nsICacheEntryInfo entryInfo); +}; + + +[scriptable, uuid(31d1c294-1dd2-11b2-be3a-c79230dca297)] +interface nsICacheDeviceInfo : nsISupports +{ + /** + * Get a human readable description of the cache device. + */ + readonly attribute ACString description; + + /** + * Get a usage report, statistics, miscellaneous data about + * the cache device. + */ + readonly attribute ACString usageReport; + + /** + * Get the number of stored cache entries. + */ + readonly attribute unsigned long entryCount; + + /** + * Get the total size of the stored cache entries. + */ + readonly attribute unsigned long totalSize; + + /** + * Get the upper limit of the size of the data the cache can store. + */ + readonly attribute unsigned long maximumSize; +}; + + +[scriptable, uuid(fab51c92-95c3-4468-b317-7de4d7588254)] +interface nsICacheEntryInfo : nsISupports +{ + /** + * Get the client id associated with this cache entry. + */ + readonly attribute ACString clientID; + + /** + * Get the id for the device that stores this cache entry. + */ + readonly attribute ACString deviceID; + + /** + * Get the key identifying the cache entry. + */ + readonly attribute ACString key; + + /** + * Get the number of times the cache entry has been opened. + */ + readonly attribute long fetchCount; + + /** + * Get the last time the cache entry was opened (in seconds since the Epoch). + */ + readonly attribute uint32_t lastFetched; + + /** + * Get the last time the cache entry was modified (in seconds since the Epoch). + */ + readonly attribute uint32_t lastModified; + + /** + * Get the expiration time of the cache entry (in seconds since the Epoch). + */ + readonly attribute uint32_t expirationTime; + + /** + * Get the cache entry data size. + */ + readonly attribute unsigned long dataSize; + + /** + * Find out whether or not the cache entry is stream based. + */ + boolean isStreamBased(); +}; |