1/*
2 * Copyright (C) 2008 Apple 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
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 *
25 */
26
27#include "config.h"
28#include "MessagePort.h"
29
30#include "DOMWindow.h"
31#include "Document.h"
32#include "EventException.h"
33#include "EventNames.h"
34#include "ExceptionCode.h"
35#include "MessageEvent.h"
36#include "SecurityOrigin.h"
37#include "Timer.h"
38#include "WorkerContext.h"
39#include <wtf/text/AtomicString.h>
40
41namespace WebCore {
42
43MessagePort::MessagePort(ScriptExecutionContext& scriptExecutionContext)
44    : m_started(false)
45    , m_closed(false)
46    , m_scriptExecutionContext(&scriptExecutionContext)
47{
48    m_scriptExecutionContext->createdMessagePort(this);
49
50    // Don't need to call processMessagePortMessagesSoon() here, because the port will not be opened until start() is invoked.
51}
52
53MessagePort::~MessagePort()
54{
55    close();
56    if (m_scriptExecutionContext)
57        m_scriptExecutionContext->destroyedMessagePort(this);
58}
59
60void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, MessagePort* port, ExceptionCode& ec)
61{
62    MessagePortArray ports;
63    if (port)
64        ports.append(port);
65    postMessage(message, &ports, ec);
66}
67
68void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionCode& ec)
69{
70    if (!isEntangled())
71        return;
72    ASSERT(m_scriptExecutionContext);
73
74    OwnPtr<MessagePortChannelArray> channels;
75    // Make sure we aren't connected to any of the passed-in ports.
76    if (ports) {
77        for (unsigned int i = 0; i < ports->size(); ++i) {
78            MessagePort* dataPort = (*ports)[i].get();
79            if (dataPort == this || m_entangledChannel->isConnectedTo(dataPort)) {
80                ec = INVALID_STATE_ERR;
81                return;
82            }
83        }
84        channels = MessagePort::disentanglePorts(ports, ec);
85        if (ec)
86            return;
87    }
88    m_entangledChannel->postMessageToRemote(message, channels.release());
89}
90
91PassOwnPtr<MessagePortChannel> MessagePort::disentangle()
92{
93    ASSERT(m_entangledChannel);
94
95    m_entangledChannel->disentangle();
96
97    // We can't receive any messages or generate any events, so remove ourselves from the list of active ports.
98    ASSERT(m_scriptExecutionContext);
99    m_scriptExecutionContext->destroyedMessagePort(this);
100    m_scriptExecutionContext = 0;
101
102    return m_entangledChannel.release();
103}
104
105// Invoked to notify us that there are messages available for this port.
106// This code may be called from another thread, and so should not call any non-threadsafe APIs (i.e. should not call into the entangled channel or access mutable variables).
107void MessagePort::messageAvailable()
108{
109    ASSERT(m_scriptExecutionContext);
110    m_scriptExecutionContext->processMessagePortMessagesSoon();
111}
112
113void MessagePort::start()
114{
115    // Do nothing if we've been cloned or closed.
116    if (!isEntangled())
117        return;
118
119    ASSERT(m_scriptExecutionContext);
120    if (m_started)
121        return;
122
123    m_started = true;
124    m_scriptExecutionContext->processMessagePortMessagesSoon();
125}
126
127void MessagePort::close()
128{
129    if (isEntangled())
130        m_entangledChannel->close();
131    m_closed = true;
132}
133
134void MessagePort::entangle(PassOwnPtr<MessagePortChannel> remote)
135{
136    // Only invoked to set our initial entanglement.
137    ASSERT(!m_entangledChannel);
138    ASSERT(m_scriptExecutionContext);
139
140    // Don't entangle the ports if the channel is closed.
141    if (remote->entangleIfOpen(this))
142        m_entangledChannel = remote;
143}
144
145void MessagePort::contextDestroyed()
146{
147    ASSERT(m_scriptExecutionContext);
148    // Must be closed before blowing away the cached context, to ensure that we get no more calls to messageAvailable().
149    // ScriptExecutionContext::closeMessagePorts() takes care of that.
150    ASSERT(m_closed);
151    m_scriptExecutionContext = 0;
152}
153
154const AtomicString& MessagePort::interfaceName() const
155{
156    return eventNames().interfaceForMessagePort;
157}
158
159ScriptExecutionContext* MessagePort::scriptExecutionContext() const
160{
161    return m_scriptExecutionContext;
162}
163
164void MessagePort::dispatchMessages()
165{
166    // Messages for contexts that are not fully active get dispatched too, but JSAbstractEventListener::handleEvent() doesn't call handlers for these.
167    // The HTML5 spec specifies that any messages sent to a document that is not fully active should be dropped, so this behavior is OK.
168    ASSERT(started());
169
170    RefPtr<SerializedScriptValue> message;
171    OwnPtr<MessagePortChannelArray> channels;
172    while (m_entangledChannel && m_entangledChannel->tryGetMessageFromRemote(message, channels)) {
173
174#if ENABLE(WORKERS)
175        // close() in Worker onmessage handler should prevent next message from dispatching.
176        if (m_scriptExecutionContext->isWorkerContext() && static_cast<WorkerContext*>(m_scriptExecutionContext)->isClosing())
177            return;
178#endif
179
180        OwnPtr<MessagePortArray> ports = MessagePort::entanglePorts(*m_scriptExecutionContext, channels.release());
181        RefPtr<Event> evt = MessageEvent::create(ports.release(), message.release());
182
183        dispatchEvent(evt.release(), ASSERT_NO_EXCEPTION);
184    }
185}
186
187bool MessagePort::hasPendingActivity()
188{
189    // The spec says that entangled message ports should always be treated as if they have a strong reference.
190    // We'll also stipulate that the queue needs to be open (if the app drops its reference to the port before start()-ing it, then it's not really entangled as it's unreachable).
191    if (m_started && m_entangledChannel && m_entangledChannel->hasPendingActivity())
192        return true;
193    if (isEntangled() && !locallyEntangledPort())
194        return true;
195    return false;
196}
197
198MessagePort* MessagePort::locallyEntangledPort()
199{
200    return m_entangledChannel ? m_entangledChannel->locallyEntangledPort(m_scriptExecutionContext) : 0;
201}
202
203PassOwnPtr<MessagePortChannelArray> MessagePort::disentanglePorts(const MessagePortArray* ports, ExceptionCode& ec)
204{
205    if (!ports || !ports->size())
206        return nullptr;
207
208    // HashSet used to efficiently check for duplicates in the passed-in array.
209    HashSet<MessagePort*> portSet;
210
211    // Walk the incoming array - if there are any duplicate ports, or null ports or cloned ports, throw an error (per section 8.3.3 of the HTML5 spec).
212    for (unsigned int i = 0; i < ports->size(); ++i) {
213        MessagePort* port = (*ports)[i].get();
214        if (!port || port->isNeutered() || portSet.contains(port)) {
215            ec = DATA_CLONE_ERR;
216            return nullptr;
217        }
218        portSet.add(port);
219    }
220
221    // Passed-in ports passed validity checks, so we can disentangle them.
222    OwnPtr<MessagePortChannelArray> portArray = adoptPtr(new MessagePortChannelArray(ports->size()));
223    for (unsigned int i = 0 ; i < ports->size() ; ++i) {
224        OwnPtr<MessagePortChannel> channel = (*ports)[i]->disentangle();
225        (*portArray)[i] = channel.release();
226    }
227    return portArray.release();
228}
229
230PassOwnPtr<MessagePortArray> MessagePort::entanglePorts(ScriptExecutionContext& context, PassOwnPtr<MessagePortChannelArray> channels)
231{
232    if (!channels || !channels->size())
233        return nullptr;
234
235    OwnPtr<MessagePortArray> portArray = adoptPtr(new MessagePortArray(channels->size()));
236    for (unsigned int i = 0; i < channels->size(); ++i) {
237        RefPtr<MessagePort> port = MessagePort::create(context);
238        port->entangle((*channels)[i].release());
239        (*portArray)[i] = port.release();
240    }
241    return portArray.release();
242}
243
244EventTargetData* MessagePort::eventTargetData()
245{
246    return &m_eventTargetData;
247}
248
249EventTargetData* MessagePort::ensureEventTargetData()
250{
251    return &m_eventTargetData;
252}
253
254} // namespace WebCore
255