Upstream version 5.34.104.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/ContentSecurityPolicy.h"
45 #include "core/frame/DOMWindow.h"
46 #include "core/frame/Frame.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/weborigin/KnownPorts.h"
52 #include "platform/weborigin/SecurityOrigin.h"
53 #include "wtf/ArrayBuffer.h"
54 #include "wtf/ArrayBufferView.h"
55 #include "wtf/HashSet.h"
56 #include "wtf/PassOwnPtr.h"
57 #include "wtf/StdLibExtras.h"
58 #include "wtf/text/CString.h"
59 #include "wtf/text/StringBuilder.h"
60 #include "wtf/text/WTFString.h"
61
62 using namespace std;
63
64 namespace WebCore {
65
66 WebSocket::EventQueue::EventQueue(EventTarget* target)
67     : m_state(Active)
68     , m_target(target)
69     , m_resumeTimer(this, &EventQueue::resumeTimerFired) { }
70
71 WebSocket::EventQueue::~EventQueue() { stop(); }
72
73 void WebSocket::EventQueue::dispatch(PassRefPtr<Event> event)
74 {
75     switch (m_state) {
76     case Active:
77         ASSERT(m_events.isEmpty());
78         ASSERT(m_target->executionContext());
79         m_target->dispatchEvent(event);
80         break;
81     case Suspended:
82         m_events.append(event);
83         break;
84     case Stopped:
85         ASSERT(m_events.isEmpty());
86         // Do nothing.
87         break;
88     }
89 }
90
91 bool WebSocket::EventQueue::isEmpty() const
92 {
93     return m_events.isEmpty();
94 }
95
96 void WebSocket::EventQueue::suspend()
97 {
98     if (m_state != Active)
99         return;
100
101     m_state = Suspended;
102 }
103
104 void WebSocket::EventQueue::resume()
105 {
106     if (m_state != Suspended || m_resumeTimer.isActive())
107         return;
108
109     m_resumeTimer.startOneShot(0);
110 }
111
112 void WebSocket::EventQueue::stop()
113 {
114     if (m_state == Stopped)
115         return;
116
117     m_state = Stopped;
118     m_resumeTimer.stop();
119     m_events.clear();
120 }
121
122 void WebSocket::EventQueue::dispatchQueuedEvents()
123 {
124     if (m_state != Active)
125         return;
126
127     RefPtr<EventQueue> protect(this);
128
129     Deque<RefPtr<Event> > events;
130     events.swap(m_events);
131     while (!events.isEmpty()) {
132         if (m_state == Stopped || m_state == Suspended)
133             break;
134         ASSERT(m_state == Active);
135         ASSERT(m_target->executionContext());
136         m_target->dispatchEvent(events.takeFirst());
137         // |this| can be stopped here.
138     }
139     if (m_state == Suspended) {
140         while (!m_events.isEmpty())
141             events.append(m_events.takeFirst());
142         events.swap(m_events);
143     }
144 }
145
146 void WebSocket::EventQueue::resumeTimerFired(Timer<EventQueue>*)
147 {
148     ASSERT(m_state == Suspended);
149     m_state = Active;
150     dispatchQueuedEvents();
151 }
152
153 const size_t maxReasonSizeInBytes = 123;
154
155 static inline bool isValidProtocolCharacter(UChar character)
156 {
157     // Hybi-10 says "(Subprotocol string must consist of) characters in the range U+0021 to U+007E not including
158     // separator characters as defined in [RFC2616]."
159     const UChar minimumProtocolCharacter = '!'; // U+0021.
160     const UChar maximumProtocolCharacter = '~'; // U+007E.
161     return character >= minimumProtocolCharacter && character <= maximumProtocolCharacter
162         && character != '"' && character != '(' && character != ')' && character != ',' && character != '/'
163         && !(character >= ':' && character <= '@') // U+003A - U+0040 (':', ';', '<', '=', '>', '?', '@').
164         && !(character >= '[' && character <= ']') // U+005B - U+005D ('[', '\\', ']').
165         && character != '{' && character != '}';
166 }
167
168 static bool isValidProtocolString(const String& protocol)
169 {
170     if (protocol.isEmpty())
171         return false;
172     for (size_t i = 0; i < protocol.length(); ++i) {
173         if (!isValidProtocolCharacter(protocol[i]))
174             return false;
175     }
176     return true;
177 }
178
179 static String encodeProtocolString(const String& protocol)
180 {
181     StringBuilder builder;
182     for (size_t i = 0; i < protocol.length(); i++) {
183         if (protocol[i] < 0x20 || protocol[i] > 0x7E)
184             builder.append(String::format("\\u%04X", protocol[i]));
185         else if (protocol[i] == 0x5c)
186             builder.append("\\\\");
187         else
188             builder.append(protocol[i]);
189     }
190     return builder.toString();
191 }
192
193 static String joinStrings(const Vector<String>& strings, const char* separator)
194 {
195     StringBuilder builder;
196     for (size_t i = 0; i < strings.size(); ++i) {
197         if (i)
198             builder.append(separator);
199         builder.append(strings[i]);
200     }
201     return builder.toString();
202 }
203
204 static unsigned long saturateAdd(unsigned long a, unsigned long b)
205 {
206     if (numeric_limits<unsigned long>::max() - a < b)
207         return numeric_limits<unsigned long>::max();
208     return a + b;
209 }
210
211 static void setInvalidStateErrorForSendMethod(ExceptionState& exceptionState)
212 {
213     exceptionState.throwDOMException(InvalidStateError, "Still in CONNECTING state.");
214 }
215
216 const char* WebSocket::subProtocolSeperator()
217 {
218     return ", ";
219 }
220
221 WebSocket::WebSocket(ExecutionContext* context)
222     : ActiveDOMObject(context)
223     , m_state(CONNECTING)
224     , m_bufferedAmount(0)
225     , m_bufferedAmountAfterClose(0)
226     , m_binaryType(BinaryTypeBlob)
227     , m_subprotocol("")
228     , m_extensions("")
229     , m_eventQueue(EventQueue::create(this))
230 {
231     ScriptWrappable::init(this);
232 }
233
234 WebSocket::~WebSocket()
235 {
236     ASSERT(!m_channel);
237 }
238
239 void WebSocket::logError(const String& message)
240 {
241     executionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
242 }
243
244 PassRefPtr<WebSocket> WebSocket::create(ExecutionContext* context, const String& url, ExceptionState& exceptionState)
245 {
246     Vector<String> protocols;
247     return create(context, url, protocols, exceptionState);
248 }
249
250 PassRefPtr<WebSocket> WebSocket::create(ExecutionContext* context, const String& url, const Vector<String>& protocols, ExceptionState& exceptionState)
251 {
252     if (url.isNull()) {
253         exceptionState.throwDOMException(SyntaxError, "Failed to create a WebSocket: the provided URL is invalid.");
254         return 0;
255     }
256
257     RefPtr<WebSocket> webSocket(adoptRef(new WebSocket(context)));
258     webSocket->suspendIfNeeded();
259
260     webSocket->connect(context->completeURL(url), protocols, exceptionState);
261     if (exceptionState.hadException())
262         return 0;
263
264     return webSocket.release();
265 }
266
267 PassRefPtr<WebSocket> WebSocket::create(ExecutionContext* context, const String& url, const String& protocol, ExceptionState& exceptionState)
268 {
269     Vector<String> protocols;
270     protocols.append(protocol);
271     return create(context, url, protocols, exceptionState);
272 }
273
274 void WebSocket::connect(const String& url, ExceptionState& exceptionState)
275 {
276     Vector<String> protocols;
277     connect(url, protocols, exceptionState);
278 }
279
280 void WebSocket::connect(const String& url, const String& protocol, ExceptionState& exceptionState)
281 {
282     Vector<String> protocols;
283     protocols.append(protocol);
284     connect(url, protocols, exceptionState);
285 }
286
287 void WebSocket::connect(const String& url, const Vector<String>& protocols, ExceptionState& exceptionState)
288 {
289     WTF_LOG(Network, "WebSocket %p connect() url='%s'", this, url.utf8().data());
290     m_url = KURL(KURL(), url);
291
292     if (!m_url.isValid()) {
293         m_state = CLOSED;
294         exceptionState.throwDOMException(SyntaxError, "The URL '" + url + "' is invalid.");
295         return;
296     }
297     if (!m_url.protocolIs("ws") && !m_url.protocolIs("wss")) {
298         m_state = CLOSED;
299         exceptionState.throwDOMException(SyntaxError, "The URL's scheme must be either 'ws' or 'wss'. '" + m_url.protocol() + "' is not allowed.");
300         return;
301     }
302     if (MixedContentChecker::isMixedContent(executionContext()->securityOrigin(), m_url)) {
303         // FIXME: Throw an exception and close the connection.
304         String message = "Connecting to a non-secure WebSocket server from a secure origin is deprecated.";
305         executionContext()->addConsoleMessage(JSMessageSource, WarningMessageLevel, message);
306     }
307     if (m_url.hasFragmentIdentifier()) {
308         m_state = CLOSED;
309         exceptionState.throwDOMException(SyntaxError, "The URL contains a fragment identifier ('" + m_url.fragmentIdentifier() + "'). Fragment identifiers are not allowed in WebSocket URLs.");
310         return;
311     }
312     if (!portAllowed(m_url)) {
313         m_state = CLOSED;
314         exceptionState.throwSecurityError("The port " + String::number(m_url.port()) + " is not allowed.");
315         return;
316     }
317
318     // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
319     bool shouldBypassMainWorldContentSecurityPolicy = false;
320     if (executionContext()->isDocument()) {
321         Document* document = toDocument(executionContext());
322         shouldBypassMainWorldContentSecurityPolicy = document->frame()->script().shouldBypassMainWorldContentSecurityPolicy();
323     }
324     if (!shouldBypassMainWorldContentSecurityPolicy && !executionContext()->contentSecurityPolicy()->allowConnectToSource(m_url)) {
325         m_state = CLOSED;
326         // The URL is safe to expose to JavaScript, as this check happens synchronously before redirection.
327         exceptionState.throwSecurityError("Refused to connect to '" + m_url.elidedString() + "' because it violates the document's Content Security Policy.");
328         return;
329     }
330
331     m_channel = WebSocketChannel::create(executionContext(), this);
332
333     // FIXME: There is a disagreement about restriction of subprotocols between WebSocket API and hybi-10 protocol
334     // draft. The former simply says "only characters in the range U+0021 to U+007E are allowed," while the latter
335     // imposes a stricter rule: "the elements MUST be non-empty strings with characters as defined in [RFC2616],
336     // and MUST all be unique strings."
337     //
338     // Here, we throw SyntaxError if the given protocols do not meet the latter criteria. This behavior does not
339     // comply with WebSocket API specification, but it seems to be the only reasonable way to handle this conflict.
340     for (size_t i = 0; i < protocols.size(); ++i) {
341         if (!isValidProtocolString(protocols[i])) {
342             m_state = CLOSED;
343             exceptionState.throwDOMException(SyntaxError, "The subprotocol '" + encodeProtocolString(protocols[i]) + "' is invalid.");
344             releaseChannel();
345             return;
346         }
347     }
348     HashSet<String> visited;
349     for (size_t i = 0; i < protocols.size(); ++i) {
350         if (!visited.add(protocols[i]).isNewEntry) {
351             m_state = CLOSED;
352             exceptionState.throwDOMException(SyntaxError, "The subprotocol '" + encodeProtocolString(protocols[i]) + "' is duplicated.");
353             releaseChannel();
354             return;
355         }
356     }
357
358     String protocolString;
359     if (!protocols.isEmpty())
360         protocolString = joinStrings(protocols, subProtocolSeperator());
361
362     m_channel->connect(m_url, protocolString);
363 }
364
365 void WebSocket::handleSendResult(WebSocketChannel::SendResult result, ExceptionState& exceptionState)
366 {
367     switch (result) {
368     case WebSocketChannel::InvalidMessage:
369         exceptionState.throwDOMException(SyntaxError, "The message contains invalid characters.");
370         return;
371     case WebSocketChannel::SendFail:
372         logError("WebSocket send() failed.");
373         return;
374     case WebSocketChannel::SendSuccess:
375         return;
376     }
377     ASSERT_NOT_REACHED();
378 }
379
380 void WebSocket::updateBufferedAmountAfterClose(unsigned long payloadSize)
381 {
382     m_bufferedAmountAfterClose = saturateAdd(m_bufferedAmountAfterClose, payloadSize);
383     m_bufferedAmountAfterClose = saturateAdd(m_bufferedAmountAfterClose, getFramingOverhead(payloadSize));
384
385     logError("WebSocket is already in CLOSING or CLOSED state.");
386 }
387
388 void WebSocket::releaseChannel()
389 {
390     ASSERT(m_channel);
391     m_channel->disconnect();
392     m_channel = 0;
393 }
394
395 void WebSocket::send(const String& message, ExceptionState& exceptionState)
396 {
397     WTF_LOG(Network, "WebSocket %p send() Sending String '%s'", this, message.utf8().data());
398     if (m_state == CONNECTING) {
399         setInvalidStateErrorForSendMethod(exceptionState);
400         return;
401     }
402     // No exception is raised if the connection was once established but has subsequently been closed.
403     if (m_state == CLOSING || m_state == CLOSED) {
404         updateBufferedAmountAfterClose(message.utf8().length());
405         return;
406     }
407     ASSERT(m_channel);
408     handleSendResult(m_channel->send(message), exceptionState);
409 }
410
411 void WebSocket::send(ArrayBuffer* binaryData, ExceptionState& exceptionState)
412 {
413     WTF_LOG(Network, "WebSocket %p send() Sending ArrayBuffer %p", this, binaryData);
414     ASSERT(binaryData);
415     if (m_state == CONNECTING) {
416         setInvalidStateErrorForSendMethod(exceptionState);
417         return;
418     }
419     if (m_state == CLOSING || m_state == CLOSED) {
420         updateBufferedAmountAfterClose(binaryData->byteLength());
421         return;
422     }
423     ASSERT(m_channel);
424     handleSendResult(m_channel->send(*binaryData, 0, binaryData->byteLength()), exceptionState);
425 }
426
427 void WebSocket::send(ArrayBufferView* arrayBufferView, ExceptionState& exceptionState)
428 {
429     WTF_LOG(Network, "WebSocket %p send() Sending ArrayBufferView %p", this, arrayBufferView);
430     ASSERT(arrayBufferView);
431     if (m_state == CONNECTING) {
432         setInvalidStateErrorForSendMethod(exceptionState);
433         return;
434     }
435     if (m_state == CLOSING || m_state == CLOSED) {
436         updateBufferedAmountAfterClose(arrayBufferView->byteLength());
437         return;
438     }
439     ASSERT(m_channel);
440     RefPtr<ArrayBuffer> arrayBuffer(arrayBufferView->buffer());
441     handleSendResult(m_channel->send(*arrayBuffer, arrayBufferView->byteOffset(), arrayBufferView->byteLength()), exceptionState);
442 }
443
444 void WebSocket::send(Blob* binaryData, ExceptionState& exceptionState)
445 {
446     WTF_LOG(Network, "WebSocket %p send() Sending Blob '%s'", this, binaryData->uuid().utf8().data());
447     ASSERT(binaryData);
448     if (m_state == CONNECTING) {
449         setInvalidStateErrorForSendMethod(exceptionState);
450         return;
451     }
452     if (m_state == CLOSING || m_state == CLOSED) {
453         updateBufferedAmountAfterClose(static_cast<unsigned long>(binaryData->size()));
454         return;
455     }
456     ASSERT(m_channel);
457     handleSendResult(m_channel->send(binaryData->blobDataHandle()), exceptionState);
458 }
459
460 void WebSocket::close(unsigned short code, const String& reason, ExceptionState& exceptionState)
461 {
462     closeInternal(code, reason, exceptionState);
463 }
464
465 void WebSocket::close(ExceptionState& exceptionState)
466 {
467     closeInternal(WebSocketChannel::CloseEventCodeNotSpecified, String(), exceptionState);
468 }
469
470 void WebSocket::close(unsigned short code, ExceptionState& exceptionState)
471 {
472     closeInternal(code, String(), exceptionState);
473 }
474
475 void WebSocket::closeInternal(int code, const String& reason, ExceptionState& exceptionState)
476 {
477     if (code == WebSocketChannel::CloseEventCodeNotSpecified) {
478         WTF_LOG(Network, "WebSocket %p close() without code and reason", this);
479     } else {
480         WTF_LOG(Network, "WebSocket %p close() code=%d reason='%s'", this, code, reason.utf8().data());
481         if (!(code == WebSocketChannel::CloseEventCodeNormalClosure || (WebSocketChannel::CloseEventCodeMinimumUserDefined <= code && code <= WebSocketChannel::CloseEventCodeMaximumUserDefined))) {
482             exceptionState.throwDOMException(InvalidAccessError, "The code must be either 1000, or between 3000 and 4999. " + String::number(code) + " is neither.");
483             return;
484         }
485         CString utf8 = reason.utf8(StrictUTF8ConversionReplacingUnpairedSurrogatesWithFFFD);
486         if (utf8.length() > maxReasonSizeInBytes) {
487             exceptionState.throwDOMException(SyntaxError, "The message must not be greater than " + String::number(maxReasonSizeInBytes) + " bytes.");
488             return;
489         }
490     }
491
492     if (m_state == CLOSING || m_state == CLOSED)
493         return;
494     if (m_state == CONNECTING) {
495         m_state = CLOSING;
496         m_channel->fail("WebSocket is closed before the connection is established.", WarningMessageLevel);
497         return;
498     }
499     m_state = CLOSING;
500     if (m_channel)
501         m_channel->close(code, reason);
502 }
503
504 const KURL& WebSocket::url() const
505 {
506     return m_url;
507 }
508
509 WebSocket::State WebSocket::readyState() const
510 {
511     return m_state;
512 }
513
514 unsigned long WebSocket::bufferedAmount() const
515 {
516     return saturateAdd(m_bufferedAmount, m_bufferedAmountAfterClose);
517 }
518
519 String WebSocket::protocol() const
520 {
521     return m_subprotocol;
522 }
523
524 String WebSocket::extensions() const
525 {
526     return m_extensions;
527 }
528
529 String WebSocket::binaryType() const
530 {
531     switch (m_binaryType) {
532     case BinaryTypeBlob:
533         return "blob";
534     case BinaryTypeArrayBuffer:
535         return "arraybuffer";
536     }
537     ASSERT_NOT_REACHED();
538     return String();
539 }
540
541 void WebSocket::setBinaryType(const String& binaryType)
542 {
543     if (binaryType == "blob") {
544         m_binaryType = BinaryTypeBlob;
545         return;
546     }
547     if (binaryType == "arraybuffer") {
548         m_binaryType = BinaryTypeArrayBuffer;
549         return;
550     }
551     logError("'" + binaryType + "' is not a valid value for binaryType; binaryType remains unchanged.");
552 }
553
554 const AtomicString& WebSocket::interfaceName() const
555 {
556     return EventTargetNames::WebSocket;
557 }
558
559 ExecutionContext* WebSocket::executionContext() const
560 {
561     return ActiveDOMObject::executionContext();
562 }
563
564 void WebSocket::contextDestroyed()
565 {
566     WTF_LOG(Network, "WebSocket %p contextDestroyed()", this);
567     ASSERT(!m_channel);
568     ASSERT(m_state == CLOSED);
569     ActiveDOMObject::contextDestroyed();
570 }
571
572 bool WebSocket::hasPendingActivity() const
573 {
574     return m_channel || !m_eventQueue->isEmpty();
575 }
576
577 void WebSocket::suspend()
578 {
579     if (m_channel)
580         m_channel->suspend();
581     m_eventQueue->suspend();
582 }
583
584 void WebSocket::resume()
585 {
586     if (m_channel)
587         m_channel->resume();
588     m_eventQueue->resume();
589 }
590
591 void WebSocket::stop()
592 {
593     m_eventQueue->stop();
594     if (m_channel) {
595         m_channel->close(WebSocketChannel::CloseEventCodeGoingAway, String());
596         releaseChannel();
597     }
598     m_state = CLOSED;
599 }
600
601 void WebSocket::didConnect()
602 {
603     WTF_LOG(Network, "WebSocket %p didConnect()", this);
604     if (m_state != CONNECTING)
605         return;
606     m_state = OPEN;
607     m_subprotocol = m_channel->subprotocol();
608     m_extensions = m_channel->extensions();
609     m_eventQueue->dispatch(Event::create(EventTypeNames::open));
610 }
611
612 void WebSocket::didReceiveMessage(const String& msg)
613 {
614     WTF_LOG(Network, "WebSocket %p didReceiveMessage() Text message '%s'", this, msg.utf8().data());
615     if (m_state != OPEN)
616         return;
617     m_eventQueue->dispatch(MessageEvent::create(msg, SecurityOrigin::create(m_url)->toString()));
618 }
619
620 void WebSocket::didReceiveBinaryData(PassOwnPtr<Vector<char> > binaryData)
621 {
622     WTF_LOG(Network, "WebSocket %p didReceiveBinaryData() %lu byte binary message", this, static_cast<unsigned long>(binaryData->size()));
623     switch (m_binaryType) {
624     case BinaryTypeBlob: {
625         size_t size = binaryData->size();
626         RefPtr<RawData> rawData = RawData::create();
627         binaryData->swap(*rawData->mutableData());
628         OwnPtr<BlobData> blobData = BlobData::create();
629         blobData->appendData(rawData.release(), 0, BlobDataItem::toEndOfFile);
630         RefPtr<Blob> blob = Blob::create(BlobDataHandle::create(blobData.release(), size));
631         m_eventQueue->dispatch(MessageEvent::create(blob.release(), SecurityOrigin::create(m_url)->toString()));
632         break;
633     }
634
635     case BinaryTypeArrayBuffer:
636         m_eventQueue->dispatch(MessageEvent::create(ArrayBuffer::create(binaryData->data(), binaryData->size()), SecurityOrigin::create(m_url)->toString()));
637         break;
638     }
639 }
640
641 void WebSocket::didReceiveMessageError()
642 {
643     WTF_LOG(Network, "WebSocket %p didReceiveMessageError()", this);
644     m_state = CLOSED;
645     m_eventQueue->dispatch(Event::create(EventTypeNames::error));
646 }
647
648 void WebSocket::didUpdateBufferedAmount(unsigned long bufferedAmount)
649 {
650     WTF_LOG(Network, "WebSocket %p didUpdateBufferedAmount() New bufferedAmount is %lu", this, bufferedAmount);
651     if (m_state == CLOSED)
652         return;
653     m_bufferedAmount = bufferedAmount;
654 }
655
656 void WebSocket::didStartClosingHandshake()
657 {
658     WTF_LOG(Network, "WebSocket %p didStartClosingHandshake()", this);
659     m_state = CLOSING;
660 }
661
662 void WebSocket::didClose(unsigned long unhandledBufferedAmount, ClosingHandshakeCompletionStatus closingHandshakeCompletion, unsigned short code, const String& reason)
663 {
664     WTF_LOG(Network, "WebSocket %p didClose()", this);
665     if (!m_channel)
666         return;
667     bool wasClean = m_state == CLOSING && !unhandledBufferedAmount && closingHandshakeCompletion == ClosingHandshakeComplete && code != WebSocketChannel::CloseEventCodeAbnormalClosure;
668
669     m_state = CLOSED;
670     m_bufferedAmount = unhandledBufferedAmount;
671     m_eventQueue->dispatch(CloseEvent::create(wasClean, code, reason));
672     releaseChannel();
673 }
674
675 size_t WebSocket::getFramingOverhead(size_t payloadSize)
676 {
677     static const size_t hybiBaseFramingOverhead = 2; // Every frame has at least two-byte header.
678     static const size_t hybiMaskingKeyLength = 4; // Every frame from client must have masking key.
679     static const size_t minimumPayloadSizeWithTwoByteExtendedPayloadLength = 126;
680     static const size_t minimumPayloadSizeWithEightByteExtendedPayloadLength = 0x10000;
681     size_t overhead = hybiBaseFramingOverhead + hybiMaskingKeyLength;
682     if (payloadSize >= minimumPayloadSizeWithEightByteExtendedPayloadLength)
683         overhead += 8;
684     else if (payloadSize >= minimumPayloadSizeWithTwoByteExtendedPayloadLength)
685         overhead += 2;
686     return overhead;
687 }
688
689 } // namespace WebCore