websocket_channel.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. // Copyright 2013 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. #ifndef NET_WEBSOCKETS_WEBSOCKET_CHANNEL_H_
  5. #define NET_WEBSOCKETS_WEBSOCKET_CHANNEL_H_
  6. #include <stdint.h>
  7. #include <memory>
  8. #include <string>
  9. #include <vector>
  10. #include "base/callback.h"
  11. #include "base/containers/queue.h"
  12. #include "base/i18n/streaming_utf8_validator.h"
  13. #include "base/memory/raw_ptr.h"
  14. #include "base/memory/scoped_refptr.h"
  15. #include "base/time/time.h"
  16. #include "base/timer/timer.h"
  17. #include "net/base/net_export.h"
  18. #include "net/websockets/websocket_event_interface.h"
  19. #include "net/websockets/websocket_frame.h"
  20. #include "net/websockets/websocket_stream.h"
  21. #include "third_party/abseil-cpp/absl/types/optional.h"
  22. #include "url/gurl.h"
  23. namespace url {
  24. class Origin;
  25. } // namespace url
  26. namespace net {
  27. class HttpRequestHeaders;
  28. class IOBuffer;
  29. class IPEndPoint;
  30. class NetLogWithSource;
  31. class IsolationInfo;
  32. class SiteForCookies;
  33. class URLRequest;
  34. class URLRequestContext;
  35. struct WebSocketHandshakeRequestInfo;
  36. struct WebSocketHandshakeResponseInfo;
  37. struct NetworkTrafficAnnotationTag;
  38. // Transport-independent implementation of WebSockets. Implements protocol
  39. // semantics that do not depend on the underlying transport. Provides the
  40. // interface to the content layer. Some WebSocket concepts are used here without
  41. // definition; please see the RFC at http://tools.ietf.org/html/rfc6455 for
  42. // clarification.
  43. class NET_EXPORT WebSocketChannel {
  44. public:
  45. // The type of a WebSocketStream creator callback. Must match the signature of
  46. // WebSocketStream::CreateAndConnectStream().
  47. typedef base::OnceCallback<std::unique_ptr<WebSocketStreamRequest>(
  48. const GURL&,
  49. const std::vector<std::string>&,
  50. const url::Origin&,
  51. const SiteForCookies&,
  52. const IsolationInfo&,
  53. const HttpRequestHeaders&,
  54. URLRequestContext*,
  55. const NetLogWithSource&,
  56. NetworkTrafficAnnotationTag,
  57. std::unique_ptr<WebSocketStream::ConnectDelegate>)>
  58. WebSocketStreamRequestCreationCallback;
  59. // Methods which return a value of type ChannelState may delete |this|. If the
  60. // return value is CHANNEL_DELETED, then the caller must return without making
  61. // any further access to member variables or methods.
  62. enum ChannelState { CHANNEL_ALIVE, CHANNEL_DELETED };
  63. // Creates a new WebSocketChannel in an idle state.
  64. // SendAddChannelRequest() must be called immediately afterwards to start the
  65. // connection process.
  66. WebSocketChannel(std::unique_ptr<WebSocketEventInterface> event_interface,
  67. URLRequestContext* url_request_context);
  68. WebSocketChannel(const WebSocketChannel&) = delete;
  69. WebSocketChannel& operator=(const WebSocketChannel&) = delete;
  70. virtual ~WebSocketChannel();
  71. // Starts the connection process.
  72. void SendAddChannelRequest(
  73. const GURL& socket_url,
  74. const std::vector<std::string>& requested_protocols,
  75. const url::Origin& origin,
  76. const SiteForCookies& site_for_cookies,
  77. const IsolationInfo& isolation_info,
  78. const HttpRequestHeaders& additional_headers,
  79. NetworkTrafficAnnotationTag traffic_annotation);
  80. // Sends a data frame to the remote side. It is the responsibility of the
  81. // caller to ensure that they have sufficient send quota to send this data,
  82. // otherwise the connection will be closed without sending. |fin| indicates
  83. // the last frame in a message, equivalent to "FIN" as specified in section
  84. // 5.2 of RFC6455. |buffer->data()| is the "Payload Data". If |op_code| is
  85. // kOpCodeText, or it is kOpCodeContinuation and the type the message is
  86. // Text, then |buffer->data()| must be a chunk of a valid UTF-8 message,
  87. // however there is no requirement for |buffer->data()| to be split on
  88. // character boundaries. Calling SendFrame may result in synchronous calls to
  89. // |event_interface_| which may result in this object being deleted. In that
  90. // case, the return value will be CHANNEL_DELETED.
  91. [[nodiscard]] ChannelState SendFrame(bool fin,
  92. WebSocketFrameHeader::OpCode op_code,
  93. scoped_refptr<IOBuffer> buffer,
  94. size_t buffer_size);
  95. // Calls WebSocketStream::ReadFrames() with the appropriate arguments. Stops
  96. // calling ReadFrames if no writable buffer in dataframe or WebSocketStream
  97. // starts async read.
  98. [[nodiscard]] ChannelState ReadFrames();
  99. // Starts the closing handshake for a client-initiated shutdown of the
  100. // connection. There is no API to close the connection without a closing
  101. // handshake, but destroying the WebSocketChannel object while connected will
  102. // effectively do that. |code| must be in the range 1000-4999. |reason| should
  103. // be a valid UTF-8 string or empty.
  104. //
  105. // Calling this function may result in synchronous calls to |event_interface_|
  106. // which may result in this object being deleted. In that case, the return
  107. // value will be CHANNEL_DELETED.
  108. [[nodiscard]] ChannelState StartClosingHandshake(uint16_t code,
  109. const std::string& reason);
  110. // Starts the connection process, using a specified creator callback rather
  111. // than the default. This is exposed for testing.
  112. void SendAddChannelRequestForTesting(
  113. const GURL& socket_url,
  114. const std::vector<std::string>& requested_protocols,
  115. const url::Origin& origin,
  116. const SiteForCookies& site_for_cookies,
  117. const IsolationInfo& isolation_info,
  118. const HttpRequestHeaders& additional_headers,
  119. NetworkTrafficAnnotationTag traffic_annotation,
  120. WebSocketStreamRequestCreationCallback callback);
  121. // The default timout for the closing handshake is a sensible value (see
  122. // kClosingHandshakeTimeoutSeconds in websocket_channel.cc). However, we can
  123. // set it to a very small value for testing purposes.
  124. void SetClosingHandshakeTimeoutForTesting(base::TimeDelta delay);
  125. // The default timout for the underlying connection close is a sensible value
  126. // (see kUnderlyingConnectionCloseTimeoutSeconds in websocket_channel.cc).
  127. // However, we can set it to a very small value for testing purposes.
  128. void SetUnderlyingConnectionCloseTimeoutForTesting(base::TimeDelta delay);
  129. // Called when the stream starts the WebSocket Opening Handshake.
  130. // This method is public for testing.
  131. void OnStartOpeningHandshake(
  132. std::unique_ptr<WebSocketHandshakeRequestInfo> request);
  133. private:
  134. // The object passes through a linear progression of states from
  135. // FRESHLY_CONSTRUCTED to CLOSED, except that the SEND_CLOSED and RECV_CLOSED
  136. // states may be skipped in case of error.
  137. enum State {
  138. FRESHLY_CONSTRUCTED,
  139. CONNECTING,
  140. CONNECTED,
  141. SEND_CLOSED, // A Close frame has been sent but not received.
  142. RECV_CLOSED, // Used briefly between receiving a Close frame and sending
  143. // the response. Once the response is sent, the state changes
  144. // to CLOSED.
  145. CLOSE_WAIT, // The Closing Handshake has completed, but the remote server
  146. // has not yet closed the connection.
  147. CLOSED, // The Closing Handshake has completed and the connection
  148. // has been closed; or the connection is failed.
  149. };
  150. // Implementation of WebSocketStream::ConnectDelegate for
  151. // WebSocketChannel. WebSocketChannel does not inherit from
  152. // WebSocketStream::ConnectDelegate directly to avoid cluttering the public
  153. // interface with the implementation of those methods, and because the
  154. // lifetime of a WebSocketChannel is longer than the lifetime of the
  155. // connection process.
  156. class ConnectDelegate;
  157. // Starts the connection process, using the supplied stream request creation
  158. // callback.
  159. void SendAddChannelRequestWithSuppliedCallback(
  160. const GURL& socket_url,
  161. const std::vector<std::string>& requested_protocols,
  162. const url::Origin& origin,
  163. const SiteForCookies& site_for_cookies,
  164. const IsolationInfo& isolation_info,
  165. const HttpRequestHeaders& additional_headers,
  166. NetworkTrafficAnnotationTag traffic_annotation,
  167. WebSocketStreamRequestCreationCallback callback);
  168. // Called when a URLRequest is created for handshaking.
  169. void OnCreateURLRequest(URLRequest* request);
  170. // Success callback from WebSocketStream::CreateAndConnectStream(). Reports
  171. // success to the event interface. May delete |this|.
  172. void OnConnectSuccess(
  173. std::unique_ptr<WebSocketStream> stream,
  174. std::unique_ptr<WebSocketHandshakeResponseInfo> response);
  175. // Failure callback from WebSocketStream::CreateAndConnectStream(). Reports
  176. // failure to the event interface. May delete |this|.
  177. void OnConnectFailure(const std::string& message,
  178. int net_error,
  179. absl::optional<int> response_code);
  180. // SSL certificate error callback from
  181. // WebSocketStream::CreateAndConnectStream(). Forwards the request to the
  182. // event interface.
  183. void OnSSLCertificateError(
  184. std::unique_ptr<WebSocketEventInterface::SSLErrorCallbacks>
  185. ssl_error_callbacks,
  186. int net_error,
  187. const SSLInfo& ssl_info,
  188. bool fatal);
  189. // Authentication request from WebSocketStream::CreateAndConnectStream().
  190. // Forwards the request to the event interface.
  191. int OnAuthRequired(const AuthChallengeInfo& auth_info,
  192. scoped_refptr<HttpResponseHeaders> response_headers,
  193. const IPEndPoint& remote_endpoint,
  194. base::OnceCallback<void(const AuthCredentials*)> callback,
  195. absl::optional<AuthCredentials>* credentials);
  196. // Sets |state_| to |new_state| and updates UMA if necessary.
  197. void SetState(State new_state);
  198. // Returns true if state_ is SEND_CLOSED, CLOSE_WAIT or CLOSED.
  199. bool InClosingState() const;
  200. // Calls WebSocketStream::WriteFrames() with the appropriate arguments
  201. [[nodiscard]] ChannelState WriteFrames();
  202. // Callback from WebSocketStream::WriteFrames. Sends pending data or adjusts
  203. // the send quota of the renderer channel as appropriate. |result| is a net
  204. // error code, usually OK. If |synchronous| is true, then OnWriteDone() is
  205. // being called from within the WriteFrames() loop and does not need to call
  206. // WriteFrames() itself.
  207. [[nodiscard]] ChannelState OnWriteDone(bool synchronous, int result);
  208. // Callback from WebSocketStream::ReadFrames. Handles any errors and processes
  209. // the returned chunks appropriately to their type. |result| is a net error
  210. // code. If |synchronous| is true, then OnReadDone() is being called from
  211. // within the ReadFrames() loop and does not need to call ReadFrames() itself.
  212. [[nodiscard]] ChannelState OnReadDone(bool synchronous, int result);
  213. // Handles a single frame that the object has received enough of to process.
  214. // May call |event_interface_| methods, send responses to the server, and
  215. // change the value of |state_|.
  216. //
  217. // This method performs sanity checks on the frame that are needed regardless
  218. // of the current state. Then, calls the HandleFrameByState() method below
  219. // which performs the appropriate action(s) depending on the current state.
  220. [[nodiscard]] ChannelState HandleFrame(std::unique_ptr<WebSocketFrame> frame);
  221. // Handles a single frame depending on the current state. It's used by the
  222. // HandleFrame() method.
  223. [[nodiscard]] ChannelState HandleFrameByState(
  224. const WebSocketFrameHeader::OpCode opcode,
  225. bool final,
  226. base::span<const char> payload);
  227. // Forwards a received data frame to the renderer, if connected. If
  228. // |expecting_continuation| is not equal to |expecting_to_read_continuation_|,
  229. // will fail the channel. Also checks the UTF-8 validity of text frames.
  230. [[nodiscard]] ChannelState HandleDataFrame(
  231. WebSocketFrameHeader::OpCode opcode,
  232. bool final,
  233. base::span<const char> payload);
  234. // Handles an incoming close frame with |code| and |reason|.
  235. [[nodiscard]] ChannelState HandleCloseFrame(uint16_t code,
  236. const std::string& reason);
  237. // Responds to a closing handshake initiated by the server.
  238. [[nodiscard]] ChannelState RespondToClosingHandshake();
  239. // Low-level method to send a single frame. Used for both data and control
  240. // frames. Either sends the frame immediately or buffers it to be scheduled
  241. // when the current write finishes. |fin| and |op_code| are defined as for
  242. // SendFrame() above, except that |op_code| may also be a control frame
  243. // opcode.
  244. [[nodiscard]] ChannelState SendFrameInternal(
  245. bool fin,
  246. WebSocketFrameHeader::OpCode op_code,
  247. scoped_refptr<IOBuffer> buffer,
  248. uint64_t buffer_size);
  249. // Performs the "Fail the WebSocket Connection" operation as defined in
  250. // RFC6455. A NotifyFailure message is sent to the renderer with |message|.
  251. // The renderer will log the message to the console but not expose it to
  252. // Javascript. Javascript will see a Close code of AbnormalClosure (1006) with
  253. // an empty reason string. If state_ is CONNECTED then a Close message is sent
  254. // to the remote host containing the supplied |code| and |reason|. If the
  255. // stream is open, closes it and sets state_ to CLOSED. This function deletes
  256. // |this|.
  257. void FailChannel(const std::string& message,
  258. uint16_t code,
  259. const std::string& reason);
  260. // Sends a Close frame to Start the WebSocket Closing Handshake, or to respond
  261. // to a Close frame from the server. As a special case, setting |code| to
  262. // kWebSocketErrorNoStatusReceived will create a Close frame with no payload;
  263. // this is symmetric with the behaviour of ParseClose.
  264. [[nodiscard]] ChannelState SendClose(uint16_t code,
  265. const std::string& reason);
  266. // Parses a Close frame payload. If no status code is supplied, then |code| is
  267. // set to 1005 (No status code) with empty |reason|. If the reason text is not
  268. // valid UTF-8, then |reason| is set to an empty string. If the payload size
  269. // is 1, or the supplied code is not permitted to be sent over the network,
  270. // then false is returned and |message| is set to an appropriate console
  271. // message.
  272. bool ParseClose(base::span<const char> payload,
  273. uint16_t* code,
  274. std::string* reason,
  275. std::string* message);
  276. // Drop this channel.
  277. // If there are pending opening handshake notifications, notify them
  278. // before dropping. This function deletes |this|.
  279. void DoDropChannel(bool was_clean, uint16_t code, const std::string& reason);
  280. // Called if the closing handshake times out. Closes the connection and
  281. // informs the |event_interface_| if appropriate.
  282. void CloseTimeout();
  283. // The URL of the remote server.
  284. GURL socket_url_;
  285. // The object receiving events.
  286. const std::unique_ptr<WebSocketEventInterface> event_interface_;
  287. // The URLRequestContext to pass to the WebSocketStream creator.
  288. const raw_ptr<URLRequestContext> url_request_context_;
  289. // The WebSocketStream on which to send and receive data.
  290. std::unique_ptr<WebSocketStream> stream_;
  291. // A data structure containing a vector of frames to be sent and the total
  292. // number of bytes contained in the vector.
  293. class SendBuffer;
  294. // Data that is currently pending write, or NULL if no write is pending.
  295. std::unique_ptr<SendBuffer> data_being_sent_;
  296. // Data that is queued up to write after the current write completes.
  297. // Only non-NULL when such data actually exists.
  298. std::unique_ptr<SendBuffer> data_to_send_next_;
  299. // Destination for the current call to WebSocketStream::ReadFrames
  300. std::vector<std::unique_ptr<WebSocketFrame>> read_frames_;
  301. // Handle to an in-progress WebSocketStream creation request. Only non-NULL
  302. // during the connection process.
  303. std::unique_ptr<WebSocketStreamRequest> stream_request_;
  304. // Timer for the closing handshake.
  305. base::OneShotTimer close_timer_;
  306. // Timeout for the closing handshake.
  307. base::TimeDelta closing_handshake_timeout_;
  308. // Timeout for the underlying connection close after completion of closing
  309. // handshake.
  310. base::TimeDelta underlying_connection_close_timeout_;
  311. // Storage for the status code and reason from the time the Close frame
  312. // arrives until the connection is closed and they are passed to
  313. // OnDropChannel().
  314. bool has_received_close_frame_ = false;
  315. uint16_t received_close_code_ = 0;
  316. std::string received_close_reason_;
  317. // The current state of the channel. Mainly used for sanity checking, but also
  318. // used to track the close state.
  319. State state_ = FRESHLY_CONSTRUCTED;
  320. // UTF-8 validator for outgoing Text messages.
  321. base::StreamingUtf8Validator outgoing_utf8_validator_;
  322. bool sending_text_message_ = false;
  323. // UTF-8 validator for incoming Text messages.
  324. base::StreamingUtf8Validator incoming_utf8_validator_;
  325. bool receiving_text_message_ = false;
  326. // True if we are in the middle of receiving a message.
  327. bool expecting_to_handle_continuation_ = false;
  328. // True if we have already sent the type (Text or Binary) of the current
  329. // message to the renderer. This can be false if the message is empty so far.
  330. bool initial_frame_forwarded_ = false;
  331. // True if we're waiting for OnReadDone() callback.
  332. bool is_reading_ = false;
  333. };
  334. } // namespace net
  335. #endif // NET_WEBSOCKETS_WEBSOCKET_CHANNEL_H_