1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/websockets/websocket_channel.h"
14 #include "base/bind.h"
15 #include "base/bind_helpers.h"
16 #include "base/callback.h"
17 #include "base/location.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/memory/scoped_vector.h"
20 #include "base/memory/weak_ptr.h"
21 #include "base/message_loop/message_loop.h"
22 #include "base/strings/string_piece.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/test_completion_callback.h"
25 #include "net/http/http_response_headers.h"
26 #include "net/url_request/url_request_context.h"
27 #include "net/websockets/websocket_errors.h"
28 #include "net/websockets/websocket_event_interface.h"
29 #include "net/websockets/websocket_handshake_request_info.h"
30 #include "net/websockets/websocket_handshake_response_info.h"
31 #include "net/websockets/websocket_mux.h"
32 #include "testing/gmock/include/gmock/gmock.h"
33 #include "testing/gtest/include/gtest/gtest.h"
35 #include "url/origin.h"
37 // Hacky macros to construct the body of a Close message from a code and a
38 // string, while ensuring the result is a compile-time constant string.
39 // Use like CLOSE_DATA(NORMAL_CLOSURE, "Explanation String")
40 #define CLOSE_DATA(code, string) WEBSOCKET_CLOSE_CODE_AS_STRING_##code string
41 #define WEBSOCKET_CLOSE_CODE_AS_STRING_NORMAL_CLOSURE "\x03\xe8"
42 #define WEBSOCKET_CLOSE_CODE_AS_STRING_GOING_AWAY "\x03\xe9"
43 #define WEBSOCKET_CLOSE_CODE_AS_STRING_PROTOCOL_ERROR "\x03\xea"
44 #define WEBSOCKET_CLOSE_CODE_AS_STRING_ABNORMAL_CLOSURE "\x03\xee"
45 #define WEBSOCKET_CLOSE_CODE_AS_STRING_SERVER_ERROR "\x03\xf3"
49 // Printing helpers to allow GoogleMock to print frames. These are explicitly
50 // designed to look like the static initialisation format we use in these
51 // tests. They have to live in the net namespace in order to be found by
52 // GoogleMock; a nested anonymous namespace will not work.
54 std::ostream
& operator<<(std::ostream
& os
, const WebSocketFrameHeader
& header
) {
55 return os
<< (header
.final
? "FINAL_FRAME" : "NOT_FINAL_FRAME") << ", "
56 << header
.opcode
<< ", "
57 << (header
.masked
? "MASKED" : "NOT_MASKED");
60 std::ostream
& operator<<(std::ostream
& os
, const WebSocketFrame
& frame
) {
61 os
<< "{" << frame
.header
<< ", ";
62 if (frame
.data
.get()) {
63 return os
<< "\"" << base::StringPiece(frame
.data
->data(),
64 frame
.header
.payload_length
)
70 std::ostream
& operator<<(std::ostream
& os
,
71 const ScopedVector
<WebSocketFrame
>& vector
) {
74 for (ScopedVector
<WebSocketFrame
>::const_iterator it
= vector
.begin();
87 std::ostream
& operator<<(std::ostream
& os
,
88 const ScopedVector
<WebSocketFrame
>* vector
) {
89 return os
<< '&' << *vector
;
94 using ::base::TimeDelta
;
96 using ::testing::AnyNumber
;
97 using ::testing::DefaultValue
;
98 using ::testing::InSequence
;
99 using ::testing::MockFunction
;
100 using ::testing::NotNull
;
101 using ::testing::Return
;
102 using ::testing::SaveArg
;
103 using ::testing::StrictMock
;
106 // A selection of characters that have traditionally been mangled in some
107 // environment or other, for testing 8-bit cleanliness.
108 const char kBinaryBlob
[] = {'\n', '\r', // BACKWARDS CRNL
111 '\x80', '\xFF', // NOT VALID UTF-8
112 '\x1A', // Control-Z, EOF on DOS
114 '\x04', // EOT, special for Unix terms
115 '\x1B', // ESC, often special
117 '\'', // single-quote, special in PHP
119 const size_t kBinaryBlobSize
= arraysize(kBinaryBlob
);
121 // The amount of quota a new connection gets by default.
122 // TODO(ricea): If kDefaultSendQuotaHighWaterMark changes, then this value will
123 // need to be updated.
124 const size_t kDefaultInitialQuota
= 1 << 17;
125 // The amount of bytes we need to send after the initial connection to trigger a
126 // quota refresh. TODO(ricea): Change this if kDefaultSendQuotaHighWaterMark or
127 // kDefaultSendQuotaLowWaterMark change.
128 const size_t kDefaultQuotaRefreshTrigger
= (1 << 16) + 1;
130 const int kVeryBigTimeoutMillis
= 60 * 60 * 24 * 1000;
132 // TestTimeouts::tiny_timeout() is 100ms! I could run halfway around the world
133 // in that time! I would like my tests to run a bit quicker.
134 const int kVeryTinyTimeoutMillis
= 1;
136 // Enough quota to pass any test.
137 const int64 kPlentyOfQuota
= INT_MAX
;
139 typedef WebSocketEventInterface::ChannelState ChannelState
;
140 const ChannelState CHANNEL_ALIVE
= WebSocketEventInterface::CHANNEL_ALIVE
;
141 const ChannelState CHANNEL_DELETED
= WebSocketEventInterface::CHANNEL_DELETED
;
143 // This typedef mainly exists to avoid having to repeat the "NOLINT" incantation
144 // all over the place.
145 typedef StrictMock
< MockFunction
<void(int)> > Checkpoint
; // NOLINT
147 // This mock is for testing expectations about how the EventInterface is used.
148 class MockWebSocketEventInterface
: public WebSocketEventInterface
{
150 MockWebSocketEventInterface() {}
152 MOCK_METHOD3(OnAddChannelResponse
,
155 const std::string
&)); // NOLINT
156 MOCK_METHOD3(OnDataFrame
,
158 WebSocketMessageType
,
159 const std::vector
<char>&)); // NOLINT
160 MOCK_METHOD1(OnFlowControl
, ChannelState(int64
)); // NOLINT
161 MOCK_METHOD0(OnClosingHandshake
, ChannelState(void)); // NOLINT
162 MOCK_METHOD1(OnFailChannel
, ChannelState(const std::string
&)); // NOLINT
163 MOCK_METHOD3(OnDropChannel
,
164 ChannelState(bool, uint16
, const std::string
&)); // NOLINT
166 // We can't use GMock with scoped_ptr.
167 ChannelState
OnStartOpeningHandshake(
168 scoped_ptr
<WebSocketHandshakeRequestInfo
>) override
{
169 OnStartOpeningHandshakeCalled();
170 return CHANNEL_ALIVE
;
172 ChannelState
OnFinishOpeningHandshake(
173 scoped_ptr
<WebSocketHandshakeResponseInfo
>) override
{
174 OnFinishOpeningHandshakeCalled();
175 return CHANNEL_ALIVE
;
177 virtual ChannelState
OnSSLCertificateError(
178 scoped_ptr
<SSLErrorCallbacks
> ssl_error_callbacks
,
180 const SSLInfo
& ssl_info
,
181 bool fatal
) override
{
182 OnSSLCertificateErrorCalled(
183 ssl_error_callbacks
.get(), url
, ssl_info
, fatal
);
184 return CHANNEL_ALIVE
;
187 MOCK_METHOD0(OnStartOpeningHandshakeCalled
, void()); // NOLINT
188 MOCK_METHOD0(OnFinishOpeningHandshakeCalled
, void()); // NOLINT
190 OnSSLCertificateErrorCalled
,
191 void(SSLErrorCallbacks
*, const GURL
&, const SSLInfo
&, bool)); // NOLINT
194 // This fake EventInterface is for tests which need a WebSocketEventInterface
195 // implementation but are not verifying how it is used.
196 class FakeWebSocketEventInterface
: public WebSocketEventInterface
{
197 ChannelState
OnAddChannelResponse(bool fail
,
198 const std::string
& selected_protocol
,
199 const std::string
& extensions
) override
{
200 return fail
? CHANNEL_DELETED
: CHANNEL_ALIVE
;
202 ChannelState
OnDataFrame(bool fin
,
203 WebSocketMessageType type
,
204 const std::vector
<char>& data
) override
{
205 return CHANNEL_ALIVE
;
207 ChannelState
OnFlowControl(int64 quota
) override
{ return CHANNEL_ALIVE
; }
208 ChannelState
OnClosingHandshake() override
{ return CHANNEL_ALIVE
; }
209 ChannelState
OnFailChannel(const std::string
& message
) override
{
210 return CHANNEL_DELETED
;
212 ChannelState
OnDropChannel(bool was_clean
,
214 const std::string
& reason
) override
{
215 return CHANNEL_DELETED
;
217 ChannelState
OnStartOpeningHandshake(
218 scoped_ptr
<WebSocketHandshakeRequestInfo
> request
) override
{
219 return CHANNEL_ALIVE
;
221 ChannelState
OnFinishOpeningHandshake(
222 scoped_ptr
<WebSocketHandshakeResponseInfo
> response
) override
{
223 return CHANNEL_ALIVE
;
225 ChannelState
OnSSLCertificateError(
226 scoped_ptr
<SSLErrorCallbacks
> ssl_error_callbacks
,
228 const SSLInfo
& ssl_info
,
229 bool fatal
) override
{
230 return CHANNEL_ALIVE
;
234 // This fake WebSocketStream is for tests that require a WebSocketStream but are
235 // not testing the way it is used. It has minimal functionality to return
236 // the |protocol| and |extensions| that it was constructed with.
237 class FakeWebSocketStream
: public WebSocketStream
{
239 // Constructs with empty protocol and extensions.
240 FakeWebSocketStream() {}
242 // Constructs with specified protocol and extensions.
243 FakeWebSocketStream(const std::string
& protocol
,
244 const std::string
& extensions
)
245 : protocol_(protocol
), extensions_(extensions
) {}
247 int ReadFrames(ScopedVector
<WebSocketFrame
>* frames
,
248 const CompletionCallback
& callback
) override
{
249 return ERR_IO_PENDING
;
252 int WriteFrames(ScopedVector
<WebSocketFrame
>* frames
,
253 const CompletionCallback
& callback
) override
{
254 return ERR_IO_PENDING
;
257 void Close() override
{}
259 // Returns the string passed to the constructor.
260 std::string
GetSubProtocol() const override
{ return protocol_
; }
262 // Returns the string passed to the constructor.
263 std::string
GetExtensions() const override
{ return extensions_
; }
266 // The string to return from GetSubProtocol().
267 std::string protocol_
;
269 // The string to return from GetExtensions().
270 std::string extensions_
;
273 // To make the static initialisers easier to read, we use enums rather than
275 enum IsFinal
{ NOT_FINAL_FRAME
, FINAL_FRAME
};
277 enum IsMasked
{ NOT_MASKED
, MASKED
};
279 // This is used to initialise a WebSocketFrame but is statically initialisable.
282 // Reserved fields omitted for now. Add them if you need them.
283 WebSocketFrameHeader::OpCode opcode
;
286 // Will be used to create the IOBuffer member. Can be NULL for NULL data. Is a
287 // nul-terminated string for ease-of-use. |header.payload_length| is
288 // initialised from |strlen(data)|. This means it is not 8-bit clean, but this
289 // is not an issue for test data.
290 const char* const data
;
294 std::ostream
& operator<<(std::ostream
& os
, const InitFrame
& frame
) {
295 os
<< "{" << (frame
.final
== FINAL_FRAME
? "FINAL_FRAME" : "NOT_FINAL_FRAME")
296 << ", " << frame
.opcode
<< ", "
297 << (frame
.masked
== MASKED
? "MASKED" : "NOT_MASKED") << ", ";
299 return os
<< "\"" << frame
.data
<< "\"}";
301 return os
<< "NULL}";
305 std::ostream
& operator<<(std::ostream
& os
, const InitFrame (&frames
)[N
]) {
308 for (size_t i
= 0; i
< N
; ++i
) {
319 // Convert a const array of InitFrame structs to the format used at
320 // runtime. Templated on the size of the array to save typing.
322 ScopedVector
<WebSocketFrame
> CreateFrameVector(
323 const InitFrame (&source_frames
)[N
]) {
324 ScopedVector
<WebSocketFrame
> result_frames
;
325 result_frames
.reserve(N
);
326 for (size_t i
= 0; i
< N
; ++i
) {
327 const InitFrame
& source_frame
= source_frames
[i
];
328 scoped_ptr
<WebSocketFrame
> result_frame(
329 new WebSocketFrame(source_frame
.opcode
));
330 size_t frame_length
= source_frame
.data
? strlen(source_frame
.data
) : 0;
331 WebSocketFrameHeader
& result_header
= result_frame
->header
;
332 result_header
.final
= (source_frame
.final
== FINAL_FRAME
);
333 result_header
.masked
= (source_frame
.masked
== MASKED
);
334 result_header
.payload_length
= frame_length
;
335 if (source_frame
.data
) {
336 result_frame
->data
= new IOBuffer(frame_length
);
337 memcpy(result_frame
->data
->data(), source_frame
.data
, frame_length
);
339 result_frames
.push_back(result_frame
.release());
341 return result_frames
.Pass();
344 // A GoogleMock action which can be used to respond to call to ReadFrames with
345 // some frames. Use like ReadFrames(_, _).WillOnce(ReturnFrames(&frames));
346 // |frames| is an array of InitFrame. |frames| needs to be passed by pointer
347 // because otherwise it will be treated as a pointer and the array size
348 // information will be lost.
349 ACTION_P(ReturnFrames
, source_frames
) {
350 *arg0
= CreateFrameVector(*source_frames
);
354 // The implementation of a GoogleMock matcher which can be used to compare a
355 // ScopedVector<WebSocketFrame>* against an expectation defined as an array of
356 // InitFrame objects. Although it is possible to compose built-in GoogleMock
357 // matchers to check the contents of a WebSocketFrame, the results are so
358 // unreadable that it is better to use this matcher.
360 class EqualsFramesMatcher
361 : public ::testing::MatcherInterface
<ScopedVector
<WebSocketFrame
>*> {
363 EqualsFramesMatcher(const InitFrame (*expect_frames
)[N
])
364 : expect_frames_(expect_frames
) {}
366 virtual bool MatchAndExplain(ScopedVector
<WebSocketFrame
>* actual_frames
,
367 ::testing::MatchResultListener
* listener
) const {
368 if (actual_frames
->size() != N
) {
369 *listener
<< "the vector size is " << actual_frames
->size();
372 for (size_t i
= 0; i
< N
; ++i
) {
373 const WebSocketFrame
& actual_frame
= *(*actual_frames
)[i
];
374 const InitFrame
& expected_frame
= (*expect_frames_
)[i
];
375 if (actual_frame
.header
.final
!= (expected_frame
.final
== FINAL_FRAME
)) {
376 *listener
<< "the frame is marked as "
377 << (actual_frame
.header
.final
? "" : "not ") << "final";
380 if (actual_frame
.header
.opcode
!= expected_frame
.opcode
) {
381 *listener
<< "the opcode is " << actual_frame
.header
.opcode
;
384 if (actual_frame
.header
.masked
!= (expected_frame
.masked
== MASKED
)) {
385 *listener
<< "the frame is "
386 << (actual_frame
.header
.masked
? "masked" : "not masked");
389 const size_t expected_length
=
390 expected_frame
.data
? strlen(expected_frame
.data
) : 0;
391 if (actual_frame
.header
.payload_length
!= expected_length
) {
392 *listener
<< "the payload length is "
393 << actual_frame
.header
.payload_length
;
396 if (expected_length
!= 0 &&
397 memcmp(actual_frame
.data
->data(),
399 actual_frame
.header
.payload_length
) != 0) {
400 *listener
<< "the data content differs";
407 virtual void DescribeTo(std::ostream
* os
) const {
408 *os
<< "matches " << *expect_frames_
;
411 virtual void DescribeNegationTo(std::ostream
* os
) const {
412 *os
<< "does not match " << *expect_frames_
;
416 const InitFrame (*expect_frames_
)[N
];
419 // The definition of EqualsFrames GoogleMock matcher. Unlike the ReturnFrames
420 // action, this can take the array by reference.
422 ::testing::Matcher
<ScopedVector
<WebSocketFrame
>*> EqualsFrames(
423 const InitFrame (&frames
)[N
]) {
424 return ::testing::MakeMatcher(new EqualsFramesMatcher
<N
>(&frames
));
427 // A GoogleMock action to run a Closure.
428 ACTION_P(InvokeClosure
, closure
) { closure
.Run(); }
430 // A GoogleMock action to run a Closure and return CHANNEL_DELETED.
431 ACTION_P(InvokeClosureReturnDeleted
, closure
) {
433 return WebSocketEventInterface::CHANNEL_DELETED
;
436 // A FakeWebSocketStream whose ReadFrames() function returns data.
437 class ReadableFakeWebSocketStream
: public FakeWebSocketStream
{
439 enum IsSync
{ SYNC
, ASYNC
};
441 // After constructing the object, call PrepareReadFrames() once for each
442 // time you wish it to return from the test.
443 ReadableFakeWebSocketStream() : index_(0), read_frames_pending_(false) {}
445 // Check that all the prepared responses have been consumed.
446 ~ReadableFakeWebSocketStream() override
{
447 CHECK(index_
>= responses_
.size());
448 CHECK(!read_frames_pending_
);
451 // Prepares a fake response. Fake responses will be returned from ReadFrames()
452 // in the same order they were prepared with PrepareReadFrames() and
453 // PrepareReadFramesError(). If |async| is ASYNC, then ReadFrames() will
454 // return ERR_IO_PENDING and the callback will be scheduled to run on the
455 // message loop. This requires the test case to run the message loop. If
456 // |async| is SYNC, the response will be returned synchronously. |error| is
457 // returned directly from ReadFrames() in the synchronous case, or passed to
458 // the callback in the asynchronous case. |frames| will be converted to a
459 // ScopedVector<WebSocketFrame> and copied to the pointer that was passed to
462 void PrepareReadFrames(IsSync async
,
464 const InitFrame (&frames
)[N
]) {
465 responses_
.push_back(new Response(async
, error
, CreateFrameVector(frames
)));
468 // An alternate version of PrepareReadFrames for when we need to construct
469 // the frames manually.
470 void PrepareRawReadFrames(IsSync async
,
472 ScopedVector
<WebSocketFrame
> frames
) {
473 responses_
.push_back(new Response(async
, error
, frames
.Pass()));
476 // Prepares a fake error response (ie. there is no data).
477 void PrepareReadFramesError(IsSync async
, int error
) {
478 responses_
.push_back(
479 new Response(async
, error
, ScopedVector
<WebSocketFrame
>()));
482 int ReadFrames(ScopedVector
<WebSocketFrame
>* frames
,
483 const CompletionCallback
& callback
) override
{
484 CHECK(!read_frames_pending_
);
485 if (index_
>= responses_
.size())
486 return ERR_IO_PENDING
;
487 if (responses_
[index_
]->async
== ASYNC
) {
488 read_frames_pending_
= true;
489 base::MessageLoop::current()->PostTask(
491 base::Bind(&ReadableFakeWebSocketStream::DoCallback
,
492 base::Unretained(this),
495 return ERR_IO_PENDING
;
497 frames
->swap(responses_
[index_
]->frames
);
498 return responses_
[index_
++]->error
;
503 void DoCallback(ScopedVector
<WebSocketFrame
>* frames
,
504 const CompletionCallback
& callback
) {
505 read_frames_pending_
= false;
506 frames
->swap(responses_
[index_
]->frames
);
507 callback
.Run(responses_
[index_
++]->error
);
512 Response(IsSync async
, int error
, ScopedVector
<WebSocketFrame
> frames
)
513 : async(async
), error(error
), frames(frames
.Pass()) {}
517 ScopedVector
<WebSocketFrame
> frames
;
520 // Bad things will happen if we attempt to copy or assign |frames|.
521 DISALLOW_COPY_AND_ASSIGN(Response
);
523 ScopedVector
<Response
> responses_
;
525 // The index into the responses_ array of the next response to be returned.
528 // True when an async response from ReadFrames() is pending. This only applies
529 // to "real" async responses. Once all the prepared responses have been
530 // returned, ReadFrames() returns ERR_IO_PENDING but read_frames_pending_ is
532 bool read_frames_pending_
;
535 // A FakeWebSocketStream where writes always complete successfully and
537 class WriteableFakeWebSocketStream
: public FakeWebSocketStream
{
539 int WriteFrames(ScopedVector
<WebSocketFrame
>* frames
,
540 const CompletionCallback
& callback
) override
{
545 // A FakeWebSocketStream where writes always fail.
546 class UnWriteableFakeWebSocketStream
: public FakeWebSocketStream
{
548 int WriteFrames(ScopedVector
<WebSocketFrame
>* frames
,
549 const CompletionCallback
& callback
) override
{
550 return ERR_CONNECTION_RESET
;
554 // A FakeWebSocketStream which echoes any frames written back. Clears the
555 // "masked" header bit, but makes no other checks for validity. Tests using this
556 // must run the MessageLoop to receive the callback(s). If a message with opcode
557 // Close is echoed, then an ERR_CONNECTION_CLOSED is returned in the next
558 // callback. The test must do something to cause WriteFrames() to be called,
559 // otherwise the ReadFrames() callback will never be called.
560 class EchoeyFakeWebSocketStream
: public FakeWebSocketStream
{
562 EchoeyFakeWebSocketStream() : read_frames_(NULL
), done_(false) {}
564 int WriteFrames(ScopedVector
<WebSocketFrame
>* frames
,
565 const CompletionCallback
& callback
) override
{
566 // Users of WebSocketStream will not expect the ReadFrames() callback to be
567 // called from within WriteFrames(), so post it to the message loop instead.
568 stored_frames_
.insert(stored_frames_
.end(), frames
->begin(), frames
->end());
569 frames
->weak_clear();
574 int ReadFrames(ScopedVector
<WebSocketFrame
>* frames
,
575 const CompletionCallback
& callback
) override
{
576 read_callback_
= callback
;
577 read_frames_
= frames
;
580 return ERR_IO_PENDING
;
584 void PostCallback() {
585 base::MessageLoop::current()->PostTask(
587 base::Bind(&EchoeyFakeWebSocketStream::DoCallback
,
588 base::Unretained(this)));
593 read_callback_
.Run(ERR_CONNECTION_CLOSED
);
594 } else if (!stored_frames_
.empty()) {
595 done_
= MoveFrames(read_frames_
);
597 read_callback_
.Run(OK
);
601 // Copy the frames stored in stored_frames_ to |out|, while clearing the
602 // "masked" header bit. Returns true if a Close Frame was seen, false
604 bool MoveFrames(ScopedVector
<WebSocketFrame
>* out
) {
605 bool seen_close
= false;
606 *out
= stored_frames_
.Pass();
607 for (ScopedVector
<WebSocketFrame
>::iterator it
= out
->begin();
610 WebSocketFrameHeader
& header
= (*it
)->header
;
611 header
.masked
= false;
612 if (header
.opcode
== WebSocketFrameHeader::kOpCodeClose
)
618 ScopedVector
<WebSocketFrame
> stored_frames_
;
619 CompletionCallback read_callback_
;
620 // Owned by the caller of ReadFrames().
621 ScopedVector
<WebSocketFrame
>* read_frames_
;
622 // True if we should close the connection.
626 // A FakeWebSocketStream where writes trigger a connection reset.
627 // This differs from UnWriteableFakeWebSocketStream in that it is asynchronous
628 // and triggers ReadFrames to return a reset as well. Tests using this need to
629 // run the message loop. There are two tricky parts here:
630 // 1. Calling the write callback may call Close(), after which the read callback
631 // should not be called.
632 // 2. Calling either callback may delete the stream altogether.
633 class ResetOnWriteFakeWebSocketStream
: public FakeWebSocketStream
{
635 ResetOnWriteFakeWebSocketStream() : closed_(false), weak_ptr_factory_(this) {}
637 int WriteFrames(ScopedVector
<WebSocketFrame
>* frames
,
638 const CompletionCallback
& callback
) override
{
639 base::MessageLoop::current()->PostTask(
641 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed
,
642 weak_ptr_factory_
.GetWeakPtr(),
644 ERR_CONNECTION_RESET
));
645 base::MessageLoop::current()->PostTask(
647 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed
,
648 weak_ptr_factory_
.GetWeakPtr(),
650 ERR_CONNECTION_RESET
));
651 return ERR_IO_PENDING
;
654 int ReadFrames(ScopedVector
<WebSocketFrame
>* frames
,
655 const CompletionCallback
& callback
) override
{
656 read_callback_
= callback
;
657 return ERR_IO_PENDING
;
660 void Close() override
{ closed_
= true; }
663 void CallCallbackUnlessClosed(const CompletionCallback
& callback
, int value
) {
668 CompletionCallback read_callback_
;
670 // An IO error can result in the socket being deleted, so we use weak pointers
671 // to ensure correct behaviour in that case.
672 base::WeakPtrFactory
<ResetOnWriteFakeWebSocketStream
> weak_ptr_factory_
;
675 // This mock is for verifying that WebSocket protocol semantics are obeyed (to
676 // the extent that they are implemented in WebSocketCommon).
677 class MockWebSocketStream
: public WebSocketStream
{
679 MOCK_METHOD2(ReadFrames
,
680 int(ScopedVector
<WebSocketFrame
>* frames
,
681 const CompletionCallback
& callback
));
682 MOCK_METHOD2(WriteFrames
,
683 int(ScopedVector
<WebSocketFrame
>* frames
,
684 const CompletionCallback
& callback
));
685 MOCK_METHOD0(Close
, void());
686 MOCK_CONST_METHOD0(GetSubProtocol
, std::string());
687 MOCK_CONST_METHOD0(GetExtensions
, std::string());
688 MOCK_METHOD0(AsWebSocketStream
, WebSocketStream
*());
691 struct ArgumentCopyingWebSocketStreamCreator
{
692 scoped_ptr
<WebSocketStreamRequest
> Create(
693 const GURL
& socket_url
,
694 const std::vector
<std::string
>& requested_subprotocols
,
695 const url::Origin
& origin
,
696 URLRequestContext
* url_request_context
,
697 const BoundNetLog
& net_log
,
698 scoped_ptr
<WebSocketStream::ConnectDelegate
> connect_delegate
) {
699 this->socket_url
= socket_url
;
700 this->requested_subprotocols
= requested_subprotocols
;
701 this->origin
= origin
;
702 this->url_request_context
= url_request_context
;
703 this->net_log
= net_log
;
704 this->connect_delegate
= connect_delegate
.Pass();
705 return make_scoped_ptr(new WebSocketStreamRequest
);
710 std::vector
<std::string
> requested_subprotocols
;
711 URLRequestContext
* url_request_context
;
713 scoped_ptr
<WebSocketStream::ConnectDelegate
> connect_delegate
;
716 // Converts a std::string to a std::vector<char>. For test purposes, it is
717 // convenient to be able to specify data as a string, but the
718 // WebSocketEventInterface requires the vector<char> type.
719 std::vector
<char> AsVector(const std::string
& s
) {
720 return std::vector
<char>(s
.begin(), s
.end());
723 class FakeSSLErrorCallbacks
724 : public WebSocketEventInterface::SSLErrorCallbacks
{
726 void CancelSSLRequest(int error
, const SSLInfo
* ssl_info
) override
{}
727 void ContinueSSLRequest() override
{}
730 // Base class for all test fixtures.
731 class WebSocketChannelTest
: public ::testing::Test
{
733 WebSocketChannelTest() : stream_(new FakeWebSocketStream
) {}
735 // Creates a new WebSocketChannel and connects it, using the settings stored
736 // in |connect_data_|.
737 void CreateChannelAndConnect() {
738 channel_
.reset(new WebSocketChannel(CreateEventInterface(),
739 &connect_data_
.url_request_context
));
740 channel_
->SendAddChannelRequestForTesting(
741 connect_data_
.socket_url
,
742 connect_data_
.requested_subprotocols
,
743 connect_data_
.origin
,
744 base::Bind(&ArgumentCopyingWebSocketStreamCreator::Create
,
745 base::Unretained(&connect_data_
.creator
)));
748 // Same as CreateChannelAndConnect(), but calls the on_success callback as
749 // well. This method is virtual so that subclasses can also set the stream.
750 virtual void CreateChannelAndConnectSuccessfully() {
751 CreateChannelAndConnect();
752 // Most tests aren't concerned with flow control from the renderer, so allow
753 // MAX_INT quota units.
754 channel_
->SendFlowControl(kPlentyOfQuota
);
755 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
758 // Returns a WebSocketEventInterface to be passed to the WebSocketChannel.
759 // This implementation returns a newly-created fake. Subclasses may return a
761 virtual scoped_ptr
<WebSocketEventInterface
> CreateEventInterface() {
762 return scoped_ptr
<WebSocketEventInterface
>(new FakeWebSocketEventInterface
);
765 // This method serves no other purpose than to provide a nice syntax for
766 // assigning to stream_. class T must be a subclass of WebSocketStream or you
767 // will have unpleasant compile errors.
769 void set_stream(scoped_ptr
<T
> stream
) {
770 stream_
= stream
.Pass();
773 // A struct containing the data that will be used to connect the channel.
774 // Grouped for readability.
776 ConnectData() : socket_url("ws://ws/"), origin("http://ws") {}
778 // URLRequestContext object.
779 URLRequestContext url_request_context
;
781 // URL to (pretend to) connect to.
783 // Requested protocols for the request.
784 std::vector
<std::string
> requested_subprotocols
;
785 // Origin of the request
788 // A fake WebSocketStreamCreator that just records its arguments.
789 ArgumentCopyingWebSocketStreamCreator creator
;
791 ConnectData connect_data_
;
793 // The channel we are testing. Not initialised until SetChannel() is called.
794 scoped_ptr
<WebSocketChannel
> channel_
;
796 // A mock or fake stream for tests that need one.
797 scoped_ptr
<WebSocketStream
> stream_
;
800 // enum of WebSocketEventInterface calls. These are intended to be or'd together
801 // in order to instruct WebSocketChannelDeletingTest when it should fail.
802 enum EventInterfaceCall
{
803 EVENT_ON_ADD_CHANNEL_RESPONSE
= 0x1,
804 EVENT_ON_DATA_FRAME
= 0x2,
805 EVENT_ON_FLOW_CONTROL
= 0x4,
806 EVENT_ON_CLOSING_HANDSHAKE
= 0x8,
807 EVENT_ON_FAIL_CHANNEL
= 0x10,
808 EVENT_ON_DROP_CHANNEL
= 0x20,
809 EVENT_ON_START_OPENING_HANDSHAKE
= 0x40,
810 EVENT_ON_FINISH_OPENING_HANDSHAKE
= 0x80,
811 EVENT_ON_SSL_CERTIFICATE_ERROR
= 0x100,
814 class WebSocketChannelDeletingTest
: public WebSocketChannelTest
{
816 ChannelState
DeleteIfDeleting(EventInterfaceCall call
) {
817 if (deleting_
& call
) {
819 return CHANNEL_DELETED
;
821 return CHANNEL_ALIVE
;
826 WebSocketChannelDeletingTest()
827 : deleting_(EVENT_ON_ADD_CHANNEL_RESPONSE
| EVENT_ON_DATA_FRAME
|
828 EVENT_ON_FLOW_CONTROL
|
829 EVENT_ON_CLOSING_HANDSHAKE
|
830 EVENT_ON_FAIL_CHANNEL
|
831 EVENT_ON_DROP_CHANNEL
|
832 EVENT_ON_START_OPENING_HANDSHAKE
|
833 EVENT_ON_FINISH_OPENING_HANDSHAKE
|
834 EVENT_ON_SSL_CERTIFICATE_ERROR
) {}
835 // Create a ChannelDeletingFakeWebSocketEventInterface. Defined out-of-line to
836 // avoid circular dependency.
837 scoped_ptr
<WebSocketEventInterface
> CreateEventInterface() override
;
839 // Tests can set deleting_ to a bitmap of EventInterfaceCall members that they
840 // want to cause Channel deletion. The default is for all calls to cause
845 // A FakeWebSocketEventInterface that deletes the WebSocketChannel on failure to
847 class ChannelDeletingFakeWebSocketEventInterface
848 : public FakeWebSocketEventInterface
{
850 ChannelDeletingFakeWebSocketEventInterface(
851 WebSocketChannelDeletingTest
* fixture
)
852 : fixture_(fixture
) {}
854 ChannelState
OnAddChannelResponse(bool fail
,
855 const std::string
& selected_protocol
,
856 const std::string
& extensions
) override
{
857 return fixture_
->DeleteIfDeleting(EVENT_ON_ADD_CHANNEL_RESPONSE
);
860 ChannelState
OnDataFrame(bool fin
,
861 WebSocketMessageType type
,
862 const std::vector
<char>& data
) override
{
863 return fixture_
->DeleteIfDeleting(EVENT_ON_DATA_FRAME
);
866 ChannelState
OnFlowControl(int64 quota
) override
{
867 return fixture_
->DeleteIfDeleting(EVENT_ON_FLOW_CONTROL
);
870 ChannelState
OnClosingHandshake() override
{
871 return fixture_
->DeleteIfDeleting(EVENT_ON_CLOSING_HANDSHAKE
);
874 ChannelState
OnFailChannel(const std::string
& message
) override
{
875 return fixture_
->DeleteIfDeleting(EVENT_ON_FAIL_CHANNEL
);
878 ChannelState
OnDropChannel(bool was_clean
,
880 const std::string
& reason
) override
{
881 return fixture_
->DeleteIfDeleting(EVENT_ON_DROP_CHANNEL
);
884 ChannelState
OnStartOpeningHandshake(
885 scoped_ptr
<WebSocketHandshakeRequestInfo
> request
) override
{
886 return fixture_
->DeleteIfDeleting(EVENT_ON_START_OPENING_HANDSHAKE
);
888 ChannelState
OnFinishOpeningHandshake(
889 scoped_ptr
<WebSocketHandshakeResponseInfo
> response
) override
{
890 return fixture_
->DeleteIfDeleting(EVENT_ON_FINISH_OPENING_HANDSHAKE
);
892 ChannelState
OnSSLCertificateError(
893 scoped_ptr
<SSLErrorCallbacks
> ssl_error_callbacks
,
895 const SSLInfo
& ssl_info
,
896 bool fatal
) override
{
897 return fixture_
->DeleteIfDeleting(EVENT_ON_SSL_CERTIFICATE_ERROR
);
901 // A pointer to the test fixture. Owned by the test harness; this object will
902 // be deleted before it is.
903 WebSocketChannelDeletingTest
* fixture_
;
906 scoped_ptr
<WebSocketEventInterface
>
907 WebSocketChannelDeletingTest::CreateEventInterface() {
908 return scoped_ptr
<WebSocketEventInterface
>(
909 new ChannelDeletingFakeWebSocketEventInterface(this));
912 // Base class for tests which verify that EventInterface methods are called
914 class WebSocketChannelEventInterfaceTest
: public WebSocketChannelTest
{
916 WebSocketChannelEventInterfaceTest()
917 : event_interface_(new StrictMock
<MockWebSocketEventInterface
>) {
918 DefaultValue
<ChannelState
>::Set(CHANNEL_ALIVE
);
919 ON_CALL(*event_interface_
, OnAddChannelResponse(true, _
, _
))
920 .WillByDefault(Return(CHANNEL_DELETED
));
921 ON_CALL(*event_interface_
, OnDropChannel(_
, _
, _
))
922 .WillByDefault(Return(CHANNEL_DELETED
));
923 ON_CALL(*event_interface_
, OnFailChannel(_
))
924 .WillByDefault(Return(CHANNEL_DELETED
));
927 ~WebSocketChannelEventInterfaceTest() override
{
928 DefaultValue
<ChannelState
>::Clear();
931 // Tests using this fixture must set expectations on the event_interface_ mock
932 // object before calling CreateChannelAndConnect() or
933 // CreateChannelAndConnectSuccessfully(). This will only work once per test
934 // case, but once should be enough.
935 scoped_ptr
<WebSocketEventInterface
> CreateEventInterface() override
{
936 return scoped_ptr
<WebSocketEventInterface
>(event_interface_
.release());
939 scoped_ptr
<MockWebSocketEventInterface
> event_interface_
;
942 // Base class for tests which verify that WebSocketStream methods are called
943 // appropriately by using a MockWebSocketStream.
944 class WebSocketChannelStreamTest
: public WebSocketChannelTest
{
946 WebSocketChannelStreamTest()
947 : mock_stream_(new StrictMock
<MockWebSocketStream
>) {}
949 void CreateChannelAndConnectSuccessfully() override
{
950 set_stream(mock_stream_
.Pass());
951 WebSocketChannelTest::CreateChannelAndConnectSuccessfully();
954 scoped_ptr
<MockWebSocketStream
> mock_stream_
;
957 // Fixture for tests which test UTF-8 validation of sent Text frames via the
959 class WebSocketChannelSendUtf8Test
960 : public WebSocketChannelEventInterfaceTest
{
962 void SetUp() override
{
963 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
964 // For the purpose of the tests using this fixture, it doesn't matter
965 // whether these methods are called or not.
966 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
, _
))
968 EXPECT_CALL(*event_interface_
, OnFlowControl(_
))
973 // Fixture for tests which test use of receive quota from the renderer.
974 class WebSocketChannelFlowControlTest
975 : public WebSocketChannelEventInterfaceTest
{
977 // Tests using this fixture should use CreateChannelAndConnectWithQuota()
978 // instead of CreateChannelAndConnectSuccessfully().
979 void CreateChannelAndConnectWithQuota(int64 quota
) {
980 CreateChannelAndConnect();
981 channel_
->SendFlowControl(quota
);
982 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
985 virtual void CreateChannelAndConnectSuccesfully() { NOTREACHED(); }
988 // Fixture for tests which test UTF-8 validation of received Text frames using a
989 // mock WebSocketStream.
990 class WebSocketChannelReceiveUtf8Test
: public WebSocketChannelStreamTest
{
992 void SetUp() override
{
993 // For the purpose of the tests using this fixture, it doesn't matter
994 // whether these methods are called or not.
995 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
996 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
1000 // Simple test that everything that should be passed to the creator function is
1001 // passed to the creator function.
1002 TEST_F(WebSocketChannelTest
, EverythingIsPassedToTheCreatorFunction
) {
1003 connect_data_
.socket_url
= GURL("ws://example.com/test");
1004 connect_data_
.origin
= url::Origin("http://example.com");
1005 connect_data_
.requested_subprotocols
.push_back("Sinbad");
1007 CreateChannelAndConnect();
1009 const ArgumentCopyingWebSocketStreamCreator
& actual
= connect_data_
.creator
;
1011 EXPECT_EQ(&connect_data_
.url_request_context
, actual
.url_request_context
);
1013 EXPECT_EQ(connect_data_
.socket_url
, actual
.socket_url
);
1014 EXPECT_EQ(connect_data_
.requested_subprotocols
,
1015 actual
.requested_subprotocols
);
1016 EXPECT_EQ(connect_data_
.origin
.string(), actual
.origin
.string());
1019 // Verify that calling SendFlowControl before the connection is established does
1020 // not cause a crash.
1021 TEST_F(WebSocketChannelTest
, SendFlowControlDuringHandshakeOkay
) {
1022 CreateChannelAndConnect();
1023 ASSERT_TRUE(channel_
);
1024 channel_
->SendFlowControl(65536);
1027 // Any WebSocketEventInterface methods can delete the WebSocketChannel and
1028 // return CHANNEL_DELETED. The WebSocketChannelDeletingTests are intended to
1029 // verify that there are no use-after-free bugs when this happens. Problems will
1030 // probably only be found when running under Address Sanitizer or a similar
1032 TEST_F(WebSocketChannelDeletingTest
, OnAddChannelResponseFail
) {
1033 CreateChannelAndConnect();
1034 EXPECT_TRUE(channel_
);
1035 connect_data_
.creator
.connect_delegate
->OnFailure("bye");
1036 EXPECT_EQ(NULL
, channel_
.get());
1039 // Deletion is possible (due to IPC failure) even if the connect succeeds.
1040 TEST_F(WebSocketChannelDeletingTest
, OnAddChannelResponseSuccess
) {
1041 CreateChannelAndConnectSuccessfully();
1042 EXPECT_EQ(NULL
, channel_
.get());
1045 TEST_F(WebSocketChannelDeletingTest
, OnDataFrameSync
) {
1046 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1047 new ReadableFakeWebSocketStream
);
1048 static const InitFrame frames
[] = {
1049 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1050 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1051 set_stream(stream
.Pass());
1052 deleting_
= EVENT_ON_DATA_FRAME
;
1054 CreateChannelAndConnectSuccessfully();
1055 EXPECT_EQ(NULL
, channel_
.get());
1058 TEST_F(WebSocketChannelDeletingTest
, OnDataFrameAsync
) {
1059 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1060 new ReadableFakeWebSocketStream
);
1061 static const InitFrame frames
[] = {
1062 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1063 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1064 set_stream(stream
.Pass());
1065 deleting_
= EVENT_ON_DATA_FRAME
;
1067 CreateChannelAndConnectSuccessfully();
1068 EXPECT_TRUE(channel_
);
1069 base::MessageLoop::current()->RunUntilIdle();
1070 EXPECT_EQ(NULL
, channel_
.get());
1073 TEST_F(WebSocketChannelDeletingTest
, OnFlowControlAfterConnect
) {
1074 deleting_
= EVENT_ON_FLOW_CONTROL
;
1076 CreateChannelAndConnectSuccessfully();
1077 EXPECT_EQ(NULL
, channel_
.get());
1080 TEST_F(WebSocketChannelDeletingTest
, OnFlowControlAfterSend
) {
1081 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
1082 // Avoid deleting the channel yet.
1083 deleting_
= EVENT_ON_FAIL_CHANNEL
| EVENT_ON_DROP_CHANNEL
;
1084 CreateChannelAndConnectSuccessfully();
1085 ASSERT_TRUE(channel_
);
1086 deleting_
= EVENT_ON_FLOW_CONTROL
;
1087 channel_
->SendFrame(true,
1088 WebSocketFrameHeader::kOpCodeText
,
1089 std::vector
<char>(kDefaultInitialQuota
, 'B'));
1090 EXPECT_EQ(NULL
, channel_
.get());
1093 TEST_F(WebSocketChannelDeletingTest
, OnClosingHandshakeSync
) {
1094 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1095 new ReadableFakeWebSocketStream
);
1096 static const InitFrame frames
[] = {
1097 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
1098 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Success")}};
1099 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1100 set_stream(stream
.Pass());
1101 deleting_
= EVENT_ON_CLOSING_HANDSHAKE
;
1102 CreateChannelAndConnectSuccessfully();
1103 EXPECT_EQ(NULL
, channel_
.get());
1106 TEST_F(WebSocketChannelDeletingTest
, OnClosingHandshakeAsync
) {
1107 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1108 new ReadableFakeWebSocketStream
);
1109 static const InitFrame frames
[] = {
1110 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
1111 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Success")}};
1112 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1113 set_stream(stream
.Pass());
1114 deleting_
= EVENT_ON_CLOSING_HANDSHAKE
;
1115 CreateChannelAndConnectSuccessfully();
1116 ASSERT_TRUE(channel_
);
1117 base::MessageLoop::current()->RunUntilIdle();
1118 EXPECT_EQ(NULL
, channel_
.get());
1121 TEST_F(WebSocketChannelDeletingTest
, OnDropChannelWriteError
) {
1122 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream
));
1123 deleting_
= EVENT_ON_DROP_CHANNEL
;
1124 CreateChannelAndConnectSuccessfully();
1125 ASSERT_TRUE(channel_
);
1126 channel_
->SendFrame(
1127 true, WebSocketFrameHeader::kOpCodeText
, AsVector("this will fail"));
1128 EXPECT_EQ(NULL
, channel_
.get());
1131 TEST_F(WebSocketChannelDeletingTest
, OnDropChannelReadError
) {
1132 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1133 new ReadableFakeWebSocketStream
);
1134 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC
,
1136 set_stream(stream
.Pass());
1137 deleting_
= EVENT_ON_DROP_CHANNEL
;
1138 CreateChannelAndConnectSuccessfully();
1139 ASSERT_TRUE(channel_
);
1140 base::MessageLoop::current()->RunUntilIdle();
1141 EXPECT_EQ(NULL
, channel_
.get());
1144 TEST_F(WebSocketChannelDeletingTest
, OnNotifyStartOpeningHandshakeError
) {
1145 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1146 new ReadableFakeWebSocketStream
);
1147 static const InitFrame frames
[] = {
1148 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1149 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1150 set_stream(stream
.Pass());
1151 deleting_
= EVENT_ON_START_OPENING_HANDSHAKE
;
1153 CreateChannelAndConnectSuccessfully();
1154 ASSERT_TRUE(channel_
);
1155 channel_
->OnStartOpeningHandshake(scoped_ptr
<WebSocketHandshakeRequestInfo
>(
1156 new WebSocketHandshakeRequestInfo(GURL("http://www.example.com/"),
1158 base::MessageLoop::current()->RunUntilIdle();
1159 EXPECT_EQ(NULL
, channel_
.get());
1162 TEST_F(WebSocketChannelDeletingTest
, OnNotifyFinishOpeningHandshakeError
) {
1163 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1164 new ReadableFakeWebSocketStream
);
1165 static const InitFrame frames
[] = {
1166 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1167 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1168 set_stream(stream
.Pass());
1169 deleting_
= EVENT_ON_FINISH_OPENING_HANDSHAKE
;
1171 CreateChannelAndConnectSuccessfully();
1172 ASSERT_TRUE(channel_
);
1173 scoped_refptr
<HttpResponseHeaders
> response_headers(
1174 new HttpResponseHeaders(""));
1175 channel_
->OnFinishOpeningHandshake(scoped_ptr
<WebSocketHandshakeResponseInfo
>(
1176 new WebSocketHandshakeResponseInfo(GURL("http://www.example.com/"),
1181 base::MessageLoop::current()->RunUntilIdle();
1182 EXPECT_EQ(NULL
, channel_
.get());
1185 TEST_F(WebSocketChannelDeletingTest
, FailChannelInSendFrame
) {
1186 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
1187 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1188 CreateChannelAndConnectSuccessfully();
1189 ASSERT_TRUE(channel_
);
1190 channel_
->SendFrame(true,
1191 WebSocketFrameHeader::kOpCodeText
,
1192 std::vector
<char>(kDefaultInitialQuota
* 2, 'T'));
1193 EXPECT_EQ(NULL
, channel_
.get());
1196 TEST_F(WebSocketChannelDeletingTest
, FailChannelInOnReadDone
) {
1197 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1198 new ReadableFakeWebSocketStream
);
1199 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC
,
1200 ERR_WS_PROTOCOL_ERROR
);
1201 set_stream(stream
.Pass());
1202 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1203 CreateChannelAndConnectSuccessfully();
1204 ASSERT_TRUE(channel_
);
1205 base::MessageLoop::current()->RunUntilIdle();
1206 EXPECT_EQ(NULL
, channel_
.get());
1209 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToMaskedFrame
) {
1210 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1211 new ReadableFakeWebSocketStream
);
1212 static const InitFrame frames
[] = {
1213 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "HELLO"}};
1214 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1215 set_stream(stream
.Pass());
1216 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1218 CreateChannelAndConnectSuccessfully();
1219 EXPECT_EQ(NULL
, channel_
.get());
1222 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToBadControlFrame
) {
1223 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1224 new ReadableFakeWebSocketStream
);
1225 static const InitFrame frames
[] = {
1226 {FINAL_FRAME
, 0xF, NOT_MASKED
, ""}};
1227 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1228 set_stream(stream
.Pass());
1229 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1231 CreateChannelAndConnectSuccessfully();
1232 EXPECT_EQ(NULL
, channel_
.get());
1235 // Version of above test with NULL data.
1236 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToBadControlFrameNull
) {
1237 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1238 new ReadableFakeWebSocketStream
);
1239 static const InitFrame frames
[] = {
1240 {FINAL_FRAME
, 0xF, NOT_MASKED
, NULL
}};
1241 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1242 set_stream(stream
.Pass());
1243 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1245 CreateChannelAndConnectSuccessfully();
1246 EXPECT_EQ(NULL
, channel_
.get());
1249 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToPongAfterClose
) {
1250 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1251 new ReadableFakeWebSocketStream
);
1252 static const InitFrame frames
[] = {
1253 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
,
1254 CLOSE_DATA(NORMAL_CLOSURE
, "Success")},
1255 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
, NOT_MASKED
, ""}};
1256 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1257 set_stream(stream
.Pass());
1258 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1260 CreateChannelAndConnectSuccessfully();
1261 EXPECT_EQ(NULL
, channel_
.get());
1264 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToPongAfterCloseNull
) {
1265 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1266 new ReadableFakeWebSocketStream
);
1267 static const InitFrame frames
[] = {
1268 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
,
1269 CLOSE_DATA(NORMAL_CLOSURE
, "Success")},
1270 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
, NOT_MASKED
, NULL
}};
1271 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1272 set_stream(stream
.Pass());
1273 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1275 CreateChannelAndConnectSuccessfully();
1276 EXPECT_EQ(NULL
, channel_
.get());
1279 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToUnknownOpCode
) {
1280 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1281 new ReadableFakeWebSocketStream
);
1282 static const InitFrame frames
[] = {{FINAL_FRAME
, 0x7, NOT_MASKED
, ""}};
1283 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1284 set_stream(stream
.Pass());
1285 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1287 CreateChannelAndConnectSuccessfully();
1288 EXPECT_EQ(NULL
, channel_
.get());
1291 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToUnknownOpCodeNull
) {
1292 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1293 new ReadableFakeWebSocketStream
);
1294 static const InitFrame frames
[] = {{FINAL_FRAME
, 0x7, NOT_MASKED
, NULL
}};
1295 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1296 set_stream(stream
.Pass());
1297 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1299 CreateChannelAndConnectSuccessfully();
1300 EXPECT_EQ(NULL
, channel_
.get());
1303 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueInvalidCloseReason
) {
1304 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1305 new ReadableFakeWebSocketStream
);
1306 static const InitFrame frames
[] = {
1307 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
1308 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "\xFF")}};
1309 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1310 set_stream(stream
.Pass());
1311 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1313 CreateChannelAndConnectSuccessfully();
1314 EXPECT_EQ(NULL
, channel_
.get());
1317 TEST_F(WebSocketChannelEventInterfaceTest
, ConnectSuccessReported
) {
1318 // false means success.
1319 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, "", ""));
1320 // OnFlowControl is always called immediately after connect to provide initial
1321 // quota to the renderer.
1322 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1324 CreateChannelAndConnect();
1326 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
1329 TEST_F(WebSocketChannelEventInterfaceTest
, ConnectFailureReported
) {
1330 EXPECT_CALL(*event_interface_
, OnFailChannel("hello"));
1332 CreateChannelAndConnect();
1334 connect_data_
.creator
.connect_delegate
->OnFailure("hello");
1337 TEST_F(WebSocketChannelEventInterfaceTest
, NonWebSocketSchemeRejected
) {
1338 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(true, "", ""));
1339 connect_data_
.socket_url
= GURL("http://www.google.com/");
1340 CreateChannelAndConnect();
1343 TEST_F(WebSocketChannelEventInterfaceTest
, ProtocolPassed
) {
1344 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, "Bob", ""));
1345 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1347 CreateChannelAndConnect();
1349 connect_data_
.creator
.connect_delegate
->OnSuccess(
1350 scoped_ptr
<WebSocketStream
>(new FakeWebSocketStream("Bob", "")));
1353 TEST_F(WebSocketChannelEventInterfaceTest
, ExtensionsPassed
) {
1354 EXPECT_CALL(*event_interface_
,
1355 OnAddChannelResponse(false, "", "extension1, extension2"));
1356 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1358 CreateChannelAndConnect();
1360 connect_data_
.creator
.connect_delegate
->OnSuccess(scoped_ptr
<WebSocketStream
>(
1361 new FakeWebSocketStream("", "extension1, extension2")));
1364 // The first frames from the server can arrive together with the handshake, in
1365 // which case they will be available as soon as ReadFrames() is called the first
1367 TEST_F(WebSocketChannelEventInterfaceTest
, DataLeftFromHandshake
) {
1368 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1369 new ReadableFakeWebSocketStream
);
1370 static const InitFrame frames
[] = {
1371 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1372 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1373 set_stream(stream
.Pass());
1376 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1377 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1381 true, WebSocketFrameHeader::kOpCodeText
, AsVector("HELLO")));
1384 CreateChannelAndConnectSuccessfully();
1387 // A remote server could accept the handshake, but then immediately send a
1389 TEST_F(WebSocketChannelEventInterfaceTest
, CloseAfterHandshake
) {
1390 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1391 new ReadableFakeWebSocketStream
);
1392 static const InitFrame frames
[] = {
1393 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
1394 NOT_MASKED
, CLOSE_DATA(SERVER_ERROR
, "Internal Server Error")}};
1395 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1396 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC
,
1397 ERR_CONNECTION_CLOSED
);
1398 set_stream(stream
.Pass());
1401 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1402 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1403 EXPECT_CALL(*event_interface_
, OnClosingHandshake());
1407 true, kWebSocketErrorInternalServerError
, "Internal Server Error"));
1410 CreateChannelAndConnectSuccessfully();
1413 // A remote server could close the connection immediately after sending the
1414 // handshake response (most likely a bug in the server).
1415 TEST_F(WebSocketChannelEventInterfaceTest
, ConnectionCloseAfterHandshake
) {
1416 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1417 new ReadableFakeWebSocketStream
);
1418 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC
,
1419 ERR_CONNECTION_CLOSED
);
1420 set_stream(stream
.Pass());
1423 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1424 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1425 EXPECT_CALL(*event_interface_
,
1426 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, _
));
1429 CreateChannelAndConnectSuccessfully();
1432 TEST_F(WebSocketChannelEventInterfaceTest
, NormalAsyncRead
) {
1433 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1434 new ReadableFakeWebSocketStream
);
1435 static const InitFrame frames
[] = {
1436 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1437 // We use this checkpoint object to verify that the callback isn't called
1438 // until we expect it to be.
1439 Checkpoint checkpoint
;
1440 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1441 set_stream(stream
.Pass());
1444 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1445 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1446 EXPECT_CALL(checkpoint
, Call(1));
1450 true, WebSocketFrameHeader::kOpCodeText
, AsVector("HELLO")));
1451 EXPECT_CALL(checkpoint
, Call(2));
1454 CreateChannelAndConnectSuccessfully();
1456 base::MessageLoop::current()->RunUntilIdle();
1460 // Extra data can arrive while a read is being processed, resulting in the next
1461 // read completing synchronously.
1462 TEST_F(WebSocketChannelEventInterfaceTest
, AsyncThenSyncRead
) {
1463 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1464 new ReadableFakeWebSocketStream
);
1465 static const InitFrame frames1
[] = {
1466 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1467 static const InitFrame frames2
[] = {
1468 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "WORLD"}};
1469 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames1
);
1470 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames2
);
1471 set_stream(stream
.Pass());
1474 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1475 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1479 true, WebSocketFrameHeader::kOpCodeText
, AsVector("HELLO")));
1483 true, WebSocketFrameHeader::kOpCodeText
, AsVector("WORLD")));
1486 CreateChannelAndConnectSuccessfully();
1487 base::MessageLoop::current()->RunUntilIdle();
1490 // Data frames are delivered the same regardless of how many reads they arrive
1492 TEST_F(WebSocketChannelEventInterfaceTest
, FragmentedMessage
) {
1493 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1494 new ReadableFakeWebSocketStream
);
1495 // Here we have one message which arrived in five frames split across three
1496 // reads. It may have been reframed on arrival, but this class doesn't care
1498 static const InitFrame frames1
[] = {
1499 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "THREE"},
1500 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
1502 static const InitFrame frames2
[] = {
1503 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
1504 NOT_MASKED
, "SMALL"}};
1505 static const InitFrame frames3
[] = {
1506 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
1508 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
1509 NOT_MASKED
, "FRAMES"}};
1510 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames1
);
1511 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames2
);
1512 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames3
);
1513 set_stream(stream
.Pass());
1516 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1517 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1521 false, WebSocketFrameHeader::kOpCodeText
, AsVector("THREE")));
1525 false, WebSocketFrameHeader::kOpCodeContinuation
, AsVector(" ")));
1526 EXPECT_CALL(*event_interface_
,
1528 WebSocketFrameHeader::kOpCodeContinuation
,
1529 AsVector("SMALL")));
1533 false, WebSocketFrameHeader::kOpCodeContinuation
, AsVector(" ")));
1534 EXPECT_CALL(*event_interface_
,
1536 WebSocketFrameHeader::kOpCodeContinuation
,
1537 AsVector("FRAMES")));
1540 CreateChannelAndConnectSuccessfully();
1541 base::MessageLoop::current()->RunUntilIdle();
1544 // A message can consist of one frame with NULL payload.
1545 TEST_F(WebSocketChannelEventInterfaceTest
, NullMessage
) {
1546 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1547 new ReadableFakeWebSocketStream
);
1548 static const InitFrame frames
[] = {
1549 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, NULL
}};
1550 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1551 set_stream(stream
.Pass());
1552 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1553 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1556 OnDataFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("")));
1557 CreateChannelAndConnectSuccessfully();
1560 // Connection closed by the remote host without a closing handshake.
1561 TEST_F(WebSocketChannelEventInterfaceTest
, AsyncAbnormalClosure
) {
1562 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1563 new ReadableFakeWebSocketStream
);
1564 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC
,
1565 ERR_CONNECTION_CLOSED
);
1566 set_stream(stream
.Pass());
1569 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1570 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1571 EXPECT_CALL(*event_interface_
,
1572 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, _
));
1575 CreateChannelAndConnectSuccessfully();
1576 base::MessageLoop::current()->RunUntilIdle();
1579 // A connection reset should produce the same event as an unexpected closure.
1580 TEST_F(WebSocketChannelEventInterfaceTest
, ConnectionReset
) {
1581 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1582 new ReadableFakeWebSocketStream
);
1583 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC
,
1584 ERR_CONNECTION_RESET
);
1585 set_stream(stream
.Pass());
1588 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1589 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1590 EXPECT_CALL(*event_interface_
,
1591 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, _
));
1594 CreateChannelAndConnectSuccessfully();
1595 base::MessageLoop::current()->RunUntilIdle();
1598 // RFC6455 5.1 "A client MUST close a connection if it detects a masked frame."
1599 TEST_F(WebSocketChannelEventInterfaceTest
, MaskedFramesAreRejected
) {
1600 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1601 new ReadableFakeWebSocketStream
);
1602 static const InitFrame frames
[] = {
1603 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "HELLO"}};
1605 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1606 set_stream(stream
.Pass());
1609 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1610 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1614 "A server must not mask any frames that it sends to the client."));
1617 CreateChannelAndConnectSuccessfully();
1618 base::MessageLoop::current()->RunUntilIdle();
1621 // RFC6455 5.2 "If an unknown opcode is received, the receiving endpoint MUST
1622 // _Fail the WebSocket Connection_."
1623 TEST_F(WebSocketChannelEventInterfaceTest
, UnknownOpCodeIsRejected
) {
1624 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1625 new ReadableFakeWebSocketStream
);
1626 static const InitFrame frames
[] = {{FINAL_FRAME
, 4, NOT_MASKED
, "HELLO"}};
1628 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1629 set_stream(stream
.Pass());
1632 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1633 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1634 EXPECT_CALL(*event_interface_
,
1635 OnFailChannel("Unrecognized frame opcode: 4"));
1638 CreateChannelAndConnectSuccessfully();
1639 base::MessageLoop::current()->RunUntilIdle();
1642 // RFC6455 5.4 "Control frames ... MAY be injected in the middle of a
1643 // fragmented message."
1644 TEST_F(WebSocketChannelEventInterfaceTest
, ControlFrameInDataMessage
) {
1645 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1646 new ReadableFakeWebSocketStream
);
1647 // We have one message of type Text split into two frames. In the middle is a
1648 // control message of type Pong.
1649 static const InitFrame frames1
[] = {
1650 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
1651 NOT_MASKED
, "SPLIT "}};
1652 static const InitFrame frames2
[] = {
1653 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
, NOT_MASKED
, ""}};
1654 static const InitFrame frames3
[] = {
1655 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
1656 NOT_MASKED
, "MESSAGE"}};
1657 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames1
);
1658 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames2
);
1659 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames3
);
1660 set_stream(stream
.Pass());
1663 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1664 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1668 false, WebSocketFrameHeader::kOpCodeText
, AsVector("SPLIT ")));
1669 EXPECT_CALL(*event_interface_
,
1671 WebSocketFrameHeader::kOpCodeContinuation
,
1672 AsVector("MESSAGE")));
1675 CreateChannelAndConnectSuccessfully();
1676 base::MessageLoop::current()->RunUntilIdle();
1679 // It seems redundant to repeat the entirety of the above test, so just test a
1680 // Pong with NULL data.
1681 TEST_F(WebSocketChannelEventInterfaceTest
, PongWithNullData
) {
1682 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1683 new ReadableFakeWebSocketStream
);
1684 static const InitFrame frames
[] = {
1685 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
, NOT_MASKED
, NULL
}};
1686 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1687 set_stream(stream
.Pass());
1688 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1689 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1691 CreateChannelAndConnectSuccessfully();
1692 base::MessageLoop::current()->RunUntilIdle();
1695 // If a frame has an invalid header, then the connection is closed and
1696 // subsequent frames must not trigger events.
1697 TEST_F(WebSocketChannelEventInterfaceTest
, FrameAfterInvalidFrame
) {
1698 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1699 new ReadableFakeWebSocketStream
);
1700 static const InitFrame frames
[] = {
1701 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "HELLO"},
1702 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, " WORLD"}};
1704 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1705 set_stream(stream
.Pass());
1708 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1709 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1713 "A server must not mask any frames that it sends to the client."));
1716 CreateChannelAndConnectSuccessfully();
1717 base::MessageLoop::current()->RunUntilIdle();
1720 // If the renderer sends lots of small writes, we don't want to update the quota
1722 TEST_F(WebSocketChannelEventInterfaceTest
, SmallWriteDoesntUpdateQuota
) {
1723 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
1726 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1727 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1730 CreateChannelAndConnectSuccessfully();
1731 channel_
->SendFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("B"));
1734 // If we send enough to go below send_quota_low_water_mask_ we should get our
1736 TEST_F(WebSocketChannelEventInterfaceTest
, LargeWriteUpdatesQuota
) {
1737 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
1738 // We use this checkpoint object to verify that the quota update comes after
1740 Checkpoint checkpoint
;
1743 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1744 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1745 EXPECT_CALL(checkpoint
, Call(1));
1746 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1747 EXPECT_CALL(checkpoint
, Call(2));
1750 CreateChannelAndConnectSuccessfully();
1752 channel_
->SendFrame(true,
1753 WebSocketFrameHeader::kOpCodeText
,
1754 std::vector
<char>(kDefaultInitialQuota
, 'B'));
1758 // Verify that our quota actually is refreshed when we are told it is.
1759 TEST_F(WebSocketChannelEventInterfaceTest
, QuotaReallyIsRefreshed
) {
1760 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
1761 Checkpoint checkpoint
;
1764 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1765 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1766 EXPECT_CALL(checkpoint
, Call(1));
1767 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1768 EXPECT_CALL(checkpoint
, Call(2));
1769 // If quota was not really refreshed, we would get an OnDropChannel()
1771 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1772 EXPECT_CALL(checkpoint
, Call(3));
1775 CreateChannelAndConnectSuccessfully();
1777 channel_
->SendFrame(true,
1778 WebSocketFrameHeader::kOpCodeText
,
1779 std::vector
<char>(kDefaultQuotaRefreshTrigger
, 'D'));
1781 // We should have received more quota at this point.
1782 channel_
->SendFrame(true,
1783 WebSocketFrameHeader::kOpCodeText
,
1784 std::vector
<char>(kDefaultQuotaRefreshTrigger
, 'E'));
1788 // If we send more than the available quota then the connection will be closed
1790 TEST_F(WebSocketChannelEventInterfaceTest
, WriteOverQuotaIsRejected
) {
1791 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
1794 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1795 EXPECT_CALL(*event_interface_
, OnFlowControl(kDefaultInitialQuota
));
1796 EXPECT_CALL(*event_interface_
, OnFailChannel("Send quota exceeded"));
1799 CreateChannelAndConnectSuccessfully();
1800 channel_
->SendFrame(true,
1801 WebSocketFrameHeader::kOpCodeText
,
1802 std::vector
<char>(kDefaultInitialQuota
+ 1, 'C'));
1805 // If a write fails, the channel is dropped.
1806 TEST_F(WebSocketChannelEventInterfaceTest
, FailedWrite
) {
1807 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream
));
1808 Checkpoint checkpoint
;
1811 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1812 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1813 EXPECT_CALL(checkpoint
, Call(1));
1814 EXPECT_CALL(*event_interface_
,
1815 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, _
));
1816 EXPECT_CALL(checkpoint
, Call(2));
1819 CreateChannelAndConnectSuccessfully();
1822 channel_
->SendFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("H"));
1826 // OnDropChannel() is called exactly once when StartClosingHandshake() is used.
1827 TEST_F(WebSocketChannelEventInterfaceTest
, SendCloseDropsChannel
) {
1828 set_stream(make_scoped_ptr(new EchoeyFakeWebSocketStream
));
1831 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1832 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1833 EXPECT_CALL(*event_interface_
,
1834 OnDropChannel(true, kWebSocketNormalClosure
, "Fred"));
1837 CreateChannelAndConnectSuccessfully();
1839 channel_
->StartClosingHandshake(kWebSocketNormalClosure
, "Fred");
1840 base::MessageLoop::current()->RunUntilIdle();
1843 // StartClosingHandshake() also works before connection completes, and calls
1845 TEST_F(WebSocketChannelEventInterfaceTest
, CloseDuringConnection
) {
1846 EXPECT_CALL(*event_interface_
,
1847 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, ""));
1849 CreateChannelAndConnect();
1850 channel_
->StartClosingHandshake(kWebSocketNormalClosure
, "Joe");
1853 // OnDropChannel() is only called once when a write() on the socket triggers a
1854 // connection reset.
1855 TEST_F(WebSocketChannelEventInterfaceTest
, OnDropChannelCalledOnce
) {
1856 set_stream(make_scoped_ptr(new ResetOnWriteFakeWebSocketStream
));
1857 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1858 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1860 EXPECT_CALL(*event_interface_
,
1861 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, ""))
1864 CreateChannelAndConnectSuccessfully();
1866 channel_
->SendFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("yt?"));
1867 base::MessageLoop::current()->RunUntilIdle();
1870 // When the remote server sends a Close frame with an empty payload,
1871 // WebSocketChannel should report code 1005, kWebSocketErrorNoStatusReceived.
1872 TEST_F(WebSocketChannelEventInterfaceTest
, CloseWithNoPayloadGivesStatus1005
) {
1873 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1874 new ReadableFakeWebSocketStream
);
1875 static const InitFrame frames
[] = {
1876 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
, ""}};
1877 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1878 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC
,
1879 ERR_CONNECTION_CLOSED
);
1880 set_stream(stream
.Pass());
1881 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1882 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1883 EXPECT_CALL(*event_interface_
, OnClosingHandshake());
1884 EXPECT_CALL(*event_interface_
,
1885 OnDropChannel(true, kWebSocketErrorNoStatusReceived
, _
));
1887 CreateChannelAndConnectSuccessfully();
1890 // A version of the above test with NULL payload.
1891 TEST_F(WebSocketChannelEventInterfaceTest
,
1892 CloseWithNullPayloadGivesStatus1005
) {
1893 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1894 new ReadableFakeWebSocketStream
);
1895 static const InitFrame frames
[] = {
1896 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
, NULL
}};
1897 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1898 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC
,
1899 ERR_CONNECTION_CLOSED
);
1900 set_stream(stream
.Pass());
1901 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1902 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1903 EXPECT_CALL(*event_interface_
, OnClosingHandshake());
1904 EXPECT_CALL(*event_interface_
,
1905 OnDropChannel(true, kWebSocketErrorNoStatusReceived
, _
));
1907 CreateChannelAndConnectSuccessfully();
1910 // If ReadFrames() returns ERR_WS_PROTOCOL_ERROR, then the connection must be
1912 TEST_F(WebSocketChannelEventInterfaceTest
, SyncProtocolErrorGivesStatus1002
) {
1913 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1914 new ReadableFakeWebSocketStream
);
1915 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC
,
1916 ERR_WS_PROTOCOL_ERROR
);
1917 set_stream(stream
.Pass());
1918 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1919 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1921 EXPECT_CALL(*event_interface_
, OnFailChannel("Invalid frame header"));
1923 CreateChannelAndConnectSuccessfully();
1926 // Async version of above test.
1927 TEST_F(WebSocketChannelEventInterfaceTest
, AsyncProtocolErrorGivesStatus1002
) {
1928 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1929 new ReadableFakeWebSocketStream
);
1930 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC
,
1931 ERR_WS_PROTOCOL_ERROR
);
1932 set_stream(stream
.Pass());
1933 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1934 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1936 EXPECT_CALL(*event_interface_
, OnFailChannel("Invalid frame header"));
1938 CreateChannelAndConnectSuccessfully();
1939 base::MessageLoop::current()->RunUntilIdle();
1942 TEST_F(WebSocketChannelEventInterfaceTest
, StartHandshakeRequest
) {
1945 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1946 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1947 EXPECT_CALL(*event_interface_
, OnStartOpeningHandshakeCalled());
1950 CreateChannelAndConnectSuccessfully();
1952 scoped_ptr
<WebSocketHandshakeRequestInfo
> request_info(
1953 new WebSocketHandshakeRequestInfo(GURL("ws://www.example.com/"),
1955 connect_data_
.creator
.connect_delegate
->OnStartOpeningHandshake(
1956 request_info
.Pass());
1958 base::MessageLoop::current()->RunUntilIdle();
1961 TEST_F(WebSocketChannelEventInterfaceTest
, FinishHandshakeRequest
) {
1964 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
1965 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1966 EXPECT_CALL(*event_interface_
, OnFinishOpeningHandshakeCalled());
1969 CreateChannelAndConnectSuccessfully();
1971 scoped_refptr
<HttpResponseHeaders
> response_headers(
1972 new HttpResponseHeaders(""));
1973 scoped_ptr
<WebSocketHandshakeResponseInfo
> response_info(
1974 new WebSocketHandshakeResponseInfo(GURL("ws://www.example.com/"),
1979 connect_data_
.creator
.connect_delegate
->OnFinishOpeningHandshake(
1980 response_info
.Pass());
1981 base::MessageLoop::current()->RunUntilIdle();
1984 TEST_F(WebSocketChannelEventInterfaceTest
, FailJustAfterHandshake
) {
1987 EXPECT_CALL(*event_interface_
, OnStartOpeningHandshakeCalled());
1988 EXPECT_CALL(*event_interface_
, OnFinishOpeningHandshakeCalled());
1989 EXPECT_CALL(*event_interface_
, OnFailChannel("bye"));
1992 CreateChannelAndConnect();
1994 WebSocketStream::ConnectDelegate
* connect_delegate
=
1995 connect_data_
.creator
.connect_delegate
.get();
1996 GURL
url("ws://www.example.com/");
1997 scoped_ptr
<WebSocketHandshakeRequestInfo
> request_info(
1998 new WebSocketHandshakeRequestInfo(url
, base::Time()));
1999 scoped_refptr
<HttpResponseHeaders
> response_headers(
2000 new HttpResponseHeaders(""));
2001 scoped_ptr
<WebSocketHandshakeResponseInfo
> response_info(
2002 new WebSocketHandshakeResponseInfo(url
,
2007 connect_delegate
->OnStartOpeningHandshake(request_info
.Pass());
2008 connect_delegate
->OnFinishOpeningHandshake(response_info
.Pass());
2010 connect_delegate
->OnFailure("bye");
2011 base::MessageLoop::current()->RunUntilIdle();
2014 // Any frame after close is invalid. This test uses a Text frame. See also
2015 // test "PingAfterCloseIfRejected".
2016 TEST_F(WebSocketChannelEventInterfaceTest
, DataAfterCloseIsRejected
) {
2017 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2018 new ReadableFakeWebSocketStream
);
2019 static const InitFrame frames
[] = {
2020 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
,
2021 CLOSE_DATA(NORMAL_CLOSURE
, "OK")},
2022 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "Payload"}};
2023 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2024 set_stream(stream
.Pass());
2025 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2026 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2030 EXPECT_CALL(*event_interface_
, OnClosingHandshake());
2031 EXPECT_CALL(*event_interface_
,
2032 OnFailChannel("Data frame received after close"));
2035 CreateChannelAndConnectSuccessfully();
2038 // A Close frame with a one-byte payload elicits a specific console error
2040 TEST_F(WebSocketChannelEventInterfaceTest
, OneByteClosePayloadMessage
) {
2041 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2042 new ReadableFakeWebSocketStream
);
2043 static const InitFrame frames
[] = {
2044 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
, "\x03"}};
2045 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2046 set_stream(stream
.Pass());
2047 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2048 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2052 "Received a broken close frame containing an invalid size body."));
2054 CreateChannelAndConnectSuccessfully();
2057 // A Close frame with a reserved status code also elicits a specific console
2059 TEST_F(WebSocketChannelEventInterfaceTest
, ClosePayloadReservedStatusMessage
) {
2060 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2061 new ReadableFakeWebSocketStream
);
2062 static const InitFrame frames
[] = {
2063 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2064 NOT_MASKED
, CLOSE_DATA(ABNORMAL_CLOSURE
, "Not valid on wire")}};
2065 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2066 set_stream(stream
.Pass());
2067 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2068 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2072 "Received a broken close frame containing a reserved status code."));
2074 CreateChannelAndConnectSuccessfully();
2077 // A Close frame with invalid UTF-8 also elicits a specific console error
2079 TEST_F(WebSocketChannelEventInterfaceTest
, ClosePayloadInvalidReason
) {
2080 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2081 new ReadableFakeWebSocketStream
);
2082 static const InitFrame frames
[] = {
2083 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2084 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "\xFF")}};
2085 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2086 set_stream(stream
.Pass());
2087 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2088 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2092 "Received a broken close frame containing invalid UTF-8."));
2094 CreateChannelAndConnectSuccessfully();
2097 // The reserved bits must all be clear on received frames. Extensions should
2098 // clear the bits when they are set correctly before passing on the frame.
2099 TEST_F(WebSocketChannelEventInterfaceTest
, ReservedBitsMustNotBeSet
) {
2100 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2101 new ReadableFakeWebSocketStream
);
2102 static const InitFrame frames
[] = {
2103 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
2104 NOT_MASKED
, "sakana"}};
2105 // It is not worth adding support for reserved bits to InitFrame just for this
2106 // one test, so set the bit manually.
2107 ScopedVector
<WebSocketFrame
> raw_frames
= CreateFrameVector(frames
);
2108 raw_frames
[0]->header
.reserved1
= true;
2109 stream
->PrepareRawReadFrames(
2110 ReadableFakeWebSocketStream::SYNC
, OK
, raw_frames
.Pass());
2111 set_stream(stream
.Pass());
2112 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2113 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2114 EXPECT_CALL(*event_interface_
,
2116 "One or more reserved bits are on: reserved1 = 1, "
2117 "reserved2 = 0, reserved3 = 0"));
2119 CreateChannelAndConnectSuccessfully();
2122 // The closing handshake times out and sends an OnDropChannel event if no
2123 // response to the client Close message is received.
2124 TEST_F(WebSocketChannelEventInterfaceTest
,
2125 ClientInitiatedClosingHandshakeTimesOut
) {
2126 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2127 new ReadableFakeWebSocketStream
);
2128 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC
,
2130 set_stream(stream
.Pass());
2131 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2132 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2133 // This checkpoint object verifies that the OnDropChannel message comes after
2135 Checkpoint checkpoint
;
2136 TestClosure completion
;
2139 EXPECT_CALL(checkpoint
, Call(1));
2140 EXPECT_CALL(*event_interface_
,
2141 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, _
))
2142 .WillOnce(InvokeClosureReturnDeleted(completion
.closure()));
2144 CreateChannelAndConnectSuccessfully();
2145 // OneShotTimer is not very friendly to testing; there is no apparent way to
2146 // set an expectation on it. Instead the tests need to infer that the timeout
2147 // was fired by the behaviour of the WebSocketChannel object.
2148 channel_
->SetClosingHandshakeTimeoutForTesting(
2149 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis
));
2150 channel_
->SetUnderlyingConnectionCloseTimeoutForTesting(
2151 TimeDelta::FromMilliseconds(kVeryBigTimeoutMillis
));
2152 channel_
->StartClosingHandshake(kWebSocketNormalClosure
, "");
2154 completion
.WaitForResult();
2157 // The closing handshake times out and sends an OnDropChannel event if a Close
2158 // message is received but the connection isn't closed by the remote host.
2159 TEST_F(WebSocketChannelEventInterfaceTest
,
2160 ServerInitiatedClosingHandshakeTimesOut
) {
2161 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2162 new ReadableFakeWebSocketStream
);
2163 static const InitFrame frames
[] = {
2164 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2165 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
2166 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
2167 set_stream(stream
.Pass());
2168 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2169 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2170 Checkpoint checkpoint
;
2171 TestClosure completion
;
2174 EXPECT_CALL(checkpoint
, Call(1));
2175 EXPECT_CALL(*event_interface_
, OnClosingHandshake());
2176 EXPECT_CALL(*event_interface_
,
2177 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, _
))
2178 .WillOnce(InvokeClosureReturnDeleted(completion
.closure()));
2180 CreateChannelAndConnectSuccessfully();
2181 channel_
->SetClosingHandshakeTimeoutForTesting(
2182 TimeDelta::FromMilliseconds(kVeryBigTimeoutMillis
));
2183 channel_
->SetUnderlyingConnectionCloseTimeoutForTesting(
2184 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis
));
2186 completion
.WaitForResult();
2189 // The renderer should provide us with some quota immediately, and then
2190 // WebSocketChannel calls ReadFrames as soon as the stream is available.
2191 TEST_F(WebSocketChannelStreamTest
, FlowControlEarly
) {
2192 Checkpoint checkpoint
;
2193 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2194 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2197 EXPECT_CALL(checkpoint
, Call(1));
2198 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2199 .WillOnce(Return(ERR_IO_PENDING
));
2200 EXPECT_CALL(checkpoint
, Call(2));
2203 set_stream(mock_stream_
.Pass());
2204 CreateChannelAndConnect();
2205 channel_
->SendFlowControl(kPlentyOfQuota
);
2207 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
2211 // If for some reason the connect succeeds before the renderer sends us quota,
2212 // we shouldn't call ReadFrames() immediately.
2213 // TODO(ricea): Actually we should call ReadFrames() with a small limit so we
2214 // can still handle control frames. This should be done once we have any API to
2215 // expose quota to the lower levels.
2216 TEST_F(WebSocketChannelStreamTest
, FlowControlLate
) {
2217 Checkpoint checkpoint
;
2218 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2219 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2222 EXPECT_CALL(checkpoint
, Call(1));
2223 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2224 .WillOnce(Return(ERR_IO_PENDING
));
2225 EXPECT_CALL(checkpoint
, Call(2));
2228 set_stream(mock_stream_
.Pass());
2229 CreateChannelAndConnect();
2230 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
2232 channel_
->SendFlowControl(kPlentyOfQuota
);
2236 // We should stop calling ReadFrames() when all quota is used.
2237 TEST_F(WebSocketChannelStreamTest
, FlowControlStopsReadFrames
) {
2238 static const InitFrame frames
[] = {
2239 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "FOUR"}};
2241 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2242 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2243 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2244 .WillOnce(ReturnFrames(&frames
));
2246 set_stream(mock_stream_
.Pass());
2247 CreateChannelAndConnect();
2248 channel_
->SendFlowControl(4);
2249 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
2252 // Providing extra quota causes ReadFrames() to be called again.
2253 TEST_F(WebSocketChannelStreamTest
, FlowControlStartsWithMoreQuota
) {
2254 static const InitFrame frames
[] = {
2255 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "FOUR"}};
2256 Checkpoint checkpoint
;
2258 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2259 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2262 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2263 .WillOnce(ReturnFrames(&frames
));
2264 EXPECT_CALL(checkpoint
, Call(1));
2265 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2266 .WillOnce(Return(ERR_IO_PENDING
));
2269 set_stream(mock_stream_
.Pass());
2270 CreateChannelAndConnect();
2271 channel_
->SendFlowControl(4);
2272 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
2274 channel_
->SendFlowControl(4);
2277 // ReadFrames() isn't called again until all pending data has been passed to
2279 TEST_F(WebSocketChannelStreamTest
, ReadFramesNotCalledUntilQuotaAvailable
) {
2280 static const InitFrame frames
[] = {
2281 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "FOUR"}};
2282 Checkpoint checkpoint
;
2284 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2285 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2288 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2289 .WillOnce(ReturnFrames(&frames
));
2290 EXPECT_CALL(checkpoint
, Call(1));
2291 EXPECT_CALL(checkpoint
, Call(2));
2292 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2293 .WillOnce(Return(ERR_IO_PENDING
));
2296 set_stream(mock_stream_
.Pass());
2297 CreateChannelAndConnect();
2298 channel_
->SendFlowControl(2);
2299 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
2301 channel_
->SendFlowControl(2);
2303 channel_
->SendFlowControl(2);
2306 // A message that needs to be split into frames to fit within quota should
2307 // maintain correct semantics.
2308 TEST_F(WebSocketChannelFlowControlTest
, SingleFrameMessageSplitSync
) {
2309 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2310 new ReadableFakeWebSocketStream
);
2311 static const InitFrame frames
[] = {
2312 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "FOUR"}};
2313 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2314 set_stream(stream
.Pass());
2317 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2318 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2321 OnDataFrame(false, WebSocketFrameHeader::kOpCodeText
, AsVector("FO")));
2325 false, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("U")));
2329 true, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("R")));
2332 CreateChannelAndConnectWithQuota(2);
2333 channel_
->SendFlowControl(1);
2334 channel_
->SendFlowControl(1);
2337 // The code path for async messages is slightly different, so test it
2339 TEST_F(WebSocketChannelFlowControlTest
, SingleFrameMessageSplitAsync
) {
2340 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2341 new ReadableFakeWebSocketStream
);
2342 static const InitFrame frames
[] = {
2343 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "FOUR"}};
2344 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
2345 set_stream(stream
.Pass());
2346 Checkpoint checkpoint
;
2349 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2350 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2351 EXPECT_CALL(checkpoint
, Call(1));
2354 OnDataFrame(false, WebSocketFrameHeader::kOpCodeText
, AsVector("FO")));
2355 EXPECT_CALL(checkpoint
, Call(2));
2359 false, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("U")));
2360 EXPECT_CALL(checkpoint
, Call(3));
2364 true, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("R")));
2367 CreateChannelAndConnectWithQuota(2);
2369 base::MessageLoop::current()->RunUntilIdle();
2371 channel_
->SendFlowControl(1);
2373 channel_
->SendFlowControl(1);
2376 // A message split into multiple frames which is further split due to quota
2377 // restrictions should stil be correct.
2378 // TODO(ricea): The message ends up split into more frames than are strictly
2379 // necessary. The complexity/performance tradeoffs here need further
2381 TEST_F(WebSocketChannelFlowControlTest
, MultipleFrameSplit
) {
2382 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2383 new ReadableFakeWebSocketStream
);
2384 static const InitFrame frames
[] = {
2385 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
2386 NOT_MASKED
, "FIRST FRAME IS 25 BYTES. "},
2387 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
2388 NOT_MASKED
, "SECOND FRAME IS 26 BYTES. "},
2389 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
2390 NOT_MASKED
, "FINAL FRAME IS 24 BYTES."}};
2391 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2392 set_stream(stream
.Pass());
2395 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2396 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2397 EXPECT_CALL(*event_interface_
,
2399 WebSocketFrameHeader::kOpCodeText
,
2400 AsVector("FIRST FRAME IS")));
2401 EXPECT_CALL(*event_interface_
,
2403 WebSocketFrameHeader::kOpCodeContinuation
,
2404 AsVector(" 25 BYTES. ")));
2405 EXPECT_CALL(*event_interface_
,
2407 WebSocketFrameHeader::kOpCodeContinuation
,
2408 AsVector("SECOND FRAME IS 26 BYTES. ")));
2409 EXPECT_CALL(*event_interface_
,
2411 WebSocketFrameHeader::kOpCodeContinuation
,
2412 AsVector("FINAL ")));
2413 EXPECT_CALL(*event_interface_
,
2415 WebSocketFrameHeader::kOpCodeContinuation
,
2416 AsVector("FRAME IS 24 BYTES.")));
2418 CreateChannelAndConnectWithQuota(14);
2419 channel_
->SendFlowControl(43);
2420 channel_
->SendFlowControl(32);
2423 // An empty message handled when we are out of quota must not be delivered
2424 // out-of-order with respect to other messages.
2425 TEST_F(WebSocketChannelFlowControlTest
, EmptyMessageNoQuota
) {
2426 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2427 new ReadableFakeWebSocketStream
);
2428 static const InitFrame frames
[] = {
2429 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
2430 NOT_MASKED
, "FIRST MESSAGE"},
2431 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
2433 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
2434 NOT_MASKED
, "THIRD MESSAGE"}};
2435 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2436 set_stream(stream
.Pass());
2439 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2440 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2441 EXPECT_CALL(*event_interface_
,
2443 WebSocketFrameHeader::kOpCodeText
,
2444 AsVector("FIRST ")));
2445 EXPECT_CALL(*event_interface_
,
2447 WebSocketFrameHeader::kOpCodeContinuation
,
2448 AsVector("MESSAGE")));
2449 EXPECT_CALL(*event_interface_
,
2451 WebSocketFrameHeader::kOpCodeText
,
2453 EXPECT_CALL(*event_interface_
,
2455 WebSocketFrameHeader::kOpCodeText
,
2456 AsVector("THIRD MESSAGE")));
2459 CreateChannelAndConnectWithQuota(6);
2460 channel_
->SendFlowControl(128);
2463 // RFC6455 5.1 "a client MUST mask all frames that it sends to the server".
2464 // WebSocketChannel actually only sets the mask bit in the header, it doesn't
2465 // perform masking itself (not all transports actually use masking).
2466 TEST_F(WebSocketChannelStreamTest
, SentFramesAreMasked
) {
2467 static const InitFrame expected
[] = {
2468 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
2469 MASKED
, "NEEDS MASKING"}};
2470 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2471 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2472 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
)).WillOnce(Return(ERR_IO_PENDING
));
2473 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2474 .WillOnce(Return(OK
));
2476 CreateChannelAndConnectSuccessfully();
2477 channel_
->SendFrame(
2478 true, WebSocketFrameHeader::kOpCodeText
, AsVector("NEEDS MASKING"));
2481 // RFC6455 5.5.1 "The application MUST NOT send any more data frames after
2482 // sending a Close frame."
2483 TEST_F(WebSocketChannelStreamTest
, NothingIsSentAfterClose
) {
2484 static const InitFrame expected
[] = {
2485 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2486 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Success")}};
2487 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2488 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2489 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
)).WillOnce(Return(ERR_IO_PENDING
));
2490 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2491 .WillOnce(Return(OK
));
2493 CreateChannelAndConnectSuccessfully();
2494 channel_
->StartClosingHandshake(1000, "Success");
2495 channel_
->SendFrame(
2496 true, WebSocketFrameHeader::kOpCodeText
, AsVector("SHOULD BE IGNORED"));
2499 // RFC6455 5.5.1 "If an endpoint receives a Close frame and did not previously
2500 // send a Close frame, the endpoint MUST send a Close frame in response."
2501 TEST_F(WebSocketChannelStreamTest
, CloseIsEchoedBack
) {
2502 static const InitFrame frames
[] = {
2503 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2504 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Close")}};
2505 static const InitFrame expected
[] = {
2506 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2507 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Close")}};
2508 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2509 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2510 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2511 .WillOnce(ReturnFrames(&frames
))
2512 .WillRepeatedly(Return(ERR_IO_PENDING
));
2513 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2514 .WillOnce(Return(OK
));
2516 CreateChannelAndConnectSuccessfully();
2519 // The converse of the above case; after sending a Close frame, we should not
2520 // send another one.
2521 TEST_F(WebSocketChannelStreamTest
, CloseOnlySentOnce
) {
2522 static const InitFrame expected
[] = {
2523 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2524 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Close")}};
2525 static const InitFrame frames_init
[] = {
2526 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2527 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Close")}};
2529 // We store the parameters that were passed to ReadFrames() so that we can
2530 // call them explicitly later.
2531 CompletionCallback read_callback
;
2532 ScopedVector
<WebSocketFrame
>* frames
= NULL
;
2534 // These are not interesting.
2535 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2536 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2538 // Use a checkpoint to make the ordering of events clearer.
2539 Checkpoint checkpoint
;
2542 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2543 .WillOnce(DoAll(SaveArg
<0>(&frames
),
2544 SaveArg
<1>(&read_callback
),
2545 Return(ERR_IO_PENDING
)));
2546 EXPECT_CALL(checkpoint
, Call(1));
2547 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2548 .WillOnce(Return(OK
));
2549 EXPECT_CALL(checkpoint
, Call(2));
2550 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2551 .WillOnce(Return(ERR_IO_PENDING
));
2552 EXPECT_CALL(checkpoint
, Call(3));
2553 // WriteFrames() must not be called again. GoogleMock will ensure that the
2554 // test fails if it is.
2557 CreateChannelAndConnectSuccessfully();
2559 channel_
->StartClosingHandshake(kWebSocketNormalClosure
, "Close");
2562 *frames
= CreateFrameVector(frames_init
);
2563 read_callback
.Run(OK
);
2567 // Invalid close status codes should not be sent on the network.
2568 TEST_F(WebSocketChannelStreamTest
, InvalidCloseStatusCodeNotSent
) {
2569 static const InitFrame expected
[] = {
2570 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2571 MASKED
, CLOSE_DATA(SERVER_ERROR
, "")}};
2573 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2574 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2575 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2576 .WillOnce(Return(ERR_IO_PENDING
));
2578 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
));
2580 CreateChannelAndConnectSuccessfully();
2581 channel_
->StartClosingHandshake(999, "");
2584 // A Close frame with a reason longer than 123 bytes cannot be sent on the
2586 TEST_F(WebSocketChannelStreamTest
, LongCloseReasonNotSent
) {
2587 static const InitFrame expected
[] = {
2588 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2589 MASKED
, CLOSE_DATA(SERVER_ERROR
, "")}};
2591 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2592 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2593 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2594 .WillOnce(Return(ERR_IO_PENDING
));
2596 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
));
2598 CreateChannelAndConnectSuccessfully();
2599 channel_
->StartClosingHandshake(1000, std::string(124, 'A'));
2602 // We generate code 1005, kWebSocketErrorNoStatusReceived, when there is no
2603 // status in the Close message from the other side. Code 1005 is not allowed to
2604 // appear on the wire, so we should not echo it back. See test
2605 // CloseWithNoPayloadGivesStatus1005, above, for confirmation that code 1005 is
2606 // correctly generated internally.
2607 TEST_F(WebSocketChannelStreamTest
, Code1005IsNotEchoed
) {
2608 static const InitFrame frames
[] = {
2609 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
, ""}};
2610 static const InitFrame expected
[] = {
2611 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
, ""}};
2612 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2613 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2614 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2615 .WillOnce(ReturnFrames(&frames
))
2616 .WillRepeatedly(Return(ERR_IO_PENDING
));
2617 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2618 .WillOnce(Return(OK
));
2620 CreateChannelAndConnectSuccessfully();
2623 TEST_F(WebSocketChannelStreamTest
, Code1005IsNotEchoedNull
) {
2624 static const InitFrame frames
[] = {
2625 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
, NULL
}};
2626 static const InitFrame expected
[] = {
2627 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
, ""}};
2628 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2629 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2630 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2631 .WillOnce(ReturnFrames(&frames
))
2632 .WillRepeatedly(Return(ERR_IO_PENDING
));
2633 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2634 .WillOnce(Return(OK
));
2636 CreateChannelAndConnectSuccessfully();
2639 // Receiving an invalid UTF-8 payload in a Close frame causes us to fail the
2641 TEST_F(WebSocketChannelStreamTest
, CloseFrameInvalidUtf8
) {
2642 static const InitFrame frames
[] = {
2643 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2644 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "\xFF")}};
2645 static const InitFrame expected
[] = {
2646 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2647 MASKED
, CLOSE_DATA(PROTOCOL_ERROR
, "Invalid UTF-8 in Close frame")}};
2649 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2650 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2651 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2652 .WillOnce(ReturnFrames(&frames
))
2653 .WillRepeatedly(Return(ERR_IO_PENDING
));
2654 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2655 .WillOnce(Return(OK
));
2656 EXPECT_CALL(*mock_stream_
, Close());
2658 CreateChannelAndConnectSuccessfully();
2661 // RFC6455 5.5.2 "Upon receipt of a Ping frame, an endpoint MUST send a Pong
2662 // frame in response"
2663 // 5.5.3 "A Pong frame sent in response to a Ping frame must have identical
2664 // "Application data" as found in the message body of the Ping frame being
2666 TEST_F(WebSocketChannelStreamTest
, PingRepliedWithPong
) {
2667 static const InitFrame frames
[] = {
2668 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePing
,
2669 NOT_MASKED
, "Application data"}};
2670 static const InitFrame expected
[] = {
2671 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
,
2672 MASKED
, "Application data"}};
2673 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2674 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2675 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2676 .WillOnce(ReturnFrames(&frames
))
2677 .WillRepeatedly(Return(ERR_IO_PENDING
));
2678 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2679 .WillOnce(Return(OK
));
2681 CreateChannelAndConnectSuccessfully();
2684 // A ping with a NULL payload should be responded to with a Pong with a NULL
2686 TEST_F(WebSocketChannelStreamTest
, NullPingRepliedWithNullPong
) {
2687 static const InitFrame frames
[] = {
2688 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePing
, NOT_MASKED
, NULL
}};
2689 static const InitFrame expected
[] = {
2690 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
, MASKED
, NULL
}};
2691 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2692 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2693 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2694 .WillOnce(ReturnFrames(&frames
))
2695 .WillRepeatedly(Return(ERR_IO_PENDING
));
2696 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2697 .WillOnce(Return(OK
));
2699 CreateChannelAndConnectSuccessfully();
2702 TEST_F(WebSocketChannelStreamTest
, PongInTheMiddleOfDataMessage
) {
2703 static const InitFrame frames
[] = {
2704 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePing
,
2705 NOT_MASKED
, "Application data"}};
2706 static const InitFrame expected1
[] = {
2707 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "Hello "}};
2708 static const InitFrame expected2
[] = {
2709 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
,
2710 MASKED
, "Application data"}};
2711 static const InitFrame expected3
[] = {
2712 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
2714 ScopedVector
<WebSocketFrame
>* read_frames
;
2715 CompletionCallback read_callback
;
2716 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2717 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2718 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2719 .WillOnce(DoAll(SaveArg
<0>(&read_frames
),
2720 SaveArg
<1>(&read_callback
),
2721 Return(ERR_IO_PENDING
)))
2722 .WillRepeatedly(Return(ERR_IO_PENDING
));
2726 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected1
), _
))
2727 .WillOnce(Return(OK
));
2728 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected2
), _
))
2729 .WillOnce(Return(OK
));
2730 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected3
), _
))
2731 .WillOnce(Return(OK
));
2734 CreateChannelAndConnectSuccessfully();
2735 channel_
->SendFrame(
2736 false, WebSocketFrameHeader::kOpCodeText
, AsVector("Hello "));
2737 *read_frames
= CreateFrameVector(frames
);
2738 read_callback
.Run(OK
);
2739 channel_
->SendFrame(
2740 true, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("World"));
2743 // WriteFrames() may not be called until the previous write has completed.
2744 // WebSocketChannel must buffer writes that happen in the meantime.
2745 TEST_F(WebSocketChannelStreamTest
, WriteFramesOneAtATime
) {
2746 static const InitFrame expected1
[] = {
2747 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "Hello "}};
2748 static const InitFrame expected2
[] = {
2749 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "World"}};
2750 CompletionCallback write_callback
;
2751 Checkpoint checkpoint
;
2753 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2754 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2755 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
)).WillOnce(Return(ERR_IO_PENDING
));
2758 EXPECT_CALL(checkpoint
, Call(1));
2759 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected1
), _
))
2760 .WillOnce(DoAll(SaveArg
<1>(&write_callback
), Return(ERR_IO_PENDING
)));
2761 EXPECT_CALL(checkpoint
, Call(2));
2762 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected2
), _
))
2763 .WillOnce(Return(ERR_IO_PENDING
));
2764 EXPECT_CALL(checkpoint
, Call(3));
2767 CreateChannelAndConnectSuccessfully();
2769 channel_
->SendFrame(
2770 false, WebSocketFrameHeader::kOpCodeText
, AsVector("Hello "));
2771 channel_
->SendFrame(
2772 true, WebSocketFrameHeader::kOpCodeText
, AsVector("World"));
2774 write_callback
.Run(OK
);
2778 // WebSocketChannel must buffer frames while it is waiting for a write to
2779 // complete, and then send them in a single batch. The batching behaviour is
2780 // important to get good throughput in the "many small messages" case.
2781 TEST_F(WebSocketChannelStreamTest
, WaitingMessagesAreBatched
) {
2782 static const char input_letters
[] = "Hello";
2783 static const InitFrame expected1
[] = {
2784 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "H"}};
2785 static const InitFrame expected2
[] = {
2786 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "e"},
2787 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "l"},
2788 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "l"},
2789 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "o"}};
2790 CompletionCallback write_callback
;
2792 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2793 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2794 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
)).WillOnce(Return(ERR_IO_PENDING
));
2797 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected1
), _
))
2798 .WillOnce(DoAll(SaveArg
<1>(&write_callback
), Return(ERR_IO_PENDING
)));
2799 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected2
), _
))
2800 .WillOnce(Return(ERR_IO_PENDING
));
2803 CreateChannelAndConnectSuccessfully();
2804 for (size_t i
= 0; i
< strlen(input_letters
); ++i
) {
2805 channel_
->SendFrame(true,
2806 WebSocketFrameHeader::kOpCodeText
,
2807 std::vector
<char>(1, input_letters
[i
]));
2809 write_callback
.Run(OK
);
2812 // When the renderer sends more on a channel than it has quota for, we send the
2813 // remote server a kWebSocketErrorGoingAway error code.
2814 TEST_F(WebSocketChannelStreamTest
, SendGoingAwayOnRendererQuotaExceeded
) {
2815 static const InitFrame expected
[] = {
2816 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2817 MASKED
, CLOSE_DATA(GOING_AWAY
, "")}};
2818 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2819 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2820 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
)).WillOnce(Return(ERR_IO_PENDING
));
2821 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2822 .WillOnce(Return(OK
));
2823 EXPECT_CALL(*mock_stream_
, Close());
2825 CreateChannelAndConnectSuccessfully();
2826 channel_
->SendFrame(true,
2827 WebSocketFrameHeader::kOpCodeText
,
2828 std::vector
<char>(kDefaultInitialQuota
+ 1, 'C'));
2831 // For convenience, most of these tests use Text frames. However, the WebSocket
2832 // protocol also has Binary frames and those need to be 8-bit clean. For the
2833 // sake of completeness, this test verifies that they are.
2834 TEST_F(WebSocketChannelStreamTest
, WrittenBinaryFramesAre8BitClean
) {
2835 ScopedVector
<WebSocketFrame
>* frames
= NULL
;
2837 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2838 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2839 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
)).WillOnce(Return(ERR_IO_PENDING
));
2840 EXPECT_CALL(*mock_stream_
, WriteFrames(_
, _
))
2841 .WillOnce(DoAll(SaveArg
<0>(&frames
), Return(ERR_IO_PENDING
)));
2843 CreateChannelAndConnectSuccessfully();
2844 channel_
->SendFrame(
2846 WebSocketFrameHeader::kOpCodeBinary
,
2847 std::vector
<char>(kBinaryBlob
, kBinaryBlob
+ kBinaryBlobSize
));
2848 ASSERT_TRUE(frames
!= NULL
);
2849 ASSERT_EQ(1U, frames
->size());
2850 const WebSocketFrame
* out_frame
= (*frames
)[0];
2851 EXPECT_EQ(kBinaryBlobSize
, out_frame
->header
.payload_length
);
2852 ASSERT_TRUE(out_frame
->data
.get());
2853 EXPECT_EQ(0, memcmp(kBinaryBlob
, out_frame
->data
->data(), kBinaryBlobSize
));
2856 // Test the read path for 8-bit cleanliness as well.
2857 TEST_F(WebSocketChannelEventInterfaceTest
, ReadBinaryFramesAre8BitClean
) {
2858 scoped_ptr
<WebSocketFrame
> frame(
2859 new WebSocketFrame(WebSocketFrameHeader::kOpCodeBinary
));
2860 WebSocketFrameHeader
& frame_header
= frame
->header
;
2861 frame_header
.final
= true;
2862 frame_header
.payload_length
= kBinaryBlobSize
;
2863 frame
->data
= new IOBuffer(kBinaryBlobSize
);
2864 memcpy(frame
->data
->data(), kBinaryBlob
, kBinaryBlobSize
);
2865 ScopedVector
<WebSocketFrame
> frames
;
2866 frames
.push_back(frame
.release());
2867 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2868 new ReadableFakeWebSocketStream
);
2869 stream
->PrepareRawReadFrames(
2870 ReadableFakeWebSocketStream::SYNC
, OK
, frames
.Pass());
2871 set_stream(stream
.Pass());
2872 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2873 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2874 EXPECT_CALL(*event_interface_
,
2876 WebSocketFrameHeader::kOpCodeBinary
,
2877 std::vector
<char>(kBinaryBlob
,
2878 kBinaryBlob
+ kBinaryBlobSize
)));
2880 CreateChannelAndConnectSuccessfully();
2883 // Invalid UTF-8 is not permitted in Text frames.
2884 TEST_F(WebSocketChannelSendUtf8Test
, InvalidUtf8Rejected
) {
2887 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2889 CreateChannelAndConnectSuccessfully();
2891 channel_
->SendFrame(
2892 true, WebSocketFrameHeader::kOpCodeText
, AsVector("\xff"));
2895 // A Text message cannot end with a partial UTF-8 character.
2896 TEST_F(WebSocketChannelSendUtf8Test
, IncompleteCharacterInFinalFrame
) {
2899 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2901 CreateChannelAndConnectSuccessfully();
2903 channel_
->SendFrame(
2904 true, WebSocketFrameHeader::kOpCodeText
, AsVector("\xc2"));
2907 // A non-final Text frame may end with a partial UTF-8 character (compare to
2909 TEST_F(WebSocketChannelSendUtf8Test
, IncompleteCharacterInNonFinalFrame
) {
2910 CreateChannelAndConnectSuccessfully();
2912 channel_
->SendFrame(
2913 false, WebSocketFrameHeader::kOpCodeText
, AsVector("\xc2"));
2916 // UTF-8 parsing context must be retained between frames.
2917 TEST_F(WebSocketChannelSendUtf8Test
, ValidCharacterSplitBetweenFrames
) {
2918 CreateChannelAndConnectSuccessfully();
2920 channel_
->SendFrame(
2921 false, WebSocketFrameHeader::kOpCodeText
, AsVector("\xf1"));
2922 channel_
->SendFrame(true,
2923 WebSocketFrameHeader::kOpCodeContinuation
,
2924 AsVector("\x80\xa0\xbf"));
2927 // Similarly, an invalid character should be detected even if split.
2928 TEST_F(WebSocketChannelSendUtf8Test
, InvalidCharacterSplit
) {
2931 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2933 CreateChannelAndConnectSuccessfully();
2935 channel_
->SendFrame(
2936 false, WebSocketFrameHeader::kOpCodeText
, AsVector("\xe1"));
2937 channel_
->SendFrame(true,
2938 WebSocketFrameHeader::kOpCodeContinuation
,
2939 AsVector("\x80\xa0\xbf"));
2942 // An invalid character must be detected in continuation frames.
2943 TEST_F(WebSocketChannelSendUtf8Test
, InvalidByteInContinuation
) {
2946 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2948 CreateChannelAndConnectSuccessfully();
2950 channel_
->SendFrame(
2951 false, WebSocketFrameHeader::kOpCodeText
, AsVector("foo"));
2952 channel_
->SendFrame(
2953 false, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("bar"));
2954 channel_
->SendFrame(
2955 true, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("\xff"));
2958 // However, continuation frames of a Binary frame will not be tested for UTF-8
2960 TEST_F(WebSocketChannelSendUtf8Test
, BinaryContinuationNotChecked
) {
2961 CreateChannelAndConnectSuccessfully();
2963 channel_
->SendFrame(
2964 false, WebSocketFrameHeader::kOpCodeBinary
, AsVector("foo"));
2965 channel_
->SendFrame(
2966 false, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("bar"));
2967 channel_
->SendFrame(
2968 true, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("\xff"));
2971 // Multiple text messages can be validated without the validation state getting
2973 TEST_F(WebSocketChannelSendUtf8Test
, ValidateMultipleTextMessages
) {
2974 CreateChannelAndConnectSuccessfully();
2976 channel_
->SendFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("foo"));
2977 channel_
->SendFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("bar"));
2980 // UTF-8 validation is enforced on received Text frames.
2981 TEST_F(WebSocketChannelEventInterfaceTest
, ReceivedInvalidUtf8
) {
2982 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2983 new ReadableFakeWebSocketStream
);
2984 static const InitFrame frames
[] = {
2985 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xff"}};
2986 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2987 set_stream(stream
.Pass());
2989 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
2990 EXPECT_CALL(*event_interface_
, OnFlowControl(kDefaultInitialQuota
));
2991 EXPECT_CALL(*event_interface_
,
2992 OnFailChannel("Could not decode a text frame as UTF-8."));
2994 CreateChannelAndConnectSuccessfully();
2995 base::MessageLoop::current()->RunUntilIdle();
2998 // Invalid UTF-8 is not sent over the network.
2999 TEST_F(WebSocketChannelStreamTest
, InvalidUtf8TextFrameNotSent
) {
3000 static const InitFrame expected
[] = {{FINAL_FRAME
,
3001 WebSocketFrameHeader::kOpCodeClose
,
3002 MASKED
, CLOSE_DATA(GOING_AWAY
, "")}};
3003 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
3004 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
3005 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3006 .WillRepeatedly(Return(ERR_IO_PENDING
));
3007 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3008 .WillOnce(Return(OK
));
3009 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3011 CreateChannelAndConnectSuccessfully();
3013 channel_
->SendFrame(
3014 true, WebSocketFrameHeader::kOpCodeText
, AsVector("\xff"));
3017 // The rest of the tests for receiving invalid UTF-8 test the communication with
3018 // the server. Since there is only one code path, it would be redundant to
3019 // perform the same tests on the EventInterface as well.
3021 // If invalid UTF-8 is received in a Text frame, the connection is failed.
3022 TEST_F(WebSocketChannelReceiveUtf8Test
, InvalidTextFrameRejected
) {
3023 static const InitFrame frames
[] = {
3024 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xff"}};
3025 static const InitFrame expected
[] = {
3026 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
,
3027 CLOSE_DATA(PROTOCOL_ERROR
, "Invalid UTF-8 in text frame")}};
3030 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3031 .WillOnce(ReturnFrames(&frames
))
3032 .WillRepeatedly(Return(ERR_IO_PENDING
));
3033 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3034 .WillOnce(Return(OK
));
3035 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3038 CreateChannelAndConnectSuccessfully();
3041 // A received Text message is not permitted to end with a partial UTF-8
3043 TEST_F(WebSocketChannelReceiveUtf8Test
, IncompleteCharacterReceived
) {
3044 static const InitFrame frames
[] = {
3045 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xc2"}};
3046 static const InitFrame expected
[] = {
3047 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
,
3048 CLOSE_DATA(PROTOCOL_ERROR
, "Invalid UTF-8 in text frame")}};
3049 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3050 .WillOnce(ReturnFrames(&frames
))
3051 .WillRepeatedly(Return(ERR_IO_PENDING
));
3052 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3053 .WillOnce(Return(OK
));
3054 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3056 CreateChannelAndConnectSuccessfully();
3059 // However, a non-final Text frame may end with a partial UTF-8 character.
3060 TEST_F(WebSocketChannelReceiveUtf8Test
, IncompleteCharacterIncompleteMessage
) {
3061 static const InitFrame frames
[] = {
3062 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xc2"}};
3063 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3064 .WillOnce(ReturnFrames(&frames
))
3065 .WillRepeatedly(Return(ERR_IO_PENDING
));
3067 CreateChannelAndConnectSuccessfully();
3070 // However, it will become an error if it is followed by an empty final frame.
3071 TEST_F(WebSocketChannelReceiveUtf8Test
, TricksyIncompleteCharacter
) {
3072 static const InitFrame frames
[] = {
3073 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xc2"},
3074 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
, NOT_MASKED
, ""}};
3075 static const InitFrame expected
[] = {
3076 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
,
3077 CLOSE_DATA(PROTOCOL_ERROR
, "Invalid UTF-8 in text frame")}};
3078 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3079 .WillOnce(ReturnFrames(&frames
))
3080 .WillRepeatedly(Return(ERR_IO_PENDING
));
3081 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3082 .WillOnce(Return(OK
));
3083 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3085 CreateChannelAndConnectSuccessfully();
3088 // UTF-8 parsing context must be retained between received frames of the same
3090 TEST_F(WebSocketChannelReceiveUtf8Test
, ReceivedParsingContextRetained
) {
3091 static const InitFrame frames
[] = {
3092 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xf1"},
3093 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3094 NOT_MASKED
, "\x80\xa0\xbf"}};
3095 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3096 .WillOnce(ReturnFrames(&frames
))
3097 .WillRepeatedly(Return(ERR_IO_PENDING
));
3099 CreateChannelAndConnectSuccessfully();
3102 // An invalid character must be detected even if split between frames.
3103 TEST_F(WebSocketChannelReceiveUtf8Test
, SplitInvalidCharacterReceived
) {
3104 static const InitFrame frames
[] = {
3105 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xe1"},
3106 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3107 NOT_MASKED
, "\x80\xa0\xbf"}};
3108 static const InitFrame expected
[] = {
3109 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
,
3110 CLOSE_DATA(PROTOCOL_ERROR
, "Invalid UTF-8 in text frame")}};
3111 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3112 .WillOnce(ReturnFrames(&frames
))
3113 .WillRepeatedly(Return(ERR_IO_PENDING
));
3114 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3115 .WillOnce(Return(OK
));
3116 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3118 CreateChannelAndConnectSuccessfully();
3121 // An invalid character received in a continuation frame must be detected.
3122 TEST_F(WebSocketChannelReceiveUtf8Test
, InvalidReceivedIncontinuation
) {
3123 static const InitFrame frames
[] = {
3124 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "foo"},
3125 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3127 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3128 NOT_MASKED
, "\xff"}};
3129 static const InitFrame expected
[] = {
3130 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
,
3131 CLOSE_DATA(PROTOCOL_ERROR
, "Invalid UTF-8 in text frame")}};
3132 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3133 .WillOnce(ReturnFrames(&frames
))
3134 .WillRepeatedly(Return(ERR_IO_PENDING
));
3135 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3136 .WillOnce(Return(OK
));
3137 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3139 CreateChannelAndConnectSuccessfully();
3142 // Continuations of binary frames must not be tested for UTF-8 validity.
3143 TEST_F(WebSocketChannelReceiveUtf8Test
, ReceivedBinaryNotUtf8Tested
) {
3144 static const InitFrame frames
[] = {
3145 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeBinary
, NOT_MASKED
, "foo"},
3146 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3148 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3149 NOT_MASKED
, "\xff"}};
3150 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3151 .WillOnce(ReturnFrames(&frames
))
3152 .WillRepeatedly(Return(ERR_IO_PENDING
));
3154 CreateChannelAndConnectSuccessfully();
3157 // Multiple Text messages can be validated.
3158 TEST_F(WebSocketChannelReceiveUtf8Test
, ValidateMultipleReceived
) {
3159 static const InitFrame frames
[] = {
3160 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "foo"},
3161 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "bar"}};
3162 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3163 .WillOnce(ReturnFrames(&frames
))
3164 .WillRepeatedly(Return(ERR_IO_PENDING
));
3166 CreateChannelAndConnectSuccessfully();
3169 // A new data message cannot start in the middle of another data message.
3170 TEST_F(WebSocketChannelEventInterfaceTest
, BogusContinuation
) {
3171 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
3172 new ReadableFakeWebSocketStream
);
3173 static const InitFrame frames
[] = {
3174 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeBinary
,
3175 NOT_MASKED
, "frame1"},
3176 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
3177 NOT_MASKED
, "frame2"}};
3178 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
3179 set_stream(stream
.Pass());
3181 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
3182 EXPECT_CALL(*event_interface_
, OnFlowControl(kDefaultInitialQuota
));
3186 false, WebSocketFrameHeader::kOpCodeBinary
, AsVector("frame1")));
3190 "Received start of new message but previous message is unfinished."));
3192 CreateChannelAndConnectSuccessfully();
3195 // A new message cannot start with a Continuation frame.
3196 TEST_F(WebSocketChannelEventInterfaceTest
, MessageStartingWithContinuation
) {
3197 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
3198 new ReadableFakeWebSocketStream
);
3199 static const InitFrame frames
[] = {
3200 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3201 NOT_MASKED
, "continuation"}};
3202 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
3203 set_stream(stream
.Pass());
3205 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
3206 EXPECT_CALL(*event_interface_
, OnFlowControl(kDefaultInitialQuota
));
3207 EXPECT_CALL(*event_interface_
,
3208 OnFailChannel("Received unexpected continuation frame."));
3210 CreateChannelAndConnectSuccessfully();
3213 // A frame passed to the renderer must be either non-empty or have the final bit
3215 TEST_F(WebSocketChannelEventInterfaceTest
, DataFramesNonEmptyOrFinal
) {
3216 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
3217 new ReadableFakeWebSocketStream
);
3218 static const InitFrame frames
[] = {
3219 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, ""},
3220 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3222 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
, NOT_MASKED
, ""}};
3223 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
3224 set_stream(stream
.Pass());
3226 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(false, _
, _
));
3227 EXPECT_CALL(*event_interface_
, OnFlowControl(kDefaultInitialQuota
));
3230 OnDataFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("")));
3232 CreateChannelAndConnectSuccessfully();
3235 // Calls to OnSSLCertificateError() must be passed through to the event
3236 // interface with the correct URL attached.
3237 TEST_F(WebSocketChannelEventInterfaceTest
, OnSSLCertificateErrorCalled
) {
3238 const GURL
wss_url("wss://example.com/sslerror");
3239 connect_data_
.socket_url
= wss_url
;
3240 const SSLInfo ssl_info
;
3241 const bool fatal
= true;
3242 scoped_ptr
<WebSocketEventInterface::SSLErrorCallbacks
> fake_callbacks(
3243 new FakeSSLErrorCallbacks
);
3245 EXPECT_CALL(*event_interface_
,
3246 OnSSLCertificateErrorCalled(NotNull(), wss_url
, _
, fatal
));
3248 CreateChannelAndConnect();
3249 connect_data_
.creator
.connect_delegate
->OnSSLCertificateError(
3250 fake_callbacks
.Pass(), ssl_info
, fatal
);
3253 // If we receive another frame after Close, it is not valid. It is not
3254 // completely clear what behaviour is required from the standard in this case,
3255 // but the current implementation fails the connection. Since a Close has
3256 // already been sent, this just means closing the connection.
3257 TEST_F(WebSocketChannelStreamTest
, PingAfterCloseIsRejected
) {
3258 static const InitFrame frames
[] = {
3259 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3260 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")},
3261 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePing
,
3262 NOT_MASKED
, "Ping body"}};
3263 static const InitFrame expected
[] = {
3264 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3265 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
3266 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
3267 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
3268 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3269 .WillOnce(ReturnFrames(&frames
))
3270 .WillRepeatedly(Return(ERR_IO_PENDING
));
3272 // We only need to verify the relative order of WriteFrames() and
3273 // Close(). The current implementation calls WriteFrames() for the Close
3274 // frame before calling ReadFrames() again, but that is an implementation
3275 // detail and better not to consider required behaviour.
3277 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3278 .WillOnce(Return(OK
));
3279 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3282 CreateChannelAndConnectSuccessfully();
3285 // A protocol error from the remote server should result in a close frame with
3286 // status 1002, followed by the connection closing.
3287 TEST_F(WebSocketChannelStreamTest
, ProtocolError
) {
3288 static const InitFrame expected
[] = {
3289 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3290 MASKED
, CLOSE_DATA(PROTOCOL_ERROR
, "WebSocket Protocol Error")}};
3291 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
3292 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
3293 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3294 .WillOnce(Return(ERR_WS_PROTOCOL_ERROR
));
3295 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3296 .WillOnce(Return(OK
));
3297 EXPECT_CALL(*mock_stream_
, Close());
3299 CreateChannelAndConnectSuccessfully();
3302 // Set the closing handshake timeout to a very tiny value before connecting.
3303 class WebSocketChannelStreamTimeoutTest
: public WebSocketChannelStreamTest
{
3305 WebSocketChannelStreamTimeoutTest() {}
3307 void CreateChannelAndConnectSuccessfully() override
{
3308 set_stream(mock_stream_
.Pass());
3309 CreateChannelAndConnect();
3310 channel_
->SendFlowControl(kPlentyOfQuota
);
3311 channel_
->SetClosingHandshakeTimeoutForTesting(
3312 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis
));
3313 channel_
->SetUnderlyingConnectionCloseTimeoutForTesting(
3314 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis
));
3315 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
3319 // In this case the server initiates the closing handshake with a Close
3320 // message. WebSocketChannel responds with a matching Close message, and waits
3321 // for the server to close the TCP/IP connection. The server never closes the
3322 // connection, so the closing handshake times out and WebSocketChannel closes
3323 // the connection itself.
3324 TEST_F(WebSocketChannelStreamTimeoutTest
, ServerInitiatedCloseTimesOut
) {
3325 static const InitFrame frames
[] = {
3326 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3327 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
3328 static const InitFrame expected
[] = {
3329 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3330 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
3331 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
3332 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
3333 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3334 .WillOnce(ReturnFrames(&frames
))
3335 .WillRepeatedly(Return(ERR_IO_PENDING
));
3336 Checkpoint checkpoint
;
3337 TestClosure completion
;
3340 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3341 .WillOnce(Return(OK
));
3342 EXPECT_CALL(checkpoint
, Call(1));
3343 EXPECT_CALL(*mock_stream_
, Close())
3344 .WillOnce(InvokeClosure(completion
.closure()));
3347 CreateChannelAndConnectSuccessfully();
3349 completion
.WaitForResult();
3352 // In this case the client initiates the closing handshake by sending a Close
3353 // message. WebSocketChannel waits for a Close message in response from the
3354 // server. The server never responds to the Close message, so the closing
3355 // handshake times out and WebSocketChannel closes the connection.
3356 TEST_F(WebSocketChannelStreamTimeoutTest
, ClientInitiatedCloseTimesOut
) {
3357 static const InitFrame expected
[] = {
3358 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3359 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
3360 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
3361 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
3362 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3363 .WillRepeatedly(Return(ERR_IO_PENDING
));
3364 TestClosure completion
;
3367 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3368 .WillOnce(Return(OK
));
3369 EXPECT_CALL(*mock_stream_
, Close())
3370 .WillOnce(InvokeClosure(completion
.closure()));
3373 CreateChannelAndConnectSuccessfully();
3374 channel_
->StartClosingHandshake(kWebSocketNormalClosure
, "OK");
3375 completion
.WaitForResult();
3378 // In this case the client initiates the closing handshake and the server
3379 // responds with a matching Close message. WebSocketChannel waits for the server
3380 // to close the TCP/IP connection, but it never does. The closing handshake
3381 // times out and WebSocketChannel closes the connection.
3382 TEST_F(WebSocketChannelStreamTimeoutTest
, ConnectionCloseTimesOut
) {
3383 static const InitFrame expected
[] = {
3384 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3385 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
3386 static const InitFrame frames
[] = {
3387 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3388 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
3389 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
3390 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
3391 TestClosure completion
;
3392 ScopedVector
<WebSocketFrame
>* read_frames
= NULL
;
3393 CompletionCallback read_callback
;
3396 // Copy the arguments to ReadFrames so that the test can call the callback
3397 // after it has send the close message.
3398 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3399 .WillOnce(DoAll(SaveArg
<0>(&read_frames
),
3400 SaveArg
<1>(&read_callback
),
3401 Return(ERR_IO_PENDING
)));
3402 // The first real event that happens is the client sending the Close
3404 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3405 .WillOnce(Return(OK
));
3406 // The |read_frames| callback is called (from this test case) at this
3407 // point. ReadFrames is called again by WebSocketChannel, waiting for
3408 // ERR_CONNECTION_CLOSED.
3409 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3410 .WillOnce(Return(ERR_IO_PENDING
));
3411 // The timeout happens and so WebSocketChannel closes the stream.
3412 EXPECT_CALL(*mock_stream_
, Close())
3413 .WillOnce(InvokeClosure(completion
.closure()));
3416 CreateChannelAndConnectSuccessfully();
3417 channel_
->StartClosingHandshake(kWebSocketNormalClosure
, "OK");
3418 ASSERT_TRUE(read_frames
);
3419 // Provide the "Close" message from the server.
3420 *read_frames
= CreateFrameVector(frames
);
3421 read_callback
.Run(OK
);
3422 completion
.WaitForResult();