ebec894316683a4596c192840368a644c5d40ecc
[WebKit-https.git] / Source / WebCore / workers / Worker.cpp
1 /*
2  * Copyright (C) 2008-2017 Apple Inc. All rights reserved.
3  * Copyright (C) 2009 Google Inc. All Rights Reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
25  */
26
27 #include "config.h"
28 #include "Worker.h"
29
30 #include "ContentSecurityPolicy.h"
31 #include "ErrorEvent.h"
32 #include "Event.h"
33 #include "EventNames.h"
34 #include "InspectorInstrumentation.h"
35 #include "LoaderStrategy.h"
36 #include "PlatformStrategies.h"
37 #include "ResourceResponse.h"
38 #include "SecurityOrigin.h"
39 #include "WorkerGlobalScopeProxy.h"
40 #include "WorkerScriptLoader.h"
41 #include "WorkerThread.h"
42 #include <JavaScriptCore/IdentifiersFactory.h>
43 #include <wtf/HashSet.h>
44 #include <wtf/IsoMallocInlines.h>
45 #include <wtf/MainThread.h>
46 #include <wtf/NeverDestroyed.h>
47 #include <wtf/Scope.h>
48
49 namespace WebCore {
50
51 WTF_MAKE_ISO_ALLOCATED_IMPL(Worker);
52
53 static HashSet<Worker*>& allWorkers()
54 {
55     static NeverDestroyed<HashSet<Worker*>> set;
56     return set;
57 }
58
59 void Worker::networkStateChanged(bool isOnLine)
60 {
61     for (auto* worker : allWorkers())
62         worker->notifyNetworkStateChange(isOnLine);
63 }
64
65 inline Worker::Worker(ScriptExecutionContext& context, JSC::RuntimeFlags runtimeFlags, const Options& options)
66     : ActiveDOMObject(&context)
67     , m_name(options.name)
68     , m_identifier("worker:" + Inspector::IdentifiersFactory::createIdentifier())
69     , m_contextProxy(WorkerGlobalScopeProxy::create(*this))
70     , m_runtimeFlags(runtimeFlags)
71     , m_eventQueue(GenericEventQueue::create(*this))
72 {
73     static bool addedListener;
74     if (!addedListener) {
75         platformStrategies()->loaderStrategy()->addOnlineStateChangeListener(&networkStateChanged);
76         addedListener = true;
77     }
78
79     auto addResult = allWorkers().add(this);
80     ASSERT_UNUSED(addResult, addResult.isNewEntry);
81 }
82
83 ExceptionOr<Ref<Worker>> Worker::create(ScriptExecutionContext& context, JSC::RuntimeFlags runtimeFlags, const String& url, const Options& options)
84 {
85     ASSERT(isMainThread());
86
87     // We don't currently support nested workers, so workers can only be created from documents.
88     ASSERT_WITH_SECURITY_IMPLICATION(context.isDocument());
89
90     auto worker = adoptRef(*new Worker(context, runtimeFlags, options));
91
92     worker->suspendIfNeeded();
93
94     bool shouldBypassMainWorldContentSecurityPolicy = context.shouldBypassMainWorldContentSecurityPolicy();
95     auto scriptURL = worker->resolveURL(url, shouldBypassMainWorldContentSecurityPolicy);
96     if (scriptURL.hasException())
97         return scriptURL.releaseException();
98
99     worker->m_shouldBypassMainWorldContentSecurityPolicy = shouldBypassMainWorldContentSecurityPolicy;
100
101     // The worker context does not exist while loading, so we must ensure that the worker object is not collected, nor are its event listeners.
102     worker->setPendingActivity(worker.get());
103
104     // https://html.spec.whatwg.org/multipage/workers.html#official-moment-of-creation
105     worker->m_workerCreationTime = MonotonicTime::now();
106
107     worker->m_scriptLoader = WorkerScriptLoader::create();
108     auto contentSecurityPolicyEnforcement = shouldBypassMainWorldContentSecurityPolicy ? ContentSecurityPolicyEnforcement::DoNotEnforce : ContentSecurityPolicyEnforcement::EnforceChildSrcDirective;
109
110     ResourceRequest request { scriptURL.releaseReturnValue() };
111     request.setInitiatorIdentifier(worker->m_identifier);
112
113     FetchOptions fetchOptions;
114     fetchOptions.mode = FetchOptions::Mode::SameOrigin;
115     fetchOptions.cache = FetchOptions::Cache::Default;
116     fetchOptions.redirect = FetchOptions::Redirect::Follow;
117     fetchOptions.destination = FetchOptions::Destination::Worker;
118     worker->m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, worker);
119     return worker;
120 }
121
122 Worker::~Worker()
123 {
124     ASSERT(isMainThread());
125     ASSERT(scriptExecutionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists.
126     allWorkers().remove(this);
127     m_contextProxy.workerObjectDestroyed();
128 }
129
130 ExceptionOr<void> Worker::postMessage(JSC::ExecState& state, JSC::JSValue messageValue, Vector<JSC::Strong<JSC::JSObject>>&& transfer)
131 {
132     Vector<RefPtr<MessagePort>> ports;
133     auto message = SerializedScriptValue::create(state, messageValue, WTFMove(transfer), ports, SerializationContext::WorkerPostMessage);
134     if (message.hasException())
135         return message.releaseException();
136
137     // Disentangle the port in preparation for sending it to the remote context.
138     auto channels = MessagePort::disentanglePorts(WTFMove(ports));
139     if (channels.hasException())
140         return channels.releaseException();
141
142     m_contextProxy.postMessageToWorkerGlobalScope({ message.releaseReturnValue(), channels.releaseReturnValue() });
143     return { };
144 }
145
146 void Worker::terminate()
147 {
148     m_contextProxy.terminateWorkerGlobalScope();
149     m_eventQueue->cancelAllEvents();
150 }
151
152 bool Worker::canSuspendForDocumentSuspension() const
153 {
154     return true;
155 }
156
157 const char* Worker::activeDOMObjectName() const
158 {
159     return "Worker";
160 }
161
162 void Worker::stop()
163 {
164     terminate();
165 }
166
167 bool Worker::hasPendingActivity() const
168 {
169     return m_contextProxy.hasPendingActivity() || ActiveDOMObject::hasPendingActivity() || m_eventQueue->hasPendingEvents();
170 }
171
172 void Worker::notifyNetworkStateChange(bool isOnLine)
173 {
174     m_contextProxy.notifyNetworkStateChange(isOnLine);
175 }
176
177 void Worker::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
178 {
179     const URL& responseURL = response.url();
180     if (!responseURL.protocolIsBlob() && !responseURL.protocolIs("file") && !SecurityOrigin::create(responseURL)->isUnique())
181         m_contentSecurityPolicyResponseHeaders = ContentSecurityPolicyResponseHeaders(response);
182     InspectorInstrumentation::didReceiveScriptResponse(scriptExecutionContext(), identifier);
183 }
184
185 void Worker::notifyFinished()
186 {
187     auto clearLoader = makeScopeExit([this] {
188         m_scriptLoader = nullptr;
189         unsetPendingActivity(*this);
190     });
191
192     auto* context = scriptExecutionContext();
193     if (!context)
194         return;
195
196     if (m_scriptLoader->failed()) {
197         enqueueEvent(Event::create(eventNames().errorEvent, Event::CanBubble::No, Event::IsCancelable::Yes));
198         return;
199     }
200
201     bool isOnline = platformStrategies()->loaderStrategy()->isOnLine();
202     const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders = m_contentSecurityPolicyResponseHeaders ? m_contentSecurityPolicyResponseHeaders.value() : context->contentSecurityPolicy()->responseHeaders();
203     m_contextProxy.startWorkerGlobalScope(m_scriptLoader->url(), m_name, context->userAgent(m_scriptLoader->url()), isOnline, m_scriptLoader->script(), contentSecurityPolicyResponseHeaders, m_shouldBypassMainWorldContentSecurityPolicy, m_workerCreationTime, m_runtimeFlags);
204     InspectorInstrumentation::scriptImported(*context, m_scriptLoader->identifier(), m_scriptLoader->script());
205 }
206
207 void Worker::enqueueEvent(Ref<Event>&& event)
208 {
209     m_eventQueue->enqueueEvent(WTFMove(event));
210 }
211
212 void Worker::dispatchEvent(Event& event)
213 {
214     RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(!m_eventQueue->isSuspended());
215
216     AbstractWorker::dispatchEvent(event);
217     if (is<ErrorEvent>(event) && !event.defaultPrevented() && event.isTrusted() && scriptExecutionContext()) {
218         auto& errorEvent = downcast<ErrorEvent>(event);
219         scriptExecutionContext()->reportException(errorEvent.message(), errorEvent.lineno(), errorEvent.colno(), errorEvent.filename(), nullptr, nullptr);
220     }
221 }
222
223 } // namespace WebCore