1 /* 2 * Copyright (C) 2009 Google 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 are 6 * met: 7 * 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 13 * distribution. 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. 17 * 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. 29 */ 30 31 #include "config.h" 32 #include "WebSharedWorkerImpl.h" 33 34 #include "DatabaseClientImpl.h" 35 #include "LocalFileSystemClient.h" 36 #include "WebDataSourceImpl.h" 37 #include "WebFrame.h" 38 #include "WebFrameImpl.h" 39 #include "WebRuntimeFeatures.h" 40 #include "WebSettings.h" 41 #include "WebView.h" 42 #include "WorkerPermissionClient.h" 43 #include "core/dom/CrossThreadTask.h" 44 #include "core/dom/Document.h" 45 #include "core/events/MessageEvent.h" 46 #include "core/html/HTMLFormElement.h" 47 #include "core/inspector/WorkerDebuggerAgent.h" 48 #include "core/inspector/WorkerInspectorController.h" 49 #include "core/loader/FrameLoadRequest.h" 50 #include "core/loader/FrameLoader.h" 51 #include "core/page/Page.h" 52 #include "core/page/PageGroup.h" 53 #include "core/workers/SharedWorkerGlobalScope.h" 54 #include "core/workers/SharedWorkerThread.h" 55 #include "core/workers/WorkerClients.h" 56 #include "core/workers/WorkerGlobalScope.h" 57 #include "core/workers/WorkerThreadStartupData.h" 58 #include "modules/webdatabase/DatabaseTask.h" 59 #include "platform/weborigin/KURL.h" 60 #include "platform/weborigin/SecurityOrigin.h" 61 #include "public/platform/WebFileError.h" 62 #include "public/platform/WebMessagePortChannel.h" 63 #include "public/platform/WebString.h" 64 #include "public/platform/WebURL.h" 65 #include "public/web/WebWorkerPermissionClientProxy.h" 66 #include "wtf/Functional.h" 67 #include "wtf/MainThread.h" 68 69 using namespace WebCore; 70 71 namespace blink { 72 73 // This function is called on the main thread to force to initialize some static 74 // values used in WebKit before any worker thread is started. This is because in 75 // our worker processs, we do not run any WebKit code in main thread and thus 76 // when multiple workers try to start at the same time, we might hit crash due 77 // to contention for initializing static values. 78 static void initializeWebKitStaticValues() 79 { 80 static bool initialized = false; 81 if (!initialized) { 82 initialized = true; 83 // Note that we have to pass a URL with valid protocol in order to follow 84 // the path to do static value initializations. 85 RefPtr<SecurityOrigin> origin = 86 SecurityOrigin::create(KURL(ParsedURLString, "http://localhost")); 87 origin.release(); 88 } 89 } 90 91 WebSharedWorkerImpl::WebSharedWorkerImpl(WebSharedWorkerClient* client) 92 : m_webView(0) 93 , m_mainFrame(0) 94 , m_askedToTerminate(false) 95 , m_client(WeakReference<WebSharedWorkerClient>::create(client)) 96 , m_clientWeakPtr(WeakPtr<WebSharedWorkerClient>(m_client)) 97 , m_pauseWorkerContextOnStart(false) 98 { 99 initializeWebKitStaticValues(); 100 } 101 102 WebSharedWorkerImpl::~WebSharedWorkerImpl() 103 { 104 ASSERT(m_webView); 105 // Detach the client before closing the view to avoid getting called back. 106 toWebFrameImpl(m_mainFrame)->setClient(0); 107 108 m_webView->close(); 109 m_mainFrame->close(); 110 } 111 112 void WebSharedWorkerImpl::stopWorkerThread() 113 { 114 if (m_askedToTerminate) 115 return; 116 m_askedToTerminate = true; 117 if (m_workerThread) 118 m_workerThread->stop(); 119 } 120 121 void WebSharedWorkerImpl::initializeLoader(const WebURL& url) 122 { 123 // Create 'shadow page'. This page is never displayed, it is used to proxy the 124 // loading requests from the worker context to the rest of WebKit and Chromium 125 // infrastructure. 126 ASSERT(!m_webView); 127 m_webView = WebView::create(0); 128 m_webView->settings()->setOfflineWebApplicationCacheEnabled(WebRuntimeFeatures::isApplicationCacheEnabled()); 129 // FIXME: Settings information should be passed to the Worker process from Browser process when the worker 130 // is created (similar to RenderThread::OnCreateNewView). 131 m_mainFrame = WebFrame::create(this); 132 m_webView->setMainFrame(m_mainFrame); 133 134 WebFrameImpl* webFrame = toWebFrameImpl(m_webView->mainFrame()); 135 136 // Construct substitute data source for the 'shadow page'. We only need it 137 // to have same origin as the worker so the loading checks work correctly. 138 CString content(""); 139 int length = static_cast<int>(content.length()); 140 RefPtr<SharedBuffer> buffer(SharedBuffer::create(content.data(), length)); 141 webFrame->frame()->loader().load(FrameLoadRequest(0, ResourceRequest(url), SubstituteData(buffer, "text/html", "UTF-8", KURL()))); 142 143 // This document will be used as 'loading context' for the worker. 144 m_loadingDocument = webFrame->frame()->document(); 145 } 146 147 void WebSharedWorkerImpl::didCreateDataSource(WebFrame*, WebDataSource* ds) 148 { 149 // Tell the loader to load the data into the 'shadow page' synchronously, 150 // so we can grab the resulting Document right after load. 151 static_cast<WebDataSourceImpl*>(ds)->setDeferMainResourceDataLoad(false); 152 } 153 154 WebApplicationCacheHost* WebSharedWorkerImpl::createApplicationCacheHost(WebFrame*, WebApplicationCacheHostClient* appcacheHostClient) 155 { 156 if (client()) 157 return client()->createApplicationCacheHost(appcacheHostClient); 158 return 0; 159 } 160 161 // WorkerReportingProxy -------------------------------------------------------- 162 163 void WebSharedWorkerImpl::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) 164 { 165 // Not suppported in SharedWorker. 166 } 167 168 void WebSharedWorkerImpl::reportConsoleMessage(MessageSource source, MessageLevel level, const String& message, int lineNumber, const String& sourceURL) 169 { 170 // Not supported in SharedWorker. 171 } 172 173 void WebSharedWorkerImpl::postMessageToPageInspector(const String& message) 174 { 175 callOnMainThread(bind(&WebSharedWorkerClient::dispatchDevToolsMessage, m_clientWeakPtr, message.isolatedCopy())); 176 } 177 178 void WebSharedWorkerImpl::updateInspectorStateCookie(const String& cookie) 179 { 180 callOnMainThread(bind(&WebSharedWorkerClient::saveDevToolsAgentState, m_clientWeakPtr, cookie.isolatedCopy())); 181 } 182 183 void WebSharedWorkerImpl::workerGlobalScopeClosed() 184 { 185 callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread, this)); 186 } 187 188 void WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread() 189 { 190 if (client()) 191 client()->workerContextClosed(); 192 193 stopWorkerThread(); 194 } 195 196 void WebSharedWorkerImpl::workerGlobalScopeStarted() 197 { 198 } 199 200 void WebSharedWorkerImpl::workerGlobalScopeDestroyed() 201 { 202 callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeDestroyedOnMainThread, this)); 203 } 204 205 void WebSharedWorkerImpl::workerGlobalScopeDestroyedOnMainThread() 206 { 207 if (client()) 208 client()->workerContextDestroyed(); 209 // The lifetime of this proxy is controlled by the worker context. 210 delete this; 211 } 212 213 // WorkerLoaderProxy ----------------------------------------------------------- 214 215 void WebSharedWorkerImpl::postTaskToLoader(PassOwnPtr<ExecutionContextTask> task) 216 { 217 ASSERT(m_loadingDocument->isDocument()); 218 m_loadingDocument->postTask(task); 219 } 220 221 bool WebSharedWorkerImpl::postTaskForModeToWorkerGlobalScope( 222 PassOwnPtr<ExecutionContextTask> task, const String& mode) 223 { 224 m_workerThread->runLoop().postTaskForMode(task, mode); 225 return true; 226 } 227 228 bool WebSharedWorkerImpl::isStarted() 229 { 230 // Should not ever be called from the worker thread (this API is only called on WebSharedWorkerProxy on the renderer thread). 231 ASSERT_NOT_REACHED(); 232 return workerThread(); 233 } 234 235 void WebSharedWorkerImpl::connect(WebMessagePortChannel* webChannel, ConnectListener* listener) 236 { 237 workerThread()->runLoop().postTask( 238 createCallbackTask(&connectTask, adoptPtr(webChannel))); 239 if (listener) 240 listener->connected(); 241 } 242 243 void WebSharedWorkerImpl::connectTask(ExecutionContext* context, PassOwnPtr<WebMessagePortChannel> channel) 244 { 245 // Wrap the passed-in channel in a MessagePort, and send it off via a connect event. 246 RefPtr<MessagePort> port = MessagePort::create(*context); 247 port->entangle(channel); 248 WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context); 249 ASSERT_WITH_SECURITY_IMPLICATION(workerGlobalScope->isSharedWorkerGlobalScope()); 250 workerGlobalScope->dispatchEvent(createConnectEvent(port)); 251 } 252 253 void WebSharedWorkerImpl::startWorkerContext(const WebURL& url, const WebString& name, const WebString& userAgent, const WebString& sourceCode, const WebString& contentSecurityPolicy, WebContentSecurityPolicyType policyType, long long) 254 { 255 initializeLoader(url); 256 257 WorkerThreadStartMode startMode = m_pauseWorkerContextOnStart ? PauseWorkerGlobalScopeOnStart : DontPauseWorkerGlobalScopeOnStart; 258 OwnPtr<WorkerClients> workerClients = WorkerClients::create(); 259 provideLocalFileSystemToWorker(workerClients.get(), LocalFileSystemClient::create()); 260 provideDatabaseClientToWorker(workerClients.get(), DatabaseClientImpl::create()); 261 WebSecurityOrigin webSecurityOrigin(m_loadingDocument->securityOrigin()); 262 providePermissionClientToWorker(workerClients.get(), adoptPtr(client()->createWorkerPermissionClientProxy(webSecurityOrigin))); 263 OwnPtr<WorkerThreadStartupData> startupData = WorkerThreadStartupData::create(url, userAgent, sourceCode, startMode, contentSecurityPolicy, static_cast<WebCore::ContentSecurityPolicy::HeaderType>(policyType), workerClients.release()); 264 setWorkerThread(SharedWorkerThread::create(name, *this, *this, startupData.release())); 265 266 workerThread()->start(); 267 } 268 269 void WebSharedWorkerImpl::terminateWorkerContext() 270 { 271 stopWorkerThread(); 272 } 273 274 void WebSharedWorkerImpl::clientDestroyed() 275 { 276 m_client.clear(); 277 } 278 279 void WebSharedWorkerImpl::pauseWorkerContextOnStart() 280 { 281 m_pauseWorkerContextOnStart = true; 282 } 283 284 static void resumeWorkerContextTask(ExecutionContext* context, bool) 285 { 286 toWorkerGlobalScope(context)->workerInspectorController()->resume(); 287 } 288 289 void WebSharedWorkerImpl::resumeWorkerContext() 290 { 291 m_pauseWorkerContextOnStart = false; 292 if (workerThread()) 293 workerThread()->runLoop().postTaskForMode(createCallbackTask(resumeWorkerContextTask, true), WorkerDebuggerAgent::debuggerTaskMode); 294 } 295 296 static void connectToWorkerContextInspectorTask(ExecutionContext* context, bool) 297 { 298 toWorkerGlobalScope(context)->workerInspectorController()->connectFrontend(); 299 } 300 301 void WebSharedWorkerImpl::attachDevTools() 302 { 303 workerThread()->runLoop().postTaskForMode(createCallbackTask(connectToWorkerContextInspectorTask, true), WorkerDebuggerAgent::debuggerTaskMode); 304 } 305 306 static void reconnectToWorkerContextInspectorTask(ExecutionContext* context, const String& savedState) 307 { 308 WorkerInspectorController* ic = toWorkerGlobalScope(context)->workerInspectorController(); 309 ic->restoreInspectorStateFromCookie(savedState); 310 ic->resume(); 311 } 312 313 void WebSharedWorkerImpl::reattachDevTools(const WebString& savedState) 314 { 315 workerThread()->runLoop().postTaskForMode(createCallbackTask(reconnectToWorkerContextInspectorTask, String(savedState)), WorkerDebuggerAgent::debuggerTaskMode); 316 } 317 318 static void disconnectFromWorkerContextInspectorTask(ExecutionContext* context, bool) 319 { 320 toWorkerGlobalScope(context)->workerInspectorController()->disconnectFrontend(); 321 } 322 323 void WebSharedWorkerImpl::detachDevTools() 324 { 325 workerThread()->runLoop().postTaskForMode(createCallbackTask(disconnectFromWorkerContextInspectorTask, true), WorkerDebuggerAgent::debuggerTaskMode); 326 } 327 328 static void dispatchOnInspectorBackendTask(ExecutionContext* context, const String& message) 329 { 330 toWorkerGlobalScope(context)->workerInspectorController()->dispatchMessageFromFrontend(message); 331 } 332 333 void WebSharedWorkerImpl::dispatchDevToolsMessage(const WebString& message) 334 { 335 workerThread()->runLoop().postTaskForMode(createCallbackTask(dispatchOnInspectorBackendTask, String(message)), WorkerDebuggerAgent::debuggerTaskMode); 336 WorkerDebuggerAgent::interruptAndDispatchInspectorCommands(workerThread()); 337 } 338 339 WebSharedWorker* WebSharedWorker::create(WebSharedWorkerClient* client) 340 { 341 return new WebSharedWorkerImpl(client); 342 } 343 344 } // namespace blink 345