2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "web/WebSharedWorkerImpl.h"
34 #include "RuntimeEnabledFeatures.h"
35 #include "core/dom/CrossThreadTask.h"
36 #include "core/dom/Document.h"
37 #include "core/events/MessageEvent.h"
38 #include "core/html/HTMLFormElement.h"
39 #include "core/inspector/InspectorInstrumentation.h"
40 #include "core/inspector/WorkerDebuggerAgent.h"
41 #include "core/inspector/WorkerInspectorController.h"
42 #include "core/loader/FrameLoadRequest.h"
43 #include "core/loader/FrameLoader.h"
44 #include "core/page/Page.h"
45 #include "core/workers/SharedWorkerGlobalScope.h"
46 #include "core/workers/SharedWorkerThread.h"
47 #include "core/workers/WorkerClients.h"
48 #include "core/workers/WorkerGlobalScope.h"
49 #include "core/workers/WorkerScriptLoader.h"
50 #include "core/workers/WorkerThreadStartupData.h"
51 #include "modules/webdatabase/DatabaseTask.h"
52 #include "platform/heap/Handle.h"
53 #include "platform/network/ContentSecurityPolicyParsers.h"
54 #include "platform/network/ResourceResponse.h"
55 #include "platform/weborigin/KURL.h"
56 #include "platform/weborigin/SecurityOrigin.h"
57 #include "public/platform/WebFileError.h"
58 #include "public/platform/WebMessagePortChannel.h"
59 #include "public/platform/WebString.h"
60 #include "public/platform/WebURL.h"
61 #include "public/web/WebFrame.h"
62 #include "public/web/WebSettings.h"
63 #include "public/web/WebView.h"
64 #include "public/web/WebWorkerPermissionClientProxy.h"
65 #include "web/DatabaseClientImpl.h"
66 #include "web/LocalFileSystemClient.h"
67 #include "web/WebDataSourceImpl.h"
68 #include "web/WebLocalFrameImpl.h"
69 #include "web/WorkerPermissionClient.h"
70 #include "wtf/Functional.h"
71 #include "wtf/MainThread.h"
73 using namespace WebCore;
77 // A thin wrapper for one-off script loading.
78 class WebSharedWorkerImpl::Loader : public WorkerScriptLoaderClient {
80 static PassOwnPtr<Loader> create()
82 return adoptPtr(new Loader());
87 m_scriptLoader->setClient(0);
90 void load(ExecutionContext* loadingContext, const KURL& scriptURL, const Closure& receiveResponseCallback, const Closure& finishCallback)
92 ASSERT(loadingContext);
93 m_receiveResponseCallback = receiveResponseCallback;
94 m_finishCallback = finishCallback;
95 m_scriptLoader->setTargetType(ResourceRequest::TargetIsSharedWorker);
96 m_scriptLoader->loadAsynchronously(
97 *loadingContext, scriptURL, DenyCrossOriginRequests, this);
100 void didReceiveResponse(unsigned long identifier, const ResourceResponse& response) OVERRIDE
102 m_identifier = identifier;
103 m_appCacheID = response.appCacheID();
104 m_receiveResponseCallback();
107 virtual void notifyFinished() OVERRIDE
114 m_scriptLoader->cancel();
117 bool failed() const { return m_scriptLoader->failed(); }
118 const KURL& url() const { return m_scriptLoader->responseURL(); }
119 String script() const { return m_scriptLoader->script(); }
120 unsigned long identifier() const { return m_identifier; }
121 long long appCacheID() const { return m_appCacheID; }
124 Loader() : m_scriptLoader(WorkerScriptLoader::create()), m_identifier(0), m_appCacheID(0)
128 RefPtr<WorkerScriptLoader> m_scriptLoader;
129 unsigned long m_identifier;
130 long long m_appCacheID;
131 Closure m_receiveResponseCallback;
132 Closure m_finishCallback;
135 // This function is called on the main thread to force to initialize some static
136 // values used in WebKit before any worker thread is started. This is because in
137 // our worker processs, we do not run any WebKit code in main thread and thus
138 // when multiple workers try to start at the same time, we might hit crash due
139 // to contention for initializing static values.
140 static void initializeWebKitStaticValues()
142 static bool initialized = false;
145 // Note that we have to pass a URL with valid protocol in order to follow
146 // the path to do static value initializations.
147 RefPtr<SecurityOrigin> origin =
148 SecurityOrigin::create(KURL(ParsedURLString, "http://localhost"));
153 WebSharedWorkerImpl::WebSharedWorkerImpl(WebSharedWorkerClient* client)
156 , m_askedToTerminate(false)
157 , m_client(WeakReference<WebSharedWorkerClient>::create(client))
158 , m_clientWeakPtr(WeakPtr<WebSharedWorkerClient>(m_client))
159 , m_pauseWorkerContextOnStart(false)
160 , m_attachDevToolsOnStart(false)
162 initializeWebKitStaticValues();
165 WebSharedWorkerImpl::~WebSharedWorkerImpl()
168 // Detach the client before closing the view to avoid getting called back.
169 toWebLocalFrameImpl(m_mainFrame)->setClient(0);
172 m_mainFrame->close();
175 void WebSharedWorkerImpl::stopWorkerThread()
177 if (m_askedToTerminate)
179 m_askedToTerminate = true;
180 if (m_mainScriptLoader)
181 m_mainScriptLoader->cancel();
183 m_workerThread->stop();
186 void WebSharedWorkerImpl::initializeLoader(const WebURL& url)
188 // Create 'shadow page'. This page is never displayed, it is used to proxy the
189 // loading requests from the worker context to the rest of WebKit and Chromium
192 m_webView = WebView::create(0);
193 m_webView->settings()->setOfflineWebApplicationCacheEnabled(RuntimeEnabledFeatures::applicationCacheEnabled());
194 // FIXME: Settings information should be passed to the Worker process from Browser process when the worker
195 // is created (similar to RenderThread::OnCreateNewView).
196 m_mainFrame = WebLocalFrame::create(this);
197 m_webView->setMainFrame(m_mainFrame);
199 WebLocalFrameImpl* webFrame = toWebLocalFrameImpl(m_webView->mainFrame());
201 // Construct substitute data source for the 'shadow page'. We only need it
202 // to have same origin as the worker so the loading checks work correctly.
204 int length = static_cast<int>(content.length());
205 RefPtr<SharedBuffer> buffer(SharedBuffer::create(content.data(), length));
206 webFrame->frame()->loader().load(FrameLoadRequest(0, ResourceRequest(url), SubstituteData(buffer, "text/html", "UTF-8", KURL())));
209 WebApplicationCacheHost* WebSharedWorkerImpl::createApplicationCacheHost(WebLocalFrame*, WebApplicationCacheHostClient* appcacheHostClient)
212 return client()->createApplicationCacheHost(appcacheHostClient);
216 void WebSharedWorkerImpl::didFinishDocumentLoad(WebLocalFrame* frame)
218 ASSERT(!m_loadingDocument);
219 ASSERT(!m_mainScriptLoader);
220 m_mainScriptLoader = Loader::create();
221 m_loadingDocument = toWebLocalFrameImpl(frame)->frame()->document();
222 m_mainScriptLoader->load(
223 m_loadingDocument.get(),
225 bind(&WebSharedWorkerImpl::didReceiveScriptLoaderResponse, this),
226 bind(&WebSharedWorkerImpl::onScriptLoaderFinished, this));
229 // WorkerReportingProxy --------------------------------------------------------
231 void WebSharedWorkerImpl::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL)
233 // Not suppported in SharedWorker.
236 void WebSharedWorkerImpl::reportConsoleMessage(MessageSource source, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
238 // Not supported in SharedWorker.
241 void WebSharedWorkerImpl::postMessageToPageInspector(const String& message)
243 // Note that we need to keep the closure creation on a separate line so
244 // that the temporary created by isolatedCopy() will always be destroyed
245 // before the copy in the closure is used on the main thread.
246 const Closure& boundFunction = bind(&WebSharedWorkerClient::dispatchDevToolsMessage, m_clientWeakPtr, message.isolatedCopy());
247 callOnMainThread(boundFunction);
250 void WebSharedWorkerImpl::updateInspectorStateCookie(const String& cookie)
252 // Note that we need to keep the closure creation on a separate line so
253 // that the temporary created by isolatedCopy() will always be destroyed
254 // before the copy in the closure is used on the main thread.
255 const Closure& boundFunction = bind(&WebSharedWorkerClient::saveDevToolsAgentState, m_clientWeakPtr, cookie.isolatedCopy());
256 callOnMainThread(boundFunction);
259 void WebSharedWorkerImpl::workerGlobalScopeClosed()
261 callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread, this));
264 void WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread()
267 client()->workerContextClosed();
272 void WebSharedWorkerImpl::workerGlobalScopeStarted(WorkerGlobalScope*)
276 void WebSharedWorkerImpl::workerGlobalScopeDestroyed()
278 callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeDestroyedOnMainThread, this));
281 void WebSharedWorkerImpl::workerGlobalScopeDestroyedOnMainThread()
284 client()->workerContextDestroyed();
285 // The lifetime of this proxy is controlled by the worker context.
289 // WorkerLoaderProxy -----------------------------------------------------------
291 void WebSharedWorkerImpl::postTaskToLoader(PassOwnPtr<ExecutionContextTask> task)
293 toWebLocalFrameImpl(m_mainFrame)->frame()->document()->postTask(task);
296 bool WebSharedWorkerImpl::postTaskToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask> task)
298 m_workerThread->runLoop().postTask(task);
302 void WebSharedWorkerImpl::connect(WebMessagePortChannel* webChannel)
304 workerThread()->runLoop().postTask(
305 createCallbackTask(&connectTask, adoptPtr(webChannel)));
308 void WebSharedWorkerImpl::connectTask(ExecutionContext* context, PassOwnPtr<WebMessagePortChannel> channel)
310 // Wrap the passed-in channel in a MessagePort, and send it off via a connect event.
311 RefPtr<MessagePort> port = MessagePort::create(*context);
312 port->entangle(channel);
313 WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
314 ASSERT_WITH_SECURITY_IMPLICATION(workerGlobalScope->isSharedWorkerGlobalScope());
315 workerGlobalScope->dispatchEvent(createConnectEvent(port));
318 void WebSharedWorkerImpl::startWorkerContext(const WebURL& url, const WebString& name, const WebString& contentSecurityPolicy, WebContentSecurityPolicyType policyType)
322 m_contentSecurityPolicy = contentSecurityPolicy;
323 m_policyType = policyType;
324 initializeLoader(url);
327 void WebSharedWorkerImpl::didReceiveScriptLoaderResponse()
329 InspectorInstrumentation::didReceiveScriptResponse(m_loadingDocument.get(), m_mainScriptLoader->identifier());
331 client()->selectAppCacheID(m_mainScriptLoader->appCacheID());
334 static void connectToWorkerContextInspectorTask(ExecutionContext* context, bool)
336 toWorkerGlobalScope(context)->workerInspectorController()->connectFrontend();
339 void WebSharedWorkerImpl::onScriptLoaderFinished()
341 ASSERT(m_loadingDocument);
342 ASSERT(m_mainScriptLoader);
343 if (m_mainScriptLoader->failed() || m_askedToTerminate) {
344 m_mainScriptLoader.clear();
346 client()->workerScriptLoadFailed();
349 WorkerThreadStartMode startMode = m_pauseWorkerContextOnStart ? PauseWorkerGlobalScopeOnStart : DontPauseWorkerGlobalScopeOnStart;
350 OwnPtrWillBeRawPtr<WorkerClients> workerClients = WorkerClients::create();
351 provideLocalFileSystemToWorker(workerClients.get(), LocalFileSystemClient::create());
352 provideDatabaseClientToWorker(workerClients.get(), DatabaseClientImpl::create());
353 WebSecurityOrigin webSecurityOrigin(m_loadingDocument->securityOrigin());
354 providePermissionClientToWorker(workerClients.get(), adoptPtr(client()->createWorkerPermissionClientProxy(webSecurityOrigin)));
355 OwnPtrWillBeRawPtr<WorkerThreadStartupData> startupData = WorkerThreadStartupData::create(m_url, m_loadingDocument->userAgent(m_url), m_mainScriptLoader->script(), startMode, m_contentSecurityPolicy, static_cast<WebCore::ContentSecurityPolicyHeaderType>(m_policyType), workerClients.release());
356 setWorkerThread(SharedWorkerThread::create(m_name, *this, *this, startupData.release()));
357 InspectorInstrumentation::scriptImported(m_loadingDocument.get(), m_mainScriptLoader->identifier(), m_mainScriptLoader->script());
358 m_mainScriptLoader.clear();
360 if (m_attachDevToolsOnStart)
361 workerThread()->runLoop().postDebuggerTask(createCallbackTask(connectToWorkerContextInspectorTask, true));
363 workerThread()->start();
365 client()->workerScriptLoaded();
368 void WebSharedWorkerImpl::terminateWorkerContext()
373 void WebSharedWorkerImpl::clientDestroyed()
378 void WebSharedWorkerImpl::pauseWorkerContextOnStart()
380 m_pauseWorkerContextOnStart = true;
383 static void resumeWorkerContextTask(ExecutionContext* context, bool)
385 toWorkerGlobalScope(context)->workerInspectorController()->resume();
388 void WebSharedWorkerImpl::resumeWorkerContext()
390 m_pauseWorkerContextOnStart = false;
392 workerThread()->runLoop().postDebuggerTask(createCallbackTask(resumeWorkerContextTask, true));
395 void WebSharedWorkerImpl::attachDevTools()
398 workerThread()->runLoop().postDebuggerTask(createCallbackTask(connectToWorkerContextInspectorTask, true));
400 m_attachDevToolsOnStart = true;
403 static void reconnectToWorkerContextInspectorTask(ExecutionContext* context, const String& savedState)
405 WorkerInspectorController* ic = toWorkerGlobalScope(context)->workerInspectorController();
406 ic->restoreInspectorStateFromCookie(savedState);
410 void WebSharedWorkerImpl::reattachDevTools(const WebString& savedState)
412 workerThread()->runLoop().postDebuggerTask(createCallbackTask(reconnectToWorkerContextInspectorTask, String(savedState)));
415 static void disconnectFromWorkerContextInspectorTask(ExecutionContext* context, bool)
417 toWorkerGlobalScope(context)->workerInspectorController()->disconnectFrontend();
420 void WebSharedWorkerImpl::detachDevTools()
422 m_attachDevToolsOnStart = false;
423 workerThread()->runLoop().postDebuggerTask(createCallbackTask(disconnectFromWorkerContextInspectorTask, true));
426 static void dispatchOnInspectorBackendTask(ExecutionContext* context, const String& message)
428 toWorkerGlobalScope(context)->workerInspectorController()->dispatchMessageFromFrontend(message);
431 void WebSharedWorkerImpl::dispatchDevToolsMessage(const WebString& message)
433 workerThread()->runLoop().postDebuggerTask(createCallbackTask(dispatchOnInspectorBackendTask, String(message)));
434 WorkerDebuggerAgent::interruptAndDispatchInspectorCommands(workerThread());
437 WebSharedWorker* WebSharedWorker::create(WebSharedWorkerClient* client)
439 return new WebSharedWorkerImpl(client);