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