Files
palemoon27/dom/cache/CacheStorage.cpp
T
roytam1 13b1aeb09f import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1137653: Correct the shape of the data object sent over if there are are crashes or the packet is malformed; r=jgriffin (d05804fe4)
- Bug 1121577 - Unset pref at delete_session, r=dburns (d2cefee52)
- Bug 1144907 - Restore previous context after calling marionette's gather_debug. r=davehunt (2d35526d2)
- Bug 1135846 - Expose marionette's actions code to chrome scope where applicable. r=dburns (2c91389b5)
- Bug 1118313 - newSession looks for non-conforming session_id property on Command. r=dburns (d72f256ec)
- Bug 1107706: Part 1: Change context from strings to enum (d4936c869)
- Bug 1107706: Part 2: Add error module and WebDriver error objects (95a58e4fa)
- Bug 1107706: Part 3: Add a command processor to Marionette (4ed444206)
- Bug 1107706: Part 4: Add dispatching mechanism to encapsulate connection (5a0cf4bfa)
- Bug 1107706: Part 5: Refactor Marionette chrome/content communication (a110867e3)
- Bug 1107706: Part 6: Make SpecialPowersError a prototypal Error (bebfc4e13)
- Bug 1107706: Part 7: Add timeout test for async scripts (795921b56)
- Bug 1107706: Part 8: Adapt emulator callbacks (4f0ec4ea3)
- Bug 1165395 Test Cache API after QuotaManager reset. r=janv (27ffd1273)
- Bug 1154325 P1 Add convenience routines to bind and get Blobs as strings. r=asuth (df1f9930a)
- Bug 1154325 P2 Use Blobs for CacheStorage keys to avoid encoding issues. r=ehsan (625588969)
- Bug 1179063 - Cleanup: Rename scopal back to scopeStmt. (r=me) (eaa5d8e3a)
- pointer style (39588e254)
- pointer style (7be6abefc)
- Bug 1162342 Enable sqlite WAL transactions in Cache API. r=ehsan (60a767033)
- Bug 1130452 - Remove support for the prefixMatch option in the service worker cache code; r=bkelly,baku (48d4d62f2)
- Bug 1166577 Use named sqlite params in Cache API code. r=ehsan (a0cbc5674)
- Bug 1166038 De-duplicate security info stored in the Cache API. r=ehsan (cdb8e8396)
- Bug 1166911 Modify Cache API sqlite code to use IS NULL literal when comparing an empty key. r=ehsan (a893706bf)
- Bug 1164620 - Part 1: Remove instances of #ifdef PR_LOGGING in various places. r=froydnj (69f3becd3)
- Bug 1161684 - Allow JAR channels to be intercepted by service workers. r=jdm (292f83299)
- Bug 1146169 - Check mChannel for null-ness in nsIInterceptedChannel::SetSecurityInfo(); r=jdm (9ed238664)
- Bug 1168208 - Refactor the existing logic for syncing the security info between Response and channel objects into a new helper class; r=nsm,jdm,bkelly (ea8852934)
- pointer style (b6ada460f)
- Bug 1163423 - Introduce JS_HasOwnProperty. r=bhackett (c189e58f0)
- pointer style (4693171b0)
- Bug 1163423 - Use JS_HasOwnProperty in WrapperAnswer::RecvHasOwn. r=billm (5029c2787)
- Bug 1168152 P1 Use a smaller sqlite page size and a growth increment in Cache. r=ehsan (9ad7f999f)
- Bug 1120501 P1 Make it easier to use Promise::All() from C++ code. r=nsm (95d1d5e2f)
- Bug 1120501 P2 Move Cache Add/AddAll logic to child process. r=ehsan,smaug (c71f9c49b)
- Bug 1168152 P2 Use a wrapper mozIStorageConnection for shared Cache connections. r=ehsan (f930635ac)
- Bug 1168152 P3 Perform incremental vacuum at tail end of Cache db connections. r=ehsan (df76df80c)
- Bug 1168152 P4 Add a test to verify Cache incremental vacuum works. r=ehsan (320d50436)
- Bug 1168152 P5 Follow-up to use 32kb growth size as intended in previous patches. r=me (92e2d3f27)
- Bug 1144236 - Add tests for the ignoreMethod match mode in DOM cache; r=bkelly (795a31d3c)
- Bug 1150001 - Cache API should not return Response body when matching Request with HEAD method. r=bkelly (690927f85)
2021-02-22 07:38:03 +08:00

