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_QUIC_QUIC_STREAM_FACTORY_H_
6 #define NET_QUIC_QUIC_STREAM_FACTORY_H_
13 #include "base/logging.h"
14 #include "base/memory/weak_ptr.h"
15 #include "net/base/address_list.h"
16 #include "net/base/completion_callback.h"
17 #include "net/base/host_port_pair.h"
18 #include "net/base/network_change_notifier.h"
19 #include "net/cert/cert_database.h"
20 #include "net/log/net_log.h"
21 #include "net/proxy/proxy_server.h"
22 #include "net/quic/network_connection.h"
23 #include "net/quic/quic_chromium_client_session.h"
24 #include "net/quic/quic_config.h"
25 #include "net/quic/quic_crypto_stream.h"
26 #include "net/quic/quic_http_stream.h"
27 #include "net/quic/quic_protocol.h"
28 #include "net/ssl/ssl_config_service.h"
32 class CertPolicyEnforcer
;
34 class ChannelIDService
;
35 class ClientSocketFactory
;
37 class HttpServerProperties
;
39 class QuicChromiumClientSession
;
40 class QuicConnectionHelper
;
41 class QuicCryptoClientStreamFactory
;
43 class QuicServerInfoFactory
;
45 class QuicStreamFactory
;
46 class TransportSecurityState
;
49 class QuicStreamFactoryPeer
;
52 // Encapsulates a pending request for a QuicHttpStream.
53 // If the request is still pending when it is destroyed, it will
54 // cancel the request with the factory.
55 class NET_EXPORT_PRIVATE QuicStreamRequest
{
57 explicit QuicStreamRequest(QuicStreamFactory
* factory
);
60 // For http, |is_https| is false.
61 // |cert_verify_flags| is bitwise OR'd of CertVerifier::VerifyFlags and it is
62 // passed to CertVerifier::Verify.
63 int Request(const HostPortPair
& host_port_pair
,
65 PrivacyMode privacy_mode
,
66 int cert_verify_flags
,
67 base::StringPiece origin_host
,
68 base::StringPiece method
,
69 const BoundNetLog
& net_log
,
70 const CompletionCallback
& callback
);
72 void OnRequestComplete(int rv
);
74 scoped_ptr
<QuicHttpStream
> ReleaseStream();
76 void set_stream(scoped_ptr
<QuicHttpStream
> stream
);
78 const std::string
& origin_host() const { return origin_host_
; }
80 PrivacyMode
privacy_mode() const { return privacy_mode_
; }
82 const BoundNetLog
& net_log() const{
87 QuicStreamFactory
* factory_
;
88 HostPortPair host_port_pair_
;
89 std::string origin_host_
;
90 PrivacyMode privacy_mode_
;
92 CompletionCallback callback_
;
93 scoped_ptr
<QuicHttpStream
> stream_
;
95 DISALLOW_COPY_AND_ASSIGN(QuicStreamRequest
);
98 // A factory for creating new QuicHttpStreams on top of a pool of
99 // QuicChromiumClientSessions.
100 class NET_EXPORT_PRIVATE QuicStreamFactory
101 : public NetworkChangeNotifier::IPAddressObserver
,
102 public SSLConfigService::Observer
,
103 public CertDatabase::Observer
{
106 HostResolver
* host_resolver
,
107 ClientSocketFactory
* client_socket_factory
,
108 base::WeakPtr
<HttpServerProperties
> http_server_properties
,
109 CertVerifier
* cert_verifier
,
110 CertPolicyEnforcer
* cert_policy_enforcer
,
111 ChannelIDService
* channel_id_service
,
112 TransportSecurityState
* transport_security_state
,
113 QuicCryptoClientStreamFactory
* quic_crypto_client_stream_factory
,
114 QuicRandom
* random_generator
,
116 size_t max_packet_length
,
117 const std::string
& user_agent_id
,
118 const QuicVersionVector
& supported_versions
,
119 bool enable_port_selection
,
120 bool always_require_handshake_confirmation
,
121 bool disable_connection_pooling
,
122 float load_server_info_timeout_srtt_multiplier
,
123 bool enable_connection_racing
,
124 bool enable_non_blocking_io
,
125 bool disable_disk_cache
,
127 int max_number_of_lossy_connections
,
128 float packet_loss_threshold
,
129 int max_recent_disabled_reasons
,
130 int threshold_timeouts_with_streams_open
,
131 int threshold_public_resets_post_handshake
,
132 int socket_receive_buffer_size
,
133 const QuicTagVector
& connection_options
);
134 ~QuicStreamFactory() override
;
136 // Creates a new QuicHttpStream to |host_port_pair| which will be
137 // owned by |request|. |is_https| specifies if the protocol is https or not.
138 // If a matching session already exists, this method will return OK. If no
139 // matching session exists, this will return ERR_IO_PENDING and will invoke
140 // OnRequestComplete asynchronously.
141 int Create(const HostPortPair
& host_port_pair
,
143 PrivacyMode privacy_mode
,
144 int cert_verify_flags
,
145 base::StringPiece origin_host
,
146 base::StringPiece method
,
147 const BoundNetLog
& net_log
,
148 QuicStreamRequest
* request
);
150 // If |packet_loss_rate| is greater than or equal to |packet_loss_threshold_|
151 // it marks QUIC as recently broken for the port of the session. Increments
152 // |number_of_lossy_connections_| by port. If |number_of_lossy_connections_|
153 // is greater than or equal to |max_number_of_lossy_connections_| then it
154 // disables QUIC. If QUIC is disabled then it closes the connection.
156 // Returns true if QUIC is disabled for the port of the session.
157 bool OnHandshakeConfirmed(QuicChromiumClientSession
* session
,
158 float packet_loss_rate
);
160 // Returns true if QUIC is disabled for this port.
161 bool IsQuicDisabled(uint16 port
);
163 // Returns reason QUIC is disabled for this port, or QUIC_DISABLED_NOT if not.
164 QuicChromiumClientSession::QuicDisabledReason
QuicDisabledReason(
167 // Returns reason QUIC is disabled as string for net-internals, or
168 // returns empty string if QUIC is not disabled.
169 const char* QuicDisabledReasonString() const;
171 // Called by a session when it becomes idle.
172 void OnIdleSession(QuicChromiumClientSession
* session
);
174 // Called by a session when it is going away and no more streams should be
176 void OnSessionGoingAway(QuicChromiumClientSession
* session
);
178 // Called by a session after it shuts down.
179 void OnSessionClosed(QuicChromiumClientSession
* session
);
181 // Called by a session whose connection has timed out.
182 void OnSessionConnectTimeout(QuicChromiumClientSession
* session
);
184 // Cancels a pending request.
185 void CancelRequest(QuicStreamRequest
* request
);
187 // Closes all current sessions.
188 void CloseAllSessions(int error
);
190 scoped_ptr
<base::Value
> QuicStreamFactoryInfoToValue() const;
192 // Delete all cached state objects in |crypto_config_|.
193 void ClearCachedStatesInCryptoConfig();
195 // NetworkChangeNotifier::IPAddressObserver methods:
197 // Until the servers support roaming, close all connections when the local
198 // IP address changes.
199 void OnIPAddressChanged() override
;
201 // SSLConfigService::Observer methods:
203 // We perform the same flushing as described above when SSL settings change.
204 void OnSSLConfigChanged() override
;
206 // CertDatabase::Observer methods:
208 // We close all sessions when certificate database is changed.
209 void OnCertAdded(const X509Certificate
* cert
) override
;
210 void OnCACertChanged(const X509Certificate
* cert
) override
;
212 bool require_confirmation() const {
213 return require_confirmation_
;
216 void set_require_confirmation(bool require_confirmation
);
218 QuicConnectionHelper
* helper() { return helper_
.get(); }
220 bool enable_port_selection() const { return enable_port_selection_
; }
222 bool has_quic_server_info_factory() {
223 return quic_server_info_factory_
!= NULL
;
226 void set_quic_server_info_factory(
227 QuicServerInfoFactory
* quic_server_info_factory
) {
228 DCHECK(!quic_server_info_factory_
);
229 quic_server_info_factory_
= quic_server_info_factory
;
232 bool enable_connection_racing() const { return enable_connection_racing_
; }
233 void set_enable_connection_racing(bool enable_connection_racing
) {
234 enable_connection_racing_
= enable_connection_racing
;
237 int socket_receive_buffer_size() const { return socket_receive_buffer_size_
; }
241 friend class test::QuicStreamFactoryPeer
;
242 FRIEND_TEST_ALL_PREFIXES(HttpStreamFactoryTest
, QuicLossyProxyMarkedAsBad
);
244 // The key used to find session by ip. Includes
245 // the ip address, port, and scheme.
246 struct NET_EXPORT_PRIVATE IpAliasKey
{
248 IpAliasKey(IPEndPoint ip_endpoint
, bool is_https
);
251 IPEndPoint ip_endpoint
;
254 // Needed to be an element of std::set.
255 bool operator<(const IpAliasKey
&other
) const;
256 bool operator==(const IpAliasKey
&other
) const;
259 typedef std::map
<QuicServerId
, QuicChromiumClientSession
*> SessionMap
;
260 typedef std::map
<QuicChromiumClientSession
*, QuicServerId
> SessionIdMap
;
261 typedef std::set
<QuicServerId
> AliasSet
;
262 typedef std::map
<QuicChromiumClientSession
*, AliasSet
> SessionAliasMap
;
263 typedef std::set
<QuicChromiumClientSession
*> SessionSet
;
264 typedef std::map
<IpAliasKey
, SessionSet
> IPAliasMap
;
265 typedef std::map
<QuicServerId
, QuicCryptoClientConfig
*> CryptoConfigMap
;
266 typedef std::set
<Job
*> JobSet
;
267 typedef std::map
<QuicServerId
, JobSet
> JobMap
;
268 typedef std::map
<QuicStreamRequest
*, QuicServerId
> RequestMap
;
269 typedef std::set
<QuicStreamRequest
*> RequestSet
;
270 typedef std::map
<QuicServerId
, RequestSet
> ServerIDRequestsMap
;
271 typedef std::deque
<enum QuicChromiumClientSession::QuicDisabledReason
>
272 DisabledReasonsQueue
;
274 // Creates a job which doesn't wait for server config to be loaded from the
275 // disk cache. This job is started via a PostTask.
276 void CreateAuxilaryJob(const QuicServerId server_id
,
277 int cert_verify_flags
,
278 bool server_and_origin_have_same_host
,
280 const BoundNetLog
& net_log
);
282 // Returns a newly created QuicHttpStream owned by the caller.
283 scoped_ptr
<QuicHttpStream
> CreateFromSession(QuicChromiumClientSession
*);
285 bool OnResolution(const QuicServerId
& server_id
,
286 const AddressList
& address_list
);
287 void OnJobComplete(Job
* job
, int rv
);
288 bool HasActiveSession(const QuicServerId
& server_id
) const;
289 bool HasActiveJob(const QuicServerId
& server_id
) const;
290 int CreateSession(const QuicServerId
& server_id
,
291 int cert_verify_flags
,
292 scoped_ptr
<QuicServerInfo
> quic_server_info
,
293 const AddressList
& address_list
,
294 base::TimeTicks dns_resolution_end_time
,
295 const BoundNetLog
& net_log
,
296 QuicChromiumClientSession
** session
);
297 void ActivateSession(const QuicServerId
& key
,
298 QuicChromiumClientSession
* session
);
300 // Returns |srtt| in micro seconds from ServerNetworkStats. Returns 0 if there
301 // is no |http_server_properties_| or if |http_server_properties_| doesn't
302 // have ServerNetworkStats for the given |server_id|.
303 int64
GetServerNetworkStatsSmoothedRttInMicroseconds(
304 const QuicServerId
& server_id
) const;
307 bool WasQuicRecentlyBroken(const QuicServerId
& server_id
) const;
308 bool CryptoConfigCacheIsEmpty(const QuicServerId
& server_id
);
310 // Initializes the cached state associated with |server_id| in
311 // |crypto_config_| with the information in |server_info|.
312 void InitializeCachedStateInCryptoConfig(
313 const QuicServerId
& server_id
,
314 const scoped_ptr
<QuicServerInfo
>& server_info
);
316 void ProcessGoingAwaySession(QuicChromiumClientSession
* session
,
317 const QuicServerId
& server_id
,
318 bool was_session_active
);
320 // Collect stats from recent connections, possibly disabling Quic.
321 void MaybeDisableQuic(QuicChromiumClientSession
* session
);
323 bool require_confirmation_
;
324 HostResolver
* host_resolver_
;
325 ClientSocketFactory
* client_socket_factory_
;
326 base::WeakPtr
<HttpServerProperties
> http_server_properties_
;
327 TransportSecurityState
* transport_security_state_
;
328 QuicServerInfoFactory
* quic_server_info_factory_
;
329 QuicCryptoClientStreamFactory
* quic_crypto_client_stream_factory_
;
330 QuicRandom
* random_generator_
;
331 scoped_ptr
<QuicClock
> clock_
;
332 const size_t max_packet_length_
;
334 // The helper used for all connections.
335 scoped_ptr
<QuicConnectionHelper
> helper_
;
337 // Contains owning pointers to all sessions that currently exist.
338 SessionIdMap all_sessions_
;
339 // Contains non-owning pointers to currently active session
340 // (not going away session, once they're implemented).
341 SessionMap active_sessions_
;
342 // Map from session to set of aliases that this session is known by.
343 SessionAliasMap session_aliases_
;
344 // Map from IP address to sessions which are connected to this address.
345 IPAliasMap ip_aliases_
;
347 // Origins which have gone away recently.
348 AliasSet gone_away_aliases_
;
350 const QuicConfig config_
;
351 QuicCryptoClientConfig crypto_config_
;
354 ServerIDRequestsMap job_requests_map_
;
355 RequestMap active_requests_
;
357 QuicVersionVector supported_versions_
;
359 // Determine if we should consistently select a client UDP port. If false,
360 // then we will just let the OS select a random client port for each new
362 bool enable_port_selection_
;
364 // Set if we always require handshake confirmation. If true, this will
365 // introduce at least one RTT for the handshake before the client sends data.
366 bool always_require_handshake_confirmation_
;
368 // Set if we do not want connection pooling.
369 bool disable_connection_pooling_
;
371 // Specifies the ratio between time to load QUIC server information from disk
372 // cache to 'smoothed RTT'. This ratio is used to calculate the timeout in
373 // milliseconds to wait for loading of QUIC server information. If we don't
374 // want to timeout, set |load_server_info_timeout_srtt_multiplier_| to 0.
375 float load_server_info_timeout_srtt_multiplier_
;
377 // Set if we want to race connections - one connection that sends
378 // INCHOATE_HELLO and another connection that sends CHLO after loading server
379 // config from the disk cache.
380 bool enable_connection_racing_
;
382 // Set if experimental non-blocking IO should be used on windows sockets.
383 bool enable_non_blocking_io_
;
385 // Set if we do not want to load server config from the disk cache.
386 bool disable_disk_cache_
;
388 // Set if AES-GCM should be preferred, even if there is no hardware support.
391 // Set if we want to disable QUIC when there is high packet loss rate.
392 // Specifies the maximum number of connections with high packet loss in a row
393 // after which QUIC will be disabled.
394 int max_number_of_lossy_connections_
;
395 // Specifies packet loss rate in fraction after which a connection is closed
396 // and is considered as a lossy connection.
397 float packet_loss_threshold_
;
398 // Count number of lossy connections by port.
399 std::map
<uint16
, int> number_of_lossy_connections_
;
401 // Keep track of stats for recently closed connections, using a
403 int max_disabled_reasons_
;
404 DisabledReasonsQueue disabled_reasons_
;
405 // Events that can trigger disabling QUIC
406 int num_public_resets_post_handshake_
;
407 int num_timeouts_with_open_streams_
;
408 // Keep track the largest values for UMA histograms, that will help
409 // determine good threshold values.
410 int max_public_resets_post_handshake_
;
411 int max_timeouts_with_open_streams_
;
412 // Thresholds if greater than zero, determine when to
413 int threshold_timeouts_with_open_streams_
;
414 int threshold_public_resets_post_handshake_
;
416 // Size of the UDP receive buffer.
417 int socket_receive_buffer_size_
;
419 // Each profile will (probably) have a unique port_seed_ value. This value
420 // is used to help seed a pseudo-random number generator (PortSuggester) so
421 // that we consistently (within this profile) suggest the same ephemeral
422 // port when we re-connect to any given server/port. The differences between
423 // profiles (probablistically) prevent two profiles from colliding in their
424 // ephemeral port requests.
427 // Local address of socket that was created in CreateSession.
428 IPEndPoint local_address_
;
429 bool check_persisted_supports_quic_
;
430 std::set
<HostPortPair
> quic_supported_servers_at_startup_
;
432 NetworkConnection network_connection_
;
434 base::TaskRunner
* task_runner_
;
436 base::WeakPtrFactory
<QuicStreamFactory
> weak_factory_
;
438 DISALLOW_COPY_AND_ASSIGN(QuicStreamFactory
);
443 #endif // NET_QUIC_QUIC_STREAM_FACTORY_H_