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(WEB_SOCKETS)
34 
35 #include "WebSocket.h"
36 
37 #include "DOMWindow.h"
38 #include "Event.h"
39 #include "EventException.h"
40 #include "EventListener.h"
41 #include "EventNames.h"
42 #include "Logging.h"
43 #include "MessageEvent.h"
44 #include "ScriptCallStack.h"
45 #include "ScriptExecutionContext.h"
46 #include "SecurityOrigin.h"
47 #include "ThreadableWebSocketChannel.h"
48 #include "WebSocketChannel.h"
49 #include <wtf/StdLibExtras.h>
50 #include <wtf/text/CString.h>
51 #include <wtf/text/StringBuilder.h>
52 #include <wtf/text/StringConcatenate.h>
53 
54 namespace WebCore {
55 
isValidProtocolString(const String & protocol)56 static bool isValidProtocolString(const String& protocol)
57 {
58     if (protocol.isNull())
59         return true;
60     if (protocol.isEmpty())
61         return false;
62     const UChar* characters = protocol.characters();
63     for (size_t i = 0; i < protocol.length(); i++) {
64         if (characters[i] < 0x20 || characters[i] > 0x7E)
65             return false;
66     }
67     return true;
68 }
69 
encodeProtocolString(const String & protocol)70 static String encodeProtocolString(const String& protocol)
71 {
72     StringBuilder builder;
73     for (size_t i = 0; i < protocol.length(); i++) {
74         if (protocol[i] < 0x20 || protocol[i] > 0x7E)
75             builder.append(String::format("\\u%04X", protocol[i]));
76         else if (protocol[i] == 0x5c)
77             builder.append("\\\\");
78         else
79             builder.append(protocol[i]);
80     }
81     return builder.toString();
82 }
83 
84 static bool webSocketsAvailable = false;
85 
setIsAvailable(bool available)86 void WebSocket::setIsAvailable(bool available)
87 {
88     webSocketsAvailable = available;
89 }
90 
isAvailable()91 bool WebSocket::isAvailable()
92 {
93     return webSocketsAvailable;
94 }
95 
WebSocket(ScriptExecutionContext * context)96 WebSocket::WebSocket(ScriptExecutionContext* context)
97     : ActiveDOMObject(context, this)
98     , m_state(CONNECTING)
99     , m_bufferedAmountAfterClose(0)
100 {
101 }
102 
~WebSocket()103 WebSocket::~WebSocket()
104 {
105     if (m_channel)
106         m_channel->disconnect();
107 }
108 
connect(const KURL & url,ExceptionCode & ec)109 void WebSocket::connect(const KURL& url, ExceptionCode& ec)
110 {
111     connect(url, String(), ec);
112 }
113 
connect(const KURL & url,const String & protocol,ExceptionCode & ec)114 void WebSocket::connect(const KURL& url, const String& protocol, ExceptionCode& ec)
115 {
116     LOG(Network, "WebSocket %p connect to %s protocol=%s", this, url.string().utf8().data(), protocol.utf8().data());
117     m_url = url;
118     m_protocol = protocol;
119 
120     if (!m_url.isValid()) {
121         scriptExecutionContext()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Invalid url for WebSocket " + url.string(), 0, scriptExecutionContext()->securityOrigin()->toString(), 0);
122         m_state = CLOSED;
123         ec = SYNTAX_ERR;
124         return;
125     }
126 
127     if (!m_url.protocolIs("ws") && !m_url.protocolIs("wss")) {
128         scriptExecutionContext()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Wrong url scheme for WebSocket " + url.string(), 0, scriptExecutionContext()->securityOrigin()->toString(), 0);
129         m_state = CLOSED;
130         ec = SYNTAX_ERR;
131         return;
132     }
133     if (m_url.hasFragmentIdentifier()) {
134         scriptExecutionContext()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "URL has fragment component " + url.string(), 0, scriptExecutionContext()->securityOrigin()->toString(), 0);
135         m_state = CLOSED;
136         ec = SYNTAX_ERR;
137         return;
138     }
139     if (!isValidProtocolString(m_protocol)) {
140         scriptExecutionContext()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Wrong protocol for WebSocket '" + encodeProtocolString(m_protocol) + "'", 0, scriptExecutionContext()->securityOrigin()->toString(), 0);
141         m_state = CLOSED;
142         ec = SYNTAX_ERR;
143         return;
144     }
145     if (!portAllowed(url)) {
146         scriptExecutionContext()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, makeString("WebSocket port ", String::number(url.port()), " blocked"), 0, scriptExecutionContext()->securityOrigin()->toString(), 0);
147         m_state = CLOSED;
148         ec = SECURITY_ERR;
149         return;
150     }
151 
152     m_channel = ThreadableWebSocketChannel::create(scriptExecutionContext(), this, m_url, m_protocol);
153     m_channel->connect();
154     ActiveDOMObject::setPendingActivity(this);
155 }
156 
send(const String & message,ExceptionCode & ec)157 bool WebSocket::send(const String& message, ExceptionCode& ec)
158 {
159     LOG(Network, "WebSocket %p send %s", this, message.utf8().data());
160     if (m_state == CONNECTING) {
161         ec = INVALID_STATE_ERR;
162         return false;
163     }
164     // No exception is raised if the connection was once established but has subsequently been closed.
165     if (m_state == CLOSED) {
166         m_bufferedAmountAfterClose += message.utf8().length() + 2; // 2 for frameing
167         return false;
168     }
169     // FIXME: check message is valid utf8.
170     ASSERT(m_channel);
171     return m_channel->send(message);
172 }
173 
close()174 void WebSocket::close()
175 {
176     LOG(Network, "WebSocket %p close", this);
177     if (m_state == CLOSED)
178         return;
179     m_state = CLOSED;
180     m_bufferedAmountAfterClose = m_channel->bufferedAmount();
181     // didClose notification may be already queued, which we will inadvertently process while waiting for bufferedAmount() to return.
182     // In this case m_channel will be set to null during didClose() call, thus we need to test validness of m_channel here.
183     if (m_channel)
184         m_channel->close();
185 }
186 
url() const187 const KURL& WebSocket::url() const
188 {
189     return m_url;
190 }
191 
readyState() const192 WebSocket::State WebSocket::readyState() const
193 {
194     return m_state;
195 }
196 
bufferedAmount() const197 unsigned long WebSocket::bufferedAmount() const
198 {
199     if (m_state == OPEN)
200         return m_channel->bufferedAmount();
201     return m_bufferedAmountAfterClose;
202 }
203 
scriptExecutionContext() const204 ScriptExecutionContext* WebSocket::scriptExecutionContext() const
205 {
206     return ActiveDOMObject::scriptExecutionContext();
207 }
208 
contextDestroyed()209 void WebSocket::contextDestroyed()
210 {
211     LOG(Network, "WebSocket %p scriptExecutionContext destroyed", this);
212     ASSERT(!m_channel);
213     ASSERT(m_state == CLOSED);
214     ActiveDOMObject::contextDestroyed();
215 }
216 
canSuspend() const217 bool WebSocket::canSuspend() const
218 {
219     return !m_channel;
220 }
221 
suspend(ReasonForSuspension)222 void WebSocket::suspend(ReasonForSuspension)
223 {
224     if (m_channel)
225         m_channel->suspend();
226 }
227 
resume()228 void WebSocket::resume()
229 {
230     if (m_channel)
231         m_channel->resume();
232 }
233 
stop()234 void WebSocket::stop()
235 {
236     bool pending = hasPendingActivity();
237     if (m_channel)
238         m_channel->disconnect();
239     m_channel = 0;
240     m_state = CLOSED;
241     ActiveDOMObject::stop();
242     if (pending)
243         ActiveDOMObject::unsetPendingActivity(this);
244 }
245 
didConnect()246 void WebSocket::didConnect()
247 {
248     LOG(Network, "WebSocket %p didConnect", this);
249     if (m_state != CONNECTING) {
250         didClose(0);
251         return;
252     }
253     ASSERT(scriptExecutionContext());
254     m_state = OPEN;
255     dispatchEvent(Event::create(eventNames().openEvent, false, false));
256 }
257 
didReceiveMessage(const String & msg)258 void WebSocket::didReceiveMessage(const String& msg)
259 {
260     LOG(Network, "WebSocket %p didReceiveMessage %s", this, msg.utf8().data());
261     if (m_state != OPEN)
262         return;
263     ASSERT(scriptExecutionContext());
264     RefPtr<MessageEvent> evt = MessageEvent::create();
265     evt->initMessageEvent(eventNames().messageEvent, false, false, SerializedScriptValue::create(msg), "", "", 0, 0);
266     dispatchEvent(evt);
267 }
268 
didReceiveMessageError()269 void WebSocket::didReceiveMessageError()
270 {
271     LOG(Network, "WebSocket %p didReceiveErrorMessage", this);
272     if (m_state != OPEN)
273         return;
274     ASSERT(scriptExecutionContext());
275     dispatchEvent(Event::create(eventNames().errorEvent, false, false));
276 }
277 
didClose(unsigned long unhandledBufferedAmount)278 void WebSocket::didClose(unsigned long unhandledBufferedAmount)
279 {
280     LOG(Network, "WebSocket %p didClose", this);
281     if (!m_channel)
282         return;
283     m_state = CLOSED;
284     m_bufferedAmountAfterClose += unhandledBufferedAmount;
285     ASSERT(scriptExecutionContext());
286     dispatchEvent(Event::create(eventNames().closeEvent, false, false));
287     if (m_channel) {
288         m_channel->disconnect();
289         m_channel = 0;
290     }
291     if (hasPendingActivity())
292         ActiveDOMObject::unsetPendingActivity(this);
293 }
294 
eventTargetData()295 EventTargetData* WebSocket::eventTargetData()
296 {
297     return &m_eventTargetData;
298 }
299 
ensureEventTargetData()300 EventTargetData* WebSocket::ensureEventTargetData()
301 {
302     return &m_eventTargetData;
303 }
304 
305 }  // namespace WebCore
306 
307 #endif
308