Implement HasPermission() method in PermissionService.
[chromium-blink-merge.git] / net / socket / transport_client_socket_pool.h
blob15cef5c02ac805986264c4f07c12b31993008718
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/client_socket_pool_histograms.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;
172 // Rolls |addrlist| forward until the first IPv4 address, if any.
173 // WARNING: this method should only be used to implement the prefer-IPv4 hack.
174 static void MakeAddressListStartWithIPv4(AddressList* addrlist);
176 private:
177 enum ConnectInterval {
178 CONNECT_INTERVAL_LE_10MS,
179 CONNECT_INTERVAL_LE_20MS,
180 CONNECT_INTERVAL_GT_20MS,
183 friend class TransportConnectJobHelper;
185 int DoResolveHost();
186 int DoResolveHostComplete(int result);
187 int DoTransportConnect();
188 int DoTransportConnectComplete(int result);
190 // Not part of the state machine.
191 void DoIPv6FallbackTransportConnect();
192 void DoIPv6FallbackTransportConnectComplete(int result);
194 // Begins the host resolution and the TCP connect. Returns OK on success
195 // and ERR_IO_PENDING if it cannot immediately service the request.
196 // Otherwise, it returns a net error code.
197 int ConnectInternal() override;
199 TransportConnectJobHelper helper_;
201 scoped_ptr<StreamSocket> transport_socket_;
203 scoped_ptr<StreamSocket> fallback_transport_socket_;
204 scoped_ptr<AddressList> fallback_addresses_;
205 base::TimeTicks fallback_connect_start_time_;
206 base::OneShotTimer<TransportConnectJob> fallback_timer_;
208 // Track the interval between this connect and previous connect.
209 ConnectInterval interval_between_connects_;
211 DISALLOW_COPY_AND_ASSIGN(TransportConnectJob);
214 class NET_EXPORT_PRIVATE TransportClientSocketPool : public ClientSocketPool {
215 public:
216 typedef TransportSocketParams SocketParams;
218 TransportClientSocketPool(
219 int max_sockets,
220 int max_sockets_per_group,
221 ClientSocketPoolHistograms* histograms,
222 HostResolver* host_resolver,
223 ClientSocketFactory* client_socket_factory,
224 NetLog* net_log);
226 ~TransportClientSocketPool() override;
228 // ClientSocketPool implementation.
229 int RequestSocket(const std::string& group_name,
230 const void* resolve_info,
231 RequestPriority priority,
232 ClientSocketHandle* handle,
233 const CompletionCallback& callback,
234 const BoundNetLog& net_log) override;
235 void RequestSockets(const std::string& group_name,
236 const void* params,
237 int num_sockets,
238 const BoundNetLog& net_log) override;
239 void CancelRequest(const std::string& group_name,
240 ClientSocketHandle* handle) override;
241 void ReleaseSocket(const std::string& group_name,
242 scoped_ptr<StreamSocket> socket,
243 int id) override;
244 void FlushWithError(int error) override;
245 void CloseIdleSockets() override;
246 int IdleSocketCount() const override;
247 int IdleSocketCountInGroup(const std::string& group_name) const override;
248 LoadState GetLoadState(const std::string& group_name,
249 const ClientSocketHandle* handle) const override;
250 base::DictionaryValue* GetInfoAsValue(
251 const std::string& name,
252 const std::string& type,
253 bool include_nested_pools) const override;
254 base::TimeDelta ConnectionTimeout() const override;
255 ClientSocketPoolHistograms* histograms() const override;
257 // HigherLayeredPool implementation.
258 bool IsStalled() const override;
259 void AddHigherLayeredPool(HigherLayeredPool* higher_pool) override;
260 void RemoveHigherLayeredPool(HigherLayeredPool* higher_pool) override;
262 protected:
263 // Methods shared with WebSocketTransportClientSocketPool
264 void NetLogTcpClientSocketPoolRequestedSocket(
265 const BoundNetLog& net_log,
266 const scoped_refptr<TransportSocketParams>* casted_params);
268 private:
269 typedef ClientSocketPoolBase<TransportSocketParams> PoolBase;
271 class TransportConnectJobFactory
272 : public PoolBase::ConnectJobFactory {
273 public:
274 TransportConnectJobFactory(ClientSocketFactory* client_socket_factory,
275 HostResolver* host_resolver,
276 NetLog* net_log)
277 : client_socket_factory_(client_socket_factory),
278 host_resolver_(host_resolver),
279 net_log_(net_log) {}
281 ~TransportConnectJobFactory() override {}
283 // ClientSocketPoolBase::ConnectJobFactory methods.
285 scoped_ptr<ConnectJob> NewConnectJob(
286 const std::string& group_name,
287 const PoolBase::Request& request,
288 ConnectJob::Delegate* delegate) const override;
290 base::TimeDelta ConnectionTimeout() const override;
292 private:
293 ClientSocketFactory* const client_socket_factory_;
294 HostResolver* const host_resolver_;
295 NetLog* net_log_;
297 DISALLOW_COPY_AND_ASSIGN(TransportConnectJobFactory);
300 PoolBase base_;
302 DISALLOW_COPY_AND_ASSIGN(TransportClientSocketPool);
305 template <class T>
306 int TransportConnectJobHelper::DoConnectInternal(T* job) {
307 next_state_ = STATE_RESOLVE_HOST;
308 return this->DoLoop(job, OK);
311 template <class T>
312 void TransportConnectJobHelper::SetOnIOComplete(T* job) {
313 // These usages of base::Unretained() are safe because IO callbacks are
314 // guaranteed not to be called after the object is destroyed.
315 on_io_complete_ = base::Bind(&TransportConnectJobHelper::OnIOComplete<T>,
316 base::Unretained(this),
317 base::Unretained(job));
320 template <class T>
321 void TransportConnectJobHelper::OnIOComplete(T* job, int result) {
322 result = this->DoLoop(job, result);
323 if (result != ERR_IO_PENDING)
324 job->NotifyDelegateOfCompletion(result); // Deletes |job| and |this|
327 template <class T>
328 int TransportConnectJobHelper::DoLoop(T* job, int result) {
329 DCHECK_NE(next_state_, STATE_NONE);
331 int rv = result;
332 do {
333 State state = next_state_;
334 next_state_ = STATE_NONE;
335 switch (state) {
336 case STATE_RESOLVE_HOST:
337 DCHECK_EQ(OK, rv);
338 rv = job->DoResolveHost();
339 break;
340 case STATE_RESOLVE_HOST_COMPLETE:
341 rv = job->DoResolveHostComplete(rv);
342 break;
343 case STATE_TRANSPORT_CONNECT:
344 DCHECK_EQ(OK, rv);
345 rv = job->DoTransportConnect();
346 break;
347 case STATE_TRANSPORT_CONNECT_COMPLETE:
348 rv = job->DoTransportConnectComplete(rv);
349 break;
350 default:
351 NOTREACHED();
352 rv = ERR_FAILED;
353 break;
355 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
357 return rv;
360 } // namespace net
362 #endif // NET_SOCKET_TRANSPORT_CLIENT_SOCKET_POOL_H_