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 "net/quic/quic_stream_factory.h"
6
7#include "base/run_loop.h"
8#include "base/strings/string_util.h"
9#include "net/base/test_data_directory.h"
10#include "net/cert/cert_verifier.h"
11#include "net/dns/mock_host_resolver.h"
12#include "net/http/http_response_headers.h"
13#include "net/http/http_response_info.h"
14#include "net/http/http_util.h"
15#include "net/http/transport_security_state.h"
16#include "net/quic/crypto/crypto_handshake.h"
17#include "net/quic/crypto/proof_verifier_chromium.h"
18#include "net/quic/crypto/quic_decrypter.h"
19#include "net/quic/crypto/quic_encrypter.h"
20#include "net/quic/quic_http_stream.h"
21#include "net/quic/quic_server_id.h"
22#include "net/quic/test_tools/mock_clock.h"
23#include "net/quic/test_tools/mock_crypto_client_stream_factory.h"
24#include "net/quic/test_tools/mock_random.h"
25#include "net/quic/test_tools/quic_test_packet_maker.h"
26#include "net/quic/test_tools/quic_test_utils.h"
27#include "net/socket/socket_test_util.h"
28#include "net/spdy/spdy_test_utils.h"
29#include "net/ssl/channel_id_service.h"
30#include "net/ssl/default_channel_id_store.h"
31#include "net/test/cert_test_util.h"
32#include "testing/gtest/include/gtest/gtest.h"
33
34using base::StringPiece;
35using std::string;
36using std::vector;
37
38namespace net {
39namespace test {
40
41namespace {
42const char kDefaultServerHostName[] = "www.google.com";
43const int kDefaultServerPort = 443;
44}  // namespace anonymous
45
46class QuicStreamFactoryPeer {
47 public:
48  static QuicCryptoClientConfig* GetCryptoConfig(QuicStreamFactory* factory) {
49    return &factory->crypto_config_;
50  }
51
52  static bool HasActiveSession(QuicStreamFactory* factory,
53                               const HostPortPair& host_port_pair,
54                               bool is_https) {
55    QuicServerId server_id(host_port_pair, is_https, PRIVACY_MODE_DISABLED);
56    return factory->HasActiveSession(server_id);
57  }
58
59  static QuicClientSession* GetActiveSession(
60      QuicStreamFactory* factory,
61      const HostPortPair& host_port_pair,
62      bool is_https) {
63    QuicServerId server_id(host_port_pair, is_https, PRIVACY_MODE_DISABLED);
64    DCHECK(factory->HasActiveSession(server_id));
65    return factory->active_sessions_[server_id];
66  }
67
68  static scoped_ptr<QuicHttpStream> CreateIfSessionExists(
69      QuicStreamFactory* factory,
70      const HostPortPair& host_port_pair,
71      bool is_https,
72      const BoundNetLog& net_log) {
73    QuicServerId server_id(host_port_pair, is_https, PRIVACY_MODE_DISABLED);
74    return factory->CreateIfSessionExists(server_id, net_log);
75  }
76
77  static bool IsLiveSession(QuicStreamFactory* factory,
78                            QuicClientSession* session) {
79    for (QuicStreamFactory::SessionIdMap::iterator it =
80             factory->all_sessions_.begin();
81         it != factory->all_sessions_.end(); ++it) {
82      if (it->first == session)
83        return true;
84    }
85    return false;
86  }
87
88  static void DisableConnectionPooling(QuicStreamFactory* factory) {
89    factory->disable_connection_pooling_ = true;
90  }
91};
92
93class QuicStreamFactoryTest : public ::testing::TestWithParam<QuicVersion> {
94 protected:
95  QuicStreamFactoryTest()
96      : random_generator_(0),
97        clock_(new MockClock()),
98        maker_(GetParam(), 0, clock_),
99        cert_verifier_(CertVerifier::CreateDefault()),
100        channel_id_service_(
101            new ChannelIDService(new DefaultChannelIDStore(NULL),
102                                 base::MessageLoopProxy::current())),
103        factory_(&host_resolver_,
104                 &socket_factory_,
105                 base::WeakPtr<HttpServerProperties>(),
106                 cert_verifier_.get(),
107                 channel_id_service_.get(),
108                 &transport_security_state_,
109                 &crypto_client_stream_factory_,
110                 &random_generator_,
111                 clock_,
112                 kDefaultMaxPacketSize,
113                 std::string(),
114                 SupportedVersions(GetParam()),
115                 /*enable_port_selection=*/true,
116                 /*enable_time_based_loss_detection=*/true,
117                 /*always_require_handshake_confirmation=*/false,
118                 /*disable_connection_pooling=*/false,
119                 QuicTagVector()),
120        host_port_pair_(kDefaultServerHostName, kDefaultServerPort),
121        is_https_(false),
122        privacy_mode_(PRIVACY_MODE_DISABLED) {
123    factory_.set_require_confirmation(false);
124    clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
125  }
126
127  scoped_ptr<QuicHttpStream> CreateIfSessionExists(
128      const HostPortPair& host_port_pair,
129      const BoundNetLog& net_log) {
130    return QuicStreamFactoryPeer::CreateIfSessionExists(
131        &factory_, host_port_pair, false, net_log_);
132  }
133
134  int GetSourcePortForNewSession(const HostPortPair& destination) {
135    return GetSourcePortForNewSessionInner(destination, false);
136  }
137
138  int GetSourcePortForNewSessionAndGoAway(
139      const HostPortPair& destination) {
140    return GetSourcePortForNewSessionInner(destination, true);
141  }
142
143  int GetSourcePortForNewSessionInner(const HostPortPair& destination,
144                                      bool goaway_received) {
145    // Should only be called if there is no active session for this destination.
146    EXPECT_EQ(NULL, CreateIfSessionExists(destination, net_log_).get());
147    size_t socket_count = socket_factory_.udp_client_sockets().size();
148
149    MockRead reads[] = {
150      MockRead(ASYNC, OK, 0)  // EOF
151    };
152    DeterministicSocketData socket_data(reads, arraysize(reads), NULL, 0);
153    socket_data.StopAfter(1);
154    socket_factory_.AddSocketDataProvider(&socket_data);
155
156    QuicStreamRequest request(&factory_);
157    EXPECT_EQ(ERR_IO_PENDING,
158              request.Request(destination,
159                              is_https_,
160                              privacy_mode_,
161                              "GET",
162                              net_log_,
163                              callback_.callback()));
164
165    EXPECT_EQ(OK, callback_.WaitForResult());
166    scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
167    EXPECT_TRUE(stream.get());
168    stream.reset();
169
170    QuicClientSession* session = QuicStreamFactoryPeer::GetActiveSession(
171        &factory_, destination, is_https_);
172
173    if (socket_count + 1 != socket_factory_.udp_client_sockets().size()) {
174      EXPECT_TRUE(false);
175      return 0;
176    }
177
178    IPEndPoint endpoint;
179    socket_factory_.
180        udp_client_sockets()[socket_count]->GetLocalAddress(&endpoint);
181    int port = endpoint.port();
182    if (goaway_received) {
183      QuicGoAwayFrame goaway(QUIC_NO_ERROR, 1, "");
184      session->OnGoAway(goaway);
185    }
186
187    factory_.OnSessionClosed(session);
188    EXPECT_EQ(NULL, CreateIfSessionExists(destination, net_log_).get());
189    EXPECT_TRUE(socket_data.at_read_eof());
190    EXPECT_TRUE(socket_data.at_write_eof());
191    return port;
192  }
193
194  scoped_ptr<QuicEncryptedPacket> ConstructRstPacket() {
195    QuicStreamId stream_id = kClientDataStreamId1;
196    return maker_.MakeRstPacket(
197        1, true, stream_id,
198        AdjustErrorForVersion(QUIC_RST_FLOW_CONTROL_ACCOUNTING, GetParam()));
199  }
200
201  MockHostResolver host_resolver_;
202  DeterministicMockClientSocketFactory socket_factory_;
203  MockCryptoClientStreamFactory crypto_client_stream_factory_;
204  MockRandom random_generator_;
205  MockClock* clock_;  // Owned by factory_.
206  QuicTestPacketMaker maker_;
207  scoped_ptr<CertVerifier> cert_verifier_;
208  scoped_ptr<ChannelIDService> channel_id_service_;
209  TransportSecurityState transport_security_state_;
210  QuicStreamFactory factory_;
211  HostPortPair host_port_pair_;
212  bool is_https_;
213  PrivacyMode privacy_mode_;
214  BoundNetLog net_log_;
215  TestCompletionCallback callback_;
216};
217
218INSTANTIATE_TEST_CASE_P(Version, QuicStreamFactoryTest,
219                        ::testing::ValuesIn(QuicSupportedVersions()));
220
221TEST_P(QuicStreamFactoryTest, CreateIfSessionExists) {
222  EXPECT_EQ(NULL, CreateIfSessionExists(host_port_pair_, net_log_).get());
223}
224
225TEST_P(QuicStreamFactoryTest, Create) {
226  MockRead reads[] = {
227    MockRead(ASYNC, OK, 0)  // EOF
228  };
229  DeterministicSocketData socket_data(reads, arraysize(reads), NULL, 0);
230  socket_factory_.AddSocketDataProvider(&socket_data);
231  socket_data.StopAfter(1);
232
233  QuicStreamRequest request(&factory_);
234  EXPECT_EQ(ERR_IO_PENDING,
235            request.Request(host_port_pair_,
236                            is_https_,
237                            privacy_mode_,
238                            "GET",
239                            net_log_,
240                            callback_.callback()));
241
242  EXPECT_EQ(OK, callback_.WaitForResult());
243  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
244  EXPECT_TRUE(stream.get());
245
246  // Will reset stream 3.
247  stream = CreateIfSessionExists(host_port_pair_, net_log_);
248  EXPECT_TRUE(stream.get());
249
250  // TODO(rtenneti): We should probably have a tests that HTTP and HTTPS result
251  // in streams on different sessions.
252  QuicStreamRequest request2(&factory_);
253  EXPECT_EQ(OK,
254            request2.Request(host_port_pair_,
255                             is_https_,
256                             privacy_mode_,
257                             "GET",
258                             net_log_,
259                             callback_.callback()));
260  stream = request2.ReleaseStream();  // Will reset stream 5.
261  stream.reset();  // Will reset stream 7.
262
263  EXPECT_TRUE(socket_data.at_read_eof());
264  EXPECT_TRUE(socket_data.at_write_eof());
265}
266
267TEST_P(QuicStreamFactoryTest, CreateZeroRtt) {
268  MockRead reads[] = {
269    MockRead(ASYNC, OK, 0)  // EOF
270  };
271  DeterministicSocketData socket_data(reads, arraysize(reads), NULL, 0);
272  socket_factory_.AddSocketDataProvider(&socket_data);
273  socket_data.StopAfter(1);
274
275  crypto_client_stream_factory_.set_handshake_mode(
276      MockCryptoClientStream::ZERO_RTT);
277  host_resolver_.set_synchronous_mode(true);
278  host_resolver_.rules()->AddIPLiteralRule(host_port_pair_.host(),
279                                           "192.168.0.1", "");
280
281  QuicStreamRequest request(&factory_);
282  EXPECT_EQ(OK,
283            request.Request(host_port_pair_,
284                            is_https_,
285                            privacy_mode_,
286                            "GET",
287                            net_log_,
288                            callback_.callback()));
289
290  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
291  EXPECT_TRUE(stream.get());
292  EXPECT_TRUE(socket_data.at_read_eof());
293  EXPECT_TRUE(socket_data.at_write_eof());
294}
295
296TEST_P(QuicStreamFactoryTest, CreateZeroRttPost) {
297  MockRead reads[] = {
298    MockRead(ASYNC, OK, 0)  // EOF
299  };
300  DeterministicSocketData socket_data(reads, arraysize(reads), NULL, 0);
301  socket_factory_.AddSocketDataProvider(&socket_data);
302  socket_data.StopAfter(1);
303
304  crypto_client_stream_factory_.set_handshake_mode(
305      MockCryptoClientStream::ZERO_RTT);
306  host_resolver_.set_synchronous_mode(true);
307  host_resolver_.rules()->AddIPLiteralRule(host_port_pair_.host(),
308                                           "192.168.0.1", "");
309
310  QuicStreamRequest request(&factory_);
311  // Posts require handshake confirmation, so this will return asynchronously.
312  EXPECT_EQ(ERR_IO_PENDING,
313            request.Request(host_port_pair_,
314                            is_https_,
315                            privacy_mode_,
316                            "POST",
317                            net_log_,
318                            callback_.callback()));
319
320  // Confirm the handshake and verify that the stream is created.
321  crypto_client_stream_factory_.last_stream()->SendOnCryptoHandshakeEvent(
322      QuicSession::HANDSHAKE_CONFIRMED);
323
324  EXPECT_EQ(OK, callback_.WaitForResult());
325  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
326  EXPECT_TRUE(stream.get());
327  EXPECT_TRUE(socket_data.at_read_eof());
328  EXPECT_TRUE(socket_data.at_write_eof());
329}
330
331TEST_P(QuicStreamFactoryTest, CreateHttpVsHttps) {
332  MockRead reads[] = {
333    MockRead(ASYNC, OK, 0)  // EOF
334  };
335  DeterministicSocketData socket_data1(reads, arraysize(reads), NULL, 0);
336  DeterministicSocketData socket_data2(reads, arraysize(reads), NULL, 0);
337  socket_factory_.AddSocketDataProvider(&socket_data1);
338  socket_factory_.AddSocketDataProvider(&socket_data2);
339  socket_data1.StopAfter(1);
340  socket_data2.StopAfter(1);
341
342  QuicStreamRequest request(&factory_);
343  EXPECT_EQ(ERR_IO_PENDING,
344            request.Request(host_port_pair_,
345                            is_https_,
346                            privacy_mode_,
347                            "GET",
348                            net_log_,
349                            callback_.callback()));
350
351  EXPECT_EQ(OK, callback_.WaitForResult());
352  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
353  EXPECT_TRUE(stream.get());
354
355  QuicStreamRequest request2(&factory_);
356  EXPECT_EQ(ERR_IO_PENDING,
357            request2.Request(host_port_pair_,
358                             !is_https_,
359                             privacy_mode_,
360                             "GET",
361                             net_log_,
362                             callback_.callback()));
363  EXPECT_EQ(OK, callback_.WaitForResult());
364  stream = request2.ReleaseStream();
365  EXPECT_TRUE(stream.get());
366  stream.reset();
367
368  EXPECT_NE(QuicStreamFactoryPeer::GetActiveSession(
369                &factory_, host_port_pair_, is_https_),
370            QuicStreamFactoryPeer::GetActiveSession(
371                &factory_, host_port_pair_, !is_https_));
372
373  EXPECT_TRUE(socket_data1.at_read_eof());
374  EXPECT_TRUE(socket_data1.at_write_eof());
375  EXPECT_TRUE(socket_data2.at_read_eof());
376  EXPECT_TRUE(socket_data2.at_write_eof());
377}
378
379TEST_P(QuicStreamFactoryTest, Pooling) {
380  MockRead reads[] = {
381    MockRead(ASYNC, OK, 0)  // EOF
382  };
383  DeterministicSocketData socket_data(reads, arraysize(reads), NULL, 0);
384  socket_factory_.AddSocketDataProvider(&socket_data);
385  socket_data.StopAfter(1);
386
387  HostPortPair server2("mail.google.com", kDefaultServerPort);
388  host_resolver_.set_synchronous_mode(true);
389  host_resolver_.rules()->AddIPLiteralRule(
390      kDefaultServerHostName, "192.168.0.1", "");
391  host_resolver_.rules()->AddIPLiteralRule(
392      "mail.google.com", "192.168.0.1", "");
393
394  QuicStreamRequest request(&factory_);
395  EXPECT_EQ(OK,
396            request.Request(host_port_pair_,
397                            is_https_,
398                            privacy_mode_,
399                            "GET",
400                            net_log_,
401                            callback_.callback()));
402  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
403  EXPECT_TRUE(stream.get());
404
405  TestCompletionCallback callback;
406  QuicStreamRequest request2(&factory_);
407  EXPECT_EQ(OK,
408            request2.Request(server2,
409                             is_https_,
410                             privacy_mode_,
411                             "GET",
412                             net_log_,
413                             callback.callback()));
414  scoped_ptr<QuicHttpStream> stream2 = request2.ReleaseStream();
415  EXPECT_TRUE(stream2.get());
416
417  EXPECT_EQ(
418      QuicStreamFactoryPeer::GetActiveSession(
419          &factory_, host_port_pair_, is_https_),
420      QuicStreamFactoryPeer::GetActiveSession(&factory_, server2, is_https_));
421
422  EXPECT_TRUE(socket_data.at_read_eof());
423  EXPECT_TRUE(socket_data.at_write_eof());
424}
425
426TEST_P(QuicStreamFactoryTest, NoPoolingIfDisabled) {
427  MockRead reads[] = {
428    MockRead(ASYNC, OK, 0)  // EOF
429  };
430  DeterministicSocketData socket_data1(reads, arraysize(reads), NULL, 0);
431  DeterministicSocketData socket_data2(reads, arraysize(reads), NULL, 0);
432  socket_factory_.AddSocketDataProvider(&socket_data1);
433  socket_factory_.AddSocketDataProvider(&socket_data2);
434  socket_data1.StopAfter(1);
435  socket_data2.StopAfter(1);
436
437  HostPortPair server2("mail.google.com", kDefaultServerPort);
438  host_resolver_.set_synchronous_mode(true);
439  host_resolver_.rules()->AddIPLiteralRule(
440      kDefaultServerHostName, "192.168.0.1", "");
441  host_resolver_.rules()->AddIPLiteralRule(
442      "mail.google.com", "192.168.0.1", "");
443
444  // Disable connection pooling.
445  QuicStreamFactoryPeer::DisableConnectionPooling(&factory_);
446
447  QuicStreamRequest request(&factory_);
448  EXPECT_EQ(OK,
449            request.Request(host_port_pair_,
450                            is_https_,
451                            privacy_mode_,
452                            "GET",
453                            net_log_,
454                            callback_.callback()));
455  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
456  EXPECT_TRUE(stream.get());
457
458  TestCompletionCallback callback;
459  QuicStreamRequest request2(&factory_);
460  EXPECT_EQ(OK,
461            request2.Request(server2,
462                             is_https_,
463                             privacy_mode_,
464                             "GET",
465                             net_log_,
466                             callback.callback()));
467  scoped_ptr<QuicHttpStream> stream2 = request2.ReleaseStream();
468  EXPECT_TRUE(stream2.get());
469
470  EXPECT_NE(
471      QuicStreamFactoryPeer::GetActiveSession(
472          &factory_, host_port_pair_, is_https_),
473      QuicStreamFactoryPeer::GetActiveSession(&factory_, server2, is_https_));
474
475  EXPECT_TRUE(socket_data1.at_read_eof());
476  EXPECT_TRUE(socket_data1.at_write_eof());
477  EXPECT_TRUE(socket_data2.at_read_eof());
478  EXPECT_TRUE(socket_data2.at_write_eof());
479}
480
481TEST_P(QuicStreamFactoryTest, NoPoolingAfterGoAway) {
482  MockRead reads[] = {
483    MockRead(ASYNC, OK, 0)  // EOF
484  };
485  DeterministicSocketData socket_data1(reads, arraysize(reads), NULL, 0);
486  DeterministicSocketData socket_data2(reads, arraysize(reads), NULL, 0);
487  socket_factory_.AddSocketDataProvider(&socket_data1);
488  socket_factory_.AddSocketDataProvider(&socket_data2);
489  socket_data1.StopAfter(1);
490  socket_data2.StopAfter(1);
491
492  HostPortPair server2("mail.google.com", kDefaultServerPort);
493  host_resolver_.set_synchronous_mode(true);
494  host_resolver_.rules()->AddIPLiteralRule(
495      kDefaultServerHostName, "192.168.0.1", "");
496  host_resolver_.rules()->AddIPLiteralRule(
497      "mail.google.com", "192.168.0.1", "");
498
499  QuicStreamRequest request(&factory_);
500  EXPECT_EQ(OK,
501            request.Request(host_port_pair_,
502                            is_https_,
503                            privacy_mode_,
504                            "GET",
505                            net_log_,
506                            callback_.callback()));
507  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
508  EXPECT_TRUE(stream.get());
509
510  TestCompletionCallback callback;
511  QuicStreamRequest request2(&factory_);
512  EXPECT_EQ(OK,
513            request2.Request(server2,
514                             is_https_,
515                             privacy_mode_,
516                             "GET",
517                             net_log_,
518                             callback.callback()));
519  scoped_ptr<QuicHttpStream> stream2 = request2.ReleaseStream();
520  EXPECT_TRUE(stream2.get());
521
522  factory_.OnSessionGoingAway(QuicStreamFactoryPeer::GetActiveSession(
523      &factory_, host_port_pair_, is_https_));
524  EXPECT_FALSE(QuicStreamFactoryPeer::HasActiveSession(
525      &factory_, host_port_pair_, is_https_));
526  EXPECT_FALSE(QuicStreamFactoryPeer::HasActiveSession(
527      &factory_, server2, is_https_));
528
529  TestCompletionCallback callback3;
530  QuicStreamRequest request3(&factory_);
531  EXPECT_EQ(OK,
532            request3.Request(server2,
533                             is_https_,
534                             privacy_mode_,
535                             "GET",
536                             net_log_,
537                             callback3.callback()));
538  scoped_ptr<QuicHttpStream> stream3 = request3.ReleaseStream();
539  EXPECT_TRUE(stream3.get());
540
541  EXPECT_TRUE(QuicStreamFactoryPeer::HasActiveSession(
542      &factory_, server2, is_https_));
543
544  EXPECT_TRUE(socket_data1.at_read_eof());
545  EXPECT_TRUE(socket_data1.at_write_eof());
546  EXPECT_TRUE(socket_data2.at_read_eof());
547  EXPECT_TRUE(socket_data2.at_write_eof());
548}
549
550TEST_P(QuicStreamFactoryTest, HttpsPooling) {
551  MockRead reads[] = {
552    MockRead(ASYNC, OK, 0)  // EOF
553  };
554  DeterministicSocketData socket_data(reads, arraysize(reads), NULL, 0);
555  socket_factory_.AddSocketDataProvider(&socket_data);
556  socket_data.StopAfter(1);
557
558  HostPortPair server1("www.example.org", 443);
559  HostPortPair server2("mail.example.org", 443);
560
561  // Load a cert that is valid for:
562  //   www.example.org (server1)
563  //   mail.example.org (server2)
564  //   www.example.com
565  base::FilePath certs_dir = GetTestCertsDirectory();
566  scoped_refptr<X509Certificate> test_cert(
567      ImportCertFromFile(certs_dir, "spdy_pooling.pem"));
568  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert.get());
569  ProofVerifyDetailsChromium verify_details;
570  verify_details.cert_verify_result.verified_cert = test_cert;
571  verify_details.cert_verify_result.is_issued_by_known_root = true;
572  crypto_client_stream_factory_.set_proof_verify_details(&verify_details);
573
574  host_resolver_.set_synchronous_mode(true);
575  host_resolver_.rules()->AddIPLiteralRule(server1.host(), "192.168.0.1", "");
576  host_resolver_.rules()->AddIPLiteralRule(server2.host(), "192.168.0.1", "");
577
578  QuicStreamRequest request(&factory_);
579  is_https_ = true;
580  EXPECT_EQ(OK,
581            request.Request(server1,
582                            is_https_,
583                            privacy_mode_,
584                            "GET",
585                            net_log_,
586                            callback_.callback()));
587  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
588  EXPECT_TRUE(stream.get());
589
590  TestCompletionCallback callback;
591  QuicStreamRequest request2(&factory_);
592  EXPECT_EQ(OK,
593            request2.Request(server2,
594                             is_https_,
595                             privacy_mode_,
596                             "GET",
597                             net_log_,
598                             callback_.callback()));
599  scoped_ptr<QuicHttpStream> stream2 = request2.ReleaseStream();
600  EXPECT_TRUE(stream2.get());
601
602  EXPECT_EQ(QuicStreamFactoryPeer::GetActiveSession(
603                &factory_, server1, is_https_),
604            QuicStreamFactoryPeer::GetActiveSession(
605                &factory_, server2, is_https_));
606
607  EXPECT_TRUE(socket_data.at_read_eof());
608  EXPECT_TRUE(socket_data.at_write_eof());
609}
610
611TEST_P(QuicStreamFactoryTest, NoHttpsPoolingIfDisabled) {
612  MockRead reads[] = {
613    MockRead(ASYNC, OK, 0)  // EOF
614  };
615  DeterministicSocketData socket_data1(reads, arraysize(reads), NULL, 0);
616  DeterministicSocketData socket_data2(reads, arraysize(reads), NULL, 0);
617  socket_factory_.AddSocketDataProvider(&socket_data1);
618  socket_factory_.AddSocketDataProvider(&socket_data2);
619  socket_data1.StopAfter(1);
620  socket_data2.StopAfter(1);
621
622  HostPortPair server1("www.example.org", 443);
623  HostPortPair server2("mail.example.org", 443);
624
625  // Load a cert that is valid for:
626  //   www.example.org (server1)
627  //   mail.example.org (server2)
628  //   www.example.com
629  base::FilePath certs_dir = GetTestCertsDirectory();
630  scoped_refptr<X509Certificate> test_cert(
631      ImportCertFromFile(certs_dir, "spdy_pooling.pem"));
632  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert.get());
633  ProofVerifyDetailsChromium verify_details;
634  verify_details.cert_verify_result.verified_cert = test_cert;
635  verify_details.cert_verify_result.is_issued_by_known_root = true;
636  crypto_client_stream_factory_.set_proof_verify_details(&verify_details);
637
638  host_resolver_.set_synchronous_mode(true);
639  host_resolver_.rules()->AddIPLiteralRule(server1.host(), "192.168.0.1", "");
640  host_resolver_.rules()->AddIPLiteralRule(server2.host(), "192.168.0.1", "");
641
642  // Disable connection pooling.
643  QuicStreamFactoryPeer::DisableConnectionPooling(&factory_);
644
645  QuicStreamRequest request(&factory_);
646  is_https_ = true;
647  EXPECT_EQ(OK,
648            request.Request(server1,
649                            is_https_,
650                            privacy_mode_,
651                            "GET",
652                            net_log_,
653                            callback_.callback()));
654  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
655  EXPECT_TRUE(stream.get());
656
657  TestCompletionCallback callback;
658  QuicStreamRequest request2(&factory_);
659  EXPECT_EQ(OK,
660            request2.Request(server2,
661                             is_https_,
662                             privacy_mode_,
663                             "GET",
664                             net_log_,
665                             callback_.callback()));
666  scoped_ptr<QuicHttpStream> stream2 = request2.ReleaseStream();
667  EXPECT_TRUE(stream2.get());
668
669  EXPECT_NE(QuicStreamFactoryPeer::GetActiveSession(
670                &factory_, server1, is_https_),
671            QuicStreamFactoryPeer::GetActiveSession(
672                &factory_, server2, is_https_));
673
674  EXPECT_TRUE(socket_data1.at_read_eof());
675  EXPECT_TRUE(socket_data1.at_write_eof());
676  EXPECT_TRUE(socket_data2.at_read_eof());
677  EXPECT_TRUE(socket_data2.at_write_eof());
678}
679
680TEST_P(QuicStreamFactoryTest, NoHttpsPoolingWithCertMismatch) {
681  MockRead reads[] = {
682    MockRead(ASYNC, OK, 0)  // EOF
683  };
684  DeterministicSocketData socket_data1(reads, arraysize(reads), NULL, 0);
685  DeterministicSocketData socket_data2(reads, arraysize(reads), NULL, 0);
686  socket_factory_.AddSocketDataProvider(&socket_data1);
687  socket_factory_.AddSocketDataProvider(&socket_data2);
688  socket_data1.StopAfter(1);
689  socket_data2.StopAfter(1);
690
691  HostPortPair server1("www.example.org", 443);
692  HostPortPair server2("mail.google.com", 443);
693
694  // Load a cert that is valid for:
695  //   www.example.org (server1)
696  //   mail.example.org
697  //   www.example.com
698  // But is not valid for mail.google.com (server2).
699  base::FilePath certs_dir = GetTestCertsDirectory();
700  scoped_refptr<X509Certificate> test_cert(
701      ImportCertFromFile(certs_dir, "spdy_pooling.pem"));
702  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert.get());
703  ProofVerifyDetailsChromium verify_details;
704  verify_details.cert_verify_result.verified_cert = test_cert;
705  crypto_client_stream_factory_.set_proof_verify_details(&verify_details);
706
707
708  host_resolver_.set_synchronous_mode(true);
709  host_resolver_.rules()->AddIPLiteralRule(server1.host(), "192.168.0.1", "");
710  host_resolver_.rules()->AddIPLiteralRule(server2.host(), "192.168.0.1", "");
711
712  QuicStreamRequest request(&factory_);
713  is_https_ = true;
714  EXPECT_EQ(OK,
715            request.Request(server1,
716                            is_https_,
717                            privacy_mode_,
718                            "GET",
719                            net_log_,
720                            callback_.callback()));
721  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
722  EXPECT_TRUE(stream.get());
723
724  TestCompletionCallback callback;
725  QuicStreamRequest request2(&factory_);
726  EXPECT_EQ(OK,
727            request2.Request(server2,
728                             is_https_,
729                             privacy_mode_,
730                             "GET",
731                             net_log_,
732                             callback_.callback()));
733  scoped_ptr<QuicHttpStream> stream2 = request2.ReleaseStream();
734  EXPECT_TRUE(stream2.get());
735
736  EXPECT_NE(QuicStreamFactoryPeer::GetActiveSession(
737                &factory_, server1, is_https_),
738            QuicStreamFactoryPeer::GetActiveSession(
739                &factory_, server2, is_https_));
740
741  EXPECT_TRUE(socket_data1.at_read_eof());
742  EXPECT_TRUE(socket_data1.at_write_eof());
743  EXPECT_TRUE(socket_data2.at_read_eof());
744  EXPECT_TRUE(socket_data2.at_write_eof());
745}
746
747TEST_P(QuicStreamFactoryTest, HttpsPoolingWithMatchingPins) {
748  MockRead reads[] = {
749    MockRead(ASYNC, OK, 0)  // EOF
750  };
751  DeterministicSocketData socket_data(reads, arraysize(reads), NULL, 0);
752  socket_factory_.AddSocketDataProvider(&socket_data);
753  socket_data.StopAfter(1);
754
755  HostPortPair server1("www.example.org", 443);
756  HostPortPair server2("mail.example.org", 443);
757  uint8 primary_pin = 1;
758  uint8 backup_pin = 2;
759  test::AddPin(&transport_security_state_, "mail.example.org", primary_pin,
760               backup_pin);
761
762  // Load a cert that is valid for:
763  //   www.example.org (server1)
764  //   mail.example.org (server2)
765  base::FilePath certs_dir = GetTestCertsDirectory();
766  scoped_refptr<X509Certificate> test_cert(
767      ImportCertFromFile(certs_dir, "spdy_pooling.pem"));
768  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert.get());
769  ProofVerifyDetailsChromium verify_details;
770  verify_details.cert_verify_result.verified_cert = test_cert;
771  verify_details.cert_verify_result.is_issued_by_known_root = true;
772  verify_details.cert_verify_result.public_key_hashes.push_back(
773      test::GetTestHashValue(primary_pin));
774  crypto_client_stream_factory_.set_proof_verify_details(&verify_details);
775
776
777  host_resolver_.set_synchronous_mode(true);
778  host_resolver_.rules()->AddIPLiteralRule(server1.host(), "192.168.0.1", "");
779  host_resolver_.rules()->AddIPLiteralRule(server2.host(), "192.168.0.1", "");
780
781  QuicStreamRequest request(&factory_);
782  is_https_ = true;
783  EXPECT_EQ(OK,
784            request.Request(server1,
785                            is_https_,
786                            privacy_mode_,
787                            "GET",
788                            net_log_,
789                            callback_.callback()));
790  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
791  EXPECT_TRUE(stream.get());
792
793  TestCompletionCallback callback;
794  QuicStreamRequest request2(&factory_);
795  EXPECT_EQ(OK,
796            request2.Request(server2,
797                             is_https_,
798                             privacy_mode_,
799                             "GET",
800                             net_log_,
801                             callback_.callback()));
802  scoped_ptr<QuicHttpStream> stream2 = request2.ReleaseStream();
803  EXPECT_TRUE(stream2.get());
804
805  EXPECT_EQ(QuicStreamFactoryPeer::GetActiveSession(
806                &factory_, server1, is_https_),
807            QuicStreamFactoryPeer::GetActiveSession(
808                &factory_, server2, is_https_));
809
810  EXPECT_TRUE(socket_data.at_read_eof());
811  EXPECT_TRUE(socket_data.at_write_eof());
812}
813
814TEST_P(QuicStreamFactoryTest, NoHttpsPoolingWithMatchingPinsIfDisabled) {
815  MockRead reads[] = {
816    MockRead(ASYNC, OK, 0)  // EOF
817  };
818  DeterministicSocketData socket_data1(reads, arraysize(reads), NULL, 0);
819  DeterministicSocketData socket_data2(reads, arraysize(reads), NULL, 0);
820  socket_factory_.AddSocketDataProvider(&socket_data1);
821  socket_factory_.AddSocketDataProvider(&socket_data2);
822  socket_data1.StopAfter(1);
823  socket_data2.StopAfter(1);
824
825  HostPortPair server1("www.example.org", 443);
826  HostPortPair server2("mail.example.org", 443);
827  uint8 primary_pin = 1;
828  uint8 backup_pin = 2;
829  test::AddPin(&transport_security_state_, "mail.example.org", primary_pin,
830               backup_pin);
831
832  // Load a cert that is valid for:
833  //   www.example.org (server1)
834  //   mail.example.org (server2)
835  base::FilePath certs_dir = GetTestCertsDirectory();
836  scoped_refptr<X509Certificate> test_cert(
837      ImportCertFromFile(certs_dir, "spdy_pooling.pem"));
838  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert.get());
839  ProofVerifyDetailsChromium verify_details;
840  verify_details.cert_verify_result.verified_cert = test_cert;
841  verify_details.cert_verify_result.is_issued_by_known_root = true;
842  verify_details.cert_verify_result.public_key_hashes.push_back(
843      test::GetTestHashValue(primary_pin));
844  crypto_client_stream_factory_.set_proof_verify_details(&verify_details);
845
846
847  host_resolver_.set_synchronous_mode(true);
848  host_resolver_.rules()->AddIPLiteralRule(server1.host(), "192.168.0.1", "");
849  host_resolver_.rules()->AddIPLiteralRule(server2.host(), "192.168.0.1", "");
850
851  // Disable connection pooling.
852  QuicStreamFactoryPeer::DisableConnectionPooling(&factory_);
853
854  QuicStreamRequest request(&factory_);
855  is_https_ = true;
856  EXPECT_EQ(OK,
857            request.Request(server1,
858                            is_https_,
859                            privacy_mode_,
860                            "GET",
861                            net_log_,
862                            callback_.callback()));
863  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
864  EXPECT_TRUE(stream.get());
865
866  TestCompletionCallback callback;
867  QuicStreamRequest request2(&factory_);
868  EXPECT_EQ(OK,
869            request2.Request(server2,
870                             is_https_,
871                             privacy_mode_,
872                             "GET",
873                             net_log_,
874                             callback_.callback()));
875  scoped_ptr<QuicHttpStream> stream2 = request2.ReleaseStream();
876  EXPECT_TRUE(stream2.get());
877
878  EXPECT_NE(QuicStreamFactoryPeer::GetActiveSession(
879                &factory_, server1, is_https_),
880            QuicStreamFactoryPeer::GetActiveSession(
881                &factory_, server2, is_https_));
882
883  EXPECT_TRUE(socket_data1.at_read_eof());
884  EXPECT_TRUE(socket_data1.at_write_eof());
885  EXPECT_TRUE(socket_data2.at_read_eof());
886  EXPECT_TRUE(socket_data2.at_write_eof());
887}
888
889TEST_P(QuicStreamFactoryTest, NoHttpsPoolingWithDifferentPins) {
890  MockRead reads[] = {
891    MockRead(ASYNC, OK, 0)  // EOF
892  };
893  DeterministicSocketData socket_data1(reads, arraysize(reads), NULL, 0);
894  DeterministicSocketData socket_data2(reads, arraysize(reads), NULL, 0);
895  socket_factory_.AddSocketDataProvider(&socket_data1);
896  socket_factory_.AddSocketDataProvider(&socket_data2);
897  socket_data1.StopAfter(1);
898  socket_data2.StopAfter(1);
899
900  HostPortPair server1("www.example.org", 443);
901  HostPortPair server2("mail.example.org", 443);
902  uint8 primary_pin = 1;
903  uint8 backup_pin = 2;
904  uint8 bad_pin = 3;
905  test::AddPin(&transport_security_state_, "mail.example.org", primary_pin,
906               backup_pin);
907
908  // Load a cert that is valid for:
909  //   www.example.org (server1)
910  //   mail.example.org (server2)
911  base::FilePath certs_dir = GetTestCertsDirectory();
912  scoped_refptr<X509Certificate> test_cert(
913      ImportCertFromFile(certs_dir, "spdy_pooling.pem"));
914  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert.get());
915  ProofVerifyDetailsChromium verify_details;
916  verify_details.cert_verify_result.verified_cert = test_cert;
917  verify_details.cert_verify_result.is_issued_by_known_root = true;
918  verify_details.cert_verify_result.public_key_hashes.push_back(
919      test::GetTestHashValue(bad_pin));
920  crypto_client_stream_factory_.set_proof_verify_details(&verify_details);
921
922
923  host_resolver_.set_synchronous_mode(true);
924  host_resolver_.rules()->AddIPLiteralRule(server1.host(), "192.168.0.1", "");
925  host_resolver_.rules()->AddIPLiteralRule(server2.host(), "192.168.0.1", "");
926
927  QuicStreamRequest request(&factory_);
928  is_https_ = true;
929  EXPECT_EQ(OK,
930            request.Request(server1,
931                            is_https_,
932                            privacy_mode_,
933                            "GET",
934                            net_log_,
935                            callback_.callback()));
936  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
937  EXPECT_TRUE(stream.get());
938
939  TestCompletionCallback callback;
940  QuicStreamRequest request2(&factory_);
941  EXPECT_EQ(OK,
942            request2.Request(server2,
943                             is_https_,
944                             privacy_mode_,
945                             "GET",
946                             net_log_,
947                             callback_.callback()));
948  scoped_ptr<QuicHttpStream> stream2 = request2.ReleaseStream();
949  EXPECT_TRUE(stream2.get());
950
951  EXPECT_NE(QuicStreamFactoryPeer::GetActiveSession(
952                &factory_, server1, is_https_),
953            QuicStreamFactoryPeer::GetActiveSession(
954                &factory_, server2, is_https_));
955
956  EXPECT_TRUE(socket_data1.at_read_eof());
957  EXPECT_TRUE(socket_data1.at_write_eof());
958  EXPECT_TRUE(socket_data2.at_read_eof());
959  EXPECT_TRUE(socket_data2.at_write_eof());
960}
961
962TEST_P(QuicStreamFactoryTest, Goaway) {
963  MockRead reads[] = {
964    MockRead(ASYNC, OK, 0)  // EOF
965  };
966  DeterministicSocketData socket_data(reads, arraysize(reads), NULL, 0);
967  socket_data.StopAfter(1);
968  socket_factory_.AddSocketDataProvider(&socket_data);
969  DeterministicSocketData socket_data2(reads, arraysize(reads), NULL, 0);
970  socket_data2.StopAfter(1);
971  socket_factory_.AddSocketDataProvider(&socket_data2);
972
973  QuicStreamRequest request(&factory_);
974  EXPECT_EQ(ERR_IO_PENDING,
975            request.Request(host_port_pair_,
976                            is_https_,
977                            privacy_mode_,
978                            "GET",
979                            net_log_,
980                            callback_.callback()));
981
982  EXPECT_EQ(OK, callback_.WaitForResult());
983  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
984  EXPECT_TRUE(stream.get());
985
986  // Mark the session as going away.  Ensure that while it is still alive
987  // that it is no longer active.
988  QuicClientSession* session = QuicStreamFactoryPeer::GetActiveSession(
989      &factory_, host_port_pair_, is_https_);
990  factory_.OnSessionGoingAway(session);
991  EXPECT_EQ(true, QuicStreamFactoryPeer::IsLiveSession(&factory_, session));
992  EXPECT_FALSE(QuicStreamFactoryPeer::HasActiveSession(
993      &factory_, host_port_pair_, is_https_));
994  EXPECT_EQ(NULL, CreateIfSessionExists(host_port_pair_, net_log_).get());
995
996  // Create a new request for the same destination and verify that a
997  // new session is created.
998  QuicStreamRequest request2(&factory_);
999  EXPECT_EQ(ERR_IO_PENDING,
1000            request2.Request(host_port_pair_,
1001                             is_https_,
1002                             privacy_mode_,
1003                             "GET",
1004                             net_log_,
1005                             callback_.callback()));
1006  EXPECT_EQ(OK, callback_.WaitForResult());
1007  scoped_ptr<QuicHttpStream> stream2 = request2.ReleaseStream();
1008  EXPECT_TRUE(stream2.get());
1009
1010  EXPECT_TRUE(QuicStreamFactoryPeer::HasActiveSession(&factory_,
1011                                                      host_port_pair_,
1012                                                      is_https_));
1013  EXPECT_NE(session,
1014            QuicStreamFactoryPeer::GetActiveSession(
1015                &factory_, host_port_pair_, is_https_));
1016  EXPECT_EQ(true, QuicStreamFactoryPeer::IsLiveSession(&factory_, session));
1017
1018  stream2.reset();
1019  stream.reset();
1020
1021  EXPECT_TRUE(socket_data.at_read_eof());
1022  EXPECT_TRUE(socket_data.at_write_eof());
1023  EXPECT_TRUE(socket_data2.at_read_eof());
1024  EXPECT_TRUE(socket_data2.at_write_eof());
1025}
1026
1027TEST_P(QuicStreamFactoryTest, MaxOpenStream) {
1028  MockRead reads[] = {
1029    MockRead(ASYNC, OK, 0)  // EOF
1030  };
1031  QuicStreamId stream_id = kClientDataStreamId1;
1032  scoped_ptr<QuicEncryptedPacket> rst(
1033      maker_.MakeRstPacket(1, true, stream_id, QUIC_STREAM_CANCELLED));
1034  MockWrite writes[] = {
1035    MockWrite(ASYNC, rst->data(), rst->length(), 1),
1036  };
1037  DeterministicSocketData socket_data(reads, arraysize(reads),
1038                                      writes, arraysize(writes));
1039  socket_factory_.AddSocketDataProvider(&socket_data);
1040  socket_data.StopAfter(1);
1041
1042  HttpRequestInfo request_info;
1043  std::vector<QuicHttpStream*> streams;
1044  // The MockCryptoClientStream sets max_open_streams to be
1045  // 2 * kDefaultMaxStreamsPerConnection.
1046  for (size_t i = 0; i < 2 * kDefaultMaxStreamsPerConnection; i++) {
1047    QuicStreamRequest request(&factory_);
1048    int rv = request.Request(host_port_pair_,
1049                             is_https_,
1050                             privacy_mode_,
1051                             "GET",
1052                             net_log_,
1053                             callback_.callback());
1054    if (i == 0) {
1055      EXPECT_EQ(ERR_IO_PENDING, rv);
1056      EXPECT_EQ(OK, callback_.WaitForResult());
1057    } else {
1058      EXPECT_EQ(OK, rv);
1059    }
1060    scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
1061    EXPECT_TRUE(stream);
1062    EXPECT_EQ(OK, stream->InitializeStream(
1063        &request_info, DEFAULT_PRIORITY, net_log_, CompletionCallback()));
1064    streams.push_back(stream.release());
1065  }
1066
1067  QuicStreamRequest request(&factory_);
1068  EXPECT_EQ(OK,
1069            request.Request(host_port_pair_,
1070                            is_https_,
1071                            privacy_mode_,
1072                            "GET",
1073                            net_log_,
1074                            CompletionCallback()));
1075  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
1076  EXPECT_TRUE(stream);
1077  EXPECT_EQ(ERR_IO_PENDING, stream->InitializeStream(
1078        &request_info, DEFAULT_PRIORITY, net_log_, callback_.callback()));
1079
1080  // Close the first stream.
1081  streams.front()->Close(false);
1082
1083  ASSERT_TRUE(callback_.have_result());
1084
1085  EXPECT_EQ(OK, callback_.WaitForResult());
1086
1087  EXPECT_TRUE(socket_data.at_read_eof());
1088  EXPECT_TRUE(socket_data.at_write_eof());
1089  STLDeleteElements(&streams);
1090}
1091
1092TEST_P(QuicStreamFactoryTest, ResolutionErrorInCreate) {
1093  DeterministicSocketData socket_data(NULL, 0, NULL, 0);
1094  socket_factory_.AddSocketDataProvider(&socket_data);
1095
1096  host_resolver_.rules()->AddSimulatedFailure(kDefaultServerHostName);
1097
1098  QuicStreamRequest request(&factory_);
1099  EXPECT_EQ(ERR_IO_PENDING,
1100            request.Request(host_port_pair_,
1101                            is_https_,
1102                            privacy_mode_,
1103                            "GET",
1104                            net_log_,
1105                            callback_.callback()));
1106
1107  EXPECT_EQ(ERR_NAME_NOT_RESOLVED, callback_.WaitForResult());
1108
1109  EXPECT_TRUE(socket_data.at_read_eof());
1110  EXPECT_TRUE(socket_data.at_write_eof());
1111}
1112
1113TEST_P(QuicStreamFactoryTest, ConnectErrorInCreate) {
1114  MockConnect connect(SYNCHRONOUS, ERR_ADDRESS_IN_USE);
1115  DeterministicSocketData socket_data(NULL, 0, NULL, 0);
1116  socket_data.set_connect_data(connect);
1117  socket_factory_.AddSocketDataProvider(&socket_data);
1118  socket_data.StopAfter(1);
1119
1120  QuicStreamRequest request(&factory_);
1121  EXPECT_EQ(ERR_IO_PENDING,
1122            request.Request(host_port_pair_,
1123                            is_https_,
1124                            privacy_mode_,
1125                            "GET",
1126                            net_log_,
1127                            callback_.callback()));
1128
1129  EXPECT_EQ(ERR_ADDRESS_IN_USE, callback_.WaitForResult());
1130
1131  EXPECT_TRUE(socket_data.at_read_eof());
1132  EXPECT_TRUE(socket_data.at_write_eof());
1133}
1134
1135TEST_P(QuicStreamFactoryTest, CancelCreate) {
1136  MockRead reads[] = {
1137    MockRead(ASYNC, OK, 0)  // EOF
1138  };
1139  DeterministicSocketData socket_data(reads, arraysize(reads), NULL, 0);
1140  socket_factory_.AddSocketDataProvider(&socket_data);
1141  {
1142    QuicStreamRequest request(&factory_);
1143    EXPECT_EQ(ERR_IO_PENDING,
1144              request.Request(host_port_pair_,
1145                              is_https_,
1146                              privacy_mode_,
1147                              "GET",
1148                              net_log_,
1149                              callback_.callback()));
1150  }
1151
1152  socket_data.StopAfter(1);
1153  base::RunLoop run_loop;
1154  run_loop.RunUntilIdle();
1155
1156  scoped_ptr<QuicHttpStream> stream(
1157      CreateIfSessionExists(host_port_pair_, net_log_));
1158  EXPECT_TRUE(stream.get());
1159  stream.reset();
1160
1161  EXPECT_TRUE(socket_data.at_read_eof());
1162  EXPECT_TRUE(socket_data.at_write_eof());
1163}
1164
1165TEST_P(QuicStreamFactoryTest, CreateConsistentEphemeralPort) {
1166  // Sequentially connect to the default host, then another host, and then the
1167  // default host.  Verify that the default host gets a consistent ephemeral
1168  // port, that is different from the other host's connection.
1169
1170  std::string other_server_name = "other.google.com";
1171  EXPECT_NE(kDefaultServerHostName, other_server_name);
1172  HostPortPair host_port_pair2(other_server_name, kDefaultServerPort);
1173
1174  int original_port = GetSourcePortForNewSession(host_port_pair_);
1175  EXPECT_NE(original_port, GetSourcePortForNewSession(host_port_pair2));
1176  EXPECT_EQ(original_port, GetSourcePortForNewSession(host_port_pair_));
1177}
1178
1179TEST_P(QuicStreamFactoryTest, GoAwayDisablesConsistentEphemeralPort) {
1180  // Get a session to the host using the port suggester.
1181  int original_port =
1182      GetSourcePortForNewSessionAndGoAway(host_port_pair_);
1183  // Verify that the port is different after the goaway.
1184  EXPECT_NE(original_port, GetSourcePortForNewSession(host_port_pair_));
1185  // Since the previous session did not goaway we should see the original port.
1186  EXPECT_EQ(original_port, GetSourcePortForNewSession(host_port_pair_));
1187}
1188
1189TEST_P(QuicStreamFactoryTest, CloseAllSessions) {
1190  MockRead reads[] = {
1191    MockRead(ASYNC, 0, 0)  // EOF
1192  };
1193  scoped_ptr<QuicEncryptedPacket> rst(ConstructRstPacket());
1194  std::vector<MockWrite> writes;
1195  writes.push_back(MockWrite(ASYNC, rst->data(), rst->length(), 1));
1196  DeterministicSocketData socket_data(reads, arraysize(reads),
1197                                      writes.empty() ? NULL  : &writes[0],
1198                                      writes.size());
1199  socket_factory_.AddSocketDataProvider(&socket_data);
1200  socket_data.StopAfter(1);
1201
1202  MockRead reads2[] = {
1203    MockRead(ASYNC, 0, 0)  // EOF
1204  };
1205  DeterministicSocketData socket_data2(reads2, arraysize(reads2), NULL, 0);
1206  socket_factory_.AddSocketDataProvider(&socket_data2);
1207  socket_data2.StopAfter(1);
1208
1209  QuicStreamRequest request(&factory_);
1210  EXPECT_EQ(ERR_IO_PENDING,
1211            request.Request(host_port_pair_,
1212                            is_https_,
1213                            privacy_mode_,
1214                            "GET",
1215                            net_log_,
1216                            callback_.callback()));
1217
1218  EXPECT_EQ(OK, callback_.WaitForResult());
1219  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
1220  HttpRequestInfo request_info;
1221  EXPECT_EQ(OK, stream->InitializeStream(&request_info,
1222                                         DEFAULT_PRIORITY,
1223                                         net_log_, CompletionCallback()));
1224
1225  // Close the session and verify that stream saw the error.
1226  factory_.CloseAllSessions(ERR_INTERNET_DISCONNECTED);
1227  EXPECT_EQ(ERR_INTERNET_DISCONNECTED,
1228            stream->ReadResponseHeaders(callback_.callback()));
1229
1230  // Now attempting to request a stream to the same origin should create
1231  // a new session.
1232
1233  QuicStreamRequest request2(&factory_);
1234  EXPECT_EQ(ERR_IO_PENDING,
1235            request2.Request(host_port_pair_,
1236                             is_https_,
1237                             privacy_mode_,
1238                             "GET",
1239                             net_log_,
1240                             callback_.callback()));
1241
1242  EXPECT_EQ(OK, callback_.WaitForResult());
1243  stream = request2.ReleaseStream();
1244  stream.reset();  // Will reset stream 3.
1245
1246  EXPECT_TRUE(socket_data.at_read_eof());
1247  EXPECT_TRUE(socket_data.at_write_eof());
1248  EXPECT_TRUE(socket_data2.at_read_eof());
1249  EXPECT_TRUE(socket_data2.at_write_eof());
1250}
1251
1252TEST_P(QuicStreamFactoryTest, OnIPAddressChanged) {
1253  MockRead reads[] = {
1254    MockRead(ASYNC, 0, 0)  // EOF
1255  };
1256  scoped_ptr<QuicEncryptedPacket> rst(ConstructRstPacket());
1257  std::vector<MockWrite> writes;
1258  writes.push_back(MockWrite(ASYNC, rst->data(), rst->length(), 1));
1259  DeterministicSocketData socket_data(reads, arraysize(reads),
1260                                      writes.empty() ? NULL  : &writes[0],
1261                                      writes.size());
1262  socket_factory_.AddSocketDataProvider(&socket_data);
1263  socket_data.StopAfter(1);
1264
1265  MockRead reads2[] = {
1266    MockRead(ASYNC, 0, 0)  // EOF
1267  };
1268  DeterministicSocketData socket_data2(reads2, arraysize(reads2), NULL, 0);
1269  socket_factory_.AddSocketDataProvider(&socket_data2);
1270  socket_data2.StopAfter(1);
1271
1272  QuicStreamRequest request(&factory_);
1273  EXPECT_EQ(ERR_IO_PENDING,
1274            request.Request(host_port_pair_,
1275                            is_https_,
1276                            privacy_mode_,
1277                            "GET",
1278                            net_log_,
1279                            callback_.callback()));
1280
1281  EXPECT_EQ(OK, callback_.WaitForResult());
1282  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
1283  HttpRequestInfo request_info;
1284  EXPECT_EQ(OK, stream->InitializeStream(&request_info,
1285                                         DEFAULT_PRIORITY,
1286                                         net_log_, CompletionCallback()));
1287
1288  // Change the IP address and verify that stream saw the error.
1289  factory_.OnIPAddressChanged();
1290  EXPECT_EQ(ERR_NETWORK_CHANGED,
1291            stream->ReadResponseHeaders(callback_.callback()));
1292  EXPECT_TRUE(factory_.require_confirmation());
1293
1294  // Now attempting to request a stream to the same origin should create
1295  // a new session.
1296
1297  QuicStreamRequest request2(&factory_);
1298  EXPECT_EQ(ERR_IO_PENDING,
1299            request2.Request(host_port_pair_,
1300                             is_https_,
1301                             privacy_mode_,
1302                             "GET",
1303                             net_log_,
1304                             callback_.callback()));
1305
1306  EXPECT_EQ(OK, callback_.WaitForResult());
1307  stream = request2.ReleaseStream();
1308  stream.reset();  // Will reset stream 3.
1309
1310  EXPECT_TRUE(socket_data.at_read_eof());
1311  EXPECT_TRUE(socket_data.at_write_eof());
1312  EXPECT_TRUE(socket_data2.at_read_eof());
1313  EXPECT_TRUE(socket_data2.at_write_eof());
1314}
1315
1316TEST_P(QuicStreamFactoryTest, OnCertAdded) {
1317  MockRead reads[] = {
1318    MockRead(ASYNC, 0, 0)  // EOF
1319  };
1320  scoped_ptr<QuicEncryptedPacket> rst(ConstructRstPacket());
1321  std::vector<MockWrite> writes;
1322  writes.push_back(MockWrite(ASYNC, rst->data(), rst->length(), 1));
1323  DeterministicSocketData socket_data(reads, arraysize(reads),
1324                                      writes.empty() ? NULL  : &writes[0],
1325                                      writes.size());
1326  socket_factory_.AddSocketDataProvider(&socket_data);
1327  socket_data.StopAfter(1);
1328
1329  MockRead reads2[] = {
1330    MockRead(ASYNC, 0, 0)  // EOF
1331  };
1332  DeterministicSocketData socket_data2(reads2, arraysize(reads2), NULL, 0);
1333  socket_factory_.AddSocketDataProvider(&socket_data2);
1334  socket_data2.StopAfter(1);
1335
1336  QuicStreamRequest request(&factory_);
1337  EXPECT_EQ(ERR_IO_PENDING,
1338            request.Request(host_port_pair_,
1339                            is_https_,
1340                            privacy_mode_,
1341                            "GET",
1342                            net_log_,
1343                            callback_.callback()));
1344
1345  EXPECT_EQ(OK, callback_.WaitForResult());
1346  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
1347  HttpRequestInfo request_info;
1348  EXPECT_EQ(OK, stream->InitializeStream(&request_info,
1349                                         DEFAULT_PRIORITY,
1350                                         net_log_, CompletionCallback()));
1351
1352  // Add a cert and verify that stream saw the event.
1353  factory_.OnCertAdded(NULL);
1354  EXPECT_EQ(ERR_CERT_DATABASE_CHANGED,
1355            stream->ReadResponseHeaders(callback_.callback()));
1356  EXPECT_FALSE(factory_.require_confirmation());
1357
1358  // Now attempting to request a stream to the same origin should create
1359  // a new session.
1360
1361  QuicStreamRequest request2(&factory_);
1362  EXPECT_EQ(ERR_IO_PENDING,
1363            request2.Request(host_port_pair_,
1364                             is_https_,
1365                             privacy_mode_,
1366                             "GET",
1367                             net_log_,
1368                             callback_.callback()));
1369
1370  EXPECT_EQ(OK, callback_.WaitForResult());
1371  stream = request2.ReleaseStream();
1372  stream.reset();  // Will reset stream 3.
1373
1374  EXPECT_TRUE(socket_data.at_read_eof());
1375  EXPECT_TRUE(socket_data.at_write_eof());
1376  EXPECT_TRUE(socket_data2.at_read_eof());
1377  EXPECT_TRUE(socket_data2.at_write_eof());
1378}
1379
1380TEST_P(QuicStreamFactoryTest, OnCACertChanged) {
1381  MockRead reads[] = {
1382    MockRead(ASYNC, 0, 0)  // EOF
1383  };
1384  scoped_ptr<QuicEncryptedPacket> rst(ConstructRstPacket());
1385  std::vector<MockWrite> writes;
1386  writes.push_back(MockWrite(ASYNC, rst->data(), rst->length(), 1));
1387  DeterministicSocketData socket_data(reads, arraysize(reads),
1388                                      writes.empty() ? NULL  : &writes[0],
1389                                      writes.size());
1390  socket_factory_.AddSocketDataProvider(&socket_data);
1391  socket_data.StopAfter(1);
1392
1393  MockRead reads2[] = {
1394    MockRead(ASYNC, 0, 0)  // EOF
1395  };
1396  DeterministicSocketData socket_data2(reads2, arraysize(reads2), NULL, 0);
1397  socket_factory_.AddSocketDataProvider(&socket_data2);
1398  socket_data2.StopAfter(1);
1399
1400  QuicStreamRequest request(&factory_);
1401  EXPECT_EQ(ERR_IO_PENDING,
1402            request.Request(host_port_pair_,
1403                            is_https_,
1404                            privacy_mode_,
1405                            "GET",
1406                            net_log_,
1407                            callback_.callback()));
1408
1409  EXPECT_EQ(OK, callback_.WaitForResult());
1410  scoped_ptr<QuicHttpStream> stream = request.ReleaseStream();
1411  HttpRequestInfo request_info;
1412  EXPECT_EQ(OK, stream->InitializeStream(&request_info,
1413                                         DEFAULT_PRIORITY,
1414                                         net_log_, CompletionCallback()));
1415
1416  // Change the CA cert and verify that stream saw the event.
1417  factory_.OnCACertChanged(NULL);
1418  EXPECT_EQ(ERR_CERT_DATABASE_CHANGED,
1419            stream->ReadResponseHeaders(callback_.callback()));
1420  EXPECT_FALSE(factory_.require_confirmation());
1421
1422  // Now attempting to request a stream to the same origin should create
1423  // a new session.
1424
1425  QuicStreamRequest request2(&factory_);
1426  EXPECT_EQ(ERR_IO_PENDING,
1427            request2.Request(host_port_pair_,
1428                             is_https_,
1429                             privacy_mode_,
1430                             "GET",
1431                             net_log_,
1432                             callback_.callback()));
1433
1434  EXPECT_EQ(OK, callback_.WaitForResult());
1435  stream = request2.ReleaseStream();
1436  stream.reset();  // Will reset stream 3.
1437
1438  EXPECT_TRUE(socket_data.at_read_eof());
1439  EXPECT_TRUE(socket_data.at_write_eof());
1440  EXPECT_TRUE(socket_data2.at_read_eof());
1441  EXPECT_TRUE(socket_data2.at_write_eof());
1442}
1443
1444TEST_P(QuicStreamFactoryTest, SharedCryptoConfig) {
1445  vector<string> cannoncial_suffixes;
1446  cannoncial_suffixes.push_back(string(".c.youtube.com"));
1447  cannoncial_suffixes.push_back(string(".googlevideo.com"));
1448
1449  for (unsigned i = 0; i < cannoncial_suffixes.size(); ++i) {
1450    string r1_host_name("r1");
1451    string r2_host_name("r2");
1452    r1_host_name.append(cannoncial_suffixes[i]);
1453    r2_host_name.append(cannoncial_suffixes[i]);
1454
1455    HostPortPair host_port_pair1(r1_host_name, 80);
1456    QuicCryptoClientConfig* crypto_config =
1457        QuicStreamFactoryPeer::GetCryptoConfig(&factory_);
1458    QuicServerId server_id1(host_port_pair1, is_https_, privacy_mode_);
1459    QuicCryptoClientConfig::CachedState* cached1 =
1460        crypto_config->LookupOrCreate(server_id1);
1461    EXPECT_FALSE(cached1->proof_valid());
1462    EXPECT_TRUE(cached1->source_address_token().empty());
1463
1464    // Mutate the cached1 to have different data.
1465    // TODO(rtenneti): mutate other members of CachedState.
1466    cached1->set_source_address_token(r1_host_name);
1467    cached1->SetProofValid();
1468
1469    HostPortPair host_port_pair2(r2_host_name, 80);
1470    QuicServerId server_id2(host_port_pair2, is_https_, privacy_mode_);
1471    QuicCryptoClientConfig::CachedState* cached2 =
1472        crypto_config->LookupOrCreate(server_id2);
1473    EXPECT_EQ(cached1->source_address_token(), cached2->source_address_token());
1474    EXPECT_TRUE(cached2->proof_valid());
1475  }
1476}
1477
1478TEST_P(QuicStreamFactoryTest, CryptoConfigWhenProofIsInvalid) {
1479  vector<string> cannoncial_suffixes;
1480  cannoncial_suffixes.push_back(string(".c.youtube.com"));
1481  cannoncial_suffixes.push_back(string(".googlevideo.com"));
1482
1483  for (unsigned i = 0; i < cannoncial_suffixes.size(); ++i) {
1484    string r3_host_name("r3");
1485    string r4_host_name("r4");
1486    r3_host_name.append(cannoncial_suffixes[i]);
1487    r4_host_name.append(cannoncial_suffixes[i]);
1488
1489    HostPortPair host_port_pair1(r3_host_name, 80);
1490    QuicCryptoClientConfig* crypto_config =
1491        QuicStreamFactoryPeer::GetCryptoConfig(&factory_);
1492    QuicServerId server_id1(host_port_pair1, is_https_, privacy_mode_);
1493    QuicCryptoClientConfig::CachedState* cached1 =
1494        crypto_config->LookupOrCreate(server_id1);
1495    EXPECT_FALSE(cached1->proof_valid());
1496    EXPECT_TRUE(cached1->source_address_token().empty());
1497
1498    // Mutate the cached1 to have different data.
1499    // TODO(rtenneti): mutate other members of CachedState.
1500    cached1->set_source_address_token(r3_host_name);
1501    cached1->SetProofInvalid();
1502
1503    HostPortPair host_port_pair2(r4_host_name, 80);
1504    QuicServerId server_id2(host_port_pair2, is_https_, privacy_mode_);
1505    QuicCryptoClientConfig::CachedState* cached2 =
1506        crypto_config->LookupOrCreate(server_id2);
1507    EXPECT_NE(cached1->source_address_token(), cached2->source_address_token());
1508    EXPECT_TRUE(cached2->source_address_token().empty());
1509    EXPECT_FALSE(cached2->proof_valid());
1510  }
1511}
1512
1513}  // namespace test
1514}  // namespace net
1515