Files
palemoon27/dom/datastore/DataStoreService.cpp
T
roytam1 e4c3e62beb import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1216751 part 1. Restrict value iterators to interfaces that have indexed properties and pair iterators to interfaces that do not have indexed properties. r=qdot (6519f3f8c5)
- Bug 1216751 part 2. For value iterators, "entries", "keys", and "values" must just come from Array.prototype. r=qdot (c0859f945c)
- Bug 1216751 part 3. For pair iterators, @@iterator should be an alias for "entries". Similarly for maplikes and "entries" and setlikes and "values". r=qdot (bbe7c04782)
- Bug 1216751 part 4. Implement forEach for iterable interfaces. r=qdot (8fdba677a4)
- Bug 1216751 part 5. Remove the now-unnecessary value iterator infrastructure, since it's entirely handled via the %ArrayPrototype% methods now. r=qdot (88d3911694)
- Bug 1231333 - part 1, JS engine: only allow futexWait in workers. r=luke (28e16fd2f9)
- Bug 1231333 - part 2, DOM: only allow futexWait in workers. r=khuey (6c4dc98037)
- Bug 1148990 - Don't ship bagheeraclient.js or tokenserverclient.js on Android. r=gps (aa9b22699a)
- Bug 1216749 - Land the Firefox Kinto.js client (r=rnewman) (ea8c74e2ea)
- Bug 1230221 - Convert JS callsites to use asyncOpen2 within services/ (r=sicking) (07ac8751f1)
- Bug 1242965 - Make services/common eslintable. r=rnewman (0c84562750)
- Bug 1055616 - Skip addons addons without a sourceURI or from a non-secure domain rather than treating them as errors. r=rnewman (7b8b738be0)
- Bug 1229986 - get Sync tps tests starting again. r=whimboo (8cd0bf4f7f)
- Bug 1003204: Removed CommonUtils.exceptionStr() in services/sync r=makh r=gfritzsche (830c106a29)
- Bug 1003204: Removed CommonUtils.exceptionStr() in services/common/ r=gfritzsche (2c7bd4f8b5)
- Bug 1234734 - Replace CommonUtils.stackTrace() with Log.stackTrace(). r=markh (3f0e88f192)
- Bug 1241715 - get Sync TPS tests working locally by tweaking observers listened for and the authentication setup. r=whimboo (529b2f3d44)
- Bug 1203736 - Convert H264::DecodeSPS assert to error return. r=jya (41c8c34c42)
- Bug 1186716: Error if SPS NAL parsing failed. r=rillian (6c158be51e)
- Bug 1187076 - Warn at end of SPS buffers. r=jya (2a49671261)
- fix broken files (a090aad200)
- Bug 1218217: avoid buffersize overflow even if codec is unbounded in dimensions r=pkerr (356140c947)
- Bug 1218217: bustage fix for static assert r=bustage (e86dc5bf3a)
- Bug 1041882 - Remove Froyo-specific support from libcubeb. r=snorp, r=padenot (e1f2d5283f)
- Bug 1073319 - Enable AVX2 for libvpx on linux (update.py). r=rillian (934fd0a896)
- Bug 1245027 - Move LOCAL_INCLUDES to moz.build in media/libvpx. r=mshal (7e56797d0e)
- parts of Bug 1151175 - Update libvpx update.py for 1.4.0. (0e3f4a470f)
- bits of 1178215 (bab7592703)
- Bug 1218124 - Add vpx_once patch to update script. r=gerald (7b72a43382)
- Bug 1225221 - vpx: Allow 8k video in update.sh. r=kinetik (9ec59f7737)
- Bug 1224363 - Upstream update patch - r=rillian (4772921a5f)
- Bug 1224361 - Upstream update patch - r=rillian (36ad6f1de4)
- Bug 1233983 - Make libvpx build with clang-cl; r=rillian (5d98a8d888)
- Bug 1224371 - Upstream update patch. r=jya (25164ba856)
- Bug 1237848 - Updated update.py patch - r=rillian (69646eb6dc)
- Bug 1184226 - Suppressing received packets when disabled, r=ekr (c8dfdb1a56)
- Bug 1184226 - Disabling write on shutdown, r=ekr (d5a810dbe5)
- Bug 1184226 - Updating transportlayerdtls logging levels, r=ekr (f3bc4a9889)
- Bug 1137932: Unwind the stack before starting the DTLS handshake. r=mt (69dce8243a)
- Bug 1214269 - read multiple DTLS packets from NSS if present. r=mt rjesup (e57b1628f5)
- Bug 1235235 - Fix -Wimplicit-fallthrough warning in media/mtransport/. r=ekr (d56c9d1244)
- Bug 1115483 - Accept a match on any a=fingerprint value. r=ekr (4a58378c09)
- Bug 1167274 - Do the right thing when accessing the proxyinfo fails for some reason. r=mt (3ea23173ea)
- Bug 1125292 - Sending ALPN header field for WebRTC calls, r=bwc (16fda60c39)
- Bug 1167443 - Fix verification of end-of-candidates in mochitests. r=mt (8d74546e68)
- Bug 1192813 - update the default candidate as new candidates arrive.  r=bwc (490ac80af2)
- Bug 1206981 - prevent ICE TCP from being turned off under e10s. r=jesup (a38afd56b8)
- Bug 1234578 - Assert if PCM is destroyed improperly. r=rjesup (f1aa0d7cbc)
- Bug 1164564 - WorkerDebugger.initialize should not return failure when called more than once;r=khuey (c316c83af7)
- Bug 1211903 - WorkerDebugger should live on the main thread;r=khuey (5586888e77)
- Bug 1164581 - Adding an overload for NS_ProxyRelease that accepts already_AddRefed, and removing all the others. r=bobbyholley (bc70230689)
- Bug 1186750 part 1 - Inlinize trivial constructors and destructors of events in DeviceStorageRequestParent. r=dhylands (0fc6b594b1)
- Bug 1186750 part 2 - Remove some unused member fields in events in DeviceStorageRequestParent. r=dhylands (d4be7e7031)
- Bug 1186750 part 3 - Abstract CancelableFileEvent in DeviceStorageReqeustParent and use already_AddRefed&& for passing DeviceStorageFile parameter. r=dhylands (cea4df4465)
- Bug 1186750 part 4 - Clear runnable list in DeviceStorageRequestParent when being destroyed. r=dhylands (a4d6018ce6)
- Bug 1196315 - Ensure MIME service is only accessed on the main thread. r=dhylands (20c07f4baf)
- Bug 1186750 part 5 - Convert nsDOMDeviceStorage::CheckPermission to take already_AddRefed&&. r=dhylands (7b2d0b415e)
- Bug 1186750 part 6 - Remove unused and unimplemented method nsDOMDeviceStorage::StorePermission. r=dhylands (e6772e7b51)
- Bug 1186750 part 7 - Convert DispatchToOwningThread and DispatchOrAbandon to take already_AddRefed&&. r=dhylands (5925568a22)
- Bug 1186750 part 8 - Convert DeviceStorageUsedSpaceCache::Dispatch to use already_AddRef&&. r=dhylands (660b44eec7)
- Bug 1186750 part 9 - Use already_AddRefed&& to initialize mFile of device storage requests. r=dhylands (c94464f412)
- Bug 1186750 part 10 - Simplify code in DeviceStorageRequestParent::Dispatch. r=dhylands (debcc219ca)
- Bug 1186750 part 11 - Convert all usage of Dispatch/NS_DispatchToMainThread in dom/devicestorage to pass in either already_AddRefed or raw pointer. r=dhylands (753694d0b5)
- Bug 1059469: Part 1 - Add a log module for dump() calls. r=bent (d94c677e49)
- Bug 1059469: Part 2 - When rescheduling the interval timer, cancel it first, and refactor things so that actually does something. r=bent (1edc485b0f)
- Bug 1243881 - patch 1 - unship performance.translateTime, r=bz (5a4afeea67)
- Bug 1243881 - patch 2 - unship performance.translateTime, r=bz (5bf9557cd4)
- Bug 1165722 - Replace JS_GetPropertyDescriptor usage in Xray code. r=bholley (e277cbcc78)
- Bug 1243824. Add support for static functions and attributes on JSXrays. r=bholley (498d6c6034)
- Bug 1228456 - SharedWorker should close the MessagePort in case the connecting runnable is not dispatched, r=smaug (c14a3e212f)
- Bug 779707 - Add crashtest. (e86caca48e)
- Bug 1228456 - add 'override' to the Cancel() method of a nsICancelableRunnable, rs=me (48db3b97e9)
- Bug 1131323 - Enable SharedWorker loads to be intercepted through service workers; r=nsm (b2d972c5e3)
- Bug 1173002 - Set worker system principal flag correctly when created from chrome, r=bz, a=kwierso. (ac9fc2980d)
- bits of 1113429 backout (a862f16bb7)
- bug 1206312 - add IndexedDatabaseManager include to IDBKeyRange. r=bz (bd6663f976)
- Bug 1247117: De-namespace much of IndexedDB. r=baku (a996e3b443)
- Bug 1196841: Update getAll/getAllKeys to match the spec and expose them. r=baku (7365769e04)
- Bug 1196840: Make IDBTransaction::ObjectStoreNames const. r=baku (e7af2b0510)
- Bug 1176165 - Fix the exception codes returned from functions that modify the IndexedDB schema, r=janv. (efa4e818d0)
- Bug 935753 - Firefox displays the "This is a secure Firefox page" indicator on pages served by addons. r=MattN (77dced27ad)
- Bug 925681 - Show identity block and reload icon in awesomebar in Australis' customization mode. ui-r=shorlander, r=Gijs (ffd1b2f6a4)
- Bug 970382 - Add about:accounts to the list of chrome UIs with a special identity mode r=gavin (6d2817d087)
- Bug 1051847 - Add trusted identity block to about:license and about:rights. r=dao (aa8dfe4d1d)
- Bug 1094947 - The trusted identity block is not displayed for the about:downloads page. r=jaws (1c51faa077)
- Bug 686281 - Implement CSS mask style; r=dbaron. (2f823c4a49)
- Bug 686281 - Mask CSS parsing and Mask DOM API. r=dbaron (f9cc291131)
- Bug 686281 - Mask CSS rendering; r=mstange (b26ba7ba7e)
- Bug 686281 - Mask CSS animation; r=dbaron. (4ce1ba671e)
- Bug 686281 - Mask CSS webkit-alias; r=dbaron. (c27f4023d6)
- Bug 686281 - Mask mochitest; r=dbaron. (010fcdfd04)
- Bug 686281 - Expands will-change of a shorthand prop to longhand ones; r=dbaron. (f8e4a6dcfd)
- Bug 686281 - A static assertion to keep value correctness of NS_RULE_NODE_IS_ANIMATION_RULE; r=dbaron. (5ae87b576b)
- Bug 686281 - Remove nsStyleSVGReset::mMask; r=dbaron (1e7a0dfb45)
- Bug 686281 - mask-composite reftests; r=dbaron (7f769e196a)
- Bug 686281 - Rename nsStyleSVGReset::mLayers to nsStyleSVGReset::mMask; Rename nsStyleBackground::mLayers to nsStyleBackground::mImage. r=dbaron (3bd4fc6e3b)
- Bug 1241275 - Change the way -moz-window-dragging works. r=heycam,roc (5691f2dbf5)
- Bug 1246892 - pass aCTF as a reference instead of value. r=roc (98b0e45063)
- Bug 1234800 - Reinstate code that adjusts dirty rects for fixed-position frames in display ports. r=tn (44e55ebacb)
- Bug 1234800 - Move this line to the right place. r=tn (1a86a7fc72)
- Bug 1216832 - Handle preserve-3d visible regions during display list building by always transforming from the preserve-3d root each time. r=roc (1887af1172)
- Bug 1231243 - In nsDisplayBackgroundImage::GetBoundsInternal(), take the union of the image bounds and the viewport bounds if APZ is enabled. r=mstange (87a1fa0ab4)
- Bug 1246622 - Handle nested preserve-3d contexts when hit testing. r=roc (6eed51c734)
- Bug 1235945 - Fix assertion error in some cases when running szip when debug flags are enabled for host tools. r=froydnj (3a0aa4f728)
- Bug 1224798: Do not produce a clip mask if our context is entirely clipped out anyway. r=jrmuizel (3926a4ef7d)
- Bug 1223604 - Disentangle nsSVGClipPathFrame::ApplyClipOrPaintClipMask and make the code easier to understand. r=Bas (c8c19a1b0d)
- Bug 1204405: Don't access prefs off main thread in testing ProcessLink::Open(). r=khuey (301aa7259d)
- Bug 1248896 - don't conditional compile on config ENABLE_TESTS in Nuwa. r=khuey (4f2fd275fd)
- Bug 1232458 - use UniquePtr<T[]> instead of nsAutoArrayPtr<T> in WindowsDllBlocklist.cpp; r=aklotz (292071bdb5)
- Bug 1247741 - Additional checks for pointer validity in LdrLoadDLL detour. r=aklotz (8ee48e8cf3)
- Bug 1113930 - Move __libc_stack_end related code block from StackWalk.cpp in a non-OSX section. r=froydnj (4f0f9e2e66)
- Bug 1113930 - Use the actual stack end address on x86 OSX and Android for the stack walker. r=froydnj (7371d9a508)
- missing bit of Bug 1216681 (fdf69e362f)
- Bug 1193593 - Test fingerprinting resistance for media queries in picture elements. r=heycam (6155b73c26)
- Bug 1232829 - Detach obsolete DocumentTimeline from refresh driver when the document is reset; r=smaug (564680e2a0)
- Bug 1075457, part 1 - Implement rendering for |clip-path:polygon()|. r=mstange, r=jwatt (76056caacd)
- Bug 1075457, part 2 - Implement circle() and ellipse() for the |clip-path| property. r=mstange, r=jwatt (4b8b39c682)
- Bug 1094571 - add unicode-range load tests. r=heycam (3358555411)
- Bug 1216695 - Remove the Request.context specific bits from fetch-request-resources.https.html; r=bkelly (2315e50b97)
- Bug 1193133 - Disable broken service worker wpt tests. r=bkelly (8f0205d5e7)
- Bug 1199831: Fix a bunch of mixed-content violations in imported ServiceWorker WPTs. r=jdm (33f261ce91)
- bit of Bug 603201 (325170577f)
- Bug 1184798 - same origin, cors and no-cors load tests. r=bkelly (f8549dd0bb)
- Bug 1210581: Test controlled worker loads (XHR, fetch, importScripts). r=ehsan (41a436df47)
- Bug 1215196 - Fix web-platform-tests iframe scripts to avoid pulling in testharness.js in them; r=bkelly (a2edb0784c)
- Bug 1242798 - Don't OSR into Ion on debuggee frames. (r=jandem) (21e17bdd9d)
- Bug 1238658 - Allow setElem-accessor optimizations only for native baseHolder objects; r=efaust (12c9766a53)
- Bug 1144630 - Follup: Fix review nit. (rs=evilpie) (67b5cc2c7f)
- Bug 1182866 - Fix Baseline GETNAME stubs to check for uninitialized lexicals. (r=jandem) (dd47d2025a)
- Bug 1189536 - Make fetch-request-xhr.https.html pass; r=bkelly (ce177226bf)
- Bug 1188822 - Make service-workers/service-worker/fetch-request-resources.https.html pass. r=bkelly (3a5f3a6660)
2023-11-14 15:08:43 +08:00

