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
, "WorkerCSPEventRunnable"),
26 bool WorkerRun(JSContext
* aCx
, WorkerPrivate
* aWorkerPrivate
) {
27 SecurityPolicyViolationEventInit violationEventInit
;
28 if (NS_WARN_IF(!violationEventInit
.Init(mJSON
))) {
32 RefPtr
<mozilla::dom::Event
> event
=
33 mozilla::dom::SecurityPolicyViolationEvent::Constructor(
34 aWorkerPrivate
->GlobalScope(), u
"securitypolicyviolation"_ns
,
36 event
->SetTrusted(true);
38 aWorkerPrivate
->GlobalScope()->DispatchEvent(*event
);
47 NS_IMPL_ISUPPORTS(WorkerCSPEventListener
, nsICSPEventListener
)
50 already_AddRefed
<WorkerCSPEventListener
> WorkerCSPEventListener::Create(
51 WorkerPrivate
* aWorkerPrivate
) {
52 MOZ_ASSERT(aWorkerPrivate
);
53 aWorkerPrivate
->AssertIsOnWorkerThread();
55 RefPtr
<WorkerCSPEventListener
> listener
= new WorkerCSPEventListener();
57 MutexAutoLock
lock(listener
->mMutex
);
58 listener
->mWorkerRef
= WeakWorkerRef::Create(aWorkerPrivate
, [listener
]() {
59 MutexAutoLock
lock(listener
->mMutex
);
60 listener
->mWorkerRef
= nullptr;
63 if (NS_WARN_IF(!listener
->mWorkerRef
)) {
67 return listener
.forget();
70 WorkerCSPEventListener::WorkerCSPEventListener()
71 : mMutex("WorkerCSPEventListener::mMutex") {}
74 WorkerCSPEventListener::OnCSPViolationEvent(const nsAString
& aJSON
) {
75 MutexAutoLock
lock(mMutex
);
80 WorkerPrivate
* workerPrivate
= mWorkerRef
->GetUnsafePrivate();
81 MOZ_ASSERT(workerPrivate
);
83 if (NS_IsMainThread()) {
84 RefPtr
<WorkerCSPEventRunnable
> runnable
=
85 new WorkerCSPEventRunnable(workerPrivate
, aJSON
);
91 SecurityPolicyViolationEventInit violationEventInit
;
92 if (NS_WARN_IF(!violationEventInit
.Init(aJSON
))) {
93 return NS_ERROR_UNEXPECTED
;
96 RefPtr
<mozilla::dom::Event
> event
=
97 mozilla::dom::SecurityPolicyViolationEvent::Constructor(
98 workerPrivate
->GlobalScope(), u
"securitypolicyviolation"_ns
,
100 event
->SetTrusted(true);
102 workerPrivate
->GlobalScope()->DispatchEvent(*event
);