summaryrefslogtreecommitdiffstats
path: root/net/socket/tcp_client_socket_pool.cc
blob: a4c43e4d9383f1db9f9badc8c859722ed9498bf8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Copyright (c) 2011, 2012 Code Aurora Forum. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/socket/tcp_client_socket_pool.h"

#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/string_util.h"
#include "base/time.h"
#include "net/base/net_log.h"
#include "net/base/net_errors.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/client_socket_pool_base.h"
#include "net/socket/tcp_client_socket.h"

using base::TimeDelta;

namespace net {

TCPSocketParams::TCPSocketParams(const HostPortPair& host_port_pair,
                                 RequestPriority priority, const GURL& referrer,
                                 bool disable_resolver_cache, bool ignore_limits)
    : destination_(host_port_pair)
#ifdef ANDROID
      , ignore_limits_(ignore_limits),
      valid_uid_(false),
      calling_uid_(0)
#endif
    {
  Initialize(priority, referrer, disable_resolver_cache);
}

// TODO(willchan): Update all unittests so we don't need this.
TCPSocketParams::TCPSocketParams(const std::string& host, int port,
                                 RequestPriority priority, const GURL& referrer,
                                 bool disable_resolver_cache)
    : destination_(HostPortPair(host, port))
#ifdef ANDROID
      , ignore_limits_(false),
      valid_uid_(false),
      calling_uid_(0)
#endif
    {
  Initialize(priority, referrer, disable_resolver_cache);
}

TCPSocketParams::~TCPSocketParams() {}

void TCPSocketParams::Initialize(RequestPriority priority,
                                 const GURL& referrer,
                                 bool disable_resolver_cache) {
  // The referrer is used by the DNS prefetch system to correlate resolutions
  // with the page that triggered them. It doesn't impact the actual addresses
  // that we resolve to.
  destination_.set_referrer(referrer);
  destination_.set_priority(priority);
  if (disable_resolver_cache)
    destination_.set_allow_cached_response(false);
}

#ifdef ANDROID
bool TCPSocketParams::getUID(uid_t *uid) const {
  if (!valid_uid_) {
    return false;
  }
  *uid = calling_uid_;
  return true;
}

void TCPSocketParams::setUID(uid_t uid) {
  valid_uid_ = true;
  calling_uid_ = uid;
}
#endif

// TCPConnectJobs will time out after this many seconds.  Note this is the total
// time, including both host resolution and TCP connect() times.
//
// TODO(eroman): The use of this constant needs to be re-evaluated. The time
// needed for TCPClientSocketXXX::Connect() can be arbitrarily long, since
// the address list may contain many alternatives, and most of those may
// timeout. Even worse, the per-connect timeout threshold varies greatly
// between systems (anywhere from 20 seconds to 190 seconds).
// See comment #12 at http://crbug.com/23364 for specifics.
static const int kTCPConnectJobTimeoutInSeconds = 240;  // 4 minutes.

TCPConnectJob::TCPConnectJob(
    const std::string& group_name,
    const scoped_refptr<TCPSocketParams>& params,
    base::TimeDelta timeout_duration,
    ClientSocketFactory* client_socket_factory,
    HostResolver* host_resolver,
    Delegate* delegate,
    NetLog* net_log)
    : ConnectJob(group_name, timeout_duration, delegate,
                 BoundNetLog::Make(net_log, NetLog::SOURCE_CONNECT_JOB)),
      params_(params),
      client_socket_factory_(client_socket_factory),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          callback_(this,
                    &TCPConnectJob::OnIOComplete)),
      resolver_(host_resolver) {}

TCPConnectJob::~TCPConnectJob() {
  // We don't worry about cancelling the host resolution and TCP connect, since
  // ~SingleRequestHostResolver and ~ClientSocket will take care of it.
}

LoadState TCPConnectJob::GetLoadState() const {
  switch (next_state_) {
    case STATE_RESOLVE_HOST:
    case STATE_RESOLVE_HOST_COMPLETE:
      return LOAD_STATE_RESOLVING_HOST;
    case STATE_TCP_CONNECT:
    case STATE_TCP_CONNECT_COMPLETE:
      return LOAD_STATE_CONNECTING;
    default:
      NOTREACHED();
      return LOAD_STATE_IDLE;
  }
}

