• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "web/WebSharedWorkerImpl.h"
33 
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/InspectorInstrumentation.h"
39 #include "core/inspector/WorkerDebuggerAgent.h"
40 #include "core/inspector/WorkerInspectorController.h"
41 #include "core/loader/FrameLoadRequest.h"
42 #include "core/loader/FrameLoader.h"
43 #include "core/page/Page.h"
44 #include "core/workers/SharedWorkerGlobalScope.h"
45 #include "core/workers/SharedWorkerThread.h"
46 #include "core/workers/WorkerClients.h"
47 #include "core/workers/WorkerGlobalScope.h"
48 #include "core/workers/WorkerScriptLoader.h"
49 #include "core/workers/WorkerThreadStartupData.h"
50 #include "modules/webdatabase/DatabaseTask.h"
51 #include "platform/RuntimeEnabledFeatures.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"
72 
73 using namespace WebCore;
74 
75 namespace blink {
76 
77 // A thin wrapper for one-off script loading.
78 class WebSharedWorkerImpl::Loader : public WorkerScriptLoaderClient {
79 public:
create()80     static PassOwnPtr<Loader> create()
81     {
82         return adoptPtr(new Loader());
83     }
84 
~Loader()85     virtual ~Loader()
86     {
87         m_scriptLoader->setClient(0);
88     }
89 
load(ExecutionContext * loadingContext,const KURL & scriptURL,const Closure & receiveResponseCallback,const Closure & finishCallback)90     void load(ExecutionContext* loadingContext, const KURL& scriptURL, const Closure& receiveResponseCallback, const Closure& finishCallback)
91     {
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);
98     }
99 
didReceiveResponse(unsigned long identifier,const ResourceResponse & response)100     void didReceiveResponse(unsigned long identifier, const ResourceResponse& response) OVERRIDE
101     {
102         m_identifier = identifier;
103         m_appCacheID = response.appCacheID();
104         m_receiveResponseCallback();
105     }
106 
notifyFinished()107     virtual void notifyFinished() OVERRIDE
108     {
109         m_finishCallback();
110     }
111 
cancel()112     void cancel()
113     {
114         m_scriptLoader->cancel();
115     }
116 
failed() const117     bool failed() const { return m_scriptLoader->failed(); }
url() const118     const KURL& url() const { return m_scriptLoader->responseURL(); }
script() const119     String script() const { return m_scriptLoader->script(); }
identifier() const120     unsigned long identifier() const { return m_identifier; }
appCacheID() const121     long long appCacheID() const { return m_appCacheID; }
122 
123 private:
Loader()124     Loader() : m_scriptLoader(WorkerScriptLoader::create()), m_identifier(0), m_appCacheID(0)
125     {
126     }
127 
128     RefPtr<WorkerScriptLoader> m_scriptLoader;
129     unsigned long m_identifier;
130     long long m_appCacheID;
131     Closure m_receiveResponseCallback;
132     Closure m_finishCallback;
133 };
134 
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.
initializeWebKitStaticValues()140 static void initializeWebKitStaticValues()
141 {
142     static bool initialized = false;
143     if (!initialized) {
144         initialized = true;
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"));
149         origin.release();
150     }
151 }
152 
WebSharedWorkerImpl(WebSharedWorkerClient * client)153 WebSharedWorkerImpl::WebSharedWorkerImpl(WebSharedWorkerClient* client)
154     : m_webView(0)
155     , m_mainFrame(0)
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)
161 {
162     initializeWebKitStaticValues();
163 }
164 
~WebSharedWorkerImpl()165 WebSharedWorkerImpl::~WebSharedWorkerImpl()
166 {
167     ASSERT(m_webView);
168     // Detach the client before closing the view to avoid getting called back.
169     toWebLocalFrameImpl(m_mainFrame)->setClient(0);
170 
171     m_webView->close();
172     m_mainFrame->close();
173 }
174 
stopWorkerThread()175 void WebSharedWorkerImpl::stopWorkerThread()
176 {
177     if (m_askedToTerminate)
178         return;
179     m_askedToTerminate = true;
180     if (m_mainScriptLoader)
181         m_mainScriptLoader->cancel();
182     if (m_workerThread)
183         m_workerThread->stop();
184 }
185 
initializeLoader(const WebURL & url)186 void WebSharedWorkerImpl::initializeLoader(const WebURL& url)
187 {
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
190     // infrastructure.
191     ASSERT(!m_webView);
192     m_webView = WebView::create(0);
193     m_webView->settings()->setOfflineWebApplicationCacheEnabled(RuntimeEnabledFeatures::applicationCacheEnabled());
194     // FIXME: http://crbug.com/363843. This needs to find a better way to
195     // not create graphics layers.
196     m_webView->settings()->setAcceleratedCompositingEnabled(false);
197     // FIXME: Settings information should be passed to the Worker process from Browser process when the worker
198     // is created (similar to RenderThread::OnCreateNewView).
199     m_mainFrame = WebLocalFrame::create(this);
200     m_webView->setMainFrame(m_mainFrame);
201 
202     WebLocalFrameImpl* webFrame = toWebLocalFrameImpl(m_webView->mainFrame());
203 
204     // Construct substitute data source for the 'shadow page'. We only need it
205     // to have same origin as the worker so the loading checks work correctly.
206     CString content("");
207     int length = static_cast<int>(content.length());
208     RefPtr<SharedBuffer> buffer(SharedBuffer::create(content.data(), length));
209     webFrame->frame()->loader().load(FrameLoadRequest(0, ResourceRequest(url), SubstituteData(buffer, "text/html", "UTF-8", KURL())));
210 }
211 
createApplicationCacheHost(WebLocalFrame *,WebApplicationCacheHostClient * appcacheHostClient)212 WebApplicationCacheHost* WebSharedWorkerImpl::createApplicationCacheHost(WebLocalFrame*, WebApplicationCacheHostClient* appcacheHostClient)
213 {
214     if (client())
215         return client()->createApplicationCacheHost(appcacheHostClient);
216     return 0;
217 }
218 
didFinishDocumentLoad(WebLocalFrame * frame)219 void WebSharedWorkerImpl::didFinishDocumentLoad(WebLocalFrame* frame)
220 {
221     ASSERT(!m_loadingDocument);
222     ASSERT(!m_mainScriptLoader);
223     m_mainScriptLoader = Loader::create();
224     m_loadingDocument = toWebLocalFrameImpl(frame)->frame()->document();
225     m_mainScriptLoader->load(
226         m_loadingDocument.get(),
227         m_url,
228         bind(&WebSharedWorkerImpl::didReceiveScriptLoaderResponse, this),
229         bind(&WebSharedWorkerImpl::onScriptLoaderFinished, this));
230 }
231 
232 // WorkerReportingProxy --------------------------------------------------------
233 
reportException(const String & errorMessage,int lineNumber,int columnNumber,const String & sourceURL)234 void WebSharedWorkerImpl::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL)
235 {
236     // Not suppported in SharedWorker.
237 }
238 
reportConsoleMessage(MessageSource source,MessageLevel level,const String & message,int lineNumber,const String & sourceURL)239 void WebSharedWorkerImpl::reportConsoleMessage(MessageSource source, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
240 {
241     // Not supported in SharedWorker.
242 }
243 
postMessageToPageInspector(const String & message)244 void WebSharedWorkerImpl::postMessageToPageInspector(const String& message)
245 {
246     // Note that we need to keep the closure creation on a separate line so
247     // that the temporary created by isolatedCopy() will always be destroyed
248     // before the copy in the closure is used on the main thread.
249     const Closure& boundFunction = bind(&WebSharedWorkerClient::dispatchDevToolsMessage, m_clientWeakPtr, message.isolatedCopy());
250     callOnMainThread(boundFunction);
251 }
252 
updateInspectorStateCookie(const String & cookie)253 void WebSharedWorkerImpl::updateInspectorStateCookie(const String& cookie)
254 {
255     // Note that we need to keep the closure creation on a separate line so
256     // that the temporary created by isolatedCopy() will always be destroyed
257     // before the copy in the closure is used on the main thread.
258     const Closure& boundFunction = bind(&WebSharedWorkerClient::saveDevToolsAgentState, m_clientWeakPtr, cookie.isolatedCopy());
259     callOnMainThread(boundFunction);
260 }
261 
workerGlobalScopeClosed()262 void WebSharedWorkerImpl::workerGlobalScopeClosed()
263 {
264     callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread, this));
265 }
266 
workerGlobalScopeClosedOnMainThread()267 void WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread()
268 {
269     if (client())
270         client()->workerContextClosed();
271 
272     stopWorkerThread();
273 }
274 
workerGlobalScopeStarted(WorkerGlobalScope *)275 void WebSharedWorkerImpl::workerGlobalScopeStarted(WorkerGlobalScope*)
276 {
277 }
278 
workerGlobalScopeDestroyed()279 void WebSharedWorkerImpl::workerGlobalScopeDestroyed()
280 {
281     callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeDestroyedOnMainThread, this));
282 }
283 
workerGlobalScopeDestroyedOnMainThread()284 void WebSharedWorkerImpl::workerGlobalScopeDestroyedOnMainThread()
285 {
286     if (client())
287         client()->workerContextDestroyed();
288     // The lifetime of this proxy is controlled by the worker context.
289     delete this;
290 }
291 
292 // WorkerLoaderProxy -----------------------------------------------------------
293 
postTaskToLoader(PassOwnPtr<ExecutionContextTask> task)294 void WebSharedWorkerImpl::postTaskToLoader(PassOwnPtr<ExecutionContextTask> task)
295 {
296     toWebLocalFrameImpl(m_mainFrame)->frame()->document()->postTask(task);
297 }
298 
postTaskToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask> task)299 bool WebSharedWorkerImpl::postTaskToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask> task)
300 {
301     m_workerThread->runLoop().postTask(task);
302     return true;
303 }
304 
connect(WebMessagePortChannel * webChannel)305 void WebSharedWorkerImpl::connect(WebMessagePortChannel* webChannel)
306 {
307     workerThread()->runLoop().postTask(
308         createCallbackTask(&connectTask, adoptPtr(webChannel)));
309 }
310 
connectTask(ExecutionContext * context,PassOwnPtr<WebMessagePortChannel> channel)311 void WebSharedWorkerImpl::connectTask(ExecutionContext* context, PassOwnPtr<WebMessagePortChannel> channel)
312 {
313     // Wrap the passed-in channel in a MessagePort, and send it off via a connect event.
314     RefPtrWillBeRawPtr<MessagePort> port = MessagePort::create(*context);
315     port->entangle(channel);
316     WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
317     ASSERT_WITH_SECURITY_IMPLICATION(workerGlobalScope->isSharedWorkerGlobalScope());
318     workerGlobalScope->dispatchEvent(createConnectEvent(port.release()));
319 }
320 
startWorkerContext(const WebURL & url,const WebString & name,const WebString & contentSecurityPolicy,WebContentSecurityPolicyType policyType)321 void WebSharedWorkerImpl::startWorkerContext(const WebURL& url, const WebString& name, const WebString& contentSecurityPolicy, WebContentSecurityPolicyType policyType)
322 {
323     m_url = url;
324     m_name = name;
325     m_contentSecurityPolicy = contentSecurityPolicy;
326     m_policyType = policyType;
327     initializeLoader(url);
328 }
329 
didReceiveScriptLoaderResponse()330 void WebSharedWorkerImpl::didReceiveScriptLoaderResponse()
331 {
332     InspectorInstrumentation::didReceiveScriptResponse(m_loadingDocument.get(), m_mainScriptLoader->identifier());
333     if (client())
334         client()->selectAppCacheID(m_mainScriptLoader->appCacheID());
335 }
336 
connectToWorkerContextInspectorTask(ExecutionContext * context,bool)337 static void connectToWorkerContextInspectorTask(ExecutionContext* context, bool)
338 {
339     toWorkerGlobalScope(context)->workerInspectorController()->connectFrontend();
340 }
341 
onScriptLoaderFinished()342 void WebSharedWorkerImpl::onScriptLoaderFinished()
343 {
344     ASSERT(m_loadingDocument);
345     ASSERT(m_mainScriptLoader);
346     if (m_mainScriptLoader->failed() || m_askedToTerminate) {
347         m_mainScriptLoader.clear();
348         if (client())
349             client()->workerScriptLoadFailed();
350         return;
351     }
352     WorkerThreadStartMode startMode = m_pauseWorkerContextOnStart ? PauseWorkerGlobalScopeOnStart : DontPauseWorkerGlobalScopeOnStart;
353     OwnPtrWillBeRawPtr<WorkerClients> workerClients = WorkerClients::create();
354     provideLocalFileSystemToWorker(workerClients.get(), LocalFileSystemClient::create());
355     provideDatabaseClientToWorker(workerClients.get(), DatabaseClientImpl::create());
356     WebSecurityOrigin webSecurityOrigin(m_loadingDocument->securityOrigin());
357     providePermissionClientToWorker(workerClients.get(), adoptPtr(client()->createWorkerPermissionClientProxy(webSecurityOrigin)));
358     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());
359     setWorkerThread(SharedWorkerThread::create(m_name, *this, *this, startupData.release()));
360     InspectorInstrumentation::scriptImported(m_loadingDocument.get(), m_mainScriptLoader->identifier(), m_mainScriptLoader->script());
361     m_mainScriptLoader.clear();
362 
363     if (m_attachDevToolsOnStart)
364         workerThread()->runLoop().postDebuggerTask(createCallbackTask(connectToWorkerContextInspectorTask, true));
365 
366     workerThread()->start();
367     if (client())
368         client()->workerScriptLoaded();
369 }
370 
terminateWorkerContext()371 void WebSharedWorkerImpl::terminateWorkerContext()
372 {
373     stopWorkerThread();
374 }
375 
clientDestroyed()376 void WebSharedWorkerImpl::clientDestroyed()
377 {
378     m_client.clear();
379 }
380 
pauseWorkerContextOnStart()381 void WebSharedWorkerImpl::pauseWorkerContextOnStart()
382 {
383     m_pauseWorkerContextOnStart = true;
384 }
385 
resumeWorkerContextTask(ExecutionContext * context,bool)386 static void resumeWorkerContextTask(ExecutionContext* context, bool)
387 {
388     toWorkerGlobalScope(context)->workerInspectorController()->resume();
389 }
390 
resumeWorkerContext()391 void WebSharedWorkerImpl::resumeWorkerContext()
392 {
393     m_pauseWorkerContextOnStart = false;
394     if (workerThread())
395         workerThread()->runLoop().postDebuggerTask(createCallbackTask(resumeWorkerContextTask, true));
396 }
397 
attachDevTools()398 void WebSharedWorkerImpl::attachDevTools()
399 {
400     if (workerThread())
401         workerThread()->runLoop().postDebuggerTask(createCallbackTask(connectToWorkerContextInspectorTask, true));
402     else
403         m_attachDevToolsOnStart = true;
404 }
405 
reconnectToWorkerContextInspectorTask(ExecutionContext * context,const String & savedState)406 static void reconnectToWorkerContextInspectorTask(ExecutionContext* context, const String& savedState)
407 {
408     WorkerInspectorController* ic = toWorkerGlobalScope(context)->workerInspectorController();
409     ic->restoreInspectorStateFromCookie(savedState);
410     ic->resume();
411 }
412 
reattachDevTools(const WebString & savedState)413 void WebSharedWorkerImpl::reattachDevTools(const WebString& savedState)
414 {
415     workerThread()->runLoop().postDebuggerTask(createCallbackTask(reconnectToWorkerContextInspectorTask, String(savedState)));
416 }
417 
disconnectFromWorkerContextInspectorTask(ExecutionContext * context,bool)418 static void disconnectFromWorkerContextInspectorTask(ExecutionContext* context, bool)
419 {
420     toWorkerGlobalScope(context)->workerInspectorController()->disconnectFrontend();
421 }
422 
detachDevTools()423 void WebSharedWorkerImpl::detachDevTools()
424 {
425     m_attachDevToolsOnStart = false;
426     workerThread()->runLoop().postDebuggerTask(createCallbackTask(disconnectFromWorkerContextInspectorTask, true));
427 }
428 
dispatchOnInspectorBackendTask(ExecutionContext * context,const String & message)429 static void dispatchOnInspectorBackendTask(ExecutionContext* context, const String& message)
430 {
431     toWorkerGlobalScope(context)->workerInspectorController()->dispatchMessageFromFrontend(message);
432 }
433 
dispatchDevToolsMessage(const WebString & message)434 void WebSharedWorkerImpl::dispatchDevToolsMessage(const WebString& message)
435 {
436     workerThread()->runLoop().postDebuggerTask(createCallbackTask(dispatchOnInspectorBackendTask, String(message)));
437     WorkerDebuggerAgent::interruptAndDispatchInspectorCommands(workerThread());
438 }
439 
create(WebSharedWorkerClient * client)440 WebSharedWorker* WebSharedWorker::create(WebSharedWorkerClient* client)
441 {
442     return new WebSharedWorkerImpl(client);
443 }
444 
445 } // namespace blink
446