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_
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"
23 class ClientSocketFactory
;
25 typedef base::Callback
<int(const AddressList
&, const BoundNetLog
& net_log
)>
26 OnHostResolutionCallback
;
28 class NET_EXPORT_PRIVATE TransportSocketParams
29 : public base::RefCounted
<TransportSocketParams
> {
31 // CombineConnectAndWrite currently translates to using TCP FastOpen.
32 // TCP FastOpen should not be used if the first write to the socket may
33 // be non-idempotent, as the underlying socket could retransmit the data
34 // on failure of the first transmission.
35 // NOTE: Currently, COMBINE_CONNECT_AND_WRITE_DESIRED is used if the data in
36 // the write is known to be idempotent, and COMBINE_CONNECT_AND_WRITE_DEFAULT
37 // is used as a default for other cases (including non-idempotent writes).
38 enum CombineConnectAndWritePolicy
{
39 COMBINE_CONNECT_AND_WRITE_DEFAULT
, // Default policy, implemented in
40 // TransportSocketParams constructor.
41 COMBINE_CONNECT_AND_WRITE_DESIRED
, // Combine if supported by socket.
42 COMBINE_CONNECT_AND_WRITE_PROHIBITED
// Do not combine.
45 // |host_resolution_callback| will be invoked after the the hostname is
46 // resolved. If |host_resolution_callback| does not return OK, then the
47 // connection will be aborted with that value. |combine_connect_and_write|
48 // defines the policy for use of TCP FastOpen on this socket.
49 TransportSocketParams(
50 const HostPortPair
& host_port_pair
,
51 bool disable_resolver_cache
,
53 const OnHostResolutionCallback
& host_resolution_callback
,
54 CombineConnectAndWritePolicy combine_connect_and_write
);
56 const HostResolver::RequestInfo
& destination() const { return destination_
; }
57 bool ignore_limits() const { return ignore_limits_
; }
58 const OnHostResolutionCallback
& host_resolution_callback() const {
59 return host_resolution_callback_
;
62 CombineConnectAndWritePolicy
combine_connect_and_write() const {
63 return combine_connect_and_write_
;
67 friend class base::RefCounted
<TransportSocketParams
>;
68 ~TransportSocketParams();
70 HostResolver::RequestInfo destination_
;
72 const OnHostResolutionCallback host_resolution_callback_
;
73 CombineConnectAndWritePolicy combine_connect_and_write_
;
75 DISALLOW_COPY_AND_ASSIGN(TransportSocketParams
);
78 // Common data and logic shared between TransportConnectJob and
79 // WebSocketTransportConnectJob.
80 class NET_EXPORT_PRIVATE TransportConnectJobHelper
{
84 STATE_RESOLVE_HOST_COMPLETE
,
85 STATE_TRANSPORT_CONNECT
,
86 STATE_TRANSPORT_CONNECT_COMPLETE
,
90 // For recording the connection time in the appropriate bucket.
91 enum ConnectionLatencyHistogram
{
92 CONNECTION_LATENCY_UNKNOWN
,
93 CONNECTION_LATENCY_IPV4_WINS_RACE
,
94 CONNECTION_LATENCY_IPV4_NO_RACE
,
95 CONNECTION_LATENCY_IPV6_RACEABLE
,
96 CONNECTION_LATENCY_IPV6_SOLO
,
99 TransportConnectJobHelper(const scoped_refptr
<TransportSocketParams
>& params
,
100 ClientSocketFactory
* client_socket_factory
,
101 HostResolver
* host_resolver
,
102 LoadTimingInfo::ConnectTiming
* connect_timing
);
103 ~TransportConnectJobHelper();
105 ClientSocketFactory
* client_socket_factory() {
106 return client_socket_factory_
;
109 const AddressList
& addresses() const { return addresses_
; }
110 State
next_state() const { return next_state_
; }
111 void set_next_state(State next_state
) { next_state_
= next_state
; }
112 CompletionCallback
on_io_complete() const { return on_io_complete_
; }
113 const TransportSocketParams
* params() { return params_
.get(); }
115 int DoResolveHost(RequestPriority priority
, const BoundNetLog
& net_log
);
116 int DoResolveHostComplete(int result
, const BoundNetLog
& net_log
);
119 int DoConnectInternal(T
* job
);
122 void SetOnIOComplete(T
* job
);
125 void OnIOComplete(T
* job
, int result
);
127 // Record the histograms Net.DNS_Resolution_And_TCP_Connection_Latency2 and
128 // Net.TCP_Connection_Latency and return the connect duration.
129 base::TimeDelta
HistogramDuration(ConnectionLatencyHistogram race_result
);
131 static const int kIPv6FallbackTimerInMs
;
135 int DoLoop(T
* job
, int result
);
137 scoped_refptr
<TransportSocketParams
> params_
;
138 ClientSocketFactory
* const client_socket_factory_
;
139 SingleRequestHostResolver resolver_
;
140 AddressList addresses_
;
142 CompletionCallback on_io_complete_
;
143 LoadTimingInfo::ConnectTiming
* connect_timing_
;
145 DISALLOW_COPY_AND_ASSIGN(TransportConnectJobHelper
);
148 // TransportConnectJob handles the host resolution necessary for socket creation
149 // and the transport (likely TCP) connect. TransportConnectJob also has fallback
150 // logic for IPv6 connect() timeouts (which may happen due to networks / routers
151 // with broken IPv6 support). Those timeouts take 20s, so rather than make the
152 // user wait 20s for the timeout to fire, we use a fallback timer
153 // (kIPv6FallbackTimerInMs) and start a connect() to a IPv4 address if the timer
154 // fires. Then we race the IPv4 connect() against the IPv6 connect() (which has
155 // a headstart) and return the one that completes first to the socket pool.
156 class NET_EXPORT_PRIVATE TransportConnectJob
: public ConnectJob
{
158 TransportConnectJob(const std::string
& group_name
,
159 RequestPriority priority
,
160 const scoped_refptr
<TransportSocketParams
>& params
,
161 base::TimeDelta timeout_duration
,
162 ClientSocketFactory
* client_socket_factory
,
163 HostResolver
* host_resolver
,
166 ~TransportConnectJob() override
;
168 // ConnectJob methods.
169 LoadState
GetLoadState() const override
;
171 // Rolls |addrlist| forward until the first IPv4 address, if any.
172 // WARNING: this method should only be used to implement the prefer-IPv4 hack.
173 static void MakeAddressListStartWithIPv4(AddressList
* addrlist
);
176 enum ConnectInterval
{
177 CONNECT_INTERVAL_LE_10MS
,
178 CONNECT_INTERVAL_LE_20MS
,
179 CONNECT_INTERVAL_GT_20MS
,
182 friend class TransportConnectJobHelper
;
185 int DoResolveHostComplete(int result
);
186 int DoTransportConnect();
187 int DoTransportConnectComplete(int result
);
189 // Not part of the state machine.
190 void DoIPv6FallbackTransportConnect();
191 void DoIPv6FallbackTransportConnectComplete(int result
);
193 // Begins the host resolution and the TCP connect. Returns OK on success
194 // and ERR_IO_PENDING if it cannot immediately service the request.
195 // Otherwise, it returns a net error code.
196 int ConnectInternal() override
;
198 TransportConnectJobHelper helper_
;
200 scoped_ptr
<StreamSocket
> transport_socket_
;
202 scoped_ptr
<StreamSocket
> fallback_transport_socket_
;
203 scoped_ptr
<AddressList
> fallback_addresses_
;
204 base::TimeTicks fallback_connect_start_time_
;
205 base::OneShotTimer
<TransportConnectJob
> fallback_timer_
;
207 // Track the interval between this connect and previous connect.
208 ConnectInterval interval_between_connects_
;
210 DISALLOW_COPY_AND_ASSIGN(TransportConnectJob
);
213 class NET_EXPORT_PRIVATE TransportClientSocketPool
: public ClientSocketPool
{
215 typedef TransportSocketParams SocketParams
;
217 TransportClientSocketPool(
219 int max_sockets_per_group
,
220 HostResolver
* host_resolver
,
221 ClientSocketFactory
* client_socket_factory
,
224 ~TransportClientSocketPool() override
;
226 // ClientSocketPool implementation.
227 int RequestSocket(const std::string
& group_name
,
228 const void* resolve_info
,
229 RequestPriority priority
,
230 ClientSocketHandle
* handle
,
231 const CompletionCallback
& callback
,
232 const BoundNetLog
& net_log
) override
;
233 void RequestSockets(const std::string
& group_name
,
236 const BoundNetLog
& net_log
) override
;
237 void CancelRequest(const std::string
& group_name
,
238 ClientSocketHandle
* handle
) override
;
239 void ReleaseSocket(const std::string
& group_name
,
240 scoped_ptr
<StreamSocket
> socket
,
242 void FlushWithError(int error
) override
;
243 void CloseIdleSockets() override
;
244 int IdleSocketCount() const override
;
245 int IdleSocketCountInGroup(const std::string
& group_name
) const override
;
246 LoadState
GetLoadState(const std::string
& group_name
,
247 const ClientSocketHandle
* handle
) const override
;
248 base::DictionaryValue
* GetInfoAsValue(
249 const std::string
& name
,
250 const std::string
& type
,
251 bool include_nested_pools
) const override
;
252 base::TimeDelta
ConnectionTimeout() const override
;
254 // HigherLayeredPool implementation.
255 bool IsStalled() const override
;
256 void AddHigherLayeredPool(HigherLayeredPool
* higher_pool
) override
;
257 void RemoveHigherLayeredPool(HigherLayeredPool
* higher_pool
) override
;
260 // Methods shared with WebSocketTransportClientSocketPool
261 void NetLogTcpClientSocketPoolRequestedSocket(
262 const BoundNetLog
& net_log
,
263 const scoped_refptr
<TransportSocketParams
>* casted_params
);
266 typedef ClientSocketPoolBase
<TransportSocketParams
> PoolBase
;
268 class TransportConnectJobFactory
269 : public PoolBase::ConnectJobFactory
{
271 TransportConnectJobFactory(ClientSocketFactory
* client_socket_factory
,
272 HostResolver
* host_resolver
,
274 : client_socket_factory_(client_socket_factory
),
275 host_resolver_(host_resolver
),
278 ~TransportConnectJobFactory() override
{}
280 // ClientSocketPoolBase::ConnectJobFactory methods.
282 scoped_ptr
<ConnectJob
> NewConnectJob(
283 const std::string
& group_name
,
284 const PoolBase::Request
& request
,
285 ConnectJob::Delegate
* delegate
) const override
;
287 base::TimeDelta
ConnectionTimeout() const override
;
290 ClientSocketFactory
* const client_socket_factory_
;
291 HostResolver
* const host_resolver_
;
294 DISALLOW_COPY_AND_ASSIGN(TransportConnectJobFactory
);
299 DISALLOW_COPY_AND_ASSIGN(TransportClientSocketPool
);
303 int TransportConnectJobHelper::DoConnectInternal(T
* job
) {
304 next_state_
= STATE_RESOLVE_HOST
;
305 return this->DoLoop(job
, OK
);
309 void TransportConnectJobHelper::SetOnIOComplete(T
* job
) {
310 // These usages of base::Unretained() are safe because IO callbacks are
311 // guaranteed not to be called after the object is destroyed.
312 on_io_complete_
= base::Bind(&TransportConnectJobHelper::OnIOComplete
<T
>,
313 base::Unretained(this),
314 base::Unretained(job
));
318 void TransportConnectJobHelper::OnIOComplete(T
* job
, int result
) {
319 result
= this->DoLoop(job
, result
);
320 if (result
!= ERR_IO_PENDING
)
321 job
->NotifyDelegateOfCompletion(result
); // Deletes |job| and |this|
325 int TransportConnectJobHelper::DoLoop(T
* job
, int result
) {
326 DCHECK_NE(next_state_
, STATE_NONE
);
330 State state
= next_state_
;
331 next_state_
= STATE_NONE
;
333 case STATE_RESOLVE_HOST
:
335 rv
= job
->DoResolveHost();
337 case STATE_RESOLVE_HOST_COMPLETE
:
338 rv
= job
->DoResolveHostComplete(rv
);
340 case STATE_TRANSPORT_CONNECT
:
342 rv
= job
->DoTransportConnect();
344 case STATE_TRANSPORT_CONNECT_COMPLETE
:
345 rv
= job
->DoTransportConnectComplete(rv
);
352 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
359 #endif // NET_SOCKET_TRANSPORT_CLIENT_SOCKET_POOL_H_