Update To 11.40.268.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/WorkerInspectorProxy.h"
50 #include "core/workers/WorkerScriptLoader.h"
51 #include "core/workers/WorkerThreadStartupData.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/WebDevToolsAgent.h"
64 #include "public/web/WebFrame.h"
65 #include "public/web/WebSettings.h"
66 #include "public/web/WebView.h"
67 #include "public/web/WebWorkerPermissionClientProxy.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_workerInspectorProxy(WorkerInspectorProxy::create())
158     , m_client(WeakReference<WebSharedWorkerClient>::create(client))
159     , m_clientWeakPtr(WeakPtr<WebSharedWorkerClient>(m_client))
160     , m_pauseWorkerContextOnStart(false)
161     , m_isPausedOnStart(false)
162 {
163     initializeWebKitStaticValues();
164 }
165
166 WebSharedWorkerImpl::~WebSharedWorkerImpl()
167 {
168     ASSERT(m_webView);
169     // Detach the client before closing the view to avoid getting called back.
170     toWebLocalFrameImpl(m_mainFrame)->setClient(0);
171
172     m_webView->close();
173     m_mainFrame->close();
174 }
175
176 void WebSharedWorkerImpl::stopWorkerThread()
177 {
178     if (m_askedToTerminate)
179         return;
180     m_askedToTerminate = true;
181     if (m_mainScriptLoader) {
182         m_mainScriptLoader->cancel();
183         m_mainScriptLoader.clear();
184         if (client())
185             client()->workerScriptLoadFailed();
186         delete this;
187         return;
188     }
189     if (m_workerThread)
190         m_workerThread->stop();
191     m_workerInspectorProxy->workerThreadTerminated();
192 }
193
194 void WebSharedWorkerImpl::initializeLoader()
195 {
196     // Create 'shadow page'. This page is never displayed, it is used to proxy the
197     // loading requests from the worker context to the rest of WebKit and Chromium
198     // infrastructure.
199     ASSERT(!m_webView);
200     m_webView = WebView::create(0);
201     m_webView->settings()->setOfflineWebApplicationCacheEnabled(RuntimeEnabledFeatures::applicationCacheEnabled());
202     // FIXME: http://crbug.com/363843. This needs to find a better way to
203     // not create graphics layers.
204     m_webView->settings()->setAcceleratedCompositingEnabled(false);
205     // FIXME: Settings information should be passed to the Worker process from Browser process when the worker
206     // is created (similar to RenderThread::OnCreateNewView).
207     m_mainFrame = WebLocalFrame::create(this);
208     m_webView->setMainFrame(m_mainFrame);
209     m_webView->setDevToolsAgentClient(this);
210
211     // If we were asked to pause worker context on start and wait for debugger then it is the good time to do that.
212     client()->workerReadyForInspection();
213     if (m_pauseWorkerContextOnStart) {
214         m_isPausedOnStart = true;
215         return;
216     }
217     loadShadowPage();
218 }
219
220 WebApplicationCacheHost* WebSharedWorkerImpl::createApplicationCacheHost(WebLocalFrame*, WebApplicationCacheHostClient* appcacheHostClient)
221 {
222     if (client())
223         return client()->createApplicationCacheHost(appcacheHostClient);
224     return 0;
225 }
226
227 void WebSharedWorkerImpl::loadShadowPage()
228 {
229     WebLocalFrameImpl* webFrame = toWebLocalFrameImpl(m_webView->mainFrame());
230
231     // Construct substitute data source for the 'shadow page'. We only need it
232     // to have same origin as the worker so the loading checks work correctly.
233     CString content("");
234     RefPtr<SharedBuffer> buffer(SharedBuffer::create(content.data(), content.length()));
235     webFrame->frame()->loader().load(FrameLoadRequest(0, ResourceRequest(m_url), SubstituteData(buffer, "text/html", "UTF-8", KURL())));
236 }
237
238 void WebSharedWorkerImpl::didFinishDocumentLoad(WebLocalFrame* frame)
239 {
240     ASSERT(!m_loadingDocument);
241     ASSERT(!m_mainScriptLoader);
242     m_mainScriptLoader = Loader::create();
243     m_loadingDocument = toWebLocalFrameImpl(frame)->frame()->document();
244     m_mainScriptLoader->load(
245         m_loadingDocument.get(),
246         m_url,
247         bind(&WebSharedWorkerImpl::didReceiveScriptLoaderResponse, this),
248         bind(&WebSharedWorkerImpl::onScriptLoaderFinished, this));
249 }
250
251 void WebSharedWorkerImpl::sendMessageToInspectorFrontend(const WebString& message)
252 {
253     client()->dispatchDevToolsMessage(message);
254 }
255
256 void WebSharedWorkerImpl::resumeStartup()
257 {
258     bool isPausedOnStart = m_isPausedOnStart;
259     m_isPausedOnStart = false;
260     if (isPausedOnStart)
261         loadShadowPage();
262 }
263
264 void WebSharedWorkerImpl::saveAgentRuntimeState(const WebString& inspectorState)
265 {
266     client()->saveDevToolsAgentState(inspectorState);
267 }
268
269 // WorkerReportingProxy --------------------------------------------------------
270
271 void WebSharedWorkerImpl::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL)
272 {
273     // Not suppported in SharedWorker.
274 }
275
276 void WebSharedWorkerImpl::reportConsoleMessage(PassRefPtrWillBeRawPtr<ConsoleMessage>)
277 {
278     // Not supported in SharedWorker.
279 }
280
281 void WebSharedWorkerImpl::postMessageToPageInspector(const String& message)
282 {
283     toWebLocalFrameImpl(m_mainFrame)->frame()->document()->postInspectorTask(createCrossThreadTask(&WebSharedWorkerImpl::postMessageToPageInspectorOnMainThread, this, message));
284 }
285
286 void WebSharedWorkerImpl::postMessageToPageInspectorOnMainThread(const String& message)
287 {
288     WorkerInspectorProxy::PageInspector* pageInspector = m_workerInspectorProxy->pageInspector();
289     if (!pageInspector)
290         return;
291     pageInspector->dispatchMessageFromWorker(message);
292
293 }
294
295 void WebSharedWorkerImpl::workerGlobalScopeClosed()
296 {
297     callOnMainThread(bind(&WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread, this));
298 }
299
300 void WebSharedWorkerImpl::workerGlobalScopeClosedOnMainThread()
301 {
302     if (client())
303         client()->workerContextClosed();
304
305     stopWorkerThread();
306 }
307
308 void WebSharedWorkerImpl::workerGlobalScopeStarted(WorkerGlobalScope*)
309 {
310 }
311
312 void WebSharedWorkerImpl::workerThreadTerminated()
313 {
314     callOnMainThread(bind(&WebSharedWorkerImpl::workerThreadTerminatedOnMainThread, this));
315 }
316
317 void WebSharedWorkerImpl::workerThreadTerminatedOnMainThread()
318 {
319     if (client())
320         client()->workerContextDestroyed();
321     // The lifetime of this proxy is controlled by the worker context.
322     delete this;
323 }
324
325 // WorkerLoaderProxy -----------------------------------------------------------
326
327 void WebSharedWorkerImpl::postTaskToLoader(PassOwnPtr<ExecutionContextTask> task)
328 {
329     toWebLocalFrameImpl(m_mainFrame)->frame()->document()->postTask(task);
330 }
331
332 bool WebSharedWorkerImpl::postTaskToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask> task)
333 {
334     m_workerThread->postTask(task);
335     return true;
336 }
337
338 void WebSharedWorkerImpl::connect(WebMessagePortChannel* webChannel)
339 {
340     workerThread()->postTask(
341         createCrossThreadTask(&connectTask, adoptPtr(webChannel)));
342 }
343
344 void WebSharedWorkerImpl::connectTask(ExecutionContext* context, PassOwnPtr<WebMessagePortChannel> channel)
345 {
346     // Wrap the passed-in channel in a MessagePort, and send it off via a connect event.
347     RefPtrWillBeRawPtr<MessagePort> port = MessagePort::create(*context);
348     port->entangle(channel);
349     WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
350     ASSERT_WITH_SECURITY_IMPLICATION(workerGlobalScope->isSharedWorkerGlobalScope());
351     workerGlobalScope->dispatchEvent(createConnectEvent(port.release()));
352 }
353
354 void WebSharedWorkerImpl::startWorkerContext(const WebURL& url, const WebString& name, const WebString& contentSecurityPolicy, WebContentSecurityPolicyType policyType)
355 {
356     m_url = url;
357     m_name = name;
358     m_contentSecurityPolicy = contentSecurityPolicy;
359     m_policyType = policyType;
360     initializeLoader();
361 }
362
363 void WebSharedWorkerImpl::didReceiveScriptLoaderResponse()
364 {
365     InspectorInstrumentation::didReceiveScriptResponse(m_loadingDocument.get(), m_mainScriptLoader->identifier());
366     if (client())
367         client()->selectAppCacheID(m_mainScriptLoader->appCacheID());
368 }
369
370 void WebSharedWorkerImpl::onScriptLoaderFinished()
371 {
372     ASSERT(m_loadingDocument);
373     ASSERT(m_mainScriptLoader);
374     if (m_askedToTerminate)
375         return;
376     if (m_mainScriptLoader->failed()) {
377         m_mainScriptLoader->cancel();
378         if (client())
379             client()->workerScriptLoadFailed();
380
381         // The SharedWorker was unable to load the initial script, so
382         // shut it down right here.
383         delete this;
384         return;
385     }
386
387     Document* document = toWebLocalFrameImpl(m_mainFrame)->frame()->document();
388     WorkerThreadStartMode startMode = DontPauseWorkerGlobalScopeOnStart;
389     if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(document))
390         startMode = PauseWorkerGlobalScopeOnStart;
391
392     // FIXME: this document's origin is pristine and without any extra privileges. (crbug.com/254993)
393     SecurityOrigin* starterOrigin = document->securityOrigin();
394
395     OwnPtrWillBeRawPtr<WorkerClients> workerClients = WorkerClients::create();
396     provideLocalFileSystemToWorker(workerClients.get(), LocalFileSystemClient::create());
397     WebSecurityOrigin webSecurityOrigin(m_loadingDocument->securityOrigin());
398     providePermissionClientToWorker(workerClients.get(), adoptPtr(client()->createWorkerPermissionClientProxy(webSecurityOrigin)));
399     OwnPtrWillBeRawPtr<WorkerThreadStartupData> startupData = WorkerThreadStartupData::create(m_url, m_loadingDocument->userAgent(m_url), m_mainScriptLoader->script(), startMode, m_contentSecurityPolicy, static_cast<ContentSecurityPolicyHeaderType>(m_policyType), starterOrigin, workerClients.release());
400     setWorkerThread(SharedWorkerThread::create(m_name, *this, *this, startupData.release()));
401     InspectorInstrumentation::scriptImported(m_loadingDocument.get(), m_mainScriptLoader->identifier(), m_mainScriptLoader->script());
402     m_mainScriptLoader.clear();
403
404     workerThread()->start();
405     m_workerInspectorProxy->workerThreadCreated(m_loadingDocument.get(), workerThread(), m_url);
406     if (client())
407         client()->workerScriptLoaded();
408 }
409
410 void WebSharedWorkerImpl::terminateWorkerContext()
411 {
412     stopWorkerThread();
413 }
414
415 void WebSharedWorkerImpl::clientDestroyed()
416 {
417     m_client.clear();
418 }
419
420 void WebSharedWorkerImpl::pauseWorkerContextOnStart()
421 {
422     m_pauseWorkerContextOnStart = true;
423 }
424
425 void WebSharedWorkerImpl::attachDevTools(const WebString& hostId)
426 {
427     WebDevToolsAgent* devtoolsAgent = m_webView->devToolsAgent();
428     if (devtoolsAgent)
429         devtoolsAgent->attach(hostId);
430 }
431
432 void WebSharedWorkerImpl::reattachDevTools(const WebString& hostId, const WebString& savedState)
433 {
434     WebDevToolsAgent* devtoolsAgent = m_webView->devToolsAgent();
435     if (devtoolsAgent)
436         devtoolsAgent->reattach(hostId, savedState);
437     resumeStartup();
438 }
439
440 void WebSharedWorkerImpl::detachDevTools()
441 {
442     WebDevToolsAgent* devtoolsAgent = m_webView->devToolsAgent();
443     if (devtoolsAgent)
444         devtoolsAgent->detach();
445 }
446
447 void WebSharedWorkerImpl::dispatchDevToolsMessage(const WebString& message)
448 {
449     if (m_askedToTerminate)
450         return;
451     WebDevToolsAgent* devtoolsAgent = m_webView->devToolsAgent();
452     if (devtoolsAgent)
453         devtoolsAgent->dispatchOnInspectorBackend(message);
454 }
455
456 WebSharedWorker* WebSharedWorker::create(WebSharedWorkerClient* client)
457 {
458     return new WebSharedWorkerImpl(client);
459 }
460
461 } // namespace blink