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 "MessageEvent.h"
35#include "SecurityOrigin.h"
36#include "Timer.h"
37#include "WorkerContext.h"
38#include <wtf/text/AtomicString.h>
39
40namespace WebCore {
41
42MessagePort::MessagePort(ScriptExecutionContext& scriptExecutionContext)
43    : m_entangledChannel(0)
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
60// FIXME: remove this when we update the ObjC bindings (bug #28774).
61void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, MessagePort* port, ExceptionCode& ec)
62{
63    MessagePortArray ports;
64    if (port)
65        ports.append(port);
66    postMessage(message, &ports, ec);
67}
68
69void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, ExceptionCode& ec)
70{
71    postMessage(message, static_cast<MessagePortArray*>(0), ec);
72}
73
74void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionCode& ec)
75{
76    if (!isEntangled())
77        return;
78    ASSERT(m_scriptExecutionContext);
79
80    OwnPtr<MessagePortChannelArray> channels;
81    // Make sure we aren't connected to any of the passed-in ports.
82    if (ports) {
83        for (unsigned int i = 0; i < ports->size(); ++i) {
84            MessagePort* dataPort = (*ports)[i].get();
85            if (dataPort == this || m_entangledChannel->isConnectedTo(dataPort)) {
86                ec = INVALID_STATE_ERR;
87                return;
88            }
89        }
90        channels = MessagePort::disentanglePorts(ports, ec);
91        if (ec)
92            return;
93    }
94    m_entangledChannel->postMessageToRemote(MessagePortChannel::EventData::create(message, channels.release()));
95}
96
97PassOwnPtr<MessagePortChannel> MessagePort::disentangle(ExceptionCode& ec)
98{
99    if (!m_entangledChannel)
100        ec = INVALID_STATE_ERR;
101    else {
102        m_entangledChannel->disentangle();
103
104        // We can't receive any messages or generate any events, so remove ourselves from the list of active ports.
105        ASSERT(m_scriptExecutionContext);
106        m_scriptExecutionContext->destroyedMessagePort(this);
107        m_scriptExecutionContext = 0;
108    }
109    return m_entangledChannel.release();
110}
111
112// Invoked to notify us that there are messages available for this port.
113// 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).
114void MessagePort::messageAvailable()
115{
116    ASSERT(m_scriptExecutionContext);
117    m_scriptExecutionContext->processMessagePortMessagesSoon();
118}
119
120void MessagePort::start()
121{
122    // Do nothing if we've been cloned or closed.
123    if (!isEntangled())
124        return;
125
126    ASSERT(m_scriptExecutionContext);
127    if (m_started)
128        return;
129
130    m_started = true;
131    m_scriptExecutionContext->processMessagePortMessagesSoon();
132}
133
134void MessagePort::close()
135{
136    m_closed = true;
137    if (!isEntangled())
138        return;
139    m_entangledChannel->close();
140}
141
142void MessagePort::entangle(PassOwnPtr<MessagePortChannel> remote)
143{
144    // Only invoked to set our initial entanglement.
145    ASSERT(!m_entangledChannel);
146    ASSERT(m_scriptExecutionContext);
147
148    // Don't entangle the ports if the channel is closed.
149    if (remote->entangleIfOpen(this))
150        m_entangledChannel = remote;
151}
152
153void MessagePort::contextDestroyed()
154{
155    ASSERT(m_scriptExecutionContext);
156    // Must be closed before blowing away the cached context, to ensure that we get no more calls to messageAvailable().
157    // ScriptExecutionContext::closeMessagePorts() takes care of that.
158    ASSERT(m_closed);
159    m_scriptExecutionContext = 0;
160}
161
162ScriptExecutionContext* MessagePort::scriptExecutionContext() const
163{
164    return m_scriptExecutionContext;
165}
166
167void MessagePort::dispatchMessages()
168{
169    // Messages for contexts that are not fully active get dispatched too, but JSAbstractEventListener::handleEvent() doesn't call handlers for these.
170    // The HTML5 spec specifies that any messages sent to a document that is not fully active should be dropped, so this behavior is OK.
171    ASSERT(started());
172
173    OwnPtr<MessagePortChannel::EventData> eventData;
174    while (m_entangledChannel && m_entangledChannel->tryGetMessageFromRemote(eventData)) {
175
176#if ENABLE(WORKERS)
177        // close() in Worker onmessage handler should prevent next message from dispatching.
178        if (m_scriptExecutionContext->isWorkerContext() && static_cast<WorkerContext*>(m_scriptExecutionContext)->isClosing())
179            return;
180#endif
181
182        OwnPtr<MessagePortArray> ports = MessagePort::entanglePorts(*m_scriptExecutionContext, eventData->channels());
183        RefPtr<Event> evt = MessageEvent::create(ports.release(), eventData->message());
184
185        ExceptionCode ec = 0;
186        dispatchEvent(evt.release(), ec);
187        ASSERT(!ec);
188    }
189}
190
191bool MessagePort::hasPendingActivity()
192{
193    // The spec says that entangled message ports should always be treated as if they have a strong reference.
194    // 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).
195    return m_started && m_entangledChannel && m_entangledChannel->hasPendingActivity();
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 0;
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->isCloned() || portSet.contains(port)) {
215            ec = INVALID_STATE_ERR;
216            return 0;
217        }
218        portSet.add(port);
219    }
220
221    // Passed-in ports passed validity checks, so we can disentangle them.
222    MessagePortChannelArray* portArray = new MessagePortChannelArray(ports->size());
223    for (unsigned int i = 0 ; i < ports->size() ; ++i) {
224        OwnPtr<MessagePortChannel> channel = (*ports)[i]->disentangle(ec);
225        ASSERT(!ec); // Can't generate exception here if passed above checks.
226        (*portArray)[i] = channel.release();
227    }
228    return portArray;
229}
230
231PassOwnPtr<MessagePortArray> MessagePort::entanglePorts(ScriptExecutionContext& context, PassOwnPtr<MessagePortChannelArray> channels)
232{
233    if (!channels || !channels->size())
234        return 0;
235
236    MessagePortArray* portArray = new MessagePortArray(channels->size());
237    for (unsigned int i = 0; i < channels->size(); ++i) {
238        RefPtr<MessagePort> port = MessagePort::create(context);
239        port->entangle((*channels)[i].release());
240        (*portArray)[i] = port.release();
241    }
242    return portArray;
243}
244
245EventTargetData* MessagePort::eventTargetData()
246{
247    return &m_eventTargetData;
248}
249
250EventTargetData* MessagePort::ensureEventTargetData()
251{
252    return &m_eventTargetData;
253}
254
255} // namespace WebCore
256