1/*
2 * Copyright (C) 2008-2017 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 *
25 */
26
27#pragma once
28
29#include "Base64Utilities.h"
30#include "CacheStorageConnection.h"
31#include "EventTarget.h"
32#include "ImageBitmap.h"
33#include "ScriptExecutionContext.h"
34#include "Supplementable.h"
35#include <wtf/URL.h>
36#include "WorkerCacheStorageConnection.h"
37#include "WorkerEventQueue.h"
38#include "WorkerScriptController.h"
39#include <JavaScriptCore/ConsoleMessage.h>
40#include <memory>
41#include <pal/SessionID.h>
42
43namespace WebCore {
44
45class ContentSecurityPolicyResponseHeaders;
46class Crypto;
47class MicrotaskQueue;
48class Performance;
49class ScheduledAction;
50class WorkerInspectorController;
51class WorkerLocation;
52class WorkerNavigator;
53class WorkerThread;
54
55namespace IDBClient {
56class IDBConnectionProxy;
57}
58
59class WorkerGlobalScope : public RefCounted<WorkerGlobalScope>, public Supplementable<WorkerGlobalScope>, public ScriptExecutionContext, public EventTargetWithInlineData, public Base64Utilities {
60 WTF_MAKE_ISO_ALLOCATED(WorkerGlobalScope);
61public:
62 virtual ~WorkerGlobalScope();
63
64 virtual bool isDedicatedWorkerGlobalScope() const { return false; }
65 virtual bool isServiceWorkerGlobalScope() const { return false; }
66
67 const URL& url() const final { return m_url; }
68 String origin() const final;
69 const String& identifier() const { return m_identifier; }
70
71#if ENABLE(INDEXED_DATABASE)
72 IDBClient::IDBConnectionProxy* idbConnectionProxy() final;
73#endif
74
75 WorkerCacheStorageConnection& cacheStorageConnection();
76
77 WorkerScriptController* script() { return m_script.get(); }
78 void clearScript() { m_script = nullptr; }
79
80 WorkerInspectorController& inspectorController() const { return *m_inspectorController; }
81
82 MicrotaskQueue& microtaskQueue() const { return *m_microtaskQueue; }
83
84 WorkerThread& thread() const { return m_thread; }
85
86 using ScriptExecutionContext::hasPendingActivity;
87
88 void postTask(Task&&) final; // Executes the task on context's thread asynchronously.
89
90 WorkerGlobalScope& self() { return *this; }
91 WorkerLocation& location() const;
92 void close();
93
94 virtual ExceptionOr<void> importScripts(const Vector<String>& urls);
95 WorkerNavigator& navigator();
96
97 void setIsOnline(bool);
98
99 ExceptionOr<int> setTimeout(JSC::ExecState&, std::unique_ptr<ScheduledAction>, int timeout, Vector<JSC::Strong<JSC::Unknown>>&& arguments);
100 void clearTimeout(int timeoutId);
101 ExceptionOr<int> setInterval(JSC::ExecState&, std::unique_ptr<ScheduledAction>, int timeout, Vector<JSC::Strong<JSC::Unknown>>&& arguments);
102 void clearInterval(int timeoutId);
103
104 bool isContextThread() const final;
105 bool isSecureContext() const final;
106
107 WorkerNavigator* optionalNavigator() const { return m_navigator.get(); }
108 WorkerLocation* optionalLocation() const { return m_location.get(); }
109
110 using RefCounted::ref;
111 using RefCounted::deref;
112
113 bool isClosing() { return m_closing; }
114
115 void addConsoleMessage(std::unique_ptr<Inspector::ConsoleMessage>&&) final;
116
117 Crypto& crypto();
118 Performance& performance() const;
119
120 void prepareForTermination();
121
122 void removeAllEventListeners() final;
123
124 void createImageBitmap(ImageBitmap::Source&&, ImageBitmapOptions&&, ImageBitmap::Promise&&);
125 void createImageBitmap(ImageBitmap::Source&&, int sx, int sy, int sw, int sh, ImageBitmapOptions&&, ImageBitmap::Promise&&);
126
127 unsigned long createUniqueIdentifier() { return m_uniqueIdentifier++; }
128
129protected:
130 WorkerGlobalScope(const URL&, Ref<SecurityOrigin>&&, const String& identifier, const String& userAgent, bool isOnline, WorkerThread&, bool shouldBypassMainWorldContentSecurityPolicy, Ref<SecurityOrigin>&& topOrigin, MonotonicTime timeOrigin, IDBClient::IDBConnectionProxy*, SocketProvider*, PAL::SessionID);
131
132 void applyContentSecurityPolicyResponseHeaders(const ContentSecurityPolicyResponseHeaders&);
133
134private:
135 void refScriptExecutionContext() final { ref(); }
136 void derefScriptExecutionContext() final { deref(); }
137
138 void refEventTarget() final { ref(); }
139 void derefEventTarget() final { deref(); }
140
141 void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&&) final;
142
143 // The following addMessage and addConsoleMessage functions are deprecated.
144 // Callers should try to create the ConsoleMessage themselves.
145 void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber, RefPtr<Inspector::ScriptCallStack>&&, JSC::ExecState*, unsigned long requestIdentifier) final;
146 void addConsoleMessage(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier) final;
147
148 bool isWorkerGlobalScope() const final { return true; }
149
150 ScriptExecutionContext* scriptExecutionContext() const final { return const_cast<WorkerGlobalScope*>(this); }
151 URL completeURL(const String&) const final;
152 PAL::SessionID sessionID() const final { return m_sessionID; }
153 String userAgent(const URL&) const final;
154 void disableEval(const String& errorMessage) final;
155 void disableWebAssembly(const String& errorMessage) final;
156 EventTarget* errorEventTarget() final;
157 WorkerEventQueue& eventQueue() const final;
158 String resourceRequestIdentifier() const final { return m_identifier; }
159 SocketProvider* socketProvider() final;
160
161 bool shouldBypassMainWorldContentSecurityPolicy() const final { return m_shouldBypassMainWorldContentSecurityPolicy; }
162 bool isJSExecutionForbidden() const final;
163 SecurityOrigin& topOrigin() const final { return m_topOrigin.get(); }
164
165#if ENABLE(WEB_CRYPTO)
166 // The following two functions are side effects of providing extra protection to serialized
167 // CryptoKey data that went through the structured clone algorithm to local storage such as
168 // IndexedDB. They don't provide any proctection against communications between mainThread
169 // and workerThreads. In fact, they cause extra expense as workerThreads cannot talk to clients
170 // to unwrap/wrap crypto keys. Hence, workerThreads must always ask mainThread to unwrap/wrap
171 // keys, which results in a second communication and plain keys being transferred between
172 // workerThreads and the mainThread.
173 bool wrapCryptoKey(const Vector<uint8_t>& key, Vector<uint8_t>& wrappedKey) final;
174 bool unwrapCryptoKey(const Vector<uint8_t>& wrappedKey, Vector<uint8_t>& key) final;
175#endif
176
177#if ENABLE(INDEXED_DATABASE)
178 void stopIndexedDatabase();
179#endif
180
181 URL m_url;
182 String m_identifier;
183 String m_userAgent;
184
185 mutable RefPtr<WorkerLocation> m_location;
186 mutable RefPtr<WorkerNavigator> m_navigator;
187
188 WorkerThread& m_thread;
189 std::unique_ptr<WorkerScriptController> m_script;
190 std::unique_ptr<WorkerInspectorController> m_inspectorController;
191 std::unique_ptr<MicrotaskQueue> m_microtaskQueue;
192
193 bool m_closing { false };
194 bool m_isOnline;
195 bool m_shouldBypassMainWorldContentSecurityPolicy;
196
197 mutable WorkerEventQueue m_eventQueue;
198
199 Ref<SecurityOrigin> m_topOrigin;
200
201#if ENABLE(INDEXED_DATABASE)
202 RefPtr<IDBClient::IDBConnectionProxy> m_connectionProxy;
203#endif
204
205 RefPtr<SocketProvider> m_socketProvider;
206
207 RefPtr<Performance> m_performance;
208 mutable RefPtr<Crypto> m_crypto;
209
210 PAL::SessionID m_sessionID;
211 RefPtr<WorkerCacheStorageConnection> m_cacheStorageConnection;
212
213 unsigned long m_uniqueIdentifier { 1 };
214};
215
216} // namespace WebCore
217
218SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::WorkerGlobalScope)
219 static bool isType(const WebCore::ScriptExecutionContext& context) { return context.isWorkerGlobalScope(); }
220SPECIALIZE_TYPE_TRAITS_END()
221