2 * Copyright (C) 2017 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
27 #include "ServiceWorkerThread.h"
29 #if ENABLE(SERVICE_WORKER)
31 #include "CacheStorageProvider.h"
32 #include "ContentSecurityPolicyResponseHeaders.h"
33 #include "EventNames.h"
34 #include "ExtendableMessageEvent.h"
35 #include "JSDOMPromise.h"
36 #include "SecurityOrigin.h"
37 #include "ServiceWorkerFetch.h"
38 #include "ServiceWorkerGlobalScope.h"
39 #include "ServiceWorkerWindowClient.h"
40 #include "WorkerDebuggerProxy.h"
41 #include "WorkerLoaderProxy.h"
42 #include "WorkerObjectProxy.h"
43 #include <inspector/IdentifiersFactory.h>
44 #include <pal/SessionID.h>
45 #include <runtime/RuntimeFlags.h>
46 #include <wtf/NeverDestroyed.h>
52 class DummyServiceWorkerThreadProxy : public WorkerObjectProxy {
54 static DummyServiceWorkerThreadProxy& shared()
56 static NeverDestroyed<DummyServiceWorkerThreadProxy> proxy;
61 void postExceptionToWorkerObject(const String&, int, int, const String&) final { };
62 void workerGlobalScopeDestroyed() final { };
63 void postMessageToWorkerObject(Ref<SerializedScriptValue>&&, std::unique_ptr<MessagePortChannelArray>&&) final { };
64 void confirmMessageFromWorkerObject(bool) final { };
65 void reportPendingActivity(bool) final { };
68 // FIXME: Use a valid WorkerReportingProxy
69 // FIXME: Use a valid WorkerObjectProxy
70 // FIXME: Use a valid isOnline flag
71 // FIXME: Use valid runtime flags
73 ServiceWorkerThread::ServiceWorkerThread(const ServiceWorkerContextData& data, PAL::SessionID, String&& userAgent, WorkerLoaderProxy& loaderProxy, WorkerDebuggerProxy& debuggerProxy, IDBClient::IDBConnectionProxy* idbConnectionProxy, SocketProvider* socketProvider)
74 : WorkerThread(data.scriptURL, "serviceworker:" + Inspector::IdentifiersFactory::createIdentifier(), WTFMove(userAgent), /* isOnline */ false, data.script, loaderProxy, debuggerProxy, DummyServiceWorkerThreadProxy::shared(), WorkerThreadStartMode::Normal, ContentSecurityPolicyResponseHeaders { }, false, SecurityOrigin::create(data.scriptURL).get(), MonotonicTime::now(), idbConnectionProxy, socketProvider, JSC::RuntimeFlags::createAllEnabled(), SessionID::defaultSessionID())
75 , m_data(data.isolatedCopy())
76 , m_workerObjectProxy(DummyServiceWorkerThreadProxy::shared())
81 ServiceWorkerThread::~ServiceWorkerThread() = default;
83 Ref<WorkerGlobalScope> ServiceWorkerThread::createWorkerGlobalScope(const URL& url, const String& identifier, const String& userAgent, bool isOnline, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, Ref<SecurityOrigin>&& topOrigin, MonotonicTime timeOrigin, PAL::SessionID sessionID)
85 return ServiceWorkerGlobalScope::create(m_data, url, identifier, userAgent, isOnline, *this, shouldBypassMainWorldContentSecurityPolicy, WTFMove(topOrigin), timeOrigin, idbConnectionProxy(), socketProvider(), sessionID);
88 void ServiceWorkerThread::runEventLoop()
90 // FIXME: There will be ServiceWorker specific things to do here.
91 WorkerThread::runEventLoop();
94 void ServiceWorkerThread::postFetchTask(Ref<ServiceWorkerFetch::Client>&& client, std::optional<ServiceWorkerClientIdentifier>&& clientId, ResourceRequest&& request, String&& referrer, FetchOptions&& options)
96 // FIXME: instead of directly using runLoop(), we should be using something like WorkerGlobalScopeProxy.
97 // FIXME: request and options come straigth from IPC so are already isolated. We should be able to take benefit of that.
98 runLoop().postTaskForMode([client = WTFMove(client), clientId, request = request.isolatedCopy(), referrer = referrer.isolatedCopy(), options = options.isolatedCopy()] (ScriptExecutionContext& context) mutable {
99 ServiceWorkerFetch::dispatchFetchEvent(WTFMove(client), downcast<ServiceWorkerGlobalScope>(context), clientId, WTFMove(request), WTFMove(referrer), WTFMove(options));
100 }, WorkerRunLoop::defaultMode());
103 static void fireMessageEvent(ServiceWorkerGlobalScope& scope, Ref<SerializedScriptValue>&& message, std::unique_ptr<MessagePortChannelArray>&& channels, ExtendableMessageEventSource&& source, Ref<SecurityOrigin>&& sourceOrigin)
105 auto ports = MessagePort::entanglePorts(scope, WTFMove(channels));
106 auto messageEvent = ExtendableMessageEvent::create(WTFMove(ports), WTFMove(message), sourceOrigin->toString(), { }, source);
107 scope.dispatchEvent(messageEvent);
108 scope.thread().workerObjectProxy().confirmMessageFromWorkerObject(scope.hasPendingActivity());
109 scope.updateExtendedEventsSet(messageEvent.ptr());
112 void ServiceWorkerThread::postMessageToServiceWorker(Ref<SerializedScriptValue>&& message, std::unique_ptr<MessagePortChannelArray>&& channels, ServiceWorkerOrClientData&& sourceData)
114 runLoop().postTask([channels = WTFMove(channels), message = WTFMove(message), sourceData = WTFMove(sourceData)] (auto& context) mutable {
115 auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
116 RefPtr<SecurityOrigin> sourceOrigin;
117 ExtendableMessageEventSource source;
118 if (WTF::holds_alternative<ServiceWorkerClientData>(sourceData)) {
119 RefPtr<ServiceWorkerClient> sourceClient = ServiceWorkerClient::getOrCreate(serviceWorkerGlobalScope, WTFMove(WTF::get<ServiceWorkerClientData>(sourceData)));
120 sourceOrigin = SecurityOrigin::create(sourceClient->url());
121 source = WTFMove(sourceClient);
123 RefPtr<ServiceWorker> sourceWorker = ServiceWorker::getOrCreate(serviceWorkerGlobalScope, WTFMove(WTF::get<ServiceWorkerData>(sourceData)));
124 sourceOrigin = SecurityOrigin::create(sourceWorker->scriptURL());
125 source = WTFMove(sourceWorker);
127 fireMessageEvent(serviceWorkerGlobalScope, WTFMove(message), WTFMove(channels), ExtendableMessageEventSource { source }, sourceOrigin.releaseNonNull());
131 void ServiceWorkerThread::fireInstallEvent()
133 ScriptExecutionContext::Task task([jobDataIdentifier = m_data.jobDataIdentifier, serviceWorkerIdentifier = this->identifier()] (ScriptExecutionContext& context) mutable {
134 context.postTask([jobDataIdentifier, serviceWorkerIdentifier](ScriptExecutionContext& context) {
135 auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
136 auto installEvent = ExtendableEvent::create(eventNames().installEvent, { }, ExtendableEvent::IsTrusted::Yes);
137 serviceWorkerGlobalScope.dispatchEvent(installEvent);
139 installEvent->whenAllExtendLifetimePromisesAreSettled([jobDataIdentifier, serviceWorkerIdentifier](HashSet<Ref<DOMPromise>>&& extendLifetimePromises) {
140 bool hasRejectedAnyPromise = false;
141 for (auto& promise : extendLifetimePromises) {
142 if (promise->status() == DOMPromise::Status::Rejected) {
143 hasRejectedAnyPromise = true;
147 callOnMainThread([jobDataIdentifier, serviceWorkerIdentifier, hasRejectedAnyPromise] () mutable {
148 if (auto* connection = SWContextManager::singleton().connection())
149 connection->didFinishInstall(jobDataIdentifier, serviceWorkerIdentifier, !hasRejectedAnyPromise);
154 runLoop().postTask(WTFMove(task));
157 void ServiceWorkerThread::fireActivateEvent()
159 ScriptExecutionContext::Task task([serviceWorkerIdentifier = this->identifier()] (ScriptExecutionContext& context) mutable {
160 context.postTask([serviceWorkerIdentifier](ScriptExecutionContext& context) {
161 auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
162 auto activateEvent = ExtendableEvent::create(eventNames().activateEvent, { }, ExtendableEvent::IsTrusted::Yes);
163 serviceWorkerGlobalScope.dispatchEvent(activateEvent);
165 activateEvent->whenAllExtendLifetimePromisesAreSettled([serviceWorkerIdentifier](HashSet<Ref<DOMPromise>>&&) {
166 callOnMainThread([serviceWorkerIdentifier] () mutable {
167 if (auto* connection = SWContextManager::singleton().connection())
168 connection->didFinishActivation(serviceWorkerIdentifier);
173 runLoop().postTask(WTFMove(task));
176 } // namespace WebCore
178 #endif // ENABLE(SERVICE_WORKER)