2 * Copyright (C) 2011 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 #include "modules/websockets/WebSocket.h"
35 #include "bindings/v8/ExceptionState.h"
36 #include "bindings/v8/ScriptController.h"
37 #include "core/dom/Document.h"
38 #include "core/dom/ExceptionCode.h"
39 #include "core/dom/ExecutionContext.h"
40 #include "core/events/Event.h"
41 #include "core/events/MessageEvent.h"
42 #include "core/fileapi/Blob.h"
43 #include "core/frame/ConsoleTypes.h"
44 #include "core/frame/ContentSecurityPolicy.h"
45 #include "core/frame/DOMWindow.h"
46 #include "core/frame/Frame.h"
47 #include "core/inspector/ScriptCallStack.h"
48 #include "modules/websockets/CloseEvent.h"
49 #include "platform/Logging.h"
50 #include "platform/blob/BlobData.h"
51 #include "platform/weborigin/KnownPorts.h"
52 #include "platform/weborigin/SecurityOrigin.h"
53 #include "wtf/ArrayBuffer.h"
54 #include "wtf/ArrayBufferView.h"
55 #include "wtf/HashSet.h"
56 #include "wtf/PassOwnPtr.h"
57 #include "wtf/StdLibExtras.h"
58 #include "wtf/text/CString.h"
59 #include "wtf/text/StringBuilder.h"
60 #include "wtf/text/WTFString.h"
66 WebSocket::EventQueue::EventQueue(EventTarget* target)
69 , m_resumeTimer(this, &EventQueue::resumeTimerFired) { }
71 WebSocket::EventQueue::~EventQueue() { stop(); }
73 void WebSocket::EventQueue::dispatch(PassRefPtr<Event> event)
77 ASSERT(m_events.isEmpty());
78 ASSERT(m_target->executionContext());
79 m_target->dispatchEvent(event);
82 m_events.append(event);
85 ASSERT(m_events.isEmpty());
91 bool WebSocket::EventQueue::isEmpty() const
93 return m_events.isEmpty();
96 void WebSocket::EventQueue::suspend()
98 if (m_state != Active)
104 void WebSocket::EventQueue::resume()
106 if (m_state != Suspended || m_resumeTimer.isActive())
109 m_resumeTimer.startOneShot(0);
112 void WebSocket::EventQueue::stop()
114 if (m_state == Stopped)
118 m_resumeTimer.stop();
122 void WebSocket::EventQueue::dispatchQueuedEvents()
124 if (m_state != Active)
127 RefPtr<EventQueue> protect(this);
129 Deque<RefPtr<Event> > events;
130 events.swap(m_events);
131 while (!events.isEmpty()) {
132 if (m_state == Stopped || m_state == Suspended)
134 ASSERT(m_state == Active);
135 ASSERT(m_target->executionContext());
136 m_target->dispatchEvent(events.takeFirst());
137 // |this| can be stopped here.
139 if (m_state == Suspended) {
140 while (!m_events.isEmpty())
141 events.append(m_events.takeFirst());
142 events.swap(m_events);
146 void WebSocket::EventQueue::resumeTimerFired(Timer<EventQueue>*)
148 ASSERT(m_state == Suspended);
150 dispatchQueuedEvents();
153 const size_t maxReasonSizeInBytes = 123;
155 static inline bool isValidProtocolCharacter(UChar character)
157 // Hybi-10 says "(Subprotocol string must consist of) characters in the range U+0021 to U+007E not including
158 // separator characters as defined in [RFC2616]."
159 const UChar minimumProtocolCharacter = '!'; // U+0021.
160 const UChar maximumProtocolCharacter = '~'; // U+007E.
161 return character >= minimumProtocolCharacter && character <= maximumProtocolCharacter
162 && character != '"' && character != '(' && character != ')' && character != ',' && character != '/'
163 && !(character >= ':' && character <= '@') // U+003A - U+0040 (':', ';', '<', '=', '>', '?', '@').
164 && !(character >= '[' && character <= ']') // U+005B - U+005D ('[', '\\', ']').
165 && character != '{' && character != '}';
168 static bool isValidProtocolString(const String& protocol)
170 if (protocol.isEmpty())
172 for (size_t i = 0; i < protocol.length(); ++i) {
173 if (!isValidProtocolCharacter(protocol[i]))
179 static String encodeProtocolString(const String& protocol)
181 StringBuilder builder;
182 for (size_t i = 0; i < protocol.length(); i++) {
183 if (protocol[i] < 0x20 || protocol[i] > 0x7E)
184 builder.append(String::format("\\u%04X", protocol[i]));
185 else if (protocol[i] == 0x5c)
186 builder.append("\\\\");
188 builder.append(protocol[i]);
190 return builder.toString();
193 static String joinStrings(const Vector<String>& strings, const char* separator)
195 StringBuilder builder;
196 for (size_t i = 0; i < strings.size(); ++i) {
198 builder.append(separator);
199 builder.append(strings[i]);
201 return builder.toString();
204 static unsigned long saturateAdd(unsigned long a, unsigned long b)
206 if (numeric_limits<unsigned long>::max() - a < b)
207 return numeric_limits<unsigned long>::max();
211 static void setInvalidStateErrorForSendMethod(ExceptionState& exceptionState)
213 exceptionState.throwDOMException(InvalidStateError, "Still in CONNECTING state.");
216 const char* WebSocket::subProtocolSeperator()
221 WebSocket::WebSocket(ExecutionContext* context)
222 : ActiveDOMObject(context)
223 , m_state(CONNECTING)
224 , m_bufferedAmount(0)
225 , m_bufferedAmountAfterClose(0)
226 , m_binaryType(BinaryTypeBlob)
229 , m_eventQueue(EventQueue::create(this))
231 ScriptWrappable::init(this);
234 WebSocket::~WebSocket()
239 void WebSocket::logError(const String& message)
241 executionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
244 PassRefPtr<WebSocket> WebSocket::create(ExecutionContext* context, const String& url, ExceptionState& exceptionState)
246 Vector<String> protocols;
247 return create(context, url, protocols, exceptionState);
250 PassRefPtr<WebSocket> WebSocket::create(ExecutionContext* context, const String& url, const Vector<String>& protocols, ExceptionState& exceptionState)
253 exceptionState.throwDOMException(SyntaxError, "Failed to create a WebSocket: the provided URL is invalid.");
257 RefPtr<WebSocket> webSocket(adoptRef(new WebSocket(context)));
258 webSocket->suspendIfNeeded();
260 webSocket->connect(context->completeURL(url), protocols, exceptionState);
261 if (exceptionState.hadException())
264 return webSocket.release();
267 PassRefPtr<WebSocket> WebSocket::create(ExecutionContext* context, const String& url, const String& protocol, ExceptionState& exceptionState)
269 Vector<String> protocols;
270 protocols.append(protocol);
271 return create(context, url, protocols, exceptionState);
274 void WebSocket::connect(const String& url, ExceptionState& exceptionState)
276 Vector<String> protocols;
277 connect(url, protocols, exceptionState);
280 void WebSocket::connect(const String& url, const String& protocol, ExceptionState& exceptionState)
282 Vector<String> protocols;
283 protocols.append(protocol);
284 connect(url, protocols, exceptionState);
287 void WebSocket::connect(const String& url, const Vector<String>& protocols, ExceptionState& exceptionState)
289 WTF_LOG(Network, "WebSocket %p connect() url='%s'", this, url.utf8().data());
290 m_url = KURL(KURL(), url);
292 if (!m_url.isValid()) {
294 exceptionState.throwDOMException(SyntaxError, "The URL '" + url + "' is invalid.");
297 if (!m_url.protocolIs("ws") && !m_url.protocolIs("wss")) {
299 exceptionState.throwDOMException(SyntaxError, "The URL's scheme must be either 'ws' or 'wss'. '" + m_url.protocol() + "' is not allowed.");
302 if (MixedContentChecker::isMixedContent(executionContext()->securityOrigin(), m_url)) {
303 // FIXME: Throw an exception and close the connection.
304 String message = "Connecting to a non-secure WebSocket server from a secure origin is deprecated.";
305 executionContext()->addConsoleMessage(JSMessageSource, WarningMessageLevel, message);
307 if (m_url.hasFragmentIdentifier()) {
309 exceptionState.throwDOMException(SyntaxError, "The URL contains a fragment identifier ('" + m_url.fragmentIdentifier() + "'). Fragment identifiers are not allowed in WebSocket URLs.");
312 if (!portAllowed(m_url)) {
314 exceptionState.throwSecurityError("The port " + String::number(m_url.port()) + " is not allowed.");
318 // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
319 bool shouldBypassMainWorldContentSecurityPolicy = false;
320 if (executionContext()->isDocument()) {
321 Document* document = toDocument(executionContext());
322 shouldBypassMainWorldContentSecurityPolicy = document->frame()->script().shouldBypassMainWorldContentSecurityPolicy();
324 if (!shouldBypassMainWorldContentSecurityPolicy && !executionContext()->contentSecurityPolicy()->allowConnectToSource(m_url)) {
326 // The URL is safe to expose to JavaScript, as this check happens synchronously before redirection.
327 exceptionState.throwSecurityError("Refused to connect to '" + m_url.elidedString() + "' because it violates the document's Content Security Policy.");
331 m_channel = WebSocketChannel::create(executionContext(), this);
333 // FIXME: There is a disagreement about restriction of subprotocols between WebSocket API and hybi-10 protocol
334 // draft. The former simply says "only characters in the range U+0021 to U+007E are allowed," while the latter
335 // imposes a stricter rule: "the elements MUST be non-empty strings with characters as defined in [RFC2616],
336 // and MUST all be unique strings."
338 // Here, we throw SyntaxError if the given protocols do not meet the latter criteria. This behavior does not
339 // comply with WebSocket API specification, but it seems to be the only reasonable way to handle this conflict.
340 for (size_t i = 0; i < protocols.size(); ++i) {
341 if (!isValidProtocolString(protocols[i])) {
343 exceptionState.throwDOMException(SyntaxError, "The subprotocol '" + encodeProtocolString(protocols[i]) + "' is invalid.");
348 HashSet<String> visited;
349 for (size_t i = 0; i < protocols.size(); ++i) {
350 if (!visited.add(protocols[i]).isNewEntry) {
352 exceptionState.throwDOMException(SyntaxError, "The subprotocol '" + encodeProtocolString(protocols[i]) + "' is duplicated.");
358 String protocolString;
359 if (!protocols.isEmpty())
360 protocolString = joinStrings(protocols, subProtocolSeperator());
362 m_channel->connect(m_url, protocolString);
365 void WebSocket::handleSendResult(WebSocketChannel::SendResult result, ExceptionState& exceptionState)
368 case WebSocketChannel::InvalidMessage:
369 exceptionState.throwDOMException(SyntaxError, "The message contains invalid characters.");
371 case WebSocketChannel::SendFail:
372 logError("WebSocket send() failed.");
374 case WebSocketChannel::SendSuccess:
377 ASSERT_NOT_REACHED();
380 void WebSocket::updateBufferedAmountAfterClose(unsigned long payloadSize)
382 m_bufferedAmountAfterClose = saturateAdd(m_bufferedAmountAfterClose, payloadSize);
383 m_bufferedAmountAfterClose = saturateAdd(m_bufferedAmountAfterClose, getFramingOverhead(payloadSize));
385 logError("WebSocket is already in CLOSING or CLOSED state.");
388 void WebSocket::releaseChannel()
391 m_channel->disconnect();
395 void WebSocket::send(const String& message, ExceptionState& exceptionState)
397 WTF_LOG(Network, "WebSocket %p send() Sending String '%s'", this, message.utf8().data());
398 if (m_state == CONNECTING) {
399 setInvalidStateErrorForSendMethod(exceptionState);
402 // No exception is raised if the connection was once established but has subsequently been closed.
403 if (m_state == CLOSING || m_state == CLOSED) {
404 updateBufferedAmountAfterClose(message.utf8().length());
408 handleSendResult(m_channel->send(message), exceptionState);
411 void WebSocket::send(ArrayBuffer* binaryData, ExceptionState& exceptionState)
413 WTF_LOG(Network, "WebSocket %p send() Sending ArrayBuffer %p", this, binaryData);
415 if (m_state == CONNECTING) {
416 setInvalidStateErrorForSendMethod(exceptionState);
419 if (m_state == CLOSING || m_state == CLOSED) {
420 updateBufferedAmountAfterClose(binaryData->byteLength());
424 handleSendResult(m_channel->send(*binaryData, 0, binaryData->byteLength()), exceptionState);
427 void WebSocket::send(ArrayBufferView* arrayBufferView, ExceptionState& exceptionState)
429 WTF_LOG(Network, "WebSocket %p send() Sending ArrayBufferView %p", this, arrayBufferView);
430 ASSERT(arrayBufferView);
431 if (m_state == CONNECTING) {
432 setInvalidStateErrorForSendMethod(exceptionState);
435 if (m_state == CLOSING || m_state == CLOSED) {
436 updateBufferedAmountAfterClose(arrayBufferView->byteLength());
440 RefPtr<ArrayBuffer> arrayBuffer(arrayBufferView->buffer());
441 handleSendResult(m_channel->send(*arrayBuffer, arrayBufferView->byteOffset(), arrayBufferView->byteLength()), exceptionState);
444 void WebSocket::send(Blob* binaryData, ExceptionState& exceptionState)
446 WTF_LOG(Network, "WebSocket %p send() Sending Blob '%s'", this, binaryData->uuid().utf8().data());
448 if (m_state == CONNECTING) {
449 setInvalidStateErrorForSendMethod(exceptionState);
452 if (m_state == CLOSING || m_state == CLOSED) {
453 updateBufferedAmountAfterClose(static_cast<unsigned long>(binaryData->size()));
457 handleSendResult(m_channel->send(binaryData->blobDataHandle()), exceptionState);
460 void WebSocket::close(unsigned short code, const String& reason, ExceptionState& exceptionState)
462 closeInternal(code, reason, exceptionState);
465 void WebSocket::close(ExceptionState& exceptionState)
467 closeInternal(WebSocketChannel::CloseEventCodeNotSpecified, String(), exceptionState);
470 void WebSocket::close(unsigned short code, ExceptionState& exceptionState)
472 closeInternal(code, String(), exceptionState);
475 void WebSocket::closeInternal(int code, const String& reason, ExceptionState& exceptionState)
477 if (code == WebSocketChannel::CloseEventCodeNotSpecified) {
478 WTF_LOG(Network, "WebSocket %p close() without code and reason", this);
480 WTF_LOG(Network, "WebSocket %p close() code=%d reason='%s'", this, code, reason.utf8().data());
481 if (!(code == WebSocketChannel::CloseEventCodeNormalClosure || (WebSocketChannel::CloseEventCodeMinimumUserDefined <= code && code <= WebSocketChannel::CloseEventCodeMaximumUserDefined))) {
482 exceptionState.throwDOMException(InvalidAccessError, "The code must be either 1000, or between 3000 and 4999. " + String::number(code) + " is neither.");
485 CString utf8 = reason.utf8(StrictUTF8ConversionReplacingUnpairedSurrogatesWithFFFD);
486 if (utf8.length() > maxReasonSizeInBytes) {
487 exceptionState.throwDOMException(SyntaxError, "The message must not be greater than " + String::number(maxReasonSizeInBytes) + " bytes.");
492 if (m_state == CLOSING || m_state == CLOSED)
494 if (m_state == CONNECTING) {
496 m_channel->fail("WebSocket is closed before the connection is established.", WarningMessageLevel);
501 m_channel->close(code, reason);
504 const KURL& WebSocket::url() const
509 WebSocket::State WebSocket::readyState() const
514 unsigned long WebSocket::bufferedAmount() const
516 return saturateAdd(m_bufferedAmount, m_bufferedAmountAfterClose);
519 String WebSocket::protocol() const
521 return m_subprotocol;
524 String WebSocket::extensions() const
529 String WebSocket::binaryType() const
531 switch (m_binaryType) {
534 case BinaryTypeArrayBuffer:
535 return "arraybuffer";
537 ASSERT_NOT_REACHED();
541 void WebSocket::setBinaryType(const String& binaryType)
543 if (binaryType == "blob") {
544 m_binaryType = BinaryTypeBlob;
547 if (binaryType == "arraybuffer") {
548 m_binaryType = BinaryTypeArrayBuffer;
551 logError("'" + binaryType + "' is not a valid value for binaryType; binaryType remains unchanged.");
554 const AtomicString& WebSocket::interfaceName() const
556 return EventTargetNames::WebSocket;
559 ExecutionContext* WebSocket::executionContext() const
561 return ActiveDOMObject::executionContext();
564 void WebSocket::contextDestroyed()
566 WTF_LOG(Network, "WebSocket %p contextDestroyed()", this);
568 ASSERT(m_state == CLOSED);
569 ActiveDOMObject::contextDestroyed();
572 bool WebSocket::hasPendingActivity() const
574 return m_channel || !m_eventQueue->isEmpty();
577 void WebSocket::suspend()
580 m_channel->suspend();
581 m_eventQueue->suspend();
584 void WebSocket::resume()
588 m_eventQueue->resume();
591 void WebSocket::stop()
593 m_eventQueue->stop();
595 m_channel->close(WebSocketChannel::CloseEventCodeGoingAway, String());
601 void WebSocket::didConnect()
603 WTF_LOG(Network, "WebSocket %p didConnect()", this);
604 if (m_state != CONNECTING)
607 m_subprotocol = m_channel->subprotocol();
608 m_extensions = m_channel->extensions();
609 m_eventQueue->dispatch(Event::create(EventTypeNames::open));
612 void WebSocket::didReceiveMessage(const String& msg)
614 WTF_LOG(Network, "WebSocket %p didReceiveMessage() Text message '%s'", this, msg.utf8().data());
617 m_eventQueue->dispatch(MessageEvent::create(msg, SecurityOrigin::create(m_url)->toString()));
620 void WebSocket::didReceiveBinaryData(PassOwnPtr<Vector<char> > binaryData)
622 WTF_LOG(Network, "WebSocket %p didReceiveBinaryData() %lu byte binary message", this, static_cast<unsigned long>(binaryData->size()));
623 switch (m_binaryType) {
624 case BinaryTypeBlob: {
625 size_t size = binaryData->size();
626 RefPtr<RawData> rawData = RawData::create();
627 binaryData->swap(*rawData->mutableData());
628 OwnPtr<BlobData> blobData = BlobData::create();
629 blobData->appendData(rawData.release(), 0, BlobDataItem::toEndOfFile);
630 RefPtr<Blob> blob = Blob::create(BlobDataHandle::create(blobData.release(), size));
631 m_eventQueue->dispatch(MessageEvent::create(blob.release(), SecurityOrigin::create(m_url)->toString()));
635 case BinaryTypeArrayBuffer:
636 m_eventQueue->dispatch(MessageEvent::create(ArrayBuffer::create(binaryData->data(), binaryData->size()), SecurityOrigin::create(m_url)->toString()));
641 void WebSocket::didReceiveMessageError()
643 WTF_LOG(Network, "WebSocket %p didReceiveMessageError()", this);
645 m_eventQueue->dispatch(Event::create(EventTypeNames::error));
648 void WebSocket::didUpdateBufferedAmount(unsigned long bufferedAmount)
650 WTF_LOG(Network, "WebSocket %p didUpdateBufferedAmount() New bufferedAmount is %lu", this, bufferedAmount);
651 if (m_state == CLOSED)
653 m_bufferedAmount = bufferedAmount;
656 void WebSocket::didStartClosingHandshake()
658 WTF_LOG(Network, "WebSocket %p didStartClosingHandshake()", this);
662 void WebSocket::didClose(unsigned long unhandledBufferedAmount, ClosingHandshakeCompletionStatus closingHandshakeCompletion, unsigned short code, const String& reason)
664 WTF_LOG(Network, "WebSocket %p didClose()", this);
667 bool wasClean = m_state == CLOSING && !unhandledBufferedAmount && closingHandshakeCompletion == ClosingHandshakeComplete && code != WebSocketChannel::CloseEventCodeAbnormalClosure;
670 m_bufferedAmount = unhandledBufferedAmount;
671 m_eventQueue->dispatch(CloseEvent::create(wasClean, code, reason));
675 size_t WebSocket::getFramingOverhead(size_t payloadSize)
677 static const size_t hybiBaseFramingOverhead = 2; // Every frame has at least two-byte header.
678 static const size_t hybiMaskingKeyLength = 4; // Every frame from client must have masking key.
679 static const size_t minimumPayloadSizeWithTwoByteExtendedPayloadLength = 126;
680 static const size_t minimumPayloadSizeWithEightByteExtendedPayloadLength = 0x10000;
681 size_t overhead = hybiBaseFramingOverhead + hybiMaskingKeyLength;
682 if (payloadSize >= minimumPayloadSizeWithEightByteExtendedPayloadLength)
684 else if (payloadSize >= minimumPayloadSizeWithTwoByteExtendedPayloadLength)
689 } // namespace WebCore