MacViews: Get c/b/ui/views/tabs to build on Mac
[chromium-blink-merge.git] / net / websockets / websocket_channel_test.cc
blob15163deb647c622f674f59e4472c0bb92adc2053
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 // TestTimeouts::tiny_timeout() is 100ms! I could run halfway around the world
131 // in that time! I would like my tests to run a bit quicker.
132 const int kVeryTinyTimeoutMillis = 1;
134 // Enough quota to pass any test.
135 const int64 kPlentyOfQuota = INT_MAX;
137 typedef WebSocketEventInterface::ChannelState ChannelState;
138 const ChannelState CHANNEL_ALIVE = WebSocketEventInterface::CHANNEL_ALIVE;
139 const ChannelState CHANNEL_DELETED = WebSocketEventInterface::CHANNEL_DELETED;
141 // This typedef mainly exists to avoid having to repeat the "NOLINT" incantation
142 // all over the place.
143 typedef StrictMock< MockFunction<void(int)> > Checkpoint; // NOLINT
145 // This mock is for testing expectations about how the EventInterface is used.
146 class MockWebSocketEventInterface : public WebSocketEventInterface {
147 public:
148 MockWebSocketEventInterface() {}
150 MOCK_METHOD3(OnAddChannelResponse,
151 ChannelState(bool,
152 const std::string&,
153 const std::string&)); // NOLINT
154 MOCK_METHOD3(OnDataFrame,
155 ChannelState(bool,
156 WebSocketMessageType,
157 const std::vector<char>&)); // NOLINT
158 MOCK_METHOD1(OnFlowControl, ChannelState(int64)); // NOLINT
159 MOCK_METHOD0(OnClosingHandshake, ChannelState(void)); // NOLINT
160 MOCK_METHOD1(OnFailChannel, ChannelState(const std::string&)); // NOLINT
161 MOCK_METHOD3(OnDropChannel,
162 ChannelState(bool, uint16, const std::string&)); // NOLINT
164 // We can't use GMock with scoped_ptr.
165 ChannelState OnStartOpeningHandshake(
166 scoped_ptr<WebSocketHandshakeRequestInfo>) override {
167 OnStartOpeningHandshakeCalled();
168 return CHANNEL_ALIVE;
170 ChannelState OnFinishOpeningHandshake(
171 scoped_ptr<WebSocketHandshakeResponseInfo>) override {
172 OnFinishOpeningHandshakeCalled();
173 return CHANNEL_ALIVE;
175 virtual ChannelState OnSSLCertificateError(
176 scoped_ptr<SSLErrorCallbacks> ssl_error_callbacks,
177 const GURL& url,
178 const SSLInfo& ssl_info,
179 bool fatal) override {
180 OnSSLCertificateErrorCalled(
181 ssl_error_callbacks.get(), url, ssl_info, fatal);
182 return CHANNEL_ALIVE;
185 MOCK_METHOD0(OnStartOpeningHandshakeCalled, void()); // NOLINT
186 MOCK_METHOD0(OnFinishOpeningHandshakeCalled, void()); // NOLINT
187 MOCK_METHOD4(
188 OnSSLCertificateErrorCalled,
189 void(SSLErrorCallbacks*, const GURL&, const SSLInfo&, bool)); // NOLINT
192 // This fake EventInterface is for tests which need a WebSocketEventInterface
193 // implementation but are not verifying how it is used.
194 class FakeWebSocketEventInterface : public WebSocketEventInterface {
195 ChannelState OnAddChannelResponse(bool fail,
196 const std::string& selected_protocol,
197 const std::string& extensions) override {
198 return fail ? CHANNEL_DELETED : 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 // TestClosure works like TestCompletionCallback, but doesn't take an argument.
426 class TestClosure {
427 public:
428 base::Closure closure() { return base::Bind(callback_.callback(), OK); }
430 void WaitForResult() { callback_.WaitForResult(); }
432 private:
433 // Delegate to TestCompletionCallback for the implementation.
434 TestCompletionCallback callback_;
437 // A GoogleMock action to run a Closure.
438 ACTION_P(InvokeClosure, closure) { closure.Run(); }
440 // A GoogleMock action to run a Closure and return CHANNEL_DELETED.
441 ACTION_P(InvokeClosureReturnDeleted, closure) {
442 closure.Run();
443 return WebSocketEventInterface::CHANNEL_DELETED;
446 // A FakeWebSocketStream whose ReadFrames() function returns data.
447 class ReadableFakeWebSocketStream : public FakeWebSocketStream {
448 public:
449 enum IsSync { SYNC, ASYNC };
451 // After constructing the object, call PrepareReadFrames() once for each
452 // time you wish it to return from the test.
453 ReadableFakeWebSocketStream() : index_(0), read_frames_pending_(false) {}
455 // Check that all the prepared responses have been consumed.
456 ~ReadableFakeWebSocketStream() override {
457 CHECK(index_ >= responses_.size());
458 CHECK(!read_frames_pending_);
461 // Prepares a fake response. Fake responses will be returned from ReadFrames()
462 // in the same order they were prepared with PrepareReadFrames() and
463 // PrepareReadFramesError(). If |async| is ASYNC, then ReadFrames() will
464 // return ERR_IO_PENDING and the callback will be scheduled to run on the
465 // message loop. This requires the test case to run the message loop. If
466 // |async| is SYNC, the response will be returned synchronously. |error| is
467 // returned directly from ReadFrames() in the synchronous case, or passed to
468 // the callback in the asynchronous case. |frames| will be converted to a
469 // ScopedVector<WebSocketFrame> and copied to the pointer that was passed to
470 // ReadFrames().
471 template <size_t N>
472 void PrepareReadFrames(IsSync async,
473 int error,
474 const InitFrame (&frames)[N]) {
475 responses_.push_back(new Response(async, error, CreateFrameVector(frames)));
478 // An alternate version of PrepareReadFrames for when we need to construct
479 // the frames manually.
480 void PrepareRawReadFrames(IsSync async,
481 int error,
482 ScopedVector<WebSocketFrame> frames) {
483 responses_.push_back(new Response(async, error, frames.Pass()));
486 // Prepares a fake error response (ie. there is no data).
487 void PrepareReadFramesError(IsSync async, int error) {
488 responses_.push_back(
489 new Response(async, error, ScopedVector<WebSocketFrame>()));
492 int ReadFrames(ScopedVector<WebSocketFrame>* frames,
493 const CompletionCallback& callback) override {
494 CHECK(!read_frames_pending_);
495 if (index_ >= responses_.size())
496 return ERR_IO_PENDING;
497 if (responses_[index_]->async == ASYNC) {
498 read_frames_pending_ = true;
499 base::MessageLoop::current()->PostTask(
500 FROM_HERE,
501 base::Bind(&ReadableFakeWebSocketStream::DoCallback,
502 base::Unretained(this),
503 frames,
504 callback));
505 return ERR_IO_PENDING;
506 } else {
507 frames->swap(responses_[index_]->frames);
508 return responses_[index_++]->error;
512 private:
513 void DoCallback(ScopedVector<WebSocketFrame>* frames,
514 const CompletionCallback& callback) {
515 read_frames_pending_ = false;
516 frames->swap(responses_[index_]->frames);
517 callback.Run(responses_[index_++]->error);
518 return;
521 struct Response {
522 Response(IsSync async, int error, ScopedVector<WebSocketFrame> frames)
523 : async(async), error(error), frames(frames.Pass()) {}
525 IsSync async;
526 int error;
527 ScopedVector<WebSocketFrame> frames;
529 private:
530 // Bad things will happen if we attempt to copy or assign |frames|.
531 DISALLOW_COPY_AND_ASSIGN(Response);
533 ScopedVector<Response> responses_;
535 // The index into the responses_ array of the next response to be returned.
536 size_t index_;
538 // True when an async response from ReadFrames() is pending. This only applies
539 // to "real" async responses. Once all the prepared responses have been
540 // returned, ReadFrames() returns ERR_IO_PENDING but read_frames_pending_ is
541 // not set to true.
542 bool read_frames_pending_;
545 // A FakeWebSocketStream where writes always complete successfully and
546 // synchronously.
547 class WriteableFakeWebSocketStream : public FakeWebSocketStream {
548 public:
549 int WriteFrames(ScopedVector<WebSocketFrame>* frames,
550 const CompletionCallback& callback) override {
551 return OK;
555 // A FakeWebSocketStream where writes always fail.
556 class UnWriteableFakeWebSocketStream : public FakeWebSocketStream {
557 public:
558 int WriteFrames(ScopedVector<WebSocketFrame>* frames,
559 const CompletionCallback& callback) override {
560 return ERR_CONNECTION_RESET;
564 // A FakeWebSocketStream which echoes any frames written back. Clears the
565 // "masked" header bit, but makes no other checks for validity. Tests using this
566 // must run the MessageLoop to receive the callback(s). If a message with opcode
567 // Close is echoed, then an ERR_CONNECTION_CLOSED is returned in the next
568 // callback. The test must do something to cause WriteFrames() to be called,
569 // otherwise the ReadFrames() callback will never be called.
570 class EchoeyFakeWebSocketStream : public FakeWebSocketStream {
571 public:
572 EchoeyFakeWebSocketStream() : read_frames_(NULL), done_(false) {}
574 int WriteFrames(ScopedVector<WebSocketFrame>* frames,
575 const CompletionCallback& callback) override {
576 // Users of WebSocketStream will not expect the ReadFrames() callback to be
577 // called from within WriteFrames(), so post it to the message loop instead.
578 stored_frames_.insert(stored_frames_.end(), frames->begin(), frames->end());
579 frames->weak_clear();
580 PostCallback();
581 return OK;
584 int ReadFrames(ScopedVector<WebSocketFrame>* frames,
585 const CompletionCallback& callback) override {
586 read_callback_ = callback;
587 read_frames_ = frames;
588 if (done_)
589 PostCallback();
590 return ERR_IO_PENDING;
593 private:
594 void PostCallback() {
595 base::MessageLoop::current()->PostTask(
596 FROM_HERE,
597 base::Bind(&EchoeyFakeWebSocketStream::DoCallback,
598 base::Unretained(this)));
601 void DoCallback() {
602 if (done_) {
603 read_callback_.Run(ERR_CONNECTION_CLOSED);
604 } else if (!stored_frames_.empty()) {
605 done_ = MoveFrames(read_frames_);
606 read_frames_ = NULL;
607 read_callback_.Run(OK);
611 // Copy the frames stored in stored_frames_ to |out|, while clearing the
612 // "masked" header bit. Returns true if a Close Frame was seen, false
613 // otherwise.
614 bool MoveFrames(ScopedVector<WebSocketFrame>* out) {
615 bool seen_close = false;
616 *out = stored_frames_.Pass();
617 for (ScopedVector<WebSocketFrame>::iterator it = out->begin();
618 it != out->end();
619 ++it) {
620 WebSocketFrameHeader& header = (*it)->header;
621 header.masked = false;
622 if (header.opcode == WebSocketFrameHeader::kOpCodeClose)
623 seen_close = true;
625 return seen_close;
628 ScopedVector<WebSocketFrame> stored_frames_;
629 CompletionCallback read_callback_;
630 // Owned by the caller of ReadFrames().
631 ScopedVector<WebSocketFrame>* read_frames_;
632 // True if we should close the connection.
633 bool done_;
636 // A FakeWebSocketStream where writes trigger a connection reset.
637 // This differs from UnWriteableFakeWebSocketStream in that it is asynchronous
638 // and triggers ReadFrames to return a reset as well. Tests using this need to
639 // run the message loop. There are two tricky parts here:
640 // 1. Calling the write callback may call Close(), after which the read callback
641 // should not be called.
642 // 2. Calling either callback may delete the stream altogether.
643 class ResetOnWriteFakeWebSocketStream : public FakeWebSocketStream {
644 public:
645 ResetOnWriteFakeWebSocketStream() : closed_(false), weak_ptr_factory_(this) {}
647 int WriteFrames(ScopedVector<WebSocketFrame>* frames,
648 const CompletionCallback& callback) override {
649 base::MessageLoop::current()->PostTask(
650 FROM_HERE,
651 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
652 weak_ptr_factory_.GetWeakPtr(),
653 callback,
654 ERR_CONNECTION_RESET));
655 base::MessageLoop::current()->PostTask(
656 FROM_HERE,
657 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
658 weak_ptr_factory_.GetWeakPtr(),
659 read_callback_,
660 ERR_CONNECTION_RESET));
661 return ERR_IO_PENDING;
664 int ReadFrames(ScopedVector<WebSocketFrame>* frames,
665 const CompletionCallback& callback) override {
666 read_callback_ = callback;
667 return ERR_IO_PENDING;
670 void Close() override { closed_ = true; }
672 private:
673 void CallCallbackUnlessClosed(const CompletionCallback& callback, int value) {
674 if (!closed_)
675 callback.Run(value);
678 CompletionCallback read_callback_;
679 bool closed_;
680 // An IO error can result in the socket being deleted, so we use weak pointers
681 // to ensure correct behaviour in that case.
682 base::WeakPtrFactory<ResetOnWriteFakeWebSocketStream> weak_ptr_factory_;
685 // This mock is for verifying that WebSocket protocol semantics are obeyed (to
686 // the extent that they are implemented in WebSocketCommon).
687 class MockWebSocketStream : public WebSocketStream {
688 public:
689 MOCK_METHOD2(ReadFrames,
690 int(ScopedVector<WebSocketFrame>* frames,
691 const CompletionCallback& callback));
692 MOCK_METHOD2(WriteFrames,
693 int(ScopedVector<WebSocketFrame>* frames,
694 const CompletionCallback& callback));
695 MOCK_METHOD0(Close, void());
696 MOCK_CONST_METHOD0(GetSubProtocol, std::string());
697 MOCK_CONST_METHOD0(GetExtensions, std::string());
698 MOCK_METHOD0(AsWebSocketStream, WebSocketStream*());
701 struct ArgumentCopyingWebSocketStreamCreator {
702 scoped_ptr<WebSocketStreamRequest> Create(
703 const GURL& socket_url,
704 const std::vector<std::string>& requested_subprotocols,
705 const url::Origin& origin,
706 URLRequestContext* url_request_context,
707 const BoundNetLog& net_log,
708 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate) {
709 this->socket_url = socket_url;
710 this->requested_subprotocols = requested_subprotocols;
711 this->origin = origin;
712 this->url_request_context = url_request_context;
713 this->net_log = net_log;
714 this->connect_delegate = connect_delegate.Pass();
715 return make_scoped_ptr(new WebSocketStreamRequest);
718 GURL socket_url;
719 url::Origin origin;
720 std::vector<std::string> requested_subprotocols;
721 URLRequestContext* url_request_context;
722 BoundNetLog net_log;
723 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate;
726 // Converts a std::string to a std::vector<char>. For test purposes, it is
727 // convenient to be able to specify data as a string, but the
728 // WebSocketEventInterface requires the vector<char> type.
729 std::vector<char> AsVector(const std::string& s) {
730 return std::vector<char>(s.begin(), s.end());
733 class FakeSSLErrorCallbacks
734 : public WebSocketEventInterface::SSLErrorCallbacks {
735 public:
736 void CancelSSLRequest(int error, const SSLInfo* ssl_info) override {}
737 void ContinueSSLRequest() override {}
740 // Base class for all test fixtures.
741 class WebSocketChannelTest : public ::testing::Test {
742 protected:
743 WebSocketChannelTest() : stream_(new FakeWebSocketStream) {}
745 // Creates a new WebSocketChannel and connects it, using the settings stored
746 // in |connect_data_|.
747 void CreateChannelAndConnect() {
748 channel_.reset(new WebSocketChannel(CreateEventInterface(),
749 &connect_data_.url_request_context));
750 channel_->SendAddChannelRequestForTesting(
751 connect_data_.socket_url,
752 connect_data_.requested_subprotocols,
753 connect_data_.origin,
754 base::Bind(&ArgumentCopyingWebSocketStreamCreator::Create,
755 base::Unretained(&connect_data_.creator)));
758 // Same as CreateChannelAndConnect(), but calls the on_success callback as
759 // well. This method is virtual so that subclasses can also set the stream.
760 virtual void CreateChannelAndConnectSuccessfully() {
761 CreateChannelAndConnect();
762 // Most tests aren't concerned with flow control from the renderer, so allow
763 // MAX_INT quota units.
764 channel_->SendFlowControl(kPlentyOfQuota);
765 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
768 // Returns a WebSocketEventInterface to be passed to the WebSocketChannel.
769 // This implementation returns a newly-created fake. Subclasses may return a
770 // mock instead.
771 virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() {
772 return scoped_ptr<WebSocketEventInterface>(new FakeWebSocketEventInterface);
775 // This method serves no other purpose than to provide a nice syntax for
776 // assigning to stream_. class T must be a subclass of WebSocketStream or you
777 // will have unpleasant compile errors.
778 template <class T>
779 void set_stream(scoped_ptr<T> stream) {
780 stream_ = stream.Pass();
783 // A struct containing the data that will be used to connect the channel.
784 // Grouped for readability.
785 struct ConnectData {
786 ConnectData() : socket_url("ws://ws/"), origin("http://ws") {}
788 // URLRequestContext object.
789 URLRequestContext url_request_context;
791 // URL to (pretend to) connect to.
792 GURL socket_url;
793 // Requested protocols for the request.
794 std::vector<std::string> requested_subprotocols;
795 // Origin of the request
796 url::Origin origin;
798 // A fake WebSocketStreamCreator that just records its arguments.
799 ArgumentCopyingWebSocketStreamCreator creator;
801 ConnectData connect_data_;
803 // The channel we are testing. Not initialised until SetChannel() is called.
804 scoped_ptr<WebSocketChannel> channel_;
806 // A mock or fake stream for tests that need one.
807 scoped_ptr<WebSocketStream> stream_;
810 // enum of WebSocketEventInterface calls. These are intended to be or'd together
811 // in order to instruct WebSocketChannelDeletingTest when it should fail.
812 enum EventInterfaceCall {
813 EVENT_ON_ADD_CHANNEL_RESPONSE = 0x1,
814 EVENT_ON_DATA_FRAME = 0x2,
815 EVENT_ON_FLOW_CONTROL = 0x4,
816 EVENT_ON_CLOSING_HANDSHAKE = 0x8,
817 EVENT_ON_FAIL_CHANNEL = 0x10,
818 EVENT_ON_DROP_CHANNEL = 0x20,
819 EVENT_ON_START_OPENING_HANDSHAKE = 0x40,
820 EVENT_ON_FINISH_OPENING_HANDSHAKE = 0x80,
821 EVENT_ON_SSL_CERTIFICATE_ERROR = 0x100,
824 class WebSocketChannelDeletingTest : public WebSocketChannelTest {
825 public:
826 ChannelState DeleteIfDeleting(EventInterfaceCall call) {
827 if (deleting_ & call) {
828 channel_.reset();
829 return CHANNEL_DELETED;
830 } else {
831 return CHANNEL_ALIVE;
835 protected:
836 WebSocketChannelDeletingTest()
837 : deleting_(EVENT_ON_ADD_CHANNEL_RESPONSE | EVENT_ON_DATA_FRAME |
838 EVENT_ON_FLOW_CONTROL |
839 EVENT_ON_CLOSING_HANDSHAKE |
840 EVENT_ON_FAIL_CHANNEL |
841 EVENT_ON_DROP_CHANNEL |
842 EVENT_ON_START_OPENING_HANDSHAKE |
843 EVENT_ON_FINISH_OPENING_HANDSHAKE |
844 EVENT_ON_SSL_CERTIFICATE_ERROR) {}
845 // Create a ChannelDeletingFakeWebSocketEventInterface. Defined out-of-line to
846 // avoid circular dependency.
847 scoped_ptr<WebSocketEventInterface> CreateEventInterface() override;
849 // Tests can set deleting_ to a bitmap of EventInterfaceCall members that they
850 // want to cause Channel deletion. The default is for all calls to cause
851 // deletion.
852 int deleting_;
855 // A FakeWebSocketEventInterface that deletes the WebSocketChannel on failure to
856 // connect.
857 class ChannelDeletingFakeWebSocketEventInterface
858 : public FakeWebSocketEventInterface {
859 public:
860 ChannelDeletingFakeWebSocketEventInterface(
861 WebSocketChannelDeletingTest* fixture)
862 : fixture_(fixture) {}
864 ChannelState OnAddChannelResponse(bool fail,
865 const std::string& selected_protocol,
866 const std::string& extensions) override {
867 return fixture_->DeleteIfDeleting(EVENT_ON_ADD_CHANNEL_RESPONSE);
870 ChannelState OnDataFrame(bool fin,
871 WebSocketMessageType type,
872 const std::vector<char>& data) override {
873 return fixture_->DeleteIfDeleting(EVENT_ON_DATA_FRAME);
876 ChannelState OnFlowControl(int64 quota) override {
877 return fixture_->DeleteIfDeleting(EVENT_ON_FLOW_CONTROL);
880 ChannelState OnClosingHandshake() override {
881 return fixture_->DeleteIfDeleting(EVENT_ON_CLOSING_HANDSHAKE);
884 ChannelState OnFailChannel(const std::string& message) override {
885 return fixture_->DeleteIfDeleting(EVENT_ON_FAIL_CHANNEL);
888 ChannelState OnDropChannel(bool was_clean,
889 uint16 code,
890 const std::string& reason) override {
891 return fixture_->DeleteIfDeleting(EVENT_ON_DROP_CHANNEL);
894 ChannelState OnStartOpeningHandshake(
895 scoped_ptr<WebSocketHandshakeRequestInfo> request) override {
896 return fixture_->DeleteIfDeleting(EVENT_ON_START_OPENING_HANDSHAKE);
898 ChannelState OnFinishOpeningHandshake(
899 scoped_ptr<WebSocketHandshakeResponseInfo> response) override {
900 return fixture_->DeleteIfDeleting(EVENT_ON_FINISH_OPENING_HANDSHAKE);
902 ChannelState OnSSLCertificateError(
903 scoped_ptr<SSLErrorCallbacks> ssl_error_callbacks,
904 const GURL& url,
905 const SSLInfo& ssl_info,
906 bool fatal) override {
907 return fixture_->DeleteIfDeleting(EVENT_ON_SSL_CERTIFICATE_ERROR);
910 private:
911 // A pointer to the test fixture. Owned by the test harness; this object will
912 // be deleted before it is.
913 WebSocketChannelDeletingTest* fixture_;
916 scoped_ptr<WebSocketEventInterface>
917 WebSocketChannelDeletingTest::CreateEventInterface() {
918 return scoped_ptr<WebSocketEventInterface>(
919 new ChannelDeletingFakeWebSocketEventInterface(this));
922 // Base class for tests which verify that EventInterface methods are called
923 // appropriately.
924 class WebSocketChannelEventInterfaceTest : public WebSocketChannelTest {
925 protected:
926 WebSocketChannelEventInterfaceTest()
927 : event_interface_(new StrictMock<MockWebSocketEventInterface>) {
928 DefaultValue<ChannelState>::Set(CHANNEL_ALIVE);
929 ON_CALL(*event_interface_, OnAddChannelResponse(true, _, _))
930 .WillByDefault(Return(CHANNEL_DELETED));
931 ON_CALL(*event_interface_, OnDropChannel(_, _, _))
932 .WillByDefault(Return(CHANNEL_DELETED));
933 ON_CALL(*event_interface_, OnFailChannel(_))
934 .WillByDefault(Return(CHANNEL_DELETED));
937 virtual ~WebSocketChannelEventInterfaceTest() {
938 DefaultValue<ChannelState>::Clear();
941 // Tests using this fixture must set expectations on the event_interface_ mock
942 // object before calling CreateChannelAndConnect() or
943 // CreateChannelAndConnectSuccessfully(). This will only work once per test
944 // case, but once should be enough.
945 scoped_ptr<WebSocketEventInterface> CreateEventInterface() override {
946 return scoped_ptr<WebSocketEventInterface>(event_interface_.release());
949 scoped_ptr<MockWebSocketEventInterface> event_interface_;
952 // Base class for tests which verify that WebSocketStream methods are called
953 // appropriately by using a MockWebSocketStream.
954 class WebSocketChannelStreamTest : public WebSocketChannelTest {
955 protected:
956 WebSocketChannelStreamTest()
957 : mock_stream_(new StrictMock<MockWebSocketStream>) {}
959 void CreateChannelAndConnectSuccessfully() override {
960 set_stream(mock_stream_.Pass());
961 WebSocketChannelTest::CreateChannelAndConnectSuccessfully();
964 scoped_ptr<MockWebSocketStream> mock_stream_;
967 // Fixture for tests which test UTF-8 validation of sent Text frames via the
968 // EventInterface.
969 class WebSocketChannelSendUtf8Test
970 : public WebSocketChannelEventInterfaceTest {
971 public:
972 virtual void SetUp() {
973 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
974 // For the purpose of the tests using this fixture, it doesn't matter
975 // whether these methods are called or not.
976 EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _, _))
977 .Times(AnyNumber());
978 EXPECT_CALL(*event_interface_, OnFlowControl(_))
979 .Times(AnyNumber());
983 // Fixture for tests which test use of receive quota from the renderer.
984 class WebSocketChannelFlowControlTest
985 : public WebSocketChannelEventInterfaceTest {
986 protected:
987 // Tests using this fixture should use CreateChannelAndConnectWithQuota()
988 // instead of CreateChannelAndConnectSuccessfully().
989 void CreateChannelAndConnectWithQuota(int64 quota) {
990 CreateChannelAndConnect();
991 channel_->SendFlowControl(quota);
992 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
995 virtual void CreateChannelAndConnectSuccesfully() { NOTREACHED(); }
998 // Fixture for tests which test UTF-8 validation of received Text frames using a
999 // mock WebSocketStream.
1000 class WebSocketChannelReceiveUtf8Test : public WebSocketChannelStreamTest {
1001 public:
1002 virtual void SetUp() {
1003 // For the purpose of the tests using this fixture, it doesn't matter
1004 // whether these methods are called or not.
1005 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1006 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
1010 // Simple test that everything that should be passed to the creator function is
1011 // passed to the creator function.
1012 TEST_F(WebSocketChannelTest, EverythingIsPassedToTheCreatorFunction) {
1013 connect_data_.socket_url = GURL("ws://example.com/test");
1014 connect_data_.origin = url::Origin("http://example.com");
1015 connect_data_.requested_subprotocols.push_back("Sinbad");
1017 CreateChannelAndConnect();
1019 const ArgumentCopyingWebSocketStreamCreator& actual = connect_data_.creator;
1021 EXPECT_EQ(&connect_data_.url_request_context, actual.url_request_context);
1023 EXPECT_EQ(connect_data_.socket_url, actual.socket_url);
1024 EXPECT_EQ(connect_data_.requested_subprotocols,
1025 actual.requested_subprotocols);
1026 EXPECT_EQ(connect_data_.origin.string(), actual.origin.string());
1029 // Verify that calling SendFlowControl before the connection is established does
1030 // not cause a crash.
1031 TEST_F(WebSocketChannelTest, SendFlowControlDuringHandshakeOkay) {
1032 CreateChannelAndConnect();
1033 ASSERT_TRUE(channel_);
1034 channel_->SendFlowControl(65536);
1037 // Any WebSocketEventInterface methods can delete the WebSocketChannel and
1038 // return CHANNEL_DELETED. The WebSocketChannelDeletingTests are intended to
1039 // verify that there are no use-after-free bugs when this happens. Problems will
1040 // probably only be found when running under Address Sanitizer or a similar
1041 // tool.
1042 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseFail) {
1043 CreateChannelAndConnect();
1044 EXPECT_TRUE(channel_);
1045 connect_data_.creator.connect_delegate->OnFailure("bye");
1046 EXPECT_EQ(NULL, channel_.get());
1049 // Deletion is possible (due to IPC failure) even if the connect succeeds.
1050 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseSuccess) {
1051 CreateChannelAndConnectSuccessfully();
1052 EXPECT_EQ(NULL, channel_.get());
1055 TEST_F(WebSocketChannelDeletingTest, OnDataFrameSync) {
1056 scoped_ptr<ReadableFakeWebSocketStream> stream(
1057 new ReadableFakeWebSocketStream);
1058 static const InitFrame frames[] = {
1059 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1060 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1061 set_stream(stream.Pass());
1062 deleting_ = EVENT_ON_DATA_FRAME;
1064 CreateChannelAndConnectSuccessfully();
1065 EXPECT_EQ(NULL, channel_.get());
1068 TEST_F(WebSocketChannelDeletingTest, OnDataFrameAsync) {
1069 scoped_ptr<ReadableFakeWebSocketStream> stream(
1070 new ReadableFakeWebSocketStream);
1071 static const InitFrame frames[] = {
1072 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1073 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1074 set_stream(stream.Pass());
1075 deleting_ = EVENT_ON_DATA_FRAME;
1077 CreateChannelAndConnectSuccessfully();
1078 EXPECT_TRUE(channel_);
1079 base::MessageLoop::current()->RunUntilIdle();
1080 EXPECT_EQ(NULL, channel_.get());
1083 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterConnect) {
1084 deleting_ = EVENT_ON_FLOW_CONTROL;
1086 CreateChannelAndConnectSuccessfully();
1087 EXPECT_EQ(NULL, channel_.get());
1090 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterSend) {
1091 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1092 // Avoid deleting the channel yet.
1093 deleting_ = EVENT_ON_FAIL_CHANNEL | EVENT_ON_DROP_CHANNEL;
1094 CreateChannelAndConnectSuccessfully();
1095 ASSERT_TRUE(channel_);
1096 deleting_ = EVENT_ON_FLOW_CONTROL;
1097 channel_->SendFrame(true,
1098 WebSocketFrameHeader::kOpCodeText,
1099 std::vector<char>(kDefaultInitialQuota, 'B'));
1100 EXPECT_EQ(NULL, channel_.get());
1103 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeSync) {
1104 scoped_ptr<ReadableFakeWebSocketStream> stream(
1105 new ReadableFakeWebSocketStream);
1106 static const InitFrame frames[] = {
1107 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1108 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
1109 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1110 set_stream(stream.Pass());
1111 deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
1112 CreateChannelAndConnectSuccessfully();
1113 EXPECT_EQ(NULL, channel_.get());
1116 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeAsync) {
1117 scoped_ptr<ReadableFakeWebSocketStream> stream(
1118 new ReadableFakeWebSocketStream);
1119 static const InitFrame frames[] = {
1120 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1121 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
1122 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1123 set_stream(stream.Pass());
1124 deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
1125 CreateChannelAndConnectSuccessfully();
1126 ASSERT_TRUE(channel_);
1127 base::MessageLoop::current()->RunUntilIdle();
1128 EXPECT_EQ(NULL, channel_.get());
1131 TEST_F(WebSocketChannelDeletingTest, OnDropChannelWriteError) {
1132 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
1133 deleting_ = EVENT_ON_DROP_CHANNEL;
1134 CreateChannelAndConnectSuccessfully();
1135 ASSERT_TRUE(channel_);
1136 channel_->SendFrame(
1137 true, WebSocketFrameHeader::kOpCodeText, AsVector("this will fail"));
1138 EXPECT_EQ(NULL, channel_.get());
1141 TEST_F(WebSocketChannelDeletingTest, OnDropChannelReadError) {
1142 scoped_ptr<ReadableFakeWebSocketStream> stream(
1143 new ReadableFakeWebSocketStream);
1144 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1145 ERR_FAILED);
1146 set_stream(stream.Pass());
1147 deleting_ = EVENT_ON_DROP_CHANNEL;
1148 CreateChannelAndConnectSuccessfully();
1149 ASSERT_TRUE(channel_);
1150 base::MessageLoop::current()->RunUntilIdle();
1151 EXPECT_EQ(NULL, channel_.get());
1154 TEST_F(WebSocketChannelDeletingTest, OnNotifyStartOpeningHandshakeError) {
1155 scoped_ptr<ReadableFakeWebSocketStream> stream(
1156 new ReadableFakeWebSocketStream);
1157 static const InitFrame frames[] = {
1158 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1159 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1160 set_stream(stream.Pass());
1161 deleting_ = EVENT_ON_START_OPENING_HANDSHAKE;
1163 CreateChannelAndConnectSuccessfully();
1164 ASSERT_TRUE(channel_);
1165 channel_->OnStartOpeningHandshake(scoped_ptr<WebSocketHandshakeRequestInfo>(
1166 new WebSocketHandshakeRequestInfo(GURL("http://www.example.com/"),
1167 base::Time())));
1168 base::MessageLoop::current()->RunUntilIdle();
1169 EXPECT_EQ(NULL, channel_.get());
1172 TEST_F(WebSocketChannelDeletingTest, OnNotifyFinishOpeningHandshakeError) {
1173 scoped_ptr<ReadableFakeWebSocketStream> stream(
1174 new ReadableFakeWebSocketStream);
1175 static const InitFrame frames[] = {
1176 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1177 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1178 set_stream(stream.Pass());
1179 deleting_ = EVENT_ON_FINISH_OPENING_HANDSHAKE;
1181 CreateChannelAndConnectSuccessfully();
1182 ASSERT_TRUE(channel_);
1183 scoped_refptr<HttpResponseHeaders> response_headers(
1184 new HttpResponseHeaders(""));
1185 channel_->OnFinishOpeningHandshake(scoped_ptr<WebSocketHandshakeResponseInfo>(
1186 new WebSocketHandshakeResponseInfo(GURL("http://www.example.com/"),
1187 200,
1188 "OK",
1189 response_headers,
1190 base::Time())));
1191 base::MessageLoop::current()->RunUntilIdle();
1192 EXPECT_EQ(NULL, channel_.get());
1195 TEST_F(WebSocketChannelDeletingTest, FailChannelInSendFrame) {
1196 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1197 deleting_ = EVENT_ON_FAIL_CHANNEL;
1198 CreateChannelAndConnectSuccessfully();
1199 ASSERT_TRUE(channel_);
1200 channel_->SendFrame(true,
1201 WebSocketFrameHeader::kOpCodeText,
1202 std::vector<char>(kDefaultInitialQuota * 2, 'T'));
1203 EXPECT_EQ(NULL, channel_.get());
1206 TEST_F(WebSocketChannelDeletingTest, FailChannelInOnReadDone) {
1207 scoped_ptr<ReadableFakeWebSocketStream> stream(
1208 new ReadableFakeWebSocketStream);
1209 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1210 ERR_WS_PROTOCOL_ERROR);
1211 set_stream(stream.Pass());
1212 deleting_ = EVENT_ON_FAIL_CHANNEL;
1213 CreateChannelAndConnectSuccessfully();
1214 ASSERT_TRUE(channel_);
1215 base::MessageLoop::current()->RunUntilIdle();
1216 EXPECT_EQ(NULL, channel_.get());
1219 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToMaskedFrame) {
1220 scoped_ptr<ReadableFakeWebSocketStream> stream(
1221 new ReadableFakeWebSocketStream);
1222 static const InitFrame frames[] = {
1223 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1224 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1225 set_stream(stream.Pass());
1226 deleting_ = EVENT_ON_FAIL_CHANNEL;
1228 CreateChannelAndConnectSuccessfully();
1229 EXPECT_EQ(NULL, channel_.get());
1232 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToBadControlFrame) {
1233 scoped_ptr<ReadableFakeWebSocketStream> stream(
1234 new ReadableFakeWebSocketStream);
1235 static const InitFrame frames[] = {
1236 {FINAL_FRAME, 0xF, NOT_MASKED, ""}};
1237 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1238 set_stream(stream.Pass());
1239 deleting_ = EVENT_ON_FAIL_CHANNEL;
1241 CreateChannelAndConnectSuccessfully();
1242 EXPECT_EQ(NULL, channel_.get());
1245 // Version of above test with NULL data.
1246 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToBadControlFrameNull) {
1247 scoped_ptr<ReadableFakeWebSocketStream> stream(
1248 new ReadableFakeWebSocketStream);
1249 static const InitFrame frames[] = {
1250 {FINAL_FRAME, 0xF, NOT_MASKED, NULL}};
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, FailChannelDueToPongAfterClose) {
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, ""}};
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, FailChannelDueToPongAfterCloseNull) {
1275 scoped_ptr<ReadableFakeWebSocketStream> stream(
1276 new ReadableFakeWebSocketStream);
1277 static const InitFrame frames[] = {
1278 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
1279 CLOSE_DATA(NORMAL_CLOSURE, "Success")},
1280 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1281 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1282 set_stream(stream.Pass());
1283 deleting_ = EVENT_ON_FAIL_CHANNEL;
1285 CreateChannelAndConnectSuccessfully();
1286 EXPECT_EQ(NULL, channel_.get());
1289 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToUnknownOpCode) {
1290 scoped_ptr<ReadableFakeWebSocketStream> stream(
1291 new ReadableFakeWebSocketStream);
1292 static const InitFrame frames[] = {{FINAL_FRAME, 0x7, NOT_MASKED, ""}};
1293 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1294 set_stream(stream.Pass());
1295 deleting_ = EVENT_ON_FAIL_CHANNEL;
1297 CreateChannelAndConnectSuccessfully();
1298 EXPECT_EQ(NULL, channel_.get());
1301 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToUnknownOpCodeNull) {
1302 scoped_ptr<ReadableFakeWebSocketStream> stream(
1303 new ReadableFakeWebSocketStream);
1304 static const InitFrame frames[] = {{FINAL_FRAME, 0x7, NOT_MASKED, NULL}};
1305 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1306 set_stream(stream.Pass());
1307 deleting_ = EVENT_ON_FAIL_CHANNEL;
1309 CreateChannelAndConnectSuccessfully();
1310 EXPECT_EQ(NULL, channel_.get());
1313 TEST_F(WebSocketChannelDeletingTest, FailChannelDueInvalidCloseReason) {
1314 scoped_ptr<ReadableFakeWebSocketStream> stream(
1315 new ReadableFakeWebSocketStream);
1316 static const InitFrame frames[] = {
1317 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1318 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
1319 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1320 set_stream(stream.Pass());
1321 deleting_ = EVENT_ON_FAIL_CHANNEL;
1323 CreateChannelAndConnectSuccessfully();
1324 EXPECT_EQ(NULL, channel_.get());
1327 TEST_F(WebSocketChannelEventInterfaceTest, ConnectSuccessReported) {
1328 // false means success.
1329 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, "", ""));
1330 // OnFlowControl is always called immediately after connect to provide initial
1331 // quota to the renderer.
1332 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1334 CreateChannelAndConnect();
1336 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
1339 TEST_F(WebSocketChannelEventInterfaceTest, ConnectFailureReported) {
1340 EXPECT_CALL(*event_interface_, OnFailChannel("hello"));
1342 CreateChannelAndConnect();
1344 connect_data_.creator.connect_delegate->OnFailure("hello");
1347 TEST_F(WebSocketChannelEventInterfaceTest, NonWebSocketSchemeRejected) {
1348 EXPECT_CALL(*event_interface_, OnAddChannelResponse(true, "", ""));
1349 connect_data_.socket_url = GURL("http://www.google.com/");
1350 CreateChannelAndConnect();
1353 TEST_F(WebSocketChannelEventInterfaceTest, ProtocolPassed) {
1354 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, "Bob", ""));
1355 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1357 CreateChannelAndConnect();
1359 connect_data_.creator.connect_delegate->OnSuccess(
1360 scoped_ptr<WebSocketStream>(new FakeWebSocketStream("Bob", "")));
1363 TEST_F(WebSocketChannelEventInterfaceTest, ExtensionsPassed) {
1364 EXPECT_CALL(*event_interface_,
1365 OnAddChannelResponse(false, "", "extension1, extension2"));
1366 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1368 CreateChannelAndConnect();
1370 connect_data_.creator.connect_delegate->OnSuccess(scoped_ptr<WebSocketStream>(
1371 new FakeWebSocketStream("", "extension1, extension2")));
1374 // The first frames from the server can arrive together with the handshake, in
1375 // which case they will be available as soon as ReadFrames() is called the first
1376 // time.
1377 TEST_F(WebSocketChannelEventInterfaceTest, DataLeftFromHandshake) {
1378 scoped_ptr<ReadableFakeWebSocketStream> stream(
1379 new ReadableFakeWebSocketStream);
1380 static const InitFrame frames[] = {
1381 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1382 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1383 set_stream(stream.Pass());
1385 InSequence s;
1386 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1387 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1388 EXPECT_CALL(
1389 *event_interface_,
1390 OnDataFrame(
1391 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1394 CreateChannelAndConnectSuccessfully();
1397 // A remote server could accept the handshake, but then immediately send a
1398 // Close frame.
1399 TEST_F(WebSocketChannelEventInterfaceTest, CloseAfterHandshake) {
1400 scoped_ptr<ReadableFakeWebSocketStream> stream(
1401 new ReadableFakeWebSocketStream);
1402 static const InitFrame frames[] = {
1403 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1404 NOT_MASKED, CLOSE_DATA(SERVER_ERROR, "Internal Server Error")}};
1405 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1406 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1407 ERR_CONNECTION_CLOSED);
1408 set_stream(stream.Pass());
1410 InSequence s;
1411 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1412 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1413 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1414 EXPECT_CALL(
1415 *event_interface_,
1416 OnDropChannel(
1417 true, kWebSocketErrorInternalServerError, "Internal Server Error"));
1420 CreateChannelAndConnectSuccessfully();
1423 // A remote server could close the connection immediately after sending the
1424 // handshake response (most likely a bug in the server).
1425 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionCloseAfterHandshake) {
1426 scoped_ptr<ReadableFakeWebSocketStream> stream(
1427 new ReadableFakeWebSocketStream);
1428 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1429 ERR_CONNECTION_CLOSED);
1430 set_stream(stream.Pass());
1432 InSequence s;
1433 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1434 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1435 EXPECT_CALL(*event_interface_,
1436 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1439 CreateChannelAndConnectSuccessfully();
1442 TEST_F(WebSocketChannelEventInterfaceTest, NormalAsyncRead) {
1443 scoped_ptr<ReadableFakeWebSocketStream> stream(
1444 new ReadableFakeWebSocketStream);
1445 static const InitFrame frames[] = {
1446 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1447 // We use this checkpoint object to verify that the callback isn't called
1448 // until we expect it to be.
1449 Checkpoint checkpoint;
1450 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1451 set_stream(stream.Pass());
1453 InSequence s;
1454 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1455 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1456 EXPECT_CALL(checkpoint, Call(1));
1457 EXPECT_CALL(
1458 *event_interface_,
1459 OnDataFrame(
1460 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1461 EXPECT_CALL(checkpoint, Call(2));
1464 CreateChannelAndConnectSuccessfully();
1465 checkpoint.Call(1);
1466 base::MessageLoop::current()->RunUntilIdle();
1467 checkpoint.Call(2);
1470 // Extra data can arrive while a read is being processed, resulting in the next
1471 // read completing synchronously.
1472 TEST_F(WebSocketChannelEventInterfaceTest, AsyncThenSyncRead) {
1473 scoped_ptr<ReadableFakeWebSocketStream> stream(
1474 new ReadableFakeWebSocketStream);
1475 static const InitFrame frames1[] = {
1476 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1477 static const InitFrame frames2[] = {
1478 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "WORLD"}};
1479 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1480 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames2);
1481 set_stream(stream.Pass());
1483 InSequence s;
1484 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1485 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1486 EXPECT_CALL(
1487 *event_interface_,
1488 OnDataFrame(
1489 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1490 EXPECT_CALL(
1491 *event_interface_,
1492 OnDataFrame(
1493 true, WebSocketFrameHeader::kOpCodeText, AsVector("WORLD")));
1496 CreateChannelAndConnectSuccessfully();
1497 base::MessageLoop::current()->RunUntilIdle();
1500 // Data frames are delivered the same regardless of how many reads they arrive
1501 // as.
1502 TEST_F(WebSocketChannelEventInterfaceTest, FragmentedMessage) {
1503 scoped_ptr<ReadableFakeWebSocketStream> stream(
1504 new ReadableFakeWebSocketStream);
1505 // Here we have one message which arrived in five frames split across three
1506 // reads. It may have been reframed on arrival, but this class doesn't care
1507 // about that.
1508 static const InitFrame frames1[] = {
1509 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "THREE"},
1510 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1511 NOT_MASKED, " "}};
1512 static const InitFrame frames2[] = {
1513 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1514 NOT_MASKED, "SMALL"}};
1515 static const InitFrame frames3[] = {
1516 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1517 NOT_MASKED, " "},
1518 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1519 NOT_MASKED, "FRAMES"}};
1520 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1521 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1522 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1523 set_stream(stream.Pass());
1525 InSequence s;
1526 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1527 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1528 EXPECT_CALL(
1529 *event_interface_,
1530 OnDataFrame(
1531 false, WebSocketFrameHeader::kOpCodeText, AsVector("THREE")));
1532 EXPECT_CALL(
1533 *event_interface_,
1534 OnDataFrame(
1535 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1536 EXPECT_CALL(*event_interface_,
1537 OnDataFrame(false,
1538 WebSocketFrameHeader::kOpCodeContinuation,
1539 AsVector("SMALL")));
1540 EXPECT_CALL(
1541 *event_interface_,
1542 OnDataFrame(
1543 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1544 EXPECT_CALL(*event_interface_,
1545 OnDataFrame(true,
1546 WebSocketFrameHeader::kOpCodeContinuation,
1547 AsVector("FRAMES")));
1550 CreateChannelAndConnectSuccessfully();
1551 base::MessageLoop::current()->RunUntilIdle();
1554 // A message can consist of one frame with NULL payload.
1555 TEST_F(WebSocketChannelEventInterfaceTest, NullMessage) {
1556 scoped_ptr<ReadableFakeWebSocketStream> stream(
1557 new ReadableFakeWebSocketStream);
1558 static const InitFrame frames[] = {
1559 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, NULL}};
1560 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1561 set_stream(stream.Pass());
1562 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1563 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1564 EXPECT_CALL(
1565 *event_interface_,
1566 OnDataFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("")));
1567 CreateChannelAndConnectSuccessfully();
1570 // Connection closed by the remote host without a closing handshake.
1571 TEST_F(WebSocketChannelEventInterfaceTest, AsyncAbnormalClosure) {
1572 scoped_ptr<ReadableFakeWebSocketStream> stream(
1573 new ReadableFakeWebSocketStream);
1574 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1575 ERR_CONNECTION_CLOSED);
1576 set_stream(stream.Pass());
1578 InSequence s;
1579 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1580 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1581 EXPECT_CALL(*event_interface_,
1582 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1585 CreateChannelAndConnectSuccessfully();
1586 base::MessageLoop::current()->RunUntilIdle();
1589 // A connection reset should produce the same event as an unexpected closure.
1590 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionReset) {
1591 scoped_ptr<ReadableFakeWebSocketStream> stream(
1592 new ReadableFakeWebSocketStream);
1593 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1594 ERR_CONNECTION_RESET);
1595 set_stream(stream.Pass());
1597 InSequence s;
1598 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1599 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1600 EXPECT_CALL(*event_interface_,
1601 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1604 CreateChannelAndConnectSuccessfully();
1605 base::MessageLoop::current()->RunUntilIdle();
1608 // RFC6455 5.1 "A client MUST close a connection if it detects a masked frame."
1609 TEST_F(WebSocketChannelEventInterfaceTest, MaskedFramesAreRejected) {
1610 scoped_ptr<ReadableFakeWebSocketStream> stream(
1611 new ReadableFakeWebSocketStream);
1612 static const InitFrame frames[] = {
1613 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1615 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1616 set_stream(stream.Pass());
1618 InSequence s;
1619 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1620 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1621 EXPECT_CALL(
1622 *event_interface_,
1623 OnFailChannel(
1624 "A server must not mask any frames that it sends to the client."));
1627 CreateChannelAndConnectSuccessfully();
1628 base::MessageLoop::current()->RunUntilIdle();
1631 // RFC6455 5.2 "If an unknown opcode is received, the receiving endpoint MUST
1632 // _Fail the WebSocket Connection_."
1633 TEST_F(WebSocketChannelEventInterfaceTest, UnknownOpCodeIsRejected) {
1634 scoped_ptr<ReadableFakeWebSocketStream> stream(
1635 new ReadableFakeWebSocketStream);
1636 static const InitFrame frames[] = {{FINAL_FRAME, 4, NOT_MASKED, "HELLO"}};
1638 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1639 set_stream(stream.Pass());
1641 InSequence s;
1642 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1643 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1644 EXPECT_CALL(*event_interface_,
1645 OnFailChannel("Unrecognized frame opcode: 4"));
1648 CreateChannelAndConnectSuccessfully();
1649 base::MessageLoop::current()->RunUntilIdle();
1652 // RFC6455 5.4 "Control frames ... MAY be injected in the middle of a
1653 // fragmented message."
1654 TEST_F(WebSocketChannelEventInterfaceTest, ControlFrameInDataMessage) {
1655 scoped_ptr<ReadableFakeWebSocketStream> stream(
1656 new ReadableFakeWebSocketStream);
1657 // We have one message of type Text split into two frames. In the middle is a
1658 // control message of type Pong.
1659 static const InitFrame frames1[] = {
1660 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
1661 NOT_MASKED, "SPLIT "}};
1662 static const InitFrame frames2[] = {
1663 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1664 static const InitFrame frames3[] = {
1665 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1666 NOT_MASKED, "MESSAGE"}};
1667 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1668 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1669 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1670 set_stream(stream.Pass());
1672 InSequence s;
1673 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1674 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1675 EXPECT_CALL(
1676 *event_interface_,
1677 OnDataFrame(
1678 false, WebSocketFrameHeader::kOpCodeText, AsVector("SPLIT ")));
1679 EXPECT_CALL(*event_interface_,
1680 OnDataFrame(true,
1681 WebSocketFrameHeader::kOpCodeContinuation,
1682 AsVector("MESSAGE")));
1685 CreateChannelAndConnectSuccessfully();
1686 base::MessageLoop::current()->RunUntilIdle();
1689 // It seems redundant to repeat the entirety of the above test, so just test a
1690 // Pong with NULL data.
1691 TEST_F(WebSocketChannelEventInterfaceTest, PongWithNullData) {
1692 scoped_ptr<ReadableFakeWebSocketStream> stream(
1693 new ReadableFakeWebSocketStream);
1694 static const InitFrame frames[] = {
1695 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1696 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1697 set_stream(stream.Pass());
1698 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1699 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1701 CreateChannelAndConnectSuccessfully();
1702 base::MessageLoop::current()->RunUntilIdle();
1705 // If a frame has an invalid header, then the connection is closed and
1706 // subsequent frames must not trigger events.
1707 TEST_F(WebSocketChannelEventInterfaceTest, FrameAfterInvalidFrame) {
1708 scoped_ptr<ReadableFakeWebSocketStream> stream(
1709 new ReadableFakeWebSocketStream);
1710 static const InitFrame frames[] = {
1711 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"},
1712 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, " WORLD"}};
1714 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1715 set_stream(stream.Pass());
1717 InSequence s;
1718 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1719 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1720 EXPECT_CALL(
1721 *event_interface_,
1722 OnFailChannel(
1723 "A server must not mask any frames that it sends to the client."));
1726 CreateChannelAndConnectSuccessfully();
1727 base::MessageLoop::current()->RunUntilIdle();
1730 // If the renderer sends lots of small writes, we don't want to update the quota
1731 // for each one.
1732 TEST_F(WebSocketChannelEventInterfaceTest, SmallWriteDoesntUpdateQuota) {
1733 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1735 InSequence s;
1736 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1737 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1740 CreateChannelAndConnectSuccessfully();
1741 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("B"));
1744 // If we send enough to go below send_quota_low_water_mask_ we should get our
1745 // quota refreshed.
1746 TEST_F(WebSocketChannelEventInterfaceTest, LargeWriteUpdatesQuota) {
1747 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1748 // We use this checkpoint object to verify that the quota update comes after
1749 // the write.
1750 Checkpoint checkpoint;
1752 InSequence s;
1753 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1754 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1755 EXPECT_CALL(checkpoint, Call(1));
1756 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1757 EXPECT_CALL(checkpoint, Call(2));
1760 CreateChannelAndConnectSuccessfully();
1761 checkpoint.Call(1);
1762 channel_->SendFrame(true,
1763 WebSocketFrameHeader::kOpCodeText,
1764 std::vector<char>(kDefaultInitialQuota, 'B'));
1765 checkpoint.Call(2);
1768 // Verify that our quota actually is refreshed when we are told it is.
1769 TEST_F(WebSocketChannelEventInterfaceTest, QuotaReallyIsRefreshed) {
1770 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1771 Checkpoint checkpoint;
1773 InSequence s;
1774 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1775 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1776 EXPECT_CALL(checkpoint, Call(1));
1777 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1778 EXPECT_CALL(checkpoint, Call(2));
1779 // If quota was not really refreshed, we would get an OnDropChannel()
1780 // message.
1781 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1782 EXPECT_CALL(checkpoint, Call(3));
1785 CreateChannelAndConnectSuccessfully();
1786 checkpoint.Call(1);
1787 channel_->SendFrame(true,
1788 WebSocketFrameHeader::kOpCodeText,
1789 std::vector<char>(kDefaultQuotaRefreshTrigger, 'D'));
1790 checkpoint.Call(2);
1791 // We should have received more quota at this point.
1792 channel_->SendFrame(true,
1793 WebSocketFrameHeader::kOpCodeText,
1794 std::vector<char>(kDefaultQuotaRefreshTrigger, 'E'));
1795 checkpoint.Call(3);
1798 // If we send more than the available quota then the connection will be closed
1799 // with an error.
1800 TEST_F(WebSocketChannelEventInterfaceTest, WriteOverQuotaIsRejected) {
1801 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1803 InSequence s;
1804 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1805 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
1806 EXPECT_CALL(*event_interface_, OnFailChannel("Send quota exceeded"));
1809 CreateChannelAndConnectSuccessfully();
1810 channel_->SendFrame(true,
1811 WebSocketFrameHeader::kOpCodeText,
1812 std::vector<char>(kDefaultInitialQuota + 1, 'C'));
1815 // If a write fails, the channel is dropped.
1816 TEST_F(WebSocketChannelEventInterfaceTest, FailedWrite) {
1817 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
1818 Checkpoint checkpoint;
1820 InSequence s;
1821 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1822 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1823 EXPECT_CALL(checkpoint, Call(1));
1824 EXPECT_CALL(*event_interface_,
1825 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1826 EXPECT_CALL(checkpoint, Call(2));
1829 CreateChannelAndConnectSuccessfully();
1830 checkpoint.Call(1);
1832 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("H"));
1833 checkpoint.Call(2);
1836 // OnDropChannel() is called exactly once when StartClosingHandshake() is used.
1837 TEST_F(WebSocketChannelEventInterfaceTest, SendCloseDropsChannel) {
1838 set_stream(make_scoped_ptr(new EchoeyFakeWebSocketStream));
1840 InSequence s;
1841 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1842 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1843 EXPECT_CALL(*event_interface_,
1844 OnDropChannel(true, kWebSocketNormalClosure, "Fred"));
1847 CreateChannelAndConnectSuccessfully();
1849 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Fred");
1850 base::MessageLoop::current()->RunUntilIdle();
1853 // StartClosingHandshake() also works before connection completes, and calls
1854 // OnDropChannel.
1855 TEST_F(WebSocketChannelEventInterfaceTest, CloseDuringConnection) {
1856 EXPECT_CALL(*event_interface_,
1857 OnDropChannel(false, kWebSocketErrorAbnormalClosure, ""));
1859 CreateChannelAndConnect();
1860 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Joe");
1863 // OnDropChannel() is only called once when a write() on the socket triggers a
1864 // connection reset.
1865 TEST_F(WebSocketChannelEventInterfaceTest, OnDropChannelCalledOnce) {
1866 set_stream(make_scoped_ptr(new ResetOnWriteFakeWebSocketStream));
1867 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1868 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1870 EXPECT_CALL(*event_interface_,
1871 OnDropChannel(false, kWebSocketErrorAbnormalClosure, ""))
1872 .Times(1);
1874 CreateChannelAndConnectSuccessfully();
1876 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("yt?"));
1877 base::MessageLoop::current()->RunUntilIdle();
1880 // When the remote server sends a Close frame with an empty payload,
1881 // WebSocketChannel should report code 1005, kWebSocketErrorNoStatusReceived.
1882 TEST_F(WebSocketChannelEventInterfaceTest, CloseWithNoPayloadGivesStatus1005) {
1883 scoped_ptr<ReadableFakeWebSocketStream> stream(
1884 new ReadableFakeWebSocketStream);
1885 static const InitFrame frames[] = {
1886 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
1887 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1888 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1889 ERR_CONNECTION_CLOSED);
1890 set_stream(stream.Pass());
1891 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1892 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1893 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1894 EXPECT_CALL(*event_interface_,
1895 OnDropChannel(true, kWebSocketErrorNoStatusReceived, _));
1897 CreateChannelAndConnectSuccessfully();
1900 // A version of the above test with NULL payload.
1901 TEST_F(WebSocketChannelEventInterfaceTest,
1902 CloseWithNullPayloadGivesStatus1005) {
1903 scoped_ptr<ReadableFakeWebSocketStream> stream(
1904 new ReadableFakeWebSocketStream);
1905 static const InitFrame frames[] = {
1906 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, NULL}};
1907 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1908 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1909 ERR_CONNECTION_CLOSED);
1910 set_stream(stream.Pass());
1911 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1912 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1913 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1914 EXPECT_CALL(*event_interface_,
1915 OnDropChannel(true, kWebSocketErrorNoStatusReceived, _));
1917 CreateChannelAndConnectSuccessfully();
1920 // If ReadFrames() returns ERR_WS_PROTOCOL_ERROR, then the connection must be
1921 // failed.
1922 TEST_F(WebSocketChannelEventInterfaceTest, SyncProtocolErrorGivesStatus1002) {
1923 scoped_ptr<ReadableFakeWebSocketStream> stream(
1924 new ReadableFakeWebSocketStream);
1925 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1926 ERR_WS_PROTOCOL_ERROR);
1927 set_stream(stream.Pass());
1928 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1929 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1931 EXPECT_CALL(*event_interface_, OnFailChannel("Invalid frame header"));
1933 CreateChannelAndConnectSuccessfully();
1936 // Async version of above test.
1937 TEST_F(WebSocketChannelEventInterfaceTest, AsyncProtocolErrorGivesStatus1002) {
1938 scoped_ptr<ReadableFakeWebSocketStream> stream(
1939 new ReadableFakeWebSocketStream);
1940 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1941 ERR_WS_PROTOCOL_ERROR);
1942 set_stream(stream.Pass());
1943 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1944 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1946 EXPECT_CALL(*event_interface_, OnFailChannel("Invalid frame header"));
1948 CreateChannelAndConnectSuccessfully();
1949 base::MessageLoop::current()->RunUntilIdle();
1952 TEST_F(WebSocketChannelEventInterfaceTest, StartHandshakeRequest) {
1954 InSequence s;
1955 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1956 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1957 EXPECT_CALL(*event_interface_, OnStartOpeningHandshakeCalled());
1960 CreateChannelAndConnectSuccessfully();
1962 scoped_ptr<WebSocketHandshakeRequestInfo> request_info(
1963 new WebSocketHandshakeRequestInfo(GURL("ws://www.example.com/"),
1964 base::Time()));
1965 connect_data_.creator.connect_delegate->OnStartOpeningHandshake(
1966 request_info.Pass());
1968 base::MessageLoop::current()->RunUntilIdle();
1971 TEST_F(WebSocketChannelEventInterfaceTest, FinishHandshakeRequest) {
1973 InSequence s;
1974 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1975 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1976 EXPECT_CALL(*event_interface_, OnFinishOpeningHandshakeCalled());
1979 CreateChannelAndConnectSuccessfully();
1981 scoped_refptr<HttpResponseHeaders> response_headers(
1982 new HttpResponseHeaders(""));
1983 scoped_ptr<WebSocketHandshakeResponseInfo> response_info(
1984 new WebSocketHandshakeResponseInfo(GURL("ws://www.example.com/"),
1985 200,
1986 "OK",
1987 response_headers,
1988 base::Time()));
1989 connect_data_.creator.connect_delegate->OnFinishOpeningHandshake(
1990 response_info.Pass());
1991 base::MessageLoop::current()->RunUntilIdle();
1994 TEST_F(WebSocketChannelEventInterfaceTest, FailJustAfterHandshake) {
1996 InSequence s;
1997 EXPECT_CALL(*event_interface_, OnStartOpeningHandshakeCalled());
1998 EXPECT_CALL(*event_interface_, OnFinishOpeningHandshakeCalled());
1999 EXPECT_CALL(*event_interface_, OnFailChannel("bye"));
2002 CreateChannelAndConnect();
2004 WebSocketStream::ConnectDelegate* connect_delegate =
2005 connect_data_.creator.connect_delegate.get();
2006 GURL url("ws://www.example.com/");
2007 scoped_ptr<WebSocketHandshakeRequestInfo> request_info(
2008 new WebSocketHandshakeRequestInfo(url, base::Time()));
2009 scoped_refptr<HttpResponseHeaders> response_headers(
2010 new HttpResponseHeaders(""));
2011 scoped_ptr<WebSocketHandshakeResponseInfo> response_info(
2012 new WebSocketHandshakeResponseInfo(url,
2013 200,
2014 "OK",
2015 response_headers,
2016 base::Time()));
2017 connect_delegate->OnStartOpeningHandshake(request_info.Pass());
2018 connect_delegate->OnFinishOpeningHandshake(response_info.Pass());
2020 connect_delegate->OnFailure("bye");
2021 base::MessageLoop::current()->RunUntilIdle();
2024 // Any frame after close is invalid. This test uses a Text frame. See also
2025 // test "PingAfterCloseIfRejected".
2026 TEST_F(WebSocketChannelEventInterfaceTest, DataAfterCloseIsRejected) {
2027 scoped_ptr<ReadableFakeWebSocketStream> stream(
2028 new ReadableFakeWebSocketStream);
2029 static const InitFrame frames[] = {
2030 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
2031 CLOSE_DATA(NORMAL_CLOSURE, "OK")},
2032 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "Payload"}};
2033 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2034 set_stream(stream.Pass());
2035 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2036 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2039 InSequence s;
2040 EXPECT_CALL(*event_interface_, OnClosingHandshake());
2041 EXPECT_CALL(*event_interface_,
2042 OnFailChannel("Data frame received after close"));
2045 CreateChannelAndConnectSuccessfully();
2048 // A Close frame with a one-byte payload elicits a specific console error
2049 // message.
2050 TEST_F(WebSocketChannelEventInterfaceTest, OneByteClosePayloadMessage) {
2051 scoped_ptr<ReadableFakeWebSocketStream> stream(
2052 new ReadableFakeWebSocketStream);
2053 static const InitFrame frames[] = {
2054 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, "\x03"}};
2055 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2056 set_stream(stream.Pass());
2057 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2058 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2059 EXPECT_CALL(
2060 *event_interface_,
2061 OnFailChannel(
2062 "Received a broken close frame containing an invalid size body."));
2064 CreateChannelAndConnectSuccessfully();
2067 // A Close frame with a reserved status code also elicits a specific console
2068 // error message.
2069 TEST_F(WebSocketChannelEventInterfaceTest, ClosePayloadReservedStatusMessage) {
2070 scoped_ptr<ReadableFakeWebSocketStream> stream(
2071 new ReadableFakeWebSocketStream);
2072 static const InitFrame frames[] = {
2073 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2074 NOT_MASKED, CLOSE_DATA(ABNORMAL_CLOSURE, "Not valid on wire")}};
2075 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2076 set_stream(stream.Pass());
2077 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2078 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2079 EXPECT_CALL(
2080 *event_interface_,
2081 OnFailChannel(
2082 "Received a broken close frame containing a reserved status code."));
2084 CreateChannelAndConnectSuccessfully();
2087 // A Close frame with invalid UTF-8 also elicits a specific console error
2088 // message.
2089 TEST_F(WebSocketChannelEventInterfaceTest, ClosePayloadInvalidReason) {
2090 scoped_ptr<ReadableFakeWebSocketStream> stream(
2091 new ReadableFakeWebSocketStream);
2092 static const InitFrame frames[] = {
2093 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2094 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
2095 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2096 set_stream(stream.Pass());
2097 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2098 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2099 EXPECT_CALL(
2100 *event_interface_,
2101 OnFailChannel(
2102 "Received a broken close frame containing invalid UTF-8."));
2104 CreateChannelAndConnectSuccessfully();
2107 // The reserved bits must all be clear on received frames. Extensions should
2108 // clear the bits when they are set correctly before passing on the frame.
2109 TEST_F(WebSocketChannelEventInterfaceTest, ReservedBitsMustNotBeSet) {
2110 scoped_ptr<ReadableFakeWebSocketStream> stream(
2111 new ReadableFakeWebSocketStream);
2112 static const InitFrame frames[] = {
2113 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2114 NOT_MASKED, "sakana"}};
2115 // It is not worth adding support for reserved bits to InitFrame just for this
2116 // one test, so set the bit manually.
2117 ScopedVector<WebSocketFrame> raw_frames = CreateFrameVector(frames);
2118 raw_frames[0]->header.reserved1 = true;
2119 stream->PrepareRawReadFrames(
2120 ReadableFakeWebSocketStream::SYNC, OK, raw_frames.Pass());
2121 set_stream(stream.Pass());
2122 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2123 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2124 EXPECT_CALL(*event_interface_,
2125 OnFailChannel(
2126 "One or more reserved bits are on: reserved1 = 1, "
2127 "reserved2 = 0, reserved3 = 0"));
2129 CreateChannelAndConnectSuccessfully();
2132 // The closing handshake times out and sends an OnDropChannel event if no
2133 // response to the client Close message is received.
2134 TEST_F(WebSocketChannelEventInterfaceTest,
2135 ClientInitiatedClosingHandshakeTimesOut) {
2136 scoped_ptr<ReadableFakeWebSocketStream> stream(
2137 new ReadableFakeWebSocketStream);
2138 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
2139 ERR_IO_PENDING);
2140 set_stream(stream.Pass());
2141 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2142 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2143 // This checkpoint object verifies that the OnDropChannel message comes after
2144 // the timeout.
2145 Checkpoint checkpoint;
2146 TestClosure completion;
2148 InSequence s;
2149 EXPECT_CALL(checkpoint, Call(1));
2150 EXPECT_CALL(*event_interface_,
2151 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _))
2152 .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
2154 CreateChannelAndConnectSuccessfully();
2155 // OneShotTimer is not very friendly to testing; there is no apparent way to
2156 // set an expectation on it. Instead the tests need to infer that the timeout
2157 // was fired by the behaviour of the WebSocketChannel object.
2158 channel_->SetClosingHandshakeTimeoutForTesting(
2159 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2160 channel_->StartClosingHandshake(kWebSocketNormalClosure, "");
2161 checkpoint.Call(1);
2162 completion.WaitForResult();
2165 // The closing handshake times out and sends an OnDropChannel event if a Close
2166 // message is received but the connection isn't closed by the remote host.
2167 TEST_F(WebSocketChannelEventInterfaceTest,
2168 ServerInitiatedClosingHandshakeTimesOut) {
2169 scoped_ptr<ReadableFakeWebSocketStream> stream(
2170 new ReadableFakeWebSocketStream);
2171 static const InitFrame frames[] = {
2172 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2173 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2174 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
2175 set_stream(stream.Pass());
2176 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2177 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2178 Checkpoint checkpoint;
2179 TestClosure completion;
2181 InSequence s;
2182 EXPECT_CALL(checkpoint, Call(1));
2183 EXPECT_CALL(*event_interface_, OnClosingHandshake());
2184 EXPECT_CALL(*event_interface_,
2185 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _))
2186 .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
2188 CreateChannelAndConnectSuccessfully();
2189 channel_->SetClosingHandshakeTimeoutForTesting(
2190 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2191 checkpoint.Call(1);
2192 completion.WaitForResult();
2195 // The renderer should provide us with some quota immediately, and then
2196 // WebSocketChannel calls ReadFrames as soon as the stream is available.
2197 TEST_F(WebSocketChannelStreamTest, FlowControlEarly) {
2198 Checkpoint checkpoint;
2199 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2200 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2202 InSequence s;
2203 EXPECT_CALL(checkpoint, Call(1));
2204 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2205 .WillOnce(Return(ERR_IO_PENDING));
2206 EXPECT_CALL(checkpoint, Call(2));
2209 set_stream(mock_stream_.Pass());
2210 CreateChannelAndConnect();
2211 channel_->SendFlowControl(kPlentyOfQuota);
2212 checkpoint.Call(1);
2213 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2214 checkpoint.Call(2);
2217 // If for some reason the connect succeeds before the renderer sends us quota,
2218 // we shouldn't call ReadFrames() immediately.
2219 // TODO(ricea): Actually we should call ReadFrames() with a small limit so we
2220 // can still handle control frames. This should be done once we have any API to
2221 // expose quota to the lower levels.
2222 TEST_F(WebSocketChannelStreamTest, FlowControlLate) {
2223 Checkpoint checkpoint;
2224 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2225 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2227 InSequence s;
2228 EXPECT_CALL(checkpoint, Call(1));
2229 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2230 .WillOnce(Return(ERR_IO_PENDING));
2231 EXPECT_CALL(checkpoint, Call(2));
2234 set_stream(mock_stream_.Pass());
2235 CreateChannelAndConnect();
2236 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2237 checkpoint.Call(1);
2238 channel_->SendFlowControl(kPlentyOfQuota);
2239 checkpoint.Call(2);
2242 // We should stop calling ReadFrames() when all quota is used.
2243 TEST_F(WebSocketChannelStreamTest, FlowControlStopsReadFrames) {
2244 static const InitFrame frames[] = {
2245 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "FOUR"}};
2247 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2248 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2249 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2250 .WillOnce(ReturnFrames(&frames));
2252 set_stream(mock_stream_.Pass());
2253 CreateChannelAndConnect();
2254 channel_->SendFlowControl(4);
2255 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2258 // Providing extra quota causes ReadFrames() to be called again.
2259 TEST_F(WebSocketChannelStreamTest, FlowControlStartsWithMoreQuota) {
2260 static const InitFrame frames[] = {
2261 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "FOUR"}};
2262 Checkpoint checkpoint;
2264 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2265 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2267 InSequence s;
2268 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2269 .WillOnce(ReturnFrames(&frames));
2270 EXPECT_CALL(checkpoint, Call(1));
2271 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2272 .WillOnce(Return(ERR_IO_PENDING));
2275 set_stream(mock_stream_.Pass());
2276 CreateChannelAndConnect();
2277 channel_->SendFlowControl(4);
2278 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2279 checkpoint.Call(1);
2280 channel_->SendFlowControl(4);
2283 // ReadFrames() isn't called again until all pending data has been passed to
2284 // the renderer.
2285 TEST_F(WebSocketChannelStreamTest, ReadFramesNotCalledUntilQuotaAvailable) {
2286 static const InitFrame frames[] = {
2287 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "FOUR"}};
2288 Checkpoint checkpoint;
2290 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2291 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2293 InSequence s;
2294 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2295 .WillOnce(ReturnFrames(&frames));
2296 EXPECT_CALL(checkpoint, Call(1));
2297 EXPECT_CALL(checkpoint, Call(2));
2298 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2299 .WillOnce(Return(ERR_IO_PENDING));
2302 set_stream(mock_stream_.Pass());
2303 CreateChannelAndConnect();
2304 channel_->SendFlowControl(2);
2305 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2306 checkpoint.Call(1);
2307 channel_->SendFlowControl(2);
2308 checkpoint.Call(2);
2309 channel_->SendFlowControl(2);
2312 // A message that needs to be split into frames to fit within quota should
2313 // maintain correct semantics.
2314 TEST_F(WebSocketChannelFlowControlTest, SingleFrameMessageSplitSync) {
2315 scoped_ptr<ReadableFakeWebSocketStream> stream(
2316 new ReadableFakeWebSocketStream);
2317 static const InitFrame frames[] = {
2318 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "FOUR"}};
2319 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2320 set_stream(stream.Pass());
2322 InSequence s;
2323 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2324 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2325 EXPECT_CALL(
2326 *event_interface_,
2327 OnDataFrame(false, WebSocketFrameHeader::kOpCodeText, AsVector("FO")));
2328 EXPECT_CALL(
2329 *event_interface_,
2330 OnDataFrame(
2331 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector("U")));
2332 EXPECT_CALL(
2333 *event_interface_,
2334 OnDataFrame(
2335 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("R")));
2338 CreateChannelAndConnectWithQuota(2);
2339 channel_->SendFlowControl(1);
2340 channel_->SendFlowControl(1);
2343 // The code path for async messages is slightly different, so test it
2344 // separately.
2345 TEST_F(WebSocketChannelFlowControlTest, SingleFrameMessageSplitAsync) {
2346 scoped_ptr<ReadableFakeWebSocketStream> stream(
2347 new ReadableFakeWebSocketStream);
2348 static const InitFrame frames[] = {
2349 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "FOUR"}};
2350 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
2351 set_stream(stream.Pass());
2352 Checkpoint checkpoint;
2354 InSequence s;
2355 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2356 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2357 EXPECT_CALL(checkpoint, Call(1));
2358 EXPECT_CALL(
2359 *event_interface_,
2360 OnDataFrame(false, WebSocketFrameHeader::kOpCodeText, AsVector("FO")));
2361 EXPECT_CALL(checkpoint, Call(2));
2362 EXPECT_CALL(
2363 *event_interface_,
2364 OnDataFrame(
2365 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector("U")));
2366 EXPECT_CALL(checkpoint, Call(3));
2367 EXPECT_CALL(
2368 *event_interface_,
2369 OnDataFrame(
2370 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("R")));
2373 CreateChannelAndConnectWithQuota(2);
2374 checkpoint.Call(1);
2375 base::MessageLoop::current()->RunUntilIdle();
2376 checkpoint.Call(2);
2377 channel_->SendFlowControl(1);
2378 checkpoint.Call(3);
2379 channel_->SendFlowControl(1);
2382 // A message split into multiple frames which is further split due to quota
2383 // restrictions should stil be correct.
2384 // TODO(ricea): The message ends up split into more frames than are strictly
2385 // necessary. The complexity/performance tradeoffs here need further
2386 // examination.
2387 TEST_F(WebSocketChannelFlowControlTest, MultipleFrameSplit) {
2388 scoped_ptr<ReadableFakeWebSocketStream> stream(
2389 new ReadableFakeWebSocketStream);
2390 static const InitFrame frames[] = {
2391 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2392 NOT_MASKED, "FIRST FRAME IS 25 BYTES. "},
2393 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2394 NOT_MASKED, "SECOND FRAME IS 26 BYTES. "},
2395 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2396 NOT_MASKED, "FINAL FRAME IS 24 BYTES."}};
2397 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2398 set_stream(stream.Pass());
2400 InSequence s;
2401 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2402 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2403 EXPECT_CALL(*event_interface_,
2404 OnDataFrame(false,
2405 WebSocketFrameHeader::kOpCodeText,
2406 AsVector("FIRST FRAME IS")));
2407 EXPECT_CALL(*event_interface_,
2408 OnDataFrame(false,
2409 WebSocketFrameHeader::kOpCodeContinuation,
2410 AsVector(" 25 BYTES. ")));
2411 EXPECT_CALL(*event_interface_,
2412 OnDataFrame(false,
2413 WebSocketFrameHeader::kOpCodeContinuation,
2414 AsVector("SECOND FRAME IS 26 BYTES. ")));
2415 EXPECT_CALL(*event_interface_,
2416 OnDataFrame(false,
2417 WebSocketFrameHeader::kOpCodeContinuation,
2418 AsVector("FINAL ")));
2419 EXPECT_CALL(*event_interface_,
2420 OnDataFrame(true,
2421 WebSocketFrameHeader::kOpCodeContinuation,
2422 AsVector("FRAME IS 24 BYTES.")));
2424 CreateChannelAndConnectWithQuota(14);
2425 channel_->SendFlowControl(43);
2426 channel_->SendFlowControl(32);
2429 // An empty message handled when we are out of quota must not be delivered
2430 // out-of-order with respect to other messages.
2431 TEST_F(WebSocketChannelFlowControlTest, EmptyMessageNoQuota) {
2432 scoped_ptr<ReadableFakeWebSocketStream> stream(
2433 new ReadableFakeWebSocketStream);
2434 static const InitFrame frames[] = {
2435 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2436 NOT_MASKED, "FIRST MESSAGE"},
2437 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2438 NOT_MASKED, NULL},
2439 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2440 NOT_MASKED, "THIRD MESSAGE"}};
2441 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2442 set_stream(stream.Pass());
2444 InSequence s;
2445 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2446 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2447 EXPECT_CALL(*event_interface_,
2448 OnDataFrame(false,
2449 WebSocketFrameHeader::kOpCodeText,
2450 AsVector("FIRST ")));
2451 EXPECT_CALL(*event_interface_,
2452 OnDataFrame(true,
2453 WebSocketFrameHeader::kOpCodeContinuation,
2454 AsVector("MESSAGE")));
2455 EXPECT_CALL(*event_interface_,
2456 OnDataFrame(true,
2457 WebSocketFrameHeader::kOpCodeText,
2458 AsVector("")));
2459 EXPECT_CALL(*event_interface_,
2460 OnDataFrame(true,
2461 WebSocketFrameHeader::kOpCodeText,
2462 AsVector("THIRD MESSAGE")));
2465 CreateChannelAndConnectWithQuota(6);
2466 channel_->SendFlowControl(128);
2469 // RFC6455 5.1 "a client MUST mask all frames that it sends to the server".
2470 // WebSocketChannel actually only sets the mask bit in the header, it doesn't
2471 // perform masking itself (not all transports actually use masking).
2472 TEST_F(WebSocketChannelStreamTest, SentFramesAreMasked) {
2473 static const InitFrame expected[] = {
2474 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2475 MASKED, "NEEDS MASKING"}};
2476 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2477 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2478 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2479 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2480 .WillOnce(Return(OK));
2482 CreateChannelAndConnectSuccessfully();
2483 channel_->SendFrame(
2484 true, WebSocketFrameHeader::kOpCodeText, AsVector("NEEDS MASKING"));
2487 // RFC6455 5.5.1 "The application MUST NOT send any more data frames after
2488 // sending a Close frame."
2489 TEST_F(WebSocketChannelStreamTest, NothingIsSentAfterClose) {
2490 static const InitFrame expected[] = {
2491 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2492 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
2493 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2494 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2495 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2496 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2497 .WillOnce(Return(OK));
2499 CreateChannelAndConnectSuccessfully();
2500 channel_->StartClosingHandshake(1000, "Success");
2501 channel_->SendFrame(
2502 true, WebSocketFrameHeader::kOpCodeText, AsVector("SHOULD BE IGNORED"));
2505 // RFC6455 5.5.1 "If an endpoint receives a Close frame and did not previously
2506 // send a Close frame, the endpoint MUST send a Close frame in response."
2507 TEST_F(WebSocketChannelStreamTest, CloseIsEchoedBack) {
2508 static const InitFrame frames[] = {
2509 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2510 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2511 static const InitFrame expected[] = {
2512 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2513 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2514 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2515 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2516 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2517 .WillOnce(ReturnFrames(&frames))
2518 .WillRepeatedly(Return(ERR_IO_PENDING));
2519 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2520 .WillOnce(Return(OK));
2522 CreateChannelAndConnectSuccessfully();
2525 // The converse of the above case; after sending a Close frame, we should not
2526 // send another one.
2527 TEST_F(WebSocketChannelStreamTest, CloseOnlySentOnce) {
2528 static const InitFrame expected[] = {
2529 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2530 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2531 static const InitFrame frames_init[] = {
2532 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2533 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2535 // We store the parameters that were passed to ReadFrames() so that we can
2536 // call them explicitly later.
2537 CompletionCallback read_callback;
2538 ScopedVector<WebSocketFrame>* frames = NULL;
2540 // These are not interesting.
2541 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2542 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2544 // Use a checkpoint to make the ordering of events clearer.
2545 Checkpoint checkpoint;
2547 InSequence s;
2548 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2549 .WillOnce(DoAll(SaveArg<0>(&frames),
2550 SaveArg<1>(&read_callback),
2551 Return(ERR_IO_PENDING)));
2552 EXPECT_CALL(checkpoint, Call(1));
2553 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2554 .WillOnce(Return(OK));
2555 EXPECT_CALL(checkpoint, Call(2));
2556 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2557 .WillOnce(Return(ERR_IO_PENDING));
2558 EXPECT_CALL(checkpoint, Call(3));
2559 // WriteFrames() must not be called again. GoogleMock will ensure that the
2560 // test fails if it is.
2563 CreateChannelAndConnectSuccessfully();
2564 checkpoint.Call(1);
2565 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Close");
2566 checkpoint.Call(2);
2568 *frames = CreateFrameVector(frames_init);
2569 read_callback.Run(OK);
2570 checkpoint.Call(3);
2573 // Invalid close status codes should not be sent on the network.
2574 TEST_F(WebSocketChannelStreamTest, InvalidCloseStatusCodeNotSent) {
2575 static const InitFrame expected[] = {
2576 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2577 MASKED, CLOSE_DATA(SERVER_ERROR, "")}};
2579 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2580 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2581 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2582 .WillOnce(Return(ERR_IO_PENDING));
2584 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
2586 CreateChannelAndConnectSuccessfully();
2587 channel_->StartClosingHandshake(999, "");
2590 // A Close frame with a reason longer than 123 bytes cannot be sent on the
2591 // network.
2592 TEST_F(WebSocketChannelStreamTest, LongCloseReasonNotSent) {
2593 static const InitFrame expected[] = {
2594 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2595 MASKED, CLOSE_DATA(SERVER_ERROR, "")}};
2597 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2598 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2599 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2600 .WillOnce(Return(ERR_IO_PENDING));
2602 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
2604 CreateChannelAndConnectSuccessfully();
2605 channel_->StartClosingHandshake(1000, std::string(124, 'A'));
2608 // We generate code 1005, kWebSocketErrorNoStatusReceived, when there is no
2609 // status in the Close message from the other side. Code 1005 is not allowed to
2610 // appear on the wire, so we should not echo it back. See test
2611 // CloseWithNoPayloadGivesStatus1005, above, for confirmation that code 1005 is
2612 // correctly generated internally.
2613 TEST_F(WebSocketChannelStreamTest, Code1005IsNotEchoed) {
2614 static const InitFrame frames[] = {
2615 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
2616 static const InitFrame expected[] = {
2617 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED, ""}};
2618 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2619 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2620 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2621 .WillOnce(ReturnFrames(&frames))
2622 .WillRepeatedly(Return(ERR_IO_PENDING));
2623 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2624 .WillOnce(Return(OK));
2626 CreateChannelAndConnectSuccessfully();
2629 TEST_F(WebSocketChannelStreamTest, Code1005IsNotEchoedNull) {
2630 static const InitFrame frames[] = {
2631 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, NULL}};
2632 static const InitFrame expected[] = {
2633 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED, ""}};
2634 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2635 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2636 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2637 .WillOnce(ReturnFrames(&frames))
2638 .WillRepeatedly(Return(ERR_IO_PENDING));
2639 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2640 .WillOnce(Return(OK));
2642 CreateChannelAndConnectSuccessfully();
2645 // Receiving an invalid UTF-8 payload in a Close frame causes us to fail the
2646 // connection.
2647 TEST_F(WebSocketChannelStreamTest, CloseFrameInvalidUtf8) {
2648 static const InitFrame frames[] = {
2649 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2650 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
2651 static const InitFrame expected[] = {
2652 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2653 MASKED, CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in Close frame")}};
2655 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2656 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2657 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2658 .WillOnce(ReturnFrames(&frames))
2659 .WillRepeatedly(Return(ERR_IO_PENDING));
2660 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2661 .WillOnce(Return(OK));
2662 EXPECT_CALL(*mock_stream_, Close());
2664 CreateChannelAndConnectSuccessfully();
2667 // RFC6455 5.5.2 "Upon receipt of a Ping frame, an endpoint MUST send a Pong
2668 // frame in response"
2669 // 5.5.3 "A Pong frame sent in response to a Ping frame must have identical
2670 // "Application data" as found in the message body of the Ping frame being
2671 // replied to."
2672 TEST_F(WebSocketChannelStreamTest, PingRepliedWithPong) {
2673 static const InitFrame frames[] = {
2674 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2675 NOT_MASKED, "Application data"}};
2676 static const InitFrame expected[] = {
2677 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
2678 MASKED, "Application data"}};
2679 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2680 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2681 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2682 .WillOnce(ReturnFrames(&frames))
2683 .WillRepeatedly(Return(ERR_IO_PENDING));
2684 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2685 .WillOnce(Return(OK));
2687 CreateChannelAndConnectSuccessfully();
2690 // A ping with a NULL payload should be responded to with a Pong with a NULL
2691 // payload.
2692 TEST_F(WebSocketChannelStreamTest, NullPingRepliedWithNullPong) {
2693 static const InitFrame frames[] = {
2694 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing, NOT_MASKED, NULL}};
2695 static const InitFrame expected[] = {
2696 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, MASKED, NULL}};
2697 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2698 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2699 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2700 .WillOnce(ReturnFrames(&frames))
2701 .WillRepeatedly(Return(ERR_IO_PENDING));
2702 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2703 .WillOnce(Return(OK));
2705 CreateChannelAndConnectSuccessfully();
2708 TEST_F(WebSocketChannelStreamTest, PongInTheMiddleOfDataMessage) {
2709 static const InitFrame frames[] = {
2710 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2711 NOT_MASKED, "Application data"}};
2712 static const InitFrame expected1[] = {
2713 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
2714 static const InitFrame expected2[] = {
2715 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
2716 MASKED, "Application data"}};
2717 static const InitFrame expected3[] = {
2718 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2719 MASKED, "World"}};
2720 ScopedVector<WebSocketFrame>* read_frames;
2721 CompletionCallback read_callback;
2722 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2723 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2724 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2725 .WillOnce(DoAll(SaveArg<0>(&read_frames),
2726 SaveArg<1>(&read_callback),
2727 Return(ERR_IO_PENDING)))
2728 .WillRepeatedly(Return(ERR_IO_PENDING));
2730 InSequence s;
2732 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2733 .WillOnce(Return(OK));
2734 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2735 .WillOnce(Return(OK));
2736 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected3), _))
2737 .WillOnce(Return(OK));
2740 CreateChannelAndConnectSuccessfully();
2741 channel_->SendFrame(
2742 false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
2743 *read_frames = CreateFrameVector(frames);
2744 read_callback.Run(OK);
2745 channel_->SendFrame(
2746 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("World"));
2749 // WriteFrames() may not be called until the previous write has completed.
2750 // WebSocketChannel must buffer writes that happen in the meantime.
2751 TEST_F(WebSocketChannelStreamTest, WriteFramesOneAtATime) {
2752 static const InitFrame expected1[] = {
2753 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
2754 static const InitFrame expected2[] = {
2755 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "World"}};
2756 CompletionCallback write_callback;
2757 Checkpoint checkpoint;
2759 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2760 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2761 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2763 InSequence s;
2764 EXPECT_CALL(checkpoint, Call(1));
2765 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2766 .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
2767 EXPECT_CALL(checkpoint, Call(2));
2768 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2769 .WillOnce(Return(ERR_IO_PENDING));
2770 EXPECT_CALL(checkpoint, Call(3));
2773 CreateChannelAndConnectSuccessfully();
2774 checkpoint.Call(1);
2775 channel_->SendFrame(
2776 false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
2777 channel_->SendFrame(
2778 true, WebSocketFrameHeader::kOpCodeText, AsVector("World"));
2779 checkpoint.Call(2);
2780 write_callback.Run(OK);
2781 checkpoint.Call(3);
2784 // WebSocketChannel must buffer frames while it is waiting for a write to
2785 // complete, and then send them in a single batch. The batching behaviour is
2786 // important to get good throughput in the "many small messages" case.
2787 TEST_F(WebSocketChannelStreamTest, WaitingMessagesAreBatched) {
2788 static const char input_letters[] = "Hello";
2789 static const InitFrame expected1[] = {
2790 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "H"}};
2791 static const InitFrame expected2[] = {
2792 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "e"},
2793 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
2794 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
2795 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "o"}};
2796 CompletionCallback write_callback;
2798 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2799 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2800 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2802 InSequence s;
2803 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2804 .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
2805 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2806 .WillOnce(Return(ERR_IO_PENDING));
2809 CreateChannelAndConnectSuccessfully();
2810 for (size_t i = 0; i < strlen(input_letters); ++i) {
2811 channel_->SendFrame(true,
2812 WebSocketFrameHeader::kOpCodeText,
2813 std::vector<char>(1, input_letters[i]));
2815 write_callback.Run(OK);
2818 // When the renderer sends more on a channel than it has quota for, we send the
2819 // remote server a kWebSocketErrorGoingAway error code.
2820 TEST_F(WebSocketChannelStreamTest, SendGoingAwayOnRendererQuotaExceeded) {
2821 static const InitFrame expected[] = {
2822 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2823 MASKED, CLOSE_DATA(GOING_AWAY, "")}};
2824 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2825 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2826 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2827 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2828 .WillOnce(Return(OK));
2829 EXPECT_CALL(*mock_stream_, Close());
2831 CreateChannelAndConnectSuccessfully();
2832 channel_->SendFrame(true,
2833 WebSocketFrameHeader::kOpCodeText,
2834 std::vector<char>(kDefaultInitialQuota + 1, 'C'));
2837 // For convenience, most of these tests use Text frames. However, the WebSocket
2838 // protocol also has Binary frames and those need to be 8-bit clean. For the
2839 // sake of completeness, this test verifies that they are.
2840 TEST_F(WebSocketChannelStreamTest, WrittenBinaryFramesAre8BitClean) {
2841 ScopedVector<WebSocketFrame>* frames = NULL;
2843 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2844 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2845 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2846 EXPECT_CALL(*mock_stream_, WriteFrames(_, _))
2847 .WillOnce(DoAll(SaveArg<0>(&frames), Return(ERR_IO_PENDING)));
2849 CreateChannelAndConnectSuccessfully();
2850 channel_->SendFrame(
2851 true,
2852 WebSocketFrameHeader::kOpCodeBinary,
2853 std::vector<char>(kBinaryBlob, kBinaryBlob + kBinaryBlobSize));
2854 ASSERT_TRUE(frames != NULL);
2855 ASSERT_EQ(1U, frames->size());
2856 const WebSocketFrame* out_frame = (*frames)[0];
2857 EXPECT_EQ(kBinaryBlobSize, out_frame->header.payload_length);
2858 ASSERT_TRUE(out_frame->data.get());
2859 EXPECT_EQ(0, memcmp(kBinaryBlob, out_frame->data->data(), kBinaryBlobSize));
2862 // Test the read path for 8-bit cleanliness as well.
2863 TEST_F(WebSocketChannelEventInterfaceTest, ReadBinaryFramesAre8BitClean) {
2864 scoped_ptr<WebSocketFrame> frame(
2865 new WebSocketFrame(WebSocketFrameHeader::kOpCodeBinary));
2866 WebSocketFrameHeader& frame_header = frame->header;
2867 frame_header.final = true;
2868 frame_header.payload_length = kBinaryBlobSize;
2869 frame->data = new IOBuffer(kBinaryBlobSize);
2870 memcpy(frame->data->data(), kBinaryBlob, kBinaryBlobSize);
2871 ScopedVector<WebSocketFrame> frames;
2872 frames.push_back(frame.release());
2873 scoped_ptr<ReadableFakeWebSocketStream> stream(
2874 new ReadableFakeWebSocketStream);
2875 stream->PrepareRawReadFrames(
2876 ReadableFakeWebSocketStream::SYNC, OK, frames.Pass());
2877 set_stream(stream.Pass());
2878 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2879 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2880 EXPECT_CALL(*event_interface_,
2881 OnDataFrame(true,
2882 WebSocketFrameHeader::kOpCodeBinary,
2883 std::vector<char>(kBinaryBlob,
2884 kBinaryBlob + kBinaryBlobSize)));
2886 CreateChannelAndConnectSuccessfully();
2889 // Invalid UTF-8 is not permitted in Text frames.
2890 TEST_F(WebSocketChannelSendUtf8Test, InvalidUtf8Rejected) {
2891 EXPECT_CALL(
2892 *event_interface_,
2893 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2895 CreateChannelAndConnectSuccessfully();
2897 channel_->SendFrame(
2898 true, WebSocketFrameHeader::kOpCodeText, AsVector("\xff"));
2901 // A Text message cannot end with a partial UTF-8 character.
2902 TEST_F(WebSocketChannelSendUtf8Test, IncompleteCharacterInFinalFrame) {
2903 EXPECT_CALL(
2904 *event_interface_,
2905 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2907 CreateChannelAndConnectSuccessfully();
2909 channel_->SendFrame(
2910 true, WebSocketFrameHeader::kOpCodeText, AsVector("\xc2"));
2913 // A non-final Text frame may end with a partial UTF-8 character (compare to
2914 // previous test).
2915 TEST_F(WebSocketChannelSendUtf8Test, IncompleteCharacterInNonFinalFrame) {
2916 CreateChannelAndConnectSuccessfully();
2918 channel_->SendFrame(
2919 false, WebSocketFrameHeader::kOpCodeText, AsVector("\xc2"));
2922 // UTF-8 parsing context must be retained between frames.
2923 TEST_F(WebSocketChannelSendUtf8Test, ValidCharacterSplitBetweenFrames) {
2924 CreateChannelAndConnectSuccessfully();
2926 channel_->SendFrame(
2927 false, WebSocketFrameHeader::kOpCodeText, AsVector("\xf1"));
2928 channel_->SendFrame(true,
2929 WebSocketFrameHeader::kOpCodeContinuation,
2930 AsVector("\x80\xa0\xbf"));
2933 // Similarly, an invalid character should be detected even if split.
2934 TEST_F(WebSocketChannelSendUtf8Test, InvalidCharacterSplit) {
2935 EXPECT_CALL(
2936 *event_interface_,
2937 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2939 CreateChannelAndConnectSuccessfully();
2941 channel_->SendFrame(
2942 false, WebSocketFrameHeader::kOpCodeText, AsVector("\xe1"));
2943 channel_->SendFrame(true,
2944 WebSocketFrameHeader::kOpCodeContinuation,
2945 AsVector("\x80\xa0\xbf"));
2948 // An invalid character must be detected in continuation frames.
2949 TEST_F(WebSocketChannelSendUtf8Test, InvalidByteInContinuation) {
2950 EXPECT_CALL(
2951 *event_interface_,
2952 OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2954 CreateChannelAndConnectSuccessfully();
2956 channel_->SendFrame(
2957 false, WebSocketFrameHeader::kOpCodeText, AsVector("foo"));
2958 channel_->SendFrame(
2959 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector("bar"));
2960 channel_->SendFrame(
2961 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("\xff"));
2964 // However, continuation frames of a Binary frame will not be tested for UTF-8
2965 // validity.
2966 TEST_F(WebSocketChannelSendUtf8Test, BinaryContinuationNotChecked) {
2967 CreateChannelAndConnectSuccessfully();
2969 channel_->SendFrame(
2970 false, WebSocketFrameHeader::kOpCodeBinary, AsVector("foo"));
2971 channel_->SendFrame(
2972 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector("bar"));
2973 channel_->SendFrame(
2974 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("\xff"));
2977 // Multiple text messages can be validated without the validation state getting
2978 // confused.
2979 TEST_F(WebSocketChannelSendUtf8Test, ValidateMultipleTextMessages) {
2980 CreateChannelAndConnectSuccessfully();
2982 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("foo"));
2983 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("bar"));
2986 // UTF-8 validation is enforced on received Text frames.
2987 TEST_F(WebSocketChannelEventInterfaceTest, ReceivedInvalidUtf8) {
2988 scoped_ptr<ReadableFakeWebSocketStream> stream(
2989 new ReadableFakeWebSocketStream);
2990 static const InitFrame frames[] = {
2991 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xff"}};
2992 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2993 set_stream(stream.Pass());
2995 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2996 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
2997 EXPECT_CALL(*event_interface_,
2998 OnFailChannel("Could not decode a text frame as UTF-8."));
3000 CreateChannelAndConnectSuccessfully();
3001 base::MessageLoop::current()->RunUntilIdle();
3004 // Invalid UTF-8 is not sent over the network.
3005 TEST_F(WebSocketChannelStreamTest, InvalidUtf8TextFrameNotSent) {
3006 static const InitFrame expected[] = {{FINAL_FRAME,
3007 WebSocketFrameHeader::kOpCodeClose,
3008 MASKED, CLOSE_DATA(GOING_AWAY, "")}};
3009 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
3010 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
3011 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3012 .WillRepeatedly(Return(ERR_IO_PENDING));
3013 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3014 .WillOnce(Return(OK));
3015 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3017 CreateChannelAndConnectSuccessfully();
3019 channel_->SendFrame(
3020 true, WebSocketFrameHeader::kOpCodeText, AsVector("\xff"));
3023 // The rest of the tests for receiving invalid UTF-8 test the communication with
3024 // the server. Since there is only one code path, it would be redundant to
3025 // perform the same tests on the EventInterface as well.
3027 // If invalid UTF-8 is received in a Text frame, the connection is failed.
3028 TEST_F(WebSocketChannelReceiveUtf8Test, InvalidTextFrameRejected) {
3029 static const InitFrame frames[] = {
3030 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xff"}};
3031 static const InitFrame expected[] = {
3032 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
3033 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
3035 InSequence s;
3036 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3037 .WillOnce(ReturnFrames(&frames))
3038 .WillRepeatedly(Return(ERR_IO_PENDING));
3039 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3040 .WillOnce(Return(OK));
3041 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3044 CreateChannelAndConnectSuccessfully();
3047 // A received Text message is not permitted to end with a partial UTF-8
3048 // character.
3049 TEST_F(WebSocketChannelReceiveUtf8Test, IncompleteCharacterReceived) {
3050 static const InitFrame frames[] = {
3051 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xc2"}};
3052 static const InitFrame expected[] = {
3053 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
3054 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
3055 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3056 .WillOnce(ReturnFrames(&frames))
3057 .WillRepeatedly(Return(ERR_IO_PENDING));
3058 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3059 .WillOnce(Return(OK));
3060 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3062 CreateChannelAndConnectSuccessfully();
3065 // However, a non-final Text frame may end with a partial UTF-8 character.
3066 TEST_F(WebSocketChannelReceiveUtf8Test, IncompleteCharacterIncompleteMessage) {
3067 static const InitFrame frames[] = {
3068 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xc2"}};
3069 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3070 .WillOnce(ReturnFrames(&frames))
3071 .WillRepeatedly(Return(ERR_IO_PENDING));
3073 CreateChannelAndConnectSuccessfully();
3076 // However, it will become an error if it is followed by an empty final frame.
3077 TEST_F(WebSocketChannelReceiveUtf8Test, TricksyIncompleteCharacter) {
3078 static const InitFrame frames[] = {
3079 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xc2"},
3080 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation, NOT_MASKED, ""}};
3081 static const InitFrame expected[] = {
3082 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
3083 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
3084 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3085 .WillOnce(ReturnFrames(&frames))
3086 .WillRepeatedly(Return(ERR_IO_PENDING));
3087 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3088 .WillOnce(Return(OK));
3089 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3091 CreateChannelAndConnectSuccessfully();
3094 // UTF-8 parsing context must be retained between received frames of the same
3095 // message.
3096 TEST_F(WebSocketChannelReceiveUtf8Test, ReceivedParsingContextRetained) {
3097 static const InitFrame frames[] = {
3098 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xf1"},
3099 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3100 NOT_MASKED, "\x80\xa0\xbf"}};
3101 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3102 .WillOnce(ReturnFrames(&frames))
3103 .WillRepeatedly(Return(ERR_IO_PENDING));
3105 CreateChannelAndConnectSuccessfully();
3108 // An invalid character must be detected even if split between frames.
3109 TEST_F(WebSocketChannelReceiveUtf8Test, SplitInvalidCharacterReceived) {
3110 static const InitFrame frames[] = {
3111 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xe1"},
3112 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3113 NOT_MASKED, "\x80\xa0\xbf"}};
3114 static const InitFrame expected[] = {
3115 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
3116 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
3117 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3118 .WillOnce(ReturnFrames(&frames))
3119 .WillRepeatedly(Return(ERR_IO_PENDING));
3120 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3121 .WillOnce(Return(OK));
3122 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3124 CreateChannelAndConnectSuccessfully();
3127 // An invalid character received in a continuation frame must be detected.
3128 TEST_F(WebSocketChannelReceiveUtf8Test, InvalidReceivedIncontinuation) {
3129 static const InitFrame frames[] = {
3130 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "foo"},
3131 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3132 NOT_MASKED, "bar"},
3133 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3134 NOT_MASKED, "\xff"}};
3135 static const InitFrame expected[] = {
3136 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
3137 CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
3138 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3139 .WillOnce(ReturnFrames(&frames))
3140 .WillRepeatedly(Return(ERR_IO_PENDING));
3141 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3142 .WillOnce(Return(OK));
3143 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3145 CreateChannelAndConnectSuccessfully();
3148 // Continuations of binary frames must not be tested for UTF-8 validity.
3149 TEST_F(WebSocketChannelReceiveUtf8Test, ReceivedBinaryNotUtf8Tested) {
3150 static const InitFrame frames[] = {
3151 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeBinary, NOT_MASKED, "foo"},
3152 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3153 NOT_MASKED, "bar"},
3154 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3155 NOT_MASKED, "\xff"}};
3156 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3157 .WillOnce(ReturnFrames(&frames))
3158 .WillRepeatedly(Return(ERR_IO_PENDING));
3160 CreateChannelAndConnectSuccessfully();
3163 // Multiple Text messages can be validated.
3164 TEST_F(WebSocketChannelReceiveUtf8Test, ValidateMultipleReceived) {
3165 static const InitFrame frames[] = {
3166 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "foo"},
3167 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "bar"}};
3168 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3169 .WillOnce(ReturnFrames(&frames))
3170 .WillRepeatedly(Return(ERR_IO_PENDING));
3172 CreateChannelAndConnectSuccessfully();
3175 // A new data message cannot start in the middle of another data message.
3176 TEST_F(WebSocketChannelEventInterfaceTest, BogusContinuation) {
3177 scoped_ptr<ReadableFakeWebSocketStream> stream(
3178 new ReadableFakeWebSocketStream);
3179 static const InitFrame frames[] = {
3180 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeBinary,
3181 NOT_MASKED, "frame1"},
3182 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
3183 NOT_MASKED, "frame2"}};
3184 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
3185 set_stream(stream.Pass());
3187 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
3188 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
3189 EXPECT_CALL(
3190 *event_interface_,
3191 OnDataFrame(
3192 false, WebSocketFrameHeader::kOpCodeBinary, AsVector("frame1")));
3193 EXPECT_CALL(
3194 *event_interface_,
3195 OnFailChannel(
3196 "Received start of new message but previous message is unfinished."));
3198 CreateChannelAndConnectSuccessfully();
3201 // A new message cannot start with a Continuation frame.
3202 TEST_F(WebSocketChannelEventInterfaceTest, MessageStartingWithContinuation) {
3203 scoped_ptr<ReadableFakeWebSocketStream> stream(
3204 new ReadableFakeWebSocketStream);
3205 static const InitFrame frames[] = {
3206 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3207 NOT_MASKED, "continuation"}};
3208 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
3209 set_stream(stream.Pass());
3211 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
3212 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
3213 EXPECT_CALL(*event_interface_,
3214 OnFailChannel("Received unexpected continuation frame."));
3216 CreateChannelAndConnectSuccessfully();
3219 // A frame passed to the renderer must be either non-empty or have the final bit
3220 // set.
3221 TEST_F(WebSocketChannelEventInterfaceTest, DataFramesNonEmptyOrFinal) {
3222 scoped_ptr<ReadableFakeWebSocketStream> stream(
3223 new ReadableFakeWebSocketStream);
3224 static const InitFrame frames[] = {
3225 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, ""},
3226 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
3227 NOT_MASKED, ""},
3228 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation, NOT_MASKED, ""}};
3229 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
3230 set_stream(stream.Pass());
3232 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
3233 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
3234 EXPECT_CALL(
3235 *event_interface_,
3236 OnDataFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("")));
3238 CreateChannelAndConnectSuccessfully();
3241 // Calls to OnSSLCertificateError() must be passed through to the event
3242 // interface with the correct URL attached.
3243 TEST_F(WebSocketChannelEventInterfaceTest, OnSSLCertificateErrorCalled) {
3244 const GURL wss_url("wss://example.com/sslerror");
3245 connect_data_.socket_url = wss_url;
3246 const SSLInfo ssl_info;
3247 const bool fatal = true;
3248 scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks> fake_callbacks(
3249 new FakeSSLErrorCallbacks);
3251 EXPECT_CALL(*event_interface_,
3252 OnSSLCertificateErrorCalled(NotNull(), wss_url, _, fatal));
3254 CreateChannelAndConnect();
3255 connect_data_.creator.connect_delegate->OnSSLCertificateError(
3256 fake_callbacks.Pass(), ssl_info, fatal);
3259 // If we receive another frame after Close, it is not valid. It is not
3260 // completely clear what behaviour is required from the standard in this case,
3261 // but the current implementation fails the connection. Since a Close has
3262 // already been sent, this just means closing the connection.
3263 TEST_F(WebSocketChannelStreamTest, PingAfterCloseIsRejected) {
3264 static const InitFrame frames[] = {
3265 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3266 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")},
3267 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
3268 NOT_MASKED, "Ping body"}};
3269 static const InitFrame expected[] = {
3270 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3271 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
3272 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
3273 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
3274 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3275 .WillOnce(ReturnFrames(&frames))
3276 .WillRepeatedly(Return(ERR_IO_PENDING));
3278 // We only need to verify the relative order of WriteFrames() and
3279 // Close(). The current implementation calls WriteFrames() for the Close
3280 // frame before calling ReadFrames() again, but that is an implementation
3281 // detail and better not to consider required behaviour.
3282 InSequence s;
3283 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3284 .WillOnce(Return(OK));
3285 EXPECT_CALL(*mock_stream_, Close()).Times(1);
3288 CreateChannelAndConnectSuccessfully();
3291 // A protocol error from the remote server should result in a close frame with
3292 // status 1002, followed by the connection closing.
3293 TEST_F(WebSocketChannelStreamTest, ProtocolError) {
3294 static const InitFrame expected[] = {
3295 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3296 MASKED, CLOSE_DATA(PROTOCOL_ERROR, "WebSocket Protocol Error")}};
3297 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
3298 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
3299 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3300 .WillOnce(Return(ERR_WS_PROTOCOL_ERROR));
3301 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3302 .WillOnce(Return(OK));
3303 EXPECT_CALL(*mock_stream_, Close());
3305 CreateChannelAndConnectSuccessfully();
3308 // Set the closing handshake timeout to a very tiny value before connecting.
3309 class WebSocketChannelStreamTimeoutTest : public WebSocketChannelStreamTest {
3310 protected:
3311 WebSocketChannelStreamTimeoutTest() {}
3313 void CreateChannelAndConnectSuccessfully() override {
3314 set_stream(mock_stream_.Pass());
3315 CreateChannelAndConnect();
3316 channel_->SendFlowControl(kPlentyOfQuota);
3317 channel_->SetClosingHandshakeTimeoutForTesting(
3318 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
3319 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
3323 // In this case the server initiates the closing handshake with a Close
3324 // message. WebSocketChannel responds with a matching Close message, and waits
3325 // for the server to close the TCP/IP connection. The server never closes the
3326 // connection, so the closing handshake times out and WebSocketChannel closes
3327 // the connection itself.
3328 TEST_F(WebSocketChannelStreamTimeoutTest, ServerInitiatedCloseTimesOut) {
3329 static const InitFrame frames[] = {
3330 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3331 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
3332 static const InitFrame expected[] = {
3333 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3334 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
3335 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
3336 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
3337 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3338 .WillOnce(ReturnFrames(&frames))
3339 .WillRepeatedly(Return(ERR_IO_PENDING));
3340 Checkpoint checkpoint;
3341 TestClosure completion;
3343 InSequence s;
3344 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3345 .WillOnce(Return(OK));
3346 EXPECT_CALL(checkpoint, Call(1));
3347 EXPECT_CALL(*mock_stream_, Close())
3348 .WillOnce(InvokeClosure(completion.closure()));
3351 CreateChannelAndConnectSuccessfully();
3352 checkpoint.Call(1);
3353 completion.WaitForResult();
3356 // In this case the client initiates the closing handshake by sending a Close
3357 // message. WebSocketChannel waits for a Close message in response from the
3358 // server. The server never responds to the Close message, so the closing
3359 // handshake times out and WebSocketChannel closes the connection.
3360 TEST_F(WebSocketChannelStreamTimeoutTest, ClientInitiatedCloseTimesOut) {
3361 static const InitFrame expected[] = {
3362 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3363 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
3364 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
3365 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
3366 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3367 .WillRepeatedly(Return(ERR_IO_PENDING));
3368 TestClosure completion;
3370 InSequence s;
3371 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3372 .WillOnce(Return(OK));
3373 EXPECT_CALL(*mock_stream_, Close())
3374 .WillOnce(InvokeClosure(completion.closure()));
3377 CreateChannelAndConnectSuccessfully();
3378 channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
3379 completion.WaitForResult();
3382 // In this case the client initiates the closing handshake and the server
3383 // responds with a matching Close message. WebSocketChannel waits for the server
3384 // to close the TCP/IP connection, but it never does. The closing handshake
3385 // times out and WebSocketChannel closes the connection.
3386 TEST_F(WebSocketChannelStreamTimeoutTest, ConnectionCloseTimesOut) {
3387 static const InitFrame expected[] = {
3388 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3389 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
3390 static const InitFrame frames[] = {
3391 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
3392 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
3393 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
3394 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
3395 TestClosure completion;
3396 ScopedVector<WebSocketFrame>* read_frames = NULL;
3397 CompletionCallback read_callback;
3399 InSequence s;
3400 // Copy the arguments to ReadFrames so that the test can call the callback
3401 // after it has send the close message.
3402 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3403 .WillOnce(DoAll(SaveArg<0>(&read_frames),
3404 SaveArg<1>(&read_callback),
3405 Return(ERR_IO_PENDING)));
3406 // The first real event that happens is the client sending the Close
3407 // message.
3408 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3409 .WillOnce(Return(OK));
3410 // The |read_frames| callback is called (from this test case) at this
3411 // point. ReadFrames is called again by WebSocketChannel, waiting for
3412 // ERR_CONNECTION_CLOSED.
3413 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3414 .WillOnce(Return(ERR_IO_PENDING));
3415 // The timeout happens and so WebSocketChannel closes the stream.
3416 EXPECT_CALL(*mock_stream_, Close())
3417 .WillOnce(InvokeClosure(completion.closure()));
3420 CreateChannelAndConnectSuccessfully();
3421 channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
3422 ASSERT_TRUE(read_frames);
3423 // Provide the "Close" message from the server.
3424 *read_frames = CreateFrameVector(frames);
3425 read_callback.Run(OK);
3426 completion.WaitForResult();
3429 } // namespace
3430 } // namespace net