• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
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 <memory>
9 #include <string>
10 #include <vector>
11 
12 #include "base/functional/callback_forward.h"
13 #include "base/memory/scoped_refptr.h"
14 #include "base/time/time.h"
15 #include "net/base/completion_once_callback.h"
16 #include "net/base/isolation_info.h"
17 #include "net/base/net_export.h"
18 #include "net/cookies/site_for_cookies.h"
19 #include "net/log/net_log_with_source.h"
20 #include "net/websockets/websocket_event_interface.h"
21 #include "net/websockets/websocket_handshake_request_info.h"
22 #include "net/websockets/websocket_handshake_response_info.h"
23 #include "third_party/abseil-cpp/absl/types/optional.h"
24 
25 class GURL;
26 
27 namespace base {
28 class OneShotTimer;
29 }
30 
31 namespace url {
32 class Origin;
33 }  // namespace url
34 
35 namespace net {
36 
37 class AuthChallengeInfo;
38 class AuthCredentials;
39 class HttpRequestHeaders;
40 class HttpResponseHeaders;
41 class IPEndPoint;
42 class NetLogWithSource;
43 class URLRequest;
44 class URLRequestContext;
45 struct WebSocketFrame;
46 class WebSocketBasicHandshakeStream;
47 class WebSocketHttp2HandshakeStream;
48 class WebSocketHttp3HandshakeStream;
49 struct NetworkTrafficAnnotationTag;
50 
51 // WebSocketStreamRequest is the caller's handle to the process of creation of a
52 // WebSocketStream. Deleting the object before the ConnectDelegate OnSuccess or
53 // OnFailure callbacks are called will cancel the request (and neither callback
54 // will be called). After OnSuccess or OnFailure have been called, this object
55 // may be safely deleted without side-effects.
56 class NET_EXPORT_PRIVATE WebSocketStreamRequest {
57  public:
58   virtual ~WebSocketStreamRequest();
59 };
60 
61 // A subclass of WebSocketStreamRequest that exposes methods that are used as
62 // part of the handshake.
63 class NET_EXPORT_PRIVATE WebSocketStreamRequestAPI
64     : public WebSocketStreamRequest {
65  public:
66   virtual void OnBasicHandshakeStreamCreated(
67       WebSocketBasicHandshakeStream* handshake_stream) = 0;
68   virtual void OnHttp2HandshakeStreamCreated(
69       WebSocketHttp2HandshakeStream* handshake_stream) = 0;
70   virtual void OnHttp3HandshakeStreamCreated(
71       WebSocketHttp3HandshakeStream* handshake_stream) = 0;
72   virtual void OnFailure(const std::string& message,
73                          int net_error,
74                          absl::optional<int> response_code) = 0;
75 };
76 
77 // WebSocketStream is a transport-agnostic interface for reading and writing
78 // WebSocket frames. This class provides an abstraction for WebSocket streams
79 // based on various transport layers, such as normal WebSocket connections
80 // (WebSocket protocol upgraded from HTTP handshake), SPDY transports, or
81 // WebSocket connections with multiplexing extension. Subtypes of
82 // WebSocketStream are responsible for managing the underlying transport
83 // appropriately.
84 //
85 // All functions except Close() can be asynchronous. If an operation cannot
86 // be finished synchronously, the function returns ERR_IO_PENDING, and
87 // |callback| will be called when the operation is finished. Non-null |callback|
88 // must be provided to these functions.
89 
90 class NET_EXPORT_PRIVATE WebSocketStream {
91  public:
92   // A concrete object derived from ConnectDelegate is supplied by the caller to
93   // CreateAndConnectStream() to receive the result of the connection.
94   class NET_EXPORT_PRIVATE ConnectDelegate {
95    public:
96     virtual ~ConnectDelegate();
97     // Called when the URLRequest is created.
98     virtual void OnCreateRequest(URLRequest* url_request) = 0;
99 
100     // Called on successful connection. The parameter is an object derived from
101     // WebSocketStream.
102     virtual void OnSuccess(
103         std::unique_ptr<WebSocketStream> stream,
104         std::unique_ptr<WebSocketHandshakeResponseInfo> response) = 0;
105 
106     // Called on failure to connect.
107     // |message| contains defails of the failure.
108     virtual void OnFailure(const std::string& message,
109                            int net_error,
110                            absl::optional<int> response_code) = 0;
111 
112     // Called when the WebSocket Opening Handshake starts.
113     virtual void OnStartOpeningHandshake(
114         std::unique_ptr<WebSocketHandshakeRequestInfo> request) = 0;
115 
116     // Called when there is an SSL certificate error. Should call
117     // ssl_error_callbacks->ContinueSSLRequest() or
118     // ssl_error_callbacks->CancelSSLRequest().
119     virtual void OnSSLCertificateError(
120         std::unique_ptr<WebSocketEventInterface::SSLErrorCallbacks>
121             ssl_error_callbacks,
122         int net_error,
123         const SSLInfo& ssl_info,
124         bool fatal) = 0;
125 
126     // Called when authentication is required. Returns a net error. The opening
127     // handshake is blocked when this function returns ERR_IO_PENDING.
128     // In that case calling |callback| resumes the handshake. |callback| can be
129     // called during the opening handshake. An implementation can rewrite
130     // |*credentials| (in the sync case) or provide new credentials (in the
131     // async case).
132     // Providing null credentials (nullopt in the sync case and nullptr in the
133     // async case) cancels authentication. Otherwise the new credentials are set
134     // and the opening handshake will be retried with the credentials.
135     virtual int OnAuthRequired(
136         const AuthChallengeInfo& auth_info,
137         scoped_refptr<HttpResponseHeaders> response_headers,
138         const IPEndPoint& remote_endpoint,
139         base::OnceCallback<void(const AuthCredentials*)> callback,
140         absl::optional<AuthCredentials>* credentials) = 0;
141   };
142 
143   // Create and connect a WebSocketStream of an appropriate type. The actual
144   // concrete type returned depends on whether multiplexing or SPDY are being
145   // used to communicate with the remote server. If the handshake completed
146   // successfully, then connect_delegate->OnSuccess() is called with a
147   // WebSocketStream instance. If it failed, then connect_delegate->OnFailure()
148   // is called with a WebSocket result code corresponding to the error. Deleting
149   // the returned WebSocketStreamRequest object will cancel the connection, in
150   // which case the |connect_delegate| object that the caller passed will be
151   // deleted without any of its methods being called. Unless cancellation is
152   // required, the caller should keep the WebSocketStreamRequest object alive
153   // until connect_delegate->OnSuccess() or OnFailure() have been called, then
154   // it is safe to delete.
155   static std::unique_ptr<WebSocketStreamRequest> CreateAndConnectStream(
156       const GURL& socket_url,
157       const std::vector<std::string>& requested_subprotocols,
158       const url::Origin& origin,
159       const SiteForCookies& site_for_cookies,
160       const IsolationInfo& isolation_info,
161       const HttpRequestHeaders& additional_headers,
162       URLRequestContext* url_request_context,
163       const NetLogWithSource& net_log,
164       NetworkTrafficAnnotationTag traffic_annotation,
165       std::unique_ptr<ConnectDelegate> connect_delegate);
166 
167   // Alternate version of CreateAndConnectStream() for testing use only. It
168   // takes |timer| as the handshake timeout timer, and for methods on
169   // WebSocketStreamRequestAPI calls the |api_delegate| object before the
170   // in-built behaviour if non-null.
171   static std::unique_ptr<WebSocketStreamRequest>
172   CreateAndConnectStreamForTesting(
173       const GURL& socket_url,
174       const std::vector<std::string>& requested_subprotocols,
175       const url::Origin& origin,
176       const SiteForCookies& site_for_cookies,
177       const IsolationInfo& isolation_info,
178       const HttpRequestHeaders& additional_headers,
179       URLRequestContext* url_request_context,
180       const NetLogWithSource& net_log,
181       NetworkTrafficAnnotationTag traffic_annotation,
182       std::unique_ptr<ConnectDelegate> connect_delegate,
183       std::unique_ptr<base::OneShotTimer> timer,
184       std::unique_ptr<WebSocketStreamRequestAPI> api_delegate);
185 
186   WebSocketStream(const WebSocketStream&) = delete;
187   WebSocketStream& operator=(const WebSocketStream&) = delete;
188 
189   // Derived classes must make sure Close() is called when the stream is not
190   // closed on destruction.
191   virtual ~WebSocketStream();
192 
193   // Reads WebSocket frame data. This operation finishes when new frame data
194   // becomes available.
195   //
196   // |frames| remains owned by the caller and must be valid until the
197   // operation completes or Close() is called. |frames| must be empty on
198   // calling.
199   //
200   // This function should not be called while the previous call of ReadFrames()
201   // is still pending.
202   //
203   // Returns net::OK or one of the net::ERR_* codes.
204   //
205   // frames->size() >= 1 if the result is OK.
206   //
207   // Only frames with complete header information are inserted into |frames|. If
208   // the currently available bytes of a new frame do not form a complete frame
209   // header, then the implementation will buffer them until all the fields in
210   // the WebSocketFrameHeader object can be filled. If ReadFrames() is freshly
211   // called in this situation, it will return ERR_IO_PENDING exactly as if no
212   // data was available.
213   //
214   // Original frame boundaries are not preserved. In particular, if only part of
215   // a frame is available, then the frame will be split, and the available data
216   // will be returned immediately.
217   //
218   // When the socket is closed on the remote side, this method will return
219   // ERR_CONNECTION_CLOSED. It will not return OK with an empty vector.
220   //
221   // If the connection is closed in the middle of receiving an incomplete frame,
222   // ReadFrames may discard the incomplete frame. Since the renderer will
223   // discard any incomplete messages when the connection is closed, this makes
224   // no difference to the overall semantics.
225   //
226   // Implementations of ReadFrames() must be able to handle being deleted during
227   // the execution of callback.Run(). In practice this means that the method
228   // calling callback.Run() (and any calling methods in the same object) must
229   // return immediately without any further method calls or access to member
230   // variables. Implementors should write test(s) for this case.
231   //
232   // Extensions which use reserved header bits should clear them when they are
233   // set correctly. If the reserved header bits are set incorrectly, it is okay
234   // to leave it to the caller to report the error.
235   //
236   // Each WebSocketFrame.data is owned by WebSocketStream and must be valid
237   // until next ReadFrames() call.
238   virtual int ReadFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
239                          CompletionOnceCallback callback) = 0;
240 
241   // Writes WebSocket frame data.
242   //
243   // |frames| must be valid until the operation completes or Close() is called.
244   //
245   // This function must not be called while a previous call of WriteFrames() is
246   // still pending.
247   //
248   // This method will only return OK if all frames were written completely.
249   // Otherwise it will return an appropriate net error code.
250   //
251   // The callback implementation is permitted to delete this
252   // object. Implementations of WriteFrames() should be robust against
253   // this. This generally means returning to the event loop immediately after
254   // calling the callback.
255   virtual int WriteFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
256                           CompletionOnceCallback callback) = 0;
257 
258   // Closes the stream. All pending I/O operations (if any) are cancelled
259   // at this point, so |frames| can be freed.
260   virtual void Close() = 0;
261 
262   // The subprotocol that was negotiated for the stream. If no protocol was
263   // negotiated, then the empty string is returned.
264   virtual std::string GetSubProtocol() const = 0;
265 
266   // The extensions that were negotiated for the stream. Since WebSocketStreams
267   // can be layered, this may be different from what this particular
268   // WebSocketStream implements. The primary purpose of this accessor is to make
269   // the data available to Javascript. The format of the string is identical to
270   // the contents of the Sec-WebSocket-Extensions header supplied by the server,
271   // with some canonicalisations applied (leading and trailing whitespace
272   // removed, multiple headers concatenated into one comma-separated list). See
273   // RFC6455 section 9.1 for the exact format specification. If no
274   // extensions were negotiated, the empty string is returned.
275   virtual std::string GetExtensions() const = 0;
276 
277   virtual const NetLogWithSource& GetNetLogWithSource() const = 0;
278 
279  protected:
280   WebSocketStream();
281 };
282 
283 // A helper function used in the implementation of CreateAndConnectStream() and
284 // WebSocketBasicHandshakeStream. It creates a WebSocketHandshakeResponseInfo
285 // object and dispatches it to the OnFinishOpeningHandshake() method of the
286 // supplied |connect_delegate|.
287 void WebSocketDispatchOnFinishOpeningHandshake(
288     WebSocketStream::ConnectDelegate* connect_delegate,
289     const GURL& gurl,
290     const scoped_refptr<HttpResponseHeaders>& headers,
291     const IPEndPoint& remote_endpoint,
292     base::Time response_time);
293 
294 }  // namespace net
295 
296 #endif  // NET_WEBSOCKETS_WEBSOCKET_STREAM_H_
297