449 lines
12 KiB
C++

/* -*- 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 "mozilla/dom/cache/CacheStorage.h"
#include "mozilla/unused.h"
#include "mozilla/dom/CacheStorageBinding.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/Response.h"
#include "mozilla/dom/cache/AutoUtils.h"
#include "mozilla/dom/cache/Cache.h"
#include "mozilla/dom/cache/CacheChild.h"
#include "mozilla/dom/cache/CacheStorageChild.h"
#include "mozilla/dom/cache/Feature.h"
#include "mozilla/dom/cache/PCacheChild.h"
#include "mozilla/dom/cache/ReadStream.h"
#include "mozilla/dom/cache/TypeUtils.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/BackgroundUtils.h"
#include "mozilla/ipc/PBackgroundChild.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "nsIGlobalObject.h"
#include "nsIScriptSecurityManager.h"
#include "WorkerPrivate.h"
namespace mozilla {
namespace dom {
namespace cache {
using mozilla::unused;
using mozilla::ErrorResult;
using mozilla::dom::workers::WorkerPrivate;
using mozilla::ipc::BackgroundChild;
using mozilla::ipc::PBackgroundChild;
using mozilla::ipc::IProtocol;
using mozilla::ipc::PrincipalInfo;
using mozilla::ipc::PrincipalToPrincipalInfo;
NS_IMPL_CYCLE_COLLECTING_ADDREF(mozilla::dom::cache::CacheStorage);
NS_IMPL_CYCLE_COLLECTING_RELEASE(mozilla::dom::cache::CacheStorage);
NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(mozilla::dom::cache::CacheStorage,
mGlobal);
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(CacheStorage)
NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_ENTRY(nsIIPCBackgroundChildCreateCallback)
NS_INTERFACE_MAP_END
// We cannot reference IPC types in a webidl binding implementation header. So
// define this in the .cpp and use heap storage in the mPendingRequests list.
struct CacheStorage::Entry final
{
nsRefPtr<Promise> mPromise;
CacheOpArgs mArgs;
// We cannot add the requests until after the actor is present. So store
// the request data separately for now.
nsRefPtr<InternalRequest> mRequest;
};
// static
already_AddRefed<CacheStorage>
CacheStorage::CreateOnMainThread(Namespace aNamespace, nsIGlobalObject* aGlobal,
nsIPrincipal* aPrincipal, ErrorResult& aRv)
{
MOZ_ASSERT(aGlobal);
MOZ_ASSERT(aPrincipal);
MOZ_ASSERT(NS_IsMainThread());
bool nullPrincipal;
nsresult rv = aPrincipal->GetIsNullPrincipal(&nullPrincipal);
if (NS_WARN_IF(NS_FAILED(rv))) {
aRv.Throw(rv);
return nullptr;
}
if (nullPrincipal) {
NS_WARNING("CacheStorage not supported on null principal.");
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
// An unknown appId means that this principal was created for the codebase
// without all the security information from the end document or worker.
// We require exact knowledge of this information before allowing the
// caller to touch the disk using the Cache API.
bool unknownAppId = false;
aPrincipal->GetUnknownAppId(&unknownAppId);
if (unknownAppId) {
NS_WARNING("CacheStorage not supported on principal with unknown appId.");
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
PrincipalInfo principalInfo;
rv = PrincipalToPrincipalInfo(aPrincipal, &principalInfo);
if (NS_WARN_IF(NS_FAILED(rv))) {
aRv.Throw(rv);
return nullptr;
}
nsRefPtr<CacheStorage> ref = new CacheStorage(aNamespace, aGlobal,
principalInfo, nullptr);
return ref.forget();
}
// static
already_AddRefed<CacheStorage>
CacheStorage::CreateOnWorker(Namespace aNamespace, nsIGlobalObject* aGlobal,
WorkerPrivate* aWorkerPrivate, ErrorResult& aRv)
{
MOZ_ASSERT(aGlobal);
MOZ_ASSERT(aWorkerPrivate);
aWorkerPrivate->AssertIsOnWorkerThread();
nsRefPtr<Feature> feature = Feature::Create(aWorkerPrivate);
if (!feature) {
NS_WARNING("Worker thread is shutting down.");
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
const PrincipalInfo& principalInfo = aWorkerPrivate->GetPrincipalInfo();
if (principalInfo.type() == PrincipalInfo::TNullPrincipalInfo) {
NS_WARNING("CacheStorage not supported on null principal.");
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
if (principalInfo.type() == PrincipalInfo::TContentPrincipalInfo &&
principalInfo.get_ContentPrincipalInfo().appId() ==
nsIScriptSecurityManager::UNKNOWN_APP_ID) {
NS_WARNING("CacheStorage not supported on principal with unknown appId.");
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
nsRefPtr<CacheStorage> ref = new CacheStorage(aNamespace, aGlobal,
principalInfo, feature);
return ref.forget();
}
CacheStorage::CacheStorage(Namespace aNamespace, nsIGlobalObject* aGlobal,
const PrincipalInfo& aPrincipalInfo, Feature* aFeature)
: mNamespace(aNamespace)
, mGlobal(aGlobal)
, mPrincipalInfo(MakeUnique<PrincipalInfo>(aPrincipalInfo))
, mFeature(aFeature)
, mActor(nullptr)
, mFailedActor(false)
{
MOZ_ASSERT(mGlobal);
// If the PBackground actor is already initialized then we can
// immediately use it
PBackgroundChild* actor = BackgroundChild::GetForCurrentThread();
if (actor) {
ActorCreated(actor);
return;
}
// Otherwise we must begin the PBackground initialization process and
// wait for the async ActorCreated() callback.
MOZ_ASSERT(NS_IsMainThread());
bool ok = BackgroundChild::GetOrCreateForCurrentThread(this);
if (!ok) {
ActorFailed();
}
}
already_AddRefed<Promise>
CacheStorage::Match(const RequestOrUSVString& aRequest,
const CacheQueryOptions& aOptions, ErrorResult& aRv)
{
NS_ASSERT_OWNINGTHREAD(CacheStorage);
if (mFailedActor) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsRefPtr<InternalRequest> request = ToInternalRequest(aRequest, IgnoreBody,
aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
nsRefPtr<Promise> promise = Promise::Create(mGlobal, aRv);
if (!promise) {
return nullptr;
}
CacheQueryParams params;
ToCacheQueryParams(params, aOptions);
nsAutoPtr<Entry> entry(new Entry());
entry->mPromise = promise;
entry->mArgs = StorageMatchArgs(CacheRequest(), params);
entry->mRequest = request;
mPendingRequests.AppendElement(entry.forget());
MaybeRunPendingRequests();
return promise.forget();
}
already_AddRefed<Promise>
CacheStorage::Has(const nsAString& aKey, ErrorResult& aRv)
{
NS_ASSERT_OWNINGTHREAD(CacheStorage);
if (mFailedActor) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsRefPtr<Promise> promise = Promise::Create(mGlobal, aRv);
if (!promise) {
return nullptr;
}
nsAutoPtr<Entry> entry(new Entry());
entry->mPromise = promise;
entry->mArgs = StorageHasArgs(nsString(aKey));
mPendingRequests.AppendElement(entry.forget());
MaybeRunPendingRequests();
return promise.forget();
}
already_AddRefed<Promise>
CacheStorage::Open(const nsAString& aKey, ErrorResult& aRv)
{
NS_ASSERT_OWNINGTHREAD(CacheStorage);
if (mFailedActor) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsRefPtr<Promise> promise = Promise::Create(mGlobal, aRv);
if (!promise) {
return nullptr;
}
nsAutoPtr<Entry> entry(new Entry());
entry->mPromise = promise;
entry->mArgs = StorageOpenArgs(nsString(aKey));
mPendingRequests.AppendElement(entry.forget());
MaybeRunPendingRequests();
return promise.forget();
}
already_AddRefed<Promise>
CacheStorage::Delete(const nsAString& aKey, ErrorResult& aRv)
{
NS_ASSERT_OWNINGTHREAD(CacheStorage);
if (mFailedActor) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsRefPtr<Promise> promise = Promise::Create(mGlobal, aRv);
if (!promise) {
return nullptr;
}
nsAutoPtr<Entry> entry(new Entry());
entry->mPromise = promise;
entry->mArgs = StorageDeleteArgs(nsString(aKey));
mPendingRequests.AppendElement(entry.forget());
MaybeRunPendingRequests();
return promise.forget();
}
already_AddRefed<Promise>
CacheStorage::Keys(ErrorResult& aRv)
{
NS_ASSERT_OWNINGTHREAD(CacheStorage);
if (mFailedActor) {
aRv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
nsRefPtr<Promise> promise = Promise::Create(mGlobal, aRv);
if (!promise) {
return nullptr;
}
nsAutoPtr<Entry> entry(new Entry());
entry->mPromise = promise;
entry->mArgs = StorageKeysArgs();
mPendingRequests.AppendElement(entry.forget());
MaybeRunPendingRequests();
return promise.forget();
}
// static
bool
CacheStorage::PrefEnabled(JSContext* aCx, JSObject* aObj)
{
return Cache::PrefEnabled(aCx, aObj);
}
nsISupports*
CacheStorage::GetParentObject() const
{
return mGlobal;
}
JSObject*
CacheStorage::WrapObject(JSContext* aContext, JS::Handle<JSObject*> aGivenProto)
{
return mozilla::dom::CacheStorageBinding::Wrap(aContext, this, aGivenProto);
}
void
CacheStorage::ActorCreated(PBackgroundChild* aActor)
{
NS_ASSERT_OWNINGTHREAD(CacheStorage);
MOZ_ASSERT(aActor);
if (NS_WARN_IF(mFeature && mFeature->Notified())) {
ActorFailed();
return;
}
// Feature ownership is passed to the CacheStorageChild actor and any actors
// it may create. The Feature will keep the worker thread alive until the
// actors can gracefully shutdown.
CacheStorageChild* newActor = new CacheStorageChild(this, mFeature);
PCacheStorageChild* constructedActor =
aActor->SendPCacheStorageConstructor(newActor, mNamespace, *mPrincipalInfo);
if (NS_WARN_IF(!constructedActor)) {
ActorFailed();
return;
}
mFeature = nullptr;
MOZ_ASSERT(constructedActor == newActor);
mActor = newActor;
MaybeRunPendingRequests();
MOZ_ASSERT(mPendingRequests.IsEmpty());
}
void
CacheStorage::ActorFailed()
{
NS_ASSERT_OWNINGTHREAD(CacheStorage);
MOZ_ASSERT(!mFailedActor);
mFailedActor = true;
mFeature = nullptr;
for (uint32_t i = 0; i < mPendingRequests.Length(); ++i) {
nsAutoPtr<Entry> entry(mPendingRequests[i].forget());
entry->mPromise->MaybeReject(NS_ERROR_UNEXPECTED);
}
mPendingRequests.Clear();
}
void
CacheStorage::DestroyInternal(CacheStorageChild* aActor)
{
NS_ASSERT_OWNINGTHREAD(CacheStorage);
MOZ_ASSERT(mActor);
MOZ_ASSERT(mActor == aActor);
mActor->ClearListener();
mActor = nullptr;
// Note that we will never get an actor again in case another request is
// made before this object is destructed.
ActorFailed();
}
nsIGlobalObject*
CacheStorage::GetGlobalObject() const
{
return mGlobal;
}
#ifdef DEBUG
void
CacheStorage::AssertOwningThread() const
{
NS_ASSERT_OWNINGTHREAD(CacheStorage);
}
#endif
CachePushStreamChild*
CacheStorage::CreatePushStream(nsIAsyncInputStream* aStream)
{
// This is true because CacheStorage always uses IgnoreBody for requests.
MOZ_CRASH("CacheStorage should never create a push stream.");
}
CacheStorage::~CacheStorage()
{
NS_ASSERT_OWNINGTHREAD(CacheStorage);
if (mActor) {
mActor->StartDestroy();
// DestroyInternal() is called synchronously by StartDestroy(). So we
// should have already cleared the mActor.
MOZ_ASSERT(!mActor);
}
}
void
CacheStorage::MaybeRunPendingRequests()
{
if (!mActor) {
return;
}
for (uint32_t i = 0; i < mPendingRequests.Length(); ++i) {
ErrorResult rv;
nsAutoPtr<Entry> entry(mPendingRequests[i].forget());
AutoChildOpArgs args(this, entry->mArgs);
if (entry->mRequest) {
args.Add(entry->mRequest, IgnoreBody, IgnoreInvalidScheme, rv);
}
if (rv.Failed()) {
entry->mPromise->MaybeReject(rv);
continue;
}
mActor->ExecuteOp(mGlobal, entry->mPromise, args.SendAsOpArgs());
}
mPendingRequests.Clear();
}
} // namespace cache
} // namespace dom
} // namespace mozilla