1523 lines
41 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 "DataStoreService.h"
#include "DataStoreCallbacks.h"
#include "DataStoreDB.h"
#include "DataStoreRevision.h"
#include "mozilla/dom/DataStore.h"
#include "mozilla/dom/DataStoreBinding.h"
#include "mozilla/dom/DataStoreImplBinding.h"
#include "nsIDataStore.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/Preferences.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/DOMError.h"
#include "mozilla/dom/IDBCursor.h"
#include "mozilla/dom/IDBObjectStore.h"
#include "mozilla/dom/IDBRequest.h"
#include "mozilla/dom/IDBTransaction.h"
#include "mozilla/dom/PermissionMessageUtils.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/unused.h"
#include "mozIApplication.h"
#include "mozIApplicationClearPrivateDataParams.h"
#include "nsIAppsService.h"
#include "nsIDOMEvent.h"
#include "nsIDocument.h"
#include "nsIDOMGlobalPropertyInitializer.h"
#include "nsIIOService.h"
#include "nsIMutableArray.h"
#include "nsIObserverService.h"
#include "nsIPermissionManager.h"
#include "nsIScriptSecurityManager.h"
#include "nsISupportsPrimitives.h"
#include "nsIUUIDGenerator.h"
#include "nsPIDOMWindow.h"
#include "nsIURI.h"
#include "nsContentUtils.h"
#include "nsNetCID.h"
#include "nsServiceManagerUtils.h"
#include "nsThreadUtils.h"
#include "nsXULAppAPI.h"
#define ASSERT_PARENT_PROCESS() \
MOZ_ASSERT(XRE_IsParentProcess()); \
if (NS_WARN_IF(!XRE_IsParentProcess())) { \
return NS_ERROR_FAILURE; \
}
using mozilla::BasePrincipal;
using mozilla::OriginAttributes;
namespace mozilla {
namespace dom {
// This class contains all the information about a DataStore.
class DataStoreInfo
{
public:
DataStoreInfo()
: mReadOnly(true)
, mEnabled(false)
{}
DataStoreInfo(const nsAString& aName,
const nsAString& aOriginURL,
const nsAString& aManifestURL,
bool aReadOnly,
bool aEnabled)
: mReadOnly(true)
, mEnabled(false)
{
Init(aName, aOriginURL, aManifestURL, aReadOnly, aEnabled);
}
void Init(const nsAString& aName,
const nsAString& aOriginURL,
const nsAString& aManifestURL,
bool aReadOnly,
bool aEnabled)
{
mName = aName;
mOriginURL = aOriginURL;
mManifestURL = aManifestURL;
mReadOnly = aReadOnly;
mEnabled = aEnabled;
}
void Update(const nsAString& aName,
const nsAString& aOriginURL,
const nsAString& aManifestURL,
bool aReadOnly)
{
mName = aName;
mOriginURL = aOriginURL;
mManifestURL = aManifestURL;
mReadOnly = aReadOnly;
}
void Enable()
{
mEnabled = true;
}
nsString mName;
nsString mOriginURL;
nsString mManifestURL;
bool mReadOnly;
// A DataStore is enabled when it has its first revision.
bool mEnabled;
};
namespace {
// Singleton for DataStoreService.
StaticRefPtr<DataStoreService> gDataStoreService;
nsString gHomeScreenManifestURL;
static uint64_t gCounterID = 0;
typedef nsClassHashtable<nsUint32HashKey, DataStoreInfo> HashApp;
void
RejectPromise(nsPIDOMWindow* aWindow, Promise* aPromise, nsresult aRv)
{
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(NS_FAILED(aRv));
RefPtr<DOMError> error;
if (aRv == NS_ERROR_DOM_SECURITY_ERR) {
error = new DOMError(aWindow, NS_LITERAL_STRING("SecurityError"),
NS_LITERAL_STRING("Access denied"));
} else {
error = new DOMError(aWindow, NS_LITERAL_STRING("InternalError"),
NS_LITERAL_STRING("An error occurred"));
}
aPromise->MaybeRejectBrokenly(error);
}
void
DeleteDatabase(const nsAString& aName,
const nsAString& aManifestURL)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
RefPtr<DataStoreDB> db = new DataStoreDB(aManifestURL, aName);
db->Delete();
}
static void
DeleteDataStoresHelper(nsClassHashtable<nsStringHashKey, HashApp>& aStores,
uint32_t aAppId)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
for (auto iter1 = aStores.Iter(); !iter1.Done(); iter1.Next()) {
nsAutoPtr<HashApp>& apps = iter1.Data();
for (auto iter2 = apps->Iter(); !iter2.Done(); iter2.Next()) {
if (aAppId == iter2.Key()) {
nsAutoPtr<DataStoreInfo>& info = iter2.Data();
DeleteDatabase(info->mName, info->mManifestURL);
iter2.Remove();
}
}
if (apps->Count() == 0) {
iter1.Remove();
}
}
}
void
GeneratePermissionName(nsAString& aPermission,
const nsAString& aName,
const nsAString& aManifestURL)
{
aPermission.AssignLiteral("indexedDB-chrome-");
aPermission.Append(aName);
aPermission.Append('|');
aPermission.Append(aManifestURL);
}
nsresult
ResetPermission(uint32_t aAppId, const nsAString& aOriginURL,
const nsAString& aManifestURL,
const nsAString& aPermission,
bool aReadOnly)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
nsresult rv;
nsCOMPtr<nsIIOService> ioService(do_GetService(NS_IOSERVICE_CONTRACTID, &rv));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
nsCOMPtr<nsIURI> uri;
rv = ioService->NewURI(NS_ConvertUTF16toUTF8(aOriginURL), nullptr, nullptr,
getter_AddRefs(uri));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
OriginAttributes attrs(aAppId, false);
nsCOMPtr<nsIPrincipal> principal =
BasePrincipal::CreateCodebasePrincipal(uri, attrs);
NS_ENSURE_TRUE(principal, NS_ERROR_FAILURE);
nsCOMPtr<nsIPermissionManager> pm =
do_GetService(NS_PERMISSIONMANAGER_CONTRACTID);
if (!pm) {
return NS_ERROR_FAILURE;
}
nsCString basePermission;
basePermission.Append(NS_ConvertUTF16toUTF8(aPermission));
// Write permission
{
nsCString permission;
permission.Append(basePermission);
permission.AppendLiteral("-write");
uint32_t perm = nsIPermissionManager::UNKNOWN_ACTION;
rv = pm->TestExactPermissionFromPrincipal(principal, permission.get(),
&perm);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (aReadOnly && perm == nsIPermissionManager::ALLOW_ACTION) {
rv = pm->RemoveFromPrincipal(principal, permission.get());
}
else if (!aReadOnly && perm != nsIPermissionManager::ALLOW_ACTION) {
rv = pm->AddFromPrincipal(principal, permission.get(),
nsIPermissionManager::ALLOW_ACTION,
nsIPermissionManager::EXPIRE_NEVER, 0);
}
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
// Read permission
{
nsCString permission;
permission.Append(basePermission);
permission.AppendLiteral("-read");
uint32_t perm = nsIPermissionManager::UNKNOWN_ACTION;
rv = pm->TestExactPermissionFromPrincipal(principal, permission.get(),
&perm);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (perm != nsIPermissionManager::ALLOW_ACTION) {
rv = pm->AddFromPrincipal(principal, permission.get(),
nsIPermissionManager::ALLOW_ACTION,
nsIPermissionManager::EXPIRE_NEVER, 0);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
}
// Generic permission
uint32_t perm = nsIPermissionManager::UNKNOWN_ACTION;
rv = pm->TestExactPermissionFromPrincipal(principal, basePermission.get(),
&perm);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (perm != nsIPermissionManager::ALLOW_ACTION) {
rv = pm->AddFromPrincipal(principal, basePermission.get(),
nsIPermissionManager::ALLOW_ACTION,
nsIPermissionManager::EXPIRE_NEVER, 0);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
return NS_OK;
}
void
HomeScreenPrefCallback(const char* aPrefName, void* /* aClosure */)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
RefPtr<DataStoreService> service = DataStoreService::Get();
if (!service) {
return;
}
service->HomeScreenPrefChanged();
}
} /* anonymous namespace */
// A PendingRequest is created when a content code wants a list of DataStores
// but some of them are not enabled yet.
class PendingRequest
{
public:
void Init(nsPIDOMWindow* aWindow, Promise* aPromise,
const nsTArray<DataStoreInfo>& aStores,
const nsTArray<nsString>& aPendingDataStores)
{
mWindow = aWindow;
mPromise = aPromise;
mStores = aStores;
mPendingDataStores = aPendingDataStores;
}
nsCOMPtr<nsPIDOMWindow> mWindow;
RefPtr<Promise> mPromise;
nsTArray<DataStoreInfo> mStores;
// This array contains the list of manifestURLs of the DataStores that are
// not enabled yet.
nsTArray<nsString> mPendingDataStores;
};
// This callback is used to enable a DataStore when its first revisionID is
// created.
class RevisionAddedEnableStoreCallback final :
public DataStoreRevisionCallback
{
private:
~RevisionAddedEnableStoreCallback() {}
public:
NS_INLINE_DECL_REFCOUNTING(RevisionAddedEnableStoreCallback);
RevisionAddedEnableStoreCallback(uint32_t aAppId,
const nsAString& aName,
const nsAString& aManifestURL)
: mAppId(aAppId)
, mName(aName)
, mManifestURL(aManifestURL)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
}
void
Run(const nsAString& aRevisionId)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
RefPtr<DataStoreService> service = DataStoreService::Get();
MOZ_ASSERT(service);
service->EnableDataStore(mAppId, mName, mManifestURL);
}
private:
uint32_t mAppId;
nsString mName;
nsString mManifestURL;
};
// This DataStoreDBCallback is called when DataStoreDB opens the DataStore DB.
// Then the first revision will be created if it's needed.
class FirstRevisionIdCallback final : public DataStoreDBCallback
, public nsIDOMEventListener
{
public:
NS_DECL_ISUPPORTS
FirstRevisionIdCallback(uint32_t aAppId, const nsAString& aName,
const nsAString& aManifestURL)
: mAppId(aAppId)
, mName(aName)
, mManifestURL(aManifestURL)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
}
void
Run(DataStoreDB* aDb, RunStatus aStatus) override
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
MOZ_ASSERT(aDb);
if (aStatus == Error) {
NS_WARNING("Failed to create the first revision.");
return;
}
ErrorResult error;
if (aStatus == Success) {
mTxn = aDb->Transaction();
RefPtr<IDBObjectStore> store =
mTxn->ObjectStore(NS_LITERAL_STRING(DATASTOREDB_REVISION), error);
if (NS_WARN_IF(error.Failed())) {
return;
}
AutoSafeJSContext cx;
mRequest = store->OpenCursor(cx, JS::UndefinedHandleValue,
IDBCursorDirection::Prev, error);
if (NS_WARN_IF(error.Failed())) {
return;
}
nsresult rv;
rv = mRequest->EventTarget::AddEventListener(NS_LITERAL_STRING("success"),
this, false);
if (NS_FAILED(rv)) {
NS_WARNING("Failed to add an EventListener.");
return;
}
return;
}
// The DB has just been created.
error = CreateFirstRevision(aDb->Transaction());
if (error.Failed()) {
NS_WARNING("Failed to add a revision to a DataStore.");
}
}
nsresult
CreateFirstRevision(IDBTransaction* aTxn)
{
MOZ_ASSERT(aTxn);
ErrorResult error;
RefPtr<IDBObjectStore> store =
aTxn->ObjectStore(NS_LITERAL_STRING(DATASTOREDB_REVISION), error);
if (NS_WARN_IF(error.Failed())) {
return error.StealNSResult();
}
MOZ_ASSERT(store);
RefPtr<RevisionAddedEnableStoreCallback> callback =
new RevisionAddedEnableStoreCallback(mAppId, mName, mManifestURL);
// Note: this cx is only used for rooting and AddRevision, neither of which
// actually care which compartment we're in.
AutoSafeJSContext cx;
// If the revision doesn't exist, let's create it.
RefPtr<DataStoreRevision> revision = new DataStoreRevision();
nsresult rv = revision->AddRevision(cx, store, 0,
DataStoreRevision::RevisionVoid,
callback);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
// nsIDOMEventListener
NS_IMETHOD
HandleEvent(nsIDOMEvent* aEvent) override
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
RefPtr<IDBRequest> request;
request.swap(mRequest);
RefPtr<IDBTransaction> txn;
txn.swap(mTxn);
request->RemoveEventListener(NS_LITERAL_STRING("success"), this, false);
nsString type;
nsresult rv = aEvent->GetType(type);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
#ifdef DEBUG
MOZ_ASSERT(type.EqualsASCII("success"));
#endif
AutoSafeJSContext cx;
ErrorResult error;
JS::Rooted<JS::Value> result(cx);
request->GetResult(cx, &result, error);
if (NS_WARN_IF(error.Failed())) {
return error.StealNSResult();
}
// This means that the content is a IDBCursor, so the first revision already
// exists.
if (result.isObject()) {
#ifdef DEBUG
IDBCursor* cursor = nullptr;
error = UNWRAP_OBJECT(IDBCursor, &result.toObject(), cursor);
MOZ_ASSERT(!error.Failed());
#endif
RefPtr<DataStoreService> service = DataStoreService::Get();
MOZ_ASSERT(service);
return service->EnableDataStore(mAppId, mName, mManifestURL);
}
rv = CreateFirstRevision(txn);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
private:
~FirstRevisionIdCallback() {}
RefPtr<IDBRequest> mRequest;
RefPtr<IDBTransaction> mTxn;
uint32_t mAppId;
nsString mName;
nsString mManifestURL;
};
NS_IMPL_ISUPPORTS(FirstRevisionIdCallback, nsIDOMEventListener)
// This class calls the 'retrieveRevisionId' method of the DataStore object for
// any DataStore in the 'mResults' array. When all of them are called, the
// promise is resolved with 'mResults'.
// The reson why this has to be done is because DataStore are object that can be
// created in any thread and in any process. The first revision has been
// created, but they don't know its value yet.
class RetrieveRevisionsCounter
{
private:
~RetrieveRevisionsCounter() {}
public:
NS_INLINE_DECL_REFCOUNTING(RetrieveRevisionsCounter);
RetrieveRevisionsCounter(uint32_t aId, Promise* aPromise, uint32_t aCount)
: mPromise(aPromise)
, mId(aId)
, mCount(aCount)
{
MOZ_ASSERT(NS_IsMainThread());
}
void
AppendDataStore(JSContext* aCx, DataStore* aDataStore,
nsIDataStore* aDataStoreIf)
{
MOZ_ASSERT(NS_IsMainThread());
mResults.AppendElement(aDataStore);
// DataStore will run this callback when the revisionID is retrieved.
JSFunction* func = js::NewFunctionWithReserved(aCx, JSCallback,
0 /* nargs */, 0 /* flags */,
nullptr);
if (!func) {
return;
}
JS::Rooted<JSObject*> obj(aCx, JS_GetFunctionObject(func));
if (!obj) {
return;
}
// We use the ID to know which counter is this. The service keeps all of
// these counters alive with their own IDs in an hashtable.
js::SetFunctionNativeReserved(obj, 0, JS::Int32Value(mId));
JS::Rooted<JS::Value> value(aCx, JS::ObjectValue(*obj));
nsresult rv = aDataStoreIf->RetrieveRevisionId(value);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
}
private:
static bool
JSCallback(JSContext* aCx, unsigned aArgc, JS::Value* aVp)
{
MOZ_ASSERT(NS_IsMainThread());
JS::CallArgs args = CallArgsFromVp(aArgc, aVp);
JS::Rooted<JS::Value> value(aCx,
js::GetFunctionNativeReserved(&args.callee(), 0));
uint32_t id = value.toInt32();
RefPtr<DataStoreService> service = DataStoreService::Get();
MOZ_ASSERT(service);
RefPtr<RetrieveRevisionsCounter> counter = service->GetCounter(id);
MOZ_ASSERT(counter);
// When all the callbacks are called, we can resolve the promise and remove
// the counter from the service.
--counter->mCount;
if (!counter->mCount) {
service->RemoveCounter(id);
counter->mPromise->MaybeResolve(counter->mResults);
}
return true;
}
RefPtr<Promise> mPromise;
nsTArray<RefPtr<DataStore>> mResults;
uint32_t mId;
uint32_t mCount;
};
/* static */ already_AddRefed<DataStoreService>
DataStoreService::GetOrCreate()
{
MOZ_ASSERT(NS_IsMainThread());
if (!gDataStoreService) {
RefPtr<DataStoreService> service = new DataStoreService();
if (NS_WARN_IF(NS_FAILED(service->Init()))) {
return nullptr;
}
gDataStoreService = service;
}
RefPtr<DataStoreService> service = gDataStoreService.get();
return service.forget();
}
/* static */ already_AddRefed<DataStoreService>
DataStoreService::Get()
{
MOZ_ASSERT(NS_IsMainThread());
RefPtr<DataStoreService> service = gDataStoreService.get();
return service.forget();
}
/* static */ void
DataStoreService::Shutdown()
{
MOZ_ASSERT(NS_IsMainThread());
if (gDataStoreService) {
if (XRE_IsParentProcess()) {
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (obs) {
obs->RemoveObserver(gDataStoreService, "webapps-clear-data");
}
nsresult rv =
Preferences::UnregisterCallback(HomeScreenPrefCallback,
"dom.mozApps.homescreenURL",
nullptr);
NS_WARN_IF(NS_FAILED(rv));
}
gDataStoreService = nullptr;
}
}
NS_INTERFACE_MAP_BEGIN(DataStoreService)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDataStoreService)
NS_INTERFACE_MAP_ENTRY(nsIDataStoreService)
NS_INTERFACE_MAP_ENTRY(nsIObserver)
NS_INTERFACE_MAP_END
NS_IMPL_ADDREF(DataStoreService)
NS_IMPL_RELEASE(DataStoreService)
DataStoreService::DataStoreService()
{
MOZ_ASSERT(NS_IsMainThread());
}
DataStoreService::~DataStoreService()
{
MOZ_ASSERT(NS_IsMainThread());
}
nsresult
DataStoreService::Init()
{
if (!XRE_IsParentProcess()) {
return NS_OK;
}
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (!obs) {
return NS_ERROR_FAILURE;
}
nsresult rv = obs->AddObserver(this, "webapps-clear-data", false);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
rv = Preferences::RegisterCallback(HomeScreenPrefCallback,
"dom.mozApps.homescreenURL",
nullptr);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
NS_IMETHODIMP
DataStoreService::InstallDataStore(uint32_t aAppId,
const nsAString& aName,
const nsAString& aOriginURL,
const nsAString& aManifestURL,
bool aReadOnly)
{
ASSERT_PARENT_PROCESS()
MOZ_ASSERT(NS_IsMainThread());
HashApp* apps = nullptr;
if (!mStores.Get(aName, &apps)) {
apps = new HashApp();
mStores.Put(aName, apps);
}
DataStoreInfo* info = nullptr;
if (!apps->Get(aAppId, &info)) {
info = new DataStoreInfo(aName, aOriginURL, aManifestURL, aReadOnly, false);
apps->Put(aAppId, info);
} else {
info->Update(aName, aOriginURL, aManifestURL, aReadOnly);
}
nsresult rv = AddPermissions(aAppId, aName, aOriginURL, aManifestURL,
aReadOnly);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// Immediately create the first revision.
return CreateFirstRevisionId(aAppId, aName, aManifestURL);
}
NS_IMETHODIMP
DataStoreService::InstallAccessDataStore(uint32_t aAppId,
const nsAString& aName,
const nsAString& aOriginURL,
const nsAString& aManifestURL,
bool aReadOnly)
{
ASSERT_PARENT_PROCESS()
MOZ_ASSERT(NS_IsMainThread());
HashApp* apps = nullptr;
if (!mAccessStores.Get(aName, &apps)) {
apps = new HashApp();
mAccessStores.Put(aName, apps);
}
DataStoreInfo* info = nullptr;
if (!apps->Get(aAppId, &info)) {
info = new DataStoreInfo(aName, aOriginURL, aManifestURL, aReadOnly, false);
apps->Put(aAppId, info);
} else {
info->Update(aName, aOriginURL, aManifestURL, aReadOnly);
}
return AddAccessPermissions(aAppId, aName, aOriginURL, aManifestURL,
aReadOnly);
}
NS_IMETHODIMP
DataStoreService::GetDataStores(nsIDOMWindow* aWindow,
const nsAString& aName,
const nsAString& aOwner,
nsISupports** aDataStores)
{
// FIXME This will be a thread-safe method.
MOZ_ASSERT(NS_IsMainThread());
nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aWindow);
if (!window) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(window);
ErrorResult rv;
RefPtr<Promise> promise = Promise::Create(global, rv);
if (rv.Failed()) {
return rv.StealNSResult();
}
nsCOMPtr<nsIDocument> document = window->GetDoc();
MOZ_ASSERT(document);
nsCOMPtr<nsIPrincipal> principal = document->NodePrincipal();
MOZ_ASSERT(principal);
nsTArray<DataStoreInfo> stores;
// If this request comes from the main process, we have access to the
// window, so we can skip the ipc communication.
if (XRE_IsParentProcess()) {
uint32_t appId;
rv = principal->GetAppId(&appId);
if (NS_WARN_IF(rv.Failed())) {
RejectPromise(window, promise, rv.StealNSResult());
promise.forget(aDataStores);
return NS_OK;
}
rv = GetDataStoreInfos(aName, aOwner, appId, principal, stores);
if (NS_WARN_IF(rv.Failed())) {
RejectPromise(window, promise, rv.StealNSResult());
promise.forget(aDataStores);
return NS_OK;
}
} else {
// This method can be called in the child so we need to send a request
// to the parent and create DataStore object here.
ContentChild* contentChild = ContentChild::GetSingleton();
nsTArray<DataStoreSetting> array;
if (!contentChild->SendDataStoreGetStores(nsAutoString(aName),
nsAutoString(aOwner),
IPC::Principal(principal),
&array)) {
RejectPromise(window, promise, NS_ERROR_FAILURE);
promise.forget(aDataStores);
return NS_OK;
}
for (uint32_t i = 0; i < array.Length(); ++i) {
DataStoreInfo* info = stores.AppendElement();
info->Init(array[i].name(), array[i].originURL(),
array[i].manifestURL(), array[i].readOnly(),
array[i].enabled());
}
}
GetDataStoresCreate(window, promise, stores);
promise.forget(aDataStores);
return NS_OK;
}
void
DataStoreService::GetDataStoresCreate(nsPIDOMWindow* aWindow, Promise* aPromise,
const nsTArray<DataStoreInfo>& aStores)
{
MOZ_ASSERT(NS_IsMainThread());
if (!aStores.Length()) {
GetDataStoresResolve(aWindow, aPromise, aStores);
return;
}
nsTArray<nsString> pendingDataStores;
for (uint32_t i = 0; i < aStores.Length(); ++i) {
if (!aStores[i].mEnabled) {
pendingDataStores.AppendElement(aStores[i].mManifestURL);
}
}
if (!pendingDataStores.Length()) {
GetDataStoresResolve(aWindow, aPromise, aStores);
return;
}
PendingRequests* requests;
if (!mPendingRequests.Get(aStores[0].mName, &requests)) {
requests = new PendingRequests();
mPendingRequests.Put(aStores[0].mName, requests);
}
PendingRequest* request = requests->AppendElement();
request->Init(aWindow, aPromise, aStores, pendingDataStores);
}
void
DataStoreService::GetDataStoresResolve(nsPIDOMWindow* aWindow,
Promise* aPromise,
const nsTArray<DataStoreInfo>& aStores)
{
MOZ_ASSERT(NS_IsMainThread());
if (!aStores.Length()) {
nsTArray<RefPtr<DataStore>> results;
aPromise->MaybeResolve(results);
return;
}
AutoSafeJSContext cx;
// The counter will finish this task once all the DataStores will know their
// first revision Ids.
RefPtr<RetrieveRevisionsCounter> counter =
new RetrieveRevisionsCounter(++gCounterID, aPromise, aStores.Length());
mPendingCounters.Put(gCounterID, counter);
for (uint32_t i = 0; i < aStores.Length(); ++i) {
nsCOMPtr<nsIDataStore> dataStore =
do_CreateInstance("@mozilla.org/dom/datastore;1");
if (NS_WARN_IF(!dataStore)) {
return;
}
nsresult rv = dataStore->Init(aWindow, aStores[i].mName,
aStores[i].mManifestURL,
aStores[i].mReadOnly);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
nsCOMPtr<nsIXPConnectWrappedJS> xpcwrappedjs = do_QueryInterface(dataStore);
if (NS_WARN_IF(!xpcwrappedjs)) {
return;
}
JS::Rooted<JSObject*> dataStoreJS(cx, xpcwrappedjs->GetJSObject());
if (NS_WARN_IF(!dataStoreJS)) {
return;
}
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aWindow);
MOZ_ASSERT(global);
JSAutoCompartment ac(cx, dataStoreJS);
RefPtr<DataStoreImpl> dataStoreObj = new DataStoreImpl(dataStoreJS,
global);
RefPtr<DataStore> exposedStore = new DataStore(aWindow);
ErrorResult error;
exposedStore->SetDataStoreImpl(*dataStoreObj, error);
if (error.Failed()) {
return;
}
JS::Rooted<JS::Value> exposedObject(cx);
if (!GetOrCreateDOMReflector(cx, exposedStore, &exposedObject)) {
JS_ClearPendingException(cx);
return;
}
dataStore->SetExposedObject(exposedObject);
counter->AppendDataStore(cx, exposedStore, dataStore);
}
}
// This method populates 'aStores' with the list of DataStores with 'aName' as
// name and available for this 'aAppId'.
nsresult
DataStoreService::GetDataStoreInfos(const nsAString& aName,
const nsAString& aOwner,
uint32_t aAppId,
nsIPrincipal* aPrincipal,
nsTArray<DataStoreInfo>& aStores)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
nsCOMPtr<nsIAppsService> appsService =
do_GetService("@mozilla.org/AppsService;1");
if (NS_WARN_IF(!appsService)) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<mozIApplication> app;
nsresult rv = appsService->GetAppByLocalId(aAppId, getter_AddRefs(app));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (!app) {
return NS_ERROR_DOM_SECURITY_ERR;
}
if (!DataStoreService::CheckPermission(aPrincipal)) {
return NS_ERROR_DOM_SECURITY_ERR;
}
aStores.Clear();
HashApp* apps = nullptr;
if (!mStores.Get(aName, &apps)) {
return NS_OK;
}
DataStoreInfo* appsInfo = nullptr;
if (apps->Get(aAppId, &appsInfo) &&
(aOwner.IsEmpty() || aOwner.Equals(appsInfo->mManifestURL))) {
DataStoreInfo* owned = aStores.AppendElement();
owned->Init(appsInfo->mName, appsInfo->mOriginURL, appsInfo->mManifestURL,
false, appsInfo->mEnabled);
}
for (auto iter = apps->ConstIter(); !iter.Done(); iter.Next()) {
if (iter.Key() == aAppId) {
continue;
}
DataStoreInfo* appInfo = iter.UserData();
MOZ_ASSERT(appInfo);
HashApp* accessApp;
if (!mAccessStores.Get(aName, &accessApp)) {
continue;
}
if (!aOwner.IsEmpty() &&
!aOwner.Equals(appInfo->mManifestURL)) {
continue;
}
DataStoreInfo* accessInfo = nullptr;
if (!accessApp->Get(aAppId, &accessInfo)) {
continue;
}
bool readOnly = appInfo->mReadOnly || accessInfo->mReadOnly;
DataStoreInfo* accessStore = aStores.AppendElement();
accessStore->Init(aName, appInfo->mOriginURL,
appInfo->mManifestURL, readOnly,
appInfo->mEnabled);
}
return NS_OK;
}
NS_IMETHODIMP
DataStoreService::GetAppManifestURLsForDataStore(const nsAString& aName,
nsIArray** aManifestURLs)
{
ASSERT_PARENT_PROCESS()
MOZ_ASSERT(NS_IsMainThread());
nsCOMPtr<nsIMutableArray> manifestURLs = do_CreateInstance(NS_ARRAY_CONTRACTID);
if (!manifestURLs) {
return NS_ERROR_OUT_OF_MEMORY;
}
HashApp* apps = nullptr;
if (mStores.Get(aName, &apps)) {
for (auto iter = apps->ConstIter(); !iter.Done(); iter.Next()) {
nsCOMPtr<nsISupportsString> manifestURL(do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID));
if (manifestURL) {
manifestURL->SetData(iter.UserData()->mManifestURL);
manifestURLs->AppendElement(manifestURL, false);
}
}
}
if (mAccessStores.Get(aName, &apps)) {
for (auto iter = apps->ConstIter(); !iter.Done(); iter.Next()) {
nsCOMPtr<nsISupportsString> manifestURL(do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID));
if (manifestURL) {
manifestURL->SetData(iter.UserData()->mManifestURL);
manifestURLs->AppendElement(manifestURL, false);
}
}
}
manifestURLs.forget(aManifestURLs);
return NS_OK;
}
bool
DataStoreService::CheckPermission(nsIPrincipal* aPrincipal)
{
// First of all, the general pref has to be turned on.
bool enabled = false;
Preferences::GetBool("dom.datastore.enabled", &enabled);
if (!enabled) {
return false;
}
// Just for testing, we can enable DataStore for any kind of app.
if (Preferences::GetBool("dom.testing.datastore_enabled_for_hosted_apps", false)) {
return true;
}
if (!aPrincipal) {
return false;
}
uint16_t status;
if (NS_FAILED(aPrincipal->GetAppStatus(&status))) {
return false;
}
// Certified apps are always allowed.
if (status == nsIPrincipal::APP_STATUS_CERTIFIED) {
return true;
}
if (status != nsIPrincipal::APP_STATUS_PRIVILEGED) {
return false;
}
// Privileged apps are allowed if they are the homescreen.
nsAdoptingString homescreen =
Preferences::GetString("dom.mozApps.homescreenURL");
if (!homescreen) {
return false;
}
uint32_t appId;
nsresult rv = aPrincipal->GetAppId(&appId);
if (NS_WARN_IF(NS_FAILED(rv))) {
return false;
}
nsCOMPtr<nsIAppsService> appsService =
do_GetService("@mozilla.org/AppsService;1");
if (NS_WARN_IF(!appsService)) {
return false;
}
nsAutoString manifestURL;
rv = appsService->GetManifestURLByLocalId(appId, manifestURL);
if (NS_WARN_IF(NS_FAILED(rv))) {
return false;
}
return manifestURL.Equals(homescreen);
}
NS_IMETHODIMP
DataStoreService::CheckPermission(nsIPrincipal* aPrincipal,
bool* aResult)
{
MOZ_ASSERT(NS_IsMainThread());
*aResult = DataStoreService::CheckPermission(aPrincipal);
return NS_OK;
}
// This method is called when an app with DataStores is deleted.
void
DataStoreService::DeleteDataStores(uint32_t aAppId)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
DeleteDataStoresHelper(mStores, aAppId);
DeleteDataStoresHelper(mAccessStores, aAppId);
}
NS_IMETHODIMP
DataStoreService::Observe(nsISupports* aSubject,
const char* aTopic,
const char16_t* aData)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
if (strcmp(aTopic, "webapps-clear-data")) {
return NS_OK;
}
nsCOMPtr<mozIApplicationClearPrivateDataParams> params =
do_QueryInterface(aSubject);
MOZ_ASSERT(params);
// DataStore is explosed to apps, not browser content.
bool browserOnly;
nsresult rv = params->GetBrowserOnly(&browserOnly);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (browserOnly) {
return NS_OK;
}
uint32_t appId;
rv = params->GetAppId(&appId);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
DeleteDataStores(appId);
return NS_OK;
}
nsresult
DataStoreService::AddPermissions(uint32_t aAppId,
const nsAString& aName,
const nsAString& aOriginURL,
const nsAString& aManifestURL,
bool aReadOnly)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
// This is the permission name.
nsString permission;
GeneratePermissionName(permission, aName, aManifestURL);
// When a new DataStore is installed, the permissions must be set for the
// owner app.
nsresult rv = ResetPermission(aAppId, aOriginURL, aManifestURL, permission,
aReadOnly);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// For any app that wants to have access to this DataStore we add the
// permissions.
HashApp* apps;
if (!mAccessStores.Get(aName, &apps)) {
return NS_OK;
}
for (auto iter = apps->ConstIter(); !iter.Done(); iter.Next()) {
DataStoreInfo* info = iter.UserData();
MOZ_ASSERT(info);
bool readOnly = aReadOnly || info->mReadOnly;
rv = ResetPermission(iter.Key(), info->mOriginURL,
info->mManifestURL,
permission, readOnly);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
return NS_OK;
}
nsresult
DataStoreService::AddAccessPermissions(uint32_t aAppId, const nsAString& aName,
const nsAString& aOriginURL,
const nsAString& aManifestURL,
bool aReadOnly)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
// When an app wants to have access to a DataStore, the permissions must be
// set.
HashApp* apps = nullptr;
if (!mStores.Get(aName, &apps)) {
return NS_OK;
}
for (auto iter = apps->ConstIter(); !iter.Done(); iter.Next()) {
DataStoreInfo* info = iter.UserData();
MOZ_ASSERT(info);
nsAutoString permission;
GeneratePermissionName(permission, aName, info->mManifestURL);
// ReadOnly is decided by the owner first.
bool readOnly = info->mReadOnly || aReadOnly;
nsresult rv = ResetPermission(aAppId, aOriginURL,
info->mManifestURL,
permission, readOnly);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
return NS_OK;
}
// This method starts the operation to create the first revision for a DataStore
// if needed.
nsresult
DataStoreService::CreateFirstRevisionId(uint32_t aAppId,
const nsAString& aName,
const nsAString& aManifestURL)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
RefPtr<DataStoreDB> db = new DataStoreDB(aManifestURL, aName);
RefPtr<FirstRevisionIdCallback> callback =
new FirstRevisionIdCallback(aAppId, aName, aManifestURL);
Sequence<nsString> dbs;
if (!dbs.AppendElement(NS_LITERAL_STRING(DATASTOREDB_REVISION), fallible)) {
return NS_ERROR_OUT_OF_MEMORY;
}
return db->Open(IDBTransactionMode::Readwrite, dbs, callback);
}
nsresult
DataStoreService::EnableDataStore(uint32_t aAppId, const nsAString& aName,
const nsAString& aManifestURL)
{
MOZ_ASSERT(NS_IsMainThread());
{
HashApp* apps = nullptr;
DataStoreInfo* info = nullptr;
if (mStores.Get(aName, &apps) && apps->Get(aAppId, &info)) {
info->Enable();
}
}
// Notify the child processes.
if (XRE_IsParentProcess()) {
nsTArray<ContentParent*> children;
ContentParent::GetAll(children);
for (uint32_t i = 0; i < children.Length(); i++) {
if (children[i]->NeedsDataStoreInfos()) {
Unused << children[i]->SendDataStoreNotify(aAppId, nsAutoString(aName),
nsAutoString(aManifestURL));
}
}
}
// Maybe we have some pending request waiting for this DataStore.
PendingRequests* requests;
if (!mPendingRequests.Get(aName, &requests)) {
return NS_OK;
}
for (uint32_t i = 0; i < requests->Length();) {
PendingRequest& request = requests->ElementAt(i);
nsTArray<nsString>::index_type pos =
request.mPendingDataStores.IndexOf(aManifestURL);
if (pos != request.mPendingDataStores.NoIndex) {
request.mPendingDataStores.RemoveElementAt(pos);
// No other pending dataStores.
if (request.mPendingDataStores.IsEmpty()) {
GetDataStoresResolve(request.mWindow, request.mPromise,
request.mStores);
requests->RemoveElementAt(i);
continue;
}
}
++i;
}
// No other pending requests for this name.
if (requests->IsEmpty()) {
mPendingRequests.Remove(aName);
}
return NS_OK;
}
already_AddRefed<RetrieveRevisionsCounter>
DataStoreService::GetCounter(uint32_t aId) const
{
MOZ_ASSERT(NS_IsMainThread());
RefPtr<RetrieveRevisionsCounter> counter;
return mPendingCounters.Get(aId, getter_AddRefs(counter))
? counter.forget() : nullptr;
}
void
DataStoreService::RemoveCounter(uint32_t aId)
{
MOZ_ASSERT(NS_IsMainThread());
mPendingCounters.Remove(aId);
}
nsresult
DataStoreService::GetDataStoresFromIPC(const nsAString& aName,
const nsAString& aOwner,
nsIPrincipal* aPrincipal,
nsTArray<DataStoreSetting>* aValue)
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
uint32_t appId;
nsresult rv = aPrincipal->GetAppId(&appId);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
nsTArray<DataStoreInfo> stores;
rv = GetDataStoreInfos(aName, aOwner, appId, aPrincipal, stores);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
for (uint32_t i = 0; i < stores.Length(); ++i) {
DataStoreSetting* data = aValue->AppendElement();
data->name() = stores[i].mName;
data->originURL() = stores[i].mOriginURL;
data->manifestURL() = stores[i].mManifestURL;
data->readOnly() = stores[i].mReadOnly;
data->enabled() = stores[i].mEnabled;
}
return NS_OK;
}
nsresult
DataStoreService::GenerateUUID(nsAString& aID)
{
nsresult rv;
if (!mUUIDGenerator) {
mUUIDGenerator = do_GetService("@mozilla.org/uuid-generator;1", &rv);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
nsID id;
rv = mUUIDGenerator->GenerateUUIDInPlace(&id);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
char chars[NSID_LENGTH];
id.ToProvidedString(chars);
CopyASCIItoUTF16(chars, aID);
return NS_OK;
}
void
DataStoreService::HomeScreenPrefChanged()
{
MOZ_ASSERT(XRE_IsParentProcess() && NS_IsMainThread());
nsAdoptingString homescreen =
Preferences::GetString("dom.mozApps.homescreenURL");
if (homescreen == gHomeScreenManifestURL) {
return;
}
// Remove datastores of the old homescreen.
if (!gHomeScreenManifestURL.IsEmpty()) {
DeleteDataStoresIfNotAllowed(gHomeScreenManifestURL);
}
gHomeScreenManifestURL = homescreen;
if (gHomeScreenManifestURL.IsEmpty()) {
return;
}
// Add datastores for the new homescreen.
AddDataStoresIfAllowed(gHomeScreenManifestURL);
}
void
DataStoreService::DeleteDataStoresIfNotAllowed(const nsAString& aManifestURL)
{
nsCOMPtr<nsIAppsService> appsService =
do_GetService("@mozilla.org/AppsService;1");
if (NS_WARN_IF(!appsService)) {
return;
}
nsCOMPtr<mozIApplication> app;
nsresult rv = appsService->GetAppByManifestURL(aManifestURL,
getter_AddRefs(app));
if (NS_WARN_IF(NS_FAILED(rv)) || !app) {
return;
}
uint32_t localId;
rv = app->GetLocalId(&localId);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
nsCOMPtr<nsIPrincipal> principal;
rv = app->GetPrincipal(getter_AddRefs(principal));
// We delete all the dataStores for this app here.
if (NS_WARN_IF(NS_FAILED(rv)) || !principal ||
!CheckPermission(principal)) {
DeleteDataStores(localId);
}
}
void
DataStoreService::AddDataStoresIfAllowed(const nsAString& aManifestURL)
{
nsCOMPtr<nsIAppsService> appsService =
do_GetService("@mozilla.org/AppsService;1");
if (NS_WARN_IF(!appsService)) {
return;
}
nsCOMPtr<mozIApplication> app;
nsresult rv = appsService->GetAppByManifestURL(aManifestURL,
getter_AddRefs(app));
if (NS_WARN_IF(NS_FAILED(rv)) || !app) {
return;
}
uint32_t localId;
rv = app->GetLocalId(&localId);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
rv = appsService->UpdateDataStoreEntriesFromLocalId(localId);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
}
} // namespace dom
} // namespace mozilla