Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / web / WebSharedWorkerImpl.cpp
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 "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"
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:
80     static PassOwnPtr<Loader> create()
81     {
82         return adoptPtr(new Loader());
83     }
84
85     virtual ~Loader()
86     {
87         m_scriptLoader->setClient(0);
88     }
89
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
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
107     virtual void notifyFinished() OVERRIDE
108     {
109         m_finishCallback();
110     }
111
112     void cancel()
113     {
114         m_scriptLoader->cancel();
115     }
116
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; }
122
123 private:
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.
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
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
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
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
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: 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);
198
199     WebLocalFrameImpl* webFrame = toWebLocalFrameImpl(m_webView->mainFrame());
200
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.
203     CString content("");
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())));
207 }
208
209 WebApplicationCacheHost* WebSharedWorkerImpl::createApplicationCacheHost(WebLocalFrame*, WebApplicationCacheHostClient* appcacheHostClient)
210 {
211     if (client())
212         return client()->createApplicationCacheHost(appcacheHostClient);
213     return 0;
214 }
215
216 void WebSharedWorkerImpl::didFinishDocumentLoad(WebLocalFrame* frame)
217 {
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(),
224         m_url,
225         bind(&WebSharedWorkerImpl::didReceiveScriptLoaderResponse, this),
226         bind(&WebSharedWorkerImpl::onScriptLoaderFinished, this));
227 }
228
229 // WorkerReportingProxy --------------------------------------------------------
230
231 void WebSharedWorkerImpl::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL)
232 {
233     // Not suppported in SharedWorker.
234 }
235
236 void WebSharedWorkerImpl::reportConsoleMessage(MessageSource source, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
237 {
238     // Not supported in SharedWorker.
239 }
240
241 void WebSharedWorkerImpl::postMessageToPageInspector(const String& message)
242 {
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);
248 }
249
250 void WebSharedWorkerImpl::updateInspectorStateCookie(const String& cookie)
251 {
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);
257 }
258
259 void WebSharedWorkerImpl::workerGlobalScopeClosed()
260 {
261     callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread, this));
262 }
263
264 void WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread()
265 {
266     if (client())
267         client()->workerContextClosed();
268
269     stopWorkerThread();
270 }
271
272 void WebSharedWorkerImpl::workerGlobalScopeStarted(WorkerGlobalScope*)
273 {
274 }
275
276 void WebSharedWorkerImpl::workerGlobalScopeDestroyed()
277 {
278     callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeDestroyedOnMainThread, this));
279 }
280
281 void WebSharedWorkerImpl::workerGlobalScopeDestroyedOnMainThread()
282 {
283     if (client())
284         client()->workerContextDestroyed();
285     // The lifetime of this proxy is controlled by the worker context.
286     delete this;
287 }
288
289 // WorkerLoaderProxy -----------------------------------------------------------
290
291 void WebSharedWorkerImpl::postTaskToLoader(PassOwnPtr<ExecutionContextTask> task)
292 {
293     toWebLocalFrameImpl(m_mainFrame)->frame()->document()->postTask(task);
294 }
295
296 bool WebSharedWorkerImpl::postTaskToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask> task)
297 {
298     m_workerThread->runLoop().postTask(task);
299     return true;
300 }
301
302 void WebSharedWorkerImpl::connect(WebMessagePortChannel* webChannel)
303 {
304     workerThread()->runLoop().postTask(
305         createCallbackTask(&connectTask, adoptPtr(webChannel)));
306 }
307
308 void WebSharedWorkerImpl::connectTask(ExecutionContext* context, PassOwnPtr<WebMessagePortChannel> channel)
309 {
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));
316 }
317
318 void WebSharedWorkerImpl::startWorkerContext(const WebURL& url, const WebString& name, const WebString& contentSecurityPolicy, WebContentSecurityPolicyType policyType)
319 {
320     m_url = url;
321     m_name = name;
322     m_contentSecurityPolicy = contentSecurityPolicy;
323     m_policyType = policyType;
324     initializeLoader(url);
325 }
326
327 void WebSharedWorkerImpl::didReceiveScriptLoaderResponse()
328 {
329     InspectorInstrumentation::didReceiveScriptResponse(m_loadingDocument.get(), m_mainScriptLoader->identifier());
330     if (client())
331         client()->selectAppCacheID(m_mainScriptLoader->appCacheID());
332 }
333
334 static void connectToWorkerContextInspectorTask(ExecutionContext* context, bool)
335 {
336     toWorkerGlobalScope(context)->workerInspectorController()->connectFrontend();
337 }
338
339 void WebSharedWorkerImpl::onScriptLoaderFinished()
340 {
341     ASSERT(m_loadingDocument);
342     ASSERT(m_mainScriptLoader);
343     if (m_mainScriptLoader->failed() || m_askedToTerminate) {
344         m_mainScriptLoader.clear();
345         if (client())
346             client()->workerScriptLoadFailed();
347         return;
348     }
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();
359
360     if (m_attachDevToolsOnStart)
361         workerThread()->runLoop().postDebuggerTask(createCallbackTask(connectToWorkerContextInspectorTask, true));
362
363     workerThread()->start();
364     if (client())
365         client()->workerScriptLoaded();
366 }
367
368 void WebSharedWorkerImpl::terminateWorkerContext()
369 {
370     stopWorkerThread();
371 }
372
373 void WebSharedWorkerImpl::clientDestroyed()
374 {
375     m_client.clear();
376 }
377
378 void WebSharedWorkerImpl::pauseWorkerContextOnStart()
379 {
380     m_pauseWorkerContextOnStart = true;
381 }
382
383 static void resumeWorkerContextTask(ExecutionContext* context, bool)
384 {
385     toWorkerGlobalScope(context)->workerInspectorController()->resume();
386 }
387
388 void WebSharedWorkerImpl::resumeWorkerContext()
389 {
390     m_pauseWorkerContextOnStart = false;
391     if (workerThread())
392         workerThread()->runLoop().postDebuggerTask(createCallbackTask(resumeWorkerContextTask, true));
393 }
394
395 void WebSharedWorkerImpl::attachDevTools()
396 {
397     if (workerThread())
398         workerThread()->runLoop().postDebuggerTask(createCallbackTask(connectToWorkerContextInspectorTask, true));
399     else
400         m_attachDevToolsOnStart = true;
401 }
402
403 static void reconnectToWorkerContextInspectorTask(ExecutionContext* context, const String& savedState)
404 {
405     WorkerInspectorController* ic = toWorkerGlobalScope(context)->workerInspectorController();
406     ic->restoreInspectorStateFromCookie(savedState);
407     ic->resume();
408 }
409
410 void WebSharedWorkerImpl::reattachDevTools(const WebString& savedState)
411 {
412     workerThread()->runLoop().postDebuggerTask(createCallbackTask(reconnectToWorkerContextInspectorTask, String(savedState)));
413 }
414
415 static void disconnectFromWorkerContextInspectorTask(ExecutionContext* context, bool)
416 {
417     toWorkerGlobalScope(context)->workerInspectorController()->disconnectFrontend();
418 }
419
420 void WebSharedWorkerImpl::detachDevTools()
421 {
422     m_attachDevToolsOnStart = false;
423     workerThread()->runLoop().postDebuggerTask(createCallbackTask(disconnectFromWorkerContextInspectorTask, true));
424 }
425
426 static void dispatchOnInspectorBackendTask(ExecutionContext* context, const String& message)
427 {
428     toWorkerGlobalScope(context)->workerInspectorController()->dispatchMessageFromFrontend(message);
429 }
430
431 void WebSharedWorkerImpl::dispatchDevToolsMessage(const WebString& message)
432 {
433     workerThread()->runLoop().postDebuggerTask(createCallbackTask(dispatchOnInspectorBackendTask, String(message)));
434     WorkerDebuggerAgent::interruptAndDispatchInspectorCommands(workerThread());
435 }
436
437 WebSharedWorker* WebSharedWorker::create(WebSharedWorkerClient* client)
438 {
439     return new WebSharedWorkerImpl(client);
440 }
441
442 } // namespace blink