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.
32 #include "modules/websockets/MainThreadWebSocketChannel.h"
34 #include "bindings/v8/ExceptionStatePlaceholder.h"
35 #include "core/dom/Document.h"
36 #include "core/dom/ExecutionContext.h"
37 #include "core/fileapi/Blob.h"
38 #include "core/fileapi/FileReaderLoader.h"
39 #include "core/inspector/InspectorInstrumentation.h"
40 #include "core/loader/CookieJar.h"
41 #include "core/loader/FrameLoader.h"
42 #include "core/loader/FrameLoaderClient.h"
43 #include "core/loader/UniqueIdentifier.h"
44 #include "core/frame/Frame.h"
45 #include "core/page/Page.h"
46 #include "modules/websockets/WebSocketChannelClient.h"
47 #include "platform/Logging.h"
48 #include "platform/network/SocketStreamError.h"
49 #include "platform/network/SocketStreamHandle.h"
50 #include "wtf/ArrayBuffer.h"
51 #include "wtf/FastMalloc.h"
52 #include "wtf/HashMap.h"
53 #include "wtf/OwnPtr.h"
54 #include "wtf/text/StringHash.h"
55 #include "wtf/text/WTFString.h"
61 const double TCPMaximumSegmentLifetime = 2 * 60.0;
63 MainThreadWebSocketChannel::MainThreadWebSocketChannel(Document* document, WebSocketChannelClient* client, const String& sourceURL, unsigned lineNumber)
64 : m_document(document)
66 , m_resumeTimer(this, &MainThreadWebSocketChannel::resumeTimerFired)
68 , m_didFailOfClientAlreadyRun(false)
69 , m_hasCalledDisconnectOnHandle(false)
70 , m_receivedClosingHandshake(false)
71 , m_closingTimer(this, &MainThreadWebSocketChannel::closingTimerFired)
72 , m_state(ChannelIdle)
73 , m_shouldDiscardReceivedData(false)
74 , m_unhandledBufferedAmount(0)
76 , m_hasContinuousFrame(false)
77 , m_closeEventCode(CloseEventCodeAbnormalClosure)
78 , m_outgoingFrameQueueStatus(OutgoingFrameQueueOpen)
79 , m_blobLoaderStatus(BlobLoaderNotStarted)
80 , m_sourceURLAtConstruction(sourceURL)
81 , m_lineNumberAtConstruction(lineNumber)
83 if (m_document->page())
84 m_identifier = createUniqueIdentifier();
87 MainThreadWebSocketChannel::~MainThreadWebSocketChannel()
91 void MainThreadWebSocketChannel::connect(const KURL& url, const String& protocol)
93 WTF_LOG(Network, "MainThreadWebSocketChannel %p connect()", this);
96 m_handshake = adoptPtr(new WebSocketHandshake(url, protocol, m_document));
98 m_handshake->addExtensionProcessor(m_perMessageDeflate.createExtensionProcessor());
99 m_handshake->addExtensionProcessor(m_deflateFramer.createExtensionProcessor());
101 InspectorInstrumentation::didCreateWebSocket(m_document, m_identifier, url, protocol);
103 m_handle = SocketStreamHandle::create(m_handshake->url(), this);
106 String MainThreadWebSocketChannel::subprotocol()
108 WTF_LOG(Network, "MainThreadWebSocketChannel %p subprotocol()", this);
109 if (!m_handshake || m_handshake->mode() != WebSocketHandshake::Connected)
111 String serverProtocol = m_handshake->serverWebSocketProtocol();
112 if (serverProtocol.isNull())
114 return serverProtocol;
117 String MainThreadWebSocketChannel::extensions()
119 WTF_LOG(Network, "MainThreadWebSocketChannel %p extensions()", this);
120 if (!m_handshake || m_handshake->mode() != WebSocketHandshake::Connected)
122 String extensions = m_handshake->acceptedExtensions();
123 if (extensions.isNull())
128 WebSocketChannel::SendResult MainThreadWebSocketChannel::send(const String& message)
130 WTF_LOG(Network, "MainThreadWebSocketChannel %p send() Sending String '%s'", this, message.utf8().data());
131 CString utf8 = message.utf8(StrictUTF8ConversionReplacingUnpairedSurrogatesWithFFFD);
132 enqueueTextFrame(utf8);
133 processOutgoingFrameQueue();
134 // m_channel->send() may happen later, thus it's not always possible to know whether
135 // the message has been sent to the socket successfully. In this case, we have no choice
136 // but to return SendSuccess.
137 return WebSocketChannel::SendSuccess;
140 WebSocketChannel::SendResult MainThreadWebSocketChannel::send(const ArrayBuffer& binaryData, unsigned byteOffset, unsigned byteLength)
142 WTF_LOG(Network, "MainThreadWebSocketChannel %p send() Sending ArrayBuffer %p byteOffset=%u byteLength=%u", this, &binaryData, byteOffset, byteLength);
143 enqueueRawFrame(WebSocketFrame::OpCodeBinary, static_cast<const char*>(binaryData.data()) + byteOffset, byteLength);
144 processOutgoingFrameQueue();
145 return WebSocketChannel::SendSuccess;
148 WebSocketChannel::SendResult MainThreadWebSocketChannel::send(PassRefPtr<BlobDataHandle> binaryData)
150 WTF_LOG(Network, "MainThreadWebSocketChannel %p send() Sending Blob '%s'", this, binaryData->uuid().utf8().data());
151 enqueueBlobFrame(WebSocketFrame::OpCodeBinary, binaryData);
152 processOutgoingFrameQueue();
153 return WebSocketChannel::SendSuccess;
156 bool MainThreadWebSocketChannel::send(const char* data, int length)
158 WTF_LOG(Network, "MainThreadWebSocketChannel %p send() Sending char* data=%p length=%d", this, data, length);
159 enqueueRawFrame(WebSocketFrame::OpCodeBinary, data, length);
160 processOutgoingFrameQueue();
164 unsigned long MainThreadWebSocketChannel::bufferedAmount() const
166 WTF_LOG(Network, "MainThreadWebSocketChannel %p bufferedAmount()", this);
168 ASSERT(!m_suspended);
169 return m_handle->bufferedAmount();
172 void MainThreadWebSocketChannel::close(int code, const String& reason)
174 WTF_LOG(Network, "MainThreadWebSocketChannel %p close() code=%d reason='%s'", this, code, reason.utf8().data());
175 ASSERT(!m_suspended);
178 startClosingHandshake(code, reason);
179 if (!m_closingTimer.isActive())
180 m_closingTimer.startOneShot(2 * TCPMaximumSegmentLifetime);
183 void MainThreadWebSocketChannel::clearDocument()
186 m_handshake->clearDocument();
190 void MainThreadWebSocketChannel::disconnectHandle()
194 m_hasCalledDisconnectOnHandle = true;
195 m_handle->disconnect();
198 void MainThreadWebSocketChannel::fail(const String& reason, MessageLevel level, const String& sourceURL, unsigned lineNumber)
200 WTF_LOG(Network, "MainThreadWebSocketChannel %p fail() reason='%s'", this, reason.utf8().data());
202 InspectorInstrumentation::didReceiveWebSocketFrameError(m_document, m_identifier, reason);
203 const String message = "WebSocket connection to '" + m_handshake->url().elidedString() + "' failed: " + reason;
204 m_document->addConsoleMessage(JSMessageSource, level, message, sourceURL, lineNumber);
206 // Hybi-10 specification explicitly states we must not continue to handle incoming data
207 // once the WebSocket connection is failed (section 7.1.7).
208 RefPtr<MainThreadWebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.
209 m_shouldDiscardReceivedData = true;
210 if (!m_buffer.isEmpty())
211 skipBuffer(m_buffer.size()); // Save memory.
212 m_deflateFramer.didFail();
213 m_perMessageDeflate.didFail();
214 m_hasContinuousFrame = false;
215 m_continuousFrameData.clear();
216 if (!m_didFailOfClientAlreadyRun) {
217 m_didFailOfClientAlreadyRun = true;
219 m_client->didReceiveMessageError();
221 if (m_state != ChannelClosed)
222 disconnectHandle(); // Will call didCloseSocketStream().
225 void MainThreadWebSocketChannel::disconnect()
227 WTF_LOG(Network, "MainThreadWebSocketChannel %p disconnect()", this);
228 if (m_identifier && m_document)
229 InspectorInstrumentation::didCloseWebSocket(m_document, m_identifier);
237 void MainThreadWebSocketChannel::suspend()
242 void MainThreadWebSocketChannel::resume()
245 if ((!m_buffer.isEmpty() || (m_state == ChannelClosed)) && m_client && !m_resumeTimer.isActive())
246 m_resumeTimer.startOneShot(0);
249 void MainThreadWebSocketChannel::willOpenSocketStream(SocketStreamHandle* handle)
251 WTF_LOG(Network, "MainThreadWebSocketChannel %p willOpenSocketStream()", this);
253 if (m_document->frame())
254 m_document->frame()->loader().client()->dispatchWillOpenSocketStream(handle);
257 void MainThreadWebSocketChannel::didOpenSocketStream(SocketStreamHandle* handle)
259 WTF_LOG(Network, "MainThreadWebSocketChannel %p didOpenSocketStream()", this);
260 ASSERT(handle == m_handle);
264 InspectorInstrumentation::willSendWebSocketHandshakeRequest(m_document, m_identifier, *m_handshake->clientHandshakeRequest());
265 CString handshakeMessage = m_handshake->clientHandshakeMessage();
266 if (!handle->send(handshakeMessage.data(), handshakeMessage.length()))
267 failAsError("Failed to send WebSocket handshake.");
270 void MainThreadWebSocketChannel::didCloseSocketStream(SocketStreamHandle* handle)
272 WTF_LOG(Network, "MainThreadWebSocketChannel %p didCloseSocketStream()", this);
273 if (m_identifier && m_document)
274 InspectorInstrumentation::didCloseWebSocket(m_document, m_identifier);
275 ASSERT_UNUSED(handle, handle == m_handle || !m_handle);
277 // Show error message on JS console if this is unexpected connection close
278 // during opening handshake.
279 if (!m_hasCalledDisconnectOnHandle && m_handshake->mode() == WebSocketHandshake::Incomplete && m_document) {
280 const String message = "WebSocket connection to '" + m_handshake->url().elidedString() + "' failed: Connection closed before receiving a handshake response";
281 m_document->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message, m_sourceURLAtConstruction, m_lineNumberAtConstruction);
284 m_state = ChannelClosed;
285 if (m_closingTimer.isActive())
286 m_closingTimer.stop();
287 if (m_outgoingFrameQueueStatus != OutgoingFrameQueueClosed)
288 abortOutgoingFrameQueue();
290 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 MainThreadWebSocketChannel::didReceiveSocketStreamData(SocketStreamHandle* handle, const char* data, int len)
303 WTF_LOG(Network, "MainThreadWebSocketChannel %p didReceiveSocketStreamData() Received %d bytes", this, len);
304 RefPtr<MainThreadWebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.
305 ASSERT(handle == m_handle);
313 m_shouldDiscardReceivedData = true;
317 if (m_shouldDiscardReceivedData)
319 if (!appendToBuffer(data, len)) {
320 m_shouldDiscardReceivedData = true;
321 failAsError("Ran out of memory while receiving WebSocket data.");
327 void MainThreadWebSocketChannel::didUpdateBufferedAmount(SocketStreamHandle*, size_t bufferedAmount)
330 m_client->didUpdateBufferedAmount(bufferedAmount);
333 void MainThreadWebSocketChannel::didFailSocketStream(SocketStreamHandle* handle, const SocketStreamError& error)
335 WTF_LOG(Network, "MainThreadWebSocketChannel %p didFailSocketStream()", this);
336 ASSERT_UNUSED(handle, handle == m_handle || !m_handle);
337 m_shouldDiscardReceivedData = true;
340 message = "WebSocket network error";
341 else if (error.localizedDescription().isNull())
342 message = "WebSocket network error: error code " + String::number(error.errorCode());
344 message = "WebSocket network error: error code " + String::number(error.errorCode()) + ", " + error.localizedDescription();
345 String failingURL = error.failingURL();
346 ASSERT(failingURL.isNull() || m_handshake->url().string() == failingURL);
347 if (failingURL.isNull())
348 failingURL = m_handshake->url().string();
349 WTF_LOG(Network, "Error Message: '%s', FailURL: '%s'", message.utf8().data(), failingURL.utf8().data());
350 RefPtr<WebSocketChannel> protect(this);
351 if (m_client && (m_state != ChannelClosing && m_state != ChannelClosed) && !m_didFailOfClientAlreadyRun) {
352 m_didFailOfClientAlreadyRun = true;
353 m_client->didReceiveMessageError();
355 if (m_state != ChannelClosed)
359 void MainThreadWebSocketChannel::didStartLoading()
361 WTF_LOG(Network, "MainThreadWebSocketChannel %p didStartLoading()", this);
362 ASSERT(m_blobLoader);
363 ASSERT(m_blobLoaderStatus == BlobLoaderStarted);
366 void MainThreadWebSocketChannel::didReceiveData()
368 WTF_LOG(Network, "MainThreadWebSocketChannel %p didReceiveData()", this);
369 ASSERT(m_blobLoader);
370 ASSERT(m_blobLoaderStatus == BlobLoaderStarted);
373 void MainThreadWebSocketChannel::didFinishLoading()
375 WTF_LOG(Network, "MainThreadWebSocketChannel %p didFinishLoading()", this);
376 ASSERT(m_blobLoader);
377 ASSERT(m_blobLoaderStatus == BlobLoaderStarted);
378 m_blobLoaderStatus = BlobLoaderFinished;
379 processOutgoingFrameQueue();
383 void MainThreadWebSocketChannel::didFail(FileError::ErrorCode errorCode)
385 WTF_LOG(Network, "MainThreadWebSocketChannel %p didFail() errorCode=%d", this, errorCode);
386 ASSERT(m_blobLoader);
387 ASSERT(m_blobLoaderStatus == BlobLoaderStarted);
388 m_blobLoader.clear();
389 m_blobLoaderStatus = BlobLoaderFailed;
390 failAsError("Failed to load Blob: error code = " + String::number(errorCode)); // FIXME: Generate human-friendly reason message.
394 bool MainThreadWebSocketChannel::appendToBuffer(const char* data, size_t len)
396 size_t newBufferSize = m_buffer.size() + len;
397 if (newBufferSize < m_buffer.size()) {
398 WTF_LOG(Network, "MainThreadWebSocketChannel %p appendToBuffer() Buffer overflow (%lu bytes already in receive buffer and appending %lu bytes)", this, static_cast<unsigned long>(m_buffer.size()), static_cast<unsigned long>(len));
401 m_buffer.append(data, len);
405 void MainThreadWebSocketChannel::skipBuffer(size_t len)
407 ASSERT_WITH_SECURITY_IMPLICATION(len <= m_buffer.size());
408 memmove(m_buffer.data(), m_buffer.data() + len, m_buffer.size() - len);
409 m_buffer.resize(m_buffer.size() - len);
412 void MainThreadWebSocketChannel::processBuffer()
414 while (!m_suspended && m_client && !m_buffer.isEmpty()) {
415 if (!processOneItemFromBuffer())
420 bool MainThreadWebSocketChannel::processOneItemFromBuffer()
422 ASSERT(!m_suspended);
424 ASSERT(!m_buffer.isEmpty());
425 WTF_LOG(Network, "MainThreadWebSocketChannel %p processBuffer() Receive buffer has %lu bytes", this, static_cast<unsigned long>(m_buffer.size()));
427 if (m_shouldDiscardReceivedData)
430 if (m_receivedClosingHandshake) {
431 skipBuffer(m_buffer.size());
435 RefPtr<MainThreadWebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.
437 if (m_handshake->mode() == WebSocketHandshake::Incomplete) {
438 int headerLength = m_handshake->readServerHandshake(m_buffer.data(), m_buffer.size());
439 if (headerLength <= 0)
441 if (m_handshake->mode() == WebSocketHandshake::Connected) {
443 InspectorInstrumentation::didReceiveWebSocketHandshakeResponse(m_document, m_identifier, m_handshake->serverHandshakeResponse());
445 if (m_deflateFramer.enabled() && m_document) {
446 const String message = "WebSocket extension \"x-webkit-deflate-frame\" is deprecated";
447 m_document->addConsoleMessage(JSMessageSource, WarningMessageLevel, message, m_sourceURLAtConstruction, m_lineNumberAtConstruction);
450 if (!m_handshake->serverSetCookie().isEmpty()) {
451 if (cookiesEnabled(m_document)) {
452 // Exception (for sandboxed documents) ignored.
453 m_document->setCookie(m_handshake->serverSetCookie(), IGNORE_EXCEPTION);
456 // FIXME: handle set-cookie2.
457 WTF_LOG(Network, "MainThreadWebSocketChannel %p Connected", this);
458 skipBuffer(headerLength);
459 m_client->didConnect();
460 WTF_LOG(Network, "MainThreadWebSocketChannel %p %lu bytes remaining in m_buffer", this, static_cast<unsigned long>(m_buffer.size()));
461 return !m_buffer.isEmpty();
463 ASSERT(m_handshake->mode() == WebSocketHandshake::Failed);
464 WTF_LOG(Network, "MainThreadWebSocketChannel %p Connection failed", this);
465 skipBuffer(headerLength);
466 m_shouldDiscardReceivedData = true;
467 failAsError(m_handshake->failureReason());
470 if (m_handshake->mode() != WebSocketHandshake::Connected)
473 return processFrame();
476 void MainThreadWebSocketChannel::resumeTimerFired(Timer<MainThreadWebSocketChannel>* timer)
478 ASSERT_UNUSED(timer, timer == &m_resumeTimer);
480 RefPtr<MainThreadWebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.
482 if (!m_suspended && m_client && (m_state == ChannelClosed) && m_handle)
483 didCloseSocketStream(m_handle.get());
486 void MainThreadWebSocketChannel::startClosingHandshake(int code, const String& reason)
488 WTF_LOG(Network, "MainThreadWebSocketChannel %p startClosingHandshake() code=%d m_state=%d m_receivedClosingHandshake=%d", this, code, m_state, m_receivedClosingHandshake);
489 if (m_state == ChannelClosing || m_state == ChannelClosed)
494 if (!m_receivedClosingHandshake && code != CloseEventCodeNotSpecified) {
495 unsigned char highByte = code >> 8;
496 unsigned char lowByte = code;
497 buf.append(static_cast<char>(highByte));
498 buf.append(static_cast<char>(lowByte));
499 buf.append(reason.utf8().data(), reason.utf8().length());
501 enqueueRawFrame(WebSocketFrame::OpCodeClose, buf.data(), buf.size());
502 processOutgoingFrameQueue();
504 m_state = ChannelClosing;
506 m_client->didStartClosingHandshake();
509 void MainThreadWebSocketChannel::closingTimerFired(Timer<MainThreadWebSocketChannel>* timer)
511 WTF_LOG(Network, "MainThreadWebSocketChannel %p closingTimerFired()", this);
512 ASSERT_UNUSED(timer, &m_closingTimer == timer);
517 bool MainThreadWebSocketChannel::processFrame()
519 ASSERT(!m_buffer.isEmpty());
521 WebSocketFrame frame;
522 const char* frameEnd;
524 WebSocketFrame::ParseFrameResult result = WebSocketFrame::parseFrame(m_buffer.data(), m_buffer.size(), frame, frameEnd, errorString);
525 if (result == WebSocketFrame::FrameIncomplete)
527 if (result == WebSocketFrame::FrameError) {
528 failAsError(errorString);
532 ASSERT(m_buffer.data() < frameEnd);
533 ASSERT(frameEnd <= m_buffer.data() + m_buffer.size());
535 OwnPtr<InflateResultHolder> inflateResult = m_deflateFramer.inflate(frame);
536 if (!inflateResult->succeeded()) {
537 failAsError(inflateResult->failureReason());
540 if (!m_perMessageDeflate.inflate(frame)) {
541 failAsError(m_perMessageDeflate.failureReason());
545 // Validate the frame data.
546 if (WebSocketFrame::isReservedOpCode(frame.opCode)) {
547 failAsError("Unrecognized frame opcode: " + String::number(frame.opCode));
551 if (frame.compress || frame.reserved2 || frame.reserved3) {
552 failAsError("One or more reserved bits are on: reserved1 = " + String::number(frame.compress) + ", reserved2 = " + String::number(frame.reserved2) + ", reserved3 = " + String::number(frame.reserved3));
557 failAsError("A server must not mask any frames that it sends to the client.");
561 // All control frames must not be fragmented.
562 if (WebSocketFrame::isControlOpCode(frame.opCode) && !frame.final) {
563 failAsError("Received fragmented control frame: opcode = " + String::number(frame.opCode));
567 // All control frames must have a payload of 125 bytes or less, which means the frame must not contain
568 // the "extended payload length" field.
569 if (WebSocketFrame::isControlOpCode(frame.opCode) && WebSocketFrame::needsExtendedLengthField(frame.payloadLength)) {
570 failAsError("Received control frame having too long payload: " + String::number(frame.payloadLength) + " bytes");
574 // A new data frame is received before the previous continuous frame finishes.
575 // Note that control frames are allowed to come in the middle of continuous frames.
576 if (m_hasContinuousFrame && frame.opCode != WebSocketFrame::OpCodeContinuation && !WebSocketFrame::isControlOpCode(frame.opCode)) {
577 failAsError("Received start of new message but previous message is unfinished.");
581 InspectorInstrumentation::didReceiveWebSocketFrame(m_document, m_identifier, frame.opCode, frame.masked, frame.payload, frame.payloadLength);
583 switch (frame.opCode) {
584 case WebSocketFrame::OpCodeContinuation:
585 // An unexpected continuation frame is received without any leading frame.
586 if (!m_hasContinuousFrame) {
587 failAsError("Received unexpected continuation frame.");
590 m_continuousFrameData.append(frame.payload, frame.payloadLength);
591 skipBuffer(frameEnd - m_buffer.data());
593 // onmessage handler may eventually call the other methods of this channel,
594 // so we should pretend that we have finished to read this frame and
595 // make sure that the member variables are in a consistent state before
596 // the handler is invoked.
597 // Vector<char>::swap() is used here to clear m_continuousFrameData.
598 OwnPtr<Vector<char> > continuousFrameData = adoptPtr(new Vector<char>);
599 m_continuousFrameData.swap(*continuousFrameData);
600 m_hasContinuousFrame = false;
601 if (m_continuousFrameOpCode == WebSocketFrame::OpCodeText) {
603 if (continuousFrameData->size())
604 message = String::fromUTF8(continuousFrameData->data(), continuousFrameData->size());
607 if (message.isNull())
608 failAsError("Could not decode a text frame as UTF-8.");
610 m_client->didReceiveMessage(message);
611 } else if (m_continuousFrameOpCode == WebSocketFrame::OpCodeBinary)
612 m_client->didReceiveBinaryData(continuousFrameData.release());
616 case WebSocketFrame::OpCodeText:
619 if (frame.payloadLength)
620 message = String::fromUTF8(frame.payload, frame.payloadLength);
623 skipBuffer(frameEnd - m_buffer.data());
624 if (message.isNull())
625 failAsError("Could not decode a text frame as UTF-8.");
627 m_client->didReceiveMessage(message);
629 m_hasContinuousFrame = true;
630 m_continuousFrameOpCode = WebSocketFrame::OpCodeText;
631 ASSERT(m_continuousFrameData.isEmpty());
632 m_continuousFrameData.append(frame.payload, frame.payloadLength);
633 skipBuffer(frameEnd - m_buffer.data());
637 case WebSocketFrame::OpCodeBinary:
639 OwnPtr<Vector<char> > binaryData = adoptPtr(new Vector<char>(frame.payloadLength));
640 memcpy(binaryData->data(), frame.payload, frame.payloadLength);
641 skipBuffer(frameEnd - m_buffer.data());
642 m_client->didReceiveBinaryData(binaryData.release());
644 m_hasContinuousFrame = true;
645 m_continuousFrameOpCode = WebSocketFrame::OpCodeBinary;
646 ASSERT(m_continuousFrameData.isEmpty());
647 m_continuousFrameData.append(frame.payload, frame.payloadLength);
648 skipBuffer(frameEnd - m_buffer.data());
652 case WebSocketFrame::OpCodeClose:
653 if (!frame.payloadLength)
654 m_closeEventCode = CloseEventCodeNoStatusRcvd;
655 else if (frame.payloadLength == 1) {
656 m_closeEventCode = CloseEventCodeAbnormalClosure;
657 failAsError("Received a broken close frame containing an invalid size body.");
660 unsigned char highByte = static_cast<unsigned char>(frame.payload[0]);
661 unsigned char lowByte = static_cast<unsigned char>(frame.payload[1]);
662 m_closeEventCode = highByte << 8 | lowByte;
663 if (m_closeEventCode == CloseEventCodeNoStatusRcvd || m_closeEventCode == CloseEventCodeAbnormalClosure || m_closeEventCode == CloseEventCodeTLSHandshake) {
664 m_closeEventCode = CloseEventCodeAbnormalClosure;
665 failAsError("Received a broken close frame containing a reserved status code.");
669 if (frame.payloadLength >= 3)
670 m_closeEventReason = String::fromUTF8(&frame.payload[2], frame.payloadLength - 2);
672 m_closeEventReason = "";
673 skipBuffer(frameEnd - m_buffer.data());
674 m_receivedClosingHandshake = true;
675 startClosingHandshake(m_closeEventCode, m_closeEventReason);
676 m_outgoingFrameQueueStatus = OutgoingFrameQueueClosing;
677 processOutgoingFrameQueue();
680 case WebSocketFrame::OpCodePing:
681 enqueueRawFrame(WebSocketFrame::OpCodePong, frame.payload, frame.payloadLength);
682 skipBuffer(frameEnd - m_buffer.data());
683 processOutgoingFrameQueue();
686 case WebSocketFrame::OpCodePong:
687 // A server may send a pong in response to our ping, or an unsolicited pong which is not associated with
688 // any specific ping. Either way, there's nothing to do on receipt of pong.
689 skipBuffer(frameEnd - m_buffer.data());
693 ASSERT_NOT_REACHED();
694 skipBuffer(frameEnd - m_buffer.data());
698 m_perMessageDeflate.resetInflateBuffer();
699 return !m_buffer.isEmpty();
702 void MainThreadWebSocketChannel::enqueueTextFrame(const CString& string)
704 ASSERT(m_outgoingFrameQueueStatus == OutgoingFrameQueueOpen);
705 OwnPtr<QueuedFrame> frame = adoptPtr(new QueuedFrame);
706 frame->opCode = WebSocketFrame::OpCodeText;
707 frame->frameType = QueuedFrameTypeString;
708 frame->stringData = string;
709 m_outgoingFrameQueue.append(frame.release());
712 void MainThreadWebSocketChannel::enqueueRawFrame(WebSocketFrame::OpCode opCode, const char* data, size_t dataLength)
714 ASSERT(m_outgoingFrameQueueStatus == OutgoingFrameQueueOpen);
715 OwnPtr<QueuedFrame> frame = adoptPtr(new QueuedFrame);
716 frame->opCode = opCode;
717 frame->frameType = QueuedFrameTypeVector;
718 frame->vectorData.resize(dataLength);
720 memcpy(frame->vectorData.data(), data, dataLength);
721 m_outgoingFrameQueue.append(frame.release());
724 void MainThreadWebSocketChannel::enqueueBlobFrame(WebSocketFrame::OpCode opCode, PassRefPtr<BlobDataHandle> blobData)
726 ASSERT(m_outgoingFrameQueueStatus == OutgoingFrameQueueOpen);
727 OwnPtr<QueuedFrame> frame = adoptPtr(new QueuedFrame);
728 frame->opCode = opCode;
729 frame->frameType = QueuedFrameTypeBlob;
730 frame->blobData = blobData;
731 m_outgoingFrameQueue.append(frame.release());
734 void MainThreadWebSocketChannel::processOutgoingFrameQueue()
736 if (m_outgoingFrameQueueStatus == OutgoingFrameQueueClosed)
739 while (!m_outgoingFrameQueue.isEmpty()) {
740 OwnPtr<QueuedFrame> frame = m_outgoingFrameQueue.takeFirst();
741 switch (frame->frameType) {
742 case QueuedFrameTypeString: {
743 if (!sendFrame(frame->opCode, frame->stringData.data(), frame->stringData.length()))
744 failAsError("Failed to send WebSocket frame.");
748 case QueuedFrameTypeVector:
749 if (!sendFrame(frame->opCode, frame->vectorData.data(), frame->vectorData.size()))
750 failAsError("Failed to send WebSocket frame.");
753 case QueuedFrameTypeBlob: {
754 switch (m_blobLoaderStatus) {
755 case BlobLoaderNotStarted:
756 ref(); // Will be derefed after didFinishLoading() or didFail().
757 ASSERT(!m_blobLoader);
758 m_blobLoader = adoptPtr(new FileReaderLoader(FileReaderLoader::ReadAsArrayBuffer, this));
759 m_blobLoaderStatus = BlobLoaderStarted;
760 m_blobLoader->start(m_document, frame->blobData);
761 m_outgoingFrameQueue.prepend(frame.release());
764 case BlobLoaderStarted:
765 case BlobLoaderFailed:
766 m_outgoingFrameQueue.prepend(frame.release());
769 case BlobLoaderFinished: {
770 RefPtr<ArrayBuffer> result = m_blobLoader->arrayBufferResult();
771 m_blobLoader.clear();
772 m_blobLoaderStatus = BlobLoaderNotStarted;
773 if (!sendFrame(frame->opCode, static_cast<const char*>(result->data()), result->byteLength()))
774 failAsError("Failed to send WebSocket frame.");
782 ASSERT_NOT_REACHED();
787 ASSERT(m_outgoingFrameQueue.isEmpty());
788 if (m_outgoingFrameQueueStatus == OutgoingFrameQueueClosing) {
789 m_outgoingFrameQueueStatus = OutgoingFrameQueueClosed;
794 void MainThreadWebSocketChannel::abortOutgoingFrameQueue()
796 m_outgoingFrameQueue.clear();
797 m_outgoingFrameQueueStatus = OutgoingFrameQueueClosed;
798 if (m_blobLoaderStatus == BlobLoaderStarted) {
799 m_blobLoader->cancel();
800 didFail(FileError::ABORT_ERR);
804 bool MainThreadWebSocketChannel::sendFrame(WebSocketFrame::OpCode opCode, const char* data, size_t dataLength)
807 ASSERT(!m_suspended);
809 WebSocketFrame frame(opCode, data, dataLength, WebSocketFrame::Final | WebSocketFrame::Masked);
810 InspectorInstrumentation::didSendWebSocketFrame(m_document, m_identifier, frame.opCode, frame.masked, frame.payload, frame.payloadLength);
812 OwnPtr<DeflateResultHolder> deflateResult = m_deflateFramer.deflate(frame);
813 if (!deflateResult->succeeded()) {
814 failAsError(deflateResult->failureReason());
818 if (!m_perMessageDeflate.deflate(frame)) {
819 failAsError(m_perMessageDeflate.failureReason());
823 Vector<char> frameData;
824 frame.makeFrameData(frameData);
826 m_perMessageDeflate.resetDeflateBuffer();
827 return m_handle->send(frameData.data(), frameData.size());
830 } // namespace WebCore