Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / net / websockets / websocket_channel_test.cc
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.
4
5 #include "net/websockets/websocket_channel.h"
6
7 #include <string.h>
8
9 #include <iostream>
10 #include <string>
11 #include <vector>
12
13 #include "base/bind.h"
14 #include "base/bind_helpers.h"
15 #include "base/callback.h"
16 #include "base/location.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/scoped_vector.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/message_loop/message_loop.h"
21 #include "base/strings/string_piece.h"
22 #include "net/base/net_errors.h"
23 #include "net/base/test_completion_callback.h"
24 #include "net/http/http_response_headers.h"
25 #include "net/url_request/url_request_context.h"
26 #include "net/websockets/websocket_errors.h"
27 #include "net/websockets/websocket_event_interface.h"
28 #include "net/websockets/websocket_handshake_request_info.h"
29 #include "net/websockets/websocket_handshake_response_info.h"
30 #include "net/websockets/websocket_mux.h"
31 #include "testing/gmock/include/gmock/gmock.h"
32 #include "testing/gtest/include/gtest/gtest.h"
33 #include "url/gurl.h"
34
35 // Hacky macros to construct the body of a Close message from a code and a
36 // string, while ensuring the result is a compile-time constant string.
37 // Use like CLOSE_DATA(NORMAL_CLOSURE, "Explanation String")
38 #define CLOSE_DATA(code, string) WEBSOCKET_CLOSE_CODE_AS_STRING_##code string
39 #define WEBSOCKET_CLOSE_CODE_AS_STRING_NORMAL_CLOSURE "\x03\xe8"
40 #define WEBSOCKET_CLOSE_CODE_AS_STRING_GOING_AWAY "\x03\xe9"
41 #define WEBSOCKET_CLOSE_CODE_AS_STRING_PROTOCOL_ERROR "\x03\xea"
42 #define WEBSOCKET_CLOSE_CODE_AS_STRING_ABNORMAL_CLOSURE "\x03\xee"
43 #define WEBSOCKET_CLOSE_CODE_AS_STRING_SERVER_ERROR "\x03\xf3"
44
45 namespace net {
46
47 // Printing helpers to allow GoogleMock to print frames. These are explicitly
48 // designed to look like the static initialisation format we use in these
49 // tests. They have to live in the net namespace in order to be found by
50 // GoogleMock; a nested anonymous namespace will not work.
51
52 std::ostream& operator<<(std::ostream& os, const WebSocketFrameHeader& header) {
53   return os << (header.final ? "FINAL_FRAME" : "NOT_FINAL_FRAME") << ", "
54             << header.opcode << ", "
55             << (header.masked ? "MASKED" : "NOT_MASKED");
56 }
57
58 std::ostream& operator<<(std::ostream& os, const WebSocketFrame& frame) {
59   os << "{" << frame.header << ", ";
60   if (frame.data) {
61     return os << "\"" << base::StringPiece(frame.data->data(),
62                                            frame.header.payload_length)
63               << "\"}";
64   }
65   return os << "NULL}";
66 }
67
68 std::ostream& operator<<(std::ostream& os,
69                          const ScopedVector<WebSocketFrame>& vector) {
70   os << "{";
71   bool first = true;
72   for (ScopedVector<WebSocketFrame>::const_iterator it = vector.begin();
73        it != vector.end();
74        ++it) {
75     if (!first) {
76       os << ",\n";
77     } else {
78       first = false;
79     }
80     os << **it;
81   }
82   return os << "}";
83 }
84
85 std::ostream& operator<<(std::ostream& os,
86                          const ScopedVector<WebSocketFrame>* vector) {
87   return os << '&' << *vector;
88 }
89
90 namespace {
91
92 using ::base::TimeDelta;
93
94 using ::testing::AnyNumber;
95 using ::testing::DefaultValue;
96 using ::testing::InSequence;
97 using ::testing::MockFunction;
98 using ::testing::Return;
99 using ::testing::SaveArg;
100 using ::testing::StrictMock;
101 using ::testing::_;
102
103 // A selection of characters that have traditionally been mangled in some
104 // environment or other, for testing 8-bit cleanliness.
105 const char kBinaryBlob[] = {'\n',   '\r',    // BACKWARDS CRNL
106                             '\0',            // nul
107                             '\x7F',          // DEL
108                             '\x80', '\xFF',  // NOT VALID UTF-8
109                             '\x1A',          // Control-Z, EOF on DOS
110                             '\x03',          // Control-C
111                             '\x04',          // EOT, special for Unix terms
112                             '\x1B',          // ESC, often special
113                             '\b',            // backspace
114                             '\'',            // single-quote, special in PHP
115 };
116 const size_t kBinaryBlobSize = arraysize(kBinaryBlob);
117
118 // The amount of quota a new connection gets by default.
119 // TODO(ricea): If kDefaultSendQuotaHighWaterMark changes, then this value will
120 // need to be updated.
121 const size_t kDefaultInitialQuota = 1 << 17;
122 // The amount of bytes we need to send after the initial connection to trigger a
123 // quota refresh. TODO(ricea): Change this if kDefaultSendQuotaHighWaterMark or
124 // kDefaultSendQuotaLowWaterMark change.
125 const size_t kDefaultQuotaRefreshTrigger = (1 << 16) + 1;
126
127 // TestTimeouts::tiny_timeout() is 100ms! I could run halfway around the world
128 // in that time! I would like my tests to run a bit quicker.
129 const int kVeryTinyTimeoutMillis = 1;
130
131 typedef WebSocketEventInterface::ChannelState ChannelState;
132 const ChannelState CHANNEL_ALIVE = WebSocketEventInterface::CHANNEL_ALIVE;
133 const ChannelState CHANNEL_DELETED = WebSocketEventInterface::CHANNEL_DELETED;
134
135 // This typedef mainly exists to avoid having to repeat the "NOLINT" incantation
136 // all over the place.
137 typedef MockFunction<void(int)> Checkpoint;  // NOLINT
138
139 // This mock is for testing expectations about how the EventInterface is used.
140 class MockWebSocketEventInterface : public WebSocketEventInterface {
141  public:
142   MockWebSocketEventInterface() {}
143
144   MOCK_METHOD3(OnAddChannelResponse,
145                ChannelState(bool,
146                             const std::string&,
147                             const std::string&));  // NOLINT
148   MOCK_METHOD3(OnDataFrame,
149                ChannelState(bool,
150                             WebSocketMessageType,
151                             const std::vector<char>&));  // NOLINT
152   MOCK_METHOD1(OnFlowControl, ChannelState(int64));  // NOLINT
153   MOCK_METHOD0(OnClosingHandshake, ChannelState(void));  // NOLINT
154   MOCK_METHOD1(OnFailChannel, ChannelState(const std::string&));  // NOLINT
155   MOCK_METHOD3(OnDropChannel,
156                ChannelState(bool, uint16, const std::string&));  // NOLINT
157
158   // We can't use GMock with scoped_ptr.
159   ChannelState OnStartOpeningHandshake(
160       scoped_ptr<WebSocketHandshakeRequestInfo>) OVERRIDE {
161     OnStartOpeningHandshakeCalled();
162     return CHANNEL_ALIVE;
163   }
164   ChannelState OnFinishOpeningHandshake(
165       scoped_ptr<WebSocketHandshakeResponseInfo>) OVERRIDE {
166     OnFinishOpeningHandshakeCalled();
167     return CHANNEL_ALIVE;
168   }
169
170   MOCK_METHOD0(OnStartOpeningHandshakeCalled, void());  // NOLINT
171   MOCK_METHOD0(OnFinishOpeningHandshakeCalled, void());  // NOLINT
172 };
173
174 // This fake EventInterface is for tests which need a WebSocketEventInterface
175 // implementation but are not verifying how it is used.
176 class FakeWebSocketEventInterface : public WebSocketEventInterface {
177   virtual ChannelState OnAddChannelResponse(
178       bool fail,
179       const std::string& selected_protocol,
180       const std::string& extensions) OVERRIDE {
181     return fail ? CHANNEL_DELETED : CHANNEL_ALIVE;
182   }
183   virtual ChannelState OnDataFrame(bool fin,
184                                    WebSocketMessageType type,
185                                    const std::vector<char>& data) OVERRIDE {
186     return CHANNEL_ALIVE;
187   }
188   virtual ChannelState OnFlowControl(int64 quota) OVERRIDE {
189     return CHANNEL_ALIVE;
190   }
191   virtual ChannelState OnClosingHandshake() OVERRIDE { return CHANNEL_ALIVE; }
192   virtual ChannelState OnFailChannel(const std::string& message) OVERRIDE {
193     return CHANNEL_DELETED;
194   }
195   virtual ChannelState OnDropChannel(bool was_clean,
196                                      uint16 code,
197                                      const std::string& reason) OVERRIDE {
198     return CHANNEL_DELETED;
199   }
200   virtual ChannelState OnStartOpeningHandshake(
201       scoped_ptr<WebSocketHandshakeRequestInfo> request) OVERRIDE {
202     return CHANNEL_ALIVE;
203   }
204   virtual ChannelState OnFinishOpeningHandshake(
205       scoped_ptr<WebSocketHandshakeResponseInfo> response) OVERRIDE {
206     return CHANNEL_ALIVE;
207   }
208 };
209
210 // This fake WebSocketStream is for tests that require a WebSocketStream but are
211 // not testing the way it is used. It has minimal functionality to return
212 // the |protocol| and |extensions| that it was constructed with.
213 class FakeWebSocketStream : public WebSocketStream {
214  public:
215   // Constructs with empty protocol and extensions.
216   FakeWebSocketStream() {}
217
218   // Constructs with specified protocol and extensions.
219   FakeWebSocketStream(const std::string& protocol,
220                       const std::string& extensions)
221       : protocol_(protocol), extensions_(extensions) {}
222
223   virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
224                          const CompletionCallback& callback) OVERRIDE {
225     return ERR_IO_PENDING;
226   }
227
228   virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
229                           const CompletionCallback& callback) OVERRIDE {
230     return ERR_IO_PENDING;
231   }
232
233   virtual void Close() OVERRIDE {}
234
235   // Returns the string passed to the constructor.
236   virtual std::string GetSubProtocol() const OVERRIDE { return protocol_; }
237
238   // Returns the string passed to the constructor.
239   virtual std::string GetExtensions() const OVERRIDE { return extensions_; }
240
241  private:
242   // The string to return from GetSubProtocol().
243   std::string protocol_;
244
245   // The string to return from GetExtensions().
246   std::string extensions_;
247 };
248
249 // To make the static initialisers easier to read, we use enums rather than
250 // bools.
251 enum IsFinal { NOT_FINAL_FRAME, FINAL_FRAME };
252
253 enum IsMasked { NOT_MASKED, MASKED };
254
255 // This is used to initialise a WebSocketFrame but is statically initialisable.
256 struct InitFrame {
257   IsFinal final;
258   // Reserved fields omitted for now. Add them if you need them.
259   WebSocketFrameHeader::OpCode opcode;
260   IsMasked masked;
261
262   // Will be used to create the IOBuffer member. Can be NULL for NULL data. Is a
263   // nul-terminated string for ease-of-use. |header.payload_length| is
264   // initialised from |strlen(data)|. This means it is not 8-bit clean, but this
265   // is not an issue for test data.
266   const char* const data;
267 };
268
269 // For GoogleMock
270 std::ostream& operator<<(std::ostream& os, const InitFrame& frame) {
271   os << "{" << (frame.final == FINAL_FRAME ? "FINAL_FRAME" : "NOT_FINAL_FRAME")
272      << ", " << frame.opcode << ", "
273      << (frame.masked == MASKED ? "MASKED" : "NOT_MASKED") << ", ";
274   if (frame.data) {
275     return os << "\"" << frame.data << "\"}";
276   }
277   return os << "NULL}";
278 }
279
280 template <size_t N>
281 std::ostream& operator<<(std::ostream& os, const InitFrame (&frames)[N]) {
282   os << "{";
283   bool first = true;
284   for (size_t i = 0; i < N; ++i) {
285     if (!first) {
286       os << ",\n";
287     } else {
288       first = false;
289     }
290     os << frames[i];
291   }
292   return os << "}";
293 }
294
295 // Convert a const array of InitFrame structs to the format used at
296 // runtime. Templated on the size of the array to save typing.
297 template <size_t N>
298 ScopedVector<WebSocketFrame> CreateFrameVector(
299     const InitFrame (&source_frames)[N]) {
300   ScopedVector<WebSocketFrame> result_frames;
301   result_frames.reserve(N);
302   for (size_t i = 0; i < N; ++i) {
303     const InitFrame& source_frame = source_frames[i];
304     scoped_ptr<WebSocketFrame> result_frame(
305         new WebSocketFrame(source_frame.opcode));
306     size_t frame_length = source_frame.data ? strlen(source_frame.data) : 0;
307     WebSocketFrameHeader& result_header = result_frame->header;
308     result_header.final = (source_frame.final == FINAL_FRAME);
309     result_header.masked = (source_frame.masked == MASKED);
310     result_header.payload_length = frame_length;
311     if (source_frame.data) {
312       result_frame->data = new IOBuffer(frame_length);
313       memcpy(result_frame->data->data(), source_frame.data, frame_length);
314     }
315     result_frames.push_back(result_frame.release());
316   }
317   return result_frames.Pass();
318 }
319
320 // A GoogleMock action which can be used to respond to call to ReadFrames with
321 // some frames. Use like ReadFrames(_, _).WillOnce(ReturnFrames(&frames));
322 // |frames| is an array of InitFrame. |frames| needs to be passed by pointer
323 // because otherwise it will be treated as a pointer and the array size
324 // information will be lost.
325 ACTION_P(ReturnFrames, source_frames) {
326   *arg0 = CreateFrameVector(*source_frames);
327   return OK;
328 }
329
330 // The implementation of a GoogleMock matcher which can be used to compare a
331 // ScopedVector<WebSocketFrame>* against an expectation defined as an array of
332 // InitFrame objects. Although it is possible to compose built-in GoogleMock
333 // matchers to check the contents of a WebSocketFrame, the results are so
334 // unreadable that it is better to use this matcher.
335 template <size_t N>
336 class EqualsFramesMatcher
337     : public ::testing::MatcherInterface<ScopedVector<WebSocketFrame>*> {
338  public:
339   EqualsFramesMatcher(const InitFrame (*expect_frames)[N])
340       : expect_frames_(expect_frames) {}
341
342   virtual bool MatchAndExplain(ScopedVector<WebSocketFrame>* actual_frames,
343                                ::testing::MatchResultListener* listener) const {
344     if (actual_frames->size() != N) {
345       *listener << "the vector size is " << actual_frames->size();
346       return false;
347     }
348     for (size_t i = 0; i < N; ++i) {
349       const WebSocketFrame& actual_frame = *(*actual_frames)[i];
350       const InitFrame& expected_frame = (*expect_frames_)[i];
351       if (actual_frame.header.final != (expected_frame.final == FINAL_FRAME)) {
352         *listener << "the frame is marked as "
353                   << (actual_frame.header.final ? "" : "not ") << "final";
354         return false;
355       }
356       if (actual_frame.header.opcode != expected_frame.opcode) {
357         *listener << "the opcode is " << actual_frame.header.opcode;
358         return false;
359       }
360       if (actual_frame.header.masked != (expected_frame.masked == MASKED)) {
361         *listener << "the frame is "
362                   << (actual_frame.header.masked ? "masked" : "not masked");
363         return false;
364       }
365       const size_t expected_length =
366           expected_frame.data ? strlen(expected_frame.data) : 0;
367       if (actual_frame.header.payload_length != expected_length) {
368         *listener << "the payload length is "
369                   << actual_frame.header.payload_length;
370         return false;
371       }
372       if (expected_length != 0 &&
373           memcmp(actual_frame.data->data(),
374                  expected_frame.data,
375                  actual_frame.header.payload_length) != 0) {
376         *listener << "the data content differs";
377         return false;
378       }
379     }
380     return true;
381   }
382
383   virtual void DescribeTo(std::ostream* os) const {
384     *os << "matches " << *expect_frames_;
385   }
386
387   virtual void DescribeNegationTo(std::ostream* os) const {
388     *os << "does not match " << *expect_frames_;
389   }
390
391  private:
392   const InitFrame (*expect_frames_)[N];
393 };
394
395 // The definition of EqualsFrames GoogleMock matcher. Unlike the ReturnFrames
396 // action, this can take the array by reference.
397 template <size_t N>
398 ::testing::Matcher<ScopedVector<WebSocketFrame>*> EqualsFrames(
399     const InitFrame (&frames)[N]) {
400   return ::testing::MakeMatcher(new EqualsFramesMatcher<N>(&frames));
401 }
402
403 // TestClosure works like TestCompletionCallback, but doesn't take an argument.
404 class TestClosure {
405  public:
406   base::Closure closure() { return base::Bind(callback_.callback(), OK); }
407
408   void WaitForResult() { callback_.WaitForResult(); }
409
410  private:
411   // Delegate to TestCompletionCallback for the implementation.
412   TestCompletionCallback callback_;
413 };
414
415 // A GoogleMock action to run a Closure.
416 ACTION_P(InvokeClosure, closure) { closure.Run(); }
417
418 // A GoogleMock action to run a Closure and return CHANNEL_DELETED.
419 ACTION_P(InvokeClosureReturnDeleted, closure) {
420   closure.Run();
421   return WebSocketEventInterface::CHANNEL_DELETED;
422 }
423
424 // A FakeWebSocketStream whose ReadFrames() function returns data.
425 class ReadableFakeWebSocketStream : public FakeWebSocketStream {
426  public:
427   enum IsSync { SYNC, ASYNC };
428
429   // After constructing the object, call PrepareReadFrames() once for each
430   // time you wish it to return from the test.
431   ReadableFakeWebSocketStream() : index_(0), read_frames_pending_(false) {}
432
433   // Check that all the prepared responses have been consumed.
434   virtual ~ReadableFakeWebSocketStream() {
435     CHECK(index_ >= responses_.size());
436     CHECK(!read_frames_pending_);
437   }
438
439   // Prepares a fake response. Fake responses will be returned from ReadFrames()
440   // in the same order they were prepared with PrepareReadFrames() and
441   // PrepareReadFramesError(). If |async| is ASYNC, then ReadFrames() will
442   // return ERR_IO_PENDING and the callback will be scheduled to run on the
443   // message loop. This requires the test case to run the message loop. If
444   // |async| is SYNC, the response will be returned synchronously. |error| is
445   // returned directly from ReadFrames() in the synchronous case, or passed to
446   // the callback in the asynchronous case. |frames| will be converted to a
447   // ScopedVector<WebSocketFrame> and copied to the pointer that was passed to
448   // ReadFrames().
449   template <size_t N>
450   void PrepareReadFrames(IsSync async,
451                          int error,
452                          const InitFrame (&frames)[N]) {
453     responses_.push_back(new Response(async, error, CreateFrameVector(frames)));
454   }
455
456   // An alternate version of PrepareReadFrames for when we need to construct
457   // the frames manually.
458   void PrepareRawReadFrames(IsSync async,
459                             int error,
460                             ScopedVector<WebSocketFrame> frames) {
461     responses_.push_back(new Response(async, error, frames.Pass()));
462   }
463
464   // Prepares a fake error response (ie. there is no data).
465   void PrepareReadFramesError(IsSync async, int error) {
466     responses_.push_back(
467         new Response(async, error, ScopedVector<WebSocketFrame>()));
468   }
469
470   virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
471                          const CompletionCallback& callback) OVERRIDE {
472     CHECK(!read_frames_pending_);
473     if (index_ >= responses_.size())
474       return ERR_IO_PENDING;
475     if (responses_[index_]->async == ASYNC) {
476       read_frames_pending_ = true;
477       base::MessageLoop::current()->PostTask(
478           FROM_HERE,
479           base::Bind(&ReadableFakeWebSocketStream::DoCallback,
480                      base::Unretained(this),
481                      frames,
482                      callback));
483       return ERR_IO_PENDING;
484     } else {
485       frames->swap(responses_[index_]->frames);
486       return responses_[index_++]->error;
487     }
488   }
489
490  private:
491   void DoCallback(ScopedVector<WebSocketFrame>* frames,
492                   const CompletionCallback& callback) {
493     read_frames_pending_ = false;
494     frames->swap(responses_[index_]->frames);
495     callback.Run(responses_[index_++]->error);
496     return;
497   }
498
499   struct Response {
500     Response(IsSync async, int error, ScopedVector<WebSocketFrame> frames)
501         : async(async), error(error), frames(frames.Pass()) {}
502
503     IsSync async;
504     int error;
505     ScopedVector<WebSocketFrame> frames;
506
507    private:
508     // Bad things will happen if we attempt to copy or assign |frames|.
509     DISALLOW_COPY_AND_ASSIGN(Response);
510   };
511   ScopedVector<Response> responses_;
512
513   // The index into the responses_ array of the next response to be returned.
514   size_t index_;
515
516   // True when an async response from ReadFrames() is pending. This only applies
517   // to "real" async responses. Once all the prepared responses have been
518   // returned, ReadFrames() returns ERR_IO_PENDING but read_frames_pending_ is
519   // not set to true.
520   bool read_frames_pending_;
521 };
522
523 // A FakeWebSocketStream where writes always complete successfully and
524 // synchronously.
525 class WriteableFakeWebSocketStream : public FakeWebSocketStream {
526  public:
527   virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
528                           const CompletionCallback& callback) OVERRIDE {
529     return OK;
530   }
531 };
532
533 // A FakeWebSocketStream where writes always fail.
534 class UnWriteableFakeWebSocketStream : public FakeWebSocketStream {
535  public:
536   virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
537                           const CompletionCallback& callback) OVERRIDE {
538     return ERR_CONNECTION_RESET;
539   }
540 };
541
542 // A FakeWebSocketStream which echoes any frames written back. Clears the
543 // "masked" header bit, but makes no other checks for validity. Tests using this
544 // must run the MessageLoop to receive the callback(s). If a message with opcode
545 // Close is echoed, then an ERR_CONNECTION_CLOSED is returned in the next
546 // callback. The test must do something to cause WriteFrames() to be called,
547 // otherwise the ReadFrames() callback will never be called.
548 class EchoeyFakeWebSocketStream : public FakeWebSocketStream {
549  public:
550   EchoeyFakeWebSocketStream() : read_frames_(NULL), done_(false) {}
551
552   virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
553                           const CompletionCallback& callback) OVERRIDE {
554     // Users of WebSocketStream will not expect the ReadFrames() callback to be
555     // called from within WriteFrames(), so post it to the message loop instead.
556     stored_frames_.insert(stored_frames_.end(), frames->begin(), frames->end());
557     frames->weak_clear();
558     PostCallback();
559     return OK;
560   }
561
562   virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
563                          const CompletionCallback& callback) OVERRIDE {
564     read_callback_ = callback;
565     read_frames_ = frames;
566     if (done_)
567       PostCallback();
568     return ERR_IO_PENDING;
569   }
570
571  private:
572   void PostCallback() {
573     base::MessageLoop::current()->PostTask(
574         FROM_HERE,
575         base::Bind(&EchoeyFakeWebSocketStream::DoCallback,
576                    base::Unretained(this)));
577   }
578
579   void DoCallback() {
580     if (done_) {
581       read_callback_.Run(ERR_CONNECTION_CLOSED);
582     } else if (!stored_frames_.empty()) {
583       done_ = MoveFrames(read_frames_);
584       read_frames_ = NULL;
585       read_callback_.Run(OK);
586     }
587   }
588
589   // Copy the frames stored in stored_frames_ to |out|, while clearing the
590   // "masked" header bit. Returns true if a Close Frame was seen, false
591   // otherwise.
592   bool MoveFrames(ScopedVector<WebSocketFrame>* out) {
593     bool seen_close = false;
594     *out = stored_frames_.Pass();
595     for (ScopedVector<WebSocketFrame>::iterator it = out->begin();
596          it != out->end();
597          ++it) {
598       WebSocketFrameHeader& header = (*it)->header;
599       header.masked = false;
600       if (header.opcode == WebSocketFrameHeader::kOpCodeClose)
601         seen_close = true;
602     }
603     return seen_close;
604   }
605
606   ScopedVector<WebSocketFrame> stored_frames_;
607   CompletionCallback read_callback_;
608   // Owned by the caller of ReadFrames().
609   ScopedVector<WebSocketFrame>* read_frames_;
610   // True if we should close the connection.
611   bool done_;
612 };
613
614 // A FakeWebSocketStream where writes trigger a connection reset.
615 // This differs from UnWriteableFakeWebSocketStream in that it is asynchronous
616 // and triggers ReadFrames to return a reset as well. Tests using this need to
617 // run the message loop. There are two tricky parts here:
618 // 1. Calling the write callback may call Close(), after which the read callback
619 //    should not be called.
620 // 2. Calling either callback may delete the stream altogether.
621 class ResetOnWriteFakeWebSocketStream : public FakeWebSocketStream {
622  public:
623   ResetOnWriteFakeWebSocketStream() : closed_(false), weak_ptr_factory_(this) {}
624
625   virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
626                           const CompletionCallback& callback) OVERRIDE {
627     base::MessageLoop::current()->PostTask(
628         FROM_HERE,
629         base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
630                    weak_ptr_factory_.GetWeakPtr(),
631                    callback,
632                    ERR_CONNECTION_RESET));
633     base::MessageLoop::current()->PostTask(
634         FROM_HERE,
635         base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
636                    weak_ptr_factory_.GetWeakPtr(),
637                    read_callback_,
638                    ERR_CONNECTION_RESET));
639     return ERR_IO_PENDING;
640   }
641
642   virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
643                          const CompletionCallback& callback) OVERRIDE {
644     read_callback_ = callback;
645     return ERR_IO_PENDING;
646   }
647
648   virtual void Close() OVERRIDE { closed_ = true; }
649
650  private:
651   void CallCallbackUnlessClosed(const CompletionCallback& callback, int value) {
652     if (!closed_)
653       callback.Run(value);
654   }
655
656   CompletionCallback read_callback_;
657   bool closed_;
658   // An IO error can result in the socket being deleted, so we use weak pointers
659   // to ensure correct behaviour in that case.
660   base::WeakPtrFactory<ResetOnWriteFakeWebSocketStream> weak_ptr_factory_;
661 };
662
663 // This mock is for verifying that WebSocket protocol semantics are obeyed (to
664 // the extent that they are implemented in WebSocketCommon).
665 class MockWebSocketStream : public WebSocketStream {
666  public:
667   MOCK_METHOD2(ReadFrames,
668                int(ScopedVector<WebSocketFrame>* frames,
669                    const CompletionCallback& callback));
670   MOCK_METHOD2(WriteFrames,
671                int(ScopedVector<WebSocketFrame>* frames,
672                    const CompletionCallback& callback));
673   MOCK_METHOD0(Close, void());
674   MOCK_CONST_METHOD0(GetSubProtocol, std::string());
675   MOCK_CONST_METHOD0(GetExtensions, std::string());
676   MOCK_METHOD0(AsWebSocketStream, WebSocketStream*());
677 };
678
679 struct ArgumentCopyingWebSocketStreamCreator {
680   scoped_ptr<WebSocketStreamRequest> Create(
681       const GURL& socket_url,
682       const std::vector<std::string>& requested_subprotocols,
683       const GURL& origin,
684       URLRequestContext* url_request_context,
685       const BoundNetLog& net_log,
686       scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate) {
687     this->socket_url = socket_url;
688     this->requested_subprotocols = requested_subprotocols;
689     this->origin = origin;
690     this->url_request_context = url_request_context;
691     this->net_log = net_log;
692     this->connect_delegate = connect_delegate.Pass();
693     return make_scoped_ptr(new WebSocketStreamRequest);
694   }
695
696   GURL socket_url;
697   GURL origin;
698   std::vector<std::string> requested_subprotocols;
699   URLRequestContext* url_request_context;
700   BoundNetLog net_log;
701   scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate;
702 };
703
704 // Converts a std::string to a std::vector<char>. For test purposes, it is
705 // convenient to be able to specify data as a string, but the
706 // WebSocketEventInterface requires the vector<char> type.
707 std::vector<char> AsVector(const std::string& s) {
708   return std::vector<char>(s.begin(), s.end());
709 }
710
711 // Base class for all test fixtures.
712 class WebSocketChannelTest : public ::testing::Test {
713  protected:
714   WebSocketChannelTest() : stream_(new FakeWebSocketStream) {}
715
716   // Creates a new WebSocketChannel and connects it, using the settings stored
717   // in |connect_data_|.
718   void CreateChannelAndConnect() {
719     channel_.reset(new WebSocketChannel(CreateEventInterface(),
720                                         &connect_data_.url_request_context));
721     channel_->SendAddChannelRequestForTesting(
722         connect_data_.socket_url,
723         connect_data_.requested_subprotocols,
724         connect_data_.origin,
725         base::Bind(&ArgumentCopyingWebSocketStreamCreator::Create,
726                    base::Unretained(&connect_data_.creator)));
727   }
728
729   // Same as CreateChannelAndConnect(), but calls the on_success callback as
730   // well. This method is virtual so that subclasses can also set the stream.
731   virtual void CreateChannelAndConnectSuccessfully() {
732     CreateChannelAndConnect();
733     connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
734   }
735
736   // Returns a WebSocketEventInterface to be passed to the WebSocketChannel.
737   // This implementation returns a newly-created fake. Subclasses may return a
738   // mock instead.
739   virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() {
740     return scoped_ptr<WebSocketEventInterface>(new FakeWebSocketEventInterface);
741   }
742
743   // This method serves no other purpose than to provide a nice syntax for
744   // assigning to stream_. class T must be a subclass of WebSocketStream or you
745   // will have unpleasant compile errors.
746   template <class T>
747   void set_stream(scoped_ptr<T> stream) {
748     // Since the definition of "PassAs" depends on the type T, the C++ standard
749     // requires the "template" keyword to indicate that "PassAs" should be
750     // parsed as a template method.
751     stream_ = stream.template PassAs<WebSocketStream>();
752   }
753
754   // A struct containing the data that will be used to connect the channel.
755   // Grouped for readability.
756   struct ConnectData {
757     ConnectData() : socket_url("ws://ws/"), origin("http://ws/") {}
758
759     // URLRequestContext object.
760     URLRequestContext url_request_context;
761
762     // URL to (pretend to) connect to.
763     GURL socket_url;
764     // Requested protocols for the request.
765     std::vector<std::string> requested_subprotocols;
766     // Origin of the request
767     GURL origin;
768
769     // A fake WebSocketStreamCreator that just records its arguments.
770     ArgumentCopyingWebSocketStreamCreator creator;
771   };
772   ConnectData connect_data_;
773
774   // The channel we are testing. Not initialised until SetChannel() is called.
775   scoped_ptr<WebSocketChannel> channel_;
776
777   // A mock or fake stream for tests that need one.
778   scoped_ptr<WebSocketStream> stream_;
779 };
780
781 // enum of WebSocketEventInterface calls. These are intended to be or'd together
782 // in order to instruct WebSocketChannelDeletingTest when it should fail.
783 enum EventInterfaceCall {
784   EVENT_ON_ADD_CHANNEL_RESPONSE = 0x1,
785   EVENT_ON_DATA_FRAME = 0x2,
786   EVENT_ON_FLOW_CONTROL = 0x4,
787   EVENT_ON_CLOSING_HANDSHAKE = 0x8,
788   EVENT_ON_FAIL_CHANNEL = 0x10,
789   EVENT_ON_DROP_CHANNEL = 0x20,
790   EVENT_ON_START_OPENING_HANDSHAKE = 0x40,
791   EVENT_ON_FINISH_OPENING_HANDSHAKE = 0x80,
792 };
793
794 class WebSocketChannelDeletingTest : public WebSocketChannelTest {
795  public:
796   ChannelState DeleteIfDeleting(EventInterfaceCall call) {
797     if (deleting_ & call) {
798       channel_.reset();
799       return CHANNEL_DELETED;
800     } else {
801       return CHANNEL_ALIVE;
802     }
803   }
804
805  protected:
806   WebSocketChannelDeletingTest()
807       : deleting_(EVENT_ON_ADD_CHANNEL_RESPONSE | EVENT_ON_DATA_FRAME |
808                   EVENT_ON_FLOW_CONTROL |
809                   EVENT_ON_CLOSING_HANDSHAKE |
810                   EVENT_ON_FAIL_CHANNEL |
811                   EVENT_ON_DROP_CHANNEL |
812                   EVENT_ON_START_OPENING_HANDSHAKE |
813                   EVENT_ON_FINISH_OPENING_HANDSHAKE) {}
814   // Create a ChannelDeletingFakeWebSocketEventInterface. Defined out-of-line to
815   // avoid circular dependency.
816   virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() OVERRIDE;
817
818   // Tests can set deleting_ to a bitmap of EventInterfaceCall members that they
819   // want to cause Channel deletion. The default is for all calls to cause
820   // deletion.
821   int deleting_;
822 };
823
824 // A FakeWebSocketEventInterface that deletes the WebSocketChannel on failure to
825 // connect.
826 class ChannelDeletingFakeWebSocketEventInterface
827     : public FakeWebSocketEventInterface {
828  public:
829   ChannelDeletingFakeWebSocketEventInterface(
830       WebSocketChannelDeletingTest* fixture)
831       : fixture_(fixture) {}
832
833   virtual ChannelState OnAddChannelResponse(
834       bool fail,
835       const std::string& selected_protocol,
836       const std::string& extensions) OVERRIDE {
837     return fixture_->DeleteIfDeleting(EVENT_ON_ADD_CHANNEL_RESPONSE);
838   }
839
840   virtual ChannelState OnDataFrame(bool fin,
841                                    WebSocketMessageType type,
842                                    const std::vector<char>& data) OVERRIDE {
843     return fixture_->DeleteIfDeleting(EVENT_ON_DATA_FRAME);
844   }
845
846   virtual ChannelState OnFlowControl(int64 quota) OVERRIDE {
847     return fixture_->DeleteIfDeleting(EVENT_ON_FLOW_CONTROL);
848   }
849
850   virtual ChannelState OnClosingHandshake() OVERRIDE {
851     return fixture_->DeleteIfDeleting(EVENT_ON_CLOSING_HANDSHAKE);
852   }
853
854   virtual ChannelState OnFailChannel(const std::string& message) OVERRIDE {
855     return fixture_->DeleteIfDeleting(EVENT_ON_FAIL_CHANNEL);
856   }
857
858   virtual ChannelState OnDropChannel(bool was_clean,
859                                      uint16 code,
860                                      const std::string& reason) OVERRIDE {
861     return fixture_->DeleteIfDeleting(EVENT_ON_DROP_CHANNEL);
862   }
863
864   virtual ChannelState OnStartOpeningHandshake(
865       scoped_ptr<WebSocketHandshakeRequestInfo> request) OVERRIDE {
866     return fixture_->DeleteIfDeleting(EVENT_ON_START_OPENING_HANDSHAKE);
867   }
868   virtual ChannelState OnFinishOpeningHandshake(
869       scoped_ptr<WebSocketHandshakeResponseInfo> response) OVERRIDE {
870     return fixture_->DeleteIfDeleting(EVENT_ON_FINISH_OPENING_HANDSHAKE);
871   }
872
873  private:
874   // A pointer to the test fixture. Owned by the test harness; this object will
875   // be deleted before it is.
876   WebSocketChannelDeletingTest* fixture_;
877 };
878
879 scoped_ptr<WebSocketEventInterface>
880 WebSocketChannelDeletingTest::CreateEventInterface() {
881   return scoped_ptr<WebSocketEventInterface>(
882       new ChannelDeletingFakeWebSocketEventInterface(this));
883 }
884
885 // Base class for tests which verify that EventInterface methods are called
886 // appropriately.
887 class WebSocketChannelEventInterfaceTest : public WebSocketChannelTest {
888  protected:
889   WebSocketChannelEventInterfaceTest()
890       : event_interface_(new StrictMock<MockWebSocketEventInterface>) {
891     DefaultValue<ChannelState>::Set(CHANNEL_ALIVE);
892     ON_CALL(*event_interface_, OnAddChannelResponse(true, _, _))
893         .WillByDefault(Return(CHANNEL_DELETED));
894     ON_CALL(*event_interface_, OnDropChannel(_, _, _))
895         .WillByDefault(Return(CHANNEL_DELETED));
896     ON_CALL(*event_interface_, OnFailChannel(_))
897         .WillByDefault(Return(CHANNEL_DELETED));
898   }
899
900   virtual ~WebSocketChannelEventInterfaceTest() {
901     DefaultValue<ChannelState>::Clear();
902   }
903
904   // Tests using this fixture must set expectations on the event_interface_ mock
905   // object before calling CreateChannelAndConnect() or
906   // CreateChannelAndConnectSuccessfully(). This will only work once per test
907   // case, but once should be enough.
908   virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() OVERRIDE {
909     return scoped_ptr<WebSocketEventInterface>(event_interface_.release());
910   }
911
912   scoped_ptr<MockWebSocketEventInterface> event_interface_;
913 };
914
915 // Base class for tests which verify that WebSocketStream methods are called
916 // appropriately by using a MockWebSocketStream.
917 class WebSocketChannelStreamTest : public WebSocketChannelTest {
918  protected:
919   WebSocketChannelStreamTest()
920       : mock_stream_(new StrictMock<MockWebSocketStream>) {}
921
922   virtual void CreateChannelAndConnectSuccessfully() OVERRIDE {
923     set_stream(mock_stream_.Pass());
924     WebSocketChannelTest::CreateChannelAndConnectSuccessfully();
925   }
926
927   scoped_ptr<MockWebSocketStream> mock_stream_;
928 };
929
930 // Fixture for tests which test UTF-8 validation of sent Text frames via the
931 // EventInterface.
932 class WebSocketChannelSendUtf8Test
933     : public WebSocketChannelEventInterfaceTest {
934  public:
935   virtual void SetUp() {
936     set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
937     // For the purpose of the tests using this fixture, it doesn't matter
938     // whether these methods are called or not.
939     EXPECT_CALL(*event_interface_, OnAddChannelResponse(_, _, _))
940         .Times(AnyNumber());
941     EXPECT_CALL(*event_interface_, OnFlowControl(_))
942         .Times(AnyNumber());
943   }
944 };
945
946 // Fixture for tests which test UTF-8 validation of received Text frames using a
947 // mock WebSocketStream.
948 class WebSocketChannelReceiveUtf8Test : public WebSocketChannelStreamTest {
949  public:
950   virtual void SetUp() {
951     // For the purpose of the tests using this fixture, it doesn't matter
952     // whether these methods are called or not.
953     EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
954     EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
955   }
956 };
957
958 // Simple test that everything that should be passed to the creator function is
959 // passed to the creator function.
960 TEST_F(WebSocketChannelTest, EverythingIsPassedToTheCreatorFunction) {
961   connect_data_.socket_url = GURL("ws://example.com/test");
962   connect_data_.origin = GURL("http://example.com/test");
963   connect_data_.requested_subprotocols.push_back("Sinbad");
964
965   CreateChannelAndConnect();
966
967   const ArgumentCopyingWebSocketStreamCreator& actual = connect_data_.creator;
968
969   EXPECT_EQ(&connect_data_.url_request_context, actual.url_request_context);
970
971   EXPECT_EQ(connect_data_.socket_url, actual.socket_url);
972   EXPECT_EQ(connect_data_.requested_subprotocols,
973             actual.requested_subprotocols);
974   EXPECT_EQ(connect_data_.origin, actual.origin);
975 }
976
977 // Verify that calling SendFlowControl before the connection is established does
978 // not cause a crash.
979 TEST_F(WebSocketChannelTest, SendFlowControlDuringHandshakeOkay) {
980   CreateChannelAndConnect();
981   ASSERT_TRUE(channel_);
982   channel_->SendFlowControl(65536);
983 }
984
985 // Any WebSocketEventInterface methods can delete the WebSocketChannel and
986 // return CHANNEL_DELETED. The WebSocketChannelDeletingTests are intended to
987 // verify that there are no use-after-free bugs when this happens. Problems will
988 // probably only be found when running under Address Sanitizer or a similar
989 // tool.
990 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseFail) {
991   CreateChannelAndConnect();
992   EXPECT_TRUE(channel_);
993   connect_data_.creator.connect_delegate->OnFailure("bye");
994   EXPECT_EQ(NULL, channel_.get());
995 }
996
997 // Deletion is possible (due to IPC failure) even if the connect succeeds.
998 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseSuccess) {
999   CreateChannelAndConnectSuccessfully();
1000   EXPECT_EQ(NULL, channel_.get());
1001 }
1002
1003 TEST_F(WebSocketChannelDeletingTest, OnDataFrameSync) {
1004   scoped_ptr<ReadableFakeWebSocketStream> stream(
1005       new ReadableFakeWebSocketStream);
1006   static const InitFrame frames[] = {
1007       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1008   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1009   set_stream(stream.Pass());
1010   deleting_ = EVENT_ON_DATA_FRAME;
1011
1012   CreateChannelAndConnectSuccessfully();
1013   EXPECT_EQ(NULL, channel_.get());
1014 }
1015
1016 TEST_F(WebSocketChannelDeletingTest, OnDataFrameAsync) {
1017   scoped_ptr<ReadableFakeWebSocketStream> stream(
1018       new ReadableFakeWebSocketStream);
1019   static const InitFrame frames[] = {
1020       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1021   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1022   set_stream(stream.Pass());
1023   deleting_ = EVENT_ON_DATA_FRAME;
1024
1025   CreateChannelAndConnectSuccessfully();
1026   EXPECT_TRUE(channel_);
1027   base::MessageLoop::current()->RunUntilIdle();
1028   EXPECT_EQ(NULL, channel_.get());
1029 }
1030
1031 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterConnect) {
1032   deleting_ = EVENT_ON_FLOW_CONTROL;
1033
1034   CreateChannelAndConnectSuccessfully();
1035   EXPECT_EQ(NULL, channel_.get());
1036 }
1037
1038 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterSend) {
1039   set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1040   // Avoid deleting the channel yet.
1041   deleting_ = EVENT_ON_FAIL_CHANNEL | EVENT_ON_DROP_CHANNEL;
1042   CreateChannelAndConnectSuccessfully();
1043   ASSERT_TRUE(channel_);
1044   deleting_ = EVENT_ON_FLOW_CONTROL;
1045   channel_->SendFrame(true,
1046                       WebSocketFrameHeader::kOpCodeText,
1047                       std::vector<char>(kDefaultInitialQuota, 'B'));
1048   EXPECT_EQ(NULL, channel_.get());
1049 }
1050
1051 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeSync) {
1052   scoped_ptr<ReadableFakeWebSocketStream> stream(
1053       new ReadableFakeWebSocketStream);
1054   static const InitFrame frames[] = {
1055       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1056        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
1057   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1058   set_stream(stream.Pass());
1059   deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
1060   CreateChannelAndConnectSuccessfully();
1061   EXPECT_EQ(NULL, channel_.get());
1062 }
1063
1064 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeAsync) {
1065   scoped_ptr<ReadableFakeWebSocketStream> stream(
1066       new ReadableFakeWebSocketStream);
1067   static const InitFrame frames[] = {
1068       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1069        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
1070   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1071   set_stream(stream.Pass());
1072   deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
1073   CreateChannelAndConnectSuccessfully();
1074   ASSERT_TRUE(channel_);
1075   base::MessageLoop::current()->RunUntilIdle();
1076   EXPECT_EQ(NULL, channel_.get());
1077 }
1078
1079 TEST_F(WebSocketChannelDeletingTest, OnDropChannelWriteError) {
1080   set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
1081   deleting_ = EVENT_ON_DROP_CHANNEL;
1082   CreateChannelAndConnectSuccessfully();
1083   ASSERT_TRUE(channel_);
1084   channel_->SendFrame(
1085       true, WebSocketFrameHeader::kOpCodeText, AsVector("this will fail"));
1086   EXPECT_EQ(NULL, channel_.get());
1087 }
1088
1089 TEST_F(WebSocketChannelDeletingTest, OnDropChannelReadError) {
1090   scoped_ptr<ReadableFakeWebSocketStream> stream(
1091       new ReadableFakeWebSocketStream);
1092   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1093                                  ERR_FAILED);
1094   set_stream(stream.Pass());
1095   deleting_ = EVENT_ON_DROP_CHANNEL;
1096   CreateChannelAndConnectSuccessfully();
1097   ASSERT_TRUE(channel_);
1098   base::MessageLoop::current()->RunUntilIdle();
1099   EXPECT_EQ(NULL, channel_.get());
1100 }
1101
1102 TEST_F(WebSocketChannelDeletingTest, OnNotifyStartOpeningHandshakeError) {
1103   scoped_ptr<ReadableFakeWebSocketStream> stream(
1104       new ReadableFakeWebSocketStream);
1105   static const InitFrame frames[] = {
1106       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1107   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1108   set_stream(stream.Pass());
1109   deleting_ = EVENT_ON_START_OPENING_HANDSHAKE;
1110
1111   CreateChannelAndConnectSuccessfully();
1112   ASSERT_TRUE(channel_);
1113   channel_->OnStartOpeningHandshake(scoped_ptr<WebSocketHandshakeRequestInfo>(
1114       new WebSocketHandshakeRequestInfo(GURL("http://www.example.com/"),
1115                                         base::Time())));
1116   base::MessageLoop::current()->RunUntilIdle();
1117   EXPECT_EQ(NULL, channel_.get());
1118 }
1119
1120 TEST_F(WebSocketChannelDeletingTest, OnNotifyFinishOpeningHandshakeError) {
1121   scoped_ptr<ReadableFakeWebSocketStream> stream(
1122       new ReadableFakeWebSocketStream);
1123   static const InitFrame frames[] = {
1124       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1125   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1126   set_stream(stream.Pass());
1127   deleting_ = EVENT_ON_FINISH_OPENING_HANDSHAKE;
1128
1129   CreateChannelAndConnectSuccessfully();
1130   ASSERT_TRUE(channel_);
1131   scoped_refptr<HttpResponseHeaders> response_headers(
1132       new HttpResponseHeaders(""));
1133   channel_->OnFinishOpeningHandshake(scoped_ptr<WebSocketHandshakeResponseInfo>(
1134       new WebSocketHandshakeResponseInfo(GURL("http://www.example.com/"),
1135                                          200,
1136                                          "OK",
1137                                          response_headers,
1138                                          base::Time())));
1139   base::MessageLoop::current()->RunUntilIdle();
1140   EXPECT_EQ(NULL, channel_.get());
1141 }
1142
1143 TEST_F(WebSocketChannelDeletingTest, FailChannelInSendFrame) {
1144   set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1145   deleting_ = EVENT_ON_FAIL_CHANNEL;
1146   CreateChannelAndConnectSuccessfully();
1147   ASSERT_TRUE(channel_);
1148   channel_->SendFrame(true,
1149                       WebSocketFrameHeader::kOpCodeText,
1150                       std::vector<char>(kDefaultInitialQuota * 2, 'T'));
1151   EXPECT_EQ(NULL, channel_.get());
1152 }
1153
1154 TEST_F(WebSocketChannelDeletingTest, FailChannelInOnReadDone) {
1155   scoped_ptr<ReadableFakeWebSocketStream> stream(
1156       new ReadableFakeWebSocketStream);
1157   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1158                                  ERR_WS_PROTOCOL_ERROR);
1159   set_stream(stream.Pass());
1160   deleting_ = EVENT_ON_FAIL_CHANNEL;
1161   CreateChannelAndConnectSuccessfully();
1162   ASSERT_TRUE(channel_);
1163   base::MessageLoop::current()->RunUntilIdle();
1164   EXPECT_EQ(NULL, channel_.get());
1165 }
1166
1167 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToMaskedFrame) {
1168   scoped_ptr<ReadableFakeWebSocketStream> stream(
1169       new ReadableFakeWebSocketStream);
1170   static const InitFrame frames[] = {
1171       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1172   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1173   set_stream(stream.Pass());
1174   deleting_ = EVENT_ON_FAIL_CHANNEL;
1175
1176   CreateChannelAndConnectSuccessfully();
1177   EXPECT_EQ(NULL, channel_.get());
1178 }
1179
1180 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToBadControlFrame) {
1181   scoped_ptr<ReadableFakeWebSocketStream> stream(
1182       new ReadableFakeWebSocketStream);
1183   static const InitFrame frames[] = {
1184       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1185   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1186   set_stream(stream.Pass());
1187   deleting_ = EVENT_ON_FAIL_CHANNEL;
1188
1189   CreateChannelAndConnectSuccessfully();
1190   EXPECT_EQ(NULL, channel_.get());
1191 }
1192
1193 // Version of above test with NULL data.
1194 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToBadControlFrameNull) {
1195   scoped_ptr<ReadableFakeWebSocketStream> stream(
1196       new ReadableFakeWebSocketStream);
1197   static const InitFrame frames[] = {
1198       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1199   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1200   set_stream(stream.Pass());
1201   deleting_ = EVENT_ON_FAIL_CHANNEL;
1202
1203   CreateChannelAndConnectSuccessfully();
1204   EXPECT_EQ(NULL, channel_.get());
1205 }
1206
1207 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToPongAfterClose) {
1208   scoped_ptr<ReadableFakeWebSocketStream> stream(
1209       new ReadableFakeWebSocketStream);
1210   static const InitFrame frames[] = {
1211       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
1212        CLOSE_DATA(NORMAL_CLOSURE, "Success")},
1213       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1214   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1215   set_stream(stream.Pass());
1216   deleting_ = EVENT_ON_FAIL_CHANNEL;
1217
1218   CreateChannelAndConnectSuccessfully();
1219   EXPECT_EQ(NULL, channel_.get());
1220 }
1221
1222 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToPongAfterCloseNull) {
1223   scoped_ptr<ReadableFakeWebSocketStream> stream(
1224       new ReadableFakeWebSocketStream);
1225   static const InitFrame frames[] = {
1226       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
1227        CLOSE_DATA(NORMAL_CLOSURE, "Success")},
1228       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1229   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1230   set_stream(stream.Pass());
1231   deleting_ = EVENT_ON_FAIL_CHANNEL;
1232
1233   CreateChannelAndConnectSuccessfully();
1234   EXPECT_EQ(NULL, channel_.get());
1235 }
1236
1237 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToUnknownOpCode) {
1238   scoped_ptr<ReadableFakeWebSocketStream> stream(
1239       new ReadableFakeWebSocketStream);
1240   static const InitFrame frames[] = {{FINAL_FRAME, 0x7, NOT_MASKED, ""}};
1241   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1242   set_stream(stream.Pass());
1243   deleting_ = EVENT_ON_FAIL_CHANNEL;
1244
1245   CreateChannelAndConnectSuccessfully();
1246   EXPECT_EQ(NULL, channel_.get());
1247 }
1248
1249 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToUnknownOpCodeNull) {
1250   scoped_ptr<ReadableFakeWebSocketStream> stream(
1251       new ReadableFakeWebSocketStream);
1252   static const InitFrame frames[] = {{FINAL_FRAME, 0x7, NOT_MASKED, NULL}};
1253   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1254   set_stream(stream.Pass());
1255   deleting_ = EVENT_ON_FAIL_CHANNEL;
1256
1257   CreateChannelAndConnectSuccessfully();
1258   EXPECT_EQ(NULL, channel_.get());
1259 }
1260
1261 TEST_F(WebSocketChannelDeletingTest, FailChannelDueInvalidCloseReason) {
1262   scoped_ptr<ReadableFakeWebSocketStream> stream(
1263       new ReadableFakeWebSocketStream);
1264   static const InitFrame frames[] = {
1265       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1266        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
1267   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1268   set_stream(stream.Pass());
1269   deleting_ = EVENT_ON_FAIL_CHANNEL;
1270
1271   CreateChannelAndConnectSuccessfully();
1272   EXPECT_EQ(NULL, channel_.get());
1273 }
1274
1275 TEST_F(WebSocketChannelEventInterfaceTest, ConnectSuccessReported) {
1276   // false means success.
1277   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, "", ""));
1278   // OnFlowControl is always called immediately after connect to provide initial
1279   // quota to the renderer.
1280   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1281
1282   CreateChannelAndConnect();
1283
1284   connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
1285 }
1286
1287 TEST_F(WebSocketChannelEventInterfaceTest, ConnectFailureReported) {
1288   EXPECT_CALL(*event_interface_, OnFailChannel("hello"));
1289
1290   CreateChannelAndConnect();
1291
1292   connect_data_.creator.connect_delegate->OnFailure("hello");
1293 }
1294
1295 TEST_F(WebSocketChannelEventInterfaceTest, NonWebSocketSchemeRejected) {
1296   EXPECT_CALL(*event_interface_, OnAddChannelResponse(true, "", ""));
1297   connect_data_.socket_url = GURL("http://www.google.com/");
1298   CreateChannelAndConnect();
1299 }
1300
1301 TEST_F(WebSocketChannelEventInterfaceTest, ProtocolPassed) {
1302   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, "Bob", ""));
1303   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1304
1305   CreateChannelAndConnect();
1306
1307   connect_data_.creator.connect_delegate->OnSuccess(
1308       scoped_ptr<WebSocketStream>(new FakeWebSocketStream("Bob", "")));
1309 }
1310
1311 TEST_F(WebSocketChannelEventInterfaceTest, ExtensionsPassed) {
1312   EXPECT_CALL(*event_interface_,
1313               OnAddChannelResponse(false, "", "extension1, extension2"));
1314   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1315
1316   CreateChannelAndConnect();
1317
1318   connect_data_.creator.connect_delegate->OnSuccess(scoped_ptr<WebSocketStream>(
1319       new FakeWebSocketStream("", "extension1, extension2")));
1320 }
1321
1322 // The first frames from the server can arrive together with the handshake, in
1323 // which case they will be available as soon as ReadFrames() is called the first
1324 // time.
1325 TEST_F(WebSocketChannelEventInterfaceTest, DataLeftFromHandshake) {
1326   scoped_ptr<ReadableFakeWebSocketStream> stream(
1327       new ReadableFakeWebSocketStream);
1328   static const InitFrame frames[] = {
1329       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1330   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1331   set_stream(stream.Pass());
1332   {
1333     InSequence s;
1334     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1335     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1336     EXPECT_CALL(
1337         *event_interface_,
1338         OnDataFrame(
1339             true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1340   }
1341
1342   CreateChannelAndConnectSuccessfully();
1343 }
1344
1345 // A remote server could accept the handshake, but then immediately send a
1346 // Close frame.
1347 TEST_F(WebSocketChannelEventInterfaceTest, CloseAfterHandshake) {
1348   scoped_ptr<ReadableFakeWebSocketStream> stream(
1349       new ReadableFakeWebSocketStream);
1350   static const InitFrame frames[] = {
1351       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1352        NOT_MASKED,  CLOSE_DATA(SERVER_ERROR, "Internal Server Error")}};
1353   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1354   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1355                                  ERR_CONNECTION_CLOSED);
1356   set_stream(stream.Pass());
1357   {
1358     InSequence s;
1359     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1360     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1361     EXPECT_CALL(*event_interface_, OnClosingHandshake());
1362     EXPECT_CALL(
1363         *event_interface_,
1364         OnDropChannel(
1365             true, kWebSocketErrorInternalServerError, "Internal Server Error"));
1366   }
1367
1368   CreateChannelAndConnectSuccessfully();
1369 }
1370
1371 // A remote server could close the connection immediately after sending the
1372 // handshake response (most likely a bug in the server).
1373 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionCloseAfterHandshake) {
1374   scoped_ptr<ReadableFakeWebSocketStream> stream(
1375       new ReadableFakeWebSocketStream);
1376   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1377                                  ERR_CONNECTION_CLOSED);
1378   set_stream(stream.Pass());
1379   {
1380     InSequence s;
1381     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1382     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1383     EXPECT_CALL(*event_interface_,
1384                 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1385   }
1386
1387   CreateChannelAndConnectSuccessfully();
1388 }
1389
1390 TEST_F(WebSocketChannelEventInterfaceTest, NormalAsyncRead) {
1391   scoped_ptr<ReadableFakeWebSocketStream> stream(
1392       new ReadableFakeWebSocketStream);
1393   static const InitFrame frames[] = {
1394       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1395   // We use this checkpoint object to verify that the callback isn't called
1396   // until we expect it to be.
1397   Checkpoint checkpoint;
1398   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1399   set_stream(stream.Pass());
1400   {
1401     InSequence s;
1402     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1403     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1404     EXPECT_CALL(checkpoint, Call(1));
1405     EXPECT_CALL(
1406         *event_interface_,
1407         OnDataFrame(
1408             true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1409     EXPECT_CALL(checkpoint, Call(2));
1410   }
1411
1412   CreateChannelAndConnectSuccessfully();
1413   checkpoint.Call(1);
1414   base::MessageLoop::current()->RunUntilIdle();
1415   checkpoint.Call(2);
1416 }
1417
1418 // Extra data can arrive while a read is being processed, resulting in the next
1419 // read completing synchronously.
1420 TEST_F(WebSocketChannelEventInterfaceTest, AsyncThenSyncRead) {
1421   scoped_ptr<ReadableFakeWebSocketStream> stream(
1422       new ReadableFakeWebSocketStream);
1423   static const InitFrame frames1[] = {
1424       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1425   static const InitFrame frames2[] = {
1426       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "WORLD"}};
1427   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1428   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames2);
1429   set_stream(stream.Pass());
1430   {
1431     InSequence s;
1432     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1433     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1434     EXPECT_CALL(
1435         *event_interface_,
1436         OnDataFrame(
1437             true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1438     EXPECT_CALL(
1439         *event_interface_,
1440         OnDataFrame(
1441             true, WebSocketFrameHeader::kOpCodeText, AsVector("WORLD")));
1442   }
1443
1444   CreateChannelAndConnectSuccessfully();
1445   base::MessageLoop::current()->RunUntilIdle();
1446 }
1447
1448 // Data frames are delivered the same regardless of how many reads they arrive
1449 // as.
1450 TEST_F(WebSocketChannelEventInterfaceTest, FragmentedMessage) {
1451   scoped_ptr<ReadableFakeWebSocketStream> stream(
1452       new ReadableFakeWebSocketStream);
1453   // Here we have one message which arrived in five frames split across three
1454   // reads. It may have been reframed on arrival, but this class doesn't care
1455   // about that.
1456   static const InitFrame frames1[] = {
1457       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "THREE"},
1458       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1459        NOT_MASKED,      " "}};
1460   static const InitFrame frames2[] = {
1461       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1462        NOT_MASKED,      "SMALL"}};
1463   static const InitFrame frames3[] = {
1464       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1465        NOT_MASKED,      " "},
1466       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1467        NOT_MASKED,  "FRAMES"}};
1468   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1469   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1470   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1471   set_stream(stream.Pass());
1472   {
1473     InSequence s;
1474     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1475     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1476     EXPECT_CALL(
1477         *event_interface_,
1478         OnDataFrame(
1479             false, WebSocketFrameHeader::kOpCodeText, AsVector("THREE")));
1480     EXPECT_CALL(
1481         *event_interface_,
1482         OnDataFrame(
1483             false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1484     EXPECT_CALL(*event_interface_,
1485                 OnDataFrame(false,
1486                             WebSocketFrameHeader::kOpCodeContinuation,
1487                             AsVector("SMALL")));
1488     EXPECT_CALL(
1489         *event_interface_,
1490         OnDataFrame(
1491             false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1492     EXPECT_CALL(*event_interface_,
1493                 OnDataFrame(true,
1494                             WebSocketFrameHeader::kOpCodeContinuation,
1495                             AsVector("FRAMES")));
1496   }
1497
1498   CreateChannelAndConnectSuccessfully();
1499   base::MessageLoop::current()->RunUntilIdle();
1500 }
1501
1502 // A message can consist of one frame with NULL payload.
1503 TEST_F(WebSocketChannelEventInterfaceTest, NullMessage) {
1504   scoped_ptr<ReadableFakeWebSocketStream> stream(
1505       new ReadableFakeWebSocketStream);
1506   static const InitFrame frames[] = {
1507       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, NULL}};
1508   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1509   set_stream(stream.Pass());
1510   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1511   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1512   EXPECT_CALL(
1513       *event_interface_,
1514       OnDataFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("")));
1515   CreateChannelAndConnectSuccessfully();
1516 }
1517
1518 // A control frame is not permitted to be split into multiple frames. RFC6455
1519 // 5.5 "All control frames ... MUST NOT be fragmented."
1520 TEST_F(WebSocketChannelEventInterfaceTest, MultiFrameControlMessageIsRejected) {
1521   scoped_ptr<ReadableFakeWebSocketStream> stream(
1522       new ReadableFakeWebSocketStream);
1523   static const InitFrame frames[] = {
1524       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePing, NOT_MASKED, "Pi"},
1525       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1526        NOT_MASKED,  "ng"}};
1527   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1528   set_stream(stream.Pass());
1529   {
1530     InSequence s;
1531     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1532     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1533     EXPECT_CALL(*event_interface_,
1534                 OnFailChannel("Received fragmented control frame: opcode = 9"));
1535   }
1536
1537   CreateChannelAndConnectSuccessfully();
1538   base::MessageLoop::current()->RunUntilIdle();
1539 }
1540
1541 // Connection closed by the remote host without a closing handshake.
1542 TEST_F(WebSocketChannelEventInterfaceTest, AsyncAbnormalClosure) {
1543   scoped_ptr<ReadableFakeWebSocketStream> stream(
1544       new ReadableFakeWebSocketStream);
1545   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1546                                  ERR_CONNECTION_CLOSED);
1547   set_stream(stream.Pass());
1548   {
1549     InSequence s;
1550     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1551     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1552     EXPECT_CALL(*event_interface_,
1553                 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1554   }
1555
1556   CreateChannelAndConnectSuccessfully();
1557   base::MessageLoop::current()->RunUntilIdle();
1558 }
1559
1560 // A connection reset should produce the same event as an unexpected closure.
1561 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionReset) {
1562   scoped_ptr<ReadableFakeWebSocketStream> stream(
1563       new ReadableFakeWebSocketStream);
1564   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1565                                  ERR_CONNECTION_RESET);
1566   set_stream(stream.Pass());
1567   {
1568     InSequence s;
1569     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1570     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1571     EXPECT_CALL(*event_interface_,
1572                 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1573   }
1574
1575   CreateChannelAndConnectSuccessfully();
1576   base::MessageLoop::current()->RunUntilIdle();
1577 }
1578
1579 // RFC6455 5.1 "A client MUST close a connection if it detects a masked frame."
1580 TEST_F(WebSocketChannelEventInterfaceTest, MaskedFramesAreRejected) {
1581   scoped_ptr<ReadableFakeWebSocketStream> stream(
1582       new ReadableFakeWebSocketStream);
1583   static const InitFrame frames[] = {
1584       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1585
1586   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1587   set_stream(stream.Pass());
1588   {
1589     InSequence s;
1590     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1591     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1592     EXPECT_CALL(
1593         *event_interface_,
1594         OnFailChannel(
1595             "A server must not mask any frames that it sends to the client."));
1596   }
1597
1598   CreateChannelAndConnectSuccessfully();
1599   base::MessageLoop::current()->RunUntilIdle();
1600 }
1601
1602 // RFC6455 5.2 "If an unknown opcode is received, the receiving endpoint MUST
1603 // _Fail the WebSocket Connection_."
1604 TEST_F(WebSocketChannelEventInterfaceTest, UnknownOpCodeIsRejected) {
1605   scoped_ptr<ReadableFakeWebSocketStream> stream(
1606       new ReadableFakeWebSocketStream);
1607   static const InitFrame frames[] = {{FINAL_FRAME, 4, NOT_MASKED, "HELLO"}};
1608
1609   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1610   set_stream(stream.Pass());
1611   {
1612     InSequence s;
1613     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1614     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1615     EXPECT_CALL(*event_interface_,
1616                 OnFailChannel("Unrecognized frame opcode: 4"));
1617   }
1618
1619   CreateChannelAndConnectSuccessfully();
1620   base::MessageLoop::current()->RunUntilIdle();
1621 }
1622
1623 // RFC6455 5.4 "Control frames ... MAY be injected in the middle of a
1624 // fragmented message."
1625 TEST_F(WebSocketChannelEventInterfaceTest, ControlFrameInDataMessage) {
1626   scoped_ptr<ReadableFakeWebSocketStream> stream(
1627       new ReadableFakeWebSocketStream);
1628   // We have one message of type Text split into two frames. In the middle is a
1629   // control message of type Pong.
1630   static const InitFrame frames1[] = {
1631       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
1632        NOT_MASKED,      "SPLIT "}};
1633   static const InitFrame frames2[] = {
1634       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1635   static const InitFrame frames3[] = {
1636       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1637        NOT_MASKED,  "MESSAGE"}};
1638   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1639   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1640   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1641   set_stream(stream.Pass());
1642   {
1643     InSequence s;
1644     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1645     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1646     EXPECT_CALL(
1647         *event_interface_,
1648         OnDataFrame(
1649             false, WebSocketFrameHeader::kOpCodeText, AsVector("SPLIT ")));
1650     EXPECT_CALL(*event_interface_,
1651                 OnDataFrame(true,
1652                             WebSocketFrameHeader::kOpCodeContinuation,
1653                             AsVector("MESSAGE")));
1654   }
1655
1656   CreateChannelAndConnectSuccessfully();
1657   base::MessageLoop::current()->RunUntilIdle();
1658 }
1659
1660 // It seems redundant to repeat the entirety of the above test, so just test a
1661 // Pong with NULL data.
1662 TEST_F(WebSocketChannelEventInterfaceTest, PongWithNullData) {
1663   scoped_ptr<ReadableFakeWebSocketStream> stream(
1664       new ReadableFakeWebSocketStream);
1665   static const InitFrame frames[] = {
1666       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1667   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1668   set_stream(stream.Pass());
1669   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1670   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1671
1672   CreateChannelAndConnectSuccessfully();
1673   base::MessageLoop::current()->RunUntilIdle();
1674 }
1675
1676 // If a frame has an invalid header, then the connection is closed and
1677 // subsequent frames must not trigger events.
1678 TEST_F(WebSocketChannelEventInterfaceTest, FrameAfterInvalidFrame) {
1679   scoped_ptr<ReadableFakeWebSocketStream> stream(
1680       new ReadableFakeWebSocketStream);
1681   static const InitFrame frames[] = {
1682       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"},
1683       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, " WORLD"}};
1684
1685   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1686   set_stream(stream.Pass());
1687   {
1688     InSequence s;
1689     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1690     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1691     EXPECT_CALL(
1692         *event_interface_,
1693         OnFailChannel(
1694             "A server must not mask any frames that it sends to the client."));
1695   }
1696
1697   CreateChannelAndConnectSuccessfully();
1698   base::MessageLoop::current()->RunUntilIdle();
1699 }
1700
1701 // If the renderer sends lots of small writes, we don't want to update the quota
1702 // for each one.
1703 TEST_F(WebSocketChannelEventInterfaceTest, SmallWriteDoesntUpdateQuota) {
1704   set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1705   {
1706     InSequence s;
1707     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1708     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1709   }
1710
1711   CreateChannelAndConnectSuccessfully();
1712   channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("B"));
1713 }
1714
1715 // If we send enough to go below send_quota_low_water_mask_ we should get our
1716 // quota refreshed.
1717 TEST_F(WebSocketChannelEventInterfaceTest, LargeWriteUpdatesQuota) {
1718   set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1719   // We use this checkpoint object to verify that the quota update comes after
1720   // the write.
1721   Checkpoint checkpoint;
1722   {
1723     InSequence s;
1724     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1725     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1726     EXPECT_CALL(checkpoint, Call(1));
1727     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1728     EXPECT_CALL(checkpoint, Call(2));
1729   }
1730
1731   CreateChannelAndConnectSuccessfully();
1732   checkpoint.Call(1);
1733   channel_->SendFrame(true,
1734                       WebSocketFrameHeader::kOpCodeText,
1735                       std::vector<char>(kDefaultInitialQuota, 'B'));
1736   checkpoint.Call(2);
1737 }
1738
1739 // Verify that our quota actually is refreshed when we are told it is.
1740 TEST_F(WebSocketChannelEventInterfaceTest, QuotaReallyIsRefreshed) {
1741   set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1742   Checkpoint checkpoint;
1743   {
1744     InSequence s;
1745     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1746     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1747     EXPECT_CALL(checkpoint, Call(1));
1748     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1749     EXPECT_CALL(checkpoint, Call(2));
1750     // If quota was not really refreshed, we would get an OnDropChannel()
1751     // message.
1752     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1753     EXPECT_CALL(checkpoint, Call(3));
1754   }
1755
1756   CreateChannelAndConnectSuccessfully();
1757   checkpoint.Call(1);
1758   channel_->SendFrame(true,
1759                       WebSocketFrameHeader::kOpCodeText,
1760                       std::vector<char>(kDefaultQuotaRefreshTrigger, 'D'));
1761   checkpoint.Call(2);
1762   // We should have received more quota at this point.
1763   channel_->SendFrame(true,
1764                       WebSocketFrameHeader::kOpCodeText,
1765                       std::vector<char>(kDefaultQuotaRefreshTrigger, 'E'));
1766   checkpoint.Call(3);
1767 }
1768
1769 // If we send more than the available quota then the connection will be closed
1770 // with an error.
1771 TEST_F(WebSocketChannelEventInterfaceTest, WriteOverQuotaIsRejected) {
1772   set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1773   {
1774     InSequence s;
1775     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1776     EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
1777     EXPECT_CALL(*event_interface_, OnFailChannel("Send quota exceeded"));
1778   }
1779
1780   CreateChannelAndConnectSuccessfully();
1781   channel_->SendFrame(true,
1782                       WebSocketFrameHeader::kOpCodeText,
1783                       std::vector<char>(kDefaultInitialQuota + 1, 'C'));
1784 }
1785
1786 // If a write fails, the channel is dropped.
1787 TEST_F(WebSocketChannelEventInterfaceTest, FailedWrite) {
1788   set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
1789   Checkpoint checkpoint;
1790   {
1791     InSequence s;
1792     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1793     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1794     EXPECT_CALL(checkpoint, Call(1));
1795     EXPECT_CALL(*event_interface_,
1796                 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _));
1797     EXPECT_CALL(checkpoint, Call(2));
1798   }
1799
1800   CreateChannelAndConnectSuccessfully();
1801   checkpoint.Call(1);
1802
1803   channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("H"));
1804   checkpoint.Call(2);
1805 }
1806
1807 // OnDropChannel() is called exactly once when StartClosingHandshake() is used.
1808 TEST_F(WebSocketChannelEventInterfaceTest, SendCloseDropsChannel) {
1809   set_stream(make_scoped_ptr(new EchoeyFakeWebSocketStream));
1810   {
1811     InSequence s;
1812     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1813     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1814     EXPECT_CALL(*event_interface_,
1815                 OnDropChannel(true, kWebSocketNormalClosure, "Fred"));
1816   }
1817
1818   CreateChannelAndConnectSuccessfully();
1819
1820   channel_->StartClosingHandshake(kWebSocketNormalClosure, "Fred");
1821   base::MessageLoop::current()->RunUntilIdle();
1822 }
1823
1824 // StartClosingHandshake() also works before connection completes, and calls
1825 // OnDropChannel.
1826 TEST_F(WebSocketChannelEventInterfaceTest, CloseDuringConnection) {
1827   EXPECT_CALL(*event_interface_,
1828               OnDropChannel(false, kWebSocketErrorAbnormalClosure, ""));
1829
1830   CreateChannelAndConnect();
1831   channel_->StartClosingHandshake(kWebSocketNormalClosure, "Joe");
1832 }
1833
1834 // OnDropChannel() is only called once when a write() on the socket triggers a
1835 // connection reset.
1836 TEST_F(WebSocketChannelEventInterfaceTest, OnDropChannelCalledOnce) {
1837   set_stream(make_scoped_ptr(new ResetOnWriteFakeWebSocketStream));
1838   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1839   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1840
1841   EXPECT_CALL(*event_interface_,
1842               OnDropChannel(false, kWebSocketErrorAbnormalClosure, ""))
1843       .Times(1);
1844
1845   CreateChannelAndConnectSuccessfully();
1846
1847   channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("yt?"));
1848   base::MessageLoop::current()->RunUntilIdle();
1849 }
1850
1851 // When the remote server sends a Close frame with an empty payload,
1852 // WebSocketChannel should report code 1005, kWebSocketErrorNoStatusReceived.
1853 TEST_F(WebSocketChannelEventInterfaceTest, CloseWithNoPayloadGivesStatus1005) {
1854   scoped_ptr<ReadableFakeWebSocketStream> stream(
1855       new ReadableFakeWebSocketStream);
1856   static const InitFrame frames[] = {
1857       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
1858   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1859   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1860                                  ERR_CONNECTION_CLOSED);
1861   set_stream(stream.Pass());
1862   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1863   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1864   EXPECT_CALL(*event_interface_, OnClosingHandshake());
1865   EXPECT_CALL(*event_interface_,
1866               OnDropChannel(true, kWebSocketErrorNoStatusReceived, _));
1867
1868   CreateChannelAndConnectSuccessfully();
1869 }
1870
1871 // A version of the above test with NULL payload.
1872 TEST_F(WebSocketChannelEventInterfaceTest,
1873        CloseWithNullPayloadGivesStatus1005) {
1874   scoped_ptr<ReadableFakeWebSocketStream> stream(
1875       new ReadableFakeWebSocketStream);
1876   static const InitFrame frames[] = {
1877       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, NULL}};
1878   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1879   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1880                                  ERR_CONNECTION_CLOSED);
1881   set_stream(stream.Pass());
1882   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1883   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1884   EXPECT_CALL(*event_interface_, OnClosingHandshake());
1885   EXPECT_CALL(*event_interface_,
1886               OnDropChannel(true, kWebSocketErrorNoStatusReceived, _));
1887
1888   CreateChannelAndConnectSuccessfully();
1889 }
1890
1891 // If ReadFrames() returns ERR_WS_PROTOCOL_ERROR, then the connection must be
1892 // failed.
1893 TEST_F(WebSocketChannelEventInterfaceTest, SyncProtocolErrorGivesStatus1002) {
1894   scoped_ptr<ReadableFakeWebSocketStream> stream(
1895       new ReadableFakeWebSocketStream);
1896   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1897                                  ERR_WS_PROTOCOL_ERROR);
1898   set_stream(stream.Pass());
1899   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1900   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1901
1902   EXPECT_CALL(*event_interface_, OnFailChannel("Invalid frame header"));
1903
1904   CreateChannelAndConnectSuccessfully();
1905 }
1906
1907 // Async version of above test.
1908 TEST_F(WebSocketChannelEventInterfaceTest, AsyncProtocolErrorGivesStatus1002) {
1909   scoped_ptr<ReadableFakeWebSocketStream> stream(
1910       new ReadableFakeWebSocketStream);
1911   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1912                                  ERR_WS_PROTOCOL_ERROR);
1913   set_stream(stream.Pass());
1914   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1915   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1916
1917   EXPECT_CALL(*event_interface_, OnFailChannel("Invalid frame header"));
1918
1919   CreateChannelAndConnectSuccessfully();
1920   base::MessageLoop::current()->RunUntilIdle();
1921 }
1922
1923 TEST_F(WebSocketChannelEventInterfaceTest, StartHandshakeRequest) {
1924   {
1925     InSequence s;
1926     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1927     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1928     EXPECT_CALL(*event_interface_, OnStartOpeningHandshakeCalled());
1929   }
1930
1931   CreateChannelAndConnectSuccessfully();
1932
1933   scoped_ptr<WebSocketHandshakeRequestInfo> request_info(
1934       new WebSocketHandshakeRequestInfo(GURL("ws://www.example.com/"),
1935                                         base::Time()));
1936   connect_data_.creator.connect_delegate->OnStartOpeningHandshake(
1937       request_info.Pass());
1938
1939   base::MessageLoop::current()->RunUntilIdle();
1940 }
1941
1942 TEST_F(WebSocketChannelEventInterfaceTest, FinishHandshakeRequest) {
1943   {
1944     InSequence s;
1945     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1946     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1947     EXPECT_CALL(*event_interface_, OnFinishOpeningHandshakeCalled());
1948   }
1949
1950   CreateChannelAndConnectSuccessfully();
1951
1952   scoped_refptr<HttpResponseHeaders> response_headers(
1953       new HttpResponseHeaders(""));
1954   scoped_ptr<WebSocketHandshakeResponseInfo> response_info(
1955       new WebSocketHandshakeResponseInfo(GURL("ws://www.example.com/"),
1956                                          200,
1957                                          "OK",
1958                                          response_headers,
1959                                          base::Time()));
1960   connect_data_.creator.connect_delegate->OnFinishOpeningHandshake(
1961       response_info.Pass());
1962   base::MessageLoop::current()->RunUntilIdle();
1963 }
1964
1965 TEST_F(WebSocketChannelEventInterfaceTest, FailJustAfterHandshake) {
1966   {
1967     InSequence s;
1968     EXPECT_CALL(*event_interface_, OnStartOpeningHandshakeCalled());
1969     EXPECT_CALL(*event_interface_, OnFinishOpeningHandshakeCalled());
1970     EXPECT_CALL(*event_interface_, OnFailChannel("bye"));
1971   }
1972
1973   CreateChannelAndConnect();
1974
1975   WebSocketStream::ConnectDelegate* connect_delegate =
1976       connect_data_.creator.connect_delegate.get();
1977   GURL url("ws://www.example.com/");
1978   scoped_ptr<WebSocketHandshakeRequestInfo> request_info(
1979       new WebSocketHandshakeRequestInfo(url, base::Time()));
1980   scoped_refptr<HttpResponseHeaders> response_headers(
1981       new HttpResponseHeaders(""));
1982   scoped_ptr<WebSocketHandshakeResponseInfo> response_info(
1983       new WebSocketHandshakeResponseInfo(url,
1984                                          200,
1985                                          "OK",
1986                                          response_headers,
1987                                          base::Time()));
1988   connect_delegate->OnStartOpeningHandshake(request_info.Pass());
1989   connect_delegate->OnFinishOpeningHandshake(response_info.Pass());
1990
1991   connect_delegate->OnFailure("bye");
1992   base::MessageLoop::current()->RunUntilIdle();
1993 }
1994
1995 // Any frame after close is invalid. This test uses a Text frame. See also
1996 // test "PingAfterCloseIfRejected".
1997 TEST_F(WebSocketChannelEventInterfaceTest, DataAfterCloseIsRejected) {
1998   scoped_ptr<ReadableFakeWebSocketStream> stream(
1999       new ReadableFakeWebSocketStream);
2000   static const InitFrame frames[] = {
2001       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
2002        CLOSE_DATA(NORMAL_CLOSURE, "OK")},
2003       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "Payload"}};
2004   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2005   set_stream(stream.Pass());
2006   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2007   EXPECT_CALL(*event_interface_, OnFlowControl(_));
2008
2009   {
2010     InSequence s;
2011     EXPECT_CALL(*event_interface_, OnClosingHandshake());
2012     EXPECT_CALL(*event_interface_,
2013                 OnFailChannel("Data frame received after close"));
2014   }
2015
2016   CreateChannelAndConnectSuccessfully();
2017 }
2018
2019 // A Close frame with a one-byte payload elicits a specific console error
2020 // message.
2021 TEST_F(WebSocketChannelEventInterfaceTest, OneByteClosePayloadMessage) {
2022   scoped_ptr<ReadableFakeWebSocketStream> stream(
2023       new ReadableFakeWebSocketStream);
2024   static const InitFrame frames[] = {
2025       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, "\x03"}};
2026   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2027   set_stream(stream.Pass());
2028   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2029   EXPECT_CALL(*event_interface_, OnFlowControl(_));
2030   EXPECT_CALL(
2031       *event_interface_,
2032       OnFailChannel(
2033           "Received a broken close frame containing an invalid size body."));
2034
2035   CreateChannelAndConnectSuccessfully();
2036 }
2037
2038 // A Close frame with a reserved status code also elicits a specific console
2039 // error message.
2040 TEST_F(WebSocketChannelEventInterfaceTest, ClosePayloadReservedStatusMessage) {
2041   scoped_ptr<ReadableFakeWebSocketStream> stream(
2042       new ReadableFakeWebSocketStream);
2043   static const InitFrame frames[] = {
2044       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2045        NOT_MASKED,  CLOSE_DATA(ABNORMAL_CLOSURE, "Not valid on wire")}};
2046   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2047   set_stream(stream.Pass());
2048   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2049   EXPECT_CALL(*event_interface_, OnFlowControl(_));
2050   EXPECT_CALL(
2051       *event_interface_,
2052       OnFailChannel(
2053           "Received a broken close frame containing a reserved status code."));
2054
2055   CreateChannelAndConnectSuccessfully();
2056 }
2057
2058 // A Close frame with invalid UTF-8 also elicits a specific console error
2059 // message.
2060 TEST_F(WebSocketChannelEventInterfaceTest, ClosePayloadInvalidReason) {
2061   scoped_ptr<ReadableFakeWebSocketStream> stream(
2062       new ReadableFakeWebSocketStream);
2063   static const InitFrame frames[] = {
2064       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2065        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
2066   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2067   set_stream(stream.Pass());
2068   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2069   EXPECT_CALL(*event_interface_, OnFlowControl(_));
2070   EXPECT_CALL(
2071       *event_interface_,
2072       OnFailChannel(
2073           "Received a broken close frame containing invalid UTF-8."));
2074
2075   CreateChannelAndConnectSuccessfully();
2076 }
2077
2078 // The closing handshake times out and sends an OnDropChannel event if no
2079 // response to the client Close message is received.
2080 TEST_F(WebSocketChannelEventInterfaceTest,
2081        ClientInitiatedClosingHandshakeTimesOut) {
2082   scoped_ptr<ReadableFakeWebSocketStream> stream(
2083       new ReadableFakeWebSocketStream);
2084   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
2085                                  ERR_IO_PENDING);
2086   set_stream(stream.Pass());
2087   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2088   EXPECT_CALL(*event_interface_, OnFlowControl(_));
2089   // This checkpoint object verifies that the OnDropChannel message comes after
2090   // the timeout.
2091   Checkpoint checkpoint;
2092   TestClosure completion;
2093   {
2094     InSequence s;
2095     EXPECT_CALL(checkpoint, Call(1));
2096     EXPECT_CALL(*event_interface_,
2097                 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _))
2098         .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
2099   }
2100   CreateChannelAndConnectSuccessfully();
2101   // OneShotTimer is not very friendly to testing; there is no apparent way to
2102   // set an expectation on it. Instead the tests need to infer that the timeout
2103   // was fired by the behaviour of the WebSocketChannel object.
2104   channel_->SetClosingHandshakeTimeoutForTesting(
2105       TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2106   channel_->StartClosingHandshake(kWebSocketNormalClosure, "");
2107   checkpoint.Call(1);
2108   completion.WaitForResult();
2109 }
2110
2111 // The closing handshake times out and sends an OnDropChannel event if a Close
2112 // message is received but the connection isn't closed by the remote host.
2113 TEST_F(WebSocketChannelEventInterfaceTest,
2114        ServerInitiatedClosingHandshakeTimesOut) {
2115   scoped_ptr<ReadableFakeWebSocketStream> stream(
2116       new ReadableFakeWebSocketStream);
2117   static const InitFrame frames[] = {
2118       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2119        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2120   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
2121   set_stream(stream.Pass());
2122   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2123   EXPECT_CALL(*event_interface_, OnFlowControl(_));
2124   Checkpoint checkpoint;
2125   TestClosure completion;
2126   {
2127     InSequence s;
2128     EXPECT_CALL(checkpoint, Call(1));
2129     EXPECT_CALL(*event_interface_, OnClosingHandshake());
2130     EXPECT_CALL(*event_interface_,
2131                 OnDropChannel(false, kWebSocketErrorAbnormalClosure, _))
2132         .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
2133   }
2134   CreateChannelAndConnectSuccessfully();
2135   channel_->SetClosingHandshakeTimeoutForTesting(
2136       TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2137   checkpoint.Call(1);
2138   completion.WaitForResult();
2139 }
2140
2141 // RFC6455 5.1 "a client MUST mask all frames that it sends to the server".
2142 // WebSocketChannel actually only sets the mask bit in the header, it doesn't
2143 // perform masking itself (not all transports actually use masking).
2144 TEST_F(WebSocketChannelStreamTest, SentFramesAreMasked) {
2145   static const InitFrame expected[] = {
2146       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2147        MASKED,      "NEEDS MASKING"}};
2148   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2149   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2150   EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2151   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2152       .WillOnce(Return(OK));
2153
2154   CreateChannelAndConnectSuccessfully();
2155   channel_->SendFrame(
2156       true, WebSocketFrameHeader::kOpCodeText, AsVector("NEEDS MASKING"));
2157 }
2158
2159 // RFC6455 5.5.1 "The application MUST NOT send any more data frames after
2160 // sending a Close frame."
2161 TEST_F(WebSocketChannelStreamTest, NothingIsSentAfterClose) {
2162   static const InitFrame expected[] = {
2163       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2164        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
2165   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2166   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2167   EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2168   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2169       .WillOnce(Return(OK));
2170
2171   CreateChannelAndConnectSuccessfully();
2172   channel_->StartClosingHandshake(1000, "Success");
2173   channel_->SendFrame(
2174       true, WebSocketFrameHeader::kOpCodeText, AsVector("SHOULD  BE IGNORED"));
2175 }
2176
2177 // RFC6455 5.5.1 "If an endpoint receives a Close frame and did not previously
2178 // send a Close frame, the endpoint MUST send a Close frame in response."
2179 TEST_F(WebSocketChannelStreamTest, CloseIsEchoedBack) {
2180   static const InitFrame frames[] = {
2181       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2182        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2183   static const InitFrame expected[] = {
2184       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2185        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2186   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2187   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2188   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2189       .WillOnce(ReturnFrames(&frames))
2190       .WillRepeatedly(Return(ERR_IO_PENDING));
2191   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2192       .WillOnce(Return(OK));
2193
2194   CreateChannelAndConnectSuccessfully();
2195 }
2196
2197 // The converse of the above case; after sending a Close frame, we should not
2198 // send another one.
2199 TEST_F(WebSocketChannelStreamTest, CloseOnlySentOnce) {
2200   static const InitFrame expected[] = {
2201       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2202        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2203   static const InitFrame frames_init[] = {
2204       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2205        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2206
2207   // We store the parameters that were passed to ReadFrames() so that we can
2208   // call them explicitly later.
2209   CompletionCallback read_callback;
2210   ScopedVector<WebSocketFrame>* frames = NULL;
2211
2212   // These are not interesting.
2213   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2214   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2215
2216   // Use a checkpoint to make the ordering of events clearer.
2217   Checkpoint checkpoint;
2218   {
2219     InSequence s;
2220     EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2221         .WillOnce(DoAll(SaveArg<0>(&frames),
2222                         SaveArg<1>(&read_callback),
2223                         Return(ERR_IO_PENDING)));
2224     EXPECT_CALL(checkpoint, Call(1));
2225     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2226         .WillOnce(Return(OK));
2227     EXPECT_CALL(checkpoint, Call(2));
2228     EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2229         .WillOnce(Return(ERR_IO_PENDING));
2230     EXPECT_CALL(checkpoint, Call(3));
2231     // WriteFrames() must not be called again. GoogleMock will ensure that the
2232     // test fails if it is.
2233   }
2234
2235   CreateChannelAndConnectSuccessfully();
2236   checkpoint.Call(1);
2237   channel_->StartClosingHandshake(kWebSocketNormalClosure, "Close");
2238   checkpoint.Call(2);
2239
2240   *frames = CreateFrameVector(frames_init);
2241   read_callback.Run(OK);
2242   checkpoint.Call(3);
2243 }
2244
2245 // Invalid close status codes should not be sent on the network.
2246 TEST_F(WebSocketChannelStreamTest, InvalidCloseStatusCodeNotSent) {
2247   static const InitFrame expected[] = {
2248       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2249        MASKED,      CLOSE_DATA(SERVER_ERROR, "")}};
2250
2251   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2252   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2253   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2254       .WillOnce(Return(ERR_IO_PENDING));
2255
2256   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
2257
2258   CreateChannelAndConnectSuccessfully();
2259   channel_->StartClosingHandshake(999, "");
2260 }
2261
2262 // A Close frame with a reason longer than 123 bytes cannot be sent on the
2263 // network.
2264 TEST_F(WebSocketChannelStreamTest, LongCloseReasonNotSent) {
2265   static const InitFrame expected[] = {
2266       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2267        MASKED,      CLOSE_DATA(SERVER_ERROR, "")}};
2268
2269   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2270   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2271   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2272       .WillOnce(Return(ERR_IO_PENDING));
2273
2274   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
2275
2276   CreateChannelAndConnectSuccessfully();
2277   channel_->StartClosingHandshake(1000, std::string(124, 'A'));
2278 }
2279
2280 // We generate code 1005, kWebSocketErrorNoStatusReceived, when there is no
2281 // status in the Close message from the other side. Code 1005 is not allowed to
2282 // appear on the wire, so we should not echo it back. See test
2283 // CloseWithNoPayloadGivesStatus1005, above, for confirmation that code 1005 is
2284 // correctly generated internally.
2285 TEST_F(WebSocketChannelStreamTest, Code1005IsNotEchoed) {
2286   static const InitFrame frames[] = {
2287       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
2288   static const InitFrame expected[] = {
2289       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED, ""}};
2290   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2291   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2292   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2293       .WillOnce(ReturnFrames(&frames))
2294       .WillRepeatedly(Return(ERR_IO_PENDING));
2295   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2296       .WillOnce(Return(OK));
2297
2298   CreateChannelAndConnectSuccessfully();
2299 }
2300
2301 TEST_F(WebSocketChannelStreamTest, Code1005IsNotEchoedNull) {
2302   static const InitFrame frames[] = {
2303       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, NULL}};
2304   static const InitFrame expected[] = {
2305       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED, ""}};
2306   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2307   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2308   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2309       .WillOnce(ReturnFrames(&frames))
2310       .WillRepeatedly(Return(ERR_IO_PENDING));
2311   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2312       .WillOnce(Return(OK));
2313
2314   CreateChannelAndConnectSuccessfully();
2315 }
2316
2317 // Receiving an invalid UTF-8 payload in a Close frame causes us to fail the
2318 // connection.
2319 TEST_F(WebSocketChannelStreamTest, CloseFrameInvalidUtf8) {
2320   static const InitFrame frames[] = {
2321       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2322        NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
2323   static const InitFrame expected[] = {
2324       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2325        MASKED, CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in Close frame")}};
2326
2327   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2328   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2329   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2330       .WillOnce(ReturnFrames(&frames))
2331       .WillRepeatedly(Return(ERR_IO_PENDING));
2332   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2333       .WillOnce(Return(OK));
2334   EXPECT_CALL(*mock_stream_, Close());
2335
2336   CreateChannelAndConnectSuccessfully();
2337 }
2338
2339 // RFC6455 5.5.2 "Upon receipt of a Ping frame, an endpoint MUST send a Pong
2340 // frame in response"
2341 // 5.5.3 "A Pong frame sent in response to a Ping frame must have identical
2342 // "Application data" as found in the message body of the Ping frame being
2343 // replied to."
2344 TEST_F(WebSocketChannelStreamTest, PingRepliedWithPong) {
2345   static const InitFrame frames[] = {
2346       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2347        NOT_MASKED,  "Application data"}};
2348   static const InitFrame expected[] = {
2349       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
2350        MASKED,      "Application data"}};
2351   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2352   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2353   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2354       .WillOnce(ReturnFrames(&frames))
2355       .WillRepeatedly(Return(ERR_IO_PENDING));
2356   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2357       .WillOnce(Return(OK));
2358
2359   CreateChannelAndConnectSuccessfully();
2360 }
2361
2362 // A ping with a NULL payload should be responded to with a Pong with a NULL
2363 // payload.
2364 TEST_F(WebSocketChannelStreamTest, NullPingRepliedWithNullPong) {
2365   static const InitFrame frames[] = {
2366       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing, NOT_MASKED, NULL}};
2367   static const InitFrame expected[] = {
2368       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, MASKED, NULL}};
2369   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2370   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2371   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2372       .WillOnce(ReturnFrames(&frames))
2373       .WillRepeatedly(Return(ERR_IO_PENDING));
2374   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2375       .WillOnce(Return(OK));
2376
2377   CreateChannelAndConnectSuccessfully();
2378 }
2379
2380 TEST_F(WebSocketChannelStreamTest, PongInTheMiddleOfDataMessage) {
2381   static const InitFrame frames[] = {
2382       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2383        NOT_MASKED,  "Application data"}};
2384   static const InitFrame expected1[] = {
2385       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
2386   static const InitFrame expected2[] = {
2387       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
2388        MASKED,      "Application data"}};
2389   static const InitFrame expected3[] = {
2390       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2391        MASKED,      "World"}};
2392   ScopedVector<WebSocketFrame>* read_frames;
2393   CompletionCallback read_callback;
2394   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2395   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2396   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2397       .WillOnce(DoAll(SaveArg<0>(&read_frames),
2398                       SaveArg<1>(&read_callback),
2399                       Return(ERR_IO_PENDING)))
2400       .WillRepeatedly(Return(ERR_IO_PENDING));
2401   {
2402     InSequence s;
2403
2404     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2405         .WillOnce(Return(OK));
2406     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2407         .WillOnce(Return(OK));
2408     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected3), _))
2409         .WillOnce(Return(OK));
2410   }
2411
2412   CreateChannelAndConnectSuccessfully();
2413   channel_->SendFrame(
2414       false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
2415   *read_frames = CreateFrameVector(frames);
2416   read_callback.Run(OK);
2417   channel_->SendFrame(
2418       true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("World"));
2419 }
2420
2421 // WriteFrames() may not be called until the previous write has completed.
2422 // WebSocketChannel must buffer writes that happen in the meantime.
2423 TEST_F(WebSocketChannelStreamTest, WriteFramesOneAtATime) {
2424   static const InitFrame expected1[] = {
2425       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
2426   static const InitFrame expected2[] = {
2427       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "World"}};
2428   CompletionCallback write_callback;
2429   Checkpoint checkpoint;
2430
2431   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2432   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2433   EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2434   {
2435     InSequence s;
2436     EXPECT_CALL(checkpoint, Call(1));
2437     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2438         .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
2439     EXPECT_CALL(checkpoint, Call(2));
2440     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2441         .WillOnce(Return(ERR_IO_PENDING));
2442     EXPECT_CALL(checkpoint, Call(3));
2443   }
2444
2445   CreateChannelAndConnectSuccessfully();
2446   checkpoint.Call(1);
2447   channel_->SendFrame(
2448       false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
2449   channel_->SendFrame(
2450       true, WebSocketFrameHeader::kOpCodeText, AsVector("World"));
2451   checkpoint.Call(2);
2452   write_callback.Run(OK);
2453   checkpoint.Call(3);
2454 }
2455
2456 // WebSocketChannel must buffer frames while it is waiting for a write to
2457 // complete, and then send them in a single batch. The batching behaviour is
2458 // important to get good throughput in the "many small messages" case.
2459 TEST_F(WebSocketChannelStreamTest, WaitingMessagesAreBatched) {
2460   static const char input_letters[] = "Hello";
2461   static const InitFrame expected1[] = {
2462       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "H"}};
2463   static const InitFrame expected2[] = {
2464       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "e"},
2465       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
2466       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
2467       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "o"}};
2468   CompletionCallback write_callback;
2469
2470   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2471   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2472   EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2473   {
2474     InSequence s;
2475     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2476         .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
2477     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2478         .WillOnce(Return(ERR_IO_PENDING));
2479   }
2480
2481   CreateChannelAndConnectSuccessfully();
2482   for (size_t i = 0; i < strlen(input_letters); ++i) {
2483     channel_->SendFrame(true,
2484                         WebSocketFrameHeader::kOpCodeText,
2485                         std::vector<char>(1, input_letters[i]));
2486   }
2487   write_callback.Run(OK);
2488 }
2489
2490 // When the renderer sends more on a channel than it has quota for, then we send
2491 // a kWebSocketMuxErrorSendQuotaViolation status code (from the draft websocket
2492 // mux specification) back to the renderer. This should not be sent to the
2493 // remote server, which may not even implement the mux specification, and could
2494 // even be using a different extension which uses that code to mean something
2495 // else.
2496 TEST_F(WebSocketChannelStreamTest, MuxErrorIsNotSentToStream) {
2497   static const InitFrame expected[] = {
2498       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2499        MASKED,      CLOSE_DATA(GOING_AWAY, "")}};
2500   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2501   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2502   EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2503   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2504       .WillOnce(Return(OK));
2505   EXPECT_CALL(*mock_stream_, Close());
2506
2507   CreateChannelAndConnectSuccessfully();
2508   channel_->SendFrame(true,
2509                       WebSocketFrameHeader::kOpCodeText,
2510                       std::vector<char>(kDefaultInitialQuota + 1, 'C'));
2511 }
2512
2513 // For convenience, most of these tests use Text frames. However, the WebSocket
2514 // protocol also has Binary frames and those need to be 8-bit clean. For the
2515 // sake of completeness, this test verifies that they are.
2516 TEST_F(WebSocketChannelStreamTest, WrittenBinaryFramesAre8BitClean) {
2517   ScopedVector<WebSocketFrame>* frames = NULL;
2518
2519   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2520   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2521   EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2522   EXPECT_CALL(*mock_stream_, WriteFrames(_, _))
2523       .WillOnce(DoAll(SaveArg<0>(&frames), Return(ERR_IO_PENDING)));
2524
2525   CreateChannelAndConnectSuccessfully();
2526   channel_->SendFrame(
2527       true,
2528       WebSocketFrameHeader::kOpCodeBinary,
2529       std::vector<char>(kBinaryBlob, kBinaryBlob + kBinaryBlobSize));
2530   ASSERT_TRUE(frames != NULL);
2531   ASSERT_EQ(1U, frames->size());
2532   const WebSocketFrame* out_frame = (*frames)[0];
2533   EXPECT_EQ(kBinaryBlobSize, out_frame->header.payload_length);
2534   ASSERT_TRUE(out_frame->data);
2535   EXPECT_EQ(0, memcmp(kBinaryBlob, out_frame->data->data(), kBinaryBlobSize));
2536 }
2537
2538 // Test the read path for 8-bit cleanliness as well.
2539 TEST_F(WebSocketChannelEventInterfaceTest, ReadBinaryFramesAre8BitClean) {
2540   scoped_ptr<WebSocketFrame> frame(
2541       new WebSocketFrame(WebSocketFrameHeader::kOpCodeBinary));
2542   WebSocketFrameHeader& frame_header = frame->header;
2543   frame_header.final = true;
2544   frame_header.payload_length = kBinaryBlobSize;
2545   frame->data = new IOBuffer(kBinaryBlobSize);
2546   memcpy(frame->data->data(), kBinaryBlob, kBinaryBlobSize);
2547   ScopedVector<WebSocketFrame> frames;
2548   frames.push_back(frame.release());
2549   scoped_ptr<ReadableFakeWebSocketStream> stream(
2550       new ReadableFakeWebSocketStream);
2551   stream->PrepareRawReadFrames(
2552       ReadableFakeWebSocketStream::SYNC, OK, frames.Pass());
2553   set_stream(stream.Pass());
2554   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2555   EXPECT_CALL(*event_interface_, OnFlowControl(_));
2556   EXPECT_CALL(*event_interface_,
2557               OnDataFrame(true,
2558                           WebSocketFrameHeader::kOpCodeBinary,
2559                           std::vector<char>(kBinaryBlob,
2560                                             kBinaryBlob + kBinaryBlobSize)));
2561
2562   CreateChannelAndConnectSuccessfully();
2563 }
2564
2565 // Invalid UTF-8 is not permitted in Text frames.
2566 TEST_F(WebSocketChannelSendUtf8Test, InvalidUtf8Rejected) {
2567   EXPECT_CALL(
2568       *event_interface_,
2569       OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2570
2571   CreateChannelAndConnectSuccessfully();
2572
2573   channel_->SendFrame(
2574       true, WebSocketFrameHeader::kOpCodeText, AsVector("\xff"));
2575 }
2576
2577 // A Text message cannot end with a partial UTF-8 character.
2578 TEST_F(WebSocketChannelSendUtf8Test, IncompleteCharacterInFinalFrame) {
2579   EXPECT_CALL(
2580       *event_interface_,
2581       OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2582
2583   CreateChannelAndConnectSuccessfully();
2584
2585   channel_->SendFrame(
2586       true, WebSocketFrameHeader::kOpCodeText, AsVector("\xc2"));
2587 }
2588
2589 // A non-final Text frame may end with a partial UTF-8 character (compare to
2590 // previous test).
2591 TEST_F(WebSocketChannelSendUtf8Test, IncompleteCharacterInNonFinalFrame) {
2592   CreateChannelAndConnectSuccessfully();
2593
2594   channel_->SendFrame(
2595       false, WebSocketFrameHeader::kOpCodeText, AsVector("\xc2"));
2596 }
2597
2598 // UTF-8 parsing context must be retained between frames.
2599 TEST_F(WebSocketChannelSendUtf8Test, ValidCharacterSplitBetweenFrames) {
2600   CreateChannelAndConnectSuccessfully();
2601
2602   channel_->SendFrame(
2603       false, WebSocketFrameHeader::kOpCodeText, AsVector("\xf1"));
2604   channel_->SendFrame(true,
2605                       WebSocketFrameHeader::kOpCodeContinuation,
2606                       AsVector("\x80\xa0\xbf"));
2607 }
2608
2609 // Similarly, an invalid character should be detected even if split.
2610 TEST_F(WebSocketChannelSendUtf8Test, InvalidCharacterSplit) {
2611   EXPECT_CALL(
2612       *event_interface_,
2613       OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2614
2615   CreateChannelAndConnectSuccessfully();
2616
2617   channel_->SendFrame(
2618       false, WebSocketFrameHeader::kOpCodeText, AsVector("\xe1"));
2619   channel_->SendFrame(true,
2620                       WebSocketFrameHeader::kOpCodeContinuation,
2621                       AsVector("\x80\xa0\xbf"));
2622 }
2623
2624 // An invalid character must be detected in continuation frames.
2625 TEST_F(WebSocketChannelSendUtf8Test, InvalidByteInContinuation) {
2626   EXPECT_CALL(
2627       *event_interface_,
2628       OnFailChannel("Browser sent a text frame containing invalid UTF-8"));
2629
2630   CreateChannelAndConnectSuccessfully();
2631
2632   channel_->SendFrame(
2633       false, WebSocketFrameHeader::kOpCodeText, AsVector("foo"));
2634   channel_->SendFrame(
2635       false, WebSocketFrameHeader::kOpCodeContinuation, AsVector("bar"));
2636   channel_->SendFrame(
2637       true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("\xff"));
2638 }
2639
2640 // However, continuation frames of a Binary frame will not be tested for UTF-8
2641 // validity.
2642 TEST_F(WebSocketChannelSendUtf8Test, BinaryContinuationNotChecked) {
2643   CreateChannelAndConnectSuccessfully();
2644
2645   channel_->SendFrame(
2646       false, WebSocketFrameHeader::kOpCodeBinary, AsVector("foo"));
2647   channel_->SendFrame(
2648       false, WebSocketFrameHeader::kOpCodeContinuation, AsVector("bar"));
2649   channel_->SendFrame(
2650       true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("\xff"));
2651 }
2652
2653 // Multiple text messages can be validated without the validation state getting
2654 // confused.
2655 TEST_F(WebSocketChannelSendUtf8Test, ValidateMultipleTextMessages) {
2656   CreateChannelAndConnectSuccessfully();
2657
2658   channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("foo"));
2659   channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("bar"));
2660 }
2661
2662 // UTF-8 validation is enforced on received Text frames.
2663 TEST_F(WebSocketChannelEventInterfaceTest, ReceivedInvalidUtf8) {
2664   scoped_ptr<ReadableFakeWebSocketStream> stream(
2665       new ReadableFakeWebSocketStream);
2666   static const InitFrame frames[] = {
2667       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xff"}};
2668   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2669   set_stream(stream.Pass());
2670
2671   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2672   EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
2673   EXPECT_CALL(*event_interface_,
2674               OnFailChannel("Could not decode a text frame as UTF-8."));
2675
2676   CreateChannelAndConnectSuccessfully();
2677   base::MessageLoop::current()->RunUntilIdle();
2678 }
2679
2680 // Invalid UTF-8 is not sent over the network.
2681 TEST_F(WebSocketChannelStreamTest, InvalidUtf8TextFrameNotSent) {
2682   static const InitFrame expected[] = {{FINAL_FRAME,
2683                                         WebSocketFrameHeader::kOpCodeClose,
2684                                         MASKED, CLOSE_DATA(GOING_AWAY, "")}};
2685   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2686   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2687   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2688       .WillRepeatedly(Return(ERR_IO_PENDING));
2689   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2690       .WillOnce(Return(OK));
2691   EXPECT_CALL(*mock_stream_, Close()).Times(1);
2692
2693   CreateChannelAndConnectSuccessfully();
2694
2695   channel_->SendFrame(
2696       true, WebSocketFrameHeader::kOpCodeText, AsVector("\xff"));
2697 }
2698
2699 // The rest of the tests for receiving invalid UTF-8 test the communication with
2700 // the server. Since there is only one code path, it would be redundant to
2701 // perform the same tests on the EventInterface as well.
2702
2703 // If invalid UTF-8 is received in a Text frame, the connection is failed.
2704 TEST_F(WebSocketChannelReceiveUtf8Test, InvalidTextFrameRejected) {
2705   static const InitFrame frames[] = {
2706       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xff"}};
2707   static const InitFrame expected[] = {
2708       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
2709        CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
2710   {
2711     InSequence s;
2712     EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2713         .WillOnce(ReturnFrames(&frames))
2714         .WillRepeatedly(Return(ERR_IO_PENDING));
2715     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2716         .WillOnce(Return(OK));
2717     EXPECT_CALL(*mock_stream_, Close()).Times(1);
2718   }
2719
2720   CreateChannelAndConnectSuccessfully();
2721 }
2722
2723 // A received Text message is not permitted to end with a partial UTF-8
2724 // character.
2725 TEST_F(WebSocketChannelReceiveUtf8Test, IncompleteCharacterReceived) {
2726   static const InitFrame frames[] = {
2727       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xc2"}};
2728   static const InitFrame expected[] = {
2729       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
2730        CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
2731   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2732       .WillOnce(ReturnFrames(&frames))
2733       .WillRepeatedly(Return(ERR_IO_PENDING));
2734   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2735       .WillOnce(Return(OK));
2736   EXPECT_CALL(*mock_stream_, Close()).Times(1);
2737
2738   CreateChannelAndConnectSuccessfully();
2739 }
2740
2741 // However, a non-final Text frame may end with a partial UTF-8 character.
2742 TEST_F(WebSocketChannelReceiveUtf8Test, IncompleteCharacterIncompleteMessage) {
2743   static const InitFrame frames[] = {
2744       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xc2"}};
2745   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2746       .WillOnce(ReturnFrames(&frames))
2747       .WillRepeatedly(Return(ERR_IO_PENDING));
2748
2749   CreateChannelAndConnectSuccessfully();
2750 }
2751
2752 // However, it will become an error if it is followed by an empty final frame.
2753 TEST_F(WebSocketChannelReceiveUtf8Test, TricksyIncompleteCharacter) {
2754   static const InitFrame frames[] = {
2755       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xc2"},
2756       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation, NOT_MASKED, ""}};
2757   static const InitFrame expected[] = {
2758       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
2759        CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
2760   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2761       .WillOnce(ReturnFrames(&frames))
2762       .WillRepeatedly(Return(ERR_IO_PENDING));
2763   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2764       .WillOnce(Return(OK));
2765   EXPECT_CALL(*mock_stream_, Close()).Times(1);
2766
2767   CreateChannelAndConnectSuccessfully();
2768 }
2769
2770 // UTF-8 parsing context must be retained between received frames of the same
2771 // message.
2772 TEST_F(WebSocketChannelReceiveUtf8Test, ReceivedParsingContextRetained) {
2773   static const InitFrame frames[] = {
2774       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xf1"},
2775       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2776        NOT_MASKED,  "\x80\xa0\xbf"}};
2777   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2778       .WillOnce(ReturnFrames(&frames))
2779       .WillRepeatedly(Return(ERR_IO_PENDING));
2780
2781   CreateChannelAndConnectSuccessfully();
2782 }
2783
2784 // An invalid character must be detected even if split between frames.
2785 TEST_F(WebSocketChannelReceiveUtf8Test, SplitInvalidCharacterReceived) {
2786   static const InitFrame frames[] = {
2787       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "\xe1"},
2788       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2789        NOT_MASKED,  "\x80\xa0\xbf"}};
2790   static const InitFrame expected[] = {
2791       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
2792        CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
2793   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2794       .WillOnce(ReturnFrames(&frames))
2795       .WillRepeatedly(Return(ERR_IO_PENDING));
2796   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2797       .WillOnce(Return(OK));
2798   EXPECT_CALL(*mock_stream_, Close()).Times(1);
2799
2800   CreateChannelAndConnectSuccessfully();
2801 }
2802
2803 // An invalid character received in a continuation frame must be detected.
2804 TEST_F(WebSocketChannelReceiveUtf8Test, InvalidReceivedIncontinuation) {
2805   static const InitFrame frames[] = {
2806       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "foo"},
2807       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2808        NOT_MASKED,      "bar"},
2809       {FINAL_FRAME,     WebSocketFrameHeader::kOpCodeContinuation,
2810        NOT_MASKED,      "\xff"}};
2811   static const InitFrame expected[] = {
2812       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED,
2813        CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in text frame")}};
2814   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2815       .WillOnce(ReturnFrames(&frames))
2816       .WillRepeatedly(Return(ERR_IO_PENDING));
2817   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2818       .WillOnce(Return(OK));
2819   EXPECT_CALL(*mock_stream_, Close()).Times(1);
2820
2821   CreateChannelAndConnectSuccessfully();
2822 }
2823
2824 // Continuations of binary frames must not be tested for UTF-8 validity.
2825 TEST_F(WebSocketChannelReceiveUtf8Test, ReceivedBinaryNotUtf8Tested) {
2826   static const InitFrame frames[] = {
2827       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeBinary, NOT_MASKED, "foo"},
2828       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2829        NOT_MASKED,      "bar"},
2830       {FINAL_FRAME,     WebSocketFrameHeader::kOpCodeContinuation,
2831        NOT_MASKED,      "\xff"}};
2832   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2833       .WillOnce(ReturnFrames(&frames))
2834       .WillRepeatedly(Return(ERR_IO_PENDING));
2835
2836   CreateChannelAndConnectSuccessfully();
2837 }
2838
2839 // Multiple Text messages can be validated.
2840 TEST_F(WebSocketChannelReceiveUtf8Test, ValidateMultipleReceived) {
2841   static const InitFrame frames[] = {
2842       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "foo"},
2843       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "bar"}};
2844   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2845       .WillOnce(ReturnFrames(&frames))
2846       .WillRepeatedly(Return(ERR_IO_PENDING));
2847
2848   CreateChannelAndConnectSuccessfully();
2849 }
2850
2851 // If we receive another frame after Close, it is not valid. It is not
2852 // completely clear what behaviour is required from the standard in this case,
2853 // but the current implementation fails the connection. Since a Close has
2854 // already been sent, this just means closing the connection.
2855 TEST_F(WebSocketChannelStreamTest, PingAfterCloseIsRejected) {
2856   static const InitFrame frames[] = {
2857       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2858        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "OK")},
2859       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2860        NOT_MASKED,  "Ping body"}};
2861   static const InitFrame expected[] = {
2862       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2863        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2864   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2865   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2866   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2867       .WillOnce(ReturnFrames(&frames))
2868       .WillRepeatedly(Return(ERR_IO_PENDING));
2869   {
2870     // We only need to verify the relative order of WriteFrames() and
2871     // Close(). The current implementation calls WriteFrames() for the Close
2872     // frame before calling ReadFrames() again, but that is an implementation
2873     // detail and better not to consider required behaviour.
2874     InSequence s;
2875     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2876         .WillOnce(Return(OK));
2877     EXPECT_CALL(*mock_stream_, Close()).Times(1);
2878   }
2879
2880   CreateChannelAndConnectSuccessfully();
2881 }
2882
2883 // A protocol error from the remote server should result in a close frame with
2884 // status 1002, followed by the connection closing.
2885 TEST_F(WebSocketChannelStreamTest, ProtocolError) {
2886   static const InitFrame expected[] = {
2887       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2888        MASKED,      CLOSE_DATA(PROTOCOL_ERROR, "WebSocket Protocol Error")}};
2889   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2890   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2891   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2892       .WillOnce(Return(ERR_WS_PROTOCOL_ERROR));
2893   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2894       .WillOnce(Return(OK));
2895   EXPECT_CALL(*mock_stream_, Close());
2896
2897   CreateChannelAndConnectSuccessfully();
2898 }
2899
2900 // Set the closing handshake timeout to a very tiny value before connecting.
2901 class WebSocketChannelStreamTimeoutTest : public WebSocketChannelStreamTest {
2902  protected:
2903   WebSocketChannelStreamTimeoutTest() {}
2904
2905   virtual void CreateChannelAndConnectSuccessfully() OVERRIDE {
2906     set_stream(mock_stream_.Pass());
2907     CreateChannelAndConnect();
2908     channel_->SetClosingHandshakeTimeoutForTesting(
2909         TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2910     connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2911   }
2912 };
2913
2914 // In this case the server initiates the closing handshake with a Close
2915 // message. WebSocketChannel responds with a matching Close message, and waits
2916 // for the server to close the TCP/IP connection. The server never closes the
2917 // connection, so the closing handshake times out and WebSocketChannel closes
2918 // the connection itself.
2919 TEST_F(WebSocketChannelStreamTimeoutTest, ServerInitiatedCloseTimesOut) {
2920   static const InitFrame frames[] = {
2921       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2922        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2923   static const InitFrame expected[] = {
2924       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2925        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2926   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2927   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2928   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2929       .WillOnce(ReturnFrames(&frames))
2930       .WillRepeatedly(Return(ERR_IO_PENDING));
2931   Checkpoint checkpoint;
2932   TestClosure completion;
2933   {
2934     InSequence s;
2935     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2936         .WillOnce(Return(OK));
2937     EXPECT_CALL(checkpoint, Call(1));
2938     EXPECT_CALL(*mock_stream_, Close())
2939         .WillOnce(InvokeClosure(completion.closure()));
2940   }
2941
2942   CreateChannelAndConnectSuccessfully();
2943   checkpoint.Call(1);
2944   completion.WaitForResult();
2945 }
2946
2947 // In this case the client initiates the closing handshake by sending a Close
2948 // message. WebSocketChannel waits for a Close message in response from the
2949 // server. The server never responds to the Close message, so the closing
2950 // handshake times out and WebSocketChannel closes the connection.
2951 TEST_F(WebSocketChannelStreamTimeoutTest, ClientInitiatedCloseTimesOut) {
2952   static const InitFrame expected[] = {
2953       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2954        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2955   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2956   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2957   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2958       .WillRepeatedly(Return(ERR_IO_PENDING));
2959   TestClosure completion;
2960   {
2961     InSequence s;
2962     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2963         .WillOnce(Return(OK));
2964     EXPECT_CALL(*mock_stream_, Close())
2965         .WillOnce(InvokeClosure(completion.closure()));
2966   }
2967
2968   CreateChannelAndConnectSuccessfully();
2969   channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
2970   completion.WaitForResult();
2971 }
2972
2973 // In this case the client initiates the closing handshake and the server
2974 // responds with a matching Close message. WebSocketChannel waits for the server
2975 // to close the TCP/IP connection, but it never does. The closing handshake
2976 // times out and WebSocketChannel closes the connection.
2977 TEST_F(WebSocketChannelStreamTimeoutTest, ConnectionCloseTimesOut) {
2978   static const InitFrame expected[] = {
2979       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2980        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2981   static const InitFrame frames[] = {
2982       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2983        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2984   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2985   EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2986   TestClosure completion;
2987   ScopedVector<WebSocketFrame>* read_frames = NULL;
2988   CompletionCallback read_callback;
2989   {
2990     InSequence s;
2991     // Copy the arguments to ReadFrames so that the test can call the callback
2992     // after it has send the close message.
2993     EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2994         .WillOnce(DoAll(SaveArg<0>(&read_frames),
2995                         SaveArg<1>(&read_callback),
2996                         Return(ERR_IO_PENDING)));
2997     // The first real event that happens is the client sending the Close
2998     // message.
2999     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
3000         .WillOnce(Return(OK));
3001     // The |read_frames| callback is called (from this test case) at this
3002     // point. ReadFrames is called again by WebSocketChannel, waiting for
3003     // ERR_CONNECTION_CLOSED.
3004     EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
3005         .WillOnce(Return(ERR_IO_PENDING));
3006     // The timeout happens and so WebSocketChannel closes the stream.
3007     EXPECT_CALL(*mock_stream_, Close())
3008         .WillOnce(InvokeClosure(completion.closure()));
3009   }
3010
3011   CreateChannelAndConnectSuccessfully();
3012   channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
3013   ASSERT_TRUE(read_frames);
3014   // Provide the "Close" message from the server.
3015   *read_frames = CreateFrameVector(frames);
3016   read_callback.Run(OK);
3017   completion.WaitForResult();
3018 }
3019
3020 }  // namespace
3021 }  // namespace net