Update Worker::notifyFinished to not use emptySessionID
[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 "Event.h"
32 #include "EventNames.h"
33 #include "InspectorInstrumentation.h"
34 #include "LoaderStrategy.h"
35 #include "PlatformStrategies.h"
36 #include "ResourceResponse.h"
37 #include "SecurityOrigin.h"
38 #include "WorkerGlobalScopeProxy.h"
39 #include "WorkerScriptLoader.h"
40 #include "WorkerThread.h"
41 #include <JavaScriptCore/IdentifiersFactory.h>
42 #include <wtf/HashSet.h>
43 #include <wtf/IsoMallocInlines.h>
44 #include <wtf/MainThread.h>
45 #include <wtf/NeverDestroyed.h>
46 #include <wtf/Scope.h>
47
48 namespace WebCore {
49
50 WTF_MAKE_ISO_ALLOCATED_IMPL(Worker);
51
52 static HashSet<Worker*>& allWorkers()
53 {
54     static NeverDestroyed<HashSet<Worker*>> set;
55     return set;
56 }
57
58 void Worker::networkStateChanged(bool isOnLine)
59 {
60     for (auto* worker : allWorkers())
61         worker->notifyNetworkStateChange(isOnLine);
62 }
63
64 inline Worker::Worker(ScriptExecutionContext& context, JSC::RuntimeFlags runtimeFlags, const Options& options)
65     : ActiveDOMObject(&context)
66     , m_name(options.name)
67     , m_identifier("worker:" + Inspector::IdentifiersFactory::createIdentifier())
68     , m_contextProxy(WorkerGlobalScopeProxy::create(*this))
69     , m_runtimeFlags(runtimeFlags)
70 {
71     static bool addedListener;
72     if (!addedListener) {
73         platformStrategies()->loaderStrategy()->addOnlineStateChangeListener(&networkStateChanged);
74         addedListener = true;
75     }
76
77     auto addResult = allWorkers().add(this);
78     ASSERT_UNUSED(addResult, addResult.isNewEntry);
79 }
80
81 ExceptionOr<Ref<Worker>> Worker::create(ScriptExecutionContext& context, JSC::RuntimeFlags runtimeFlags, const String& url, const Options& options)
82 {
83     ASSERT(isMainThread());
84
85     // We don't currently support nested workers, so workers can only be created from documents.
86     ASSERT_WITH_SECURITY_IMPLICATION(context.isDocument());
87
88     auto worker = adoptRef(*new Worker(context, runtimeFlags, options));
89
90     worker->suspendIfNeeded();
91
92     bool shouldBypassMainWorldContentSecurityPolicy = context.shouldBypassMainWorldContentSecurityPolicy();
93     auto scriptURL = worker->resolveURL(url, shouldBypassMainWorldContentSecurityPolicy);
94     if (scriptURL.hasException())
95         return scriptURL.releaseException();
96
97     worker->m_shouldBypassMainWorldContentSecurityPolicy = shouldBypassMainWorldContentSecurityPolicy;
98
99     // The worker context does not exist while loading, so we must ensure that the worker object is not collected, nor are its event listeners.
100     worker->setPendingActivity(worker.get());
101
102     // https://html.spec.whatwg.org/multipage/workers.html#official-moment-of-creation
103     worker->m_workerCreationTime = MonotonicTime::now();
104
105     worker->m_scriptLoader = WorkerScriptLoader::create();
106     auto contentSecurityPolicyEnforcement = shouldBypassMainWorldContentSecurityPolicy ? ContentSecurityPolicyEnforcement::DoNotEnforce : ContentSecurityPolicyEnforcement::EnforceChildSrcDirective;
107
108     ResourceRequest request { scriptURL.releaseReturnValue() };
109     request.setInitiatorIdentifier(worker->m_identifier);
110
111     FetchOptions fetchOptions;
112     fetchOptions.mode = FetchOptions::Mode::SameOrigin;
113     fetchOptions.cache = FetchOptions::Cache::Default;
114     fetchOptions.redirect = FetchOptions::Redirect::Follow;
115     fetchOptions.destination = FetchOptions::Destination::Worker;
116     worker->m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, worker);
117     return worker;
118 }
119
120 Worker::~Worker()
121 {
122     ASSERT(isMainThread());
123     ASSERT(scriptExecutionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists.
124     allWorkers().remove(this);
125     m_contextProxy.workerObjectDestroyed();
126 }
127
128 ExceptionOr<void> Worker::postMessage(JSC::ExecState& state, JSC::JSValue messageValue, Vector<JSC::Strong<JSC::JSObject>>&& transfer)
129 {
130     Vector<RefPtr<MessagePort>> ports;
131     auto message = SerializedScriptValue::create(state, messageValue, WTFMove(transfer), ports, SerializationContext::WorkerPostMessage);
132     if (message.hasException())
133         return message.releaseException();
134
135     // Disentangle the port in preparation for sending it to the remote context.
136     auto channels = MessagePort::disentanglePorts(WTFMove(ports));
137     if (channels.hasException())
138         return channels.releaseException();
139
140     m_contextProxy.postMessageToWorkerGlobalScope({ message.releaseReturnValue(), channels.releaseReturnValue() });
141     return { };
142 }
143
144 void Worker::terminate()
145 {
146     m_contextProxy.terminateWorkerGlobalScope();
147 }
148
149 bool Worker::canSuspendForDocumentSuspension() const
150 {
151     // FIXME: It is not currently possible to suspend a worker, so pages with workers can not go into page cache.
152     return false;
153 }
154
155 const char* Worker::activeDOMObjectName() const
156 {
157     return "Worker";
158 }
159
160 void Worker::stop()
161 {
162     terminate();
163 }
164
165 bool Worker::hasPendingActivity() const
166 {
167     return m_contextProxy.hasPendingActivity() || ActiveDOMObject::hasPendingActivity();
168 }
169
170 void Worker::notifyNetworkStateChange(bool isOnLine)
171 {
172     m_contextProxy.notifyNetworkStateChange(isOnLine);
173 }
174
175 void Worker::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
176 {
177     const URL& responseURL = response.url();
178     if (!responseURL.protocolIsBlob() && !responseURL.protocolIs("file") && !SecurityOrigin::create(responseURL)->isUnique())
179         m_contentSecurityPolicyResponseHeaders = ContentSecurityPolicyResponseHeaders(response);
180     InspectorInstrumentation::didReceiveScriptResponse(scriptExecutionContext(), identifier);
181 }
182
183 void Worker::notifyFinished()
184 {
185     auto clearLoader = makeScopeExit([this] {
186         m_scriptLoader = nullptr;
187         unsetPendingActivity(*this);
188     });
189
190     auto* context = scriptExecutionContext();
191     if (!context)
192         return;
193
194     if (m_scriptLoader->failed()) {
195         dispatchEvent(Event::create(eventNames().errorEvent, Event::CanBubble::No, Event::IsCancelable::Yes));
196         return;
197     }
198
199     bool isOnline = platformStrategies()->loaderStrategy()->isOnLine();
200     const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders = m_contentSecurityPolicyResponseHeaders ? m_contentSecurityPolicyResponseHeaders.value() : context->contentSecurityPolicy()->responseHeaders();
201     m_contextProxy.startWorkerGlobalScope(m_scriptLoader->url(), m_name, context->userAgent(m_scriptLoader->url()), isOnline, m_scriptLoader->script(), contentSecurityPolicyResponseHeaders, m_shouldBypassMainWorldContentSecurityPolicy, m_workerCreationTime, m_runtimeFlags, context->sessionID());
202     InspectorInstrumentation::scriptImported(*context, m_scriptLoader->identifier(), m_scriptLoader->script());
203 }
204
205 } // namespace WebCore