Check USB device path access when prompting users to select a device.
[chromium-blink-merge.git] / net / websockets / websocket_channel_test.cc
blob57dd2da9d90eb4ef3dad4f4ab758d8ac5282bd85
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"
7 #include <limits.h>
8 #include <string.h>
10 #include <iostream>
11 #include <string>
12 #include <vector>
14 #include "base/bind.h"
15 #include "base/bind_helpers.h"
16 #include "base/callback.h"
17 #include "base/location.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/memory/scoped_vector.h"
20 #include "base/memory/weak_ptr.h"
21 #include "base/message_loop/message_loop.h"
22 #include "base/strings/string_piece.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/test_completion_callback.h"
25 #include "net/http/http_response_headers.h"
26 #include "net/url_request/url_request_context.h"
27 #include "net/websockets/websocket_errors.h"
28 #include "net/websockets/websocket_event_interface.h"
29 #include "net/websockets/websocket_handshake_request_info.h"
30 #include "net/websockets/websocket_handshake_response_info.h"
31 #include "net/websockets/websocket_mux.h"
32 #include "testing/gmock/include/gmock/gmock.h"
33 #include "testing/gtest/include/gtest/gtest.h"
34 #include "url/gurl.h"
35 #include "url/origin.h"
37 // Hacky macros to construct the body of a Close message from a code and a
38 // string, while ensuring the result is a compile-time constant string.
39 // Use like CLOSE_DATA(NORMAL_CLOSURE, "Explanation String")
40 #define CLOSE_DATA(code, string) WEBSOCKET_CLOSE_CODE_AS_STRING_##code string
41 #define WEBSOCKET_CLOSE_CODE_AS_STRING_NORMAL_CLOSURE "\x03\xe8"
42 #define WEBSOCKET_CLOSE_CODE_AS_STRING_GOING_AWAY "\x03\xe9"
43 #define WEBSOCKET_CLOSE_CODE_AS_STRING_PROTOCOL_ERROR "\x03\xea"
44 #define WEBSOCKET_CLOSE_CODE_AS_STRING_ABNORMAL_CLOSURE "\x03\xee"
45 #define WEBSOCKET_CLOSE_CODE_AS_STRING_SERVER_ERROR "\x03\xf3"
47 namespace net {
49 // Printing helpers to allow GoogleMock to print frames. These are explicitly
50 // designed to look like the static initialisation format we use in these
51 // tests. They have to live in the net namespace in order to be found by
52 // GoogleMock; a nested anonymous namespace will not work.
54 std::ostream& operator<<(std::ostream& os, const WebSocketFrameHeader& header) {
55 return os << (header.final ? "FINAL_FRAME" : "NOT_FINAL_FRAME") << ", "
56 << header.opcode << ", "
57 << (header.masked ? "MASKED" : "NOT_MASKED");
60 std::ostream& operator<<(std::ostream& os, const WebSocketFrame& frame) {
61 os << "{" << frame.header << ", ";
62 if (frame.data.get()) {
63 return os << "\"" << base::StringPiece(frame.data->data(),
64 frame.header.payload_length)
65 << "\"}";
67 return os << "NULL}";
70 std::ostream& operator<<(std::ostream& os,
71 const ScopedVector<WebSocketFrame>& vector) {
72 os << "{";
73 bool first = true;
74 for (ScopedVector<WebSocketFrame>::const_iterator it = vector.begin();
75 it != vector.end();
76 ++it) {
77 if (!first) {
78 os << ",\n";
79 } else {
80 first = false;
82 os << **it;
84 return os << "}";
87 std::ostream& operator<<(std::ostream& os,
88 const ScopedVector<WebSocketFrame>* vector) {
89 return os << '&' << *vector;
92 namespace {
94 using ::base::TimeDelta;
96 using ::testing::AnyNumber;
97 using ::testing::DefaultValue;
98 using ::testing::InSequence;
99 using ::testing::MockFunction;
100 using ::testing::NotNull;
101 using ::testing::Return;
102 using ::testing::SaveArg;
103 using ::testing::StrictMock;
104 using ::testing::_;
106 // A selection of characters that have traditionally been mangled in some
107 // environment or other, for testing 8-bit cleanliness.
108 const char kBinaryBlob[] = {'\n', '\r', // BACKWARDS CRNL
109 '\0', // nul
110 '\x7F', // DEL
111 '\x80', '\xFF', // NOT VALID UTF-8
112 '\x1A', // Control-Z, EOF on DOS
113 '\x03', // Control-C
114 '\x04', // EOT, special for Unix terms
115 '\x1B', // ESC, often special
116 '\b', // backspace
117 '\'', // single-quote, special in PHP
119 const size_t kBinaryBlobSize = arraysize(kBinaryBlob);
121 // The amount of quota a new connection gets by default.
122 // TODO(ricea): If kDefaultSendQuotaHighWaterMark changes, then this value will
123 // need to be updated.
124 const size_t kDefaultInitialQuota = 1 << 17;
125 // The amount of bytes we need to send after the initial connection to trigger a
126 // quota refresh. TODO(ricea): Change this if kDefaultSendQuotaHighWaterMark or
127 // kDefaultSendQuotaLowWaterMark change.
128 const size_t kDefaultQuotaRefreshTrigger = (1 << 16) + 1;
130 const int kVeryBigTimeoutMillis = 60 * 60 * 24 * 1000;
132 // TestTimeouts::tiny_timeout() is 100ms! I could run halfway around the world
133 // in that time! I would like my tests to run a bit quicker.
134 const int kVeryTinyTimeoutMillis = 1;
136 // Enough quota to pass any test.
137 const int64 kPlentyOfQuota = INT_MAX;
139 typedef WebSocketEventInterface::ChannelState ChannelState;
140 const ChannelState CHANNEL_ALIVE = WebSocketEventInterface::CHANNEL_ALIVE;
141 const ChannelState CHANNEL_DELETED = WebSocketEventInterface::CHANNEL_DELETED;
143 // This typedef mainly exists to avoid having to repeat the "NOLINT" incantation
144 // all over the place.
145 typedef StrictMock< MockFunction<void(int)> > Checkpoint; // NOLINT
147 // This mock is for testing expectations about how the EventInterface is used.
148 class MockWebSocketEventInterface : public WebSocketEventInterface {
149 public:
150 MockWebSocketEventInterface() {}
152 MOCK_METHOD2(OnAddChannelResponse,
153 ChannelState(const std::string&,
154 const std::string&)); // NOLINT
155 MOCK_METHOD3(OnDataFrame,
156 ChannelState(bool,
157 WebSocketMessageType,
158 const std::vector<char>&)); // NOLINT
159 MOCK_METHOD1(OnFlowControl, ChannelState(int64)); // NOLINT
160 MOCK_METHOD0(OnClosingHandshake, ChannelState(void)); // NOLINT
161 MOCK_METHOD1(OnFailChannel, ChannelState(const std::string&)); // NOLINT
162 MOCK_METHOD3(OnDropChannel,
163 ChannelState(bool, uint16, const std::string&)); // NOLINT
165 // We can't use GMock with scoped_ptr.
166 ChannelState OnStartOpeningHandshake(
167 scoped_ptr<WebSocketHandshakeRequestInfo>) override {
168 OnStartOpeningHandshakeCalled();
169 return CHANNEL_ALIVE;
171 ChannelState OnFinishOpeningHandshake(
172 scoped_ptr<WebSocketHandshakeResponseInfo>) override {
173 OnFinishOpeningHandshakeCalled();
174 return CHANNEL_ALIVE;
176 virtual ChannelState OnSSLCertificateError(
177 scoped_ptr<SSLErrorCallbacks> ssl_error_callbacks,
178 const GURL& url,
179 const SSLInfo& ssl_info,
180 bool fatal) override {
181 OnSSLCertificateErrorCalled(
182 ssl_error_callbacks.get(), url, ssl_info, fatal);
183 return CHANNEL_ALIVE;
186 MOCK_METHOD0(OnStartOpeningHandshakeCalled, void()); // NOLINT
187 MOCK_METHOD0(OnFinishOpeningHandshakeCalled, void()); // NOLINT
188 MOCK_METHOD4(
189 OnSSLCertificateErrorCalled,
190 void(SSLErrorCallbacks*, const GURL&, const SSLInfo&, bool)); // NOLINT
193 // This fake EventInterface is for tests which need a WebSocketEventInterface
194 // implementation but are not verifying how it is used.
195 class FakeWebSocketEventInterface : public WebSocketEventInterface {
196 ChannelState OnAddChannelResponse(const std::string& selected_protocol,
197 const std::string& extensions) override {
198 return CHANNEL_ALIVE;
200 ChannelState OnDataFrame(bool fin,
201 WebSocketMessageType type,
202 const std::vector<char>& data) override {
203 return CHANNEL_ALIVE;
205 ChannelState OnFlowControl(int64 quota) override { return CHANNEL_ALIVE; }
206 ChannelState OnClosingHandshake() override { return CHANNEL_ALIVE; }
207 ChannelState OnFailChannel(const std::string& message) override {
208 return CHANNEL_DELETED;
210 ChannelState OnDropChannel(bool was_clean,
211 uint16 code,
212 const std::string& reason) override {
213 return CHANNEL_DELETED;
215 ChannelState OnStartOpeningHandshake(
216 scoped_ptr<WebSocketHandshakeRequestInfo> request) override {
217 return CHANNEL_ALIVE;
219 ChannelState OnFinishOpeningHandshake(
220 scoped_ptr<WebSocketHandshakeResponseInfo> response) override {
221 return CHANNEL_ALIVE;
223 ChannelState OnSSLCertificateError(
224 scoped_ptr<SSLErrorCallbacks> ssl_error_callbacks,
225 const GURL& url,
226 const SSLInfo& ssl_info,
227 bool fatal) override {
228 return CHANNEL_ALIVE;
232 // This fake WebSocketStream is for tests that require a WebSocketStream but are
233 // not testing the way it is used. It has minimal functionality to return
234 // the |protocol| and |extensions| that it was constructed with.
235 class FakeWebSocketStream : public WebSocketStream {
236 public:
237 // Constructs with empty protocol and extensions.
238 FakeWebSocketStream() {}
240 // Constructs with specified protocol and extensions.
241 FakeWebSocketStream(const std::string& protocol,
242 const std::string& extensions)
243 : protocol_(protocol), extensions_(extensions) {}
245 int ReadFrames(ScopedVector<WebSocketFrame>* frames,
246 const CompletionCallback& callback) override {
247 return ERR_IO_PENDING;
250 int WriteFrames(ScopedVector<WebSocketFrame>* frames,
251 const CompletionCallback& callback) override {
252 return ERR_IO_PENDING;
255 void Close() override {}
257 // Returns the string passed to the constructor.
258 std::string GetSubProtocol() const override { return protocol_; }
260 // Returns the string passed to the constructor.
261 std::string GetExtensions() const override { return extensions_; }
263 private:
264 // The string to return from GetSubProtocol().
265 std::string protocol_;
267 // The string to return from GetExtensions().
268 std::string extensions_;
271 // To make the static initialisers easier to read, we use enums rather than
272 // bools.
273 enum IsFinal { NOT_FINAL_FRAME, FINAL_FRAME };
275 enum IsMasked { NOT_MASKED, MASKED };
277 // This is used to initialise a WebSocketFrame but is statically initialisable.
278 struct InitFrame {
279 IsFinal final;
280 // Reserved fields omitted for now. Add them if you need them.
281 WebSocketFrameHeader::OpCode opcode;
282 IsMasked masked;
284 // Will be used to create the IOBuffer member. Can be NULL for NULL data. Is a
285 // nul-terminated string for ease-of-use. |header.payload_length| is
286 // initialised from |strlen(data)|. This means it is not 8-bit clean, but this
287 // is not an issue for test data.
288 const char* const data;
291 // For GoogleMock
292 std::ostream& operator<<(std::ostream& os, const InitFrame& frame) {
293 os << "{" << (frame.final == FINAL_FRAME ? "FINAL_FRAME" : "NOT_FINAL_FRAME")
294 << ", " << frame.opcode << ", "
295 << (frame.masked == MASKED ? "MASKED" : "NOT_MASKED") << ", ";
296 if (frame.data) {
297 return os << "\"" << frame.data << "\"}";
299 return os << "NULL}";
302 template <size_t N>
303 std::ostream& operator<<(std::ostream& os, const InitFrame (&frames)[N]) {
304 os << "{";
305 bool first = true;
306 for (size_t i = 0; i < N; ++i) {
307 if (!first) {
308 os << ",\n";
309 } else {
310 first = false;
312 os << frames[i];
314 return os << "}";
317 // Convert a const array of InitFrame structs to the format used at
318 // runtime. Templated on the size of the array to save typing.
319 template <size_t N>
320 ScopedVector<WebSocketFrame> CreateFrameVector(
321 const InitFrame (&source_frames)[N]) {
322 ScopedVector<WebSocketFrame> result_frames;
323 result_frames.reserve(N);
324 for (size_t i = 0; i < N; ++i) {
325 const InitFrame& source_frame = source_frames[i];
326 scoped_ptr<WebSocketFrame> result_frame(
327 new WebSocketFrame(source_frame.opcode));
328 size_t frame_length = source_frame.data ? strlen(source_frame.data) : 0;
329 WebSocketFrameHeader& result_header = result_frame->header;
330 result_header.final = (source_frame.final == FINAL_FRAME);
331 result_header.masked = (source_frame.masked == MASKED);
332 result_header.payload_length = frame_length;
333 if (source_frame.data) {
334 result_frame->data = new IOBuffer(frame_length);
335 memcpy(result_frame->data->data(), source_frame.data, frame_length);
337 result_frames.push_back(result_frame.release());
339 return result_frames.Pass();
342 // A GoogleMock action which can be used to respond to call to ReadFrames with
343 // some frames. Use like ReadFrames(_, _).WillOnce(ReturnFrames(&frames));
344 // |frames| is an array of InitFrame. |frames| needs to be passed by pointer
345 // because otherwise it will be treated as a pointer and the array size
346 // information will be lost.
347 ACTION_P(ReturnFrames, source_frames) {
348 *arg0 = CreateFrameVector(*source_frames);
349 return OK;
352 // The implementation of a GoogleMock matcher which can be used to compare a
353 // ScopedVector<WebSocketFrame>* against an expectation defined as an array of
354 // InitFrame objects. Although it is possible to compose built-in GoogleMock
355 // matchers to check the contents of a WebSocketFrame, the results are so
356 // unreadable that it is better to use this matcher.
357 template <size_t N>
358 class EqualsFramesMatcher
359 : public ::testing::MatcherInterface<ScopedVector<WebSocketFrame>*> {
360 public:
361 EqualsFramesMatcher(const InitFrame (*expect_frames)[N])
362 : expect_frames_(expect_frames) {}
364 virtual bool MatchAndExplain(ScopedVector<WebSocketFrame>* actual_frames,
365 ::testing::MatchResultListener* listener) const {
366 if (actual_frames->size() != N) {
367 *listener << "the vector size is " << actual_frames->size();
368 return false;
370 for (size_t i = 0; i < N; ++i) {
371 const WebSocketFrame& actual_frame = *(*actual_frames)[i];
372 const InitFrame& expected_frame = (*expect_frames_)[i];
373 if (actual_frame.header.final != (expected_frame.final == FINAL_FRAME)) {
374 *listener << "the frame is marked as "
375 << (actual_frame.header.final ? "" : "not ") << "final";
376 return false;
378 if (actual_frame.header.opcode != expected_frame.opcode) {
379 *listener << "the opcode is " << actual_frame.header.opcode;
380 return false;
382 if (actual_frame.header.masked != (expected_frame.masked == MASKED)) {
383 *listener << "the frame is "
384 << (actual_frame.header.masked ? "masked" : "not masked");
385 return false;
387 const size_t expected_length =
388 expected_frame.data ? strlen(expected_frame.data) : 0;
389 if (actual_frame.header.payload_length != expected_length) {
390 *listener << "the payload length is "
391 << actual_frame.header.payload_length;
392 return false;
394 if (expected_length != 0 &&
395 memcmp(actual_frame.data->data(),
396 expected_frame.data,
397 actual_frame.header.payload_length) != 0) {
398 *listener << "the data content differs";
399 return false;
402 return true;
405 virtual void DescribeTo(std::ostream* os) const {
406 *os << "matches " << *expect_frames_;
409 virtual void DescribeNegationTo(std::ostream* os) const {
410 *os << "does not match " << *expect_frames_;
413 private:
414 const InitFrame (*expect_frames_)[N];
417 // The definition of EqualsFrames GoogleMock matcher. Unlike the ReturnFrames
418 // action, this can take the array by reference.
419 template <size_t N>
420 ::testing::Matcher<ScopedVector<WebSocketFrame>*> EqualsFrames(
421 const InitFrame (&frames)[N]) {
422 return ::testing::MakeMatcher(new EqualsFramesMatcher<N>(&frames));
425 // A GoogleMock action to run a Closure.
426 ACTION_P(InvokeClosure, closure) { closure.Run(); }
428 // A GoogleMock action to run a Closure and return CHANNEL_DELETED.
429 ACTION_P(InvokeClosureReturnDeleted, closure) {
430 closure.Run();
431 return WebSocketEventInterface::CHANNEL_DELETED;
434 // A FakeWebSocketStream whose ReadFrames() function returns data.
435 class ReadableFakeWebSocketStream : public FakeWebSocketStream {
436 public:
437 enum IsSync { SYNC, ASYNC };
439 // After constructing the object, call PrepareReadFrames() once for each
440 // time you wish it to return from the test.
441 ReadableFakeWebSocketStream() : index_(0), read_frames_pending_(false) {}
443 // Check that all the prepared responses have been consumed.
444 ~ReadableFakeWebSocketStream() override {
445 CHECK(index_ >= responses_.size());
446 CHECK(!read_frames_pending_);
449 // Prepares a fake response. Fake responses will be returned from ReadFrames()
450 // in the same order they were prepared with PrepareReadFrames() and
451 // PrepareReadFramesError(). If |async| is ASYNC, then ReadFrames() will
452 // return ERR_IO_PENDING and the callback will be scheduled to run on the
453 // message loop. This requires the test case to run the message loop. If
454 // |async| is SYNC, the response will be returned synchronously. |error| is
455 // returned directly from ReadFrames() in the synchronous case, or passed to
456 // the callback in the asynchronous case. |frames| will be converted to a
457 // ScopedVector<WebSocketFrame> and copied to the pointer that was passed to
458 // ReadFrames().
459 template <size_t N>
460 void PrepareReadFrames(IsSync async,
461 int error,
462 const InitFrame (&frames)[N]) {
463 responses_.push_back(new Response(async, error, CreateFrameVector(frames)));
466 // An alternate version of PrepareReadFrames for when we need to construct
467 // the frames manually.
468 void PrepareRawReadFrames(IsSync async,
469 int error,
470 ScopedVector<WebSocketFrame> frames) {
471 responses_.push_back(new Response(async, error, frames.Pass()));
474 // Prepares a fake error response (ie. there is no data).
475 void PrepareReadFramesError(IsSync async, int error) {
476 responses_.push_back(
477 new Response(async, error, ScopedVector<WebSocketFrame>()));
480 int ReadFrames(ScopedVector<WebSocketFrame>* frames,
481 const CompletionCallback& callback) override {
482 CHECK(!read_frames_pending_);
483 if (index_ >= responses_.size())
484 return ERR_IO_PENDING;
485 if (responses_[index_]->async == ASYNC) {
486 read_frames_pending_ = true;
487 base::MessageLoop::current()->PostTask(
488 FROM_HERE,
489 base::Bind(&ReadableFakeWebSocketStream::DoCallback,
490 base::Unretained(this),
491 frames,
492 callback));
493 return ERR_IO_PENDING;
494 } else {
495 frames->swap(responses_[index_]->frames);
496 return responses_[index_++]->error;
500 private:
501 void DoCallback(ScopedVector<WebSocketFrame>* frames,
502 const CompletionCallback& callback) {
503 read_frames_pending_ = false;
504 frames->swap(responses_[index_]->frames);
505 callback.Run(responses_[index_++]->error);
506 return;
509 struct Response {
510 Response(IsSync async, int error, ScopedVector<WebSocketFrame> frames)
511 : async(async), error(error), frames(frames.Pass()) {}
513 IsSync async;
514 int error;
515 ScopedVector<WebSocketFrame> frames;
517 private:
518 // Bad things will happen if we attempt to copy or assign |frames|.
519 DISALLOW_COPY_AND_ASSIGN(Response);
521 ScopedVector<Response> responses_;
523 // The index into the responses_ array of the next response to be returned.
524 size_t index_;
526 // True when an async response from ReadFrames() is pending. This only applies
527 // to "real" async responses. Once all the prepared responses have been
528 // returned, ReadFrames() returns ERR_IO_PENDING but read_frames_pending_ is
529 // not set to true.
530 bool read_frames_pending_;
533 // A FakeWebSocketStream where writes always complete successfully and
534 // synchronously.
535 class WriteableFakeWebSocketStream : public FakeWebSocketStream {
536 public:
537 int WriteFrames(ScopedVector<WebSocketFrame>* frames,
538 const CompletionCallback& callback) override {
539 return OK;
543 // A FakeWebSocketStream where writes always fail.
544 class UnWriteableFakeWebSocketStream : public FakeWebSocketStream {
545 public:
546 int WriteFrames(ScopedVector<WebSocketFrame>* frames,
547 const CompletionCallback& callback) override {
548 return ERR_CONNECTION_RESET;
552 // A FakeWebSocketStream which echoes any frames written back. Clears the
553 // "masked" header bit, but makes no other checks for validity. Tests using this
554 // must run the MessageLoop to receive the callback(s). If a message with opcode
555 // Close is echoed, then an ERR_CONNECTION_CLOSED is returned in the next
556 // callback. The test must do something to cause WriteFrames() to be called,
557 // otherwise the ReadFrames() callback will never be called.
558 class EchoeyFakeWebSocketStream : public FakeWebSocketStream {
559 public:
560 EchoeyFakeWebSocketStream() : read_frames_(NULL), done_(false) {}
562 int WriteFrames(ScopedVector<WebSocketFrame>* frames,
563 const CompletionCallback& callback) override {
564 // Users of WebSocketStream will not expect the ReadFrames() callback to be
565 // called from within WriteFrames(), so post it to the message loop instead.
566 stored_frames_.insert(stored_frames_.end(), frames->begin(), frames->end());
567 frames->weak_clear();
568 PostCallback();
569 return OK;
572 int ReadFrames(ScopedVector<WebSocketFrame>* frames,
573 const CompletionCallback& callback) override {
574 read_callback_ = callback;
575 read_frames_ = frames;
576 if (done_)
577 PostCallback();
578 return ERR_IO_PENDING;
581 private:
582 void PostCallback() {
583 base::MessageLoop::current()->PostTask(
584 FROM_HERE,
585 base::Bind(&EchoeyFakeWebSocketStream::DoCallback,
586 base::Unretained(this)));
589 void DoCallback() {
590 if (done_) {
591 read_callback_.Run(ERR_CONNECTION_CLOSED);
592 } else if (!stored_frames_.empty()) {
593 done_ = MoveFrames(read_frames_);
594 read_frames_ = NULL;
595 read_callback_.Run(OK);
599 // Copy the frames stored in stored_frames_ to |out|, while clearing the
600 // "masked" header bit. Returns true if a Close Frame was seen, false
601 // otherwise.
602 bool MoveFrames(ScopedVector<WebSocketFrame>* out) {
603 bool seen_close = false;
604 *out = stored_frames_.Pass();
605 for (ScopedVector<WebSocketFrame>::iterator it = out->begin();
606 it != out->end();
607 ++it) {
608 WebSocketFrameHeader& header = (*it)->header;
609 header.masked = false;
610 if (header.opcode == WebSocketFrameHeader::kOpCodeClose)
611 seen_close = true;
613 return seen_close;
616 ScopedVector<WebSocketFrame> stored_frames_;
617 CompletionCallback read_callback_;
618 // Owned by the caller of ReadFrames().
619 ScopedVector<WebSocketFrame>* read_frames_;
620 // True if we should close the connection.
621 bool done_;
624 // A FakeWebSocketStream where writes trigger a connection reset.
625 // This differs from UnWriteableFakeWebSocketStream in that it is asynchronous
626 // and triggers ReadFrames to return a reset as well. Tests using this need to
627 // run the message loop. There are two tricky parts here:
628 // 1. Calling the write callback may call Close(), after which the read callback
629 // should not be called.
630 // 2. Calling either callback may delete the stream altogether.
631 class ResetOnWriteFakeWebSocketStream : public FakeWebSocketStream {
632 public:
633 ResetOnWriteFakeWebSocketStream() : closed_(false), weak_ptr_factory_(this) {}
635 int WriteFrames(ScopedVector<WebSocketFrame>* frames,
636 const CompletionCallback& callback) override {
637 base::MessageLoop::current()->PostTask(
638 FROM_HERE,
639 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
640 weak_ptr_factory_.GetWeakPtr(),
641 callback,
642 ERR_CONNECTION_RESET));
643 base::MessageLoop::current()->PostTask(
644 FROM_HERE,
645 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
646 weak_ptr_factory_.GetWeakPtr(),
647 read_callback_,
648 ERR_CONNECTION_RESET));
649 return ERR_IO_PENDING;
652 int ReadFrames(ScopedVector<WebSocketFrame>* frames,
653 const CompletionCallback& callback) override {
654 read_callback_ = callback;
655 return ERR_IO_PENDING;
658 void Close() override { closed_ = true; }
660 private:
661 void CallCallbackUnlessClosed(const CompletionCallback& callback, int value) {
662 if (!closed_)
663 callback.Run(value);
666 CompletionCallback read_callback_;
667 bool closed_;
668 // An IO error can result in the socket being deleted, so we use weak pointers
669 // to ensure correct behaviour in that case.
670 base::WeakPtrFactory<ResetOnWriteFakeWebSocketStream> weak_ptr_factory_;
673 // This mock is for verifying that WebSocket protocol semantics are obeyed (to
674 // the extent that they are implemented in WebSocketCommon).
675 class MockWebSocketStream : public WebSocketStream {
676 public:
677 MOCK_METHOD2(ReadFrames,
678 int(ScopedVector<WebSocketFrame>* frames,
679 const CompletionCallback& callback));
680 MOCK_METHOD2(WriteFrames,
681 int(ScopedVector<WebSocketFrame>* frames,
682 const CompletionCallback& callback));
683 MOCK_METHOD0(Close, void());
684 MOCK_CONST_METHOD0(GetSubProtocol, std::string());
685 MOCK_CONST_METHOD0(GetExtensions, std::string());
686 MOCK_METHOD0(AsWebSocketStream, WebSocketStream*());
689 struct ArgumentCopyingWebSocketStreamCreator {
690 scoped_ptr<WebSocketStreamRequest> Create(
691 const GURL& socket_url,
692 const std::vector<std::string>& requested_subprotocols,
693 const url::Origin& origin,
694 URLRequestContext* url_request_context,
695 const BoundNetLog& net_log,
696 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate) {
697 this->socket_url = socket_url;
698 this->requested_subprotocols = requested_subprotocols;
699 this->origin = origin;
700 this->url_request_context = url_request_context;
701 this->net_log = net_log;
702 this->connect_delegate = connect_delegate.Pass();
703 return make_scoped_ptr(new WebSocketStreamRequest);
706 GURL socket_url;
707 url::Origin origin;
708 std::vector<std::string> requested_subprotocols;
709 URLRequestContext* url_request_context;
710 BoundNetLog net_log;
711 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate;
714 // Converts a std::string to a std::vector<char>. For test purposes, it is
715 // convenient to be able to specify data as a string, but the
716 // WebSocketEventInterface requires the vector<char> type.
717 std::vector<char> AsVector(const std::string& s) {
718 return std::vector<char>(s.begin(), s.end());
721 class FakeSSLErrorCallbacks
722 : public WebSocketEventInterface::SSLErrorCallbacks {
723 public:
724 void CancelSSLRequest(int error, const SSLInfo* ssl_info) override {}
725 void ContinueSSLRequest() override {}
728 // Base class for all test fixtures.
729 class WebSocketChannelTest : public ::testing::Test {
730 protected:
731 WebSocketChannelTest() : stream_(new FakeWebSocketStream) {}
733 // Creates a new WebSocketChannel and connects it, using the settings stored
734 // in |connect_data_|.
735 void CreateChannelAndConnect() {
736 channel_.reset(new WebSocketChannel(CreateEventInterface(),
737 &connect_data_.url_request_context));
738 channel_->SendAddChannelRequestForTesting(
739 connect_data_.socket_url,
740 connect_data_.requested_subprotocols,
741 connect_data_.origin,
742 base::Bind(&ArgumentCopyingWebSocketStreamCreator::Create,
743 base::Unretained(&connect_data_.creator)));
746 // Same as CreateChannelAndConnect(), but calls the on_success callback as
747 // well. This method is virtual so that subclasses can also set the stream.
748 virtual void CreateChannelAndConnectSuccessfully() {
749 CreateChannelAndConnect();
750 // Most tests aren't concerned with flow control from the renderer, so allow
751 // MAX_INT quota units.
752 channel_->SendFlowControl(kPlentyOfQuota);
753 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
756 // Returns a WebSocketEventInterface to be passed to the WebSocketChannel.
757 // This implementation returns a newly-created fake. Subclasses may return a
758 // mock instead.
759 virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() {
760 return scoped_ptr<WebSocketEventInterface>(new FakeWebSocketEventInterface);
763 // This method serves no other purpose than to provide a nice syntax for
764 // assigning to stream_. class T must be a subclass of WebSocketStream or you
765 // will have unpleasant compile errors.
766 template <class T>
767 void set_stream(scoped_ptr<T> stream) {
768 stream_ = stream.Pass();
771 // A struct containing the data that will be used to connect the channel.
772 // Grouped for readability.
773 struct ConnectData {
774 ConnectData() : socket_url("ws://ws/"), origin("http://ws") {}
776 // URLRequestContext object.
777 URLRequestContext url_request_context;
779 // URL to (pretend to) connect to.
780 GURL socket_url;
781 // Requested protocols for the request.
782 std::vector<std::string> requested_subprotocols;
783 // Origin of the request
784 url::Origin origin;
786 // A fake WebSocketStreamCreator that just records its arguments.
787 ArgumentCopyingWebSocketStreamCreator creator;
789 ConnectData connect_data_;
791 // The channel we are testing. Not initialised until SetChannel() is called.
792 scoped_ptr<WebSocketChannel> channel_;
794 // A mock or fake stream for tests that need one.
795 scoped_ptr<WebSocketStream> stream_;
798 // enum of WebSocketEventInterface calls. These are intended to be or'd together
799 // in order to instruct WebSocketChannelDeletingTest when it should fail.
800 enum EventInterfaceCall {
801 EVENT_ON_ADD_CHANNEL_RESPONSE = 0x1,
802 EVENT_ON_DATA_FRAME = 0x2,
803 EVENT_ON_FLOW_CONTROL = 0x4,
804 EVENT_ON_CLOSING_HANDSHAKE = 0x8,
805 EVENT_ON_FAIL_CHANNEL = 0x10,
806 EVENT_ON_DROP_CHANNEL = 0x20,
807 EVENT_ON_START_OPENING_HANDSHAKE = 0x40,
808 EVENT_ON_FINISH_OPENING_HANDSHAKE = 0x80,
809 EVENT_ON_SSL_CERTIFICATE_ERROR = 0x100,
812 class WebSocketChannelDeletingTest : public WebSocketChannelTest {
813 public:
814 ChannelState DeleteIfDeleting(EventInterfaceCall call) {
815 if (deleting_ & call) {
816 channel_.reset();
817 return CHANNEL_DELETED;
818 } else {
819 return CHANNEL_ALIVE;
823 protected:
824 WebSocketChannelDeletingTest()
825 : deleting_(EVENT_ON_ADD_CHANNEL_RESPONSE | EVENT_ON_DATA_FRAME |
826 EVENT_ON_FLOW_CONTROL |
827 EVENT_ON_CLOSING_HANDSHAKE |
828 EVENT_ON_FAIL_CHANNEL |
829 EVENT_ON_DROP_CHANNEL |
830 EVENT_ON_START_OPENING_HANDSHAKE |
831 EVENT_ON_FINISH_OPENING_HANDSHAKE |
832 EVENT_ON_SSL_CERTIFICATE_ERROR) {}
833 // Create a ChannelDeletingFakeWebSocketEventInterface. Defined out-of-line to
834 // avoid circular dependency.
835 scoped_ptr<WebSocketEventInterface> CreateEventInterface() override;
837 // Tests can set deleting_ to a bitmap of EventInterfaceCall members that they
838 // want to cause Channel deletion. The default is for all calls to cause
839 // deletion.
840 int deleting_;
843 // A FakeWebSocketEventInterface that deletes the WebSocketChannel on failure to
844 // connect.
845 class ChannelDeletingFakeWebSocketEventInterface
846 : public FakeWebSocketEventInterface {
847 public:
848 ChannelDeletingFakeWebSocketEventInterface(
849 WebSocketChannelDeletingTest* fixture)
850 : fixture_(fixture) {}
852 ChannelState OnAddChannelResponse(const std::string& selected_protocol,
853 const std::string& extensions) override {
854 return fixture_->DeleteIfDeleting(EVENT_ON_ADD_CHANNEL_RESPONSE);
857 ChannelState OnDataFrame(bool fin,
858 WebSocketMessageType type,
859 const std::vector<char>& data) override {
860 return fixture_->DeleteIfDeleting(EVENT_ON_DATA_FRAME);
863 ChannelState OnFlowControl(int64 quota) override {
864 return fixture_->DeleteIfDeleting(EVENT_ON_FLOW_CONTROL);
867 ChannelState OnClosingHandshake() override {
868 return fixture_->DeleteIfDeleting(EVENT_ON_CLOSING_HANDSHAKE);
871 ChannelState OnFailChannel(const std::string& message) override {
872 return fixture_->DeleteIfDeleting(EVENT_ON_FAIL_CHANNEL);
875 ChannelState OnDropChannel(bool was_clean,
876 uint16 code,
877 const std::string& reason) override {
878 return fixture_->DeleteIfDeleting(EVENT_ON_DROP_CHANNEL);
881 ChannelState OnStartOpeningHandshake(
882 scoped_ptr<WebSocketHandshakeRequestInfo> request) override {
883 return fixture_->DeleteIfDeleting(EVENT_ON_START_OPENING_HANDSHAKE);
885 ChannelState OnFinishOpeningHandshake(
886 scoped_ptr<WebSocketHandshakeResponseInfo> response) override {
887 return fixture_->DeleteIfDeleting(EVENT_ON_FINISH_OPENING_HANDSHAKE);
889 ChannelState OnSSLCertificateError(
890 scoped_ptr<SSLErrorCallbacks> ssl_error_callbacks,
891 const GURL& url,
892 const SSLInfo& ssl_info,
893 bool fatal) override {
894 return fixture_->DeleteIfDeleting(EVENT_ON_SSL_CERTIFICATE_ERROR);
897 private:
898 // A pointer to the test fixture. Owned by the test harness; this object will
899 // be deleted before it is.
900 WebSocketChannelDeletingTest* fixture_;
903 scoped_ptr<WebSocketEventInterface>
904 WebSocketChannelDeletingTest::CreateEventInterface() {
905 return scoped_ptr<WebSocketEventInterface>(
906 new ChannelDeletingFakeWebSocketEventInterface(this));
909 // Base class for tests which verify that EventInterface methods are called
910 // appropriately.
911 class WebSocketChannelEventInterfaceTest : public WebSocketChannelTest {
912 protected:
913 WebSocketChannelEventInterfaceTest()
914 : event_interface_(new StrictMock<MockWebSocketEventInterface>) {
915 DefaultValue<ChannelState>::Set(CHANNEL_ALIVE);
916 ON_CALL(*event_interface_, OnDropChannel(_, _, _))
917 .WillByDefault(Return(CHANNEL_DELETED));
918 ON_CALL(*event_interface_, OnFailChannel(_))
919 .WillByDefault(Return(CHANNEL_DELETED));
922 ~WebSocketChannelEventInterfaceTest() override {
923 DefaultValue<ChannelState>::Clear();
926 // Tests using this fixture must set expectations on the event_interface_ mock
927 // object before calling CreateChannelAndConnect() or
928 // CreateChannelAndConnectSuccessfully(). This will only work once per test
929 // case, but once should be enough.
930 scoped_ptr<WebSocketEventInterface> CreateEventInterface() override {
931 return scoped_ptr<WebSocketEventInterface>(event_interface_.release());
934 scoped_ptr<MockWebSocketEventInterface> event_interface_;
937 // Base class for tests which verify that WebSocketStream methods are called
938 // appropriately by using a MockWebSocketStream.
939 class WebSocketChannelStreamTest : public WebSocketChannelTest {
940 protected:
941 WebSocketChannelStreamTest()
942 : mock_stream_(new StrictMock<MockWebSocketStream>) {}
944 void CreateChannelAndConnectSuccessfully() override {
945 set_stream(mock_stream_.Pass());
946 WebSocketChannelTest::CreateChannelAndConnectSuccessfully();
949 scoped_ptr<MockWebSocketStream> mock_stream_;
952 // Fixture for tests which test UTF-8 validation of sent Text frames via the
953 // EventInterface.
954 class WebSocketChannelSendUtf8Test
955 : public WebSocketChannelEventInterfaceTest {
956 public:
957 void SetUp() override {
958 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
959 // For the purpose of the tests using this fixture, it doesn't matter
960 // whether these methods are called or not.
961 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _))
962 .Times(AnyNumber());
963 EXPECT_CALL(*event_interface_, OnFlowControl(_))
964 .Times(AnyNumber());
968 // Fixture for tests which test use of receive quota from the renderer.
969 class WebSocketChannelFlowControlTest
970 : public WebSocketChannelEventInterfaceTest {
971 protected:
972 // Tests using this fixture should use CreateChannelAndConnectWithQuota()
973 // instead of CreateChannelAndConnectSuccessfully().
974 void CreateChannelAndConnectWithQuota(int64 quota) {
975 CreateChannelAndConnect();
976 channel_->SendFlowControl(quota);
977 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
980 virtual void CreateChannelAndConnectSuccesfully() { NOTREACHED(); }
983 // Fixture for tests which test UTF-8 validation of received Text frames using a
984 // mock WebSocketStream.
985 class WebSocketChannelReceiveUtf8Test : public WebSocketChannelStreamTest {
986 public:
987 void SetUp() override {
988 // For the purpose of the tests using this fixture, it doesn't matter
989 // whether these methods are called or not.
990 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
991 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
995 // Simple test that everything that should be passed to the creator function is
996 // passed to the creator function.
997 TEST_F(WebSocketChannelTest, EverythingIsPassedToTheCreatorFunction) {
998 connect_data_.socket_url = GURL("ws://example.com/test");
999 connect_data_.origin = url::Origin("http://example.com");
1000 connect_data_.requested_subprotocols.push_back("Sinbad");
1002 CreateChannelAndConnect();
1004 const ArgumentCopyingWebSocketStreamCreator& actual = connect_data_.creator;
1006 EXPECT_EQ(&connect_data_.url_request_context, actual.url_request_context);
1008 EXPECT_EQ(connect_data_.socket_url, actual.socket_url);
1009 EXPECT_EQ(connect_data_.requested_subprotocols,
1010 actual.requested_subprotocols);
1011 EXPECT_EQ(connect_data_.origin.string(), actual.origin.string());
1014 // Verify that calling SendFlowControl before the connection is established does
1015 // not cause a crash.
1016 TEST_F(WebSocketChannelTest, SendFlowControlDuringHandshakeOkay) {
1017 CreateChannelAndConnect();
1018 ASSERT_TRUE(channel_);
1019 channel_->SendFlowControl(65536);
1022 // Any WebSocketEventInterface methods can delete the WebSocketChannel and
1023 // return CHANNEL_DELETED. The WebSocketChannelDeletingTests are intended to
1024 // verify that there are no use-after-free bugs when this happens. Problems will
1025 // probably only be found when running under Address Sanitizer or a similar
1026 // tool.
1027 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseFail) {
1028 CreateChannelAndConnect();
1029 EXPECT_TRUE(channel_);
1030 connect_data_.creator.connect_delegate->OnFailure("bye");
1031 EXPECT_EQ(NULL, channel_.get());
1034 // Deletion is possible (due to IPC failure) even if the connect succeeds.
1035 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseSuccess) {
1036 CreateChannelAndConnectSuccessfully();
1037 EXPECT_EQ(NULL, channel_.get());
1040 TEST_F(WebSocketChannelDeletingTest, OnDataFrameSync) {
1041 scoped_ptr<ReadableFakeWebSocketStream> stream(
1042 new ReadableFakeWebSocketStream);
1043 static const InitFrame frames[] = {
1044 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1045 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1046 set_stream(stream.Pass());
1047 deleting_ = EVENT_ON_DATA_FRAME;
1049 CreateChannelAndConnectSuccessfully();
1050 EXPECT_EQ(NULL, channel_.get());
1053 TEST_F(WebSocketChannelDeletingTest, OnDataFrameAsync) {
1054 scoped_ptr<ReadableFakeWebSocketStream> stream(
1055 new ReadableFakeWebSocketStream);
1056 static const InitFrame frames[] = {
1057 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1058 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1059 set_stream(stream.Pass());
1060 deleting_ = EVENT_ON_DATA_FRAME;
1062 CreateChannelAndConnectSuccessfully();
1063 EXPECT_TRUE(channel_);
1064 base::MessageLoop::current()->RunUntilIdle();
1065 EXPECT_EQ(NULL, channel_.get());
1068 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterConnect) {
1069 deleting_ = EVENT_ON_FLOW_CONTROL;
1071 CreateChannelAndConnectSuccessfully();
1072 EXPECT_EQ(NULL, channel_.get());
1075 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterSend) {
1076 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1077 // Avoid deleting the channel yet.
1078 deleting_ = EVENT_ON_FAIL_CHANNEL | EVENT_ON_DROP_CHANNEL;
1079 CreateChannelAndConnectSuccessfully();
1080 ASSERT_TRUE(channel_);
1081 deleting_ = EVENT_ON_FLOW_CONTROL;
1082 channel_->SendFrame(true,
1083 WebSocketFrameHeader::kOpCodeText,
1084 std::vector<char>(kDefaultInitialQuota, 'B'));
1085 EXPECT_EQ(NULL, channel_.get());
1088 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeSync) {
1089 scoped_ptr<ReadableFakeWebSocketStream> stream(
1090 new ReadableFakeWebSocketStream);
1091 static const InitFrame frames[] = {
1092 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1093 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
1094 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1095 set_stream(stream.Pass());
1096 deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
1097 CreateChannelAndConnectSuccessfully();
1098 EXPECT_EQ(NULL, channel_.get());
1101 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeAsync) {
1102 scoped_ptr<ReadableFakeWebSocketStream> stream(
1103 new ReadableFakeWebSocketStream);
1104 static const InitFrame frames[] = {
1105 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1106 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
1107 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1108 set_stream(stream.Pass());
1109 deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
1110 CreateChannelAndConnectSuccessfully();
1111 ASSERT_TRUE(channel_);
1112 base::MessageLoop::current()->RunUntilIdle();
1113 EXPECT_EQ(NULL, channel_.get());
1116 TEST_F(WebSocketChannelDeletingTest, OnDropChannelWriteError) {
1117 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
1118 deleting_ = EVENT_ON_DROP_CHANNEL;
1119 CreateChannelAndConnectSuccessfully();
1120 ASSERT_TRUE(channel_);
1121 channel_->SendFrame(
1122 true, WebSocketFrameHeader::kOpCodeText, AsVector("this will fail"));
1123 EXPECT_EQ(NULL, channel_.get());
1126 TEST_F(WebSocketChannelDeletingTest, OnDropChannelReadError) {
1127 scoped_ptr<ReadableFakeWebSocketStream> stream(
1128 new ReadableFakeWebSocketStream);
1129 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1130 ERR_FAILED);
1131 set_stream(stream.Pass());
1132 deleting_ = EVENT_ON_DROP_CHANNEL;
1133 CreateChannelAndConnectSuccessfully();
1134 ASSERT_TRUE(channel_);
1135 base::MessageLoop::current()->RunUntilIdle();
1136 EXPECT_EQ(NULL, channel_.get());
1139 TEST_F(WebSocketChannelDeletingTest, OnNotifyStartOpeningHandshakeError) {
1140 scoped_ptr<ReadableFakeWebSocketStream> stream(
1141 new ReadableFakeWebSocketStream);
1142 static const InitFrame frames[] = {
1143 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1144 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1145 set_stream(stream.Pass());
1146 deleting_ = EVENT_ON_START_OPENING_HANDSHAKE;
1148 CreateChannelAndConnectSuccessfully();
1149 ASSERT_TRUE(channel_);
1150 channel_->OnStartOpeningHandshake(scoped_ptr<WebSocketHandshakeRequestInfo>(
1151 new WebSocketHandshakeRequestInfo(GURL("http://www.example.com/"),
1152 base::Time())));
1153 base::MessageLoop::current()->RunUntilIdle();
1154 EXPECT_EQ(NULL, channel_.get());
1157 TEST_F(WebSocketChannelDeletingTest, OnNotifyFinishOpeningHandshakeError) {
1158 scoped_ptr<ReadableFakeWebSocketStream> stream(
1159 new ReadableFakeWebSocketStream);
1160 static const InitFrame frames[] = {
1161 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1162 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1163 set_stream(stream.Pass());
1164 deleting_ = EVENT_ON_FINISH_OPENING_HANDSHAKE;
1166 CreateChannelAndConnectSuccessfully();
1167 ASSERT_TRUE(channel_);
1168 scoped_refptr<HttpResponseHeaders> response_headers(
1169 new HttpResponseHeaders(""));
1170 channel_->OnFinishOpeningHandshake(scoped_ptr<WebSocketHandshakeResponseInfo>(
1171 new WebSocketHandshakeResponseInfo(GURL("http://www.example.com/"),
1172 200,
1173 "OK",
1174 response_headers,
1175 base::Time())));
1176 base::MessageLoop::current()->RunUntilIdle();
1177 EXPECT_EQ(NULL, channel_.get());
1180 TEST_F(WebSocketChannelDeletingTest, FailChannelInSendFrame) {
1181 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1182 deleting_ = EVENT_ON_FAIL_CHANNEL;
1183 CreateChannelAndConnectSuccessfully();
1184 ASSERT_TRUE(channel_);
1185 channel_->SendFrame(true,
1186 WebSocketFrameHeader::kOpCodeText,
1187 std::vector<char>(kDefaultInitialQuota * 2, 'T'));
1188 EXPECT_EQ(NULL, channel_.get());
1191 TEST_F(WebSocketChannelDeletingTest, FailChannelInOnReadDone) {
1192 scoped_ptr<ReadableFakeWebSocketStream> stream(
1193 new ReadableFakeWebSocketStream);
1194 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1195 ERR_WS_PROTOCOL_ERROR);
1196 set_stream(stream.Pass());
1197 deleting_ = EVENT_ON_FAIL_CHANNEL;
1198 CreateChannelAndConnectSuccessfully();
1199 ASSERT_TRUE(channel_);
1200 base::MessageLoop::current()->RunUntilIdle();
1201 EXPECT_EQ(NULL, channel_.get());
1204 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToMaskedFrame) {
1205 scoped_ptr<ReadableFakeWebSocketStream> stream(
1206 new ReadableFakeWebSocketStream);
1207 static const InitFrame frames[] = {
1208 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1209 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1210 set_stream(stream.Pass());
1211 deleting_ = EVENT_ON_FAIL_CHANNEL;
1213 CreateChannelAndConnectSuccessfully();
1214 EXPECT_EQ(NULL, channel_.get());
1217 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToBadControlFrame) {
1218 scoped_ptr<ReadableFakeWebSocketStream> stream(
1219 new ReadableFakeWebSocketStream);
1220 static const InitFrame frames[] = {
1221 {FINAL_FRAME, 0xF, NOT_MASKED, ""}};
1222 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1223 set_stream(stream.Pass());
1224 deleting_ = EVENT_ON_FAIL_CHANNEL;
1226 CreateChannelAndConnectSuccessfully();
1227 EXPECT_EQ(NULL, channel_.get());
1230 // Version of above test with NULL data.
1231 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToBadControlFrameNull) {
1232 scoped_ptr<ReadableFakeWebSocketStream> stream(
1233 new ReadableFakeWebSocketStream);
1234 static const InitFrame frames[] = {
1235 {FINAL_FRAME, 0xF, NOT_MASKED, NULL}};
1236 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1237 set_stream(stream.Pass());
1238 deleting_ = EVENT_ON_FAIL_CHANNEL;
1240 CreateChannelAndConnectSuccessfully();
1241 EXPECT_EQ(NULL, channel_.get());
1244 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToPongAfterClose) {
1245 scoped_ptr<ReadableFakeWebSocketStream> stream(
1246 new ReadableFakeWebSocketStream);
1247 static const InitFrame frames[] = {
1248 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
1249 CLOSE_DATA(NORMAL_CLOSURE, "Success")},
1250 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1251 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1252 set_stream(stream.Pass());
1253 deleting_ = EVENT_ON_FAIL_CHANNEL;
1255 CreateChannelAndConnectSuccessfully();
1256 EXPECT_EQ(NULL, channel_.get());
1259 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToPongAfterCloseNull) {
1260 scoped_ptr<ReadableFakeWebSocketStream> stream(
1261 new ReadableFakeWebSocketStream);
1262 static const InitFrame frames[] = {
1263 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
1264 CLOSE_DATA(NORMAL_CLOSURE, "Success")},
1265 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1266 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1267 set_stream(stream.Pass());
1268 deleting_ = EVENT_ON_FAIL_CHANNEL;
1270 CreateChannelAndConnectSuccessfully();
1271 EXPECT_EQ(NULL, channel_.get());
1274 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToUnknownOpCode) {
1275 scoped_ptr<ReadableFakeWebSocketStream> stream(
1276 new ReadableFakeWebSocketStream);
1277 static const InitFrame frames[] = {{FINAL_FRAME, 0x7, NOT_MASKED, ""}};
1278 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1279 set_stream(stream.Pass());
1280 deleting_ = EVENT_ON_FAIL_CHANNEL;
1282 CreateChannelAndConnectSuccessfully();
1283 EXPECT_EQ(NULL, channel_.get());
1286 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToUnknownOpCodeNull) {
1287 scoped_ptr<ReadableFakeWebSocketStream> stream(
1288 new ReadableFakeWebSocketStream);
1289 static const InitFrame frames[] = {{FINAL_FRAME, 0x7, NOT_MASKED, NULL}};
1290 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1291 set_stream(stream.Pass());
1292 deleting_ = EVENT_ON_FAIL_CHANNEL;
1294 CreateChannelAndConnectSuccessfully();
1295 EXPECT_EQ(NULL, channel_.get());
1298 TEST_F(WebSocketChannelDeletingTest, FailChannelDueInvalidCloseReason) {
1299 scoped_ptr<ReadableFakeWebSocketStream> stream(
1300 new ReadableFakeWebSocketStream);
1301 static const InitFrame frames[] = {
1302 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1303 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
1304 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1305 set_stream(stream.Pass());
1306 deleting_ = EVENT_ON_FAIL_CHANNEL;
1308 CreateChannelAndConnectSuccessfully();
1309 EXPECT_EQ(NULL, channel_.get());
1312 TEST_F(WebSocketChannelEventInterfaceTest, ConnectSuccessReported) {
1313 // false means success.
1314 EXPECT_CALL(*event_interface_, OnAddChannelResponse("", ""));
1315 // OnFlowControl is always called immediately after connect to provide initial
1316 // quota to the renderer.
1317 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1319 CreateChannelAndConnect();
1321 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
1324 TEST_F(WebSocketChannelEventInterfaceTest, ConnectFailureReported) {
1325 EXPECT_CALL(*event_interface_, OnFailChannel("hello"));
1327 CreateChannelAndConnect();
1329 connect_data_.creator.connect_delegate->OnFailure("hello");
1332 TEST_F(WebSocketChannelEventInterfaceTest, NonWebSocketSchemeRejected) {
1333 EXPECT_CALL(*event_interface_, OnFailChannel("Invalid scheme"));
1334 connect_data_.socket_url = GURL("http://www.google.com/");
1335 CreateChannelAndConnect();
1338 TEST_F(WebSocketChannelEventInterfaceTest, ProtocolPassed) {
1339 EXPECT_CALL(*event_interface_, OnAddChannelResponse("Bob", ""));
1340 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1342 CreateChannelAndConnect();
1344 connect_data_.creator.connect_delegate->OnSuccess(
1345 scoped_ptr<WebSocketStream>(new FakeWebSocketStream("Bob", "")));
1348 TEST_F(WebSocketChannelEventInterfaceTest, ExtensionsPassed) {
1349 EXPECT_CALL(*event_interface_,
1350 OnAddChannelResponse("", "extension1, extension2"));
1351 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1353 CreateChannelAndConnect();
1355 connect_data_.creator.connect_delegate->OnSuccess(scoped_ptr<WebSocketStream>(
1356 new FakeWebSocketStream("", "extension1, extension2")));
1359 // The first frames from the server can arrive together with the handshake, in
1360 // which case they will be available as soon as ReadFrames() is called the first
1361 // time.
1362 TEST_F(WebSocketChannelEventInterfaceTest, DataLeftFromHandshake) {
1363 scoped_ptr<ReadableFakeWebSocketStream> stream(
1364 new ReadableFakeWebSocketStream);
1365 static const InitFrame frames[] = {
1366 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1367 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1368 set_stream(stream.Pass());
1370 InSequence s;
1371 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1372 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1373 EXPECT_CALL(
1374 *event_interface_,
1375 OnDataFrame(
1376 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1379 CreateChannelAndConnectSuccessfully();
1382 // A remote server could accept the handshake, but then immediately send a
1383 // Close frame.
1384 TEST_F(WebSocketChannelEventInterfaceTest, CloseAfterHandshake) {
1385 scoped_ptr<ReadableFakeWebSocketStream> stream(
1386 new ReadableFakeWebSocketStream);
1387 static const InitFrame frames[] = {
1388 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1389 NOT_MASKED, CLOSE_DATA(SERVER_ERROR, "Internal Server Error")}};
1390 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1391 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1392 ERR_CONNECTION_CLOSED);
1393 set_stream(stream.Pass());
1395 InSequence s;
1396 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1397 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1398 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1399 EXPECT_CALL(
1400 *event_interface_,
1401 OnDropChannel(
1402 true, kWebSocketErrorInternalServerError, "Internal Server Error"));
1405 CreateChannelAndConnectSuccessfully();
1408 // A remote server could close the connection immediately after sending the
1409 // handshake response (most likely a bug in the server).
1410 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionCloseAfterHandshake) {
1411 scoped_ptr<ReadableFakeWebSocketStream> stream(
1412 new ReadableFakeWebSocketStream);
1413 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1414 ERR_CONNECTION_CLOSED);
1415 set_stream(stream.Pass());
1417 InSequence s;
1418 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1419 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1420 EXPECT_CALL(*event_interface_,
1421 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1424 CreateChannelAndConnectSuccessfully();
1427 TEST_F(WebSocketChannelEventInterfaceTest, NormalAsyncRead) {
1428 scoped_ptr<ReadableFakeWebSocketStream> stream(
1429 new ReadableFakeWebSocketStream);
1430 static const InitFrame frames[] = {
1431 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1432 // We use this checkpoint object to verify that the callback isn't called
1433 // until we expect it to be.
1434 Checkpoint checkpoint;
1435 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1436 set_stream(stream.Pass());
1438 InSequence s;
1439 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1440 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1441 EXPECT_CALL(checkpoint, Call(1));
1442 EXPECT_CALL(
1443 *event_interface_,
1444 OnDataFrame(
1445 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1446 EXPECT_CALL(checkpoint, Call(2));
1449 CreateChannelAndConnectSuccessfully();
1450 checkpoint.Call(1);
1451 base::MessageLoop::current()->RunUntilIdle();
1452 checkpoint.Call(2);
1455 // Extra data can arrive while a read is being processed, resulting in the next
1456 // read completing synchronously.
1457 TEST_F(WebSocketChannelEventInterfaceTest, AsyncThenSyncRead) {
1458 scoped_ptr<ReadableFakeWebSocketStream> stream(
1459 new ReadableFakeWebSocketStream);
1460 static const InitFrame frames1[] = {
1461 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1462 static const InitFrame frames2[] = {
1463 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "WORLD"}};
1464 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1465 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames2);
1466 set_stream(stream.Pass());
1468 InSequence s;
1469 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1470 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1471 EXPECT_CALL(
1472 *event_interface_,
1473 OnDataFrame(
1474 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1475 EXPECT_CALL(
1476 *event_interface_,
1477 OnDataFrame(
1478 true, WebSocketFrameHeader::kOpCodeText, AsVector("WORLD")));
1481 CreateChannelAndConnectSuccessfully();
1482 base::MessageLoop::current()->RunUntilIdle();
1485 // Data frames are delivered the same regardless of how many reads they arrive
1486 // as.
1487 TEST_F(WebSocketChannelEventInterfaceTest, FragmentedMessage) {
1488 scoped_ptr<ReadableFakeWebSocketStream> stream(
1489 new ReadableFakeWebSocketStream);
1490 // Here we have one message which arrived in five frames split across three
1491 // reads. It may have been reframed on arrival, but this class doesn't care
1492 // about that.
1493 static const InitFrame frames1[] = {
1494 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "THREE"},
1495 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1496 NOT_MASKED, " "}};
1497 static const InitFrame frames2[] = {
1498 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1499 NOT_MASKED, "SMALL"}};
1500 static const InitFrame frames3[] = {
1501 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1502 NOT_MASKED, " "},
1503 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1504 NOT_MASKED, "FRAMES"}};
1505 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1506 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1507 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1508 set_stream(stream.Pass());
1510 InSequence s;
1511 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1512 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1513 EXPECT_CALL(
1514 *event_interface_,
1515 OnDataFrame(
1516 false, WebSocketFrameHeader::kOpCodeText, AsVector("THREE")));
1517 EXPECT_CALL(
1518 *event_interface_,
1519 OnDataFrame(
1520 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1521 EXPECT_CALL(*event_interface_,
1522 OnDataFrame(false,
1523 WebSocketFrameHeader::kOpCodeContinuation,
1524 AsVector("SMALL")));
1525 EXPECT_CALL(
1526 *event_interface_,
1527 OnDataFrame(
1528 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1529 EXPECT_CALL(*event_interface_,
1530 OnDataFrame(true,
1531 WebSocketFrameHeader::kOpCodeContinuation,
1532 AsVector("FRAMES")));
1535 CreateChannelAndConnectSuccessfully();
1536 base::MessageLoop::current()->RunUntilIdle();
1539 // A message can consist of one frame with NULL payload.
1540 TEST_F(WebSocketChannelEventInterfaceTest, NullMessage) {
1541 scoped_ptr<ReadableFakeWebSocketStream> stream(
1542 new ReadableFakeWebSocketStream);
1543 static const InitFrame frames[] = {
1544 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, NULL}};
1545 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1546 set_stream(stream.Pass());
1547 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1548 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1549 EXPECT_CALL(
1550 *event_interface_,
1551 OnDataFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("")));
1552 CreateChannelAndConnectSuccessfully();
1555 // Connection closed by the remote host without a closing handshake.
1556 TEST_F(WebSocketChannelEventInterfaceTest, AsyncAbnormalClosure) {
1557 scoped_ptr<ReadableFakeWebSocketStream> stream(
1558 new ReadableFakeWebSocketStream);
1559 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1560 ERR_CONNECTION_CLOSED);
1561 set_stream(stream.Pass());
1563 InSequence s;
1564 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1565 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1566 EXPECT_CALL(*event_interface_,
1567 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1570 CreateChannelAndConnectSuccessfully();
1571 base::MessageLoop::current()->RunUntilIdle();
1574 // A connection reset should produce the same event as an unexpected closure.
1575 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionReset) {
1576 scoped_ptr<ReadableFakeWebSocketStream> stream(
1577 new ReadableFakeWebSocketStream);
1578 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1579 ERR_CONNECTION_RESET);
1580 set_stream(stream.Pass());
1582 InSequence s;
1583 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1584 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1585 EXPECT_CALL(*event_interface_,
1586 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1589 CreateChannelAndConnectSuccessfully();
1590 base::MessageLoop::current()->RunUntilIdle();
1593 // RFC6455 5.1 "A client MUST close a connection if it detects a masked frame."
1594 TEST_F(WebSocketChannelEventInterfaceTest, MaskedFramesAreRejected) {
1595 scoped_ptr<ReadableFakeWebSocketStream> stream(
1596 new ReadableFakeWebSocketStream);
1597 static const InitFrame frames[] = {
1598 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1600 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1601 set_stream(stream.Pass());
1603 InSequence s;
1604 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1605 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1606 EXPECT_CALL(
1607 *event_interface_,
1608 OnFailChannel(
1609 "A server must not mask any frames that it sends to the client."));
1612 CreateChannelAndConnectSuccessfully();
1613 base::MessageLoop::current()->RunUntilIdle();
1616 // RFC6455 5.2 "If an unknown opcode is received, the receiving endpoint MUST
1617 // _Fail the WebSocket Connection_."
1618 TEST_F(WebSocketChannelEventInterfaceTest, UnknownOpCodeIsRejected) {
1619 scoped_ptr<ReadableFakeWebSocketStream> stream(
1620 new ReadableFakeWebSocketStream);
1621 static const InitFrame frames[] = {{FINAL_FRAME, 4, NOT_MASKED, "HELLO"}};
1623 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1624 set_stream(stream.Pass());
1626 InSequence s;
1627 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1628 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1629 EXPECT_CALL(*event_interface_,
1630 OnFailChannel("Unrecognized frame opcode: 4"));
1633 CreateChannelAndConnectSuccessfully();
1634 base::MessageLoop::current()->RunUntilIdle();
1637 // RFC6455 5.4 "Control frames ... MAY be injected in the middle of a
1638 // fragmented message."
1639 TEST_F(WebSocketChannelEventInterfaceTest, ControlFrameInDataMessage) {
1640 scoped_ptr<ReadableFakeWebSocketStream> stream(
1641 new ReadableFakeWebSocketStream);
1642 // We have one message of type Text split into two frames. In the middle is a
1643 // control message of type Pong.
1644 static const InitFrame frames1[] = {
1645 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
1646 NOT_MASKED, "SPLIT "}};
1647 static const InitFrame frames2[] = {
1648 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1649 static const InitFrame frames3[] = {
1650 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1651 NOT_MASKED, "MESSAGE"}};
1652 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1653 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1654 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1655 set_stream(stream.Pass());
1657 InSequence s;
1658 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1659 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1660 EXPECT_CALL(
1661 *event_interface_,
1662 OnDataFrame(
1663 false, WebSocketFrameHeader::kOpCodeText, AsVector("SPLIT ")));
1664 EXPECT_CALL(*event_interface_,
1665 OnDataFrame(true,
1666 WebSocketFrameHeader::kOpCodeContinuation,
1667 AsVector("MESSAGE")));
1670 CreateChannelAndConnectSuccessfully();
1671 base::MessageLoop::current()->RunUntilIdle();
1674 // It seems redundant to repeat the entirety of the above test, so just test a
1675 // Pong with NULL data.
1676 TEST_F(WebSocketChannelEventInterfaceTest, PongWithNullData) {
1677 scoped_ptr<ReadableFakeWebSocketStream> stream(
1678 new ReadableFakeWebSocketStream);
1679 static const InitFrame frames[] = {
1680 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1681 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1682 set_stream(stream.Pass());
1683 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1684 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1686 CreateChannelAndConnectSuccessfully();
1687 base::MessageLoop::current()->RunUntilIdle();
1690 // If a frame has an invalid header, then the connection is closed and
1691 // subsequent frames must not trigger events.
1692 TEST_F(WebSocketChannelEventInterfaceTest, FrameAfterInvalidFrame) {
1693 scoped_ptr<ReadableFakeWebSocketStream> stream(
1694 new ReadableFakeWebSocketStream);
1695 static const InitFrame frames[] = {
1696 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"},
1697 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, " WORLD"}};
1699 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1700 set_stream(stream.Pass());
1702 InSequence s;
1703 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1704 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1705 EXPECT_CALL(
1706 *event_interface_,
1707 OnFailChannel(
1708 "A server must not mask any frames that it sends to the client."));
1711 CreateChannelAndConnectSuccessfully();
1712 base::MessageLoop::current()->RunUntilIdle();
1715 // If the renderer sends lots of small writes, we don't want to update the quota
1716 // for each one.
1717 TEST_F(WebSocketChannelEventInterfaceTest, SmallWriteDoesntUpdateQuota) {
1718 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1720 InSequence s;
1721 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1722 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1725 CreateChannelAndConnectSuccessfully();
1726 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("B"));
1729 // If we send enough to go below send_quota_low_water_mask_ we should get our
1730 // quota refreshed.
1731 TEST_F(WebSocketChannelEventInterfaceTest, LargeWriteUpdatesQuota) {
1732 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1733 // We use this checkpoint object to verify that the quota update comes after
1734 // the write.
1735 Checkpoint checkpoint;
1737 InSequence s;
1738 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1739 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1740 EXPECT_CALL(checkpoint, Call(1));
1741 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1742 EXPECT_CALL(checkpoint, Call(2));
1745 CreateChannelAndConnectSuccessfully();
1746 checkpoint.Call(1);
1747 channel_->SendFrame(true,
1748 WebSocketFrameHeader::kOpCodeText,
1749 std::vector<char>(kDefaultInitialQuota, 'B'));
1750 checkpoint.Call(2);
1753 // Verify that our quota actually is refreshed when we are told it is.
1754 TEST_F(WebSocketChannelEventInterfaceTest, QuotaReallyIsRefreshed) {
1755 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1756 Checkpoint checkpoint;
1758 InSequence s;
1759 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1760 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1761 EXPECT_CALL(checkpoint, Call(1));
1762 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1763 EXPECT_CALL(checkpoint, Call(2));
1764 // If quota was not really refreshed, we would get an OnDropChannel()
1765 // message.
1766 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1767 EXPECT_CALL(checkpoint, Call(3));
1770 CreateChannelAndConnectSuccessfully();
1771 checkpoint.Call(1);
1772 channel_->SendFrame(true,
1773 WebSocketFrameHeader::kOpCodeText,
1774 std::vector<char>(kDefaultQuotaRefreshTrigger, 'D'));
1775 checkpoint.Call(2);
1776 // We should have received more quota at this point.
1777 channel_->SendFrame(true,
1778 WebSocketFrameHeader::kOpCodeText,
1779 std::vector<char>(kDefaultQuotaRefreshTrigger, 'E'));
1780 checkpoint.Call(3);
1783 // If we send more than the available quota then the connection will be closed
1784 // with an error.
1785 TEST_F(WebSocketChannelEventInterfaceTest, WriteOverQuotaIsRejected) {
1786 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1788 InSequence s;
1789 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1790 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
1791 EXPECT_CALL(*event_interface_, OnFailChannel("Send quota exceeded"));
1794 CreateChannelAndConnectSuccessfully();
1795 channel_->SendFrame(true,
1796 WebSocketFrameHeader::kOpCodeText,
1797 std::vector<char>(kDefaultInitialQuota + 1, 'C'));
1800 // If a write fails, the channel is dropped.
1801 TEST_F(WebSocketChannelEventInterfaceTest, FailedWrite) {
1802 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
1803 Checkpoint checkpoint;
1805 InSequence s;
1806 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1807 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1808 EXPECT_CALL(checkpoint, Call(1));
1809 EXPECT_CALL(*event_interface_,
1810 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1811 EXPECT_CALL(checkpoint, Call(2));
1814 CreateChannelAndConnectSuccessfully();
1815 checkpoint.Call(1);
1817 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("H"));
1818 checkpoint.Call(2);
1821 // OnDropChannel() is called exactly once when StartClosingHandshake() is used.
1822 TEST_F(WebSocketChannelEventInterfaceTest, SendCloseDropsChannel) {
1823 set_stream(make_scoped_ptr(new EchoeyFakeWebSocketStream));
1825 InSequence s;
1826 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1827 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1828 EXPECT_CALL(*event_interface_,
1829 OnDropChannel(true, kWebSocketNormalClosure, "Fred"));
1832 CreateChannelAndConnectSuccessfully();
1834 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Fred");
1835 base::MessageLoop::current()->RunUntilIdle();
1838 // StartClosingHandshake() also works before connection completes, and calls
1839 // OnDropChannel.
1840 TEST_F(WebSocketChannelEventInterfaceTest, CloseDuringConnection) {
1841 EXPECT_CALL(*event_interface_,
1842 OnDropChannel(false, kWebSocketErrorAbnormalClosure, ""));
1844 CreateChannelAndConnect();
1845 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Joe");
1848 // OnDropChannel() is only called once when a write() on the socket triggers a
1849 // connection reset.
1850 TEST_F(WebSocketChannelEventInterfaceTest, OnDropChannelCalledOnce) {
1851 set_stream(make_scoped_ptr(new ResetOnWriteFakeWebSocketStream));
1852 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1853 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1855 EXPECT_CALL(*event_interface_,
1856 OnDropChannel(false, kWebSocketErrorAbnormalClosure, ""))
1857 .Times(1);
1859 CreateChannelAndConnectSuccessfully();
1861 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("yt?"));
1862 base::MessageLoop::current()->RunUntilIdle();
1865 // When the remote server sends a Close frame with an empty payload,
1866 // WebSocketChannel should report code 1005, kWebSocketErrorNoStatusReceived.
1867 TEST_F(WebSocketChannelEventInterfaceTest, CloseWithNoPayloadGivesStatus1005) {
1868 scoped_ptr<ReadableFakeWebSocketStream> stream(
1869 new ReadableFakeWebSocketStream);
1870 static const InitFrame frames[] = {
1871 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
1872 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1873 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1874 ERR_CONNECTION_CLOSED);
1875 set_stream(stream.Pass());
1876 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1877 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1878 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1879 EXPECT_CALL(*event_interface_,
1880 OnDropChannel(true, kWebSocketErrorNoStatusReceived, _));
1882 CreateChannelAndConnectSuccessfully();
1885 // A version of the above test with NULL payload.
1886 TEST_F(WebSocketChannelEventInterfaceTest,
1887 CloseWithNullPayloadGivesStatus1005) {
1888 scoped_ptr<ReadableFakeWebSocketStream> stream(
1889 new ReadableFakeWebSocketStream);
1890 static const InitFrame frames[] = {
1891 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, NULL}};
1892 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1893 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1894 ERR_CONNECTION_CLOSED);
1895 set_stream(stream.Pass());
1896 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1897 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1898 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1899 EXPECT_CALL(*event_interface_,
1900 OnDropChannel(true, kWebSocketErrorNoStatusReceived, _));
1902 CreateChannelAndConnectSuccessfully();
1905 // If ReadFrames() returns ERR_WS_PROTOCOL_ERROR, then the connection must be
1906 // failed.
1907 TEST_F(WebSocketChannelEventInterfaceTest, SyncProtocolErrorGivesStatus1002) {
1908 scoped_ptr<ReadableFakeWebSocketStream> stream(
1909 new ReadableFakeWebSocketStream);
1910 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1911 ERR_WS_PROTOCOL_ERROR);
1912 set_stream(stream.Pass());
1913 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1914 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1916 EXPECT_CALL(*event_interface_, OnFailChannel("Invalid frame header"));
1918 CreateChannelAndConnectSuccessfully();
1921 // Async version of above test.
1922 TEST_F(WebSocketChannelEventInterfaceTest, AsyncProtocolErrorGivesStatus1002) {
1923 scoped_ptr<ReadableFakeWebSocketStream> stream(
1924 new ReadableFakeWebSocketStream);
1925 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1926 ERR_WS_PROTOCOL_ERROR);
1927 set_stream(stream.Pass());
1928 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1929 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1931 EXPECT_CALL(*event_interface_, OnFailChannel("Invalid frame header"));
1933 CreateChannelAndConnectSuccessfully();
1934 base::MessageLoop::current()->RunUntilIdle();
1937 TEST_F(WebSocketChannelEventInterfaceTest, StartHandshakeRequest) {
1939 InSequence s;
1940 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1941 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1942 EXPECT_CALL(*event_interface_, OnStartOpeningHandshakeCalled());
1945 CreateChannelAndConnectSuccessfully();
1947 scoped_ptr<WebSocketHandshakeRequestInfo> request_info(
1948 new WebSocketHandshakeRequestInfo(GURL("ws://www.example.com/"),
1949 base::Time()));
1950 connect_data_.creator.connect_delegate->OnStartOpeningHandshake(
1951 request_info.Pass());
1953 base::MessageLoop::current()->RunUntilIdle();
1956 TEST_F(WebSocketChannelEventInterfaceTest, FinishHandshakeRequest) {
1958 InSequence s;
1959 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
1960 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1961 EXPECT_CALL(*event_interface_, OnFinishOpeningHandshakeCalled());
1964 CreateChannelAndConnectSuccessfully();
1966 scoped_refptr<HttpResponseHeaders> response_headers(
1967 new HttpResponseHeaders(""));
1968 scoped_ptr<WebSocketHandshakeResponseInfo> response_info(
1969 new WebSocketHandshakeResponseInfo(GURL("ws://www.example.com/"),
1970 200,
1971 "OK",
1972 response_headers,
1973 base::Time()));
1974 connect_data_.creator.connect_delegate->OnFinishOpeningHandshake(
1975 response_info.Pass());
1976 base::MessageLoop::current()->RunUntilIdle();
1979 TEST_F(WebSocketChannelEventInterfaceTest, FailJustAfterHandshake) {
1981 InSequence s;
1982 EXPECT_CALL(*event_interface_, OnStartOpeningHandshakeCalled());
1983 EXPECT_CALL(*event_interface_, OnFinishOpeningHandshakeCalled());
1984 EXPECT_CALL(*event_interface_, OnFailChannel("bye"));
1987 CreateChannelAndConnect();
1989 WebSocketStream::ConnectDelegate* connect_delegate =
1990 connect_data_.creator.connect_delegate.get();
1991 GURL url("ws://www.example.com/");
1992 scoped_ptr<WebSocketHandshakeRequestInfo> request_info(
1993 new WebSocketHandshakeRequestInfo(url, base::Time()));
1994 scoped_refptr<HttpResponseHeaders> response_headers(
1995 new HttpResponseHeaders(""));
1996 scoped_ptr<WebSocketHandshakeResponseInfo> response_info(
1997 new WebSocketHandshakeResponseInfo(url,
1998 200,
1999 "OK",
2000 response_headers,
2001 base::Time()));
2002 connect_delegate->OnStartOpeningHandshake(request_info.Pass());
2003 connect_delegate->OnFinishOpeningHandshake(response_info.Pass());
2005 connect_delegate->OnFailure("bye");
2006 base::MessageLoop::current()->RunUntilIdle();
2009 // Any frame after close is invalid. This test uses a Text frame. See also
2010 // test "PingAfterCloseIfRejected".
2011 TEST_F(WebSocketChannelEventInterfaceTest, DataAfterCloseIsRejected) {
2012 scoped_ptr<ReadableFakeWebSocketStream> stream(
2013 new ReadableFakeWebSocketStream);
2014 static const InitFrame frames[] = {
2015 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
2016 CLOSE_DATA(NORMAL_CLOSURE, "OK")},
2017 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "Payload"}};
2018 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2019 set_stream(stream.Pass());
2020 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2021 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2024 InSequence s;
2025 EXPECT_CALL(*event_interface_, OnClosingHandshake());
2026 EXPECT_CALL(*event_interface_,
2027 OnFailChannel("Data frame received after close"));
2030 CreateChannelAndConnectSuccessfully();
2033 // A Close frame with a one-byte payload elicits a specific console error
2034 // message.
2035 TEST_F(WebSocketChannelEventInterfaceTest, OneByteClosePayloadMessage) {
2036 scoped_ptr<ReadableFakeWebSocketStream> stream(
2037 new ReadableFakeWebSocketStream);
2038 static const InitFrame frames[] = {
2039 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, "\x03"}};
2040 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2041 set_stream(stream.Pass());
2042 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2043 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2044 EXPECT_CALL(
2045 *event_interface_,
2046 OnFailChannel(
2047 "Received a broken close frame containing an invalid size body."));
2049 CreateChannelAndConnectSuccessfully();
2052 // A Close frame with a reserved status code also elicits a specific console
2053 // error message.
2054 TEST_F(WebSocketChannelEventInterfaceTest, ClosePayloadReservedStatusMessage) {
2055 scoped_ptr<ReadableFakeWebSocketStream> stream(
2056 new ReadableFakeWebSocketStream);
2057 static const InitFrame frames[] = {
2058 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2059 NOT_MASKED, CLOSE_DATA(ABNORMAL_CLOSURE, "Not valid on wire")}};
2060 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2061 set_stream(stream.Pass());
2062 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2063 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2064 EXPECT_CALL(
2065 *event_interface_,
2066 OnFailChannel(
2067 "Received a broken close frame containing a reserved status code."));
2069 CreateChannelAndConnectSuccessfully();
2072 // A Close frame with invalid UTF-8 also elicits a specific console error
2073 // message.
2074 TEST_F(WebSocketChannelEventInterfaceTest, ClosePayloadInvalidReason) {
2075 scoped_ptr<ReadableFakeWebSocketStream> stream(
2076 new ReadableFakeWebSocketStream);
2077 static const InitFrame frames[] = {
2078 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2079 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
2080 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2081 set_stream(stream.Pass());
2082 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2083 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2084 EXPECT_CALL(
2085 *event_interface_,
2086 OnFailChannel(
2087 "Received a broken close frame containing invalid UTF-8."));
2089 CreateChannelAndConnectSuccessfully();
2092 // The reserved bits must all be clear on received frames. Extensions should
2093 // clear the bits when they are set correctly before passing on the frame.
2094 TEST_F(WebSocketChannelEventInterfaceTest, ReservedBitsMustNotBeSet) {
2095 scoped_ptr<ReadableFakeWebSocketStream> stream(
2096 new ReadableFakeWebSocketStream);
2097 static const InitFrame frames[] = {
2098 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2099 NOT_MASKED, "sakana"}};
2100 // It is not worth adding support for reserved bits to InitFrame just for this
2101 // one test, so set the bit manually.
2102 ScopedVector<WebSocketFrame> raw_frames = CreateFrameVector(frames);
2103 raw_frames[0]->header.reserved1 = true;
2104 stream->PrepareRawReadFrames(
2105 ReadableFakeWebSocketStream::SYNC, OK, raw_frames.Pass());
2106 set_stream(stream.Pass());
2107 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2108 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2109 EXPECT_CALL(*event_interface_,
2110 OnFailChannel(
2111 "One or more reserved bits are on: reserved1 = 1, "
2112 "reserved2 = 0, reserved3 = 0"));
2114 CreateChannelAndConnectSuccessfully();
2117 // The closing handshake times out and sends an OnDropChannel event if no
2118 // response to the client Close message is received.
2119 TEST_F(WebSocketChannelEventInterfaceTest,
2120 ClientInitiatedClosingHandshakeTimesOut) {
2121 scoped_ptr<ReadableFakeWebSocketStream> stream(
2122 new ReadableFakeWebSocketStream);
2123 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
2124 ERR_IO_PENDING);
2125 set_stream(stream.Pass());
2126 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2127 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2128 // This checkpoint object verifies that the OnDropChannel message comes after
2129 // the timeout.
2130 Checkpoint checkpoint;
2131 TestClosure completion;
2133 InSequence s;
2134 EXPECT_CALL(checkpoint, Call(1));
2135 EXPECT_CALL(*event_interface_,
2136 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _))
2137 .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
2139 CreateChannelAndConnectSuccessfully();
2140 // OneShotTimer is not very friendly to testing; there is no apparent way to
2141 // set an expectation on it. Instead the tests need to infer that the timeout
2142 // was fired by the behaviour of the WebSocketChannel object.
2143 channel_->SetClosingHandshakeTimeoutForTesting(
2144 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2145 channel_->SetUnderlyingConnectionCloseTimeoutForTesting(
2146 TimeDelta::FromMilliseconds(kVeryBigTimeoutMillis));
2147 channel_->StartClosingHandshake(kWebSocketNormalClosure, "");
2148 checkpoint.Call(1);
2149 completion.WaitForResult();
2152 // The closing handshake times out and sends an OnDropChannel event if a Close
2153 // message is received but the connection isn't closed by the remote host.
2154 TEST_F(WebSocketChannelEventInterfaceTest,
2155 ServerInitiatedClosingHandshakeTimesOut) {
2156 scoped_ptr<ReadableFakeWebSocketStream> stream(
2157 new ReadableFakeWebSocketStream);
2158 static const InitFrame frames[] = {
2159 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2160 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2161 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
2162 set_stream(stream.Pass());
2163 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2164 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2165 Checkpoint checkpoint;
2166 TestClosure completion;
2168 InSequence s;
2169 EXPECT_CALL(checkpoint, Call(1));
2170 EXPECT_CALL(*event_interface_, OnClosingHandshake());
2171 EXPECT_CALL(*event_interface_,
2172 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _))
2173 .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
2175 CreateChannelAndConnectSuccessfully();
2176 channel_->SetClosingHandshakeTimeoutForTesting(
2177 TimeDelta::FromMilliseconds(kVeryBigTimeoutMillis));
2178 channel_->SetUnderlyingConnectionCloseTimeoutForTesting(
2179 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2180 checkpoint.Call(1);
2181 completion.WaitForResult();
2184 // The renderer should provide us with some quota immediately, and then
2185 // WebSocketChannel calls ReadFrames as soon as the stream is available.
2186 TEST_F(WebSocketChannelStreamTest, FlowControlEarly) {
2187 Checkpoint checkpoint;
2188 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2189 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2191 InSequence s;
2192 EXPECT_CALL(checkpoint, Call(1));
2193 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2194 .WillOnce(Return(ERR_IO_PENDING));
2195 EXPECT_CALL(checkpoint, Call(2));
2198 set_stream(mock_stream_.Pass());
2199 CreateChannelAndConnect();
2200 channel_->SendFlowControl(kPlentyOfQuota);
2201 checkpoint.Call(1);
2202 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2203 checkpoint.Call(2);
2206 // If for some reason the connect succeeds before the renderer sends us quota,
2207 // we shouldn't call ReadFrames() immediately.
2208 // TODO(ricea): Actually we should call ReadFrames() with a small limit so we
2209 // can still handle control frames. This should be done once we have any API to
2210 // expose quota to the lower levels.
2211 TEST_F(WebSocketChannelStreamTest, FlowControlLate) {
2212 Checkpoint checkpoint;
2213 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2214 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2216 InSequence s;
2217 EXPECT_CALL(checkpoint, Call(1));
2218 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2219 .WillOnce(Return(ERR_IO_PENDING));
2220 EXPECT_CALL(checkpoint, Call(2));
2223 set_stream(mock_stream_.Pass());
2224 CreateChannelAndConnect();
2225 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2226 checkpoint.Call(1);
2227 channel_->SendFlowControl(kPlentyOfQuota);
2228 checkpoint.Call(2);
2231 // We should stop calling ReadFrames() when all quota is used.
2232 TEST_F(WebSocketChannelStreamTest, FlowControlStopsReadFrames) {
2233 static const InitFrame frames[] = {
2234 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "FOUR"}};
2236 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2237 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2238 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2239 .WillOnce(ReturnFrames(&frames));
2241 set_stream(mock_stream_.Pass());
2242 CreateChannelAndConnect();
2243 channel_->SendFlowControl(4);
2244 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2247 // Providing extra quota causes ReadFrames() to be called again.
2248 TEST_F(WebSocketChannelStreamTest, FlowControlStartsWithMoreQuota) {
2249 static const InitFrame frames[] = {
2250 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "FOUR"}};
2251 Checkpoint checkpoint;
2253 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2254 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2256 InSequence s;
2257 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2258 .WillOnce(ReturnFrames(&frames));
2259 EXPECT_CALL(checkpoint, Call(1));
2260 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2261 .WillOnce(Return(ERR_IO_PENDING));
2264 set_stream(mock_stream_.Pass());
2265 CreateChannelAndConnect();
2266 channel_->SendFlowControl(4);
2267 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2268 checkpoint.Call(1);
2269 channel_->SendFlowControl(4);
2272 // ReadFrames() isn't called again until all pending data has been passed to
2273 // the renderer.
2274 TEST_F(WebSocketChannelStreamTest, ReadFramesNotCalledUntilQuotaAvailable) {
2275 static const InitFrame frames[] = {
2276 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "FOUR"}};
2277 Checkpoint checkpoint;
2279 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2280 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2282 InSequence s;
2283 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2284 .WillOnce(ReturnFrames(&frames));
2285 EXPECT_CALL(checkpoint, Call(1));
2286 EXPECT_CALL(checkpoint, Call(2));
2287 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2288 .WillOnce(Return(ERR_IO_PENDING));
2291 set_stream(mock_stream_.Pass());
2292 CreateChannelAndConnect();
2293 channel_->SendFlowControl(2);
2294 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2295 checkpoint.Call(1);
2296 channel_->SendFlowControl(2);
2297 checkpoint.Call(2);
2298 channel_->SendFlowControl(2);
2301 // A message that needs to be split into frames to fit within quota should
2302 // maintain correct semantics.
2303 TEST_F(WebSocketChannelFlowControlTest, SingleFrameMessageSplitSync) {
2304 scoped_ptr<ReadableFakeWebSocketStream> stream(
2305 new ReadableFakeWebSocketStream);
2306 static const InitFrame frames[] = {
2307 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "FOUR"}};
2308 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2309 set_stream(stream.Pass());
2311 InSequence s;
2312 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2313 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2314 EXPECT_CALL(
2315 *event_interface_,
2316 OnDataFrame(false, WebSocketFrameHeader::kOpCodeText, AsVector("FO")));
2317 EXPECT_CALL(
2318 *event_interface_,
2319 OnDataFrame(
2320 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector("U")));
2321 EXPECT_CALL(
2322 *event_interface_,
2323 OnDataFrame(
2324 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("R")));
2327 CreateChannelAndConnectWithQuota(2);
2328 channel_->SendFlowControl(1);
2329 channel_->SendFlowControl(1);
2332 // The code path for async messages is slightly different, so test it
2333 // separately.
2334 TEST_F(WebSocketChannelFlowControlTest, SingleFrameMessageSplitAsync) {
2335 scoped_ptr<ReadableFakeWebSocketStream> stream(
2336 new ReadableFakeWebSocketStream);
2337 static const InitFrame frames[] = {
2338 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "FOUR"}};
2339 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
2340 set_stream(stream.Pass());
2341 Checkpoint checkpoint;
2343 InSequence s;
2344 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2345 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2346 EXPECT_CALL(checkpoint, Call(1));
2347 EXPECT_CALL(
2348 *event_interface_,
2349 OnDataFrame(false, WebSocketFrameHeader::kOpCodeText, AsVector("FO")));
2350 EXPECT_CALL(checkpoint, Call(2));
2351 EXPECT_CALL(
2352 *event_interface_,
2353 OnDataFrame(
2354 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector("U")));
2355 EXPECT_CALL(checkpoint, Call(3));
2356 EXPECT_CALL(
2357 *event_interface_,
2358 OnDataFrame(
2359 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("R")));
2362 CreateChannelAndConnectWithQuota(2);
2363 checkpoint.Call(1);
2364 base::MessageLoop::current()->RunUntilIdle();
2365 checkpoint.Call(2);
2366 channel_->SendFlowControl(1);
2367 checkpoint.Call(3);
2368 channel_->SendFlowControl(1);
2371 // A message split into multiple frames which is further split due to quota
2372 // restrictions should stil be correct.
2373 // TODO(ricea): The message ends up split into more frames than are strictly
2374 // necessary. The complexity/performance tradeoffs here need further
2375 // examination.
2376 TEST_F(WebSocketChannelFlowControlTest, MultipleFrameSplit) {
2377 scoped_ptr<ReadableFakeWebSocketStream> stream(
2378 new ReadableFakeWebSocketStream);
2379 static const InitFrame frames[] = {
2380 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2381 NOT_MASKED, "FIRST FRAME IS 25 BYTES. "},
2382 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2383 NOT_MASKED, "SECOND FRAME IS 26 BYTES. "},
2384 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2385 NOT_MASKED, "FINAL FRAME IS 24 BYTES."}};
2386 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2387 set_stream(stream.Pass());
2389 InSequence s;
2390 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2391 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2392 EXPECT_CALL(*event_interface_,
2393 OnDataFrame(false,
2394 WebSocketFrameHeader::kOpCodeText,
2395 AsVector("FIRST FRAME IS")));
2396 EXPECT_CALL(*event_interface_,
2397 OnDataFrame(false,
2398 WebSocketFrameHeader::kOpCodeContinuation,
2399 AsVector(" 25 BYTES. ")));
2400 EXPECT_CALL(*event_interface_,
2401 OnDataFrame(false,
2402 WebSocketFrameHeader::kOpCodeContinuation,
2403 AsVector("SECOND FRAME IS 26 BYTES. ")));
2404 EXPECT_CALL(*event_interface_,
2405 OnDataFrame(false,
2406 WebSocketFrameHeader::kOpCodeContinuation,
2407 AsVector("FINAL ")));
2408 EXPECT_CALL(*event_interface_,
2409 OnDataFrame(true,
2410 WebSocketFrameHeader::kOpCodeContinuation,
2411 AsVector("FRAME IS 24 BYTES.")));
2413 CreateChannelAndConnectWithQuota(14);
2414 channel_->SendFlowControl(43);
2415 channel_->SendFlowControl(32);
2418 // An empty message handled when we are out of quota must not be delivered
2419 // out-of-order with respect to other messages.
2420 TEST_F(WebSocketChannelFlowControlTest, EmptyMessageNoQuota) {
2421 scoped_ptr<ReadableFakeWebSocketStream> stream(
2422 new ReadableFakeWebSocketStream);
2423 static const InitFrame frames[] = {
2424 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2425 NOT_MASKED, "FIRST MESSAGE"},
2426 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2427 NOT_MASKED, NULL},
2428 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2429 NOT_MASKED, "THIRD MESSAGE"}};
2430 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2431 set_stream(stream.Pass());
2433 InSequence s;
2434 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2435 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2436 EXPECT_CALL(*event_interface_,
2437 OnDataFrame(false,
2438 WebSocketFrameHeader::kOpCodeText,
2439 AsVector("FIRST ")));
2440 EXPECT_CALL(*event_interface_,
2441 OnDataFrame(true,
2442 WebSocketFrameHeader::kOpCodeContinuation,
2443 AsVector("MESSAGE")));
2444 EXPECT_CALL(*event_interface_,
2445 OnDataFrame(true,
2446 WebSocketFrameHeader::kOpCodeText,
2447 AsVector("")));
2448 EXPECT_CALL(*event_interface_,
2449 OnDataFrame(true,
2450 WebSocketFrameHeader::kOpCodeText,
2451 AsVector("THIRD MESSAGE")));
2454 CreateChannelAndConnectWithQuota(6);
2455 channel_->SendFlowControl(128);
2458 // RFC6455 5.1 "a client MUST mask all frames that it sends to the server".
2459 // WebSocketChannel actually only sets the mask bit in the header, it doesn't
2460 // perform masking itself (not all transports actually use masking).
2461 TEST_F(WebSocketChannelStreamTest, SentFramesAreMasked) {
2462 static const InitFrame expected[] = {
2463 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2464 MASKED, "NEEDS MASKING"}};
2465 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2466 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2467 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2468 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2469 .WillOnce(Return(OK));
2471 CreateChannelAndConnectSuccessfully();
2472 channel_->SendFrame(
2473 true, WebSocketFrameHeader::kOpCodeText, AsVector("NEEDS MASKING"));
2476 // RFC6455 5.5.1 "The application MUST NOT send any more data frames after
2477 // sending a Close frame."
2478 TEST_F(WebSocketChannelStreamTest, NothingIsSentAfterClose) {
2479 static const InitFrame expected[] = {
2480 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2481 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
2482 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2483 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2484 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2485 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2486 .WillOnce(Return(OK));
2488 CreateChannelAndConnectSuccessfully();
2489 channel_->StartClosingHandshake(1000, "Success");
2490 channel_->SendFrame(
2491 true, WebSocketFrameHeader::kOpCodeText, AsVector("SHOULD BE IGNORED"));
2494 // RFC6455 5.5.1 "If an endpoint receives a Close frame and did not previously
2495 // send a Close frame, the endpoint MUST send a Close frame in response."
2496 TEST_F(WebSocketChannelStreamTest, CloseIsEchoedBack) {
2497 static const InitFrame frames[] = {
2498 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2499 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2500 static const InitFrame expected[] = {
2501 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2502 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2503 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2504 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2505 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2506 .WillOnce(ReturnFrames(&frames))
2507 .WillRepeatedly(Return(ERR_IO_PENDING));
2508 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2509 .WillOnce(Return(OK));
2511 CreateChannelAndConnectSuccessfully();
2514 // The converse of the above case; after sending a Close frame, we should not
2515 // send another one.
2516 TEST_F(WebSocketChannelStreamTest, CloseOnlySentOnce) {
2517 static const InitFrame expected[] = {
2518 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2519 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2520 static const InitFrame frames_init[] = {
2521 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2522 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2524 // We store the parameters that were passed to ReadFrames() so that we can
2525 // call them explicitly later.
2526 CompletionCallback read_callback;
2527 ScopedVector<WebSocketFrame>* frames = NULL;
2529 // These are not interesting.
2530 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2531 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2533 // Use a checkpoint to make the ordering of events clearer.
2534 Checkpoint checkpoint;
2536 InSequence s;
2537 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2538 .WillOnce(DoAll(SaveArg<0>(&frames),
2539 SaveArg<1>(&read_callback),
2540 Return(ERR_IO_PENDING)));
2541 EXPECT_CALL(checkpoint, Call(1));
2542 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2543 .WillOnce(Return(OK));
2544 EXPECT_CALL(checkpoint, Call(2));
2545 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2546 .WillOnce(Return(ERR_IO_PENDING));
2547 EXPECT_CALL(checkpoint, Call(3));
2548 // WriteFrames() must not be called again. GoogleMock will ensure that the
2549 // test fails if it is.
2552 CreateChannelAndConnectSuccessfully();
2553 checkpoint.Call(1);
2554 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Close");
2555 checkpoint.Call(2);
2557 *frames = CreateFrameVector(frames_init);
2558 read_callback.Run(OK);
2559 checkpoint.Call(3);
2562 // Invalid close status codes should not be sent on the network.
2563 TEST_F(WebSocketChannelStreamTest, InvalidCloseStatusCodeNotSent) {
2564 static const InitFrame expected[] = {
2565 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2566 MASKED, CLOSE_DATA(SERVER_ERROR, "")}};
2568 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2569 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2570 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2571 .WillOnce(Return(ERR_IO_PENDING));
2573 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
2575 CreateChannelAndConnectSuccessfully();
2576 channel_->StartClosingHandshake(999, "");
2579 // A Close frame with a reason longer than 123 bytes cannot be sent on the
2580 // network.
2581 TEST_F(WebSocketChannelStreamTest, LongCloseReasonNotSent) {
2582 static const InitFrame expected[] = {
2583 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2584 MASKED, CLOSE_DATA(SERVER_ERROR, "")}};
2586 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2587 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2588 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2589 .WillOnce(Return(ERR_IO_PENDING));
2591 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
2593 CreateChannelAndConnectSuccessfully();
2594 channel_->StartClosingHandshake(1000, std::string(124, 'A'));
2597 // We generate code 1005, kWebSocketErrorNoStatusReceived, when there is no
2598 // status in the Close message from the other side. Code 1005 is not allowed to
2599 // appear on the wire, so we should not echo it back. See test
2600 // CloseWithNoPayloadGivesStatus1005, above, for confirmation that code 1005 is
2601 // correctly generated internally.
2602 TEST_F(WebSocketChannelStreamTest, Code1005IsNotEchoed) {
2603 static const InitFrame frames[] = {
2604 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
2605 static const InitFrame expected[] = {
2606 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED, ""}};
2607 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2608 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2609 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2610 .WillOnce(ReturnFrames(&frames))
2611 .WillRepeatedly(Return(ERR_IO_PENDING));
2612 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2613 .WillOnce(Return(OK));
2615 CreateChannelAndConnectSuccessfully();
2618 TEST_F(WebSocketChannelStreamTest, Code1005IsNotEchoedNull) {
2619 static const InitFrame frames[] = {
2620 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, NULL}};
2621 static const InitFrame expected[] = {
2622 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED, ""}};
2623 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2624 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2625 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2626 .WillOnce(ReturnFrames(&frames))
2627 .WillRepeatedly(Return(ERR_IO_PENDING));
2628 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2629 .WillOnce(Return(OK));
2631 CreateChannelAndConnectSuccessfully();
2634 // Receiving an invalid UTF-8 payload in a Close frame causes us to fail the
2635 // connection.
2636 TEST_F(WebSocketChannelStreamTest, CloseFrameInvalidUtf8) {
2637 static const InitFrame frames[] = {
2638 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2639 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
2640 static const InitFrame expected[] = {
2641 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2642 MASKED, CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in Close frame")}};
2644 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2645 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2646 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2647 .WillOnce(ReturnFrames(&frames))
2648 .WillRepeatedly(Return(ERR_IO_PENDING));
2649 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2650 .WillOnce(Return(OK));
2651 EXPECT_CALL(*mock_stream_, Close());
2653 CreateChannelAndConnectSuccessfully();
2656 // RFC6455 5.5.2 "Upon receipt of a Ping frame, an endpoint MUST send a Pong
2657 // frame in response"
2658 // 5.5.3 "A Pong frame sent in response to a Ping frame must have identical
2659 // "Application data" as found in the message body of the Ping frame being
2660 // replied to."
2661 TEST_F(WebSocketChannelStreamTest, PingRepliedWithPong) {
2662 static const InitFrame frames[] = {
2663 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2664 NOT_MASKED, "Application data"}};
2665 static const InitFrame expected[] = {
2666 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
2667 MASKED, "Application data"}};
2668 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2669 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2670 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2671 .WillOnce(ReturnFrames(&frames))
2672 .WillRepeatedly(Return(ERR_IO_PENDING));
2673 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2674 .WillOnce(Return(OK));
2676 CreateChannelAndConnectSuccessfully();
2679 // A ping with a NULL payload should be responded to with a Pong with a NULL
2680 // payload.
2681 TEST_F(WebSocketChannelStreamTest, NullPingRepliedWithNullPong) {
2682 static const InitFrame frames[] = {
2683 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing, NOT_MASKED, NULL}};
2684 static const InitFrame expected[] = {
2685 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, MASKED, NULL}};
2686 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2687 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2688 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2689 .WillOnce(ReturnFrames(&frames))
2690 .WillRepeatedly(Return(ERR_IO_PENDING));
2691 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2692 .WillOnce(Return(OK));
2694 CreateChannelAndConnectSuccessfully();
2697 TEST_F(WebSocketChannelStreamTest, PongInTheMiddleOfDataMessage) {
2698 static const InitFrame frames[] = {
2699 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2700 NOT_MASKED, "Application data"}};
2701 static const InitFrame expected1[] = {
2702 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
2703 static const InitFrame expected2[] = {
2704 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
2705 MASKED, "Application data"}};
2706 static const InitFrame expected3[] = {
2707 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2708 MASKED, "World"}};
2709 ScopedVector<WebSocketFrame>* read_frames;
2710 CompletionCallback read_callback;
2711 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2712 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2713 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2714 .WillOnce(DoAll(SaveArg<0>(&read_frames),
2715 SaveArg<1>(&read_callback),
2716 Return(ERR_IO_PENDING)))
2717 .WillRepeatedly(Return(ERR_IO_PENDING));
2719 InSequence s;
2721 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2722 .WillOnce(Return(OK));
2723 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2724 .WillOnce(Return(OK));
2725 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected3), _))
2726 .WillOnce(Return(OK));
2729 CreateChannelAndConnectSuccessfully();
2730 channel_->SendFrame(
2731 false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
2732 *read_frames = CreateFrameVector(frames);
2733 read_callback.Run(OK);
2734 channel_->SendFrame(
2735 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("World"));
2738 // WriteFrames() may not be called until the previous write has completed.
2739 // WebSocketChannel must buffer writes that happen in the meantime.
2740 TEST_F(WebSocketChannelStreamTest, WriteFramesOneAtATime) {
2741 static const InitFrame expected1[] = {
2742 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
2743 static const InitFrame expected2[] = {
2744 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "World"}};
2745 CompletionCallback write_callback;
2746 Checkpoint checkpoint;
2748 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2749 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2750 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2752 InSequence s;
2753 EXPECT_CALL(checkpoint, Call(1));
2754 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2755 .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
2756 EXPECT_CALL(checkpoint, Call(2));
2757 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2758 .WillOnce(Return(ERR_IO_PENDING));
2759 EXPECT_CALL(checkpoint, Call(3));
2762 CreateChannelAndConnectSuccessfully();
2763 checkpoint.Call(1);
2764 channel_->SendFrame(
2765 false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
2766 channel_->SendFrame(
2767 true, WebSocketFrameHeader::kOpCodeText, AsVector("World"));
2768 checkpoint.Call(2);
2769 write_callback.Run(OK);
2770 checkpoint.Call(3);
2773 // WebSocketChannel must buffer frames while it is waiting for a write to
2774 // complete, and then send them in a single batch. The batching behaviour is
2775 // important to get good throughput in the "many small messages" case.
2776 TEST_F(WebSocketChannelStreamTest, WaitingMessagesAreBatched) {
2777 static const char input_letters[] = "Hello";
2778 static const InitFrame expected1[] = {
2779 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "H"}};
2780 static const InitFrame expected2[] = {
2781 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "e"},
2782 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
2783 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
2784 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "o"}};
2785 CompletionCallback write_callback;
2787 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2788 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2789 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2791 InSequence s;
2792 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2793 .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
2794 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2795 .WillOnce(Return(ERR_IO_PENDING));
2798 CreateChannelAndConnectSuccessfully();
2799 for (size_t i = 0; i < strlen(input_letters); ++i) {
2800 channel_->SendFrame(true,
2801 WebSocketFrameHeader::kOpCodeText,
2802 std::vector<char>(1, input_letters[i]));
2804 write_callback.Run(OK);
2807 // When the renderer sends more on a channel than it has quota for, we send the
2808 // remote server a kWebSocketErrorGoingAway error code.
2809 TEST_F(WebSocketChannelStreamTest, SendGoingAwayOnRendererQuotaExceeded) {
2810 static const InitFrame expected[] = {
2811 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2812 MASKED, CLOSE_DATA(GOING_AWAY, "")}};
2813 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2814 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2815 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2816 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2817 .WillOnce(Return(OK));
2818 EXPECT_CALL(*mock_stream_, Close());
2820 CreateChannelAndConnectSuccessfully();
2821 channel_->SendFrame(true,
2822 WebSocketFrameHeader::kOpCodeText,
2823 std::vector<char>(kDefaultInitialQuota + 1, 'C'));
2826 // For convenience, most of these tests use Text frames. However, the WebSocket
2827 // protocol also has Binary frames and those need to be 8-bit clean. For the
2828 // sake of completeness, this test verifies that they are.
2829 TEST_F(WebSocketChannelStreamTest, WrittenBinaryFramesAre8BitClean) {
2830 ScopedVector<WebSocketFrame>* frames = NULL;
2832 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2833 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2834 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2835 EXPECT_CALL(*mock_stream_, WriteFrames(_, _))
2836 .WillOnce(DoAll(SaveArg<0>(&frames), Return(ERR_IO_PENDING)));
2838 CreateChannelAndConnectSuccessfully();
2839 channel_->SendFrame(
2840 true,
2841 WebSocketFrameHeader::kOpCodeBinary,
2842 std::vector<char>(kBinaryBlob, kBinaryBlob + kBinaryBlobSize));
2843 ASSERT_TRUE(frames != NULL);
2844 ASSERT_EQ(1U, frames->size());
2845 const WebSocketFrame* out_frame = (*frames)[0];
2846 EXPECT_EQ(kBinaryBlobSize, out_frame->header.payload_length);
2847 ASSERT_TRUE(out_frame->data.get());
2848 EXPECT_EQ(0, memcmp(kBinaryBlob, out_frame->data->data(), kBinaryBlobSize));
2851 // Test the read path for 8-bit cleanliness as well.
2852 TEST_F(WebSocketChannelEventInterfaceTest, ReadBinaryFramesAre8BitClean) {
2853 scoped_ptr<WebSocketFrame> frame(
2854 new WebSocketFrame(WebSocketFrameHeader::kOpCodeBinary));
2855 WebSocketFrameHeader& frame_header = frame->header;
2856 frame_header.final = true;
2857 frame_header.payload_length = kBinaryBlobSize;
2858 frame->data = new IOBuffer(kBinaryBlobSize);
2859 memcpy(frame->data->data(), kBinaryBlob, kBinaryBlobSize);
2860 ScopedVector<WebSocketFrame> frames;
2861 frames.push_back(frame.release());
2862 scoped_ptr<ReadableFakeWebSocketStream> stream(
2863 new ReadableFakeWebSocketStream);
2864 stream->PrepareRawReadFrames(
2865 ReadableFakeWebSocketStream::SYNC, OK, frames.Pass());
2866 set_stream(stream.Pass());
2867 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2868 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2869 EXPECT_CALL(*event_interface_,
2870 OnDataFrame(true,
2871 WebSocketFrameHeader::kOpCodeBinary,
2872 std::vector<char>(kBinaryBlob,
2873 kBinaryBlob + kBinaryBlobSize)));
2875 CreateChannelAndConnectSuccessfully();
2878 // Invalid UTF-8 is not permitted in Text frames.
2879 TEST_F(WebSocketChannelSendUtf8Test, InvalidUtf8Rejected) {
2880 EXPECT_CALL(
2881 *event_interface_,
2882 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2884 CreateChannelAndConnectSuccessfully();
2886 channel_->SendFrame(
2887 true, WebSocketFrameHeader::kOpCodeText, AsVector("\xff"));
2890 // A Text message cannot end with a partial UTF-8 character.
2891 TEST_F(WebSocketChannelSendUtf8Test, IncompleteCharacterInFinalFrame) {
2892 EXPECT_CALL(
2893 *event_interface_,
2894 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2896 CreateChannelAndConnectSuccessfully();
2898 channel_->SendFrame(
2899 true, WebSocketFrameHeader::kOpCodeText, AsVector("\xc2"));
2902 // A non-final Text frame may end with a partial UTF-8 character (compare to
2903 // previous test).
2904 TEST_F(WebSocketChannelSendUtf8Test, IncompleteCharacterInNonFinalFrame) {
2905 CreateChannelAndConnectSuccessfully();
2907 channel_->SendFrame(
2908 false, WebSocketFrameHeader::kOpCodeText, AsVector("\xc2"));
2911 // UTF-8 parsing context must be retained between frames.
2912 TEST_F(WebSocketChannelSendUtf8Test, ValidCharacterSplitBetweenFrames) {
2913 CreateChannelAndConnectSuccessfully();
2915 channel_->SendFrame(
2916 false, WebSocketFrameHeader::kOpCodeText, AsVector("\xf1"));
2917 channel_->SendFrame(true,
2918 WebSocketFrameHeader::kOpCodeContinuation,
2919 AsVector("\x80\xa0\xbf"));
2922 // Similarly, an invalid character should be detected even if split.
2923 TEST_F(WebSocketChannelSendUtf8Test, InvalidCharacterSplit) {
2924 EXPECT_CALL(
2925 *event_interface_,
2926 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2928 CreateChannelAndConnectSuccessfully();
2930 channel_->SendFrame(
2931 false, WebSocketFrameHeader::kOpCodeText, AsVector("\xe1"));
2932 channel_->SendFrame(true,
2933 WebSocketFrameHeader::kOpCodeContinuation,
2934 AsVector("\x80\xa0\xbf"));
2937 // An invalid character must be detected in continuation frames.
2938 TEST_F(WebSocketChannelSendUtf8Test, InvalidByteInContinuation) {
2939 EXPECT_CALL(
2940 *event_interface_,
2941 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2943 CreateChannelAndConnectSuccessfully();
2945 channel_->SendFrame(
2946 false, WebSocketFrameHeader::kOpCodeText, AsVector("foo"));
2947 channel_->SendFrame(
2948 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector("bar"));
2949 channel_->SendFrame(
2950 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("\xff"));
2953 // However, continuation frames of a Binary frame will not be tested for UTF-8
2954 // validity.
2955 TEST_F(WebSocketChannelSendUtf8Test, BinaryContinuationNotChecked) {
2956 CreateChannelAndConnectSuccessfully();
2958 channel_->SendFrame(
2959 false, WebSocketFrameHeader::kOpCodeBinary, AsVector("foo"));
2960 channel_->SendFrame(
2961 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector("bar"));
2962 channel_->SendFrame(
2963 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("\xff"));
2966 // Multiple text messages can be validated without the validation state getting
2967 // confused.
2968 TEST_F(WebSocketChannelSendUtf8Test, ValidateMultipleTextMessages) {
2969 CreateChannelAndConnectSuccessfully();
2971 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("foo"));
2972 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("bar"));
2975 // UTF-8 validation is enforced on received Text frames.
2976 TEST_F(WebSocketChannelEventInterfaceTest, ReceivedInvalidUtf8) {
2977 scoped_ptr<ReadableFakeWebSocketStream> stream(
2978 new ReadableFakeWebSocketStream);
2979 static const InitFrame frames[] = {
2980 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xff"}};
2981 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2982 set_stream(stream.Pass());
2984 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
2985 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
2986 EXPECT_CALL(*event_interface_,
2987 OnFailChannel("Could not decode a text frame as UTF-8."));
2989 CreateChannelAndConnectSuccessfully();
2990 base::MessageLoop::current()->RunUntilIdle();
2993 // Invalid UTF-8 is not sent over the network.
2994 TEST_F(WebSocketChannelStreamTest, InvalidUtf8TextFrameNotSent) {
2995 static const InitFrame expected[] = {{FINAL_FRAME,
2996 WebSocketFrameHeader::kOpCodeClose,
2997 MASKED, CLOSE_DATA(GOING_AWAY, "")}};
2998 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2999 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
3000 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3001 .WillRepeatedly(Return(ERR_IO_PENDING));
3002 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3003 .WillOnce(Return(OK));
3004 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3006 CreateChannelAndConnectSuccessfully();
3008 channel_->SendFrame(
3009 true, WebSocketFrameHeader::kOpCodeText, AsVector("\xff"));
3012 // The rest of the tests for receiving invalid UTF-8 test the communication with
3013 // the server. Since there is only one code path, it would be redundant to
3014 // perform the same tests on the EventInterface as well.
3016 // If invalid UTF-8 is received in a Text frame, the connection is failed.
3017 TEST_F(WebSocketChannelReceiveUtf8Test, InvalidTextFrameRejected) {
3018 static const InitFrame frames[] = {
3019 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xff"}};
3020 static const InitFrame expected[] = {
3021 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
3022 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
3024 InSequence s;
3025 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3026 .WillOnce(ReturnFrames(&frames))
3027 .WillRepeatedly(Return(ERR_IO_PENDING));
3028 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3029 .WillOnce(Return(OK));
3030 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3033 CreateChannelAndConnectSuccessfully();
3036 // A received Text message is not permitted to end with a partial UTF-8
3037 // character.
3038 TEST_F(WebSocketChannelReceiveUtf8Test, IncompleteCharacterReceived) {
3039 static const InitFrame frames[] = {
3040 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xc2"}};
3041 static const InitFrame expected[] = {
3042 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
3043 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
3044 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3045 .WillOnce(ReturnFrames(&frames))
3046 .WillRepeatedly(Return(ERR_IO_PENDING));
3047 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3048 .WillOnce(Return(OK));
3049 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3051 CreateChannelAndConnectSuccessfully();
3054 // However, a non-final Text frame may end with a partial UTF-8 character.
3055 TEST_F(WebSocketChannelReceiveUtf8Test, IncompleteCharacterIncompleteMessage) {
3056 static const InitFrame frames[] = {
3057 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xc2"}};
3058 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3059 .WillOnce(ReturnFrames(&frames))
3060 .WillRepeatedly(Return(ERR_IO_PENDING));
3062 CreateChannelAndConnectSuccessfully();
3065 // However, it will become an error if it is followed by an empty final frame.
3066 TEST_F(WebSocketChannelReceiveUtf8Test, TricksyIncompleteCharacter) {
3067 static const InitFrame frames[] = {
3068 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xc2"},
3069 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation, NOT_MASKED, ""}};
3070 static const InitFrame expected[] = {
3071 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
3072 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
3073 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3074 .WillOnce(ReturnFrames(&frames))
3075 .WillRepeatedly(Return(ERR_IO_PENDING));
3076 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3077 .WillOnce(Return(OK));
3078 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3080 CreateChannelAndConnectSuccessfully();
3083 // UTF-8 parsing context must be retained between received frames of the same
3084 // message.
3085 TEST_F(WebSocketChannelReceiveUtf8Test, ReceivedParsingContextRetained) {
3086 static const InitFrame frames[] = {
3087 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xf1"},
3088 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3089 NOT_MASKED, "\x80\xa0\xbf"}};
3090 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3091 .WillOnce(ReturnFrames(&frames))
3092 .WillRepeatedly(Return(ERR_IO_PENDING));
3094 CreateChannelAndConnectSuccessfully();
3097 // An invalid character must be detected even if split between frames.
3098 TEST_F(WebSocketChannelReceiveUtf8Test, SplitInvalidCharacterReceived) {
3099 static const InitFrame frames[] = {
3100 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xe1"},
3101 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3102 NOT_MASKED, "\x80\xa0\xbf"}};
3103 static const InitFrame expected[] = {
3104 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
3105 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
3106 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3107 .WillOnce(ReturnFrames(&frames))
3108 .WillRepeatedly(Return(ERR_IO_PENDING));
3109 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3110 .WillOnce(Return(OK));
3111 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3113 CreateChannelAndConnectSuccessfully();
3116 // An invalid character received in a continuation frame must be detected.
3117 TEST_F(WebSocketChannelReceiveUtf8Test, InvalidReceivedIncontinuation) {
3118 static const InitFrame frames[] = {
3119 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "foo"},
3120 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3121 NOT_MASKED, "bar"},
3122 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3123 NOT_MASKED, "\xff"}};
3124 static const InitFrame expected[] = {
3125 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
3126 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
3127 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3128 .WillOnce(ReturnFrames(&frames))
3129 .WillRepeatedly(Return(ERR_IO_PENDING));
3130 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3131 .WillOnce(Return(OK));
3132 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3134 CreateChannelAndConnectSuccessfully();
3137 // Continuations of binary frames must not be tested for UTF-8 validity.
3138 TEST_F(WebSocketChannelReceiveUtf8Test, ReceivedBinaryNotUtf8Tested) {
3139 static const InitFrame frames[] = {
3140 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeBinary, NOT_MASKED, "foo"},
3141 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3142 NOT_MASKED, "bar"},
3143 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3144 NOT_MASKED, "\xff"}};
3145 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3146 .WillOnce(ReturnFrames(&frames))
3147 .WillRepeatedly(Return(ERR_IO_PENDING));
3149 CreateChannelAndConnectSuccessfully();
3152 // Multiple Text messages can be validated.
3153 TEST_F(WebSocketChannelReceiveUtf8Test, ValidateMultipleReceived) {
3154 static const InitFrame frames[] = {
3155 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "foo"},
3156 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "bar"}};
3157 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3158 .WillOnce(ReturnFrames(&frames))
3159 .WillRepeatedly(Return(ERR_IO_PENDING));
3161 CreateChannelAndConnectSuccessfully();
3164 // A new data message cannot start in the middle of another data message.
3165 TEST_F(WebSocketChannelEventInterfaceTest, BogusContinuation) {
3166 scoped_ptr<ReadableFakeWebSocketStream> stream(
3167 new ReadableFakeWebSocketStream);
3168 static const InitFrame frames[] = {
3169 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeBinary,
3170 NOT_MASKED, "frame1"},
3171 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
3172 NOT_MASKED, "frame2"}};
3173 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
3174 set_stream(stream.Pass());
3176 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
3177 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
3178 EXPECT_CALL(
3179 *event_interface_,
3180 OnDataFrame(
3181 false, WebSocketFrameHeader::kOpCodeBinary, AsVector("frame1")));
3182 EXPECT_CALL(
3183 *event_interface_,
3184 OnFailChannel(
3185 "Received start of new message but previous message is unfinished."));
3187 CreateChannelAndConnectSuccessfully();
3190 // A new message cannot start with a Continuation frame.
3191 TEST_F(WebSocketChannelEventInterfaceTest, MessageStartingWithContinuation) {
3192 scoped_ptr<ReadableFakeWebSocketStream> stream(
3193 new ReadableFakeWebSocketStream);
3194 static const InitFrame frames[] = {
3195 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3196 NOT_MASKED, "continuation"}};
3197 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
3198 set_stream(stream.Pass());
3200 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
3201 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
3202 EXPECT_CALL(*event_interface_,
3203 OnFailChannel("Received unexpected continuation frame."));
3205 CreateChannelAndConnectSuccessfully();
3208 // A frame passed to the renderer must be either non-empty or have the final bit
3209 // set.
3210 TEST_F(WebSocketChannelEventInterfaceTest, DataFramesNonEmptyOrFinal) {
3211 scoped_ptr<ReadableFakeWebSocketStream> stream(
3212 new ReadableFakeWebSocketStream);
3213 static const InitFrame frames[] = {
3214 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, ""},
3215 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3216 NOT_MASKED, ""},
3217 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation, NOT_MASKED, ""}};
3218 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
3219 set_stream(stream.Pass());
3221 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _));
3222 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
3223 EXPECT_CALL(
3224 *event_interface_,
3225 OnDataFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("")));
3227 CreateChannelAndConnectSuccessfully();
3230 // Calls to OnSSLCertificateError() must be passed through to the event
3231 // interface with the correct URL attached.
3232 TEST_F(WebSocketChannelEventInterfaceTest, OnSSLCertificateErrorCalled) {
3233 const GURL wss_url("wss://example.com/sslerror");
3234 connect_data_.socket_url = wss_url;
3235 const SSLInfo ssl_info;
3236 const bool fatal = true;
3237 scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks> fake_callbacks(
3238 new FakeSSLErrorCallbacks);
3240 EXPECT_CALL(*event_interface_,
3241 OnSSLCertificateErrorCalled(NotNull(), wss_url, _, fatal));
3243 CreateChannelAndConnect();
3244 connect_data_.creator.connect_delegate->OnSSLCertificateError(
3245 fake_callbacks.Pass(), ssl_info, fatal);
3248 // If we receive another frame after Close, it is not valid. It is not
3249 // completely clear what behaviour is required from the standard in this case,
3250 // but the current implementation fails the connection. Since a Close has
3251 // already been sent, this just means closing the connection.
3252 TEST_F(WebSocketChannelStreamTest, PingAfterCloseIsRejected) {
3253 static const InitFrame frames[] = {
3254 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3255 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")},
3256 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
3257 NOT_MASKED, "Ping body"}};
3258 static const InitFrame expected[] = {
3259 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3260 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
3261 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
3262 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
3263 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3264 .WillOnce(ReturnFrames(&frames))
3265 .WillRepeatedly(Return(ERR_IO_PENDING));
3267 // We only need to verify the relative order of WriteFrames() and
3268 // Close(). The current implementation calls WriteFrames() for the Close
3269 // frame before calling ReadFrames() again, but that is an implementation
3270 // detail and better not to consider required behaviour.
3271 InSequence s;
3272 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3273 .WillOnce(Return(OK));
3274 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3277 CreateChannelAndConnectSuccessfully();
3280 // A protocol error from the remote server should result in a close frame with
3281 // status 1002, followed by the connection closing.
3282 TEST_F(WebSocketChannelStreamTest, ProtocolError) {
3283 static const InitFrame expected[] = {
3284 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3285 MASKED, CLOSE_DATA(PROTOCOL_ERROR, "WebSocket Protocol Error")}};
3286 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
3287 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
3288 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3289 .WillOnce(Return(ERR_WS_PROTOCOL_ERROR));
3290 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3291 .WillOnce(Return(OK));
3292 EXPECT_CALL(*mock_stream_, Close());
3294 CreateChannelAndConnectSuccessfully();
3297 // Set the closing handshake timeout to a very tiny value before connecting.
3298 class WebSocketChannelStreamTimeoutTest : public WebSocketChannelStreamTest {
3299 protected:
3300 WebSocketChannelStreamTimeoutTest() {}
3302 void CreateChannelAndConnectSuccessfully() override {
3303 set_stream(mock_stream_.Pass());
3304 CreateChannelAndConnect();
3305 channel_->SendFlowControl(kPlentyOfQuota);
3306 channel_->SetClosingHandshakeTimeoutForTesting(
3307 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
3308 channel_->SetUnderlyingConnectionCloseTimeoutForTesting(
3309 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
3310 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
3314 // In this case the server initiates the closing handshake with a Close
3315 // message. WebSocketChannel responds with a matching Close message, and waits
3316 // for the server to close the TCP/IP connection. The server never closes the
3317 // connection, so the closing handshake times out and WebSocketChannel closes
3318 // the connection itself.
3319 TEST_F(WebSocketChannelStreamTimeoutTest, ServerInitiatedCloseTimesOut) {
3320 static const InitFrame frames[] = {
3321 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3322 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
3323 static const InitFrame expected[] = {
3324 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3325 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
3326 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
3327 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
3328 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3329 .WillOnce(ReturnFrames(&frames))
3330 .WillRepeatedly(Return(ERR_IO_PENDING));
3331 Checkpoint checkpoint;
3332 TestClosure completion;
3334 InSequence s;
3335 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3336 .WillOnce(Return(OK));
3337 EXPECT_CALL(checkpoint, Call(1));
3338 EXPECT_CALL(*mock_stream_, Close())
3339 .WillOnce(InvokeClosure(completion.closure()));
3342 CreateChannelAndConnectSuccessfully();
3343 checkpoint.Call(1);
3344 completion.WaitForResult();
3347 // In this case the client initiates the closing handshake by sending a Close
3348 // message. WebSocketChannel waits for a Close message in response from the
3349 // server. The server never responds to the Close message, so the closing
3350 // handshake times out and WebSocketChannel closes the connection.
3351 TEST_F(WebSocketChannelStreamTimeoutTest, ClientInitiatedCloseTimesOut) {
3352 static const InitFrame expected[] = {
3353 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3354 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
3355 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
3356 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
3357 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3358 .WillRepeatedly(Return(ERR_IO_PENDING));
3359 TestClosure completion;
3361 InSequence s;
3362 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3363 .WillOnce(Return(OK));
3364 EXPECT_CALL(*mock_stream_, Close())
3365 .WillOnce(InvokeClosure(completion.closure()));
3368 CreateChannelAndConnectSuccessfully();
3369 channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
3370 completion.WaitForResult();
3373 // In this case the client initiates the closing handshake and the server
3374 // responds with a matching Close message. WebSocketChannel waits for the server
3375 // to close the TCP/IP connection, but it never does. The closing handshake
3376 // times out and WebSocketChannel closes the connection.
3377 TEST_F(WebSocketChannelStreamTimeoutTest, ConnectionCloseTimesOut) {
3378 static const InitFrame expected[] = {
3379 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3380 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
3381 static const InitFrame frames[] = {
3382 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3383 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
3384 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
3385 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
3386 TestClosure completion;
3387 ScopedVector<WebSocketFrame>* read_frames = NULL;
3388 CompletionCallback read_callback;
3390 InSequence s;
3391 // Copy the arguments to ReadFrames so that the test can call the callback
3392 // after it has send the close message.
3393 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3394 .WillOnce(DoAll(SaveArg<0>(&read_frames),
3395 SaveArg<1>(&read_callback),
3396 Return(ERR_IO_PENDING)));
3397 // The first real event that happens is the client sending the Close
3398 // message.
3399 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3400 .WillOnce(Return(OK));
3401 // The |read_frames| callback is called (from this test case) at this
3402 // point. ReadFrames is called again by WebSocketChannel, waiting for
3403 // ERR_CONNECTION_CLOSED.
3404 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3405 .WillOnce(Return(ERR_IO_PENDING));
3406 // The timeout happens and so WebSocketChannel closes the stream.
3407 EXPECT_CALL(*mock_stream_, Close())
3408 .WillOnce(InvokeClosure(completion.closure()));
3411 CreateChannelAndConnectSuccessfully();
3412 channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
3413 ASSERT_TRUE(read_frames);
3414 // Provide the "Close" message from the server.
3415 *read_frames = CreateFrameVector(frames);
3416 read_callback.Run(OK);
3417 completion.WaitForResult();
3420 } // namespace
3421 } // namespace net