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 "SharedWorkerRepository.h"
36
37#include "Event.h"
38#include "EventNames.h"
39#include "MessagePortChannel.h"
40#include "PlatformMessagePortChannel.h"
41#include "ScriptExecutionContext.h"
42#include "SharedWorker.h"
43#include "WebFrameClient.h"
44#include "WebFrameImpl.h"
45#include "WebKit.h"
46#include "WebKitClient.h"
47#include "WebMessagePortChannel.h"
48#include "WebSharedWorker.h"
49#include "WebSharedWorkerRepository.h"
50#include "WebString.h"
51#include "WebURL.h"
52#include "WorkerScriptLoader.h"
53#include "WorkerScriptLoaderClient.h"
54
55namespace WebCore {
56
57class Document;
58using WebKit::WebFrameImpl;
59using WebKit::WebMessagePortChannel;
60using WebKit::WebSharedWorker;
61using WebKit::WebSharedWorkerRepository;
62
63// Callback class that keeps the SharedWorker and WebSharedWorker objects alive while loads are potentially happening, and also translates load errors into error events on the worker.
64class SharedWorkerScriptLoader : private WorkerScriptLoaderClient, private WebSharedWorker::ConnectListener {
65public:
66    SharedWorkerScriptLoader(PassRefPtr<SharedWorker> worker, const KURL& url, const String& name, PassOwnPtr<MessagePortChannel> port, PassOwnPtr<WebSharedWorker> webWorker)
67        : m_worker(worker)
68        , m_url(url)
69        , m_name(name)
70        , m_webWorker(webWorker)
71        , m_port(port)
72        , m_loading(false)
73    {
74    }
75
76    ~SharedWorkerScriptLoader();
77    void load();
78    static void stopAllLoadersForContext(ScriptExecutionContext*);
79
80private:
81    // WorkerScriptLoaderClient callback
82    virtual void notifyFinished();
83
84    virtual void connected();
85
86    const ScriptExecutionContext* loadingContext() { return m_worker->scriptExecutionContext(); }
87
88    void sendConnect();
89
90    RefPtr<SharedWorker> m_worker;
91    KURL m_url;
92    String m_name;
93    OwnPtr<WebSharedWorker> m_webWorker;
94    OwnPtr<MessagePortChannel> m_port;
95    WorkerScriptLoader m_scriptLoader;
96    bool m_loading;
97};
98
99static Vector<SharedWorkerScriptLoader*>& pendingLoaders()
100{
101    AtomicallyInitializedStatic(Vector<SharedWorkerScriptLoader*>&, loaders = *new Vector<SharedWorkerScriptLoader*>);
102    return loaders;
103}
104
105void SharedWorkerScriptLoader::stopAllLoadersForContext(ScriptExecutionContext* context)
106{
107    // Walk our list of pending loaders and shutdown any that belong to this context.
108    Vector<SharedWorkerScriptLoader*>& loaders = pendingLoaders();
109    for (unsigned i = 0; i < loaders.size(); ) {
110        SharedWorkerScriptLoader* loader = loaders[i];
111        if (context == loader->loadingContext()) {
112            loaders.remove(i);
113            delete loader;
114        } else
115            i++;
116    }
117}
118
119SharedWorkerScriptLoader::~SharedWorkerScriptLoader()
120{
121    if (m_loading)
122        m_worker->unsetPendingActivity(m_worker.get());
123}
124
125void SharedWorkerScriptLoader::load()
126{
127    ASSERT(!m_loading);
128    // If the shared worker is not yet running, load the script resource for it, otherwise just send it a connect event.
129    if (m_webWorker->isStarted())
130        sendConnect();
131    else {
132        m_scriptLoader.loadAsynchronously(m_worker->scriptExecutionContext(), m_url, DenyCrossOriginRequests, this);
133        // Keep the worker + JS wrapper alive until the resource load is complete in case we need to dispatch an error event.
134        m_worker->setPendingActivity(m_worker.get());
135        m_loading = true;
136    }
137}
138
139// Extracts a WebMessagePortChannel from a MessagePortChannel.
140static WebMessagePortChannel* getWebPort(PassOwnPtr<MessagePortChannel> port)
141{
142    // Extract the WebMessagePortChannel to send to the worker.
143    PlatformMessagePortChannel* platformChannel = port->channel();
144    WebMessagePortChannel* webPort = platformChannel->webChannelRelease();
145    webPort->setClient(0);
146    return webPort;
147}
148
149void SharedWorkerScriptLoader::notifyFinished()
150{
151    if (m_scriptLoader.failed()) {
152        m_worker->dispatchEvent(Event::create(eventNames().errorEvent, false, true));
153        delete this;
154    } else {
155        // Pass the script off to the worker, then send a connect event.
156        m_webWorker->startWorkerContext(m_url, m_name, m_worker->scriptExecutionContext()->userAgent(m_url), m_scriptLoader.script());
157        sendConnect();
158    }
159}
160
161void SharedWorkerScriptLoader::sendConnect()
162{
163    // Send the connect event off, and linger until it is done sending.
164    m_webWorker->connect(getWebPort(m_port.release()), this);
165}
166
167void SharedWorkerScriptLoader::connected()
168{
169    // Connect event has been sent, so free ourselves (this releases the SharedWorker so it can be freed as well if unreferenced).
170    delete this;
171}
172
173bool SharedWorkerRepository::isAvailable()
174{
175    // Allow the WebKitClient to determine if SharedWorkers are available.
176    return WebKit::webKitClient()->sharedWorkerRepository();
177}
178
179static WebSharedWorkerRepository::DocumentID getId(void* document)
180{
181    ASSERT(document);
182    return reinterpret_cast<WebSharedWorkerRepository::DocumentID>(document);
183}
184
185void SharedWorkerRepository::connect(PassRefPtr<SharedWorker> worker, PassOwnPtr<MessagePortChannel> port, const KURL& url, const String& name, ExceptionCode& ec)
186{
187    // This should not be callable unless there's a SharedWorkerRepository for
188    // this context (since isAvailable() should have returned null).
189    ASSERT(WebKit::webKitClient()->sharedWorkerRepository());
190
191    // No nested workers (for now) - connect() should only be called from document context.
192    ASSERT(worker->scriptExecutionContext()->isDocument());
193    Document* document = static_cast<Document*>(worker->scriptExecutionContext());
194    WebFrameImpl* webFrame = WebFrameImpl::fromFrame(document->frame());
195    OwnPtr<WebSharedWorker> webWorker;
196    webWorker = webFrame->client()->createSharedWorker(webFrame, url, name, getId(document));
197
198    if (!webWorker) {
199        // Existing worker does not match this url, so return an error back to the caller.
200        ec = URL_MISMATCH_ERR;
201        return;
202    }
203
204    WebKit::webKitClient()->sharedWorkerRepository()->addSharedWorker(
205        webWorker.get(), getId(document));
206
207    // The loader object manages its own lifecycle (and the lifecycles of the two worker objects).
208    // It will free itself once loading is completed.
209    SharedWorkerScriptLoader* loader = new SharedWorkerScriptLoader(worker, url, name, port.release(), webWorker.release());
210    loader->load();
211}
212
213void SharedWorkerRepository::documentDetached(Document* document)
214{
215    WebSharedWorkerRepository* repo = WebKit::webKitClient()->sharedWorkerRepository();
216    if (repo)
217        repo->documentDetached(getId(document));
218
219    // Stop the creation of any pending SharedWorkers for this context.
220    // FIXME: Need a way to invoke this for WorkerContexts as well when we support for nested workers.
221    SharedWorkerScriptLoader::stopAllLoadersForContext(document);
222}
223
224bool SharedWorkerRepository::hasSharedWorkers(Document* document)
225{
226    WebSharedWorkerRepository* repo = WebKit::webKitClient()->sharedWorkerRepository();
227    return repo && repo->hasSharedWorkers(getId(document));
228}
229
230
231
232} // namespace WebCore
233
234#endif // ENABLE(SHARED_WORKERS)
235