Bug 1831122 [wpt PR 39823] - Update wpt metadata, a=testonly
[gecko.git] / dom / indexedDB / IDBFactory.cpp
blob9bc3864c305326e8a3d9aece981ca6fc8e3b9e8a
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "IDBFactory.h"
9 #include "BackgroundChildImpl.h"
10 #include "IDBRequest.h"
11 #include "IndexedDatabaseManager.h"
12 #include "mozilla/BasePrincipal.h"
13 #include "mozilla/ErrorResult.h"
14 #include "mozilla/Preferences.h"
15 #include "mozilla/dom/BindingDeclarations.h"
16 #include "mozilla/dom/Document.h"
17 #include "mozilla/dom/IDBFactoryBinding.h"
18 #include "mozilla/dom/quota/PersistenceType.h"
19 #include "mozilla/dom/quota/QuotaManager.h"
20 #include "mozilla/dom/BrowserChild.h"
21 #include "mozilla/dom/WorkerPrivate.h"
22 #include "mozilla/ipc/BackgroundChild.h"
23 #include "mozilla/ipc/BackgroundUtils.h"
24 #include "mozilla/ipc/PBackground.h"
25 #include "mozilla/ipc/PBackgroundChild.h"
26 #include "mozilla/StaticPrefs_dom.h"
27 #include "mozilla/StorageAccess.h"
28 #include "mozilla/Telemetry.h"
29 #include "nsAboutProtocolUtils.h"
30 #include "nsContentUtils.h"
31 #include "nsGlobalWindow.h"
32 #include "nsIAboutModule.h"
33 #include "nsILoadContext.h"
34 #include "nsIURI.h"
35 #include "nsIUUIDGenerator.h"
36 #include "nsIWebNavigation.h"
37 #include "nsNetUtil.h"
38 #include "nsSandboxFlags.h"
39 #include "nsServiceManagerUtils.h"
40 #include "ProfilerHelpers.h"
41 #include "ReportInternalError.h"
42 #include "ThreadLocal.h"
44 // Include this last to avoid path problems on Windows.
45 #include "ActorsChild.h"
47 namespace mozilla::dom {
49 using namespace mozilla::dom::indexedDB;
50 using namespace mozilla::dom::quota;
51 using namespace mozilla::ipc;
53 namespace {
55 Telemetry::LABELS_IDB_CUSTOM_OPEN_WITH_OPTIONS_COUNT IdentifyPrincipalType(
56 const mozilla::ipc::PrincipalInfo& aPrincipalInfo) {
57 switch (aPrincipalInfo.type()) {
58 case PrincipalInfo::TSystemPrincipalInfo:
59 return Telemetry::LABELS_IDB_CUSTOM_OPEN_WITH_OPTIONS_COUNT::system;
60 case PrincipalInfo::TContentPrincipalInfo: {
61 const ContentPrincipalInfo& info =
62 aPrincipalInfo.get_ContentPrincipalInfo();
64 nsCOMPtr<nsIURI> uri;
66 if (NS_WARN_IF(NS_FAILED(NS_NewURI(getter_AddRefs(uri), info.spec())))) {
67 // This could be discriminated as an extra error value, but this is
68 // extremely unlikely to fail, so we just misuse ContentOther
69 return Telemetry::LABELS_IDB_CUSTOM_OPEN_WITH_OPTIONS_COUNT::
70 content_other;
73 // TODO Are there constants defined for the schemes somewhere?
74 if (uri->SchemeIs("file")) {
75 return Telemetry::LABELS_IDB_CUSTOM_OPEN_WITH_OPTIONS_COUNT::
76 content_file;
78 if (uri->SchemeIs("http") || uri->SchemeIs("https")) {
79 return Telemetry::LABELS_IDB_CUSTOM_OPEN_WITH_OPTIONS_COUNT::
80 content_http_https;
82 if (uri->SchemeIs("moz-extension")) {
83 return Telemetry::LABELS_IDB_CUSTOM_OPEN_WITH_OPTIONS_COUNT::
84 content_moz_ext;
86 if (uri->SchemeIs("about")) {
87 return Telemetry::LABELS_IDB_CUSTOM_OPEN_WITH_OPTIONS_COUNT::
88 content_about;
90 return Telemetry::LABELS_IDB_CUSTOM_OPEN_WITH_OPTIONS_COUNT::
91 content_other;
93 case PrincipalInfo::TExpandedPrincipalInfo:
94 return Telemetry::LABELS_IDB_CUSTOM_OPEN_WITH_OPTIONS_COUNT::expanded;
95 default:
96 return Telemetry::LABELS_IDB_CUSTOM_OPEN_WITH_OPTIONS_COUNT::other;
100 } // namespace
102 struct IDBFactory::PendingRequestInfo {
103 RefPtr<IDBOpenDBRequest> mRequest;
104 FactoryRequestParams mParams;
106 PendingRequestInfo(IDBOpenDBRequest* aRequest,
107 const FactoryRequestParams& aParams)
108 : mRequest(aRequest), mParams(aParams) {
109 MOZ_ASSERT(aRequest);
110 MOZ_ASSERT(aParams.type() != FactoryRequestParams::T__None);
114 IDBFactory::IDBFactory(const IDBFactoryGuard&)
115 : mBackgroundActor(nullptr),
116 mInnerWindowID(0),
117 mActiveTransactionCount(0),
118 mActiveDatabaseCount(0),
119 mBackgroundActorFailed(false),
120 mPrivateBrowsingMode(false) {
121 AssertIsOnOwningThread();
124 IDBFactory::~IDBFactory() {
125 MOZ_ASSERT_IF(mBackgroundActorFailed, !mBackgroundActor);
127 if (mBackgroundActor) {
128 mBackgroundActor->SendDeleteMeInternal();
129 MOZ_ASSERT(!mBackgroundActor, "SendDeleteMeInternal should have cleared!");
133 // static
134 Result<RefPtr<IDBFactory>, nsresult> IDBFactory::CreateForWindow(
135 nsPIDOMWindowInner* aWindow) {
136 MOZ_ASSERT(NS_IsMainThread());
137 MOZ_ASSERT(aWindow);
139 nsCOMPtr<nsIPrincipal> principal;
140 nsresult rv = AllowedForWindowInternal(aWindow, &principal);
142 if (rv == NS_ERROR_DOM_NOT_SUPPORTED_ERR) {
143 NS_WARNING("IndexedDB is not permitted in a third-party window.");
144 return RefPtr<IDBFactory>{};
147 if (NS_WARN_IF(NS_FAILED(rv))) {
148 if (rv == NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR) {
149 IDB_REPORT_INTERNAL_ERR();
151 return Err(rv);
154 MOZ_ASSERT(principal);
156 auto principalInfo = MakeUnique<PrincipalInfo>();
157 rv = PrincipalToPrincipalInfo(principal, principalInfo.get());
158 if (NS_WARN_IF(NS_FAILED(rv))) {
159 IDB_REPORT_INTERNAL_ERR();
160 return Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
163 MOZ_ASSERT(principalInfo->type() == PrincipalInfo::TContentPrincipalInfo ||
164 principalInfo->type() == PrincipalInfo::TSystemPrincipalInfo);
166 if (NS_WARN_IF(!QuotaManager::IsPrincipalInfoValid(*principalInfo))) {
167 IDB_REPORT_INTERNAL_ERR();
168 return Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
171 nsCOMPtr<nsIWebNavigation> webNav = do_GetInterface(aWindow);
172 nsCOMPtr<nsILoadContext> loadContext = do_QueryInterface(webNav);
174 auto factory = MakeRefPtr<IDBFactory>(IDBFactoryGuard{});
175 factory->mPrincipalInfo = std::move(principalInfo);
177 factory->mGlobal = do_QueryInterface(aWindow);
178 MOZ_ASSERT(factory->mGlobal);
180 factory->mBrowserChild = BrowserChild::GetFrom(aWindow);
181 factory->mEventTarget =
182 nsGlobalWindowInner::Cast(aWindow)->EventTargetFor(TaskCategory::Other);
183 factory->mInnerWindowID = aWindow->WindowID();
184 factory->mPrivateBrowsingMode =
185 loadContext && loadContext->UsePrivateBrowsing();
187 return factory;
190 // static
191 Result<RefPtr<IDBFactory>, nsresult> IDBFactory::CreateForMainThreadJS(
192 nsIGlobalObject* aGlobal) {
193 MOZ_ASSERT(NS_IsMainThread());
194 MOZ_ASSERT(aGlobal);
196 nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(aGlobal);
197 if (NS_WARN_IF(!sop)) {
198 return Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
201 auto principalInfo = MakeUnique<PrincipalInfo>();
202 nsIPrincipal* principal = sop->GetEffectiveStoragePrincipal();
203 MOZ_ASSERT(principal);
204 bool isSystem;
205 if (!AllowedForPrincipal(principal, &isSystem)) {
206 return Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
209 nsresult rv = PrincipalToPrincipalInfo(principal, principalInfo.get());
210 if (NS_WARN_IF(NS_FAILED(rv))) {
211 return Err(rv);
214 if (NS_WARN_IF(!QuotaManager::IsPrincipalInfoValid(*principalInfo))) {
215 return Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
218 return CreateForMainThreadJSInternal(aGlobal, std::move(principalInfo));
221 // static
222 Result<RefPtr<IDBFactory>, nsresult> IDBFactory::CreateForWorker(
223 nsIGlobalObject* aGlobal, const PrincipalInfo& aPrincipalInfo,
224 uint64_t aInnerWindowID) {
225 MOZ_ASSERT(!NS_IsMainThread());
226 MOZ_ASSERT(aGlobal);
227 MOZ_ASSERT(aPrincipalInfo.type() != PrincipalInfo::T__None);
229 return CreateInternal(aGlobal, MakeUnique<PrincipalInfo>(aPrincipalInfo),
230 aInnerWindowID);
233 // static
234 Result<RefPtr<IDBFactory>, nsresult> IDBFactory::CreateForMainThreadJSInternal(
235 nsIGlobalObject* aGlobal, UniquePtr<PrincipalInfo> aPrincipalInfo) {
236 MOZ_ASSERT(NS_IsMainThread());
237 MOZ_ASSERT(aGlobal);
238 MOZ_ASSERT(aPrincipalInfo);
240 IndexedDatabaseManager* mgr = IndexedDatabaseManager::GetOrCreate();
241 if (NS_WARN_IF(!mgr)) {
242 IDB_REPORT_INTERNAL_ERR();
243 return Err(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
246 return CreateInternal(aGlobal, std::move(aPrincipalInfo),
247 /* aInnerWindowID */ 0);
250 // static
251 Result<RefPtr<IDBFactory>, nsresult> IDBFactory::CreateInternal(
252 nsIGlobalObject* aGlobal, UniquePtr<PrincipalInfo> aPrincipalInfo,
253 uint64_t aInnerWindowID) {
254 MOZ_ASSERT(aGlobal);
255 MOZ_ASSERT(aPrincipalInfo);
256 MOZ_ASSERT(aPrincipalInfo->type() != PrincipalInfo::T__None);
258 if (aPrincipalInfo->type() != PrincipalInfo::TContentPrincipalInfo &&
259 aPrincipalInfo->type() != PrincipalInfo::TSystemPrincipalInfo) {
260 NS_WARNING("IndexedDB not allowed for this principal!");
261 return RefPtr<IDBFactory>{};
264 auto factory = MakeRefPtr<IDBFactory>(IDBFactoryGuard{});
265 factory->mPrincipalInfo = std::move(aPrincipalInfo);
266 factory->mGlobal = aGlobal;
267 factory->mEventTarget = GetCurrentSerialEventTarget();
268 factory->mInnerWindowID = aInnerWindowID;
270 return factory;
273 // static
274 bool IDBFactory::AllowedForWindow(nsPIDOMWindowInner* aWindow) {
275 MOZ_ASSERT(NS_IsMainThread());
276 MOZ_ASSERT(aWindow);
278 return !NS_WARN_IF(NS_FAILED(AllowedForWindowInternal(aWindow, nullptr)));
281 // static
282 nsresult IDBFactory::AllowedForWindowInternal(
283 nsPIDOMWindowInner* aWindow, nsCOMPtr<nsIPrincipal>* aPrincipal) {
284 MOZ_ASSERT(NS_IsMainThread());
285 MOZ_ASSERT(aWindow);
287 if (NS_WARN_IF(!IndexedDatabaseManager::GetOrCreate())) {
288 return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
291 StorageAccess access = StorageAllowedForWindow(aWindow);
293 // the factory callsite records whether the browser is in private browsing.
294 // and thus we don't have to respect that setting here. IndexedDB has no
295 // concept of session-local storage, and thus ignores it.
296 if (access == StorageAccess::eDeny) {
297 return NS_ERROR_DOM_SECURITY_ERR;
300 if (ShouldPartitionStorage(access) &&
301 !StoragePartitioningEnabled(
302 access, aWindow->GetExtantDoc()->CookieJarSettings())) {
303 return NS_ERROR_DOM_SECURITY_ERR;
306 nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(aWindow);
307 MOZ_ASSERT(sop);
309 nsCOMPtr<nsIPrincipal> principal = sop->GetEffectiveStoragePrincipal();
310 if (NS_WARN_IF(!principal)) {
311 return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
314 if (principal->IsSystemPrincipal()) {
315 *aPrincipal = std::move(principal);
316 return NS_OK;
319 // About URIs shouldn't be able to access IndexedDB unless they have the
320 // nsIAboutModule::ENABLE_INDEXED_DB flag set on them.
322 if (principal->SchemeIs("about")) {
323 uint32_t flags;
324 if (NS_SUCCEEDED(principal->GetAboutModuleFlags(&flags))) {
325 if (!(flags & nsIAboutModule::ENABLE_INDEXED_DB)) {
326 return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
328 } else {
329 return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
333 if (aPrincipal) {
334 *aPrincipal = std::move(principal);
336 return NS_OK;
339 // static
340 bool IDBFactory::AllowedForPrincipal(nsIPrincipal* aPrincipal,
341 bool* aIsSystemPrincipal) {
342 MOZ_ASSERT(NS_IsMainThread());
343 MOZ_ASSERT(aPrincipal);
345 if (NS_WARN_IF(!IndexedDatabaseManager::GetOrCreate())) {
346 return false;
349 if (aPrincipal->IsSystemPrincipal()) {
350 if (aIsSystemPrincipal) {
351 *aIsSystemPrincipal = true;
353 return true;
356 if (aIsSystemPrincipal) {
357 *aIsSystemPrincipal = false;
360 return !aPrincipal->GetIsNullPrincipal();
363 void IDBFactory::UpdateActiveTransactionCount(int32_t aDelta) {
364 AssertIsOnOwningThread();
365 MOZ_DIAGNOSTIC_ASSERT(aDelta > 0 || (mActiveTransactionCount + aDelta) <
366 mActiveTransactionCount);
367 mActiveTransactionCount += aDelta;
370 void IDBFactory::UpdateActiveDatabaseCount(int32_t aDelta) {
371 AssertIsOnOwningThread();
372 MOZ_DIAGNOSTIC_ASSERT(aDelta > 0 ||
373 (mActiveDatabaseCount + aDelta) < mActiveDatabaseCount);
374 mActiveDatabaseCount += aDelta;
376 nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(mGlobal);
377 if (window) {
378 window->UpdateActiveIndexedDBDatabaseCount(aDelta);
382 bool IDBFactory::IsChrome() const {
383 AssertIsOnOwningThread();
384 MOZ_ASSERT(mPrincipalInfo);
386 return mPrincipalInfo->type() == PrincipalInfo::TSystemPrincipalInfo;
389 RefPtr<IDBOpenDBRequest> IDBFactory::Open(JSContext* aCx,
390 const nsAString& aName,
391 uint64_t aVersion,
392 CallerType aCallerType,
393 ErrorResult& aRv) {
394 return OpenInternal(aCx,
395 /* aPrincipal */ nullptr, aName,
396 Optional<uint64_t>(aVersion),
397 /* aDeleting */ false, aCallerType, aRv);
400 RefPtr<IDBOpenDBRequest> IDBFactory::Open(JSContext* aCx,
401 const nsAString& aName,
402 const IDBOpenDBOptions& aOptions,
403 CallerType aCallerType,
404 ErrorResult& aRv) {
405 // This overload is nonstandard, see bug 1275496.
406 // Ignore calls with empty options for telemetry of usage count.
407 // Unfortunately, we cannot distinguish between the use of the method with
408 // only a single argument (which actually is a standard overload we don't want
409 // to count) an empty dictionary passed explicitly (which is the custom
410 // overload we would like to count). However, we assume that the latter is so
411 // rare that it can be neglected.
412 if (aOptions.IsAnyMemberPresent()) {
413 Telemetry::AccumulateCategorical(IdentifyPrincipalType(*mPrincipalInfo));
416 return OpenInternal(aCx,
417 /* aPrincipal */ nullptr, aName, aOptions.mVersion,
418 /* aDeleting */ false, aCallerType, aRv);
421 RefPtr<IDBOpenDBRequest> IDBFactory::DeleteDatabase(
422 JSContext* aCx, const nsAString& aName, const IDBOpenDBOptions& aOptions,
423 CallerType aCallerType, ErrorResult& aRv) {
424 return OpenInternal(aCx,
425 /* aPrincipal */ nullptr, aName, Optional<uint64_t>(),
426 /* aDeleting */ true, aCallerType, aRv);
429 int16_t IDBFactory::Cmp(JSContext* aCx, JS::Handle<JS::Value> aFirst,
430 JS::Handle<JS::Value> aSecond, ErrorResult& aRv) {
431 Key first, second;
432 auto result = first.SetFromJSVal(aCx, aFirst);
433 if (result.isErr()) {
434 aRv = result.unwrapErr().ExtractErrorResult(
435 InvalidMapsTo<NS_ERROR_DOM_INDEXEDDB_DATA_ERR>);
436 return 0;
439 result = second.SetFromJSVal(aCx, aSecond);
440 if (result.isErr()) {
441 aRv = result.unwrapErr().ExtractErrorResult(
442 InvalidMapsTo<NS_ERROR_DOM_INDEXEDDB_DATA_ERR>);
443 return 0;
446 if (first.IsUnset() || second.IsUnset()) {
447 aRv.Throw(NS_ERROR_DOM_INDEXEDDB_DATA_ERR);
448 return 0;
451 return Key::CompareKeys(first, second);
454 RefPtr<IDBOpenDBRequest> IDBFactory::OpenForPrincipal(
455 JSContext* aCx, nsIPrincipal* aPrincipal, const nsAString& aName,
456 uint64_t aVersion, SystemCallerGuarantee aGuarantee, ErrorResult& aRv) {
457 MOZ_ASSERT(aPrincipal);
458 if (!NS_IsMainThread()) {
459 MOZ_CRASH(
460 "Figure out security checks for workers! What's this aPrincipal "
461 "we have on a worker thread?");
464 return OpenInternal(aCx, aPrincipal, aName, Optional<uint64_t>(aVersion),
465 /* aDeleting */ false, aGuarantee, aRv);
468 RefPtr<IDBOpenDBRequest> IDBFactory::OpenForPrincipal(
469 JSContext* aCx, nsIPrincipal* aPrincipal, const nsAString& aName,
470 const IDBOpenDBOptions& aOptions, SystemCallerGuarantee aGuarantee,
471 ErrorResult& aRv) {
472 MOZ_ASSERT(aPrincipal);
473 if (!NS_IsMainThread()) {
474 MOZ_CRASH(
475 "Figure out security checks for workers! What's this aPrincipal "
476 "we have on a worker thread?");
479 return OpenInternal(aCx, aPrincipal, aName, aOptions.mVersion,
480 /* aDeleting */ false, aGuarantee, aRv);
483 RefPtr<IDBOpenDBRequest> IDBFactory::DeleteForPrincipal(
484 JSContext* aCx, nsIPrincipal* aPrincipal, const nsAString& aName,
485 const IDBOpenDBOptions& aOptions, SystemCallerGuarantee aGuarantee,
486 ErrorResult& aRv) {
487 MOZ_ASSERT(aPrincipal);
488 if (!NS_IsMainThread()) {
489 MOZ_CRASH(
490 "Figure out security checks for workers! What's this aPrincipal "
491 "we have on a worker thread?");
494 return OpenInternal(aCx, aPrincipal, aName, Optional<uint64_t>(),
495 /* aDeleting */ true, aGuarantee, aRv);
498 RefPtr<IDBOpenDBRequest> IDBFactory::OpenInternal(
499 JSContext* aCx, nsIPrincipal* aPrincipal, const nsAString& aName,
500 const Optional<uint64_t>& aVersion, bool aDeleting, CallerType aCallerType,
501 ErrorResult& aRv) {
502 if (NS_WARN_IF(!mGlobal)) {
503 aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
504 return nullptr;
507 CommonFactoryRequestParams commonParams;
509 PrincipalInfo& principalInfo = commonParams.principalInfo();
511 if (aPrincipal) {
512 if (!NS_IsMainThread()) {
513 MOZ_CRASH(
514 "Figure out security checks for workers! What's this "
515 "aPrincipal we have on a worker thread?");
517 MOZ_ASSERT(aCallerType == CallerType::System);
518 MOZ_DIAGNOSTIC_ASSERT(mPrivateBrowsingMode ==
519 (aPrincipal->GetPrivateBrowsingId() > 0));
521 if (NS_WARN_IF(
522 NS_FAILED(PrincipalToPrincipalInfo(aPrincipal, &principalInfo)))) {
523 IDB_REPORT_INTERNAL_ERR();
524 aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
525 return nullptr;
528 if (principalInfo.type() != PrincipalInfo::TContentPrincipalInfo &&
529 principalInfo.type() != PrincipalInfo::TSystemPrincipalInfo) {
530 IDB_REPORT_INTERNAL_ERR();
531 aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
532 return nullptr;
535 if (NS_WARN_IF(!QuotaManager::IsPrincipalInfoValid(principalInfo))) {
536 IDB_REPORT_INTERNAL_ERR();
537 aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
538 return nullptr;
540 } else {
541 if (mGlobal->GetStorageAccess() == StorageAccess::ePrivateBrowsing) {
542 if (NS_IsMainThread()) {
543 SetUseCounter(
544 mGlobal->GetGlobalJSObject(),
545 aDeleting
546 ? eUseCounter_custom_PrivateBrowsingIDBFactoryOpen
547 : eUseCounter_custom_PrivateBrowsingIDBFactoryDeleteDatabase);
548 } else {
549 SetUseCounter(
550 aDeleting ? UseCounterWorker::Custom_PrivateBrowsingIDBFactoryOpen
551 : UseCounterWorker::
552 Custom_PrivateBrowsingIDBFactoryDeleteDatabase);
555 principalInfo = *mPrincipalInfo;
558 uint64_t version = 0;
559 if (!aDeleting && aVersion.WasPassed()) {
560 if (aVersion.Value() < 1) {
561 aRv.ThrowTypeError("0 (Zero) is not a valid database version.");
562 return nullptr;
564 version = aVersion.Value();
567 // Nothing can be done here if we have previously failed to create a
568 // background actor.
569 if (mBackgroundActorFailed) {
570 IDB_REPORT_INTERNAL_ERR();
571 aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
572 return nullptr;
575 PersistenceType persistenceType;
577 bool isInternal = principalInfo.type() == PrincipalInfo::TSystemPrincipalInfo;
578 if (!isInternal &&
579 principalInfo.type() == PrincipalInfo::TContentPrincipalInfo) {
580 nsCString origin =
581 principalInfo.get_ContentPrincipalInfo().originNoSuffix();
582 isInternal = QuotaManager::IsOriginInternal(origin);
585 const bool isPrivate =
586 principalInfo.type() == PrincipalInfo::TContentPrincipalInfo &&
587 principalInfo.get_ContentPrincipalInfo().attrs().mPrivateBrowsingId > 0;
589 if (isInternal) {
590 // Chrome privilege and internal origins always get persistent storage.
591 persistenceType = PERSISTENCE_TYPE_PERSISTENT;
592 } else if (isPrivate) {
593 persistenceType = PERSISTENCE_TYPE_PRIVATE;
594 } else {
595 persistenceType = PERSISTENCE_TYPE_DEFAULT;
598 DatabaseMetadata& metadata = commonParams.metadata();
599 metadata.name() = aName;
600 metadata.persistenceType() = persistenceType;
602 FactoryRequestParams params;
603 if (aDeleting) {
604 metadata.version() = 0;
605 params = DeleteDatabaseRequestParams(commonParams);
606 } else {
607 metadata.version() = version;
608 params = OpenDatabaseRequestParams(commonParams);
611 if (!mBackgroundActor) {
612 BackgroundChildImpl::ThreadLocal* threadLocal =
613 BackgroundChildImpl::GetThreadLocalForCurrentThread();
615 UniquePtr<ThreadLocal> newIDBThreadLocal;
616 ThreadLocal* idbThreadLocal;
618 if (threadLocal && threadLocal->mIndexedDBThreadLocal) {
619 idbThreadLocal = threadLocal->mIndexedDBThreadLocal.get();
620 } else {
621 nsCOMPtr<nsIUUIDGenerator> uuidGen =
622 do_GetService("@mozilla.org/uuid-generator;1");
623 MOZ_ASSERT(uuidGen);
625 nsID id;
626 MOZ_ALWAYS_SUCCEEDS(uuidGen->GenerateUUIDInPlace(&id));
628 newIDBThreadLocal = WrapUnique(new ThreadLocal(id));
629 idbThreadLocal = newIDBThreadLocal.get();
632 PBackgroundChild* backgroundActor =
633 BackgroundChild::GetOrCreateForCurrentThread();
634 if (NS_WARN_IF(!backgroundActor)) {
635 IDB_REPORT_INTERNAL_ERR();
636 aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
637 return nullptr;
641 BackgroundFactoryChild* actor = new BackgroundFactoryChild(*this);
643 mBackgroundActor = static_cast<BackgroundFactoryChild*>(
644 backgroundActor->SendPBackgroundIDBFactoryConstructor(
645 actor, idbThreadLocal->GetLoggingInfo()));
647 if (NS_WARN_IF(!mBackgroundActor)) {
648 mBackgroundActorFailed = true;
649 IDB_REPORT_INTERNAL_ERR();
650 aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
651 return nullptr;
655 if (newIDBThreadLocal) {
656 if (!threadLocal) {
657 threadLocal = BackgroundChildImpl::GetThreadLocalForCurrentThread();
659 MOZ_ASSERT(threadLocal);
660 MOZ_ASSERT(!threadLocal->mIndexedDBThreadLocal);
662 threadLocal->mIndexedDBThreadLocal = std::move(newIDBThreadLocal);
666 RefPtr<IDBOpenDBRequest> request = IDBOpenDBRequest::Create(
667 aCx, SafeRefPtr{this, AcquireStrongRefFromRawPtr{}}, mGlobal);
668 if (!request) {
669 MOZ_ASSERT(!NS_IsMainThread());
670 aRv.ThrowUncatchableException();
671 return nullptr;
674 MOZ_ASSERT(request);
676 if (aDeleting) {
677 IDB_LOG_MARK_CHILD_REQUEST(
678 "indexedDB.deleteDatabase(\"%s\")", "IDBFactory.deleteDatabase(%.0s)",
679 request->LoggingSerialNumber(), NS_ConvertUTF16toUTF8(aName).get());
680 } else {
681 IDB_LOG_MARK_CHILD_REQUEST(
682 "indexedDB.open(\"%s\", %s)", "IDBFactory.open(%.0s%.0s)",
683 request->LoggingSerialNumber(), NS_ConvertUTF16toUTF8(aName).get(),
684 IDB_LOG_STRINGIFY(aVersion));
687 nsresult rv = InitiateRequest(WrapNotNull(request), params);
688 if (NS_WARN_IF(NS_FAILED(rv))) {
689 IDB_REPORT_INTERNAL_ERR();
690 aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
691 return nullptr;
694 return request;
697 nsresult IDBFactory::InitiateRequest(
698 const NotNull<RefPtr<IDBOpenDBRequest>>& aRequest,
699 const FactoryRequestParams& aParams) {
700 MOZ_ASSERT(mBackgroundActor);
701 MOZ_ASSERT(!mBackgroundActorFailed);
703 bool deleting;
704 uint64_t requestedVersion;
706 switch (aParams.type()) {
707 case FactoryRequestParams::TDeleteDatabaseRequestParams: {
708 const DatabaseMetadata& metadata =
709 aParams.get_DeleteDatabaseRequestParams().commonParams().metadata();
710 deleting = true;
711 requestedVersion = metadata.version();
712 break;
715 case FactoryRequestParams::TOpenDatabaseRequestParams: {
716 const DatabaseMetadata& metadata =
717 aParams.get_OpenDatabaseRequestParams().commonParams().metadata();
718 deleting = false;
719 requestedVersion = metadata.version();
720 break;
723 default:
724 MOZ_CRASH("Should never get here!");
727 auto actor = new BackgroundFactoryRequestChild(
728 SafeRefPtr{this, AcquireStrongRefFromRawPtr{}}, aRequest, deleting,
729 requestedVersion);
731 if (!mBackgroundActor->SendPBackgroundIDBFactoryRequestConstructor(actor,
732 aParams)) {
733 aRequest->DispatchNonTransactionError(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
734 return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
737 return NS_OK;
740 void IDBFactory::DisconnectFromGlobal(nsIGlobalObject* aOldGlobal) {
741 MOZ_DIAGNOSTIC_ASSERT(aOldGlobal);
742 // If CC unlinks us first, then mGlobal might be nullptr
743 MOZ_DIAGNOSTIC_ASSERT(!mGlobal || mGlobal == aOldGlobal);
745 mGlobal = nullptr;
748 NS_IMPL_CYCLE_COLLECTING_ADDREF(IDBFactory)
749 NS_IMPL_CYCLE_COLLECTING_RELEASE(IDBFactory)
751 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(IDBFactory)
752 NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
753 NS_INTERFACE_MAP_ENTRY(nsISupports)
754 NS_INTERFACE_MAP_END
756 NS_IMPL_CYCLE_COLLECTION_CLASS(IDBFactory)
758 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(IDBFactory)
759 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mGlobal)
760 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBrowserChild)
761 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEventTarget)
762 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
764 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(IDBFactory)
765 NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
766 NS_IMPL_CYCLE_COLLECTION_UNLINK(mGlobal)
767 NS_IMPL_CYCLE_COLLECTION_UNLINK(mBrowserChild)
768 NS_IMPL_CYCLE_COLLECTION_UNLINK(mEventTarget)
769 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
771 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(IDBFactory)
772 NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
773 NS_IMPL_CYCLE_COLLECTION_TRACE_END
775 JSObject* IDBFactory::WrapObject(JSContext* aCx,
776 JS::Handle<JSObject*> aGivenProto) {
777 return IDBFactory_Binding::Wrap(aCx, this, aGivenProto);
780 } // namespace mozilla::dom