WebCore/websockets/WebSocketChannel.cpp
changeset 0 4f2f89ce4247
equal deleted inserted replaced
-1:000000000000 0:4f2f89ce4247
       
     1 /*
       
     2  * Copyright (C) 2009 Google Inc.  All rights reserved.
       
     3  *
       
     4  * Redistribution and use in source and binary forms, with or without
       
     5  * modification, are permitted provided that the following conditions are
       
     6  * met:
       
     7  *
       
     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
       
    13  * distribution.
       
    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.
       
    17  *
       
    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.
       
    29  */
       
    30 
       
    31 #include "config.h"
       
    32 
       
    33 #if ENABLE(WEB_SOCKETS)
       
    34 
       
    35 #include "WebSocketChannel.h"
       
    36 
       
    37 #include "CookieJar.h"
       
    38 #include "Document.h"
       
    39 #include "Logging.h"
       
    40 #include "PlatformString.h"
       
    41 #include "ScriptExecutionContext.h"
       
    42 #include "SocketStreamError.h"
       
    43 #include "SocketStreamHandle.h"
       
    44 #include "StringHash.h"
       
    45 #include "WebSocketChannelClient.h"
       
    46 #include "WebSocketHandshake.h"
       
    47 
       
    48 #include <wtf/text/CString.h>
       
    49 #include <wtf/Deque.h>
       
    50 #include <wtf/FastMalloc.h>
       
    51 #include <wtf/HashMap.h>
       
    52 
       
    53 namespace WebCore {
       
    54 
       
    55 WebSocketChannel::WebSocketChannel(ScriptExecutionContext* context, WebSocketChannelClient* client, const KURL& url, const String& protocol)
       
    56     : m_context(context)
       
    57     , m_client(client)
       
    58     , m_handshake(url, protocol, context)
       
    59     , m_buffer(0)
       
    60     , m_bufferSize(0)
       
    61     , m_resumeTimer(this, &WebSocketChannel::resumeTimerFired)
       
    62     , m_suspended(false)
       
    63     , m_closed(false)
       
    64     , m_unhandledBufferedAmount(0)
       
    65 {
       
    66 }
       
    67 
       
    68 WebSocketChannel::~WebSocketChannel()
       
    69 {
       
    70     fastFree(m_buffer);
       
    71 }
       
    72 
       
    73 void WebSocketChannel::connect()
       
    74 {
       
    75     LOG(Network, "WebSocketChannel %p connect", this);
       
    76     ASSERT(!m_handle);
       
    77     ASSERT(!m_suspended);
       
    78     m_handshake.reset();
       
    79     ref();
       
    80     m_handle = SocketStreamHandle::create(m_handshake.url(), this);
       
    81 }
       
    82 
       
    83 bool WebSocketChannel::send(const String& msg)
       
    84 {
       
    85     LOG(Network, "WebSocketChannel %p send %s", this, msg.utf8().data());
       
    86     ASSERT(m_handle);
       
    87     ASSERT(!m_suspended);
       
    88     Vector<char> buf;
       
    89     buf.append('\0');  // frame type
       
    90     buf.append(msg.utf8().data(), msg.utf8().length());
       
    91     buf.append('\xff');  // frame end
       
    92     return m_handle->send(buf.data(), buf.size());
       
    93 }
       
    94 
       
    95 unsigned long WebSocketChannel::bufferedAmount() const
       
    96 {
       
    97     LOG(Network, "WebSocketChannel %p bufferedAmount", this);
       
    98     ASSERT(m_handle);
       
    99     ASSERT(!m_suspended);
       
   100     return m_handle->bufferedAmount();
       
   101 }
       
   102 
       
   103 void WebSocketChannel::close()
       
   104 {
       
   105     LOG(Network, "WebSocketChannel %p close", this);
       
   106     ASSERT(!m_suspended);
       
   107     if (m_handle)
       
   108         m_handle->close();  // will call didClose()
       
   109 }
       
   110 
       
   111 void WebSocketChannel::disconnect()
       
   112 {
       
   113     LOG(Network, "WebSocketChannel %p disconnect", this);
       
   114     m_handshake.clearScriptExecutionContext();
       
   115     m_client = 0;
       
   116     m_context = 0;
       
   117     if (m_handle)
       
   118         m_handle->close();
       
   119 }
       
   120 
       
   121 void WebSocketChannel::suspend()
       
   122 {
       
   123     m_suspended = true;
       
   124 }
       
   125 
       
   126 void WebSocketChannel::resume()
       
   127 {
       
   128     m_suspended = false;
       
   129     if ((m_buffer || m_closed) && m_client && !m_resumeTimer.isActive())
       
   130         m_resumeTimer.startOneShot(0);
       
   131 }
       
   132 
       
   133 void WebSocketChannel::didOpen(SocketStreamHandle* handle)
       
   134 {
       
   135     LOG(Network, "WebSocketChannel %p didOpen", this);
       
   136     ASSERT(handle == m_handle);
       
   137     if (!m_context)
       
   138         return;
       
   139     const CString& handshakeMessage = m_handshake.clientHandshakeMessage();
       
   140     if (!handle->send(handshakeMessage.data(), handshakeMessage.length())) {
       
   141         m_context->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "Error sending handshake message.", 0, m_handshake.clientOrigin());
       
   142         handle->close();
       
   143     }
       
   144 }
       
   145 
       
   146 void WebSocketChannel::didClose(SocketStreamHandle* handle)
       
   147 {
       
   148     LOG(Network, "WebSocketChannel %p didClose", this);
       
   149     ASSERT_UNUSED(handle, handle == m_handle || !m_handle);
       
   150     m_closed = true;
       
   151     if (m_handle) {
       
   152         m_unhandledBufferedAmount = m_handle->bufferedAmount();
       
   153         if (m_suspended)
       
   154             return;
       
   155         WebSocketChannelClient* client = m_client;
       
   156         m_client = 0;
       
   157         m_context = 0;
       
   158         m_handle = 0;
       
   159         if (client)
       
   160             client->didClose(m_unhandledBufferedAmount);
       
   161     }
       
   162     deref();
       
   163 }
       
   164 
       
   165 void WebSocketChannel::didReceiveData(SocketStreamHandle* handle, const char* data, int len)
       
   166 {
       
   167     LOG(Network, "WebSocketChannel %p didReceiveData %d", this, len);
       
   168     RefPtr<WebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.
       
   169     ASSERT(handle == m_handle);
       
   170     if (!m_context) {
       
   171         return;
       
   172     }
       
   173     if (!m_client) {
       
   174         handle->close();
       
   175         return;
       
   176     }
       
   177     if (!appendToBuffer(data, len)) {
       
   178         handle->close();
       
   179         return;
       
   180     }
       
   181     while (!m_suspended && m_client && m_buffer)
       
   182         if (!processBuffer())
       
   183             break;
       
   184 }
       
   185 
       
   186 void WebSocketChannel::didFail(SocketStreamHandle* handle, const SocketStreamError&)
       
   187 {
       
   188     LOG(Network, "WebSocketChannel %p didFail", this);
       
   189     ASSERT(handle == m_handle || !m_handle);
       
   190     handle->close();
       
   191 }
       
   192 
       
   193 void WebSocketChannel::didReceiveAuthenticationChallenge(SocketStreamHandle*, const AuthenticationChallenge&)
       
   194 {
       
   195 }
       
   196 
       
   197 void WebSocketChannel::didCancelAuthenticationChallenge(SocketStreamHandle*, const AuthenticationChallenge&)
       
   198 {
       
   199 }
       
   200 
       
   201 bool WebSocketChannel::appendToBuffer(const char* data, int len)
       
   202 {
       
   203     char* newBuffer = 0;
       
   204     if (tryFastMalloc(m_bufferSize + len).getValue(newBuffer)) {
       
   205         if (m_buffer)
       
   206             memcpy(newBuffer, m_buffer, m_bufferSize);
       
   207         memcpy(newBuffer + m_bufferSize, data, len);
       
   208         fastFree(m_buffer);
       
   209         m_buffer = newBuffer;
       
   210         m_bufferSize += len;
       
   211         return true;
       
   212     }
       
   213     m_context->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, String::format("WebSocket frame (at %d bytes) is too long.", m_bufferSize + len), 0, m_handshake.clientOrigin());
       
   214     return false;
       
   215 }
       
   216 
       
   217 void WebSocketChannel::skipBuffer(int len)
       
   218 {
       
   219     ASSERT(len <= m_bufferSize);
       
   220     m_bufferSize -= len;
       
   221     if (!m_bufferSize) {
       
   222         fastFree(m_buffer);
       
   223         m_buffer = 0;
       
   224         return;
       
   225     }
       
   226     memmove(m_buffer, m_buffer + len, m_bufferSize);
       
   227 }
       
   228 
       
   229 bool WebSocketChannel::processBuffer()
       
   230 {
       
   231     ASSERT(!m_suspended);
       
   232     ASSERT(m_client);
       
   233     ASSERT(m_buffer);
       
   234 
       
   235     if (m_handshake.mode() == WebSocketHandshake::Incomplete) {
       
   236         int headerLength = m_handshake.readServerHandshake(m_buffer, m_bufferSize);
       
   237         if (headerLength <= 0)
       
   238             return false;
       
   239         if (m_handshake.mode() == WebSocketHandshake::Connected) {
       
   240             if (!m_handshake.serverSetCookie().isEmpty()) {
       
   241                 if (m_context->isDocument()) {
       
   242                     Document* document = static_cast<Document*>(m_context);
       
   243                     if (cookiesEnabled(document)) {
       
   244                         ExceptionCode ec; // Exception (for sandboxed documents) ignored.
       
   245                         document->setCookie(m_handshake.serverSetCookie(), ec);
       
   246                     }
       
   247                 }
       
   248             }
       
   249             // FIXME: handle set-cookie2.
       
   250             LOG(Network, "WebSocketChannel %p connected", this);
       
   251             skipBuffer(headerLength);
       
   252             m_client->didConnect();
       
   253             LOG(Network, "remaining in read buf %ul", m_bufferSize);
       
   254             return m_buffer;
       
   255         }
       
   256         LOG(Network, "WebSocketChannel %p connection failed", this);
       
   257         skipBuffer(headerLength);
       
   258         if (!m_closed)
       
   259             m_handle->close();
       
   260         return false;
       
   261     }
       
   262     if (m_handshake.mode() != WebSocketHandshake::Connected)
       
   263         return false;
       
   264 
       
   265     const char* nextFrame = m_buffer;
       
   266     const char* p = m_buffer;
       
   267     const char* end = p + m_bufferSize;
       
   268 
       
   269     unsigned char frameByte = static_cast<unsigned char>(*p++);
       
   270     if ((frameByte & 0x80) == 0x80) {
       
   271         int length = 0;
       
   272         while (p < end) {
       
   273             if (length > std::numeric_limits<int>::max() / 128) {
       
   274                 LOG(Network, "frame length overflow %d", length);
       
   275                 skipBuffer(p + length - m_buffer);
       
   276                 m_client->didReceiveMessageError();
       
   277                 if (!m_client)
       
   278                     return false;
       
   279                 if (!m_closed)
       
   280                     m_handle->close();
       
   281                 return false;
       
   282             }
       
   283             char msgByte = *p;
       
   284             length = length * 128 + (msgByte & 0x7f);
       
   285             ++p;
       
   286             if (!(msgByte & 0x80))
       
   287                 break;
       
   288         }
       
   289         if (p + length < end) {
       
   290             p += length;
       
   291             nextFrame = p;
       
   292             skipBuffer(nextFrame - m_buffer);
       
   293             m_client->didReceiveMessageError();
       
   294             return m_buffer;
       
   295         }
       
   296         return false;
       
   297     }
       
   298 
       
   299     const char* msgStart = p;
       
   300     while (p < end && *p != '\xff')
       
   301         ++p;
       
   302     if (p < end && *p == '\xff') {
       
   303         int msgLength = p - msgStart;
       
   304         ++p;
       
   305         nextFrame = p;
       
   306         if (frameByte == 0x00) {
       
   307             String msg = String::fromUTF8(msgStart, msgLength);
       
   308             skipBuffer(nextFrame - m_buffer);
       
   309             m_client->didReceiveMessage(msg);
       
   310         } else {
       
   311             skipBuffer(nextFrame - m_buffer);
       
   312             m_client->didReceiveMessageError();
       
   313         }
       
   314         return m_buffer;
       
   315     }
       
   316     return false;
       
   317 }
       
   318 
       
   319 void WebSocketChannel::resumeTimerFired(Timer<WebSocketChannel>* timer)
       
   320 {
       
   321     ASSERT_UNUSED(timer, timer == &m_resumeTimer);
       
   322 
       
   323     RefPtr<WebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference.
       
   324     while (!m_suspended && m_client && m_buffer)
       
   325         if (!processBuffer())
       
   326             break;
       
   327     if (!m_suspended && m_client && m_closed && m_handle)
       
   328         didClose(m_handle.get());
       
   329 }
       
   330 
       
   331 }  // namespace WebCore
       
   332 
       
   333 #endif  // ENABLE(WEB_SOCKETS)