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