We started redesigning GpuMemoryBuffer interface to handle multiple buffers [0].
[chromium-blink-merge.git] / net / socket / transport_client_socket_pool.h
blob48ddd1334fab5974b651eb04bc293ac885f9bd49
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"
21 namespace net {
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> {
30 public:
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,
52 bool ignore_limits,
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_;
66 private:
67 friend class base::RefCounted<TransportSocketParams>;
68 ~TransportSocketParams();
70 HostResolver::RequestInfo destination_;
71 bool ignore_limits_;
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 {
81 public:
82 enum State {
83 STATE_RESOLVE_HOST,
84 STATE_RESOLVE_HOST_COMPLETE,
85 STATE_TRANSPORT_CONNECT,
86 STATE_TRANSPORT_CONNECT_COMPLETE,
87 STATE_NONE,
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);
118 template <class T>
119 int DoConnectInternal(T* job);
121 template <class T>
122 void SetOnIOComplete(T* job);
124 template <class T>
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;
133 private:
134 template <class T>
135 int DoLoop(T* job, int result);
137 scoped_refptr<TransportSocketParams> params_;
138 ClientSocketFactory* const client_socket_factory_;
139 SingleRequestHostResolver resolver_;
140 AddressList addresses_;
141 State next_state_;
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 {
157 public:
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,
164 Delegate* delegate,
165 NetLog* net_log);
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);
175 private:
176 enum ConnectInterval {
177 CONNECT_INTERVAL_LE_10MS,
178 CONNECT_INTERVAL_LE_20MS,
179 CONNECT_INTERVAL_GT_20MS,
182 friend class TransportConnectJobHelper;
184 int DoResolveHost();
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 {
214 public:
215 typedef TransportSocketParams SocketParams;
217 TransportClientSocketPool(
218 int max_sockets,
219 int max_sockets_per_group,
220 HostResolver* host_resolver,
221 ClientSocketFactory* client_socket_factory,
222 NetLog* net_log);
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,
234 const void* params,
235 int num_sockets,
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,
241 int id) override;
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;
259 protected:
260 // Methods shared with WebSocketTransportClientSocketPool
261 void NetLogTcpClientSocketPoolRequestedSocket(
262 const BoundNetLog& net_log,
263 const scoped_refptr<TransportSocketParams>* casted_params);
265 private:
266 typedef ClientSocketPoolBase<TransportSocketParams> PoolBase;
268 class TransportConnectJobFactory
269 : public PoolBase::ConnectJobFactory {
270 public:
271 TransportConnectJobFactory(ClientSocketFactory* client_socket_factory,
272 HostResolver* host_resolver,
273 NetLog* net_log)
274 : client_socket_factory_(client_socket_factory),
275 host_resolver_(host_resolver),
276 net_log_(net_log) {}
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;
289 private:
290 ClientSocketFactory* const client_socket_factory_;
291 HostResolver* const host_resolver_;
292 NetLog* net_log_;
294 DISALLOW_COPY_AND_ASSIGN(TransportConnectJobFactory);
297 PoolBase base_;
299 DISALLOW_COPY_AND_ASSIGN(TransportClientSocketPool);
302 template <class T>
303 int TransportConnectJobHelper::DoConnectInternal(T* job) {
304 next_state_ = STATE_RESOLVE_HOST;
305 return this->DoLoop(job, OK);
308 template <class T>
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));
317 template <class T>
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|
324 template <class T>
325 int TransportConnectJobHelper::DoLoop(T* job, int result) {
326 DCHECK_NE(next_state_, STATE_NONE);
328 int rv = result;
329 do {
330 State state = next_state_;
331 next_state_ = STATE_NONE;
332 switch (state) {
333 case STATE_RESOLVE_HOST:
334 DCHECK_EQ(OK, rv);
335 rv = job->DoResolveHost();
336 break;
337 case STATE_RESOLVE_HOST_COMPLETE:
338 rv = job->DoResolveHostComplete(rv);
339 break;
340 case STATE_TRANSPORT_CONNECT:
341 DCHECK_EQ(OK, rv);
342 rv = job->DoTransportConnect();
343 break;
344 case STATE_TRANSPORT_CONNECT_COMPLETE:
345 rv = job->DoTransportConnectComplete(rv);
346 break;
347 default:
348 NOTREACHED();
349 rv = ERR_FAILED;
350 break;
352 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
354 return rv;
357 } // namespace net
359 #endif // NET_SOCKET_TRANSPORT_CLIENT_SOCKET_POOL_H_