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 "WorkerCSPEventListener.h"
9 #include "WorkerRunnable.h"
10 #include "WorkerScope.h"
11 #include "mozilla/dom/SecurityPolicyViolationEvent.h"
12 #include "mozilla/dom/SecurityPolicyViolationEventBinding.h"
13 #include "mozilla/dom/WorkerRunnable.h"
15 using namespace mozilla::dom
;
19 class WorkerCSPEventRunnable final
: public MainThreadWorkerRunnable
{
21 WorkerCSPEventRunnable(WorkerPrivate
* aWorkerPrivate
, const nsAString
& aJSON
)
22 : MainThreadWorkerRunnable(aWorkerPrivate
), mJSON(aJSON
) {}
25 bool WorkerRun(JSContext
* aCx
, WorkerPrivate
* aWorkerPrivate
) {
26 SecurityPolicyViolationEventInit violationEventInit
;
27 if (NS_WARN_IF(!violationEventInit
.Init(mJSON
))) {
31 RefPtr
<mozilla::dom::Event
> event
=
32 mozilla::dom::SecurityPolicyViolationEvent::Constructor(
33 aWorkerPrivate
->GlobalScope(), u
"securitypolicyviolation"_ns
,
35 event
->SetTrusted(true);
37 aWorkerPrivate
->GlobalScope()->DispatchEvent(*event
);
46 NS_IMPL_ISUPPORTS(WorkerCSPEventListener
, nsICSPEventListener
)
49 already_AddRefed
<WorkerCSPEventListener
> WorkerCSPEventListener::Create(
50 WorkerPrivate
* aWorkerPrivate
) {
51 MOZ_ASSERT(aWorkerPrivate
);
52 aWorkerPrivate
->AssertIsOnWorkerThread();
54 RefPtr
<WorkerCSPEventListener
> listener
= new WorkerCSPEventListener();
56 MutexAutoLock
lock(listener
->mMutex
);
57 listener
->mWorkerRef
= WeakWorkerRef::Create(aWorkerPrivate
, [listener
]() {
58 MutexAutoLock
lock(listener
->mMutex
);
59 listener
->mWorkerRef
= nullptr;
62 if (NS_WARN_IF(!listener
->mWorkerRef
)) {
66 return listener
.forget();
69 WorkerCSPEventListener::WorkerCSPEventListener()
70 : mMutex("WorkerCSPEventListener::mMutex") {}
73 WorkerCSPEventListener::OnCSPViolationEvent(const nsAString
& aJSON
) {
74 MutexAutoLock
lock(mMutex
);
79 WorkerPrivate
* workerPrivate
= mWorkerRef
->GetUnsafePrivate();
80 MOZ_ASSERT(workerPrivate
);
82 if (NS_IsMainThread()) {
83 RefPtr
<WorkerCSPEventRunnable
> runnable
=
84 new WorkerCSPEventRunnable(workerPrivate
, aJSON
);
90 SecurityPolicyViolationEventInit violationEventInit
;
91 if (NS_WARN_IF(!violationEventInit
.Init(aJSON
))) {
92 return NS_ERROR_UNEXPECTED
;
95 RefPtr
<mozilla::dom::Event
> event
=
96 mozilla::dom::SecurityPolicyViolationEvent::Constructor(
97 workerPrivate
->GlobalScope(), u
"securitypolicyviolation"_ns
,
99 event
->SetTrusted(true);
101 workerPrivate
->GlobalScope()->DispatchEvent(*event
);