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/DOMWindow.h"
45 #include "core/frame/LocalFrame.h"
46 #include "core/frame/csp/ContentSecurityPolicy.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/heap/Handle.h"
52 #include "platform/weborigin/KnownPorts.h"
53 #include "platform/weborigin/SecurityOrigin.h"
54 #include "public/platform/Platform.h"
55 #include "wtf/ArrayBuffer.h"
56 #include "wtf/ArrayBufferView.h"
57 #include "wtf/Assertions.h"
58 #include "wtf/HashSet.h"
59 #include "wtf/PassOwnPtr.h"
60 #include "wtf/StdLibExtras.h"
61 #include "wtf/text/CString.h"
62 #include "wtf/text/StringBuilder.h"
63 #include "wtf/text/WTFString.h"
69 WebSocket::EventQueue::EventQueue(EventTarget* target)
72 , m_resumeTimer(this, &EventQueue::resumeTimerFired) { }
74 WebSocket::EventQueue::~EventQueue() { stop(); }
76 void WebSocket::EventQueue::dispatch(PassRefPtrWillBeRawPtr<Event> event)
80 ASSERT(m_events.isEmpty());
81 ASSERT(m_target->executionContext());
82 m_target->dispatchEvent(event);
85 m_events.append(event);
88 ASSERT(m_events.isEmpty());
94 bool WebSocket::EventQueue::isEmpty() const
96 return m_events.isEmpty();
99 void WebSocket::EventQueue::suspend()
101 if (m_state != Active)
107 void WebSocket::EventQueue::resume()
109 if (m_state != Suspended || m_resumeTimer.isActive())
112 m_resumeTimer.startOneShot(0, FROM_HERE);
115 void WebSocket::EventQueue::stop()
117 if (m_state == Stopped)
121 m_resumeTimer.stop();
125 void WebSocket::EventQueue::dispatchQueuedEvents()
127 if (m_state != Active)
130 RefPtrWillBeRawPtr<EventQueue> protect(this);
132 WillBeHeapDeque<RefPtrWillBeMember<Event> > events;
133 events.swap(m_events);
134 while (!events.isEmpty()) {
135 if (m_state == Stopped || m_state == Suspended)
137 ASSERT(m_state == Active);
138 ASSERT(m_target->executionContext());
139 m_target->dispatchEvent(events.takeFirst());
140 // |this| can be stopped here.
142 if (m_state == Suspended) {
143 while (!m_events.isEmpty())
144 events.append(m_events.takeFirst());
145 events.swap(m_events);
149 void WebSocket::EventQueue::resumeTimerFired(Timer<EventQueue>*)
151 ASSERT(m_state == Suspended);
153 dispatchQueuedEvents();
156 void WebSocket::EventQueue::trace(Visitor* visitor)
158 visitor->trace(m_events);
161 const size_t maxReasonSizeInBytes = 123;
163 static inline bool isValidSubprotocolCharacter(UChar character)
165 const UChar minimumProtocolCharacter = '!'; // U+0021.
166 const UChar maximumProtocolCharacter = '~'; // U+007E.
167 // Set to true if character does not matches "separators" ABNF defined in
168 // RFC2616. SP and HT are excluded since the range check excludes them.
169 bool isNotSeparator = character != '"' && character != '(' && character != ')' && character != ',' && character != '/'
170 && !(character >= ':' && character <= '@') // U+003A - U+0040 (':', ';', '<', '=', '>', '?', '@').
171 && !(character >= '[' && character <= ']') // U+005B - U+005D ('[', '\\', ']').
172 && character != '{' && character != '}';
173 return character >= minimumProtocolCharacter && character <= maximumProtocolCharacter && isNotSeparator;
176 static bool isValidSubprotocolString(const String& protocol)
178 if (protocol.isEmpty())
180 for (size_t i = 0; i < protocol.length(); ++i) {
181 if (!isValidSubprotocolCharacter(protocol[i]))
187 static String encodeSubprotocolString(const String& protocol)
189 StringBuilder builder;
190 for (size_t i = 0; i < protocol.length(); i++) {
191 if (protocol[i] < 0x20 || protocol[i] > 0x7E)
192 builder.append(String::format("\\u%04X", protocol[i]));
193 else if (protocol[i] == 0x5c)
194 builder.append("\\\\");
196 builder.append(protocol[i]);
198 return builder.toString();
201 static String joinStrings(const Vector<String>& strings, const char* separator)
203 StringBuilder builder;
204 for (size_t i = 0; i < strings.size(); ++i) {
206 builder.append(separator);
207 builder.append(strings[i]);
209 return builder.toString();
212 static unsigned long saturateAdd(unsigned long a, unsigned long b)
214 if (numeric_limits<unsigned long>::max() - a < b)
215 return numeric_limits<unsigned long>::max();
219 static void setInvalidStateErrorForSendMethod(ExceptionState& exceptionState)
221 exceptionState.throwDOMException(InvalidStateError, "Still in CONNECTING state.");
224 const char* WebSocket::subProtocolSeperator()
229 WebSocket::WebSocket(ExecutionContext* context)
230 : ActiveDOMObject(context)
231 , m_state(CONNECTING)
232 , m_bufferedAmount(0)
233 , m_bufferedAmountAfterClose(0)
234 , m_binaryType(BinaryTypeBlob)
237 , m_eventQueue(EventQueue::create(this))
239 ScriptWrappable::init(this);
242 WebSocket::~WebSocket()
247 void WebSocket::logError(const String& message)
249 executionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
252 PassRefPtrWillBeRawPtr<WebSocket> WebSocket::create(ExecutionContext* context, const String& url, ExceptionState& exceptionState)
254 Vector<String> protocols;
255 return create(context, url, protocols, exceptionState);
258 PassRefPtrWillBeRawPtr<WebSocket> WebSocket::create(ExecutionContext* context, const String& url, const Vector<String>& protocols, ExceptionState& exceptionState)
261 exceptionState.throwDOMException(SyntaxError, "Failed to create a WebSocket: the provided URL is invalid.");
265 RefPtrWillBeRawPtr<WebSocket> webSocket(adoptRefWillBeRefCountedGarbageCollected(new WebSocket(context)));
266 webSocket->suspendIfNeeded();
268 webSocket->connect(url, protocols, exceptionState);
269 if (exceptionState.hadException())
272 return webSocket.release();
275 PassRefPtrWillBeRawPtr<WebSocket> WebSocket::create(ExecutionContext* context, const String& url, const String& protocol, ExceptionState& exceptionState)
277 Vector<String> protocols;
278 protocols.append(protocol);
279 return create(context, url, protocols, exceptionState);
282 void WebSocket::connect(const String& url, ExceptionState& exceptionState)
284 Vector<String> protocols;
285 connect(url, protocols, exceptionState);
288 void WebSocket::connect(const String& url, const String& protocol, ExceptionState& exceptionState)
290 Vector<String> protocols;
291 protocols.append(protocol);
292 connect(url, protocols, exceptionState);
295 void WebSocket::connect(const String& url, const Vector<String>& protocols, ExceptionState& exceptionState)
297 WTF_LOG(Network, "WebSocket %p connect() url='%s'", this, url.utf8().data());
298 m_url = KURL(KURL(), url);
300 if (!m_url.isValid()) {
302 exceptionState.throwDOMException(SyntaxError, "The URL '" + url + "' is invalid.");
305 if (!m_url.protocolIs("ws") && !m_url.protocolIs("wss")) {
307 exceptionState.throwDOMException(SyntaxError, "The URL's scheme must be either 'ws' or 'wss'. '" + m_url.protocol() + "' is not allowed.");
311 if (m_url.hasFragmentIdentifier()) {
313 exceptionState.throwDOMException(SyntaxError, "The URL contains a fragment identifier ('" + m_url.fragmentIdentifier() + "'). Fragment identifiers are not allowed in WebSocket URLs.");
316 if (!portAllowed(m_url)) {
318 exceptionState.throwSecurityError("The port " + String::number(m_url.port()) + " is not allowed.");
322 // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
323 bool shouldBypassMainWorldContentSecurityPolicy = false;
324 if (executionContext()->isDocument()) {
325 Document* document = toDocument(executionContext());
326 shouldBypassMainWorldContentSecurityPolicy = document->frame()->script().shouldBypassMainWorldContentSecurityPolicy();
328 if (!shouldBypassMainWorldContentSecurityPolicy && !executionContext()->contentSecurityPolicy()->allowConnectToSource(m_url)) {
330 // The URL is safe to expose to JavaScript, as this check happens synchronously before redirection.
331 exceptionState.throwSecurityError("Refused to connect to '" + m_url.elidedString() + "' because it violates the document's Content Security Policy.");
335 m_channel = WebSocketChannel::create(executionContext(), this);
337 for (size_t i = 0; i < protocols.size(); ++i) {
338 if (!isValidSubprotocolString(protocols[i])) {
340 exceptionState.throwDOMException(SyntaxError, "The subprotocol '" + encodeSubprotocolString(protocols[i]) + "' is invalid.");
345 HashSet<String> visited;
346 for (size_t i = 0; i < protocols.size(); ++i) {
347 if (!visited.add(protocols[i]).isNewEntry) {
349 exceptionState.throwDOMException(SyntaxError, "The subprotocol '" + encodeSubprotocolString(protocols[i]) + "' is duplicated.");
355 String protocolString;
356 if (!protocols.isEmpty())
357 protocolString = joinStrings(protocols, subProtocolSeperator());
359 if (!m_channel->connect(m_url, protocolString)) {
361 exceptionState.throwSecurityError("An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.");
367 void WebSocket::handleSendResult(WebSocketChannel::SendResult result, ExceptionState& exceptionState, WebSocketSendType dataType)
370 case WebSocketChannel::InvalidMessage:
371 exceptionState.throwDOMException(SyntaxError, "The message contains invalid characters.");
373 case WebSocketChannel::SendFail:
374 logError("WebSocket send() failed.");
376 case WebSocketChannel::SendSuccess:
377 blink::Platform::current()->histogramEnumeration("WebCore.WebSocket.SendType", dataType, WebSocketSendTypeMax);
380 ASSERT_NOT_REACHED();
383 void WebSocket::updateBufferedAmountAfterClose(unsigned long payloadSize)
385 m_bufferedAmountAfterClose = saturateAdd(m_bufferedAmountAfterClose, payloadSize);
386 m_bufferedAmountAfterClose = saturateAdd(m_bufferedAmountAfterClose, getFramingOverhead(payloadSize));
388 logError("WebSocket is already in CLOSING or CLOSED state.");
391 void WebSocket::releaseChannel()
394 m_channel->disconnect();
398 void WebSocket::send(const String& message, ExceptionState& exceptionState)
400 WTF_LOG(Network, "WebSocket %p send() Sending String '%s'", this, message.utf8().data());
401 if (m_state == CONNECTING) {
402 setInvalidStateErrorForSendMethod(exceptionState);
405 // No exception is raised if the connection was once established but has subsequently been closed.
406 if (m_state == CLOSING || m_state == CLOSED) {
407 updateBufferedAmountAfterClose(message.utf8().length());
411 handleSendResult(m_channel->send(message), exceptionState, WebSocketSendTypeString);
414 void WebSocket::send(ArrayBuffer* binaryData, ExceptionState& exceptionState)
416 WTF_LOG(Network, "WebSocket %p send() Sending ArrayBuffer %p", this, binaryData);
418 if (m_state == CONNECTING) {
419 setInvalidStateErrorForSendMethod(exceptionState);
422 if (m_state == CLOSING || m_state == CLOSED) {
423 updateBufferedAmountAfterClose(binaryData->byteLength());
427 handleSendResult(m_channel->send(*binaryData, 0, binaryData->byteLength()), exceptionState, WebSocketSendTypeArrayBuffer);
430 void WebSocket::send(ArrayBufferView* arrayBufferView, ExceptionState& exceptionState)
432 WTF_LOG(Network, "WebSocket %p send() Sending ArrayBufferView %p", this, arrayBufferView);
433 ASSERT(arrayBufferView);
434 if (m_state == CONNECTING) {
435 setInvalidStateErrorForSendMethod(exceptionState);
438 if (m_state == CLOSING || m_state == CLOSED) {
439 updateBufferedAmountAfterClose(arrayBufferView->byteLength());
443 RefPtr<ArrayBuffer> arrayBuffer(arrayBufferView->buffer());
444 handleSendResult(m_channel->send(*arrayBuffer, arrayBufferView->byteOffset(), arrayBufferView->byteLength()), exceptionState, WebSocketSendTypeArrayBufferView);
447 void WebSocket::send(Blob* binaryData, ExceptionState& exceptionState)
449 WTF_LOG(Network, "WebSocket %p send() Sending Blob '%s'", this, binaryData->uuid().utf8().data());
451 if (m_state == CONNECTING) {
452 setInvalidStateErrorForSendMethod(exceptionState);
455 if (m_state == CLOSING || m_state == CLOSED) {
456 updateBufferedAmountAfterClose(static_cast<unsigned long>(binaryData->size()));
460 handleSendResult(m_channel->send(binaryData->blobDataHandle()), exceptionState, WebSocketSendTypeBlob);
463 void WebSocket::close(unsigned short code, const String& reason, ExceptionState& exceptionState)
465 closeInternal(code, reason, exceptionState);
468 void WebSocket::close(ExceptionState& exceptionState)
470 closeInternal(WebSocketChannel::CloseEventCodeNotSpecified, String(), exceptionState);
473 void WebSocket::close(unsigned short code, ExceptionState& exceptionState)
475 closeInternal(code, String(), exceptionState);
478 void WebSocket::closeInternal(int code, const String& reason, ExceptionState& exceptionState)
480 if (code == WebSocketChannel::CloseEventCodeNotSpecified) {
481 WTF_LOG(Network, "WebSocket %p close() without code and reason", this);
483 WTF_LOG(Network, "WebSocket %p close() code=%d reason='%s'", this, code, reason.utf8().data());
484 if (!(code == WebSocketChannel::CloseEventCodeNormalClosure || (WebSocketChannel::CloseEventCodeMinimumUserDefined <= code && code <= WebSocketChannel::CloseEventCodeMaximumUserDefined))) {
485 exceptionState.throwDOMException(InvalidAccessError, "The code must be either 1000, or between 3000 and 4999. " + String::number(code) + " is neither.");
488 CString utf8 = reason.utf8(StrictUTF8ConversionReplacingUnpairedSurrogatesWithFFFD);
489 if (utf8.length() > maxReasonSizeInBytes) {
490 exceptionState.throwDOMException(SyntaxError, "The message must not be greater than " + String::number(maxReasonSizeInBytes) + " bytes.");
495 if (m_state == CLOSING || m_state == CLOSED)
497 if (m_state == CONNECTING) {
499 m_channel->fail("WebSocket is closed before the connection is established.", WarningMessageLevel);
504 m_channel->close(code, reason);
507 const KURL& WebSocket::url() const
512 WebSocket::State WebSocket::readyState() const
517 unsigned long WebSocket::bufferedAmount() const
519 return saturateAdd(m_bufferedAmount, m_bufferedAmountAfterClose);
522 String WebSocket::protocol() const
524 return m_subprotocol;
527 String WebSocket::extensions() const
532 String WebSocket::binaryType() const
534 switch (m_binaryType) {
537 case BinaryTypeArrayBuffer:
538 return "arraybuffer";
540 ASSERT_NOT_REACHED();
544 void WebSocket::setBinaryType(const String& binaryType)
546 if (binaryType == "blob") {
547 m_binaryType = BinaryTypeBlob;
550 if (binaryType == "arraybuffer") {
551 m_binaryType = BinaryTypeArrayBuffer;
554 logError("'" + binaryType + "' is not a valid value for binaryType; binaryType remains unchanged.");
557 const AtomicString& WebSocket::interfaceName() const
559 return EventTargetNames::WebSocket;
562 ExecutionContext* WebSocket::executionContext() const
564 return ActiveDOMObject::executionContext();
567 void WebSocket::contextDestroyed()
569 WTF_LOG(Network, "WebSocket %p contextDestroyed()", this);
571 ASSERT(m_state == CLOSED);
572 ActiveDOMObject::contextDestroyed();
575 bool WebSocket::hasPendingActivity() const
577 return m_channel || !m_eventQueue->isEmpty();
580 void WebSocket::suspend()
583 m_channel->suspend();
584 m_eventQueue->suspend();
587 void WebSocket::resume()
591 m_eventQueue->resume();
594 void WebSocket::stop()
596 m_eventQueue->stop();
598 m_channel->close(WebSocketChannel::CloseEventCodeGoingAway, String());
604 void WebSocket::didConnect()
606 WTF_LOG(Network, "WebSocket %p didConnect()", this);
607 if (m_state != CONNECTING)
610 m_subprotocol = m_channel->subprotocol();
611 m_extensions = m_channel->extensions();
612 m_eventQueue->dispatch(Event::create(EventTypeNames::open));
615 void WebSocket::didReceiveMessage(const String& msg)
617 WTF_LOG(Network, "WebSocket %p didReceiveMessage() Text message '%s'", this, msg.utf8().data());
620 m_eventQueue->dispatch(MessageEvent::create(msg, SecurityOrigin::create(m_url)->toString()));
623 void WebSocket::didReceiveBinaryData(PassOwnPtr<Vector<char> > binaryData)
625 WTF_LOG(Network, "WebSocket %p didReceiveBinaryData() %lu byte binary message", this, static_cast<unsigned long>(binaryData->size()));
626 switch (m_binaryType) {
627 case BinaryTypeBlob: {
628 size_t size = binaryData->size();
629 RefPtr<RawData> rawData = RawData::create();
630 binaryData->swap(*rawData->mutableData());
631 OwnPtr<BlobData> blobData = BlobData::create();
632 blobData->appendData(rawData.release(), 0, BlobDataItem::toEndOfFile);
633 RefPtrWillBeRawPtr<Blob> blob = Blob::create(BlobDataHandle::create(blobData.release(), size));
634 m_eventQueue->dispatch(MessageEvent::create(blob.release(), SecurityOrigin::create(m_url)->toString()));
638 case BinaryTypeArrayBuffer:
639 RefPtr<ArrayBuffer> arrayBuffer = ArrayBuffer::create(binaryData->data(), binaryData->size());
641 // Failed to allocate an ArrayBuffer. We need to crash the renderer
642 // since there's no way defined in the spec to tell this to the
646 m_eventQueue->dispatch(MessageEvent::create(arrayBuffer.release(), SecurityOrigin::create(m_url)->toString()));
651 void WebSocket::didReceiveMessageError()
653 WTF_LOG(Network, "WebSocket %p didReceiveMessageError()", this);
655 m_eventQueue->dispatch(Event::create(EventTypeNames::error));
658 void WebSocket::didUpdateBufferedAmount(unsigned long bufferedAmount)
660 WTF_LOG(Network, "WebSocket %p didUpdateBufferedAmount() New bufferedAmount is %lu", this, bufferedAmount);
661 if (m_state == CLOSED)
663 m_bufferedAmount = bufferedAmount;
666 void WebSocket::didStartClosingHandshake()
668 WTF_LOG(Network, "WebSocket %p didStartClosingHandshake()", this);
672 void WebSocket::didClose(unsigned long unhandledBufferedAmount, ClosingHandshakeCompletionStatus closingHandshakeCompletion, unsigned short code, const String& reason)
674 WTF_LOG(Network, "WebSocket %p didClose()", this);
677 bool wasClean = m_state == CLOSING && !unhandledBufferedAmount && closingHandshakeCompletion == ClosingHandshakeComplete && code != WebSocketChannel::CloseEventCodeAbnormalClosure;
680 m_bufferedAmount = unhandledBufferedAmount;
681 m_eventQueue->dispatch(CloseEvent::create(wasClean, code, reason));
685 size_t WebSocket::getFramingOverhead(size_t payloadSize)
687 static const size_t hybiBaseFramingOverhead = 2; // Every frame has at least two-byte header.
688 static const size_t hybiMaskingKeyLength = 4; // Every frame from client must have masking key.
689 static const size_t minimumPayloadSizeWithTwoByteExtendedPayloadLength = 126;
690 static const size_t minimumPayloadSizeWithEightByteExtendedPayloadLength = 0x10000;
691 size_t overhead = hybiBaseFramingOverhead + hybiMaskingKeyLength;
692 if (payloadSize >= minimumPayloadSizeWithEightByteExtendedPayloadLength)
694 else if (payloadSize >= minimumPayloadSizeWithTwoByteExtendedPayloadLength)
699 void WebSocket::trace(Visitor* visitor)
701 visitor->trace(m_channel);
702 visitor->trace(m_eventQueue);
705 } // namespace WebCore