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"
13 #include "base/bind.h"
14 #include "base/bind_helpers.h"
15 #include "base/callback.h"
16 #include "base/location.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/scoped_vector.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/message_loop/message_loop.h"
21 #include "base/strings/string_piece.h"
22 #include "net/base/net_errors.h"
23 #include "net/base/test_completion_callback.h"
24 #include "net/http/http_response_headers.h"
25 #include "net/url_request/url_request_context.h"
26 #include "net/websockets/websocket_errors.h"
27 #include "net/websockets/websocket_event_interface.h"
28 #include "net/websockets/websocket_handshake_request_info.h"
29 #include "net/websockets/websocket_handshake_response_info.h"
30 #include "net/websockets/websocket_mux.h"
31 #include "testing/gmock/include/gmock/gmock.h"
32 #include "testing/gtest/include/gtest/gtest.h"
35 // Hacky macros to construct the body of a Close message from a code and a
36 // string, while ensuring the result is a compile-time constant string.
37 // Use like CLOSE_DATA(NORMAL_CLOSURE, "Explanation String")
38 #define CLOSE_DATA(code, string) WEBSOCKET_CLOSE_CODE_AS_STRING_##code string
39 #define WEBSOCKET_CLOSE_CODE_AS_STRING_NORMAL_CLOSURE "\x03\xe8"
40 #define WEBSOCKET_CLOSE_CODE_AS_STRING_GOING_AWAY "\x03\xe9"
41 #define WEBSOCKET_CLOSE_CODE_AS_STRING_PROTOCOL_ERROR "\x03\xea"
42 #define WEBSOCKET_CLOSE_CODE_AS_STRING_ABNORMAL_CLOSURE "\x03\xee"
43 #define WEBSOCKET_CLOSE_CODE_AS_STRING_SERVER_ERROR "\x03\xf3"
47 // Printing helpers to allow GoogleMock to print frames. These are explicitly
48 // designed to look like the static initialisation format we use in these
49 // tests. They have to live in the net namespace in order to be found by
50 // GoogleMock; a nested anonymous namespace will not work.
52 std::ostream& operator<<(std::ostream& os, const WebSocketFrameHeader& header) {
53 return os << (header.final ? "FINAL_FRAME" : "NOT_FINAL_FRAME") << ", "
54 << header.opcode << ", "
55 << (header.masked ? "MASKED" : "NOT_MASKED");
58 std::ostream& operator<<(std::ostream& os, const WebSocketFrame& frame) {
59 os << "{" << frame.header << ", ";
61 return os << "\"" << base::StringPiece(frame.data->data(),
62 frame.header.payload_length)
68 std::ostream& operator<<(std::ostream& os,
69 const ScopedVector<WebSocketFrame>& vector) {
72 for (ScopedVector<WebSocketFrame>::const_iterator it = vector.begin();
85 std::ostream& operator<<(std::ostream& os,
86 const ScopedVector<WebSocketFrame>* vector) {
87 return os << '&' << *vector;
92 using ::base::TimeDelta;
94 using ::testing::AnyNumber;
95 using ::testing::DefaultValue;
96 using ::testing::InSequence;
97 using ::testing::MockFunction;
98 using ::testing::Return;
99 using ::testing::SaveArg;
100 using ::testing::StrictMock;
103 // A selection of characters that have traditionally been mangled in some
104 // environment or other, for testing 8-bit cleanliness.
105 const char kBinaryBlob[] = {'\n', '\r', // BACKWARDS CRNL
108 '\x80', '\xFF', // NOT VALID UTF-8
109 '\x1A', // Control-Z, EOF on DOS
111 '\x04', // EOT, special for Unix terms
112 '\x1B', // ESC, often special
114 '\'', // single-quote, special in PHP
116 const size_t kBinaryBlobSize = arraysize(kBinaryBlob);
118 // The amount of quota a new connection gets by default.
119 // TODO(ricea): If kDefaultSendQuotaHighWaterMark changes, then this value will
120 // need to be updated.
121 const size_t kDefaultInitialQuota = 1 << 17;
122 // The amount of bytes we need to send after the initial connection to trigger a
123 // quota refresh. TODO(ricea): Change this if kDefaultSendQuotaHighWaterMark or
124 // kDefaultSendQuotaLowWaterMark change.
125 const size_t kDefaultQuotaRefreshTrigger = (1 << 16) + 1;
127 // TestTimeouts::tiny_timeout() is 100ms! I could run halfway around the world
128 // in that time! I would like my tests to run a bit quicker.
129 const int kVeryTinyTimeoutMillis = 1;
131 typedef WebSocketEventInterface::ChannelState ChannelState;
132 const ChannelState CHANNEL_ALIVE = WebSocketEventInterface::CHANNEL_ALIVE;
133 const ChannelState CHANNEL_DELETED = WebSocketEventInterface::CHANNEL_DELETED;
135 // This typedef mainly exists to avoid having to repeat the "NOLINT" incantation
136 // all over the place.
137 typedef MockFunction<void(int)> Checkpoint; // NOLINT
139 // This mock is for testing expectations about how the EventInterface is used.
140 class MockWebSocketEventInterface : public WebSocketEventInterface {
142 MockWebSocketEventInterface() {}
144 MOCK_METHOD3(OnAddChannelResponse,
147 const std::string&)); // NOLINT
148 MOCK_METHOD3(OnDataFrame,
150 WebSocketMessageType,
151 const std::vector<char>&)); // NOLINT
152 MOCK_METHOD1(OnFlowControl, ChannelState(int64)); // NOLINT
153 MOCK_METHOD0(OnClosingHandshake, ChannelState(void)); // NOLINT
154 MOCK_METHOD1(OnFailChannel, ChannelState(const std::string&)); // NOLINT
155 MOCK_METHOD3(OnDropChannel,
156 ChannelState(bool, uint16, const std::string&)); // NOLINT
158 // We can't use GMock with scoped_ptr.
159 ChannelState OnStartOpeningHandshake(
160 scoped_ptr<WebSocketHandshakeRequestInfo>) OVERRIDE {
161 OnStartOpeningHandshakeCalled();
162 return CHANNEL_ALIVE;
164 ChannelState OnFinishOpeningHandshake(
165 scoped_ptr<WebSocketHandshakeResponseInfo>) OVERRIDE {
166 OnFinishOpeningHandshakeCalled();
167 return CHANNEL_ALIVE;
170 MOCK_METHOD0(OnStartOpeningHandshakeCalled, void()); // NOLINT
171 MOCK_METHOD0(OnFinishOpeningHandshakeCalled, void()); // NOLINT
174 // This fake EventInterface is for tests which need a WebSocketEventInterface
175 // implementation but are not verifying how it is used.
176 class FakeWebSocketEventInterface : public WebSocketEventInterface {
177 virtual ChannelState OnAddChannelResponse(
179 const std::string& selected_protocol,
180 const std::string& extensions) OVERRIDE {
181 return fail ? CHANNEL_DELETED : CHANNEL_ALIVE;
183 virtual ChannelState OnDataFrame(bool fin,
184 WebSocketMessageType type,
185 const std::vector<char>& data) OVERRIDE {
186 return CHANNEL_ALIVE;
188 virtual ChannelState OnFlowControl(int64 quota) OVERRIDE {
189 return CHANNEL_ALIVE;
191 virtual ChannelState OnClosingHandshake() OVERRIDE { return CHANNEL_ALIVE; }
192 virtual ChannelState OnFailChannel(const std::string& message) OVERRIDE {
193 return CHANNEL_DELETED;
195 virtual ChannelState OnDropChannel(bool was_clean,
197 const std::string& reason) OVERRIDE {
198 return CHANNEL_DELETED;
200 virtual ChannelState OnStartOpeningHandshake(
201 scoped_ptr<WebSocketHandshakeRequestInfo> request) OVERRIDE {
202 return CHANNEL_ALIVE;
204 virtual ChannelState OnFinishOpeningHandshake(
205 scoped_ptr<WebSocketHandshakeResponseInfo> response) OVERRIDE {
206 return CHANNEL_ALIVE;
210 // This fake WebSocketStream is for tests that require a WebSocketStream but are
211 // not testing the way it is used. It has minimal functionality to return
212 // the |protocol| and |extensions| that it was constructed with.
213 class FakeWebSocketStream : public WebSocketStream {
215 // Constructs with empty protocol and extensions.
216 FakeWebSocketStream() {}
218 // Constructs with specified protocol and extensions.
219 FakeWebSocketStream(const std::string& protocol,
220 const std::string& extensions)
221 : protocol_(protocol), extensions_(extensions) {}
223 virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
224 const CompletionCallback& callback) OVERRIDE {
225 return ERR_IO_PENDING;
228 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
229 const CompletionCallback& callback) OVERRIDE {
230 return ERR_IO_PENDING;
233 virtual void Close() OVERRIDE {}
235 // Returns the string passed to the constructor.
236 virtual std::string GetSubProtocol() const OVERRIDE { return protocol_; }
238 // Returns the string passed to the constructor.
239 virtual std::string GetExtensions() const OVERRIDE { return extensions_; }
242 // The string to return from GetSubProtocol().
243 std::string protocol_;
245 // The string to return from GetExtensions().
246 std::string extensions_;
249 // To make the static initialisers easier to read, we use enums rather than
251 enum IsFinal { NOT_FINAL_FRAME, FINAL_FRAME };
253 enum IsMasked { NOT_MASKED, MASKED };
255 // This is used to initialise a WebSocketFrame but is statically initialisable.
258 // Reserved fields omitted for now. Add them if you need them.
259 WebSocketFrameHeader::OpCode opcode;
262 // Will be used to create the IOBuffer member. Can be NULL for NULL data. Is a
263 // nul-terminated string for ease-of-use. |header.payload_length| is
264 // initialised from |strlen(data)|. This means it is not 8-bit clean, but this
265 // is not an issue for test data.
266 const char* const data;
270 std::ostream& operator<<(std::ostream& os, const InitFrame& frame) {
271 os << "{" << (frame.final == FINAL_FRAME ? "FINAL_FRAME" : "NOT_FINAL_FRAME")
272 << ", " << frame.opcode << ", "
273 << (frame.masked == MASKED ? "MASKED" : "NOT_MASKED") << ", ";
275 return os << "\"" << frame.data << "\"}";
277 return os << "NULL}";
281 std::ostream& operator<<(std::ostream& os, const InitFrame (&frames)[N]) {
284 for (size_t i = 0; i < N; ++i) {
295 // Convert a const array of InitFrame structs to the format used at
296 // runtime. Templated on the size of the array to save typing.
298 ScopedVector<WebSocketFrame> CreateFrameVector(
299 const InitFrame (&source_frames)[N]) {
300 ScopedVector<WebSocketFrame> result_frames;
301 result_frames.reserve(N);
302 for (size_t i = 0; i < N; ++i) {
303 const InitFrame& source_frame = source_frames[i];
304 scoped_ptr<WebSocketFrame> result_frame(
305 new WebSocketFrame(source_frame.opcode));
306 size_t frame_length = source_frame.data ? strlen(source_frame.data) : 0;
307 WebSocketFrameHeader& result_header = result_frame->header;
308 result_header.final = (source_frame.final == FINAL_FRAME);
309 result_header.masked = (source_frame.masked == MASKED);
310 result_header.payload_length = frame_length;
311 if (source_frame.data) {
312 result_frame->data = new IOBuffer(frame_length);
313 memcpy(result_frame->data->data(), source_frame.data, frame_length);
315 result_frames.push_back(result_frame.release());
317 return result_frames.Pass();
320 // A GoogleMock action which can be used to respond to call to ReadFrames with
321 // some frames. Use like ReadFrames(_, _).WillOnce(ReturnFrames(&frames));
322 // |frames| is an array of InitFrame. |frames| needs to be passed by pointer
323 // because otherwise it will be treated as a pointer and the array size
324 // information will be lost.
325 ACTION_P(ReturnFrames, source_frames) {
326 *arg0 = CreateFrameVector(*source_frames);
330 // The implementation of a GoogleMock matcher which can be used to compare a
331 // ScopedVector<WebSocketFrame>* against an expectation defined as an array of
332 // InitFrame objects. Although it is possible to compose built-in GoogleMock
333 // matchers to check the contents of a WebSocketFrame, the results are so
334 // unreadable that it is better to use this matcher.
336 class EqualsFramesMatcher
337 : public ::testing::MatcherInterface<ScopedVector<WebSocketFrame>*> {
339 EqualsFramesMatcher(const InitFrame (*expect_frames)[N])
340 : expect_frames_(expect_frames) {}
342 virtual bool MatchAndExplain(ScopedVector<WebSocketFrame>* actual_frames,
343 ::testing::MatchResultListener* listener) const {
344 if (actual_frames->size() != N) {
345 *listener << "the vector size is " << actual_frames->size();
348 for (size_t i = 0; i < N; ++i) {
349 const WebSocketFrame& actual_frame = *(*actual_frames)[i];
350 const InitFrame& expected_frame = (*expect_frames_)[i];
351 if (actual_frame.header.final != (expected_frame.final == FINAL_FRAME)) {
352 *listener << "the frame is marked as "
353 << (actual_frame.header.final ? "" : "not ") << "final";
356 if (actual_frame.header.opcode != expected_frame.opcode) {
357 *listener << "the opcode is " << actual_frame.header.opcode;
360 if (actual_frame.header.masked != (expected_frame.masked == MASKED)) {
361 *listener << "the frame is "
362 << (actual_frame.header.masked ? "masked" : "not masked");
365 const size_t expected_length =
366 expected_frame.data ? strlen(expected_frame.data) : 0;
367 if (actual_frame.header.payload_length != expected_length) {
368 *listener << "the payload length is "
369 << actual_frame.header.payload_length;
372 if (expected_length != 0 &&
373 memcmp(actual_frame.data->data(),
375 actual_frame.header.payload_length) != 0) {
376 *listener << "the data content differs";
383 virtual void DescribeTo(std::ostream* os) const {
384 *os << "matches " << *expect_frames_;
387 virtual void DescribeNegationTo(std::ostream* os) const {
388 *os << "does not match " << *expect_frames_;
392 const InitFrame (*expect_frames_)[N];
395 // The definition of EqualsFrames GoogleMock matcher. Unlike the ReturnFrames
396 // action, this can take the array by reference.
398 ::testing::Matcher<ScopedVector<WebSocketFrame>*> EqualsFrames(
399 const InitFrame (&frames)[N]) {
400 return ::testing::MakeMatcher(new EqualsFramesMatcher<N>(&frames));
403 // TestClosure works like TestCompletionCallback, but doesn't take an argument.
406 base::Closure closure() { return base::Bind(callback_.callback(), OK); }
408 void WaitForResult() { callback_.WaitForResult(); }
411 // Delegate to TestCompletionCallback for the implementation.
412 TestCompletionCallback callback_;
415 // A GoogleMock action to run a Closure.
416 ACTION_P(InvokeClosure, closure) { closure.Run(); }
418 // A GoogleMock action to run a Closure and return CHANNEL_DELETED.
419 ACTION_P(InvokeClosureReturnDeleted, closure) {
421 return WebSocketEventInterface::CHANNEL_DELETED;
424 // A FakeWebSocketStream whose ReadFrames() function returns data.
425 class ReadableFakeWebSocketStream : public FakeWebSocketStream {
427 enum IsSync { SYNC, ASYNC };
429 // After constructing the object, call PrepareReadFrames() once for each
430 // time you wish it to return from the test.
431 ReadableFakeWebSocketStream() : index_(0), read_frames_pending_(false) {}
433 // Check that all the prepared responses have been consumed.
434 virtual ~ReadableFakeWebSocketStream() {
435 CHECK(index_ >= responses_.size());
436 CHECK(!read_frames_pending_);
439 // Prepares a fake response. Fake responses will be returned from ReadFrames()
440 // in the same order they were prepared with PrepareReadFrames() and
441 // PrepareReadFramesError(). If |async| is ASYNC, then ReadFrames() will
442 // return ERR_IO_PENDING and the callback will be scheduled to run on the
443 // message loop. This requires the test case to run the message loop. If
444 // |async| is SYNC, the response will be returned synchronously. |error| is
445 // returned directly from ReadFrames() in the synchronous case, or passed to
446 // the callback in the asynchronous case. |frames| will be converted to a
447 // ScopedVector<WebSocketFrame> and copied to the pointer that was passed to
450 void PrepareReadFrames(IsSync async,
452 const InitFrame (&frames)[N]) {
453 responses_.push_back(new Response(async, error, CreateFrameVector(frames)));
456 // An alternate version of PrepareReadFrames for when we need to construct
457 // the frames manually.
458 void PrepareRawReadFrames(IsSync async,
460 ScopedVector<WebSocketFrame> frames) {
461 responses_.push_back(new Response(async, error, frames.Pass()));
464 // Prepares a fake error response (ie. there is no data).
465 void PrepareReadFramesError(IsSync async, int error) {
466 responses_.push_back(
467 new Response(async, error, ScopedVector<WebSocketFrame>()));
470 virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
471 const CompletionCallback& callback) OVERRIDE {
472 CHECK(!read_frames_pending_);
473 if (index_ >= responses_.size())
474 return ERR_IO_PENDING;
475 if (responses_[index_]->async == ASYNC) {
476 read_frames_pending_ = true;
477 base::MessageLoop::current()->PostTask(
479 base::Bind(&ReadableFakeWebSocketStream::DoCallback,
480 base::Unretained(this),
483 return ERR_IO_PENDING;
485 frames->swap(responses_[index_]->frames);
486 return responses_[index_++]->error;
491 void DoCallback(ScopedVector<WebSocketFrame>* frames,
492 const CompletionCallback& callback) {
493 read_frames_pending_ = false;
494 frames->swap(responses_[index_]->frames);
495 callback.Run(responses_[index_++]->error);
500 Response(IsSync async, int error, ScopedVector<WebSocketFrame> frames)
501 : async(async), error(error), frames(frames.Pass()) {}
505 ScopedVector<WebSocketFrame> frames;
508 // Bad things will happen if we attempt to copy or assign |frames|.
509 DISALLOW_COPY_AND_ASSIGN(Response);
511 ScopedVector<Response> responses_;
513 // The index into the responses_ array of the next response to be returned.
516 // True when an async response from ReadFrames() is pending. This only applies
517 // to "real" async responses. Once all the prepared responses have been
518 // returned, ReadFrames() returns ERR_IO_PENDING but read_frames_pending_ is
520 bool read_frames_pending_;
523 // A FakeWebSocketStream where writes always complete successfully and
525 class WriteableFakeWebSocketStream : public FakeWebSocketStream {
527 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
528 const CompletionCallback& callback) OVERRIDE {
533 // A FakeWebSocketStream where writes always fail.
534 class UnWriteableFakeWebSocketStream : public FakeWebSocketStream {
536 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
537 const CompletionCallback& callback) OVERRIDE {
538 return ERR_CONNECTION_RESET;
542 // A FakeWebSocketStream which echoes any frames written back. Clears the
543 // "masked" header bit, but makes no other checks for validity. Tests using this
544 // must run the MessageLoop to receive the callback(s). If a message with opcode
545 // Close is echoed, then an ERR_CONNECTION_CLOSED is returned in the next
546 // callback. The test must do something to cause WriteFrames() to be called,
547 // otherwise the ReadFrames() callback will never be called.
548 class EchoeyFakeWebSocketStream : public FakeWebSocketStream {
550 EchoeyFakeWebSocketStream() : read_frames_(NULL), done_(false) {}
552 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
553 const CompletionCallback& callback) OVERRIDE {
554 // Users of WebSocketStream will not expect the ReadFrames() callback to be
555 // called from within WriteFrames(), so post it to the message loop instead.
556 stored_frames_.insert(stored_frames_.end(), frames->begin(), frames->end());
557 frames->weak_clear();
562 virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
563 const CompletionCallback& callback) OVERRIDE {
564 read_callback_ = callback;
565 read_frames_ = frames;
568 return ERR_IO_PENDING;
572 void PostCallback() {
573 base::MessageLoop::current()->PostTask(
575 base::Bind(&EchoeyFakeWebSocketStream::DoCallback,
576 base::Unretained(this)));
581 read_callback_.Run(ERR_CONNECTION_CLOSED);
582 } else if (!stored_frames_.empty()) {
583 done_ = MoveFrames(read_frames_);
585 read_callback_.Run(OK);
589 // Copy the frames stored in stored_frames_ to |out|, while clearing the
590 // "masked" header bit. Returns true if a Close Frame was seen, false
592 bool MoveFrames(ScopedVector<WebSocketFrame>* out) {
593 bool seen_close = false;
594 *out = stored_frames_.Pass();
595 for (ScopedVector<WebSocketFrame>::iterator it = out->begin();
598 WebSocketFrameHeader& header = (*it)->header;
599 header.masked = false;
600 if (header.opcode == WebSocketFrameHeader::kOpCodeClose)
606 ScopedVector<WebSocketFrame> stored_frames_;
607 CompletionCallback read_callback_;
608 // Owned by the caller of ReadFrames().
609 ScopedVector<WebSocketFrame>* read_frames_;
610 // True if we should close the connection.
614 // A FakeWebSocketStream where writes trigger a connection reset.
615 // This differs from UnWriteableFakeWebSocketStream in that it is asynchronous
616 // and triggers ReadFrames to return a reset as well. Tests using this need to
617 // run the message loop. There are two tricky parts here:
618 // 1. Calling the write callback may call Close(), after which the read callback
619 // should not be called.
620 // 2. Calling either callback may delete the stream altogether.
621 class ResetOnWriteFakeWebSocketStream : public FakeWebSocketStream {
623 ResetOnWriteFakeWebSocketStream() : closed_(false), weak_ptr_factory_(this) {}
625 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
626 const CompletionCallback& callback) OVERRIDE {
627 base::MessageLoop::current()->PostTask(
629 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
630 weak_ptr_factory_.GetWeakPtr(),
632 ERR_CONNECTION_RESET));
633 base::MessageLoop::current()->PostTask(
635 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
636 weak_ptr_factory_.GetWeakPtr(),
638 ERR_CONNECTION_RESET));
639 return ERR_IO_PENDING;
642 virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
643 const CompletionCallback& callback) OVERRIDE {
644 read_callback_ = callback;
645 return ERR_IO_PENDING;
648 virtual void Close() OVERRIDE { closed_ = true; }
651 void CallCallbackUnlessClosed(const CompletionCallback& callback, int value) {
656 CompletionCallback read_callback_;
658 // An IO error can result in the socket being deleted, so we use weak pointers
659 // to ensure correct behaviour in that case.
660 base::WeakPtrFactory<ResetOnWriteFakeWebSocketStream> weak_ptr_factory_;
663 // This mock is for verifying that WebSocket protocol semantics are obeyed (to
664 // the extent that they are implemented in WebSocketCommon).
665 class MockWebSocketStream : public WebSocketStream {
667 MOCK_METHOD2(ReadFrames,
668 int(ScopedVector<WebSocketFrame>* frames,
669 const CompletionCallback& callback));
670 MOCK_METHOD2(WriteFrames,
671 int(ScopedVector<WebSocketFrame>* frames,
672 const CompletionCallback& callback));
673 MOCK_METHOD0(Close, void());
674 MOCK_CONST_METHOD0(GetSubProtocol, std::string());
675 MOCK_CONST_METHOD0(GetExtensions, std::string());
676 MOCK_METHOD0(AsWebSocketStream, WebSocketStream*());
679 struct ArgumentCopyingWebSocketStreamCreator {
680 scoped_ptr<WebSocketStreamRequest> Create(
681 const GURL& socket_url,
682 const std::vector<std::string>& requested_subprotocols,
684 URLRequestContext* url_request_context,
685 const BoundNetLog& net_log,
686 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate) {
687 this->socket_url = socket_url;
688 this->requested_subprotocols = requested_subprotocols;
689 this->origin = origin;
690 this->url_request_context = url_request_context;
691 this->net_log = net_log;
692 this->connect_delegate = connect_delegate.Pass();
693 return make_scoped_ptr(new WebSocketStreamRequest);
698 std::vector<std::string> requested_subprotocols;
699 URLRequestContext* url_request_context;
701 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate;
704 // Converts a std::string to a std::vector<char>. For test purposes, it is
705 // convenient to be able to specify data as a string, but the
706 // WebSocketEventInterface requires the vector<char> type.
707 std::vector<char> AsVector(const std::string& s) {
708 return std::vector<char>(s.begin(), s.end());
711 // Base class for all test fixtures.
712 class WebSocketChannelTest : public ::testing::Test {
714 WebSocketChannelTest() : stream_(new FakeWebSocketStream) {}
716 // Creates a new WebSocketChannel and connects it, using the settings stored
717 // in |connect_data_|.
718 void CreateChannelAndConnect() {
719 channel_.reset(new WebSocketChannel(CreateEventInterface(),
720 &connect_data_.url_request_context));
721 channel_->SendAddChannelRequestForTesting(
722 connect_data_.socket_url,
723 connect_data_.requested_subprotocols,
724 connect_data_.origin,
725 base::Bind(&ArgumentCopyingWebSocketStreamCreator::Create,
726 base::Unretained(&connect_data_.creator)));
729 // Same as CreateChannelAndConnect(), but calls the on_success callback as
730 // well. This method is virtual so that subclasses can also set the stream.
731 virtual void CreateChannelAndConnectSuccessfully() {
732 CreateChannelAndConnect();
733 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
736 // Returns a WebSocketEventInterface to be passed to the WebSocketChannel.
737 // This implementation returns a newly-created fake. Subclasses may return a
739 virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() {
740 return scoped_ptr<WebSocketEventInterface>(new FakeWebSocketEventInterface);
743 // This method serves no other purpose than to provide a nice syntax for
744 // assigning to stream_. class T must be a subclass of WebSocketStream or you
745 // will have unpleasant compile errors.
747 void set_stream(scoped_ptr<T> stream) {
748 // Since the definition of "PassAs" depends on the type T, the C++ standard
749 // requires the "template" keyword to indicate that "PassAs" should be
750 // parsed as a template method.
751 stream_ = stream.template PassAs<WebSocketStream>();
754 // A struct containing the data that will be used to connect the channel.
755 // Grouped for readability.
757 ConnectData() : socket_url("ws://ws/"), origin("http://ws/") {}
759 // URLRequestContext object.
760 URLRequestContext url_request_context;
762 // URL to (pretend to) connect to.
764 // Requested protocols for the request.
765 std::vector<std::string> requested_subprotocols;
766 // Origin of the request
769 // A fake WebSocketStreamCreator that just records its arguments.
770 ArgumentCopyingWebSocketStreamCreator creator;
772 ConnectData connect_data_;
774 // The channel we are testing. Not initialised until SetChannel() is called.
775 scoped_ptr<WebSocketChannel> channel_;
777 // A mock or fake stream for tests that need one.
778 scoped_ptr<WebSocketStream> stream_;
781 // enum of WebSocketEventInterface calls. These are intended to be or'd together
782 // in order to instruct WebSocketChannelDeletingTest when it should fail.
783 enum EventInterfaceCall {
784 EVENT_ON_ADD_CHANNEL_RESPONSE = 0x1,
785 EVENT_ON_DATA_FRAME = 0x2,
786 EVENT_ON_FLOW_CONTROL = 0x4,
787 EVENT_ON_CLOSING_HANDSHAKE = 0x8,
788 EVENT_ON_FAIL_CHANNEL = 0x10,
789 EVENT_ON_DROP_CHANNEL = 0x20,
790 EVENT_ON_START_OPENING_HANDSHAKE = 0x40,
791 EVENT_ON_FINISH_OPENING_HANDSHAKE = 0x80,
794 class WebSocketChannelDeletingTest : public WebSocketChannelTest {
796 ChannelState DeleteIfDeleting(EventInterfaceCall call) {
797 if (deleting_ & call) {
799 return CHANNEL_DELETED;
801 return CHANNEL_ALIVE;
806 WebSocketChannelDeletingTest()
807 : deleting_(EVENT_ON_ADD_CHANNEL_RESPONSE | EVENT_ON_DATA_FRAME |
808 EVENT_ON_FLOW_CONTROL |
809 EVENT_ON_CLOSING_HANDSHAKE |
810 EVENT_ON_FAIL_CHANNEL |
811 EVENT_ON_DROP_CHANNEL |
812 EVENT_ON_START_OPENING_HANDSHAKE |
813 EVENT_ON_FINISH_OPENING_HANDSHAKE) {}
814 // Create a ChannelDeletingFakeWebSocketEventInterface. Defined out-of-line to
815 // avoid circular dependency.
816 virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() OVERRIDE;
818 // Tests can set deleting_ to a bitmap of EventInterfaceCall members that they
819 // want to cause Channel deletion. The default is for all calls to cause
824 // A FakeWebSocketEventInterface that deletes the WebSocketChannel on failure to
826 class ChannelDeletingFakeWebSocketEventInterface
827 : public FakeWebSocketEventInterface {
829 ChannelDeletingFakeWebSocketEventInterface(
830 WebSocketChannelDeletingTest* fixture)
831 : fixture_(fixture) {}
833 virtual ChannelState OnAddChannelResponse(
835 const std::string& selected_protocol,
836 const std::string& extensions) OVERRIDE {
837 return fixture_->DeleteIfDeleting(EVENT_ON_ADD_CHANNEL_RESPONSE);
840 virtual ChannelState OnDataFrame(bool fin,
841 WebSocketMessageType type,
842 const std::vector<char>& data) OVERRIDE {
843 return fixture_->DeleteIfDeleting(EVENT_ON_DATA_FRAME);
846 virtual ChannelState OnFlowControl(int64 quota) OVERRIDE {
847 return fixture_->DeleteIfDeleting(EVENT_ON_FLOW_CONTROL);
850 virtual ChannelState OnClosingHandshake() OVERRIDE {
851 return fixture_->DeleteIfDeleting(EVENT_ON_CLOSING_HANDSHAKE);
854 virtual ChannelState OnFailChannel(const std::string& message) OVERRIDE {
855 return fixture_->DeleteIfDeleting(EVENT_ON_FAIL_CHANNEL);
858 virtual ChannelState OnDropChannel(bool was_clean,
860 const std::string& reason) OVERRIDE {
861 return fixture_->DeleteIfDeleting(EVENT_ON_DROP_CHANNEL);
864 virtual ChannelState OnStartOpeningHandshake(
865 scoped_ptr<WebSocketHandshakeRequestInfo> request) OVERRIDE {
866 return fixture_->DeleteIfDeleting(EVENT_ON_START_OPENING_HANDSHAKE);
868 virtual ChannelState OnFinishOpeningHandshake(
869 scoped_ptr<WebSocketHandshakeResponseInfo> response) OVERRIDE {
870 return fixture_->DeleteIfDeleting(EVENT_ON_FINISH_OPENING_HANDSHAKE);
874 // A pointer to the test fixture. Owned by the test harness; this object will
875 // be deleted before it is.
876 WebSocketChannelDeletingTest* fixture_;
879 scoped_ptr<WebSocketEventInterface>
880 WebSocketChannelDeletingTest::CreateEventInterface() {
881 return scoped_ptr<WebSocketEventInterface>(
882 new ChannelDeletingFakeWebSocketEventInterface(this));
885 // Base class for tests which verify that EventInterface methods are called
887 class WebSocketChannelEventInterfaceTest : public WebSocketChannelTest {
889 WebSocketChannelEventInterfaceTest()
890 : event_interface_(new StrictMock<MockWebSocketEventInterface>) {
891 DefaultValue<ChannelState>::Set(CHANNEL_ALIVE);
892 ON_CALL(*event_interface_, OnAddChannelResponse(true, _, _))
893 .WillByDefault(Return(CHANNEL_DELETED));
894 ON_CALL(*event_interface_, OnDropChannel(_, _, _))
895 .WillByDefault(Return(CHANNEL_DELETED));
896 ON_CALL(*event_interface_, OnFailChannel(_))
897 .WillByDefault(Return(CHANNEL_DELETED));
900 virtual ~WebSocketChannelEventInterfaceTest() {
901 DefaultValue<ChannelState>::Clear();
904 // Tests using this fixture must set expectations on the event_interface_ mock
905 // object before calling CreateChannelAndConnect() or
906 // CreateChannelAndConnectSuccessfully(). This will only work once per test
907 // case, but once should be enough.
908 virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() OVERRIDE {
909 return scoped_ptr<WebSocketEventInterface>(event_interface_.release());
912 scoped_ptr<MockWebSocketEventInterface> event_interface_;
915 // Base class for tests which verify that WebSocketStream methods are called
916 // appropriately by using a MockWebSocketStream.
917 class WebSocketChannelStreamTest : public WebSocketChannelTest {
919 WebSocketChannelStreamTest()
920 : mock_stream_(new StrictMock<MockWebSocketStream>) {}
922 virtual void CreateChannelAndConnectSuccessfully() OVERRIDE {
923 set_stream(mock_stream_.Pass());
924 WebSocketChannelTest::CreateChannelAndConnectSuccessfully();
927 scoped_ptr<MockWebSocketStream> mock_stream_;
930 // Fixture for tests which test UTF-8 validation of sent Text frames via the
932 class WebSocketChannelSendUtf8Test
933 : public WebSocketChannelEventInterfaceTest {
935 virtual void SetUp() {
936 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
937 // For the purpose of the tests using this fixture, it doesn't matter
938 // whether these methods are called or not.
939 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _, _))
941 EXPECT_CALL(*event_interface_, OnFlowControl(_))
946 // Fixture for tests which test UTF-8 validation of received Text frames using a
947 // mock WebSocketStream.
948 class WebSocketChannelReceiveUtf8Test : public WebSocketChannelStreamTest {
950 virtual void SetUp() {
951 // For the purpose of the tests using this fixture, it doesn't matter
952 // whether these methods are called or not.
953 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
954 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
958 // Simple test that everything that should be passed to the creator function is
959 // passed to the creator function.
960 TEST_F(WebSocketChannelTest, EverythingIsPassedToTheCreatorFunction) {
961 connect_data_.socket_url = GURL("ws://example.com/test");
962 connect_data_.origin = GURL("http://example.com/test");
963 connect_data_.requested_subprotocols.push_back("Sinbad");
965 CreateChannelAndConnect();
967 const ArgumentCopyingWebSocketStreamCreator& actual = connect_data_.creator;
969 EXPECT_EQ(&connect_data_.url_request_context, actual.url_request_context);
971 EXPECT_EQ(connect_data_.socket_url, actual.socket_url);
972 EXPECT_EQ(connect_data_.requested_subprotocols,
973 actual.requested_subprotocols);
974 EXPECT_EQ(connect_data_.origin, actual.origin);
977 // Verify that calling SendFlowControl before the connection is established does
978 // not cause a crash.
979 TEST_F(WebSocketChannelTest, SendFlowControlDuringHandshakeOkay) {
980 CreateChannelAndConnect();
981 ASSERT_TRUE(channel_);
982 channel_->SendFlowControl(65536);
985 // Any WebSocketEventInterface methods can delete the WebSocketChannel and
986 // return CHANNEL_DELETED. The WebSocketChannelDeletingTests are intended to
987 // verify that there are no use-after-free bugs when this happens. Problems will
988 // probably only be found when running under Address Sanitizer or a similar
990 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseFail) {
991 CreateChannelAndConnect();
992 EXPECT_TRUE(channel_);
993 connect_data_.creator.connect_delegate->OnFailure("bye");
994 EXPECT_EQ(NULL, channel_.get());
997 // Deletion is possible (due to IPC failure) even if the connect succeeds.
998 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseSuccess) {
999 CreateChannelAndConnectSuccessfully();
1000 EXPECT_EQ(NULL, channel_.get());
1003 TEST_F(WebSocketChannelDeletingTest, OnDataFrameSync) {
1004 scoped_ptr<ReadableFakeWebSocketStream> stream(
1005 new ReadableFakeWebSocketStream);
1006 static const InitFrame frames[] = {
1007 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1008 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1009 set_stream(stream.Pass());
1010 deleting_ = EVENT_ON_DATA_FRAME;
1012 CreateChannelAndConnectSuccessfully();
1013 EXPECT_EQ(NULL, channel_.get());
1016 TEST_F(WebSocketChannelDeletingTest, OnDataFrameAsync) {
1017 scoped_ptr<ReadableFakeWebSocketStream> stream(
1018 new ReadableFakeWebSocketStream);
1019 static const InitFrame frames[] = {
1020 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1021 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1022 set_stream(stream.Pass());
1023 deleting_ = EVENT_ON_DATA_FRAME;
1025 CreateChannelAndConnectSuccessfully();
1026 EXPECT_TRUE(channel_);
1027 base::MessageLoop::current()->RunUntilIdle();
1028 EXPECT_EQ(NULL, channel_.get());
1031 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterConnect) {
1032 deleting_ = EVENT_ON_FLOW_CONTROL;
1034 CreateChannelAndConnectSuccessfully();
1035 EXPECT_EQ(NULL, channel_.get());
1038 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterSend) {
1039 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1040 // Avoid deleting the channel yet.
1041 deleting_ = EVENT_ON_FAIL_CHANNEL | EVENT_ON_DROP_CHANNEL;
1042 CreateChannelAndConnectSuccessfully();
1043 ASSERT_TRUE(channel_);
1044 deleting_ = EVENT_ON_FLOW_CONTROL;
1045 channel_->SendFrame(true,
1046 WebSocketFrameHeader::kOpCodeText,
1047 std::vector<char>(kDefaultInitialQuota, 'B'));
1048 EXPECT_EQ(NULL, channel_.get());
1051 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeSync) {
1052 scoped_ptr<ReadableFakeWebSocketStream> stream(
1053 new ReadableFakeWebSocketStream);
1054 static const InitFrame frames[] = {
1055 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1056 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
1057 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1058 set_stream(stream.Pass());
1059 deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
1060 CreateChannelAndConnectSuccessfully();
1061 EXPECT_EQ(NULL, channel_.get());
1064 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeAsync) {
1065 scoped_ptr<ReadableFakeWebSocketStream> stream(
1066 new ReadableFakeWebSocketStream);
1067 static const InitFrame frames[] = {
1068 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1069 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
1070 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1071 set_stream(stream.Pass());
1072 deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
1073 CreateChannelAndConnectSuccessfully();
1074 ASSERT_TRUE(channel_);
1075 base::MessageLoop::current()->RunUntilIdle();
1076 EXPECT_EQ(NULL, channel_.get());
1079 TEST_F(WebSocketChannelDeletingTest, OnDropChannelWriteError) {
1080 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
1081 deleting_ = EVENT_ON_DROP_CHANNEL;
1082 CreateChannelAndConnectSuccessfully();
1083 ASSERT_TRUE(channel_);
1084 channel_->SendFrame(
1085 true, WebSocketFrameHeader::kOpCodeText, AsVector("this will fail"));
1086 EXPECT_EQ(NULL, channel_.get());
1089 TEST_F(WebSocketChannelDeletingTest, OnDropChannelReadError) {
1090 scoped_ptr<ReadableFakeWebSocketStream> stream(
1091 new ReadableFakeWebSocketStream);
1092 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1094 set_stream(stream.Pass());
1095 deleting_ = EVENT_ON_DROP_CHANNEL;
1096 CreateChannelAndConnectSuccessfully();
1097 ASSERT_TRUE(channel_);
1098 base::MessageLoop::current()->RunUntilIdle();
1099 EXPECT_EQ(NULL, channel_.get());
1102 TEST_F(WebSocketChannelDeletingTest, OnNotifyStartOpeningHandshakeError) {
1103 scoped_ptr<ReadableFakeWebSocketStream> stream(
1104 new ReadableFakeWebSocketStream);
1105 static const InitFrame frames[] = {
1106 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1107 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1108 set_stream(stream.Pass());
1109 deleting_ = EVENT_ON_START_OPENING_HANDSHAKE;
1111 CreateChannelAndConnectSuccessfully();
1112 ASSERT_TRUE(channel_);
1113 channel_->OnStartOpeningHandshake(scoped_ptr<WebSocketHandshakeRequestInfo>(
1114 new WebSocketHandshakeRequestInfo(GURL("http://www.example.com/"),
1116 base::MessageLoop::current()->RunUntilIdle();
1117 EXPECT_EQ(NULL, channel_.get());
1120 TEST_F(WebSocketChannelDeletingTest, OnNotifyFinishOpeningHandshakeError) {
1121 scoped_ptr<ReadableFakeWebSocketStream> stream(
1122 new ReadableFakeWebSocketStream);
1123 static const InitFrame frames[] = {
1124 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1125 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1126 set_stream(stream.Pass());
1127 deleting_ = EVENT_ON_FINISH_OPENING_HANDSHAKE;
1129 CreateChannelAndConnectSuccessfully();
1130 ASSERT_TRUE(channel_);
1131 scoped_refptr<HttpResponseHeaders> response_headers(
1132 new HttpResponseHeaders(""));
1133 channel_->OnFinishOpeningHandshake(scoped_ptr<WebSocketHandshakeResponseInfo>(
1134 new WebSocketHandshakeResponseInfo(GURL("http://www.example.com/"),
1139 base::MessageLoop::current()->RunUntilIdle();
1140 EXPECT_EQ(NULL, channel_.get());
1143 TEST_F(WebSocketChannelDeletingTest, FailChannelInSendFrame) {
1144 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1145 deleting_ = EVENT_ON_FAIL_CHANNEL;
1146 CreateChannelAndConnectSuccessfully();
1147 ASSERT_TRUE(channel_);
1148 channel_->SendFrame(true,
1149 WebSocketFrameHeader::kOpCodeText,
1150 std::vector<char>(kDefaultInitialQuota * 2, 'T'));
1151 EXPECT_EQ(NULL, channel_.get());
1154 TEST_F(WebSocketChannelDeletingTest, FailChannelInOnReadDone) {
1155 scoped_ptr<ReadableFakeWebSocketStream> stream(
1156 new ReadableFakeWebSocketStream);
1157 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1158 ERR_WS_PROTOCOL_ERROR);
1159 set_stream(stream.Pass());
1160 deleting_ = EVENT_ON_FAIL_CHANNEL;
1161 CreateChannelAndConnectSuccessfully();
1162 ASSERT_TRUE(channel_);
1163 base::MessageLoop::current()->RunUntilIdle();
1164 EXPECT_EQ(NULL, channel_.get());
1167 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToMaskedFrame) {
1168 scoped_ptr<ReadableFakeWebSocketStream> stream(
1169 new ReadableFakeWebSocketStream);
1170 static const InitFrame frames[] = {
1171 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1172 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1173 set_stream(stream.Pass());
1174 deleting_ = EVENT_ON_FAIL_CHANNEL;
1176 CreateChannelAndConnectSuccessfully();
1177 EXPECT_EQ(NULL, channel_.get());
1180 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToBadControlFrame) {
1181 scoped_ptr<ReadableFakeWebSocketStream> stream(
1182 new ReadableFakeWebSocketStream);
1183 static const InitFrame frames[] = {
1184 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1185 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1186 set_stream(stream.Pass());
1187 deleting_ = EVENT_ON_FAIL_CHANNEL;
1189 CreateChannelAndConnectSuccessfully();
1190 EXPECT_EQ(NULL, channel_.get());
1193 // Version of above test with NULL data.
1194 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToBadControlFrameNull) {
1195 scoped_ptr<ReadableFakeWebSocketStream> stream(
1196 new ReadableFakeWebSocketStream);
1197 static const InitFrame frames[] = {
1198 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1199 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1200 set_stream(stream.Pass());
1201 deleting_ = EVENT_ON_FAIL_CHANNEL;
1203 CreateChannelAndConnectSuccessfully();
1204 EXPECT_EQ(NULL, channel_.get());
1207 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToPongAfterClose) {
1208 scoped_ptr<ReadableFakeWebSocketStream> stream(
1209 new ReadableFakeWebSocketStream);
1210 static const InitFrame frames[] = {
1211 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
1212 CLOSE_DATA(NORMAL_CLOSURE, "Success")},
1213 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1214 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1215 set_stream(stream.Pass());
1216 deleting_ = EVENT_ON_FAIL_CHANNEL;
1218 CreateChannelAndConnectSuccessfully();
1219 EXPECT_EQ(NULL, channel_.get());
1222 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToPongAfterCloseNull) {
1223 scoped_ptr<ReadableFakeWebSocketStream> stream(
1224 new ReadableFakeWebSocketStream);
1225 static const InitFrame frames[] = {
1226 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
1227 CLOSE_DATA(NORMAL_CLOSURE, "Success")},
1228 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1229 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1230 set_stream(stream.Pass());
1231 deleting_ = EVENT_ON_FAIL_CHANNEL;
1233 CreateChannelAndConnectSuccessfully();
1234 EXPECT_EQ(NULL, channel_.get());
1237 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToUnknownOpCode) {
1238 scoped_ptr<ReadableFakeWebSocketStream> stream(
1239 new ReadableFakeWebSocketStream);
1240 static const InitFrame frames[] = {{FINAL_FRAME, 0x7, NOT_MASKED, ""}};
1241 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1242 set_stream(stream.Pass());
1243 deleting_ = EVENT_ON_FAIL_CHANNEL;
1245 CreateChannelAndConnectSuccessfully();
1246 EXPECT_EQ(NULL, channel_.get());
1249 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToUnknownOpCodeNull) {
1250 scoped_ptr<ReadableFakeWebSocketStream> stream(
1251 new ReadableFakeWebSocketStream);
1252 static const InitFrame frames[] = {{FINAL_FRAME, 0x7, NOT_MASKED, NULL}};
1253 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1254 set_stream(stream.Pass());
1255 deleting_ = EVENT_ON_FAIL_CHANNEL;
1257 CreateChannelAndConnectSuccessfully();
1258 EXPECT_EQ(NULL, channel_.get());
1261 TEST_F(WebSocketChannelDeletingTest, FailChannelDueInvalidCloseReason) {
1262 scoped_ptr<ReadableFakeWebSocketStream> stream(
1263 new ReadableFakeWebSocketStream);
1264 static const InitFrame frames[] = {
1265 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1266 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
1267 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1268 set_stream(stream.Pass());
1269 deleting_ = EVENT_ON_FAIL_CHANNEL;
1271 CreateChannelAndConnectSuccessfully();
1272 EXPECT_EQ(NULL, channel_.get());
1275 TEST_F(WebSocketChannelEventInterfaceTest, ConnectSuccessReported) {
1276 // false means success.
1277 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, "", ""));
1278 // OnFlowControl is always called immediately after connect to provide initial
1279 // quota to the renderer.
1280 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1282 CreateChannelAndConnect();
1284 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
1287 TEST_F(WebSocketChannelEventInterfaceTest, ConnectFailureReported) {
1288 EXPECT_CALL(*event_interface_, OnFailChannel("hello"));
1290 CreateChannelAndConnect();
1292 connect_data_.creator.connect_delegate->OnFailure("hello");
1295 TEST_F(WebSocketChannelEventInterfaceTest, NonWebSocketSchemeRejected) {
1296 EXPECT_CALL(*event_interface_, OnAddChannelResponse(true, "", ""));
1297 connect_data_.socket_url = GURL("http://www.google.com/");
1298 CreateChannelAndConnect();
1301 TEST_F(WebSocketChannelEventInterfaceTest, ProtocolPassed) {
1302 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, "Bob", ""));
1303 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1305 CreateChannelAndConnect();
1307 connect_data_.creator.connect_delegate->OnSuccess(
1308 scoped_ptr<WebSocketStream>(new FakeWebSocketStream("Bob", "")));
1311 TEST_F(WebSocketChannelEventInterfaceTest, ExtensionsPassed) {
1312 EXPECT_CALL(*event_interface_,
1313 OnAddChannelResponse(false, "", "extension1, extension2"));
1314 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1316 CreateChannelAndConnect();
1318 connect_data_.creator.connect_delegate->OnSuccess(scoped_ptr<WebSocketStream>(
1319 new FakeWebSocketStream("", "extension1, extension2")));
1322 // The first frames from the server can arrive together with the handshake, in
1323 // which case they will be available as soon as ReadFrames() is called the first
1325 TEST_F(WebSocketChannelEventInterfaceTest, DataLeftFromHandshake) {
1326 scoped_ptr<ReadableFakeWebSocketStream> stream(
1327 new ReadableFakeWebSocketStream);
1328 static const InitFrame frames[] = {
1329 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1330 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1331 set_stream(stream.Pass());
1334 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1335 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1339 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1342 CreateChannelAndConnectSuccessfully();
1345 // A remote server could accept the handshake, but then immediately send a
1347 TEST_F(WebSocketChannelEventInterfaceTest, CloseAfterHandshake) {
1348 scoped_ptr<ReadableFakeWebSocketStream> stream(
1349 new ReadableFakeWebSocketStream);
1350 static const InitFrame frames[] = {
1351 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1352 NOT_MASKED, CLOSE_DATA(SERVER_ERROR, "Internal Server Error")}};
1353 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1354 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1355 ERR_CONNECTION_CLOSED);
1356 set_stream(stream.Pass());
1359 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1360 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1361 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1365 true, kWebSocketErrorInternalServerError, "Internal Server Error"));
1368 CreateChannelAndConnectSuccessfully();
1371 // A remote server could close the connection immediately after sending the
1372 // handshake response (most likely a bug in the server).
1373 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionCloseAfterHandshake) {
1374 scoped_ptr<ReadableFakeWebSocketStream> stream(
1375 new ReadableFakeWebSocketStream);
1376 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1377 ERR_CONNECTION_CLOSED);
1378 set_stream(stream.Pass());
1381 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1382 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1383 EXPECT_CALL(*event_interface_,
1384 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1387 CreateChannelAndConnectSuccessfully();
1390 TEST_F(WebSocketChannelEventInterfaceTest, NormalAsyncRead) {
1391 scoped_ptr<ReadableFakeWebSocketStream> stream(
1392 new ReadableFakeWebSocketStream);
1393 static const InitFrame frames[] = {
1394 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1395 // We use this checkpoint object to verify that the callback isn't called
1396 // until we expect it to be.
1397 Checkpoint checkpoint;
1398 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1399 set_stream(stream.Pass());
1402 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1403 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1404 EXPECT_CALL(checkpoint, Call(1));
1408 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1409 EXPECT_CALL(checkpoint, Call(2));
1412 CreateChannelAndConnectSuccessfully();
1414 base::MessageLoop::current()->RunUntilIdle();
1418 // Extra data can arrive while a read is being processed, resulting in the next
1419 // read completing synchronously.
1420 TEST_F(WebSocketChannelEventInterfaceTest, AsyncThenSyncRead) {
1421 scoped_ptr<ReadableFakeWebSocketStream> stream(
1422 new ReadableFakeWebSocketStream);
1423 static const InitFrame frames1[] = {
1424 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1425 static const InitFrame frames2[] = {
1426 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "WORLD"}};
1427 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1428 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames2);
1429 set_stream(stream.Pass());
1432 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1433 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1437 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1441 true, WebSocketFrameHeader::kOpCodeText, AsVector("WORLD")));
1444 CreateChannelAndConnectSuccessfully();
1445 base::MessageLoop::current()->RunUntilIdle();
1448 // Data frames are delivered the same regardless of how many reads they arrive
1450 TEST_F(WebSocketChannelEventInterfaceTest, FragmentedMessage) {
1451 scoped_ptr<ReadableFakeWebSocketStream> stream(
1452 new ReadableFakeWebSocketStream);
1453 // Here we have one message which arrived in five frames split across three
1454 // reads. It may have been reframed on arrival, but this class doesn't care
1456 static const InitFrame frames1[] = {
1457 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "THREE"},
1458 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1460 static const InitFrame frames2[] = {
1461 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1462 NOT_MASKED, "SMALL"}};
1463 static const InitFrame frames3[] = {
1464 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1466 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1467 NOT_MASKED, "FRAMES"}};
1468 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1469 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1470 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1471 set_stream(stream.Pass());
1474 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1475 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1479 false, WebSocketFrameHeader::kOpCodeText, AsVector("THREE")));
1483 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1484 EXPECT_CALL(*event_interface_,
1486 WebSocketFrameHeader::kOpCodeContinuation,
1487 AsVector("SMALL")));
1491 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1492 EXPECT_CALL(*event_interface_,
1494 WebSocketFrameHeader::kOpCodeContinuation,
1495 AsVector("FRAMES")));
1498 CreateChannelAndConnectSuccessfully();
1499 base::MessageLoop::current()->RunUntilIdle();
1502 // A message can consist of one frame with NULL payload.
1503 TEST_F(WebSocketChannelEventInterfaceTest, NullMessage) {
1504 scoped_ptr<ReadableFakeWebSocketStream> stream(
1505 new ReadableFakeWebSocketStream);
1506 static const InitFrame frames[] = {
1507 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, NULL}};
1508 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1509 set_stream(stream.Pass());
1510 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1511 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1514 OnDataFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("")));
1515 CreateChannelAndConnectSuccessfully();
1518 // A control frame is not permitted to be split into multiple frames. RFC6455
1519 // 5.5 "All control frames ... MUST NOT be fragmented."
1520 TEST_F(WebSocketChannelEventInterfaceTest, MultiFrameControlMessageIsRejected) {
1521 scoped_ptr<ReadableFakeWebSocketStream> stream(
1522 new ReadableFakeWebSocketStream);
1523 static const InitFrame frames[] = {
1524 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePing, NOT_MASKED, "Pi"},
1525 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1527 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1528 set_stream(stream.Pass());
1531 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1532 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1533 EXPECT_CALL(*event_interface_,
1534 OnFailChannel("Received fragmented control frame: opcode = 9"));
1537 CreateChannelAndConnectSuccessfully();
1538 base::MessageLoop::current()->RunUntilIdle();
1541 // Connection closed by the remote host without a closing handshake.
1542 TEST_F(WebSocketChannelEventInterfaceTest, AsyncAbnormalClosure) {
1543 scoped_ptr<ReadableFakeWebSocketStream> stream(
1544 new ReadableFakeWebSocketStream);
1545 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1546 ERR_CONNECTION_CLOSED);
1547 set_stream(stream.Pass());
1550 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1551 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1552 EXPECT_CALL(*event_interface_,
1553 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1556 CreateChannelAndConnectSuccessfully();
1557 base::MessageLoop::current()->RunUntilIdle();
1560 // A connection reset should produce the same event as an unexpected closure.
1561 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionReset) {
1562 scoped_ptr<ReadableFakeWebSocketStream> stream(
1563 new ReadableFakeWebSocketStream);
1564 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1565 ERR_CONNECTION_RESET);
1566 set_stream(stream.Pass());
1569 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1570 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1571 EXPECT_CALL(*event_interface_,
1572 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1575 CreateChannelAndConnectSuccessfully();
1576 base::MessageLoop::current()->RunUntilIdle();
1579 // RFC6455 5.1 "A client MUST close a connection if it detects a masked frame."
1580 TEST_F(WebSocketChannelEventInterfaceTest, MaskedFramesAreRejected) {
1581 scoped_ptr<ReadableFakeWebSocketStream> stream(
1582 new ReadableFakeWebSocketStream);
1583 static const InitFrame frames[] = {
1584 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1586 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1587 set_stream(stream.Pass());
1590 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1591 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1595 "A server must not mask any frames that it sends to the client."));
1598 CreateChannelAndConnectSuccessfully();
1599 base::MessageLoop::current()->RunUntilIdle();
1602 // RFC6455 5.2 "If an unknown opcode is received, the receiving endpoint MUST
1603 // _Fail the WebSocket Connection_."
1604 TEST_F(WebSocketChannelEventInterfaceTest, UnknownOpCodeIsRejected) {
1605 scoped_ptr<ReadableFakeWebSocketStream> stream(
1606 new ReadableFakeWebSocketStream);
1607 static const InitFrame frames[] = {{FINAL_FRAME, 4, NOT_MASKED, "HELLO"}};
1609 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1610 set_stream(stream.Pass());
1613 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1614 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1615 EXPECT_CALL(*event_interface_,
1616 OnFailChannel("Unrecognized frame opcode: 4"));
1619 CreateChannelAndConnectSuccessfully();
1620 base::MessageLoop::current()->RunUntilIdle();
1623 // RFC6455 5.4 "Control frames ... MAY be injected in the middle of a
1624 // fragmented message."
1625 TEST_F(WebSocketChannelEventInterfaceTest, ControlFrameInDataMessage) {
1626 scoped_ptr<ReadableFakeWebSocketStream> stream(
1627 new ReadableFakeWebSocketStream);
1628 // We have one message of type Text split into two frames. In the middle is a
1629 // control message of type Pong.
1630 static const InitFrame frames1[] = {
1631 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
1632 NOT_MASKED, "SPLIT "}};
1633 static const InitFrame frames2[] = {
1634 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1635 static const InitFrame frames3[] = {
1636 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1637 NOT_MASKED, "MESSAGE"}};
1638 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1639 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1640 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1641 set_stream(stream.Pass());
1644 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1645 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1649 false, WebSocketFrameHeader::kOpCodeText, AsVector("SPLIT ")));
1650 EXPECT_CALL(*event_interface_,
1652 WebSocketFrameHeader::kOpCodeContinuation,
1653 AsVector("MESSAGE")));
1656 CreateChannelAndConnectSuccessfully();
1657 base::MessageLoop::current()->RunUntilIdle();
1660 // It seems redundant to repeat the entirety of the above test, so just test a
1661 // Pong with NULL data.
1662 TEST_F(WebSocketChannelEventInterfaceTest, PongWithNullData) {
1663 scoped_ptr<ReadableFakeWebSocketStream> stream(
1664 new ReadableFakeWebSocketStream);
1665 static const InitFrame frames[] = {
1666 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1667 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1668 set_stream(stream.Pass());
1669 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1670 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1672 CreateChannelAndConnectSuccessfully();
1673 base::MessageLoop::current()->RunUntilIdle();
1676 // If a frame has an invalid header, then the connection is closed and
1677 // subsequent frames must not trigger events.
1678 TEST_F(WebSocketChannelEventInterfaceTest, FrameAfterInvalidFrame) {
1679 scoped_ptr<ReadableFakeWebSocketStream> stream(
1680 new ReadableFakeWebSocketStream);
1681 static const InitFrame frames[] = {
1682 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"},
1683 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, " WORLD"}};
1685 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1686 set_stream(stream.Pass());
1689 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1690 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1694 "A server must not mask any frames that it sends to the client."));
1697 CreateChannelAndConnectSuccessfully();
1698 base::MessageLoop::current()->RunUntilIdle();
1701 // If the renderer sends lots of small writes, we don't want to update the quota
1703 TEST_F(WebSocketChannelEventInterfaceTest, SmallWriteDoesntUpdateQuota) {
1704 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1707 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1708 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1711 CreateChannelAndConnectSuccessfully();
1712 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("B"));
1715 // If we send enough to go below send_quota_low_water_mask_ we should get our
1717 TEST_F(WebSocketChannelEventInterfaceTest, LargeWriteUpdatesQuota) {
1718 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1719 // We use this checkpoint object to verify that the quota update comes after
1721 Checkpoint checkpoint;
1724 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1725 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1726 EXPECT_CALL(checkpoint, Call(1));
1727 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1728 EXPECT_CALL(checkpoint, Call(2));
1731 CreateChannelAndConnectSuccessfully();
1733 channel_->SendFrame(true,
1734 WebSocketFrameHeader::kOpCodeText,
1735 std::vector<char>(kDefaultInitialQuota, 'B'));
1739 // Verify that our quota actually is refreshed when we are told it is.
1740 TEST_F(WebSocketChannelEventInterfaceTest, QuotaReallyIsRefreshed) {
1741 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1742 Checkpoint checkpoint;
1745 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1746 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1747 EXPECT_CALL(checkpoint, Call(1));
1748 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1749 EXPECT_CALL(checkpoint, Call(2));
1750 // If quota was not really refreshed, we would get an OnDropChannel()
1752 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1753 EXPECT_CALL(checkpoint, Call(3));
1756 CreateChannelAndConnectSuccessfully();
1758 channel_->SendFrame(true,
1759 WebSocketFrameHeader::kOpCodeText,
1760 std::vector<char>(kDefaultQuotaRefreshTrigger, 'D'));
1762 // We should have received more quota at this point.
1763 channel_->SendFrame(true,
1764 WebSocketFrameHeader::kOpCodeText,
1765 std::vector<char>(kDefaultQuotaRefreshTrigger, 'E'));
1769 // If we send more than the available quota then the connection will be closed
1771 TEST_F(WebSocketChannelEventInterfaceTest, WriteOverQuotaIsRejected) {
1772 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1775 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1776 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
1777 EXPECT_CALL(*event_interface_, OnFailChannel("Send quota exceeded"));
1780 CreateChannelAndConnectSuccessfully();
1781 channel_->SendFrame(true,
1782 WebSocketFrameHeader::kOpCodeText,
1783 std::vector<char>(kDefaultInitialQuota + 1, 'C'));
1786 // If a write fails, the channel is dropped.
1787 TEST_F(WebSocketChannelEventInterfaceTest, FailedWrite) {
1788 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
1789 Checkpoint checkpoint;
1792 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1793 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1794 EXPECT_CALL(checkpoint, Call(1));
1795 EXPECT_CALL(*event_interface_,
1796 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1797 EXPECT_CALL(checkpoint, Call(2));
1800 CreateChannelAndConnectSuccessfully();
1803 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("H"));
1807 // OnDropChannel() is called exactly once when StartClosingHandshake() is used.
1808 TEST_F(WebSocketChannelEventInterfaceTest, SendCloseDropsChannel) {
1809 set_stream(make_scoped_ptr(new EchoeyFakeWebSocketStream));
1812 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1813 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1814 EXPECT_CALL(*event_interface_,
1815 OnDropChannel(true, kWebSocketNormalClosure, "Fred"));
1818 CreateChannelAndConnectSuccessfully();
1820 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Fred");
1821 base::MessageLoop::current()->RunUntilIdle();
1824 // StartClosingHandshake() also works before connection completes, and calls
1826 TEST_F(WebSocketChannelEventInterfaceTest, CloseDuringConnection) {
1827 EXPECT_CALL(*event_interface_,
1828 OnDropChannel(false, kWebSocketErrorAbnormalClosure, ""));
1830 CreateChannelAndConnect();
1831 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Joe");
1834 // OnDropChannel() is only called once when a write() on the socket triggers a
1835 // connection reset.
1836 TEST_F(WebSocketChannelEventInterfaceTest, OnDropChannelCalledOnce) {
1837 set_stream(make_scoped_ptr(new ResetOnWriteFakeWebSocketStream));
1838 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1839 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1841 EXPECT_CALL(*event_interface_,
1842 OnDropChannel(false, kWebSocketErrorAbnormalClosure, ""))
1845 CreateChannelAndConnectSuccessfully();
1847 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("yt?"));
1848 base::MessageLoop::current()->RunUntilIdle();
1851 // When the remote server sends a Close frame with an empty payload,
1852 // WebSocketChannel should report code 1005, kWebSocketErrorNoStatusReceived.
1853 TEST_F(WebSocketChannelEventInterfaceTest, CloseWithNoPayloadGivesStatus1005) {
1854 scoped_ptr<ReadableFakeWebSocketStream> stream(
1855 new ReadableFakeWebSocketStream);
1856 static const InitFrame frames[] = {
1857 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
1858 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1859 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1860 ERR_CONNECTION_CLOSED);
1861 set_stream(stream.Pass());
1862 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1863 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1864 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1865 EXPECT_CALL(*event_interface_,
1866 OnDropChannel(true, kWebSocketErrorNoStatusReceived, _));
1868 CreateChannelAndConnectSuccessfully();
1871 // A version of the above test with NULL payload.
1872 TEST_F(WebSocketChannelEventInterfaceTest,
1873 CloseWithNullPayloadGivesStatus1005) {
1874 scoped_ptr<ReadableFakeWebSocketStream> stream(
1875 new ReadableFakeWebSocketStream);
1876 static const InitFrame frames[] = {
1877 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, NULL}};
1878 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1879 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1880 ERR_CONNECTION_CLOSED);
1881 set_stream(stream.Pass());
1882 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1883 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1884 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1885 EXPECT_CALL(*event_interface_,
1886 OnDropChannel(true, kWebSocketErrorNoStatusReceived, _));
1888 CreateChannelAndConnectSuccessfully();
1891 // If ReadFrames() returns ERR_WS_PROTOCOL_ERROR, then the connection must be
1893 TEST_F(WebSocketChannelEventInterfaceTest, SyncProtocolErrorGivesStatus1002) {
1894 scoped_ptr<ReadableFakeWebSocketStream> stream(
1895 new ReadableFakeWebSocketStream);
1896 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1897 ERR_WS_PROTOCOL_ERROR);
1898 set_stream(stream.Pass());
1899 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1900 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1902 EXPECT_CALL(*event_interface_, OnFailChannel("Invalid frame header"));
1904 CreateChannelAndConnectSuccessfully();
1907 // Async version of above test.
1908 TEST_F(WebSocketChannelEventInterfaceTest, AsyncProtocolErrorGivesStatus1002) {
1909 scoped_ptr<ReadableFakeWebSocketStream> stream(
1910 new ReadableFakeWebSocketStream);
1911 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1912 ERR_WS_PROTOCOL_ERROR);
1913 set_stream(stream.Pass());
1914 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1915 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1917 EXPECT_CALL(*event_interface_, OnFailChannel("Invalid frame header"));
1919 CreateChannelAndConnectSuccessfully();
1920 base::MessageLoop::current()->RunUntilIdle();
1923 TEST_F(WebSocketChannelEventInterfaceTest, StartHandshakeRequest) {
1926 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1927 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1928 EXPECT_CALL(*event_interface_, OnStartOpeningHandshakeCalled());
1931 CreateChannelAndConnectSuccessfully();
1933 scoped_ptr<WebSocketHandshakeRequestInfo> request_info(
1934 new WebSocketHandshakeRequestInfo(GURL("ws://www.example.com/"),
1936 connect_data_.creator.connect_delegate->OnStartOpeningHandshake(
1937 request_info.Pass());
1939 base::MessageLoop::current()->RunUntilIdle();
1942 TEST_F(WebSocketChannelEventInterfaceTest, FinishHandshakeRequest) {
1945 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1946 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1947 EXPECT_CALL(*event_interface_, OnFinishOpeningHandshakeCalled());
1950 CreateChannelAndConnectSuccessfully();
1952 scoped_refptr<HttpResponseHeaders> response_headers(
1953 new HttpResponseHeaders(""));
1954 scoped_ptr<WebSocketHandshakeResponseInfo> response_info(
1955 new WebSocketHandshakeResponseInfo(GURL("ws://www.example.com/"),
1960 connect_data_.creator.connect_delegate->OnFinishOpeningHandshake(
1961 response_info.Pass());
1962 base::MessageLoop::current()->RunUntilIdle();
1965 TEST_F(WebSocketChannelEventInterfaceTest, FailJustAfterHandshake) {
1968 EXPECT_CALL(*event_interface_, OnStartOpeningHandshakeCalled());
1969 EXPECT_CALL(*event_interface_, OnFinishOpeningHandshakeCalled());
1970 EXPECT_CALL(*event_interface_, OnFailChannel("bye"));
1973 CreateChannelAndConnect();
1975 WebSocketStream::ConnectDelegate* connect_delegate =
1976 connect_data_.creator.connect_delegate.get();
1977 GURL url("ws://www.example.com/");
1978 scoped_ptr<WebSocketHandshakeRequestInfo> request_info(
1979 new WebSocketHandshakeRequestInfo(url, base::Time()));
1980 scoped_refptr<HttpResponseHeaders> response_headers(
1981 new HttpResponseHeaders(""));
1982 scoped_ptr<WebSocketHandshakeResponseInfo> response_info(
1983 new WebSocketHandshakeResponseInfo(url,
1988 connect_delegate->OnStartOpeningHandshake(request_info.Pass());
1989 connect_delegate->OnFinishOpeningHandshake(response_info.Pass());
1991 connect_delegate->OnFailure("bye");
1992 base::MessageLoop::current()->RunUntilIdle();
1995 // Any frame after close is invalid. This test uses a Text frame. See also
1996 // test "PingAfterCloseIfRejected".
1997 TEST_F(WebSocketChannelEventInterfaceTest, DataAfterCloseIsRejected) {
1998 scoped_ptr<ReadableFakeWebSocketStream> stream(
1999 new ReadableFakeWebSocketStream);
2000 static const InitFrame frames[] = {
2001 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
2002 CLOSE_DATA(NORMAL_CLOSURE, "OK")},
2003 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "Payload"}};
2004 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2005 set_stream(stream.Pass());
2006 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2007 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2011 EXPECT_CALL(*event_interface_, OnClosingHandshake());
2012 EXPECT_CALL(*event_interface_,
2013 OnFailChannel("Data frame received after close"));
2016 CreateChannelAndConnectSuccessfully();
2019 // A Close frame with a one-byte payload elicits a specific console error
2021 TEST_F(WebSocketChannelEventInterfaceTest, OneByteClosePayloadMessage) {
2022 scoped_ptr<ReadableFakeWebSocketStream> stream(
2023 new ReadableFakeWebSocketStream);
2024 static const InitFrame frames[] = {
2025 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, "\x03"}};
2026 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2027 set_stream(stream.Pass());
2028 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2029 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2033 "Received a broken close frame containing an invalid size body."));
2035 CreateChannelAndConnectSuccessfully();
2038 // A Close frame with a reserved status code also elicits a specific console
2040 TEST_F(WebSocketChannelEventInterfaceTest, ClosePayloadReservedStatusMessage) {
2041 scoped_ptr<ReadableFakeWebSocketStream> stream(
2042 new ReadableFakeWebSocketStream);
2043 static const InitFrame frames[] = {
2044 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2045 NOT_MASKED, CLOSE_DATA(ABNORMAL_CLOSURE, "Not valid on wire")}};
2046 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2047 set_stream(stream.Pass());
2048 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2049 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2053 "Received a broken close frame containing a reserved status code."));
2055 CreateChannelAndConnectSuccessfully();
2058 // A Close frame with invalid UTF-8 also elicits a specific console error
2060 TEST_F(WebSocketChannelEventInterfaceTest, ClosePayloadInvalidReason) {
2061 scoped_ptr<ReadableFakeWebSocketStream> stream(
2062 new ReadableFakeWebSocketStream);
2063 static const InitFrame frames[] = {
2064 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2065 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
2066 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2067 set_stream(stream.Pass());
2068 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2069 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2073 "Received a broken close frame containing invalid UTF-8."));
2075 CreateChannelAndConnectSuccessfully();
2078 // The closing handshake times out and sends an OnDropChannel event if no
2079 // response to the client Close message is received.
2080 TEST_F(WebSocketChannelEventInterfaceTest,
2081 ClientInitiatedClosingHandshakeTimesOut) {
2082 scoped_ptr<ReadableFakeWebSocketStream> stream(
2083 new ReadableFakeWebSocketStream);
2084 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
2086 set_stream(stream.Pass());
2087 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2088 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2089 // This checkpoint object verifies that the OnDropChannel message comes after
2091 Checkpoint checkpoint;
2092 TestClosure completion;
2095 EXPECT_CALL(checkpoint, Call(1));
2096 EXPECT_CALL(*event_interface_,
2097 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _))
2098 .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
2100 CreateChannelAndConnectSuccessfully();
2101 // OneShotTimer is not very friendly to testing; there is no apparent way to
2102 // set an expectation on it. Instead the tests need to infer that the timeout
2103 // was fired by the behaviour of the WebSocketChannel object.
2104 channel_->SetClosingHandshakeTimeoutForTesting(
2105 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2106 channel_->StartClosingHandshake(kWebSocketNormalClosure, "");
2108 completion.WaitForResult();
2111 // The closing handshake times out and sends an OnDropChannel event if a Close
2112 // message is received but the connection isn't closed by the remote host.
2113 TEST_F(WebSocketChannelEventInterfaceTest,
2114 ServerInitiatedClosingHandshakeTimesOut) {
2115 scoped_ptr<ReadableFakeWebSocketStream> stream(
2116 new ReadableFakeWebSocketStream);
2117 static const InitFrame frames[] = {
2118 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2119 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2120 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
2121 set_stream(stream.Pass());
2122 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2123 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2124 Checkpoint checkpoint;
2125 TestClosure completion;
2128 EXPECT_CALL(checkpoint, Call(1));
2129 EXPECT_CALL(*event_interface_, OnClosingHandshake());
2130 EXPECT_CALL(*event_interface_,
2131 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _))
2132 .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
2134 CreateChannelAndConnectSuccessfully();
2135 channel_->SetClosingHandshakeTimeoutForTesting(
2136 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2138 completion.WaitForResult();
2141 // RFC6455 5.1 "a client MUST mask all frames that it sends to the server".
2142 // WebSocketChannel actually only sets the mask bit in the header, it doesn't
2143 // perform masking itself (not all transports actually use masking).
2144 TEST_F(WebSocketChannelStreamTest, SentFramesAreMasked) {
2145 static const InitFrame expected[] = {
2146 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2147 MASKED, "NEEDS MASKING"}};
2148 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2149 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2150 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2151 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2152 .WillOnce(Return(OK));
2154 CreateChannelAndConnectSuccessfully();
2155 channel_->SendFrame(
2156 true, WebSocketFrameHeader::kOpCodeText, AsVector("NEEDS MASKING"));
2159 // RFC6455 5.5.1 "The application MUST NOT send any more data frames after
2160 // sending a Close frame."
2161 TEST_F(WebSocketChannelStreamTest, NothingIsSentAfterClose) {
2162 static const InitFrame expected[] = {
2163 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2164 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
2165 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2166 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2167 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2168 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2169 .WillOnce(Return(OK));
2171 CreateChannelAndConnectSuccessfully();
2172 channel_->StartClosingHandshake(1000, "Success");
2173 channel_->SendFrame(
2174 true, WebSocketFrameHeader::kOpCodeText, AsVector("SHOULD BE IGNORED"));
2177 // RFC6455 5.5.1 "If an endpoint receives a Close frame and did not previously
2178 // send a Close frame, the endpoint MUST send a Close frame in response."
2179 TEST_F(WebSocketChannelStreamTest, CloseIsEchoedBack) {
2180 static const InitFrame frames[] = {
2181 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2182 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2183 static const InitFrame expected[] = {
2184 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2185 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2186 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2187 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2188 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2189 .WillOnce(ReturnFrames(&frames))
2190 .WillRepeatedly(Return(ERR_IO_PENDING));
2191 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2192 .WillOnce(Return(OK));
2194 CreateChannelAndConnectSuccessfully();
2197 // The converse of the above case; after sending a Close frame, we should not
2198 // send another one.
2199 TEST_F(WebSocketChannelStreamTest, CloseOnlySentOnce) {
2200 static const InitFrame expected[] = {
2201 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2202 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2203 static const InitFrame frames_init[] = {
2204 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2205 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2207 // We store the parameters that were passed to ReadFrames() so that we can
2208 // call them explicitly later.
2209 CompletionCallback read_callback;
2210 ScopedVector<WebSocketFrame>* frames = NULL;
2212 // These are not interesting.
2213 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2214 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2216 // Use a checkpoint to make the ordering of events clearer.
2217 Checkpoint checkpoint;
2220 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2221 .WillOnce(DoAll(SaveArg<0>(&frames),
2222 SaveArg<1>(&read_callback),
2223 Return(ERR_IO_PENDING)));
2224 EXPECT_CALL(checkpoint, Call(1));
2225 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2226 .WillOnce(Return(OK));
2227 EXPECT_CALL(checkpoint, Call(2));
2228 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2229 .WillOnce(Return(ERR_IO_PENDING));
2230 EXPECT_CALL(checkpoint, Call(3));
2231 // WriteFrames() must not be called again. GoogleMock will ensure that the
2232 // test fails if it is.
2235 CreateChannelAndConnectSuccessfully();
2237 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Close");
2240 *frames = CreateFrameVector(frames_init);
2241 read_callback.Run(OK);
2245 // Invalid close status codes should not be sent on the network.
2246 TEST_F(WebSocketChannelStreamTest, InvalidCloseStatusCodeNotSent) {
2247 static const InitFrame expected[] = {
2248 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2249 MASKED, CLOSE_DATA(SERVER_ERROR, "")}};
2251 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2252 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2253 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2254 .WillOnce(Return(ERR_IO_PENDING));
2256 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
2258 CreateChannelAndConnectSuccessfully();
2259 channel_->StartClosingHandshake(999, "");
2262 // A Close frame with a reason longer than 123 bytes cannot be sent on the
2264 TEST_F(WebSocketChannelStreamTest, LongCloseReasonNotSent) {
2265 static const InitFrame expected[] = {
2266 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2267 MASKED, CLOSE_DATA(SERVER_ERROR, "")}};
2269 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2270 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2271 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2272 .WillOnce(Return(ERR_IO_PENDING));
2274 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
2276 CreateChannelAndConnectSuccessfully();
2277 channel_->StartClosingHandshake(1000, std::string(124, 'A'));
2280 // We generate code 1005, kWebSocketErrorNoStatusReceived, when there is no
2281 // status in the Close message from the other side. Code 1005 is not allowed to
2282 // appear on the wire, so we should not echo it back. See test
2283 // CloseWithNoPayloadGivesStatus1005, above, for confirmation that code 1005 is
2284 // correctly generated internally.
2285 TEST_F(WebSocketChannelStreamTest, Code1005IsNotEchoed) {
2286 static const InitFrame frames[] = {
2287 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
2288 static const InitFrame expected[] = {
2289 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED, ""}};
2290 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2291 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2292 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2293 .WillOnce(ReturnFrames(&frames))
2294 .WillRepeatedly(Return(ERR_IO_PENDING));
2295 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2296 .WillOnce(Return(OK));
2298 CreateChannelAndConnectSuccessfully();
2301 TEST_F(WebSocketChannelStreamTest, Code1005IsNotEchoedNull) {
2302 static const InitFrame frames[] = {
2303 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, NULL}};
2304 static const InitFrame expected[] = {
2305 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED, ""}};
2306 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2307 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2308 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2309 .WillOnce(ReturnFrames(&frames))
2310 .WillRepeatedly(Return(ERR_IO_PENDING));
2311 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2312 .WillOnce(Return(OK));
2314 CreateChannelAndConnectSuccessfully();
2317 // Receiving an invalid UTF-8 payload in a Close frame causes us to fail the
2319 TEST_F(WebSocketChannelStreamTest, CloseFrameInvalidUtf8) {
2320 static const InitFrame frames[] = {
2321 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2322 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
2323 static const InitFrame expected[] = {
2324 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2325 MASKED, CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in Close frame")}};
2327 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2328 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2329 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2330 .WillOnce(ReturnFrames(&frames))
2331 .WillRepeatedly(Return(ERR_IO_PENDING));
2332 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2333 .WillOnce(Return(OK));
2334 EXPECT_CALL(*mock_stream_, Close());
2336 CreateChannelAndConnectSuccessfully();
2339 // RFC6455 5.5.2 "Upon receipt of a Ping frame, an endpoint MUST send a Pong
2340 // frame in response"
2341 // 5.5.3 "A Pong frame sent in response to a Ping frame must have identical
2342 // "Application data" as found in the message body of the Ping frame being
2344 TEST_F(WebSocketChannelStreamTest, PingRepliedWithPong) {
2345 static const InitFrame frames[] = {
2346 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2347 NOT_MASKED, "Application data"}};
2348 static const InitFrame expected[] = {
2349 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
2350 MASKED, "Application data"}};
2351 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2352 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2353 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2354 .WillOnce(ReturnFrames(&frames))
2355 .WillRepeatedly(Return(ERR_IO_PENDING));
2356 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2357 .WillOnce(Return(OK));
2359 CreateChannelAndConnectSuccessfully();
2362 // A ping with a NULL payload should be responded to with a Pong with a NULL
2364 TEST_F(WebSocketChannelStreamTest, NullPingRepliedWithNullPong) {
2365 static const InitFrame frames[] = {
2366 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing, NOT_MASKED, NULL}};
2367 static const InitFrame expected[] = {
2368 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, MASKED, NULL}};
2369 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2370 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2371 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2372 .WillOnce(ReturnFrames(&frames))
2373 .WillRepeatedly(Return(ERR_IO_PENDING));
2374 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2375 .WillOnce(Return(OK));
2377 CreateChannelAndConnectSuccessfully();
2380 TEST_F(WebSocketChannelStreamTest, PongInTheMiddleOfDataMessage) {
2381 static const InitFrame frames[] = {
2382 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2383 NOT_MASKED, "Application data"}};
2384 static const InitFrame expected1[] = {
2385 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
2386 static const InitFrame expected2[] = {
2387 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
2388 MASKED, "Application data"}};
2389 static const InitFrame expected3[] = {
2390 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2392 ScopedVector<WebSocketFrame>* read_frames;
2393 CompletionCallback read_callback;
2394 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2395 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2396 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2397 .WillOnce(DoAll(SaveArg<0>(&read_frames),
2398 SaveArg<1>(&read_callback),
2399 Return(ERR_IO_PENDING)))
2400 .WillRepeatedly(Return(ERR_IO_PENDING));
2404 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2405 .WillOnce(Return(OK));
2406 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2407 .WillOnce(Return(OK));
2408 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected3), _))
2409 .WillOnce(Return(OK));
2412 CreateChannelAndConnectSuccessfully();
2413 channel_->SendFrame(
2414 false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
2415 *read_frames = CreateFrameVector(frames);
2416 read_callback.Run(OK);
2417 channel_->SendFrame(
2418 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("World"));
2421 // WriteFrames() may not be called until the previous write has completed.
2422 // WebSocketChannel must buffer writes that happen in the meantime.
2423 TEST_F(WebSocketChannelStreamTest, WriteFramesOneAtATime) {
2424 static const InitFrame expected1[] = {
2425 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
2426 static const InitFrame expected2[] = {
2427 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "World"}};
2428 CompletionCallback write_callback;
2429 Checkpoint checkpoint;
2431 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2432 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2433 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2436 EXPECT_CALL(checkpoint, Call(1));
2437 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2438 .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
2439 EXPECT_CALL(checkpoint, Call(2));
2440 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2441 .WillOnce(Return(ERR_IO_PENDING));
2442 EXPECT_CALL(checkpoint, Call(3));
2445 CreateChannelAndConnectSuccessfully();
2447 channel_->SendFrame(
2448 false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
2449 channel_->SendFrame(
2450 true, WebSocketFrameHeader::kOpCodeText, AsVector("World"));
2452 write_callback.Run(OK);
2456 // WebSocketChannel must buffer frames while it is waiting for a write to
2457 // complete, and then send them in a single batch. The batching behaviour is
2458 // important to get good throughput in the "many small messages" case.
2459 TEST_F(WebSocketChannelStreamTest, WaitingMessagesAreBatched) {
2460 static const char input_letters[] = "Hello";
2461 static const InitFrame expected1[] = {
2462 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "H"}};
2463 static const InitFrame expected2[] = {
2464 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "e"},
2465 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
2466 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
2467 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "o"}};
2468 CompletionCallback write_callback;
2470 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2471 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2472 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2475 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2476 .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
2477 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2478 .WillOnce(Return(ERR_IO_PENDING));
2481 CreateChannelAndConnectSuccessfully();
2482 for (size_t i = 0; i < strlen(input_letters); ++i) {
2483 channel_->SendFrame(true,
2484 WebSocketFrameHeader::kOpCodeText,
2485 std::vector<char>(1, input_letters[i]));
2487 write_callback.Run(OK);
2490 // When the renderer sends more on a channel than it has quota for, then we send
2491 // a kWebSocketMuxErrorSendQuotaViolation status code (from the draft websocket
2492 // mux specification) back to the renderer. This should not be sent to the
2493 // remote server, which may not even implement the mux specification, and could
2494 // even be using a different extension which uses that code to mean something
2496 TEST_F(WebSocketChannelStreamTest, MuxErrorIsNotSentToStream) {
2497 static const InitFrame expected[] = {
2498 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2499 MASKED, CLOSE_DATA(GOING_AWAY, "")}};
2500 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2501 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2502 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2503 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2504 .WillOnce(Return(OK));
2505 EXPECT_CALL(*mock_stream_, Close());
2507 CreateChannelAndConnectSuccessfully();
2508 channel_->SendFrame(true,
2509 WebSocketFrameHeader::kOpCodeText,
2510 std::vector<char>(kDefaultInitialQuota + 1, 'C'));
2513 // For convenience, most of these tests use Text frames. However, the WebSocket
2514 // protocol also has Binary frames and those need to be 8-bit clean. For the
2515 // sake of completeness, this test verifies that they are.
2516 TEST_F(WebSocketChannelStreamTest, WrittenBinaryFramesAre8BitClean) {
2517 ScopedVector<WebSocketFrame>* frames = NULL;
2519 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2520 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2521 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2522 EXPECT_CALL(*mock_stream_, WriteFrames(_, _))
2523 .WillOnce(DoAll(SaveArg<0>(&frames), Return(ERR_IO_PENDING)));
2525 CreateChannelAndConnectSuccessfully();
2526 channel_->SendFrame(
2528 WebSocketFrameHeader::kOpCodeBinary,
2529 std::vector<char>(kBinaryBlob, kBinaryBlob + kBinaryBlobSize));
2530 ASSERT_TRUE(frames != NULL);
2531 ASSERT_EQ(1U, frames->size());
2532 const WebSocketFrame* out_frame = (*frames)[0];
2533 EXPECT_EQ(kBinaryBlobSize, out_frame->header.payload_length);
2534 ASSERT_TRUE(out_frame->data);
2535 EXPECT_EQ(0, memcmp(kBinaryBlob, out_frame->data->data(), kBinaryBlobSize));
2538 // Test the read path for 8-bit cleanliness as well.
2539 TEST_F(WebSocketChannelEventInterfaceTest, ReadBinaryFramesAre8BitClean) {
2540 scoped_ptr<WebSocketFrame> frame(
2541 new WebSocketFrame(WebSocketFrameHeader::kOpCodeBinary));
2542 WebSocketFrameHeader& frame_header = frame->header;
2543 frame_header.final = true;
2544 frame_header.payload_length = kBinaryBlobSize;
2545 frame->data = new IOBuffer(kBinaryBlobSize);
2546 memcpy(frame->data->data(), kBinaryBlob, kBinaryBlobSize);
2547 ScopedVector<WebSocketFrame> frames;
2548 frames.push_back(frame.release());
2549 scoped_ptr<ReadableFakeWebSocketStream> stream(
2550 new ReadableFakeWebSocketStream);
2551 stream->PrepareRawReadFrames(
2552 ReadableFakeWebSocketStream::SYNC, OK, frames.Pass());
2553 set_stream(stream.Pass());
2554 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2555 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2556 EXPECT_CALL(*event_interface_,
2558 WebSocketFrameHeader::kOpCodeBinary,
2559 std::vector<char>(kBinaryBlob,
2560 kBinaryBlob + kBinaryBlobSize)));
2562 CreateChannelAndConnectSuccessfully();
2565 // Invalid UTF-8 is not permitted in Text frames.
2566 TEST_F(WebSocketChannelSendUtf8Test, InvalidUtf8Rejected) {
2569 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2571 CreateChannelAndConnectSuccessfully();
2573 channel_->SendFrame(
2574 true, WebSocketFrameHeader::kOpCodeText, AsVector("\xff"));
2577 // A Text message cannot end with a partial UTF-8 character.
2578 TEST_F(WebSocketChannelSendUtf8Test, IncompleteCharacterInFinalFrame) {
2581 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2583 CreateChannelAndConnectSuccessfully();
2585 channel_->SendFrame(
2586 true, WebSocketFrameHeader::kOpCodeText, AsVector("\xc2"));
2589 // A non-final Text frame may end with a partial UTF-8 character (compare to
2591 TEST_F(WebSocketChannelSendUtf8Test, IncompleteCharacterInNonFinalFrame) {
2592 CreateChannelAndConnectSuccessfully();
2594 channel_->SendFrame(
2595 false, WebSocketFrameHeader::kOpCodeText, AsVector("\xc2"));
2598 // UTF-8 parsing context must be retained between frames.
2599 TEST_F(WebSocketChannelSendUtf8Test, ValidCharacterSplitBetweenFrames) {
2600 CreateChannelAndConnectSuccessfully();
2602 channel_->SendFrame(
2603 false, WebSocketFrameHeader::kOpCodeText, AsVector("\xf1"));
2604 channel_->SendFrame(true,
2605 WebSocketFrameHeader::kOpCodeContinuation,
2606 AsVector("\x80\xa0\xbf"));
2609 // Similarly, an invalid character should be detected even if split.
2610 TEST_F(WebSocketChannelSendUtf8Test, InvalidCharacterSplit) {
2613 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2615 CreateChannelAndConnectSuccessfully();
2617 channel_->SendFrame(
2618 false, WebSocketFrameHeader::kOpCodeText, AsVector("\xe1"));
2619 channel_->SendFrame(true,
2620 WebSocketFrameHeader::kOpCodeContinuation,
2621 AsVector("\x80\xa0\xbf"));
2624 // An invalid character must be detected in continuation frames.
2625 TEST_F(WebSocketChannelSendUtf8Test, InvalidByteInContinuation) {
2628 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2630 CreateChannelAndConnectSuccessfully();
2632 channel_->SendFrame(
2633 false, WebSocketFrameHeader::kOpCodeText, AsVector("foo"));
2634 channel_->SendFrame(
2635 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector("bar"));
2636 channel_->SendFrame(
2637 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("\xff"));
2640 // However, continuation frames of a Binary frame will not be tested for UTF-8
2642 TEST_F(WebSocketChannelSendUtf8Test, BinaryContinuationNotChecked) {
2643 CreateChannelAndConnectSuccessfully();
2645 channel_->SendFrame(
2646 false, WebSocketFrameHeader::kOpCodeBinary, AsVector("foo"));
2647 channel_->SendFrame(
2648 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector("bar"));
2649 channel_->SendFrame(
2650 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("\xff"));
2653 // Multiple text messages can be validated without the validation state getting
2655 TEST_F(WebSocketChannelSendUtf8Test, ValidateMultipleTextMessages) {
2656 CreateChannelAndConnectSuccessfully();
2658 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("foo"));
2659 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("bar"));
2662 // UTF-8 validation is enforced on received Text frames.
2663 TEST_F(WebSocketChannelEventInterfaceTest, ReceivedInvalidUtf8) {
2664 scoped_ptr<ReadableFakeWebSocketStream> stream(
2665 new ReadableFakeWebSocketStream);
2666 static const InitFrame frames[] = {
2667 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xff"}};
2668 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2669 set_stream(stream.Pass());
2671 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2672 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
2673 EXPECT_CALL(*event_interface_,
2674 OnFailChannel("Could not decode a text frame as UTF-8."));
2676 CreateChannelAndConnectSuccessfully();
2677 base::MessageLoop::current()->RunUntilIdle();
2680 // Invalid UTF-8 is not sent over the network.
2681 TEST_F(WebSocketChannelStreamTest, InvalidUtf8TextFrameNotSent) {
2682 static const InitFrame expected[] = {{FINAL_FRAME,
2683 WebSocketFrameHeader::kOpCodeClose,
2684 MASKED, CLOSE_DATA(GOING_AWAY, "")}};
2685 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2686 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2687 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2688 .WillRepeatedly(Return(ERR_IO_PENDING));
2689 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2690 .WillOnce(Return(OK));
2691 EXPECT_CALL(*mock_stream_, Close()).Times(1);
2693 CreateChannelAndConnectSuccessfully();
2695 channel_->SendFrame(
2696 true, WebSocketFrameHeader::kOpCodeText, AsVector("\xff"));
2699 // The rest of the tests for receiving invalid UTF-8 test the communication with
2700 // the server. Since there is only one code path, it would be redundant to
2701 // perform the same tests on the EventInterface as well.
2703 // If invalid UTF-8 is received in a Text frame, the connection is failed.
2704 TEST_F(WebSocketChannelReceiveUtf8Test, InvalidTextFrameRejected) {
2705 static const InitFrame frames[] = {
2706 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xff"}};
2707 static const InitFrame expected[] = {
2708 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
2709 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
2712 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2713 .WillOnce(ReturnFrames(&frames))
2714 .WillRepeatedly(Return(ERR_IO_PENDING));
2715 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2716 .WillOnce(Return(OK));
2717 EXPECT_CALL(*mock_stream_, Close()).Times(1);
2720 CreateChannelAndConnectSuccessfully();
2723 // A received Text message is not permitted to end with a partial UTF-8
2725 TEST_F(WebSocketChannelReceiveUtf8Test, IncompleteCharacterReceived) {
2726 static const InitFrame frames[] = {
2727 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xc2"}};
2728 static const InitFrame expected[] = {
2729 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
2730 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
2731 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2732 .WillOnce(ReturnFrames(&frames))
2733 .WillRepeatedly(Return(ERR_IO_PENDING));
2734 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2735 .WillOnce(Return(OK));
2736 EXPECT_CALL(*mock_stream_, Close()).Times(1);
2738 CreateChannelAndConnectSuccessfully();
2741 // However, a non-final Text frame may end with a partial UTF-8 character.
2742 TEST_F(WebSocketChannelReceiveUtf8Test, IncompleteCharacterIncompleteMessage) {
2743 static const InitFrame frames[] = {
2744 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xc2"}};
2745 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2746 .WillOnce(ReturnFrames(&frames))
2747 .WillRepeatedly(Return(ERR_IO_PENDING));
2749 CreateChannelAndConnectSuccessfully();
2752 // However, it will become an error if it is followed by an empty final frame.
2753 TEST_F(WebSocketChannelReceiveUtf8Test, TricksyIncompleteCharacter) {
2754 static const InitFrame frames[] = {
2755 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xc2"},
2756 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation, NOT_MASKED, ""}};
2757 static const InitFrame expected[] = {
2758 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
2759 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
2760 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2761 .WillOnce(ReturnFrames(&frames))
2762 .WillRepeatedly(Return(ERR_IO_PENDING));
2763 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2764 .WillOnce(Return(OK));
2765 EXPECT_CALL(*mock_stream_, Close()).Times(1);
2767 CreateChannelAndConnectSuccessfully();
2770 // UTF-8 parsing context must be retained between received frames of the same
2772 TEST_F(WebSocketChannelReceiveUtf8Test, ReceivedParsingContextRetained) {
2773 static const InitFrame frames[] = {
2774 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xf1"},
2775 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2776 NOT_MASKED, "\x80\xa0\xbf"}};
2777 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2778 .WillOnce(ReturnFrames(&frames))
2779 .WillRepeatedly(Return(ERR_IO_PENDING));
2781 CreateChannelAndConnectSuccessfully();
2784 // An invalid character must be detected even if split between frames.
2785 TEST_F(WebSocketChannelReceiveUtf8Test, SplitInvalidCharacterReceived) {
2786 static const InitFrame frames[] = {
2787 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xe1"},
2788 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2789 NOT_MASKED, "\x80\xa0\xbf"}};
2790 static const InitFrame expected[] = {
2791 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
2792 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
2793 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2794 .WillOnce(ReturnFrames(&frames))
2795 .WillRepeatedly(Return(ERR_IO_PENDING));
2796 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2797 .WillOnce(Return(OK));
2798 EXPECT_CALL(*mock_stream_, Close()).Times(1);
2800 CreateChannelAndConnectSuccessfully();
2803 // An invalid character received in a continuation frame must be detected.
2804 TEST_F(WebSocketChannelReceiveUtf8Test, InvalidReceivedIncontinuation) {
2805 static const InitFrame frames[] = {
2806 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "foo"},
2807 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2809 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2810 NOT_MASKED, "\xff"}};
2811 static const InitFrame expected[] = {
2812 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
2813 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
2814 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2815 .WillOnce(ReturnFrames(&frames))
2816 .WillRepeatedly(Return(ERR_IO_PENDING));
2817 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2818 .WillOnce(Return(OK));
2819 EXPECT_CALL(*mock_stream_, Close()).Times(1);
2821 CreateChannelAndConnectSuccessfully();
2824 // Continuations of binary frames must not be tested for UTF-8 validity.
2825 TEST_F(WebSocketChannelReceiveUtf8Test, ReceivedBinaryNotUtf8Tested) {
2826 static const InitFrame frames[] = {
2827 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeBinary, NOT_MASKED, "foo"},
2828 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2830 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2831 NOT_MASKED, "\xff"}};
2832 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2833 .WillOnce(ReturnFrames(&frames))
2834 .WillRepeatedly(Return(ERR_IO_PENDING));
2836 CreateChannelAndConnectSuccessfully();
2839 // Multiple Text messages can be validated.
2840 TEST_F(WebSocketChannelReceiveUtf8Test, ValidateMultipleReceived) {
2841 static const InitFrame frames[] = {
2842 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "foo"},
2843 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "bar"}};
2844 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2845 .WillOnce(ReturnFrames(&frames))
2846 .WillRepeatedly(Return(ERR_IO_PENDING));
2848 CreateChannelAndConnectSuccessfully();
2851 // If we receive another frame after Close, it is not valid. It is not
2852 // completely clear what behaviour is required from the standard in this case,
2853 // but the current implementation fails the connection. Since a Close has
2854 // already been sent, this just means closing the connection.
2855 TEST_F(WebSocketChannelStreamTest, PingAfterCloseIsRejected) {
2856 static const InitFrame frames[] = {
2857 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2858 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")},
2859 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2860 NOT_MASKED, "Ping body"}};
2861 static const InitFrame expected[] = {
2862 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2863 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2864 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2865 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2866 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2867 .WillOnce(ReturnFrames(&frames))
2868 .WillRepeatedly(Return(ERR_IO_PENDING));
2870 // We only need to verify the relative order of WriteFrames() and
2871 // Close(). The current implementation calls WriteFrames() for the Close
2872 // frame before calling ReadFrames() again, but that is an implementation
2873 // detail and better not to consider required behaviour.
2875 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2876 .WillOnce(Return(OK));
2877 EXPECT_CALL(*mock_stream_, Close()).Times(1);
2880 CreateChannelAndConnectSuccessfully();
2883 // A protocol error from the remote server should result in a close frame with
2884 // status 1002, followed by the connection closing.
2885 TEST_F(WebSocketChannelStreamTest, ProtocolError) {
2886 static const InitFrame expected[] = {
2887 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2888 MASKED, CLOSE_DATA(PROTOCOL_ERROR, "WebSocket Protocol Error")}};
2889 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2890 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2891 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2892 .WillOnce(Return(ERR_WS_PROTOCOL_ERROR));
2893 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2894 .WillOnce(Return(OK));
2895 EXPECT_CALL(*mock_stream_, Close());
2897 CreateChannelAndConnectSuccessfully();
2900 // Set the closing handshake timeout to a very tiny value before connecting.
2901 class WebSocketChannelStreamTimeoutTest : public WebSocketChannelStreamTest {
2903 WebSocketChannelStreamTimeoutTest() {}
2905 virtual void CreateChannelAndConnectSuccessfully() OVERRIDE {
2906 set_stream(mock_stream_.Pass());
2907 CreateChannelAndConnect();
2908 channel_->SetClosingHandshakeTimeoutForTesting(
2909 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2910 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2914 // In this case the server initiates the closing handshake with a Close
2915 // message. WebSocketChannel responds with a matching Close message, and waits
2916 // for the server to close the TCP/IP connection. The server never closes the
2917 // connection, so the closing handshake times out and WebSocketChannel closes
2918 // the connection itself.
2919 TEST_F(WebSocketChannelStreamTimeoutTest, ServerInitiatedCloseTimesOut) {
2920 static const InitFrame frames[] = {
2921 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2922 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2923 static const InitFrame expected[] = {
2924 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2925 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2926 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2927 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2928 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2929 .WillOnce(ReturnFrames(&frames))
2930 .WillRepeatedly(Return(ERR_IO_PENDING));
2931 Checkpoint checkpoint;
2932 TestClosure completion;
2935 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2936 .WillOnce(Return(OK));
2937 EXPECT_CALL(checkpoint, Call(1));
2938 EXPECT_CALL(*mock_stream_, Close())
2939 .WillOnce(InvokeClosure(completion.closure()));
2942 CreateChannelAndConnectSuccessfully();
2944 completion.WaitForResult();
2947 // In this case the client initiates the closing handshake by sending a Close
2948 // message. WebSocketChannel waits for a Close message in response from the
2949 // server. The server never responds to the Close message, so the closing
2950 // handshake times out and WebSocketChannel closes the connection.
2951 TEST_F(WebSocketChannelStreamTimeoutTest, ClientInitiatedCloseTimesOut) {
2952 static const InitFrame expected[] = {
2953 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2954 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2955 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2956 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2957 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2958 .WillRepeatedly(Return(ERR_IO_PENDING));
2959 TestClosure completion;
2962 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2963 .WillOnce(Return(OK));
2964 EXPECT_CALL(*mock_stream_, Close())
2965 .WillOnce(InvokeClosure(completion.closure()));
2968 CreateChannelAndConnectSuccessfully();
2969 channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
2970 completion.WaitForResult();
2973 // In this case the client initiates the closing handshake and the server
2974 // responds with a matching Close message. WebSocketChannel waits for the server
2975 // to close the TCP/IP connection, but it never does. The closing handshake
2976 // times out and WebSocketChannel closes the connection.
2977 TEST_F(WebSocketChannelStreamTimeoutTest, ConnectionCloseTimesOut) {
2978 static const InitFrame expected[] = {
2979 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2980 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2981 static const InitFrame frames[] = {
2982 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2983 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2984 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2985 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2986 TestClosure completion;
2987 ScopedVector<WebSocketFrame>* read_frames = NULL;
2988 CompletionCallback read_callback;
2991 // Copy the arguments to ReadFrames so that the test can call the callback
2992 // after it has send the close message.
2993 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2994 .WillOnce(DoAll(SaveArg<0>(&read_frames),
2995 SaveArg<1>(&read_callback),
2996 Return(ERR_IO_PENDING)));
2997 // The first real event that happens is the client sending the Close
2999 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3000 .WillOnce(Return(OK));
3001 // The |read_frames| callback is called (from this test case) at this
3002 // point. ReadFrames is called again by WebSocketChannel, waiting for
3003 // ERR_CONNECTION_CLOSED.
3004 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3005 .WillOnce(Return(ERR_IO_PENDING));
3006 // The timeout happens and so WebSocketChannel closes the stream.
3007 EXPECT_CALL(*mock_stream_, Close())
3008 .WillOnce(InvokeClosure(completion.closure()));
3011 CreateChannelAndConnectSuccessfully();
3012 channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
3013 ASSERT_TRUE(read_frames);
3014 // Provide the "Close" message from the server.
3015 *read_frames = CreateFrameVector(frames);
3016 read_callback.Run(OK);
3017 completion.WaitForResult();