Home | History | Annotate | Download | only in websockets
      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 #ifndef NET_WEBSOCKETS_WEBSOCKET_STREAM_H_
      6 #define NET_WEBSOCKETS_WEBSOCKET_STREAM_H_
      7 
      8 #include <string>
      9 #include <vector>
     10 
     11 #include "base/basictypes.h"
     12 #include "base/callback_forward.h"
     13 #include "base/memory/ref_counted.h"
     14 #include "base/memory/scoped_ptr.h"
     15 #include "base/memory/scoped_vector.h"
     16 #include "base/time/time.h"
     17 #include "net/base/completion_callback.h"
     18 #include "net/base/net_export.h"
     19 #include "net/websockets/websocket_event_interface.h"
     20 #include "net/websockets/websocket_handshake_request_info.h"
     21 #include "net/websockets/websocket_handshake_response_info.h"
     22 
     23 class GURL;
     24 
     25 namespace url {
     26 class Origin;
     27 }  // namespace url
     28 
     29 namespace net {
     30 
     31 class BoundNetLog;
     32 class URLRequestContext;
     33 struct WebSocketFrame;
     34 
     35 // WebSocketStreamRequest is the caller's handle to the process of creation of a
     36 // WebSocketStream. Deleting the object before the OnSuccess or OnFailure
     37 // callbacks are called will cancel the request (and neither callback will be
     38 // called). After OnSuccess or OnFailure have been called, this object may be
     39 // safely deleted without side-effects.
     40 class NET_EXPORT_PRIVATE WebSocketStreamRequest {
     41  public:
     42   virtual ~WebSocketStreamRequest();
     43 };
     44 
     45 // WebSocketStream is a transport-agnostic interface for reading and writing
     46 // WebSocket frames. This class provides an abstraction for WebSocket streams
     47 // based on various transport layers, such as normal WebSocket connections
     48 // (WebSocket protocol upgraded from HTTP handshake), SPDY transports, or
     49 // WebSocket connections with multiplexing extension. Subtypes of
     50 // WebSocketStream are responsible for managing the underlying transport
     51 // appropriately.
     52 //
     53 // All functions except Close() can be asynchronous. If an operation cannot
     54 // be finished synchronously, the function returns ERR_IO_PENDING, and
     55 // |callback| will be called when the operation is finished. Non-null |callback|
     56 // must be provided to these functions.
     57 
     58 class NET_EXPORT_PRIVATE WebSocketStream {
     59  public:
     60   // A concrete object derived from ConnectDelegate is supplied by the caller to
     61   // CreateAndConnectStream() to receive the result of the connection.
     62   class NET_EXPORT_PRIVATE ConnectDelegate {
     63    public:
     64     virtual ~ConnectDelegate();
     65     // Called on successful connection. The parameter is an object derived from
     66     // WebSocketStream.
     67     virtual void OnSuccess(scoped_ptr<WebSocketStream> stream) = 0;
     68 
     69     // Called on failure to connect.
     70     // |message| contains defails of the failure.
     71     virtual void OnFailure(const std::string& message) = 0;
     72 
     73     // Called when the WebSocket Opening Handshake starts.
     74     virtual void OnStartOpeningHandshake(
     75         scoped_ptr<WebSocketHandshakeRequestInfo> request) = 0;
     76 
     77     // Called when the WebSocket Opening Handshake ends.
     78     virtual void OnFinishOpeningHandshake(
     79         scoped_ptr<WebSocketHandshakeResponseInfo> response) = 0;
     80 
     81     // Called when there is an SSL certificate error. Should call
     82     // ssl_error_callbacks->ContinueSSLRequest() or
     83     // ssl_error_callbacks->CancelSSLRequest().
     84     virtual void OnSSLCertificateError(
     85         scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks>
     86             ssl_error_callbacks,
     87         const SSLInfo& ssl_info,
     88         bool fatal) = 0;
     89   };
     90 
     91   // Create and connect a WebSocketStream of an appropriate type. The actual
     92   // concrete type returned depends on whether multiplexing or SPDY are being
     93   // used to communicate with the remote server. If the handshake completed
     94   // successfully, then connect_delegate->OnSuccess() is called with a
     95   // WebSocketStream instance. If it failed, then connect_delegate->OnFailure()
     96   // is called with a WebSocket result code corresponding to the error. Deleting
     97   // the returned WebSocketStreamRequest object will cancel the connection, in
     98   // which case the |connect_delegate| object that the caller passed will be
     99   // deleted without any of its methods being called. Unless cancellation is
    100   // required, the caller should keep the WebSocketStreamRequest object alive
    101   // until connect_delegate->OnSuccess() or OnFailure() have been called, then
    102   // it is safe to delete.
    103   static scoped_ptr<WebSocketStreamRequest> CreateAndConnectStream(
    104       const GURL& socket_url,
    105       const std::vector<std::string>& requested_subprotocols,
    106       const url::Origin& origin,
    107       URLRequestContext* url_request_context,
    108       const BoundNetLog& net_log,
    109       scoped_ptr<ConnectDelegate> connect_delegate);
    110 
    111   // Derived classes must make sure Close() is called when the stream is not
    112   // closed on destruction.
    113   virtual ~WebSocketStream();
    114 
    115   // Reads WebSocket frame data. This operation finishes when new frame data
    116   // becomes available.
    117   //
    118   // |frames| remains owned by the caller and must be valid until the
    119   // operation completes or Close() is called. |frames| must be empty on
    120   // calling.
    121   //
    122   // This function should not be called while the previous call of ReadFrames()
    123   // is still pending.
    124   //
    125   // Returns net::OK or one of the net::ERR_* codes.
    126   //
    127   // frames->size() >= 1 if the result is OK.
    128   //
    129   // Only frames with complete header information are inserted into |frames|. If
    130   // the currently available bytes of a new frame do not form a complete frame
    131   // header, then the implementation will buffer them until all the fields in
    132   // the WebSocketFrameHeader object can be filled. If ReadFrames() is freshly
    133   // called in this situation, it will return ERR_IO_PENDING exactly as if no
    134   // data was available.
    135   //
    136   // Original frame boundaries are not preserved. In particular, if only part of
    137   // a frame is available, then the frame will be split, and the available data
    138   // will be returned immediately.
    139   //
    140   // When the socket is closed on the remote side, this method will return
    141   // ERR_CONNECTION_CLOSED. It will not return OK with an empty vector.
    142   //
    143   // If the connection is closed in the middle of receiving an incomplete frame,
    144   // ReadFrames may discard the incomplete frame. Since the renderer will
    145   // discard any incomplete messages when the connection is closed, this makes
    146   // no difference to the overall semantics.
    147   //
    148   // Implementations of ReadFrames() must be able to handle being deleted during
    149   // the execution of callback.Run(). In practice this means that the method
    150   // calling callback.Run() (and any calling methods in the same object) must
    151   // return immediately without any further method calls or access to member
    152   // variables. Implementors should write test(s) for this case.
    153   //
    154   // Extensions which use reserved header bits should clear them when they are
    155   // set correctly. If the reserved header bits are set incorrectly, it is okay
    156   // to leave it to the caller to report the error.
    157   virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
    158                          const CompletionCallback& callback) = 0;
    159 
    160   // Writes WebSocket frame data.
    161   //
    162   // |frames| must be valid until the operation completes or Close() is called.
    163   //
    164   // This function must not be called while a previous call of WriteFrames() is
    165   // still pending.
    166   //
    167   // This method will only return OK if all frames were written completely.
    168   // Otherwise it will return an appropriate net error code.
    169   //
    170   // The callback implementation is permitted to delete this
    171   // object. Implementations of WriteFrames() should be robust against
    172   // this. This generally means returning to the event loop immediately after
    173   // calling the callback.
    174   virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
    175                           const CompletionCallback& callback) = 0;
    176 
    177   // Closes the stream. All pending I/O operations (if any) are cancelled
    178   // at this point, so |frames| can be freed.
    179   virtual void Close() = 0;
    180 
    181   // The subprotocol that was negotiated for the stream. If no protocol was
    182   // negotiated, then the empty string is returned.
    183   virtual std::string GetSubProtocol() const = 0;
    184 
    185   // The extensions that were negotiated for the stream. Since WebSocketStreams
    186   // can be layered, this may be different from what this particular
    187   // WebSocketStream implements. The primary purpose of this accessor is to make
    188   // the data available to Javascript. The format of the string is identical to
    189   // the contents of the Sec-WebSocket-Extensions header supplied by the server,
    190   // with some canonicalisations applied (leading and trailing whitespace
    191   // removed, multiple headers concatenated into one comma-separated list). See
    192   // RFC6455 section 9.1 for the exact format specification. If no
    193   // extensions were negotiated, the empty string is returned.
    194   virtual std::string GetExtensions() const = 0;
    195 
    196  protected:
    197   WebSocketStream();
    198 
    199  private:
    200   DISALLOW_COPY_AND_ASSIGN(WebSocketStream);
    201 };
    202 
    203 // A helper function used in the implementation of CreateAndConnectStream() and
    204 // WebSocketBasicHandshakeStream. It creates a WebSocketHandshakeResponseInfo
    205 // object and dispatches it to the OnFinishOpeningHandshake() method of the
    206 // supplied |connect_delegate|.
    207 void WebSocketDispatchOnFinishOpeningHandshake(
    208     WebSocketStream::ConnectDelegate* connect_delegate,
    209     const GURL& gurl,
    210     const scoped_refptr<HttpResponseHeaders>& headers,
    211     base::Time response_time);
    212 
    213 }  // namespace net
    214 
    215 #endif  // NET_WEBSOCKETS_WEBSOCKET_STREAM_H_
    216