Home | History | Annotate | Download | only in quic
      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.
      4 //
      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.
      9 
     10 #ifndef NET_QUIC_QUIC_CLIENT_SESSION_H_
     11 #define NET_QUIC_QUIC_CLIENT_SESSION_H_
     12 
     13 #include <string>
     14 
     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_protocol.h"
     25 #include "net/quic/quic_reliable_client_stream.h"
     26 
     27 namespace net {
     28 
     29 class CertVerifyResult;
     30 class DatagramClientSocket;
     31 class QuicConnectionHelper;
     32 class QuicCryptoClientStreamFactory;
     33 class QuicDefaultPacketWriter;
     34 class QuicServerId;
     35 class QuicServerInfo;
     36 class QuicStreamFactory;
     37 class SSLInfo;
     38 
     39 namespace test {
     40 class QuicClientSessionPeer;
     41 }  // namespace test
     42 
     43 class NET_EXPORT_PRIVATE QuicClientSession : public QuicClientSessionBase {
     44  public:
     45   // An interface for observing events on a session.
     46   class NET_EXPORT_PRIVATE Observer {
     47    public:
     48     virtual ~Observer() {}
     49     virtual void OnCryptoHandshakeConfirmed() = 0;
     50     virtual void OnSessionClosed(int error) = 0;
     51   };
     52 
     53   // A helper class used to manage a request to create a stream.
     54   class NET_EXPORT_PRIVATE StreamRequest {
     55    public:
     56     StreamRequest();
     57     ~StreamRequest();
     58 
     59     // Starts a request to create a stream.  If OK is returned, then
     60     // |stream| will be updated with the newly created stream.  If
     61     // ERR_IO_PENDING is returned, then when the request is eventuallly
     62     // complete |callback| will be called.
     63     int StartRequest(const base::WeakPtr<QuicClientSession>& session,
     64                      QuicReliableClientStream** stream,
     65                      const CompletionCallback& callback);
     66 
     67     // Cancels any pending stream creation request. May be called
     68     // repeatedly.
     69     void CancelRequest();
     70 
     71    private:
     72     friend class QuicClientSession;
     73 
     74     // Called by |session_| for an asynchronous request when the stream
     75     // request has finished successfully.
     76     void OnRequestCompleteSuccess(QuicReliableClientStream* stream);
     77 
     78     // Called by |session_| for an asynchronous request when the stream
     79     // request has finished with an error. Also called with ERR_ABORTED
     80     // if |session_| is destroyed while the stream request is still pending.
     81     void OnRequestCompleteFailure(int rv);
     82 
     83     base::WeakPtr<QuicClientSession> session_;
     84     CompletionCallback callback_;
     85     QuicReliableClientStream** stream_;
     86 
     87     DISALLOW_COPY_AND_ASSIGN(StreamRequest);
     88   };
     89 
     90   // Constructs a new session which will own |connection| and |helper|, but
     91   // not |stream_factory|, which must outlive this session.
     92   // TODO(rch): decouple the factory from the session via a Delegate interface.
     93   QuicClientSession(QuicConnection* connection,
     94                     scoped_ptr<DatagramClientSocket> socket,
     95                     scoped_ptr<QuicDefaultPacketWriter> writer,
     96                     QuicStreamFactory* stream_factory,
     97                     QuicCryptoClientStreamFactory* crypto_client_stream_factory,
     98                     scoped_ptr<QuicServerInfo> server_info,
     99                     const QuicServerId& server_id,
    100                     const QuicConfig& config,
    101                     QuicCryptoClientConfig* crypto_config,
    102                     base::TaskRunner* task_runner,
    103                     NetLog* net_log);
    104   virtual ~QuicClientSession();
    105 
    106   void AddObserver(Observer* observer);
    107   void RemoveObserver(Observer* observer);
    108 
    109   // Attempts to create a new stream.  If the stream can be
    110   // created immediately, returns OK.  If the open stream limit
    111   // has been reached, returns ERR_IO_PENDING, and |request|
    112   // will be added to the stream requets queue and will
    113   // be completed asynchronously.
    114   // TODO(rch): remove |stream| from this and use setter on |request|
    115   // and fix in spdy too.
    116   int TryCreateStream(StreamRequest* request,
    117                       QuicReliableClientStream** stream);
    118 
    119   // Cancels the pending stream creation request.
    120   void CancelRequest(StreamRequest* request);
    121 
    122   // QuicSession methods:
    123   virtual void OnStreamFrames(
    124       const std::vector<QuicStreamFrame>& frames) OVERRIDE;
    125   virtual QuicReliableClientStream* CreateOutgoingDataStream() OVERRIDE;
    126   virtual QuicCryptoClientStream* GetCryptoStream() OVERRIDE;
    127   virtual void CloseStream(QuicStreamId stream_id) OVERRIDE;
    128   virtual void SendRstStream(QuicStreamId id,
    129                              QuicRstStreamErrorCode error,
    130                              QuicStreamOffset bytes_written) OVERRIDE;
    131   virtual void OnCryptoHandshakeEvent(CryptoHandshakeEvent event) OVERRIDE;
    132   virtual void OnCryptoHandshakeMessageSent(
    133       const CryptoHandshakeMessage& message) OVERRIDE;
    134   virtual void OnCryptoHandshakeMessageReceived(
    135       const CryptoHandshakeMessage& message) OVERRIDE;
    136   virtual bool GetSSLInfo(SSLInfo* ssl_info) const OVERRIDE;
    137 
    138   // QuicClientSessionBase methods:
    139   virtual void OnProofValid(
    140       const QuicCryptoClientConfig::CachedState& cached) OVERRIDE;
    141   virtual void OnProofVerifyDetailsAvailable(
    142       const ProofVerifyDetails& verify_details) OVERRIDE;
    143 
    144   // QuicConnectionVisitorInterface methods:
    145   virtual void OnConnectionClosed(QuicErrorCode error, bool from_peer) OVERRIDE;
    146   virtual void OnSuccessfulVersionNegotiation(
    147       const QuicVersion& version) OVERRIDE;
    148 
    149   // Performs a crypto handshake with the server.
    150   int CryptoConnect(bool require_confirmation,
    151                     const CompletionCallback& callback);
    152 
    153   // Resumes a crypto handshake with the server after a timeout.
    154   int ResumeCryptoConnect(const CompletionCallback& callback);
    155 
    156   // Causes the QuicConnectionHelper to start reading from the socket
    157   // and passing the data along to the QuicConnection.
    158   void StartReading();
    159 
    160   // Close the session because of |error| and notifies the factory
    161   // that this session has been closed, which will delete the session.
    162   void CloseSessionOnError(int error);
    163 
    164   base::Value* GetInfoAsValue(const std::set<HostPortPair>& aliases);
    165 
    166   const BoundNetLog& net_log() const { return net_log_; }
    167 
    168   base::WeakPtr<QuicClientSession> GetWeakPtr();
    169 
    170   // Returns the number of client hello messages that have been sent on the
    171   // crypto stream. If the handshake has completed then this is one greater
    172   // than the number of round-trips needed for the handshake.
    173   int GetNumSentClientHellos() const;
    174 
    175   // Returns true if |hostname| may be pooled onto this session.  If this
    176   // is a secure QUIC session, then |hostname| must match the certificate
    177   // presented during the handshake.
    178   bool CanPool(const std::string& hostname) const;
    179 
    180  protected:
    181   // QuicSession methods:
    182   virtual QuicDataStream* CreateIncomingDataStream(QuicStreamId id) OVERRIDE;
    183 
    184  private:
    185   friend class test::QuicClientSessionPeer;
    186 
    187   typedef std::set<Observer*> ObserverSet;
    188   typedef std::list<StreamRequest*> StreamRequestQueue;
    189 
    190   QuicReliableClientStream* CreateOutgoingReliableStreamImpl();
    191   // A completion callback invoked when a read completes.
    192   void OnReadComplete(int result);
    193 
    194   void OnClosedStream();
    195 
    196   // A Session may be closed via any of three methods:
    197   // OnConnectionClosed - called by the connection when the connection has been
    198   //     closed, perhaps due to a timeout or a protocol error.
    199   // CloseSessionOnError - called from the owner of the session,
    200   //     the QuicStreamFactory, when there is an error.
    201   // OnReadComplete - when there is a read error.
    202   // This method closes all stream and performs any necessary cleanup.
    203   void CloseSessionOnErrorInner(int net_error, QuicErrorCode quic_error);
    204 
    205   void CloseAllStreams(int net_error);
    206   void CloseAllObservers(int net_error);
    207 
    208   // Notifies the factory that this session is going away and no more streams
    209   // should be created from it.  This needs to be called before closing any
    210   // streams, because closing a stream may cause a new stream to be created.
    211   void NotifyFactoryOfSessionGoingAway();
    212 
    213   // Posts a task to notify the factory that this session has been closed.
    214   void NotifyFactoryOfSessionClosedLater();
    215 
    216   // Notifies the factory that this session has been closed which will
    217   // delete |this|.
    218   void NotifyFactoryOfSessionClosed();
    219 
    220   void OnConnectTimeout();
    221 
    222   bool require_confirmation_;
    223   scoped_ptr<QuicCryptoClientStream> crypto_stream_;
    224   QuicStreamFactory* stream_factory_;
    225   scoped_ptr<DatagramClientSocket> socket_;
    226   scoped_ptr<QuicDefaultPacketWriter> writer_;
    227   scoped_refptr<IOBufferWithSize> read_buffer_;
    228   scoped_ptr<QuicServerInfo> server_info_;
    229   scoped_ptr<CertVerifyResult> cert_verify_result_;
    230   std::string pinning_failure_log_;
    231   ObserverSet observers_;
    232   StreamRequestQueue stream_requests_;
    233   bool read_pending_;
    234   CompletionCallback callback_;
    235   size_t num_total_streams_;
    236   base::TaskRunner* task_runner_;
    237   BoundNetLog net_log_;
    238   base::TimeTicks handshake_start_;  // Time the handshake was started.
    239   QuicConnectionLogger logger_;
    240   // Number of packets read in the current read loop.
    241   size_t num_packets_read_;
    242   // True when the session is going away, and streams may no longer be created
    243   // on this session. Existing stream will continue to be processed.
    244   bool going_away_;
    245   base::WeakPtrFactory<QuicClientSession> weak_factory_;
    246 
    247   DISALLOW_COPY_AND_ASSIGN(QuicClientSession);
    248 };
    249 
    250 }  // namespace net
    251 
    252 #endif  // NET_QUIC_QUIC_CLIENT_SESSION_H_
    253