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