Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / modules / websockets / WebSocket.cpp
1 /*
2  * Copyright (C) 2011 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 #include "modules/websockets/WebSocket.h"
34
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"
64
65 using namespace std;
66
67 namespace WebCore {
68
69 WebSocket::EventQueue::EventQueue(EventTarget* target)
70     : m_state(Active)
71     , m_target(target)
72     , m_resumeTimer(this, &EventQueue::resumeTimerFired) { }
73
74 WebSocket::EventQueue::~EventQueue() { stop(); }
75
76 void WebSocket::EventQueue::dispatch(PassRefPtrWillBeRawPtr<Event> event)
77 {
78     switch (m_state) {
79     case Active:
80         ASSERT(m_events.isEmpty());
81         ASSERT(m_target->executionContext());
82         m_target->dispatchEvent(event);
83         break;
84     case Suspended:
85         m_events.append(event);
86         break;
87     case Stopped:
88         ASSERT(m_events.isEmpty());
89         // Do nothing.
90         break;
91     }
92 }
93
94 bool WebSocket::EventQueue::isEmpty() const
95 {
96     return m_events.isEmpty();
97 }
98
99 void WebSocket::EventQueue::suspend()
100 {
101     if (m_state != Active)
102         return;
103
104     m_state = Suspended;
105 }
106
107 void WebSocket::EventQueue::resume()
108 {
109     if (m_state != Suspended || m_resumeTimer.isActive())
110         return;
111
112     m_resumeTimer.startOneShot(0, FROM_HERE);
113 }
114
115 void WebSocket::EventQueue::stop()
116 {
117     if (m_state == Stopped)
118         return;
119
120     m_state = Stopped;
121     m_resumeTimer.stop();
122     m_events.clear();
123 }
124
125 void WebSocket::EventQueue::dispatchQueuedEvents()
126 {
127     if (m_state != Active)
128         return;
129
130     RefPtrWillBeRawPtr<EventQueue> protect(this);
131
132     WillBeHeapDeque<RefPtrWillBeMember<Event> > events;
133     events.swap(m_events);
134     while (!events.isEmpty()) {
135         if (m_state == Stopped || m_state == Suspended)
136             break;
137         ASSERT(m_state == Active);
138         ASSERT(m_target->executionContext());
139         m_target->dispatchEvent(events.takeFirst());
140         // |this| can be stopped here.
141     }
142     if (m_state == Suspended) {
143         while (!m_events.isEmpty())
144             events.append(m_events.takeFirst());
145         events.swap(m_events);
146     }
147 }
148
149 void WebSocket::EventQueue::resumeTimerFired(Timer<EventQueue>*)
150 {
151     ASSERT(m_state == Suspended);
152     m_state = Active;
153     dispatchQueuedEvents();
154 }
155
156 void WebSocket::EventQueue::trace(Visitor* visitor)
157 {
158     visitor->trace(m_events);
159 }
160
161 const size_t maxReasonSizeInBytes = 123;
162
163 static inline bool isValidSubprotocolCharacter(UChar character)
164 {
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;
174 }
175
176 static bool isValidSubprotocolString(const String& protocol)
177 {
178     if (protocol.isEmpty())
179         return false;
180     for (size_t i = 0; i < protocol.length(); ++i) {
181         if (!isValidSubprotocolCharacter(protocol[i]))
182             return false;
183     }
184     return true;
185 }
186
187 static String encodeSubprotocolString(const String& protocol)
188 {
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("\\\\");
195         else
196             builder.append(protocol[i]);
197     }
198     return builder.toString();
199 }
200
201 static String joinStrings(const Vector<String>& strings, const char* separator)
202 {
203     StringBuilder builder;
204     for (size_t i = 0; i < strings.size(); ++i) {
205         if (i)
206             builder.append(separator);
207         builder.append(strings[i]);
208     }
209     return builder.toString();
210 }
211
212 static unsigned long saturateAdd(unsigned long a, unsigned long b)
213 {
214     if (numeric_limits<unsigned long>::max() - a < b)
215         return numeric_limits<unsigned long>::max();
216     return a + b;
217 }
218
219 static void setInvalidStateErrorForSendMethod(ExceptionState& exceptionState)
220 {
221     exceptionState.throwDOMException(InvalidStateError, "Still in CONNECTING state.");
222 }
223
224 const char* WebSocket::subProtocolSeperator()
225 {
226     return ", ";
227 }
228
229 WebSocket::WebSocket(ExecutionContext* context)
230     : ActiveDOMObject(context)
231     , m_state(CONNECTING)
232     , m_bufferedAmount(0)
233     , m_bufferedAmountAfterClose(0)
234     , m_binaryType(BinaryTypeBlob)
235     , m_subprotocol("")
236     , m_extensions("")
237     , m_eventQueue(EventQueue::create(this))
238 {
239     ScriptWrappable::init(this);
240 }
241
242 WebSocket::~WebSocket()
243 {
244     ASSERT(!m_channel);
245 }
246
247 void WebSocket::logError(const String& message)
248 {
249     executionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
250 }
251
252 PassRefPtrWillBeRawPtr<WebSocket> WebSocket::create(ExecutionContext* context, const String& url, ExceptionState& exceptionState)
253 {
254     Vector<String> protocols;
255     return create(context, url, protocols, exceptionState);
256 }
257
258 PassRefPtrWillBeRawPtr<WebSocket> WebSocket::create(ExecutionContext* context, const String& url, const Vector<String>& protocols, ExceptionState& exceptionState)
259 {
260     if (url.isNull()) {
261         exceptionState.throwDOMException(SyntaxError, "Failed to create a WebSocket: the provided URL is invalid.");
262         return nullptr;
263     }
264
265     RefPtrWillBeRawPtr<WebSocket> webSocket(adoptRefWillBeRefCountedGarbageCollected(new WebSocket(context)));
266     webSocket->suspendIfNeeded();
267
268     webSocket->connect(url, protocols, exceptionState);
269     if (exceptionState.hadException())
270         return nullptr;
271
272     return webSocket.release();
273 }
274
275 PassRefPtrWillBeRawPtr<WebSocket> WebSocket::create(ExecutionContext* context, const String& url, const String& protocol, ExceptionState& exceptionState)
276 {
277     Vector<String> protocols;
278     protocols.append(protocol);
279     return create(context, url, protocols, exceptionState);
280 }
281
282 void WebSocket::connect(const String& url, ExceptionState& exceptionState)
283 {
284     Vector<String> protocols;
285     connect(url, protocols, exceptionState);
286 }
287
288 void WebSocket::connect(const String& url, const String& protocol, ExceptionState& exceptionState)
289 {
290     Vector<String> protocols;
291     protocols.append(protocol);
292     connect(url, protocols, exceptionState);
293 }
294
295 void WebSocket::connect(const String& url, const Vector<String>& protocols, ExceptionState& exceptionState)
296 {
297     WTF_LOG(Network, "WebSocket %p connect() url='%s'", this, url.utf8().data());
298     m_url = KURL(KURL(), url);
299
300     if (!m_url.isValid()) {
301         m_state = CLOSED;
302         exceptionState.throwDOMException(SyntaxError, "The URL '" + url + "' is invalid.");
303         return;
304     }
305     if (!m_url.protocolIs("ws") && !m_url.protocolIs("wss")) {
306         m_state = CLOSED;
307         exceptionState.throwDOMException(SyntaxError, "The URL's scheme must be either 'ws' or 'wss'. '" + m_url.protocol() + "' is not allowed.");
308         return;
309     }
310
311     if (m_url.hasFragmentIdentifier()) {
312         m_state = CLOSED;
313         exceptionState.throwDOMException(SyntaxError, "The URL contains a fragment identifier ('" + m_url.fragmentIdentifier() + "'). Fragment identifiers are not allowed in WebSocket URLs.");
314         return;
315     }
316     if (!portAllowed(m_url)) {
317         m_state = CLOSED;
318         exceptionState.throwSecurityError("The port " + String::number(m_url.port()) + " is not allowed.");
319         return;
320     }
321
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();
327     }
328     if (!shouldBypassMainWorldContentSecurityPolicy && !executionContext()->contentSecurityPolicy()->allowConnectToSource(m_url)) {
329         m_state = CLOSED;
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.");
332         return;
333     }
334
335     m_channel = WebSocketChannel::create(executionContext(), this);
336
337     for (size_t i = 0; i < protocols.size(); ++i) {
338         if (!isValidSubprotocolString(protocols[i])) {
339             m_state = CLOSED;
340             exceptionState.throwDOMException(SyntaxError, "The subprotocol '" + encodeSubprotocolString(protocols[i]) + "' is invalid.");
341             releaseChannel();
342             return;
343         }
344     }
345     HashSet<String> visited;
346     for (size_t i = 0; i < protocols.size(); ++i) {
347         if (!visited.add(protocols[i]).isNewEntry) {
348             m_state = CLOSED;
349             exceptionState.throwDOMException(SyntaxError, "The subprotocol '" + encodeSubprotocolString(protocols[i]) + "' is duplicated.");
350             releaseChannel();
351             return;
352         }
353     }
354
355     String protocolString;
356     if (!protocols.isEmpty())
357         protocolString = joinStrings(protocols, subProtocolSeperator());
358
359     if (!m_channel->connect(m_url, protocolString)) {
360         m_state = CLOSED;
361         exceptionState.throwSecurityError("An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.");
362         releaseChannel();
363         return;
364     }
365 }
366
367 void WebSocket::handleSendResult(WebSocketChannel::SendResult result, ExceptionState& exceptionState, WebSocketSendType dataType)
368 {
369     switch (result) {
370     case WebSocketChannel::InvalidMessage:
371         exceptionState.throwDOMException(SyntaxError, "The message contains invalid characters.");
372         return;
373     case WebSocketChannel::SendFail:
374         logError("WebSocket send() failed.");
375         return;
376     case WebSocketChannel::SendSuccess:
377         blink::Platform::current()->histogramEnumeration("WebCore.WebSocket.SendType", dataType, WebSocketSendTypeMax);
378         return;
379     }
380     ASSERT_NOT_REACHED();
381 }
382
383 void WebSocket::updateBufferedAmountAfterClose(unsigned long payloadSize)
384 {
385     m_bufferedAmountAfterClose = saturateAdd(m_bufferedAmountAfterClose, payloadSize);
386     m_bufferedAmountAfterClose = saturateAdd(m_bufferedAmountAfterClose, getFramingOverhead(payloadSize));
387
388     logError("WebSocket is already in CLOSING or CLOSED state.");
389 }
390
391 void WebSocket::releaseChannel()
392 {
393     ASSERT(m_channel);
394     m_channel->disconnect();
395     m_channel = nullptr;
396 }
397
398 void WebSocket::send(const String& message, ExceptionState& exceptionState)
399 {
400     WTF_LOG(Network, "WebSocket %p send() Sending String '%s'", this, message.utf8().data());
401     if (m_state == CONNECTING) {
402         setInvalidStateErrorForSendMethod(exceptionState);
403         return;
404     }
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());
408         return;
409     }
410     ASSERT(m_channel);
411     handleSendResult(m_channel->send(message), exceptionState, WebSocketSendTypeString);
412 }
413
414 void WebSocket::send(ArrayBuffer* binaryData, ExceptionState& exceptionState)
415 {
416     WTF_LOG(Network, "WebSocket %p send() Sending ArrayBuffer %p", this, binaryData);
417     ASSERT(binaryData);
418     if (m_state == CONNECTING) {
419         setInvalidStateErrorForSendMethod(exceptionState);
420         return;
421     }
422     if (m_state == CLOSING || m_state == CLOSED) {
423         updateBufferedAmountAfterClose(binaryData->byteLength());
424         return;
425     }
426     ASSERT(m_channel);
427     handleSendResult(m_channel->send(*binaryData, 0, binaryData->byteLength()), exceptionState, WebSocketSendTypeArrayBuffer);
428 }
429
430 void WebSocket::send(ArrayBufferView* arrayBufferView, ExceptionState& exceptionState)
431 {
432     WTF_LOG(Network, "WebSocket %p send() Sending ArrayBufferView %p", this, arrayBufferView);
433     ASSERT(arrayBufferView);
434     if (m_state == CONNECTING) {
435         setInvalidStateErrorForSendMethod(exceptionState);
436         return;
437     }
438     if (m_state == CLOSING || m_state == CLOSED) {
439         updateBufferedAmountAfterClose(arrayBufferView->byteLength());
440         return;
441     }
442     ASSERT(m_channel);
443     RefPtr<ArrayBuffer> arrayBuffer(arrayBufferView->buffer());
444     handleSendResult(m_channel->send(*arrayBuffer, arrayBufferView->byteOffset(), arrayBufferView->byteLength()), exceptionState, WebSocketSendTypeArrayBufferView);
445 }
446
447 void WebSocket::send(Blob* binaryData, ExceptionState& exceptionState)
448 {
449     WTF_LOG(Network, "WebSocket %p send() Sending Blob '%s'", this, binaryData->uuid().utf8().data());
450     ASSERT(binaryData);
451     if (m_state == CONNECTING) {
452         setInvalidStateErrorForSendMethod(exceptionState);
453         return;
454     }
455     if (m_state == CLOSING || m_state == CLOSED) {
456         updateBufferedAmountAfterClose(static_cast<unsigned long>(binaryData->size()));
457         return;
458     }
459     ASSERT(m_channel);
460     handleSendResult(m_channel->send(binaryData->blobDataHandle()), exceptionState, WebSocketSendTypeBlob);
461 }
462
463 void WebSocket::close(unsigned short code, const String& reason, ExceptionState& exceptionState)
464 {
465     closeInternal(code, reason, exceptionState);
466 }
467
468 void WebSocket::close(ExceptionState& exceptionState)
469 {
470     closeInternal(WebSocketChannel::CloseEventCodeNotSpecified, String(), exceptionState);
471 }
472
473 void WebSocket::close(unsigned short code, ExceptionState& exceptionState)
474 {
475     closeInternal(code, String(), exceptionState);
476 }
477
478 void WebSocket::closeInternal(int code, const String& reason, ExceptionState& exceptionState)
479 {
480     if (code == WebSocketChannel::CloseEventCodeNotSpecified) {
481         WTF_LOG(Network, "WebSocket %p close() without code and reason", this);
482     } else {
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.");
486             return;
487         }
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.");
491             return;
492         }
493     }
494
495     if (m_state == CLOSING || m_state == CLOSED)
496         return;
497     if (m_state == CONNECTING) {
498         m_state = CLOSING;
499         m_channel->fail("WebSocket is closed before the connection is established.", WarningMessageLevel);
500         return;
501     }
502     m_state = CLOSING;
503     if (m_channel)
504         m_channel->close(code, reason);
505 }
506
507 const KURL& WebSocket::url() const
508 {
509     return m_url;
510 }
511
512 WebSocket::State WebSocket::readyState() const
513 {
514     return m_state;
515 }
516
517 unsigned long WebSocket::bufferedAmount() const
518 {
519     return saturateAdd(m_bufferedAmount, m_bufferedAmountAfterClose);
520 }
521
522 String WebSocket::protocol() const
523 {
524     return m_subprotocol;
525 }
526
527 String WebSocket::extensions() const
528 {
529     return m_extensions;
530 }
531
532 String WebSocket::binaryType() const
533 {
534     switch (m_binaryType) {
535     case BinaryTypeBlob:
536         return "blob";
537     case BinaryTypeArrayBuffer:
538         return "arraybuffer";
539     }
540     ASSERT_NOT_REACHED();
541     return String();
542 }
543
544 void WebSocket::setBinaryType(const String& binaryType)
545 {
546     if (binaryType == "blob") {
547         m_binaryType = BinaryTypeBlob;
548         return;
549     }
550     if (binaryType == "arraybuffer") {
551         m_binaryType = BinaryTypeArrayBuffer;
552         return;
553     }
554     logError("'" + binaryType + "' is not a valid value for binaryType; binaryType remains unchanged.");
555 }
556
557 const AtomicString& WebSocket::interfaceName() const
558 {
559     return EventTargetNames::WebSocket;
560 }
561
562 ExecutionContext* WebSocket::executionContext() const
563 {
564     return ActiveDOMObject::executionContext();
565 }
566
567 void WebSocket::contextDestroyed()
568 {
569     WTF_LOG(Network, "WebSocket %p contextDestroyed()", this);
570     ASSERT(!m_channel);
571     ASSERT(m_state == CLOSED);
572     ActiveDOMObject::contextDestroyed();
573 }
574
575 bool WebSocket::hasPendingActivity() const
576 {
577     return m_channel || !m_eventQueue->isEmpty();
578 }
579
580 void WebSocket::suspend()
581 {
582     if (m_channel)
583         m_channel->suspend();
584     m_eventQueue->suspend();
585 }
586
587 void WebSocket::resume()
588 {
589     if (m_channel)
590         m_channel->resume();
591     m_eventQueue->resume();
592 }
593
594 void WebSocket::stop()
595 {
596     m_eventQueue->stop();
597     if (m_channel) {
598         m_channel->close(WebSocketChannel::CloseEventCodeGoingAway, String());
599         releaseChannel();
600     }
601     m_state = CLOSED;
602 }
603
604 void WebSocket::didConnect()
605 {
606     WTF_LOG(Network, "WebSocket %p didConnect()", this);
607     if (m_state != CONNECTING)
608         return;
609     m_state = OPEN;
610     m_subprotocol = m_channel->subprotocol();
611     m_extensions = m_channel->extensions();
612     m_eventQueue->dispatch(Event::create(EventTypeNames::open));
613 }
614
615 void WebSocket::didReceiveMessage(const String& msg)
616 {
617     WTF_LOG(Network, "WebSocket %p didReceiveMessage() Text message '%s'", this, msg.utf8().data());
618     if (m_state != OPEN)
619         return;
620     m_eventQueue->dispatch(MessageEvent::create(msg, SecurityOrigin::create(m_url)->toString()));
621 }
622
623 void WebSocket::didReceiveBinaryData(PassOwnPtr<Vector<char> > binaryData)
624 {
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()));
635         break;
636     }
637
638     case BinaryTypeArrayBuffer:
639         RefPtr<ArrayBuffer> arrayBuffer = ArrayBuffer::create(binaryData->data(), binaryData->size());
640         if (!arrayBuffer) {
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
643             // user.
644             CRASH();
645         }
646         m_eventQueue->dispatch(MessageEvent::create(arrayBuffer.release(), SecurityOrigin::create(m_url)->toString()));
647         break;
648     }
649 }
650
651 void WebSocket::didReceiveMessageError()
652 {
653     WTF_LOG(Network, "WebSocket %p didReceiveMessageError()", this);
654     m_state = CLOSED;
655     m_eventQueue->dispatch(Event::create(EventTypeNames::error));
656 }
657
658 void WebSocket::didUpdateBufferedAmount(unsigned long bufferedAmount)
659 {
660     WTF_LOG(Network, "WebSocket %p didUpdateBufferedAmount() New bufferedAmount is %lu", this, bufferedAmount);
661     if (m_state == CLOSED)
662         return;
663     m_bufferedAmount = bufferedAmount;
664 }
665
666 void WebSocket::didStartClosingHandshake()
667 {
668     WTF_LOG(Network, "WebSocket %p didStartClosingHandshake()", this);
669     m_state = CLOSING;
670 }
671
672 void WebSocket::didClose(unsigned long unhandledBufferedAmount, ClosingHandshakeCompletionStatus closingHandshakeCompletion, unsigned short code, const String& reason)
673 {
674     WTF_LOG(Network, "WebSocket %p didClose()", this);
675     if (!m_channel)
676         return;
677     bool wasClean = m_state == CLOSING && !unhandledBufferedAmount && closingHandshakeCompletion == ClosingHandshakeComplete && code != WebSocketChannel::CloseEventCodeAbnormalClosure;
678
679     m_state = CLOSED;
680     m_bufferedAmount = unhandledBufferedAmount;
681     m_eventQueue->dispatch(CloseEvent::create(wasClean, code, reason));
682     releaseChannel();
683 }
684
685 size_t WebSocket::getFramingOverhead(size_t payloadSize)
686 {
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)
693         overhead += 8;
694     else if (payloadSize >= minimumPayloadSizeWithTwoByteExtendedPayloadLength)
695         overhead += 2;
696     return overhead;
697 }
698
699 void WebSocket::trace(Visitor* visitor)
700 {
701     visitor->trace(m_channel);
702     visitor->trace(m_eventQueue);
703 }
704
705 } // namespace WebCore