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 file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "TemporaryAccessGrantObserver.h"
9 #include "mozilla/PermissionManager.h"
10 #include "mozilla/Services.h"
11 #include "nsIObserverService.h"
12 #include "nsTHashtable.h"
13 #include "nsXULAppAPI.h"
15 using namespace mozilla
;
17 StaticAutoPtr
<TemporaryAccessGrantObserver::ObserversTable
>
18 TemporaryAccessGrantObserver::sObservers
;
20 TemporaryAccessGrantObserver::TemporaryAccessGrantObserver(
21 PermissionManager
* aPM
, nsIPrincipal
* aPrincipal
, const nsACString
& aType
)
22 : mPM(aPM
), mPrincipal(aPrincipal
), mType(aType
) {
23 MOZ_ASSERT(XRE_IsParentProcess(),
24 "Enforcing temporary access grant lifetimes can only be done in "
25 "the parent process");
28 NS_IMPL_ISUPPORTS(TemporaryAccessGrantObserver
, nsIObserver
, nsINamed
)
31 void TemporaryAccessGrantObserver::Create(PermissionManager
* aPM
,
32 nsIPrincipal
* aPrincipal
,
33 const nsACString
& aType
) {
34 MOZ_ASSERT(XRE_IsParentProcess());
37 sObservers
= new ObserversTable();
39 sObservers
->LookupOrInsertWith(
40 std::make_pair(nsCOMPtr
<nsIPrincipal
>(aPrincipal
), nsCString(aType
)),
41 [&]() -> nsCOMPtr
<nsITimer
> {
42 // Only create a new observer if we don't have a matching
43 // entry in our hashtable.
44 nsCOMPtr
<nsITimer
> timer
;
45 RefPtr
<TemporaryAccessGrantObserver
> observer
=
46 new TemporaryAccessGrantObserver(aPM
, aPrincipal
, aType
);
47 nsresult rv
= NS_NewTimerWithObserver(getter_AddRefs(timer
), observer
,
48 24 * 60 * 60 * 1000, // 24 hours
49 nsITimer::TYPE_ONE_SHOT
);
51 if (NS_SUCCEEDED(rv
)) {
52 observer
->SetTimer(timer
);
60 void TemporaryAccessGrantObserver::SetTimer(nsITimer
* aTimer
) {
62 nsCOMPtr
<nsIObserverService
> observerService
=
63 mozilla::services::GetObserverService();
64 if (observerService
) {
65 observerService
->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID
, false);
70 TemporaryAccessGrantObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
71 const char16_t
* aData
) {
72 if (strcmp(aTopic
, NS_TIMER_CALLBACK_TOPIC
) == 0) {
73 Unused
<< mPM
->RemoveFromPrincipal(mPrincipal
, mType
);
75 MOZ_ASSERT(sObservers
);
76 sObservers
->Remove(std::make_pair(mPrincipal
, mType
));
77 } else if (strcmp(aTopic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
) == 0) {
78 nsCOMPtr
<nsIObserverService
> observerService
=
79 mozilla::services::GetObserverService();
80 if (observerService
) {
81 observerService
->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID
);
94 TemporaryAccessGrantObserver::GetName(nsACString
& aName
) {
95 aName
.AssignLiteral("TemporaryAccessGrantObserver");