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