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/socket/transport_client_socket_pool.h"
6 
7 #include <utility>
8 
9 #include "base/bind.h"
10 #include "base/callback.h"
11 #include "base/callback_helpers.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/optional.h"
14 #include "base/run_loop.h"
15 #include "base/stl_util.h"
16 #include "base/test/bind.h"
17 #include "base/test/scoped_feature_list.h"
18 #include "base/threading/platform_thread.h"
19 #include "build/build_config.h"
20 #include "net/base/completion_once_callback.h"
21 #include "net/base/features.h"
22 #include "net/base/ip_endpoint.h"
23 #include "net/base/load_timing_info.h"
24 #include "net/base/load_timing_info_test_util.h"
25 #include "net/base/net_errors.h"
26 #include "net/base/privacy_mode.h"
27 #include "net/base/proxy_server.h"
28 #include "net/base/test_completion_callback.h"
29 #include "net/cert/ct_policy_enforcer.h"
30 #include "net/cert/mock_cert_verifier.h"
31 #include "net/dns/mock_host_resolver.h"
32 #include "net/dns/public/secure_dns_mode.h"
33 #include "net/http/http_network_session.h"
34 #include "net/http/http_proxy_connect_job.h"
35 #include "net/http/transport_security_state.h"
36 #include "net/log/net_log_with_source.h"
37 #include "net/log/test_net_log.h"
38 #include "net/proxy_resolution/configured_proxy_resolution_service.h"
39 #include "net/socket/client_socket_handle.h"
40 #include "net/socket/connect_job.h"
41 #include "net/socket/socket_tag.h"
42 #include "net/socket/socket_test_util.h"
43 #include "net/socket/socks_connect_job.h"
44 #include "net/socket/ssl_connect_job.h"
45 #include "net/socket/stream_socket.h"
46 #include "net/socket/transport_client_socket_pool.h"
47 #include "net/socket/transport_client_socket_pool_test_util.h"
48 #include "net/socket/transport_connect_job.h"
49 #include "net/spdy/spdy_test_util_common.h"
50 #include "net/ssl/ssl_config_service.h"
51 #include "net/test/embedded_test_server/embedded_test_server.h"
52 #include "net/test/gtest_util.h"
53 #include "net/test/test_with_task_environment.h"
54 #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
55 #include "testing/gmock/include/gmock/gmock.h"
56 #include "testing/gtest/include/gtest/gtest.h"
57 #include "url/gurl.h"
58 #include "url/origin.h"
59 
60 using net::test::IsError;
61 using net::test::IsOk;
62 
63 namespace net {
64 
65 namespace {
66 
67 const int kMaxSockets = 32;
68 const int kMaxSocketsPerGroup = 6;
69 constexpr base::TimeDelta kUnusedIdleSocketTimeout =
70     base::TimeDelta::FromSeconds(10);
71 const RequestPriority kDefaultPriority = LOW;
72 
73 class SOCKS5MockData {
74  public:
SOCKS5MockData(IoMode mode)75   explicit SOCKS5MockData(IoMode mode) {
76     writes_.reset(new MockWrite[2]);
77     writes_[0] =
78         MockWrite(mode, kSOCKS5GreetRequest, kSOCKS5GreetRequestLength);
79     writes_[1] = MockWrite(mode, kSOCKS5OkRequest, kSOCKS5OkRequestLength);
80 
81     reads_.reset(new MockRead[2]);
82     reads_[0] =
83         MockRead(mode, kSOCKS5GreetResponse, kSOCKS5GreetResponseLength);
84     reads_[1] = MockRead(mode, kSOCKS5OkResponse, kSOCKS5OkResponseLength);
85 
86     data_.reset(new StaticSocketDataProvider(
87         base::make_span(reads_.get(), 2), base::make_span(writes_.get(), 2)));
88   }
89 
data_provider()90   SocketDataProvider* data_provider() { return data_.get(); }
91 
92  private:
93   std::unique_ptr<StaticSocketDataProvider> data_;
94   std::unique_ptr<MockWrite[]> writes_;
95   std::unique_ptr<MockRead[]> reads_;
96 };
97 
98 class TransportClientSocketPoolTest : public ::testing::Test,
99                                       public WithTaskEnvironment {
100  protected:
101   // Constructor that allows mocking of the time.
TransportClientSocketPoolTest(base::test::TaskEnvironment::TimeSource time_source=base::test::TaskEnvironment::TimeSource::DEFAULT)102   explicit TransportClientSocketPoolTest(
103       base::test::TaskEnvironment::TimeSource time_source =
104           base::test::TaskEnvironment::TimeSource::DEFAULT)
105       : WithTaskEnvironment(time_source),
106         connect_backup_jobs_enabled_(
107             TransportClientSocketPool::set_connect_backup_jobs_enabled(true)),
108         group_id_(HostPortPair("www.google.com", 80),
109                   ClientSocketPool::SocketType::kHttp,
110                   PrivacyMode::PRIVACY_MODE_DISABLED,
111                   NetworkIsolationKey(),
112                   false /* disable_secure_dns */),
113         params_(ClientSocketPool::SocketParams::CreateForHttpForTesting()),
114         client_socket_factory_(&net_log_) {
115     std::unique_ptr<MockCertVerifier> cert_verifier =
116         std::make_unique<MockCertVerifier>();
117     cert_verifier->set_default_result(OK);
118     session_deps_.cert_verifier = std::move(cert_verifier);
119 
120     http_network_session_ =
121         SpdySessionDependencies::SpdyCreateSession(&session_deps_);
122 
123     common_connect_job_params_ = std::make_unique<CommonConnectJobParams>(
124         http_network_session_->CreateCommonConnectJobParams());
125     common_connect_job_params_->client_socket_factory = &client_socket_factory_;
126     pool_ = std::make_unique<TransportClientSocketPool>(
127         kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
128         ProxyServer::Direct(), false /* is_for_websockets */,
129         common_connect_job_params_.get());
130 
131     tagging_common_connect_job_params_ =
132         std::make_unique<CommonConnectJobParams>(
133             http_network_session_->CreateCommonConnectJobParams());
134     tagging_common_connect_job_params_->client_socket_factory =
135         &tagging_client_socket_factory_;
136     tagging_pool_ = std::make_unique<TransportClientSocketPool>(
137         kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
138         ProxyServer::Direct(), false /* is_for_websockets */,
139         tagging_common_connect_job_params_.get());
140 
141     common_connect_job_params_for_real_sockets_ =
142         std::make_unique<CommonConnectJobParams>(
143             http_network_session_->CreateCommonConnectJobParams());
144     common_connect_job_params_for_real_sockets_->client_socket_factory =
145         ClientSocketFactory::GetDefaultFactory();
146     pool_for_real_sockets_ = std::make_unique<TransportClientSocketPool>(
147         kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
148         ProxyServer::Direct(), false /* is_for_websockets */,
149         common_connect_job_params_for_real_sockets_.get());
150   }
151 
~TransportClientSocketPoolTest()152   ~TransportClientSocketPoolTest() override {
153     TransportClientSocketPool::set_connect_backup_jobs_enabled(
154         connect_backup_jobs_enabled_);
155   }
156 
StartRequest(const std::string & host_name,RequestPriority priority)157   int StartRequest(const std::string& host_name, RequestPriority priority) {
158     ClientSocketPool::GroupId group_id(
159         HostPortPair(host_name, 80), ClientSocketPool::SocketType::kHttp,
160         PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
161         false /* disable_secure_dns */);
162     return test_base_.StartRequestUsingPool(
163         pool_.get(), group_id, priority,
164         ClientSocketPool::RespectLimits::ENABLED,
165         ClientSocketPool::SocketParams::CreateForHttpForTesting());
166   }
167 
GetOrderOfRequest(size_t index)168   int GetOrderOfRequest(size_t index) {
169     return test_base_.GetOrderOfRequest(index);
170   }
171 
ReleaseOneConnection(ClientSocketPoolTest::KeepAlive keep_alive)172   bool ReleaseOneConnection(ClientSocketPoolTest::KeepAlive keep_alive) {
173     return test_base_.ReleaseOneConnection(keep_alive);
174   }
175 
ReleaseAllConnections(ClientSocketPoolTest::KeepAlive keep_alive)176   void ReleaseAllConnections(ClientSocketPoolTest::KeepAlive keep_alive) {
177     test_base_.ReleaseAllConnections(keep_alive);
178   }
179 
requests()180   std::vector<std::unique_ptr<TestSocketRequest>>* requests() {
181     return test_base_.requests();
182   }
completion_count() const183   size_t completion_count() const { return test_base_.completion_count(); }
184 
185   bool connect_backup_jobs_enabled_;
186   RecordingTestNetLog net_log_;
187 
188   // |group_id_| and |params_| correspond to the same group.
189   const ClientSocketPool::GroupId group_id_;
190   scoped_refptr<ClientSocketPool::SocketParams> params_;
191 
192   MockTransportClientSocketFactory client_socket_factory_;
193   MockTaggingClientSocketFactory tagging_client_socket_factory_;
194 
195   // None of these tests check SPDY behavior, but this is a convenient way to
196   // create most objects needed by the socket pools, as well as a SpdySession
197   // pool, which is required by HttpProxyConnectJobs when using an HTTPS proxy.
198   SpdySessionDependencies session_deps_;
199   // As with |session_deps_|, this is a convenient way to construct objects
200   // these tests depend on.
201   std::unique_ptr<HttpNetworkSession> http_network_session_;
202 
203   std::unique_ptr<CommonConnectJobParams> common_connect_job_params_;
204   std::unique_ptr<TransportClientSocketPool> pool_;
205 
206   // Just like |pool_|, except it uses a real MockTaggingClientSocketFactory
207   // instead of MockTransportClientSocketFactory.
208   std::unique_ptr<CommonConnectJobParams> tagging_common_connect_job_params_;
209   std::unique_ptr<TransportClientSocketPool> tagging_pool_;
210 
211   // Just like |pool_|, except it uses a real ClientSocketFactory instead of
212   // |client_socket_factory_|.
213   std::unique_ptr<CommonConnectJobParams>
214       common_connect_job_params_for_real_sockets_;
215   std::unique_ptr<TransportClientSocketPool> pool_for_real_sockets_;
216 
217   ClientSocketPoolTest test_base_;
218 
219  private:
220   DISALLOW_COPY_AND_ASSIGN(TransportClientSocketPoolTest);
221 };
222 
TEST_F(TransportClientSocketPoolTest,Basic)223 TEST_F(TransportClientSocketPoolTest, Basic) {
224   TestCompletionCallback callback;
225   ClientSocketHandle handle;
226   int rv =
227       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
228                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
229                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
230                   pool_.get(), NetLogWithSource());
231   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
232   EXPECT_FALSE(handle.is_initialized());
233   EXPECT_FALSE(handle.socket());
234 
235   EXPECT_THAT(callback.WaitForResult(), IsOk());
236   EXPECT_TRUE(handle.is_initialized());
237   EXPECT_TRUE(handle.socket());
238   TestLoadTimingInfoConnectedNotReused(handle);
239   EXPECT_EQ(0u, handle.connection_attempts().size());
240 }
241 
242 // Make sure that TransportConnectJob passes on its priority to its
243 // HostResolver request on Init.
TEST_F(TransportClientSocketPoolTest,SetResolvePriorityOnInit)244 TEST_F(TransportClientSocketPoolTest, SetResolvePriorityOnInit) {
245   for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
246     RequestPriority priority = static_cast<RequestPriority>(i);
247     TestCompletionCallback callback;
248     ClientSocketHandle handle;
249     EXPECT_EQ(
250         ERR_IO_PENDING,
251         handle.Init(group_id_, params_,
252                     base::nullopt /* proxy_annotation_tag */, priority,
253                     SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
254                     callback.callback(), ClientSocketPool::ProxyAuthCallback(),
255                     pool_.get(), NetLogWithSource()));
256     EXPECT_EQ(priority, session_deps_.host_resolver->last_request_priority());
257   }
258 }
259 
TEST_F(TransportClientSocketPoolTest,SetDisableSecureDns)260 TEST_F(TransportClientSocketPoolTest, SetDisableSecureDns) {
261   for (bool disable_secure_dns : {false, true}) {
262     TestCompletionCallback callback;
263     ClientSocketHandle handle;
264     ClientSocketPool::GroupId group_id(
265         HostPortPair("www.google.com", 80), ClientSocketPool::SocketType::kHttp,
266         PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
267         disable_secure_dns);
268     EXPECT_EQ(
269         ERR_IO_PENDING,
270         handle.Init(group_id, params_, base::nullopt /* proxy_annotation_tag */,
271                     LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
272                     callback.callback(), ClientSocketPool::ProxyAuthCallback(),
273                     pool_.get(), NetLogWithSource()));
274     EXPECT_EQ(disable_secure_dns,
275               session_deps_.host_resolver->last_secure_dns_mode_override()
276                   .has_value());
277     if (disable_secure_dns) {
278       EXPECT_EQ(
279           net::SecureDnsMode::kOff,
280           session_deps_.host_resolver->last_secure_dns_mode_override().value());
281     }
282   }
283 }
284 
TEST_F(TransportClientSocketPoolTest,ReprioritizeRequests)285 TEST_F(TransportClientSocketPoolTest, ReprioritizeRequests) {
286   session_deps_.host_resolver->set_ondemand_mode(true);
287 
288   TestCompletionCallback callback1;
289   ClientSocketHandle handle1;
290   int rv1 =
291       handle1.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
292                    LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
293                    callback1.callback(), ClientSocketPool::ProxyAuthCallback(),
294                    pool_.get(), NetLogWithSource());
295   EXPECT_THAT(rv1, IsError(ERR_IO_PENDING));
296 
297   TestCompletionCallback callback2;
298   ClientSocketHandle handle2;
299   int rv2 = handle2.Init(
300       group_id_, params_, base::nullopt /* proxy_annotation_tag */, HIGHEST,
301       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
302       callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
303       NetLogWithSource());
304   EXPECT_THAT(rv2, IsError(ERR_IO_PENDING));
305 
306   TestCompletionCallback callback3;
307   ClientSocketHandle handle3;
308   int rv3 = handle3.Init(
309       group_id_, params_, base::nullopt /* proxy_annotation_tag */, LOWEST,
310       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
311       callback3.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
312       NetLogWithSource());
313   EXPECT_THAT(rv3, IsError(ERR_IO_PENDING));
314 
315   TestCompletionCallback callback4;
316   ClientSocketHandle handle4;
317   int rv4 = handle4.Init(
318       group_id_, params_, base::nullopt /* proxy_annotation_tag */, MEDIUM,
319       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
320       callback4.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
321       NetLogWithSource());
322   EXPECT_THAT(rv4, IsError(ERR_IO_PENDING));
323 
324   TestCompletionCallback callback5;
325   ClientSocketHandle handle5;
326   int rv5 = handle5.Init(
327       group_id_, params_, base::nullopt /* proxy_annotation_tag */, HIGHEST,
328       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
329       callback5.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
330       NetLogWithSource());
331   EXPECT_THAT(rv5, IsError(ERR_IO_PENDING));
332 
333   TestCompletionCallback callback6;
334   ClientSocketHandle handle6;
335   int rv6 =
336       handle6.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
337                    LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
338                    callback6.callback(), ClientSocketPool::ProxyAuthCallback(),
339                    pool_.get(), NetLogWithSource());
340   EXPECT_THAT(rv6, IsError(ERR_IO_PENDING));
341 
342   // New jobs are created for each of the first 6 requests with the
343   // corresponding priority.
344   //
345   // Queue of pending requests:
346   // Request  Job  Priority
347   // =======  ===  ========
348   //    2      2   HIGHEST
349   //    5      5   HIGHEST
350   //    4      4   MEDIUM
351   //    1      1   LOW
352   //    6      6   LOW
353   //    3      3   LOWEST
354   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
355   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(2));
356   EXPECT_EQ(LOWEST, session_deps_.host_resolver->request_priority(3));
357   EXPECT_EQ(MEDIUM, session_deps_.host_resolver->request_priority(4));
358   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(5));
359   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(6));
360 
361   // Inserting a highest-priority request steals the job from the lowest
362   // priority request and reprioritizes it to match the new request.
363   TestCompletionCallback callback7;
364   ClientSocketHandle handle7;
365   int rv7 = handle7.Init(
366       group_id_, params_, base::nullopt /* proxy_annotation_tag */, HIGHEST,
367       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
368       callback7.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
369       NetLogWithSource());
370   EXPECT_THAT(rv7, IsError(ERR_IO_PENDING));
371   // Request  Job  Priority
372   // =======  ===  ========
373   //    2      2   HIGHEST
374   //    5      5   HIGHEST
375   //    7      3   HIGHEST
376   //    4      4   MEDIUM
377   //    1      1   LOW
378   //    6      6   LOW
379   //    3          LOWEST
380   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
381   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(2));
382   EXPECT_EQ(HIGHEST,
383             session_deps_.host_resolver->request_priority(3));  // reprioritized
384   EXPECT_EQ(MEDIUM, session_deps_.host_resolver->request_priority(4));
385   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(5));
386   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(6));
387 
388   TestCompletionCallback callback8;
389   ClientSocketHandle handle8;
390   int rv8 = handle8.Init(
391       group_id_, params_, base::nullopt /* proxy_annotation_tag */, HIGHEST,
392       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
393       callback8.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
394       NetLogWithSource());
395   EXPECT_THAT(rv8, IsError(ERR_IO_PENDING));
396   // Request  Job  Priority
397   // =======  ===  ========
398   //    2      2   HIGHEST
399   //    5      5   HIGHEST
400   //    7      3   HIGHEST
401   //    8      6   HIGHEST
402   //    4      4   MEDIUM
403   //    1      1   LOW
404   //    6          LOW
405   //    3          LOWEST
406   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
407   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(2));
408   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(3));
409   EXPECT_EQ(MEDIUM, session_deps_.host_resolver->request_priority(4));
410   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(5));
411   EXPECT_EQ(HIGHEST,
412             session_deps_.host_resolver->request_priority(6));  // reprioritized
413 
414   // A request completes, then the socket is returned to the socket pool and
415   // goes to the highest remaining request. The job from the highest request
416   // should then be reassigned to the first request without a job.
417   session_deps_.host_resolver->ResolveNow(2);
418   EXPECT_THAT(callback2.WaitForResult(), IsOk());
419   EXPECT_TRUE(handle2.is_initialized());
420   EXPECT_TRUE(handle2.socket());
421   handle2.Reset();
422   EXPECT_THAT(callback5.WaitForResult(), IsOk());
423   EXPECT_TRUE(handle5.is_initialized());
424   EXPECT_TRUE(handle5.socket());
425   // Request  Job  Priority
426   // =======  ===  ========
427   //    7      3   HIGHEST
428   //    8      6   HIGHEST
429   //    4      4   MEDIUM
430   //    1      1   LOW
431   //    6      5   LOW
432   //    3          LOWEST
433   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
434   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(3));
435   EXPECT_EQ(MEDIUM, session_deps_.host_resolver->request_priority(4));
436   EXPECT_EQ(LOW,
437             session_deps_.host_resolver->request_priority(5));  // reprioritized
438   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(6));
439 
440   // Cancelling a request with a job reassigns the job to a lower request.
441   handle7.Reset();
442   // Request  Job  Priority
443   // =======  ===  ========
444   //    8      6   HIGHEST
445   //    4      4   MEDIUM
446   //    1      1   LOW
447   //    6      5   LOW
448   //    3      3   LOWEST
449   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
450   EXPECT_EQ(LOWEST,
451             session_deps_.host_resolver->request_priority(3));  // reprioritized
452   EXPECT_EQ(MEDIUM, session_deps_.host_resolver->request_priority(4));
453   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(5));
454   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(6));
455 
456   // Reprioritizing a request changes its job's priority.
457   pool_->SetPriority(group_id_, &handle4, LOWEST);
458   // Request  Job  Priority
459   // =======  ===  ========
460   //    8      6   HIGHEST
461   //    1      1   LOW
462   //    6      5   LOW
463   //    3      3   LOWEST
464   //    4      4   LOWEST
465   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
466   EXPECT_EQ(LOWEST, session_deps_.host_resolver->request_priority(3));
467   EXPECT_EQ(LOWEST,
468             session_deps_.host_resolver->request_priority(4));  // reprioritized
469   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(5));
470   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(6));
471 
472   pool_->SetPriority(group_id_, &handle3, MEDIUM);
473   // Request  Job  Priority
474   // =======  ===  ========
475   //    8      6   HIGHEST
476   //    3      3   MEDIUM
477   //    1      1   LOW
478   //    6      5   LOW
479   //    4      4   LOWEST
480   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
481   EXPECT_EQ(MEDIUM,
482             session_deps_.host_resolver->request_priority(3));  // reprioritized
483   EXPECT_EQ(LOWEST, session_deps_.host_resolver->request_priority(4));
484   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(5));
485   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(6));
486 
487   // Host resolution finishes for a lower-down request. The highest request
488   // should get the socket and its job should be reassigned to the lower
489   // request.
490   session_deps_.host_resolver->ResolveNow(1);
491   EXPECT_THAT(callback8.WaitForResult(), IsOk());
492   EXPECT_TRUE(handle8.is_initialized());
493   EXPECT_TRUE(handle8.socket());
494   // Request  Job  Priority
495   // =======  ===  ========
496   //    3      3   MEDIUM
497   //    1      6   LOW
498   //    6      5   LOW
499   //    4      4   LOWEST
500   EXPECT_EQ(MEDIUM, session_deps_.host_resolver->request_priority(3));
501   EXPECT_EQ(LOWEST, session_deps_.host_resolver->request_priority(4));
502   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(5));
503   EXPECT_EQ(LOW,
504             session_deps_.host_resolver->request_priority(6));  // reprioritized
505 
506   // Host resolution finishes for the highest request. Nothing gets
507   // reprioritized.
508   session_deps_.host_resolver->ResolveNow(3);
509   EXPECT_THAT(callback3.WaitForResult(), IsOk());
510   EXPECT_TRUE(handle3.is_initialized());
511   EXPECT_TRUE(handle3.socket());
512   // Request  Job  Priority
513   // =======  ===  ========
514   //    1      6   LOW
515   //    6      5   LOW
516   //    4      4   LOWEST
517   EXPECT_EQ(LOWEST, session_deps_.host_resolver->request_priority(4));
518   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(5));
519   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(6));
520 
521   session_deps_.host_resolver->ResolveAllPending();
522   EXPECT_THAT(callback1.WaitForResult(), IsOk());
523   EXPECT_TRUE(handle1.is_initialized());
524   EXPECT_TRUE(handle1.socket());
525   EXPECT_THAT(callback4.WaitForResult(), IsOk());
526   EXPECT_TRUE(handle4.is_initialized());
527   EXPECT_TRUE(handle4.socket());
528   EXPECT_THAT(callback6.WaitForResult(), IsOk());
529   EXPECT_TRUE(handle6.is_initialized());
530   EXPECT_TRUE(handle6.socket());
531 }
532 
TEST_F(TransportClientSocketPoolTest,RequestIgnoringLimitsIsReprioritized)533 TEST_F(TransportClientSocketPoolTest, RequestIgnoringLimitsIsReprioritized) {
534   TransportClientSocketPool pool(
535       kMaxSockets, 1, kUnusedIdleSocketTimeout, ProxyServer::Direct(),
536       false /* is_for_websockets */, common_connect_job_params_.get());
537 
538   // Creates a job which ignores limits whose priority is MAXIMUM_PRIORITY.
539   TestCompletionCallback callback1;
540   ClientSocketHandle handle1;
541   int rv1 = handle1.Init(
542       group_id_, params_, base::nullopt /* proxy_annotation_tag */,
543       MAXIMUM_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::DISABLED,
544       callback1.callback(), ClientSocketPool::ProxyAuthCallback(), &pool,
545       NetLogWithSource());
546   EXPECT_THAT(rv1, IsError(ERR_IO_PENDING));
547 
548   EXPECT_EQ(MAXIMUM_PRIORITY, session_deps_.host_resolver->request_priority(1));
549 
550   TestCompletionCallback callback2;
551   ClientSocketHandle handle2;
552   int rv2 =
553       handle2.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
554                    LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
555                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
556                    &pool, NetLogWithSource());
557   EXPECT_THAT(rv2, IsError(ERR_IO_PENDING));
558 
559   // |handle2| gets assigned the job, which is reprioritized.
560   handle1.Reset();
561   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
562 }
563 
TEST_F(TransportClientSocketPoolTest,InitHostResolutionFailure)564 TEST_F(TransportClientSocketPoolTest, InitHostResolutionFailure) {
565   session_deps_.host_resolver->rules()->AddSimulatedTimeoutFailure(
566       group_id_.destination().host());
567   TestCompletionCallback callback;
568   ClientSocketHandle handle;
569   EXPECT_EQ(
570       ERR_IO_PENDING,
571       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
572                   kDefaultPriority, SocketTag(),
573                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
574                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
575                   NetLogWithSource()));
576   EXPECT_THAT(callback.WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED));
577   EXPECT_THAT(handle.resolve_error_info().error, IsError(ERR_DNS_TIMED_OUT));
578   ASSERT_EQ(1u, handle.connection_attempts().size());
579   EXPECT_TRUE(handle.connection_attempts()[0].endpoint.address().empty());
580   EXPECT_THAT(handle.connection_attempts()[0].result,
581               IsError(ERR_NAME_NOT_RESOLVED));
582 }
583 
TEST_F(TransportClientSocketPoolTest,InitConnectionFailure)584 TEST_F(TransportClientSocketPoolTest, InitConnectionFailure) {
585   client_socket_factory_.set_default_client_socket_type(
586       MockTransportClientSocketFactory::MOCK_FAILING_CLIENT_SOCKET);
587   TestCompletionCallback callback;
588   ClientSocketHandle handle;
589   EXPECT_EQ(
590       ERR_IO_PENDING,
591       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
592                   kDefaultPriority, SocketTag(),
593                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
594                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
595                   NetLogWithSource()));
596   EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CONNECTION_FAILED));
597   ASSERT_EQ(1u, handle.connection_attempts().size());
598   EXPECT_EQ("127.0.0.1:80",
599             handle.connection_attempts()[0].endpoint.ToString());
600   EXPECT_THAT(handle.connection_attempts()[0].result,
601               IsError(ERR_CONNECTION_FAILED));
602 
603   // Make the host resolutions complete synchronously this time.
604   session_deps_.host_resolver->set_synchronous_mode(true);
605   EXPECT_EQ(
606       ERR_CONNECTION_FAILED,
607       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
608                   kDefaultPriority, SocketTag(),
609                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
610                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
611                   NetLogWithSource()));
612   ASSERT_EQ(1u, handle.connection_attempts().size());
613   EXPECT_EQ("127.0.0.1:80",
614             handle.connection_attempts()[0].endpoint.ToString());
615   EXPECT_THAT(handle.connection_attempts()[0].result,
616               IsError(ERR_CONNECTION_FAILED));
617 }
618 
TEST_F(TransportClientSocketPoolTest,PendingRequests)619 TEST_F(TransportClientSocketPoolTest, PendingRequests) {
620   // First request finishes asynchronously.
621   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
622   EXPECT_THAT((*requests())[0]->WaitForResult(), IsOk());
623 
624   // Make all subsequent host resolutions complete synchronously.
625   session_deps_.host_resolver->set_synchronous_mode(true);
626 
627   // Rest of them finish synchronously, until we reach the per-group limit.
628   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
629   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
630   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
631   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
632   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
633 
634   // The rest are pending since we've used all active sockets.
635   EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING));
636   EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING));
637   EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING));
638   EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING));
639   EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING));
640   EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING));
641   EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING));
642   EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING));
643   EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING));
644   EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING));
645 
646   ReleaseAllConnections(ClientSocketPoolTest::KEEP_ALIVE);
647 
648   EXPECT_EQ(kMaxSocketsPerGroup, client_socket_factory_.allocation_count());
649 
650   // One initial asynchronous request and then 10 pending requests.
651   EXPECT_EQ(11U, completion_count());
652 
653   // First part of requests, all with the same priority, finishes in FIFO order.
654   EXPECT_EQ(1, GetOrderOfRequest(1));
655   EXPECT_EQ(2, GetOrderOfRequest(2));
656   EXPECT_EQ(3, GetOrderOfRequest(3));
657   EXPECT_EQ(4, GetOrderOfRequest(4));
658   EXPECT_EQ(5, GetOrderOfRequest(5));
659   EXPECT_EQ(6, GetOrderOfRequest(6));
660 
661   // Make sure that rest of the requests complete in the order of priority.
662   EXPECT_EQ(7, GetOrderOfRequest(7));
663   EXPECT_EQ(14, GetOrderOfRequest(8));
664   EXPECT_EQ(15, GetOrderOfRequest(9));
665   EXPECT_EQ(10, GetOrderOfRequest(10));
666   EXPECT_EQ(13, GetOrderOfRequest(11));
667   EXPECT_EQ(8, GetOrderOfRequest(12));
668   EXPECT_EQ(16, GetOrderOfRequest(13));
669   EXPECT_EQ(11, GetOrderOfRequest(14));
670   EXPECT_EQ(12, GetOrderOfRequest(15));
671   EXPECT_EQ(9, GetOrderOfRequest(16));
672 
673   // Make sure we test order of all requests made.
674   EXPECT_EQ(ClientSocketPoolTest::kIndexOutOfBounds, GetOrderOfRequest(17));
675 }
676 
TEST_F(TransportClientSocketPoolTest,PendingRequests_NoKeepAlive)677 TEST_F(TransportClientSocketPoolTest, PendingRequests_NoKeepAlive) {
678   // First request finishes asynchronously.
679   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
680   EXPECT_THAT((*requests())[0]->WaitForResult(), IsOk());
681 
682   // Make all subsequent host resolutions complete synchronously.
683   session_deps_.host_resolver->set_synchronous_mode(true);
684 
685   // Rest of them finish synchronously, until we reach the per-group limit.
686   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
687   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
688   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
689   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
690   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
691 
692   // The rest are pending since we've used all active sockets.
693   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
694   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
695   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
696   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
697   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
698 
699   ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE);
700 
701   // The pending requests should finish successfully.
702   EXPECT_THAT((*requests())[6]->WaitForResult(), IsOk());
703   EXPECT_THAT((*requests())[7]->WaitForResult(), IsOk());
704   EXPECT_THAT((*requests())[8]->WaitForResult(), IsOk());
705   EXPECT_THAT((*requests())[9]->WaitForResult(), IsOk());
706   EXPECT_THAT((*requests())[10]->WaitForResult(), IsOk());
707 
708   EXPECT_EQ(static_cast<int>(requests()->size()),
709             client_socket_factory_.allocation_count());
710 
711   // First asynchronous request, and then last 5 pending requests.
712   EXPECT_EQ(6U, completion_count());
713 }
714 
715 // This test will start up a RequestSocket() and then immediately Cancel() it.
716 // The pending host resolution will eventually complete, and destroy the
717 // ClientSocketPool which will crash if the group was not cleared properly.
TEST_F(TransportClientSocketPoolTest,CancelRequestClearGroup)718 TEST_F(TransportClientSocketPoolTest, CancelRequestClearGroup) {
719   TestCompletionCallback callback;
720   ClientSocketHandle handle;
721   EXPECT_EQ(
722       ERR_IO_PENDING,
723       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
724                   kDefaultPriority, SocketTag(),
725                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
726                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
727                   NetLogWithSource()));
728   handle.Reset();
729 }
730 
TEST_F(TransportClientSocketPoolTest,TwoRequestsCancelOne)731 TEST_F(TransportClientSocketPoolTest, TwoRequestsCancelOne) {
732   ClientSocketHandle handle;
733   TestCompletionCallback callback;
734   ClientSocketHandle handle2;
735   TestCompletionCallback callback2;
736 
737   EXPECT_EQ(
738       ERR_IO_PENDING,
739       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
740                   kDefaultPriority, SocketTag(),
741                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
742                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
743                   NetLogWithSource()));
744   EXPECT_EQ(
745       ERR_IO_PENDING,
746       handle2.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
747                    kDefaultPriority, SocketTag(),
748                    ClientSocketPool::RespectLimits::ENABLED,
749                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
750                    pool_.get(), NetLogWithSource()));
751 
752   handle.Reset();
753 
754   EXPECT_THAT(callback2.WaitForResult(), IsOk());
755   handle2.Reset();
756 }
757 
TEST_F(TransportClientSocketPoolTest,ConnectCancelConnect)758 TEST_F(TransportClientSocketPoolTest, ConnectCancelConnect) {
759   client_socket_factory_.set_default_client_socket_type(
760       MockTransportClientSocketFactory::MOCK_PENDING_CLIENT_SOCKET);
761   ClientSocketHandle handle;
762   TestCompletionCallback callback;
763   EXPECT_EQ(
764       ERR_IO_PENDING,
765       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
766                   kDefaultPriority, SocketTag(),
767                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
768                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
769                   NetLogWithSource()));
770 
771   handle.Reset();
772 
773   TestCompletionCallback callback2;
774   EXPECT_EQ(
775       ERR_IO_PENDING,
776       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
777                   kDefaultPriority, SocketTag(),
778                   ClientSocketPool::RespectLimits::ENABLED,
779                   callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
780                   pool_.get(), NetLogWithSource()));
781 
782   session_deps_.host_resolver->set_synchronous_mode(true);
783   // At this point, handle has two ConnectingSockets out for it.  Due to the
784   // setting the mock resolver into synchronous mode, the host resolution for
785   // both will return in the same loop of the MessageLoop.  The client socket
786   // is a pending socket, so the Connect() will asynchronously complete on the
787   // next loop of the MessageLoop.  That means that the first
788   // ConnectingSocket will enter OnIOComplete, and then the second one will.
789   // If the first one is not cancelled, it will advance the load state, and
790   // then the second one will crash.
791 
792   EXPECT_THAT(callback2.WaitForResult(), IsOk());
793   EXPECT_FALSE(callback.have_result());
794 
795   handle.Reset();
796 }
797 
TEST_F(TransportClientSocketPoolTest,CancelRequest)798 TEST_F(TransportClientSocketPoolTest, CancelRequest) {
799   // First request finishes asynchronously.
800   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
801   EXPECT_THAT((*requests())[0]->WaitForResult(), IsOk());
802 
803   // Make all subsequent host resolutions complete synchronously.
804   session_deps_.host_resolver->set_synchronous_mode(true);
805 
806   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
807   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
808   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
809   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
810   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
811 
812   // Reached per-group limit, queue up requests.
813   EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING));
814   EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING));
815   EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING));
816   EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING));
817   EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING));
818   EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING));
819   EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING));
820   EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING));
821   EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING));
822   EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING));
823 
824   // Cancel a request.
825   size_t index_to_cancel = kMaxSocketsPerGroup + 2;
826   EXPECT_FALSE((*requests())[index_to_cancel]->handle()->is_initialized());
827   (*requests())[index_to_cancel]->handle()->Reset();
828 
829   ReleaseAllConnections(ClientSocketPoolTest::KEEP_ALIVE);
830 
831   EXPECT_EQ(kMaxSocketsPerGroup,
832             client_socket_factory_.allocation_count());
833   EXPECT_EQ(requests()->size() - kMaxSocketsPerGroup, completion_count());
834 
835   EXPECT_EQ(1, GetOrderOfRequest(1));
836   EXPECT_EQ(2, GetOrderOfRequest(2));
837   EXPECT_EQ(3, GetOrderOfRequest(3));
838   EXPECT_EQ(4, GetOrderOfRequest(4));
839   EXPECT_EQ(5, GetOrderOfRequest(5));
840   EXPECT_EQ(6, GetOrderOfRequest(6));
841   EXPECT_EQ(14, GetOrderOfRequest(7));
842   EXPECT_EQ(7, GetOrderOfRequest(8));
843   EXPECT_EQ(ClientSocketPoolTest::kRequestNotFound,
844             GetOrderOfRequest(9));  // Canceled request.
845   EXPECT_EQ(9, GetOrderOfRequest(10));
846   EXPECT_EQ(10, GetOrderOfRequest(11));
847   EXPECT_EQ(11, GetOrderOfRequest(12));
848   EXPECT_EQ(8, GetOrderOfRequest(13));
849   EXPECT_EQ(12, GetOrderOfRequest(14));
850   EXPECT_EQ(13, GetOrderOfRequest(15));
851   EXPECT_EQ(15, GetOrderOfRequest(16));
852 
853   // Make sure we test order of all requests made.
854   EXPECT_EQ(ClientSocketPoolTest::kIndexOutOfBounds, GetOrderOfRequest(17));
855 }
856 
857 class RequestSocketCallback : public TestCompletionCallbackBase {
858  public:
RequestSocketCallback(const ClientSocketPool::GroupId & group_id,scoped_refptr<ClientSocketPool::SocketParams> socket_params,ClientSocketHandle * handle,TransportClientSocketPool * pool)859   RequestSocketCallback(
860       const ClientSocketPool::GroupId& group_id,
861       scoped_refptr<ClientSocketPool::SocketParams> socket_params,
862       ClientSocketHandle* handle,
863       TransportClientSocketPool* pool)
864       : group_id_(group_id),
865         socket_params_(socket_params),
866         handle_(handle),
867         pool_(pool),
868         within_callback_(false) {}
869 
870   ~RequestSocketCallback() override = default;
871 
callback()872   CompletionOnceCallback callback() {
873     return base::BindOnce(&RequestSocketCallback::OnComplete,
874                           base::Unretained(this));
875   }
876 
877  private:
OnComplete(int result)878   void OnComplete(int result) {
879     SetResult(result);
880     ASSERT_THAT(result, IsOk());
881 
882     if (!within_callback_) {
883       // Don't allow reuse of the socket.  Disconnect it and then release it and
884       // run through the MessageLoop once to get it completely released.
885       handle_->socket()->Disconnect();
886       handle_->Reset();
887       base::RunLoop(base::RunLoop::Type::kNestableTasksAllowed).RunUntilIdle();
888       within_callback_ = true;
889       int rv = handle_->Init(
890           group_id_, socket_params_, base::nullopt /* proxy_annotation_tag */,
891           LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
892           callback(), ClientSocketPool::ProxyAuthCallback(), pool_,
893           NetLogWithSource());
894       EXPECT_THAT(rv, IsOk());
895     }
896   }
897 
898   const ClientSocketPool::GroupId group_id_;
899   scoped_refptr<ClientSocketPool::SocketParams> socket_params_;
900   ClientSocketHandle* const handle_;
901   TransportClientSocketPool* const pool_;
902   bool within_callback_;
903 
904   DISALLOW_COPY_AND_ASSIGN(RequestSocketCallback);
905 };
906 
TEST_F(TransportClientSocketPoolTest,RequestTwice)907 TEST_F(TransportClientSocketPoolTest, RequestTwice) {
908   ClientSocketHandle handle;
909   RequestSocketCallback callback(group_id_, params_, &handle, pool_.get());
910   int rv =
911       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
912                   LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
913                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
914                   pool_.get(), NetLogWithSource());
915   ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
916 
917   // The callback is going to request "www.google.com". We want it to complete
918   // synchronously this time.
919   session_deps_.host_resolver->set_synchronous_mode(true);
920 
921   EXPECT_THAT(callback.WaitForResult(), IsOk());
922 
923   handle.Reset();
924 }
925 
926 // Make sure that pending requests get serviced after active requests get
927 // cancelled.
TEST_F(TransportClientSocketPoolTest,CancelActiveRequestWithPendingRequests)928 TEST_F(TransportClientSocketPoolTest, CancelActiveRequestWithPendingRequests) {
929   client_socket_factory_.set_default_client_socket_type(
930       MockTransportClientSocketFactory::MOCK_PENDING_CLIENT_SOCKET);
931 
932   // Queue up all the requests
933   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
934   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
935   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
936   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
937   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
938   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
939   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
940   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
941   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
942 
943   // Now, kMaxSocketsPerGroup requests should be active.  Let's cancel them.
944   ASSERT_LE(kMaxSocketsPerGroup, static_cast<int>(requests()->size()));
945   for (int i = 0; i < kMaxSocketsPerGroup; i++)
946     (*requests())[i]->handle()->Reset();
947 
948   // Let's wait for the rest to complete now.
949   for (size_t i = kMaxSocketsPerGroup; i < requests()->size(); ++i) {
950     EXPECT_THAT((*requests())[i]->WaitForResult(), IsOk());
951     (*requests())[i]->handle()->Reset();
952   }
953 
954   EXPECT_EQ(requests()->size() - kMaxSocketsPerGroup, completion_count());
955 }
956 
957 // Make sure that pending requests get serviced after active requests fail.
TEST_F(TransportClientSocketPoolTest,FailingActiveRequestWithPendingRequests)958 TEST_F(TransportClientSocketPoolTest, FailingActiveRequestWithPendingRequests) {
959   client_socket_factory_.set_default_client_socket_type(
960       MockTransportClientSocketFactory::MOCK_PENDING_FAILING_CLIENT_SOCKET);
961 
962   const int kNumRequests = 2 * kMaxSocketsPerGroup + 1;
963   ASSERT_LE(kNumRequests, kMaxSockets);  // Otherwise the test will hang.
964 
965   // Queue up all the requests
966   for (int i = 0; i < kNumRequests; i++)
967     EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
968 
969   for (int i = 0; i < kNumRequests; i++)
970     EXPECT_THAT((*requests())[i]->WaitForResult(),
971                 IsError(ERR_CONNECTION_FAILED));
972 }
973 
TEST_F(TransportClientSocketPoolTest,IdleSocketLoadTiming)974 TEST_F(TransportClientSocketPoolTest, IdleSocketLoadTiming) {
975   TestCompletionCallback callback;
976   ClientSocketHandle handle;
977   int rv =
978       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
979                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
980                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
981                   pool_.get(), NetLogWithSource());
982   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
983   EXPECT_FALSE(handle.is_initialized());
984   EXPECT_FALSE(handle.socket());
985 
986   EXPECT_THAT(callback.WaitForResult(), IsOk());
987   EXPECT_TRUE(handle.is_initialized());
988   EXPECT_TRUE(handle.socket());
989   TestLoadTimingInfoConnectedNotReused(handle);
990 
991   handle.Reset();
992   // Need to run all pending to release the socket back to the pool.
993   base::RunLoop().RunUntilIdle();
994 
995   // Now we should have 1 idle socket.
996   EXPECT_EQ(1, pool_->IdleSocketCount());
997 
998   rv = handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
999                    LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1000                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1001                    pool_.get(), NetLogWithSource());
1002   EXPECT_THAT(rv, IsOk());
1003   EXPECT_EQ(0, pool_->IdleSocketCount());
1004   TestLoadTimingInfoConnectedReused(handle);
1005 }
1006 
TEST_F(TransportClientSocketPoolTest,CloseIdleSocketsOnIPAddressChange)1007 TEST_F(TransportClientSocketPoolTest, CloseIdleSocketsOnIPAddressChange) {
1008   TestCompletionCallback callback;
1009   ClientSocketHandle handle;
1010   int rv =
1011       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
1012                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1013                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1014                   pool_.get(), NetLogWithSource());
1015   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1016   EXPECT_FALSE(handle.is_initialized());
1017   EXPECT_FALSE(handle.socket());
1018 
1019   EXPECT_THAT(callback.WaitForResult(), IsOk());
1020   EXPECT_TRUE(handle.is_initialized());
1021   EXPECT_TRUE(handle.socket());
1022 
1023   handle.Reset();
1024 
1025   // Need to run all pending to release the socket back to the pool.
1026   base::RunLoop().RunUntilIdle();
1027 
1028   // Now we should have 1 idle socket.
1029   EXPECT_EQ(1, pool_->IdleSocketCount());
1030 
1031   // After an IP address change, we should have 0 idle sockets.
1032   NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1033   base::RunLoop().RunUntilIdle();  // Notification happens async.
1034 
1035   EXPECT_EQ(0, pool_->IdleSocketCount());
1036 }
1037 
TEST_F(TransportClientSocketPoolTest,SSLCertError)1038 TEST_F(TransportClientSocketPoolTest, SSLCertError) {
1039   StaticSocketDataProvider data;
1040   tagging_client_socket_factory_.AddSocketDataProvider(&data);
1041   SSLSocketDataProvider ssl(ASYNC, ERR_CERT_COMMON_NAME_INVALID);
1042   tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl);
1043 
1044   const HostPortPair kHostPortPair("ssl.server.test", 443);
1045 
1046   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
1047       base::MakeRefCounted<ClientSocketPool::SocketParams>(
1048           std::make_unique<SSLConfig>() /* ssl_config_for_origin */,
1049           nullptr /* ssl_config_for_proxy */);
1050 
1051   ClientSocketHandle handle;
1052   TestCompletionCallback callback;
1053   int rv =
1054       handle.Init(ClientSocketPool::GroupId(
1055                       kHostPortPair, ClientSocketPool::SocketType::kSsl,
1056                       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
1057                       false /* disable_secure_dns */),
1058                   socket_params, base::nullopt /* proxy_annotation_tag */,
1059                   MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1060                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1061                   tagging_pool_.get(), NetLogWithSource());
1062   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1063   EXPECT_FALSE(handle.is_initialized());
1064   EXPECT_FALSE(handle.socket());
1065 
1066   EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CERT_COMMON_NAME_INVALID));
1067   EXPECT_TRUE(handle.is_initialized());
1068   EXPECT_TRUE(handle.socket());
1069 }
1070 
TEST_F(TransportClientSocketPoolTest,CloseIdleSocketsOnSSLConfigChange)1071 TEST_F(TransportClientSocketPoolTest, CloseIdleSocketsOnSSLConfigChange) {
1072   TestCompletionCallback callback;
1073   ClientSocketHandle handle;
1074   int rv =
1075       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
1076                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1077                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1078                   pool_.get(), NetLogWithSource());
1079   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1080   EXPECT_FALSE(handle.is_initialized());
1081   EXPECT_FALSE(handle.socket());
1082 
1083   EXPECT_THAT(callback.WaitForResult(), IsOk());
1084   EXPECT_TRUE(handle.is_initialized());
1085   EXPECT_TRUE(handle.socket());
1086 
1087   handle.Reset();
1088 
1089   // Need to run all pending to release the socket back to the pool.
1090   base::RunLoop().RunUntilIdle();
1091 
1092   // Now we should have 1 idle socket.
1093   EXPECT_EQ(1, pool_->IdleSocketCount());
1094 
1095   // After an SSL configuration change, we should have 0 idle sockets.
1096   session_deps_.ssl_config_service->NotifySSLContextConfigChange();
1097   base::RunLoop().RunUntilIdle();  // Notification happens async.
1098 
1099   EXPECT_EQ(0, pool_->IdleSocketCount());
1100 }
1101 
TEST_F(TransportClientSocketPoolTest,BackupSocketConnect)1102 TEST_F(TransportClientSocketPoolTest, BackupSocketConnect) {
1103   // Case 1 tests the first socket stalling, and the backup connecting.
1104   MockTransportClientSocketFactory::ClientSocketType case1_types[] = {
1105     // The first socket will not connect.
1106     MockTransportClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET,
1107     // The second socket will connect more quickly.
1108     MockTransportClientSocketFactory::MOCK_CLIENT_SOCKET
1109   };
1110 
1111   // Case 2 tests the first socket being slow, so that we start the
1112   // second connect, but the second connect stalls, and we still
1113   // complete the first.
1114   MockTransportClientSocketFactory::ClientSocketType case2_types[] = {
1115     // The first socket will connect, although delayed.
1116     MockTransportClientSocketFactory::MOCK_DELAYED_CLIENT_SOCKET,
1117     // The second socket will not connect.
1118     MockTransportClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET
1119   };
1120 
1121   MockTransportClientSocketFactory::ClientSocketType* cases[2] = {
1122     case1_types,
1123     case2_types
1124   };
1125 
1126   for (size_t index = 0; index < base::size(cases); ++index) {
1127     client_socket_factory_.set_client_socket_types(cases[index], 2);
1128 
1129     EXPECT_EQ(0, pool_->IdleSocketCount());
1130 
1131     TestCompletionCallback callback;
1132     ClientSocketHandle handle;
1133     int rv = handle.Init(
1134         group_id_, params_, base::nullopt /* proxy_annotation_tag */, LOW,
1135         SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1136         callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
1137         NetLogWithSource());
1138     EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1139     EXPECT_FALSE(handle.is_initialized());
1140     EXPECT_FALSE(handle.socket());
1141 
1142     // Create the first socket, set the timer.
1143     base::RunLoop().RunUntilIdle();
1144 
1145     // Wait for the backup socket timer to fire.
1146     base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
1147         ClientSocketPool::kMaxConnectRetryIntervalMs + 50));
1148 
1149     // Let the appropriate socket connect.
1150     base::RunLoop().RunUntilIdle();
1151 
1152     EXPECT_THAT(callback.WaitForResult(), IsOk());
1153     EXPECT_TRUE(handle.is_initialized());
1154     EXPECT_TRUE(handle.socket());
1155 
1156     // One socket is stalled, the other is active.
1157     EXPECT_EQ(0, pool_->IdleSocketCount());
1158     handle.Reset();
1159 
1160     // Close all pending connect jobs and existing sockets.
1161     pool_->FlushWithError(ERR_NETWORK_CHANGED, "Network changed");
1162   }
1163 }
1164 
1165 // Test the case where a socket took long enough to start the creation
1166 // of the backup socket, but then we cancelled the request after that.
TEST_F(TransportClientSocketPoolTest,BackupSocketCancel)1167 TEST_F(TransportClientSocketPoolTest, BackupSocketCancel) {
1168   client_socket_factory_.set_default_client_socket_type(
1169       MockTransportClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET);
1170 
1171   enum { CANCEL_BEFORE_WAIT, CANCEL_AFTER_WAIT };
1172 
1173   for (int index = CANCEL_BEFORE_WAIT; index < CANCEL_AFTER_WAIT; ++index) {
1174     EXPECT_EQ(0, pool_->IdleSocketCount());
1175 
1176     TestCompletionCallback callback;
1177     ClientSocketHandle handle;
1178     int rv = handle.Init(
1179         group_id_, params_, base::nullopt /* proxy_annotation_tag */, LOW,
1180         SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1181         callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
1182         NetLogWithSource());
1183     EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1184     EXPECT_FALSE(handle.is_initialized());
1185     EXPECT_FALSE(handle.socket());
1186 
1187     // Create the first socket, set the timer.
1188     base::RunLoop().RunUntilIdle();
1189 
1190     if (index == CANCEL_AFTER_WAIT) {
1191       // Wait for the backup socket timer to fire.
1192       base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
1193           ClientSocketPool::kMaxConnectRetryIntervalMs));
1194     }
1195 
1196     // Let the appropriate socket connect.
1197     base::RunLoop().RunUntilIdle();
1198 
1199     handle.Reset();
1200 
1201     EXPECT_FALSE(callback.have_result());
1202     EXPECT_FALSE(handle.is_initialized());
1203     EXPECT_FALSE(handle.socket());
1204 
1205     // One socket is stalled, the other is active.
1206     EXPECT_EQ(0, pool_->IdleSocketCount());
1207   }
1208 }
1209 
1210 // Test the case where a socket took long enough to start the creation
1211 // of the backup socket and never completes, and then the backup
1212 // connection fails.
TEST_F(TransportClientSocketPoolTest,BackupSocketFailAfterStall)1213 TEST_F(TransportClientSocketPoolTest, BackupSocketFailAfterStall) {
1214   MockTransportClientSocketFactory::ClientSocketType case_types[] = {
1215     // The first socket will not connect.
1216     MockTransportClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET,
1217     // The second socket will fail immediately.
1218     MockTransportClientSocketFactory::MOCK_FAILING_CLIENT_SOCKET
1219   };
1220 
1221   client_socket_factory_.set_client_socket_types(case_types, 2);
1222 
1223   EXPECT_EQ(0, pool_->IdleSocketCount());
1224 
1225   TestCompletionCallback callback;
1226   ClientSocketHandle handle;
1227   int rv =
1228       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
1229                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1230                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1231                   pool_.get(), NetLogWithSource());
1232   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1233   EXPECT_FALSE(handle.is_initialized());
1234   EXPECT_FALSE(handle.socket());
1235 
1236   // Create the first socket, set the timer.
1237   base::RunLoop().RunUntilIdle();
1238 
1239   // Wait for the backup socket timer to fire.
1240   base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
1241       ClientSocketPool::kMaxConnectRetryIntervalMs));
1242 
1243   // Let the second connect be synchronous. Otherwise, the emulated
1244   // host resolution takes an extra trip through the message loop.
1245   session_deps_.host_resolver->set_synchronous_mode(true);
1246 
1247   // Let the appropriate socket connect.
1248   base::RunLoop().RunUntilIdle();
1249 
1250   EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CONNECTION_FAILED));
1251   EXPECT_FALSE(handle.is_initialized());
1252   EXPECT_FALSE(handle.socket());
1253   ASSERT_EQ(1u, handle.connection_attempts().size());
1254   EXPECT_THAT(handle.connection_attempts()[0].result,
1255               IsError(ERR_CONNECTION_FAILED));
1256   EXPECT_EQ(0, pool_->IdleSocketCount());
1257   handle.Reset();
1258 }
1259 
1260 // Test the case where a socket took long enough to start the creation
1261 // of the backup socket and eventually completes, but the backup socket
1262 // fails.
TEST_F(TransportClientSocketPoolTest,BackupSocketFailAfterDelay)1263 TEST_F(TransportClientSocketPoolTest, BackupSocketFailAfterDelay) {
1264   MockTransportClientSocketFactory::ClientSocketType case_types[] = {
1265     // The first socket will connect, although delayed.
1266     MockTransportClientSocketFactory::MOCK_DELAYED_CLIENT_SOCKET,
1267     // The second socket will not connect.
1268     MockTransportClientSocketFactory::MOCK_FAILING_CLIENT_SOCKET
1269   };
1270 
1271   client_socket_factory_.set_client_socket_types(case_types, 2);
1272   client_socket_factory_.set_delay(base::TimeDelta::FromSeconds(5));
1273 
1274   EXPECT_EQ(0, pool_->IdleSocketCount());
1275 
1276   TestCompletionCallback callback;
1277   ClientSocketHandle handle;
1278   int rv =
1279       handle.Init(group_id_, params_, base::nullopt /* proxy_annotation_tag */,
1280                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1281                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1282                   pool_.get(), NetLogWithSource());
1283   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1284   EXPECT_FALSE(handle.is_initialized());
1285   EXPECT_FALSE(handle.socket());
1286 
1287   // Create the first socket, set the timer.
1288   base::RunLoop().RunUntilIdle();
1289 
1290   // Wait for the backup socket timer to fire.
1291   base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
1292       ClientSocketPool::kMaxConnectRetryIntervalMs));
1293 
1294   // Let the second connect be synchronous. Otherwise, the emulated
1295   // host resolution takes an extra trip through the message loop.
1296   session_deps_.host_resolver->set_synchronous_mode(true);
1297 
1298   // Let the appropriate socket connect.
1299   base::RunLoop().RunUntilIdle();
1300 
1301   EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CONNECTION_FAILED));
1302   EXPECT_FALSE(handle.is_initialized());
1303   EXPECT_FALSE(handle.socket());
1304   ASSERT_EQ(1u, handle.connection_attempts().size());
1305   EXPECT_THAT(handle.connection_attempts()[0].result,
1306               IsError(ERR_CONNECTION_FAILED));
1307   handle.Reset();
1308 }
1309 
1310 // Test the case that SOCKSSocketParams are provided.
TEST_F(TransportClientSocketPoolTest,SOCKS)1311 TEST_F(TransportClientSocketPoolTest, SOCKS) {
1312   const HostPortPair kDestination("host", 80);
1313 
1314   TransportClientSocketPool proxy_pool(
1315       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
1316       ProxyServer::FromURI("socks5://foopy",
1317                            ProxyServer::SCHEME_HTTP /* default_scheme */),
1318       false /* is_for_websockets */, tagging_common_connect_job_params_.get());
1319 
1320   for (IoMode socket_io_mode : {SYNCHRONOUS, ASYNC}) {
1321     scoped_refptr<ClientSocketPool::SocketParams> socket_params =
1322         base::MakeRefCounted<ClientSocketPool::SocketParams>(
1323             nullptr /* ssl_config_for_origin */,
1324             nullptr /* ssl_config_for_proxy */);
1325 
1326     SOCKS5MockData data(socket_io_mode);
1327     data.data_provider()->set_connect_data(MockConnect(socket_io_mode, OK));
1328     tagging_client_socket_factory_.AddSocketDataProvider(data.data_provider());
1329     ClientSocketHandle handle;
1330     TestCompletionCallback callback;
1331     int rv = handle.Init(
1332         ClientSocketPool::GroupId(
1333             kDestination, ClientSocketPool::SocketType::kHttp,
1334             PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
1335             false /* disable_secure_dns */),
1336         socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1337         ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
1338         ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
1339     EXPECT_THAT(callback.GetResult(rv), IsOk());
1340     EXPECT_TRUE(handle.is_initialized());
1341     EXPECT_TRUE(handle.socket());
1342     EXPECT_TRUE(data.data_provider()->AllReadDataConsumed());
1343     EXPECT_TRUE(data.data_provider()->AllWriteDataConsumed());
1344   }
1345 }
1346 
1347 // Make sure there's no crash when an auth challenge is received over HTTP2
1348 // and there are two pending Requests to the socket pool, with a single
1349 // ConnectJob.
1350 //
1351 // See https://crbug.com/940848
TEST_F(TransportClientSocketPoolTest,SpdyOneConnectJobTwoRequestsError)1352 TEST_F(TransportClientSocketPoolTest, SpdyOneConnectJobTwoRequestsError) {
1353   const HostPortPair kEndpoint("unresolvable.host.name", 443);
1354 
1355   session_deps_.host_resolver->set_synchronous_mode(true);
1356 
1357   // Create a socket pool which only allows a single connection at a time.
1358   TransportClientSocketPool pool(
1359       1, 1, kUnusedIdleSocketTimeout,
1360       ProxyServer::FromURI("https://unresolvable.proxy.name",
1361                            ProxyServer::SCHEME_HTTP /* default_scheme */),
1362       false /* is_for_websockets */, tagging_common_connect_job_params_.get());
1363 
1364   // First connection attempt will get an error after creating the SpdyStream.
1365 
1366   SpdyTestUtil spdy_util;
1367   spdy::SpdySerializedFrame connect(spdy_util.ConstructSpdyConnect(
1368       nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority, kEndpoint));
1369 
1370   MockWrite writes[] = {
1371       CreateMockWrite(connect, 0, ASYNC),
1372       MockWrite(SYNCHRONOUS, ERR_IO_PENDING, 2),
1373   };
1374 
1375   MockRead reads[] = {
1376       MockRead(ASYNC, ERR_FAILED, 1),
1377   };
1378 
1379   SequencedSocketData socket_data(MockConnect(SYNCHRONOUS, OK), reads, writes);
1380   tagging_client_socket_factory_.AddSocketDataProvider(&socket_data);
1381   SSLSocketDataProvider ssl_data(SYNCHRONOUS, OK);
1382   ssl_data.next_proto = kProtoHTTP2;
1383   tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data);
1384 
1385   // Second connection also fails.  Not a vital part of this test, but allows
1386   // waiting for the second request to complete without too much extra code.
1387   SequencedSocketData socket_data2(
1388       MockConnect(SYNCHRONOUS, ERR_CONNECTION_TIMED_OUT),
1389       base::span<const MockRead>(), base::span<const MockWrite>());
1390   tagging_client_socket_factory_.AddSocketDataProvider(&socket_data2);
1391   SSLSocketDataProvider ssl_data2(SYNCHRONOUS, OK);
1392   tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data2);
1393 
1394   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
1395       base::MakeRefCounted<ClientSocketPool::SocketParams>(
1396           std::make_unique<SSLConfig>() /* ssl_config_for_origin */,
1397           std::make_unique<SSLConfig>() /* ssl_config_for_proxy */);
1398 
1399   ClientSocketPool::GroupId group_id(
1400       kEndpoint, ClientSocketPool::SocketType::kSsl,
1401       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
1402       false /* disable_secure_dns */);
1403 
1404   // Start the first connection attempt.
1405   TestCompletionCallback callback1;
1406   ClientSocketHandle handle1;
1407   int rv1 = handle1.Init(
1408       group_id, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, HIGHEST,
1409       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1410       callback1.callback(), ClientSocketPool::ProxyAuthCallback(), &pool,
1411       NetLogWithSource());
1412   ASSERT_THAT(rv1, IsError(ERR_IO_PENDING));
1413 
1414   // Create a second request with a lower priority.
1415   TestCompletionCallback callback2;
1416   ClientSocketHandle handle2;
1417   int rv2 = handle2.Init(
1418       group_id, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOWEST,
1419       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1420       callback2.callback(), ClientSocketPool::ProxyAuthCallback(), &pool,
1421       NetLogWithSource());
1422   ASSERT_THAT(rv2, IsError(ERR_IO_PENDING));
1423 
1424   // First connection fails after creating a SpdySession and a SpdyStream on
1425   // that session. The SpdyStream will be destroyed under the
1426   // SpdyProxyClientSocket. The failure will result in temporarily assigning the
1427   // failed ConnectJob to the second request, which results in an unneeded
1428   // reprioritization, which should not dereference the null SpdyStream.
1429   //
1430   // TODO(mmenke): Avoid that temporary reassignment.
1431   ASSERT_THAT(callback1.WaitForResult(), IsError(ERR_FAILED));
1432 
1433   // Second connection fails, getting a connection error.
1434   ASSERT_THAT(callback2.WaitForResult(), IsError(ERR_PROXY_CONNECTION_FAILED));
1435 }
1436 
1437 // Make sure there's no crash when an auth challenge is received over HTTP2
1438 // and there are two pending Requests to the socket pool, with a single
1439 // ConnectJob.
1440 //
1441 // See https://crbug.com/940848
TEST_F(TransportClientSocketPoolTest,SpdyAuthOneConnectJobTwoRequests)1442 TEST_F(TransportClientSocketPoolTest, SpdyAuthOneConnectJobTwoRequests) {
1443   const HostPortPair kEndpoint("unresolvable.host.name", 443);
1444   const HostPortPair kProxy("unresolvable.proxy.name", 443);
1445 
1446   session_deps_.host_resolver->set_synchronous_mode(true);
1447 
1448   // Create a socket pool which only allows a single connection at a time.
1449   TransportClientSocketPool pool(
1450       1, 1, kUnusedIdleSocketTimeout,
1451       ProxyServer::FromURI("https://unresolvable.proxy.name",
1452                            ProxyServer::SCHEME_HTTP /* default_scheme */),
1453       false /* is_for_websockets */, tagging_common_connect_job_params_.get());
1454 
1455   SpdyTestUtil spdy_util;
1456   spdy::SpdySerializedFrame connect(spdy_util.ConstructSpdyConnect(
1457       nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority, kEndpoint));
1458 
1459   MockWrite writes[] = {
1460       CreateMockWrite(connect, 0, ASYNC),
1461       MockWrite(SYNCHRONOUS, ERR_IO_PENDING, 4),
1462   };
1463 
1464   // The proxy responds to the connect with a 407, and them an
1465   // ERROR_CODE_HTTP_1_1_REQUIRED.
1466 
1467   const char kAuthStatus[] = "407";
1468   const char* const kAuthChallenge[] = {
1469       "proxy-authenticate",
1470       "NTLM",
1471   };
1472   spdy::SpdySerializedFrame connect_auth_resp(spdy_util.ConstructSpdyReplyError(
1473       kAuthStatus, kAuthChallenge, base::size(kAuthChallenge) / 2, 1));
1474   spdy::SpdySerializedFrame reset(
1475       spdy_util.ConstructSpdyRstStream(1, spdy::ERROR_CODE_HTTP_1_1_REQUIRED));
1476   MockRead reads[] = {
1477       CreateMockRead(connect_auth_resp, 1, ASYNC),
1478       CreateMockRead(reset, 2, SYNCHRONOUS),
1479       MockRead(SYNCHRONOUS, ERR_IO_PENDING, 3),
1480   };
1481 
1482   SequencedSocketData socket_data(MockConnect(SYNCHRONOUS, OK), reads, writes);
1483   tagging_client_socket_factory_.AddSocketDataProvider(&socket_data);
1484   SSLSocketDataProvider ssl_data(SYNCHRONOUS, OK);
1485   ssl_data.next_proto = kProtoHTTP2;
1486   tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data);
1487 
1488   // Second connection fails, and gets a different error.  Not a vital part of
1489   // this test, but allows waiting for the second request to complete without
1490   // too much extra code.
1491   SequencedSocketData socket_data2(
1492       MockConnect(SYNCHRONOUS, ERR_CONNECTION_TIMED_OUT),
1493       base::span<const MockRead>(), base::span<const MockWrite>());
1494   tagging_client_socket_factory_.AddSocketDataProvider(&socket_data2);
1495   SSLSocketDataProvider ssl_data2(SYNCHRONOUS, OK);
1496   tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data2);
1497 
1498   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
1499       base::MakeRefCounted<ClientSocketPool::SocketParams>(
1500           std::make_unique<SSLConfig>() /* ssl_config_for_origin */,
1501           std::make_unique<SSLConfig>() /* ssl_config_for_proxy */);
1502 
1503   ClientSocketPool::GroupId group_id(
1504       kEndpoint, ClientSocketPool::SocketType::kSsl,
1505       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
1506       false /* disable_secure_dns */);
1507 
1508   // Start the first connection attempt.
1509   TestCompletionCallback callback1;
1510   ClientSocketHandle handle1;
1511   base::RunLoop run_loop;
1512   int rv1 = handle1.Init(group_id, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS,
1513                          HIGHEST, SocketTag(),
1514                          ClientSocketPool::RespectLimits::ENABLED,
1515                          callback1.callback(),
1516                          base::BindLambdaForTesting(
1517                              [&](const HttpResponseInfo& response,
1518                                  HttpAuthController* auth_controller,
1519                                  base::OnceClosure restart_with_auth_callback) {
1520                                run_loop.Quit();
1521                              }),
1522                          &pool, NetLogWithSource());
1523   ASSERT_THAT(rv1, IsError(ERR_IO_PENDING));
1524 
1525   // Create a second request with a lower priority.
1526   TestCompletionCallback callback2;
1527   ClientSocketHandle handle2;
1528   int rv2 = handle2.Init(
1529       group_id, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOWEST,
1530       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1531       callback2.callback(), ClientSocketPool::ProxyAuthCallback(), &pool,
1532       NetLogWithSource());
1533   ASSERT_THAT(rv2, IsError(ERR_IO_PENDING));
1534 
1535   // The ConnectJob connection sees the auth challenge and HTTP2 error, which
1536   // causes the SpdySession to be destroyed, as well as the SpdyStream. Then the
1537   // ConnectJob is bound to the first request. Binding the request will result
1538   // in temporarily assigning the ConnectJob to the second request, which
1539   // results in an unneeded reprioritization, which should not dereference the
1540   // null SpdyStream.
1541   //
1542   // TODO(mmenke): Avoid that temporary reassignment.
1543   run_loop.Run();
1544 
1545   // Just tear down everything without continuing - there are other tests for
1546   // auth over HTTP2.
1547 }
1548 
TEST_F(TransportClientSocketPoolTest,HttpTunnelSetupRedirect)1549 TEST_F(TransportClientSocketPoolTest, HttpTunnelSetupRedirect) {
1550   const HostPortPair kEndpoint("host.test", 443);
1551 
1552   const std::string kRedirectTarget = "https://some.other.host.test/";
1553 
1554   const std::string kResponseText =
1555       "HTTP/1.1 302 Found\r\n"
1556       "Location: " +
1557       kRedirectTarget +
1558       "\r\n"
1559       "Set-Cookie: foo=bar\r\n"
1560       "\r\n";
1561 
1562   for (IoMode io_mode : {SYNCHRONOUS, ASYNC}) {
1563     SCOPED_TRACE(io_mode);
1564     session_deps_.host_resolver->set_synchronous_mode(io_mode == SYNCHRONOUS);
1565 
1566     for (bool use_https_proxy : {false, true}) {
1567       SCOPED_TRACE(use_https_proxy);
1568 
1569       TransportClientSocketPool proxy_pool(
1570           kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
1571           ProxyServer::FromURI(
1572               use_https_proxy ? "https://proxy.test" : "http://proxy.test",
1573               ProxyServer::SCHEME_HTTP /* default_scheme */),
1574           false /* is_for_websockets */,
1575           tagging_common_connect_job_params_.get());
1576 
1577       MockWrite writes[] = {
1578           MockWrite(ASYNC, 0,
1579                     "CONNECT host.test:443 HTTP/1.1\r\n"
1580                     "Host: host.test:443\r\n"
1581                     "Proxy-Connection: keep-alive\r\n\r\n"),
1582       };
1583       MockRead reads[] = {
1584           MockRead(ASYNC, 1, kResponseText.c_str()),
1585       };
1586 
1587       SequencedSocketData data(reads, writes);
1588       tagging_client_socket_factory_.AddSocketDataProvider(&data);
1589       SSLSocketDataProvider ssl(ASYNC, OK);
1590       tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl);
1591 
1592       ClientSocketHandle handle;
1593       TestCompletionCallback callback;
1594 
1595       scoped_refptr<ClientSocketPool::SocketParams> socket_params =
1596           base::MakeRefCounted<ClientSocketPool::SocketParams>(
1597               std::make_unique<SSLConfig>() /* ssl_config_for_origin */,
1598               std::make_unique<SSLConfig>() /* ssl_config_for_proxy */);
1599 
1600       int rv = handle.Init(
1601           ClientSocketPool::GroupId(
1602               kEndpoint, ClientSocketPool::SocketType::kSsl,
1603               PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
1604               false /* disable_secure_dns */),
1605           socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1606           ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
1607           ClientSocketPool::ProxyAuthCallback(), &proxy_pool,
1608           NetLogWithSource());
1609       rv = callback.GetResult(rv);
1610 
1611       // We don't trust 302 responses to CONNECT.
1612       EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
1613       EXPECT_FALSE(handle.is_initialized());
1614     }
1615   }
1616 }
1617 
TEST_F(TransportClientSocketPoolTest,NetworkIsolationKey)1618 TEST_F(TransportClientSocketPoolTest, NetworkIsolationKey) {
1619   const auto kOrigin = url::Origin::Create(GURL("https://foo.test/"));
1620   const NetworkIsolationKey kNetworkIsolationKey(kOrigin, kOrigin);
1621   const char kHost[] = "bar.test";
1622 
1623   base::test::ScopedFeatureList scoped_feature_list;
1624   scoped_feature_list.InitWithFeatures(
1625       // enabled_features
1626       {features::kPartitionConnectionsByNetworkIsolationKey,
1627        features::kSplitHostCacheByNetworkIsolationKey},
1628       // disabled_features
1629       {});
1630 
1631   session_deps_.host_resolver->set_ondemand_mode(true);
1632 
1633   TransportClientSocketPool::GroupId group_id(
1634       HostPortPair(kHost, 80), ClientSocketPool::SocketType::kHttp,
1635       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkIsolationKey,
1636       false /* disable_secure_dns */);
1637   ClientSocketHandle handle;
1638   TestCompletionCallback callback;
1639   EXPECT_THAT(
1640       handle.Init(group_id,
1641                   base::MakeRefCounted<ClientSocketPool::SocketParams>(
1642                       nullptr /* ssl_config_for_origin */,
1643                       nullptr /* ssl_config_for_proxy */),
1644                   TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1645                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
1646                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
1647                   NetLogWithSource()),
1648       IsError(ERR_IO_PENDING));
1649 
1650   ASSERT_EQ(1u, session_deps_.host_resolver->last_id());
1651   EXPECT_EQ(kHost, session_deps_.host_resolver->request_host(1));
1652   EXPECT_EQ(kNetworkIsolationKey,
1653             session_deps_.host_resolver->request_network_isolation_key(1));
1654 }
1655 
TEST_F(TransportClientSocketPoolTest,NetworkIsolationKeySsl)1656 TEST_F(TransportClientSocketPoolTest, NetworkIsolationKeySsl) {
1657   const auto kOrigin = url::Origin::Create(GURL("https://foo.test/"));
1658   const NetworkIsolationKey kNetworkIsolationKey(kOrigin, kOrigin);
1659   const char kHost[] = "bar.test";
1660 
1661   base::test::ScopedFeatureList scoped_feature_list;
1662   scoped_feature_list.InitWithFeatures(
1663       // enabled_features
1664       {features::kPartitionConnectionsByNetworkIsolationKey,
1665        features::kSplitHostCacheByNetworkIsolationKey},
1666       // disabled_features
1667       {});
1668 
1669   session_deps_.host_resolver->set_ondemand_mode(true);
1670 
1671   TransportClientSocketPool::GroupId group_id(
1672       HostPortPair(kHost, 443), ClientSocketPool::SocketType::kSsl,
1673       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkIsolationKey,
1674       false /* disable_secure_dns */);
1675   ClientSocketHandle handle;
1676   TestCompletionCallback callback;
1677   EXPECT_THAT(
1678       handle.Init(group_id,
1679                   base::MakeRefCounted<ClientSocketPool::SocketParams>(
1680                       std::make_unique<SSLConfig>() /* ssl_config_for_origin */,
1681                       nullptr /* ssl_config_for_proxy */),
1682                   TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1683                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
1684                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
1685                   NetLogWithSource()),
1686       IsError(ERR_IO_PENDING));
1687 
1688   ASSERT_EQ(1u, session_deps_.host_resolver->last_id());
1689   EXPECT_EQ(kHost, session_deps_.host_resolver->request_host(1));
1690   EXPECT_EQ(kNetworkIsolationKey,
1691             session_deps_.host_resolver->request_network_isolation_key(1));
1692 }
1693 
1694 // Test that, in the case of an HTTP proxy, the NetworkIsolationKey is not used.
TEST_F(TransportClientSocketPoolTest,NetworkIsolationKeyHttpProxy)1695 TEST_F(TransportClientSocketPoolTest, NetworkIsolationKeyHttpProxy) {
1696   const auto kOrigin = url::Origin::Create(GURL("https://foo.test/"));
1697   const NetworkIsolationKey kNetworkIsolationKey(kOrigin, kOrigin);
1698   const char kHost[] = "bar.test";
1699   const ProxyServer kProxyServer = ProxyServer::FromURI(
1700       "http://proxy.test", ProxyServer::SCHEME_HTTP /* default_scheme */);
1701 
1702   base::test::ScopedFeatureList scoped_feature_list;
1703   scoped_feature_list.InitWithFeatures(
1704       // enabled_features
1705       {features::kPartitionConnectionsByNetworkIsolationKey,
1706        features::kSplitHostCacheByNetworkIsolationKey},
1707       // disabled_features
1708       {});
1709 
1710   session_deps_.host_resolver->set_ondemand_mode(true);
1711 
1712   TransportClientSocketPool proxy_pool(
1713       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, kProxyServer,
1714       false /* is_for_websockets */, tagging_common_connect_job_params_.get());
1715 
1716   TransportClientSocketPool::GroupId group_id(
1717       HostPortPair(kHost, 80), ClientSocketPool::SocketType::kHttp,
1718       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkIsolationKey,
1719       false /* disable_secure_dns */);
1720   ClientSocketHandle handle;
1721   TestCompletionCallback callback;
1722   EXPECT_THAT(
1723       handle.Init(group_id,
1724                   base::MakeRefCounted<ClientSocketPool::SocketParams>(
1725                       nullptr /* ssl_config_for_origin */,
1726                       nullptr /* ssl_config_for_proxy */),
1727                   TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1728                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
1729                   ClientSocketPool::ProxyAuthCallback(), &proxy_pool,
1730                   NetLogWithSource()),
1731       IsError(ERR_IO_PENDING));
1732 
1733   ASSERT_EQ(1u, session_deps_.host_resolver->last_id());
1734   EXPECT_EQ(kProxyServer.host_port_pair().host(),
1735             session_deps_.host_resolver->request_host(1));
1736   EXPECT_EQ(NetworkIsolationKey(),
1737             session_deps_.host_resolver->request_network_isolation_key(1));
1738 }
1739 
1740 // Test that, in the case of an HTTPS proxy, the NetworkIsolationKey is not
1741 // used.
TEST_F(TransportClientSocketPoolTest,NetworkIsolationKeyHttpsProxy)1742 TEST_F(TransportClientSocketPoolTest, NetworkIsolationKeyHttpsProxy) {
1743   const auto kOrigin = url::Origin::Create(GURL("https://foo.test/"));
1744   const NetworkIsolationKey kNetworkIsolationKey(kOrigin, kOrigin);
1745   const char kHost[] = "bar.test";
1746   const ProxyServer kProxyServer = ProxyServer::FromURI(
1747       "https://proxy.test", ProxyServer::SCHEME_HTTP /* default_scheme */);
1748 
1749   base::test::ScopedFeatureList scoped_feature_list;
1750   scoped_feature_list.InitWithFeatures(
1751       // enabled_features
1752       {features::kPartitionConnectionsByNetworkIsolationKey,
1753        features::kSplitHostCacheByNetworkIsolationKey},
1754       // disabled_features
1755       {});
1756 
1757   session_deps_.host_resolver->set_ondemand_mode(true);
1758 
1759   TransportClientSocketPool proxy_pool(
1760       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, kProxyServer,
1761       false /* is_for_websockets */, tagging_common_connect_job_params_.get());
1762 
1763   TransportClientSocketPool::GroupId group_id(
1764       HostPortPair(kHost, 80), ClientSocketPool::SocketType::kHttp,
1765       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkIsolationKey,
1766       false /* disable_secure_dns */);
1767   ClientSocketHandle handle;
1768   TestCompletionCallback callback;
1769   EXPECT_THAT(
1770       handle.Init(group_id,
1771                   base::MakeRefCounted<ClientSocketPool::SocketParams>(
1772                       nullptr /* ssl_config_for_origin */,
1773                       std::make_unique<SSLConfig>() /* ssl_config_for_proxy */),
1774                   TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1775                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
1776                   ClientSocketPool::ProxyAuthCallback(), &proxy_pool,
1777                   NetLogWithSource()),
1778       IsError(ERR_IO_PENDING));
1779 
1780   ASSERT_EQ(1u, session_deps_.host_resolver->last_id());
1781   EXPECT_EQ(kProxyServer.host_port_pair().host(),
1782             session_deps_.host_resolver->request_host(1));
1783   EXPECT_EQ(NetworkIsolationKey(),
1784             session_deps_.host_resolver->request_network_isolation_key(1));
1785 }
1786 
1787 // Test that, in the case of a SOCKS5 proxy, the NetworkIsolationKey is only
1788 // used for the destination DNS lookup, not the proxy DNS lookup.
TEST_F(TransportClientSocketPoolTest,NetworkIsolationKeySocks4Proxy)1789 TEST_F(TransportClientSocketPoolTest, NetworkIsolationKeySocks4Proxy) {
1790   const auto kOrigin = url::Origin::Create(GURL("https://foo.test/"));
1791   const NetworkIsolationKey kNetworkIsolationKey(kOrigin, kOrigin);
1792   const char kHost[] = "bar.test";
1793   const ProxyServer kProxyServer = ProxyServer::FromURI(
1794       "socks4://proxy.test", ProxyServer::SCHEME_HTTP /* default_scheme */);
1795 
1796   base::test::ScopedFeatureList scoped_feature_list;
1797   scoped_feature_list.InitWithFeatures(
1798       // enabled_features
1799       {features::kPartitionConnectionsByNetworkIsolationKey,
1800        features::kSplitHostCacheByNetworkIsolationKey},
1801       // disabled_features
1802       {});
1803 
1804   session_deps_.host_resolver->set_ondemand_mode(true);
1805 
1806   // Test will establish a connection, but never use it to transfer data, since
1807   // it stalls at the second DNS lookup.
1808   StaticSocketDataProvider data;
1809   data.set_connect_data(MockConnect(SYNCHRONOUS, OK));
1810   tagging_client_socket_factory_.AddSocketDataProvider(&data);
1811 
1812   TransportClientSocketPool proxy_pool(
1813       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, kProxyServer,
1814       false /* is_for_websockets */, tagging_common_connect_job_params_.get());
1815 
1816   TransportClientSocketPool::GroupId group_id(
1817       HostPortPair(kHost, 80), ClientSocketPool::SocketType::kHttp,
1818       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkIsolationKey,
1819       false /* disable_secure_dns */);
1820   ClientSocketHandle handle;
1821   TestCompletionCallback callback;
1822   EXPECT_THAT(
1823       handle.Init(group_id,
1824                   base::MakeRefCounted<ClientSocketPool::SocketParams>(
1825                       nullptr /* ssl_config_for_origin */,
1826                       nullptr /* ssl_config_for_proxy */),
1827                   TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1828                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
1829                   ClientSocketPool::ProxyAuthCallback(), &proxy_pool,
1830                   NetLogWithSource()),
1831       IsError(ERR_IO_PENDING));
1832 
1833   // First lookup is for the proxy's hostname, and should not use the NIK.
1834   ASSERT_EQ(1u, session_deps_.host_resolver->last_id());
1835   EXPECT_EQ(kProxyServer.host_port_pair().host(),
1836             session_deps_.host_resolver->request_host(1));
1837   EXPECT_EQ(NetworkIsolationKey(),
1838             session_deps_.host_resolver->request_network_isolation_key(1));
1839 
1840   // First lookup completes, starting the second one. The second lookup is for
1841   // the destination's hostname, and should use the NIK.
1842   session_deps_.host_resolver->ResolveOnlyRequestNow();
1843   ASSERT_EQ(2u, session_deps_.host_resolver->last_id());
1844   EXPECT_EQ(kHost, session_deps_.host_resolver->request_host(2));
1845   EXPECT_EQ(kNetworkIsolationKey,
1846             session_deps_.host_resolver->request_network_isolation_key(2));
1847 }
1848 
1849 // Test that, in the case of a SOCKS5 proxy, the NetworkIsolationKey is not
1850 // used.
TEST_F(TransportClientSocketPoolTest,NetworkIsolationKeySocks5Proxy)1851 TEST_F(TransportClientSocketPoolTest, NetworkIsolationKeySocks5Proxy) {
1852   const auto kOrigin = url::Origin::Create(GURL("https://foo.test/"));
1853   const NetworkIsolationKey kNetworkIsolationKey(kOrigin, kOrigin);
1854   const char kHost[] = "bar.test";
1855   const ProxyServer kProxyServer = ProxyServer::FromURI(
1856       "socks5://proxy.test", ProxyServer::SCHEME_HTTP /* default_scheme */);
1857 
1858   base::test::ScopedFeatureList scoped_feature_list;
1859   scoped_feature_list.InitWithFeatures(
1860       // enabled_features
1861       {features::kPartitionConnectionsByNetworkIsolationKey,
1862        features::kSplitHostCacheByNetworkIsolationKey},
1863       // disabled_features
1864       {});
1865 
1866   session_deps_.host_resolver->set_ondemand_mode(true);
1867 
1868   TransportClientSocketPool proxy_pool(
1869       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, kProxyServer,
1870       false /* is_for_websockets */, tagging_common_connect_job_params_.get());
1871 
1872   TransportClientSocketPool::GroupId group_id(
1873       HostPortPair(kHost, 80), ClientSocketPool::SocketType::kHttp,
1874       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkIsolationKey,
1875       false /* disable_secure_dns */);
1876   ClientSocketHandle handle;
1877   TestCompletionCallback callback;
1878   EXPECT_THAT(
1879       handle.Init(group_id,
1880                   base::MakeRefCounted<ClientSocketPool::SocketParams>(
1881                       nullptr /* ssl_config_for_origin */,
1882                       nullptr /* ssl_config_for_proxy */),
1883                   TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1884                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
1885                   ClientSocketPool::ProxyAuthCallback(), &proxy_pool,
1886                   NetLogWithSource()),
1887       IsError(ERR_IO_PENDING));
1888 
1889   ASSERT_EQ(1u, session_deps_.host_resolver->last_id());
1890   EXPECT_EQ(kProxyServer.host_port_pair().host(),
1891             session_deps_.host_resolver->request_host(1));
1892   EXPECT_EQ(NetworkIsolationKey(),
1893             session_deps_.host_resolver->request_network_isolation_key(1));
1894 }
1895 
1896 // Test that SocketTag passed into TransportClientSocketPool is applied to
1897 // returned sockets.
1898 #if defined(OS_ANDROID)
TEST_F(TransportClientSocketPoolTest,Tag)1899 TEST_F(TransportClientSocketPoolTest, Tag) {
1900   if (!CanGetTaggedBytes()) {
1901     DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
1902     return;
1903   }
1904 
1905   // Start test server.
1906   EmbeddedTestServer test_server;
1907   test_server.AddDefaultHandlers(base::FilePath());
1908   ASSERT_TRUE(test_server.Start());
1909 
1910   ClientSocketHandle handle;
1911   int32_t tag_val1 = 0x12345678;
1912   SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
1913   int32_t tag_val2 = 0x87654321;
1914   SocketTag tag2(getuid(), tag_val2);
1915 
1916   // Test socket is tagged before connected.
1917   uint64_t old_traffic = GetTaggedBytes(tag_val1);
1918   const ClientSocketPool::GroupId kGroupId(
1919       test_server.host_port_pair(), ClientSocketPool::SocketType::kHttp,
1920       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
1921       false /* disable_secure_dns */);
1922   scoped_refptr<ClientSocketPool::SocketParams> params =
1923       ClientSocketPool::SocketParams::CreateForHttpForTesting();
1924   TestCompletionCallback callback;
1925   int rv =
1926       handle.Init(kGroupId, params, base::nullopt /* proxy_annotation_tag */,
1927                   LOW, tag1, ClientSocketPool::RespectLimits::ENABLED,
1928                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1929                   pool_for_real_sockets_.get(), NetLogWithSource());
1930   EXPECT_THAT(callback.GetResult(rv), IsOk());
1931   EXPECT_TRUE(handle.socket());
1932   EXPECT_TRUE(handle.socket()->IsConnected());
1933   EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
1934 
1935   // Test reused socket is retagged.
1936   StreamSocket* socket = handle.socket();
1937   handle.Reset();
1938   old_traffic = GetTaggedBytes(tag_val2);
1939   rv = handle.Init(kGroupId, params, base::nullopt /* proxy_annotation_tag */,
1940                    LOW, tag2, ClientSocketPool::RespectLimits::ENABLED,
1941                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1942                    pool_for_real_sockets_.get(), NetLogWithSource());
1943   EXPECT_THAT(rv, IsOk());
1944   EXPECT_TRUE(handle.socket());
1945   EXPECT_TRUE(handle.socket()->IsConnected());
1946   EXPECT_EQ(handle.socket(), socket);
1947   const char kRequest[] = "GET / HTTP/1.0\n\n";
1948   scoped_refptr<IOBuffer> write_buffer =
1949       base::MakeRefCounted<StringIOBuffer>(kRequest);
1950   rv =
1951       handle.socket()->Write(write_buffer.get(), strlen(kRequest),
1952                              callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
1953   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback.GetResult(rv));
1954   EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
1955   // Disconnect socket to prevent reuse.
1956   handle.socket()->Disconnect();
1957   handle.Reset();
1958 
1959   // Test connect jobs that are orphaned and then adopted, appropriately apply
1960   // new tag. Request socket with |tag1|.
1961   TestCompletionCallback callback2;
1962   rv = handle.Init(kGroupId, params, base::nullopt /* proxy_annotation_tag */,
1963                    LOW, tag1, ClientSocketPool::RespectLimits::ENABLED,
1964                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
1965                    pool_for_real_sockets_.get(), NetLogWithSource());
1966   EXPECT_TRUE(rv == OK || rv == ERR_IO_PENDING) << "Result: " << rv;
1967   // Abort and request socket with |tag2|.
1968   handle.Reset();
1969   rv = handle.Init(kGroupId, params, base::nullopt /* proxy_annotation_tag */,
1970                    LOW, tag2, ClientSocketPool::RespectLimits::ENABLED,
1971                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1972                    pool_for_real_sockets_.get(), NetLogWithSource());
1973   EXPECT_THAT(callback.GetResult(rv), IsOk());
1974   EXPECT_TRUE(handle.socket());
1975   EXPECT_TRUE(handle.socket()->IsConnected());
1976   // Verify socket has |tag2| applied.
1977   old_traffic = GetTaggedBytes(tag_val2);
1978   rv =
1979       handle.socket()->Write(write_buffer.get(), strlen(kRequest),
1980                              callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
1981   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback.GetResult(rv));
1982   EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
1983   // Disconnect socket to prevent reuse.
1984   handle.socket()->Disconnect();
1985   handle.Reset();
1986   // Eat the left over connect job from the second request.
1987   // TODO(pauljensen): remove when crbug.com/800731 fixed.
1988   rv = handle.Init(kGroupId, params, base::nullopt /* proxy_annotation_tag */,
1989                    LOW, tag1, ClientSocketPool::RespectLimits::ENABLED,
1990                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1991                    pool_for_real_sockets_.get(), NetLogWithSource());
1992   EXPECT_THAT(rv, IsOk());
1993   // Disconnect socket to prevent reuse.
1994   handle.socket()->Disconnect();
1995   handle.Reset();
1996 
1997   // Test two connect jobs of differing priorities. Start the lower priority one
1998   // first but expect its socket to get vended to the higher priority request.
1999   ClientSocketHandle handle_high_pri;
2000   TestCompletionCallback callback_high_pri;
2001   rv = handle.Init(kGroupId, params, base::nullopt /* proxy_annotation_tag */,
2002                    LOW, tag1, ClientSocketPool::RespectLimits::ENABLED,
2003                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
2004                    pool_for_real_sockets_.get(), NetLogWithSource());
2005   EXPECT_TRUE(rv == OK || rv == ERR_IO_PENDING) << "Result: " << rv;
2006   int rv_high_pri = handle_high_pri.Init(
2007       kGroupId, params, base::nullopt /* proxy_annotation_tag */, HIGHEST, tag2,
2008       ClientSocketPool::RespectLimits::ENABLED, callback_high_pri.callback(),
2009       ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(),
2010       NetLogWithSource());
2011   EXPECT_THAT(callback_high_pri.GetResult(rv_high_pri), IsOk());
2012   EXPECT_TRUE(handle_high_pri.socket());
2013   EXPECT_TRUE(handle_high_pri.socket()->IsConnected());
2014   EXPECT_THAT(callback.GetResult(rv), IsOk());
2015   EXPECT_TRUE(handle.socket());
2016   EXPECT_TRUE(handle.socket()->IsConnected());
2017   // Verify |handle_high_pri| has |tag2| applied.
2018   old_traffic = GetTaggedBytes(tag_val2);
2019   rv = handle_high_pri.socket()->Write(write_buffer.get(), strlen(kRequest),
2020                                        callback.callback(),
2021                                        TRAFFIC_ANNOTATION_FOR_TESTS);
2022   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback.GetResult(rv));
2023   EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
2024   // Verify |handle| has |tag1| applied.
2025   old_traffic = GetTaggedBytes(tag_val1);
2026   rv =
2027       handle.socket()->Write(write_buffer.get(), strlen(kRequest),
2028                              callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
2029   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback.GetResult(rv));
2030   EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
2031 }
2032 
TEST_F(TransportClientSocketPoolTest,TagSOCKSProxy)2033 TEST_F(TransportClientSocketPoolTest, TagSOCKSProxy) {
2034   session_deps_.host_resolver->set_synchronous_mode(true);
2035 
2036   TransportClientSocketPool proxy_pool(
2037       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
2038       ProxyServer::FromURI("socks5://proxy",
2039                            ProxyServer::SCHEME_HTTP /* default_scheme */),
2040       false /* is_for_websockets */, tagging_common_connect_job_params_.get());
2041 
2042   SocketTag tag1(SocketTag::UNSET_UID, 0x12345678);
2043   SocketTag tag2(getuid(), 0x87654321);
2044   const HostPortPair kDestination("host", 80);
2045   const ClientSocketPool::GroupId kGroupId(
2046       kDestination, ClientSocketPool::SocketType::kHttp,
2047       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
2048       false /* disable_secure_dns */);
2049   scoped_refptr<ClientSocketPool::SocketParams> socks_params =
2050       base::MakeRefCounted<ClientSocketPool::SocketParams>(
2051           nullptr /* ssl_config_for_origin */,
2052           nullptr /* ssl_config_for_proxy */);
2053 
2054   // Test socket is tagged when created synchronously.
2055   SOCKS5MockData data_sync(SYNCHRONOUS);
2056   data_sync.data_provider()->set_connect_data(MockConnect(SYNCHRONOUS, OK));
2057   tagging_client_socket_factory_.AddSocketDataProvider(
2058       data_sync.data_provider());
2059   ClientSocketHandle handle;
2060   int rv = handle.Init(
2061       kGroupId, socks_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag1,
2062       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2063       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2064   EXPECT_THAT(rv, IsOk());
2065   EXPECT_TRUE(handle.is_initialized());
2066   EXPECT_TRUE(handle.socket());
2067   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2068             tag1);
2069   EXPECT_TRUE(tagging_client_socket_factory_.GetLastProducedTCPSocket()
2070                   ->tagged_before_connected());
2071 
2072   // Test socket is tagged when reused synchronously.
2073   StreamSocket* socket = handle.socket();
2074   handle.Reset();
2075   rv = handle.Init(
2076       kGroupId, socks_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag2,
2077       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2078       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2079   EXPECT_THAT(rv, IsOk());
2080   EXPECT_TRUE(handle.socket());
2081   EXPECT_TRUE(handle.socket()->IsConnected());
2082   EXPECT_EQ(handle.socket(), socket);
2083   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2084             tag2);
2085   handle.socket()->Disconnect();
2086   handle.Reset();
2087 
2088   // Test socket is tagged when created asynchronously.
2089   SOCKS5MockData data_async(ASYNC);
2090   tagging_client_socket_factory_.AddSocketDataProvider(
2091       data_async.data_provider());
2092   TestCompletionCallback callback;
2093   rv = handle.Init(kGroupId, socks_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW,
2094                    tag1, ClientSocketPool::RespectLimits::ENABLED,
2095                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
2096                    &proxy_pool, NetLogWithSource());
2097   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
2098   EXPECT_THAT(callback.WaitForResult(), IsOk());
2099   EXPECT_TRUE(handle.is_initialized());
2100   EXPECT_TRUE(handle.socket());
2101   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2102             tag1);
2103   EXPECT_TRUE(tagging_client_socket_factory_.GetLastProducedTCPSocket()
2104                   ->tagged_before_connected());
2105 
2106   // Test socket is tagged when reused after being created asynchronously.
2107   socket = handle.socket();
2108   handle.Reset();
2109   rv = handle.Init(
2110       kGroupId, socks_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag2,
2111       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2112       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2113   EXPECT_THAT(rv, IsOk());
2114   EXPECT_TRUE(handle.socket());
2115   EXPECT_TRUE(handle.socket()->IsConnected());
2116   EXPECT_EQ(handle.socket(), socket);
2117   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2118             tag2);
2119 }
2120 
TEST_F(TransportClientSocketPoolTest,TagSSLDirect)2121 TEST_F(TransportClientSocketPoolTest, TagSSLDirect) {
2122   if (!CanGetTaggedBytes()) {
2123     DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
2124     return;
2125   }
2126 
2127   // Start test server.
2128   EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
2129   test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, SSLServerConfig());
2130   test_server.AddDefaultHandlers(base::FilePath());
2131   ASSERT_TRUE(test_server.Start());
2132 
2133   TestCompletionCallback callback;
2134   ClientSocketHandle handle;
2135   int32_t tag_val1 = 0x12345678;
2136   SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
2137   int32_t tag_val2 = 0x87654321;
2138   SocketTag tag2(getuid(), tag_val2);
2139   const ClientSocketPool::GroupId kGroupId(
2140       test_server.host_port_pair(), ClientSocketPool::SocketType::kSsl,
2141       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
2142       false /* disable_secure_dns */);
2143 
2144   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2145       base::MakeRefCounted<ClientSocketPool::SocketParams>(
2146           std::make_unique<SSLConfig>() /* ssl_config_for_origin */,
2147           nullptr /* ssl_config_for_proxy */);
2148 
2149   // Test socket is tagged before connected.
2150   uint64_t old_traffic = GetTaggedBytes(tag_val1);
2151   int rv = handle.Init(
2152       kGroupId, socket_params, base::nullopt /* proxy_annotation_tag */, LOW,
2153       tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
2154       ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(),
2155       NetLogWithSource());
2156   EXPECT_THAT(callback.GetResult(rv), IsOk());
2157   EXPECT_TRUE(handle.socket());
2158   EXPECT_TRUE(handle.socket()->IsConnected());
2159   EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
2160 
2161   // Test reused socket is retagged.
2162   StreamSocket* socket = handle.socket();
2163   handle.Reset();
2164   old_traffic = GetTaggedBytes(tag_val2);
2165   TestCompletionCallback callback2;
2166   rv = handle.Init(kGroupId, socket_params,
2167                    base::nullopt /* proxy_annotation_tag */, LOW, tag2,
2168                    ClientSocketPool::RespectLimits::ENABLED,
2169                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
2170                    pool_for_real_sockets_.get(), NetLogWithSource());
2171   EXPECT_THAT(rv, IsOk());
2172   EXPECT_TRUE(handle.socket());
2173   EXPECT_TRUE(handle.socket()->IsConnected());
2174   EXPECT_EQ(handle.socket(), socket);
2175   const char kRequest[] = "GET / HTTP/1.1\r\n\r\n";
2176   scoped_refptr<IOBuffer> write_buffer =
2177       base::MakeRefCounted<StringIOBuffer>(kRequest);
2178   rv =
2179       handle.socket()->Write(write_buffer.get(), strlen(kRequest),
2180                              callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
2181   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback.GetResult(rv));
2182   scoped_refptr<IOBufferWithSize> read_buffer =
2183       base::MakeRefCounted<IOBufferWithSize>(1);
2184   rv = handle.socket()->Read(read_buffer.get(), read_buffer->size(),
2185                              callback.callback());
2186   EXPECT_EQ(read_buffer->size(), callback.GetResult(rv));
2187   EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
2188   // Disconnect socket to prevent reuse.
2189   handle.socket()->Disconnect();
2190   handle.Reset();
2191 }
2192 
TEST_F(TransportClientSocketPoolTest,TagSSLDirectTwoSockets)2193 TEST_F(TransportClientSocketPoolTest, TagSSLDirectTwoSockets) {
2194   if (!CanGetTaggedBytes()) {
2195     DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
2196     return;
2197   }
2198 
2199   // Start test server.
2200   EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
2201   test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, SSLServerConfig());
2202   test_server.AddDefaultHandlers(base::FilePath());
2203   ASSERT_TRUE(test_server.Start());
2204 
2205   ClientSocketHandle handle;
2206   int32_t tag_val1 = 0x12345678;
2207   SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
2208   int32_t tag_val2 = 0x87654321;
2209   SocketTag tag2(getuid(), tag_val2);
2210   const ClientSocketPool::GroupId kGroupId(
2211       test_server.host_port_pair(), ClientSocketPool::SocketType::kSsl,
2212       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
2213       false /* disable_secure_dns */);
2214   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2215       base::MakeRefCounted<ClientSocketPool::SocketParams>(
2216           std::make_unique<SSLConfig>() /* ssl_config_for_origin */,
2217           nullptr /* ssl_config_for_proxy */);
2218 
2219   // Test connect jobs that are orphaned and then adopted, appropriately apply
2220   // new tag. Request socket with |tag1|.
2221   TestCompletionCallback callback;
2222   int rv = handle.Init(
2223       kGroupId, socket_params, base::nullopt /* proxy_annotation_tag */, LOW,
2224       tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
2225       ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(),
2226       NetLogWithSource());
2227   EXPECT_TRUE(rv == OK || rv == ERR_IO_PENDING) << "Result: " << rv;
2228   // Abort and request socket with |tag2|.
2229   handle.Reset();
2230   TestCompletionCallback callback2;
2231   rv = handle.Init(kGroupId, socket_params,
2232                    base::nullopt /* proxy_annotation_tag */, LOW, tag2,
2233                    ClientSocketPool::RespectLimits::ENABLED,
2234                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
2235                    pool_for_real_sockets_.get(), NetLogWithSource());
2236   EXPECT_THAT(callback2.GetResult(rv), IsOk());
2237   EXPECT_TRUE(handle.socket());
2238   EXPECT_TRUE(handle.socket()->IsConnected());
2239   // Verify socket has |tag2| applied.
2240   uint64_t old_traffic = GetTaggedBytes(tag_val2);
2241   const char kRequest[] = "GET / HTTP/1.1\r\n\r\n";
2242   scoped_refptr<IOBuffer> write_buffer =
2243       base::MakeRefCounted<StringIOBuffer>(kRequest);
2244   rv = handle.socket()->Write(write_buffer.get(), strlen(kRequest),
2245                               callback2.callback(),
2246                               TRAFFIC_ANNOTATION_FOR_TESTS);
2247   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback2.GetResult(rv));
2248   scoped_refptr<IOBufferWithSize> read_buffer =
2249       base::MakeRefCounted<IOBufferWithSize>(1);
2250   rv = handle.socket()->Read(read_buffer.get(), read_buffer->size(),
2251                              callback2.callback());
2252   EXPECT_EQ(read_buffer->size(), callback2.GetResult(rv));
2253   EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
2254 }
2255 
TEST_F(TransportClientSocketPoolTest,TagSSLDirectTwoSocketsFullPool)2256 TEST_F(TransportClientSocketPoolTest, TagSSLDirectTwoSocketsFullPool) {
2257   if (!CanGetTaggedBytes()) {
2258     DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
2259     return;
2260   }
2261 
2262   // Start test server.
2263   EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
2264   test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, SSLServerConfig());
2265   test_server.AddDefaultHandlers(base::FilePath());
2266   ASSERT_TRUE(test_server.Start());
2267 
2268   TestCompletionCallback callback;
2269   ClientSocketHandle handle;
2270   int32_t tag_val1 = 0x12345678;
2271   SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
2272   int32_t tag_val2 = 0x87654321;
2273   SocketTag tag2(getuid(), tag_val2);
2274   const ClientSocketPool::GroupId kGroupId(
2275       test_server.host_port_pair(), ClientSocketPool::SocketType::kSsl,
2276       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
2277       false /* disable_secure_dns */);
2278   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2279       base::MakeRefCounted<ClientSocketPool::SocketParams>(
2280           std::make_unique<SSLConfig>() /* ssl_config_for_origin */,
2281           nullptr /* ssl_config_for_proxy */);
2282 
2283   // Test that sockets paused by a full underlying socket pool are properly
2284   // connected and tagged when underlying pool is freed up.
2285   // Fill up all slots in TCP pool.
2286   ClientSocketHandle tcp_handles[kMaxSocketsPerGroup];
2287   int rv;
2288   for (auto& tcp_handle : tcp_handles) {
2289     rv = tcp_handle.Init(
2290         kGroupId, socket_params, base::nullopt /* proxy_annotation_tag */, LOW,
2291         tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
2292         ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(),
2293         NetLogWithSource());
2294     EXPECT_THAT(callback.GetResult(rv), IsOk());
2295     EXPECT_TRUE(tcp_handle.socket());
2296     EXPECT_TRUE(tcp_handle.socket()->IsConnected());
2297   }
2298   // Request two SSL sockets.
2299   ClientSocketHandle handle_to_be_canceled;
2300   rv = handle_to_be_canceled.Init(
2301       kGroupId, socket_params, base::nullopt /* proxy_annotation_tag */, LOW,
2302       tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
2303       ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(),
2304       NetLogWithSource());
2305   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
2306   rv = handle.Init(kGroupId, socket_params,
2307                    base::nullopt /* proxy_annotation_tag */, LOW, tag2,
2308                    ClientSocketPool::RespectLimits::ENABLED,
2309                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
2310                    pool_for_real_sockets_.get(), NetLogWithSource());
2311   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
2312   // Cancel first request.
2313   handle_to_be_canceled.Reset();
2314   // Disconnect a TCP socket to free up a slot.
2315   tcp_handles[0].socket()->Disconnect();
2316   tcp_handles[0].Reset();
2317   // Verify |handle| gets a valid tagged socket.
2318   EXPECT_THAT(callback.WaitForResult(), IsOk());
2319   EXPECT_TRUE(handle.socket());
2320   EXPECT_TRUE(handle.socket()->IsConnected());
2321   uint64_t old_traffic = GetTaggedBytes(tag_val2);
2322   const char kRequest[] = "GET / HTTP/1.1\r\n\r\n";
2323   scoped_refptr<IOBuffer> write_buffer =
2324       base::MakeRefCounted<StringIOBuffer>(kRequest);
2325   rv =
2326       handle.socket()->Write(write_buffer.get(), strlen(kRequest),
2327                              callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
2328   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback.GetResult(rv));
2329   scoped_refptr<IOBufferWithSize> read_buffer =
2330       base::MakeRefCounted<IOBufferWithSize>(1);
2331   EXPECT_EQ(handle.socket()->Read(read_buffer.get(), read_buffer->size(),
2332                                   callback.callback()),
2333             ERR_IO_PENDING);
2334   EXPECT_THAT(callback.WaitForResult(), read_buffer->size());
2335   EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
2336 }
2337 
TEST_F(TransportClientSocketPoolTest,TagHttpProxyNoTunnel)2338 TEST_F(TransportClientSocketPoolTest, TagHttpProxyNoTunnel) {
2339   SocketTag tag1(SocketTag::UNSET_UID, 0x12345678);
2340   SocketTag tag2(getuid(), 0x87654321);
2341 
2342   TransportClientSocketPool proxy_pool(
2343       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
2344       ProxyServer::FromURI("http://proxy",
2345                            ProxyServer::SCHEME_HTTP /* default_scheme */),
2346       false /* is_for_websockets */, tagging_common_connect_job_params_.get());
2347 
2348   session_deps_.host_resolver->set_synchronous_mode(true);
2349   SequencedSocketData socket_data;
2350   socket_data.set_connect_data(MockConnect(SYNCHRONOUS, OK));
2351   tagging_client_socket_factory_.AddSocketDataProvider(&socket_data);
2352 
2353   const HostPortPair kDestination("www.google.com", 80);
2354   const ClientSocketPool::GroupId kGroupId(
2355       kDestination, ClientSocketPool::SocketType::kHttp,
2356       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
2357       false /* disable_secure_dns */);
2358   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2359       base::MakeRefCounted<ClientSocketPool::SocketParams>(
2360           nullptr /* ssl_config_for_origin */,
2361           nullptr /* ssl_config_for_proxy */);
2362 
2363   // Verify requested socket is tagged properly.
2364   ClientSocketHandle handle;
2365   int rv = handle.Init(
2366       kGroupId, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag1,
2367       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2368       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2369   EXPECT_THAT(rv, IsOk());
2370   EXPECT_TRUE(handle.is_initialized());
2371   ASSERT_TRUE(handle.socket());
2372   EXPECT_TRUE(handle.socket()->IsConnected());
2373   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2374             tag1);
2375   EXPECT_TRUE(tagging_client_socket_factory_.GetLastProducedTCPSocket()
2376                   ->tagged_before_connected());
2377 
2378   // Verify reused socket is retagged properly.
2379   StreamSocket* socket = handle.socket();
2380   handle.Reset();
2381   rv = handle.Init(
2382       kGroupId, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag2,
2383       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2384       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2385   EXPECT_THAT(rv, IsOk());
2386   EXPECT_TRUE(handle.socket());
2387   EXPECT_TRUE(handle.socket()->IsConnected());
2388   EXPECT_EQ(handle.socket(), socket);
2389   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2390             tag2);
2391   handle.socket()->Disconnect();
2392   handle.Reset();
2393 }
2394 
2395 // This creates a tunnel without SSL on top of it - something not normally done,
2396 // though some non-HTTP consumers use this path to create tunnels for other
2397 // uses.
TEST_F(TransportClientSocketPoolTest,TagHttpProxyTunnel)2398 TEST_F(TransportClientSocketPoolTest, TagHttpProxyTunnel) {
2399   SocketTag tag1(SocketTag::UNSET_UID, 0x12345678);
2400   SocketTag tag2(getuid(), 0x87654321);
2401 
2402   TransportClientSocketPool proxy_pool(
2403       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
2404       ProxyServer::FromURI("http://proxy",
2405                            ProxyServer::SCHEME_HTTP /* default_scheme */),
2406       false /* is_for_websockets */, tagging_common_connect_job_params_.get());
2407 
2408   session_deps_.host_resolver->set_synchronous_mode(true);
2409 
2410   std::string request =
2411       "CONNECT www.google.com:443 HTTP/1.1\r\n"
2412       "Host: www.google.com:443\r\n"
2413       "Proxy-Connection: keep-alive\r\n\r\n";
2414   MockWrite writes[] = {
2415       MockWrite(SYNCHRONOUS, 0, request.c_str()),
2416   };
2417   MockRead reads[] = {
2418       MockRead(SYNCHRONOUS, 1, "HTTP/1.1 200 Connection Established\r\n\r\n"),
2419   };
2420 
2421   SequencedSocketData socket_data(MockConnect(SYNCHRONOUS, OK), reads, writes);
2422   tagging_client_socket_factory_.AddSocketDataProvider(&socket_data);
2423   SSLSocketDataProvider ssl_data(SYNCHRONOUS, OK);
2424   tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data);
2425 
2426   const HostPortPair kDestination("www.google.com", 443);
2427   const ClientSocketPool::GroupId kGroupId(
2428       kDestination, ClientSocketPool::SocketType::kSsl,
2429       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
2430       false /* disable_secure_dns */);
2431 
2432   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2433       base::MakeRefCounted<ClientSocketPool::SocketParams>(
2434           std::make_unique<SSLConfig>() /* ssl_config_for_origin */,
2435           nullptr /* ssl_config_for_proxy */);
2436 
2437   // Verify requested socket is tagged properly.
2438   ClientSocketHandle handle;
2439   int rv = handle.Init(
2440       kGroupId, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag1,
2441       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2442       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2443   EXPECT_THAT(rv, IsOk());
2444   EXPECT_TRUE(handle.is_initialized());
2445   ASSERT_TRUE(handle.socket());
2446   EXPECT_TRUE(handle.socket()->IsConnected());
2447   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2448             tag1);
2449   EXPECT_TRUE(tagging_client_socket_factory_.GetLastProducedTCPSocket()
2450                   ->tagged_before_connected());
2451 
2452   // Verify reused socket is retagged properly.
2453   StreamSocket* socket = handle.socket();
2454   handle.Reset();
2455   rv = handle.Init(
2456       kGroupId, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag2,
2457       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2458       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2459   EXPECT_THAT(rv, IsOk());
2460   EXPECT_TRUE(handle.socket());
2461   EXPECT_TRUE(handle.socket()->IsConnected());
2462   EXPECT_EQ(handle.socket(), socket);
2463   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2464             tag2);
2465   handle.socket()->Disconnect();
2466   handle.Reset();
2467 }
2468 
2469 #endif  // defined(OS_ANDROID)
2470 
2471 // Class that enables tests to set mock time.
2472 class TransportClientSocketPoolMockNowSourceTest
2473     : public TransportClientSocketPoolTest {
2474  protected:
TransportClientSocketPoolMockNowSourceTest()2475   TransportClientSocketPoolMockNowSourceTest()
2476       : TransportClientSocketPoolTest(
2477             base::test::TaskEnvironment::TimeSource::MOCK_TIME) {}
2478 
2479  private:
2480   DISALLOW_COPY_AND_ASSIGN(TransportClientSocketPoolMockNowSourceTest);
2481 };
2482 
2483 // Tests that changing the idle unused socket timeout using the experiment
2484 // works. The test first sets the value of timeout duration for idle sockets.
2485 // Next, it opens |kNumIdleSockets| sockets. To trigger the cleanup of idle
2486 // sockets that may have timedout, it then opens one more socket. This is
2487 // required since requesting a new socket triggers cleanup of idle timedout
2488 // sockets. Next, the test verifies the count of idle timed-out sockets.
TEST_F(TransportClientSocketPoolMockNowSourceTest,IdleUnusedSocketTimeout)2489 TEST_F(TransportClientSocketPoolMockNowSourceTest, IdleUnusedSocketTimeout) {
2490   const HostPortPair kHostPortPair1("www.foo.com", 80);
2491   const HostPortPair kHostPortPair2("www.bar.com", 80);
2492 
2493   const struct {
2494     bool use_first_socket;
2495     int fast_forward_seconds;
2496     int unused_idle_socket_timeout_seconds;
2497     bool expect_idle_socket;
2498   } kTests[] = {
2499       // When the clock is fast forwarded by a duration longer than
2500       // |unused_idle_socket_timeout_seconds|, the first unused idle socket is
2501       // expected to be timedout, and cleared.
2502       {false, 0, 0, false},
2503       {false, 9, 10, true},
2504       {false, 11, 10, false},
2505       {false, 19, 20, true},
2506       {false, 21, 20, false},
2507       // If |use_first_socket| is true, then the test would write some data to
2508       // the socket, thereby marking it as "used". Thereafter, this idle socket
2509       // should be timedout based on used idle socket timeout, and changing
2510       // |unused_idle_socket_timeout_seconds| should not affect the
2511       // |expected_idle_sockets|.
2512       {true, 0, 0, true},
2513       {true, 9, 10, true},
2514       {true, 11, 10, true},
2515       {true, 19, 20, true},
2516       {true, 21, 20, true},
2517   };
2518 
2519   for (const auto& test : kTests) {
2520     SpdySessionDependencies session_deps(
2521         ConfiguredProxyResolutionService::CreateDirect());
2522     std::unique_ptr<HttpNetworkSession> session(
2523         SpdySessionDependencies::SpdyCreateSession(&session_deps));
2524 
2525     base::test::ScopedFeatureList scoped_feature_list_;
2526     std::map<std::string, std::string> parameters;
2527     parameters["unused_idle_socket_timeout_seconds"] =
2528         base::NumberToString(test.unused_idle_socket_timeout_seconds);
2529     scoped_feature_list_.InitAndEnableFeatureWithParameters(
2530         net::features::kNetUnusedIdleSocketTimeout, parameters);
2531 
2532     const char kWriteData[] = "1";
2533     const MockWrite kWrites[] = {MockWrite(SYNCHRONOUS, kWriteData)};
2534 
2535     SequencedSocketData provider_socket_1(MockConnect(ASYNC, OK),
2536                                           base::span<MockRead>(), kWrites);
2537     {
2538       // Create 1 socket.
2539       scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2540           base::MakeRefCounted<ClientSocketPool::SocketParams>(
2541               nullptr /* ssl_config_for_origin */,
2542               nullptr /* ssl_config_for_proxy */);
2543       session_deps.socket_factory->AddSocketDataProvider(&provider_socket_1);
2544       ClientSocketHandle connection;
2545       TestCompletionCallback callback;
2546       int rv = connection.Init(
2547           ClientSocketPool::GroupId(
2548               kHostPortPair1, ClientSocketPool::SocketType::kHttp,
2549               PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
2550               false /* disable_secure_dns */),
2551           ClientSocketPool::SocketParams::CreateForHttpForTesting(),
2552           base::nullopt /* proxy_annotation_tag */, MEDIUM, SocketTag(),
2553           ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
2554           ClientSocketPool::ProxyAuthCallback(),
2555           session->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL,
2556                                  ProxyServer::Direct()),
2557           NetLogWithSource());
2558       EXPECT_THAT(callback.GetResult(rv), IsOk());
2559       EXPECT_FALSE(connection.socket()->WasEverUsed());
2560 
2561       // Writing some data to the socket should set WasEverUsed.
2562       if (test.use_first_socket) {
2563         // Generate |socket_write_data| from kMockWriteData by appending null
2564         // character to the latter.
2565         auto write_buffer = base::MakeRefCounted<StringIOBuffer>(kWriteData);
2566         TestCompletionCallback write_callback;
2567         int rv = connection.socket()->Write(
2568             write_buffer.get(), write_buffer->size(), write_callback.callback(),
2569             TRAFFIC_ANNOTATION_FOR_TESTS);
2570         EXPECT_EQ(rv, 1);
2571         EXPECT_TRUE(connection.socket()->WasEverUsed());
2572       }
2573     }
2574 
2575     EXPECT_EQ(1, session
2576                      ->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL,
2577                                      ProxyServer::Direct())
2578                      ->IdleSocketCount());
2579 
2580     // Moving the clock forward may cause the idle socket to be timedout.
2581     FastForwardBy(base::TimeDelta::FromSeconds(test.fast_forward_seconds));
2582 
2583     {
2584       // Request a new socket to trigger cleanup of idle timedout sockets.
2585       scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2586           base::MakeRefCounted<ClientSocketPool::SocketParams>(
2587               nullptr /* ssl_config_for_origin */,
2588               nullptr /* ssl_config_for_proxy */);
2589       SequencedSocketData provider_socket_2(MockConnect(ASYNC, OK),
2590                                             base::span<MockRead>(),
2591                                             base::span<MockWrite>());
2592       session_deps.socket_factory->AddSocketDataProvider(&provider_socket_2);
2593       ClientSocketHandle connection;
2594       TestCompletionCallback callback;
2595       int rv = connection.Init(
2596           ClientSocketPool::GroupId(
2597               kHostPortPair2, ClientSocketPool::SocketType::kHttp,
2598               PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(),
2599               false /* disable_secure_dns */),
2600           socket_params, base::nullopt /* proxy_annotation_tag */, MEDIUM,
2601           SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
2602           callback.callback(), ClientSocketPool::ProxyAuthCallback(),
2603           session->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL,
2604                                  ProxyServer::Direct()),
2605           NetLogWithSource());
2606       EXPECT_THAT(callback.GetResult(rv), IsOk());
2607       connection.socket()->Disconnect();
2608     }
2609 
2610     EXPECT_EQ(test.expect_idle_socket ? 1 : 0,
2611               session
2612                   ->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL,
2613                                   ProxyServer::Direct())
2614                   ->IdleSocketCount());
2615   }
2616 }
2617 
2618 }  // namespace
2619 
2620 }  // namespace net
2621