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 // A client specific QuicSession subclass. This class owns the underlying
6 // QuicConnection and QuicConnectionHelper objects. The connection stores
7 // a non-owning pointer to the helper so this session needs to ensure that
8 // the helper outlives the connection.
10 #ifndef NET_QUIC_QUIC_CLIENT_SESSION_H_
11 #define NET_QUIC_QUIC_CLIENT_SESSION_H_
15 #include "base/basictypes.h"
16 #include "base/containers/hash_tables.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/time/time.h"
19 #include "net/base/completion_callback.h"
20 #include "net/proxy/proxy_server.h"
21 #include "net/quic/quic_client_session_base.h"
22 #include "net/quic/quic_connection_logger.h"
23 #include "net/quic/quic_crypto_client_stream.h"
24 #include "net/quic/quic_packet_reader.h"
25 #include "net/quic/quic_protocol.h"
26 #include "net/quic/quic_reliable_client_stream.h"
30 class CertVerifyResult
;
31 class DatagramClientSocket
;
32 class QuicConnectionHelper
;
33 class QuicCryptoClientStreamFactory
;
36 class QuicStreamFactory
;
38 class TransportSecurityState
;
41 class QuicClientSessionPeer
;
44 class NET_EXPORT_PRIVATE QuicClientSession
: public QuicClientSessionBase
,
45 public QuicPacketReader::Visitor
{
47 // Reasons to disable QUIC, that is under certain pathological
48 // connection errors. Note: these values must be kept in sync with
49 // the corresponding values of QuicDisabledReason in:
50 // tools/metrics/histograms/histograms.xml
51 enum QuicDisabledReason
{
52 QUIC_DISABLED_NOT
= 0, // default, not disabled
53 QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
= 1,
54 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
= 2,
55 QUIC_DISABLED_BAD_PACKET_LOSS_RATE
= 3,
56 QUIC_DISABLED_MAX
= 4,
59 // An interface for observing events on a session.
60 class NET_EXPORT_PRIVATE Observer
{
62 virtual ~Observer() {}
63 virtual void OnCryptoHandshakeConfirmed() = 0;
64 virtual void OnSessionClosed(int error
) = 0;
67 // A helper class used to manage a request to create a stream.
68 class NET_EXPORT_PRIVATE StreamRequest
{
73 // Starts a request to create a stream. If OK is returned, then
74 // |stream| will be updated with the newly created stream. If
75 // ERR_IO_PENDING is returned, then when the request is eventuallly
76 // complete |callback| will be called.
77 int StartRequest(const base::WeakPtr
<QuicClientSession
>& session
,
78 QuicReliableClientStream
** stream
,
79 const CompletionCallback
& callback
);
81 // Cancels any pending stream creation request. May be called
86 friend class QuicClientSession
;
88 // Called by |session_| for an asynchronous request when the stream
89 // request has finished successfully.
90 void OnRequestCompleteSuccess(QuicReliableClientStream
* stream
);
92 // Called by |session_| for an asynchronous request when the stream
93 // request has finished with an error. Also called with ERR_ABORTED
94 // if |session_| is destroyed while the stream request is still pending.
95 void OnRequestCompleteFailure(int rv
);
97 base::WeakPtr
<QuicClientSession
> session_
;
98 CompletionCallback callback_
;
99 QuicReliableClientStream
** stream_
;
101 DISALLOW_COPY_AND_ASSIGN(StreamRequest
);
104 // Constructs a new session which will own |connection|, but not
105 // |stream_factory|, which must outlive this session.
106 // TODO(rch): decouple the factory from the session via a Delegate interface.
107 QuicClientSession(QuicConnection
* connection
,
108 scoped_ptr
<DatagramClientSocket
> socket
,
109 QuicStreamFactory
* stream_factory
,
110 QuicCryptoClientStreamFactory
* crypto_client_stream_factory
,
111 TransportSecurityState
* transport_security_state
,
112 scoped_ptr
<QuicServerInfo
> server_info
,
113 const QuicServerId
& server_id
,
114 int cert_verify_flags
,
115 const QuicConfig
& config
,
116 QuicCryptoClientConfig
* crypto_config
,
117 const char* const connection_description
,
118 base::TimeTicks dns_resolution_end_time
,
119 base::TaskRunner
* task_runner
,
121 ~QuicClientSession() override
;
123 void AddObserver(Observer
* observer
);
124 void RemoveObserver(Observer
* observer
);
126 // Attempts to create a new stream. If the stream can be
127 // created immediately, returns OK. If the open stream limit
128 // has been reached, returns ERR_IO_PENDING, and |request|
129 // will be added to the stream requets queue and will
130 // be completed asynchronously.
131 // TODO(rch): remove |stream| from this and use setter on |request|
132 // and fix in spdy too.
133 int TryCreateStream(StreamRequest
* request
,
134 QuicReliableClientStream
** stream
);
136 // Cancels the pending stream creation request.
137 void CancelRequest(StreamRequest
* request
);
139 // QuicSession methods:
140 void OnStreamFrames(const std::vector
<QuicStreamFrame
>& frames
) override
;
141 QuicReliableClientStream
* CreateOutgoingDynamicStream() override
;
142 QuicCryptoClientStream
* GetCryptoStream() override
;
143 void CloseStream(QuicStreamId stream_id
) override
;
144 void SendRstStream(QuicStreamId id
,
145 QuicRstStreamErrorCode error
,
146 QuicStreamOffset bytes_written
) override
;
147 void OnCryptoHandshakeEvent(CryptoHandshakeEvent event
) override
;
148 void OnCryptoHandshakeMessageSent(
149 const CryptoHandshakeMessage
& message
) override
;
150 void OnCryptoHandshakeMessageReceived(
151 const CryptoHandshakeMessage
& message
) override
;
153 // QuicClientSessionBase methods:
154 void OnProofValid(const QuicCryptoClientConfig::CachedState
& cached
) override
;
155 void OnProofVerifyDetailsAvailable(
156 const ProofVerifyDetails
& verify_details
) override
;
158 // QuicConnectionVisitorInterface methods:
159 void OnConnectionClosed(QuicErrorCode error
, bool from_peer
) override
;
160 void OnSuccessfulVersionNegotiation(const QuicVersion
& version
) override
;
162 // QuicPacketReader::Visitor methods:
163 void OnReadError(int result
) override
;
164 bool OnPacket(const QuicEncryptedPacket
& packet
,
165 IPEndPoint local_address
,
166 IPEndPoint peer_address
) override
;
168 // Gets the SSL connection information.
169 bool GetSSLInfo(SSLInfo
* ssl_info
) const;
171 // Performs a crypto handshake with the server.
172 int CryptoConnect(bool require_confirmation
,
173 const CompletionCallback
& callback
);
175 // Resumes a crypto handshake with the server after a timeout.
176 int ResumeCryptoConnect(const CompletionCallback
& callback
);
178 // Causes the QuicConnectionHelper to start reading from the socket
179 // and passing the data along to the QuicConnection.
182 // Close the session because of |error| and notifies the factory
183 // that this session has been closed, which will delete the session.
184 void CloseSessionOnError(int error
, QuicErrorCode quic_error
);
186 // Close the session because of |error| and notifies the factory later that
187 // this session has been closed, which will delete the session.
188 void CloseSessionOnErrorAndNotifyFactoryLater(int error
,
189 QuicErrorCode quic_error
);
191 scoped_ptr
<base::Value
> GetInfoAsValue(const std::set
<HostPortPair
>& aliases
);
193 const BoundNetLog
& net_log() const { return net_log_
; }
195 base::WeakPtr
<QuicClientSession
> GetWeakPtr();
197 // Returns the number of client hello messages that have been sent on the
198 // crypto stream. If the handshake has completed then this is one greater
199 // than the number of round-trips needed for the handshake.
200 int GetNumSentClientHellos() const;
202 // Returns true if |hostname| may be pooled onto this session. If this
203 // is a secure QUIC session, then |hostname| must match the certificate
204 // presented during the handshake.
205 bool CanPool(const std::string
& hostname
, PrivacyMode privacy_mode
) const;
207 const QuicServerId
& server_id() const { return server_id_
; }
209 QuicDisabledReason
disabled_reason() const { return disabled_reason_
; }
212 // QuicSession methods:
213 QuicDataStream
* CreateIncomingDynamicStream(QuicStreamId id
) override
;
216 friend class test::QuicClientSessionPeer
;
218 typedef std::set
<Observer
*> ObserverSet
;
219 typedef std::list
<StreamRequest
*> StreamRequestQueue
;
221 QuicReliableClientStream
* CreateOutgoingReliableStreamImpl();
222 // A completion callback invoked when a read completes.
223 void OnReadComplete(int result
);
225 void OnClosedStream();
227 // Close the session because of |error| and records it in UMA histogram.
228 void RecordAndCloseSessionOnError(int error
, QuicErrorCode quic_error
);
230 // A Session may be closed via any of three methods:
231 // OnConnectionClosed - called by the connection when the connection has been
232 // closed, perhaps due to a timeout or a protocol error.
233 // CloseSessionOnError - called from the owner of the session,
234 // the QuicStreamFactory, when there is an error.
235 // OnReadComplete - when there is a read error.
236 // This method closes all stream and performs any necessary cleanup.
237 void CloseSessionOnErrorInner(int net_error
, QuicErrorCode quic_error
);
239 void CloseAllStreams(int net_error
);
240 void CloseAllObservers(int net_error
);
242 // Notifies the factory that this session is going away and no more streams
243 // should be created from it. This needs to be called before closing any
244 // streams, because closing a stream may cause a new stream to be created.
245 void NotifyFactoryOfSessionGoingAway();
247 // Posts a task to notify the factory that this session has been closed.
248 void NotifyFactoryOfSessionClosedLater();
250 // Notifies the factory that this session has been closed which will
252 void NotifyFactoryOfSessionClosed();
254 void OnConnectTimeout();
256 QuicServerId server_id_
;
257 bool require_confirmation_
;
258 scoped_ptr
<QuicCryptoClientStream
> crypto_stream_
;
259 QuicStreamFactory
* stream_factory_
;
260 scoped_ptr
<DatagramClientSocket
> socket_
;
261 TransportSecurityState
* transport_security_state_
;
262 scoped_ptr
<QuicServerInfo
> server_info_
;
263 scoped_ptr
<CertVerifyResult
> cert_verify_result_
;
264 std::string pinning_failure_log_
;
265 ObserverSet observers_
;
266 StreamRequestQueue stream_requests_
;
267 CompletionCallback callback_
;
268 size_t num_total_streams_
;
269 base::TaskRunner
* task_runner_
;
270 BoundNetLog net_log_
;
271 QuicPacketReader packet_reader_
;
272 base::TimeTicks dns_resolution_end_time_
;
273 base::TimeTicks handshake_start_
; // Time the handshake was started.
274 scoped_ptr
<QuicConnectionLogger
> logger_
;
275 // True when the session is going away, and streams may no longer be created
276 // on this session. Existing stream will continue to be processed.
278 QuicDisabledReason disabled_reason_
;
279 base::WeakPtrFactory
<QuicClientSession
> weak_factory_
;
281 DISALLOW_COPY_AND_ASSIGN(QuicClientSession
);
286 #endif // NET_QUIC_QUIC_CLIENT_SESSION_H_