- add sources.
[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/safe_numerics.h"
22 #include "base/strings/string_piece.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/test_completion_callback.h"
25 #include "net/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_mux.h"
29 #include "testing/gmock/include/gmock/gmock.h"
30 #include "testing/gtest/include/gtest/gtest.h"
31 #include "url/gurl.h"
32
33 // Hacky macros to construct the body of a Close message from a code and a
34 // string, while ensuring the result is a compile-time constant string.
35 // Use like CLOSE_DATA(NORMAL_CLOSURE, "Explanation String")
36 #define CLOSE_DATA(code, string) WEBSOCKET_CLOSE_CODE_AS_STRING_##code string
37 #define WEBSOCKET_CLOSE_CODE_AS_STRING_NORMAL_CLOSURE "\x03\xe8"
38 #define WEBSOCKET_CLOSE_CODE_AS_STRING_GOING_AWAY "\x03\xe9"
39 #define WEBSOCKET_CLOSE_CODE_AS_STRING_PROTOCOL_ERROR "\x03\xea"
40 #define WEBSOCKET_CLOSE_CODE_AS_STRING_SERVER_ERROR "\x03\xf3"
41
42 namespace net {
43
44 // Printing helpers to allow GoogleMock to print frames. These are explicitly
45 // designed to look like the static initialisation format we use in these
46 // tests. They have to live in the net namespace in order to be found by
47 // GoogleMock; a nested anonymous namespace will not work.
48
49 std::ostream& operator<<(std::ostream& os, const WebSocketFrameHeader& header) {
50   return os << (header.final ? "FINAL_FRAME" : "NOT_FINAL_FRAME") << ", "
51             << header.opcode << ", "
52             << (header.masked ? "MASKED" : "NOT_MASKED");
53 }
54
55 std::ostream& operator<<(std::ostream& os, const WebSocketFrame& frame) {
56   os << "{" << frame.header << ", ";
57   if (frame.data) {
58     return os << "\"" << base::StringPiece(frame.data->data(),
59                                            frame.header.payload_length)
60               << "\"}";
61   }
62   return os << "NULL}";
63 }
64
65 std::ostream& operator<<(std::ostream& os,
66                          const ScopedVector<WebSocketFrame>& vector) {
67   os << "{";
68   bool first = true;
69   for (ScopedVector<WebSocketFrame>::const_iterator it = vector.begin();
70        it != vector.end();
71        ++it) {
72     if (!first) {
73       os << ",\n";
74     } else {
75       first = false;
76     }
77     os << **it;
78   }
79   return os << "}";
80 }
81
82 std::ostream& operator<<(std::ostream& os,
83                          const ScopedVector<WebSocketFrame>* vector) {
84   return os << '&' << *vector;
85 }
86
87 namespace {
88
89 using ::base::TimeDelta;
90
91 using ::testing::AnyNumber;
92 using ::testing::DefaultValue;
93 using ::testing::InSequence;
94 using ::testing::MockFunction;
95 using ::testing::Return;
96 using ::testing::SaveArg;
97 using ::testing::StrictMock;
98 using ::testing::_;
99
100 // A selection of characters that have traditionally been mangled in some
101 // environment or other, for testing 8-bit cleanliness.
102 const char kBinaryBlob[] = {'\n',   '\r',    // BACKWARDS CRNL
103                             '\0',            // nul
104                             '\x7F',          // DEL
105                             '\x80', '\xFF',  // NOT VALID UTF-8
106                             '\x1A',          // Control-Z, EOF on DOS
107                             '\x03',          // Control-C
108                             '\x04',          // EOT, special for Unix terms
109                             '\x1B',          // ESC, often special
110                             '\b',            // backspace
111                             '\'',            // single-quote, special in PHP
112 };
113 const size_t kBinaryBlobSize = arraysize(kBinaryBlob);
114
115 // The amount of quota a new connection gets by default.
116 // TODO(ricea): If kDefaultSendQuotaHighWaterMark changes, then this value will
117 // need to be updated.
118 const size_t kDefaultInitialQuota = 1 << 17;
119 // The amount of bytes we need to send after the initial connection to trigger a
120 // quota refresh. TODO(ricea): Change this if kDefaultSendQuotaHighWaterMark or
121 // kDefaultSendQuotaLowWaterMark change.
122 const size_t kDefaultQuotaRefreshTrigger = (1 << 16) + 1;
123
124 // TestTimeouts::tiny_timeout() is 100ms! I could run halfway around the world
125 // in that time! I would like my tests to run a bit quicker.
126 const int kVeryTinyTimeoutMillis = 1;
127
128 typedef WebSocketEventInterface::ChannelState ChannelState;
129 const ChannelState CHANNEL_ALIVE = WebSocketEventInterface::CHANNEL_ALIVE;
130 const ChannelState CHANNEL_DELETED = WebSocketEventInterface::CHANNEL_DELETED;
131
132 // This typedef mainly exists to avoid having to repeat the "NOLINT" incantation
133 // all over the place.
134 typedef MockFunction<void(int)> Checkpoint;  // NOLINT
135
136 // This mock is for testing expectations about how the EventInterface is used.
137 class MockWebSocketEventInterface : public WebSocketEventInterface {
138  public:
139   MOCK_METHOD2(OnAddChannelResponse,
140                ChannelState(bool, const std::string&));  // NOLINT
141   MOCK_METHOD3(OnDataFrame,
142                ChannelState(bool,
143                             WebSocketMessageType,
144                             const std::vector<char>&));  // NOLINT
145   MOCK_METHOD1(OnFlowControl, ChannelState(int64));      // NOLINT
146   MOCK_METHOD0(OnClosingHandshake, ChannelState(void));  // NOLINT
147   MOCK_METHOD2(OnDropChannel,
148                ChannelState(uint16, const std::string&));  // NOLINT
149 };
150
151 // This fake EventInterface is for tests which need a WebSocketEventInterface
152 // implementation but are not verifying how it is used.
153 class FakeWebSocketEventInterface : public WebSocketEventInterface {
154   virtual ChannelState OnAddChannelResponse(
155       bool fail,
156       const std::string& selected_protocol) OVERRIDE {
157     return fail ? CHANNEL_DELETED : CHANNEL_ALIVE;
158   }
159   virtual ChannelState OnDataFrame(bool fin,
160                                    WebSocketMessageType type,
161                                    const std::vector<char>& data) OVERRIDE {
162     return CHANNEL_ALIVE;
163   }
164   virtual ChannelState OnFlowControl(int64 quota) OVERRIDE {
165     return CHANNEL_ALIVE;
166   }
167   virtual ChannelState OnClosingHandshake() OVERRIDE { return CHANNEL_ALIVE; }
168   virtual ChannelState OnDropChannel(uint16 code,
169                                      const std::string& reason) OVERRIDE {
170     return CHANNEL_DELETED;
171   }
172 };
173
174 // This fake WebSocketStream is for tests that require a WebSocketStream but are
175 // not testing the way it is used. It has minimal functionality to return
176 // the |protocol| and |extensions| that it was constructed with.
177 class FakeWebSocketStream : public WebSocketStream {
178  public:
179   // Constructs with empty protocol and extensions.
180   FakeWebSocketStream() {}
181
182   // Constructs with specified protocol and extensions.
183   FakeWebSocketStream(const std::string& protocol,
184                       const std::string& extensions)
185       : protocol_(protocol), extensions_(extensions) {}
186
187   virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
188                          const CompletionCallback& callback) OVERRIDE {
189     return ERR_IO_PENDING;
190   }
191
192   virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
193                           const CompletionCallback& callback) OVERRIDE {
194     return ERR_IO_PENDING;
195   }
196
197   virtual void Close() OVERRIDE {}
198
199   // Returns the string passed to the constructor.
200   virtual std::string GetSubProtocol() const OVERRIDE { return protocol_; }
201
202   // Returns the string passed to the constructor.
203   virtual std::string GetExtensions() const OVERRIDE { return extensions_; }
204
205  private:
206   // The string to return from GetSubProtocol().
207   std::string protocol_;
208
209   // The string to return from GetExtensions().
210   std::string extensions_;
211 };
212
213 // To make the static initialisers easier to read, we use enums rather than
214 // bools.
215 enum IsFinal {
216   NOT_FINAL_FRAME,
217   FINAL_FRAME
218 };
219
220 enum IsMasked {
221   NOT_MASKED,
222   MASKED
223 };
224
225 // This is used to initialise a WebSocketFrame but is statically initialisable.
226 struct InitFrame {
227   IsFinal final;
228   // Reserved fields omitted for now. Add them if you need them.
229   WebSocketFrameHeader::OpCode opcode;
230   IsMasked masked;
231
232   // Will be used to create the IOBuffer member. Can be NULL for NULL data. Is a
233   // nul-terminated string for ease-of-use. |header.payload_length| is
234   // initialised from |strlen(data)|. This means it is not 8-bit clean, but this
235   // is not an issue for test data.
236   const char* const data;
237 };
238
239 // For GoogleMock
240 std::ostream& operator<<(std::ostream& os, const InitFrame& frame) {
241   os << "{" << (frame.final == FINAL_FRAME ? "FINAL_FRAME" : "NOT_FINAL_FRAME")
242      << ", " << frame.opcode << ", "
243      << (frame.masked == MASKED ? "MASKED" : "NOT_MASKED") << ", ";
244   if (frame.data) {
245     return os << "\"" << frame.data << "\"}";
246   }
247   return os << "NULL}";
248 }
249
250 template <size_t N>
251 std::ostream& operator<<(std::ostream& os, const InitFrame (&frames)[N]) {
252   os << "{";
253   bool first = true;
254   for (size_t i = 0; i < N; ++i) {
255     if (!first) {
256       os << ",\n";
257     } else {
258       first = false;
259     }
260     os << frames[i];
261   }
262   return os << "}";
263 }
264
265 // Convert a const array of InitFrame structs to the format used at
266 // runtime. Templated on the size of the array to save typing.
267 template <size_t N>
268 ScopedVector<WebSocketFrame> CreateFrameVector(
269     const InitFrame (&source_frames)[N]) {
270   ScopedVector<WebSocketFrame> result_frames;
271   result_frames.reserve(N);
272   for (size_t i = 0; i < N; ++i) {
273     const InitFrame& source_frame = source_frames[i];
274     scoped_ptr<WebSocketFrame> result_frame(
275         new WebSocketFrame(source_frame.opcode));
276     size_t frame_length = source_frame.data ? strlen(source_frame.data) : 0;
277     WebSocketFrameHeader& result_header = result_frame->header;
278     result_header.final = (source_frame.final == FINAL_FRAME);
279     result_header.masked = (source_frame.masked == MASKED);
280     result_header.payload_length = frame_length;
281     if (source_frame.data) {
282       result_frame->data = new IOBuffer(frame_length);
283       memcpy(result_frame->data->data(), source_frame.data, frame_length);
284     }
285     result_frames.push_back(result_frame.release());
286   }
287   return result_frames.Pass();
288 }
289
290 // A GoogleMock action which can be used to respond to call to ReadFrames with
291 // some frames. Use like ReadFrames(_, _).WillOnce(ReturnFrames(&frames));
292 // |frames| is an array of InitFrame. |frames| needs to be passed by pointer
293 // because otherwise it will be treated as a pointer and the array size
294 // information will be lost.
295 ACTION_P(ReturnFrames, source_frames) {
296   *arg0 = CreateFrameVector(*source_frames);
297   return OK;
298 }
299
300 // The implementation of a GoogleMock matcher which can be used to compare a
301 // ScopedVector<WebSocketFrame>* against an expectation defined as an array of
302 // InitFrame objects. Although it is possible to compose built-in GoogleMock
303 // matchers to check the contents of a WebSocketFrame, the results are so
304 // unreadable that it is better to use this matcher.
305 template <size_t N>
306 class EqualsFramesMatcher
307     : public ::testing::MatcherInterface<ScopedVector<WebSocketFrame>*> {
308  public:
309   EqualsFramesMatcher(const InitFrame (*expect_frames)[N])
310       : expect_frames_(expect_frames) {}
311
312   virtual bool MatchAndExplain(ScopedVector<WebSocketFrame>* actual_frames,
313                                ::testing::MatchResultListener* listener) const {
314     if (actual_frames->size() != N) {
315       *listener << "the vector size is " << actual_frames->size();
316       return false;
317     }
318     for (size_t i = 0; i < N; ++i) {
319       const WebSocketFrame& actual_frame = *(*actual_frames)[i];
320       const InitFrame& expected_frame = (*expect_frames_)[i];
321       if (actual_frame.header.final != (expected_frame.final == FINAL_FRAME)) {
322         *listener << "the frame is marked as "
323                   << (actual_frame.header.final ? "" : "not ") << "final";
324         return false;
325       }
326       if (actual_frame.header.opcode != expected_frame.opcode) {
327         *listener << "the opcode is " << actual_frame.header.opcode;
328         return false;
329       }
330       if (actual_frame.header.masked != (expected_frame.masked == MASKED)) {
331         *listener << "the frame is "
332                   << (actual_frame.header.masked ? "masked" : "not masked");
333         return false;
334       }
335       const size_t expected_length =
336           expected_frame.data ? strlen(expected_frame.data) : 0;
337       if (actual_frame.header.payload_length != expected_length) {
338         *listener << "the payload length is "
339                   << actual_frame.header.payload_length;
340         return false;
341       }
342       if (expected_length != 0 &&
343           memcmp(actual_frame.data->data(),
344                  expected_frame.data,
345                  actual_frame.header.payload_length) != 0) {
346         *listener << "the data content differs";
347         return false;
348       }
349     }
350     return true;
351   }
352
353   virtual void DescribeTo(std::ostream* os) const {
354     *os << "matches " << *expect_frames_;
355   }
356
357   virtual void DescribeNegationTo(std::ostream* os) const {
358     *os << "does not match " << *expect_frames_;
359   }
360
361  private:
362   const InitFrame (*expect_frames_)[N];
363 };
364
365 // The definition of EqualsFrames GoogleMock matcher. Unlike the ReturnFrames
366 // action, this can take the array by reference.
367 template <size_t N>
368 ::testing::Matcher<ScopedVector<WebSocketFrame>*> EqualsFrames(
369     const InitFrame (&frames)[N]) {
370   return ::testing::MakeMatcher(new EqualsFramesMatcher<N>(&frames));
371 }
372
373 // TestClosure works like TestCompletionCallback, but doesn't take an argument.
374 class TestClosure {
375  public:
376   base::Closure closure() { return base::Bind(callback_.callback(), OK); }
377
378   void WaitForResult() { callback_.WaitForResult(); }
379
380  private:
381   // Delegate to TestCompletionCallback for the implementation.
382   TestCompletionCallback callback_;
383 };
384
385 // A GoogleMock action to run a Closure.
386 ACTION_P(InvokeClosure, closure) { closure.Run(); }
387
388 // A GoogleMock action to run a Closure and return CHANNEL_DELETED.
389 ACTION_P(InvokeClosureReturnDeleted, closure) {
390   closure.Run();
391   return WebSocketEventInterface::CHANNEL_DELETED;
392 }
393
394 // A FakeWebSocketStream whose ReadFrames() function returns data.
395 class ReadableFakeWebSocketStream : public FakeWebSocketStream {
396  public:
397   enum IsSync {
398     SYNC,
399     ASYNC
400   };
401
402   // After constructing the object, call PrepareReadFrames() once for each
403   // time you wish it to return from the test.
404   ReadableFakeWebSocketStream() : index_(0), read_frames_pending_(false) {}
405
406   // Check that all the prepared responses have been consumed.
407   virtual ~ReadableFakeWebSocketStream() {
408     CHECK(index_ >= responses_.size());
409     CHECK(!read_frames_pending_);
410   }
411
412   // Prepares a fake response. Fake responses will be returned from ReadFrames()
413   // in the same order they were prepared with PrepareReadFrames() and
414   // PrepareReadFramesError(). If |async| is ASYNC, then ReadFrames() will
415   // return ERR_IO_PENDING and the callback will be scheduled to run on the
416   // message loop. This requires the test case to run the message loop. If
417   // |async| is SYNC, the response will be returned synchronously. |error| is
418   // returned directly from ReadFrames() in the synchronous case, or passed to
419   // the callback in the asynchronous case. |frames| will be converted to a
420   // ScopedVector<WebSocketFrame> and copied to the pointer that was passed to
421   // ReadFrames().
422   template <size_t N>
423   void PrepareReadFrames(IsSync async,
424                          int error,
425                          const InitFrame (&frames)[N]) {
426     responses_.push_back(new Response(async, error, CreateFrameVector(frames)));
427   }
428
429   // An alternate version of PrepareReadFrames for when we need to construct
430   // the frames manually.
431   void PrepareRawReadFrames(IsSync async,
432                             int error,
433                             ScopedVector<WebSocketFrame> frames) {
434     responses_.push_back(new Response(async, error, frames.Pass()));
435   }
436
437   // Prepares a fake error response (ie. there is no data).
438   void PrepareReadFramesError(IsSync async, int error) {
439     responses_.push_back(
440         new Response(async, error, ScopedVector<WebSocketFrame>()));
441   }
442
443   virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
444                          const CompletionCallback& callback) OVERRIDE {
445     CHECK(!read_frames_pending_);
446     if (index_ >= responses_.size())
447       return ERR_IO_PENDING;
448     if (responses_[index_]->async == ASYNC) {
449       read_frames_pending_ = true;
450       base::MessageLoop::current()->PostTask(
451           FROM_HERE,
452           base::Bind(&ReadableFakeWebSocketStream::DoCallback,
453                      base::Unretained(this),
454                      frames,
455                      callback));
456       return ERR_IO_PENDING;
457     } else {
458       frames->swap(responses_[index_]->frames);
459       return responses_[index_++]->error;
460     }
461   }
462
463  private:
464   void DoCallback(ScopedVector<WebSocketFrame>* frames,
465                   const CompletionCallback& callback) {
466     read_frames_pending_ = false;
467     frames->swap(responses_[index_]->frames);
468     callback.Run(responses_[index_++]->error);
469     return;
470   }
471
472   struct Response {
473     Response(IsSync async, int error, ScopedVector<WebSocketFrame> frames)
474         : async(async), error(error), frames(frames.Pass()) {}
475
476     IsSync async;
477     int error;
478     ScopedVector<WebSocketFrame> frames;
479
480    private:
481     // Bad things will happen if we attempt to copy or assign |frames|.
482     DISALLOW_COPY_AND_ASSIGN(Response);
483   };
484   ScopedVector<Response> responses_;
485
486   // The index into the responses_ array of the next response to be returned.
487   size_t index_;
488
489   // True when an async response from ReadFrames() is pending. This only applies
490   // to "real" async responses. Once all the prepared responses have been
491   // returned, ReadFrames() returns ERR_IO_PENDING but read_frames_pending_ is
492   // not set to true.
493   bool read_frames_pending_;
494 };
495
496 // A FakeWebSocketStream where writes always complete successfully and
497 // synchronously.
498 class WriteableFakeWebSocketStream : public FakeWebSocketStream {
499  public:
500   virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
501                           const CompletionCallback& callback) OVERRIDE {
502     return OK;
503   }
504 };
505
506 // A FakeWebSocketStream where writes always fail.
507 class UnWriteableFakeWebSocketStream : public FakeWebSocketStream {
508  public:
509   virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
510                           const CompletionCallback& callback) OVERRIDE {
511     return ERR_CONNECTION_RESET;
512   }
513 };
514
515 // A FakeWebSocketStream which echoes any frames written back. Clears the
516 // "masked" header bit, but makes no other checks for validity. Tests using this
517 // must run the MessageLoop to receive the callback(s). If a message with opcode
518 // Close is echoed, then an ERR_CONNECTION_CLOSED is returned in the next
519 // callback. The test must do something to cause WriteFrames() to be called,
520 // otherwise the ReadFrames() callback will never be called.
521 class EchoeyFakeWebSocketStream : public FakeWebSocketStream {
522  public:
523   EchoeyFakeWebSocketStream() : read_frames_(NULL), done_(false) {}
524
525   virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
526                           const CompletionCallback& callback) OVERRIDE {
527     // Users of WebSocketStream will not expect the ReadFrames() callback to be
528     // called from within WriteFrames(), so post it to the message loop instead.
529     stored_frames_.insert(stored_frames_.end(), frames->begin(), frames->end());
530     frames->weak_clear();
531     PostCallback();
532     return OK;
533   }
534
535   virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
536                          const CompletionCallback& callback) OVERRIDE {
537     read_callback_ = callback;
538     read_frames_ = frames;
539     if (done_)
540       PostCallback();
541     return ERR_IO_PENDING;
542   }
543
544  private:
545   void PostCallback() {
546     base::MessageLoop::current()->PostTask(
547         FROM_HERE,
548         base::Bind(&EchoeyFakeWebSocketStream::DoCallback,
549                    base::Unretained(this)));
550   }
551
552   void DoCallback() {
553     if (done_) {
554       read_callback_.Run(ERR_CONNECTION_CLOSED);
555     } else if (!stored_frames_.empty()) {
556       done_ = MoveFrames(read_frames_);
557       read_frames_ = NULL;
558       read_callback_.Run(OK);
559     }
560   }
561
562   // Copy the frames stored in stored_frames_ to |out|, while clearing the
563   // "masked" header bit. Returns true if a Close Frame was seen, false
564   // otherwise.
565   bool MoveFrames(ScopedVector<WebSocketFrame>* out) {
566     bool seen_close = false;
567     *out = stored_frames_.Pass();
568     for (ScopedVector<WebSocketFrame>::iterator it = out->begin();
569          it != out->end();
570          ++it) {
571       WebSocketFrameHeader& header = (*it)->header;
572       header.masked = false;
573       if (header.opcode == WebSocketFrameHeader::kOpCodeClose)
574         seen_close = true;
575     }
576     return seen_close;
577   }
578
579   ScopedVector<WebSocketFrame> stored_frames_;
580   CompletionCallback read_callback_;
581   // Owned by the caller of ReadFrames().
582   ScopedVector<WebSocketFrame>* read_frames_;
583   // True if we should close the connection.
584   bool done_;
585 };
586
587 // A FakeWebSocketStream where writes trigger a connection reset.
588 // This differs from UnWriteableFakeWebSocketStream in that it is asynchronous
589 // and triggers ReadFrames to return a reset as well. Tests using this need to
590 // run the message loop. There are two tricky parts here:
591 // 1. Calling the write callback may call Close(), after which the read callback
592 //    should not be called.
593 // 2. Calling either callback may delete the stream altogether.
594 class ResetOnWriteFakeWebSocketStream : public FakeWebSocketStream {
595  public:
596   ResetOnWriteFakeWebSocketStream() : closed_(false), weak_ptr_factory_(this) {}
597
598   virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
599                           const CompletionCallback& callback) OVERRIDE {
600     base::MessageLoop::current()->PostTask(
601         FROM_HERE,
602         base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
603                    weak_ptr_factory_.GetWeakPtr(),
604                    callback,
605                    ERR_CONNECTION_RESET));
606     base::MessageLoop::current()->PostTask(
607         FROM_HERE,
608         base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
609                    weak_ptr_factory_.GetWeakPtr(),
610                    read_callback_,
611                    ERR_CONNECTION_RESET));
612     return ERR_IO_PENDING;
613   }
614
615   virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
616                          const CompletionCallback& callback) OVERRIDE {
617     read_callback_ = callback;
618     return ERR_IO_PENDING;
619   }
620
621   virtual void Close() OVERRIDE { closed_ = true; }
622
623  private:
624   void CallCallbackUnlessClosed(const CompletionCallback& callback, int value) {
625     if (!closed_)
626       callback.Run(value);
627   }
628
629   CompletionCallback read_callback_;
630   bool closed_;
631   // An IO error can result in the socket being deleted, so we use weak pointers
632   // to ensure correct behaviour in that case.
633   base::WeakPtrFactory<ResetOnWriteFakeWebSocketStream> weak_ptr_factory_;
634 };
635
636 // This mock is for verifying that WebSocket protocol semantics are obeyed (to
637 // the extent that they are implemented in WebSocketCommon).
638 class MockWebSocketStream : public WebSocketStream {
639  public:
640   MOCK_METHOD2(ReadFrames,
641                int(ScopedVector<WebSocketFrame>* frames,
642                    const CompletionCallback& callback));
643   MOCK_METHOD2(WriteFrames,
644                int(ScopedVector<WebSocketFrame>* frames,
645                    const CompletionCallback& callback));
646   MOCK_METHOD0(Close, void());
647   MOCK_CONST_METHOD0(GetSubProtocol, std::string());
648   MOCK_CONST_METHOD0(GetExtensions, std::string());
649   MOCK_METHOD0(AsWebSocketStream, WebSocketStream*());
650 };
651
652 struct ArgumentCopyingWebSocketStreamFactory {
653   scoped_ptr<WebSocketStreamRequest> Factory(
654       const GURL& socket_url,
655       const std::vector<std::string>& requested_subprotocols,
656       const GURL& origin,
657       URLRequestContext* url_request_context,
658       const BoundNetLog& net_log,
659       scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate) {
660     this->socket_url = socket_url;
661     this->requested_subprotocols = requested_subprotocols;
662     this->origin = origin;
663     this->url_request_context = url_request_context;
664     this->net_log = net_log;
665     this->connect_delegate = connect_delegate.Pass();
666     return make_scoped_ptr(new WebSocketStreamRequest);
667   }
668
669   GURL socket_url;
670   GURL origin;
671   std::vector<std::string> requested_subprotocols;
672   URLRequestContext* url_request_context;
673   BoundNetLog net_log;
674   scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate;
675 };
676
677 // Converts a std::string to a std::vector<char>. For test purposes, it is
678 // convenient to be able to specify data as a string, but the
679 // WebSocketEventInterface requires the vector<char> type.
680 std::vector<char> AsVector(const std::string& s) {
681   return std::vector<char>(s.begin(), s.end());
682 }
683
684 // Base class for all test fixtures.
685 class WebSocketChannelTest : public ::testing::Test {
686  protected:
687   WebSocketChannelTest() : stream_(new FakeWebSocketStream) {}
688
689   // Creates a new WebSocketChannel and connects it, using the settings stored
690   // in |connect_data_|.
691   void CreateChannelAndConnect() {
692     channel_.reset(new WebSocketChannel(CreateEventInterface(),
693                                         &connect_data_.url_request_context));
694     channel_->SendAddChannelRequestForTesting(
695         connect_data_.socket_url,
696         connect_data_.requested_subprotocols,
697         connect_data_.origin,
698         base::Bind(&ArgumentCopyingWebSocketStreamFactory::Factory,
699                    base::Unretained(&connect_data_.factory)));
700   }
701
702   // Same as CreateChannelAndConnect(), but calls the on_success callback as
703   // well. This method is virtual so that subclasses can also set the stream.
704   virtual void CreateChannelAndConnectSuccessfully() {
705     CreateChannelAndConnect();
706     connect_data_.factory.connect_delegate->OnSuccess(stream_.Pass());
707   }
708
709   // Returns a WebSocketEventInterface to be passed to the WebSocketChannel.
710   // This implementation returns a newly-created fake. Subclasses may return a
711   // mock instead.
712   virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() {
713     return scoped_ptr<WebSocketEventInterface>(new FakeWebSocketEventInterface);
714   }
715
716   // This method serves no other purpose than to provide a nice syntax for
717   // assigning to stream_. class T must be a subclass of WebSocketStream or you
718   // will have unpleasant compile errors.
719   template <class T>
720   void set_stream(scoped_ptr<T> stream) {
721     // Since the definition of "PassAs" depends on the type T, the C++ standard
722     // requires the "template" keyword to indicate that "PassAs" should be
723     // parsed as a template method.
724     stream_ = stream.template PassAs<WebSocketStream>();
725   }
726
727   // A struct containing the data that will be used to connect the channel.
728   // Grouped for readability.
729   struct ConnectData {
730     // URLRequestContext object.
731     URLRequestContext url_request_context;
732
733     // URL to (pretend to) connect to.
734     GURL socket_url;
735     // Requested protocols for the request.
736     std::vector<std::string> requested_subprotocols;
737     // Origin of the request
738     GURL origin;
739
740     // A fake WebSocketStreamFactory that just records its arguments.
741     ArgumentCopyingWebSocketStreamFactory factory;
742   };
743   ConnectData connect_data_;
744
745   // The channel we are testing. Not initialised until SetChannel() is called.
746   scoped_ptr<WebSocketChannel> channel_;
747
748   // A mock or fake stream for tests that need one.
749   scoped_ptr<WebSocketStream> stream_;
750 };
751
752 // enum of WebSocketEventInterface calls. These are intended to be or'd together
753 // in order to instruct WebSocketChannelDeletingTest when it should fail.
754 enum EventInterfaceCall {
755   EVENT_ON_ADD_CHANNEL_RESPONSE = 0x1,
756   EVENT_ON_DATA_FRAME = 0x2,
757   EVENT_ON_FLOW_CONTROL = 0x4,
758   EVENT_ON_CLOSING_HANDSHAKE = 0x8,
759   EVENT_ON_DROP_CHANNEL = 0x10,
760 };
761
762 class WebSocketChannelDeletingTest : public WebSocketChannelTest {
763  public:
764   ChannelState DeleteIfDeleting(EventInterfaceCall call) {
765     if (deleting_ & call) {
766       channel_.reset();
767       return CHANNEL_DELETED;
768     } else {
769       return CHANNEL_ALIVE;
770     }
771   }
772
773  protected:
774   WebSocketChannelDeletingTest()
775       : deleting_(EVENT_ON_ADD_CHANNEL_RESPONSE | EVENT_ON_DATA_FRAME |
776                   EVENT_ON_FLOW_CONTROL |
777                   EVENT_ON_CLOSING_HANDSHAKE |
778                   EVENT_ON_DROP_CHANNEL) {}
779   // Create a ChannelDeletingFakeWebSocketEventInterface. Defined out-of-line to
780   // avoid circular dependency.
781   virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() OVERRIDE;
782
783   // Tests can set deleting_ to a bitmap of EventInterfaceCall members that they
784   // want to cause Channel deletion. The default is for all calls to cause
785   // deletion.
786   int deleting_;
787 };
788
789 // A FakeWebSocketEventInterface that deletes the WebSocketChannel on failure to
790 // connect.
791 class ChannelDeletingFakeWebSocketEventInterface
792     : public FakeWebSocketEventInterface {
793  public:
794   ChannelDeletingFakeWebSocketEventInterface(
795       WebSocketChannelDeletingTest* fixture)
796       : fixture_(fixture) {}
797
798   virtual ChannelState OnAddChannelResponse(
799       bool fail,
800       const std::string& selected_protocol) OVERRIDE {
801     return fixture_->DeleteIfDeleting(EVENT_ON_ADD_CHANNEL_RESPONSE);
802   }
803
804   virtual ChannelState OnDataFrame(bool fin,
805                                    WebSocketMessageType type,
806                                    const std::vector<char>& data) OVERRIDE {
807     return fixture_->DeleteIfDeleting(EVENT_ON_DATA_FRAME);
808   }
809
810   virtual ChannelState OnFlowControl(int64 quota) OVERRIDE {
811     return fixture_->DeleteIfDeleting(EVENT_ON_FLOW_CONTROL);
812   }
813
814   virtual ChannelState OnClosingHandshake() OVERRIDE {
815     return fixture_->DeleteIfDeleting(EVENT_ON_CLOSING_HANDSHAKE);
816   }
817
818   virtual ChannelState OnDropChannel(uint16 code,
819                                      const std::string& reason) OVERRIDE {
820     return fixture_->DeleteIfDeleting(EVENT_ON_DROP_CHANNEL);
821   }
822
823  private:
824   // A pointer to the test fixture. Owned by the test harness; this object will
825   // be deleted before it is.
826   WebSocketChannelDeletingTest* fixture_;
827 };
828
829 scoped_ptr<WebSocketEventInterface>
830 WebSocketChannelDeletingTest::CreateEventInterface() {
831   return scoped_ptr<WebSocketEventInterface>(
832       new ChannelDeletingFakeWebSocketEventInterface(this));
833 }
834
835 // Base class for tests which verify that EventInterface methods are called
836 // appropriately.
837 class WebSocketChannelEventInterfaceTest : public WebSocketChannelTest {
838  protected:
839   WebSocketChannelEventInterfaceTest()
840       : event_interface_(new StrictMock<MockWebSocketEventInterface>) {
841     DefaultValue<ChannelState>::Set(CHANNEL_ALIVE);
842     ON_CALL(*event_interface_, OnAddChannelResponse(true, _))
843         .WillByDefault(Return(CHANNEL_DELETED));
844     ON_CALL(*event_interface_, OnDropChannel(_, _))
845         .WillByDefault(Return(CHANNEL_DELETED));
846   }
847
848   virtual ~WebSocketChannelEventInterfaceTest() {
849     DefaultValue<ChannelState>::Clear();
850   }
851
852   // Tests using this fixture must set expectations on the event_interface_ mock
853   // object before calling CreateChannelAndConnect() or
854   // CreateChannelAndConnectSuccessfully(). This will only work once per test
855   // case, but once should be enough.
856   virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() OVERRIDE {
857     return scoped_ptr<WebSocketEventInterface>(event_interface_.release());
858   }
859
860   scoped_ptr<MockWebSocketEventInterface> event_interface_;
861 };
862
863 // Base class for tests which verify that WebSocketStream methods are called
864 // appropriately by using a MockWebSocketStream.
865 class WebSocketChannelStreamTest : public WebSocketChannelTest {
866  protected:
867   WebSocketChannelStreamTest()
868       : mock_stream_(new StrictMock<MockWebSocketStream>) {}
869
870   virtual void CreateChannelAndConnectSuccessfully() OVERRIDE {
871     set_stream(mock_stream_.Pass());
872     WebSocketChannelTest::CreateChannelAndConnectSuccessfully();
873   }
874
875   scoped_ptr<MockWebSocketStream> mock_stream_;
876 };
877
878 // Simple test that everything that should be passed to the factory function is
879 // passed to the factory function.
880 TEST_F(WebSocketChannelTest, EverythingIsPassedToTheFactoryFunction) {
881   connect_data_.socket_url = GURL("ws://example.com/test");
882   connect_data_.origin = GURL("http://example.com/test");
883   connect_data_.requested_subprotocols.push_back("Sinbad");
884
885   CreateChannelAndConnect();
886
887   const ArgumentCopyingWebSocketStreamFactory& actual = connect_data_.factory;
888
889   EXPECT_EQ(&connect_data_.url_request_context, actual.url_request_context);
890
891   EXPECT_EQ(connect_data_.socket_url, actual.socket_url);
892   EXPECT_EQ(connect_data_.requested_subprotocols,
893             actual.requested_subprotocols);
894   EXPECT_EQ(connect_data_.origin, actual.origin);
895 }
896
897 // Any WebSocketEventInterface methods can delete the WebSocketChannel and
898 // return CHANNEL_DELETED. The WebSocketChannelDeletingTests are intended to
899 // verify that there are no use-after-free bugs when this happens. Problems will
900 // probably only be found when running under Address Sanitizer or a similar
901 // tool.
902 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseFail) {
903   CreateChannelAndConnect();
904   EXPECT_TRUE(channel_);
905   connect_data_.factory.connect_delegate->OnFailure(
906       kWebSocketErrorNoStatusReceived);
907   EXPECT_EQ(NULL, channel_.get());
908 }
909
910 // Deletion is possible (due to IPC failure) even if the connect succeeds.
911 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseSuccess) {
912   CreateChannelAndConnectSuccessfully();
913   EXPECT_EQ(NULL, channel_.get());
914 }
915
916 TEST_F(WebSocketChannelDeletingTest, OnDataFrameSync) {
917   scoped_ptr<ReadableFakeWebSocketStream> stream(
918       new ReadableFakeWebSocketStream);
919   static const InitFrame frames[] = {
920       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
921   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
922   set_stream(stream.Pass());
923   deleting_ = EVENT_ON_DATA_FRAME;
924
925   CreateChannelAndConnectSuccessfully();
926   EXPECT_EQ(NULL, channel_.get());
927 }
928
929 TEST_F(WebSocketChannelDeletingTest, OnDataFrameAsync) {
930   scoped_ptr<ReadableFakeWebSocketStream> stream(
931       new ReadableFakeWebSocketStream);
932   static const InitFrame frames[] = {
933       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
934   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
935   set_stream(stream.Pass());
936   deleting_ = EVENT_ON_DATA_FRAME;
937
938   CreateChannelAndConnectSuccessfully();
939   EXPECT_TRUE(channel_);
940   base::MessageLoop::current()->RunUntilIdle();
941   EXPECT_EQ(NULL, channel_.get());
942 }
943
944 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterConnect) {
945   deleting_ = EVENT_ON_FLOW_CONTROL;
946
947   CreateChannelAndConnectSuccessfully();
948   EXPECT_EQ(NULL, channel_.get());
949 }
950
951 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterSend) {
952   set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
953   // Avoid deleting the channel yet.
954   deleting_ = EVENT_ON_DROP_CHANNEL;
955   CreateChannelAndConnectSuccessfully();
956   ASSERT_TRUE(channel_);
957   deleting_ = EVENT_ON_FLOW_CONTROL;
958   channel_->SendFrame(true,
959                       WebSocketFrameHeader::kOpCodeText,
960                       std::vector<char>(kDefaultInitialQuota, 'B'));
961   EXPECT_EQ(NULL, channel_.get());
962 }
963
964 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeSync) {
965   scoped_ptr<ReadableFakeWebSocketStream> stream(
966       new ReadableFakeWebSocketStream);
967   static const InitFrame frames[] = {
968       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
969        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
970   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
971   set_stream(stream.Pass());
972   deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
973   CreateChannelAndConnectSuccessfully();
974   EXPECT_EQ(NULL, channel_.get());
975 }
976
977 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeAsync) {
978   scoped_ptr<ReadableFakeWebSocketStream> stream(
979       new ReadableFakeWebSocketStream);
980   static const InitFrame frames[] = {
981       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
982        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
983   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
984   set_stream(stream.Pass());
985   deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
986   CreateChannelAndConnectSuccessfully();
987   ASSERT_TRUE(channel_);
988   base::MessageLoop::current()->RunUntilIdle();
989   EXPECT_EQ(NULL, channel_.get());
990 }
991
992 TEST_F(WebSocketChannelDeletingTest, OnDropChannelWriteError) {
993   set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
994   deleting_ = EVENT_ON_DROP_CHANNEL;
995   CreateChannelAndConnectSuccessfully();
996   ASSERT_TRUE(channel_);
997   channel_->SendFrame(
998       true, WebSocketFrameHeader::kOpCodeText, AsVector("this will fail"));
999   EXPECT_EQ(NULL, channel_.get());
1000 }
1001
1002 TEST_F(WebSocketChannelDeletingTest, OnDropChannelReadError) {
1003   scoped_ptr<ReadableFakeWebSocketStream> stream(
1004       new ReadableFakeWebSocketStream);
1005   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1006                                  ERR_FAILED);
1007   set_stream(stream.Pass());
1008   deleting_ = EVENT_ON_DROP_CHANNEL;
1009   CreateChannelAndConnectSuccessfully();
1010   ASSERT_TRUE(channel_);
1011   base::MessageLoop::current()->RunUntilIdle();
1012   EXPECT_EQ(NULL, channel_.get());
1013 }
1014
1015 TEST_F(WebSocketChannelDeletingTest, FailChannelInSendFrame) {
1016   set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1017   deleting_ = EVENT_ON_DROP_CHANNEL;
1018   CreateChannelAndConnectSuccessfully();
1019   ASSERT_TRUE(channel_);
1020   channel_->SendFrame(true,
1021                       WebSocketFrameHeader::kOpCodeText,
1022                       std::vector<char>(kDefaultInitialQuota * 2, 'T'));
1023   EXPECT_EQ(NULL, channel_.get());
1024 }
1025
1026 TEST_F(WebSocketChannelDeletingTest, FailChannelInOnReadDone) {
1027   scoped_ptr<ReadableFakeWebSocketStream> stream(
1028       new ReadableFakeWebSocketStream);
1029   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1030                                  ERR_WS_PROTOCOL_ERROR);
1031   set_stream(stream.Pass());
1032   deleting_ = EVENT_ON_DROP_CHANNEL;
1033   CreateChannelAndConnectSuccessfully();
1034   ASSERT_TRUE(channel_);
1035   base::MessageLoop::current()->RunUntilIdle();
1036   EXPECT_EQ(NULL, channel_.get());
1037 }
1038
1039 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToMaskedFrame) {
1040   scoped_ptr<ReadableFakeWebSocketStream> stream(
1041       new ReadableFakeWebSocketStream);
1042   static const InitFrame frames[] = {
1043       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1044   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1045   set_stream(stream.Pass());
1046   deleting_ = EVENT_ON_DROP_CHANNEL;
1047
1048   CreateChannelAndConnectSuccessfully();
1049   EXPECT_EQ(NULL, channel_.get());
1050 }
1051
1052 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToBadControlFrame) {
1053   scoped_ptr<ReadableFakeWebSocketStream> stream(
1054       new ReadableFakeWebSocketStream);
1055   static const InitFrame frames[] = {
1056       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1057   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1058   set_stream(stream.Pass());
1059   deleting_ = EVENT_ON_DROP_CHANNEL;
1060
1061   CreateChannelAndConnectSuccessfully();
1062   EXPECT_EQ(NULL, channel_.get());
1063 }
1064
1065 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToPongAfterClose) {
1066   scoped_ptr<ReadableFakeWebSocketStream> stream(
1067       new ReadableFakeWebSocketStream);
1068   static const InitFrame frames[] = {
1069     {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
1070      CLOSE_DATA(NORMAL_CLOSURE, "Success")},
1071     {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1072   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1073   set_stream(stream.Pass());
1074   deleting_ = EVENT_ON_DROP_CHANNEL;
1075
1076   CreateChannelAndConnectSuccessfully();
1077   EXPECT_EQ(NULL, channel_.get());
1078 }
1079
1080 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToUnknownOpCode) {
1081   scoped_ptr<ReadableFakeWebSocketStream> stream(
1082       new ReadableFakeWebSocketStream);
1083   static const InitFrame frames[] = {{FINAL_FRAME, 0x7, NOT_MASKED, ""}};
1084   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1085   set_stream(stream.Pass());
1086   deleting_ = EVENT_ON_DROP_CHANNEL;
1087
1088   CreateChannelAndConnectSuccessfully();
1089   EXPECT_EQ(NULL, channel_.get());
1090 }
1091
1092 TEST_F(WebSocketChannelEventInterfaceTest, ConnectSuccessReported) {
1093   // false means success.
1094   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, ""));
1095   // OnFlowControl is always called immediately after connect to provide initial
1096   // quota to the renderer.
1097   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1098
1099   CreateChannelAndConnect();
1100
1101   connect_data_.factory.connect_delegate->OnSuccess(stream_.Pass());
1102 }
1103
1104 TEST_F(WebSocketChannelEventInterfaceTest, ConnectFailureReported) {
1105   // true means failure.
1106   EXPECT_CALL(*event_interface_, OnAddChannelResponse(true, ""));
1107
1108   CreateChannelAndConnect();
1109
1110   connect_data_.factory.connect_delegate->OnFailure(
1111       kWebSocketErrorNoStatusReceived);
1112 }
1113
1114 TEST_F(WebSocketChannelEventInterfaceTest, ProtocolPassed) {
1115   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, "Bob"));
1116   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1117
1118   CreateChannelAndConnect();
1119
1120   connect_data_.factory.connect_delegate->OnSuccess(
1121       scoped_ptr<WebSocketStream>(new FakeWebSocketStream("Bob", "")));
1122 }
1123
1124 // The first frames from the server can arrive together with the handshake, in
1125 // which case they will be available as soon as ReadFrames() is called the first
1126 // time.
1127 TEST_F(WebSocketChannelEventInterfaceTest, DataLeftFromHandshake) {
1128   scoped_ptr<ReadableFakeWebSocketStream> stream(
1129       new ReadableFakeWebSocketStream);
1130   static const InitFrame frames[] = {
1131       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1132   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1133   set_stream(stream.Pass());
1134   {
1135     InSequence s;
1136     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1137     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1138     EXPECT_CALL(
1139         *event_interface_,
1140         OnDataFrame(
1141             true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1142   }
1143
1144   CreateChannelAndConnectSuccessfully();
1145 }
1146
1147 // A remote server could accept the handshake, but then immediately send a
1148 // Close frame.
1149 TEST_F(WebSocketChannelEventInterfaceTest, CloseAfterHandshake) {
1150   scoped_ptr<ReadableFakeWebSocketStream> stream(
1151       new ReadableFakeWebSocketStream);
1152   static const InitFrame frames[] = {
1153       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1154        NOT_MASKED,  CLOSE_DATA(SERVER_ERROR, "Internal Server Error")}};
1155   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1156   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1157                                  ERR_CONNECTION_CLOSED);
1158   set_stream(stream.Pass());
1159   {
1160     InSequence s;
1161     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1162     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1163     EXPECT_CALL(*event_interface_, OnClosingHandshake());
1164     EXPECT_CALL(*event_interface_,
1165                 OnDropChannel(kWebSocketErrorInternalServerError,
1166                               "Internal Server Error"));
1167   }
1168
1169   CreateChannelAndConnectSuccessfully();
1170 }
1171
1172 // A remote server could close the connection immediately after sending the
1173 // handshake response (most likely a bug in the server).
1174 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionCloseAfterHandshake) {
1175   scoped_ptr<ReadableFakeWebSocketStream> stream(
1176       new ReadableFakeWebSocketStream);
1177   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1178                                  ERR_CONNECTION_CLOSED);
1179   set_stream(stream.Pass());
1180   {
1181     InSequence s;
1182     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1183     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1184     EXPECT_CALL(*event_interface_,
1185                 OnDropChannel(kWebSocketErrorAbnormalClosure, _));
1186   }
1187
1188   CreateChannelAndConnectSuccessfully();
1189 }
1190
1191 TEST_F(WebSocketChannelEventInterfaceTest, NormalAsyncRead) {
1192   scoped_ptr<ReadableFakeWebSocketStream> stream(
1193       new ReadableFakeWebSocketStream);
1194   static const InitFrame frames[] = {
1195       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1196   // We use this checkpoint object to verify that the callback isn't called
1197   // until we expect it to be.
1198   Checkpoint checkpoint;
1199   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1200   set_stream(stream.Pass());
1201   {
1202     InSequence s;
1203     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1204     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1205     EXPECT_CALL(checkpoint, Call(1));
1206     EXPECT_CALL(
1207         *event_interface_,
1208         OnDataFrame(
1209             true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1210     EXPECT_CALL(checkpoint, Call(2));
1211   }
1212
1213   CreateChannelAndConnectSuccessfully();
1214   checkpoint.Call(1);
1215   base::MessageLoop::current()->RunUntilIdle();
1216   checkpoint.Call(2);
1217 }
1218
1219 // Extra data can arrive while a read is being processed, resulting in the next
1220 // read completing synchronously.
1221 TEST_F(WebSocketChannelEventInterfaceTest, AsyncThenSyncRead) {
1222   scoped_ptr<ReadableFakeWebSocketStream> stream(
1223       new ReadableFakeWebSocketStream);
1224   static const InitFrame frames1[] = {
1225       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1226   static const InitFrame frames2[] = {
1227       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "WORLD"}};
1228   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1229   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames2);
1230   set_stream(stream.Pass());
1231   {
1232     InSequence s;
1233     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1234     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1235     EXPECT_CALL(
1236         *event_interface_,
1237         OnDataFrame(
1238             true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1239     EXPECT_CALL(
1240         *event_interface_,
1241         OnDataFrame(
1242             true, WebSocketFrameHeader::kOpCodeText, AsVector("WORLD")));
1243   }
1244
1245   CreateChannelAndConnectSuccessfully();
1246   base::MessageLoop::current()->RunUntilIdle();
1247 }
1248
1249 // Data frames are delivered the same regardless of how many reads they arrive
1250 // as.
1251 TEST_F(WebSocketChannelEventInterfaceTest, FragmentedMessage) {
1252   scoped_ptr<ReadableFakeWebSocketStream> stream(
1253       new ReadableFakeWebSocketStream);
1254   // Here we have one message which arrived in five frames split across three
1255   // reads. It may have been reframed on arrival, but this class doesn't care
1256   // about that.
1257   static const InitFrame frames1[] = {
1258       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "THREE"},
1259       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1260        NOT_MASKED,      " "}};
1261   static const InitFrame frames2[] = {
1262       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1263        NOT_MASKED,      "SMALL"}};
1264   static const InitFrame frames3[] = {
1265       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1266        NOT_MASKED,      " "},
1267       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1268        NOT_MASKED,  "FRAMES"}};
1269   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1270   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1271   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1272   set_stream(stream.Pass());
1273   {
1274     InSequence s;
1275     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1276     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1277     EXPECT_CALL(
1278         *event_interface_,
1279         OnDataFrame(
1280             false, WebSocketFrameHeader::kOpCodeText, AsVector("THREE")));
1281     EXPECT_CALL(
1282         *event_interface_,
1283         OnDataFrame(
1284             false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1285     EXPECT_CALL(*event_interface_,
1286                 OnDataFrame(false,
1287                             WebSocketFrameHeader::kOpCodeContinuation,
1288                             AsVector("SMALL")));
1289     EXPECT_CALL(
1290         *event_interface_,
1291         OnDataFrame(
1292             false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1293     EXPECT_CALL(*event_interface_,
1294                 OnDataFrame(true,
1295                             WebSocketFrameHeader::kOpCodeContinuation,
1296                             AsVector("FRAMES")));
1297   }
1298
1299   CreateChannelAndConnectSuccessfully();
1300   base::MessageLoop::current()->RunUntilIdle();
1301 }
1302
1303 // A control frame is not permitted to be split into multiple frames. RFC6455
1304 // 5.5 "All control frames ... MUST NOT be fragmented."
1305 TEST_F(WebSocketChannelEventInterfaceTest, MultiFrameControlMessageIsRejected) {
1306   scoped_ptr<ReadableFakeWebSocketStream> stream(
1307       new ReadableFakeWebSocketStream);
1308   static const InitFrame frames[] = {
1309       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePing, NOT_MASKED, "Pi"},
1310       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1311        NOT_MASKED,  "ng"}};
1312   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1313   set_stream(stream.Pass());
1314   {
1315     InSequence s;
1316     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1317     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1318     EXPECT_CALL(*event_interface_,
1319                 OnDropChannel(kWebSocketErrorProtocolError, _));
1320   }
1321
1322   CreateChannelAndConnectSuccessfully();
1323   base::MessageLoop::current()->RunUntilIdle();
1324 }
1325
1326 // Connection closed by the remote host without a closing handshake.
1327 TEST_F(WebSocketChannelEventInterfaceTest, AsyncAbnormalClosure) {
1328   scoped_ptr<ReadableFakeWebSocketStream> stream(
1329       new ReadableFakeWebSocketStream);
1330   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1331                                  ERR_CONNECTION_CLOSED);
1332   set_stream(stream.Pass());
1333   {
1334     InSequence s;
1335     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1336     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1337     EXPECT_CALL(*event_interface_,
1338                 OnDropChannel(kWebSocketErrorAbnormalClosure, _));
1339   }
1340
1341   CreateChannelAndConnectSuccessfully();
1342   base::MessageLoop::current()->RunUntilIdle();
1343 }
1344
1345 // A connection reset should produce the same event as an unexpected closure.
1346 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionReset) {
1347   scoped_ptr<ReadableFakeWebSocketStream> stream(
1348       new ReadableFakeWebSocketStream);
1349   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1350                                  ERR_CONNECTION_RESET);
1351   set_stream(stream.Pass());
1352   {
1353     InSequence s;
1354     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1355     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1356     EXPECT_CALL(*event_interface_,
1357                 OnDropChannel(kWebSocketErrorAbnormalClosure, _));
1358   }
1359
1360   CreateChannelAndConnectSuccessfully();
1361   base::MessageLoop::current()->RunUntilIdle();
1362 }
1363
1364 // RFC6455 5.1 "A client MUST close a connection if it detects a masked frame."
1365 TEST_F(WebSocketChannelEventInterfaceTest, MaskedFramesAreRejected) {
1366   scoped_ptr<ReadableFakeWebSocketStream> stream(
1367       new ReadableFakeWebSocketStream);
1368   static const InitFrame frames[] = {
1369       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1370
1371   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1372   set_stream(stream.Pass());
1373   {
1374     InSequence s;
1375     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1376     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1377     EXPECT_CALL(*event_interface_,
1378                 OnDropChannel(kWebSocketErrorProtocolError, _));
1379   }
1380
1381   CreateChannelAndConnectSuccessfully();
1382   base::MessageLoop::current()->RunUntilIdle();
1383 }
1384
1385 // RFC6455 5.2 "If an unknown opcode is received, the receiving endpoint MUST
1386 // _Fail the WebSocket Connection_."
1387 TEST_F(WebSocketChannelEventInterfaceTest, UnknownOpCodeIsRejected) {
1388   scoped_ptr<ReadableFakeWebSocketStream> stream(
1389       new ReadableFakeWebSocketStream);
1390   static const InitFrame frames[] = {{FINAL_FRAME, 4, NOT_MASKED, "HELLO"}};
1391
1392   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1393   set_stream(stream.Pass());
1394   {
1395     InSequence s;
1396     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1397     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1398     EXPECT_CALL(*event_interface_,
1399                 OnDropChannel(kWebSocketErrorProtocolError, _));
1400   }
1401
1402   CreateChannelAndConnectSuccessfully();
1403   base::MessageLoop::current()->RunUntilIdle();
1404 }
1405
1406 // RFC6455 5.4 "Control frames ... MAY be injected in the middle of a
1407 // fragmented message."
1408 TEST_F(WebSocketChannelEventInterfaceTest, ControlFrameInDataMessage) {
1409   scoped_ptr<ReadableFakeWebSocketStream> stream(
1410       new ReadableFakeWebSocketStream);
1411   // We have one message of type Text split into two frames. In the middle is a
1412   // control message of type Pong.
1413   static const InitFrame frames1[] = {
1414       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
1415        NOT_MASKED,      "SPLIT "}};
1416   static const InitFrame frames2[] = {
1417       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1418   static const InitFrame frames3[] = {
1419       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1420        NOT_MASKED,  "MESSAGE"}};
1421   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1422   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1423   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1424   set_stream(stream.Pass());
1425   {
1426     InSequence s;
1427     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1428     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1429     EXPECT_CALL(
1430         *event_interface_,
1431         OnDataFrame(
1432             false, WebSocketFrameHeader::kOpCodeText, AsVector("SPLIT ")));
1433     EXPECT_CALL(*event_interface_,
1434                 OnDataFrame(true,
1435                             WebSocketFrameHeader::kOpCodeContinuation,
1436                             AsVector("MESSAGE")));
1437   }
1438
1439   CreateChannelAndConnectSuccessfully();
1440   base::MessageLoop::current()->RunUntilIdle();
1441 }
1442
1443 // If a frame has an invalid header, then the connection is closed and
1444 // subsequent frames must not trigger events.
1445 TEST_F(WebSocketChannelEventInterfaceTest, FrameAfterInvalidFrame) {
1446   scoped_ptr<ReadableFakeWebSocketStream> stream(
1447       new ReadableFakeWebSocketStream);
1448   static const InitFrame frames[] = {
1449       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"},
1450       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, " WORLD"}};
1451
1452   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1453   set_stream(stream.Pass());
1454   {
1455     InSequence s;
1456     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1457     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1458     EXPECT_CALL(*event_interface_,
1459                 OnDropChannel(kWebSocketErrorProtocolError, _));
1460   }
1461
1462   CreateChannelAndConnectSuccessfully();
1463   base::MessageLoop::current()->RunUntilIdle();
1464 }
1465
1466 // If the renderer sends lots of small writes, we don't want to update the quota
1467 // for each one.
1468 TEST_F(WebSocketChannelEventInterfaceTest, SmallWriteDoesntUpdateQuota) {
1469   set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1470   {
1471     InSequence s;
1472     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1473     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1474   }
1475
1476   CreateChannelAndConnectSuccessfully();
1477   channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("B"));
1478 }
1479
1480 // If we send enough to go below send_quota_low_water_mask_ we should get our
1481 // quota refreshed.
1482 TEST_F(WebSocketChannelEventInterfaceTest, LargeWriteUpdatesQuota) {
1483   set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1484   // We use this checkpoint object to verify that the quota update comes after
1485   // the write.
1486   Checkpoint checkpoint;
1487   {
1488     InSequence s;
1489     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1490     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1491     EXPECT_CALL(checkpoint, Call(1));
1492     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1493     EXPECT_CALL(checkpoint, Call(2));
1494   }
1495
1496   CreateChannelAndConnectSuccessfully();
1497   checkpoint.Call(1);
1498   channel_->SendFrame(true,
1499                       WebSocketFrameHeader::kOpCodeText,
1500                       std::vector<char>(kDefaultInitialQuota, 'B'));
1501   checkpoint.Call(2);
1502 }
1503
1504 // Verify that our quota actually is refreshed when we are told it is.
1505 TEST_F(WebSocketChannelEventInterfaceTest, QuotaReallyIsRefreshed) {
1506   set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1507   Checkpoint checkpoint;
1508   {
1509     InSequence s;
1510     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1511     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1512     EXPECT_CALL(checkpoint, Call(1));
1513     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1514     EXPECT_CALL(checkpoint, Call(2));
1515     // If quota was not really refreshed, we would get an OnDropChannel()
1516     // message.
1517     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1518     EXPECT_CALL(checkpoint, Call(3));
1519   }
1520
1521   CreateChannelAndConnectSuccessfully();
1522   checkpoint.Call(1);
1523   channel_->SendFrame(true,
1524                       WebSocketFrameHeader::kOpCodeText,
1525                       std::vector<char>(kDefaultQuotaRefreshTrigger, 'D'));
1526   checkpoint.Call(2);
1527   // We should have received more quota at this point.
1528   channel_->SendFrame(true,
1529                       WebSocketFrameHeader::kOpCodeText,
1530                       std::vector<char>(kDefaultQuotaRefreshTrigger, 'E'));
1531   checkpoint.Call(3);
1532 }
1533
1534 // If we send more than the available quota then the connection will be closed
1535 // with an error.
1536 TEST_F(WebSocketChannelEventInterfaceTest, WriteOverQuotaIsRejected) {
1537   set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1538   {
1539     InSequence s;
1540     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1541     EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
1542     EXPECT_CALL(*event_interface_,
1543                 OnDropChannel(kWebSocketMuxErrorSendQuotaViolation, _));
1544   }
1545
1546   CreateChannelAndConnectSuccessfully();
1547   channel_->SendFrame(true,
1548                       WebSocketFrameHeader::kOpCodeText,
1549                       std::vector<char>(kDefaultInitialQuota + 1, 'C'));
1550 }
1551
1552 // If a write fails, the channel is dropped.
1553 TEST_F(WebSocketChannelEventInterfaceTest, FailedWrite) {
1554   set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
1555   Checkpoint checkpoint;
1556   {
1557     InSequence s;
1558     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1559     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1560     EXPECT_CALL(checkpoint, Call(1));
1561     EXPECT_CALL(*event_interface_,
1562                 OnDropChannel(kWebSocketErrorAbnormalClosure, _));
1563     EXPECT_CALL(checkpoint, Call(2));
1564   }
1565
1566   CreateChannelAndConnectSuccessfully();
1567   checkpoint.Call(1);
1568
1569   channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("H"));
1570   checkpoint.Call(2);
1571 }
1572
1573 // OnDropChannel() is called exactly once when StartClosingHandshake() is used.
1574 TEST_F(WebSocketChannelEventInterfaceTest, SendCloseDropsChannel) {
1575   set_stream(make_scoped_ptr(new EchoeyFakeWebSocketStream));
1576   {
1577     InSequence s;
1578     EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1579     EXPECT_CALL(*event_interface_, OnFlowControl(_));
1580     EXPECT_CALL(*event_interface_,
1581                 OnDropChannel(kWebSocketNormalClosure, "Fred"));
1582   }
1583
1584   CreateChannelAndConnectSuccessfully();
1585
1586   channel_->StartClosingHandshake(kWebSocketNormalClosure, "Fred");
1587   base::MessageLoop::current()->RunUntilIdle();
1588 }
1589
1590 // OnDropChannel() is only called once when a write() on the socket triggers a
1591 // connection reset.
1592 TEST_F(WebSocketChannelEventInterfaceTest, OnDropChannelCalledOnce) {
1593   set_stream(make_scoped_ptr(new ResetOnWriteFakeWebSocketStream));
1594   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1595   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1596
1597   EXPECT_CALL(*event_interface_,
1598               OnDropChannel(kWebSocketErrorAbnormalClosure, "Abnormal Closure"))
1599       .Times(1);
1600
1601   CreateChannelAndConnectSuccessfully();
1602
1603   channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("yt?"));
1604   base::MessageLoop::current()->RunUntilIdle();
1605 }
1606
1607 // When the remote server sends a Close frame with an empty payload,
1608 // WebSocketChannel should report code 1005, kWebSocketErrorNoStatusReceived.
1609 TEST_F(WebSocketChannelEventInterfaceTest, CloseWithNoPayloadGivesStatus1005) {
1610   scoped_ptr<ReadableFakeWebSocketStream> stream(
1611       new ReadableFakeWebSocketStream);
1612   static const InitFrame frames[] = {
1613       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
1614   stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1615   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1616                                  ERR_CONNECTION_CLOSED);
1617   set_stream(stream.Pass());
1618   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1619   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1620   EXPECT_CALL(*event_interface_, OnClosingHandshake());
1621   EXPECT_CALL(*event_interface_,
1622               OnDropChannel(kWebSocketErrorNoStatusReceived, _));
1623
1624   CreateChannelAndConnectSuccessfully();
1625 }
1626
1627 // If ReadFrames() returns ERR_WS_PROTOCOL_ERROR, then
1628 // kWebSocketErrorProtocolError must be sent to the renderer.
1629 TEST_F(WebSocketChannelEventInterfaceTest, SyncProtocolErrorGivesStatus1002) {
1630   scoped_ptr<ReadableFakeWebSocketStream> stream(
1631       new ReadableFakeWebSocketStream);
1632   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1633                                  ERR_WS_PROTOCOL_ERROR);
1634   set_stream(stream.Pass());
1635   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1636   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1637
1638   EXPECT_CALL(*event_interface_,
1639               OnDropChannel(kWebSocketErrorProtocolError, _));
1640
1641   CreateChannelAndConnectSuccessfully();
1642 }
1643
1644 // Async version of above test.
1645 TEST_F(WebSocketChannelEventInterfaceTest, AsyncProtocolErrorGivesStatus1002) {
1646   scoped_ptr<ReadableFakeWebSocketStream> stream(
1647       new ReadableFakeWebSocketStream);
1648   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1649                                  ERR_WS_PROTOCOL_ERROR);
1650   set_stream(stream.Pass());
1651   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1652   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1653
1654   EXPECT_CALL(*event_interface_,
1655               OnDropChannel(kWebSocketErrorProtocolError, _));
1656
1657   CreateChannelAndConnectSuccessfully();
1658   base::MessageLoop::current()->RunUntilIdle();
1659 }
1660
1661 // The closing handshake times out and sends an OnDropChannel event if no
1662 // response to the client Close message is received.
1663 TEST_F(WebSocketChannelEventInterfaceTest,
1664        ClientInitiatedClosingHandshakeTimesOut) {
1665   scoped_ptr<ReadableFakeWebSocketStream> stream(
1666       new ReadableFakeWebSocketStream);
1667   stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1668                                  ERR_IO_PENDING);
1669   set_stream(stream.Pass());
1670   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1671   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1672   // This checkpoint object verifies that the OnDropChannel message comes after
1673   // the timeout.
1674   Checkpoint checkpoint;
1675   TestClosure completion;
1676   {
1677     InSequence s;
1678     EXPECT_CALL(checkpoint, Call(1));
1679     EXPECT_CALL(*event_interface_,
1680                 OnDropChannel(kWebSocketErrorAbnormalClosure, _))
1681         .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
1682   }
1683   CreateChannelAndConnectSuccessfully();
1684   // OneShotTimer is not very friendly to testing; there is no apparent way to
1685   // set an expectation on it. Instead the tests need to infer that the timeout
1686   // was fired by the behaviour of the WebSocketChannel object.
1687   channel_->SetClosingHandshakeTimeoutForTesting(
1688       TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
1689   channel_->StartClosingHandshake(kWebSocketNormalClosure, "");
1690   checkpoint.Call(1);
1691   completion.WaitForResult();
1692 }
1693
1694 // The closing handshake times out and sends an OnDropChannel event if a Close
1695 // message is received but the connection isn't closed by the remote host.
1696 TEST_F(WebSocketChannelEventInterfaceTest,
1697        ServerInitiatedClosingHandshakeTimesOut) {
1698   scoped_ptr<ReadableFakeWebSocketStream> stream(
1699       new ReadableFakeWebSocketStream);
1700   static const InitFrame frames[] = {
1701       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1702        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
1703   stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1704   set_stream(stream.Pass());
1705   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1706   EXPECT_CALL(*event_interface_, OnFlowControl(_));
1707   Checkpoint checkpoint;
1708   TestClosure completion;
1709   {
1710     InSequence s;
1711     EXPECT_CALL(checkpoint, Call(1));
1712     EXPECT_CALL(*event_interface_, OnClosingHandshake());
1713     EXPECT_CALL(*event_interface_,
1714                 OnDropChannel(kWebSocketErrorAbnormalClosure, _))
1715         .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
1716   }
1717   CreateChannelAndConnectSuccessfully();
1718   channel_->SetClosingHandshakeTimeoutForTesting(
1719       TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
1720   checkpoint.Call(1);
1721   completion.WaitForResult();
1722 }
1723
1724 // RFC6455 5.1 "a client MUST mask all frames that it sends to the server".
1725 // WebSocketChannel actually only sets the mask bit in the header, it doesn't
1726 // perform masking itself (not all transports actually use masking).
1727 TEST_F(WebSocketChannelStreamTest, SentFramesAreMasked) {
1728   static const InitFrame expected[] = {
1729       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
1730        MASKED,      "NEEDS MASKING"}};
1731   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1732   EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
1733   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
1734       .WillOnce(Return(OK));
1735
1736   CreateChannelAndConnectSuccessfully();
1737   channel_->SendFrame(
1738       true, WebSocketFrameHeader::kOpCodeText, AsVector("NEEDS MASKING"));
1739 }
1740
1741 // RFC6455 5.5.1 "The application MUST NOT send any more data frames after
1742 // sending a Close frame."
1743 TEST_F(WebSocketChannelStreamTest, NothingIsSentAfterClose) {
1744   static const InitFrame expected[] = {
1745       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1746        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
1747   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1748   EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
1749   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
1750       .WillOnce(Return(OK));
1751
1752   CreateChannelAndConnectSuccessfully();
1753   channel_->StartClosingHandshake(1000, "Success");
1754   channel_->SendFrame(
1755       true, WebSocketFrameHeader::kOpCodeText, AsVector("SHOULD  BE IGNORED"));
1756 }
1757
1758 // RFC6455 5.5.1 "If an endpoint receives a Close frame and did not previously
1759 // send a Close frame, the endpoint MUST send a Close frame in response."
1760 TEST_F(WebSocketChannelStreamTest, CloseIsEchoedBack) {
1761   static const InitFrame frames[] = {
1762       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1763        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
1764   static const InitFrame expected[] = {
1765       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1766        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
1767   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1768   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1769       .WillOnce(ReturnFrames(&frames))
1770       .WillRepeatedly(Return(ERR_IO_PENDING));
1771   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
1772       .WillOnce(Return(OK));
1773
1774   CreateChannelAndConnectSuccessfully();
1775 }
1776
1777 // The converse of the above case; after sending a Close frame, we should not
1778 // send another one.
1779 TEST_F(WebSocketChannelStreamTest, CloseOnlySentOnce) {
1780   static const InitFrame expected[] = {
1781       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1782        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
1783   static const InitFrame frames_init[] = {
1784       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1785        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
1786
1787   // We store the parameters that were passed to ReadFrames() so that we can
1788   // call them explicitly later.
1789   CompletionCallback read_callback;
1790   ScopedVector<WebSocketFrame>* frames = NULL;
1791
1792   // Use a checkpoint to make the ordering of events clearer.
1793   Checkpoint checkpoint;
1794   {
1795     InSequence s;
1796     EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1797     EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1798         .WillOnce(DoAll(SaveArg<0>(&frames),
1799                         SaveArg<1>(&read_callback),
1800                         Return(ERR_IO_PENDING)));
1801     EXPECT_CALL(checkpoint, Call(1));
1802     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
1803         .WillOnce(Return(OK));
1804     EXPECT_CALL(checkpoint, Call(2));
1805     EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1806         .WillOnce(Return(ERR_IO_PENDING));
1807     EXPECT_CALL(checkpoint, Call(3));
1808     // WriteFrames() must not be called again. GoogleMock will ensure that the
1809     // test fails if it is.
1810   }
1811
1812   CreateChannelAndConnectSuccessfully();
1813   checkpoint.Call(1);
1814   channel_->StartClosingHandshake(kWebSocketNormalClosure, "Close");
1815   checkpoint.Call(2);
1816
1817   *frames = CreateFrameVector(frames_init);
1818   read_callback.Run(OK);
1819   checkpoint.Call(3);
1820 }
1821
1822 // Invalid close status codes should not be sent on the network.
1823 TEST_F(WebSocketChannelStreamTest, InvalidCloseStatusCodeNotSent) {
1824   static const InitFrame expected[] = {
1825       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1826        MASKED,      CLOSE_DATA(SERVER_ERROR, "Internal Error")}};
1827
1828   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1829   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1830       .WillOnce(Return(ERR_IO_PENDING));
1831
1832   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
1833
1834   CreateChannelAndConnectSuccessfully();
1835   channel_->StartClosingHandshake(999, "");
1836 }
1837
1838 // A Close frame with a reason longer than 123 bytes cannot be sent on the
1839 // network.
1840 TEST_F(WebSocketChannelStreamTest, LongCloseReasonNotSent) {
1841   static const InitFrame expected[] = {
1842       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1843        MASKED,      CLOSE_DATA(SERVER_ERROR, "Internal Error")}};
1844
1845   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1846   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1847       .WillOnce(Return(ERR_IO_PENDING));
1848
1849   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
1850
1851   CreateChannelAndConnectSuccessfully();
1852   channel_->StartClosingHandshake(1000, std::string(124, 'A'));
1853 }
1854
1855 // We generate code 1005, kWebSocketErrorNoStatusReceived, when there is no
1856 // status in the Close message from the other side. Code 1005 is not allowed to
1857 // appear on the wire, so we should not echo it back. See test
1858 // CloseWithNoPayloadGivesStatus1005, above, for confirmation that code 1005 is
1859 // correctly generated internally.
1860 TEST_F(WebSocketChannelStreamTest, Code1005IsNotEchoed) {
1861   static const InitFrame frames[] = {
1862       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
1863   static const InitFrame expected[] = {
1864       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED, ""}};
1865   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1866   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1867       .WillOnce(ReturnFrames(&frames))
1868       .WillRepeatedly(Return(ERR_IO_PENDING));
1869   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
1870       .WillOnce(Return(OK));
1871
1872   CreateChannelAndConnectSuccessfully();
1873 }
1874
1875 // RFC6455 5.5.2 "Upon receipt of a Ping frame, an endpoint MUST send a Pong
1876 // frame in response"
1877 // 5.5.3 "A Pong frame sent in response to a Ping frame must have identical
1878 // "Application data" as found in the message body of the Ping frame being
1879 // replied to."
1880 TEST_F(WebSocketChannelStreamTest, PingRepliedWithPong) {
1881   static const InitFrame frames[] = {
1882       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
1883        NOT_MASKED,  "Application data"}};
1884   static const InitFrame expected[] = {
1885       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
1886        MASKED,      "Application data"}};
1887   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1888   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1889       .WillOnce(ReturnFrames(&frames))
1890       .WillRepeatedly(Return(ERR_IO_PENDING));
1891   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
1892       .WillOnce(Return(OK));
1893
1894   CreateChannelAndConnectSuccessfully();
1895 }
1896
1897 TEST_F(WebSocketChannelStreamTest, PongInTheMiddleOfDataMessage) {
1898   static const InitFrame frames[] = {
1899       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
1900        NOT_MASKED,  "Application data"}};
1901   static const InitFrame expected1[] = {
1902       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
1903   static const InitFrame expected2[] = {
1904       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
1905        MASKED,      "Application data"}};
1906   static const InitFrame expected3[] = {
1907       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1908        MASKED,      "World"}};
1909   ScopedVector<WebSocketFrame>* read_frames;
1910   CompletionCallback read_callback;
1911   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1912   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1913       .WillOnce(DoAll(SaveArg<0>(&read_frames),
1914                       SaveArg<1>(&read_callback),
1915                       Return(ERR_IO_PENDING)))
1916       .WillRepeatedly(Return(ERR_IO_PENDING));
1917   {
1918     InSequence s;
1919
1920     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
1921         .WillOnce(Return(OK));
1922     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
1923         .WillOnce(Return(OK));
1924     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected3), _))
1925         .WillOnce(Return(OK));
1926   }
1927
1928   CreateChannelAndConnectSuccessfully();
1929   channel_->SendFrame(
1930       false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
1931   *read_frames = CreateFrameVector(frames);
1932   read_callback.Run(OK);
1933   channel_->SendFrame(
1934       true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("World"));
1935 }
1936
1937 // WriteFrames() may not be called until the previous write has completed.
1938 // WebSocketChannel must buffer writes that happen in the meantime.
1939 TEST_F(WebSocketChannelStreamTest, WriteFramesOneAtATime) {
1940   static const InitFrame expected1[] = {
1941       {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
1942   static const InitFrame expected2[] = {
1943       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "World"}};
1944   CompletionCallback write_callback;
1945   Checkpoint checkpoint;
1946
1947   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1948   EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
1949   {
1950     InSequence s;
1951     EXPECT_CALL(checkpoint, Call(1));
1952     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
1953         .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
1954     EXPECT_CALL(checkpoint, Call(2));
1955     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
1956         .WillOnce(Return(ERR_IO_PENDING));
1957     EXPECT_CALL(checkpoint, Call(3));
1958   }
1959
1960   CreateChannelAndConnectSuccessfully();
1961   checkpoint.Call(1);
1962   channel_->SendFrame(
1963       false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
1964   channel_->SendFrame(
1965       true, WebSocketFrameHeader::kOpCodeText, AsVector("World"));
1966   checkpoint.Call(2);
1967   write_callback.Run(OK);
1968   checkpoint.Call(3);
1969 }
1970
1971 // WebSocketChannel must buffer frames while it is waiting for a write to
1972 // complete, and then send them in a single batch. The batching behaviour is
1973 // important to get good throughput in the "many small messages" case.
1974 TEST_F(WebSocketChannelStreamTest, WaitingMessagesAreBatched) {
1975   static const char input_letters[] = "Hello";
1976   static const InitFrame expected1[] = {
1977       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "H"}};
1978   static const InitFrame expected2[] = {
1979       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "e"},
1980       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
1981       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
1982       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "o"}};
1983   CompletionCallback write_callback;
1984
1985   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1986   EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
1987   {
1988     InSequence s;
1989     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
1990         .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
1991     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
1992         .WillOnce(Return(ERR_IO_PENDING));
1993   }
1994
1995   CreateChannelAndConnectSuccessfully();
1996   for (size_t i = 0; i < strlen(input_letters); ++i) {
1997     channel_->SendFrame(true,
1998                         WebSocketFrameHeader::kOpCodeText,
1999                         std::vector<char>(1, input_letters[i]));
2000   }
2001   write_callback.Run(OK);
2002 }
2003
2004 // When the renderer sends more on a channel than it has quota for, then we send
2005 // a kWebSocketMuxErrorSendQuotaViolation status code (from the draft websocket
2006 // mux specification) back to the renderer. This should not be sent to the
2007 // remote server, which may not even implement the mux specification, and could
2008 // even be using a different extension which uses that code to mean something
2009 // else.
2010 TEST_F(WebSocketChannelStreamTest, MuxErrorIsNotSentToStream) {
2011   static const InitFrame expected[] = {
2012       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2013        MASKED,      CLOSE_DATA(GOING_AWAY, "Internal Error")}};
2014   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2015   EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2016   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2017       .WillOnce(Return(OK));
2018   EXPECT_CALL(*mock_stream_, Close());
2019
2020   CreateChannelAndConnectSuccessfully();
2021   channel_->SendFrame(true,
2022                       WebSocketFrameHeader::kOpCodeText,
2023                       std::vector<char>(kDefaultInitialQuota + 1, 'C'));
2024 }
2025
2026 // For convenience, most of these tests use Text frames. However, the WebSocket
2027 // protocol also has Binary frames and those need to be 8-bit clean. For the
2028 // sake of completeness, this test verifies that they are.
2029 TEST_F(WebSocketChannelStreamTest, WrittenBinaryFramesAre8BitClean) {
2030   ScopedVector<WebSocketFrame>* frames = NULL;
2031
2032   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2033   EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2034   EXPECT_CALL(*mock_stream_, WriteFrames(_, _))
2035       .WillOnce(DoAll(SaveArg<0>(&frames), Return(ERR_IO_PENDING)));
2036
2037   CreateChannelAndConnectSuccessfully();
2038   channel_->SendFrame(
2039       true,
2040       WebSocketFrameHeader::kOpCodeBinary,
2041       std::vector<char>(kBinaryBlob, kBinaryBlob + kBinaryBlobSize));
2042   ASSERT_TRUE(frames != NULL);
2043   ASSERT_EQ(1U, frames->size());
2044   const WebSocketFrame* out_frame = (*frames)[0];
2045   EXPECT_EQ(kBinaryBlobSize, out_frame->header.payload_length);
2046   ASSERT_TRUE(out_frame->data);
2047   EXPECT_EQ(0, memcmp(kBinaryBlob, out_frame->data->data(), kBinaryBlobSize));
2048 }
2049
2050 // Test the read path for 8-bit cleanliness as well.
2051 TEST_F(WebSocketChannelEventInterfaceTest, ReadBinaryFramesAre8BitClean) {
2052   scoped_ptr<WebSocketFrame> frame(
2053       new WebSocketFrame(WebSocketFrameHeader::kOpCodeBinary));
2054   WebSocketFrameHeader& frame_header = frame->header;
2055   frame_header.final = true;
2056   frame_header.payload_length = kBinaryBlobSize;
2057   frame->data = new IOBuffer(kBinaryBlobSize);
2058   memcpy(frame->data->data(), kBinaryBlob, kBinaryBlobSize);
2059   ScopedVector<WebSocketFrame> frames;
2060   frames.push_back(frame.release());
2061   scoped_ptr<ReadableFakeWebSocketStream> stream(
2062       new ReadableFakeWebSocketStream);
2063   stream->PrepareRawReadFrames(
2064       ReadableFakeWebSocketStream::SYNC, OK, frames.Pass());
2065   set_stream(stream.Pass());
2066   EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
2067   EXPECT_CALL(*event_interface_, OnFlowControl(_));
2068   EXPECT_CALL(*event_interface_,
2069               OnDataFrame(true,
2070                           WebSocketFrameHeader::kOpCodeBinary,
2071                           std::vector<char>(kBinaryBlob,
2072                                             kBinaryBlob + kBinaryBlobSize)));
2073
2074   CreateChannelAndConnectSuccessfully();
2075 }
2076
2077 // If we receive another frame after Close, it is not valid. It is not
2078 // completely clear what behaviour is required from the standard in this case,
2079 // but the current implementation fails the connection. Since a Close has
2080 // already been sent, this just means closing the connection.
2081 TEST_F(WebSocketChannelStreamTest, PingAfterCloseIsRejected) {
2082   static const InitFrame frames[] = {
2083       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2084        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "OK")},
2085       {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2086        NOT_MASKED,  "Ping body"}};
2087   static const InitFrame expected[] = {
2088       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2089        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2090   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2091   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2092       .WillOnce(ReturnFrames(&frames))
2093       .WillRepeatedly(Return(ERR_IO_PENDING));
2094   {
2095     // We only need to verify the relative order of WriteFrames() and
2096     // Close(). The current implementation calls WriteFrames() for the Close
2097     // frame before calling ReadFrames() again, but that is an implementation
2098     // detail and better not to consider required behaviour.
2099     InSequence s;
2100     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2101         .WillOnce(Return(OK));
2102     EXPECT_CALL(*mock_stream_, Close()).Times(1);
2103   }
2104
2105   CreateChannelAndConnectSuccessfully();
2106 }
2107
2108 // A protocol error from the remote server should result in a close frame with
2109 // status 1002, followed by the connection closing.
2110 TEST_F(WebSocketChannelStreamTest, ProtocolError) {
2111   static const InitFrame expected[] = {
2112       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2113        MASKED,      CLOSE_DATA(PROTOCOL_ERROR, "WebSocket Protocol Error")}};
2114   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2115   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2116       .WillOnce(Return(ERR_WS_PROTOCOL_ERROR));
2117   EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2118       .WillOnce(Return(OK));
2119   EXPECT_CALL(*mock_stream_, Close());
2120
2121   CreateChannelAndConnectSuccessfully();
2122 }
2123
2124 // Set the closing handshake timeout to a very tiny value before connecting.
2125 class WebSocketChannelStreamTimeoutTest : public WebSocketChannelStreamTest {
2126  protected:
2127   WebSocketChannelStreamTimeoutTest() {}
2128
2129   virtual void CreateChannelAndConnectSuccessfully() OVERRIDE {
2130     set_stream(mock_stream_.Pass());
2131     CreateChannelAndConnect();
2132     channel_->SetClosingHandshakeTimeoutForTesting(
2133         TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2134     connect_data_.factory.connect_delegate->OnSuccess(stream_.Pass());
2135   }
2136 };
2137
2138 // In this case the server initiates the closing handshake with a Close
2139 // message. WebSocketChannel responds with a matching Close message, and waits
2140 // for the server to close the TCP/IP connection. The server never closes the
2141 // connection, so the closing handshake times out and WebSocketChannel closes
2142 // the connection itself.
2143 TEST_F(WebSocketChannelStreamTimeoutTest, ServerInitiatedCloseTimesOut) {
2144   static const InitFrame frames[] = {
2145       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2146        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2147   static const InitFrame expected[] = {
2148       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2149        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2150   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2151   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2152       .WillOnce(ReturnFrames(&frames))
2153       .WillRepeatedly(Return(ERR_IO_PENDING));
2154   Checkpoint checkpoint;
2155   TestClosure completion;
2156   {
2157     InSequence s;
2158     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2159         .WillOnce(Return(OK));
2160     EXPECT_CALL(checkpoint, Call(1));
2161     EXPECT_CALL(*mock_stream_, Close())
2162         .WillOnce(InvokeClosure(completion.closure()));
2163   }
2164
2165   CreateChannelAndConnectSuccessfully();
2166   checkpoint.Call(1);
2167   completion.WaitForResult();
2168 }
2169
2170 // In this case the client initiates the closing handshake by sending a Close
2171 // message. WebSocketChannel waits for a Close message in response from the
2172 // server. The server never responds to the Close message, so the closing
2173 // handshake times out and WebSocketChannel closes the connection.
2174 TEST_F(WebSocketChannelStreamTimeoutTest, ClientInitiatedCloseTimesOut) {
2175   static const InitFrame expected[] = {
2176       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2177        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2178   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2179   EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2180       .WillRepeatedly(Return(ERR_IO_PENDING));
2181   TestClosure completion;
2182   {
2183     InSequence s;
2184     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2185         .WillOnce(Return(OK));
2186     EXPECT_CALL(*mock_stream_, Close())
2187         .WillOnce(InvokeClosure(completion.closure()));
2188   }
2189
2190   CreateChannelAndConnectSuccessfully();
2191   channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
2192   completion.WaitForResult();
2193 }
2194
2195 // In this case the client initiates the closing handshake and the server
2196 // responds with a matching Close message. WebSocketChannel waits for the server
2197 // to close the TCP/IP connection, but it never does. The closing handshake
2198 // times out and WebSocketChannel closes the connection.
2199 TEST_F(WebSocketChannelStreamTimeoutTest, ConnectionCloseTimesOut) {
2200   static const InitFrame expected[] = {
2201       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2202        MASKED,      CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2203   static const InitFrame frames[] = {
2204       {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2205        NOT_MASKED,  CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2206   EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2207   TestClosure completion;
2208   ScopedVector<WebSocketFrame>* read_frames = NULL;
2209   CompletionCallback read_callback;
2210   {
2211     InSequence s;
2212     // Copy the arguments to ReadFrames so that the test can call the callback
2213     // after it has send the close message.
2214     EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2215         .WillOnce(DoAll(SaveArg<0>(&read_frames),
2216                         SaveArg<1>(&read_callback),
2217                         Return(ERR_IO_PENDING)));
2218     // The first real event that happens is the client sending the Close
2219     // message.
2220     EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2221         .WillOnce(Return(OK));
2222     // The |read_frames| callback is called (from this test case) at this
2223     // point. ReadFrames is called again by WebSocketChannel, waiting for
2224     // ERR_CONNECTION_CLOSED.
2225     EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2226         .WillOnce(Return(ERR_IO_PENDING));
2227     // The timeout happens and so WebSocketChannel closes the stream.
2228     EXPECT_CALL(*mock_stream_, Close())
2229         .WillOnce(InvokeClosure(completion.closure()));
2230   }
2231
2232   CreateChannelAndConnectSuccessfully();
2233   channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
2234   ASSERT_TRUE(read_frames);
2235   // Provide the "Close" message from the server.
2236   *read_frames = CreateFrameVector(frames);
2237   read_callback.Run(OK);
2238   completion.WaitForResult();
2239 }
2240
2241 }  // namespace
2242 }  // namespace net