void TCPConnectJob::OnIOComplete(int result) {
  int rv = DoLoop(result);
  if (rv != ERR_IO_PENDING)
    NotifyDelegateOfCompletion(rv);  // Deletes |this|
}

int TCPConnectJob::DoLoop(int result) {
  DCHECK_NE(next_state_, STATE_NONE);

  int rv = result;
  do {
    State state = next_state_;
    next_state_ = STATE_NONE;
    switch (state) {
      case STATE_RESOLVE_HOST:
        DCHECK_EQ(OK, rv);
        rv = DoResolveHost();
        break;
      case STATE_RESOLVE_HOST_COMPLETE:
        rv = DoResolveHostComplete(rv);
        break;
      case STATE_TCP_CONNECT:
        DCHECK_EQ(OK, rv);
        rv = DoTCPConnect();
        break;
      case STATE_TCP_CONNECT_COMPLETE:
        rv = DoTCPConnectComplete(rv);
        break;
      default:
        NOTREACHED();
        rv = ERR_FAILED;
        break;
    }
  } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);

  return rv;
}

int TCPConnectJob::DoResolveHost() {
  next_state_ = STATE_RESOLVE_HOST_COMPLETE;
  return resolver_.Resolve(params_->destination(), &addresses_, &callback_,
                           net_log());
}

int TCPConnectJob::DoResolveHostComplete(int result) {
  if (result == OK)
    next_state_ = STATE_TCP_CONNECT;
  return result;
}

int TCPConnectJob::DoTCPConnect() {
  next_state_ = STATE_TCP_CONNECT_COMPLETE;
  set_socket(client_socket_factory_->CreateTCPClientSocket(
        addresses_, net_log().net_log(), net_log().source()));
  connect_start_time_ = base::TimeTicks::Now();

#ifdef ANDROID
  uid_t calling_uid = 0;
  bool valid_uid = params_->getUID(&calling_uid);
#endif

  return socket()->Connect(&callback_,
#ifdef ANDROID
                           params_->ignore_limits(),
                           valid_uid,
                           calling_uid
#endif
                          );
}

int TCPConnectJob::DoTCPConnectComplete(int result) {
  if (result == OK) {
    DCHECK(connect_start_time_ != base::TimeTicks());
    DCHECK(start_time_ != base::TimeTicks());
    base::TimeTicks now = base::TimeTicks::Now();
    base::TimeDelta total_duration = now - start_time_;
    UMA_HISTOGRAM_CUSTOM_TIMES(
        "Net.DNS_Resolution_And_TCP_Connection_Latency2",
        total_duration,
        base::TimeDelta::FromMilliseconds(1),
        base::TimeDelta::FromMinutes(10),
        100);

    base::TimeDelta connect_duration = now - connect_start_time_;
    UMA_HISTOGRAM_CUSTOM_TIMES("Net.TCP_Connection_Latency",
        connect_duration,
        base::TimeDelta::FromMilliseconds(1),
        base::TimeDelta::FromMinutes(10),
        100);
  } else {
    // Delete the socket on error.
    set_socket(NULL);
  }

  return result;
}

int TCPConnectJob::ConnectInternal() {
  next_state_ = STATE_RESOLVE_HOST;
  start_time_ = base::TimeTicks::Now();
  return DoLoop(OK);
}

ConnectJob* TCPClientSocketPool::TCPConnectJobFactory::NewConnectJob(
    const std::string& group_name,
    const PoolBase::Request& request,
    ConnectJob::Delegate* delegate) const {
  return new TCPConnectJob(group_name, request.params(), ConnectionTimeout(),
                           client_socket_factory_, host_resolver_, delegate,
                           net_log_);
}

base::TimeDelta
    TCPClientSocketPool::TCPConnectJobFactory::ConnectionTimeout() const {
  return base::TimeDelta::FromSeconds(kTCPConnectJobTimeoutInSeconds);
}

