Update V8 to version 4.6.48.
[chromium-blink-merge.git] / net / socket / transport_client_socket_pool.h
blobf2016708f6e149529cfc57599883089fec4846dd
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.
5 #ifndef NET_SOCKET_TRANSPORT_CLIENT_SOCKET_POOL_H_
6 #define NET_SOCKET_TRANSPORT_CLIENT_SOCKET_POOL_H_
8 #include <string>
10 #include "base/basictypes.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/time/time.h"
14 #include "base/timer/timer.h"
15 #include "net/base/host_port_pair.h"
16 #include "net/dns/host_resolver.h"
17 #include "net/dns/single_request_host_resolver.h"
18 #include "net/socket/client_socket_pool.h"
19 #include "net/socket/client_socket_pool_base.h"
20 #include "net/socket/connection_attempts.h"
22 namespace net {
24 class ClientSocketFactory;
26 typedef base::Callback<int(const AddressList&, const BoundNetLog& net_log)>
27 OnHostResolutionCallback;
29 class NET_EXPORT_PRIVATE TransportSocketParams
30 : public base::RefCounted<TransportSocketParams> {
31 public:
32 // CombineConnectAndWrite currently translates to using TCP FastOpen.
33 // TCP FastOpen should not be used if the first write to the socket may
34 // be non-idempotent, as the underlying socket could retransmit the data
35 // on failure of the first transmission.
36 // NOTE: Currently, COMBINE_CONNECT_AND_WRITE_DESIRED is used if the data in
37 // the write is known to be idempotent, and COMBINE_CONNECT_AND_WRITE_DEFAULT
38 // is used as a default for other cases (including non-idempotent writes).
39 enum CombineConnectAndWritePolicy {
40 COMBINE_CONNECT_AND_WRITE_DEFAULT, // Default policy, implemented in
41 // TransportSocketParams constructor.
42 COMBINE_CONNECT_AND_WRITE_DESIRED, // Combine if supported by socket.
43 COMBINE_CONNECT_AND_WRITE_PROHIBITED // Do not combine.
46 // |host_resolution_callback| will be invoked after the the hostname is
47 // resolved. If |host_resolution_callback| does not return OK, then the
48 // connection will be aborted with that value. |combine_connect_and_write|
49 // defines the policy for use of TCP FastOpen on this socket.
50 TransportSocketParams(
51 const HostPortPair& host_port_pair,
52 bool disable_resolver_cache,
53 bool ignore_limits,
54 const OnHostResolutionCallback& host_resolution_callback,
55 CombineConnectAndWritePolicy combine_connect_and_write);
57 const HostResolver::RequestInfo& destination() const { return destination_; }
58 bool ignore_limits() const { return ignore_limits_; }
59 const OnHostResolutionCallback& host_resolution_callback() const {
60 return host_resolution_callback_;
63 CombineConnectAndWritePolicy combine_connect_and_write() const {
64 return combine_connect_and_write_;
67 private:
68 friend class base::RefCounted<TransportSocketParams>;
69 ~TransportSocketParams();
71 HostResolver::RequestInfo destination_;
72 bool ignore_limits_;
73 const OnHostResolutionCallback host_resolution_callback_;
74 CombineConnectAndWritePolicy combine_connect_and_write_;
76 DISALLOW_COPY_AND_ASSIGN(TransportSocketParams);
79 // Common data and logic shared between TransportConnectJob and
80 // WebSocketTransportConnectJob.
81 class NET_EXPORT_PRIVATE TransportConnectJobHelper {
82 public:
83 enum State {
84 STATE_RESOLVE_HOST,
85 STATE_RESOLVE_HOST_COMPLETE,
86 STATE_TRANSPORT_CONNECT,
87 STATE_TRANSPORT_CONNECT_COMPLETE,
88 STATE_NONE,
91 // For recording the connection time in the appropriate bucket.
92 enum ConnectionLatencyHistogram {
93 CONNECTION_LATENCY_UNKNOWN,
94 CONNECTION_LATENCY_IPV4_WINS_RACE,
95 CONNECTION_LATENCY_IPV4_NO_RACE,
96 CONNECTION_LATENCY_IPV6_RACEABLE,
97 CONNECTION_LATENCY_IPV6_SOLO,
100 TransportConnectJobHelper(const scoped_refptr<TransportSocketParams>& params,
101 ClientSocketFactory* client_socket_factory,
102 HostResolver* host_resolver,
103 LoadTimingInfo::ConnectTiming* connect_timing);
104 ~TransportConnectJobHelper();
106 ClientSocketFactory* client_socket_factory() {
107 return client_socket_factory_;
110 const AddressList& addresses() const { return addresses_; }
111 State next_state() const { return next_state_; }
112 void set_next_state(State next_state) { next_state_ = next_state; }
113 CompletionCallback on_io_complete() const { return on_io_complete_; }
114 const TransportSocketParams* params() { return params_.get(); }
116 int DoResolveHost(RequestPriority priority, const BoundNetLog& net_log);
117 int DoResolveHostComplete(int result, const BoundNetLog& net_log);
119 template <class T>
120 int DoConnectInternal(T* job);
122 template <class T>
123 void SetOnIOComplete(T* job);
125 template <class T>
126 void OnIOComplete(T* job, int result);
128 // Record the histograms Net.DNS_Resolution_And_TCP_Connection_Latency2 and
129 // Net.TCP_Connection_Latency and return the connect duration.
130 base::TimeDelta HistogramDuration(ConnectionLatencyHistogram race_result);
132 static const int kIPv6FallbackTimerInMs;
134 private:
135 template <class T>
136 int DoLoop(T* job, int result);
138 scoped_refptr<TransportSocketParams> params_;
139 ClientSocketFactory* const client_socket_factory_;
140 SingleRequestHostResolver resolver_;
141 AddressList addresses_;
142 State next_state_;
143 CompletionCallback on_io_complete_;
144 LoadTimingInfo::ConnectTiming* connect_timing_;
146 DISALLOW_COPY_AND_ASSIGN(TransportConnectJobHelper);
149 // TransportConnectJob handles the host resolution necessary for socket creation
150 // and the transport (likely TCP) connect. TransportConnectJob also has fallback
151 // logic for IPv6 connect() timeouts (which may happen due to networks / routers
152 // with broken IPv6 support). Those timeouts take 20s, so rather than make the
153 // user wait 20s for the timeout to fire, we use a fallback timer
154 // (kIPv6FallbackTimerInMs) and start a connect() to a IPv4 address if the timer
155 // fires. Then we race the IPv4 connect() against the IPv6 connect() (which has
156 // a headstart) and return the one that completes first to the socket pool.
157 class NET_EXPORT_PRIVATE TransportConnectJob : public ConnectJob {
158 public:
159 TransportConnectJob(const std::string& group_name,
160 RequestPriority priority,
161 const scoped_refptr<TransportSocketParams>& params,
162 base::TimeDelta timeout_duration,
163 ClientSocketFactory* client_socket_factory,
164 HostResolver* host_resolver,
165 Delegate* delegate,
166 NetLog* net_log);
167 ~TransportConnectJob() override;
169 // ConnectJob methods.
170 LoadState GetLoadState() const override;
171 void GetAdditionalErrorState(ClientSocketHandle* handle) override;
173 // Rolls |addrlist| forward until the first IPv4 address, if any.
174 // WARNING: this method should only be used to implement the prefer-IPv4 hack.
175 static void MakeAddressListStartWithIPv4(AddressList* addrlist);
177 private:
178 enum ConnectInterval {
179 CONNECT_INTERVAL_LE_10MS,
180 CONNECT_INTERVAL_LE_20MS,
181 CONNECT_INTERVAL_GT_20MS,
184 friend class TransportConnectJobHelper;
186 int DoResolveHost();
187 int DoResolveHostComplete(int result);
188 int DoTransportConnect();
189 int DoTransportConnectComplete(int result);
191 // Not part of the state machine.
192 void DoIPv6FallbackTransportConnect();
193 void DoIPv6FallbackTransportConnectComplete(int result);
195 // Begins the host resolution and the TCP connect. Returns OK on success
196 // and ERR_IO_PENDING if it cannot immediately service the request.
197 // Otherwise, it returns a net error code.
198 int ConnectInternal() override;
200 void CopyConnectionAttemptsFromSockets();
202 TransportConnectJobHelper helper_;
204 scoped_ptr<StreamSocket> transport_socket_;
206 scoped_ptr<StreamSocket> fallback_transport_socket_;
207 scoped_ptr<AddressList> fallback_addresses_;
208 base::TimeTicks fallback_connect_start_time_;
209 base::OneShotTimer<TransportConnectJob> fallback_timer_;
211 // Track the interval between this connect and previous connect.
212 ConnectInterval interval_between_connects_;
214 int resolve_result_;
216 // Used in the failure case to save connection attempts made on the main and
217 // fallback sockets and pass them on in |GetAdditionalErrorState|. (In the
218 // success case, connection attempts are passed through the returned socket;
219 // attempts are copied from the other socket, if one exists, into it before
220 // it is returned.)
221 ConnectionAttempts connection_attempts_;
222 ConnectionAttempts fallback_connection_attempts_;
224 DISALLOW_COPY_AND_ASSIGN(TransportConnectJob);
227 class NET_EXPORT_PRIVATE TransportClientSocketPool : public ClientSocketPool {
228 public:
229 typedef TransportSocketParams SocketParams;
231 TransportClientSocketPool(
232 int max_sockets,
233 int max_sockets_per_group,
234 HostResolver* host_resolver,
235 ClientSocketFactory* client_socket_factory,
236 NetLog* net_log);
238 ~TransportClientSocketPool() override;
240 // ClientSocketPool implementation.
241 int RequestSocket(const std::string& group_name,
242 const void* resolve_info,
243 RequestPriority priority,
244 ClientSocketHandle* handle,
245 const CompletionCallback& callback,
246 const BoundNetLog& net_log) override;
247 void RequestSockets(const std::string& group_name,
248 const void* params,
249 int num_sockets,
250 const BoundNetLog& net_log) override;
251 void CancelRequest(const std::string& group_name,
252 ClientSocketHandle* handle) override;
253 void ReleaseSocket(const std::string& group_name,
254 scoped_ptr<StreamSocket> socket,
255 int id) override;
256 void FlushWithError(int error) override;
257 void CloseIdleSockets() override;
258 int IdleSocketCount() const override;
259 int IdleSocketCountInGroup(const std::string& group_name) const override;
260 LoadState GetLoadState(const std::string& group_name,
261 const ClientSocketHandle* handle) const override;
262 scoped_ptr<base::DictionaryValue> GetInfoAsValue(
263 const std::string& name,
264 const std::string& type,
265 bool include_nested_pools) const override;
266 base::TimeDelta ConnectionTimeout() const override;
268 // HigherLayeredPool implementation.
269 bool IsStalled() const override;
270 void AddHigherLayeredPool(HigherLayeredPool* higher_pool) override;
271 void RemoveHigherLayeredPool(HigherLayeredPool* higher_pool) override;
273 protected:
274 // Methods shared with WebSocketTransportClientSocketPool
275 void NetLogTcpClientSocketPoolRequestedSocket(
276 const BoundNetLog& net_log,
277 const scoped_refptr<TransportSocketParams>* casted_params);
279 private:
280 typedef ClientSocketPoolBase<TransportSocketParams> PoolBase;
282 class TransportConnectJobFactory
283 : public PoolBase::ConnectJobFactory {
284 public:
285 TransportConnectJobFactory(ClientSocketFactory* client_socket_factory,
286 HostResolver* host_resolver,
287 NetLog* net_log)
288 : client_socket_factory_(client_socket_factory),
289 host_resolver_(host_resolver),
290 net_log_(net_log) {}
292 ~TransportConnectJobFactory() override {}
294 // ClientSocketPoolBase::ConnectJobFactory methods.
296 scoped_ptr<ConnectJob> NewConnectJob(
297 const std::string& group_name,
298 const PoolBase::Request& request,
299 ConnectJob::Delegate* delegate) const override;
301 base::TimeDelta ConnectionTimeout() const override;
303 private:
304 ClientSocketFactory* const client_socket_factory_;
305 HostResolver* const host_resolver_;
306 NetLog* net_log_;
308 DISALLOW_COPY_AND_ASSIGN(TransportConnectJobFactory);
311 PoolBase base_;
313 DISALLOW_COPY_AND_ASSIGN(TransportClientSocketPool);
316 template <class T>
317 int TransportConnectJobHelper::DoConnectInternal(T* job) {
318 next_state_ = STATE_RESOLVE_HOST;
319 return this->DoLoop(job, OK);
322 template <class T>
323 void TransportConnectJobHelper::SetOnIOComplete(T* job) {
324 // These usages of base::Unretained() are safe because IO callbacks are
325 // guaranteed not to be called after the object is destroyed.
326 on_io_complete_ = base::Bind(&TransportConnectJobHelper::OnIOComplete<T>,
327 base::Unretained(this),
328 base::Unretained(job));
331 template <class T>
332 void TransportConnectJobHelper::OnIOComplete(T* job, int result) {
333 result = this->DoLoop(job, result);
334 if (result != ERR_IO_PENDING)
335 job->NotifyDelegateOfCompletion(result); // Deletes |job| and |this|
338 template <class T>
339 int TransportConnectJobHelper::DoLoop(T* job, int result) {
340 DCHECK_NE(next_state_, STATE_NONE);
342 int rv = result;
343 do {
344 State state = next_state_;
345 next_state_ = STATE_NONE;
346 switch (state) {
347 case STATE_RESOLVE_HOST:
348 DCHECK_EQ(OK, rv);
349 rv = job->DoResolveHost();
350 break;
351 case STATE_RESOLVE_HOST_COMPLETE:
352 rv = job->DoResolveHostComplete(rv);
353 break;
354 case STATE_TRANSPORT_CONNECT:
355 DCHECK_EQ(OK, rv);
356 rv = job->DoTransportConnect();
357 break;
358 case STATE_TRANSPORT_CONNECT_COMPLETE:
359 rv = job->DoTransportConnectComplete(rv);
360 break;
361 default:
362 NOTREACHED();
363 rv = ERR_FAILED;
364 break;
366 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
368 return rv;
371 } // namespace net
373 #endif // NET_SOCKET_TRANSPORT_CLIENT_SOCKET_POOL_H_