tizen beta release
[framework/web/webkit-efl.git] / Source / WebCore / workers / DefaultSharedWorkerRepository.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
33 #if ENABLE(SHARED_WORKERS)
34
35 #include "DefaultSharedWorkerRepository.h"
36
37 #include "ActiveDOMObject.h"
38 #include "CrossThreadTask.h"
39 #include "Document.h"
40 #include "ExceptionCode.h"
41 #include "InspectorInstrumentation.h"
42 #include "MessageEvent.h"
43 #include "MessagePort.h"
44 #include "NotImplemented.h"
45 #include "PlatformString.h"
46 #include "ScriptCallStack.h"
47 #include "SecurityOrigin.h"
48 #include "SecurityOriginHash.h"
49 #include "SharedWorker.h"
50 #include "SharedWorkerContext.h"
51 #include "SharedWorkerRepository.h"
52 #include "SharedWorkerThread.h"
53 #include "WorkerLoaderProxy.h"
54 #include "WorkerReportingProxy.h"
55 #include "WorkerScriptLoader.h"
56 #include "WorkerScriptLoaderClient.h"
57 #include <wtf/HashSet.h>
58 #include <wtf/Threading.h>
59
60 namespace WebCore {
61
62 class SharedWorkerProxy : public ThreadSafeRefCounted<SharedWorkerProxy>, public WorkerLoaderProxy, public WorkerReportingProxy {
63 public:
64     static PassRefPtr<SharedWorkerProxy> create(const String& name, const KURL& url, PassRefPtr<SecurityOrigin> origin) { return adoptRef(new SharedWorkerProxy(name, url, origin)); }
65
66     void setThread(PassRefPtr<SharedWorkerThread> thread) { m_thread = thread; }
67     SharedWorkerThread* thread() { return m_thread.get(); }
68     bool isClosing() const { return m_closing; }
69     KURL url() const
70     {
71         // Don't use m_url.copy() because it isn't a threadsafe method.
72         return KURL(ParsedURLString, m_url.string().isolatedCopy());
73     }
74
75     String name() const { return m_name.isolatedCopy(); }
76     bool matches(const String& name, PassRefPtr<SecurityOrigin> origin, const KURL& urlToMatch) const;
77
78     // WorkerLoaderProxy
79     virtual void postTaskToLoader(PassOwnPtr<ScriptExecutionContext::Task>);
80     virtual void postTaskForModeToWorkerContext(PassOwnPtr<ScriptExecutionContext::Task>, const String&);
81
82     // WorkerReportingProxy
83     virtual void postExceptionToWorkerObject(const String& errorMessage, int lineNumber, const String& sourceURL);
84     virtual void postConsoleMessageToWorkerObject(MessageSource, MessageType, MessageLevel, const String& message, int lineNumber, const String& sourceURL);
85 #if ENABLE(INSPECTOR)
86     virtual void postMessageToPageInspector(const String&);
87     virtual void updateInspectorStateCookie(const String&);
88 #endif
89     virtual void workerContextClosed();
90     virtual void workerContextDestroyed();
91
92     // Updates the list of the worker's documents, per section 4.5 of the WebWorkers spec.
93     void addToWorkerDocuments(ScriptExecutionContext*);
94
95     bool isInWorkerDocuments(Document* document) { return m_workerDocuments.contains(document); }
96
97     // Removes a detached document from the list of worker's documents. May set the closing flag if this is the last document in the list.
98     void documentDetached(Document*);
99
100 private:
101     SharedWorkerProxy(const String& name, const KURL&, PassRefPtr<SecurityOrigin>);
102     void close();
103
104     bool m_closing;
105     String m_name;
106     KURL m_url;
107     // The thread is freed when the proxy is destroyed, so we need to make sure that the proxy stays around until the SharedWorkerContext exits.
108     RefPtr<SharedWorkerThread> m_thread;
109     RefPtr<SecurityOrigin> m_origin;
110     HashSet<Document*> m_workerDocuments;
111     // Ensures exclusive access to the worker documents. Must not grab any other locks (such as the DefaultSharedWorkerRepository lock) while holding this one.
112     Mutex m_workerDocumentsLock;
113 };
114
115 SharedWorkerProxy::SharedWorkerProxy(const String& name, const KURL& url, PassRefPtr<SecurityOrigin> origin)
116     : m_closing(false)
117     , m_name(name.isolatedCopy())
118     , m_url(url.copy())
119     , m_origin(origin)
120 {
121     // We should be the sole owner of the SecurityOrigin, as we will free it on another thread.
122     ASSERT(m_origin->hasOneRef());
123 }
124
125 bool SharedWorkerProxy::matches(const String& name, PassRefPtr<SecurityOrigin> origin, const KURL& urlToMatch) const
126 {
127     // If the origins don't match, or the names don't match, then this is not the proxy we are looking for.
128     if (!origin->equal(m_origin.get()))
129         return false;
130
131     // If the names are both empty, compares the URLs instead per the Web Workers spec.
132     if (name.isEmpty() && m_name.isEmpty())
133         return urlToMatch == url();
134
135     return name == m_name;
136 }
137
138 void SharedWorkerProxy::postTaskToLoader(PassOwnPtr<ScriptExecutionContext::Task> task)
139 {
140     MutexLocker lock(m_workerDocumentsLock);
141
142     if (isClosing())
143         return;
144
145     // If we aren't closing, then we must have at least one document.
146     ASSERT(m_workerDocuments.size());
147
148     // Just pick an arbitrary active document from the HashSet and pass load requests to it.
149     // FIXME: Do we need to deal with the case where the user closes the document mid-load, via a shadow document or some other solution?
150     Document* document = *(m_workerDocuments.begin());
151     document->postTask(task);
152 }
153
154 void SharedWorkerProxy::postTaskForModeToWorkerContext(PassOwnPtr<ScriptExecutionContext::Task> task, const String& mode)
155 {
156     if (isClosing())
157         return;
158     ASSERT(m_thread);
159     m_thread->runLoop().postTaskForMode(task, mode);
160 }
161
162 static void postExceptionTask(ScriptExecutionContext* context, const String& errorMessage, int lineNumber, const String& sourceURL)
163 {
164     context->reportException(errorMessage, lineNumber, sourceURL, 0);
165 }
166
167 void SharedWorkerProxy::postExceptionToWorkerObject(const String& errorMessage, int lineNumber, const String& sourceURL)
168 {
169     MutexLocker lock(m_workerDocumentsLock);
170     for (HashSet<Document*>::iterator iter = m_workerDocuments.begin(); iter != m_workerDocuments.end(); ++iter)
171         (*iter)->postTask(createCallbackTask(&postExceptionTask, errorMessage, lineNumber, sourceURL));
172 }
173
174 static void postConsoleMessageTask(ScriptExecutionContext* document, MessageSource source, MessageType type, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceURL)
175 {
176     document->addMessage(source, type, level, message, lineNumber, sourceURL, 0);
177 }
178
179 void SharedWorkerProxy::postConsoleMessageToWorkerObject(MessageSource source, MessageType type, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
180 {
181     MutexLocker lock(m_workerDocumentsLock);
182     for (HashSet<Document*>::iterator iter = m_workerDocuments.begin(); iter != m_workerDocuments.end(); ++iter)
183         (*iter)->postTask(createCallbackTask(&postConsoleMessageTask, source, type, level, message, lineNumber, sourceURL));
184 }
185
186 #if ENABLE(INSPECTOR)
187 void SharedWorkerProxy::postMessageToPageInspector(const String&)
188 {
189     notImplemented();
190 }
191
192 void SharedWorkerProxy::updateInspectorStateCookie(const String&)
193 {
194     notImplemented();
195 }
196 #endif
197
198 void SharedWorkerProxy::workerContextClosed()
199 {
200     if (isClosing())
201         return;
202     close();
203 }
204
205 void SharedWorkerProxy::workerContextDestroyed()
206 {
207     // The proxy may be freed by this call, so do not reference it any further.
208     DefaultSharedWorkerRepository::instance().removeProxy(this);
209 }
210
211 void SharedWorkerProxy::addToWorkerDocuments(ScriptExecutionContext* context)
212 {
213     // Nested workers are not yet supported, so passed-in context should always be a Document.
214     ASSERT(context->isDocument());
215     ASSERT(!isClosing());
216     MutexLocker lock(m_workerDocumentsLock);
217     Document* document = static_cast<Document*>(context);
218     m_workerDocuments.add(document);
219 }
220
221 void SharedWorkerProxy::documentDetached(Document* document)
222 {
223     if (isClosing())
224         return;
225     // Remove the document from our set (if it's there) and if that was the last document in the set, mark the proxy as closed.
226     MutexLocker lock(m_workerDocumentsLock);
227     m_workerDocuments.remove(document);
228     if (!m_workerDocuments.size())
229         close();
230 }
231
232 void SharedWorkerProxy::close()
233 {
234     ASSERT(!isClosing());
235     m_closing = true;
236     // Stop the worker thread - the proxy will stay around until we get workerThreadExited() notification.
237     if (m_thread)
238         m_thread->stop();
239 }
240
241 class SharedWorkerConnectTask : public ScriptExecutionContext::Task {
242 public:
243     static PassOwnPtr<SharedWorkerConnectTask> create(PassOwnPtr<MessagePortChannel> channel)
244     {
245         return adoptPtr(new SharedWorkerConnectTask(channel));
246     }
247
248 private:
249     SharedWorkerConnectTask(PassOwnPtr<MessagePortChannel> channel)
250         : m_channel(channel)
251     {
252     }
253
254     virtual void performTask(ScriptExecutionContext* scriptContext)
255     {
256         RefPtr<MessagePort> port = MessagePort::create(*scriptContext);
257         port->entangle(m_channel.release());
258         ASSERT(scriptContext->isWorkerContext());
259         WorkerContext* workerContext = static_cast<WorkerContext*>(scriptContext);
260         // Since close() stops the thread event loop, this should not ever get called while closing.
261         ASSERT(!workerContext->isClosing());
262         ASSERT(workerContext->isSharedWorkerContext());
263         workerContext->dispatchEvent(createConnectEvent(port));
264     }
265
266     OwnPtr<MessagePortChannel> m_channel;
267 };
268
269 // Loads the script on behalf of a worker.
270 class SharedWorkerScriptLoader : public RefCounted<SharedWorkerScriptLoader>, private WorkerScriptLoaderClient {
271 public:
272     SharedWorkerScriptLoader(PassRefPtr<SharedWorker>, PassOwnPtr<MessagePortChannel>, PassRefPtr<SharedWorkerProxy>);
273     void load(const KURL&);
274
275 private:
276     // WorkerScriptLoaderClient callbacks
277     virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse&);
278     virtual void notifyFinished();
279
280     RefPtr<SharedWorker> m_worker;
281     OwnPtr<MessagePortChannel> m_port;
282     RefPtr<SharedWorkerProxy> m_proxy;
283     RefPtr<WorkerScriptLoader> m_scriptLoader;
284 };
285
286 SharedWorkerScriptLoader::SharedWorkerScriptLoader(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, PassRefPtr<SharedWorkerProxy> proxy)
287     : m_worker(worker)
288     , m_port(port)
289     , m_proxy(proxy)
290 {
291 }
292
293 void SharedWorkerScriptLoader::load(const KURL& url)
294 {
295     // Stay alive (and keep the SharedWorker and JS wrapper alive) until the load finishes.
296     this->ref();
297     m_worker->setPendingActivity(m_worker.get());
298
299     // Mark this object as active for the duration of the load.
300     m_scriptLoader = WorkerScriptLoader::create();
301 #if PLATFORM(CHROMIUM)
302     m_scriptLoader->setTargetType(ResourceRequest::TargetIsSharedWorker);
303 #endif
304     m_scriptLoader->loadAsynchronously(m_worker->scriptExecutionContext(), url, DenyCrossOriginRequests, this);
305 }
306
307 void SharedWorkerScriptLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse&)
308 {
309     InspectorInstrumentation::didReceiveScriptResponse(m_worker->scriptExecutionContext(), identifier);
310 }
311
312 void SharedWorkerScriptLoader::notifyFinished()
313 {
314     // FIXME: This method is not guaranteed to be invoked if we are loading from WorkerContext (see comment for WorkerScriptLoaderClient::notifyFinished()).
315     // We need to address this before supporting nested workers.
316
317     // Hand off the just-loaded code to the repository to start up the worker thread.
318     if (m_scriptLoader->failed())
319         m_worker->dispatchEvent(Event::create(eventNames().errorEvent, false, true));
320     else {
321         InspectorInstrumentation::scriptImported(m_worker->scriptExecutionContext(), m_scriptLoader->identifier(), m_scriptLoader->script());
322         DefaultSharedWorkerRepository::instance().workerScriptLoaded(*m_proxy, m_worker->scriptExecutionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), m_port.release());
323     }
324     m_worker->unsetPendingActivity(m_worker.get());
325     this->deref(); // This frees this object - must be the last action in this function.
326 }
327
328 DefaultSharedWorkerRepository& DefaultSharedWorkerRepository::instance()
329 {
330     AtomicallyInitializedStatic(DefaultSharedWorkerRepository*, instance = new DefaultSharedWorkerRepository);
331     return *instance;
332 }
333
334 void DefaultSharedWorkerRepository::workerScriptLoaded(SharedWorkerProxy& proxy, const String& userAgent, const String& workerScript, PassOwnPtr<MessagePortChannel> port)
335 {
336     MutexLocker lock(m_lock);
337     if (proxy.isClosing())
338         return;
339
340     // Another loader may have already started up a thread for this proxy - if so, just send a connect to the pre-existing thread.
341     if (!proxy.thread()) {
342         RefPtr<SharedWorkerThread> thread = SharedWorkerThread::create(proxy.name(), proxy.url(), userAgent, workerScript, proxy, proxy, DontPauseWorkerContextOnStart);
343         proxy.setThread(thread);
344         thread->start();
345     }
346     proxy.thread()->runLoop().postTask(SharedWorkerConnectTask::create(port));
347 }
348
349 bool SharedWorkerRepository::isAvailable()
350 {
351     // SharedWorkers are enabled on the default WebKit platform.
352     return true;
353 }
354
355 void SharedWorkerRepository::connect(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, const KURL& url, const String& name, ExceptionCode& ec)
356 {
357     DefaultSharedWorkerRepository::instance().connectToWorker(worker, port, url, name, ec);
358 }
359
360 void SharedWorkerRepository::documentDetached(Document* document)
361 {
362     DefaultSharedWorkerRepository::instance().documentDetached(document);
363 }
364
365 bool SharedWorkerRepository::hasSharedWorkers(Document* document)
366 {
367     return DefaultSharedWorkerRepository::instance().hasSharedWorkers(document);
368 }
369
370 bool DefaultSharedWorkerRepository::hasSharedWorkers(Document* document)
371 {
372     MutexLocker lock(m_lock);
373     for (unsigned i = 0; i < m_proxies.size(); i++) {
374         if (m_proxies[i]->isInWorkerDocuments(document))
375             return true;
376     }
377     return false;
378 }
379
380 void DefaultSharedWorkerRepository::removeProxy(SharedWorkerProxy* proxy)
381 {
382     MutexLocker lock(m_lock);
383     for (unsigned i = 0; i < m_proxies.size(); i++) {
384         if (proxy == m_proxies[i].get()) {
385             m_proxies.remove(i);
386             return;
387         }
388     }
389 }
390
391 void DefaultSharedWorkerRepository::documentDetached(Document* document)
392 {
393     MutexLocker lock(m_lock);
394     for (unsigned i = 0; i < m_proxies.size(); i++)
395         m_proxies[i]->documentDetached(document);
396 }
397
398 void DefaultSharedWorkerRepository::connectToWorker(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, const KURL& url, const String& name, ExceptionCode& ec)
399 {
400     MutexLocker lock(m_lock);
401     ASSERT(worker->scriptExecutionContext()->securityOrigin()->canAccess(SecurityOrigin::create(url).get()));
402     // Fetch a proxy corresponding to this SharedWorker.
403     RefPtr<SharedWorkerProxy> proxy = getProxy(name, url);
404     proxy->addToWorkerDocuments(worker->scriptExecutionContext());
405     if (proxy->url() != url) {
406         // Proxy already existed under alternate URL - return an error.
407         ec = URL_MISMATCH_ERR;
408         return;
409     }
410     // If proxy is already running, just connect to it - otherwise, kick off a loader to load the script.
411     if (proxy->thread())
412         proxy->thread()->runLoop().postTask(SharedWorkerConnectTask::create(port));
413     else {
414         RefPtr<SharedWorkerScriptLoader> loader = adoptRef(new SharedWorkerScriptLoader(worker, port, proxy.release()));
415         loader->load(url);
416     }
417 }
418
419 // Creates a new SharedWorkerProxy or returns an existing one from the repository. Must only be called while the repository mutex is held.
420 PassRefPtr<SharedWorkerProxy> DefaultSharedWorkerRepository::getProxy(const String& name, const KURL& url)
421 {
422     // Look for an existing worker, and create one if it doesn't exist.
423     // Items in the cache are freed on another thread, so do a threadsafe copy of the URL before creating the origin,
424     // to make sure no references to external strings linger.
425     RefPtr<SecurityOrigin> origin = SecurityOrigin::create(KURL(ParsedURLString, url.string().isolatedCopy()));
426     for (unsigned i = 0; i < m_proxies.size(); i++) {
427         if (!m_proxies[i]->isClosing() && m_proxies[i]->matches(name, origin, url))
428             return m_proxies[i];
429     }
430     // Proxy is not in the repository currently - create a new one.
431     RefPtr<SharedWorkerProxy> proxy = SharedWorkerProxy::create(name, url, origin.release());
432     m_proxies.append(proxy);
433     return proxy.release();
434 }
435
436 DefaultSharedWorkerRepository::DefaultSharedWorkerRepository()
437 {
438 }
439
440 DefaultSharedWorkerRepository::~DefaultSharedWorkerRepository()
441 {
442 }
443
444 } // namespace WebCore
445
446 #endif // ENABLE(SHARED_WORKERS)