blob: 22d7911b58acf529dce328cb25c1b3c37d8d216d [file] [log] [blame]
[email protected]999bcaa2013-07-17 13:42:541// 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
5#ifndef NET_WEBSOCKETS_WEBSOCKET_CHANNEL_H_
6#define NET_WEBSOCKETS_WEBSOCKET_CHANNEL_H_
7
8#include <string>
9#include <vector>
10
11#include "base/basictypes.h"
12#include "base/callback.h"
[email protected]f485985e2013-10-24 13:47:4413#include "base/compiler_specific.h" // for WARN_UNUSED_RESULT
[email protected]999bcaa2013-07-17 13:42:5414#include "base/memory/scoped_ptr.h"
15#include "base/memory/scoped_vector.h"
[email protected]3a266762013-10-23 08:15:1016#include "base/time/time.h"
17#include "base/timer/timer.h"
[email protected]999bcaa2013-07-17 13:42:5418#include "net/base/net_export.h"
[email protected]f485985e2013-10-24 13:47:4419#include "net/websockets/websocket_event_interface.h"
[email protected]999bcaa2013-07-17 13:42:5420#include "net/websockets/websocket_frame.h"
21#include "net/websockets/websocket_stream.h"
[email protected]15fbdb42013-07-20 00:09:3822#include "url/gurl.h"
[email protected]999bcaa2013-07-17 13:42:5423
24namespace net {
25
[email protected]2f5d9f62013-09-26 12:14:2826class BoundNetLog;
27class IOBuffer;
[email protected]999bcaa2013-07-17 13:42:5428class URLRequestContext;
[email protected]cd48ed12014-01-22 14:34:2229struct WebSocketHandshakeRequestInfo;
30struct WebSocketHandshakeResponseInfo;
[email protected]999bcaa2013-07-17 13:42:5431
32// Transport-independent implementation of WebSockets. Implements protocol
33// semantics that do not depend on the underlying transport. Provides the
34// interface to the content layer. Some WebSocket concepts are used here without
35// definition; please see the RFC at http://tools.ietf.org/html/rfc6455 for
36// clarification.
37class NET_EXPORT WebSocketChannel {
38 public:
[email protected]969dde72013-11-13 15:59:1439 // The type of a WebSocketStream creator callback. Must match the signature of
[email protected]999bcaa2013-07-17 13:42:5440 // WebSocketStream::CreateAndConnectStream().
41 typedef base::Callback<scoped_ptr<WebSocketStreamRequest>(
42 const GURL&,
43 const std::vector<std::string>&,
44 const GURL&,
45 URLRequestContext*,
46 const BoundNetLog&,
[email protected]969dde72013-11-13 15:59:1447 scoped_ptr<WebSocketStream::ConnectDelegate>)> WebSocketStreamCreator;
[email protected]999bcaa2013-07-17 13:42:5448
[email protected]dab33eb2013-10-08 02:27:5149 // Creates a new WebSocketChannel in an idle state.
[email protected]999bcaa2013-07-17 13:42:5450 // SendAddChannelRequest() must be called immediately afterwards to start the
51 // connection process.
[email protected]dab33eb2013-10-08 02:27:5152 WebSocketChannel(scoped_ptr<WebSocketEventInterface> event_interface,
53 URLRequestContext* url_request_context);
[email protected]999bcaa2013-07-17 13:42:5454 virtual ~WebSocketChannel();
55
56 // Starts the connection process.
57 void SendAddChannelRequest(
[email protected]dab33eb2013-10-08 02:27:5158 const GURL& socket_url,
[email protected]999bcaa2013-07-17 13:42:5459 const std::vector<std::string>& requested_protocols,
[email protected]dab33eb2013-10-08 02:27:5160 const GURL& origin);
[email protected]999bcaa2013-07-17 13:42:5461
62 // Sends a data frame to the remote side. The frame should usually be no
63 // larger than 32KB to prevent the time required to copy the buffers from from
64 // unduly delaying other tasks that need to run on the IO thread. This method
65 // has a hard limit of 2GB. It is the responsibility of the caller to ensure
66 // that they have sufficient send quota to send this data, otherwise the
67 // connection will be closed without sending. |fin| indicates the last frame
68 // in a message, equivalent to "FIN" as specified in section 5.2 of
69 // RFC6455. |data| is the "Payload Data". If |op_code| is kOpCodeText, or it
70 // is kOpCodeContinuation and the type the message is Text, then |data| must
71 // be a chunk of a valid UTF-8 message, however there is no requirement for
72 // |data| to be split on character boundaries.
73 void SendFrame(bool fin,
74 WebSocketFrameHeader::OpCode op_code,
75 const std::vector<char>& data);
76
77 // Sends |quota| units of flow control to the remote side. If the underlying
78 // transport has a concept of |quota|, then it permits the remote server to
79 // send up to |quota| units of data.
80 void SendFlowControl(int64 quota);
81
[email protected]caab2cc2013-08-27 10:24:3782 // Starts the closing handshake for a client-initiated shutdown of the
[email protected]999bcaa2013-07-17 13:42:5483 // connection. There is no API to close the connection without a closing
84 // handshake, but destroying the WebSocketChannel object while connected will
85 // effectively do that. |code| must be in the range 1000-4999. |reason| should
86 // be a valid UTF-8 string or empty.
87 //
88 // This does *not* trigger the event OnClosingHandshake(). The caller should
89 // assume that the closing handshake has started and perform the equivalent
90 // processing to OnClosingHandshake() if necessary.
91 void StartClosingHandshake(uint16 code, const std::string& reason);
92
[email protected]969dde72013-11-13 15:59:1493 // Starts the connection process, using a specified creator callback rather
[email protected]999bcaa2013-07-17 13:42:5494 // than the default. This is exposed for testing.
95 void SendAddChannelRequestForTesting(
[email protected]dab33eb2013-10-08 02:27:5196 const GURL& socket_url,
[email protected]999bcaa2013-07-17 13:42:5497 const std::vector<std::string>& requested_protocols,
98 const GURL& origin,
[email protected]969dde72013-11-13 15:59:1499 const WebSocketStreamCreator& creator);
[email protected]999bcaa2013-07-17 13:42:54100
[email protected]3a266762013-10-23 08:15:10101 // The default timout for the closing handshake is a sensible value (see
102 // kClosingHandshakeTimeoutSeconds in websocket_channel.cc). However, we can
103 // set it to a very small value for testing purposes.
104 void SetClosingHandshakeTimeoutForTesting(base::TimeDelta delay);
105
[email protected]cd48ed12014-01-22 14:34:22106 // Called when the stream starts the WebSocket Opening Handshake.
107 // This method is public for testing.
108 void OnStartOpeningHandshake(
109 scoped_ptr<WebSocketHandshakeRequestInfo> request);
110
111 // Called when the stream ends the WebSocket Opening Handshake.
112 // This method is public for testing.
113 void OnFinishOpeningHandshake(
114 scoped_ptr<WebSocketHandshakeResponseInfo> response);
115
[email protected]999bcaa2013-07-17 13:42:54116 private:
[email protected]cd48ed12014-01-22 14:34:22117 class HandshakeNotificationSender;
118
[email protected]f485985e2013-10-24 13:47:44119 // Methods which return a value of type ChannelState may delete |this|. If the
120 // return value is CHANNEL_DELETED, then the caller must return without making
121 // any further access to member variables or methods.
122 typedef WebSocketEventInterface::ChannelState ChannelState;
123
[email protected]caab2cc2013-08-27 10:24:37124 // The object passes through a linear progression of states from
125 // FRESHLY_CONSTRUCTED to CLOSED, except that the SEND_CLOSED and RECV_CLOSED
126 // states may be skipped in case of error.
[email protected]999bcaa2013-07-17 13:42:54127 enum State {
128 FRESHLY_CONSTRUCTED,
129 CONNECTING,
130 CONNECTED,
[email protected]caab2cc2013-08-27 10:24:37131 SEND_CLOSED, // A Close frame has been sent but not received.
[email protected]999bcaa2013-07-17 13:42:54132 RECV_CLOSED, // Used briefly between receiving a Close frame and sending
[email protected]caab2cc2013-08-27 10:24:37133 // the response. Once the response is sent, the state changes
[email protected]999bcaa2013-07-17 13:42:54134 // to CLOSED.
[email protected]c0d29c22013-07-26 20:40:41135 CLOSE_WAIT, // The Closing Handshake has completed, but the remote server
136 // has not yet closed the connection.
137 CLOSED, // The Closing Handshake has completed and the connection
138 // has been closed; or the connection is failed.
[email protected]999bcaa2013-07-17 13:42:54139 };
140
[email protected]caab2cc2013-08-27 10:24:37141 // When failing a channel, sometimes it is inappropriate to expose the real
142 // reason for failing to the remote server. This enum is used by FailChannel()
143 // to select between sending the real status or a "Going Away" status.
[email protected]999bcaa2013-07-17 13:42:54144 enum ExposeError {
145 SEND_REAL_ERROR,
146 SEND_GOING_AWAY,
147 };
148
[email protected]caab2cc2013-08-27 10:24:37149 // Implementation of WebSocketStream::ConnectDelegate for
150 // WebSocketChannel. WebSocketChannel does not inherit from
151 // WebSocketStream::ConnectDelegate directly to avoid cluttering the public
152 // interface with the implementation of those methods, and because the
[email protected]999bcaa2013-07-17 13:42:54153 // lifetime of a WebSocketChannel is longer than the lifetime of the
154 // connection process.
155 class ConnectDelegate;
156
[email protected]969dde72013-11-13 15:59:14157 // Starts the connection process, using the supplied creator callback.
158 void SendAddChannelRequestWithSuppliedCreator(
[email protected]dab33eb2013-10-08 02:27:51159 const GURL& socket_url,
[email protected]999bcaa2013-07-17 13:42:54160 const std::vector<std::string>& requested_protocols,
161 const GURL& origin,
[email protected]969dde72013-11-13 15:59:14162 const WebSocketStreamCreator& creator);
[email protected]999bcaa2013-07-17 13:42:54163
164 // Success callback from WebSocketStream::CreateAndConnectStream(). Reports
[email protected]f485985e2013-10-24 13:47:44165 // success to the event interface. May delete |this|.
[email protected]999bcaa2013-07-17 13:42:54166 void OnConnectSuccess(scoped_ptr<WebSocketStream> stream);
167
168 // Failure callback from WebSocketStream::CreateAndConnectStream(). Reports
[email protected]f485985e2013-10-24 13:47:44169 // failure to the event interface. May delete |this|.
[email protected]96868202014-01-09 10:38:04170 void OnConnectFailure(const std::string& message);
[email protected]999bcaa2013-07-17 13:42:54171
[email protected]cd48ed12014-01-22 14:34:22172 // Posts a task that sends pending notifications relating WebSocket Opening
173 // Handshake to the renderer.
174 void ScheduleOpeningHandshakeNotification();
175
[email protected]c0d29c22013-07-26 20:40:41176 // Returns true if state_ is SEND_CLOSED, CLOSE_WAIT or CLOSED.
177 bool InClosingState() const;
178
[email protected]999bcaa2013-07-17 13:42:54179 // Calls WebSocketStream::WriteFrames() with the appropriate arguments
[email protected]f485985e2013-10-24 13:47:44180 ChannelState WriteFrames() WARN_UNUSED_RESULT;
[email protected]999bcaa2013-07-17 13:42:54181
182 // Callback from WebSocketStream::WriteFrames. Sends pending data or adjusts
183 // the send quota of the renderer channel as appropriate. |result| is a net
184 // error code, usually OK. If |synchronous| is true, then OnWriteDone() is
185 // being called from within the WriteFrames() loop and does not need to call
186 // WriteFrames() itself.
[email protected]f485985e2013-10-24 13:47:44187 ChannelState OnWriteDone(bool synchronous, int result) WARN_UNUSED_RESULT;
[email protected]999bcaa2013-07-17 13:42:54188
189 // Calls WebSocketStream::ReadFrames() with the appropriate arguments.
[email protected]f485985e2013-10-24 13:47:44190 ChannelState ReadFrames() WARN_UNUSED_RESULT;
[email protected]999bcaa2013-07-17 13:42:54191
192 // Callback from WebSocketStream::ReadFrames. Handles any errors and processes
193 // the returned chunks appropriately to their type. |result| is a net error
194 // code. If |synchronous| is true, then OnReadDone() is being called from
195 // within the ReadFrames() loop and does not need to call ReadFrames() itself.
[email protected]f485985e2013-10-24 13:47:44196 ChannelState OnReadDone(bool synchronous, int result) WARN_UNUSED_RESULT;
[email protected]999bcaa2013-07-17 13:42:54197
[email protected]2f5d9f62013-09-26 12:14:28198 // Processes a single frame that has been read from the stream.
[email protected]f485985e2013-10-24 13:47:44199 ChannelState ProcessFrame(
200 scoped_ptr<WebSocketFrame> frame) WARN_UNUSED_RESULT;
[email protected]caab2cc2013-08-27 10:24:37201
202 // Handles a frame that the object has received enough of to process. May call
[email protected]2f5d9f62013-09-26 12:14:28203 // |event_interface_| methods, send responses to the server, and change the
204 // value of |state_|.
[email protected]f485985e2013-10-24 13:47:44205 ChannelState HandleFrame(const WebSocketFrameHeader::OpCode opcode,
206 bool final,
207 const scoped_refptr<IOBuffer>& data_buffer,
208 size_t size) WARN_UNUSED_RESULT;
[email protected]999bcaa2013-07-17 13:42:54209
210 // Low-level method to send a single frame. Used for both data and control
211 // frames. Either sends the frame immediately or buffers it to be scheduled
212 // when the current write finishes. |fin| and |op_code| are defined as for
213 // SendFrame() above, except that |op_code| may also be a control frame
214 // opcode.
[email protected]f485985e2013-10-24 13:47:44215 ChannelState SendIOBuffer(bool fin,
216 WebSocketFrameHeader::OpCode op_code,
217 const scoped_refptr<IOBuffer>& buffer,
218 size_t size) WARN_UNUSED_RESULT;
[email protected]999bcaa2013-07-17 13:42:54219
[email protected]caab2cc2013-08-27 10:24:37220 // Performs the "Fail the WebSocket Connection" operation as defined in
[email protected]999bcaa2013-07-17 13:42:54221 // RFC6455. The supplied code and reason are sent back to the renderer in an
222 // OnDropChannel message. If state_ is CONNECTED then a Close message is sent
223 // to the remote host. If |expose| is SEND_REAL_ERROR then the remote host is
[email protected]caab2cc2013-08-27 10:24:37224 // given the same status code passed to the renderer; otherwise it is sent a
[email protected]2f5d9f62013-09-26 12:14:28225 // fixed "Going Away" code. Closes the stream_ and sets state_ to CLOSED.
[email protected]f485985e2013-10-24 13:47:44226 // FailChannel() always returns CHANNEL_DELETED. It is not valid to access any
227 // member variables or methods after calling FailChannel().
228 ChannelState FailChannel(ExposeError expose,
229 uint16 code,
230 const std::string& reason) WARN_UNUSED_RESULT;
[email protected]999bcaa2013-07-17 13:42:54231
232 // Sends a Close frame to Start the WebSocket Closing Handshake, or to respond
[email protected]c0d29c22013-07-26 20:40:41233 // 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.
[email protected]f485985e2013-10-24 13:47:44236 ChannelState SendClose(uint16 code,
237 const std::string& reason) WARN_UNUSED_RESULT;
[email protected]999bcaa2013-07-17 13:42:54238
239 // Parses a Close frame. If no status code is supplied, then |code| is set to
240 // 1005 (No status code) with empty |reason|. If the supplied code is
241 // outside the valid range, then 1002 (Protocol error) is set instead. If the
242 // reason text is not valid UTF-8, then |reason| is set to an empty string
243 // instead.
[email protected]2f5d9f62013-09-26 12:14:28244 void ParseClose(const scoped_refptr<IOBuffer>& buffer,
245 size_t size,
[email protected]999bcaa2013-07-17 13:42:54246 uint16* code,
247 std::string* reason);
248
[email protected]cd48ed12014-01-22 14:34:22249 // Drop this channel.
250 // If there are pending opening handshake notifications, notify them
251 // before dropping.
252 ChannelState DoDropChannel(uint16 code, const std::string& reason);
253
[email protected]3a266762013-10-23 08:15:10254 // Called if the closing handshake times out. Closes the connection and
255 // informs the |event_interface_| if appropriate.
256 void CloseTimeout();
257
[email protected]caab2cc2013-08-27 10:24:37258 // The URL of the remote server.
[email protected]dab33eb2013-10-08 02:27:51259 GURL socket_url_;
[email protected]999bcaa2013-07-17 13:42:54260
261 // The object receiving events.
262 const scoped_ptr<WebSocketEventInterface> event_interface_;
263
[email protected]969dde72013-11-13 15:59:14264 // The URLRequestContext to pass to the WebSocketStream creator.
[email protected]dab33eb2013-10-08 02:27:51265 URLRequestContext* const url_request_context_;
266
[email protected]caab2cc2013-08-27 10:24:37267 // The WebSocketStream on which to send and receive data.
[email protected]999bcaa2013-07-17 13:42:54268 scoped_ptr<WebSocketStream> stream_;
269
270 // A data structure containing a vector of frames to be sent and the total
271 // number of bytes contained in the vector.
272 class SendBuffer;
273 // Data that is currently pending write, or NULL if no write is pending.
274 scoped_ptr<SendBuffer> data_being_sent_;
275 // Data that is queued up to write after the current write completes.
276 // Only non-NULL when such data actually exists.
277 scoped_ptr<SendBuffer> data_to_send_next_;
278
279 // Destination for the current call to WebSocketStream::ReadFrames
[email protected]2f5d9f62013-09-26 12:14:28280 ScopedVector<WebSocketFrame> read_frames_;
281
[email protected]999bcaa2013-07-17 13:42:54282 // Handle to an in-progress WebSocketStream creation request. Only non-NULL
283 // during the connection process.
284 scoped_ptr<WebSocketStreamRequest> stream_request_;
[email protected]2f5d9f62013-09-26 12:14:28285
[email protected]caab2cc2013-08-27 10:24:37286 // If the renderer's send quota reaches this level, it is sent a quota
287 // refresh. "quota units" are currently bytes. TODO(ricea): Update the
288 // definition of quota units when necessary.
[email protected]999bcaa2013-07-17 13:42:54289 int send_quota_low_water_mark_;
[email protected]caab2cc2013-08-27 10:24:37290 // The level the quota is refreshed to when it reaches the low_water_mark
291 // (quota units).
[email protected]999bcaa2013-07-17 13:42:54292 int send_quota_high_water_mark_;
293 // The current amount of quota that the renderer has available for sending
294 // on this logical channel (quota units).
295 int current_send_quota_;
296
[email protected]3a266762013-10-23 08:15:10297 // Timer for the closing handshake.
298 base::OneShotTimer<WebSocketChannel> timer_;
299
300 // Timeout for the closing handshake.
301 base::TimeDelta timeout_;
302
[email protected]caab2cc2013-08-27 10:24:37303 // Storage for the status code and reason from the time the Close frame
304 // arrives until the connection is closed and they are passed to
305 // OnDropChannel().
[email protected]999bcaa2013-07-17 13:42:54306 uint16 closing_code_;
307 std::string closing_reason_;
308
309 // The current state of the channel. Mainly used for sanity checking, but also
310 // used to track the close state.
311 State state_;
312
[email protected]cd48ed12014-01-22 14:34:22313 // |notification_sender_| is owned by this object.
314 scoped_ptr<HandshakeNotificationSender> notification_sender_;
315
[email protected]999bcaa2013-07-17 13:42:54316 DISALLOW_COPY_AND_ASSIGN(WebSocketChannel);
317};
318
319} // namespace net
320
321#endif // NET_WEBSOCKETS_WEBSOCKET_CHANNEL_H_