TCPClientSocketPool::TCPClientSocketPool(
    int max_sockets,
    int max_sockets_per_group,
    ClientSocketPoolHistograms* histograms,
    HostResolver* host_resolver,
    ClientSocketFactory* client_socket_factory,
    NetLog* net_log,
    HttpNetworkSession *network_session)
    : base_(max_sockets, max_sockets_per_group, histograms,
            base::TimeDelta::FromSeconds(
                ClientSocketPool::unused_idle_socket_timeout()),
            base::TimeDelta::FromSeconds(kUsedIdleSocketTimeout),
            new TCPConnectJobFactory(client_socket_factory,
                                     host_resolver, net_log),
            network_session) {
  base_.EnableConnectBackupJobs();
}

TCPClientSocketPool::~TCPClientSocketPool() {}

int TCPClientSocketPool::RequestSocket(
    const std::string& group_name,
    const void* params,
    RequestPriority priority,
    ClientSocketHandle* handle,
    CompletionCallback* callback,
    const BoundNetLog& net_log) {
  const scoped_refptr<TCPSocketParams>* casted_params =
      static_cast<const scoped_refptr<TCPSocketParams>*>(params);

  if (net_log.IsLoggingAllEvents()) {
    // TODO(eroman): Split out the host and port parameters.
    net_log.AddEvent(
        NetLog::TYPE_TCP_CLIENT_SOCKET_POOL_REQUESTED_SOCKET,
        make_scoped_refptr(new NetLogStringParameter(
            "host_and_port",
            casted_params->get()->destination().host_port_pair().ToString())));
  }

  return base_.RequestSocket(group_name, *casted_params, priority, handle,
                             callback, net_log);
}

void TCPClientSocketPool::RequestSockets(
    const std::string& group_name,
    const void* params,
    int num_sockets,
    const BoundNetLog& net_log) {
  const scoped_refptr<TCPSocketParams>* casted_params =
      static_cast<const scoped_refptr<TCPSocketParams>*>(params);

  if (net_log.IsLoggingAllEvents()) {
    // TODO(eroman): Split out the host and port parameters.
    net_log.AddEvent(
        NetLog::TYPE_TCP_CLIENT_SOCKET_POOL_REQUESTED_SOCKETS,
        make_scoped_refptr(new NetLogStringParameter(
            "host_and_port",
            casted_params->get()->destination().host_port_pair().ToString())));
  }

  base_.RequestSockets(group_name, *casted_params, num_sockets, net_log);
}

void TCPClientSocketPool::CancelRequest(
    const std::string& group_name,
    ClientSocketHandle* handle) {
  base_.CancelRequest(group_name, handle);
}

void TCPClientSocketPool::ReleaseSocket(
    const std::string& group_name,
    ClientSocket* socket,
    int id) {
  base_.ReleaseSocket(group_name, socket, id);
}

void TCPClientSocketPool::Flush() {
  base_.Flush();
}

void TCPClientSocketPool::CloseIdleSockets() {
  base_.CloseIdleSockets();
}

int TCPClientSocketPool::IdleSocketCount() const {
  return base_.idle_socket_count();
}

int TCPClientSocketPool::IdleSocketCountInGroup(
    const std::string& group_name) const {
  return base_.IdleSocketCountInGroup(group_name);
}

LoadState TCPClientSocketPool::GetLoadState(
    const std::string& group_name, const ClientSocketHandle* handle) const {
  return base_.GetLoadState(group_name, handle);
}

DictionaryValue* TCPClientSocketPool::GetInfoAsValue(
    const std::string& name,
    const std::string& type,
    bool include_nested_pools) const {
  return base_.GetInfoAsValue(name, type);
}

base::TimeDelta TCPClientSocketPool::ConnectionTimeout() const {
  return base_.ConnectionTimeout();
}

ClientSocketPoolHistograms* TCPClientSocketPool::histograms() const {
  return base_.histograms();
}

}  // namespace net