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/single_thread_task_runner.h"
23 #include "base/strings/string_piece.h"
24 #include "base/thread_task_runner_handle.h"
25 #include "net/base/net_errors.h"
26 #include "net/base/test_completion_callback.h"
27 #include "net/http/http_response_headers.h"
28 #include "net/url_request/url_request_context.h"
29 #include "net/websockets/websocket_errors.h"
30 #include "net/websockets/websocket_event_interface.h"
31 #include "net/websockets/websocket_handshake_request_info.h"
32 #include "net/websockets/websocket_handshake_response_info.h"
33 #include "net/websockets/websocket_mux.h"
34 #include "testing/gmock/include/gmock/gmock.h"
35 #include "testing/gtest/include/gtest/gtest.h"
37 #include "url/origin.h"
39 // Hacky macros to construct the body of a Close message from a code and a
40 // string, while ensuring the result is a compile-time constant string.
41 // Use like CLOSE_DATA(NORMAL_CLOSURE, "Explanation String")
42 #define CLOSE_DATA(code, string) WEBSOCKET_CLOSE_CODE_AS_STRING_##code string
43 #define WEBSOCKET_CLOSE_CODE_AS_STRING_NORMAL_CLOSURE "\x03\xe8"
44 #define WEBSOCKET_CLOSE_CODE_AS_STRING_GOING_AWAY "\x03\xe9"
45 #define WEBSOCKET_CLOSE_CODE_AS_STRING_PROTOCOL_ERROR "\x03\xea"
46 #define WEBSOCKET_CLOSE_CODE_AS_STRING_ABNORMAL_CLOSURE "\x03\xee"
47 #define WEBSOCKET_CLOSE_CODE_AS_STRING_SERVER_ERROR "\x03\xf3"
51 // Printing helpers to allow GoogleMock to print frames. These are explicitly
52 // designed to look like the static initialisation format we use in these
53 // tests. They have to live in the net namespace in order to be found by
54 // GoogleMock; a nested anonymous namespace will not work.
56 std::ostream
& operator<<(std::ostream
& os
, const WebSocketFrameHeader
& header
) {
57 return os
<< (header
.final
? "FINAL_FRAME" : "NOT_FINAL_FRAME") << ", "
58 << header
.opcode
<< ", "
59 << (header
.masked
? "MASKED" : "NOT_MASKED");
62 std::ostream
& operator<<(std::ostream
& os
, const WebSocketFrame
& frame
) {
63 os
<< "{" << frame
.header
<< ", ";
64 if (frame
.data
.get()) {
65 return os
<< "\"" << base::StringPiece(frame
.data
->data(),
66 frame
.header
.payload_length
)
72 std::ostream
& operator<<(std::ostream
& os
,
73 const ScopedVector
<WebSocketFrame
>& vector
) {
76 for (ScopedVector
<WebSocketFrame
>::const_iterator it
= vector
.begin();
89 std::ostream
& operator<<(std::ostream
& os
,
90 const ScopedVector
<WebSocketFrame
>* vector
) {
91 return os
<< '&' << *vector
;
96 using ::base::TimeDelta
;
98 using ::testing::AnyNumber
;
99 using ::testing::DefaultValue
;
100 using ::testing::InSequence
;
101 using ::testing::MockFunction
;
102 using ::testing::NotNull
;
103 using ::testing::Return
;
104 using ::testing::SaveArg
;
105 using ::testing::StrictMock
;
108 // A selection of characters that have traditionally been mangled in some
109 // environment or other, for testing 8-bit cleanliness.
110 const char kBinaryBlob
[] = {'\n', '\r', // BACKWARDS CRNL
113 '\x80', '\xFF', // NOT VALID UTF-8
114 '\x1A', // Control-Z, EOF on DOS
116 '\x04', // EOT, special for Unix terms
117 '\x1B', // ESC, often special
119 '\'', // single-quote, special in PHP
121 const size_t kBinaryBlobSize
= arraysize(kBinaryBlob
);
123 // The amount of quota a new connection gets by default.
124 // TODO(ricea): If kDefaultSendQuotaHighWaterMark changes, then this value will
125 // need to be updated.
126 const size_t kDefaultInitialQuota
= 1 << 17;
127 // The amount of bytes we need to send after the initial connection to trigger a
128 // quota refresh. TODO(ricea): Change this if kDefaultSendQuotaHighWaterMark or
129 // kDefaultSendQuotaLowWaterMark change.
130 const size_t kDefaultQuotaRefreshTrigger
= (1 << 16) + 1;
132 const int kVeryBigTimeoutMillis
= 60 * 60 * 24 * 1000;
134 // TestTimeouts::tiny_timeout() is 100ms! I could run halfway around the world
135 // in that time! I would like my tests to run a bit quicker.
136 const int kVeryTinyTimeoutMillis
= 1;
138 // Enough quota to pass any test.
139 const int64 kPlentyOfQuota
= INT_MAX
;
141 typedef WebSocketEventInterface::ChannelState ChannelState
;
142 const ChannelState CHANNEL_ALIVE
= WebSocketEventInterface::CHANNEL_ALIVE
;
143 const ChannelState CHANNEL_DELETED
= WebSocketEventInterface::CHANNEL_DELETED
;
145 // This typedef mainly exists to avoid having to repeat the "NOLINT" incantation
146 // all over the place.
147 typedef StrictMock
< MockFunction
<void(int)> > Checkpoint
; // NOLINT
149 // This mock is for testing expectations about how the EventInterface is used.
150 class MockWebSocketEventInterface
: public WebSocketEventInterface
{
152 MockWebSocketEventInterface() {}
154 MOCK_METHOD2(OnAddChannelResponse
,
155 ChannelState(const std::string
&,
156 const std::string
&)); // NOLINT
157 MOCK_METHOD3(OnDataFrame
,
159 WebSocketMessageType
,
160 const std::vector
<char>&)); // NOLINT
161 MOCK_METHOD1(OnFlowControl
, ChannelState(int64
)); // NOLINT
162 MOCK_METHOD0(OnClosingHandshake
, ChannelState(void)); // NOLINT
163 MOCK_METHOD1(OnFailChannel
, ChannelState(const std::string
&)); // NOLINT
164 MOCK_METHOD3(OnDropChannel
,
165 ChannelState(bool, uint16
, const std::string
&)); // NOLINT
167 // We can't use GMock with scoped_ptr.
168 ChannelState
OnStartOpeningHandshake(
169 scoped_ptr
<WebSocketHandshakeRequestInfo
>) override
{
170 OnStartOpeningHandshakeCalled();
171 return CHANNEL_ALIVE
;
173 ChannelState
OnFinishOpeningHandshake(
174 scoped_ptr
<WebSocketHandshakeResponseInfo
>) override
{
175 OnFinishOpeningHandshakeCalled();
176 return CHANNEL_ALIVE
;
178 ChannelState
OnSSLCertificateError(
179 scoped_ptr
<SSLErrorCallbacks
> ssl_error_callbacks
,
181 const SSLInfo
& ssl_info
,
182 bool fatal
) override
{
183 OnSSLCertificateErrorCalled(
184 ssl_error_callbacks
.get(), url
, ssl_info
, fatal
);
185 return CHANNEL_ALIVE
;
188 MOCK_METHOD0(OnStartOpeningHandshakeCalled
, void()); // NOLINT
189 MOCK_METHOD0(OnFinishOpeningHandshakeCalled
, void()); // NOLINT
191 OnSSLCertificateErrorCalled
,
192 void(SSLErrorCallbacks
*, const GURL
&, const SSLInfo
&, bool)); // NOLINT
195 // This fake EventInterface is for tests which need a WebSocketEventInterface
196 // implementation but are not verifying how it is used.
197 class FakeWebSocketEventInterface
: public WebSocketEventInterface
{
198 ChannelState
OnAddChannelResponse(const std::string
& selected_protocol
,
199 const std::string
& extensions
) override
{
200 return 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
.Pass());
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::ThreadTaskRunnerHandle::Get()->PostTask(
490 FROM_HERE
, base::Bind(&ReadableFakeWebSocketStream::DoCallback
,
491 base::Unretained(this), frames
, callback
));
492 return ERR_IO_PENDING
;
494 frames
->swap(responses_
[index_
]->frames
);
495 return responses_
[index_
++]->error
;
500 void DoCallback(ScopedVector
<WebSocketFrame
>* frames
,
501 const CompletionCallback
& callback
) {
502 read_frames_pending_
= false;
503 frames
->swap(responses_
[index_
]->frames
);
504 callback
.Run(responses_
[index_
++]->error
);
509 Response(IsSync async
, int error
, ScopedVector
<WebSocketFrame
> frames
)
510 : async(async
), error(error
), frames(frames
.Pass()) {}
514 ScopedVector
<WebSocketFrame
> frames
;
517 // Bad things will happen if we attempt to copy or assign |frames|.
518 DISALLOW_COPY_AND_ASSIGN(Response
);
520 ScopedVector
<Response
> responses_
;
522 // The index into the responses_ array of the next response to be returned.
525 // True when an async response from ReadFrames() is pending. This only applies
526 // to "real" async responses. Once all the prepared responses have been
527 // returned, ReadFrames() returns ERR_IO_PENDING but read_frames_pending_ is
529 bool read_frames_pending_
;
532 // A FakeWebSocketStream where writes always complete successfully and
534 class WriteableFakeWebSocketStream
: public FakeWebSocketStream
{
536 int WriteFrames(ScopedVector
<WebSocketFrame
>* frames
,
537 const CompletionCallback
& callback
) override
{
542 // A FakeWebSocketStream where writes always fail.
543 class UnWriteableFakeWebSocketStream
: public FakeWebSocketStream
{
545 int WriteFrames(ScopedVector
<WebSocketFrame
>* frames
,
546 const CompletionCallback
& callback
) override
{
547 return ERR_CONNECTION_RESET
;
551 // A FakeWebSocketStream which echoes any frames written back. Clears the
552 // "masked" header bit, but makes no other checks for validity. Tests using this
553 // must run the MessageLoop to receive the callback(s). If a message with opcode
554 // Close is echoed, then an ERR_CONNECTION_CLOSED is returned in the next
555 // callback. The test must do something to cause WriteFrames() to be called,
556 // otherwise the ReadFrames() callback will never be called.
557 class EchoeyFakeWebSocketStream
: public FakeWebSocketStream
{
559 EchoeyFakeWebSocketStream() : read_frames_(NULL
), done_(false) {}
561 int WriteFrames(ScopedVector
<WebSocketFrame
>* frames
,
562 const CompletionCallback
& callback
) override
{
563 // Users of WebSocketStream will not expect the ReadFrames() callback to be
564 // called from within WriteFrames(), so post it to the message loop instead.
565 stored_frames_
.insert(stored_frames_
.end(), frames
->begin(), frames
->end());
566 frames
->weak_clear();
571 int ReadFrames(ScopedVector
<WebSocketFrame
>* frames
,
572 const CompletionCallback
& callback
) override
{
573 read_callback_
= callback
;
574 read_frames_
= frames
;
577 return ERR_IO_PENDING
;
581 void PostCallback() {
582 base::ThreadTaskRunnerHandle::Get()->PostTask(
583 FROM_HERE
, base::Bind(&EchoeyFakeWebSocketStream::DoCallback
,
584 base::Unretained(this)));
589 read_callback_
.Run(ERR_CONNECTION_CLOSED
);
590 } else if (!stored_frames_
.empty()) {
591 done_
= MoveFrames(read_frames_
);
593 read_callback_
.Run(OK
);
597 // Copy the frames stored in stored_frames_ to |out|, while clearing the
598 // "masked" header bit. Returns true if a Close Frame was seen, false
600 bool MoveFrames(ScopedVector
<WebSocketFrame
>* out
) {
601 bool seen_close
= false;
602 *out
= stored_frames_
.Pass();
603 for (ScopedVector
<WebSocketFrame
>::iterator it
= out
->begin();
606 WebSocketFrameHeader
& header
= (*it
)->header
;
607 header
.masked
= false;
608 if (header
.opcode
== WebSocketFrameHeader::kOpCodeClose
)
614 ScopedVector
<WebSocketFrame
> stored_frames_
;
615 CompletionCallback read_callback_
;
616 // Owned by the caller of ReadFrames().
617 ScopedVector
<WebSocketFrame
>* read_frames_
;
618 // True if we should close the connection.
622 // A FakeWebSocketStream where writes trigger a connection reset.
623 // This differs from UnWriteableFakeWebSocketStream in that it is asynchronous
624 // and triggers ReadFrames to return a reset as well. Tests using this need to
625 // run the message loop. There are two tricky parts here:
626 // 1. Calling the write callback may call Close(), after which the read callback
627 // should not be called.
628 // 2. Calling either callback may delete the stream altogether.
629 class ResetOnWriteFakeWebSocketStream
: public FakeWebSocketStream
{
631 ResetOnWriteFakeWebSocketStream() : closed_(false), weak_ptr_factory_(this) {}
633 int WriteFrames(ScopedVector
<WebSocketFrame
>* frames
,
634 const CompletionCallback
& callback
) override
{
635 base::ThreadTaskRunnerHandle::Get()->PostTask(
637 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed
,
638 weak_ptr_factory_
.GetWeakPtr(), callback
,
639 ERR_CONNECTION_RESET
));
640 base::ThreadTaskRunnerHandle::Get()->PostTask(
642 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed
,
643 weak_ptr_factory_
.GetWeakPtr(), read_callback_
,
644 ERR_CONNECTION_RESET
));
645 return ERR_IO_PENDING
;
648 int ReadFrames(ScopedVector
<WebSocketFrame
>* frames
,
649 const CompletionCallback
& callback
) override
{
650 read_callback_
= callback
;
651 return ERR_IO_PENDING
;
654 void Close() override
{ closed_
= true; }
657 void CallCallbackUnlessClosed(const CompletionCallback
& callback
, int value
) {
662 CompletionCallback read_callback_
;
664 // An IO error can result in the socket being deleted, so we use weak pointers
665 // to ensure correct behaviour in that case.
666 base::WeakPtrFactory
<ResetOnWriteFakeWebSocketStream
> weak_ptr_factory_
;
669 // This mock is for verifying that WebSocket protocol semantics are obeyed (to
670 // the extent that they are implemented in WebSocketCommon).
671 class MockWebSocketStream
: public WebSocketStream
{
673 MOCK_METHOD2(ReadFrames
,
674 int(ScopedVector
<WebSocketFrame
>* frames
,
675 const CompletionCallback
& callback
));
676 MOCK_METHOD2(WriteFrames
,
677 int(ScopedVector
<WebSocketFrame
>* frames
,
678 const CompletionCallback
& callback
));
679 MOCK_METHOD0(Close
, void());
680 MOCK_CONST_METHOD0(GetSubProtocol
, std::string());
681 MOCK_CONST_METHOD0(GetExtensions
, std::string());
682 MOCK_METHOD0(AsWebSocketStream
, WebSocketStream
*());
685 struct ArgumentCopyingWebSocketStreamCreator
{
686 scoped_ptr
<WebSocketStreamRequest
> Create(
687 const GURL
& socket_url
,
688 const std::vector
<std::string
>& requested_subprotocols
,
689 const url::Origin
& origin
,
690 URLRequestContext
* url_request_context
,
691 const BoundNetLog
& net_log
,
692 scoped_ptr
<WebSocketStream::ConnectDelegate
> connect_delegate
) {
693 this->socket_url
= socket_url
;
694 this->requested_subprotocols
= requested_subprotocols
;
695 this->origin
= origin
;
696 this->url_request_context
= url_request_context
;
697 this->net_log
= net_log
;
698 this->connect_delegate
= connect_delegate
.Pass();
699 return make_scoped_ptr(new WebSocketStreamRequest
);
704 std::vector
<std::string
> requested_subprotocols
;
705 URLRequestContext
* url_request_context
;
707 scoped_ptr
<WebSocketStream::ConnectDelegate
> connect_delegate
;
710 // Converts a std::string to a std::vector<char>. For test purposes, it is
711 // convenient to be able to specify data as a string, but the
712 // WebSocketEventInterface requires the vector<char> type.
713 std::vector
<char> AsVector(const std::string
& s
) {
714 return std::vector
<char>(s
.begin(), s
.end());
717 class FakeSSLErrorCallbacks
718 : public WebSocketEventInterface::SSLErrorCallbacks
{
720 void CancelSSLRequest(int error
, const SSLInfo
* ssl_info
) override
{}
721 void ContinueSSLRequest() override
{}
724 // Base class for all test fixtures.
725 class WebSocketChannelTest
: public ::testing::Test
{
727 WebSocketChannelTest() : stream_(new FakeWebSocketStream
) {}
729 // Creates a new WebSocketChannel and connects it, using the settings stored
730 // in |connect_data_|.
731 void CreateChannelAndConnect() {
732 channel_
.reset(new WebSocketChannel(CreateEventInterface(),
733 &connect_data_
.url_request_context
));
734 channel_
->SendAddChannelRequestForTesting(
735 connect_data_
.socket_url
,
736 connect_data_
.requested_subprotocols
,
737 connect_data_
.origin
,
738 base::Bind(&ArgumentCopyingWebSocketStreamCreator::Create
,
739 base::Unretained(&connect_data_
.creator
)));
742 // Same as CreateChannelAndConnect(), but calls the on_success callback as
743 // well. This method is virtual so that subclasses can also set the stream.
744 virtual void CreateChannelAndConnectSuccessfully() {
745 CreateChannelAndConnect();
746 // Most tests aren't concerned with flow control from the renderer, so allow
747 // MAX_INT quota units.
748 channel_
->SendFlowControl(kPlentyOfQuota
);
749 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
752 // Returns a WebSocketEventInterface to be passed to the WebSocketChannel.
753 // This implementation returns a newly-created fake. Subclasses may return a
755 virtual scoped_ptr
<WebSocketEventInterface
> CreateEventInterface() {
756 return scoped_ptr
<WebSocketEventInterface
>(new FakeWebSocketEventInterface
);
759 // This method serves no other purpose than to provide a nice syntax for
760 // assigning to stream_. class T must be a subclass of WebSocketStream or you
761 // will have unpleasant compile errors.
763 void set_stream(scoped_ptr
<T
> stream
) {
764 stream_
= stream
.Pass();
767 // A struct containing the data that will be used to connect the channel.
768 // Grouped for readability.
770 ConnectData() : socket_url("ws://ws/"), origin(GURL("http://ws")) {}
772 // URLRequestContext object.
773 URLRequestContext url_request_context
;
775 // URL to (pretend to) connect to.
777 // Requested protocols for the request.
778 std::vector
<std::string
> requested_subprotocols
;
779 // Origin of the request
782 // A fake WebSocketStreamCreator that just records its arguments.
783 ArgumentCopyingWebSocketStreamCreator creator
;
785 ConnectData connect_data_
;
787 // The channel we are testing. Not initialised until SetChannel() is called.
788 scoped_ptr
<WebSocketChannel
> channel_
;
790 // A mock or fake stream for tests that need one.
791 scoped_ptr
<WebSocketStream
> stream_
;
794 // enum of WebSocketEventInterface calls. These are intended to be or'd together
795 // in order to instruct WebSocketChannelDeletingTest when it should fail.
796 enum EventInterfaceCall
{
797 EVENT_ON_ADD_CHANNEL_RESPONSE
= 0x1,
798 EVENT_ON_DATA_FRAME
= 0x2,
799 EVENT_ON_FLOW_CONTROL
= 0x4,
800 EVENT_ON_CLOSING_HANDSHAKE
= 0x8,
801 EVENT_ON_FAIL_CHANNEL
= 0x10,
802 EVENT_ON_DROP_CHANNEL
= 0x20,
803 EVENT_ON_START_OPENING_HANDSHAKE
= 0x40,
804 EVENT_ON_FINISH_OPENING_HANDSHAKE
= 0x80,
805 EVENT_ON_SSL_CERTIFICATE_ERROR
= 0x100,
808 class WebSocketChannelDeletingTest
: public WebSocketChannelTest
{
810 ChannelState
DeleteIfDeleting(EventInterfaceCall call
) {
811 if (deleting_
& call
) {
813 return CHANNEL_DELETED
;
815 return CHANNEL_ALIVE
;
820 WebSocketChannelDeletingTest()
821 : deleting_(EVENT_ON_ADD_CHANNEL_RESPONSE
| EVENT_ON_DATA_FRAME
|
822 EVENT_ON_FLOW_CONTROL
|
823 EVENT_ON_CLOSING_HANDSHAKE
|
824 EVENT_ON_FAIL_CHANNEL
|
825 EVENT_ON_DROP_CHANNEL
|
826 EVENT_ON_START_OPENING_HANDSHAKE
|
827 EVENT_ON_FINISH_OPENING_HANDSHAKE
|
828 EVENT_ON_SSL_CERTIFICATE_ERROR
) {}
829 // Create a ChannelDeletingFakeWebSocketEventInterface. Defined out-of-line to
830 // avoid circular dependency.
831 scoped_ptr
<WebSocketEventInterface
> CreateEventInterface() override
;
833 // Tests can set deleting_ to a bitmap of EventInterfaceCall members that they
834 // want to cause Channel deletion. The default is for all calls to cause
839 // A FakeWebSocketEventInterface that deletes the WebSocketChannel on failure to
841 class ChannelDeletingFakeWebSocketEventInterface
842 : public FakeWebSocketEventInterface
{
844 ChannelDeletingFakeWebSocketEventInterface(
845 WebSocketChannelDeletingTest
* fixture
)
846 : fixture_(fixture
) {}
848 ChannelState
OnAddChannelResponse(const std::string
& selected_protocol
,
849 const std::string
& extensions
) override
{
850 return fixture_
->DeleteIfDeleting(EVENT_ON_ADD_CHANNEL_RESPONSE
);
853 ChannelState
OnDataFrame(bool fin
,
854 WebSocketMessageType type
,
855 const std::vector
<char>& data
) override
{
856 return fixture_
->DeleteIfDeleting(EVENT_ON_DATA_FRAME
);
859 ChannelState
OnFlowControl(int64 quota
) override
{
860 return fixture_
->DeleteIfDeleting(EVENT_ON_FLOW_CONTROL
);
863 ChannelState
OnClosingHandshake() override
{
864 return fixture_
->DeleteIfDeleting(EVENT_ON_CLOSING_HANDSHAKE
);
867 ChannelState
OnFailChannel(const std::string
& message
) override
{
868 return fixture_
->DeleteIfDeleting(EVENT_ON_FAIL_CHANNEL
);
871 ChannelState
OnDropChannel(bool was_clean
,
873 const std::string
& reason
) override
{
874 return fixture_
->DeleteIfDeleting(EVENT_ON_DROP_CHANNEL
);
877 ChannelState
OnStartOpeningHandshake(
878 scoped_ptr
<WebSocketHandshakeRequestInfo
> request
) override
{
879 return fixture_
->DeleteIfDeleting(EVENT_ON_START_OPENING_HANDSHAKE
);
881 ChannelState
OnFinishOpeningHandshake(
882 scoped_ptr
<WebSocketHandshakeResponseInfo
> response
) override
{
883 return fixture_
->DeleteIfDeleting(EVENT_ON_FINISH_OPENING_HANDSHAKE
);
885 ChannelState
OnSSLCertificateError(
886 scoped_ptr
<SSLErrorCallbacks
> ssl_error_callbacks
,
888 const SSLInfo
& ssl_info
,
889 bool fatal
) override
{
890 return fixture_
->DeleteIfDeleting(EVENT_ON_SSL_CERTIFICATE_ERROR
);
894 // A pointer to the test fixture. Owned by the test harness; this object will
895 // be deleted before it is.
896 WebSocketChannelDeletingTest
* fixture_
;
899 scoped_ptr
<WebSocketEventInterface
>
900 WebSocketChannelDeletingTest::CreateEventInterface() {
901 return scoped_ptr
<WebSocketEventInterface
>(
902 new ChannelDeletingFakeWebSocketEventInterface(this));
905 // Base class for tests which verify that EventInterface methods are called
907 class WebSocketChannelEventInterfaceTest
: public WebSocketChannelTest
{
909 WebSocketChannelEventInterfaceTest()
910 : event_interface_(new StrictMock
<MockWebSocketEventInterface
>) {
911 DefaultValue
<ChannelState
>::Set(CHANNEL_ALIVE
);
912 ON_CALL(*event_interface_
, OnDropChannel(_
, _
, _
))
913 .WillByDefault(Return(CHANNEL_DELETED
));
914 ON_CALL(*event_interface_
, OnFailChannel(_
))
915 .WillByDefault(Return(CHANNEL_DELETED
));
918 ~WebSocketChannelEventInterfaceTest() override
{
919 DefaultValue
<ChannelState
>::Clear();
922 // Tests using this fixture must set expectations on the event_interface_ mock
923 // object before calling CreateChannelAndConnect() or
924 // CreateChannelAndConnectSuccessfully(). This will only work once per test
925 // case, but once should be enough.
926 scoped_ptr
<WebSocketEventInterface
> CreateEventInterface() override
{
927 return scoped_ptr
<WebSocketEventInterface
>(event_interface_
.release());
930 scoped_ptr
<MockWebSocketEventInterface
> event_interface_
;
933 // Base class for tests which verify that WebSocketStream methods are called
934 // appropriately by using a MockWebSocketStream.
935 class WebSocketChannelStreamTest
: public WebSocketChannelTest
{
937 WebSocketChannelStreamTest()
938 : mock_stream_(new StrictMock
<MockWebSocketStream
>) {}
940 void CreateChannelAndConnectSuccessfully() override
{
941 set_stream(mock_stream_
.Pass());
942 WebSocketChannelTest::CreateChannelAndConnectSuccessfully();
945 scoped_ptr
<MockWebSocketStream
> mock_stream_
;
948 // Fixture for tests which test UTF-8 validation of sent Text frames via the
950 class WebSocketChannelSendUtf8Test
951 : public WebSocketChannelEventInterfaceTest
{
953 void SetUp() override
{
954 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
955 // For the purpose of the tests using this fixture, it doesn't matter
956 // whether these methods are called or not.
957 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
))
959 EXPECT_CALL(*event_interface_
, OnFlowControl(_
))
964 // Fixture for tests which test use of receive quota from the renderer.
965 class WebSocketChannelFlowControlTest
966 : public WebSocketChannelEventInterfaceTest
{
968 // Tests using this fixture should use CreateChannelAndConnectWithQuota()
969 // instead of CreateChannelAndConnectSuccessfully().
970 void CreateChannelAndConnectWithQuota(int64 quota
) {
971 CreateChannelAndConnect();
972 channel_
->SendFlowControl(quota
);
973 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
976 virtual void CreateChannelAndConnectSuccesfully() { NOTREACHED(); }
979 // Fixture for tests which test UTF-8 validation of received Text frames using a
980 // mock WebSocketStream.
981 class WebSocketChannelReceiveUtf8Test
: public WebSocketChannelStreamTest
{
983 void SetUp() override
{
984 // For the purpose of the tests using this fixture, it doesn't matter
985 // whether these methods are called or not.
986 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
987 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
991 // Simple test that everything that should be passed to the creator function is
992 // passed to the creator function.
993 TEST_F(WebSocketChannelTest
, EverythingIsPassedToTheCreatorFunction
) {
994 connect_data_
.socket_url
= GURL("ws://example.com/test");
995 connect_data_
.origin
= url::Origin(GURL("http://example.com"));
996 connect_data_
.requested_subprotocols
.push_back("Sinbad");
998 CreateChannelAndConnect();
1000 const ArgumentCopyingWebSocketStreamCreator
& actual
= connect_data_
.creator
;
1002 EXPECT_EQ(&connect_data_
.url_request_context
, actual
.url_request_context
);
1004 EXPECT_EQ(connect_data_
.socket_url
, actual
.socket_url
);
1005 EXPECT_EQ(connect_data_
.requested_subprotocols
,
1006 actual
.requested_subprotocols
);
1007 EXPECT_EQ(connect_data_
.origin
.Serialize(), actual
.origin
.Serialize());
1010 // Verify that calling SendFlowControl before the connection is established does
1011 // not cause a crash.
1012 TEST_F(WebSocketChannelTest
, SendFlowControlDuringHandshakeOkay
) {
1013 CreateChannelAndConnect();
1014 ASSERT_TRUE(channel_
);
1015 channel_
->SendFlowControl(65536);
1018 // Any WebSocketEventInterface methods can delete the WebSocketChannel and
1019 // return CHANNEL_DELETED. The WebSocketChannelDeletingTests are intended to
1020 // verify that there are no use-after-free bugs when this happens. Problems will
1021 // probably only be found when running under Address Sanitizer or a similar
1023 TEST_F(WebSocketChannelDeletingTest
, OnAddChannelResponseFail
) {
1024 CreateChannelAndConnect();
1025 EXPECT_TRUE(channel_
);
1026 connect_data_
.creator
.connect_delegate
->OnFailure("bye");
1027 EXPECT_EQ(NULL
, channel_
.get());
1030 // Deletion is possible (due to IPC failure) even if the connect succeeds.
1031 TEST_F(WebSocketChannelDeletingTest
, OnAddChannelResponseSuccess
) {
1032 CreateChannelAndConnectSuccessfully();
1033 EXPECT_EQ(NULL
, channel_
.get());
1036 TEST_F(WebSocketChannelDeletingTest
, OnDataFrameSync
) {
1037 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1038 new ReadableFakeWebSocketStream
);
1039 static const InitFrame frames
[] = {
1040 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1041 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1042 set_stream(stream
.Pass());
1043 deleting_
= EVENT_ON_DATA_FRAME
;
1045 CreateChannelAndConnectSuccessfully();
1046 EXPECT_EQ(NULL
, channel_
.get());
1049 TEST_F(WebSocketChannelDeletingTest
, OnDataFrameAsync
) {
1050 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1051 new ReadableFakeWebSocketStream
);
1052 static const InitFrame frames
[] = {
1053 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1054 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1055 set_stream(stream
.Pass());
1056 deleting_
= EVENT_ON_DATA_FRAME
;
1058 CreateChannelAndConnectSuccessfully();
1059 EXPECT_TRUE(channel_
);
1060 base::MessageLoop::current()->RunUntilIdle();
1061 EXPECT_EQ(NULL
, channel_
.get());
1064 TEST_F(WebSocketChannelDeletingTest
, OnFlowControlAfterConnect
) {
1065 deleting_
= EVENT_ON_FLOW_CONTROL
;
1067 CreateChannelAndConnectSuccessfully();
1068 EXPECT_EQ(NULL
, channel_
.get());
1071 TEST_F(WebSocketChannelDeletingTest
, OnFlowControlAfterSend
) {
1072 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
1073 // Avoid deleting the channel yet.
1074 deleting_
= EVENT_ON_FAIL_CHANNEL
| EVENT_ON_DROP_CHANNEL
;
1075 CreateChannelAndConnectSuccessfully();
1076 ASSERT_TRUE(channel_
);
1077 deleting_
= EVENT_ON_FLOW_CONTROL
;
1078 channel_
->SendFrame(true,
1079 WebSocketFrameHeader::kOpCodeText
,
1080 std::vector
<char>(kDefaultInitialQuota
, 'B'));
1081 EXPECT_EQ(NULL
, channel_
.get());
1084 TEST_F(WebSocketChannelDeletingTest
, OnClosingHandshakeSync
) {
1085 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1086 new ReadableFakeWebSocketStream
);
1087 static const InitFrame frames
[] = {
1088 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
1089 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Success")}};
1090 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1091 set_stream(stream
.Pass());
1092 deleting_
= EVENT_ON_CLOSING_HANDSHAKE
;
1093 CreateChannelAndConnectSuccessfully();
1094 EXPECT_EQ(NULL
, channel_
.get());
1097 TEST_F(WebSocketChannelDeletingTest
, OnClosingHandshakeAsync
) {
1098 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1099 new ReadableFakeWebSocketStream
);
1100 static const InitFrame frames
[] = {
1101 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
1102 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Success")}};
1103 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1104 set_stream(stream
.Pass());
1105 deleting_
= EVENT_ON_CLOSING_HANDSHAKE
;
1106 CreateChannelAndConnectSuccessfully();
1107 ASSERT_TRUE(channel_
);
1108 base::MessageLoop::current()->RunUntilIdle();
1109 EXPECT_EQ(NULL
, channel_
.get());
1112 TEST_F(WebSocketChannelDeletingTest
, OnDropChannelWriteError
) {
1113 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream
));
1114 deleting_
= EVENT_ON_DROP_CHANNEL
;
1115 CreateChannelAndConnectSuccessfully();
1116 ASSERT_TRUE(channel_
);
1117 channel_
->SendFrame(
1118 true, WebSocketFrameHeader::kOpCodeText
, AsVector("this will fail"));
1119 EXPECT_EQ(NULL
, channel_
.get());
1122 TEST_F(WebSocketChannelDeletingTest
, OnDropChannelReadError
) {
1123 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1124 new ReadableFakeWebSocketStream
);
1125 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC
,
1127 set_stream(stream
.Pass());
1128 deleting_
= EVENT_ON_DROP_CHANNEL
;
1129 CreateChannelAndConnectSuccessfully();
1130 ASSERT_TRUE(channel_
);
1131 base::MessageLoop::current()->RunUntilIdle();
1132 EXPECT_EQ(NULL
, channel_
.get());
1135 TEST_F(WebSocketChannelDeletingTest
, OnNotifyStartOpeningHandshakeError
) {
1136 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1137 new ReadableFakeWebSocketStream
);
1138 static const InitFrame frames
[] = {
1139 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1140 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1141 set_stream(stream
.Pass());
1142 deleting_
= EVENT_ON_START_OPENING_HANDSHAKE
;
1144 CreateChannelAndConnectSuccessfully();
1145 ASSERT_TRUE(channel_
);
1146 channel_
->OnStartOpeningHandshake(scoped_ptr
<WebSocketHandshakeRequestInfo
>(
1147 new WebSocketHandshakeRequestInfo(GURL("http://www.example.com/"),
1149 base::MessageLoop::current()->RunUntilIdle();
1150 EXPECT_EQ(NULL
, channel_
.get());
1153 TEST_F(WebSocketChannelDeletingTest
, OnNotifyFinishOpeningHandshakeError
) {
1154 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1155 new ReadableFakeWebSocketStream
);
1156 static const InitFrame frames
[] = {
1157 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1158 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1159 set_stream(stream
.Pass());
1160 deleting_
= EVENT_ON_FINISH_OPENING_HANDSHAKE
;
1162 CreateChannelAndConnectSuccessfully();
1163 ASSERT_TRUE(channel_
);
1164 scoped_refptr
<HttpResponseHeaders
> response_headers(
1165 new HttpResponseHeaders(""));
1166 channel_
->OnFinishOpeningHandshake(scoped_ptr
<WebSocketHandshakeResponseInfo
>(
1167 new WebSocketHandshakeResponseInfo(GURL("http://www.example.com/"),
1172 base::MessageLoop::current()->RunUntilIdle();
1173 EXPECT_EQ(NULL
, channel_
.get());
1176 TEST_F(WebSocketChannelDeletingTest
, FailChannelInSendFrame
) {
1177 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
1178 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1179 CreateChannelAndConnectSuccessfully();
1180 ASSERT_TRUE(channel_
);
1181 channel_
->SendFrame(true,
1182 WebSocketFrameHeader::kOpCodeText
,
1183 std::vector
<char>(kDefaultInitialQuota
* 2, 'T'));
1184 EXPECT_EQ(NULL
, channel_
.get());
1187 TEST_F(WebSocketChannelDeletingTest
, FailChannelInOnReadDone
) {
1188 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1189 new ReadableFakeWebSocketStream
);
1190 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC
,
1191 ERR_WS_PROTOCOL_ERROR
);
1192 set_stream(stream
.Pass());
1193 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1194 CreateChannelAndConnectSuccessfully();
1195 ASSERT_TRUE(channel_
);
1196 base::MessageLoop::current()->RunUntilIdle();
1197 EXPECT_EQ(NULL
, channel_
.get());
1200 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToMaskedFrame
) {
1201 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1202 new ReadableFakeWebSocketStream
);
1203 static const InitFrame frames
[] = {
1204 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "HELLO"}};
1205 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1206 set_stream(stream
.Pass());
1207 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1209 CreateChannelAndConnectSuccessfully();
1210 EXPECT_EQ(NULL
, channel_
.get());
1213 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToBadControlFrame
) {
1214 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1215 new ReadableFakeWebSocketStream
);
1216 static const InitFrame frames
[] = {
1217 {FINAL_FRAME
, 0xF, NOT_MASKED
, ""}};
1218 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1219 set_stream(stream
.Pass());
1220 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1222 CreateChannelAndConnectSuccessfully();
1223 EXPECT_EQ(NULL
, channel_
.get());
1226 // Version of above test with NULL data.
1227 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToBadControlFrameNull
) {
1228 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1229 new ReadableFakeWebSocketStream
);
1230 static const InitFrame frames
[] = {
1231 {FINAL_FRAME
, 0xF, NOT_MASKED
, NULL
}};
1232 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1233 set_stream(stream
.Pass());
1234 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1236 CreateChannelAndConnectSuccessfully();
1237 EXPECT_EQ(NULL
, channel_
.get());
1240 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToPongAfterClose
) {
1241 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1242 new ReadableFakeWebSocketStream
);
1243 static const InitFrame frames
[] = {
1244 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
,
1245 CLOSE_DATA(NORMAL_CLOSURE
, "Success")},
1246 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
, NOT_MASKED
, ""}};
1247 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1248 set_stream(stream
.Pass());
1249 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1251 CreateChannelAndConnectSuccessfully();
1252 EXPECT_EQ(NULL
, channel_
.get());
1255 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToPongAfterCloseNull
) {
1256 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1257 new ReadableFakeWebSocketStream
);
1258 static const InitFrame frames
[] = {
1259 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
,
1260 CLOSE_DATA(NORMAL_CLOSURE
, "Success")},
1261 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
, NOT_MASKED
, NULL
}};
1262 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1263 set_stream(stream
.Pass());
1264 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1266 CreateChannelAndConnectSuccessfully();
1267 EXPECT_EQ(NULL
, channel_
.get());
1270 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToUnknownOpCode
) {
1271 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1272 new ReadableFakeWebSocketStream
);
1273 static const InitFrame frames
[] = {{FINAL_FRAME
, 0x7, NOT_MASKED
, ""}};
1274 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1275 set_stream(stream
.Pass());
1276 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1278 CreateChannelAndConnectSuccessfully();
1279 EXPECT_EQ(NULL
, channel_
.get());
1282 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueToUnknownOpCodeNull
) {
1283 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1284 new ReadableFakeWebSocketStream
);
1285 static const InitFrame frames
[] = {{FINAL_FRAME
, 0x7, NOT_MASKED
, NULL
}};
1286 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1287 set_stream(stream
.Pass());
1288 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1290 CreateChannelAndConnectSuccessfully();
1291 EXPECT_EQ(NULL
, channel_
.get());
1294 TEST_F(WebSocketChannelDeletingTest
, FailChannelDueInvalidCloseReason
) {
1295 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1296 new ReadableFakeWebSocketStream
);
1297 static const InitFrame frames
[] = {
1298 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
1299 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "\xFF")}};
1300 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1301 set_stream(stream
.Pass());
1302 deleting_
= EVENT_ON_FAIL_CHANNEL
;
1304 CreateChannelAndConnectSuccessfully();
1305 EXPECT_EQ(NULL
, channel_
.get());
1308 TEST_F(WebSocketChannelEventInterfaceTest
, ConnectSuccessReported
) {
1309 // false means success.
1310 EXPECT_CALL(*event_interface_
, OnAddChannelResponse("", ""));
1311 // OnFlowControl is always called immediately after connect to provide initial
1312 // quota to the renderer.
1313 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1315 CreateChannelAndConnect();
1317 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
1320 TEST_F(WebSocketChannelEventInterfaceTest
, ConnectFailureReported
) {
1321 EXPECT_CALL(*event_interface_
, OnFailChannel("hello"));
1323 CreateChannelAndConnect();
1325 connect_data_
.creator
.connect_delegate
->OnFailure("hello");
1328 TEST_F(WebSocketChannelEventInterfaceTest
, NonWebSocketSchemeRejected
) {
1329 EXPECT_CALL(*event_interface_
, OnFailChannel("Invalid scheme"));
1330 connect_data_
.socket_url
= GURL("http://www.google.com/");
1331 CreateChannelAndConnect();
1334 TEST_F(WebSocketChannelEventInterfaceTest
, ProtocolPassed
) {
1335 EXPECT_CALL(*event_interface_
, OnAddChannelResponse("Bob", ""));
1336 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1338 CreateChannelAndConnect();
1340 connect_data_
.creator
.connect_delegate
->OnSuccess(
1341 scoped_ptr
<WebSocketStream
>(new FakeWebSocketStream("Bob", "")));
1344 TEST_F(WebSocketChannelEventInterfaceTest
, ExtensionsPassed
) {
1345 EXPECT_CALL(*event_interface_
,
1346 OnAddChannelResponse("", "extension1, extension2"));
1347 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1349 CreateChannelAndConnect();
1351 connect_data_
.creator
.connect_delegate
->OnSuccess(scoped_ptr
<WebSocketStream
>(
1352 new FakeWebSocketStream("", "extension1, extension2")));
1355 // The first frames from the server can arrive together with the handshake, in
1356 // which case they will be available as soon as ReadFrames() is called the first
1358 TEST_F(WebSocketChannelEventInterfaceTest
, DataLeftFromHandshake
) {
1359 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1360 new ReadableFakeWebSocketStream
);
1361 static const InitFrame frames
[] = {
1362 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1363 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1364 set_stream(stream
.Pass());
1367 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1368 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1372 true, WebSocketFrameHeader::kOpCodeText
, AsVector("HELLO")));
1375 CreateChannelAndConnectSuccessfully();
1378 // A remote server could accept the handshake, but then immediately send a
1380 TEST_F(WebSocketChannelEventInterfaceTest
, CloseAfterHandshake
) {
1381 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1382 new ReadableFakeWebSocketStream
);
1383 static const InitFrame frames
[] = {
1384 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
1385 NOT_MASKED
, CLOSE_DATA(SERVER_ERROR
, "Internal Server Error")}};
1386 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1387 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC
,
1388 ERR_CONNECTION_CLOSED
);
1389 set_stream(stream
.Pass());
1392 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1393 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1394 EXPECT_CALL(*event_interface_
, OnClosingHandshake());
1398 true, kWebSocketErrorInternalServerError
, "Internal Server Error"));
1401 CreateChannelAndConnectSuccessfully();
1404 // A remote server could close the connection immediately after sending the
1405 // handshake response (most likely a bug in the server).
1406 TEST_F(WebSocketChannelEventInterfaceTest
, ConnectionCloseAfterHandshake
) {
1407 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1408 new ReadableFakeWebSocketStream
);
1409 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC
,
1410 ERR_CONNECTION_CLOSED
);
1411 set_stream(stream
.Pass());
1414 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1415 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1416 EXPECT_CALL(*event_interface_
,
1417 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, _
));
1420 CreateChannelAndConnectSuccessfully();
1423 TEST_F(WebSocketChannelEventInterfaceTest
, NormalAsyncRead
) {
1424 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1425 new ReadableFakeWebSocketStream
);
1426 static const InitFrame frames
[] = {
1427 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1428 // We use this checkpoint object to verify that the callback isn't called
1429 // until we expect it to be.
1430 Checkpoint checkpoint
;
1431 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1432 set_stream(stream
.Pass());
1435 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1436 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1437 EXPECT_CALL(checkpoint
, Call(1));
1441 true, WebSocketFrameHeader::kOpCodeText
, AsVector("HELLO")));
1442 EXPECT_CALL(checkpoint
, Call(2));
1445 CreateChannelAndConnectSuccessfully();
1447 base::MessageLoop::current()->RunUntilIdle();
1451 // Extra data can arrive while a read is being processed, resulting in the next
1452 // read completing synchronously.
1453 TEST_F(WebSocketChannelEventInterfaceTest
, AsyncThenSyncRead
) {
1454 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1455 new ReadableFakeWebSocketStream
);
1456 static const InitFrame frames1
[] = {
1457 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "HELLO"}};
1458 static const InitFrame frames2
[] = {
1459 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "WORLD"}};
1460 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames1
);
1461 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames2
);
1462 set_stream(stream
.Pass());
1465 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1466 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1470 true, WebSocketFrameHeader::kOpCodeText
, AsVector("HELLO")));
1474 true, WebSocketFrameHeader::kOpCodeText
, AsVector("WORLD")));
1477 CreateChannelAndConnectSuccessfully();
1478 base::MessageLoop::current()->RunUntilIdle();
1481 // Data frames are delivered the same regardless of how many reads they arrive
1483 TEST_F(WebSocketChannelEventInterfaceTest
, FragmentedMessage
) {
1484 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1485 new ReadableFakeWebSocketStream
);
1486 // Here we have one message which arrived in five frames split across three
1487 // reads. It may have been reframed on arrival, but this class doesn't care
1489 static const InitFrame frames1
[] = {
1490 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "THREE"},
1491 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
1493 static const InitFrame frames2
[] = {
1494 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
1495 NOT_MASKED
, "SMALL"}};
1496 static const InitFrame frames3
[] = {
1497 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
1499 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
1500 NOT_MASKED
, "FRAMES"}};
1501 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames1
);
1502 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames2
);
1503 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames3
);
1504 set_stream(stream
.Pass());
1507 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1508 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1512 false, WebSocketFrameHeader::kOpCodeText
, AsVector("THREE")));
1516 false, WebSocketFrameHeader::kOpCodeContinuation
, AsVector(" ")));
1517 EXPECT_CALL(*event_interface_
,
1519 WebSocketFrameHeader::kOpCodeContinuation
,
1520 AsVector("SMALL")));
1524 false, WebSocketFrameHeader::kOpCodeContinuation
, AsVector(" ")));
1525 EXPECT_CALL(*event_interface_
,
1527 WebSocketFrameHeader::kOpCodeContinuation
,
1528 AsVector("FRAMES")));
1531 CreateChannelAndConnectSuccessfully();
1532 base::MessageLoop::current()->RunUntilIdle();
1535 // A message can consist of one frame with NULL payload.
1536 TEST_F(WebSocketChannelEventInterfaceTest
, NullMessage
) {
1537 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1538 new ReadableFakeWebSocketStream
);
1539 static const InitFrame frames
[] = {
1540 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, NULL
}};
1541 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1542 set_stream(stream
.Pass());
1543 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1544 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1547 OnDataFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("")));
1548 CreateChannelAndConnectSuccessfully();
1551 // Connection closed by the remote host without a closing handshake.
1552 TEST_F(WebSocketChannelEventInterfaceTest
, AsyncAbnormalClosure
) {
1553 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1554 new ReadableFakeWebSocketStream
);
1555 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC
,
1556 ERR_CONNECTION_CLOSED
);
1557 set_stream(stream
.Pass());
1560 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1561 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1562 EXPECT_CALL(*event_interface_
,
1563 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, _
));
1566 CreateChannelAndConnectSuccessfully();
1567 base::MessageLoop::current()->RunUntilIdle();
1570 // A connection reset should produce the same event as an unexpected closure.
1571 TEST_F(WebSocketChannelEventInterfaceTest
, ConnectionReset
) {
1572 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1573 new ReadableFakeWebSocketStream
);
1574 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC
,
1575 ERR_CONNECTION_RESET
);
1576 set_stream(stream
.Pass());
1579 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1580 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1581 EXPECT_CALL(*event_interface_
,
1582 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, _
));
1585 CreateChannelAndConnectSuccessfully();
1586 base::MessageLoop::current()->RunUntilIdle();
1589 // RFC6455 5.1 "A client MUST close a connection if it detects a masked frame."
1590 TEST_F(WebSocketChannelEventInterfaceTest
, MaskedFramesAreRejected
) {
1591 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1592 new ReadableFakeWebSocketStream
);
1593 static const InitFrame frames
[] = {
1594 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "HELLO"}};
1596 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1597 set_stream(stream
.Pass());
1600 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1601 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1605 "A server must not mask any frames that it sends to the client."));
1608 CreateChannelAndConnectSuccessfully();
1609 base::MessageLoop::current()->RunUntilIdle();
1612 // RFC6455 5.2 "If an unknown opcode is received, the receiving endpoint MUST
1613 // _Fail the WebSocket Connection_."
1614 TEST_F(WebSocketChannelEventInterfaceTest
, UnknownOpCodeIsRejected
) {
1615 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1616 new ReadableFakeWebSocketStream
);
1617 static const InitFrame frames
[] = {{FINAL_FRAME
, 4, NOT_MASKED
, "HELLO"}};
1619 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1620 set_stream(stream
.Pass());
1623 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1624 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1625 EXPECT_CALL(*event_interface_
,
1626 OnFailChannel("Unrecognized frame opcode: 4"));
1629 CreateChannelAndConnectSuccessfully();
1630 base::MessageLoop::current()->RunUntilIdle();
1633 // RFC6455 5.4 "Control frames ... MAY be injected in the middle of a
1634 // fragmented message."
1635 TEST_F(WebSocketChannelEventInterfaceTest
, ControlFrameInDataMessage
) {
1636 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1637 new ReadableFakeWebSocketStream
);
1638 // We have one message of type Text split into two frames. In the middle is a
1639 // control message of type Pong.
1640 static const InitFrame frames1
[] = {
1641 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
1642 NOT_MASKED
, "SPLIT "}};
1643 static const InitFrame frames2
[] = {
1644 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
, NOT_MASKED
, ""}};
1645 static const InitFrame frames3
[] = {
1646 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
1647 NOT_MASKED
, "MESSAGE"}};
1648 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames1
);
1649 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames2
);
1650 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames3
);
1651 set_stream(stream
.Pass());
1654 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1655 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1659 false, WebSocketFrameHeader::kOpCodeText
, AsVector("SPLIT ")));
1660 EXPECT_CALL(*event_interface_
,
1662 WebSocketFrameHeader::kOpCodeContinuation
,
1663 AsVector("MESSAGE")));
1666 CreateChannelAndConnectSuccessfully();
1667 base::MessageLoop::current()->RunUntilIdle();
1670 // It seems redundant to repeat the entirety of the above test, so just test a
1671 // Pong with NULL data.
1672 TEST_F(WebSocketChannelEventInterfaceTest
, PongWithNullData
) {
1673 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1674 new ReadableFakeWebSocketStream
);
1675 static const InitFrame frames
[] = {
1676 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
, NOT_MASKED
, NULL
}};
1677 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1678 set_stream(stream
.Pass());
1679 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1680 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1682 CreateChannelAndConnectSuccessfully();
1683 base::MessageLoop::current()->RunUntilIdle();
1686 // If a frame has an invalid header, then the connection is closed and
1687 // subsequent frames must not trigger events.
1688 TEST_F(WebSocketChannelEventInterfaceTest
, FrameAfterInvalidFrame
) {
1689 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1690 new ReadableFakeWebSocketStream
);
1691 static const InitFrame frames
[] = {
1692 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "HELLO"},
1693 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, " WORLD"}};
1695 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
1696 set_stream(stream
.Pass());
1699 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1700 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1704 "A server must not mask any frames that it sends to the client."));
1707 CreateChannelAndConnectSuccessfully();
1708 base::MessageLoop::current()->RunUntilIdle();
1711 // If the renderer sends lots of small writes, we don't want to update the quota
1713 TEST_F(WebSocketChannelEventInterfaceTest
, SmallWriteDoesntUpdateQuota
) {
1714 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
1717 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1718 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1721 CreateChannelAndConnectSuccessfully();
1722 channel_
->SendFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("B"));
1725 // If we send enough to go below send_quota_low_water_mask_ we should get our
1727 TEST_F(WebSocketChannelEventInterfaceTest
, LargeWriteUpdatesQuota
) {
1728 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
1729 // We use this checkpoint object to verify that the quota update comes after
1731 Checkpoint checkpoint
;
1734 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1735 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1736 EXPECT_CALL(checkpoint
, Call(1));
1737 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1738 EXPECT_CALL(checkpoint
, Call(2));
1741 CreateChannelAndConnectSuccessfully();
1743 channel_
->SendFrame(true,
1744 WebSocketFrameHeader::kOpCodeText
,
1745 std::vector
<char>(kDefaultInitialQuota
, 'B'));
1749 // Verify that our quota actually is refreshed when we are told it is.
1750 TEST_F(WebSocketChannelEventInterfaceTest
, QuotaReallyIsRefreshed
) {
1751 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
1752 Checkpoint checkpoint
;
1755 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1756 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1757 EXPECT_CALL(checkpoint
, Call(1));
1758 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1759 EXPECT_CALL(checkpoint
, Call(2));
1760 // If quota was not really refreshed, we would get an OnDropChannel()
1762 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1763 EXPECT_CALL(checkpoint
, Call(3));
1766 CreateChannelAndConnectSuccessfully();
1768 channel_
->SendFrame(true,
1769 WebSocketFrameHeader::kOpCodeText
,
1770 std::vector
<char>(kDefaultQuotaRefreshTrigger
, 'D'));
1772 // We should have received more quota at this point.
1773 channel_
->SendFrame(true,
1774 WebSocketFrameHeader::kOpCodeText
,
1775 std::vector
<char>(kDefaultQuotaRefreshTrigger
, 'E'));
1779 // If we send more than the available quota then the connection will be closed
1781 TEST_F(WebSocketChannelEventInterfaceTest
, WriteOverQuotaIsRejected
) {
1782 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream
));
1785 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1786 EXPECT_CALL(*event_interface_
, OnFlowControl(kDefaultInitialQuota
));
1787 EXPECT_CALL(*event_interface_
, OnFailChannel("Send quota exceeded"));
1790 CreateChannelAndConnectSuccessfully();
1791 channel_
->SendFrame(true,
1792 WebSocketFrameHeader::kOpCodeText
,
1793 std::vector
<char>(kDefaultInitialQuota
+ 1, 'C'));
1796 // If a write fails, the channel is dropped.
1797 TEST_F(WebSocketChannelEventInterfaceTest
, FailedWrite
) {
1798 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream
));
1799 Checkpoint checkpoint
;
1802 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1803 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1804 EXPECT_CALL(checkpoint
, Call(1));
1805 EXPECT_CALL(*event_interface_
,
1806 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, _
));
1807 EXPECT_CALL(checkpoint
, Call(2));
1810 CreateChannelAndConnectSuccessfully();
1813 channel_
->SendFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("H"));
1817 // OnDropChannel() is called exactly once when StartClosingHandshake() is used.
1818 TEST_F(WebSocketChannelEventInterfaceTest
, SendCloseDropsChannel
) {
1819 set_stream(make_scoped_ptr(new EchoeyFakeWebSocketStream
));
1822 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1823 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1824 EXPECT_CALL(*event_interface_
,
1825 OnDropChannel(true, kWebSocketNormalClosure
, "Fred"));
1828 CreateChannelAndConnectSuccessfully();
1830 channel_
->StartClosingHandshake(kWebSocketNormalClosure
, "Fred");
1831 base::MessageLoop::current()->RunUntilIdle();
1834 // StartClosingHandshake() also works before connection completes, and calls
1836 TEST_F(WebSocketChannelEventInterfaceTest
, CloseDuringConnection
) {
1837 EXPECT_CALL(*event_interface_
,
1838 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, ""));
1840 CreateChannelAndConnect();
1841 channel_
->StartClosingHandshake(kWebSocketNormalClosure
, "Joe");
1844 // OnDropChannel() is only called once when a write() on the socket triggers a
1845 // connection reset.
1846 TEST_F(WebSocketChannelEventInterfaceTest
, OnDropChannelCalledOnce
) {
1847 set_stream(make_scoped_ptr(new ResetOnWriteFakeWebSocketStream
));
1848 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1849 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1851 EXPECT_CALL(*event_interface_
,
1852 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, ""))
1855 CreateChannelAndConnectSuccessfully();
1857 channel_
->SendFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("yt?"));
1858 base::MessageLoop::current()->RunUntilIdle();
1861 // When the remote server sends a Close frame with an empty payload,
1862 // WebSocketChannel should report code 1005, kWebSocketErrorNoStatusReceived.
1863 TEST_F(WebSocketChannelEventInterfaceTest
, CloseWithNoPayloadGivesStatus1005
) {
1864 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1865 new ReadableFakeWebSocketStream
);
1866 static const InitFrame frames
[] = {
1867 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
, ""}};
1868 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1869 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC
,
1870 ERR_CONNECTION_CLOSED
);
1871 set_stream(stream
.Pass());
1872 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1873 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1874 EXPECT_CALL(*event_interface_
, OnClosingHandshake());
1875 EXPECT_CALL(*event_interface_
,
1876 OnDropChannel(true, kWebSocketErrorNoStatusReceived
, _
));
1878 CreateChannelAndConnectSuccessfully();
1881 // A version of the above test with NULL payload.
1882 TEST_F(WebSocketChannelEventInterfaceTest
,
1883 CloseWithNullPayloadGivesStatus1005
) {
1884 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1885 new ReadableFakeWebSocketStream
);
1886 static const InitFrame frames
[] = {
1887 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
, NULL
}};
1888 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
1889 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC
,
1890 ERR_CONNECTION_CLOSED
);
1891 set_stream(stream
.Pass());
1892 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1893 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1894 EXPECT_CALL(*event_interface_
, OnClosingHandshake());
1895 EXPECT_CALL(*event_interface_
,
1896 OnDropChannel(true, kWebSocketErrorNoStatusReceived
, _
));
1898 CreateChannelAndConnectSuccessfully();
1901 // If ReadFrames() returns ERR_WS_PROTOCOL_ERROR, then the connection must be
1903 TEST_F(WebSocketChannelEventInterfaceTest
, SyncProtocolErrorGivesStatus1002
) {
1904 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1905 new ReadableFakeWebSocketStream
);
1906 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC
,
1907 ERR_WS_PROTOCOL_ERROR
);
1908 set_stream(stream
.Pass());
1909 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1910 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1912 EXPECT_CALL(*event_interface_
, OnFailChannel("Invalid frame header"));
1914 CreateChannelAndConnectSuccessfully();
1917 // Async version of above test.
1918 TEST_F(WebSocketChannelEventInterfaceTest
, AsyncProtocolErrorGivesStatus1002
) {
1919 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
1920 new ReadableFakeWebSocketStream
);
1921 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC
,
1922 ERR_WS_PROTOCOL_ERROR
);
1923 set_stream(stream
.Pass());
1924 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1925 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1927 EXPECT_CALL(*event_interface_
, OnFailChannel("Invalid frame header"));
1929 CreateChannelAndConnectSuccessfully();
1930 base::MessageLoop::current()->RunUntilIdle();
1933 TEST_F(WebSocketChannelEventInterfaceTest
, StartHandshakeRequest
) {
1936 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1937 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1938 EXPECT_CALL(*event_interface_
, OnStartOpeningHandshakeCalled());
1941 CreateChannelAndConnectSuccessfully();
1943 scoped_ptr
<WebSocketHandshakeRequestInfo
> request_info(
1944 new WebSocketHandshakeRequestInfo(GURL("ws://www.example.com/"),
1946 connect_data_
.creator
.connect_delegate
->OnStartOpeningHandshake(
1947 request_info
.Pass());
1949 base::MessageLoop::current()->RunUntilIdle();
1952 TEST_F(WebSocketChannelEventInterfaceTest
, FinishHandshakeRequest
) {
1955 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
1956 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
1957 EXPECT_CALL(*event_interface_
, OnFinishOpeningHandshakeCalled());
1960 CreateChannelAndConnectSuccessfully();
1962 scoped_refptr
<HttpResponseHeaders
> response_headers(
1963 new HttpResponseHeaders(""));
1964 scoped_ptr
<WebSocketHandshakeResponseInfo
> response_info(
1965 new WebSocketHandshakeResponseInfo(GURL("ws://www.example.com/"),
1970 connect_data_
.creator
.connect_delegate
->OnFinishOpeningHandshake(
1971 response_info
.Pass());
1972 base::MessageLoop::current()->RunUntilIdle();
1975 TEST_F(WebSocketChannelEventInterfaceTest
, FailJustAfterHandshake
) {
1978 EXPECT_CALL(*event_interface_
, OnStartOpeningHandshakeCalled());
1979 EXPECT_CALL(*event_interface_
, OnFinishOpeningHandshakeCalled());
1980 EXPECT_CALL(*event_interface_
, OnFailChannel("bye"));
1983 CreateChannelAndConnect();
1985 WebSocketStream::ConnectDelegate
* connect_delegate
=
1986 connect_data_
.creator
.connect_delegate
.get();
1987 GURL
url("ws://www.example.com/");
1988 scoped_ptr
<WebSocketHandshakeRequestInfo
> request_info(
1989 new WebSocketHandshakeRequestInfo(url
, base::Time()));
1990 scoped_refptr
<HttpResponseHeaders
> response_headers(
1991 new HttpResponseHeaders(""));
1992 scoped_ptr
<WebSocketHandshakeResponseInfo
> response_info(
1993 new WebSocketHandshakeResponseInfo(url
,
1998 connect_delegate
->OnStartOpeningHandshake(request_info
.Pass());
1999 connect_delegate
->OnFinishOpeningHandshake(response_info
.Pass());
2001 connect_delegate
->OnFailure("bye");
2002 base::MessageLoop::current()->RunUntilIdle();
2005 // Any frame after close is invalid. This test uses a Text frame. See also
2006 // test "PingAfterCloseIfRejected".
2007 TEST_F(WebSocketChannelEventInterfaceTest
, DataAfterCloseIsRejected
) {
2008 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2009 new ReadableFakeWebSocketStream
);
2010 static const InitFrame frames
[] = {
2011 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
,
2012 CLOSE_DATA(NORMAL_CLOSURE
, "OK")},
2013 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "Payload"}};
2014 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2015 set_stream(stream
.Pass());
2016 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2017 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2021 EXPECT_CALL(*event_interface_
, OnClosingHandshake());
2022 EXPECT_CALL(*event_interface_
,
2023 OnFailChannel("Data frame received after close"));
2026 CreateChannelAndConnectSuccessfully();
2029 // A Close frame with a one-byte payload elicits a specific console error
2031 TEST_F(WebSocketChannelEventInterfaceTest
, OneByteClosePayloadMessage
) {
2032 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2033 new ReadableFakeWebSocketStream
);
2034 static const InitFrame frames
[] = {
2035 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
, "\x03"}};
2036 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2037 set_stream(stream
.Pass());
2038 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2039 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2043 "Received a broken close frame containing an invalid size body."));
2045 CreateChannelAndConnectSuccessfully();
2048 // A Close frame with a reserved status code also elicits a specific console
2050 TEST_F(WebSocketChannelEventInterfaceTest
, ClosePayloadReservedStatusMessage
) {
2051 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2052 new ReadableFakeWebSocketStream
);
2053 static const InitFrame frames
[] = {
2054 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2055 NOT_MASKED
, CLOSE_DATA(ABNORMAL_CLOSURE
, "Not valid on wire")}};
2056 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2057 set_stream(stream
.Pass());
2058 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2059 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2063 "Received a broken close frame containing a reserved status code."));
2065 CreateChannelAndConnectSuccessfully();
2068 // A Close frame with invalid UTF-8 also elicits a specific console error
2070 TEST_F(WebSocketChannelEventInterfaceTest
, ClosePayloadInvalidReason
) {
2071 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2072 new ReadableFakeWebSocketStream
);
2073 static const InitFrame frames
[] = {
2074 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2075 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "\xFF")}};
2076 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2077 set_stream(stream
.Pass());
2078 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2079 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2083 "Received a broken close frame containing invalid UTF-8."));
2085 CreateChannelAndConnectSuccessfully();
2088 // The reserved bits must all be clear on received frames. Extensions should
2089 // clear the bits when they are set correctly before passing on the frame.
2090 TEST_F(WebSocketChannelEventInterfaceTest
, ReservedBitsMustNotBeSet
) {
2091 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2092 new ReadableFakeWebSocketStream
);
2093 static const InitFrame frames
[] = {
2094 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
2095 NOT_MASKED
, "sakana"}};
2096 // It is not worth adding support for reserved bits to InitFrame just for this
2097 // one test, so set the bit manually.
2098 ScopedVector
<WebSocketFrame
> raw_frames
= CreateFrameVector(frames
);
2099 raw_frames
[0]->header
.reserved1
= true;
2100 stream
->PrepareRawReadFrames(
2101 ReadableFakeWebSocketStream::SYNC
, OK
, raw_frames
.Pass());
2102 set_stream(stream
.Pass());
2103 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2104 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2105 EXPECT_CALL(*event_interface_
,
2107 "One or more reserved bits are on: reserved1 = 1, "
2108 "reserved2 = 0, reserved3 = 0"));
2110 CreateChannelAndConnectSuccessfully();
2113 // The closing handshake times out and sends an OnDropChannel event if no
2114 // response to the client Close message is received.
2115 TEST_F(WebSocketChannelEventInterfaceTest
,
2116 ClientInitiatedClosingHandshakeTimesOut
) {
2117 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2118 new ReadableFakeWebSocketStream
);
2119 stream
->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC
,
2121 set_stream(stream
.Pass());
2122 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2123 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2124 // This checkpoint object verifies that the OnDropChannel message comes after
2126 Checkpoint checkpoint
;
2127 TestClosure completion
;
2130 EXPECT_CALL(checkpoint
, Call(1));
2131 EXPECT_CALL(*event_interface_
,
2132 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, _
))
2133 .WillOnce(InvokeClosureReturnDeleted(completion
.closure()));
2135 CreateChannelAndConnectSuccessfully();
2136 // OneShotTimer is not very friendly to testing; there is no apparent way to
2137 // set an expectation on it. Instead the tests need to infer that the timeout
2138 // was fired by the behaviour of the WebSocketChannel object.
2139 channel_
->SetClosingHandshakeTimeoutForTesting(
2140 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis
));
2141 channel_
->SetUnderlyingConnectionCloseTimeoutForTesting(
2142 TimeDelta::FromMilliseconds(kVeryBigTimeoutMillis
));
2143 channel_
->StartClosingHandshake(kWebSocketNormalClosure
, "");
2145 completion
.WaitForResult();
2148 // The closing handshake times out and sends an OnDropChannel event if a Close
2149 // message is received but the connection isn't closed by the remote host.
2150 TEST_F(WebSocketChannelEventInterfaceTest
,
2151 ServerInitiatedClosingHandshakeTimesOut
) {
2152 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2153 new ReadableFakeWebSocketStream
);
2154 static const InitFrame frames
[] = {
2155 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2156 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
2157 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
2158 set_stream(stream
.Pass());
2159 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2160 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2161 Checkpoint checkpoint
;
2162 TestClosure completion
;
2165 EXPECT_CALL(checkpoint
, Call(1));
2166 EXPECT_CALL(*event_interface_
, OnClosingHandshake());
2167 EXPECT_CALL(*event_interface_
,
2168 OnDropChannel(false, kWebSocketErrorAbnormalClosure
, _
))
2169 .WillOnce(InvokeClosureReturnDeleted(completion
.closure()));
2171 CreateChannelAndConnectSuccessfully();
2172 channel_
->SetClosingHandshakeTimeoutForTesting(
2173 TimeDelta::FromMilliseconds(kVeryBigTimeoutMillis
));
2174 channel_
->SetUnderlyingConnectionCloseTimeoutForTesting(
2175 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis
));
2177 completion
.WaitForResult();
2180 // The renderer should provide us with some quota immediately, and then
2181 // WebSocketChannel calls ReadFrames as soon as the stream is available.
2182 TEST_F(WebSocketChannelStreamTest
, FlowControlEarly
) {
2183 Checkpoint checkpoint
;
2184 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2185 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2188 EXPECT_CALL(checkpoint
, Call(1));
2189 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2190 .WillOnce(Return(ERR_IO_PENDING
));
2191 EXPECT_CALL(checkpoint
, Call(2));
2194 set_stream(mock_stream_
.Pass());
2195 CreateChannelAndConnect();
2196 channel_
->SendFlowControl(kPlentyOfQuota
);
2198 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
2202 // If for some reason the connect succeeds before the renderer sends us quota,
2203 // we shouldn't call ReadFrames() immediately.
2204 // TODO(ricea): Actually we should call ReadFrames() with a small limit so we
2205 // can still handle control frames. This should be done once we have any API to
2206 // expose quota to the lower levels.
2207 TEST_F(WebSocketChannelStreamTest
, FlowControlLate
) {
2208 Checkpoint checkpoint
;
2209 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2210 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2213 EXPECT_CALL(checkpoint
, Call(1));
2214 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2215 .WillOnce(Return(ERR_IO_PENDING
));
2216 EXPECT_CALL(checkpoint
, Call(2));
2219 set_stream(mock_stream_
.Pass());
2220 CreateChannelAndConnect();
2221 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
2223 channel_
->SendFlowControl(kPlentyOfQuota
);
2227 // We should stop calling ReadFrames() when all quota is used.
2228 TEST_F(WebSocketChannelStreamTest
, FlowControlStopsReadFrames
) {
2229 static const InitFrame frames
[] = {
2230 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "FOUR"}};
2232 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2233 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2234 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2235 .WillOnce(ReturnFrames(&frames
));
2237 set_stream(mock_stream_
.Pass());
2238 CreateChannelAndConnect();
2239 channel_
->SendFlowControl(4);
2240 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
2243 // Providing extra quota causes ReadFrames() to be called again.
2244 TEST_F(WebSocketChannelStreamTest
, FlowControlStartsWithMoreQuota
) {
2245 static const InitFrame frames
[] = {
2246 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "FOUR"}};
2247 Checkpoint checkpoint
;
2249 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2250 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2253 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2254 .WillOnce(ReturnFrames(&frames
));
2255 EXPECT_CALL(checkpoint
, Call(1));
2256 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2257 .WillOnce(Return(ERR_IO_PENDING
));
2260 set_stream(mock_stream_
.Pass());
2261 CreateChannelAndConnect();
2262 channel_
->SendFlowControl(4);
2263 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
2265 channel_
->SendFlowControl(4);
2268 // ReadFrames() isn't called again until all pending data has been passed to
2270 TEST_F(WebSocketChannelStreamTest
, ReadFramesNotCalledUntilQuotaAvailable
) {
2271 static const InitFrame frames
[] = {
2272 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "FOUR"}};
2273 Checkpoint checkpoint
;
2275 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2276 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2279 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2280 .WillOnce(ReturnFrames(&frames
));
2281 EXPECT_CALL(checkpoint
, Call(1));
2282 EXPECT_CALL(checkpoint
, Call(2));
2283 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2284 .WillOnce(Return(ERR_IO_PENDING
));
2287 set_stream(mock_stream_
.Pass());
2288 CreateChannelAndConnect();
2289 channel_
->SendFlowControl(2);
2290 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
2292 channel_
->SendFlowControl(2);
2294 channel_
->SendFlowControl(2);
2297 // A message that needs to be split into frames to fit within quota should
2298 // maintain correct semantics.
2299 TEST_F(WebSocketChannelFlowControlTest
, SingleFrameMessageSplitSync
) {
2300 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2301 new ReadableFakeWebSocketStream
);
2302 static const InitFrame frames
[] = {
2303 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "FOUR"}};
2304 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2305 set_stream(stream
.Pass());
2308 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2309 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2312 OnDataFrame(false, WebSocketFrameHeader::kOpCodeText
, AsVector("FO")));
2316 false, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("U")));
2320 true, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("R")));
2323 CreateChannelAndConnectWithQuota(2);
2324 channel_
->SendFlowControl(1);
2325 channel_
->SendFlowControl(1);
2328 // The code path for async messages is slightly different, so test it
2330 TEST_F(WebSocketChannelFlowControlTest
, SingleFrameMessageSplitAsync
) {
2331 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2332 new ReadableFakeWebSocketStream
);
2333 static const InitFrame frames
[] = {
2334 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "FOUR"}};
2335 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC
, OK
, frames
);
2336 set_stream(stream
.Pass());
2337 Checkpoint checkpoint
;
2340 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2341 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2342 EXPECT_CALL(checkpoint
, Call(1));
2345 OnDataFrame(false, WebSocketFrameHeader::kOpCodeText
, AsVector("FO")));
2346 EXPECT_CALL(checkpoint
, Call(2));
2350 false, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("U")));
2351 EXPECT_CALL(checkpoint
, Call(3));
2355 true, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("R")));
2358 CreateChannelAndConnectWithQuota(2);
2360 base::MessageLoop::current()->RunUntilIdle();
2362 channel_
->SendFlowControl(1);
2364 channel_
->SendFlowControl(1);
2367 // A message split into multiple frames which is further split due to quota
2368 // restrictions should stil be correct.
2369 // TODO(ricea): The message ends up split into more frames than are strictly
2370 // necessary. The complexity/performance tradeoffs here need further
2372 TEST_F(WebSocketChannelFlowControlTest
, MultipleFrameSplit
) {
2373 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2374 new ReadableFakeWebSocketStream
);
2375 static const InitFrame frames
[] = {
2376 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
2377 NOT_MASKED
, "FIRST FRAME IS 25 BYTES. "},
2378 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
2379 NOT_MASKED
, "SECOND FRAME IS 26 BYTES. "},
2380 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
2381 NOT_MASKED
, "FINAL FRAME IS 24 BYTES."}};
2382 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2383 set_stream(stream
.Pass());
2386 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2387 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2388 EXPECT_CALL(*event_interface_
,
2390 WebSocketFrameHeader::kOpCodeText
,
2391 AsVector("FIRST FRAME IS")));
2392 EXPECT_CALL(*event_interface_
,
2394 WebSocketFrameHeader::kOpCodeContinuation
,
2395 AsVector(" 25 BYTES. ")));
2396 EXPECT_CALL(*event_interface_
,
2398 WebSocketFrameHeader::kOpCodeContinuation
,
2399 AsVector("SECOND FRAME IS 26 BYTES. ")));
2400 EXPECT_CALL(*event_interface_
,
2402 WebSocketFrameHeader::kOpCodeContinuation
,
2403 AsVector("FINAL ")));
2404 EXPECT_CALL(*event_interface_
,
2406 WebSocketFrameHeader::kOpCodeContinuation
,
2407 AsVector("FRAME IS 24 BYTES.")));
2409 CreateChannelAndConnectWithQuota(14);
2410 channel_
->SendFlowControl(43);
2411 channel_
->SendFlowControl(32);
2414 // An empty message handled when we are out of quota must not be delivered
2415 // out-of-order with respect to other messages.
2416 TEST_F(WebSocketChannelFlowControlTest
, EmptyMessageNoQuota
) {
2417 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2418 new ReadableFakeWebSocketStream
);
2419 static const InitFrame frames
[] = {
2420 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
2421 NOT_MASKED
, "FIRST MESSAGE"},
2422 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
2424 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
2425 NOT_MASKED
, "THIRD MESSAGE"}};
2426 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2427 set_stream(stream
.Pass());
2430 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2431 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2432 EXPECT_CALL(*event_interface_
,
2434 WebSocketFrameHeader::kOpCodeText
,
2435 AsVector("FIRST ")));
2436 EXPECT_CALL(*event_interface_
,
2438 WebSocketFrameHeader::kOpCodeContinuation
,
2439 AsVector("MESSAGE")));
2440 EXPECT_CALL(*event_interface_
,
2442 WebSocketFrameHeader::kOpCodeText
,
2444 EXPECT_CALL(*event_interface_
,
2446 WebSocketFrameHeader::kOpCodeText
,
2447 AsVector("THIRD MESSAGE")));
2450 CreateChannelAndConnectWithQuota(6);
2451 channel_
->SendFlowControl(128);
2454 // RFC6455 5.1 "a client MUST mask all frames that it sends to the server".
2455 // WebSocketChannel actually only sets the mask bit in the header, it doesn't
2456 // perform masking itself (not all transports actually use masking).
2457 TEST_F(WebSocketChannelStreamTest
, SentFramesAreMasked
) {
2458 static const InitFrame expected
[] = {
2459 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
2460 MASKED
, "NEEDS MASKING"}};
2461 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2462 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2463 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
)).WillOnce(Return(ERR_IO_PENDING
));
2464 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2465 .WillOnce(Return(OK
));
2467 CreateChannelAndConnectSuccessfully();
2468 channel_
->SendFrame(
2469 true, WebSocketFrameHeader::kOpCodeText
, AsVector("NEEDS MASKING"));
2472 // RFC6455 5.5.1 "The application MUST NOT send any more data frames after
2473 // sending a Close frame."
2474 TEST_F(WebSocketChannelStreamTest
, NothingIsSentAfterClose
) {
2475 static const InitFrame expected
[] = {
2476 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2477 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Success")}};
2478 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2479 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2480 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
)).WillOnce(Return(ERR_IO_PENDING
));
2481 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2482 .WillOnce(Return(OK
));
2484 CreateChannelAndConnectSuccessfully();
2485 channel_
->StartClosingHandshake(1000, "Success");
2486 channel_
->SendFrame(
2487 true, WebSocketFrameHeader::kOpCodeText
, AsVector("SHOULD BE IGNORED"));
2490 // RFC6455 5.5.1 "If an endpoint receives a Close frame and did not previously
2491 // send a Close frame, the endpoint MUST send a Close frame in response."
2492 TEST_F(WebSocketChannelStreamTest
, CloseIsEchoedBack
) {
2493 static const InitFrame frames
[] = {
2494 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2495 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Close")}};
2496 static const InitFrame expected
[] = {
2497 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2498 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Close")}};
2499 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2500 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2501 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2502 .WillOnce(ReturnFrames(&frames
))
2503 .WillRepeatedly(Return(ERR_IO_PENDING
));
2504 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2505 .WillOnce(Return(OK
));
2507 CreateChannelAndConnectSuccessfully();
2510 // The converse of the above case; after sending a Close frame, we should not
2511 // send another one.
2512 TEST_F(WebSocketChannelStreamTest
, CloseOnlySentOnce
) {
2513 static const InitFrame expected
[] = {
2514 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2515 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Close")}};
2516 static const InitFrame frames_init
[] = {
2517 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2518 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "Close")}};
2520 // We store the parameters that were passed to ReadFrames() so that we can
2521 // call them explicitly later.
2522 CompletionCallback read_callback
;
2523 ScopedVector
<WebSocketFrame
>* frames
= NULL
;
2525 // These are not interesting.
2526 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2527 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2529 // Use a checkpoint to make the ordering of events clearer.
2530 Checkpoint checkpoint
;
2533 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2534 .WillOnce(DoAll(SaveArg
<0>(&frames
),
2535 SaveArg
<1>(&read_callback
),
2536 Return(ERR_IO_PENDING
)));
2537 EXPECT_CALL(checkpoint
, Call(1));
2538 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2539 .WillOnce(Return(OK
));
2540 EXPECT_CALL(checkpoint
, Call(2));
2541 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2542 .WillOnce(Return(ERR_IO_PENDING
));
2543 EXPECT_CALL(checkpoint
, Call(3));
2544 // WriteFrames() must not be called again. GoogleMock will ensure that the
2545 // test fails if it is.
2548 CreateChannelAndConnectSuccessfully();
2550 channel_
->StartClosingHandshake(kWebSocketNormalClosure
, "Close");
2553 *frames
= CreateFrameVector(frames_init
);
2554 read_callback
.Run(OK
);
2558 // Invalid close status codes should not be sent on the network.
2559 TEST_F(WebSocketChannelStreamTest
, InvalidCloseStatusCodeNotSent
) {
2560 static const InitFrame expected
[] = {
2561 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2562 MASKED
, CLOSE_DATA(SERVER_ERROR
, "")}};
2564 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2565 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2566 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2567 .WillOnce(Return(ERR_IO_PENDING
));
2569 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
));
2571 CreateChannelAndConnectSuccessfully();
2572 channel_
->StartClosingHandshake(999, "");
2575 // A Close frame with a reason longer than 123 bytes cannot be sent on the
2577 TEST_F(WebSocketChannelStreamTest
, LongCloseReasonNotSent
) {
2578 static const InitFrame expected
[] = {
2579 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2580 MASKED
, CLOSE_DATA(SERVER_ERROR
, "")}};
2582 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2583 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2584 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2585 .WillOnce(Return(ERR_IO_PENDING
));
2587 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
));
2589 CreateChannelAndConnectSuccessfully();
2590 channel_
->StartClosingHandshake(1000, std::string(124, 'A'));
2593 // We generate code 1005, kWebSocketErrorNoStatusReceived, when there is no
2594 // status in the Close message from the other side. Code 1005 is not allowed to
2595 // appear on the wire, so we should not echo it back. See test
2596 // CloseWithNoPayloadGivesStatus1005, above, for confirmation that code 1005 is
2597 // correctly generated internally.
2598 TEST_F(WebSocketChannelStreamTest
, Code1005IsNotEchoed
) {
2599 static const InitFrame frames
[] = {
2600 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
, ""}};
2601 static const InitFrame expected
[] = {
2602 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
, ""}};
2603 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2604 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2605 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2606 .WillOnce(ReturnFrames(&frames
))
2607 .WillRepeatedly(Return(ERR_IO_PENDING
));
2608 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2609 .WillOnce(Return(OK
));
2611 CreateChannelAndConnectSuccessfully();
2614 TEST_F(WebSocketChannelStreamTest
, Code1005IsNotEchoedNull
) {
2615 static const InitFrame frames
[] = {
2616 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, NOT_MASKED
, NULL
}};
2617 static const InitFrame expected
[] = {
2618 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
, ""}};
2619 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2620 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2621 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2622 .WillOnce(ReturnFrames(&frames
))
2623 .WillRepeatedly(Return(ERR_IO_PENDING
));
2624 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2625 .WillOnce(Return(OK
));
2627 CreateChannelAndConnectSuccessfully();
2630 // Receiving an invalid UTF-8 payload in a Close frame causes us to fail the
2632 TEST_F(WebSocketChannelStreamTest
, CloseFrameInvalidUtf8
) {
2633 static const InitFrame frames
[] = {
2634 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2635 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "\xFF")}};
2636 static const InitFrame expected
[] = {
2637 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2638 MASKED
, CLOSE_DATA(PROTOCOL_ERROR
, "Invalid UTF-8 in Close frame")}};
2640 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2641 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2642 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2643 .WillOnce(ReturnFrames(&frames
))
2644 .WillRepeatedly(Return(ERR_IO_PENDING
));
2645 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2646 .WillOnce(Return(OK
));
2647 EXPECT_CALL(*mock_stream_
, Close());
2649 CreateChannelAndConnectSuccessfully();
2652 // RFC6455 5.5.2 "Upon receipt of a Ping frame, an endpoint MUST send a Pong
2653 // frame in response"
2654 // 5.5.3 "A Pong frame sent in response to a Ping frame must have identical
2655 // "Application data" as found in the message body of the Ping frame being
2657 TEST_F(WebSocketChannelStreamTest
, PingRepliedWithPong
) {
2658 static const InitFrame frames
[] = {
2659 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePing
,
2660 NOT_MASKED
, "Application data"}};
2661 static const InitFrame expected
[] = {
2662 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
,
2663 MASKED
, "Application data"}};
2664 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2665 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2666 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2667 .WillOnce(ReturnFrames(&frames
))
2668 .WillRepeatedly(Return(ERR_IO_PENDING
));
2669 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2670 .WillOnce(Return(OK
));
2672 CreateChannelAndConnectSuccessfully();
2675 // A ping with a NULL payload should be responded to with a Pong with a NULL
2677 TEST_F(WebSocketChannelStreamTest
, NullPingRepliedWithNullPong
) {
2678 static const InitFrame frames
[] = {
2679 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePing
, NOT_MASKED
, NULL
}};
2680 static const InitFrame expected
[] = {
2681 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
, MASKED
, NULL
}};
2682 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2683 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2684 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2685 .WillOnce(ReturnFrames(&frames
))
2686 .WillRepeatedly(Return(ERR_IO_PENDING
));
2687 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2688 .WillOnce(Return(OK
));
2690 CreateChannelAndConnectSuccessfully();
2693 TEST_F(WebSocketChannelStreamTest
, PongInTheMiddleOfDataMessage
) {
2694 static const InitFrame frames
[] = {
2695 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePing
,
2696 NOT_MASKED
, "Application data"}};
2697 static const InitFrame expected1
[] = {
2698 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "Hello "}};
2699 static const InitFrame expected2
[] = {
2700 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePong
,
2701 MASKED
, "Application data"}};
2702 static const InitFrame expected3
[] = {
2703 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
2705 ScopedVector
<WebSocketFrame
>* read_frames
;
2706 CompletionCallback read_callback
;
2707 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2708 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2709 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2710 .WillOnce(DoAll(SaveArg
<0>(&read_frames
),
2711 SaveArg
<1>(&read_callback
),
2712 Return(ERR_IO_PENDING
)))
2713 .WillRepeatedly(Return(ERR_IO_PENDING
));
2717 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected1
), _
))
2718 .WillOnce(Return(OK
));
2719 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected2
), _
))
2720 .WillOnce(Return(OK
));
2721 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected3
), _
))
2722 .WillOnce(Return(OK
));
2725 CreateChannelAndConnectSuccessfully();
2726 channel_
->SendFrame(
2727 false, WebSocketFrameHeader::kOpCodeText
, AsVector("Hello "));
2728 *read_frames
= CreateFrameVector(frames
);
2729 read_callback
.Run(OK
);
2730 channel_
->SendFrame(
2731 true, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("World"));
2734 // WriteFrames() may not be called until the previous write has completed.
2735 // WebSocketChannel must buffer writes that happen in the meantime.
2736 TEST_F(WebSocketChannelStreamTest
, WriteFramesOneAtATime
) {
2737 static const InitFrame expected1
[] = {
2738 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "Hello "}};
2739 static const InitFrame expected2
[] = {
2740 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "World"}};
2741 CompletionCallback write_callback
;
2742 Checkpoint checkpoint
;
2744 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2745 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2746 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
)).WillOnce(Return(ERR_IO_PENDING
));
2749 EXPECT_CALL(checkpoint
, Call(1));
2750 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected1
), _
))
2751 .WillOnce(DoAll(SaveArg
<1>(&write_callback
), Return(ERR_IO_PENDING
)));
2752 EXPECT_CALL(checkpoint
, Call(2));
2753 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected2
), _
))
2754 .WillOnce(Return(ERR_IO_PENDING
));
2755 EXPECT_CALL(checkpoint
, Call(3));
2758 CreateChannelAndConnectSuccessfully();
2760 channel_
->SendFrame(
2761 false, WebSocketFrameHeader::kOpCodeText
, AsVector("Hello "));
2762 channel_
->SendFrame(
2763 true, WebSocketFrameHeader::kOpCodeText
, AsVector("World"));
2765 write_callback
.Run(OK
);
2769 // WebSocketChannel must buffer frames while it is waiting for a write to
2770 // complete, and then send them in a single batch. The batching behaviour is
2771 // important to get good throughput in the "many small messages" case.
2772 TEST_F(WebSocketChannelStreamTest
, WaitingMessagesAreBatched
) {
2773 static const char input_letters
[] = "Hello";
2774 static const InitFrame expected1
[] = {
2775 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "H"}};
2776 static const InitFrame expected2
[] = {
2777 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "e"},
2778 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "l"},
2779 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "l"},
2780 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, MASKED
, "o"}};
2781 CompletionCallback write_callback
;
2783 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2784 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2785 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
)).WillOnce(Return(ERR_IO_PENDING
));
2788 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected1
), _
))
2789 .WillOnce(DoAll(SaveArg
<1>(&write_callback
), Return(ERR_IO_PENDING
)));
2790 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected2
), _
))
2791 .WillOnce(Return(ERR_IO_PENDING
));
2794 CreateChannelAndConnectSuccessfully();
2795 for (size_t i
= 0; i
< strlen(input_letters
); ++i
) {
2796 channel_
->SendFrame(true,
2797 WebSocketFrameHeader::kOpCodeText
,
2798 std::vector
<char>(1, input_letters
[i
]));
2800 write_callback
.Run(OK
);
2803 // When the renderer sends more on a channel than it has quota for, we send the
2804 // remote server a kWebSocketErrorGoingAway error code.
2805 TEST_F(WebSocketChannelStreamTest
, SendGoingAwayOnRendererQuotaExceeded
) {
2806 static const InitFrame expected
[] = {
2807 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
2808 MASKED
, CLOSE_DATA(GOING_AWAY
, "")}};
2809 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2810 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2811 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
)).WillOnce(Return(ERR_IO_PENDING
));
2812 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2813 .WillOnce(Return(OK
));
2814 EXPECT_CALL(*mock_stream_
, Close());
2816 CreateChannelAndConnectSuccessfully();
2817 channel_
->SendFrame(true,
2818 WebSocketFrameHeader::kOpCodeText
,
2819 std::vector
<char>(kDefaultInitialQuota
+ 1, 'C'));
2822 // For convenience, most of these tests use Text frames. However, the WebSocket
2823 // protocol also has Binary frames and those need to be 8-bit clean. For the
2824 // sake of completeness, this test verifies that they are.
2825 TEST_F(WebSocketChannelStreamTest
, WrittenBinaryFramesAre8BitClean
) {
2826 ScopedVector
<WebSocketFrame
>* frames
= NULL
;
2828 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2829 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2830 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
)).WillOnce(Return(ERR_IO_PENDING
));
2831 EXPECT_CALL(*mock_stream_
, WriteFrames(_
, _
))
2832 .WillOnce(DoAll(SaveArg
<0>(&frames
), Return(ERR_IO_PENDING
)));
2834 CreateChannelAndConnectSuccessfully();
2835 channel_
->SendFrame(
2837 WebSocketFrameHeader::kOpCodeBinary
,
2838 std::vector
<char>(kBinaryBlob
, kBinaryBlob
+ kBinaryBlobSize
));
2839 ASSERT_TRUE(frames
!= NULL
);
2840 ASSERT_EQ(1U, frames
->size());
2841 const WebSocketFrame
* out_frame
= (*frames
)[0];
2842 EXPECT_EQ(kBinaryBlobSize
, out_frame
->header
.payload_length
);
2843 ASSERT_TRUE(out_frame
->data
.get());
2844 EXPECT_EQ(0, memcmp(kBinaryBlob
, out_frame
->data
->data(), kBinaryBlobSize
));
2847 // Test the read path for 8-bit cleanliness as well.
2848 TEST_F(WebSocketChannelEventInterfaceTest
, ReadBinaryFramesAre8BitClean
) {
2849 scoped_ptr
<WebSocketFrame
> frame(
2850 new WebSocketFrame(WebSocketFrameHeader::kOpCodeBinary
));
2851 WebSocketFrameHeader
& frame_header
= frame
->header
;
2852 frame_header
.final
= true;
2853 frame_header
.payload_length
= kBinaryBlobSize
;
2854 frame
->data
= new IOBuffer(kBinaryBlobSize
);
2855 memcpy(frame
->data
->data(), kBinaryBlob
, kBinaryBlobSize
);
2856 ScopedVector
<WebSocketFrame
> frames
;
2857 frames
.push_back(frame
.Pass());
2858 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2859 new ReadableFakeWebSocketStream
);
2860 stream
->PrepareRawReadFrames(
2861 ReadableFakeWebSocketStream::SYNC
, OK
, frames
.Pass());
2862 set_stream(stream
.Pass());
2863 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2864 EXPECT_CALL(*event_interface_
, OnFlowControl(_
));
2865 EXPECT_CALL(*event_interface_
,
2867 WebSocketFrameHeader::kOpCodeBinary
,
2868 std::vector
<char>(kBinaryBlob
,
2869 kBinaryBlob
+ kBinaryBlobSize
)));
2871 CreateChannelAndConnectSuccessfully();
2874 // Invalid UTF-8 is not permitted in Text frames.
2875 TEST_F(WebSocketChannelSendUtf8Test
, InvalidUtf8Rejected
) {
2878 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2880 CreateChannelAndConnectSuccessfully();
2882 channel_
->SendFrame(
2883 true, WebSocketFrameHeader::kOpCodeText
, AsVector("\xff"));
2886 // A Text message cannot end with a partial UTF-8 character.
2887 TEST_F(WebSocketChannelSendUtf8Test
, IncompleteCharacterInFinalFrame
) {
2890 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2892 CreateChannelAndConnectSuccessfully();
2894 channel_
->SendFrame(
2895 true, WebSocketFrameHeader::kOpCodeText
, AsVector("\xc2"));
2898 // A non-final Text frame may end with a partial UTF-8 character (compare to
2900 TEST_F(WebSocketChannelSendUtf8Test
, IncompleteCharacterInNonFinalFrame
) {
2901 CreateChannelAndConnectSuccessfully();
2903 channel_
->SendFrame(
2904 false, WebSocketFrameHeader::kOpCodeText
, AsVector("\xc2"));
2907 // UTF-8 parsing context must be retained between frames.
2908 TEST_F(WebSocketChannelSendUtf8Test
, ValidCharacterSplitBetweenFrames
) {
2909 CreateChannelAndConnectSuccessfully();
2911 channel_
->SendFrame(
2912 false, WebSocketFrameHeader::kOpCodeText
, AsVector("\xf1"));
2913 channel_
->SendFrame(true,
2914 WebSocketFrameHeader::kOpCodeContinuation
,
2915 AsVector("\x80\xa0\xbf"));
2918 // Similarly, an invalid character should be detected even if split.
2919 TEST_F(WebSocketChannelSendUtf8Test
, InvalidCharacterSplit
) {
2922 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2924 CreateChannelAndConnectSuccessfully();
2926 channel_
->SendFrame(
2927 false, WebSocketFrameHeader::kOpCodeText
, AsVector("\xe1"));
2928 channel_
->SendFrame(true,
2929 WebSocketFrameHeader::kOpCodeContinuation
,
2930 AsVector("\x80\xa0\xbf"));
2933 // An invalid character must be detected in continuation frames.
2934 TEST_F(WebSocketChannelSendUtf8Test
, InvalidByteInContinuation
) {
2937 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2939 CreateChannelAndConnectSuccessfully();
2941 channel_
->SendFrame(
2942 false, WebSocketFrameHeader::kOpCodeText
, AsVector("foo"));
2943 channel_
->SendFrame(
2944 false, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("bar"));
2945 channel_
->SendFrame(
2946 true, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("\xff"));
2949 // However, continuation frames of a Binary frame will not be tested for UTF-8
2951 TEST_F(WebSocketChannelSendUtf8Test
, BinaryContinuationNotChecked
) {
2952 CreateChannelAndConnectSuccessfully();
2954 channel_
->SendFrame(
2955 false, WebSocketFrameHeader::kOpCodeBinary
, AsVector("foo"));
2956 channel_
->SendFrame(
2957 false, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("bar"));
2958 channel_
->SendFrame(
2959 true, WebSocketFrameHeader::kOpCodeContinuation
, AsVector("\xff"));
2962 // Multiple text messages can be validated without the validation state getting
2964 TEST_F(WebSocketChannelSendUtf8Test
, ValidateMultipleTextMessages
) {
2965 CreateChannelAndConnectSuccessfully();
2967 channel_
->SendFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("foo"));
2968 channel_
->SendFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("bar"));
2971 // UTF-8 validation is enforced on received Text frames.
2972 TEST_F(WebSocketChannelEventInterfaceTest
, ReceivedInvalidUtf8
) {
2973 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
2974 new ReadableFakeWebSocketStream
);
2975 static const InitFrame frames
[] = {
2976 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xff"}};
2977 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
2978 set_stream(stream
.Pass());
2980 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
2981 EXPECT_CALL(*event_interface_
, OnFlowControl(kDefaultInitialQuota
));
2982 EXPECT_CALL(*event_interface_
,
2983 OnFailChannel("Could not decode a text frame as UTF-8."));
2985 CreateChannelAndConnectSuccessfully();
2986 base::MessageLoop::current()->RunUntilIdle();
2989 // Invalid UTF-8 is not sent over the network.
2990 TEST_F(WebSocketChannelStreamTest
, InvalidUtf8TextFrameNotSent
) {
2991 static const InitFrame expected
[] = {{FINAL_FRAME
,
2992 WebSocketFrameHeader::kOpCodeClose
,
2993 MASKED
, CLOSE_DATA(GOING_AWAY
, "")}};
2994 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
2995 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
2996 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
2997 .WillRepeatedly(Return(ERR_IO_PENDING
));
2998 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
2999 .WillOnce(Return(OK
));
3000 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3002 CreateChannelAndConnectSuccessfully();
3004 channel_
->SendFrame(
3005 true, WebSocketFrameHeader::kOpCodeText
, AsVector("\xff"));
3008 // The rest of the tests for receiving invalid UTF-8 test the communication with
3009 // the server. Since there is only one code path, it would be redundant to
3010 // perform the same tests on the EventInterface as well.
3012 // If invalid UTF-8 is received in a Text frame, the connection is failed.
3013 TEST_F(WebSocketChannelReceiveUtf8Test
, InvalidTextFrameRejected
) {
3014 static const InitFrame frames
[] = {
3015 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xff"}};
3016 static const InitFrame expected
[] = {
3017 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
,
3018 CLOSE_DATA(PROTOCOL_ERROR
, "Invalid UTF-8 in text frame")}};
3021 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3022 .WillOnce(ReturnFrames(&frames
))
3023 .WillRepeatedly(Return(ERR_IO_PENDING
));
3024 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3025 .WillOnce(Return(OK
));
3026 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3029 CreateChannelAndConnectSuccessfully();
3032 // A received Text message is not permitted to end with a partial UTF-8
3034 TEST_F(WebSocketChannelReceiveUtf8Test
, IncompleteCharacterReceived
) {
3035 static const InitFrame frames
[] = {
3036 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xc2"}};
3037 static const InitFrame expected
[] = {
3038 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
,
3039 CLOSE_DATA(PROTOCOL_ERROR
, "Invalid UTF-8 in text frame")}};
3040 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3041 .WillOnce(ReturnFrames(&frames
))
3042 .WillRepeatedly(Return(ERR_IO_PENDING
));
3043 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3044 .WillOnce(Return(OK
));
3045 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3047 CreateChannelAndConnectSuccessfully();
3050 // However, a non-final Text frame may end with a partial UTF-8 character.
3051 TEST_F(WebSocketChannelReceiveUtf8Test
, IncompleteCharacterIncompleteMessage
) {
3052 static const InitFrame frames
[] = {
3053 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xc2"}};
3054 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3055 .WillOnce(ReturnFrames(&frames
))
3056 .WillRepeatedly(Return(ERR_IO_PENDING
));
3058 CreateChannelAndConnectSuccessfully();
3061 // However, it will become an error if it is followed by an empty final frame.
3062 TEST_F(WebSocketChannelReceiveUtf8Test
, TricksyIncompleteCharacter
) {
3063 static const InitFrame frames
[] = {
3064 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xc2"},
3065 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
, NOT_MASKED
, ""}};
3066 static const InitFrame expected
[] = {
3067 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
,
3068 CLOSE_DATA(PROTOCOL_ERROR
, "Invalid UTF-8 in text frame")}};
3069 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3070 .WillOnce(ReturnFrames(&frames
))
3071 .WillRepeatedly(Return(ERR_IO_PENDING
));
3072 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3073 .WillOnce(Return(OK
));
3074 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3076 CreateChannelAndConnectSuccessfully();
3079 // UTF-8 parsing context must be retained between received frames of the same
3081 TEST_F(WebSocketChannelReceiveUtf8Test
, ReceivedParsingContextRetained
) {
3082 static const InitFrame frames
[] = {
3083 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xf1"},
3084 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3085 NOT_MASKED
, "\x80\xa0\xbf"}};
3086 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3087 .WillOnce(ReturnFrames(&frames
))
3088 .WillRepeatedly(Return(ERR_IO_PENDING
));
3090 CreateChannelAndConnectSuccessfully();
3093 // An invalid character must be detected even if split between frames.
3094 TEST_F(WebSocketChannelReceiveUtf8Test
, SplitInvalidCharacterReceived
) {
3095 static const InitFrame frames
[] = {
3096 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "\xe1"},
3097 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3098 NOT_MASKED
, "\x80\xa0\xbf"}};
3099 static const InitFrame expected
[] = {
3100 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
,
3101 CLOSE_DATA(PROTOCOL_ERROR
, "Invalid UTF-8 in text frame")}};
3102 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3103 .WillOnce(ReturnFrames(&frames
))
3104 .WillRepeatedly(Return(ERR_IO_PENDING
));
3105 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3106 .WillOnce(Return(OK
));
3107 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3109 CreateChannelAndConnectSuccessfully();
3112 // An invalid character received in a continuation frame must be detected.
3113 TEST_F(WebSocketChannelReceiveUtf8Test
, InvalidReceivedIncontinuation
) {
3114 static const InitFrame frames
[] = {
3115 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "foo"},
3116 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3118 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3119 NOT_MASKED
, "\xff"}};
3120 static const InitFrame expected
[] = {
3121 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
, MASKED
,
3122 CLOSE_DATA(PROTOCOL_ERROR
, "Invalid UTF-8 in text frame")}};
3123 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3124 .WillOnce(ReturnFrames(&frames
))
3125 .WillRepeatedly(Return(ERR_IO_PENDING
));
3126 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3127 .WillOnce(Return(OK
));
3128 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3130 CreateChannelAndConnectSuccessfully();
3133 // Continuations of binary frames must not be tested for UTF-8 validity.
3134 TEST_F(WebSocketChannelReceiveUtf8Test
, ReceivedBinaryNotUtf8Tested
) {
3135 static const InitFrame frames
[] = {
3136 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeBinary
, NOT_MASKED
, "foo"},
3137 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3139 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3140 NOT_MASKED
, "\xff"}};
3141 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3142 .WillOnce(ReturnFrames(&frames
))
3143 .WillRepeatedly(Return(ERR_IO_PENDING
));
3145 CreateChannelAndConnectSuccessfully();
3148 // Multiple Text messages can be validated.
3149 TEST_F(WebSocketChannelReceiveUtf8Test
, ValidateMultipleReceived
) {
3150 static const InitFrame frames
[] = {
3151 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "foo"},
3152 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, "bar"}};
3153 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3154 .WillOnce(ReturnFrames(&frames
))
3155 .WillRepeatedly(Return(ERR_IO_PENDING
));
3157 CreateChannelAndConnectSuccessfully();
3160 // A new data message cannot start in the middle of another data message.
3161 TEST_F(WebSocketChannelEventInterfaceTest
, BogusContinuation
) {
3162 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
3163 new ReadableFakeWebSocketStream
);
3164 static const InitFrame frames
[] = {
3165 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeBinary
,
3166 NOT_MASKED
, "frame1"},
3167 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
,
3168 NOT_MASKED
, "frame2"}};
3169 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
3170 set_stream(stream
.Pass());
3172 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
3173 EXPECT_CALL(*event_interface_
, OnFlowControl(kDefaultInitialQuota
));
3177 false, WebSocketFrameHeader::kOpCodeBinary
, AsVector("frame1")));
3181 "Received start of new message but previous message is unfinished."));
3183 CreateChannelAndConnectSuccessfully();
3186 // A new message cannot start with a Continuation frame.
3187 TEST_F(WebSocketChannelEventInterfaceTest
, MessageStartingWithContinuation
) {
3188 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
3189 new ReadableFakeWebSocketStream
);
3190 static const InitFrame frames
[] = {
3191 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3192 NOT_MASKED
, "continuation"}};
3193 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
3194 set_stream(stream
.Pass());
3196 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
3197 EXPECT_CALL(*event_interface_
, OnFlowControl(kDefaultInitialQuota
));
3198 EXPECT_CALL(*event_interface_
,
3199 OnFailChannel("Received unexpected continuation frame."));
3201 CreateChannelAndConnectSuccessfully();
3204 // A frame passed to the renderer must be either non-empty or have the final bit
3206 TEST_F(WebSocketChannelEventInterfaceTest
, DataFramesNonEmptyOrFinal
) {
3207 scoped_ptr
<ReadableFakeWebSocketStream
> stream(
3208 new ReadableFakeWebSocketStream
);
3209 static const InitFrame frames
[] = {
3210 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeText
, NOT_MASKED
, ""},
3211 {NOT_FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
,
3213 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeContinuation
, NOT_MASKED
, ""}};
3214 stream
->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC
, OK
, frames
);
3215 set_stream(stream
.Pass());
3217 EXPECT_CALL(*event_interface_
, OnAddChannelResponse(_
, _
));
3218 EXPECT_CALL(*event_interface_
, OnFlowControl(kDefaultInitialQuota
));
3221 OnDataFrame(true, WebSocketFrameHeader::kOpCodeText
, AsVector("")));
3223 CreateChannelAndConnectSuccessfully();
3226 // Calls to OnSSLCertificateError() must be passed through to the event
3227 // interface with the correct URL attached.
3228 TEST_F(WebSocketChannelEventInterfaceTest
, OnSSLCertificateErrorCalled
) {
3229 const GURL
wss_url("wss://example.com/sslerror");
3230 connect_data_
.socket_url
= wss_url
;
3231 const SSLInfo ssl_info
;
3232 const bool fatal
= true;
3233 scoped_ptr
<WebSocketEventInterface::SSLErrorCallbacks
> fake_callbacks(
3234 new FakeSSLErrorCallbacks
);
3236 EXPECT_CALL(*event_interface_
,
3237 OnSSLCertificateErrorCalled(NotNull(), wss_url
, _
, fatal
));
3239 CreateChannelAndConnect();
3240 connect_data_
.creator
.connect_delegate
->OnSSLCertificateError(
3241 fake_callbacks
.Pass(), ssl_info
, fatal
);
3244 // If we receive another frame after Close, it is not valid. It is not
3245 // completely clear what behaviour is required from the standard in this case,
3246 // but the current implementation fails the connection. Since a Close has
3247 // already been sent, this just means closing the connection.
3248 TEST_F(WebSocketChannelStreamTest
, PingAfterCloseIsRejected
) {
3249 static const InitFrame frames
[] = {
3250 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3251 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")},
3252 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodePing
,
3253 NOT_MASKED
, "Ping body"}};
3254 static const InitFrame expected
[] = {
3255 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3256 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
3257 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
3258 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
3259 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3260 .WillOnce(ReturnFrames(&frames
))
3261 .WillRepeatedly(Return(ERR_IO_PENDING
));
3263 // We only need to verify the relative order of WriteFrames() and
3264 // Close(). The current implementation calls WriteFrames() for the Close
3265 // frame before calling ReadFrames() again, but that is an implementation
3266 // detail and better not to consider required behaviour.
3268 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3269 .WillOnce(Return(OK
));
3270 EXPECT_CALL(*mock_stream_
, Close()).Times(1);
3273 CreateChannelAndConnectSuccessfully();
3276 // A protocol error from the remote server should result in a close frame with
3277 // status 1002, followed by the connection closing.
3278 TEST_F(WebSocketChannelStreamTest
, ProtocolError
) {
3279 static const InitFrame expected
[] = {
3280 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3281 MASKED
, CLOSE_DATA(PROTOCOL_ERROR
, "WebSocket Protocol Error")}};
3282 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
3283 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
3284 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3285 .WillOnce(Return(ERR_WS_PROTOCOL_ERROR
));
3286 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3287 .WillOnce(Return(OK
));
3288 EXPECT_CALL(*mock_stream_
, Close());
3290 CreateChannelAndConnectSuccessfully();
3293 // Set the closing handshake timeout to a very tiny value before connecting.
3294 class WebSocketChannelStreamTimeoutTest
: public WebSocketChannelStreamTest
{
3296 WebSocketChannelStreamTimeoutTest() {}
3298 void CreateChannelAndConnectSuccessfully() override
{
3299 set_stream(mock_stream_
.Pass());
3300 CreateChannelAndConnect();
3301 channel_
->SendFlowControl(kPlentyOfQuota
);
3302 channel_
->SetClosingHandshakeTimeoutForTesting(
3303 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis
));
3304 channel_
->SetUnderlyingConnectionCloseTimeoutForTesting(
3305 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis
));
3306 connect_data_
.creator
.connect_delegate
->OnSuccess(stream_
.Pass());
3310 // In this case the server initiates the closing handshake with a Close
3311 // message. WebSocketChannel responds with a matching Close message, and waits
3312 // for the server to close the TCP/IP connection. The server never closes the
3313 // connection, so the closing handshake times out and WebSocketChannel closes
3314 // the connection itself.
3315 TEST_F(WebSocketChannelStreamTimeoutTest
, ServerInitiatedCloseTimesOut
) {
3316 static const InitFrame frames
[] = {
3317 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3318 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
3319 static const InitFrame expected
[] = {
3320 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3321 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
3322 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
3323 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
3324 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3325 .WillOnce(ReturnFrames(&frames
))
3326 .WillRepeatedly(Return(ERR_IO_PENDING
));
3327 Checkpoint checkpoint
;
3328 TestClosure completion
;
3331 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3332 .WillOnce(Return(OK
));
3333 EXPECT_CALL(checkpoint
, Call(1));
3334 EXPECT_CALL(*mock_stream_
, Close())
3335 .WillOnce(InvokeClosure(completion
.closure()));
3338 CreateChannelAndConnectSuccessfully();
3340 completion
.WaitForResult();
3343 // In this case the client initiates the closing handshake by sending a Close
3344 // message. WebSocketChannel waits for a Close message in response from the
3345 // server. The server never responds to the Close message, so the closing
3346 // handshake times out and WebSocketChannel closes the connection.
3347 TEST_F(WebSocketChannelStreamTimeoutTest
, ClientInitiatedCloseTimesOut
) {
3348 static const InitFrame expected
[] = {
3349 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3350 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
3351 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
3352 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
3353 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3354 .WillRepeatedly(Return(ERR_IO_PENDING
));
3355 TestClosure completion
;
3358 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3359 .WillOnce(Return(OK
));
3360 EXPECT_CALL(*mock_stream_
, Close())
3361 .WillOnce(InvokeClosure(completion
.closure()));
3364 CreateChannelAndConnectSuccessfully();
3365 channel_
->StartClosingHandshake(kWebSocketNormalClosure
, "OK");
3366 completion
.WaitForResult();
3369 // In this case the client initiates the closing handshake and the server
3370 // responds with a matching Close message. WebSocketChannel waits for the server
3371 // to close the TCP/IP connection, but it never does. The closing handshake
3372 // times out and WebSocketChannel closes the connection.
3373 TEST_F(WebSocketChannelStreamTimeoutTest
, ConnectionCloseTimesOut
) {
3374 static const InitFrame expected
[] = {
3375 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3376 MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
3377 static const InitFrame frames
[] = {
3378 {FINAL_FRAME
, WebSocketFrameHeader::kOpCodeClose
,
3379 NOT_MASKED
, CLOSE_DATA(NORMAL_CLOSURE
, "OK")}};
3380 EXPECT_CALL(*mock_stream_
, GetSubProtocol()).Times(AnyNumber());
3381 EXPECT_CALL(*mock_stream_
, GetExtensions()).Times(AnyNumber());
3382 TestClosure completion
;
3383 ScopedVector
<WebSocketFrame
>* read_frames
= NULL
;
3384 CompletionCallback read_callback
;
3387 // Copy the arguments to ReadFrames so that the test can call the callback
3388 // after it has send the close message.
3389 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3390 .WillOnce(DoAll(SaveArg
<0>(&read_frames
),
3391 SaveArg
<1>(&read_callback
),
3392 Return(ERR_IO_PENDING
)));
3393 // The first real event that happens is the client sending the Close
3395 EXPECT_CALL(*mock_stream_
, WriteFrames(EqualsFrames(expected
), _
))
3396 .WillOnce(Return(OK
));
3397 // The |read_frames| callback is called (from this test case) at this
3398 // point. ReadFrames is called again by WebSocketChannel, waiting for
3399 // ERR_CONNECTION_CLOSED.
3400 EXPECT_CALL(*mock_stream_
, ReadFrames(_
, _
))
3401 .WillOnce(Return(ERR_IO_PENDING
));
3402 // The timeout happens and so WebSocketChannel closes the stream.
3403 EXPECT_CALL(*mock_stream_
, Close())
3404 .WillOnce(InvokeClosure(completion
.closure()));
3407 CreateChannelAndConnectSuccessfully();
3408 channel_
->StartClosingHandshake(kWebSocketNormalClosure
, "OK");
3409 ASSERT_TRUE(read_frames
);
3410 // Provide the "Close" message from the server.
3411 *read_frames
= CreateFrameVector(frames
);
3412 read_callback
.Run(OK
);
3413 completion
.WaitForResult();