Rename AtomicString to AtomString
[WebKit.git] / Source / WebCore / workers / service / context / ServiceWorkerThread.cpp
1 /*
2  * Copyright (C) 2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
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.
12  *
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.
24  */
25
26 #include "config.h"
27 #include "ServiceWorkerThread.h"
28
29 #if ENABLE(SERVICE_WORKER)
30
31 #include "CacheStorageProvider.h"
32 #include "ContentSecurityPolicyResponseHeaders.h"
33 #include "EventNames.h"
34 #include "ExtendableMessageEvent.h"
35 #include "JSDOMPromise.h"
36 #include "LoaderStrategy.h"
37 #include "PlatformStrategies.h"
38 #include "SWContextManager.h"
39 #include "SecurityOrigin.h"
40 #include "ServiceWorkerFetch.h"
41 #include "ServiceWorkerGlobalScope.h"
42 #include "ServiceWorkerWindowClient.h"
43 #include "WorkerDebuggerProxy.h"
44 #include "WorkerLoaderProxy.h"
45 #include "WorkerObjectProxy.h"
46 #include <JavaScriptCore/IdentifiersFactory.h>
47 #include <JavaScriptCore/RuntimeFlags.h>
48 #include <pal/SessionID.h>
49 #include <wtf/NeverDestroyed.h>
50
51 using namespace PAL;
52
53 namespace WebCore {
54
55 class DummyServiceWorkerThreadProxy : public WorkerObjectProxy {
56 public:
57     static DummyServiceWorkerThreadProxy& shared()
58     {
59         static NeverDestroyed<DummyServiceWorkerThreadProxy> proxy;
60         return proxy;
61     }
62
63 private:
64     void postExceptionToWorkerObject(const String&, int, int, const String&) final { };
65     void workerGlobalScopeDestroyed() final { };
66     void postMessageToWorkerObject(MessageWithMessagePorts&&) final { };
67     void confirmMessageFromWorkerObject(bool) final { };
68     void reportPendingActivity(bool) final { };
69 };
70
71 // FIXME: Use a valid WorkerReportingProxy
72 // FIXME: Use a valid WorkerObjectProxy
73 // FIXME: Use valid runtime flags
74
75 ServiceWorkerThread::ServiceWorkerThread(const ServiceWorkerContextData& data, PAL::SessionID, String&& userAgent, WorkerLoaderProxy& loaderProxy, WorkerDebuggerProxy& debuggerProxy, IDBClient::IDBConnectionProxy* idbConnectionProxy, SocketProvider* socketProvider)
76     : WorkerThread(data.scriptURL, emptyString(), "serviceworker:" + Inspector::IdentifiersFactory::createIdentifier(), WTFMove(userAgent), platformStrategies()->loaderStrategy()->isOnLine(), data.script, loaderProxy, debuggerProxy, DummyServiceWorkerThreadProxy::shared(), WorkerThreadStartMode::Normal, data.contentSecurityPolicy, false, data.registration.key.topOrigin().securityOrigin().get(), MonotonicTime::now(), idbConnectionProxy, socketProvider, JSC::RuntimeFlags::createAllEnabled(), data.sessionID)
77     , m_data(data.isolatedCopy())
78     , m_workerObjectProxy(DummyServiceWorkerThreadProxy::shared())
79 {
80     AtomString::init();
81 }
82
83 ServiceWorkerThread::~ServiceWorkerThread() = default;
84
85 Ref<WorkerGlobalScope> ServiceWorkerThread::createWorkerGlobalScope(const URL& url, Ref<SecurityOrigin>&& origin, const String& name, const String& identifier, const String& userAgent, bool isOnline, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicy, bool shouldBypassMainWorldContentSecurityPolicy, Ref<SecurityOrigin>&& topOrigin, MonotonicTime timeOrigin, PAL::SessionID sessionID)
86 {
87     UNUSED_PARAM(name);
88     return ServiceWorkerGlobalScope::create(m_data, url, WTFMove(origin), identifier, userAgent, isOnline, *this, contentSecurityPolicy, shouldBypassMainWorldContentSecurityPolicy, WTFMove(topOrigin), timeOrigin, idbConnectionProxy(), socketProvider(), sessionID);
89 }
90
91 void ServiceWorkerThread::runEventLoop()
92 {
93     // FIXME: There will be ServiceWorker specific things to do here.
94     WorkerThread::runEventLoop();
95 }
96
97 void ServiceWorkerThread::postFetchTask(Ref<ServiceWorkerFetch::Client>&& client, Optional<ServiceWorkerClientIdentifier>&& clientId, ResourceRequest&& request, String&& referrer, FetchOptions&& options)
98 {
99     // FIXME: instead of directly using runLoop(), we should be using something like WorkerGlobalScopeProxy.
100     // FIXME: request and options come straigth from IPC so are already isolated. We should be able to take benefit of that.
101     runLoop().postTaskForMode([client = WTFMove(client), clientId, request = request.isolatedCopy(), referrer = referrer.isolatedCopy(), options = options.isolatedCopy()] (ScriptExecutionContext& context) mutable {
102         context.postTask([client = WTFMove(client), clientId, request = WTFMove(request), referrer = WTFMove(referrer), options = WTFMove(options)] (ScriptExecutionContext& context) mutable {
103             ServiceWorkerFetch::dispatchFetchEvent(WTFMove(client), downcast<ServiceWorkerGlobalScope>(context), clientId, WTFMove(request), WTFMove(referrer), WTFMove(options));
104         });
105     }, WorkerRunLoop::defaultMode());
106 }
107
108 static void fireMessageEvent(ServiceWorkerGlobalScope& scope, MessageWithMessagePorts&& message, ExtendableMessageEventSource&& source, const URL& sourceURL)
109 {
110     auto ports = MessagePort::entanglePorts(scope, WTFMove(message.transferredPorts));
111     auto messageEvent = ExtendableMessageEvent::create(WTFMove(ports), WTFMove(message.message), SecurityOriginData::fromURL(sourceURL).toString(), { }, source);
112     scope.dispatchEvent(messageEvent);
113     scope.thread().workerObjectProxy().confirmMessageFromWorkerObject(scope.hasPendingActivity());
114     scope.updateExtendedEventsSet(messageEvent.ptr());
115 }
116
117 void ServiceWorkerThread::postMessageToServiceWorker(MessageWithMessagePorts&& message, ServiceWorkerOrClientData&& sourceData)
118 {
119     runLoop().postTask([message = WTFMove(message), sourceData = WTFMove(sourceData)] (auto& context) mutable {
120         auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
121         URL sourceURL;
122         ExtendableMessageEventSource source;
123         if (WTF::holds_alternative<ServiceWorkerClientData>(sourceData)) {
124             RefPtr<ServiceWorkerClient> sourceClient = ServiceWorkerClient::getOrCreate(serviceWorkerGlobalScope, WTFMove(WTF::get<ServiceWorkerClientData>(sourceData)));
125
126             RELEASE_ASSERT(!sourceClient->url().protocolIsInHTTPFamily() || !serviceWorkerGlobalScope.url().protocolIsInHTTPFamily() || protocolHostAndPortAreEqual(serviceWorkerGlobalScope.url(), sourceClient->url()));
127
128             sourceURL = sourceClient->url();
129             source = WTFMove(sourceClient);
130         } else {
131             RefPtr<ServiceWorker> sourceWorker = ServiceWorker::getOrCreate(serviceWorkerGlobalScope, WTFMove(WTF::get<ServiceWorkerData>(sourceData)));
132
133             RELEASE_ASSERT(!sourceWorker->scriptURL().protocolIsInHTTPFamily() || !serviceWorkerGlobalScope.url().protocolIsInHTTPFamily() || protocolHostAndPortAreEqual(serviceWorkerGlobalScope.url(), sourceWorker->scriptURL()));
134
135             sourceURL = sourceWorker->scriptURL();
136             source = WTFMove(sourceWorker);
137         }
138         fireMessageEvent(serviceWorkerGlobalScope, WTFMove(message), ExtendableMessageEventSource { source }, sourceURL);
139     });
140 }
141
142 void ServiceWorkerThread::fireInstallEvent()
143 {
144     ScriptExecutionContext::Task task([jobDataIdentifier = m_data.jobDataIdentifier, serviceWorkerIdentifier = this->identifier()] (ScriptExecutionContext& context) mutable {
145         context.postTask([jobDataIdentifier, serviceWorkerIdentifier](ScriptExecutionContext& context) {
146             auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
147             auto installEvent = ExtendableEvent::create(eventNames().installEvent, { }, ExtendableEvent::IsTrusted::Yes);
148             serviceWorkerGlobalScope.dispatchEvent(installEvent);
149
150             installEvent->whenAllExtendLifetimePromisesAreSettled([jobDataIdentifier, serviceWorkerIdentifier](HashSet<Ref<DOMPromise>>&& extendLifetimePromises) {
151                 bool hasRejectedAnyPromise = false;
152                 for (auto& promise : extendLifetimePromises) {
153                     if (promise->status() == DOMPromise::Status::Rejected) {
154                         hasRejectedAnyPromise = true;
155                         break;
156                     }
157                 }
158                 callOnMainThread([jobDataIdentifier, serviceWorkerIdentifier, hasRejectedAnyPromise] () mutable {
159                     if (auto* connection = SWContextManager::singleton().connection())
160                         connection->didFinishInstall(jobDataIdentifier, serviceWorkerIdentifier, !hasRejectedAnyPromise);
161                 });
162             });
163         });
164     });
165     runLoop().postTask(WTFMove(task));
166 }
167
168 void ServiceWorkerThread::fireActivateEvent()
169 {
170     ScriptExecutionContext::Task task([serviceWorkerIdentifier = this->identifier()] (ScriptExecutionContext& context) mutable {
171         context.postTask([serviceWorkerIdentifier](ScriptExecutionContext& context) {
172             auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
173             auto activateEvent = ExtendableEvent::create(eventNames().activateEvent, { }, ExtendableEvent::IsTrusted::Yes);
174             serviceWorkerGlobalScope.dispatchEvent(activateEvent);
175
176             activateEvent->whenAllExtendLifetimePromisesAreSettled([serviceWorkerIdentifier](HashSet<Ref<DOMPromise>>&&) {
177                 callOnMainThread([serviceWorkerIdentifier] () mutable {
178                     if (auto* connection = SWContextManager::singleton().connection())
179                         connection->didFinishActivation(serviceWorkerIdentifier);
180                 });
181             });
182         });
183     });
184     runLoop().postTask(WTFMove(task));
185 }
186
187 } // namespace WebCore
188
189 #endif // ENABLE(SERVICE_WORKER)