Upstream version 9.38.198.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 "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"
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->setRequestContext(WebURLRequest::RequestContextSharedWorker);
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         m_mainScriptLoader.clear();
183         if (client())
184             client()->workerScriptLoadFailed();
185         delete this;
186         return;
187     }
188     if (m_workerThread)
189         m_workerThread->stop();
190 }
191
192 void WebSharedWorkerImpl::initializeLoader(const WebURL& url)
193 {
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
196     // infrastructure.
197     ASSERT(!m_webView);
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);
207
208     WebLocalFrameImpl* webFrame = toWebLocalFrameImpl(m_webView->mainFrame());
209
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.
212     CString content("");
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())));
216 }
217
218 WebApplicationCacheHost* WebSharedWorkerImpl::createApplicationCacheHost(WebLocalFrame*, WebApplicationCacheHostClient* appcacheHostClient)
219 {
220     if (client())
221         return client()->createApplicationCacheHost(appcacheHostClient);
222     return 0;
223 }
224
225 void WebSharedWorkerImpl::didFinishDocumentLoad(WebLocalFrame* frame)
226 {
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(),
233         m_url,
234         bind(&WebSharedWorkerImpl::didReceiveScriptLoaderResponse, this),
235         bind(&WebSharedWorkerImpl::onScriptLoaderFinished, this));
236 }
237
238 // WorkerReportingProxy --------------------------------------------------------
239
240 void WebSharedWorkerImpl::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL)
241 {
242     // Not suppported in SharedWorker.
243 }
244
245 void WebSharedWorkerImpl::reportConsoleMessage(PassRefPtrWillBeRawPtr<ConsoleMessage>)
246 {
247     // Not supported in SharedWorker.
248 }
249
250 void WebSharedWorkerImpl::postMessageToPageInspector(const String& message)
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::dispatchDevToolsMessage, m_clientWeakPtr, message.isolatedCopy());
256     callOnMainThread(boundFunction);
257 }
258
259 void WebSharedWorkerImpl::updateInspectorStateCookie(const String& cookie)
260 {
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);
266 }
267
268 void WebSharedWorkerImpl::workerGlobalScopeClosed()
269 {
270     callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread, this));
271 }
272
273 void WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread()
274 {
275     if (client())
276         client()->workerContextClosed();
277
278     stopWorkerThread();
279 }
280
281 void WebSharedWorkerImpl::workerGlobalScopeStarted(WorkerGlobalScope*)
282 {
283 }
284
285 void WebSharedWorkerImpl::workerThreadTerminated()
286 {
287     callOnMainThread(bind(&WebSharedWorkerImpl::workerThreadTerminatedOnMainThread, this));
288 }
289
290 void WebSharedWorkerImpl::workerThreadTerminatedOnMainThread()
291 {
292     if (client())
293         client()->workerContextDestroyed();
294     // The lifetime of this proxy is controlled by the worker context.
295     delete this;
296 }
297
298 // WorkerLoaderProxy -----------------------------------------------------------
299
300 void WebSharedWorkerImpl::postTaskToLoader(PassOwnPtr<ExecutionContextTask> task)
301 {
302     toWebLocalFrameImpl(m_mainFrame)->frame()->document()->postTask(task);
303 }
304
305 bool WebSharedWorkerImpl::postTaskToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask> task)
306 {
307     m_workerThread->postTask(task);
308     return true;
309 }
310
311 void WebSharedWorkerImpl::connect(WebMessagePortChannel* webChannel)
312 {
313     workerThread()->postTask(
314         createCrossThreadTask(&connectTask, adoptPtr(webChannel)));
315 }
316
317 void WebSharedWorkerImpl::connectTask(ExecutionContext* context, PassOwnPtr<WebMessagePortChannel> channel)
318 {
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()));
325 }
326
327 void WebSharedWorkerImpl::startWorkerContext(const WebURL& url, const WebString& name, const WebString& contentSecurityPolicy, WebContentSecurityPolicyType policyType)
328 {
329     m_url = url;
330     m_name = name;
331     m_contentSecurityPolicy = contentSecurityPolicy;
332     m_policyType = policyType;
333     initializeLoader(url);
334 }
335
336 void WebSharedWorkerImpl::didReceiveScriptLoaderResponse()
337 {
338     InspectorInstrumentation::didReceiveScriptResponse(m_loadingDocument.get(), m_mainScriptLoader->identifier());
339     if (client())
340         client()->selectAppCacheID(m_mainScriptLoader->appCacheID());
341 }
342
343 static void connectToWorkerContextInspectorTask(ExecutionContext* context, bool)
344 {
345     toWorkerGlobalScope(context)->workerInspectorController()->connectFrontend();
346 }
347
348 void WebSharedWorkerImpl::onScriptLoaderFinished()
349 {
350     ASSERT(m_loadingDocument);
351     ASSERT(m_mainScriptLoader);
352     if (m_askedToTerminate)
353         return;
354     if (m_mainScriptLoader->failed()) {
355         m_mainScriptLoader->cancel();
356         if (client())
357             client()->workerScriptLoadFailed();
358
359         // The SharedWorker was unable to load the initial script, so
360         // shut it down right here.
361         delete this;
362         return;
363     }
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();
374
375     if (m_attachDevToolsOnStart)
376         workerThread()->postDebuggerTask(createCrossThreadTask(connectToWorkerContextInspectorTask, true));
377
378     workerThread()->start();
379     if (client())
380         client()->workerScriptLoaded();
381 }
382
383 void WebSharedWorkerImpl::terminateWorkerContext()
384 {
385     stopWorkerThread();
386 }
387
388 void WebSharedWorkerImpl::clientDestroyed()
389 {
390     m_client.clear();
391 }
392
393 void WebSharedWorkerImpl::pauseWorkerContextOnStart()
394 {
395     m_pauseWorkerContextOnStart = true;
396 }
397
398 static void resumeWorkerContextTask(ExecutionContext* context, bool)
399 {
400     toWorkerGlobalScope(context)->workerInspectorController()->resume();
401 }
402
403 void WebSharedWorkerImpl::resumeWorkerContext()
404 {
405     m_pauseWorkerContextOnStart = false;
406     if (workerThread())
407         workerThread()->postDebuggerTask(createCrossThreadTask(resumeWorkerContextTask, true));
408 }
409
410 void WebSharedWorkerImpl::attachDevTools()
411 {
412     if (workerThread())
413         workerThread()->postDebuggerTask(createCrossThreadTask(connectToWorkerContextInspectorTask, true));
414     else
415         m_attachDevToolsOnStart = true;
416 }
417
418 static void reconnectToWorkerContextInspectorTask(ExecutionContext* context, const String& savedState)
419 {
420     WorkerInspectorController* ic = toWorkerGlobalScope(context)->workerInspectorController();
421     ic->restoreInspectorStateFromCookie(savedState);
422     ic->resume();
423 }
424
425 void WebSharedWorkerImpl::reattachDevTools(const WebString& savedState)
426 {
427     workerThread()->postDebuggerTask(createCrossThreadTask(reconnectToWorkerContextInspectorTask, String(savedState)));
428 }
429
430 static void disconnectFromWorkerContextInspectorTask(ExecutionContext* context, bool)
431 {
432     toWorkerGlobalScope(context)->workerInspectorController()->disconnectFrontend();
433 }
434
435 void WebSharedWorkerImpl::detachDevTools()
436 {
437     m_attachDevToolsOnStart = false;
438     workerThread()->postDebuggerTask(createCrossThreadTask(disconnectFromWorkerContextInspectorTask, true));
439 }
440
441 static void dispatchOnInspectorBackendTask(ExecutionContext* context, const String& message)
442 {
443     toWorkerGlobalScope(context)->workerInspectorController()->dispatchMessageFromFrontend(message);
444 }
445
446 void WebSharedWorkerImpl::dispatchDevToolsMessage(const WebString& message)
447 {
448     if (m_askedToTerminate)
449         return;
450     workerThread()->postDebuggerTask(createCrossThreadTask(dispatchOnInspectorBackendTask, String(message)));
451     workerThread()->interruptAndDispatchInspectorCommands();
452 }
453
454 WebSharedWorker* WebSharedWorker::create(WebSharedWorkerClient* client)
455 {
456     return new WebSharedWorkerImpl(client);
457 }
458
459 } // namespace blink