Upstream version 11.40.277.0
[platform/framework/web/crosswalk.git] / src / jingle / glue / chrome_async_socket_unittest.cc
1 // Copyright (c) 2012 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 "jingle/glue/chrome_async_socket.h"
6
7 #include <deque>
8 #include <string>
9
10 #include "base/basictypes.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/message_loop/message_pump_default.h"
15 #include "jingle/glue/resolving_client_socket_factory.h"
16 #include "net/base/address_list.h"
17 #include "net/base/net_errors.h"
18 #include "net/base/net_util.h"
19 #include "net/cert/mock_cert_verifier.h"
20 #include "net/http/transport_security_state.h"
21 #include "net/socket/socket_test_util.h"
22 #include "net/socket/ssl_client_socket.h"
23 #include "net/ssl/ssl_config_service.h"
24 #include "net/url_request/url_request_context_getter.h"
25 #include "testing/gtest/include/gtest/gtest.h"
26 #include "third_party/webrtc/base/ipaddress.h"
27 #include "third_party/webrtc/base/sigslot.h"
28 #include "third_party/webrtc/base/socketaddress.h"
29
30 namespace jingle_glue {
31
32 namespace {
33
34 // Data provider that handles reads/writes for ChromeAsyncSocket.
35 class AsyncSocketDataProvider : public net::SocketDataProvider {
36  public:
37   AsyncSocketDataProvider() : has_pending_read_(false) {}
38
39   ~AsyncSocketDataProvider() override {
40     EXPECT_TRUE(writes_.empty());
41     EXPECT_TRUE(reads_.empty());
42   }
43
44   // If there's no read, sets the "has pending read" flag.  Otherwise,
45   // pops the next read.
46   net::MockRead GetNextRead() override {
47     if (reads_.empty()) {
48       DCHECK(!has_pending_read_);
49       has_pending_read_ = true;
50       const net::MockRead pending_read(net::SYNCHRONOUS, net::ERR_IO_PENDING);
51       return pending_read;
52     }
53     net::MockRead mock_read = reads_.front();
54     reads_.pop_front();
55     return mock_read;
56   }
57
58   // Simply pops the next write and, if applicable, compares it to
59   // |data|.
60   net::MockWriteResult OnWrite(const std::string& data) override {
61     DCHECK(!writes_.empty());
62     net::MockWrite mock_write = writes_.front();
63     writes_.pop_front();
64     if (mock_write.result != net::OK) {
65       return net::MockWriteResult(mock_write.mode, mock_write.result);
66     }
67     std::string expected_data(mock_write.data, mock_write.data_len);
68     EXPECT_EQ(expected_data, data);
69     if (expected_data != data) {
70       return net::MockWriteResult(net::SYNCHRONOUS, net::ERR_UNEXPECTED);
71     }
72     return net::MockWriteResult(mock_write.mode, data.size());
73   }
74
75   // We ignore resets so we can pre-load the socket data provider with
76   // read/write events.
77   void Reset() override {}
78
79   // If there is a pending read, completes it with the given read.
80   // Otherwise, queues up the given read.
81   void AddRead(const net::MockRead& mock_read) {
82     DCHECK_NE(mock_read.result, net::ERR_IO_PENDING);
83     if (has_pending_read_) {
84       socket()->OnReadComplete(mock_read);
85       has_pending_read_ = false;
86       return;
87     }
88     reads_.push_back(mock_read);
89   }
90
91   // Simply queues up the given write.
92   void AddWrite(const net::MockWrite& mock_write) {
93     writes_.push_back(mock_write);
94   }
95
96  private:
97   std::deque<net::MockRead> reads_;
98   bool has_pending_read_;
99
100   std::deque<net::MockWrite> writes_;
101
102   DISALLOW_COPY_AND_ASSIGN(AsyncSocketDataProvider);
103 };
104
105 class MockXmppClientSocketFactory : public ResolvingClientSocketFactory {
106  public:
107   MockXmppClientSocketFactory(
108       net::ClientSocketFactory* mock_client_socket_factory,
109       const net::AddressList& address_list)
110           : mock_client_socket_factory_(mock_client_socket_factory),
111             address_list_(address_list),
112             cert_verifier_(new net::MockCertVerifier),
113             transport_security_state_(new net::TransportSecurityState) {
114   }
115
116   // ResolvingClientSocketFactory implementation.
117   scoped_ptr<net::StreamSocket> CreateTransportClientSocket(
118       const net::HostPortPair& host_and_port) override {
119     return mock_client_socket_factory_->CreateTransportClientSocket(
120         address_list_, NULL, net::NetLog::Source());
121   }
122
123   scoped_ptr<net::SSLClientSocket> CreateSSLClientSocket(
124       scoped_ptr<net::ClientSocketHandle> transport_socket,
125       const net::HostPortPair& host_and_port) override {
126     net::SSLClientSocketContext context;
127     context.cert_verifier = cert_verifier_.get();
128     context.transport_security_state = transport_security_state_.get();
129     return mock_client_socket_factory_->CreateSSLClientSocket(
130         transport_socket.Pass(), host_and_port, ssl_config_, context);
131   }
132
133  private:
134   scoped_ptr<net::ClientSocketFactory> mock_client_socket_factory_;
135   net::AddressList address_list_;
136   net::SSLConfig ssl_config_;
137   scoped_ptr<net::CertVerifier> cert_verifier_;
138   scoped_ptr<net::TransportSecurityState> transport_security_state_;
139 };
140
141 class ChromeAsyncSocketTest
142     : public testing::Test,
143       public sigslot::has_slots<> {
144  protected:
145   ChromeAsyncSocketTest()
146       : ssl_socket_data_provider_(net::ASYNC, net::OK),
147         addr_("localhost", 35) {
148     // GTest death tests execute in a fork()ed but not exec()ed process.
149     // On OS X a CoreFoundation-backed message loop will exit with a
150     // __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__
151     // when called.
152     // Explicitly create a MessagePumpDefault which can run in this enivronment.
153     scoped_ptr<base::MessagePump> pump(new base::MessagePumpDefault());
154     message_loop_.reset(new base::MessageLoop(pump.Pass()));
155   }
156
157   virtual ~ChromeAsyncSocketTest() {}
158
159   virtual void SetUp() {
160     scoped_ptr<net::MockClientSocketFactory> mock_client_socket_factory(
161         new net::MockClientSocketFactory());
162     mock_client_socket_factory->AddSocketDataProvider(
163         &async_socket_data_provider_);
164     mock_client_socket_factory->AddSSLSocketDataProvider(
165         &ssl_socket_data_provider_);
166
167     // Fake DNS resolution for |addr_| and pass it to the factory.
168     net::IPAddressNumber resolved_addr;
169     EXPECT_TRUE(net::ParseIPLiteralToNumber("127.0.0.1", &resolved_addr));
170     const net::AddressList address_list =
171         net::AddressList::CreateFromIPAddress(resolved_addr, addr_.port());
172     scoped_ptr<MockXmppClientSocketFactory> mock_xmpp_client_socket_factory(
173         new MockXmppClientSocketFactory(
174             mock_client_socket_factory.release(),
175             address_list));
176     chrome_async_socket_.reset(
177         new ChromeAsyncSocket(mock_xmpp_client_socket_factory.release(),
178                               14, 20)),
179
180     chrome_async_socket_->SignalConnected.connect(
181         this, &ChromeAsyncSocketTest::OnConnect);
182     chrome_async_socket_->SignalSSLConnected.connect(
183         this, &ChromeAsyncSocketTest::OnSSLConnect);
184     chrome_async_socket_->SignalClosed.connect(
185         this, &ChromeAsyncSocketTest::OnClose);
186     chrome_async_socket_->SignalRead.connect(
187         this, &ChromeAsyncSocketTest::OnRead);
188     chrome_async_socket_->SignalError.connect(
189         this, &ChromeAsyncSocketTest::OnError);
190   }
191
192   virtual void TearDown() {
193     // Run any tasks that we forgot to pump.
194     message_loop_->RunUntilIdle();
195     ExpectClosed();
196     ExpectNoSignal();
197     chrome_async_socket_.reset();
198   }
199
200   enum Signal {
201     SIGNAL_CONNECT,
202     SIGNAL_SSL_CONNECT,
203     SIGNAL_CLOSE,
204     SIGNAL_READ,
205     SIGNAL_ERROR,
206   };
207
208   // Helper struct that records the state at the time of a signal.
209
210   struct SignalSocketState {
211     SignalSocketState()
212         : signal(SIGNAL_ERROR),
213           state(ChromeAsyncSocket::STATE_CLOSED),
214           error(ChromeAsyncSocket::ERROR_NONE),
215           net_error(net::OK) {}
216
217     SignalSocketState(
218         Signal signal,
219         ChromeAsyncSocket::State state,
220         ChromeAsyncSocket::Error error,
221         net::Error net_error)
222         : signal(signal),
223           state(state),
224           error(error),
225           net_error(net_error) {}
226
227     bool IsEqual(const SignalSocketState& other) const {
228       return
229           (signal == other.signal) &&
230           (state == other.state) &&
231           (error == other.error) &&
232           (net_error == other.net_error);
233     }
234
235     static SignalSocketState FromAsyncSocket(
236         Signal signal,
237         buzz::AsyncSocket* async_socket) {
238       return SignalSocketState(signal,
239                                async_socket->state(),
240                                async_socket->error(),
241                                static_cast<net::Error>(
242                                    async_socket->GetError()));
243     }
244
245     static SignalSocketState NoError(
246         Signal signal, buzz::AsyncSocket::State state) {
247         return SignalSocketState(signal, state,
248                                  buzz::AsyncSocket::ERROR_NONE,
249                                  net::OK);
250     }
251
252     Signal signal;
253     ChromeAsyncSocket::State state;
254     ChromeAsyncSocket::Error error;
255     net::Error net_error;
256   };
257
258   void CaptureSocketState(Signal signal) {
259     signal_socket_states_.push_back(
260         SignalSocketState::FromAsyncSocket(
261             signal, chrome_async_socket_.get()));
262   }
263
264   void OnConnect() {
265     CaptureSocketState(SIGNAL_CONNECT);
266   }
267
268   void OnSSLConnect() {
269     CaptureSocketState(SIGNAL_SSL_CONNECT);
270   }
271
272   void OnClose() {
273     CaptureSocketState(SIGNAL_CLOSE);
274   }
275
276   void OnRead() {
277     CaptureSocketState(SIGNAL_READ);
278   }
279
280   void OnError() {
281     ADD_FAILURE();
282   }
283
284   // State expect functions.
285
286   void ExpectState(ChromeAsyncSocket::State state,
287                    ChromeAsyncSocket::Error error,
288                    net::Error net_error) {
289     EXPECT_EQ(state, chrome_async_socket_->state());
290     EXPECT_EQ(error, chrome_async_socket_->error());
291     EXPECT_EQ(net_error, chrome_async_socket_->GetError());
292   }
293
294   void ExpectNonErrorState(ChromeAsyncSocket::State state) {
295     ExpectState(state, ChromeAsyncSocket::ERROR_NONE, net::OK);
296   }
297
298   void ExpectErrorState(ChromeAsyncSocket::State state,
299                         ChromeAsyncSocket::Error error) {
300     ExpectState(state, error, net::OK);
301   }
302
303   void ExpectClosed() {
304     ExpectNonErrorState(ChromeAsyncSocket::STATE_CLOSED);
305   }
306
307   // Signal expect functions.
308
309   void ExpectNoSignal() {
310     if (!signal_socket_states_.empty()) {
311       ADD_FAILURE() << signal_socket_states_.front().signal;
312     }
313   }
314
315   void ExpectSignalSocketState(
316       SignalSocketState expected_signal_socket_state) {
317     if (signal_socket_states_.empty()) {
318       ADD_FAILURE() << expected_signal_socket_state.signal;
319       return;
320     }
321     EXPECT_TRUE(expected_signal_socket_state.IsEqual(
322         signal_socket_states_.front()))
323         << signal_socket_states_.front().signal;
324     signal_socket_states_.pop_front();
325   }
326
327   void ExpectReadSignal() {
328     ExpectSignalSocketState(
329         SignalSocketState::NoError(
330             SIGNAL_READ, ChromeAsyncSocket::STATE_OPEN));
331   }
332
333   void ExpectSSLConnectSignal() {
334     ExpectSignalSocketState(
335         SignalSocketState::NoError(SIGNAL_SSL_CONNECT,
336                                    ChromeAsyncSocket::STATE_TLS_OPEN));
337   }
338
339   void ExpectSSLReadSignal() {
340     ExpectSignalSocketState(
341         SignalSocketState::NoError(
342             SIGNAL_READ, ChromeAsyncSocket::STATE_TLS_OPEN));
343   }
344
345   // Open/close utility functions.
346
347   void DoOpenClosed() {
348     ExpectClosed();
349     async_socket_data_provider_.set_connect_data(
350         net::MockConnect(net::SYNCHRONOUS, net::OK));
351     EXPECT_TRUE(chrome_async_socket_->Connect(addr_));
352     ExpectNonErrorState(ChromeAsyncSocket::STATE_CONNECTING);
353
354     message_loop_->RunUntilIdle();
355     // We may not necessarily be open; may have been other events
356     // queued up.
357     ExpectSignalSocketState(
358         SignalSocketState::NoError(
359             SIGNAL_CONNECT, ChromeAsyncSocket::STATE_OPEN));
360   }
361
362   void DoCloseOpened(SignalSocketState expected_signal_socket_state) {
363     // We may be in an error state, so just compare state().
364     EXPECT_EQ(ChromeAsyncSocket::STATE_OPEN, chrome_async_socket_->state());
365     EXPECT_TRUE(chrome_async_socket_->Close());
366     ExpectSignalSocketState(expected_signal_socket_state);
367     ExpectNonErrorState(ChromeAsyncSocket::STATE_CLOSED);
368   }
369
370   void DoCloseOpenedNoError() {
371     DoCloseOpened(
372         SignalSocketState::NoError(
373             SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED));
374   }
375
376   void DoSSLOpenClosed() {
377     const char kDummyData[] = "dummy_data";
378     async_socket_data_provider_.AddRead(net::MockRead(kDummyData));
379     DoOpenClosed();
380     ExpectReadSignal();
381     EXPECT_EQ(kDummyData, DrainRead(1));
382
383     EXPECT_TRUE(chrome_async_socket_->StartTls("fakedomain.com"));
384     message_loop_->RunUntilIdle();
385     ExpectSSLConnectSignal();
386     ExpectNoSignal();
387     ExpectNonErrorState(ChromeAsyncSocket::STATE_TLS_OPEN);
388   }
389
390   void DoSSLCloseOpened(SignalSocketState expected_signal_socket_state) {
391     // We may be in an error state, so just compare state().
392     EXPECT_EQ(ChromeAsyncSocket::STATE_TLS_OPEN,
393               chrome_async_socket_->state());
394     EXPECT_TRUE(chrome_async_socket_->Close());
395     ExpectSignalSocketState(expected_signal_socket_state);
396     ExpectNonErrorState(ChromeAsyncSocket::STATE_CLOSED);
397   }
398
399   void DoSSLCloseOpenedNoError() {
400     DoSSLCloseOpened(
401         SignalSocketState::NoError(
402             SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED));
403   }
404
405   // Read utility fucntions.
406
407   std::string DrainRead(size_t buf_size) {
408     std::string read;
409     scoped_ptr<char[]> buf(new char[buf_size]);
410     size_t len_read;
411     while (true) {
412       bool success =
413           chrome_async_socket_->Read(buf.get(), buf_size, &len_read);
414       if (!success) {
415         ADD_FAILURE();
416         break;
417       }
418       if (len_read == 0U) {
419         break;
420       }
421       read.append(buf.get(), len_read);
422     }
423     return read;
424   }
425
426   // ChromeAsyncSocket expects a message loop.
427   scoped_ptr<base::MessageLoop> message_loop_;
428
429   AsyncSocketDataProvider async_socket_data_provider_;
430   net::SSLSocketDataProvider ssl_socket_data_provider_;
431
432   scoped_ptr<ChromeAsyncSocket> chrome_async_socket_;
433   std::deque<SignalSocketState> signal_socket_states_;
434   const rtc::SocketAddress addr_;
435
436  private:
437   DISALLOW_COPY_AND_ASSIGN(ChromeAsyncSocketTest);
438 };
439
440 TEST_F(ChromeAsyncSocketTest, InitialState) {
441   ExpectClosed();
442   ExpectNoSignal();
443 }
444
445 TEST_F(ChromeAsyncSocketTest, EmptyClose) {
446   ExpectClosed();
447   EXPECT_TRUE(chrome_async_socket_->Close());
448   ExpectClosed();
449 }
450
451 TEST_F(ChromeAsyncSocketTest, ImmediateConnectAndClose) {
452   DoOpenClosed();
453
454   ExpectNonErrorState(ChromeAsyncSocket::STATE_OPEN);
455
456   DoCloseOpenedNoError();
457 }
458
459 // After this, no need to test immediate successful connect and
460 // Close() so thoroughly.
461
462 TEST_F(ChromeAsyncSocketTest, DoubleClose) {
463   DoOpenClosed();
464
465   EXPECT_TRUE(chrome_async_socket_->Close());
466   ExpectClosed();
467   ExpectSignalSocketState(
468       SignalSocketState::NoError(
469           SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED));
470
471   EXPECT_TRUE(chrome_async_socket_->Close());
472   ExpectClosed();
473 }
474
475 TEST_F(ChromeAsyncSocketTest, NoHostnameConnect) {
476   rtc::IPAddress ip_address;
477   EXPECT_TRUE(rtc::IPFromString("127.0.0.1", &ip_address));
478   const rtc::SocketAddress no_hostname_addr(ip_address, addr_.port());
479   EXPECT_FALSE(chrome_async_socket_->Connect(no_hostname_addr));
480   ExpectErrorState(ChromeAsyncSocket::STATE_CLOSED,
481                    ChromeAsyncSocket::ERROR_DNS);
482
483   EXPECT_TRUE(chrome_async_socket_->Close());
484   ExpectClosed();
485 }
486
487 TEST_F(ChromeAsyncSocketTest, ZeroPortConnect) {
488   const rtc::SocketAddress zero_port_addr(addr_.hostname(), 0);
489   EXPECT_FALSE(chrome_async_socket_->Connect(zero_port_addr));
490   ExpectErrorState(ChromeAsyncSocket::STATE_CLOSED,
491                    ChromeAsyncSocket::ERROR_DNS);
492
493   EXPECT_TRUE(chrome_async_socket_->Close());
494   ExpectClosed();
495 }
496
497 TEST_F(ChromeAsyncSocketTest, DoubleConnect) {
498   EXPECT_DEBUG_DEATH({
499     DoOpenClosed();
500
501     EXPECT_FALSE(chrome_async_socket_->Connect(addr_));
502     ExpectErrorState(ChromeAsyncSocket::STATE_OPEN,
503                      ChromeAsyncSocket::ERROR_WRONGSTATE);
504
505     DoCloseOpened(
506         SignalSocketState(SIGNAL_CLOSE,
507                           ChromeAsyncSocket::STATE_CLOSED,
508                           ChromeAsyncSocket::ERROR_WRONGSTATE,
509                           net::OK));
510   }, "non-closed socket");
511 }
512
513 TEST_F(ChromeAsyncSocketTest, ImmediateConnectCloseBeforeRead) {
514   DoOpenClosed();
515
516   EXPECT_TRUE(chrome_async_socket_->Close());
517   ExpectClosed();
518   ExpectSignalSocketState(
519       SignalSocketState::NoError(
520           SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED));
521
522   message_loop_->RunUntilIdle();
523 }
524
525 TEST_F(ChromeAsyncSocketTest, HangingConnect) {
526   EXPECT_TRUE(chrome_async_socket_->Connect(addr_));
527   ExpectNonErrorState(ChromeAsyncSocket::STATE_CONNECTING);
528   ExpectNoSignal();
529
530   EXPECT_TRUE(chrome_async_socket_->Close());
531   ExpectClosed();
532   ExpectSignalSocketState(
533       SignalSocketState::NoError(
534           SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED));
535 }
536
537 TEST_F(ChromeAsyncSocketTest, PendingConnect) {
538   async_socket_data_provider_.set_connect_data(
539       net::MockConnect(net::ASYNC, net::OK));
540   EXPECT_TRUE(chrome_async_socket_->Connect(addr_));
541   ExpectNonErrorState(ChromeAsyncSocket::STATE_CONNECTING);
542   ExpectNoSignal();
543
544   message_loop_->RunUntilIdle();
545   ExpectNonErrorState(ChromeAsyncSocket::STATE_OPEN);
546   ExpectSignalSocketState(
547       SignalSocketState::NoError(
548           SIGNAL_CONNECT, ChromeAsyncSocket::STATE_OPEN));
549   ExpectNoSignal();
550
551   message_loop_->RunUntilIdle();
552
553   DoCloseOpenedNoError();
554 }
555
556 // After this no need to test successful pending connect so
557 // thoroughly.
558
559 TEST_F(ChromeAsyncSocketTest, PendingConnectCloseBeforeRead) {
560   async_socket_data_provider_.set_connect_data(
561       net::MockConnect(net::ASYNC, net::OK));
562   EXPECT_TRUE(chrome_async_socket_->Connect(addr_));
563
564   message_loop_->RunUntilIdle();
565   ExpectSignalSocketState(
566       SignalSocketState::NoError(
567           SIGNAL_CONNECT, ChromeAsyncSocket::STATE_OPEN));
568
569   DoCloseOpenedNoError();
570
571   message_loop_->RunUntilIdle();
572 }
573
574 TEST_F(ChromeAsyncSocketTest, PendingConnectError) {
575   async_socket_data_provider_.set_connect_data(
576       net::MockConnect(net::ASYNC, net::ERR_TIMED_OUT));
577   EXPECT_TRUE(chrome_async_socket_->Connect(addr_));
578
579   message_loop_->RunUntilIdle();
580
581   ExpectSignalSocketState(
582       SignalSocketState(
583           SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED,
584           ChromeAsyncSocket::ERROR_WINSOCK, net::ERR_TIMED_OUT));
585 }
586
587 // After this we can assume Connect() and Close() work as expected.
588
589 TEST_F(ChromeAsyncSocketTest, EmptyRead) {
590   DoOpenClosed();
591
592   char buf[4096];
593   size_t len_read = 10000U;
594   EXPECT_TRUE(chrome_async_socket_->Read(buf, sizeof(buf), &len_read));
595   EXPECT_EQ(0U, len_read);
596
597   DoCloseOpenedNoError();
598 }
599
600 TEST_F(ChromeAsyncSocketTest, WrongRead) {
601   EXPECT_DEBUG_DEATH({
602     async_socket_data_provider_.set_connect_data(
603         net::MockConnect(net::ASYNC, net::OK));
604     EXPECT_TRUE(chrome_async_socket_->Connect(addr_));
605     ExpectNonErrorState(ChromeAsyncSocket::STATE_CONNECTING);
606     ExpectNoSignal();
607
608     char buf[4096];
609     size_t len_read;
610     EXPECT_FALSE(chrome_async_socket_->Read(buf, sizeof(buf), &len_read));
611     ExpectErrorState(ChromeAsyncSocket::STATE_CONNECTING,
612                      ChromeAsyncSocket::ERROR_WRONGSTATE);
613     EXPECT_TRUE(chrome_async_socket_->Close());
614     ExpectSignalSocketState(
615         SignalSocketState(
616             SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED,
617             ChromeAsyncSocket::ERROR_WRONGSTATE, net::OK));
618   }, "non-open");
619 }
620
621 TEST_F(ChromeAsyncSocketTest, WrongReadClosed) {
622   char buf[4096];
623   size_t len_read;
624   EXPECT_FALSE(chrome_async_socket_->Read(buf, sizeof(buf), &len_read));
625   ExpectErrorState(ChromeAsyncSocket::STATE_CLOSED,
626                    ChromeAsyncSocket::ERROR_WRONGSTATE);
627   EXPECT_TRUE(chrome_async_socket_->Close());
628 }
629
630 const char kReadData[] = "mydatatoread";
631
632 TEST_F(ChromeAsyncSocketTest, Read) {
633   async_socket_data_provider_.AddRead(net::MockRead(kReadData));
634   DoOpenClosed();
635
636   ExpectReadSignal();
637   ExpectNoSignal();
638
639   EXPECT_EQ(kReadData, DrainRead(1));
640
641   message_loop_->RunUntilIdle();
642
643   DoCloseOpenedNoError();
644 }
645
646 TEST_F(ChromeAsyncSocketTest, ReadTwice) {
647   async_socket_data_provider_.AddRead(net::MockRead(kReadData));
648   DoOpenClosed();
649
650   ExpectReadSignal();
651   ExpectNoSignal();
652
653   EXPECT_EQ(kReadData, DrainRead(1));
654
655   message_loop_->RunUntilIdle();
656
657   const char kReadData2[] = "mydatatoread2";
658   async_socket_data_provider_.AddRead(net::MockRead(kReadData2));
659
660   ExpectReadSignal();
661   ExpectNoSignal();
662
663   EXPECT_EQ(kReadData2, DrainRead(1));
664
665   DoCloseOpenedNoError();
666 }
667
668 TEST_F(ChromeAsyncSocketTest, ReadError) {
669   async_socket_data_provider_.AddRead(net::MockRead(kReadData));
670   DoOpenClosed();
671
672   ExpectReadSignal();
673   ExpectNoSignal();
674
675   EXPECT_EQ(kReadData, DrainRead(1));
676
677   message_loop_->RunUntilIdle();
678
679   async_socket_data_provider_.AddRead(
680       net::MockRead(net::SYNCHRONOUS, net::ERR_TIMED_OUT));
681
682   ExpectSignalSocketState(
683       SignalSocketState(
684           SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED,
685           ChromeAsyncSocket::ERROR_WINSOCK, net::ERR_TIMED_OUT));
686 }
687
688 TEST_F(ChromeAsyncSocketTest, ReadEmpty) {
689   async_socket_data_provider_.AddRead(net::MockRead(""));
690   DoOpenClosed();
691
692   ExpectSignalSocketState(
693       SignalSocketState::NoError(
694           SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED));
695 }
696
697 TEST_F(ChromeAsyncSocketTest, PendingRead) {
698   DoOpenClosed();
699
700   ExpectNoSignal();
701
702   async_socket_data_provider_.AddRead(net::MockRead(kReadData));
703
704   ExpectSignalSocketState(
705       SignalSocketState::NoError(
706           SIGNAL_READ, ChromeAsyncSocket::STATE_OPEN));
707   ExpectNoSignal();
708
709   EXPECT_EQ(kReadData, DrainRead(1));
710
711   message_loop_->RunUntilIdle();
712
713   DoCloseOpenedNoError();
714 }
715
716 TEST_F(ChromeAsyncSocketTest, PendingEmptyRead) {
717   DoOpenClosed();
718
719   ExpectNoSignal();
720
721   async_socket_data_provider_.AddRead(net::MockRead(""));
722
723   ExpectSignalSocketState(
724       SignalSocketState::NoError(
725           SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED));
726 }
727
728 TEST_F(ChromeAsyncSocketTest, PendingReadError) {
729   DoOpenClosed();
730
731   ExpectNoSignal();
732
733   async_socket_data_provider_.AddRead(
734       net::MockRead(net::ASYNC, net::ERR_TIMED_OUT));
735
736   ExpectSignalSocketState(
737       SignalSocketState(
738           SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED,
739           ChromeAsyncSocket::ERROR_WINSOCK, net::ERR_TIMED_OUT));
740 }
741
742 // After this we can assume non-SSL Read() works as expected.
743
744 TEST_F(ChromeAsyncSocketTest, WrongWrite) {
745   EXPECT_DEBUG_DEATH({
746     std::string data("foo");
747     EXPECT_FALSE(chrome_async_socket_->Write(data.data(), data.size()));
748     ExpectErrorState(ChromeAsyncSocket::STATE_CLOSED,
749                      ChromeAsyncSocket::ERROR_WRONGSTATE);
750     EXPECT_TRUE(chrome_async_socket_->Close());
751   }, "non-open");
752 }
753
754 const char kWriteData[] = "mydatatowrite";
755
756 TEST_F(ChromeAsyncSocketTest, SyncWrite) {
757   async_socket_data_provider_.AddWrite(
758       net::MockWrite(net::SYNCHRONOUS, kWriteData, 3));
759   async_socket_data_provider_.AddWrite(
760       net::MockWrite(net::SYNCHRONOUS, kWriteData + 3, 5));
761   async_socket_data_provider_.AddWrite(
762       net::MockWrite(net::SYNCHRONOUS,
763                      kWriteData + 8, arraysize(kWriteData) - 8));
764   DoOpenClosed();
765
766   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData, 3));
767   message_loop_->RunUntilIdle();
768   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData + 3, 5));
769   message_loop_->RunUntilIdle();
770   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData + 8,
771                                           arraysize(kWriteData) - 8));
772   message_loop_->RunUntilIdle();
773
774   ExpectNoSignal();
775
776   DoCloseOpenedNoError();
777 }
778
779 TEST_F(ChromeAsyncSocketTest, AsyncWrite) {
780   DoOpenClosed();
781
782   async_socket_data_provider_.AddWrite(
783       net::MockWrite(net::ASYNC, kWriteData, 3));
784   async_socket_data_provider_.AddWrite(
785       net::MockWrite(net::ASYNC, kWriteData + 3, 5));
786   async_socket_data_provider_.AddWrite(
787       net::MockWrite(net::ASYNC, kWriteData + 8, arraysize(kWriteData) - 8));
788
789   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData, 3));
790   message_loop_->RunUntilIdle();
791   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData + 3, 5));
792   message_loop_->RunUntilIdle();
793   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData + 8,
794                                           arraysize(kWriteData) - 8));
795   message_loop_->RunUntilIdle();
796
797   ExpectNoSignal();
798
799   DoCloseOpenedNoError();
800 }
801
802 TEST_F(ChromeAsyncSocketTest, AsyncWriteError) {
803   DoOpenClosed();
804
805   async_socket_data_provider_.AddWrite(
806       net::MockWrite(net::ASYNC, kWriteData, 3));
807   async_socket_data_provider_.AddWrite(
808       net::MockWrite(net::ASYNC, kWriteData + 3, 5));
809   async_socket_data_provider_.AddWrite(
810       net::MockWrite(net::ASYNC, net::ERR_TIMED_OUT));
811
812   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData, 3));
813   message_loop_->RunUntilIdle();
814   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData + 3, 5));
815   message_loop_->RunUntilIdle();
816   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData + 8,
817                                           arraysize(kWriteData) - 8));
818   message_loop_->RunUntilIdle();
819
820   ExpectSignalSocketState(
821       SignalSocketState(
822           SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED,
823           ChromeAsyncSocket::ERROR_WINSOCK, net::ERR_TIMED_OUT));
824 }
825
826 TEST_F(ChromeAsyncSocketTest, LargeWrite) {
827   EXPECT_DEBUG_DEATH({
828     DoOpenClosed();
829
830     std::string large_data(100, 'x');
831     EXPECT_FALSE(chrome_async_socket_->Write(large_data.data(),
832                                              large_data.size()));
833     ExpectState(ChromeAsyncSocket::STATE_OPEN,
834                 ChromeAsyncSocket::ERROR_WINSOCK,
835                 net::ERR_INSUFFICIENT_RESOURCES);
836     DoCloseOpened(
837         SignalSocketState(
838             SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED,
839             ChromeAsyncSocket::ERROR_WINSOCK,
840             net::ERR_INSUFFICIENT_RESOURCES));
841     }, "exceed the max write buffer");
842 }
843
844 TEST_F(ChromeAsyncSocketTest, LargeAccumulatedWrite) {
845   EXPECT_DEBUG_DEATH({
846     DoOpenClosed();
847
848     std::string data(15, 'x');
849     EXPECT_TRUE(chrome_async_socket_->Write(data.data(), data.size()));
850     EXPECT_FALSE(chrome_async_socket_->Write(data.data(), data.size()));
851     ExpectState(ChromeAsyncSocket::STATE_OPEN,
852                 ChromeAsyncSocket::ERROR_WINSOCK,
853                 net::ERR_INSUFFICIENT_RESOURCES);
854     DoCloseOpened(
855         SignalSocketState(
856             SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED,
857             ChromeAsyncSocket::ERROR_WINSOCK,
858             net::ERR_INSUFFICIENT_RESOURCES));
859     }, "exceed the max write buffer");
860 }
861
862 // After this we can assume non-SSL I/O works as expected.
863
864 TEST_F(ChromeAsyncSocketTest, HangingSSLConnect) {
865   async_socket_data_provider_.AddRead(net::MockRead(kReadData));
866   DoOpenClosed();
867   ExpectReadSignal();
868
869   EXPECT_TRUE(chrome_async_socket_->StartTls("fakedomain.com"));
870   ExpectNoSignal();
871
872   ExpectNonErrorState(ChromeAsyncSocket::STATE_TLS_CONNECTING);
873   EXPECT_TRUE(chrome_async_socket_->Close());
874   ExpectSignalSocketState(
875       SignalSocketState::NoError(SIGNAL_CLOSE,
876                                  ChromeAsyncSocket::STATE_CLOSED));
877   ExpectNonErrorState(ChromeAsyncSocket::STATE_CLOSED);
878 }
879
880 TEST_F(ChromeAsyncSocketTest, ImmediateSSLConnect) {
881   async_socket_data_provider_.AddRead(net::MockRead(kReadData));
882   DoOpenClosed();
883   ExpectReadSignal();
884
885   EXPECT_TRUE(chrome_async_socket_->StartTls("fakedomain.com"));
886   message_loop_->RunUntilIdle();
887   ExpectSSLConnectSignal();
888   ExpectNoSignal();
889   ExpectNonErrorState(ChromeAsyncSocket::STATE_TLS_OPEN);
890
891   DoSSLCloseOpenedNoError();
892 }
893
894 TEST_F(ChromeAsyncSocketTest, DoubleSSLConnect) {
895   EXPECT_DEBUG_DEATH({
896     async_socket_data_provider_.AddRead(net::MockRead(kReadData));
897     DoOpenClosed();
898     ExpectReadSignal();
899
900     EXPECT_TRUE(chrome_async_socket_->StartTls("fakedomain.com"));
901     message_loop_->RunUntilIdle();
902     ExpectSSLConnectSignal();
903     ExpectNoSignal();
904     ExpectNonErrorState(ChromeAsyncSocket::STATE_TLS_OPEN);
905
906     EXPECT_FALSE(chrome_async_socket_->StartTls("fakedomain.com"));
907
908     DoSSLCloseOpened(
909         SignalSocketState(SIGNAL_CLOSE,
910                           ChromeAsyncSocket::STATE_CLOSED,
911                           ChromeAsyncSocket::ERROR_WRONGSTATE,
912                           net::OK));
913   }, "wrong state");
914 }
915
916 TEST_F(ChromeAsyncSocketTest, FailedSSLConnect) {
917   ssl_socket_data_provider_.connect =
918       net::MockConnect(net::ASYNC, net::ERR_CERT_COMMON_NAME_INVALID),
919
920   async_socket_data_provider_.AddRead(net::MockRead(kReadData));
921   DoOpenClosed();
922   ExpectReadSignal();
923
924   EXPECT_TRUE(chrome_async_socket_->StartTls("fakedomain.com"));
925   message_loop_->RunUntilIdle();
926   ExpectSignalSocketState(
927       SignalSocketState(
928           SIGNAL_CLOSE, ChromeAsyncSocket::STATE_CLOSED,
929           ChromeAsyncSocket::ERROR_WINSOCK,
930           net::ERR_CERT_COMMON_NAME_INVALID));
931
932   EXPECT_TRUE(chrome_async_socket_->Close());
933   ExpectClosed();
934 }
935
936 TEST_F(ChromeAsyncSocketTest, ReadDuringSSLConnecting) {
937   async_socket_data_provider_.AddRead(net::MockRead(kReadData));
938   DoOpenClosed();
939   ExpectReadSignal();
940   EXPECT_EQ(kReadData, DrainRead(1));
941
942   EXPECT_TRUE(chrome_async_socket_->StartTls("fakedomain.com"));
943   ExpectNoSignal();
944
945   // Shouldn't do anything.
946   async_socket_data_provider_.AddRead(net::MockRead(kReadData));
947
948   char buf[4096];
949   size_t len_read = 10000U;
950   EXPECT_TRUE(chrome_async_socket_->Read(buf, sizeof(buf), &len_read));
951   EXPECT_EQ(0U, len_read);
952
953   message_loop_->RunUntilIdle();
954   ExpectSSLConnectSignal();
955   ExpectSSLReadSignal();
956   ExpectNoSignal();
957   ExpectNonErrorState(ChromeAsyncSocket::STATE_TLS_OPEN);
958
959   len_read = 10000U;
960   EXPECT_TRUE(chrome_async_socket_->Read(buf, sizeof(buf), &len_read));
961   EXPECT_EQ(kReadData, std::string(buf, len_read));
962
963   DoSSLCloseOpenedNoError();
964 }
965
966 TEST_F(ChromeAsyncSocketTest, WriteDuringSSLConnecting) {
967   async_socket_data_provider_.AddRead(net::MockRead(kReadData));
968   DoOpenClosed();
969   ExpectReadSignal();
970
971   EXPECT_TRUE(chrome_async_socket_->StartTls("fakedomain.com"));
972   ExpectNoSignal();
973   ExpectNonErrorState(ChromeAsyncSocket::STATE_TLS_CONNECTING);
974
975   async_socket_data_provider_.AddWrite(
976       net::MockWrite(net::ASYNC, kWriteData, 3));
977
978   // Shouldn't do anything.
979   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData, 3));
980
981   // TODO(akalin): Figure out how to test that the write happens
982   // *after* the SSL connect.
983
984   message_loop_->RunUntilIdle();
985   ExpectSSLConnectSignal();
986   ExpectNoSignal();
987
988   message_loop_->RunUntilIdle();
989
990   DoSSLCloseOpenedNoError();
991 }
992
993 TEST_F(ChromeAsyncSocketTest, SSLConnectDuringPendingRead) {
994   EXPECT_DEBUG_DEATH({
995     DoOpenClosed();
996
997     EXPECT_FALSE(chrome_async_socket_->StartTls("fakedomain.com"));
998
999     DoCloseOpened(
1000         SignalSocketState(SIGNAL_CLOSE,
1001                           ChromeAsyncSocket::STATE_CLOSED,
1002                           ChromeAsyncSocket::ERROR_WRONGSTATE,
1003                           net::OK));
1004   }, "wrong state");
1005 }
1006
1007 TEST_F(ChromeAsyncSocketTest, SSLConnectDuringPostedWrite) {
1008   EXPECT_DEBUG_DEATH({
1009     DoOpenClosed();
1010
1011     async_socket_data_provider_.AddWrite(
1012         net::MockWrite(net::ASYNC, kWriteData, 3));
1013     EXPECT_TRUE(chrome_async_socket_->Write(kWriteData, 3));
1014
1015     EXPECT_FALSE(chrome_async_socket_->StartTls("fakedomain.com"));
1016
1017     message_loop_->RunUntilIdle();
1018
1019     DoCloseOpened(
1020         SignalSocketState(SIGNAL_CLOSE,
1021                           ChromeAsyncSocket::STATE_CLOSED,
1022                           ChromeAsyncSocket::ERROR_WRONGSTATE,
1023                           net::OK));
1024   }, "wrong state");
1025 }
1026
1027 // After this we can assume SSL connect works as expected.
1028
1029 TEST_F(ChromeAsyncSocketTest, SSLRead) {
1030   DoSSLOpenClosed();
1031   async_socket_data_provider_.AddRead(net::MockRead(kReadData));
1032   message_loop_->RunUntilIdle();
1033
1034   ExpectSSLReadSignal();
1035   ExpectNoSignal();
1036
1037   EXPECT_EQ(kReadData, DrainRead(1));
1038
1039   message_loop_->RunUntilIdle();
1040
1041   DoSSLCloseOpenedNoError();
1042 }
1043
1044 TEST_F(ChromeAsyncSocketTest, SSLSyncWrite) {
1045   async_socket_data_provider_.AddWrite(
1046       net::MockWrite(net::SYNCHRONOUS, kWriteData, 3));
1047   async_socket_data_provider_.AddWrite(
1048       net::MockWrite(net::SYNCHRONOUS, kWriteData + 3, 5));
1049   async_socket_data_provider_.AddWrite(
1050       net::MockWrite(net::SYNCHRONOUS,
1051                      kWriteData + 8, arraysize(kWriteData) - 8));
1052   DoSSLOpenClosed();
1053
1054   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData, 3));
1055   message_loop_->RunUntilIdle();
1056   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData + 3, 5));
1057   message_loop_->RunUntilIdle();
1058   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData + 8,
1059                                           arraysize(kWriteData) - 8));
1060   message_loop_->RunUntilIdle();
1061
1062   ExpectNoSignal();
1063
1064   DoSSLCloseOpenedNoError();
1065 }
1066
1067 TEST_F(ChromeAsyncSocketTest, SSLAsyncWrite) {
1068   DoSSLOpenClosed();
1069
1070   async_socket_data_provider_.AddWrite(
1071       net::MockWrite(net::ASYNC, kWriteData, 3));
1072   async_socket_data_provider_.AddWrite(
1073       net::MockWrite(net::ASYNC, kWriteData + 3, 5));
1074   async_socket_data_provider_.AddWrite(
1075       net::MockWrite(net::ASYNC, kWriteData + 8, arraysize(kWriteData) - 8));
1076
1077   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData, 3));
1078   message_loop_->RunUntilIdle();
1079   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData + 3, 5));
1080   message_loop_->RunUntilIdle();
1081   EXPECT_TRUE(chrome_async_socket_->Write(kWriteData + 8,
1082                                           arraysize(kWriteData) - 8));
1083   message_loop_->RunUntilIdle();
1084
1085   ExpectNoSignal();
1086
1087   DoSSLCloseOpenedNoError();
1088 }
1089
1090 }  // namespace
1091
1092 }  // namespace jingle_glue