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