2 * Copyright (C) 2011, 2012 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 "WebSocketChannel.h"
38 #include "CookieJar.h"
40 #include "FileError.h"
41 #include "FileReaderLoader.h"
42 #include "InspectorInstrumentation.h"
45 #include "ProgressTracker.h"
46 #include "ScriptCallStack.h"
47 #include "ScriptExecutionContext.h"
49 #include "SocketStreamError.h"
50 #include "SocketStreamHandle.h"
51 #include "WebSocketChannelClient.h"
52 #include "WebSocketHandshake.h"
54 #include <wtf/ArrayBuffer.h>
55 #include <wtf/CryptographicallyRandomNumber.h>
56 #include <wtf/Deque.h>
57 #include <wtf/FastMalloc.h>
58 #include <wtf/HashMap.h>
59 #include <wtf/OwnPtr.h>
60 #include <wtf/PassOwnPtr.h>
61 #include <wtf/text/CString.h>
62 #include <wtf/text/StringHash.h>
63 #include <wtf/text/WTFString.h>
69 const double TCPMaximumSegmentLifetime = 2 * 60.0;
71 // Constants for hybi-10 frame format.
72 const unsigned char finalBit = 0x80;
73 const unsigned char compressBit = 0x40;
74 const unsigned char reserved2Bit = 0x20;
75 const unsigned char reserved3Bit = 0x10;
76 const unsigned char opCodeMask = 0xF;
77 const unsigned char maskBit = 0x80;
78 const unsigned char payloadLengthMask = 0x7F;
79 const size_t maxPayloadLengthWithoutExtendedLengthField = 125;
80 const size_t payloadLengthWithTwoByteExtendedLengthField = 126;
81 const size_t payloadLengthWithEightByteExtendedLengthField = 127;
82 const size_t maskingKeyWidthInBytes = 4;
84 WebSocketChannel::WebSocketChannel(Document* document, WebSocketChannelClient* client)
85 : m_document(document)
89 , m_resumeTimer(this, &WebSocketChannel::resumeTimerFired)
92 , m_receivedClosingHandshake(false)
93 , m_closingTimer(this, &WebSocketChannel::closingTimerFired)
95 , m_shouldDiscardReceivedData(false)
96 , m_unhandledBufferedAmount(0)
98 , m_useHixie76Protocol(true)
99 , m_hasContinuousFrame(false)
100 , m_closeEventCode(CloseEventCodeAbnormalClosure)
101 , m_outgoingFrameQueueStatus(OutgoingFrameQueueOpen)
103 , m_blobLoaderStatus(BlobLoaderNotStarted)
106 if (Settings* settings = m_document->settings())
107 m_useHixie76Protocol = settings->useHixie76WebSocketProtocol();
109 if (Page* page = m_document->page())
110 m_identifier = page->progress()->createUniqueIdentifier();
113 WebSocketChannel::~WebSocketChannel()
118 bool WebSocketChannel::useHixie76Protocol()
120 return m_useHixie76Protocol;
123 void WebSocketChannel::connect(const KURL& url, const String& protocol)
125 LOG(Network, "WebSocketChannel %p connect", this);
127 ASSERT(!m_suspended);
128 m_handshake = adoptPtr(new WebSocketHandshake(url, protocol, m_document, m_useHixie76Protocol));
129 m_handshake->reset();
131 InspectorInstrumentation::didCreateWebSocket(m_document, m_identifier, url, m_document->url());
133 m_handle = SocketStreamHandle::create(m_handshake->url(), this);
136 String WebSocketChannel::subprotocol()
138 LOG(Network, "WebSocketChannel %p subprotocol", this);
139 if (!m_handshake || m_handshake->mode() != WebSocketHandshake::Connected)
141 String serverProtocol = m_handshake->serverWebSocketProtocol();
142 if (serverProtocol.isNull())
144 return serverProtocol;
147 String WebSocketChannel::extensions()
149 LOG(Network, "WebSocketChannel %p extensions", this);
150 if (!m_handshake || m_handshake->mode() != WebSocketHandshake::Connected)
152 String extensions = m_handshake->acceptedExtensions();
153 if (extensions.isNull())
158 bool WebSocketChannel::send(const String& message)
160 LOG(Network, "WebSocketChannel %p send %s", this, message.utf8().data());
161 if (m_useHixie76Protocol) {
162 CString utf8 = message.utf8();
163 return sendFrameHixie76(utf8.data(), utf8.length());
165 enqueueTextFrame(message);
166 // According to WebSocket API specification, WebSocket.send() should return void instead
167 // of boolean. However, our implementation still returns boolean due to compatibility
168 // concern (see bug 65850).
169 // m_channel->send() may happen later, thus it's not always possible to know whether
170 // the message has been sent to the socket successfully. In this case, we have no choice
171 // but to return true.
175 bool WebSocketChannel::send(const ArrayBuffer& binaryData)
177 LOG(Network, "WebSocketChannel %p send arraybuffer %p", this, &binaryData);
178 ASSERT(!m_useHixie76Protocol);
179 enqueueRawFrame(WebSocketFrame::OpCodeBinary, static_cast<const char*>(binaryData.data()), binaryData.byteLength());
183 bool WebSocketChannel::send(const Blob& binaryData)
185 LOG(Network, "WebSocketChannel %p send blob %s", this, binaryData.url().string().utf8().data());
186 ASSERT(!m_useHixie76Protocol);
187 enqueueBlobFrame(WebSocketFrame::OpCodeBinary, binaryData);
191 bool WebSocketChannel::send(const char* data, int length)
193 LOG(Network, "WebSocketChannel %p send binary %p (%dB)", this, data, length);
194 ASSERT(!m_useHixie76Protocol);
195 enqueueRawFrame(WebSocketFrame::OpCodeBinary, data, length);
199 unsigned long WebSocketChannel::bufferedAmount() const
201 LOG(Network, "WebSocketChannel %p bufferedAmount", this);
203 ASSERT(!m_suspended);
204 return m_handle->bufferedAmount();
207 void WebSocketChannel::close(int code, const String& reason)
209 LOG(Network, "WebSocketChannel %p close", this);
210 ASSERT(!m_suspended);
213 startClosingHandshake(code, reason);
214 if (m_closing && !m_closingTimer.isActive())
215 m_closingTimer.startOneShot(2 * TCPMaximumSegmentLifetime);
218 void WebSocketChannel::fail(const String& reason)
220 LOG(Network, "WebSocketChannel %p fail: %s", this, reason.utf8().data());
221 ASSERT(!m_suspended);
223 m_document->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, reason, m_handshake->clientOrigin());
224 if (!m_useHixie76Protocol) {
225 // Hybi-10 specification explicitly states we must not continue to handle incoming data
226 // once the WebSocket connection is failed (section 7.1.7).
227 // FIXME: Should we do this in hixie-76 too?
228 m_shouldDiscardReceivedData = true;
230 skipBuffer(m_bufferSize); // Save memory.
231 m_hasContinuousFrame = false;
232 m_continuousFrameData.clear();
234 if (m_handle && !m_closed)
235 m_handle->disconnect(); // Will call didClose().
238 void WebSocketChannel::disconnect()
240 LOG(Network, "WebSocketChannel %p disconnect", this);
241 if (m_identifier && m_document)
242 InspectorInstrumentation::didCloseWebSocket(m_document, m_identifier);
244 m_handshake->clearScriptExecutionContext();
248 m_handle->disconnect();
251 void WebSocketChannel::suspend()
256 void WebSocketChannel::resume()
259 if ((m_buffer || m_closed) && m_client && !m_resumeTimer.isActive())
260 m_resumeTimer.startOneShot(0);
263 void WebSocketChannel::didOpenSocketStream(SocketStreamHandle* handle)
265 LOG(Network, "WebSocketChannel %p didOpenSocketStream", this);
266 ASSERT(handle == m_handle);
270 InspectorInstrumentation::willSendWebSocketHandshakeRequest(m_document, m_identifier, m_handshake->clientHandshakeRequest());
271 CString handshakeMessage = m_handshake->clientHandshakeMessage();
272 if (!handle->send(handshakeMessage.data(), handshakeMessage.length()))
273 fail("Failed to send WebSocket handshake.");
276 void WebSocketChannel::didCloseSocketStream(SocketStreamHandle* handle)
278 LOG(Network, "WebSocketChannel %p didCloseSocketStream", this);
279 if (m_identifier && m_document)
280 InspectorInstrumentation::didCloseWebSocket(m_document, m_identifier);
281 ASSERT_UNUSED(handle, handle == m_handle || !m_handle);
283 if (m_closingTimer.isActive())
284 m_closingTimer.stop();
285 if (!m_useHixie76Protocol && m_outgoingFrameQueueStatus != OutgoingFrameQueueClosed)
286 abortOutgoingFrameQueue();
288 m_unhandledBufferedAmount = m_handle->bufferedAmount();
291 WebSocketChannelClient* client = m_client;
296 client->didClose(m_unhandledBufferedAmount, m_receivedClosingHandshake ? WebSocketChannelClient::ClosingHandshakeComplete : WebSocketChannelClient::ClosingHandshakeIncomplete, m_closeEventCode, m_closeEventReason);
301 void WebSocketChannel::didReceiveSocketStreamData(SocketStreamHandle* handle, const char* data, int len)
303 LOG(Network, "WebSocketChannel %p didReceiveSocketStreamData %d", this, len);
304 RefPtr<WebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.
305 ASSERT(handle == m_handle);
310 handle->disconnect();
314 m_shouldDiscardReceivedData = true;
315 handle->disconnect();
318 if (m_shouldDiscardReceivedData)
320 if (!appendToBuffer(data, len)) {
321 m_shouldDiscardReceivedData = true;
322 fail("Ran out of memory while receiving WebSocket data.");
325 while (!m_suspended && m_client && m_buffer)
326 if (!processBuffer())
330 void WebSocketChannel::didUpdateBufferedAmount(SocketStreamHandle*, size_t bufferedAmount)
333 m_client->didUpdateBufferedAmount(bufferedAmount);
336 void WebSocketChannel::didFailSocketStream(SocketStreamHandle* handle, const SocketStreamError& error)
338 LOG(Network, "WebSocketChannel %p didFailSocketStream", this);
339 ASSERT(handle == m_handle || !m_handle);
343 message = "WebSocket network error";
344 else if (error.localizedDescription().isNull())
345 message = "WebSocket network error: error code " + String::number(error.errorCode());
347 message = "WebSocket network error: " + error.localizedDescription();
348 String failingURL = error.failingURL();
349 ASSERT(failingURL.isNull() || m_handshake->url().string() == failingURL);
350 if (failingURL.isNull())
351 failingURL = m_handshake->url().string();
352 m_document->addConsoleMessage(NetworkMessageSource, LogMessageType, ErrorMessageLevel, message, failingURL);
354 m_shouldDiscardReceivedData = true;
355 handle->disconnect();
358 void WebSocketChannel::didReceiveAuthenticationChallenge(SocketStreamHandle*, const AuthenticationChallenge&)
362 void WebSocketChannel::didCancelAuthenticationChallenge(SocketStreamHandle*, const AuthenticationChallenge&)
367 void WebSocketChannel::didStartLoading()
369 LOG(Network, "WebSocketChannel %p didStartLoading", this);
370 ASSERT(m_blobLoader);
371 ASSERT(m_blobLoaderStatus == BlobLoaderStarted);
374 void WebSocketChannel::didReceiveData()
376 LOG(Network, "WebSocketChannel %p didReceiveData", this);
377 ASSERT(m_blobLoader);
378 ASSERT(m_blobLoaderStatus == BlobLoaderStarted);
381 void WebSocketChannel::didFinishLoading()
383 LOG(Network, "WebSocketChannel %p didFinishLoading", this);
384 ASSERT(m_blobLoader);
385 ASSERT(m_blobLoaderStatus == BlobLoaderStarted);
386 m_blobLoaderStatus = BlobLoaderFinished;
387 processOutgoingFrameQueue();
391 void WebSocketChannel::didFail(int errorCode)
393 LOG(Network, "WebSocketChannel %p didFail %d", this, errorCode);
394 ASSERT(m_blobLoader);
395 ASSERT(m_blobLoaderStatus == BlobLoaderStarted);
396 m_blobLoader.clear();
397 m_blobLoaderStatus = BlobLoaderFailed;
398 fail("Failed to load Blob: error code = " + String::number(errorCode)); // FIXME: Generate human-friendly reason message.
403 bool WebSocketChannel::appendToBuffer(const char* data, size_t len)
405 size_t newBufferSize = m_bufferSize + len;
406 if (newBufferSize < m_bufferSize) {
407 LOG(Network, "WebSocket buffer overflow (%lu+%lu)", static_cast<unsigned long>(m_bufferSize), static_cast<unsigned long>(len));
411 if (!tryFastMalloc(newBufferSize).getValue(newBuffer))
415 memcpy(newBuffer, m_buffer, m_bufferSize);
416 memcpy(newBuffer + m_bufferSize, data, len);
418 m_buffer = newBuffer;
419 m_bufferSize = newBufferSize;
423 void WebSocketChannel::skipBuffer(size_t len)
425 ASSERT(len <= m_bufferSize);
432 memmove(m_buffer, m_buffer + len, m_bufferSize);
435 bool WebSocketChannel::processBuffer()
437 ASSERT(!m_suspended);
440 LOG(Network, "WebSocketChannel %p processBuffer %lu", this, static_cast<unsigned long>(m_bufferSize));
442 if (m_shouldDiscardReceivedData)
445 if (m_receivedClosingHandshake) {
446 skipBuffer(m_bufferSize);
450 RefPtr<WebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.
452 if (m_handshake->mode() == WebSocketHandshake::Incomplete) {
453 int headerLength = m_handshake->readServerHandshake(m_buffer, m_bufferSize);
454 if (headerLength <= 0)
456 if (m_handshake->mode() == WebSocketHandshake::Connected) {
458 InspectorInstrumentation::didReceiveWebSocketHandshakeResponse(m_document, m_identifier, m_handshake->serverHandshakeResponse());
459 if (!m_handshake->serverSetCookie().isEmpty()) {
460 if (cookiesEnabled(m_document)) {
461 ExceptionCode ec; // Exception (for sandboxed documents) ignored.
462 m_document->setCookie(m_handshake->serverSetCookie(), ec);
465 // FIXME: handle set-cookie2.
466 LOG(Network, "WebSocketChannel %p connected", this);
467 skipBuffer(headerLength);
468 m_client->didConnect();
469 LOG(Network, "remaining in read buf %lu", static_cast<unsigned long>(m_bufferSize));
472 ASSERT(m_handshake->mode() == WebSocketHandshake::Failed);
473 LOG(Network, "WebSocketChannel %p connection failed", this);
474 skipBuffer(headerLength);
475 m_shouldDiscardReceivedData = true;
476 fail(m_handshake->failureReason());
479 if (m_handshake->mode() != WebSocketHandshake::Connected)
482 if (m_useHixie76Protocol)
483 return processFrameHixie76();
485 return processFrame();
488 void WebSocketChannel::resumeTimerFired(Timer<WebSocketChannel>* timer)
490 ASSERT_UNUSED(timer, timer == &m_resumeTimer);
492 RefPtr<WebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.
493 while (!m_suspended && m_client && m_buffer)
494 if (!processBuffer())
496 if (!m_suspended && m_client && m_closed && m_handle)
497 didCloseSocketStream(m_handle.get());
500 void WebSocketChannel::startClosingHandshake(int code, const String& reason)
502 LOG(Network, "WebSocketChannel %p closing %d %d", this, m_closing, m_receivedClosingHandshake);
506 if (m_useHixie76Protocol) {
510 if (!m_handle->send(buf.data(), buf.size())) {
511 m_handle->disconnect();
516 if (!m_receivedClosingHandshake && code != CloseEventCodeNotSpecified) {
517 unsigned char highByte = code >> 8;
518 unsigned char lowByte = code;
519 buf.append(static_cast<char>(highByte));
520 buf.append(static_cast<char>(lowByte));
521 buf.append(reason.utf8().data(), reason.utf8().length());
523 enqueueRawFrame(WebSocketFrame::OpCodeClose, buf.data(), buf.size());
527 m_client->didStartClosingHandshake();
530 void WebSocketChannel::closingTimerFired(Timer<WebSocketChannel>* timer)
532 LOG(Network, "WebSocketChannel %p closing timer", this);
533 ASSERT_UNUSED(timer, &m_closingTimer == timer);
535 m_handle->disconnect();
538 WebSocketChannel::ParseFrameResult WebSocketChannel::parseFrame(WebSocketFrame& frame, const char*& frameEnd)
540 const char* p = m_buffer;
541 const char* bufferEnd = m_buffer + m_bufferSize;
543 if (m_bufferSize < 2)
544 return FrameIncomplete;
546 unsigned char firstByte = *p++;
547 unsigned char secondByte = *p++;
549 bool final = firstByte & finalBit;
550 bool compress = firstByte & compressBit;
551 bool reserved2 = firstByte & reserved2Bit;
552 bool reserved3 = firstByte & reserved3Bit;
553 unsigned char opCode = firstByte & opCodeMask;
555 bool masked = secondByte & maskBit;
556 uint64_t payloadLength64 = secondByte & payloadLengthMask;
557 if (payloadLength64 > maxPayloadLengthWithoutExtendedLengthField) {
558 int extendedPayloadLengthSize;
559 if (payloadLength64 == payloadLengthWithTwoByteExtendedLengthField)
560 extendedPayloadLengthSize = 2;
562 ASSERT(payloadLength64 == payloadLengthWithEightByteExtendedLengthField);
563 extendedPayloadLengthSize = 8;
565 if (bufferEnd - p < extendedPayloadLengthSize)
566 return FrameIncomplete;
568 for (int i = 0; i < extendedPayloadLengthSize; ++i) {
569 payloadLength64 <<= 8;
570 payloadLength64 |= static_cast<unsigned char>(*p++);
574 // FIXME: UINT64_C(0x7FFFFFFFFFFFFFFF) should be used but it did not compile on Qt bots.
576 static const uint64_t maxPayloadLength = 0x7FFFFFFFFFFFFFFFui64;
578 static const uint64_t maxPayloadLength = 0x7FFFFFFFFFFFFFFFull;
580 size_t maskingKeyLength = masked ? maskingKeyWidthInBytes : 0;
581 if (payloadLength64 > maxPayloadLength || payloadLength64 + maskingKeyLength > numeric_limits<size_t>::max()) {
582 fail("WebSocket frame length too large: " + String::number(payloadLength64) + " bytes");
585 size_t payloadLength = static_cast<size_t>(payloadLength64);
587 if (static_cast<size_t>(bufferEnd - p) < maskingKeyLength + payloadLength)
588 return FrameIncomplete;
591 const char* maskingKey = p;
592 char* payload = const_cast<char*>(p + maskingKeyWidthInBytes);
593 for (size_t i = 0; i < payloadLength; ++i)
594 payload[i] ^= maskingKey[i % maskingKeyWidthInBytes]; // Unmask the payload.
597 frame.opCode = static_cast<WebSocketFrame::OpCode>(opCode);
599 frame.compress = compress;
600 frame.reserved2 = reserved2;
601 frame.reserved3 = reserved3;
602 frame.masked = masked;
603 frame.payload = p + maskingKeyLength;
604 frame.payloadLength = payloadLength;
605 frameEnd = p + maskingKeyLength + payloadLength;
609 bool WebSocketChannel::processFrame()
613 WebSocketFrame frame;
614 const char* frameEnd;
615 if (parseFrame(frame, frameEnd) != FrameOK)
618 ASSERT(m_buffer < frameEnd);
619 ASSERT(frameEnd <= m_buffer + m_bufferSize);
621 // Validate the frame data.
622 if (WebSocketFrame::isReservedOpCode(frame.opCode)) {
623 fail("Unrecognized frame opcode: " + String::number(frame.opCode));
627 if (frame.reserved2 || frame.reserved3) {
628 fail("One or more reserved bits are on: reserved2 = " + String::number(frame.reserved2) + ", reserved3 = " + String::number(frame.reserved3));
632 // All control frames must not be fragmented.
633 if (WebSocketFrame::isControlOpCode(frame.opCode) && !frame.final) {
634 fail("Received fragmented control frame: opcode = " + String::number(frame.opCode));
638 // All control frames must have a payload of 125 bytes or less, which means the frame must not contain
639 // the "extended payload length" field.
640 if (WebSocketFrame::isControlOpCode(frame.opCode) && frame.payloadLength > maxPayloadLengthWithoutExtendedLengthField) {
641 fail("Received control frame having too long payload: " + String::number(frame.payloadLength) + " bytes");
645 // A new data frame is received before the previous continuous frame finishes.
646 // Note that control frames are allowed to come in the middle of continuous frames.
647 if (m_hasContinuousFrame && frame.opCode != WebSocketFrame::OpCodeContinuation && !WebSocketFrame::isControlOpCode(frame.opCode)) {
648 fail("Received new data frame but previous continuous frame is unfinished.");
652 switch (frame.opCode) {
653 case WebSocketFrame::OpCodeContinuation:
654 // An unexpected continuation frame is received without any leading frame.
655 if (!m_hasContinuousFrame) {
656 fail("Received unexpected continuation frame.");
659 m_continuousFrameData.append(frame.payload, frame.payloadLength);
660 skipBuffer(frameEnd - m_buffer);
662 // onmessage handler may eventually call the other methods of this channel,
663 // so we should pretend that we have finished to read this frame and
664 // make sure that the member variables are in a consistent state before
665 // the handler is invoked.
666 // Vector<char>::swap() is used here to clear m_continuousFrameData.
667 OwnPtr<Vector<char> > continuousFrameData = adoptPtr(new Vector<char>);
668 m_continuousFrameData.swap(*continuousFrameData);
669 m_hasContinuousFrame = false;
670 if (m_continuousFrameOpCode == WebSocketFrame::OpCodeText) {
672 if (continuousFrameData->size())
673 message = String::fromUTF8(continuousFrameData->data(), continuousFrameData->size());
676 if (message.isNull())
677 fail("Could not decode a text frame as UTF-8.");
679 m_client->didReceiveMessage(message);
680 } else if (m_continuousFrameOpCode == WebSocketFrame::OpCodeBinary)
681 m_client->didReceiveBinaryData(continuousFrameData.release());
685 case WebSocketFrame::OpCodeText:
688 if (frame.payloadLength)
689 message = String::fromUTF8(frame.payload, frame.payloadLength);
692 skipBuffer(frameEnd - m_buffer);
693 if (message.isNull())
694 fail("Could not decode a text frame as UTF-8.");
696 m_client->didReceiveMessage(message);
698 m_hasContinuousFrame = true;
699 m_continuousFrameOpCode = WebSocketFrame::OpCodeText;
700 ASSERT(m_continuousFrameData.isEmpty());
701 m_continuousFrameData.append(frame.payload, frame.payloadLength);
702 skipBuffer(frameEnd - m_buffer);
706 case WebSocketFrame::OpCodeBinary:
708 OwnPtr<Vector<char> > binaryData = adoptPtr(new Vector<char>(frame.payloadLength));
709 memcpy(binaryData->data(), frame.payload, frame.payloadLength);
710 skipBuffer(frameEnd - m_buffer);
711 m_client->didReceiveBinaryData(binaryData.release());
713 m_hasContinuousFrame = true;
714 m_continuousFrameOpCode = WebSocketFrame::OpCodeBinary;
715 ASSERT(m_continuousFrameData.isEmpty());
716 m_continuousFrameData.append(frame.payload, frame.payloadLength);
717 skipBuffer(frameEnd - m_buffer);
721 case WebSocketFrame::OpCodeClose:
722 if (frame.payloadLength >= 2) {
723 unsigned char highByte = static_cast<unsigned char>(frame.payload[0]);
724 unsigned char lowByte = static_cast<unsigned char>(frame.payload[1]);
725 m_closeEventCode = highByte << 8 | lowByte;
727 m_closeEventCode = CloseEventCodeNoStatusRcvd;
728 if (frame.payloadLength >= 3)
729 m_closeEventReason = String::fromUTF8(&frame.payload[2], frame.payloadLength - 2);
731 m_closeEventReason = "";
732 skipBuffer(frameEnd - m_buffer);
733 m_receivedClosingHandshake = true;
734 startClosingHandshake(m_closeEventCode, m_closeEventReason);
736 m_outgoingFrameQueueStatus = OutgoingFrameQueueClosing;
737 processOutgoingFrameQueue();
741 case WebSocketFrame::OpCodePing:
742 enqueueRawFrame(WebSocketFrame::OpCodePong, frame.payload, frame.payloadLength);
743 skipBuffer(frameEnd - m_buffer);
746 case WebSocketFrame::OpCodePong:
747 // A server may send a pong in response to our ping, or an unsolicited pong which is not associated with
748 // any specific ping. Either way, there's nothing to do on receipt of pong.
749 skipBuffer(frameEnd - m_buffer);
753 ASSERT_NOT_REACHED();
754 skipBuffer(frameEnd - m_buffer);
761 bool WebSocketChannel::processFrameHixie76()
763 const char* nextFrame = m_buffer;
764 const char* p = m_buffer;
765 const char* end = p + m_bufferSize;
767 unsigned char frameByte = static_cast<unsigned char>(*p++);
768 if ((frameByte & 0x80) == 0x80) {
770 bool errorFrame = false;
771 bool lengthFinished = false;
773 if (length > numeric_limits<size_t>::max() / 128) {
774 LOG(Network, "frame length overflow %lu", static_cast<unsigned long>(length));
778 size_t newLength = length * 128;
779 unsigned char msgByte = static_cast<unsigned char>(*p);
780 unsigned int lengthMsgByte = msgByte & 0x7f;
781 if (newLength > numeric_limits<size_t>::max() - lengthMsgByte) {
782 LOG(Network, "frame length overflow %lu+%u", static_cast<unsigned long>(newLength), lengthMsgByte);
786 newLength += lengthMsgByte;
787 if (newLength < length) { // sanity check
788 LOG(Network, "frame length integer wrap %lu->%lu", static_cast<unsigned long>(length), static_cast<unsigned long>(newLength));
794 if (!(msgByte & 0x80)) {
795 lengthFinished = true;
799 if (!errorFrame && !lengthFinished)
801 if (p + length < p) {
802 LOG(Network, "frame buffer pointer wrap %p+%lu->%p", p, static_cast<unsigned long>(length), p + length);
806 skipBuffer(m_bufferSize); // Save memory.
807 m_shouldDiscardReceivedData = true;
808 m_client->didReceiveMessageError();
809 fail("WebSocket frame length too large");
812 ASSERT(p + length >= p);
813 if (p + length <= end) {
816 ASSERT(nextFrame > m_buffer);
817 skipBuffer(nextFrame - m_buffer);
818 if (frameByte == 0xff && !length) {
819 m_receivedClosingHandshake = true;
820 startClosingHandshake(CloseEventCodeNotSpecified, "");
822 m_handle->close(); // close after sending FF 00.
824 m_client->didReceiveMessageError();
830 const char* msgStart = p;
831 while (p < end && *p != '\xff')
833 if (p < end && *p == '\xff') {
834 int msgLength = p - msgStart;
837 if (frameByte == 0x00) {
838 String msg = String::fromUTF8(msgStart, msgLength);
839 skipBuffer(nextFrame - m_buffer);
840 m_client->didReceiveMessage(msg);
842 skipBuffer(nextFrame - m_buffer);
843 m_client->didReceiveMessageError();
850 void WebSocketChannel::enqueueTextFrame(const String& string)
852 ASSERT(!m_useHixie76Protocol);
853 ASSERT(m_outgoingFrameQueueStatus == OutgoingFrameQueueOpen);
854 OwnPtr<QueuedFrame> frame = adoptPtr(new QueuedFrame);
855 frame->opCode = WebSocketFrame::OpCodeText;
856 frame->frameType = QueuedFrameTypeString;
857 frame->stringData = string;
858 m_outgoingFrameQueue.append(frame.release());
859 processOutgoingFrameQueue();
862 void WebSocketChannel::enqueueRawFrame(WebSocketFrame::OpCode opCode, const char* data, size_t dataLength)
864 ASSERT(!m_useHixie76Protocol);
865 ASSERT(m_outgoingFrameQueueStatus == OutgoingFrameQueueOpen);
866 OwnPtr<QueuedFrame> frame = adoptPtr(new QueuedFrame);
867 frame->opCode = opCode;
868 frame->frameType = QueuedFrameTypeVector;
869 frame->vectorData.resize(dataLength);
871 memcpy(frame->vectorData.data(), data, dataLength);
872 m_outgoingFrameQueue.append(frame.release());
873 processOutgoingFrameQueue();
876 void WebSocketChannel::enqueueBlobFrame(WebSocketFrame::OpCode opCode, const Blob& blob)
878 ASSERT(!m_useHixie76Protocol);
879 ASSERT(m_outgoingFrameQueueStatus == OutgoingFrameQueueOpen);
880 OwnPtr<QueuedFrame> frame = adoptPtr(new QueuedFrame);
881 frame->opCode = opCode;
882 frame->frameType = QueuedFrameTypeBlob;
883 frame->blobData = Blob::create(blob.url(), blob.type(), blob.size());
884 m_outgoingFrameQueue.append(frame.release());
885 processOutgoingFrameQueue();
888 void WebSocketChannel::processOutgoingFrameQueue()
890 ASSERT(!m_useHixie76Protocol);
891 if (m_outgoingFrameQueueStatus == OutgoingFrameQueueClosed)
894 while (!m_outgoingFrameQueue.isEmpty()) {
895 OwnPtr<QueuedFrame> frame = m_outgoingFrameQueue.takeFirst();
896 switch (frame->frameType) {
897 case QueuedFrameTypeString: {
898 CString utf8 = frame->stringData.utf8();
899 if (!sendFrame(frame->opCode, utf8.data(), utf8.length()))
900 fail("Failed to send WebSocket frame.");
904 case QueuedFrameTypeVector:
905 if (!sendFrame(frame->opCode, frame->vectorData.data(), frame->vectorData.size()))
906 fail("Failed to send WebSocket frame.");
909 case QueuedFrameTypeBlob: {
911 switch (m_blobLoaderStatus) {
912 case BlobLoaderNotStarted:
913 ref(); // Will be derefed after didFinishLoading() or didFail().
914 ASSERT(!m_blobLoader);
915 m_blobLoader = adoptPtr(new FileReaderLoader(FileReaderLoader::ReadAsArrayBuffer, this));
916 m_blobLoaderStatus = BlobLoaderStarted;
917 m_blobLoader->start(m_document, frame->blobData.get());
918 m_outgoingFrameQueue.prepend(frame.release());
921 case BlobLoaderStarted:
922 case BlobLoaderFailed:
923 m_outgoingFrameQueue.prepend(frame.release());
926 case BlobLoaderFinished: {
927 RefPtr<ArrayBuffer> result = m_blobLoader->arrayBufferResult();
928 m_blobLoader.clear();
929 m_blobLoaderStatus = BlobLoaderNotStarted;
930 if (!sendFrame(frame->opCode, static_cast<const char*>(result->data()), result->byteLength()))
931 fail("Failed to send WebSocket frame.");
936 fail("FileReader is not available. Could not send a Blob as WebSocket binary message.");
942 ASSERT_NOT_REACHED();
947 ASSERT(m_outgoingFrameQueue.isEmpty());
948 if (m_outgoingFrameQueueStatus == OutgoingFrameQueueClosing) {
949 m_outgoingFrameQueueStatus = OutgoingFrameQueueClosed;
954 void WebSocketChannel::abortOutgoingFrameQueue()
956 ASSERT(!m_useHixie76Protocol);
957 m_outgoingFrameQueue.clear();
958 m_outgoingFrameQueueStatus = OutgoingFrameQueueClosed;
960 if (m_blobLoaderStatus == BlobLoaderStarted) {
961 m_blobLoader->cancel();
962 didFail(FileError::ABORT_ERR);
967 static void appendMaskedFramePayload(const WebSocketFrame& frame, Vector<char>& frameData)
969 size_t maskingKeyStart = frameData.size();
970 frameData.grow(frameData.size() + maskingKeyWidthInBytes); // Add placeholder for masking key. Will be overwritten.
971 size_t payloadStart = frameData.size();
972 frameData.append(frame.payload, frame.payloadLength);
974 cryptographicallyRandomValues(frameData.data() + maskingKeyStart, maskingKeyWidthInBytes);
975 for (size_t i = 0; i < frame.payloadLength; ++i)
976 frameData[payloadStart + i] ^= frameData[maskingKeyStart + i % maskingKeyWidthInBytes];
979 static void makeFrameData(const WebSocketFrame& frame, Vector<char>& frameData)
981 unsigned char firstByte = (frame.final ? finalBit : 0) | frame.opCode;
983 firstByte |= compressBit;
984 frameData.append(firstByte);
985 if (frame.payloadLength <= maxPayloadLengthWithoutExtendedLengthField)
986 frameData.append(maskBit | frame.payloadLength);
987 else if (frame.payloadLength <= 0xFFFF) {
988 frameData.append(maskBit | payloadLengthWithTwoByteExtendedLengthField);
989 frameData.append((frame.payloadLength & 0xFF00) >> 8);
990 frameData.append(frame.payloadLength & 0xFF);
992 frameData.append(maskBit | payloadLengthWithEightByteExtendedLengthField);
993 char extendedPayloadLength[8];
994 size_t remaining = frame.payloadLength;
995 // Fill the length into extendedPayloadLength in the network byte order.
996 for (int i = 0; i < 8; ++i) {
997 extendedPayloadLength[7 - i] = remaining & 0xFF;
1001 frameData.append(extendedPayloadLength, 8);
1004 appendMaskedFramePayload(frame, frameData);
1007 bool WebSocketChannel::sendFrame(WebSocketFrame::OpCode opCode, const char* data, size_t dataLength)
1010 ASSERT(!m_suspended);
1012 ASSERT(!(opCode & ~opCodeMask)); // Checks whether "opCode" fits in the range of opCodes.
1013 WebSocketFrame frame(opCode, true, false, true, data, dataLength);
1014 Vector<char> frameData;
1015 makeFrameData(frame, frameData);
1017 return m_handle->send(frameData.data(), frameData.size());
1020 bool WebSocketChannel::sendFrameHixie76(const char* data, size_t dataLength)
1023 ASSERT(!m_suspended);
1026 frame.append('\0'); // Frame type.
1027 frame.append(data, dataLength);
1028 frame.append('\xff'); // Frame end.
1029 return m_handle->send(frame.data(), frame.size());
1032 } // namespace WebCore
1034 #endif // ENABLE(WEB_SOCKETS)