2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
33 #if ENABLE(WEB_SOCKETS)
35 #include "WebSocket.h"
39 #include "CloseEvent.h"
40 #include "DOMWindow.h"
42 #include "EventException.h"
43 #include "EventListener.h"
44 #include "EventNames.h"
45 #include "ExceptionCode.h"
47 #include "MessageEvent.h"
48 #include "ScriptCallStack.h"
49 #include "ScriptExecutionContext.h"
50 #include "SecurityOrigin.h"
51 #include "ThreadableWebSocketChannel.h"
52 #include "WebSocketChannel.h"
53 #include <wtf/HashSet.h>
54 #include <wtf/OwnPtr.h>
55 #include <wtf/PassOwnPtr.h>
56 #include <wtf/StdLibExtras.h>
57 #include <wtf/text/CString.h>
58 #include <wtf/text/StringBuilder.h>
59 #include <wtf/text/WTFString.h>
63 static inline bool isValidProtocolCharacter(UChar character)
65 // Hybi-10 says "(Subprotocol string must consist of) characters in the range U+0021 to U+007E not including
66 // separator characters as defined in [RFC2616]."
67 const UChar minimumProtocolCharacter = '!'; // U+0021.
68 const UChar maximumProtocolCharacter = '~'; // U+007E.
69 return character >= minimumProtocolCharacter && character <= maximumProtocolCharacter
70 && character != '"' && character != '(' && character != ')' && character != ',' && character != '/'
71 && !(character >= ':' && character <= '@') // U+003A - U+0040 (':', ';', '<', '=', '>', '?', '@').
72 && !(character >= '[' && character <= ']') // U+005B - U+005D ('[', '\\', ']').
73 && character != '{' && character != '}';
76 static bool isValidProtocolString(const String& protocol)
78 if (protocol.isEmpty())
80 for (size_t i = 0; i < protocol.length(); ++i) {
81 if (!isValidProtocolCharacter(protocol[i]))
87 static bool isValidProtocolStringHixie76(const String& protocol)
89 if (protocol.isNull())
91 if (protocol.isEmpty())
93 const UChar* characters = protocol.characters();
94 for (size_t i = 0; i < protocol.length(); i++) {
95 if (characters[i] < 0x20 || characters[i] > 0x7E)
101 static String encodeProtocolString(const String& protocol)
103 StringBuilder builder;
104 for (size_t i = 0; i < protocol.length(); i++) {
105 if (protocol[i] < 0x20 || protocol[i] > 0x7E)
106 builder.append(String::format("\\u%04X", protocol[i]));
107 else if (protocol[i] == 0x5c)
108 builder.append("\\\\");
110 builder.append(protocol[i]);
112 return builder.toString();
115 static String joinStrings(const Vector<String>& strings, const char* separator)
117 StringBuilder builder;
118 for (size_t i = 0; i < strings.size(); ++i) {
120 builder.append(separator);
121 builder.append(strings[i]);
123 return builder.toString();
126 static bool webSocketsAvailable = false;
128 void WebSocket::setIsAvailable(bool available)
130 webSocketsAvailable = available;
133 bool WebSocket::isAvailable()
135 return webSocketsAvailable;
138 WebSocket::WebSocket(ScriptExecutionContext* context)
139 : ActiveDOMObject(context, this)
140 , m_state(CONNECTING)
141 , m_bufferedAmountAfterClose(0)
142 , m_binaryType(BinaryTypeBlob)
143 , m_useHixie76Protocol(true)
148 WebSocket::~WebSocket()
151 m_channel->disconnect();
154 void WebSocket::connect(const String& url, ExceptionCode& ec)
156 Vector<String> protocols;
157 connect(url, protocols, ec);
160 void WebSocket::connect(const String& url, const String& protocol, ExceptionCode& ec)
162 Vector<String> protocols;
163 protocols.append(protocol);
164 connect(url, protocols, ec);
167 void WebSocket::connect(const String& url, const Vector<String>& protocols, ExceptionCode& ec)
169 LOG(Network, "WebSocket %p connect to %s", this, url.utf8().data());
170 m_url = KURL(KURL(), url);
172 if (!m_url.isValid()) {
173 scriptExecutionContext()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Invalid url for WebSocket " + m_url.string(), 0, scriptExecutionContext()->securityOrigin()->toString(), 0);
179 if (!m_url.protocolIs("ws") && !m_url.protocolIs("wss")) {
180 scriptExecutionContext()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Wrong url scheme for WebSocket " + m_url.string(), 0, scriptExecutionContext()->securityOrigin()->toString(), 0);
185 if (m_url.hasFragmentIdentifier()) {
186 scriptExecutionContext()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "URL has fragment component " + m_url.string(), 0, scriptExecutionContext()->securityOrigin()->toString(), 0);
191 if (!portAllowed(m_url)) {
192 scriptExecutionContext()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "WebSocket port " + String::number(m_url.port()) + " blocked", 0, scriptExecutionContext()->securityOrigin()->toString(), 0);
198 m_channel = ThreadableWebSocketChannel::create(scriptExecutionContext(), this);
199 m_useHixie76Protocol = m_channel->useHixie76Protocol();
201 String protocolString;
202 if (m_useHixie76Protocol) {
203 if (!protocols.isEmpty()) {
204 // Emulate JavaScript's Array.toString() behavior.
205 protocolString = joinStrings(protocols, ",");
207 if (!isValidProtocolStringHixie76(protocolString)) {
208 scriptExecutionContext()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Wrong protocol for WebSocket '" + encodeProtocolString(protocolString) + "'", 0, scriptExecutionContext()->securityOrigin()->toString(), 0);
214 // FIXME: There is a disagreement about restriction of subprotocols between WebSocket API and hybi-10 protocol
215 // draft. The former simply says "only characters in the range U+0021 to U+007E are allowed," while the latter
216 // imposes a stricter rule: "the elements MUST be non-empty strings with characters as defined in [RFC2616],
217 // and MUST all be unique strings."
219 // Here, we throw SYNTAX_ERR if the given protocols do not meet the latter criteria. This behavior does not
220 // comply with WebSocket API specification, but it seems to be the only reasonable way to handle this conflict.
221 for (size_t i = 0; i < protocols.size(); ++i) {
222 if (!isValidProtocolString(protocols[i])) {
223 scriptExecutionContext()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Wrong protocol for WebSocket '" + encodeProtocolString(protocols[i]) + "'", 0, scriptExecutionContext()->securityOrigin()->toString(), 0);
229 HashSet<String> visited;
230 for (size_t i = 0; i < protocols.size(); ++i) {
231 if (visited.contains(protocols[i])) {
232 scriptExecutionContext()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "WebSocket protocols contain duplicates: '" + encodeProtocolString(protocols[i]) + "'", 0, scriptExecutionContext()->securityOrigin()->toString(), 0);
237 visited.add(protocols[i]);
240 if (!protocols.isEmpty())
241 protocolString = joinStrings(protocols, ", ");
244 m_channel->connect(m_url, protocolString);
245 ActiveDOMObject::setPendingActivity(this);
248 bool WebSocket::send(const String& message, ExceptionCode& ec)
250 LOG(Network, "WebSocket %p send %s", this, message.utf8().data());
251 if (m_state == CONNECTING) {
252 ec = INVALID_STATE_ERR;
255 // No exception is raised if the connection was once established but has subsequently been closed.
256 if (m_state == CLOSING || m_state == CLOSED) {
257 m_bufferedAmountAfterClose += message.utf8().length() + 2; // 2 for frameing
260 // FIXME: check message is valid utf8.
262 return m_channel->send(message);
265 void WebSocket::close()
267 LOG(Network, "WebSocket %p close", this);
268 if (m_state == CLOSING || m_state == CLOSED)
270 if (m_state == CONNECTING) {
272 m_channel->fail("WebSocket is closed before the connection is established.");
276 m_bufferedAmountAfterClose = m_channel->bufferedAmount();
277 // didClose notification may be already queued, which we will inadvertently process while waiting for bufferedAmount() to return.
278 // In this case m_channel will be set to null during didClose() call, thus we need to test validness of m_channel here.
283 const KURL& WebSocket::url() const
288 WebSocket::State WebSocket::readyState() const
293 unsigned long WebSocket::bufferedAmount() const
296 return m_channel->bufferedAmount();
297 else if (m_state == CLOSING)
298 return m_channel->bufferedAmount() + m_bufferedAmountAfterClose;
299 return m_bufferedAmountAfterClose;
302 String WebSocket::protocol() const
304 if (m_useHixie76Protocol)
306 return m_subprotocol;
309 String WebSocket::binaryType() const
311 if (m_useHixie76Protocol)
313 switch (m_binaryType) {
316 case BinaryTypeArrayBuffer:
317 return "arraybuffer";
319 ASSERT_NOT_REACHED();
323 void WebSocket::setBinaryType(const String& binaryType, ExceptionCode& ec)
325 if (m_useHixie76Protocol)
327 if (binaryType == "blob") {
328 m_binaryType = BinaryTypeBlob;
331 if (binaryType == "arraybuffer") {
332 m_binaryType = BinaryTypeArrayBuffer;
339 ScriptExecutionContext* WebSocket::scriptExecutionContext() const
341 return ActiveDOMObject::scriptExecutionContext();
344 void WebSocket::contextDestroyed()
346 LOG(Network, "WebSocket %p scriptExecutionContext destroyed", this);
348 ASSERT(m_state == CLOSED);
349 ActiveDOMObject::contextDestroyed();
352 bool WebSocket::canSuspend() const
357 void WebSocket::suspend(ReasonForSuspension)
360 m_channel->suspend();
363 void WebSocket::resume()
369 void WebSocket::stop()
371 bool pending = hasPendingActivity();
373 m_channel->disconnect();
376 ActiveDOMObject::stop();
378 ActiveDOMObject::unsetPendingActivity(this);
381 void WebSocket::didConnect()
383 LOG(Network, "WebSocket %p didConnect", this);
384 if (m_state != CONNECTING) {
385 didClose(0, ClosingHandshakeIncomplete, WebSocketChannel::CloseEventCodeAbnormalClosure, "");
388 ASSERT(scriptExecutionContext());
390 m_subprotocol = m_channel->subprotocol();
391 dispatchEvent(Event::create(eventNames().openEvent, false, false));
394 void WebSocket::didReceiveMessage(const String& msg)
396 LOG(Network, "WebSocket %p didReceiveMessage %s", this, msg.utf8().data());
397 if (m_state != OPEN && m_state != CLOSING)
399 ASSERT(scriptExecutionContext());
400 dispatchEvent(MessageEvent::create(msg));
403 void WebSocket::didReceiveBinaryData(PassOwnPtr<Vector<char> > binaryData)
405 switch (m_binaryType) {
406 case BinaryTypeBlob: {
407 size_t size = binaryData->size();
408 RefPtr<RawData> rawData = RawData::create();
409 binaryData->swap(*rawData->mutableData());
410 OwnPtr<BlobData> blobData = BlobData::create();
411 blobData->appendData(rawData.release(), 0, BlobDataItem::toEndOfFile);
412 RefPtr<Blob> blob = Blob::create(blobData.release(), size);
413 dispatchEvent(MessageEvent::create(blob.release()));
417 case BinaryTypeArrayBuffer:
418 dispatchEvent(MessageEvent::create(ArrayBuffer::create(binaryData->data(), binaryData->size())));
423 void WebSocket::didReceiveMessageError()
425 LOG(Network, "WebSocket %p didReceiveErrorMessage", this);
426 if (m_state != OPEN && m_state != CLOSING)
428 ASSERT(scriptExecutionContext());
429 dispatchEvent(Event::create(eventNames().errorEvent, false, false));
432 void WebSocket::didStartClosingHandshake()
434 LOG(Network, "WebSocket %p didStartClosingHandshake", this);
438 void WebSocket::didClose(unsigned long unhandledBufferedAmount, ClosingHandshakeCompletionStatus closingHandshakeCompletion, unsigned short code, const String& reason)
440 LOG(Network, "WebSocket %p didClose", this);
443 bool wasClean = m_state == CLOSING && !unhandledBufferedAmount && closingHandshakeCompletion == ClosingHandshakeComplete;
445 m_bufferedAmountAfterClose += unhandledBufferedAmount;
446 ASSERT(scriptExecutionContext());
447 RefPtr<CloseEvent> event = CloseEvent::create();
448 event->initCloseEvent(eventNames().closeEvent, false, false, wasClean, code, reason);
449 dispatchEvent(event);
451 m_channel->disconnect();
454 if (hasPendingActivity())
455 ActiveDOMObject::unsetPendingActivity(this);
458 EventTargetData* WebSocket::eventTargetData()
460 return &m_eventTargetData;
463 EventTargetData* WebSocket::ensureEventTargetData()
465 return &m_eventTargetData;
468 } // namespace WebCore