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.
5 #ifndef NET_WEBSOCKETS_WEBSOCKET_CHANNEL_H_
6 #define NET_WEBSOCKETS_WEBSOCKET_CHANNEL_H_
11 #include "base/basictypes.h"
12 #include "base/callback.h"
13 #include "base/compiler_specific.h" // for WARN_UNUSED_RESULT
14 #include "base/i18n/streaming_utf8_validator.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/memory/scoped_vector.h"
17 #include "base/time/time.h"
18 #include "base/timer/timer.h"
19 #include "net/base/net_export.h"
20 #include "net/websockets/websocket_event_interface.h"
21 #include "net/websockets/websocket_frame.h"
22 #include "net/websockets/websocket_stream.h"
29 class URLRequestContext;
30 struct WebSocketHandshakeRequestInfo;
31 struct WebSocketHandshakeResponseInfo;
33 // Transport-independent implementation of WebSockets. Implements protocol
34 // semantics that do not depend on the underlying transport. Provides the
35 // interface to the content layer. Some WebSocket concepts are used here without
36 // definition; please see the RFC at http://tools.ietf.org/html/rfc6455 for
38 class NET_EXPORT WebSocketChannel {
40 // The type of a WebSocketStream creator callback. Must match the signature of
41 // WebSocketStream::CreateAndConnectStream().
42 typedef base::Callback<scoped_ptr<WebSocketStreamRequest>(
44 const std::vector<std::string>&,
48 scoped_ptr<WebSocketStream::ConnectDelegate>)> WebSocketStreamCreator;
50 // Creates a new WebSocketChannel in an idle state.
51 // SendAddChannelRequest() must be called immediately afterwards to start the
52 // connection process.
53 WebSocketChannel(scoped_ptr<WebSocketEventInterface> event_interface,
54 URLRequestContext* url_request_context);
55 virtual ~WebSocketChannel();
57 // Starts the connection process.
58 void SendAddChannelRequest(
59 const GURL& socket_url,
60 const std::vector<std::string>& requested_protocols,
63 // Sends a data frame to the remote side. The frame should usually be no
64 // larger than 32KB to prevent the time required to copy the buffers from from
65 // unduly delaying other tasks that need to run on the IO thread. This method
66 // has a hard limit of 2GB. It is the responsibility of the caller to ensure
67 // that they have sufficient send quota to send this data, otherwise the
68 // connection will be closed without sending. |fin| indicates the last frame
69 // in a message, equivalent to "FIN" as specified in section 5.2 of
70 // RFC6455. |data| is the "Payload Data". If |op_code| is kOpCodeText, or it
71 // is kOpCodeContinuation and the type the message is Text, then |data| must
72 // be a chunk of a valid UTF-8 message, however there is no requirement for
73 // |data| to be split on character boundaries.
74 void SendFrame(bool fin,
75 WebSocketFrameHeader::OpCode op_code,
76 const std::vector<char>& data);
78 // Sends |quota| units of flow control to the remote side. If the underlying
79 // transport has a concept of |quota|, then it permits the remote server to
80 // send up to |quota| units of data.
81 void SendFlowControl(int64 quota);
83 // Starts the closing handshake for a client-initiated shutdown of the
84 // connection. There is no API to close the connection without a closing
85 // handshake, but destroying the WebSocketChannel object while connected will
86 // effectively do that. |code| must be in the range 1000-4999. |reason| should
87 // be a valid UTF-8 string or empty.
89 // This does *not* trigger the event OnClosingHandshake(). The caller should
90 // assume that the closing handshake has started and perform the equivalent
91 // processing to OnClosingHandshake() if necessary.
92 void StartClosingHandshake(uint16 code, const std::string& reason);
94 // Starts the connection process, using a specified creator callback rather
95 // than the default. This is exposed for testing.
96 void SendAddChannelRequestForTesting(
97 const GURL& socket_url,
98 const std::vector<std::string>& requested_protocols,
100 const WebSocketStreamCreator& creator);
102 // The default timout for the closing handshake is a sensible value (see
103 // kClosingHandshakeTimeoutSeconds in websocket_channel.cc). However, we can
104 // set it to a very small value for testing purposes.
105 void SetClosingHandshakeTimeoutForTesting(base::TimeDelta delay);
107 // Called when the stream starts the WebSocket Opening Handshake.
108 // This method is public for testing.
109 void OnStartOpeningHandshake(
110 scoped_ptr<WebSocketHandshakeRequestInfo> request);
112 // Called when the stream ends the WebSocket Opening Handshake.
113 // This method is public for testing.
114 void OnFinishOpeningHandshake(
115 scoped_ptr<WebSocketHandshakeResponseInfo> response);
118 class HandshakeNotificationSender;
120 // Methods which return a value of type ChannelState may delete |this|. If the
121 // return value is CHANNEL_DELETED, then the caller must return without making
122 // any further access to member variables or methods.
123 typedef WebSocketEventInterface::ChannelState ChannelState;
125 // The object passes through a linear progression of states from
126 // FRESHLY_CONSTRUCTED to CLOSED, except that the SEND_CLOSED and RECV_CLOSED
127 // states may be skipped in case of error.
132 SEND_CLOSED, // A Close frame has been sent but not received.
133 RECV_CLOSED, // Used briefly between receiving a Close frame and sending
134 // the response. Once the response is sent, the state changes
136 CLOSE_WAIT, // The Closing Handshake has completed, but the remote server
137 // has not yet closed the connection.
138 CLOSED, // The Closing Handshake has completed and the connection
139 // has been closed; or the connection is failed.
142 // Implementation of WebSocketStream::ConnectDelegate for
143 // WebSocketChannel. WebSocketChannel does not inherit from
144 // WebSocketStream::ConnectDelegate directly to avoid cluttering the public
145 // interface with the implementation of those methods, and because the
146 // lifetime of a WebSocketChannel is longer than the lifetime of the
147 // connection process.
148 class ConnectDelegate;
150 // Starts the connection process, using the supplied creator callback.
151 void SendAddChannelRequestWithSuppliedCreator(
152 const GURL& socket_url,
153 const std::vector<std::string>& requested_protocols,
155 const WebSocketStreamCreator& creator);
157 // Success callback from WebSocketStream::CreateAndConnectStream(). Reports
158 // success to the event interface. May delete |this|.
159 void OnConnectSuccess(scoped_ptr<WebSocketStream> stream);
161 // Failure callback from WebSocketStream::CreateAndConnectStream(). Reports
162 // failure to the event interface. May delete |this|.
163 void OnConnectFailure(const std::string& message);
165 // Posts a task that sends pending notifications relating WebSocket Opening
166 // Handshake to the renderer.
167 void ScheduleOpeningHandshakeNotification();
169 // Returns true if state_ is SEND_CLOSED, CLOSE_WAIT or CLOSED.
170 bool InClosingState() const;
172 // Calls WebSocketStream::WriteFrames() with the appropriate arguments
173 ChannelState WriteFrames() WARN_UNUSED_RESULT;
175 // Callback from WebSocketStream::WriteFrames. Sends pending data or adjusts
176 // the send quota of the renderer channel as appropriate. |result| is a net
177 // error code, usually OK. If |synchronous| is true, then OnWriteDone() is
178 // being called from within the WriteFrames() loop and does not need to call
179 // WriteFrames() itself.
180 ChannelState OnWriteDone(bool synchronous, int result) WARN_UNUSED_RESULT;
182 // Calls WebSocketStream::ReadFrames() with the appropriate arguments.
183 ChannelState ReadFrames() WARN_UNUSED_RESULT;
185 // Callback from WebSocketStream::ReadFrames. Handles any errors and processes
186 // the returned chunks appropriately to their type. |result| is a net error
187 // code. If |synchronous| is true, then OnReadDone() is being called from
188 // within the ReadFrames() loop and does not need to call ReadFrames() itself.
189 ChannelState OnReadDone(bool synchronous, int result) WARN_UNUSED_RESULT;
191 // Handles a single frame that the object has received enough of to process.
192 // May call |event_interface_| methods, send responses to the server, and
193 // change the value of |state_|.
195 // This method performs sanity checks on the frame that are needed regardless
196 // of the current state. Then, calls the HandleFrameByState() method below
197 // which performs the appropriate action(s) depending on the current state.
198 ChannelState HandleFrame(
199 scoped_ptr<WebSocketFrame> frame) WARN_UNUSED_RESULT;
201 // Handles a single frame depending on the current state. It's used by the
202 // HandleFrame() method.
203 ChannelState HandleFrameByState(
204 const WebSocketFrameHeader::OpCode opcode,
206 const scoped_refptr<IOBuffer>& data_buffer,
207 size_t size) WARN_UNUSED_RESULT;
209 // Low-level method to send a single frame. Used for both data and control
210 // frames. Either sends the frame immediately or buffers it to be scheduled
211 // when the current write finishes. |fin| and |op_code| are defined as for
212 // SendFrame() above, except that |op_code| may also be a control frame
214 ChannelState SendIOBuffer(bool fin,
215 WebSocketFrameHeader::OpCode op_code,
216 const scoped_refptr<IOBuffer>& buffer,
217 size_t size) WARN_UNUSED_RESULT;
219 // Performs the "Fail the WebSocket Connection" operation as defined in
220 // RFC6455. A NotifyFailure message is sent to the renderer with |message|.
221 // The renderer will log the message to the console but not expose it to
222 // Javascript. Javascript will see a Close code of AbnormalClosure (1006) with
223 // an empty reason string. If state_ is CONNECTED then a Close message is sent
224 // to the remote host containing the supplied |code| and |reason|. If the
225 // stream is open, closes it and sets state_ to CLOSED. FailChannel() always
226 // returns CHANNEL_DELETED. It is not valid to access any member variables or
227 // methods after calling FailChannel().
228 ChannelState FailChannel(const std::string& message,
230 const std::string& reason) WARN_UNUSED_RESULT;
232 // Sends a Close frame to Start the WebSocket Closing Handshake, or to respond
233 // to a Close frame from the server. As a special case, setting |code| to
234 // kWebSocketErrorNoStatusReceived will create a Close frame with no payload;
235 // this is symmetric with the behaviour of ParseClose.
236 ChannelState SendClose(uint16 code,
237 const std::string& reason) WARN_UNUSED_RESULT;
239 // Parses a Close frame payload. If no status code is supplied, then |code| is
240 // set to 1005 (No status code) with empty |reason|. If the reason text is not
241 // valid UTF-8, then |reason| is set to an empty string. If the payload size
242 // is 1, or the supplied code is not permitted to be sent over the network,
243 // then false is returned and |message| is set to an appropriate console
245 bool ParseClose(const scoped_refptr<IOBuffer>& buffer,
249 std::string* message);
251 // Drop this channel.
252 // If there are pending opening handshake notifications, notify them
254 ChannelState DoDropChannel(bool was_clean,
256 const std::string& reason);
258 // Called if the closing handshake times out. Closes the connection and
259 // informs the |event_interface_| if appropriate.
262 // The URL of the remote server.
265 // The object receiving events.
266 const scoped_ptr<WebSocketEventInterface> event_interface_;
268 // The URLRequestContext to pass to the WebSocketStream creator.
269 URLRequestContext* const url_request_context_;
271 // The WebSocketStream on which to send and receive data.
272 scoped_ptr<WebSocketStream> stream_;
274 // A data structure containing a vector of frames to be sent and the total
275 // number of bytes contained in the vector.
277 // Data that is currently pending write, or NULL if no write is pending.
278 scoped_ptr<SendBuffer> data_being_sent_;
279 // Data that is queued up to write after the current write completes.
280 // Only non-NULL when such data actually exists.
281 scoped_ptr<SendBuffer> data_to_send_next_;
283 // Destination for the current call to WebSocketStream::ReadFrames
284 ScopedVector<WebSocketFrame> read_frames_;
286 // Handle to an in-progress WebSocketStream creation request. Only non-NULL
287 // during the connection process.
288 scoped_ptr<WebSocketStreamRequest> stream_request_;
290 // If the renderer's send quota reaches this level, it is sent a quota
291 // refresh. "quota units" are currently bytes. TODO(ricea): Update the
292 // definition of quota units when necessary.
293 int send_quota_low_water_mark_;
294 // The level the quota is refreshed to when it reaches the low_water_mark
296 int send_quota_high_water_mark_;
297 // The current amount of quota that the renderer has available for sending
298 // on this logical channel (quota units).
299 int current_send_quota_;
301 // Timer for the closing handshake.
302 base::OneShotTimer<WebSocketChannel> timer_;
304 // Timeout for the closing handshake.
305 base::TimeDelta timeout_;
307 // Storage for the status code and reason from the time the Close frame
308 // arrives until the connection is closed and they are passed to
310 uint16 received_close_code_;
311 std::string received_close_reason_;
313 // The current state of the channel. Mainly used for sanity checking, but also
314 // used to track the close state.
317 // |notification_sender_| is owned by this object.
318 scoped_ptr<HandshakeNotificationSender> notification_sender_;
320 // UTF-8 validator for outgoing Text messages.
321 base::StreamingUtf8Validator outgoing_utf8_validator_;
322 bool sending_text_message_;
324 // UTF-8 validator for incoming Text messages.
325 base::StreamingUtf8Validator incoming_utf8_validator_;
326 bool receiving_text_message_;
328 DISALLOW_COPY_AND_ASSIGN(WebSocketChannel);
333 #endif // NET_WEBSOCKETS_WEBSOCKET_CHANNEL_H_