CSP: Implement child-src directive
[WebKit-https.git] / Source / WebCore / workers / Worker.cpp
1 /*
2  * Copyright (C) 2008, 2010 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
28 #include "config.h"
29
30 #include "Worker.h"
31
32 #include "DOMWindow.h"
33 #include "CachedResourceLoader.h"
34 #include "ContentSecurityPolicy.h"
35 #include "Document.h"
36 #include "EventListener.h"
37 #include "EventNames.h"
38 #include "ExceptionCode.h"
39 #include "Frame.h"
40 #include "FrameLoader.h"
41 #include "InspectorInstrumentation.h"
42 #include "MessageEvent.h"
43 #include "NetworkStateNotifier.h"
44 #include "SecurityOrigin.h"
45 #include "TextEncoding.h"
46 #include "WorkerGlobalScopeProxy.h"
47 #include "WorkerScriptLoader.h"
48 #include "WorkerThread.h"
49 #include <wtf/HashSet.h>
50 #include <wtf/MainThread.h>
51
52 namespace WebCore {
53
54 static HashSet<Worker*>* allWorkers;
55
56 void networkStateChanged(bool isOnLine)
57 {
58     for (auto& worker : *allWorkers)
59         worker->notifyNetworkStateChange(isOnLine);
60 }
61
62 inline Worker::Worker(ScriptExecutionContext& context)
63     : ActiveDOMObject(&context)
64     , m_contextProxy(WorkerGlobalScopeProxy::create(this))
65 {
66     if (!allWorkers) {
67         allWorkers = new HashSet<Worker*>;
68         networkStateNotifier().addNetworkStateChangeListener(networkStateChanged);
69     }
70
71     HashSet<Worker*>::AddResult addResult = allWorkers->add(this);
72     ASSERT_UNUSED(addResult, addResult.isNewEntry);
73 }
74
75 RefPtr<Worker> Worker::create(ScriptExecutionContext& context, const String& url, ExceptionCode& ec)
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     Ref<Worker> worker = adoptRef(*new Worker(context));
83
84     worker->suspendIfNeeded();
85
86     bool shouldBypassMainWorldContentSecurityPolicy = context.shouldBypassMainWorldContentSecurityPolicy();
87     URL scriptURL = worker->resolveURL(url, shouldBypassMainWorldContentSecurityPolicy, ec);
88     if (scriptURL.isEmpty())
89         return nullptr;
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     worker->m_scriptLoader = WorkerScriptLoader::create();
97     auto contentSecurityPolicyEnforcement = shouldBypassMainWorldContentSecurityPolicy ? ContentSecurityPolicyEnforcement::DoNotEnforce : ContentSecurityPolicyEnforcement::EnforceChildSrcDirective;
98     worker->m_scriptLoader->loadAsynchronously(&context, scriptURL, DenyCrossOriginRequests, contentSecurityPolicyEnforcement, worker.ptr());
99     return WTFMove(worker);
100 }
101
102 Worker::~Worker()
103 {
104     ASSERT(isMainThread());
105     ASSERT(scriptExecutionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists.
106     allWorkers->remove(this);
107     m_contextProxy->workerObjectDestroyed();
108 }
109
110 void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, MessagePort* port, ExceptionCode& ec)
111 {
112     MessagePortArray ports;
113     if (port)
114         ports.append(port);
115     postMessage(message, &ports, ec);
116 }
117
118 void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionCode& ec)
119 {
120     // Disentangle the port in preparation for sending it to the remote context.
121     std::unique_ptr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, ec);
122     if (ec)
123         return;
124     m_contextProxy->postMessageToWorkerGlobalScope(message, WTFMove(channels));
125 }
126
127 void Worker::terminate()
128 {
129     m_contextProxy->terminateWorkerGlobalScope();
130 }
131
132 bool Worker::canSuspendForDocumentSuspension() const
133 {
134     // FIXME: It is not currently possible to suspend a worker, so pages with workers can not go into page cache.
135     return false;
136 }
137
138 const char* Worker::activeDOMObjectName() const
139 {
140     return "Worker";
141 }
142
143 void Worker::stop()
144 {
145     terminate();
146 }
147
148 bool Worker::hasPendingActivity() const
149 {
150     return m_contextProxy->hasPendingActivity() || ActiveDOMObject::hasPendingActivity();
151 }
152
153 void Worker::notifyNetworkStateChange(bool isOnLine)
154 {
155     m_contextProxy->notifyNetworkStateChange(isOnLine);
156 }
157
158 void Worker::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
159 {
160     const URL& responseURL = response.url();
161     if (!responseURL.protocolIs("blob") && !responseURL.protocolIs("file") && !SecurityOrigin::create(responseURL)->isUnique())
162         m_contentSecurityPolicyResponseHeaders = ContentSecurityPolicyResponseHeaders(response);
163     InspectorInstrumentation::didReceiveScriptResponse(scriptExecutionContext(), identifier);
164 }
165
166 void Worker::notifyFinished()
167 {
168     if (m_scriptLoader->failed())
169         dispatchEvent(Event::create(eventNames().errorEvent, false, true));
170     else {
171         const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders = m_contentSecurityPolicyResponseHeaders ? m_contentSecurityPolicyResponseHeaders.value() : scriptExecutionContext()->contentSecurityPolicy()->responseHeaders();
172         m_contextProxy->startWorkerGlobalScope(m_scriptLoader->url(), scriptExecutionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), contentSecurityPolicyResponseHeaders, m_shouldBypassMainWorldContentSecurityPolicy, DontPauseWorkerGlobalScopeOnStart);
173         InspectorInstrumentation::scriptImported(scriptExecutionContext(), m_scriptLoader->identifier(), m_scriptLoader->script());
174     }
175     m_scriptLoader = nullptr;
176
177     unsetPendingActivity(this);
178 }
179
180 } // namespace WebCore