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 "core/dom/CrossThreadTask.h"
35 #include "core/dom/Document.h"
36 #include "core/events/MessageEvent.h"
37 #include "core/html/HTMLFormElement.h"
38 #include "core/inspector/ConsoleMessage.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/RuntimeEnabledFeatures.h"
53 #include "platform/heap/Handle.h"
54 #include "platform/network/ContentSecurityPolicyParsers.h"
55 #include "platform/network/ResourceResponse.h"
56 #include "platform/weborigin/KURL.h"
57 #include "platform/weborigin/SecurityOrigin.h"
58 #include "public/platform/WebFileError.h"
59 #include "public/platform/WebMessagePortChannel.h"
60 #include "public/platform/WebString.h"
61 #include "public/platform/WebURL.h"
62 #include "public/platform/WebURLRequest.h"
63 #include "public/web/WebFrame.h"
64 #include "public/web/WebSettings.h"
65 #include "public/web/WebView.h"
66 #include "public/web/WebWorkerPermissionClientProxy.h"
67 #include "web/DatabaseClientImpl.h"
68 #include "web/LocalFileSystemClient.h"
69 #include "web/WebDataSourceImpl.h"
70 #include "web/WebLocalFrameImpl.h"
71 #include "web/WorkerPermissionClient.h"
72 #include "wtf/Functional.h"
73 #include "wtf/MainThread.h"
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->setRequestContext(WebURLRequest::RequestContextSharedWorker);
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();
182 m_mainScriptLoader.clear();
184 client()->workerScriptLoadFailed();
189 m_workerThread->stop();
192 void WebSharedWorkerImpl::initializeLoader(const WebURL& url)
194 // Create 'shadow page'. This page is never displayed, it is used to proxy the
195 // loading requests from the worker context to the rest of WebKit and Chromium
198 m_webView = WebView::create(0);
199 m_webView->settings()->setOfflineWebApplicationCacheEnabled(RuntimeEnabledFeatures::applicationCacheEnabled());
200 // FIXME: http://crbug.com/363843. This needs to find a better way to
201 // not create graphics layers.
202 m_webView->settings()->setAcceleratedCompositingEnabled(false);
203 // FIXME: Settings information should be passed to the Worker process from Browser process when the worker
204 // is created (similar to RenderThread::OnCreateNewView).
205 m_mainFrame = WebLocalFrame::create(this);
206 m_webView->setMainFrame(m_mainFrame);
208 WebLocalFrameImpl* webFrame = toWebLocalFrameImpl(m_webView->mainFrame());
210 // Construct substitute data source for the 'shadow page'. We only need it
211 // to have same origin as the worker so the loading checks work correctly.
213 int length = static_cast<int>(content.length());
214 RefPtr<SharedBuffer> buffer(SharedBuffer::create(content.data(), length));
215 webFrame->frame()->loader().load(FrameLoadRequest(0, ResourceRequest(url), SubstituteData(buffer, "text/html", "UTF-8", KURL())));
218 WebApplicationCacheHost* WebSharedWorkerImpl::createApplicationCacheHost(WebLocalFrame*, WebApplicationCacheHostClient* appcacheHostClient)
221 return client()->createApplicationCacheHost(appcacheHostClient);
225 void WebSharedWorkerImpl::didFinishDocumentLoad(WebLocalFrame* frame)
227 ASSERT(!m_loadingDocument);
228 ASSERT(!m_mainScriptLoader);
229 m_mainScriptLoader = Loader::create();
230 m_loadingDocument = toWebLocalFrameImpl(frame)->frame()->document();
231 m_mainScriptLoader->load(
232 m_loadingDocument.get(),
234 bind(&WebSharedWorkerImpl::didReceiveScriptLoaderResponse, this),
235 bind(&WebSharedWorkerImpl::onScriptLoaderFinished, this));
238 // WorkerReportingProxy --------------------------------------------------------
240 void WebSharedWorkerImpl::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL)
242 // Not suppported in SharedWorker.
245 void WebSharedWorkerImpl::reportConsoleMessage(PassRefPtrWillBeRawPtr<ConsoleMessage>)
247 // Not supported in SharedWorker.
250 void WebSharedWorkerImpl::postMessageToPageInspector(const String& message)
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::dispatchDevToolsMessage, m_clientWeakPtr, message.isolatedCopy());
256 callOnMainThread(boundFunction);
259 void WebSharedWorkerImpl::updateInspectorStateCookie(const String& cookie)
261 // Note that we need to keep the closure creation on a separate line so
262 // that the temporary created by isolatedCopy() will always be destroyed
263 // before the copy in the closure is used on the main thread.
264 const Closure& boundFunction = bind(&WebSharedWorkerClient::saveDevToolsAgentState, m_clientWeakPtr, cookie.isolatedCopy());
265 callOnMainThread(boundFunction);
268 void WebSharedWorkerImpl::workerGlobalScopeClosed()
270 callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread, this));
273 void WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread()
276 client()->workerContextClosed();
281 void WebSharedWorkerImpl::workerGlobalScopeStarted(WorkerGlobalScope*)
285 void WebSharedWorkerImpl::workerThreadTerminated()
287 callOnMainThread(bind(&WebSharedWorkerImpl::workerThreadTerminatedOnMainThread, this));
290 void WebSharedWorkerImpl::workerThreadTerminatedOnMainThread()
293 client()->workerContextDestroyed();
294 // The lifetime of this proxy is controlled by the worker context.
298 // WorkerLoaderProxy -----------------------------------------------------------
300 void WebSharedWorkerImpl::postTaskToLoader(PassOwnPtr<ExecutionContextTask> task)
302 toWebLocalFrameImpl(m_mainFrame)->frame()->document()->postTask(task);
305 bool WebSharedWorkerImpl::postTaskToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask> task)
307 m_workerThread->postTask(task);
311 void WebSharedWorkerImpl::connect(WebMessagePortChannel* webChannel)
313 workerThread()->postTask(
314 createCrossThreadTask(&connectTask, adoptPtr(webChannel)));
317 void WebSharedWorkerImpl::connectTask(ExecutionContext* context, PassOwnPtr<WebMessagePortChannel> channel)
319 // Wrap the passed-in channel in a MessagePort, and send it off via a connect event.
320 RefPtrWillBeRawPtr<MessagePort> port = MessagePort::create(*context);
321 port->entangle(channel);
322 WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
323 ASSERT_WITH_SECURITY_IMPLICATION(workerGlobalScope->isSharedWorkerGlobalScope());
324 workerGlobalScope->dispatchEvent(createConnectEvent(port.release()));
327 void WebSharedWorkerImpl::startWorkerContext(const WebURL& url, const WebString& name, const WebString& contentSecurityPolicy, WebContentSecurityPolicyType policyType)
331 m_contentSecurityPolicy = contentSecurityPolicy;
332 m_policyType = policyType;
333 initializeLoader(url);
336 void WebSharedWorkerImpl::didReceiveScriptLoaderResponse()
338 InspectorInstrumentation::didReceiveScriptResponse(m_loadingDocument.get(), m_mainScriptLoader->identifier());
340 client()->selectAppCacheID(m_mainScriptLoader->appCacheID());
343 static void connectToWorkerContextInspectorTask(ExecutionContext* context, bool)
345 toWorkerGlobalScope(context)->workerInspectorController()->connectFrontend();
348 void WebSharedWorkerImpl::onScriptLoaderFinished()
350 ASSERT(m_loadingDocument);
351 ASSERT(m_mainScriptLoader);
352 if (m_askedToTerminate)
354 if (m_mainScriptLoader->failed()) {
355 m_mainScriptLoader->cancel();
357 client()->workerScriptLoadFailed();
359 // The SharedWorker was unable to load the initial script, so
360 // shut it down right here.
364 WorkerThreadStartMode startMode = m_pauseWorkerContextOnStart ? PauseWorkerGlobalScopeOnStart : DontPauseWorkerGlobalScopeOnStart;
365 OwnPtrWillBeRawPtr<WorkerClients> workerClients = WorkerClients::create();
366 provideLocalFileSystemToWorker(workerClients.get(), LocalFileSystemClient::create());
367 provideDatabaseClientToWorker(workerClients.get(), DatabaseClientImpl::create());
368 WebSecurityOrigin webSecurityOrigin(m_loadingDocument->securityOrigin());
369 providePermissionClientToWorker(workerClients.get(), adoptPtr(client()->createWorkerPermissionClientProxy(webSecurityOrigin)));
370 OwnPtrWillBeRawPtr<WorkerThreadStartupData> startupData = WorkerThreadStartupData::create(m_url, m_loadingDocument->userAgent(m_url), m_mainScriptLoader->script(), startMode, m_contentSecurityPolicy, static_cast<ContentSecurityPolicyHeaderType>(m_policyType), workerClients.release());
371 setWorkerThread(SharedWorkerThread::create(m_name, *this, *this, startupData.release()));
372 InspectorInstrumentation::scriptImported(m_loadingDocument.get(), m_mainScriptLoader->identifier(), m_mainScriptLoader->script());
373 m_mainScriptLoader.clear();
375 if (m_attachDevToolsOnStart)
376 workerThread()->postDebuggerTask(createCrossThreadTask(connectToWorkerContextInspectorTask, true));
378 workerThread()->start();
380 client()->workerScriptLoaded();
383 void WebSharedWorkerImpl::terminateWorkerContext()
388 void WebSharedWorkerImpl::clientDestroyed()
393 void WebSharedWorkerImpl::pauseWorkerContextOnStart()
395 m_pauseWorkerContextOnStart = true;
398 static void resumeWorkerContextTask(ExecutionContext* context, bool)
400 toWorkerGlobalScope(context)->workerInspectorController()->resume();
403 void WebSharedWorkerImpl::resumeWorkerContext()
405 m_pauseWorkerContextOnStart = false;
407 workerThread()->postDebuggerTask(createCrossThreadTask(resumeWorkerContextTask, true));
410 void WebSharedWorkerImpl::attachDevTools()
413 workerThread()->postDebuggerTask(createCrossThreadTask(connectToWorkerContextInspectorTask, true));
415 m_attachDevToolsOnStart = true;
418 static void reconnectToWorkerContextInspectorTask(ExecutionContext* context, const String& savedState)
420 WorkerInspectorController* ic = toWorkerGlobalScope(context)->workerInspectorController();
421 ic->restoreInspectorStateFromCookie(savedState);
425 void WebSharedWorkerImpl::reattachDevTools(const WebString& savedState)
427 workerThread()->postDebuggerTask(createCrossThreadTask(reconnectToWorkerContextInspectorTask, String(savedState)));
430 static void disconnectFromWorkerContextInspectorTask(ExecutionContext* context, bool)
432 toWorkerGlobalScope(context)->workerInspectorController()->disconnectFrontend();
435 void WebSharedWorkerImpl::detachDevTools()
437 m_attachDevToolsOnStart = false;
438 workerThread()->postDebuggerTask(createCrossThreadTask(disconnectFromWorkerContextInspectorTask, true));
441 static void dispatchOnInspectorBackendTask(ExecutionContext* context, const String& message)
443 toWorkerGlobalScope(context)->workerInspectorController()->dispatchMessageFromFrontend(message);
446 void WebSharedWorkerImpl::dispatchDevToolsMessage(const WebString& message)
448 if (m_askedToTerminate)
450 workerThread()->postDebuggerTask(createCrossThreadTask(dispatchOnInspectorBackendTask, String(message)));
451 workerThread()->interruptAndDispatchInspectorCommands();
454 WebSharedWorker* WebSharedWorker::create(WebSharedWorkerClient* client)
456 return new WebSharedWorkerImpl(client);